Encryption using ECB¶
ID: swift/ecb-encryptionKind: path-problemSecurity severity: 7.5Severity: warningPrecision: highTags: - security - external/cwe/cwe-327Query suites: - swift-code-scanning.qls - swift-security-extended.qls - swift-security-and-quality.qls
Click to see the query in the CodeQL repository
ECB should not be used as a mode for encryption as it has dangerous weaknesses. Data is encrypted the same way every time, which means that the same plaintext input will always produce the same ciphertext. This behavior makes messages encrypted with ECB more vulnerable to replay attacks.
Recommendation¶
Use a different cipher mode such as CBC.
Example¶
The following example shows six cases of instantiating a cipher with various encryption keys and block modes. In the ‘BAD’ cases, the mode of encryption is ECB, making the encrypted data vulnerable to replay attacks. In the ‘GOOD’ cases, the encryption mode is CBC, which protects the encrypted data against replay attacks.
funcencrypt(key:Key,padding:Padding){// ...// BAD: ECB is used for block modeletblockMode=ECB()_=tryAES(key:key,blockMode:blockMode,padding:padding)_=tryAES(key:key,blockMode:blockMode)_=tryBlowfish(key:key,blockMode:blockMode,padding:padding)// GOOD: ECB is not used for block modeletaesBlockMode=CBC(iv:AES.randomIV(AES.blockSize))letblowfishBlockMode=CBC(iv:Blowfish.randomIV(Blowfish.blockSize))_=tryAES(key:key,blockMode:aesBlockMode,padding:padding)_=tryAES(key:key,blockMode:aesBlockMode)_=tryBlowfish(key:key,blockMode:blowfishBlockMode,padding:padding)// ...}
References¶
Wikipedia, block cipher modes of operation,Electronic codebook (ECB).
Common Weakness Enumeration:CWE-327.