dns_server.go 12 KB

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