Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detect client bufsize and truncate/compress the reply accordingly #183

Merged
merged 6 commits into from
Aug 7, 2024
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 34 additions & 2 deletions pkg/dns/dns_proxy_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,47 @@ 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("request info", "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
}

go h.updateCache(time.Now(), response)
err = w.WriteMsg(response)

scopedLog.Info("truncating response before sending reply to client", "bufsize", bufsize)
reply := 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.
*/
reply.Truncate(bufsize)

scopedLog.Info("original response and processed reply", "response", response, "reply", reply)
err = w.WriteMsg(reply)
}

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
Expand Down
Loading