PromptBase
Upgrade
Close icon
General
Home
Marketplace
Create
Hire
Login
Chat
Sell
Explore

Prompt Details

Model
(v3)
Token size
581
Example input
[Language]: Python [Framework]: Flask [Level: Low/Medium/High/Critical]: Critical [Paste_Code_Here]: from flask import Flask, request import sqlite3 app = Flask(__name__) @app.route('/user_profile') def get_user(): user_id = request.args.get('id') conn = sqlite3.connect('users.db') cursor = conn.cursor() # ثغرة أمنية: دمج المدخلات مباشرة query = "SELECT * FROM users WHERE id = " + user_id cursor.execute(query) return str(cursor.fetchone())
Example output
# 🛡️ AI SECURITY AUDIT REPORT --- ## 1. Executive Summary - **Overall Risk Rating:** **CRITICAL** - **Language/Framework:** Python / Flask - **Key Findings:** A critical SQL injection vulnerability was identified that allows complete database compromise. The application directly concatenates user-supplied input into SQL queries without any sanitization or parameterization, exposing all database contents to attackers. --- ## 2. Vulnerability Breakdown | Vulnerability | Type | CVSS Score | Impact | | :--- | :--- | :--- | :--- | | SQL Injection | CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') | **9.8 (CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N)** | Full database compromise, potential data breach, unauthorized data manipulation, and possible remote code execution in certain configurations | --- ## 3. Deep Technical Analysis ### Issue: Critical SQL Injection via Direct String Concatenation - **Line(s) of Code:** Lines 7-10 ```python user_id = request.args.get('id') query = "SELECT * FROM users WHERE id = " + user_id cursor.execute(query) ``` - **Threat Vector:** An attacker can inject malicious SQL code through the `id` parameter. Since the application uses string concatenation to build the SQL query, any unsanitized user input becomes executable SQL code. Attack vectors include: - **Authentication bypass:** `?id=1 OR 1=1` would return all users - **Data exfiltration:** `?id=1 UNION SELECT username, password FROM users` would extract credentials - **Database modification:** `?id=1; DROP TABLE users; --` could delete tables (if multiple query execution is enabled) - **Time-based blind injection for data enumeration** - **Impact:** - **Data Breach:** Complete exposure of all database contents including user credentials, PII, and sensitive business data - **Data Integrity Compromise:** Unauthorized modification or deletion of critical data - **Potential RCE:** In certain database configurations (e.g., MySQL with `INTO OUTFILE`), attackers could write webshells to the server - **Lateral Movement:** Compromised database credentials may be reused across other services - **Compliance Violations:** GDPR, HIPAA, PCI-DSS non-compliance leading to regulatory penalties - **Additional Issues Identified:** 1. **No Error Handling:** Database errors are not caught, potentially leaking sensitive system information through stack traces 2. **Missing Input Validation:** No type checking, length validation, or allow-list validation 3. **Unclosed Database Connections:** The connection is never closed (`conn.close()` missing), leading to connection leaks 4. **No Authentication:** Endpoint lacks any authentication/authorization controls 5. **Unsafe Return:** Raw database output is returned directly, potentially exposing internal data structures --- ## 4. Remediation (The Secure Patch) ```python from flask import Flask, request, jsonify import sqlite3 import re from contextlib import contextmanager from functools import wraps app = Flask(__name__) # Security Configuration ALLOWED_IDS = re.compile(r'^[0-9]+$') # Only allow numeric IDs # Database connection management with context manager @contextmanager def get_db_connection(): """Secure database connection handler with automatic cleanup""" conn = None try: conn = sqlite3.connect('users.db') conn.row_factory = sqlite3.Row # Enable named column access yield conn except sqlite3.Error as e: app.logger.error(f"Database error: {e}") raise finally: if conn: conn.close() # Input validation decorator def validate_user_id(f): """Decorator to validate user ID parameter""" @wraps(f) def decorated_function(*args, **kwargs): user_id = request.args.get('id', '').strip() # Validate input: must exist and match allowed pattern if not user_id or not ALLOWED_IDS.match(user_id): return jsonify({ 'error': 'Invalid user ID format', 'message': 'User ID must be a positive integer' }), 400 # Convert to integer for type safety try: user_id_int = int(user_id) if user_id_int <= 0: raise ValueError return f(user_id_int, *args, **kwargs) except ValueError: return jsonify({ 'error': 'Invalid user ID', 'message': 'User ID must be a positive integer' }), 400 return decorated_function # Authentication middleware (to be implemented based on your auth system) def require_auth(f): """Decorator for authentication (simplified example)""" @wraps(f) def decorated_function(*args, **kwargs): # Implement proper authentication here # e.g., check JWT tokens, session cookies, API keys auth_header = request.headers.get('Authorization') if not auth_header: return jsonify({'error': 'Authentication required'}), 401 # Add your authentication logic here # For demonstration, assume auth passes return f(*args, **kwargs) return decorated_function @app.route('/user_profile') @require_auth # Add authentication @validate_user_id # Add input validation def get_user(user_id): """ Securely retrieve user profile by ID. Uses parameterized queries to prevent SQL injection. """ try: with get_db_connection() as conn: cursor = conn.cursor() # SECURE: Parameterized query prevents SQL injection query = "SELECT id, username, email, created_at FROM users WHERE id = ?" cursor.execute(query, (user_id,)) user = cursor.fetchone() if user is None: return jsonify({ 'error': 'User not found', 'message': f'No user exists with ID {user_id}' }), 404 # Convert Row to dictionary for safe JSON serialization user_data = dict(user) # Remove sensitive fields before returning sensitive_fields = ['password_hash', 'reset_token', 'api_key'] for field in sensitive_fields: user_data.pop(field, None) return jsonify({ 'status': 'success', 'data': user_data }), 200 except sqlite3.DatabaseError as e: app.logger.error(f"Database query failed: {e}", exc_info=True) return jsonify({ 'error': 'Database error', 'message': 'Unable to retrieve user data at this time' }), 500 except Exception as e: app.logger.error(f"Unexpected error: {e}", exc_info=True) return jsonify({ 'error': 'Internal server error', 'message': 'An unexpected error occurred' }), 500 # Health check endpoint for monitoring @app.route('/health') def health_check(): """Simple health check endpoint""" try: with get_db_connection() as conn: cursor = conn.cursor() cursor.execute("SELECT 1") cursor.fetchone() return jsonify({'status': 'healthy', 'database': 'connected'}), 200 except Exception as e: return jsonify({'status': 'unhealthy', 'error': str(e)}), 503 # Additional security headers middleware @app.after_request def add_security_headers(response): """Add security headers to all responses""" response.headers['X-Content-Type-Options'] = 'nosniff' response.headers['X-Frame-Options'] = 'DENY' response.headers['X-XSS-Protection'] = '1; mode=block' response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains' return response if __name__ == '__main__': # Never run with debug=True in production app.run(host='0.0.0.0', port=5000, debug=False) ``` --- ## 5. Security Improvements Summary ### Key Fixes Applied: 1. **SQL Injection Prevention:** Replaced string concatenation with parameterized queries (using `?` placeholders) 2. **Input Validation:** Implemented strict allow-list validation using regex to ensure only numeric IDs are accepted 3. **Database Connection Management:** Added context manager to ensure connections are properly closed, preventing resource leaks 4. **Error Handling:** Implemented comprehensive error handling with logging (not exposing stack traces to clients) 5. **Authentication Placeholder:** Added decorator structure for implementing proper authentication 6. **Data Sanitization:** Removed sensitive fields before returning data to clients 7. **Security Headers:** Added response headers to mitigate XSS, clickjacking, and MIME-type sniffing 8. **JSON Responses:** Standardized to JSON format with proper HTTP status codes for better security and API usability 9. **Logging:** Added structured logging for security monitoring and incident response ### Additional Recommendations: - **Implement Rate Limiting:** Use Flask-Limiter to prevent brute-force attacks - **Add Request Validation:** Use libraries like `marshmallow` or `pydantic` for robust input validation - **Enable CSRF Protection:** Use Flask-WTF for state-changing operations - **Use Environment Variables:** Store database paths and credentials in environment variables - **Implement Proper Authentication:** Integrate with OAuth2, JWT, or session-based authentication - **Add Database Encryption:** Consider SQLite encryption extensions for data-at-rest protection - **Implement Audit Logging:** Log all sensitive operations for compliance and forensics This patched code eliminates the critical SQL injection vulnerability while improving overall application security posture, maintainability, and error handling.
Add to Cart
Instant accessInstant access
Usage rightsCommercial use
Money-back guaranteeMoney‑back
By purchasing this prompt, you agree to our terms of service
V3
Tested icon
Guide icon
4 examples icon
Free credits icon
Turn AI into a Senior Security Researcher. This Mega-Prompt conducts deep code audits based on OWASP 2026 standards, identifies vulnerabilities (SQLi, XSS, Logic Flaws), and generates instant secure code patches
...more
Updated 3 weeks ago
Report
Browse Marketplace