--- name: sh-kb-crypto description: "Knowledge base for finding cryptographic failures - weak hashing/encryption, insecure randomness, hardcoded/static keys and IVs, ECB mode, missing integrity, and predictable tokens. Use when hunting crypto misuse. CWE-327/328/330/326/916, OWASP A02:2021-Cryptographic Failures." --- # Cryptographic Failures - Hunter Knowledge Base Broken or misused cryptography: weak algorithms, predictable randomness, static keys/IVs, missing integrity, or protecting nothing (plaintext). Impact depends on what the crypto was meant to protect. ## What to hunt - **Weak/broken algorithms** (CWE-327/328): `MD5`/`SHA1` for passwords or signatures, `DES`/`3DES`/`RC4`, fast hashes for password storage (should be argon2/bcrypt/scrypt/PBKDF2). - **Insecure randomness** (CWE-330/338): `Math.random()`, `random.random()`/`random.randint`, `rand()`, `java.util.Random`, time-seeded RNG used for tokens/session ids/password-reset/OTP/nonces/keys. - **Static/hardcoded key or IV** (CWE-321/329): fixed AES key/IV in source; reused nonce; predictable salt. - **ECB mode** (CWE-327): `AES/ECB` leaks plaintext patterns. - **Missing integrity / unauthenticated encryption**: CBC without a MAC (padding-oracle risk); encrypt without authenticate; not using AEAD (AES-GCM/ChaCha20-Poly1305). - **Bad TLS/cert handling**: disabled verification (`verify=False`, `rejectUnauthorized:false`, `InsecureSkipVerify:true`, trust-all TrustManager/HostnameVerifier). - **Weak KDF params**: low PBKDF2 iterations, no salt. - **Nonce/IV misuse**: AES-GCM or ChaCha20 nonce reused under one key (counter reset on restart, constant nonce, random 96-bit nonces at very high volume) - reuse breaks confidentiality and forgery resistance; CBC with a predictable IV; CTR with a repeated counter block. - **Unsafe comparison and MAC construction**: `==` on MACs/signatures (timing); `hash(secret + msg)` instead of HMAC (length extension); MAC not covering all fields (type, version, user id, expiry); MAC-then-encrypt; truncated MAC. - **Public-key misuse**: RSA PKCS#1 v1.5 encryption with distinguishable errors (Bleichenbacher style), RSA keys under 2048 bits, textbook RSA, ECDSA with a reused or biased nonce, signature verified against a key taken from the message itself, `Signature.verify` result ignored. - **Key management**: key derived from a password/username/constant, key in the repo/image/client bundle, one key for many purposes (encrypt and sign, all tenants), no rotation path, keys logged, `.env` defaults shipped. - **Missing crypto where it matters**: secrets, tokens or PII stored/transmitted in cleartext or merely base64/XOR "encrypted"; HTTP endpoints or `http://` URLs for credentials; cookies without `Secure`; `Math.random` fallback when `crypto` is unavailable. - **TLS config**: protocol floor set to SSLv3/TLS 1.0/1.1, `ssl._create_unverified_context`, `check_hostname=False`, `CURLOPT_SSL_VERIFYPEER=0`/`CURLOPT_SSL_VERIFYHOST=0`, custom `ServerCertificateValidationCallback` returning true, `NODE_TLS_REJECT_UNAUTHORIZED=0`, pinned-cert check removed, Go `tls.Config{MinVersion` absent/low. ## Sinks (grep targets) `md5(|sha1(|MD5|SHA1|DES|RC4|Math.random|random\.(random|randint|choice)|util.Random|AES/ECB|ECB| verify=False|rejectUnauthorized|InsecureSkipVerify|createCipher\(|PBKDF2.*iterations|IV\s*=`. Look near "password", "token", "key", "encrypt", "sign", "session". Per stack, safe vs unsafe: Python `hashlib.md5/sha1`, `random`, `Crypto.Cipher.AES.MODE_ECB`, `hmac` compared with `==` (use `hmac.compare_digest`); Node `crypto.createCipher` (deprecated, weak key derivation), `createHash('md5')`, `Math.random`, `jsonwebtoken` secrets that are short; Java `Cipher.getInstance("AES")` (defaults to ECB), `"DES"`, `new Random()`, `MessageDigest.getInstance("MD5")`, `SecureRandom.setSeed` with a constant; Go `math/rand` for tokens, `crypto/md5`, `crypto/des`, `crypto/rc4`; PHP `rand()/mt_rand()/uniqid()` for tokens, `md5()`, `openssl_encrypt` with ECB or a fixed IV, `password_hash` is fine; Ruby `rand`, `Random.new`, `Digest::MD5`, `OpenSSL::Cipher` with a fixed `iv`/`key`; C# `new Random()`, `MD5.Create()`, `DESCryptoServiceProvider`, `RijndaelManaged` with `CipherMode.ECB`. ## Detection recipe 1. Grep the patterns above; for each, determine **what is being protected** and the **threat model**. 2. Password storage: which hash + salt + params? Token generation: which RNG? Encryption: algorithm, mode, key/IV source, integrity? 3. Confirm the weakness is used on security-relevant data (a non-security CRC/`md5` for a cache key is fine). 4. For randomness, trace the value to its use: is it a secret an attacker must not guess (reset token, session id, invite code, API key, CSRF token, password generator, 2FA code, file name that guards access)? Note the length and alphabet: a 6-digit code from a CSPRNG still needs rate limiting (see `auth`). 5. For keys and IVs, find where each comes from: literal, config default, derived from a user-known value, or KMS. Check git history/config templates for the real value, not only the current source. 6. For encryption, check what happens on tamper: is there a MAC/AEAD tag, and is the error distinguishable (padding vs MAC failure) in responses or timing? 7. Look at stored/second-order uses: tokens generated in a worker or migration, keys in a seed script, cookies or hidden fields carrying `encrypt(user_id)` that the client can replay or swap. ## Variant hunting Once one weak primitive is found, grep the same helper/wrapper (`generate_token`, `encrypt_value`, `CryptoUtil`) for all callers - one weak wrapper usually serves many features. Search the other languages and services for the same constant key or salt string; search for the same RNG in every token/ID generator; check sibling features (reset, invite, email verify, API key, share link, signed URL, CSRF token, remember-me) for the identical construction. ## PoC / evidence - The code using the weak primitive at `file:line`. For randomness: show tokens derive from a predictable RNG (attacker can predict/brute future values). For static key: show the literal key/IV. - Padding oracle / ECB: describe the exploit conditions; a full oracle PoC is usually `needs-runtime`. ## False-positive filters - MD5/SHA1 used for **non-security** purposes (ETags, cache keys, dedup checksums) - not a finding. - CSPRNG in use: `secrets`/`os.urandom` (Python), `crypto.randomBytes` (Node), `SecureRandom` (Java), `crypto/rand` (Go). Password hashing via argon2/bcrypt/scrypt with salt. - A hash used where the input is already high-entropy and secret (HMAC key id, token fingerprint, API-key lookup of a 256-bit random token) - fast hashes are acceptable there; they are not for human-chosen passwords. - Test, fixture, example or docs files holding keys; confirm the key is not the one deployed before reporting. - Real evidence of a finding: an attacker can state a concrete capability (predict the next token, decrypt or forge a value, read traffic) given the primitive, the key/IV/nonce source, and the data it protects. "Uses SHA1" alone is not enough. - AEAD (AES-GCM/ChaCha20-Poly1305) or encrypt-then-MAC; per-message random IV/nonce; keys from a KMS/secret manager. TLS verification enabled (the insecure flags are dev-only and not shipped). ## Detection signals (for defenders) - **Logs needed**: web/proxy/WAF logs (token and cookie values hashed or truncated, status, response size, timing), auth/app logs for token validation failures, TLS terminator and egress proxy logs, cloud KMS audit logs. - **Token prediction/forgery**: bursts of requests presenting many distinct reset/session/OTP values with mostly invalid results from one source; successful use of a token that was never issued (no matching issuance event); sequential or near-sequential token values across users. - **Padding/decryption oracle**: many requests that differ by one byte of an encrypted cookie or parameter, with alternating error classes (decrypt error vs MAC/validation error) or response-time differences. - **Key exposure**: KMS `Decrypt`/`GetSecretValue` calls from unexpected principals or networks; secrets scanner hits in repos; a signing key used from two environments. - **TLS downgrade/MITM**: outbound connections from a service that previously validated certs now accepting unexpected issuers; TLS handshakes negotiating legacy protocol versions or weak ciphers in proxy/IDS logs; certificate chain or SNI mismatches in egress logs. - **Behaviour detection ideas**: (1) per-source count of distinct token values tried against token-check routes over a short window with a low success ratio; (2) authenticated activity carrying a token id with no issuance event in the auth log. - **ATT&CK**: T1110 (Brute Force) for token/OTP guessing, T1557 (Adversary-in-the-Middle) for TLS validation failures exploited on the network, T1552 (Unsecured Credentials) for hardcoded or exposed keys, T1550 (Use Alternate Authentication Material) for forged tokens. ## CWE / OWASP / severity CWE-327/328/330/338/321/326/916, CWE-295 (cert validation). OWASP A02:2021. Forgeable tokens / broken auth crypto / disabled TLS verification -> **high/critical**; weak-but-limited -> medium. ## Chaining hints Predictable reset/session tokens -> `auth` account takeover; static JWT/HMAC key -> forge tokens; disabled TLS verification -> MITM -> credential capture; weak password hash + a `secrets`/`sqli` DB dump -> mass credential cracking. ## Mitigation Use argon2/bcrypt/scrypt (salted) for passwords; CSPRNG for all tokens/keys/IVs; AES-GCM or ChaCha20-Poly1305 (AEAD) with per-message nonces; keys from a KMS/secret manager, never hardcoded; enforce TLS certificate verification; drop MD5/SHA1/DES/RC4/ECB for security purposes.