Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions cmd/wireproxy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ func main() {
}

tun.StartPingIPs()
tun.StartEndpointReresolve()

if *info != "" {
go func() {
Expand Down
24 changes: 22 additions & 2 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 {
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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 {
Expand Down
146 changes: 146 additions & 0 deletions reresolve.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
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
handshakeSec int64
handshakeNsec int64
}

// 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
for _, line := range strings.Split(ipc, "\n") {
key, value, ok := strings.Cut(line, "=")
if !ok {
continue
}
switch key {
case "public_key":
current = &peerStatus{}
statuses[value] = current
case "endpoint":
if current != nil {
current.endpoint = value
}
case "last_handshake_time_sec":
if current != nil {
current.handshakeSec, _ = strconv.ParseInt(value, 10, 64)
}
case "last_handshake_time_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
}

// 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)
}
}()
}
Loading