From ccd97ee8c10022c6ba26813c8d6373f337000c6a Mon Sep 17 00:00:00 2001 From: Nick Khyl Date: Thu, 15 Oct 2026 15:44:47 +0000 Subject: [PATCH] wip: primary dns --- control/controlknobs/controlknobs.go | 8 ++ ipn/ipnlocal/dnsconfig_test.go | 107 ++++++++++++++++++++- ipn/ipnlocal/local.go | 2 +- ipn/ipnlocal/local_test.go | 2 +- ipn/ipnlocal/node_backend.go | 58 ++++++++++- ipn/ipnlocal/primary_dns_suffix.go | 12 +++ ipn/ipnlocal/primary_dns_suffix_windows.go | 13 +++ net/dns/manager_windows.go | 8 +- tailcfg/tailcfg.go | 11 ++- util/winutil/winenv/winenv_windows.go | 16 +++ 10 files changed, 229 insertions(+), 8 deletions(-) create mode 100644 ipn/ipnlocal/primary_dns_suffix.go create mode 100644 ipn/ipnlocal/primary_dns_suffix_windows.go diff --git a/control/controlknobs/controlknobs.go b/control/controlknobs/controlknobs.go index bde36df0d..9621c7d45 100644 --- a/control/controlknobs/controlknobs.go +++ b/control/controlknobs/controlknobs.go @@ -148,6 +148,12 @@ type Knobs struct { // quad-100 as primary. Off by default; has no effect on other platforms. // See tailscale/corp#45534 and tailscale/corp#48693. ScopeQuad100OnMacOS atomic.Bool + + // UseQuad100ForPrimaryDNSSuffix indicates that the node should add peer + // DNS entries under the device's primary DNS suffix so MagicDNS (quad-100) + // can resolve them directly, avoiding hosts file writes on domain-joined + // Windows devices. + UseQuad100ForPrimaryDNSSuffix atomic.Bool } // UpdateFromNodeAttributes updates k (if non-nil) based on the provided self @@ -185,6 +191,7 @@ func (k *Knobs) UpdateFromNodeAttributes(capMap tailcfg.NodeCapMap) { neverGSOEqualTail = has(nodecap.NeverGSOEqualTail) cacheNetworkMaps = has(nodecap.CacheNetworkMaps) scopeQuad100OnMacOS = has(nodecap.ScopeQuad100OnMacOS) + useQuad100ForPrimaryDNSSuffix = has(tailcfg.NodeAttrUseQuad100ForPrimaryDNSSuffix) ) if has(nodecap.OneCGNATEnable) { @@ -220,6 +227,7 @@ func (k *Knobs) UpdateFromNodeAttributes(capMap tailcfg.NodeCapMap) { k.NeverGSOEqualTail.Store(neverGSOEqualTail) k.CacheNetworkMaps.Store(cacheNetworkMaps) k.ScopeQuad100OnMacOS.Store(scopeQuad100OnMacOS) + k.UseQuad100ForPrimaryDNSSuffix.Store(useQuad100ForPrimaryDNSSuffix) } // AsDebugJSON returns k as something that can be marshalled with json.Marshal diff --git a/ipn/ipnlocal/dnsconfig_test.go b/ipn/ipnlocal/dnsconfig_test.go index 71b316f0b..1ef1279a9 100644 --- a/ipn/ipnlocal/dnsconfig_test.go +++ b/ipn/ipnlocal/dnsconfig_test.go @@ -537,7 +537,7 @@ func TestDNSConfigForNetmap(t *testing.T) { t.Run(tt.name, func(t *testing.T) { goos := cmp.Or(tt.os, "linux") var log tstest.MemLogger - got := dnsConfigForNetmap(tt.nm, peersMap(tt.peers), tt.prefs.View(), tt.expired, log.Logf, goos, tt.extraRoutes) + got := dnsConfigForNetmap(tt.nm, peersMap(tt.peers), tt.prefs.View(), tt.expired, log.Logf, goos, tt.extraRoutes, "") if !reflect.DeepEqual(got, tt.want) { gotj, _ := json.MarshalIndent(got, "", "\t") wantj, _ := json.MarshalIndent(tt.want, "", "\t") @@ -561,6 +561,111 @@ func peersMap(s []tailcfg.NodeView) map[tailcfg.NodeID]tailcfg.NodeView { return m } +func TestDNSConfigPrimaryDNSSuffix(t *testing.T) { + nm := &netmap.NetworkMap{ + SelfNode: (&tailcfg.Node{ + Name: "mynode.tail1234.ts.net.", + Addresses: ipps("100.101.101.101"), + }).View(), + DNS: tailcfg.DNSConfig{ + Proxied: true, + Domains: []string{"tail1234.ts.net"}, + Resolvers: []*dnstype.Resolver{{Addr: "8.8.8.8"}}, + }, + } + peers := nodeViews([]*tailcfg.Node{ + { + ID: 1, + Name: "peer1.tail1234.ts.net.", + Addresses: ipps("100.102.102.102"), + }, + { + ID: 2, + Name: "peer2.tail1234.ts.net.", + Addresses: ipps("100.103.103.103"), + }, + }) + prefs := &ipn.Prefs{CorpDNS: true} + + tests := []struct { + name string + primarySuffix string + splitDNS map[string][]*dnstype.Resolver + wantHosts map[dnsname.FQDN][]netip.Addr + wantRoute bool + }{ + { + name: "empty suffix is no-op", + primarySuffix: "", + wantHosts: map[dnsname.FQDN][]netip.Addr{ + "mynode.tail1234.ts.net.": {netip.MustParseAddr("100.101.101.101")}, + "peer1.tail1234.ts.net.": {netip.MustParseAddr("100.102.102.102")}, + "peer2.tail1234.ts.net.": {netip.MustParseAddr("100.103.103.103")}, + }, + }, + { + name: "adds aliases under primary suffix", + primarySuffix: "corp.example.com", + wantHosts: map[dnsname.FQDN][]netip.Addr{ + "mynode.tail1234.ts.net.": {netip.MustParseAddr("100.101.101.101")}, + "peer1.tail1234.ts.net.": {netip.MustParseAddr("100.102.102.102")}, + "peer2.tail1234.ts.net.": {netip.MustParseAddr("100.103.103.103")}, + "mynode.corp.example.com.": {netip.MustParseAddr("100.101.101.101")}, + "peer1.corp.example.com.": {netip.MustParseAddr("100.102.102.102")}, + "peer2.corp.example.com.": {netip.MustParseAddr("100.103.103.103")}, + }, + wantRoute: true, + }, + { + name: "existing splitDNS route not overwritten", + primarySuffix: "corp.example.com", + splitDNS: map[string][]*dnstype.Resolver{ + "corp.example.com": {{Addr: "10.0.0.1"}}, + }, + wantHosts: map[dnsname.FQDN][]netip.Addr{ + "mynode.tail1234.ts.net.": {netip.MustParseAddr("100.101.101.101")}, + "peer1.tail1234.ts.net.": {netip.MustParseAddr("100.102.102.102")}, + "peer2.tail1234.ts.net.": {netip.MustParseAddr("100.103.103.103")}, + "mynode.corp.example.com.": {netip.MustParseAddr("100.101.101.101")}, + "peer1.corp.example.com.": {netip.MustParseAddr("100.102.102.102")}, + "peer2.corp.example.com.": {netip.MustParseAddr("100.103.103.103")}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + nmCopy := *nm + if tt.splitDNS != nil { + nmCopy.DNS.Routes = tt.splitDNS + } + var log tstest.MemLogger + got := dnsConfigForNetmap(&nmCopy, peersMap(peers), prefs.View(), false, log.Logf, "windows", nil, tt.primarySuffix) + + if !reflect.DeepEqual(got.Hosts, tt.wantHosts) { + gotj, _ := json.MarshalIndent(got.Hosts, "", "\t") + wantj, _ := json.MarshalIndent(tt.wantHosts, "", "\t") + t.Errorf("Hosts wrong\n got: %s\n\nwant: %s\n", gotj, wantj) + } + + psFQDN := dnsname.FQDN("corp.example.com.") + route, hasRoute := got.Routes[psFQDN] + if tt.wantRoute { + if !hasRoute { + t.Error("expected route for primary DNS suffix, got none") + } else if route == nil { + t.Error("route for primary suffix should have resolvers (not nil/authoritative)") + } + } + if tt.splitDNS != nil && hasRoute { + // Verify existing splitDNS route was preserved. + if len(route) != 1 || route[0].Addr != "10.0.0.1" { + t.Errorf("splitDNS route was overwritten: got %v", route) + } + } + }) + } +} + func TestAllowExitNodeDNSProxyToServeName(t *testing.T) { b := newTestLocalBackend(t) if b.allowExitNodeDNSProxyToServeName("google.com") { diff --git a/ipn/ipnlocal/local.go b/ipn/ipnlocal/local.go index 816c02327..88461701d 100644 --- a/ipn/ipnlocal/local.go +++ b/ipn/ipnlocal/local.go @@ -6138,7 +6138,7 @@ func (b *LocalBackend) authReconfigLocked() { if f, ok := b.extHost.hooks.ExtraDNSRoutes.GetOk(); ok { extraDNSRoutes = f() } - dcfg := cn.dnsConfigForNetmap(prefs, b.keyExpired, cmp.Or(b.goos, runtime.GOOS), extraDNSRoutes) + dcfg := cn.dnsConfigForNetmap(prefs, b.keyExpired, cmp.Or(b.goos, runtime.GOOS), extraDNSRoutes, b.ControlKnobs()) // If the current node is an app connector, ensure the app connector machine is started b.reconfigAppConnectorLocked(nm.SelfNode, prefs) diff --git a/ipn/ipnlocal/local_test.go b/ipn/ipnlocal/local_test.go index 7986cb150..4e452cdd0 100644 --- a/ipn/ipnlocal/local_test.go +++ b/ipn/ipnlocal/local_test.go @@ -3498,7 +3498,7 @@ func TestDNSConfigForNetmapForExitNodeConfigs(t *testing.T) { } prefs := &ipn.Prefs{ExitNodeID: tc.exitNode, CorpDNS: true} - got := dnsConfigForNetmap(nm, peersMap(tc.peers), prefs.View(), false, t.Logf, "", nil) + got := dnsConfigForNetmap(nm, peersMap(tc.peers), prefs.View(), false, t.Logf, "", nil, "") if !resolversEqual(t, got.DefaultResolvers, tc.wantDefaultResolvers) { t.Errorf("DefaultResolvers: got %#v, want %#v", got.DefaultResolvers, tc.wantDefaultResolvers) } diff --git a/ipn/ipnlocal/node_backend.go b/ipn/ipnlocal/node_backend.go index a9e7baaa2..6eedece00 100644 --- a/ipn/ipnlocal/node_backend.go +++ b/ipn/ipnlocal/node_backend.go @@ -15,6 +15,7 @@ import ( "sync/atomic" "go4.org/netipx" + "tailscale.com/control/controlknobs" "tailscale.com/feature/buildfeatures" "tailscale.com/ipn" "tailscale.com/net/dns" @@ -1183,10 +1184,14 @@ func (nb *nodeBackend) setFilter(f *filter.Filter) { nb.filterAtomic.Store(f) } -func (nb *nodeBackend) dnsConfigForNetmap(prefs ipn.PrefsView, selfExpired bool, goos string, extraRoutes map[string][]*dnstype.Resolver) *dns.Config { +func (nb *nodeBackend) dnsConfigForNetmap(prefs ipn.PrefsView, selfExpired bool, goos string, extraRoutes map[string][]*dnstype.Resolver, knobs *controlknobs.Knobs) *dns.Config { nb.mu.Lock() defer nb.mu.Unlock() - return dnsConfigForNetmap(nb.netMap, nb.peers, prefs, selfExpired, nb.logf, goos, extraRoutes) + var suffix string + if knobs != nil && knobs.UseQuad100ForPrimaryDNSSuffix.Load() { + suffix = primaryDNSSuffix() + } + return dnsConfigForNetmap(nb.netMap, nb.peers, prefs, selfExpired, nb.logf, goos, extraRoutes, suffix) } // magicDNSHostAddrs returns the MagicDNS A/AAAA answer for fqdn from @@ -1435,7 +1440,10 @@ func useWithExitNodeRoutes(routes map[string][]*dnstype.Resolver) map[string][]* // [ipnext.Hooks.ExtraDNSRoutes]. They are added alongside nm's own DNS // routes and get the same treatment, including the UseWithExitNode // filtering when an exit node proxies DNS. -func dnsConfigForNetmap(nm *netmap.NetworkMap, peers map[tailcfg.NodeID]tailcfg.NodeView, prefs ipn.PrefsView, selfExpired bool, logf logger.Logf, goos string, extraRoutes map[string][]*dnstype.Resolver) *dns.Config { +// +// primarySuffix, if non-empty, causes peer host entries to be added +// under that DNS suffix so MagicDNS can resolve them directly. +func dnsConfigForNetmap(nm *netmap.NetworkMap, peers map[tailcfg.NodeID]tailcfg.NodeView, prefs ipn.PrefsView, selfExpired bool, logf logger.Logf, goos string, extraRoutes map[string][]*dnstype.Resolver, primarySuffix string) *dns.Config { if nm == nil { return nil } @@ -1644,6 +1652,50 @@ func dnsConfigForNetmap(nm *netmap.NetworkMap, peers map[tailcfg.NodeID]tailcfg. addSplitDNSRoutes(extraRoutes) coverExtraRecords() + // If a primary DNS suffix is specified (e.g., AD domain on Windows), + // add peer host entries under that suffix so MagicDNS can resolve + // queries like "host123.corp.example.com" directly from the peer list. + // This avoids writing to the OS hosts file on domain-joined Windows + // devices, which causes DNS performance problems. + if primarySuffix != "" && nm.DNS.Proxied { + psFQDN, err := dnsname.ToFQDN(primarySuffix) + if err == nil { + toAdd := map[dnsname.FQDN][]netip.Addr{} + for fqdn, ips := range dcfg.Hosts { + label := dnsname.FirstLabel(string(fqdn)) + if label == "" { + continue + } + aliasFQDN, err := dnsname.ToFQDN(label + "." + primarySuffix) + if err != nil || aliasFQDN == fqdn { + continue + } + if _, exists := dcfg.Hosts[aliasFQDN]; !exists { + toAdd[aliasFQDN] = ips + } + } + for fqdn, ips := range toAdd { + dcfg.Hosts[fqdn] = ips + } + + // Ensure the primary DNS suffix is routed through MagicDNS + // so it becomes a MatchDomain on Windows (NRPT rule). Use + // resolvers from the route if already configured (splitDNS), + // otherwise fall back to default or fallback resolvers. + // Do NOT use nil (that would make it a localDomain, returning + // NXDOMAIN for non-peer names and breaking corporate DNS). + if _, hasRoute := dcfg.Routes[psFQDN]; !hasRoute { + resolvers := dcfg.DefaultResolvers + if len(resolvers) == 0 { + resolvers = nm.DNS.FallbackResolvers + } + if len(resolvers) > 0 { + dcfg.Routes[psFQDN] = slices.Clone(resolvers) + } + } + } + } + // Set FallbackResolvers as the default resolvers in the // scenarios that can't handle a purely split-DNS config. See // https://github.com/tailscale/tailscale/issues/1743 for diff --git a/ipn/ipnlocal/primary_dns_suffix.go b/ipn/ipnlocal/primary_dns_suffix.go new file mode 100644 index 000000000..fa672c649 --- /dev/null +++ b/ipn/ipnlocal/primary_dns_suffix.go @@ -0,0 +1,12 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build !windows + +package ipnlocal + +// primaryDNSSuffix returns the device's primary DNS suffix. +// On non-Windows platforms, this is not applicable and returns an empty string. +func primaryDNSSuffix() string { + return "" +} diff --git a/ipn/ipnlocal/primary_dns_suffix_windows.go b/ipn/ipnlocal/primary_dns_suffix_windows.go new file mode 100644 index 000000000..38e6ec06d --- /dev/null +++ b/ipn/ipnlocal/primary_dns_suffix_windows.go @@ -0,0 +1,13 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package ipnlocal + +import "tailscale.com/util/winutil/winenv" + +// primaryDNSSuffix returns the device's primary DNS suffix, which on +// domain-joined Windows devices is the AD domain name (e.g., "corp.example.com"). +// Returns an empty string if the device is not domain-joined or on error. +func primaryDNSSuffix() string { + return winenv.DomainName() +} diff --git a/net/dns/manager_windows.go b/net/dns/manager_windows.go index 91196451b..89b098c90 100644 --- a/net/dns/manager_windows.go +++ b/net/dns/manager_windows.go @@ -404,6 +404,10 @@ func (m *windowsManager) disableHostsFileUpdates() bool { return disableHostsFileUpdatesLocal() || (m.knobs != nil && m.knobs.DisableHostsFileUpdates.Load()) } +func (m *windowsManager) useQuad100ForPrimaryDNSSuffix() bool { + return m.knobs != nil && m.knobs.UseQuad100ForPrimaryDNSSuffix.Load() +} + func (m *windowsManager) SetDNS(cfg OSConfig) error { // We can configure Windows DNS in one of two ways: // @@ -450,11 +454,13 @@ func (m *windowsManager) SetDNS(cfg OSConfig) error { return err } var hosts []*HostEntry - if !m.disableHostsFileUpdates() && winenv.IsDomainJoined() { + if !m.disableHostsFileUpdates() && !m.useQuad100ForPrimaryDNSSuffix() && winenv.IsDomainJoined() { // On domain-joined Windows devices the primary search domain (the one the device is joined to) // always takes precedence over other search domains. This breaks MagicDNS when we are the primary // resolver on the device (see #18712). To work around this Windows behavior, we should write MagicDNS // host names the hosts file just as we do when we're not the primary resolver. + // When UseQuad100ForPrimaryDNSSuffix is enabled, MagicDNS resolves peers + // under the primary suffix directly, so hosts file writes are unnecessary. hosts = cfg.Hosts } if err := m.setHosts(hosts); err != nil { diff --git a/tailcfg/tailcfg.go b/tailcfg/tailcfg.go index da8a53d35..81b8e4095 100644 --- a/tailcfg/tailcfg.go +++ b/tailcfg/tailcfg.go @@ -198,7 +198,8 @@ type CapabilityVersion int // - 147: 2026-09-09: Client handles 429/503 responses with retry-after headers to /machine/ endpoints // - 148: 2026-09-15: Client understands [Node.StableTailnetID] // - 149: 2026-10-07: Sentinel version to request the server send back [NodeAttrCacheNetworkMaps] set to enabled -const CurrentCapabilityVersion CapabilityVersion = 149 +// - 150: 2026-10-15: Client understands [NodeAttrUseQuad100ForPrimaryDNSSuffix] +const CurrentCapabilityVersion CapabilityVersion = 150 // ID is an integer ID for a user, node, or login allocated by the // control plane. @@ -2581,6 +2582,14 @@ const ( // Deprecated: Do not add any further values here, use [nodecap] instead. NodeAttrPrefixServices = nodecap.ServicesPrefix + + // NodeAttrUseQuad100ForPrimaryDNSSuffix makes the client add MagicDNS + // host entries for peers under the device's primary DNS suffix (the AD + // domain on Windows), so that MagicDNS (quad-100) can resolve peer names + // directly without hosts file entries. This avoids the DNS performance + // problems caused by large hosts files on domain-joined Windows devices. + NodeAttrUseQuad100ForPrimaryDNSSuffix NodeCapability = "use-quad100-for-primary-dns-suffix" + // Deprecated: Do not add any further values here, use [nodecap] instead. ) diff --git a/util/winutil/winenv/winenv_windows.go b/util/winutil/winenv/winenv_windows.go index eb7e87ced..e477473f3 100644 --- a/util/winutil/winenv/winenv_windows.go +++ b/util/winutil/winenv/winenv_windows.go @@ -76,6 +76,22 @@ func IsDomainJoined() bool { return status == windows.NetSetupDomainName } +// DomainName returns the AD domain name if the device is domain-joined, +// or an empty string otherwise. This corresponds to the "primary DNS suffix" +// shown by ipconfig /all on Windows. +func DomainName() string { + var domain *uint16 + var status uint32 + if err := windows.NetGetJoinInformation(nil, &domain, &status); err != nil { + return "" + } + defer windows.NetApiBufferFree((*byte)(unsafe.Pointer(domain))) + if status != windows.NetSetupDomainName { + return "" + } + return windows.UTF16PtrToString(domain) +} + // IsMDMRegistered reports whether the device is MDM-registered. func IsMDMRegistered() bool { const S_OK int32 = 0