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
Post-review hardening for v1.6.0 (3 senior reviewers: 2 FIX-FIRST + 1 SHIP)
Okan YILDIZd7b57c8ee5a6
diff --git a/Compliance/Test-NISTCompliance.ps1 b/Compliance/Test-NISTCompliance.ps1index 50ed949..7d60c0c 100644--- a/Compliance/Test-NISTCompliance.ps1+++ b/Compliance/Test-NISTCompliance.ps1@@ -226,7 +226,7 @@ function Test-NISTCompliance {$acl = Get-Acl $logPath -ErrorAction SilentlyContinue$protected = @()if ($acl) {- $protected = @($acl.Access | Where-Object { (Test-IdentityReferenceIsSid -IdentityReference $_.IdentityReference -Sid 'S-1-5-32-545') -and $_.FileSystemRights -match "FullControl|Modify|Write" })+ $protected = @($acl.Access | Where-Object { ((Test-IdentityReferenceIsSid -IdentityReference $_.IdentityReference -Sid 'S-1-5-32-545') -or (Test-IdentityReferenceIsSid -IdentityReference $_.IdentityReference -Sid 'S-1-5-11') -or (Test-IdentityReferenceIsSid -IdentityReference $_.IdentityReference -Sid 'S-1-1-0')) -and $_.FileSystemRights -match "FullControl|Modify|Write" })}$control = [PSCustomObject]@{diff --git a/Compliance/Test-PCI-DSS.ps1 b/Compliance/Test-PCI-DSS.ps1index 662e0b6..ee44355 100644--- a/Compliance/Test-PCI-DSS.ps1+++ b/Compliance/Test-PCI-DSS.ps1@@ -328,7 +328,7 @@ function Test-PCI-DSS {Description = 'Logs must contain sufficient detail'Expected = 'File system auditing enabled'Actual = if ($null -eq $objectAuditValue) { 'Unable to determine (insufficient privileges or unsupported platform)' }- elseif ($objectAuditValue -ge 1) { "Enabled" } else { "Not configured" }+ elseif ($objectAuditValue -ge 1 -and $objectAuditValue -le 3) { "Enabled" } else { "Not configured" }Status = if ($null -eq $objectAuditValue) { 'NotApplicable' }elseif ($objectAuditValue -ge 1 -and $objectAuditValue -le 3) { 'InPlace' } else { 'NotInPlace' }Priority = 'High'diff --git a/Core/Test-SystemIntegrity.ps1 b/Core/Test-SystemIntegrity.ps1index 068007a..bda31f9 100644--- a/Core/Test-SystemIntegrity.ps1+++ b/Core/Test-SystemIntegrity.ps1@@ -48,6 +48,7 @@ function Test-SystemIntegrity {try {# Run SFC scanWrite-Host "Running System File Checker (SFC)..." -ForegroundColor Yellow+ $scanStart = Get-Date$sfcOutput = & sfc /scannow 2>&1 | Out-String$sfcExitCode = $LASTEXITCODE@@ -57,9 +58,12 @@ function Test-SystemIntegrity {$cbsLogPath = "$env:windir\Logs\CBS\CBS.log"$cbsLogAvailable = Test-Path $cbsLogPath$cannotRepairLines = @()+ $cbsTimestampsParseable = $falseif ($cbsLogAvailable) {- $cannotRepairLines = @(Get-Content $cbsLogPath -Tail 500 -ErrorAction SilentlyContinue |- Where-Object { $_ -match '\[SR\]' -and $_ -match 'Cannot repair' })+ $cbsTail = @(Get-Content $cbsLogPath -Tail 500 -ErrorAction SilentlyContinue)+ $cbsTailFilter = Select-CbsTailForCurrentScan -Lines $cbsTail -Since $scanStart+ $cbsTimestampsParseable = $cbsTailFilter.TimestampsParseable+ $cannotRepairLines = @($cbsTailFilter.Lines | Where-Object { $_ -match '\[SR\]' -and $_ -match 'Cannot repair' })}if ($sfcExitCode -ne 0) {@@ -69,6 +73,9 @@ function Test-SystemIntegrity {elseif ($cannotRepairLines.Count -gt 0 -or(-not $cbsLogAvailable -and $sfcOutput -match "Windows Resource Protection found corrupt files")) {$results.SFCResult = "Corrupt files found"+ if (-not $cbsTimestampsParseable -and $cannotRepairLines.Count -gt 0) {+ $results.SFCResult = "Corrupt files found (possible stale CBS.log entries)"+ }if ($cannotRepairLines.Count -gt 0) {$results.CorruptedFiles = $cannotRepairLines@@ -111,9 +118,12 @@ function Test-SystemIntegrity {# separate those; servicing-stack CBS.log markers ('[SR]'/'Cannot# repair', component-store corruption) are written in English$storeCorruptionLines = @()+ $dismTimestampsParseable = $falseif ($cbsLogAvailable) {- $storeCorruptionLines = @(Get-Content $cbsLogPath -Tail 500 -ErrorAction SilentlyContinue |- Where-Object { $_ -match '(?i)component store' -and $_ -match '(?i)corrupt' })+ $dismTail = @(Get-Content $cbsLogPath -Tail 500 -ErrorAction SilentlyContinue)+ $dismTailFilter = Select-CbsTailForCurrentScan -Lines $dismTail -Since $scanStart+ $dismTimestampsParseable = $dismTailFilter.TimestampsParseable+ $storeCorruptionLines = @($dismTailFilter.Lines | Where-Object { $_ -match '(?i)component store' -and $_ -match '(?i)corrupt' })}$repairable = ($storeCorruptionLines.Count -gt 0) -or ($dismCheck -match "The component store is repairable")@@ -124,6 +134,9 @@ function Test-SystemIntegrity {}elseif ($repairable) {$results.DISMResult = "Repairable corruption detected"+ if (-not $dismTimestampsParseable -and $storeCorruptionLines.Count -gt 0) {+ $results.DISMResult = "Repairable corruption detected (possible stale CBS.log entries)"+ }if ($RepairFiles) {Write-Host "Attempting DISM repair..." -ForegroundColor Yellow@@ -179,4 +192,43 @@ function Test-SystemIntegrity {end {return $results}-}\ No newline at end of file+}++function Select-CbsTailForCurrentScan {+ [CmdletBinding()]+ param(+ [Parameter()]+ [AllowEmptyCollection()]+ [string[]]$Lines = @(),++ [Parameter(Mandatory = $true)]+ [datetime]$Since+ )++ $windowStart = $Since.AddMinutes(-5)+ $currentScanLines = @()+ $timestampsParseable = $false++ foreach ($line in $Lines) {+ if ($null -eq $line) { continue }+ if ($line -match '^(?<ts>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})') {+ try {+ $lineTime = [datetime]::ParseExact($Matches.ts, 'yyyy-MM-dd HH:mm:ss', [System.Globalization.CultureInfo]::InvariantCulture)+ $timestampsParseable = $true+ if ($lineTime -ge $windowStart) {+ $currentScanLines += $line+ }+ } catch { }+ }+ }++ $filteredLines = @($Lines)+ if ($timestampsParseable) {+ $filteredLines = @($currentScanLines)+ }++ [PSCustomObject]@{+ Lines = $filteredLines+ TimestampsParseable = $timestampsParseable+ }+}diff --git a/Enterprise/Get-MultiSystemAudit.ps1 b/Enterprise/Get-MultiSystemAudit.ps1index a974be9..11efd40 100644--- a/Enterprise/Get-MultiSystemAudit.ps1+++ b/Enterprise/Get-MultiSystemAudit.ps1@@ -192,12 +192,19 @@ function Get-MultiSystemAudit {# Admin accounts$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)+ $lookupOk = $false+ try {+ $admins = @(Get-LocalGroupMember -SID ([System.Security.Principal.SecurityIdentifier]'S-1-5-32-544') -ErrorAction Stop)+ $lookupOk = $true+ } catch {+ try {+ $adminGroupName = ([System.Security.Principal.SecurityIdentifier]'S-1-5-32-544').Translate([System.Security.Principal.NTAccount]).Value.Split('\')[-1]+ $group = ([ADSI]"WinNT://./$adminGroupName,group")+ $admins = @($group.psbase.Invoke('Members'))+ $lookupOk = $true+ } catch { $lookupOk = $false }}- if (-not $adminLookupSucceeded) {+ if (-not $lookupOk) {$findings += [PSCustomObject]@{Severity = 'Low'Finding = 'Unable to determine administrator count'@@ -278,12 +285,19 @@ function Get-MultiSystemAudit {# Admin accounts$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)+ $lookupOk = $false+ try {+ $admins = @(Get-LocalGroupMember -SID ([System.Security.Principal.SecurityIdentifier]'S-1-5-32-544') -ErrorAction Stop)+ $lookupOk = $true+ } catch {+ try {+ $adminGroupName = ([System.Security.Principal.SecurityIdentifier]'S-1-5-32-544').Translate([System.Security.Principal.NTAccount]).Value.Split('\')[-1]+ $group = ([ADSI]"WinNT://./$adminGroupName,group")+ $admins = @($group.psbase.Invoke('Members'))+ $lookupOk = $true+ } catch { $lookupOk = $false }}- if (-not $adminLookupSucceeded) {+ if (-not $lookupOk) {$findings += [PSCustomObject]@{Severity = 'Low'Finding = 'Unable to determine administrator count'diff --git a/Forensics/Get-FileSystemJournal.ps1 b/Forensics/Get-FileSystemJournal.ps1index d7c0375..1048675 100644--- a/Forensics/Get-FileSystemJournal.ps1+++ b/Forensics/Get-FileSystemJournal.ps1@@ -116,9 +116,9 @@ function Get-FileSystemJournal {$fsutilExitCode = $script:FsutilLastExitCodeif ($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."+ if ($fsutilExitCode -eq 1 -or $fsutilExitCode -eq 5) {+ Write-Warning "fsutil denied access to the USN journal (exit code $fsutilExitCode); fsutil requires elevation or access denied. Rerun from an elevated prompt."+ $result.Notes += "USN journal read failed: fsutil requires elevation or access denied."}else {Write-Warning "fsutil usn readjournal failed with exit code $fsutilExitCode."@@ -232,9 +232,9 @@ function Get-FileSystemJournal {$fsutilExitCode = $script:FsutilLastExitCodeif ($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."+ if ($fsutilExitCode -eq 1 -or $fsutilExitCode -eq 5) {+ Write-Warning "fsutil denied access to volume metadata (exit code $fsutilExitCode); fsutil requires elevation or access denied. Rerun from an elevated prompt."+ $result.Notes += "MFT summary collection failed: fsutil requires elevation or access denied."}else {Write-Warning "fsutil fsinfo ntfsinfo failed with exit code $fsutilExitCode."@@ -322,9 +322,9 @@ function Get-FileSystemJournal {$rawLines = @(Get-FsutilOutput -Arguments @('usn', 'readjournal', "$drive`:"))$fsutilExitCode = $script:FsutilLastExitCodeif ($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."+ if ($fsutilExitCode -eq 1 -or $fsutilExitCode -eq 5) {+ Write-Warning "fsutil denied access to the USN journal (exit code $fsutilExitCode); fsutil requires elevation or access denied; journal comparison will be skipped."+ $result.Notes += "USN journal comparison skipped: fsutil requires elevation or access denied."}else {Write-Warning "fsutil usn readjournal failed with exit code $fsutilExitCode; journal comparison will be skipped."diff --git a/Private/Get-AuditPolicyTable.ps1 b/Private/Get-AuditPolicyTable.ps1index 6cb18d4..b6d2bd0 100644--- a/Private/Get-AuditPolicyTable.ps1+++ b/Private/Get-AuditPolicyTable.ps1@@ -78,6 +78,29 @@ $script:AuditSubcategoryMap = @{$script:AuditPolicyTableCache = $null+function Copy-AuditPolicyTable {+ <#+ .SYNOPSIS+ Clones an audit policy table (new hashtable + shallow-cloned entry objects).+ .DESCRIPTION+ Cache entries are PSCustomObjects returned by reference; without a clone a+ caller mutating .Value/.Source would corrupt the session cache. Entries+ contain only scalars, so a shallow .PSObject.Copy() per entry suffices.+ #>+ [CmdletBinding()]+ [OutputType([hashtable])]+ param(+ [Parameter(Mandatory = $true)]+ [hashtable]$Table+ )++ $copy = @{}+ foreach ($key in $Table.Keys) {+ $copy[$key] = $Table[$key].PSObject.Copy()+ }+ return $copy+}+function Get-AuditSubcategoryGuid {[CmdletBinding()][OutputType([string])]@@ -106,9 +129,10 @@ function ConvertFrom-AuditPolicyBackupCsv {row, subcategory names, inclusion text) are never interpreted: the headerrow 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).+ numeric value only (which also drops the Option: rows), and rows are+ merged per GUID: the System row wins when present, otherwise the per-user+ row for that GUID is used (per-user-only subcategories are not dropped).+ Accepts either a file -Path or raw -Lines (first line = header in both cases).#>[CmdletBinding(DefaultParameterSetName = 'Path')][OutputType([hashtable])]@@ -152,14 +176,27 @@ function ConvertFrom-AuditPolicyBackupCsv {$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 }+ # Localized Windows may localize the Target column.+ # auditpol emits the System row before the per-user rows, but the merge below+ # is order-independent: per GUID the System row wins when present, otherwise+ # the per-user row for THAT GUID is used (per-user-only subcategories must+ # not be dropped just because other GUIDs have System rows).$seen = @{}- foreach ($row in $effective) {+ $seenFromSystem = @{}+ foreach ($row in $candidates) {$key = (($row.Guid -replace '[{}]', '').Trim()).ToLowerInvariant()- if ($seen.ContainsKey($key)) { continue }+ $isSystemRow = ($row.Target -eq 'System')+ if ($seen.ContainsKey($key)) {+ # First-wins among same-target duplicates; a later System row+ # overrides an already-recorded per-user row for the same GUID.+ if ($isSystemRow -and -not $seenFromSystem[$key]) {+ $values[$key] = [int]($row.Value.Trim())+ $seenFromSystem[$key] = $true+ }+ continue+ }$seen[$key] = $true+ $seenFromSystem[$key] = $isSystemRow$values[$key] = [int]($row.Value.Trim())}return $values@@ -180,7 +217,8 @@ function Get-AuditPolicyTable {$null -ne $Subcategory -and $Subcategory.Count -gt 0)if (-not $subsetRequested -and -not $Force -and $null -ne $script:AuditPolicyTableCache) {- return $script:AuditPolicyTableCache+ # Clone on read: callers must not be able to mutate the cached entries+ return (Copy-AuditPolicyTable -Table $script:AuditPolicyTableCache)}if ($subsetRequested) {@@ -225,7 +263,7 @@ function Get-AuditPolicyTable {}if (-not $isWindowsHost) {Write-Verbose 'Get-AuditPolicyTable: not a Windows host; audit policy not applicable'- if (-not $subsetRequested) { $script:AuditPolicyTableCache = $table }+ if (-not $subsetRequested) { $script:AuditPolicyTableCache = Copy-AuditPolicyTable -Table $table }return $table}@@ -394,7 +432,9 @@ public static class AuditPolicyNative {}if (-not $subsetRequested) {- $script:AuditPolicyTableCache = $table+ # Cache keeps its own copy so caller mutations of the returned table+ # cannot corrupt the session cache+ $script:AuditPolicyTableCache = Copy-AuditPolicyTable -Table $table}return $table}diff --git a/Private/Get-LocalPasswordPolicy.ps1 b/Private/Get-LocalPasswordPolicy.ps1index e874a69..d1c5ee8 100644--- a/Private/Get-LocalPasswordPolicy.ps1+++ b/Private/Get-LocalPasswordPolicy.ps1@@ -1,4 +1,4 @@-<#+<#.SYNOPSISLocale-invariant local password/lockout policy helper (private)..DESCRIPTION@@ -7,13 +7,91 @@PasswordComplexity/ClearTextPassword (and serves as full fallback) from asecedit /export INF whose [System Access] keys are English on all locales.NEVER calls 'net accounts' (localized output).+ ConvertTo-PolicyFromModals holds all pure unit/sentinel conversion logic so+ it can be tested off-Windows (no P/Invoke, no OS calls)..NOTESStruct 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").+ ALL NetApi time fields are SECONDS: USER_MODALS_INFO_0 max/min password age+ and force-logoff, and USER_MODALS_INFO_3 lockout duration and observation+ window (Microsoft Learn: usrmod3_lockout_duration "Specifies, in seconds...";+ usrmod3_lockout_observation_window "...in seconds").+ TIMEQ_FOREVER ([uint32]::MaxValue) maps to -1 ("never" / "until admin unlocks").+ Sentinel checks MUST compare against [uint32]::MaxValue, never 0xFFFFFFFF:+ PowerShell parses the literal 0xFFFFFFFF as [int] -1, so+ '[uint32]4294967295 -eq 0xFFFFFFFF' is $false and the branch never fires.#>+function ConvertTo-PolicyFromModals {+ [CmdletBinding()]+ [OutputType([PSCustomObject])]+ param(+ [Parameter()]+ $Modals0,++ [Parameter()]+ $Modals3+ )++ $converted = [PSCustomObject]@{+ MinPasswordLength = $null+ MaxPasswordAgeDays = $null+ MinPasswordAgeDays = $null+ PasswordHistoryLength = $null+ ForceLogoffHours = $null+ LockoutThreshold = $null+ LockoutDurationMinutes = $null+ LockoutObservationWindowMinutes = $null+ }++ if ($null -ne $Modals0) {+ $converted.MinPasswordLength = [int]$Modals0.usrmod0_min_passwd_len++ # USER_MODALS_INFO_0 ages are seconds; TIMEQ_FOREVER = [uint32]::MaxValue.+ if ($Modals0.usrmod0_max_passwd_age -eq [uint32]::MaxValue) {+ $converted.MaxPasswordAgeDays = -1+ }+ else {+ $converted.MaxPasswordAgeDays = [int][math]::Round($Modals0.usrmod0_max_passwd_age / 86400)+ }+ if ($Modals0.usrmod0_min_passwd_age -eq [uint32]::MaxValue) {+ $converted.MinPasswordAgeDays = -1+ }+ else {+ $converted.MinPasswordAgeDays = [int][math]::Round($Modals0.usrmod0_min_passwd_age / 86400)+ }+ if ($Modals0.usrmod0_force_logoff -eq [uint32]::MaxValue) {+ $converted.ForceLogoffHours = -1+ }+ else {+ $converted.ForceLogoffHours = [int][math]::Round($Modals0.usrmod0_force_logoff / 3600)+ }+ $converted.PasswordHistoryLength = [int]$Modals0.usrmod0_password_hist_len+ }++ if ($null -ne $Modals3) {+ # USER_MODALS_INFO_3 lockout duration and observation window are SECONDS+ # (Microsoft Learn), so divide by 60 to report minutes. TIMEQ_FOREVER+ # ([uint32]::MaxValue) duration = "until admin unlocks" -> -1, checked+ # BEFORE the seconds-to-minutes conversion.+ # Reported even when threshold is 0 (lockout disabled).+ if ($Modals3.usrmod3_lockout_duration -eq [uint32]::MaxValue) {+ $converted.LockoutDurationMinutes = -1+ }+ else {+ $converted.LockoutDurationMinutes = [int][math]::Round($Modals3.usrmod3_lockout_duration / 60)+ }+ if ($Modals3.usrmod3_lockout_observation_window -eq [uint32]::MaxValue) {+ $converted.LockoutObservationWindowMinutes = -1+ }+ else {+ $converted.LockoutObservationWindowMinutes = [int][math]::Round($Modals3.usrmod3_lockout_observation_window / 60)+ }+ $converted.LockoutThreshold = [int]$Modals3.usrmod3_lockout_threshold+ }++ return $converted+}+function Get-LocalPasswordPolicy {[CmdletBinding()][OutputType([PSCustomObject])]@@ -49,6 +127,8 @@ function Get-LocalPasswordPolicy {# --- Primary: NetUserModalsGet levels 0 and 3 ---$netApiOk = $false+ $modals0 = $null+ $modals3 = $nullif (-not ([bool]('NetApiModals' -as [type]))) {$netApiModalsSource = @'using System;@@ -64,8 +144,8 @@ public static class NetApiModals {}[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_duration; // seconds; 0xFFFFFFFF = TIMEQ_FOREVER+ public uint usrmod3_lockout_observation_window; // seconds; 0xFFFFFFFF = TIMEQ_FOREVERpublic uint usrmod3_lockout_threshold;}[DllImport("netapi32.dll", CharSet = CharSet.Unicode)]@@ -99,28 +179,9 @@ public static class NetApiModals {if ([bool]('NetApiModals' -as [type])) {$level0Error = [uint32]0try {- $modals0 = [NetApiModals]::GetLevel0([ref]$level0Error)+ $level0 = [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+ $modals0 = $level0$netApiOk = $true}else {@@ -133,23 +194,9 @@ public static class NetApiModals {$level3Error = [uint32]0try {- $modals3 = [NetApiModals]::GetLevel3([ref]$level3Error)+ $level3 = [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+ $modals3 = $level3$netApiOk = $true}else {@@ -160,7 +207,18 @@ public static class NetApiModals {Write-Verbose "Get-LocalPasswordPolicy: NetApi level 3 failed: $($_.Exception.Message)"}- if ($netApiOk) { $policy.Source = 'NetApi' }+ if ($netApiOk) {+ $converted = ConvertTo-PolicyFromModals -Modals0 $modals0 -Modals3 $modals3+ $policy.MinPasswordLength = $converted.MinPasswordLength+ $policy.MaxPasswordAgeDays = $converted.MaxPasswordAgeDays+ $policy.MinPasswordAgeDays = $converted.MinPasswordAgeDays+ $policy.PasswordHistoryLength = $converted.PasswordHistoryLength+ $policy.ForceLogoffHours = $converted.ForceLogoffHours+ $policy.LockoutThreshold = $converted.LockoutThreshold+ $policy.LockoutDurationMinutes = $converted.LockoutDurationMinutes+ $policy.LockoutObservationWindowMinutes = $converted.LockoutObservationWindowMinutes+ $policy.Source = 'NetApi'+ }}# --- Secedit (elevated): full fallback, or merge of the two NetApi cannot see ---@@ -247,7 +305,11 @@ public static class NetApiModals {if ($seceditData.ContainsKey('ClearTextPassword') -and $seceditData['ClearTextPassword'] -match '^-?\d+$') {$policy.ClearTextPassword = ([int]$seceditData['ClearTextPassword'] -eq 1)}- if ($netApiOk) { $policy.Source = 'NetApi+Secedit' }+ # Only claim '+Secedit' when the merge actually contributed one of the+ # two fields NetApi cannot see; an INF lacking both leaves Source='NetApi'.+ if ($netApiOk -and (($null -ne $policy.PasswordComplexity) -or ($null -ne $policy.ClearTextPassword))) {+ $policy.Source = 'NetApi+Secedit'+ }}if ($policy.Source -eq 'Unavailable') {diff --git a/Private/Get-WlanProfileList.ps1 b/Private/Get-WlanProfileList.ps1index 01d29c6..4d56466 100644--- a/Private/Get-WlanProfileList.ps1+++ b/Private/Get-WlanProfileList.ps1@@ -1,4 +1,4 @@-<#+<#.SYNOPSISLocale-invariant WLAN profile list helper (private)..DESCRIPTION@@ -130,14 +130,14 @@ public static class WlanNative {Write-Verbose "Get-WlanProfileList: WLAN API unavailable (win32 $win32Error)"return $result}- foreach ($profile in $profiles) {- $flags = [uint32]$profile.Flags+ foreach ($wlanProfile in $profiles) {+ $flags = [uint32]$wlanProfile.Flags$result += [PSCustomObject]@{- Name = $profile.Name+ Name = $wlanProfile.NameFlags = $flagsIsGroupPolicy = [bool]($flags -band 1)IsPerUser = [bool]($flags -band 2)- InterfaceDescription = $profile.InterfaceDescription+ InterfaceDescription = $wlanProfile.InterfaceDescription}}}diff --git a/Private/IdentityHelpers.ps1 b/Private/IdentityHelpers.ps1index 2e53ea3..3e128f6 100644--- a/Private/IdentityHelpers.ps1+++ b/Private/IdentityHelpers.ps1@@ -1,4 +1,4 @@-<#+<#.SYNOPSISLocale-invariant identity helpers (private)..DESCRIPTION@@ -103,6 +103,13 @@ function Get-AdminGroupMembers {catch {Write-Verbose "Get-AdminGroupMembers: member Class unreadable: $($_.Exception.Message)"}+ try {+ $memberSidBytes = [byte[]]($member.GetType().InvokeMember('objectSID', 'GetProperty', $null, $member, $null))+ $memberSid = (New-Object Security.Principal.SecurityIdentifier($memberSidBytes, 0)).Value+ }+ catch {+ Write-Verbose "Get-AdminGroupMembers: member objectSID unreadable: $($_.Exception.Message)"+ }$members += [PSCustomObject]@{Name = $memberNameSID = $memberSiddiff --git a/README.md b/README.mdindex 8648ebb..b09fb38 100644--- a/README.md+++ b/README.md@@ -148,6 +148,12 @@ A single, cohesive PowerShell module that consolidates essential security functi<td>✅ Open Source</td></tr><tr>+<td><strong>Non-English Windows</strong></td>+<td>✅ Fully locale-invariant (API/GUID/SID)</td>+<td>✅ Varies</td>+<td>❌ Often parses English-only output</td>+</tr>+<tr><td><strong>Support</strong></td><td>✅ Community + Pro</td><td>✅ Vendor Support</td>@@ -236,7 +242,11 @@ WindowsSecurityAudit/│ ├── Invoke-SecurityRemediation.ps1│ └── Set-SecurityBaseline.ps1│-├── 📁 Private/ # Internal functions (hidden)+├── 📁 Private/ # Internal locale-invariant data sources (hidden)+│ ├── Get-AuditPolicyTable.ps1 # Audit policy via AuditQuerySystemPolicy/GUID CSV+│ ├── Get-LocalPasswordPolicy.ps1 # Password policy via NetUserModalsGet+│ ├── Get-WlanProfileList.ps1 # WLAN profiles via wlanapi.dll+│ └── IdentityHelpers.ps1 # SID-first group/user/ACL resolution│├── 📁 Reporting/ # Reporting (4 functions)│ ├── Get-SecurityMetrics.ps1@@ -251,8 +261,11 @@ WindowsSecurityAudit/│ ├── Invoke-IncidentResponse.ps1│ └── Send-SiemEvent.ps1│-├── 📁 tests/ # Pester tests (413 tests)-│ └── WindowsSecurityAudit.Tests.ps1+├── 📁 tests/ # Pester tests (498 tests)+│ ├── WindowsSecurityAudit.Tests.ps1 # Public API surface (425 tests)+│ ├── Smoke.Windows.Tests.ps1 # Real-Windows execution smoke tests (48)+│ ├── Locale.Regression.Tests.ps1 # EN/DE fixture equivalence + no-text-readers guard (25)+│ └── fixtures/ # auditpol EN/DE (cp1252) CSV fixtures│├── 📁 ThreatHunting/ # Threat Hunting (7 functions)│ ├── Export-AttackNavigatorLayer.ps1@@ -286,6 +299,7 @@ WindowsSecurityAudit/### Minimum Requirements- **Operating System**: Windows 10 1809+ / Windows Server 2016+- **PowerShell**: Version 5.1 (Windows PowerShell) or PowerShell 7++- **Display Language**: Any — all checks are locale-invariant since v1.6.0 (API/GUID/SID-based; correct results on Turkish, German, French and every other Windows UI language)- **Memory**: 4GB RAM (8GB recommended for enterprise scanning)- **Storage**: 1GB for module + 10GB for reports and logs- **Processor**: 2 cores minimum (4+ cores recommended)@@ -823,8 +837,8 @@ The full feature set is documented in the module tables above — this section o**Quality infrastructure:**-- 🧪 **Pester test suite** (`tests/WindowsSecurityAudit.Tests.ps1`) covering the public API surface (now 333 tests)-- ⚙️ **GitHub Actions CI** (`.github/workflows/ci.yml`) on windows-latest: PSScriptAnalyzer Error gate, module import verified under both **PowerShell 7 (pwsh)** and **Windows PowerShell 5.1**, plus the full Pester suite+- 🧪 **Pester test suite** (`tests/`) covering the public API surface plus real-Windows smoke tests and locale-regression fixtures (now 498 tests)+- ⚙️ **GitHub Actions CI** (`.github/workflows/ci.yml`) on windows-latest: PSScriptAnalyzer Error gate, module import verified under both **PowerShell 7 (pwsh)** and **Windows PowerShell 5.1**, plus the full Pester suite and a real-Windows smoke job### 📦 Already in the Toolbox (v1.0.0)diff --git a/ThreatHunting/Find-APTIndicators.ps1 b/ThreatHunting/Find-APTIndicators.ps1index d08a301..1bf7b48 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*") {+ if ($service.Name -like "*$legit*" -or $service.DisplayName -like "*$legit*") {$isWhitelisted = $truebreak}@@ -156,7 +156,7 @@ function Find-APTIndicators {# Check for actual malicious namesforeach ($malName in $knownMaliciousNames) {- if ($service.Name -match $malName) {+ if ($service.Name -match $malName -or $service.DisplayName -match $malName) {$suspiciousScore += 70$reasons += "CRITICAL: Name matches known malware: $malName"}diff --git a/WindowsSecurityAudit.psd1 b/WindowsSecurityAudit.psd1index 9ccc936..3bfd3a8 100644--- a/WindowsSecurityAudit.psd1+++ b/WindowsSecurityAudit.psd1@@ -5,7 +5,7 @@Author = 'Okan YILDIZ'CompanyName = 'okanyildiz'Copyright = '(c) 2026 Okan YILDIZ. All rights reserved.'- Description = 'Windows Security Audit Module'+ Description = 'Comprehensive Windows security audit and DFIR toolkit: 72 functions across 14 categories — threat hunting (MITRE ATT&CK mapping, lateral movement, LOLBins, data exfiltration), compliance (CIS Benchmark, NIST 800-53, PCI-DSS), vulnerability management (NVD CVE matching, CPE resolution, EOL software), forensics (artifact collection, memory dumps, USN journal, Sysmon analytics), SIEM integration (Splunk HEC, Microsoft Sentinel, CEF/NDJSON), threat intelligence feeds (abuse.ch, AbuseIPDB, MISP, TAXII/STIX), Active Directory security, hardening baselines and automated remediation. Runs on Windows PowerShell 5.1+ and PowerShell 7. Fully locale-invariant since v1.6.0: all checks use APIs, GUIDs and SIDs instead of parsing localized console output, producing correct results on non-English Windows (Turkish, German, French, ...). Zero external dependencies. Free and open source — support development: https://buymeacoffee.com/okanyildizr'PowerShellVersion = '5.1'FunctionsToExport = '*'CmdletsToExport = @()diff --git a/tests/Locale.Regression.Tests.ps1 b/tests/Locale.Regression.Tests.ps1index 59624da..8bd1795 100644--- a/tests/Locale.Regression.Tests.ps1+++ b/tests/Locale.Regression.Tests.ps1@@ -20,12 +20,12 @@to Unavailable/empty/$null instead of throwing; Test-IdentityReferenceIsSidand Get-WellKnownSid honor their SID contracts on every platform.- Two documented seams do NOT exist yet and their tests are skipped on purpose:+ One documented seam does NOT exist yet and its test is 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.+ honest-unknown on localized inclusion text). The NetApi seconds->days /+ TIMEQ_FOREVER (0xFFFFFFFF) -> -1 conversion seam now EXISTS as the pure+ ConvertTo-PolicyFromModals helper in Private/Get-LocalPasswordPolicy.ps1 and+ is covered by the tests below.The module targets Windows PowerShell 5.1+, so only APIs available in5.1 are used here (no null-coalescing/ternary operators, no ForEach-Object -Parallel).@@ -37,36 +37,51 @@ BeforeDiscovery {# 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.+ # Every regex carries BadSamples: representative offending snippets the regex+ # MUST match, pinned by the guard self-test below so a regex can never+ # silently rot into a dead guard.$script:ForbiddenReaders = @(@{Name = "raw 'auditpol /get' text parsing (localized Inclusion columns)"Regex = 'auditpol(\.exe)?\s+/get\b'Grandfathered = @()+ BadSamples = @(+ '$output = auditpol /get /category:* /r'+ '$output = auditpol.exe /get /subcategory:"Logon"'+ )}@{Name = "'Minimum password length' label parsing of 'net accounts' output"- Regex = 'Select-String\s+["''][^"'']*[Pp]assword\s+[Ll]ength'+ Regex = 'Select-String\b(\s+-Pattern)?\s+["''][^"'']*[Pp]assword\s+[Ll]ength'Grandfathered = @()+ BadSamples = @(+ 'Select-String ''Minimum password length'''+ 'Select-String -Pattern ''Minimum password length'''+ )}@{Name = 'name-based Get-LocalGroupMember -Group with a string literal'Regex = 'Get-LocalGroupMember\b[^\n|]*-Group\s+["'']'Grandfathered = @()+ BadSamples = @('Get-LocalGroupMember -Group ''Administrators''')}@{Name = 'name-based Get-LocalUser -Name Guest/Administrator'Regex = 'Get-LocalUser\b[^\n|]*-Name\s+["''](Guest|Administrator)["'']'Grandfathered = @()+ BadSamples = @('Get-LocalUser -Name ''Guest''')}@{Name = 'string identities (Everyone / NT AUTHORITY\SYSTEM / BUILTIN\Administrators) in FileSystemAccessRule'Regex = 'FileSystemAccessRule\(\s*["''](Everyone|NT AUTHORITY\\SYSTEM|BUILTIN\\Administrators)["'']'Grandfathered = @()+ BadSamples = @('New-Object System.Security.AccessControl.FileSystemAccessRule(''Everyone'', ''FullControl'', ''Allow'')')}@{Name = "IdentityReference matched against '(Everyone' style name patterns"Regex = 'IdentityReference\b[^\n]*-match\s+["''][^"'']*\(?Everyone'Grandfathered = @()+ BadSamples = @('$rule.IdentityReference -match ''^(Everyone|BUILTIN)''')})}@@ -81,6 +96,20 @@ BeforeAll {Import-Module -Name $script:ModulePath -Force -DisableNameChecking+ # Invocation-context guard for 'net accounts' reads (leading = | ; { ( & or+ # line start). Hardening/Set-SecurityBaseline.ps1 is allowed (legit /set writes).+ # Defined in BeforeAll (not BeforeDiscovery): run-phase script state is fresh,+ # so runtime references from It blocks need run-phase initialization.+ $script:NetAccountsGuard = @{+ Name = "'net accounts' invocation outside Hardening/Set-SecurityBaseline.ps1"+ Regex = '(?m)(=|\||;|\{|\(|&)\s*net(\.exe)?\s+accounts\b|^[ \t]*net(\.exe)?\s+accounts\b'+ Allowed = @('Hardening/Set-SecurityBaseline.ps1')+ BadSamples = @(+ '$x = net accounts'+ '$x = & net accounts'+ )+ }+$script:IsWindowsHost = $falsetry {$script:IsWindowsHost = [System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform(@@ -192,6 +221,60 @@ Describe 'ConvertFrom-AuditPolicyBackupCsv fixture equivalence (WinLogKit PR #58}}+ It 'merges per-GUID: a per-user-only GUID survives next to a GUID where the System row wins' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ $lines = @(+ 'Machine Name,Policy Target,Subcategory,Subcategory GUID,Inclusion Setting,Exclusion Setting,Setting Value'+ 'WSA-TEST01,System,Logon,{0CCE9215-69AE-11D9-BED3-505054503030},Success and Failure,,3'+ 'WSA-TEST01,S-1-5-21-3623811015-3361044348-30300820-1001,Logoff,{0CCE9216-69AE-11D9-BED3-505054503030},Success,,1'+ )+ $map = ConvertFrom-AuditPolicyBackupCsv -Lines $lines+ $map.Count | Should -Be 2 -Because 'a GUID with only per-user rows must not be dropped just because another GUID has a System row'+ $map['0cce9215-69ae-11d9-bed3-505054503030'] | Should -Be 3 -Because 'the System row wins for Logon'+ $map['0cce9216-69ae-11d9-bed3-505054503030'] | Should -Be 1 -Because 'Logoff has only the per-user row, so it is the source'+ }+ }++ It 'lets the System row win even when the per-user row comes first (reordered rows)' {+ 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'+ 'WSA-TEST01,System,Logon,{0CCE9215-69AE-11D9-BED3-505054503030},Success and Failure,,3'+ )+ $map = ConvertFrom-AuditPolicyBackupCsv -Lines $lines+ $map.Count | Should -Be 1+ $map['0cce9215-69ae-11d9-bed3-505054503030'] | Should -Be 3 -Because 'row order must not matter: System wins regardless of position'+ }+ }++ It 'drops rows whose Setting Value is outside the 0-3 range' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ $lines = @(+ 'Machine Name,Policy Target,Subcategory,Subcategory GUID,Inclusion Setting,Exclusion Setting,Setting Value'+ 'WSA-TEST01,System,Logon,{0CCE9215-69AE-11D9-BED3-505054503030},Success,,5'+ 'WSA-TEST01,System,Logoff,{0CCE9216-69AE-11D9-BED3-505054503030},Success,,1'+ )+ $map = ConvertFrom-AuditPolicyBackupCsv -Lines $lines+ $map.Count | Should -Be 1 -Because "'5' is not a valid audit setting value (0-3) and the row must be rejected"+ $map.ContainsKey('0cce9215-69ae-11d9-bed3-505054503030') | Should -BeFalse+ $map['0cce9216-69ae-11d9-bed3-505054503030'] | Should -Be 1+ }+ }++ It 'lets the first System row win when duplicate System rows exist for one GUID' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ $lines = @(+ 'Machine Name,Policy Target,Subcategory,Subcategory GUID,Inclusion Setting,Exclusion Setting,Setting Value'+ 'WSA-TEST01,System,Logon,{0CCE9215-69AE-11D9-BED3-505054503030},Success and Failure,,3'+ 'WSA-TEST01,System,Logon,{0CCE9215-69AE-11D9-BED3-505054503030},Success,,1'+ )+ $map = ConvertFrom-AuditPolicyBackupCsv -Lines $lines+ $map.Count | Should -Be 1+ $map['0cce9215-69ae-11d9-bed3-505054503030'] | Should -Be 3 -Because 'the first System row for a GUID wins'+ }+ }+It 'accepts raw -Lines with the same result as -Path' {InModuleScope -ModuleName $script:ModuleName -ArgumentList $script:EnFixture -ScriptBlock {param($enFixture)@@ -237,10 +320,8 @@ Describe 'No locale-fragile text readers (static regression guard)' {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- )+ $regex = $script:NetAccountsGuard.Regex+ $allowed = $script:NetAccountsGuard.Allowed$offenders = @(foreach ($file in $script:GuardedFiles) {if ($allowed -contains $file.RelativePath) { continue }@@ -250,6 +331,18 @@ Describe 'No locale-fragile text readers (static regression guard)' {)$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 ', '))}++ It 'guard regex still matches its representative bad samples: <Name>' -ForEach $script:ForbiddenReaders {+ foreach ($sample in $_.BadSamples) {+ $sample -match $_.Regex | Should -BeTrue -Because "a guard regex that no longer matches its own bad sample is a dead guard (sample: $sample)"+ }+ }++ It "guard regex still matches its representative bad samples: net accounts invocation" {+ foreach ($sample in $script:NetAccountsGuard.BadSamples) {+ $sample -match $script:NetAccountsGuard.Regex | Should -BeTrue -Because "a guard regex that no longer matches its own bad sample is a dead guard (sample: $sample)"+ }+ }}Describe 'Private helper contract and degradation' {@@ -339,12 +432,160 @@ Describe 'Private helper contract and degradation' {$sids.AuthenticatedUsers | Should -Be 'S-1-5-11'}}++ It 'Test-IdentityReferenceIsSid matches a SecurityIdentifier object input against its SID string' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ # On non-Windows .NET the whole System.Security.Principal.Windows+ # surface (including every SecurityIdentifier constructor) throws+ # PlatformNotSupportedException, so the object cannot be built there;+ # the assertion itself runs wherever the type is constructible.+ $sidObject = $null+ try {+ $sidObject = [System.Security.Principal.SecurityIdentifier]'S-1-5-32-544'+ }+ catch {+ Set-ItResult -Skipped -Because 'SecurityIdentifier cannot be constructed on this platform (Windows Principal functionality is not supported)'+ return+ }+ Test-IdentityReferenceIsSid -IdentityReference $sidObject -Sid 'S-1-5-32-544' | Should -BeTrue+ Test-IdentityReferenceIsSid -IdentityReference $sidObject -Sid 'S-1-1-0' | Should -BeFalse+ }+ }+ }++ Context 'Get-AuditSubcategoryGuid name resolution' {+ It 'resolves subcategory names case-insensitively' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ Get-AuditSubcategoryGuid -Name 'logon' | Should -Be '{0CCE9215-69AE-11D9-BED3-505054503030}'+ Get-AuditSubcategoryGuid -Name 'Logon' | Should -Be '{0CCE9215-69AE-11D9-BED3-505054503030}'+ }+ }++ It 'returns null for an unknown subcategory name' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ Get-AuditSubcategoryGuid -Name 'Not A Real Subcategory' | Should -BeNullOrEmpty+ }+ }+ }++ Context 'Get-AuditPolicyTable subset selection and cache behavior' {+ It 'returns exactly the requested subcategories' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ $table = Get-AuditPolicyTable -Subcategory 'Logon', 'Logoff'+ $table.Count | Should -Be 2+ $table.ContainsKey('0cce9215-69ae-11d9-bed3-505054503030') | Should -BeTrue+ $table.ContainsKey('0cce9216-69ae-11d9-bed3-505054503030') | Should -BeTrue+ }+ }++ It 'skips unknown names in -Subcategory' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ $table = Get-AuditPolicyTable -Subcategory 'Logon', 'Logoff', 'Not A Real Subcategory'+ $table.Count | Should -Be 2 -Because 'unknown subcategory names are skipped, not fatal'+ }+ }++ It 'serves equivalent content from the cache on repeated calls without -Force' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ $first = Get-AuditPolicyTable+ $second = Get-AuditPolicyTable+ $second.Count | Should -Be $first.Count+ $firstKeys = @($first.Keys | Sort-Object)+ (@($second.Keys | Sort-Object) -join ',') | Should -Be ($firstKeys -join ',')+ foreach ($key in $firstKeys) {+ $second[$key].Value | Should -Be $first[$key].Value+ $second[$key].Success | Should -Be $first[$key].Success+ $second[$key].Failure | Should -Be $first[$key].Failure+ $second[$key].Source | Should -Be $first[$key].Source+ }+ }+ }++ It 'never lets callers corrupt the cache (clone-on-read)' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ $table = Get-AuditPolicyTable+ $entry = $table['0cce9215-69ae-11d9-bed3-505054503030']+ $originalValue = $entry.Value+ $entry.Value = 999+ $fresh = Get-AuditPolicyTable+ $fresh['0cce9215-69ae-11d9-bed3-505054503030'].Value |+ Should -Be $originalValue -Because 'mutating a returned table must not corrupt the cached table'+ # Hygiene: rebuild the cache so no later test inherits state from this one+ $null = Get-AuditPolicyTable -Force+ }+ }+ }++ Context 'Get-LocalUserByRid RID suffix matching' {+ It 'does not match a user whose SID merely ends with the RID digits (RID 500 vs ...-1500)' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ # Get-LocalUser does not exist on non-Windows hosts and Pester can+ # only mock existing commands, so define a stub first. The SID is a+ # duck-typed .Value holder because SecurityIdentifier constructors+ # throw PlatformNotSupportedException off Windows; the code under+ # test only ever touches $_.SID.Value.+ function Get-LocalUser { }+ Mock Get-LocalUser {+ @(+ [PSCustomObject]@{+ Name = 'Rid1500User'+ SID = [PSCustomObject]@{ Value = 'S-1-5-21-3623811015-3361044348-30300820-1500' }+ Enabled = $true+ Description = ''+ }+ )+ }+ Get-LocalUserByRid -Rid 500 | Should -BeNullOrEmpty -Because 'SID ...-1500 must not match RID 500 (suffix match includes the dash)'+ $hit = Get-LocalUserByRid -Rid 1500+ $hit.Name | Should -Be 'Rid1500User' -Because 'the mock wiring must actually be exercised (positive control)'+ }+ }}- # 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 {+ Context 'ConvertTo-PolicyFromModals pure conversion seam' {+ It 'converts NetApi seconds to days/hours/minutes and TIMEQ_FOREVER (0xFFFFFFFF) to -1' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ $modals0 = @{+ usrmod0_min_passwd_len = [uint32]7+ usrmod0_max_passwd_age = [uint32]3628800 # 42 days, in seconds+ usrmod0_min_passwd_age = [uint32]86400 # 1 day, in seconds+ usrmod0_force_logoff = [uint32]::MaxValue # TIMEQ_FOREVER+ usrmod0_password_hist_len = [uint32]5+ }+ $modals3 = @{+ usrmod3_lockout_duration = [uint32]1800 # 30 minutes, in seconds+ usrmod3_lockout_observation_window = [uint32]600 # 10 minutes, in seconds+ usrmod3_lockout_threshold = [uint32]5+ }+ $policy = ConvertTo-PolicyFromModals -Modals0 $modals0 -Modals3 $modals3+ $policy.MinPasswordLength | Should -Be 7+ $policy.MaxPasswordAgeDays | Should -Be 42+ $policy.MinPasswordAgeDays | Should -Be 1+ $policy.PasswordHistoryLength | Should -Be 5+ $policy.ForceLogoffHours | Should -Be -1 -Because 'TIMEQ_FOREVER (0xFFFFFFFF) maps to -1'+ $policy.LockoutThreshold | Should -Be 5+ $policy.LockoutDurationMinutes | Should -Be 30+ $policy.LockoutObservationWindowMinutes | Should -Be 10+ }+ }++ It 'maps a TIMEQ_FOREVER lockout duration to -1 and null Modals0 to null fields' {+ InModuleScope -ModuleName $script:ModuleName -ScriptBlock {+ $modals3 = @{+ usrmod3_lockout_duration = [uint32]::MaxValue # TIMEQ_FOREVER: until admin unlocks+ usrmod3_lockout_observation_window = [uint32]600+ usrmod3_lockout_threshold = [uint32]0+ }+ $policy = ConvertTo-PolicyFromModals -Modals0 $null -Modals3 $modals3+ $policy.LockoutDurationMinutes | Should -Be -1+ $policy.LockoutObservationWindowMinutes | Should -Be 10+ $policy.LockoutThreshold | Should -Be 0+ $policy.MinPasswordLength | Should -BeNullOrEmpty+ $policy.MaxPasswordAgeDays | Should -BeNullOrEmpty+ $policy.MinPasswordAgeDays | Should -BeNullOrEmpty+ $policy.PasswordHistoryLength | Should -BeNullOrEmpty+ $policy.ForceLogoffHours | Should -BeNullOrEmpty+ }+ }}}