python.cryptography.security.insecure-cipher-mode-ecb.insecure-cipher-mode-ecb

Verifed by r2c
Community Favorite
profile photo of semgrepsemgrep
Author
99,223
Download Count*

ECB (Electronic Code Book) is the simplest mode of operation for block ciphers. Each block of data is encrypted in the same way. This means identical plaintext blocks will always result in identical ciphertext blocks, which can leave significant patterns in the output. Use a different, cryptographically strong mode instead, such as GCM.

Run Locally

Run in CI

Defintion

rules:
  - id: insecure-cipher-mode-ecb
    message: ECB (Electronic Code Book) is the simplest mode of operation for block
      ciphers.  Each block of data is encrypted in the same way.  This means
      identical plaintext blocks will always result in identical ciphertext
      blocks, which can leave significant patterns in the output. Use a
      different, cryptographically strong mode instead, such as GCM.
    metadata:
      source-rule-url: https://github.com/PyCQA/bandit/blob/d5f8fa0d89d7b11442fc6ec80ca42953974354c8/bandit/blacklists/calls.py#L101
      cwe:
        - "CWE-327: Use of a Broken or Risky Cryptographic Algorithm"
      owasp:
        - A03:2017 - Sensitive Data Exposure
        - A02:2021 - Cryptographic Failures
      bandit-code: B305
      references:
        - https://cryptography.io/en/latest/hazmat/primitives/symmetric-encryption/#insecure-modes
        - https://crypto.stackexchange.com/questions/20941/why-shouldnt-i-use-ecb-encryption
      category: security
      technology:
        - cryptography
      subcategory:
        - audit
      likelihood: LOW
      impact: LOW
      confidence: MEDIUM
      functional-categories:
        - crypto::search::mode::cryptography
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
      vulnerability_class:
        - Cryptographic Issues
    severity: WARNING
    languages:
      - python
    pattern: cryptography.hazmat.primitives.ciphers.modes.ECB($IV)
    fix: cryptography.hazmat.primitives.ciphers.modes.GCM($IV)

Examples

insecure-cipher-mode-ecb.py

# cf. https://github.com/PyCQA/bandit/blob/b1411bfb43795d3ffd268bef17a839dee954c2b1/examples/cipher-modes.py

from cryptography.hazmat.primitives.ciphers.modes import CBC
from cryptography.hazmat.primitives.ciphers.modes import ECB


# Insecure mode
# ruleid: insecure-cipher-mode-ecb
mode = ECB(iv)

# Secure cipher and mode
# ok: insecure-cipher-mode-ecb
cipher = AES.new(key, blockalgo.MODE_CTR, iv)

# Secure mode
# ok: insecure-cipher-mode-ecb
mode = CBC(iv)