Gorstaks EDR

 avatar
unknown
powershell
3 months ago
475 kB
5
No Index
# Antivirus.ps1 - Single-file EDR (generated from current Bin logic)
# Author: Gorstak | Usage: .\Antivirus.ps1 | .\Antivirus.ps1 -RemoveRules | .\Antivirus.ps1 -RegisterSchedule | .\Antivirus.ps1 -UnregisterSchedule
#Requires -RunAsAdministrator
param(
    [Parameter(Mandatory=$false)][switch]$RemoveRules = $false,
    [Parameter(Mandatory=$false)][switch]$RegisterSchedule = $false,
    [Parameter(Mandatory=$false)][switch]$UnregisterSchedule = $false
)
$script:ScriptRoot = if ($PSScriptRoot) { $PSScriptRoot } else { Split-Path -Parent $MyInvocation.MyCommand.Path }

# --- OptimizedConfig ---
# Optimized configuration for EDR modules
# Provides tick intervals, scan limits, batch settings, CPU throttling
#Requires -Version 5.1

# Tick intervals (seconds) - aligned with GShield Antivirus.ps1
$script:ModuleTickIntervals = @{
    "HashDetection" = 90
    "ResponseEngine" = 180
    "MemoryScanning" = 90
    "BeaconDetection" = 60
    "NetworkTrafficMonitoring" = 45
    "AMSIBypassDetection" = 90
    "ProcessAnomalyDetection" = 90
    "EventLogMonitoring" = 90
    "FileEntropyDetection" = 120
    "Initializer" = 300
    "PrivacyForgeSpoofing" = 60
    "GSecurityLite" = 60
    "NeuroBehaviorMonitor" = 15
    "PasswordRotator" = 86400
    "YaraDetection" = 120
    "WMIPersistenceDetection" = 60
    "ScheduledTaskDetection" = 60
    "RegistryPersistenceDetection" = 60
    "DLLHijackingDetection" = 60
    "TokenManipulationDetection" = 30
    "ProcessHollowingDetection" = 20
    "KeyloggerDetection" = 30
    "ReflectiveDLLInjectionDetection" = 30
    "RansomwareDetection" = 15
    "NetworkAnomalyDetection" = 30
    "DNSExfiltrationDetection" = 60
    "RootkitDetection" = 60
    "ClipboardMonitoring" = 10
    "COMMonitoring" = 60
    "BrowserExtensionMonitoring" = 60
    "ShadowCopyMonitoring" = 30
    "USBMonitoring" = 30
    "WebcamGuardian" = 20
    "AttackToolsDetection" = 60
    "AdvancedThreatDetection" = 60
    "FirewallRuleMonitoring" = 60
    "ServiceMonitoring" = 60
    "FilelessDetection" = 20
    "NamedPipeMonitoring" = 60
    "CodeInjectionDetection" = 30
    "DataExfiltrationDetection" = 60
    "HoneypotMonitoring" = 300
    "LateralMovementDetection" = 30
    "ProcessCreationDetection" = 60
    "QuarantineManagement" = 300
    "PasswordManagement" = 300
    "IdsDetection" = 60
    "CredentialDumpDetection" = 20
    "LOLBinDetection" = 30
    "MemoryAcquisitionDetection" = 90
    "MobileDeviceMonitoring" = 90
    "CVE-MitigationPatcher" = 3600
    "BCDSecurity" = 300
    "CredentialProtection" = 300
    "HidMacroGuard" = 60
    "LocalProxyDetection" = 60
    "ScriptContentScan" = 120
    "ScriptHostDetection" = 60
    "MitreMapping" = 300
    "RealTimeFileMonitor" = 60
    "AsrRules" = 86400
    "GRulesC2Block" = 3600
    "ProcessAuditing" = 86400
    "KeyScramblerManagement" = 60
    "GFocus" = 2
    "StartupPersistenceDetection" = 120
    "SuspiciousParentChildDetection" = 45
    "ScriptBlockLoggingCheck" = 86400
}

$script:ScanLimits = @{
    "MaxFiles" = 500
    "MaxProcesses" = 500
    "MaxConnections" = 1000
    "MaxEvents" = 500
    "SampleSizeBytes" = 4096
}

function Get-TickInterval {
    param([string]$ModuleName)
    if ($script:ModuleTickIntervals.ContainsKey($ModuleName)) {
        return $script:ModuleTickIntervals[$ModuleName]
    }
    return 90
}

function Get-ScanLimit {
    param([string]$LimitName)
    if ($script:ScanLimits.ContainsKey($LimitName)) {
        return $script:ScanLimits[$LimitName]
    }
    return 500
}

function Get-BatchSettings {
    return @{
        BatchSize = 50
        BatchDelayMs = 10
    }
}

function Get-LoopSleep {
    return 5
}

function Test-CPULoadThreshold {
    try {
        $cpu = Get-Counter '\Processor(_Total)\% Processor Time' -ErrorAction SilentlyContinue
        if ($cpu -and $cpu.CounterSamples[0].CookedValue -gt 90) { return $true }
    } catch { }
    return $false
}

function Get-CPULoad {
    try {
        $cpu = Get-Counter '\Processor(_Total)\% Processor Time' -ErrorAction SilentlyContinue
        if ($cpu) { return [int]$cpu.CounterSamples[0].CookedValue }
    } catch { }
    return 0
}

function Write-Log {
    param(
        [string]$Level,
        [string]$Message,
        [string]$Category = ""
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $output = "[$timestamp] [$Level] $Message"
    
    if ($Category) {
        $output = "[$timestamp] [$Level] [$Category] $Message"
    }
    
    Write-Output $output
}

# Standard detection log format for Response Engine: timestamp|Type|Risk|Details
function Write-DetectionLog {
    param(
        [string]$LogName,
        [string]$DetectionType,
        [string]$Risk,
        [hashtable]$Details = @{}
    )
    $logPath = "$env:ProgramData\Antivirus\Logs\${LogName}_$(Get-Date -Format 'yyyy-MM-dd').log"
    $parts = @()
    if ($Details.ProcessId) { $parts += "PID:$($Details.ProcessId)" }
    if ($Details.ProcessName) { $parts += $Details.ProcessName }
    if ($Details.FilePath) { $parts += $Details.FilePath }
    if ($Details.RemoteAddress) { $parts += $Details.RemoteAddress }
    if ($Details.CommandLine) { $parts += ($Details.CommandLine -replace '\|',' ') }
    foreach ($k in @('Detail','Tool','Type','Path','Value')) {
        if ($Details[$k]) { $parts += $Details[$k] }
    }
    $detailsStr = ($parts -join '|').Trim('|')
    if (-not $detailsStr -and $Details.Count -gt 0) { $detailsStr = ($Details.GetEnumerator() | ForEach-Object { "$($_.Key)=$($_.Value)" }) -join '|' }
    $line = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')|$DetectionType|$Risk|$detailsStr"
    $line | Add-Content -Path $logPath -ErrorAction SilentlyContinue
}

# Deduplication support
$script:ReportedThreats = @{}
$script:ReportedThreatsTTL = 300  # seconds

function Test-Deduplication {
    param([string]$Key)
    
    $now = Get-Date
    
    # Clean old entries
    $expired = @($script:ReportedThreats.Keys | Where-Object { ($now - $script:ReportedThreats[$_]).TotalSeconds -gt $script:ReportedThreatsTTL })
    foreach ($k in $expired) { $script:ReportedThreats.Remove($k) }
    
    if ($script:ReportedThreats.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedThreats[$Key] = $now
    return $true
}

# --- CacheManager ---
# Cache Manager Module
# Provides caching to reduce repeated expensive operations
#Requires -Version 5.1

$script:SignatureCache = @{}
$script:HashCache = @{}
$script:ProcessCache = @{}
$script:LastCacheClean = Get-Date

function Get-CachedSignature {
    param([string]$FilePath)
    
    $now = Get-Date
    $ttl = 60 # minutes
    
    if ($script:SignatureCache.ContainsKey($FilePath)) {
        $cached = $script:SignatureCache[$FilePath]
        if (($now - $cached.Timestamp).TotalMinutes -lt $ttl) {
            return $cached.Value
        }
    }
    
    try {
        $sig = Get-AuthenticodeSignature -FilePath $FilePath -ErrorAction SilentlyContinue
        $script:SignatureCache[$FilePath] = @{
            Value = $sig
            Timestamp = $now
        }
        return $sig
    } catch {
        return $null
    }
}

function Get-CachedFileHash {
    param(
        [string]$FilePath,
        [string]$Algorithm = "MD5"
    )
    
    $now = Get-Date
    $ttl = 120 # minutes
    $key = "$FilePath|$Algorithm"
    
    if ($script:HashCache.ContainsKey($key)) {
        $cached = $script:HashCache[$key]
        $fileInfo = Get-Item $FilePath -ErrorAction SilentlyContinue
        if ($fileInfo -and $cached.LastWrite -eq $fileInfo.LastWriteTime -and ($now - $cached.Timestamp).TotalMinutes -lt $ttl) {
            return $cached.Value
        }
    }
    
    try {
        $fileInfo = Get-Item $FilePath -ErrorAction SilentlyContinue
        if (-not $fileInfo) { return $null }
        
        $hash = (Get-FileHash -Path $FilePath -Algorithm $Algorithm -ErrorAction SilentlyContinue).Hash
        $script:HashCache[$key] = @{
            Value = $hash
            Timestamp = $now
            LastWrite = $fileInfo.LastWriteTime
        }
        return $hash
    } catch {
        return $null
    }
}

function Get-CachedProcess {
    param([int]$ProcessId)
    
    $now = Get-Date
    $ttl = 30 # seconds - processes change frequently
    $key = "$ProcessId"
    
    if ($script:ProcessCache.ContainsKey($key)) {
        $cached = $script:ProcessCache[$key]
        if (($now - $cached.Timestamp).TotalSeconds -lt $ttl) {
            return $cached.Value
        }
    }
    
    try {
        $proc = Get-Process -Id $ProcessId -ErrorAction SilentlyContinue
        if ($proc) {
            $script:ProcessCache[$key] = @{
                Value = $proc
                Timestamp = $now
            }
        }
        return $proc
    } catch {
        return $null
    }
}

function Clear-ExpiredCache {
    $now = Get-Date
    
    if (($now - $script:LastCacheClean).TotalMinutes -lt 30) {
        return
    }
    
    $script:LastCacheClean = $now
    
    # Clean signature cache
    $expiredSigs = @($script:SignatureCache.Keys | Where-Object {
        ($now - $script:SignatureCache[$_].Timestamp).TotalMinutes -gt 60
    })
    foreach ($key in $expiredSigs) {
        $script:SignatureCache.Remove($key)
    }
    
    # Clean hash cache
    $expiredHashes = @($script:HashCache.Keys | Where-Object {
        ($now - $script:HashCache[$_].Timestamp).TotalMinutes -gt 120
    })
    foreach ($key in $expiredHashes) {
        $script:HashCache.Remove($key)
    }
    
    # Clean process cache
    $expiredProcs = @($script:ProcessCache.Keys | Where-Object {
        ($now - $script:ProcessCache[$_].Timestamp).TotalSeconds -gt 60
    })
    foreach ($key in $expiredProcs) {
        $script:ProcessCache.Remove($key)
    }
}

# --- Initializer ---
# Initializer Module
# Sets up the Antivirus EDR environment - runs once at startup - Optimized for low resource usage


$ModuleName = "Initializer"
$script:LastTick = Get-Date
$TickInterval = Get-TickInterval -ModuleName $ModuleName
$Initialized = $false

function Invoke-Initialization {
    try {
        Write-Output "STATS:$ModuleName`:Starting environment initialization"
        
        # Create required directories
        $directories = @(
            "$env:ProgramData\Antivirus",
            "$env:ProgramData\Antivirus\Logs",
            "$env:ProgramData\Antivirus\Data",
            "$env:ProgramData\Antivirus\Modules", 
            "$env:ProgramData\Antivirus\Quarantine",
            "$env:ProgramData\Antivirus\Reports"
        )
        
        foreach ($dir in $directories) {
            if (-not (Test-Path $dir)) {
                New-Item -Path $dir -ItemType Directory -Force | Out-Null
                Write-Output "STATS:$ModuleName`:Created directory: $dir"
            }
        }
        
        # Initialize log files with headers
        $logFiles = @(
            "$env:ProgramData\Antivirus\Logs\System_$(Get-Date -Format 'yyyy-MM-dd').log",
            "$env:ProgramData\Antivirus\Logs\Threats_$(Get-Date -Format 'yyyy-MM-dd').log",
            "$env:ProgramData\Antivirus\Logs\Responses_$(Get-Date -Format 'yyyy-MM-dd').log"
        )
        
        foreach ($logFile in $logFiles) {
            if (-not (Test-Path $logFile)) {
                $header = "# Antivirus EDR Log - Created $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')`n# Format: Timestamp|Module|Action|Details`n"
                Set-Content -Path $logFile -Value $header
                Write-Output "STATS:$ModuleName`:Initialized log: $logFile"
            }
        }
        
        # Create Event Log source if it doesn't exist
        try {
            if (-not [System.Diagnostics.EventLog]::SourceExists("AntivirusEDR")) {
                [System.Diagnostics.EventLog]::CreateEventSource("AntivirusEDR", "Application")
                Write-Output "STATS:$ModuleName`:Created Event Log source: AntivirusEDR"
            }
        } catch {
            Write-Output "ERROR:$ModuleName`:Failed to create Event Log source: $_"
        }
        
        # Initialize configuration file
        $configFile = "$env:ProgramData\Antivirus\Data\config.json"
        if (-not (Test-Path $configFile)) {
            $defaultConfig = @{
                Version = "1.0"
                Initialized = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
                LastUpdate = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
                Settings = @{
                    MaxLogSizeMB = 100
                    QuarantineRetentionDays = 30
                    EnableRealTimeResponse = $true
                    ResponseSeverity = "Medium"
                }
            }
            $defaultConfig | ConvertTo-Json -Depth 3 | Set-Content -Path $configFile
            Write-Output "STATS:$ModuleName`:Created configuration file"
        }
        
        # Create status tracking file
        $statusFile = "$env:ProgramData\Antivirus\Data\agent_status.json"
        if (-not (Test-Path $statusFile)) {
            $statusTemplate = @{
                LastCheck = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
                ActiveAgents = @()
                SystemHealth = "Healthy"
                TotalDetections = 0
                TotalResponses = 0
            }
            $statusTemplate | ConvertTo-Json -Depth 3 | Set-Content -Path $statusFile
            Write-Output "STATS:$ModuleName`:Created agent status file"
        }
        
        # Create whitelist file
        $whitelistFile = "$env:ProgramData\Antivirus\Data\whitelist.json"
        if (-not (Test-Path $whitelistFile)) {
            $defaultWhitelist = @{
                Processes = @("explorer.exe", "svchost.exe", "System", "csrss.exe", "wininit.exe", "services.exe", "lsass.exe", "dwm.exe")
                Paths = @("$env:SystemRoot\System32", "$env:SystemRoot\SysWOW64", "$env:ProgramFiles", "${env:ProgramFiles(x86)}")
                Hashes = @()
                Publishers = @("Microsoft Corporation", "Microsoft Windows")
            }
            $defaultWhitelist | ConvertTo-Json -Depth 3 | Set-Content -Path $whitelistFile
            Write-Output "STATS:$ModuleName`:Created whitelist file"
        }
        
        # Create threat database placeholder
        $threatDbFile = "$env:ProgramData\Antivirus\Data\threat_database.json"
        if (-not (Test-Path $threatDbFile)) {
            $defaultThreatDb = @{
                Version = "1.0"
                LastUpdate = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
                Hashes = @{}
                Signatures = @()
            }
            $defaultThreatDb | ConvertTo-Json -Depth 3 | Set-Content -Path $threatDbFile
            Write-Output "STATS:$ModuleName`:Created threat database"
        }
        
        Write-Output "STATS:$ModuleName`:Environment initialization complete"
        return $true
    }
    catch {
        Write-Output "ERROR:$ModuleName`:Initialization failed: $_"
        return $false
    }
}

if (-not $ModuleConfig) {
    Invoke-Initialization
}

# --- HashDetection ---
# Returns true if hash is in local threat database (HashDatabasePath). Loads DB on first use.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "HashDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "hashdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-HashDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-HashDetection

# --- AMSIBypassDetection ---
# Detects AMSI bypass techniques (amsi.dll patching, etc.).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "AMSIBypassDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "amsibypassdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against BypassPatterns patterns
        foreach ($pattern in $script:BypassPatterns) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_AMSIBypassDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "AMSIBypassDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-AMSIBypassDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-AMSIBypassDetection

# --- GFocus ---
# Remote ports indicating proxy usage (quantum threat) - connections to these are blocked.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "GFocus"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 2
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Network-based detection
    try {
        $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue
        
        foreach ($conn in $connections) {
            $remoteIP = $conn.RemoteAddress
            $remotePort = $conn.RemotePort
            $localPort = $conn.LocalPort
            $owningPid = $conn.OwningProcess
            
            # Check for suspicious ports
            $suspiciousPorts = @(4444, 5555, 6666, 1337, 31337, 8080, 8443, 9001, 9090)
            if ($suspiciousPorts -contains $remotePort -or $suspiciousPorts -contains $localPort) {
                $proc = Get-Process -Id $owningPid -ErrorAction SilentlyContinue
                $key = "Net_${owningPid}_${remoteIP}_${remotePort}"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious network connection: $($proc.Name) (PID: $owningPid) -> ${remoteIP}:${remotePort}"
                }
            }
        }
    }
    catch {
        # Silent continue on network errors
    }
}
# Main execution
function Invoke-GFocus {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-GFocus

# --- ResponseEngine ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "ResponseEngine"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 180
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "responseengine_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # Network-based detection
    try {
        $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue
        
        foreach ($conn in $connections) {
            $remoteIP = $conn.RemoteAddress
            $remotePort = $conn.RemotePort
            $localPort = $conn.LocalPort
            $owningPid = $conn.OwningProcess
            
            # Check for suspicious ports
            $suspiciousPorts = @(4444, 5555, 6666, 1337, 31337, 8080, 8443, 9001, 9090)
            if ($suspiciousPorts -contains $remotePort -or $suspiciousPorts -contains $localPort) {
                $proc = Get-Process -Id $owningPid -ErrorAction SilentlyContinue
                $key = "Net_${owningPid}_${remoteIP}_${remotePort}"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious network connection: $($proc.Name) (PID: $owningPid) -> ${remoteIP}:${remotePort}"
                }
            }
        }
    }
    catch {
        # Silent continue on network errors
    }
    # Driver monitoring
    try {
        $drivers = Get-CimInstance Win32_SystemDriver -ErrorAction SilentlyContinue | 
                   Where-Object { $_.State -eq "Running" }
        
        foreach ($drv in $drivers) {
            if ($drv.PathName) {
                $pathLower = $drv.PathName.ToLower()
                
                # Check for drivers loaded from non-standard paths
                if ($pathLower -notmatch "system32\\drivers|windows") {
                    $key = "Drv_$($drv.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Non-standard driver path: $($drv.Name) - $($drv.PathName)" -Level "WARNING"
                    }
                }
            }
        }
    }
    catch {
        # Silent continue on driver errors
    }
}
# Main execution
function Invoke-ResponseEngine {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-ResponseEngine

# --- BeaconDetection ---
# Detects potential C2 beaconing (periodic outbound connections to unusual ports).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "BeaconDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 60
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "beacondetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Network-based detection
    try {
        $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue
        
        foreach ($conn in $connections) {
            $remoteIP = $conn.RemoteAddress
            $remotePort = $conn.RemotePort
            $localPort = $conn.LocalPort
            $owningPid = $conn.OwningProcess
            
            # Check for suspicious ports
            $suspiciousPorts = @(4444, 5555, 6666, 1337, 31337, 8080, 8443, 9001, 9090)
            if ($suspiciousPorts -contains $remotePort -or $suspiciousPorts -contains $localPort) {
                $proc = Get-Process -Id $owningPid -ErrorAction SilentlyContinue
                $key = "Net_${owningPid}_${remoteIP}_${remotePort}"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious network connection: $($proc.Name) (PID: $owningPid) -> ${remoteIP}:${remotePort}"
                }
            }
        }
    }
    catch {
        # Silent continue on network errors
    }
}
# Main execution
function Invoke-BeaconDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-BeaconDetection

# --- NetworkTrafficMonitoring ---
# Monitors TCP/UDP connections and network statistics for anomalies.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "NetworkTrafficMonitoring"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 45
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "networktrafficmonitoring_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Generic process monitoring
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | 
                 Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        
        # Add job-specific detection logic here based on patterns
        # This is a fallback for jobs that need manual review
        
        Write-Detection "Monitoring active for $ModuleName" -Level "INFO"
        break  # Only log once per run
    }
}
# Main execution
function Invoke-NetworkTrafficMonitoring {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-NetworkTrafficMonitoring

# --- ProcessAnomalyDetection ---
# Detects process anomalies: unusual parent-child relationships, injection indicators, suspicious modules.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "ProcessAnomalyDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "processanomalydetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against SystemBinaries patterns
        foreach ($pattern in $script:SystemBinaries) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_ProcessAnomalyDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "ProcessAnomalyDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
}
# Main execution
function Invoke-ProcessAnomalyDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-ProcessAnomalyDetection

# --- EventLogMonitoring ---
# Monitors Security and Application event logs for failures, privilege escalation, log clearing (from AgentsAntivirus).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "EventLogMonitoring"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 60
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "eventlogmonitoring_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Generic process monitoring
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | 
                 Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        
        # Add job-specific detection logic here based on patterns
        # This is a fallback for jobs that need manual review
        
        Write-Detection "Monitoring active for $ModuleName" -Level "INFO"
        break  # Only log once per run
    }
}
# Main execution
function Invoke-EventLogMonitoring {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-EventLogMonitoring

# --- FileEntropyDetection ---
# Detects high-entropy files (packed, encrypted) as potential malware. Runs CleanGuard on matches.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "FileEntropyDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 120
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "fileentropydetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-FileEntropyDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-FileEntropyDetection

# --- YaraDetection ---
# Runs YARA rules against suspicious files. Quarantines on match when CleanGuard concurs.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "YaraDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

$script:VcDlls = @(
        "vcruntime140.dll",
        "msvcp140.dll"
    )

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "yaradetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-YaraDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-YaraDetection

# --- WMIPersistenceDetection ---
# Monitors WMI event subscriptions for persistence (EventConsumer, Filter, Binding).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "WMIPersistenceDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 120
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "wmipersistencedetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
    # Scheduled task detection
    try {
        $tasks = Get-ScheduledTask -ErrorAction SilentlyContinue | 
                 Where-Object { $_.State -ne "Disabled" }
        
        foreach ($task in $tasks) {
            $actions = $task.Actions
            foreach ($action in $actions) {
                if ($action.Execute) {
                    $execLower = $action.Execute.ToLower()
                    
                    # Check for suspicious task actions
                    if ($execLower -match "powershell|cmd|wscript|cscript|mshta|rundll32") {
                        $key = "Task_$($task.TaskName)"
                        if (Test-ShouldReport -Key $key) {
                            Write-Detection "Suspicious scheduled task: $($task.TaskName) - $($action.Execute) $($action.Arguments)" -Level "WARNING"
                        }
                    }
                }
            }
        }
    }
    catch {
        # Silent continue on task errors
    }
}
# Main execution
function Invoke-WMIPersistenceDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-WMIPersistenceDetection

# --- ScheduledTaskDetection ---
# Monitors scheduled tasks for suspicious actions or triggers (persistence detection).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "ScheduledTaskDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 120
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "scheduledtaskdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Scheduled task detection
    try {
        $tasks = Get-ScheduledTask -ErrorAction SilentlyContinue | 
                 Where-Object { $_.State -ne "Disabled" }
        
        foreach ($task in $tasks) {
            $actions = $task.Actions
            foreach ($action in $actions) {
                if ($action.Execute) {
                    $execLower = $action.Execute.ToLower()
                    
                    # Check for suspicious task actions
                    if ($execLower -match "powershell|cmd|wscript|cscript|mshta|rundll32") {
                        $key = "Task_$($task.TaskName)"
                        if (Test-ShouldReport -Key $key) {
                            Write-Detection "Suspicious scheduled task: $($task.TaskName) - $($action.Execute) $($action.Arguments)" -Level "WARNING"
                        }
                    }
                }
            }
        }
    }
    catch {
        # Silent continue on task errors
    }
}
# Main execution
function Invoke-ScheduledTaskDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-ScheduledTaskDetection

# --- RegistryPersistenceDetection ---
# Monitors registry Run keys for suspicious patterns and unsigned executables (from AgentsAntivirus logic).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "RegistryPersistenceDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 120
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "registrypersistencedetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-RegistryPersistenceDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-RegistryPersistenceDetection

# --- DLLHijackingDetection ---
# DLL Explorer–style: scans loaded DLLs only. Removes *_elf.dll always, and suspicious/unsigned loaded DLLs. Automated response: kill host process, quarantine DLL.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "DLLHijackingDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "dllhijackingdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-DLLHijackingDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-DLLHijackingDetection

# --- TokenManipulationDetection ---
# Detects token manipulation (privilege escalation, impersonation) via loaded modules and behavior.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "TokenManipulationDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 30
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "tokenmanipulationdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Generic process monitoring
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | 
                 Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        
        # Add job-specific detection logic here based on patterns
        # This is a fallback for jobs that need manual review
        
        Write-Detection "Monitoring active for $ModuleName" -Level "INFO"
        break  # Only log once per run
    }
}
# Main execution
function Invoke-TokenManipulationDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-TokenManipulationDetection

# --- ProcessHollowingDetection ---
# Detects process hollowing: parent-child mismatch, path/image mismatch, unusual loaded modules.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "ProcessHollowingDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 20
$script:SelfPid = $PID

$script:SuspiciousParents = @(
        "winlogon.exe",
        "services.exe"
    )

$script:SuspiciousChildren = @(
        "cmd.exe",
        "powershell.exe",
        "pwsh.exe",
        "wmic.exe",
        "rundll32.exe"
    )

$script:LegitNames = @(
        "svchost.exe",
        "explorer.exe",
        "notepad.exe",
        "calc.exe",
        "dwm.exe"
    )

$script:TrustedModules = @(
        "kernel32.dll",
        "ntdll.dll",
        "user32.dll"
    )

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "processhollowingdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-ProcessHollowingDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-ProcessHollowingDetection

# --- KeyloggerDetection ---
# Detects keylogger indicators: keyboard hooks, raw input monitoring, low-level hooks, suspicious loaded modules.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "KeyloggerDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 45
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "keyloggerdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against CommandLinePatterns patterns
        foreach ($pattern in $script:CommandLinePatterns) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_KeyloggerDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "KeyloggerDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }        
        # Check against SuspiciousWindowTitles patterns
        foreach ($pattern in $script:SuspiciousWindowTitles) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_KeyloggerDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "KeyloggerDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }        
        # Check against SuspiciousModuleNames patterns
        foreach ($pattern in $script:SuspiciousModuleNames) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_KeyloggerDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "KeyloggerDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
}
# Main execution
function Invoke-KeyloggerDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-KeyloggerDetection

# --- ReflectiveDLLInjectionDetection ---
# Detects reflective DLL injection (DLL loaded without LoadLibrary, etc.).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "ReflectiveDLLInjectionDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "reflectivedllinjectiondetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against Patterns patterns
        foreach ($pattern in $script:Patterns) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_ReflectiveDLLInjectionDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "ReflectiveDLLInjectionDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
}
# Main execution
function Invoke-ReflectiveDLLInjectionDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-ReflectiveDLLInjectionDetection

# --- RansomwareDetection ---
# Detects ransomware behavior: command-line patterns, ransom notes, shadow copy deletion (from AgentsAntivirus).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "RansomwareDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 15
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "ransomwaredetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against Patterns patterns
        foreach ($pattern in $script:Patterns) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_RansomwareDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "RansomwareDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }        
        # Check against RansomNoteNames patterns
        foreach ($pattern in $script:RansomNoteNames) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_RansomwareDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "RansomwareDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
}
# Main execution
function Invoke-RansomwareDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-RansomwareDetection

# --- NetworkAnomalyDetection ---
# Detects anomalous network behavior (suspicious ports, unusual connections).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "NetworkAnomalyDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "networkanomalydetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Network-based detection
    try {
        $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue
        
        foreach ($conn in $connections) {
            $remoteIP = $conn.RemoteAddress
            $remotePort = $conn.RemotePort
            $localPort = $conn.LocalPort
            $owningPid = $conn.OwningProcess
            
            # Check for suspicious ports
            $suspiciousPorts = @(4444, 5555, 6666, 1337, 31337, 8080, 8443, 9001, 9090)
            if ($suspiciousPorts -contains $remotePort -or $suspiciousPorts -contains $localPort) {
                $proc = Get-Process -Id $owningPid -ErrorAction SilentlyContinue
                $key = "Net_${owningPid}_${remoteIP}_${remotePort}"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious network connection: $($proc.Name) (PID: $owningPid) -> ${remoteIP}:${remotePort}"
                }
            }
        }
    }
    catch {
        # Silent continue on network errors
    }
}
# Main execution
function Invoke-NetworkAnomalyDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-NetworkAnomalyDetection

# --- DNSExfiltrationDetection ---
# Monitors DNS traffic for potential exfiltration (unusual queries, tunneling).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "DNSExfiltrationDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "dnsexfiltrationdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against DnsExfilProcessNames patterns
        foreach ($pattern in $script:DnsExfilProcessNames) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_DNSExfiltrationDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "DNSExfiltrationDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }        
        # Check against DnsTunnelingTools patterns
        foreach ($pattern in $script:DnsTunnelingTools) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_DNSExfiltrationDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "DNSExfiltrationDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
}
# Main execution
function Invoke-DNSExfiltrationDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-DNSExfiltrationDetection

# --- RootkitDetection ---
# Detects and terminates rootkit indicators: hidden processes, suspicious drivers, boot entries, non-standard services.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "RootkitDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 180
$script:SelfPid = $PID

$script:CriticalBcdIds = @()

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "rootkitdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
    # Service-based detection
    try {
        $services = Get-CimInstance Win32_Service -ErrorAction SilentlyContinue | 
                    Where-Object { $_.State -eq "Running" -and $_.PathName }
        
        foreach ($svc in $services) {
            $pathLower = $svc.PathName.ToLower()
            
            # Check for services running from suspicious locations
            if ($pathLower -notmatch "system32|program files|windows") {
                $key = "Svc_$($svc.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Non-standard service path: $($svc.Name) - $($svc.PathName)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on service errors
    }
    # Driver monitoring
    try {
        $drivers = Get-CimInstance Win32_SystemDriver -ErrorAction SilentlyContinue | 
                   Where-Object { $_.State -eq "Running" }
        
        foreach ($drv in $drivers) {
            if ($drv.PathName) {
                $pathLower = $drv.PathName.ToLower()
                
                # Check for drivers loaded from non-standard paths
                if ($pathLower -notmatch "system32\\drivers|windows") {
                    $key = "Drv_$($drv.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Non-standard driver path: $($drv.Name) - $($drv.PathName)" -Level "WARNING"
                    }
                }
            }
        }
    }
    catch {
        # Silent continue on driver errors
    }
}
# Main execution
function Invoke-RootkitDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-RootkitDetection

# --- ClipboardMonitoring ---
# Monitors clipboard for sensitive content (credentials, credit cards) or exfiltration patterns.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "ClipboardMonitoring"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "clipboardmonitoring_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Generic process monitoring
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | 
                 Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        
        # Add job-specific detection logic here based on patterns
        # This is a fallback for jobs that need manual review
        
        Write-Detection "Monitoring active for $ModuleName" -Level "INFO"
        break  # Only log once per run
    }
}
# Main execution
function Invoke-ClipboardMonitoring {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-ClipboardMonitoring

# --- COMMonitoring ---
# Monitors COM object usage and COM hijacking (suspicious command lines, non-system InprocServer32, registration spikes).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "COMMonitoring"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 120
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "commonitoring_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against SuspiciousCOMObjects patterns
        foreach ($pattern in $script:SuspiciousCOMObjects) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_COMMonitoring_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "COMMonitoring detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
}
# Main execution
function Invoke-COMMonitoring {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-COMMonitoring

# --- BrowserExtensionMonitoring ---
# Monitors browser extensions for malicious or policy-violating add-ons.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "BrowserExtensionMonitoring"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 300
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "browserextensionmonitoring_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Generic process monitoring
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | 
                 Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        
        # Add job-specific detection logic here based on patterns
        # This is a fallback for jobs that need manual review
        
        Write-Detection "Monitoring active for $ModuleName" -Level "INFO"
        break  # Only log once per run
    }
}
# Main execution
function Invoke-BrowserExtensionMonitoring {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-BrowserExtensionMonitoring

# --- ShadowCopyMonitoring ---
# Monitors shadow copy / VSS for deletion or tampering (ransomware indicator).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "ShadowCopyMonitoring"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "shadowcopymonitoring_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
            }
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
    # Service-based detection
    try {
        $services = Get-CimInstance Win32_Service -ErrorAction SilentlyContinue | 
                    Where-Object { $_.State -eq "Running" -and $_.PathName }
        
        foreach ($svc in $services) {
            $pathLower = $svc.PathName.ToLower()
            
            # Check for services running from suspicious locations
            if ($pathLower -notmatch "system32|program files|windows") {
                $key = "Svc_$($svc.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Non-standard service path: $($svc.Name) - $($svc.PathName)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on service errors
    }
}
# Main execution
function Invoke-ShadowCopyMonitoring {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-ShadowCopyMonitoring

# --- USBMonitoring ---
# Monitors USB device connections for autorun or suspicious device classes.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "USBMonitoring"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "usbmonitoring_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
}
# Main execution
function Invoke-USBMonitoring {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-USBMonitoring

# --- WebcamGuardian ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "WebcamGuardian"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 10
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "webcamguardian_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
}
# Main execution
function Invoke-WebcamGuardian {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-WebcamGuardian

# --- AttackToolsDetection ---
# Detects known attack tools (Mimikatz, Cobalt Strike, etc.) via process and module analysis.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "AttackToolsDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "attacktoolsdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against Tools patterns
        foreach ($pattern in $script:Tools) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_AttackToolsDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "AttackToolsDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
}
# Main execution
function Invoke-AttackToolsDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-AttackToolsDetection

# --- AdvancedThreatDetection ---
# Advanced threat scan over suspicious paths. Quarantines files flagged by CleanGuard.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "AdvancedThreatDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "advancedthreatdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-AdvancedThreatDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-AdvancedThreatDetection

# --- FirewallRuleMonitoring ---
# Monitors firewall rules for unauthorized changes or malicious additions.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "FirewallRuleMonitoring"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 120
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "firewallrulemonitoring_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Generic process monitoring
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | 
                 Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        
        # Add job-specific detection logic here based on patterns
        # This is a fallback for jobs that need manual review
        
        Write-Detection "Monitoring active for $ModuleName" -Level "INFO"
        break  # Only log once per run
    }
}
# Main execution
function Invoke-FirewallRuleMonitoring {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-FirewallRuleMonitoring

# --- ServiceMonitoring ---
# Monitors Windows services: unsigned executables, non-system paths, SYSTEM services outside Windows, critical services stopped (from AgentsAntivirus).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "ServiceMonitoring"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 60
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "servicemonitoring_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
    # Service-based detection
    try {
        $services = Get-CimInstance Win32_Service -ErrorAction SilentlyContinue | 
                    Where-Object { $_.State -eq "Running" -and $_.PathName }
        
        foreach ($svc in $services) {
            $pathLower = $svc.PathName.ToLower()
            
            # Check for services running from suspicious locations
            if ($pathLower -notmatch "system32|program files|windows") {
                $key = "Svc_$($svc.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Non-standard service path: $($svc.Name) - $($svc.PathName)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on service errors
    }
}
# Main execution
function Invoke-ServiceMonitoring {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-ServiceMonitoring

# --- FilelessDetection ---
# Detects fileless malware (scripts in memory, WMI, registry-based execution).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "FilelessDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "filelessdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against FilelessIndicators patterns
        foreach ($pattern in $script:FilelessIndicators) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_FilelessDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "FilelessDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
}
# Main execution
function Invoke-FilelessDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-FilelessDetection

# --- MemoryScanning ---
# Scans process memory for known malware signatures or injection artifacts.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "MemoryScanning"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "memoryscanning_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Generic process monitoring
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | 
                 Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        
        # Add job-specific detection logic here based on patterns
        # This is a fallback for jobs that need manual review
        
        Write-Detection "Monitoring active for $ModuleName" -Level "INFO"
        break  # Only log once per run
    }
}
# Main execution
function Invoke-MemoryScanning {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-MemoryScanning

# --- NamedPipeMonitoring ---
# Monitors named pipes for suspicious C2/lateral movement patterns (paexec, psexec, mimikatz, random names) from AgentsAntivirus.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "NamedPipeMonitoring"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 45
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "namedpipemonitoring_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
}
# Main execution
function Invoke-NamedPipeMonitoring {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-NamedPipeMonitoring

# --- CodeInjectionDetection ---
# Detects code injection (VirtualAllocEx, WriteProcessMemory, CreateRemoteThread patterns).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "CodeInjectionDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "codeinjectiondetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against Patterns patterns
        foreach ($pattern in $script:Patterns) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_CodeInjectionDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "CodeInjectionDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
}
# Main execution
function Invoke-CodeInjectionDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-CodeInjectionDetection

# --- DataExfiltrationDetection ---
# Detects data exfiltration via network, clipboard, or file transfer patterns.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "DataExfiltrationDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "dataexfiltrationdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
            }
}
# Main execution
function Invoke-DataExfiltrationDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-DataExfiltrationDetection

# --- HoneypotMonitoring ---
# Monitors honeypot/decanoy files for tampering (ransomware, wiper detection).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "HoneypotMonitoring"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "honeypotmonitoring_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-HoneypotMonitoring {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-HoneypotMonitoring

# --- LateralMovementDetection ---
# Detects lateral movement (PsExec, WMI, RDP, etc.) via process and network analysis.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "LateralMovementDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "lateralmovementdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against Patterns patterns
        foreach ($pattern in $script:Patterns) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_LateralMovementDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "LateralMovementDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
    # Scheduled task detection
    try {
        $tasks = Get-ScheduledTask -ErrorAction SilentlyContinue | 
                 Where-Object { $_.State -ne "Disabled" }
        
        foreach ($task in $tasks) {
            $actions = $task.Actions
            foreach ($action in $actions) {
                if ($action.Execute) {
                    $execLower = $action.Execute.ToLower()
                    
                    # Check for suspicious task actions
                    if ($execLower -match "powershell|cmd|wscript|cscript|mshta|rundll32") {
                        $key = "Task_$($task.TaskName)"
                        if (Test-ShouldReport -Key $key) {
                            Write-Detection "Suspicious scheduled task: $($task.TaskName) - $($action.Execute) $($action.Arguments)" -Level "WARNING"
                        }
                    }
                }
            }
        }
    }
    catch {
        # Silent continue on task errors
    }
}
# Main execution
function Invoke-LateralMovementDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-LateralMovementDetection

# --- ProcessCreationDetection ---
# Monitors process creation events. Entry point for behavioral analysis pipeline.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "ProcessCreationDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 120
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "processcreationdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against SuspiciousParentNames patterns
        foreach ($pattern in $script:SuspiciousParentNames) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_ProcessCreationDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "ProcessCreationDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }        
        # Check against SuspiciousChildPaths patterns
        foreach ($pattern in $script:SuspiciousChildPaths) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_ProcessCreationDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "ProcessCreationDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }        
        # Check against DocumentViewerParents patterns
        foreach ($pattern in $script:DocumentViewerParents) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_ProcessCreationDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "ProcessCreationDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }        
        # Check against ForbiddenScriptChildren patterns
        foreach ($pattern in $script:ForbiddenScriptChildren) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_ProcessCreationDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "ProcessCreationDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
}
# Main execution
function Invoke-ProcessCreationDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-ProcessCreationDetection

# --- QuarantineManagement ---
# Manages quarantine folder: strips execute on files, kills processes running from quarantine, watches for dropped executables.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "QuarantineManagement"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 60
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "quarantinemanagement_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-QuarantineManagement {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-QuarantineManagement

# --- PrivacyForgeSpoofing ---
# Rotate identity at most this often (seconds).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "PrivacyForgeSpoofing"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 300
$script:SelfPid = $PID

$script:FingerprintHeavyProcesses = @(
        "discord",
        "discordptb",
        "discorddevelopment",
        "slack",
        "teams",
        "ms-teams",
        "steam",
        "steamwebhelper",
        "epicgameslauncher",
        "spotify",
        "zoom",
        "skype",
        "chrome",
        "firefox",
        "msedge",
        "edge",
        "opera",
        "brave",
        "vivaldi",
        "chromium",
        "code",
        "devenv",
        "threads",
        "instagram",
        "twitter",
        "x",
        "telegram",
        "whatsapp",
        "signal",
        "twitch",
        "obs",
        "streamlabs",
        "epicgameslauncher",
        "gog galaxy",
        "ea app",
        "ubisoft connect",
        "line",
        "wechat",
        "messenger",
        "teams legacy",
        "element",
        "element desktop"
    )

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "privacyforgespoofing_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-PrivacyForgeSpoofing {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-PrivacyForgeSpoofing

# --- PasswordManagement ---
# Monitors password policy, plaintext password files, and failed logon attempts.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "PasswordManagement"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 300
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "passwordmanagement_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
}
# Main execution
function Invoke-PasswordManagement {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-PasswordManagement

# --- IdsDetection ---
# Intrusion detection: correlates events for multi-stage attack patterns.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "IdsDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 45
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "idsdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against IdsSignatures patterns
        foreach ($pattern in $script:IdsSignatures) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_IdsDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "IdsDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
    # Scheduled task detection
    try {
        $tasks = Get-ScheduledTask -ErrorAction SilentlyContinue | 
                 Where-Object { $_.State -ne "Disabled" }
        
        foreach ($task in $tasks) {
            $actions = $task.Actions
            foreach ($action in $actions) {
                if ($action.Execute) {
                    $execLower = $action.Execute.ToLower()
                    
                    # Check for suspicious task actions
                    if ($execLower -match "powershell|cmd|wscript|cscript|mshta|rundll32") {
                        $key = "Task_$($task.TaskName)"
                        if (Test-ShouldReport -Key $key) {
                            Write-Detection "Suspicious scheduled task: $($task.TaskName) - $($action.Execute) $($action.Arguments)" -Level "WARNING"
                        }
                    }
                }
            }
        }
    }
    catch {
        # Silent continue on task errors
    }
}
# Main execution
function Invoke-IdsDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-IdsDetection

# --- CredentialDumpDetection ---
# Detects credential dumping: LSASS access, registry hive access, memory dump creation, known tools.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "CredentialDumpDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "credentialdumpdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against CredentialTools patterns
        foreach ($pattern in $script:CredentialTools) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_CredentialDumpDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "CredentialDumpDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
}
# Main execution
function Invoke-CredentialDumpDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-CredentialDumpDetection

# --- LOLBinDetection ---
# Detects LOLBins (Living-Off-the-Land binaries) misuse: mshta, certutil, bitsadmin, etc. Suspends or kills based on severity.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "LOLBinDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "lolbindetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
            }
    # Scheduled task detection
    try {
        $tasks = Get-ScheduledTask -ErrorAction SilentlyContinue | 
                 Where-Object { $_.State -ne "Disabled" }
        
        foreach ($task in $tasks) {
            $actions = $task.Actions
            foreach ($action in $actions) {
                if ($action.Execute) {
                    $execLower = $action.Execute.ToLower()
                    
                    # Check for suspicious task actions
                    if ($execLower -match "powershell|cmd|wscript|cscript|mshta|rundll32") {
                        $key = "Task_$($task.TaskName)"
                        if (Test-ShouldReport -Key $key) {
                            Write-Detection "Suspicious scheduled task: $($task.TaskName) - $($action.Execute) $($action.Arguments)" -Level "WARNING"
                        }
                    }
                }
            }
        }
    }
    catch {
        # Silent continue on task errors
    }
}
# Main execution
function Invoke-LOLBinDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-LOLBinDetection

# --- MemoryAcquisitionDetection ---
# Detects pmem/WinPmem and similar physical memory acquisition tools used for credential theft.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "MemoryAcquisitionDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "memoryacquisitiondetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against ProcessPatterns patterns
        foreach ($pattern in $script:ProcessPatterns) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_MemoryAcquisitionDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "MemoryAcquisitionDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }        
        # Check against CommandLinePatterns patterns
        foreach ($pattern in $script:CommandLinePatterns) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_MemoryAcquisitionDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "MemoryAcquisitionDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
}
# Main execution
function Invoke-MemoryAcquisitionDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-MemoryAcquisitionDetection

# --- MobileDeviceMonitoring ---
# Monitors mobile device connections (MTP, etc.) for policy compliance.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "MobileDeviceMonitoring"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "mobiledevicemonitoring_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
}
# Main execution
function Invoke-MobileDeviceMonitoring {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-MobileDeviceMonitoring

# --- BCDSecurity ---
# BCD Security - Boot Configuration Data protection and cleanup
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "BCDSecurity"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 600
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "bcdsecurity_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Generic process monitoring
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | 
                 Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        
        # Add job-specific detection logic here based on patterns
        # This is a fallback for jobs that need manual review
        
        Write-Detection "Monitoring active for $ModuleName" -Level "INFO"
        break  # Only log once per run
    }
}
# Main execution
function Invoke-BCDSecurity {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-BCDSecurity

# --- CredentialProtection ---
# Remove legacy random-password task and script if present (no longer used).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "CredentialProtection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 300
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "credentialprotection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # Scheduled task detection
    try {
        $tasks = Get-ScheduledTask -ErrorAction SilentlyContinue | 
                 Where-Object { $_.State -ne "Disabled" }
        
        foreach ($task in $tasks) {
            $actions = $task.Actions
            foreach ($action in $actions) {
                if ($action.Execute) {
                    $execLower = $action.Execute.ToLower()
                    
                    # Check for suspicious task actions
                    if ($execLower -match "powershell|cmd|wscript|cscript|mshta|rundll32") {
                        $key = "Task_$($task.TaskName)"
                        if (Test-ShouldReport -Key $key) {
                            Write-Detection "Suspicious scheduled task: $($task.TaskName) - $($action.Execute) $($action.Arguments)" -Level "WARNING"
                        }
                    }
                }
            }
        }
    }
    catch {
        # Silent continue on task errors
    }
    # Driver monitoring
    try {
        $drivers = Get-CimInstance Win32_SystemDriver -ErrorAction SilentlyContinue | 
                   Where-Object { $_.State -eq "Running" }
        
        foreach ($drv in $drivers) {
            if ($drv.PathName) {
                $pathLower = $drv.PathName.ToLower()
                
                # Check for drivers loaded from non-standard paths
                if ($pathLower -notmatch "system32\\drivers|windows") {
                    $key = "Drv_$($drv.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Non-standard driver path: $($drv.Name) - $($drv.PathName)" -Level "WARNING"
                    }
                }
            }
        }
    }
    catch {
        # Silent continue on driver errors
    }
}
# Main execution
function Invoke-CredentialProtection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-CredentialProtection

# --- HidMacroGuard ---
# Detects and removes malicious macros/payload-on-button configurations from USB HID devices (mice, keyboards, macro pads).
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "HidMacroGuard"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 300
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "hidmacroguard_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Generic process monitoring
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | 
                 Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        
        # Add job-specific detection logic here based on patterns
        # This is a fallback for jobs that need manual review
        
        Write-Detection "Monitoring active for $ModuleName" -Level "INFO"
        break  # Only log once per run
    }
}
# Main execution
function Invoke-HidMacroGuard {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-HidMacroGuard

# --- LocalProxyDetection ---
# Detects local proxy pattern (listen on localhost + outbound 443) used by Shadow TLS and similar TLS camouflage tools.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "LocalProxyDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 60
$script:SelfPid = $PID

$script:BrowserProcessNames = @(
        "chrome",
        "firefox",
        "msedge",
        "iexplore",
        "opera",
        "brave",
        "vivaldi",
        "waterfox",
        "palemoon",
        "seamonkey",
        "librewolf",
        "tor",
        "dragon",
        "iridium",
        "chromium",
        "maxthon",
        "slimjet",
        "citrio",
        "browser",
        "edge",
        "edgedev",
        "edgebeta",
        "edgecanary",
        "operagx",
        "operaneon",
        "naver",
        "whale",
        "yandex"
    )

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "localproxydetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Network-based detection
    try {
        $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue
        
        foreach ($conn in $connections) {
            $remoteIP = $conn.RemoteAddress
            $remotePort = $conn.RemotePort
            $localPort = $conn.LocalPort
            $owningPid = $conn.OwningProcess
            
            # Check for suspicious ports
            $suspiciousPorts = @(4444, 5555, 6666, 1337, 31337, 8080, 8443, 9001, 9090)
            if ($suspiciousPorts -contains $remotePort -or $suspiciousPorts -contains $localPort) {
                $proc = Get-Process -Id $owningPid -ErrorAction SilentlyContinue
                $key = "Net_${owningPid}_${remoteIP}_${remotePort}"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious network connection: $($proc.Name) (PID: $owningPid) -> ${remoteIP}:${remotePort}"
                }
            }
        }
    }
    catch {
        # Silent continue on network errors
    }
}
# Main execution
function Invoke-LocalProxyDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-LocalProxyDetection

# --- ScriptContentScan ---
# Scans suspicious folders for script/text RAT patterns. Quarantines only script extensions (policy 1); logs only for other text.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "ScriptContentScan"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 180
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "scriptcontentscan_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-ScriptContentScan {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-ScriptContentScan

# --- ScriptHostDetection ---
# Detects script-host based RAT execution (mshta/wscript/cscript) via command-line patterns and executed script targets.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "ScriptHostDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 30
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "scripthostdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against SuspiciousIndicators patterns
        foreach ($pattern in $script:SuspiciousIndicators) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_ScriptHostDetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "ScriptHostDetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-ScriptHostDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-ScriptHostDetection

# --- MitreMapping ---
# Maps detections to MITRE ATT&CK framework for reporting and correlation. Produces correlation report.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "MitreMapping"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 120
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "mitremapping_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # Scheduled task detection
    try {
        $tasks = Get-ScheduledTask -ErrorAction SilentlyContinue | 
                 Where-Object { $_.State -ne "Disabled" }
        
        foreach ($task in $tasks) {
            $actions = $task.Actions
            foreach ($action in $actions) {
                if ($action.Execute) {
                    $execLower = $action.Execute.ToLower()
                    
                    # Check for suspicious task actions
                    if ($execLower -match "powershell|cmd|wscript|cscript|mshta|rundll32") {
                        $key = "Task_$($task.TaskName)"
                        if (Test-ShouldReport -Key $key) {
                            Write-Detection "Suspicious scheduled task: $($task.TaskName) - $($action.Execute) $($action.Arguments)" -Level "WARNING"
                        }
                    }
                }
            }
        }
    }
    catch {
        # Silent continue on task errors
    }
}
# Main execution
function Invoke-MitreMapping {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-MitreMapping

$script:EmbeddedRealTimeFileMonitor = $true
# --- RealTimeFileMonitor ---
# Run() only initializes watchers once; interval is nominal.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "RealTimeFileMonitor"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 3600
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "realtimefilemonitor_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # Driver monitoring
    try {
        $drivers = Get-CimInstance Win32_SystemDriver -ErrorAction SilentlyContinue | 
                   Where-Object { $_.State -eq "Running" }
        
        foreach ($drv in $drivers) {
            if ($drv.PathName) {
                $pathLower = $drv.PathName.ToLower()
                
                # Check for drivers loaded from non-standard paths
                if ($pathLower -notmatch "system32\\drivers|windows") {
                    $key = "Drv_$($drv.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Non-standard driver path: $($drv.Name) - $($drv.PathName)" -Level "WARNING"
                    }
                }
            }
        }
    }
    catch {
        # Silent continue on driver errors
    }
}
# Main execution
function Invoke-RealTimeFileMonitor {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-RealTimeFileMonitor

# --- KeyScramblerManagement ---
# Manages key scrambling / anti-keylogger measures. Coordinates keylogger detection, HID macro guard, and secure input recommendations.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "KeyScramblerManagement"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 90
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "keyscramblermanagement_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-KeyScramblerManagement {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-KeyScramblerManagement

# --- NeuroBehaviorMonitor ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "NeuroBehaviorMonitor"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 1
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "neurobehaviormonitor_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Generic process monitoring
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | 
                 Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        
        # Add job-specific detection logic here based on patterns
        # This is a fallback for jobs that need manual review
        
        Write-Detection "Monitoring active for $ModuleName" -Level "INFO"
        break  # Only log once per run
    }
}
# Main execution
function Invoke-NeuroBehaviorMonitor {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-NeuroBehaviorMonitor

# --- StartupPersistenceDetection ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "StartupPersistenceDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 120
$script:SelfPid = $PID

$script:ScriptExtensions = @(
        ".vbs",
        ".vbe",
        ".js",
        ".jse",
        ".wsf",
        ".ps1",
        ".bat",
        ".cmd",
        ".scr"
    )

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "startuppersistencedetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-StartupPersistenceDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-StartupPersistenceDetection

# --- SuspiciousParentChildDetection ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "SuspiciousParentChildDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 45
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "suspiciousparentchilddetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
            }
}
# Main execution
function Invoke-SuspiciousParentChildDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-SuspiciousParentChildDetection

# --- ScriptBlockLoggingCheck ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "ScriptBlockLoggingCheck"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 86400
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "scriptblockloggingcheck_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-ScriptBlockLoggingCheck {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-ScriptBlockLoggingCheck

# --- DriverWatcher ---
# Monitors drivers and minifilters; alerts on non-whitelisted vendors.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "DriverWatcher"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 120
$script:SelfPid = $PID

$script:AllowedVendors = @(
        "Microsoft",
        "Realtek",
        "Dolby",
        "Intel",
        "Advanced Micro Devices",
        "AMD",
        "NVIDIA",
        "MediaTek"
    )

$script:BlocklistedMinifilters = @(
        "bfs",
        "unionfs"
    )

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "driverwatcher_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
    # Service-based detection
    try {
        $services = Get-CimInstance Win32_Service -ErrorAction SilentlyContinue | 
                    Where-Object { $_.State -eq "Running" -and $_.PathName }
        
        foreach ($svc in $services) {
            $pathLower = $svc.PathName.ToLower()
            
            # Check for services running from suspicious locations
            if ($pathLower -notmatch "system32|program files|windows") {
                $key = "Svc_$($svc.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Non-standard service path: $($svc.Name) - $($svc.PathName)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on service errors
    }
}
# Main execution
function Invoke-DriverWatcher {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-DriverWatcher

# --- CrudePayloadGuard ---
# WMI-based process creation watcher for XSS/injection patterns in command line. Blocks malicious URLs via firewall.
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "CrudePayloadGuard"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 60
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "crudepayloadguard_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
}
# Main execution
function Invoke-CrudePayloadGuard {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-CrudePayloadGuard

# --- PUPDetection ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "PUPDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 120
$script:SelfPid = $PID

$script:PUPProcessNames = @(
        "conduit",
        "ask",
        "babylon",
        "delta-homes",
        "dosearches",
        "ilivid",
        "iminent",
        "incredibar",
        "mywebsearch",
        "searchprotect",
        "sweetim",
        "sweetpacks",
        "wajam",
        "webssearches",
        "yontoo",
        "zugo",
        "mindspark",
        "shopperz",
        "asktoolbar",
        "baborytoolbar",
        "conduitengine",
        "dealply",
        "funmoods",
        "genieo",
        "installcore",
        "opencandy",
        "perion",
        "snapdo",
        "somoto",
        "softonic",
        "spigot",
        "superfish",
        "visualbee",
        "browsefox",
        "crossrider",
        "goobzo",
        "istartsurf",
        "omniboxes",
        "qvo6",
        "safefinder",
        "searchqu",
        "trovi",
        "tuvaro",
        "vosteran",
        "amonetize",
        "downloadhelper",
        "filetour",
        "installbrain",
        "installerex",
        "outbrowse",
        "vittalia",
        "downloadmr",
        "downloader",
        "optimizers",
        "pcoptimizer",
        "regclean",
        "driverfixer",
        "driverupdate",
        "winzip driver",
        "slimcleaner",
        "systweak",
        "uniblue",
        "reimage",
        "restoro",
        "xmrig",
        "minergate",
        "nicehash",
        "coinhive"
    )

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "pupdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-PUPDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-PUPDetection

# --- PUMDetection ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "PUMDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 180
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "pumdetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # Driver monitoring
    try {
        $drivers = Get-CimInstance Win32_SystemDriver -ErrorAction SilentlyContinue | 
                   Where-Object { $_.State -eq "Running" }
        
        foreach ($drv in $drivers) {
            if ($drv.PathName) {
                $pathLower = $drv.PathName.ToLower()
                
                # Check for drivers loaded from non-standard paths
                if ($pathLower -notmatch "system32\\drivers|windows") {
                    $key = "Drv_$($drv.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Non-standard driver path: $($drv.Name) - $($drv.PathName)" -Level "WARNING"
                    }
                }
            }
        }
    }
    catch {
        # Silent continue on driver errors
    }
}
# Main execution
function Invoke-PUMDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-PUMDetection

# --- PUADetection ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "PUADetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 180
$script:SelfPid = $PID

$script:RemoteAccessTools = @(
        "ammyy",
        "ammyadmin",
        "anydesk",
        "atera",
        "connectwise",
        "dameware",
        "logmein",
        "netop",
        "radmin",
        "remcos",
        "rustdesk",
        "screenconnect",
        "showmypc",
        "splashtop",
        "supremo",
        "teamviewer",
        "tightvnc",
        "ultravnc",
        "vnc",
        "vncserver",
        "realvnc"
    )

$script:RogueSecurity = @(
        "antivirus360",
        "antivirus2009",
        "antivirus2010",
        "antispyware",
        "defensewall",
        "drweb-antivirus",
        "errorsafe",
        "fakealert",
        "pcdefender",
        "personalantivirus",
        "privacycenter",
        "registrybooster",
        "registryfix",
        "registrymechanic",
        "securityshield",
        "securitysuite",
        "spyhunter",
        "spywarestop",
        "systemdefender",
        "virusremover",
        "winantivirus",
        "winfixer",
        "winspyware",
        "xpantivirus"
    )

$script:SystemOptimizers = @(
        "advancedsystemcare",
        "auslogics",
        "ccleaner",
        "cleaner",
        "driverbooster",
        "drivereasy",
        "driverfixer",
        "drivermax",
        "driverreviver",
        "driverupdate",
        "glaryutilities",
        "iobit",
        "pcboost",
        "pccleaner",
        "pcfaster",
        "pckeeper",
        "pcmechanic",
        "pcoptimizer",
        "pcspeedup",
        "pctotal",
        "reginout",
        "regclean",
        "registrycleaner",
        "registryreviver",
        "slimcleaner",
        "slimware",
        "speedupmypc",
        "systweak",
        "tuneup",
        "uniblue",
        "wise care",
        "wisecleaner",
        "wiseregistry"
    )

$script:CryptoMiners = @(
        "bfgminer",
        "ccminer",
        "cgminer",
        "claymore",
        "cpuminer",
        "cryptonight",
        "ethminer",
        "gminer",
        "lolminer",
        "minerd",
        "minergate",
        "nanominer",
        "nbminer",
        "nicehash",
        "phoenixminer",
        "sgminer",
        "t-rex",
        "xmr-stak",
        "xmrig",
        "z-enemy"
    )

$script:P2PClients = @(
        "ares",
        "bittorrent",
        "deluge",
        "emule",
        "frostwire",
        "imesh",
        "kazaa",
        "limewire",
        "qbittorrent",
        "transmission",
        "utorrent",
        "vuze"
    )

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "puadetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against RogueSecurity patterns
        foreach ($pattern in $script:RogueSecurity) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_PUADetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "PUADetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }        
        # Check against SystemOptimizers patterns
        foreach ($pattern in $script:SystemOptimizers) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_PUADetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "PUADetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }        
        # Check against CryptoMiners patterns
        foreach ($pattern in $script:CryptoMiners) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_PUADetection_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "PUADetection detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-PUADetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-PUADetection

# --- WMIPhoneHomeDetection ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "WMIPhoneHomeDetection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 30
$script:SelfPid = $PID

$script:WbemProcesses = @(
        "wmiprvse",
        "wmiprvse.exe",
        "wmic",
        "wmic.exe",
        "scrcons",
        "scrcons.exe",
        "wmiadap",
        "wmiadap.exe",
        "wmiapsrv",
        "wmiapsrv.exe",
        "unsecapp",
        "unsecapp.exe",
        "mofcomp",
        "mofcomp.exe",
        "winmgmt",
        "winmgmt.exe"
    )

$script:AllowedRemoteIPs = @(
        "127.0.0.1",
        "::1",
        "0.0.0.0"
    )

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "wmiphonehomedetection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Network-based detection
    try {
        $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue
        
        foreach ($conn in $connections) {
            $remoteIP = $conn.RemoteAddress
            $remotePort = $conn.RemotePort
            $localPort = $conn.LocalPort
            $owningPid = $conn.OwningProcess
            
            # Check for suspicious ports
            $suspiciousPorts = @(4444, 5555, 6666, 1337, 31337, 8080, 8443, 9001, 9090)
            if ($suspiciousPorts -contains $remotePort -or $suspiciousPorts -contains $localPort) {
                $proc = Get-Process -Id $owningPid -ErrorAction SilentlyContinue
                $key = "Net_${owningPid}_${remoteIP}_${remotePort}"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious network connection: $($proc.Name) (PID: $owningPid) -> ${remoteIP}:${remotePort}"
                }
            }
        }
    }
    catch {
        # Silent continue on network errors
    }
}
# Main execution
function Invoke-WMIPhoneHomeDetection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-WMIPhoneHomeDetection

# --- WMIPolicyProtection ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "WMIPolicyProtection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 60
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "wmipolicyprotection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Network-based detection
    try {
        $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue
        
        foreach ($conn in $connections) {
            $remoteIP = $conn.RemoteAddress
            $remotePort = $conn.RemotePort
            $localPort = $conn.LocalPort
            $owningPid = $conn.OwningProcess
            
            # Check for suspicious ports
            $suspiciousPorts = @(4444, 5555, 6666, 1337, 31337, 8080, 8443, 9001, 9090)
            if ($suspiciousPorts -contains $remotePort -or $suspiciousPorts -contains $localPort) {
                $proc = Get-Process -Id $owningPid -ErrorAction SilentlyContinue
                $key = "Net_${owningPid}_${remoteIP}_${remotePort}"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious network connection: $($proc.Name) (PID: $owningPid) -> ${remoteIP}:${remotePort}"
                }
            }
        }
    }
    catch {
        # Silent continue on network errors
    }
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
}
# Main execution
function Invoke-WMIPolicyProtection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-WMIPolicyProtection

$script:EmbeddedAsrRules = $true
# --- AsrRules ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "AsrRules"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 3600
$script:SelfPid = $PID

$script:AsrRuleIds = @(
        "56a863a9-875e-4185-98a7-b882c64b5ce5",
        "5beb7efe-fd9a-4556-801d-275e5ffc04cc",
        "e6db77e5-3df2-4cf1-b95a-636979351e5b",
        "d4f940ab-401b-4efc-aadc-ad5f3c50688a",
        "b2b3f03d-6a65-4f7b-a9c7-1c7ef74a9ba4"
    )

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "asrrules_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Generic process monitoring
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | 
                 Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        
        # Add job-specific detection logic here based on patterns
        # This is a fallback for jobs that need manual review
        
        Write-Detection "Monitoring active for $ModuleName" -Level "INFO"
        break  # Only log once per run
    }
}
# Main execution
function Invoke-AsrRules {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-AsrRules

# --- CVEMitigationPatcher ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "CVEMitigationPatcher"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 3600
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "cvemitigationpatcher_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-CVEMitigationPatcher {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-CVEMitigationPatcher

# --- PasswordRotator ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "PasswordRotator"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 3600
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "passwordrotator_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
    # Scheduled task detection
    try {
        $tasks = Get-ScheduledTask -ErrorAction SilentlyContinue | 
                 Where-Object { $_.State -ne "Disabled" }
        
        foreach ($task in $tasks) {
            $actions = $task.Actions
            foreach ($action in $actions) {
                if ($action.Execute) {
                    $execLower = $action.Execute.ToLower()
                    
                    # Check for suspicious task actions
                    if ($execLower -match "powershell|cmd|wscript|cscript|mshta|rundll32") {
                        $key = "Task_$($task.TaskName)"
                        if (Test-ShouldReport -Key $key) {
                            Write-Detection "Suspicious scheduled task: $($task.TaskName) - $($action.Execute) $($action.Arguments)" -Level "WARNING"
                        }
                    }
                }
            }
        }
    }
    catch {
        # Silent continue on task errors
    }
}
# Main execution
function Invoke-PasswordRotator {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-PasswordRotator

$script:EmbeddedGRulesC2Block = $true
# --- GRulesC2Block ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "GRulesC2Block"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 1800
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "grulesc2block_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-GRulesC2Block {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-GRulesC2Block

# --- GSecurityLite ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "GSecurityLite"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 30
$script:SelfPid = $PID

$script:SafeProcesses = @(
        "Idle",
        "System",
        "Registry",
        "MemCompression",
        "smss",
        "csrss",
        "wininit",
        "services",
        "winlogon",
        "lsass",
        "dwm",
        "sihost",
        "fontdrvhost",
        "explorer",
        "360chrome",
        "360se",
        "arc",
        "brave",
        "chrome",
        "chromium",
        "edge",
        "firefox",
        "iexplore",
        "msedge",
        "opera",
        "operagx",
        "vivaldi",
        "waterfox",
        "Steam",
        "steamwebhelper",
        "gameoverlayui",
        "EpicGamesLauncher",
        "EpicWebHelper",
        "GOGGalaxy",
        "GalaxyClient",
        "XboxPcApp",
        "GameBar",
        "Discord",
        "DiscordPTB",
        "DiscordCanary",
        "EasyAntiCheat",
        "BattlEye",
        "BEService",
        "vgc",
        "vgtray",
        "Faceit",
        "RzSDKService",
        "LightingService",
        "iCUE",
        "ArmouryCrate",
        "cs2",
        "VALORANT-Win64-Shipping",
        "LeagueClient",
        "GenshinImpact",
        "gedr",
        "GEDR",
        "Antivirus"
    )

$script:MaliciousProcessNames = @(
        "mimikatz",
        "procdump",
        "mimilib",
        "pypykatz"
    )

$script:SuspiciousCIDRs = @(
        "208.95.0.0/16",
        "208.97.0.0/16",
        "65.9.0.0/16",
        "194.36.0.0/16",
        "52.109.0.0/16",
        "2.16.0.0/16",
        "2.18.0.0/16",
        "20.82.0.0/16",
        "20.190.0.0/16",
        "135.236.0.0/16",
        "23.32.0.0/16",
        "2.22.89.0/24",
        "23.35.0.0/16",
        "40.69.0.0/16",
        "51.124.0.0/16"
    )

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "gsecuritylite_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against MaliciousProcessNames patterns
        foreach ($pattern in $script:MaliciousProcessNames) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_GSecurityLite_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "GSecurityLite detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }        
        # Check against SuspiciousCIDRs patterns
        foreach ($pattern in $script:SuspiciousCIDRs) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_GSecurityLite_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "GSecurityLite detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # Network-based detection
    try {
        $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue
        
        foreach ($conn in $connections) {
            $remoteIP = $conn.RemoteAddress
            $remotePort = $conn.RemotePort
            $localPort = $conn.LocalPort
            $owningPid = $conn.OwningProcess
            
            # Check for suspicious ports
            $suspiciousPorts = @(4444, 5555, 6666, 1337, 31337, 8080, 8443, 9001, 9090)
            if ($suspiciousPorts -contains $remotePort -or $suspiciousPorts -contains $localPort) {
                $proc = Get-Process -Id $owningPid -ErrorAction SilentlyContinue
                $key = "Net_${owningPid}_${remoteIP}_${remotePort}"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious network connection: $($proc.Name) (PID: $owningPid) -> ${remoteIP}:${remotePort}"
                }
            }
        }
    }
    catch {
        # Silent continue on network errors
    }
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
}
# Main execution
function Invoke-GSecurityLite {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-GSecurityLite

# --- AudioEnhancement ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "AudioEnhancement"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 3600
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "audioenhancement_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-AudioEnhancement {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-AudioEnhancement

# --- BCDCleanupEnhanced ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "BCDCleanupEnhanced"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 86400
$script:SelfPid = $PID

$script:CriticalIds = @()

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "bcdcleanupenhanced_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Driver monitoring
    try {
        $drivers = Get-CimInstance Win32_SystemDriver -ErrorAction SilentlyContinue | 
                   Where-Object { $_.State -eq "Running" }
        
        foreach ($drv in $drivers) {
            if ($drv.PathName) {
                $pathLower = $drv.PathName.ToLower()
                
                # Check for drivers loaded from non-standard paths
                if ($pathLower -notmatch "system32\\drivers|windows") {
                    $key = "Drv_$($drv.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Non-standard driver path: $($drv.Name) - $($drv.PathName)" -Level "WARNING"
                    }
                }
            }
        }
    }
    catch {
        # Silent continue on driver errors
    }
}
# Main execution
function Invoke-BCDCleanupEnhanced {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-BCDCleanupEnhanced

# --- BrowserHardening ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "BrowserHardening"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 3600
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "browserhardening_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-BrowserHardening {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-BrowserHardening

# --- CredentialHardening ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "CredentialHardening"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 3600
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "credentialhardening_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # Driver monitoring
    try {
        $drivers = Get-CimInstance Win32_SystemDriver -ErrorAction SilentlyContinue | 
                   Where-Object { $_.State -eq "Running" }
        
        foreach ($drv in $drivers) {
            if ($drv.PathName) {
                $pathLower = $drv.PathName.ToLower()
                
                # Check for drivers loaded from non-standard paths
                if ($pathLower -notmatch "system32\\drivers|windows") {
                    $key = "Drv_$($drv.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Non-standard driver path: $($drv.Name) - $($drv.PathName)" -Level "WARNING"
                    }
                }
            }
        }
    }
    catch {
        # Silent continue on driver errors
    }
}
# Main execution
function Invoke-CredentialHardening {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-CredentialHardening

# --- PerformanceTweaks ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "PerformanceTweaks"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 86400
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "performancetweaks_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-PerformanceTweaks {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-PerformanceTweaks

# --- NetworkDebloat ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "NetworkDebloat"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 3600
$script:SelfPid = $PID

$script:ComponentsToDisable = @(
        "ms_server",
        "ms_msclient",
        "ms_pacer",
        "ms_lltdio",
        "ms_rspndr",
        "ms_tcpip6"
    )

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "networkdebloat_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Generic process monitoring
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | 
                 Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        
        # Add job-specific detection logic here based on patterns
        # This is a fallback for jobs that need manual review
        
        Write-Detection "Monitoring active for $ModuleName" -Level "INFO"
        break  # Only log once per run
    }
}
# Main execution
function Invoke-NetworkDebloat {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-NetworkDebloat

# --- NullSessionProtection ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "NullSessionProtection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 3600
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "nullsessionprotection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-NullSessionProtection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-NullSessionProtection

# --- RemoteAccessPrevention ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "RemoteAccessPrevention"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 3600
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "remoteaccessprevention_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-RemoteAccessPrevention {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-RemoteAccessPrevention

# --- SecurityPolicyHardening ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "SecurityPolicyHardening"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 86400
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "securitypolicyhardening_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-SecurityPolicyHardening {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-SecurityPolicyHardening

# --- SecureRemoteAccess ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "SecureRemoteAccess"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 3600
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "secureremoteaccess_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-SecureRemoteAccess {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-SecureRemoteAccess

# --- DnsSecure ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "DnsSecure"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 3600
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "dnssecure_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Generic process monitoring
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | 
                 Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        
        # Add job-specific detection logic here based on patterns
        # This is a fallback for jobs that need manual review
        
        Write-Detection "Monitoring active for $ModuleName" -Level "INFO"
        break  # Only log once per run
    }
}
# Main execution
function Invoke-DnsSecure {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-DnsSecure

# --- DeviceFiltering ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "DeviceFiltering"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 3600
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "devicefiltering_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
}
# Main execution
function Invoke-DeviceFiltering {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-DeviceFiltering

# --- Unhooker ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "Unhooker"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 3600
$script:SelfPid = $PID

$script:DllsToRefresh = @(
        "ntdll.dll",
        "kernel32.dll",
        "kernelbase.dll",
        "advapi32.dll"
    )

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "unhooker_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-Unhooker {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-Unhooker

# --- TelemetryCorruption ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "TelemetryCorruption"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 3600
$script:SelfPid = $PID

$script:TelemetryFiles = @(
        "%ProgramData%\Microsoft\Diagnosis\ETLLogs\AutoLogger\AutoLogger-Diagtrack-Listener.etl",
        "%ProgramData%\Microsoft\Diagnosis\ETLLogs\AutoLogger\AutoLogger-Diagtrack-Listener_1.etl",
        "%ProgramData%\Microsoft\Diagnosis\ETLLogs\ShutdownLogger.etl",
        "%LocalAppData%\Microsoft\Windows\WebCache\WebCacheV01.dat",
        "%ProgramData%\Microsoft\Windows\AppRepository\StateRepository-Deployment.srd",
        "%ProgramData%\Microsoft\Diagnosis\eventTranscript\eventTranscript.db",
        "%SystemRoot%\System32\winevt\Logs\Microsoft-Windows-Telemetry%4Operational.evtx",
        "%ProgramData%\NVIDIA Corporation\NvTelemetry\NvTelemetryContainer.etl",
        "%LocalAppData%\Google\Chrome\User Data\Default\Web Data",
        "%ProgramData%\Adobe\ARM\log\ARMTelemetry.etl",
        "%ProgramData%\Intel\Telemetry\IntelData.etl",
        "%ProgramData%\AMD\CN\AMDDiag.etl",
        "%LocalAppData%\Steam\htmlcache\Cookies",
        "%ProgramData%\Epic\EpicGamesLauncher\Data\EOSAnalytics.etl",
        "%AppData%\Discord\Local Storage\leveldb\*.ldb",
        "%AppData%\Mozilla\Firefox\Profiles\*\telemetry.sqlite",
        "%ProgramData%\Logitech\LogiSync\Telemetry.etl",
        "%ProgramData%\Razer\Synapse3\Logs\RazerSynapse.log",
        "%ProgramData%\Corsair\CUE\logs\iCUETelemetry.log"
    )

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "telemetrycorruption_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-TelemetryCorruption {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-TelemetryCorruption

# --- CookieProtection ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "CookieProtection"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 300
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "cookieprotection_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-CookieProtection {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-CookieProtection

# --- CustomControlsRemover ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "CustomControlsRemover"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 60
$script:SelfPid = $PID

$script:BasePaths = @(
        "SOFTWARE\WOW6432Node\Classes\CLSID",
        "SOFTWARE\Classes\CLSID"
    )

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "customcontrolsremover_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # Registry-based detection
    $registryPaths = @(
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($regPath in $registryPaths) {
        if (-not (Test-Path $regPath)) { continue }
        
        try {
            $entries = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
            $properties = $entries.PSObject.Properties | Where-Object { $_.Name -notmatch "^PS" }
            
            foreach ($prop in $properties) {
                $value = $prop.Value
                if ($value -match "\.exe|\.dll|\.ps1|\.vbs|\.bat|powershell|cmd\.exe") {
                    $key = "Reg_$regPath_$($prop.Name)"
                    if (Test-ShouldReport -Key $key) {
                        Write-Detection "Registry persistence found: $regPath\$($prop.Name) = $value" -Level "WARNING"
                    }
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
}
# Main execution
function Invoke-CustomControlsRemover {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-CustomControlsRemover

# --- SessionTerminator ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "SessionTerminator"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 30
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "sessionterminator_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Generic process monitoring
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | 
                 Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        
        # Add job-specific detection logic here based on patterns
        # This is a fallback for jobs that need manual review
        
        Write-Detection "Monitoring active for $ModuleName" -Level "INFO"
        break  # Only log once per run
    }
}
# Main execution
function Invoke-SessionTerminator {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-SessionTerminator

# --- NetworkBridgeRemoval ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "NetworkBridgeRemoval"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 30
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "networkbridgeremoval_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Generic process monitoring
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | 
                 Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        
        # Add job-specific detection logic here based on patterns
        # This is a fallback for jobs that need manual review
        
        Write-Detection "Monitoring active for $ModuleName" -Level "INFO"
        break  # Only log once per run
    }
}
# Main execution
function Invoke-NetworkBridgeRemoval {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-NetworkBridgeRemoval

# --- GSecurityEnhanced ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "GSecurityEnhanced"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 30
$script:SelfPid = $PID

$script:SafeProcesses = @(
        "System",
        "Idle",
        "Registry",
        "MemCompression",
        "smss",
        "csrss",
        "wininit",
        "services",
        "winlogon",
        "lsass",
        "dwm",
        "sihost",
        "fontdrvhost",
        "explorer",
        "svchost",
        "taskhostw",
        "spoolsv",
        "SearchUI",
        "SearchIndexer",
        "RuntimeBroker",
        "gedr",
        "GEDR",
        "Antivirus"
    )

$script:BadProcessNames = @(
        "mimikatz",
        "procdump",
        "mimilib",
        "pypykatz",
        "lazagne"
    )

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "gsecurityenhanced_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Get all running processes
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        $procPath = if ($proc.ExecutablePath) { $proc.ExecutablePath } else { "" }
                
        # Check against BadProcessNames patterns
        foreach ($pattern in $script:BadProcessNames) {
            if ($cmdLine -match [regex]::Escape($pattern.ToLower()) -or 
                $procName -match [regex]::Escape($pattern) -or
                $procPath -match [regex]::Escape($pattern)) {
                
                $key = "$($proc.ProcessId)_GSecurityEnhanced_$pattern"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "GSecurityEnhanced detected: $($proc.Name) (PID: $($proc.ProcessId)) matched pattern: $pattern"
                    
                    # Invoke threat response if configured
                    if ($ModuleConfig -and $ModuleConfig.AutoKill) {
                        Invoke-ThreatResponse -ProcessId $proc.ProcessId -ProcessName $proc.Name -Reason $pattern
                    }
                }
                break
            }
        }    }
    # File-based detection
    $scanPaths = @(
        "$env:TEMP",
        "$env:LOCALAPPDATA\Temp",
        "$env:USERPROFILE\Downloads",
        "$env:USERPROFILE\Desktop"
    )
    
    $suspiciousExtensions = @(".exe", ".dll", ".ps1", ".vbs", ".bat", ".cmd", ".scr")
    
    foreach ($basePath in $scanPaths) {
        if (-not (Test-Path $basePath)) { continue }
        
        try {
            $files = Get-ChildItem -Path $basePath -File -ErrorAction SilentlyContinue | 
                     Where-Object { $suspiciousExtensions -contains $_.Extension.ToLower() }
            
            foreach ($file in $files) {
                $key = "File_$($file.FullName)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "Suspicious file found: $($file.FullName)" -Level "WARNING"
                }
            }
        }
        catch {
            # Silent continue on access errors
        }
    }
    # WMI-based detection
    try {
        # Check for WMI event subscriptions (persistence mechanism)
        $eventFilters = Get-CimInstance -Namespace "root\subscription" -ClassName __EventFilter -ErrorAction SilentlyContinue
        $consumers = Get-CimInstance -Namespace "root\subscription" -ClassName __EventConsumer -ErrorAction SilentlyContinue
        $bindings = Get-CimInstance -Namespace "root\subscription" -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue
        
        if ($eventFilters -or $consumers -or $bindings) {
            foreach ($filter in $eventFilters) {
                $key = "WMI_Filter_$($filter.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Filter found: $($filter.Name) - $($filter.Query)" -Level "WARNING"
                }
            }
            foreach ($consumer in $consumers) {
                $key = "WMI_Consumer_$($consumer.Name)"
                if (Test-ShouldReport -Key $key) {
                    Write-Detection "WMI Event Consumer found: $($consumer.Name)" -Level "WARNING"
                }
            }
        }
    }
    catch {
        # Silent continue on WMI errors
    }
}
# Main execution
function Invoke-GSecurityEnhanced {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-GSecurityEnhanced

$script:EmbeddedProcessAuditing = $true
# --- ProcessAuditing ---
# GEDR Detection Job
# Converted from GEDR C# job - FULL IMPLEMENTATION

$ModuleName = "ProcessAuditing"
$script:LastRun = [DateTime]::MinValue
$script:TickInterval = 3600
$script:SelfPid = $PID

# Helper function for deduplication
function Test-ShouldReport {
    param([string]$Key)
    
    if ($null -eq $script:ReportedItems) {
        $script:ReportedItems = @{}
    }
    
    if ($script:ReportedItems.ContainsKey($Key)) {
        return $false
    }
    
    $script:ReportedItems[$Key] = [DateTime]::UtcNow
    return $true
}

# Helper function for logging
function Write-Detection {
    param(
        [string]$Message,
        [string]$Level = "THREAT",
        [string]$LogFile = "processauditing_detections.log"
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] [$Level] [$ModuleName] $Message"
    
    # Write to console
    switch ($Level) {
        "THREAT" { Write-Host $logEntry -ForegroundColor Red }
        "WARNING" { Write-Host $logEntry -ForegroundColor Yellow }
        "INFO" { Write-Host $logEntry -ForegroundColor Cyan }
        default { Write-Host $logEntry }
    }
    
    # Write to log file
    $logPath = Join-Path $env:LOCALAPPDATA "GEDR\Logs"
    if (-not (Test-Path $logPath)) { New-Item -ItemType Directory -Path $logPath -Force | Out-Null }
    Add-Content -Path (Join-Path $logPath $LogFile) -Value $logEntry -ErrorAction SilentlyContinue
}

# Helper function for threat response
function Invoke-ThreatResponse {
    param(
        [int]$ProcessId,
        [string]$ProcessName,
        [string]$Reason
    )
    
    Write-Detection "Threat response triggered for $ProcessName (PID: $ProcessId) - $Reason"
    
    # Don't kill critical system processes
    $criticalProcesses = @("System", "smss", "csrss", "wininit", "services", "lsass", "svchost", "dwm", "explorer")
    if ($criticalProcesses -contains $ProcessName) {
        Write-Detection "Skipping critical process: $ProcessName" -Level "WARNING"
        return
    }
    
    try {
        Stop-Process -Id $ProcessId -Force -ErrorAction Stop
        Write-Detection "Terminated process: $ProcessName (PID: $ProcessId)"
    }
    catch {
        Write-Detection "Failed to terminate $ProcessName (PID: $ProcessId): $($_.Exception.Message)" -Level "WARNING"
    }
}

function Start-Detection {
    # Generic process monitoring
    $processes = Get-CimInstance Win32_Process -ErrorAction SilentlyContinue | 
                 Select-Object ProcessId, Name, CommandLine, ExecutablePath
    
    foreach ($proc in $processes) {
        if ($proc.ProcessId -eq $script:SelfPid) { continue }
        
        $cmdLine = if ($proc.CommandLine) { $proc.CommandLine.ToLower() } else { "" }
        $procName = if ($proc.Name) { $proc.Name } else { "" }
        
        # Add job-specific detection logic here based on patterns
        # This is a fallback for jobs that need manual review
        
        Write-Detection "Monitoring active for $ModuleName" -Level "INFO"
        break  # Only log once per run
    }
}
# Main execution
function Invoke-ProcessAuditing {
    $now = Get-Date
    if ($script:LastRun -ne [DateTime]::MinValue -and ($now - $script:LastRun).TotalSeconds -lt $script:TickInterval) {
        return
    }
    $script:LastRun = $now
    
    try {
        Start-Detection
    }
    catch {
        Write-Detection "Error in $ModuleName : $($_.Exception.Message)" -Level "ERROR"
    }
}

# Execute
Invoke-ProcessAuditing

# --- Scheduler ---
$script:ModuleLastRun = @{}
$script:AntivirusTaskName = 'GShieldAntivirusEDR'

function Update-AgentStatus {
    param([array]$ScheduleList, [hashtable]$LastRun)
    $statusFile = "$env:ProgramData\Antivirus\Data\agent_status.json"
    $cutoff = (Get-Date).AddMinutes(-10)
    $active = @($ScheduleList | Where-Object { $LastRun[$_.Name] -and $LastRun[$_.Name] -ge $cutoff } | ForEach-Object { $_.Name })
    if ($active.Count -eq 0) { $active = @($ScheduleList | ForEach-Object { $_.Name }) }
    $status = @{ LastCheck = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss'); ActiveAgents = $active; SystemHealth = 'Healthy'; TotalDetections = 0; TotalResponses = 0 }
    if (Test-Path $statusFile) { try { $existing = Get-Content $statusFile -Raw | ConvertFrom-Json; if ($existing.PSObject.Properties['TotalDetections']) { $status.TotalDetections = $existing.TotalDetections }; if ($existing.PSObject.Properties['TotalResponses']) { $status.TotalResponses = $existing.TotalResponses } } catch { } }
    $status | ConvertTo-Json -Depth 3 | Set-Content -Path $statusFile -ErrorAction SilentlyContinue
}

$schedule = @(
    @{ Name = 'Initializer'; Interval = 300; Invoke = 'Invoke-Initialization' }
    @{ Name = 'HashDetection'; Interval = 90; Invoke = 'Invoke-HashDetection' }
    @{ Name = 'AMSIBypassDetection'; Interval = 90; Invoke = 'Invoke-AMSIBypassDetection' }
    @{ Name = 'GFocus'; Interval = 2; Invoke = 'Invoke-GFocus' }
    @{ Name = 'ResponseEngine'; Interval = 180; Invoke = 'Invoke-ResponseEngine' }
    @{ Name = 'BeaconDetection'; Interval = 60; Invoke = 'Invoke-BeaconDetection' }
    @{ Name = 'NetworkTrafficMonitoring'; Interval = 45; Invoke = 'Invoke-NetworkTrafficMonitoring' }
    @{ Name = 'ProcessAnomalyDetection'; Interval = 90; Invoke = 'Invoke-ProcessAnomalyDetection' }
    @{ Name = 'EventLogMonitoring'; Interval = 90; Invoke = 'Invoke-EventLogMonitoring' }
    @{ Name = 'FileEntropyDetection'; Interval = 120; Invoke = 'Invoke-FileEntropyDetection' }
    @{ Name = 'YaraDetection'; Interval = 120; Invoke = 'Invoke-YaraDetection' }
    @{ Name = 'WMIPersistenceDetection'; Interval = 60; Invoke = 'Invoke-WMIPersistenceDetection' }
    @{ Name = 'ScheduledTaskDetection'; Interval = 60; Invoke = 'Invoke-ScheduledTaskDetection' }
    @{ Name = 'RegistryPersistenceDetection'; Interval = 60; Invoke = 'Invoke-RegistryPersistenceDetection' }
    @{ Name = 'DLLHijackingDetection'; Interval = 60; Invoke = 'Invoke-DLLHijackingDetection' }
    @{ Name = 'TokenManipulationDetection'; Interval = 30; Invoke = 'Invoke-TokenManipulationDetection' }
    @{ Name = 'ProcessHollowingDetection'; Interval = 20; Invoke = 'Invoke-ProcessHollowingDetection' }
    @{ Name = 'KeyloggerDetection'; Interval = 30; Invoke = 'Invoke-KeyloggerDetection' }
    @{ Name = 'ReflectiveDLLInjectionDetection'; Interval = 30; Invoke = 'Invoke-ReflectiveDLLInjectionDetection' }
    @{ Name = 'RansomwareDetection'; Interval = 15; Invoke = 'Invoke-RansomwareDetection' }
    @{ Name = 'NetworkAnomalyDetection'; Interval = 30; Invoke = 'Invoke-NetworkAnomalyDetection' }
    @{ Name = 'DNSExfiltrationDetection'; Interval = 60; Invoke = 'Invoke-DNSExfiltrationDetection' }
    @{ Name = 'RootkitDetection'; Interval = 60; Invoke = 'Invoke-RootkitDetection' }
    @{ Name = 'ClipboardMonitoring'; Interval = 10; Invoke = 'Invoke-ClipboardMonitoring' }
    @{ Name = 'COMMonitoring'; Interval = 60; Invoke = 'Invoke-COMMonitoring' }
    @{ Name = 'BrowserExtensionMonitoring'; Interval = 60; Invoke = 'Invoke-BrowserExtensionMonitoring' }
    @{ Name = 'ShadowCopyMonitoring'; Interval = 30; Invoke = 'Invoke-ShadowCopyMonitoring' }
    @{ Name = 'USBMonitoring'; Interval = 30; Invoke = 'Invoke-USBMonitoring' }
    @{ Name = 'WebcamGuardian'; Interval = 20; Invoke = 'Invoke-WebcamGuardian' }
    @{ Name = 'AttackToolsDetection'; Interval = 60; Invoke = 'Invoke-AttackToolsDetection' }
    @{ Name = 'AdvancedThreatDetection'; Interval = 60; Invoke = 'Invoke-AdvancedThreatDetection' }
    @{ Name = 'FirewallRuleMonitoring'; Interval = 60; Invoke = 'Invoke-FirewallRuleMonitoring' }
    @{ Name = 'ServiceMonitoring'; Interval = 60; Invoke = 'Invoke-ServiceMonitoring' }
    @{ Name = 'FilelessDetection'; Interval = 20; Invoke = 'Invoke-FilelessDetection' }
    @{ Name = 'MemoryScanning'; Interval = 90; Invoke = 'Invoke-MemoryScanning' }
    @{ Name = 'NamedPipeMonitoring'; Interval = 60; Invoke = 'Invoke-NamedPipeMonitoring' }
    @{ Name = 'CodeInjectionDetection'; Interval = 30; Invoke = 'Invoke-CodeInjectionDetection' }
    @{ Name = 'DataExfiltrationDetection'; Interval = 60; Invoke = 'Invoke-DataExfiltrationDetection' }
    @{ Name = 'HoneypotMonitoring'; Interval = 300; Invoke = 'Invoke-HoneypotMonitoring' }
    @{ Name = 'LateralMovementDetection'; Interval = 30; Invoke = 'Invoke-LateralMovementDetection' }
    @{ Name = 'ProcessCreationDetection'; Interval = 60; Invoke = 'Invoke-ProcessCreationDetection' }
    @{ Name = 'QuarantineManagement'; Interval = 300; Invoke = 'Invoke-QuarantineManagement' }
    @{ Name = 'PrivacyForgeSpoofing'; Interval = 300; Invoke = 'Invoke-PrivacyForgeSpoofing' }
    @{ Name = 'PasswordManagement'; Interval = 300; Invoke = 'Invoke-PasswordManagement' }
    @{ Name = 'IdsDetection'; Interval = 60; Invoke = 'Invoke-IdsDetection' }
    @{ Name = 'CredentialDumpDetection'; Interval = 20; Invoke = 'Invoke-CredentialDumpDetection' }
    @{ Name = 'LOLBinDetection'; Interval = 30; Invoke = 'Invoke-LOLBinDetection' }
    @{ Name = 'MemoryAcquisitionDetection'; Interval = 90; Invoke = 'Invoke-MemoryAcquisitionDetection' }
    @{ Name = 'MobileDeviceMonitoring'; Interval = 90; Invoke = 'Invoke-MobileDeviceMonitoring' }
    @{ Name = 'BCDSecurity'; Interval = 300; Invoke = 'Invoke-BCDSecurity' }
    @{ Name = 'CredentialProtection'; Interval = 300; Invoke = 'Invoke-CredentialProtection' }
    @{ Name = 'HidMacroGuard'; Interval = 60; Invoke = 'Invoke-HidMacroGuard' }
    @{ Name = 'LocalProxyDetection'; Interval = 60; Invoke = 'Invoke-LocalProxyDetection' }
    @{ Name = 'ScriptContentScan'; Interval = 120; Invoke = 'Invoke-ScriptContentScan' }
    @{ Name = 'ScriptHostDetection'; Interval = 60; Invoke = 'Invoke-ScriptHostDetection' }
    @{ Name = 'MitreMapping'; Interval = 300; Invoke = 'Invoke-MitreMapping' }
    @{ Name = 'RealTimeFileMonitor'; Interval = 60; Invoke = 'Invoke-RealTimeFileMonitor' }
    @{ Name = 'KeyScramblerManagement'; Interval = 60; Invoke = 'Invoke-KeyScramblerManagement' }
    @{ Name = 'NeuroBehaviorMonitor'; Interval = 15; Invoke = 'Invoke-NeuroBehaviorMonitor' }
    @{ Name = 'StartupPersistenceDetection'; Interval = 120; Invoke = 'Invoke-StartupPersistenceDetection' }
    @{ Name = 'SuspiciousParentChildDetection'; Interval = 45; Invoke = 'Invoke-SuspiciousParentChildDetection' }
    @{ Name = 'ScriptBlockLoggingCheck'; Interval = 86400; Invoke = 'Invoke-ScriptBlockLoggingCheck' }
    @{ Name = 'DriverWatcher'; Interval = 60; Invoke = 'Invoke-DriverWatcher' }
    @{ Name = 'CrudePayloadGuard'; Interval = 60; Invoke = 'Invoke-CrudePayloadGuard' }
    @{ Name = 'PUPDetection'; Interval = 120; Invoke = 'Invoke-PUPDetection' }
    @{ Name = 'PUMDetection'; Interval = 180; Invoke = 'Invoke-PUMDetection' }
    @{ Name = 'PUADetection'; Interval = 180; Invoke = 'Invoke-PUADetection' }
    @{ Name = 'WMIPhoneHomeDetection'; Interval = 60; Invoke = 'Invoke-WMIPhoneHomeDetection' }
    @{ Name = 'WMIPolicyProtection'; Interval = 120; Invoke = 'Invoke-WMIPolicyProtection' }
    @{ Name = 'AsrRules'; Interval = 300; Invoke = 'Invoke-AsrRules' }
    @{ Name = 'CVEMitigationPatcher'; Interval = 86400; Invoke = 'Invoke-CVEMitigationPatcher' }
    @{ Name = 'PasswordRotator'; Interval = 86400; Invoke = 'Invoke-PasswordRotator' }
    @{ Name = 'GRulesC2Block'; Interval = 300; Invoke = 'Invoke-GRulesC2Block' }
    @{ Name = 'GSecurityLite'; Interval = 300; Invoke = 'Invoke-GSecurityLite' }
    @{ Name = 'AudioEnhancement'; Interval = 3600; Invoke = 'Invoke-AudioEnhancement' }
    @{ Name = 'BCDCleanupEnhanced'; Interval = 86400; Invoke = 'Invoke-BCDCleanupEnhanced' }
    @{ Name = 'BrowserHardening'; Interval = 3600; Invoke = 'Invoke-BrowserHardening' }
    @{ Name = 'CredentialHardening'; Interval = 3600; Invoke = 'Invoke-CredentialHardening' }
    @{ Name = 'PerformanceTweaks'; Interval = 86400; Invoke = 'Invoke-PerformanceTweaks' }
    @{ Name = 'NetworkDebloat'; Interval = 3600; Invoke = 'Invoke-NetworkDebloat' }
    @{ Name = 'NullSessionProtection'; Interval = 3600; Invoke = 'Invoke-NullSessionProtection' }
    @{ Name = 'RemoteAccessPrevention'; Interval = 3600; Invoke = 'Invoke-RemoteAccessPrevention' }
    @{ Name = 'SecurityPolicyHardening'; Interval = 86400; Invoke = 'Invoke-SecurityPolicyHardening' }
    @{ Name = 'SecureRemoteAccess'; Interval = 3600; Invoke = 'Invoke-SecureRemoteAccess' }
    @{ Name = 'DnsSecure'; Interval = 3600; Invoke = 'Invoke-DnsSecure' }
    @{ Name = 'DeviceFiltering'; Interval = 3600; Invoke = 'Invoke-DeviceFiltering' }
    @{ Name = 'Unhooker'; Interval = 3600; Invoke = 'Invoke-Unhooker' }
    @{ Name = 'TelemetryCorruption'; Interval = 3600; Invoke = 'Invoke-TelemetryCorruption' }
    @{ Name = 'CookieProtection'; Interval = 300; Invoke = 'Invoke-CookieProtection' }
    @{ Name = 'CustomControlsRemover'; Interval = 60; Invoke = 'Invoke-CustomControlsRemover' }
    @{ Name = 'SessionTerminator'; Interval = 30; Invoke = 'Invoke-SessionTerminator' }
    @{ Name = 'NetworkBridgeRemoval'; Interval = 30; Invoke = 'Invoke-NetworkBridgeRemoval' }
    @{ Name = 'GSecurityEnhanced'; Interval = 30; Invoke = 'Invoke-GSecurityEnhanced' }
    @{ Name = 'ProcessAuditing'; Interval = 300; Invoke = 'Invoke-ProcessAuditing' }
)

if ($UnregisterSchedule) {
    $t = Get-ScheduledTask -TaskName $script:AntivirusTaskName -ErrorAction SilentlyContinue
    if ($t) { Unregister-ScheduledTask -TaskName $script:AntivirusTaskName -Confirm:$false; Write-Host "Scheduled task '$($script:AntivirusTaskName)' removed." } else { Write-Host "Scheduled task '$($script:AntivirusTaskName)' not found." }
    exit 0
}

if ($RegisterSchedule) {
    $scriptPath = if ($PSCommandPath) { $PSCommandPath } else { $MyInvocation.MyCommand.Path }
    if (-not $scriptPath -or -not (Test-Path $scriptPath)) { Write-Host 'Could not resolve script path.'; exit 1 }
    $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument "-ExecutionPolicy Bypass -NoProfile -WindowStyle Hidden -File `"$scriptPath`"" -WorkingDirectory (Split-Path $scriptPath)
    $trigger = New-ScheduledTaskTrigger -AtStartup
    $principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
    $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1)
    $task = Get-ScheduledTask -TaskName $script:AntivirusTaskName -ErrorAction SilentlyContinue
    if ($task) { Set-ScheduledTask -TaskName $script:AntivirusTaskName -Action $action -Trigger $trigger -Principal $principal -Settings $settings | Out-Null; Write-Host "Updated scheduled task '$($script:AntivirusTaskName)'." }
    else { Register-ScheduledTask -TaskName $script:AntivirusTaskName -Action $action -Trigger $trigger -Principal $principal -Settings $settings | Out-Null; Write-Host "Registered scheduled task '$($script:AntivirusTaskName)'." }
    exit 0
}

if ($RemoveRules) {
    if (Get-Command Remove-BlockedRules -ErrorAction SilentlyContinue) { Remove-BlockedRules }; exit 0
}

Invoke-Initialization | Out-Null

$loopSleep = 5
$lastStatusUpdate = [datetime]::MinValue
while ($true) {
    $now = Get-Date
    foreach ($m in $schedule) {
        if (-not $script:ModuleLastRun.ContainsKey($m.Name)) { $script:ModuleLastRun[$m.Name] = [datetime]::MinValue }
        if (($now - $script:ModuleLastRun[$m.Name]).TotalSeconds -ge $m.Interval) {
            $script:ModuleName = $m.Name
            try { & $m.Invoke | Out-Null } catch { Write-Output "ERROR:$($m.Name):$_" }
            $script:ModuleLastRun[$m.Name] = $now
        }
    }
    if (($now - $lastStatusUpdate).TotalSeconds -ge 60) { Update-AgentStatus -ScheduleList $schedule -LastRun $script:ModuleLastRun; $lastStatusUpdate = $now }
    Start-Sleep -Seconds $loopSleep
}
Editor is loading...
Leave a Comment