Skip to content

Commit

Permalink
Update ParseSubnets to account for IPv6
Browse files Browse the repository at this point in the history
  • Loading branch information
kirkhauck committed Sep 5, 2023
1 parent dc17f30 commit 58dd47e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 12 deletions.
7 changes: 6 additions & 1 deletion parser/filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ func TestFilterDomain(t *testing.T) {

func TestFilterSingleIP(t *testing.T) {

fsTest := &filter{
fsTest := filter{
// purposely omitting internal subnet definition
alwaysIncluded: util.ParseSubnets([]string{"10.0.0.1/32", "10.0.0.3/32", "1.1.1.1/32", "1.1.1.3/32"}),
neverIncluded: util.ParseSubnets([]string{"10.0.0.4/32", "10.0.0.3/32", "1.1.1.2/32", "1.1.1.3/32"}),
Expand All @@ -207,3 +207,8 @@ func TestFilterSingleIP(t *testing.T) {
assert.Equal(t, test.out, output, test.msg)
}
}

// In alwaysIncluded, just leave it as an empty slice, replace
// util.ParseSubnets with []*net.IPNet
// In neverIncluded, include the IPv6 address without CIDR.
// Test case will be modeled after the "never" test case
35 changes: 24 additions & 11 deletions util/ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,30 +26,43 @@ func init() {
})
}

//ParseSubnets parses the provided subnets into net.ipnet format
func ParseSubnets(subnets []string) (parsedSubnets []*net.IPNet) {
// ParseSubnets parses the provided subnets into net.IPNet format
func ParseSubnets(subnets []string) []*net.IPNet {
var parsedSubnets []*net.IPNet

for _, entry := range subnets {
//try to parse out cidr range
// Try to parse out CIDR range
_, block, err := net.ParseCIDR(entry)

//if there was an error, check if entry was an IP not a range
// If there was an error, check if entry was an IP, not a range
if err != nil {
// try to parse out IP as range of single host
_, block, err = net.ParseCIDR(entry + "/32")
ipAddr := net.ParseIP(entry)
if ipAddr == nil {
fmt.Fprintf(os.Stdout, "Error parsing entry: %s\n", err.Error())
continue
}

// Check if it's an IPv4 or IPv6 address and append the appropriate subnet mask
var subnetMask string
if ipAddr.To4() != nil {
subnetMask = "/32" // IPv4
} else {
subnetMask = "/128" // IPv6
}

// Append the subnet mask and parse as a CIDR range
_, block, err = net.ParseCIDR(entry + subnetMask)

// if error, report and return
if err != nil {
fmt.Fprintf(os.Stdout, "Error parsing CIDR entry: %s\n", err.Error())
os.Exit(-1)
return
continue
}
}

// add cidr range to list
// Add CIDR range to the list
parsedSubnets = append(parsedSubnets, block)
}
return
return parsedSubnets
}

//IPIsPubliclyRoutable checks if an IP address is publicly routable. See privateIPBlocks.
Expand Down

0 comments on commit 58dd47e

Please sign in to comment.