From 95b7f5530f9bf530e77a5797cce21f7bad744f84 Mon Sep 17 00:00:00 2001 From: "Lawrence, Rendall" Date: Tue, 5 Mar 2024 11:01:18 +0300 Subject: [PATCH] change math/rand to crypto/rand in non-test code --- .golangci.yaml | 1 - cmd/mochi/server_test.go | 15 ++++++++++++--- frontend/http/frontend_test.go | 8 ++++++-- frontend/udp/connection_id_test.go | 1 + frontend/udp/frontend.go | 22 ++++++++++++---------- middleware/jwt/jwt_test.go | 10 +++++++--- pkg/xorshift/prng_test.go | 3 +++ storage/test/storage_bench.go | 1 + 8 files changed, 42 insertions(+), 19 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 7eb8775..fcae1c9 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -14,7 +14,6 @@ linters-settings: - "all" gosec: excludes: - - "G404" # Allow the usage of math/rand - "G505" # Allow SHA1 usage linters: enable: diff --git a/cmd/mochi/server_test.go b/cmd/mochi/server_test.go index 5af270b..757a11f 100644 --- a/cmd/mochi/server_test.go +++ b/cmd/mochi/server_test.go @@ -67,6 +67,7 @@ func buildUDPConnReq() []byte { copy(req, udpConnectHeader) // TxID + // nolint:gosec binary.BigEndian.PutUint32(req[12:16], rand.Uint32()) return req } @@ -127,12 +128,15 @@ func buildAnnounceUDPReq(txID, connID []byte) []byte { copy(req[12:16], txID) // InfoHash + // nolint:gosec copy(req[16:36], hashes[rand.Intn(len(hashes))]) // PeerID + // nolint:gosec copy(req[36:56], peers[rand.Intn(len(peers))]) var down, left uint64 + // nolint:gosec if rand.Intn(2) == 0 { down, left = 1, 0 } else { @@ -150,6 +154,7 @@ func buildAnnounceUDPReq(txID, connID []byte) []byte { req[92], req[95] = byte(announceNumWant>>24), byte(announceNumWant>>16) // Port + // nolint:gosec p := rand.Intn(math.MaxInt16) + 1 req[96], req[97] = byte(p>>8), byte(p) return req @@ -251,6 +256,7 @@ func BenchmarkServerHTTPAnnounce(b *testing.B) { addr := "127.0.0.1" + frontend.DefaultListenAddress for i := range reqs { var down, left string + // nolint:gosec if rand.Intn(2) == 0 { down, left = "1", "0" } else { @@ -267,9 +273,12 @@ func BenchmarkServerHTTPAnnounce(b *testing.B) { "downloaded": []string{down}, "uploaded": []string{"0"}, "numwant": []string{"1"}, - "port": []string{strconv.FormatInt(int64(rand.Intn(math.MaxInt16)+1), 10)}, - "info_hash": []string{str2bytes.BytesToString(hashes[rand.Intn(len(hashes))])}, - "peer_id": []string{str2bytes.BytesToString(peers[rand.Intn(len(peers))])}, + // nolint:gosec + "port": []string{strconv.FormatInt(int64(rand.Intn(math.MaxInt16)+1), 10)}, + // nolint:gosec + "info_hash": []string{str2bytes.BytesToString(hashes[rand.Intn(len(hashes))])}, + // nolint:gosec + "peer_id": []string{str2bytes.BytesToString(peers[rand.Intn(len(peers))])}, }.Encode(), } reqs[i] = u.String() diff --git a/frontend/http/frontend_test.go b/frontend/http/frontend_test.go index f47271b..16fb041 100644 --- a/frontend/http/frontend_test.go +++ b/frontend/http/frontend_test.go @@ -18,6 +18,7 @@ import ( ) var ( + // nolint:gosec addr = fmt.Sprintf("127.0.0.1:%d", rand.Int63n(10000)+16384) hashes = make([]string, 10) peers = make([]string, 10) @@ -27,6 +28,7 @@ func init() { _ = log.ConfigureLogger("", "error", false, false) for i := range hashes { var bb []byte + // nolint:gosec if rand.Int()%2 == 0 { bb = make([]byte, bittorrent.InfoHashV1Len) } else { @@ -106,8 +108,10 @@ func BenchmarkAnnounce(b *testing.B) { "uploaded": []string{"0"}, "numwant": []string{"1"}, "port": []string{"12345"}, - "info_hash": []string{hashes[rand.Intn(len(hashes))]}, - "peer_id": []string{peers[rand.Intn(len(peers))]}, + // nolint:gosec + "info_hash": []string{hashes[rand.Intn(len(hashes))]}, + // nolint:gosec + "peer_id": []string{peers[rand.Intn(len(peers))]}, }.Encode(), } if err := runGet(u.String(), true); err != nil { diff --git a/frontend/udp/connection_id_test.go b/frontend/udp/connection_id_test.go index dae1ef9..a73dc14 100644 --- a/frontend/udp/connection_id_test.go +++ b/frontend/udp/connection_id_test.go @@ -50,6 +50,7 @@ func simpleNewConnectionID(ip netip.Addr, now time.Time, key []byte) []byte { mac := hmac.New(func() hash.Hash { return xxhash.New() }, key) + // nolint:gosec buffer[0] = byte(rand.Int()) binary.BigEndian.PutUint64(buffer[1:], uint64(now.Unix())) mac.Write(buffer) diff --git a/frontend/udp/frontend.go b/frontend/udp/frontend.go index 4e9a350..596a58a 100644 --- a/frontend/udp/frontend.go +++ b/frontend/udp/frontend.go @@ -5,10 +5,10 @@ package udp import ( "bytes" "context" + "crypto/rand" "encoding/binary" "errors" "io" - "math/rand" "net" "net/netip" "sync" @@ -26,17 +26,15 @@ import ( const ( // Name - registered name of the frontend - Name = "udp" - defaultKeyLen = 32 - maxAllowedClockSkew = 30 * time.Second - defaultMaxClockSkew = 10 * time.Second -) - -var ( - logger = log.NewLogger("frontend/udp") + Name = "udp" + defaultKeyLen = 32 + maxAllowedClockSkew = 30 * time.Second + defaultMaxClockSkew = 10 * time.Second allowedGeneratedPrivateKeyRunes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" ) +var logger = log.NewLogger("frontend/udp") + func init() { frontend.RegisterBuilder(Name, NewFrontend) } @@ -67,8 +65,12 @@ func (cfg Config) Validate() (validCfg Config) { // Generate a private key if one isn't provided by the user. if cfg.PrivateKey == "" { pkeyRunes := make([]byte, defaultKeyLen) + if _, err := rand.Read(pkeyRunes); err != nil { + panic(err) + } + l := len(allowedGeneratedPrivateKeyRunes) for i := range pkeyRunes { - pkeyRunes[i] = allowedGeneratedPrivateKeyRunes[rand.Intn(len(allowedGeneratedPrivateKeyRunes))] + pkeyRunes[i] = allowedGeneratedPrivateKeyRunes[int(pkeyRunes[i])%l] } validCfg.PrivateKey = string(pkeyRunes) diff --git a/middleware/jwt/jwt_test.go b/middleware/jwt/jwt_test.go index 0b338fa..cf5cb64 100644 --- a/middleware/jwt/jwt_test.go +++ b/middleware/jwt/jwt_test.go @@ -102,7 +102,8 @@ func TestHook_HandleAnnounceValid(t *testing.T) { Audience: []string{"test"}, ExpiresAt: &jwt.NumericDate{Time: time.Now().Add(time.Hour)}, NotBefore: &jwt.NumericDate{Time: time.Now().Add(-time.Hour)}, - ID: strconv.FormatInt(rand.Int63(), 16), + // nolint:gosec + ID: strconv.FormatInt(rand.Int63(), 16), }, InfoHash: infoHash.String(), }) @@ -145,7 +146,8 @@ func TestHook_HandleAnnounceInvalid(t *testing.T) { Audience: []string{"test"}, ExpiresAt: &jwt.NumericDate{Time: time.Now().Add(time.Hour)}, NotBefore: &jwt.NumericDate{Time: time.Now().Add(-time.Hour)}, - ID: strconv.FormatInt(rand.Int63(), 16), + // nolint:gosec + ID: strconv.FormatInt(rand.Int63(), 16), }, InfoHash: infoHash.String(), }) @@ -184,6 +186,7 @@ func TestHook_HandleScrapeValid(t *testing.T) { })) defer s.Close() + // nolint:gosec ihs := make(bittorrent.InfoHashes, rand.Intn(10)+1) ihss := make([]string, len(ihs)) for i := range ihs { @@ -200,7 +203,8 @@ func TestHook_HandleScrapeValid(t *testing.T) { Audience: []string{"test"}, ExpiresAt: &jwt.NumericDate{Time: time.Now().Add(time.Hour)}, NotBefore: &jwt.NumericDate{Time: time.Now().Add(-time.Hour)}, - ID: strconv.FormatInt(rand.Int63(), 16), + // nolint:gosec + ID: strconv.FormatInt(rand.Int63(), 16), }, InfoHashes: ihss, }) diff --git a/pkg/xorshift/prng_test.go b/pkg/xorshift/prng_test.go index ce93c0b..b07ab22 100644 --- a/pkg/xorshift/prng_test.go +++ b/pkg/xorshift/prng_test.go @@ -8,12 +8,14 @@ import ( func BenchmarkRand(b *testing.B) { var cnt uint64 for i := 0; i < b.N; i++ { + // nolint:gosec cnt = rand.Uint64() } _ = cnt } func BenchmarkXoRoShiRo128SS(b *testing.B) { + // nolint:gosec v, s0, s1 := uint64(0), rand.Uint64(), rand.Uint64() for i := 0; i < b.N; i++ { v, s0, s1 = XoRoShiRo128SS(s0, s1) @@ -22,6 +24,7 @@ func BenchmarkXoRoShiRo128SS(b *testing.B) { } func BenchmarkXorShift64Star(b *testing.B) { + // nolint:gosec v, s := uint64(0), rand.Uint64() for i := 0; i < b.N; i++ { v, s = XorShift64S(s) diff --git a/storage/test/storage_bench.go b/storage/test/storage_bench.go index cac5e8b..349a1f8 100644 --- a/storage/test/storage_bench.go +++ b/storage/test/storage_bench.go @@ -48,6 +48,7 @@ func generatePeers() (a [peersCount]bittorrent.Peer) { if !ok { panic("unable to create ip from random bytes") } + // nolint:gosec port := uint16(rand.Int63()) a[i] = bittorrent.Peer{ ID: randPeerID(),