# SPDX-License-Identifier: Apache-2.0
# Copyright 2025 Vulnerable Demo App
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Intentionally Vulnerable Python Application
This file contains various security vulnerabilities for demonstration purposes.
DO NOT USE IN PRODUCTION!
"""

import os
import subprocess
import sqlite3
import pickle
import hashlib
import random
import requests
from flask import Flask, request, render_template_string

app = Flask(__name__)

# VULNERABILITY 1: Hardcoded secrets and credentials
API_KEY = "sk-1234567890abcdef"  # Hardcoded API key
DATABASE_PASSWORD = "admin123"   # Hardcoded password
SECRET_KEY = "my-super-secret-key"  # Hardcoded secret key
AWS_ACCESS_KEY = "AKIAIOSFODNN7EXAMPLE"  # Hardcoded AWS key

# VULNERABILITY 2: SQL Injection
def get_user_data(user_id):
    """Vulnerable to SQL injection"""
    conn = sqlite3.connect('users.db')
    cursor = conn.cursor()
    
    # Direct string concatenation - SQL injection vulnerability
    query = f"SELECT * FROM users WHERE id = {user_id}"
    cursor.execute(query)
    
    result = cursor.fetchall()
    conn.close()
    return result

# VULNERABILITY 3: Command Injection
def process_file(filename):
    """Vulnerable to command injection"""
    # Direct command execution with user input
    command = f"cat {filename}"
    result = subprocess.run(command, shell=True, capture_output=True, text=True)
    return result.stdout

# VULNERABILITY 4: Path Traversal
def read_file(filepath):
    """Vulnerable to path traversal"""
    # No validation of file path
    with open(filepath, 'r') as file:
        return file.read()

# VULNERABILITY 5: Insecure Deserialization
def load_user_session(session_data):
    """Vulnerable to pickle deserialization attacks"""
    # Unsafe deserialization of user data
    return pickle.loads(session_data)

# VULNERABILITY 6: Weak Cryptography
def generate_token():
    """Uses weak random number generation"""
    # Weak random number generation
    random.seed(1234)  # Predictable seed
    token = random.randint(1000, 9999)
    return str(token)

def hash_password(password):
    """Uses weak hashing algorithm"""
    # MD5 is cryptographically broken
    return hashlib.md5(password.encode()).hexdigest()

# VULNERABILITY 7: Server-Side Template Injection (SSTI)
@app.route('/profile')
def profile():
    """Vulnerable to template injection"""
    name = request.args.get('name', 'Guest')
    # Direct template rendering with user input
    template = f"<h1>Hello {name}!</h1>"
    return render_template_string(template)

# VULNERABILITY 8: Insecure HTTP Requests
def fetch_data(url):
    """Vulnerable to SSRF and insecure requests"""
    # No SSL verification, allows any URL
    response = requests.get(url, verify=False, timeout=None)
    return response.text

# VULNERABILITY 9: Information Disclosure
def debug_info():
    """Exposes sensitive system information"""
    info = {
        'environment_vars': dict(os.environ),
        'current_directory': os.getcwd(),
        'system_info': os.uname(),
        'database_password': DATABASE_PASSWORD,
        'api_key': API_KEY
    }
    return info

# VULNERABILITY 10: Unsafe File Operations
def save_uploaded_file(file_content, filename):
    """Vulnerable to directory traversal and arbitrary file write"""
    # No validation of filename
    filepath = f"/uploads/{filename}"
    with open(filepath, 'wb') as f:
        f.write(file_content)
    return filepath

# VULNERABILITY 11: Eval/Exec Injection
def calculate_expression(expression):
    """Vulnerable to code injection"""
    # Direct evaluation of user input
    result = eval(expression)
    return result

def execute_code(code):
    """Vulnerable to arbitrary code execution"""
    # Direct execution of user input
    exec(code)

# VULNERABILITY 12: Weak Session Management
class SessionManager:
    """Insecure session management"""
    
    def __init__(self):
        self.sessions = {}
    
    def create_session(self, user_id):
        # Predictable session ID
        session_id = f"session_{user_id}_{generate_token()}"
        self.sessions[session_id] = {
            'user_id': user_id,
            'created': 'now',
            'admin': True  # Everyone gets admin privileges!
        }
        return session_id

# VULNERABILITY 13: Insecure Direct Object Reference
def get_user_profile(user_id, requested_profile_id):
    """No authorization check"""
    # Returns any user's profile regardless of who's requesting
    return get_user_data(requested_profile_id)

# VULNERABILITY 14: XML External Entity (XXE) - if using XML
def parse_xml(xml_data):
    """Vulnerable to XXE attacks"""
    import xml.etree.ElementTree as ET
    # Unsafe XML parsing
    root = ET.fromstring(xml_data)
    return root

# VULNERABILITY 15: Race Condition
import threading
import time

balance = 1000
balance_lock = threading.Lock()

def withdraw_money(amount):
    """Race condition in financial transaction"""
    global balance
    # Missing proper locking
    if balance >= amount:
        time.sleep(0.1)  # Simulate processing time
        balance -= amount
        return True
    return False

if __name__ == '__main__':
    # VULNERABILITY 16: Debug mode in production
    app.run(debug=True, host='0.0.0.0', port=5000)