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

Community Favorite
profile photo of semgrepsemgrep
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]
      vulnerability_class:
        - Cryptographic Issues
    message: Do not use `math/rand`. Use `crypto/rand` instead.
    languages:
      - go
    severity: WARNING
    patterns:
      - pattern-either:
          - pattern: |
              import $RAND "$MATH"
          - pattern: |
              import "$MATH"
      - metavariable-regex:
          metavariable: $MATH
          regex: ^(math/rand)$
      - pattern-either:
          - pattern-inside: |
              ...
              rand.$FUNC(...)
          - pattern-inside: |
              ...
              $RAND.$FUNC(...)
      - focus-metavariable:
          - $MATH
    fix: |
      crypto/rand

Examples

math_random.go

package main

import (
	"crypto/rand"
	// ruleid: math-random-used
	mrand "math/rand"
)

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

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

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

func main2() {
	// ok: 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)
}