Skip to content

G404 false positive when math/rand is imported by a different file in a package than calls rand.Read #291

@bconway

Description

@bconway

Summary

When math/rand is imported by a file in a package which is different than the file importing crypto/rand (and also calls rand.Read), a G404 is throw incorrectly - I believe.

Steps to reproduce the behavior

Contrived example:

init.go:

package main

import (
	"math/rand"
	"time"
)

func init() {
	rand.Seed(time.Now().UnixNano())
}

main.go:

package main

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
)

func RandBytes(n int) string {
	b := make([]byte, n)
	if _, err := rand.Read(b); err != nil {
		panic(err)
	}
	return hex.EncodeToString(b)
}

func main() {
	fmt.Println(RandBytes(5))
}

gosec version

latest via go get -u

Go version (output of 'go version')

go version go1.12.1 darwin/amd64

Operating system / Environment

macOS Mojave

Expected behavior

No errors.

Actual behavior

$ gosec .
[gosec] 2019/03/19 21:45:09 including rules: default
[gosec] 2019/03/19 21:45:09 excluding rules: default
[gosec] 2019/03/19 21:45:09 Searching directory: /.../src/gitlab.com/bconway/gosectest
[gosec] 2019/03/19 21:45:09 Checking package: main
[gosec] 2019/03/19 21:45:09 Checking file: /.../src/gitlab.com/bconway/gosectest/init.go
[gosec] 2019/03/19 21:45:09 Checking file: /.../src/gitlab.com/bconway/gosectest/main.go
Results:


[/.../src/gitlab.com/bconway/gosectest/main.go:11] - G404: Use of weak random number generator (math/rand instead of crypto/rand) (Confidence: MEDIUM, Severity: HIGH)
  > rand.Read(b)


Summary:
   Files: 2
   Lines: 29
   Nosec: 0
  Issues: 1

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions