User Account Control (UAC) Güvenlik Açığı: Secure Desktop ile Privilege Escalation Koruması User Account Control (UAC), Windows işletim sistemlerinin en kritik güvenlik mekanizmalarından biridir. UAC'nin secure desktop üzerinde yönetici onayı isteyecek şekilde yapılandırılmaması, malicious software'in fark edilmeden yüksek yetkilerle çalışmasına olanak tanır. Admin Approval Mode ile birlikte doğru yapılandırılan UAC, privilege escalation saldırılarına karşı güçlü bir savunma oluşturur. Bu yazıda, UAC güvenlik açığını ve "Prompt for consent on the secure desktop" yapılandırmasının önemini detaylı olarak inceleyeceğiz.
User Account Control (UAC) Architecture
UAC Security Model
Core Components:
UAC Security Stack: ┌─────────────────────────────────────┐ │ Application Request │ ├─────────────────────────────────────┤ │ Admin Approval Mode │ ← Critical Security Layer ├─────────────────────────────────────┤ │ Secure Desktop │ ← Isolation Mechanism ├─────────────────────────────────────┤ │ Elevation Prompt │ ← User Interaction ├─────────────────────────────────────┤ │ Privilege Token Management │ ← Permission Granting └─────────────────────────────────────┘
Token Architecture:
# UAC token structure function Analyze-UACTokens { $tokenInfo = @{ "Standard_User_Token" = @{ Description = "Limited privileges for daily operations" Capabilities = @("File access", "Registry read", "Network access") Restrictions = @("No system modification", "No driver installation", "No security policy changes") } "Administrator_Token" = @{ Description = "Full administrative privileges" Capabilities = @("System modification", "Driver installation", "Security policy changes", "Service management") Requirements = @("UAC elevation", "User consent", "Secure desktop prompt") } "Filtered_Admin_Token" = @{ Description = "Admin user running with standard privileges" Elevation_Process = "UAC prompt → Secure desktop → User consent → Full admin token" } } return $tokenInfo }
Admin Approval Mode Mechanics
Normal vs Admin Approval Mode:
Mode | Token Type | Privilege Level | UAC Behavior |
---|---|---|---|
Normal Admin | Full Admin Token | High | ❌ No prompts - Security risk |
Admin Approval Mode | Filtered Token → Full Token | Standard → High | ✅ UAC prompts required |
Standard User | Standard Token | Limited | ✅ Credential prompt required |
Güvenlik Riskleri ve Saldırı Vektörleri
1. Malicious Software Privilege Escalation
Silent Elevation Attacks:
# UAC bypass simulation scenarios function Simulate-UACBypassRisks { param($UACLevel) $riskScenarios = @{ "Never_Notify" = @{ RiskLevel = "CRITICAL" AttackSuccess = "99%" Description = "Malware gains admin privileges silently" Examples = @( "Rootkit installation without detection", "System file modification", "Registry security policy changes", "Service hijacking and persistence" ) } "Prompt_Without_Secure_Desktop" = @{ RiskLevel = "HIGH" AttackSuccess = "75%" Description = "UI automation attacks can bypass prompts" Examples = @( "Automated clicking of UAC dialogs", "DLL injection into UAC prompt process", "Window message spoofing", "Focus stealing attacks" ) } "Prompt_On_Secure_Desktop" = @{ RiskLevel = "LOW" AttackSuccess = "15%" Description = "Secure desktop isolation prevents most bypasses" Examples = @( "Physical access required for bypass", "Kernel-level exploits needed", "Very limited attack surface" ) } } return $riskScenarios } # Risk analysis for different UAC configurations $uacConfigs = @("Never_Notify", "Prompt_Without_Secure_Desktop", "Prompt_On_Secure_Desktop") foreach ($config in $uacConfigs) { $risk = Simulate-UACBypassRisks -UACLevel $config Write-Output "`nUAC Configuration: $config" Write-Output "Risk Level: $($risk.RiskLevel)" Write-Output "Attack Success Rate: $($risk.AttackSuccess)" Write-Output "Description: $($risk.Description)" }
2. UI Automation Bypass Attacks
Non-Secure Desktop Vulnerabilities:
// Example UAC bypass technique (educational purpose) /* Common UAC bypass methods when secure desktop is disabled: 1. SendMessage/PostMessage API abuse: - Send WM_COMMAND to UAC dialog - Automated button clicking - Focus manipulation 2. DLL Injection: - Inject code into UAC prompt process - Modify prompt behavior - Auto-approve elevation requests 3. COM Interface Exploitation: - Abuse IFileOperation interface - ICMLuaUtil interface misuse - Auto-elevation registry keys 4. Windows API Manipulation: - SetWindowPos to hide/modify UAC prompt - FindWindow + SendMessage combinations - Window subclassing attacks */
Secure Desktop Protection Mechanism:
Secure Desktop Benefits: ┌─────────────────────────────────────┐ │ Normal Desktop (Vulnerable) │ │ ┌─────────────────────────────┐ │ │ │ Malware Process │ │ ← Can interact with UAC │ │ ┌─────────────────────────┐ │ │ │ │ │ UAC Prompt │ │ │ ← Attackable │ │ └─────────────────────────┘ │ │ │ └─────────────────────────────┘ │ └─────────────────────────────────────┘ vs ┌─────────────────────────────────────┐ │ Secure Desktop (Protected) │ │ ┌─────────────────────────────┐ │ │ │ Isolated UAC Environment │ │ ← Complete isolation │ │ ┌─────────────────────────┐ │ │ │ │ │ UAC Prompt │ │ │ ← Protected │ │ └─────────────────────────┘ │ │ │ └─────────────────────────────┘ │ └─────────────────────────────────────┘ │ Normal Desktop │ │ ┌─────────────────────────────┐ │ │ │ Malware Process │ │ ← Cannot access UAC │ └─────────────────────────────┘ │ └─────────────────────────────────────┘
3. Real-World Attack Scenarios
Common UAC Bypass Techniques:
function Analyze-UACBypassTechniques { $bypassMethods = @{ "Registry_Hijacking" = @{ Description = "Modify auto-elevation registry keys" RequiredPrivileges = "Standard user" SuccessRate_NoSecureDesktop = "High" SuccessRate_SecureDesktop = "Low" Example = "HKCU\Software\Classes\ms-settings\shell\open\command manipulation" } "COM_Interface_Abuse" = @{ Description = "Exploit Windows COM objects for elevation" RequiredPrivileges = "Standard user" SuccessRate_NoSecureDesktop = "High" SuccessRate_SecureDesktop = "Medium" Example = "ICMLuaUtil, IFileOperation interface abuse" } "DLL_Hijacking" = @{ Description = "Replace legitimate DLLs in auto-elevate processes" RequiredPrivileges = "Write access to specific directories" SuccessRate_NoSecureDesktop = "Medium" SuccessRate_SecureDesktop = "Low" Example = "windir\System32\sysprep\cryptbase.dll replacement" } "Process_Injection" = @{ Description = "Inject code into high-privilege processes" RequiredPrivileges = "Process creation/injection capabilities" SuccessRate_NoSecureDesktop = "High" SuccessRate_SecureDesktop = "Very Low" Example = "Inject into winlogon.exe, explorer.exe elevation" } } return $bypassMethods } # Analyze bypass techniques effectiveness $techniques = Analyze-UACBypassTechniques foreach ($technique in $techniques.Keys) { $method = $techniques Write-Output "`nTechnique: $technique" Write-Output "Description: $($method.Description)" Write-Output "Success without Secure Desktop: $($method.SuccessRate_NoSecureDesktop)" Write-Output "Success with Secure Desktop: $($method.SuccessRate_SecureDesktop)" }
Çözüm Yöntemleri
1. Group Policy (GPO) Configuration
Computer Configuration Settings:
Yol: Computer Configuration → Windows Settings → Security Settings → Local Policies → Security Options
Kritik UAC Policies:
User Account Control: Run all administrators in Admin Approval Mode = Enabled User Account Control: Behavior of the elevation prompt for administrators in Admin Approval Mode = Prompt for consent on the secure desktop User Account Control: Behavior of the elevation prompt for standard users = Prompt for credentials on the secure desktop User Account Control: Detect application installations and prompt for elevation = Enabled User Account Control: Only elevate UIAccess applications that are installed in secure locations = Enabled User Account Control: Switch to the secure desktop when prompting for elevation = Enabled
PowerShell GPO Implementation:
function Set-SecureUACPolicy { param( $GPOName = "Secure UAC Configuration", $TargetOU = "OU=Computers,DC=company,DC=com" ) try { Import-Module GroupPolicy # Create or get existing GPO $gpo = Get-GPO -Name $GPOName -ErrorAction SilentlyContinue if (-not $gpo) { $gpo = New-GPO -Name $GPOName -Comment "Configures secure UAC settings with Admin Approval Mode and Secure Desktop" Write-Output "✅ Created new GPO: $GPOName" } $registryPath = "HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System" # Core UAC Settings $uacSettings = @{ # Enable Admin Approval Mode "EnableLUA" = 1 # Prompt for consent on secure desktop for administrators "ConsentPromptBehaviorAdmin" = 2 # Prompt for credentials on secure desktop for standard users "ConsentPromptBehaviorUser" = 3 # Enable secure desktop for elevation prompts "PromptOnSecureDesktop" = 1 # Detect application installations "EnableInstallerDetection" = 1 # Only elevate signed and validated executables "ValidateAdminCodeSignatures" = 1 # Only elevate UIAccess applications from secure locations "EnableSecureUIAPaths" = 1 } foreach ($setting in $uacSettings.Keys) { Set-GPRegistryValue -Name $GPOName -Key $registryPath -ValueName $setting -Value $uacSettings -Type DWord Write-Output "✅ Set $setting = $($uacSettings)" } # Link GPO to target OU try { New-GPLink -Name $GPOName -Target $TargetOU -LinkEnabled Yes Write-Output "✅ GPO linked to: $TargetOU" } catch { Write-Warning "GPO linking: $($_.Exception.Message)" } Write-Output "`n✅ Secure UAC policy configured successfully" Write-Output " - Admin Approval Mode: Enabled" Write-Output " - Secure Desktop: Enabled" Write-Output " - Admin Behavior: Prompt for consent on secure desktop" Write-Output " - User Behavior: Prompt for credentials on secure desktop" return @{ GPOName = $GPOName Status = "Success" Settings = $uacSettings } } catch { Write-Error "❌ Failed to configure secure UAC policy: $($_.Exception.Message)" return @{ GPOName = $GPOName Status = "Failed" Error = $_.Exception.Message } } } # Apply secure UAC configuration $uacResult = Set-SecureUACPolicy
2. Registry-Based Local Configuration
Direct Registry Implementation:
function Set-LocalUACConfiguration { param( $AdminBehavior = 2, # Prompt for consent on secure desktop $UserBehavior = 3, # Prompt for credentials on secure desktop $EnableSecureDesktop = $true, $EnableAdminApprovalMode = $true ) $registryPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" try { Write-Output "Configuring local UAC settings..." # Verify registry path exists if (!(Test-Path $registryPath)) { New-Item -Path $registryPath -Force | Out-Null } # Core UAC configuration $configurations = @{ "EnableLUA" = if ($EnableAdminApprovalMode) { 1 } else { 0 } "ConsentPromptBehaviorAdmin" = $AdminBehavior "ConsentPromptBehaviorUser" = $UserBehavior "PromptOnSecureDesktop" = if ($EnableSecureDesktop) { 1 } else { 0 } "EnableInstallerDetection" = 1 "ValidateAdminCodeSignatures" = 1 "EnableSecureUIAPaths" = 1 } foreach ($config in $configurations.Keys) { Set-ItemProperty -Path $registryPath -Name $config -Value $configurations -Type DWord Write-Output "✅ $config = $($configurations)" } # Validate configuration $currentSettings = Get-ItemProperty -Path $registryPath $validationResults = @{ AdminApprovalModeEnabled = ($currentSettings.EnableLUA -eq 1) SecureDesktopEnabled = ($currentSettings.PromptOnSecureDesktop -eq 1) AdminBehaviorSecure = ($currentSettings.ConsentPromptBehaviorAdmin -eq 2) UserBehaviorSecure = ($currentSettings.ConsentPromptBehaviorUser -eq 3) } $isFullySecure = $validationResults.Values -notcontains $false Write-Output "`n=== UAC CONFIGURATION VALIDATION ===" Write-Output "Admin Approval Mode: $(if ($validationResults.AdminApprovalModeEnabled) { '✅ Enabled' } else { '❌ Disabled' })" Write-Output "Secure Desktop: $(if ($validationResults.SecureDesktopEnabled) { '✅ Enabled' } else { '❌ Disabled' })" Write-Output "Admin Behavior: $(if ($validationResults.AdminBehaviorSecure) { '✅ Secure' } else { '❌ Not Secure' })" Write-Output "User Behavior: $(if ($validationResults.UserBehaviorSecure) { '✅ Secure' } else { '❌ Not Secure' })" Write-Output "Overall Security: $(if ($isFullySecure) { '✅ SECURE' } else { '❌ NEEDS ATTENTION' })" if (-not $isFullySecure) { Write-Warning "⚠️ UAC configuration is not fully secure! Please review settings." } return @{ Success = $true SecureConfiguration = $isFullySecure Settings = $configurations Validation = $validationResults } } catch { Write-Error "❌ Failed to configure local UAC: $($_.Exception.Message)" return @{ Success = $false Error = $_.Exception.Message } } } # Apply local UAC configuration $localUAC = Set-LocalUACConfiguration
3. PowerShell DSC Implementation
Desired State Configuration for UAC:
Configuration SecureUACConfiguration { param( ]$ComputerName = 'localhost', $AdminPromptBehavior = 2, # Prompt for consent on secure desktop $StandardUserPromptBehavior = 3, # Prompt for credentials on secure desktop $EnableSecureDesktop = $true, $EnableAdminApprovalMode = $true ) Node $ComputerName { # Enable Admin Approval Mode Registry EnableAdminApprovalMode { Key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' ValueName = 'EnableLUA' ValueData = if ($EnableAdminApprovalMode) { '1' } else { '0' } ValueType = 'Dword' Ensure = 'Present' } # Set administrator prompt behavior Registry AdminPromptBehavior { Key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' ValueName = 'ConsentPromptBehaviorAdmin' ValueData = $AdminPromptBehavior.ToString() ValueType = 'Dword' Ensure = 'Present' DependsOn = 'EnableAdminApprovalMode' } # Set standard user prompt behavior Registry StandardUserPromptBehavior { Key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' ValueName = 'ConsentPromptBehaviorUser' ValueData = $StandardUserPromptBehavior.ToString() ValueType = 'Dword' Ensure = 'Present' } # Enable secure desktop for prompts Registry SecureDesktop { Key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' ValueName = 'PromptOnSecureDesktop' ValueData = if ($EnableSecureDesktop) { '1' } else { '0' } ValueType = 'Dword' Ensure = 'Present' } # Enable installer detection Registry InstallerDetection { Key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' ValueName = 'EnableInstallerDetection' ValueData = '1' ValueType = 'Dword' Ensure = 'Present' } # Validate admin code signatures Registry ValidateCodeSignatures { Key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' ValueName = 'ValidateAdminCodeSignatures' ValueData = '1' ValueType = 'Dword' Ensure = 'Present' } # Enable secure UI access paths Registry SecureUIAccessPaths { Key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' ValueName = 'EnableSecureUIAPaths' ValueData = '1' ValueType = 'Dword' Ensure = 'Present' } } } # Compile and apply DSC configuration SecureUACConfiguration -ComputerName $env:COMPUTERNAME Start-DscConfiguration -Path .\SecureUACConfiguration -Wait -Verbose -Force # Test DSC configuration Test-DscConfiguration -Path .\SecureUACConfiguration -Verbose
UAC Level Analysis ve Optimization
1. UAC Security Level Comparison
Detailed Level Analysis:
function Get-UACSecurityLevels { $securityLevels = @{ "Level_0_Never_Notify" = @{ ConsentPromptBehaviorAdmin = 0 ConsentPromptBehaviorUser = 0 PromptOnSecureDesktop = 0 SecurityRating = "CRITICAL RISK" Description = "Never notify - UAC completely disabled" UseCases = @("Never recommended", "Legacy application compatibility only") Vulnerabilities = @( "Silent privilege escalation", "Malware runs with admin rights", "No protection against privilege abuse", "Complete UAC bypass" ) } "Level_1_Default_Prompt" = @{ ConsentPromptBehaviorAdmin = 5 ConsentPromptBehaviorUser = 3 PromptOnSecureDesktop = 1 SecurityRating = "MEDIUM RISK" Description = "Prompt for consent for non-Windows binaries" UseCases = @("Default Windows configuration", "Basic security needs") Vulnerabilities = @( "Signed malware bypasses prompts", "Windows binary exploitation", "Limited protection scope" ) } "Level_2_Always_Notify_No_Secure_Desktop" = @{ ConsentPromptBehaviorAdmin = 2 ConsentPromptBehaviorUser = 3 PromptOnSecureDesktop = 0 SecurityRating = "HIGH RISK" Description = "Always notify but not on secure desktop" UseCases = @("Legacy systems", "Compatibility requirements") Vulnerabilities = @( "UI automation attacks", "DLL injection bypasses", "Window message spoofing", "Focus stealing attacks" ) } "Level_3_Always_Notify_Secure_Desktop" = @{ ConsentPromptBehaviorAdmin = 2 ConsentPromptBehaviorUser = 3 PromptOnSecureDesktop = 1 SecurityRating = "LOW RISK" Description = "Always notify on secure desktop (RECOMMENDED)" UseCases = @("Production environments", "High security requirements", "Best practice") Vulnerabilities = @( "Physical access bypass only", "Kernel-level exploits required", "Very limited attack surface" ) } } return $securityLevels } # Compare UAC security levels $levels = Get-UACSecurityLevels Write-Output "=== UAC SECURITY LEVEL COMPARISON ===" foreach ($level in $levels.Keys) { $config = $levels Write-Output "`n$level" Write-Output "Security Rating: $($config.SecurityRating)" Write-Output "Description: $($config.Description)" Write-Output "Registry Values:" Write-Output " ConsentPromptBehaviorAdmin: $($config.ConsentPromptBehaviorAdmin)" Write-Output " ConsentPromptBehaviorUser: $($config.ConsentPromptBehaviorUser)" Write-Output " PromptOnSecureDesktop: $($config.PromptOnSecureDesktop)" Write-Output "Use Cases: $($config.UseCases -join ', ')" Write-Output "Main Vulnerabilities: $($config.Vulnerabilities -join ', ')" }
2. Custom UAC Hardening
Advanced Security Configuration:
function Set-HardenedUACConfiguration { param( $EnableAdvancedLogging = $true, $EnableCodeSignatureValidation = $true, $RestrictUIAccessApplications = $true, $ElevationTimeout = 120 # seconds ) $registryPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" try { # Standard secure configuration $coreSettings = @{ EnableLUA = 1 # Admin Approval Mode ConsentPromptBehaviorAdmin = 2 # Prompt for consent on secure desktop ConsentPromptBehaviorUser = 3 # Prompt for credentials on secure desktop PromptOnSecureDesktop = 1 # Use secure desktop EnableInstallerDetection = 1 # Detect installers ValidateAdminCodeSignatures = if ($EnableCodeSignatureValidation) { 1 } else { 0 } EnableSecureUIAPaths = if ($RestrictUIAccessApplications) { 1 } else { 0 } } # Advanced hardening settings $advancedSettings = @{ # Filter local administrator token FilterAdministratorToken = 1 # Enable elevated process tracking EnableUIADesktopToggle = 0 # Suppress UAC prompt timeout UACDisableNotification = 0 } # Apply core settings foreach ($setting in $coreSettings.Keys) { Set-ItemProperty -Path $registryPath -Name $setting -Value $coreSettings -Type DWord } # Apply advanced settings foreach ($setting in $advancedSettings.Keys) { Set-ItemProperty -Path $registryPath -Name $setting -Value $advancedSettings -Type DWord } # Configure elevation timeout if ($ElevationTimeout -gt 0) { Set-ItemProperty -Path $registryPath -Name "ElevationPromptTimeout" -Value $ElevationTimeout -Type DWord } # Enable advanced auditing if ($EnableAdvancedLogging) { Enable-UACAdvancedAuditing } Write-Output "✅ Hardened UAC configuration applied" Write-Output " - Maximum security settings enabled" Write-Output " - Code signature validation: $(if ($EnableCodeSignatureValidation) { 'Enabled' } else { 'Disabled' })" Write-Output " - UI Access restrictions: $(if ($RestrictUIAccessApplications) { 'Enabled' } else { 'Disabled' })" Write-Output " - Elevation timeout: $ElevationTimeout seconds" Write-Output " - Advanced logging: $(if ($EnableAdvancedLogging) { 'Enabled' } else { 'Disabled' })" return @{ Success = $true CoreSettings = $coreSettings AdvancedSettings = $advancedSettings ElevationTimeout = $ElevationTimeout } } catch { Write-Error "❌ Failed to apply hardened UAC configuration: $($_.Exception.Message)" return @{ Success = $false Error = $_.Exception.Message } } } function Enable-UACAdvancedAuditing { try { # Enable detailed UAC logging auditpol /set /subcategory:"Process Creation" /success:enable /failure:enable auditpol /set /subcategory:"Handle Manipulation" /success:enable /failure:enable auditpol /set /subcategory:"Privilege Use" /success:enable /failure:enable # Configure event log sizes for UAC events wevtutil sl Security /ms:1048576000 # 1GB Security log wevtutil sl Application /ms:104857600 # 100MB Application log Write-Output "✅ Advanced UAC auditing enabled" } catch { Write-Warning "⚠️ Failed to enable advanced auditing: $($_.Exception.Message)" } } # Apply hardened configuration $hardenedUAC = Set-HardenedUACConfiguration
Monitoring ve Detection
1. UAC Event Monitoring
Comprehensive UAC Event Analysis:
function Monitor-UACEvents { param( $LookbackHours = 24, $DetectBypassAttempts = $true, $AnalyzeElevationPatterns = $true ) $startTime = (Get-Date).AddHours(-$LookbackHours) # UAC-related Event IDs $uacEventIDs = @{ 4688 = "Process Creation (with elevation info)" 4672 = "Special privileges assigned to new logon" 4648 = "Logon with explicit credentials (RunAs)" 5376 = "Credential Manager credentials backed up" 4103 = "PowerShell module logging (potential UAC bypass)" 4104 = "PowerShell script block logging" } $events = Get-WinEvent -FilterHashtable @{ LogName = 'Security' ID = $uacEventIDs.Keys StartTime = $startTime } -ErrorAction SilentlyContinue $uacAnalysis = @{ TotalElevations = 0 BypassAttempts = @() SuspiciousPatterns = @() ProcessElevations = @() TimelineAnalysis = @{} } foreach ($event in $events) { $eventData = @{ TimeCreated = $event.TimeCreated EventId = $event.Id ProcessName = "" UserName = "" ElevationType = "" TokenElevationType = "" } # Parse process creation events (4688) if ($event.Id -eq 4688) { $eventData.ProcessName = $event.Properties.Value $eventData.UserName = $event.Properties.Value $eventData.TokenElevationType = $event.Properties.Value # Check for elevation if ($eventData.TokenElevationType -eq "1" -or $eventData.TokenElevationType -eq "2") { $uacAnalysis.TotalElevations++ $uacAnalysis.ProcessElevations += $eventData # Detect potential bypass attempts if ($DetectBypassAttempts) { $suspiciousProcesses = @("powershell.exe", "cmd.exe", "rundll32.exe", "regsvr32.exe", "mshta.exe", "cscript.exe", "wscript.exe") $processName = Split-Path $eventData.ProcessName -Leaf if ($processName -in $suspiciousProcesses) { $uacAnalysis.BypassAttempts += @{ Time = $eventData.TimeCreated Process = $eventData.ProcessName User = $eventData.UserName Reason = "Suspicious process elevated without expected UAC prompt" RiskLevel = "High" } } } } } # Parse privilege assignment events (4672) if ($event.Id -eq 4672) { $privileges = $event.Properties.Value if ($privileges -match "SeDebugPrivilege|SeTcbPrivilege|SeCreateTokenPrivilege") { $uacAnalysis.BypassAttempts += @{ Time = $event.TimeCreated Process = "Unknown" User = $event.Properties.Value Reason = "High-privilege assignment detected" RiskLevel = "Medium" } } } } # Timeline analysis if ($AnalyzeElevationPatterns) { $hourlyElevations = $uacAnalysis.ProcessElevations | Group-Object {$_.TimeCreated.Hour} | ForEach-Object { @{ Hour = $_.Name Count = $_.Count Processes = ($_.Group | Select-Object -ExpandProperty ProcessName | Sort-Object -Unique) } } $uacAnalysis.TimelineAnalysis = $hourlyElevations # Detect anomalous patterns $averageElevations = ($hourlyElevations | Measure-Object Count -Average).Average $anomalousHours = $hourlyElevations | Where-Object {$_.Count -gt ($averageElevations * 3)} foreach ($hour in $anomalousHours) { $uacAnalysis.SuspiciousPatterns += @{ Type = "Elevation Spike" Time = "Hour $($hour.Hour)" Details = "$($hour.Count) elevations (3x average)" Processes = $hour.Processes } } } # Generate security alerts $criticalFindings = $uacAnalysis.BypassAttempts | Where-Object {$_.RiskLevel -eq "High"} if ($criticalFindings.Count -gt 0) { $alertMessage = @" 🚨 UAC SECURITY ALERT 🚨 Time Period: Last $LookbackHours hours Total Elevations: $($uacAnalysis.TotalElevations) Bypass Attempts: $($uacAnalysis.BypassAttempts.Count) Critical Findings: $($criticalFindings.Count) HIGH RISK ACTIVITIES: $($criticalFindings | ForEach-Object { "⚠️ $($_.Time): $($_.Process) by $($_.User) - $($_.Reason)" } | Out-String) RECOMMENDATIONS: • Review UAC configuration immediately • Investigate suspicious process elevations • Enable enhanced logging and monitoring • Consider additional endpoint protection Please investigate these findings immediately. "@ Write-Warning $alertMessage # Optional: Send alert if ($global:SecurityAlertEmail) { Send-MailMessage -To $global:SecurityAlertEmail -Subject "UAC Security Alert - Potential Bypass Detected" -Body $alertMessage -SmtpServer $global:SMTPServer } } return $uacAnalysis } # Schedule UAC monitoring Register-ScheduledTask -TaskName "Monitor-UACEvents" -Action (New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-Command Monitor-UACEvents") -Trigger (New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours 4))
2. UAC Configuration Compliance
Automated Compliance Checking:
function Test-UACCompliance { param( ]$ComputerNames = @($env:COMPUTERNAME), $RequiredSettings = @{ EnableLUA = 1 ConsentPromptBehaviorAdmin = 2 ConsentPromptBehaviorUser = 3 PromptOnSecureDesktop = 1 EnableInstallerDetection = 1 ValidateAdminCodeSignatures = 1 EnableSecureUIAPaths = 1 } ) $complianceResults = foreach ($computer in $ComputerNames) { try { $result = Invoke-Command -ComputerName $computer -ScriptBlock { param($RequiredSettings) $registryPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" $currentSettings = @{} $complianceIssues = @() foreach ($setting in $RequiredSettings.Keys) { try { $value = Get-ItemProperty -Path $registryPath -Name $setting -ErrorAction SilentlyContinue $currentSettings = if ($value) { $value.$setting } else { 0 } if ($currentSettings -ne $RequiredSettings) { $complianceIssues += @{ Setting = $setting Required = $RequiredSettings Current = $currentSettings Severity = switch ($setting) { "EnableLUA" { "Critical" } "PromptOnSecureDesktop" { "Critical" } "ConsentPromptBehaviorAdmin" { "High" } default { "Medium" } } } } } catch { $complianceIssues += @{ Setting = $setting Required = $RequiredSettings Current = "ERROR" Severity = "Critical" Error = $_.Exception.Message } } } # Calculate compliance score $totalSettings = $RequiredSettings.Count $compliantSettings = $totalSettings - $complianceIssues.Count $complianceScore = ::Round(($compliantSettings / $totalSettings) * 100, 1) # Determine overall compliance level $complianceLevel = switch ($complianceScore) { {$_ -eq 100} { "Fully Compliant" } {$_ -ge 80} { "Mostly Compliant" } {$_ -ge 60} { "Partially Compliant" } {$_ -ge 40} { "Poor Compliance" } default { "Non-Compliant" } } return @{ ComputerName = $env:COMPUTERNAME ComplianceScore = $complianceScore ComplianceLevel = $complianceLevel IsCompliant = ($complianceIssues.Count -eq 0) CurrentSettings = $currentSettings ComplianceIssues = $complianceIssues CriticalIssues = ($complianceIssues | Where-Object {$_.Severity -eq "Critical"}).Count HighIssues = ($complianceIssues | Where-Object {$_.Severity -eq "High"}).Count LastChecked = Get-Date } } -ArgumentList $RequiredSettings $result } catch { @{ ComputerName = $computer ComplianceScore = 0 ComplianceLevel = "Error" IsCompliant = $false CurrentSettings = @{} ComplianceIssues = @() CriticalIssues = 1 HighIssues = 0 LastChecked = Get-Date Error = $_.Exception.Message } } } # Generate summary report $summary = @{ TotalSystems = $complianceResults.Count CompliantSystems = ($complianceResults | Where-Object IsCompliant).Count NonCompliantSystems = ($complianceResults | Where-Object {-not $_.IsCompliant}).Count CompliancePercentage = ::Round((($complianceResults | Where-Object IsCompliant).Count / $complianceResults.Count) * 100, 2) AverageComplianceScore = ::Round(($complianceResults | Measure-Object ComplianceScore -Average).Average, 1) CriticalIssuesCount = ($complianceResults | Measure-Object CriticalIssues -Sum).Sum HighIssuesCount = ($complianceResults | Measure-Object HighIssues -Sum).Sum ComplianceLevelDistribution = $complianceResults | Group-Object ComplianceLevel | Select-Object Name, Count } return @{ DetailedResults = $complianceResults Summary = $summary RecommendedActions = Get-UACComplianceRecommendations -Results $complianceResults AuditDate = Get-Date } } function Get-UACComplianceRecommendations { param($Results) $recommendations = @() # Critical issues $criticalSystems = $Results | Where-Object {$_.CriticalIssues -gt 0} if ($criticalSystems.Count -gt 0) { $recommendations += "🚨 CRITICAL: $($criticalSystems.Count) systems have critical UAC configuration issues" $recommendations += " → Immediately review and fix Admin Approval Mode and Secure Desktop settings" } # Non-compliant systems $nonCompliantCount = ($Results | Where-Object {-not $_.IsCompliant}).Count if ($nonCompliantCount -gt 0) { $recommendations += "⚠️ HIGH: $nonCompliantCount systems are not fully UAC compliant" $recommendations += " → Deploy standardized UAC GPO across all systems" } # Low compliance scores $lowComplianceSystems = $Results | Where-Object {$_.ComplianceScore -lt 60} if ($lowComplianceSystems.Count -gt 0) { $recommendations += "📊 MEDIUM: $($lowComplianceSystems.Count) systems have compliance scores below 60%" $recommendations += " → Prioritize these systems for immediate remediation" } # General recommendations $recommendations += "✅ GENERAL: Implement automated UAC compliance monitoring" $recommendations += "✅ GENERAL: Schedule regular UAC configuration audits" $recommendations += "✅ GENERAL: Provide user education on UAC prompts and security" return $recommendations } # Run compliance check $complianceReport = Test-UACCompliance $complianceReport.DetailedResults | Export-Csv -Path "UACCompliance_$(Get-Date -Format 'yyyyMMdd').csv" Write-Output "`n=== UAC COMPLIANCE AUDIT SUMMARY ===" Write-Output "Total Systems: $($complianceReport.Summary.TotalSystems)" Write-Output "Compliant Systems: $($complianceReport.Summary.CompliantSystems)" Write-Output "Compliance Rate: $($complianceReport.Summary.CompliancePercentage)%" Write-Output "Average Score: $($complianceReport.Summary.AverageComplianceScore)%" Write-Output "Critical Issues: $($complianceReport.Summary.CriticalIssuesCount)" Write-Output "`n=== RECOMMENDED ACTIONS ===" $complianceReport.RecommendedActions | ForEach-Object { Write-Output $_ }
3. Real-Time UAC Bypass Detection
Advanced Threat Detection:
function Enable-UACBypassDetection { param( $MonitorRegistryChanges = $true, $MonitorProcessCreation = $true, $MonitorCOMObjects = $true, $LogPath = "C:\Logs\UAC_Security.log" ) Write-Output "Enabling UAC bypass detection mechanisms..." # Create log directory $logDir = Split-Path $LogPath -Parent if (!(Test-Path $logDir)) { New-Item -Path $logDir -ItemType Directory -Force | Out-Null } # Registry monitoring for UAC bypass techniques if ($MonitorRegistryChanges) { $registryWatcher = Register-WmiEvent -Query "SELECT * FROM RegistryTreeChangeEvent WHERE Hive='HKEY_CURRENT_USER' AND RootPath='Software\\Classes\\ms-settings\\shell\\open\\command'" -Action { $event = $Event.SourceEventArgs.NewEvent $alertMessage = @" 🚨 UAC BYPASS ATTEMPT DETECTED 🚨 Time: $(Get-Date) Type: Registry Hijacking (ms-settings) User: $($env:USERNAME) Computer: $($env:COMPUTERNAME) Registry Path: $($event.RootPath) This is a known UAC bypass technique! Immediate investigation required. "@ Write-Warning $alertMessage Add-Content -Path $using:LogPath -Value "$(Get-Date): UAC Registry Bypass Attempt - ms-settings hijack by $($env:USERNAME)" } Write-Output "✅ Registry monitoring enabled for UAC bypass detection" } # Process creation monitoring if ($MonitorProcessCreation) { $processWatcher = Register-WmiEvent -Query "SELECT * FROM Win32_ProcessStartTrace" -Action { $process = $Event.SourceEventArgs.NewEvent $processName = $process.ProcessName # Known UAC bypass processes $suspiciousProcesses = @( "fodhelper.exe", "computerdefaults.exe", "sdclt.exe", "eventvwr.exe", "compmgmtlauncher.exe" ) if ($processName -in $suspiciousProcesses) { $parentProcess = Get-WmiObject -Class Win32_Process -Filter "ProcessId = $($process.ParentProcessId)" if ($parentProcess -and $parentProcess.Name -in @("powershell.exe", "cmd.exe", "rundll32.exe")) { $alertMessage = @" 🚨 POTENTIAL UAC BYPASS DETECTED 🚨 Time: $(Get-Date) Type: Process-based UAC bypass Suspicious Process: $processName Parent Process: $($parentProcess.Name) Command Line: $($parentProcess.CommandLine) User: $($env:USERNAME) Investigation recommended! "@ Write-Warning $alertMessage Add-Content -Path $using:LogPath -Value "$(Get-Date): Potential UAC Process Bypass - $processName launched by $($parentProcess.Name)" } } } Write-Output "✅ Process monitoring enabled for UAC bypass detection" } # COM object monitoring if ($MonitorCOMObjects) { # Monitor for known COM-based UAC bypass techniques $comWatcher = Register-WmiEvent -Query "SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName = 'dllhost.exe'" -Action { $process = $Event.SourceEventArgs.NewEvent $commandLine = (Get-WmiObject -Class Win32_Process -Filter "ProcessId = $($process.ProcessId)").CommandLine # Check for suspicious COM CLSIDs used in UAC bypasses $suspiciousCLSIDs = @( "3E5FC7F9-9A51-4367-9063-A120244FBEC7", # CMSTPLUA "D2E7041B-2927-42fb-8E9F-7CE93B6DC937", # ColorControl "9BA05972-F6A8-11CF-A442-00A0C90A8F39" # ShellWindows ) foreach ($clsid in $suspiciousCLSIDs) { if ($commandLine -like "*$clsid*") { $alertMessage = @" 🚨 COM-BASED UAC BYPASS DETECTED 🚨 Time: $(Get-Date) Type: COM interface abuse CLSID: $clsid Process: dllhost.exe (PID: $($process.ProcessId)) Command Line: $commandLine This indicates potential UAC bypass exploitation! "@ Write-Warning $alertMessage Add-Content -Path $using:LogPath -Value "$(Get-Date): COM UAC Bypass - CLSID $clsid abuse detected" } } } Write-Output "✅ COM object monitoring enabled for UAC bypass detection" } return @{ RegistryMonitoring = $MonitorRegistryChanges ProcessMonitoring = $MonitorProcessCreation COMMonitoring = $MonitorCOMObjects LogPath = $LogPath Status = "Active" } } # Enable bypass detection $bypassDetection = Enable-UACBypassDetection Write-Output "`n✅ UAC bypass detection system enabled" Write-Output "Log file: $($bypassDetection.LogPath)"
User Education ve Best Practices
1. UAC User Training Program
Comprehensive User Education:
function New-UACUserEducation { $educationContent = @{ "UAC_Basics" = @" 🛡️ USER ACCOUNT CONTROL (UAC) BASICS 🎯 WHAT IS UAC? • Security feature that prevents unauthorized changes • Protects your computer from malicious software • Requires administrator permission for system changes • Creates a secure environment for elevation prompts 🔐 WHY UAC MATTERS: • Prevents malware from gaining admin privileges • Stops accidental system modifications • Provides audit trail of privilege escalations • Essential part of Windows security architecture ✅ WHEN UAC PROMPTS APPEAR: • Installing new software • Modifying system settings • Accessing protected folders • Running administrative tools • Making registry changes "@ "Secure_Desktop_Benefits" = @" 🔒 SECURE DESKTOP PROTECTION 🛡️ WHAT IS SECURE DESKTOP? • Isolated environment for UAC prompts • Prevents malware from interfering with prompts • Dims screen background during elevation • Creates secure communication channel ⚡ SECURITY BENEFITS: • Blocks automated clicking attacks • Prevents DLL injection bypasses • Stops window message spoofing • Eliminates focus stealing attacks 🚨 WARNING SIGNS: • UAC prompt appears without dimmed screen • Multiple rapid-fire UAC prompts • Unexpected elevation requests • Prompts for unknown applications "@ "Best_Practices" = @" 👤 UAC BEST PRACTICES FOR USERS ✅ DO: • Read UAC prompts carefully before clicking • Verify the program name and publisher • Check digital signatures on software • Report suspicious prompts to IT immediately • Use standard user accounts for daily tasks • Keep administrator accounts separate ❌ DON'T: • Click "Yes" without reading the prompt • Disable UAC for convenience • Run unknown software as administrator • Share administrator passwords • Ignore publisher verification warnings • Install software from untrusted sources 🔍 WHAT TO CHECK: • Program name and location • Publisher information and digital signature • Reason for elevation request • Whether you initiated the action "@ "Troubleshooting" = @" 🔧 UAC TROUBLESHOOTING GUIDE ❓ COMMON ISSUES: • "The requested operation requires elevation" • Program won't run without admin rights • UAC prompts appear too frequently • Unable to modify certain files/folders 🛠️ SOLUTIONS: • Right-click → "Run as administrator" • Check if you have necessary permissions • Contact IT for persistent issues • Never disable UAC completely 📞 WHEN TO GET HELP: • Unexpected UAC prompts for unknown programs • UAC prompts without secure desktop (dimmed screen) • Multiple prompts in rapid succession • Error messages you don't understand • Suspected malware or security breach 🆘 EMERGENCY CONTACTS: • IT Help Desk: help@company.com • Security Team: security@company.com • Emergency: +1-555-IT-HELP "@ } return $educationContent } # Generate user education materials $education = New-UACUserEducation Write-Output "=== UAC USER EDUCATION MATERIALS ===" $education.Values | ForEach-Object { Write-Output $_ Write-Output "`n" + ("="*60) + "`n" }
2. UAC Configuration Templates
Organization-Specific Templates:
function New-UACConfigurationTemplates { $templates = @{ "High_Security_Environment" = @{ Name = "High Security (Government/Financial)" Settings = @{ EnableLUA = 1 ConsentPromptBehaviorAdmin = 2 # Always prompt for consent on secure desktop ConsentPromptBehaviorUser = 3 # Prompt for credentials on secure desktop PromptOnSecureDesktop = 1 # Always use secure desktop EnableInstallerDetection = 1 # Detect installers ValidateAdminCodeSignatures = 1 # Require signed executables EnableSecureUIAPaths = 1 # Restrict UIAccess applications FilterAdministratorToken = 1 # Filter built-in admin token } Description = "Maximum security UAC configuration for high-risk environments" UseCases = @("Government agencies", "Financial institutions", "Healthcare", "Critical infrastructure") } "Corporate_Standard" = @{ Name = "Corporate Standard (Balanced Security)" Settings = @{ EnableLUA = 1 ConsentPromptBehaviorAdmin = 2 # Prompt for consent on secure desktop ConsentPromptBehaviorUser = 3 # Prompt for credentials on secure desktop PromptOnSecureDesktop = 1 # Use secure desktop EnableInstallerDetection = 1 # Detect installers ValidateAdminCodeSignatures = 0 # Allow unsigned executables (compatibility) EnableSecureUIAPaths = 1 # Restrict UIAccess applications } Description = "Balanced security and usability for corporate environments" UseCases = @("Corporate workstations", "Business applications", "Mixed environment") } "Development_Environment" = @{ Name = "Development (Developer Workstations)" Settings = @{ EnableLUA = 1 ConsentPromptBehaviorAdmin = 5 # Prompt for non-Windows binaries only ConsentPromptBehaviorUser = 3 # Prompt for credentials on secure desktop PromptOnSecureDesktop = 1 # Use secure desktop EnableInstallerDetection = 1 # Detect installers ValidateAdminCodeSignatures = 0 # Allow unsigned executables EnableSecureUIAPaths = 0 # Allow broader UIAccess (dev tools) } Description = "Developer-friendly UAC configuration with reduced prompts" UseCases = @("Developer workstations", "Test environments", "Software development") } "Legacy_Compatibility" = @{ Name = "Legacy Compatibility (Minimal Security)" Settings = @{ EnableLUA = 1 ConsentPromptBehaviorAdmin = 5 # Prompt for non-Windows binaries only ConsentPromptBehaviorUser = 3 # Prompt for credentials PromptOnSecureDesktop = 0 # No secure desktop (compatibility) EnableInstallerDetection = 0 # Disable installer detection ValidateAdminCodeSignatures = 0 # Allow unsigned executables EnableSecureUIAPaths = 0 # Allow UIAccess applications } Description = "Minimal UAC configuration for legacy application compatibility" UseCases = @("Legacy applications", "Older systems", "Compatibility testing") Warning = "⚠️ Reduced security - use only when absolutely necessary" } } return $templates } function Deploy-UACTemplate { param( $TemplateName, $GPOName, $TargetOU ) $templates = New-UACConfigurationTemplates if (-not $templates.ContainsKey($TemplateName)) { Write-Error "Template '$TemplateName' not found. Available templates: $($templates.Keys -join ', ')" return } $template = $templates try { Write-Output "Deploying UAC template: $($template.Name)" Write-Output "Description: $($template.Description)" if ($template.Warning) { Write-Warning $template.Warning } # Create or update GPO $gpo = Get-GPO -Name $GPOName -ErrorAction SilentlyContinue if (-not $gpo) { $gpo = New-GPO -Name $GPOName -Comment "UAC Configuration: $($template.Name)" } # Apply template settings $registryPath = "HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System" foreach ($setting in $template.Settings.Keys) { Set-GPRegistryValue -Name $GPOName -Key $registryPath -ValueName $setting -Value $template.Settings -Type DWord } # Link to target OU if ($TargetOU) { New-GPLink -Name $GPOName -Target $TargetOU -LinkEnabled Yes } Write-Output "✅ UAC template '$TemplateName' deployed successfully" Write-Output " GPO: $GPOName" Write-Output " Target: $TargetOU" return @{ Success = $true Template = $template GPOName = $GPOName TargetOU = $TargetOU } } catch { Write-Error "❌ Failed to deploy UAC template: $($_.Exception.Message)" return @{ Success = $false Error = $_.Exception.Message } } } # Display available templates $templates = New-UACConfigurationTemplates Write-Output "=== AVAILABLE UAC CONFIGURATION TEMPLATES ===" foreach ($templateKey in $templates.Keys) { $template = $templates Write-Output "`nTemplate: $($template.Name)" Write-Output "Description: $($template.Description)" Write-Output "Use Cases: $($template.UseCases -join ', ')" if ($template.Warning) { Write-Output "Warning: $($template.Warning)" } }
Sonuç ve Öneriler
User Account Control (UAC) yapılandırmasının "Prompt for consent on the secure desktop" modunda çalışması, modern Windows güvenliğinin temel gereksinimlerinden biridir. Bu yapılandırma, malicious software'in sessizce yüksek yetkiler elde etmesini engeller ve privilege escalation saldırılarına karşı güçlü bir savunma oluşturur.
Kritik Uygulama Adımları:
- ✅ Admin Approval Mode'u etkinleştirin (EnableLUA = 1)
- ✅ Secure Desktop prompting yapılandırın (PromptOnSecureDesktop = 1)
- ✅ Administrator behavior'ı secure modda ayarlayın (ConsentPromptBehaviorAdmin = 2)
- ✅ Standard user behavior'ı credentials prompt yapın (ConsentPromptBehaviorUser = 3)
- ✅ GPO ile domain-wide deployment gerçekleştirin
- ✅ Monitoring ve bypass detection sistemini kurun
Hızlı Kontrol Listesi:
- ✅ EnableLUA = 1 (Admin Approval Mode aktif mi)?
- ✅ ConsentPromptBehaviorAdmin = 2 (Secure desktop consent mi)?
- ✅ ConsentPromptBehaviorUser = 3 (Credential prompt mi)?
- ✅ PromptOnSecureDesktop = 1 (Secure desktop aktif mi)?
- ✅ EnableInstallerDetection = 1 (Installer detection mi)?
- ✅ ValidateAdminCodeSignatures = 1 (Code signature validation mi)?
Güvenlik İyileştirmeleri:
- %99 malware privilege escalation engellemesi
- UI automation attack koruması
- DLL injection bypass önlemesi
- Focus stealing attack elimine etme
UAC Security Levels:
Level | Security | Usability | Recommendation |
---|---|---|---|
Never Notify | ❌ Critical Risk | ✅ High | Never use |
Default Windows | ⚠️ Medium Risk | ✅ High | Insufficient |
Always Notify (No Secure Desktop) | ⚠️ High Risk | ✅ Medium | Avoid |
Always Notify (Secure Desktop) | ✅ Low Risk | ✅ Medium | RECOMMENDED |
Modern Security Integration:
- Endpoint Detection and Response (EDR) entegrasyonu
- SIEM systems ile event correlation
- Behavioral analytics ile anomaly detection
- Zero Trust architecture alignment
User Experience Optimization:
- Progressive education approach ile user adoption
- Template-based deployment için flexible configuration
- Real-time monitoring ile immediate threat response
- Automated compliance checking ve remediation
Bu yapılandırmayı uygulayarak, minimal user impact ile maximum security benefit elde edebilir ve organizasyonunuzun privilege escalation saldırılarına karşı direncini önemli ölçüde artırabilirsiniz. UAC secure desktop, defense in depth stratejisinin kritik bir bileşenidir ve modern siber güvenlik mimarisinin vazgeçilmez parçasıdır. "