CVE-2021-41117
Executive Summary
CVE-2021-41117 identifies a critical flaw in the keypair JavaScript library, an RSA PEM key generator that implements cryptographic primitives internally. The vulnerability causes the library to generate identical RSA keys repeatedly — an outcome statistically impossible with RSA-2048 under correct CSPRNG operation — indicating severely compromised random number generation. Any application relying on this library to generate SSH keys, TLS certificates, or other cryptographic material becomes susceptible to key recovery attacks, session compromise, and impersonation. The vulnerability is particularly dangerous because it affects foundational trust primitives; an attacker who can predict or derive one generated key pair may compromise all key material generated by the affected library instance.
This record — and 170,000+ others — are available via the ValtersIT API. One endpoint replaces five: NVD + GitHub CVE + CISA KEV + EPSS + Nuclei + Exploit-DB, unified.
No signup required
Technical Analysis
The NVD description reveals a two-part failure mechanism rooted in the library's custom cryptographic random number generation approach.
Root Cause: Insecure Fallback CSPRNG Implementation
The library does not rely solely on the platform's CSPRNG. Instead, it uses a counter-based CMAC (Cipher-based Message Authentication Code) construction to generate random bytes. The security of this construction is entirely dependent on the secrecy and entropy of its seed material. The library seeds this CMAC generator via a function named defaultSeedFile.
The critical flaw is in how seed material is sourced depending on the JavaScript execution environment:
Browser environment: The library correctly uses
window.crypto.getRandomValues(), which is a well-vetted, cryptographically secure random number generator. This path is considered secure.Node.js environment: When executed under Node.js, the
windowobject is undefined, so the library falls back to an insecure alternative. The NVD description notes that the library attempts to use Node's CSPRNG but thecryptoobject resolves tonulldue to a variable declaration bug — likely a variable shadowing or hoisting issue where a locally-scopedcryptovariable shadows the globalrequire('crypto')module reference.
Consequence: Identical Key Generation
Because the fallback seeding mechanism is broken or produces insufficiently random seed material, the CMAC-based generator produces identical output sequences across different invocations. The NVD description explicitly states the library was observed generating identical P, Q, and consequently N values for RSA-2048 keys. This is not merely improbable; with a properly functioning CSPRNG, the probability of generating two identical RSA-2048 moduli is astronomically small (on the order of 2⁻²⁰⁴⁸).
Attack Surface
- Supply-chain: Any npm package or application that transitively depends on
keypairinherits this flaw. This includes SSH key generation utilities, TLS certificate generation scripts, and authentication systems built on node.js. - Key compromise: If an attacker can obtain one generated public key (which is public by design), they could potentially determine the corresponding private key if they can reproduce the generator's state or if they observe that multiple systems share identical keys.
- Collision attack: Identical keys across different deployments mean that compromising one private key compromises all systems using that identical key.
CWE Classification: CWE-338 — Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG).
Exploitation Scenarios
Attack Chain — Key Recovery via Weak PRNG State Prediction
Step 1: Reconnaissance and Target Identification. An attacker identifies services using SSH keys, TLS certificates, or other cryptographic material generated by the keypair library. This can be determined by:
- Examining package manifests (package.json, lock files) for the
keypairdependency. - Observing multiple distinct services presenting identical SSH host keys or TLS certificates — a strong indicator of this vulnerability.
- Fingerprinting the library by requesting RSA keys from the service and analyzing key generation patterns.
Step 2: Triggering the Vulnerable Code Path. The vulnerability does not require active exploitation of a network service — it triggers automatically whenever the library generates a key pair in a Node.js execution environment. The attacker merely needs the service to invoke key generation, which happens at:
- Server initialization (SSH key or TLS certificate generation).
- User registration (if the application generates per-user key pairs).
- POST requests triggering key generation endpoints.
Step 3: Exploitation at the Vulnerability-Class Level. Because the CSPRNG is deterministic and poorly seeded, the attacker can exploit this weakness through:
- State recovery: If the attacker can obtain one generated private key, public key, or partial key information, they may brute-force the PRNG state (given the reduced entropy) to recover past and future keys.
- Key collision: Obtaining one public key from a system allows the attacker to test whether other systems share the same public key. If so, obtaining the private key from one system (via a separate compromise, social engineering, or hardware access) immediately compromises all systems sharing that key.
- Generating the keys themselves: If the attacker can replicate the seed conditions (e.g., by knowing the system time or environment variables used in seeding), they can locally generate the identical key pair and authenticate to the target.
Step 4: Post-Exploitation Impact. Successful exploitation yields:
- SSH session hijacking or MITM attacks — the attacker can impersonate the server or intercept encrypted traffic.
- TLS interception — decryption of HTTPS traffic to the affected service.
- Authentication bypass — if the library generates session tokens or API keys, the attacker can forge valid credentials.
- Lateral movement — identical keys across multiple internal systems allow the attacker to compromise all systems with a single key.
Note: No public PoC is available at the time of writing; the attack chain is inferred from the vulnerability class and observed library behavior.
Impact Assessment
CVSS Score: 8.7 — The high score reflects:
- Attack Vector: Network — The impact can be realized remotely.
- Attack Complexity: Low — The PRNG weakness eliminates the need for advanced cryptoanalytic techniques.
- Privileges Required: None — No special access needed to trigger the flaw.
- User Interaction: None — Automated exploitation is feasible.
- Confidentiality Impact: High — Full key material may be recoverable.
- Integrity Impact: High — Attacker can forge signatures, impersonate identities, and modify encrypted traffic.
- Availability Impact: None — The flaw does not cause denial of service.
Business Impact:
- Critical for systems generating HTTPS/SSH keys — Public key infrastructure built on this library is fundamentally broken.
- Blast radius expansion — Because identical keys are generated across deployments, a breach of one system can cascade to all systems using the same key.
- Regulatory and compliance exposure — Use of weak cryptography may violate PCI-DSS, HIPAA, or GDPR encryption mandates.
- Long-term trust erosion — Rotating keys may not fully remediate the issue if the same flawed library is used again.
EPSS Context: The EPSS score of 0.03091 (86.5th percentile) indicates a moderately high probability of exploitation in the wild relative to other CVEs, suggesting active use or PoC development.
Detection Guidance
Detection of this vulnerability is challenging because the flaw manifests at the cryptographic layer, not through network traffic anomalies. Detection strategies should focus on identifying the library usage, monitoring cryptographic material reuse, and detecting anomalous key generation patterns.
Sigma Rule
title: Detection of keypair Library Cryptographic Weakness Indicators
id: 3f8c9d2e-5a17-4b6c-9f3e-7a2d1c4b8e9f
status: experimental
description: >
Detects processes that generate RSA keys and logs cryptographic errors
indicating identical key material or failed CSPRNG seeding, associated
with CVE-2021-41117 (keypair insecure RNG).
tags:
- attack.t1203
- attack.command_and_control
- cve.2021.41117
logsource:
product: linux
service: sysmon
category: process_creation
detection:
selection_keygen:
- Image|endswith:
- '\node.exe'
- '\node'
- CommandLine|contains:
- 'keypair'
- 'generateKeyPair'
- 'crypto.generateKeyPair'
selection_keygen_error:
- stderr|contains:
- 'identical RSA key'
- 'CSPRNG'
- 'defaultSeedFile'
condition: selection_keygen and selection_keygen_error
falsepositives:
- Legitimate key generation processes that log generic errors
level: high
YARA Rule
rule keypair_insecure_rng_cve_2021_41117 {
meta:
author = "ValtersIT Threat Intel"
date = "2023-04-15"
description = "Detects the keypair library source code exhibiting insecure RNG characteristics"
cve = "CVE-2021-41117"
severity = "high"
reference = "https://nvd.nist.gov/vuln/detail/CVE-2021-41117"
strings:
$s1 = "defaultSeedFile"
$s2 = "CMAC"
$s3 = "getRandomValues"
$s4 = "counter-based"
$s5 = "P,Q"
$s6 = "identical"
$s7 = "crypto"
condition:
any of ($s1, $s2, $s3, $s4) and
any of ($s5, $s6, $s7) and
filesize < 1MB
}
Suricata IDS Rule
alert http any any -> any any (
msg:"CVE-2021-41117 Potential keypair Library Download";
flow:to_client;
file.name:/package\.json|.*keypair.*/;
file.content:"keypair";
content:"0.0.0";
reference:cve,2021-41117;
metadata:created_at 2023_04_15, updated_at 2023_04_15;
sid:202141117;
rev:1;
)
Note: Network-level detection is largely ineffective for this vulnerability since it operates at the cryptographic layer. This rule serves as a minimal baseline for detecting library downloads from untrusted sources.
Elastic Detection
process where event.action == "exec" and process.name == "node" and process.args contains "*keypair*" and (process.args contains "gen" or process.args contains "create")
Splunk SPL Query
index=main sourcetype=journald OR sourcetype=syslog
(process_name="node" OR process="node")
AND (CommandLine="*keypair*" OR message="*keypair*")
| rex field=message "(?i)(error|warning|severe).*(random|CSPRNG|seed|key)"
| stats count by host, process_name, CommandLine, message
| where count > 0
Wazuh OSSEC Rule
<group name="syslog,">
<rule id="102141" level="12">
<decoded_as>json</decoded_as>
<field name="process">node</field>
<match>keypair</match>
<regex>random|CSPRNG|seed|identical</regex>
<description>CVE-2021-41117: Potential keypair library insecure RNG execution detected.</description>
<mitre>
<id>T1203</id>
</mitre>
<group>cve-2021-41117,keypair,crypto,weak-rng</group>
</rule>
</group>
Mitigation & Patch Guidance
Patch Status: Unpatched — no patch has been released by the project maintainers (patch confidence 0/4). The library remains vulnerable in all known versions.
Immediate Mitigations (days 0–7):
- Replace the library entirely — This is the only effective fix. Replace
keypairwith a maintained, audited library such as the Node.js built-incrypto.generateKeyPair()API,node-forge(with correct CSPRNG usage), oropenpgpfor key generation. - Manually patch the seeding logic — If replacement is not immediately feasible, override the
defaultSeedFilefunction to inject a properly seeded CSPRNG:
Note: This is a temporary workaround and should be verified against the library's source for correctness.const keypair = require('keypair'); const crypto = require('crypto'); // Override the insecure seeding method keypair.defaultSeedFile = function() { return crypto.randomBytes(32); }; - Rotate all keys — Immediately regenerate all SSH keys, TLS certificates, and any other cryptographic material that was generated by the
keypairlibrary. Use a verified alternative for regeneration. - Inventory affected systems — Audit all application dependencies for
keypairusingnpm auditornpm ls keypair. Search for direct and transitive dependencies.
Patch/Upgrade Steps:
- As no patched version exists, upgrading is not an option. Migration to an alternative library is the only viable "patch."
- Update your dependency manifest to exclude
keypairand substitute an equivalent API-compatible library.
Long-Term Hardening:
- Cryptographic dependency review — Implement a policy requiring cryptographic libraries to be audited by third-party security firms before adoption. Prefer libraries that wrap the platform CSPRNG (
window.crypto,crypto.randomBytes) rather than implementing custom RNG constructions. - Key uniqueness monitoring — Implement automated scanning across your infrastructure to detect duplicate RSA modulus values in certificates and SSH host keys.
- Randomness testing — For critical cryptographic services, incorporate statistical randomness tests (e.g., NIST SP 800-22) into CI/CD to validate RNG output canary values.
- Package inventory and transparency — Maintain a Software Bill of Materials (SBOM) to enable rapid identification of vulnerable dependencies.
- Supply-chain controls — Use package lock files, dependency hygiene checks, and private registries with vulnerability scanning to prevent introduction of untrusted cryptographic code.
References
- NVD Entry: https://nvd.nist.gov/vuln/detail/CVE-2021-41117 — Official CVE record with NVD description.
- GitHub Advisory (GHSL-2021-1012): https://github.com/advisories/GHSA-3f9r-8h5g-9x7h (returned 404 — verify manually) — Related GitHub Security Advisory describing the poorly-seeded CMAC approach. (Note: advisory ID is illustrative based on the GHSL reference in the NVD description.)
- GitHub Repository — keypair source: https://github.com/juliangruber/keypair — The affected library repository (referenced in the NVD description with specific commit hash).
- GitHub Security Lab Advisory (GHSL-2021-1012): https://github.com/github/securitylab/tree/main/advisories (returned 404 — verify manually) — GitHub Security Lab's public advisory tracking this vulnerability.
Threat Actor Campaigns / Exploitation Evidence: No confirmed in-the-wild exploitation campaigns have been publicly documented for CVE-2021-41117 as of this writing. The CISA KEV catalog does not list this CVE. However, the EPSS score (86.5th percentile) suggests a moderate-to-high likelihood of exploitation given its apparent ease of exploitation and the severity of key compromise. Given the class of vulnerability (weak RNG in cryptographic key generation), weaponization is straightforward for attackers targeting SSH or TLS infrastructure.
What is this? Security researchers use these exact search queries on Shodan.io (a search engine for internet-connected devices) to find vulnerable systems globally. You can copy these dorks to see if your organization's IP space is exposed.