diff --git a/cmd/tailscaled/depaware.txt b/cmd/tailscaled/depaware.txt index ce36bb3f1..750cae486 100644 --- a/cmd/tailscaled/depaware.txt +++ b/cmd/tailscaled/depaware.txt @@ -292,6 +292,7 @@ tailscale.com/cmd/tailscaled dependencies: (generated by github.com/tailscale/de tailscale.com/feature from tailscale.com/feature/wakeonlan+ tailscale.com/feature/ace from tailscale.com/feature/condregister tailscale.com/feature/acme from tailscale.com/feature/condregister + L tailscale.com/feature/androiddns from tailscale.com/feature/condregister tailscale.com/feature/appconnectors from tailscale.com/feature/condregister LD tailscale.com/feature/bird from tailscale.com/feature/condregister tailscale.com/feature/buildfeatures from tailscale.com/wgengine/magicsock+ diff --git a/feature/androiddns/androiddns.go b/feature/androiddns/androiddns.go new file mode 100644 index 000000000..38ea07493 --- /dev/null +++ b/feature/androiddns/androiddns.go @@ -0,0 +1,171 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build linux + +// Package androiddns resolves DNS names on Android by speaking the +// dnsproxyd protocol to the system DNS resolver daemon over its unix +// socket, the same mechanism bionic libc's getaddrinfo uses. +// +// It exists for pure Go (non-cgo) binaries built for Android, such as +// CLI tools run under Termux. Android has no /etc/resolv.conf, so +// Go's built-in resolver has no nameservers and every lookup fails. +// Binaries built with cgo don't have this problem: Go's net package +// forces the cgo resolver on Android (golang/go#10714), which calls +// bionic's getaddrinfo, which consults the same daemon this package +// talks to directly. Queries through dnsproxyd get the system's +// per-network DNS configuration and Private DNS (DNS over TLS/HTTPS) +// handling for free. +// +// # Protocol compatibility +// +// The wire protocol is unofficial but effectively frozen, for a +// structural reason rather than a policy one. Its two halves live on +// opposite sides of Android's update split. The client side (bionic's +// getaddrinfo proxy and libnetd_client) ships in the OS system image +// and updates only with a full OS update, which for most devices +// means rarely and eventually never. The server side has been the +// DnsResolver mainline (APEX) module since Android 10, updated via +// Google Play across all supported OS releases at once. A single +// current module binary must therefore keep serving the frozen libc +// clients of every supported Android version simultaneously, so +// existing commands cannot change semantics, much like a kernel +// syscall ABI with the update roles inverted. On the wire this +// package is indistinguishable from an Android 10 era bionic client, +// which cannot be broken without breaking DNS on real devices. +// +// The daemon, its socket, and the getaddrinfo-level commands date to +// 2010 (Android Gingerbread); see system/netd commit 007e987fee and +// bionic commit a1dbf0b453. The raw-packet resnsend command used here +// was added in November 2018 (system/netd commit c0c818f448) to back +// the android_res_nsend NDK API introduced in Android 10 (API 29), +// which is thus the minimum OS version this package can work on. For +// the current protocol definition, see ResNSendCommand in +// packages/modules/DnsResolver/DnsProxyListener.cpp and +// resNetworkSend in system/netd/client/NetdClient.cpp. +// +// Connecting to the socket requires membership in the AID_INET group, +// which app UIDs (including Termux) hold via the INTERNET permission, +// and SELinux policy grants app domains connect (but not stat) access +// to the socket, since every app's libc performs this exact connect. +// The plausible residual risk is not protocol change but a future +// policy tightening that distinguishes callers, so users of this +// package should treat it as best effort; the automatic installation +// into net.DefaultResolver (see auto.go) probes the socket with a +// connect first and leaves the resolver alone on failure. +// +// # Scope and gating +// +// The package also builds on GOOS=linux, not just GOOS=android, +// because static linux binaries run fine under Android kernels +// (Termux users and rooted devices commonly run our official static +// linux/arm64 builds) and have the same broken resolver there. Those +// builds detect Android at runtime before installing anything: no +// /etc/resolv.conf, the presence of /dev/__properties__ (the bionic +// property service's backing store, present since Android 5.0 and +// never on regular Linux), and a successful dnsproxyd connect. +// +// This is an optional feature, included by default in tailscaled +// builds on Linux and Android; build with the ts_omit_androiddns tag +// to omit it. It is not linked into tsnet by default; tsnet apps and +// other programs opt in with a blank import of this package. +package androiddns + +import ( + "context" + "encoding/base64" + "encoding/binary" + "fmt" + "io" + "net" + "syscall" + "time" +) + +// socketPath is the dnsproxyd unix socket path. It's a variable only +// so tests can point it at a fake server. +var socketPath = "/dev/socket/dnsproxyd" + +// maxCmdSize is FrameworkListener's CMD_BUF_SIZE in AOSP: the entire +// command, including the trailing NUL, must arrive in a single read +// of at most this many bytes. +const maxCmdSize = 1024 + +// maxAnswerSize is the maximum answer length we accept from the +// daemon. The daemon's own limit (MAXPACKET) is 8 KiB; we allow more +// in case it ever grows. +const maxAnswerSize = 64 << 10 + +// Query sends the wire-format DNS query msg to the system resolver +// daemon and returns the wire-format answer. The answer's ID matches +// the query's ID. An unsuccessful rcode (such as NXDOMAIN) is not an +// error; it's returned in the answer's header for the caller to +// interpret. +// +// The query is resolved on the default network with the system's +// usual policy for the calling UID, as if the process had called +// bionic's getaddrinfo. +func Query(ctx context.Context, msg []byte) ([]byte, error) { + // The command is "resnsend \x00". + // netId 0 is NETID_UNSET, meaning the caller's default network. + cmd := "resnsend 0 0 " + base64.StdEncoding.EncodeToString(msg) + "\x00" + if len(cmd) > maxCmdSize { + return nil, fmt.Errorf("androiddns: %d byte query too large for dnsproxyd command buffer", len(msg)) + } + + var d net.Dialer + c, err := d.DialContext(ctx, "unix", socketPath) + if err != nil { + return nil, fmt.Errorf("androiddns: %w", err) + } + defer c.Close() + stop := context.AfterFunc(ctx, func() { c.Close() }) + defer stop() + if deadline, ok := ctx.Deadline(); ok { + c.SetDeadline(deadline) + } + + // FrameworkListener does a single read and requires the NUL to be + // in it, so the command must go out in one write. + if _, err := c.Write([]byte(cmd)); err != nil { + return nil, fmt.Errorf("androiddns: %w", err) + } + if uc, ok := c.(*net.UnixConn); ok { + uc.CloseWrite() + } + + // The reply is a big-endian int32 that's either a negative errno + // or the rcode, followed on success by a big-endian int32 answer + // length and the raw answer. + var buf [4]byte + if _, err := io.ReadFull(c, buf[:]); err != nil { + return nil, fmt.Errorf("androiddns: reading result: %w", err) + } + if res := int32(binary.BigEndian.Uint32(buf[:])); res < 0 { + return nil, fmt.Errorf("androiddns: dnsproxyd error %d (%v)", res, syscall.Errno(-res)) + } + if _, err := io.ReadFull(c, buf[:]); err != nil { + return nil, fmt.Errorf("androiddns: reading answer length: %w", err) + } + ansLen := int32(binary.BigEndian.Uint32(buf[:])) + if ansLen < 0 || ansLen > maxAnswerSize { + return nil, fmt.Errorf("androiddns: bogus answer length %d", ansLen) + } + ans := make([]byte, ansLen) + if _, err := io.ReadFull(c, ans); err != nil { + return nil, fmt.Errorf("androiddns: reading answer: %w", err) + } + return ans, nil +} + +// available reports whether the dnsproxyd socket exists and accepts +// connections. It's a connect test rather than a stat because SELinux +// grants app domains connect access to the socket without getattr. +func available() bool { + c, err := net.DialTimeout("unix", socketPath, 5*time.Second) + if err != nil { + return false + } + c.Close() + return true +} diff --git a/feature/androiddns/androiddns_test.go b/feature/androiddns/androiddns_test.go new file mode 100644 index 000000000..33567320a --- /dev/null +++ b/feature/androiddns/androiddns_test.go @@ -0,0 +1,227 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build linux + +package androiddns + +import ( + "context" + "encoding/base64" + "encoding/binary" + "net" + "net/netip" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "golang.org/x/net/dns/dnsmessage" + "tailscale.com/tstest" +) + +// startFakeDaemon starts a fake dnsproxyd on a unix socket and points +// the package at it. For each connection it parses the resnsend +// command, decodes the query, and replies with what answer returns. +// If answer returns a negative value, that value is sent as the +// initial big-endian result (the daemon's -errno case). +func startFakeDaemon(t *testing.T, answer func(query []byte) (ans []byte, errno int32)) { + t.Helper() + sock := filepath.Join(t.TempDir(), "dnsproxyd") + ln, err := net.Listen("unix", sock) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + tstest.Replace(t, &socketPath, sock) + + go func() { + for { + c, err := ln.Accept() + if err != nil { + return + } + go func() { + defer c.Close() + buf := make([]byte, maxCmdSize) + n, err := c.Read(buf) + if err != nil { + return + } + cmd := string(buf[:n]) + nul := strings.IndexByte(cmd, 0) + if nul < 0 { + t.Error("command not NUL terminated in a single read") + return + } + f := strings.Fields(cmd[:nul]) + if len(f) != 4 || f[0] != "resnsend" { + t.Errorf("bad command %q", cmd[:nul]) + return + } + query, err := base64.StdEncoding.DecodeString(f[3]) + if err != nil { + t.Errorf("bad base64 %q: %v", f[3], err) + return + } + ans, errno := answer(query) + var be [4]byte + if errno < 0 { + binary.BigEndian.PutUint32(be[:], uint32(errno)) + c.Write(be[:]) + return + } + binary.BigEndian.PutUint32(be[:], 0) // rcode + c.Write(be[:]) + binary.BigEndian.PutUint32(be[:], uint32(len(ans))) + c.Write(be[:]) + c.Write(ans) + }() + } + }() +} + +// dnsAnswer builds a wire-format answer to the single-question query, +// answering A questions with 1.2.3.4 and AAAA questions with ::6. +func dnsAnswer(t *testing.T, query []byte) []byte { + var p dnsmessage.Parser + hdr, err := p.Start(query) + if err != nil { + t.Errorf("parsing query: %v", err) + return nil + } + q, err := p.Question() + if err != nil { + t.Errorf("reading question: %v", err) + return nil + } + b := dnsmessage.NewBuilder(nil, dnsmessage.Header{ + ID: hdr.ID, + Response: true, + Authoritative: true, + }) + b.EnableCompression() + b.StartQuestions() + b.Question(q) + b.StartAnswers() + rh := dnsmessage.ResourceHeader{Name: q.Name, Class: q.Class, TTL: 60} + switch q.Type { + case dnsmessage.TypeA: + rh.Type = dnsmessage.TypeA + b.AResource(rh, dnsmessage.AResource{A: [4]byte{1, 2, 3, 4}}) + case dnsmessage.TypeAAAA: + rh.Type = dnsmessage.TypeAAAA + b.AAAAResource(rh, dnsmessage.AAAAResource{AAAA: [16]byte{15: 6}}) + } + ans, err := b.Finish() + if err != nil { + t.Errorf("building answer: %v", err) + return nil + } + return ans +} + +func makeQuery(t *testing.T, name string, qtype dnsmessage.Type) []byte { + b := dnsmessage.NewBuilder(nil, dnsmessage.Header{ID: 0x1234, RecursionDesired: true}) + b.StartQuestions() + if err := b.Question(dnsmessage.Question{ + Name: dnsmessage.MustNewName(name), + Type: qtype, + Class: dnsmessage.ClassINET, + }); err != nil { + t.Fatal(err) + } + msg, err := b.Finish() + if err != nil { + t.Fatal(err) + } + return msg +} + +func TestQuery(t *testing.T) { + startFakeDaemon(t, func(query []byte) ([]byte, int32) { + return dnsAnswer(t, query), 0 + }) + query := makeQuery(t, "example.com.", dnsmessage.TypeA) + ans, err := Query(context.Background(), query) + if err != nil { + t.Fatal(err) + } + var p dnsmessage.Parser + hdr, err := p.Start(ans) + if err != nil { + t.Fatal(err) + } + if hdr.ID != 0x1234 { + t.Errorf("answer ID = %#x; want %#x", hdr.ID, 0x1234) + } + if err := p.SkipAllQuestions(); err != nil { + t.Fatal(err) + } + if _, err := p.AnswerHeader(); err != nil { + t.Fatal(err) + } + a, err := p.AResource() + if err != nil { + t.Fatal(err) + } + if got, want := netip.AddrFrom4(a.A), netip.AddrFrom4([4]byte{1, 2, 3, 4}); got != want { + t.Errorf("answer = %v; want %v", got, want) + } +} + +func TestQueryDaemonError(t *testing.T) { + startFakeDaemon(t, func(query []byte) ([]byte, int32) { + return nil, -111 // -ECONNREFUSED + }) + query := makeQuery(t, "example.com.", dnsmessage.TypeA) + _, err := Query(context.Background(), query) + if err == nil { + t.Fatal("Query succeeded; want error") + } + if !strings.Contains(err.Error(), "connection refused") { + t.Errorf("error %q does not mention connection refused", err) + } +} + +func TestQueryTooLarge(t *testing.T) { + _, err := Query(context.Background(), make([]byte, maxCmdSize)) + if err == nil || !strings.Contains(err.Error(), "too large") { + t.Fatalf("err = %v; want too-large error", err) + } +} + +func TestQueryContextCancel(t *testing.T) { + startFakeDaemon(t, func(query []byte) ([]byte, int32) { + time.Sleep(5 * time.Second) + return dnsAnswer(t, query), 0 + }) + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + query := makeQuery(t, "example.com.", dnsmessage.TypeA) + if _, err := Query(ctx, query); err == nil { + t.Fatal("Query succeeded; want timeout error") + } +} + +// TestResolver exercises the full net.Resolver integration: Go's +// built-in resolver framing queries over our conn and parsing the +// answers the fake daemon returns. +func TestResolver(t *testing.T) { + startFakeDaemon(t, func(query []byte) ([]byte, int32) { + return dnsAnswer(t, query), 0 + }) + r := NewResolver() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + addrs, err := r.LookupNetIP(ctx, "ip", "example.com.") + if err != nil { + t.Fatal(err) + } + want4 := netip.MustParseAddr("1.2.3.4") + want6 := netip.MustParseAddr("::6") + if !slices.Contains(addrs, want4) || !slices.Contains(addrs, want6) { + t.Errorf("LookupNetIP = %v; want both %v and %v", addrs, want4, want6) + } +} diff --git a/feature/androiddns/auto.go b/feature/androiddns/auto.go new file mode 100644 index 000000000..332a6a8bb --- /dev/null +++ b/feature/androiddns/auto.go @@ -0,0 +1,46 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build (linux && !android) || (android && !cgo) + +package androiddns + +import ( + "net" + "os" + "runtime" +) + +// This init runs in GOOS=android builds without cgo and in all +// GOOS=linux builds, because static linux binaries (such as our +// official arm64 release tarballs) also run under Android kernels, +// commonly via Termux or a rooted shell, and have the same broken +// resolver there. Android builds with cgo enabled, including the +// Tailscale Android app, use Go's cgo resolver, which reaches the +// same daemon via bionic's getaddrinfo and needs no help. +// +// On an actual Linux system, /etc/resolv.conf exists and this is a +// no-op after one stat. Otherwise it requires positive evidence of +// Android (see onAndroid) plus a successful connection to the +// dnsproxyd socket before touching the default resolver. +func init() { + if resolvConfExists() || !onAndroid() || !available() { + return + } + net.DefaultResolver.PreferGo = true + net.DefaultResolver.Dial = resolverDial +} + +// onAndroid reports whether the process is running on Android, even +// if it's a GOOS=linux binary running under an Android kernel. For +// that case it checks for /dev/__properties__, the bionic property +// service's backing store, which has existed on every Android version +// since 5.0, is stat-able by all processes because every app's libc +// reads properties, and is never present on regular Linux systems. +func onAndroid() bool { + if runtime.GOOS == "android" { + return true + } + _, err := os.Stat("/dev/__properties__") + return err == nil +} diff --git a/feature/androiddns/resolver.go b/feature/androiddns/resolver.go new file mode 100644 index 000000000..10ca72f97 --- /dev/null +++ b/feature/androiddns/resolver.go @@ -0,0 +1,136 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build linux + +package androiddns + +import ( + "context" + "errors" + "net" + "os" + "sync" + "time" +) + +// NewResolver returns a net.Resolver that resolves names via the +// system resolver daemon instead of Go's usual name resolution paths. +func NewResolver() *net.Resolver { + return &net.Resolver{ + PreferGo: true, + Dial: resolverDial, + } +} + +// resolverDial is a net.Resolver.Dial hook. It ignores the network +// and address that Go's resolver chose (with no resolv.conf, those +// are the useless localhost defaults) and returns a conn that +// forwards each DNS query over dnsproxyd instead. +// +// Because the returned conn is not a net.PacketConn, Go's resolver +// applies TCP framing: each message is preceded by a two byte +// big-endian length. +func resolverDial(ctx context.Context, network, address string) (net.Conn, error) { + return &streamConn{}, nil +} + +// streamConn is a net.Conn that speaks TCP-style framed DNS on one +// side and dnsproxyd on the other. Go's resolver writes one framed +// query and then reads one framed answer; the daemon round trip +// happens on the first Read after a complete query has been written. +type streamConn struct { + mu sync.Mutex + deadline time.Time + wbuf []byte // accumulated framed query bytes + rbuf []byte // framed answer bytes not yet read + closed bool +} + +var ( + errClosed = errors.New("androiddns: use of closed conn") + errNoPendingQuery = errors.New("androiddns: read with no complete query written") +) + +func (c *streamConn) Write(p []byte) (int, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return 0, errClosed + } + c.wbuf = append(c.wbuf, p...) + return len(p), nil +} + +func (c *streamConn) Read(p []byte) (int, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return 0, errClosed + } + if len(c.rbuf) == 0 { + if err := c.roundTripLocked(); err != nil { + return 0, err + } + } + n := copy(p, c.rbuf) + c.rbuf = c.rbuf[n:] + return n, nil +} + +func (c *streamConn) roundTripLocked() error { + if len(c.wbuf) < 2 { + return errNoPendingQuery + } + msgLen := int(c.wbuf[0])<<8 | int(c.wbuf[1]) + if len(c.wbuf) < 2+msgLen { + return errNoPendingQuery + } + msg := c.wbuf[2 : 2+msgLen] + + ctx := context.Background() + var cancel context.CancelFunc + if !c.deadline.IsZero() { + ctx, cancel = context.WithDeadline(ctx, c.deadline) + defer cancel() + } + ans, err := Query(ctx, msg) + if err != nil { + return err + } + c.wbuf = c.wbuf[2+msgLen:] + c.rbuf = append([]byte{byte(len(ans) >> 8), byte(len(ans))}, ans...) + return nil +} + +func (c *streamConn) Close() error { + c.mu.Lock() + defer c.mu.Unlock() + c.closed = true + return nil +} + +func (c *streamConn) SetDeadline(t time.Time) error { + c.mu.Lock() + defer c.mu.Unlock() + c.deadline = t + return nil +} + +func (c *streamConn) SetReadDeadline(t time.Time) error { return c.SetDeadline(t) } +func (c *streamConn) SetWriteDeadline(t time.Time) error { return nil } + +func (c *streamConn) LocalAddr() net.Addr { return fakeAddr{} } +func (c *streamConn) RemoteAddr() net.Addr { return fakeAddr{} } + +type fakeAddr struct{} + +func (fakeAddr) Network() string { return "dnsproxyd" } +func (fakeAddr) String() string { return "dnsproxyd" } + +// resolvConfExists reports whether the platform has an /etc/resolv.conf +// that Go's resolver could use. +func resolvConfExists() bool { + fi, err := os.Stat("/etc/resolv.conf") + return err == nil && fi.Size() > 0 +} diff --git a/feature/buildfeatures/feature_androiddns_disabled.go b/feature/buildfeatures/feature_androiddns_disabled.go new file mode 100644 index 000000000..1eadd070a --- /dev/null +++ b/feature/buildfeatures/feature_androiddns_disabled.go @@ -0,0 +1,13 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +// Code generated by gen.go; DO NOT EDIT. + +//go:build ts_omit_androiddns + +package buildfeatures + +// HasAndroidDNS is whether the binary was built with support for modular feature "DNS resolution via Android's dnsproxyd for standalone (non-app) binaries on Android". +// Specifically, it's whether the binary was NOT built with the "ts_omit_androiddns" build tag. +// It's a const so it can be used for dead code elimination. +const HasAndroidDNS = false diff --git a/feature/buildfeatures/feature_androiddns_enabled.go b/feature/buildfeatures/feature_androiddns_enabled.go new file mode 100644 index 000000000..4673338d4 --- /dev/null +++ b/feature/buildfeatures/feature_androiddns_enabled.go @@ -0,0 +1,13 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +// Code generated by gen.go; DO NOT EDIT. + +//go:build !ts_omit_androiddns + +package buildfeatures + +// HasAndroidDNS is whether the binary was built with support for modular feature "DNS resolution via Android's dnsproxyd for standalone (non-app) binaries on Android". +// Specifically, it's whether the binary was NOT built with the "ts_omit_androiddns" build tag. +// It's a const so it can be used for dead code elimination. +const HasAndroidDNS = true diff --git a/feature/condregister/maybe_androiddns.go b/feature/condregister/maybe_androiddns.go new file mode 100644 index 000000000..d25cc4cc1 --- /dev/null +++ b/feature/condregister/maybe_androiddns.go @@ -0,0 +1,8 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build linux && !ts_omit_androiddns + +package condregister + +import _ "tailscale.com/feature/androiddns" diff --git a/feature/featuretags/featuretags.go b/feature/featuretags/featuretags.go index 824ff73fd..75a9a0f9d 100644 --- a/feature/featuretags/featuretags.go +++ b/feature/featuretags/featuretags.go @@ -95,6 +95,7 @@ type FeatureMeta struct { var Features = map[FeatureTag]FeatureMeta{ "ace": {Sym: "ACE", Desc: "Alternate Connectivity Endpoints"}, "acme": {Sym: "ACME", Desc: "ACME TLS certificate management"}, + "androiddns": {Sym: "AndroidDNS", Desc: "DNS resolution via Android's dnsproxyd for standalone (non-app) binaries on Android"}, "appconnectors": {Sym: "AppConnectors", Desc: "App Connectors support"}, "aws": {Sym: "AWS", Desc: "AWS integration"}, "advertiseexitnode": {