Compare commits

...

13 commits

Author SHA1 Message Date
9e050b140b 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) <noreply@anthropic.com>
2026-07-11 11:56:37 -03:00
1a397c363f 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) <noreply@anthropic.com>
2026-07-11 11:54:12 -03:00
1d919aafc5 tunnel: fix panic on send to closed writeCh during disconnect
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) <noreply@anthropic.com>
2026-06-07 21:15:34 +05:30
51824b830e 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 <VPN_IP>" 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) <noreply@anthropic.com>
2026-06-07 01:06:17 +05:30
857733863c 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) <noreply@anthropic.com>
2026-06-07 00:42:56 +05:30
47e06b525c 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) <noreply@anthropic.com>
2026-06-06 23:16:27 +05:30
14ec4a02dd 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) <noreply@anthropic.com>
2026-06-06 23:07:55 +05:30
fc07ac507d 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) <noreply@anthropic.com>
2026-06-06 22:58:00 +05:30
b3f4c5f42b 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) <noreply@anthropic.com>
2026-06-06 22:53:06 +05:30
6416159164 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) <noreply@anthropic.com>
2026-06-06 22:05:34 +05:30
61237283f5 consolidate docs into README.md, remove docs/
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-06-06 17:54:38 +05:30
42f8333783 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) <noreply@anthropic.com>
2026-06-06 17:53:01 +05:30
8a3ea06c9e add CLAUDE.md with project context and protocol notes
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-06-06 17:45:19 +05:30
12 changed files with 662 additions and 494 deletions

143
CLAUDE.md Normal file
View file

@ -0,0 +1,143 @@
# 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`, `-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
### 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 <VPN_IP> table N` + `ip route replace default via <VPN_GW> dev <TAP> 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 <VPN_IP>` 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)
- **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 -connmark
```
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), `iptables` (only for `-connmark`)
- `vendorHash = null` in flake.nix (deps are vendored)

275
README.md
View file

@ -2,29 +2,272 @@
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)
- 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
- ~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`
- `iptables` on `$PATH` (only if using `-connmark`)
## 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) |
| `-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-secs` | `5` | Delay between reconnection attempts in seconds |
### 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 <VPN_IP> table N` and `ip route replace default via <VPN_GW> dev <TAP> 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.
**`-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:
```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 \
-connmark
```
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 <VPN_IP> 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 <VPN_IP>` 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.
### Keepalive
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
```
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

View file

@ -30,12 +30,14 @@ 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")
reconnectDelay := flag.Duration("reconnect-delay", 5*time.Second, "Delay between reconnection attempts")
noDHCP := flag.Bool("no-dhcp", false, "Disable built-in DHCP client")
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")
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()
@ -89,27 +91,29 @@ func main() {
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
netOpts := netcfg.Options{
DHCP: *dhcpEnabled,
DHCP: !*noDHCP,
AcceptDefaultGW: *acceptDefaultGW,
AcceptStaticRoutes: *acceptStaticRoutes,
AcceptDNS: *acceptDNS,
PolicyRouteTable: *policyRouteTable,
ConnMark: *connMark,
}
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
}
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):
}
}
}

View file

@ -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()
@ -59,7 +59,14 @@ 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
if lease.LeaseTime > 0 {
stopRenew := make(chan struct{})
defer close(stopRenew)
go renewLoop(dhcpClient, tunnel, dev.Name, lease, opts, stopRenew)
}
}
@ -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, opts.ConnMark)
}
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...")

View file

@ -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 <VPN_GW> dev <TAP> table N
ip rule add from <VPN_IP> 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.

View file

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

View file

@ -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`

View file

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

View file

@ -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 |
| `-dhcp` | `true` | Run built-in DHCP client after connecting |
| `-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
```
### `-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.
### `-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 <VPN_IP> table 200
ip route replace default via <VPN_GW> dev <TAP> 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 -dhcp=false -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

View file

@ -4,8 +4,10 @@ import (
"encoding/binary"
"fmt"
"io"
"log"
"math/rand"
"sync"
"sync/atomic"
"time"
)
@ -22,29 +24,61 @@ 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
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 {
return &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{}),
keepaliveTimeout: keepaliveTimeout,
}
t.lastRecv.Store(time.Now().UnixNano())
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 {
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.
// 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.
@ -54,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 {
@ -83,19 +118,34 @@ func (t *Tunnel) ReadFrames() ([][]byte, error) {
}
// WriteFrames sends a batch of Ethernet frames to the server.
// Safe for concurrent use — messages are queued for the single writer goroutine.
func (t *Tunnel) WriteFrames(frames [][]byte) error {
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)
}
select {
case t.writeCh <- buf:
if err, ok := t.writeErr.Load().(error); ok {
return err
}
return nil
case <-t.stopCh:
return fmt.Errorf("tunnel closed")
}
}
// FrameHandler is called for each Ethernet frame received from the server.
@ -170,17 +220,41 @@ 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 {
// 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])
select {
case t.writeCh <- buf:
case <-t.stopCh:
return
}
}
}
}()
// 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
}
}
}
}()
}
}

View file

@ -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 {
@ -150,6 +151,50 @@ 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) {
c.xid = rand.Uint32()
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 {

View file

@ -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.
@ -80,15 +81,31 @@ 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.
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()
run("ip", "rule", "del", "table", t)
// 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 {
log.Printf("warning: policy rule: %v", err)
@ -96,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 <VPN_IP>" 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() {
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)
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)
}
}
@ -222,3 +264,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()
}