From 8a3ea06c9e011629e0a3a9c807c05a405c65cf98 Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 6 Jun 2026 17:45:19 +0530 Subject: [PATCH 01/26] add CLAUDE.md with project context and protocol notes Co-Authored-By: Claude Opus 4.6 (1M context) --- CLAUDE.md | 137 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 CLAUDE.md diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..e82a155 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,137 @@ +# CLAUDE.md + +## What this is + +Standalone SoftEther VPN client written in Go. Single binary, Linux only, ~2100 LOC. Connects to SoftEther VPN servers using the native protocol over TLS with built-in DHCP, automatic reconnection, and route management. Zero runtime deps beyond `ip` (iproute2). + +**Repo**: `/storage/gitrepos/softether-go/` +**Remote**: `ssh://forgejo@git.sagar.ch:2255/sagar/softether-go.git` + +## Build & test + +```bash +# Build (no Go on this host, use nix-shell) +nix-shell -p go --run "cd /storage/gitrepos/softether-go && CGO_ENABLED=0 go build -o softether-go ./cmd/softether-go/" + +# Nix build +nix build + +# Docker test (staging server) +docker run --rm --cap-add NET_ADMIN --device /dev/net/tun \ + -v /storage/gitrepos/softether-go/softether-go:/usr/bin/softether-go \ + alpine:latest sh -c ' + apk add --no-cache iproute2 curl > /dev/null 2>&1 + softether-go -host 50-117-55-1.ip.fresh.ipb.cloud -port 992 \ + -user b83dsu -pass xrXRYmG9 -plain-password -insecure -tap vpn0 \ + -accept-default-gateway -accept-dns 2>&1 & + sleep 12 && curl -s https://ifconfig.me && echo "" + kill %1; wait' +``` + +## Project structure + +``` +cmd/softether-go/ + main.go Flag parsing, TAP setup, reconnect loop + session.go Session lifecycle (connect → bridge → DHCP → configure), runDHCP + +pkg/client/ + client.go SoftEther handshake: TLS → signature → hello → auth → welcome + tunnel.go TCP block framing, keepalive, Bridge() for bidirectional frame forwarding + crypto.go SHA-0 (not SHA-1) for password hashing + +pkg/protocol/ + http.go TLS connection, HTTP POST for Pack exchange + pack.go Pack binary serialization (SoftEther's wire format) + +pkg/dhcp/ + dhcp.go Raw Ethernet/IP/UDP DHCP client through VPN tunnel + +pkg/netcfg/ + netcfg.go TAP config, routing (default/static/policy), DNS, server host route + +pkg/tap/ + tap.go Linux TAP device via /dev/net/tun (IFF_TAP | IFF_NO_PI) +``` + +## CLI flags + +Required: `-host`, `-user` +Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-dhcp` (true), `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-reconnect-delay` (5s) + +## SoftEther protocol pitfalls + +### Pack element name collision +SoftEther's `AddElement` rejects case-insensitive duplicate names, and `PackRead` returns NULL on failure — **aborting the entire Pack parse**. The auth pack has `hubname` (lowercase, auth field). Do NOT also add `HubName` (node info field) — they collide. The `HubName` line is commented out in `client.go`. + +### Node info LittleEndian32 +`OutRpcNodeInfo` wraps int fields (`ClientProductVer`, `ClientProductBuild`, `ClientPort`, `ServerPort2`, `ProxyPort`) with `LittleEndian32()` before `PackAddInt`. Our Pack writes big-endian ints, so we pre-swap these with `swapLE32()`. Without this, server logs show garbled version numbers. + +### BufStr wire format +`WriteBufStr`: writes `uint32(strlen+1)` then `strlen` bytes — NO null terminator on wire. The +1 in the size field accounts for a logical null, but it's not transmitted. + +### SHA-0 password hashing +SoftEther uses SHA-0 (withdrawn FIPS-180), NOT SHA-1. Only difference: no left-rotate in the message schedule expansion (`W[t] = W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]`, no `rol(1, ...)`). + +### DHCPForce policy +Server drops packets from IPs not in its DhcpAllocated table. On disconnect, server clears ALL MAC/IP entries for the session. Fresh DHCP is required on every reconnect — reusing old IP gets silently dropped. + +### pencore padding +HTTP-transported Packs must include a `pencore` element with random data. Without it, server may reject the Pack. + +## Architecture decisions + +### Bridge starts before DHCP +The frame bridge runs concurrently with DHCP. The DHCP client intercepts server frames via `FeedFrame` callback. Non-DHCP frames go to TAP (OS drops them since TAP has no IP yet). This avoids missing DHCP responses. + +### TAP goroutine leak on disconnect +The TAP→Server goroutine in `Bridge()` blocks on `tapRead` (TAP fd doesn't support `SetReadDeadline`). On disconnect, it survives until the next TAP frame arrives, then `WriteFrames` fails on the closed connection and it exits. Holds 1.6 KB buffer. Not worth adding `poll(2)` complexity. + +### Single TCP connection +`max_connection` is set to 1. SoftEther supports multiple TCP connections for bandwidth aggregation, but this adds complexity for minimal gain on modern connections. + +### Server host route +Before connecting, resolves server hostname and adds `/32` route via current default gateway. Prevents routing loop when `-accept-default-gateway` installs VPN as default route. + +### Policy routing +`-policy-route-table N` adds `ip rule from table N` + `ip route replace default via dev table N`. Needed when VPN server port-forwards to client — ensures reply packets go back through VPN tunnel, not default route. + +## Performance + +- **RAM**: 4.6 MB RSS idle, flat under 97 Mbit/s load (vs SoftEther C client: ~23 MB across 4 processes) +- **Speed**: 97 Mbit/s down, 95 Mbit/s up, 140ms ping (single TCP, Docker, staging server) +- **Binary**: ~7.5 MB static (CGO_ENABLED=0) + +## Test servers + +| Server | Host | Port | User | Pass | Auth | +|---|---|---|---|---|---| +| Staging (US) | 50-117-55-1.ip.fresh.ipb.cloud | 992 | b83dsu | xrXRYmG9 | plain (RADIUS) | +| Production (India) | 65-20-68-5.ip.fresh.ipb.cloud | 992 | T0Eq5yf97gXy8Q | (empty) | plain (RADIUS) | + +The staging user/pass was split from the original username `b83dsuxrXRYmG9` — the SoftEther server patches in softether-5 concatenate username+password when len==14. + +## NixOS integration (pending) + +junto host currently uses the SoftEther C client (`modules/apps/softether-client.nix`). Plan is to replace with softether-go. The C client module config for junto: +- Instance name: `india-pub-ip` +- MAC: `5E-3B-6F-63-A8-3E` (deterministic from sha256 of instance name) +- Policy route table: 200 +- No default gateway (`nogateway`), no DNS override +- dhcpcd with custom script for policy routing + +Equivalent softether-go command: +``` +softether-go -host 65-20-68-5.ip.fresh.ipb.cloud -port 992 \ + -user T0Eq5yf97gXy8Q -plain-password -insecure \ + -tap india-pub-ip -mac 5E:3B:6F:63:A8:3E \ + -policy-route-table 200 +``` + +To add as flake input: `softether-go.url = "git+https://git.sagar.ch/sagar/softether-go.git";` + +## Dependencies + +- Go 1.24+, single dep: `golang.org/x/sys` (vendored) +- Runtime: `ip` (iproute2) +- `vendorHash = null` in flake.nix (deps are vendored) From e33ce4c8ad940d9b5d7e6f959ea9ddb49c6f4ffe Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 6 Jun 2026 17:45:19 +0530 Subject: [PATCH 02/26] add CLAUDE.md with project context and protocol notes Co-Authored-By: Claude Opus 4.6 (1M context) --- CLAUDE.md | 137 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 CLAUDE.md diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..f538ef6 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,137 @@ +# CLAUDE.md + +## What this is + +Standalone SoftEther VPN client written in Go. Single binary, Linux only, ~2100 LOC. Connects to SoftEther VPN servers using the native protocol over TLS with built-in DHCP, automatic reconnection, and route management. Zero runtime deps beyond `ip` (iproute2). + +**Repo**: `/storage/gitrepos/softether-go/` +**Remote**: `ssh://forgejo@git.sagar.ch:2255/sagar/softether-go.git` + +## Build & test + +```bash +# Build (no Go on this host, use nix-shell) +nix-shell -p go --run "cd /storage/gitrepos/softether-go && CGO_ENABLED=0 go build -o softether-go ./cmd/softether-go/" + +# Nix build +nix build + +# Docker test (staging server) +docker run --rm --cap-add NET_ADMIN --device /dev/net/tun \ + -v /storage/gitrepos/softether-go/softether-go:/usr/bin/softether-go \ + alpine:latest sh -c ' + apk add --no-cache iproute2 curl > /dev/null 2>&1 + softether-go -host 50-117-55-1.ip.fresh.ipb.cloud -port 992 \ + -user -pass -plain-password -insecure -tap vpn0 \ + -accept-default-gateway -accept-dns 2>&1 & + sleep 12 && curl -s https://ifconfig.me && echo "" + kill %1; wait' +``` + +## Project structure + +``` +cmd/softether-go/ + main.go Flag parsing, TAP setup, reconnect loop + session.go Session lifecycle (connect → bridge → DHCP → configure), runDHCP + +pkg/client/ + client.go SoftEther handshake: TLS → signature → hello → auth → welcome + tunnel.go TCP block framing, keepalive, Bridge() for bidirectional frame forwarding + crypto.go SHA-0 (not SHA-1) for password hashing + +pkg/protocol/ + http.go TLS connection, HTTP POST for Pack exchange + pack.go Pack binary serialization (SoftEther's wire format) + +pkg/dhcp/ + dhcp.go Raw Ethernet/IP/UDP DHCP client through VPN tunnel + +pkg/netcfg/ + netcfg.go TAP config, routing (default/static/policy), DNS, server host route + +pkg/tap/ + tap.go Linux TAP device via /dev/net/tun (IFF_TAP | IFF_NO_PI) +``` + +## CLI flags + +Required: `-host`, `-user` +Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-dhcp` (true), `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-reconnect-delay` (5s) + +## SoftEther protocol pitfalls + +### Pack element name collision +SoftEther's `AddElement` rejects case-insensitive duplicate names, and `PackRead` returns NULL on failure — **aborting the entire Pack parse**. The auth pack has `hubname` (lowercase, auth field). Do NOT also add `HubName` (node info field) — they collide. The `HubName` line is commented out in `client.go`. + +### Node info LittleEndian32 +`OutRpcNodeInfo` wraps int fields (`ClientProductVer`, `ClientProductBuild`, `ClientPort`, `ServerPort2`, `ProxyPort`) with `LittleEndian32()` before `PackAddInt`. Our Pack writes big-endian ints, so we pre-swap these with `swapLE32()`. Without this, server logs show garbled version numbers. + +### BufStr wire format +`WriteBufStr`: writes `uint32(strlen+1)` then `strlen` bytes — NO null terminator on wire. The +1 in the size field accounts for a logical null, but it's not transmitted. + +### SHA-0 password hashing +SoftEther uses SHA-0 (withdrawn FIPS-180), NOT SHA-1. Only difference: no left-rotate in the message schedule expansion (`W[t] = W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]`, no `rol(1, ...)`). + +### DHCPForce policy +Server drops packets from IPs not in its DhcpAllocated table. On disconnect, server clears ALL MAC/IP entries for the session. Fresh DHCP is required on every reconnect — reusing old IP gets silently dropped. + +### pencore padding +HTTP-transported Packs must include a `pencore` element with random data. Without it, server may reject the Pack. + +## Architecture decisions + +### Bridge starts before DHCP +The frame bridge runs concurrently with DHCP. The DHCP client intercepts server frames via `FeedFrame` callback. Non-DHCP frames go to TAP (OS drops them since TAP has no IP yet). This avoids missing DHCP responses. + +### TAP goroutine leak on disconnect +The TAP→Server goroutine in `Bridge()` blocks on `tapRead` (TAP fd doesn't support `SetReadDeadline`). On disconnect, it survives until the next TAP frame arrives, then `WriteFrames` fails on the closed connection and it exits. Holds 1.6 KB buffer. Not worth adding `poll(2)` complexity. + +### Single TCP connection +`max_connection` is set to 1. SoftEther supports multiple TCP connections for bandwidth aggregation, but this adds complexity for minimal gain on modern connections. + +### Server host route +Before connecting, resolves server hostname and adds `/32` route via current default gateway. Prevents routing loop when `-accept-default-gateway` installs VPN as default route. + +### Policy routing +`-policy-route-table N` adds `ip rule from table N` + `ip route replace default via dev table N`. Needed when VPN server port-forwards to client — ensures reply packets go back through VPN tunnel, not default route. + +## Performance + +- **RAM**: 4.6 MB RSS idle, flat under 97 Mbit/s load (vs SoftEther C client: ~23 MB across 4 processes) +- **Speed**: 97 Mbit/s down, 95 Mbit/s up, 140ms ping (single TCP, Docker, staging server) +- **Binary**: ~7.5 MB static (CGO_ENABLED=0) + +## Test servers + +| Server | Host | Port | User | Pass | Auth | +|---|---|---|---|---|---| +| Staging (US) | 50-117-55-1.ip.fresh.ipb.cloud | 992 | `` | `` | plain (RADIUS) | +| Production (India) | 65-20-68-5.ip.fresh.ipb.cloud | 992 | `` | `` | plain (RADIUS) | + +Credentials are not kept in this repo: take the username and password of a test service from WHMCS. The SoftEther server patches in softether-5 concatenate username+password when len==14, so a 14-character key can be given as the username with an empty password. + +## NixOS integration (pending) + +junto host currently uses the SoftEther C client (`modules/apps/softether-client.nix`). Plan is to replace with softether-go. The C client module config for junto: +- Instance name: `india-pub-ip` +- MAC: `5E-3B-6F-63-A8-3E` (deterministic from sha256 of instance name) +- Policy route table: 200 +- No default gateway (`nogateway`), no DNS override +- dhcpcd with custom script for policy routing + +Equivalent softether-go command: +``` +softether-go -host 65-20-68-5.ip.fresh.ipb.cloud -port 992 \ + -user -plain-password -insecure \ + -tap india-pub-ip -mac 5E:3B:6F:63:A8:3E \ + -policy-route-table 200 +``` + +To add as flake input: `softether-go.url = "git+https://git.sagar.ch/sagar/softether-go.git";` + +## Dependencies + +- Go 1.24+, single dep: `golang.org/x/sys` (vendored) +- Runtime: `ip` (iproute2) +- `vendorHash = null` in flake.nix (deps are vendored) From 42f83337837ccc0ec5651759974a58f5d422563d Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 6 Jun 2026 17:53:01 +0530 Subject: [PATCH 03/26] rename -dhcp flag to -no-dhcp for cleaner UX DHCP is on by default; use -no-dhcp to disable. Co-Authored-By: Claude Opus 4.6 (1M context) --- CLAUDE.md | 2 +- cmd/softether-go/main.go | 4 ++-- docs/usage.md | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index e82a155..5bd87a0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,7 +57,7 @@ pkg/tap/ ## CLI flags Required: `-host`, `-user` -Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-dhcp` (true), `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-reconnect-delay` (5s) +Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-no-dhcp`, `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-reconnect-delay` (5s) ## SoftEther protocol pitfalls diff --git a/cmd/softether-go/main.go b/cmd/softether-go/main.go index 642b9db..b00bc8b 100644 --- a/cmd/softether-go/main.go +++ b/cmd/softether-go/main.go @@ -30,7 +30,7 @@ func main() { tapName := flag.String("tap", "", "TAP interface name (empty = kernel-assigned)") macAddr := flag.String("mac", "", "TAP interface MAC address (e.g. 5E:3B:6F:63:A8:3E)") insecure := flag.Bool("insecure", false, "Skip TLS certificate verification") - dhcpEnabled := flag.Bool("dhcp", true, "Run built-in DHCP client after connecting") + noDHCP := flag.Bool("no-dhcp", false, "Disable built-in DHCP client") reconnectDelay := flag.Duration("reconnect-delay", 5*time.Second, "Delay between reconnection attempts") acceptDefaultGW := flag.Bool("accept-default-gateway", false, "Install DHCP-provided gateway as default route") acceptStaticRoutes := flag.Bool("accept-static-routes", false, "Install DHCP classless static routes (option 121/249)") @@ -89,7 +89,7 @@ func main() { signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) netOpts := netcfg.Options{ - DHCP: *dhcpEnabled, + DHCP: !*noDHCP, AcceptDefaultGW: *acceptDefaultGW, AcceptStaticRoutes: *acceptStaticRoutes, AcceptDNS: *acceptDNS, diff --git a/docs/usage.md b/docs/usage.md index e8c31e7..02ceb46 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -22,7 +22,7 @@ softether-go [flags] | `-mac` | *(auto)* | TAP interface MAC address (e.g. `5E:3B:6F:63:A8:3E`) | | `-plain-password` | `false` | Send password as plaintext (AuthType 2, for RADIUS/external auth) | | `-insecure` | `false` | Skip TLS certificate verification | -| `-dhcp` | `true` | Run built-in DHCP client after connecting | +| `-no-dhcp` | `false` | Disable built-in DHCP client | | `-accept-default-gateway` | `false` | Install DHCP-provided gateway as default route | | `-accept-static-routes` | `false` | Install DHCP classless static routes (option 121/249) | | `-accept-dns` | `false` | Set `/etc/resolv.conf` from DHCP-provided DNS servers | @@ -57,9 +57,9 @@ Sets a specific MAC address on the TAP interface before connecting. Useful for d softether-go -host vpn.example.com -user admin -mac 5E:3B:6F:63:A8:3E ``` -### `-dhcp` +### `-no-dhcp` -Enabled by default. Runs the built-in DHCP client through the VPN tunnel after connecting. Disable with `-dhcp=false` if the TAP interface will be configured manually or by an external DHCP client. +Disables the built-in DHCP client. Use this if the TAP interface will be configured manually or by an external DHCP client. ### `-accept-default-gateway` @@ -117,7 +117,7 @@ softether-go \ No DHCP (manual configuration): ```bash -softether-go -host vpn.example.com -user admin -pass secret -dhcp=false -tap vpn0 +softether-go -host vpn.example.com -user admin -pass secret -no-dhcp -tap vpn0 ``` ## Docker From a9b8e639bbbb7b0bc7c0a16965c00974ec50a26b Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 6 Jun 2026 17:53:01 +0530 Subject: [PATCH 04/26] rename -dhcp flag to -no-dhcp for cleaner UX DHCP is on by default; use -no-dhcp to disable. Co-Authored-By: Claude Opus 4.6 (1M context) --- CLAUDE.md | 2 +- cmd/softether-go/main.go | 4 ++-- docs/usage.md | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index f538ef6..27732a3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,7 +57,7 @@ pkg/tap/ ## CLI flags Required: `-host`, `-user` -Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-dhcp` (true), `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-reconnect-delay` (5s) +Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-no-dhcp`, `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-reconnect-delay` (5s) ## SoftEther protocol pitfalls diff --git a/cmd/softether-go/main.go b/cmd/softether-go/main.go index 642b9db..b00bc8b 100644 --- a/cmd/softether-go/main.go +++ b/cmd/softether-go/main.go @@ -30,7 +30,7 @@ func main() { tapName := flag.String("tap", "", "TAP interface name (empty = kernel-assigned)") macAddr := flag.String("mac", "", "TAP interface MAC address (e.g. 5E:3B:6F:63:A8:3E)") insecure := flag.Bool("insecure", false, "Skip TLS certificate verification") - dhcpEnabled := flag.Bool("dhcp", true, "Run built-in DHCP client after connecting") + noDHCP := flag.Bool("no-dhcp", false, "Disable built-in DHCP client") reconnectDelay := flag.Duration("reconnect-delay", 5*time.Second, "Delay between reconnection attempts") acceptDefaultGW := flag.Bool("accept-default-gateway", false, "Install DHCP-provided gateway as default route") acceptStaticRoutes := flag.Bool("accept-static-routes", false, "Install DHCP classless static routes (option 121/249)") @@ -89,7 +89,7 @@ func main() { signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) netOpts := netcfg.Options{ - DHCP: *dhcpEnabled, + DHCP: !*noDHCP, AcceptDefaultGW: *acceptDefaultGW, AcceptStaticRoutes: *acceptStaticRoutes, AcceptDNS: *acceptDNS, diff --git a/docs/usage.md b/docs/usage.md index e8c31e7..02ceb46 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -22,7 +22,7 @@ softether-go [flags] | `-mac` | *(auto)* | TAP interface MAC address (e.g. `5E:3B:6F:63:A8:3E`) | | `-plain-password` | `false` | Send password as plaintext (AuthType 2, for RADIUS/external auth) | | `-insecure` | `false` | Skip TLS certificate verification | -| `-dhcp` | `true` | Run built-in DHCP client after connecting | +| `-no-dhcp` | `false` | Disable built-in DHCP client | | `-accept-default-gateway` | `false` | Install DHCP-provided gateway as default route | | `-accept-static-routes` | `false` | Install DHCP classless static routes (option 121/249) | | `-accept-dns` | `false` | Set `/etc/resolv.conf` from DHCP-provided DNS servers | @@ -57,9 +57,9 @@ Sets a specific MAC address on the TAP interface before connecting. Useful for d softether-go -host vpn.example.com -user admin -mac 5E:3B:6F:63:A8:3E ``` -### `-dhcp` +### `-no-dhcp` -Enabled by default. Runs the built-in DHCP client through the VPN tunnel after connecting. Disable with `-dhcp=false` if the TAP interface will be configured manually or by an external DHCP client. +Disables the built-in DHCP client. Use this if the TAP interface will be configured manually or by an external DHCP client. ### `-accept-default-gateway` @@ -117,7 +117,7 @@ softether-go \ No DHCP (manual configuration): ```bash -softether-go -host vpn.example.com -user admin -pass secret -dhcp=false -tap vpn0 +softether-go -host vpn.example.com -user admin -pass secret -no-dhcp -tap vpn0 ``` ## Docker From 61237283f50dac6f8debd36c30db49f8d13bb14e Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 6 Jun 2026 17:54:38 +0530 Subject: [PATCH 05/26] consolidate docs into README.md, remove docs/ Co-Authored-By: Claude Opus 4.6 (1M context) --- README.md | 264 ++++++++++++++++++++++++++++++++++++++++--- docs/architecture.md | 149 ------------------------ docs/building.md | 54 --------- docs/main.md | 29 ----- docs/structure.md | 63 ----------- docs/usage.md | 143 ----------------------- 6 files changed, 248 insertions(+), 454 deletions(-) delete mode 100644 docs/architecture.md delete mode 100644 docs/building.md delete mode 100644 docs/main.md delete mode 100644 docs/structure.md delete mode 100644 docs/usage.md diff --git a/README.md b/README.md index 11159a1..85b84fc 100644 --- a/README.md +++ b/README.md @@ -2,29 +2,261 @@ Standalone SoftEther VPN client written in Go. Connects to SoftEther VPN servers using the native protocol over TLS, with built-in DHCP, automatic reconnection, and route management. Single static binary, Linux only, zero runtime dependencies beyond `ip` (iproute2). -## Quick start +## Features + +- Native SoftEther protocol (TLS + HTTP handshake + TCP block framing) +- Built-in DHCP client (raw Ethernet frame construction through the VPN tunnel) +- Automatic reconnection with fresh DHCP on each reconnect +- Host route to VPN server via existing default gateway (prevents routing loops) +- Classless static routes (DHCP option 121/249, RFC 3442) +- Policy routing for asymmetric return paths (VPN port forwards) +- DNS configuration from DHCP lease (backup/restore of `/etc/resolv.conf`) +- Deterministic MAC address support for stable DHCP assignments +- Hashed password (SHA-0) and plaintext password (RADIUS/external) authentication +- ~4.6 MB RAM under load, single process + +## Requirements + +- Linux (uses `/dev/net/tun` for TAP devices) +- `CAP_NET_ADMIN` or root (TAP device creation, route management) +- `ip` command (iproute2) on `$PATH` + +## Building + +Requires Go 1.24 or later. ```bash -# Build go build -o softether-go ./cmd/softether-go/ - -# Connect (minimal) -softether-go -host vpn.example.com -user admin -pass secret -plain-password - -# Connect with full network setup -softether-go -host vpn.example.com -user admin -pass secret \ - -plain-password -tap vpn0 -mac 5E:3B:6F:63:A8:3E \ - -accept-default-gateway -accept-dns -policy-route-table 200 ``` -## Documentation +Static binary (for Alpine, scratch containers): -See [docs/main.md](docs/main.md) for full documentation: +```bash +CGO_ENABLED=0 go build -o softether-go ./cmd/softether-go/ +``` -- [Usage & CLI reference](docs/usage.md) -- [How it works](docs/architecture.md) -- [Building](docs/building.md) -- [Project structure](docs/structure.md) +Cross-compilation: + +```bash +CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o softether-go ./cmd/softether-go/ +``` + +Nix: + +```bash +nix build # result in ./result/bin/softether-go +nix develop # dev shell with Go tooling +``` + +The only Go dependency is `golang.org/x/sys` (vendored in `vendor/`). + +## Usage + +``` +softether-go [flags] +``` + +### Required flags + +| Flag | Description | +|---|---| +| `-host` | SoftEther server hostname or IP | +| `-user` | Authentication username | + +### Optional flags + +| Flag | Default | Description | +|---|---|---| +| `-pass` | `""` | Authentication password | +| `-port` | `443` | Server port | +| `-hub` | `DEFAULT` | Virtual hub name | +| `-tap` | *(auto)* | TAP interface name (kernel-assigned if empty) | +| `-mac` | *(auto)* | TAP interface MAC address (e.g. `5E:3B:6F:63:A8:3E`) | +| `-plain-password` | `false` | Send password as plaintext (AuthType 2, for RADIUS/external auth) | +| `-insecure` | `false` | Skip TLS certificate verification | +| `-no-dhcp` | `false` | Disable built-in DHCP client | +| `-accept-default-gateway` | `false` | Install DHCP-provided gateway as default route | +| `-accept-static-routes` | `false` | Install DHCP classless static routes (option 121/249) | +| `-accept-dns` | `false` | Set `/etc/resolv.conf` from DHCP-provided DNS servers | +| `-policy-route-table` | `0` | Policy routing table number (0 = disabled) | +| `-reconnect-delay` | `5s` | Delay between reconnection attempts | + +### Authentication + +**Hashed password (AuthType 1)** — the default. Password is hashed with SHA-0 and combined with the server's random challenge. Used for local user accounts. + +```bash +softether-go -host vpn.example.com -user admin -pass secret +``` + +**Plaintext password (AuthType 2)** — enabled with `-plain-password`. Password sent as-is over TLS. Used for RADIUS/external auth. + +```bash +softether-go -host vpn.example.com -user admin -pass secret -plain-password +``` + +### Network configuration + +**`-mac`** — sets a specific MAC for deterministic DHCP assignments across reconnects. + +**`-accept-default-gateway`** — installs DHCP gateway as default route (metric 50). A `/32` host route to the VPN server via the original gateway prevents routing loops. + +**`-accept-static-routes`** — installs classless static routes from DHCP option 121/249. A `0.0.0.0/0` entry is only installed if `-accept-default-gateway` is also set. + +**`-accept-dns`** — overwrites `/etc/resolv.conf` with DHCP DNS servers. Original is backed up and restored on disconnect. + +**`-policy-route-table N`** — policy routing for asymmetric return paths. Adds `ip rule from table N` and `ip route replace default via dev table N`. Needed when the VPN server forwards ports to the client. + +### Examples + +Minimal: +```bash +softether-go -host vpn.example.com -user admin -pass secret +``` + +Full setup: +```bash +softether-go \ + -host vpn.example.com \ + -port 992 \ + -user admin \ + -pass secret \ + -plain-password \ + -tap vpn0 \ + -mac 5E:3B:6F:63:A8:3E \ + -insecure \ + -accept-default-gateway \ + -accept-static-routes \ + -accept-dns \ + -policy-route-table 200 +``` + +No DHCP (manual config): +```bash +softether-go -host vpn.example.com -user admin -pass secret -no-dhcp -tap vpn0 +``` + +### Docker + +```bash +docker run --rm -it \ + --cap-add NET_ADMIN \ + --device /dev/net/tun \ + -v ./softether-go:/usr/bin/softether-go \ + alpine \ + softether-go -host vpn.example.com -user admin -pass secret \ + -plain-password -insecure -tap vpn0 \ + -accept-default-gateway -accept-dns +``` + +Container needs `iproute2` (`apk add iproute2` on Alpine). + +### Signals + +- **SIGINT / SIGTERM** — clean shutdown: closes tunnel, flushes TAP, restores DNS, removes routes +- During reconnect delay, signal triggers immediate shutdown + +## Architecture + +### Connection flow + +``` +Client Server + │ │ + ├──── TLS handshake ───────────────────►│ Standard TLS, looks like HTTPS + │ │ + ├──── POST /vpnsvc/connect.cgi ────────►│ Upload signature ("VPNCONNECT") + │ │ + │◄──── HTTP 200 (Pack: hello) ──────────┤ Server version + random challenge + │ │ + ├──── POST /vpnsvc/vpn.cgi ───────────►│ Upload auth (credentials + metadata) + │ │ + │◄──── HTTP 200 (Pack: welcome) ────────┤ Session info (or error code) + │ │ + │◄────── TCP block framing ────────────►│ Ethernet frames + keepalive + │ │ +``` + +1. **TLS connect** — standard TLS to the server port (typically 443 or 992) +2. **Upload signature** — `VPNCONNECT` via HTTP POST to `/vpnsvc/connect.cgi` +3. **Download Hello** — server sends version info and 20-byte random challenge +4. **Upload Auth** — credentials, client version, connection options, node info as a Pack +5. **Download Welcome** — session info on success, error code on failure +6. **Tunnel mode** — raw TCP block framing: `uint32(numBlocks) + [uint32(size) + data]...`. Keepalive: `uint32(0xFFFFFFFF) + uint32(randSize) + randData` + +### Session lifecycle + +1. **Start bridge** — bidirectional frame forwarding begins immediately +2. **DHCP exchange** — DHCP frames sent through tunnel while bridge runs. DHCP client intercepts server frames via `FeedFrame` callback +3. **Configure TAP** — IP, routes, DNS, policy routing applied from lease +4. **Wait** — blocks until bridge errors or signal arrives +5. **Cleanup** — flush addresses, restore DNS, remove policy routes +6. **Reconnect** — wait, then repeat with fresh handshake and DHCP + +### DHCP through the tunnel + +SoftEther operates at Layer 2. The built-in DHCP client constructs complete Ethernet/IP/UDP/DHCP frames sent through the tunnel: + +``` +DHCP Client VPN Tunnel DHCP Server (on VPN) + │ │ │ + ├── DISCOVER ──► WriteFrames ├────────────────────────────►│ + │ │ │ + │◄── FeedFrame ◄─ ReadFrames ◄──────── OFFER ─────────────┤ + │ │ │ + ├── REQUEST ───► WriteFrames ├────────────────────────────►│ + │ │ │ + │◄── FeedFrame ◄─ ReadFrames ◄──────── ACK ───────────────┤ + │ │ │ +``` + +DHCP options requested: subnet mask (1), router (3), DNS (6), lease time (51), classless static routes (121/249). + +**Why fresh DHCP on reconnect**: SoftEther's `DHCPForce` policy drops packets from IPs not in its `DhcpAllocated` table. On disconnect, the server clears all entries for the session. + +### Routing + +**Server host route** — `/32` route to VPN server via current default gateway, added before first connection. Prevents routing loop when VPN becomes default route. + +**Default gateway** — DHCP gateway installed with metric 50, lower than existing default routes. + +**Static routes** — classless routes from option 121/249. Default route entries (`0.0.0.0/0`) only installed with `-accept-default-gateway`. + +**Policy routing** — `ip rule from table N` ensures reply packets for VPN port forwards go back through the tunnel, not the default route. + +### Password hashing + +SoftEther uses **SHA-0** (not SHA-1) — no left-rotate in message schedule. `HashedPassword = SHA0(password)`, `SecurePassword = SHA0(HashedPassword + ServerRandom)`. Plaintext auth (AuthType 2) sends password as-is over TLS. + +### Keepalive + +Sent every 3 seconds: `uint32(0xFFFFFFFF) + uint32(randSize) + randData`. Silently consumed, never forwarded to TAP. + +## Project structure + +``` +cmd/softether-go/ + main.go Flag parsing, TAP setup, reconnect loop + session.go Session lifecycle, DHCP orchestration + +pkg/client/ + client.go SoftEther handshake and session + tunnel.go TCP block framing, keepalive, frame bridging + crypto.go SHA-0 and password hashing + +pkg/protocol/ + http.go TLS connection, HTTP transport layer + pack.go Pack binary serialization + +pkg/dhcp/ + dhcp.go DHCP client (raw Ethernet frames) + +pkg/netcfg/ + netcfg.go TAP configuration, routing, DNS management + +pkg/tap/ + tap.go Linux TAP device management +``` ## License diff --git a/docs/architecture.md b/docs/architecture.md deleted file mode 100644 index abe1437..0000000 --- a/docs/architecture.md +++ /dev/null @@ -1,149 +0,0 @@ -# Architecture - -## Connection flow - -The SoftEther protocol layers HTTP over TLS, then switches to raw TCP framing for the data tunnel. - -``` -Client Server - │ │ - ├──── TLS handshake ───────────────────►│ Standard TLS, looks like HTTPS - │ │ - ├──── POST /vpnsvc/connect.cgi ────────►│ Upload signature ("VPNCONNECT") - │ │ - │◄──── HTTP 200 (Pack: hello) ──────────┤ Server version + random challenge - │ │ - ├──── POST /vpnsvc/vpn.cgi ───────────►│ Upload auth (credentials + metadata) - │ │ - │◄──── HTTP 200 (Pack: welcome) ────────┤ Session info (or error code) - │ │ - │◄────── TCP block framing ────────────►│ Ethernet frames + keepalive - │ │ -``` - -### Step details - -1. **TLS connect** — standard TLS to the server port (typically 443 or 992). The connection looks like normal HTTPS traffic to network observers. - -2. **Upload signature** — the client sends `VPNCONNECT` as the body of an HTTP POST to `/vpnsvc/connect.cgi`. The server validates this to confirm the client speaks the SoftEther protocol. - -3. **Download Hello** — the server responds with a binary Pack containing its version info and a 20-byte random challenge used for password hashing. - -4. **Upload Auth** — the client sends credentials (hashed or plaintext password), client version, connection options, and node info as a Pack via HTTP POST to `/vpnsvc/vpn.cgi`. - -5. **Download Welcome** — the server responds with session info (session name, connection name, session key, policies) on success, or an error code on failure. - -6. **Tunnel mode** — the connection switches from HTTP to raw TCP block framing. Each message is `uint32(numBlocks) + [uint32(size) + data]...`. Keepalive packets use `0xFFFFFFFF` as the block count, followed by random padding. - -## Pack format - -SoftEther uses a custom binary serialization called "Pack" for all structured data exchange. A Pack contains named Elements, each holding typed Values (int, string, data, ip4). - -Key details: -- Element names are **case-insensitive** (compared with `StrCmpi`) -- `AddElement` rejects duplicate names — the second add silently fails -- String values use BufStr encoding: `uint32(strlen+1)` followed by `strlen` bytes (no null terminator on wire) -- HTTP-transported Packs include a `pencore` dummy element with random padding - -## Session lifecycle - -After connecting, a session proceeds as: - -1. **Start bridge** — bidirectional frame forwarding between the tunnel and TAP device begins immediately in the background -2. **DHCP exchange** — if enabled, DHCP frames are sent through the tunnel while the bridge is already running. The DHCP client intercepts server frames via a callback (`FeedFrame`) before they reach the TAP device -3. **Configure TAP** — IP address, routes, DNS, and policy routing are applied from the DHCP lease -4. **Wait** — the session blocks until the bridge errors (server disconnect, network failure) or a signal arrives -5. **Cleanup** — TAP addresses are flushed, DNS is restored, policy routes are removed - -On disconnect, the reconnect loop waits and starts a new session with a fresh handshake and DHCP exchange. - -## DHCP through the tunnel - -SoftEther operates at Layer 2 — the tunnel carries raw Ethernet frames. The built-in DHCP client constructs complete Ethernet/IP/UDP/DHCP frames and sends them through the tunnel's frame transport. - -``` -DHCP Client VPN Tunnel DHCP Server (on VPN) - │ │ │ - ├── DISCOVER ──► WriteFrames ├────────────────────────────►│ - │ │ │ - │◄── FeedFrame ◄─ ReadFrames ◄──────── OFFER ─────────────┤ - │ │ │ - ├── REQUEST ───► WriteFrames ├────────────────────────────►│ - │ │ │ - │◄── FeedFrame ◄─ ReadFrames ◄──────── ACK ───────────────┤ - │ │ │ -``` - -The frame bridge runs concurrently with the DHCP exchange. All server frames pass through the `FeedFrame` callback, which identifies DHCP responses by transaction ID. Non-DHCP frames are written to the TAP device as normal (though the TAP has no IP yet, so the OS drops them). - -### Why raw frames? - -The VPN tunnel transports Ethernet frames, and the DHCP exchange must happen *inside* the tunnel before the TAP interface has an IP address. Constructing frames directly avoids any external dependency (`dhcpcd`, `udhcpc`) and keeps the client self-contained. - -### DHCP options requested - -- Option 1: Subnet Mask -- Option 3: Router (gateway) -- Option 6: DNS Servers -- Option 51: Lease Time -- Option 121: Classless Static Routes (RFC 3442) -- Option 249: Microsoft Classless Static Routes - -### Why DHCP is required on reconnect - -SoftEther servers with `DHCPForce` policy discard any packet whose source IP is not in the server's IP table with `DhcpAllocated=true`. When a session disconnects, the server calls `HubPaFree` which deletes **all** MAC and IP table entries for that session. The new session has no entries, so all traffic is dropped until a fresh DHCP exchange creates a new `DhcpAllocated=true` entry. - -## Routing - -### Server host route - -Before the first connection, the client resolves the server hostname and adds a `/32` host route via the current default gateway: - -``` -50.117.55.1/32 via 172.17.0.1 dev eth0 -``` - -This ensures the VPN tunnel traffic itself always uses the original path, even after `-accept-default-gateway` installs a new default route via the VPN. - -### Default gateway - -With `-accept-default-gateway`, the DHCP-provided gateway is installed as a default route with metric 50: - -``` -default via 10.100.8.1 dev vpn0 metric 50 -``` - -The metric ensures it takes precedence over any existing default route with a higher metric, while the server host route (no metric, most specific) keeps the tunnel traffic on the original path. - -### Static routes - -With `-accept-static-routes`, classless static routes from DHCP option 121 or 249 are installed. A `0.0.0.0/0` entry in static routes is treated as a default gateway and only installed if `-accept-default-gateway` is also set. Per RFC 3442, option 121 takes precedence over option 3 (Router) when present. - -### Policy routing - -With `-policy-route-table N`, the client sets up policy routing for asymmetric return paths: - -``` -ip route replace default via dev table N -ip rule add from table N -``` - -This is needed when the VPN server has port forwards to the client. Without policy routing, inbound traffic arrives via the VPN tunnel but reply packets use the default route (home router) instead of going back through the tunnel. The remote host sees replies from a different IP and drops them. - -The policy route is cleaned up on disconnect and re-applied with each new DHCP lease (since the VPN IP may change). - -## Keepalive - -The client sends keepalive packets every 3 seconds. A keepalive is `uint32(0xFFFFFFFF) + uint32(randSize) + randData`. The server sends keepalives in the same format. Keepalive packets are silently consumed and never forwarded to the TAP device. - -## Password hashing - -SoftEther uses **SHA-0** (not SHA-1) for password hashing. SHA-0 differs from SHA-1 only in the message schedule — there is no left-rotate of the W[t] values. - -For hashed password auth (AuthType 1): -``` -HashedPassword = SHA0(password) -SecurePassword = SHA0(HashedPassword + ServerRandom) -``` - -For plaintext auth (AuthType 2), the password is sent as-is over the TLS connection. diff --git a/docs/building.md b/docs/building.md deleted file mode 100644 index 53f0d43..0000000 --- a/docs/building.md +++ /dev/null @@ -1,54 +0,0 @@ -# Building - -## Go - -Requires Go 1.24 or later. - -```bash -go build -o softether-go ./cmd/softether-go/ -``` - -### Static binary - -For deployment in minimal containers (Alpine, scratch) or systems without glibc: - -```bash -CGO_ENABLED=0 go build -o softether-go ./cmd/softether-go/ -``` - -### Cross-compilation - -```bash -CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o softether-go ./cmd/softether-go/ -CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o softether-go ./cmd/softether-go/ -``` - -Only Linux targets are supported (the TAP device interface uses Linux-specific ioctls). - -## Nix - -Build with the flake: - -```bash -nix build -``` - -The result is in `./result/bin/softether-go`. - -Enter a development shell with Go tooling: - -```bash -nix develop -``` - -Build within the dev shell: - -```bash -nix develop -c bash -c 'go build -o softether-go ./cmd/softether-go/' -``` - -## Dependencies - -The only Go dependency is `golang.org/x/sys` for Linux syscall constants (TUN/TAP ioctls). Dependencies are vendored in `vendor/`. - -At runtime, the only external dependency is `ip` (iproute2) for route and address management. diff --git a/docs/main.md b/docs/main.md deleted file mode 100644 index 744a6fc..0000000 --- a/docs/main.md +++ /dev/null @@ -1,29 +0,0 @@ -# softether-go documentation - -Standalone SoftEther VPN client written in Go. Connects to SoftEther VPN servers using the native protocol over TLS, with built-in DHCP, automatic reconnection, and route management. - -## Features - -- Native SoftEther protocol (TLS + HTTP handshake + TCP block framing) -- Built-in DHCP client (raw Ethernet frame construction through the VPN tunnel) -- Automatic reconnection with fresh DHCP on each reconnect -- Host route to VPN server via existing default gateway (prevents routing loops) -- Classless static routes (DHCP option 121/249, RFC 3442) -- Policy routing for asymmetric return paths (VPN port forwards) -- DNS configuration from DHCP lease (backup/restore of `/etc/resolv.conf`) -- Deterministic MAC address support for stable DHCP assignments -- Hashed password (SHA-0) and plaintext password (RADIUS/external) authentication -- Single static binary, Linux only - -## Contents - -- [Usage & CLI reference](usage.md) — flags, examples, Docker usage -- [Architecture](architecture.md) — connection flow, DHCP, reconnection, routing -- [Building](building.md) — Go, Nix, static builds -- [Project structure](structure.md) — source layout and package descriptions - -## Requirements - -- Linux (uses `/dev/net/tun` for TAP devices) -- `CAP_NET_ADMIN` or root (TAP device creation, route management) -- `ip` command (iproute2) on `$PATH` diff --git a/docs/structure.md b/docs/structure.md deleted file mode 100644 index fd70c86..0000000 --- a/docs/structure.md +++ /dev/null @@ -1,63 +0,0 @@ -# Project structure - -``` -softether-go/ -├── cmd/softether-go/ -│ ├── main.go Flag parsing, TAP setup, reconnect loop -│ └── session.go Session lifecycle, DHCP orchestration -├── pkg/ -│ ├── client/ -│ │ ├── client.go SoftEther handshake and session -│ │ ├── tunnel.go TCP block framing, keepalive, frame bridging -│ │ └── crypto.go SHA-0 and password hashing -│ ├── protocol/ -│ │ ├── http.go TLS connection, HTTP transport layer -│ │ └── pack.go Pack binary serialization -│ ├── dhcp/ -│ │ └── dhcp.go DHCP client (raw Ethernet frames) -│ ├── netcfg/ -│ │ └── netcfg.go TAP configuration, routing, DNS management -│ └── tap/ -│ └── tap.go Linux TAP device management -├── docs/ Documentation -├── vendor/ Vendored Go dependencies -├── flake.nix Nix build definition -├── go.mod -└── go.sum -``` - -## Package details - -### `cmd/softether-go` - -CLI entry point, split into two files: - -**`main.go`** — flag parsing, TAP device creation, MAC configuration, signal handling, and the reconnect loop. Calls `runSession` for each connection attempt. - -**`session.go`** — one VPN session lifecycle: connect to server, start bridge, run DHCP, configure TAP (IP/routes/DNS/policy routing), and wait for disconnect or signal. Also contains `runDHCP` which orchestrates the DHCP exchange through the tunnel. - -### `pkg/client` - -**`client.go`** — implements the SoftEther handshake: TLS connect, signature upload, hello/auth/welcome pack exchange. Exports `Connect(Config) (*Session, error)` and the `Config`/`Session` types. - -**`tunnel.go`** — TCP block framing after the HTTP handshake completes. `ReadFrames()` reads batches of Ethernet frames from the server. `WriteFrames()` sends batches. `Bridge()` runs bidirectional frame forwarding between the tunnel and a TAP device, with an optional `FrameHandler` callback for intercepting frames (used by DHCP). `StartKeepalive()` sends periodic keepalive packets (every 3s). - -**`crypto.go`** — SHA-0 implementation (differs from SHA-1 only in the message schedule — no left-rotate). `HashPassword()` produces `SHA0(password)`. `SecurePassword()` produces `SHA0(hashed + serverRandom)`. - -### `pkg/protocol` - -**`http.go`** — HTTP transport layer. `DialTLS()` establishes the TLS connection. `UploadSignature()` sends the protocol signature. `SendPack()` and `RecvPack()` exchange binary Packs as HTTP POST request/response bodies. - -**`pack.go`** — SoftEther Pack binary serialization. A Pack is a list of named Elements, each containing typed Values (int, string, data, ip4). Handles the BufStr wire format (`uint32(strlen+1)` then `strlen` bytes) and the `pencore` random padding element. - -### `pkg/dhcp` - -**`dhcp.go`** — DHCP client that constructs complete Ethernet/IP/UDP/DHCP frames. The full DHCP exchange (DISCOVER → OFFER → REQUEST → ACK) runs through the VPN tunnel's frame transport. Parses lease information including classless static routes (option 121/249, RFC 3442). - -### `pkg/netcfg` - -**`netcfg.go`** — network configuration for the VPN tunnel. `ConfigureTAP()` sets IP address, routes, and DNS on the TAP interface from a DHCP lease. `ConfigurePolicyRoute()` sets up policy routing for asymmetric return paths. `AddServerRoute()` adds a host route to the VPN server via the current default gateway. `ResolveHost()` resolves hostnames to IPv4. - -### `pkg/tap` - -**`tap.go`** — Linux TAP (Layer 2) device management via `/dev/net/tun`. Opens TAP devices with `IFF_TAP | IFF_NO_PI`, reads/writes raw Ethernet frames. Provides `MAC()` and `SetMAC()` for hardware address management, and `SetUp()` to bring the interface up. diff --git a/docs/usage.md b/docs/usage.md deleted file mode 100644 index 02ceb46..0000000 --- a/docs/usage.md +++ /dev/null @@ -1,143 +0,0 @@ -# Usage - -``` -softether-go [flags] -``` - -## Required flags - -| Flag | Description | -|---|---| -| `-host` | SoftEther server hostname or IP | -| `-user` | Authentication username | - -## Optional flags - -| Flag | Default | Description | -|---|---|---| -| `-pass` | `""` | Authentication password | -| `-port` | `443` | Server port | -| `-hub` | `DEFAULT` | Virtual hub name | -| `-tap` | *(auto)* | TAP interface name (kernel-assigned if empty) | -| `-mac` | *(auto)* | TAP interface MAC address (e.g. `5E:3B:6F:63:A8:3E`) | -| `-plain-password` | `false` | Send password as plaintext (AuthType 2, for RADIUS/external auth) | -| `-insecure` | `false` | Skip TLS certificate verification | -| `-no-dhcp` | `false` | Disable built-in DHCP client | -| `-accept-default-gateway` | `false` | Install DHCP-provided gateway as default route | -| `-accept-static-routes` | `false` | Install DHCP classless static routes (option 121/249) | -| `-accept-dns` | `false` | Set `/etc/resolv.conf` from DHCP-provided DNS servers | -| `-policy-route-table` | `0` | Policy routing table number (0 = disabled) | -| `-reconnect-delay` | `5s` | Delay between reconnection attempts | - -## Authentication - -Two authentication modes are supported: - -**Hashed password (AuthType 1)** — the default. Password is hashed with SHA-0 and combined with the server's random challenge to produce a `SecurePassword`. Used for local user accounts on the SoftEther server. - -```bash -softether-go -host vpn.example.com -user admin -pass secret -``` - -**Plaintext password (AuthType 2)** — enabled with `-plain-password`. Password is sent as-is over TLS. Used when the server delegates authentication to an external system like RADIUS. - -```bash -softether-go -host vpn.example.com -user admin -pass secret -plain-password -``` - -## Network configuration flags - -These flags control what the client does with the DHCP lease it receives from the VPN server. - -### `-mac` - -Sets a specific MAC address on the TAP interface before connecting. Useful for deterministic DHCP assignments — the server sees the same MAC across reconnects and can assign the same IP. - -```bash -softether-go -host vpn.example.com -user admin -mac 5E:3B:6F:63:A8:3E -``` - -### `-no-dhcp` - -Disables the built-in DHCP client. Use this if the TAP interface will be configured manually or by an external DHCP client. - -### `-accept-default-gateway` - -Adds a default route via the DHCP-provided gateway on the TAP interface with metric 50. Before doing this, the client adds a `/32` host route to the VPN server via the current default gateway so the tunnel itself is not routed through the VPN. - -Without this flag, only the subnet route (implicit from the assigned IP/mask) is added. - -### `-accept-static-routes` - -Installs classless static routes from DHCP option 121 (RFC 3442) or option 249 (Microsoft variant). These are non-default routes pushed by the DHCP server, such as routes to specific subnets via the VPN gateway. - -If a static route entry has destination `0.0.0.0/0` (default route), it is only installed when `-accept-default-gateway` is also set. Per RFC 3442, when option 121 is present it takes precedence over option 3 (Router). - -### `-accept-dns` - -Overwrites `/etc/resolv.conf` with the DNS servers from the DHCP lease. The original file is backed up in memory and restored when the session ends (disconnect, reconnect, or shutdown). - -### `-policy-route-table` - -Enables policy routing for asymmetric return paths. Set to a routing table number (e.g. `200`). When enabled, the client adds: - -``` -ip rule add from table 200 -ip route replace default via dev table 200 -``` - -This ensures reply packets from the VPN IP are routed back through the VPN tunnel, not the default route. Needed when the VPN server forwards ports to the client — without it, reply packets leave via the home router and get dropped. - -Cleaned up on disconnect and shutdown. - -## Examples - -Minimal connection: -```bash -softether-go -host vpn.example.com -user admin -pass secret -``` - -Full setup with routing, DNS, and policy routing: -```bash -softether-go \ - -host vpn.example.com \ - -port 992 \ - -hub DEFAULT \ - -user admin \ - -pass secret \ - -plain-password \ - -tap vpn0 \ - -mac 5E:3B:6F:63:A8:3E \ - -insecure \ - -accept-default-gateway \ - -accept-static-routes \ - -accept-dns \ - -policy-route-table 200 -``` - -No DHCP (manual configuration): -```bash -softether-go -host vpn.example.com -user admin -pass secret -no-dhcp -tap vpn0 -``` - -## Docker - -The client works in containers with `NET_ADMIN` capability and the TUN device: - -```bash -docker run --rm -it \ - --cap-add NET_ADMIN \ - --device /dev/net/tun \ - -v ./softether-go:/usr/bin/softether-go \ - alpine \ - softether-go -host vpn.example.com -user admin -pass secret \ - -plain-password -insecure -tap vpn0 \ - -accept-default-gateway -accept-dns -``` - -The container needs `iproute2` installed (`apk add iproute2` on Alpine) for the `ip` command. - -## Signals - -- **SIGINT / SIGTERM** — clean shutdown: closes tunnel, flushes TAP addresses, restores DNS, removes server host route, cleans up policy routes -- During reconnect delay, a signal triggers immediate shutdown instead of waiting From d5878a170f7364b3b5f1fb43865ecc87b54dadff Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 6 Jun 2026 17:54:38 +0530 Subject: [PATCH 06/26] consolidate docs into README.md, remove docs/ Co-Authored-By: Claude Opus 4.6 (1M context) --- README.md | 264 ++++++++++++++++++++++++++++++++++++++++--- docs/architecture.md | 149 ------------------------ docs/building.md | 54 --------- docs/main.md | 29 ----- docs/structure.md | 63 ----------- docs/usage.md | 143 ----------------------- 6 files changed, 248 insertions(+), 454 deletions(-) delete mode 100644 docs/architecture.md delete mode 100644 docs/building.md delete mode 100644 docs/main.md delete mode 100644 docs/structure.md delete mode 100644 docs/usage.md diff --git a/README.md b/README.md index 11159a1..85b84fc 100644 --- a/README.md +++ b/README.md @@ -2,29 +2,261 @@ Standalone SoftEther VPN client written in Go. Connects to SoftEther VPN servers using the native protocol over TLS, with built-in DHCP, automatic reconnection, and route management. Single static binary, Linux only, zero runtime dependencies beyond `ip` (iproute2). -## Quick start +## Features + +- Native SoftEther protocol (TLS + HTTP handshake + TCP block framing) +- Built-in DHCP client (raw Ethernet frame construction through the VPN tunnel) +- Automatic reconnection with fresh DHCP on each reconnect +- Host route to VPN server via existing default gateway (prevents routing loops) +- Classless static routes (DHCP option 121/249, RFC 3442) +- Policy routing for asymmetric return paths (VPN port forwards) +- DNS configuration from DHCP lease (backup/restore of `/etc/resolv.conf`) +- Deterministic MAC address support for stable DHCP assignments +- Hashed password (SHA-0) and plaintext password (RADIUS/external) authentication +- ~4.6 MB RAM under load, single process + +## Requirements + +- Linux (uses `/dev/net/tun` for TAP devices) +- `CAP_NET_ADMIN` or root (TAP device creation, route management) +- `ip` command (iproute2) on `$PATH` + +## Building + +Requires Go 1.24 or later. ```bash -# Build go build -o softether-go ./cmd/softether-go/ - -# Connect (minimal) -softether-go -host vpn.example.com -user admin -pass secret -plain-password - -# Connect with full network setup -softether-go -host vpn.example.com -user admin -pass secret \ - -plain-password -tap vpn0 -mac 5E:3B:6F:63:A8:3E \ - -accept-default-gateway -accept-dns -policy-route-table 200 ``` -## Documentation +Static binary (for Alpine, scratch containers): -See [docs/main.md](docs/main.md) for full documentation: +```bash +CGO_ENABLED=0 go build -o softether-go ./cmd/softether-go/ +``` -- [Usage & CLI reference](docs/usage.md) -- [How it works](docs/architecture.md) -- [Building](docs/building.md) -- [Project structure](docs/structure.md) +Cross-compilation: + +```bash +CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o softether-go ./cmd/softether-go/ +``` + +Nix: + +```bash +nix build # result in ./result/bin/softether-go +nix develop # dev shell with Go tooling +``` + +The only Go dependency is `golang.org/x/sys` (vendored in `vendor/`). + +## Usage + +``` +softether-go [flags] +``` + +### Required flags + +| Flag | Description | +|---|---| +| `-host` | SoftEther server hostname or IP | +| `-user` | Authentication username | + +### Optional flags + +| Flag | Default | Description | +|---|---|---| +| `-pass` | `""` | Authentication password | +| `-port` | `443` | Server port | +| `-hub` | `DEFAULT` | Virtual hub name | +| `-tap` | *(auto)* | TAP interface name (kernel-assigned if empty) | +| `-mac` | *(auto)* | TAP interface MAC address (e.g. `5E:3B:6F:63:A8:3E`) | +| `-plain-password` | `false` | Send password as plaintext (AuthType 2, for RADIUS/external auth) | +| `-insecure` | `false` | Skip TLS certificate verification | +| `-no-dhcp` | `false` | Disable built-in DHCP client | +| `-accept-default-gateway` | `false` | Install DHCP-provided gateway as default route | +| `-accept-static-routes` | `false` | Install DHCP classless static routes (option 121/249) | +| `-accept-dns` | `false` | Set `/etc/resolv.conf` from DHCP-provided DNS servers | +| `-policy-route-table` | `0` | Policy routing table number (0 = disabled) | +| `-reconnect-delay` | `5s` | Delay between reconnection attempts | + +### Authentication + +**Hashed password (AuthType 1)** — the default. Password is hashed with SHA-0 and combined with the server's random challenge. Used for local user accounts. + +```bash +softether-go -host vpn.example.com -user admin -pass secret +``` + +**Plaintext password (AuthType 2)** — enabled with `-plain-password`. Password sent as-is over TLS. Used for RADIUS/external auth. + +```bash +softether-go -host vpn.example.com -user admin -pass secret -plain-password +``` + +### Network configuration + +**`-mac`** — sets a specific MAC for deterministic DHCP assignments across reconnects. + +**`-accept-default-gateway`** — installs DHCP gateway as default route (metric 50). A `/32` host route to the VPN server via the original gateway prevents routing loops. + +**`-accept-static-routes`** — installs classless static routes from DHCP option 121/249. A `0.0.0.0/0` entry is only installed if `-accept-default-gateway` is also set. + +**`-accept-dns`** — overwrites `/etc/resolv.conf` with DHCP DNS servers. Original is backed up and restored on disconnect. + +**`-policy-route-table N`** — policy routing for asymmetric return paths. Adds `ip rule from table N` and `ip route replace default via dev table N`. Needed when the VPN server forwards ports to the client. + +### Examples + +Minimal: +```bash +softether-go -host vpn.example.com -user admin -pass secret +``` + +Full setup: +```bash +softether-go \ + -host vpn.example.com \ + -port 992 \ + -user admin \ + -pass secret \ + -plain-password \ + -tap vpn0 \ + -mac 5E:3B:6F:63:A8:3E \ + -insecure \ + -accept-default-gateway \ + -accept-static-routes \ + -accept-dns \ + -policy-route-table 200 +``` + +No DHCP (manual config): +```bash +softether-go -host vpn.example.com -user admin -pass secret -no-dhcp -tap vpn0 +``` + +### Docker + +```bash +docker run --rm -it \ + --cap-add NET_ADMIN \ + --device /dev/net/tun \ + -v ./softether-go:/usr/bin/softether-go \ + alpine \ + softether-go -host vpn.example.com -user admin -pass secret \ + -plain-password -insecure -tap vpn0 \ + -accept-default-gateway -accept-dns +``` + +Container needs `iproute2` (`apk add iproute2` on Alpine). + +### Signals + +- **SIGINT / SIGTERM** — clean shutdown: closes tunnel, flushes TAP, restores DNS, removes routes +- During reconnect delay, signal triggers immediate shutdown + +## Architecture + +### Connection flow + +``` +Client Server + │ │ + ├──── TLS handshake ───────────────────►│ Standard TLS, looks like HTTPS + │ │ + ├──── POST /vpnsvc/connect.cgi ────────►│ Upload signature ("VPNCONNECT") + │ │ + │◄──── HTTP 200 (Pack: hello) ──────────┤ Server version + random challenge + │ │ + ├──── POST /vpnsvc/vpn.cgi ───────────►│ Upload auth (credentials + metadata) + │ │ + │◄──── HTTP 200 (Pack: welcome) ────────┤ Session info (or error code) + │ │ + │◄────── TCP block framing ────────────►│ Ethernet frames + keepalive + │ │ +``` + +1. **TLS connect** — standard TLS to the server port (typically 443 or 992) +2. **Upload signature** — `VPNCONNECT` via HTTP POST to `/vpnsvc/connect.cgi` +3. **Download Hello** — server sends version info and 20-byte random challenge +4. **Upload Auth** — credentials, client version, connection options, node info as a Pack +5. **Download Welcome** — session info on success, error code on failure +6. **Tunnel mode** — raw TCP block framing: `uint32(numBlocks) + [uint32(size) + data]...`. Keepalive: `uint32(0xFFFFFFFF) + uint32(randSize) + randData` + +### Session lifecycle + +1. **Start bridge** — bidirectional frame forwarding begins immediately +2. **DHCP exchange** — DHCP frames sent through tunnel while bridge runs. DHCP client intercepts server frames via `FeedFrame` callback +3. **Configure TAP** — IP, routes, DNS, policy routing applied from lease +4. **Wait** — blocks until bridge errors or signal arrives +5. **Cleanup** — flush addresses, restore DNS, remove policy routes +6. **Reconnect** — wait, then repeat with fresh handshake and DHCP + +### DHCP through the tunnel + +SoftEther operates at Layer 2. The built-in DHCP client constructs complete Ethernet/IP/UDP/DHCP frames sent through the tunnel: + +``` +DHCP Client VPN Tunnel DHCP Server (on VPN) + │ │ │ + ├── DISCOVER ──► WriteFrames ├────────────────────────────►│ + │ │ │ + │◄── FeedFrame ◄─ ReadFrames ◄──────── OFFER ─────────────┤ + │ │ │ + ├── REQUEST ───► WriteFrames ├────────────────────────────►│ + │ │ │ + │◄── FeedFrame ◄─ ReadFrames ◄──────── ACK ───────────────┤ + │ │ │ +``` + +DHCP options requested: subnet mask (1), router (3), DNS (6), lease time (51), classless static routes (121/249). + +**Why fresh DHCP on reconnect**: SoftEther's `DHCPForce` policy drops packets from IPs not in its `DhcpAllocated` table. On disconnect, the server clears all entries for the session. + +### Routing + +**Server host route** — `/32` route to VPN server via current default gateway, added before first connection. Prevents routing loop when VPN becomes default route. + +**Default gateway** — DHCP gateway installed with metric 50, lower than existing default routes. + +**Static routes** — classless routes from option 121/249. Default route entries (`0.0.0.0/0`) only installed with `-accept-default-gateway`. + +**Policy routing** — `ip rule from table N` ensures reply packets for VPN port forwards go back through the tunnel, not the default route. + +### Password hashing + +SoftEther uses **SHA-0** (not SHA-1) — no left-rotate in message schedule. `HashedPassword = SHA0(password)`, `SecurePassword = SHA0(HashedPassword + ServerRandom)`. Plaintext auth (AuthType 2) sends password as-is over TLS. + +### Keepalive + +Sent every 3 seconds: `uint32(0xFFFFFFFF) + uint32(randSize) + randData`. Silently consumed, never forwarded to TAP. + +## Project structure + +``` +cmd/softether-go/ + main.go Flag parsing, TAP setup, reconnect loop + session.go Session lifecycle, DHCP orchestration + +pkg/client/ + client.go SoftEther handshake and session + tunnel.go TCP block framing, keepalive, frame bridging + crypto.go SHA-0 and password hashing + +pkg/protocol/ + http.go TLS connection, HTTP transport layer + pack.go Pack binary serialization + +pkg/dhcp/ + dhcp.go DHCP client (raw Ethernet frames) + +pkg/netcfg/ + netcfg.go TAP configuration, routing, DNS management + +pkg/tap/ + tap.go Linux TAP device management +``` ## License diff --git a/docs/architecture.md b/docs/architecture.md deleted file mode 100644 index abe1437..0000000 --- a/docs/architecture.md +++ /dev/null @@ -1,149 +0,0 @@ -# Architecture - -## Connection flow - -The SoftEther protocol layers HTTP over TLS, then switches to raw TCP framing for the data tunnel. - -``` -Client Server - │ │ - ├──── TLS handshake ───────────────────►│ Standard TLS, looks like HTTPS - │ │ - ├──── POST /vpnsvc/connect.cgi ────────►│ Upload signature ("VPNCONNECT") - │ │ - │◄──── HTTP 200 (Pack: hello) ──────────┤ Server version + random challenge - │ │ - ├──── POST /vpnsvc/vpn.cgi ───────────►│ Upload auth (credentials + metadata) - │ │ - │◄──── HTTP 200 (Pack: welcome) ────────┤ Session info (or error code) - │ │ - │◄────── TCP block framing ────────────►│ Ethernet frames + keepalive - │ │ -``` - -### Step details - -1. **TLS connect** — standard TLS to the server port (typically 443 or 992). The connection looks like normal HTTPS traffic to network observers. - -2. **Upload signature** — the client sends `VPNCONNECT` as the body of an HTTP POST to `/vpnsvc/connect.cgi`. The server validates this to confirm the client speaks the SoftEther protocol. - -3. **Download Hello** — the server responds with a binary Pack containing its version info and a 20-byte random challenge used for password hashing. - -4. **Upload Auth** — the client sends credentials (hashed or plaintext password), client version, connection options, and node info as a Pack via HTTP POST to `/vpnsvc/vpn.cgi`. - -5. **Download Welcome** — the server responds with session info (session name, connection name, session key, policies) on success, or an error code on failure. - -6. **Tunnel mode** — the connection switches from HTTP to raw TCP block framing. Each message is `uint32(numBlocks) + [uint32(size) + data]...`. Keepalive packets use `0xFFFFFFFF` as the block count, followed by random padding. - -## Pack format - -SoftEther uses a custom binary serialization called "Pack" for all structured data exchange. A Pack contains named Elements, each holding typed Values (int, string, data, ip4). - -Key details: -- Element names are **case-insensitive** (compared with `StrCmpi`) -- `AddElement` rejects duplicate names — the second add silently fails -- String values use BufStr encoding: `uint32(strlen+1)` followed by `strlen` bytes (no null terminator on wire) -- HTTP-transported Packs include a `pencore` dummy element with random padding - -## Session lifecycle - -After connecting, a session proceeds as: - -1. **Start bridge** — bidirectional frame forwarding between the tunnel and TAP device begins immediately in the background -2. **DHCP exchange** — if enabled, DHCP frames are sent through the tunnel while the bridge is already running. The DHCP client intercepts server frames via a callback (`FeedFrame`) before they reach the TAP device -3. **Configure TAP** — IP address, routes, DNS, and policy routing are applied from the DHCP lease -4. **Wait** — the session blocks until the bridge errors (server disconnect, network failure) or a signal arrives -5. **Cleanup** — TAP addresses are flushed, DNS is restored, policy routes are removed - -On disconnect, the reconnect loop waits and starts a new session with a fresh handshake and DHCP exchange. - -## DHCP through the tunnel - -SoftEther operates at Layer 2 — the tunnel carries raw Ethernet frames. The built-in DHCP client constructs complete Ethernet/IP/UDP/DHCP frames and sends them through the tunnel's frame transport. - -``` -DHCP Client VPN Tunnel DHCP Server (on VPN) - │ │ │ - ├── DISCOVER ──► WriteFrames ├────────────────────────────►│ - │ │ │ - │◄── FeedFrame ◄─ ReadFrames ◄──────── OFFER ─────────────┤ - │ │ │ - ├── REQUEST ───► WriteFrames ├────────────────────────────►│ - │ │ │ - │◄── FeedFrame ◄─ ReadFrames ◄──────── ACK ───────────────┤ - │ │ │ -``` - -The frame bridge runs concurrently with the DHCP exchange. All server frames pass through the `FeedFrame` callback, which identifies DHCP responses by transaction ID. Non-DHCP frames are written to the TAP device as normal (though the TAP has no IP yet, so the OS drops them). - -### Why raw frames? - -The VPN tunnel transports Ethernet frames, and the DHCP exchange must happen *inside* the tunnel before the TAP interface has an IP address. Constructing frames directly avoids any external dependency (`dhcpcd`, `udhcpc`) and keeps the client self-contained. - -### DHCP options requested - -- Option 1: Subnet Mask -- Option 3: Router (gateway) -- Option 6: DNS Servers -- Option 51: Lease Time -- Option 121: Classless Static Routes (RFC 3442) -- Option 249: Microsoft Classless Static Routes - -### Why DHCP is required on reconnect - -SoftEther servers with `DHCPForce` policy discard any packet whose source IP is not in the server's IP table with `DhcpAllocated=true`. When a session disconnects, the server calls `HubPaFree` which deletes **all** MAC and IP table entries for that session. The new session has no entries, so all traffic is dropped until a fresh DHCP exchange creates a new `DhcpAllocated=true` entry. - -## Routing - -### Server host route - -Before the first connection, the client resolves the server hostname and adds a `/32` host route via the current default gateway: - -``` -50.117.55.1/32 via 172.17.0.1 dev eth0 -``` - -This ensures the VPN tunnel traffic itself always uses the original path, even after `-accept-default-gateway` installs a new default route via the VPN. - -### Default gateway - -With `-accept-default-gateway`, the DHCP-provided gateway is installed as a default route with metric 50: - -``` -default via 10.100.8.1 dev vpn0 metric 50 -``` - -The metric ensures it takes precedence over any existing default route with a higher metric, while the server host route (no metric, most specific) keeps the tunnel traffic on the original path. - -### Static routes - -With `-accept-static-routes`, classless static routes from DHCP option 121 or 249 are installed. A `0.0.0.0/0` entry in static routes is treated as a default gateway and only installed if `-accept-default-gateway` is also set. Per RFC 3442, option 121 takes precedence over option 3 (Router) when present. - -### Policy routing - -With `-policy-route-table N`, the client sets up policy routing for asymmetric return paths: - -``` -ip route replace default via dev table N -ip rule add from table N -``` - -This is needed when the VPN server has port forwards to the client. Without policy routing, inbound traffic arrives via the VPN tunnel but reply packets use the default route (home router) instead of going back through the tunnel. The remote host sees replies from a different IP and drops them. - -The policy route is cleaned up on disconnect and re-applied with each new DHCP lease (since the VPN IP may change). - -## Keepalive - -The client sends keepalive packets every 3 seconds. A keepalive is `uint32(0xFFFFFFFF) + uint32(randSize) + randData`. The server sends keepalives in the same format. Keepalive packets are silently consumed and never forwarded to the TAP device. - -## Password hashing - -SoftEther uses **SHA-0** (not SHA-1) for password hashing. SHA-0 differs from SHA-1 only in the message schedule — there is no left-rotate of the W[t] values. - -For hashed password auth (AuthType 1): -``` -HashedPassword = SHA0(password) -SecurePassword = SHA0(HashedPassword + ServerRandom) -``` - -For plaintext auth (AuthType 2), the password is sent as-is over the TLS connection. diff --git a/docs/building.md b/docs/building.md deleted file mode 100644 index 53f0d43..0000000 --- a/docs/building.md +++ /dev/null @@ -1,54 +0,0 @@ -# Building - -## Go - -Requires Go 1.24 or later. - -```bash -go build -o softether-go ./cmd/softether-go/ -``` - -### Static binary - -For deployment in minimal containers (Alpine, scratch) or systems without glibc: - -```bash -CGO_ENABLED=0 go build -o softether-go ./cmd/softether-go/ -``` - -### Cross-compilation - -```bash -CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o softether-go ./cmd/softether-go/ -CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o softether-go ./cmd/softether-go/ -``` - -Only Linux targets are supported (the TAP device interface uses Linux-specific ioctls). - -## Nix - -Build with the flake: - -```bash -nix build -``` - -The result is in `./result/bin/softether-go`. - -Enter a development shell with Go tooling: - -```bash -nix develop -``` - -Build within the dev shell: - -```bash -nix develop -c bash -c 'go build -o softether-go ./cmd/softether-go/' -``` - -## Dependencies - -The only Go dependency is `golang.org/x/sys` for Linux syscall constants (TUN/TAP ioctls). Dependencies are vendored in `vendor/`. - -At runtime, the only external dependency is `ip` (iproute2) for route and address management. diff --git a/docs/main.md b/docs/main.md deleted file mode 100644 index 744a6fc..0000000 --- a/docs/main.md +++ /dev/null @@ -1,29 +0,0 @@ -# softether-go documentation - -Standalone SoftEther VPN client written in Go. Connects to SoftEther VPN servers using the native protocol over TLS, with built-in DHCP, automatic reconnection, and route management. - -## Features - -- Native SoftEther protocol (TLS + HTTP handshake + TCP block framing) -- Built-in DHCP client (raw Ethernet frame construction through the VPN tunnel) -- Automatic reconnection with fresh DHCP on each reconnect -- Host route to VPN server via existing default gateway (prevents routing loops) -- Classless static routes (DHCP option 121/249, RFC 3442) -- Policy routing for asymmetric return paths (VPN port forwards) -- DNS configuration from DHCP lease (backup/restore of `/etc/resolv.conf`) -- Deterministic MAC address support for stable DHCP assignments -- Hashed password (SHA-0) and plaintext password (RADIUS/external) authentication -- Single static binary, Linux only - -## Contents - -- [Usage & CLI reference](usage.md) — flags, examples, Docker usage -- [Architecture](architecture.md) — connection flow, DHCP, reconnection, routing -- [Building](building.md) — Go, Nix, static builds -- [Project structure](structure.md) — source layout and package descriptions - -## Requirements - -- Linux (uses `/dev/net/tun` for TAP devices) -- `CAP_NET_ADMIN` or root (TAP device creation, route management) -- `ip` command (iproute2) on `$PATH` diff --git a/docs/structure.md b/docs/structure.md deleted file mode 100644 index fd70c86..0000000 --- a/docs/structure.md +++ /dev/null @@ -1,63 +0,0 @@ -# Project structure - -``` -softether-go/ -├── cmd/softether-go/ -│ ├── main.go Flag parsing, TAP setup, reconnect loop -│ └── session.go Session lifecycle, DHCP orchestration -├── pkg/ -│ ├── client/ -│ │ ├── client.go SoftEther handshake and session -│ │ ├── tunnel.go TCP block framing, keepalive, frame bridging -│ │ └── crypto.go SHA-0 and password hashing -│ ├── protocol/ -│ │ ├── http.go TLS connection, HTTP transport layer -│ │ └── pack.go Pack binary serialization -│ ├── dhcp/ -│ │ └── dhcp.go DHCP client (raw Ethernet frames) -│ ├── netcfg/ -│ │ └── netcfg.go TAP configuration, routing, DNS management -│ └── tap/ -│ └── tap.go Linux TAP device management -├── docs/ Documentation -├── vendor/ Vendored Go dependencies -├── flake.nix Nix build definition -├── go.mod -└── go.sum -``` - -## Package details - -### `cmd/softether-go` - -CLI entry point, split into two files: - -**`main.go`** — flag parsing, TAP device creation, MAC configuration, signal handling, and the reconnect loop. Calls `runSession` for each connection attempt. - -**`session.go`** — one VPN session lifecycle: connect to server, start bridge, run DHCP, configure TAP (IP/routes/DNS/policy routing), and wait for disconnect or signal. Also contains `runDHCP` which orchestrates the DHCP exchange through the tunnel. - -### `pkg/client` - -**`client.go`** — implements the SoftEther handshake: TLS connect, signature upload, hello/auth/welcome pack exchange. Exports `Connect(Config) (*Session, error)` and the `Config`/`Session` types. - -**`tunnel.go`** — TCP block framing after the HTTP handshake completes. `ReadFrames()` reads batches of Ethernet frames from the server. `WriteFrames()` sends batches. `Bridge()` runs bidirectional frame forwarding between the tunnel and a TAP device, with an optional `FrameHandler` callback for intercepting frames (used by DHCP). `StartKeepalive()` sends periodic keepalive packets (every 3s). - -**`crypto.go`** — SHA-0 implementation (differs from SHA-1 only in the message schedule — no left-rotate). `HashPassword()` produces `SHA0(password)`. `SecurePassword()` produces `SHA0(hashed + serverRandom)`. - -### `pkg/protocol` - -**`http.go`** — HTTP transport layer. `DialTLS()` establishes the TLS connection. `UploadSignature()` sends the protocol signature. `SendPack()` and `RecvPack()` exchange binary Packs as HTTP POST request/response bodies. - -**`pack.go`** — SoftEther Pack binary serialization. A Pack is a list of named Elements, each containing typed Values (int, string, data, ip4). Handles the BufStr wire format (`uint32(strlen+1)` then `strlen` bytes) and the `pencore` random padding element. - -### `pkg/dhcp` - -**`dhcp.go`** — DHCP client that constructs complete Ethernet/IP/UDP/DHCP frames. The full DHCP exchange (DISCOVER → OFFER → REQUEST → ACK) runs through the VPN tunnel's frame transport. Parses lease information including classless static routes (option 121/249, RFC 3442). - -### `pkg/netcfg` - -**`netcfg.go`** — network configuration for the VPN tunnel. `ConfigureTAP()` sets IP address, routes, and DNS on the TAP interface from a DHCP lease. `ConfigurePolicyRoute()` sets up policy routing for asymmetric return paths. `AddServerRoute()` adds a host route to the VPN server via the current default gateway. `ResolveHost()` resolves hostnames to IPv4. - -### `pkg/tap` - -**`tap.go`** — Linux TAP (Layer 2) device management via `/dev/net/tun`. Opens TAP devices with `IFF_TAP | IFF_NO_PI`, reads/writes raw Ethernet frames. Provides `MAC()` and `SetMAC()` for hardware address management, and `SetUp()` to bring the interface up. diff --git a/docs/usage.md b/docs/usage.md deleted file mode 100644 index 02ceb46..0000000 --- a/docs/usage.md +++ /dev/null @@ -1,143 +0,0 @@ -# Usage - -``` -softether-go [flags] -``` - -## Required flags - -| Flag | Description | -|---|---| -| `-host` | SoftEther server hostname or IP | -| `-user` | Authentication username | - -## Optional flags - -| Flag | Default | Description | -|---|---|---| -| `-pass` | `""` | Authentication password | -| `-port` | `443` | Server port | -| `-hub` | `DEFAULT` | Virtual hub name | -| `-tap` | *(auto)* | TAP interface name (kernel-assigned if empty) | -| `-mac` | *(auto)* | TAP interface MAC address (e.g. `5E:3B:6F:63:A8:3E`) | -| `-plain-password` | `false` | Send password as plaintext (AuthType 2, for RADIUS/external auth) | -| `-insecure` | `false` | Skip TLS certificate verification | -| `-no-dhcp` | `false` | Disable built-in DHCP client | -| `-accept-default-gateway` | `false` | Install DHCP-provided gateway as default route | -| `-accept-static-routes` | `false` | Install DHCP classless static routes (option 121/249) | -| `-accept-dns` | `false` | Set `/etc/resolv.conf` from DHCP-provided DNS servers | -| `-policy-route-table` | `0` | Policy routing table number (0 = disabled) | -| `-reconnect-delay` | `5s` | Delay between reconnection attempts | - -## Authentication - -Two authentication modes are supported: - -**Hashed password (AuthType 1)** — the default. Password is hashed with SHA-0 and combined with the server's random challenge to produce a `SecurePassword`. Used for local user accounts on the SoftEther server. - -```bash -softether-go -host vpn.example.com -user admin -pass secret -``` - -**Plaintext password (AuthType 2)** — enabled with `-plain-password`. Password is sent as-is over TLS. Used when the server delegates authentication to an external system like RADIUS. - -```bash -softether-go -host vpn.example.com -user admin -pass secret -plain-password -``` - -## Network configuration flags - -These flags control what the client does with the DHCP lease it receives from the VPN server. - -### `-mac` - -Sets a specific MAC address on the TAP interface before connecting. Useful for deterministic DHCP assignments — the server sees the same MAC across reconnects and can assign the same IP. - -```bash -softether-go -host vpn.example.com -user admin -mac 5E:3B:6F:63:A8:3E -``` - -### `-no-dhcp` - -Disables the built-in DHCP client. Use this if the TAP interface will be configured manually or by an external DHCP client. - -### `-accept-default-gateway` - -Adds a default route via the DHCP-provided gateway on the TAP interface with metric 50. Before doing this, the client adds a `/32` host route to the VPN server via the current default gateway so the tunnel itself is not routed through the VPN. - -Without this flag, only the subnet route (implicit from the assigned IP/mask) is added. - -### `-accept-static-routes` - -Installs classless static routes from DHCP option 121 (RFC 3442) or option 249 (Microsoft variant). These are non-default routes pushed by the DHCP server, such as routes to specific subnets via the VPN gateway. - -If a static route entry has destination `0.0.0.0/0` (default route), it is only installed when `-accept-default-gateway` is also set. Per RFC 3442, when option 121 is present it takes precedence over option 3 (Router). - -### `-accept-dns` - -Overwrites `/etc/resolv.conf` with the DNS servers from the DHCP lease. The original file is backed up in memory and restored when the session ends (disconnect, reconnect, or shutdown). - -### `-policy-route-table` - -Enables policy routing for asymmetric return paths. Set to a routing table number (e.g. `200`). When enabled, the client adds: - -``` -ip rule add from table 200 -ip route replace default via dev table 200 -``` - -This ensures reply packets from the VPN IP are routed back through the VPN tunnel, not the default route. Needed when the VPN server forwards ports to the client — without it, reply packets leave via the home router and get dropped. - -Cleaned up on disconnect and shutdown. - -## Examples - -Minimal connection: -```bash -softether-go -host vpn.example.com -user admin -pass secret -``` - -Full setup with routing, DNS, and policy routing: -```bash -softether-go \ - -host vpn.example.com \ - -port 992 \ - -hub DEFAULT \ - -user admin \ - -pass secret \ - -plain-password \ - -tap vpn0 \ - -mac 5E:3B:6F:63:A8:3E \ - -insecure \ - -accept-default-gateway \ - -accept-static-routes \ - -accept-dns \ - -policy-route-table 200 -``` - -No DHCP (manual configuration): -```bash -softether-go -host vpn.example.com -user admin -pass secret -no-dhcp -tap vpn0 -``` - -## Docker - -The client works in containers with `NET_ADMIN` capability and the TUN device: - -```bash -docker run --rm -it \ - --cap-add NET_ADMIN \ - --device /dev/net/tun \ - -v ./softether-go:/usr/bin/softether-go \ - alpine \ - softether-go -host vpn.example.com -user admin -pass secret \ - -plain-password -insecure -tap vpn0 \ - -accept-default-gateway -accept-dns -``` - -The container needs `iproute2` installed (`apk add iproute2` on Alpine) for the `ip` command. - -## Signals - -- **SIGINT / SIGTERM** — clean shutdown: closes tunnel, flushes TAP addresses, restores DNS, removes server host route, cleans up policy routes -- During reconnect delay, a signal triggers immediate shutdown instead of waiting From 641615916497baa0241bb7ffe11b9eacace8749e Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 6 Jun 2026 22:05:34 +0530 Subject: [PATCH 07/26] add DHCP lease renewal at T/2 - Add Renew() to dhcp.Client: sends REQUEST with ciaddr (RENEWING state) - Start renewal goroutine in session at lease_time/2 - On IP change: flush TAP, reconfigure address/routes/DNS/policy routes - On renewal failure: retry at T/4 (min 60s) Co-Authored-By: Claude Opus 4.6 (1M context) --- cmd/softether-go/session.go | 51 +++++++++++++++++++++++++++++++++++++ pkg/dhcp/dhcp.go | 43 +++++++++++++++++++++++++++++++ pkg/netcfg/netcfg.go | 11 ++++++++ 3 files changed, 105 insertions(+) diff --git a/cmd/softether-go/session.go b/cmd/softether-go/session.go index 5cf3d18..8cf8f41 100644 --- a/cmd/softether-go/session.go +++ b/cmd/softether-go/session.go @@ -61,6 +61,13 @@ func runSession(cfg client.Config, dev *tap.Device, mac net.HardwareAddr, opts n if opts.PolicyRouteTable > 0 && lease.Gateway != nil { defer netcfg.ConfigurePolicyRoute(dev.Name, lease, opts.PolicyRouteTable)() } + + // Start DHCP renewal at T/2 + if lease.LeaseTime > 0 { + stopRenew := make(chan struct{}) + defer close(stopRenew) + go renewLoop(dhcpClient, tunnel, dev.Name, lease, opts, stopRenew) + } } select { @@ -71,6 +78,50 @@ func runSession(cfg client.Config, dev *tap.Device, mac net.HardwareAddr, opts n } } +func renewLoop(dc *dhcp.Client, tunnel *client.Tunnel, ifname string, lease *dhcp.Lease, opts netcfg.Options, stop chan struct{}) { + currentIP := lease.ClientIP + renewAt := lease.LeaseTime / 2 + + for { + select { + case <-stop: + return + case <-time.After(renewAt): + } + + log.Printf("dhcp: renewing lease for %s...", currentIP) + newLease, err := dc.Renew(currentIP, func(frame []byte) error { + return tunnel.WriteFrames([][]byte{frame}) + }, 10*time.Second) + if err != nil { + log.Printf("dhcp: renewal failed: %v", err) + // Try again at T/4 of remaining time, or 60s minimum + renewAt = lease.LeaseTime / 4 + if renewAt < 60*time.Second { + renewAt = 60 * time.Second + } + continue + } + + ones, _ := newLease.SubnetMask.Size() + log.Printf("dhcp: renewed lease: ip=%s/%d gw=%s ttl=%v", + newLease.ClientIP, ones, newLease.Gateway, newLease.LeaseTime) + + if !newLease.ClientIP.Equal(currentIP) { + log.Printf("dhcp: IP changed %s → %s, reconfiguring", currentIP, newLease.ClientIP) + netcfg.ReconfigureTAP(ifname, newLease, opts.AcceptDefaultGW, opts.AcceptStaticRoutes, opts.AcceptDNS) + if opts.PolicyRouteTable > 0 && newLease.Gateway != nil { + netcfg.ConfigurePolicyRoute(ifname, newLease, opts.PolicyRouteTable) + } + currentIP = newLease.ClientIP + } + + if newLease.LeaseTime > 0 { + renewAt = newLease.LeaseTime / 2 + } + } +} + func runDHCP(dc *dhcp.Client, tunnel *client.Tunnel) (*dhcp.Lease, error) { log.Println("starting DHCP exchange...") diff --git a/pkg/dhcp/dhcp.go b/pkg/dhcp/dhcp.go index 7eb8064..a5be160 100644 --- a/pkg/dhcp/dhcp.go +++ b/pkg/dhcp/dhcp.go @@ -150,6 +150,49 @@ func (c *Client) Run(sendFrame func([]byte) error, timeout time.Duration) (*Leas return lease, nil } +// Renew sends a DHCP REQUEST to renew the current lease. +// In RENEWING state: ciaddr = current IP, no requested-IP or server-ID options. +// Returns the renewed lease on ACK, or error on NAK/timeout. +func (c *Client) Renew(currentIP net.IP, sendFrame func([]byte) error, timeout time.Duration) (*Lease, error) { + var ciaddr [4]byte + copy(ciaddr[:], currentIP.To4()) + + opts := []dhcpOption{ + {optMessageType, []byte{dhcpRequest}}, + {optParamRequest, []byte{optSubnetMask, optRouter, optDNS, optLeaseTime, optClasslessRoutes, optMSClasslessRoutes}}, + } + frame := c.buildFrame(opts, ciaddr, nil) + if err := sendFrame(frame); err != nil { + return nil, fmt.Errorf("send renew: %w", err) + } + + ack, err := c.waitForType(dhcpAck, timeout) + if err != nil { + return nil, fmt.Errorf("waiting for renew ack: %w", err) + } + + lease := &Lease{ + ClientIP: net.IP(ack.yiaddr[:]).To4(), + ServerIP: ack.getOptionIP(optServerID), + SubnetMask: net.IPMask(ack.getOptionRaw(optSubnetMask)), + Gateway: ack.getOptionIP(optRouter), + DNS: ack.getOptionIPs(optDNS), + } + if lt := ack.getOptionUint32(optLeaseTime); lt > 0 { + lease.LeaseTime = time.Duration(lt) * time.Second + } + if lease.SubnetMask == nil { + lease.SubnetMask = net.CIDRMask(24, 32) + } + if routes := parseClasslessRoutes(ack.getOptionRaw(optClasslessRoutes)); len(routes) > 0 { + lease.Routes = routes + } else if routes := parseClasslessRoutes(ack.getOptionRaw(optMSClasslessRoutes)); len(routes) > 0 { + lease.Routes = routes + } + + return lease, nil +} + func (c *Client) waitForType(msgType byte, timeout time.Duration) (*dhcpMsg, error) { deadline := time.After(timeout) for { diff --git a/pkg/netcfg/netcfg.go b/pkg/netcfg/netcfg.go index df5bfcd..2c46837 100644 --- a/pkg/netcfg/netcfg.go +++ b/pkg/netcfg/netcfg.go @@ -80,6 +80,17 @@ func ConfigureTAP(ifname string, lease *dhcp.Lease, acceptDefaultGW, acceptStati return cleanup, nil } +// ReconfigureTAP flushes the current TAP config and applies a new lease. +// Used when DHCP renewal returns a different IP address. +func ReconfigureTAP(ifname string, lease *dhcp.Lease, acceptDefaultGW, acceptStaticRoutes, acceptDNS bool) { + log.Printf("tap %s: reconfiguring for new IP", ifname) + run("ip", "addr", "flush", "dev", ifname) + // Ignore errors — best effort reconfiguration + if _, err := ConfigureTAP(ifname, lease, acceptDefaultGW, acceptStaticRoutes, acceptDNS); err != nil { + log.Printf("warning: reconfigure tap: %v", err) + } +} + // ConfigurePolicyRoute sets up policy routing so packets from the VPN IP are routed // back through the VPN gateway. Needed when the VPN server forwards ports to the // client — without it, reply packets use the default route instead of the VPN tunnel. From a62ed3287fa179b28e0f17fe8ca488ab23a5e7d5 Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 6 Jun 2026 22:05:34 +0530 Subject: [PATCH 08/26] add DHCP lease renewal at T/2 - Add Renew() to dhcp.Client: sends REQUEST with ciaddr (RENEWING state) - Start renewal goroutine in session at lease_time/2 - On IP change: flush TAP, reconfigure address/routes/DNS/policy routes - On renewal failure: retry at T/4 (min 60s) Co-Authored-By: Claude Opus 4.6 (1M context) --- cmd/softether-go/session.go | 51 +++++++++++++++++++++++++++++++++++++ pkg/dhcp/dhcp.go | 43 +++++++++++++++++++++++++++++++ pkg/netcfg/netcfg.go | 11 ++++++++ 3 files changed, 105 insertions(+) diff --git a/cmd/softether-go/session.go b/cmd/softether-go/session.go index 5cf3d18..8cf8f41 100644 --- a/cmd/softether-go/session.go +++ b/cmd/softether-go/session.go @@ -61,6 +61,13 @@ func runSession(cfg client.Config, dev *tap.Device, mac net.HardwareAddr, opts n if opts.PolicyRouteTable > 0 && lease.Gateway != nil { defer netcfg.ConfigurePolicyRoute(dev.Name, lease, opts.PolicyRouteTable)() } + + // Start DHCP renewal at T/2 + if lease.LeaseTime > 0 { + stopRenew := make(chan struct{}) + defer close(stopRenew) + go renewLoop(dhcpClient, tunnel, dev.Name, lease, opts, stopRenew) + } } select { @@ -71,6 +78,50 @@ func runSession(cfg client.Config, dev *tap.Device, mac net.HardwareAddr, opts n } } +func renewLoop(dc *dhcp.Client, tunnel *client.Tunnel, ifname string, lease *dhcp.Lease, opts netcfg.Options, stop chan struct{}) { + currentIP := lease.ClientIP + renewAt := lease.LeaseTime / 2 + + for { + select { + case <-stop: + return + case <-time.After(renewAt): + } + + log.Printf("dhcp: renewing lease for %s...", currentIP) + newLease, err := dc.Renew(currentIP, func(frame []byte) error { + return tunnel.WriteFrames([][]byte{frame}) + }, 10*time.Second) + if err != nil { + log.Printf("dhcp: renewal failed: %v", err) + // Try again at T/4 of remaining time, or 60s minimum + renewAt = lease.LeaseTime / 4 + if renewAt < 60*time.Second { + renewAt = 60 * time.Second + } + continue + } + + ones, _ := newLease.SubnetMask.Size() + log.Printf("dhcp: renewed lease: ip=%s/%d gw=%s ttl=%v", + newLease.ClientIP, ones, newLease.Gateway, newLease.LeaseTime) + + if !newLease.ClientIP.Equal(currentIP) { + log.Printf("dhcp: IP changed %s → %s, reconfiguring", currentIP, newLease.ClientIP) + netcfg.ReconfigureTAP(ifname, newLease, opts.AcceptDefaultGW, opts.AcceptStaticRoutes, opts.AcceptDNS) + if opts.PolicyRouteTable > 0 && newLease.Gateway != nil { + netcfg.ConfigurePolicyRoute(ifname, newLease, opts.PolicyRouteTable) + } + currentIP = newLease.ClientIP + } + + if newLease.LeaseTime > 0 { + renewAt = newLease.LeaseTime / 2 + } + } +} + func runDHCP(dc *dhcp.Client, tunnel *client.Tunnel) (*dhcp.Lease, error) { log.Println("starting DHCP exchange...") diff --git a/pkg/dhcp/dhcp.go b/pkg/dhcp/dhcp.go index 7eb8064..a5be160 100644 --- a/pkg/dhcp/dhcp.go +++ b/pkg/dhcp/dhcp.go @@ -150,6 +150,49 @@ func (c *Client) Run(sendFrame func([]byte) error, timeout time.Duration) (*Leas return lease, nil } +// Renew sends a DHCP REQUEST to renew the current lease. +// In RENEWING state: ciaddr = current IP, no requested-IP or server-ID options. +// Returns the renewed lease on ACK, or error on NAK/timeout. +func (c *Client) Renew(currentIP net.IP, sendFrame func([]byte) error, timeout time.Duration) (*Lease, error) { + var ciaddr [4]byte + copy(ciaddr[:], currentIP.To4()) + + opts := []dhcpOption{ + {optMessageType, []byte{dhcpRequest}}, + {optParamRequest, []byte{optSubnetMask, optRouter, optDNS, optLeaseTime, optClasslessRoutes, optMSClasslessRoutes}}, + } + frame := c.buildFrame(opts, ciaddr, nil) + if err := sendFrame(frame); err != nil { + return nil, fmt.Errorf("send renew: %w", err) + } + + ack, err := c.waitForType(dhcpAck, timeout) + if err != nil { + return nil, fmt.Errorf("waiting for renew ack: %w", err) + } + + lease := &Lease{ + ClientIP: net.IP(ack.yiaddr[:]).To4(), + ServerIP: ack.getOptionIP(optServerID), + SubnetMask: net.IPMask(ack.getOptionRaw(optSubnetMask)), + Gateway: ack.getOptionIP(optRouter), + DNS: ack.getOptionIPs(optDNS), + } + if lt := ack.getOptionUint32(optLeaseTime); lt > 0 { + lease.LeaseTime = time.Duration(lt) * time.Second + } + if lease.SubnetMask == nil { + lease.SubnetMask = net.CIDRMask(24, 32) + } + if routes := parseClasslessRoutes(ack.getOptionRaw(optClasslessRoutes)); len(routes) > 0 { + lease.Routes = routes + } else if routes := parseClasslessRoutes(ack.getOptionRaw(optMSClasslessRoutes)); len(routes) > 0 { + lease.Routes = routes + } + + return lease, nil +} + func (c *Client) waitForType(msgType byte, timeout time.Duration) (*dhcpMsg, error) { deadline := time.After(timeout) for { diff --git a/pkg/netcfg/netcfg.go b/pkg/netcfg/netcfg.go index df5bfcd..2c46837 100644 --- a/pkg/netcfg/netcfg.go +++ b/pkg/netcfg/netcfg.go @@ -80,6 +80,17 @@ func ConfigureTAP(ifname string, lease *dhcp.Lease, acceptDefaultGW, acceptStati return cleanup, nil } +// ReconfigureTAP flushes the current TAP config and applies a new lease. +// Used when DHCP renewal returns a different IP address. +func ReconfigureTAP(ifname string, lease *dhcp.Lease, acceptDefaultGW, acceptStaticRoutes, acceptDNS bool) { + log.Printf("tap %s: reconfiguring for new IP", ifname) + run("ip", "addr", "flush", "dev", ifname) + // Ignore errors — best effort reconfiguration + if _, err := ConfigureTAP(ifname, lease, acceptDefaultGW, acceptStaticRoutes, acceptDNS); err != nil { + log.Printf("warning: reconfigure tap: %v", err) + } +} + // ConfigurePolicyRoute sets up policy routing so packets from the VPN IP are routed // back through the VPN gateway. Needed when the VPN server forwards ports to the // client — without it, reply packets use the default route instead of the VPN tunnel. From b3f4c5f42b55772350978ae8179794acd3888026 Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 6 Jun 2026 22:53:06 +0530 Subject: [PATCH 09/26] tunnel: add write mutex for concurrent safety WriteFrames and keepalive both write multi-part messages to the TLS connection. Without synchronization, their writes could interleave and corrupt the framing. Add writeMu to serialize all tunnel writes. Co-Authored-By: Claude Opus 4.6 (1M context) --- pkg/client/tunnel.go | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/pkg/client/tunnel.go b/pkg/client/tunnel.go index b40e407..f8d43f0 100644 --- a/pkg/client/tunnel.go +++ b/pkg/client/tunnel.go @@ -28,6 +28,7 @@ const ( // SoftEther VPN session. Each "block" is one Ethernet frame. type Tunnel struct { sess *Session + writeMu sync.Mutex stopCh chan struct{} stopped sync.Once } @@ -83,7 +84,11 @@ func (t *Tunnel) ReadFrames() ([][]byte, error) { } // WriteFrames sends a batch of Ethernet frames to the server. +// Safe for concurrent use from multiple goroutines. func (t *Tunnel) WriteFrames(frames [][]byte) error { + t.writeMu.Lock() + defer t.writeMu.Unlock() + if err := binary.Write(t.sess.Conn, binary.BigEndian, uint32(len(frames))); err != nil { return fmt.Errorf("write num blocks: %w", err) } @@ -170,14 +175,20 @@ func (t *Tunnel) StartKeepalive() { return case <-ticker.C: size := uint32(rng.Intn(int(maxKeepaliveSize))) + 1 - if err := binary.Write(t.sess.Conn, binary.BigEndian, keepAliveMagic); err != nil { - return - } - if err := binary.Write(t.sess.Conn, binary.BigEndian, size); err != nil { - return - } rng.Read(randBuf[:size]) - if _, err := t.sess.Conn.Write(randBuf[:size]); err != nil { + + t.writeMu.Lock() + err1 := binary.Write(t.sess.Conn, binary.BigEndian, keepAliveMagic) + var err2, err3 error + if err1 == nil { + err2 = binary.Write(t.sess.Conn, binary.BigEndian, size) + } + if err2 == nil { + _, err3 = t.sess.Conn.Write(randBuf[:size]) + } + t.writeMu.Unlock() + + if err1 != nil || err2 != nil || err3 != nil { return } } From ca050d46f25c8a0643787ce9f9465563e95136d4 Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 6 Jun 2026 22:53:06 +0530 Subject: [PATCH 10/26] tunnel: add write mutex for concurrent safety WriteFrames and keepalive both write multi-part messages to the TLS connection. Without synchronization, their writes could interleave and corrupt the framing. Add writeMu to serialize all tunnel writes. Co-Authored-By: Claude Opus 4.6 (1M context) --- pkg/client/tunnel.go | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/pkg/client/tunnel.go b/pkg/client/tunnel.go index b40e407..f8d43f0 100644 --- a/pkg/client/tunnel.go +++ b/pkg/client/tunnel.go @@ -28,6 +28,7 @@ const ( // SoftEther VPN session. Each "block" is one Ethernet frame. type Tunnel struct { sess *Session + writeMu sync.Mutex stopCh chan struct{} stopped sync.Once } @@ -83,7 +84,11 @@ func (t *Tunnel) ReadFrames() ([][]byte, error) { } // WriteFrames sends a batch of Ethernet frames to the server. +// Safe for concurrent use from multiple goroutines. func (t *Tunnel) WriteFrames(frames [][]byte) error { + t.writeMu.Lock() + defer t.writeMu.Unlock() + if err := binary.Write(t.sess.Conn, binary.BigEndian, uint32(len(frames))); err != nil { return fmt.Errorf("write num blocks: %w", err) } @@ -170,14 +175,20 @@ func (t *Tunnel) StartKeepalive() { return case <-ticker.C: size := uint32(rng.Intn(int(maxKeepaliveSize))) + 1 - if err := binary.Write(t.sess.Conn, binary.BigEndian, keepAliveMagic); err != nil { - return - } - if err := binary.Write(t.sess.Conn, binary.BigEndian, size); err != nil { - return - } rng.Read(randBuf[:size]) - if _, err := t.sess.Conn.Write(randBuf[:size]); err != nil { + + t.writeMu.Lock() + err1 := binary.Write(t.sess.Conn, binary.BigEndian, keepAliveMagic) + var err2, err3 error + if err1 == nil { + err2 = binary.Write(t.sess.Conn, binary.BigEndian, size) + } + if err2 == nil { + _, err3 = t.sess.Conn.Write(randBuf[:size]) + } + t.writeMu.Unlock() + + if err1 != nil || err2 != nil || err3 != nil { return } } From fc07ac507db8e6dc607d0f950936e810889d2603 Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 6 Jun 2026 22:58:00 +0530 Subject: [PATCH 11/26] dhcp: generate fresh xid per exchange New random transaction ID for each DHCP exchange (initial and renewal) to avoid matching stale responses from previous transactions. Co-Authored-By: Claude Opus 4.6 (1M context) --- pkg/dhcp/dhcp.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pkg/dhcp/dhcp.go b/pkg/dhcp/dhcp.go index a5be160..7108eed 100644 --- a/pkg/dhcp/dhcp.go +++ b/pkg/dhcp/dhcp.go @@ -96,6 +96,7 @@ func (c *Client) FeedFrame(frame []byte) { // sendFrame is called to transmit each Ethernet frame through the tunnel. // Returns the lease on success. func (c *Client) Run(sendFrame func([]byte) error, timeout time.Duration) (*Lease, error) { + c.xid = rand.Uint32() // Send DISCOVER disc := c.buildDiscover() if err := sendFrame(disc); err != nil { @@ -154,6 +155,7 @@ func (c *Client) Run(sendFrame func([]byte) error, timeout time.Duration) (*Leas // In RENEWING state: ciaddr = current IP, no requested-IP or server-ID options. // Returns the renewed lease on ACK, or error on NAK/timeout. func (c *Client) Renew(currentIP net.IP, sendFrame func([]byte) error, timeout time.Duration) (*Lease, error) { + c.xid = rand.Uint32() var ciaddr [4]byte copy(ciaddr[:], currentIP.To4()) From e84afd7c3e5741f5477a90e2bf171424c1b62a00 Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 6 Jun 2026 22:58:00 +0530 Subject: [PATCH 12/26] dhcp: generate fresh xid per exchange New random transaction ID for each DHCP exchange (initial and renewal) to avoid matching stale responses from previous transactions. Co-Authored-By: Claude Opus 4.6 (1M context) --- pkg/dhcp/dhcp.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pkg/dhcp/dhcp.go b/pkg/dhcp/dhcp.go index a5be160..7108eed 100644 --- a/pkg/dhcp/dhcp.go +++ b/pkg/dhcp/dhcp.go @@ -96,6 +96,7 @@ func (c *Client) FeedFrame(frame []byte) { // sendFrame is called to transmit each Ethernet frame through the tunnel. // Returns the lease on success. func (c *Client) Run(sendFrame func([]byte) error, timeout time.Duration) (*Lease, error) { + c.xid = rand.Uint32() // Send DISCOVER disc := c.buildDiscover() if err := sendFrame(disc); err != nil { @@ -154,6 +155,7 @@ func (c *Client) Run(sendFrame func([]byte) error, timeout time.Duration) (*Leas // In RENEWING state: ciaddr = current IP, no requested-IP or server-ID options. // Returns the renewed lease on ACK, or error on NAK/timeout. func (c *Client) Renew(currentIP net.IP, sendFrame func([]byte) error, timeout time.Duration) (*Lease, error) { + c.xid = rand.Uint32() var ciaddr [4]byte copy(ciaddr[:], currentIP.To4()) From 14ec4a02dd8c6352978fcf6e9ae06c5590b86794 Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 6 Jun 2026 23:07:55 +0530 Subject: [PATCH 13/26] tunnel: buffer WriteFrames into single TLS write Assemble numBlocks + frame sizes + frame data into one buffer before writing. Reduces TLS records and syscalls from 3 per frame to 1. Co-Authored-By: Claude Opus 4.6 (1M context) --- pkg/client/tunnel.go | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/pkg/client/tunnel.go b/pkg/client/tunnel.go index f8d43f0..5a36c44 100644 --- a/pkg/client/tunnel.go +++ b/pkg/client/tunnel.go @@ -85,20 +85,31 @@ func (t *Tunnel) ReadFrames() ([][]byte, error) { // WriteFrames sends a batch of Ethernet frames to the server. // Safe for concurrent use from multiple goroutines. +// Assembles the entire message into one buffer for a single TLS write. func (t *Tunnel) WriteFrames(frames [][]byte) error { - t.writeMu.Lock() - defer t.writeMu.Unlock() - - if err := binary.Write(t.sess.Conn, binary.BigEndian, uint32(len(frames))); err != nil { - return fmt.Errorf("write num blocks: %w", err) + // Calculate total size: 4 (numBlocks) + per frame: 4 (size) + len(data) + total := 4 + for _, f := range frames { + total += 4 + len(f) } - for _, frame := range frames { - if err := binary.Write(t.sess.Conn, binary.BigEndian, uint32(len(frame))); err != nil { - return fmt.Errorf("write block size: %w", err) - } - if _, err := t.sess.Conn.Write(frame); err != nil { - return fmt.Errorf("write block data: %w", err) - } + + buf := make([]byte, total) + off := 0 + binary.BigEndian.PutUint32(buf[off:], uint32(len(frames))) + off += 4 + for _, f := range frames { + binary.BigEndian.PutUint32(buf[off:], uint32(len(f))) + off += 4 + copy(buf[off:], f) + off += len(f) + } + + t.writeMu.Lock() + _, err := t.sess.Conn.Write(buf) + t.writeMu.Unlock() + + if err != nil { + return fmt.Errorf("write frames: %w", err) } return nil } From 47d4b77bf029bfacb627217e15bfc1d4c26f1989 Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 6 Jun 2026 23:07:55 +0530 Subject: [PATCH 14/26] tunnel: buffer WriteFrames into single TLS write Assemble numBlocks + frame sizes + frame data into one buffer before writing. Reduces TLS records and syscalls from 3 per frame to 1. Co-Authored-By: Claude Opus 4.6 (1M context) --- pkg/client/tunnel.go | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/pkg/client/tunnel.go b/pkg/client/tunnel.go index f8d43f0..5a36c44 100644 --- a/pkg/client/tunnel.go +++ b/pkg/client/tunnel.go @@ -85,20 +85,31 @@ func (t *Tunnel) ReadFrames() ([][]byte, error) { // WriteFrames sends a batch of Ethernet frames to the server. // Safe for concurrent use from multiple goroutines. +// Assembles the entire message into one buffer for a single TLS write. func (t *Tunnel) WriteFrames(frames [][]byte) error { - t.writeMu.Lock() - defer t.writeMu.Unlock() - - if err := binary.Write(t.sess.Conn, binary.BigEndian, uint32(len(frames))); err != nil { - return fmt.Errorf("write num blocks: %w", err) + // Calculate total size: 4 (numBlocks) + per frame: 4 (size) + len(data) + total := 4 + for _, f := range frames { + total += 4 + len(f) } - for _, frame := range frames { - if err := binary.Write(t.sess.Conn, binary.BigEndian, uint32(len(frame))); err != nil { - return fmt.Errorf("write block size: %w", err) - } - if _, err := t.sess.Conn.Write(frame); err != nil { - return fmt.Errorf("write block data: %w", err) - } + + buf := make([]byte, total) + off := 0 + binary.BigEndian.PutUint32(buf[off:], uint32(len(frames))) + off += 4 + for _, f := range frames { + binary.BigEndian.PutUint32(buf[off:], uint32(len(f))) + off += 4 + copy(buf[off:], f) + off += len(f) + } + + t.writeMu.Lock() + _, err := t.sess.Conn.Write(buf) + t.writeMu.Unlock() + + if err != nil { + return fmt.Errorf("write frames: %w", err) } return nil } From 47e06b525c3fbae3ec843d2513368df47ebfcf1b Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 6 Jun 2026 23:16:27 +0530 Subject: [PATCH 15/26] tunnel: replace write mutex with channel-based single writer All writes (frames, keepalive, DHCP renewal) are queued to a buffered channel and drained by a single writer goroutine. Eliminates mutex contention on the data path entirely. Co-Authored-By: Claude Opus 4.6 (1M context) --- pkg/client/tunnel.go | 63 ++++++++++++++++++++++++++------------------ 1 file changed, 38 insertions(+), 25 deletions(-) diff --git a/pkg/client/tunnel.go b/pkg/client/tunnel.go index 5a36c44..1332204 100644 --- a/pkg/client/tunnel.go +++ b/pkg/client/tunnel.go @@ -22,13 +22,15 @@ const ( keepAliveMagic uint32 = 0xFFFFFFFF // Magic value indicating a keepalive packet maxKeepaliveSize uint32 = 512 // Max random data in keepalive keepAliveInterval = 3 * time.Second + writeChanSize = 128 // Buffered write queue depth ) // Tunnel handles bidirectional TCP block framing for Ethernet frames over a // SoftEther VPN session. Each "block" is one Ethernet frame. type Tunnel struct { sess *Session - writeMu sync.Mutex + writeCh chan []byte // serialized messages queued for the single writer + writeErr error // last write error stopCh chan struct{} stopped sync.Once } @@ -36,15 +38,32 @@ type Tunnel struct { // NewTunnel creates a tunnel from an established session. // Call StartKeepalive() before reading/writing frames. func NewTunnel(sess *Session) *Tunnel { - return &Tunnel{ - sess: sess, - stopCh: make(chan struct{}), + t := &Tunnel{ + sess: sess, + writeCh: make(chan []byte, writeChanSize), + stopCh: make(chan struct{}), + } + go t.writeLoop() + return t +} + +// writeLoop is the single goroutine that writes to the connection. +// All writes are serialized through writeCh — no mutex needed. +func (t *Tunnel) writeLoop() { + for buf := range t.writeCh { + if _, err := t.sess.Conn.Write(buf); err != nil { + t.writeErr = err + return + } } } // Close stops the keepalive goroutine and closes the underlying connection. func (t *Tunnel) Close() error { - t.stopped.Do(func() { close(t.stopCh) }) + t.stopped.Do(func() { + close(t.stopCh) + close(t.writeCh) + }) return t.sess.Conn.Close() } @@ -84,8 +103,7 @@ func (t *Tunnel) ReadFrames() ([][]byte, error) { } // WriteFrames sends a batch of Ethernet frames to the server. -// Safe for concurrent use from multiple goroutines. -// Assembles the entire message into one buffer for a single TLS write. +// Safe for concurrent use — messages are queued for the single writer goroutine. func (t *Tunnel) WriteFrames(frames [][]byte) error { // Calculate total size: 4 (numBlocks) + per frame: 4 (size) + len(data) total := 4 @@ -104,14 +122,12 @@ func (t *Tunnel) WriteFrames(frames [][]byte) error { off += len(f) } - t.writeMu.Lock() - _, err := t.sess.Conn.Write(buf) - t.writeMu.Unlock() - - if err != nil { - return fmt.Errorf("write frames: %w", err) + select { + case t.writeCh <- buf: + return t.writeErr + case <-t.stopCh: + return fmt.Errorf("tunnel closed") } - return nil } // FrameHandler is called for each Ethernet frame received from the server. @@ -188,18 +204,15 @@ func (t *Tunnel) StartKeepalive() { size := uint32(rng.Intn(int(maxKeepaliveSize))) + 1 rng.Read(randBuf[:size]) - t.writeMu.Lock() - err1 := binary.Write(t.sess.Conn, binary.BigEndian, keepAliveMagic) - var err2, err3 error - if err1 == nil { - err2 = binary.Write(t.sess.Conn, binary.BigEndian, size) - } - if err2 == nil { - _, err3 = t.sess.Conn.Write(randBuf[:size]) - } - t.writeMu.Unlock() + // Assemble keepalive into one buffer + buf := make([]byte, 8+size) + binary.BigEndian.PutUint32(buf[0:4], keepAliveMagic) + binary.BigEndian.PutUint32(buf[4:8], size) + copy(buf[8:], randBuf[:size]) - if err1 != nil || err2 != nil || err3 != nil { + select { + case t.writeCh <- buf: + case <-t.stopCh: return } } From 1fceb30873f3684998abc96df392867225a54dca Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 6 Jun 2026 23:16:27 +0530 Subject: [PATCH 16/26] tunnel: replace write mutex with channel-based single writer All writes (frames, keepalive, DHCP renewal) are queued to a buffered channel and drained by a single writer goroutine. Eliminates mutex contention on the data path entirely. Co-Authored-By: Claude Opus 4.6 (1M context) --- pkg/client/tunnel.go | 63 ++++++++++++++++++++++++++------------------ 1 file changed, 38 insertions(+), 25 deletions(-) diff --git a/pkg/client/tunnel.go b/pkg/client/tunnel.go index 5a36c44..1332204 100644 --- a/pkg/client/tunnel.go +++ b/pkg/client/tunnel.go @@ -22,13 +22,15 @@ const ( keepAliveMagic uint32 = 0xFFFFFFFF // Magic value indicating a keepalive packet maxKeepaliveSize uint32 = 512 // Max random data in keepalive keepAliveInterval = 3 * time.Second + writeChanSize = 128 // Buffered write queue depth ) // Tunnel handles bidirectional TCP block framing for Ethernet frames over a // SoftEther VPN session. Each "block" is one Ethernet frame. type Tunnel struct { sess *Session - writeMu sync.Mutex + writeCh chan []byte // serialized messages queued for the single writer + writeErr error // last write error stopCh chan struct{} stopped sync.Once } @@ -36,15 +38,32 @@ type Tunnel struct { // NewTunnel creates a tunnel from an established session. // Call StartKeepalive() before reading/writing frames. func NewTunnel(sess *Session) *Tunnel { - return &Tunnel{ - sess: sess, - stopCh: make(chan struct{}), + t := &Tunnel{ + sess: sess, + writeCh: make(chan []byte, writeChanSize), + stopCh: make(chan struct{}), + } + go t.writeLoop() + return t +} + +// writeLoop is the single goroutine that writes to the connection. +// All writes are serialized through writeCh — no mutex needed. +func (t *Tunnel) writeLoop() { + for buf := range t.writeCh { + if _, err := t.sess.Conn.Write(buf); err != nil { + t.writeErr = err + return + } } } // Close stops the keepalive goroutine and closes the underlying connection. func (t *Tunnel) Close() error { - t.stopped.Do(func() { close(t.stopCh) }) + t.stopped.Do(func() { + close(t.stopCh) + close(t.writeCh) + }) return t.sess.Conn.Close() } @@ -84,8 +103,7 @@ func (t *Tunnel) ReadFrames() ([][]byte, error) { } // WriteFrames sends a batch of Ethernet frames to the server. -// Safe for concurrent use from multiple goroutines. -// Assembles the entire message into one buffer for a single TLS write. +// Safe for concurrent use — messages are queued for the single writer goroutine. func (t *Tunnel) WriteFrames(frames [][]byte) error { // Calculate total size: 4 (numBlocks) + per frame: 4 (size) + len(data) total := 4 @@ -104,14 +122,12 @@ func (t *Tunnel) WriteFrames(frames [][]byte) error { off += len(f) } - t.writeMu.Lock() - _, err := t.sess.Conn.Write(buf) - t.writeMu.Unlock() - - if err != nil { - return fmt.Errorf("write frames: %w", err) + select { + case t.writeCh <- buf: + return t.writeErr + case <-t.stopCh: + return fmt.Errorf("tunnel closed") } - return nil } // FrameHandler is called for each Ethernet frame received from the server. @@ -188,18 +204,15 @@ func (t *Tunnel) StartKeepalive() { size := uint32(rng.Intn(int(maxKeepaliveSize))) + 1 rng.Read(randBuf[:size]) - t.writeMu.Lock() - err1 := binary.Write(t.sess.Conn, binary.BigEndian, keepAliveMagic) - var err2, err3 error - if err1 == nil { - err2 = binary.Write(t.sess.Conn, binary.BigEndian, size) - } - if err2 == nil { - _, err3 = t.sess.Conn.Write(randBuf[:size]) - } - t.writeMu.Unlock() + // Assemble keepalive into one buffer + buf := make([]byte, 8+size) + binary.BigEndian.PutUint32(buf[0:4], keepAliveMagic) + binary.BigEndian.PutUint32(buf[4:8], size) + copy(buf[8:], randBuf[:size]) - if err1 != nil || err2 != nil || err3 != nil { + select { + case t.writeCh <- buf: + case <-t.stopCh: return } } From 857733863c70b6bf3e9a114a2a03c617d7981f1e Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sun, 7 Jun 2026 00:42:56 +0530 Subject: [PATCH 17/26] netcfg: suppress RTNETLINK errors from policy route cleanup Use runQuiet for ip rule/route del commands that may fail harmlessly when no existing rule exists (e.g. first run after deploy). Co-Authored-By: Claude Opus 4.6 (1M context) --- pkg/netcfg/netcfg.go | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/pkg/netcfg/netcfg.go b/pkg/netcfg/netcfg.go index 2c46837..47ead19 100644 --- a/pkg/netcfg/netcfg.go +++ b/pkg/netcfg/netcfg.go @@ -99,7 +99,7 @@ func ConfigurePolicyRoute(ifname string, lease *dhcp.Lease, table int) func() { clientIP := lease.ClientIP.String() gw := lease.Gateway.String() - run("ip", "rule", "del", "table", t) + runQuiet("ip", "rule", "del", "table", t) run("ip", "route", "replace", "default", "via", gw, "dev", ifname, "table", t) if err := run("ip", "rule", "add", "from", clientIP, "table", t); err != nil { log.Printf("warning: policy rule: %v", err) @@ -108,8 +108,8 @@ func ConfigurePolicyRoute(ifname string, lease *dhcp.Lease, table int) func() { } return func() { - run("ip", "rule", "del", "table", t) - run("ip", "route", "del", "default", "table", t) + runQuiet("ip", "rule", "del", "table", t) + runQuiet("ip", "route", "del", "default", "table", t) log.Printf("policy route: cleaned up table %s", t) } } @@ -233,3 +233,7 @@ func run(name string, args ...string) error { cmd.Stderr = os.Stderr return cmd.Run() } + +func runQuiet(name string, args ...string) error { + return exec.Command(name, args...).Run() +} From 42ae25b281778af4f9420ff901217d2e3461e433 Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sun, 7 Jun 2026 00:42:56 +0530 Subject: [PATCH 18/26] netcfg: suppress RTNETLINK errors from policy route cleanup Use runQuiet for ip rule/route del commands that may fail harmlessly when no existing rule exists (e.g. first run after deploy). Co-Authored-By: Claude Opus 4.6 (1M context) --- pkg/netcfg/netcfg.go | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/pkg/netcfg/netcfg.go b/pkg/netcfg/netcfg.go index 2c46837..47ead19 100644 --- a/pkg/netcfg/netcfg.go +++ b/pkg/netcfg/netcfg.go @@ -99,7 +99,7 @@ func ConfigurePolicyRoute(ifname string, lease *dhcp.Lease, table int) func() { clientIP := lease.ClientIP.String() gw := lease.Gateway.String() - run("ip", "rule", "del", "table", t) + runQuiet("ip", "rule", "del", "table", t) run("ip", "route", "replace", "default", "via", gw, "dev", ifname, "table", t) if err := run("ip", "rule", "add", "from", clientIP, "table", t); err != nil { log.Printf("warning: policy rule: %v", err) @@ -108,8 +108,8 @@ func ConfigurePolicyRoute(ifname string, lease *dhcp.Lease, table int) func() { } return func() { - run("ip", "rule", "del", "table", t) - run("ip", "route", "del", "default", "table", t) + runQuiet("ip", "rule", "del", "table", t) + runQuiet("ip", "route", "del", "default", "table", t) log.Printf("policy route: cleaned up table %s", t) } } @@ -233,3 +233,7 @@ func run(name string, args ...string) error { cmd.Stderr = os.Stderr return cmd.Run() } + +func runQuiet(name string, args ...string) error { + return exec.Command(name, args...).Run() +} From 51824b830ea4640b93efb40a42537d6092b6e150 Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sun, 7 Jun 2026 01:00:43 +0530 Subject: [PATCH 19/26] netcfg: add -connmark flag for DNAT reply routing When VPN traffic is DNAT'd to local namespaces/VMs, reply packets have a different source IP (namespace veth) so the policy route's "from " rule doesn't match. CONNMARK marks all connections arriving on the VPN interface and restores the mark on reply packets, routing them back through the tunnel via fwmark rule. New flag: -connmark (requires -policy-route-table) Co-Authored-By: Claude Opus 4.6 (1M context) --- CLAUDE.md | 9 ++++++--- README.md | 10 +++++++++- cmd/softether-go/main.go | 2 ++ cmd/softether-go/session.go | 4 ++-- pkg/netcfg/netcfg.go | 33 ++++++++++++++++++++++++++++++++- 5 files changed, 51 insertions(+), 7 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 5bd87a0..c7ba978 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,7 +57,7 @@ pkg/tap/ ## CLI flags Required: `-host`, `-user` -Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-no-dhcp`, `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-reconnect-delay` (5s) +Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-no-dhcp`, `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-connmark`, `-reconnect-delay` (5s) ## SoftEther protocol pitfalls @@ -96,6 +96,9 @@ Before connecting, resolves server hostname and adds `/32` route via current def ### Policy routing `-policy-route-table N` adds `ip rule from table N` + `ip route replace default via dev table N`. Needed when VPN server port-forwards to client — ensures reply packets go back through VPN tunnel, not default route. +### CONNMARK for DNAT reply routing +`-connmark` (requires `-policy-route-table`) adds iptables CONNMARK rules so DNAT'd connections (port forwards to namespaces/VMs) have replies routed back through the tunnel. Without this, replies from DNAT targets use the default route because their source IP doesn't match the `from ` policy rule. CONNMARK marks incoming VPN connections and restores the mark on reply packets. + ## Performance - **RAM**: 4.6 MB RSS idle, flat under 97 Mbit/s load (vs SoftEther C client: ~23 MB across 4 processes) @@ -125,7 +128,7 @@ Equivalent softether-go command: softether-go -host 65-20-68-5.ip.fresh.ipb.cloud -port 992 \ -user T0Eq5yf97gXy8Q -plain-password -insecure \ -tap india-pub-ip -mac 5E:3B:6F:63:A8:3E \ - -policy-route-table 200 + -policy-route-table 200 -connmark ``` To add as flake input: `softether-go.url = "git+https://git.sagar.ch/sagar/softether-go.git";` @@ -133,5 +136,5 @@ To add as flake input: `softether-go.url = "git+https://git.sagar.ch/sagar/softe ## Dependencies - Go 1.24+, single dep: `golang.org/x/sys` (vendored) -- Runtime: `ip` (iproute2) +- Runtime: `ip` (iproute2), `iptables` (only for `-connmark`) - `vendorHash = null` in flake.nix (deps are vendored) diff --git a/README.md b/README.md index 85b84fc..291dd35 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ Standalone SoftEther VPN client written in Go. Connects to SoftEther VPN servers - Host route to VPN server via existing default gateway (prevents routing loops) - Classless static routes (DHCP option 121/249, RFC 3442) - Policy routing for asymmetric return paths (VPN port forwards) +- CONNMARK-based DNAT reply routing (for port forwards to namespaces/VMs) - DNS configuration from DHCP lease (backup/restore of `/etc/resolv.conf`) - Deterministic MAC address support for stable DHCP assignments - Hashed password (SHA-0) and plaintext password (RADIUS/external) authentication @@ -20,6 +21,7 @@ Standalone SoftEther VPN client written in Go. Connects to SoftEther VPN servers - Linux (uses `/dev/net/tun` for TAP devices) - `CAP_NET_ADMIN` or root (TAP device creation, route management) - `ip` command (iproute2) on `$PATH` +- `iptables` on `$PATH` (only if using `-connmark`) ## Building @@ -79,6 +81,7 @@ softether-go [flags] | `-accept-static-routes` | `false` | Install DHCP classless static routes (option 121/249) | | `-accept-dns` | `false` | Set `/etc/resolv.conf` from DHCP-provided DNS servers | | `-policy-route-table` | `0` | Policy routing table number (0 = disabled) | +| `-connmark` | `false` | Use CONNMARK to route DNAT reply traffic back through VPN | | `-reconnect-delay` | `5s` | Delay between reconnection attempts | ### Authentication @@ -107,6 +110,8 @@ softether-go -host vpn.example.com -user admin -pass secret -plain-password **`-policy-route-table N`** — policy routing for asymmetric return paths. Adds `ip rule from table N` and `ip route replace default via dev table N`. Needed when the VPN server forwards ports to the client. +**`-connmark`** — requires `-policy-route-table`. Uses iptables CONNMARK to route DNAT reply traffic back through the VPN tunnel. Without this, traffic forwarded to local namespaces/VMs (via DNAT) gets replies routed via the default gateway instead of the tunnel, breaking the connection. Adds `CONNMARK --set-mark` on incoming VPN packets and `CONNMARK --restore-mark` on reply packets from other interfaces. + ### Examples Minimal: @@ -128,7 +133,8 @@ softether-go \ -accept-default-gateway \ -accept-static-routes \ -accept-dns \ - -policy-route-table 200 + -policy-route-table 200 \ + -connmark ``` No DHCP (manual config): @@ -224,6 +230,8 @@ DHCP options requested: subnet mask (1), router (3), DNS (6), lease time (51), c **Policy routing** — `ip rule from table N` ensures reply packets for VPN port forwards go back through the tunnel, not the default route. +**CONNMARK (`-connmark`)** — solves a subtler routing problem: when VPN traffic is DNAT'd to a local namespace or VM, the reply packets have a different source IP (the namespace veth) so the `from ` rule doesn't match. CONNMARK marks all connections arriving on the VPN interface, then restores the mark on reply packets from any interface, routing them back through the tunnel via `fwmark` rule. + ### Password hashing SoftEther uses **SHA-0** (not SHA-1) — no left-rotate in message schedule. `HashedPassword = SHA0(password)`, `SecurePassword = SHA0(HashedPassword + ServerRandom)`. Plaintext auth (AuthType 2) sends password as-is over TLS. diff --git a/cmd/softether-go/main.go b/cmd/softether-go/main.go index b00bc8b..82e667c 100644 --- a/cmd/softether-go/main.go +++ b/cmd/softether-go/main.go @@ -36,6 +36,7 @@ func main() { acceptStaticRoutes := flag.Bool("accept-static-routes", false, "Install DHCP classless static routes (option 121/249)") acceptDNS := flag.Bool("accept-dns", false, "Set /etc/resolv.conf from DHCP-provided DNS servers") policyRouteTable := flag.Int("policy-route-table", 0, "Policy routing table: route replies from VPN IP back through VPN gateway") + connMark := flag.Bool("connmark", false, "Use CONNMARK to route DNAT reply traffic back through VPN (for port forwards to namespaces/VMs)") flag.Parse() @@ -94,6 +95,7 @@ func main() { AcceptStaticRoutes: *acceptStaticRoutes, AcceptDNS: *acceptDNS, PolicyRouteTable: *policyRouteTable, + ConnMark: *connMark, } for { diff --git a/cmd/softether-go/session.go b/cmd/softether-go/session.go index 8cf8f41..bb7a285 100644 --- a/cmd/softether-go/session.go +++ b/cmd/softether-go/session.go @@ -59,7 +59,7 @@ func runSession(cfg client.Config, dev *tap.Device, mac net.HardwareAddr, opts n defer cleanup() if opts.PolicyRouteTable > 0 && lease.Gateway != nil { - defer netcfg.ConfigurePolicyRoute(dev.Name, lease, opts.PolicyRouteTable)() + defer netcfg.ConfigurePolicyRoute(dev.Name, lease, opts.PolicyRouteTable, opts.ConnMark)() } // Start DHCP renewal at T/2 @@ -111,7 +111,7 @@ func renewLoop(dc *dhcp.Client, tunnel *client.Tunnel, ifname string, lease *dhc log.Printf("dhcp: IP changed %s → %s, reconfiguring", currentIP, newLease.ClientIP) netcfg.ReconfigureTAP(ifname, newLease, opts.AcceptDefaultGW, opts.AcceptStaticRoutes, opts.AcceptDNS) if opts.PolicyRouteTable > 0 && newLease.Gateway != nil { - netcfg.ConfigurePolicyRoute(ifname, newLease, opts.PolicyRouteTable) + netcfg.ConfigurePolicyRoute(ifname, newLease, opts.PolicyRouteTable, opts.ConnMark) } currentIP = newLease.ClientIP } diff --git a/pkg/netcfg/netcfg.go b/pkg/netcfg/netcfg.go index 47ead19..8281347 100644 --- a/pkg/netcfg/netcfg.go +++ b/pkg/netcfg/netcfg.go @@ -21,6 +21,7 @@ type Options struct { AcceptStaticRoutes bool AcceptDNS bool PolicyRouteTable int + ConnMark bool } // ConfigureTAP sets the IP address, routes, and DNS on a TAP interface from a DHCP lease. @@ -94,11 +95,16 @@ func ReconfigureTAP(ifname string, lease *dhcp.Lease, acceptDefaultGW, acceptSta // ConfigurePolicyRoute sets up policy routing so packets from the VPN IP are routed // back through the VPN gateway. Needed when the VPN server forwards ports to the // client — without it, reply packets use the default route instead of the VPN tunnel. -func ConfigurePolicyRoute(ifname string, lease *dhcp.Lease, table int) func() { +// +// When connmark is true, also sets up CONNMARK rules so that DNAT'd connections +// (e.g. port forwards to namespaces/VMs) have their reply traffic routed back +// through the tunnel. +func ConfigurePolicyRoute(ifname string, lease *dhcp.Lease, table int, connmark bool) func() { t := fmt.Sprintf("%d", table) clientIP := lease.ClientIP.String() gw := lease.Gateway.String() + // Policy route: packets from VPN IP use VPN gateway runQuiet("ip", "rule", "del", "table", t) run("ip", "route", "replace", "default", "via", gw, "dev", ifname, "table", t) if err := run("ip", "rule", "add", "from", clientIP, "table", t); err != nil { @@ -107,9 +113,34 @@ func ConfigurePolicyRoute(ifname string, lease *dhcp.Lease, table int) func() { log.Printf("policy route: from %s via %s dev %s table %s", clientIP, gw, ifname, t) } + if connmark { + mark := t + // CONNMARK: mark connections arriving on VPN interface, restore mark on replies. + // This ensures DNAT'd traffic (forwarded to namespaces/VMs) returns via the + // tunnel instead of the default route. Without this, reply packets from DNAT + // targets (e.g. namespace veth) have a different source IP than the VPN IP, + // so the "from " policy rule doesn't match them. + log.Printf("connmark: adding CONNMARK rules on %s (mark %s)", ifname, mark) + runQuiet("ip", "rule", "del", "fwmark", mark, "table", t) + run("iptables", "-t", "mangle", "-A", "PREROUTING", "-i", ifname, "-j", "CONNMARK", "--set-mark", mark) + run("iptables", "-t", "mangle", "-A", "PREROUTING", "!", "-i", ifname, "-m", "connmark", "--mark", mark, "-j", "CONNMARK", "--restore-mark") + if err := run("ip", "rule", "add", "fwmark", mark, "table", t); err != nil { + log.Printf("warning: fwmark rule: %v", err) + } else { + log.Printf("connmark: fwmark %s → table %s for DNAT reply routing", mark, t) + } + } + return func() { runQuiet("ip", "rule", "del", "table", t) runQuiet("ip", "route", "del", "default", "table", t) + if connmark { + mark := t + log.Printf("connmark: removing CONNMARK rules (mark %s)", mark) + runQuiet("ip", "rule", "del", "fwmark", mark, "table", t) + runQuiet("iptables", "-t", "mangle", "-D", "PREROUTING", "-i", ifname, "-j", "CONNMARK", "--set-mark", mark) + runQuiet("iptables", "-t", "mangle", "-D", "PREROUTING", "!", "-i", ifname, "-m", "connmark", "--mark", mark, "-j", "CONNMARK", "--restore-mark") + } log.Printf("policy route: cleaned up table %s", t) } } From 629e2cce8d44504d6e0b0c5751d051cefe82ef24 Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sun, 7 Jun 2026 01:00:43 +0530 Subject: [PATCH 20/26] netcfg: add -connmark flag for DNAT reply routing When VPN traffic is DNAT'd to local namespaces/VMs, reply packets have a different source IP (namespace veth) so the policy route's "from " rule doesn't match. CONNMARK marks all connections arriving on the VPN interface and restores the mark on reply packets, routing them back through the tunnel via fwmark rule. New flag: -connmark (requires -policy-route-table) Co-Authored-By: Claude Opus 4.6 (1M context) --- CLAUDE.md | 9 ++++++--- README.md | 10 +++++++++- cmd/softether-go/main.go | 2 ++ cmd/softether-go/session.go | 4 ++-- pkg/netcfg/netcfg.go | 33 ++++++++++++++++++++++++++++++++- 5 files changed, 51 insertions(+), 7 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 27732a3..6f2b60e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,7 +57,7 @@ pkg/tap/ ## CLI flags Required: `-host`, `-user` -Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-no-dhcp`, `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-reconnect-delay` (5s) +Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-no-dhcp`, `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-connmark`, `-reconnect-delay` (5s) ## SoftEther protocol pitfalls @@ -96,6 +96,9 @@ Before connecting, resolves server hostname and adds `/32` route via current def ### Policy routing `-policy-route-table N` adds `ip rule from table N` + `ip route replace default via dev table N`. Needed when VPN server port-forwards to client — ensures reply packets go back through VPN tunnel, not default route. +### CONNMARK for DNAT reply routing +`-connmark` (requires `-policy-route-table`) adds iptables CONNMARK rules so DNAT'd connections (port forwards to namespaces/VMs) have replies routed back through the tunnel. Without this, replies from DNAT targets use the default route because their source IP doesn't match the `from ` policy rule. CONNMARK marks incoming VPN connections and restores the mark on reply packets. + ## Performance - **RAM**: 4.6 MB RSS idle, flat under 97 Mbit/s load (vs SoftEther C client: ~23 MB across 4 processes) @@ -125,7 +128,7 @@ Equivalent softether-go command: softether-go -host 65-20-68-5.ip.fresh.ipb.cloud -port 992 \ -user -plain-password -insecure \ -tap india-pub-ip -mac 5E:3B:6F:63:A8:3E \ - -policy-route-table 200 + -policy-route-table 200 -connmark ``` To add as flake input: `softether-go.url = "git+https://git.sagar.ch/sagar/softether-go.git";` @@ -133,5 +136,5 @@ To add as flake input: `softether-go.url = "git+https://git.sagar.ch/sagar/softe ## Dependencies - Go 1.24+, single dep: `golang.org/x/sys` (vendored) -- Runtime: `ip` (iproute2) +- Runtime: `ip` (iproute2), `iptables` (only for `-connmark`) - `vendorHash = null` in flake.nix (deps are vendored) diff --git a/README.md b/README.md index 85b84fc..291dd35 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ Standalone SoftEther VPN client written in Go. Connects to SoftEther VPN servers - Host route to VPN server via existing default gateway (prevents routing loops) - Classless static routes (DHCP option 121/249, RFC 3442) - Policy routing for asymmetric return paths (VPN port forwards) +- CONNMARK-based DNAT reply routing (for port forwards to namespaces/VMs) - DNS configuration from DHCP lease (backup/restore of `/etc/resolv.conf`) - Deterministic MAC address support for stable DHCP assignments - Hashed password (SHA-0) and plaintext password (RADIUS/external) authentication @@ -20,6 +21,7 @@ Standalone SoftEther VPN client written in Go. Connects to SoftEther VPN servers - Linux (uses `/dev/net/tun` for TAP devices) - `CAP_NET_ADMIN` or root (TAP device creation, route management) - `ip` command (iproute2) on `$PATH` +- `iptables` on `$PATH` (only if using `-connmark`) ## Building @@ -79,6 +81,7 @@ softether-go [flags] | `-accept-static-routes` | `false` | Install DHCP classless static routes (option 121/249) | | `-accept-dns` | `false` | Set `/etc/resolv.conf` from DHCP-provided DNS servers | | `-policy-route-table` | `0` | Policy routing table number (0 = disabled) | +| `-connmark` | `false` | Use CONNMARK to route DNAT reply traffic back through VPN | | `-reconnect-delay` | `5s` | Delay between reconnection attempts | ### Authentication @@ -107,6 +110,8 @@ softether-go -host vpn.example.com -user admin -pass secret -plain-password **`-policy-route-table N`** — policy routing for asymmetric return paths. Adds `ip rule from table N` and `ip route replace default via dev table N`. Needed when the VPN server forwards ports to the client. +**`-connmark`** — requires `-policy-route-table`. Uses iptables CONNMARK to route DNAT reply traffic back through the VPN tunnel. Without this, traffic forwarded to local namespaces/VMs (via DNAT) gets replies routed via the default gateway instead of the tunnel, breaking the connection. Adds `CONNMARK --set-mark` on incoming VPN packets and `CONNMARK --restore-mark` on reply packets from other interfaces. + ### Examples Minimal: @@ -128,7 +133,8 @@ softether-go \ -accept-default-gateway \ -accept-static-routes \ -accept-dns \ - -policy-route-table 200 + -policy-route-table 200 \ + -connmark ``` No DHCP (manual config): @@ -224,6 +230,8 @@ DHCP options requested: subnet mask (1), router (3), DNS (6), lease time (51), c **Policy routing** — `ip rule from table N` ensures reply packets for VPN port forwards go back through the tunnel, not the default route. +**CONNMARK (`-connmark`)** — solves a subtler routing problem: when VPN traffic is DNAT'd to a local namespace or VM, the reply packets have a different source IP (the namespace veth) so the `from ` rule doesn't match. CONNMARK marks all connections arriving on the VPN interface, then restores the mark on reply packets from any interface, routing them back through the tunnel via `fwmark` rule. + ### Password hashing SoftEther uses **SHA-0** (not SHA-1) — no left-rotate in message schedule. `HashedPassword = SHA0(password)`, `SecurePassword = SHA0(HashedPassword + ServerRandom)`. Plaintext auth (AuthType 2) sends password as-is over TLS. diff --git a/cmd/softether-go/main.go b/cmd/softether-go/main.go index b00bc8b..82e667c 100644 --- a/cmd/softether-go/main.go +++ b/cmd/softether-go/main.go @@ -36,6 +36,7 @@ func main() { acceptStaticRoutes := flag.Bool("accept-static-routes", false, "Install DHCP classless static routes (option 121/249)") acceptDNS := flag.Bool("accept-dns", false, "Set /etc/resolv.conf from DHCP-provided DNS servers") policyRouteTable := flag.Int("policy-route-table", 0, "Policy routing table: route replies from VPN IP back through VPN gateway") + connMark := flag.Bool("connmark", false, "Use CONNMARK to route DNAT reply traffic back through VPN (for port forwards to namespaces/VMs)") flag.Parse() @@ -94,6 +95,7 @@ func main() { AcceptStaticRoutes: *acceptStaticRoutes, AcceptDNS: *acceptDNS, PolicyRouteTable: *policyRouteTable, + ConnMark: *connMark, } for { diff --git a/cmd/softether-go/session.go b/cmd/softether-go/session.go index 8cf8f41..bb7a285 100644 --- a/cmd/softether-go/session.go +++ b/cmd/softether-go/session.go @@ -59,7 +59,7 @@ func runSession(cfg client.Config, dev *tap.Device, mac net.HardwareAddr, opts n defer cleanup() if opts.PolicyRouteTable > 0 && lease.Gateway != nil { - defer netcfg.ConfigurePolicyRoute(dev.Name, lease, opts.PolicyRouteTable)() + defer netcfg.ConfigurePolicyRoute(dev.Name, lease, opts.PolicyRouteTable, opts.ConnMark)() } // Start DHCP renewal at T/2 @@ -111,7 +111,7 @@ func renewLoop(dc *dhcp.Client, tunnel *client.Tunnel, ifname string, lease *dhc log.Printf("dhcp: IP changed %s → %s, reconfiguring", currentIP, newLease.ClientIP) netcfg.ReconfigureTAP(ifname, newLease, opts.AcceptDefaultGW, opts.AcceptStaticRoutes, opts.AcceptDNS) if opts.PolicyRouteTable > 0 && newLease.Gateway != nil { - netcfg.ConfigurePolicyRoute(ifname, newLease, opts.PolicyRouteTable) + netcfg.ConfigurePolicyRoute(ifname, newLease, opts.PolicyRouteTable, opts.ConnMark) } currentIP = newLease.ClientIP } diff --git a/pkg/netcfg/netcfg.go b/pkg/netcfg/netcfg.go index 47ead19..8281347 100644 --- a/pkg/netcfg/netcfg.go +++ b/pkg/netcfg/netcfg.go @@ -21,6 +21,7 @@ type Options struct { AcceptStaticRoutes bool AcceptDNS bool PolicyRouteTable int + ConnMark bool } // ConfigureTAP sets the IP address, routes, and DNS on a TAP interface from a DHCP lease. @@ -94,11 +95,16 @@ func ReconfigureTAP(ifname string, lease *dhcp.Lease, acceptDefaultGW, acceptSta // ConfigurePolicyRoute sets up policy routing so packets from the VPN IP are routed // back through the VPN gateway. Needed when the VPN server forwards ports to the // client — without it, reply packets use the default route instead of the VPN tunnel. -func ConfigurePolicyRoute(ifname string, lease *dhcp.Lease, table int) func() { +// +// When connmark is true, also sets up CONNMARK rules so that DNAT'd connections +// (e.g. port forwards to namespaces/VMs) have their reply traffic routed back +// through the tunnel. +func ConfigurePolicyRoute(ifname string, lease *dhcp.Lease, table int, connmark bool) func() { t := fmt.Sprintf("%d", table) clientIP := lease.ClientIP.String() gw := lease.Gateway.String() + // Policy route: packets from VPN IP use VPN gateway runQuiet("ip", "rule", "del", "table", t) run("ip", "route", "replace", "default", "via", gw, "dev", ifname, "table", t) if err := run("ip", "rule", "add", "from", clientIP, "table", t); err != nil { @@ -107,9 +113,34 @@ func ConfigurePolicyRoute(ifname string, lease *dhcp.Lease, table int) func() { log.Printf("policy route: from %s via %s dev %s table %s", clientIP, gw, ifname, t) } + if connmark { + mark := t + // CONNMARK: mark connections arriving on VPN interface, restore mark on replies. + // This ensures DNAT'd traffic (forwarded to namespaces/VMs) returns via the + // tunnel instead of the default route. Without this, reply packets from DNAT + // targets (e.g. namespace veth) have a different source IP than the VPN IP, + // so the "from " policy rule doesn't match them. + log.Printf("connmark: adding CONNMARK rules on %s (mark %s)", ifname, mark) + runQuiet("ip", "rule", "del", "fwmark", mark, "table", t) + run("iptables", "-t", "mangle", "-A", "PREROUTING", "-i", ifname, "-j", "CONNMARK", "--set-mark", mark) + run("iptables", "-t", "mangle", "-A", "PREROUTING", "!", "-i", ifname, "-m", "connmark", "--mark", mark, "-j", "CONNMARK", "--restore-mark") + if err := run("ip", "rule", "add", "fwmark", mark, "table", t); err != nil { + log.Printf("warning: fwmark rule: %v", err) + } else { + log.Printf("connmark: fwmark %s → table %s for DNAT reply routing", mark, t) + } + } + return func() { runQuiet("ip", "rule", "del", "table", t) runQuiet("ip", "route", "del", "default", "table", t) + if connmark { + mark := t + log.Printf("connmark: removing CONNMARK rules (mark %s)", mark) + runQuiet("ip", "rule", "del", "fwmark", mark, "table", t) + runQuiet("iptables", "-t", "mangle", "-D", "PREROUTING", "-i", ifname, "-j", "CONNMARK", "--set-mark", mark) + runQuiet("iptables", "-t", "mangle", "-D", "PREROUTING", "!", "-i", ifname, "-m", "connmark", "--mark", mark, "-j", "CONNMARK", "--restore-mark") + } log.Printf("policy route: cleaned up table %s", t) } } From 1d919aafc5a14bd9c70481e59449acfd11b1b5c8 Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sun, 7 Jun 2026 16:29:08 +0530 Subject: [PATCH 21/26] tunnel: fix panic on send to closed writeCh during disconnect MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the server disconnects, Close() was closing both stopCh and writeCh. The TAP→Server goroutine could race and send to the closed writeCh, causing a panic. Fix: don't close writeCh in Close(), let writeLoop exit via stopCh instead. Co-Authored-By: Claude Opus 4.6 (1M context) --- pkg/client/tunnel.go | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/pkg/client/tunnel.go b/pkg/client/tunnel.go index 1332204..9d9d2a2 100644 --- a/pkg/client/tunnel.go +++ b/pkg/client/tunnel.go @@ -6,6 +6,7 @@ import ( "io" "math/rand" "sync" + "sync/atomic" "time" ) @@ -29,8 +30,8 @@ const ( // SoftEther VPN session. Each "block" is one Ethernet frame. type Tunnel struct { sess *Session - writeCh chan []byte // serialized messages queued for the single writer - writeErr error // last write error + writeCh chan []byte // serialized messages queued for the single writer + writeErr atomic.Value // stores error from writeLoop stopCh chan struct{} stopped sync.Once } @@ -50,20 +51,23 @@ func NewTunnel(sess *Session) *Tunnel { // writeLoop is the single goroutine that writes to the connection. // All writes are serialized through writeCh — no mutex needed. func (t *Tunnel) writeLoop() { - for buf := range t.writeCh { - if _, err := t.sess.Conn.Write(buf); err != nil { - t.writeErr = err + for { + select { + case buf := <-t.writeCh: + if _, err := t.sess.Conn.Write(buf); err != nil { + t.writeErr.Store(err) + return + } + case <-t.stopCh: return } } } // Close stops the keepalive goroutine and closes the underlying connection. +// The writeCh is not closed here — writeLoop exits when the connection write fails. func (t *Tunnel) Close() error { - t.stopped.Do(func() { - close(t.stopCh) - close(t.writeCh) - }) + t.stopped.Do(func() { close(t.stopCh) }) return t.sess.Conn.Close() } @@ -124,7 +128,10 @@ func (t *Tunnel) WriteFrames(frames [][]byte) error { select { case t.writeCh <- buf: - return t.writeErr + if err, ok := t.writeErr.Load().(error); ok { + return err + } + return nil case <-t.stopCh: return fmt.Errorf("tunnel closed") } From c248661eaf7f342f14f11ccb2760a5b46d81f3e7 Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sun, 7 Jun 2026 16:29:08 +0530 Subject: [PATCH 22/26] tunnel: fix panic on send to closed writeCh during disconnect MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the server disconnects, Close() was closing both stopCh and writeCh. The TAP→Server goroutine could race and send to the closed writeCh, causing a panic. Fix: don't close writeCh in Close(), let writeLoop exit via stopCh instead. Co-Authored-By: Claude Opus 4.6 (1M context) --- pkg/client/tunnel.go | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/pkg/client/tunnel.go b/pkg/client/tunnel.go index 1332204..9d9d2a2 100644 --- a/pkg/client/tunnel.go +++ b/pkg/client/tunnel.go @@ -6,6 +6,7 @@ import ( "io" "math/rand" "sync" + "sync/atomic" "time" ) @@ -29,8 +30,8 @@ const ( // SoftEther VPN session. Each "block" is one Ethernet frame. type Tunnel struct { sess *Session - writeCh chan []byte // serialized messages queued for the single writer - writeErr error // last write error + writeCh chan []byte // serialized messages queued for the single writer + writeErr atomic.Value // stores error from writeLoop stopCh chan struct{} stopped sync.Once } @@ -50,20 +51,23 @@ func NewTunnel(sess *Session) *Tunnel { // writeLoop is the single goroutine that writes to the connection. // All writes are serialized through writeCh — no mutex needed. func (t *Tunnel) writeLoop() { - for buf := range t.writeCh { - if _, err := t.sess.Conn.Write(buf); err != nil { - t.writeErr = err + for { + select { + case buf := <-t.writeCh: + if _, err := t.sess.Conn.Write(buf); err != nil { + t.writeErr.Store(err) + return + } + case <-t.stopCh: return } } } // Close stops the keepalive goroutine and closes the underlying connection. +// The writeCh is not closed here — writeLoop exits when the connection write fails. func (t *Tunnel) Close() error { - t.stopped.Do(func() { - close(t.stopCh) - close(t.writeCh) - }) + t.stopped.Do(func() { close(t.stopCh) }) return t.sess.Conn.Close() } @@ -124,7 +128,10 @@ func (t *Tunnel) WriteFrames(frames [][]byte) error { select { case t.writeCh <- buf: - return t.writeErr + if err, ok := t.writeErr.Load().(error); ok { + return err + } + return nil case <-t.stopCh: return fmt.Errorf("tunnel closed") } From 1a397c363f26b516bf32bd9cfed3e42af2a39b4b Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 11 Jul 2026 11:54:12 -0300 Subject: [PATCH 23/26] tunnel: add -keepalive-timeout-secs for dead connection detection Tracks last server receive time (atomic) and runs a watchdog goroutine that closes the connection if no data arrives within the timeout, triggering reconnection. Also fixes Close() to guard Conn.Close() inside sync.Once so concurrent/repeated calls are safe. Co-Authored-By: Claude Opus 4.6 (1M context) --- CLAUDE.md | 5 +++- README.md | 5 +++- cmd/softether-go/main.go | 3 +- cmd/softether-go/session.go | 4 +-- pkg/client/tunnel.go | 58 ++++++++++++++++++++++++++++--------- 5 files changed, 57 insertions(+), 18 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index c7ba978..d9ce20b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,7 +57,7 @@ pkg/tap/ ## CLI flags Required: `-host`, `-user` -Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-no-dhcp`, `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-connmark`, `-reconnect-delay` (5s) +Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-no-dhcp`, `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-connmark`, `-reconnect-delay` (5s), `-keepalive-timeout-secs` (0=disabled) ## SoftEther protocol pitfalls @@ -99,6 +99,9 @@ Before connecting, resolves server hostname and adds `/32` route via current def ### CONNMARK for DNAT reply routing `-connmark` (requires `-policy-route-table`) adds iptables CONNMARK rules so DNAT'd connections (port forwards to namespaces/VMs) have replies routed back through the tunnel. Without this, replies from DNAT targets use the default route because their source IP doesn't match the `from ` policy rule. CONNMARK marks incoming VPN connections and restores the mark on reply packets. +### Keepalive timeout watchdog +`-keepalive-timeout-secs N` enables a receive-side watchdog. The server sends keepalives every ~3s. The watchdog checks at `N/3` intervals whether any data (frames or keepalives) was received within the last N seconds. If not, it closes the connection, triggering the reconnect loop. Without this, a half-open TCP connection can go undetected for minutes (depends on kernel `tcp_retries2`). `Close()` is guarded by `sync.Once` so the watchdog, Bridge error path, and `defer tunnel.Close()` can all call it safely. + ## Performance - **RAM**: 4.6 MB RSS idle, flat under 97 Mbit/s load (vs SoftEther C client: ~23 MB across 4 processes) diff --git a/README.md b/README.md index 291dd35..b80f0b3 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,7 @@ softether-go [flags] | `-accept-dns` | `false` | Set `/etc/resolv.conf` from DHCP-provided DNS servers | | `-policy-route-table` | `0` | Policy routing table number (0 = disabled) | | `-connmark` | `false` | Use CONNMARK to route DNAT reply traffic back through VPN | +| `-keepalive-timeout-secs` | `0` | Close connection if no server data within N seconds (0 = disabled) | | `-reconnect-delay` | `5s` | Delay between reconnection attempts | ### Authentication @@ -112,6 +113,8 @@ softether-go -host vpn.example.com -user admin -pass secret -plain-password **`-connmark`** — requires `-policy-route-table`. Uses iptables CONNMARK to route DNAT reply traffic back through the VPN tunnel. Without this, traffic forwarded to local namespaces/VMs (via DNAT) gets replies routed via the default gateway instead of the tunnel, breaking the connection. Adds `CONNMARK --set-mark` on incoming VPN packets and `CONNMARK --restore-mark` on reply packets from other interfaces. +**`-keepalive-timeout-secs N`** — enables a receive-side keepalive watchdog. The server sends keepalives every ~3 seconds. If no data (frames or keepalives) is received within N seconds, the connection is closed and the reconnect loop kicks in. Detects half-open TCP connections that would otherwise stall for minutes. Recommended value: `15`. + ### Examples Minimal: @@ -238,7 +241,7 @@ SoftEther uses **SHA-0** (not SHA-1) — no left-rotate in message schedule. `Ha ### Keepalive -Sent every 3 seconds: `uint32(0xFFFFFFFF) + uint32(randSize) + randData`. Silently consumed, never forwarded to TAP. +Sent every 3 seconds: `uint32(0xFFFFFFFF) + uint32(randSize) + randData`. Incoming keepalives update a receive timestamp. With `-keepalive-timeout-secs N`, a watchdog checks this timestamp at `N/3` intervals and closes the connection if no data arrived within N seconds, triggering reconnection. ## Project structure diff --git a/cmd/softether-go/main.go b/cmd/softether-go/main.go index 82e667c..1122a06 100644 --- a/cmd/softether-go/main.go +++ b/cmd/softether-go/main.go @@ -37,6 +37,7 @@ func main() { acceptDNS := flag.Bool("accept-dns", false, "Set /etc/resolv.conf from DHCP-provided DNS servers") policyRouteTable := flag.Int("policy-route-table", 0, "Policy routing table: route replies from VPN IP back through VPN gateway") connMark := flag.Bool("connmark", false, "Use CONNMARK to route DNAT reply traffic back through VPN (for port forwards to namespaces/VMs)") + keepaliveTimeout := flag.Int("keepalive-timeout-secs", 0, "Close connection if no data from server within N seconds (0 = disabled)") flag.Parse() @@ -99,7 +100,7 @@ func main() { } for { - err := runSession(cfg, dev, mac, netOpts, sig) + err := runSession(cfg, dev, mac, netOpts, time.Duration(*keepaliveTimeout)*time.Second, sig) if err == errShutdown { log.Println("shutting down") return diff --git a/cmd/softether-go/session.go b/cmd/softether-go/session.go index bb7a285..ee353db 100644 --- a/cmd/softether-go/session.go +++ b/cmd/softether-go/session.go @@ -15,7 +15,7 @@ import ( var errShutdown = fmt.Errorf("shutdown requested") -func runSession(cfg client.Config, dev *tap.Device, mac net.HardwareAddr, opts netcfg.Options, sig chan os.Signal) error { +func runSession(cfg client.Config, dev *tap.Device, mac net.HardwareAddr, opts netcfg.Options, keepaliveTimeout time.Duration, sig chan os.Signal) error { log.Printf("connecting to %s:%d hub=%s user=%s", cfg.Host, cfg.Port, cfg.Hub, cfg.Username) sess, err := client.Connect(cfg) @@ -24,7 +24,7 @@ func runSession(cfg client.Config, dev *tap.Device, mac net.HardwareAddr, opts n } log.Printf("connected: session=%s connection=%s", sess.SessionName, sess.ConnectionName) - tunnel := client.NewTunnel(sess) + tunnel := client.NewTunnel(sess, keepaliveTimeout) tunnel.StartKeepalive() defer tunnel.Close() diff --git a/pkg/client/tunnel.go b/pkg/client/tunnel.go index 9d9d2a2..9abe334 100644 --- a/pkg/client/tunnel.go +++ b/pkg/client/tunnel.go @@ -4,6 +4,7 @@ import ( "encoding/binary" "fmt" "io" + "log" "math/rand" "sync" "sync/atomic" @@ -29,21 +30,26 @@ const ( // Tunnel handles bidirectional TCP block framing for Ethernet frames over a // SoftEther VPN session. Each "block" is one Ethernet frame. type Tunnel struct { - sess *Session - writeCh chan []byte // serialized messages queued for the single writer - writeErr atomic.Value // stores error from writeLoop - stopCh chan struct{} - stopped sync.Once + sess *Session + writeCh chan []byte // serialized messages queued for the single writer + writeErr atomic.Value // stores error from writeLoop + stopCh chan struct{} + stopped sync.Once + keepaliveTimeout time.Duration // 0 = disabled + lastRecv atomic.Int64 // unix nano of last data received from server } // NewTunnel creates a tunnel from an established session. -// Call StartKeepalive() before reading/writing frames. -func NewTunnel(sess *Session) *Tunnel { +// keepaliveTimeout controls how long to wait for server data before closing the +// connection (0 = disabled). Call StartKeepalive() before reading/writing frames. +func NewTunnel(sess *Session, keepaliveTimeout time.Duration) *Tunnel { t := &Tunnel{ - sess: sess, - writeCh: make(chan []byte, writeChanSize), - stopCh: make(chan struct{}), + sess: sess, + writeCh: make(chan []byte, writeChanSize), + stopCh: make(chan struct{}), + keepaliveTimeout: keepaliveTimeout, } + t.lastRecv.Store(time.Now().UnixNano()) go t.writeLoop() return t } @@ -65,10 +71,14 @@ func (t *Tunnel) writeLoop() { } // Close stops the keepalive goroutine and closes the underlying connection. -// The writeCh is not closed here — writeLoop exits when the connection write fails. +// Safe for concurrent/repeated calls — only the first call actually closes. func (t *Tunnel) Close() error { - t.stopped.Do(func() { close(t.stopCh) }) - return t.sess.Conn.Close() + var err error + t.stopped.Do(func() { + close(t.stopCh) + err = t.sess.Conn.Close() + }) + return err } // ReadFrames reads a batch of Ethernet frames from the server. @@ -78,6 +88,7 @@ func (t *Tunnel) ReadFrames() ([][]byte, error) { if err := binary.Read(t.sess.Conn, binary.BigEndian, &numBlocks); err != nil { return nil, fmt.Errorf("read num blocks: %w", err) } + t.lastRecv.Store(time.Now().UnixNano()) // Keepalive: server sends 0xFFFFFFFF + uint32(size) + random data if numBlocks == keepAliveMagic { @@ -225,4 +236,25 @@ func (t *Tunnel) StartKeepalive() { } } }() + + // Watchdog: close connection if no data received within timeout + if t.keepaliveTimeout > 0 { + go func() { + ticker := time.NewTicker(t.keepaliveTimeout / 3) + defer ticker.Stop() + for { + select { + case <-t.stopCh: + return + case <-ticker.C: + last := time.Unix(0, t.lastRecv.Load()) + if time.Since(last) > t.keepaliveTimeout { + log.Printf("keepalive timeout: no data from server for %v, closing connection", t.keepaliveTimeout) + t.Close() + return + } + } + } + }() + } } From 20f41353e71ac5bfa6fda332a6da80c7f748e42d Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 11 Jul 2026 11:54:12 -0300 Subject: [PATCH 24/26] tunnel: add -keepalive-timeout-secs for dead connection detection Tracks last server receive time (atomic) and runs a watchdog goroutine that closes the connection if no data arrives within the timeout, triggering reconnection. Also fixes Close() to guard Conn.Close() inside sync.Once so concurrent/repeated calls are safe. Co-Authored-By: Claude Opus 4.6 (1M context) --- CLAUDE.md | 5 +++- README.md | 5 +++- cmd/softether-go/main.go | 3 +- cmd/softether-go/session.go | 4 +-- pkg/client/tunnel.go | 58 ++++++++++++++++++++++++++++--------- 5 files changed, 57 insertions(+), 18 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 6f2b60e..d1f7a05 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,7 +57,7 @@ pkg/tap/ ## CLI flags Required: `-host`, `-user` -Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-no-dhcp`, `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-connmark`, `-reconnect-delay` (5s) +Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-no-dhcp`, `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-connmark`, `-reconnect-delay` (5s), `-keepalive-timeout-secs` (0=disabled) ## SoftEther protocol pitfalls @@ -99,6 +99,9 @@ Before connecting, resolves server hostname and adds `/32` route via current def ### CONNMARK for DNAT reply routing `-connmark` (requires `-policy-route-table`) adds iptables CONNMARK rules so DNAT'd connections (port forwards to namespaces/VMs) have replies routed back through the tunnel. Without this, replies from DNAT targets use the default route because their source IP doesn't match the `from ` policy rule. CONNMARK marks incoming VPN connections and restores the mark on reply packets. +### Keepalive timeout watchdog +`-keepalive-timeout-secs N` enables a receive-side watchdog. The server sends keepalives every ~3s. The watchdog checks at `N/3` intervals whether any data (frames or keepalives) was received within the last N seconds. If not, it closes the connection, triggering the reconnect loop. Without this, a half-open TCP connection can go undetected for minutes (depends on kernel `tcp_retries2`). `Close()` is guarded by `sync.Once` so the watchdog, Bridge error path, and `defer tunnel.Close()` can all call it safely. + ## Performance - **RAM**: 4.6 MB RSS idle, flat under 97 Mbit/s load (vs SoftEther C client: ~23 MB across 4 processes) diff --git a/README.md b/README.md index 291dd35..b80f0b3 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,7 @@ softether-go [flags] | `-accept-dns` | `false` | Set `/etc/resolv.conf` from DHCP-provided DNS servers | | `-policy-route-table` | `0` | Policy routing table number (0 = disabled) | | `-connmark` | `false` | Use CONNMARK to route DNAT reply traffic back through VPN | +| `-keepalive-timeout-secs` | `0` | Close connection if no server data within N seconds (0 = disabled) | | `-reconnect-delay` | `5s` | Delay between reconnection attempts | ### Authentication @@ -112,6 +113,8 @@ softether-go -host vpn.example.com -user admin -pass secret -plain-password **`-connmark`** — requires `-policy-route-table`. Uses iptables CONNMARK to route DNAT reply traffic back through the VPN tunnel. Without this, traffic forwarded to local namespaces/VMs (via DNAT) gets replies routed via the default gateway instead of the tunnel, breaking the connection. Adds `CONNMARK --set-mark` on incoming VPN packets and `CONNMARK --restore-mark` on reply packets from other interfaces. +**`-keepalive-timeout-secs N`** — enables a receive-side keepalive watchdog. The server sends keepalives every ~3 seconds. If no data (frames or keepalives) is received within N seconds, the connection is closed and the reconnect loop kicks in. Detects half-open TCP connections that would otherwise stall for minutes. Recommended value: `15`. + ### Examples Minimal: @@ -238,7 +241,7 @@ SoftEther uses **SHA-0** (not SHA-1) — no left-rotate in message schedule. `Ha ### Keepalive -Sent every 3 seconds: `uint32(0xFFFFFFFF) + uint32(randSize) + randData`. Silently consumed, never forwarded to TAP. +Sent every 3 seconds: `uint32(0xFFFFFFFF) + uint32(randSize) + randData`. Incoming keepalives update a receive timestamp. With `-keepalive-timeout-secs N`, a watchdog checks this timestamp at `N/3` intervals and closes the connection if no data arrived within N seconds, triggering reconnection. ## Project structure diff --git a/cmd/softether-go/main.go b/cmd/softether-go/main.go index 82e667c..1122a06 100644 --- a/cmd/softether-go/main.go +++ b/cmd/softether-go/main.go @@ -37,6 +37,7 @@ func main() { acceptDNS := flag.Bool("accept-dns", false, "Set /etc/resolv.conf from DHCP-provided DNS servers") policyRouteTable := flag.Int("policy-route-table", 0, "Policy routing table: route replies from VPN IP back through VPN gateway") connMark := flag.Bool("connmark", false, "Use CONNMARK to route DNAT reply traffic back through VPN (for port forwards to namespaces/VMs)") + keepaliveTimeout := flag.Int("keepalive-timeout-secs", 0, "Close connection if no data from server within N seconds (0 = disabled)") flag.Parse() @@ -99,7 +100,7 @@ func main() { } for { - err := runSession(cfg, dev, mac, netOpts, sig) + err := runSession(cfg, dev, mac, netOpts, time.Duration(*keepaliveTimeout)*time.Second, sig) if err == errShutdown { log.Println("shutting down") return diff --git a/cmd/softether-go/session.go b/cmd/softether-go/session.go index bb7a285..ee353db 100644 --- a/cmd/softether-go/session.go +++ b/cmd/softether-go/session.go @@ -15,7 +15,7 @@ import ( var errShutdown = fmt.Errorf("shutdown requested") -func runSession(cfg client.Config, dev *tap.Device, mac net.HardwareAddr, opts netcfg.Options, sig chan os.Signal) error { +func runSession(cfg client.Config, dev *tap.Device, mac net.HardwareAddr, opts netcfg.Options, keepaliveTimeout time.Duration, sig chan os.Signal) error { log.Printf("connecting to %s:%d hub=%s user=%s", cfg.Host, cfg.Port, cfg.Hub, cfg.Username) sess, err := client.Connect(cfg) @@ -24,7 +24,7 @@ func runSession(cfg client.Config, dev *tap.Device, mac net.HardwareAddr, opts n } log.Printf("connected: session=%s connection=%s", sess.SessionName, sess.ConnectionName) - tunnel := client.NewTunnel(sess) + tunnel := client.NewTunnel(sess, keepaliveTimeout) tunnel.StartKeepalive() defer tunnel.Close() diff --git a/pkg/client/tunnel.go b/pkg/client/tunnel.go index 9d9d2a2..9abe334 100644 --- a/pkg/client/tunnel.go +++ b/pkg/client/tunnel.go @@ -4,6 +4,7 @@ import ( "encoding/binary" "fmt" "io" + "log" "math/rand" "sync" "sync/atomic" @@ -29,21 +30,26 @@ const ( // Tunnel handles bidirectional TCP block framing for Ethernet frames over a // SoftEther VPN session. Each "block" is one Ethernet frame. type Tunnel struct { - sess *Session - writeCh chan []byte // serialized messages queued for the single writer - writeErr atomic.Value // stores error from writeLoop - stopCh chan struct{} - stopped sync.Once + sess *Session + writeCh chan []byte // serialized messages queued for the single writer + writeErr atomic.Value // stores error from writeLoop + stopCh chan struct{} + stopped sync.Once + keepaliveTimeout time.Duration // 0 = disabled + lastRecv atomic.Int64 // unix nano of last data received from server } // NewTunnel creates a tunnel from an established session. -// Call StartKeepalive() before reading/writing frames. -func NewTunnel(sess *Session) *Tunnel { +// keepaliveTimeout controls how long to wait for server data before closing the +// connection (0 = disabled). Call StartKeepalive() before reading/writing frames. +func NewTunnel(sess *Session, keepaliveTimeout time.Duration) *Tunnel { t := &Tunnel{ - sess: sess, - writeCh: make(chan []byte, writeChanSize), - stopCh: make(chan struct{}), + sess: sess, + writeCh: make(chan []byte, writeChanSize), + stopCh: make(chan struct{}), + keepaliveTimeout: keepaliveTimeout, } + t.lastRecv.Store(time.Now().UnixNano()) go t.writeLoop() return t } @@ -65,10 +71,14 @@ func (t *Tunnel) writeLoop() { } // Close stops the keepalive goroutine and closes the underlying connection. -// The writeCh is not closed here — writeLoop exits when the connection write fails. +// Safe for concurrent/repeated calls — only the first call actually closes. func (t *Tunnel) Close() error { - t.stopped.Do(func() { close(t.stopCh) }) - return t.sess.Conn.Close() + var err error + t.stopped.Do(func() { + close(t.stopCh) + err = t.sess.Conn.Close() + }) + return err } // ReadFrames reads a batch of Ethernet frames from the server. @@ -78,6 +88,7 @@ func (t *Tunnel) ReadFrames() ([][]byte, error) { if err := binary.Read(t.sess.Conn, binary.BigEndian, &numBlocks); err != nil { return nil, fmt.Errorf("read num blocks: %w", err) } + t.lastRecv.Store(time.Now().UnixNano()) // Keepalive: server sends 0xFFFFFFFF + uint32(size) + random data if numBlocks == keepAliveMagic { @@ -225,4 +236,25 @@ func (t *Tunnel) StartKeepalive() { } } }() + + // Watchdog: close connection if no data received within timeout + if t.keepaliveTimeout > 0 { + go func() { + ticker := time.NewTicker(t.keepaliveTimeout / 3) + defer ticker.Stop() + for { + select { + case <-t.stopCh: + return + case <-ticker.C: + last := time.Unix(0, t.lastRecv.Load()) + if time.Since(last) > t.keepaliveTimeout { + log.Printf("keepalive timeout: no data from server for %v, closing connection", t.keepaliveTimeout) + t.Close() + return + } + } + } + }() + } } From 9e050b140b9fba25d26491e6e4a8d9f6e01ab202 Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 11 Jul 2026 11:56:37 -0300 Subject: [PATCH 25/26] cli: rename -reconnect-delay to -reconnect-delay-secs All time arguments now use -secs suffix with integer seconds for consistency (-reconnect-delay-secs, -keepalive-timeout-secs). Co-Authored-By: Claude Opus 4.6 (1M context) --- CLAUDE.md | 2 +- README.md | 2 +- cmd/softether-go/main.go | 7 ++++--- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index d9ce20b..02c0d5d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,7 +57,7 @@ pkg/tap/ ## CLI flags Required: `-host`, `-user` -Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-no-dhcp`, `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-connmark`, `-reconnect-delay` (5s), `-keepalive-timeout-secs` (0=disabled) +Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-no-dhcp`, `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-connmark`, `-reconnect-delay-secs` (5), `-keepalive-timeout-secs` (0=disabled) ## SoftEther protocol pitfalls diff --git a/README.md b/README.md index b80f0b3..b60d55b 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ softether-go [flags] | `-policy-route-table` | `0` | Policy routing table number (0 = disabled) | | `-connmark` | `false` | Use CONNMARK to route DNAT reply traffic back through VPN | | `-keepalive-timeout-secs` | `0` | Close connection if no server data within N seconds (0 = disabled) | -| `-reconnect-delay` | `5s` | Delay between reconnection attempts | +| `-reconnect-delay-secs` | `5` | Delay between reconnection attempts in seconds | ### Authentication diff --git a/cmd/softether-go/main.go b/cmd/softether-go/main.go index 1122a06..c4c25ce 100644 --- a/cmd/softether-go/main.go +++ b/cmd/softether-go/main.go @@ -31,7 +31,7 @@ func main() { macAddr := flag.String("mac", "", "TAP interface MAC address (e.g. 5E:3B:6F:63:A8:3E)") insecure := flag.Bool("insecure", false, "Skip TLS certificate verification") noDHCP := flag.Bool("no-dhcp", false, "Disable built-in DHCP client") - reconnectDelay := flag.Duration("reconnect-delay", 5*time.Second, "Delay between reconnection attempts") + reconnectDelay := flag.Int("reconnect-delay-secs", 5, "Delay between reconnection attempts in seconds") acceptDefaultGW := flag.Bool("accept-default-gateway", false, "Install DHCP-provided gateway as default route") acceptStaticRoutes := flag.Bool("accept-static-routes", false, "Install DHCP classless static routes (option 121/249)") acceptDNS := flag.Bool("accept-dns", false, "Set /etc/resolv.conf from DHCP-provided DNS servers") @@ -106,13 +106,14 @@ func main() { return } log.Printf("session ended: %v", err) - log.Printf("reconnecting in %v...", *reconnectDelay) + delay := time.Duration(*reconnectDelay) * time.Second + log.Printf("reconnecting in %v...", delay) select { case <-sig: log.Println("shutting down") return - case <-time.After(*reconnectDelay): + case <-time.After(delay): } } } From 4c2b4dcec1468ef3ff127aceb74bef20a75d73eb Mon Sep 17 00:00:00 2001 From: Git Sagar Date: Sat, 11 Jul 2026 11:56:37 -0300 Subject: [PATCH 26/26] cli: rename -reconnect-delay to -reconnect-delay-secs All time arguments now use -secs suffix with integer seconds for consistency (-reconnect-delay-secs, -keepalive-timeout-secs). Co-Authored-By: Claude Opus 4.6 (1M context) --- CLAUDE.md | 2 +- README.md | 2 +- cmd/softether-go/main.go | 7 ++++--- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index d1f7a05..085ee9d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,7 +57,7 @@ pkg/tap/ ## CLI flags Required: `-host`, `-user` -Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-no-dhcp`, `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-connmark`, `-reconnect-delay` (5s), `-keepalive-timeout-secs` (0=disabled) +Optional: `-pass`, `-port` (443), `-hub` (DEFAULT), `-tap` (auto), `-mac`, `-plain-password`, `-insecure`, `-no-dhcp`, `-accept-default-gateway`, `-accept-static-routes`, `-accept-dns`, `-policy-route-table` (0=disabled), `-connmark`, `-reconnect-delay-secs` (5), `-keepalive-timeout-secs` (0=disabled) ## SoftEther protocol pitfalls diff --git a/README.md b/README.md index b80f0b3..b60d55b 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,7 @@ softether-go [flags] | `-policy-route-table` | `0` | Policy routing table number (0 = disabled) | | `-connmark` | `false` | Use CONNMARK to route DNAT reply traffic back through VPN | | `-keepalive-timeout-secs` | `0` | Close connection if no server data within N seconds (0 = disabled) | -| `-reconnect-delay` | `5s` | Delay between reconnection attempts | +| `-reconnect-delay-secs` | `5` | Delay between reconnection attempts in seconds | ### Authentication diff --git a/cmd/softether-go/main.go b/cmd/softether-go/main.go index 1122a06..c4c25ce 100644 --- a/cmd/softether-go/main.go +++ b/cmd/softether-go/main.go @@ -31,7 +31,7 @@ func main() { macAddr := flag.String("mac", "", "TAP interface MAC address (e.g. 5E:3B:6F:63:A8:3E)") insecure := flag.Bool("insecure", false, "Skip TLS certificate verification") noDHCP := flag.Bool("no-dhcp", false, "Disable built-in DHCP client") - reconnectDelay := flag.Duration("reconnect-delay", 5*time.Second, "Delay between reconnection attempts") + reconnectDelay := flag.Int("reconnect-delay-secs", 5, "Delay between reconnection attempts in seconds") acceptDefaultGW := flag.Bool("accept-default-gateway", false, "Install DHCP-provided gateway as default route") acceptStaticRoutes := flag.Bool("accept-static-routes", false, "Install DHCP classless static routes (option 121/249)") acceptDNS := flag.Bool("accept-dns", false, "Set /etc/resolv.conf from DHCP-provided DNS servers") @@ -106,13 +106,14 @@ func main() { return } log.Printf("session ended: %v", err) - log.Printf("reconnecting in %v...", *reconnectDelay) + delay := time.Duration(*reconnectDelay) * time.Second + log.Printf("reconnecting in %v...", delay) select { case <-sig: log.Println("shutting down") return - case <-time.After(*reconnectDelay): + case <-time.After(delay): } } }