mirror of
https://github.com/tailscale/tailscale.git
synced 2026-12-06 08:32:21 -08:00
net/dns/resolver: only accept UDP DNS replies from the queried resolver
The forwarder's upstream UDP socket is unconnected, so any host that could send a datagram to its ephemeral port reached the single ReadFromUDPAddrPort call that decided the query: a datagram with the right 16-bit transaction ID was returned to the client as the resolver's answer no matter what address it came from, and a datagram with the wrong ID failed the query outright, handing it to the TCP fallback (or to nothing at all, with TCP retries disabled). sendUDP now keeps reading until a datagram arrives that could be a reply to the query it sent: one from the resolver's address and port carrying the transaction ID of the request. Other datagrams are dropped and counted, so neither a spoofed reply nor a single stray datagram can answer or end the query. This is the same source check the kernel applies to a connected socket; the socket stays unconnected because its ListenPacket path is what binds the query to a link (IP_BOUND_IF on macOS, ForwardLinkSelector elsewhere). The read loop still ends when the query context expires and closeOnCtxDone closes the conn, as before. On Windows an oversized datagram is reported as a truncation error without a source address, so there the transaction ID remains the only check, as before. Thanks to Ben Carman for the report! Updates tailscale/corp#48187 Reported-by: Ben Carman Signed-off-by: Brad Fitzpatrick <[email protected]> Change-Id: Ibabbec5c82739b66caa6fb943faa376c39adbf64
This commit is contained in:
1 parent
3ea665b113
commit
2fc4be0f76
4 files changed
+201
-19
No files matched your search
@@ -813,33 +813,54 @@ func (f *forwarder) sendUDP(ctx context.Context, fq *forwardQuery, rr resolverAn
|
||||
|
||||
// The 1 extra byte is to detect packet truncation.
|
||||
out := make([]byte, maxResponseBytes+1)
|
||||
n, _, err := conn.ReadFromUDPAddrPort(out)
|
||||
if err != nil {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
|
||||
// The conn is unconnected (see dialUDP), so datagrams can arrive from
|
||||
// any address, not just the resolver we queried. A reply must come
|
||||
// from the resolver's address and carry the transaction ID we sent.
|
||||
// Datagrams that are neither are dropped rather than acted on, so
|
||||
// neither a spoofed reply nor a single stray datagram can decide the
|
||||
// query. The loop ends when the conn is closed, which the query's
|
||||
// context cancellation does via fq.closeOnCtxDone.
|
||||
var n int
|
||||
for {
|
||||
var src netip.AddrPort
|
||||
var err error
|
||||
n, src, err = conn.ReadFromUDPAddrPort(out)
|
||||
if err != nil {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !neterror.PacketWasTruncated(err) {
|
||||
metricDNSFwdUDPErrorRead.Add(1)
|
||||
return nil, err
|
||||
}
|
||||
// Windows reports a datagram larger than out as a
|
||||
// truncation error, returning the bytes that fit in
|
||||
// out but no source address. Fall through and let the
|
||||
// txid check decide, since the source can't be checked.
|
||||
} else if src != ipp {
|
||||
// Not from the resolver we asked, so not a reply to
|
||||
// this query.
|
||||
metricDNSFwdUDPDropSrc.Add(1)
|
||||
continue
|
||||
}
|
||||
if neterror.PacketWasTruncated(err) {
|
||||
err = nil
|
||||
} else {
|
||||
metricDNSFwdUDPErrorRead.Add(1)
|
||||
return nil, err
|
||||
if n < headerBytes {
|
||||
f.logf("recv: packet too small (%d bytes)", n)
|
||||
continue
|
||||
}
|
||||
if getTxID(out[:n]) != fq.txid {
|
||||
metricDNSFwdUDPErrorTxID.Add(1)
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
truncated := n > maxResponseBytes
|
||||
if truncated {
|
||||
n = maxResponseBytes
|
||||
}
|
||||
if n < headerBytes {
|
||||
f.logf("recv: packet too small (%d bytes)", n)
|
||||
}
|
||||
out = out[:n]
|
||||
tcFlagAlreadySet := truncatedFlagSet(out)
|
||||
|
||||
txid := getTxID(out)
|
||||
if txid != fq.txid {
|
||||
metricDNSFwdUDPErrorTxID.Add(1)
|
||||
return nil, errTxIDMismatch
|
||||
}
|
||||
rcode := getRCode(out)
|
||||
|
||||
// don't forward transient errors back to the client when the server fails
|
||||
|
||||
@@ -1119,6 +1119,166 @@ func TestForwarderTCPFallbackError(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestForwarderIgnoresStrayDatagrams checks that a datagram that is not a
|
||||
// reply to the query in flight can neither answer the query nor end it. The
|
||||
// forwarder's upstream UDP socket is unconnected, so when reading a reply it
|
||||
// has to sort out datagrams from other sources: a spoofed reply from another
|
||||
// address carrying the query's transaction ID, a datagram from the resolver
|
||||
// with the wrong transaction ID, and a datagram too short to hold a DNS
|
||||
// header must all be ignored in favor of the resolver's real reply. A spoofed
|
||||
// reply with no real reply behind it must never be returned to the client.
|
||||
//
|
||||
// See tailscale/corp#48187.
|
||||
func TestForwarderIgnoresStrayDatagrams(t *testing.T) {
|
||||
const domain = "stray-datagram.example.com."
|
||||
|
||||
// Use a nonzero query ID so that a real reply has to copy it from the
|
||||
// query, and so that a stray datagram can carry an ID that doesn't
|
||||
// match. The spoofed reply differs from the real one only in its
|
||||
// answer address, so returning it is detectable.
|
||||
const queryID = 0x1e5a
|
||||
request := makeTestRequest(t, domain, dns.TypeA, 0)
|
||||
binary.BigEndian.PutUint16(request[0:2], queryID)
|
||||
realResponse := makeTestResponse(t, domain, dns.RCodeSuccess, netip.MustParseAddr("127.0.0.1"))
|
||||
spoofedResponse := makeTestResponse(t, domain, dns.RCodeSuccess, netip.MustParseAddr("127.0.0.9"))
|
||||
binary.BigEndian.PutUint16(realResponse[0:2], queryID)
|
||||
binary.BigEndian.PutUint16(spoofedResponse[0:2], queryID)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
onQuery func(resolver, spoofer *net.UDPConn, dst netip.AddrPort)
|
||||
// wantNone is true when no reply should ever reach the client.
|
||||
wantNone bool
|
||||
}{
|
||||
{
|
||||
// A spoofed reply from some other source address, with
|
||||
// the transaction ID of the query, then the real reply.
|
||||
name: "wrong-source-right-txid",
|
||||
onQuery: func(resolver, spoofer *net.UDPConn, dst netip.AddrPort) {
|
||||
spoofer.WriteToUDPAddrPort(spoofedResponse, dst)
|
||||
resolver.WriteToUDPAddrPort(realResponse, dst)
|
||||
},
|
||||
},
|
||||
{
|
||||
// A datagram from the resolver with the wrong
|
||||
// transaction ID, then the real reply.
|
||||
name: "right-source-wrong-txid",
|
||||
onQuery: func(resolver, spoofer *net.UDPConn, dst netip.AddrPort) {
|
||||
badTxID := append([]byte(nil), spoofedResponse...)
|
||||
binary.BigEndian.PutUint16(badTxID[0:2], queryID+1)
|
||||
resolver.WriteToUDPAddrPort(badTxID, dst)
|
||||
resolver.WriteToUDPAddrPort(realResponse, dst)
|
||||
},
|
||||
},
|
||||
{
|
||||
// A datagram from the resolver too short to hold a DNS
|
||||
// header, then the real reply.
|
||||
name: "right-source-too-short",
|
||||
onQuery: func(resolver, spoofer *net.UDPConn, dst netip.AddrPort) {
|
||||
resolver.WriteToUDPAddrPort([]byte("not dns"), dst)
|
||||
resolver.WriteToUDPAddrPort(realResponse, dst)
|
||||
},
|
||||
},
|
||||
{
|
||||
// A spoofed reply with the right transaction ID from a
|
||||
// wrong source, and never a real reply.
|
||||
name: "wrong-source-right-txid-no-reply",
|
||||
wantNone: true,
|
||||
onQuery: func(resolver, spoofer *net.UDPConn, dst netip.AddrPort) {
|
||||
spoofer.WriteToUDPAddrPort(spoofedResponse, dst)
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// The resolver the forwarder queries, and a second socket
|
||||
// standing in for a spoofer elsewhere on the network.
|
||||
resolver, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resolver.Close()
|
||||
spoofer, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer spoofer.Close()
|
||||
|
||||
// On each query, aim the subtest's datagrams at the
|
||||
// forwarder's socket, whose address is the query's source.
|
||||
go func() {
|
||||
buf := make([]byte, 512)
|
||||
for {
|
||||
n, src, err := resolver.ReadFromUDPAddrPort(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if !bytes.Equal(buf[:n], request) {
|
||||
t.Errorf("invalid request\ngot: %+v\nwant: %+v", buf[:n], request)
|
||||
return
|
||||
}
|
||||
tt.onQuery(resolver, spoofer, src)
|
||||
}
|
||||
}()
|
||||
|
||||
logf := tstest.WhileTestRunningLogger(t)
|
||||
bus := eventbustest.NewBus(t)
|
||||
netMon, err := netmon.New(bus, logf)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer netMon.Close()
|
||||
|
||||
var dialer tsdial.Dialer
|
||||
dialer.SetNetMon(netMon)
|
||||
dialer.SetBus(bus)
|
||||
|
||||
fwd := newForwarder(logf, netMon, nil, &dialer, health.NewTracker(bus), nil)
|
||||
|
||||
rpkt := packet{
|
||||
bs: request,
|
||||
family: "udp",
|
||||
addr: netip.MustParseAddrPort("127.0.0.1:12345"),
|
||||
}
|
||||
rchan := make(chan packet, 1)
|
||||
|
||||
// When a reply is expected it should arrive promptly;
|
||||
// when none is, the query only has to outlast the
|
||||
// spoofed datagram.
|
||||
timeout := 5 * time.Second
|
||||
if tt.wantNone {
|
||||
timeout = 500 * time.Millisecond
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
resolverAddr, err := netip.ParseAddrPort(resolver.LocalAddr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := fwd.forwardWithDestChan(ctx, rpkt, rchan,
|
||||
resolverAndDelay{name: &dnstype.Resolver{Addr: resolverAddr.String()}}); err != nil && !tt.wantNone {
|
||||
t.Fatalf("forwardWithDestChan: %v", err)
|
||||
}
|
||||
|
||||
select {
|
||||
case res := <-rchan:
|
||||
if tt.wantNone {
|
||||
t.Fatalf("forwarder returned a reply anyway: %+v", res.bs)
|
||||
}
|
||||
if !bytes.Equal(res.bs, realResponse) {
|
||||
t.Errorf("invalid response\ngot: %+v\nwant: %+v", res.bs, realResponse)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
if !tt.wantNone {
|
||||
t.Fatalf("timed out waiting for response: %v", ctx.Err())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// netstackUpstream is a resolver at a tailnet (CGNAT) address. In userspace
|
||||
// networking mode the host stack has no route to it; only netstack does.
|
||||
var netstackUpstream = netip.MustParseAddrPort("100.64.1.2:53")
|
||||
|
||||
@@ -1557,6 +1557,7 @@ var (
|
||||
|
||||
metricDNSFwdUDP = clientmetric.NewCounter("dns_query_fwd_udp") // on entry
|
||||
metricDNSFwdUDPWrote = clientmetric.NewCounter("dns_query_fwd_udp_wrote") // sent UDP packet
|
||||
metricDNSFwdUDPDropSrc = clientmetric.NewCounter("dns_query_fwd_udp_drop_src")
|
||||
metricDNSFwdUDPErrorWrite = clientmetric.NewCounter("dns_query_fwd_udp_error_write")
|
||||
metricDNSFwdUDPErrorServer = clientmetric.NewCounter("dns_query_fwd_udp_error_server")
|
||||
metricDNSFwdUDPErrorRefused = clientmetric.NewCounter("dns_query_fwd_udp_error_refused")
|
||||
|
||||
@@ -50,8 +50,8 @@ var packetWasTruncated func(error) bool // non-nil on Windows at least
|
||||
// size and an error are returned (as per the partial fix for golang/go#14074).
|
||||
// If the WSAEMSGSIZE error is returned, then we ignore the error to get
|
||||
// semantics similar to the POSIX operating systems. One caveat is that it
|
||||
// appears that the source address is not returned when WSAEMSGSIZE occurs, but
|
||||
// we do not currently look at the source address.
|
||||
// appears that the source address is not returned when WSAEMSGSIZE occurs, so
|
||||
// a caller can't check where a truncated datagram came from.
|
||||
func PacketWasTruncated(err error) bool {
|
||||
if packetWasTruncated == nil {
|
||||
return false
|
||||
|
||||
Reference in new issue
Block a user