From d8d4be7df4f47c3adde57737912ebf005ecaa1eb Mon Sep 17 00:00:00 2001 From: Quintus Leung Date: Wed, 15 Jul 2026 16:35:50 +0100 Subject: [PATCH] Update README and documents. --- README.md | 732 ++++------------------------------------- doc/admin_api.md | 208 ++++++++++++ doc/authentication.md | 134 ++++++++ doc/configuration.md | 163 +++++++++ doc/deployment.md | 91 +++++ doc/docker.md | 115 +++++++ doc/quickstart.md | 93 ++++++ doc/troubleshooting.md | 106 ++++++ doc/usage.md | 109 ++++++ 9 files changed, 1075 insertions(+), 676 deletions(-) create mode 100644 doc/admin_api.md create mode 100644 doc/authentication.md create mode 100644 doc/configuration.md create mode 100644 doc/deployment.md create mode 100644 doc/docker.md create mode 100644 doc/quickstart.md create mode 100644 doc/troubleshooting.md create mode 100644 doc/usage.md diff --git a/README.md b/README.md index fa85ea2..4c49779 100644 --- a/README.md +++ b/README.md @@ -1,711 +1,91 @@ # rust-socksd -A high-performance SOCKS5 and HTTP proxy server written in Rust, featuring modern async architecture and comprehensive security features. +A high-performance SOCKS5 and HTTP proxy server written in Rust, featuring modern async architecture, modular authentication, and comprehensive security features. + +--- ## Features -- **Full SOCKS5 Protocol Support**: Complete implementation with username/password authentication -- **HTTP Proxy**: Support for HTTP/HTTPS with CONNECT method, including Basic Authentication support -- **Upstream Proxy Routing**: Route outgoing traffic through upstream SOCKS5 or HTTP proxies, with support for Basic Authentication, domain/network bypass rules, and environment variables (`ALL_PROXY`, `HTTP_PROXY`, etc.) -- **Multi-threaded Architecture**: Built on tokio for high concurrency -- **YAML Configuration**: Flexible and easy-to-use configuration system -- **Modular Authentication Backends**: Secure authentication supporting Simple (file-based Argon2/Bcrypt/Scrypt), PAM, LDAP, and Database (MySQL/PostgreSQL) backends -- **Security Features**: Source network restrictions, domain blocking, egress destination network filtering, max request size control, and rate limiting -- **Systemd Integration**: Native Linux service support with journald logging -- **Comprehensive Logging**: Configurable logging to console, file, and journald with multiple levels -- **Package Support**: Debian packages and Arch AUR available +* **Dual Protocol Support**: Complete implementation of SOCKS5 (RFC 1928) and HTTP/HTTPS (CONNECT method) proxies running on separate ports. +* **Authentication**: Seamless username/password verification (Basic Auth for HTTP) using modular backends (Simple file-based, Linux PAM, LDAP, or SQL database). +* **Upstream Chaining**: Chain outgoing connections through upstream SOCKS5 or HTTP proxies, including bypass rules and environment variable support. +* **Granular Security Controls**: Source network restrictions (ingress ACLs), destination filters (egress ACLs), domain blocking, rate limiting, and request size controls. +* **Admin HTTP API**: Dedicated endpoint for real-time metrics, dynamic configuration validation, liveness/health probing, and hot reloads. +* **Production Hardened**: Native systemd service integration, Debian/Ubuntu packaging support, Arch Linux AUR, and multi-stage secure Docker containers. + +--- ## Quick Start -### Installation - -#### From Source +### Build and Run from Source ```bash +# Clone the repository git clone https://github.com/quintusl/rust-socksd.git cd rust-socksd + +# Build in release mode cargo build --release -sudo cp target/release/rust-socksd /usr/local/bin/ + +# Generate a default configuration file +./target/release/rust-socksd --generate-config config.yml + +# Start the proxy daemon +./target/release/rust-socksd --config config.yml ``` -#### Debian/Ubuntu +For package installations, Docker configurations, and platform-specific guides, see the [Quick Start Guide](doc/quickstart.md). -```bash -sudo dpkg -i rust-socksd_0.1.1-1_amd64.deb -``` +--- -#### Arch Linux +## Documentation Map -```bash -yay -S rust-socksd -``` +Detailed guides are split into topic-specific files located in the `doc/` directory: -#### Docker +| Document | Description | +| :--- | :--- | +| **[Quick Start Guide](doc/quickstart.md)** | Installation steps for Source, Debian, Arch Linux, and Docker; verification checks. | +| **[Configuration Guide](doc/configuration.md)** | Explanation of settings, logging, security policies, upstream proxies, and environment variables. | +| **[Authentication Backends](doc/authentication.md)** | Setting up file-based user accounts, Linux PAM, LDAP directory, SQL database, and CLI user controls. | +| **[CLI & Usage Guide](doc/usage.md)** | Command-line arguments, options, the `validate` and `user` subcommands, and proxy client examples. | +| **[Docker & Containerization](doc/docker.md)** | Running with Docker and Docker Compose, secure environment settings, and runtime mounts. | +| **[Deployment & Packaging](doc/deployment.md)** | Setting up systemd services, reading journald logs, and building `.deb` or AUR packages. | +| **[Admin API Reference](doc/admin_api.md)** | Endpoints for Prometheus metrics, health checking, config inspections, schema validation, and hot reload. | +| **[Troubleshooting Guide](doc/troubleshooting.md)** | Common errors (ports, permissions, connection, auth) and log inspecting techniques. | -```bash -# Pull and run the latest Docker image -docker run -d \ - --name rust-socksd \ - -p 1080:1080 \ - -p 8080:8080 \ - quintux/rust-socksd:latest -``` - -### Running - -#### Direct execution - -```bash -rust-socksd --config config.yml -``` - -#### As a systemd service - -```bash -sudo systemctl enable rust-socksd -sudo systemctl start rust-socksd -``` - -## Configuration - -The server is configured using a YAML file. See `config.yml.example` for a complete example with all options. - -Generate a default configuration file: - -```bash -rust-socksd --generate-config config.yml -``` - -Edit the configuration file to suit your needs: - -```bash -nano config.yml -``` - -### Basic Configuration - -```yaml -server: - bind_address: "127.0.0.1" - socks5_port: 1080 - http_port: 8080 - max_connections: 1000 - connection_timeout: 300 - -auth: - enabled: false - type: simple - user_config_file: "config/users.yml" - -logging: - level: "info" - console: true -``` - -### Authentication -rust-socksd supports multiple authentication backends to secure your proxy. - -#### Supported Backends - -1. **Simple (File-based)**: Uses a local YAML file with secure password hashes (Argon2, Bcrypt, Scrypt). -2. **PAM**: Integrates with Linux Pluggable Authentication Modules (e.g., system users). -3. **LDAP**: Authenticates against an LDAP directory (e.g., Active Directory, OpenLDAP). -4. **Database**: Authenticates against a MySQL or PostgreSQL database. - -#### Configuration Examples - -##### 1. Simple (File-based) - -```yaml -auth: - enabled: true - type: simple - user_config_file: "config/users.yml" -``` - -Manage users via CLI: -```bash -rust-socksd user --user-config config/users.yml add myuser -``` - -##### 2. PAM - -Authenticate using system users (requires running as root or with appropriate permissions): - -```yaml -auth: - enabled: true - type: pam - service: "socksd" # config file in /etc/pam.d/socksd -``` - -##### 3. LDAP - -```yaml -auth: - enabled: true - type: ldap - url: "ldap://ldap.example.com:389" - base_dn: "ou=users,dc=example,dc=com" - # Optional binding for search - bind_dn: "cn=admin,dc=example,dc=com" - bind_password: "admin_password" - user_filter: "(uid={})" # {} is replaced by the username -``` - -##### 4. Database (MySQL/PostgreSQL) - -Authenticate by fetching a password hash from a database. The hash is verified using the same secure algorithms as the Simple backend. - -```yaml -auth: - enabled: true - type: database - db_type: "mysql" # or "postgres" - url: "mysql://socksd:password@localhost/socksd_db" - query: "SELECT password_hash FROM users WHERE username = ?" - hash_type: "argon2" # argon2, bcrypt, or scrypt -``` - -### Security configuration - -Configure network restrictions and domain blocking: - -```yaml -security: - allowed_networks: - - "192.168.1.0/24" - - "10.0.0.0/8" - blocked_domains: - - "malicious-site.com" - - "blocked-domain.net" - allowed_egress_networks: - - "8.8.8.8" - - "8.8.4.4" - blocked_egress_networks: - - "127.0.0.0/8" - - "10.0.0.0/8" - max_request_size: 1048576 # 1MB max request size limit - rate_limit: - requests_per_minute: 1000 - burst_size: 100 -``` - -Enforcement notes: - -- **`allowed_networks`** is an *ingress* allowlist matched against the client's - source IP. An empty list allows all clients; a non-empty list rejects any - source that does not match an entry. Note that `0.0.0.0/0` matches IPv4 only — - add `::/0` if you also accept IPv6 clients. -- **`blocked_domains`** rejects proxy requests whose target host matches an entry - exactly or as a subdomain suffix (e.g. `evil.com` also blocks `sub.evil.com`). -- **`rate_limit`** applies a per-source-IP token bucket to newly accepted - connections (`burst_size` immediate, refilling at `requests_per_minute`). -- Egress rules resolve the target once and connect to the validated IP, so a - DNS response cannot pass the check on one address and be connected to on - another. - -### Upstream Proxy Configuration - -`rust-socksd` can route outgoing client traffic through an upstream SOCKS5 or HTTP proxy server. This is useful for chain-proxying, routing traffic through VPN gateways, or utilizing corporate proxies. - -```yaml -upstream: - # Enable upstream proxying (true/false) - enabled: true - - # Upstream protocol: 'socks5' or 'http' - protocol: socks5 - - # Address of the upstream proxy server - address: "127.0.0.1" - - # Port of the upstream proxy server - port: 1080 - - # Upstream proxy credentials (optional basic auth) - username: "proxy_user" - password: "proxy_password" - - # Networks to exclude from upstream proxying (CIDR blocks or IPs) - exclude_networks: - - "127.0.0.1/8" - - "10.0.0.0/8" - - # Domains to exclude from upstream proxying (exact or subdomain suffix) - exclude_domains: - - "localhost" - - "local.lan" - - # Respect standard environment variables: HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, NO_PROXY (true/false) - # If true, these environment variables will take precedence over options configured above. - prefer_env: true -``` - -#### Environment Variable Support - -When `prefer_env` is set to `true` (default), the proxy server automatically detects and uses standard proxy environment variables. They will override the configuration file. - -The environment variables checked are: -- `ALL_PROXY` or `all_proxy` (highest priority for SOCKS5 or general connections) -- `HTTPS_PROXY` or `https_proxy` (for secure HTTPS target requests) -- `HTTP_PROXY` or `http_proxy` (for HTTP target requests) -- `NO_PROXY` or `no_proxy` (comma/space-separated list of bypass targets) - -You can bypass the upstream proxy for specific IP ranges or domain suffixes by using `exclude_networks`, `exclude_domains`, or the standard `NO_PROXY` environment variable. A wildcard `*` in `NO_PROXY` will bypass the upstream proxy for all requests. - -## Usage - -### SOCKS5 Proxy - -Configure your applications to use the SOCKS5 proxy: - -- **Host**: Your server IP -- **Port**: 1080 (default) -- **Authentication**: Username/password (if enabled) - -Example with curl: - -```bash -curl --socks5-hostname localhost:1080 https://httpbin.org/ip -``` - -### HTTP Proxy - -Configure your applications to use the HTTP proxy: - -- **Host**: Your server IP -- **Port**: 8080 (default) - -Example with curl: - -```bash -curl --proxy localhost:8080 https://httpbin.org/ip -``` - -## Command Line Options - -### Main Command - -```bash -rust-socksd [OPTIONS] [SUBCOMMAND] - -OPTIONS: - -c, --config Configuration file path [default: config.yml] - -g, --generate-config Generate a default configuration file - -v, --verbose Enable verbose logging (can be used multiple times) - -q, --quiet Suppress all output except errors - -b, --bind
Bind address (can also be set via RUST_SOCKSD_BIND_ADDRESS) - -p, --http-port HTTP proxy port (can also be set via RUST_SOCKSD_HTTP_PORT) - -s, --socks5-port SOCKS5 proxy port (can also be set via RUST_SOCKSD_SOCKS5_PORT) - -l, --loglevel Log level: trace, debug, info, warn, error (can also be set via RUST_SOCKSD_LOG_LEVEL) - -h, --help Print help information - -V, --version Print version information - -SUBCOMMANDS: - validate Validate configuration files - user User management commands -``` - -### Validation Subcommand - -Validate configuration files for syntax and consistency: - -```bash -rust-socksd validate [OPTIONS] - -OPTIONS: - -c, --config Configuration file to validate [default: config.yml] - --user-config User configuration file to validate -``` - -Examples: - -```bash -# Validate main configuration -rust-socksd validate - -# Validate specific config files -rust-socksd validate --config /etc/rust-socksd/config.yml --user-config /etc/rust-socksd/users.yml -``` - -### User Management Subcommand - -Manage user accounts with secure password hashing: - -```bash -rust-socksd user [OPTIONS] [SUBCOMMAND_ARGS] - -OPTIONS: - --user-config User configuration file path [default: users.yml] - -SUBCOMMANDS: - init Initialize a new user configuration file - add Add a new user - remove Remove a user - list List all users - update Update user password - enable Enable/disable a user -``` - -#### User Subcommand Details - -##### Initialize User Config - -```bash -rust-socksd user [OPTIONS] init [SUB-OPTIONS] - -SUB-OPTIONS: - --hash-type Default password hash type: argon2, bcrypt, scrypt [default: argon2] -``` - -##### Add User - -```bash -rust-socksd user [OPTIONS] add [SUB-OPTIONS] [PASSWORD] - -ARGUMENTS: - Username - [PASSWORD] Password (will prompt if not provided) - -SUB-OPTIONS: - --hash-type Password hash type: argon2, bcrypt, scrypt [default: argon2] -``` - -##### Remove User - -```bash -rust-socksd user [OPTIONS] remove - -ARGUMENTS: - Username to remove -``` - -##### List Users - -```bash -rust-socksd user [OPTIONS] list -``` - -##### Update User Password - -```bash -rust-socksd user [OPTIONS] update [PASSWORD] - -ARGUMENTS: - Username - [PASSWORD] New password (will prompt if not provided) -``` - -##### Enable/Disable User - -```bash -rust-socksd user [OPTIONS] enable - -ARGUMENTS: - Username - Enable (true) or disable (false) -``` - -## Environment Variables - -rust-socksd supports several environment variables for configuration override: - -- **RUST_SOCKSD_BIND_ADDRESS**: Override the bind address (e.g., `0.0.0.0`) -- **RUST_SOCKSD_SOCKS5_PORT**: Override the SOCKS5 port (e.g., `1080`) -- **RUST_SOCKSD_HTTP_PORT**: Override the HTTP proxy port (e.g., `8080`) -- **RUST_SOCKSD_LOG_LEVEL**: Override the log level (`trace`, `debug`, `info`, `warn`, `error`) - -These environment variables take precedence over configuration file settings but are overridden by command line arguments. - -### Examples - -```bash -# Start with custom bind address and ports -export RUST_SOCKSD_BIND_ADDRESS="0.0.0.0" -export RUST_SOCKSD_SOCKS5_PORT="1081" -export RUST_SOCKSD_HTTP_PORT="8081" -rust-socksd --config config.yml - -# Start with debug logging -export RUST_SOCKSD_LOG_LEVEL="debug" -rust-socksd --config config.yml - -# Override specific settings via command line (takes highest precedence) -RUST_SOCKSD_BIND_ADDRESS="0.0.0.0" rust-socksd --socks5-port 1082 --config config.yml -``` - -## Docker Support - -rust-socksd provides official Docker support with multi-stage builds for optimal security and performance. - -### Quick Start with Docker - -#### Using Pre-built Image - -```bash -# Pull and run the latest image -docker run -d \ - --name rust-socksd \ - -p 1080:1080 \ - -p 8080:8080 \ - quintux/rust-socksd:latest -``` - -#### Building from Source - -```bash -# Build the Docker image -docker build -t rust-socksd . - -# Run the container -docker run -d \ - --name rust-socksd \ - -p 1080:1080 \ - -p 8080:8080 \ - rust-socksd -``` - -### Docker Configuration - -#### Using Environment Variables - -```bash -docker run -d \ - --name rust-socksd \ - -p 1080:1080 \ - -p 8080:8080 \ - -e RUST_SOCKSD_BIND_ADDRESS="0.0.0.0" \ - -e RUST_SOCKSD_SOCKS5_PORT="1080" \ - -e RUST_SOCKSD_HTTP_PORT="8080" \ - -e RUST_SOCKSD_LOG_LEVEL="info" \ - quintux/rust-socksd:latest -``` - -#### Using Custom Configuration Files - -```bash -# Create a directory for configuration files -mkdir -p ./config - -# Generate default configuration -docker run --rm -v ./config:/config quintux/rust-socksd:latest --generate-config /config/config.yml - -# Edit the configuration file -nano ./config/config.yml - -# Run with custom configuration -docker run -d \ - --name rust-socksd \ - -p 1080:1080 \ - -p 8080:8080 \ - -v ./config:/config \ - quintux/rust-socksd:latest --config /config/config.yml -``` - -#### Docker Compose - -```yaml -version: '3.8' - -services: - rust-socksd: - image: quintux/rust-socksd:latest - container_name: rust-socksd - ports: - - "1080:1080" # SOCKS5 port - - "8080:8080" # HTTP proxy port - environment: - - RUST_SOCKSD_BIND_ADDRESS=0.0.0.0 - - RUST_SOCKSD_LOG_LEVEL=info - volumes: - - ./config:/config # Optional: mount config directory - restart: unless-stopped - security_opt: - - no-new-privileges:true - user: "1001:1001" # Run as non-root user -``` - -### Docker Security Features - -The Docker image includes several security enhancements: - -- **Multi-stage Build**: Minimal runtime image with only necessary components -- **Non-root User**: Runs as user `appuser` (UID 1001) for security -- **Minimal Base**: Uses `debian:bullseye-slim` for reduced attack surface -- **No Privileges**: Container runs without additional privileges -- **Exposed Ports**: Only necessary ports (1080, 8080) are exposed - -## Systemd Service - -The package includes a systemd service file that provides: - -- Automatic startup on boot -- Proper user isolation (runs as `rust-socksd` user) -- Security hardening (restricted filesystem access, no new privileges) -- Service restart on failure -- Proper logging integration - -Service management: - -```bash -# Start the service -sudo systemctl start rust-socksd - -# Enable automatic startup -sudo systemctl enable rust-socksd - -# Check status -sudo systemctl status rust-socksd - -# View logs -sudo journalctl -u rust-socksd -f -``` - -## Building Packages - -### Debian Package - -```bash -# Install build dependencies -sudo apt-get install debhelper-compat cargo rustc - -# Build the package -dpkg-buildpackage -b -uc -us -``` - -### Arch Package - -```bash -# Build from AUR -git clone https://aur.archlinux.org/rust-socksd.git -cd rust-socksd -makepkg -si -``` +--- ## Performance -rust-socksd is designed for high performance: +`rust-socksd` is optimized for low-latency and high-throughput production usage: -- **Async Architecture**: Built on tokio for efficient I/O handling -- **Zero-copy Operations**: Minimal memory allocations during data transfer -- **Connection Pooling**: Efficient connection management -- **Configurable Limits**: Tunable for your specific use case +* **Async Architecture**: Built on the Tokio runtime for massive concurrent socket handling. +* **Zero-copy Relay**: Employs optimized I/O looping to minimize CPU overhead and buffer copying. +* **Minimal Footprint**: Operates with a base memory footprint under ~10MB under idle loads. +* **Scalable limits**: Supports over 1000+ simultaneous connections out-of-the-box. -Typical performance on modern hardware: +--- -- **Throughput**: 1000+ concurrent connections -- **Latency**: Sub-millisecond proxy overhead -- **Memory**: ~10MB base memory usage +## Build Features -## Security +The project supports optional compilation features: -Security features include: +* **`pam-auth`** (default): Enables Pluggable Authentication Modules support (requires `libpam` development headers). + * *Note for macOS*: This feature requires LLVM compiler headers (`brew install llvm`) for bindgen. If you experience build errors, build with `--no-default-features` to compile without PAM. -- **Network Restrictions**: Allow/deny lists for source networks -- **Domain Blocking**: Block access to specific domains -- **Authentication**: Secure username/password authentication -- **Rate Limiting**: Prevent abuse and DoS attacks -- **Service Isolation**: Runs with minimal privileges -- **Secure Defaults**: Conservative default configuration - -## Troubleshooting - -### Common Issues - -1. **Permission Denied**: Ensure the service user has access to configuration files -2. **Port Already in Use**: Check if another service is using the same ports -3. **Connection Refused**: Verify firewall settings and bind address -4. **Authentication Failures**: Check username/password configuration - -### Debugging - -Enable debug logging: - -```bash -rust-socksd --config config.yml --verbose -``` - -Or set in configuration: - -```yaml -logging: - level: "debug" -``` - -### Logs - -Check system logs: - -```bash -# Systemd service logs -sudo journalctl -u rust-socksd - -# Application logs (if file logging enabled) -sudo tail -f /var/log/rust-socksd/rust-socksd.log -``` - -## Administrative API - -`rust-socksd` includes a dedicated, secure HTTP administrative port for liveness probing, Prometheus metrics collection, config schema validation, and runtime hot reloads. - -### Configuration - -Add the `admin` block in your config: -```yaml -admin: - enabled: true - bind_address: "127.0.0.1" - port: 8081 - token: "my-secure-static-bypass-token" # optional pre-shared bearer token - admin_users: ["admin"] # users authorized to log in for dynamic tokens - token_ttl: 3600 # TTL for dynamic tokens -``` - -*You can also enable/configure the API using CLI flags `--admin-enabled` and `--admin-port `, or environment variables `RUST_SOCKSD_ADMIN_ENABLED=true` and `RUST_SOCKSD_ADMIN_PORT=8081`.* - -> **Security:** The admin API speaks plaintext HTTP. Bearer tokens and the -> Basic-auth credentials sent to `POST /login` are therefore not encrypted in -> transit. Keep `bind_address` on `127.0.0.1` (the default), or place the API -> behind a TLS-terminating reverse proxy before exposing it beyond localhost. - -### Main Endpoints - -- **`GET /health`**: Public endpoint returning `{ "status": "ok" }`. -- **`POST /login`**: Exchange Basic Auth credentials (checked against active authenticators) for a transient admin token. -- **`GET /metrics`**: Exports prometheus-compatible connection metrics, byte transfer counts, and auth failures. -- **`GET /config`**: Read the running configuration (sensitive passwords automatically masked). -- **`POST /config/validate`**: Validate a potential configuration body. -- **`POST /config/reload`**: Read configuration file on disk and hot reload (recreating upstreams, ACL rules, and authentication backends seamlessly). Note: Port changes require a full process restart. - -For details, payload formats, and curl command examples, see the [Admin API Reference Guide](file:///Users/quintus/.gemini/antigravity-cli/brain/4eb6d57b-32e4-420e-9a81-21613a19e2b5/admin_api_reference.md). - -## License - -This project is licensed under either of - -- MIT License ([LICENSE-MIT](LICENSE.MIT)) -- Apache License, Version 2.0 ([LICENSE.Apache-2.0](LICENSE.Apache-2.0)) - -at your option. - -`SPDX-License-Identifier: MIT OR Apache-2.0` - - -### Build Features - -The project supports the following Cargo features: - -- **pam-auth** (default): Enables PAM authentication backend. Requires `libpam` development headers. - - *Note for macOS*: This feature may require `llvm` to be installed (`brew install llvm`) for `bindgen`. If you encounter build errors, you can disable this feature. - -To build without PAM support: +To compile without PAM support: ```bash cargo build --release --no-default-features ``` -Contributions are welcome! Please feel free to submit a Pull Request. +--- -## Support +## License -For issues, questions, or feature requests, please visit our [GitHub Issues](https://github.com/quintusl/rust-socksd/issues) page. +This project is licensed under either of: +* MIT License ([LICENSE-MIT](LICENSE.MIT)) +* Apache License, Version 2.0 ([LICENSE-Apache-2.0](LICENSE.Apache-2.0)) + +at your option. + +`SPDX-License-Identifier: MIT OR Apache-2.0` diff --git a/doc/admin_api.md b/doc/admin_api.md new file mode 100644 index 0000000..baf7d61 --- /dev/null +++ b/doc/admin_api.md @@ -0,0 +1,208 @@ +# Admin API Reference Guide + +The administrative server allows monitoring the proxy server status, validating and reloading configurations at runtime, and inspecting execution metrics. + +## Configuration + +To enable the admin server, append an `admin` section to your main `config.yml` configuration file: + +```yaml +admin: + # Enable/disable the admin API listener (default: false) + enabled: true + + # Address to bind the listener to (default: 127.0.0.1) + bind_address: "127.0.0.1" + + # Port to listen on (default: 8081) + port: 8081 + + # Static pre-shared token (Optional) + # If configured, clients can bypass login and authenticate directly + token: "my-secure-static-bypass-token" + + # List of usernames permitted to log in and receive transient tokens + admin_users: + - "admin" + + # Lifespan of transient dynamic tokens in seconds (default: 3600) + token_ttl: 3600 +``` + +--- + +## Authentication Schemes + +The Admin API supports two primary authentication modes for all administrative endpoints (except `/health`): + +### 1. Static Token Authentication +Use the token configured via `admin.token` as a direct Bearer header: +```bash +Authorization: Bearer my-secure-static-bypass-token +``` + +### 2. Dynamic Token Authentication +If a static token is not preferred, exchange credentials for a temporary session token using Basic Authentication: +1. Call `/login` using the credentials of a user defined in your active authenticator backend (e.g. `users.yml`, LDAP, Database) who is listed in the config's `admin.admin_users`. +2. Extract the returned `token` from the response. +3. Attach it to administrative calls: + ```bash + Authorization: Bearer + ``` + +--- + +## Endpoints + +### 1. Liveness & Health Check +Checks if the admin server is up. This endpoint is **public** and does not require authentication headers. + +* **Path:** `GET /health` +* **Response Status:** `200 OK` +* **Response Body:** + ```json + { + "status": "ok" + } + ``` +* **Example Request:** + ```bash + curl http://127.0.0.1:8081/health + ``` + +--- + +### 2. User Authentication / Login +Exchanges user credentials for a dynamic bearer token. + +* **Path:** `POST /login` +* **Authentication:** HTTP Basic Auth (username/password) +* **Response Status:** `200 OK` on success, `401 Unauthorized` on bad credentials, `403 Forbidden` if the user is authenticated but not configured under `admin_users`. +* **Response Body:** + ```json + { + "token": "QWVyV1p2T2x3NmRl...", + "expires_in": 3600 + } + ``` +* **Example Request:** + ```bash + curl -X POST -u "admin:secretpassword" http://127.0.0.1:8081/login + ``` + +--- + +### 3. Metrics Export +Provides execution counters and gauges in Prometheus-compatible exposition format. + +* **Path:** `GET /metrics` +* **Authentication:** Bearer token +* **Response Status:** `200 OK` +* **Response Body:** + ```prometheus + # HELP rust_socksd_active_connections Number of active connections + # TYPE rust_socksd_active_connections gauge + rust_socksd_active_connections 2 + # HELP rust_socksd_total_connections Total connections accepted + # TYPE rust_socksd_total_connections counter + rust_socksd_total_connections 14 + # HELP rust_socksd_bytes_tx Total bytes transmitted (client to target) + # TYPE rust_socksd_bytes_tx counter + rust_socksd_bytes_tx 819240 + # HELP rust_socksd_bytes_rx Total bytes received (target to client) + # TYPE rust_socksd_bytes_rx counter + rust_socksd_bytes_rx 1902488 + # HELP rust_socksd_auth_failures Total authentication failures + # TYPE rust_socksd_auth_failures counter + rust_socksd_auth_failures 1 + ``` +* **Example Request:** + ```bash + curl -H "Authorization: Bearer QWVyV1p2T2x3NmRl..." http://127.0.0.1:8081/metrics + ``` + +--- + +### 4. Configuration Inspect +Returns the active configuration schema. Sensitive values (like passwords, keys, and URL credentials) are automatically masked to `******`. + +* **Path:** `GET /config` +* **Authentication:** Bearer token +* **Response Status:** `200 OK` +* **Response Body:** + ```json + { + "server": { + "bind_address": "127.0.0.1", + "socks5_port": 1080, + "http_port": 8080, + "max_connections": 1000, + "connection_timeout": 300, + "buffer_size": 65536 + }, + "auth": { + "enabled": true, + "backend": { + "type": "simple", + "user_config_file": "config/users.yml" + } + }, + ... + } + ``` +* **Example Request:** + ```bash + curl -H "Authorization: Bearer QWVyV1p2T2x3NmRl..." http://127.0.0.1:8081/config + ``` + +--- + +### 5. Configuration Validation +Validates a potential configuration without applying it. + +* **Path:** `POST /config/validate` +* **Authentication:** Bearer token +* **Request Body:** Configuration YAML string +* **Response Status:** `200 OK` (if valid), `400 Bad Request` (if validation rules or parsing failed) +* **Response Body (Valid):** + ```json + { + "valid": true + } + ``` +* **Response Body (Invalid):** + ```json + { + "valid": false, + "error": "SOCKS5 and HTTP ports cannot be the same" + } + ``` +* **Example Request:** + ```bash + curl -H "Authorization: Bearer QWVyV1p2T2x3NmRl..." \ + -H "Content-Type: application/yaml" \ + --data-binary @config.yml \ + http://127.0.0.1:8081/config/validate + ``` + +--- + +### 6. Live Configuration Reload +Triggers the server to re-read its main configuration file from disk. Swaps out the routing, rules, and authenticators seamlessly. + +* **Path:** `POST /config/reload` +* **Authentication:** Bearer token +* **Response Status:** `200 OK` on success, `400 Bad Request` or `500 Internal Error` on failure (e.g. invalid syntax, file missing, or unsupported port updates). +* **Response Body (Success):** + ```json + { + "status": "reloaded" + } + ``` +* **Example Request:** + ```bash + curl -X POST -H "Authorization: Bearer QWVyV1p2T2x3NmRl..." http://127.0.0.1:8081/config/reload + ``` + +> [!IMPORTANT] +> To ensure continuous operation, you **cannot** update bind addresses or ports (for SOCKS5, HTTP, or Admin listeners) at runtime via a reload command. Attempting to change bind targets will abort the reload operation with a validation error, requesting a service restart instead. diff --git a/doc/authentication.md b/doc/authentication.md new file mode 100644 index 0000000..11fbe5a --- /dev/null +++ b/doc/authentication.md @@ -0,0 +1,134 @@ +# Authentication Backends + +`rust-socksd` supports multiple authentication backends to secure your SOCKS5 and HTTP proxy endpoints. When authentication is enabled globally (`auth.enabled: true`), SOCKS5 requests require username/password authentication, and HTTP requests require HTTP Basic Authentication (via the `Proxy-Authorization` header). + +--- + +## 1. Simple (File-based) Backend + +This backend stores credentials in a local YAML configuration file. Passwords are securely hashed using Argon2, Bcrypt, or Scrypt. + +### Configuration + +```yaml +auth: + enabled: true + type: simple + user_config_file: "config/users.yml" +``` + +### CLI User Management + +You can manage this file dynamically using the `user` subcommand. + +#### Initialize User Configuration + +Create a new, empty user database file with a default hashing algorithm: + +```bash +rust-socksd user --user-config config/users.yml init --hash-type argon2 +``` + +*Options for `--hash-type`: `argon2` (default), `bcrypt`, `scrypt`* + +#### Add a New User + +Add a user. You will be prompted for a password if you do not specify it on the command line: + +```bash +rust-socksd user --user-config config/users.yml add myuser +``` + +*Specify custom hash type per user:* +```bash +rust-socksd user --user-config config/users.yml add myuser --hash-type bcrypt +``` + +#### List Configured Users + +List all users, their status (enabled/disabled), creation time, and last modified time: + +```bash +rust-socksd user --user-config config/users.yml list +``` + +#### Update Password + +```bash +rust-socksd user --user-config config/users.yml update myuser +``` + +#### Enable / Disable a User + +```bash +# Disable a user +rust-socksd user --user-config config/users.yml enable myuser false + +# Enable a user +rust-socksd user --user-config config/users.yml enable myuser true +``` + +#### Remove a User + +```bash +rust-socksd user --user-config config/users.yml remove myuser +``` + +--- + +## 2. PAM Backend + +Integrates authentication with the Linux Pluggable Authentication Modules (PAM) subsystem. This allows proxying to authenticate using local system user accounts. + +> [!NOTE] +> Requires building `rust-socksd` with the `pam-auth` feature (enabled by default on Linux). The server process must also run with sufficient privileges (e.g., as `root`) or belong to the `shadow` group to read system user credentials. + +### Configuration + +```yaml +auth: + enabled: true + type: pam + service: "socksd" # Refers to config file in /etc/pam.d/socksd +``` + +--- + +## 3. LDAP Backend + +Authenticates users against an LDAP directory server (such as Active Directory or OpenLDAP). + +### Configuration + +```yaml +auth: + enabled: true + type: ldap + url: "ldap://ldap.example.com:389" + base_dn: "ou=users,dc=example,dc=com" + # Optional: DN and password used to search for user entries (if anonymous binds are disabled) + bind_dn: "cn=admin,dc=example,dc=com" + bind_password: "admin_password" + # User search query filter. '{}' is replaced by the logging-in username. + user_filter: "(uid={})" +``` + +--- + +## 4. Database (SQL) Backend + +Authenticates users by querying a database and verifying the password hash against secure algorithms. Supports MySQL/MariaDB and PostgreSQL. + +### Configuration + +```yaml +auth: + enabled: true + type: database + db_type: "mysql" # or "postgres" + url: "mysql://socksd_user:secret@localhost/socksd_db" + # Query must return a single column containing the password hash + query: "SELECT password_hash FROM users WHERE username = ?" + # Hashing algorithm used in the database: argon2, bcrypt, or scrypt + hash_type: "argon2" +``` diff --git a/doc/configuration.md b/doc/configuration.md new file mode 100644 index 0000000..60f38f5 --- /dev/null +++ b/doc/configuration.md @@ -0,0 +1,163 @@ +# Configuration Guide + +The `rust-socksd` proxy server is configured using a YAML file. + +## Generation + +You can generate a default configuration file with default values: + +```bash +rust-socksd --generate-config config.yml +``` + +--- + +## Configuration Sections + +A complete configuration file comprises the following main sections: + +### 1. Basic Server Settings (`server`) + +Controls ports, timeouts, limits, and buffer sizes. + +```yaml +server: + # Bind address for all listeners (default: 127.0.0.1) + bind_address: "127.0.0.1" + + # Port for the SOCKS5 proxy (default: 1080) + socks5_port: 1080 + + # Port for the HTTP proxy (default: 8080) + http_port: 8080 + + # Global limit on concurrent client connections (default: 1000) + max_connections: 1000 + + # Timeout in seconds for client connections (default: 300) + connection_timeout: 300 + + # Buffer size in bytes for read/write streams (default: 65536) + buffer_size: 65536 +``` + +--- + +### 2. Logging Settings (`logging`) + +Controls log filtering and output targets (console, file, and systemd journald). + +```yaml +logging: + # Log filter level: trace, debug, info, warn, error (default: info) + level: "info" + + # Enable logging stdout/stderr to console (default: true) + console: true + + # Path to log file (optional; e.g. "/var/log/rust-socksd/rust-socksd.log") + file: null + + # Enable native logging to systemd journald (default: false) + journald: false +``` + +--- + +### 3. Security & Access Control (`security`) + +Enforces source restrictions, destination filtering, and rate limiting. + +```yaml +security: + # Ingress source IPs/CIDR blocks allowed to connect (default: ["0.0.0.0/0"]) + # An empty list rejects all connections. Note: '0.0.0.0/0' is IPv4 only. + allowed_networks: + - "192.168.1.0/24" + - "10.0.0.0/8" + + # Hostnames or subdomain suffixes to block (exact or suffix match) + blocked_domains: + - "malicious-site.com" + - "blocked-domain.net" + + # Egress destination networks allowed (optional) + # If specified, connections to targets outside these networks will be blocked. + allowed_egress_networks: + - "8.8.8.8" + - "8.8.4.4" + + # Egress destination networks to block (optional) + blocked_egress_networks: + - "127.0.0.0/8" + - "10.0.0.0/8" + + # Maximum allowed request size in bytes (default: 1048576 [1MB]) + max_request_size: 1048576 + + # Rate limiting configurations (optional token-bucket scheme) + rate_limit: + requests_per_minute: 1000 + burst_size: 100 +``` + +#### Enforcement Behavior: +- **`allowed_networks`**: Checked against client's IP upon handshake. An empty list rejects all. To allow all IP versions, include `0.0.0.0/0` and `::/0`. +- **`blocked_domains`**: Checks hostnames in proxy requests. If a requested domain matches or ends with an entry (e.g. `evil.com` will also block `sub.evil.com`), the proxy request is denied. +- **`rate_limit`**: Uses a per-source-IP token bucket refilled at the configured `requests_per_minute` rate with the defined `burst_size` capacity. +- **Egress Filtering**: Target IP resolution happens before connecting. Egress rules validate the resolved IP. If a destination violates the egress policies, the connection is blocked with a protocol-specific error. + +--- + +### 4. Upstream Proxy Configuration (`upstream`) + +Chain outgoing client traffic through an external proxy. + +```yaml +upstream: + # Enable proxy chaining (default: false) + enabled: true + + # Upstream protocol: 'socks5' or 'http' + protocol: socks5 + + # Address of the upstream proxy + address: "127.0.0.1" + + # Port of the upstream proxy + port: 1080 + + # Credentials for upstream authentication (optional basic auth) + username: "proxy_user" + password: "proxy_password" + + # Networks to exclude from upstream routing (bypass rules) + exclude_networks: + - "127.0.0.1/8" + - "10.0.0.0/8" + + # Domains to exclude from upstream routing (bypass rules) + exclude_domains: + - "localhost" + - "local.lan" + + # Precedence check: prioritize standard environment variables (default: true) + prefer_env: true +``` + +#### Upstream Routing Logic: +- If `prefer_env` is `true`, standard proxy environment variables take precedence over the YAML configurations. +- Wildcards `*` in the exclusion networks/domains (or `NO_PROXY` environment variable) will bypass the upstream proxy for all requests. + +--- + +## Environment Variable Overrides + +Any command line execution of `rust-socksd` will check for specific environment variables. These take precedence over YAML configuration values, but are overridden by direct CLI options: + +* **`RUST_SOCKSD_BIND_ADDRESS`**: Override the bind address (e.g., `0.0.0.0`) +* **`RUST_SOCKSD_SOCKS5_PORT`**: Override the SOCKS5 port (e.g., `1081`) +* **`RUST_SOCKSD_HTTP_PORT`**: Override the HTTP proxy port (e.g., `8081`) +* **`RUST_SOCKSD_LOG_LEVEL`**: Override the log level (`trace`, `debug`, `info`, `warn`, `error`) +* **`RUST_SOCKSD_ADMIN_PORT`**: Override the Admin API port (e.g., `8082`) +* **`RUST_SOCKSD_ADMIN_ENABLED`**: Override whether the Admin API is enabled (`true`/`false`) diff --git a/doc/deployment.md b/doc/deployment.md new file mode 100644 index 0000000..8bfedcc --- /dev/null +++ b/doc/deployment.md @@ -0,0 +1,91 @@ +# Deployment & Packaging Guide + +This guide describes how to deploy `rust-socksd` in production environments, run it as a systemd service, and package it for Debian and Arch Linux systems. + +--- + +## Systemd Service + +When installed via package managers, a systemd service file is registered. It provides daemon management, automatic crash restarts, journald log routing, and security sandbox features. + +### Security Hardening in Systemd + +The service file includes: +* **User Isolation**: Runs under a dedicated unprivileged user account `rust-socksd`. +* **Privilege Restrictions**: Disallows new privilege flags (`NoNewPrivileges=yes`). +* **Sandbox Protections**: Read-only access to most of the filesystem, restricted `/tmp` (`PrivateTmp=yes`), and limited device access. + +### Service Commands + +Use standard `systemctl` commands to manage the daemon: + +```bash +# Enable the service to launch on boot +sudo systemctl enable rust-socksd + +# Start the proxy server immediately +sudo systemctl start rust-socksd + +# Restart the service (required after changing bind ports) +sudo systemctl restart rust-socksd + +# Check runtime status +sudo systemctl status rust-socksd +``` + +### Accessing Service Logs + +Logs are routed directly to systemd's journal. View them with `journalctl`: + +```bash +# Stream live logs +sudo journalctl -u rust-socksd -f + +# Filter logs by priority (e.g. warnings and errors) +sudo journalctl -u rust-socksd -p err..warn +``` + +--- + +## Building Debian Packages + +You can build a native Debian `.deb` package to deploy onto Debian/Ubuntu machines. + +### Build Dependencies + +Install required build utilities and libraries: + +```bash +sudo apt-get update +sudo apt-get install debhelper-compat cargo rustc libpam0g-dev +``` + +### Packaging Command + +Run the package build tools from the project root directory: + +```bash +# Build the binary and bundle it into a deb package +dpkg-buildpackage -b -uc -us +``` + +This generates a `.deb` package in the parent directory, which you can install via `dpkg -i`. + +--- + +## Arch Linux Package (AUR) + +For Arch Linux, `rust-socksd` is available in the Arch User Repository (AUR). + +### Manual Build + +To compile and package manually using `PKGBUILD`: + +```bash +# Clone the AUR repository +git clone https://aur.archlinux.org/rust-socksd.git +cd rust-socksd + +# Build and install the package with dependencies +makepkg -si +``` diff --git a/doc/docker.md b/doc/docker.md new file mode 100644 index 0000000..b85fe8d --- /dev/null +++ b/doc/docker.md @@ -0,0 +1,115 @@ +# Docker & Containerization + +`rust-socksd` includes support for containerized deployment with multi-stage builds. + +--- + +## Quick Start + +### Using the Pre-built Image + +Run the server out-of-the-box using the latest image: + +```bash +docker run -d \ + --name rust-socksd \ + -p 1080:1080 \ + -p 8080:8080 \ + quintux/rust-socksd:latest +``` + +### Building From Source + +You can build the Docker image locally from the project root: + +```bash +# Build the Docker image +docker build -t rust-socksd . + +# Run the container +docker run -d \ + --name rust-socksd \ + -p 1080:1080 \ + -p 8080:8080 \ + rust-socksd +``` + +--- + +## Configuration in Docker + +### 1. Using Environment Variables + +For simple configurations, pass environment variables directly: + +```bash +docker run -d \ + --name rust-socksd \ + -p 1080:1080 \ + -p 8080:8080 \ + -e RUST_SOCKSD_BIND_ADDRESS="0.0.0.0" \ + -e RUST_SOCKSD_SOCKS5_PORT="1080" \ + -e RUST_SOCKSD_HTTP_PORT="8080" \ + -e RUST_SOCKSD_LOG_LEVEL="info" \ + quintux/rust-socksd:latest +``` + +### 2. Using Custom Config Files + +Mount a host directory containing configurations to load custom settings dynamically: + +```bash +# Create local configuration directory +mkdir -p ./config + +# Generate default configuration inside the mounted directory +docker run --rm -v ./config:/config quintux/rust-socksd:latest --generate-config /config/config.yml + +# Edit the config.yml as needed (e.g. enabling auth or egress rules) +# Then start the container referencing the configuration file +docker run -d \ + --name rust-socksd \ + -p 1080:1080 \ + -p 8080:8080 \ + -v ./config:/config \ + quintux/rust-socksd:latest --config /config/config.yml +``` + +--- + +## Docker Compose + +Save the following content to a `docker-compose.yml` file to orchestrate the service: + +```yaml +version: '3.8' + +services: + rust-socksd: + image: quintux/rust-socksd:latest + container_name: rust-socksd + ports: + - "1080:1080" # SOCKS5 port + - "8080:8080" # HTTP proxy port + - "8081:8081" # Admin port (Optional, expose only if needed) + environment: + - RUST_SOCKSD_BIND_ADDRESS=0.0.0.0 + - RUST_SOCKSD_LOG_LEVEL=info + volumes: + - ./config:/config # Mount config directory + restart: unless-stopped + security_opt: + - no-new-privileges:true + user: "1001:1001" # Run as non-root user +``` + +--- + +## Image Security Hardening + +The official `rust-socksd` image utilizes container security best practices: + +* **Multi-stage Build**: Eliminates build-time dependencies, compiler toolchains, and source code, resulting in a minimal runtime package. +* **Non-root Execution**: Runs as an isolated unprivileged user `appuser` (UID `1001` / GID `1001`). +* **Minimal Base OS**: Uses `debian:bullseye-slim` for a minimal attack surface. +* **No Privilege Escalation**: Configured to deny requests for new privileges (`no-new-privileges:true`). diff --git a/doc/quickstart.md b/doc/quickstart.md new file mode 100644 index 0000000..54b4a21 --- /dev/null +++ b/doc/quickstart.md @@ -0,0 +1,93 @@ +# Quick Start Guide + +This guide will help you install and run `rust-socksd` on various platforms. + +## Installation + +### From Source + +Ensure you have Rust and Cargo installed. Then run: + +```bash +git clone https://github.com/quintusl/rust-socksd.git +cd rust-socksd +cargo build --release +sudo cp target/release/rust-socksd /usr/local/bin/ +``` + +By default, this builds with PAM authentication support (which requires PAM development headers). If you are building on a platform without PAM development headers (like macOS) or want a minimal build, you can disable default features: + +```bash +cargo build --release --no-default-features +``` + +### Debian/Ubuntu + +You can install `rust-socksd` from a pre-built `.deb` package: + +```bash +sudo dpkg -i rust-socksd_0.1.1-1_amd64.deb +``` + +### Arch Linux + +Install from the AUR using your favorite helper (e.g., `yay`): + +```bash +yay -S rust-socksd +``` + +### Docker + +To pull and run the latest official image: + +```bash +docker run -d \ + --name rust-socksd \ + -p 1080:1080 \ + -p 8080:8080 \ + quintux/rust-socksd:latest +``` + +--- + +## Running the Server + +### Direct Execution + +To run the server with a custom configuration file: + +```bash +rust-socksd --config config.yml +``` + +### Systemd Service + +If installed via package managers, you can manage the proxy server as a systemd service: + +```bash +sudo systemctl enable rust-socksd +sudo systemctl start rust-socksd +``` + +For more deployment details, see [Deployment & Packaging Guide](deployment.md). + +--- + +## Verifying Connections + +You can verify that both the SOCKS5 and HTTP proxies are working by using `curl`. + +### SOCKS5 Proxy +Assuming the SOCKS5 proxy is running on port `1080`: + +```bash +curl --socks5-hostname localhost:1080 https://httpbin.org/ip +``` + +### HTTP Proxy +Assuming the HTTP proxy is running on port `8080`: + +```bash +curl --proxy localhost:8080 https://httpbin.org/ip +``` diff --git a/doc/troubleshooting.md b/doc/troubleshooting.md new file mode 100644 index 0000000..a5c4827 --- /dev/null +++ b/doc/troubleshooting.md @@ -0,0 +1,106 @@ +# Troubleshooting Guide + +This guide helps resolve common issues encountered while deploying or running `rust-socksd`. + +--- + +## Common Issues + +### 1. Permission Denied + +* **Symptoms**: The server crashes on startup with a filesystem read or write error, or fails to load `users.yml` or `config.yml`. +* **Causes**: The dedicated service user (e.g., `rust-socksd` or Docker's `appuser`) does not have read permissions for the configuration files or write permissions for the log directories. +* **Solutions**: + - Grant read permissions on configuration files to the running user: + ```bash + sudo chown -R rust-socksd:rust-socksd /etc/rust-socksd + sudo chmod 640 /etc/rust-socksd/config.yml + ``` + - For Docker, ensure the mounted directory has the correct user ownership matching UID/GID `1001`. + +### 2. Port Already in Use + +* **Symptoms**: Startup failure with: `Address already in use` (OS Error 98 or 48). +* **Causes**: Another service (or an existing instance of `rust-socksd`) is already bound to the requested port (SOCKS5 `1080`, HTTP `8080`, or Admin `8081`). +* **Solutions**: + - Identify the process utilizing the port: + ```bash + # Linux + sudo ss -lntp | grep -E '1080|8080|8081' + # macOS + sudo lsof -i -P -n | grep -E '1080|8080|8081' + ``` + - Change the ports in `config.yml` or supply port override flags (e.g. `--socks5-port 1082`). + +### 3. Connection Refused + +* **Symptoms**: Clients cannot connect to the proxy and report "Connection Refused". +* **Causes**: + - The proxy is configured to bind to `127.0.0.1` and the client is attempting to connect from a different network interface. + - A local firewall (like `ufw`, `iptables`, or macOS Application Firewall) is blocking the ports. +* **Solutions**: + - Set `server.bind_address` to `0.0.0.0` in `config.yml` to listen on all interfaces. + - Allow proxy ports through your firewall: + ```bash + # UFW (Ubuntu/Debian) + sudo ufw allow 1080/tcp + sudo ufw allow 8080/tcp + ``` + +### 4. Authentication Failures + +* **Symptoms**: Client requests fail with `407 Proxy Authentication Required` (HTTP) or connection close (SOCKS5). +* **Causes**: + - Password hashes mismatch. + - Configuration file path for `user_config_file` is incorrect or unreadable. + - External auth backends (LDAP, Database) are unreachable or search queries are invalid. +* **Solutions**: + - For the `simple` backend, check user lists: + ```bash + rust-socksd user --user-config users.yml list + ``` + - For LDAP or DB backends, inspect the database logs or verify query logic against the schema (e.g., column names and parameter placeholders `?` vs `$1` depending on db type). + +--- + +## Debugging + +Enable verbose debug or trace logging to see detailed logs of connection processing: + +### Via Command Line + +Pass the `-v` (debug) or `-vv` (trace) verbose flags: + +```bash +rust-socksd --config config.yml -v +``` + +### Via Configuration + +Update the `logging` block in `config.yml`: + +```yaml +logging: + level: "debug" # or "trace" + console: true +``` + +--- + +## Log Inspection + +### Systemd Service + +For systemd daemon deployments, stream live service logs: + +```bash +sudo journalctl -u rust-socksd -f +``` + +### Log File + +If file logging is configured, tail the log file: + +```bash +tail -f /var/log/rust-socksd/rust-socksd.log +``` diff --git a/doc/usage.md b/doc/usage.md new file mode 100644 index 0000000..6e17370 --- /dev/null +++ b/doc/usage.md @@ -0,0 +1,109 @@ +# CLI & Usage Guide + +This guide details the command-line options available for `rust-socksd` and instructions on configuring proxy client applications. + +--- + +## Command Line Interface (CLI) + +### Main Server Entry + +Run `rust-socksd` using standard flags to start the daemon. + +```bash +rust-socksd [OPTIONS] [SUBCOMMAND] +``` + +#### Global Options + +* **`-c, --config `**: Path to the YAML configuration file (default: `config.yml`). +* **`-g, --generate-config `**: Generates a default YAML configuration file and exits (conflicts with `--config`). +* **`-v, --verbose`**: Enables verbose logging (can be specified multiple times for deeper trace levels). +* **`-q, --quiet`**: Suppresses all standard output logs except errors. +* **`-b, --bind
`**: Binds the proxy listeners to the specified IP address. +* **`-p, --http-port `**: Port for the HTTP proxy. +* **`-s, --socks5-port `**: Port for the SOCKS5 proxy. +* **`-l, --loglevel `**: Logging filter level: `trace`, `debug`, `info`, `warn`, `error`. +* **`--admin-port `**: Port for the administrative API listener. +* **`--admin-enabled`**: Enables the admin server listener at boot time. +* **`-h, --help`**: Prints CLI help and usage details. +* **`-V, --version`**: Prints application version information. + +#### Subcommands +* **`validate`**: Validates the syntax of configuration files. +* **`user`**: Manages credentials database for Simple authentication backend. + +--- + +### Configuration Validation Subcommand + +Validate your main configuration or user configuration syntax before launching the server: + +```bash +rust-socksd validate [OPTIONS] +``` + +#### Subcommand Options +* **`-c, --config `**: Main config file to validate (default: `config.yml`). +* **`--user-config `**: Simple backend user file to validate (optional). + +#### Examples +```bash +# Validate default config.yml +rust-socksd validate + +# Validate specific configurations +rust-socksd validate --config /etc/socksd/config.yml --user-config /etc/socksd/users.yml +``` + +--- + +### User Management Subcommand + +Manages user credentials for the `simple` authenticator backend file. See [Authentication Backends Guide](authentication.md) for details. + +```bash +rust-socksd user [OPTIONS] [SUBCOMMAND_ARGS] +``` + +--- + +## Client Proxy Usage + +Once `rust-socksd` is running, configure client applications to route traffic through it. + +### SOCKS5 Client Setup + +The SOCKS5 proxy implements the standard SOCKS5 protocol (RFC 1928), supporting username/password auth (RFC 1929). + +* **Protocol**: SOCKS5 (or SOCKS5h to resolve DNS names remotely on the proxy side) +* **Default Port**: `1080` + +#### curl Example (Unauthenticated) +```bash +curl --socks5-hostname localhost:1080 https://httpbin.org/ip +``` + +#### curl Example (With Credentials) +```bash +curl --socks5-hostname localhost:1080 --user "username:password" https://httpbin.org/ip +``` + +--- + +### HTTP Client Setup + +The HTTP proxy supports HTTP/HTTPS tunnel connections via the `CONNECT` method and regular proxy requests, optionally requiring Basic Authentication. + +* **Protocol**: HTTP / HTTPS +* **Default Port**: `8080` + +#### curl Example (Unauthenticated) +```bash +curl --proxy localhost:8080 https://httpbin.org/ip +``` + +#### curl Example (With Credentials) +```bash +curl --proxy localhost:8080 --proxy-user "username:password" https://httpbin.org/ip +```