Skip to content

Commit

Permalink
fix crypto/rand: argument to Int is <= 0
Browse files Browse the repository at this point in the history
Signed-off-by: zcq98 <[email protected]>
  • Loading branch information
zcq98 authored and bobz965 committed May 24, 2024
1 parent e31784a commit 1e8c1e6
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
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

0 comments on commit 1e8c1e6

Please sign in to comment.