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