diff --git a/README.md b/README.md index cd6f0718..73ed1479 100644 --- a/README.md +++ b/README.md @@ -45,22 +45,25 @@ of wireproxy by [@artem-russkikh](https://github.com/artem-russkikh). ```bash usage: wireproxy [-h|--help] [-c|--config ""] [-s|--silent] - [-d|--daemon] [-i|--info ""] [-v|--version] - [-n|--configtest] + [-d|--daemon] [-i|--info ""] [-H|--healthcheck + ""] [-v|--version] [-n|--configtest] Userspace wireguard client for proxying Arguments: - -h --help Print help information - -c --config Path of configuration file - Default paths: /etc/wireproxy/wireproxy.conf, $HOME/.config/wireproxy.conf - -s --silent Silent mode - -d --daemon Make wireproxy run in background - -i --info Specify the address and port for exposing health status - -v --version Print version - -n --configtest Configtest mode. Only check the configuration file for - validity. + -h --help Print help information + -c --config Path of configuration file + Default paths: /etc/wireproxy/wireproxy.conf, $HOME/.config/wireproxy.conf + -s --silent Silent mode + -d --daemon Make wireproxy run in background + -i --info Specify the address and port for exposing health status + -H --healthcheck Request /readyz from the health endpoint at the given + address and port (see --info), exit 0 if healthy and 1 + otherwise + -v --version Print version + -n --configtest Configtest mode. Only check the configuration file for + validity. ``` # Build instruction @@ -91,6 +94,7 @@ Instructions for using wireproxy with Firefox container tabs and auto-start on M [Interface] Address = 10.200.200.2/32 # The subnet should be /32 and /128 for IPv4 and v6 respectively # MTU = 1420 (optional) +# MaxHandshakeAge = 180 (optional, see "Health endpoint" below) PrivateKey = uCTIK+56CPyCvwJxmU5dBfuyJvPuSXAq1FzHdnIxe1Q= # PrivateKey = $MY_WIREGUARD_PRIVATE_KEY # Alternatively, reference environment variables DNS = 10.200.200.1 @@ -320,3 +324,48 @@ CheckAlive = 1.1.1.1 If nothing is set for `CheckAlive`, an empty JSON object with 200 will be the response. The peer which the ICMP ping packet is routed to depends on the `AllowedIPs` set for each peers. + +## MaxHandshakeAge + +`MaxHandshakeAge` (`[Interface]`, in seconds, disabled by default) makes `/readyz` also +respond with a 503 if the last handshake of any peer is older than that many seconds, or +if a peer has never completed a handshake. This works without `CheckAlive`. The last +handshake time (unix seconds, `0` if none) of each peer is added to the response under +`handshake:`. Peers with no `Endpoint` in the config only answer handshakes, +so they are not checked: they are listed with a `handshake_skipped:` entry of +`1` and never make `/readyz` fail, even if they connected once and have a learned endpoint: + +```ini +[Interface] +PrivateKey = censored +Address = 10.2.0.2/32 +MaxHandshakeAge = 180 +``` + +```text +< HTTP/1.1 503 Service Unavailable +< +{"handshake:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX=":0} +``` + +Note that wireguard only handshakes while there is traffic, so set `PersistentKeepalive` +on peers that may be idle for longer than `MaxHandshakeAge`. + +## Health check in a container + +`--healthcheck/-H
` requests `/readyz` from the given address (the same value as +`--info`) and exits with 0 if the response is a 200, otherwise with 1. It does not read a +configuration file. As the container image has no shell, `curl` or `wget`, this is how to +use `/readyz` as a Docker health check: + +```dockerfile +CMD [ "--config", "/etc/wireproxy/config", "--info", "127.0.0.1:9080" ] +HEALTHCHECK CMD [ "/usr/bin/wireproxy", "--healthcheck", "127.0.0.1:9080" ] +``` + +or with Compose: + +```yaml +healthcheck: + test: ["CMD", "/usr/bin/wireproxy", "--healthcheck", "127.0.0.1:9080"] +``` diff --git a/cmd/wireproxy/main.go b/cmd/wireproxy/main.go index e993e880..849fd54b 100644 --- a/cmd/wireproxy/main.go +++ b/cmd/wireproxy/main.go @@ -11,6 +11,7 @@ import ( "os/signal" "strconv" "syscall" + "time" "github.com/landlock-lsm/go-landlock/landlock" @@ -213,6 +214,7 @@ func main() { silent := parser.Flag("s", "silent", &argparse.Options{Help: "Silent mode"}) daemon := parser.Flag("d", "daemon", &argparse.Options{Help: "Make wireproxy run in background"}) info := parser.String("i", "info", &argparse.Options{Help: "Specify the address and port for exposing health status"}) + healthcheck := parser.String("H", "healthcheck", &argparse.Options{Help: "Request /readyz from the health endpoint at the given address and port (see --info), exit 0 if healthy and 1 otherwise"}) printVerison := parser.Flag("v", "version", &argparse.Options{Help: "Print version"}) configTest := parser.Flag("n", "configtest", &argparse.Options{Help: "Configtest mode. Only check the configuration file for validity."}) @@ -227,6 +229,14 @@ func main() { return } + if *healthcheck != "" { + if err := wireproxy.Healthcheck(*healthcheck, 3*time.Second); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + return + } + if *config == "" { if path, config_exist := configFilePath(); config_exist { *config = path diff --git a/config.go b/config.go index 9bf53ff4..01bdf14d 100644 --- a/config.go +++ b/config.go @@ -33,6 +33,9 @@ type DeviceConfig struct { ListenPort *int CheckAlive []netip.Addr CheckAliveInterval int + // MaxHandshakeAge is the age, in seconds, of the last handshake of a peer + // after which /readyz reports unavailable. 0 disables the check. + MaxHandshakeAge int } type UDPProxyTunnelConfig struct { @@ -326,6 +329,18 @@ func ParseInterface(cfg *ini.File, device *DeviceConfig) error { device.CheckAliveInterval = value } + if sectionKey, err := section.GetKey("MaxHandshakeAge"); err == nil { + value, err := sectionKey.Int() + if err != nil { + return err + } + if value < 0 { + return errors.New("MaxHandshakeAge should not be negative") + } + + device.MaxHandshakeAge = value + } + return nil } diff --git a/health.go b/health.go new file mode 100644 index 00000000..1c5df486 --- /dev/null +++ b/health.go @@ -0,0 +1,92 @@ +package wireproxy + +import ( + "encoding/base64" + "encoding/hex" + "fmt" + "io" + "net/http" + "strconv" + "strings" + "time" +) + +// handshakeRecords reports the last handshake time of every peer found in an +// IpcGet response as unix seconds (0 if there has never been one), keyed by +// "handshake:". stale is true if any checked peer has no +// handshake or one older than maxAge. +// +// Peers with no Endpoint in the configuration only answer handshakes and have +// never connected out, so none can be expected of them: they are left out of the +// verdict and flagged in records with a "handshake_skipped:" +// entry of 1. The configuration is consulted rather than the IPC "endpoint" line, +// which wireguard also reports for endpoints learned from incoming packets. +func handshakeRecords(ipc string, peers []PeerConfig, maxAge time.Duration, now time.Time) (records map[string]uint64, stale bool) { + configured := make(map[string]bool) + for _, peer := range peers { + if peer.Endpoint != nil { + configured[base64Key(peer.PublicKey)] = true + } + } + + records = make(map[string]uint64) + skipped := make(map[string]bool) + var key64 string + for _, line := range strings.Split(ipc, "\n") { + key, value, ok := strings.Cut(line, "=") + if !ok { + continue + } + switch key { + case "public_key": + key64 = base64Key(value) + records["handshake:"+key64] = 0 + if !configured[key64] { + skipped[key64] = true + } + case "last_handshake_time_sec": + if sec, err := strconv.ParseUint(value, 10, 63); err == nil && key64 != "" { + records["handshake:"+key64] = sec + } + } + } + + for peer, record := range records { + if skipped[strings.TrimPrefix(peer, "handshake:")] { + continue + } + if record == 0 || now.Sub(time.Unix(int64(record), 0)) > maxAge { + stale = true + } + } + for peer := range skipped { + records["handshake_skipped:"+peer] = 1 + } + return records, stale +} + +// base64Key converts a wireguard key given as hex (as in IpcGet and the parsed +// configuration) to base64; a key that is not hex is returned unchanged. +func base64Key(key string) string { + if raw, err := hex.DecodeString(key); err == nil { + return base64.StdEncoding.EncodeToString(raw) + } + return key +} + +// Healthcheck requests /readyz from the health endpoint listening on addr +// (the value of --info) and returns an error unless it responds with 200. +func Healthcheck(addr string, timeout time.Duration) error { + client := http.Client{Timeout: timeout} + resp, err := client.Get("http://" + addr + "/readyz") + if err != nil { + return err + } + defer func() { _ = resp.Body.Close() }() + + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1024)) + return fmt.Errorf("unhealthy: %s: %s", resp.Status, strings.TrimSpace(string(body))) + } + return nil +} diff --git a/health_test.go b/health_test.go new file mode 100644 index 00000000..66d6d27f --- /dev/null +++ b/health_test.go @@ -0,0 +1,317 @@ +package wireproxy + +import ( + "crypto/ecdh" + "encoding/hex" + "encoding/json" + "fmt" + "maps" + "net/http" + "net/http/httptest" + "net/netip" + "strconv" + "strings" + "sync" + "testing" + "time" + + "golang.zx2c4.com/wireguard/conn" + "golang.zx2c4.com/wireguard/device" + "golang.zx2c4.com/wireguard/tun/netstack" +) + +const ( + // base64 of the 32 bytes 00..00 01 and 00..00 02 + handshakeKeyA = "handshake:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE=" + handshakeKeyB = "handshake:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAI=" + handshakeHexA = "0000000000000000000000000000000000000000000000000000000000000001" + handshakeHexB = "0000000000000000000000000000000000000000000000000000000000000002" +) + +func TestHandshakeRecords(t *testing.T) { + now := time.Unix(1_700_000_000, 0) + maxAge := 2 * time.Minute + ipc := func(a, b int64) string { + return fmt.Sprintf("private_key=aa\npublic_key=%s\nendpoint=192.0.2.1:51820\nlast_handshake_time_sec=%d\nlast_handshake_time_nsec=0\n"+ + "public_key=%s\nendpoint=192.0.2.2:51820\nlast_handshake_time_sec=%d\nlast_handshake_time_nsec=0\n", handshakeHexA, a, handshakeHexB, b) + } + + endpoint := "192.0.2.1:51820" + peers := []PeerConfig{{PublicKey: handshakeHexA, Endpoint: &endpoint}, {PublicKey: handshakeHexB, Endpoint: &endpoint}} + + tests := []struct { + name string + ipc string + wantStale bool + wantA uint64 + wantB uint64 + }{ + {"all fresh", ipc(now.Unix()-10, now.Unix()-100), false, uint64(now.Unix() - 10), uint64(now.Unix() - 100)}, + {"one stale", ipc(now.Unix()-10, now.Unix()-300), true, uint64(now.Unix() - 10), uint64(now.Unix() - 300)}, + {"one never", ipc(now.Unix()-10, 0), true, uint64(now.Unix() - 10), 0}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + records, stale := handshakeRecords(tt.ipc, peers, maxAge, now) + if stale != tt.wantStale { + t.Fatalf("stale = %v, want %v", stale, tt.wantStale) + } + if len(records) != 2 || records[handshakeKeyA] != tt.wantA || records[handshakeKeyB] != tt.wantB { + t.Fatalf("unexpected records: %v", records) + } + }) + } + + if records, stale := handshakeRecords("private_key=aa\n", peers, maxAge, now); stale || len(records) != 0 { + t.Fatalf("no peers should not be stale, got %v %v", stale, records) + } + + t.Run("peer without a configured endpoint is skipped", func(t *testing.T) { + // B has no Endpoint in the config and never handshook, but wireguard + // reports an endpoint for it (as it does for one learned from a packet). + // Only A counts, and B stays in the records, flagged as skipped. + records, stale := handshakeRecords(ipc(now.Unix()-10, 0), peers[:1], maxAge, now) + if stale { + t.Fatal("a peer without a configured endpoint must not make the check stale") + } + want := map[string]uint64{handshakeKeyA: uint64(now.Unix() - 10), handshakeKeyB: 0, "handshake_skipped:" + strings.TrimPrefix(handshakeKeyB, "handshake:"): 1} + if !maps.Equal(records, want) { + t.Fatalf("records = %v, want %v", records, want) + } + }) + + t.Run("config key may be base64", func(t *testing.T) { + b64 := &PeerConfig{PublicKey: strings.TrimPrefix(handshakeKeyA, "handshake:"), Endpoint: &endpoint} + _, stale := handshakeRecords(ipc(0, now.Unix()-10), []PeerConfig{*b64, peers[1]}, maxAge, now) + if !stale { + t.Fatal("a base64 config key must match the hex key in the IPC output") + } + }) +} + +func newReadyzTun(t *testing.T, maxHandshakeAge int) VirtualTun { + t.Helper() + return newReadyzTunPeer(t, maxHandshakeAge, true) +} + +// newReadyzTunPeer returns a tun with one peer. The IPC peer always has an endpoint; +// configuredEndpoint says whether the configuration has one too. +func newReadyzTunPeer(t *testing.T, maxHandshakeAge int, configuredEndpoint bool) VirtualTun { + t.Helper() + tun, _, err := netstack.CreateNetTUN([]netip.Addr{netip.MustParseAddr("10.0.0.2")}, nil, 1420) + if err != nil { + t.Fatal(err) + } + dev := device.NewDevice(tun, conn.NewDefaultBind(), device.NewLogger(device.LogLevelSilent, "")) + t.Cleanup(dev.Close) + + // The device is not brought up, so no handshake can ever happen. + endpoint := "192.0.2.1:51820" + request := "private_key=" + handshakeHexB + "\npublic_key=" + handshakeHexA + "\n" + + "endpoint=" + endpoint + "\nallowed_ip=0.0.0.0/0\n" + if err := dev.IpcSet(request); err != nil { + t.Fatal(err) + } + + conf := &DeviceConfig{CheckAliveInterval: 5, MaxHandshakeAge: maxHandshakeAge} + peer := PeerConfig{PublicKey: handshakeHexA} + if configuredEndpoint { + peer.Endpoint = &endpoint + } + conf.Peers = []PeerConfig{peer} + + return VirtualTun{ + Dev: dev, + Conf: conf, + PingRecord: make(map[string]uint64), + PingRecordLock: new(sync.Mutex), + } +} + +func TestReadyzMaxHandshakeAge(t *testing.T) { + t.Run("unset keeps the existing behaviour", func(t *testing.T) { + rec := httptest.NewRecorder() + newReadyzTun(t, 0).ServeHTTP(rec, httptest.NewRequest("GET", "/readyz", nil)) + if rec.Code != http.StatusOK || strings.TrimSpace(rec.Body.String()) != "{}" { + t.Fatalf("got %d %q", rec.Code, rec.Body.String()) + } + }) + + t.Run("peer that never handshook is unavailable", func(t *testing.T) { + rec := httptest.NewRecorder() + newReadyzTun(t, 120).ServeHTTP(rec, httptest.NewRequest("GET", "/readyz", nil)) + if rec.Code != http.StatusServiceUnavailable { + t.Fatalf("got %d %q", rec.Code, rec.Body.String()) + } + if strings.TrimSpace(rec.Body.String()) != `{"`+handshakeKeyA+`":0}` { + t.Fatalf("unexpected body %q", rec.Body.String()) + } + }) + + t.Run("peer without a configured endpoint is skipped", func(t *testing.T) { + rec := httptest.NewRecorder() + newReadyzTunPeer(t, 120, false).ServeHTTP(rec, httptest.NewRequest("GET", "/readyz", nil)) + want := `{"` + handshakeKeyA + `":0,"handshake_skipped:` + strings.TrimPrefix(handshakeKeyA, "handshake:") + `":1}` + if rec.Code != http.StatusOK || strings.TrimSpace(rec.Body.String()) != want { + t.Fatalf("got %d %q, want 200 %q", rec.Code, rec.Body.String(), want) + } + }) +} + +// TestReadyzFreshHandshake brings up two wireguard devices over loopback and +// expects /readyz of the initiator to turn 200 once they have handshaked. Only the +// endpoint is loopback: wireguard-go's default bind listens on all interfaces, and +// there is no option to restrict it. +func TestReadyzFreshHandshake(t *testing.T) { + keyHex := func(seed byte) (private, public string) { + raw := make([]byte, 32) + raw[1] = seed + key, err := ecdh.X25519().NewPrivateKey(raw) + if err != nil { + t.Fatal(err) + } + return hex.EncodeToString(raw), hex.EncodeToString(key.PublicKey().Bytes()) + } + newDev := func() (*device.Device, *netstack.Net) { + tun, tnet, err := netstack.CreateNetTUN([]netip.Addr{netip.MustParseAddr("10.0.0.2")}, nil, 1420) + if err != nil { + t.Fatal(err) + } + dev := device.NewDevice(tun, conn.NewDefaultBind(), device.NewLogger(device.LogLevelSilent, "")) + t.Cleanup(dev.Close) + return dev, tnet + } + + privA, pubA := keyHex(1) + privB, pubB := keyHex(2) + + devB, _ := newDev() + if err := devB.IpcSet("private_key=" + privB + "\nlisten_port=0\npublic_key=" + pubA + "\nallowed_ip=0.0.0.0/0\n"); err != nil { + t.Fatal(err) + } + if err := devB.Up(); err != nil { + t.Fatal(err) + } + ipc, err := devB.IpcGet() + if err != nil { + t.Fatal(err) + } + var portB string + for _, line := range strings.Split(ipc, "\n") { + if v, ok := strings.CutPrefix(line, "listen_port="); ok { + portB = v + } + } + if _, err := strconv.Atoi(portB); err != nil { + t.Fatalf("no listen_port in %q", ipc) + } + + endpoint := "127.0.0.1:" + portB + devA, _ := newDev() + if err := devA.IpcSet("private_key=" + privA + "\nlisten_port=0\npublic_key=" + pubB + + "\nendpoint=" + endpoint + "\npersistent_keepalive_interval=1\nallowed_ip=0.0.0.0/0\n"); err != nil { + t.Fatal(err) + } + if err := devA.Up(); err != nil { + t.Fatal(err) + } + + tun := VirtualTun{ + Dev: devA, + Conf: &DeviceConfig{CheckAliveInterval: 5, MaxHandshakeAge: 120, Peers: []PeerConfig{{PublicKey: pubB, Endpoint: &endpoint}}}, + PingRecord: make(map[string]uint64), + PingRecordLock: new(sync.Mutex), + } + + deadline := time.Now().Add(10 * time.Second) + for { + rec := httptest.NewRecorder() + tun.ServeHTTP(rec, httptest.NewRequest("GET", "/readyz", nil)) + if rec.Code == http.StatusOK { + var body map[string]uint64 + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatal(err) + } + if len(body) != 1 { + t.Fatalf("unexpected body %q", rec.Body.String()) + } + for _, sec := range body { + if sec == 0 { + t.Fatalf("200 with an empty handshake time: %q", rec.Body.String()) + } + } + return + } + if time.Now().After(deadline) { + t.Fatalf("no fresh handshake within 10s, last got %d %q", rec.Code, rec.Body.String()) + } + time.Sleep(100 * time.Millisecond) + } +} + +func TestMaxHandshakeAgeConfig(t *testing.T) { + const base = ` +[Interface] +PrivateKey = LAr1aNSNF9d0MjwUgAVC4020T0N/E5NUtqVv5EnsSz0= +Address = 10.5.0.2 +` + tests := []struct { + extra string + want int + wantErr bool + }{ + {"", 0, false}, + {"MaxHandshakeAge = 180", 180, false}, + {"MaxHandshakeAge = 0", 0, false}, + {"MaxHandshakeAge = -1", 0, true}, + {"MaxHandshakeAge = abc", 0, true}, + } + for _, tt := range tests { + var cfg DeviceConfig + iniData, err := loadIniConfig(base + tt.extra) + if err != nil { + t.Fatal(err) + } + err = ParseInterface(iniData, &cfg) + if (err != nil) != tt.wantErr { + t.Fatalf("%q: unexpected error state: %v", tt.extra, err) + } + if err == nil && cfg.MaxHandshakeAge != tt.want { + t.Fatalf("%q: expected %d, got %d", tt.extra, tt.want, cfg.MaxHandshakeAge) + } + } +} + +func TestHealthcheck(t *testing.T) { + serve := func(status int) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/readyz" { + w.WriteHeader(http.StatusNotFound) + return + } + w.WriteHeader(status) + _, _ = w.Write([]byte(`{"1.1.1.1":0}`)) + })) + } + addr := func(s *httptest.Server) string { return strings.TrimPrefix(s.URL, "http://") } + + ok := serve(http.StatusOK) + defer ok.Close() + if err := Healthcheck(addr(ok), time.Second); err != nil { + t.Fatalf("expected healthy, got %v", err) + } + + bad := serve(http.StatusServiceUnavailable) + defer bad.Close() + err := Healthcheck(addr(bad), time.Second) + if err == nil || !strings.Contains(err.Error(), "503") || !strings.Contains(err.Error(), `{"1.1.1.1":0}`) { + t.Fatalf("expected a 503 error with the body, got %v", err) + } + + closed := serve(http.StatusOK) + closedAddr := addr(closed) + closed.Close() + if err := Healthcheck(closedAddr, time.Second); err == nil { + t.Fatal("expected an error for an unreachable address") + } +} diff --git a/routine.go b/routine.go index 731d0175..0f1631ec 100644 --- a/routine.go +++ b/routine.go @@ -420,13 +420,6 @@ func (d VirtualTun) ServeHTTP(w http.ResponseWriter, r *http.Request) { } d.PingRecordLock.Unlock() - body, err := json.Marshal(records) - if err != nil { - errorLogger.Printf("Failed to get device metrics: %s\n", err.Error()) - w.WriteHeader(http.StatusInternalServerError) - return - } - status := http.StatusOK for _, record := range records { lastPong := time.Unix(int64(record), 0) @@ -437,6 +430,29 @@ func (d VirtualTun) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } + if d.Conf.MaxHandshakeAge > 0 { + get, err := d.Dev.IpcGet() + if err != nil { + errorLogger.Printf("Failed to get device metrics: %s\n", err.Error()) + w.WriteHeader(http.StatusInternalServerError) + return + } + handshakes, stale := handshakeRecords(get, d.Conf.Peers, time.Duration(d.Conf.MaxHandshakeAge)*time.Second, time.Now()) + for addr, record := range handshakes { + records[addr] = record + } + if stale { + status = http.StatusServiceUnavailable + } + } + + body, err := json.Marshal(records) + if err != nil { + errorLogger.Printf("Failed to get device metrics: %s\n", err.Error()) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.WriteHeader(status) _, _ = w.Write(body) _, _ = w.Write([]byte("\n"))