CoolFace
Apppublic

mugdhav/security_auditor_orig

sourceHugging Facemitupdated 8mo agoView on Hugging Face
1likes
vulnerable_sample.py280 linesDownload Raw Back to test_samples
1#!/usr/bin/env python32"""3VULNERABLE CODE SAMPLES - FOR TESTING ONLY4==========================================5This file contains intentionally vulnerable code patterns.6DO NOT use this code in production!7 8This file demonstrates various security vulnerabilities that the9security checker should detect. Think of it as a "patient" for10our security "doctor" to diagnose.11"""12 13import os14import pickle15import hashlib16import random17import subprocess18import sqlite319import yaml20from flask import Flask, request, redirect21 22app = Flask(__name__)23 24# ============================================================25# VULNERABILITY 1: SQL Injection26# Analogy: Like leaving your house key under the doormat27# ============================================================28 29def get_user_unsafe(username):30    """VULNERABLE: User input directly concatenated into SQL query."""31    conn = sqlite3.connect('users.db')32    cursor = conn.cursor()33    34    # BAD: String formatting in SQL query35    query = f"SELECT * FROM users WHERE username = '{username}'"36    cursor.execute(query)37    38    return cursor.fetchone()39 40 41def search_products_unsafe(search_term):42    """VULNERABLE: Another SQL injection example."""43    conn = sqlite3.connect('products.db')44    cursor = conn.cursor()45    46    # BAD: f-string in execute47    cursor.execute(f"SELECT * FROM products WHERE name LIKE '%{search_term}%'")48    49    return cursor.fetchall()50 51 52# ============================================================53# VULNERABILITY 2: Command Injection54# Analogy: Like letting a stranger operate your computer55# ============================================================56 57def ping_server_unsafe(hostname):58    """VULNERABLE: User input passed directly to shell command."""59    # BAD: os.system with user input60    os.system(f"ping -c 1 {hostname}")61 62 63def convert_file_unsafe(filename):64    """VULNERABLE: subprocess with shell=True and user input."""65    # BAD: shell=True with f-string66    subprocess.call(f"convert {filename} output.pdf", shell=True)67 68 69# ============================================================70# VULNERABILITY 3: Hardcoded Credentials71# Analogy: Writing your PIN on your credit card72# ============================================================73 74# BAD: Passwords in source code75DATABASE_PASSWORD = "SuperSecret123!"76API_KEY = "sk-1234567890abcdef1234567890abcdef"77SECRET_TOKEN = "my_very_secret_token_12345"78 79def connect_to_database():80    """VULNERABLE: Hardcoded password."""81    password = "AnotherHardcodedPass123"82    return f"mysql://user:{password}@localhost/db"83 84 85# ============================================================86# VULNERABILITY 4: Weak Password Hashing87# Analogy: Using a paper lock instead of a steel one88# ============================================================89 90def hash_password_weak(password):91    """VULNERABLE: Using MD5 for password hashing."""92    # BAD: MD5 is cryptographically broken93    return hashlib.md5(password.encode()).hexdigest()94 95 96def verify_password_sha1(password, stored_hash):97    """VULNERABLE: Using SHA1 for password hashing."""98    # BAD: SHA1 is not suitable for passwords99    return hashlib.sha1(password.encode()).hexdigest() == stored_hash100 101 102# ============================================================103# VULNERABILITY 5: Insecure Deserialization104# Analogy: Opening a package without checking what's inside105# ============================================================106 107def load_user_data_unsafe(data):108    """VULNERABLE: Deserializing untrusted data with pickle."""109    # BAD: pickle.loads on user-provided data110    return pickle.loads(data)111 112 113def load_config_unsafe(config_file):114    """VULNERABLE: yaml.load without SafeLoader."""115    with open(config_file) as f:116        # BAD: yaml.load without specifying Loader117        return yaml.load(f)118 119 120# ============================================================121# VULNERABILITY 6: Insecure Random Number Generation122# Analogy: Using predictable dice in a casino123# ============================================================124 125def generate_token_unsafe():126    """VULNERABLE: Using random module for security tokens."""127    # BAD: random.random is not cryptographically secure128    return ''.join([chr(int(random.random() * 26) + 65) for _ in range(32)])129 130 131def generate_session_id_unsafe():132    """VULNERABLE: Using random.randint for session IDs."""133    # BAD: Predictable session IDs134    return str(random.randint(100000, 999999))135 136 137# ============================================================138# VULNERABILITY 7: Path Traversal139# Analogy: A visitor who can access any room in your house140# ============================================================141 142def read_file_unsafe(filename):143    """VULNERABLE: User input used directly in file path."""144    # BAD: No path validation145    with open(f"/uploads/{filename}") as f:146        return f.read()147 148 149def serve_image_unsafe(image_name):150    """VULNERABLE: Path traversal in file operations."""151    # BAD: Could access ../../etc/passwd152    path = "/images/" + image_name153    with open(path, 'rb') as f:154        return f.read()155 156 157# ============================================================158# VULNERABILITY 8: XSS (Cross-Site Scripting)159# Analogy: Letting someone put their own signs in your store160# ============================================================161 162@app.route('/search')163def search_results_unsafe():164    """VULNERABLE: Reflected XSS vulnerability."""165    query = request.args.get('q', '')166    # BAD: User input rendered directly in HTML167    return f"<html><body>Results for: {query}</body></html>"168 169 170# ============================================================171# VULNERABILITY 9: Open Redirect172# Analogy: A sign that sends visitors anywhere they want173# ============================================================174 175@app.route('/redirect')176def redirect_unsafe():177    """VULNERABLE: Open redirect vulnerability."""178    # BAD: Unvalidated redirect URL179    next_url = request.args.get('next')180    return redirect(next_url)181 182 183# ============================================================184# VULNERABILITY 10: Debug Mode Enabled185# Analogy: Leaving your diary open on the coffee table186# ============================================================187 188# BAD: Debug mode in production189DEBUG = True190FLASK_DEBUG = True191 192if __name__ == '__main__':193    # BAD: Debug mode enabled194    app.run(debug=True, host='0.0.0.0')195 196 197# ============================================================198# VULNERABILITY 11: SSL Verification Disabled199# Analogy: Accepting any ID without checking if it's real200# ============================================================201 202import requests203 204def fetch_data_unsafe(url):205    """VULNERABLE: SSL verification disabled."""206    # BAD: verify=False allows MITM attacks207    response = requests.get(url, verify=False)208    return response.text209 210 211# ============================================================212# VULNERABILITY 12: Sensitive Data in Logs213# Analogy: Announcing credit card numbers over a loudspeaker214# ============================================================215 216import logging217 218def log_login_unsafe(username, password):219    """VULNERABLE: Logging sensitive information."""220    # BAD: Password logged in plaintext221    logging.info(f"Login attempt: username={username}, password={password}")222 223 224def log_payment_unsafe(card_number, cvv):225    """VULNERABLE: Logging credit card information."""226    # BAD: Credit card data in logs227    print(f"Processing payment: card={card_number}, cvv={cvv}")228 229 230# ============================================================231# VULNERABILITY 13: Hardcoded Encryption Key232# Analogy: Using the same lock combination as everyone else233# ============================================================234 235# BAD: Hardcoded encryption key236ENCRYPTION_KEY = b'ThisIsASecretKey1234567890123456'237AES_IV = b'InitializationV!'238 239 240def encrypt_unsafe(data):241    """VULNERABLE: Using hardcoded encryption key."""242    from Crypto.Cipher import AES243    # BAD: Hardcoded key used directly244    key = b'MySuperSecretKey1234567890123456'245    cipher = AES.new(key, AES.MODE_CBC, AES_IV)246    return cipher.encrypt(data)247 248 249# ============================================================250# VULNERABILITY 14: CORS Wildcard251# Analogy: Allowing anyone to pick up your mail252# ============================================================253 254@app.after_request255def add_cors_headers(response):256    """VULNERABLE: Permissive CORS configuration."""257    # BAD: Wildcard CORS allows any origin258    response.headers['Access-Control-Allow-Origin'] = '*'259    response.headers['Access-Control-Allow-Methods'] = '*'260    return response261 262 263# ============================================================264# VULNERABILITY 15: JWT Without Verification265# Analogy: Accepting any badge without checking if it's real266# ============================================================267 268import jwt269 270def decode_token_unsafe(token):271    """VULNERABLE: JWT decoded without verification."""272    # BAD: verify=False bypasses signature check273    return jwt.decode(token, verify=False)274 275 276def decode_with_none_alg(token):277    """VULNERABLE: Allowing 'none' algorithm."""278    # BAD: 'none' algorithm is insecure279    return jwt.decode(token, algorithms=['none'])280