forked from cottand/leng
-
Notifications
You must be signed in to change notification settings - Fork 0
/
doh.go
255 lines (215 loc) · 6.1 KB
/
doh.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package main
import (
"context"
"crypto/tls"
"encoding/base64"
"fmt"
"github.com/cottand/leng/internal/metric"
"github.com/miekg/dns"
"github.com/prometheus/client_golang/prometheus"
"io"
stdlog "log"
"net"
"net/http"
"time"
)
/**
This implementation is heavily inspired by CoreDNS and used as per their Apache 2 license
see https://github.com/coredns/coredns/blob/v1.11.1/core/dnsserver/server_https.go
There is no NOTICE redistribution as, at the time of producing the derivative work, CoreDNS did
not distribute such a notice with their work.
*/
const mimeTypeDOH = "application/dns-message"
// pathDOH is the URL path that should be used.
const pathDOH = "/dns-query"
// ServerHTTPS represents an instance of a DNS-over-HTTPS server.
type ServerHTTPS struct {
Net string
handler dns.Handler
httpsServer *http.Server
tlsConfig *tls.Config
validRequest func(*http.Request) bool
bind string
ttl time.Duration
}
// loggerAdapter is a simple adapter around CoreDNS logger made to implement io.Writer in order to log errors from HTTP server
type loggerAdapter struct {
}
func (l *loggerAdapter) Write(p []byte) (n int, err error) {
logger.Debugf("Writing HTTP request=%v", string(p))
return len(p), nil
}
// NewServerHTTPS returns a new HTTPS server capable of performing DoH with dns
func NewServerHTTPS(
dns dns.Handler,
bind string,
timeout time.Duration,
ttl time.Duration,
tls *tls.Config,
) (*ServerHTTPS, error) {
// http/2 is recommended when using DoH. We need to specify it in next protos
// or the upgrade won't happen.
if tls != nil {
tls.NextProtos = []string{"h2", "http/1.1"}
}
// Use a custom request validation func or use the standard DoH path check.
srv := &http.Server{
ReadTimeout: timeout,
WriteTimeout: timeout,
ErrorLog: stdlog.New(&loggerAdapter{}, "", 0),
Addr: bind,
}
sh := &ServerHTTPS{
handler: dns, httpsServer: srv, ttl: ttl, bind: bind,
}
srv.Handler = sh
return sh, nil
}
func (s *ServerHTTPS) ListenAndServe() error {
return s.httpsServer.ListenAndServe()
}
// Stop stops the server. It blocks until the server is totally stopped.
func (s *ServerHTTPS) Stop() error {
if s.httpsServer != nil {
_ = s.httpsServer.Shutdown(context.Background())
}
return nil
}
// ServeHTTP is the eventLoop that gets the HTTP request and converts to the dns format, calls the resolver,
// converts it back and write it to the client.
func (s *ServerHTTPS) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if !(r.URL.Path == pathDOH) {
http.Error(w, "", http.StatusNotFound)
countResponse(http.StatusNotFound)
return
}
msg, err := requestToMsg(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
countResponse(http.StatusBadRequest)
logger.Noticef("error when serving DoH request: %v", err)
return
}
var writer = DohResponseWriter{remoteAddr: r.RemoteAddr, host: r.Host, delegate: w, completed: make(chan empty, 1)}
s.handler.ServeDNS(&writer, msg)
_, ok := <-writer.completed
if writer.err != nil || ok != true {
return
}
age := s.ttl // seconds
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%v", age.Seconds()))
}
func countResponse(status int) {
metric.DohResponseCount.With(prometheus.Labels{"status": fmt.Sprint(status)}).Inc()
}
// Shutdown stops the server (non gracefully).
func (s *ServerHTTPS) Shutdown() {
if s.httpsServer != nil {
_ = s.httpsServer.Shutdown(context.Background())
}
}
func requestToMsg(req *http.Request) (*dns.Msg, error) {
if req.Method == "GET" {
return getRequestToMsg(req)
}
if req.Method == "POST" {
return postRequestToMsg(req)
}
return nil, fmt.Errorf("unexpected method for DoH request %v", req.Method)
}
// postRequestToMsg extracts the dns message from the request body.
func postRequestToMsg(req *http.Request) (*dns.Msg, error) {
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(req.Body)
buf, err := io.ReadAll(req.Body)
if err != nil {
return nil, err
}
m := new(dns.Msg)
err = m.Unpack(buf)
return m, err
}
// getRequestToMsg extract the dns message from the GET request.
func getRequestToMsg(req *http.Request) (*dns.Msg, error) {
values := req.URL.Query()
b64, ok := values["dns"]
if !ok {
return nil, fmt.Errorf("no 'dns' query parameter found")
}
if len(b64) != 1 {
return nil, fmt.Errorf("multiple 'dns' query values found")
}
return base64ToMsg(b64[0])
}
func base64ToMsg(b64 string) (*dns.Msg, error) {
buf, err := base64.RawURLEncoding.DecodeString(b64)
if err != nil {
return nil, err
}
m := new(dns.Msg)
err = m.Unpack(buf)
return m, err
}
type empty struct{}
// DohResponseWriter implements dns.ResponseWriter
type DohResponseWriter struct {
msg *dns.Msg
remoteAddr string
delegate http.ResponseWriter
host string
err error
completed chan empty
}
// See section 4.2.1 of RFC 8484.
// We are using code 500 to indicate an unexpected situation when the chain
// eventLoop has not provided any response message.
func (w *DohResponseWriter) handleErr(err error) {
logger.Warningf("error when replying to DoH: %v", err)
http.Error(w.delegate, "No response", http.StatusInternalServerError)
countResponse(http.StatusInternalServerError)
w.err = err
return
}
func (w *DohResponseWriter) LocalAddr() net.Addr {
addr, _ := net.ResolveTCPAddr("tcp", w.remoteAddr)
return addr
}
func (w *DohResponseWriter) RemoteAddr() net.Addr {
addr, _ := net.ResolveTCPAddr("tcp", w.remoteAddr)
return addr
}
func (w *DohResponseWriter) WriteMsg(msg *dns.Msg) error {
defer func() {
w.completed <- empty{}
close(w.completed)
}()
w.msg = msg
buf, err := msg.Pack()
if err != nil {
w.handleErr(err)
return err
}
w.delegate.Header().Set("Content-Type", mimeTypeDOH)
_, err = w.Write(buf)
if err != nil {
w.handleErr(err)
return err
}
countResponse(http.StatusOK)
return nil
}
func (w *DohResponseWriter) Write(bytes []byte) (int, error) {
return w.delegate.Write(bytes)
}
func (w *DohResponseWriter) Close() error {
return nil
}
func (w *DohResponseWriter) TsigStatus() error {
return nil
}
func (w *DohResponseWriter) TsigTimersOnly(_ bool) {
}
func (w *DohResponseWriter) Hijack() {
return
}