diff --git a/net/tsdial/tsdial.go b/net/tsdial/tsdial.go index 28016a5f7..8322522b6 100644 --- a/net/tsdial/tsdial.go +++ b/net/tsdial/tsdial.go @@ -646,6 +646,11 @@ func (d *Dialer) dialOneUser(ctx context.Context, network string, ipp netip.Addr if routes := d.routes.Load(); routes != nil { if isTailscaleRoute, _ := routes.Lookup(ipp.Addr()); isTailscaleRoute { + // This is a check to prevent userspace mode + // from dialing via the host's default route. + if d.UseNetstackForIP != nil { + return nil, fmt.Errorf("no tailnet peer for %v; refusing to dial it from the local network", ipp.Addr()) + } return d.getPeerDialer().DialContext(ctx, network, ipp.String()) } diff --git a/net/tsdial/tsdial_test.go b/net/tsdial/tsdial_test.go index c8868ab36..1881ffb60 100644 --- a/net/tsdial/tsdial_test.go +++ b/net/tsdial/tsdial_test.go @@ -232,3 +232,44 @@ func (c *closingPipeConn) Close() error { } return c.Conn.Close() } + +// This test verifies that in userspace-networking mode +// a user dial to an address that matches a Tailscale route +// but that no netstack peer claims it is refused. +func TestUserDialTailscaleRouteWithoutPeer(t *testing.T) { + tests := []struct { + name string + useNetstackFor func(netip.Addr) bool + wantErr bool + }{ + {"userspace_refused", func(netip.Addr) bool { return false }, true}, + {"tun_uses_peer_dialer", nil, false}, + } + // A loopback listener stands in for a destination reachable from the + // host's network; the connect completes without an Accept. + for _, laddr := range []string{"127.0.0.1:0", "[::1]:0"} { + ln, err := net.Listen("tcp", laddr) + if err != nil { + t.Logf("skipping %v: %v", laddr, err) + continue + } + defer ln.Close() + for _, tt := range tests { + t.Run(tt.name+"/"+laddr, func(t *testing.T) { + d := &Dialer{UseNetstackForIP: tt.useNetstackFor} + rt := &bart.Table[bool]{} + rt.Insert(netip.MustParsePrefix("0.0.0.0/0"), true) + rt.Insert(netip.MustParsePrefix("::/0"), true) + d.routes.Store(rt) + + c, err := d.UserDial(context.Background(), "tcp", ln.Addr().String()) + if c != nil { + c.Close() + } + if gotErr := err != nil; gotErr != tt.wantErr { + t.Errorf("UserDial err = %v, wantErr %v", err, tt.wantErr) + } + }) + } + } +}