From f7d046b446d57b80d7853e33f09d207bb6fa56a5 Mon Sep 17 00:00:00 2001 From: dividedby <64715420+dividedby@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:53:00 -0600 Subject: [PATCH 1/2] Re-resolve hostname peer endpoints when the handshake goes stale An Endpoint hostname was resolved once at config load, so a peer behind dynamic DNS stayed unreachable after its IP changed until wireproxy was restarted. For peers whose endpoint is a hostname, check the last handshake every EndpointReresolveInterval seconds ([Interface], default 30, 0 disables). When it is older than 135s or has never happened (the threshold used by wireguard-tools' contrib/reresolve-dns), resolve the hostname again and set the new endpoint with update_only if it differs from the current one. A failed lookup is logged and the current endpoint is kept. IP literal endpoints never start the loop. Startup behaviour for an unresolvable hostname is unchanged. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 13 +++ cmd/wireproxy/main.go | 1 + config.go | 24 ++++- reresolve.go | 138 +++++++++++++++++++++++++++ reresolve_test.go | 212 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 386 insertions(+), 2 deletions(-) create mode 100644 reresolve.go create mode 100644 reresolve_test.go diff --git a/README.md b/README.md index cd6f0718..02abf044 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,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) +# EndpointReresolveInterval = 30 (optional, see "Dynamic DNS endpoints" below) PrivateKey = uCTIK+56CPyCvwJxmU5dBfuyJvPuSXAq1FzHdnIxe1Q= # PrivateKey = $MY_WIREGUARD_PRIVATE_KEY # Alternatively, reference environment variables DNS = 10.200.200.1 @@ -255,6 +256,18 @@ AllowedIPs = 10.254.254.100/32 # Note there is no Endpoint defined here. ``` +# Dynamic DNS endpoints + +A `[Peer]` `Endpoint` that is a hostname is resolved when the config is loaded. +To follow a peer whose IP address changes (e.g. behind dynamic DNS), wireproxy checks +every `EndpointReresolveInterval` seconds (`[Interface]`, defaults to 30, `0` disables) +the last handshake of each peer with a hostname endpoint. If there has been no +handshake for more than 135 seconds, the hostname is resolved again and the peer's +endpoint is updated if the address changed. A failed lookup is logged and the +current endpoint is kept. Endpoints given as an IP address are never re-resolved. + +The hostname must still resolve when wireproxy starts. + # Health endpoint Wireproxy supports exposing a health endpoint for monitoring purposes. diff --git a/cmd/wireproxy/main.go b/cmd/wireproxy/main.go index e993e880..bf8ad095 100644 --- a/cmd/wireproxy/main.go +++ b/cmd/wireproxy/main.go @@ -289,6 +289,7 @@ func main() { } tun.StartPingIPs() + tun.StartEndpointReresolve() if *info != "" { go func() { diff --git a/config.go b/config.go index 9bf53ff4..0fd8f154 100644 --- a/config.go +++ b/config.go @@ -21,6 +21,9 @@ type PeerConfig struct { Endpoint *string KeepAlive int AllowedIPs []netip.Prefix + // EndpointRaw is the endpoint as written in the config (host:port), + // kept so that a hostname can be resolved again at runtime. + EndpointRaw string } // DeviceConfig contains the information to initiate a wireguard connection @@ -33,6 +36,9 @@ type DeviceConfig struct { ListenPort *int CheckAlive []netip.Addr CheckAliveInterval int + // EndpointReresolveInterval is how often, in seconds, peers with a hostname + // endpoint are checked for a stale handshake. 0 disables re-resolving. + EndpointReresolveInterval int } type UDPProxyTunnelConfig struct { @@ -326,6 +332,19 @@ func ParseInterface(cfg *ini.File, device *DeviceConfig) error { device.CheckAliveInterval = value } + device.EndpointReresolveInterval = 30 + if sectionKey, err := section.GetKey("EndpointReresolveInterval"); err == nil { + value, err := sectionKey.Int() + if err != nil { + return err + } + if value < 0 { + return errors.New("EndpointReresolveInterval should not be negative") + } + + device.EndpointReresolveInterval = value + } + return nil } @@ -357,12 +376,13 @@ func ParsePeers(cfg *ini.File, peers *[]PeerConfig) error { } if sectionKey, err := section.GetKey("Endpoint"); err == nil { - value := sectionKey.String() - decoded, err = resolveIPPAndPort(strings.ToLower(value)) + value := strings.ToLower(sectionKey.String()) + decoded, err = resolveIPPAndPort(value) if err != nil { return err } peer.Endpoint = &decoded + peer.EndpointRaw = value } if sectionKey, err := section.GetKey("PersistentKeepalive"); err == nil { diff --git a/reresolve.go b/reresolve.go new file mode 100644 index 00000000..df2d914b --- /dev/null +++ b/reresolve.go @@ -0,0 +1,138 @@ +package wireproxy + +import ( + "fmt" + "log" + "net" + "net/netip" + "strconv" + "strings" + "time" +) + +// reresolveHandshakeAge is how old the last handshake of a peer has to be +// before its endpoint is resolved again: REKEY_AFTER_TIME (120s) plus a +// margin, the same threshold as wireguard-tools' contrib/reresolve-dns. +const reresolveHandshakeAge = 135 * time.Second + +// ipcDevice is the part of *device.Device used to update peer endpoints. +type ipcDevice interface { + IpcGet() (string, error) + IpcSet(string) error +} + +// peerStatus is what IpcGet reports about a peer that is needed to decide +// whether its endpoint should be resolved again. +type peerStatus struct { + endpoint string + lastHandshake time.Time // zero if there has never been a handshake +} + +// parsePeerStatuses extracts the endpoint and last handshake time of every +// peer in an IpcGet response, keyed by hex public key. +func parsePeerStatuses(ipc string) map[string]*peerStatus { + statuses := make(map[string]*peerStatus) + var current *peerStatus + var sec, nsec int64 + for _, line := range strings.Split(ipc, "\n") { + key, value, ok := strings.Cut(line, "=") + if !ok { + continue + } + switch key { + case "public_key": + current = &peerStatus{} + sec, nsec = 0, 0 + statuses[value] = current + case "endpoint": + if current != nil { + current.endpoint = value + } + case "last_handshake_time_sec": + sec, _ = strconv.ParseInt(value, 10, 64) + case "last_handshake_time_nsec": + nsec, _ = strconv.ParseInt(value, 10, 64) + if current != nil && sec != 0 { + current.lastHandshake = time.Unix(sec, nsec) + } + } + } + return statuses +} + +// reresolvablePeers returns the peers whose endpoint is a hostname, which can +// change over time. Peers without an endpoint or with an IP literal are skipped. +func reresolvablePeers(peers []PeerConfig) []PeerConfig { + var result []PeerConfig + for _, peer := range peers { + if peer.Endpoint == nil || peer.EndpointRaw == "" { + continue + } + host, _, err := net.SplitHostPort(peer.EndpointRaw) + if err != nil { + continue + } + if _, err := netip.ParseAddr(host); err == nil { + continue + } + result = append(result, peer) + } + return result +} + +// reresolveEndpoints resolves the endpoint of every given peer again if its +// last handshake is older than reresolveHandshakeAge (or never happened), and +// updates the peer if the resolved address differs from the current one. +// Failures keep the current endpoint. +func reresolveEndpoints(dev ipcDevice, peers []PeerConfig, resolve func(string) (string, error), now time.Time) { + get, err := dev.IpcGet() + if err != nil { + errorLogger.Printf("Failed to get device state to re-resolve endpoints: %s\n", err.Error()) + return + } + statuses := parsePeerStatuses(get) + + for _, peer := range peers { + status, ok := statuses[peer.PublicKey] + if !ok { + continue + } + if !status.lastHandshake.IsZero() && now.Sub(status.lastHandshake) <= reresolveHandshakeAge { + continue + } + + endpoint, err := resolve(peer.EndpointRaw) + if err != nil { + errorLogger.Printf("Failed to resolve endpoint %s: %s\n", peer.EndpointRaw, err.Error()) + continue + } + if endpoint == status.endpoint { + continue + } + + request := fmt.Sprintf("public_key=%s\nupdate_only=true\nendpoint=%s\n", peer.PublicKey, endpoint) + if err := dev.IpcSet(request); err != nil { + errorLogger.Printf("Failed to update endpoint of %s: %s\n", peer.EndpointRaw, err.Error()) + continue + } + log.Printf("Endpoint %s changed from %s to %s\n", peer.EndpointRaw, status.endpoint, endpoint) + } +} + +// StartEndpointReresolve periodically resolves hostname endpoints again, so +// that a peer behind a dynamic DNS name is found after its IP address changes. +// It does nothing if disabled or if no peer has a hostname endpoint. +func (d VirtualTun) StartEndpointReresolve() { + peers := reresolvablePeers(d.Conf.Peers) + if d.Conf.EndpointReresolveInterval <= 0 || len(peers) == 0 { + return + } + + go func() { + ticker := time.NewTicker(time.Duration(d.Conf.EndpointReresolveInterval) * time.Second) + defer ticker.Stop() + for now := range ticker.C { + reresolveEndpoints(d.Dev, peers, resolveIPPAndPort, now) + } + }() +} diff --git a/reresolve_test.go b/reresolve_test.go new file mode 100644 index 00000000..8842c105 --- /dev/null +++ b/reresolve_test.go @@ -0,0 +1,212 @@ +package wireproxy + +import ( + "errors" + "fmt" + "strings" + "testing" + "time" +) + +const ( + testKeyA = "0000000000000000000000000000000000000000000000000000000000000001" + testKeyB = "0000000000000000000000000000000000000000000000000000000000000002" +) + +type fakeIpcDevice struct { + get string + getErr error + sets []string +} + +func (f *fakeIpcDevice) IpcGet() (string, error) { return f.get, f.getErr } + +func (f *fakeIpcDevice) IpcSet(request string) error { + f.sets = append(f.sets, request) + return nil +} + +func ipcPeer(key, endpoint string, handshake time.Time) string { + var sec, nsec int64 + if !handshake.IsZero() { + sec, nsec = handshake.Unix(), int64(handshake.Nanosecond()) + } + return fmt.Sprintf("public_key=%s\nendpoint=%s\nlast_handshake_time_sec=%d\nlast_handshake_time_nsec=%d\ntx_bytes=1\nrx_bytes=1\n", + key, endpoint, sec, nsec) +} + +func fixedResolver(addr string, err error, calls *int) func(string) (string, error) { + return func(string) (string, error) { + *calls++ + return addr, err + } +} + +func hostPeer(key string) PeerConfig { + endpoint := "1.1.1.1:51820" + return PeerConfig{PublicKey: key, Endpoint: &endpoint, EndpointRaw: "vpn.example.com:51820"} +} + +func TestReresolveStaleHandshakeChangedIP(t *testing.T) { + now := time.Unix(1_700_000_000, 0) + dev := &fakeIpcDevice{get: "private_key=aa\nlisten_port=0\n" + + ipcPeer(testKeyA, "1.1.1.1:51820", now.Add(-10*time.Minute))} + calls := 0 + + reresolveEndpoints(dev, []PeerConfig{hostPeer(testKeyA)}, fixedResolver("2.2.2.2:51820", nil, &calls), now) + + if calls != 1 { + t.Fatalf("expected 1 resolve, got %d", calls) + } + want := "public_key=" + testKeyA + "\nupdate_only=true\nendpoint=2.2.2.2:51820\n" + if len(dev.sets) != 1 || dev.sets[0] != want { + t.Fatalf("unexpected IpcSet calls: %q", dev.sets) + } +} + +func TestReresolveNeverHandshaken(t *testing.T) { + now := time.Unix(1_700_000_000, 0) + dev := &fakeIpcDevice{get: ipcPeer(testKeyA, "1.1.1.1:51820", time.Time{})} + calls := 0 + + reresolveEndpoints(dev, []PeerConfig{hostPeer(testKeyA)}, fixedResolver("2.2.2.2:51820", nil, &calls), now) + + if calls != 1 || len(dev.sets) != 1 { + t.Fatalf("expected 1 resolve and 1 IpcSet, got %d and %d", calls, len(dev.sets)) + } +} + +func TestReresolveFreshHandshakeDoesNotResolve(t *testing.T) { + now := time.Unix(1_700_000_000, 0) + dev := &fakeIpcDevice{get: ipcPeer(testKeyA, "1.1.1.1:51820", now.Add(-30*time.Second))} + calls := 0 + + reresolveEndpoints(dev, []PeerConfig{hostPeer(testKeyA)}, fixedResolver("2.2.2.2:51820", nil, &calls), now) + + if calls != 0 || len(dev.sets) != 0 { + t.Fatalf("expected no resolve and no IpcSet, got %d and %d", calls, len(dev.sets)) + } +} + +func TestReresolveUnchangedIP(t *testing.T) { + now := time.Unix(1_700_000_000, 0) + dev := &fakeIpcDevice{get: ipcPeer(testKeyA, "1.1.1.1:51820", now.Add(-10*time.Minute))} + calls := 0 + + reresolveEndpoints(dev, []PeerConfig{hostPeer(testKeyA)}, fixedResolver("1.1.1.1:51820", nil, &calls), now) + + if calls != 1 || len(dev.sets) != 0 { + t.Fatalf("expected 1 resolve and no IpcSet, got %d and %d", calls, len(dev.sets)) + } +} + +func TestReresolveErrorKeepsEndpoint(t *testing.T) { + now := time.Unix(1_700_000_000, 0) + dev := &fakeIpcDevice{get: ipcPeer(testKeyA, "1.1.1.1:51820", now.Add(-10*time.Minute))} + calls := 0 + + reresolveEndpoints(dev, []PeerConfig{hostPeer(testKeyA)}, fixedResolver("", errors.New("no such host"), &calls), now) + + if calls != 1 || len(dev.sets) != 0 { + t.Fatalf("expected 1 resolve and no IpcSet, got %d and %d", calls, len(dev.sets)) + } +} + +func TestReresolveIpcGetErrorDoesNothing(t *testing.T) { + dev := &fakeIpcDevice{getErr: errors.New("boom")} + calls := 0 + + reresolveEndpoints(dev, []PeerConfig{hostPeer(testKeyA)}, fixedResolver("2.2.2.2:51820", nil, &calls), time.Now()) + + if calls != 0 || len(dev.sets) != 0 { + t.Fatalf("expected no resolve and no IpcSet, got %d and %d", calls, len(dev.sets)) + } +} + +func TestReresolveOnlyUpdatesStalePeer(t *testing.T) { + now := time.Unix(1_700_000_000, 0) + dev := &fakeIpcDevice{get: ipcPeer(testKeyA, "1.1.1.1:51820", now.Add(-5*time.Second)) + + ipcPeer(testKeyB, "[2001:db8::1]:51820", now.Add(-10*time.Minute))} + calls := 0 + + reresolveEndpoints(dev, []PeerConfig{hostPeer(testKeyA), hostPeer(testKeyB)}, fixedResolver("[2001:db8::2]:51820", nil, &calls), now) + + want := "public_key=" + testKeyB + "\nupdate_only=true\nendpoint=[2001:db8::2]:51820\n" + if calls != 1 || len(dev.sets) != 1 || dev.sets[0] != want { + t.Fatalf("unexpected result: %d resolves, IpcSet calls %q", calls, dev.sets) + } +} + +func TestReresolvablePeers(t *testing.T) { + const config = ` +[Peer] +PublicKey = e8LKAc+f9xEzq9Ar7+MfKRrs+gZ/4yzvpRJLRJ/VJ1w= +Endpoint = 94.140.11.15:51820 + +[Peer] +PublicKey = LAr1aNSNF9d0MjwUgAVC4020T0N/E5NUtqVv5EnsSz0= +Endpoint = [::1]:51820 + +[Peer] +PublicKey = QP+A67Z2UBrMgvNIdHv8gPel5URWNLS4B3ZQ2hQIZlg= +` + iniData, err := loadIniConfig(config) + if err != nil { + t.Fatal(err) + } + var peers []PeerConfig + if err := ParsePeers(iniData, &peers); err != nil { + t.Fatal(err) + } + if got := reresolvablePeers(peers); len(got) != 0 { + t.Fatalf("expected no re-resolvable peers, got %d", len(got)) + } + + // localhost resolves without network access + hostConfig := strings.Replace(config, "94.140.11.15", "LocalHost", 1) + iniData, err = loadIniConfig(hostConfig) + if err != nil { + t.Fatal(err) + } + peers = nil + if err := ParsePeers(iniData, &peers); err != nil { + t.Fatal(err) + } + got := reresolvablePeers(peers) + if len(got) != 1 || got[0].EndpointRaw != "localhost:51820" { + t.Fatalf("expected the hostname peer only, got %+v", got) + } +} + +func TestEndpointReresolveIntervalConfig(t *testing.T) { + const base = ` +[Interface] +PrivateKey = LAr1aNSNF9d0MjwUgAVC4020T0N/E5NUtqVv5EnsSz0= +Address = 10.5.0.2 +` + tests := []struct { + extra string + want int + wantErr bool + }{ + {"", 30, false}, + {"EndpointReresolveInterval = 10", 10, false}, + {"EndpointReresolveInterval = 0", 0, false}, + {"EndpointReresolveInterval = -1", 0, true}, + {"EndpointReresolveInterval = 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.EndpointReresolveInterval != tt.want { + t.Fatalf("%q: expected %d, got %d", tt.extra, tt.want, cfg.EndpointReresolveInterval) + } + } +} From dcef948e6656624add0a1476ff25cb3de160ae9b Mon Sep 17 00:00:00 2001 From: dividedby <64715420+dividedby@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:05:22 -0600 Subject: [PATCH 2/2] reresolve: read handshake time in any key order Store the seconds and nanoseconds per peer and build the time after the whole IpcGet response is read. Fixes golangci-lint ineffassign on nsec and no longer depends on last_handshake_time_sec preceding _nsec. Co-Authored-By: Claude Opus 5.5 --- reresolve.go | 20 ++++++++++++++------ reresolve_test.go | 11 +++++++++++ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/reresolve.go b/reresolve.go index df2d914b..235e0f5c 100644 --- a/reresolve.go +++ b/reresolve.go @@ -26,6 +26,8 @@ type ipcDevice interface { type peerStatus struct { endpoint string lastHandshake time.Time // zero if there has never been a handshake + handshakeSec int64 + handshakeNsec int64 } // parsePeerStatuses extracts the endpoint and last handshake time of every @@ -33,7 +35,6 @@ type peerStatus struct { func parsePeerStatuses(ipc string) map[string]*peerStatus { statuses := make(map[string]*peerStatus) var current *peerStatus - var sec, nsec int64 for _, line := range strings.Split(ipc, "\n") { key, value, ok := strings.Cut(line, "=") if !ok { @@ -42,21 +43,28 @@ func parsePeerStatuses(ipc string) map[string]*peerStatus { switch key { case "public_key": current = &peerStatus{} - sec, nsec = 0, 0 statuses[value] = current case "endpoint": if current != nil { current.endpoint = value } case "last_handshake_time_sec": - sec, _ = strconv.ParseInt(value, 10, 64) + if current != nil { + current.handshakeSec, _ = strconv.ParseInt(value, 10, 64) + } case "last_handshake_time_nsec": - nsec, _ = strconv.ParseInt(value, 10, 64) - if current != nil && sec != 0 { - current.lastHandshake = time.Unix(sec, nsec) + if current != nil { + current.handshakeNsec, _ = strconv.ParseInt(value, 10, 64) } } } + // The seconds and nanoseconds keys may arrive in either order, so the + // handshake time is assembled once the whole response has been read. + for _, status := range statuses { + if status.handshakeSec != 0 { + status.lastHandshake = time.Unix(status.handshakeSec, status.handshakeNsec) + } + } return statuses } diff --git a/reresolve_test.go b/reresolve_test.go index 8842c105..f5a0665e 100644 --- a/reresolve_test.go +++ b/reresolve_test.go @@ -210,3 +210,14 @@ Address = 10.5.0.2 } } } + +func TestParsePeerStatusesHandshakeKeyOrder(t *testing.T) { + ipc := "public_key=aa\nlast_handshake_time_nsec=5\nlast_handshake_time_sec=100\nendpoint=192.0.2.1:51820\n" + status := parsePeerStatuses(ipc)["aa"] + if status == nil { + t.Fatal("peer aa not parsed") + } + if want := time.Unix(100, 5); !status.lastHandshake.Equal(want) { + t.Fatalf("lastHandshake = %v, want %v", status.lastHandshake, want) + } +}