# WebSocket SSH Documentation

## Table of Contents

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

## Overview

WebSocket SSH (wsssh) is a tunneling system that enables secure SSH/SCP access to remote machines through WebSocket-based intermediaries. Unlike traditional SSH jump hosts, wsssh uses WebSocket connections for real-time, bidirectional communication between clients and servers.

### Key Components

#### Python Implementation (Primary)
- **wssshd**: WebSocket SSH Daemon - Central server with web interface
- **wssshc**: WebSocket SSH Client - Registers machines with the daemon
- **wsssh**: SSH wrapper - Provides SSH access through tunnels
- **wsscp**: SCP wrapper - Provides SCP access through tunnels

#### C Implementation (Alternative)
- **wssshc**: Lightweight C client for registration (OpenSSL-based)
- **wsssh**: Native SSH wrapper with direct system integration
- **wsscp**: Native SCP wrapper optimized for file transfers

### Core Features

- **Dual Implementation**: Python (full-featured) and C (lightweight) versions
- **Intelligent Hostname Parsing**: Automatic detection of client IDs and server endpoints
- **SSL/TLS Encryption**: Secure WebSocket communications with OpenSSL
- **Multi-client Support**: Route connections to different registered clients
- **Simplified CLI**: No need to specify "ssh" or "scp" commands explicitly
- **Drop-in Replacement**: Compatible with existing SSH/SCP workflows
- **Debian Packaging**: Professional system integration with dependencies
- **Cross-platform**: Works on Linux, macOS, and Windows
- **Donation Support**: Community funding through PayPal and cryptocurrency

## Architecture

### System Architecture

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

### Data Flow

1. **Registration Phase**:
   - wssshc connects to wssshd via WebSocket
   - Registers with unique client ID
   - 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 SSH server
    - wsssh launches SSH client to local tunnel port

3. **Data Transfer Phase**:
   - SSH traffic flows: SSH Client ↔ wsssh ↔ wssshd ↔ wssshc ↔ SSH Server
   - All WebSocket connections are encrypted with SSL/TLS

## Protocol Specification

### WebSocket Message Format

All messages are JSON-encoded with the following structure:

```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"
}
```

**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"
}
```

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

**Tunnel Error** (wssshd → wsssh):
```json
{
  "type": "tunnel_error",
  "request_id": "unique_request_uuid",
  "error": "error_description"
}
```

**Forward Tunnel Request** (wssshd → wssshc):
```json
{
  "type": "tunnel_request",
  "request_id": "unique_request_uuid"
}
```

#### Data Transfer Messages

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

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

### Hostname Parsing Algorithm

The hostname parsing follows this 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 ssh_port specified: use ssh_port
   else: use 22 (default)
```

## API Reference

### wssshd (WebSocket SSH Daemon)

#### Command Line Options

```bash
wssshd --host HOST --port PORT --domain DOMAIN [--debug]
```

- `--host HOST`: Bind address for WebSocket server (default: 0.0.0.0)
- `--port PORT`: WebSocket server port (required)
- `--domain DOMAIN`: Domain suffix for hostname parsing (required)
- `--debug`: Enable debug output

#### WebSocket Endpoints

- `ws://HOST:PORT/`: Main WebSocket endpoint for client connections

### wssshc (WebSocket SSH Client)

#### Command Line Options

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

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

### wsssh (SSH Wrapper)

#### Command Line Options

```bash
wsssh [--local-port PORT] [--debug] ssh [SSH_OPTIONS...] user@host [COMMAND...]
```

- `--local-port PORT`: Local tunnel port (default: auto-assign)
- `--debug`: Enable debug output

#### Environment Variables

- None

### wsscp (SCP Wrapper)

#### Command Line Options

```bash
wsscp [--local-port PORT] [--debug] [SCP_OPTIONS...] SOURCE... DESTINATION
```

- `--local-port PORT`: Local tunnel port (default: auto-assign)
- `--debug`: Enable debug output

### C Implementation Tools

#### wssshc (C Client)

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

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

#### wsssh (C SSH Wrapper)

```bash
wsssh user@client.domain -p PORT [SSH_OPTIONS...]
```

- `-p PORT`: wssshd server port
- `--local-port PORT`: Local tunnel port (default: auto)
- `--debug`: Enable debug output

#### wsscp (C SCP Wrapper)

```bash
wsscp [SCP_OPTIONS...] SOURCE... DESTINATION
```

- `-P PORT`: wssshd server port
- `--local-port PORT`: Local tunnel port (default: auto)
- `--debug`: Enable debug output

## Configuration

### SSL Certificate Configuration

The system uses SSL/TLS certificates for WebSocket encryption:

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

Certificates are automatically generated during the build process using OpenSSL:

```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"
```

### Client Configuration

Each client machine requires:

1. **Unique Client ID**: Identifier for routing connections
2. **Network Access**: Ability to connect to wssshd server
3. **SSH Server**: Running SSH daemon (sshd) on the client machine

### Server Configuration

The wssshd server requires:

1. **Network Interface**: IP address and port for WebSocket connections
2. **Domain Configuration**: Domain suffix for hostname parsing
3. **SSL Certificates**: Valid certificate and private key files

## Security

### Encryption

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

### Authentication

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

### Security Considerations

1. **Certificate Management**:
   - Use proper 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

4. **SSH Security**:
   - Disable password authentication
   - Use key-based authentication
   - Implement SSH hardening practices

### Known Security Limitations

- Self-signed certificates may trigger warnings
- No built-in DDoS protection
- Basic client authentication (ID-based only)
- No session encryption beyond SSL/TLS

## 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 WebSocket connection
curl -I https://localhost:9898
```

#### Client Not Registered

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

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

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

# Verify client appears in wssshd logs
tail -f 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
```

#### Tunnel Connection Issues

**Symptoms**: SSH/SCP connections hang or fail

**Causes**:
- Local SSH server not running
- Port conflicts
- Firewall blocking local ports

**Solutions**:
```bash
# Check local SSH server
systemctl status sshd

# Test local SSH connection
ssh localhost

# Check port availability
netstat -tlnp | grep :22
```

### Debug Mode

Enable debug output for detailed troubleshooting:

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

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

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

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

### Log Analysis

Key log messages to monitor:

- **Registration**: "Client X registered"
- **Tunnel Requests**: "Tunnel request for client X"
- **Connection Issues**: "Connection failed" or "SSL verification failed"
- **Data Transfer**: "Forwarding X bytes"

## Development

### Project Structure

```
wsssh/
├── wssshd.py          # WebSocket SSH Daemon (Python)
├── wssshc.py          # WebSocket SSH Client (Python)
├── wsssh.py           # SSH wrapper (Python)
├── wsscp.py           # SCP wrapper (Python)
├── build.sh           # Build script (supports --debian)
├── clean.sh           # Clean script
├── requirements.txt   # Python dependencies
├── cert.pem           # SSL certificate (auto-generated)
├── key.pem            # SSL private key (auto-generated)
├── templates/         # Flask web templates
├── static/            # Web assets
├── wssshtools/        # C implementation directory
│   ├── wssshc.c       # C client (280 lines)
│   ├── wsssh.c        # C SSH wrapper (378 lines)
│   ├── wsscp.c        # C SCP wrapper (418 lines)
│   ├── configure.sh   # Build configuration
│   ├── Makefile       # GNU Make build system
│   └── debian/        # Debian packaging
│       ├── control    # Package metadata
│       ├── rules      # Build rules
│       ├── changelog  # Package changelog
│       ├── copyright  # Copyright info
│       └── compat     # Debhelper compatibility
├── .gitignore         # Git ignore rules
├── LICENSE.md         # GPLv3 license
├── README.md          # Main documentation
├── DOCUMENTATION.md   # This file
├── CHANGELOG.md       # Version history
└── logos/             # Logo and icon assets
    ├── logo-*.png     # Various logo sizes
    ├── icon-*.png     # Application icons
    ├── banner-*.png   # Banner images
    └── favicon.ico    # Web favicon
```

### Dependencies

#### Python Implementation
- **Python 3.7+**
- **websockets**: WebSocket client/server library
- **Flask**: Web framework for admin interface
- **Flask-Login**: User authentication
- **Flask-SQLAlchemy**: Database support
- **ssl**: SSL/TLS support (built-in)
- **asyncio**: Asynchronous I/O (built-in)
- **subprocess**: Process management (built-in)
- **socket**: Network sockets (built-in)

#### C Implementation
- **GCC**: GNU C Compiler
- **Make**: GNU Make build system
- **OpenSSL**: SSL/TLS library (libssl-dev)
- **pkg-config**: Build configuration tool
- **Man Pages**: Comprehensive documentation (man)

#### Debian Packaging
- **debhelper**: Debian packaging helper
- **dh-autoreconf**: Autotools integration
- **gcc**: C compiler
- **libssl-dev**: OpenSSL development headers

### Building from Source

#### Python Implementation
```bash
# Install Python dependencies
pip3 install -r requirements.txt

# Build Python binaries
./build.sh

# Build with Debian package
./build.sh --debian
```

#### C Implementation
```bash
# Configure and build C tools
cd wssshtools
./configure.sh
make

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

#### Debian Package
```bash
# Build Debian package
./build.sh --debian

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

#### Clean Build Artifacts
```bash
# Clean all build artifacts
./clean.sh
```

### Testing

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

# Integration tests
python3 -m pytest tests/integration/

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

### Code Style

- Follow PEP 8 style guidelines
- Use type hints for function parameters
- Include docstrings for all public functions
- Use descriptive variable names

### Contributing

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

### Release Process

1. Update version in all relevant files
2. Update CHANGELOG.md
3. Create git tag
4. Build release binaries
5. Create GitHub release
6. Update documentation

---

## Donations

If you find WebSocket SSH useful, please consider supporting the project development:

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

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

Your support helps us continue developing and maintaining this open-source project! ❤️

## Support

For support and questions:

- **GitHub Issues**: Bug reports and feature requests
- **Documentation**: This comprehensive guide
- **Community**: Join discussions and get help

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