refactor: extract session/netcfg/tunnel, add mac/dhcp/policy-route flags

- Split cmd/softether-go into main.go (flags, reconnect loop) and
  session.go (session lifecycle, DHCP orchestration)
- Extract network config to pkg/netcfg (TAP config, routing, DNS, policy routes)
- Move frame bridging to pkg/client/tunnel.go as Bridge() method
- Add -mac, -dhcp, -policy-route-table CLI flags
- Add SetMAC() to pkg/tap for deterministic DHCP assignments
- Update all docs to reflect new structure and flags

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Git Sagar 2026-06-06 16:43:12 +05:30
parent 846ed96ff4
commit 17c1063e1f
10 changed files with 495 additions and 332 deletions

View file

@ -45,6 +45,18 @@ Key details:
- 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.
@ -62,7 +74,7 @@ DHCP Client VPN Tunnel DHCP Server (on VPN)
│ │ │
```
The DHCP client starts reading tunnel frames **before** sending DISCOVER, so responses are not missed. Non-DHCP frames received during the exchange are dropped (the TAP bridge is not yet active).
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?
@ -81,19 +93,6 @@ The VPN tunnel transports Ethernet frames, and the DHCP exchange must happen *in
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.
## Reconnection
On disconnect (TCP error, server timeout, etc.), the client:
1. Flushes IP addresses from the TAP interface
2. Restores `/etc/resolv.conf` if DNS was modified
3. Waits `-reconnect-delay` (default 5s)
4. Establishes a new TLS connection and repeats the full handshake
5. Runs a fresh DHCP exchange through the new tunnel
6. Reconfigures the TAP interface with the new lease
The TAP device itself persists across reconnections — only its IP configuration is reset. The host route to the VPN server also persists.
## Routing
### Server host route
@ -120,6 +119,19 @@ The metric ensures it takes precedence over any existing default route with a hi
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.

View file

@ -9,7 +9,9 @@ Standalone SoftEther VPN client written in Go. Connects to SoftEther VPN servers
- 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

View file

@ -3,17 +3,20 @@
```
softether-go/
├── cmd/softether-go/
│ └── main.go CLI entry point
│ ├── 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 and keepalive
│ │ ├── tunnel.go TCP block framing, keepalive, frame bridging
│ │ └── crypto.go SHA-0 and password hashing
│ ├── protocol/
│ │ ├── http.go HTTP transport layer
│ │ ├── 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
@ -27,18 +30,17 @@ softether-go/
### `cmd/softether-go`
CLI entry point. Handles flag parsing, signal handling, and the reconnection loop. On each session:
- Connects to the server
- Runs DHCP through the tunnel
- Configures the TAP interface (IP, routes, DNS)
- Bridges Ethernet frames between the TAP device and the VPN tunnel
- Cleans up on disconnect and retries
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. `ReadFrames()` reads batches of Ethernet frames from the server. `WriteFrames()` sends batches. `StartKeepalive()` sends periodic keepalive packets (every 3s) to prevent server timeout.
**`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)`.
@ -52,6 +54,10 @@ CLI entry point. Handles flag parsing, signal handling, and the reconnection loo
**`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()` to get the hardware address and `SetUp()` to bring the interface up.
**`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

@ -19,11 +19,14 @@ softether-go [flags]
| `-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
@ -46,6 +49,18 @@ softether-go -host vpn.example.com -user admin -pass secret -plain-password
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.
@ -62,6 +77,19 @@ If a static route entry has destination `0.0.0.0/0` (default route), it is only
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:
@ -69,7 +97,7 @@ Minimal connection:
softether-go -host vpn.example.com -user admin -pass secret
```
Full setup with routing and DNS:
Full setup with routing, DNS, and policy routing:
```bash
softether-go \
-host vpn.example.com \
@ -79,20 +107,17 @@ softether-go \
-pass secret \
-plain-password \
-tap vpn0 \
-mac 5E:3B:6F:63:A8:3E \
-insecure \
-accept-default-gateway \
-accept-static-routes \
-accept-dns
-accept-dns \
-policy-route-table 200
```
Named TAP interface with custom reconnect delay:
No DHCP (manual configuration):
```bash
softether-go \
-host vpn.example.com \
-user admin \
-pass secret \
-tap myvpn \
-reconnect-delay 10s
softether-go -host vpn.example.com -user admin -pass secret -dhcp=false -tap vpn0
```
## Docker
@ -114,5 +139,5 @@ The container needs `iproute2` installed (`apk add iproute2` on Alpine) for the
## Signals
- **SIGINT / SIGTERM** — clean shutdown: closes tunnel, flushes TAP addresses, restores DNS, removes server host route
- **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