Skip to content

False positive for G404 if both math/rand and crypto/rand are imported #862

@thaJeztah

Description

@thaJeztah

Summary

If a file imports both math/rand and crypto/rand, gosec reports a false positive.

Steps to reproduce the behavior

Create a file that imports both;

package main

import (
	"crypto/rand"
	"math/big"
	rnd "math/rand"
)

func main() {
	_, _ = rand.Int(rand.Reader, big.NewInt(int64(2)))
	_ = rnd.Intn(2)
}

gosec version

Tried both the latest release (v2.3.1) and "master"

go install github.com/securego/gosec/v2/cmd/[email protected]


go install github.com/securego/gosec/v2/cmd/gosec@master
go: downloading github.com/securego/gosec v0.0.0-20200330112059-e030aa4f768b
go: downloading github.com/securego/gosec/v2 v2.13.2-0.20220829082147-ae58325bfea0
go: downloading github.com/nbutton23/zxcvbn-go v0.0.0-20210217022336-fa2cb2858354
go: downloading golang.org/x/tools v0.1.12
go: downloading github.com/google/uuid v1.3.0
go: downloading github.com/gookit/color v1.5.1
go: downloading gopkg.in/yaml.v2 v2.4.0
go: downloading github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778
go: downloading golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4
go: downloading golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f

Go version (output of 'go version')

go version
go version go1.19 darwin/amd64

Operating system / Environment

macOS, but reproduces as well on Linux (running inside a golang:1.19 container

Expected behavior

Actual behavior

gosec --quiet .
Results:


[/gosec-issue/main.go:10] - G404 (CWE-338): Use of weak random number generator (math/rand instead of crypto/rand) (Confidence: MEDIUM, Severity: HIGH)
    9: func main() {
  > 10: 	_, _ = rand.Int(rand.Reader, big.NewInt(int64(2)))
    11: 	_ = rnd.Intn(2)



Summary:
  Gosec  : dev
  Files  : 1
  Lines  : 12
  Nosec  : 0
  Issues : 1

Editing the file to remove the additional import makes the false positive disappear;

package main

import (
	"crypto/rand"
	"math/big"
	// rnd "math/rand"
)

func main() {
	_, _ = rand.Int(rand.Reader, big.NewInt(int64(2)))
	// _ = rnd.Intn(2)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions