Skip to content

Commit abf4d0e

Browse files
profile,cmd: resolve SOCKS names through the selected profile's DNS
Resolve SOCKS hostname destinations with the selected profile's effective DNS configuration, without falling back to the host resolver. Race address families and literal-only TCP connections, bound CNAME chains, and fail closed on lookup errors. Leave DNS-upstream bootstrap dialing unchanged. Cover lookup validation, cancellation and losing connection cleanup with Go tests. Exercise real private IPv4/IPv6 names, aliases, conflicting host entries, resolver outages and recovery in the Linux process integration. Change-Id: I7985e3dfe263711919aaea38747442a8c8119048 Co-authored-by: Shelley <shelley@exe.dev>
1 parent 5dcd535 commit abf4d0e

5 files changed

Lines changed: 827 additions & 2 deletions

File tree

‎cmd/linux-network-e2e/rig.go‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,23 @@ func (r *rig) setupPeer() {
342342
peer := decode[tailStatus](r.e("peer", "tailscale", "--socket=/private/tailscaled.sock", "status", "--json"))
343343
r.peerIPs = peer.Self.TailscaleIPs
344344
require(contains(r.peerIPs, "100.64.0.1"), "fresh sequential allocator")
345-
require(privateWrite(filepath.Join(r.tmp, "peer", "dnsmasq.conf"), dnsmasqConfig) == nil, "private resolver config")
345+
var v4, v6 string
346+
for _, text := range r.peerIPs {
347+
ip := must(netip.ParseAddr(text))
348+
if ip.Is4() {
349+
v4 = ip.String()
350+
} else {
351+
v6 = ip.String()
352+
}
353+
}
354+
require(v4 != "" && v6 != "", "private resolver dual-stack targets")
355+
config := dnsmasqConfig + fmt.Sprintf(`host-record=proxy.corp.test,%s,%s,60
356+
host-record=proxy4.corp.test,%s,60
357+
host-record=proxy6.corp.test,%s,60
358+
host-record=outage.corp.test,%s,60
359+
cname=alias.corp.test,proxy.corp.test
360+
`, v4, v6, v4, v6, v4)
361+
require(privateWrite(filepath.Join(r.tmp, "peer", "dnsmasq.conf"), config) == nil, "private resolver config")
346362
r.e("peer", "dnsmasq", "--conf-file=/private/dnsmasq.conf")
347363
}
348364

‎cmd/linux-network-e2e/socks.go‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,11 @@ func (r *rig) socksTests() {
120120
r.start("client", r.image, false, []string{
121121
"--env-file", filepath.Join(r.tmp, "client", "env"),
122122
"--mount", "type=bind,src=" + r.bind(r.binaryDir) + ",dst=/checkout,readonly",
123+
// A host-resolver fallback would succeed for these names even when
124+
// the profile resolver rejects them or is unavailable.
125+
"--add-host=missing.corp.test:100.64.0.1",
126+
"--add-host=outage.corp.test:100.64.0.1",
127+
"--add-host=proxy.corp.test:127.0.0.1",
123128
}, nil)
124129
r.e("client", "test", "!", "-e", "/dev/net/tun")
125130
r.e("client", "ln", "-s", "/checkout/tailmix", "/bin/tailmix")
@@ -175,6 +180,20 @@ func (r *rig) socksTests() {
175180
check("effective IPv6 stream", net.JoinHostPort(effective[1], "18080"), true)
176181
check("MagicDNS stream", "resolver.isolated.test:18080", true)
177182
check("normalized MagicDNS stream", "RESOLVER.ISOLATED.TEST.:18080", true)
183+
check("private dual-stack DNS stream", "proxy.corp.test:18080", true)
184+
check("private IPv4-only DNS stream", "proxy4.corp.test:18080", true)
185+
check("private IPv6-only DNS stream", "proxy6.corp.test:18080", true)
186+
check("private DNS alias stream", "alias.corp.test:18080", true)
187+
check("private NXDOMAIN without host fallback", "missing.corp.test:18080", false)
188+
if err := guarded(func() {
189+
r.pause("STOP")
190+
check("private resolver outage without host fallback", "outage.corp.test:18080", false)
191+
}); err != nil {
192+
r.pause("CONT")
193+
panic(err)
194+
}
195+
r.pause("CONT")
196+
check("private resolver recovery", "outage.corp.test:18080", true)
178197

179198
for _, ip := range r.peerIPs {
180199
check("canonical address refusal", net.JoinHostPort(ip, "18080"), false)

‎cmd/tailmixd/supervisor.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -509,7 +509,7 @@ func (s *supervisor) reconcileLocked() (err error) {
509509
profiles = append(profiles, socksproxy.Profile{
510510
ID: status.ProfileID,
511511
MagicDNSSuffix: status.MagicDNSSuffix,
512-
Dialer: managed.runtime.Engine,
512+
Dialer: tailmixprofile.SOCKSDialer{Engine: managed.runtime.Engine},
513513
})
514514
}
515515
var subnetRoutes []socksproxy.SubnetRoute

‎profile/socksdial.go‎

Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
package profile
2+
3+
import (
4+
"context"
5+
"errors"
6+
"net"
7+
"net/netip"
8+
"strconv"
9+
"strings"
10+
"time"
11+
12+
"golang.org/x/net/dns/dnsmessage"
13+
"tailscale.com/net/netx"
14+
)
15+
16+
// SOCKSDialer resolves SOCKS names through the selected profile's effective DNS
17+
// configuration. Do not use it for the DNS forwarder's own upstream connections:
18+
// those may need Engine.Dial to bootstrap a resolver's hostname.
19+
type SOCKSDialer struct {
20+
Engine Engine
21+
}
22+
23+
type socksDNSQueryer interface {
24+
QueryDNSContext(context.Context, string, dnsmessage.Type) ([]byte, error)
25+
}
26+
27+
var (
28+
errSOCKSTarget = errors.New("invalid SOCKS TCP target")
29+
errSOCKSDNS = errors.New("profile SOCKS DNS resolution failed")
30+
errSOCKSDial = errors.New("profile SOCKS connection failed")
31+
)
32+
33+
const socksFallbackDelay = 250 * time.Millisecond
34+
35+
func (d SOCKSDialer) Dial(ctx context.Context, network, addr string) (net.Conn, error) {
36+
if err := ctx.Err(); err != nil {
37+
return nil, err
38+
}
39+
if d.Engine == nil || (network != "tcp" && network != "tcp4" && network != "tcp6") {
40+
return nil, errSOCKSTarget
41+
}
42+
host, port, err := net.SplitHostPort(addr)
43+
if err != nil {
44+
return nil, errSOCKSTarget
45+
}
46+
if _, err := netip.ParseAddr(host); err == nil {
47+
return d.Engine.Dial(ctx, network, addr)
48+
}
49+
queryer, ok := d.Engine.(socksDNSQueryer)
50+
if !ok {
51+
return nil, errSOCKSDNS
52+
}
53+
portNum, err := strconv.ParseUint(port, 10, 16)
54+
if err != nil || host == "" {
55+
return nil, errSOCKSTarget
56+
}
57+
// The router has already validated and qualified the name. Make the wire
58+
// question absolute without consulting search domains or the host resolver.
59+
name := strings.TrimSuffix(host, ".") + "."
60+
if _, err := dnsmessage.NewName(name); err != nil {
61+
return nil, errSOCKSTarget
62+
}
63+
ctx, cancel := context.WithCancel(ctx)
64+
defer cancel()
65+
type result struct {
66+
conn net.Conn
67+
err error
68+
}
69+
results := make(chan result)
70+
fallback := make(chan struct{})
71+
types := []dnsmessage.Type{dnsmessage.TypeAAAA, dnsmessage.TypeA}
72+
if network == "tcp4" {
73+
types = []dnsmessage.Type{dnsmessage.TypeA}
74+
} else if network == "tcp6" {
75+
types = []dnsmessage.Type{dnsmessage.TypeAAAA}
76+
}
77+
for _, typ := range types {
78+
go func() {
79+
if typ == dnsmessage.TypeAAAA {
80+
// An unavailable IPv6 family should not delay IPv4.
81+
defer close(fallback)
82+
}
83+
ips, err := socksLookup(ctx, queryer, name, typ)
84+
var conn net.Conn
85+
if err == nil {
86+
if typ == dnsmessage.TypeA && network == "tcp" {
87+
timer := time.NewTimer(socksFallbackDelay)
88+
select {
89+
case <-timer.C:
90+
case <-fallback:
91+
case <-ctx.Done():
92+
}
93+
timer.Stop()
94+
}
95+
addrs := make([]netip.AddrPort, 0, len(ips))
96+
for _, ip := range ips {
97+
addrs = append(addrs, netip.AddrPortFrom(ip, uint16(portNum)))
98+
}
99+
conn, err = netx.RaceDial(ctx, addrs, func(ctx context.Context, _ string, literal string) (net.Conn, error) {
100+
// RaceDial uses "tcp"; retain the caller's family restriction.
101+
if err := ctx.Err(); err != nil {
102+
return nil, err
103+
}
104+
return d.Engine.Dial(ctx, network, literal)
105+
}, socksFallbackDelay)
106+
if err != nil {
107+
err = errSOCKSDial
108+
}
109+
}
110+
select {
111+
case results <- result{conn, err}:
112+
case <-ctx.Done():
113+
if conn != nil {
114+
conn.Close()
115+
}
116+
}
117+
}()
118+
}
119+
var lastErr error
120+
for range types {
121+
select {
122+
case res := <-results:
123+
if err := ctx.Err(); err != nil {
124+
if res.conn != nil {
125+
res.conn.Close()
126+
}
127+
return nil, err
128+
}
129+
if res.err == nil {
130+
return res.conn, nil
131+
}
132+
lastErr = res.err
133+
case <-ctx.Done():
134+
return nil, ctx.Err()
135+
}
136+
}
137+
return nil, lastErr
138+
}
139+
140+
// socksLookup accepts only addresses owned by the question name or its CNAME
141+
// chain, never unrelated answers or additional-section glue. Follow CNAME-only
142+
// replies through the same profile, with one shared bound for hops and queries.
143+
func socksLookup(ctx context.Context, queryer socksDNSQueryer, name string, typ dnsmessage.Type) ([]netip.Addr, error) {
144+
seen := make(map[string]bool)
145+
for hops := 0; hops < 8; {
146+
wire, err := queryer.QueryDNSContext(ctx, name, typ)
147+
if err != nil || ctx.Err() != nil || len(wire) > 65535 {
148+
return nil, errSOCKSDNS
149+
}
150+
var msg dnsmessage.Message
151+
if err := msg.Unpack(wire); err != nil || !msg.Response || msg.Truncated ||
152+
msg.OpCode != 0 || msg.RCode != dnsmessage.RCodeSuccess || len(msg.Questions) != 1 {
153+
return nil, errSOCKSDNS
154+
}
155+
// QueryDNSContext owns the transaction ID; its API exposes no request
156+
// ID to compare. Validate the question instead (backend IDs may vary).
157+
q := msg.Questions[0]
158+
if !strings.EqualFold(q.Name.String(), name) || q.Type != typ || q.Class != dnsmessage.ClassINET {
159+
return nil, errSOCKSDNS
160+
}
161+
for hops < 8 {
162+
key := strings.ToLower(name)
163+
if seen[key] {
164+
return nil, errSOCKSDNS
165+
}
166+
seen[key] = true
167+
hops++
168+
var ips []netip.Addr
169+
var cname string
170+
for _, answer := range msg.Answers {
171+
if answer.Header.Class != dnsmessage.ClassINET || !strings.EqualFold(answer.Header.Name.String(), name) {
172+
continue
173+
}
174+
switch body := answer.Body.(type) {
175+
case *dnsmessage.AResource:
176+
if typ == dnsmessage.TypeA {
177+
ips = append(ips, netip.AddrFrom4(body.A))
178+
}
179+
case *dnsmessage.AAAAResource:
180+
ip := netip.AddrFrom16(body.AAAA)
181+
if typ == dnsmessage.TypeAAAA && !ip.Is4In6() {
182+
ips = append(ips, ip)
183+
}
184+
case *dnsmessage.CNAMEResource:
185+
cname = body.CNAME.String()
186+
}
187+
}
188+
if len(ips) != 0 {
189+
return ips, nil
190+
}
191+
if cname == "" {
192+
if !strings.EqualFold(name, q.Name.String()) {
193+
// This response ended at an alias; query its terminal name.
194+
delete(seen, key)
195+
hops--
196+
break
197+
}
198+
return nil, errSOCKSDNS
199+
}
200+
name = cname
201+
}
202+
}
203+
return nil, errSOCKSDNS
204+
}

0 commit comments

Comments
 (0)