Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix crypto/rand: argument to Int is <= 0 #4077

Merged
merged 1 commit into from
May 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pkg/util/net.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ func genRandomIP(cidr string, isIPv6 bool) string {
if isIPv6 {
hostBits = 128 - netMask
}
add, err := rand.Int(rand.Reader, big.NewInt(1<<(uint(hostBits)-1)))
add, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), uint(hostBits)-1))
if err != nil {
LogFatalAndExit(err, "failed to generate random ip")
}
Expand Down
45 changes: 45 additions & 0 deletions pkg/util/net_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,51 @@ func TestGenerateRandomV4IP(t *testing.T) {
}
}

func TestGenerateRandomV6IP(t *testing.T) {
tests := []struct {
name string
cidr string
wantErr bool
wantIPv6 bool
}{
{
name: "valid IPv6 CIDR",
cidr: "2001:db8::/64",
wantErr: false,
wantIPv6: true,
},
{
name: "invalid CIDR format",
cidr: "2001:db8::1",
wantErr: true,
wantIPv6: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ip := GenerateRandomV6IP(tt.cidr)
if tt.wantErr {
if ip != "" {
t.Errorf("GenerateRandomV6IP(%s) = %s; want empty string", tt.cidr, ip)
}
return
}

parsedIP, _, err := net.ParseCIDR(ip)
if err != nil {
t.Errorf("GenerateRandomV6IP(%s) returned invalid IP: %v", tt.cidr, err)
return
}

isIPv6 := parsedIP.To4() == nil
if isIPv6 != tt.wantIPv6 {
t.Errorf("GenerateRandomV6IP(%s) returned %v; want IPv6: %v", tt.cidr, parsedIP, tt.wantIPv6)
}
})
}
}

func TestIPToString(t *testing.T) {
tests := []struct {
name string
Expand Down
Loading