### GET /proxy-image Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt Proxies an image from a given URL, ensuring the URL is from an allowed host and that the content type is an image. ```APIDOC ## GET /proxy-image ### Description Proxies an image from a specified URL, validating the host and content type. ### Method GET ### Endpoint /proxy-image ### Parameters #### Query Parameters - **url** (string) - Required - The URL of the image to proxy. ### Request Example ``` GET /proxy-image?url=https://cdn.example.com/images/logo.png ``` ### Response #### Success Response (200) - **response body** (binary) - The image data. - **Content-Type** (header) - The MIME type of the image. #### Response Example (Binary image data with appropriate Content-Type header) ``` -------------------------------- ### Flask Webhook Service with SSRF Prevention Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt A Flask application demonstrating common SSRF vulnerabilities in webhook and URL fetching endpoints. Includes examples of accessing internal services, cloud metadata, and performing network scanning. The code also outlines potential fixes and validation strategies. ```python from flask import Flask, request, jsonify import requests app = Flask(__name__) @app.route('/fetch-url', methods=['POST']) def fetch_url(): url = request.json.get('url') response = requests.get(url) return jsonify({'content': response.text}) @app.route('/webhook/test', methods=['POST']) def test_webhook(): webhook_url = request.json.get('callback_url') payload = {'event': 'test', 'status': 'success'} requests.post(webhook_url, json=payload) return jsonify({'message': 'Webhook triggered'}) @app.route('/proxy-image', methods=['GET']) def proxy_image(): image_url = request.args.get('url') response = requests.get(image_url, stream=True) return response.content, 200, {'Content-Type': response.headers.get('content-type')} ``` ```python from flask import Flask, request, jsonify, abort import requests from urllib.parse import urlparse import ipaddress import socket app = Flask(__name__) # ... (Additional SSRF prevention code would go here) ``` -------------------------------- ### Bash Script for CI/CD Security Scanning Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt An example bash script designed for integration into a CI/CD pipeline to automate security scanning of code changes. It identifies changed files and reads a general security prompt for analysis. ```bash #!/bin/bash # Example CI/CD integration script for automated security scanning # File: .github/workflows/security-scan.sh # Get changed files in the pull request CHANGED_FILES=$(git diff --name-only origin/main...HEAD | grep -E '\.(py|js|ts|java|go)$') # Read the general security prompt SECURITY_PROMPT=$(cat code-review/code-review.md) ``` -------------------------------- ### Injection Vulnerability Analysis Prompt Usage with Node.js Express Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt Illustrates the usage of a specialized prompt for analyzing injection vulnerabilities in a Node.js Express application. It includes example code snippets demonstrating potential injection flaws. ```javascript const express = require('express'); const { exec } = require('child_process'); const app = express(); app.get('/ping', (req, res) => { const host = req.query.host; exec(`ping -c 4 ${host}`, (error, stdout, stderr) => { if (error) { return res.status(500).json({ error: error.message }); } res.json({ output: stdout }); }); }); app.get('/backup', (req, res) => { const filename = req.query.file; exec(`tar -czf /backups/${filename}.tar.gz /var/www/`, (error, stdout) => { res.json({ success: true, file: filename }); }); }); ``` -------------------------------- ### GET /api/admin/users Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt Retrieves a list of all users in the system, accessible only by administrators. ```APIDOC ## GET /api/admin/users ### Description Retrieves a list of all users registered in the system. This endpoint is protected and requires administrative privileges. ### Method GET ### Endpoint /api/admin/users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example GET /api/admin/users ### Response #### Success Response (200) - **users** (array) - A list of user objects, each containing id, username, email, and role. #### Response Example [ { "id": 1, "username": "johndoe", "email": "john.doe@example.com", "role": "user" }, { "id": 2, "username": "admin", "email": "admin@example.com", "role": "admin" } ] ``` -------------------------------- ### GET /api/documents/ Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt Retrieves a specific document by its ID, ensuring the logged-in user is the owner. ```APIDOC ## GET /api/documents/ ### Description Retrieves a specific document by its ID. Includes ownership validation to ensure the user can only access their own documents. ### Method GET ### Endpoint /api/documents/ ### Parameters #### Path Parameters - **doc_id** (string) - Required - The unique identifier of the document to retrieve. #### Query Parameters None #### Request Body None ### Request Example GET /api/documents/123 ### Response #### Success Response (200) - **document_data** (object) - The data of the requested document. #### Response Example { "id": 123, "title": "Example Document", "content": "This is the document content.", "owner_id": 456 } ``` -------------------------------- ### Bash: Clone Repository and Create Branch Source: https://github.com/jagan-raj-r/appsec-prompt-cheatsheet/blob/main/CONTRIBUTING.md Commands to fork and clone the AppSec Prompt Cheatsheet repository, navigate into the project directory, and create a new branch for feature development. This is the initial step for contributing new prompts or making changes. ```bash git clone https://github.com/[your-username]/appsec-prompt-cheatsheet.git cd appsec-prompt-cheatsheet git checkout -b feature/new-prompt-name ``` -------------------------------- ### Secure Password Hashing with Bcrypt Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt Demonstrates how to securely hash and verify passwords using the bcrypt algorithm with automatic salting. Ensures that passwords are not stored in plain text and are protected against brute-force attacks. ```python import bcrypt class UserAuth: # ... (other methods) # Fix 2: Use bcrypt with automatic salting def hash_password(self, password): salt = bcrypt.gensalt(rounds=12) return bcrypt.hashpw(password.encode(), salt) def verify_password(self, password, hash): return bcrypt.checkpw(password.encode(), hash) ``` -------------------------------- ### POST /fetch-url Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt Fetches and returns the content of a given URL after validating it to prevent SSRF attacks. The response content is limited to 10000 characters. ```APIDOC ## POST /fetch-url ### Description Fetches content from a URL after validation to prevent SSRF. Limits response size. ### Method POST ### Endpoint /fetch-url ### Parameters #### Request Body - **url** (string) - Required - The URL to fetch content from. ### Request Example ```json { "url": "http://example.com/data" } ``` ### Response #### Success Response (200) - **content** (string) - The first 10000 characters of the fetched content. #### Response Example ```json { "content": "..." } ``` ``` -------------------------------- ### Fetch URL Safely with Validation in Flask/Python Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt This Flask route demonstrates how to safely fetch content from a URL after validating it using the `validate_url` function. It prevents SSRF by enforcing allowed schemes, hostnames (optionally whitelisted), and blocking access to private IP ranges. Dependencies include Flask, requests, and the previously defined `validate_url` function. It returns the fetched content or an error. ```python # Assume 'app', 'request', 'jsonify', 'abort' from Flask and 'requests' are imported # Assume 'validate_url' function is defined as above @app.route('/fetch-url', methods=['POST']) def fetch_url(): url = request.json.get('url') if not url: abort(400, "URL required") # Validate URL is_valid, error = validate_url(url) if not is_valid: abort(400, f"Invalid URL: {error}") try: # Add timeout and disable redirects to prevent bypass response = requests.get( url, timeout=5, allow_redirects=False, headers={'User-Agent': 'SafeBot/1.0'} ) return jsonify({'content': response.text[:10000]}) # Limit response size except requests.RequestException as e: abort(500, "Request failed") ``` -------------------------------- ### Git: Commit and Push Changes Source: https://github.com/jagan-raj-r/appsec-prompt-cheatsheet/blob/main/CONTRIBUTING.md Commands to commit staged changes with a descriptive message and push them to the remote repository on your fork. This is part of the workflow for submitting contributions. ```bash git commit -m "Add: XSS analysis prompt for React applications" git push origin feature/new-prompt-name ``` -------------------------------- ### Bash Script for File Vulnerability Scanning with Anthropic Claude API Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt This Bash script defines a function `scan_file` that reads a file's content, constructs a prompt including the code, and sends it to the Anthropic Claude API. It then parses the JSON response using `jq` to count critical vulnerabilities and reports the findings. The script iterates through changed files, calling `scan_file` for each and exiting with an error code if any critical vulnerabilities are detected. ```bash scan_file() { local file=$1 local code=$(cat "$file") # Combine prompt with code local full_prompt="${SECURITY_PROMPT} ``` ${code} ```" # Call Claude API (requires ANTHROPIC_API_KEY environment variable) curl https://api.anthropic.com/v1/messages \ -H "content-type: application/json" \ -H "x-api-key: $ANTHROPIC_API_KEY" \ -H "anthropic-version: 2023-06-01" \ -d '{ \ "model": "claude-3-5-sonnet-20241022", \ "max_tokens": 4096, \ "messages": [ \ { \ "role": "user", \ "content": "'""$full_prompt"'"" \ } \ ] \ }' > "scan_results_${file//\/\_}.json" # Parse results and check for critical/high vulnerabilities CRITICAL_COUNT=$(jq -r '.content[0].text' "scan_results_${file//\/\_}.json" | grep -c "Critical") if [ "$CRITICAL_COUNT" -gt 0 ]; then echo "❌ Critical vulnerabilities found in $file" return 1 fi } # Scan all changed files EXIT_CODE=0 for file in $CHANGED_FILES; do echo "Scanning $file..." scan_file "$file" || EXIT_CODE=1 done # Exit with error if any critical vulnerabilities found exit $EXIT_CODE ``` -------------------------------- ### POST /webhook/test Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt Triggers a test webhook to a specified callback URL. The webhook URL is validated against a whitelist of allowed hosts. ```APIDOC ## POST /webhook/test ### Description Triggers a test webhook to a specified callback URL, enforcing a whitelist of allowed hosts. ### Method POST ### Endpoint /webhook/test ### Parameters #### Request Body - **callback_url** (string) - Required - The URL of the webhook to trigger. ### Request Example ```json { "callback_url": "https://hooks.example.com/my-hook" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates that the webhook was triggered successfully. #### Response Example ```json { "message": "Webhook triggered" } ``` ``` -------------------------------- ### Python: Identify and fix cryptographic failures (OWASP A02:2021) Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt This Python code snippet illustrates common cryptographic failures such as hard-coded secrets, weak hashing algorithms (MD5), insecure data transmission (HTTP), and data exposure in logs. The associated prompt helps analyze these vulnerabilities and suggests fixes like using environment variables, strong hashing algorithms (bcrypt, Argon2), HTTPS, and avoiding sensitive data logging. It uses libraries like `hashlib`, `requests`, `bcrypt`, `os`, and `logging`. ```python import hashlib import requests import bcrypt import os import logging from cryptography.fernet import Fernet from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2 # Configuration # API_KEY = "sk-1234567890abcdef" # Hard-coded secret # DB_PASSWORD = "admin123" # Hard-coded secret # ENCRYPTION_KEY = "mysecretkey" # Hard-coded secret API_KEY = os.environ.get('API_KEY') DB_PASSWORD = os.environ.get('DB_PASSWORD') class UserAuth: def hash_password(self, password): # Weak hashing without salt # return hashlib.md5(password.encode()).hexdigest() # Fix: Use bcrypt for strong hashing salt = bcrypt.gensalt() return bcrypt.hashpw(password.encode(), salt) def verify_password(self, password, hashed_password): # return self.hash_password(password) == hash # Incorrect comparison for bcrypt # Fix: Use bcrypt.checkpw for verification try: return bcrypt.checkpw(password.encode(), hashed_password) except ValueError: return False # Handle cases where hashed_password is not valid bcrypt format def send_user_data(self, user_data): # Sending sensitive data over HTTP # response = requests.post( # 'http://api.example.com/users', # json=user_data, # headers={'X-API-Key': API_KEY} # ) # Fix: Use HTTPS for secure transmission response = requests.post( 'https://api.example.com/users', json=user_data, headers={'X-API-Key': API_KEY} ) return response.json() def log_activity(self, user, action): # Logging sensitive information # print(f"User {user['email']} performed {action} with password {user['password']}") # Fix: Never log sensitive data like passwords logging.basicConfig(level=logging.INFO) logging.info(f"User {user.get('email', 'N/A')} performed {action}") def encrypt_data(self, data, key): # Example of proper encryption key derivation (not direct use of key) kdf = PBKDF2( algorithm=hashes.SHA256(), length=32, salt=b'some_salt_for_kdf', # Use a unique salt for KDF iterations=100000, ) derived_key = kdf.derive(key.encode()) f = Fernet(derived_key) return f.encrypt(data.encode()) def decrypt_data(self, encrypted_data, key): kdf = PBKDF2( algorithm=hashes.SHA256(), length=32, salt=b'some_salt_for_kdf', # Must use the same salt as used for derivation iterations=100000, ) derived_key = kdf.derive(key.encode()) f = Fernet(derived_key) return f.decrypt(encrypted_data).decode() ``` -------------------------------- ### Secure User Data Transmission with HTTPS Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt Illustrates how to securely transmit user data over HTTPS, excluding sensitive fields like passwords. It emphasizes using HTTPS, verifying SSL certificates, and setting appropriate timeouts for network requests. ```python import requests # Assuming API_KEY is defined elsewhere # API_KEY = "your_api_key" class UserAuth: # ... (other methods) # Fix 3: Use HTTPS for secure transmission def send_user_data(self, user_data): # Remove sensitive fields before transmission safe_data = { 'email': user_data['email'], 'username': user_data['username'] # Do not send password or sensitive data } response = requests.post( 'https://api.example.com/users', # HTTPS instead of HTTP json=safe_data, headers={'X-API-Key': API_KEY}, timeout=10, verify=True # Verify SSL certificates ) return response.json() ``` -------------------------------- ### General Security Code Review Prompt Usage with Python Flask Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt Demonstrates how to use a general security code review prompt with a Python Flask API. It shows the process of adding code to the prompt and the expected output, including vulnerability identification and fixes. ```python from flask import Flask, request import sqlite3 app = Flask(__name__) @app.route('/user/') def get_user(user_id): conn = sqlite3.connect('database.db') cursor = conn.cursor() query = f"SELECT * FROM users WHERE id = {user_id}" cursor.execute(query) user = cursor.fetchone() return {'user': user} @app.route('/search') def search(): keyword = request.args.get('q') conn = sqlite3.connect('database.db') cursor = conn.cursor() cursor.execute("SELECT * FROM products WHERE name LIKE '%" + keyword + "%'") results = cursor.fetchall() return {'results': results} ``` ```python # Fixed version with parameterized queries @app.route('/user/') def get_user(user_id): conn = sqlite3.connect('database.db') cursor = conn.cursor() cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,)) user = cursor.fetchone() return {'user': user} @app.route('/search') def search(): keyword = request.args.get('q') conn = sqlite3.connect('database.db') cursor = conn.cursor() cursor.execute("SELECT * FROM products WHERE name LIKE ?", (f"%{keyword}%",)) results = cursor.fetchall() return {'results': results} ``` -------------------------------- ### Client-Side Security Analysis Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt Provides guidance on analyzing client-side vulnerabilities including XSS, CSRF, insecure DOM manipulation, and postMessage security. ```APIDOC ## Client-Side Security Analysis (XSS and DOM Security) ### Description Comprehensive prompt for analyzing client-side vulnerabilities including all XSS variants (Reflected, Stored, DOM-based), CSRF, insecure DOM manipulation, client-side injection, insecure storage, and postMessage security issues. ### Usage Example with React/JavaScript Application (Detailed prompt or guidance would follow here, but is omitted as per schema instructions for API documentation snippets.) ``` -------------------------------- ### Python Flask: Add admin authorization check for user listing Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt This Python Flask snippet shows how to implement an admin authorization check before listing users. It connects to an SQLite database, fetches user details, and returns them as JSON. The `@require_admin` decorator (assumed to be defined elsewhere) ensures that only administrators can access this endpoint. It requires Flask and session management. ```python import sqlite3 from flask import Flask, session, jsonify, request, abort app = Flask(__name__) app.secret_key = 'your secret key' # Needed for session management # Mock decorator for demonstration def require_login(f): # In a real app, this would check if the user is logged in session['user_id'] = 1 # Mock user ID return f def require_admin(f): # In a real app, this would check if the user is an admin return f @app.route('/api/admin/users') @require_admin def admin_users(): conn = sqlite3.connect('app.db') cursor = conn.cursor() cursor.execute("SELECT id, username, email, role FROM users") users = cursor.fetchall() return jsonify(users) ``` -------------------------------- ### Fix OS Command Injection in Node.js Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt Demonstrates fixing OS command injection vulnerabilities in a Node.js Express application. It uses `child_process.execFile` with argument arrays and sanitizes input to prevent malicious command execution. Dependencies include Node.js and the Express framework. ```javascript const { execFile } = require('child_process'); const path = require('path'); // Fix 1: Use execFile with argument array instead of shell app.get('/ping', (req, res) => { const host = req.query.host; // Validate hostname format if (!/^[a-zA-Z0-9.-]+$/.test(host)) { return res.status(400).json({ error: 'Invalid hostname' }); } execFile('ping', ['-c', '4', host], (error, stdout, stderr) => { if (error) { return res.status(500).json({ error: 'Ping failed' }); } res.json({ output: stdout }); }); }); // Fix 2: Validate and sanitize filename, use safe path construction app.get('/backup', (req, res) => { const filename = req.query.file; // Whitelist alphanumeric characters only if (!/^[a-zA-Z0-9_-]+$/.test(filename)) { return res.status(400).json({ error: 'Invalid filename' }); } const safePath = path.join('/backups', `${filename}.tar.gz`); execFile('tar', ['-czf', safePath, '/var/www/'], (error, stdout) => { if (error) { return res.status(500).json({ error: 'Backup failed' }); } res.json({ success: true, file: filename }); }); }); ``` -------------------------------- ### Validate URLs to Prevent SSRF Attacks in Python Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt This Python function validates URLs to prevent SSRF attacks by checking schemes, hostnames, resolving IPs, and blocking known private/loopback ranges and common service ports. It requires the 'ipaddress', 'urllib.parse', and 'socket' modules. Input is a URL string and an optional list of allowed hosts. Output is a boolean indicating validity and an error message if invalid. ```python import ipaddress from urllib.parse import urlparse import socket BLOCKED_IPS = [ ipaddress.ip_network('10.0.0.0/8'), # Private network ipaddress.ip_network('172.16.0.0/12'), # Private network ipaddress.ip_network('192.168.0.0/16'), # Private network ipaddress.ip_network('127.0.0.0/8'), # Loopback ipaddress.ip_network('169.254.0.0/16'), # AWS metadata ipaddress.ip_network('::1/128'), # IPv6 loopback ] ALLOWED_SCHEMES = ['http', 'https'] BLOCKED_PORTS = [22, 23, 25, 3306, 5432, 6379, 27017] # Common service ports def validate_url(url, allowed_hosts=None): """Validate URL to prevent SSRF attacks""" try: parsed = urlparse(url) # Check scheme if parsed.scheme not in ALLOWED_SCHEMES: return False, "Only HTTP/HTTPS allowed" # Check for hostname if not parsed.hostname: return False, "Invalid hostname" # If whitelist provided, enforce it if allowed_hosts and parsed.hostname not in allowed_hosts: return False, f"Host not in whitelist" # Resolve hostname to IP try: ip = socket.gethostbyname(parsed.hostname) ip_obj = ipaddress.ip_address(ip) # Check if IP is in blocked ranges for blocked_network in BLOCKED_IPS: if ip_obj in blocked_network: return False, f"Access to {ip} is blocked" except socket.gaierror: return False, "Cannot resolve hostname" # Check port port = parsed.port or (443 if parsed.scheme == 'https' else 80) if port in BLOCKED_PORTS: return False, f"Port {port} is blocked" return True, None except Exception as e: return False, str(e) ``` -------------------------------- ### Python Flask: Add ownership validation to document retrieval Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt This Python Flask snippet demonstrates how to add ownership validation when retrieving a document. It connects to an SQLite database, queries for a document matching the provided ID and the current user's ID, and returns a 404 error if the document is not found or does not belong to the user. It requires Flask, Flask-SQLAlchemy, and session management. ```python import sqlite3 from flask import Flask, session, jsonify, request, abort app = Flask(__name__) app.secret_key = 'your secret key' # Needed for session management # Mock decorator for demonstration def require_login(f): # In a real app, this would check if the user is logged in session['user_id'] = 1 # Mock user ID return f def require_admin(f): # In a real app, this would check if the user is an admin return f @app.route('/api/documents/') @require_login def get_document(doc_id): user_id = session.get('user_id') conn = sqlite3.connect('app.db') cursor = conn.cursor() cursor.execute( "SELECT * FROM documents WHERE id = ? AND owner_id = ?", (doc_id, user_id) ) doc = cursor.fetchone() if not doc: abort(404) return jsonify(doc) ``` -------------------------------- ### Restrict Image Proxy to Trusted CDNs in Flask/Python Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt This Flask route implements a secure image proxy by validating the image URL against a whitelist of trusted CDN domains using `validate_url`. It also verifies the 'Content-Type' header to ensure the URL points to an actual image, preventing the server from proxying non-image or malicious content. It returns the image content or an error. ```python # Assume 'app', 'request', 'jsonify', 'abort' from Flask and 'requests' are imported # Assume 'validate_url' function is defined as above @app.route('/proxy-image', methods=['GET']) def proxy_image(): image_url = request.args.get('url') # Only allow images from trusted CDNs ALLOWED_IMAGE_HOSTS = ['cdn.example.com', 'images.cloudfront.net'] is_valid, error = validate_url(image_url, allowed_hosts=ALLOWED_IMAGE_HOSTS) if not is_valid: abort(400, f"Invalid image URL: {error}") try: response = requests.get( image_url, stream=True, timeout=10, allow_redirects=False ) # Verify content-type is actually an image content_type = response.headers.get('content-type', '') if not content_type.startswith('image/'): abort(400, "URL does not point to an image") return response.content, 200, {'Content-Type': content_type} except requests.RequestException: abort(500, "Failed to fetch image") ``` -------------------------------- ### Whitelist Webhook Domains with URL Validation in Flask/Python Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt This Flask route secures webhook calls by validating the provided callback URL against a predefined whitelist of allowed hosts using the `validate_url` function. This prevents requests from being sent to unauthorized or malicious endpoints. It returns a success message or an error if the URL is invalid or the webhook delivery fails. ```python # Assume 'app', 'request', 'jsonify', 'abort' from Flask and 'requests' are imported # Assume 'validate_url' function is defined as above @app.route('/webhook/test', methods=['POST']) def test_webhook(): webhook_url = request.json.get('callback_url') # Define allowed webhook domains ALLOWED_WEBHOOK_HOSTS = ['hooks.example.com', 'webhooks.trusted-partner.com'] is_valid, error = validate_url(webhook_url, allowed_hosts=ALLOWED_WEBHOOK_HOSTS) if not is_valid: abort(400, f"Invalid webhook URL: {error}") payload = {'event': 'test', 'status': 'success'} try: requests.post( webhook_url, json=payload, timeout=5, allow_redirects=False ) return jsonify({'message': 'Webhook triggered'}) except requests.RequestException: abort(500, "Webhook delivery failed") ``` -------------------------------- ### Cryptographic Failures Analysis (OWASP A02:2021) Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt Prompt for identifying weak encryption, hard-coded secrets, poor key management, insecure transmission, and weak password storage. ```APIDOC ## Cryptographic Failures Analysis (OWASP A02:2021) ### Description This prompt is designed to identify vulnerabilities related to cryptographic failures, including weak encryption algorithms, hard-coded secrets, poor key management practices, insecure data transmission (e.g., lack of TLS/SSL), weak password storage mechanisms, and data exposure vulnerabilities. ### Method N/A (Analysis Prompt) ### Endpoint N/A (Applies to entire application/codebase) ### Parameters N/A ### Request Example (Refer to detailed usage example in the original documentation) ### Response #### Success Response (Analysis Results) - **Vulnerability Table**: A table detailing identified vulnerabilities, their location, type, severity, attack vector, impact, and recommended fixes. #### Response Example (Table Snippet) | # | Location | Vulnerability Type | Severity | Attack/Exploit | Impact | Fix | |---|----------|-------------------|----------|----------------|---------|-----| | 1 | Line 5-7 | Hard-coded Secrets | Critical | Extract from source code | API and database compromise | Use environment variables | | 2 | Line 12 | Weak Hashing (MD5) | Critical | Rainbow table/hash collision | Password compromise | Use bcrypt, Argon2, or PBKDF2 | ``` -------------------------------- ### Logging without Sensitive Information Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt Provides a method for logging user activities while excluding sensitive information. It demonstrates how to use Python's logging module to log only non-sensitive identifiers and relevant details. ```python import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class UserAuth: # ... (other methods) # Fix 4: Log without sensitive information def log_activity(self, user, action): # Only log non-sensitive identifiers logger.info( f"User {user.get('user_id', 'unknown')} performed {action}", extra={'user_id': user.get('user_id')} ) ``` -------------------------------- ### JavaScript Security Fixes (React) Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt Demonstrates how to fix Reflected XSS, DOM-based XSS, Insecure Storage, CSRF, and Stored XSS in a React application. It utilizes DOMPurify for sanitization and fetch API for CSRF token retrieval. Sensitive data should not be stored in localStorage; httpOnly cookies are preferred. ```javascript import React, { useState, useEffect } from 'react'; import DOMPurify from 'dompurify'; function UserProfile() { const [userBio, setUserBio] = useState(''); const [searchResults, setSearchResults] = useState([]); const [csrfToken, setCsrfToken] = useState(''); useEffect(() => { // Fix 1: Sanitize URL parameters const params = new URLSearchParams(window.location.search); const bio = params.get('bio'); if (bio) { // Use DOMPurify to sanitize HTML setUserBio(DOMPurify.sanitize(bio)); } // Fix 3: Don't store sensitive tokens in localStorage // Use httpOnly cookies set by server instead // If you must use localStorage, encrypt the token // Fetch CSRF token from server fetch('/api/csrf-token', { credentials: 'include' }) .then(res => res.json()) .then(data => setCsrfToken(data.csrfToken)); }, []); // Fix 2: Use textContent instead of innerHTML const handleSearch = (query) => { const resultsDiv = document.getElementById('search-results'); // Safely set text content resultsDiv.textContent = `Results for: ${query}`; // Or better yet, use React state instead of direct DOM manipulation setSearchResults([query]); }; // Fix 4: Implement CSRF protection const handleDeleteAccount = async () => { if (!csrfToken) { alert('Security token not available'); return; } // Confirm critical action if (!window.confirm('Are you sure you want to delete your account?')) { return; } try { const response = await fetch('/api/account/delete', { method: 'DELETE', credentials: 'include', headers: { 'X-CSRF-Token': csrfToken, 'Content-Type': 'application/json' } }); if (response.ok) { window.location.href = '/goodbye'; } else { alert('Failed to delete account'); } } catch (error) { console.error('Error deleting account:', error); } }; return (
{/* Fix 5: Sanitize user-generated content before rendering */}
handleSearch(e.target.value)} placeholder="Search..." /> {/* Better: Use React to render instead of innerHTML */}
{searchResults.map((result, index) => (
Results for: {result}
))}
); } export default UserProfile; // Additional security headers to set on the server: // Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' // X-Content-Type-Options: nosniff // X-Frame-Options: DENY // Strict-Transport-Security: max-age=31536000; includeSubDomains ``` -------------------------------- ### React XSS and CSRF Vulnerabilities in JavaScript Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt Demonstrates DOM-based XSS via innerHTML manipulation, Stored XSS through dangerouslySetInnerHTML, and missing CSRF protection in a fetch request. This code is vulnerable and should not be used in production without proper sanitization and CSRF tokens. ```javascript import React, { useState, useEffect } from 'react'; function UserProfile() { const [userBio, setUserBio] = useState(''); const [searchResults, setSearchResults] = useState([]); useEffect(() => { // Load user data from URL parameter const params = new URLSearchParams(window.location.search); const bio = params.get('bio'); setUserBio(bio); // Store API token in localStorage localStorage.setItem('api_token', 'secret-api-key-12345'); }, []); const handleSearch = (query) => { // DOM-based XSS vulnerability document.getElementById('search-results').innerHTML = `
Results for: ${query}
`; }; const handleDeleteAccount = () => { // Missing CSRF protection fetch('/api/account/delete', { method: 'DELETE', credentials: 'include' }); }; return (
{/* Stored XSS vulnerability */}
handleSearch(e.target.value)} />
); } export default UserProfile; ``` -------------------------------- ### Fix Broken Access Control in Python Flask Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt Illustrates how to fix broken access control vulnerabilities in a Python Flask application. It implements authorization decorators to enforce login requirements and role-based access for administrative actions, preventing unauthorized data access and privilege escalation. Dependencies include Flask and SQLite. ```python from flask import Flask, request, session, jsonify, abort from functools import wraps import sqlite3 app = Flask(__name__) app.secret_key = 'secure-random-key-here' # Authorization decorator def require_admin(f): @wraps(f) def decorated_function(*args, **kwargs): if not session.get('user_id'): abort(401) if not session.get('is_admin'): abort(403) return f(*args, **kwargs) return decorated_function def require_login(f): @wraps(f) def decorated_function(*args, **kwargs): if not session.get('user_id'): abort(401) return f(*args, **kwargs) return decorated_function @app.route('/api/documents/') @require_login # Added login check def get_document(doc_id): # Retrieve document with ownership check user_id = session.get('user_id') conn = sqlite3.connect('app.db') cursor = conn.cursor() cursor.execute("SELECT * FROM documents WHERE id = ? AND owner_id = ?", (doc_id, user_id)) doc = cursor.fetchone() if not doc: abort(404) # Document not found or not owned by user return jsonify(doc) @app.route('/api/admin/users') @require_admin # Added admin check def admin_users(): # No admin check performed conn = sqlite3.connect('app.db') cursor = conn.cursor() cursor.execute("SELECT * FROM users") users = cursor.fetchall() return jsonify(users) @app.route('/api/user//update', methods=['POST']) @require_login # Added login check def update_user(user_id): # User can update their own profile current_user_id = session.get('user_id') if str(current_user_id) != str(user_id) and not session.get('is_admin'): # Allow admins to update any user abort(403) new_email = request.json.get('email') conn = sqlite3.connect('app.db') cursor = conn.cursor() cursor.execute("UPDATE users SET email = ? WHERE id = ?", (new_email, user_id)) conn.commit() return jsonify({'success': True}) ``` -------------------------------- ### POST /api/user//update Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt Updates the email address for a specific user. Users can only update their own profile, unless they are administrators. ```APIDOC ## POST /api/user//update ### Description Updates the email address for a specified user. Access control ensures that only the user themselves or an administrator can perform this action. Input email is validated. ### Method POST ### Endpoint /api/user//update ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user whose profile is to be updated. #### Query Parameters None #### Request Body - **email** (string) - Required - The new email address for the user. ### Request Example POST /api/user/123/update { "email": "new.email@example.com" } ### Response #### Success Response (200) - **success** (boolean) - Indicates if the update was successful. #### Response Example { "success": true } #### Error Responses - **400 Bad Request**: If the email format is invalid or missing. - **403 Forbidden**: If the user is not authorized to update the profile. ``` -------------------------------- ### Python Flask: Validate user can only update own profile Source: https://context7.com/jagan-raj-r/appsec-prompt-cheatsheet/llms.txt This Python Flask snippet enforces that users can only update their own profile, with an exception for administrators. It checks the current user's ID against the requested user ID and the admin status from the session. It also validates the email format before updating the user's email in the SQLite database. Requires Flask, session management, and request handling. ```python import sqlite3 from flask import Flask, session, jsonify, request, abort app = Flask(__name__) app.secret_key = 'your secret key' # Needed for session management # Mock decorator for demonstration def require_login(f): # In a real app, this would check if the user is logged in session['user_id'] = 1 # Mock user ID session['is_admin'] = False # Mock admin status return f def require_admin(f): # In a real app, this would check if the user is an admin return f @app.route('/api/user//update', methods=['POST']) @require_login def update_user(user_id): current_user_id = session.get('user_id') # Users can only update their own profile (unless admin) if str(current_user_id) != str(user_id) and not session.get('is_admin'): abort(403) new_email = request.json.get('email') # Validate email format if not new_email or '@' not in new_email: abort(400) conn = sqlite3.connect('app.db') cursor = conn.cursor() cursor.execute("UPDATE users SET email = ? WHERE id = ?", (new_email, user_id)) conn.commit() return jsonify({'success': True}) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.