func DiscoverDNS(domain string) (*m.SuggestedMonitor, error) { recordType := "A" recordName := domain server := "8.8.8.8" for { nameservers, err := net.LookupNS(domain) if err != nil || len(nameservers) < 1 { parts := strings.Split(domain, ".") if len(parts) < 2 { break } domain = strings.Join(parts[1:], ".") } else { servers := make([]string, len(nameservers)) for i, ns := range nameservers { s := strings.TrimSuffix(ns.Host, ".") servers[i] = s } server = strings.Join(servers, ",") break } } settings := []m.MonitorSettingDTO{ {Variable: "name", Value: recordName}, {Variable: "type", Value: recordType}, {Variable: "server", Value: server}, } return &m.SuggestedMonitor{MonitorTypeId: 4, Settings: settings}, nil }
func (c *Bootstrap) checkDomain(fqdn string, cached bool, r serviceRegistry) (uris []string, err error) { uris, err = r.matchDomain(fqdn) if err != nil { return } if len(uris) > 0 || !cached { return } if nsSet, err := net.LookupNS(fqdn); err != nil || len(nsSet) == 0 { return nil, nil } c.reloadCache = true body, cached, err := c.fetch(fmt.Sprintf(c.Bootstrap, dns)) if err != nil { return nil, err } defer body.Close() if err := json.NewDecoder(body).Decode(&r); err != nil { return nil, err } return r.matchDomain(fqdn) }
// checkNSRecordMatches does a spot check for DNS misconfiguration, and prints a warning // if using it for DNS is likely to be broken. func checkNSRecordMatches(domain, hostname string) { time.Sleep(1 * time.Second) results, err := net.LookupNS(domain) if err != nil { log.Printf("|WARN| No working NS records found for %s", domain) log.Printf("|WARN| You can still test things using `dig example.%s @%s`, but you won't be able to resolve hosts directly.", domain, hostname) log.Printf("|WARN| See https://github.com/ConradIrwin/aws-name-server for instructions on setting up NS records.") return } matched := false for _, record := range results { if record.Host == hostname { matched = true } } if !matched { log.Printf("|WARN| The NS record for %s points to: %s", domain, results[0].Host) log.Printf("|WARN| But --hostname is: %s", hostname) log.Printf("|WARN| These hostnames must match if you want DNS to work properly.") log.Printf("|WARN| See https://github.com/ConradIrwin/aws-name-server for instructions on NS records.") } }
func main() { members := make([]string, 0) raft.SetLogLevel(0) flag.Parse() if discover { ns, err := net.LookupNS(domain) if err != nil { log.Fatal(err) return } if len(ns) < 1 { log.Fatal("No NS records found for ", domain) return } for _, n := range ns { members = append(members, strings.TrimPrefix(n.Host, ".")) } } else if join != "" { members = strings.Split(join, ",") } s := NewServer(members, domain, ldns, lhttp, dataDir, rtimeout, wtimeout, secret) // Set up metrics if specified on the command line if metricsToStdErr { go metrics.Log(metrics.DefaultRegistry, 60e9, log.New(os.Stderr, "metrics: ", log.Lmicroseconds)) } if len(graphiteServer) > 1 { addr, err := net.ResolveTCPAddr("tcp", graphiteServer) if err != nil { go metrics.Graphite(metrics.DefaultRegistry, 10e9, "skydns", addr) } } if len(stathatUser) > 1 { go stathat.Stathat(metrics.DefaultRegistry, 10e9, stathatUser) } waiter, err := s.Start() if err != nil { log.Fatal(err) return } waiter.Wait() }
func domainExists(name string) (bool, error) { nss, err := net.LookupNS(name) if err != nil { if err, ok := err.(*net.DNSError); ok { if err.Err == "no such host" { return false, nil } } return false, err } return len(nss) > 0, nil }
func (l *lookup) process() { nss, err := net.LookupNS(l.name) if err != nil { l.err = err } else { for _, ns := range nss { if strings.HasSuffix(ns.Host, ".ns.cloudflare.com.") { l.cloudflare = true break } } } }
func (d Domain) ns() string { addrs, err := net.LookupNS(d.domain) if err != nil { return "\nName servers\n" + "--\n" + err.Error() } records := "\nName servers\n" + "--\n" for _, val := range addrs { records += val.Host + "\n" } return records }
func main() { members := make([]string, 0) raft.SetLogLevel(0) flag.Parse() nameservers := strings.Split(nameserver, ",") // empty argument given if len(nameservers) == 1 && nameservers[0] == "" { nameservers = make([]string, 0) config, err := dns.ClientConfigFromFile("/etc/resolv.conf") if err == nil { for _, s := range config.Servers { nameservers = append(nameservers, net.JoinHostPort(s, config.Port)) } } else { log.Fatal(err) return } } if discover { ns, err := net.LookupNS(domain) if err != nil { log.Fatal(err) return } if len(ns) < 1 { log.Fatal("No NS records found for ", domain) return } for _, n := range ns { members = append(members, strings.TrimPrefix(n.Host, ".")) } } else if join != "" { members = strings.Split(join, ",") } s := server.NewServer(members, domain, ldns, lhttp, dataDir, rtimeout, wtimeout, secret, nameservers) stats.Collect() waiter, err := s.Start() if err != nil { log.Fatal(err) return } waiter.Wait() }
func ns(domain string) (data []byte, err error) { nss, err := net.LookupNS(domain) if err != nil { err = os.ErrNotExist return } buf := bytes.NewBuffer(make([]byte, 0, len(nss)*16)) for _, ns := range nss { buf.WriteString(ns.Host) buf.WriteByte('\n') } data = buf.Bytes() return }
func dns(w http.ResponseWriter, r *http.Request) { q := r.URL.Query().Get("q") // Note that the below is NOT safe from input attacks, but that's OK // because this is just for debugging. fmt.Fprintf(w, `<html><body> <form action="/dns"> <input name="q" type="text" value="%v"></input> <button type="submit">Lookup</button> </form> <br/><br/><pre>`, q) { res, err := net.LookupNS(q) spew.Fprintf(w, "LookupNS(%v):\nResult: %#v\nError: %v\n\n", q, res, err) } { res, err := net.LookupTXT(q) spew.Fprintf(w, "LookupTXT(%v):\nResult: %#v\nError: %v\n\n", q, res, err) } { cname, res, err := net.LookupSRV("", "", q) spew.Fprintf(w, `LookupSRV("", "", %v): cname: %v Result: %#v Error: %v `, q, cname, res, err) } { res, err := net.LookupHost(q) spew.Fprintf(w, "LookupHost(%v):\nResult: %#v\nError: %v\n\n", q, res, err) } { res, err := net.LookupIP(q) spew.Fprintf(w, "LookupIP(%v):\nResult: %#v\nError: %v\n\n", q, res, err) } { res, err := net.LookupMX(q) spew.Fprintf(w, "LookupMX(%v):\nResult: %#v\nError: %v\n\n", q, res, err) } fmt.Fprintf(w, `</pre> </body> </html>`) }
func main() { var err error cmdFlags() flag.Parse() if interfaces, err = net.Interfaces(); err != nil { panic(err) } if interfaceAddrs, err = net.InterfaceAddrs(); err != nil { panic(err) } if Options.listInterfaces { listInterfaces(interfaces) } else if Options.listInterfaceAddrs { listInterfaceAddrs(interfaceAddrs) } else if Options.rdns != "" { hostnames, _ := net.LookupAddr(Options.rdns) for _, hostname := range hostnames { fmt.Println(hostname) } } else if Options.ip != "" { ips, _ := net.LookupIP(Options.ip) for _, ip := range ips { fmt.Println(ip) } } else if Options.mx != "" { mxs, _ := net.LookupMX(Options.mx) for _, mx := range mxs { fmt.Println(mx.Pref, mx.Host) } } else if Options.ns != "" { nss, _ := net.LookupNS(Options.ns) for _, ns := range nss { fmt.Println(ns.Host) } } else if Options.txt != "" { txts, _ := net.LookupTXT(Options.txt) for _, txt := range txts { fmt.Println(txt) } } }
func ZoneTransfer(domain string) Results { results := NewResultSet() fqdn := dns.Fqdn(domain) servers, err := net.LookupNS(domain) if err != nil { log.Fatal(err) } for _, server := range servers { msg := new(dns.Msg) msg.SetAxfr(fqdn) transfer := new(dns.Transfer) answerChan, err := transfer.In(msg, net.JoinHostPort(server.Host, "53")) if err != nil { log.Println(err) continue } for envelope := range answerChan { if envelope.Error != nil { log.Println(envelope.Error) break } for _, rr := range envelope.RR { switch v := rr.(type) { case *dns.A: results.Add(strings.TrimRight(v.Header().Name, "."), v.A.String()) case *dns.AAAA: results.Add(strings.TrimRight(v.Header().Name, "."), v.AAAA.String()) default: } } } } return results.Results() }
func check(domain string, tldPlusOne string) bool { // check ns record if len(tldPlusOne) == 0 { tldPlusOne, _ = publicsuffix.EffectiveTLDPlusOne(domain) } nss, err := net.LookupNS(tldPlusOne) if err != nil { log.Println("LookupNS failed", tldPlusOne, err) addToIgnoreList(tldPlusOne, false) addToIgnoreList(domain, false) return false } for _, v := range nss { if chinaNS.MatchString(v.Host) { addToChinaList(tldPlusOne) return true } // check if ns record is belong to china domain ns := strings.TrimSuffix(strings.TrimSpace(v.Host), ".") ns, err = publicsuffix.EffectiveTLDPlusOne(domain) if err == nil && isChina(ns) { addToChinaList(tldPlusOne) return true } } // put it in ignores list to avoid double check addToIgnoreList(tldPlusOne, false) if len(nss) > 0 { log.Println("out-china ns server:", nss[0].Host) } return false }
func DiscoverDNS(endpoint *Endpoint) (*m.Check, error) { domain := endpoint.Host recordType := "A" recordName := domain server := "8.8.8.8" for { nameservers, err := net.LookupNS(domain) if err != nil || len(nameservers) < 1 { parts := strings.Split(domain, ".") if len(parts) < 2 { break } domain = strings.Join(parts[1:], ".") } else { servers := make([]string, len(nameservers)) for i, ns := range nameservers { s := strings.TrimSuffix(ns.Host, ".") servers[i] = s } server = strings.Join(servers, ",") break } } return &m.Check{ Type: "dns", Frequency: 60, Settings: map[string]interface{}{ "name": recordName, "type": recordType, "server": server, "timeout": 5, "protocol": "udp", }, Enabled: true, }, nil }
func configure(hub *StatusHub) { cfg, err := configRead(*configFile) if err != nil { log.Printf("Could not read config file: %s\n", err) os.Exit(2) } hub.MarkConfigurationStart() wg := &sync.WaitGroup{} errch := make(chan error, 20) for _, server := range cfg.Servers.A { log.Println("Adding", server) wg.Add(1) hub.AddNameBackground(server, errch) } for _, domain := range cfg.Servers.Domain { log.Println("Adding NSes for", domain) nses, err := net.LookupNS(domain) log.Printf("NSes: %#v: %s\n", nses, err) for _, ns := range nses { log.Printf("Adding '%s'\n", ns.Host) wg.Add(1) hub.AddNameBackground(ns.Host, errch) } } for _, txtconfig := range cfg.Servers.Txt { x := strings.SplitN(txtconfig, ",", 2) txtname := strings.TrimSpace(x[0]) txtbase := strings.TrimSpace(x[1]) log.Println("Adding TXT for", txtname, txtbase) txts, err := net.LookupTXT(txtname) log.Printf("TXTs: %#v: %s\n", txts, err) names := []string{} for _, txt := range txts { for _, name := range strings.Split(txt, " ") { names = append(names, name) } } nameSlice := []string{"", txtbase} for _, name := range names { nameSlice[0] = name hub.AddNameBackground(strings.Join(nameSlice, "."), errch) } } go func() { for err := range errch { if err != nil { log.Println(err) } wg.Done() } }() wg.Wait() close(errch) hub.MarkConfigurationEnd() }
func main() { members := make([]string, 0) raft.SetLogLevel(0) flag.Parse() nameservers := strings.Split(nameserver, ",") // empty argument given if len(nameservers) == 1 && nameservers[0] == "" { nameservers = make([]string, 0) config, err := dns.ClientConfigFromFile("/etc/resolv.conf") if err == nil { for _, s := range config.Servers { nameservers = append(nameservers, net.JoinHostPort(s, config.Port)) } } else { log.Fatal(err) return } } if discover { ns, err := net.LookupNS(domain) if err != nil { log.Fatal(err) return } if len(ns) < 1 { log.Fatal("No NS records found for ", domain) return } for _, n := range ns { members = append(members, strings.TrimPrefix(n.Host, ".")) } } else if join != "" { members = strings.Split(join, ",") } s := server.NewServer(members, domain, ldns, lhttp, dataDir, rtimeout, wtimeout, secret, nameservers, !norr, tlskey, tlspem) if dnssec != "" { k, p, e := server.ParseKeyFile(dnssec) if e != nil { log.Fatal(e) return } if k.Header().Name != dns.Fqdn(domain) { log.Fatal(errors.New("Owner name of DNSKEY must match SkyDNS domain")) return } s.SetKeys(k, p) } stats.Collect() waiter, err := s.Start() if err != nil { log.Fatal(err) return } waiter.Wait() }
func main() { members := make([]string, 0) raft.SetLogLevel(0) flag.Parse() nameservers := strings.Split(nameserver, ",") // empty argument given if len(nameservers) == 1 && nameservers[0] == "" { nameservers = make([]string, 0) config, err := dns.ClientConfigFromFile("/etc/resolv.conf") if err == nil { for _, s := range config.Servers { nameservers = append(nameservers, net.JoinHostPort(s, config.Port)) } } else { log.Fatal(err) return } } if discover { ns, err := net.LookupNS(domain) if err != nil { log.Fatal(err) return } if len(ns) < 1 { log.Fatal("No NS records found for ", domain) return } for _, n := range ns { members = append(members, strings.TrimPrefix(n.Host, ".")) } } else if join != "" { members = strings.Split(join, ",") } s := server.NewServer(members, domain, ldns, lhttp, dataDir, rtimeout, wtimeout, secret, nameservers) // Set up metrics if specified on the command line if metricsToStdErr { go metrics.Log(metrics.DefaultRegistry, 60e9, log.New(os.Stderr, "metrics: ", log.Lmicroseconds)) } if len(graphiteServer) > 1 { addr, err := net.ResolveTCPAddr("tcp", graphiteServer) if err != nil { go metrics.Graphite(metrics.DefaultRegistry, 10e9, "skydns", addr) } } if len(stathatUser) > 1 { go stathat.Stathat(metrics.DefaultRegistry, 10e9, stathatUser) } waiter, err := s.Start() if err != nil { log.Fatal(err) return } waiter.Wait() }
func main() { // Load the configuration m := multiconfig.NewWithPath(os.Getenv("config")) cfg := &dns.Config{} m.MustLoad(cfg) // Parse the log level lvl, err := log.LvlFromString(cfg.LogLevel) if err != nil { panic(err) } // Create a new logger l := log.New() l.SetHandler( log.LvlFilterHandler(lvl, log.StdoutHandler), ) // Start the initialization il := l.New("module", "init") il.Info("Starting up the application") // Parse the Redis connection string url := redisurl.Parse(cfg.Redis) // Create an options list opts := []redis.DialOption{} if url.Database != 0 { opts = append(opts, redis.DialDatabase(url.Database)) } if url.Password != "" { opts = append(opts, redis.DialPassword(url.Password)) } // Verify the DNS setup results, err := net.LookupNS(cfg.Domain) if err != nil { il.Warn("Unable to look up the NS of domain", "domain", cfg.Domain, "error", err.Error()) } if len(results) > 0 { found := false for _, record := range results { if record.Host == cfg.Hostname { found = true } } if !found { existing := []string{} for _, record := range results { existing = append(existing, record.Host) } il.Warn("Invalid NS records for the domain", "domain", cfg.Domain, "records", existing) } } else { il.Warn("No NS records found for domain", "domain", cfg.Domain, "error", err.Error()) } // Dial the server rc, err := redis.Dial("tcp", url.Host+":"+strconv.Itoa(url.Port), opts...) if err != nil { il.Crit("Unable to connect to the Redis server", "error", err.Error()) return } // Initialize the DNS server ds := &dns.DNS{ Config: cfg, Redis: rc, } if err := ds.ListenAndServe(); err != nil { il.Crit("Error while listening to the specified port", "error", err.Error()) } }