resolvconf.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16:
  2. //go:build go1.21
  3. // Package resolvconf is used to generate a container's /etc/resolv.conf file.
  4. //
  5. // Constructor Load and Parse read a resolv.conf file from the filesystem or
  6. // a reader respectively, and return a ResolvConf object.
  7. //
  8. // The ResolvConf object can then be updated with overrides for nameserver,
  9. // search domains, and DNS options.
  10. //
  11. // ResolvConf can then be transformed to make it suitable for legacy networking,
  12. // a network with an internal nameserver, or used as-is for host networking.
  13. //
  14. // This package includes methods to write the file for the container, along with
  15. // a hash that can be used to detect modifications made by the user to avoid
  16. // overwriting those updates.
  17. package resolvconf
  18. import (
  19. "bufio"
  20. "bytes"
  21. "context"
  22. "fmt"
  23. "io"
  24. "io/fs"
  25. "net/netip"
  26. "os"
  27. "strconv"
  28. "strings"
  29. "text/template"
  30. "github.com/containerd/log"
  31. "github.com/docker/docker/errdefs"
  32. "github.com/docker/docker/pkg/ioutils"
  33. "github.com/opencontainers/go-digest"
  34. "github.com/pkg/errors"
  35. )
  36. // Fallback nameservers, to use if none can be obtained from the host or command
  37. // line options.
  38. var (
  39. defaultIPv4NSs = []netip.Addr{
  40. netip.MustParseAddr("8.8.8.8"),
  41. netip.MustParseAddr("8.8.4.4"),
  42. }
  43. defaultIPv6NSs = []netip.Addr{
  44. netip.MustParseAddr("2001:4860:4860::8888"),
  45. netip.MustParseAddr("2001:4860:4860::8844"),
  46. }
  47. )
  48. // ResolvConf represents a resolv.conf file. It can be constructed by
  49. // reading a resolv.conf file, using method Parse().
  50. type ResolvConf struct {
  51. nameServers []netip.Addr
  52. search []string
  53. options []string
  54. other []string // Unrecognised directives from the host's file, if any.
  55. md metadata
  56. }
  57. // ExtDNSEntry represents a nameserver address that was removed from the
  58. // container's resolv.conf when it was transformed by TransformForIntNS(). These
  59. // are addresses read from the host's file, or applied via an override ('--dns').
  60. type ExtDNSEntry struct {
  61. Addr netip.Addr
  62. HostLoopback bool // The address is loopback, in the host's namespace.
  63. }
  64. func (ed ExtDNSEntry) String() string {
  65. if ed.HostLoopback {
  66. return fmt.Sprintf("host(%s)", ed.Addr)
  67. }
  68. return ed.Addr.String()
  69. }
  70. // metadata is used to track where components of the generated file have come
  71. // from, in order to generate comments in the file for debug/info. Struct members
  72. // are exported for use by 'text/template'.
  73. type metadata struct {
  74. SourcePath string
  75. Header string
  76. NSOverride bool
  77. SearchOverride bool
  78. OptionsOverride bool
  79. NDotsFrom string
  80. UsedDefaultNS bool
  81. Transform string
  82. InvalidNSs []string
  83. ExtNameServers []ExtDNSEntry
  84. }
  85. // Load opens a file at path and parses it as a resolv.conf file.
  86. // On error, the returned ResolvConf will be zero-valued.
  87. func Load(path string) (ResolvConf, error) {
  88. f, err := os.Open(path)
  89. if err != nil {
  90. return ResolvConf{}, err
  91. }
  92. defer f.Close()
  93. return Parse(f, path)
  94. }
  95. // Parse parses a resolv.conf file from reader.
  96. // path is optional if reader is an *os.File.
  97. // On error, the returned ResolvConf will be zero-valued.
  98. func Parse(reader io.Reader, path string) (ResolvConf, error) {
  99. var rc ResolvConf
  100. rc.md.SourcePath = path
  101. if path == "" {
  102. if namer, ok := reader.(interface{ Name() string }); ok {
  103. rc.md.SourcePath = namer.Name()
  104. }
  105. }
  106. scanner := bufio.NewScanner(reader)
  107. for scanner.Scan() {
  108. rc.processLine(scanner.Text())
  109. }
  110. if err := scanner.Err(); err != nil {
  111. return ResolvConf{}, errdefs.System(err)
  112. }
  113. if _, ok := rc.Option("ndots"); ok {
  114. rc.md.NDotsFrom = "host"
  115. }
  116. return rc, nil
  117. }
  118. // SetHeader sets the content to be included verbatim at the top of the
  119. // generated resolv.conf file. No formatting or checking is done on the
  120. // string. It must be valid resolv.conf syntax. (Comments must have '#'
  121. // or ';' in the first column of each line).
  122. //
  123. // For example:
  124. //
  125. // SetHeader("# My resolv.conf\n# This file was generated.")
  126. func (rc *ResolvConf) SetHeader(c string) {
  127. rc.md.Header = c
  128. }
  129. // NameServers returns addresses used in nameserver directives.
  130. func (rc *ResolvConf) NameServers() []netip.Addr {
  131. return append([]netip.Addr(nil), rc.nameServers...)
  132. }
  133. // OverrideNameServers replaces the current set of nameservers.
  134. func (rc *ResolvConf) OverrideNameServers(nameServers []netip.Addr) {
  135. rc.nameServers = nameServers
  136. rc.md.NSOverride = true
  137. }
  138. // Search returns the current DNS search domains.
  139. func (rc *ResolvConf) Search() []string {
  140. return append([]string(nil), rc.search...)
  141. }
  142. // OverrideSearch replaces the current DNS search domains.
  143. func (rc *ResolvConf) OverrideSearch(search []string) {
  144. var filtered []string
  145. for _, s := range search {
  146. if s != "." {
  147. filtered = append(filtered, s)
  148. }
  149. }
  150. rc.search = filtered
  151. rc.md.SearchOverride = true
  152. }
  153. // Options returns the current options.
  154. func (rc *ResolvConf) Options() []string {
  155. return append([]string(nil), rc.options...)
  156. }
  157. // Option finds the last option named search, and returns (value, true) if
  158. // found, else ("", false). Options are treated as "name:value", where the
  159. // ":value" may be omitted.
  160. //
  161. // For example, for "ndots:1 edns0":
  162. //
  163. // Option("ndots") -> ("1", true)
  164. // Option("edns0") -> ("", true)
  165. func (rc *ResolvConf) Option(search string) (string, bool) {
  166. for i := len(rc.options) - 1; i >= 0; i -= 1 {
  167. k, v, _ := strings.Cut(rc.options[i], ":")
  168. if k == search {
  169. return v, true
  170. }
  171. }
  172. return "", false
  173. }
  174. // OverrideOptions replaces the current DNS options.
  175. func (rc *ResolvConf) OverrideOptions(options []string) {
  176. rc.options = append([]string(nil), options...)
  177. rc.md.NDotsFrom = ""
  178. if _, exists := rc.Option("ndots"); exists {
  179. rc.md.NDotsFrom = "override"
  180. }
  181. rc.md.OptionsOverride = true
  182. }
  183. // AddOption adds a single DNS option.
  184. func (rc *ResolvConf) AddOption(option string) {
  185. if len(option) > 6 && option[:6] == "ndots:" {
  186. rc.md.NDotsFrom = "internal"
  187. }
  188. rc.options = append(rc.options, option)
  189. }
  190. // TransformForLegacyNw makes sure the resolv.conf file will be suitable for
  191. // use in a legacy network (one that has no internal resolver).
  192. // - Remove loopback addresses inherited from the host's resolv.conf, because
  193. // they'll only work in the host's namespace.
  194. // - Remove IPv6 addresses if !ipv6.
  195. // - Add default nameservers if there are no addresses left.
  196. func (rc *ResolvConf) TransformForLegacyNw(ipv6 bool) {
  197. rc.md.Transform = "legacy"
  198. if rc.md.NSOverride {
  199. return
  200. }
  201. var filtered []netip.Addr
  202. for _, addr := range rc.nameServers {
  203. if !addr.IsLoopback() && (!addr.Is6() || ipv6) {
  204. filtered = append(filtered, addr)
  205. }
  206. }
  207. rc.nameServers = filtered
  208. if len(rc.nameServers) == 0 {
  209. log.G(context.TODO()).Info("No non-localhost DNS nameservers are left in resolv.conf. Using default external servers")
  210. rc.nameServers = defaultNSAddrs(ipv6)
  211. rc.md.UsedDefaultNS = true
  212. }
  213. }
  214. // TransformForIntNS makes sure the resolv.conf file will be suitable for
  215. // use in a network sandbox that has an internal DNS resolver.
  216. // - Add internalNS as a nameserver.
  217. // - Remove other nameservers, stashing them as ExtNameServers for the
  218. // internal resolver to use.
  219. // - Mark ExtNameServers that must be used in the host namespace.
  220. // - If no ExtNameServer addresses are found, use the defaults.
  221. // - Return an error if an "ndots" option inherited from the host's config, or
  222. // supplied in an override is not valid.
  223. // - Ensure there's an 'options' value for each entry in reqdOptions. If the
  224. // option includes a ':', and an option with a matching prefix exists, it
  225. // is not modified.
  226. func (rc *ResolvConf) TransformForIntNS(
  227. ipv6 bool,
  228. internalNS netip.Addr,
  229. reqdOptions []string,
  230. ) ([]ExtDNSEntry, error) {
  231. // The transformed config must list the internal nameserver.
  232. newNSs := []netip.Addr{internalNS}
  233. // Filter out other nameservers, keeping them for use as upstream nameservers by the
  234. // internal nameserver.
  235. rc.md.ExtNameServers = nil
  236. for _, addr := range rc.nameServers {
  237. // Extract this NS. Mark addresses that did not come from an override, but will
  238. // definitely not work in the container's namespace as 'HostLoopback'. Upstream
  239. // requests for these servers will be made in the host's network namespace. (So,
  240. // '--dns 127.0.0.53' means use a nameserver listening on the container's
  241. // loopback interface. But, if the host's resolv.conf contains 'nameserver
  242. // 127.0.0.53', the host's resolver will be used.)
  243. rc.md.ExtNameServers = append(rc.md.ExtNameServers, ExtDNSEntry{
  244. Addr: addr,
  245. HostLoopback: !rc.md.NSOverride && (addr.IsLoopback() || (addr.Is6() && !ipv6) || addr.Zone() != ""),
  246. })
  247. }
  248. rc.nameServers = newNSs
  249. // If there are no external nameservers, and the only nameserver left is the
  250. // internal resolver, use the defaults as ext nameservers.
  251. if len(rc.md.ExtNameServers) == 0 && len(rc.nameServers) == 1 {
  252. log.G(context.TODO()).Info("No non-localhost DNS nameservers are left in resolv.conf. Using default external servers")
  253. for _, addr := range defaultNSAddrs(ipv6) {
  254. rc.md.ExtNameServers = append(rc.md.ExtNameServers, ExtDNSEntry{Addr: addr})
  255. }
  256. rc.md.UsedDefaultNS = true
  257. }
  258. // For each option required by the nameserver, add it if not already present. If
  259. // the option is already present, don't override it. Apart from ndots - if the
  260. // ndots value is invalid and an ndots option is required, replace the existing
  261. // value.
  262. for _, opt := range reqdOptions {
  263. optName, _, _ := strings.Cut(opt, ":")
  264. if optName == "ndots" {
  265. rc.options = removeInvalidNDots(rc.options)
  266. // No need to update rc.md.NDotsFrom, if there is no ndots option remaining,
  267. // it'll be set to "internal" when the required value is added.
  268. }
  269. if _, exists := rc.Option(optName); !exists {
  270. rc.AddOption(opt)
  271. }
  272. }
  273. rc.md.Transform = "internal resolver"
  274. return append([]ExtDNSEntry(nil), rc.md.ExtNameServers...), nil
  275. }
  276. // Generate returns content suitable for writing to a resolv.conf file. If comments
  277. // is true, the file will include header information if supplied, and a trailing
  278. // comment that describes how the file was constructed and lists external resolvers.
  279. func (rc *ResolvConf) Generate(comments bool) ([]byte, error) {
  280. s := struct {
  281. Md *metadata
  282. NameServers []netip.Addr
  283. Search []string
  284. Options []string
  285. Other []string
  286. Overrides []string
  287. Comments bool
  288. }{
  289. Md: &rc.md,
  290. NameServers: rc.nameServers,
  291. Search: rc.search,
  292. Options: rc.options,
  293. Other: rc.other,
  294. Comments: comments,
  295. }
  296. if rc.md.NSOverride {
  297. s.Overrides = append(s.Overrides, "nameservers")
  298. }
  299. if rc.md.SearchOverride {
  300. s.Overrides = append(s.Overrides, "search")
  301. }
  302. if rc.md.OptionsOverride {
  303. s.Overrides = append(s.Overrides, "options")
  304. }
  305. const templateText = `{{if .Comments}}{{with .Md.Header}}{{.}}
  306. {{end}}{{end}}{{range .NameServers -}}
  307. nameserver {{.}}
  308. {{end}}{{with .Search -}}
  309. search {{join . " "}}
  310. {{end}}{{with .Options -}}
  311. options {{join . " "}}
  312. {{end}}{{with .Other -}}
  313. {{join . "\n"}}
  314. {{end}}{{if .Comments}}
  315. # Based on host file: '{{.Md.SourcePath}}'{{with .Md.Transform}} ({{.}}){{end}}
  316. {{if .Md.UsedDefaultNS -}}
  317. # Used default nameservers.
  318. {{end -}}
  319. {{with .Md.ExtNameServers -}}
  320. # ExtServers: {{.}}
  321. {{end -}}
  322. {{with .Md.InvalidNSs -}}
  323. # Invalid nameservers: {{.}}
  324. {{end -}}
  325. # Overrides: {{.Overrides}}
  326. {{with .Md.NDotsFrom -}}
  327. # Option ndots from: {{.}}
  328. {{end -}}
  329. {{end -}}
  330. `
  331. funcs := template.FuncMap{"join": strings.Join}
  332. var buf bytes.Buffer
  333. templ, err := template.New("summary").Funcs(funcs).Parse(templateText)
  334. if err != nil {
  335. return nil, errdefs.System(err)
  336. }
  337. if err := templ.Execute(&buf, s); err != nil {
  338. return nil, errdefs.System(err)
  339. }
  340. return buf.Bytes(), nil
  341. }
  342. // WriteFile generates content and writes it to path. If hashPath is non-zero, it
  343. // also writes a file containing a hash of the content, to enable UserModified()
  344. // to determine whether the file has been modified.
  345. func (rc *ResolvConf) WriteFile(path, hashPath string, perm os.FileMode) error {
  346. content, err := rc.Generate(true)
  347. if err != nil {
  348. return err
  349. }
  350. // Write the resolv.conf file - it's bind-mounted into the container, so can't
  351. // move a temp file into place, just have to truncate and write it.
  352. if err := os.WriteFile(path, content, perm); err != nil {
  353. return errdefs.System(err)
  354. }
  355. // Write the hash file.
  356. if hashPath != "" {
  357. hashFile, err := ioutils.NewAtomicFileWriter(hashPath, perm)
  358. if err != nil {
  359. return errdefs.System(err)
  360. }
  361. defer hashFile.Close()
  362. digest := digest.FromBytes(content)
  363. if _, err = hashFile.Write([]byte(digest)); err != nil {
  364. return err
  365. }
  366. }
  367. return nil
  368. }
  369. // UserModified can be used to determine whether the resolv.conf file has been
  370. // modified since it was generated. It returns false with no error if the file
  371. // matches the hash, true with no error if the file no longer matches the hash,
  372. // and false with an error if the result cannot be determined.
  373. func UserModified(rcPath, rcHashPath string) (bool, error) {
  374. currRCHash, err := os.ReadFile(rcHashPath)
  375. if err != nil {
  376. // If the hash file doesn't exist, can only assume it hasn't been written
  377. // yet (so, the user hasn't modified the file it hashes).
  378. if errors.Is(err, fs.ErrNotExist) {
  379. return false, nil
  380. }
  381. return false, errors.Wrapf(err, "failed to read hash file %s", rcHashPath)
  382. }
  383. expected, err := digest.Parse(string(currRCHash))
  384. if err != nil {
  385. return false, errors.Wrapf(err, "failed to parse hash file %s", rcHashPath)
  386. }
  387. v := expected.Verifier()
  388. currRC, err := os.Open(rcPath)
  389. if err != nil {
  390. return false, errors.Wrapf(err, "failed to open %s to check for modifications", rcPath)
  391. }
  392. defer currRC.Close()
  393. if _, err := io.Copy(v, currRC); err != nil {
  394. return false, errors.Wrapf(err, "failed to hash %s to check for modifications", rcPath)
  395. }
  396. return !v.Verified(), nil
  397. }
  398. func (rc *ResolvConf) processLine(line string) {
  399. fields := strings.Fields(line)
  400. // Strip blank lines and comments.
  401. if len(fields) == 0 || fields[0][0] == '#' || fields[0][0] == ';' {
  402. return
  403. }
  404. switch fields[0] {
  405. case "nameserver":
  406. if len(fields) < 2 {
  407. return
  408. }
  409. if addr, err := netip.ParseAddr(fields[1]); err != nil {
  410. rc.md.InvalidNSs = append(rc.md.InvalidNSs, fields[1])
  411. } else {
  412. rc.nameServers = append(rc.nameServers, addr)
  413. }
  414. case "domain":
  415. // 'domain' is an obsolete name for 'search'.
  416. fallthrough
  417. case "search":
  418. if len(fields) < 2 {
  419. return
  420. }
  421. // Only the last 'search' directive is used.
  422. rc.search = fields[1:]
  423. case "options":
  424. if len(fields) < 2 {
  425. return
  426. }
  427. // Accumulate options.
  428. rc.options = append(rc.options, fields[1:]...)
  429. default:
  430. // Copy anything that's not a recognised directive.
  431. rc.other = append(rc.other, line)
  432. }
  433. }
  434. func defaultNSAddrs(ipv6 bool) []netip.Addr {
  435. var addrs []netip.Addr
  436. addrs = append(addrs, defaultIPv4NSs...)
  437. if ipv6 {
  438. addrs = append(addrs, defaultIPv6NSs...)
  439. }
  440. return addrs
  441. }
  442. // removeInvalidNDots filters ill-formed "ndots" settings from options.
  443. // The backing array of the options slice is reused.
  444. func removeInvalidNDots(options []string) []string {
  445. n := 0
  446. for _, opt := range options {
  447. k, v, _ := strings.Cut(opt, ":")
  448. if k == "ndots" {
  449. ndots, err := strconv.Atoi(v)
  450. if err != nil || ndots < 0 {
  451. continue
  452. }
  453. }
  454. options[n] = opt
  455. n++
  456. }
  457. clear(options[n:]) // Zero out the obsolete elements, for GC.
  458. return options[:n]
  459. }