Skip to content

Commit d170acb

Browse files
committed
Fix IPFamilyOf to notice bad *net.IPNets
A manually-constructed IPNet could have a Mask that doesn't match its IP (in which case .String() would return "<nil>" and .Contains() would always return false). So treat that as IPFamilyUnknown.
1 parent df38949 commit d170acb

File tree

2 files changed

+9
-15
lines changed

2 files changed

+9
-15
lines changed

net/v2/ipfamily.go

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -117,10 +117,16 @@ func IPFamilyOfString(ip string) IPFamily {
117117

118118
// IPFamilyOfCIDR returns the IP family of cidr.
119119
func IPFamilyOfCIDR(cidr *net.IPNet) IPFamily {
120-
if cidr == nil {
121-
return IPFamilyUnknown
120+
if cidr != nil {
121+
family := IPFamilyOf(cidr.IP)
122+
// An IPv6 CIDR must have a 128-bit mask. An IPv4 CIDR must have a
123+
// 32- or 128-bit mask. (Any other mask length is invalid.)
124+
_, masklen := cidr.Mask.Size()
125+
if masklen == 128 || (family == IPv4 && masklen == 32) {
126+
return family
127+
}
122128
}
123-
return IPFamilyOf(cidr.IP)
129+
return IPFamilyUnknown
124130
}
125131

126132
// IPFamilyOfCIDRString returns the IP family of cidr.

net/v2/ips_test.go

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -669,18 +669,12 @@ var badTestCIDRs = []testCIDR{
669669
ipnets: []*net.IPNet{
670670
{IP: net.IP{192, 168, 0, 0}, Mask: net.IPMask{255, 0, 255, 0}},
671671
},
672-
673-
// IPFamilyOfCIDR only looks at IP and doesn't notice that Mask is invalid
674-
skipFamily: true,
675672
},
676673
{
677674
desc: "IPNet containing IPv6 IP and IPv4 Mask is invalid",
678675
ipnets: []*net.IPNet{
679676
{IP: net.IP{0x20, 0x01, 0x0D, 0xB8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, Mask: net.CIDRMask(24, 32)},
680677
},
681-
682-
// IPFamilyOfCIDR only looks at IP and doesn't notice that Mask is invalid
683-
skipFamily: true,
684678
},
685679
{
686680
desc: "the zero netip.Prefix is invalid",
@@ -702,19 +696,13 @@ var badTestCIDRs = []testCIDR{
702696
prefixes: []netip.Prefix{
703697
netip.PrefixFrom(netip.IPv4Unspecified(), -1),
704698
},
705-
706-
// IPFamilyOf only looks at IP and doesn't notice that Mask is invalid
707-
skipFamily: true,
708699
},
709700
{
710701
desc: "Prefix containing a too-long length is invalid",
711702
family: IPv4,
712703
prefixes: []netip.Prefix{
713704
netip.PrefixFrom(netip.IPv4Unspecified(), 64),
714705
},
715-
716-
// IPFamilyOf only looks at IP and doesn't notice that Mask is invalid
717-
skipFamily: true,
718706
},
719707
}
720708

0 commit comments

Comments
 (0)