-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatterns.json
More file actions
227 lines (227 loc) · 58.7 KB
/
Copy pathpatterns.json
File metadata and controls
227 lines (227 loc) · 58.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
[
{
"schema_version": "1.0",
"name": "AEAD Nonce Reuse Leading to Loss of Confidentiality and Integrity",
"description": "The provided documentation describes a catastrophic vulnerability resulting from the reuse of a nonce (Number used once) with the same key in AEAD (Authenticated Encryption with Associated Data) ciphers, specifically AES-GCM and ChaCha20-Poly1305. This is a critical implementation flaw, as the security guarantees of these ciphers depend on the uniqueness of the (key, nonce) pair for every encryption operation. Reusing a nonce leads to a complete failure of both confidentiality and integrity.\n\n1. **Loss of Confidentiality**: Both AES-GCM (which uses Counter Mode) and ChaCha20 are stream ciphers at their core. They generate a pseudo-random keystream from the key and nonce, which is then XORed with the plaintext to produce the ciphertext. If the same (key, nonce) pair is used for two different plaintexts (P1, P2), the exact same keystream is generated. An attacker who obtains the two corresponding ciphertexts (C1, C2) can compute their XOR: C1 ⊕ C2 = (P1 ⊕ Keystream) ⊕ (P2 ⊕ Keystream) = P1 ⊕ P2. This leaks the XOR of the two plaintexts, and if an attacker knows or can guess one of the plaintexts, they can recover the other entirely.\n\n2. **Loss of Integrity and Authenticity (Authentication Forgery)**: The authentication mechanisms of GCM and Poly1305 are also compromised by nonce reuse. The one-time authentication key used to compute the tag is derived from the master key and the nonce. Reusing the nonce causes this one-time key to be reused, allowing an attacker to recover it.\n - In **AES-GCM**, the authentication tag is computed using a universal hash key `H` (derived from the encryption key) and a nonce-dependent value `C`. Reusing a nonce means `C` is also reused. As detailed in the corpus, an attacker with two ciphertexts and their tags produced with the same nonce can construct a polynomial equation in the unknown `H`. Solving this equation reveals the secret hash key `H`, which allows the attacker to compute a valid authentication tag for any arbitrary message, completely breaking the cipher's integrity protection.\n - In **ChaCha20-Poly1305**, a similar failure occurs. The per-message Poly1305 key `(r, s)` is generated from the main key and the nonce. Reusing the nonce leads to the reuse of this `(r, s)` pair. As described, this allows an attacker with two message-tag pairs to construct equations and solve for the secret key `r`. Once `r` is recovered, the attacker gains the ability to forge valid tags for arbitrary data, thus breaking authenticity.",
"audit": {
"description": "This resource flags all code snippets that perform encryption using AEAD ciphers like AES-GCM or ChaCha20-Poly1305. Nonce reuse with these ciphers can lead to a catastrophic failure of confidentiality and integrity. The agent should analyze the highlighted code to determine if the nonce (or IV) is generated in a way that could allow it to be reused with the same encryption key. Look for hardcoded nonces, nonces from weak random sources (e.g., non-cryptographic RNGs, low-resolution timestamps), or counters that might reset.",
"prompt": "This code performs encryption using an Authenticated Encryption with Associated Data (AEAD) cipher, specifically AES-GCM or ChaCha20-Poly1305. This includes initializing the cipher (e.g., using functions like `NewGCM`, `createCipheriv`, `AESGCM`, `ChaCha20Poly1305`) and performing the encryption operation (e.g., `seal`, `encrypt`). The nonce (or IV) is specified or generated in this code with static, predictable, or weak methods."
}
},
{
"schema_version": "1.0",
"name": "CBC Bit-Flipping Attack",
"description": "This attack is possible when an application uses CBC mode for confidentiality but fails to pair it with a Message Authentication Code (MAC) or another integrity-checking mechanism. The scenario involves an attacker who has some knowledge of the plaintext format and can modify the ciphertext in transit. The root cause lies in the CBC decryption formula, `P_i = D_K(C_i) ⊕ C_{i-1}`, where the decryption of a plaintext block `P_i` is XORed with the previous ciphertext block `C_{i-1}`. Modifying a bit in `C_{i-1}` will cause a corresponding bit flip in the decrypted `P_i`, while the decrypted `P_{i-1}` becomes completely garbled. This allows an attacker to precisely tamper with the contents of a specific plaintext block by modifying the preceding ciphertext block. For example, if a session cookie contains `...;admin=0;...`, an attacker can flip the appropriate bits in the preceding ciphertext block to change the value to `admin=1`. Although this corrupts the previous plaintext block, an application might ignore the garbled data and only parse the now-malicious value, leading to privilege escalation or other integrity violations.",
"audit": {
"description": "Identifies code locations where a cryptographic cipher is configured to use Cipher Block Chaining (CBC) mode. The use of CBC mode without a corresponding message authentication code (MAC) for integrity checking can make the application vulnerable to CBC bit-flipping attacks, allowing an attacker to manipulate the decrypted data.",
"prompt": "This code initializes or uses a cryptographic cipher explicitly configured with Cipher Block Chaining (CBC) mode. Look for cipher initializations (e.g., `AES.new`, `Cipher(...)`) where a parameter specifies CBC mode (e.g., `AES.MODE_CBC`, `modes.CBC(...)`)."
}
},
{
"schema_version": "1.0",
"name": "Ciphertext Malleability in CTR Mode",
"description": "This vulnerability affects applications that use CTR mode for confidentiality but do not employ a separate mechanism for ensuring data integrity, such as a Message Authentication Code (MAC). The scenario involves an attacker with some knowledge of the plaintext structure. The root cause is the linear nature of the XOR operation used in CTR mode (`C = P ⊕ Keystream`), which means modifications to the ciphertext are directly transferred to the plaintext upon decryption. An attacker can perform a bit-flipping attack with surgical precision by XORing the ciphertext `C` with a chosen difference `Δ`, causing the resulting plaintext `P'` to become `P ⊕ Δ`. Unlike the CBC bit-flipping attack, this modification has no side effects and does not corrupt any other part of the message. This allows an attacker to silently and cleanly tamper with encrypted data, such as changing a transaction amount in a financial message, leading to a complete loss of integrity.",
"audit": {
"description": "This resource identifies code snippets that use CTR (Counter) mode for encryption. CTR mode itself does not provide integrity protection, making the ciphertext malleable. These locations should be investigated to ensure a separate Message Authentication Code (MAC), such as HMAC, is used to prevent bit-flipping attacks.",
"prompt": "This code snippet performs cryptographic operations using a cipher configured in CTR (Counter) mode. This includes instantiating ciphers with constants like `MODE_CTR` or classes like `modes.CTR` from libraries such as `pycryptodome`, `pycrypto`, or `cryptography`."
}
},
{
"schema_version": "1.0",
"name": "Cryptographic Parameter Validation Flaws",
"description": "Flaws from insufficient input validation in cryptographic functions leading to memory corruption. Technical specifics include: (1) Missing bounds checks in memcpy and other similar operations within cryptographic APIs, restrict computationally intensive numbers (e.g., primes during Diffie-Hellman negotiations); (2) Triggered by user-controlled input sizes exceeding buffer capacities. Exploitable specifics refer to attackers manipulate ciphertext/size inputs to exceed allocated Examples: (1) PHP openssl_seal() heap overflow (r_5) - wild memcpy with attacker-controlled IV length; OpenSSL PBKDF2 invalid memcpy parameter (r_66) - heap overflow via crafted parameter passing. (2) Client DoS due to large DH parameter (CVE-2018-0732). (3) In OpenSSL (crypto/evp/evp_enc.c, crypto/rsa/rsa_oaep.c), `EVP_EncryptUpdate()` (CVE-2016-2106), `RSA_padding_check_PKCS1_type_2(), the attacker can crafts malicious-length ciphertext to overflow `EVP_CIPHER_CTX` buffer",
"audit": {
"description": "This resource identifies calls to cryptographic functions where the size of the input data, key, initialization vector (IV), or other parameters is not a hardcoded constant. Such locations are potential triggers for memory corruption vulnerabilities (e.g., heap overflows) if the underlying cryptographic library fails to perform adequate bounds checking on user-controlled input sizes.",
"prompt": "This code calls a cryptographic function (such as those from OpenSSL, or functions related to encryption, decryption, sealing, key derivation like PBKDF2, or Diffie-Hellman exchanges) and passes an argument for data, a key, an initialization vector (IV), or a parameter whose size is determined by a variable rather than a hardcoded literal. This is a potential trigger for memory corruption vulnerabilities if the cryptographic library lacks proper bounds checking."
}
},
{
"schema_version": "1.0",
"name": "Diffie-Hellman Small Subgroup Attack due to Missing Key Validation",
"description": "During a Diffie-Hellman key exchange, an attacker provides a public key that is not an element of the large prime-order subgroup intended for the protocol. The vulnerability is the receiving implementation's failure to validate that the public key has the correct order. This forces the resulting shared secret into a small, predictable set of values, leaking information about the victim's private key.\n1. In ECDH, for curves where the order is a product of a large prime n and a small cofactor h > 1 (e.g., Curve25519 where h=8), an attacker sends a point of small order. The victim computes the shared secret S = d_victim * P_attacker. The resulting point S is confined to the small subgroup, revealing information about d_victim mod h. For Curve25519, this leaks the 3 least significant bits of the private key.\n2. In classic finite field Diffie-Hellman, an attacker sends a public value Y that is an element of a small order subgroup, such as Y=1 (order 1) or Y=p-1 (order 2). If the victim computes the shared secret S = Y^d_victim mod p, the result is predictable. For Y=p-1, the secret S will be either 1 (if d_victim is even) or p-1 (if d_victim is odd), directly leaking the least significant bit (LSB) of the private key.",
"audit": {
"description": "Identifies code locations performing Diffie-Hellman (DH) or Elliptic Curve Diffie-Hellman (ECDH) key exchange. This is the critical step where a shared secret is computed using a peer's public key. A 'Small Subgroup Attack' or 'Invalid Curve Attack' is possible if the peer's public key is not validated to be a member of the correct large-order subgroup before this operation, which can leak bits of the private key.",
"prompt": "This code performs a Diffie-Hellman (DH) or Elliptic Curve Diffie-Hellman (ECDH) key exchange to compute a shared secret from a peer's public key. This typically involves a function call that takes a peer's public key and the local private key to compute a shared secret, using functions like `exchange`, `shared_secret`, `generateSecret`, or `ECDH`."
}
},
{
"schema_version": "1.0",
"name": "ECDH Invalid Curve Attack due to Missing Point-on-Curve Validation",
"description": "In an Elliptic Curve Diffie-Hellman (ECDH) key exchange, a malicious party sends a public key to a victim. The vulnerability stems from the victim's implementation failing to verify that the received public key point actually lies on the agreed-upon elliptic curve. Many scalar multiplication algorithms, which are the core of ECDH, do not use the curve's 'b' parameter from the equation y^2 = x^3 + ax + b. An attacker exploits this by sending a point that lies on a different, specially crafted \"invalid\" curve (y^2 = x^3 + ax + b') that shares the same 'a' parameter but has a group order with many small prime factors. When the victim calculates the shared secret S = d_victim * P_attacker, the result S also lies on the attacker's weak curve. Since the point P_attacker has a small order r, the shared secret S only depends on d_victim mod r. The attacker can determine S (e.g., through a timing side-channel or an oracle that uses the key) and then brute-force the small range of possibilities to find d_victim mod r. By repeating this attack with points from different weak curves having different small prime orders, the attacker collects enough congruences to reconstruct the victim's entire private key d_victim using the Chinese Remainder Theorem (CRT).",
"audit": {
"description": "This resource flags code snippets that perform an Elliptic Curve Diffie-Hellman (ECDH) key exchange. These are potential locations for an Invalid Curve Attack if the implementation does not validate that a received public key point lies on the correct elliptic curve before computing the shared secret.",
"prompt": "This code snippet performs an Elliptic Curve Diffie-Hellman (ECDH) key exchange. It uses a public key, potentially from an external source, to compute a shared secret through scalar multiplication."
}
},
{
"schema_version": "1.0",
"name": "Hash Length Extension Attacks",
"description": "This section covers vulnerabilities where hash functions susceptible to length extension attacks are used inappropriately for authentication or integrity verification. Length extension attacks allow attackers to append data to a message and compute a valid hash for the extended message without knowing the original secret key. Common form like H(secret || user_data) where attackers can append more the user_data. Authentication tokens/signatures generated via H(secret || user_data) enable privilege escalation or parameter tampering. Attackers extend tokens with illicit roles or payloads validated by victim systems. MD5/SHA1/SHA256 or other MD-based iterative structure hash design can all be vulnerable to it. This can lead to HTML injection, privilege escalation, authentication bypass and other security compromises as demonstrated in various applications. Example: Zomato's token mechanism allowed extending session metadata via SHA-256 to inject HTML payloads into server-rendered views (CVE details in r_81).",
"audit": {
"description": "This resource flags code snippets that use hash functions susceptible to length extension attacks (e.g., MD5, SHA1, SHA256) to create Message Authentication Codes (MACs), signatures, or authentication tokens. These implementations are often vulnerable if they use the H(secret || message) construction, allowing attackers to forge valid signatures for extended messages without knowing the secret.",
"prompt": "This code uses a hash function from a library like hashlib (e.g., md5, sha1, sha256) to generate a signature, authentication token, or message authentication code (MAC). The hashed content is a concatenation of a secret key and some message data, in a pattern similar to `hash(secret + data)`."
}
},
{
"schema_version": "1.0",
"name": "Inconsistent Behaviour and Flawed Error Handling",
"description": "These vulnerabilities stem from (1) inconsistent calculation path or error/exception throwing path which may leak the invovled secret bytes/bit/pattern. The inconsistency can be observed by attacker through normal entrypoints exposed outside. Or the response code/content returned from the normal network channel. A typical example of such consistency is padding oracle attacks. (2) Failures to validate error conditions before proceeding with cryptographic operations. Specifics include ignoring return codes from OpenSSL EVP_* functions in wrapper libraries, which can be induced injected faults during cryptographic operations. Example: (1) Node.js crypto library (crypto_cipher.cc) proceeding with decryption after OpenSSL errors, enabling plaintext recovery (r_52). (2) multiple OpenSSL error handling issues in Node.js crypto library (CVE-2023-23919)",
"audit": {
"description": "This resource flags code locations that perform cryptographic operations, particularly decryption, where the error handling logic is either inconsistent or missing. This includes patterns like padding oracles where different errors are returned based on secret data, or cases where error return codes from cryptographic libraries (like OpenSSL) are ignored. These locations are potential entry points for side-channel attacks or information disclosure.",
"prompt": "This code performs a cryptographic operation (such as decryption) and immediately afterward either (1) enters a conditional block or try/except block where different types of cryptographic errors could be handled in distinguishable ways that are observable by an attacker, or (2) fails to check the return value of the cryptographic function for an error before using the resulting data."
}
},
{
"schema_version": "1.0",
"name": "Insecure ECDSA Nonce Generation from Key and Message Components",
"description": "The paper analyzes a custom ECDSA implementation on the Bitcoin blockchain that uses a critically flawed nonce generation scheme, enabling full private key recovery from a single signature.\n\n1. **Implementation Flaw:** The implementation forgoes secure nonce generation (e.g., random or RFC 6979 deterministic) and instead constructs the nonce `k` from public and secret data. As described in Section 1, the nonce is formed by concatenating the 128 most significant bits of the message hash (`h_msb`) with the 128 most significant bits of the private key (`d_msb`). This is formalized as `k = 2^128 * h_msb + d_msb` (Section 3). This method directly embeds half of the secret key into the nonce, a value that becomes partially recoverable from the public signature components.\n\n2. **Attack and Impact:** This predictable nonce structure creates a solvable mathematical relationship between public signature values and the unknown portions of the private key. The paper details a lattice-based attack (Section 3.1, \"Main Attack\") that solves for the full private key `d` in approximately one core-second using a single signature. The impact is a complete and immediate compromise of the signing key, allowing an attacker to steal any funds controlled by it.\n\n3. **Real-World Evidence:** The authors scanned the Bitcoin blockchain and discovered 88,230 signatures exhibiting this flaw, originating from software used by a single entity from 2015 to 2022 to sweep funds from compromised addresses (Section 5). While the actor may have intentionally used this method on keys they considered already public (Section 5.2), the unique signature artifact inadvertently created a fingerprint that allowed researchers to link their activities across thousands of transactions, compromising their operational pseudonymity. This highlights how even deliberate but flawed cryptographic shortcuts can have unintended security consequences.",
"audit": {
"description": "This resource flags code snippets that implement ECDSA signing with a custom, deterministic nonce generation scheme. Specifically, it looks for implementations where the nonce 'k' is derived by combining parts of the message hash and the private key, which is a critical vulnerability that can lead to private key recovery.",
"prompt": "This code performs ECDSA signing. It uses a custom, non-standard method to generate the nonce `k`. The nonce is constructed by combining a portion of the message hash with a portion of the private key, for example, by concatenating their most significant bits. This is in contrast to secure methods like using a random number generator or RFC 6979."
}
},
{
"schema_version": "1.0",
"name": "Insecure Standard Library Random Functions",
"description": "These vulnerabilities stem from using programming language standard library random functions that are designed for statistical purposes rather than cryptographic security. Implementation mechanisms typically involve Math.random() in JavaScript environments, Python's random module, or similar non-cryptographic PRNGs that use linear congruential generators or Mersenne Twister algorithms. Vulnerability triggers occur when these functions are used for generating authentication tokens, session identifiers, encryption keys, or password reset tokens. Exploitable specifics include predictable seed values, observable state transitions, and the ability to forecast future values after observing a sequence of outputs. Example 1: Gratipay using Python's random module for cryptographically sensitive operations, allowing attackers to predict subsequent random values. Example 2: crypto-js library in Node.js using Math.random() as entropy source in /node_modules/crypto-js/*, enabling state prediction attacks. Example 3: Alvocrypt implementation using insecure PRNG for key generation, making encrypted data vulnerable to brute-force attacks on predictable key space. Example 4: Nextcloud (r_31, r_106) used predictable RNG in file-sharing password generation (e.g., via PHP rand()), allowing brute-force attacks against share links with disabled policy enforcement",
"audit": {
"description": "This resource flags code snippets that use standard library pseudo-random number generators (PRNGs) which are not cryptographically secure. This includes Python's `random` module, JavaScript's `Math.random()`, and PHP's `rand()` or `mt_rand()`. Such functions are predictable and should not be used for security-sensitive operations like generating tokens, session IDs, encryption keys, or password reset links.",
"prompt": "The code uses a non-cryptographically secure pseudo-random number generator, such as functions from Python's `random` module, JavaScript's `Math.random()`, or PHP's `rand()` or `mt_rand()`."
}
},
{
"schema_version": "1.0",
"name": "Invalid Point or Public Key Attacks",
"description": "This flaw occurs in ECC/DLP signature verification libraries (e.g., ECDSA, EdDSA) when the implementation **fails to rigorously validate an input public key or point $P$** before performing cryptographic operations (like point multiplication). The attacker can supply a malicious public key that is **not on the curve** or is **not a member of the correct prime-order subgroup**.\n\n**Consequences:**\n1. **Side-Channel Leakage:** The use of an invalid point can cause the signing or verification process to execute in a **non-constant time**, potentially leaking information about the private key through timing attacks.\n2. **Miscalculation/Denial of Service:** Operations on invalid points can lead to unexpected exceptions, infinite loops, or **invalid results** that compromise the integrity of the verification process, potentially leading to denial of service or protocol failure.",
"audit": {
"description": "Flags code locations performing elliptic curve signature verification (e.g., ECDSA, EdDSA). These are potential entry points for an invalid curve point attack, where an attacker supplies a malicious public key. The subsequent analysis should check if the public key is rigorously validated (i.e., checked to be on the curve and in the correct subgroup) before it is used in the verification function.",
"prompt": "This code performs elliptic curve signature verification, such as ECDSA or EdDSA, using libraries like `cryptography`, `ecdsa`, `pynacl`, etc. It specifically looks for calls to verification functions where the public key is a variable, likely originating from an external source (e.g., network request, file, database), and not a hardcoded constant."
}
},
{
"schema_version": "1.0",
"name": "Keystream Counter Overflow",
"description": "This vulnerability occurs when an implementation encrypts more data under a single (Key, Nonce) pair than the cipher's block counter can support, causing the counter to wrap around to its initial value. For example, the IETF specification for ChaCha20 uses a 32-bit block counter, which allows for the encryption of 2^32 blocks of 64 bytes each, for a total of 256 GiB of data. If an application attempts to encrypt more than this limit in a single session without rekeying or changing the nonce, the counter will overflow and reset. This causes the keystream to repeat from the beginning, which is functionally equivalent to nonce reuse. Any data encrypted after the counter wraps will be compromised, as an attacker can XOR it with the data from the beginning of the stream to recover the plaintext XOR.",
"audit": {
"description": "Flags code snippets that perform encryption using a stream cipher or a block cipher in a counter-based mode (e.g., ChaCha20, AES-GCM, AES-CTR). These snippets typically involve initializing a cipher with a key and nonce, and then using it to encrypt data in a loop, such as processing a file or network stream. This pattern is a prerequisite for potential cryptographic counter overflow vulnerabilities, which occur if more data is encrypted than the cipher's counter can handle without rekeying.",
"prompt": "This code performs encryption using a stream cipher or a block cipher in a counter-based mode (like ChaCha20, Salsa20, AES-GCM, or AES-CTR). The encryption is applied repeatedly to chunks of data, for example, inside a loop that reads from a file or network stream, without rekeying or changing the nonce inside the loop, or with insufficient counter size to handle the total data volume."
}
},
{
"schema_version": "1.0",
"name": "Keystream Reuse in CTR Mode",
"description": "This is a critical vulnerability that occurs when an application uses Counter (CTR) mode or another stream cipher mode and reuses the same nonce (or a combination of nonce and initial counter value) for more than one encryption operation with the same key. The root cause is that in CTR mode, a unique keystream is generated by encrypting a sequence of `(Nonce, Counter)` values; if the same `(Key, Nonce)` pair is ever reused, the exact same keystream is generated. This leads to a catastrophic failure of confidentiality. If an attacker obtains two ciphertexts, `C_1` and `C_2`, that were generated using the same keystream (`KS`), they can compute `C_1 ⊕ C_2`. This operation cancels out the keystream, yielding the XOR of the two original plaintexts (`P_1 ⊕ P_2`). Given the statistical properties of common data formats, an attacker can often separate the two plaintexts from their XOR sum, recovering both original messages.",
"audit": {
"description": "This resource flags code snippets that perform encryption using a stream cipher mode like CTR, OFB, or CFB. These modes are vulnerable to nonce reuse, where encrypting different plaintexts with the same key and nonce can lead to a catastrophic loss of confidentiality. The flagged locations are potential attack surfaces that require further analysis to determine if the nonce (or IV) is generated and managed securely for each encryption operation.",
"prompt": "This code snippet initializes a cipher for encryption using a stream cipher mode such as CTR (Counter mode), OFB (Output Feedback), or CFB (Cipher Feedback). This could involve using libraries like `cryptography.hazmat.primitives.ciphers`, `Crypto.Cipher`, or similar cryptographic packages where a nonce or IV is explicitly provided (or provided with low entropy)"
}
},
{
"schema_version": "1.0",
"name": "Nonce Reuse in Stream Ciphers",
"description": "This vulnerability occurs when a unique (Key, Nonce) pair is used to encrypt more than one distinct plaintext message. Stream ciphers generate a keystream based on the key and nonce, which is then XORed with the plaintext. If the same keystream is used twice, an attacker who obtains the two corresponding ciphertexts (C1, C2) can XOR them together (C1 ⊕ C2) to cancel out the keystream, revealing the XOR of the two plaintexts (P1 ⊕ P2). This significantly reduces the complexity of cryptanalysis, often allowing for full plaintext recovery using statistical methods like crib-dragging.\n\nCommon implementation failures leading to nonce reuse include:\n1. **Random Nonce Collision:** Using a randomly generated nonce with an insufficient bit-length. For example, using a 64-bit random nonce for ChaCha20 increases the probability of a collision to unacceptable levels in high-volume or long-running applications, as predicted by the birthday paradox. Standards like IETF RFC 7539 (96-bit nonce) or XChaCha20 (192-bit nonce) are designed to mitigate this.\n2. **State Rollback:** In virtualized or containerized environments, taking a snapshot of a running system and later rolling back to it restores the application's memory state, including the cryptographic context (key and last-used nonce/counter). If the application resumes operation without re-initializing its cryptographic state, it will reuse nonces, compromising all new messages encrypted until the nonce state diverges from its pre-rollback path.\n3. **Deterministic Nonce Generation without State:** Generating nonces using a simple counter that is reset to zero every time an application or device restarts. This guarantees nonce reuse across sessions.",
"audit": {
"description": "This resource flags all code snippets that perform encryption using a stream cipher or an Authenticated Encryption with Associated Data (AEAD) mode, such as ChaCha20, XChaCha20, AES-GCM, or AES-CTR. Such code is a potential site for a nonce reuse vulnerability if the nonce is not managed correctly.",
"prompt": "This code snippet performs encryption using a stream cipher or an Authenticated Encryption with Associated Data (AEAD) mode, such as ChaCha20, XChaCha20, AES-GCM, or AES-CTR. Such code is a potential site for a nonce reuse vulnerability if the nonce is not managed correctly."
}
},
{
"schema_version": "1.0",
"name": "Nonces with Biased Structure (Shared Affixes)",
"description": "Even if the nonce k is large, its security is compromised if it is not uniformly drawn from its required range, particularly when nonces generated by the same key share a large constant prefix (MSBs) or suffix (LSBs). This structural bias allows an attacker to algebraically eliminate the shared constant portion across multiple signatures. The remaining smaller, variable portion can then be solved using a lattice attack, compromising the private key. This vulnerability often signals memory management bugs (copy errors) or flawed custom nonce generation logic that improperly mixes random and static data.",
"audit": {
"description": "This resource identifies code snippets related to the generation or use of a custom nonce (often named 'k') in cryptographic signing operations like ECDSA or DSA. Standard libraries typically handle nonce generation securely (e.g., via RFC 6979). Providing a custom nonce is error-prone and can lead to private key recovery if the nonce is biased or predictable, for example, by mixing random data with static data. These locations are critical entry points for investigating potential biased nonce vulnerabilities.",
"prompt": "This code snippet implements custom logic to generate a nonce (often named 'k') for a cryptographic signing algorithm (like ECDSA or DSA), or it calls a signing function and explicitly provides a custom-generated nonce as an argument."
}
},
{
"schema_version": "1.0",
"name": "Not Hashing Message Before Signing/Verification",
"description": "This vulnerability arises from an implementation flaw where the signature or verification function either **directly accepts the raw message input** or allows a path to be signed/verified **without first applying a cryptographic hash function** (e.g., SHA-256).\n\n**Consequences:**\n1. **Full Preimage Attack:** If a short or predictable message is signed directly, an attacker might be able to find the message that corresponds to the signature value without needing to break the underlying hash function.\n2. **Arbitrary Data Signature:** This flaw allows the system to sign an arbitrary, unconstrained length of data. If the signature scheme's security is based on the hash output being modulo the group order $n$, signing a very long message directly can lead to a signature that is effectively based on a large number modulo $n$, which may be easier to forge than the output of a secure hash function (Hash-then-Sign principle violation).",
"audit": {
"description": "This resource flags code snippets where a cryptographic signing or verification function is called directly on a message without first applying a standard cryptographic hash function (e.g., SHA-256). This violates the 'hash-then-sign' principle and can lead to signature forgery or other attacks.",
"prompt": "This code snippet contains a call to a cryptographic signing or verification function (such as `sign`, `verify`, `sign_recoverable`, `recover`, `verify_compact`) where the message argument is not the result of a call to a cryptographic hash function (like those from `hashlib`, `Crypto.Hash`, `sha3`, or `keccak`)."
}
},
{
"schema_version": "1.0",
"name": "Padding Oracle Attack in CBC Mode",
"description": "This vulnerability occurs when a server-side application decrypts data encrypted in Cipher Block Chaining (CBC) mode and its error handling leaks information about the validity of the PKCS#7 padding. The root cause is a side-channel where the application provides a distinguishable response—such as a specific error message, a different HTTP status code, or a measurable time delay—for a padding validation failure compared to other decryption errors (e.g., a message authentication code failure). This difference creates an 'oracle' that an attacker can query. An attacker can intercept a ciphertext and, without knowing the encryption key, iteratively send modified versions of it to the server. By observing the oracle's response to each modification, the attacker can deduce the value of each byte of the intermediate plaintext state. This process can be repeated for every block, allowing the attacker to decrypt the entire ciphertext, completely compromising data confidentiality.",
"audit": {
"description": "This resource identifies code snippets where cryptographic decryption is performed and is surrounded by error handling. These are potential sites for padding oracle vulnerabilities, as the way different cryptographic exceptions (especially padding errors vs. other errors) are handled can leak information to an attacker.",
"prompt": "This code performs cryptographic decryption, potentially using a block cipher in CBC mode. It includes error handling (e.g., a try-except block) that catches and handles exceptions related to decryption. Specifically, it may handle padding-related errors differently from other cryptographic errors, potentially leading to a padding oracle vulnerability."
}
},
{
"schema_version": "1.0",
"name": "Private Key Disclosure in ECIES (Elliptic Curve Integrated Encryption Scheme) via Invalid Curve Attack",
"description": "#### **1. Background: Generic ECIES (Elliptic Curve Integrated Encryption Scheme)**\n\nThis document describes a critical vulnerability in implementations of Elliptic Curve Cryptography (ECC) protocols, such ECIES-like encryption schemes. The vulnerability stems from the failure of a recipient to validate that a received public key point is actually on the pre-approved elliptic curve. This omission allows for an \"Invalid Curve Attack,\" a type of side-channel attack where a carefully crafted, malicious point can be used to create an information oracle, ultimately leading to the complete recovery of the recipient's private key.\n\nLet's review a generic ECC-based key agreement and encryption flow. The elliptic curve is defined by the equation $y^2 \\equiv x^3 + ax + b \\pmod{p}$, with a base point $G$ of prime order $n$. User B has a private key $d$ (an integer where $1 \\le d < n$) and a corresponding public key $P_B = [d]G$.\n\n**Operations of the Initiator (Party A):**\n\n1. Generate an ephemeral random integer $k \\ in [1, n-1]$.\n2. Calculate the ephemeral public key point $R = [k]G$. This point is sent as part of the exchange to the recipient.\n3. Calculate the shared secret point $S = [k]P_B$. Since $P_B = [d]G$, this is equivalent to $S = [k]([d]G) = [d]([k]G) = [d]R$.\n4. Derive a symmetric key from the coordinates of the shared secret point $S$ using a Key Derivation Function (KDF): $K = \\text{KDF}(x_S, y_S)$.\n5. Use the symmetric key $K$ to encrypt a message $M$ into ciphertext $C_\\text{enc}$, and potentially generate a Message Authentication Code (MAC) tag $T$.\n6. Combine the ephemeral public key point $R$, the encrypted message $C_\\text{enc}$, and the tag $T$ into a final cryptographic payload to be sent to User B.\n\n**Operations of the Responder (Party B):**\n\n1. **[CRITICAL STEP]** Parse the ephemeral public key point $R$ from the received data. It is **essential to verify** that $R$ is a valid point on the expected elliptic curve. This means its coordinates $(x_R, y_R)$ must satisfy the curve equation: $y_R^2 \\equiv x_R^3 + ax_R + b \\pmod{p}$.\n2. Use their private key $d$ to calculate the shared secret point $S' = [d]R$.\n3. Derive the symmetric key using the same KDF: $K' = \\text{KDF}(x_{S'}, y_{S'})$.\n4. Use the key $K'$ to decrypt the message $M'$ and recalculate the MAC tag $T'$.\n5. If the calculated tag $T'$ matches the received tag $T$, the decryption is successful and the message $M'$ is authentic. Otherwise, the payload is rejected.\n\n#### **2. The Vulnerability: Omitting Public Point Validation**\n\nThe vulnerability arises when an ECC library or protocol implementation **skips Step 1** of the responder's process. If the implementation does not validate that the received point $R$ is on the legitimate curve, it will perform the scalar multiplication `[d]R` using its private key on a point of unknown origin.\n\nAn attacker can exploit this by crafting a point $R$ that lies on a **different, but related, elliptic curve**. This curve is defined as $y^2 \\equiv x^3 + ax + b^* \\pmod{p}$, sharing the same field prime $p$ and coefficient $a$ as the legitimate curve, but with a different coefficient $b^*$. The coordinates of the attacker's chosen point $R=(x_R, y_R)$ inherently define this new curve, where $b^* \\equiv y_R^2 - x_R^3 - ax_R \\pmod{p}$.\n\nMany ECC libraries' scalar multiplication algorithms depend only on the point's coordinates and the curve parameters $a$ and $p$. They do not inherently require the point to satisfy the curve equation involving the specific coefficient $b$. Therefore, the computation `[d]R` proceeds, but it does so on the attacker-chosen \"invalid curve.\"\n\n#### **3. The Attack: Creating an Information Oracle**\n\nThe security of ECC relies on the difficulty of the discrete logarithm problem on groups of a large, prime order. However, an attacker is free to choose a point $R$ that belongs to a \"weak\" curve, specifically one whose group of points contains a subgroup of a **small, smooth order**.\n\nFor example, an attacker can choose a **point of order 2**. On an elliptic curve, a point $(x, y)$ has order 2 if and only if $y=0$ (and it is not the point at infinity). An attacker can find a point $R = (x_R, 0)$ that lies on some curve $y^2 \\equiv x^3 + ax + b^* \\pmod{p}$ (which implies $x_R^3+ax_R+b^* \\equiv 0 \\pmod p$). This point satisfies $[2]R = \\mathcal{O}$ (the point at infinity).\n\nThe attacker sends this special point $R$ to the victim. The victim's system, which lacks the validation step, proceeds to compute $S' = [d]R$. Based on the properties of scalar multiplication, the result $S'$ reveals information about the private key $d$:\n\n- If the private key $d$ is **even** ($d \\equiv 0 \\pmod 2$), then $S' = [d]R = [2k]R = [k]([2]R) = [k]\\mathcal{O} = \\mathcal{O}$. The result is the point at infinity.\n- If the private key $d$ is **odd** ($d \\equiv 1 \\pmod 2$), then $S' = [d]R = [(2k+1)]R = [2k]R + R = \\mathcal{O} + R = R$. The result is the original point sent by the attacker.\n\nDepending on whether a subsequent operation (like the KDF or MAC check) behaves differently when its input `S'` is the point at infinity, the attacker can observe this difference (e.g., via an error message, a timing delay, or a different MAC validation outcome). This side channel acts as an oracle, revealing the least significant bit (LSB) of the private key `d`.\n\nBy choosing points of other small orders (e.g., order 3, 5, etc.), the attacker can repeat this process to learn information about $d \\pmod 3$, $d \\pmod 5$, and so on. Finally, using the Chinese Remainder Theorem (CRT) or similar techniques, the attacker can combine these pieces of information to fully reconstruct the victim's private key `d`.\n\n#### **4. Mitigation**\n\nIn any scenario involving the processing of externally-supplied elliptic curve points, it is **mandatory** to strictly validate that the point satisfies the expected curve equation before performing any operation with a private key (such as scalar multiplication). Upon receiving an ephemeral public key point $R(x_R, y_R)$, the following checks must be performed:\n\n1. **Coordinate Range Check**: Ensure that $0 \\le x_R < p$ and $0 \\le y_R < p$.\n2. **Point-on-Curve Validation**: Calculate $y_R^2 \\pmod p$ and $(x_R^3 + ax_R + b) \\pmod p$, and verify that the two results are equal.\n3. **(Optional but Recommended) Subgroup Confinement Check**: Verify that the point belongs to the correct prime-order subgroup. This can be achieved by checking that $[n]R = \\mathcal{O}$ and $R \\ ne \\mathcal{O}$. This step mitigates more advanced subgroup attacks.",
"audit": {
"description": "This resource flags code snippets where an externally-provided Elliptic Curve (EC) public key is used in a cryptographic operation (like ECDH key exchange or ECIES) without clear evidence of point-on-curve validation. This is a potential entry point for an Invalid Curve Attack, where a malicious point could be used to leak the private key.",
"prompt": "This code snippet performs an elliptic curve scalar multiplication in ECIES decryption or other similar IES/PKE. It uses an ecc point that originates from an external or untrusted source (e.g., deserialized from a network request or read from a file). This point is then used in a cryptographic operation involving a private key, such as scalar multiplication, without first explicitly verifying that the point is valid and lies on the expected curve."
}
},
{
"schema_version": "1.0",
"name": "Reusing The Same Value Of k In Different Signatures",
"description": "As part of the message signing process, the user is required to randomly generate a `𝑘` value and use it to sign the message. It is very important to use different `𝑘` values in different signatures. Otherwise - given two signed messages where the user used the same value `𝑘` instead of re-generating it, an attacker could calculate the user's private key.\n\nAs mentioned, during message signing the user publicly sends $r=x_1\\ \\ \\ \\ (mod\\ p)$ and and $s=k^{-1}(z+rd_A)$. Assuming that the user signed two different messages corresponding to $𝑧_1$ and $𝑧_2$, and publicly sent two pairs of values $𝑟, 𝑠_1$ and $𝑟, 𝑠_2$, i.e. used the same `𝑘` value in these two signatures. We note that:\n\n$s_1-s_2=k^{-1}(z_1+rd_A)-k^{-1}(z_2+rd_A)=k^{-1}(z_1+rd_A-z_2-rd_A)=k^{-1}(z_1-z_2)$\n\nFrom this, the attacker can find the value of `𝑘` by calculating:\n\n$\\displaystyle k=\\frac {z_1-z_2}{s_1-s_2}$\n\nAfter the attacker found `𝑘`, they can calculate the user's private key from one of the signatures. Note that:\n\n$r^{-1}(ks-z)=r^{-1}(kk^{-1}(z+rd_A)-z)=r^{-1}(z+rd_A-z)=r^{-1}rd_A=d_A$\n\nGiven the values of `𝑟`, `𝑠` and `𝑧` of a message and its signature, and the value of `𝑘` that the attacker found, the attacker can calculate $d_A=r^{-1}(ks-z)$. From this point, the attacker can sign any message they want, on behalf of the user whose private key they obtained.\n\nThe following code snippet performs this attack:\n\n```python\nfrom ecdsa.ecdsa import curve_256, generator_256, Public_key, Private_key\nfrom Crypto.Util.number import bytes_to_long, long_to_bytes\nfrom hashlib import sha256\nimport random\n\n# Select a curve and generator\ncurve = curve_256\ngenerator = generator_256\nn = generator.order()\n\n# Create private key and public keys\nsecret_key = 6743529130774090927928101169617481154782309\npublic_key = Public_key(generator, generator * secret_key)\nprivate_key = Private_key(public_key, secret_key)\n\n# Sign 2 messages using the same k\nk = random.randrange(curve.p())\nmessage1 = \"Life is like a box of chocolates.\"\nmessage2 = \"You never know what you're gonna get.\"\nz1 = bytes_to_long(sha256(message1.encode()).digest())\nz2 = bytes_to_long(sha256(message2.encode()).digest())\n\nsignature1 = private_key.sign(z1, k)\nsignature2 = private_key.sign(z2, k)\n\n# Given the two messages and their signatures, find k\nfound_k = (z1 - z2) * inverse_mod(signature1.s - signature2.s, n) % n\nassert k == found_k\n\n# Given k and one of the messages, find the private key\nfound_key = inverse_mod(signature1.r, n) * (found_k * signature1.s - z1) % n\nassert found_key == secret_key\nprint(\"success!\")\nprint(\"The secret is:\", long_to_bytes(found_key).decode())\n```\n\n\nIn this code snippet, the library ecdsa is used, along with a known curve. We define a private key and use it to sign two messages. The value of `𝑘` is randomly generated, but it remains the same for the two signatures. Given the two messages and their signatures, the code performs the calculation we saw to find `𝑘`. Finally, we use the value of `𝑘` we found to calculate the private key as we saw. The output is:\n\n```\nSuccess!\nThe secret is: Mistakes were made\n```\n\nIt is interesting to note that this attack was actually used in 2010, when Sony insecurely implemented their signing mechanism on the PlayStation console software. Sony used a static value of `𝑘` for its signatures, which allowed attackers to obtain Sony's private key using the above calculation. This led to the ability to sign any code, and make PlayStation agree to run it. Later this ability was used to install pirated and unofficial games on the console.",
"audit": {
"description": "This resource flags all code snippets that perform cryptographic signing (e.g., ECDSA) where a nonce or 'k' value is explicitly provided to the signing function. Manually providing the nonce increases the risk of its reuse for different signatures, which can lead to private key compromise.",
"prompt": "In ECDSA or EDDSA, this code snippet calls a cryptographic signing function with specified nonce or nonce derived from a fixed source, such that there is a non-negligible probability that the same nonce is used to sign different messages."
}
},
{
"schema_version": "1.0",
"name": "Signature Malleability Attack",
"description": "This vulnerability allows an attacker to create a second, **valid signature** for the same message by algebraically modifying an existing signature, **without possessing the private key**. The two signatures $(r, s)$ and $(r, s')$ are equally valid for the message. This flaw impacts protocols (e.g., blockchains) that use the signature as a unique transaction identifier or rely on one-time processing.\n\n**Common Implementation Causes:**\n1. **ECDSA Inversion:** In ECDSA, if the library does not enforce a canonical $s$ value (e.g., $s \\le n/2$), the signature $(r, s)$ can be transformed to a valid signature $(r, n-s)$ because $s \\equiv -s \\pmod n$. Both are mathematically valid, but $(r, n-s)$ is a distinct representation.\n2. **Parameter Non-Checks:** Failing to strictly check that $r$ and $s$ are within the defined bounds of the curve's order $n$ (i.e., $1 \\le r, s < n$) can introduce additional, non-standard valid signatures.",
"audit": {
"description": "This resource identifies code snippets performing Elliptic Curve Digital Signature Algorithm (ECDSA) signature verification. These are potential locations for signature malleability vulnerabilities if the code accepts non-canonical signatures (e.g., both 's' and 'n-s' are considered valid) or fails to validate signature parameters properly.",
"prompt": "This code performs Elliptic Curve Digital Signature Algorithm (ECDSA) signature verification. It likely uses cryptographic libraries (such as 'ecdsa', 'cryptography', 'pycryptodome', 'libsecp256k1') to validate a digital signature (r, s) against a message and a public key."
}
},
{
"schema_version": "1.0",
"name": "Unverified Public Key in EdDSA Signature Generation",
"description": "This vulnerability occurs in EdDSA implementations that accept the public key as a distinct parameter in the signing function, rather than deriving it internally from the private key. The root cause is the failure to cryptographically verify that the provided public key corresponds to the provided private key before using it in the signature calculation.\n\nSecurity Scenario: An attacker tricks a victim into signing the exact same message twice with the same private key. For the first signature, the correct public key is used. For the second signature, the attacker supplies a different, maliciously crafted public key to the signing function. This is sometimes referred to as a 'Fake Public Key' or 'Double Public Key' attack.\n\nImplementation Flaw: Certain cryptographic libraries, for performance reasons, expose a signing API such as `sign(private_key, public_key, message)`. The EdDSA signature algorithm computes a challenge hash over the nonce-point `R`, the public key `A`, and the message `M`, as `H(R, A, M)`. A vulnerable implementation directly uses the `public_key` parameter `A` in this hash. The attack proceeds as follows:\n\n1. **First Signature (Legitimate):** The victim signs message `M` with private key `s` and correct public key `A`. The resulting signature is `(R, S)`, where `S = r + H(R, A, M) * s mod L`. The nonce `r` in EdDSA is deterministic, derived from the private key and the message.\n2. **Second Signature (Malicious):** The attacker induces the victim to sign the *same message* `M` with the *same private key* `s`, but injects a fake public key `A'`. Since `M` and `s` are unchanged, the deterministic nonce `r` and its corresponding point `R` are identical to the first signature. The new signature is `(R, S')`, where `S' = r + H(R, A', M) * s mod L`.\n\nSecurity Consequence: The attacker now possesses two equations with two unknowns (`r` and `s`). By subtracting the second equation from the first, the unknown nonce `r` is eliminated: `S - S' = s * (H(R, A, M) - H(R, A', M)) mod L`. Since every other value in this equation is known, the attacker can solve for the private key scalar `s`, leading to a complete and permanent compromise of the private key. A secure implementation must either derive the public key from the private key internally or explicitly verify that the provided public key `A` satisfies `A = sB`, where `B` is the curve's base point.",
"audit": {
"description": "This resource flags EdDSA signing functions that accept the public key as a separate parameter. This is a prerequisite for a 'Fake Public Key' attack, where supplying a malicious public key can lead to private key disclosure if the implementation doesn't verify the correspondence between the private and public keys.",
"prompt": "This code implements an EdDSA signing function that accepts the public key as a distinct parameter alongside the private key and message. This public key is then used directly within the signature generation process, such as being included in the data that is hashed to compute the signature's challenge component."
}
},
{
"schema_version": "1.0",
"name": "Use of Cryptographically Broken or Weakened Hash Functions",
"description": "A vulnerability where the application relies on hash algorithms with known cryptographic weaknesses for security-critical functions like integrity verification or digital signatures. The root cause is the selection of algorithms whose collision resistance or preimage resistance has been practically compromised.\n\nSecurity Scenario: An application uses a weak hash function for generating file checksums, signing digital certificates or tokens (e.g., JWTs), or deriving keys. This allows an attacker to create malicious data that is accepted as authentic.\n\nImplementation Variants:\n1. **MD5**: Its collision resistance is completely broken. An attacker can generate two distinct inputs (e.g., a benign executable and a malicious one) that produce the same MD5 hash in seconds. This bypasses integrity checks and allows for the substitution of malicious content. It is also vulnerable to length extension attacks when used in MAC constructions.\n2. **SHA-1**: Practical collision attacks (e.g., the SHAttered attack) have been demonstrated, enabling the creation of two different documents (like PDF files or TLS certificates) with the same SHA-1 hash. This makes it unsuitable for any application requiring collision resistance, especially digital signatures.\n\nConsequence: Loss of data integrity, signature forgery, and authentication bypass. Use of these algorithms in any security context is considered a high-severity flaw. Relevant APIs include `java.security.MessageDigest.getInstance(\"MD5\")` or `crypto.createHash('sha1')`.",
"audit": {
"description": "This resource flags all code snippets that use weak cryptographic hash functions like MD5 or SHA-1. These algorithms have known vulnerabilities and are not secure for applications like integrity verification, password storage, or digital signatures.",
"prompt": "This code uses the weak cryptographic hash algorithms MD5 or SHA-1. This includes direct function calls (e.g., `md5()`, `hashlib.sha1()`) or instantiations where 'MD5' or 'SHA1' is used as an identifier or string literal (e.g., `crypto.createHash('md5')`, `MessageDigest.getInstance(\"SHA1\")`)."
}
},
{
"schema_version": "1.0",
"name": "Use of Insecure Symmetric Ciphers with Small Key or Block Sizes",
"description": "A vulnerability where the application encrypts data using symmetric ciphers that are vulnerable due to insufficient key length, small block size, or internal statistical flaws. The root cause is the use of legacy algorithms that can no longer withstand attacks from modern computing resources.\n\nSecurity Scenario: A system encrypts sensitive data-in-transit or data-at-rest, such as session cookies, user credentials, or backups, using an outdated cipher. An attacker who can observe the ciphertext can potentially decrypt it.\n\nImplementation Variants:\n1. **DES**: Uses a 56-bit key, which is vulnerable to exhaustive key search (brute-force) attacks. Modern hardware can recover a DES key in hours or less, leading to a total loss of confidentiality.\n2. **3DES (Triple DES) and Blowfish**: These ciphers use a 64-bit block size. When encrypting large amounts of data (around 32 GB) with a single key, birthday-bound collisions in ciphertext blocks become highly probable. The \"Sweet32\" attack exploits this to recover small fragments of plaintext, such as authentication tokens or passwords from an encrypted session.\n\nConsequence: Disclosure of sensitive information. An attacker can decrypt confidential data, leading to session hijacking, data breaches, or further system compromise. Relevant APIs include any call specifying ciphers like `DES`, `TripleDES`, or `Blowfish`.",
"audit": {
"description": "This resource flags code snippets that utilize weak symmetric encryption algorithms such as DES, 3DES (Triple DES), or Blowfish. These ciphers are considered insecure due to small key sizes or block sizes, making them vulnerable to attacks like brute-forcing or birthday attacks (e.g., Sweet32), which can lead to the decryption of sensitive data.",
"prompt": "This code snippet uses or configures a weak symmetric encryption algorithm, specifically DES, 3DES (Triple DES), or Blowfish, in cryptography-related API calls."
}
},
{
"schema_version": "1.0",
"name": "Use of Small Constant or Low-Entropy Nonces",
"description": "A simple but effective vulnerability occurs when developers use small, predictable integers (e.g., k=1, 2, 9, 1337) as the signature nonce. While these fall under the general category of biased nonces, the values are often so small that the private key can be recovered by simple brute-forcing the most likely small nonce candidates and checking if the resulting calculated private key matches the public key. This is typically attributed to developer oversight, using test/placeholder values in production, or highly simplistic custom signature generation logic.",
"audit": {
"description": "This resource flags all code snippets where a cryptographic signature is generated using a small, predictable integer constant as the nonce (often named 'k'). This is a severe vulnerability as it allows for the recovery of the private key by brute-forcing a small range of possible nonces.",
"prompt": "This code performs a cryptographic signing operation and explicitly provides a small, constant integer (e.g., 1, 2, 1337) as the nonce (the parameter is often named 'k'). This includes calls to signing functions from common cryptography libraries (like `ecdsa`, `cryptography`, `pycoin`, `libsecp256k1`) or custom implementations of signing algorithms where the nonce is not generated randomly."
}
},
{
"schema_version": "1.0",
"name": "Use of Statistically Flawed Stream Ciphers",
"description": "A vulnerability where the application uses a stream cipher, most notably RC4, that produces a keystream with detectable statistical biases. The root cause is a flaw in the cipher's pseudo-random generation algorithm (PRGA) that makes its output distinguishable from true randomness.\n\nSecurity Scenario: An application, such as a TLS server or a custom network protocol, uses RC4 to encrypt communications. An attacker who can capture a sufficient quantity of encrypted traffic can leverage these statistical biases to recover portions of the plaintext.\n\nImplementation Details: The initial bytes of the RC4 keystream are particularly biased. In protocols like TLS, where the same plaintext is often sent at the beginning of many sessions (e.g., HTTP headers), an attacker can mount a practical plaintext recovery attack by analyzing many different ciphertexts. The use of RC3 is also a critical flaw, as it was an early, broken design that indicates the use of an extremely antiquated and insecure library.\n\nConsequence: Loss of confidentiality. An attacker can decrypt sensitive information from encrypted streams, compromising user privacy and security. Any use of `RC4`, `ARC4`, or `RC3` in a cryptographic library is a high-severity vulnerability.",
"audit": {
"description": "This resource flags all code snippets that use or configure insecure stream ciphers, specifically RC4, ARC4, or RC3. The use of these ciphers is deprecated and can lead to the compromise of encrypted data due to statistical weaknesses.",
"prompt": "This code uses, configures, or references an insecure stream cipher algorithm, specifically RC4, ARC4, or RC3."
}
}
]