# fastapi (Python) Security Rules 61 detection rules for fastapi framework in Python - Total rules: 61 - CWE coverage: 48 ## CRITICAL (9) - **Authentication Bypass Vulnerability**: Detects authentication checks that can be bypassed due to missing return statements or weak boolean logic. - **Client-Controlled Authorization Data**: Detects authorization decisions based on client-controllable data such as cookies, query parameters, or form fields. - **Code Injection via eval/exec**: Detects untrusted user input flowing into code evaluation functions (eval, exec, compile). - **OS Command Injection**: Detects untrusted user input flowing into operating system command execution functions without proper sanitization. - **JWT Algorithm Confusion Attack**: Detects JWT tokens decoded without algorithm verification or accepting the 'none' algorithm, allowing token forgery. - **Sensitive Field Exposure in API Response**: 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) - **SQL Injection via Database Queries**: Detects untrusted user input flowing into SQL database queries without proper parameterization. - **Unsafe Deserialization**: Detects untrusted user input being deserialized using unsafe methods like pickle.loads() or yaml.load(). - **Credential Exfiltration via User-Controlled Endpoint**: 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. ## HIGH (30) - **FastAPI JWT Security Issues**: Detects JWT security issues in FastAPI applications including: - Weak or hardcoded secrets - Missing algorithm verification - Insufficient token validation - Insecure token storage patterns - **FastAPI Endpoint Missing Authentication**: Detects FastAPI endpoints that perform sensitive operations without authentication via Depends() dependency injection. - **Business Logic Bypass**: Detects client-controlled business-critical values (price, quantity, discount) flowing to payment or business operations without server-side validation. - **CORS Regex Bypass Vulnerability**: 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**: Detects user creation flows that assign elevated privileges by default. - **Exposed Administrative Endpoint**: 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**: 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**: Detects hardcoded passwords, API keys, tokens, and other credentials in source code. Credentials should be stored in environment variables or secure vaults. - **HTTP Header Injection**: Detects user input flowing into HTTP response headers without CRLF sanitization. - **Insecure Direct Object Reference (IDOR)**: Detects database object access using user-provided IDs without ownership verification. - **Insecure File Upload**: 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. - **JWT Signed with Weak Secret**: Detects JWT tokens signed with weak, hardcoded, or default secret keys that can be brute-forced. - **LDAP Injection**: Detects LDAP queries constructed with unsanitized user input. - **LLM Excessive Agency**: 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**: 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**: 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**: 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**: 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**: 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**: 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 - **NoSQL Injection**: Detects untrusted user input being used in NoSQL queries without proper validation. - **Path Traversal / Directory Traversal**: Detects untrusted user input being used in file system operations without proper validation. - **Missing Role/Permission Checks**: Detects privileged operations like role modification without verifying user permissions. - **AI Prompt Injection**: Detects untrusted user input flowing directly into AI/LLM prompts without sanitization. - **Server-Side Request Forgery (SSRF)**: Detects user input controlling URLs in HTTP requests, allowing requests to arbitrary destinations including internal services and cloud metadata endpoints. - **Sensitive Tokens in URL Parameters**: 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. - **Weak Password Hashing Algorithm**: Detects use of weak password hashing algorithms like MD5 or SHA-1 instead of bcrypt, argon2, or PBKDF2. - **Weak Password Reset Token**: Detects password reset tokens generated using weak or predictable methods like timestamps or non-cryptographic random. - **Cross-Site Scripting (XSS) in Templates**: Detects untrusted user input being rendered in HTML responses without proper escaping. - **XML External Entity (XXE) Injection**: 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. ## MEDIUM (18) - **FastAPI CORS Misconfiguration**: Detects overly permissive CORS configuration in FastAPI applications. Allowing all origins (*) with credentials enabled can lead to CSRF and data theft. - **FastAPI Missing Request Validation**: Detects FastAPI endpoints that accept raw Request objects instead of Pydantic models. This bypasses FastAPI's automatic validation and can lead to type confusion and injection vulnerabilities. - **Business Logic Input Validation**: 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**: 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**: 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. - **CORS Misconfiguration**: 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. - **Empty Exception Handler**: Detects empty except blocks that silently swallow exceptions. This can hide security-critical errors, authentication failures, or data validation issues. - **Error Message Information Disclosure**: 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. - **Potential IDOR - Generic Data Access**: Detects route parameters flowing to generic data access without visible ownership verification. - **Insecure Cookie Configuration**: Detects cookies set without httpOnly, secure, or sameSite flags. Missing flags make cookies vulnerable to XSS, MITM, and CSRF attacks. - **Insufficient Security Event Logging**: 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. - **LLM Denial of Service**: 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. - **Log Injection / Log Forging**: Detects user input flowing directly into log messages without sanitization. - **Missing API Rate Limiting**: 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**: 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. - **Open Redirect**: Detects unvalidated redirects using user input. - **HTTP Parameter Pollution**: Detects handling of duplicate HTTP parameters without proper validation. - **Weak Cryptographic Algorithm**: 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. ## LOW (3) - **Overly Broad Exception Handler**: 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. - **Hardcoded Development URLs**: 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. - **Server Information Disclosure**: 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.