Ejemplo n.º 1
3
func getHostName(domainName string) (string, error) {
	host := strings.ToLower(domainName)
	addr, err := net.LookupHost(host)
	if err != nil || len(addr) < 1 {
		host = "www." + domainName
		addr, err = net.LookupHost(host)
		if err != nil || len(addr) < 1 {
			return "", errors.New("failed to lookup IP of domain.")
		}
	}
	return host, nil
}
Ejemplo n.º 2
0
func NewEndpoint(domainName string) (*Endpoint, error) {
	host := strings.ToLower(domainName)
	e := &Endpoint{Host: host}
	if strings.Contains(host, "://") {
		u, err := url.Parse(host)
		if err != nil {
			return nil, err
		}
		e.Host = strings.Split(u.Host, ":")[0]
		e.URL = u
	}

	if net.ParseIP(e.Host) != nil {
		// the parsed host is an IP address.
		e.IsIP = true
		return e, nil
	}

	addr, err := net.LookupHost(e.Host)
	if err != nil || len(addr) < 1 {
		e.Host = "www." + domainName
		addr, err = net.LookupHost(e.Host)
		if err != nil || len(addr) < 1 {
			return nil, fmt.Errorf("failed to lookup IP of domain %s.", e.Host)
		}
	}

	return e, nil
}
Ejemplo n.º 3
0
func isHostInCN(req *http.Request) bool {
	if nil == ipfunc {
		return true
	}
	host := req.Host
	if strings.Contains(host, ":") {
		host, _, _ = net.SplitHostPort(host)
	}
	//consider use trusted DNS
	var ip string
	var ok bool
	if strings.HasSuffix(host, ".cn") {
		return true
	} else {
		if ips, err := net.LookupHost(host); nil == err && len(ips) > 0 {
			ip = ips[0]
			ok = true
		}
	}
	if !ok || nil == ipfunc {
		return false
	}
	country, err := ipfunc.FindCountry(ip)
	if nil != err {
		log.Printf("[WARN]Find country error:%v\n", err)
		return false
	}
	ret := strings.EqualFold(country, "CN")

	return ret
}
Ejemplo n.º 4
0
Archivo: dns.go Proyecto: ryansb/cjdcmd
// Resolve a hostname to an IP address using the system DNS settings first, then HypeDNS
func resolveHost(hostname string) (ips []string, err error) {
	var ip string
	// Try the system DNS setup
	result, _ := net.LookupHost(hostname)
	if len(result) > 0 {
		goto end
	}

	// Try with hypedns
	ip, err = lookupHypeDNS(hostname)

	if ip == "" || err != nil {
		err = fmt.Errorf("Unable to resolve hostname. This is usually caused by not having a route to hypedns. Please try again in a few seconds.")
		return
	}

	result = append(result, ip)

end:
	for _, addr := range result {
		tIP := net.ParseIP(addr)
		// Only grab the cjdns IP's
		if tIP[0] == 0xfc {
			ips = append(ips, padIPv6(net.ParseIP(addr)))
		}
	}

	return
}
Ejemplo n.º 5
0
func validateApiEndpoint(config *config) error {
	if config.ApiEndpoint == nil {
		return fmt.Errorf("* 'api' must not be null")
	}

	if config.GetApiEndpoint() == "" {
		return fmt.Errorf("* Invalid configuration: 'api' must be a valid Cloud Controller endpoint but was blank")
	}

	u, err := url.Parse(config.GetApiEndpoint())
	if err != nil {
		return fmt.Errorf("* Invalid configuration: 'api' must be a valid URL but was set to '%s'", config.GetApiEndpoint())
	}

	host := u.Host
	if host == "" {
		// url.Parse misunderstood our convention and treated the hostname as a URL path
		host = u.Path
	}

	if _, err = net.LookupHost(host); err != nil {
		return fmt.Errorf("* Invalid configuration for 'api' <%s>: %s", config.GetApiEndpoint(), err)
	}

	return nil
}
Ejemplo n.º 6
0
func TestCountrySpodhuis(t *testing.T) {
	ipList, err := net.LookupHost(checkSksHostname)
	if err != nil {
		t.Fatalf("LookupHost(%s) failed: %s", checkSksHostname, err)
	}
	if len(ipList) != checkSksIPCount {
		t.Fatalf("Wrong number of IP addresses for \"%s\": expected %d got %d",
			checkSksHostname, checkSksIPCount, len(ipList))
	}
	var expectSucceed bool
	for _, ip := range ipList {
		switch {
		case net.ParseIP(ip).To4() != nil:
			expectSucceed = true
		default:
			expectSucceed = checkSksExpectIPv6HasCountry
		}
		country, err := CountryForIPString(ip)
		if err != nil {
			if expectSucceed {
				t.Fatalf("Failed to resolve country for [%s] (from \"%s\"): %s",
					ip, checkSksHostname, err)
			}
			continue
		}
		if !expectSucceed {
			t.Fatalf("Unexpectedly resolved country for [%s] (from \"%s\")",
				ip, checkSksHostname)
		}
		if country != checkSksCountry {
			t.Fatalf("Host \"%s\" IP [%s]: expected country \"%s\", got \"%s\"",
				checkSksHostname, ip, checkSksCountry, country)
		}
	}
}
Ejemplo n.º 7
0
// getAddress gets the localhosts IPv4 address.
func GetAddress() (string, error) {
	name, err := os.Hostname()
	if err != nil {
		log.Print("Error Resolving Hostname:", err)
		return "", err
	}

	if ipv4host == "NONE" {
		as, err := net.LookupHost(name)
		if err != nil {
			return "", err
		}

		addr := ""

		for _, a := range as {
			log.Printf("a = %+v", a)
			if ipv4Reg.MatchString(a) {
				log.Print("matches")
				addr = a
			}
		}

		if addr == "" {
			err = errors.New("No IPv4 Address for Hostname")
		}
		return addr, err
	}
	return ipv4host, nil
}
Ejemplo n.º 8
0
func (r *ReplicaSet) proxyHostname() string {
	const home = "127.0.0.1"

	hostname, err := os.Hostname()
	if err != nil {
		r.Log.Error(err)
		return home
	}

	// The follow logic ensures that the hostname resolves to a local address.
	// If it doesn't we don't use it since it probably wont work anyways.
	hostnameAddrs, err := net.LookupHost(hostname)
	if err != nil {
		r.Log.Error(err)
		return home
	}

	interfaceAddrs, err := net.InterfaceAddrs()
	if err != nil {
		r.Log.Error(err)
		return home
	}

	for _, ia := range interfaceAddrs {
		sa := ia.String()
		for _, ha := range hostnameAddrs {
			// check for an exact match or a match ignoring the suffix bits
			if sa == ha || strings.HasPrefix(sa, ha+"/") {
				return hostname
			}
		}
	}
	r.Log.Warnf("hostname %s doesn't resolve to the current host", hostname)
	return home
}
Ejemplo n.º 9
0
func requiresEtcHostsEdits(t *testing.T) {
	addrs, err := net.LookupHost(testDomain)
	if err != nil || len(addrs) != 1 || addrs[0] != "127.0.0.1" {
		t.Skip("/etc/hosts file not properly configured, skipping test. see README for required edits")
	}
	return
}
Ejemplo n.º 10
0
func LookupIP(host string) (addrs []net.IP, err error) {
	ip := net.ParseIP(host)
	if ip == nil || ip.To4() == nil {

		ip, ipnet, err := net.ParseCIDR(host)
		if err != nil || ip.To4() == nil {

			hosts, err := net.LookupHost(host)
			if err != nil {
				return nil, err
			}

			addrs := make([]net.IP, 0, len(hosts))
			for _, v := range hosts {
				ip = net.ParseIP(v)
				ip = ip.To4()
				if ip != nil {
					addrs = append(addrs, ip)
				}
			}

			return addrs, nil
		}

		addrs, _ := HostAddr(ipnet)
		return addrs, nil
	}

	return []net.IP{ip}, nil
}
Ejemplo n.º 11
0
func checkNameResolve(inFilename string, debug bool) (err error) {
	rawBytes, err := ioutil.ReadFile(inFilename)
	if err != nil {
		return err
	}
	text := string(rawBytes)
	lines := strings.Split(text, "\n")
	for _, line := range lines {
		if line == "" {
			if debug == true {
				log.Println("End of file")
			}
			return nil
		}
		ip, err := net.LookupHost(line)
		if debug == true {
			log.Println("Try to resolve", line, "IP(s):", ip, "Error:", err)
		} else {
			if err != nil {
				fmt.Println(line)
			}
		}
	}
	return nil
}
Ejemplo n.º 12
0
Archivo: dns.go Proyecto: badoo/thunder
func (r *resolver) resolveAndUpdate(item cacheItem) (cacheItem, error) {
	ips, err := net.LookupHost(item.host)
	if err != nil {
		if r.logger != nil {
			r.logger.Warnf("resolveAndUpdate %v: %v", item.host, err)
		}

		r.cacheLock.Lock()
		delete(r.cache, item.host)
		r.cacheLock.Unlock()

		return cacheItem{err: err}, err
	}

	if item.ips == nil || !util.StrSliceEqual(item.ips, ips) {
		if r.logger != nil {
			r.logger.Debugf("resolveAndUpdate: %s ips changed %v -> %v", item.host, item.ips, ips)
		}

		item.ips = ips
		item.err = err

		r.cacheLock.Lock()
		r.cache[item.host] = item
		r.cacheLock.Unlock()
	}

	return item, nil
}
Ejemplo n.º 13
0
func ExampleSocks4Client() {
	user := ""
	client, err := NewSocks4Client("tcp", "127.0.0.1:1080", user, Direct)
	if err != nil {
		return
	}
	addrs, err := net.LookupHost("www.google.com")
	if err != nil {
		return
	}
	if len(addrs) == 0 {
		return
	}
	conn, err := client.Dial("tcp", addrs[0]+":80")
	if err != nil {
		return
	}
	httpClient := httputil.NewClientConn(conn, nil)
	defer httpClient.Close()

	request, err := http.NewRequest("GET", "/", nil)
	if err != nil {
		return
	}
	resp, err := httpClient.Do(request)
	if err != nil {
		return
	}
	dump, err := httputil.DumpResponse(resp, true)
	if err != nil {
		return
	}
	println(string(dump))
	return
}
Ejemplo n.º 14
0
func Connect(socket *Socket, host string, portno int) (retval int, err error) {

	addrs, err := net.LookupHost(host)

	if err != nil {
		return -1, fmt.Errorf("Unable to connect to the socket: %s", err)
	}

	resolvedHost := addrs[0]

	if socket.af == syscall.AF_INET6 {
		resolvedHost = fmt.Sprintf("[%s]", resolvedHost)
	}

	rsa, salen, err := createSockaddr(resolvedHost, portno)

	if err != nil {
		return -1, fmt.Errorf("could not convert syscall.Sockaddr to syscall.RawSockaddrAny %s", err)
	}

	retval = int(C.udt_connect(socket.sock, (*C.struct_sockaddr)(unsafe.Pointer(rsa)),
		C.int(salen)))
	if retval != 0 {
		return retval, udtErrDesc("Unable to connect to the socket")
	}
	return
}
Ejemplo n.º 15
0
func lookup() {
	for {
		req := <-requestChan
		req.addrs, req.err = net.LookupHost(req.host)
		req.done <- 1
	}
}
Ejemplo n.º 16
0
// Compares the request's origin with a list of defined origins and allows it if one of them matches
func AllowKnownOrigin(w http.ResponseWriter, req *http.Request) {
	headerOrigin := req.Header.Get("Origin")
	if headerOrigin != "" {
		addr := strings.Split(req.RemoteAddr, ":")[0]
		for _, srcOrigin := range KnownOrigins {
			if srcOrigin == headerOrigin {
				logs.Debug("Match : %s - %s", srcOrigin, headerOrigin)
				w.Header().Set("Access-Control-Allow-Origin", headerOrigin)
				return
			}

			originAddr, err := net.LookupHost(srcOrigin)
			var origin string
			if err == nil {
				origin = originAddr[0]
			} else {
				origin = srcOrigin
			}
			if origin == addr {
				logs.Debug("Match : %s - %s", addr, origin)
				w.Header().Set("Access-Control-Allow-Origin", headerOrigin)
				return
			}
		}
	}
	w.Header().Set("Access-Control-Allow-Origin", "https://cloud.quorumapps.com")
}
Ejemplo n.º 17
0
func testOnGCE() bool {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	resc := make(chan bool, 2)

	// Try two strategies in parallel.
	// See https://github.com/GoogleCloudPlatform/gcloud-golang/issues/194
	go func() {
		res, err := ctxhttp.Get(ctx, metaClient, "http://"+metadataIP)
		if err != nil {
			resc <- false
			return
		}
		defer res.Body.Close()
		resc <- res.Header.Get("Metadata-Flavor") == "Google"
	}()

	go func() {
		addrs, err := net.LookupHost("metadata.google.internal")
		if err != nil || len(addrs) == 0 {
			resc <- false
			return
		}
		resc <- strsContains(addrs, metadataIP)
	}()

	return <-resc
}
Ejemplo n.º 18
0
func BlackList(ip string, bl []string, v string) ([]string, error) {
	result := []string{}

	rIp, ipv := reverseIP(ip)
	if ipv != "ipv4" {
		return result, errors.New(ipv + " not supported")
	}

	if v != "n" {
		log.Println("Reverse:", rIp)
	}

	var wg sync.WaitGroup

	//ToDo add ipv6 blacklist support
	for _, b := range bl {
		wg.Add(1)
		go func(b string) {
			i, err := net.LookupHost(rIp + "." + b)
			if err == nil {
				result = append(result, b)
			}
			if v != "n" {
				log.Println("Checked: ", b, i)
			}
			defer wg.Done()
		}(b)

	}
	wg.Wait()

	return result, nil
}
Ejemplo n.º 19
0
// Resolvable checks if the given host can be resolved on the TCP and UDP nets
func Resolvable(host string) bool {
	_, err := net.LookupHost(host)
	if err == nil {
		return true
	}
	return false
}
Ejemplo n.º 20
0
func detectWildcard(domain string) (bool, map[string]struct{}, error) {
	bytes := make([]byte, 12)
	_, err := rand.Read(bytes)
	if err != nil {
		return false, nil, err
	}

	domain = fmt.Sprintf("%s.%s", hex.EncodeToString(bytes), domain)

	answers, err := net.LookupHost(domain)
	if err != nil {
		if asserted, ok := err.(*net.DNSError); ok && asserted.Err == "no such host" {
			return false, nil, nil
		}

		return false, nil, err
	}

	responses := make(map[string]struct{})

	for _, answer := range answers {
		responses[answer] = struct{}{}
	}

	return true, responses, nil
}
Ejemplo n.º 21
0
func HostAddrIP4(hostaddr string) net.IP {
	// find out what ip4 host address to advertise
	localHost := hostaddr + ":0"
	if hostaddr == "" {
		// no public local host address given by command line
		hostname, err := os.Hostname()
		if err != nil {
			fmt.Println(TAG, "Oops:", err)
			os.Exit(1)
		}
		fmt.Println(TAG, "Hostname", hostname)
		addrs, err := net.LookupHost(hostname)
		if err != nil {
			fmt.Println(TAG, "Oops:", err)
			os.Exit(1)
		}
		for _, a := range addrs {
			fmt.Println(TAG, "range addrs", a)
			localHost = fmt.Sprintf("%s:0", a)
		}
	}
	fmt.Println(TAG, "localHost", localHost)

	// get the localHost address into an IP4 byte array
	localHostAddr, ert := net.ResolveTCPAddr("tcp", localHost)
	if ert != nil {
		fmt.Println("Resolve localHostAddr error", ert)
		os.Exit(1)
	}
	return localHostAddr.IP.To4()
}
Ejemplo n.º 22
0
//(Ljava/lang/String;)[Ljava/net/InetAddress;
func i6di_lookupAllHostAddr(frame *rtda.Frame) {
	vars := frame.LocalVars()
	host := rtda.GoString(vars.GetRef(1))
	address, _ := net.LookupHost(host)
	constructorCount := uint(len(address))

	inetAddress := heap.BootLoader().LoadClass("java/net/InetAddress")
	inetAddressArr := inetAddress.NewArray(constructorCount)

	stack := frame.OperandStack()
	stack.PushRef(inetAddressArr)

	//TODO
	//getByName descriptor:(Ljava/lang/String;)Ljava/net/InetAddress;
	//if constructorCount > 0 {
	//	thread := frame.Thread()
	//	constructorObjs := inetAddressArr.Refs()
	//	inetAddressGetByNameMethod := inetAddress.GetStaticMethod("getByName", "(Ljava/lang/String;)Ljava/net/InetAddress;")

	//	fmt.Println(constructorObjs[0])
	//	fmt.Println(inetAddressGetByNameMethod)
	//	fmt.Println(thread)
	//	thread.InvokeMethodWithShim(inetAddressGetByNameMethod, []interface{}{
	//		constructorObjs[0],
	//		rtda.JString(host),
	//	})
	//}
}
Ejemplo n.º 23
0
// multiscan scans all DNS addresses returned for the host, returning the lowest grade
// and the concatenation of all the output.
func multiscan(host string, scan scanFunc) (grade Grade, output Output, err error) {
	domain, port, _ := net.SplitHostPort(host)
	var addrs []string
	addrs, err = net.LookupHost(domain)
	if err != nil {
		return
	}

	grade = Good
	out := make(map[string]Output)

	for _, addr := range addrs {
		var g Grade
		var o Output

		g, o, err = scan(net.JoinHostPort(addr, port))
		if err != nil {
			grade = Bad
			return
		}

		if g < grade {
			grade = g
		}

		out[addr] = o
	}
	output = out
	return
}
Ejemplo n.º 24
0
func main() {
	flag.Parse()
	file, err := os.Open(*wordlist)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		prefix := scanner.Text()
		host := fmt.Sprintf(prefix + "." + *hostname)

		// If the domain name is created is valid and if
		// it exists print out the domain and the respective IPs
		if isDomainName(host) {
			addrs, err := net.LookupHost(host)
			if err != nil {
				//fmt.Println(err)
				continue
			}
			fmt.Println("\n" + host)
			for _, a := range addrs {
				if isPrivate(a) {
					// Mark the private IPs
					fmt.Print("[+] ")
				}
				fmt.Println(a)
			}

		}
	}
}
Ejemplo n.º 25
0
func (rbl *RBL) LookupRBL(ip net.IP) (RBLResult, error) {
	res := RBLResult{
		Listed: false,
		Ip:     ip,
		Zone:   rbl.Zone,
		Text:   "",
	}

	query, err := rbl.query(ip)
	if err != nil {
		return res, err
	}

	addrs, err := net.LookupHost(query)
	reg, _ := regexp.Compile("(?i:no such host)")
	if err != nil && reg.FindStringIndex(err.Error()) == nil {
		return res, err
	}

	if len(addrs) > 0 {
		res.Listed = true
		text, err := net.LookupTXT(query)
		if err == nil {
			res.Text = strings.Join(text, "\n")
		}
	}

	return res, nil
}
Ejemplo n.º 26
0
func main() {
	flag.Parse()
	c := make(chan int)
	defer close(c)
	if len(os.Args) < 2 {
		usage()
		return
	}

	args := flag.Args()
	max := len(args)
	finised := 0
	for i := 0; i < len(args); i++ {
		go func(i int) {
			defer func() { c <- 1 }()
			for l := 0; l < loop; l++ {
				ips, err := net.LookupHost(args[i])
				if err != nil {
					fmt.Fprintln(os.Stderr, "resolv error:", err.Error())
					return
				}
				fmt.Println("resloved success, ips:", strings.Join(ips, ","))
				if sleep > 0 {
					time.Sleep(1 * time.Second)
				}
			}
		}(i)
	}
	for finised < max {
		select {
		case <-c:
			finised++
		}
	}
}
Ejemplo n.º 27
0
// SimpleHTTPS checks for DNS, public IP and port bindings
func (s *simpleHTTPChallenge) CanSolve(domain string) bool {

	// determine public ip
	resp, err := http.Get("https://icanhazip.com/")
	if err != nil {
		logger().Printf("Could not get public IP -> %v", err)
		return false
	}
	defer resp.Body.Close()

	ip, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		logger().Printf("Could not get public IP -> %v", err)
		return false
	}
	ipStr := string(ip)
	ipStr = strings.Replace(ipStr, "\n", "", -1)

	// resolve domain we should solve for
	resolvedIPs, err := net.LookupHost(domain)
	if err != nil {
		logger().Printf("Could not lookup DNS A record for %s", domain)
		return false
	}

	// if the resolve does not resolve to our public ip, we can't solve.
	for _, resolvedIP := range resolvedIPs {
		if resolvedIP == ipStr {
			return true
		}
	}

	logger().Printf("SimpleHTTP: Domain %s does not resolve to the public ip of this server. Determined IP: %s Resolved IP: %s", domain, ipStr, resolvedIPs[0])
	return false
}
Ejemplo n.º 28
0
// Contains returns true if container includes the given host and false
// otherwise. The specified host can be a DNS name or an IP.
func (i *IPNetContainer) Contains(host string) bool {
	originalHost := host
	if result, exists := i.cache[host]; exists {
		return result
	}

	addToCache := func(result bool) bool {
		i.cache[originalHost] = result
		return result
	}

	ips, err := net.LookupHost(host)
	if err == nil {
		host = ips[0]
	}

	parsedIP := net.ParseIP(host)
	if parsedIP == nil {
		return addToCache(false)
	}

	for _, network := range i.networks {
		if network.Contains(parsedIP) {
			return addToCache(true)
		}
	}

	return addToCache(false)
}
Ejemplo n.º 29
0
// OtherSystemInfo retrieves information from the system like hostname, IPv4 address, pagesize,
// target architecture and target operating system.
func OtherSystemInfo() map[string]string {
	otherInfoMap := make(map[string]string)

	// Hostname
	hostname, err := os.Hostname()
	if err != nil {
		otherInfoMap["hostname"] = "Error: The hostname for the current system could not be retrieved."
	} else {
		otherInfoMap["hostname"] = hostname
	}

	// IP address
	addresses, err := net.LookupHost(hostname)
	if err != nil {
		otherInfoMap["ipv4_address"] = "Error: The IPv4 address for the current system could not be retrieved."
	} else {
		for _, address := range addresses {
			ipv4_address := net.ParseIP(address).To4()
			if ipv4_address != nil {
				otherInfoMap["ipv4_address"] = address
			}
		}
	}

	otherInfoMap["os_pagesize"] = strconv.Itoa(os.Getpagesize())
	otherInfoMap["target_architecture"] = runtime.GOARCH
	otherInfoMap["target_os"] = runtime.GOOS
	return otherInfoMap
}
Ejemplo n.º 30
0
func getPulicIp(hostname string) string {
	if len(hostname) == 0 {
		return ""
	}
	var ipAddr string = ""
	addrs, err := net.LookupHost(hostname)
	if err != nil {
		log.Println(fmt.Sprintf("ERR: Failed to resolve ip address %s", err))
	} else {
		for _, ip := range addrs {
			// Skip ipv6 / local ipaddresses
			if isIpv4Ip(ip) == false && ipv6 == false {
				continue
			}
			// Skip local
			if isLocalIp(ip) == true && noBindLocalhost == true {
				continue
			}
			if debug {
				log.Println(fmt.Sprintf("DEBUG: Host %s resolves to %s", hostname, ip))
			}
			ipAddr = ip
		}
	}
	return ipAddr
}