// Helper function, checks if the given IP is within one of the reserved IP
// address ranges. See ipv4NetFiltered and ipv6NetFiltered variable
// initialization in init().
func isInAddressRange(ip net.IP, ipv4ranges, ipv6ranges []*net.IPNet) bool {
	if len(ip) == net.IPv4len {
		for _, net := range ipv4ranges {
			if net.Contains(ip) {
				return true
			}
		}
	} else if len(ip) == net.IPv6len {
		for _, net := range ipv6ranges {
			if net.Contains(ip) {
				return true
			}
		}
	}
	return false
}
Ejemplo n.º 2
0
func lookup(stmt *sql.Stmt, IP net.IP, nIP uint32) (*GeoIP, error) {
	var reserved bool
	for _, net := range reservedIPs {
		if net.Contains(IP) {
			reserved = true
			break
		}
	}
	geoip := GeoIP{Ip: IP.String()}
	if reserved {
		geoip.CountryCode = "RD"
		geoip.CountryName = "Reserved"
	} else {
		if err := stmt.QueryRow(nIP).Scan(
			&geoip.CountryCode,
			&geoip.CountryName,
			&geoip.RegionCode,
			&geoip.RegionName,
			&geoip.CityName,
			&geoip.ZipCode,
			&geoip.Latitude,
			&geoip.Longitude,
			&geoip.MetroCode,
			&geoip.AreaCode,
		); err != nil {
			return nil, err
		}
	}
	return &geoip, nil
}
Ejemplo n.º 3
0
func exportReverse(db *database.DB, domain *database.Domain) (string, error) {
	_, net, err := net.ParseCIDR(domain.Name)
	if err != nil {
		panic("Export reverse on a non-CIDR")
	}
	if ones, _ := net.Mask.Size(); ones%8 != 0 {
		return "", fmt.Errorf("Reverse zone CIDR must be 8-bit aligned, cannot generate zone for %s", net)
	}

	ret := []string{
		fmt.Sprintf("$ORIGIN %s", arpaZone(net)),
		"$TTL 600",
		domain.SOA(),
		"",
	}

	for _, host := range db.Hosts {
		for _, addr := range sortedAddrs(host) {
			if !net.Contains(addr) {
				continue
			}

			if fqdn := host.Attrs["fqdn"]; fqdn != "" {
				ret = append(ret, fmt.Sprintf("%s IN PTR %s.", arpaHost(net, addr), fqdn))
			} else if hostname := host.Attrs["hostname"]; hostname != "" {
				if domain := ipDomain(host, addr); domain != "" {
					ret = append(ret, fmt.Sprintf("%s IN PTR %s.%s.", arpaHost(net, addr), hostname, domain))
				}
			}
		}
	}

	return strings.Join(ret, "\n"), nil
}
Ejemplo n.º 4
0
func (p *PerHost) dialerForRequest(host string) Dialer {
	if ip := net.ParseIP(host); ip != nil {
		for _, net := range p.bypassNetworks {
			if net.Contains(ip) {
				return p.bypass
			}
		}
		for _, bypassIP := range p.bypassIPs {
			if bypassIP.Equal(ip) {
				return p.bypass
			}
		}
		return p.def
	}

	for _, zone := range p.bypassZones {
		if strings.HasSuffix(host, zone) {
			return p.bypass
		}
		if host == zone[1:] {
			// For a zone "example.com", we match "example.com"
			// too.
			return p.bypass
		}
	}
	for _, bypassHost := range p.bypassHosts {
		if bypassHost == host {
			return p.bypass
		}
	}
	return p.def
}
Ejemplo n.º 5
0
func (h *handler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	tmp := strings.Split(r.RemoteAddr, ":")
	ip := net.ParseIP(tmp[0])

	if ip.String() == "127.0.0.1" {
		// allow the proxy header to be used instead..
		forwarded_for := r.Header.Get("X-Forwarded-For")
		if forwarded_for != "" {
			log.Infof("TODO: Forwarded for %s", forwarded_for)
		}

	}

	allowed := false
	for _, net := range h.nets {
		if net.Contains(ip) {
			allowed = true
			break
		}
	}
	// fmt.Printf("%s access=%v\n", tmp[0], allowed)
	if allowed == false {
		rw.WriteHeader(http.StatusForbidden)
		fmt.Fprintf(rw, "Forbidden")
		return
	}
	h.Handler.ServeHTTP(rw, r)
}
Ejemplo n.º 6
0
func GeoipLookup(stmt *sql.Stmt, ip string) (*GeoIP, error) {
	IP := net.ParseIP(ip)
	reserved := false
	for _, net := range reservedIPs {
		if net.Contains(IP) {
			reserved = true
			break
		}
	}
	geoip := GeoIP{Ip: ip}
	if reserved {
		geoip.CountryCode = "RD"
		geoip.CountryName = "Reserved"
	} else {
		var uintIP uint32
		b := bytes.NewBuffer(IP.To4())
		binary.Read(b, binary.BigEndian, &uintIP)
		if err := stmt.QueryRow(uintIP).Scan(
			&geoip.CountryCode,
			&geoip.CountryName,
			&geoip.RegionCode,
			&geoip.RegionName,
			&geoip.CityName,
			&geoip.ZipCode,
			&geoip.Latitude,
			&geoip.Longitude,
			&geoip.MetroCode,
			&geoip.AreaCode,
		); err != nil {
			return nil, err
		}
	}
	return &geoip, nil
}
Ejemplo n.º 7
0
// handleProxy /p/fileid=asdf;token=asdf;gid=123;page=321;passkey=asdf/filename
func (s *DefaultServer) handleProxy(c *gin.Context) {
	mode := s.cfg.Settings.ProxyMode
	if mode == ProxyDisabled {
		c.String(http.StatusForbidden, "proxy disabled")
		return
	}
	args := ParseArgs(c.Param("kwds"))
	fileID := args.Get("fileid")
	f, err := FileFromID(fileID)
	if err != nil {
		log.Println("proxy:", "bad file id", fileID, err)
		c.String(http.StatusBadRequest, "400: bad file id")
		return
	}
	galleryID := args.GetInt("gid")
	page := args.GetInt("page")
	passkey := args.Get("passkey")
	token := args.Get("token")
	filename := c.Param("filename")

	if s.db.Exists(f) {
		log.Println("proxy:", "file already exists; serving from cache", f)
		s.frontend.Handle(f, c.Writer)
		s.events <- Event{EventSent, f}
		return
	}

	if mode == ProxyLocalNetworksOpen || mode == ProxyLocalNetworksProtected {
		ip, err := FromRequest(c.Request)
		if err != nil {
			log.Println("proxy:", "unable to extract ip from", c.Request.RemoteAddr)
			c.String(http.StatusInternalServerError, "unable to parse ip")
			return
		}
		var isLocal bool
		for _, net := range LocalNetworks {
			if net.Contains(ip) {
				isLocal = true
				break
			}
		}
		if !isLocal {
			log.Println("proxy:", "access from non-local network by", ip, "<-", c.Request.RemoteAddr)
			c.String(http.StatusForbidden, "bad ip")
			return
		}
	}

	if mode == ProxyLocalNetworksProtected || mode == ProxyAllNetworksProtected {
		// checking passkey
		if passkey != s.proxyPasskey(f) {
			log.Println("proxy:", "bad passkey provided")
			c.String(http.StatusForbidden, "bad passkey")
			return
		}
	}

	s.proxy(c, f, token, galleryID, page, filename)
}
Ejemplo n.º 8
0
// Contains returns true if IP is in Networks.
func (n Networks) Contains(ip net.IP) bool {
	for _, net := range n {
		if net.Contains(ip) {
			return true
		}
	}
	return false
}
Ejemplo n.º 9
0
func isPrivateV4(ip net.IP) bool {
	for _, net := range privateNetworks {
		if net.Contains(ip) {
			return true
		}
	}
	return false
}
Ejemplo n.º 10
0
func isPrivateIp(ip net.IP) bool {
	for _, net := range privateIpNets {
		if net.Contains(ip) {
			return true
		}
	}
	return false
}
Ejemplo n.º 11
0
func cidrMatches(ip net.IP, cidr string) bool {
	_, net, err := net.ParseCIDR(cidr)
	if err != nil {
		http_sheep.Baa(1, "Invalid CIDR for allowed_gre_addr in the configuration file: %s", cidr)
		return false
	}
	return net.Contains(ip)
}
Ejemplo n.º 12
0
func GeoipLookup(db *sql.DB, ip string) (*GeoIP, error) {
	IP := net.ParseIP(ip)
	reserved := false
	for _, net := range reservedIPs {
		if net.Contains(IP) {
			reserved = true
			break
		}
	}
	geoip := GeoIP{Ip: ip}
	if reserved {
		geoip.CountryCode = "RD"
		geoip.CountryName = "Reserved"
	} else {
		q := `SELECT
		  city_location.country_code, country_blocks.country_name,
		  city_location.region_code, region_names.region_name,
		  city_location.city_name, city_location.postal_code,
		  city_location.latitude, city_location.longitude,
		  city_location.metro_code, city_location.area_code
		FROM city_blocks
		  NATURAL JOIN city_location
		  INNER JOIN country_blocks ON
		    city_location.country_code = country_blocks.country_code
		  LEFT OUTER JOIN region_names ON
		    city_location.country_code = region_names.country_code
		    AND
		    city_location.region_code = region_names.region_code
		WHERE city_blocks.ip_start <= ?
		ORDER BY city_blocks.ip_start DESC LIMIT 1`
		stmt, err := db.Prepare(q)
		if err != nil {
			if debug {
				log.Println("[debug] SQLite", err.Error())
			}
			return nil, err
		}
		defer stmt.Close()
		var uintIP uint32
		b := bytes.NewBuffer(IP.To4())
		binary.Read(b, binary.BigEndian, &uintIP)
		err = stmt.QueryRow(uintIP).Scan(
			&geoip.CountryCode,
			&geoip.CountryName,
			&geoip.RegionCode,
			&geoip.RegionName,
			&geoip.CityName,
			&geoip.ZipCode,
			&geoip.Latitude,
			&geoip.Longitude,
			&geoip.MetroCode,
			&geoip.AreaCode)
		if err != nil {
			return nil, err
		}
	}
	return &geoip, nil
}
Ejemplo n.º 13
0
// Helper function, checks if the given IP is within one of the reserved IP
// address ranges. See ipv4NetFiltered and ipv6NetFiltered variable
// initialization in init().
func isFiltered(ip net.IP) bool {
	if len(ip) == net.IPv4len {
		for _, net := range ipv4NetFiltered {
			if net.Contains(ip) {
				return true
			}
		}

	} else if len(ip) == net.IPv6len {
		for _, net := range ipv6NetFiltered {
			if net.Contains(ip) {
				return true
			}
		}
	}

	return false
}
Ejemplo n.º 14
0
func ipFilter(addr string, nets *[]*net.IPNet) bool {
	if ip := net.ParseIP(addr); ip != nil {
		for _, net := range *nets {
			if net.Contains(ip) {
				return true
			}
		}
	}
	return false
}
Ejemplo n.º 15
0
Archivo: ip.go Proyecto: kmchen/gonexmo
// IsTrustedIP returns true if the provided IP address came from
// a trusted Nexmo server.
func IsTrustedIP(ipStr string) bool {
	ip := net.ParseIP(ipStr)

	for _, net := range subnets {
		if net.Contains(ip) {
			return true
		}
	}
	return false
}
Ejemplo n.º 16
0
func (f *summaryFormatter) trackIp(ip net.IP) {
	for _, net := range f.ipAddrs {
		if net.Contains(ip) {
			return
		}
	}

	ipNet := net.IPNet{ip, ip.DefaultMask()}
	f.ipAddrs = append(f.ipAddrs, ipNet)
	f.netStrings = append(f.netStrings, ipNet.String())
}
Ejemplo n.º 17
0
func IsPrivate(ipString string) bool {
	if privateNetworks == nil {
		Init()
	}

	ip := net.ParseIP(ipString)
	for _, net := range privateNetworks {
		if net.Contains(ip) {
			return true
		}
	}
	return false
}
Ejemplo n.º 18
0
// Utility routine to look up a network by member IP @ips in @networks.
// Return pointer to matching network if found, else nil.
func NetworkByIP(ips string, networks []Network) (*Network, error) {
	ip := net.ParseIP(ips)
	if ip == nil {
		return nil, errors.Errorf("Invalid IP address %s", ips)
	}
	for i := range networks {
		if _, net, err := net.ParseCIDR(networks[i].Cidr); err != nil {
			return nil, errors.Errorf("failed to parse CIDR %s: %s", networks[i].Cidr, err)
		} else if net.Contains(ip) {
			return &networks[i], nil
		}
	}
	return nil, nil
}
Ejemplo n.º 19
0
func (r *restrictedEndpointsAdmission) findRestrictedIP(ep *kapi.Endpoints) string {
	for _, subset := range ep.Subsets {
		for _, addr := range subset.Addresses {
			ip := net.ParseIP(addr.IP)
			if ip == nil {
				continue
			}
			for _, net := range r.restrictedNetworks {
				if net.Contains(ip) {
					return addr.IP
				}
			}
		}
	}
	return ""
}
Ejemplo n.º 20
0
func (db *DB) Lookup(ip net.IP, nIP uint32) (*geoipRecord, error) {
	for _, net := range reservedIPs {
		if net.Contains(ip) {
			return &geoipRecord{
				Ip:          ip.String(),
				CountryCode: "RD",
				CountryName: "Reserved",
			}, nil
		}
	}
	var locId int
	if err := db.stmt.QueryRow(nIP).Scan(&locId); err != nil {
		return nil, err
	}
	return db.newRecord(&ip, locId), nil
}
Ejemplo n.º 21
0
func GeoipLookup(db *sql.DB, ip string) (*GeoIP, error) {
	IP := net.ParseIP(ip)
	reserved := false
	for _, net := range reservedIPs {
		if net.Contains(IP) {
			reserved = true
			break
		}
	}
	geoip := GeoIP{Ip: ip}
	if reserved {
		geoip.CountryCode = "RD"
		geoip.CountryName = "Reserved"
	} else {
		stmt, err := db.Prepare(query)
		if err != nil {
			if conf.Debug {
				log.Println("[debug] SQLite", err.Error())
			}
			return nil, err
		}
		defer stmt.Close()
		var uintIP uint32
		b := bytes.NewBuffer(IP.To4())
		binary.Read(b, binary.BigEndian, &uintIP)
		err = stmt.QueryRow(uintIP).Scan(
			&geoip.CountryCode,
			&geoip.CountryName,
			&geoip.RegionCode,
			&geoip.RegionName,
			&geoip.CityName,
			&geoip.ZipCode,
			&geoip.Latitude,
			&geoip.Longitude,
			&geoip.MetroCode,
			&geoip.AreaCode)
		if err != nil {
			return nil, err
		}
	}
	return &geoip, nil
}
Ejemplo n.º 22
0
func ipdb_lookup(stmt *sql.Stmt, cache *Cache, IP net.IP, nIP uint32) (*GeoIP, error) {
	var reserved bool
	for _, net := range reservedIPs {
		if net.Contains(IP) {
			reserved = true
			break
		}
	}

	geoip := &GeoIP{Ip: IP.String()}
	if reserved {
		geoip.CountryCode = "RD"
		geoip.CountryName = "Reserved"
	} else {
		var locId int
		if err := stmt.QueryRow(nIP).Scan(&locId); err != nil {
			return nil, err
		}

		cache.Update(geoip, locId)
	}

	return geoip, nil
}
Ejemplo n.º 23
0
func Lookup(w http.ResponseWriter, req *http.Request, db *sql.DB) {
	format, addr := req.Vars[0], req.Vars[1]
	if addr == "" {
		addr = req.RemoteAddr // port number previously removed
	} else {
		addrs, err := net.LookupHost(addr)
		if err != nil {
			http.Error(w, http.StatusText(404), 404)
			return
		}
		addr = addrs[0]
	}
	IP := net.ParseIP(addr)
	reserved := false
	for _, net := range reservedIPs {
		if net.Contains(IP) {
			reserved = true
			break
		}
	}
	geoip := GeoIP{Ip: addr}
	if reserved {
		geoip.CountryCode = "RD"
		geoip.CountryName = "Reserved"
	} else {
		q := "SELECT " +
			"  city_location.country_code, country_blocks.country_name, " +
			"  city_location.region_code, region_names.region_name, " +
			"  city_location.city_name, city_location.postal_code, " +
			"  city_location.latitude, city_location.longitude, " +
			"  city_location.metro_code, city_location.area_code " +
			"FROM city_blocks " +
			"  NATURAL JOIN city_location " +
			"  INNER JOIN country_blocks ON " +
			"    city_location.country_code = country_blocks.country_code " +
			"  INNER JOIN region_names ON " +
			"    city_location.country_code = region_names.country_code " +
			"    AND " +
			"    city_location.region_code = region_names.region_code " +
			"WHERE city_blocks.ip_start <= ? " +
			"ORDER BY city_blocks.ip_start DESC LIMIT 1"
		stmt, err := db.Prepare(q)
		if err != nil {
			if debug {
				log.Println("[debug] SQLite", err.Error())
			}
			http.Error(w, http.StatusText(500), 500)
			return
		}
		defer stmt.Close()
		var uintIP uint32
		b := bytes.NewBuffer(IP.To4())
		binary.Read(b, binary.BigEndian, &uintIP)
		err = stmt.QueryRow(uintIP).Scan(
			&geoip.CountryCode,
			&geoip.CountryName,
			&geoip.RegionCode,
			&geoip.RegionName,
			&geoip.CityName,
			&geoip.ZipCode,
			&geoip.Latitude,
			&geoip.Longitude,
			&geoip.MetroCode,
			&geoip.AreaCode)
		if err != nil {
			http.Error(w, http.StatusText(404), 404)
			return
		}
	}
	switch format[0] {
	case 'c':
		w.Header().Set("Content-Type", "application/csv")
		fmt.Fprintf(w, `"%s","%s","%s","%s","%s","%s",`+
			`"%s","%0.4f","%0.4f","%s","%s"`+"\r\n",
			geoip.Ip,
			geoip.CountryCode, geoip.CountryName,
			geoip.RegionCode, geoip.RegionName,
			geoip.CityName, geoip.ZipCode,
			geoip.Latitude, geoip.Longitude,
			geoip.MetroCode, geoip.AreaCode)
	case 'j':
		resp, err := json.Marshal(geoip)
		if err != nil {
			if debug {
				log.Println("[debug] JSON", err.Error())
			}
			http.Error(w, http.StatusText(404), 404)
			return
		}
		callback := req.FormValue("callback")
		if callback != "" {
			w.Header().Set("Content-Type", "text/javascript")
			fmt.Fprintf(w, "%s(%s);\n", callback, resp)
		} else {
			w.Header().Set("Content-Type", "application/json")
			fmt.Fprintf(w, "%s\n", resp)
		}
	case 'x':
		w.Header().Set("Content-Type", "application/xml")
		resp, err := xml.MarshalIndent(geoip, "", " ")
		if err != nil {
			if debug {
				log.Println("[debug] XML", err.Error())
			}
			http.Error(w, http.StatusText(500), 500)
			return
		}
		fmt.Fprintf(w, xml.Header+"%s\n", resp)
	}
}
Ejemplo n.º 24
0
func Lookup(req *web.RequestHandler, db *sql.DB) {
	format, addr := req.Vars[1], req.Vars[2]
	if addr == "" {
		addr = strings.Split(req.HTTP.RemoteAddr, ":")[0]
	} else {
		addrs, err := net.LookupHost(addr)
		if err != nil {
			req.HTTPError(404, "")
			return
		}
		addr = addrs[0]
	}
	IP := net.ParseIP(addr)
	reserved := false
	for _, net := range reservedIPs {
		if net.Contains(IP) {
			reserved = true
			break
		}
	}
	geoip := GeoIP{Ip: addr}
	if reserved {
		geoip.CountryCode = "RD"
		geoip.CountryName = "Reserved"
	} else {
		q := "SELECT " +
			"  city_location.country_code, country_blocks.country_name, " +
			"  city_location.region_code, region_names.region_name, " +
			"  city_location.city_name, city_location.postal_code, " +
			"  city_location.latitude, city_location.longitude, " +
			"  city_location.metro_code, city_location.area_code " +
			"FROM city_blocks " +
			"  NATURAL JOIN city_location " +
			"  INNER JOIN country_blocks ON " +
			"    city_location.country_code = country_blocks.country_code " +
			"  INNER JOIN region_names ON " +
			"    city_location.country_code = region_names.country_code " +
			"    AND " +
			"    city_location.region_code = region_names.region_code " +
			"WHERE city_blocks.ip_start <= ? " +
			"ORDER BY city_blocks.ip_start DESC LIMIT 1"
		stmt, err := db.Prepare(q)
		if err != nil {
			req.HTTPError(500, "SQLite: %s", err.Error())
			return
		}
		defer stmt.Close()
		var uintIP uint32
		b := bytes.NewBuffer(IP.To4())
		binary.Read(b, binary.BigEndian, &uintIP)
		err = stmt.QueryRow(uintIP).Scan(
			&geoip.CountryCode,
			&geoip.CountryName,
			&geoip.RegionCode,
			&geoip.RegionName,
			&geoip.CityName,
			&geoip.ZipCode,
			&geoip.Latitude,
			&geoip.Longitude,
			&geoip.MetroCode,
			&geoip.AreaCode)
		if err != nil {
			req.HTTPError(404, "")
			return
		}
	}
	switch format[0] {
	case 'c':
		req.SetHeader("Content-Type", "application/csv")
		req.Write(`"%s","%s","%s","%s","%s","%s",`+
			`"%s","%0.4f","%0.4f","%s","%s"`+"\r\n",
			geoip.Ip,
			geoip.CountryCode, geoip.CountryName,
			geoip.RegionCode, geoip.RegionName,
			geoip.CityName, geoip.ZipCode,
			geoip.Latitude, geoip.Longitude,
			geoip.MetroCode, geoip.AreaCode)
	case 'j':
		resp, err := json.Marshal(geoip)
		if err != nil {
			req.HTTPError(500, "JSON Marshal: %s", err.Error())
			return
		}
		callback := req.HTTP.FormValue("callback")
		if callback != "" {
			req.SetHeader("Content-Type", "text/javascript")
			req.Write("%s(%s);\r\n", callback, resp)
		} else {
			req.SetHeader("Content-Type", "application/json")
			req.Write("%s\r\n", resp)
		}
	case 'x':
		req.SetHeader("Content-Type", "application/xml")
		resp, err := xml.MarshalIndent(geoip, "", " ")
		if err != nil {
			req.HTTPError(500, "XML Marshal: %s", err.Error())
			return
		}
		req.Write(`<?xml version="1.0" encoding="UTF-8"?>`+
			"%s\r\n", resp)
	}
}