| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | package dns |
| 7 | |
| 8 | import ( |
| 9 | "context" |
| 10 | "net" |
| 11 | "runtime" |
| 12 | "strconv" |
| 13 | "strings" |
| 14 | |
| 15 | "github.com/miekg/dns" |
| 16 | "github.com/sirupsen/logrus" |
| 17 | ) |
| 18 | |
| 19 | |
| 20 | |
| 21 | const truncateSize = 512 |
| 22 | |
| 23 | var defaultFallbackIPs = []string{"8.8.8.8", "1.1.1.1"} |
| 24 | |
| 25 | type Network string |
| 26 | |
| 27 | const ( |
| 28 | TCP Network = "tcp" |
| 29 | UDP Network = "udp" |
| 30 | ) |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | var ( |
| 37 | Names func(name string) bool |
| 38 | Answered func(name string, ips []net.IP) |
| 39 | ) |
| 40 | |
| 41 | type HandlerOptions struct { |
| 42 | IPv6 bool |
| 43 | StaticHosts map[string]string |
| 44 | UpstreamServers []string |
| 45 | TruncateReply bool |
| 46 | } |
| 47 | |
| 48 | type ServerOptions struct { |
| 49 | HandlerOptions |
| 50 | Address string |
| 51 | TCPPort int |
| 52 | UDPPort int |
| 53 | } |
| 54 | |
| 55 | type Handler struct { |
| 56 | truncate bool |
| 57 | clientConfig *dns.ClientConfig |
| 58 | clients []*dns.Client |
| 59 | ipv6 bool |
| 60 | cnameToHost map[string]string |
| 61 | hostToIP map[string]net.IP |
| 62 | } |
| 63 | |
| 64 | type Server struct { |
| 65 | udp *dns.Server |
| 66 | tcp *dns.Server |
| 67 | } |
| 68 | |
| 69 | func (s *Server) Shutdown() { |
| 70 | if s.udp != nil { |
| 71 | _ = s.udp.Shutdown() |
| 72 | } |
| 73 | if s.tcp != nil { |
| 74 | _ = s.tcp.Shutdown() |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | func newStaticClientConfig(ips []string) (*dns.ClientConfig, error) { |
| 79 | logrus.Tracef("newStaticClientConfig creating config for the following IPs: %v", ips) |
| 80 | config := "nameserver " + strings.Join(ips, "\nnameserver ") + "\n" |
| 81 | return dns.ClientConfigFromReader(strings.NewReader(config)) |
| 82 | } |
| 83 | |
| 84 | func (h *Handler) lookupCnameToHost(cname string) string { |
| 85 | |
| 86 | |
| 87 | |
| 88 | cname = dns.CanonicalName(cname) |
| 89 | seen := make(map[string]bool) |
| 90 | for !seen[cname] { |
| 91 | if _, ok := h.cnameToHost[cname]; ok { |
| 92 | seen[cname] = true |
| 93 | cname = h.cnameToHost[cname] |
| 94 | continue |
| 95 | } |
| 96 | break |
| 97 | } |
| 98 | return cname |
| 99 | } |
| 100 | |
| 101 | func NewHandler(opts HandlerOptions) (dns.Handler, error) { |
| 102 | var cc *dns.ClientConfig |
| 103 | var err error |
| 104 | if len(opts.UpstreamServers) == 0 { |
| 105 | if runtime.GOOS != "windows" { |
| 106 | cc, err = dns.ClientConfigFromFile("/etc/resolv.conf") |
| 107 | if err != nil { |
| 108 | logrus.WithError(err).Warnf("failed to detect system DNS, falling back to %v", defaultFallbackIPs) |
| 109 | cc, err = newStaticClientConfig(defaultFallbackIPs) |
| 110 | if err != nil { |
| 111 | return nil, err |
| 112 | } |
| 113 | } |
| 114 | } else { |
| 115 | |
| 116 | |
| 117 | cc, err = newStaticClientConfig(defaultFallbackIPs) |
| 118 | if err != nil { |
| 119 | return nil, err |
| 120 | } |
| 121 | } |
| 122 | } else { |
| 123 | if cc, err = newStaticClientConfig(opts.UpstreamServers); err != nil { |
| 124 | logrus.WithError(err).Warnf("failed to create a client config from: %v, falling back to %v", opts.UpstreamServers, defaultFallbackIPs) |
| 125 | if cc, err = newStaticClientConfig(defaultFallbackIPs); err != nil { |
| 126 | return nil, err |
| 127 | } |
| 128 | } |
| 129 | } |
| 130 | clients := []*dns.Client{ |
| 131 | {}, |
| 132 | {Net: "tcp"}, |
| 133 | } |
| 134 | h := &Handler{ |
| 135 | truncate: opts.TruncateReply, |
| 136 | clientConfig: cc, |
| 137 | clients: clients, |
| 138 | ipv6: opts.IPv6, |
| 139 | cnameToHost: make(map[string]string), |
| 140 | hostToIP: make(map[string]net.IP), |
| 141 | } |
| 142 | for host, address := range opts.StaticHosts { |
| 143 | cname := dns.CanonicalName(host) |
| 144 | if ip := net.ParseIP(address); ip != nil { |
| 145 | h.hostToIP[cname] = ip |
| 146 | } else { |
| 147 | h.cnameToHost[cname] = dns.CanonicalName(address) |
| 148 | } |
| 149 | } |
| 150 | return h, nil |
| 151 | } |
| 152 | |
| 153 | |
| 154 | var Exchange func(context.Context, *dns.Msg) (*dns.Msg, error) |
| 155 | |
| 156 | func (h *Handler) handleQuery(ctx context.Context, w dns.ResponseWriter, req *dns.Msg) { |
| 157 | if Exchange != nil { |
| 158 | defer w.Close() |
| 159 | answer, err := Exchange(ctx, req) |
| 160 | if err != nil { |
| 161 | answer = new(dns.Msg) |
| 162 | answer.SetRcode(req, dns.RcodeServerFailure) |
| 163 | } |
| 164 | _ = w.WriteMsg(answer) |
| 165 | return |
| 166 | } |
| 167 | var ( |
| 168 | reply dns.Msg |
| 169 | handled bool |
| 170 | ) |
| 171 | defer w.Close() |
| 172 | reply.SetReply(req) |
| 173 | logrus.Tracef("handleQuery received DNS query: %v", req) |
| 174 | for _, q := range req.Question { |
| 175 | if Names != nil && !Names(strings.TrimSuffix(q.Name, ".")) { |
| 176 | reply.SetRcode(req, dns.RcodeNameError) |
| 177 | handled = true |
| 178 | continue |
| 179 | } |
| 180 | hdr := dns.RR_Header{ |
| 181 | Name: q.Name, |
| 182 | Rrtype: q.Qtype, |
| 183 | Class: q.Qclass, |
| 184 | Ttl: 5, |
| 185 | } |
| 186 | qtype := q.Qtype |
| 187 | switch q.Qtype { |
| 188 | case dns.TypeAAAA: |
| 189 | if !h.ipv6 { |
| 190 | |
| 191 | |
| 192 | reply.SetRcode(req, dns.RcodeSuccess) |
| 193 | reply.SetReply(req) |
| 194 | handled = true |
| 195 | break |
| 196 | } |
| 197 | fallthrough |
| 198 | case dns.TypeA: |
| 199 | var err error |
| 200 | var addrs []net.IP |
| 201 | cname := h.lookupCnameToHost(q.Name) |
| 202 | if _, ok := h.hostToIP[cname]; ok { |
| 203 | addrs = []net.IP{h.hostToIP[cname]} |
| 204 | } else { |
| 205 | addrs, err = net.DefaultResolver.LookupIP(ctx, "ip", cname) |
| 206 | if err != nil { |
| 207 | logrus.WithError(err).Debug("handleQuery lookup IP failed") |
| 208 | continue |
| 209 | } |
| 210 | } |
| 211 | if Answered != nil { |
| 212 | Answered(strings.TrimSuffix(q.Name, "."), addrs) |
| 213 | } |
| 214 | for _, ip := range addrs { |
| 215 | var a dns.RR |
| 216 | ipv6 := ip.To4() == nil |
| 217 | if qtype == dns.TypeA && !ipv6 { |
| 218 | hdr.Rrtype = dns.TypeA |
| 219 | a = &dns.A{ |
| 220 | Hdr: hdr, |
| 221 | A: ip.To4(), |
| 222 | } |
| 223 | } else if qtype == dns.TypeAAAA && ipv6 { |
| 224 | hdr.Rrtype = dns.TypeAAAA |
| 225 | a = &dns.AAAA{ |
| 226 | Hdr: hdr, |
| 227 | AAAA: ip.To16(), |
| 228 | } |
| 229 | } else { |
| 230 | continue |
| 231 | } |
| 232 | reply.Answer = append(reply.Answer, a) |
| 233 | handled = true |
| 234 | } |
| 235 | case dns.TypeCNAME: |
| 236 | cname := h.lookupCnameToHost(q.Name) |
| 237 | var err error |
| 238 | if _, ok := h.hostToIP[cname]; !ok { |
| 239 | cname, err = net.DefaultResolver.LookupCNAME(ctx, cname) |
| 240 | if err != nil { |
| 241 | logrus.WithError(err).Debug("handleQuery lookup CNAME failed") |
| 242 | continue |
| 243 | } |
| 244 | } |
| 245 | if cname != "" && cname != dns.CanonicalName(q.Name) { |
| 246 | hdr.Rrtype = dns.TypeCNAME |
| 247 | a := &dns.CNAME{ |
| 248 | Hdr: hdr, |
| 249 | Target: cname, |
| 250 | } |
| 251 | reply.Answer = append(reply.Answer, a) |
| 252 | handled = true |
| 253 | } |
| 254 | case dns.TypeTXT: |
| 255 | txt, err := net.DefaultResolver.LookupTXT(ctx, q.Name) |
| 256 | if err != nil { |
| 257 | logrus.WithError(err).Debug("handleQuery lookup TXT failed") |
| 258 | continue |
| 259 | } |
| 260 | for _, s := range txt { |
| 261 | a := &dns.TXT{ |
| 262 | Hdr: hdr, |
| 263 | } |
| 264 | |
| 265 | |
| 266 | |
| 267 | a.Txt = chunkify(s, 255) |
| 268 | reply.Answer = append(reply.Answer, a) |
| 269 | handled = true |
| 270 | } |
| 271 | case dns.TypeNS: |
| 272 | ns, err := net.DefaultResolver.LookupNS(ctx, q.Name) |
| 273 | if err != nil { |
| 274 | logrus.WithError(err).Debug("handleQuery lookup NS failed") |
| 275 | continue |
| 276 | } |
| 277 | for _, s := range ns { |
| 278 | if s.Host != "" { |
| 279 | a := &dns.NS{ |
| 280 | Hdr: hdr, |
| 281 | Ns: s.Host, |
| 282 | } |
| 283 | reply.Answer = append(reply.Answer, a) |
| 284 | handled = true |
| 285 | } |
| 286 | } |
| 287 | case dns.TypeMX: |
| 288 | mx, err := net.DefaultResolver.LookupMX(ctx, q.Name) |
| 289 | if err != nil { |
| 290 | logrus.WithError(err).Debugf("handleQuery lookup MX failed") |
| 291 | continue |
| 292 | } |
| 293 | for _, s := range mx { |
| 294 | if s.Host != "" { |
| 295 | a := &dns.MX{ |
| 296 | Hdr: hdr, |
| 297 | Mx: s.Host, |
| 298 | Preference: s.Pref, |
| 299 | } |
| 300 | reply.Answer = append(reply.Answer, a) |
| 301 | handled = true |
| 302 | } |
| 303 | } |
| 304 | case dns.TypeSRV: |
| 305 | _, addrs, err := net.DefaultResolver.LookupSRV(ctx, "", "", q.Name) |
| 306 | if err != nil { |
| 307 | logrus.WithError(err).Debug("handleQuery lookup SRV failed") |
| 308 | continue |
| 309 | } |
| 310 | hdr.Rrtype = dns.TypeSRV |
| 311 | for _, addr := range addrs { |
| 312 | a := &dns.SRV{ |
| 313 | Hdr: hdr, |
| 314 | Target: addr.Target, |
| 315 | Port: addr.Port, |
| 316 | Priority: addr.Priority, |
| 317 | Weight: addr.Weight, |
| 318 | } |
| 319 | reply.Answer = append(reply.Answer, a) |
| 320 | handled = true |
| 321 | } |
| 322 | } |
| 323 | } |
| 324 | if handled { |
| 325 | if h.truncate { |
| 326 | reply.Truncate(truncateSize) |
| 327 | } |
| 328 | if err := w.WriteMsg(&reply); err != nil { |
| 329 | logrus.WithError(err).Debugf("handleQuery failed writing DNS reply") |
| 330 | } |
| 331 | |
| 332 | return |
| 333 | } |
| 334 | h.handleDefault(w, req) |
| 335 | } |
| 336 | |
| 337 | func (h *Handler) handleDefault(w dns.ResponseWriter, req *dns.Msg) { |
| 338 | logrus.Tracef("handleDefault for %v", req) |
| 339 | for _, client := range h.clients { |
| 340 | for _, srv := range h.clientConfig.Servers { |
| 341 | addr := net.JoinHostPort(srv, h.clientConfig.Port) |
| 342 | reply, _, err := client.Exchange(req, addr) |
| 343 | if err != nil { |
| 344 | logrus.WithError(err).Debugf("handleDefault failed to perform a synchronous query with upstream [%v]", addr) |
| 345 | continue |
| 346 | } |
| 347 | if h.truncate { |
| 348 | logrus.Tracef("handleDefault truncating reply: %v", reply) |
| 349 | reply.Truncate(truncateSize) |
| 350 | } |
| 351 | if err = w.WriteMsg(reply); err != nil { |
| 352 | logrus.WithError(err).Debugf("handleDefault failed writing DNS reply to [%v]", addr) |
| 353 | } |
| 354 | return |
| 355 | } |
| 356 | } |
| 357 | var reply dns.Msg |
| 358 | reply.SetReply(req) |
| 359 | if h.truncate { |
| 360 | logrus.Tracef("handleDefault truncating reply: %v", reply) |
| 361 | reply.Truncate(truncateSize) |
| 362 | } |
| 363 | if err := w.WriteMsg(&reply); err != nil { |
| 364 | logrus.WithError(err).Debugf("handleDefault failed writing DNS reply") |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | func (h *Handler) ServeDNS(w dns.ResponseWriter, req *dns.Msg) { |
| 369 | switch req.Opcode { |
| 370 | case dns.OpcodeQuery: |
| 371 | h.handleQuery(context.Background(), w, req) |
| 372 | default: |
| 373 | h.handleDefault(w, req) |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | func Start(opts ServerOptions) (*Server, error) { |
| 378 | server := &Server{} |
| 379 | if opts.UDPPort > 0 { |
| 380 | udpSrv, err := listenAndServe(UDP, opts) |
| 381 | if err != nil { |
| 382 | return nil, err |
| 383 | } |
| 384 | server.udp = udpSrv |
| 385 | } |
| 386 | if opts.TCPPort > 0 { |
| 387 | tcpSrv, err := listenAndServe(TCP, opts) |
| 388 | if err != nil { |
| 389 | return nil, err |
| 390 | } |
| 391 | server.tcp = tcpSrv |
| 392 | } |
| 393 | return server, nil |
| 394 | } |
| 395 | |
| 396 | func listenAndServe(network Network, opts ServerOptions) (*dns.Server, error) { |
| 397 | var addr string |
| 398 | |
| 399 | if network == UDP { |
| 400 | opts.HandlerOptions.TruncateReply = true |
| 401 | addr = net.JoinHostPort(opts.Address, strconv.Itoa(opts.UDPPort)) |
| 402 | } else { |
| 403 | addr = net.JoinHostPort(opts.Address, strconv.Itoa(opts.TCPPort)) |
| 404 | } |
| 405 | h, err := NewHandler(opts.HandlerOptions) |
| 406 | if err != nil { |
| 407 | return nil, err |
| 408 | } |
| 409 | s := &dns.Server{Net: string(network), Addr: addr, Handler: h} |
| 410 | go func() { |
| 411 | logrus.Debugf("Start %v DNS listening on: %v", network, addr) |
| 412 | if e := s.ListenAndServe(); e != nil { |
| 413 | panic(e) |
| 414 | } |
| 415 | }() |
| 416 | |
| 417 | return s, nil |
| 418 | } |
| 419 | |
| 420 | func chunkify(buffer string, limit int) []string { |
| 421 | var result []string |
| 422 | for buffer != "" { |
| 423 | if len(buffer) < limit { |
| 424 | limit = len(buffer) |
| 425 | } |
| 426 | result = append(result, buffer[:limit]) |
| 427 | buffer = buffer[limit:] |
| 428 | } |
| 429 | return result |
| 430 | } |