swift.lang.crypto.insecure-random.insecure-random
semgrep
Author
unknown
Download Count*
License
A random number generator was detected which is not guaranteed to be Cryptographically secure. If the source of entropy is used for security purposes (e.g. with other Cryptographic operations), make sure to use the SecCopyRandomBytes
API explicitly.
Run Locally
Run in CI
Defintion
rules:
- id: insecure-random
message: A random number generator was detected which is **not** *guaranteed* to
be Cryptographically secure. If the source of entropy is used for security
purposes (e.g. with other Cryptographic operations), make sure to use the
`SecCopyRandomBytes` API explicitly.
severity: WARNING
metadata:
likelihood: LOW
impact: LOW
confidence: LOW
category: security
cwe:
- "CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator
(PRNG)"
masvs:
- "MSTG-CRYPTO-6: All random values are generated using a sufficiently
secure random number generator."
owasp:
- A02:2021 - Cryptographic Failures
references:
- https://mobile-security.gitbook.io/masvs/security-requirements/0x08-v3-cryptography_verification_requirements
- https://developer.apple.com/documentation/security/1399291-secrandomcopybytes
- https://developer.apple.com/documentation/security/randomization_services?language=swift
- https://github.com/apple/swift-evolution/blob/main/proposals/0202-random-unification.md
subcategory:
- audit
technology:
- ios
- macos
license: Commons Clause License Condition v1.0[LGPL-2.1-only]
vulnerability_class:
- Cryptographic Issues
languages:
- swift
pattern-either:
- pattern: random()
- pattern: Int.random(...)
- pattern: Bool.random(...)
- pattern: Float.random(...)
- pattern: Double.random(...)
- pattern: arc4random()
- pattern: arc4random_buf(...)
- pattern: arc4random_uniform(...)
- pattern: SystemRandomNumberGenerator(...)
- pattern: rand()
Examples
insecure-random.swift
import Foundation
func example() -> Void {
// ruleid: insecure-random
let randomInt = Int.random(in: 0..<6)
// ruleid: insecure-random
let randomDouble = Double.random(in: 2.71828...3.14159)
// ruleid: insecure-random
let randomBool = Bool.random()
// ruleid: insecure-random
let diceRoll = Int(arc4random_uniform(6) + 1)
// ruleid: insecure-random
let a = Int.random(in: 0 ... 10)
// ruleid: insecure-random
var k: Int = random() % 10;
// ruleid: insecure-random
let randomNumber = arc4random()
var r: Self = 0
// ruleid: insecure-random
arc4random_buf(&r, MemoryLayout<Self>.size)
// ruleid: insecure-random
let x = Int.random(in: 1...100)
// ruleid: insecure-random
var g = SystemRandomNumberGenerator()
// ruleid: insecure-random
let y = Int.random(in: 1...100, using: &g)
// ruleid: insecure-random
if (Int.random(in: 1...100) < 50) {
println("foo")
}
var printRandom = {
// ruleid: insecure-random
let a = Int.random(in: 1...10)
print(a)
}
// okid: insecure-random
Test.random(in: 1...10)
}
Short Link: https://sg.run/Lb76