Skip to content

About

Experimenting with Gemini: Implementation of erebe/wstunnel in Go

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

wstunnel-go

A feature-complete Go implementation of wstunnel, designed for high performance, ease of use, and library integration.

wstunnel-go allows you to tunnel any traffic through a WebSocket or HTTP/2 connection, effectively bypassing restrictive firewalls and proxies that only allow HTTP/HTTPS traffic.

Features

  • Protocol Support:
    • TCP: Reliable stream tunneling.
    • UDP: Datagram tunneling with state tracking.
    • SOCKS5: Local SOCKS5 proxy (with optional authentication), supporting CONNECT and UDP ASSOCIATE. UDP is relayed through a UDP socket at the listener's address, one tunnel per pair of sender and destination, and ends after timeout_sec of silence (30 seconds by default, 0 for never).
    • HTTP Proxy: Local HTTP CONNECT proxy (with optional authentication).
    • Unix Domain Sockets: Tunneling to/from local unix sockets.
    • Stdio: Tunneling via standard input/output.
  • TProxy Support: Transparent proxying for TCP and UDP on Linux (requires root/CAP_NET_ADMIN).
  • Tun mode (Go-only, Linux client): Route whole subnets through the server with a TUN device: -L 'tun://wst0?route=10.0.0.0/8' on the client, --enable-tun on the server. The server forwards each TCP/UDP flow to the real network through a userspace TCP/IP stack. With route=default (-L 'tun://wst0?route=default') the whole host's IPv4 and IPv6 traffic goes through the tunnel. See docs/TUN.md.
  • Reverse Tunneling: Stable support for static reverse TCP, reverse UDP, reverse SOCKS5, reverse HTTP proxy and reverse Unix socket tunnels (server-to-client). A reverse UDP tunnel keeps one client connection per peer address and ends a peer after timeout_sec of silence (30 seconds by default, 0 for never). A reverse SOCKS5 tunnel (-R socks5://[bind:]port, optional ?login=&password=) runs the SOCKS5 listener on the server and connects out from the client, supporting CONNECT and UDP ASSOCIATE. A reverse HTTP proxy tunnel (-R http://[bind:]port, optional ?login=&password=) does the same for an HTTP proxy: CONNECT requests, and plain requests with an absolute URL that are replayed to the target as they came. A reverse listener keeps the settings it was started with; a client that returns with other credentials or timeouts replaces an idle listener, and is refused while visitors are being served.
  • Transports:
    • WebSocket-like transport: Secure WebSocket-style transport (default) with intentional RFC 6455 deviations for compatibility with the original Rust implementation.
    • RFC 6455 compliant WebSocket: Enable strict RFC 6455 compliance with --mode ws (compatible with standard Go clients).
    • HTTP/2: Full-duplex streaming over HTTP/2.
  • Deployment:
    • Systemd: Ready-to-use systemd unit templates for Linux.
    • Windows Task Scheduler: PowerShell scripts for easy deployment as a background task on Windows.
    • Docker: (Coming soon) Ready-to-use Docker images.
  • Security:
    • TLS (wss://, https://): Full TLS support with certificate verification.
    • mTLS: Support for client certificates and private keys.
    • ECH (Encrypted Client Hello): Enable ECH for enhanced privacy.
    • SNI Control: Override or disable Server Name Indication.
    • JWT Authentication: Fully compatible with the original Rust implementation's JWT-based auth.
    • Restriction Rules: Server-side YAML configuration to restrict allowed tunnel destinations and path prefixes.
  • Advanced Networking:
    • SO_MARK: (Linux only) Support for marking outgoing packets.
    • DNS Control: Custom DNS resolvers and IPv4/IPv6 preference.
    • Proxy Support: Connect through HTTP/HTTPS proxies (with authentication).
    • Proxy Protocol: Support for Proxy Protocol (v1/v2) to preserve client IP.
  • Modern Architecture:
    • Highly Concurrent: Leverages Go's goroutines for efficient handling of many simultaneous tunnels.
    • Structured Logging: Uses log/slog for modern, structured logging.
    • Library First: Designed as a library for easy integration into other Go projects.
  • Interoperability: Maintains full protocol compatibility and CLI parity with the original Rust implementation.

Installation

Prerequisites

  • Go version 1.27.2 or above.
  • make (optional, for convenient building).

Build from Source

git clone https://github.com/kad/wstunnel-go.git
cd wstunnel-go
make build
# Binary will be available in ./bin/wstunnel-go

Alternatively, using standard Go commands:

go build -o wstunnel-go ./cmd/wstunnel-go

Download Pre-built Binaries and Packages

Binaries for various platforms (Linux, macOS, Windows) and distribution packages (.deb, .rpm, .apk) are available on the Releases page.

Installation via Package Manager (Linux)

For Debian/Ubuntu-based systems:

sudo dpkg -i wstunnel-go_amd64.deb

Systemd Integration (Linux)

wstunnel-go provides systemd template units for easy management of client and server instances.

  1. Place your configuration YAML file in /etc/wstunnel-go/client-myserver.yaml.
  2. Enable and start the service:
    sudo systemctl enable --now wstunnel-go-client@myserver

For the server:

  1. Place your configuration YAML file in /etc/wstunnel-go/server-main.yaml.
  2. Enable and start the service:
    sudo systemctl enable --now wstunnel-go-server@main

For a tun (packet tunnel) client or server, including a systemd unit that grants CAP_NET_ADMIN to the client and the Caddy variants, see Deployment in docs/TUN.md. That section also has the full-tunnel variants (route=default): one command line, the same tunnel from a YAML file, and the systemd unit. The routing and the socket mark need CAP_NET_ADMIN and nothing else; dns= runs resolvectl, whose permission under that capability alone depends on your systemd/polkit setup (see the TUN.md notes).

Windows Task Scheduler Integration

Use the provided PowerShell scripts in the packaging/windows directory to register wstunnel-go as a background task.

# In an elevated PowerShell session:
.\packaging\windows\install.ps1 -ConfigPath "C:\path\to\your\client.yaml" -BinaryPath "C:\path\to\wstunnel-go.exe"

# Control the task:
.\packaging\windows\control.ps1 -Action start

Caddy Integration (Server)

wstunnel-go can be built into Caddy as an HTTP handler. It serves the WebSocket (mode rust and mode ws) and HTTP/2 transports, including tun sessions; WebTransport is not served through Caddy.

The Caddy module is released separately with matching Go module tags: v0.0.4 for the root module and pkg/caddy/v0.0.4 for Caddy. Maintainers can prepare both annotated tags locally with:

make tag VERSION=0.0.4
git push --atomic origin refs/tags/v0.0.4 refs/tags/pkg/caddy/v0.0.4

VERSION accepts stable v0/v1 versions, with or without the leading v. For a new release, both tags point to HEAD. To backfill a missing Caddy tag, run the same command with an existing root release version: it uses that release's commit, even if HEAD has moved on. Existing tags are never moved; conflicting tags cause an error. The command does not push automatically.

  1. Build Caddy with the wstunnel-go module:

    xcaddy build --with github.com/kad/wstunnel-go/pkg/caddy
  2. Configure it in the Caddyfile:

    example.com {
        route /wstunnel/* {
            wstunnel {
                prefix wstunnel
                mode rust
                # restrict_config /etc/wstunnel/rules.yaml
            }
        }
    }

    The directive runs before reverse_proxy by default, so a site can proxy everything else. An explicit order wstunnel before reverse_proxy in the global options is accepted but not needed. Clients must use the same prefix (--http-upgrade-path-prefix wstunnel).

  3. To accept tun sessions (Go-only, see docs/TUN.md), add enable_tun, a restriction rule that allows Tun, and a limit on where flows may go:

    wstunnel {
        prefix wstunnel
        enable_tun
        restrict_config /etc/wstunnel/rules.yaml
        tun_allow 10.0.0.0/8 192.0.2.0/24
    }

    See docs/CONFIG.md for every subdirective.

wstunnel-go in Caddy automatically leverages Caddy's TLS termination, including mTLS. When Caddy reloads its configuration the old handler is cleaned up: its tun sessions and reverse-tunnel listeners are closed, so a reload applies new rules and limits to tun sessions and reverse tunnels. Forward tunnels that are already open keep running under the old rules until they end.

Usage

Client Mode

wstunnel-go provides a CLI that mirrors the original tool's arguments.

# Forward local SOCKS5 to remote server
wstunnel-go client -L socks5://127.0.0.1:1080 wss://my-server.com

# Forward local port to remote destination
wstunnel-go client -L tcp://8080:google.com:443 wss://my-server.com

# Reverse tunnel: remote server port 8080 forwards to local 127.0.0.1:80
wstunnel-go client -R tcp://8080:127.0.0.1:80 wss://my-server.com

# Use HTTP/2 transport
wstunnel-go client -L tcp://8080:google.com:443 https://my-server.com

# Use custom DNS resolver and prefer IPv4
wstunnel-go client --dns-resolver 8.8.8.8 --dns-resolver-prefer-ipv4 -L tcp://8080:google.com:443 wss://my-server.com

# Route 10.0.0.0/8 through the server with a TUN device (Linux, Go-only; see docs/TUN.md)
sudo wstunnel-go client -L 'tun://wst0?route=10.0.0.0/8' wss://my-server.com

# Route all IPv4 and IPv6 traffic through the server (full tunnel; see docs/TUN.md)
sudo wstunnel-go client -L 'tun://wst0?route=default&routing=auto&dns=1.1.1.1' wss://my-server.com

Server Mode

# Start a basic server listening on port 8080
wstunnel-go server ws://0.0.0.0:8080

# Start server with mTLS and restriction rules
wstunnel-go server --tls-certificate cert.pem --tls-private-key key.pem --tls-client-ca-certs ca.pem --restrict-config rules.yaml

Configuration

wstunnel-go can be configured via command-line flags, environment variables, or a YAML configuration file.

For a comprehensive YAML guide with annotated client/server examples and option descriptions, see docs/CONFIG.md.

CLI Flags

Global Flags

  • --config: Path to YAML configuration file.
  • --log-lvl: Log verbosity (TRACE, DEBUG, INFO, WARN, ERROR, OFF). Default: INFO.
  • --no-color: Disable color output.
  • --nb-worker-threads: Number of OS threads that run Go code at once (sets GOMAXPROCS; 0 keeps the default) (environment variable: TOKIO_WORKER_THREADS).

Client Flags

  • -L, --local-to-remote: Define a local-to-remote tunnel.
  • -R, --remote-to-local: Define a remote-to-local (reverse) tunnel.
  • --http-upgrade-path-prefix: HTTP upgrade path prefix (default: "v1").
  • --jwt-secret: Shared secret used to sign tunnel JWTs.
  • --http-upgrade-credentials: Raw Authorization header value for the upgrade request (for Basic auth, pass the full Basic ... value).
  • -H, --header: Custom HTTP headers for upgrade request.
  • --http-headers-file: File containing custom HTTP headers.
  • --tls-verify-certificate: Enable/disable TLS cert verification.
  • --tls-sni-override: Override SNI domain.
  • --tls-sni-disable: Disable sending SNI.
  • --tls-ech-enable: Enable ECH.
  • --http-proxy: Use an HTTP proxy for the connection.
  • --connection-min-idle: Maintain a pool of idle connections.
  • --connection-retry-max-backoff: Maximum retry backoff for server connection.
  • --dns-resolver: Custom DNS resolver(s).
  • --dns-resolver-prefer-ipv4: Prioritize IPv4 for DNS lookup.
  • --websocket-ping-frequency: Frequency of WebSocket pings.
  • --websocket-mask-frame: Enable masking of WebSocket frames.

Server Flags

  • --restrict-to: Restrict tunnels to specific destinations.
  • -r, --restrict-http-upgrade-path-prefix: Restrict tunnels to specific path prefixes.
  • --jwt-secret: Shared secret used to verify tunnel JWT signatures when running with --mode ws. In --mode rust, tunnel JWTs are parsed in Rust-compatible mode and are not cryptographically verified.
  • --insecure-no-jwt-validation: Allow Rust-compatible parsing of HS256 tunnel JWTs without signature verification in situations where --mode ws would otherwise reject them.
  • --restrict-config: Path to a YAML file with restriction rules.
  • --tls-certificate, --tls-private-key: Paths to TLS cert/key for the server.
  • --tls-client-ca-certs: Enable mTLS by providing CA certificates to verify clients.
  • --remote-to-local-server-idle-timeout: Idle timeout for reverse tunnel server.
  • --enable-tun: Accept packet-level tun sessions (Go-only extension). Off by default, and required even when restrictions allow every protocol.
  • --tun-udp-timeout: Close a tun UDP flow after this long without traffic (default 30s).
  • --tun-max-flows: Maximum concurrent outbound flows across all tun sessions (default 4096).
  • --tun-max-sessions: Maximum concurrent tun sessions; extra sessions are closed immediately (default 256).
  • --tun-allow: Limit tun flow destinations to this CIDR or address; repeatable. The built-in deny list still applies.

YAML Configuration Example

mode: client # or server
log_lvl: INFO
no_color: false
client:
  remote_addr: wss://my-server.com
  local_to_remote:
    - "tcp://8080:google.com:443"
    - "socks5://127.0.0.1:1080"
server:
  listen_addr: ws://0.0.0.0:8080
  restrict_config: /etc/wstunnel/rules.yaml

The full set of YAML keys, tunnel examples, and detailed descriptions for both client and server config lives in docs/CONFIG.md.

API Reference (Library Usage)

wstunnel-go is built with a modular design, making it easy to use as a library.

import (
    "github.com/kad/wstunnel-go/pkg/client"
    "github.com/kad/wstunnel-go/pkg/protocol"
)

func main() {
    config := client.Config{
        ServerURL: "wss://my-server.com",
        PathPrefix: "v1",
        // ... other config
    }
    c := client.NewClient(config)

    ltr, _ := client.ParseTunnelArg("tcp://8080:google.com:443", false)
    go c.StartTunnel(ltr)

    select {}
}

Status & Interoperability

wstunnel-go aims for 100% parity with the Rust version.

Feature Status Interop (Rust)
TCP Forward/Reverse ✅ ✅
UDP Forward ✅ ✅
UDP Reverse ✅ ✅
SOCKS5 Forward ✅ ✅
SOCKS5 Reverse ✅ ✅
HTTP Proxy (CONNECT) ✅ ✅
Reverse HTTP Proxy ✅ ✅
Unix Sockets ✅ ✅
Stdio Tunneling ✅ ✅
YAML Restrictions ✅ ✅
mTLS ✅ ✅
HTTP/2 Transport ✅ ✅
TProxy (Linux) ✅ ✅
Tun mode (packet tunnel, Linux client) ✅ n/a (Go-only)
JWT Authentication ✅ ✅

Performance Metrics

Metric wstunnel (Rust) wstunnel-go
Throughput (TCP) ~ Gbps ~ Gbps
Latency Overhead < 1ms < 1ms
Memory Usage (Idle) ~ 10MB ~ 20MB

Note: Benchmarks are environment-dependent. Go version typically shows slightly higher memory usage due to GC and goroutine stacks, but comparable throughput.

Compatibility Versions

  • Rust wstunnel: v9.0.0+
  • Go: 1.27.2+

Contributing

Contributions are welcome! Please ensure you follow the project's coding standards:

  1. Run make fmt to format code.
  2. Run make lint and make vet for static analysis.
  3. Ensure all tests pass with make test.
  4. Run make test-interop if you change protocol-related code.

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

Experimenting with Gemini: Implementation of erebe/wstunnel in Go

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages