Socat Network Operations Manager
Python Variant
Production-grade socat session manager for network operations.
Listeners, bidirectional forwards, TLS tunnels, and transparent redirectors
with unique Session IDs, protocol-aware lifecycle management, and zero external dependencies.
Quick Start ·
Modes ·
Usage Guide ·
Changelog ·
Security ·
Testing ·
Contributing
Full Documentation Wiki — detailed guides, architecture with Mermaid diagrams, operational scenarios, and exhaustive developer reference.
Table of Contents
Overview
socat-manager provides a unified command-line interface and interactive menu for managing socat-based network operations. It wraps socat's complex syntax into seven structured operational modes, adding session tracking, process group isolation, protocol-aware lifecycle management, traffic capture, and automatic restart capabilities.
This is a complete Python 3.12+ reimplementation of socat_manager.sh v2.3.0 (4,470 lines of bash, 91 functions) with full functional parity. The Python variant uses only the standard library at runtime — zero external PyPI dependencies.
Every launched socat process receives a unique 8-character hex Session ID, is placed in its own process group via os.setsid(), and is tracked in a persistent .session metadata file. This enables reliable status queries and clean shutdowns across terminal sessions and script invocations — you can launch a redirector in one terminal, check its status from another, and stop it from a third.
(back to top)
Key Highlights
|
Feature |
Description |
| 🔀 |
Seven Operational Modes |
listen, batch, forward, tunnel, redirect — plus status and stop for lifecycle management |
| 🔌 |
Protocol Flexibility |
TCP4, TCP6, UDP4, UDP6 individually (--proto) or both TCP+UDP simultaneously (--dual-stack) |
| 📡 |
Traffic Capture |
Verbose hex dump logging (--capture) on all modes — listen, batch, forward, tunnel, redirect |
| 🔖 |
Session Tracking |
Unique 8-char hex Session IDs with persistent .session metadata files |
| 🔒 |
Process Isolation |
Each socat process in its own process group via os.setsid() with direct PID access |
| 🛡️ |
Protocol-Aware Stop |
Stopping TCP does not affect UDP on the same port, and vice versa |
| 🖥️ |
Interactive Menu |
Run with no arguments for a guided, menu-driven interface with validation and cancel support |
| ⚡ |
Non-Blocking Launch |
Script returns to prompt immediately — no terminal blocking |
| 🔄 |
Watchdog Auto-Restart |
Monitor-first design with configurable exponential backoff and max restarts |
| 📦 |
Batch Operations |
Launch listeners on port lists, ranges, or config files in a single command |
| 📝 |
Structured Logging |
Dual-output (file + console) with correlation IDs and per-session audit trails |
| 🐍 |
Zero Dependencies |
Python standard library only — no pip packages required at runtime |
(back to top)
Features
Core Capabilities
- Seven operational modes: listen, batch, forward, tunnel, redirect, status, stop
- Protocol flexibility: TCP4, TCP6, UDP4, UDP6 individually via
--proto, or both TCP and UDP simultaneously via --dual-stack
- Traffic capture: Verbose hex dump logging (
--capture) available on all operational modes (listen, batch, forward, tunnel, redirect)
- Session management: Unique 8-char hex Session IDs with
.session metadata files for persistent tracking
- Process group isolation: Each socat process launched via
os.setsid() in subprocess.Popen for reliable cross-invocation tracking
- Protocol-aware stop: Stopping a TCP session does not affect a UDP session on the same port, and vice versa
- Non-blocking launch: Script returns to prompt immediately after launching sessions — no terminal blocking
- Watchdog auto-restart: Monitor-first design (no duplicate launch), configurable exponential backoff (1s, 2s, 4s... 60s cap), configurable max restarts and initial backoff via
--max-restarts and --backoff
- Interactive menu: No-args launches a full-featured menu with guided input, validation, dependency checking, socat-opts examples, configurable watchdog prompts, paired forward after listener, and cancel support at every prompt
- Batch operations: Launch listeners on port lists, ranges, or config files in a single command
- Standalone runner:
python3 socat-manager.py — no pip install, no venv, no system modification
- Cross-variant interoperability: Session files use the same KEY=VALUE format as the bash variant — both can read each other's session files
Input Validation and Security
- 9 whitelist-based validators at the trust boundary: ports, hostnames, protocols, file paths, socat options, session names, session IDs, port ranges, port lists
- Command injection prevention:
subprocess.Popen with argument lists only — shell=True never appears in the 6,779-line codebase
- No
eval(), exec(), compile(), or __import__() anywhere
- Shell metacharacters (
; | & $ ` ( ) { } [ ] < > ! #) blocked in hostnames and file paths
- Session directory permissions restricted to 0o700
- Session files restricted to 0o600
- Private key files restricted to 0o600
- Capture log files restricted to 0o600
- Only socat processes targeted during port-based fallback kill (process name verification via
/proc/{pid}/comm)
See SECURITY.md for the full STRIDE threat model, 7-layer defense-in-depth analysis, and secure deployment guidelines.
Logging and Audit
- Structured master execution log with correlation IDs
- Per-session log files for independent audit trails
- Traffic capture logs (socat
-v hex dumps) per session and protocol
- Console output with color-coded severity levels (DEBUG, INFO, WARNING, ERROR, CRITICAL)
- Terminal-aware: ANSI colors gated on TTY detection (
sys.stderr.isatty())
(back to top)
Architecture
Process Launch Model
socat-manager (launcher)
│
├── subprocess.Popen(cmd, preexec_fn=os.setsid, close_fds=True)
│ │
│ └── socat (PID == PGID, session leader)
│ ├── socat fork (child for connection 1)
│ ├── socat fork (child for connection 2)
│ └── ...
│
├── Popen.pid gives real socat PID directly
├── Registers session: SID, PID, PGID, protocol, port, command
├── Returns (sid, pid) tuple to caller
└── Returns to prompt (non-blocking)
Key design decisions:
os.setsid as preexec_fn creates a new process group. Socat becomes the group leader (PID == PGID), so os.killpg(pgid, signal) terminates socat and all its fork children in one operation.
Direct PID access via Popen.pid: Unlike the bash variant which requires a PID-file handoff pattern (setsid wrapper PID problem), Python's Popen.pid gives the real socat PID directly. No staging files, no polling, no race conditions.
launch_socat_session() returns (sid, pid) tuple: The PID is passed to the watchdog for monitoring. This eliminates the critical bug where the watchdog would launch a duplicate socat on an already-bound port.
close_fds=True prevents file descriptor leakage from the management script to the socat process.
subprocess.Popen with argument lists only: The cmd parameter is always list[str], never a shell string. shell=True is never used.
Session File Format
SESSION_FILE_VERSION=v2.3
SESSION_ID=a1b2c3d4
SESSION_NAME=redir-tcp4-8443-example.com-443
PID=12345
PGID=12345
MODE=redirect
PROTOCOL=tcp4
LOCAL_PORT=8443
REMOTE_HOST=example.com
REMOTE_PORT=443
SOCAT_CMD=socat TCP4-LISTEN:8443,reuseaddr,fork,backlog=128,keepalive TCP4:example.com:443
STARTED=2026-03-30T14:30:00+00:00
CORRELATION=a1b2c3d4
LAUNCHER_PID=9999
Stop Sequence
1. Read session metadata (PID, PGID, PROTOCOL, PORT)
2. Signal watchdog via .stop file (tells watchdog: do not restart)
3. SIGTERM entire process group: os.killpg(pgid, SIGTERM)
4. SIGTERM specific PID + children: os.kill(pid, SIGTERM); pkill -TERM -P pid
5. Wait grace period (5 seconds, checking every 0.5s)
6. SIGKILL if still alive: os.killpg + os.kill + pkill -KILL -P
7. Fallback: protocol-scoped port-based kill via ss (socat processes only)
8. Verify port freed (protocol-scoped, avoids cross-protocol interference)
9. Remove session file + .stop + .launching files after confirmed dead
(back to top)
Prerequisites
Required
| Dependency |
Purpose |
Install |
| Python 3.12+ |
Framework runtime |
Pre-installed on Ubuntu 24.04+; sudo apt-get install python3 |
| socat |
Core network operations |
sudo apt-get install -y socat |
Optional
| Dependency |
Purpose |
Install |
| openssl |
TLS certificate generation (tunnel mode) |
sudo apt-get install -y openssl |
| ss (iproute2) |
Port status checking, session verification |
sudo apt-get install -y iproute2 |
| pstree (psmisc) |
Process tree display in status detail view |
sudo apt-get install -y psmisc |
| flock (util-linux) |
Advisory file locking for session concurrency |
Pre-installed on most Linux |
System Requirements
- Linux kernel (any modern distribution)
- Python 3.12+ (uses
match/case, slots=True, from __future__ import annotations)
- Root/sudo for privileged ports (<1024)
- Zero external PyPI packages at runtime (standard library only)
Compatibility
Designed for the same 8 environments verified by the bash variant's CI pipeline:
| Distribution |
Version |
Python |
Status |
Notes |
| Ubuntu |
22.04 LTS |
3.12+ |
✅ Expected |
May need python3.12 package |
| Ubuntu |
24.04 LTS |
3.12 |
✅ Expected |
Python 3.12 pre-installed |
| Debian |
12 (Bookworm) |
3.12+ |
✅ Expected |
May need python3.12 package |
| Kali Linux |
Rolling |
3.12+ |
✅ Expected |
socat typically pre-installed |