diff --git a/cmd/derper/bootstrap_dns.go b/cmd/derper/bootstrap_dns.go index 9abc95df5..20f9c86aa 100644 --- a/cmd/derper/bootstrap_dns.go +++ b/cmd/derper/bootstrap_dns.go @@ -5,19 +5,17 @@ package main import ( "context" - "encoding/binary" "encoding/json" "expvar" + "fmt" "log" - "math/rand/v2" "net" "net/http" - "net/netip" - "strconv" "strings" "sync/atomic" "time" + "tailscale.com/net/dnsfallback/fallbacknames" "tailscale.com/syncs" "tailscale.com/util/mak" "tailscale.com/util/slicesx" @@ -26,24 +24,20 @@ import ( const refreshTimeout = time.Minute type dnsEntryMap struct { - IPs map[string][]net.IP - Percent map[string]float64 // "foo.com" => 0.5 for 50% + IPs map[string][]net.IP } var ( - dnsCache atomic.Pointer[dnsEntryMap] - dnsCacheBytes syncs.AtomicValue[[]byte] // of JSON - unpublishedDNSCache atomic.Pointer[dnsEntryMap] - bootstrapLookupMap syncs.Map[string, bool] + dnsCache atomic.Pointer[dnsEntryMap] + dnsCacheBytes syncs.AtomicValue[[]byte] // of JSON + bootstrapLookupMap syncs.Map[string, bool] ) var ( - bootstrapDNSRequests = expvar.NewInt("counter_bootstrap_dns_requests") - publishedDNSHits = expvar.NewInt("counter_bootstrap_dns_published_hits") - publishedDNSMisses = expvar.NewInt("counter_bootstrap_dns_published_misses") - unpublishedDNSHits = expvar.NewInt("counter_bootstrap_dns_unpublished_hits") - unpublishedDNSMisses = expvar.NewInt("counter_bootstrap_dns_unpublished_misses") - unpublishedDNSPercentMisses = expvar.NewInt("counter_bootstrap_dns_unpublished_percent_misses") + bootstrapDNSRequests = expvar.NewInt("counter_bootstrap_dns_requests") + publishedDNSHits = expvar.NewInt("counter_bootstrap_dns_published_hits") + publishedDNSMisses = expvar.NewInt("counter_bootstrap_dns_published_misses") + unknownDNSNames = expvar.NewInt("counter_bootstrap_dns_unknown_names") ) func init() { @@ -52,13 +46,36 @@ func init() { })) } +// bootstrapDNSNames returns the hostnames in the --bootstrap-dns-names flag. +func bootstrapDNSNames() []string { + if *bootstrapDNS == "" { + return nil + } + return strings.Split(*bootstrapDNS, ",") +} + +// validateBootstrapDNSNames returns an error if any of the +// --bootstrap-dns-names hostnames isn't one that clients' DERP-based +// fallback DNS will ever ask for. +// +// We're slowly removing that fallback DNS mechanism, so names can be +// removed from the flag but new kinds of names can't be added. +// See https://github.com/tailscale/tailscale/issues/21028. +func validateBootstrapDNSNames() error { + for _, name := range bootstrapDNSNames() { + if !fallbacknames.IsTailscaleHost(name) { + return fmt.Errorf("--bootstrap-dns-names entry %q is not a name clients' fallback DNS resolves (see tailscale.com/net/dnsfallback/fallbacknames)", name) + } + } + return nil +} + func refreshBootstrapDNSLoop() { - if *bootstrapDNS == "" && *unpublishedDNS == "" { + if *bootstrapDNS == "" { return } for { refreshBootstrapDNS() - refreshUnpublishedDNS() time.Sleep(10 * time.Minute) } } @@ -69,7 +86,7 @@ func refreshBootstrapDNS() { } ctx, cancel := context.WithTimeout(context.Background(), refreshTimeout) defer cancel() - dnsEntries := resolveList(ctx, *bootstrapDNS) + dnsEntries := resolveList(ctx, bootstrapDNSNames()) // Randomize the order of the IPs for each name to avoid the client biasing // to IPv6 for _, vv := range dnsEntries.IPs { @@ -85,52 +102,18 @@ func refreshBootstrapDNS() { dnsCacheBytes.Store(j) } -func refreshUnpublishedDNS() { - if *unpublishedDNS == "" { - return - } - ctx, cancel := context.WithTimeout(context.Background(), refreshTimeout) - defer cancel() - dnsEntries := resolveList(ctx, *unpublishedDNS) - unpublishedDNSCache.Store(dnsEntries) -} - -// resolveList takes a comma-separated list of DNS names to resolve. -// -// If an entry contains a slash, it's two DNS names: the first is the one to -// resolve and the second is that of a TXT recording containing the rollout -// percentage in range "0".."100". If the TXT record doesn't exist or is -// malformed, the percentage is 0. If the TXT record is not provided (there's no -// slash), then the percentage is 100. -func resolveList(ctx context.Context, list string) *dnsEntryMap { - ents := strings.Split(list, ",") - +// resolveList resolves each of names. +func resolveList(ctx context.Context, names []string) *dnsEntryMap { ret := &dnsEntryMap{} var r net.Resolver - for _, ent := range ents { - name, txtName, _ := strings.Cut(ent, "/") + for _, name := range names { addrs, err := r.LookupIP(ctx, "ip", name) if err != nil { log.Printf("bootstrap DNS lookup %q: %v", name, err) continue } mak.Set(&ret.IPs, name, addrs) - - if txtName == "" { - mak.Set(&ret.Percent, name, 1.0) - continue - } - vals, err := r.LookupTXT(ctx, txtName) - if err != nil { - log.Printf("bootstrap DNS lookup %q: %v", txtName, err) - continue - } - for _, v := range vals { - if v, err := strconv.Atoi(v); err == nil && v >= 0 && v <= 100 { - mak.Set(&ret.Percent, name, float64(v)/100) - } - } } return ret } @@ -143,77 +126,31 @@ func handleBootstrapDNS(w http.ResponseWriter, r *http.Request) { // request, so keeping a connection open is pointlessly expensive. w.Header().Set("Connection", "close") - // Try answering a query from our hidden map first + // If we have a "q" query, track whether it's a name we publish and + // whether we have IPs for it. if q := r.URL.Query().Get("q"); q != "" { bootstrapLookupMap.Store(q, true) if bootstrapLookupMap.Len() > 500 { // defensive bootstrapLookupMap.Clear() } - if m := unpublishedDNSCache.Load(); m != nil && len(m.IPs[q]) > 0 { - unpublishedDNSHits.Add(1) - - percent := m.Percent[q] - if remoteAddrMatchesPercent(r.RemoteAddr, percent) { - // Only return the specific query, not everything. - m := map[string][]net.IP{q: m.IPs[q]} - j, err := json.MarshalIndent(m, "", "\t") - if err == nil { - w.Write(j) - return - } - } else { - unpublishedDNSPercentMisses.Add(1) - } - } - - // If we have a "q" query for a name in the published cache - // list, then track whether that's a hit/miss. m := dnsCache.Load() var inPub bool var ips []net.IP if m != nil { ips, inPub = m.IPs[q] } - if inPub { - if len(ips) > 0 { - publishedDNSHits.Add(1) - } else { - publishedDNSMisses.Add(1) - } - } else { - // If it wasn't in either cache, treat this as a query - // for the unpublished cache, and thus a cache miss. - unpublishedDNSMisses.Add(1) + switch { + case !inPub: + unknownDNSNames.Add(1) + case len(ips) > 0: + publishedDNSHits.Add(1) + default: + publishedDNSMisses.Add(1) } } - // Fall back to returning the public set of cached DNS names + // Return the whole published set of cached DNS names. Clients pick + // out the one they asked for. j := dnsCacheBytes.Load() w.Write(j) } - -// percent is [0.0, 1.0]. -func remoteAddrMatchesPercent(remoteAddr string, percent float64) bool { - if percent == 0 { - return false - } - if percent == 1 { - return true - } - reqIPStr, _, err := net.SplitHostPort(remoteAddr) - if err != nil { - return false - } - reqIP, err := netip.ParseAddr(reqIPStr) - if err != nil { - return false - } - if reqIP.IsLoopback() { - // For local testing. - return rand.Float64() < 0.5 - } - reqIP16 := reqIP.As16() - rndSrc := rand.NewPCG(binary.LittleEndian.Uint64(reqIP16[:8]), binary.LittleEndian.Uint64(reqIP16[8:])) - rnd := rand.New(rndSrc) - return percent > rnd.Float64() -} diff --git a/cmd/derper/bootstrap_dns_test.go b/cmd/derper/bootstrap_dns_test.go index 2055b9751..2a9c27cc4 100644 --- a/cmd/derper/bootstrap_dns_test.go +++ b/cmd/derper/bootstrap_dns_test.go @@ -10,13 +10,11 @@ import ( "net" "net/http" "net/http/httptest" - "net/netip" "net/url" "reflect" "testing" "tailscale.com/tstest" - "tailscale.com/tstest/nettest" ) func BenchmarkHandleBootstrapDNS(b *testing.B) { @@ -79,110 +77,41 @@ func getBootstrapDNS(t *testing.T, q string) map[string][]net.IP { return m } -func TestUnpublishedDNS(t *testing.T) { - nettest.SkipIfNoNetwork(t) - - const published = "login.tailscale.com" - const unpublished = "log.tailscale.com" - - prev1, prev2 := *bootstrapDNS, *unpublishedDNS - *bootstrapDNS = published - *unpublishedDNS = unpublished - t.Cleanup(func() { - *bootstrapDNS = prev1 - *unpublishedDNS = prev2 - }) - - refreshBootstrapDNS() - refreshUnpublishedDNS() - - hasResponse := func(q string) bool { - _, found := getBootstrapDNS(t, q)[q] - return found - } - - if !hasResponse(published) { - t.Errorf("expected response for: %s", published) - } - if !hasResponse(unpublished) { - t.Errorf("expected response for: %s", unpublished) - } - - // Verify that querying for a random query or a real query does not - // leak our unpublished domain - m1 := getBootstrapDNS(t, published) - if _, found := m1[unpublished]; found { - t.Errorf("found unpublished domain %s: %+v", unpublished, m1) - } - m2 := getBootstrapDNS(t, "random.example.com") - if _, found := m2[unpublished]; found { - t.Errorf("found unpublished domain %s: %+v", unpublished, m2) - } -} - func resetMetrics(tb testing.TB) { tstest.AssertNotParallel(tb) publishedDNSHits.Set(0) publishedDNSMisses.Set(0) - unpublishedDNSHits.Set(0) - unpublishedDNSMisses.Set(0) + unknownDNSNames.Set(0) bootstrapLookupMap.Clear() } -// Verify that we don't count an empty list in the unpublishedDNSCache as a -// cache hit in our metrics. -func TestUnpublishedDNSEmptyList(t *testing.T) { +func TestBootstrapDNSMetrics(t *testing.T) { pub := &dnsEntryMap{ - IPs: map[string][]net.IP{"tailscale.com": {net.IPv4(10, 10, 10, 10)}}, + IPs: map[string][]net.IP{"controlplane.tailscale.com": {net.IPv4(1, 2, 3, 4)}}, } setDNSCache(t, pub) - unpublishedDNSCache.Store(&dnsEntryMap{ - IPs: map[string][]net.IP{ - "log.tailscale.com": {}, - "controlplane.tailscale.com": {net.IPv4(1, 2, 3, 4)}, - }, - Percent: map[string]float64{ - "log.tailscale.com": 1.0, - "controlplane.tailscale.com": 1.0, - }, - }) - - t.Run("CacheMiss", func(t *testing.T) { - // One domain in map but empty, one not in map at all - for _, q := range []string{"log.tailscale.com", "login.tailscale.com"} { - resetMetrics(t) - ips := getBootstrapDNS(t, q) - - // Expected our public map to be returned on a cache miss - if !reflect.DeepEqual(ips, pub.IPs) { - t.Errorf("got ips=%+v; want %+v", ips, pub.IPs) - } - if v := unpublishedDNSHits.Value(); v != 0 { - t.Errorf("got hits=%d; want 0", v) - } - if v := unpublishedDNSMisses.Value(); v != 1 { - t.Errorf("got misses=%d; want 1", v) - } - } - }) - - // Verify that we do get a valid response and metric. - t.Run("CacheHit", func(t *testing.T) { + for _, tt := range []struct { + q string + hits, misses, unkn int64 + }{ + {"controlplane.tailscale.com", 1, 0, 0}, + {"headscale.example.com", 0, 0, 1}, + } { resetMetrics(t) - ips := getBootstrapDNS(t, "controlplane.tailscale.com") - want := map[string][]net.IP{"controlplane.tailscale.com": {net.IPv4(1, 2, 3, 4)}} - if !reflect.DeepEqual(ips, want) { - t.Errorf("got ips=%+v; want %+v", ips, want) + if ips := getBootstrapDNS(t, tt.q); !reflect.DeepEqual(ips, pub.IPs) { + t.Errorf("q=%q: got ips=%+v; want %+v", tt.q, ips, pub.IPs) } - if v := unpublishedDNSHits.Value(); v != 1 { - t.Errorf("got hits=%d; want 1", v) + if got := publishedDNSHits.Value(); got != tt.hits { + t.Errorf("q=%q: published hits = %d; want %d", tt.q, got, tt.hits) } - if v := unpublishedDNSMisses.Value(); v != 0 { - t.Errorf("got misses=%d; want 0", v) + if got := publishedDNSMisses.Value(); got != tt.misses { + t.Errorf("q=%q: published misses = %d; want %d", tt.q, got, tt.misses) } - }) - + if got := unknownDNSNames.Value(); got != tt.unkn { + t.Errorf("q=%q: unknown names = %d; want %d", tt.q, got, tt.unkn) + } + } } func TestLookupMetric(t *testing.T) { @@ -199,53 +128,21 @@ func TestLookupMetric(t *testing.T) { } } -func TestRemoteAddrMatchesPercent(t *testing.T) { - tests := []struct { - remoteAddr string - percent float64 - want bool +func TestValidateBootstrapDNSNames(t *testing.T) { + for _, tt := range []struct { + flag string + wantErr bool }{ - // 0% and 100%. - {"10.0.0.1:1234", 0.0, false}, - {"10.0.0.1:1234", 1.0, true}, - - // Invalid IP. - {"", 1.0, true}, - {"", 0.0, false}, - {"", 0.5, false}, - - // Small manual sample at 50%. The func uses a deterministic PRNG seed. - {"1.2.3.4:567", 0.5, true}, - {"1.2.3.5:567", 0.5, true}, - {"1.2.3.6:567", 0.5, false}, - {"1.2.3.7:567", 0.5, true}, - {"1.2.3.8:567", 0.5, false}, - {"1.2.3.9:567", 0.5, true}, - {"1.2.3.10:567", 0.5, true}, - } - for _, tt := range tests { - got := remoteAddrMatchesPercent(tt.remoteAddr, tt.percent) - if got != tt.want { - t.Errorf("remoteAddrMatchesPercent(%q, %v) = %v; want %v", tt.remoteAddr, tt.percent, got, tt.want) + {"", false}, + {"log.tailscale.io,log.tailscale.com,login.tailscale.com,controlplane.tailscale.com,login.us.tailscale.com", false}, + {"controlplane.tailscale.com,headscale.example.com", true}, + {"log.tailscale.com/log-percent.tailscale.com", true}, + {"controlplane.tailscale.com,", true}, + } { + tstest.Replace(t, bootstrapDNS, tt.flag) + err := validateBootstrapDNSNames() + if (err != nil) != tt.wantErr { + t.Errorf("validateBootstrapDNSNames with %q = %v; want error: %v", tt.flag, err, tt.wantErr) } } - - var match, all int - const wantPercent = 0.5 - for a := range 256 { - for b := range 256 { - all++ - if remoteAddrMatchesPercent( - netip.AddrPortFrom(netip.AddrFrom4([4]byte{1, 2, byte(a), byte(b)}), 12345).String(), - wantPercent) { - match++ - } - } - } - gotPercent := float64(match) / float64(all) - const tolerance = 0.005 - t.Logf("got percent %v (goal %v)", gotPercent, wantPercent) - if gotPercent < wantPercent-tolerance || gotPercent > wantPercent+tolerance { - t.Errorf("got %v; want %v ± %v", gotPercent, wantPercent, tolerance) - } } diff --git a/cmd/derper/depaware.txt b/cmd/derper/depaware.txt index b6917f417..3ecaf4153 100644 --- a/cmd/derper/depaware.txt +++ b/cmd/derper/depaware.txt @@ -100,6 +100,7 @@ tailscale.com/cmd/derper dependencies: (generated by github.com/tailscale/depawa tailscale.com/net/bakedroots from tailscale.com/net/tlsdial+ tailscale.com/net/connectproxy from tailscale.com/cmd/derper tailscale.com/net/dnscache from tailscale.com/derp/derphttp + tailscale.com/net/dnsfallback/fallbacknames from tailscale.com/cmd/derper tailscale.com/net/ktimeout from tailscale.com/cmd/derper tailscale.com/net/netaddr from tailscale.com/ipn+ tailscale.com/net/netknob from tailscale.com/net/netns diff --git a/cmd/derper/derper.go b/cmd/derper/derper.go index 3bdb8666b..25a1ee8f7 100644 --- a/cmd/derper/derper.go +++ b/cmd/derper/derper.go @@ -77,8 +77,7 @@ var ( secretsURL = flag.String("secrets-url", "", "SETEC server URL for secrets retrieval of mesh key") secretPrefix = flag.String("secrets-path-prefix", "prod/derp", "setec path prefix for \""+setecMeshKeyName+"\" secret for DERP mesh key") secretsCacheDir = flag.String("secrets-cache-dir", defaultSetecCacheDir(), "directory to cache setec secrets in (required if --secrets-url is set)") - bootstrapDNS = flag.String("bootstrap-dns-names", "", "optional comma-separated list of hostnames to make available at /bootstrap-dns") - unpublishedDNS = flag.String("unpublished-bootstrap-dns-names", "", "optional comma-separated list of hostnames to make available at /bootstrap-dns and not publish in the list. If an entry contains a slash, the second part names a DNS record to poll for its TXT record with a `0` to `100` value for rollout percentage.") + bootstrapDNS = flag.String("bootstrap-dns-names", "", "optional comma-separated list of hostnames to make available at /bootstrap-dns for Tailscale clients' fallback DNS; each must be one of Tailscale's own hostnames, which are the only ones clients ask for (see https://github.com/tailscale/tailscale/issues/21028)") verifyClients = flag.Bool("verify-clients", false, "verify clients to this DERP server through a local tailscaled instance.") verifyClientURL = flag.String("verify-client-url", "", "if non-empty, an admission controller URL for permitting client connections; see tailcfg.DERPAdmitClientRequest") @@ -173,6 +172,9 @@ func main() { fmt.Println(version.Long()) return } + if err := validateBootstrapDNSNames(); err != nil { + log.Fatal(err) + } ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer cancel()