1
0

dns_server.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. crt, _ := findCertificateForVpnAddr(d.certState(), d.hostMap, ip)
  234. if crt == nil {
  235. return ""
  236. }
  237. b, err := crt.MarshalJSON()
  238. if err != nil {
  239. return ""
  240. }
  241. return string(b)
  242. }
  243. // clearRecords drops all DNS records, including the self entry.
  244. func (d *dnsServer) clearRecords() {
  245. d.Lock()
  246. defer d.Unlock()
  247. clear(d.dnsMap4)
  248. clear(d.dnsMap6)
  249. d.selfHost = ""
  250. }
  251. // seedSelf inserts (or refreshes) a record for our own cert name pointing at our VPN addresses,
  252. // so a single-lighthouse network can resolve the lighthouse's own hostname without the two-process workaround.
  253. func (d *dnsServer) seedSelf() {
  254. if !d.enabled.Load() {
  255. return
  256. }
  257. cs := d.certState()
  258. if cs == nil {
  259. return
  260. }
  261. c := cs.GetDefaultCertificate()
  262. if c == nil {
  263. return
  264. }
  265. newHost := strings.ToLower(c.Name()) + "."
  266. d.Lock()
  267. defer d.Unlock()
  268. if d.selfHost != "" && d.selfHost != newHost {
  269. delete(d.dnsMap4, d.selfHost)
  270. delete(d.dnsMap6, d.selfHost)
  271. }
  272. d.selfHost = newHost
  273. delete(d.dnsMap4, newHost)
  274. delete(d.dnsMap6, newHost)
  275. haveV4, haveV6 := false, false
  276. for _, addr := range cs.myVpnAddrs {
  277. if addr.Is4() && !haveV4 {
  278. d.dnsMap4[newHost] = addr
  279. haveV4 = true
  280. } else if addr.Is6() && !haveV6 {
  281. d.dnsMap6[newHost] = addr
  282. haveV6 = true
  283. }
  284. if haveV4 && haveV6 {
  285. break
  286. }
  287. }
  288. }
  289. func (d *dnsServer) certState() *CertState {
  290. if d.pki == nil {
  291. return nil
  292. }
  293. return d.pki.getCertState()
  294. }
  295. // Add adds the first IPv4 and IPv6 address that appears in `addresses` as the record for `host`
  296. func (d *dnsServer) Add(host string, addresses []netip.Addr) {
  297. if !d.enabled.Load() {
  298. return
  299. }
  300. host = strings.ToLower(host)
  301. d.Lock()
  302. defer d.Unlock()
  303. haveV4 := false
  304. haveV6 := false
  305. for _, addr := range addresses {
  306. if addr.Is4() && !haveV4 {
  307. d.dnsMap4[host] = addr
  308. haveV4 = true
  309. } else if addr.Is6() && !haveV6 {
  310. d.dnsMap6[host] = addr
  311. haveV6 = true
  312. }
  313. if haveV4 && haveV6 {
  314. break
  315. }
  316. }
  317. }
  318. func (d *dnsServer) isSelfNebulaOrLocalhost(addr string) bool {
  319. a, _, _ := net.SplitHostPort(addr)
  320. b, err := netip.ParseAddr(a)
  321. if err != nil {
  322. return false
  323. }
  324. if b.IsLoopback() {
  325. return true
  326. }
  327. cs := d.certState()
  328. if cs == nil || cs.myVpnAddrsTable == nil {
  329. return false
  330. }
  331. //if we found it in this table, it's good
  332. return cs.myVpnAddrsTable.Contains(b)
  333. }
  334. func (d *dnsServer) parseQuery(m *dns.Msg, w dns.ResponseWriter) {
  335. debugEnabled := d.l.Enabled(context.Background(), slog.LevelDebug)
  336. // Per RFC 2308 §2.2, a name that exists but has no record of the requested
  337. // type must be answered with NOERROR and an empty answer section (NODATA),
  338. // not NXDOMAIN (RFC 2308 §2.1), which is reserved for names that do not
  339. // exist at all.
  340. anyNameExists := false
  341. for _, q := range m.Question {
  342. switch q.Qtype {
  343. case dns.TypeA, dns.TypeAAAA:
  344. qType := dns.TypeToString[q.Qtype]
  345. if debugEnabled {
  346. d.l.Debug("DNS query", "type", qType, "name", q.Name)
  347. }
  348. ip, nameExists := d.Query(q.Qtype, q.Name)
  349. if nameExists {
  350. anyNameExists = true
  351. }
  352. if ip.IsValid() {
  353. rr, err := dns.NewRR(fmt.Sprintf("%s %s %s", q.Name, qType, ip))
  354. if err == nil {
  355. m.Answer = append(m.Answer, rr)
  356. }
  357. }
  358. case dns.TypeTXT:
  359. // We only answer these queries from nebula nodes or localhost
  360. if !d.isSelfNebulaOrLocalhost(w.RemoteAddr().String()) {
  361. return
  362. }
  363. if debugEnabled {
  364. d.l.Debug("DNS query", "type", "TXT", "name", q.Name)
  365. }
  366. ip := d.QueryCert(q.Name)
  367. if ip != "" {
  368. rr, err := dns.NewRR(fmt.Sprintf("%s TXT %s", q.Name, ip))
  369. if err == nil {
  370. m.Answer = append(m.Answer, rr)
  371. }
  372. }
  373. }
  374. }
  375. if len(m.Answer) == 0 && !anyNameExists {
  376. m.Rcode = dns.RcodeNameError
  377. }
  378. }
  379. func (d *dnsServer) handleDnsRequest(w dns.ResponseWriter, r *dns.Msg) {
  380. m := new(dns.Msg)
  381. m.SetReply(r)
  382. m.Compress = false
  383. switch r.Opcode {
  384. case dns.OpcodeQuery:
  385. d.parseQuery(m, w)
  386. }
  387. w.WriteMsg(m)
  388. }
  389. func getDnsServerAddr(c *config.C) string {
  390. dnsHost := strings.TrimSpace(c.GetString("lighthouse.dns.host", ""))
  391. // Old guidance was to provide the literal `[::]` in `lighthouse.dns.host` but that won't resolve.
  392. if dnsHost == "[::]" {
  393. dnsHost = "::"
  394. }
  395. return net.JoinHostPort(dnsHost, strconv.Itoa(c.GetInt("lighthouse.dns.port", 53)))
  396. }