dns_server.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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
  89. runningStarted := d.started
  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 != nil {
  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 == nil {
  110. // Was disabled (or never started); bring it up now.
  111. go d.Start()
  112. } else if !sameAddr {
  113. d.shutdownServer(running, runningStarted, "reload")
  114. // Old Start goroutine has now exited; bring up a fresh listener on the new address.
  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. if d.ctx.Err() != nil {
  147. d.serverMu.Unlock()
  148. return
  149. }
  150. addr := d.addr
  151. server := &dns.Server{
  152. Addr: addr,
  153. Net: "udp",
  154. Handler: d.mux,
  155. NotifyStartedFunc: func() { close(started) },
  156. }
  157. d.server = server
  158. d.started = started
  159. d.serverMu.Unlock()
  160. // Per-invocation ctx watcher. Exits when Start does, so we don't leak a
  161. // watcher per reload-driven restart.
  162. done := make(chan struct{})
  163. go func() {
  164. select {
  165. case <-d.ctx.Done():
  166. d.shutdownServer(server, started, "shutdown")
  167. case <-done:
  168. }
  169. }()
  170. d.l.Info("Starting DNS responder", "dnsListener", addr)
  171. err := server.ListenAndServe()
  172. close(done)
  173. // If the listener never bound (bind error) NotifyStartedFunc never fires,
  174. // so close started here to release any Stop caller waiting on it.
  175. select {
  176. case <-started:
  177. default:
  178. close(started)
  179. }
  180. if err != nil {
  181. d.l.Warn("Failed to run the DNS responder", "error", err)
  182. }
  183. }
  184. // Stop shuts down the active server, if any. Idempotent.
  185. func (d *dnsServer) Stop() {
  186. d.serverMu.Lock()
  187. srv := d.server
  188. started := d.started
  189. d.server = nil
  190. d.started = nil
  191. d.serverMu.Unlock()
  192. d.shutdownServer(srv, started, "stop")
  193. }
  194. // Query returns the address for the given name and query type. The second
  195. // return value reports whether the name is known at all (in either A or AAAA),
  196. // which lets callers distinguish NODATA from NXDOMAIN.
  197. func (d *dnsServer) Query(q uint16, data string) (netip.Addr, bool) {
  198. data = strings.ToLower(data)
  199. d.RLock()
  200. defer d.RUnlock()
  201. addr4, haveV4 := d.dnsMap4[data]
  202. addr6, haveV6 := d.dnsMap6[data]
  203. nameExists := haveV4 || haveV6
  204. switch q {
  205. case dns.TypeA:
  206. if haveV4 {
  207. return addr4, nameExists
  208. }
  209. case dns.TypeAAAA:
  210. if haveV6 {
  211. return addr6, nameExists
  212. }
  213. }
  214. return netip.Addr{}, nameExists
  215. }
  216. func (d *dnsServer) QueryCert(data string) string {
  217. if len(data) < 2 {
  218. return ""
  219. }
  220. ip, err := netip.ParseAddr(data[:len(data)-1])
  221. if err != nil {
  222. return ""
  223. }
  224. // The hostmap only ever contains peers we have handshaked with, so it never carries an entry for ourselves.
  225. // Answer self lookups straight from the local cert state.
  226. if cs := d.certState(); cs != nil && cs.myVpnAddrsTable != nil && cs.myVpnAddrsTable.Contains(ip) {
  227. c := cs.GetDefaultCertificate()
  228. if c == nil {
  229. return ""
  230. }
  231. b, err := c.MarshalJSON()
  232. if err != nil {
  233. return ""
  234. }
  235. return string(b)
  236. }
  237. hostinfo := d.hostMap.QueryVpnAddr(ip)
  238. if hostinfo == nil {
  239. return ""
  240. }
  241. q := hostinfo.GetCert()
  242. if q == nil {
  243. return ""
  244. }
  245. b, err := q.Certificate.MarshalJSON()
  246. if err != nil {
  247. return ""
  248. }
  249. return string(b)
  250. }
  251. // clearRecords drops all DNS records, including the self entry.
  252. func (d *dnsServer) clearRecords() {
  253. d.Lock()
  254. defer d.Unlock()
  255. clear(d.dnsMap4)
  256. clear(d.dnsMap6)
  257. d.selfHost = ""
  258. }
  259. // seedSelf inserts (or refreshes) a record for our own cert name pointing at our VPN addresses,
  260. // so a single-lighthouse network can resolve the lighthouse's own hostname without the two-process workaround.
  261. func (d *dnsServer) seedSelf() {
  262. if !d.enabled.Load() {
  263. return
  264. }
  265. cs := d.certState()
  266. if cs == nil {
  267. return
  268. }
  269. c := cs.GetDefaultCertificate()
  270. if c == nil {
  271. return
  272. }
  273. newHost := strings.ToLower(c.Name()) + "."
  274. d.Lock()
  275. defer d.Unlock()
  276. if d.selfHost != "" && d.selfHost != newHost {
  277. delete(d.dnsMap4, d.selfHost)
  278. delete(d.dnsMap6, d.selfHost)
  279. }
  280. d.selfHost = newHost
  281. delete(d.dnsMap4, newHost)
  282. delete(d.dnsMap6, newHost)
  283. haveV4, haveV6 := false, false
  284. for _, addr := range cs.myVpnAddrs {
  285. if addr.Is4() && !haveV4 {
  286. d.dnsMap4[newHost] = addr
  287. haveV4 = true
  288. } else if addr.Is6() && !haveV6 {
  289. d.dnsMap6[newHost] = addr
  290. haveV6 = true
  291. }
  292. if haveV4 && haveV6 {
  293. break
  294. }
  295. }
  296. }
  297. func (d *dnsServer) certState() *CertState {
  298. if d.pki == nil {
  299. return nil
  300. }
  301. return d.pki.getCertState()
  302. }
  303. // Add adds the first IPv4 and IPv6 address that appears in `addresses` as the record for `host`
  304. func (d *dnsServer) Add(host string, addresses []netip.Addr) {
  305. if !d.enabled.Load() {
  306. return
  307. }
  308. host = strings.ToLower(host)
  309. d.Lock()
  310. defer d.Unlock()
  311. haveV4 := false
  312. haveV6 := false
  313. for _, addr := range addresses {
  314. if addr.Is4() && !haveV4 {
  315. d.dnsMap4[host] = addr
  316. haveV4 = true
  317. } else if addr.Is6() && !haveV6 {
  318. d.dnsMap6[host] = addr
  319. haveV6 = true
  320. }
  321. if haveV4 && haveV6 {
  322. break
  323. }
  324. }
  325. }
  326. func (d *dnsServer) isSelfNebulaOrLocalhost(addr string) bool {
  327. a, _, _ := net.SplitHostPort(addr)
  328. b, err := netip.ParseAddr(a)
  329. if err != nil {
  330. return false
  331. }
  332. if b.IsLoopback() {
  333. return true
  334. }
  335. cs := d.certState()
  336. if cs == nil || cs.myVpnAddrsTable == nil {
  337. return false
  338. }
  339. //if we found it in this table, it's good
  340. return cs.myVpnAddrsTable.Contains(b)
  341. }
  342. func (d *dnsServer) parseQuery(m *dns.Msg, w dns.ResponseWriter) {
  343. debugEnabled := d.l.Enabled(context.Background(), slog.LevelDebug)
  344. // Per RFC 2308 §2.2, a name that exists but has no record of the requested
  345. // type must be answered with NOERROR and an empty answer section (NODATA),
  346. // not NXDOMAIN (RFC 2308 §2.1), which is reserved for names that do not
  347. // exist at all.
  348. anyNameExists := false
  349. for _, q := range m.Question {
  350. switch q.Qtype {
  351. case dns.TypeA, dns.TypeAAAA:
  352. qType := dns.TypeToString[q.Qtype]
  353. if debugEnabled {
  354. d.l.Debug("DNS query", "type", qType, "name", q.Name)
  355. }
  356. ip, nameExists := d.Query(q.Qtype, q.Name)
  357. if nameExists {
  358. anyNameExists = true
  359. }
  360. if ip.IsValid() {
  361. rr, err := dns.NewRR(fmt.Sprintf("%s %s %s", q.Name, qType, ip))
  362. if err == nil {
  363. m.Answer = append(m.Answer, rr)
  364. }
  365. }
  366. case dns.TypeTXT:
  367. // We only answer these queries from nebula nodes or localhost
  368. if !d.isSelfNebulaOrLocalhost(w.RemoteAddr().String()) {
  369. return
  370. }
  371. if debugEnabled {
  372. d.l.Debug("DNS query", "type", "TXT", "name", q.Name)
  373. }
  374. ip := d.QueryCert(q.Name)
  375. if ip != "" {
  376. rr, err := dns.NewRR(fmt.Sprintf("%s TXT %s", q.Name, ip))
  377. if err == nil {
  378. m.Answer = append(m.Answer, rr)
  379. }
  380. }
  381. }
  382. }
  383. if len(m.Answer) == 0 && !anyNameExists {
  384. m.Rcode = dns.RcodeNameError
  385. }
  386. }
  387. func (d *dnsServer) handleDnsRequest(w dns.ResponseWriter, r *dns.Msg) {
  388. m := new(dns.Msg)
  389. m.SetReply(r)
  390. m.Compress = false
  391. switch r.Opcode {
  392. case dns.OpcodeQuery:
  393. d.parseQuery(m, w)
  394. }
  395. w.WriteMsg(m)
  396. }
  397. func getDnsServerAddr(c *config.C) string {
  398. dnsHost := strings.TrimSpace(c.GetString("lighthouse.dns.host", ""))
  399. // Old guidance was to provide the literal `[::]` in `lighthouse.dns.host` but that won't resolve.
  400. if dnsHost == "[::]" {
  401. dnsHost = "::"
  402. }
  403. return net.JoinHostPort(dnsHost, strconv.Itoa(c.GetInt("lighthouse.dns.port", 53)))
  404. }