From 5db7ea1732ae204ccf9709aa3a87dcfbe130af08 Mon Sep 17 00:00:00 2001 From: Muhammad Iqbal Alaydrus Date: Tue, 22 Nov 2022 17:31:22 +0700 Subject: [PATCH] - fixing incorrect IP comparison. `unsafeCompare` was comparing between converted IP address with IP string. - `IPInRange` should be both inclusive to accommodate /32 private subnet additions - added more tests --- core/netutil/ip.go | 8 +------- core/netutil/ip_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/core/netutil/ip.go b/core/netutil/ip.go index 77173735..f8984e72 100644 --- a/core/netutil/ip.go +++ b/core/netutil/ip.go @@ -4,7 +4,6 @@ import ( "bytes" "net" "strings" - "unsafe" ) /* Based on: @@ -18,14 +17,9 @@ type IPRange struct { End string `ini:"end" json:"end" yaml:"End" toml:"End"` } -func unsafeCompare(a []byte, b string) int { - bb := *(*[]byte)(unsafe.Pointer(&b)) - return bytes.Compare(a, bb) -} - // IPInRange reports whether a given IP Address is within a range given. func IPInRange(r IPRange, ipAddress net.IP) bool { - return unsafeCompare(ipAddress, r.Start) >= 0 && unsafeCompare(ipAddress, r.End) < 0 + return bytes.Compare(ipAddress, net.ParseIP(r.Start)) >= 0 && bytes.Compare(ipAddress, net.ParseIP(r.End)) <= 0 } // IPIsPrivateSubnet reports whether this "ipAddress" is in a private subnet. diff --git a/core/netutil/ip_test.go b/core/netutil/ip_test.go index ac4eb4aa..a02e65c6 100644 --- a/core/netutil/ip_test.go +++ b/core/netutil/ip_test.go @@ -58,4 +58,34 @@ func TestIP(t *testing.T) { if expected := "126.105.144.250"; expected != got { t.Logf("expected addr to be found: %s but got: %s", expected, got) } + + addresses = []string{ + "10.10.233.1", + "126.105.144.250", + "192.168.99.33", + "172.18.22.23", + "10.0.0.0", + "10.255.255.255", + } + + got, ok = GetIPAddress(addresses, privateRanges) + if !ok { + t.Logf("expected addr to be matched") + } + + if expected := "126.105.144.250"; expected != got { + t.Logf("expected addr to be found: %s but got: %s", expected, got) + } + + addresses = []string{ + "10.0.0.0", + "10.10.233.1", + "192.168.99.33", + "172.18.22.23", + } + + got, ok = GetIPAddress(addresses, privateRanges) + if ok { + t.Logf("expected addr to not be matched") + } }