# Flask (Python) Security Security vulnerabilities and detection rules for flask framework. 63 rules across 49 CWE categories. - Total rules: 63 - CWE categories: 49 - Critical rules: 10 ## CWEs - **CWE-200**: Exposure of Sensitive Information to an Unauthorized Actor - **CWE-94**: Improper Control of Generation of Code ('Code Injection') - **CWE-942**: Permissive Cross-domain Policy with Untrusted Domains - **CWE-269**: Improper Privilege Management - **CWE-502**: Deserialization of Untrusted Data - **CWE-614**: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute - **CWE-639**: Authorization Bypass Through User-Controlled Key - **CWE-778**: Insufficient Logging - **CWE-16**: Configuration - **CWE-20**: Improper Input Validation - **CWE-22**: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') - **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-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-209**: Generation of Error Message Containing Sensitive Information - **CWE-235**: Improper Handling of Extra Parameters - **CWE-284**: Improper Access Control - **CWE-287**: Improper Authentication - **CWE-326**: Inadequate Encryption Strength - **CWE-327**: Use of a Broken or Risky Cryptographic Algorithm - **CWE-347**: Improper Verification of Cryptographic Signature - **CWE-384**: Session Fixation - **CWE-391**: Unchecked Error Condition - **CWE-396**: Declaration of Catch for Generic Exception - **CWE-400**: Uncontrolled Resource Consumption - **CWE-425**: Direct Request ('Forced Browsing') - **CWE-434**: Unrestricted Upload of File with Dangerous Type - **CWE-444**: Inconsistent Interpretation of HTTP Requests ('HTTP Request Smuggling') - **CWE-489**: Active Debug Code - **CWE-547**: Use of Hard-coded, Security-relevant Constants - **CWE-598**: Use of GET Request Method With Sensitive Query Strings - **CWE-601**: URL Redirection to Untrusted Site ('Open Redirect') - **CWE-611**: Improper Restriction of XML External Entity Reference - **CWE-640**: Weak Password Recovery Mechanism for Forgotten Password - **CWE-755**: Improper Handling of Exceptional Conditions - **CWE-770**: Allocation of Resources Without Limits or Throttling - **CWE-798**: Use of Hard-coded Credentials - **CWE-807**: Reliance on Untrusted Inputs in a Security Decision - **CWE-829**: Inclusion of Functionality from Untrusted Control Sphere - **CWE-840**: Business Logic Errors - **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 ## Rules - **Flask CORS Misconfiguration** [MEDIUM]: Detects overly permissive CORS configuration in Flask applications using flask-cors. Allowing all origins (*) with credentials enabled can lead to cross-site request forgery and data theft. - **Flask Debug Mode in Production** [HIGH]: Detects Flask applications running with debug mode enabled. Debug mode exposes sensitive information, allows code execution through the interactive debugger, and should NEVER be enabled in production. - **Flask Insecure Session Configuration** [MEDIUM]: Detects insecure Flask session configuration that can lead to session hijacking or tampering. Sessions should use secure cookies and strong secret keys. - **Authentication Bypass Vulnerability** [CRITICAL]: Detects authentication checks that can be bypassed due to missing return statements or weak boolean logic. - **Avoid print() when logging module exists** [low]: Detects print() calls when the logging module is used in the codebase. CAPABILITY-GATED: This rule only fires when Python's logging module or a logging library (loguru, structlog) is detected. If the project only uses print(), that's an architectural choice - not a violation. When logging infrastructure exists, print() calls are outliers that should be reviewed: - They bypass structured logging - They don't respect log levels - They can't be easily filtered in production - They go to stdout, not stderr (may interfere with output parsing) - **Overly Broad Exception Handler** [LOW]: Detects overly broad exception handlers (bare except: or except BaseException) that catch system exceptions like KeyboardInterrupt, SystemExit, which should not be caught in normal error handling. - **Business Logic Bypass** [HIGH]: Detects client-controlled business-critical values (price, quantity, discount) flowing to payment or business operations without server-side validation. - **Business Logic Input Validation** [MEDIUM]: Detects business-critical input values (discount, refund, quantity, price) that are used in operations without proper validation. Missing validation can lead to financial fraud, inventory errors, or business logic bypass. - **HTTP Cache Poisoning** [MEDIUM]: Detects cache key construction using unsanitized user input. Cache poisoning occurs when attackers manipulate cache keys to serve malicious content to other users or bypass security controls. - **Missing Clickjacking Protection** [MEDIUM]: Detects missing clickjacking protection headers (X-Frame-Options or CSP frame-ancestors). Without these headers, attackers can embed your site in iframes to perform clickjacking attacks, tricking users into clicking malicious elements. - **Client-Controlled Authorization Data** [CRITICAL]: Detects authorization decisions based on client-controllable data such as cookies, query parameters, or form fields. - **Code Injection via eval/exec** [CRITICAL]: Detects untrusted user input flowing into code evaluation functions (eval, exec, compile). - **OS Command Injection** [CRITICAL]: Detects untrusted user input flowing into operating system command execution functions without proper sanitization. - **CORS Misconfiguration** [MEDIUM]: Detects overly permissive CORS (Cross-Origin Resource Sharing) configurations that allow any origin (*) with credentials, or reflect the Origin header without validation. This can expose sensitive data to malicious sites. - **CORS Regex Bypass Vulnerability** [HIGH]: Detects CORS implementations using weak regex patterns, prefix/suffix matching, or substring checks that can be bypassed by attackers to allow unauthorized cross-origin access from malicious domains. Common bypass patterns: 1. Unanchored regex: r"https://.*\.example\.com" matches "https://evil.com/.example.com" 2. Unescaped dots: r"https://app.trusted.com" matches "https://appXtrusted.com" 3. Prefix matching: startswith("https://trusted.com") allows "https://trusted.com.evil.com" 4. Suffix matching: endswith(".trusted.com") can be abused with subdomain takeover 5. Contains check: "trusted.com" in origin matches "nottrusted.com" - **Default Privilege Assignment in User Creation** [HIGH]: Detects user creation flows that assign elevated privileges by default. - **Empty Exception Handler** [MEDIUM]: Detects empty except blocks that silently swallow exceptions. This can hide security-critical errors, authentication failures, or data validation issues. - **Error Message Information Disclosure** [MEDIUM]: Detects error messages that expose sensitive implementation details like stack traces, database errors, file paths, or internal system information. This information can help attackers understand the system architecture. - **Exposed Administrative Endpoint** [HIGH]: Detects administrative endpoints (admin, debug, internal, system) that lack proper authentication or authorization checks. These endpoints should require admin privileges and be protected from public access. - **Security Check Failing Open** [HIGH]: Detects security checks (authentication, authorization, validation) inside try/except blocks that return success on exception. This causes the system to "fail open" - granting access when security checks fail. - **Hardcoded Credentials** [HIGH]: Detects hardcoded passwords, API keys, tokens, and other credentials in source code. Credentials should be stored in environment variables or secure vaults. - **Hardcoded Development URLs** [LOW]: Detects hardcoded development URLs such as localhost or 127.0.0.1 in production code. This indicates: 1. Configuration management issues 2. Potential production deployment problems 3. Leftover development/test code 4. API endpoints pointing to local services Development URLs should be configurable via environment variables. - **HTTP Header Injection** [HIGH]: Detects user input flowing into HTTP response headers without CRLF sanitization. - **Insecure Direct Object Reference (IDOR)** [HIGH]: Detects database object access using user-provided IDs without ownership verification. - **Potential IDOR - Generic Data Access** [MEDIUM]: Detects route parameters flowing to generic data access without visible ownership verification. - **Information Disclosure** [MEDIUM]: Detects information disclosure vulnerabilities: debug mode enabled, exposing stack traces, returning detailed error messages, or leaking sensitive data. - **Insecure Cookie Configuration** [MEDIUM]: Detects cookies set without httpOnly, secure, or sameSite flags. Missing flags make cookies vulnerable to XSS, MITM, and CSRF attacks. - **Insecure File Upload** [HIGH]: Detects file uploads without proper validation of file type, size, or content. Malicious uploads can lead to code execution, path traversal, or denial of service. Always validate file extensions, MIME types, content, and size. - **Insufficient Security Event Logging** [MEDIUM]: Detects security-critical operations (authentication, authorization failures, admin actions) without proper logging. Insufficient logging prevents detection of attacks and hinders incident response. This rule only triggers on files containing security-critical patterns like: - Authentication (login, logout, authenticate, check_password) - Authorization decorators (@login_required, @permission_required) - Privilege checks (is_staff, is_superuser, is_admin, has_perm) - Session management with auth/user/token data NOTE: This rule only applies to authentication/authorization related code. Not every view needs audit logging - focus on security-critical operations. - **JWT Algorithm Confusion Attack** [CRITICAL]: Detects JWT tokens decoded without algorithm verification or accepting the 'none' algorithm, allowing token forgery. - **JWT Signed with Weak Secret** [HIGH]: Detects JWT tokens signed with weak, hardcoded, or default secret keys that can be brute-forced. - **LDAP Injection** [HIGH]: Detects LDAP queries constructed with unsanitized user input. - **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 NOTE: Rate limiting is covered separately by framework-specific rate-limiting rules. - **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 - **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, exec, compile) - Command execution (os.system, subprocess) - SQL queries (cursor.execute, raw queries) - Template rendering (Jinja2, Django templates) - File operations (open, write, unlink) - Deserialization (pickle, yaml.load) - **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 - **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 source code or logs - Model weights exposed via insecure endpoints - Model extraction attacks via unrestricted API access - Insecure model serialization and storage - **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 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 pickle for model serialization (RCE risk) - trust_remote_code=True in HuggingFace - Compromised training data sources - Third-party plugins without verification - **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 - **Log Injection / Log Forging** [MEDIUM]: Detects user input flowing directly into log messages without sanitization. - **Missing API Rate Limiting** [MEDIUM]: Detects API endpoints without rate limiting. Unprotected endpoints are vulnerable to brute force attacks, credential stuffing, and denial of service. Always implement rate limiting on authentication, expensive operations, and public APIs. - **Missing Security Headers** [MEDIUM]: Detects missing security headers like HSTS, X-Content-Type-Options, X-XSS-Protection, Referrer-Policy, and Permissions-Policy. These headers provide defense-in-depth against various attacks. NOTE: This rule only applies to app setup files (settings.py, middleware, app.py, etc.). Security headers should be configured at the application level, not in individual view handlers. - **NoSQL Injection** [HIGH]: Detects untrusted user input being used in NoSQL queries without proper validation. - **Open Redirect** [MEDIUM]: Detects unvalidated redirects using user input. - **HTTP Parameter Pollution** [MEDIUM]: Detects handling of duplicate HTTP parameters without proper validation. - **Path Traversal / Directory Traversal** [HIGH]: Detects untrusted user input being used in file system operations without proper validation. - **Missing Role/Permission Checks** [HIGH]: Detects privileged operations like role modification without verifying user permissions. - **AI Prompt Injection** [HIGH]: Detects untrusted user input flowing directly into AI/LLM prompts without sanitization. - **Sensitive Field Exposure in API Response** [CRITICAL]: Detects when sensitive data fields (passwords, tokens, secrets) are exposed through API endpoint responses. This commonly happens when: 1. Returning user dictionaries with sensitive fields 2. Serializing ORM objects without excluding sensitive fields 3. Including sensitive fields in JSON responses 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) - **Server Information Disclosure** [LOW]: Detects server configuration that exposes version information, framework details, or other implementation details through HTTP headers. This information helps attackers identify known vulnerabilities in specific versions. - **Session Fixation Vulnerability** [HIGH]: Detects missing session regeneration after authentication, which enables session fixation attacks. Session fixation is a serious authentication vulnerability where an attacker forces a victim to use a session ID that the attacker already knows. The attack works like this: 1. Attacker obtains a valid session ID (e.g., by visiting the login page) 2. Attacker tricks victim into authenticating with that session ID (via URL, cookie injection, etc.) 3. Victim logs in, and the pre-known session ID becomes authenticated 4. Attacker uses the same session ID to hijack the victim's authenticated session Why this matters: - Attackers can gain full access to victim accounts without knowing credentials - Session tokens are often long-lived, giving attackers extended access windows - The attack is invisible to the victim who authenticated normally - Multi-factor authentication may be bypassed since attacker rides on legitimate auth Always regenerate session IDs immediately after successful authentication to invalidate any pre-existing session tokens an attacker might possess. - **SQL Injection via Database Queries** [CRITICAL]: Detects untrusted user input flowing into SQL database queries without proper parameterization. - **Server-Side Request Forgery (SSRF)** [HIGH]: Detects user input controlling URLs in HTTP requests, allowing requests to arbitrary destinations including internal services and cloud metadata endpoints. - **Server-Side Template Injection (SSTI)** [CRITICAL]: Detects user input used directly in template rendering, allowing arbitrary code execution. - **Sensitive Tokens in URL Parameters** [HIGH]: Detects sensitive tokens, API keys, or credentials being passed as URL query parameters. URLs are logged by browsers, proxies, and servers, exposing secrets. Use HTTP headers (Authorization) or request body instead. - **Unsafe Deserialization** [CRITICAL]: Detects untrusted user input being deserialized using unsafe methods like pickle.loads() or yaml.load(). - **Weak Cryptographic Algorithm** [MEDIUM]: Detects use of weak or deprecated cryptographic algorithms like MD5, SHA-1, DES, or RC4. Use modern algorithms like SHA-256, SHA-3, AES, or ChaCha20. - **Weak Password Hashing Algorithm** [HIGH]: Detects use of weak password hashing algorithms like MD5 or SHA-1 instead of bcrypt, argon2, or PBKDF2. - **Weak Password Reset Token** [HIGH]: Detects password reset tokens generated using weak or predictable methods like timestamps or non-cryptographic random. - **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: ```python # User controls 'endpoint' from request endpoint = request.form.get('webhook_url') # Server sends its internal API key to attacker-controlled URL requests.post(endpoint, headers={'X-API-Key': os.environ['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) in Templates** [HIGH]: Detects untrusted user input being rendered in HTML responses without proper escaping. - **XML External Entity (XXE) Injection** [HIGH]: Detects XML parsing with external entity processing enabled. XXE attacks allow attackers to read local files, perform SSRF, or cause denial of service. Always disable external entity processing when parsing untrusted XML.