Skip to content
Closed
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
14 changes: 14 additions & 0 deletions export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,20 @@ func WaitForDERPForTest(t testing.TB, s *Server, c *Client) {
}
}

// MeowForTest sets up c's network stack without going on the network and
// hands its meow straight to s, as if it had arrived over DERP. A test can
// then check how s took the client before c advertises any endpoints.
func MeowForTest(t testing.TB, s *Server, c *Client) {
t.Helper()
c.startMu.Lock()
err := c.initLocked()
c.startMu.Unlock()
if err != nil {
t.Fatalf("initializing client: %v", err)
}
s.lb.onMeow(c.lb.pub, c.lb.discoPublic())
}

// PingForTest waits for the client's DERP connection and performs the
// meow/meowed handshake.
func PingForTest(t testing.TB, s *Server, c *Client) PingResult {
Expand Down
58 changes: 40 additions & 18 deletions tailcat.go
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,12 @@ type locoBackend struct {
hybrid bool // whether to use the hybrid post-quantum WireGuard handshake
isServer bool

// discoPriv is the node's path-discovery key. A server derives it from
// its node key, because the key is part of its address. A client gets a
// fresh one per Client, so a server can tell a restarted client from the
// old one and drop the old one's direct path.
discoPriv key.DiscoPrivate

// discoPublic returns the node's disco public key, memoized to
// avoid redoing the curve25519 derivation for every client that
// joins.
Expand Down Expand Up @@ -686,7 +692,7 @@ func (s *Server) startLocked(ctx context.Context) error {
return fmt.Errorf("missing RegionID in %v", logger.AsJSON(reg))
}

lb := newLocoBackend(priv, psk)
lb := newLocoBackend(priv, discoPrivateForNode(priv), psk)
lb.hybrid = s.Hybrid
lb.logf = logf
lb.dm = &tailcfg.DERPMap{}
Expand Down Expand Up @@ -1060,7 +1066,9 @@ func (s *Server) TailcatAddr() Addr {
return s.lb.tailcatAddr()
}

func newLocoBackend(priv key.NodePrivate, psk PresharedKey) *locoBackend {
// newLocoBackend returns a backend for node key priv that uses discoPriv
// for path discovery.
func newLocoBackend(priv key.NodePrivate, discoPriv key.DiscoPrivate, psk PresharedKey) *locoBackend {
pub := priv.Public()
addr := tcAddrForKey(pub)
addrPrefix := netip.PrefixFrom(addr, addr.BitLen())
Expand All @@ -1071,8 +1079,9 @@ func newLocoBackend(priv key.NodePrivate, psk PresharedKey) *locoBackend {
addr: addr,
addrPrefix: addrPrefix,
presharedKey: psk,
discoPriv: discoPriv,
}
lb.discoPublic = sync.OnceValue(func() key.DiscoPublic { return discoPrivateForNode(lb.priv).Public() })
lb.discoPublic = sync.OnceValue(func() key.DiscoPublic { return lb.discoPriv.Public() })
return lb
}

Expand Down Expand Up @@ -1656,8 +1665,9 @@ func (b *locoBackend) onEngineStatus(st *wgengine.Status, err error) {
// control plane flow uses in regular Tailscale. The peer's magicsock
// reacts by disco-pinging those endpoints, which both teaches it a
// direct path to us and teaches us its address from the pings we
// receive back. It's called whenever our endpoints change and when a
// peer first completes the meow handshake, and is idempotent.
// receive back. It's called whenever our endpoints change, when a peer
// first completes the meow handshake, and when a known client comes back
// with a new disco key. It is idempotent.
func (b *locoBackend) advertiseEndpoints() {
if runtime.GOOS == "js" {
// In browsers this does nothing: js/wasm has no UDP, so
Expand All @@ -1678,7 +1688,6 @@ func (b *locoBackend) advertiseEndpoints() {
return
}
payload := (&disco.CallMeMaybe{MyNumber: eps}).AppendMarshal(nil)
discoPriv := discoPrivateForNode(b.priv)
mc := b.sys.MagicSock.Get()
regionID := b.derpRegionID()
for _, p := range peers {
Expand All @@ -1688,7 +1697,7 @@ func (b *locoBackend) advertiseEndpoints() {
pkt := make([]byte, 0, 512)
pkt = append(pkt, disco.Magic...)
pkt = b.discoPublic().AppendTo(pkt)
pkt = append(pkt, discoPriv.Shared(p.DiscoKey()).Seal(payload)...)
pkt = append(pkt, b.discoPriv.Shared(p.DiscoKey()).Seal(payload)...)
if _, err := mc.SendDERPPacketTo(p.Key(), regionID, pkt); err != nil {
b.logf("advertiseEndpoints to %v: %v", p.Key().ShortString(), err)
}
Expand Down Expand Up @@ -1811,14 +1820,27 @@ func (lb *locoBackend) Start() error {
}

// onMeow handles a MeowPing from the client with node key src and
// disco key discoPub, adding it as a WireGuard peer. It reports
// whether the client is allowed and configured, meaning a "meowed"
// disco key discoPub, adding it as a WireGuard peer. For a client it
// already knows that comes back with a different disco key (a restarted
// client), it updates the peer's disco key instead. It reports whether
// the client is allowed and configured, meaning a "meowed"
// acknowledgment may be sent.
func (b *locoBackend) onMeow(src key.NodePublic, discoPub key.DiscoPublic) bool {
b.logf("got meow from %v", src.String())
b.mu.Lock()
defer b.mu.Unlock()
if _, ok := b.clients[src]; ok {
if n, ok := b.clients[src]; ok {
if n.DiscoKey == discoPub {
return true
}
// The client restarted with a new disco key. Updating it makes
// magicsock forget the old process's direct path, so replies go
// through DERP until the new path is found.
n = n.Clone() // the old netmap still holds views of n
n.DiscoKey = discoPub
b.clients[src] = n
b.setNetworkMapLocked()
go b.advertiseEndpoints()
return true
}
if b.allowClient != nil {
Expand Down Expand Up @@ -2018,13 +2040,13 @@ func createEngine(logf logger.Logf, lb *locoBackend) (err error) {
if lb.isServer {
conf.DERPAppName = "tailcat-server"
}
// Both sides deterministically derive a separate disco key from their
// node private key. The public disco key, unlike the node key, is safe to
// expose in direct-path disco frames. Knowing our own disco private key
// is what lets either side seal the
// call-me-maybe messages that advertise our UDP endpoints (see
// locoBackend.advertiseEndpoints).
conf.ForceDiscoKey = discoPrivateForNode(lb.priv)
// The server derives a separate disco key from its node private key,
// and a client uses a fresh one (see locoBackend.discoPriv). The public
// disco key, unlike the node key, is safe to expose in direct-path
// disco frames. Knowing our own disco private key is what lets either
// side seal the call-me-maybe messages that advertise our UDP
// endpoints (see locoBackend.advertiseEndpoints).
conf.ForceDiscoKey = lb.discoPriv
netns.SetEnabled(false)
e, err := wgengine.NewUserspaceEngine(logf, conf)
if err != nil {
Expand Down Expand Up @@ -2122,7 +2144,7 @@ func (c *Client) initLocked() error {
if ci.ServerDiscoPublic.IsZero() {
return errors.New("legacy tailcat address lacks a separate disco key; generate a new address with an updated tailcat server")
}
lb := newLocoBackend(c.nodeKeyLocked(), ci.PresharedKey)
lb := newLocoBackend(c.nodeKeyLocked(), key.NewDisco(), ci.PresharedKey)
lb.logf = logf
lb.dm = &tailcfg.DERPMap{}
lb.serverPub = ci.ServerPublic.NodePublic
Expand Down
122 changes: 122 additions & 0 deletions tailcat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,128 @@ func TestDisconnectClient(t *testing.T) {
}
}

// TestClientRestartSameKey checks that when a client process restarts
// with the same node key, the server stops using the old process's
// direct UDP path as soon as the new process's meow arrives. The server
// used to keep that path, so its WireGuard handshake response could go
// to a dead port and the new client waited for the handshake retry,
// about 5 s.
func TestClientRestartSameKey(t *testing.T) {
t.Parallel()

dm := integration.RunDERPAndSTUN(t, mkLogger(t, "derpstun"), "127.0.0.1")
reg := dm.Regions[1]
if reg == nil {
t.Fatal("no region 1 in derpmap")
}

s := &Server{Key: key.NewNode(), Logf: mkLogger(t, "server"), Region: reg}
t.Cleanup(func() { s.Close() })
s.OnTCP = func(port uint16) func(net.Conn) {
if port != 80 {
return nil
}
return func(c net.Conn) {
io.WriteString(c, "hello\n")
c.Close()
}
}
if err := s.Start(); err != nil {
t.Fatalf("server Start: %v", err)
}

dial := func(c *Client, timeout time.Duration) (time.Duration, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
t0 := time.Now()
conn, err := c.DialTCPPort(ctx, 80)
if err != nil {
return 0, err
}
defer conn.Close()
conn.SetReadDeadline(time.Now().Add(timeout))
got, err := io.ReadAll(conn)
if err != nil {
return 0, err
}
if string(got) != "hello\n" {
return 0, fmt.Errorf("read %q; want %q", got, "hello\n")
}
return time.Since(t0), nil
}

nodeKey := key.NewNode()

// serverPath reports the direct address the server uses for nodeKey,
// or "" if it sends over DERP.
serverPath := func() string {
if ps, ok := s.Status().Peer[nodeKey.Public()]; ok {
return ps.CurAddr
}
return ""
}
// waitDirect waits until c and the server both use a direct path and
// returns the server's address for c.
waitDirect := func(c *Client) string {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
res, err := c.DiscoPing(ctx)
cancel()
if err == nil && res.Endpoint != "" {
if p := serverPath(); p != "" {
return p
}
}
if time.Now().After(deadline) {
t.Fatalf("no direct path both ways (last ping %+v, %v; server path %q)", res, err, serverPath())
}
time.Sleep(100 * time.Millisecond)
}
}

prev := &Client{Server: s.TailcatAddr(), Key: nodeKey, Logf: mkLogger(t, "client0")}
t.Cleanup(func() { prev.Close() })
PingForTest(t, s, prev)
if _, err := dial(prev, 10*time.Second); err != nil {
t.Fatalf("client0: %v", err)
}

// Restart twice, so the second restart replaces a client that was
// itself a restart.
for i := 1; i <= 2; i++ {
oldPath := waitDirect(prev)
prev.Close()
// WireGuard rounds handshake timestamps down to about 16.8 ms and
// rejects one that isn't newer than the last from the same key
// as a replay. A real process restart takes longer than that.
time.Sleep(50 * time.Millisecond)

name := fmt.Sprintf("client%d", i)
c := &Client{Server: s.TailcatAddr(), Key: nodeKey, Logf: mkLogger(t, name)}
t.Cleanup(func() { c.Close() })

// Hand the new process's meow to the server before the client goes
// on the network. Once it is up, the client advertises its endpoints,
// and on a fast machine the server can find the new path that way
// before the first dial, which hides the bug. Here only the meow can
// make the server drop the previous process's path.
MeowForTest(t, s, c)
if p := serverPath(); p == oldPath {
t.Errorf("%s: after the new process's meow, the server still sends to the previous process at %s", name, p)
}

PingForTest(t, s, c)
d, err := dial(c, 10*time.Second)
if err != nil {
t.Fatalf("%s: %v", name, err)
}
t.Logf("%s dialed in %v", name, d)
prev = c
}
}

func TestUDP(t *testing.T) {
dm := integration.RunDERPAndSTUN(t, mkLogger(t, "derpstun"), "127.0.0.1")
reg := dm.Regions[1]
Expand Down