# WSSSH: Warp-Powered Stefy's Spatial Secure Hyperdrive - Technical Documentation

## Table of Contents

1. [Overview](#overview)
2. [Architecture](#architecture)
3. [Protocol Specification](#protocol-specification)
4. [API Reference](#api-reference)
5. [Configuration](#configuration)
6. [Logging Configuration](#logging-configuration)
7. [Security](#security)
8. [Troubleshooting](#troubleshooting)
9. [Development](#development)
10. [Recent Updates](#recent-updates)

## Overview

WSSSH is a universal tunneling system that provides secure access to remote machines through various transport protocols. The system consists of multiple components implemented in C, offering high performance, minimal dependencies, and enterprise-grade reliability.

### Key Components

#### Server Component
- **wssshd2**: High-performance C daemon with embedded SQLite database and web interface
- **WebSocket/Transport Support**: Multiple transport protocol implementations
- **Client Management**: Registration and authentication system with persistent storage
- **Tunnel Routing**: Intelligent request routing to registered clients
- **Embedded Web UI**: Self-contained web interface with user management

#### C Implementation (Primary)
- **wssshc**: Lightweight C client for registration (OpenSSL-based)
- **wsssh**: Native SSH wrapper with direct system integration
- **wsscp**: Native SCP wrapper optimized for file transfers
- **wsssht**: Tunnel setup tool for manual connections

### Core Features

- **Universal Transport Support**: WebSocket and extensible transport architecture
- **Intelligent Hostname Parsing**: Automatic client ID and server endpoint detection
- **SSL/TLS Encryption**: Secure communications with OpenSSL
- **Multi-client Architecture**: Route connections to different registered clients
- **Simplified CLI**: Drop-in replacements for SSH/SCP commands
- **Debian Packaging**: Professional system integration
- **Service Management**: Complete init scripts and watchdog monitoring
- **Advanced Logging**: Automatic log rotation and monitoring
- **Multiple Operating Modes**: Interactive, silent, bridge, script, and daemon modes
- **Enterprise Reliability**: Production-grade process supervision
- **Server Stability**: Robust error handling with comprehensive crash prevention and graceful client disconnection management

## Operating Modes

WSSSH supports multiple operating modes to accommodate different use cases:

### Interactive Mode (Default)
Standard interactive SSH/SCP sessions with full user interface and progress indicators.

### Silent Mode
```bash
wsssht --silent --clientid myclient --wssshd-host example.com
```
Suppresses all informational output, perfect for automation and background operations.

### Bridge Mode
```bash
wsssht --bridge --clientid myclient --wssshd-host example.com
```
Provides JSON-based interface for programmatic integration:
- Receives JSON commands from stdin
- Sends JSON status updates and responses to stdout
- Perfect for integration with other tools and automation frameworks
- Structured error reporting and connection status updates

### Script Mode
```bash
wsssht --script --clientid myclient --wssshd-host example.com
```
Designed for scripting environments with:
- JSON protocol for all communications
- Periodic status updates (every 30 seconds)
- Script command processing (`status`, `quit`, `exit`)
- Timestamped events for monitoring and logging

### Daemon Mode
```bash
wsssht --daemon --clientid myclient --wssshd-host example.com
```
Implements lazy tunnel initialization:
- Waits for first connection attempt before establishing tunnel
- Reduces resource usage for intermittent connections
- Maintains full functionality after tunnel establishment

## Architecture

### System Architecture

```
┌─────────────────┐    Transport Layer    ┌─────────────────┐
│   SSH/SCP       │◄────────────────────►│     wssshd      │
│   Client        │                       │   (Daemon)      │
└─────────────────┘                       └─────────────────┘
                                                 │
                                                 │ Transport Layer
                                                 ▼
                                         ┌─────────────────┐
                                         │    wssshc       │
                                         │   (Client)      │
                                         │                 │
                                         │ ┌─────────────┐ │
                                         │ │ SSH Server  │ │
                                         │ │ (sshd)      │ │
                                         │ └─────────────┘ │
                                         └─────────────────┘
```

### Data Flow

1. **Registration Phase**:
   - wssshc connects to wssshd via selected transport
   - Registers with unique client ID and authentication
   - Maintains persistent connection

2. **Connection Phase**:
   - User runs `wsssh user@client.domain` (simplified CLI)
   - wsssh parses hostname to extract client ID and server endpoint
   - wsssh connects to wssshd and requests tunnel to client
   - wssshd forwards request to appropriate wssshc
   - wssshc establishes local tunnel to target service

3. **Data Transfer Phase**:
   - Traffic flows: SSH Client ↔ wsssh ↔ wssshd ↔ wssshc ↔ Target Service
   - All transport connections are encrypted with SSL/TLS

## Protocol Specification

### Transport Layer

WSSSH supports multiple transport protocols:

#### WebSocket Transport
- **Protocol**: WebSocket (RFC 6455)
- **Encryption**: SSL/TLS
- **Features**: Bidirectional communication, frame-based messaging
- **Default Transport**: Primary transport implementation

#### Extensible Architecture
- **Transport Plugins**: Modular transport implementation
- **Configuration**: Transport selection via command-line options
- **Negotiation**: Automatic transport negotiation between client and server

### Message Format

All control messages use JSON format:

```json
{
  "type": "message_type",
  "request_id": "uuid_string",
  "client_id": "client_identifier",
  "data": "base64_encoded_data"
}
```

### Message Types

#### Client Registration Messages

**Register Client** (wssshc → wssshd):
```json
{
  "type": "register",
  "id": "client_unique_id",
  "password": "authentication_password"
}
```

**Registration Acknowledgment** (wssshd → wssshc):
```json
{
  "type": "registered",
  "id": "client_unique_id"
}
```

#### Tunnel Management Messages

**Request Tunnel** (wsssh → wssshd):
```json
{
  "type": "tunnel_request",
  "client_id": "target_client_id",
  "request_id": "unique_request_uuid",
  "service": "ssh"
}
```

**Tunnel Acknowledgment** (wssshd → wsssh):
```json
{
  "type": "tunnel_ack",
  "request_id": "unique_request_uuid",
  "local_port": 49234
}
```

**Tunnel Data** (bidirectional):
```json
{
  "type": "tunnel_data",
  "request_id": "unique_request_uuid",
  "data": "base64_encoded_binary_data"
}
```

**Close Tunnel** (any → any):
```json
{
  "type": "tunnel_close",
  "request_id": "unique_request_uuid"
}
```

### Hostname Parsing Algorithm

```
Input: hostname (e.g., "myclient.example.com:9898")

1. Split by ':' to separate port
   host_part = "myclient.example.com"
   port_part = "9898" (optional)

2. Split host_part by '.' to get parts
   parts = ["myclient", "example", "com"]

3. If parts.length >= 2:
   client_id = parts[0]  // "myclient"
   wssshd_host = parts[1:].join('.')  // "example.com"
   Else:
   client_id = host_part  // fallback
   wssshd_host = "localhost"  // fallback

4. Determine wssshd_port:
   if port_part exists: use port_part
   elif config port exists: use config port
   else: use 9898 (default)
```

## API Reference

### wssshd (Universal Tunneling Daemon)

#### Command Line Options

```bash
wssshd --host HOST --port PORT --domain DOMAIN --password PASS [--web-host HOST --web-port PORT] [--web-https] [--debug]
```

- `--host HOST`: Bind address for the daemon
- `--port PORT`: Daemon port
- `--domain DOMAIN`: Domain suffix for hostname parsing
- `--password PASS`: Registration password
- `--web-host HOST`: Web interface bind address
- `--web-port PORT`: Web interface port
- `--web-https`: Enable HTTPS for web interface
- `--debug`: Enable debug output

#### Configuration File

wssshd supports `/etc/wssshd.conf`:

```ini
[wssshd]
host = 0.0.0.0
port = 9898
password = mysecret
domain = example.com
web-host = 0.0.0.0
web-port = 8080
web-https = false
```

### wssshc (Client Registration)

#### Command Line Options

```bash
wssshc --server-ip IP --port PORT --id ID --password PASS [--interval SEC] [--debug]
```

- `--server-ip IP`: wssshd server IP address
- `--port PORT`: wssshd server port (default: 9898)
- `--id ID`: Unique client identifier
- `--password PASS`: Registration password
- `--interval SEC`: Reconnection interval in seconds (default: 30)
- `--debug`: Enable debug output

#### Configuration File

wssshc supports `~/.config/wsssh/wssshc.conf`:

```ini
[wssshc]
password = mysecret
server-ip = 192.168.1.100
port = 9898
id = client1
```

### wsssh (SSH Wrapper)

#### Command Line Options

```bash
wsssh [options] user@client.domain [ssh_options...]
```

- `--local-port PORT`: Local tunnel port (default: auto)
- `--tunnel TRANSPORT`: Transport for data channel
- `--tunnel-control TRANSPORT`: Transport for control channel
- `--service SERVICE`: Service type (default: ssh)
- `--enc ENCODING`: Data encoding: hex, base64, or bin (default: hex)
- `--debug`: Enable debug output
- `--dev-tunnel`: Setup tunnel but don't launch SSH

### wsscp (SCP Wrapper)

#### Command Line Options

```bash
wsscp [options] [scp_options...] source destination
```

- `--local-port PORT`: Local tunnel port (default: auto)
- `--tunnel TRANSPORT`: Transport for data channel
- `--tunnel-control TRANSPORT`: Transport for control channel
- `--service SERVICE`: Service type (default: ssh)
- `--enc ENCODING`: Data encoding: hex, base64, or bin (default: hex)
- `--debug`: Enable debug output
- `--dev-tunnel`: Setup tunnel but don't launch SCP

### wsssht (Tunnel Setup Tool)

#### Command Line Options

```bash
wsssht [--config FILE] [--clientid ID] [--tunnel-port PORT] [--tunnel-host HOST] [--wssshd-host HOST] [--wssshd-port PORT] [--interval SEC] [--debug] [--tunnel TRANSPORT] [--tunnel-control TYPES] [--service SERVICE] [--mode MODE] [--silent] [--bridge] [--script] [--daemon] [--help] [service://]clientid[@wssshd-host][:wssshd-port]
```

- `--config FILE`: Custom config file
- `--clientid ID`: Client ID for tunnel
- `--tunnel-port PORT`: Local tunnel port (default: auto)
- `--tunnel-host HOST`: Local bind address (default: 127.0.0.1)
- `--wssshd-host HOST`: wssshd server hostname
- `--wssshd-port PORT`: wssshd server port (default: 9898)
- `--interval SEC`: Connection retry interval (default: 5)
- `--debug`: Enable debug output
- `--tunnel TRANSPORT`: Data channel transport
- `--tunnel-control TYPES`: Control channel transport
- `--service SERVICE`: Service type (default: ssh)
- `--mode MODE`: Operating mode (interactive/silent/bridge/script)
- `--silent`: Shortcut for silent mode
- `--bridge`: Shortcut for bridge mode
- `--script`: Shortcut for script mode
- `--daemon`: Enable daemon mode
- `--help`: Display help message

## Configuration

### Config File Locations

WSSSH uses a hierarchical configuration system:

1. **Command line options** (highest priority)
2. **User configuration**: `~/.config/wsssh/wsssht.conf`
3. **System configuration**: `/etc/wsssht.conf` (lowest priority)

### Configuration Options

#### wsssht Configuration

```ini
[wsssht]
wssshd-host = example.com
wssshd-port = 9898
clientid = myclient
tunnel-port = 0
tunnel-host = 127.0.0.1
tunnel = websocket
tunnel-control = websocket
service = ssh
interval = 5
mode = interactive
daemon = false
```

#### Service Configuration Files

WSSSH supports multiple services per client through individual service configuration files. These files are stored in the `services-path` directory (default: `/etc/wsssh.d/`) and allow you to configure different services like SSH, RDP, VNC, etc.

##### Service Configuration File Format
Each service configuration file defines a single service with the following format:

```ini
[service_name]
# Target host for the tunnel connection
tunnel-host = 192.168.1.100

# Target port for the tunnel connection
tunnel-port = 22

# Optional command to execute before establishing the tunnel
# command = /usr/local/bin/setup-tunnel.sh

# Protocol to use (tcp or udp, default: tcp)
proto = tcp
```

##### Service Configuration Examples

**SSH Service** (`/etc/wsssh.d/ssh.conf`):
```ini
[ssh]
tunnel-host = 192.168.1.100
tunnel-port = 22
proto = tcp
```

**RDP Service** (`/etc/wsssh.d/rdp.conf`):
```ini
[rdp]
tunnel-host = 192.168.1.100
tunnel-port = 3389
proto = tcp
```

**VNC Service** (`/etc/wsssh.d/vnc.conf`):
```ini
[vnc]
tunnel-host = 192.168.1.100
tunnel-port = 5900
proto = tcp
```

**Custom Service with Setup Command** (`/etc/wsssh.d/custom.conf`):
```ini
[custom]
tunnel-host = 10.0.0.5
tunnel-port = 8080
command = /usr/local/bin/prepare-service.sh
proto = tcp
```

##### Service Configuration Directory Setup

```bash
# Create the services directory
sudo mkdir -p /etc/wsssh.d/

# Copy example service configurations
sudo cp service.conf.example /etc/wsssh.d/ssh.conf

# Edit the service configuration
sudo editor /etc/wsssh.d/ssh.conf
```

##### Multiple Services Configuration

You can configure multiple services by creating separate configuration files in the services directory:

```bash
# SSH service
sudo cp service.conf.example /etc/wsssh.d/ssh.conf
sudo editor /etc/wsssh.d/ssh.conf

# RDP service
sudo cp service.conf.example /etc/wsssh.d/rdp.conf
sudo editor /etc/wsssh.d/rdp.conf

# VNC service
sudo cp service.conf.example /etc/wsssh.d/vnc.conf
sudo editor /etc/wsssh.d/vnc.conf
```

##### Service Discovery and Loading

- Service configuration files are loaded from the `services-path` directory specified in `wssshc.conf`
- Multiple directories can be specified using colon separation: `/etc/wsssh.d/:/usr/local/etc/wsssh.d/`
- Files must have a `.conf` extension
- The section name `[service_name]` defines the service identifier used in tunnel requests
- Services are loaded at client startup and registered with the server

#### wsssh/wsscp Configuration

```ini
[default]
port = 9898
domain = example.com
tunnel = websocket
tunnel-control = websocket
service = ssh
```

### SSL Certificate Configuration

The system uses SSL/TLS certificates for encryption:

- **Certificate File**: `cert.pem` (X.509 certificate)
- **Private Key File**: `key.pem` (RSA/ECDSA private key)

Certificates are automatically generated during build:

```bash
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem \
  -days 365 -nodes -subj "/C=US/ST=State/L=City/O=Organization/CN=localhost"
```

## Logging Configuration

### Log Files and Locations

WSSSH implements comprehensive logging:

- **wssshd logs**: `/var/log/wssshd/wssshd.log`
- **wssshc logs**: `/var/log/wssshc/wssshc.log`
- **Watchdog logs**: `/var/log/wssshd/watchdog.log`, `/var/log/wssshc/watchdog.log`

### Logrotate Configuration

```bash
/var/log/wssshd/wssshd.log {
    weekly
    missingok
    rotate 52
    compress
    delaycompress
    notifempty
    create 644 wssshd wssshd
    postrotate
        systemctl reload wssshd
    endscript
}
```

### Log Analysis

Key log entries to monitor:

- **Client Registration**: `"Client X registered"` or `"Client X disconnected"`
- **Tunnel Operations**: `"Tunnel request for client X"` or `"Tunnel established"`
- **Errors**: `"Connection failed"`, `"SSL verification failed"`, `"Authentication error"`

## Security

### Encryption

- **Transport Layer**: All connections use SSL/TLS encryption
- **Certificate Validation**: Clients verify server certificates
- **Data Protection**: All tunnel data is encrypted end-to-end

### Authentication

- **Client Registration**: Unique client IDs with password authentication
- **SSH Authentication**: Standard SSH authentication mechanisms
- **Connection Isolation**: Each tunnel session is isolated

### Security Considerations

1. **Certificate Management**:
   - Use CA-signed certificates in production
   - Regularly rotate certificates
   - Implement certificate pinning if required

2. **Network Security**:
   - Restrict wssshd access to trusted networks
   - Use firewalls to limit exposure
   - Implement rate limiting

3. **Client Security**:
   - Use strong, unique client IDs
   - Regularly rotate client registrations
   - Monitor client connection logs

## Troubleshooting

### Common Issues

#### Connection Refused

**Symptoms**: "Connection refused" when connecting to wssshd

**Causes**:
- wssshd not running
- Firewall blocking port
- Incorrect host/port configuration

**Solutions**:
```bash
# Check if wssshd is running
netstat -tlnp | grep :9898

# Test connection
curl -I https://localhost:9898
```

#### Client Not Registered

**Symptoms**: "Client not registered" error

**Causes**:
- wssshc not running on target machine
- Incorrect client ID
- Network connectivity issues

**Solutions**:
```bash
# Verify client registration
./wssshc --server-ip <ip> --port 9898 --id <client_id> --password <password>

# Check server logs
tail -f /var/log/wssshd/wssshd.log
```

#### SSL Certificate Errors

**Symptoms**: SSL verification failures

**Causes**:
- Self-signed certificates
- Expired certificates
- Certificate hostname mismatch

**Solutions**:
```bash
# Regenerate certificates
./build.sh

# Check certificate validity
openssl x509 -in cert.pem -text -noout
```

### Debug Mode

Enable debug output for detailed troubleshooting:

```bash
# wssshd debug
./wssshd --debug --host 0.0.0.0 --port 9898 --domain example.com --password mysecret

# wssshc debug
./wssshc --debug --server-ip <ip> --port 9898 --id client1 --password <password>

# wsssh debug
./wsssh --debug user@client.example.com

# wsscp debug
./wsscp --debug file user@client.example.com:/path/

# wsssht debug
./wsssht --debug myclient@example.com
```

## Development

### Project Structure

```
wsssh/
├── build.sh               # Build script for all components
├── clean.sh               # Clean script
├── wssshd2/               # C server implementation
│   ├── main.c            # Server main entry point
│   ├── web.c             # Embedded web interface with SQLite
│   ├── config.c          # Configuration handling
│   ├── terminal.c        # Terminal session management
│   ├── websocket.c       # WebSocket protocol handling
│   ├── ssl.c             # SSL/TLS encryption
│   ├── tunnel.c          # Tunnel management
│   ├── assets.c          # Embedded web assets
│   ├── html_pages/       # Embedded HTML templates
│   ├── configure.sh      # Build configuration
│   ├── Makefile          # Build system
│   └── assets.o          # Compiled embedded assets
├── wssshtools/            # C client tools
│   ├── wssshc.c          # Client registration tool
│   ├── wsssh.c           # SSH wrapper
│   ├── wsscp.c           # SCP wrapper
│   ├── wsssht.c          # Tunnel setup tool
│   ├── libwsssht/        # Shared libraries
│   │   ├── wsssht.h      # Main header
│   │   ├── utils.h/c     # Utility functions
│   │   ├── modes.h/c     # Operating modes
│   │   ├── threads.h/c   # Thread management
│   │   ├── tunnel.h/c    # Tunnel functions
│   │   ├── websocket.h/c # WebSocket support
│   │   ├── wssh_ssl.h/c  # SSL/TLS support
│   │   └── wssshlib.h/c  # Core library
│   ├── configure.sh      # Build configuration
│   ├── Makefile          # Build system
│   ├── man/              # Manual pages
│   └── debian/           # Debian packaging
├── wsssh-server/         # Server Debian package
├── CHANGELOG.md          # Version history
├── DOCUMENTATION.md      # Technical documentation
├── TODO.md               # Development tasks
├── README.md             # Project overview
└── BRIDGE_MODE_TESTING.md # Testing documentation
```

### Dependencies

#### Server Dependencies (wssshd2)
- **GCC**: GNU C Compiler (4.8+)
- **Make**: GNU Make build system
- **SQLite3**: Database library (libsqlite3-dev)
- **OpenSSL**: SSL/TLS library (libssl-dev)
- **pkg-config**: Build configuration tool

#### Client Tools Dependencies (wssshtools)
- **GCC**: GNU C Compiler (4.8+)
- **Make**: GNU Make build system
- **OpenSSL**: SSL/TLS library (libssl-dev)
- **pkg-config**: Build configuration tool

### Building from Source

#### Server Build (C Implementation)
```bash
# Build server binary with embedded web interface
./build.sh --server-only

# Or build everything
./build.sh
```

#### Client Tools Build
```bash
# Configure and build C tools
cd wssshtools
./configure.sh
make

# Install system-wide (optional)
sudo make install
```

#### Debian Packages
```bash
# Build all packages
./build.sh --debian

# Install packages
sudo dpkg -i dist/wsssh-server*.deb dist/wsssh-tools*.deb
```

### Testing

```bash
# Unit tests
python3 -m pytest tests/test_*.py

# Integration tests
python3 -m pytest tests/integration/

# Manual testing
./test/manual_test.sh
```

## Recent Updates

### Version 1.7.0 - Major C Implementation Transition
- **Complete Architecture Migration**: Transitioned from Python/PyInstaller to native C implementation
  - Replaced Python wssshd with high-performance C daemon (`wssshd2/`)
  - Eliminated Python runtime dependencies for server component
  - Maintained full backward compatibility for client tools
  - Improved performance and reduced resource usage

- **SQLite Database Integration**: Persistent user management with secure storage
  - Automatic database creation and schema management
  - User authentication with password hashing
  - Admin user role management
  - Security warnings for default credentials
  - Database-backed session management

- **Embedded Web Interface**: Self-contained web server with no external dependencies
  - HTML/CSS/JavaScript assets embedded in binary
  - User management interface with add/edit/delete functionality
  - Real-time terminal interface with fullscreen support
  - Responsive Bootstrap-based design
  - AJAX-powered dynamic content updates

- **Enhanced Security Features**:
  - Automatic security warnings for default admin credentials
  - Proper session management with configurable timeouts
  - Input validation and bounds checking
  - Secure password storage with hashing
  - Admin role-based access control

- **Professional ASCII Art**: Startup banner with project branding
- **Comprehensive Debug Options**: Database, web, and general debug logging
- **Smart Directory Selection**: Automatic root vs user directory detection
- **Updated Debian Packaging**: Modified for C binary with proper dependencies

### Version 1.6.5
- **Flexible Data Encoding Support**: New `--enc` option for wsssht with multiple encoding modes
  - `--enc hex`: Hexadecimal encoding of binary data (default, backward compatible)
  - `--enc base64`: Base64 encoding of binary data for better efficiency
  - `--enc bin`: Direct binary data transmission without encoding
  - Configuration file support with `enc = hex` option in `wsssht.conf`
  - Automatic encoding negotiation between wsssht and wssshc clients

### Version 1.6.2
- **Tunnel Close Forwarding**: Critical fix for tunnel closure synchronization between wssshc, server, and wsssht
- **Web Terminal JavaScript Fixes**: Comprehensive fixes for web interface terminal functionality
- **Fullscreen Terminal Support**: Enhanced web terminal with fullscreen toggle functionality
- **Logo Serving Path**: Fixed web interface logo loading from correct directory

### Version 1.6.1
- **Major Code Refactoring**: Complete modularization of wsssht.c
- **Operating Modes**: Multiple operating modes implementation
- **Bridge Mode**: JSON stdin/stdout interface
- **Script Mode**: JSON protocol for scripting
- **Daemon Mode**: Lazy tunnel initialization

### Version 1.5.0
- **Peer-to-Peer Tunneling**: Advanced tunneling system
- **Transport Selection**: Configurable transport protocols
- **PyInstaller Template Fix**: Frozen executable template loading

### Version 1.4.8
- **SSL Connection Stability**: Comprehensive SSL error handling
- **Process Exit Handling**: Fixed critical process hanging issues
- **Code Architecture**: Modular design with shared libraries

---

## Donations

If you find WSSSH useful, please consider supporting the project:

### PayPal
Donate via PayPal to: **info@nexlab.net**

### Cryptocurrency
- **Bitcoin (BTC)**: `bc1q3zlkpu95amtcltsk85y0eacyzzk29v68tgc5hx`
- **Ethereum (ETH)**: `0xdA6dAb526515b5cb556d20269207D43fcc760E51`

## License

This project is licensed under the GNU General Public License v3.0 (GPLv3).

Copyright (C) 2024 Stefy Lanza <stefy@nexlab.net> and SexHack.me

See [LICENSE.md](LICENSE.md) for the full license text.