dns_server.go 12 KB

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