import os
import re

# Define the OWASP Top 10 vulnerabilities patterns
OWASP_TOP_10 = {
    "Injection": [
        r"(?i)\b(?:select|insert|update|delete|drop|alter|create)\b[^;]*\b(?:from|into|where)\b",
        r"(?i)\b(?:exec|eval|system|os\.popen|subprocess\.call)\b",
        r"(?i)\b(?:<\?php|\$_(GET|POST|REQUEST|COOKIE))\b"
    ],
    "Broken Authentication": [
        r"(?i)\b(?:password|passwd|admin|login)\b"
    ],
    "Sensitive Data Exposure": [
        r"(?i)\b(?:apikey|secretkey|password|credentials)\b"
    ],
    "XML External Entities (XXE)": [
        r"(?i)\b<!ENTITY\b"
    ],
    "Broken Access Control": [
        r"(?i)\b(?:chmod|chown|chmod777)\b"
    ],
    "Security Misconfiguration": [
        r"(?i)\b(?:debug=True|verbose=True)\b"
    ],
    "Cross-Site Scripting (XSS)": [
        r"(?i)<\s*script\b[^>]*>[^<]*<\s*/\s*script\s*>",
        r"(?i)\b(?:alert|document\.write|eval\(|javascript:|<\s*img\b[^>]*\sonerror\b)",
    ],
    "Insecure Deserialization": [
        r"(?i)\b(?:pickle|cPickle|unpickle|pyYAML|yaml\.load)\b"
    ],
    "Using Components with Known Vulnerabilities": [
        r"(?i)\b(?:django|flask|rails|struts|phpmyadmin)\b"
    ],
    "Insufficient Logging and Monitoring": [
        r"(?i)\b(?:print|console\.log)\b"
    ]
}

def scan_directory(directory):
    vulnerabilities = []

    for root, dirs, files in os.walk(directory):
        for file in files:
            file_path = os.path.join(root, file)
            with open(file_path, "r", encoding="latin-1") as f:
                content = f.read()
            for vulnerability, patterns in OWASP_TOP_10.items():
                for pattern in patterns:
                    matches = re.findall(pattern, content)
                    if matches:
                        vulnerabilities.append((file_path, vulnerability, matches))

    return vulnerabilities

# Example usage
directory_to_scan = "E:/Repos/VulnerabilityScanner"
print(f"directory: {directory_to_scan}")
vulnerabilities_found = scan_directory(directory_to_scan)

if vulnerabilities_found:
    for file_path, vulnerability, matches in vulnerabilities_found:
        print(f"Vulnerability: {vulnerability}")
        print(f"File: {file_path}")
        print("Matches:")
        for match in matches:
            print(match)
        print()
else:
    print("No vulnerabilities found.")