Debian Codegraph @

dns_server.go

raw
1 package nebula
2
3 import (
4 "context"
5 "fmt"
6 "log/slog"
7 "net"
8 "net/netip"
9 "strconv"
10 "strings"
11 "sync"
12 "sync/atomic"
13
14 "github.com/miekg/dns"
15 "github.com/slackhq/nebula/config"
16 )
17
18 type dnsServer struct {
19 sync.RWMutex
20 l *slog.Logger
21 ctx context.Context
22 dnsMap4 map[string]netip.Addr
23 dnsMap6 map[string]netip.Addr
24 hostMap *HostMap
25 pki *PKI
26
27 // selfHost is the cached FQDN we last seeded for ourselves
28 selfHost string
29
30 mux *dns.ServeMux
31
32 // enabled mirrors `lighthouse.serve_dns && lighthouse.am_lighthouse`.
33 // Start, Add, and reload consult it so callers don't need to know the
34 // gating rules. When it toggles off via reload, accumulated records are
35 // cleared so a later re-enable starts with a fresh map populated from
36 // new handshakes.
37 enabled atomic.Bool
38
39 serverMu sync.Mutex
40 server *dns.Server
41 // started is closed once `server` has finished binding (or after
42 // ListenAndServe returns on a bind failure). Stop waits on it before
43 // calling Shutdown to avoid the miekg/dns "server not started" race
44 // where a Shutdown that arrives before bind completes is silently
45 // ignored, leaving the listener running forever.
46 started chan struct{}
47 addr string
48 }
49
50 // newDnsServerFromConfig builds a dnsServer, applies the initial config, and
51 // registers a reload callback. The reload callback is registered before the
52 // initial config is applied, so a SIGHUP can later enable, fix, or disable
53 // DNS even if the initial application failed.
54 //
55 // The dnsServer internally gates on `lighthouse.serve_dns &&
56 // lighthouse.am_lighthouse`. Start and Add are safe to call unconditionally,
57 // they no-op when DNS isn't enabled. Each Start invocation owns a ctx-cancel
58 // watcher that tears the listener down on nebula shutdown. The returned
59 // pointer is always non-nil, even on error.
60 func newDnsServerFromConfig(ctx context.Context, l *slog.Logger, pki *PKI, hostMap *HostMap, c *config.C) (*dnsServer, error) {
61 ds := &dnsServer{
62 l: l,
63 ctx: ctx,
64 dnsMap4: make(map[string]netip.Addr),
65 dnsMap6: make(map[string]netip.Addr),
66 hostMap: hostMap,
67 pki: pki,
68 }
69 ds.mux = dns.NewServeMux()
70 ds.mux.HandleFunc(".", ds.handleDnsRequest)
71
72 c.RegisterReloadCallback(func(c *config.C) {
73 if err := ds.reload(c, false); err != nil {
74 ds.l.Error("Failed to reload DNS responder from config", "error", err)
75 }
76 })
77
78 if err := ds.reload(c, true); err != nil {
79 return ds, err
80 }
81 ds.seedSelf()
82 return ds, nil
83 }
84
85 // reload applies the latest config and reconciles the running state with it:
86 // - enabled toggled on -> spawn a runner
87 // - enabled toggled off -> stop the runner
88 // - listen address changed (while running) -> restart on the new address
89 // - everything else -> no-op
90 //
91 // On the initial call it only records configuration; Control.Start is what
92 // launches the first runner via dnsStart.
93 func (d *dnsServer) reload(c *config.C, initial bool) error {
94 wantsDns := c.GetBool("lighthouse.serve_dns", false)
95 amLighthouse := c.GetBool("lighthouse.am_lighthouse", false)
96 enabled := wantsDns && amLighthouse
97 newAddr := getDnsServerAddr(c)
98
99 d.serverMu.Lock()
100 running := d.server != nil
101 sameAddr := d.addr == newAddr
102 d.addr = newAddr
103 d.enabled.Store(enabled)
104 d.serverMu.Unlock()
105
106 if initial {
107 if wantsDns && !amLighthouse {
108 d.l.Warn("DNS server refusing to run because this host is not a lighthouse.")
109 }
110 return nil
111 }
112
113 if !enabled {
114 if running {
115 d.Stop()
116 }
117 // Drop any records that accumulated while enabled; a later re-enable
118 // will repopulate from fresh handshakes and a fresh seedSelf.
119 d.clearRecords()
120 return nil
121 }
122
123 if !running {
124 // Was disabled (or never started); bring it up now.
125 go d.Start()
126 } else if !sameAddr {
127 // Stop clears the slot before shutting down, otherwise the Start below can find the dying server and refuse
128 d.Stop()
129 go d.Start()
130 }
131
132 // Refresh the self entry every enabled reload so cert renewals that change our name or VPN addresses are picked up.
133 d.seedSelf()
134 return nil
135 }
136
137 // shutdownServer waits for the server to finish binding (so Shutdown actually
138 // stops it rather than no-oping) and then shuts it down.
139 func (d *dnsServer) shutdownServer(srv *dns.Server, started chan struct{}, reason string) {
140 if srv == nil {
141 return
142 }
143 if started != nil {
144 <-started
145 }
146 if err := srv.Shutdown(); err != nil {
147 d.l.Warn("Failed to shut down the DNS responder", "reason", reason, "error", err)
148 }
149 }
150
151 // Start binds and serves the DNS responder. Blocks until Stop is called or
152 // the listener errors. Safe to call when DNS is disabled (returns
153 // immediately). This is what Control.dnsStart points at.
154 //
155 // Must be invoked after the tun device is active so that lighthouse.dns.host
156 // may bind to a nebula IP.
157 func (d *dnsServer) Start() {
158 if !d.enabled.Load() {
159 return
160 }
161
162 started := make(chan struct{})
163 d.serverMu.Lock()
164 // Re-check enabled under the lock, a disable that raced our check above snapshots the slot under it too.
165 // Two reloads in quick succession can both spawn a Start, the loser would orphan the live listener past Stop
166 if d.ctx.Err() != nil || d.server != nil || !d.enabled.Load() {
167 d.serverMu.Unlock()
168 return
169 }
170 addr := d.addr
171 server := &dns.Server{
172 Addr: addr,
173 Net: "udp",
174 Handler: d.mux,
175 NotifyStartedFunc: func() { close(started) },
176 }
177 d.server = server
178 d.started = started
179 d.serverMu.Unlock()
180
181 // Per-invocation ctx watcher. Exits when Start does, so we don't leak a
182 // watcher per reload-driven restart.
183 done := make(chan struct{})
184 go func() {
185 select {
186 case <-d.ctx.Done():
187 d.shutdownServer(server, started, "shutdown")
188 case <-done:
189 }
190 }()
191
192 d.l.Info("Starting DNS responder", "dnsListener", addr)
193 err := server.ListenAndServe()
194 close(done)
195
196 // If the listener never bound (bind error) NotifyStartedFunc never fires,
197 // so close started here to release any Stop caller waiting on it.
198 select {
199 case <-started:
200 default:
201 close(started)
202 }
203
204 // Release our slot, unless a reload already replaced us, so a dead listener can't block a future Start
205 d.serverMu.Lock()
206 if d.server == server {
207 d.server = nil
208 d.started = nil
209 }
210 d.serverMu.Unlock()
211
212 if err != nil {
213 d.l.Warn("Failed to run the DNS responder", "error", err)
214 }
215 }
216
217 // Stop shuts down the active server, if any. Idempotent.
218 func (d *dnsServer) Stop() {
219 d.serverMu.Lock()
220 srv := d.server
221 started := d.started
222 d.server = nil
223 d.started = nil
224 d.serverMu.Unlock()
225 d.shutdownServer(srv, started, "stop")
226 }
227
228 // Query returns the address for the given name and query type. The second
229 // return value reports whether the name is known at all (in either A or AAAA),
230 // which lets callers distinguish NODATA from NXDOMAIN.
231 func (d *dnsServer) Query(q uint16, data string) (netip.Addr, bool) {
232 data = strings.ToLower(data)
233 d.RLock()
234 defer d.RUnlock()
235 addr4, haveV4 := d.dnsMap4[data]
236 addr6, haveV6 := d.dnsMap6[data]
237 nameExists := haveV4 || haveV6
238 switch q {
239 case dns.TypeA:
240 if haveV4 {
241 return addr4, nameExists
242 }
243 case dns.TypeAAAA:
244 if haveV6 {
245 return addr6, nameExists
246 }
247 }
248
249 return netip.Addr{}, nameExists
250 }
251
252 func (d *dnsServer) QueryCert(data string) string {
253 if len(data) < 2 {
254 return ""
255 }
256 ip, err := netip.ParseAddr(data[:len(data)-1])
257 if err != nil {
258 return ""
259 }
260
261 // The hostmap only ever contains peers we have handshaked with, so it never carries an entry for ourselves.
262 // Answer self lookups straight from the local cert state.
263 if cs := d.certState(); cs != nil && cs.myVpnAddrsTable != nil && cs.myVpnAddrsTable.Contains(ip) {
264 c := cs.GetDefaultCertificate()
265 if c == nil {
266 return ""
267 }
268 b, err := c.MarshalJSON()
269 if err != nil {
270 return ""
271 }
272 return string(b)
273 }
274
275 hostinfo := d.hostMap.QueryVpnAddr(ip)
276 if hostinfo == nil {
277 return ""
278 }
279
280 q := hostinfo.GetCert()
281 if q == nil {
282 return ""
283 }
284
285 b, err := q.Certificate.MarshalJSON()
286 if err != nil {
287 return ""
288 }
289 return string(b)
290 }
291
292 // clearRecords drops all DNS records, including the self entry.
293 func (d *dnsServer) clearRecords() {
294 d.Lock()
295 defer d.Unlock()
296 clear(d.dnsMap4)
297 clear(d.dnsMap6)
298 d.selfHost = ""
299 }
300
301 // seedSelf inserts (or refreshes) a record for our own cert name pointing at our VPN addresses,
302 // so a single-lighthouse network can resolve the lighthouse's own hostname without the two-process workaround.
303 func (d *dnsServer) seedSelf() {
304 if !d.enabled.Load() {
305 return
306 }
307 cs := d.certState()
308 if cs == nil {
309 return
310 }
311 c := cs.GetDefaultCertificate()
312 if c == nil {
313 return
314 }
315 newHost := strings.ToLower(c.Name()) + "."
316
317 d.Lock()
318 defer d.Unlock()
319 if d.selfHost != "" && d.selfHost != newHost {
320 delete(d.dnsMap4, d.selfHost)
321 delete(d.dnsMap6, d.selfHost)
322 }
323 d.selfHost = newHost
324 delete(d.dnsMap4, newHost)
325 delete(d.dnsMap6, newHost)
326 haveV4, haveV6 := false, false
327 for _, addr := range cs.myVpnAddrs {
328 if addr.Is4() && !haveV4 {
329 d.dnsMap4[newHost] = addr
330 haveV4 = true
331 } else if addr.Is6() && !haveV6 {
332 d.dnsMap6[newHost] = addr
333 haveV6 = true
334 }
335 if haveV4 && haveV6 {
336 break
337 }
338 }
339 }
340
341 func (d *dnsServer) certState() *CertState {
342 if d.pki == nil {
343 return nil
344 }
345 return d.pki.getCertState()
346 }
347
348 // Add adds the first IPv4 and IPv6 address that appears in `addresses` as the record for `host`
349 func (d *dnsServer) Add(host string, addresses []netip.Addr) {
350 if !d.enabled.Load() {
351 return
352 }
353 host = strings.ToLower(host)
354 d.Lock()
355 defer d.Unlock()
356 haveV4 := false
357 haveV6 := false
358 for _, addr := range addresses {
359 if addr.Is4() && !haveV4 {
360 d.dnsMap4[host] = addr
361 haveV4 = true
362 } else if addr.Is6() && !haveV6 {
363 d.dnsMap6[host] = addr
364 haveV6 = true
365 }
366 if haveV4 && haveV6 {
367 break
368 }
369 }
370 }
371
372 func (d *dnsServer) isSelfNebulaOrLocalhost(addr string) bool {
373 a, _, _ := net.SplitHostPort(addr)
374 b, err := netip.ParseAddr(a)
375 if err != nil {
376 return false
377 }
378
379 if b.IsLoopback() {
380 return true
381 }
382
383 cs := d.certState()
384 if cs == nil || cs.myVpnAddrsTable == nil {
385 return false
386 }
387 //if we found it in this table, it's good
388 return cs.myVpnAddrsTable.Contains(b)
389 }
390
391 func (d *dnsServer) parseQuery(m *dns.Msg, w dns.ResponseWriter) {
392 debugEnabled := d.l.Enabled(context.Background(), slog.LevelDebug)
393 // Per RFC 2308 §2.2, a name that exists but has no record of the requested
394 // type must be answered with NOERROR and an empty answer section (NODATA),
395 // not NXDOMAIN (RFC 2308 §2.1), which is reserved for names that do not
396 // exist at all.
397 anyNameExists := false
398 for _, q := range m.Question {
399 switch q.Qtype {
400 case dns.TypeA, dns.TypeAAAA:
401 qType := dns.TypeToString[q.Qtype]
402 if debugEnabled {
403 d.l.Debug("DNS query", "type", qType, "name", q.Name)
404 }
405 ip, nameExists := d.Query(q.Qtype, q.Name)
406 if nameExists {
407 anyNameExists = true
408 }
409 if ip.IsValid() {
410 rr, err := dns.NewRR(fmt.Sprintf("%s %s %s", q.Name, qType, ip))
411 if err == nil {
412 m.Answer = append(m.Answer, rr)
413 }
414 }
415 case dns.TypeTXT:
416 // We only answer these queries from nebula nodes or localhost
417 if !d.isSelfNebulaOrLocalhost(w.RemoteAddr().String()) {
418 return
419 }
420 if debugEnabled {
421 d.l.Debug("DNS query", "type", "TXT", "name", q.Name)
422 }
423 ip := d.QueryCert(q.Name)
424 if ip != "" {
425 rr, err := dns.NewRR(fmt.Sprintf("%s TXT %s", q.Name, ip))
426 if err == nil {
427 m.Answer = append(m.Answer, rr)
428 }
429 }
430 }
431 }
432
433 if len(m.Answer) == 0 && !anyNameExists {
434 m.Rcode = dns.RcodeNameError
435 }
436 }
437
438 func (d *dnsServer) handleDnsRequest(w dns.ResponseWriter, r *dns.Msg) {
439 m := new(dns.Msg)
440 m.SetReply(r)
441 m.Compress = false
442
443 switch r.Opcode {
444 case dns.OpcodeQuery:
445 d.parseQuery(m, w)
446 }
447
448 w.WriteMsg(m)
449 }
450
451 func getDnsServerAddr(c *config.C) string {
452 dnsHost := strings.TrimSpace(c.GetString("lighthouse.dns.host", ""))
453 // Old guidance was to provide the literal `[::]` in `lighthouse.dns.host` but that won't resolve.
454 if dnsHost == "[::]" {
455 dnsHost = "::"
456 }
457 return net.JoinHostPort(dnsHost, strconv.Itoa(c.GetInt("lighthouse.dns.port", 53)))
458 }