resolvconf.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. // Package resolvconf provides utility code to query and update DNS configuration in /etc/resolv.conf
  2. package resolvconf
  3. import (
  4. "bytes"
  5. "os"
  6. "regexp"
  7. "strings"
  8. "sync"
  9. "github.com/sirupsen/logrus"
  10. )
  11. const (
  12. // defaultPath is the default path to the resolv.conf that contains information to resolve DNS. See Path().
  13. defaultPath = "/etc/resolv.conf"
  14. // alternatePath is a path different from defaultPath, that may be used to resolve DNS. See Path().
  15. alternatePath = "/run/systemd/resolve/resolv.conf"
  16. )
  17. // constants for the IP address type
  18. const (
  19. IP = iota // IPv4 and IPv6
  20. IPv4
  21. IPv6
  22. )
  23. var (
  24. detectSystemdResolvConfOnce sync.Once
  25. pathAfterSystemdDetection = defaultPath
  26. )
  27. // Path returns the path to the resolv.conf file that libnetwork should use.
  28. //
  29. // When /etc/resolv.conf contains 127.0.0.53 as the only nameserver, then
  30. // it is assumed systemd-resolved manages DNS. Because inside the container 127.0.0.53
  31. // is not a valid DNS server, Path() returns /run/systemd/resolve/resolv.conf
  32. // which is the resolv.conf that systemd-resolved generates and manages.
  33. // Otherwise Path() returns /etc/resolv.conf.
  34. //
  35. // Errors are silenced as they will inevitably resurface at future open/read calls.
  36. //
  37. // More information at https://www.freedesktop.org/software/systemd/man/systemd-resolved.service.html#/etc/resolv.conf
  38. func Path() string {
  39. detectSystemdResolvConfOnce.Do(func() {
  40. candidateResolvConf, err := os.ReadFile(defaultPath)
  41. if err != nil {
  42. // silencing error as it will resurface at next calls trying to read defaultPath
  43. return
  44. }
  45. ns := GetNameservers(candidateResolvConf, IP)
  46. if len(ns) == 1 && ns[0] == "127.0.0.53" {
  47. pathAfterSystemdDetection = alternatePath
  48. logrus.Infof("detected 127.0.0.53 nameserver, assuming systemd-resolved, so using resolv.conf: %s", alternatePath)
  49. }
  50. })
  51. return pathAfterSystemdDetection
  52. }
  53. const (
  54. // ipLocalhost is a regex pattern for IPv4 or IPv6 loopback range.
  55. ipLocalhost = `((127\.([0-9]{1,3}\.){2}[0-9]{1,3})|(::1)$)`
  56. ipv4NumBlock = `(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)`
  57. ipv4Address = `(` + ipv4NumBlock + `\.){3}` + ipv4NumBlock
  58. // This is not an IPv6 address verifier as it will accept a super-set of IPv6, and also
  59. // will *not match* IPv4-Embedded IPv6 Addresses (RFC6052), but that and other variants
  60. // -- e.g. other link-local types -- either won't work in containers or are unnecessary.
  61. // For readability and sufficiency for Docker purposes this seemed more reasonable than a
  62. // 1000+ character regexp with exact and complete IPv6 validation
  63. ipv6Address = `([0-9A-Fa-f]{0,4}:){2,7}([0-9A-Fa-f]{0,4})(%\w+)?`
  64. )
  65. var (
  66. // Note: the default IPv4 & IPv6 resolvers are set to Google's Public DNS
  67. defaultIPv4Dns = []string{"nameserver 8.8.8.8", "nameserver 8.8.4.4"}
  68. defaultIPv6Dns = []string{"nameserver 2001:4860:4860::8888", "nameserver 2001:4860:4860::8844"}
  69. localhostNSRegexp = regexp.MustCompile(`(?m)^nameserver\s+` + ipLocalhost + `\s*\n*`)
  70. nsIPv6Regexp = regexp.MustCompile(`(?m)^nameserver\s+` + ipv6Address + `\s*\n*`)
  71. nsRegexp = regexp.MustCompile(`^\s*nameserver\s*((` + ipv4Address + `)|(` + ipv6Address + `))\s*$`)
  72. nsIPv6Regexpmatch = regexp.MustCompile(`^\s*nameserver\s*((` + ipv6Address + `))\s*$`)
  73. nsIPv4Regexpmatch = regexp.MustCompile(`^\s*nameserver\s*((` + ipv4Address + `))\s*$`)
  74. searchRegexp = regexp.MustCompile(`^\s*search\s*(([^\s]+\s*)*)$`)
  75. optionsRegexp = regexp.MustCompile(`^\s*options\s*(([^\s]+\s*)*)$`)
  76. )
  77. var lastModified struct {
  78. sync.Mutex
  79. sha256 string
  80. contents []byte
  81. }
  82. // File contains the resolv.conf content and its hash
  83. type File struct {
  84. Content []byte
  85. Hash string
  86. }
  87. // Get returns the contents of /etc/resolv.conf and its hash
  88. func Get() (*File, error) {
  89. return GetSpecific(Path())
  90. }
  91. // GetSpecific returns the contents of the user specified resolv.conf file and its hash
  92. func GetSpecific(path string) (*File, error) {
  93. resolv, err := os.ReadFile(path)
  94. if err != nil {
  95. return nil, err
  96. }
  97. hash, err := hashData(bytes.NewReader(resolv))
  98. if err != nil {
  99. return nil, err
  100. }
  101. return &File{Content: resolv, Hash: hash}, nil
  102. }
  103. // GetIfChanged retrieves the host /etc/resolv.conf file, checks against the last hash
  104. // and, if modified since last check, returns the bytes and new hash.
  105. // This feature is used by the resolv.conf updater for containers
  106. func GetIfChanged() (*File, error) {
  107. lastModified.Lock()
  108. defer lastModified.Unlock()
  109. resolv, err := os.ReadFile(Path())
  110. if err != nil {
  111. return nil, err
  112. }
  113. newHash, err := hashData(bytes.NewReader(resolv))
  114. if err != nil {
  115. return nil, err
  116. }
  117. if lastModified.sha256 != newHash {
  118. lastModified.sha256 = newHash
  119. lastModified.contents = resolv
  120. return &File{Content: resolv, Hash: newHash}, nil
  121. }
  122. // nothing changed, so return no data
  123. return nil, nil
  124. }
  125. // GetLastModified retrieves the last used contents and hash of the host resolv.conf.
  126. // Used by containers updating on restart
  127. func GetLastModified() *File {
  128. lastModified.Lock()
  129. defer lastModified.Unlock()
  130. return &File{Content: lastModified.contents, Hash: lastModified.sha256}
  131. }
  132. // FilterResolvDNS cleans up the config in resolvConf. It has two main jobs:
  133. // 1. It looks for localhost (127.*|::1) entries in the provided
  134. // resolv.conf, removing local nameserver entries, and, if the resulting
  135. // cleaned config has no defined nameservers left, adds default DNS entries
  136. // 2. Given the caller provides the enable/disable state of IPv6, the filter
  137. // code will remove all IPv6 nameservers if it is not enabled for containers
  138. //
  139. func FilterResolvDNS(resolvConf []byte, ipv6Enabled bool) (*File, error) {
  140. cleanedResolvConf := localhostNSRegexp.ReplaceAll(resolvConf, []byte{})
  141. // if IPv6 is not enabled, also clean out any IPv6 address nameserver
  142. if !ipv6Enabled {
  143. cleanedResolvConf = nsIPv6Regexp.ReplaceAll(cleanedResolvConf, []byte{})
  144. }
  145. // if the resulting resolvConf has no more nameservers defined, add appropriate
  146. // default DNS servers for IPv4 and (optionally) IPv6
  147. if len(GetNameservers(cleanedResolvConf, IP)) == 0 {
  148. logrus.Infof("No non-localhost DNS nameservers are left in resolv.conf. Using default external servers: %v", defaultIPv4Dns)
  149. dns := defaultIPv4Dns
  150. if ipv6Enabled {
  151. logrus.Infof("IPv6 enabled; Adding default IPv6 external servers: %v", defaultIPv6Dns)
  152. dns = append(dns, defaultIPv6Dns...)
  153. }
  154. cleanedResolvConf = append(cleanedResolvConf, []byte("\n"+strings.Join(dns, "\n"))...)
  155. }
  156. hash, err := hashData(bytes.NewReader(cleanedResolvConf))
  157. if err != nil {
  158. return nil, err
  159. }
  160. return &File{Content: cleanedResolvConf, Hash: hash}, nil
  161. }
  162. // getLines parses input into lines and strips away comments.
  163. func getLines(input []byte, commentMarker []byte) [][]byte {
  164. lines := bytes.Split(input, []byte("\n"))
  165. var output [][]byte
  166. for _, currentLine := range lines {
  167. var commentIndex = bytes.Index(currentLine, commentMarker)
  168. if commentIndex == -1 {
  169. output = append(output, currentLine)
  170. } else {
  171. output = append(output, currentLine[:commentIndex])
  172. }
  173. }
  174. return output
  175. }
  176. // GetNameservers returns nameservers (if any) listed in /etc/resolv.conf
  177. func GetNameservers(resolvConf []byte, kind int) []string {
  178. nameservers := []string{}
  179. for _, line := range getLines(resolvConf, []byte("#")) {
  180. var ns [][]byte
  181. if kind == IP {
  182. ns = nsRegexp.FindSubmatch(line)
  183. } else if kind == IPv4 {
  184. ns = nsIPv4Regexpmatch.FindSubmatch(line)
  185. } else if kind == IPv6 {
  186. ns = nsIPv6Regexpmatch.FindSubmatch(line)
  187. }
  188. if len(ns) > 0 {
  189. nameservers = append(nameservers, string(ns[1]))
  190. }
  191. }
  192. return nameservers
  193. }
  194. // GetNameserversAsCIDR returns nameservers (if any) listed in
  195. // /etc/resolv.conf as CIDR blocks (e.g., "1.2.3.4/32")
  196. // This function's output is intended for net.ParseCIDR
  197. func GetNameserversAsCIDR(resolvConf []byte) []string {
  198. nameservers := []string{}
  199. for _, nameserver := range GetNameservers(resolvConf, IP) {
  200. var address string
  201. // If IPv6, strip zone if present
  202. if strings.Contains(nameserver, ":") {
  203. address = strings.Split(nameserver, "%")[0] + "/128"
  204. } else {
  205. address = nameserver + "/32"
  206. }
  207. nameservers = append(nameservers, address)
  208. }
  209. return nameservers
  210. }
  211. // GetSearchDomains returns search domains (if any) listed in /etc/resolv.conf
  212. // If more than one search line is encountered, only the contents of the last
  213. // one is returned.
  214. func GetSearchDomains(resolvConf []byte) []string {
  215. domains := []string{}
  216. for _, line := range getLines(resolvConf, []byte("#")) {
  217. match := searchRegexp.FindSubmatch(line)
  218. if match == nil {
  219. continue
  220. }
  221. domains = strings.Fields(string(match[1]))
  222. }
  223. return domains
  224. }
  225. // GetOptions returns options (if any) listed in /etc/resolv.conf
  226. // If more than one options line is encountered, only the contents of the last
  227. // one is returned.
  228. func GetOptions(resolvConf []byte) []string {
  229. options := []string{}
  230. for _, line := range getLines(resolvConf, []byte("#")) {
  231. match := optionsRegexp.FindSubmatch(line)
  232. if match == nil {
  233. continue
  234. }
  235. options = strings.Fields(string(match[1]))
  236. }
  237. return options
  238. }
  239. // Build writes a configuration file to path containing a "nameserver" entry
  240. // for every element in dns, a "search" entry for every element in
  241. // dnsSearch, and an "options" entry for every element in dnsOptions.
  242. func Build(path string, dns, dnsSearch, dnsOptions []string) (*File, error) {
  243. content := bytes.NewBuffer(nil)
  244. if len(dnsSearch) > 0 {
  245. if searchString := strings.Join(dnsSearch, " "); strings.Trim(searchString, " ") != "." {
  246. if _, err := content.WriteString("search " + searchString + "\n"); err != nil {
  247. return nil, err
  248. }
  249. }
  250. }
  251. for _, dns := range dns {
  252. if _, err := content.WriteString("nameserver " + dns + "\n"); err != nil {
  253. return nil, err
  254. }
  255. }
  256. if len(dnsOptions) > 0 {
  257. if optsString := strings.Join(dnsOptions, " "); strings.Trim(optsString, " ") != "" {
  258. if _, err := content.WriteString("options " + optsString + "\n"); err != nil {
  259. return nil, err
  260. }
  261. }
  262. }
  263. hash, err := hashData(bytes.NewReader(content.Bytes()))
  264. if err != nil {
  265. return nil, err
  266. }
  267. return &File{Content: content.Bytes(), Hash: hash}, os.WriteFile(path, content.Bytes(), 0644)
  268. }