Skip to content

Commit 1006025

Browse files
author
Tim Cooper
committed
fix IPv6Prefix bug
1 parent 6579be8 commit 1006025

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

attribute.go

+8-5
Original file line numberDiff line numberDiff line change
@@ -467,18 +467,21 @@ func IPv6Prefix(a Attribute) (*net.IPNet, error) {
467467
}
468468

469469
prefixLength := int(a[1])
470-
if (len(a)-2)*8 < prefixLength {
470+
if prefixLength > net.IPv6len*8 {
471471
return nil, errors.New("invalid prefix length")
472472
}
473473

474474
ip := make(net.IP, net.IPv6len)
475475
copy(ip, a[2:])
476476

477-
// clear final non-mask bits
478-
if i := uint(prefixLength % 8); i != 0 {
479-
for ; i < 8; i++ {
480-
ip[prefixLength/8] &^= 1 << (7 - i)
477+
bit := uint(prefixLength % 8)
478+
for octet := prefixLength / 8; octet < len(ip); octet++ {
479+
for ; bit < 8; bit++ {
480+
if ip[octet]&(1<<(7-bit)) != 0 {
481+
return nil, errors.New("invalid prefix data")
482+
}
481483
}
484+
bit = 0
482485
}
483486

484487
return &net.IPNet{

attribute_test.go

+13
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,19 @@ func TestIPv6Prefix(t *testing.T) {
130130
}
131131
}
132132

133+
func TestIPv6Prefix_issue118(t *testing.T) {
134+
ipNet, err := IPv6Prefix([]byte{0x00, 0x40, 0x20, 0x01, 0x15, 0x30, 0x10, 0x0e})
135+
if err != nil {
136+
t.Fatalf("unexpected error: %s", err)
137+
}
138+
if expected := net.ParseIP("2001:1530:100e::"); !ipNet.IP.Equal(expected) {
139+
t.Fatalf("got %v, expected %v", ipNet.IP, expected)
140+
}
141+
if ones, size := ipNet.Mask.Size(); ones != 64 || size != 128 {
142+
t.Fatalf("got %v:%v, expected 64, 128", ones, size)
143+
}
144+
}
145+
133146
func ipNetEquals(a, b *net.IPNet) bool {
134147
if a == nil && b == nil {
135148
return true

0 commit comments

Comments
 (0)