A comprehensive Windows security auditing and threat detection toolkit. Features 58 production-ready PowerShell functions organized into 14 modules for enterprise-grade security assessment, compliance validation, and incident response.
PowerShell
v1.6.0: Locale-invariant auditing — APIs/GUIDs/SIDs replace localized text parsing
Okan YILDIZ1a2aa9943444
diff --git a/Analysis/Get-RegistryAnalysis.ps1 b/Analysis/Get-RegistryAnalysis.ps1index 8729279..7088287 100644--- a/Analysis/Get-RegistryAnalysis.ps1+++ b/Analysis/Get-RegistryAnalysis.ps1@@ -274,8 +274,16 @@ function Get-RegistryAnalysis {$acl = Get-Acl -Path $keyPath -ErrorAction Stop# Check for overly permissive access+ $permissiveSids = @('S-1-1-0', 'S-1-5-32-545', 'S-1-5-11')foreach ($access in $acl.Access) {- if ($access.IdentityReference -match '(Everyone|Users|Authenticated Users)' -and+ $isPermissiveIdentity = $false+ foreach ($sid in $permissiveSids) {+ if (Test-IdentityReferenceIsSid -IdentityReference $access.IdentityReference -Sid $sid) {+ $isPermissiveIdentity = $true+ break+ }+ }+ if ($isPermissiveIdentity -and$access.RegistryRights -match '(FullControl|Write|Modify)') {$results.PermissionIssues += [PSCustomObject]@{diff --git a/CHANGELOG.md b/CHANGELOG.mdindex abc1065..ea7988f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+## [1.6.0] - 2026-10-26++### Added++- Locale-invariant Windows support: new internal helpers in `Private/` replace all localized console-output parsing with APIs, GUIDs and SIDs, so the module produces correct results on non-English Windows (Turkish, German, French, ...):+ - `Get-AuditPolicyTable`: advanced audit policy via `AuditQuerySystemPolicy` P/Invoke (GUID-keyed, privilege-failure aware), falling back to `auditpol /backup` fixed-header CSV parsing (numeric Setting Value, German-fixture tested) and GUID-addressed `auditpol /get` with honest "unknown" instead of guessing from localized text. Includes the full 59-subcategory GUID map (MS-GPAC).+ - `Get-LocalPasswordPolicy`: password/lockout policy via `NetUserModalsGet` (levels 0+3, non-admin, locale-invariant) with an elevated `secedit /export` fallback that also covers `PasswordComplexity`/`ClearTextPassword`.+ - `Get-WlanProfileList`: WLAN profiles via `wlanapi.dll` P/Invoke instead of localized `netsh wlan show profiles` output; missing WLAN service/feature is "not applicable", not an error.+ - Identity helpers: `Get-AdminGroupMembers` (SID-first with ADSI fallback, 32-bit-PowerShell and unresolvable-SID safe), `Get-LocalUserByRid` (RID 500/501 instead of localized names), `Test-IdentityReferenceIsSid`, `Get-WellKnownSid`.+- Locale regression test suite (`tests/Locale.Regression.Tests.ps1`): English/German (ANSI cp1252) auditpol fixture equivalence tests and a static "no text readers" guard that fails the build if localized-output parsing (`auditpol /get`, `net accounts`, name-based group/user lookups, string identities in ACL rules) ever re-enters the codebase.++### Fixed++- Silent false PASS on non-English Windows across compliance checks: `Guest`/`Administrator` account checks (PCI 7.1.1, CIS 2.3.1.1/2.3.1.5, NIST AC-2) and `Administrators` group membership checks (Invoke-SecurityAssessment, Get-MultiSystemAudit, Invoke-EnterpriseSecurityScan) failed closed-by-accident (lookup exception swallowed → "0 admins"/"disabled" → pass). All now SID/RID-based and report an honest "unable to determine" state on lookup failure.+- Audit policy checks (PCI 10.2.1/10.3.1, NIST AU-2/AU-12, CIS 17.1.1/17.2.1/17.5.1) and password policy checks (PCI 8.2.3/8.2.4, NIST IA-2/IA-5) never matched on localized `auditpol`/`net accounts` output.+- `Enable-AuditPolicies`: `auditpol /set` now uses subcategory GUIDs (worked only on English Windows before); post-change verification no longer parses localized text; file/registry SACLs for "Everyone" use SID `S-1-1-0` (audit rules were silently never applied on non-English systems).+- ACL lockdowns of the scheduled-scan script (embeds the webhook secret) and of memory dumps (potentially credential-bearing) threw `IdentityNotMappedException` on non-English Windows and left the files world-readable — now SID-based (`S-1-5-18`, `S-1-5-32-544`) with post-`Set-Acl` verification for dump files.+- `Get-SecurityMisconfigurations` world-writable check and `Get-RegistryAnalysis` permissive-ACL check matched localized identity names ('Everyone'/'Users') and never fired on non-English systems — now SID-based.+- `Find-DefenseEvasion` Defender 5007 severity keyed off localized event message text — now uses the structured registry-path property.+- `Get-FileSystemJournal`: elevation/permission detection now uses `$LASTEXITCODE` instead of English error text; localized fsutil output produces an explicit warning instead of silently empty forensic evidence; timestamp parsing is invariant-culture only.+- `Test-SystemIntegrity`: SFC/DISM verdicts no longer rely on localized English sentences — exit codes plus locale-stable CBS.log `[SR]`/`Cannot repair` markers are primary.+- `Set-SecurityBaseline`: `net accounts`/`bcdedit` failures are now surfaced via `$LASTEXITCODE` warnings instead of silently passing.+- `Find-APTIndicators`: service matching uses the non-localized service `Name` only, not the SCM-localized `DisplayName`.+## [1.5.0] - 2026-10-25### Addeddiff --git a/Compliance/Test-CISBenchmark.ps1 b/Compliance/Test-CISBenchmark.ps1index 191e77d..0fe975f 100644--- a/Compliance/Test-CISBenchmark.ps1+++ b/Compliance/Test-CISBenchmark.ps1@@ -231,48 +231,71 @@ function Test-CISBenchmark {try {# CIS 17.1.1 - Audit Credential Validation- $auditResult = auditpol /get /subcategory:"Credential Validation" 2>$null- $auditStatus = if ($auditResult -match "Success and Failure") { "Success and Failure" } else { "Not Configured" }-+ $auditTable = Get-AuditPolicyTable -Subcategory 'Credential Validation', 'Application Group Management', 'Account Lockout'+ $credentialValidationGuid = Get-AuditSubcategoryGuid -Name 'Credential Validation'+ $credentialValidation = $null+ if ($null -ne $credentialValidationGuid) {+ $credentialValidationKey = ($credentialValidationGuid -replace '[{}]', '').ToLowerInvariant()+ $credentialValidation = $auditTable[$credentialValidationKey]+ }+$control = [PSCustomObject]@{ControlID = 'CIS-17.1.1'ControlName = 'Audit Credential Validation'Category = 'AuditPolicy'Expected = 'Success and Failure'- Actual = $auditStatus- Status = if ($auditStatus -eq "Success and Failure") { 'Pass' } else { 'Fail' }+ Actual = if ($null -eq $credentialValidation -or $null -eq $credentialValidation.Value) { 'Unable to determine' }+ elseif ($credentialValidation.Success -and $credentialValidation.Failure) { 'Success and Failure' }+ elseif ($credentialValidation.Success) { 'Success' }+ elseif ($credentialValidation.Failure) { 'Failure' } else { 'No Auditing' }+ Status = if ($null -eq $credentialValidation -or $null -eq $credentialValidation.Value) { 'Manual' }+ elseif ($credentialValidation.Value -eq 3) { 'Pass' } else { 'Fail' }Severity = 'High'Remediation = 'Configure to audit Success and Failure'}$results.Controls += $control-+# CIS 17.2.1 - Audit Application Group Management- $auditResult = auditpol /get /subcategory:"Application Group Management" 2>$null- $auditStatus = if ($auditResult -match "Success and Failure") { "Success and Failure" } else { "Not Configured" }-+ $appGroupGuid = Get-AuditSubcategoryGuid -Name 'Application Group Management'+ $appGroupManagement = $null+ if ($null -ne $appGroupGuid) {+ $appGroupKey = ($appGroupGuid -replace '[{}]', '').ToLowerInvariant()+ $appGroupManagement = $auditTable[$appGroupKey]+ }+$control = [PSCustomObject]@{ControlID = 'CIS-17.2.1'ControlName = 'Audit Application Group Management'Category = 'AuditPolicy'Expected = 'Success and Failure'- Actual = $auditStatus- Status = if ($auditStatus -eq "Success and Failure") { 'Pass' } else { 'Fail' }+ Actual = if ($null -eq $appGroupManagement -or $null -eq $appGroupManagement.Value) { 'Unable to determine' }+ elseif ($appGroupManagement.Success -and $appGroupManagement.Failure) { 'Success and Failure' }+ elseif ($appGroupManagement.Success) { 'Success' }+ elseif ($appGroupManagement.Failure) { 'Failure' } else { 'No Auditing' }+ Status = if ($null -eq $appGroupManagement -or $null -eq $appGroupManagement.Value) { 'Manual' }+ elseif ($appGroupManagement.Value -eq 3) { 'Pass' } else { 'Fail' }Severity = 'Medium'Remediation = 'Configure to audit Success and Failure'}$results.Controls += $control-+# CIS 17.5.1 - Audit Account Lockout- $auditResult = auditpol /get /subcategory:"Account Lockout" 2>$null- $auditStatus = if ($auditResult -match "Success|Failure") { "Configured" } else { "Not Configured" }-+ $accountLockoutGuid = Get-AuditSubcategoryGuid -Name 'Account Lockout'+ $accountLockout = $null+ if ($null -ne $accountLockoutGuid) {+ $accountLockoutKey = ($accountLockoutGuid -replace '[{}]', '').ToLowerInvariant()+ $accountLockout = $auditTable[$accountLockoutKey]+ }+$control = [PSCustomObject]@{ControlID = 'CIS-17.5.1'ControlName = 'Audit Account Lockout'Category = 'AuditPolicy'Expected = 'Success'- Actual = $auditStatus- Status = if ($auditStatus -eq "Configured") { 'Pass' } else { 'Fail' }+ Actual = if ($null -eq $accountLockout -or $null -eq $accountLockout.Value) { 'Unable to determine' }+ elseif ($accountLockout.Value -ge 1 -and $accountLockout.Value -le 3) { 'Configured' } else { 'Not Configured' }+ Status = if ($null -eq $accountLockout -or $null -eq $accountLockout.Value) { 'Manual' }+ elseif ($accountLockout.Value -ge 1 -and $accountLockout.Value -le 3) { 'Pass' } else { 'Fail' }Severity = 'Medium'Remediation = 'Configure to audit Success'}@@ -289,30 +312,34 @@ function Test-CISBenchmark {try {# CIS 2.3.1.1 - Accounts: Administrator account status- $adminUser = Get-LocalUser -Name "Administrator" -ErrorAction SilentlyContinue- $adminDisabled = if ($adminUser) { $adminUser.Enabled } else { $false }+ $adminUser = Get-LocalUserByRid -Rid 500 -ErrorAction SilentlyContinue+ $adminKnown = ($null -ne $adminUser) -and ($null -ne $adminUser.Enabled)$control = [PSCustomObject]@{ControlID = 'CIS-2.3.1.1'ControlName = 'Accounts: Administrator account status'Category = 'SecurityOptions'Expected = 'Disabled'- Actual = if ($adminDisabled -eq $false) { 'Disabled' } else { 'Enabled' }- Status = if ($adminDisabled -eq $false) { 'Pass' } else { 'Fail' }+ Actual = if (-not $adminKnown) { 'Unable to determine' }+ elseif ($adminUser.Enabled) { 'Enabled' } else { 'Disabled' }+ Status = if (-not $adminKnown) { 'Manual' }+ elseif ($adminUser.Enabled) { 'Fail' } else { 'Pass' }Severity = 'High'Remediation = 'Disable the built-in Administrator account'}$results.Controls += $control-+# CIS 2.3.1.5 - Accounts: Guest account status- $guestUser = Get-LocalUser -Name "Guest" -ErrorAction SilentlyContinue- $guestDisabled = if ($guestUser) { $guestUser.Enabled } else { $false }+ $guestUser = Get-LocalUserByRid -Rid 501 -ErrorAction SilentlyContinue+ $guestKnown = ($null -ne $guestUser) -and ($null -ne $guestUser.Enabled)$control = [PSCustomObject]@{ControlID = 'CIS-2.3.1.5'ControlName = 'Accounts: Guest account status'Category = 'SecurityOptions'Expected = 'Disabled'- Actual = if ($guestDisabled -eq $false) { 'Disabled' } else { 'Enabled' }- Status = if ($guestDisabled -eq $false) { 'Pass' } else { 'Fail' }+ Actual = if (-not $guestKnown) { 'Unable to determine' }+ elseif ($guestUser.Enabled) { 'Enabled' } else { 'Disabled' }+ Status = if (-not $guestKnown) { 'Manual' }+ elseif ($guestUser.Enabled) { 'Fail' } else { 'Pass' }Severity = 'High'Remediation = 'Disable the Guest account'}diff --git a/Compliance/Test-NISTCompliance.ps1 b/Compliance/Test-NISTCompliance.ps1index 76a471a..50ed949 100644--- a/Compliance/Test-NISTCompliance.ps1+++ b/Compliance/Test-NISTCompliance.ps1@@ -95,19 +95,22 @@ function Test-NISTCompliance {try {# AC-2: Account Management- $guestUser = Get-LocalUser -Name "Guest" -ErrorAction SilentlyContinue- $guestDisabled = ($null -eq $guestUser) -or ($guestUser.Enabled -eq $false)- $adminUser = Get-LocalUser -Name "Administrator" -ErrorAction SilentlyContinue- $adminDisabled = ($null -eq $adminUser) -or ($adminUser.Enabled -eq $false)-+ $guestUser = Get-LocalUserByRid -Rid 501 -ErrorAction SilentlyContinue+ $guestKnown = ($null -ne $guestUser) -and ($null -ne $guestUser.Enabled)+ $guestDisabled = $guestKnown -and ($guestUser.Enabled -eq $false)+ $adminUser = Get-LocalUserByRid -Rid 500 -ErrorAction SilentlyContinue+ $adminKnown = ($null -ne $adminUser) -and ($null -ne $adminUser.Enabled)+ $adminDisabled = $adminKnown -and ($adminUser.Enabled -eq $false)+$control = [PSCustomObject]@{ControlID = 'AC-2'ControlName = 'Account Management'ControlFamily = 'AccessControl'Description = 'Guest and default Administrator accounts should be disabled'Expected = 'Guest and Administrator accounts disabled'- Actual = "Guest: $(if($guestDisabled){'Disabled'}else{'Enabled'}), Admin: $(if($adminDisabled){'Disabled'}else{'Enabled'})"- Status = if ($guestDisabled -and $adminDisabled) { 'Compliant' }+ Actual = "Guest: $(if(-not $guestKnown){'Unknown'}elseif($guestDisabled){'Disabled'}else{'Enabled'}), Admin: $(if(-not $adminKnown){'Unknown'}elseif($adminDisabled){'Disabled'}else{'Enabled'})"+ Status = if (-not $guestKnown -or -not $adminKnown) { 'NotApplicable' }+ elseif ($guestDisabled -and $adminDisabled) { 'Compliant' }elseif ($guestDisabled -or $adminDisabled) { 'PartiallyCompliant' }else { 'NonCompliant' }Impact = 'High'@@ -177,17 +180,24 @@ function Test-NISTCompliance {try {# AU-2: Audit Events- $auditLogons = auditpol /get /subcategory:"Logon" 2>$null- $auditConfigured = $auditLogons -match "Success and Failure|Success|Failure"-+ $logonGuid = Get-AuditSubcategoryGuid -Name 'Logon'+ $logonAuditValue = $null+ if ($null -ne $logonGuid) {+ $logonTable = Get-AuditPolicyTable -Subcategory 'Logon'+ $logonKey = ($logonGuid -replace '[{}]', '').ToLowerInvariant()+ if ($logonTable.ContainsKey($logonKey)) { $logonAuditValue = $logonTable[$logonKey].Value }+ }+$control = [PSCustomObject]@{ControlID = 'AU-2'ControlName = 'Audit Events'ControlFamily = 'AuditAccountability'Description = 'System must audit significant security events'Expected = 'Audit policies configured'- Actual = if ($auditConfigured) { "Configured" } else { "Not configured" }- Status = if ($auditConfigured) { 'Compliant' } else { 'NonCompliant' }+ Actual = if ($null -eq $logonAuditValue) { 'Unable to determine' }+ elseif ($logonAuditValue -ge 1 -and $logonAuditValue -le 3) { "Configured" } else { "Not configured" }+ Status = if ($null -eq $logonAuditValue) { 'NotApplicable' }+ elseif ($logonAuditValue -ge 1 -and $logonAuditValue -le 3) { 'Compliant' } else { 'NonCompliant' }Impact = 'High'Remediation = 'Enable audit policies for security events'}@@ -216,7 +226,7 @@ function Test-NISTCompliance {$acl = Get-Acl $logPath -ErrorAction SilentlyContinue$protected = @()if ($acl) {- $protected = @($acl.Access | Where-Object { $_.IdentityReference -match "Users" -and $_.FileSystemRights -match "FullControl|Modify|Write" })+ $protected = @($acl.Access | Where-Object { (Test-IdentityReferenceIsSid -IdentityReference $_.IdentityReference -Sid 'S-1-5-32-545') -and $_.FileSystemRights -match "FullControl|Modify|Write" })}$control = [PSCustomObject]@{@@ -234,17 +244,24 @@ function Test-NISTCompliance {}# AU-12: Audit Generation- $auditProcessCreation = auditpol /get /subcategory:"Process Creation" 2>$null- $processAuditConfigured = $auditProcessCreation -match "Success"-+ $processCreationGuid = Get-AuditSubcategoryGuid -Name 'Process Creation'+ $processAuditEntry = $null+ if ($null -ne $processCreationGuid) {+ $processTable = Get-AuditPolicyTable -Subcategory 'Process Creation'+ $processKey = ($processCreationGuid -replace '[{}]', '').ToLowerInvariant()+ if ($processTable.ContainsKey($processKey)) { $processAuditEntry = $processTable[$processKey] }+ }+$control = [PSCustomObject]@{ControlID = 'AU-12'ControlName = 'Audit Generation'ControlFamily = 'AuditAccountability'Description = 'System must generate audit records for defined events'Expected = 'Process creation auditing enabled'- Actual = if ($processAuditConfigured) { "Enabled" } else { "Disabled" }- Status = if ($processAuditConfigured) { 'Compliant' } else { 'NonCompliant' }+ Actual = if ($null -eq $processAuditEntry -or $null -eq $processAuditEntry.Value) { 'Unable to determine' }+ elseif ($processAuditEntry.Success) { "Enabled" } else { "Disabled" }+ Status = if ($null -eq $processAuditEntry -or $null -eq $processAuditEntry.Value) { 'NotApplicable' }+ elseif ($processAuditEntry.Success) { 'Compliant' } else { 'NonCompliant' }Impact = 'Medium'Remediation = 'Enable process creation auditing'}@@ -261,48 +278,42 @@ function Test-NISTCompliance {try {# IA-2: Identification and Authentication- $passwordPolicy = net accounts 2>$null- $minPasswordLengthLine = $passwordPolicy | Select-String "Minimum password length" | Select-Object -First 1-- if ($minPasswordLengthLine) {- $minPasswordLength = $minPasswordLengthLine.ToString().Split(':')[1].Trim()+ $passwordPolicy = Get-LocalPasswordPolicy+ $minPasswordLength = $passwordPolicy.MinPasswordLength- $control = [PSCustomObject]@{- ControlID = 'IA-2'- ControlName = 'Identification and Authentication'- ControlFamily = 'IdentificationAuthentication'- Description = 'System must uniquely identify and authenticate users'- Expected = 'Minimum password length >= 14 characters'- Actual = "$minPasswordLength characters"- Status = if ([int]$minPasswordLength -ge 14) { 'Compliant' } else { 'NonCompliant' }- Impact = 'High'- Remediation = 'Set minimum password length to 14 characters'- }- $results.Controls += $control+ $control = [PSCustomObject]@{+ ControlID = 'IA-2'+ ControlName = 'Identification and Authentication'+ ControlFamily = 'IdentificationAuthentication'+ Description = 'System must uniquely identify and authenticate users'+ Expected = 'Minimum password length >= 14 characters'+ Actual = if ($null -eq $minPasswordLength) { 'Unable to determine' }+ else { "$minPasswordLength characters" }+ Status = if ($null -eq $minPasswordLength) { 'NotApplicable' }+ elseif ($minPasswordLength -ge 14) { 'Compliant' } else { 'NonCompliant' }+ Impact = 'High'+ Remediation = 'Set minimum password length to 14 characters'}+ $results.Controls += $control# IA-5: Authenticator Management- $maxPasswordAgeLine = $passwordPolicy | Select-String "Maximum password age" | Select-Object -First 1-- if ($maxPasswordAgeLine) {- $maxPasswordAge = $maxPasswordAgeLine.ToString().Split(':')[1].Trim().Split(' ')[0]- $maxAgeDays = 0- $maxAgeIsNumeric = [int]::TryParse($maxPasswordAge, [ref]$maxAgeDays)+ $maxAgeDays = $passwordPolicy.MaxPasswordAgeDays- $control = [PSCustomObject]@{- ControlID = 'IA-5'- ControlName = 'Authenticator Management'- ControlFamily = 'IdentificationAuthentication'- Description = 'Authenticators must be managed securely'- Expected = 'Maximum password age <= 60 days'- Actual = "$maxPasswordAge days"- Status = if ($maxAgeIsNumeric -and $maxAgeDays -le 60 -and $maxAgeDays -gt 0) { 'Compliant' } else { 'NonCompliant' }- Impact = 'High'- Remediation = 'Set maximum password age to 60 days or less'- }- $results.Controls += $control+ $control = [PSCustomObject]@{+ ControlID = 'IA-5'+ ControlName = 'Authenticator Management'+ ControlFamily = 'IdentificationAuthentication'+ Description = 'Authenticators must be managed securely'+ Expected = 'Maximum password age <= 60 days'+ Actual = if ($null -eq $maxAgeDays) { 'Unable to determine' }+ elseif ($maxAgeDays -eq -1) { 'Never expires' } else { "$maxAgeDays days" }+ Status = if ($null -eq $maxAgeDays) { 'NotApplicable' }+ elseif ($maxAgeDays -gt 0 -and $maxAgeDays -le 60) { 'Compliant' } else { 'NonCompliant' }+ Impact = 'High'+ Remediation = 'Set maximum password age to 60 days or less'}-+ $results.Controls += $control+# IA-8: Identification and Authentication (Non-Organizational Users)$regTest = Test-RegistryValue -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' `-Name 'LimitBlankPasswordUse' -ExpectedValue 1diff --git a/Compliance/Test-PCI-DSS.ps1 b/Compliance/Test-PCI-DSS.ps1index dd6a77a..662e0b6 100644--- a/Compliance/Test-PCI-DSS.ps1+++ b/Compliance/Test-PCI-DSS.ps1@@ -208,64 +208,61 @@ function Test-PCI-DSS {try {# Req 7.1: Limit access to system components- $guestUser = Get-LocalUser -Name "Guest" -ErrorAction SilentlyContinue- $guestDisabled = ($null -eq $guestUser) -or ($guestUser.Enabled -eq $false)-+ $guestUser = Get-LocalUserByRid -Rid 501 -ErrorAction SilentlyContinue+ $guestKnown = ($null -ne $guestUser) -and ($null -ne $guestUser.Enabled)+ $guestDisabled = $guestKnown -and ($guestUser.Enabled -eq $false)+$req = [PSCustomObject]@{RequirementID = '7.1.1'RequirementName = 'Access Limitations'Category = 'AccessControl'Description = 'Unnecessary accounts must be disabled'Expected = 'Guest account disabled'- Actual = if ($guestDisabled) { "Disabled" } else { "Enabled" }- Status = if ($guestDisabled) { 'InPlace' } else { 'NotInPlace' }+ Actual = if (-not $guestKnown) { 'Unable to determine (insufficient privileges or unsupported platform)' }+ elseif ($guestDisabled) { "Disabled" } else { "Enabled" }+ Status = if (-not $guestKnown) { 'NotApplicable' }+ elseif ($guestDisabled) { 'InPlace' } else { 'NotInPlace' }Priority = 'High'Remediation = 'Disable Guest and other unnecessary accounts'}$results.Requirements += $req# Req 8.2: User identification and authentication- $passwordPolicy = net accounts 2>$null- $minPasswordLengthLine = $passwordPolicy | Select-String "Minimum password length" | Select-Object -First 1-- if ($minPasswordLengthLine) {- $minPasswordLength = $minPasswordLengthLine.ToString().Split(':')[1].Trim()+ $passwordPolicy = Get-LocalPasswordPolicy+ $minPasswordLength = $passwordPolicy.MinPasswordLength- $req = [PSCustomObject]@{- RequirementID = '8.2.3'- RequirementName = 'Password Complexity'- Category = 'AccessControl'- Description = 'Passwords must meet minimum complexity'- Expected = 'Minimum 12 characters (or 8 if MFA)'- Actual = "$minPasswordLength characters"- Status = if ([int]$minPasswordLength -ge 12) { 'InPlace' } else { 'NotInPlace' }- Priority = 'Critical'- Remediation = 'Set minimum password length to 12 characters'- }- $results.Requirements += $req+ $req = [PSCustomObject]@{+ RequirementID = '8.2.3'+ RequirementName = 'Password Complexity'+ Category = 'AccessControl'+ Description = 'Passwords must meet minimum complexity'+ Expected = 'Minimum 12 characters (or 8 if MFA)'+ Actual = if ($null -eq $minPasswordLength) { 'Unable to determine (insufficient privileges or unsupported platform)' }+ else { "$minPasswordLength characters" }+ Status = if ($null -eq $minPasswordLength) { 'NotApplicable' }+ elseif ($minPasswordLength -ge 12) { 'InPlace' } else { 'NotInPlace' }+ Priority = 'Critical'+ Remediation = 'Set minimum password length to 12 characters'}+ $results.Requirements += $req# Req 8.2.4: Change passwords every 90 days- $maxPasswordAgeLine = $passwordPolicy | Select-String "Maximum password age" | Select-Object -First 1-- if ($maxPasswordAgeLine) {- $maxPasswordAge = $maxPasswordAgeLine.ToString().Split(':')[1].Trim().Split(' ')[0]- $maxAgeDays = 0- $maxAgeIsNumeric = [int]::TryParse($maxPasswordAge, [ref]$maxAgeDays)+ $maxAgeDays = $passwordPolicy.MaxPasswordAgeDays- $req = [PSCustomObject]@{- RequirementID = '8.2.4'- RequirementName = 'Password Change Frequency'- Category = 'AccessControl'- Description = 'Passwords must be changed periodically'- Expected = '90 days or less'- Actual = "$maxPasswordAge days"- Status = if ($maxAgeIsNumeric -and $maxAgeDays -le 90 -and $maxAgeDays -gt 0) { 'InPlace' } else { 'NotInPlace' }- Priority = 'High'- Remediation = 'Set maximum password age to 90 days'- }- $results.Requirements += $req+ $req = [PSCustomObject]@{+ RequirementID = '8.2.4'+ RequirementName = 'Password Change Frequency'+ Category = 'AccessControl'+ Description = 'Passwords must be changed periodically'+ Expected = '90 days or less'+ Actual = if ($null -eq $maxAgeDays) { 'Unable to determine (insufficient privileges or unsupported platform)' }+ elseif ($maxAgeDays -eq -1) { 'Never expires' } else { "$maxAgeDays days" }+ Status = if ($null -eq $maxAgeDays) { 'NotApplicable' }+ elseif ($maxAgeDays -gt 0 -and $maxAgeDays -le 90) { 'InPlace' } else { 'NotInPlace' }+ Priority = 'High'+ Remediation = 'Set maximum password age to 90 days'}+ $results.Requirements += $req# Req 8.3: Multi-factor authentication$req = [PSCustomObject]@{@@ -292,34 +289,48 @@ function Test-PCI-DSS {try {# Req 10.2: Audit logs for all users- $auditLogons = auditpol /get /subcategory:"Logon" 2>$null- $logonAuditEnabled = $auditLogons -match "Success and Failure"-+ $logonGuid = Get-AuditSubcategoryGuid -Name 'Logon'+ $logonAuditValue = $null+ if ($null -ne $logonGuid) {+ $logonTable = Get-AuditPolicyTable -Subcategory 'Logon'+ $logonKey = ($logonGuid -replace '[{}]', '').ToLowerInvariant()+ if ($logonTable.ContainsKey($logonKey)) { $logonAuditValue = $logonTable[$logonKey].Value }+ }+$req = [PSCustomObject]@{RequirementID = '10.2.1'RequirementName = 'User Access Logging'Category = 'Monitoring'Description = 'All access to system components must be logged'Expected = 'Logon auditing: Success and Failure'- Actual = if ($logonAuditEnabled) { "Enabled" } else { "Not configured" }- Status = if ($logonAuditEnabled) { 'InPlace' } else { 'NotInPlace' }+ Actual = if ($null -eq $logonAuditValue) { 'Unable to determine (insufficient privileges or unsupported platform)' }+ elseif ($logonAuditValue -eq 3) { "Enabled" } else { "Not configured" }+ Status = if ($null -eq $logonAuditValue) { 'NotApplicable' }+ elseif ($logonAuditValue -eq 3) { 'InPlace' } else { 'NotInPlace' }Priority = 'Critical'Remediation = 'Enable audit policy for Logon events'}$results.Requirements += $req-+# Req 10.3: Audit trail content- $auditObjectAccess = auditpol /get /subcategory:"File System" 2>$null- $objectAuditEnabled = $auditObjectAccess -match "Success|Failure"-+ $fileSystemGuid = Get-AuditSubcategoryGuid -Name 'File System'+ $objectAuditValue = $null+ if ($null -ne $fileSystemGuid) {+ $fileSystemTable = Get-AuditPolicyTable -Subcategory 'File System'+ $fileSystemKey = ($fileSystemGuid -replace '[{}]', '').ToLowerInvariant()+ if ($fileSystemTable.ContainsKey($fileSystemKey)) { $objectAuditValue = $fileSystemTable[$fileSystemKey].Value }+ }+$req = [PSCustomObject]@{RequirementID = '10.3.1'RequirementName = 'Audit Trail Details'Category = 'Monitoring'Description = 'Logs must contain sufficient detail'Expected = 'File system auditing enabled'- Actual = if ($objectAuditEnabled) { "Enabled" } else { "Not configured" }- Status = if ($objectAuditEnabled) { 'InPlace' } else { 'NotInPlace' }+ Actual = if ($null -eq $objectAuditValue) { 'Unable to determine (insufficient privileges or unsupported platform)' }+ elseif ($objectAuditValue -ge 1) { "Enabled" } else { "Not configured" }+ Status = if ($null -eq $objectAuditValue) { 'NotApplicable' }+ elseif ($objectAuditValue -ge 1 -and $objectAuditValue -le 3) { 'InPlace' } else { 'NotInPlace' }Priority = 'High'Remediation = 'Enable file system object access auditing'}diff --git a/Core/Test-SystemIntegrity.ps1 b/Core/Test-SystemIntegrity.ps1index f6f4db4..068007a 100644--- a/Core/Test-SystemIntegrity.ps1+++ b/Core/Test-SystemIntegrity.ps1@@ -49,27 +49,44 @@ function Test-SystemIntegrity {# Run SFC scanWrite-Host "Running System File Checker (SFC)..." -ForegroundColor Yellow$sfcOutput = & sfc /scannow 2>&1 | Out-String-- # Parse SFC results- if ($sfcOutput -match "Windows Resource Protection found corrupt files") {+ $sfcExitCode = $LASTEXITCODE++ # SFC output text is fully localized; the exit code and the CBS.log+ # '[SR]'/'Cannot repair' tokens (written in English by the SFC engine+ # regardless of UI language) are the locale-invariant sources+ $cbsLogPath = "$env:windir\Logs\CBS\CBS.log"+ $cbsLogAvailable = Test-Path $cbsLogPath+ $cannotRepairLines = @()+ if ($cbsLogAvailable) {+ $cannotRepairLines = @(Get-Content $cbsLogPath -Tail 500 -ErrorAction SilentlyContinue |+ Where-Object { $_ -match '\[SR\]' -and $_ -match 'Cannot repair' })+ }++ if ($sfcExitCode -ne 0) {+ $results.SFCResult = "SFC could not complete scan - may need to run in Safe Mode"+ Write-Warning "SFC could not complete the scan (exit code $sfcExitCode)"+ }+ elseif ($cannotRepairLines.Count -gt 0 -or+ (-not $cbsLogAvailable -and $sfcOutput -match "Windows Resource Protection found corrupt files")) {$results.SFCResult = "Corrupt files found"-- # Get CBS log details (with error handling)- $cbsLogPath = "$env:windir\Logs\CBS\CBS.log"- if (Test-Path $cbsLogPath) {- $cbsLog = Get-Content $cbsLogPath -Tail 100 -ErrorAction SilentlyContinue |++ if ($cannotRepairLines.Count -gt 0) {+ $results.CorruptedFiles = $cannotRepairLines+ }+ elseif ($cbsLogAvailable) {+ $cbsLog = Get-Content $cbsLogPath -Tail 100 -ErrorAction SilentlyContinue |Where-Object { $_ -match "corrupt" -or $_ -match "repaired" }if ($cbsLog) {$results.CorruptedFiles = $cbsLog}}-+if ($RepairFiles) {Write-Host "Attempting to repair corrupt files..." -ForegroundColor Yellow$results.RepairAttempted = $true}}- elseif ($sfcOutput -match "Windows Resource Protection did not find any integrity violations") {+ elseif ($cbsLogAvailable -or $sfcOutput -match "Windows Resource Protection did not find any integrity violations") {$results.SFCResult = "No integrity violations found"Write-Host "SFC: No integrity violations found" -ForegroundColor Green}@@ -84,30 +101,52 @@ function Test-SystemIntegrity {# Run DISM if detailed scan requestedif ($DetailedScan) {Write-Host "Running DISM health check..." -ForegroundColor Yellow-+# Check image health$dismCheck = & dism /Online /Cleanup-Image /CheckHealth 2>&1 | Out-String-- if ($dismCheck -match "No component store corruption detected") {- $results.DISMResult = "Healthy"- Write-Host "DISM: System image is healthy" -ForegroundColor Green+ $dismCheckExitCode = $LASTEXITCODE++ # DISM output text is fully localized and CheckHealth returns 0 for+ # both 'healthy' and 'repairable', so the exit code alone cannot+ # separate those; servicing-stack CBS.log markers ('[SR]'/'Cannot+ # repair', component-store corruption) are written in English+ $storeCorruptionLines = @()+ if ($cbsLogAvailable) {+ $storeCorruptionLines = @(Get-Content $cbsLogPath -Tail 500 -ErrorAction SilentlyContinue |+ Where-Object { $_ -match '(?i)component store' -and $_ -match '(?i)corrupt' })+ }++ $repairable = ($storeCorruptionLines.Count -gt 0) -or ($dismCheck -match "The component store is repairable")++ if ($dismCheckExitCode -ne 0) {+ $results.DISMResult = "DISM CheckHealth failed (exit code $dismCheckExitCode) - review CBS.log"+ Write-Warning "DISM CheckHealth failed with exit code $dismCheckExitCode"}- elseif ($dismCheck -match "The component store is repairable") {+ elseif ($repairable) {$results.DISMResult = "Repairable corruption detected"-+if ($RepairFiles) {Write-Host "Attempting DISM repair..." -ForegroundColor Yellow- $dismRepair = & dism /Online /Cleanup-Image /RestoreHealth 2>&1 | Out-String-- if ($dismRepair -match "The restore operation completed successfully") {+ $null = & dism /Online /Cleanup-Image /RestoreHealth 2>&1 | Out-String+ $dismRepairExitCode = $LASTEXITCODE++ if ($dismRepairExitCode -eq 0) {$results.RepairSuccessful = $true$results.DISMResult = "Repaired successfully"Write-Host "DISM repair completed successfully" -ForegroundColor Green}+ else {+ $results.DISMResult = "Repair failed (exit code $dismRepairExitCode) - review CBS.log"+ Write-Warning "DISM RestoreHealth failed with exit code $dismRepairExitCode"+ }}}+ elseif ($dismCheck -match "No component store corruption detected") {+ $results.DISMResult = "Healthy"+ Write-Host "DISM: System image is healthy" -ForegroundColor Green+ }else {- $results.DISMResult = "Check completed"+ $results.DISMResult = "Check completed - review CBS.log"}}diff --git a/Detection/Find-DefenseEvasion.ps1 b/Detection/Find-DefenseEvasion.ps1index 86a08e3..ec33231 100644--- a/Detection/Find-DefenseEvasion.ps1+++ b/Detection/Find-DefenseEvasion.ps1@@ -410,7 +410,17 @@ function Find-DefenseEvasion {elseif (5007 -eq $eventId) {$sev = 'Medium'$desc = 'Defender configuration changed'- if (-not [string]::IsNullOrEmpty($msg) -and $msg -match '(?i)exclusion') {+ $exclusionPath = $null+ if ($null -ne $evt.PSObject.Properties['Properties'] -and $null -ne $evt.Properties) {+ foreach ($prop in $evt.Properties) {+ if ($null -ne $prop -and $null -ne $prop.Value -and+ $prop.Value -is [string] -and $prop.Value -match '(?i)\\Exclusions\\') {+ $exclusionPath = $prop.Value+ break+ }+ }+ }+ if ($null -ne $exclusionPath) {$sev = 'High'$desc = 'Defender exclusion changed'}diff --git a/Enterprise/Get-MultiSystemAudit.ps1 b/Enterprise/Get-MultiSystemAudit.ps1index d139d4a..a974be9 100644--- a/Enterprise/Get-MultiSystemAudit.ps1+++ b/Enterprise/Get-MultiSystemAudit.ps1@@ -191,8 +191,18 @@ function Get-MultiSystemAudit {}# Admin accounts- $admins = @(Get-LocalGroupMember -Group "Administrators" -ErrorAction SilentlyContinue)- if ($admins.Count -le 2) {+ $admins = @()+ $adminLookupSucceeded = $false+ if (Get-Command Get-AdminGroupMembers -ErrorAction SilentlyContinue) {+ $admins = @(Get-AdminGroupMembers)+ $adminLookupSucceeded = ((Get-Variable -Name AdminGroupLookupSucceeded -Scope Script -ValueOnly -ErrorAction SilentlyContinue) -eq $true)+ }+ if (-not $adminLookupSucceeded) {+ $findings += [PSCustomObject]@{+ Severity = 'Low'+ Finding = 'Unable to determine administrator count'+ }+ } elseif ($admins.Count -le 2) {$score += 15} else {$findings += [PSCustomObject]@{@@ -267,8 +277,18 @@ function Get-MultiSystemAudit {}# Admin accounts- $admins = @(Get-LocalGroupMember -Group "Administrators" -ErrorAction SilentlyContinue)- if ($admins.Count -le 2) {+ $admins = @()+ $adminLookupSucceeded = $false+ if (Get-Command Get-AdminGroupMembers -ErrorAction SilentlyContinue) {+ $admins = @(Get-AdminGroupMembers)+ $adminLookupSucceeded = ((Get-Variable -Name AdminGroupLookupSucceeded -Scope Script -ValueOnly -ErrorAction SilentlyContinue) -eq $true)+ }+ if (-not $adminLookupSucceeded) {+ $findings += [PSCustomObject]@{+ Severity = 'Low'+ Finding = 'Unable to determine administrator count'+ }+ } elseif ($admins.Count -le 2) {$score += 15} else {$findings += [PSCustomObject]@{diff --git a/Enterprise/Invoke-EnterpriseSecurityScan.ps1 b/Enterprise/Invoke-EnterpriseSecurityScan.ps1index a0d3236..f712257 100644--- a/Enterprise/Invoke-EnterpriseSecurityScan.ps1+++ b/Enterprise/Invoke-EnterpriseSecurityScan.ps1@@ -329,15 +329,25 @@ function Invoke-EnterpriseSecurityScan {# Additional checks for Standard/Comprehensive scansif ($ScanType -in @('Standard', 'Comprehensive')) {# Check for admin accounts- $adminCount = @(Get-LocalGroupMember -Group "Administrators" -ErrorAction SilentlyContinue).Count- $result.Details.AdminAccounts = $adminCount+ $adminAccounts = @()+ $adminLookupSucceeded = $false+ if (Get-Command Get-AdminGroupMembers -ErrorAction SilentlyContinue) {+ $adminAccounts = @(Get-AdminGroupMembers)+ $adminLookupSucceeded = ((Get-Variable -Name AdminGroupLookupSucceeded -Scope Script -ValueOnly -ErrorAction SilentlyContinue) -eq $true)+ }+ if ($adminLookupSucceeded) {+ $adminCount = $adminAccounts.Count+ $result.Details.AdminAccounts = $adminCount- if ($adminCount -gt 3) {- $result.Findings += [PSCustomObject]@{- Severity = 'Medium'- Category = 'Accounts'- Finding = "$adminCount administrator accounts (excessive)"+ if ($adminCount -gt 3) {+ $result.Findings += [PSCustomObject]@{+ Severity = 'Medium'+ Category = 'Accounts'+ Finding = "$adminCount administrator accounts (excessive)"+ }}+ } else {+ $result.Details.AdminAccounts = 'Unknown'}# Check for suspicious servicesdiff --git a/Enterprise/Invoke-SecurityAssessment.ps1 b/Enterprise/Invoke-SecurityAssessment.ps1index 10ba55b..ba66f28 100644--- a/Enterprise/Invoke-SecurityAssessment.ps1+++ b/Enterprise/Invoke-SecurityAssessment.ps1@@ -378,12 +378,9 @@ function Invoke-SecurityAssessment {}}- # WiFi security (if applicable; netsh absent on non-Windows or Server Core - guard the lookup)- $wifiProfiles = $null- if (Get-Command netsh -ErrorAction SilentlyContinue) {- $wifiProfiles = netsh wlan show profiles | Select-String "All User Profile"- }- if ($wifiProfiles) {+ # WiFi security (if applicable)+ $wifiProfiles = @(Get-WlanProfileList)+ if ($wifiProfiles.Count -gt 0) {$networkSecurity.CategoryScore += 10$networkSecurity.Checks += [PSCustomObject]@{Check = 'WiFi Profiles'@@ -478,17 +475,25 @@ function Invoke-SecurityAssessment {}}- # Password policy (net.exe absent on non-Windows - guard the lookup)- $passwordPolicy = $null- if (Get-Command net -ErrorAction SilentlyContinue) {- $passwordPolicy = net accounts- }- $accountSecurity.CategoryScore += 20- $accountSecurity.Checks += [PSCustomObject]@{- Check = 'Password Policy'- Status = 'Info'- Score = 20- Details = 'Configured'+ # Password policy+ $passwordPolicy = Get-LocalPasswordPolicy+ if ($null -ne $passwordPolicy -and $passwordPolicy.Source -ne 'Unavailable') {+ $minLengthText = if ($null -eq $passwordPolicy.MinPasswordLength) { 'unknown' } else { "$($passwordPolicy.MinPasswordLength)" }+ $maxAgeText = if ($null -eq $passwordPolicy.MaxPasswordAgeDays) { 'unknown' } elseif ($passwordPolicy.MaxPasswordAgeDays -lt 0) { 'never' } else { "$($passwordPolicy.MaxPasswordAgeDays) days" }+ $accountSecurity.CategoryScore += 20+ $accountSecurity.Checks += [PSCustomObject]@{+ Check = 'Password Policy'+ Status = 'Info'+ Score = 20+ Details = "Min length: $minLengthText, Max age: $maxAgeText"+ }+ } else {+ $accountSecurity.Checks += [PSCustomObject]@{+ Check = 'Password Policy'+ Status = 'Warning'+ Score = 0+ Details = 'Unable to determine password policy'+ }}# Accounts without passwords@@ -518,8 +523,15 @@ function Invoke-SecurityAssessment {}# Administrator group members- $admins = @(Get-LocalGroupMember -Group "Administrators" -ErrorAction SilentlyContinue)- if ($admins.Count -le 2) {+ $admins = @(Get-AdminGroupMembers)+ if ($script:AdminGroupLookupSucceeded -ne $true) {+ $accountSecurity.Checks += [PSCustomObject]@{+ Check = 'Administrator Group Size'+ Status = 'Warning'+ Score = 0+ Details = 'Unable to enumerate administrators'+ }+ } elseif ($admins.Count -le 2) {$accountSecurity.CategoryScore += 20$accountSecurity.Checks += [PSCustomObject]@{Check = 'Administrator Group Size'@@ -728,12 +740,12 @@ try {}}- # Audit logging (auditpol absent on non-Windows - guard the lookup)- $auditPolicy = $null- if (Get-Command auditpol -ErrorAction SilentlyContinue) {- $auditPolicy = auditpol /get /category:* 2>&1- }- if ($auditPolicy -match 'Success') {+ # Audit logging+ $auditTable = Get-AuditPolicyTable+ $auditEntries = if ($null -ne $auditTable) { @($auditTable.Values) } else { @() }+ $auditedCount = @($auditEntries | Where-Object { $_.Success -or $_.Failure }).Count+ $knownCount = @($auditEntries | Where-Object { $null -ne $_.Value }).Count+ if ($auditedCount -gt 0) {$dataProtection.CategoryScore += 15$dataProtection.Checks += [PSCustomObject]@{Check = 'Audit Logging'@@ -741,6 +753,13 @@ try {Score = 15Details = 'Configured'}+ } elseif ($knownCount -eq 0) {+ $dataProtection.Checks += [PSCustomObject]@{+ Check = 'Audit Logging'+ Status = 'Warning'+ Score = 0+ Details = 'Unable to determine'+ }} else {$dataProtection.Checks += [PSCustomObject]@{Check = 'Audit Logging'diff --git a/Enterprise/Register-ScheduledSecurityScan.ps1 b/Enterprise/Register-ScheduledSecurityScan.ps1index 2afa10b..f394d27 100644--- a/Enterprise/Register-ScheduledSecurityScan.ps1+++ b/Enterprise/Register-ScheduledSecurityScan.ps1@@ -684,7 +684,11 @@ exit 0foreach ($existingRule in @($scriptAcl.Access)) {$null = $scriptAcl.RemoveAccessRule($existingRule)}- foreach ($identity in @('NT AUTHORITY\SYSTEM', 'BUILTIN\Administrators')) {+ $aclIdentities = @(+ (New-Object System.Security.Principal.SecurityIdentifier('S-1-5-18')),+ (New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544'))+ )+ foreach ($identity in $aclIdentities) {$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($identity,[System.Security.AccessControl.FileSystemRights]::FullControl,diff --git a/Forensics/Export-MemoryDump.ps1 b/Forensics/Export-MemoryDump.ps1index b9212ff..01b9018 100644--- a/Forensics/Export-MemoryDump.ps1+++ b/Forensics/Export-MemoryDump.ps1@@ -84,16 +84,17 @@ function Export-MemoryDump {# in Register-ScheduledSecurityScan)function Protect-DumpFile {param([Parameter(Mandatory = $true)][string]$Path)- if ($env:OS -ne 'Windows_NT') { return }+ if ($env:OS -ne 'Windows_NT') { return $true }+ $requiredSids = @('S-1-5-18', 'S-1-5-32-544')try {$fileAcl = Get-Acl -Path $Path -ErrorAction Stop$fileAcl.SetAccessRuleProtection($true, $false)foreach ($existingRule in @($fileAcl.Access)) {$null = $fileAcl.RemoveAccessRule($existingRule)}- foreach ($identity in @('NT AUTHORITY\SYSTEM', 'BUILTIN\Administrators')) {+ foreach ($sidString in $requiredSids) {$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule(- $identity,+ (New-Object System.Security.Principal.SecurityIdentifier($sidString)),[System.Security.AccessControl.FileSystemRights]::FullControl,[System.Security.AccessControl.AccessControlType]::Allow)$fileAcl.AddAccessRule($accessRule)@@ -102,7 +103,23 @@ function Export-MemoryDump {}catch {Write-Warning "Could not restrict permissions on '$Path'; the dump may contain credentials and may be readable by other local users: $_"+ return $false}++ $appliedAcl = Get-Acl -Path $Path -ErrorAction SilentlyContinue+ if ($null -eq $appliedAcl) {+ Write-Warning "ACL verification FAILED on '$Path': could not re-read the ACL; the dump may contain credentials and may be readable by other local users."+ return $false+ }+ $missingSids = @($requiredSids | Where-Object {+ $sid = $_+ -not @($appliedAcl.Access | Where-Object { Test-IdentityReferenceIsSid -IdentityReference $_.IdentityReference -Sid $sid }).Count+ })+ if ($missingSids.Count -gt 0) {+ Write-Warning "ACL verification FAILED on '$Path': missing access rules for SID(s) $($missingSids -join ', '); the dump may contain credentials and may be readable by other local users."+ return $false+ }+ return $true}}@@ -365,7 +382,7 @@ public class ProcessDump {if ($result.Success -and (Test-Path $dumpFilePath)) {$dumpFile = Get-Item $dumpFilePath$result.FileSize = $dumpFile.Length- Protect-DumpFile -Path $dumpFilePath+ $null = Protect-DumpFile -Path $dumpFilePath$fileSizeMB = [Math]::Round($dumpFile.Length / 1MB, 2)Write-Host "`n[SUCCESS] Memory dump created!" -ForegroundColor Green@@ -382,7 +399,7 @@ public class ProcessDump {Compress-Archive -Path $dumpFilePath -DestinationPath $zipPath -CompressionLevel Optimalif (Test-Path $zipPath) {- Protect-DumpFile -Path $zipPath+ $null = Protect-DumpFile -Path $zipPath$zipFile = Get-Item $zipPath$zipSizeMB = [Math]::Round($zipFile.Length / 1MB, 2)$compressionRatio = [Math]::Round((1 - ($zipFile.Length / $dumpFile.Length)) * 100, 1)diff --git a/Forensics/Get-FileSystemJournal.ps1 b/Forensics/Get-FileSystemJournal.ps1index b213174..d7c0375 100644--- a/Forensics/Get-FileSystemJournal.ps1+++ b/Forensics/Get-FileSystemJournal.ps1@@ -113,11 +113,17 @@ function Get-FileSystemJournal {try {$rawLines = @(Get-FsutilOutput -Arguments @('usn', 'readjournal', "$drive`:"))+ $fsutilExitCode = $script:FsutilLastExitCode- $denied = @($rawLines | Where-Object { $_ -match '(?i)administrative privileges|access is denied|requires elevation' })- if ($denied.Count -gt 0) {- Write-Warning "fsutil denied access to the USN journal. Rerun from an elevated prompt."- $result.Notes += "USN journal read failed: fsutil requires administrative privileges."+ if ($fsutilExitCode -ne 0) {+ if ($fsutilExitCode -eq 5) {+ Write-Warning "fsutil denied access to the USN journal (exit code 5). Rerun from an elevated prompt."+ $result.Notes += "USN journal read failed: fsutil requires administrative privileges."+ }+ else {+ Write-Warning "fsutil usn readjournal failed with exit code $fsutilExitCode."+ $result.Notes += "USN journal read failed: fsutil exited with code $fsutilExitCode."+ }}else {$journalRecords = @(ConvertFrom-UsnJournalOutput -Lines $rawLines -MaxRecords $MaxRecords)@@ -223,11 +229,17 @@ function Get-FileSystemJournal {try {$ntfsLines = @(Get-FsutilOutput -Arguments @('fsinfo', 'ntfsinfo', "$drive`:"))+ $fsutilExitCode = $script:FsutilLastExitCode- $denied = @($ntfsLines | Where-Object { $_ -match '(?i)administrative privileges|access is denied|requires elevation' })- if ($denied.Count -gt 0) {- Write-Warning "fsutil denied access to volume metadata. Rerun from an elevated prompt."- $result.Notes += "MFT summary collection failed: fsutil requires administrative privileges."+ if ($fsutilExitCode -ne 0) {+ if ($fsutilExitCode -eq 5) {+ Write-Warning "fsutil denied access to volume metadata (exit code 5). Rerun from an elevated prompt."+ $result.Notes += "MFT summary collection failed: fsutil requires administrative privileges."+ }+ else {+ Write-Warning "fsutil fsinfo ntfsinfo failed with exit code $fsutilExitCode."+ $result.Notes += "MFT summary collection failed: fsutil exited with code $fsutilExitCode."+ }}else {$volumeInfo = @{}@@ -242,6 +254,14 @@ function Get-FileSystemJournal {}$mftValidBytes = $null+ if ($volumeInfo.Count -gt 0) {+ $expectedFields = @('Mft Valid Data Length', 'Bytes Per FileRecord Segment', 'Mft Start Lcn', 'Mft2 Start Lcn', 'Mft Zone Start', 'Mft Zone End')+ $matchedFields = @($expectedFields | Where-Object { $volumeInfo.ContainsKey($_) })+ if ($matchedFields.Count -eq 0) {+ Write-Warning "fsutil ntfsinfo returned data but none of the expected volume fields were recognized; localized fsutil output cannot be mapped (English locale required). MFT summary values will be null."+ $result.Notes += "MFT summary values unavailable: localized fsutil ntfsinfo output cannot be parsed; English locale is required."+ }+ }if ($volumeInfo.ContainsKey('Mft Valid Data Length')) {$mftValidBytes = ConvertFrom-JournalNumericText -Text $volumeInfo['Mft Valid Data Length']}@@ -300,10 +320,16 @@ function Get-FileSystemJournal {try {Write-Host " Reading USN journal for creation-record comparison..." -ForegroundColor Gray$rawLines = @(Get-FsutilOutput -Arguments @('usn', 'readjournal', "$drive`:"))- $denied = @($rawLines | Where-Object { $_ -match '(?i)administrative privileges|access is denied|requires elevation' })- if ($denied.Count -gt 0) {- Write-Warning "fsutil denied access to the USN journal; journal comparison will be skipped."- $result.Notes += "USN journal comparison skipped: fsutil requires administrative privileges."+ $fsutilExitCode = $script:FsutilLastExitCode+ if ($fsutilExitCode -ne 0) {+ if ($fsutilExitCode -eq 5) {+ Write-Warning "fsutil denied access to the USN journal (exit code 5); journal comparison will be skipped."+ $result.Notes += "USN journal comparison skipped: fsutil requires administrative privileges."+ }+ else {+ Write-Warning "fsutil usn readjournal failed with exit code $fsutilExitCode; journal comparison will be skipped."+ $result.Notes += "USN journal comparison skipped: fsutil exited with code $fsutilExitCode."+ }}else {$creationRecords = @(ConvertFrom-UsnJournalOutput -Lines $rawLines -MaxRecords $MaxRecords |@@ -487,6 +513,7 @@ function Get-FsutilOutput {)$output = @(& fsutil @Arguments 2>&1)+ $script:FsutilLastExitCode = $LASTEXITCODEreturn @($output | ForEach-Object { "$_" })}@@ -566,6 +593,13 @@ function ConvertFrom-UsnJournalOutput {$records += (New-UsnJournalRecord -Fields $current)}+ if ($records.Count -eq 0) {+ $contentLines = @($Lines | Where-Object { $null -ne $_ -and $_ -notmatch '^\s*$' })+ if ($contentLines.Count -gt 0) {+ Write-Warning "fsutil returned USN journal output but no records could be parsed; localized fsutil output is not supported (English locale required for USN journal parsing)."+ }+ }+return @($records)}@@ -607,11 +641,8 @@ function New-UsnJournalRecord {if ([datetime]::TryParse($timeStampText, [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref]$parsedDate)) {$timeStamp = $parsedDate}- elseif ([datetime]::TryParse($timeStampText, [ref]$parsedDate)) {- $timeStamp = $parsedDate- }else {- Write-Verbose "Could not parse journal time stamp: $timeStampText"+ Write-Verbose "Could not parse journal time stamp '$timeStampText' with the invariant culture; localized fsutil timestamps require an English locale. TimeStamp is set to null."}}diff --git a/Hardening/Enable-AuditPolicies.ps1 b/Hardening/Enable-AuditPolicies.ps1index f09bbdd..ee072f4 100644--- a/Hardening/Enable-AuditPolicies.ps1+++ b/Hardening/Enable-AuditPolicies.ps1@@ -81,7 +81,7 @@ function Enable-AuditPolicies {Comprehensive = @{'Account Logon' = @('Credential Validation', 'Kerberos Authentication Service', 'Kerberos Service Ticket Operations')'Account Management' = @('User Account Management', 'Security Group Management', 'Computer Account Management', 'Distribution Group Management', 'Application Group Management')- 'Detailed Tracking' = @('Process Creation', 'Process Termination', 'DPAPI Activity', 'RPC Events', 'PNP Activity')+ 'Detailed Tracking' = @('Process Creation', 'Process Termination', 'DPAPI Activity', 'RPC Events', 'Plug and Play Events')'Logon/Logoff' = @('Logon', 'Logoff', 'Account Lockout', 'Special Logon', 'Other Logon/Logoff Events', 'Network Policy Server')'Object Access' = @('File System', 'Registry', 'Kernel Object', 'SAM', 'Handle Manipulation', 'File Share', 'Filtering Platform Packet Drop', 'Filtering Platform Connection')'Policy Change' = @('Audit Policy Change', 'Authentication Policy Change', 'Authorization Policy Change', 'MPSSVC Rule-Level Policy Change', 'Filtering Platform Policy Change')@@ -89,6 +89,14 @@ function Enable-AuditPolicies {'System' = @('Security State Change', 'Security System Extension', 'System Integrity', 'IPsec Driver', 'Other System Events')}}++ foreach ($level in @($auditSettings.Keys)) {+ foreach ($category in @($auditSettings[$level].Keys)) {+ $auditSettings[$level][$category] = @($auditSettings[$level][$category] | ForEach-Object {+ @{ Name = $_; Guid = Get-AuditSubcategoryGuid -Name $_ }+ })+ }+ }}process {@@ -103,23 +111,27 @@ function Enable-AuditPolicies {foreach ($subcategory in $selectedSettings[$category]) {try {+ if ($null -eq $subcategory.Guid) {+ Write-Warning " - Skipped: $($subcategory.Name) (no GUID in subcategory map)"+ continue+ }# Enable both Success and Failure auditing- if ($PSCmdlet.ShouldProcess($subcategory, "Enable audit policy")) {- $result = & auditpol /set /subcategory:"$subcategory" /success:enable /failure:enable 2>&1+ if ($PSCmdlet.ShouldProcess($subcategory.Name, "Enable audit policy")) {+ $result = & auditpol /set /subcategory:"$($subcategory.Guid)" /success:enable /failure:enable 2>&1if ($LASTEXITCODE -eq 0) {- $results.PoliciesConfigured += $subcategory- Write-Host " + $subcategory" -ForegroundColor Green+ $results.PoliciesConfigured += $subcategory.Name+ Write-Host " + $($subcategory.Name)" -ForegroundColor Green}else {- $results.Errors += "Failed to configure: $subcategory - $result"- Write-Warning " - Failed: $subcategory"+ $results.Errors += "Failed to configure: $($subcategory.Name) - $result"+ Write-Warning " - Failed: $($subcategory.Name)"}}}catch {- $results.Errors += "Error configuring $subcategory : $_"- Write-Warning " - Error: $subcategory"+ $results.Errors += "Error configuring $($subcategory.Name) : $_"+ Write-Warning " - Error: $($subcategory.Name)"}}@@ -128,7 +140,7 @@ function Enable-AuditPolicies {if ($results.AuditCategories.ContainsKey($categoryKey)) {$results.AuditCategories[$categoryKey] = @{Configured = $true- Subcategories = $selectedSettings[$category]+ Subcategories = @($selectedSettings[$category] | ForEach-Object { $_.Name })}}}@@ -221,7 +233,7 @@ function Enable-AuditPolicies {# Create audit rule for Everyone - Track both Success and Failure$auditRule = New-Object System.Security.AccessControl.FileSystemAuditRule(- "Everyone",+ (New-Object System.Security.Principal.SecurityIdentifier('S-1-1-0')),"Delete,DeleteSubdirectoriesAndFiles,ChangePermissions,TakeOwnership","ContainerInherit,ObjectInherit","None",@@ -264,7 +276,7 @@ function Enable-AuditPolicies {$acl = Get-Acl $regKey$auditRule = New-Object System.Security.AccessControl.RegistryAuditRule(- "Everyone",+ (New-Object System.Security.Principal.SecurityIdentifier('S-1-1-0')),"SetValue,CreateSubKey,Delete","ContainerInherit","None",@@ -314,8 +326,29 @@ function Enable-AuditPolicies {# Verify current audit policyWrite-Host "`nVerifying configuration..." -ForegroundColor Cyan- $verifyResult = auditpol /get /category:* | Out-String- Write-Verbose $verifyResult+ $auditTable = Get-AuditPolicyTable -Force+ $verifiedPolicies = 0+ $unverifiedPolicies = @()+ foreach ($category in $selectedSettings.Keys) {+ foreach ($subcategory in $selectedSettings[$category]) {+ if ($null -eq $subcategory.Guid) { continue }+ $guidKey = ($subcategory.Guid -replace '[{}]', '').ToLowerInvariant()+ if ($auditTable.ContainsKey($guidKey) -and $null -ne $auditTable[$guidKey].Value -and+ $auditTable[$guidKey].Value -ge 1 -and $auditTable[$guidKey].Value -le 3) {+ $verifiedPolicies+++ }+ else {+ $unverifiedPolicies += $subcategory.Name+ }+ }+ }+ Write-Host " Verified: $verifiedPolicies subcategories with auditing enabled" -ForegroundColor White+ if ($unverifiedPolicies.Count -gt 0) {+ Write-Host " Unverified: $($unverifiedPolicies.Count)" -ForegroundColor Yellow+ foreach ($name in $unverifiedPolicies) {+ Write-Host " - $name" -ForegroundColor Yellow+ }+ }Write-Host "`nRecommendations:" -ForegroundColor CyanWrite-Host " 1. Monitor Security event log regularly" -ForegroundColor Whitediff --git a/Hardening/Set-SecurityBaseline.ps1 b/Hardening/Set-SecurityBaseline.ps1index a21590d..e734b1c 100644--- a/Hardening/Set-SecurityBaseline.ps1+++ b/Hardening/Set-SecurityBaseline.ps1@@ -269,11 +269,17 @@ function Set-SecurityBaseline {# Configure account lockout policynet accounts /lockoutthreshold:5 /lockoutduration:30 /lockoutwindow:30 | Out-Null+ if ($LASTEXITCODE -ne 0) {+ Write-Warning " Account lockout policy configuration failed (net accounts exit code $LASTEXITCODE)"+ }$results.Changes += "Account lockout policy configured (5 attempts, 30 min lockout)"# Password policyif ($BaselineLevel -in @('Recommended', 'Strict')) {net accounts /minpwlen:12 /maxpwage:90 /minpwage:1 /uniquepw:5 | Out-Null+ if ($LASTEXITCODE -ne 0) {+ Write-Warning " Password policy configuration failed (net accounts exit code $LASTEXITCODE)"+ }$results.Changes += "Password policy: 12 char minimum, 90 day max age"}@@ -311,6 +317,9 @@ function Set-SecurityBaseline {# Enable DEP (Data Execution Prevention)bcdedit /set nx AlwaysOn | Out-Null+ if ($LASTEXITCODE -ne 0) {+ Write-Warning " DEP configuration failed (bcdedit exit code $LASTEXITCODE)"+ }$results.Changes += "DEP enabled"# Disable unnecessary servicesdiff --git a/Private/Get-AuditPolicyTable.ps1 b/Private/Get-AuditPolicyTable.ps1new file mode 100644index 0000000..6cb18d4--- /dev/null+++ b/Private/Get-AuditPolicyTable.ps1@@ -0,0 +1,400 @@+<#+.SYNOPSIS+ Locale-invariant advanced audit policy helpers (private).+.DESCRIPTION+ Get-AuditPolicyTable resolves per-subcategory audit policy settings keyed by+ subcategory GUID (GUIDs are locale-invariant; canonical English names come+ from the static map below). Resolution order:+ 1. AuditQuerySystemPolicy API (advapi32)+ 2. auditpol /backup CSV (elevated)+ 3. auditpol /get CSV (English Inclusion text only, non-admin)+ 4. Unavailable (all Values $null)+.NOTES+ GUID map verified against MS-GPAC and dsccommunity/AuditPolicyDsc+ ($AuditSubcategoryToGUIDHash, edited from "auditpol /list /subcategory:* /v").+#>++$script:AuditSubcategoryMap = @{+ 'Security State Change' = '{0CCE9210-69AE-11D9-BED3-505054503030}'+ 'Security System Extension' = '{0CCE9211-69AE-11D9-BED3-505054503030}'+ 'System Integrity' = '{0CCE9212-69AE-11D9-BED3-505054503030}'+ 'IPsec Driver' = '{0CCE9213-69AE-11D9-BED3-505054503030}'+ 'Other System Events' = '{0CCE9214-69AE-11D9-BED3-505054503030}'+ 'Logon' = '{0CCE9215-69AE-11D9-BED3-505054503030}'+ 'Logoff' = '{0CCE9216-69AE-11D9-BED3-505054503030}'+ 'Account Lockout' = '{0CCE9217-69AE-11D9-BED3-505054503030}'+ 'IPsec Main Mode' = '{0CCE9218-69AE-11D9-BED3-505054503030}'+ 'IPsec Quick Mode' = '{0CCE9219-69AE-11D9-BED3-505054503030}'+ 'IPsec Extended Mode' = '{0CCE921A-69AE-11D9-BED3-505054503030}'+ 'Special Logon' = '{0CCE921B-69AE-11D9-BED3-505054503030}'+ 'Other Logon/Logoff Events' = '{0CCE921C-69AE-11D9-BED3-505054503030}'+ 'Network Policy Server' = '{0CCE9243-69AE-11D9-BED3-505054503030}'+ 'User / Device Claims' = '{0CCE9247-69AE-11D9-BED3-505054503030}'+ 'Group Membership' = '{0CCE9249-69AE-11D9-BED3-505054503030}'+ 'File System' = '{0CCE921D-69AE-11D9-BED3-505054503030}'+ 'Registry' = '{0CCE921E-69AE-11D9-BED3-505054503030}'+ 'Kernel Object' = '{0CCE921F-69AE-11D9-BED3-505054503030}'+ 'SAM' = '{0CCE9220-69AE-11D9-BED3-505054503030}'+ 'Certification Services' = '{0CCE9221-69AE-11D9-BED3-505054503030}'+ 'Application Generated' = '{0CCE9222-69AE-11D9-BED3-505054503030}'+ 'Handle Manipulation' = '{0CCE9223-69AE-11D9-BED3-505054503030}'+ 'File Share' = '{0CCE9224-69AE-11D9-BED3-505054503030}'+ 'Filtering Platform Packet Drop' = '{0CCE9225-69AE-11D9-BED3-505054503030}'+ 'Filtering Platform Connection' = '{0CCE9226-69AE-11D9-BED3-505054503030}'+ 'Other Object Access Events' = '{0CCE9227-69AE-11D9-BED3-505054503030}'+ 'Detailed File Share' = '{0CCE9244-69AE-11D9-BED3-505054503030}'+ 'Removable Storage' = '{0CCE9245-69AE-11D9-BED3-505054503030}'+ 'Central Policy Staging' = '{0CCE9246-69AE-11D9-BED3-505054503030}'+ 'Sensitive Privilege Use' = '{0CCE9228-69AE-11D9-BED3-505054503030}'+ 'Non Sensitive Privilege Use' = '{0CCE9229-69AE-11D9-BED3-505054503030}'+ 'Other Privilege Use Events' = '{0CCE922A-69AE-11D9-BED3-505054503030}'+ 'Process Creation' = '{0CCE922B-69AE-11D9-BED3-505054503030}'+ 'Process Termination' = '{0CCE922C-69AE-11D9-BED3-505054503030}'+ 'DPAPI Activity' = '{0CCE922D-69AE-11D9-BED3-505054503030}'+ 'RPC Events' = '{0CCE922E-69AE-11D9-BED3-505054503030}'+ 'Plug and Play Events' = '{0CCE9248-69AE-11D9-BED3-505054503030}'+ 'Token Right Adjusted Events' = '{0CCE924A-69AE-11D9-BED3-505054503030}'+ 'Audit Policy Change' = '{0CCE922F-69AE-11D9-BED3-505054503030}'+ 'Authentication Policy Change' = '{0CCE9230-69AE-11D9-BED3-505054503030}'+ 'Authorization Policy Change' = '{0CCE9231-69AE-11D9-BED3-505054503030}'+ 'MPSSVC Rule-Level Policy Change' = '{0CCE9232-69AE-11D9-BED3-505054503030}'+ 'Filtering Platform Policy Change' = '{0CCE9233-69AE-11D9-BED3-505054503030}'+ 'Other Policy Change Events' = '{0CCE9234-69AE-11D9-BED3-505054503030}'+ 'User Account Management' = '{0CCE9235-69AE-11D9-BED3-505054503030}'+ 'Computer Account Management' = '{0CCE9236-69AE-11D9-BED3-505054503030}'+ 'Security Group Management' = '{0CCE9237-69AE-11D9-BED3-505054503030}'+ 'Distribution Group Management' = '{0CCE9238-69AE-11D9-BED3-505054503030}'+ 'Application Group Management' = '{0CCE9239-69AE-11D9-BED3-505054503030}'+ 'Other Account Management Events' = '{0CCE923A-69AE-11D9-BED3-505054503030}'+ 'Directory Service Access' = '{0CCE923B-69AE-11D9-BED3-505054503030}'+ 'Directory Service Changes' = '{0CCE923C-69AE-11D9-BED3-505054503030}'+ 'Directory Service Replication' = '{0CCE923D-69AE-11D9-BED3-505054503030}'+ 'Detailed Directory Service Replication' = '{0CCE923E-69AE-11D9-BED3-505054503030}'+ 'Credential Validation' = '{0CCE923F-69AE-11D9-BED3-505054503030}'+ 'Kerberos Service Ticket Operations' = '{0CCE9240-69AE-11D9-BED3-505054503030}'+ 'Other Account Logon Events' = '{0CCE9241-69AE-11D9-BED3-505054503030}'+ 'Kerberos Authentication Service' = '{0CCE9242-69AE-11D9-BED3-505054503030}'+}++$script:AuditPolicyTableCache = $null++function Get-AuditSubcategoryGuid {+ [CmdletBinding()]+ [OutputType([string])]+ param(+ [Parameter()]+ [string]$Name+ )++ if ([string]::IsNullOrWhiteSpace($Name)) { return $null }+ if ($script:AuditSubcategoryMap.ContainsKey($Name)) {+ return $script:AuditSubcategoryMap[$Name]+ }+ foreach ($key in $script:AuditSubcategoryMap.Keys) {+ if ($key -ieq $Name) { return $script:AuditSubcategoryMap[$key] }+ }+ return $null+}++function ConvertFrom-AuditPolicyBackupCsv {+ <#+ .SYNOPSIS+ Parses an 'auditpol /backup' CSV into a locale-invariant GUID -> value map (private).+ .DESCRIPTION+ Returns a hashtable keyed by lowercase subcategory GUID (no braces) with the+ numeric Setting Value (0-3) for each row. Locale-dependent columns (header+ row, subcategory names, inclusion text) are never interpreted: the header+ row is skipped positionally and replaced by fixed English headers+ (WinLogKit PR #58 / AuditPolicyDsc pattern), rows are matched by GUID and+ numeric value only (which also drops the Option: rows), and when both+ System and per-user rows exist the System rows win. Accepts either a file+ -Path or raw -Lines (first line = header in both cases).+ #>+ [CmdletBinding(DefaultParameterSetName = 'Path')]+ [OutputType([hashtable])]+ param(+ [Parameter(Mandatory = $true, ParameterSetName = 'Path')]+ [ValidateNotNullOrEmpty()]+ [string]$Path,++ [Parameter(Mandatory = $true, ParameterSetName = 'Lines')]+ [AllowEmptyCollection()]+ [AllowEmptyString()]+ [string[]]$Lines+ )++ $values = @{}++ $rawLines = @()+ if ($PSCmdlet.ParameterSetName -eq 'Path') {+ # Backup file is ANSI/system codepage on localized Windows: read WITHOUT+ # -Encoding (forcing UTF8 corrupts it, salt#68354).+ $rawLines = @(Get-Content -LiteralPath $Path)+ }+ else {+ $rawLines = @($Lines)+ }++ $dataLines = @($rawLines | Select-Object -Skip 1 |+ Where-Object { -not [string]::IsNullOrWhiteSpace($_) })+ if ($dataLines.Count -eq 0) { return $values }++ $rows = @($dataLines | ConvertFrom-Csv -Header 'Machine', 'Target', 'Subcategory', 'Guid', 'Inclusion', 'Exclusion', 'Value')+ $guidPattern = '^[0-9A-Fa-f]{8}(-[0-9A-Fa-f]{4}){3}-[0-9A-Fa-f]{12}$'+ $candidates = @()+ foreach ($row in $rows) {+ $rowGuid = ''+ if ($null -ne $row.Guid) { $rowGuid = ($row.Guid -replace '[{}]', '').Trim() }+ $rowValue = ''+ if ($null -ne $row.Value) { $rowValue = $row.Value.Trim() }+ # GUID/Value filters drop the Option: rows+ if ($rowGuid -match $guidPattern -and $rowValue -match '^[0-3]$') {+ $candidates += $row+ }+ }+ # Localized Windows may localize the Target column+ $systemRows = @($candidates | Where-Object { $_.Target -eq 'System' })+ if ($systemRows.Count -gt 0) { $effective = $systemRows } else { $effective = $candidates }+ $seen = @{}+ foreach ($row in $effective) {+ $key = (($row.Guid -replace '[{}]', '').Trim()).ToLowerInvariant()+ if ($seen.ContainsKey($key)) { continue }+ $seen[$key] = $true+ $values[$key] = [int]($row.Value.Trim())+ }+ return $values+}++function Get-AuditPolicyTable {+ [CmdletBinding()]+ [OutputType([hashtable])]+ param(+ [Parameter()]+ [string[]]$Subcategory,++ [Parameter()]+ [switch]$Force+ )++ $subsetRequested = ($PSBoundParameters.ContainsKey('Subcategory') -and+ $null -ne $Subcategory -and $Subcategory.Count -gt 0)++ if (-not $subsetRequested -and -not $Force -and $null -ne $script:AuditPolicyTableCache) {+ return $script:AuditPolicyTableCache+ }++ if ($subsetRequested) {+ $names = @($Subcategory)+ }+ else {+ $names = @($script:AuditSubcategoryMap.Keys)+ }++ # Table keyed by lowercase GUID without braces+ $guidToName = @{}+ foreach ($name in $names) {+ $guid = Get-AuditSubcategoryGuid -Name $name+ if ($null -eq $guid) {+ Write-Verbose "Get-AuditPolicyTable: unknown subcategory name '$name' (skipped)"+ continue+ }+ $key = ($guid -replace '[{}]', '').ToLowerInvariant()+ $guidToName[$key] = $name+ }++ $table = @{}+ foreach ($key in $guidToName.Keys) {+ $table[$key] = [PSCustomObject]@{+ Guid = ('{' + $key.ToUpperInvariant() + '}')+ Name = $guidToName[$key]+ Value = $null+ Success = $false+ Failure = $false+ Source = 'Unavailable'+ }+ }++ $isWindowsHost = $false+ try {+ $isWindowsHost = [System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform(+ [System.Runtime.InteropServices.OSPlatform]::Windows)+ }+ catch {+ # RuntimeInformation missing on old .NET Framework (PS 5.1)+ $isWindowsHost = ($env:OS -eq 'Windows_NT')+ }+ if (-not $isWindowsHost) {+ Write-Verbose 'Get-AuditPolicyTable: not a Windows host; audit policy not applicable'+ if (-not $subsetRequested) { $script:AuditPolicyTableCache = $table }+ return $table+ }++ $resolved = $false+ $auditpol = $null++ # --- Strategy 1: AuditQuerySystemPolicy API (HardeningLens pattern) ---+ if (-not ([bool]('AuditPolicyNative' -as [type]))) {+ $auditPolicyNativeSource = @'+using System;+using System.Runtime.InteropServices;+public static class AuditPolicyNative {+ [StructLayout(LayoutKind.Sequential)]+ public struct AUDIT_POLICY_INFORMATION {+ public Guid AuditSubCategoryGuid;+ public UInt32 AuditingInformation;+ public Guid AuditCategoryGuid;+ }+ [DllImport("advapi32.dll", SetLastError = true)]+ [return: MarshalAs(UnmanagedType.U1)]+ private static extern bool AuditQuerySystemPolicy([In] Guid[] pSubCategoryGuids, UInt32 PolicyCount, out IntPtr ppAuditPolicy);+ [DllImport("advapi32.dll")] private static extern void AuditFree(IntPtr buffer);+ public static AUDIT_POLICY_INFORMATION[] QueryPolicies(Guid[] guids, out int win32Error) {+ win32Error = 0;+ IntPtr buffer = IntPtr.Zero;+ if (!AuditQuerySystemPolicy(guids, (UInt32)guids.Length, out buffer)) {+ win32Error = Marshal.GetLastWin32Error();+ return null;+ }+ try {+ AUDIT_POLICY_INFORMATION[] result = new AUDIT_POLICY_INFORMATION[guids.Length];+ IntPtr current = buffer;+ int size = Marshal.SizeOf(typeof(AUDIT_POLICY_INFORMATION));+ for (int i = 0; i < guids.Length; i++) {+ result[i] = (AUDIT_POLICY_INFORMATION)Marshal.PtrToStructure(current, typeof(AUDIT_POLICY_INFORMATION));+ current = new IntPtr(current.ToInt64() + size);+ }+ return result;+ } finally { AuditFree(buffer); }+ }+}+'@+ try {+ Add-Type -TypeDefinition $auditPolicyNativeSource -ErrorAction Stop+ }+ catch {+ # Add-Type -TypeDefinition is blocked under Constrained Language Mode (JEA)+ Write-Verbose "Get-AuditPolicyTable: Add-Type AuditPolicyNative failed: $($_.Exception.Message)"+ }+ }++ if ([bool]('AuditPolicyNative' -as [type])) {+ try {+ $guidList = New-Object 'System.Collections.Generic.List[guid]'+ foreach ($key in $guidToName.Keys) { $guidList.Add([guid]$key) }+ $win32Error = 0+ $policies = [AuditPolicyNative]::QueryPolicies($guidList.ToArray(), [ref]$win32Error)+ if ($null -ne $policies) {+ for ($i = 0; $i -lt $policies.Count; $i++) {+ $key = $policies[$i].AuditSubCategoryGuid.ToString()+ if (-not $table.ContainsKey($key)) { continue }+ # POLICY_AUDIT_EVENT_SUCCESS=1, FAILURE=2, NONE=4; 4 and 0 both mean No Auditing+ $raw = [int]$policies[$i].AuditingInformation+ $success = [bool]($raw -band 1)+ $failure = [bool]($raw -band 2)+ $value = 0+ if ($success) { $value += 1 }+ if ($failure) { $value += 2 }+ $entry = $table[$key]+ $entry.Value = $value+ $entry.Success = $success+ $entry.Failure = $failure+ $entry.Source = 'Api'+ $resolved = $true+ }+ }+ else {+ # 5 = ACCESS_DENIED, 1314 = PRIVILEGE_NOT_HELD: fall through to next strategy+ Write-Verbose "Get-AuditPolicyTable: AuditQuerySystemPolicy failed (win32 $win32Error)"+ }+ }+ catch {+ Write-Verbose "Get-AuditPolicyTable: API strategy failed: $($_.Exception.Message)"+ }+ }++ # --- Strategy 2: auditpol /backup CSV (elevated) ---+ if (-not $resolved) {+ $auditpol = Get-Command 'auditpol.exe' -ErrorAction SilentlyContinue+ if ($null -eq $auditpol) {+ $auditpol = Get-Command 'auditpol' -ErrorAction SilentlyContinue+ }+ if ($null -ne $auditpol) {+ $tempFile = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath ('wsa-audit-{0}.csv' -f [guid]::NewGuid().ToString('N'))+ try {+ $null = & $auditpol.Source '/backup' "/file:$tempFile" 2>&1+ if ($LASTEXITCODE -eq 0 -and (Test-Path -LiteralPath $tempFile)) {+ $backupValues = ConvertFrom-AuditPolicyBackupCsv -Path $tempFile+ foreach ($key in $backupValues.Keys) {+ if (-not $table.ContainsKey($key)) { continue }+ $value = $backupValues[$key]+ $entry = $table[$key]+ $entry.Value = $value+ $entry.Success = [bool]($value -band 1)+ $entry.Failure = [bool]($value -band 2)+ $entry.Source = 'BackupCsv'+ $resolved = $true+ }+ }+ else {+ Write-Verbose "Get-AuditPolicyTable: auditpol /backup failed (exit $LASTEXITCODE); elevation required"+ }+ }+ catch {+ Write-Verbose "Get-AuditPolicyTable: backup CSV strategy failed: $($_.Exception.Message)"+ }+ finally {+ if (Test-Path -LiteralPath $tempFile -ErrorAction SilentlyContinue) {+ Remove-Item -LiteralPath $tempFile -Force -ErrorAction SilentlyContinue+ }+ }+ }+ }++ # --- Strategy 3: auditpol /get CSV (non-admin, English text only) ---+ if (-not $resolved -and $null -ne $auditpol) {+ try {+ $output = @(& $auditpol.Source '/get' '/category:*' '/r' 2>$null)+ if ($LASTEXITCODE -eq 0 -and $output.Count -gt 1) {+ $lines = @($output | Select-Object -Skip 1 |+ Where-Object { -not [string]::IsNullOrWhiteSpace($_) })+ $rows = @($lines | ConvertFrom-Csv -Header 'Machine', 'Target', 'Subcategory', 'Guid', 'Inclusion', 'Exclusion')+ foreach ($row in $rows) {+ if ($null -eq $row.Guid) { continue }+ $key = (($row.Guid -replace '[{}]', '').Trim()).ToLowerInvariant()+ if (-not $table.ContainsKey($key)) { continue }+ $inclusion = ''+ if ($null -ne $row.Inclusion) { $inclusion = $row.Inclusion.Trim() }+ # Interpret ONLY canonical English text; localized text stays honestly unknown+ $value = $null+ if ($inclusion -ieq 'Success and Failure') { $value = 3 }+ elseif ($inclusion -ieq 'Success') { $value = 1 }+ elseif ($inclusion -ieq 'Failure') { $value = 2 }+ elseif ($inclusion -ieq 'No Auditing') { $value = 0 }+ $entry = $table[$key]+ if ($null -ne $value) {+ $entry.Value = $value+ $entry.Success = [bool]($value -band 1)+ $entry.Failure = [bool]($value -band 2)+ }+ $entry.Source = 'GetQuery'+ $resolved = $true+ }+ }+ else {+ Write-Verbose "Get-AuditPolicyTable: auditpol /get failed (exit $LASTEXITCODE)"+ }+ }+ catch {+ Write-Verbose "Get-AuditPolicyTable: get CSV strategy failed: $($_.Exception.Message)"+ }+ }++ if (-not $resolved) {+ Write-Verbose 'Get-AuditPolicyTable: all resolution strategies failed; returning Unavailable table'+ }++ if (-not $subsetRequested) {+ $script:AuditPolicyTableCache = $table+ }+ return $table+}diff --git a/Private/Get-LocalPasswordPolicy.ps1 b/Private/Get-LocalPasswordPolicy.ps1new file mode 100644index 0000000..e874a69--- /dev/null+++ b/Private/Get-LocalPasswordPolicy.ps1@@ -0,0 +1,257 @@+<#+.SYNOPSIS+ Locale-invariant local password/lockout policy helper (private).+.DESCRIPTION+ Get-LocalPasswordPolicy queries the local SAM account policy via+ NetUserModalsGet (netapi32, levels 0 and 3). When elevated, it merges+ PasswordComplexity/ClearTextPassword (and serves as full fallback) from a+ secedit /export INF whose [System Access] keys are English on all locales.+ NEVER calls 'net accounts' (localized output).+.NOTES+ Struct layouts verified from lmaccess.h (USER_MODALS_INFO_0/3).+ NetApi ages are seconds; USER_MODALS_INFO_3 duration/observation window are+ MINUTES per lmaccess.h (some sources wrongly say seconds). TIMEQ_FOREVER+ (0xFFFFFFFF) maps to -1 ("never" / "until admin unlocks").+#>++function Get-LocalPasswordPolicy {+ [CmdletBinding()]+ [OutputType([PSCustomObject])]+ param()++ $policy = [PSCustomObject]@{+ MinPasswordLength = $null+ MaxPasswordAgeDays = $null+ MinPasswordAgeDays = $null+ PasswordHistoryLength = $null+ LockoutThreshold = $null+ LockoutDurationMinutes = $null+ LockoutObservationWindowMinutes = $null+ ForceLogoffHours = $null+ PasswordComplexity = $null+ ClearTextPassword = $null+ Source = 'Unavailable'+ }++ $isWindowsHost = $false+ try {+ $isWindowsHost = [System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform(+ [System.Runtime.InteropServices.OSPlatform]::Windows)+ }+ catch {+ # RuntimeInformation missing on old .NET Framework (PS 5.1)+ $isWindowsHost = ($env:OS -eq 'Windows_NT')+ }+ if (-not $isWindowsHost) {+ Write-Verbose 'Get-LocalPasswordPolicy: not a Windows host; local SAM policy not applicable'+ return $policy+ }++ # --- Primary: NetUserModalsGet levels 0 and 3 ---+ $netApiOk = $false+ if (-not ([bool]('NetApiModals' -as [type]))) {+ $netApiModalsSource = @'+using System;+using System.Runtime.InteropServices;+public static class NetApiModals {+ [StructLayout(LayoutKind.Sequential)]+ public struct USER_MODALS_INFO_0 {+ public uint usrmod0_min_passwd_len;+ public uint usrmod0_max_passwd_age; // seconds+ public uint usrmod0_min_passwd_age; // seconds+ public uint usrmod0_force_logoff; // seconds; 0xFFFFFFFF = TIMEQ_FOREVER+ public uint usrmod0_password_hist_len;+ }+ [StructLayout(LayoutKind.Sequential)]+ public struct USER_MODALS_INFO_3 {+ public uint usrmod3_lockout_duration; // minutes+ public uint usrmod3_lockout_observation_window; // minutes+ public uint usrmod3_lockout_threshold;+ }+ [DllImport("netapi32.dll", CharSet = CharSet.Unicode)]+ private static extern uint NetUserModalsGet(string server, int level, out IntPtr bufPtr);+ [DllImport("netapi32.dll")] private static extern uint NetApiBufferFree(IntPtr bufPtr);+ public static USER_MODALS_INFO_0 GetLevel0(out uint netError) {+ IntPtr buf = IntPtr.Zero;+ netError = NetUserModalsGet(null, 0, out buf);+ if (netError != 0) { return new USER_MODALS_INFO_0(); }+ try { return (USER_MODALS_INFO_0)Marshal.PtrToStructure(buf, typeof(USER_MODALS_INFO_0)); }+ finally { NetApiBufferFree(buf); }+ }+ public static USER_MODALS_INFO_3 GetLevel3(out uint netError) {+ IntPtr buf = IntPtr.Zero;+ netError = NetUserModalsGet(null, 3, out buf);+ if (netError != 0) { return new USER_MODALS_INFO_3(); }+ try { return (USER_MODALS_INFO_3)Marshal.PtrToStructure(buf, typeof(USER_MODALS_INFO_3)); }+ finally { NetApiBufferFree(buf); }+ }+}+'@+ try {+ Add-Type -TypeDefinition $netApiModalsSource -ErrorAction Stop+ }+ catch {+ # Add-Type -TypeDefinition is blocked under Constrained Language Mode (JEA)+ Write-Verbose "Get-LocalPasswordPolicy: Add-Type NetApiModals failed: $($_.Exception.Message)"+ }+ }++ if ([bool]('NetApiModals' -as [type])) {+ $level0Error = [uint32]0+ try {+ $modals0 = [NetApiModals]::GetLevel0([ref]$level0Error)+ if ($level0Error -eq 0) {+ $policy.MinPasswordLength = [int]$modals0.usrmod0_min_passwd_len+ if ($modals0.usrmod0_max_passwd_age -eq 0xFFFFFFFF) {+ $policy.MaxPasswordAgeDays = -1+ }+ else {+ $policy.MaxPasswordAgeDays = [int][math]::Round($modals0.usrmod0_max_passwd_age / 86400)+ }+ if ($modals0.usrmod0_min_passwd_age -eq 0xFFFFFFFF) {+ $policy.MinPasswordAgeDays = -1+ }+ else {+ $policy.MinPasswordAgeDays = [int][math]::Round($modals0.usrmod0_min_passwd_age / 86400)+ }+ if ($modals0.usrmod0_force_logoff -eq 0xFFFFFFFF) {+ $policy.ForceLogoffHours = -1+ }+ else {+ $policy.ForceLogoffHours = [int][math]::Round($modals0.usrmod0_force_logoff / 3600)+ }+ $policy.PasswordHistoryLength = [int]$modals0.usrmod0_password_hist_len+ $netApiOk = $true+ }+ else {+ Write-Verbose "Get-LocalPasswordPolicy: NetUserModalsGet level 0 failed (netError $level0Error)"+ }+ }+ catch {+ Write-Verbose "Get-LocalPasswordPolicy: NetApi level 0 failed: $($_.Exception.Message)"+ }++ $level3Error = [uint32]0+ try {+ $modals3 = [NetApiModals]::GetLevel3([ref]$level3Error)+ if ($level3Error -eq 0) {+ # Minutes per lmaccess.h; reported as-is even when threshold is 0+ # (lockout disabled). TIMEQ_FOREVER duration = until admin unlocks.+ if ($modals3.usrmod3_lockout_duration -eq 0xFFFFFFFF) {+ $policy.LockoutDurationMinutes = -1+ }+ else {+ $policy.LockoutDurationMinutes = [int]$modals3.usrmod3_lockout_duration+ }+ if ($modals3.usrmod3_lockout_observation_window -eq 0xFFFFFFFF) {+ $policy.LockoutObservationWindowMinutes = -1+ }+ else {+ $policy.LockoutObservationWindowMinutes = [int]$modals3.usrmod3_lockout_observation_window+ }+ $policy.LockoutThreshold = [int]$modals3.usrmod3_lockout_threshold+ $netApiOk = $true+ }+ else {+ Write-Verbose "Get-LocalPasswordPolicy: NetUserModalsGet level 3 failed (netError $level3Error)"+ }+ }+ catch {+ Write-Verbose "Get-LocalPasswordPolicy: NetApi level 3 failed: $($_.Exception.Message)"+ }++ if ($netApiOk) { $policy.Source = 'NetApi' }+ }++ # --- Secedit (elevated): full fallback, or merge of the two NetApi cannot see ---+ $isAdmin = $false+ try {+ $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()+ ).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ }+ catch {+ $isAdmin = $false+ }++ $needSecedit = (-not $netApiOk) -or ($null -eq $policy.PasswordComplexity)+ $seceditData = $null+ if ($needSecedit -and $isAdmin) {+ $secedit = Get-Command 'secedit.exe' -ErrorAction SilentlyContinue+ if ($null -eq $secedit) {+ $secedit = Get-Command 'secedit' -ErrorAction SilentlyContinue+ }+ if ($null -ne $secedit) {+ $tempFile = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath ('wsa-secpol-{0}.inf' -f [guid]::NewGuid().ToString('N'))+ try {+ $null = & $secedit.Source '/export' '/cfg' $tempFile '/quiet' 2>&1+ if ($LASTEXITCODE -eq 0 -and (Test-Path -LiteralPath $tempFile)) {+ # INF is UTF-16 with BOM; Get-Content auto-detects.+ # [System Access] keys are English on all locales.+ $seceditData = @{}+ $inSection = $false+ foreach ($line in (Get-Content -LiteralPath $tempFile)) {+ $trimmed = $line.Trim()+ if ($trimmed -match '^\[') {+ $inSection = ($trimmed -ieq '[System Access]')+ continue+ }+ if ($inSection -and $trimmed -match '^([^=]+)=(.*)$') {+ $seceditData[$Matches[1].Trim()] = $Matches[2].Trim()+ }+ }+ }+ else {+ Write-Verbose "Get-LocalPasswordPolicy: secedit /export failed (exit $LASTEXITCODE)"+ }+ }+ catch {+ Write-Verbose "Get-LocalPasswordPolicy: secedit fallback failed: $($_.Exception.Message)"+ }+ finally {+ if (Test-Path -LiteralPath $tempFile -ErrorAction SilentlyContinue) {+ Remove-Item -LiteralPath $tempFile -Force -ErrorAction SilentlyContinue+ }+ }+ }+ }++ if ($null -ne $seceditData) {+ if (-not $netApiOk) {+ # INF ages are already in days; -1 sentinel = never+ if ($seceditData.ContainsKey('MinimumPasswordLength') -and $seceditData['MinimumPasswordLength'] -match '^-?\d+$') {+ $policy.MinPasswordLength = [int]$seceditData['MinimumPasswordLength']+ }+ if ($seceditData.ContainsKey('MaximumPasswordAge') -and $seceditData['MaximumPasswordAge'] -match '^-?\d+$') {+ $policy.MaxPasswordAgeDays = [int]$seceditData['MaximumPasswordAge']+ }+ if ($seceditData.ContainsKey('MinimumPasswordAge') -and $seceditData['MinimumPasswordAge'] -match '^-?\d+$') {+ $policy.MinPasswordAgeDays = [int]$seceditData['MinimumPasswordAge']+ }+ if ($seceditData.ContainsKey('PasswordHistorySize') -and $seceditData['PasswordHistorySize'] -match '^-?\d+$') {+ $policy.PasswordHistoryLength = [int]$seceditData['PasswordHistorySize']+ }+ if ($seceditData.ContainsKey('LockoutBadCount') -and $seceditData['LockoutBadCount'] -match '^-?\d+$') {+ $policy.LockoutThreshold = [int]$seceditData['LockoutBadCount']+ }+ if ($seceditData.ContainsKey('LockoutDuration') -and $seceditData['LockoutDuration'] -match '^-?\d+$') {+ $policy.LockoutDurationMinutes = [int]$seceditData['LockoutDuration']+ }+ if ($seceditData.ContainsKey('ResetLockoutCount') -and $seceditData['ResetLockoutCount'] -match '^-?\d+$') {+ $policy.LockoutObservationWindowMinutes = [int]$seceditData['ResetLockoutCount']+ }+ $policy.Source = 'Secedit'+ }+ if ($seceditData.ContainsKey('PasswordComplexity') -and $seceditData['PasswordComplexity'] -match '^-?\d+$') {+ $policy.PasswordComplexity = ([int]$seceditData['PasswordComplexity'] -eq 1)+ }+ if ($seceditData.ContainsKey('ClearTextPassword') -and $seceditData['ClearTextPassword'] -match '^-?\d+$') {+ $policy.ClearTextPassword = ([int]$seceditData['ClearTextPassword'] -eq 1)+ }+ if ($netApiOk) { $policy.Source = 'NetApi+Secedit' }+ }++ if ($policy.Source -eq 'Unavailable') {+ Write-Verbose 'Get-LocalPasswordPolicy: all resolution strategies failed; returning Unavailable'+ }+ return $policy+}diff --git a/Private/Get-WlanProfileList.ps1 b/Private/Get-WlanProfileList.ps1new file mode 100644index 0000000..01d29c6--- /dev/null+++ b/Private/Get-WlanProfileList.ps1@@ -0,0 +1,151 @@+<#+.SYNOPSIS+ Locale-invariant WLAN profile list helper (private).+.DESCRIPTION+ Get-WlanProfileList enumerates Wi-Fi profiles via wlanapi.dll. Profiles and+ interface descriptions come straight from the API, so no locale parsing is+ involved. Returns an empty array (NOT an error) when: not Windows,+ wlanapi.dll missing, WlanSvc stopped (WlanOpenHandle error 1062 or any+ nonzero), or zero interfaces.+.NOTES+ P/Invoke signatures verbatim from ManagedWifi (Apache-2.0). All enumeration+ and marshaling happens inside C# to avoid the PS 5.1 binder picking wrong+ PtrToStructure overloads; every list buffer is freed with WlanFreeMemory.+#>++function Get-WlanProfileList {+ [CmdletBinding()]+ [OutputType([PSCustomObject[]])]+ param()++ $result = @()++ # Cheap pre-check so macOS/Linux dev boxes degrade silently+ $isWindowsHost = $false+ try {+ $isWindowsHost = [System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform(+ [System.Runtime.InteropServices.OSPlatform]::Windows)+ }+ catch {+ # RuntimeInformation missing on old .NET Framework (PS 5.1)+ $isWindowsHost = ($env:OS -eq 'Windows_NT')+ }+ if (-not $isWindowsHost) {+ Write-Verbose 'Get-WlanProfileList: not a Windows host; WLAN not applicable'+ return $result+ }++ if (-not ([bool]('WlanNative' -as [type]))) {+ $wlanNativeSource = @'+using System;+using System.Collections.Generic;+using System.Runtime.InteropServices;+public static class WlanNative {+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]+ public struct WLAN_INTERFACE_INFO {+ public Guid InterfaceGuid;+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]+ public string InterfaceDescription;+ public int isState;+ }+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]+ public struct WLAN_PROFILE_INFO {+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]+ public string strProfileName;+ public uint dwFlags;+ }+ [DllImport("wlanapi.dll")]+ public static extern int WlanOpenHandle(uint clientVersion, IntPtr pReserved, out uint negotiatedVersion, out IntPtr clientHandle);+ [DllImport("wlanapi.dll")]+ public static extern int WlanEnumInterfaces(IntPtr clientHandle, IntPtr pReserved, out IntPtr ppInterfaceList);+ [DllImport("wlanapi.dll")]+ public static extern int WlanGetProfileList(IntPtr clientHandle, [MarshalAs(UnmanagedType.LPStruct)] Guid interfaceGuid, IntPtr pReserved, out IntPtr ppProfileList);+ [DllImport("wlanapi.dll")]+ public static extern void WlanFreeMemory(IntPtr pMemory);+ [DllImport("wlanapi.dll")]+ public static extern int WlanCloseHandle(IntPtr clientHandle, IntPtr pReserved);+ public class WlanProfile {+ public string Name;+ public uint Flags;+ public string InterfaceDescription;+ }+ public static WlanProfile[] GetProfiles(out int win32Error) {+ win32Error = 0;+ List<WlanProfile> profiles = new List<WlanProfile>();+ IntPtr clientHandle = IntPtr.Zero;+ uint negotiatedVersion = 0;+ int err = WlanOpenHandle(2, IntPtr.Zero, out negotiatedVersion, out clientHandle);+ if (err != 0) { win32Error = err; return null; }+ try {+ IntPtr pInterfaceList;+ err = WlanEnumInterfaces(clientHandle, IntPtr.Zero, out pInterfaceList);+ if (err != 0) { win32Error = err; return null; }+ try {+ // List header is { uint dwNumberOfItems; uint dwIndex; } then the item array+ int interfaceCount = Marshal.ReadInt32(pInterfaceList);+ int interfaceSize = Marshal.SizeOf(typeof(WLAN_INTERFACE_INFO));+ IntPtr currentInterface = new IntPtr(pInterfaceList.ToInt64() + 8);+ for (int i = 0; i < interfaceCount; i++) {+ WLAN_INTERFACE_INFO iface = (WLAN_INTERFACE_INFO)Marshal.PtrToStructure(currentInterface, typeof(WLAN_INTERFACE_INFO));+ currentInterface = new IntPtr(currentInterface.ToInt64() + interfaceSize);+ IntPtr pProfileList;+ int profileErr = WlanGetProfileList(clientHandle, iface.InterfaceGuid, IntPtr.Zero, out pProfileList);+ if (profileErr != 0) { continue; }+ try {+ int profileCount = Marshal.ReadInt32(pProfileList);+ int profileSize = Marshal.SizeOf(typeof(WLAN_PROFILE_INFO));+ IntPtr currentProfile = new IntPtr(pProfileList.ToInt64() + 8);+ for (int j = 0; j < profileCount; j++) {+ WLAN_PROFILE_INFO info = (WLAN_PROFILE_INFO)Marshal.PtrToStructure(currentProfile, typeof(WLAN_PROFILE_INFO));+ currentProfile = new IntPtr(currentProfile.ToInt64() + profileSize);+ WlanProfile profile = new WlanProfile();+ profile.Name = info.strProfileName;+ profile.Flags = info.dwFlags;+ profile.InterfaceDescription = iface.InterfaceDescription;+ profiles.Add(profile);+ }+ } finally { WlanFreeMemory(pProfileList); }+ }+ } finally { WlanFreeMemory(pInterfaceList); }+ } finally { WlanCloseHandle(clientHandle, IntPtr.Zero); }+ return profiles.ToArray();+ }+}+'@+ try {+ Add-Type -TypeDefinition $wlanNativeSource -ErrorAction Stop+ }+ catch {+ # Add-Type -TypeDefinition is blocked under Constrained Language Mode (JEA)+ Write-Verbose "Get-WlanProfileList: Add-Type WlanNative failed: $($_.Exception.Message)"+ return $result+ }+ }++ try {+ $win32Error = 0+ $profiles = [WlanNative]::GetProfiles([ref]$win32Error)+ if ($null -eq $profiles) {+ # 1062 = WlanSvc not running; any nonzero is 'not applicable', not an error+ Write-Verbose "Get-WlanProfileList: WLAN API unavailable (win32 $win32Error)"+ return $result+ }+ foreach ($profile in $profiles) {+ $flags = [uint32]$profile.Flags+ $result += [PSCustomObject]@{+ Name = $profile.Name+ Flags = $flags+ IsGroupPolicy = [bool]($flags -band 1)+ IsPerUser = [bool]($flags -band 2)+ InterfaceDescription = $profile.InterfaceDescription+ }+ }+ }+ catch {+ # wlanapi.dll missing etc.: 'not applicable', not an error+ Write-Verbose "Get-WlanProfileList: enumeration failed: $($_.Exception.Message)"+ $result = @()+ }++ return $result+}diff --git a/Private/IdentityHelpers.ps1 b/Private/IdentityHelpers.ps1new file mode 100644index 0000000..2e53ea3--- /dev/null+++ b/Private/IdentityHelpers.ps1@@ -0,0 +1,275 @@+<#+.SYNOPSIS+ Locale-invariant identity helpers (private).+.DESCRIPTION+ SID-based lookups that survive non-English Windows, 32-bit PowerShell on+ 64-bit Windows (LocalAccounts module missing), domain controllers (no local+ SAM), and unresolvable SIDs (AzureAD-joined machines, PowerShell#2996).+ All functions degrade to empty/$null/$false instead of throwing.+#>++# False = last admin-group lookup failed (unknown), NOT 'zero admins'+$script:AdminGroupLookupSucceeded = $false++function Get-WellKnownSid {+ [CmdletBinding()]+ [OutputType([hashtable])]+ param()++ return @{+ Administrators = 'S-1-5-32-544'+ Users = 'S-1-5-32-545'+ Guests = 'S-1-5-32-546'+ BackupOperators = 'S-1-5-32-551'+ RemoteDesktopUsers = 'S-1-5-32-555'+ System = 'S-1-5-18'+ LocalService = 'S-1-5-19'+ NetworkService = 'S-1-5-20'+ Everyone = 'S-1-1-0'+ AuthenticatedUsers = 'S-1-5-11'+ }+}++function Get-AdminGroupMembers {+ [CmdletBinding()]+ [OutputType([PSCustomObject[]])]+ param(+ [Parameter()]+ [string]$Sid = 'S-1-5-32-544'+ )++ $script:AdminGroupLookupSucceeded = $false+ $members = @()++ # Preferred: LocalAccounts module, addressed by SID (locale-invariant).+ # NOTE: module is missing in 32-bit PowerShell on 64-bit Windows.+ if (Get-Command 'Get-LocalGroupMember' -ErrorAction SilentlyContinue) {+ try {+ $sidObject = [Security.Principal.SecurityIdentifier]$Sid+ $raw = @(Get-LocalGroupMember -SID $sidObject -ErrorAction Stop)+ foreach ($member in $raw) {+ $memberName = $null+ $memberSid = $null+ $memberClass = $null+ if ($null -ne $member) {+ if ($member.PSObject.Properties['Name']) { $memberName = $member.Name }+ if ($member.PSObject.Properties['SID'] -and $null -ne $member.SID) {+ $memberSid = $member.SID.Value+ }+ if ($member.PSObject.Properties['ObjectClass']) { $memberClass = $member.ObjectClass }+ }+ $members += [PSCustomObject]@{+ Name = $memberName+ SID = $memberSid+ ObjectClass = $memberClass+ }+ }+ $script:AdminGroupLookupSucceeded = $true+ return $members+ }+ catch {+ # Includes the known 'Failed to compare two elements' bug on+ # unresolvable SIDs (AzureAD-joined machines, PowerShell#2996)+ Write-Verbose "Get-AdminGroupMembers: Get-LocalGroupMember failed, trying ADSI: $($_.Exception.Message)"+ }+ }++ # Fallback: ADSI WinNT provider. SID -> localized group name, then enumerate.+ try {+ $groupName = ([Security.Principal.SecurityIdentifier]$Sid).Translate(+ [Security.Principal.NTAccount]).Value.Split('\')[-1]+ }+ catch {+ Write-Verbose "Get-AdminGroupMembers: cannot translate SID $Sid : $($_.Exception.Message)"+ return $members+ }++ try {+ $group = ([ADSI]"WinNT://./$groupName,group")+ $rawMembers = @($group.psbase.Invoke('Members'))+ foreach ($member in $rawMembers) {+ $memberName = $null+ $memberSid = $null+ $memberClass = $null+ try {+ $memberName = $member.GetType().InvokeMember('Name', 'GetProperty', $null, $member, $null)+ }+ catch {+ Write-Verbose "Get-AdminGroupMembers: member Name unreadable: $($_.Exception.Message)"+ }+ try {+ $memberClass = $member.GetType().InvokeMember('Class', 'GetProperty', $null, $member, $null)+ }+ catch {+ Write-Verbose "Get-AdminGroupMembers: member Class unreadable: $($_.Exception.Message)"+ }+ $members += [PSCustomObject]@{+ Name = $memberName+ SID = $memberSid+ ObjectClass = $memberClass+ }+ }+ $script:AdminGroupLookupSucceeded = $true+ }+ catch {+ Write-Verbose "Get-AdminGroupMembers: ADSI enumeration failed: $($_.Exception.Message)"+ $members = @()+ }++ return $members+}++function Get-LocalUserByRid {+ [CmdletBinding()]+ [OutputType([PSCustomObject])]+ param(+ [Parameter(Mandatory = $true)]+ [int]$Rid+ )++ $suffix = "-$Rid"++ # Preferred: LocalAccounts module (missing in 32-bit PowerShell on 64-bit Windows)+ if (Get-Command 'Get-LocalUser' -ErrorAction SilentlyContinue) {+ try {+ $user = @(Get-LocalUser -ErrorAction Stop |+ Where-Object { $null -ne $_.SID -and $_.SID.Value.EndsWith($suffix) } |+ Select-Object -First 1)+ if ($user.Count -gt 0 -and $null -ne $user[0]) {+ return [PSCustomObject]@{+ Name = $user[0].Name+ SID = $user[0].SID.Value+ Enabled = $user[0].Enabled+ Description = $user[0].Description+ }+ }+ }+ catch {+ Write-Verbose "Get-LocalUserByRid: Get-LocalUser failed: $($_.Exception.Message)"+ }+ }++ # Fallback: CIM Win32_UserAccount (SID values are locale-invariant)+ if (Get-Command 'Get-CimInstance' -ErrorAction SilentlyContinue) {+ try {+ $account = @(Get-CimInstance -ClassName 'Win32_UserAccount' -Filter 'LocalAccount=True' -ErrorAction Stop |+ Where-Object { $null -ne $_.SID -and $_.SID.EndsWith($suffix) } |+ Select-Object -First 1)+ if ($account.Count -gt 0 -and $null -ne $account[0]) {+ $enabled = $null+ if ($account[0].PSObject.Properties['Disabled'] -and $null -ne $account[0].Disabled) {+ $enabled = (-not $account[0].Disabled)+ }+ return [PSCustomObject]@{+ Name = $account[0].Name+ SID = $account[0].SID+ Enabled = $enabled+ Description = $account[0].Description+ }+ }+ }+ catch {+ Write-Verbose "Get-LocalUserByRid: CIM query failed: $($_.Exception.Message)"+ }+ }++ # Last resort: ADSI WinNT provider, RID extracted from objectSID bytes+ try {+ $computer = [ADSI]'WinNT://.'+ foreach ($child in @($computer.psbase.Children)) {+ $schemaClass = $null+ try {+ $schemaClass = $child.GetType().InvokeMember('SchemaClassName', 'GetProperty', $null, $child, $null)+ }+ catch {+ continue+ }+ if ($schemaClass -ne 'User') { continue }+ try {+ $sidBytes = [byte[]]($child.GetType().InvokeMember('objectSID', 'GetProperty', $null, $child, $null))+ $userSid = (New-Object Security.Principal.SecurityIdentifier($sidBytes, 0)).Value+ if ($userSid.EndsWith($suffix)) {+ $userName = $child.GetType().InvokeMember('Name', 'GetProperty', $null, $child, $null)+ $userFlags = 0+ $description = $null+ try {+ $userFlags = [int]($child.GetType().InvokeMember('UserFlags', 'GetProperty', $null, $child, $null))+ }+ catch {+ Write-Verbose "Get-LocalUserByRid: UserFlags unreadable: $($_.Exception.Message)"+ }+ try {+ $description = $child.GetType().InvokeMember('Description', 'GetProperty', $null, $child, $null)+ }+ catch {+ Write-Verbose "Get-LocalUserByRid: Description unreadable: $($_.Exception.Message)"+ }+ # ADS_UF_ACCOUNTDISABLE = 0x2+ return [PSCustomObject]@{+ Name = $userName+ SID = $userSid+ Enabled = (-not [bool]($userFlags -band 0x2))+ Description = $description+ }+ }+ }+ catch {+ Write-Verbose "Get-LocalUserByRid: ADSI user unreadable: $($_.Exception.Message)"+ }+ }+ }+ catch {+ Write-Verbose "Get-LocalUserByRid: ADSI enumeration failed: $($_.Exception.Message)"+ }++ return $null+}++function Test-IdentityReferenceIsSid {+ [CmdletBinding()]+ [OutputType([bool])]+ param(+ [Parameter()]+ $IdentityReference,++ [Parameter()]+ [string]$Sid+ )++ if ($null -eq $IdentityReference -or [string]::IsNullOrEmpty($Sid)) { return $false }++ try {+ if ($IdentityReference -is [Security.Principal.SecurityIdentifier]) {+ return ($IdentityReference.Value -eq $Sid)+ }++ $ntAccount = $null+ if ($IdentityReference -is [Security.Principal.NTAccount]) {+ $ntAccount = $IdentityReference+ }+ elseif ($IdentityReference -is [string]) {+ # Some ACLs carry unresolved SIDs as plain strings+ if ($IdentityReference -eq $Sid) { return $true }+ try {+ $ntAccount = New-Object Security.Principal.NTAccount($IdentityReference)+ }+ catch {+ $ntAccount = $null+ }+ }++ if ($null -ne $ntAccount) {+ try {+ return ($ntAccount.Translate([Security.Principal.SecurityIdentifier]).Value -eq $Sid)+ }+ catch {+ # Untranslatable name; fall through to raw string equality+ }+ }++ return ([string]$IdentityReference -eq $Sid)+ }+ catch {+ return $false+ }+}diff --git a/README.md b/README.mdindex 83ced11..8648ebb 100644--- a/README.md+++ b/README.md@@ -5,7 +5,7 @@[](https://github.com/PowerShell/PowerShell)[](https://www.microsoft.com/windows)[](LICENSE)-[](https://github.com/okanyildiz/WindowsSecurityAudit/releases)+[](https://github.com/okanyildiz/WindowsSecurityAudit/releases)[](https://github.com/okanyildiz/WindowsSecurityAudit)[](https://github.com/okanyildiz/WindowsSecurityAudit)[](https://github.com/okanyildiz/WindowsSecurityAudit/actions/workflows/ci.yml)@@ -698,7 +698,24 @@ The Reporting module transforms raw security data into actionable intelligence tThe full feature set is documented in the module tables above — this section only covers what changed per release, newest first:-### 🆕 v1.5.0 — Fleet Scans, Sysmon Analytics, SIEM Streaming & Smart Alerts+### 🆕 v1.6.0 — Full Non-English Windows Support (Locale-Invariant Auditing)++**A correctness overhaul, not just a feature:** every check that parsed localized console output (`auditpol`, `net accounts`, `netsh`, `fsutil`, SFC/DISM) or matched localized identity names (`Administrators`, `Guest`, `Everyone`, `NT AUTHORITY\SYSTEM`) has been rewritten to use **APIs, GUIDs and SIDs** — the module now produces correct results on Turkish, German, French and any other Windows display language, and reports an honest *"unable to determine"* instead of a silent wrong PASS when data is unreachable.++**New internal data sources (`Private/`, 4 helpers):**++| Helper | Replaces | How |+|--------|----------|-----|+| **`Get-AuditPolicyTable`** | localized `auditpol /get` text parsing | `AuditQuerySystemPolicy` P/Invoke (GUID-keyed) → elevated `auditpol /backup` fixed-header CSV (numeric Setting Value) → GUID-addressed `/get` with honest unknowns; full **59-subcategory GUID map** (MS-GPAC) |+| **`Get-LocalPasswordPolicy`** | localized `net accounts` parsing | `NetUserModalsGet` levels 0+3 (non-admin, binary API) with elevated `secedit /export` fallback for `PasswordComplexity` |+| **`Get-WlanProfileList`** | localized `netsh wlan show profiles` | `wlanapi.dll` P/Invoke; missing WLAN service/feature = "not applicable", not an error |+| **Identity helpers** | name-based group/user/ACL lookups | SID-first (`S-1-5-32-544`, RID 500/501, `S-1-1-0`…) with ADSI fallback; safe under 32-bit PowerShell and AzureAD unresolvable SIDs |++**27 call sites migrated across 16 files** — compliance frameworks (CIS/NIST/PCI-DSS), enterprise assessment & fleet scans, audit-policy hardening (GUID-based `/set` — `Enable-AuditPolicies` previously only worked on English Windows), registry/ACL analysis, defense-evasion detection, SFC/DISM integrity, memory-dump and scheduled-scan **ACL lockdowns (these silently failed on non-English systems, leaving credential-bearing files world-readable)**.++**Regression armor:** new `tests/Locale.Regression.Tests.ps1` — English/German (ANSI cp1252) auditpol fixture equivalence tests, plus a static **"no text readers" guard** that fails CI if localized-output parsing ever re-enters the codebase.++### v1.5.0 — Fleet Scans, Sysmon Analytics, SIEM Streaming & Smart Alerts**3 new functions** — bringing the toolkit to **72 functions across 14 modules**:@@ -980,13 +997,15 @@ We work with Fortune 500 companies, government agencies, and organizations of al## 🚀 Roadmap-### Version 1.6 (Next)-- [ ] **Locale-invariant parsing** — make `auditpol` / `net accounts` parsing robust on non-English Windows-- [ ] **Raw $MFT record parsing** — go beyond fsutil summary output for full file-system timelines-- [ ] **JEA endpoint support** — run remote scans through Just Enough Administration constrained endpoints+### Version 1.7 (Next)+- [ ] **Raw $MFT record parsing** — go beyond fsutil summary output for full file-system timelines (locale-invariant `FSCTL_READ_USN_JOURNAL` P/Invoke replaces fsutil text parsing)+- [ ] **JEA endpoint support** — run remote scans through Just Enough Administration constrained endpoints (CLM-safe: precompiled helpers, no Add-Type dependency)- [ ] **Alert webhook DPAPI protection** — encrypt stored webhook URLs at rest- [ ] **SIEM streaming auth profiles** — named credential profiles and OAuth flows for Send-SiemEvent+### Version 1.6 (Released)+- [x] **Locale-invariant auditing** — all `auditpol` / `net accounts` / `netsh` / `fsutil` / SFC-DISM parsing and name-based identity lookups replaced by APIs, GUIDs and SIDs; correct results on non-English Windows with honest "unable to determine" states+### Version 2.0 (Future)- [ ] Web-based GUI dashboard- [ ] REST API for remote managementdiff --git a/ThreatHunting/Find-APTIndicators.ps1 b/ThreatHunting/Find-APTIndicators.ps1index 1bf7b48..d08a301 100644--- a/ThreatHunting/Find-APTIndicators.ps1+++ b/ThreatHunting/Find-APTIndicators.ps1@@ -141,7 +141,7 @@ function Find-APTIndicators {# Skip whitelisted services$isWhitelisted = $falseforeach ($legit in $legitimateServices) {- if ($service.Name -like "*$legit*" -or $service.DisplayName -like "*$legit*") {+ if ($service.Name -like "*$legit*") {$isWhitelisted = $truebreak}@@ -156,7 +156,7 @@ function Find-APTIndicators {# Check for actual malicious namesforeach ($malName in $knownMaliciousNames) {- if ($service.Name -match $malName -or $service.DisplayName -match $malName) {+ if ($service.Name -match $malName) {$suspiciousScore += 70$reasons += "CRITICAL: Name matches known malware: $malName"}diff --git a/Vulnerability/Get-SecurityMisconfigurations.ps1 b/Vulnerability/Get-SecurityMisconfigurations.ps1index 95bccd3..90fc31b 100644--- a/Vulnerability/Get-SecurityMisconfigurations.ps1+++ b/Vulnerability/Get-SecurityMisconfigurations.ps1@@ -334,7 +334,7 @@ function Get-SecurityMisconfigurations {try {$acl = Get-Acl $path -ErrorAction SilentlyContinue$everyoneWrite = $acl.Access | Where-Object {- $_.IdentityReference -eq 'Everyone' -and+ (Test-IdentityReferenceIsSid -IdentityReference $_.IdentityReference -Sid 'S-1-1-0') -and$_.FileSystemRights -match 'Write|FullControl|Modify'}diff --git a/WindowsSecurityAudit.psd1 b/WindowsSecurityAudit.psd1index da06520..9ccc936 100644--- a/WindowsSecurityAudit.psd1+++ b/WindowsSecurityAudit.psd1@@ -1,6 +1,6 @@@{RootModule = 'WindowsSecurityAudit.psm1'- ModuleVersion = '1.5.0'+ ModuleVersion = '1.6.0'GUID = 'a8d7c4e5-3b2f-4e8a-9c1d-6f5a8b9d2e7c'Author = 'Okan YILDIZ'CompanyName = 'okanyildiz'diff --git a/WindowsSecurityAudit.psm1 b/WindowsSecurityAudit.psm1index f4e8601..addde7f 100644--- a/WindowsSecurityAudit.psm1+++ b/WindowsSecurityAudit.psm1@@ -14,7 +14,7 @@ Set-StrictMode -Version Latest# Module variables$script:ModuleRoot = $PSScriptRoot-$script:ModuleVersion = '1.5.0'+$script:ModuleVersion = '1.6.0'# Import all function files$Public = @(Get-ChildItem -Path "$PSScriptRoot\Core\*.ps1" -ErrorAction SilentlyContinue)diff --git a/tests/Locale.Regression.Tests.ps1 b/tests/Locale.Regression.Tests.ps1new file mode 100644index 0000000..59624da--- /dev/null+++ b/tests/Locale.Regression.Tests.ps1@@ -0,0 +1,350 @@+#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' }++<#+.SYNOPSIS+ Locale-regression tests for the Private/ locale-invariant helpers.+.DESCRIPTION+ Cross-platform tests (run green on macOS and on the Windows CI lint job):++ * Fixture equivalence (WinLogKit PR #58 pattern): the English and German+ (ANSI/cp1252, localized header + names + inclusion text) auditpol /backup+ fixtures in tests/fixtures/ must parse to IDENTICAL GUID -> Value maps via+ ConvertFrom-AuditPolicyBackupCsv. Junk Option: rows and blank lines are+ filtered by the GUID regex; System rows win over per-user rows.+ * Static regression guard ('no text readers'): locale-fragile parsing patterns+ are forbidden in every module file. All legacy call sites were migrated to the+ Private/ helpers in v1.6.0, so the forbidden lists below carry NO grandfather+ entries — any occurrence anywhere fails the build.+ * Helper contract/degradation on non-Windows hosts: Get-AuditPolicyTable,+ Get-LocalPasswordPolicy, Get-WlanProfileList and Get-LocalUserByRid degrade+ to Unavailable/empty/$null instead of throwing; Test-IdentityReferenceIsSid+ and Get-WellKnownSid honor their SID contracts on every platform.++ Two documented seams do NOT exist yet and their tests are skipped on purpose:+ the auditpol /get CSV parse is still inline in Get-AuditPolicyTable (strategy 3,+ honest-unknown on localized inclusion text), and the NetApi seconds->days /+ TIMEQ_FOREVER (0xFFFFFFFF) -> -1 conversions are inline behind the C#+ NetUserModalsGet interop in Get-LocalPasswordPolicy.ps1. Extract pure parser+ seams first, then unskip.++ The module targets Windows PowerShell 5.1+, so only APIs available in+ 5.1 are used here (no null-coalescing/ternary operators, no ForEach-Object -Parallel).+#>++BeforeDiscovery {+ $script:ModuleRoot = Split-Path -Parent $PSScriptRoot+ $script:ModuleName = 'WindowsSecurityAudit'++ # Locale-fragile patterns that must never appear. All legacy call sites were+ # migrated to the Private/ helpers in v1.6.0 — any match anywhere fails the guard.+ $script:ForbiddenReaders = @(+ @{+ Name = "raw 'auditpol /get' text parsing (localized Inclusion columns)"+ Regex = 'auditpol(\.exe)?\s+/get\b'+ Grandfathered = @()+ }+ @{+ Name = "'Minimum password length' label parsing of 'net accounts' output"+ Regex = 'Select-String\s+["''][^"'']*[Pp]assword\s+[Ll]ength'+ Grandfathered = @()+ }+ @{+ Name = 'name-based Get-LocalGroupMember -Group with a string literal'+ Regex = 'Get-LocalGroupMember\b[^\n|]*-Group\s+["'']'+ Grandfathered = @()+ }+ @{+ Name = 'name-based Get-LocalUser -Name Guest/Administrator'+ Regex = 'Get-LocalUser\b[^\n|]*-Name\s+["''](Guest|Administrator)["'']'+ Grandfathered = @()+ }+ @{+ Name = 'string identities (Everyone / NT AUTHORITY\SYSTEM / BUILTIN\Administrators) in FileSystemAccessRule'+ Regex = 'FileSystemAccessRule\(\s*["''](Everyone|NT AUTHORITY\\SYSTEM|BUILTIN\\Administrators)["'']'+ Grandfathered = @()+ }+ @{+ Name = "IdentityReference matched against '(Everyone' style name patterns"+ Regex = 'IdentityReference\b[^\n]*-match\s+["''][^"'']*\(?Everyone'+ Grandfathered = @()+ }+ )+}++BeforeAll {+ $script:ModuleRoot = Split-Path -Parent $PSScriptRoot+ $script:ModuleName = 'WindowsSecurityAudit'+ $script:ModulePath = Join-Path -Path $script:ModuleRoot -ChildPath "$script:ModuleName.psm1"+ $script:FixturePath = Join-Path -Path $PSScriptRoot -ChildPath 'fixtures'+ $script:EnFixture = Join-Path -Path $script:FixturePath -ChildPath 'auditpol-backup-en.csv'+ $script:DeFixture = Join-Path -Path $script:FixturePath -ChildPath 'auditpol-backup-de.csv'++ Import-Module -Name $script:ModulePath -Force -DisableNameChecking++ $script:IsWindowsHost = $false+ try {+ $script:IsWindowsHost = [System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform(+ [System.Runtime.InteropServices.OSPlatform]::Windows)+ }+ catch {+ # RuntimeInformation missing on old .NET Framework (PS 5.1)+ $script:IsWindowsHost = ($env:OS -eq 'Windows_NT')+ }++ # Every module .ps1 file except the tests folder and Private/Get-AuditPolicyTable.ps1+ # (the one file allowed to touch auditpol /get output, covered by fixtures instead)+ $script:GuardedFiles = @(+ Get-ChildItem -Path $script:ModuleRoot -Filter '*.ps1' -Recurse -File |+ Where-Object {+ $_.FullName -notmatch '[\\/]\.git[\\/]' -and+ $_.FullName -notmatch '[\\/]tests[\\/]' -and+ $_.FullName -ne (Join-Path -Path $script:ModuleRoot -ChildPath 'Private/Get-AuditPolicyTable.ps1')+ } |+ ForEach-Object {+ $relative = $_.FullName.Substring($script:ModuleRoot.Length) -replace '^[\\/]+', '' -replace '[\\/]', '/'+ [PSCustomObject]@{ FullName = $_.FullName; RelativePath = $relative }+ }+ )+}++AfterAll {+ Remove-Module -Name $script:ModuleName -Force -ErrorAction SilentlyContinue+}++Describe 'ConvertFrom-AuditPolicyBackupCsv fixture equivalence (WinLogKit PR #58 pattern)' {+ It 'parses the German ANSI/cp1252 fixture without throwing (salt#68354)' {+ InModuleScope -ModuleName $script:ModuleName -ArgumentList $script:DeFixture -ScriptBlock {+ param($deFixture)+ { ConvertFrom-AuditPolicyBackupCsv -Path $deFixture } | Should -Not -Throw+ }+ }++ It 'pins the English fixture to the expected GUID -> Value map' {+ InModuleScope -ModuleName $script:ModuleName -ArgumentList $script:EnFixture -ScriptBlock {+ param($enFixture)+ $expected = @{+ '0cce9210-69ae-11d9-bed3-505054503030' = 3 # Security State Change+ '0cce9212-69ae-11d9-bed3-505054503030' = 3 # System Integrity+ '0cce9215-69ae-11d9-bed3-505054503030' = 3 # Logon+ '0cce9216-69ae-11d9-bed3-505054503030' = 1 # Logoff+ '0cce921b-69ae-11d9-bed3-505054503030' = 1 # Special Logon+ '0cce921d-69ae-11d9-bed3-505054503030' = 0 # File System (No Auditing)+ '0cce9228-69ae-11d9-bed3-505054503030' = 2 # Sensitive Privilege Use (Failure)+ '0cce922b-69ae-11d9-bed3-505054503030' = 1 # Process Creation+ '0cce923b-69ae-11d9-bed3-505054503030' = 2 # Directory Service Access+ '0cce923f-69ae-11d9-bed3-505054503030' = 3 # Credential Validation+ }+ $map = ConvertFrom-AuditPolicyBackupCsv -Path $enFixture+ $map.Count | Should -Be $expected.Count+ foreach ($key in @($expected.Keys)) {+ $map.ContainsKey($key) | Should -BeTrue -Because "GUID $key must be parsed"+ $map[$key] | Should -Be $expected[$key] -Because "numeric Setting Value is locale-invariant ($key)"+ }+ }+ }++ It 'produces IDENTICAL GUID -> Value maps from the English and the localized German fixture' {+ InModuleScope -ModuleName $script:ModuleName -ArgumentList $script:EnFixture, $script:DeFixture -ScriptBlock {+ param($enFixture, $deFixture)+ $enMap = ConvertFrom-AuditPolicyBackupCsv -Path $enFixture+ $deMap = ConvertFrom-AuditPolicyBackupCsv -Path $deFixture+ $deMap.Count | Should -Be $enMap.Count+ $enKeys = @($enMap.Keys | Sort-Object)+ $deKeys = @($deMap.Keys | Sort-Object)+ ($deKeys -join ',') | Should -Be ($enKeys -join ',') -Because 'subcategory GUIDs are locale-invariant'+ foreach ($key in $enKeys) {+ $deMap[$key] | Should -Be $enMap[$key] -Because "localized names/inclusion text must not change the numeric value ($key)"+ }+ }+ }++ It 'filters the Option:CrashOnAuditFail junk row and blank lines via the GUID regex' {+ InModuleScope -ModuleName $script:ModuleName -ArgumentList $script:EnFixture -ScriptBlock {+ param($enFixture)+ # The fixture carries 10 real subcategory rows plus one Option: row+ # (no GUID), one blank line and one per-user row: exactly 10 survive+ $map = ConvertFrom-AuditPolicyBackupCsv -Path $enFixture+ $map.Count | Should -Be 10 -Because 'the Option: junk row, the blank line and the per-user row must not add entries'+ @($map.Keys | Where-Object { $_ -notmatch '^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$' }).Count |+ Should -Be 0 -Because 'every surviving key must be a bare GUID'+ }+ }++ It 'lets System rows win over per-user rows for the same GUID' {+ InModuleScope -ModuleName $script:ModuleName -ArgumentList $script:EnFixture, $script:DeFixture -ScriptBlock {+ param($enFixture, $deFixture)+ # Both fixtures carry a per-user Logon row (value 1) after the System row (value 3)+ $enMap = ConvertFrom-AuditPolicyBackupCsv -Path $enFixture+ $deMap = ConvertFrom-AuditPolicyBackupCsv -Path $deFixture+ $enMap['0cce9215-69ae-11d9-bed3-505054503030'] | Should -Be 3 -Because 'the System row must win over the per-user SID row'+ $deMap['0cce9215-69ae-11d9-bed3-505054503030'] | Should -Be 3 -Because 'the System row must win over the per-user SID row'+ }+ }++ It 'falls back to per-user rows only when no System rows exist' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ $lines = @(+ 'Machine Name,Policy Target,Subcategory,Subcategory GUID,Inclusion Setting,Exclusion Setting,Setting Value'+ 'WSA-TEST01,S-1-5-21-3623811015-3361044348-30300820-1001,Logon,{0CCE9215-69AE-11D9-BED3-505054503030},Success,,1'+ )+ $map = ConvertFrom-AuditPolicyBackupCsv -Lines $lines+ $map['0cce9215-69ae-11d9-bed3-505054503030'] | Should -Be 1 -Because 'with no System row present the per-user row is the only source'+ }+ }++ It 'accepts raw -Lines with the same result as -Path' {+ InModuleScope -ModuleName $script:ModuleName -ArgumentList $script:EnFixture -ScriptBlock {+ param($enFixture)+ $fromPath = ConvertFrom-AuditPolicyBackupCsv -Path $enFixture+ # No -Encoding, exactly like the production read of the backup file+ $fromLines = ConvertFrom-AuditPolicyBackupCsv -Lines @(Get-Content -LiteralPath $enFixture)+ $fromLines.Count | Should -Be $fromPath.Count+ foreach ($key in @($fromPath.Keys)) {+ $fromLines[$key] | Should -Be $fromPath[$key]+ }+ }+ }++ It 'returns an empty map for content without a header and data rows' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ $map = ConvertFrom-AuditPolicyBackupCsv -Lines @('header only')+ $map.Count | Should -Be 0+ }+ }++ # SKIPPED (no parse seam): the auditpol /get CSV parse (6 columns, no numeric+ # value, English-only Inclusion text) is still inline in Get-AuditPolicyTable+ # (strategy 3) and the change under test allowed extracting only the BackupCsv+ # strategy. Once a ConvertFrom-AuditPolicyGetCsv-style seam exists, add a German+ # /r fixture ('Erfolg und Fehler') asserting Value stays $null (honest unknown)+ # instead of being guessed from localized text.+ It 'never guesses values from localized auditpol /get inclusion text' -Skip {+ }+}++Describe 'No locale-fragile text readers (static regression guard)' {+ It 'no new file uses <Name>' -ForEach $script:ForbiddenReaders {+ $offenders = @(+ foreach ($file in $script:GuardedFiles) {+ if ($_.Grandfathered -contains $file.RelativePath) { continue }+ $content = Get-Content -Path $file.FullName -Raw+ if ($null -ne $content -and $content -match $_.Regex) { $file.RelativePath }+ }+ )+ $offenders.Count | Should -Be 0 -Because ("locale-fragile pattern '{0}' is forbidden module-wide since v1.6.0 (use the Private/ locale-invariant helpers): {1}" -f $_.Name, ($offenders -join ', '))+ }++ It "'net accounts' appears only in Hardening/Set-SecurityBaseline.ps1 (legit /set usage)" {+ # Invocation context only: the doc comment in Private/Get-LocalPasswordPolicy.ps1+ # ('NEVER calls net accounts') is documentation, not an invocation+ $regex = '(?m)(=|\||;|\{|\()\s*net(\.exe)?\s+accounts\b|^[ \t]*net(\.exe)?\s+accounts\b'+ $allowed = @(+ 'Hardening/Set-SecurityBaseline.ps1' # legit /set (write) usage+ )+ $offenders = @(+ foreach ($file in $script:GuardedFiles) {+ if ($allowed -contains $file.RelativePath) { continue }+ $content = Get-Content -Path $file.FullName -Raw+ if ($null -ne $content -and $content -match $regex) { $file.RelativePath }+ }+ )+ $offenders.Count | Should -Be 0 -Because ("'net accounts' output is localized; reads must go through Get-LocalPasswordPolicy, writes belong to Set-SecurityBaseline: {0}" -f ($offenders -join ', '))+ }+}++Describe 'Private helper contract and degradation' {+ Context 'non-Windows hosts (macOS/Linux dev boxes and CI)' {+ It 'Get-AuditPolicyTable returns 59 entries, all Source=Unavailable with null Values' {+ if ($script:IsWindowsHost) {+ Set-ItResult -Skipped -Because 'on Windows the table resolves real data via Api/BackupCsv instead of degrading'+ return+ }+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ $table = Get-AuditPolicyTable -Force+ $table.Count | Should -Be 59 -Because 'one entry per known audit subcategory GUID'+ $entries = @($table.Values)+ @($entries | Where-Object { $_.Source -ne 'Unavailable' }).Count | Should -Be 0+ @($entries | Where-Object { $null -ne $_.Value }).Count | Should -Be 0+ @($entries | Where-Object { $_.Success -or $_.Failure }).Count | Should -Be 0+ }+ }++ It 'Get-LocalPasswordPolicy degrades to Source=Unavailable' {+ if ($script:IsWindowsHost) {+ Set-ItResult -Skipped -Because 'on Windows the SAM policy resolves via NetApi/Secedit instead of degrading'+ return+ }+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ $policy = Get-LocalPasswordPolicy+ $policy.Source | Should -Be 'Unavailable'+ $policy.MinPasswordLength | Should -BeNullOrEmpty+ $policy.MaxPasswordAgeDays | Should -BeNullOrEmpty+ }+ }++ It 'Get-WlanProfileList returns an empty array' {+ if ($script:IsWindowsHost) {+ Set-ItResult -Skipped -Because 'on Windows the WLAN API may return real profiles'+ return+ }+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ $profiles = @(Get-WlanProfileList)+ $profiles.Count | Should -Be 0+ }+ }++ It 'Get-LocalUserByRid -Rid 500 returns null instead of throwing' {+ if ($script:IsWindowsHost) {+ Set-ItResult -Skipped -Because 'on Windows RID 500 (built-in Administrator) exists and resolves'+ return+ }+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ { Get-LocalUserByRid -Rid 500 } | Should -Not -Throw+ Get-LocalUserByRid -Rid 500 | Should -BeNullOrEmpty+ }+ }+ }++ Context 'platform-independent identity helpers' {+ It 'Test-IdentityReferenceIsSid matches a raw unresolved SID string against the same SID' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ Test-IdentityReferenceIsSid -IdentityReference 'S-1-1-0' -Sid 'S-1-1-0' | Should -BeTrue+ }+ }++ It 'Test-IdentityReferenceIsSid rejects a raw SID string against a different SID' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ Test-IdentityReferenceIsSid -IdentityReference 'S-1-1-0' -Sid 'S-1-5-32-544' | Should -BeFalse+ }+ }++ It 'Test-IdentityReferenceIsSid returns false for null input' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ Test-IdentityReferenceIsSid -IdentityReference $null -Sid 'S-1-1-0' | Should -BeFalse+ }+ }++ It 'Get-WellKnownSid contains the documented mappings' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ $sids = Get-WellKnownSid+ $sids.Administrators | Should -Be 'S-1-5-32-544'+ $sids.Users | Should -Be 'S-1-5-32-545'+ $sids.Guests | Should -Be 'S-1-5-32-546'+ $sids.BackupOperators | Should -Be 'S-1-5-32-551'+ $sids.RemoteDesktopUsers | Should -Be 'S-1-5-32-555'+ $sids.System | Should -Be 'S-1-5-18'+ $sids.LocalService | Should -Be 'S-1-5-19'+ $sids.NetworkService | Should -Be 'S-1-5-20'+ $sids.Everyone | Should -Be 'S-1-1-0'+ $sids.AuthenticatedUsers | Should -Be 'S-1-5-11'+ }+ }+ }++ # SKIPPED (no parse seam): the NetApi seconds -> days conversion and the+ # TIMEQ_FOREVER (0xFFFFFFFF) -> -1 mapping live inline behind the C#+ # NetUserModalsGet interop in Get-LocalPasswordPolicy.ps1 and cannot execute+ # on non-Windows hosts. Extract a pure conversion helper first, then unskip.+ It 'converts NetApi seconds to days and TIMEQ_FOREVER (0xFFFFFFFF) to -1' -Skip {+ }+}diff --git a/tests/fixtures/auditpol-backup-de.csv b/tests/fixtures/auditpol-backup-de.csvnew file mode 100644index 0000000..fec2aba--- /dev/null+++ b/tests/fixtures/auditpol-backup-de.csv@@ -0,0 +1,14 @@+Computername,Richtlinienziel,Unterkategorie,Unterkategorie-GUID,Einbeziehungseinstellung,Ausschlusseinstellung,Einstellungswert+WSA-TEST01,System,�nderung des Sicherheitszustands,{0CCE9210-69AE-11D9-BED3-505054503030},Erfolg und Fehler,,3+WSA-TEST01,System,Systemintegrit�t,{0CCE9212-69AE-11D9-BED3-505054503030},Erfolg und Fehler,,3+WSA-TEST01,System,Anmelden,{0CCE9215-69AE-11D9-BED3-505054503030},Erfolg und Fehler,,3+WSA-TEST01,System,Abmelden,{0CCE9216-69AE-11D9-BED3-505054503030},Erfolg,,1++WSA-TEST01,System,Spezielle Anmeldung,{0CCE921B-69AE-11D9-BED3-505054503030},Erfolg,,1+WSA-TEST01,System,Dateisystem,{0CCE921D-69AE-11D9-BED3-505054503030},Keine �berwachung,,0+WSA-TEST01,System,Verwendung sensibler Rechte,{0CCE9228-69AE-11D9-BED3-505054503030},Fehler,,2+WSA-TEST01,System,Prozesserstellung,{0CCE922B-69AE-11D9-BED3-505054503030},Erfolg,,1+WSA-TEST01,System,Verzeichnisdienstzugriff,{0CCE923B-69AE-11D9-BED3-505054503030},Fehler,,2+WSA-TEST01,System,Anmeldeinformations�berpr�fung,{0CCE923F-69AE-11D9-BED3-505054503030},Erfolg und Fehler,,3+WSA-TEST01,System,Option:CrashOnAuditFail,,Erfolg,,0+WSA-TEST01,S-1-5-21-3623811015-3361044348-30300820-1001,Anmelden,{0CCE9215-69AE-11D9-BED3-505054503030},Erfolg,,1diff --git a/tests/fixtures/auditpol-backup-en.csv b/tests/fixtures/auditpol-backup-en.csvnew file mode 100644index 0000000..e28219a--- /dev/null+++ b/tests/fixtures/auditpol-backup-en.csv@@ -0,0 +1,14 @@+Machine Name,Policy Target,Subcategory,Subcategory GUID,Inclusion Setting,Exclusion Setting,Setting Value+WSA-TEST01,System,Security State Change,{0CCE9210-69AE-11D9-BED3-505054503030},Success and Failure,,3+WSA-TEST01,System,System Integrity,{0CCE9212-69AE-11D9-BED3-505054503030},Success and Failure,,3+WSA-TEST01,System,Logon,{0CCE9215-69AE-11D9-BED3-505054503030},Success and Failure,,3+WSA-TEST01,System,Logoff,{0CCE9216-69AE-11D9-BED3-505054503030},Success,,1++WSA-TEST01,System,Special Logon,{0CCE921B-69AE-11D9-BED3-505054503030},Success,,1+WSA-TEST01,System,File System,{0CCE921D-69AE-11D9-BED3-505054503030},No Auditing,,0+WSA-TEST01,System,Sensitive Privilege Use,{0CCE9228-69AE-11D9-BED3-505054503030},Failure,,2+WSA-TEST01,System,Process Creation,{0CCE922B-69AE-11D9-BED3-505054503030},Success,,1+WSA-TEST01,System,Directory Service Access,{0CCE923B-69AE-11D9-BED3-505054503030},Failure,,2+WSA-TEST01,System,Credential Validation,{0CCE923F-69AE-11D9-BED3-505054503030},Success and Failure,,3+WSA-TEST01,System,Option:CrashOnAuditFail,,Success,,0+WSA-TEST01,S-1-5-21-3623811015-3361044348-30300820-1001,Logon,{0CCE9215-69AE-11D9-BED3-505054503030},Success,,1