Skip to content

Commit

Permalink
Merge pull request #183 from metal-stack/fix-dns-reply
Browse files Browse the repository at this point in the history
Detect client bufsize and truncate/compress the reply accordingly
  • Loading branch information
mreiger committed Aug 7, 2024
2 parents 0ff6088 + 4fb4d3d commit 5873713
Showing 1 changed file with 32 additions and 2 deletions.
34 changes: 32 additions & 2 deletions pkg/dns/dns_proxy_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,18 +57,48 @@ func (h *DNSProxyHandler) ServeDNS(w dnsgo.ResponseWriter, request *dnsgo.Msg) {
}
}()

scopedLog.Info("started processing request")
response, err := h.getDataFromDNS(w.LocalAddr(), request)
serverAddress := w.LocalAddr()
bufsize := getBufSize(serverAddress.Network(), request)
scopedLog.Info("started processing request", "server", serverAddress, "bufsize", bufsize, "request", request)

response, err := h.getDataFromDNS(serverAddress, request)
if err != nil {
scopedLog.Error(err, "failed to get DNS response")
err = w.WriteMsg(refusedMsg(request))
return
}

originalResponse := response.Copy()
/*
Why are we truncating the answer?
DNS has a feature where a DNS server can "compress" the names in a message, and will usually do this if the reply will not fit in the maximum payload length for a DNS packet; for more explanation see here: https://datatracker.ietf.org/doc/html/rfc1035#autoid-44
Unfortunately, in dnsgo the compression status of a message is apparently not retained, so if you take a compressed message and write it out again your wind up with a bigger message, without any checks whether the resulting message is too big for the receiver. If this happens, it breaks name resolution.
Therefore we find out the buffer size of the client from the request (with UDP it's 512 bytes by default) and limit the reply to this buffer size before we send it out. The Truncate method will try compression first to fit the message into the buffer size and will truncate the message if necessary.
*/
response.Truncate(bufsize)
scopedLog.Info("processing response", "buffer size", bufsize, "original response", originalResponse, "truncated response", response)

go h.updateCache(time.Now(), response)

err = w.WriteMsg(response)
}

func getBufSize(protocol string, request *dnsgo.Msg) int {
if request.Extra != nil {
for _, rr := range request.Extra {
switch r := rr.(type) {
case *dnsgo.OPT:
return int(r.UDPSize())
}
}
}

if protocol == "tcp" {
return dnsgo.MaxMsgSize
}
return dnsgo.MinMsgSize
}

// UpdateDNSServerAddr validates and if successful updates DNS server address
func (h *DNSProxyHandler) UpdateDNSServerAddr(addr string) error {
m := new(dnsgo.Msg)
Expand Down

0 comments on commit 5873713

Please sign in to comment.