Illystre/Rustdesk-FreeConsole
0 forks
BetterDesk Console - Free web console for Rustdesk
id: 19
109,372 Lines
  • JavaScript 26.6%
  • Go 26.4%
  • Markdown 13.2%
  • Shell 10%
  • JSON 8.7%
  • CSS 5.8%
  • PowerShell 5%
  • ProtoBuf 2%
  • Python 1.9%
  • Yaml 0.4%
  • XML 0%
README.md

🚀 BetterDesk — RustDesk-Compatible Server & Web Console

BetterDesk Logo



License Go Node.js Version Security Database

A clean-room RustDesk-compatible server written in Go — single binary replacing hbbs + hbbr — with full protocol support, TLS everywhere, PostgreSQL backend, and a modern Node.js web management console.

Architecture • Installation • Configuration • Security • API • Troubleshooting


✅ End-to-End Encryption — Fully Working

E2E encryption between RustDesk clients is fully functional. Both P2P (punch-hole) and relay sessions establish NaCl-encrypted channels with proper SignedId + PublicKey handshake. The green lock indicator appears in the RustDesk client for all connection modes.

Additionally, you can enable TLS on relay ports (--tls-relay / TLS_RELAY=Y) for an extra transport-level encryption layer on top of the E2E channel.


📋 Table of Contents


🌟 Overview

BetterDesk is a complete RustDesk infrastructure solution consisting of two main components:

  1. BetterDesk Server — A clean-room Go implementation that replaces both hbbs (signal) and hbbr (relay) with a single binary. It implements the full RustDesk wire protocol, including UDP/TCP/WebSocket signal, TCP/WebSocket relay, NaCl secure handshake, and a comprehensive HTTP REST API.

  2. BetterDesk Console — A Node.js (Express.js) web management panel with device monitoring, TOTP 2FA, RBAC, address book sync, and RustDesk Client API.

Why BetterDesk?

FeatureOriginal RustDesk ServerBetterDesk Server
Binaries2 (hbbs + hbbr)1 single binary
LanguageRustGo (pure Go, no CGO)
DatabaseSQLite onlySQLite + PostgreSQL
TLSNot built-inTLS everywhere (auto-detect plain/TLS on same port)
APIMinimalFull REST API with JWT + API keys
Status trackingBinary (online/offline)4-tier (Online/Degraded/Critical/Offline)
Rate limitingNoneIP, bandwidth, connection limits
MetricsNonePrometheus exposition format
Admin consoleNoneTCP admin (telnet/netcat)
Device enrollmentOpen onlyOpen/Managed/Locked modes
Audit trailNoneRing-buffer + JSON file audit logging
Hot reloadRestart requiredSIGHUP config reload
Multi-instanceFile-based onlyPostgreSQL LISTEN/NOTIFY for real-time sync
Web panelNoneFull Node.js console with TOTP 2FA

🤖 AI-Assisted Development: This project was developed with significant assistance from AI coding tools (Claude/GitHub Copilot). All code has been reviewed, tested, and validated for production use.


🏗️ Architecture

RustDesk Desktop/Mobile Clients
  │
  ├── UDP (:21116) ──────► Signal Server ──► RegisterPeer, PunchHole, RequestRelay
  ├── TCP (:21116) ──────► Signal Server ──► NaCl Secure Handshake → encrypted channel
  ├── TCP (:21115) ──────► NAT Test      ──► TestNatRequest, OnlineRequest, ConfigUpdate
  ├── WS  (:21118) ──────► WS Signal     ──► WebSocket-based signal (web clients)
  │
  ├── TCP (:21117) ──────► Relay Server  ──► UUID pairing → bidirectional io.Copy pipe
  ├── WS  (:21119) ──────► WS Relay      ──► WebSocket relay (web clients)
  │
  └── HTTP (:21121) ─────► Client API    ──► Login, address book sync, heartbeat, sysinfo
                                              (WAN-facing, 7-layer security stack)

Admin / Web Console
  │
  ├── HTTP  (:21114) ────► REST API      ──► JWT/API-key auth → CRUD endpoints
  ├── WS    (:21114) ────► Event Stream  ──► Real-time peer status push
  ├── TCP   (admin)  ────► Admin Console ──► telnet/netcat management (127.0.0.1 only)
  └── HTTP  (:5000)  ────► Web Console   ──► Node.js + Express + EJS (LAN)
                                              TOTP 2FA, RBAC, device management

Database Layer
  │
  ├── SQLite  ──► Pure Go (modernc.org/sqlite), WAL mode, single binary
  └── PostgreSQL ──► pgx/v5 + pgxpool, LISTEN/NOTIFY, row-level locking

Port Map

PortProtocolServiceDirection
21114HTTP(S)REST API (Go server)LAN
21115TCPNAT type test + OnlineRequestWAN
21116TCP + UDPSignal Server (registration, punch hole)WAN
21117TCPRelay Server (bidirectional stream)WAN
21118WS(S)WebSocket SignalWAN
21119WS(S)WebSocket RelayWAN
21121HTTPRustDesk Client API (login, AB sync)WAN
5000HTTPWeb Console (admin panel)LAN

All TCP/WS ports support dual-mode TLS — plain and TLS on the same port with automatic detection.


🔧 BetterDesk Go Server

The Go server (betterdesk-server/) is a ~20,000 LOC clean-room implementation of the RustDesk signal and relay protocol. It compiles to a single static binary with no external dependencies (pure Go, no CGO required).

Server Modes

# Default: run everything (signal + relay + API + admin)
./betterdesk-server -mode all

# Signal only (no relay)
./betterdesk-server -mode signal

# Relay only
./betterdesk-server -mode relay

Protocol Implementation

The server implements the complete RustDesk rendezvous/relay protocol:

Signal Protocol (UDP/TCP/WS)

MessageDirectionDescription
RegisterPeerClient → ServerHeartbeat registration (~12s interval), updates in-memory peer map
RegisterPeerResponseServer → ClientSuggested heartbeat interval, request online status
RegisterPkClient → ServerPublic key registration with UUID consistency check
RegisterPkResponseServer → ClientRegistration result
PunchHoleRequestClient A → ServerRequest hole-punch to Client B
PunchHoleServer → Client BForward punch request with Client A's address
PunchHoleSentClient B → ServerConfirm punch sent
PunchHoleResponseServer → Client ARelay response with Client B's NAT info
RequestRelayClient → ServerRequest relay session
RelayResponseServer → ClientsRelay server address + UUID for pairing
FetchLocalAddr / LocalAddrBidirectionalLAN address exchange for direct connections
TestNatRequestClient → Server (:21115)NAT type detection
TestNatResponseServer → ClientNAT type + ConfigUpdate (relay/rendezvous servers)
OnlineRequestClient → Server (:21115)Bulk online status query (bitmask response)

Relay Protocol (TCP/WS)

The relay is a pure opaque byte pipe:

  1. Client A connects, sends RequestRelay{uuid: "..."} → registered as pending
  2. Client B connects with the same UUID → pair found
  3. Bidirectional io.Copy begins immediately (relay is a pure opaque byte pipe)
  4. Timeouts: 30s pairing, 30s idle (extended on activity via idleTimeoutConn)

The relay does not parse, inspect, or modify traffic between paired clients. E2E encryption is entirely between the two RustDesk clients.

Wire Protocol (codec/)

Matches hbb_common::bytes_codec::BytesCodec:

  • TCP: Variable-length framing — bottom 2 bits of header = header length - 1, remaining bits = payload length (little-endian). Supports 1-4 byte headers (max frame: 64 KB)
  • UDP: Raw protobuf (no framing)
  • WebSocket: Raw protobuf per binary WS frame

Cryptography

Server-Client Secure Handshake (NaCl)

Server                                          Client
  │                                                │
  │  KeyExchange{keys: [Ed25519_sign(Cv_pub)]}     │
  │ ──────────────────────────────────────────────► │
  │                                                │
  │  KeyExchange{keys: [client_cv_pub,             │
  │               nacl_box(symmetric_key)]}         │
  │ ◄────────────────────────────────────────────── │
  │                                                │
  │  ═══ All traffic encrypted with NaCl secretbox ═══
  1. Server generates Ed25519 keypair → derives Curve25519 public key → signs with Ed25519
  2. Client verifies signature → generates its own Curve25519 keypair
  3. Client encrypts a random symmetric key using NaCl box (Curve25519 DH)
  4. All subsequent messages use NaCl secretbox with sequential nonces
  5. Backward compatible: Auto-detects old (plain) vs new (encrypted) clients

Key Storage

  • Private key: id_ed25519 file (auto-generated if missing)
  • Public key: id_ed25519.pub (base64-encoded, same format as original RustDesk)
  • Key format: Standard Ed25519 (32-byte seed), compatible with existing RustDesk clients

Password Hashing

  • Algorithm: PBKDF2-HMAC-SHA256
  • Iterations: 100,000
  • Salt: 16-byte cryptographically random
  • Comparison: Constant-time (subtle.ConstantTimeCompare)

Database Backends

SQLite (Default)

./betterdesk-server -db ./db_v2.sqlite3
  • Driver: modernc.org/sqlite — pure Go, no CGO required
  • Journal mode: WAL (Write-Ahead Logging) for concurrent reads
  • Foreign keys: Enabled by default
  • Connection limit: 1 (SQLite single-writer constraint)
  • Write serialization: sync.RWMutex around all write operations
  • Tables: peers, server_config, id_change_history, users, api_keys, device_tokens

PostgreSQL

./betterdesk-server -db "postgres://user:password@localhost:5432/betterdesk?sslmode=disable"
  • Driver: pgx/v5 with pgxpool connection pooling
  • Pool size: Configurable via pool_max_conns DSN parameter (default: 10)
  • Native types: BOOLEAN, BYTEA, TIMESTAMPTZ, BIGSERIAL
  • Row-level locking: SELECT ... FOR UPDATE in ChangePeerID (replaces SQLite global mutex)
  • LISTEN/NOTIFY: Real-time cross-instance event push for multi-server deployments
  • Partial indexes: WHERE banned = TRUE, WHERE peer_id != '' for performance
  • Auto-detection: DSN starting with postgres:// or postgresql:// automatically selects PostgreSQL

Schema Overview

-- Core tables (both backends)
peers              -- Device records (21 fields: id, uuid, pk, ip, note, status, etc.)
server_config      -- Key-value configuration store
id_change_history  -- Device ID change audit trail
users              -- Admin/operator/viewer accounts (PBKDF2 + TOTP)
api_keys           -- API key management (SHA256 hash storage)
device_tokens      -- Enrollment tokens (Dual Key System)

TLS Support

BetterDesk supports TLS on all transport layers with a unique dual-mode auto-detection system:

# Enable TLS on signal ports (21116 TCP + 21115 + 21118 WSS)
./betterdesk-server -tls-signal -tls-cert server.crt -tls-key server.key

# Enable TLS on relay ports (21117 TCP + 21119 WSS)
./betterdesk-server -tls-relay -tls-cert server.crt -tls-key server.key

# Enable TLS on everything
./betterdesk-server -tls-signal -tls-relay -tls-cert server.crt -tls-key server.key

# HTTPS on API
./betterdesk-server -tls-cert server.crt -tls-key server.key -force-https

DualModeListener (config/tls.go)

Accepts both plain and TLS connections on the same port:

  1. Peeks first byte of incoming connection
  2. If 0x16 (TLS ClientHello) → upgrades to tls.Server()
  3. Otherwise → passes through as plain TCP via peekedConn

This means existing RustDesk clients (no TLS) continue to work alongside TLS-enabled clients without port changes. Minimum TLS version: TLS 1.2.

Rate Limiting & DDoS Protection

LayerTypeDefaultConfigurable
IP rate limiterSliding window per-IP20 registrations/minVia constants
Login rate limiterPer-IP5 attempts / 5 minVia constants
Bandwidth limiterToken bucket1 GB/s global, 16 MB/s per-sessionVia constants
Connection limiterPer-IP concurrent20 relay connections/IP-relay-max-conns-ip
TCP punch cacheTTL + max size2 min TTL, 10K max entriesVia constants
WebSocket originsWhitelistAccept allWS_ALLOWED_ORIGINS env
Relay idle timeoutPer-session30s (extended on activity)Via constants
Relay pair timeoutPending sessions30sVia constants

Enrollment & Device Tokens

The Dual Key System controls which devices can register with the server:

ModeBehavior
open (default)Accept all device registrations
managedNew devices need admin approval OR a valid enrollment token
lockedOnly devices with pre-issued valid enrollment tokens can register
# Set enrollment mode
./betterdesk-server -mode all
# Then via API: PUT /api/enrollment/mode {"mode": "managed"}

Device tokens have statuses: pending, active, revoked, expired. Bulk generation is supported via POST /api/tokens/generate-bulk.

4-Tier Device Status System

ONLINE    → Last heartbeat < 15s ago
DEGRADED  → 2 consecutive missed heartbeats (15-30s)
CRITICAL  → 4+ missed heartbeats (30-60s)
OFFLINE   → Beyond RegTimeout (30s) with no heartbeat
  • Heartbeat interval: Clients send RegisterPeer every ~12s
  • Cleaner goroutine: Runs every 3s, checks all peers, publishes status transition events
  • Debounced DB sync: Memory → database sync every 60s (avoids write storms)

Admin TCP Console

A lightweight management interface accessible via telnet or netcat:

./betterdesk-server -admin-port 9090 -admin-password "secret"
# Then: telnet 127.0.0.1 9090

Commands: status, peers [count|info <id>], ban/unban/kick <id>, blocklist [add|rm], config [get|set], reload, quit

Admin console binds to 127.0.0.1 only — never exposed to the network.


🖥️ Web Console (Node.js)

The web console (web-nodejs/) is an Express.js application providing a full-featured management UI.

Features

  • Dashboard — Real-time statistics cards (total, active, inactive, banned devices)
  • Device management — Search, filter, sort, add notes, ban/unban, change ID
  • Device details — Hardware tab (sysinfo), metrics tab (live CPU/RAM/disk bars + history charts)
  • TOTP 2FA — Two-factor authentication with otplib
  • RBAC — Admin, Operator, Viewer roles with permission enforcement
  • Address book sync — Full AB storage with address_books table
  • RustDesk Client API — Dedicated WAN port (21121) with 7-layer security
  • Desktop connect — One-click connect via rustdesk:// URI handler
  • i18n — JSON-based translations (English + Polish built-in)
  • CSRF protection — Double-submit cookie pattern with csrf-csrf
  • WebSocket — Real-time status updates from Go server event bus

RustDesk Client API (Port 21121)

Allows RustDesk desktop clients to:

  • Login/logout with username and password
  • Sync address books across devices
  • Send heartbeats and system information
  • Query device groups and user information

Security middleware stack (7 layers):

LayerProtection
1Request timeout (10s request / 15s headers)
2Security headers (no server fingerprinting)
3Request logger (full audit trail)
4Path whitelist (only known RustDesk endpoints)
5Global rate limit (100 req/15min per IP)
6Login rate limit (5 attempts/15min per IP)
7Body size limit (1KB default, 64KB for address book)

🛡️ Security Architecture

Server-Level Security

ComponentImplementation
Transport encryptionNaCl secretbox (signal TCP), TLS 1.2+ (all ports), WSS (WebSocket)
Password storagePBKDF2-HMAC-SHA256, 100K iterations, 16-byte random salt
JWT tokensHS256 with HMAC-equal verification (constant-time), configurable expiry, unique JTI
2FA partial tokens5-minute TTL (prevents long-lived intermediate auth states)
TOTP 2FARFC 6238 compliant, ±1 time step tolerance, constant-time code comparison
API authenticationJWT Bearer token OR API key (X-API-Key header, SHA256 hash lookup)
Input validationPeer ID: ^[A-Za-z0-9_-]{6,16}$, config key: ^[A-Za-z0-9_.\-]{1,64}$
SQL injectionParameterized queries only, LIKE patterns escape % and _
IP blocklistIP, CIDR, device ID blocking with hot-reload (SIGHUP)
Rate limitingPer-IP sliding window (registrations, login, TCP connections)
Bandwidth limitingToken bucket (global: 1 GB/s, per-session: 16 MB/s)
Audit loggingRing buffer (10K events) + optional JSON-lines file output
Error handlingNever exposes internal details to clients
Credentials fileAdmin password file written with mode 0600
Proxy trustX-Forwarded-For only when TRUST_PROXY=Y

Console-Level Security

ComponentImplementation
CSRFDouble-submit cookie pattern (csrf-csrf)
Session fixationSession regeneration after login
Timing-safe authPre-computed dummy bcrypt hash for non-existent users
WebSocket authSession cookie required for WS upgrade
HelmetSecurity headers (CSP, HSTS, X-Frame-Options)
Rate limitingexpress-rate-limit on all endpoints
XSS preventionHTML sanitization, textContent instead of innerHTML
Sort injectionWhitelisted sort fields and directions

📦 Installation

Prerequisites

RequirementVersionNotes
Go1.21+Auto-installed by scripts if missing (downloads Go 1.22.1)
Node.js18+Auto-installed by scripts if missing
GitAnyFor cloning the repository
OSLinux (Ubuntu 20.04+, Debian 11+, CentOS 8+), Windows 10+, Docker
PostgreSQL14+Optional — SQLite is the default

Linux

git clone https://github.com/UNITRONIX/Rustdesk-FreeConsole.git
cd Rustdesk-FreeConsole
chmod +x betterdesk.sh

# Interactive mode (recommended for first install)
sudo ./betterdesk.sh

# Automatic mode (non-interactive)
sudo ./betterdesk.sh --auto

# Skip Go binary SHA256 verification
sudo ./betterdesk.sh --skip-verify

# Custom API port
API_PORT=21120 sudo ./betterdesk.sh --auto

The script will:

  1. Install Go toolchain if not present
  2. Compile betterdesk-server from source (single binary)
  3. Install Node.js and the web console
  4. Create systemd services (betterdesk-server.service + betterdesk-console.service)
  5. Generate Ed25519 keys (or preserve existing ones)
  6. Create initial admin user (credentials saved to .admin_credentials)
  7. Start all services

Windows

# Run PowerShell as Administrator
git clone https://github.com/UNITRONIX/Rustdesk-FreeConsole.git
cd Rustdesk-FreeConsole

# Interactive mode
.etterdesk.ps1

# Automatic mode
.etterdesk.ps1 -Auto

# Skip verification
.etterdesk.ps1 -SkipVerify

The script installs Go, compiles the server, sets up NSSM services (BetterDeskServer + BetterDeskConsole) or scheduled tasks as fallback.

Docker

git clone https://github.com/UNITRONIX/Rustdesk-FreeConsole.git
cd Rustdesk-FreeConsole
chmod +x betterdesk-docker.sh
./betterdesk-docker.sh

Or manually with Docker Compose:

docker compose build
docker compose up -d

Note: Docker images are built locally — they are not available on Docker Hub. Always use docker compose build first.

All scripts provide an interactive menu:

OptionDescription
1🚀 New installation (compile Go server + install Node.js console)
2⬆️ Update existing installation
3🔧 Repair installation
4✅ Validate installation
5💾 Create backup
6🔐 Reset admin password
7🔨 Build/rebuild Go server binary
8📊 Diagnostics
9🗑️ Uninstall
C🔒 Configure SSL/TLS certificates
M🔄 Migrate from existing RustDesk (Docker)
P🔀 Database migration (SQLite ↔ PostgreSQL)
S⚙️ Settings (path configuration)

What Gets Installed

/opt/rustdesk/                    # (Linux) or C:\BetterDesk\ (Windows)
├── betterdesk-server             # Single Go binary (signal + relay + API)
├── id_ed25519                    # Ed25519 private key (mode 0600)
├── id_ed25519.pub                # Ed25519 public key (base64)
├── db_v2.sqlite3                 # SQLite database (if using SQLite)
├── .admin_credentials            # Initial admin password (mode 0600)
├── .api_key                      # API key for console ↔ server auth
└── web-console/                  # Node.js web console
    ├── server.js
    ├── package.json
    ├── .env                      # Console configuration
    └── ...

🖥️ RustDesk Client Configuration

After installing BetterDesk server, configure your RustDesk desktop clients to connect to it.

Basic Setup

  1. Open the RustDesk client
  2. Click the menu (≡) button → Network → ID/Relay Server
  3. Fill in:
FieldValueExample
ID ServerYour server IP or domainbetterdesk.example.com
Relay ServerSame as ID Server (or leave empty)betterdesk.example.com
API Serverhttp(s)://<server>:21121http://betterdesk.example.com:21121
KeyContents of id_ed25519.pub on the server(base64 public key string)

Tip: The public key can be found in the Web Console under Dashboard → Server Keys, or by reading the file /opt/rustdesk/id_ed25519.pub (Linux) / C:\BetterDesk\id_ed25519.pub (Windows) on the server.

Mass Deployment

For deploying to many clients, use the RustDesk configuration string:

rustdesk://config/<base64-encoded-json>

JSON structure:

{
  "host": "betterdesk.example.com",
  "relay": "betterdesk.example.com",
  "api": "http://betterdesk.example.com:21121",
  "key": "<contents-of-id_ed25519.pub>"
}

You can also use the --config command-line flag when starting RustDesk:

rustdesk --config '{"host":"betterdesk.example.com","key":"<pubkey>"}'

Desktop Client Login

RustDesk desktop clients can log in to the BetterDesk server using their user account. This enables address book synchronization, device grouping, and audit trail per user.

How to Log In

  1. Open the RustDesk client
  2. Click the account icon (person silhouette) in the bottom-left corner
  3. Enter your username and password (the same credentials used for the Web Console)
  4. Click Login

Note: The login API runs on port 21121 (the RustDesk Client API), not on port 21114 (which is the server management REST API for LAN-only use). Make sure the API Server field in the client points to http(s)://<server>:21121.

What Login Enables

FeatureDescription
Address Book SyncYour address book is stored server-side and synced across all devices where you're logged in
User IdentityConnections are associated with your user account in audit logs
Device GroupsAccess to pre-configured device groups and strategies
Heartbeat + SysinfoThe client periodically sends system information (CPU, RAM, OS) to the server

Troubleshooting Login

ProblemSolution
"Login failed"Verify the API Server field is set to http://<server>:21121 (not 21114)
"Connection refused"Ensure port 21121 is open in the firewall and the console is running
TOTP 2FA promptEnter the 6-digit code from your authenticator app (if 2FA is enabled for your account)
"Invalid credentials"Reset password via Web Console → Users, or run the installer with option 6

Ports Required on Client Side

Ensure the following outbound ports are accessible from clients to the server:

PortProtocolPurpose
21115TCPNAT type detection (automatic)
21116TCP + UDPSignal / ID registration
21117TCPRelay (connection forwarding)
21118TCP (WS)WebSocket signal (optional, web clients)
21119TCP (WS)WebSocket relay (optional, web clients)
21121TCPRustDesk Client API — login, address book sync, heartbeat

Port 21114 is the Go server management REST API (LAN-only) — it is not used by RustDesk desktop clients. Do not expose it to the internet.


🔒 TLS / SSL Certificates

BetterDesk supports TLS on all layers: Go server transport (signal + relay), Go server HTTPS API, and the Node.js web console.

Self-Signed Certificate (Quick Start)

For testing or internal networks, generate a self-signed certificate:

# Create certificate directory
mkdir -p /opt/rustdesk/ssl

# Generate a self-signed certificate (valid for 3 years)
openssl req -x509 -nodes -days 1095 -newkey rsa:2048 \
  -keyout /opt/rustdesk/ssl/betterdesk.key \
  -out /opt/rustdesk/ssl/betterdesk.crt \
  -subj "/CN=$(hostname -f)/O=BetterDesk/C=US" \
  -addext "subjectAltName=DNS:$(hostname -f),DNS:localhost,IP:$(curl -s ifconfig.me),IP:127.0.0.1"

# Secure the private key
chmod 600 /opt/rustdesk/ssl/betterdesk.key

Windows (PowerShell):

New-Item -ItemType Directory -Path "C:\BetterDesk\ssl" -Force
openssl req -x509 -nodes -days 1095 -newkey rsa:2048 `
  -keyout "C:\BetterDesk\ssl\betterdesk.key" `
  -out "C:\BetterDesk\ssl\betterdesk.crt" `
  -subj "/CN=localhost/O=BetterDesk"

Applying TLS to Go Server

Once you have certificate files, configure the Go server:

# TLS on signal ports (21116 TCP + 21115 + 21118 WSS)
./betterdesk-server -tls-signal -tls-cert /opt/rustdesk/ssl/betterdesk.crt -tls-key /opt/rustdesk/ssl/betterdesk.key

# TLS on relay ports (21117 TCP + 21119 WSS)
./betterdesk-server -tls-relay -tls-cert /opt/rustdesk/ssl/betterdesk.crt -tls-key /opt/rustdesk/ssl/betterdesk.key

# TLS everywhere + force HTTPS on API
./betterdesk-server -tls-signal -tls-relay -force-https \
  -tls-cert /opt/rustdesk/ssl/betterdesk.crt \
  -tls-key /opt/rustdesk/ssl/betterdesk.key

For systemd, add the flags to ExecStart in /etc/systemd/system/betterdesk-server.service:

ExecStart=/opt/rustdesk/betterdesk-server -mode all ... \
  -tls-signal -tls-relay \
  -tls-cert /opt/rustdesk/ssl/betterdesk.crt \
  -tls-key /opt/rustdesk/ssl/betterdesk.key

Dual-mode: BetterDesk auto-detects plain vs TLS on the same port (first-byte 0x16 detection). Existing non-TLS clients continue to work without changes.

Applying TLS to Web Console (Node.js)

Edit the console .env file:

HTTPS_ENABLED=true
SSL_CERT_PATH=/opt/rustdesk/ssl/betterdesk.crt
SSL_KEY_PATH=/opt/rustdesk/ssl/betterdesk.key
HTTP_REDIRECT_HTTPS=true

Or use the ALL-IN-ONE script menu option C (SSL Configuration) which supports:

  • Let's Encrypt — automatic certificate via certbot (requires public domain + port 80)
  • Custom certificate — provide your own PEM cert + key
  • Self-signed — auto-generated for testing

Let's Encrypt (Production)

For production servers with a public domain:

# Install certbot
sudo apt install certbot  # Debian/Ubuntu

# Obtain certificate (standalone mode, port 80 must be open)
sudo certbot certonly --standalone -d betterdesk.example.com

# Certificate files:
# /etc/letsencrypt/live/betterdesk.example.com/fullchain.pem
# /etc/letsencrypt/live/betterdesk.example.com/privkey.pem

Then configure both the Go server and Node.js console to use these paths.

Auto-renewal: The ALL-IN-ONE script automatically adds a certbot renewal cron job when you use the Let's Encrypt option.

Automatic TLS During Installation

The ALL-IN-ONE scripts (betterdesk.sh / betterdesk.ps1) automatically generate a self-signed certificate during every fresh installation:

  1. Certificate location: <RUSTDESK_PATH>/ssl/betterdesk.crt + betterdesk.key
  2. Validity: 3 years, RSA 2048-bit, with SAN (server IP + localhost)
  3. Go server flags: -tls-cert, -tls-key, -tls-signal, -tls-relay, -force-https added automatically
  4. Node.js console: .env pre-populated with SSL_CERT_PATH / SSL_KEY_PATH and BETTERDESK_API_URL set to https://
  5. Dual-mode: Existing non-TLS clients continue to work (auto-detection on same port)

You can upgrade to Let's Encrypt or a custom certificate at any time using menu option C. If certificate generation fails during install (e.g., openssl missing), the server runs without TLS and you can generate certificates later.


⚙️ Configuration Reference

CLI Flags

FlagDefaultEnv VarDescription
-port21116PORTSignal port (UDP + TCP)
-relay-port21117RELAY_PORTRelay port (TCP)
-api-port21114API_PORTHTTP REST API port
-modeallMODEServer mode: all, signal, relay
-db./db_v2.sqlite3DB_URLDatabase DSN — file path (SQLite) or postgres://... (PostgreSQL)
-key-fileid_ed25519KEY_FILEEd25519 key file path (without extension)
-relay-servers(empty)RELAY_SERVERSComma-separated relay addresses for ConfigUpdate
-rendezvous-servers(empty)RENDEZVOUS_SERVERSComma-separated rendezvous addresses
-mask(empty)MASKLAN mask (e.g. 192.168.0.0/24)
-always-relayfalseALWAYS_USE_RELAY=YForce relay for all connections (no P2P)
-blocklist(empty)BLOCKLIST_FILEPath to IP/ID/CIDR blocklist file
-audit-log(empty)AUDIT_LOG_FILEPath to audit log file (JSON lines)
-tls-cert(empty)TLS_CERTTLS certificate file (PEM)
-tls-key(empty)TLS_KEYTLS private key file (PEM)
-tls-signalfalseTLS_SIGNAL=YEnable TLS on signal ports
-tls-relayfalseTLS_RELAY=YEnable TLS on relay ports
-log-formattextLOG_FORMATLog format: text or json
-admin-port0ADMIN_PORTTCP admin console port (0 = disabled)
-admin-password(empty)ADMIN_PASSWORDAdmin TCP console password
-jwt-secret(auto)JWT_SECRETJWT signing secret (auto-generated if omitted)
-jwt-expiry24JWT_EXPIRY_HOURSJWT token expiry in hours
-force-httpsfalseFORCE_HTTPS=YReject non-TLS API requests
-trust-proxyfalseTRUST_PROXY=YTrust X-Forwarded-For / X-Real-IP headers
-relay-max-conns-ip20RELAY_MAX_CONNS_PER_IPMax relay connections per IP
-init-admin-useradminINIT_ADMIN_USERInitial admin username
-init-admin-pass(auto)INIT_ADMIN_PASSInitial admin password (auto-generated if omitted)
-version——Show version and exit

Environment-Only Variables

Env VarDescription
WS_ALLOWED_ORIGINSComma-separated allowed WebSocket origins
ENROLLMENT_MODEDevice enrollment: open, managed, or locked

Protocol Constants

ConstantValueDescription
RegTimeout30sTime after last heartbeat to mark peer offline
HeartbeatCheck3sStatus cleaner goroutine interval
HeartbeatExpected15sExpected heartbeat interval from clients
DegradedThreshold2 missedTransitions to DEGRADED status
CriticalThreshold4 missedTransitions to CRITICAL status
HeartbeatSuggestion12sSuggested heartbeat interval sent to clients
TCPConnTimeout20sTCP connection establishment timeout
RelayPairTimeout30sTime to wait for relay pair match
RelayIdleTimeout30sClose idle relay sessions (extended on activity)
DefaultTotalBandwidth1 GB/sGlobal bandwidth limit
DefaultSingleBandwidth16 MB/sPer-session bandwidth limit
IPRateLimitRegistrations20/minRegistration rate limit per IP
IDChangeCooldown5 minMinimum interval between ID changes
MaxFrameSize64 KBMaximum wire protocol frame size

Console Configuration (.env)

PORT=5000              # Web console port
API_PORT=21121         # RustDesk Client API port
API_ENABLED=true       # Enable/disable Client API
HTTPS_ENABLED=false    # Enable HTTPS on console
SSL_CERT_PATH=         # SSL certificate path
SSL_KEY_PATH=          # SSL key path
TRUST_PROXY=false      # Trust X-Forwarded-For
DB_PATH=               # Path to SQLite database
HBBS_API_URL=          # Go server API URL (http://localhost:21114)
HBBS_API_KEY=          # API key for Go server

📡 API Reference

Authentication

All API requests (except public endpoints) require authentication:

# Option 1: JWT Bearer token (from POST /api/auth/login)
curl -H "Authorization: Bearer <jwt_token>" http://localhost:21114/api/peers

# Option 2: API key
curl -H "X-API-Key: <your_api_key>" http://localhost:21114/api/peers

Public Endpoints (No Auth)

MethodPathDescription
GET/api/healthHealth check + peer counts
GET/api/server/statsServer stats (memory, goroutines, peer breakdown)
GET/api/server/pubkeyEd25519 public key (base64 + hex)
GET/metricsPrometheus metrics
POST/api/auth/loginLogin → JWT token
POST/api/auth/login/2faComplete TOTP 2FA flow

Viewer+ Endpoints

MethodPathDescription
GET/api/peersList all peers (?include_deleted=true)
GET/api/peers/{id}Get single peer
GET/api/peers/status/summaryAggregate status counts
GET/api/peers/onlineAll online peer snapshots
GET/api/peers/{id}/statusDetailed live status (missed beats, transport)
GET/api/blocklistList blocklist entries
PUT/api/peers/{id}/tagsSet peer tags
GET/api/tags/{tag}/peersPeers by tag (LIKE pattern, %_ escaped)
GET/api/audit/eventsRecent events (?limit=50&action=peer_banned)
GET/api/ws/eventsWebSocket real-time events (?filter=peer_online)
GET/api/auth/meCurrent user info

Admin-Only Endpoints

MethodPathDescription
DELETE/api/peers/{id}Delete peer (?hard=true for permanent)
POST/api/peers/{id}/banBan peer (with reason)
POST/api/peers/{id}/unbanUnban peer
POST/api/peers/{id}/change-idChange device ID (validated: 6-16 chars, [A-Za-z0-9_-])
POST/api/blocklistAdd IP/CIDR/ID to blocklist
DELETE/api/blocklist/{entry}Remove blocklist entry
GET/PUT/api/config/{key}Server configuration (key validated: 1-64 chars)
GET/POST/PUT/DELETE/api/users, /api/users/{id}User CRUD
POST/api/users/{id}/totp/setupGenerate TOTP secret + QR URI
POST/api/users/{id}/totp/confirmConfirm TOTP enrollment
DELETE/api/users/{id}/totpDisable TOTP
GET/POST/DELETE/api/keys, /api/keys/{id}API key management
GET/POST/PUT/DELETE/api/tokens, /api/tokens/{id}Device token CRUD
POST/api/tokens/generate-bulkBulk generate enrollment tokens
POST/api/tokens/{id}/bindBind token to specific peer ID
GET/PUT/api/enrollment/modeEnrollment mode management

Example: Login Flow

# Step 1: Login (returns JWT or requires 2FA)
curl -X POST http://localhost:21114/api/auth/login   -H "Content-Type: application/json"   -d '{"username":"admin","password":"your_password"}'

# Response (no 2FA):
# {"token":"eyJhbG...","user":{"id":1,"username":"admin","role":"admin"}}

# Response (2FA required):
# {"requires_2fa":true,"partial_token":"eyJhbG..."}

# Step 2 (if 2FA): Complete with TOTP code
curl -X POST http://localhost:21114/api/auth/login/2fa   -H "Content-Type: application/json"   -d '{"partial_token":"eyJhbG...","code":"123456"}'

WebSocket Events

// Connect to real-time event stream
const ws = new WebSocket('ws://localhost:21114/api/ws/events?filter=peer_online,peer_offline');

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  // { "type": "peer_online", "peer_id": "ABC123", "timestamp": "..." }
};

Event types: peer_online, peer_degraded, peer_critical, peer_offline, peer_banned, peer_unbanned, peer_deleted, peer_id_changed, blocklist_updated, server_stats


🔄 Migration Guide

From Original RustDesk (Rust) to BetterDesk (Go)

The migration tool (betterdesk-server/tools/migrate/) supports multiple migration paths:

# Compile migration tool
cd betterdesk-server/tools/migrate
go build -o migrate .

# Mode 1: Rust hbbs → BetterDesk Go (preserves peer table → peers)
./migrate -mode rust2go -src /opt/rustdesk/db_v2.sqlite3 -dst /opt/betterdesk/db_v2.sqlite3

# Mode 2: SQLite → PostgreSQL
./migrate -mode sqlite2pg -src /opt/betterdesk/db_v2.sqlite3   -dst "postgres://user:pass@localhost:5432/betterdesk"

# Mode 3: PostgreSQL → SQLite (reverse)
./migrate -mode pg2sqlite -src "postgres://..." -dst ./backup.sqlite3

# Mode 4: Node.js console → Go server
./migrate -mode nodejs2go -src /opt/betterdesk/web-console/betterdesk.db   -dst /opt/betterdesk/db_v2.sqlite3

# Mode 5: Backup
./migrate -mode backup -src /opt/betterdesk/db_v2.sqlite3

The migration tool auto-detects the source schema (original RustDesk peer table vs BetterDesk peers table) and maps columns accordingly. Ed25519 keys, UUIDs, ID history, bans, and tags are fully preserved.

Using ALL-IN-ONE Scripts

Both betterdesk.sh and betterdesk.ps1 include built-in migration options:

  • Option M — Migrate from existing RustDesk Docker installation
  • Option P — Database migration (SQLite ↔ PostgreSQL)

From Existing Docker RustDesk

./betterdesk-docker.sh
# Select: M (Migrate from existing RustDesk)

The wizard auto-detects existing containers, creates a backup, and migrates data to BetterDesk.


📊 Monitoring & Metrics

Prometheus Metrics

Available at GET /metrics (no authentication required):

# Counters (monotonic)
betterdesk_registrations_total
betterdesk_expired_total
betterdesk_relay_sessions_total
betterdesk_relay_bytes_total
betterdesk_bandwidth_throttle_hits_total
betterdesk_audit_events_total

# Gauges (current values)
betterdesk_uptime_seconds
betterdesk_peers_total
betterdesk_peers_online
betterdesk_peers_degraded
betterdesk_peers_critical
betterdesk_peers_offline
betterdesk_peers_banned
betterdesk_peers_udp
betterdesk_peers_tcp
betterdesk_peers_ws
betterdesk_relay_active_sessions
betterdesk_blocklist_entries
betterdesk_event_subscribers
betterdesk_goroutines
betterdesk_memory_alloc_bytes
betterdesk_memory_sys_bytes

Grafana Integration

Point a Prometheus scraper at http://your-server:21114/metrics and import the metrics above. No additional exporter needed.

Audit Logging

# Enable file-based audit log
./betterdesk-server -audit-log /var/log/betterdesk/audit.jsonl

Events logged: login, failed auth, peer banned/unbanned, config changes, ID changes, blocklist modifications. Each event includes timestamp, action, actor, target, IP, and details.


🔧 Troubleshooting

Common Issues

SymptomCauseSolution
Key mismatch errorsKeys changed during installRestore from backup: cp /opt/rustdesk-backup-*/id_ed25519* /opt/rustdesk/
All devices offlineDatabase missing last_online columnRun repair: sudo ./betterdesk.sh → option 3
API not respondingWrong binary or portCheck: curl http://localhost:21114/api/health
E2E encryptionNot showing green lockVerify server is v2.4.0+; enable --tls-relay for extra layer
Docker: "pull access denied"Images not on Docker HubBuild locally: docker compose build
Docker: "no such table"Wrong binary in containerRebuild: docker compose build --no-cache
Services won't startPermission issuessudo chmod 600 /opt/rustdesk/id_ed25519
Go compilation failsMissing Go toolchainScript auto-installs, or: sudo apt install golang-go
PostgreSQL connectionWrong DSN formatMust start with postgres:// or postgresql://
Connect button won't workCustom RustDesk schemeSet via browser console: setCustomScheme('your-scheme')

Diagnostics

# Linux — run built-in diagnostics
sudo ./betterdesk.sh  # Select option 8

# Check service status
sudo systemctl status betterdesk-server
sudo systemctl status betterdesk-console

# Check logs
sudo journalctl -u betterdesk-server -n 100 --no-pager
sudo journalctl -u betterdesk-console -n 100 --no-pager

# Test API
curl http://localhost:21114/api/health
curl http://localhost:21114/api/server/stats

# Check metrics
curl http://localhost:21114/metrics

# Windows — check services
Get-Service BetterDeskServer
Get-Service BetterDeskConsole

Key Management

# Backup keys (CRITICAL — losing keys disconnects ALL clients)
cp /opt/rustdesk/id_ed25519 /opt/rustdesk/id_ed25519.backup
cp /opt/rustdesk/id_ed25519.pub /opt/rustdesk/id_ed25519.pub.backup

# Restore keys from automatic backup
BACKUP=$(ls -d /opt/rustdesk-backup-* | sort | tail -1)
sudo cp $BACKUP/id_ed25519* /opt/rustdesk/
sudo chmod 600 /opt/rustdesk/id_ed25519
sudo systemctl restart betterdesk-server

Firewall Configuration

# RustDesk protocol ports (WAN)
sudo ufw allow 21115/tcp    # NAT test
sudo ufw allow 21116/tcp    # Signal (TCP)
sudo ufw allow 21116/udp    # Signal (UDP)
sudo ufw allow 21117/tcp    # Relay
sudo ufw allow 21121/tcp    # RustDesk Client API (login/AB)

# Admin ports (LAN only)
sudo ufw allow from 192.168.0.0/16 to any port 21114 proto tcp  # REST API
sudo ufw allow from 192.168.0.0/16 to any port 5000 proto tcp   # Web Console

🔐 E2E Encryption

Overview

RustDesk clients support end-to-end encryption for remote desktop sessions. BetterDesk Server fully supports this — both P2P (hole-punch) and relay-mode connections establish an encrypted E2E channel with NaCl key exchange.

How It Works

  1. Client A requests connection to Client B via the signal server
  2. Signal server facilitates hole-punching (sends PunchHoleResponse with Client B's public key) or relay setup (sends RelayResponse with relay UUID and SignIdPk credential)
  3. Once connected (P2P or relay), clients perform an asymmetric key exchange using NaCl (Message.SignedId + Message.PublicKey)
  4. All subsequent session traffic (video, audio, clipboard, files) is encrypted end-to-end

Key Implementation Details

ComponentImplementation
PunchHoleResponseIncludes pk field (responder's public key) for E2E handshake initiation
RelayResponseUses SignIdPk() NaCl combined format (64-byte Ed25519 signature + IdPk protobuf)
Relay serverPure opaque byte pipe — does not send its own RelayResponse confirmation, allowing clients to exchange Message.SignedId / Message.PublicKey directly
Transport layerOptional TLS via --tls-relay for defense-in-depth on top of E2E

Verified Behavior

  • Green lock indicator appears in the RustDesk client for all connection modes
  • Message.SignedId + Message.PublicKey handshake confirmed between peers via debug logging
  • Compatible with RustDesk clients v1.1.9+ (standard and custom builds)

🛠️ Technology Stack

BetterDesk Go Server

ComponentTechnology
LanguageGo 1.21+ (pure Go, no CGO)
ProtocolRustDesk rendezvous + relay (protobuf)
CryptoNaCl (Curve25519 + secretbox), Ed25519 (golang.org/x/crypto)
DatabaseSQLite (modernc.org/sqlite), PostgreSQL (pgx/v5 + pgxpool)
WebSocketcoder/websocket
Protobufgoogle.golang.org/protobuf
TLSStandard library crypto/tls (min TLS 1.2)

Web Console (Node.js)

ComponentTechnology
RuntimeNode.js 18+
FrameworkExpress.js
TemplatesEJS
Databasebetter-sqlite3
Authbcrypt + TOTP (otplib)
Securitycsrf-csrf, Helmet, express-rate-limit
Client APIDedicated port with 7-layer security

Frontend

ComponentTechnology
UIHTML5, CSS3 (glassmorphism), JavaScript ES6+
IconsMaterial Icons (offline)
ChartsLive metric bars + history charts
i18nJSON-based translations

DevOps

ComponentTechnology
Linux servicessystemd (betterdesk-server.service + betterdesk-console.service)
Windows servicesNSSM (BetterDeskServer + BetterDeskConsole)
DockerDocker Compose with local image builds
InstallationBash (betterdesk.sh) + PowerShell (betterdesk.ps1) ALL-IN-ONE
CI/CDGitHub Actions (multi-platform build)

🏗️ Building from Source

Go Server

cd betterdesk-server

# Linux (amd64)
CGO_ENABLED=0 go build -ldflags="-s -w" -o betterdesk-server .

# Linux (arm64)
CGO_ENABLED=0 GOARCH=arm64 go build -ldflags="-s -w" -o betterdesk-server-arm64 .

# Windows
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="-s -w" -o betterdesk-server.exe .

Migration Tool

cd betterdesk-server/tools/migrate
go build -o migrate .

Node.js Console

cd web-nodejs
npm install
npm start

🌍 Internationalization (i18n)

BetterDesk Console supports multiple languages through JSON-based translations.

Built-in languages: 🇬🇧 English (default), 🇵🇱 Polish

Adding a new language:

  1. Copy web-nodejs/lang/en.json → web-nodejs/lang/{code}.json
  2. Translate all string values
  3. Update the _meta section with language info
  4. Upload via Settings → Language Settings or place in the lang/ folder

See Contributing Translations for details.


📂 Project Structure

Rustdesk-FreeConsole/
├── betterdesk-server/           # Go server (~20K LOC)
│   ├── main.go                  # Entry point, flags, boot sequence
│   ├── signal/                  # Signal server (UDP/TCP/WS)
│   ├── relay/                   # Relay server (TCP/WS)
│   ├── api/                     # HTTP REST API + auth handlers
│   ├── crypto/                  # Ed25519, NaCl, Curve25519, address codec
│   ├── db/                      # Database interface + SQLite + PostgreSQL
│   ├── config/                  # Configuration, constants, TLS, DualModeListener
│   ├── codec/                   # Wire protocol framing (TCP + WS)
│   ├── peer/                    # Concurrent in-memory peer map (4-tier status)
│   ├── security/                # IP/ID/CIDR blocklist
│   ├── auth/                    # JWT, PBKDF2, RBAC roles, TOTP 2FA
│   ├── ratelimit/               # IP limiter, bandwidth limiter, conn limiter
│   ├── metrics/                 # Prometheus text exposition
│   ├── audit/                   # Ring-buffer audit log
│   ├── events/                  # Pub/sub event bus (11 event types)
│   ├── logging/                 # Text/JSON structured logging
│   ├── admin/                   # TCP management console
│   ├── reload/                  # Hot-reload (SIGHUP / manual)
│   ├── proto/                   # Generated protobuf (rendezvous + message)
│   └── tools/migrate/           # Migration tool (5 modes)
├── web-nodejs/                  # Node.js web console
│   ├── server.js                # Express app (dual port: 5000 + 21121)
│   ├── routes/                  # API routes (panel + Client API)
│   ├── middleware/              # Security, CSRF, WAN, i18n, rate limiting
│   ├── services/                # Auth, DB, WebSocket relay
│   ├── views/                   # EJS templates
│   ├── public/                  # Static assets (CSS, JS)
│   └── lang/                    # i18n translations (EN, PL)
├── betterdesk.sh                # Linux ALL-IN-ONE installer (v2.4.0)
├── betterdesk.ps1               # Windows ALL-IN-ONE installer (v2.4.0)
├── betterdesk-docker.sh         # Docker installer (v2.4.0)
├── docker-compose.yml           # Docker orchestration
├── migrations/                  # Database migration scripts
├── docs/                        # Documentation
├── dev_modules/                 # Development & testing utilities
└── archive/                     # Archived: Rust binaries, Flask console

🤝 Contributing

Contributions are welcome! See CONTRIBUTING.md for guidelines.

Reporting Issues

  1. Run diagnostics: sudo ./betterdesk.sh → option 8
  2. Collect logs: journalctl -u betterdesk-server -n 100
  3. Open a GitHub Issue with system info, logs, and reproduction steps

Pull Requests

  1. Fork → branch (feature/your-feature) → commit → push → PR
  2. Follow existing code style and conventions
  3. Update documentation and i18n keys for new features
  4. Test with real RustDesk clients on both Linux and Windows

📄 License

This project is licensed under the GNU Affero General Public License v3.0 (AGPL-3.0) — see LICENSE.

The Go server is a clean-room implementation. The web console and installation scripts are also AGPL-3.0 for license consistency.


🙏 Credits


📞 Support


Made with ❤️ by UNITRONIX & the community

If you find this project useful, please consider giving it a ⭐ on GitHub!

⬆ Back to Top

Please wait...
Connection lost or session expired, reload to recover
Page is in error, reload to recover