Skip to content

Commit

Permalink
enable gosec linter and fix the errors it reports. (#390)
Browse files Browse the repository at this point in the history
  • Loading branch information
cosnicolaou authored Apr 17, 2023
1 parent e03230a commit d442c8d
Show file tree
Hide file tree
Showing 51 changed files with 117 additions and 75 deletions.
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ linters-settings:
linters:
enable:
- bodyclose
- gosec
- gocritic
- gocyclo
- gofmt
Expand Down
6 changes: 3 additions & 3 deletions v23/flow/message/internal_message_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,15 @@ import (
func randomTestCases() []uint64 {
c := make([]uint64, 4096)
for i := range c {
c[i] = rand.Uint64()
c[i] = rand.Uint64() //nolint:gosec
}
return c
}

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
}
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion v23/security/algo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
1 change: 1 addition & 0 deletions v23/security/blessings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions v23/security/publickey.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/md5"
"crypto/md5" //nolint:gosec
"crypto/rsa"
"crypto/x509"
"encoding"
Expand Down Expand Up @@ -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]
Expand Down
11 changes: 5 additions & 6 deletions v23/security/signature.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ package security

import (
"crypto"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
)
Expand Down Expand Up @@ -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[:]
Expand All @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion v23/vdl/vdltest/entry_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion v23/vdl/vdltest/internal/vdltestgen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down
2 changes: 1 addition & 1 deletion v23/vdl/vdltest/type_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}

Expand Down
2 changes: 1 addition & 1 deletion v23/vdl/vdltest/value_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}

Expand Down
4 changes: 2 additions & 2 deletions v23/vdlroot/time/time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion v23/vom/vomtest/internal/vomforever/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}
Expand Down
2 changes: 1 addition & 1 deletion x/ref/cmd/gclogs/format_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion x/ref/cmd/gclogs/gclogs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
7 changes: 6 additions & 1 deletion x/ref/cmd/principal/bless.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions x/ref/cmd/principal/internal/scripting/scripting_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)+`
Expand Down Expand Up @@ -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, `
Expand Down
4 changes: 2 additions & 2 deletions x/ref/lib/discovery/encoding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion x/ref/lib/discovery/plugins/ble/encoding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion x/ref/lib/discovery/plugins/ble/uuid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion x/ref/lib/discovery/update_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion x/ref/lib/discovery/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion x/ref/lib/pubsub/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
6 changes: 3 additions & 3 deletions x/ref/lib/security/internal/lockedfile/lockedfile_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down Expand Up @@ -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)
}

Expand All @@ -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{})
Expand Down
6 changes: 3 additions & 3 deletions x/ref/lib/security/internal/lockedfile/transform_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion x/ref/lib/security/principal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion x/ref/lib/security/serialization/serialization_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
4 changes: 2 additions & 2 deletions x/ref/lib/stats/counter/tracker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions x/ref/lib/vdl/codegen/swift/util_namespace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion x/ref/lib/vtrace/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
Loading

0 comments on commit d442c8d

Please sign in to comment.