dns_server.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. package nebula
  2. import (
  3. "context"
  4. "fmt"
  5. "net"
  6. "net/netip"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "sync/atomic"
  11. "github.com/gaissmai/bart"
  12. "github.com/miekg/dns"
  13. "github.com/sirupsen/logrus"
  14. "github.com/slackhq/nebula/config"
  15. )
  16. type dnsServer struct {
  17. sync.RWMutex
  18. l *logrus.Logger
  19. ctx context.Context
  20. dnsMap4 map[string]netip.Addr
  21. dnsMap6 map[string]netip.Addr
  22. hostMap *HostMap
  23. myVpnAddrsTable *bart.Lite
  24. mux *dns.ServeMux
  25. // enabled mirrors `lighthouse.serve_dns && lighthouse.am_lighthouse`.
  26. // Start, Add, and reload consult it so callers don't need to know the
  27. // gating rules. When it toggles off via reload, accumulated records are
  28. // cleared so a later re-enable starts with a fresh map populated from
  29. // new handshakes.
  30. enabled atomic.Bool
  31. serverMu sync.Mutex
  32. server *dns.Server
  33. // started is closed once `server` has finished binding (or after
  34. // ListenAndServe returns on a bind failure). Stop waits on it before
  35. // calling Shutdown to avoid the miekg/dns "server not started" race
  36. // where a Shutdown that arrives before bind completes is silently
  37. // ignored, leaving the listener running forever.
  38. started chan struct{}
  39. addr string
  40. }
  41. // newDnsServerFromConfig builds a dnsServer, applies the initial config, and
  42. // registers a reload callback. The reload callback is registered before the
  43. // initial config is applied, so a SIGHUP can later enable, fix, or disable
  44. // DNS even if the initial application failed.
  45. //
  46. // The dnsServer internally gates on `lighthouse.serve_dns &&
  47. // lighthouse.am_lighthouse`. Start and Add are safe to call unconditionally,
  48. // they no-op when DNS isn't enabled. Each Start invocation owns a ctx-cancel
  49. // watcher that tears the listener down on nebula shutdown. The returned
  50. // pointer is always non-nil, even on error.
  51. func newDnsServerFromConfig(ctx context.Context, l *logrus.Logger, cs *CertState, hostMap *HostMap, c *config.C) (*dnsServer, error) {
  52. ds := &dnsServer{
  53. l: l,
  54. ctx: ctx,
  55. dnsMap4: make(map[string]netip.Addr),
  56. dnsMap6: make(map[string]netip.Addr),
  57. hostMap: hostMap,
  58. myVpnAddrsTable: cs.myVpnAddrsTable,
  59. }
  60. ds.mux = dns.NewServeMux()
  61. ds.mux.HandleFunc(".", ds.handleDnsRequest)
  62. c.RegisterReloadCallback(func(c *config.C) {
  63. if err := ds.reload(c, false); err != nil {
  64. l.WithError(err).Error("Failed to reload DNS responder from config")
  65. }
  66. })
  67. if err := ds.reload(c, true); err != nil {
  68. return ds, err
  69. }
  70. return ds, nil
  71. }
  72. // reload applies the latest config and reconciles the running state with it:
  73. // - enabled toggled on -> spawn a runner
  74. // - enabled toggled off -> stop the runner
  75. // - listen address changed (while running) -> restart on the new address
  76. // - everything else -> no-op
  77. //
  78. // On the initial call it only records configuration; Control.Start is what
  79. // launches the first runner via dnsStart.
  80. func (d *dnsServer) reload(c *config.C, initial bool) error {
  81. wantsDns := c.GetBool("lighthouse.serve_dns", false)
  82. amLighthouse := c.GetBool("lighthouse.am_lighthouse", false)
  83. enabled := wantsDns && amLighthouse
  84. newAddr := getDnsServerAddr(c)
  85. d.serverMu.Lock()
  86. running := d.server
  87. runningStarted := d.started
  88. sameAddr := d.addr == newAddr
  89. d.addr = newAddr
  90. d.enabled.Store(enabled)
  91. d.serverMu.Unlock()
  92. if initial {
  93. if wantsDns && !amLighthouse {
  94. d.l.Warn("DNS server refusing to run because this host is not a lighthouse.")
  95. }
  96. return nil
  97. }
  98. if !enabled {
  99. if running != nil {
  100. d.Stop()
  101. }
  102. // Drop any records that accumulated while enabled; a later re-enable
  103. // will repopulate from fresh handshakes.
  104. d.clearRecords()
  105. return nil
  106. }
  107. if running == nil {
  108. // Was disabled (or never started); bring it up now.
  109. go d.Start()
  110. return nil
  111. }
  112. if sameAddr {
  113. return nil
  114. }
  115. d.shutdownServer(running, runningStarted, "reload")
  116. // Old Start goroutine has now exited; bring up a fresh listener on the
  117. // new address.
  118. go d.Start()
  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.WithError(err).WithField("reason", reason).Warn("Failed to shut down the DNS responder")
  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.WithField("dnsListener", addr).Info("Starting DNS responder")
  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.WithError(err).Warn("Failed to run the DNS responder")
  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. func (d *dnsServer) Query(q uint16, data string) netip.Addr {
  195. data = strings.ToLower(data)
  196. d.RLock()
  197. defer d.RUnlock()
  198. switch q {
  199. case dns.TypeA:
  200. if r, ok := d.dnsMap4[data]; ok {
  201. return r
  202. }
  203. case dns.TypeAAAA:
  204. if r, ok := d.dnsMap6[data]; ok {
  205. return r
  206. }
  207. }
  208. return netip.Addr{}
  209. }
  210. func (d *dnsServer) QueryCert(data string) string {
  211. ip, err := netip.ParseAddr(data[:len(data)-1])
  212. if err != nil {
  213. return ""
  214. }
  215. hostinfo := d.hostMap.QueryVpnAddr(ip)
  216. if hostinfo == nil {
  217. return ""
  218. }
  219. q := hostinfo.GetCert()
  220. if q == nil {
  221. return ""
  222. }
  223. b, err := q.Certificate.MarshalJSON()
  224. if err != nil {
  225. return ""
  226. }
  227. return string(b)
  228. }
  229. // clearRecords drops all DNS records.
  230. func (d *dnsServer) clearRecords() {
  231. d.Lock()
  232. defer d.Unlock()
  233. clear(d.dnsMap4)
  234. clear(d.dnsMap6)
  235. }
  236. // Add adds the first IPv4 and IPv6 address that appears in `addresses` as the record for `host`
  237. func (d *dnsServer) Add(host string, addresses []netip.Addr) {
  238. if !d.enabled.Load() {
  239. return
  240. }
  241. host = strings.ToLower(host)
  242. d.Lock()
  243. defer d.Unlock()
  244. haveV4 := false
  245. haveV6 := false
  246. for _, addr := range addresses {
  247. if addr.Is4() && !haveV4 {
  248. d.dnsMap4[host] = addr
  249. haveV4 = true
  250. } else if addr.Is6() && !haveV6 {
  251. d.dnsMap6[host] = addr
  252. haveV6 = true
  253. }
  254. if haveV4 && haveV6 {
  255. break
  256. }
  257. }
  258. }
  259. func (d *dnsServer) isSelfNebulaOrLocalhost(addr string) bool {
  260. a, _, _ := net.SplitHostPort(addr)
  261. b, err := netip.ParseAddr(a)
  262. if err != nil {
  263. return false
  264. }
  265. if b.IsLoopback() {
  266. return true
  267. }
  268. //if we found it in this table, it's good
  269. return d.myVpnAddrsTable.Contains(b)
  270. }
  271. func (d *dnsServer) parseQuery(m *dns.Msg, w dns.ResponseWriter) {
  272. for _, q := range m.Question {
  273. switch q.Qtype {
  274. case dns.TypeA, dns.TypeAAAA:
  275. qType := dns.TypeToString[q.Qtype]
  276. d.l.Debugf("Query for %s %s", qType, q.Name)
  277. ip := d.Query(q.Qtype, q.Name)
  278. if ip.IsValid() {
  279. rr, err := dns.NewRR(fmt.Sprintf("%s %s %s", q.Name, qType, ip))
  280. if err == nil {
  281. m.Answer = append(m.Answer, rr)
  282. }
  283. }
  284. case dns.TypeTXT:
  285. // We only answer these queries from nebula nodes or localhost
  286. if !d.isSelfNebulaOrLocalhost(w.RemoteAddr().String()) {
  287. return
  288. }
  289. d.l.Debugf("Query for TXT %s", q.Name)
  290. ip := d.QueryCert(q.Name)
  291. if ip != "" {
  292. rr, err := dns.NewRR(fmt.Sprintf("%s TXT %s", q.Name, ip))
  293. if err == nil {
  294. m.Answer = append(m.Answer, rr)
  295. }
  296. }
  297. }
  298. }
  299. if len(m.Answer) == 0 {
  300. m.Rcode = dns.RcodeNameError
  301. }
  302. }
  303. func (d *dnsServer) handleDnsRequest(w dns.ResponseWriter, r *dns.Msg) {
  304. m := new(dns.Msg)
  305. m.SetReply(r)
  306. m.Compress = false
  307. switch r.Opcode {
  308. case dns.OpcodeQuery:
  309. d.parseQuery(m, w)
  310. }
  311. w.WriteMsg(m)
  312. }
  313. func getDnsServerAddr(c *config.C) string {
  314. dnsHost := strings.TrimSpace(c.GetString("lighthouse.dns.host", ""))
  315. // Old guidance was to provide the literal `[::]` in `lighthouse.dns.host` but that won't resolve.
  316. if dnsHost == "[::]" {
  317. dnsHost = "::"
  318. }
  319. return net.JoinHostPort(dnsHost, strconv.Itoa(c.GetInt("lighthouse.dns.port", 53)))
  320. }