From d442c8d4c86d9c393f2b6307c7216c98a15de5e5 Mon Sep 17 00:00:00 2001 From: Cosmos Nicolaou Date: Mon, 17 Apr 2023 14:08:08 -0700 Subject: [PATCH] enable gosec linter and fix the errors it reports. (#390) --- .golangci.yml | 1 + v23/flow/message/internal_message_test.go | 6 +++--- v23/security/algo_test.go | 2 +- v23/security/blessings_test.go | 1 + v23/security/publickey.go | 4 ++-- v23/security/signature.go | 11 +++++------ v23/vdl/vdltest/entry_generator.go | 2 +- v23/vdl/vdltest/internal/vdltestgen/main.go | 2 +- v23/vdl/vdltest/type_generator.go | 2 +- v23/vdl/vdltest/value_generator.go | 2 +- v23/vdlroot/time/time_test.go | 4 ++-- v23/vom/vomtest/internal/vomforever/main.go | 2 +- x/ref/cmd/gclogs/format_test.go | 2 +- x/ref/cmd/gclogs/gclogs_test.go | 2 +- x/ref/cmd/principal/bless.go | 7 ++++++- .../principal/internal/scripting/scripting_test.go | 6 +++--- x/ref/lib/discovery/encoding_test.go | 4 ++-- x/ref/lib/discovery/plugins/ble/encoding_test.go | 2 +- x/ref/lib/discovery/plugins/ble/uuid_test.go | 2 +- x/ref/lib/discovery/update_test.go | 2 +- x/ref/lib/discovery/util_test.go | 2 +- x/ref/lib/pubsub/config_test.go | 2 +- .../internal/lockedfile/filelock/filelock_test.go | 2 +- .../internal/lockedfile/lockedfile_test.go | 6 +++--- .../security/internal/lockedfile/transform_test.go | 6 +++--- x/ref/lib/security/principal_test.go | 2 +- .../security/serialization/serialization_test.go | 2 +- x/ref/lib/stats/counter/tracker_test.go | 4 ++-- x/ref/lib/vdl/codegen/swift/util_namespace_test.go | 4 ++-- x/ref/lib/vtrace/store.go | 2 +- x/ref/runtime/internal/cloudvm/cloudpaths/paths.go | 2 +- .../internal/cloudvm/cloudvmtest/aws_mock.go | 5 ++++- .../internal/cloudvm/cloudvmtest/gcp_mock.go | 7 ++++++- x/ref/runtime/internal/flow/conn/readq_test.go | 2 +- x/ref/runtime/internal/flow/conn/writeq_test.go | 6 +++--- x/ref/runtime/internal/naming/namespace/cache.go | 2 +- x/ref/runtime/internal/rpc/client.go | 2 +- x/ref/runtime/internal/rpc/proxymgr.go | 2 +- .../runtime/internal/rpc/stress/internal/client.go | 2 +- x/ref/runtime/internal/rpc/stress/internal/util.go | 10 +++++----- x/ref/runtime/internal/rpc/stress/stress/stress.go | 2 +- x/ref/runtime/internal/rt/security.go | 2 +- x/ref/runtime/protocols/lib/websocket/conn_test.go | 1 + x/ref/runtime/protocols/lib/websocket/listener.go | 5 ++++- .../debug/debug/browseserver/browseserver.go | 8 +++++++- x/ref/services/debug/debug/impl.go | 6 +++++- x/ref/services/http/http/http.go | 10 +++++++++- x/ref/services/internal/pproflib/proxy_test.go | 14 +++++++++----- x/ref/test/basics/tls_test.go | 2 ++ x/ref/test/compatibility/build.go | 2 +- x/ref/test/testutil/rand.go | 2 +- 51 files changed, 117 insertions(+), 75 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index cb8214641..4f446266f 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -16,6 +16,7 @@ linters-settings: linters: enable: - bodyclose + - gosec - gocritic - gocyclo - gofmt diff --git a/v23/flow/message/internal_message_test.go b/v23/flow/message/internal_message_test.go index 5da3778c0..b72f97bc6 100644 --- a/v23/flow/message/internal_message_test.go +++ b/v23/flow/message/internal_message_test.go @@ -21,7 +21,7 @@ import ( func randomTestCases() []uint64 { c := make([]uint64, 4096) for i := range c { - c[i] = rand.Uint64() + c[i] = rand.Uint64() //nolint:gosec } return c } @@ -29,7 +29,7 @@ func randomTestCases() []uint64 { func randomMaxTestCases(limit int64) []uint64 { c := make([]uint64, 4096) for i := range c { - c[i] = uint64(rand.Int63n(limit)) + c[i] = uint64(rand.Int63n(limit)) //nolint:gosec } return c } @@ -38,7 +38,7 @@ func randomLargeTestCases() []uint64 { c := make([]uint64, 4096) for i := range c { for c[i] < math.MaxUint32 { - c[i] = rand.Uint64() + c[i] = rand.Uint64() //nolint:gosec } } return c diff --git a/v23/security/algo_test.go b/v23/security/algo_test.go index f5ef4251b..29f338906 100644 --- a/v23/security/algo_test.go +++ b/v23/security/algo_test.go @@ -16,7 +16,7 @@ import ( func TestRSAPanic(t *testing.T) { // Make sure that using a key with < 2048 bits causes a panic. - key, err := rsa.GenerateKey(rand.Reader, 1024) + key, err := rsa.GenerateKey(rand.Reader, 1024) //nolint:gosec if err != nil { t.Fatal(err) } diff --git a/v23/security/blessings_test.go b/v23/security/blessings_test.go index 0ce529963..672c8fe00 100644 --- a/v23/security/blessings_test.go +++ b/v23/security/blessings_test.go @@ -60,6 +60,7 @@ func TestByteSize(t *testing.T) { func verifyBlessingSignatures(t *testing.T, blessings ...security.Blessings) { for _, b := range blessings { + b := b if err := security.ExposeVerifySignature(&b); err != nil { _, _, line, _ := runtime.Caller(1) t.Fatalf("line %v: invalid signature for blessing %v: %v", line, b.String(), err) diff --git a/v23/security/publickey.go b/v23/security/publickey.go index 450469c52..b52c49467 100644 --- a/v23/security/publickey.go +++ b/v23/security/publickey.go @@ -8,7 +8,7 @@ import ( "crypto" "crypto/ecdsa" "crypto/ed25519" - "crypto/md5" + "crypto/md5" //nolint:gosec "crypto/rsa" "crypto/x509" "encoding" @@ -108,7 +108,7 @@ func (pk publicKeyCommon) MarshalBinary() ([]byte, error) { func (pk publicKeyCommon) String() string { const hextable = "0123456789abcdef" - hash := md5.Sum(pk.keyBytes) + hash := md5.Sum(pk.keyBytes) //nolint:gosec var repr [md5.Size * 3]byte for i, v := range hash { repr[i*3] = hextable[v>>4] diff --git a/v23/security/signature.go b/v23/security/signature.go index 1fcb73749..2607cd459 100644 --- a/v23/security/signature.go +++ b/v23/security/signature.go @@ -6,7 +6,6 @@ package security import ( "crypto" - "crypto/sha1" "crypto/sha256" "crypto/sha512" ) @@ -84,9 +83,9 @@ func messageDigest(hash crypto.Hash, purpose, message []byte, key PublicKey) []b func cryptoSum(hash crypto.Hash, data []byte) []byte { switch hash { - case crypto.SHA1: - h := sha1.Sum(data) - return h[:] + // case crypto.SHA1: + // h := sha1.Sum(data) + // return h[:] case crypto.SHA256: h := sha256.Sum256(data) return h[:] @@ -102,8 +101,8 @@ func cryptoSum(hash crypto.Hash, data []byte) []byte { func cryptoHash(h Hash) crypto.Hash { switch h { - case SHA1Hash: - return crypto.SHA1 + // case SHA1Hash: + // return crypto.SHA1 case SHA256Hash: return crypto.SHA256 case SHA384Hash: diff --git a/v23/vdl/vdltest/entry_generator.go b/v23/vdl/vdltest/entry_generator.go index 1c4d080ca..6ed5a86b2 100644 --- a/v23/vdl/vdltest/entry_generator.go +++ b/v23/vdl/vdltest/entry_generator.go @@ -56,7 +56,7 @@ func NewEntryGenerator(sourceTypes []*vdl.Type) *EntryGenerator { valueGen: NewValueGenerator(sourceTypes), hasher: fnv.New64a(), randSeed: now, - rng: rand.New(rand.NewSource(now)), + rng: rand.New(rand.NewSource(now)), //nolint:gosec } for _, tt := range sourceTypes { kind := tt.NonOptional().Kind() diff --git a/v23/vdl/vdltest/internal/vdltestgen/main.go b/v23/vdl/vdltest/internal/vdltestgen/main.go index bd09be60c..06e733021 100644 --- a/v23/vdl/vdltest/internal/vdltestgen/main.go +++ b/v23/vdl/vdltest/internal/vdltestgen/main.go @@ -51,7 +51,7 @@ const ( vdltestPkgName = "v.io/v23/vdl/vdltest" typeGenFileName = "type_gen.vdl" typeManualFileName = "type_manual.vdl" - passGenFileName = "entry_pass_gen.vdl" + passGenFileName = "entry_pass_gen.vdl" //nolint:gosec failGenFileName = "entry_fail_gen.vdl" ) diff --git a/v23/vdl/vdltest/type_generator.go b/v23/vdl/vdltest/type_generator.go index c01c50c7e..411c78da4 100644 --- a/v23/vdl/vdltest/type_generator.go +++ b/v23/vdl/vdltest/type_generator.go @@ -46,7 +46,7 @@ func NewTypeGenerator() *TypeGenerator { BaseTypesPerKind: []int{3, 1}, FieldsPerKind: []int{-1, 2, 1}, MaxArrayLen: 3, - rng: rand.New(rand.NewSource(time.Now().Unix())), + rng: rand.New(rand.NewSource(time.Now().Unix())), //nolint:gosec } } diff --git a/v23/vdl/vdltest/value_generator.go b/v23/vdl/vdltest/value_generator.go index 584423e76..502a7bc3c 100644 --- a/v23/vdl/vdltest/value_generator.go +++ b/v23/vdl/vdltest/value_generator.go @@ -39,7 +39,7 @@ func NewValueGenerator(types []*vdl.Type) *ValueGenerator { RandomZeroPercentage: 20, MaxLen: 3, MaxCycleDepth: 3, - rng: rand.New(rand.NewSource(time.Now().Unix())), + rng: rand.New(rand.NewSource(time.Now().Unix())), //nolint:gosec } } diff --git a/v23/vdlroot/time/time_test.go b/v23/vdlroot/time/time_test.go index fe2896177..9d3a73b5b 100644 --- a/v23/vdlroot/time/time_test.go +++ b/v23/vdlroot/time/time_test.go @@ -112,11 +112,11 @@ func TestDurationToFromNative(t *testing.T) { } func randGoDuration() gotime.Duration { - return gotime.Duration(rand.Int63()) + return gotime.Duration(rand.Int63()) //nolint:gosec } func randomDuration() Duration { - return Duration{rand.Int63(), int32(rand.Intn(nanosPerSecond))} + return Duration{rand.Int63(), int32(rand.Intn(nanosPerSecond))} //nolint:gosec } func TestDurationToNativeError(t *testing.T) { diff --git a/v23/vom/vomtest/internal/vomforever/main.go b/v23/vom/vomtest/internal/vomforever/main.go index 21ba5f332..eb585151f 100644 --- a/v23/vom/vomtest/internal/vomforever/main.go +++ b/v23/vom/vomtest/internal/vomforever/main.go @@ -62,7 +62,7 @@ func genEntries() chan entry { modes := []vdltest.GenMode{vdltest.GenFull, vdltest.GenPosMax, vdltest.GenNegMax, vdltest.GenPosMin, vdltest.GenNegMin, vdltest.GenRandom} for i := 0; i < numValuesPerTypeList; i++ { out <- entry{ - Value: valgen.Gen(types[rand.Intn(len(types))], modes[rand.Intn(len(modes))]), + Value: valgen.Gen(types[rand.Intn(len(types))], modes[rand.Intn(len(modes))]), //nolint:gosec Types: types, } } diff --git a/x/ref/cmd/gclogs/format_test.go b/x/ref/cmd/gclogs/format_test.go index b46a8a67a..3bc8ed27a 100644 --- a/x/ref/cmd/gclogs/format_test.go +++ b/x/ref/cmd/gclogs/format_test.go @@ -58,7 +58,7 @@ func TestParseFileInfo(t *testing.T) { defer os.RemoveAll(tmpdir) name := "program.host.user.log.vanadium.INFO.20141204-131502.12345" - if err := os.WriteFile(filepath.Join(tmpdir, name), []byte{}, 0644); err != nil { + if err := os.WriteFile(filepath.Join(tmpdir, name), []byte{}, 0600); err != nil { t.Fatalf("os.WriteFile failed: %v", err) } link := "program.INFO" diff --git a/x/ref/cmd/gclogs/gclogs_test.go b/x/ref/cmd/gclogs/gclogs_test.go index 74f0a8b93..2c293a586 100644 --- a/x/ref/cmd/gclogs/gclogs_test.go +++ b/x/ref/cmd/gclogs/gclogs_test.go @@ -40,7 +40,7 @@ func setup(t *testing.T, workdir, username string) (tmpdir string) { for _, l := range logfiles { l.name = strings.ReplaceAll(l.name, "%USER%", username) filename := filepath.Join(tmpdir, l.name) - if err := os.WriteFile(filename, []byte{}, 0644); err != nil { + if err := os.WriteFile(filename, []byte{}, 0600); err != nil { t.Fatalf("os.WriteFile failed: %v", err) } mtime := time.Now().Add(-l.age) diff --git a/x/ref/cmd/principal/bless.go b/x/ref/cmd/principal/bless.go index b1ec2dcda..ab4485977 100644 --- a/x/ref/cmd/principal/bless.go +++ b/x/ref/cmd/principal/bless.go @@ -166,7 +166,12 @@ func getMacaroonForBlessRPC(key security.PublicKey, blessServerURL string, bless tmplArgs.Blessings = blessed ln.Close() }) - go http.Serve(ln, nil) //nolint:errcheck + s := &http.Server{ + ReadTimeout: 5 * time.Second, + WriteTimeout: 5 * time.Second, + ReadHeaderTimeout: 5 * time.Second, + } + go s.Serve(ln) //nolint:errcheck // Print the link to start the flow. url, err := seekBlessingsURL(key, blessServerURL, redirectURL, state) diff --git a/x/ref/cmd/principal/internal/scripting/scripting_test.go b/x/ref/cmd/principal/internal/scripting/scripting_test.go index 5fb95abd1..5a8f90c7c 100644 --- a/x/ref/cmd/principal/internal/scripting/scripting_test.go +++ b/x/ref/cmd/principal/internal/scripting/scripting_test.go @@ -85,7 +85,7 @@ func TestPrincipal(t *testing.T) { sshFile := filepath.Join(t.TempDir(), "ssh") pkBytes := sectestdata.SSHPublicKeyBytes(keys.ECDSA256, sectestdata.SSHKeyPublic) - err = os.WriteFile(sshFile, pkBytes, 0666) + err = os.WriteFile(sshFile, pkBytes, 0600) fail(t, err) pk, err := seclib.ParsePublicKey(pkBytes) @@ -127,7 +127,7 @@ func TestPublicKey(t *testing.T) { fail(t, err) ssh := filepath.Join(t.TempDir(), "ssh") - err = os.WriteFile(ssh, sectestdata.SSHPublicKeyBytes(keys.ECDSA256, sectestdata.SSHKeyPublic), 0666) + err = os.WriteFile(ssh, sectestdata.SSHPublicKeyBytes(keys.ECDSA256, sectestdata.SSHKeyPublic), 0600) fail(t, err) out := execute(t, ctx, fmt.Sprintf("k1 := decodePublicKeyBase64(%q)", b1)+` @@ -215,7 +215,7 @@ Expires at 2020-01-12 23:00:00 +0000 UTC } pubKeyFile := filepath.Join(t.TempDir(), "ssl") - err := os.WriteFile(pubKeyFile, sectestdata.X509PublicKeyBytes(keys.ED25519), 0666) + err := os.WriteFile(pubKeyFile, sectestdata.X509PublicKeyBytes(keys.ED25519), 0600) fail(t, err) out = execute(t, ctx, ` diff --git a/x/ref/lib/discovery/encoding_test.go b/x/ref/lib/discovery/encoding_test.go index 5e200912b..c7437a43a 100644 --- a/x/ref/lib/discovery/encoding_test.go +++ b/x/ref/lib/discovery/encoding_test.go @@ -17,7 +17,7 @@ import ( ) func TestEncodingBuffer(t *testing.T) { - rand := rand.New(rand.NewSource(0)) + rand := rand.New(rand.NewSource(0)) //nolint:gosec randBytes := func() []byte { p := make([]byte, rand.Intn(128)) rand.Read(p) @@ -109,7 +109,7 @@ func TestPackEncryptionKeys(t *testing.T) { } func TestEncodeWireCiphertext(t *testing.T) { - rand := rand.New(rand.NewSource(0)) + rand := rand.New(rand.NewSource(0)) //nolint:gosec for i := 0; i < 1; i++ { v, ok := quick.Value(reflect.TypeOf(bcrypter.WireCiphertext{}), rand) if !ok { diff --git a/x/ref/lib/discovery/plugins/ble/encoding_test.go b/x/ref/lib/discovery/plugins/ble/encoding_test.go index 2a7506937..39e38a369 100644 --- a/x/ref/lib/discovery/plugins/ble/encoding_test.go +++ b/x/ref/lib/discovery/plugins/ble/encoding_test.go @@ -15,7 +15,7 @@ import ( ) func TestEncode(t *testing.T) { //nolint:gocyclo - rand := rand.New(rand.NewSource(0)) + rand := rand.New(rand.NewSource(0)) //nolint:gosec randBytes := func(n int) []byte { p := make([]byte, rand.Intn(n)) rand.Read(p) diff --git a/x/ref/lib/discovery/plugins/ble/uuid_test.go b/x/ref/lib/discovery/plugins/ble/uuid_test.go index 4d7a8da90..abe935299 100644 --- a/x/ref/lib/discovery/plugins/ble/uuid_test.go +++ b/x/ref/lib/discovery/plugins/ble/uuid_test.go @@ -14,7 +14,7 @@ import ( ) func TestServiceUuid(t *testing.T) { - rand := rand.New(rand.NewSource(0)) + rand := rand.New(rand.NewSource(0)) //nolint:gosec randString := func() string { p := make([]byte, rand.Intn(32)) rand.Read(p) diff --git a/x/ref/lib/discovery/update_test.go b/x/ref/lib/discovery/update_test.go index 86563b694..e68cf40af 100644 --- a/x/ref/lib/discovery/update_test.go +++ b/x/ref/lib/discovery/update_test.go @@ -13,7 +13,7 @@ import ( ) func TestUpdateBasic(t *testing.T) { - rand := rand.New(rand.NewSource(0)) + rand := rand.New(rand.NewSource(0)) //nolint:gosec for i := 0; i < 10; i++ { v, ok := quick.Value(reflect.TypeOf(AdInfo{}), rand) if !ok { diff --git a/x/ref/lib/discovery/util_test.go b/x/ref/lib/discovery/util_test.go index 4073dd20f..4e6048feb 100644 --- a/x/ref/lib/discovery/util_test.go +++ b/x/ref/lib/discovery/util_test.go @@ -91,7 +91,7 @@ func TestHashAd(t *testing.T) { } func TestHashAdCoverage(t *testing.T) { - rand := rand.New(rand.NewSource(0)) + rand := rand.New(rand.NewSource(0)) //nolint:gosec gen := func(v reflect.Value) { for { r, ok := quick.Value(v.Type(), rand) diff --git a/x/ref/lib/pubsub/config_test.go b/x/ref/lib/pubsub/config_test.go index 0574f8c36..71ca10479 100644 --- a/x/ref/lib/pubsub/config_test.go +++ b/x/ref/lib/pubsub/config_test.go @@ -271,7 +271,7 @@ func testStream(t *testing.T, consumerBufSize int) { t.Fatal(err) } - rnd := rand.New(rand.NewSource(time.Now().UnixNano())) + rnd := rand.New(rand.NewSource(time.Now().UnixNano())) //nolint:gosec limit := rnd.Intn(5000) if limit < 100 { limit = 100 diff --git a/x/ref/lib/security/internal/lockedfile/filelock/filelock_test.go b/x/ref/lib/security/internal/lockedfile/filelock/filelock_test.go index 2d7f15dfd..6541798f3 100644 --- a/x/ref/lib/security/internal/lockedfile/filelock/filelock_test.go +++ b/x/ref/lib/security/internal/lockedfile/filelock/filelock_test.go @@ -199,7 +199,7 @@ func TestLockNotDroppedByExecCommand(t *testing.T) { // Some kinds of file locks are dropped when a duplicated or forked file // descriptor is unlocked. Double-check that the approach used by os/exec does // not accidentally drop locks. - cmd := exec.Command(os.Args[0], "-test.run=^$") + cmd := exec.Command(os.Args[0], "-test.run=^$") //nolint:gosec if err := cmd.Run(); err != nil { t.Fatalf("exec failed: %v", err) } diff --git a/x/ref/lib/security/internal/lockedfile/lockedfile_test.go b/x/ref/lib/security/internal/lockedfile/lockedfile_test.go index b4b26e5e6..bd15bfafa 100644 --- a/x/ref/lib/security/internal/lockedfile/lockedfile_test.go +++ b/x/ref/lib/security/internal/lockedfile/lockedfile_test.go @@ -154,7 +154,7 @@ func TestCanLockExistingFile(t *testing.T) { defer remove() path := filepath.Join(dir, "existing.txt") - if err := os.WriteFile(path, []byte("ok"), 0777); err != nil { + if err := os.WriteFile(path, []byte("ok"), 0600); err != nil { t.Fatalf("os.WriteFile: %v", err) } @@ -200,7 +200,7 @@ func TestSpuriousEDEADLK(t *testing.T) { } defer b.Close() - if err := os.WriteFile(filepath.Join(dir, "locked"), []byte("ok"), 0666); err != nil { + if err := os.WriteFile(filepath.Join(dir, "locked"), []byte("ok"), 0600); err != nil { t.Fatal(err) } @@ -225,7 +225,7 @@ func TestSpuriousEDEADLK(t *testing.T) { t.Fatal(err) } - cmd := exec.Command(os.Args[0], "-test.run="+t.Name()) + cmd := exec.Command(os.Args[0], "-test.run="+t.Name()) //nolint:gosec cmd.Env = append(os.Environ(), fmt.Sprintf("%s=%s", dirVar, dir)) qDone := make(chan struct{}) diff --git a/x/ref/lib/security/internal/lockedfile/transform_test.go b/x/ref/lib/security/internal/lockedfile/transform_test.go index 2e553e9e9..d8029298e 100644 --- a/x/ref/lib/security/internal/lockedfile/transform_test.go +++ b/x/ref/lib/security/internal/lockedfile/transform_test.go @@ -61,9 +61,9 @@ func TestTransform(t *testing.T) { go func() { defer func() { <-sem }() - time.Sleep(time.Duration(rand.Intn(100)) * time.Microsecond) - chunkWords := roundDownToPowerOf2(rand.Intn(maxChunkWords) + 1) - offset := rand.Intn(chunkWords) + time.Sleep(time.Duration(rand.Intn(100)) * time.Microsecond) //nolint:gosec + chunkWords := roundDownToPowerOf2(rand.Intn(maxChunkWords) + 1) //nolint:gosec + offset := rand.Intn(chunkWords) //nolint:gosec err := lockedfile.Transform(path, func(data []byte) (chunk []byte, err error) { chunk = buf[offset*8 : (offset+chunkWords)*8] diff --git a/x/ref/lib/security/principal_test.go b/x/ref/lib/security/principal_test.go index 0f392c5c0..e48b0989c 100644 --- a/x/ref/lib/security/principal_test.go +++ b/x/ref/lib/security/principal_test.go @@ -422,7 +422,7 @@ func useSSHPublicKeyAsPrincipal(ctx context.Context, from, to, name string) erro if err := store.WriteKeyPair(ctx, pubBytes, privBytes); err != nil { return err } - return os.WriteFile(filepath.Join(to, directoryLockfileName), nil, 0666) + return os.WriteFile(filepath.Join(to, directoryLockfileName), nil, 0600) } func createAliceAndBob(ctx context.Context, t *testing.T, creator func(dir string, pass []byte) (security.Principal, error)) (principals, daemons map[string]security.Principal) { diff --git a/x/ref/lib/security/serialization/serialization_test.go b/x/ref/lib/security/serialization/serialization_test.go index 2d0e2f518..6f4bff044 100644 --- a/x/ref/lib/security/serialization/serialization_test.go +++ b/x/ref/lib/security/serialization/serialization_test.go @@ -116,7 +116,7 @@ func TestIntegrityAndAuthenticity(t *testing.T) { tamper := func(b []byte) []byte { c := make([]byte, len(b)) copy(c, b) - c[mrand.Int()%len(b)]++ + c[mrand.Int()%len(b)]++ //nolint:gosec return c } diff --git a/x/ref/lib/stats/counter/tracker_test.go b/x/ref/lib/stats/counter/tracker_test.go index 35a4eb578..5d1a78d2c 100644 --- a/x/ref/lib/stats/counter/tracker_test.go +++ b/x/ref/lib/stats/counter/tracker_test.go @@ -161,7 +161,7 @@ func max(a, b int64) int64 { } func TestTrackerConcurrent(t *testing.T) { - rnd := rand.New(rand.NewSource(time.Now().UnixNano())) + rnd := rand.New(rand.NewSource(time.Now().UnixNano())) //nolint:gosec var rndMu sync.Mutex const numGoRoutines = 100 @@ -206,7 +206,7 @@ func TestTrackerConcurrent(t *testing.T) { func BenchmarkTrackerPush(b *testing.B) { const numVals = 10000 - vals := rand.New(rand.NewSource(time.Now().UnixNano())).Perm(numVals) + vals := rand.New(rand.NewSource(time.Now().UnixNano())).Perm(numVals) //nolint:gosec tracker := counter.NewTracker() b.SetParallelism(100) diff --git a/x/ref/lib/vdl/codegen/swift/util_namespace_test.go b/x/ref/lib/vdl/codegen/swift/util_namespace_test.go index fc5caa1ba..52fc8bc16 100644 --- a/x/ref/lib/vdl/codegen/swift/util_namespace_test.go +++ b/x/ref/lib/vdl/codegen/swift/util_namespace_test.go @@ -87,7 +87,7 @@ func createTmpVdlPath(t *testing.T, modules []moduleConfig, pkgs []pkgConfig) (s } sh.Cmd("mkdir", "-p", filepath.Join(tempDir, module.Path)).Run() moduleConfigPath := filepath.Join(tempDir, module.Path, "swiftmodule") - err := os.WriteFile(moduleConfigPath, []byte(module.Name), 0644) + err := os.WriteFile(moduleConfigPath, []byte(module.Name), 0600) if err != nil { sh.Cleanup() t.Fatalf("Unable to create temp vdl.config file: %v", err) @@ -101,7 +101,7 @@ func createTmpVdlPath(t *testing.T, modules []moduleConfig, pkgs []pkgConfig) (s sh.Cmd("mkdir", "-p", filepath.Join(tempDir, pkg.Path)).Run() for file, contents := range pkg.Files { vdlPath := filepath.Join(tempDir, pkg.Path, file) - err := os.WriteFile(vdlPath, []byte(contents), 0644) + err := os.WriteFile(vdlPath, []byte(contents), 0600) if err != nil { sh.Cleanup() t.Fatalf("Unable to create temp vdl file at %v: %v", vdlPath, err) diff --git a/x/ref/lib/vtrace/store.go b/x/ref/lib/vtrace/store.go index 0bef71747..76d213db9 100644 --- a/x/ref/lib/vtrace/store.go +++ b/x/ref/lib/vtrace/store.go @@ -124,7 +124,7 @@ func (s *Store) rootRecordingLocked(traceid, parentid uniqueid.Id, name string) return ts } sr := s.opts.SampleRate - if traceid == parentid && sr > 0.0 && (sr >= 1.0 || rand.Float64() < sr) { + if traceid == parentid && sr > 0.0 && (sr >= 1.0 || rand.Float64() < sr) { //nolint:gosec // If this is a root span, we may automatically sample it for collection. return s.forceCollectLocked(traceid, s.defaultLevel) } diff --git a/x/ref/runtime/internal/cloudvm/cloudpaths/paths.go b/x/ref/runtime/internal/cloudvm/cloudpaths/paths.go index 15729cb91..b1c47da03 100644 --- a/x/ref/runtime/internal/cloudvm/cloudpaths/paths.go +++ b/x/ref/runtime/internal/cloudvm/cloudpaths/paths.go @@ -7,7 +7,7 @@ package cloudpaths // AWS constants for its EC2 metadata service. const ( AWSHost = "http://169.254.169.254" - AWSTokenPath = "/latest/api/token" + AWSTokenPath = "/latest/api/token" //nolint:gosec AWSIdentityDocPath = "/latest/dynamic/instance-identity/document" AWSPublicIPPath = "/latest/meta-data/public-ipv4" AWSPrivateIPPath = "/latest/meta-data/local-ipv4" diff --git a/x/ref/runtime/internal/cloudvm/cloudvmtest/aws_mock.go b/x/ref/runtime/internal/cloudvm/cloudvmtest/aws_mock.go index 92fde87c4..bf3bf8025 100644 --- a/x/ref/runtime/internal/cloudvm/cloudvmtest/aws_mock.go +++ b/x/ref/runtime/internal/cloudvm/cloudvmtest/aws_mock.go @@ -79,7 +79,10 @@ func StartAWSMetadataServer(t *testing.T, imdsv2Only bool) (string, func()) { }) srv := http.Server{ - Handler: mux, + Handler: mux, + ReadTimeout: time.Second, + WriteTimeout: time.Second, + ReadHeaderTimeout: time.Second, } go srv.Serve(l) return "http://" + l.Addr().String(), func() { l.Close() } diff --git a/x/ref/runtime/internal/cloudvm/cloudvmtest/gcp_mock.go b/x/ref/runtime/internal/cloudvm/cloudvmtest/gcp_mock.go index 35f009ad6..8d085744a 100644 --- a/x/ref/runtime/internal/cloudvm/cloudvmtest/gcp_mock.go +++ b/x/ref/runtime/internal/cloudvm/cloudvmtest/gcp_mock.go @@ -9,6 +9,7 @@ import ( "net" "net/http" "testing" + "time" "v.io/x/ref/runtime/internal/cloudvm/cloudpaths" ) @@ -46,6 +47,10 @@ func StartGCPMetadataServer(t *testing.T) (string, func()) { func(w http.ResponseWriter, r *http.Request) { respond(w, r, "") }) - go http.Serve(l, nil) + s := &http.Server{ + ReadTimeout: time.Second, + WriteTimeout: time.Second, + } + go s.Serve(l) return "http://" + l.Addr().String(), func() { l.Close() } } diff --git a/x/ref/runtime/internal/flow/conn/readq_test.go b/x/ref/runtime/internal/flow/conn/readq_test.go index 9439ac187..3f292aa03 100644 --- a/x/ref/runtime/internal/flow/conn/readq_test.go +++ b/x/ref/runtime/internal/flow/conn/readq_test.go @@ -222,7 +222,7 @@ func TestReadqClose(t *testing.T) { go func() { defer wg.Done() - stopat := rand.Int31n(int32(iterations)) + stopat := rand.Int31n(int32(iterations)) //nolint: gosec for i := 0; i < iterations; i++ { msg, err := r.get(ctx) if err == io.EOF { diff --git a/x/ref/runtime/internal/flow/conn/writeq_test.go b/x/ref/runtime/internal/flow/conn/writeq_test.go index e6e11655a..26438bce9 100644 --- a/x/ref/runtime/internal/flow/conn/writeq_test.go +++ b/x/ref/runtime/internal/flow/conn/writeq_test.go @@ -377,7 +377,7 @@ func TestWriteqFIFOOrdering(t *testing.T) { if active := wq.getActive(); active != &w.writer { errCh <- fmt.Errorf("invariant violated: active: got %p, want %p", active, &w.writer) } - time.Sleep(time.Duration(rand.Int31n(100)) * time.Millisecond) + time.Sleep(time.Duration(rand.Int31n(100)) * time.Millisecond) //nolint: gosec doneCh <- doneRecord{w, n} wq.done(&w.writer) wg.Done() @@ -522,7 +522,7 @@ func TestWriteqConcurrency(t *testing.T) { errCh <- fmt.Errorf("invariant violated: active: got %p, want %p", active, &shared.writer) return } - time.Sleep(time.Duration(rand.Int31n(100)) * time.Nanosecond) + time.Sleep(time.Duration(rand.Int31n(100)) * time.Nanosecond) //nolint: gosec wq.done(&shared.writer) } }(i) @@ -618,7 +618,7 @@ func TestWriteqContextCancel(t *testing.T) { go func(cancel func()) { <-startCancel defer done.Done() - time.Sleep(time.Duration(rand.Int31n(100)) * time.Nanosecond) + time.Sleep(time.Duration(rand.Int31n(100)) * time.Nanosecond) //nolint: gosec cancel() }(cancel) } diff --git a/x/ref/runtime/internal/naming/namespace/cache.go b/x/ref/runtime/internal/naming/namespace/cache.go index 4f9223343..9c116d66a 100644 --- a/x/ref/runtime/internal/naming/namespace/cache.go +++ b/x/ref/runtime/internal/naming/namespace/cache.go @@ -53,7 +53,7 @@ func isStale(now time.Time, e naming.MountEntry) bool { // randomDrop randomly removes one cache entry. Assumes we've already locked the cache. func (c *ttlCache) randomDrop() { - n := rand.Intn(len(c.entries)) + n := rand.Intn(len(c.entries)) //nolint:gosec for k := range c.entries { if n == 0 { delete(c.entries, k) diff --git a/x/ref/runtime/internal/rpc/client.go b/x/ref/runtime/internal/rpc/client.go index 3f9c36b0a..a99d0a215 100644 --- a/x/ref/runtime/internal/rpc/client.go +++ b/x/ref/runtime/internal/rpc/client.go @@ -1015,7 +1015,7 @@ func shouldRetry(action verror.ActionCode, requireResolve bool, connOpts *connec // from forming. The first time you retry n should be 0, then 1 etc. func backoff(n uint, deadline time.Time) bool { // This is ((100 to 200) * 2^n) ms. - b := time.Duration((100+rand.Intn(100))< maxBackoff { b = maxBackoff } diff --git a/x/ref/runtime/internal/rpc/proxymgr.go b/x/ref/runtime/internal/rpc/proxymgr.go index 4a1e061e8..3c79e7d8a 100644 --- a/x/ref/runtime/internal/rpc/proxymgr.go +++ b/x/ref/runtime/internal/rpc/proxymgr.go @@ -49,7 +49,7 @@ func newProxyManager(s serverProxyAPI, proxyName string, policy rpc.ProxyPolicy, limit: limit, proxyName: proxyName, active: map[string]bool{}, - rand: rand.New(rand.NewSource(time.Now().UnixNano())), + rand: rand.New(rand.NewSource(time.Now().UnixNano())), //nolint: gosec } switch policy { case rpc.UseFirstProxy, rpc.UseRandomProxy: diff --git a/x/ref/runtime/internal/rpc/stress/internal/client.go b/x/ref/runtime/internal/rpc/stress/internal/client.go index 2322d10e0..9d9b518ac 100644 --- a/x/ref/runtime/internal/rpc/stress/internal/client.go +++ b/x/ref/runtime/internal/rpc/stress/internal/client.go @@ -76,7 +76,7 @@ func CallSumStream(ctx *context.T, server string, maxChunkCnt, maxPayloadSize in ctx.Fatalf("Stream failed: %v", err) } - chunkCnt := rand.Intn(maxChunkCnt) + 1 + chunkCnt := rand.Intn(maxChunkCnt) + 1 //nolint:gosec args := make([]stress.SumArg, chunkCnt) done := make(chan error, 1) go func() { diff --git a/x/ref/runtime/internal/rpc/stress/internal/util.go b/x/ref/runtime/internal/rpc/stress/internal/util.go index adf15e254..3dedfd5c7 100644 --- a/x/ref/runtime/internal/rpc/stress/internal/util.go +++ b/x/ref/runtime/internal/rpc/stress/internal/util.go @@ -5,7 +5,7 @@ package internal import ( - "crypto/md5" + "crypto/md5" //nolint:gosec crand "crypto/rand" "encoding/binary" "math/rand" @@ -16,9 +16,9 @@ import ( // newSumArg returns a randomly generated SumArg. func newSumArg(maxPayloadSize int) (stress.SumArg, error) { var arg stress.SumArg - arg.ABool = rand.Intn(2) == 0 - arg.AInt64 = rand.Int63() - arg.AListOfBytes = make([]byte, rand.Intn(maxPayloadSize)+1) + arg.ABool = rand.Intn(2) == 0 //nolint:gosec + arg.AInt64 = rand.Int63() //nolint:gosec + arg.AListOfBytes = make([]byte, rand.Intn(maxPayloadSize)+1) //nolint:gosec _, err := crand.Read(arg.AListOfBytes) return arg, err } @@ -31,7 +31,7 @@ func lenSumArg(arg *stress.SumArg) int { // doSum returns the MD5 checksum of the SumArg. func doSum(arg *stress.SumArg) ([]byte, error) { - h := md5.New() + h := md5.New() //nolint:gosec if arg.ABool { if err := binary.Write(h, binary.LittleEndian, arg.AInt64); err != nil { return nil, err diff --git a/x/ref/runtime/internal/rpc/stress/stress/stress.go b/x/ref/runtime/internal/rpc/stress/stress/stress.go index 06b5b9f96..a3f9996e7 100644 --- a/x/ref/runtime/internal/rpc/stress/stress/stress.go +++ b/x/ref/runtime/internal/rpc/stress/stress/stress.go @@ -56,7 +56,7 @@ func runStressTest(ctx *context.T, env *cmdline.Env, args []string) error { return env.UsageErrorf("invalid output format: %s\n", outFormat) } - rnd := rand.New(rand.NewSource(time.Now().UnixNano())) + rnd := rand.New(rand.NewSource(time.Now().UnixNano())) //nolint:gosec fmt.Fprintf(env.Stdout, "starting stress test against %d server(s) using %d core(s)...\n", len(args), runtime.NumCPU()) fmt.Fprintf(env.Stdout, "workers: %d, maxChunkCnt: %d, maxPayloadSize: %d, duration: %v\n", workers, maxChunkCnt, maxPayloadSize, duration) diff --git a/x/ref/runtime/internal/rt/security.go b/x/ref/runtime/internal/rt/security.go index 03042ffb9..7cf9aba0a 100644 --- a/x/ref/runtime/internal/rt/security.go +++ b/x/ref/runtime/internal/rt/security.go @@ -61,7 +61,7 @@ func defaultBlessingName() string { "apple", "banana", "cherry", "dragonfruit", "elderberry", "fig", "grape", "honeydew", } name := fmt.Sprintf("anonymous-%s-%d", - options[rand.New(rand.NewSource(time.Now().Unix())).Intn(len(options))], + options[rand.New(rand.NewSource(time.Now().Unix())).Intn(len(options))], //nolint: gosec os.Getpid()) host, _ := os.Hostname() // (none) is a common default hostname and contains parentheses, diff --git a/x/ref/runtime/protocols/lib/websocket/conn_test.go b/x/ref/runtime/protocols/lib/websocket/conn_test.go index f73bcdbab..6c4e87401 100644 --- a/x/ref/runtime/protocols/lib/websocket/conn_test.go +++ b/x/ref/runtime/protocols/lib/websocket/conn_test.go @@ -57,6 +57,7 @@ func TestMultipleGoRoutines(t *testing.T) { const numWritesPerWriter int = 1000 const totalWrites int = numWriters * numWritesPerWriter s := &http.Server{ + ReadHeaderTimeout: time.Second, Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { http.Error(w, "Method not allowed.", http.StatusMethodNotAllowed) diff --git a/x/ref/runtime/protocols/lib/websocket/listener.go b/x/ref/runtime/protocols/lib/websocket/listener.go index 33126438c..ffd520c23 100644 --- a/x/ref/runtime/protocols/lib/websocket/listener.go +++ b/x/ref/runtime/protocols/lib/websocket/listener.go @@ -48,7 +48,10 @@ func listener(protocol, address string, hybrid bool) (flow.Listener, error) { hybrid: hybrid, } go ln.netAcceptLoop() - httpsrv := http.Server{Handler: ln} + httpsrv := http.Server{ + Handler: ln, + ReadHeaderTimeout: time.Second, + } go httpsrv.Serve(&chanListener{Listener: netLn, c: ln.httpQ}) //nolint:errcheck return ln, nil } diff --git a/x/ref/services/debug/debug/browseserver/browseserver.go b/x/ref/services/debug/debug/browseserver/browseserver.go index 1d8d0fb97..15dbda087 100644 --- a/x/ref/services/debug/debug/browseserver/browseserver.go +++ b/x/ref/services/debug/debug/browseserver/browseserver.go @@ -80,7 +80,13 @@ func Serve(ctx *context.T, httpAddr, name string, timeout time.Duration, assets <-ctx.Done() ln.Close() }() - return http.Serve(ln, mux) + s := &http.Server{ + ReadTimeout: time.Second, + WriteTimeout: time.Second, + ReadHeaderTimeout: time.Second, + Handler: mux, + } + return s.Serve(ln) } // CreateServeMux returns a ServeMux object that has handlers set up. diff --git a/x/ref/services/debug/debug/impl.go b/x/ref/services/debug/debug/impl.go index 02b63735a..e3a7b6c73 100644 --- a/x/ref/services/debug/debug/impl.go +++ b/x/ref/services/debug/debug/impl.go @@ -644,7 +644,11 @@ func startPprofProxyHTTPServer(ctx *context.T, name string) (string, error) { return "", err } http.Handle("/", pproflib.PprofProxy(ctx, "", name)) - go http.Serve(ln, nil) //nolint:errcheck + s := &http.Server{ + ReadTimeout: time.Second, + WriteTimeout: time.Second, + ReadHeaderTimeout: time.Second} + go s.Serve(ln) //nolint:errcheck go func() { <-ctx.Done() ln.Close() diff --git a/x/ref/services/http/http/http.go b/x/ref/services/http/http/http.go index 9a4f955bc..004d5737a 100644 --- a/x/ref/services/http/http/http.go +++ b/x/ref/services/http/http/http.go @@ -5,6 +5,8 @@ package main import ( + "time" + "v.io/x/ref/services/http/httplib" "flag" @@ -48,7 +50,13 @@ func findPortAndListen(mux *http.ServeMux) { if err == nil { log.Println("Monitoring on " + fmtPort(currPort) + "/debug/requests...") defer ln.Close() - http.Serve(ln, mux) //nolint:errcheck + s := &http.Server{ + ReadTimeout: time.Second, + WriteTimeout: time.Second, + ReadHeaderTimeout: time.Second, + Handler: mux, + } + s.Serve(ln) //nolint:errcheck break } currPort++ diff --git a/x/ref/services/internal/pproflib/proxy_test.go b/x/ref/services/internal/pproflib/proxy_test.go index 546517206..cdeddc0d4 100644 --- a/x/ref/services/internal/pproflib/proxy_test.go +++ b/x/ref/services/internal/pproflib/proxy_test.go @@ -42,8 +42,13 @@ func TestPProfProxy(t *testing.T) { t.Fatal(err) } defer ln.Close() - //nolint:errcheck - go http.Serve(ln, pproflib.PprofProxy(ctx, "/myprefix", endpoints[0].Name())) + srv := &http.Server{ + ReadTimeout: 5 * time.Second, + WriteTimeout: 5 * time.Second, + ReadHeaderTimeout: 5 * time.Second, + Handler: pproflib.PprofProxy(ctx, "/myprefix", endpoints[0].Name()), + } + go srv.Serve(ln) //nolint:errcheck testcases := []string{ "/myprefix/pprof/", "/myprefix/pprof/cmdline", @@ -55,8 +60,7 @@ func TestPProfProxy(t *testing.T) { // Make sure the web server is up and running before starting tests. for { - url := fmt.Sprintf("http://%s/myprefix/pprof/", ln.Addr()) - resp, err := http.Get(url) + resp, err := http.Get(fmt.Sprintf("http://%s/myprefix/pprof/", ln.Addr())) if err == nil && resp.StatusCode == 200 { break } @@ -66,7 +70,7 @@ func TestPProfProxy(t *testing.T) { for _, c := range testcases { url := fmt.Sprintf("http://%s%s", ln.Addr(), c) - resp, err := http.Get(url) + resp, err := http.Get(url) //nolint:gosec if err != nil { t.Fatalf("%v: http.Get failed: %v", url, err) } diff --git a/x/ref/test/basics/tls_test.go b/x/ref/test/basics/tls_test.go index 2058eebff..c93b255a0 100644 --- a/x/ref/test/basics/tls_test.go +++ b/x/ref/test/basics/tls_test.go @@ -144,12 +144,14 @@ func newTLSConfigs() (client, server *tls.Config, err error) { Certificates: []tls.Certificate{serverCert}, ClientCAs: certpool, ClientAuth: tls.RequireAndVerifyClientCert, + MinVersion: tls.VersionTLS13, SessionTicketsDisabled: true, } client = &tls.Config{ Certificates: []tls.Certificate{clientCert}, RootCAs: certpool, ServerName: "127.0.0.1", + MinVersion: tls.VersionTLS13, SessionTicketsDisabled: true, } return client, server, nil diff --git a/x/ref/test/compatibility/build.go b/x/ref/test/compatibility/build.go index b07978053..486f5bae4 100644 --- a/x/ref/test/compatibility/build.go +++ b/x/ref/test/compatibility/build.go @@ -105,7 +105,7 @@ func readFile(dir, file string) string { } func (o builder) run(ctx context.Context, dir string, args ...string) error { - cmd := exec.CommandContext(ctx, args[0], args[1:]...) + cmd := exec.CommandContext(ctx, args[0], args[1:]...) //nolint:gosec cmd.Dir = dir cmd.Env = append(cmd.Env, "GOPATH="+o.gopath, diff --git a/x/ref/test/testutil/rand.go b/x/ref/test/testutil/rand.go index 7732ae3f5..7c372ff11 100644 --- a/x/ref/test/testutil/rand.go +++ b/x/ref/test/testutil/rand.go @@ -92,7 +92,7 @@ func NewRandGenerator(logger loggingFunc) *Random { } } logger("Seeded pseudo-random number generator with %v", seed) - return &Random{rand: rand.New(rand.NewSource(seed))} + return &Random{rand: rand.New(rand.NewSource(seed))} //nolint:gosec } // TODO(caprita): Consider deprecating InitRandGenerator in favor of using