# SPDX-License-Identifier: Apache-2.0
# Copyright 2025 Security Test Project
#
# 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.

"""
Vulnerable test file containing intentional security vulnerabilities
for demonstration and testing purposes.
"""

import sqlite3
import subprocess
import os

def vulnerable_sql_query(user_id):
    """SQL Injection vulnerability - directly concatenating user input"""
    conn = sqlite3.connect('users.db')
    cursor = conn.cursor()
    
    # VULNERABLE: Direct string concatenation allows SQL injection
    query = f"SELECT * FROM users WHERE id = {user_id}"
    cursor.execute(query)
    
    results = cursor.fetchall()
    conn.close()
    return results

def vulnerable_command_execution(filename):
    """Command Injection vulnerability - using user input in shell commands"""
    
    # VULNERABLE: Direct use of user input in shell command
    command = f"cat {filename}"
    result = subprocess.run(command, shell=True, capture_output=True, text=True)
    return result.stdout

def another_sql_vulnerability(username, password):
    """Another SQL injection example with string formatting"""
    conn = sqlite3.connect('auth.db')
    cursor = conn.cursor()
    
    # VULNERABLE: String formatting allows SQL injection
    query = "SELECT * FROM users WHERE username = '{}' AND password = '{}'".format(username, password)
    cursor.execute(query)
    
    user = cursor.fetchone()
    conn.close()
    return user

def os_command_injection(user_input):
    """Command injection using os.system"""
    
    # VULNERABLE: Direct use of user input with os.system
    os.system(f"echo {user_input}")

def path_traversal_vulnerability(file_path):
    """Path traversal vulnerability"""
    
    # VULNERABLE: No validation of file path
    with open(f"/var/www/uploads/{file_path}", 'r') as f:
        return f.read()

# Example usage that would be exploitable
if __name__ == "__main__":
    # These calls would be vulnerable to injection attacks
    vulnerable_sql_query("1 OR 1=1")  # SQL injection
    vulnerable_command_execution("file.txt; rm -rf /")  # Command injection
    another_sql_vulnerability("admin", "' OR '1'='1")  # SQL injection
    os_command_injection("hello; rm important_file.txt")  # Command injection
    path_traversal_vulnerability("../../../etc/passwd")  # Path traversal