Debian Codegraph @

dnshttp/dnshttp.go

raw
1 // Package dnshttp deals with converting HTTP requests and responses to dns.Msg types. This is part of DNS
2 // over HTTP (DOH).
3 // The mandatory tls.Config must contain tlsConfig.NextProtos = []string{"h2", "http/1.1"}, see [NextProtos].
4 package dnshttp
5
6 import (
7 "bytes"
8 "encoding/base64"
9 "fmt"
10 "io"
11 "net/http"
12 "net/url"
13
14 "codeberg.org/miekg/dns"
15 )
16
17 // MimeType is the DOH mimetype.
18 const MimeType = "application/dns-message"
19
20 // Path is the URL path that is used by DOH.
21 const Path = "/dns-query"
22
23 // NextProtos is the configuration a tls.Config must carry to be compatible with most clients.
24 var NextProtos = []string{"h2", "http/1.1"}
25
26 // NewRequest returns a new DOH request given a HTTP method, URL and a [dns.Msg].
27 //
28 // The URL should not have a path, so "/dns-query" should be excluded. The URL must have a scheme, although
29 // this isn't checked. Supported methods are GET or POST. NewRequest call Pack on m and sets m.ID to zero.
30 func NewRequest(method, URL string, m *dns.Msg) (*http.Request, error) {
31 m.ID = 0
32 if err := m.Pack(); err != nil {
33 return nil, err
34 }
35
36 URL, err := url.JoinPath(URL, Path)
37 if err != nil {
38 return nil, err
39 }
40
41 switch method {
42 case http.MethodGet:
43 b64 := base64.RawURLEncoding.EncodeToString(m.Data)
44 req, err := http.NewRequest(method, URL+"?dns="+b64, nil)
45 if err != nil {
46 return req, err
47 }
48 req.Header.Set("Accept", MimeType)
49 return req, nil
50 case http.MethodPost:
51 req, err := http.NewRequest(method, URL, bytes.NewReader(m.Data))
52 if err != nil {
53 return req, err
54 }
55 req.Header.Set("Content-Type", MimeType)
56 req.Header.Set("Accept", MimeType)
57 return req, nil
58 }
59 return nil, fmt.Errorf("%s: %s", http.StatusText(http.StatusMethodNotAllowed), method)
60 }
61
62 // Request converts req to a [dns.Msg]. This is used inside the ServerHTTP method to make a [dns.Msg] that will
63 // then be given to the (embedded) [dns.ServeMux]:
64 //
65 // func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
66 // m, err := dnshttp.Request(r)
67 // if err != nil {
68 // http.Error(w, err.Error(), http.StatusBadRequest)
69 // return
70 // }
71 // hw := dnshttp.NewResponseWriter(w, r, r.Context().Value(http.LocalAddrContextKey).(net.Addr))
72 // h.mux.ServeDNS(context.Background(), hw, m) // assuming *handler embeds a dns.ServeMux
73 // }
74 //
75 // The request must have the Content-Type header set to [MimeType].
76 func Request(req *http.Request) (*dns.Msg, error) {
77 switch req.Method {
78 case http.MethodGet:
79 values := req.URL.Query()
80 b64, ok := values["dns"]
81 if !ok || len(b64) != 1 {
82 return nil, fmt.Errorf("no 'dns' or multiple query parameter found")
83 }
84 buf, err := base64.RawURLEncoding.DecodeString(b64[0])
85 if err != nil {
86 return nil, err
87 }
88 if len(buf) > dns.MaxMsgSize {
89 return nil, fmt.Errorf("dns msg too big")
90 }
91 m := &dns.Msg{Data: buf}
92 err = m.Unpack()
93 if err != nil {
94 return m, err
95 }
96 if action := MsgAcceptFunc(m); action != dns.MsgAccept {
97 return nil, fmt.Errorf("dns msg unacceptable")
98 }
99 return m, nil
100
101 case http.MethodPost:
102 if x := req.Header.Get("Content-Type"); x != MimeType {
103 return nil, fmt.Errorf("Content-Type other than %q is not supported", MimeType)
104 }
105
106 defer req.Body.Close()
107 m, err := msg(req.Body)
108 if err != nil {
109 return m, err
110 }
111 if action := MsgAcceptFunc(m); action != dns.MsgAccept {
112 return nil, fmt.Errorf("dns msg unacceptable")
113 }
114 return m, nil
115
116 }
117 return nil, fmt.Errorf("%s: %s", http.StatusText(http.StatusMethodNotAllowed), req.Method)
118 }
119
120 // Response converts resp to a [dns.Msg].
121 func Response(resp *http.Response) (*dns.Msg, error) {
122 defer resp.Body.Close()
123 return msg(resp.Body)
124 }
125
126 // msg converts the (usually the body) ReadCloser to a [dns.Msg].
127 func msg(r io.ReadCloser) (*dns.Msg, error) {
128 buf, err := io.ReadAll(http.MaxBytesReader(nil, r, 65536))
129 if err != nil {
130 return nil, err
131 }
132 m := &dns.Msg{Data: buf}
133 err = m.Unpack()
134 return m, err
135 }
136
137 // MsgAccepFunc is the function that checks if the incoming message is valid. This function can be a noop, but
138 // should never be nil.
139 var MsgAcceptFunc = DefaultMsgAcceptFunc
140
141 // DefaultMsgAcceptFunc does everything the dns.DefaultMsgAcceptFunc does in addition to the check mandated by
142 // DOQ, that the Pseudo section cannot contain an TCP-KEEPALIVE option. Not other checks are performed.
143 func DefaultMsgAcceptFunc(m *dns.Msg) dns.MsgAcceptAction {
144 // copied from dns.DefaultMsgAcceptFunc, keep in sync.
145 if m.Response {
146 return dns.MsgIgnore
147 }
148 if _, ok := dns.OpcodeToString[m.Opcode]; !ok {
149 return dns.MsgRejectNotImplemented
150 }
151 if m.ID != 0 {
152 return dns.MsgReject
153 }
154 if len(m.Question) != 1 {
155 return dns.MsgReject
156 }
157 if _, ok := m.Question[0].(*dns.RRSIG); ok {
158 return dns.MsgRejectRefused
159 }
160 for _, o := range m.Pseudo {
161 if _, ok := o.(*dns.TCPKEEPALIVE); ok {
162 return dns.MsgReject
163 }
164 }
165 return dns.MsgAccept
166 }