# WebSocket SSH (wsssh)

![WebSocket SSH Logo](logos/logo-256.png)

A modern SSH tunneling system that uses WebSocket connections to securely route SSH/SCP traffic through registered client machines. This allows you to access remote servers through intermediate "jump hosts" using WebSocket-based tunnels.

## Features

- **Dual Implementation**: Python (full-featured) and C (lightweight) versions available
- **WebSocket-based Tunneling**: Secure SSH/SCP access through WebSocket connections
- **Client Registration**: Register client machines with the WebSocket daemon
- **Password Authentication**: Secure client registration with configurable passwords
- **Web Management Interface**: Professional admin panel with user management and HTML5 terminal
- **Intelligent Hostname Parsing**: `<CLIENT_ID>.<WSSSHD_HOST>` format with `-p`/`-P` port options
- **Simplified CLI**: No need to specify "ssh" or "scp" commands explicitly
- **Drop-in SSH/SCP Replacement**: Use `wsssh` and `wsscp` as direct replacements for `ssh` and `scp`
- **SSL/TLS Encryption**: All WebSocket communications are encrypted
- **Multi-client Support**: Route connections to different registered clients
- **Cross-platform**: Works on Linux, macOS, and Windows
- **Debian Packaging**: Easy installation with proper system integration
- **wsssh-server Package**: Standalone Debian package for wssshd daemon
- **PyInstaller Binary**: Standalone wssshd binary with no Python dependencies
- **Professional Service Management**: Complete init scripts and service integration
- **Watchdog Monitoring**: Automatic daemon restart and high availability
- **Enterprise Reliability**: Professional process supervision and monitoring
- **Donation Support**: Community funding through PayPal and cryptocurrency

## Architecture

The system consists of multiple components available in both Python and C implementations:

### Python Implementation (Primary)
1. **`wssshd`** - WebSocket SSH Daemon (server)
   - Manages WebSocket connections with SSL/TLS encryption
   - Handles client registrations with password authentication
   - Routes tunnel requests to appropriate clients
   - Professional web management interface with user administration
   - HTML5 terminal interface for SSH connections
   - Donation modal integrated into the web interface

2. **`wssshc`** - WebSocket SSH Client (registration)
   - Registers client machines with the daemon
   - Maintains persistent WebSocket connection
   - Automatic reconnection with configurable intervals

3. **`wsssh`** - SSH wrapper with tunneling
   - Simplified CLI (no need to specify "ssh" command)
   - Parses SSH commands and hostnames intelligently
   - Establishes WebSocket tunnels automatically
   - Launches SSH to local tunnel port

4. **`wsscp`** - SCP wrapper with tunneling
   - Simplified CLI (no need to specify "scp" command)
   - Similar to wsssh but optimized for SCP operations
   - Handles file transfers through secure tunnels

### C Implementation (Alternative)
Located in the `wssshtools/` directory:

1. **`wssshc`** - Lightweight C client for registration
   - Minimal dependencies (OpenSSL only)
   - Native WebSocket implementation
   - Optimized for embedded systems

2. **`wsssh`** - Native SSH wrapper
   - Direct system integration
   - No Python runtime required
   - High performance for production use

3. **`wsscp`** - Native SCP wrapper
   - Optimized file transfer operations
   - Consistent with SSH wrapper design
   - Enterprise-ready performance

## Installation

### From Source

```bash
# Clone the repository
git clone https://git.nexlab.net/nexlab/wsssh.git
cd wsssh

# Install dependencies
pip3 install -r requirements.txt

# Build binaries (optional)
./build.sh
```

### Using Pre-built Binaries

Download the latest release binaries for your platform from the releases page.

### Debian Package Installation

For Debian/Ubuntu systems, you can install both the server and client components via Debian packages:

#### wsssh-server Package (Daemon)
```bash
# Build the wsssh-server package
./build.sh --server-only

# Install the server package (no Python dependencies required!)
sudo dpkg -i dist/wsssh-server*.deb

# Configure the service
sudo cp /usr/share/wsssh/wssshd.conf.example /etc/wssshd.conf
sudo editor /etc/wssshd.conf

# Enable and start the service
sudo echo "START=yes" > /etc/default/wssshd
sudo /etc/init.d/wssshd start

# Check service status
sudo /etc/init.d/wssshd status

# View the man page
man wssshd
```

**Note**: The wsssh-server package uses a standalone PyInstaller binary that bundles all Python dependencies, so no additional Python packages are required for installation.

**Upgrade Note**: When upgrading the wsssh-server package, if the wssshd service is running, you will be prompted for confirmation before the service is stopped for the upgrade. The service will be automatically restarted afterward if it was running, ensuring zero-downtime upgrades.

**Non-Interactive Installation**: For automated deployments or CI/CD pipelines, use:
```bash
export DEBIAN_FRONTEND=noninteractive
sudo dpkg -i dist/wsssh-server*.deb
```
The service will be stopped and restarted automatically without user interaction.

#### wsssh-tools Package (C Implementation)
```bash
# Build the wsssh-tools package
./build.sh --wssshtools-only

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

# The C tools will be available system-wide
wssshc --help
wsssh --help
wsscp --help
```

#### Build Both Packages
```bash
# Build both packages
./build.sh --debian

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

### C Implementation Build

To build the C tools from source:

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

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

The C tools include comprehensive man pages:

```bash
man wssshc    # WebSocket SSH client
man wsssh     # SSH wrapper
man wsscp     # SCP wrapper
```

## Quick Start

### 1. Start the WebSocket Daemon

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

### 2. Register a Client

On the client machine you want to access through:

```bash
./wssshc --server-ip <daemon_ip> --port 9898 --id myclient --password mysecret
```

### 3. Connect via SSH

```bash
# Simplified CLI (recommended)
./wsssh user@myclient.example.com -p 9898

# Or using C implementation
./wssshtools/wsssh user@myclient.example.com -p 9898
```

This automatically:
- Parses `myclient.example.com` to extract client ID `myclient`
- Connects to wssshd at `example.com:9898`
- Requests tunnel to client `myclient`
- Opens local port and launches `ssh user@localhost`

## Hostname Format

The system uses intelligent hostname parsing with config file support:

```
<CLIENT_ID>.<WSSSHD_HOST>
```

**Supported Formats:**
- `user@client.domain` - Full specification with domain
- `user@client` - Uses domain from config file or defaults to localhost

Port is specified using `-p` (SSH) or `-P` (SCP) options, or from config file.

### Examples:

- `remote.example.com -p 9898` → Client: `remote`, Server: `example.com:9898`
- `server.datacenter.com -P 2222` → Client: `server`, Server: `datacenter.com:2222`
- `test.localhost -p 8080` → Client: `test`, Server: `localhost:8080`
- `myclient` (with config domain `example.com`) → Client: `myclient`, Server: `example.com:<config_port>`

## Port Detection Priority

1. **Command line option**: `-p <port>` (SSH) or `-P <port>` (SCP)
2. **Config file**: `port` setting in `~/.config/wsssh/wsssh.conf`
3. **Default**: `22` (standard SSH port)

## Detailed Usage

### wssshd (WebSocket SSH Daemon)

```bash
./wssshd --host 0.0.0.0 --port 9898 --domain example.com --password mysecret [--web-host 0.0.0.0 --web-port 8080] [--web-https] [--debug]
```

**Options:**
- `--host`: Bind address
- `--port`: WebSocket port
- `--domain`: Domain suffix for hostname parsing
- `--password`: Registration password
- `--web-host`: Web interface bind address (optional)
- `--web-port`: Web interface port (optional)
- `--web-https`: Enable HTTPS for web interface
- `--debug`: Enable debug output

**Configuration File:**
wssshd supports a system-wide configuration file at `/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
```

Command line options override configuration file values. Required parameters are only mandatory when not provided in either the config file or command line.

**Web Interface:**
When `--web-host` and `--web-port` are specified, a web management interface is available with:
- User authentication (default: admin/admin123)
- Client connection overview
- User management (admin only)
- HTML5 terminal interface

### wssshc (WebSocket SSH Client)

```bash
./wssshc --server-ip <ip> --port 9898 --id client1 --password mysecret [--interval 30] [--debug]
```

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

**Configuration File:**
wssshc supports an optional configuration file at `~/.config/wsssh/wssshc.conf`:

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

Command line options override configuration file values. Required parameters are only mandatory when not provided in either the config file or command line.

### wsssh (SSH Wrapper)

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

**Options:**
- `--local-port`: Local tunnel port (default: auto)
- `--debug`: Enable debug output

**Examples:**
```bash
# Basic SSH connection with explicit port and domain
./wsssh -p 9898 user@myclient.example.com

# SSH with custom port
./wsssh -p 2222 user@myclient.example.com

# SSH using config file defaults
./wsssh user@myclient

# SSH with options
./wsssh -p 9898 -i ~/.ssh/key user@myclient.example.com ls -la
```

### wsscp (SCP Wrapper)

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

**Options:**
- `--local-port`: Local tunnel port (default: auto)
- `--debug`: Enable debug output

**Examples:**
```bash
# Copy file to remote with explicit port and domain
./wsscp -P 9898 localfile user@myclient.example.com:/remote/path/

# Copy file from remote
./wsscp -P 9898 user@myclient.example.com:/remote/file ./localfile

# Copy using config file defaults
./wsscp localfile user@myclient:/remote/path/

# Copy with custom port
./wsscp -P 2222 localfile user@myclient.example.com:/remote/path/
```

## Configuration

### Config File

WebSocket SSH supports an optional INI-formatted configuration file at `~/.config/wsssh/wsssh.conf`:

```ini
[default]
port=8080
domain=example.com
```

**Configuration Options:**
- `port`: Default WebSocket server port (used when not specified via `-p`/`-P` options)
- `domain`: Default domain suffix (used when hostname doesn't include domain)

**Precedence Rules:**
- **Port**: Command line `-p`/`-P` options override config file, config file overrides default (22)
- **Domain**: Command line domain (e.g., `user@client.domain`) overrides config domain, config domain overrides localhost

**Examples:**
```bash
# Uses config port 8080 and domain example.com
./wsssh user@myclient

# Uses command line port 2222, config domain example.com
./wsssh -p 2222 user@myclient

# Uses command line port 2222 and domain mydomain.com
./wsssh -p 2222 user@myclient.mydomain.com
```

### SSL Certificates

The system uses self-signed SSL certificates for WebSocket encryption. Certificates are automatically generated during the build process if they don't exist.

- `cert.pem`: SSL certificate
- `key.pem`: Private key

Certificates are created with:
- 4096-bit RSA key
- Valid for 365 days
- Subject: `/C=US/ST=State/L=City/O=Organization/CN=localhost`

### Client Registration

Each client machine must be registered with wssshd using a unique ID:

```bash
./wssshc --server-ip <daemon_ip> --port <port> --id <unique_id> --password <password>
```

The client will maintain a persistent WebSocket connection to the daemon.

## Security Considerations

- **SSL/TLS**: All WebSocket communications are encrypted
- **Client Authentication**: Clients are identified by unique IDs
- **Network Security**: Ensure wssshd is only accessible from trusted networks
- **Certificate Validation**: Currently uses self-signed certificates

## Troubleshooting

### Connection Issues

1. **Check wssshd is running**: Verify the daemon is accessible on the specified port
2. **Client registration**: Ensure the client is registered and connected
3. **Firewall rules**: Check that required ports are open
4. **SSL certificates**: Verify certificate files exist and are valid

### Debug Mode

Enable debug output for detailed troubleshooting:

```bash
./wssshd --debug --host 0.0.0.0 --port 9898 --domain example.com --password mysecret
./wssshc --debug --server-ip <ip> --port 9898 --id client1 --password mysecret
./wsssh --debug -p 9898 user@client.domain
```

### Common Issues

- **"Client not registered"**: Register the client with wssshc first
- **"Connection refused"**: Check wssshd is running and ports are accessible
- **"SSL verification failed"**: The system uses self-signed certificates

## Development

### Building from Source

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

# Run tests
python3 -m pytest

# Build binaries
./build.sh

# Clean build artifacts
./clean.sh
```

### Project Structure

```
wsssh/
├── wssshd.py          # WebSocket SSH Daemon with web interface
├── wssshc.py          # WebSocket SSH Client
├── wsssh.py           # SSH wrapper (simplified CLI)
├── wsscp.py           # SCP wrapper (simplified CLI)
├── build.sh           # Build script (supports --debian flag)
├── clean.sh           # Clean script
├── requirements.txt   # Python dependencies
├── cert.pem           # SSL certificate (auto-generated)
├── key.pem            # SSL private key (auto-generated)
├── templates/         # Flask HTML templates
│   ├── base.html      # Base template with donation modal
│   ├── index.html     # Dashboard
│   ├── login.html     # Authentication
│   ├── terminal.html  # HTML5 terminal
│   └── users.html     # User management
├── static/            # Static web assets
├── wssshtools/        # C implementation directory
│   ├── wssshc.c       # C client for registration
│   ├── wsssh.c        # C SSH wrapper
│   ├── wsscp.c        # C SCP wrapper
│   ├── configure.sh   # C build configuration
│   ├── Makefile       # C 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          # This file
├── DOCUMENTATION.md   # Technical documentation
└── CHANGELOG.md       # Version history

## Logos and Icons

The project includes a comprehensive set of logos and icons derived from the original `image.jpg`:

### Logo Files
- `logos/logo-512.png` - High-resolution logo (512x512)
- `logos/logo-256.png` - Standard logo (256x256)
- `logos/logo-128.png` - Medium logo (128x128)
- `logos/logo-64.png` - Small logo (64x64)
- `logos/logo-high-quality.png` - Maximum quality version
- `logos/banner-800x200.png` - Banner version (800x200)

### Icon Files
- `logos/icon-256.png` - Large icon (256x256)
- `logos/icon-128.png` - Desktop icon (128x128)
- `logos/icon-64.png` - Toolbar icon (64x64)
- `logos/icon-48.png` - Application icon (48x48)
- `logos/icon-32.png` - Small icon (32x32)
- `logos/icon-16.png` - Tiny icon (16x16)
- `logos/favicon.ico` - Web favicon (32x32)

### Usage
- **Web**: Use `logos/favicon.ico` for website favicons
- **Desktop**: Use `logos/icon-128.png` or `logos/icon-64.png` for desktop shortcuts
- **Documentation**: Use `logos/logo-256.png` for README files and documentation
- **Marketing**: Use `logos/banner-800x200.png` for banners and social media
```

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

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

## Support

- **Issues**: Report bugs and request features on GitHub
- **Documentation**: See the [docs/](docs/) directory for detailed documentation
- **Community**: Join our community discussions

## Donations

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

### 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! ❤️

## Changelog

### Version 1.4.2 (Latest)
- **Debian Package Build System Fixes**: Comprehensive fixes for wsssh-server package building
  - Fixed Makefile syntax error in debian/rules by replacing here document with echo commands
  - Resolved "missing separator" error caused by tab characters in PyInstaller spec generation
  - Removed redundant debian/compat file causing debhelper compatibility conflicts
  - Added automatic directory creation in install target to prevent "No such file or directory" errors
  - Implemented binary reuse logic to avoid unnecessary rebuilds of wssshd binary
  - Enhanced build efficiency by copying existing binaries from dist/ directory when available
  - Fixed --server-only option to properly build wsssh-server Debian package

- **Build System Improvements**: Enhanced build script functionality and error handling
  - More robust error handling and directory creation for Debian package builds
  - Intelligent reuse of existing build artifacts to reduce build times
  - Improved output messages showing package build status
  - Better dependency checking and error reporting for Debian builds

### Version 1.4.1
- **Watchdog Scripts for High Availability**: Professional daemon monitoring and automatic restart
  - `wssshd-watchdog`: Comprehensive watchdog script for wssshd daemon with automatic restart on failure
  - `wssshc-watchdog`: Watchdog script for wssshc client daemon with configurable restart limits
  - Enhanced init scripts that launch daemons through watchdog for process supervision
  - Configurable monitoring intervals (default: 30 seconds) and restart policies
  - Prevents restart loops with 5-restart limit per 5-minute window
  - Detailed logging to /var/log/wssshd/watchdog.log and /var/log/wssshc/watchdog.log
  - Integration with syslog for system monitoring and troubleshooting
  - Proper signal handling and resource cleanup on shutdown

- **Enterprise Reliability Features**: Production-grade process supervision and monitoring
  - Automatic daemon restart on unexpected termination or crashes
  - Non-blocking watchdog operation that doesn't interfere with normal service operation
  - Enhanced service status reporting showing both daemon and watchdog process information
  - Robust error handling for various failure scenarios and edge cases
  - Professional standards compliance for enterprise deployment

### Version 1.4.0
- **wsssh-server Debian Package**: Complete standalone Debian package for wssshd daemon
- **PyInstaller Binary Packaging**: wssshd packaged as standalone executable with no Python dependencies
- **Professional Service Management**: Complete init scripts with wssshd user/group support and rc2.d integration
- **Comprehensive wssshd Man Page**: Full documentation for wssshd daemon with usage examples and configuration
- **Enhanced Build System**: Updated build.sh with --server-only option for selective package building
- **Multi-Package Architecture**: Separate wsssh-server (daemon) and wsssh-tools (clients) packages
- **Security Hardening**: Dedicated wssshd user/group with minimal privileges and proper file ownership
- **System Integration**: Complete Debian packaging with postinst/postrm scripts and service management
- **Configuration Management**: /etc/default/wssshd service control and /etc/wssshd.conf configuration
- **Enterprise Ready**: Production-grade deployment with professional standards compliance

### Version 1.3.4
- **Enhanced WebSocket Connection Management**: Robust ping/pong frame handling and automatic reconnection for wsssh.c and wsscp.c
- **Fixed Ping Frame Parsing**: Corrected WebSocket ping frame processing in C implementations with proper pong responses
- **Automatic Reconnection Logic**: Added smart reconnection with 1-second intervals for WebSocket recovery and configurable --interval for initial setup
- **Improved Connection Resilience**: Better handling of network interruptions with seamless tunnel recovery
- **Enhanced Debug Output**: Clear logging for connection state changes and reconnection attempts

### Previous Updates
- Enhanced logo assets with higher quality versions for better visual presentation
- Improved C implementation files for better performance and reliability
- Added dedicated clean script for easier project maintenance

See [CHANGELOG.md](CHANGELOG.md) for complete version history and changes.