Skip to content
Permalink
Browse files
Fixed geoip lookup to check for invalid IP ranges
The geoip lookup function now returns the empty string for IP addresses
that are not present in the table. New tests for invalid IP address
lookups were added and a bug fix for checking an invalid returned index
  • Loading branch information
cohosh committed Mar 15, 2019
1 parent fbb87b5 commit be4d245375722d958dd85f1a53849cdc37b3382b
Showing with 34 additions and 3 deletions.
  1. +23 −1 broker/geoip.go
  2. +3 −1 broker/metrics.go
  3. +8 −1 broker/snowflake-broker_test.go
@@ -175,6 +175,20 @@ func GeoIPRangeClosure(key net.IP, entry GeoIPEntry) bool {
return true
}

func GeoIPCheckRange (key net.IP, entry GeoIPEntry) bool {
a := key.To16()
b := entry.ipLow.To16()
c := entry.ipHigh.To16()

for i, v := range a {
if v < b[i] || v > c[i] {
return false
}
}

return true
}

//Returns the country location of an IPv4 or IPv6 address.
func GetCountryByAddr(table GeoIPTable, addr string) string {
//translate addr string to IP
@@ -185,7 +199,15 @@ func GetCountryByAddr(table GeoIPTable, addr string) string {
return GeoIPRangeClosure(ip, table.ElementAt(i))
})

if index == -1 {
if index == table.Len() {
return ""
}

// check to see if addr is in the range specified by the returned index
// search on IPs in invalid ranges (e.g., 127.0.0.0/8) will return the
//country code of the next highest range
log.Println("Checking index ", index)
if ! GeoIPCheckRange(ip, table.ElementAt(index)) {
return ""
}

@@ -43,7 +43,9 @@ func (m Metrics) UpdateCountryStats(addr string) {
}

//update map of countries and counts
m.countryStats.counts[country] = m.countryStats.counts[country] + 1
if country != "" {
m.countryStats.counts[country] = m.countryStats.counts[country] + 1
}

}

@@ -278,7 +278,14 @@ func TestGeoip(t *testing.T) {
err = GeoIPLoadFile(tv6, "./geoip6")
So(err, ShouldEqual, nil)

So(GetCountryByAddr(tv4, "129.97.208.23"), ShouldEqual, "CA")
So(GetCountryByAddr(tv4, "129.97.208.23"), ShouldEqual, "CA") //University of Waterloo
So(GetCountryByAddr(tv4, "127.0.0.1"), ShouldEqual, "")
So(GetCountryByAddr(tv4, "0.0.0.0"), ShouldEqual, "")
So(GetCountryByAddr(tv4, "255.255.255.255"), ShouldEqual, "")

So(GetCountryByAddr(tv6, "2620:101:f000:0:250:56ff:fe80:168e"), ShouldEqual, "CA")
So(GetCountryByAddr(tv6, "fd00:0:0:0:0:0:0:1"), ShouldEqual, "")
So(GetCountryByAddr(tv6, "0:0:0:0:0:0:0:0"), ShouldEqual, "")
So(GetCountryByAddr(tv6, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"), ShouldEqual, "")
})
}

0 comments on commit be4d245

Please sign in to comment.