go.lang.security.audit.crypto.math_random.math-random-used

Community Favorite
profile photo of returntocorpreturntocorp
Author
72,039
Download Count*

Do not use math/rand. Use crypto/rand instead.

Run Locally

Run in CI

Defintion

rules:
  - id: math-random-used
    metadata:
      cwe:
        - "CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator
          (PRNG)"
      owasp:
        - A02:2021 - Cryptographic Failures
      references:
        - https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html#secure-random-number-generation
      category: security
      technology:
        - go
      confidence: MEDIUM
      subcategory:
        - vuln
      likelihood: MEDIUM
      impact: MEDIUM
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
    message: Do not use `math/rand`. Use `crypto/rand` instead.
    languages:
      - go
    severity: WARNING
    pattern-either:
      - patterns:
          - pattern-inside: |
              import mrand "math/rand"
              ...
          - pattern-either:
              - pattern: mrand.Int()
              - pattern: mrand.Read(...)
      - patterns:
          - pattern-inside: |
              import "math/rand"
              ...
          - pattern-not-inside: |
              import "crypto/rand"
              ...
          - pattern-either:
              - pattern: rand.Int()
              - pattern: rand.Read(...)

Examples

math_random.go

package main

import (
	"crypto/rand"
	mrand "math/rand"
)

func main() {
	main0()
	main1()
	main2()
	main3()
}

func main0() {
	// ruleid: math-random-used
	bad, _ := mrand.Read(nil)
	println(bad)
}

func main1() {
	// ok: math-random-used
	good, _ := rand.Read(nil)
	println(good)
}

func main2() {
	// ruleid: math-random-used
	bad := mrand.Int()
	println(bad)
}

func main3() {
	// ok: math-random-used
	good, _ := rand.Read(nil)
	println(good)
	i := mrand.Int31()
	println(i)
}