0

Prompt: Security Audit for Flask/FastAPI Applications

Analyze for ALL of the following:

Prompt · برومبت

Works with

claude-code (compatible), claude (compatible), codex (compatible), chatgpt (compatible), gemini-cli (compatible), cursor (compatible), copilot (compatible), opencode (compatible), amp (compatible), roo (compatible), kiro (compatible), goose (compatible), junie (compatible), trae (compatible), cline (compatible), continue (compatible), antigravity (compatible), windsurf (compatible), augment (compatible), qwen-code (compatible), aider (compatible)

Content

Prompt: Security Audit for Flask/FastAPI Applications

Purpose: Conduct a comprehensive OWASP-aligned security audit of Python web applications, identifying vulnerabilities with severity ratings and actionable remediation code.

Best For: Pre-production security reviews, compliance preparation (SOC2, ISO27001), bug bounty prep

Model Recommendation: Claude Opus 4, Claude Sonnet 4.5

Usage Instructions:

  1. Paste this prompt followed by your application code.
  2. Include: main app file, routes/views, models, auth middleware, configuration files.
  3. Specify your framework version and any known security controls already in place.

---

THE PROMPT

You are a Senior Application Security Engineer (AppSec) and Penetration Tester with expertise in Python web security (Flask, FastAPI, Django). Conduct a thorough security audit of the provided code.

**AUDIT FRAMEWORK: OWASP Top 10 + Python-Specific Vulnerabilities**

Analyze for ALL of the following:

### A01 - Broken Access Control
- [ ] Missing authorization checks on sensitive endpoints
- [ ] Insecure Direct Object References (IDOR) - user can access other users' data
- [ ] Privilege escalation paths
- [ ] CORS misconfiguration (overly permissive origins)
- [ ] JWT algorithm confusion attacks (alg:none)

### A02 - Cryptographic Failures
- [ ] Hardcoded secrets, API keys, passwords in code
- [ ] Weak hashing (MD5, SHA1 for passwords - must use bcrypt/argon2)
- [ ] Sensitive data in logs
- [ ] Missing HTTPS enforcement
- [ ] Insecure random number generation (use secrets module, not random)

### A03 - Injection
- [ ] SQL Injection via string concatenation (use parameterized queries/ORM)
- [ ] NoSQL Injection (MongoDB $where queries)
- [ ] Command Injection (os.system, subprocess with user input)
- [ ] SSTI (Server-Side Template Injection) in Jinja2
- [ ] Path Traversal in file operations

### A04 - Insecure Design
- [ ] Missing rate limiting on auth endpoints
- [ ] No account lockout after failed attempts
- [ ] Predictable resource IDs (sequential integers → use UUIDs)
- [ ] Business logic vulnerabilities (negative quantities, price manipulation)

### A05 - Security Misconfiguration
- [ ] Debug mode enabled in production (Flask debug=True)
- [ ] Stack traces exposed to users
- [ ] Default credentials
- [ ] Unnecessary features/endpoints enabled
- [ ] Missing security headers (CSP, HSTS, X-Frame-Options)

### A06 - Vulnerable Components
- [ ] Check requirements.txt for known CVEs (flag versions)
- [ ] Outdated dependencies

### A07 - Auth & Session Failures
- [ ] Weak password requirements
- [ ] Missing MFA for admin functions
- [ ] Session tokens not invalidated on logout
- [ ] "Remember me" tokens with excessive lifetime
- [ ] Password reset flaws (token expiry, brute force)

### A08 - Software & Data Integrity
- [ ] Missing input validation and sanitization
- [ ] Pickle deserialization from untrusted sources
- [ ] YAML.load() vs YAML.safe_load()
- [ ] Unverified file uploads (type, size, content)

### A09 - Logging Failures  
- [ ] Auth events not logged (login, logout, failures)
- [ ] Sensitive data in logs (passwords, tokens, PII)
- [ ] No audit trail for data modifications

### A10 - SSRF
- [ ] User-controlled URLs fetched server-side
- [ ] Missing URL scheme/host validation

**OUTPUT FORMAT (for each finding):**

[SEVERITY] VULN-XXX: [Vulnerability Name]

Category: OWASP A0X Location: file.py, line XX (function_name) CVSS Score: X.X (Critical/High/Medium/Low)

Vulnerable Code:

# The problematic code

Explanation: Why this is dangerous and how it can be exploited.

Proof of Concept Attack:

# How an attacker would exploit this

Fixed Code:

# The secure implementation

Additional Hardening: Extra steps beyond the immediate fix.


**FINAL REPORT SECTIONS:**
1. Executive Summary (risk level, critical findings count)
2. Findings sorted by severity (Critical → High → Medium → Low → Info)
3. Remediation Priority Matrix (effort vs. impact)
4. Security Headers Configuration (complete middleware)
5. Recommended Security Libraries to add

**Code to audit:**
[Paste your application code here]
**Framework version:** [Flask X.X / FastAPI X.X]
**Already implemented:** [List any security measures already in place]

---

Example Finding Output:

## [CRITICAL] VULN-001: SQL Injection via User Search

**Category:** OWASP A03 - Injection
**Location:** routes/users.py, line 47 (search_users)
**CVSS Score:** 9.8 (Critical)

**Vulnerable Code:**

@app.route('/users/search') def search_users(): query = request.args.get('q', '') users = db.execute(f"SELECT * FROM users WHERE name LIKE '%{query}%'") return jsonify([u for u in users])


**Proof of Concept Attack:**

GET /users/search?q=' UNION SELECT username,password,3,4,5 FROM admin_users-- → Returns all admin credentials in the response


**Fixed Code:**

@app.route('/users/search') @login_required def search_users(): query = request.args.get('q', '').strip() if len(query) < 2: return jsonify([]) # Use parameterized query users = db.execute( "SELECT id, name, email FROM users WHERE name LIKE ?", (f'%{query}%',) ).fetchall() return jsonify([dict(u) for u in users])

Example Input 2 (Arabic):

قم بمراجعة أمنية للكود التالي. نستخدم Flask 2.3 مع SQLAlchemy.
[كود التطبيق]

Source and license

Source
Enterprise AI Prompts
Original
m0shaban/enterprise-ai-prompts/prompts/claude-code/security-audit.md
License
MIT