wgengine/{tswg,router/osrouter}: make MagicDNS work in kernel mode

In kernel mode, the tswg device doesn't hand tailscaled packets, so
those to the Tailscale service IPs (100.100.100.100 and
fd7a:115c:a1e0::53: MagicDNS, the web client and so on), which the
router routes to tailscale0, went nowhere.

Rather than teach the kernel about them, the tun.Device that tswg gives
tailscaled's TUN wrapper is now a real TUN device, tailscale0-svc,
instead of a fake, and the Linux router sends just the routes to the
service IPs there, when the device says it has one (serviceTUN). So
netstack answers them as in TUN mode, with its replies going back to
the OS through it. Nothing else is routed to it.

TestTSWGTailscaledMagicDNS checks queries to both service IPs, over UDP
and TCP, for a control-provided record and a peer's name, and fails
without the router change. For it, tta gets /dns-lookup, which asks a
given DNS server directly, as gokrazy has no resolver tools.

Updates #426

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: Id34c54a91eb211cc6353cdbc83a2501f927b237e
This commit is contained in:
Brad Fitzpatrick committed 2026-11-09 15:47:37 +00:00
1 parent 9416180488
commit f34a3fd86c
6 files changed
+210 -17

No files matched your search

+29
View File
@@ -355,6 +355,35 @@ func main() {
w.Header().Set("Content-Type", "application/octet-stream")
w.Write(data)
})
ttaMux.HandleFunc("/dns-lookup", func(w http.ResponseWriter, r *http.Request) {
// Look up name's IP addresses by asking the DNS server
// server directly, over net ("udp", the default, or "tcp"),
// through the OS's network stack.
q := r.URL.Query()
server, name, network := q.Get("server"), q.Get("name"), q.Get("net")
if server == "" || name == "" {
http.Error(w, "missing server or name", http.StatusBadRequest)
return
}
if network == "" {
network = "udp"
}
res := &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
var d net.Dialer
return d.DialContext(ctx, network, net.JoinHostPort(server, "53"))
},
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
addrs, err := res.LookupHost(ctx, name)
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
io.WriteString(w, strings.Join(addrs, "\n")+"\n")
})
ttaMux.HandleFunc("/http-get", func(w http.ResponseWriter, r *http.Request) {
targetURL := r.URL.Query().Get("url")
if targetURL == "" {
+73
View File
@@ -0,0 +1,73 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package vmtest_test
import (
"fmt"
"net/url"
"strings"
"testing"
"time"
"tailscale.com/net/tsaddr"
"tailscale.com/tailcfg"
"tailscale.com/tstest"
"tailscale.com/tstest/natlab/vmtest"
"tailscale.com/tstest/natlab/vnet"
"tailscale.com/types/dnstype"
)
// TestTSWGTailscaledMagicDNS checks MagicDNS in kernel mode: queries to
// 100.100.100.100 and fd7a:115c:a1e0::53, over UDP and TCP, from the
// node's own network stack, answered by tailscaled. In kernel mode the
// tswg device doesn't hand tailscaled packets, so the router sends the
// routes to the service IPs to a separate TUN device, from which netstack
// answers them as in TUN mode.
func TestTSWGTailscaledMagicDNS(t *testing.T) {
f := newTSWGTailscaledOpts(t, vnet.EasyNAT, tswgTailscaledOpts{
vmOpts: []vmtest.EnvOption{vmtest.ControlDNS("tailnet.test", &tailcfg.DNSConfig{
Proxied: true,
Domains: []string{"tailnet.test", "record"},
Routes: map[string][]*dnstype.Resolver{
"tailnet.test": nil,
"record": nil,
},
ExtraRecords: []tailcfg.DNSRecord{
{Name: "extratest.record", Type: "A", Value: "1.2.3.4"},
},
})},
})
n1, n2 := f.nodes[0], f.nodes[1]
peerName := strings.TrimSuffix(f.env.Status(n2).Self.DNSName, ".")
peerIP := f.ip(n2).String()
for _, server := range []string{tsaddr.TailscaleServiceIP().String(), tsaddr.TailscaleServiceIPv6().String()} {
for _, network := range []string{"udp", "tcp"} {
for name, want := range map[string]string{
"extratest.record": "1.2.3.4",
peerName: peerIP,
} {
if err := tstest.WaitFor(20*time.Second, func() error {
got, err := ttaErr(n1, "GET", "/dns-lookup?"+url.Values{
"server": {server}, "name": {name}, "net": {network},
}.Encode(), nil)
if err != nil {
return err
}
if !strings.Contains(got, want) {
return fmt.Errorf("got %q, want %q", strings.TrimSpace(got), want)
}
return nil
}); err != nil {
t.Errorf("[%s] looking up %s at %s over %s: %v", n1.Name(), name, server, network, err)
} else {
t.Logf("[%s] %s at %s over %s: %s", n1.Name(), name, server, network, want)
}
}
}
}
// And the tunnel to the peer still works.
f.env.LANPing(n1, f.ip(n2))
}
+2 -1
View File
@@ -42,6 +42,7 @@ func newTSWGTailscaled(t *testing.T, nat vnet.NAT) *tswgTailscaled {
// tswgTailscaledOpts are options for newTSWGTailscaledOpts.
type tswgTailscaledOpts struct {
env []vnet.TailscaledEnv // more environment for both tailscaleds
vmOpts []vmtest.EnvOption // options for vmtest.New
tunNodes int // how many nodes, from the last, to leave in TUN mode (wireguard-go)
sameLAN bool // put both nodes on one LAN, behind one NAT
}
@@ -51,7 +52,7 @@ func newTSWGTailscaledOpts(t *testing.T, nat vnet.NAT, opts tswgTailscaledOpts)
dir := tswgDir(t)
ko := buildTSWGForGokrazy(t, dir)
f := &tswgTailscaled{t: t, env: vmtest.New(t), ko: ko}
f := &tswgTailscaled{t: t, env: vmtest.New(t, opts.vmOpts...), ko: ko}
var lan *vnet.Network
if opts.sameLAN {
lan = f.env.AddNetwork("2.1.1.1", "192.168.1.1/24", nat)
+44 -5
View File
@@ -65,6 +65,7 @@ type linuxRouter struct {
closed atomic.Bool
logf func(fmt string, args ...any)
tunname string
svcTunName string // if non-empty, the device for routes to the Tailscale service IPs; see serviceTUN
netMon *netmon.Monitor
health *health.Tracker
eventClient *eventbus.Client
@@ -114,6 +115,15 @@ type linuxRouter struct {
magicsockPortV6 uint16
}
// serviceTUN is implemented by a tun.Device whose Name is a device that
// doesn't hand tailscaled the packets routed to it, such as the tswg
// kernel data plane's, and which has a second, real TUN device for the
// packets tailscaled answers itself, to the Tailscale service IPs
// (MagicDNS and so on). Routes to those go to the second device.
type serviceTUN interface {
ServiceTUNName() string
}
func newUserspaceRouter(logf logger.Logf, tunDev tun.Device, netMon *netmon.Monitor, health *health.Tracker, bus *eventbus.Bus) (router.Router, error) {
tunname, err := tunDev.Name()
if err != nil {
@@ -124,7 +134,36 @@ func newUserspaceRouter(logf logger.Logf, tunDev tun.Device, netMon *netmon.Moni
ambientCapNetAdmin: useAmbientCaps(),
}
return newUserspaceRouterAdvanced(logf, tunname, netMon, cmd, health, bus)
rt, err := newUserspaceRouterAdvanced(logf, tunname, netMon, cmd, health, bus)
if err != nil {
return nil, err
}
if st, ok := tunDev.(serviceTUN); ok {
rt.(*linuxRouter).svcTunName = st.ServiceTUNName()
}
return rt, nil
}
// routeDev returns the device for the route to cidr.
func (r *linuxRouter) routeDev(cidr netip.Prefix) string {
if r.svcTunName != "" && cidr.IsSingleIP() &&
(cidr.Addr() == tsaddr.TailscaleServiceIP() || cidr.Addr() == tsaddr.TailscaleServiceIPv6()) {
return r.svcTunName
}
return r.tunname
}
// routeLinkIndex returns the interface index of routeDev(cidr).
func (r *linuxRouter) routeLinkIndex(cidr netip.Prefix) (int, error) {
dev := r.routeDev(cidr)
if dev == r.tunname {
return r.linkIndex()
}
link, err := netlink.LinkByName(dev)
if err != nil {
return 0, fmt.Errorf("failed to look up link %q: %w", dev, err)
}
return link.Attrs().Index, nil
}
func newUserspaceRouterAdvanced(logf logger.Logf, tunname string, netMon *netmon.Monitor, cmd commandRunner, health *health.Tracker, bus *eventbus.Bus) (router.Router, error) {
@@ -1192,9 +1231,9 @@ func (r *linuxRouter) addRoute(cidr netip.Prefix) error {
return nil
}
if r.useIPCommand() {
return r.addRouteDef([]string{normalizeCIDR(cidr), "dev", r.tunname}, cidr)
return r.addRouteDef([]string{normalizeCIDR(cidr), "dev", r.routeDev(cidr)}, cidr)
}
linkIndex, err := r.linkIndex()
linkIndex, err := r.routeLinkIndex(cidr)
if err != nil {
return err
}
@@ -1269,9 +1308,9 @@ func (r *linuxRouter) delRoute(cidr netip.Prefix) error {
return nil
}
if r.useIPCommand() {
return r.delRouteDef([]string{normalizeCIDR(cidr), "dev", r.tunname}, cidr)
return r.delRouteDef([]string{normalizeCIDR(cidr), "dev", r.routeDev(cidr)}, cidr)
}
linkIndex, err := r.linkIndex()
linkIndex, err := r.routeLinkIndex(cidr)
if err != nil {
return err
}
@@ -2112,3 +2112,26 @@ func TestCleanUpOnlyTouchesTunInterface(t *testing.T) {
t.Errorf("non-Tailscale CGNAT addr on eth0 was wrongly removed; ips=%q", fake.ips)
}
}
func TestRouteDevServiceTUN(t *testing.T) {
r := &linuxRouter{tunname: "tailscale0", svcTunName: "tailscale0-svc"}
for _, tt := range []struct {
cidr string
want string
}{
{"100.100.100.100/32", "tailscale0-svc"},
{"fd7a:115c:a1e0::53/128", "tailscale0-svc"},
{"100.64.0.0/10", "tailscale0"},
{"100.100.100.0/24", "tailscale0"},
{"fd7a:115c:a1e0::/48", "tailscale0"},
{"10.0.0.0/8", "tailscale0"},
} {
if got := r.routeDev(netip.MustParsePrefix(tt.cidr)); got != tt.want {
t.Errorf("routeDev(%s) = %q, want %q", tt.cidr, got, tt.want)
}
}
r.svcTunName = ""
if got := r.routeDev(netip.MustParsePrefix("100.100.100.100/32")); got != "tailscale0" {
t.Errorf("without a service TUN, routeDev(100.100.100.100/32) = %q, want tailscale0", got)
}
}
+39 -11
View File
@@ -9,7 +9,7 @@ import (
"github.com/tailscale/netlink"
"github.com/tailscale/wireguard-go/tun"
"tailscale.com/net/tstun"
"golang.org/x/sys/unix"
)
// ErrModuleNotLoaded is returned by NewTailscaleDevice when the tswg kernel
@@ -21,13 +21,21 @@ var ErrModuleNotLoaded = errors.New("tswg: kernel module not loaded")
// any existing tswg device of that name, and sets its MTU.
//
// It returns a tun.Device for the rest of tailscaled (the engine, router
// and so on) to hold in place of a TUN device. It carries no packets; it
// only reports name as its name, so that the router configures addresses
// and routes on the tswg device.
// and so on) to hold in place of a TUN device. It reports name as its
// name, so that the router configures addresses and routes on the tswg
// device, but its packets are those of a real TUN device, named name plus
// "-svc", for the packets tailscaled answers itself: the router sends
// routes to the Tailscale service IPs (100.100.100.100 and
// fd7a:115c:a1e0::53, for MagicDNS and so on) there, and netstack answers
// them as in TUN mode. Nothing else is routed to it.
func NewTailscaleDevice(name string, mtu int) (tun.Device, error) {
if !ModuleLoaded() {
return nil, ErrModuleNotLoaded
}
svcName := name + "-svc"
if len(svcName) >= unix.IFNAMSIZ {
return nil, fmt.Errorf("tswg: device name %q too long for its service TUN %q", name, svcName)
}
if link, err := netlink.LinkByName(name); err == nil {
if link.Type() != LinkType {
return nil, fmt.Errorf("tswg: existing interface %q has type %q, not %q", name, link.Type(), LinkType)
@@ -49,17 +57,37 @@ func NewTailscaleDevice(name string, mtu int) (tun.Device, error) {
DeleteLink(name)
return nil, fmt.Errorf("tswg: setting MTU of %q: %w", name, err)
}
return &nameOnlyTUN{Device: tstun.NewFake(), name: name}, nil
svc, err := tun.CreateTUN(svcName, mtu)
if err != nil {
DeleteLink(name)
return nil, fmt.Errorf("tswg: creating service TUN %q: %w", svcName, err)
}
// The router brings up only the device it's told the name of.
svcLink, err := netlink.LinkByName(svcName)
if err == nil {
err = netlink.LinkSetUp(svcLink)
}
if err != nil {
svc.Close()
DeleteLink(name)
return nil, fmt.Errorf("tswg: bringing up service TUN %q: %w", svcName, err)
}
return &serviceTUN{Device: svc, name: name, svcName: svcName}, nil
}
// nameOnlyTUN is a fake tun.Device that reports a given name.
// serviceTUN is the tun.Device that NewTailscaleDevice returns: the real
// TUN device svcName, reporting the tswg device's name.
//
// It deliberately embeds only the tun.Device interface, so that optional
// methods of the underlying fake (such as IsFakeTun, which other code uses
// to detect userspace networking mode) aren't promoted.
type nameOnlyTUN struct {
// methods of the underlying device aren't promoted.
type serviceTUN struct {
tun.Device
name string
name string
svcName string
}
func (t *nameOnlyTUN) Name() (string, error) { return t.name, nil }
func (t *serviceTUN) Name() (string, error) { return t.name, nil }
// ServiceTUNName returns the name of the real TUN device, for the router;
// see NewTailscaleDevice.
func (t *serviceTUN) ServiceTUNName() string { return t.svcName }