Zennoxa Shield
Rules / Swift
SHIELD-SWIFT-015

Insecure random for security token

highSwiftCWE-338CVSS 7.4

What it detects

arc4random or a non-cryptographic random source is used to generate a token.

How to fix

Generate security tokens with SecRandomCopyBytes for cryptographic strength.

Vulnerable — Shield flags thisOneTimeCode.swift
import Foundation

func generateOneTimeCode() -> String {
    let otp = Int.random(in: 100000...999999)
    return String(otp)
}
Fixed — scans cleanOneTimeCode.swift
import Foundation
import Security

func generateOneTimeCode() -> String {
    var bytes = [UInt8](repeating: 0, count: 32)
    let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)
    precondition(status == errSecSuccess, "SecRandomCopyBytes failed")
    return Data(bytes).base64EncodedString()
}

Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-SWIFT-015, the fixed one does not.

SHIELD-SWIFT-015: Insecure random for security token — Zennoxa Shield