scala.lang.security.audit.insecure-random.insecure-random

profile photo of semgrepsemgrep
Author
unknown
Download Count*

Flags the use of a predictable random value from scala.util.Random. This can lead to vulnerabilities when used in security contexts, such as in a CSRF token, password reset token, or any other secret value. To fix this, use java.security.SecureRandom instead.

Run Locally

Run in CI

Defintion

rules:
  - id: insecure-random
    metadata:
      cwe:
        - "CWE-330: Use of Insufficiently Random Values"
      owasp:
        - A02:2021 - Cryptographic Failures
      category: security
      technology:
        - scala
        - cryptography
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
      resources:
        - https://find-sec-bugs.github.io/bugs.htm
      confidence: LOW
      references:
        - https://owasp.org/Top10/A02_2021-Cryptographic_Failures
      subcategory:
        - audit
      likelihood: LOW
      impact: MEDIUM
      vulnerability_class:
        - Cryptographic Issues
    message: Flags the use of a predictable random value from `scala.util.Random`.
      This can lead to vulnerabilities when used in security contexts, such as
      in a CSRF token, password reset token, or any other secret value. To fix
      this, use java.security.SecureRandom instead.
    severity: WARNING
    languages:
      - scala
    patterns:
      - pattern: |
          import scala.util.Random

Examples

insecure-random.scala

class Test {
  def bad1() {
    // ruleid: insecure-random
    import scala.util.Random

    val result = Seq.fill(16)(Random.nextInt)
    return result.map("%02x" format _).mkString
  }

  def ok1() {
    // ok: insecure-random
    import java.security.SecureRandom

    val rand = new SecureRandom()
    val value = Array.ofDim[Byte](16)
    rand.nextBytes(value)
    return value.map("%02x" format _).mkString
  }
}