T09 · Insecure Skill Coding Practices
- Location
- scripts/digital_legacy.py:152
- Finding
- Nonstandard Encryption Fallback Contradicts the Advertised AES-256-GCM Security Model<![CDATA[ ## Vulnerability Details **File Location**: `scripts/digital_legacy.py:152-192` **Vulnerability Type**: Custom cryptographic construction and misleading algorithm reporting **Risk Level**: High ### Vulnerable Code ```python def encrypt(data: str, passphrase: str) -> bytes: """Encrypt a string with AES-256-GCM or stdlib fallback. Uses the `cryptography` library if available (proper AES-GCM). Falls back to a stdlib XOR-stream cipher with HMAC authentication if not. The fallback is less secure but functional for personal use. """ plaintext = data.encode('utf-8') salt = secrets.token_bytes(SALT_LENGTH) nonce = secrets.token_bytes(NONCE_LENGTH) key = derive_key(passphrase, salt) try: from cryptography.hazmat.primitives.ciphers.aead import AESGCM aesgcm = AESGCM(key) ciphertext = aesgcm.encrypt(nonce, plaintext, None) return salt + nonce + ciphertext except ImportError: # Fallback: XOR-stream with HMAC-SHA256 authentication return _encrypt_fallback(plaintext, key, salt, nonce) def _encrypt_fallback(plaintext: bytes, key: bytes, salt: bytes, nonce: bytes) -> bytes: """Stdlib-only encryption: XOR keystream + HMAC tag.""" import hmac # Generate keystream from key + nonce (PBKDF2 as PRNG) keystream = b'' counter = 0 while len(keystream) < len(plaintext): block = hashlib.sha256(key + nonce + counter.to_bytes(4, 'big')).digest() keystream += block counter += 1 # XOR encrypt ciphertext = bytes(a ^ b for a, b in zip(plaintext, keystream)) # HMAC authentication tag tag = hmac.new(key, salt + nonce + ciphertext, hashlib.sha256).digest()[:TAG_LENGTH] return salt + nonce + ciphertext + tag ``` ### Technical Analysis The application uses AES-256-GCM only when the optional `cryptography` package is installed. Otherwise, it silently falls back to a custom construction consisting of: 1. A SHA-256-based k ...[truncated 2188 chars]
- Remediation
- <![CDATA[ ## Remediation Suggestions 1. Remove the custom XOR-based fallback entirely. 2. Require a maintained authenticated-encryption implementation such as `cryptography`'s `AESGCM` or `ChaCha20Poly1305`. 3. Fail closed with a clear installation error if the required cryptographic dependency is unavailable. 4. Add a versioned file header containing: - Format version - Encryption algorithm - KDF algorithm and parameters - Salt and nonce lengths 5. Derive distinct encryption and authentication keys if a composition is ever necessary, although a standard AEAD construction is strongly preferred. 6. Update all documentation and command output so it accurately identifies the algorithm actually used. 7. Add known-answer, tampering, wrong-passphrase, and cross-environment compatibility tests. 8. Consider a migration command that decrypts legacy fallback files and re-encrypts them using the standardized format. ]]>
