Rules / Swift
SHIELD-SWIFT-015
Insecure random for security token
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.