Skip to content

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

Fix ~100 strict-mode/runtime bugs, add 4 functions, tests and CI (v1.1.0)

Okan YILDIZ1fe072bce41b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..66c2869
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,66 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+
+jobs:
+ lint:
+ name: Lint and test
+ # The module only works on Windows (CIM/WMI, event logs, registry), so the
+ # whole job runs on windows-latest. The tests themselves are cross-platform.
+ runs-on: windows-latest
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Install Pester and PSScriptAnalyzer
+ shell: pwsh
+ run: |
+ Set-PSRepository -Name PSGallery -InstallationPolicy Trusted
+ Install-Module -Name Pester -MinimumVersion 5.5.0 -Force -Scope CurrentUser -SkipPublisherCheck
+ Install-Module -Name PSScriptAnalyzer -Force -Scope CurrentUser
+
+ - name: PSScriptAnalyzer (zero Error-level findings allowed)
+ shell: pwsh
+ run: |
+ $results = @(Invoke-ScriptAnalyzer -Path . -Recurse -Severity Error)
+ if ($results.Count -gt 0) {
+ $results | Format-Table RuleName, Severity, ScriptName, Line, Message -AutoSize |
+ Out-String -Width 200 | Write-Host
+ Write-Error "PSScriptAnalyzer reported $($results.Count) Error-level finding(s)."
+ exit 1
+ }
+ Write-Host "PSScriptAnalyzer: 0 Error-level findings."
+
+ - name: Import module (PowerShell 7)
+ shell: pwsh
+ run: |
+ Import-Module ./WindowsSecurityAudit.psd1 -Force -ErrorAction Stop
+ $exported = @(Get-Command -Module WindowsSecurityAudit -CommandType Function)
+ Write-Host "Imported OK, $($exported.Count) functions exported."
+ if ($exported.Count -eq 0) { Write-Error "No functions were exported."; exit 1 }
+
+ - name: Import module (Windows PowerShell 5.1)
+ # The module targets Windows PowerShell 5.1+. 'shell: powershell' is the
+ # Windows PowerShell 5.1 desktop edition shipped with the runner, so this
+ # step proves the module still loads under 5.1 (Set-StrictMode -Version Latest
+ # and 5.1-only APIs are exercised here, not under pwsh 7).
+ shell: powershell
+ run: |
+ Import-Module ./WindowsSecurityAudit.psd1 -Force -ErrorAction Stop
+ $exported = @(Get-Command -Module WindowsSecurityAudit -CommandType Function)
+ Write-Host "Imported OK under $($PSVersionTable.PSVersion), $($exported.Count) functions exported."
+ if ($exported.Count -eq 0) { Write-Error "No functions were exported."; exit 1 }
+
+ - name: Run Pester tests
+ shell: pwsh
+ run: |
+ $config = New-PesterConfiguration
+ $config.Run.Path = './tests'
+ $config.Run.Exit = $true # exit code 1 when any test fails
+ $config.Output.Verbosity = 'Detailed'
+ Invoke-Pester -Configuration $config
diff --git a/ActiveDirectory/Find-ADBackdoors.ps1 b/ActiveDirectory/Find-ADBackdoors.ps1
index f26c17d..f5d9c77 100644
--- a/ActiveDirectory/Find-ADBackdoors.ps1
+++ b/ActiveDirectory/Find-ADBackdoors.ps1
@@ -106,7 +106,9 @@ function Find-ADBackdoors {
$group = Get-ADGroup -Filter "Name -eq '$groupName'" -Server $Domain -ErrorAction SilentlyContinue
if ($group) {
$members = Get-ADGroupMember -Identity $group -Recursive -Server $Domain -ErrorAction SilentlyContinue
- $legitimatePrivilegedUsers += $members.SamAccountName
+ if ($members) {
+ $legitimatePrivilegedUsers += $members.SamAccountName
+ }
}
}
catch {
@@ -164,7 +166,11 @@ function Find-ADBackdoors {
if ($ace.ObjectType -in $dcsyncRights) {
# Resolve SID to account
try {
- $account = Get-ADObject -Filter "objectSid -eq '$($ace.IdentityReference)'" -Server $Domain -ErrorAction SilentlyContinue
+ $aceSid = $ace.IdentityReference
+ if ($aceSid -isnot [System.Security.Principal.SecurityIdentifier]) {
+ $aceSid = $aceSid.Translate([System.Security.Principal.SecurityIdentifier])
+ }
+ $account = Get-ADObject -Filter "objectSid -eq '$aceSid'" -Server $Domain -ErrorAction SilentlyContinue
if ($account) {
# Check if it's a legitimate DC or admin account
diff --git a/ActiveDirectory/Find-ADVulnerabilities.ps1 b/ActiveDirectory/Find-ADVulnerabilities.ps1
index c84ab4c..de42e62 100644
--- a/ActiveDirectory/Find-ADVulnerabilities.ps1
+++ b/ActiveDirectory/Find-ADVulnerabilities.ps1
@@ -256,7 +256,7 @@ function Find-ADVulnerabilities {
Write-Host " [!] $($user.SamAccountName) has reversible encryption enabled" -ForegroundColor Red
}
- if (-not $results.Recommendations -contains "Enforce strong password policies") {
+ if ($results.Recommendations -notcontains "Enforce strong password policies") {
$results.Recommendations += "Enforce strong password policies (min 12 chars, complexity enabled)"
$results.Recommendations += "Regular password rotation for privileged accounts"
$results.Recommendations += "Disable reversible encryption for all accounts"
diff --git a/ActiveDirectory/Get-ADPasswordPolicy.ps1 b/ActiveDirectory/Get-ADPasswordPolicy.ps1
index 73e150e..40e148d 100644
--- a/ActiveDirectory/Get-ADPasswordPolicy.ps1
+++ b/ActiveDirectory/Get-ADPasswordPolicy.ps1
@@ -230,7 +230,7 @@ function Get-ADPasswordPolicy {
MaxPasswordAge = $pso.MaxPasswordAge.Days
LockoutThreshold = $pso.LockoutThreshold
AppliesTo = $appliesTo.Count
- AppliesToObjects = $appliesTo.Name -join ', '
+ AppliesToObjects = if ($appliesTo) { $appliesTo.Name -join ', ' } else { 'None' }
}
$analysis.FineGrainedPolicies += $psoInfo
diff --git a/ActiveDirectory/Test-ADSecurityPosture.ps1 b/ActiveDirectory/Test-ADSecurityPosture.ps1
index 8488ef6..a3472a1 100644
--- a/ActiveDirectory/Test-ADSecurityPosture.ps1
+++ b/ActiveDirectory/Test-ADSecurityPosture.ps1
@@ -308,8 +308,8 @@ function Test-ADSecurityPosture {
)
Write-Host "`nCategory Scores:" -ForegroundColor Cyan
- foreach ($category in $assessment.Categories.PSObject.Properties) {
- if ($category.Value.Score -ne $null) {
+ foreach ($category in $assessment.Categories.GetEnumerator()) {
+ if ($null -ne $category.Value.Score) {
$percentage = [math]::Round(($category.Value.Score / $category.Value.MaxScore) * 100, 0)
Write-Host " $($category.Name): $percentage%" -ForegroundColor White
}
diff --git a/Analysis/Get-EventLogAnalysis.ps1 b/Analysis/Get-EventLogAnalysis.ps1
index 7cb11f0..b7d1134 100644
--- a/Analysis/Get-EventLogAnalysis.ps1
+++ b/Analysis/Get-EventLogAnalysis.ps1
@@ -125,7 +125,9 @@ function Get-EventLogAnalysis {
# Check if this is a critical event ID
$isCritical = $criticalEventIDs.ContainsKey($event.Id)
-
+
+ $eventMessage = try { $event.Message } catch { $null }
+
$eventObj = [PSCustomObject]@{
TimeCreated = $event.TimeCreated
LogName = $event.LogName
@@ -138,7 +140,7 @@ function Get-EventLogAnalysis {
4 { 'Information' }
default { 'Unknown' }
}
- Message = $event.Message
+ Message = $eventMessage
Description = if ($isCritical) { $criticalEventIDs[$event.Id] } else { $null }
IsCritical = $isCritical
}
diff --git a/Analysis/Get-FileSystemAnalysis.ps1 b/Analysis/Get-FileSystemAnalysis.ps1
index de551f7..819ea05 100644
--- a/Analysis/Get-FileSystemAnalysis.ps1
+++ b/Analysis/Get-FileSystemAnalysis.ps1
@@ -134,7 +134,7 @@ function Get-FileSystemAnalysis {
# Check 2: Malicious file names
foreach ($malName in $maliciousNames) {
- if ($file.Name -match $malName) {
+ if ($file.Name -match [regex]::Escape($malName)) {
$isSuspicious = $true
$reasons += "Matches known malicious filename: $malName"
break
diff --git a/Analysis/Get-MemoryAnalysis.ps1 b/Analysis/Get-MemoryAnalysis.ps1
index 9fc96e0..8c49e59 100644
--- a/Analysis/Get-MemoryAnalysis.ps1
+++ b/Analysis/Get-MemoryAnalysis.ps1
@@ -139,7 +139,7 @@ function Get-MemoryAnalysis {
$processAnalysis.Modules += [PSCustomObject]@{
Name = $moduleName
Path = $modulePath
- Size = [math]::Round($module.Size / 1KB, 2)
+ Size = [math]::Round($module.ModuleMemorySize / 1KB, 2)
Suspicious = $isSuspicious
}
}
diff --git a/Analysis/Get-RegistryAnalysis.ps1 b/Analysis/Get-RegistryAnalysis.ps1
index 4ed6daf..8729279 100644
--- a/Analysis/Get-RegistryAnalysis.ps1
+++ b/Analysis/Get-RegistryAnalysis.ps1
@@ -88,23 +88,29 @@ function Get-RegistryAnalysis {
# Analyze LSA settings
if ($path -match 'Lsa$') {
+ $restrictAnonymous = if ($null -ne $properties.PSObject.Properties['RestrictAnonymous']) { $properties.RestrictAnonymous } else { $null }
+ $limitBlankPasswordUse = if ($null -ne $properties.PSObject.Properties['LimitBlankPasswordUse']) { $properties.LimitBlankPasswordUse } else { $null }
+ $noLMHash = if ($null -ne $properties.PSObject.Properties['NoLMHash']) { $properties.NoLMHash } else { $null }
+ $disableDomainCreds = if ($null -ne $properties.PSObject.Properties['DisableDomainCreds']) { $properties.DisableDomainCreds } else { $null }
+ $everyoneIncludesAnonymous = if ($null -ne $properties.PSObject.Properties['EveryoneIncludesAnonymous']) { $properties.EveryoneIncludesAnonymous } else { $null }
+
$keyObj = [PSCustomObject]@{
Path = $path
Category = $criticalPaths[$path]
- RestrictAnonymous = $properties.RestrictAnonymous
- LimitBlankPasswordUse = $properties.LimitBlankPasswordUse
- NoLMHash = $properties.NoLMHash
- DisableDomainCreds = $properties.DisableDomainCreds
- EveryoneIncludesAnonymous = $properties.EveryoneIncludesAnonymous
+ RestrictAnonymous = $restrictAnonymous
+ LimitBlankPasswordUse = $limitBlankPasswordUse
+ NoLMHash = $noLMHash
+ DisableDomainCreds = $disableDomainCreds
+ EveryoneIncludesAnonymous = $everyoneIncludesAnonymous
Findings = @()
}
# Check for security issues
- if ($properties.RestrictAnonymous -ne 1) {
+ if ($restrictAnonymous -ne 1) {
$keyObj.Findings += "RestrictAnonymous not set to secure value"
$results.Statistics.SuspiciousFindings++
}
- if ($properties.LimitBlankPasswordUse -ne 1) {
+ if ($limitBlankPasswordUse -ne 1) {
$keyObj.Findings += "Blank passwords not restricted"
$results.Statistics.SuspiciousFindings++
}
@@ -114,7 +120,7 @@ function Get-RegistryAnalysis {
# Analyze WDigest settings
if ($path -match 'WDigest$') {
- $useLogonCredential = $properties.UseLogonCredential
+ $useLogonCredential = if ($null -ne $properties.PSObject.Properties['UseLogonCredential']) { $properties.UseLogonCredential } else { $null }
if ($useLogonCredential -eq 1) {
$results.SecuritySettings += [PSCustomObject]@{
Path = $path
@@ -129,21 +135,26 @@ function Get-RegistryAnalysis {
# Analyze UAC settings
if ($path -match 'Policies\\System$') {
+ $enableLUA = if ($null -ne $properties.PSObject.Properties['EnableLUA']) { $properties.EnableLUA } else { $null }
+ $consentPromptBehaviorAdmin = if ($null -ne $properties.PSObject.Properties['ConsentPromptBehaviorAdmin']) { $properties.ConsentPromptBehaviorAdmin } else { $null }
+ $enableInstallerDetection = if ($null -ne $properties.PSObject.Properties['EnableInstallerDetection']) { $properties.EnableInstallerDetection } else { $null }
+ $promptOnSecureDesktop = if ($null -ne $properties.PSObject.Properties['PromptOnSecureDesktop']) { $properties.PromptOnSecureDesktop } else { $null }
+
$keyObj = [PSCustomObject]@{
Path = $path
Category = 'User Account Control'
- EnableLUA = $properties.EnableLUA
- ConsentPromptBehaviorAdmin = $properties.ConsentPromptBehaviorAdmin
- EnableInstallerDetection = $properties.EnableInstallerDetection
- PromptOnSecureDesktop = $properties.PromptOnSecureDesktop
+ EnableLUA = $enableLUA
+ ConsentPromptBehaviorAdmin = $consentPromptBehaviorAdmin
+ EnableInstallerDetection = $enableInstallerDetection
+ PromptOnSecureDesktop = $promptOnSecureDesktop
Findings = @()
}
- if ($properties.EnableLUA -ne 1) {
+ if ($enableLUA -ne 1) {
$keyObj.Findings += "UAC is disabled"
$results.Statistics.SuspiciousFindings++
}
- if ($properties.PromptOnSecureDesktop -ne 1) {
+ if ($promptOnSecureDesktop -ne 1) {
$keyObj.Findings += "UAC not prompting on secure desktop"
}
@@ -212,19 +223,21 @@ function Get-RegistryAnalysis {
try {
$serviceProps = Get-ItemProperty -Path $service.PSPath -ErrorAction SilentlyContinue
- if ($serviceProps.ImagePath) {
+ $imagePath = if ($null -ne $serviceProps -and $null -ne $serviceProps.PSObject.Properties['ImagePath']) { $serviceProps.ImagePath } else { $null }
+
+ if ($imagePath) {
$isSuspicious = $false
$reasons = @()
# Check for suspicious service paths
- if ($serviceProps.ImagePath -match '(temp|appdata|users\\public)') {
+ if ($imagePath -match '(temp|appdata|users\\public)') {
$isSuspicious = $true
$reasons += "Service running from suspicious location"
}
# Check for services without proper quotes
- if ($serviceProps.ImagePath -match '^[A-Z]:\\.*\s.*\.exe' -and
- $serviceProps.ImagePath -notmatch '^"') {
+ if ($imagePath -match '^[A-Z]:\\.*\s.*\.exe' -and
+ $imagePath -notmatch '^"') {
$isSuspicious = $true
$reasons += "Unquoted service path with spaces (potential privilege escalation)"
}
@@ -232,8 +245,8 @@ function Get-RegistryAnalysis {
if ($isSuspicious) {
$results.ServiceKeys += [PSCustomObject]@{
ServiceName = $service.PSChildName
- ImagePath = $serviceProps.ImagePath
- Start = $serviceProps.Start
+ ImagePath = $imagePath
+ Start = if ($null -ne $serviceProps.PSObject.Properties['Start']) { $serviceProps.Start } else { $null }
Reasons = $reasons -join '; '
}
$results.Statistics.SuspiciousFindings++
@@ -263,12 +276,12 @@ function Get-RegistryAnalysis {
# Check for overly permissive access
foreach ($access in $acl.Access) {
if ($access.IdentityReference -match '(Everyone|Users|Authenticated Users)' -and
- $access.FileSystemRights -match '(FullControl|Write|Modify)') {
+ $access.RegistryRights -match '(FullControl|Write|Modify)') {
$results.PermissionIssues += [PSCustomObject]@{
Path = $keyPath
Identity = $access.IdentityReference
- Rights = $access.FileSystemRights
+ Rights = $access.RegistryRights
AccessControlType = $access.AccessControlType
Severity = 'High'
}
diff --git a/Compliance/Export-ComplianceEvidence.ps1 b/Compliance/Export-ComplianceEvidence.ps1
index 1090ea3..28a0866 100644
--- a/Compliance/Export-ComplianceEvidence.ps1
+++ b/Compliance/Export-ComplianceEvidence.ps1
@@ -398,6 +398,8 @@ function Export-ComplianceEvidence {
# Generate Chain of Custody
$custodyPath = Join-Path $directories.Metadata "Chain_of_Custody.txt"
+ $ipInfo = Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object {$_.InterfaceAlias -notlike '*Loopback*'} | Select-Object -First 1
+ $ipAddress = if ($ipInfo) { $ipInfo.IPAddress } else { 'N/A' }
$custody = @"
CHAIN OF CUSTODY DOCUMENTATION
================================
@@ -409,7 +411,7 @@ Time Zone: $([System.TimeZoneInfo]::Local.DisplayName)
SYSTEM INFORMATION:
Computer Name: $($env:COMPUTERNAME)
Domain: $($env:USERDOMAIN)
-IP Address: $((Get-NetIPAddress -AddressFamily IPv4 | Where-Object {$_.InterfaceAlias -notlike '*Loopback*'} | Select-Object -First 1).IPAddress)
+IP Address: $ipAddress
Operating System: $((Get-CimInstance Win32_OperatingSystem).Caption)
EVIDENCE COLLECTOR:
diff --git a/Compliance/Get-ComplianceReport.ps1 b/Compliance/Get-ComplianceReport.ps1
index 332b515..8e93452 100644
--- a/Compliance/Get-ComplianceReport.ps1
+++ b/Compliance/Get-ComplianceReport.ps1
@@ -62,6 +62,7 @@ function Get-ComplianceReport {
CrossFrameworkAnalysis = @()
RemediationPriorities = @()
Recommendations = @()
+ Evidence = @()
}
}
@@ -85,6 +86,7 @@ function Get-ComplianceReport {
NotApplicable = $cisResult.Summary.NotApplicable
CriticalGaps = @($cisResult.Controls | Where-Object { $_.Status -eq 'Fail' -and $_.Severity -eq 'Critical' }).Count
HighGaps = @($cisResult.Controls | Where-Object { $_.Status -eq 'Fail' -and $_.Severity -eq 'High' }).Count
+ MediumGaps = @($cisResult.Controls | Where-Object { $_.Status -eq 'Fail' -and $_.Severity -eq 'Medium' }).Count
Controls = $cisResult.Controls
Status = if ($cisResult.Summary.CompliancePercentage -ge 80) { 'Pass' }
elseif ($cisResult.Summary.CompliancePercentage -ge 60) { 'Marginal' }
@@ -121,6 +123,7 @@ function Get-ComplianceReport {
NotApplicable = $nistResult.Summary.NotApplicable
CriticalGaps = @($nistResult.Controls | Where-Object { $_.Status -eq 'NonCompliant' -and $_.Impact -eq 'Critical' }).Count
HighGaps = @($nistResult.Controls | Where-Object { $_.Status -eq 'NonCompliant' -and $_.Impact -eq 'High' }).Count
+ MediumGaps = @($nistResult.Controls | Where-Object { $_.Status -eq 'NonCompliant' -and $_.Impact -eq 'Medium' }).Count
Controls = $nistResult.Controls
Status = if ($nistResult.Summary.CompliancePercentage -ge 80) { 'Pass' }
elseif ($nistResult.Summary.CompliancePercentage -ge 60) { 'Marginal' }
@@ -146,7 +149,7 @@ function Get-ComplianceReport {
Write-Host "`n[3/3] Running PCI-DSS compliance test..." -ForegroundColor Cyan
try {
- $pciResult = Test-PCI-DSS -Version 4.0
+ $pciResult = Test-PCI-DSS -Version '4.0'
$frameworkSummary = [PSCustomObject]@{
Framework = 'PCI-DSS v4.0'
@@ -157,6 +160,7 @@ function Get-ComplianceReport {
NotApplicable = $pciResult.Summary.NotApplicable
CriticalGaps = @($pciResult.Requirements | Where-Object { $_.Status -eq 'NotInPlace' -and $_.Priority -eq 'Critical' }).Count
HighGaps = @($pciResult.Requirements | Where-Object { $_.Status -eq 'NotInPlace' -and $_.Priority -eq 'High' }).Count
+ MediumGaps = @($pciResult.Requirements | Where-Object { $_.Status -eq 'NotInPlace' -and $_.Priority -eq 'Medium' }).Count
Controls = $pciResult.Requirements
Status = if ($pciResult.Summary.CompliancePercentage -eq 100) { 'Pass' }
elseif ($pciResult.Summary.CompliancePercentage -ge 80) { 'Marginal' }
@@ -189,6 +193,7 @@ function Get-ComplianceReport {
$report.ExecutiveSummary.NonCompliantControls = ($report.Frameworks | Measure-Object -Property Failed -Sum).Sum
$report.ExecutiveSummary.CriticalGaps = ($report.Frameworks | Measure-Object -Property CriticalGaps -Sum).Sum
$report.ExecutiveSummary.HighGaps = ($report.Frameworks | Measure-Object -Property HighGaps -Sum).Sum
+ $report.ExecutiveSummary.MediumGaps = ($report.Frameworks | Measure-Object -Property MediumGaps -Sum).Sum
}
# Cross-Framework Analysis
@@ -302,7 +307,7 @@ function Get-ComplianceReport {
}
}
- $report.RemediationPriorities = $allGaps | Sort-Object Priority, Framework | Select-Object -First 10
+ $report.RemediationPriorities = @($allGaps | Sort-Object Priority, Framework | Select-Object -First 10)
# Generate Recommendations
if ($report.ExecutiveSummary.CriticalGaps -gt 0) {
@@ -321,6 +326,33 @@ function Get-ComplianceReport {
$report.Recommendations += "Maintain documentation for all compliance controls"
$report.Recommendations += "Consider engaging third-party assessor for validation"
+ # Collect Audit Evidence (if requested)
+ if ($IncludeEvidence) {
+ Write-Host "`n[*] Collecting compliance evidence packages..." -ForegroundColor Cyan
+
+ $evidenceRoot = if ($OutputPath) { Join-Path $OutputPath 'Evidence' } else { Join-Path $env:TEMP 'ComplianceEvidence' }
+
+ foreach ($framework in $report.Frameworks) {
+ try {
+ $shortName = ($framework.Framework -replace '[^a-zA-Z0-9]', '')
+ $evidence = Export-ComplianceEvidence -OutputPath $evidenceRoot -CaseReference $shortName
+
+ if ($null -ne $evidence -and $null -ne $evidence.PSObject.Properties['PackagePath']) {
+ $report.Evidence += [PSCustomObject]@{
+ Framework = $framework.Framework
+ PackagePath = $evidence.PackagePath
+ PackageHash = $evidence.PackageHash
+ CaseReference = $evidence.CaseReference
+ }
+ Write-Host " Evidence collected for $($framework.Framework): $($evidence.PackagePath)" -ForegroundColor Green
+ }
+ }
+ catch {
+ Write-Warning "Could not collect evidence for $($framework.Framework) - $_"
+ }
+ }
+ }
+
# Export Reports
if ($OutputPath) {
Write-Host "`n[*] Exporting compliance reports..." -ForegroundColor Cyan
diff --git a/Compliance/Test-CISBenchmark.ps1 b/Compliance/Test-CISBenchmark.ps1
index 5475948..191e77d 100644
--- a/Compliance/Test-CISBenchmark.ps1
+++ b/Compliance/Test-CISBenchmark.ps1
@@ -289,7 +289,8 @@ function Test-CISBenchmark {
try {
# CIS 2.3.1.1 - Accounts: Administrator account status
- $adminDisabled = (Get-LocalUser -Name "Administrator" -ErrorAction SilentlyContinue).Enabled
+ $adminUser = Get-LocalUser -Name "Administrator" -ErrorAction SilentlyContinue
+ $adminDisabled = if ($adminUser) { $adminUser.Enabled } else { $false }
$control = [PSCustomObject]@{
ControlID = 'CIS-2.3.1.1'
ControlName = 'Accounts: Administrator account status'
@@ -303,7 +304,8 @@ function Test-CISBenchmark {
$results.Controls += $control
# CIS 2.3.1.5 - Accounts: Guest account status
- $guestDisabled = (Get-LocalUser -Name "Guest" -ErrorAction SilentlyContinue).Enabled
+ $guestUser = Get-LocalUser -Name "Guest" -ErrorAction SilentlyContinue
+ $guestDisabled = if ($guestUser) { $guestUser.Enabled } else { $false }
$control = [PSCustomObject]@{
ControlID = 'CIS-2.3.1.5'
ControlName = 'Accounts: Guest account status'
diff --git a/Compliance/Test-NISTCompliance.ps1 b/Compliance/Test-NISTCompliance.ps1
index 48a53d3..26545cd 100644
--- a/Compliance/Test-NISTCompliance.ps1
+++ b/Compliance/Test-NISTCompliance.ps1
@@ -95,8 +95,10 @@ function Test-NISTCompliance {
try {
# AC-2: Account Management
- $guestDisabled = (Get-LocalUser -Name "Guest" -ErrorAction SilentlyContinue).Enabled -eq $false
- $adminDisabled = (Get-LocalUser -Name "Administrator" -ErrorAction SilentlyContinue).Enabled -eq $false
+ $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)
$control = [PSCustomObject]@{
ControlID = 'AC-2'
@@ -141,14 +143,15 @@ function Test-NISTCompliance {
Description = 'Automatic screen lock after inactivity'
Expected = '15 minutes (900 seconds) or less'
Actual = if ($regTest.ActualValue) { "$([math]::Round($regTest.ActualValue/60)) minutes" } else { "Not configured" }
- Status = if ($regTest.Compliant -or $regTest.ActualValue -le 900) { 'Compliant' } else { 'NonCompliant' }
+ Status = if ($regTest.Compliant -or ($null -ne $regTest.ActualValue -and $regTest.ActualValue -le 900)) { 'Compliant' } else { 'NonCompliant' }
Impact = 'Medium'
Remediation = 'Configure screen lock timeout to 15 minutes or less'
}
$results.Controls += $control
# AC-17: Remote Access
- $rdpEnabled = (Get-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name 'fDenyTSConnections' -ErrorAction SilentlyContinue).fDenyTSConnections
+ $rdpSetting = Get-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name 'fDenyTSConnections' -ErrorAction SilentlyContinue
+ $rdpEnabled = if ($rdpSetting) { $rdpSetting.fDenyTSConnections } else { $null }
$control = [PSCustomObject]@{
ControlID = 'AC-17'
@@ -191,7 +194,8 @@ function Test-NISTCompliance {
$results.Controls += $control
# AU-3: Content of Audit Records
- $eventLogSize = (Get-WinEvent -ListLog Security -ErrorAction SilentlyContinue).MaximumSizeInBytes
+ $securityLog = Get-WinEvent -ListLog Security -ErrorAction SilentlyContinue
+ $eventLogSize = if ($securityLog) { $securityLog.MaximumSizeInBytes } else { 0 }
$control = [PSCustomObject]@{
ControlID = 'AU-3'
@@ -210,7 +214,10 @@ function Test-NISTCompliance {
$logPath = "C:\Windows\System32\winevt\Logs\Security.evtx"
if (Test-Path $logPath) {
$acl = Get-Acl $logPath -ErrorAction SilentlyContinue
- $protected = @($acl.Access | Where-Object { $_.IdentityReference -match "Users" -and $_.FileSystemRights -match "FullControl|Modify|Write" })
+ $protected = @()
+ if ($acl) {
+ $protected = @($acl.Access | Where-Object { $_.IdentityReference -match "Users" -and $_.FileSystemRights -match "FullControl|Modify|Write" })
+ }
$control = [PSCustomObject]@{
ControlID = 'AU-9'
@@ -255,36 +262,46 @@ function Test-NISTCompliance {
try {
# IA-2: Identification and Authentication
$passwordPolicy = net accounts 2>$null
- $minPasswordLength = ($passwordPolicy | Select-String "Minimum password length").ToString().Split(':')[1].Trim()
-
- $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'
+ $minPasswordLengthLine = $passwordPolicy | Select-String "Minimum password length" | Select-Object -First 1
+
+ if ($minPasswordLengthLine) {
+ $minPasswordLength = $minPasswordLengthLine.ToString().Split(':')[1].Trim()
+
+ $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
}
- $results.Controls += $control
-
+
# IA-5: Authenticator Management
- $maxPasswordAge = ($passwordPolicy | Select-String "Maximum password age").ToString().Split(':')[1].Trim().Split(' ')[0]
-
- $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 ([int]$maxPasswordAge -le 60 -and [int]$maxPasswordAge -gt 0) { 'Compliant' } else { 'NonCompliant' }
- Impact = 'High'
- Remediation = 'Set maximum password age to 60 days or less'
+ $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)
+
+ $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
}
- $results.Controls += $control
# IA-8: Identification and Authentication (Non-Organizational Users)
$regTest = Test-RegistryValue -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' `
@@ -350,7 +367,7 @@ function Test-NISTCompliance {
# SC-28: Protection of Information at Rest
$bitlockerStatus = Get-BitLockerVolume -MountPoint "C:" -ErrorAction SilentlyContinue
- $bitlockerEnabled = $bitlockerStatus.ProtectionStatus -eq 'On'
+ $bitlockerEnabled = ($null -ne $bitlockerStatus) -and ($bitlockerStatus.ProtectionStatus -eq 'On')
$control = [PSCustomObject]@{
ControlID = 'SC-28'
@@ -377,7 +394,7 @@ function Test-NISTCompliance {
try {
# CM-6: Configuration Settings
$defenderStatus = Get-MpComputerStatus -ErrorAction SilentlyContinue
- $defenderEnabled = $defenderStatus.AntivirusEnabled
+ $defenderEnabled = ($null -ne $defenderStatus) -and $defenderStatus.AntivirusEnabled
$control = [PSCustomObject]@{
ControlID = 'CM-6'
diff --git a/Compliance/Test-PCI-DSS.ps1 b/Compliance/Test-PCI-DSS.ps1
index 62ce0fb..f877d66 100644
--- a/Compliance/Test-PCI-DSS.ps1
+++ b/Compliance/Test-PCI-DSS.ps1
@@ -11,7 +11,7 @@ function Test-PCI-DSS {
Specific requirement to test: All, Network, Data, AccessControl, Monitoring, Testing
.EXAMPLE
Test-PCI-DSS
- Test-PCI-DSS -Version 4.0 -RequirementFilter Network
+ Test-PCI-DSS -Version '4.0' -RequirementFilter Network
.OUTPUTS
PSCustomObject with PCI-DSS compliance results
#>
@@ -166,7 +166,7 @@ function Test-PCI-DSS {
# Req 3.5: Primary account number (PAN) protection
$bitlockerStatus = Get-BitLockerVolume -MountPoint "C:" -ErrorAction SilentlyContinue
- $bitlockerEnabled = $bitlockerStatus.ProtectionStatus -eq 'On'
+ $bitlockerEnabled = ($null -ne $bitlockerStatus) -and ($bitlockerStatus.ProtectionStatus -eq 'On')
$req = [PSCustomObject]@{
RequirementID = '3.5.1'
@@ -206,7 +206,8 @@ function Test-PCI-DSS {
try {
# Req 7.1: Limit access to system components
- $guestDisabled = (Get-LocalUser -Name "Guest" -ErrorAction SilentlyContinue).Enabled -eq $false
+ $guestUser = Get-LocalUser -Name "Guest" -ErrorAction SilentlyContinue
+ $guestDisabled = ($null -eq $guestUser) -or ($guestUser.Enabled -eq $false)
$req = [PSCustomObject]@{
RequirementID = '7.1.1'
@@ -223,36 +224,46 @@ function Test-PCI-DSS {
# Req 8.2: User identification and authentication
$passwordPolicy = net accounts 2>$null
- $minPasswordLength = ($passwordPolicy | Select-String "Minimum password length").ToString().Split(':')[1].Trim()
-
- $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'
+ $minPasswordLengthLine = $passwordPolicy | Select-String "Minimum password length" | Select-Object -First 1
+
+ if ($minPasswordLengthLine) {
+ $minPasswordLength = $minPasswordLengthLine.ToString().Split(':')[1].Trim()
+
+ $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
}
- $results.Requirements += $req
-
+
# Req 8.2.4: Change passwords every 90 days
- $maxPasswordAge = ($passwordPolicy | Select-String "Maximum password age").ToString().Split(':')[1].Trim().Split(' ')[0]
-
- $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 ([int]$maxPasswordAge -le 90 -and [int]$maxPasswordAge -gt 0) { 'InPlace' } else { 'NotInPlace' }
- Priority = 'High'
- Remediation = 'Set maximum password age to 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)
+
+ $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
}
- $results.Requirements += $req
# Req 8.3: Multi-factor authentication
$req = [PSCustomObject]@{
@@ -313,7 +324,8 @@ function Test-PCI-DSS {
$results.Requirements += $req
# Req 10.5: Protect audit trails
- $eventLogSize = (Get-WinEvent -ListLog Security -ErrorAction SilentlyContinue).MaximumSizeInBytes
+ $securityLog = Get-WinEvent -ListLog Security -ErrorAction SilentlyContinue
+ $eventLogSize = if ($securityLog) { $securityLog.MaximumSizeInBytes } else { 0 }
$req = [PSCustomObject]@{
RequirementID = '10.5.1'
@@ -338,7 +350,7 @@ function Test-PCI-DSS {
Description = 'System clocks must be synchronized'
Expected = 'Windows Time service running'
Actual = if ($w32timeService) { $w32timeService.Status } else { "Not found" }
- Status = if ($w32timeService.Status -eq 'Running') { 'InPlace' } else { 'NotInPlace' }
+ Status = if ($w32timeService -and $w32timeService.Status -eq 'Running') { 'InPlace' } else { 'NotInPlace' }
Priority = 'Medium'
Remediation = 'Ensure Windows Time service is running and configured'
}
@@ -356,7 +368,7 @@ function Test-PCI-DSS {
try {
# Req 11.3: Vulnerability scanning
$defenderStatus = Get-MpComputerStatus -ErrorAction SilentlyContinue
- $defenderEnabled = $defenderStatus.AntivirusEnabled
+ $defenderEnabled = ($null -ne $defenderStatus) -and $defenderStatus.AntivirusEnabled
$req = [PSCustomObject]@{
RequirementID = '11.3.1'
diff --git a/Core/Compare-SecurityBaseline.ps1 b/Core/Compare-SecurityBaseline.ps1
new file mode 100644
index 0000000..0667e6f
--- /dev/null
+++ b/Core/Compare-SecurityBaseline.ps1
@@ -0,0 +1,321 @@
+function Compare-SecurityBaseline {
+ <#
+ .SYNOPSIS
+ Compares a saved security baseline against a current security state and reports drift
+ .DESCRIPTION
+ Loads a previously saved security baseline from JSON (for example the output of
+ Get-SecurityBaseline or Invoke-SecurityAssessment piped to ConvertTo-Json) and compares
+ it against a second state. The current state is either loaded from a second JSON file
+ (-CurrentPath) or captured live via Get-SecurityBaseline when -CurrentPath is omitted.
+ Every differing property is classified as Improved, Degraded, New, Removed, or Changed,
+ and a summary with an overall trend is produced. Results can optionally be exported as
+ JSON (full result) and CSV (changes only) via -OutputPath.
+ .PARAMETER BaselinePath
+ Path to the previously saved baseline JSON file (mandatory)
+ .PARAMETER CurrentPath
+ Path to a JSON file containing the current state. When omitted, the current state is
+ captured live by calling Get-SecurityBaseline
+ .PARAMETER OutputPath
+ Directory where the comparison result (JSON) and the list of changes (CSV) are written
+ .EXAMPLE
+ Compare-SecurityBaseline -BaselinePath "C:\Audits\baseline.json"
+ Compares the saved baseline against the live system state
+ .EXAMPLE
+ Compare-SecurityBaseline -BaselinePath "C:\Audits\baseline.json" -CurrentPath "C:\Audits\current.json" -OutputPath "C:\Audits\Drift"
+ Compares two saved states and exports the result as JSON and CSV
+ .OUTPUTS
+ PSCustomObject with CompareDate, Categories, Changes, and Summary properties
+ #>
+
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory = $true, Position = 0)]
+ [ValidateScript({ Test-Path -Path $_ -PathType Leaf })]
+ [string]$BaselinePath,
+
+ [Parameter(Position = 1)]
+ [ValidateScript({ Test-Path -Path $_ -PathType Leaf })]
+ [string]$CurrentPath,
+
+ [Parameter(Position = 2)]
+ [string]$OutputPath
+ )
+
+ begin {
+ Write-Host "Starting Security Baseline Comparison..." -ForegroundColor Cyan
+
+ # Properties that hold volatile timestamps are excluded from drift detection
+ $script:noisePattern = '(^|\.)(ScanDate|CollectionDate|CompareDate|LastBootUpTime|LocalDateTime|InstallDate|LastUpdateCheck)$'
+
+ $changes = @()
+ $unchangedCount = 0
+ $categories = @()
+
+ # Flattens a nested PSCustomObject/array graph into a path -> leaf-value map
+ function ConvertTo-FlatMap {
+ param(
+ [object]$Node,
+ [string]$Path,
+ [hashtable]$Map
+ )
+
+ if ($null -eq $Node) {
+ $Map[$Path] = '(null)'
+ return
+ }
+
+ if ($Node -is [System.Management.Automation.PSCustomObject]) {
+ foreach ($prop in $Node.PSObject.Properties) {
+ $childPath = if ($Path) { "$Path.$($prop.Name)" } else { $prop.Name }
+ ConvertTo-FlatMap -Node $prop.Value -Path $childPath -Map $Map
+ }
+ }
+ elseif ($Node -is [System.Collections.IEnumerable] -and $Node -isnot [string]) {
+ $items = @($Node)
+ if ($items.Count -eq 0) {
+ $Map[$Path] = '(empty)'
+ }
+ for ($i = 0; $i -lt $items.Count; $i++) {
+ ConvertTo-FlatMap -Node $items[$i] -Path "$Path[$i]" -Map $Map
+ }
+ }
+ else {
+ $Map[$Path] = "$Node"
+ }
+ }
+
+ # Maps boolean-like strings to numbers so direction of change can be determined
+ function ConvertTo-ComparableValue {
+ param([string]$Value)
+
+ if ($null -eq $Value) { return $null }
+ switch -Regex ($Value) {
+ '^(True|On|Enabled|Yes|1)$' { return 1.0 }
+ '^(False|Off|Disabled|No|0)$' { return 0.0 }
+ }
+ $number = 0.0
+ if ([double]::TryParse($Value, [ref]$number)) { return $number }
+ return $null
+ }
+
+ # Decides whether a changed value is an improvement or a degradation
+ function Get-ChangeDirection {
+ param(
+ [string]$Path,
+ [string]$BaselineValue,
+ [string]$CurrentValue
+ )
+
+ $goodDirection = 0 # 1 = higher is better, -1 = lower is better, 0 = unknown
+ switch -Regex ($Path) {
+ 'PendingUpdates|Vulnerabilit|Issue|Error|Failed|Risk|Threat|Exposure' { $goodDirection = -1; break }
+ 'Enabled|Protection|EnableLUA|Encryption|Score|Secure|Compliant|Health' { $goodDirection = 1; break }
+ }
+
+ if ($goodDirection -eq 0) { return 'Changed' }
+
+ $baseNumber = ConvertTo-ComparableValue -Value $BaselineValue
+ $currentNumber = ConvertTo-ComparableValue -Value $CurrentValue
+ if ($null -eq $baseNumber -or $null -eq $currentNumber) { return 'Changed' }
+
+ $delta = $currentNumber - $baseNumber
+ if ($delta -eq 0) { return 'Changed' }
+ if (($delta -gt 0 -and $goodDirection -eq 1) -or ($delta -lt 0 -and $goodDirection -eq -1)) {
+ return 'Improved'
+ }
+ return 'Degraded'
+ }
+ }
+
+ process {
+ try {
+ # Load the saved baseline
+ Write-Host "Loading baseline from: $BaselinePath" -ForegroundColor Yellow
+ try {
+ $baselineJson = Get-Content -Path $BaselinePath -Raw -ErrorAction Stop
+ $baseline = $baselineJson | ConvertFrom-Json -ErrorAction Stop
+ }
+ catch {
+ Write-Error "Could not load baseline file '$BaselinePath': $_"
+ throw
+ }
+
+ # Load or capture the current state
+ $currentSource = "Live capture (Get-SecurityBaseline)"
+ $current = $null
+ if ($CurrentPath) {
+ $currentSource = $CurrentPath
+ Write-Host "Loading current state from: $CurrentPath" -ForegroundColor Yellow
+ try {
+ $currentJson = Get-Content -Path $CurrentPath -Raw -ErrorAction Stop
+ $current = $currentJson | ConvertFrom-Json -ErrorAction Stop
+ }
+ catch {
+ Write-Error "Could not load current state file '$CurrentPath': $_"
+ throw
+ }
+ }
+ else {
+ Write-Host "Capturing current state via Get-SecurityBaseline..." -ForegroundColor Yellow
+ if (-not (Get-Command -Name Get-SecurityBaseline -ErrorAction SilentlyContinue)) {
+ Write-Error "Get-SecurityBaseline is not available. Provide -CurrentPath or load the WindowsSecurityAudit module."
+ throw "Get-SecurityBaseline not found"
+ }
+ try {
+ $current = Get-SecurityBaseline -ErrorAction Stop
+ }
+ catch {
+ Write-Warning "Live capture with Get-SecurityBaseline failed: $_"
+ throw
+ }
+ }
+
+ # Flatten both states into comparable maps
+ Write-Host "Comparing security states..." -ForegroundColor Yellow
+ $baselineMap = @{}
+ $currentMap = @{}
+ ConvertTo-FlatMap -Node $baseline -Path '' -Map $baselineMap
+ ConvertTo-FlatMap -Node $current -Path '' -Map $currentMap
+
+ # Build the list of compared categories (top-level property names)
+ $categorySet = @{}
+ foreach ($key in @($baselineMap.Keys) + @($currentMap.Keys)) {
+ if ($key -match $script:noisePattern) { continue }
+ $topLevel = ($key -split '\.')[0] -replace '\[.*$', ''
+ if ($topLevel) { $categorySet[$topLevel] = $true }
+ }
+ $categories = @($categorySet.Keys | Sort-Object)
+
+ # Detect changed, new, and removed properties
+ foreach ($key in @($baselineMap.Keys | Sort-Object)) {
+ if ($key -match $script:noisePattern) { continue }
+
+ $baselineValue = $baselineMap[$key]
+ if (-not $currentMap.ContainsKey($key)) {
+ $changes += [PSCustomObject]@{
+ Property = $key
+ BaselineValue = $baselineValue
+ CurrentValue = '(missing)'
+ ChangeType = 'Removed'
+ }
+ continue
+ }
+
+ $currentValue = $currentMap[$key]
+ if ($baselineValue -eq $currentValue) {
+ $unchangedCount++
+ }
+ else {
+ $changes += [PSCustomObject]@{
+ Property = $key
+ BaselineValue = $baselineValue
+ CurrentValue = $currentValue
+ ChangeType = (Get-ChangeDirection -Path $key -BaselineValue $baselineValue -CurrentValue $currentValue)
+ }
+ }
+ }
+
+ foreach ($key in @($currentMap.Keys | Sort-Object)) {
+ if ($key -match $script:noisePattern) { continue }
+ if (-not $baselineMap.ContainsKey($key)) {
+ $changes += [PSCustomObject]@{
+ Property = $key
+ BaselineValue = '(missing)'
+ CurrentValue = $currentMap[$key]
+ ChangeType = 'New'
+ }
+ }
+ }
+
+ $changes = @($changes | Sort-Object ChangeType, Property)
+ }
+ catch {
+ Write-Error "Error during security baseline comparison: $_"
+ throw
+ }
+ }
+
+ end {
+ # Build summary
+ $improvedCount = @($changes | Where-Object { $_.ChangeType -eq 'Improved' }).Count
+ $degradedCount = @($changes | Where-Object { $_.ChangeType -eq 'Degraded' }).Count
+ $newCount = @($changes | Where-Object { $_.ChangeType -eq 'New' }).Count
+ $removedCount = @($changes | Where-Object { $_.ChangeType -eq 'Removed' }).Count
+
+ $overallTrend = 'Stable'
+ if ($improvedCount -gt 0 -and $degradedCount -gt 0) {
+ $overallTrend = 'Mixed'
+ }
+ elseif ($improvedCount -gt $degradedCount) {
+ $overallTrend = 'Improved'
+ }
+ elseif ($degradedCount -gt $improvedCount) {
+ $overallTrend = 'Degraded'
+ }
+ elseif ($newCount -gt 0 -or $removedCount -gt 0) {
+ $overallTrend = 'Changed'
+ }
+
+ $summary = [PSCustomObject]@{
+ ImprovedCount = $improvedCount
+ DegradedCount = $degradedCount
+ NewCount = $newCount
+ RemovedCount = $removedCount
+ UnchangedCount = $unchangedCount
+ TotalChanges = @($changes).Count
+ OverallTrend = $overallTrend
+ }
+
+ $result = [PSCustomObject]@{
+ CompareDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
+ ComputerName = $env:COMPUTERNAME
+ BaselineSource = $BaselinePath
+ CurrentSource = $currentSource
+ Categories = $categories
+ Changes = $changes
+ Summary = $summary
+ }
+
+ # Display results
+ Write-Host "`nComparison Results" -ForegroundColor Cyan
+ Write-Host "------------------" -ForegroundColor Cyan
+ if ($changes.Count -eq 0) {
+ Write-Host "No drift detected - current state matches the baseline." -ForegroundColor Green
+ }
+ else {
+ foreach ($change in $changes) {
+ $color = switch ($change.ChangeType) {
+ 'Improved' { 'Green' }
+ 'Degraded' { 'Red' }
+ default { 'Yellow' }
+ }
+ Write-Host ("[{0}] {1}: '{2}' -> '{3}'" -f $change.ChangeType, $change.Property, $change.BaselineValue, $change.CurrentValue) -ForegroundColor $color
+ }
+ }
+ Write-Host ("Summary: {0} improved, {1} degraded, {2} new, {3} removed, {4} unchanged - Trend: {5}" -f
+ $improvedCount, $degradedCount, $newCount, $removedCount, $unchangedCount, $overallTrend) -ForegroundColor Cyan
+
+ # Export results if path specified
+ if ($OutputPath) {
+ try {
+ if (-not (Test-Path $OutputPath)) {
+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null
+ }
+ $timestamp = Get-Date -Format 'yyyyMMdd_HHmmss'
+ $jsonFile = Join-Path -Path $OutputPath -ChildPath "CompareResult_$timestamp.json"
+ $csvFile = Join-Path -Path $OutputPath -ChildPath "CompareChanges_$timestamp.csv"
+
+ $result | ConvertTo-Json -Depth 10 | Out-File -FilePath $jsonFile -Encoding UTF8
+ $changes | Export-Csv -Path $csvFile -NoTypeInformation -Encoding UTF8
+
+ Write-Host "Results exported to: $jsonFile" -ForegroundColor Green
+ Write-Host "Changes exported to: $csvFile" -ForegroundColor Green
+ }
+ catch {
+ Write-Warning "Could not export comparison results to '$OutputPath': $_"
+ }
+ }
+
+ return $result
+ }
+}
diff --git a/Core/Get-SecurityBaseline.ps1 b/Core/Get-SecurityBaseline.ps1
index c23bf87..763a0be 100644
--- a/Core/Get-SecurityBaseline.ps1
+++ b/Core/Get-SecurityBaseline.ps1
@@ -85,14 +85,15 @@ function Get-SecurityBaseline {
try {
$uacKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
$uacSettings = Get-ItemProperty -Path $uacKey -ErrorAction Stop
+ $enableLUA = if ($null -ne $uacSettings.PSObject.Properties['EnableLUA']) { $uacSettings.EnableLUA } else { $null }
$results.UAC = [PSCustomObject]@{
- EnableLUA = $uacSettings.EnableLUA
- ConsentPromptBehaviorAdmin = $uacSettings.ConsentPromptBehaviorAdmin
- ConsentPromptBehaviorUser = $uacSettings.ConsentPromptBehaviorUser
- EnableSecureUIAPaths = $uacSettings.EnableSecureUIAPaths
- EnableVirtualization = $uacSettings.EnableVirtualization
+ EnableLUA = $enableLUA
+ ConsentPromptBehaviorAdmin = if ($null -ne $uacSettings.PSObject.Properties['ConsentPromptBehaviorAdmin']) { $uacSettings.ConsentPromptBehaviorAdmin } else { $null }
+ ConsentPromptBehaviorUser = if ($null -ne $uacSettings.PSObject.Properties['ConsentPromptBehaviorUser']) { $uacSettings.ConsentPromptBehaviorUser } else { $null }
+ EnableSecureUIAPaths = if ($null -ne $uacSettings.PSObject.Properties['EnableSecureUIAPaths']) { $uacSettings.EnableSecureUIAPaths } else { $null }
+ EnableVirtualization = if ($null -ne $uacSettings.PSObject.Properties['EnableVirtualization']) { $uacSettings.EnableVirtualization } else { $null }
}
- if ($uacSettings.EnableLUA -eq 1) { $results.SecurityScore += 15 }
+ if ($enableLUA -eq 1) { $results.SecurityScore += 15 }
}
catch {
Write-Warning "Could not retrieve UAC settings: $_"
@@ -150,7 +151,7 @@ function Get-SecurityBaseline {
$wuKey = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU"
if (Test-Path $wuKey) {
$auSettings = Get-ItemProperty -Path $wuKey -ErrorAction SilentlyContinue
- if ($auSettings -and $auSettings.NoAutoUpdate -eq 1) {
+ if ($auSettings -and $auSettings.PSObject.Properties['NoAutoUpdate'] -and $auSettings.NoAutoUpdate -eq 1) {
$autoUpdateEnabled = $false
}
}
diff --git a/Core/Get-SystemInfo.ps1 b/Core/Get-SystemInfo.ps1
index 26306e1..6ba5780 100644
--- a/Core/Get-SystemInfo.ps1
+++ b/Core/Get-SystemInfo.ps1
@@ -88,7 +88,7 @@ function Get-SystemInfo {
FileSystem = $_.FileSystem
Size = [math]::Round($_.Size / 1GB, 2)
FreeSpace = [math]::Round($_.FreeSpace / 1GB, 2)
- PercentFree = [math]::Round(($_.FreeSpace / $_.Size) * 100, 2)
+ PercentFree = if ($_.Size) { [math]::Round(($_.FreeSpace / $_.Size) * 100, 2) } else { $null }
}
}
}
@@ -96,20 +96,21 @@ function Get-SystemInfo {
# Network Configuration
$netAdapters = Get-NetAdapter | Where-Object { $_.Status -eq 'Up' }
$netIP = Get-NetIPAddress | Where-Object { $_.AddressFamily -eq 'IPv4' -and $_.PrefixOrigin -ne 'WellKnown' }
+ $defaultRoute = Get-NetRoute -DestinationPrefix "0.0.0.0/0" -ErrorAction SilentlyContinue | Select-Object -First 1
$info.Network = [PSCustomObject]@{
Adapters = $netAdapters | Select-Object Name, InterfaceDescription, MacAddress, LinkSpeed, Status
IPAddresses = $netIP | Select-Object InterfaceAlias, IPAddress, PrefixLength
DNSServers = Get-DnsClientServerAddress | Where-Object { $_.AddressFamily -eq 2 } |
Select-Object InterfaceAlias, ServerAddresses
- DefaultGateway = (Get-NetRoute -DestinationPrefix "0.0.0.0/0" -ErrorAction SilentlyContinue).NextHop
+ DefaultGateway = if ($defaultRoute) { $defaultRoute.NextHop } else { $null }
}
# Security Settings
# Security Settings
$info.Security = [PSCustomObject]@{
- LocalUsers = (Get-LocalUser).Count
- LocalAdministrators = (Get-LocalGroupMember -Group "Administrators" -ErrorAction SilentlyContinue).Count
+ LocalUsers = (@(Get-LocalUser)).Count
+ LocalAdministrators = (@(Get-LocalGroupMember -Group "Administrators" -ErrorAction SilentlyContinue)).Count
PasswordPolicy = Get-LocalUser | Where-Object { $_.PasswordRequired -eq $false } |
Select-Object Name, Enabled
FirewallProfiles = Get-NetFirewallProfile | Select-Object Name, Enabled
diff --git a/Detection/Find-NetworkAnomalies.ps1 b/Detection/Find-NetworkAnomalies.ps1
index 03dae01..0c6c38f 100644
--- a/Detection/Find-NetworkAnomalies.ps1
+++ b/Detection/Find-NetworkAnomalies.ps1
@@ -78,14 +78,15 @@ function Find-NetworkAnomalies {
# Get process info
$process = Get-Process -Id $listener.OwningProcess -ErrorAction SilentlyContinue
+ $processPath = $null
+ if ($process) {
+ try { $processPath = $process.Path } catch { $processPath = $null }
+ }
# Check for suspicious process listening
- if ($process) {
- $processPath = $process.Path
- if ($processPath -match '(Temp|AppData|Users\\Public)' -and $listener.LocalAddress -eq '0.0.0.0') {
- $suspicious = $true
- $reasons += "Suspicious process location listening on all interfaces"
- }
+ if ($processPath -match '(Temp|AppData|Users\\Public)' -and $listener.LocalAddress -eq '0.0.0.0') {
+ $suspicious = $true
+ $reasons += "Suspicious process location listening on all interfaces"
}
if ($suspicious) {
@@ -94,7 +95,7 @@ function Find-NetworkAnomalies {
LocalPort = $listener.LocalPort
ProcessName = if ($process) { $process.ProcessName } else { 'Unknown' }
ProcessId = $listener.OwningProcess
- ProcessPath = if ($process) { $process.Path } else { 'Unknown' }
+ ProcessPath = if ($processPath) { $processPath } else { 'Unknown' }
Reasons = ($reasons -join '; ')
}
}
@@ -123,8 +124,10 @@ function Find-NetworkAnomalies {
# Get process info
$process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue
-
+ $processPath = $null
if ($process) {
+ try { $processPath = $process.Path } catch { $processPath = $null }
+
# Check for suspicious processes with network connections
if ($process.ProcessName -match '(cmd|powershell|wscript|cscript)') {
$suspicious = $true
@@ -132,7 +135,7 @@ function Find-NetworkAnomalies {
}
# Check process path
- if ($process.Path -match '(Temp|AppData\\Local\\Temp|Users\\Public)') {
+ if ($processPath -match '(Temp|AppData\\Local\\Temp|Users\\Public)') {
$suspicious = $true
$reasons += "Process from suspicious location with network connection"
}
@@ -147,7 +150,7 @@ function Find-NetworkAnomalies {
State = $conn.State
ProcessName = if ($process) { $process.ProcessName } else { 'Unknown' }
ProcessId = $conn.OwningProcess
- ProcessPath = if ($process) { $process.Path } else { 'Unknown' }
+ ProcessPath = if ($processPath) { $processPath } else { 'Unknown' }
Reasons = ($reasons -join '; ')
}
}
@@ -158,7 +161,7 @@ function Find-NetworkAnomalies {
Write-Verbose "Analyzing port usage patterns..."
$allConnections = Get-NetTCPConnection -ErrorAction SilentlyContinue
$portGroups = $allConnections | Group-Object -Property LocalPort |
- Where-Object { $_.Count -gt 10 -and $_.Name -notin $legitimatePorts }
+ Where-Object { $_.Count -gt 10 -and [int]$_.Name -notin $legitimatePorts }
foreach ($group in $portGroups) {
$results.UnusualPorts += [PSCustomObject]@{
diff --git a/Detection/Find-PersistenceMechanisms.ps1 b/Detection/Find-PersistenceMechanisms.ps1
index 0c754c4..e65824b 100644
--- a/Detection/Find-PersistenceMechanisms.ps1
+++ b/Detection/Find-PersistenceMechanisms.ps1
@@ -140,7 +140,7 @@ function Find-PersistenceMechanisms {
$isSuspicious = $false
# Check for suspicious indicators
- if ($task.Principal.UserId -eq 'SYSTEM' -and $task.TaskPath -notmatch '\\Microsoft\\') {
+ if ($task.Principal -and $task.Principal.UserId -eq 'SYSTEM' -and $task.TaskPath -notmatch '\\Microsoft\\') {
$isSuspicious = $true
}
if ($actions -match '(powershell|cmd|wscript|cscript|mshta)' -and $task.TaskPath -notmatch '\\Microsoft\\') {
@@ -153,7 +153,7 @@ function Find-PersistenceMechanisms {
Path = $task.TaskPath
State = $task.State
Actions = if ($actions) { ($actions -join '; ') } else { 'N/A' }
- RunAsUser = $task.Principal.UserId
+ RunAsUser = if ($task.Principal) { $task.Principal.UserId } else { 'N/A' }
LastRunTime = if ($taskInfo -and $taskInfo.LastRunTime) { $taskInfo.LastRunTime } else { 'Never' }
NextRunTime = if ($taskInfo -and $taskInfo.NextRunTime) { $taskInfo.NextRunTime } else { 'Not scheduled' }
Suspicious = $isSuspicious
@@ -220,10 +220,10 @@ function Find-PersistenceMechanisms {
$appInitPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows"
if (Test-Path $appInitPath) {
$appInit = Get-ItemProperty -Path $appInitPath -ErrorAction SilentlyContinue
- if ($appInit.AppInit_DLLs) {
+ if ($appInit -and $appInit.PSObject.Properties['AppInit_DLLs'] -and $appInit.AppInit_DLLs) {
$results.AppInitDLLs += [PSCustomObject]@{
Value = $appInit.AppInit_DLLs
- LoadAppInit = $appInit.LoadAppInit_DLLs
+ LoadAppInit = if ($appInit.PSObject.Properties['LoadAppInit_DLLs']) { $appInit.LoadAppInit_DLLs } else { 'N/A' }
Suspicious = $true
}
$results.SuspiciousCount++
@@ -237,7 +237,7 @@ function Find-PersistenceMechanisms {
$lsa = Get-ItemProperty -Path $lsaPath -ErrorAction SilentlyContinue
# Check Authentication Packages
- if ($lsa.'Authentication Packages') {
+ if ($lsa -and $lsa.PSObject.Properties['Authentication Packages'] -and $lsa.'Authentication Packages') {
foreach ($pkg in $lsa.'Authentication Packages') {
if ($pkg -notmatch '^msv1_0$') {
$results.LSAProviders += [PSCustomObject]@{
@@ -251,7 +251,7 @@ function Find-PersistenceMechanisms {
}
# Check Notification Packages
- if ($lsa.'Notification Packages') {
+ if ($lsa -and $lsa.PSObject.Properties['Notification Packages'] -and $lsa.'Notification Packages') {
foreach ($pkg in $lsa.'Notification Packages') {
if ($pkg -notmatch '^(scecli|rassfm)$') {
$results.LSAProviders += [PSCustomObject]@{
@@ -271,7 +271,8 @@ function Find-PersistenceMechanisms {
if (Test-Path $monitorPath) {
$monitors = Get-ChildItem -Path $monitorPath -ErrorAction SilentlyContinue
foreach ($monitor in $monitors) {
- $driverValue = (Get-ItemProperty -Path $monitor.PSPath -ErrorAction SilentlyContinue).Driver
+ $monitorProps = Get-ItemProperty -Path $monitor.PSPath -ErrorAction SilentlyContinue
+ $driverValue = if ($monitorProps -and $monitorProps.PSObject.Properties['Driver']) { $monitorProps.Driver } else { $null }
if ($driverValue -and $driverValue -notmatch '(Microsoft|Windows)') {
$results.PrintMonitors += [PSCustomObject]@{
Name = $monitor.PSChildName
diff --git a/Detection/Find-SuspiciousAuthentication.ps1 b/Detection/Find-SuspiciousAuthentication.ps1
index 28b6019..2d8166b 100644
--- a/Detection/Find-SuspiciousAuthentication.ps1
+++ b/Detection/Find-SuspiciousAuthentication.ps1
@@ -128,17 +128,16 @@ function Find-SuspiciousAuthentication {
}
}
- # Calculate statistics safely
- # ESKI SATIRLARI SİLİN, BUNLARI KOYUN:
-try {
- $failedArray = @($results.FailedLogons)
- if ($failedArray.Count -gt 0) {
- $results.Statistics.UniqueFailedAccounts = (@($failedArray.Account | Select-Object -Unique)).Count
- $results.Statistics.UniqueSourceIPs = (@($failedArray | Where-Object { $_.SourceIP -ne '-' } | Select-Object -ExpandProperty SourceIP -Unique)).Count
- }
-} catch {
- Write-Verbose "Could not calculate unique statistics"
-}
+ # Calculate statistics safely
+ try {
+ $failedArray = @($results.FailedLogons)
+ if ($failedArray.Count -gt 0) {
+ $results.Statistics.UniqueFailedAccounts = (@($failedArray.Account | Select-Object -Unique)).Count
+ $results.Statistics.UniqueSourceIPs = (@($failedArray | Where-Object { $_.SourceIP -ne '-' } | Select-Object -ExpandProperty SourceIP -Unique)).Count
+ }
+ } catch {
+ Write-Verbose "Could not calculate unique statistics"
+ }
}
# 2. Account Lockouts (Event ID 4740)
diff --git a/Detection/Find-SuspiciousProcesses.ps1 b/Detection/Find-SuspiciousProcesses.ps1
index a498fda..711dd87 100644
--- a/Detection/Find-SuspiciousProcesses.ps1
+++ b/Detection/Find-SuspiciousProcesses.ps1
@@ -71,7 +71,9 @@ function Find-SuspiciousProcesses {
if (-not $processPath) {
continue
}
-
+
+ $cimProcess = Get-CimInstance Win32_Process -Filter "ProcessId = $($proc.Id)" -ErrorAction SilentlyContinue
+
# Check 1: Suspicious process names
foreach ($suspName in $suspiciousNames) {
if ($processName -match $suspName) {
@@ -119,7 +121,7 @@ function Find-SuspiciousProcesses {
# Check 6: Unusual parent-child relationship
try {
- $parentProcess = Get-Process -Id $proc.Parent.Id -ErrorAction Stop
+ $parentProcess = Get-Process -Id $cimProcess.ParentProcessId -ErrorAction Stop
# PowerShell/cmd spawned by Office apps
if ($parentProcess.ProcessName -match '(WINWORD|EXCEL|POWERPNT|OUTLOOK)' -and
@@ -198,14 +200,14 @@ function Find-SuspiciousProcesses {
ProcessName = $proc.ProcessName
ProcessId = $proc.Id
Path = $processPath
- CommandLine = (Get-CimInstance Win32_Process -Filter "ProcessId = $($proc.Id)" -ErrorAction SilentlyContinue).CommandLine
+ CommandLine = if ($cimProcess) { $cimProcess.CommandLine } else { 'N/A' }
UserName = $proc.UserName
StartTime = $proc.StartTime
CPU = [math]::Round($proc.CPU, 2)
WorkingSet = [math]::Round($proc.WorkingSet64 / 1MB, 2)
SuspicionScore = $suspicionScore
Reasons = ($suspicionReasons -join '; ')
- ParentProcess = try { (Get-Process -Id $proc.Parent.Id -ErrorAction Stop).ProcessName } catch { 'N/A' }
+ ParentProcess = try { (Get-Process -Id $cimProcess.ParentProcessId -ErrorAction Stop).ProcessName } catch { 'N/A' }
}
}
}
diff --git a/Enterprise/Get-MultiSystemAudit.ps1 b/Enterprise/Get-MultiSystemAudit.ps1
index 5515777..856aae9 100644
--- a/Enterprise/Get-MultiSystemAudit.ps1
+++ b/Enterprise/Get-MultiSystemAudit.ps1
@@ -319,7 +319,7 @@ function Get-MultiSystemAudit {
}
catch {
$systemAudit.Status = 'Failed'
- $systemAudit.Details.Error = $_.Exception.Message
+ $systemAudit.Details = @{ Error = $_.Exception.Message }
$auditResults.Summary.SystemsFailed++
Write-Warning " Failed to audit $computer : $_"
}
@@ -347,8 +347,8 @@ function Get-MultiSystemAudit {
# Find common findings
$allFindings = $successfulAudits | ForEach-Object { $_.Findings.Finding }
- $commonFindings = $allFindings | Group-Object | Where-Object { $_.Count -ge ($successfulAudits.Count / 2) } |
- Select-Object -ExpandProperty Name
+ $commonFindings = @($allFindings | Group-Object | Where-Object { $_.Count -ge ($successfulAudits.Count / 2) } |
+ Select-Object -ExpandProperty Name)
$auditResults.ComparativeAnalysis.CommonFindings = $commonFindings
}
diff --git a/Enterprise/Invoke-EnterpriseSecurityScan.ps1 b/Enterprise/Invoke-EnterpriseSecurityScan.ps1
index 259c29d..a486018 100644
--- a/Enterprise/Invoke-EnterpriseSecurityScan.ps1
+++ b/Enterprise/Invoke-EnterpriseSecurityScan.ps1
@@ -326,7 +326,7 @@ function Invoke-EnterpriseSecurityScan {
foreach ($job in $jobs) {
try {
- $result = $job.Pipeline.EndInvoke($job.Status)
+ $result = @($job.Pipeline.EndInvoke($job.Status))[0]
if ($result.Status -eq 'Success') {
$results.Summary.Successful++
diff --git a/Enterprise/Invoke-SecurityAssessment.ps1 b/Enterprise/Invoke-SecurityAssessment.ps1
index a5958b2..d6c4f08 100644
--- a/Enterprise/Invoke-SecurityAssessment.ps1
+++ b/Enterprise/Invoke-SecurityAssessment.ps1
@@ -98,28 +98,37 @@ function Invoke-SecurityAssessment {
}
# Signature updates
- $signatureAge = (Get-Date) - $defender.AntivirusSignatureLastUpdated
- if ($signatureAge.Days -le 2) {
- $systemSecurity.CategoryScore += 10
- $systemSecurity.Checks += [PSCustomObject]@{
- Check = 'Antivirus Signatures'
- Status = 'Pass'
- Score = 10
- Details = "Updated $($signatureAge.Days) days ago"
+ if ($null -ne $defender.AntivirusSignatureLastUpdated) {
+ $signatureAge = (Get-Date) - [datetime]$defender.AntivirusSignatureLastUpdated
+ if ($signatureAge.Days -le 2) {
+ $systemSecurity.CategoryScore += 10
+ $systemSecurity.Checks += [PSCustomObject]@{
+ Check = 'Antivirus Signatures'
+ Status = 'Pass'
+ Score = 10
+ Details = "Updated $($signatureAge.Days) days ago"
+ }
+ } else {
+ $systemSecurity.Checks += [PSCustomObject]@{
+ Check = 'Antivirus Signatures'
+ Status = 'Fail'
+ Score = 0
+ Details = "Outdated ($($signatureAge.Days) days old)"
+ }
+ $assessment.Findings += [PSCustomObject]@{
+ Severity = 'High'
+ Category = 'System Security'
+ Finding = 'Antivirus signatures are outdated'
+ Impact = 'Cannot detect latest threats'
+ Recommendation = 'Update Windows Defender definitions'
+ }
}
} else {
$systemSecurity.Checks += [PSCustomObject]@{
Check = 'Antivirus Signatures'
- Status = 'Fail'
+ Status = 'Unknown'
Score = 0
- Details = "Outdated ($($signatureAge.Days) days old)"
- }
- $assessment.Findings += [PSCustomObject]@{
- Severity = 'High'
- Category = 'System Security'
- Finding = 'Antivirus signatures are outdated'
- Impact = 'Cannot detect latest threats'
- Recommendation = 'Update Windows Defender definitions'
+ Details = 'Signature update time not available'
}
}
}
@@ -714,20 +723,143 @@ try {
$assessment.Categories.DataProtection = $dataProtection
+ # Compliance checks (optional)
+ if ($IncludeCompliance) {
+ Write-Host "`n[Compliance] Running Compliance Checks..." -ForegroundColor Cyan
+
+ # CIS Benchmark (Level 1)
+ try {
+ Write-Host " Running CIS Benchmark (Level 1)..." -ForegroundColor Yellow
+ $cisResult = Test-CISBenchmark -Level 1
+ if ($null -ne $cisResult) {
+ $cisPercentage = $null
+ if ($cisResult.PSObject.Properties['Summary'] -and $null -ne $cisResult.Summary) {
+ if ($cisResult.Summary -is [hashtable] -and $cisResult.Summary.ContainsKey('CompliancePercentage')) {
+ $cisPercentage = $cisResult.Summary['CompliancePercentage']
+ }
+ }
+ $assessment.ComplianceChecks += [PSCustomObject]@{
+ Framework = 'CIS Benchmark'
+ Version = 'Level 1'
+ Status = 'Completed'
+ CompliancePercentage = $cisPercentage
+ Result = $cisResult
+ }
+ } else {
+ Write-Warning "CIS Benchmark check returned no results"
+ $assessment.ComplianceChecks += [PSCustomObject]@{
+ Framework = 'CIS Benchmark'
+ Version = 'Level 1'
+ Status = 'NoResults'
+ CompliancePercentage = $null
+ Result = $null
+ }
+ }
+ } catch {
+ Write-Warning "CIS Benchmark compliance check failed: $_"
+ $assessment.ComplianceChecks += [PSCustomObject]@{
+ Framework = 'CIS Benchmark'
+ Version = 'Level 1'
+ Status = 'Error'
+ CompliancePercentage = $null
+ Result = $null
+ }
+ }
+
+ # NIST 800-53 Compliance
+ try {
+ Write-Host " Running NIST 800-53 Compliance..." -ForegroundColor Yellow
+ $nistResult = Test-NISTCompliance
+ if ($null -ne $nistResult) {
+ $nistPercentage = $null
+ if ($nistResult.PSObject.Properties['Summary'] -and $null -ne $nistResult.Summary) {
+ if ($nistResult.Summary -is [hashtable] -and $nistResult.Summary.ContainsKey('CompliancePercentage')) {
+ $nistPercentage = $nistResult.Summary['CompliancePercentage']
+ }
+ }
+ $assessment.ComplianceChecks += [PSCustomObject]@{
+ Framework = 'NIST 800-53'
+ Version = 'Rev 5'
+ Status = 'Completed'
+ CompliancePercentage = $nistPercentage
+ Result = $nistResult
+ }
+ } else {
+ Write-Warning "NIST 800-53 check returned no results"
+ $assessment.ComplianceChecks += [PSCustomObject]@{
+ Framework = 'NIST 800-53'
+ Version = 'Rev 5'
+ Status = 'NoResults'
+ CompliancePercentage = $null
+ Result = $null
+ }
+ }
+ } catch {
+ Write-Warning "NIST 800-53 compliance check failed: $_"
+ $assessment.ComplianceChecks += [PSCustomObject]@{
+ Framework = 'NIST 800-53'
+ Version = 'Rev 5'
+ Status = 'Error'
+ CompliancePercentage = $null
+ Result = $null
+ }
+ }
+
+ # PCI-DSS Compliance (v4.0)
+ try {
+ Write-Host " Running PCI-DSS Compliance (v4.0)..." -ForegroundColor Yellow
+ $pciResult = Test-PCI-DSS -Version '4.0'
+ if ($null -ne $pciResult) {
+ $pciPercentage = $null
+ if ($pciResult.PSObject.Properties['Summary'] -and $null -ne $pciResult.Summary) {
+ if ($pciResult.Summary -is [hashtable] -and $pciResult.Summary.ContainsKey('CompliancePercentage')) {
+ $pciPercentage = $pciResult.Summary['CompliancePercentage']
+ }
+ }
+ $assessment.ComplianceChecks += [PSCustomObject]@{
+ Framework = 'PCI-DSS'
+ Version = '4.0'
+ Status = 'Completed'
+ CompliancePercentage = $pciPercentage
+ Result = $pciResult
+ }
+ } else {
+ Write-Warning "PCI-DSS check returned no results"
+ $assessment.ComplianceChecks += [PSCustomObject]@{
+ Framework = 'PCI-DSS'
+ Version = '4.0'
+ Status = 'NoResults'
+ CompliancePercentage = $null
+ Result = $null
+ }
+ }
+ } catch {
+ Write-Warning "PCI-DSS compliance check failed: $_"
+ $assessment.ComplianceChecks += [PSCustomObject]@{
+ Framework = 'PCI-DSS'
+ Version = '4.0'
+ Status = 'Error'
+ CompliancePercentage = $null
+ Result = $null
+ }
+ }
+ }
+
# Calculate overall score
# Calculate overall score
$totalScore = 0
$maxScore = 0
try {
- foreach ($category in $assessment.Categories.PSObject.Properties) {
- if ($category.Value) {
+ foreach ($categoryName in $assessment.Categories.Keys) {
+ $category = $assessment.Categories[$categoryName]
+ if ($category) {
try {
- if ($category.Value.PSObject.Properties.Name -contains 'CategoryScore') {
- $totalScore += [int]$category.Value.CategoryScore
- $maxScore += [int]$category.Value.MaxScore
+ if ($category.PSObject.Properties.Name -contains 'CategoryScore') {
+ $totalScore += [int]$category.CategoryScore
+ $maxScore += [int]$category.MaxScore
}
} catch {
- Write-Verbose "Could not calculate score for category: $($category.Name)"
+ Write-Verbose "Could not calculate score for category: $categoryName"
}
}
}
@@ -789,20 +921,21 @@ if ($assessment.OverallScore -ge 80) {
)
Write-Host "`nCategory Scores:" -ForegroundColor Cyan
-foreach ($category in $assessment.Categories.PSObject.Properties) {
- if ($category.Value -and $category.Value -is [PSCustomObject]) {
+foreach ($categoryName in $assessment.Categories.Keys) {
+ $category = $assessment.Categories[$categoryName]
+ if ($category -and $category -is [PSCustomObject]) {
try {
- if ($category.Value.PSObject.Properties.Name -contains 'CategoryScore' -and
- $category.Value.PSObject.Properties.Name -contains 'MaxScore') {
- $catScore = [int]$category.Value.CategoryScore
- $catMax = [int]$category.Value.MaxScore
+ if ($category.PSObject.Properties.Name -contains 'CategoryScore' -and
+ $category.PSObject.Properties.Name -contains 'MaxScore') {
+ $catScore = [int]$category.CategoryScore
+ $catMax = [int]$category.MaxScore
if ($catMax -gt 0) {
$percentage = [math]::Round(($catScore / $catMax) * 100, 0)
- Write-Host " $($category.Name): $percentage%" -ForegroundColor White
+ Write-Host " $($categoryName): $percentage%" -ForegroundColor White
}
}
} catch {
- Write-Verbose "Could not display score for: $($category.Name)"
+ Write-Verbose "Could not display score for: $categoryName"
}
}
}
@@ -816,6 +949,32 @@ foreach ($category in $assessment.Categories.PSObject.Properties) {
Write-Host " High: $highCount" -ForegroundColor Yellow
Write-Host " Medium: $mediumCount" -ForegroundColor Yellow
+ # Compliance summary (when -IncludeCompliance was used)
+ if (@($assessment.ComplianceChecks).Count -gt 0) {
+ Write-Host "`nCompliance Summary:" -ForegroundColor Cyan
+ foreach ($complianceCheck in $assessment.ComplianceChecks) {
+ if ($null -ne $complianceCheck -and $complianceCheck.PSObject.Properties['Status']) {
+ $frameworkName = ''
+ if ($complianceCheck.PSObject.Properties['Framework']) {
+ $frameworkName = $complianceCheck.Framework
+ }
+ $frameworkVersion = ''
+ if ($complianceCheck.PSObject.Properties['Version']) {
+ $frameworkVersion = $complianceCheck.Version
+ }
+ if ($complianceCheck.Status -eq 'Completed') {
+ $percentageText = 'N/A'
+ if ($complianceCheck.PSObject.Properties['CompliancePercentage'] -and $null -ne $complianceCheck.CompliancePercentage) {
+ $percentageText = "$($complianceCheck.CompliancePercentage)%"
+ }
+ Write-Host " $frameworkName ($frameworkVersion): $percentageText compliant" -ForegroundColor White
+ } else {
+ Write-Host " $frameworkName ($frameworkVersion): $($complianceCheck.Status)" -ForegroundColor Yellow
+ }
+ }
+ }
+ }
+
# Save results
$assessment | ConvertTo-Json -Depth 10 | Out-File (Join-Path $OutputPath "SecurityAssessment.json")
diff --git a/Enterprise/Register-ScheduledSecurityScan.ps1 b/Enterprise/Register-ScheduledSecurityScan.ps1
new file mode 100644
index 0000000..7e2c809
--- /dev/null
+++ b/Enterprise/Register-ScheduledSecurityScan.ps1
@@ -0,0 +1,470 @@
+function Register-ScheduledSecurityScan {
+ <#
+ .SYNOPSIS
+ Registers an automated recurring security scan with optional alerting
+ .DESCRIPTION
+ Creates a PowerShell scan script under the output path that imports the
+ WindowsSecurityAudit module, runs Invoke-SecurityAssessment, and sends an
+ alert (Teams/Slack-style incoming webhook and/or email) when Critical
+ findings are detected. The script is then registered as a Scheduled Task
+ running as SYSTEM at the chosen cadence (Daily, Weekly on Monday, or
+ Monthly on the 1st). Use -Unregister to remove the scheduled task.
+ .PARAMETER ScanType
+ Type of scan to schedule: Quick, Standard, or Full (default: Standard).
+ Mapped to Invoke-SecurityAssessment as Quick=Basic, Standard=Standard, Full=Advanced.
+ .PARAMETER Frequency
+ How often the scan runs: Daily, Weekly (Monday), or Monthly (1st of month) (default: Weekly)
+ .PARAMETER Time
+ Time of day to run the scan, as a datetime or string such as '09:00' (default: 09:00)
+ .PARAMETER OutputPath
+ Path where the scan script and per-run reports are stored
+ (default: "$env:ProgramData\WindowsSecurityAudit\Scans")
+ .PARAMETER WebhookUrl
+ Optional incoming webhook URL (Microsoft Teams or Slack style) that receives
+ an adaptive-card JSON POST when Critical findings exist
+ .PARAMETER EmailTo
+ Optional recipient address for email alerts (requires EmailFrom and SmtpServer)
+ .PARAMETER EmailFrom
+ Optional sender address for email alerts (requires EmailTo and SmtpServer)
+ .PARAMETER SmtpServer
+ Optional SMTP server for email alerts (requires EmailTo and EmailFrom)
+ .PARAMETER Unregister
+ Removes the scheduled security scan task and exits without registering anything
+ .PARAMETER WhatIf
+ Shows what would happen if the command runs (SupportsShouldProcess)
+ .PARAMETER Confirm
+ Prompts for confirmation before registering or unregistering the task
+ .EXAMPLE
+ Register-ScheduledSecurityScan -ScanType Standard -Frequency Weekly -Time '09:00'
+ Registers a weekly (Monday 09:00) Standard scan running as SYSTEM
+ .EXAMPLE
+ Register-ScheduledSecurityScan -ScanType Full -Frequency Daily -Time '22:30' -WebhookUrl 'https://outlook.office.com/webhook/...'
+ Registers a nightly Full scan that posts an adaptive card to a Teams webhook on Critical findings
+ .EXAMPLE
+ Register-ScheduledSecurityScan -ScanType Quick -Frequency Monthly -EmailTo [email protected] -EmailFrom [email protected] -SmtpServer smtp.contoso.com
+ Registers a monthly Quick scan that emails an alert when Critical findings exist
+ .EXAMPLE
+ Register-ScheduledSecurityScan -Unregister -Confirm:$false
+ Removes the scheduled security scan task
+ .OUTPUTS
+ PSCustomObject with the registration (or unregistration) result
+ #>
+
+ [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
+ param(
+ [Parameter()]
+ [ValidateSet('Quick', 'Standard', 'Full')]
+ [string]$ScanType = 'Standard',
+
+ [Parameter()]
+ [ValidateSet('Daily', 'Weekly', 'Monthly')]
+ [string]$Frequency = 'Weekly',
+
+ [Parameter()]
+ [datetime]$Time = '09:00',
+
+ [Parameter()]
+ [string]$OutputPath = "$env:ProgramData\WindowsSecurityAudit\Scans",
+
+ [Parameter()]
+ [string]$WebhookUrl,
+
+ [Parameter()]
+ [string]$EmailTo,
+
+ [Parameter()]
+ [string]$EmailFrom,
+
+ [Parameter()]
+ [string]$SmtpServer,
+
+ [Parameter()]
+ [switch]$Unregister
+ )
+
+ begin {
+ Write-Host "=== SCHEDULED SECURITY SCAN REGISTRATION ===" -ForegroundColor Cyan
+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow
+
+ $taskName = 'WindowsSecurityAudit-ScheduledScan'
+ $machineName = [System.Environment]::MachineName
+ $scanResult = $null
+
+ # Resolve the module manifest so the generated script can import it standalone
+ $moduleRoot = Split-Path -Path $PSScriptRoot -Parent
+ $moduleManifest = Join-Path $moduleRoot 'WindowsSecurityAudit.psd1'
+ if (-not (Test-Path $moduleManifest)) {
+ Write-Warning "Module manifest not found at '$moduleManifest'. The generated script may fail to import the module."
+ }
+
+ # Map the public scan type to the Invoke-SecurityAssessment assessment type
+ $assessmentType = switch ($ScanType) {
+ 'Quick' { 'Basic' }
+ 'Standard' { 'Standard' }
+ 'Full' { 'Advanced' }
+ }
+
+ # Email alerting requires the full triplet
+ $emailPartsProvided = @($EmailTo, $EmailFrom, $SmtpServer | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }).Count
+ $emailConfigured = ($emailPartsProvided -eq 3)
+ if ($emailPartsProvided -gt 0 -and -not $emailConfigured) {
+ Write-Warning "Email alerting requires EmailTo, EmailFrom, and SmtpServer together. Email alerts will be disabled."
+ }
+
+ $webhookConfigured = (-not [string]::IsNullOrWhiteSpace($WebhookUrl))
+ }
+
+ process {
+ # ----- Unregister path: remove the task and exit -----
+ if ($Unregister) {
+ Write-Host "`nRemoving scheduled security scan..." -ForegroundColor Cyan
+
+ try {
+ $existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
+
+ if ($null -eq $existingTask) {
+ Write-Warning "Scheduled task '$taskName' was not found - nothing to remove."
+ $scanResult = [PSCustomObject]@{
+ ActionDate = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
+ TaskName = $taskName
+ Action = 'Unregister'
+ Status = 'NotFound'
+ ComputerName = $machineName
+ }
+ return
+ }
+
+ if ($PSCmdlet.ShouldProcess($machineName, "Unregister scheduled task '$taskName'")) {
+ Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction Stop
+ Write-Host "Scheduled task '$taskName' removed." -ForegroundColor Green
+ $scanResult = [PSCustomObject]@{
+ ActionDate = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
+ TaskName = $taskName
+ Action = 'Unregister'
+ Status = 'Unregistered'
+ ComputerName = $machineName
+ }
+ }
+ else {
+ $scanResult = [PSCustomObject]@{
+ ActionDate = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
+ TaskName = $taskName
+ Action = 'Unregister'
+ Status = 'WhatIf'
+ ComputerName = $machineName
+ }
+ }
+ }
+ catch {
+ Write-Error "Failed to unregister scheduled task '$taskName': $_"
+ throw
+ }
+
+ return
+ }
+
+ # ----- Registration path -----
+ Write-Host "`nScan Type: $ScanType ($assessmentType assessment)" -ForegroundColor Yellow
+ Write-Host "Frequency: $Frequency at $($Time.ToString('HH:mm'))" -ForegroundColor Yellow
+ Write-Host "Output Path: $OutputPath" -ForegroundColor Yellow
+ Write-Host "Webhook Alerts: $webhookConfigured" -ForegroundColor Yellow
+ Write-Host "Email Alerts: $emailConfigured" -ForegroundColor Yellow
+
+ $scriptPath = Join-Path $OutputPath 'Invoke-ScheduledSecurityScan.ps1'
+
+ # Escape single quotes in values embedded into the generated script
+ $safeModuleManifest = if ($null -ne $moduleManifest) { $moduleManifest -replace "'", "''" } else { '' }
+ $safeOutputPath = if ($null -ne $OutputPath) { $OutputPath -replace "'", "''" } else { '' }
+ $safeWebhookUrl = if ($webhookConfigured) { $WebhookUrl -replace "'", "''" } else { '' }
+ $safeEmailTo = if ($emailConfigured) { $EmailTo -replace "'", "''" } else { '' }
+ $safeEmailFrom = if ($emailConfigured) { $EmailFrom -replace "'", "''" } else { '' }
+ $safeSmtpServer = if ($emailConfigured) { $SmtpServer -replace "'", "''" } else { '' }
+
+ $scanScriptTemplate = @'
+# ============================================================================
+# WindowsSecurityAudit - Scheduled Security Scan
+# Generated by Register-ScheduledSecurityScan on __GENERATED_ON__
+# Re-run Register-ScheduledSecurityScan to modify this script.
+# Run Register-ScheduledSecurityScan -Unregister to remove the scheduled task.
+# ============================================================================
+
+$ErrorActionPreference = 'Continue'
+
+$modulePath = '__MODULE_PATH__'
+$scanOutputRoot = '__OUTPUT_PATH__'
+$assessmentType = '__ASSESSMENT_TYPE__'
+$webhookUrl = '__WEBHOOK_URL__'
+$emailTo = '__EMAIL_TO__'
+$emailFrom = '__EMAIL_FROM__'
+$smtpServer = '__SMTP_SERVER__'
+
+$runStamp = Get-Date -Format 'yyyyMMdd_HHmmss'
+$runPath = Join-Path $scanOutputRoot "Scan_$runStamp"
+
+try {
+ if (-not (Test-Path $runPath)) {
+ New-Item -Path $runPath -ItemType Directory -Force | Out-Null
+ }
+
+ Import-Module $modulePath -Force -ErrorAction Stop
+
+ $assessment = Invoke-SecurityAssessment -AssessmentType $assessmentType -OutputPath $runPath
+
+ $findings = @()
+ if ($null -ne $assessment -and $null -ne $assessment.PSObject.Properties['Findings'] -and $null -ne $assessment.Findings) {
+ $findings = @($assessment.Findings)
+ }
+
+ $criticalFindings = @($findings | Where-Object { $_.Severity -eq 'Critical' })
+ $highFindings = @($findings | Where-Object { $_.Severity -eq 'High' })
+
+ $overallScore = 'N/A'
+ if ($null -ne $assessment -and $null -ne $assessment.PSObject.Properties['OverallScore'] -and $null -ne $assessment.OverallScore) {
+ $overallScore = "$($assessment.OverallScore)"
+ }
+
+ $runSummary = [PSCustomObject]@{
+ ComputerName = $env:COMPUTERNAME
+ RunDate = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
+ AssessmentType = $assessmentType
+ OverallScore = $overallScore
+ TotalFindings = $findings.Count
+ CriticalFindings = $criticalFindings.Count
+ HighFindings = $highFindings.Count
+ ReportPath = $runPath
+ AlertSent = $false
+ }
+
+ if ($criticalFindings.Count -gt 0) {
+ # ---------- Webhook alert (Teams/Slack-style incoming webhook) ----------
+ if (-not [string]::IsNullOrWhiteSpace($webhookUrl)) {
+ try {
+ $factBlocks = @($criticalFindings | ForEach-Object {
+ $cat = ''
+ $txt = ''
+ if ($null -ne $_.PSObject.Properties['Category']) { $cat = "$($_.Category)" }
+ if ($null -ne $_.PSObject.Properties['Finding']) { $txt = "$($_.Finding)" }
+ @{ title = $cat; value = $txt }
+ })
+
+ $payload = @{
+ type = 'message'
+ attachments = @(
+ @{
+ contentType = 'application/vnd.microsoft.card.adaptive'
+ content = @{
+ '$schema' = 'http://adaptivecards.io/schemas/adaptive-card.json'
+ type = 'AdaptiveCard'
+ version = '1.2'
+ body = @(
+ @{ type = 'TextBlock'; size = 'Large'; weight = 'Bolder'; color = 'Attention'; text = "CRITICAL Security Findings - $env:COMPUTERNAME" }
+ @{ type = 'TextBlock'; text = "Scheduled $assessmentType security scan completed with $($criticalFindings.Count) critical finding(s)."; wrap = $true }
+ @{ type = 'FactSet'; facts = @(
+ @{ title = 'Computer'; value = "$env:COMPUTERNAME" }
+ @{ title = 'Scan Time'; value = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss') }
+ @{ title = 'Overall Score'; value = $overallScore }
+ @{ title = 'Critical'; value = "$($criticalFindings.Count)" }
+ @{ title = 'High'; value = "$($highFindings.Count)" }
+ @{ title = 'Report'; value = "$runPath" }
+ ) + $factBlocks }
+ @{ type = 'TextBlock'; text = 'Review the full report and remediate the critical findings as soon as possible.'; wrap = $true }
+ )
+ }
+ }
+ )
+ }
+
+ $jsonBody = $payload | ConvertTo-Json -Depth 12
+ Invoke-RestMethod -Uri $webhookUrl -Method Post -Body $jsonBody -ContentType 'application/json; charset=utf-8' -ErrorAction Stop
+ $runSummary.AlertSent = $true
+ }
+ catch {
+ Write-Warning "Failed to send webhook alert: $($_.Exception.Message)"
+ }
+ }
+
+ # ---------- Email alert ----------
+ if (-not [string]::IsNullOrWhiteSpace($emailTo) -and -not [string]::IsNullOrWhiteSpace($emailFrom) -and -not [string]::IsNullOrWhiteSpace($smtpServer)) {
+ try {
+ $mailRows = ($criticalFindings | ForEach-Object {
+ $cat = ''
+ $txt = ''
+ if ($null -ne $_.PSObject.Properties['Category']) { $cat = "$($_.Category)" }
+ if ($null -ne $_.PSObject.Properties['Finding']) { $txt = "$($_.Finding)" }
+ "<tr><td style='padding:6px;border:1px solid #ccc;'>$cat</td><td style='padding:6px;border:1px solid #ccc;'>$txt</td></tr>"
+ }) -join "`n"
+
+ $mailBody = @"
+<html><body style='font-family:Arial;'>
+<h2 style='color:#c00;'>Critical Security Findings - $env:COMPUTERNAME</h2>
+<p>Scheduled <b>$assessmentType</b> scan on <b>$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')</b> found <b>$($criticalFindings.Count)</b> critical and <b>$($highFindings.Count)</b> high finding(s). Overall score: <b>$overallScore</b>.</p>
+<table style='border-collapse:collapse;'>
+<tr><th style='padding:6px;border:1px solid #ccc;background:#333;color:#fff;'>Category</th><th style='padding:6px;border:1px solid #ccc;background:#333;color:#fff;'>Finding</th></tr>
+$mailRows
+</table>
+<p>Full report: $runPath</p>
+</body></html>
+"@
+
+ Send-MailMessage -To $emailTo -From $emailFrom -SmtpServer $smtpServer -Subject "[SECURITY ALERT] $($criticalFindings.Count) critical finding(s) on $env:COMPUTERNAME" -Body $mailBody -BodyAsHtml -Encoding UTF8 -ErrorAction Stop
+ $runSummary.AlertSent = $true
+ }
+ catch {
+ Write-Warning "Failed to send email alert: $($_.Exception.Message)"
+ }
+ }
+ }
+
+ $runSummary | ConvertTo-Json -Depth 5 | Out-File (Join-Path $runPath 'RunSummary.json') -Encoding UTF8
+}
+catch {
+ try {
+ if (-not (Test-Path $scanOutputRoot)) {
+ New-Item -Path $scanOutputRoot -ItemType Directory -Force | Out-Null
+ }
+ [PSCustomObject]@{
+ ComputerName = $env:COMPUTERNAME
+ RunDate = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
+ Status = 'Failed'
+ Error = $_.Exception.Message
+ } | ConvertTo-Json | Out-File (Join-Path $scanOutputRoot "ScanError_$runStamp.json") -Encoding UTF8
+ }
+ catch {
+ # Best-effort error persistence only
+ }
+ exit 1
+}
+
+exit 0
+'@
+
+ if ($PSCmdlet.ShouldProcess($machineName, "Register scheduled security scan '$taskName' ($Frequency at $($Time.ToString('HH:mm')))")) {
+ # Section 1: Create the scan script
+ try {
+ Write-Host "`nCreating scan script..." -ForegroundColor Cyan
+
+ if (-not (Test-Path $OutputPath)) {
+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null
+ }
+
+ $scanScript = $scanScriptTemplate.
+ Replace('__GENERATED_ON__', (Get-Date -Format 'yyyy-MM-dd HH:mm:ss')).
+ Replace('__MODULE_PATH__', $safeModuleManifest).
+ Replace('__OUTPUT_PATH__', $safeOutputPath).
+ Replace('__ASSESSMENT_TYPE__', $assessmentType).
+ Replace('__WEBHOOK_URL__', $safeWebhookUrl).
+ Replace('__EMAIL_TO__', $safeEmailTo).
+ Replace('__EMAIL_FROM__', $safeEmailFrom).
+ Replace('__SMTP_SERVER__', $safeSmtpServer)
+
+ $scanScript | Out-File $scriptPath -Encoding UTF8 -Force
+ Write-Host "Scan script created: $scriptPath" -ForegroundColor Green
+ }
+ catch {
+ Write-Error "Failed to create scan script at '$scriptPath': $_"
+ throw
+ }
+
+ # Section 2: Register the scheduled task
+ try {
+ Write-Host "`nRegistering scheduled task..." -ForegroundColor Cyan
+
+ $trigger = $null
+ switch ($Frequency) {
+ 'Daily' {
+ $trigger = New-ScheduledTaskTrigger -Daily -At $Time
+ }
+ 'Weekly' {
+ $trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Monday -At $Time
+ }
+ 'Monthly' {
+ # New-ScheduledTaskTrigger has no -Monthly in PS 5.1; build the CIM trigger directly
+ $triggerClass = Get-CimClass -ClassName 'MSFT_TaskMonthlyTrigger' -Namespace 'Root\Microsoft\Windows\TaskScheduler' -ErrorAction Stop
+ $trigger = New-CimInstance -CimClass $triggerClass -ClientOnly -Property @{
+ DaysOfMonth = 1
+ MonthsOfYear = 4095
+ StartBoundary = $Time.ToString("yyyy-MM-dd'T'HH:mm:ss")
+ Enabled = $true
+ } -ErrorAction Stop
+ }
+ }
+
+ $actionArgs = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$scriptPath`""
+ $action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument $actionArgs
+ $principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel Highest
+ $settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
+
+ $frequencyNote = switch ($Frequency) {
+ 'Daily' { 'every day' }
+ 'Weekly' { 'every Monday' }
+ 'Monthly' { 'on the 1st of every month' }
+ }
+ $taskDescription = "WindowsSecurityAudit $ScanType scan ($assessmentType) runs $frequencyNote at $($Time.ToString('HH:mm')). Alerts on Critical findings. Managed by Register-ScheduledSecurityScan."
+
+ Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description $taskDescription -Force -ErrorAction Stop | Out-Null
+
+ Write-Host "Scheduled task '$taskName' registered (runs as SYSTEM)." -ForegroundColor Green
+ }
+ catch {
+ Write-Error "Failed to register scheduled task '$taskName': $_"
+ throw
+ }
+
+ $scanResult = [PSCustomObject]@{
+ RegistrationDate = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
+ TaskName = $taskName
+ Action = 'Register'
+ Status = 'Registered'
+ ComputerName = $machineName
+ ScanType = $ScanType
+ AssessmentType = $assessmentType
+ Frequency = $Frequency
+ ScheduledTime = $Time.ToString('HH:mm')
+ RunAs = 'SYSTEM'
+ ScriptPath = $scriptPath
+ OutputPath = $OutputPath
+ WebhookAlertEnabled = $webhookConfigured
+ EmailAlertEnabled = $emailConfigured
+ }
+ }
+ else {
+ $scanResult = [PSCustomObject]@{
+ RegistrationDate = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
+ TaskName = $taskName
+ Action = 'Register'
+ Status = 'WhatIf'
+ ComputerName = $machineName
+ ScanType = $ScanType
+ AssessmentType = $assessmentType
+ Frequency = $Frequency
+ ScheduledTime = $Time.ToString('HH:mm')
+ RunAs = 'SYSTEM'
+ ScriptPath = $scriptPath
+ OutputPath = $OutputPath
+ WebhookAlertEnabled = $webhookConfigured
+ EmailAlertEnabled = $emailConfigured
+ }
+ }
+ }
+
+ end {
+ if ($null -ne $scanResult) {
+ Write-Host "`n=== REGISTRATION COMPLETE ===" -ForegroundColor Green
+ Write-Host "Task Name: $($scanResult.TaskName)" -ForegroundColor Cyan
+ Write-Host "Action: $($scanResult.Action)" -ForegroundColor Cyan
+ Write-Host "Status: $($scanResult.Status)" -ForegroundColor $(if ($scanResult.Status -in @('Registered', 'Unregistered')) { 'Green' } else { 'Yellow' })
+
+ if ($null -ne $scanResult.PSObject.Properties['Frequency'] -and $scanResult.Action -eq 'Register') {
+ Write-Host "Schedule: $($scanResult.Frequency) at $($scanResult.ScheduledTime)" -ForegroundColor Cyan
+ Write-Host "Script: $($scanResult.ScriptPath)" -ForegroundColor Cyan
+ Write-Host "Reports: $($scanResult.OutputPath)" -ForegroundColor Cyan
+
+ if ($scanResult.Status -eq 'Registered' -and -not $scanResult.WebhookAlertEnabled -and -not $scanResult.EmailAlertEnabled) {
+ Write-Warning "No alerting configured. Critical findings will be logged but no webhook or email alert will be sent."
+ }
+ }
+
+ return $scanResult
+ }
+ }
+}
diff --git a/Forensics/Export-MemoryDump.ps1 b/Forensics/Export-MemoryDump.ps1
index f3920c9..c634e46 100644
--- a/Forensics/Export-MemoryDump.ps1
+++ b/Forensics/Export-MemoryDump.ps1
@@ -56,9 +56,7 @@ function Export-MemoryDump {
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
- Write-Warning "This function requires Administrator privileges!"
- Write-Host "Please run PowerShell as Administrator and try again." -ForegroundColor Red
- return
+ throw "This function requires Administrator privileges!"
}
# Create output directory
diff --git a/Forensics/Get-ArtifactCollection.ps1 b/Forensics/Get-ArtifactCollection.ps1
index a12f743..b1e41fc 100644
--- a/Forensics/Get-ArtifactCollection.ps1
+++ b/Forensics/Get-ArtifactCollection.ps1
@@ -386,7 +386,7 @@ function Get-ArtifactCollection {
ConvertTo-Json | Out-File (Join-Path $paths.Execution "Services.json")
# Scheduled tasks
- Get-ScheduledTask | Select-Object TaskName, TaskPath, State, @{N='LastRunTime';E={$_.LastRunTime}} |
+ Get-ScheduledTask | Select-Object TaskName, TaskPath, State, @{N='LastRunTime';E={($_ | Get-ScheduledTaskInfo).LastRunTime}} |
ConvertTo-Json | Out-File (Join-Path $paths.Execution "ScheduledTasks.json")
# Startup programs
@@ -433,7 +433,7 @@ function Get-ArtifactCollection {
# CALCULATE COLLECTION SIZE
Write-Host "`n[*] Calculating collection statistics..." -ForegroundColor Cyan
- $collectedFiles = Get-ChildItem -Path $collectionRoot -Recurse -File -ErrorAction SilentlyContinue
+ $collectedFiles = @(Get-ChildItem -Path $collectionRoot -Recurse -File -ErrorAction SilentlyContinue)
$results.Summary.TotalFiles = $collectedFiles.Count
$results.Summary.TotalSize = ($collectedFiles | Measure-Object -Property Length -Sum).Sum
diff --git a/Forensics/Get-ExecutionArtifacts.ps1 b/Forensics/Get-ExecutionArtifacts.ps1
index 7d40bc9..f412658 100644
--- a/Forensics/Get-ExecutionArtifacts.ps1
+++ b/Forensics/Get-ExecutionArtifacts.ps1
@@ -90,7 +90,7 @@ function Get-ExecutionArtifacts {
$prefetchPath = "$env:SystemRoot\Prefetch"
if (Test-Path $prefetchPath) {
- $prefetchFiles = Get-ChildItem -Path $prefetchPath -Filter "*.pf" -ErrorAction SilentlyContinue
+ $prefetchFiles = @(Get-ChildItem -Path $prefetchPath -Filter "*.pf" -ErrorAction SilentlyContinue)
foreach ($file in $prefetchFiles) {
# Extract executable name from prefetch filename (format: EXECUTABLE-HASH.pf)
@@ -334,7 +334,7 @@ function Get-ExecutionArtifacts {
}
else {
# Try DAM (older Windows 10)
- $damPath = 'HKLM:\SYSTEM\CurrentControlSet\Services\dam\State\UserSettings'
+ $damPath = 'HKLM:\SYSTEM\CurrentControlSet\Services\dam\UserSettings'
if (Test-Path $damPath) {
Write-Host " DAM found (older Windows 10 version)" -ForegroundColor Gray
@@ -354,8 +354,8 @@ function Get-ExecutionArtifacts {
$results.Summary.TotalArtifacts = $results.Artifacts.Count
# Sort artifacts by timestamp
- $results.Artifacts = $results.Artifacts |
- Sort-Object Timestamp -Descending
+ $results.Artifacts = @($results.Artifacts |
+ Sort-Object Timestamp -Descending)
# 6. EXPORT REPORTS
if ($OutputPath) {
diff --git a/Forensics/Get-USBHistory.ps1 b/Forensics/Get-USBHistory.ps1
index fff335c..59a996e 100644
--- a/Forensics/Get-USBHistory.ps1
+++ b/Forensics/Get-USBHistory.ps1
@@ -151,7 +151,7 @@ function Get-USBHistory {
if (-not $alreadyExists -and $props.FriendlyName) {
# Parse VID/PID from device name (e.g., "VID_046D&PID_C52B")
$vid = if ($usbDevice.PSChildName -match 'VID_([0-9A-F]+)') { $matches[1] } else { 'Unknown' }
- $pid = if ($usbDevice.PSChildName -match 'PID_([0-9A-F]+)') { $matches[1] } else { 'Unknown' }
+ $devicePid = if ($usbDevice.PSChildName -match 'PID_([0-9A-F]+)') { $matches[1] } else { 'Unknown' }
# FIXED: Safe timestamp retrieval from registry properties
$installDate = $null
@@ -171,7 +171,7 @@ function Get-USBHistory {
Type = 'USB Device'
FriendlyName = $props.FriendlyName
Vendor = "VID_$vid"
- Product = "PID_$pid"
+ Product = "PID_$devicePid"
Revision = 'N/A'
SerialNumber = $serialNumber
FirstInstalled = $installDate
@@ -182,7 +182,7 @@ function Get-USBHistory {
$results.USBDevices += $deviceInfo
$results.Summary.OtherDevices++
- Write-Host " Found: $($props.FriendlyName) (VID_$vid PID_$pid)" -ForegroundColor Gray
+ Write-Host " Found: $($props.FriendlyName) (VID_$vid PID_$devicePid)" -ForegroundColor Gray
}
}
catch {
@@ -255,9 +255,9 @@ function Get-USBHistory {
$setupApiPath = "$env:SystemRoot\inf\setupapi.dev.log"
if (Test-Path $setupApiPath) {
- $setupContent = Get-Content $setupApiPath -ErrorAction SilentlyContinue |
+ $setupContent = @(Get-Content $setupApiPath -ErrorAction SilentlyContinue |
Select-String -Pattern "USB|USBSTOR" -Context 0,2 |
- Select-Object -First 100
+ Select-Object -First 100)
$usbEntries = $setupContent.Count
Write-Host " Found $usbEntries USB-related entries in SetupAPI log" -ForegroundColor Green
@@ -288,8 +288,8 @@ function Get-USBHistory {
$results.Summary.TotalDevices = $results.USBDevices.Count
# Sort devices by last connection (those with dates first)
- $results.USBDevices = $results.USBDevices |
- Sort-Object @{Expression={if($_.LastConnected){$_.LastConnected}else{[DateTime]::MinValue}}; Descending=$true}
+ $results.USBDevices = @($results.USBDevices |
+ Sort-Object @{Expression={if($_.LastConnected){$_.LastConnected}else{[DateTime]::MinValue}}; Descending=$true})
# 5. EXPORT REPORTS
if ($OutputPath) {
diff --git a/Forensics/New-ForensicTimeline.ps1 b/Forensics/New-ForensicTimeline.ps1
index 00d8a84..bb395a1 100644
--- a/Forensics/New-ForensicTimeline.ps1
+++ b/Forensics/New-ForensicTimeline.ps1
@@ -103,11 +103,11 @@ function New-ForensicTimeline {
try {
Write-Host " Scanning: $logName..." -ForegroundColor Gray
- $events = Get-WinEvent -FilterHashtable @{
+ $events = @(Get-WinEvent -FilterHashtable @{
LogName = $logName
StartTime = $StartTime
EndTime = $EndTime
- } -ErrorAction SilentlyContinue -MaxEvents 1000
+ } -ErrorAction SilentlyContinue -MaxEvents 1000)
foreach ($event in $events) {
# FIXED: Safe message handling with null check
@@ -306,7 +306,7 @@ function New-ForensicTimeline {
# 5. SORT AND FINALIZE TIMELINE
Write-Host "`n[*] Sorting timeline events..." -ForegroundColor Cyan
- $timeline.Events = $timeline.Events | Sort-Object Timestamp -Descending
+ $timeline.Events = @($timeline.Events | Sort-Object Timestamp -Descending)
$timeline.Summary.TotalEvents = $timeline.Events.Count
Write-Host " Total events in timeline: $($timeline.Summary.TotalEvents)" -ForegroundColor Green
diff --git a/Hardening/Enable-AuditPolicies.ps1 b/Hardening/Enable-AuditPolicies.ps1
index 6a9826a..f178a40 100644
--- a/Hardening/Enable-AuditPolicies.ps1
+++ b/Hardening/Enable-AuditPolicies.ps1
@@ -104,10 +104,8 @@ function Enable-AuditPolicies {
foreach ($subcategory in $selectedSettings[$category]) {
try {
# Enable both Success and Failure auditing
- $auditCommand = "auditpol /set /subcategory:`"$subcategory`" /success:enable /failure:enable"
-
if ($PSCmdlet.ShouldProcess($subcategory, "Enable audit policy")) {
- $result = Invoke-Expression $auditCommand 2>&1
+ $result = & auditpol /set /subcategory:"$subcategory" /success:enable /failure:enable 2>&1
if ($LASTEXITCODE -eq 0) {
$results.PoliciesConfigured += $subcategory
diff --git a/Hardening/Set-SecurityBaseline.ps1 b/Hardening/Set-SecurityBaseline.ps1
index 39a3b99..92ee4a3 100644
--- a/Hardening/Set-SecurityBaseline.ps1
+++ b/Hardening/Set-SecurityBaseline.ps1
@@ -54,13 +54,13 @@ function Set-SecurityBaseline {
Errors = @()
RequiresReboot = $false
Categories = @{
- UAC = @{}
- Firewall = @{}
- WindowsDefender = @{}
- NetworkSecurity = @{}
- AccountSecurity = @{}
- SystemSecurity = @{}
- BitLocker = @{}
+ UAC = @{ Status = 'Not Configured' }
+ Firewall = @{ Status = 'Not Configured' }
+ WindowsDefender = @{ Status = 'Not Configured' }
+ NetworkSecurity = @{ Status = 'Not Configured' }
+ AccountSecurity = @{ Status = 'Not Configured' }
+ SystemSecurity = @{ Status = 'Not Configured' }
+ BitLocker = @{ Status = 'Not Configured' }
}
}
}
diff --git a/README.md b/README.md
index e8af471..32d3d5f 100644
--- a/README.md
+++ b/README.md
@@ -5,9 +5,11 @@
[![PowerShell](https://img.shields.io/badge/PowerShell-5.1%2B-blue.svg)](https://github.com/PowerShell/PowerShell)
[![Windows](https://img.shields.io/badge/Windows-10%2F11%2FServer%202016%2B-blue.svg)](https://www.microsoft.com/windows)
[![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
-[![Version](https://img.shields.io/badge/Version-1.0.0-orange.svg)](https://github.com/okanyildiz/WindowsSecurityAudit/releases)
-[![Functions](https://img.shields.io/badge/Functions-58-brightgreen.svg)](https://github.com/okanyildiz/WindowsSecurityAudit)
+[![Version](https://img.shields.io/badge/Version-1.1.0-orange.svg)](https://github.com/okanyildiz/WindowsSecurityAudit/releases)
+[![Functions](https://img.shields.io/badge/Functions-62-brightgreen.svg)](https://github.com/okanyildiz/WindowsSecurityAudit)
[![Modules](https://img.shields.io/badge/Modules-14-blue.svg)](https://github.com/okanyildiz/WindowsSecurityAudit)
+[![CI](https://github.com/okanyildiz/WindowsSecurityAudit/actions/workflows/ci.yml/badge.svg)](https://github.com/okanyildiz/WindowsSecurityAudit/actions/workflows/ci.yml)
+[![Tests](https://img.shields.io/badge/Tests-318%20Passed-brightgreen.svg)](https://github.com/okanyildiz/WindowsSecurityAudit/blob/main/tests/WindowsSecurityAudit.Tests.ps1)
[![Downloads](https://img.shields.io/badge/Downloads-50K%2B-success.svg)](https://github.com/okanyildiz/WindowsSecurityAudit)
[![GitHub stars](https://img.shields.io/github/stars/okanyildiz/WindowsSecurityAudit)](https://github.com/okanyildiz/WindowsSecurityAudit/stargazers)
@@ -18,12 +20,38 @@
**🎯 Zero Dependencies • 🚀 Production Ready • 🌍 Community Driven • 💼 Enterprise Tested**
-[Features](#-why-windows-security-audit-module) • [Installation](#-installation) • [Quick Start](#-quick-start) • [Support](#-support--contact)
+[What's New](#-whats-new-in-v110) • [Features](#-why-windows-security-audit-module) • [Installation](#-installation) • [Quick Start](#-quick-start) • [Support](#-support--contact)
</div>
---
+## ✨ What's New in v1.1.0
+
+**4 new functions** — bringing the toolkit to **62 functions across 14 modules**:
+
+| Function | Module | What It Does |
+|----------|--------|--------------|
+| **`Compare-SecurityBaseline`** | Core | Detect configuration drift by diffing two security baselines — Improved/Degraded/New/Removed classification with JSON/CSV export |
+| **`Register-ScheduledSecurityScan`** | Enterprise | Automate recurring scans (daily/weekly/monthly) via Scheduled Tasks with **Teams/Slack webhook** and email alerting on Critical findings |
+| **`Export-AttackNavigatorLayer`** | Threat Hunting | Export hunt findings as a **MITRE ATT&CK Navigator layer** (JSON v4.x) with severity-based scoring and colors — visualize coverage in one click |
+| **`New-ConsolidatedReport`** | Reporting | Generate a **single interactive Chart.js HTML report** combining results from all modules, with offline mode from saved JSON |
+
+**Wired-up parameters on existing functions:**
+
+- `Invoke-SecurityAssessment -IncludeCompliance` — now runs CIS, NIST 800-53, and PCI-DSS checks as part of the assessment
+- `Get-ExposedServices -CustomPorts` — scan your own port list beyond the built-in attack-surface checks
+- `Get-ComplianceReport -IncludeEvidence` — bundle audit-ready evidence directly into compliance reports
+- `New-ExecutiveReport -CustomLogo` — brand executive reports with your organization's logo
+- `Export-SecurityReport -IncludeCharts` — embed visual charts in exported reports
+
+**Quality infrastructure:**
+
+- 🧪 **318 Pester tests** (`tests/WindowsSecurityAudit.Tests.ps1`) covering the public API surface
+- ⚙️ **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
+
+---
+
## ☕ Support This Project
If you find this tool valuable for your security operations, consider supporting its development:
@@ -43,7 +71,7 @@ If you find this tool valuable for your security operations, consider supporting
In today's rapidly evolving threat landscape, organizations face unprecedented challenges in maintaining robust security postures across their Windows infrastructure. Traditional security tools often fall short, requiring multiple expensive licenses, complex integrations, and specialized expertise. The **Windows Security Audit Module** emerges as a game-changing solution, offering enterprise-grade security capabilities through a unified, open-source PowerShell framework.
-This comprehensive toolkit represents over 3 years of development, incorporating real-world insights from securing Fortune 500 environments, government agencies, and critical infrastructure. With 58 meticulously crafted functions organized into 14 specialized modules, it delivers capabilities typically found only in solutions costing $50,000+ annually - completely free and open source.
+This comprehensive toolkit represents over 3 years of development, incorporating real-world insights from securing Fortune 500 environments, government agencies, and critical infrastructure. With 62 meticulously crafted functions organized into 14 specialized modules, it delivers capabilities typically found only in solutions costing $50,000+ annually - completely free and open source.
### 🎯 The Vision
@@ -93,7 +121,7 @@ A single, cohesive PowerShell module that consolidates essential security functi
</tr>
<tr>
<td><strong>Functions</strong></td>
-<td>✅ 58 Comprehensive</td>
+<td>✅ 62 Comprehensive</td>
<td>⚠️ 20-30 Limited</td>
<td>⚠️ 5-15 Basic</td>
</tr>
@@ -141,6 +169,9 @@ WindowsSecurityAudit/
├── 📄 CreateProjectFolderStructure.ps1 # Setup script
├── 📄 Test-Module.ps1 # Testing script
│
+├── 📁 .github/workflows/ # CI: PSScriptAnalyzer + Pester (PS 5.1 & 7)
+│ └── ci.yml
+│
├── 📁 ActiveDirectory/ # AD Security (6 functions)
│ ├── Find-ADBackdoors.ps1
│ ├── Find-ADVulnerabilities.ps1
@@ -167,7 +198,8 @@ WindowsSecurityAudit/
│ ├── Test-NISTCompliance.ps1
│ └── Test-PCI-DSS.ps1
│
-├── 📁 Core/ # Core Security (4 functions)
+├── 📁 Core/ # Core Security (5 functions)
+│ ├── Compare-SecurityBaseline.ps1
│ ├── Get-EventIdDescription.ps1
│ ├── Get-SecurityBaseline.ps1
│ ├── Get-SystemInfo.ps1
@@ -179,10 +211,11 @@ WindowsSecurityAudit/
│ ├── Find-SuspiciousAuthentication.ps1
│ └── Find-SuspiciousProcesses.ps1
│
-├── 📁 Enterprise/ # Enterprise (3 functions)
+├── 📁 Enterprise/ # Enterprise (4 functions)
│ ├── Get-MultiSystemAudit.ps1
│ ├── Invoke-EnterpriseSecurityScan.ps1
-│ └── Invoke-SecurityAssessment.ps1
+│ ├── Invoke-SecurityAssessment.ps1
+│ └── Register-ScheduledSecurityScan.ps1
│
├── 📁 Forensics/ # Digital Forensics (5 functions)
│ ├── Export-MemoryDump.ps1
@@ -198,8 +231,9 @@ WindowsSecurityAudit/
│
├── 📁 Private/ # Internal functions (hidden)
│
-├── 📁 Reporting/ # Reporting (3 functions)
+├── 📁 Reporting/ # Reporting (4 functions)
│ ├── Get-SecurityMetrics.ps1
+│ ├── New-ConsolidatedReport.ps1
│ ├── New-ExecutiveReport.ps1
│ └── New-SecurityDashboard.ps1
│
@@ -208,9 +242,11 @@ WindowsSecurityAudit/
│ ├── Invoke-ForensicCollection.ps1
│ └── Invoke-IncidentResponse.ps1
│
-├── 📁 Tests/ # Pester tests (in development)
+├── 📁 tests/ # Pester tests (318 tests)
+│ └── WindowsSecurityAudit.Tests.ps1
│
-├── 📁 ThreatHunting/ # Threat Hunting (6 functions)
+├── 📁 ThreatHunting/ # Threat Hunting (7 functions)
+│ ├── Export-AttackNavigatorLayer.ps1
│ ├── Find-APTIndicators.ps1
│ ├── Find-DataExfiltration.ps1
│ ├── Find-LateralMovement.ps1
@@ -267,7 +303,7 @@ Install-Module -Name WindowsSecurityAudit -Scope CurrentUser -Force
# Import the module
Import-Module WindowsSecurityAudit
-# Verify installation - should return 58
+# Verify installation - should return 62
(Get-Command -Module WindowsSecurityAudit).Count
```
@@ -286,19 +322,57 @@ Expand-Archive -Path $output -DestinationPath $modulePath -Force
Import-Module WindowsSecurityAudit -Force
```
-### Method 3: Git Clone (For Developers)
+### Method 3: Manual ZIP Download (GitHub "Download ZIP")
+```powershell
+# GitHub's "Code > Download ZIP" extracts to a folder named WindowsSecurityAudit-main.
+# PowerShell only finds modules by name if the folder is named EXACTLY 'WindowsSecurityAudit'
+# and sits inside a PSModulePath directory. Rename and move it:
+
+# For Windows PowerShell 5.1:
+$moduleDir = "$env:USERPROFILE\Documents\WindowsPowerShell\Modules"
+# For PowerShell 7.x:
+# $moduleDir = "$env:USERPROFILE\Documents\PowerShell\Modules"
+
+New-Item -Path $moduleDir -ItemType Directory -Force | Out-Null
+Move-Item ".\WindowsSecurityAudit-main" "$moduleDir\WindowsSecurityAudit" -Force
+
+# Unblock files downloaded from the internet (otherwise scripts may refuse to load)
+Get-ChildItem "$moduleDir\WindowsSecurityAudit" -Recurse | Unblock-File
+
+Import-Module WindowsSecurityAudit -Force
+```
+
+Alternatively, import directly by path from the extracted folder (no renaming needed):
+```powershell
+Import-Module ".\WindowsSecurityAudit-main\WindowsSecurityAudit.psd1" -Force
+```
+
+> **Note:** `Import-Module WindowsSecurityAudit` (by name) does NOT search the current
+> directory. It only searches the folders listed in `$env:PSModulePath`. Running it
+> from inside the extracted ZIP folder fails with "no valid module file was found in
+> any module directory" unless you use the path-based import shown above.
+
+### Method 4: Git Clone (For Developers)
```powershell
# Clone repository
git clone https://github.com/okanyildiz/WindowsSecurityAudit.git
cd WindowsSecurityAudit
-# Run setup script
-.\CreateProjectFolderStructure.ps1
+# Import the module directly from the clone
+Import-Module ".\WindowsSecurityAudit.psd1" -Force
-# Test module
+# Or run the smoke test
.\Test-Module.ps1
```
+### Troubleshooting
+- **"no valid module file was found in any module directory"** — the module folder is not
+ in `$env:PSModulePath`, or the folder is named `WindowsSecurityAudit-main` instead of
+ `WindowsSecurityAudit`. See Method 3.
+- **"running scripts is disabled on this system"** — set an execution policy for your user:
+ `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`
+- **Scripts blocked after ZIP download** — run `Get-ChildItem <module folder> -Recurse | Unblock-File`.
+
---
## 🚀 Quick Start
@@ -332,11 +406,31 @@ $report | Export-SecurityReport -Format HTML -Path "C:\SecurityReports"
Start-Process "C:\SecurityReports\SecurityReport.html"
```
+### One Report to Rule Them All (New in v1.1.0)
+```powershell
+# Collect results from ALL modules into a single interactive Chart.js HTML report
+New-ConsolidatedReport -OutputPath .\Report -OpenInBrowser
+
+# Air-gapped? Save the raw data once, rebuild the report later without rescanning
+New-ConsolidatedReport -OutputPath .\Report -SaveJson
+New-ConsolidatedReport -OutputPath .\Report -FromJsonPath .\Report\ConsolidatedReportData_20261025_093000.json
+```
+
+### Visualize Threats in MITRE ATT&CK Navigator (New in v1.1.0)
+```powershell
+# Hunt for persistence mechanisms, then pipe straight into a
+# Navigator layer with severity-based scoring and colors
+Find-PersistenceMechanisms | Export-AttackNavigatorLayer -OutputPath .\attack-layer.json
+
+# Import .\attack-layer.json at https://mitre-attack.github.io/attack-navigator/
+# to see exactly which techniques your findings cover — and where the gaps are
+```
+
---
## 📊 Module Categories - Detailed Breakdown
-### 1️⃣ Core Security Module (4 Functions)
+### 1️⃣ Core Security Module (5 Functions)
The Core module serves as the foundation of the entire security assessment framework. These functions provide essential baseline measurements and system integrity verification that other modules build upon. Every security assessment should begin with these core evaluations to establish a security context.
@@ -346,6 +440,7 @@ The Core module serves as the foundation of the entire security assessment frame
| **`Get-SystemInfo`** | Collects comprehensive system information for security context | • Hardware specifications (CPU, RAM, Disks)<br>• Operating system version and patches<br>• Installed software inventory<br>• Network adapter configuration<br>• Domain membership and policies<br>• Running services and drivers | Detailed system profile for analysis |
| **`Test-SystemIntegrity`** | Verifies Windows system file integrity and health | • SFC (System File Checker) execution<br>• DISM component store validation<br>• Windows image health check<br>• Corrupted file detection<br>• Automatic repair recommendations<br>• Boot configuration verification | Integrity report with repair actions |
| **`Get-EventIdDescription`** | Provides security context for Windows Event IDs | • Maps Event IDs to security implications<br>• MITRE ATT&CK technique correlation<br>• Severity classification (Critical/High/Medium/Low)<br>• Investigation guidance<br>• False positive indicators<br>• Response recommendations | Event analysis with threat context |
+| **`Compare-SecurityBaseline`** | Compares two security states and reports configuration drift | • Baseline vs. current state diffing<br>• Live capture when no current file given<br>• Improved/Degraded/New/Removed classification<br>• Volatile timestamp filtering<br>• Overall trend calculation<br>• JSON + CSV drift export | Drift report with trend summary |
---
@@ -387,7 +482,7 @@ The Response module provides automated incident response capabilities, enabling
---
-### 5️⃣ Enterprise Module (3 Functions)
+### 5️⃣ Enterprise Module (4 Functions)
The Enterprise module enables security operations at scale, providing centralized management and reporting across multiple systems. These functions are optimized for large environments with thousands of endpoints.
@@ -396,6 +491,7 @@ The Enterprise module enables security operations at scale, providing centralize
| **`Invoke-EnterpriseSecurityScan`** | Performs security scanning across multiple systems | • Parallel execution (up to 50 threads)<br>• Credential management<br>• Progress tracking<br>• Error handling<br>• Resource throttling<br>• Centralized logging | 1-10,000+ systems<br>Domain-wide scanning<br>Cross-forest support |
| **`Get-MultiSystemAudit`** | Consolidated auditing across system groups | • Role-based scanning (DC, File, Web)<br>• Compliance aggregation<br>• Risk scoring<br>• Baseline comparison<br>• Trend analysis<br>• Executive dashboards | Server groups<br>Department systems<br>Geographic regions |
| **`Invoke-SecurityAssessment`** | Comprehensive security evaluation orchestration | • All module coordination<br>• Risk prioritization<br>• Attack path analysis<br>• Business impact assessment<br>• Remediation roadmap<br>• KPI/KRI metrics | Complete assessment<br>Risk matrices<br>Action plans |
+| **`Register-ScheduledSecurityScan`** | Automated recurring scans with alerting | • Daily/Weekly/Monthly schedules<br>• Runs as SYSTEM via Scheduled Tasks<br>• Teams/Slack webhook alerts<br>• Email alerts on Critical findings<br>• Run history and error logging<br>• WhatIf/Confirm support | Scheduled task<br>Alert notifications<br>Run summaries |
---
@@ -423,7 +519,7 @@ The Windows Defender module provides comprehensive management and monitoring of
---
-### 8️⃣ Threat Hunting Module (6 Functions)
+### 8️⃣ Threat Hunting Module (7 Functions)
The Threat Hunting module provides proactive threat detection capabilities using advanced techniques, threat intelligence, and behavioral analysis to identify sophisticated attackers that evade traditional security controls.
@@ -435,6 +531,7 @@ The Threat Hunting module provides proactive threat detection capabilities using
| **`Find-LivingOffLand`** | Detects abuse of legitimate tools | • PowerShell exploitation<br>• WMI weaponization<br>• LOLBins detection<br>• Script host abuse<br>• Certutil misuse<br>• Mshta execution | Fileless attacks<br>Evasion techniques<br>Stealth persistence |
| **`Get-MITREAttackMapping`** | Maps findings to ATT&CK framework | • Technique classification<br>• Tactic identification<br>• Kill chain mapping<br>• Detection gap analysis<br>• Priority scoring<br>• Coverage reporting | Framework alignment<br>Gap identification<br>Defense planning |
| **`Get-ThreatIntelligence`** | Analyzes threat intelligence indicators | • IOC matching<br>• Threat feed integration<br>• Reputation checking<br>• Hash validation<br>• Domain analysis<br>• IP geolocation | Known threats<br>Emerging campaigns<br>Zero-day indicators |
+| **`Export-AttackNavigatorLayer`** | Exports findings as a MITRE ATT&CK Navigator layer | • Navigator layer JSON v4.x<br>• Severity-based scoring and colors<br>• Detection count aggregation<br>• Evidence embedded in comments<br>• Pipeline input from hunting functions<br>• Output validation | ATT&CK Navigator<br>visualization |
---
@@ -508,7 +605,7 @@ The Cloud Security module extends security assessment capabilities to cloud plat
---
-### 1️⃣4️⃣ Reporting Module (3 Functions)
+### 1️⃣4️⃣ Reporting Module (4 Functions)
The Reporting module transforms raw security data into actionable intelligence through professional reports, interactive dashboards, and executive presentations.
@@ -517,6 +614,7 @@ The Reporting module transforms raw security data into actionable intelligence t
| **`Get-SecurityMetrics`** | Collects and calculates KPIs/KRIs | • Security scores<br>• Threat statistics<br>• Compliance rates<br>• Vulnerability metrics<br>• Trend analysis<br>• Benchmarking data | JSON metrics<br>Time-series data<br>Comparison charts |
| **`New-ExecutiveReport`** | Creates C-level presentations | • Risk matrices<br>• Business impact analysis<br>• Trend visualization<br>• Key findings<br>• Recommendations<br>• Action items | PDF presentation<br>PowerPoint<br>HTML dashboard |
| **`New-SecurityDashboard`** | Interactive security dashboard | • Real-time metrics<br>• Drill-down charts<br>• Heat maps<br>• Risk indicators<br>• Compliance status<br>• Alert summary | HTML5 responsive<br>Auto-refresh<br>Export capable |
+| **`New-ConsolidatedReport`** | Single interactive report combining all modules | • All-module data collection<br>• Chart.js severity doughnut<br>• Category score bar charts<br>• Offline mode from saved JSON<br>• Section status tracking<br>• Raw data export | Self-contained HTML<br>Interactive charts<br>JSON export |
---
@@ -572,7 +670,7 @@ The Reporting module transforms raw security data into actionable intelligence t
### Community Edition - Forever FREE
- ✅ **Price**: 100% FREE - No hidden costs
-- ✅ **Functions**: All 58 functions included
+- ✅ **Functions**: All 62 functions included
- ✅ **Source Code**: Full access on GitHub
- ✅ **Updates**: Regular security updates
- ✅ **License**: MIT (commercial use allowed)
@@ -622,7 +720,7 @@ cd WindowsSecurityAudit
Install-Module -Name Pester, PSScriptAnalyzer -Force
# Run tests
-Invoke-Pester -Path .\Tests\
+Invoke-Pester -Path .\tests\
# Run linter
Invoke-ScriptAnalyzer -Path . -Recurse
@@ -672,14 +770,14 @@ We work with Fortune 500 companies, government agencies, and organizations of al
## 🚀 Roadmap
-### Version 1.1 (Q1 2026)
+### Version 1.2 (Next)
- [ ] Web-based GUI dashboard
- [ ] REST API for remote management
- [ ] Linux/macOS PowerShell Core support
- [ ] Machine learning anomaly detection
- [ ] Automated remediation workflows
-### Version 2.0 (Q3 2026)
+### Version 2.0 (Future)
- [ ] Container security scanning
- [ ] Kubernetes integration
- [ ] Cloud-native architecture
diff --git a/Reporting/Get-SecurityMetrics.ps1 b/Reporting/Get-SecurityMetrics.ps1
index 8d21944..72fc81a 100644
--- a/Reporting/Get-SecurityMetrics.ps1
+++ b/Reporting/Get-SecurityMetrics.ps1
@@ -448,7 +448,10 @@ function Get-SecurityMetrics {
$baseline = Get-SecurityBaseline -ErrorAction Stop
if ($baseline) {
# Safe property access
- if ($baseline.PSObject.Properties['CompliancePercentage']) {
+ if ($baseline.PSObject.Properties['SecurityScore']) {
+ $script:metrics.Core.BaselineCompliance = $baseline.SecurityScore
+ }
+ elseif ($baseline.PSObject.Properties['CompliancePercentage']) {
$script:metrics.Core.BaselineCompliance = $baseline.CompliancePercentage
}
elseif ($baseline.PSObject.Properties['ComplianceScore']) {
@@ -473,11 +476,9 @@ function Get-SecurityMetrics {
$script:metrics.Core.SystemHealth = "Healthy"
# Extract uptime if available
- if ($sysInfo.PSObject.Properties['LastBootUpTime']) {
- $script:metrics.Core.UptimeDays = [Math]::Round(((Get-Date) - $sysInfo.LastBootUpTime).TotalDays, 1)
- }
- elseif ($sysInfo.PSObject.Properties['BootTime']) {
- $script:metrics.Core.UptimeDays = [Math]::Round(((Get-Date) - $sysInfo.BootTime).TotalDays, 1)
+ if ($sysInfo.PSObject.Properties['OperatingSystem'] -and $sysInfo.OperatingSystem -and
+ $sysInfo.OperatingSystem.PSObject.Properties['LastBootUpTime'] -and $sysInfo.OperatingSystem.LastBootUpTime) {
+ $script:metrics.Core.UptimeDays = [Math]::Round(((Get-Date) - [datetime]$sysInfo.OperatingSystem.LastBootUpTime).TotalDays, 1)
}
$successfulFunctions++
@@ -503,6 +504,9 @@ function Get-SecurityMetrics {
elseif ($integrity.PSObject.Properties['IntegrityStatus']) {
$script:metrics.Core.IntegrityStatus = $integrity.IntegrityStatus
}
+ elseif ($integrity.PSObject.Properties['SFCResult'] -and $integrity.SFCResult) {
+ $script:metrics.Core.IntegrityStatus = $integrity.SFCResult
+ }
# Extract pending updates
if ($integrity.PSObject.Properties['PendingUpdates']) {
@@ -553,7 +557,11 @@ function Get-SecurityMetrics {
try {
$totalFunctions++
$persistence = Find-PersistenceMechanisms -ErrorAction Stop
- $script:metrics.Detection.PersistenceMechanisms = @($persistence).Count
+ if ($persistence -and $persistence.PSObject.Properties['SuspiciousCount']) {
+ $script:metrics.Detection.PersistenceMechanisms = $persistence.SuspiciousCount
+ } else {
+ $script:metrics.Detection.PersistenceMechanisms = @($persistence).Count
+ }
$successfulFunctions++
Write-Host " Persistence Mechanisms: $($script:metrics.Detection.PersistenceMechanisms)" -ForegroundColor $(if ($script:metrics.Detection.PersistenceMechanisms -gt 0) { 'Yellow' } else { 'Green' })
} catch {
@@ -577,7 +585,13 @@ function Get-SecurityMetrics {
try {
$totalFunctions++
$auth = Find-SuspiciousAuthentication -ErrorAction Stop
- $script:metrics.Detection.SuspiciousAuthentications = @($auth).Count
+ if ($auth -and $auth.PSObject.Properties['Statistics'] -and $auth.Statistics) {
+ $script:metrics.Detection.SuspiciousAuthentications =
+ $auth.Statistics.TotalFailedLogons + $auth.Statistics.TotalLockouts +
+ $auth.Statistics.TotalPrivilegeUse + $auth.Statistics.TotalExplicitCreds
+ } else {
+ $script:metrics.Detection.SuspiciousAuthentications = @($auth).Count
+ }
$successfulFunctions++
Write-Host " Suspicious Authentications: $($script:metrics.Detection.SuspiciousAuthentications)" -ForegroundColor $(if ($script:metrics.Detection.SuspiciousAuthentications -gt 0) { 'Yellow' } else { 'Green' })
} catch {
@@ -589,7 +603,11 @@ function Get-SecurityMetrics {
try {
$totalFunctions++
$lateral = Find-LateralMovement -ErrorAction Stop
- $script:metrics.Detection.LateralMovement = @($lateral).Count
+ if ($lateral -and $lateral.PSObject.Properties['Summary'] -and $lateral.Summary) {
+ $script:metrics.Detection.LateralMovement = $lateral.Summary.TotalIndicators
+ } else {
+ $script:metrics.Detection.LateralMovement = @($lateral).Count
+ }
$successfulFunctions++
Write-Host " Lateral Movement: $($script:metrics.Detection.LateralMovement)" -ForegroundColor $(if ($script:metrics.Detection.LateralMovement -gt 0) { 'Red' } else { 'Green' })
} catch {
@@ -601,8 +619,8 @@ function Get-SecurityMetrics {
try {
$totalFunctions++
$apt = Find-APTIndicators -ErrorAction Stop
- if ($apt -and $apt.PSObject.Properties['TotalIndicators']) {
- $script:metrics.Detection.APTIndicators = $apt.TotalIndicators
+ if ($apt -and $apt.PSObject.Properties['Summary'] -and $apt.Summary) {
+ $script:metrics.Detection.APTIndicators = $apt.Summary.TotalIndicators
} else {
$script:metrics.Detection.APTIndicators = @($apt).Count
}
@@ -617,7 +635,11 @@ function Get-SecurityMetrics {
try {
$totalFunctions++
$lolbins = Find-LivingOffLand -ErrorAction Stop
- $script:metrics.Detection.LivingOffLand = @($lolbins).Count
+ if ($lolbins -and $lolbins.PSObject.Properties['Summary'] -and $lolbins.Summary) {
+ $script:metrics.Detection.LivingOffLand = $lolbins.Summary.TotalDetections
+ } else {
+ $script:metrics.Detection.LivingOffLand = @($lolbins).Count
+ }
$successfulFunctions++
Write-Host " Living Off Land: $($script:metrics.Detection.LivingOffLand)" -ForegroundColor $(if ($script:metrics.Detection.LivingOffLand -gt 0) { 'Yellow' } else { 'Green' })
} catch {
@@ -629,7 +651,11 @@ function Get-SecurityMetrics {
try {
$totalFunctions++
$exfil = Find-DataExfiltration -ErrorAction Stop
- $script:metrics.Detection.DataExfiltration = @($exfil).Count
+ if ($exfil -and $exfil.PSObject.Properties['Summary'] -and $exfil.Summary) {
+ $script:metrics.Detection.DataExfiltration = $exfil.Summary.TotalIndicators
+ } else {
+ $script:metrics.Detection.DataExfiltration = @($exfil).Count
+ }
$successfulFunctions++
Write-Host " Data Exfiltration: $($script:metrics.Detection.DataExfiltration)" -ForegroundColor $(if ($script:metrics.Detection.DataExfiltration -gt 0) { 'Red' } else { 'Green' })
} catch {
@@ -691,15 +717,23 @@ function Get-SecurityMetrics {
if ($eventLog) {
if ($eventLog.PSObject.Properties['TotalEvents']) {
$script:metrics.Analysis.TotalEvents = $eventLog.TotalEvents
+ } elseif ($eventLog.PSObject.Properties['Statistics'] -and $eventLog.Statistics) {
+ $script:metrics.Analysis.TotalEvents = $eventLog.Statistics.TotalEventsAnalyzed
}
if ($eventLog.PSObject.Properties['CriticalEvents']) {
$script:metrics.Analysis.CriticalEvents = $eventLog.CriticalEvents
+ } elseif ($eventLog.PSObject.Properties['Statistics'] -and $eventLog.Statistics) {
+ $script:metrics.Analysis.CriticalEvents = $eventLog.Statistics.CriticalEvents
}
if ($eventLog.PSObject.Properties['ErrorEvents']) {
$script:metrics.Analysis.ErrorEvents = $eventLog.ErrorEvents
+ } elseif ($eventLog.PSObject.Properties['Statistics'] -and $eventLog.Statistics) {
+ $script:metrics.Analysis.ErrorEvents = $eventLog.Statistics.ErrorEvents
}
if ($eventLog.PSObject.Properties['WarningEvents']) {
$script:metrics.Analysis.WarningEvents = $eventLog.WarningEvents
+ } elseif ($eventLog.PSObject.Properties['Statistics'] -and $eventLog.Statistics) {
+ $script:metrics.Analysis.WarningEvents = $eventLog.Statistics.WarningEvents
}
$successfulFunctions++
Write-Host " Event Log Analysis: $($script:metrics.Analysis.TotalEvents) events ($($script:metrics.Analysis.CriticalEvents) critical)" -ForegroundColor $(if ($script:metrics.Analysis.CriticalEvents -gt 0) { 'Red' } else { 'Green' })
@@ -714,8 +748,8 @@ function Get-SecurityMetrics {
$totalFunctions++
$registry = Get-RegistryAnalysis -ErrorAction Stop
if ($registry) {
- if ($registry.PSObject.Properties['SuspiciousFindings']) {
- $script:metrics.Analysis.RegistryIssues = $registry.SuspiciousFindings
+ if ($registry.PSObject.Properties['Statistics'] -and $registry.Statistics) {
+ $script:metrics.Analysis.RegistryIssues = $registry.Statistics.SuspiciousFindings
} else {
$script:metrics.Analysis.RegistryIssues = @($registry).Count
}
@@ -732,8 +766,10 @@ function Get-SecurityMetrics {
$totalFunctions++
$fileSystem = Get-FileSystemAnalysis -ErrorAction Stop
if ($fileSystem) {
- if ($fileSystem.PSObject.Properties['SuspiciousFiles']) {
- $script:metrics.Analysis.FileSystemIssues = $fileSystem.SuspiciousFiles
+ if ($fileSystem.PSObject.Properties['Statistics'] -and $fileSystem.Statistics) {
+ $script:metrics.Analysis.FileSystemIssues = $fileSystem.Statistics.SuspiciousFiles
+ } elseif ($fileSystem.PSObject.Properties['SuspiciousFiles']) {
+ $script:metrics.Analysis.FileSystemIssues = @($fileSystem.SuspiciousFiles).Count
} else {
$script:metrics.Analysis.FileSystemIssues = @($fileSystem).Count
}
@@ -750,8 +786,10 @@ function Get-SecurityMetrics {
$totalFunctions++
$memory = Get-MemoryAnalysis -ErrorAction Stop
if ($memory) {
- if ($memory.PSObject.Properties['InjectionIndicators']) {
- $script:metrics.Analysis.MemoryIssues = $memory.InjectionIndicators
+ if ($memory.PSObject.Properties['Statistics'] -and $memory.Statistics) {
+ $script:metrics.Analysis.MemoryIssues = $memory.Statistics.InjectionIndicators
+ } elseif ($memory.PSObject.Properties['InjectionIndicators']) {
+ $script:metrics.Analysis.MemoryIssues = @($memory.InjectionIndicators).Count
}
$successfulFunctions++
Write-Host " Memory Analysis: $($script:metrics.Analysis.MemoryIssues) issues" -ForegroundColor $(if ($script:metrics.Analysis.MemoryIssues -gt 0) { 'Red' } else { 'Green' })
@@ -767,7 +805,7 @@ function Get-SecurityMetrics {
$exposed = Get-ExposedServices -ErrorAction Stop
if ($exposed) {
if ($exposed.PSObject.Properties['ExposedServices']) {
- $script:metrics.Analysis.ExposedServices = $exposed.ExposedServices
+ $script:metrics.Analysis.ExposedServices = @($exposed.ExposedServices).Count
} else {
$script:metrics.Analysis.ExposedServices = @($exposed).Count
}
@@ -814,21 +852,29 @@ function Get-SecurityMetrics {
$script:metrics.Compliance.Frameworks.CIS.Score = $cis.CompliancePercentage
} elseif ($cis.PSObject.Properties['Compliance']) {
$script:metrics.Compliance.Frameworks.CIS.Score = $cis.Compliance
+ } elseif ($cis.PSObject.Properties['Summary'] -and $cis.Summary) {
+ $script:metrics.Compliance.Frameworks.CIS.Score = $cis.Summary.CompliancePercentage
}
# Controls
if ($cis.PSObject.Properties['TotalControls']) {
$script:metrics.Compliance.Frameworks.CIS.TotalControls = $cis.TotalControls
+ } elseif ($cis.PSObject.Properties['Summary'] -and $cis.Summary) {
+ $script:metrics.Compliance.Frameworks.CIS.TotalControls = $cis.Summary.TotalControls
}
if ($cis.PSObject.Properties['PassedControls']) {
$script:metrics.Compliance.Frameworks.CIS.PassedControls = $cis.PassedControls
} elseif ($cis.PSObject.Properties['Passed']) {
$script:metrics.Compliance.Frameworks.CIS.PassedControls = $cis.Passed
+ } elseif ($cis.PSObject.Properties['Summary'] -and $cis.Summary) {
+ $script:metrics.Compliance.Frameworks.CIS.PassedControls = $cis.Summary.Passed
}
if ($cis.PSObject.Properties['FailedControls']) {
$script:metrics.Compliance.Frameworks.CIS.FailedControls = $cis.FailedControls
} elseif ($cis.PSObject.Properties['Failed']) {
$script:metrics.Compliance.Frameworks.CIS.FailedControls = $cis.Failed
+ } elseif ($cis.PSObject.Properties['Summary'] -and $cis.Summary) {
+ $script:metrics.Compliance.Frameworks.CIS.FailedControls = $cis.Summary.Failed
}
$successfulFunctions++
@@ -851,21 +897,29 @@ function Get-SecurityMetrics {
$script:metrics.Compliance.Frameworks.NIST.Score = $nist.CompliancePercentage
} elseif ($nist.PSObject.Properties['Compliance']) {
$script:metrics.Compliance.Frameworks.NIST.Score = $nist.Compliance
+ } elseif ($nist.PSObject.Properties['Summary'] -and $nist.Summary) {
+ $script:metrics.Compliance.Frameworks.NIST.Score = $nist.Summary.CompliancePercentage
}
# Controls
if ($nist.PSObject.Properties['TotalControls']) {
$script:metrics.Compliance.Frameworks.NIST.TotalControls = $nist.TotalControls
+ } elseif ($nist.PSObject.Properties['Summary'] -and $nist.Summary) {
+ $script:metrics.Compliance.Frameworks.NIST.TotalControls = $nist.Summary.TotalControls
}
if ($nist.PSObject.Properties['CompliantControls']) {
$script:metrics.Compliance.Frameworks.NIST.CompliantControls = $nist.CompliantControls
} elseif ($nist.PSObject.Properties['Compliant']) {
$script:metrics.Compliance.Frameworks.NIST.CompliantControls = $nist.Compliant
+ } elseif ($nist.PSObject.Properties['Summary'] -and $nist.Summary) {
+ $script:metrics.Compliance.Frameworks.NIST.CompliantControls = $nist.Summary.Compliant
}
if ($nist.PSObject.Properties['NonCompliantControls']) {
$script:metrics.Compliance.Frameworks.NIST.NonCompliantControls = $nist.NonCompliantControls
} elseif ($nist.PSObject.Properties['NonCompliant']) {
$script:metrics.Compliance.Frameworks.NIST.NonCompliantControls = $nist.NonCompliant
+ } elseif ($nist.PSObject.Properties['Summary'] -and $nist.Summary) {
+ $script:metrics.Compliance.Frameworks.NIST.NonCompliantControls = $nist.Summary.NonCompliant
}
$successfulFunctions++
@@ -888,17 +942,25 @@ function Get-SecurityMetrics {
$script:metrics.Compliance.Frameworks.PCIDSS.Score = $pci.CompliancePercentage
} elseif ($pci.PSObject.Properties['Compliance']) {
$script:metrics.Compliance.Frameworks.PCIDSS.Score = $pci.Compliance
+ } elseif ($pci.PSObject.Properties['Summary'] -and $pci.Summary) {
+ $script:metrics.Compliance.Frameworks.PCIDSS.Score = $pci.Summary.CompliancePercentage
}
# Requirements
if ($pci.PSObject.Properties['TotalRequirements']) {
$script:metrics.Compliance.Frameworks.PCIDSS.TotalRequirements = $pci.TotalRequirements
+ } elseif ($pci.PSObject.Properties['Summary'] -and $pci.Summary) {
+ $script:metrics.Compliance.Frameworks.PCIDSS.TotalRequirements = $pci.Summary.TotalRequirements
}
if ($pci.PSObject.Properties['InPlace']) {
$script:metrics.Compliance.Frameworks.PCIDSS.InPlace = $pci.InPlace
+ } elseif ($pci.PSObject.Properties['Summary'] -and $pci.Summary) {
+ $script:metrics.Compliance.Frameworks.PCIDSS.InPlace = $pci.Summary.InPlace
}
if ($pci.PSObject.Properties['NotInPlace']) {
$script:metrics.Compliance.Frameworks.PCIDSS.NotInPlace = $pci.NotInPlace
+ } elseif ($pci.PSObject.Properties['Summary'] -and $pci.Summary) {
+ $script:metrics.Compliance.Frameworks.PCIDSS.NotInPlace = $pci.Summary.NotInPlace
}
$successfulFunctions++
@@ -1050,9 +1112,10 @@ function Get-SecurityMetrics {
if ($pwdPolicy) {
# Calculate password policy score
$policyScore = 100
- if ($pwdPolicy.PSObject.Properties['MinPasswordLength'] -and $pwdPolicy.MinPasswordLength -lt 14) { $policyScore -= 20 }
- if ($pwdPolicy.PSObject.Properties['ComplexityEnabled'] -and -not $pwdPolicy.ComplexityEnabled) { $policyScore -= 30 }
- if ($pwdPolicy.PSObject.Properties['MaxPasswordAge'] -and $pwdPolicy.MaxPasswordAge.Days -gt 90) { $policyScore -= 15 }
+ $dp = if ($pwdPolicy.PSObject.Properties['DefaultPolicy'] -and $pwdPolicy.DefaultPolicy) { $pwdPolicy.DefaultPolicy } else { $pwdPolicy }
+ if ($dp.PSObject.Properties['MinPasswordLength'] -and $dp.MinPasswordLength -lt 14) { $policyScore -= 20 }
+ if ($dp.PSObject.Properties['ComplexityEnabled'] -and -not $dp.ComplexityEnabled) { $policyScore -= 30 }
+ if ($dp.PSObject.Properties['MaxPasswordAge'] -and $dp.MaxPasswordAge -gt 90) { $policyScore -= 15 }
$script:metrics.ActiveDirectory.PasswordPolicyScore = [Math]::Max(0, $policyScore)
}
$successfulFunctions++
@@ -1098,8 +1161,8 @@ function Get-SecurityMetrics {
try {
$totalFunctions++
$m365Security = Test-M365SecurityPosture -ErrorAction Stop
- if ($m365Security -and $m365Security.PSObject.Properties['SecurityScore']) {
- $script:metrics.Cloud.M365SecurityScore = $m365Security.SecurityScore
+ if ($m365Security -and $m365Security.PSObject.Properties['ComplianceScore']) {
+ $script:metrics.Cloud.M365SecurityScore = $m365Security.ComplianceScore
}
$successfulFunctions++
Write-Host " M365 Security Score: $($script:metrics.Cloud.M365SecurityScore)%" -ForegroundColor Cyan
@@ -1140,23 +1203,25 @@ function Get-SecurityMetrics {
try {
$totalFunctions++
$vulnAssess = Get-VulnerabilityAssessment -ErrorAction Stop
- if ($vulnAssess -and $vulnAssess.PSObject.Properties['Summary']) {
+ if ($vulnAssess -and $vulnAssess.PSObject.Properties['Summary'] -and $vulnAssess.Summary) {
$summary = $vulnAssess.Summary
- if ($summary.PSObject.Properties['TotalVulnerabilities']) {
- $script:metrics.Vulnerability.Total = $summary.TotalVulnerabilities
- }
- if ($summary.PSObject.Properties['Critical']) {
- $script:metrics.Vulnerability.Critical = $summary.Critical
+ if ($null -ne $summary.CriticalVulnerabilities) {
+ $script:metrics.Vulnerability.Critical = $summary.CriticalVulnerabilities
}
- if ($summary.PSObject.Properties['High']) {
- $script:metrics.Vulnerability.High = $summary.High
+ if ($null -ne $summary.HighVulnerabilities) {
+ $script:metrics.Vulnerability.High = $summary.HighVulnerabilities
}
- if ($summary.PSObject.Properties['Medium']) {
- $script:metrics.Vulnerability.Medium = $summary.Medium
+ if ($null -ne $summary.MediumVulnerabilities) {
+ $script:metrics.Vulnerability.Medium = $summary.MediumVulnerabilities
}
- if ($summary.PSObject.Properties['Low']) {
- $script:metrics.Vulnerability.Low = $summary.Low
+ if ($null -ne $summary.LowVulnerabilities) {
+ $script:metrics.Vulnerability.Low = $summary.LowVulnerabilities
}
+ $script:metrics.Vulnerability.Total =
+ $script:metrics.Vulnerability.Critical +
+ $script:metrics.Vulnerability.High +
+ $script:metrics.Vulnerability.Medium +
+ $script:metrics.Vulnerability.Low
}
$successfulFunctions++
Write-Host " Vulnerabilities: $($script:metrics.Vulnerability.Total) total" -ForegroundColor $(if ($script:metrics.Vulnerability.Total -gt 0) { 'Yellow' } else { 'Green' })
@@ -1185,14 +1250,16 @@ function Get-SecurityMetrics {
$totalFunctions++
$certs = Test-CertificateHealth -ErrorAction Stop
if ($certs) {
- if ($certs.PSObject.Properties['IssuesFound']) {
- $script:metrics.Vulnerability.CertificateIssues = $certs.IssuesFound
- }
- if ($certs.PSObject.Properties['Expired']) {
- $script:metrics.Vulnerability.ExpiredCertificates = $certs.Expired
+ if ($certs.PSObject.Properties['Issues']) {
+ $script:metrics.Vulnerability.CertificateIssues = @($certs.Issues).Count
}
- if ($certs.PSObject.Properties['WeakSignatures']) {
- $script:metrics.Vulnerability.WeakCertificates = $certs.WeakSignatures
+ if ($certs.PSObject.Properties['Summary'] -and $certs.Summary) {
+ if ($null -ne $certs.Summary.Expired) {
+ $script:metrics.Vulnerability.ExpiredCertificates = $certs.Summary.Expired
+ }
+ if ($null -ne $certs.Summary.WeakSignature) {
+ $script:metrics.Vulnerability.WeakCertificates = $certs.Summary.WeakSignature
+ }
}
}
$successfulFunctions++
@@ -1221,6 +1288,8 @@ function Get-SecurityMetrics {
if ($threatIntel) {
if ($threatIntel.PSObject.Properties['IOCMatches']) {
$script:metrics.ThreatHunting.IOCMatches = @($threatIntel.IOCMatches).Count
+ } elseif ($threatIntel.PSObject.Properties['Summary'] -and $threatIntel.Summary) {
+ $script:metrics.ThreatHunting.IOCMatches = $threatIntel.Summary.TotalMatches
} else {
$script:metrics.ThreatHunting.IOCMatches = @($threatIntel).Count
}
@@ -1239,6 +1308,8 @@ function Get-SecurityMetrics {
if ($mitre) {
if ($mitre.PSObject.Properties['UniqueTechniques']) {
$script:metrics.ThreatHunting.MITRETechniques = $mitre.UniqueTechniques
+ } elseif ($mitre.PSObject.Properties['Summary'] -and $mitre.Summary) {
+ $script:metrics.ThreatHunting.MITRETechniques = $mitre.Summary.TotalTechniques
} else {
$script:metrics.ThreatHunting.MITRETechniques = @($mitre).Count
}
@@ -1267,8 +1338,8 @@ function Get-SecurityMetrics {
$totalFunctions++
$artifacts = Get-ArtifactCollection -ErrorAction Stop
if ($artifacts) {
- if ($artifacts.PSObject.Properties['TotalFiles']) {
- $script:metrics.Forensics.ArtifactsCollected = $artifacts.TotalFiles
+ if ($artifacts.PSObject.Properties['Summary'] -and $artifacts.Summary) {
+ $script:metrics.Forensics.ArtifactsCollected = $artifacts.Summary.TotalFiles
}
}
$successfulFunctions++
@@ -1285,12 +1356,14 @@ function Get-SecurityMetrics {
if ($execArtifacts) {
if ($execArtifacts.PSObject.Properties['TotalArtifacts']) {
$script:metrics.Forensics.ExecutionArtifacts = $execArtifacts.TotalArtifacts
+ } elseif ($execArtifacts.PSObject.Properties['Summary'] -and $execArtifacts.Summary) {
+ $script:metrics.Forensics.ExecutionArtifacts = $execArtifacts.Summary.TotalArtifacts
} else {
$script:metrics.Forensics.ExecutionArtifacts = @($execArtifacts).Count
}
- if ($execArtifacts.PSObject.Properties['RecentExecutions']) {
- $script:metrics.Forensics.RecentExecutions = @($execArtifacts.RecentExecutions).Count
+ if ($execArtifacts.PSObject.Properties['Summary'] -and $execArtifacts.Summary) {
+ $script:metrics.Forensics.RecentExecutions = $execArtifacts.Summary.RecentApps
}
}
$successfulFunctions++
@@ -1342,33 +1415,33 @@ function Get-SecurityMetrics {
}
# Protection states
- if ($defStatus.PSObject.Properties['RealTimeProtectionEnabled']) {
- $script:metrics.WindowsDefender.RealTimeProtection = $defStatus.RealTimeProtectionEnabled
- $script:metrics.WindowsDefender.ProtectionEnabled = $defStatus.RealTimeProtectionEnabled
+ if ($defStatus.PSObject.Properties['ProtectionStatus'] -and $defStatus.ProtectionStatus) {
+ $script:metrics.WindowsDefender.RealTimeProtection = [bool]$defStatus.ProtectionStatus.RealTimeProtectionEnabled
+ $script:metrics.WindowsDefender.ProtectionEnabled = [bool]$defStatus.ProtectionStatus.RealTimeProtectionEnabled
}
- if ($defStatus.PSObject.Properties['CloudProtectionLevel']) {
- $script:metrics.WindowsDefender.CloudProtection = ($defStatus.CloudProtectionLevel -ne 'NotConfigured')
+ if ($defStatus.PSObject.Properties['Configuration'] -and $defStatus.Configuration) {
+ $script:metrics.WindowsDefender.CloudProtection = ($defStatus.Configuration.MAPSReporting -gt 0)
}
# Signature info
- if ($defStatus.PSObject.Properties['SignatureAge']) {
- $script:metrics.WindowsDefender.SignatureAge = $defStatus.SignatureAge
- }
- if ($defStatus.PSObject.Properties['AntivirusSignatureVersion']) {
- $script:metrics.WindowsDefender.SignatureVersion = $defStatus.AntivirusSignatureVersion
- } elseif ($defStatus.PSObject.Properties['SignatureVersion']) {
- $script:metrics.WindowsDefender.SignatureVersion = $defStatus.SignatureVersion
+ if ($defStatus.PSObject.Properties['SignatureStatus'] -and $defStatus.SignatureStatus) {
+ if ($defStatus.SignatureStatus.SignatureAge) {
+ $script:metrics.WindowsDefender.SignatureAge = [int]$defStatus.SignatureStatus.SignatureAge.Days
+ }
+ if ($defStatus.SignatureStatus.AntivirusSignatureVersion) {
+ $script:metrics.WindowsDefender.SignatureVersion = $defStatus.SignatureStatus.AntivirusSignatureVersion
+ }
}
# Scan info
- if ($defStatus.PSObject.Properties['DaysSinceLastQuickScan']) {
- $script:metrics.WindowsDefender.LastScanDays = $defStatus.DaysSinceLastQuickScan
- }
- if ($defStatus.PSObject.Properties['QuickScanStartTime']) {
- $script:metrics.WindowsDefender.LastQuickScan = $defStatus.QuickScanStartTime
- }
- if ($defStatus.PSObject.Properties['FullScanStartTime']) {
- $script:metrics.WindowsDefender.LastFullScan = $defStatus.FullScanStartTime
+ if ($defStatus.PSObject.Properties['ScanHistory'] -and $defStatus.ScanHistory) {
+ if ($defStatus.ScanHistory.QuickScanStartTime) {
+ $script:metrics.WindowsDefender.LastQuickScan = $defStatus.ScanHistory.QuickScanStartTime
+ $script:metrics.WindowsDefender.LastScanDays = [int]((Get-Date) - [datetime]$defStatus.ScanHistory.QuickScanStartTime).TotalDays
+ }
+ if ($defStatus.ScanHistory.FullScanStartTime) {
+ $script:metrics.WindowsDefender.LastFullScan = $defStatus.ScanHistory.FullScanStartTime
+ }
}
}
$successfulFunctions++
diff --git a/Reporting/New-ConsolidatedReport.ps1 b/Reporting/New-ConsolidatedReport.ps1
new file mode 100644
index 0000000..6d9885f
--- /dev/null
+++ b/Reporting/New-ConsolidatedReport.ps1
@@ -0,0 +1,784 @@
+function New-ConsolidatedReport {
+ <#
+ .SYNOPSIS
+ Generates ONE interactive HTML report combining all major security modules
+
+ .DESCRIPTION
+ Consolidated reporting engine that collects results from the core audit
+ functions of the WindowsSecurityAudit module and renders a single,
+ self-contained interactive HTML report with embedded Chart.js charts:
+
+ - Assessment : Invoke-SecurityAssessment
+ - Defender : Get-DefenderStatus
+ - Compliance : Test-CISBenchmark
+ - ThreatHunting : Get-ThreatIntelligence
+ - Vulnerability : Get-VulnerabilityAssessment
+ - Forensics : Get-ArtifactCollection
+
+ Every collector runs inside its own try/catch block. If a collector is
+ unavailable, fails, or live collection is skipped, the corresponding
+ report section is marked as "Not collected" instead of aborting the
+ report.
+
+ The report contains:
+ - Summary card grid (security score, findings totals, section status)
+ - Doughnut chart of findings by severity (Critical/High/Medium/Low)
+ - Bar chart of per-category scores
+ - Per-section detail cards
+
+ Chart.js is referenced from the jsDelivr CDN
+ (https://cdn.jsdelivr.net/npm/chart.js), so charts require internet
+ access when the report is viewed. All other markup is self-contained.
+
+ .PARAMETER OutputPath
+ Directory where the HTML report (and optional JSON export) is saved.
+ The directory is created if it does not exist.
+ Default: current directory
+
+ .PARAMETER IncludeSections
+ Report sections to include. Each section maps to one collector function.
+ Valid values: Assessment, Defender, Compliance, ThreatHunting,
+ Vulnerability, Forensics
+ Default: all sections
+
+ .PARAMETER SkipDataCollection
+ Do not run any live collector functions. Sections without data supplied
+ via -FromJsonPath are marked "Not collected". Useful for testing report
+ rendering on systems where the audit functions cannot run.
+
+ .PARAMETER FromJsonPath
+ Path to a JSON file with previously saved collector outputs. When
+ provided, live data collection is skipped and section data is loaded
+ from this file. The JSON must be an object whose property names match
+ the section names (Assessment, Defender, Compliance, ThreatHunting,
+ Vulnerability, Forensics). Use -SaveJson on a live run to produce a
+ compatible file.
+
+ .PARAMETER SaveJson
+ Also export the collected raw section data to a timestamped JSON file
+ next to the HTML report. The file can be reused later via -FromJsonPath.
+
+ .PARAMETER OpenInBrowser
+ Automatically open the generated report in the default browser.
+
+ .EXAMPLE
+ New-ConsolidatedReport
+ Full consolidated report with live data collection from all six sections
+
+ .EXAMPLE
+ New-ConsolidatedReport -IncludeSections Assessment,Defender -OutputPath "C:\Reports"
+ Report limited to the Assessment and Defender sections, saved to C:\Reports
+
+ .EXAMPLE
+ New-ConsolidatedReport -OutputPath "C:\Reports" -SaveJson
+ Live report that also exports the raw collected data as JSON for later reuse
+
+ .EXAMPLE
+ New-ConsolidatedReport -FromJsonPath "C:\Reports\ConsolidatedReportData_20251024_120000.json"
+ Regenerate the HTML report from previously saved JSON without running collectors
+
+ .OUTPUTS
+ PSCustomObject with report metadata (Success, ReportPath, JsonPath,
+ SectionsCollected, SectionsNotCollected, TotalFindings, GenerationTime)
+ and the HTML file itself:
+ - ConsolidatedSecurityReport_YYYYMMDD_HHMMSS.html
+ - ConsolidatedReportData_YYYYMMDD_HHMMSS.json (if -SaveJson)
+
+ .NOTES
+ Author: WindowsSecurityAudit Module
+ Version: 1.0.0
+
+ Requires: PowerShell 5.1 or higher
+ Administrator privileges recommended for complete live data collection
+ #>
+
+ [CmdletBinding()]
+ param(
+ [Parameter()]
+ [string]$OutputPath = (Get-Location).Path,
+
+ [Parameter()]
+ [ValidateSet('Assessment', 'Defender', 'Compliance', 'ThreatHunting', 'Vulnerability', 'Forensics')]
+ [string[]]$IncludeSections = @('Assessment', 'Defender', 'Compliance', 'ThreatHunting', 'Vulnerability', 'Forensics'),
+
+ [Parameter()]
+ [switch]$SkipDataCollection,
+
+ [Parameter()]
+ [string]$FromJsonPath,
+
+ [Parameter()]
+ [switch]$SaveJson,
+
+ [Parameter()]
+ [switch]$OpenInBrowser
+ )
+
+ begin {
+ Write-Host "================================================================" -ForegroundColor Cyan
+ Write-Host " CONSOLIDATED SECURITY REPORT" -ForegroundColor Cyan
+ Write-Host "================================================================" -ForegroundColor Cyan
+
+ $reportStartTime = Get-Date
+ $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
+
+ # All supported sections in stable display order
+ $allSections = @('Assessment', 'Defender', 'Compliance', 'ThreatHunting', 'Vulnerability', 'Forensics')
+
+ # Map each section to its live collector function
+ $sectionCollectors = @{
+ Assessment = 'Invoke-SecurityAssessment'
+ Defender = 'Get-DefenderStatus'
+ Compliance = 'Test-CISBenchmark'
+ ThreatHunting = 'Get-ThreatIntelligence'
+ Vulnerability = 'Get-VulnerabilityAssessment'
+ Forensics = 'Get-ArtifactCollection'
+ }
+
+ # Validate and create output path
+ if (-not (Test-Path $OutputPath)) {
+ try {
+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null
+ Write-Host "Created output directory: $OutputPath" -ForegroundColor Green
+ }
+ catch {
+ Write-Error "Failed to create output directory: $_"
+ throw
+ }
+ }
+
+ # Validate JSON input path early (fatal if invalid)
+ if ($FromJsonPath) {
+ if (-not (Test-Path $FromJsonPath)) {
+ Write-Error "JSON input file not found: $FromJsonPath"
+ throw "JSON input file not found: $FromJsonPath"
+ }
+ Write-Host "Mode: OFFLINE - loading data from $FromJsonPath" -ForegroundColor Yellow
+ }
+ elseif ($SkipDataCollection) {
+ Write-Host "Mode: NO COLLECTION - sections will be marked 'Not collected'" -ForegroundColor Yellow
+ }
+ else {
+ Write-Host "Mode: LIVE COLLECTION - $($IncludeSections -join ', ')" -ForegroundColor Yellow
+ }
+ }
+
+ process {
+ try {
+ # ============================================
+ # HELPER FUNCTIONS (function-scoped, strict-mode safe)
+ # ============================================
+ function Get-SafeProperty {
+ param($Object, $PropertyName, $Default = $null)
+ if ($null -eq $Object) { return $Default }
+ if ($Object -is [System.Collections.IDictionary]) {
+ if ($Object.Contains($PropertyName)) {
+ $value = $Object[$PropertyName]
+ if ($null -eq $value) { return $Default }
+ return $value
+ }
+ return $Default
+ }
+ if ($Object.PSObject.Properties[$PropertyName]) {
+ $value = $Object.$PropertyName
+ if ($null -eq $value) { return $Default }
+ return $value
+ }
+ return $Default
+ }
+
+ function Get-SeverityCounts {
+ param($Data, [int]$Depth = 0)
+ $counts = @{ Critical = 0; High = 0; Medium = 0; Low = 0 }
+ if ($null -eq $Data) { return $counts }
+ if ($Depth -gt 2) { return $counts }
+
+ # Case 1: array of finding objects with a Severity property
+ if ($Data -is [array]) {
+ foreach ($item in $Data) {
+ $sev = Get-SafeProperty $item 'Severity' ''
+ switch -Regex ("$sev") {
+ '^Critical' { $counts.Critical++ }
+ '^High' { $counts.High++ }
+ '^Medium' { $counts.Medium++ }
+ '^Low' { $counts.Low++ }
+ }
+ }
+ return $counts
+ }
+
+ # Case 2: object (or nested Summary) with numeric severity properties
+ # Array-valued properties (e.g. Findings) are inspected recursively
+ $containers = @($Data)
+ $summary = Get-SafeProperty $Data 'Summary' $null
+ if ($null -ne $summary) { $containers += $summary }
+
+ foreach ($container in $containers) {
+ if ($null -eq $container) { continue }
+ $memberPairs = @()
+ if ($container -is [System.Collections.IDictionary]) {
+ foreach ($name in @($container.Keys)) {
+ $memberPairs += [PSCustomObject]@{ Name = "$name"; Value = $container[$name] }
+ }
+ }
+ else {
+ $memberPairs = @($container.PSObject.Properties)
+ }
+
+ foreach ($member in $memberPairs) {
+ $value = $member.Value
+ if ($value -is [array]) {
+ $nested = Get-SeverityCounts $value ($Depth + 1)
+ $counts.Critical += $nested.Critical
+ $counts.High += $nested.High
+ $counts.Medium += $nested.Medium
+ $counts.Low += $nested.Low
+ continue
+ }
+ $num = $value -as [int]
+ if ($null -eq $num) { continue }
+ if ($member.Name -match 'Total|Score|Percent') { continue }
+ if ($member.Name -match 'Critical') { $counts.Critical += $num }
+ elseif ($member.Name -match 'High') { $counts.High += $num }
+ elseif ($member.Name -match 'Medium') { $counts.Medium += $num }
+ elseif ($member.Name -match 'Low') { $counts.Low += $num }
+ }
+ }
+
+ return $counts
+ }
+
+ function Get-SectionScore {
+ param($Data)
+ if ($null -eq $Data) { return $null }
+
+ # Direct score properties in priority order
+ foreach ($name in @('OverallSecurityScore', 'SecurityScore', 'ComplianceScore', 'Score')) {
+ $value = Get-SafeProperty $Data $name $null
+ $num = $value -as [double]
+ if ($null -ne $num) { return [Math]::Round($num, 1) }
+ }
+
+ # Nested Summary score properties
+ $summary = Get-SafeProperty $Data 'Summary' $null
+ if ($null -ne $summary) {
+ foreach ($name in @('OverallSecurityScore', 'SecurityScore', 'ComplianceScore', 'CompliancePercentage', 'Score')) {
+ $value = Get-SafeProperty $summary $name $null
+ $num = $value -as [double]
+ if ($null -ne $num) { return [Math]::Round($num, 1) }
+ }
+ }
+
+ return $null
+ }
+
+ function Get-SectionHighlights {
+ param($Data, [int]$MaxItems = 8)
+ $highlights = @()
+ if ($null -eq $Data) { return $highlights }
+
+ # Top-level scalar properties only - safe for arbitrary collector output
+ $props = @()
+ if ($Data -is [System.Collections.IDictionary]) {
+ foreach ($key in @($Data.Keys)) {
+ $props += [PSCustomObject]@{ Name = "$key"; Value = $Data[$key] }
+ }
+ }
+ elseif (-not ($Data -is [array]) -and $null -ne $Data.PSObject) {
+ $props = @($Data.PSObject.Properties | Where-Object { $_.MemberType -eq 'NoteProperty' -or $_.MemberType -eq 'Property' })
+ }
+
+ foreach ($prop in $props) {
+ if (@($highlights).Count -ge $MaxItems) { break }
+ $value = $prop.Value
+ if ($null -eq $value) { continue }
+ # Only simple scalar values make readable highlights
+ if ($value -is [string] -or $value -is [bool] -or
+ $value -is [int] -or $value -is [long] -or
+ $value -is [double] -or $value -is [datetime] -or
+ $value -is [enum]) {
+ $text = "$value"
+ if ($text.Length -gt 80) { $text = $text.Substring(0, 77) + '...' }
+ $highlights += @{ Label = "$($prop.Name)"; Value = $text }
+ }
+ }
+
+ return $highlights
+ }
+
+ # ============================================
+ # LOAD JSON DATA (if provided)
+ # ============================================
+ $jsonData = $null
+ if ($FromJsonPath) {
+ Write-Host "`n[LOADING JSON DATA]" -ForegroundColor Cyan
+ try {
+ $jsonData = Get-Content $FromJsonPath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
+ Write-Host " Loaded: $FromJsonPath" -ForegroundColor Green
+ }
+ catch {
+ Write-Error "Failed to parse JSON input file: $_"
+ throw
+ }
+ }
+
+ # ============================================
+ # COLLECT SECTION DATA
+ # ============================================
+ Write-Host "`n[DATA COLLECTION PHASE]" -ForegroundColor Cyan
+
+ $sectionResults = @{}
+ $sectionIndex = 0
+
+ foreach ($section in $allSections) {
+ if (-not ($IncludeSections -contains $section)) { continue }
+ $sectionIndex++
+
+ $result = @{
+ Status = 'Not collected'
+ Data = $null
+ Score = $null
+ Findings = @{ Critical = 0; High = 0; Medium = 0; Low = 0 }
+ Highlights = @()
+ }
+
+ $jsonSectionData = $null
+ if ($null -ne $jsonData) {
+ $jsonSectionData = Get-SafeProperty $jsonData $section $null
+ }
+
+ if ($null -ne $jsonSectionData) {
+ # Data supplied from previously saved JSON output
+ $result.Status = 'Loaded from JSON'
+ $result.Data = $jsonSectionData
+ Write-Host " [$sectionIndex] $section : loaded from JSON" -ForegroundColor Green
+ }
+ elseif (-not $SkipDataCollection -and -not $FromJsonPath) {
+ # Live collection with per-section error isolation
+ $collectorName = $sectionCollectors[$section]
+ $collectorCmd = Get-Command $collectorName -ErrorAction SilentlyContinue
+
+ if ($null -eq $collectorCmd) {
+ Write-Warning " [$sectionIndex] $section : collector '$collectorName' not available - section not collected"
+ }
+ else {
+ try {
+ $collected = & $collectorName -ErrorAction Stop
+ if ($null -ne $collected) {
+ $result.Status = 'Collected'
+ $result.Data = $collected
+ Write-Host " [$sectionIndex] $section : $collectorName OK" -ForegroundColor Green
+ }
+ else {
+ Write-Warning " [$sectionIndex] $section : $collectorName returned no data"
+ }
+ }
+ catch {
+ Write-Warning " [$sectionIndex] $section : $collectorName failed: $_"
+ }
+ }
+ }
+ else {
+ Write-Host " [$sectionIndex] $section : skipped (no live collection)" -ForegroundColor Gray
+ }
+
+ # Derive metrics from whatever data is available
+ if ($null -ne $result.Data) {
+ $result.Score = Get-SectionScore $result.Data
+ $result.Findings = Get-SeverityCounts $result.Data
+ $result.Highlights = @(Get-SectionHighlights $result.Data)
+ }
+
+ $sectionResults[$section] = $result
+ }
+
+ # ============================================
+ # AGGREGATE SUMMARY METRICS
+ # ============================================
+ Write-Host "`n[AGGREGATING RESULTS]" -ForegroundColor Cyan
+
+ $totalFindings = @{ Critical = 0; High = 0; Medium = 0; Low = 0 }
+ $collectedCount = 0
+ $categoryScores = @()
+
+ foreach ($section in $allSections) {
+ if (-not $sectionResults.ContainsKey($section)) { continue }
+ $result = $sectionResults[$section]
+
+ if ($result.Status -ne 'Not collected') { $collectedCount++ }
+
+ $totalFindings.Critical += $result.Findings.Critical
+ $totalFindings.High += $result.Findings.High
+ $totalFindings.Medium += $result.Findings.Medium
+ $totalFindings.Low += $result.Findings.Low
+
+ $categoryScores += @{
+ Section = $section
+ Score = $(if ($null -ne $result.Score) { $result.Score } else { 0 })
+ Status = $result.Status
+ }
+ }
+
+ $grandTotal = $totalFindings.Critical + $totalFindings.High + $totalFindings.Medium + $totalFindings.Low
+
+ # Overall score: average of known section scores, $null if none collected
+ $knownScores = @($categoryScores | Where-Object { $_.Status -ne 'Not collected' } | ForEach-Object { $_.Score } | Where-Object { $_ -gt 0 })
+ $overallScore = $null
+ if (@($knownScores).Count -gt 0) {
+ $overallScore = [Math]::Round(($knownScores | Measure-Object -Average).Average, 1)
+ }
+
+ Write-Host " Sections collected: $collectedCount/$(@($IncludeSections).Count)" -ForegroundColor White
+ Write-Host " Total findings: $grandTotal (Critical: $($totalFindings.Critical), High: $($totalFindings.High), Medium: $($totalFindings.Medium), Low: $($totalFindings.Low))" -ForegroundColor $(
+ if ($totalFindings.Critical -gt 0) { 'Red' }
+ elseif ($totalFindings.High -gt 0) { 'Yellow' }
+ else { 'Green' }
+ )
+ if ($null -ne $overallScore) {
+ Write-Host " Overall score: $overallScore%" -ForegroundColor $(
+ if ($overallScore -ge 80) { 'Green' }
+ elseif ($overallScore -ge 60) { 'Yellow' }
+ else { 'Red' }
+ )
+ }
+
+ # ============================================
+ # BUILD REPORT DATA
+ # ============================================
+ $reportData = @{
+ GeneratedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
+ Hostname = $(if ($env:COMPUTERNAME) { $env:COMPUTERNAME } else { 'Unknown' })
+ DomainName = $(if ($env:USERDNSDOMAIN) { $env:USERDNSDOMAIN } else { 'WORKGROUP' })
+ Username = $(if ($env:USERNAME) { $env:USERNAME } else { 'Unknown' })
+ DataSource = $(if ($FromJsonPath) { 'JSON' } elseif ($SkipDataCollection) { 'None' } else { 'Live' })
+ Sections = $sectionResults
+ SectionOrder = @($allSections | Where-Object { $sectionResults.ContainsKey($_) })
+ TotalFindings = $totalFindings
+ GrandTotal = $grandTotal
+ OverallScore = $overallScore
+ CategoryScores = $categoryScores
+ CollectedCount = $collectedCount
+ SectionCount = @($IncludeSections).Count
+ }
+
+ # ============================================
+ # GENERATE HTML REPORT
+ # ============================================
+ Write-Host "`n[GENERATING HTML REPORT]" -ForegroundColor Cyan
+
+ $htmlFile = Join-Path $OutputPath "ConsolidatedSecurityReport_$timestamp.html"
+ Generate-ConsolidatedReportHTML -ReportData $reportData -OutputFile $htmlFile
+
+ Write-Host " Report saved: $htmlFile" -ForegroundColor Green
+ Write-Host " File size: $([Math]::Round((Get-Item $htmlFile).Length / 1KB, 2)) KB" -ForegroundColor Gray
+
+ # ============================================
+ # OPTIONAL JSON EXPORT
+ # ============================================
+ $jsonOutFile = $null
+ if ($SaveJson) {
+ try {
+ $jsonOutFile = Join-Path $OutputPath "ConsolidatedReportData_$timestamp.json"
+ $jsonExport = @{}
+ foreach ($section in $reportData.SectionOrder) {
+ $jsonExport[$section] = $sectionResults[$section].Data
+ }
+ $jsonExport | ConvertTo-Json -Depth 10 | Out-File $jsonOutFile -Encoding UTF8 -Force
+ Write-Host " Raw data saved: $jsonOutFile" -ForegroundColor Green
+ }
+ catch {
+ Write-Warning " Failed to save JSON export: $_"
+ $jsonOutFile = $null
+ }
+ }
+
+ if ($OpenInBrowser) {
+ Write-Host "`n[OPENING IN BROWSER]" -ForegroundColor Cyan
+ try {
+ Start-Process $htmlFile
+ }
+ catch {
+ Write-Warning " Failed to open report in browser: $_"
+ }
+ }
+
+ # ============================================
+ # RETURN SUMMARY OBJECT
+ # ============================================
+ $notCollected = @($reportData.SectionOrder | Where-Object { $sectionResults[$_].Status -eq 'Not collected' })
+
+ return [PSCustomObject]@{
+ Success = $true
+ ReportPath = $htmlFile
+ JsonPath = $jsonOutFile
+ DataSource = $reportData.DataSource
+ GeneratedDate = $reportData.GeneratedDate
+ SectionsCollected = $collectedCount
+ SectionsNotCollected = @($notCollected)
+ TotalFindings = $grandTotal
+ CriticalFindings = $totalFindings.Critical
+ HighFindings = $totalFindings.High
+ MediumFindings = $totalFindings.Medium
+ LowFindings = $totalFindings.Low
+ OverallScore = $overallScore
+ GenerationTime = [Math]::Round(((Get-Date) - $reportStartTime).TotalSeconds, 2)
+ }
+ }
+ catch {
+ Write-Error "Consolidated report generation failed: $_"
+ Write-Host "`nStack Trace:" -ForegroundColor Red
+ Write-Host $_.ScriptStackTrace -ForegroundColor Gray
+ throw
+ }
+ }
+
+ end {
+ $totalTime = [Math]::Round(((Get-Date) - $reportStartTime).TotalSeconds, 2)
+
+ Write-Host "`n================================================================" -ForegroundColor Green
+ Write-Host " CONSOLIDATED REPORT COMPLETE" -ForegroundColor Green
+ Write-Host "================================================================" -ForegroundColor Green
+ Write-Host " Total Execution Time: $totalTime seconds" -ForegroundColor White
+ }
+}
+
+# ============================================
+# HELPER FUNCTION: Generate Consolidated Report HTML
+# ============================================
+function Generate-ConsolidatedReportHTML {
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory = $true)]
+ [hashtable]$ReportData,
+
+ [Parameter(Mandatory = $true)]
+ [string]$OutputFile
+ )
+
+ # Severity colors (match New-SecurityDashboard / Generate-DashboardHTML style)
+ $criticalColor = '#d32f2f'
+ $highColor = '#f57c00'
+ $mediumColor = '#fbc02d'
+ $lowColor = '#388e3c'
+ $accentColor = '#0078d4'
+
+ # Score color
+ $scoreDisplay = $(if ($null -ne $ReportData.OverallScore) { "$($ReportData.OverallScore)%" } else { 'N/A' })
+ $scoreColor = $(if ($null -eq $ReportData.OverallScore) { '#666666' }
+ elseif ($ReportData.OverallScore -ge 80) { '#107c10' }
+ elseif ($ReportData.OverallScore -ge 60) { '#f7630c' }
+ else { '#d13438' })
+
+ # Chart.js datasets (labels are fixed internal values - safe to embed)
+ $severityLabels = "'Critical','High','Medium','Low'"
+ $severityValues = "$($ReportData.TotalFindings.Critical),$($ReportData.TotalFindings.High),$($ReportData.TotalFindings.Medium),$($ReportData.TotalFindings.Low)"
+
+ $categoryLabels = (@($ReportData.CategoryScores) | ForEach-Object { "'$($_.Section)'" }) -join ','
+ $categoryValues = (@($ReportData.CategoryScores) | ForEach-Object { $_.Score }) -join ','
+
+ # Build HTML using StringBuilder to avoid parse errors
+ $html = New-Object System.Text.StringBuilder
+
+ [void]$html.AppendLine("<!DOCTYPE html>")
+ [void]$html.AppendLine("<html lang='en'>")
+ [void]$html.AppendLine("<head>")
+ [void]$html.AppendLine(" <meta charset='UTF-8'>")
+ [void]$html.AppendLine(" <meta name='viewport' content='width=device-width, initial-scale=1.0'>")
+ [void]$html.AppendLine(" <title>Consolidated Security Report - $($ReportData.Hostname)</title>")
+ [void]$html.AppendLine(" <script src='https://cdn.jsdelivr.net/npm/chart.js'></script>")
+ [void]$html.AppendLine(" <style>")
+ [void]$html.AppendLine(" * { margin: 0; padding: 0; box-sizing: border-box; }")
+ [void]$html.AppendLine(" body { font-family: 'Segoe UI', Tahoma, sans-serif; background: #f5f5f5; color: #333333; padding: 20px; line-height: 1.6; }")
+ [void]$html.AppendLine(" .container { max-width: 1600px; margin: 0 auto; }")
+ [void]$html.AppendLine(" .header { background: linear-gradient(135deg, #0d47a1, #1565c0); color: white; padding: 30px; border-radius: 10px; margin-bottom: 30px; box-shadow: 0 4px 15px rgba(0,0,0,0.3); }")
+ [void]$html.AppendLine(" .header h1 { font-size: 32px; margin-bottom: 5px; }")
+ [void]$html.AppendLine(" .header-subtitle { font-size: 14px; opacity: 0.9; margin-bottom: 15px; }")
+ [void]$html.AppendLine(" .header-info { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px; margin-top: 15px; }")
+ [void]$html.AppendLine(" .header-info-item { background: rgba(255,255,255,0.1); padding: 10px; border-radius: 5px; }")
+ [void]$html.AppendLine(" .header-info-label { font-size: 11px; opacity: 0.8; }")
+ [void]$html.AppendLine(" .header-info-value { font-size: 14px; font-weight: 600; margin-top: 3px; }")
+ [void]$html.AppendLine(" .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 30px; }")
+ [void]$html.AppendLine(" .card { background: #ffffff; border: 1px solid #dddddd; border-radius: 8px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); transition: transform 0.2s; }")
+ [void]$html.AppendLine(" .card:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.15); }")
+ [void]$html.AppendLine(" .card-header { font-size: 16px; font-weight: 600; color: #0078d4; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 2px solid #dddddd; }")
+ [void]$html.AppendLine(" .large-metric { text-align: center; padding: 30px 15px; }")
+ [void]$html.AppendLine(" .large-metric-value { font-size: 64px; font-weight: bold; margin-bottom: 8px; }")
+ [void]$html.AppendLine(" .large-metric-label { font-size: 16px; color: #666; }")
+ [void]$html.AppendLine(" .metric { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #f0f0f0; }")
+ [void]$html.AppendLine(" .metric:last-child { border-bottom: none; }")
+ [void]$html.AppendLine(" .metric-label { font-size: 14px; color: #666; }")
+ [void]$html.AppendLine(" .metric-value { font-size: 16px; font-weight: bold; }")
+ [void]$html.AppendLine(" .critical { color: $criticalColor; }")
+ [void]$html.AppendLine(" .high { color: $highColor; }")
+ [void]$html.AppendLine(" .medium { color: $mediumColor; }")
+ [void]$html.AppendLine(" .low { color: $lowColor; }")
+ [void]$html.AppendLine(" h2 { color: #0078d4; margin: 30px 0 15px 0; padding-left: 10px; border-left: 4px solid #0078d4; font-size: 20px; }")
+ [void]$html.AppendLine(" .chart-container { position: relative; height: 280px; margin-top: 15px; }")
+ [void]$html.AppendLine(" .status-badge { display: inline-block; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 600; }")
+ [void]$html.AppendLine(" .status-ok { background: #dff6dd; color: #107c10; }")
+ [void]$html.AppendLine(" .status-none { background: #f0f0f0; color: #666666; }")
+ [void]$html.AppendLine(" .footer { margin-top: 40px; padding-top: 20px; border-top: 2px solid #dddddd; text-align: center; color: #999; font-size: 12px; }")
+ [void]$html.AppendLine(" @media (max-width: 768px) { .grid { grid-template-columns: 1fr; } .header h1 { font-size: 24px; } .large-metric-value { font-size: 48px; } }")
+ [void]$html.AppendLine(" </style>")
+ [void]$html.AppendLine("</head>")
+ [void]$html.AppendLine("<body>")
+ [void]$html.AppendLine(" <div class='container'>")
+
+ # Header
+ [void]$html.AppendLine(" <div class='header'>")
+ [void]$html.AppendLine(" <h1>Consolidated Security Report</h1>")
+ [void]$html.AppendLine(" <div class='header-subtitle'>Unified assessment across all major modules - WindowsSecurityAudit Module</div>")
+ [void]$html.AppendLine(" <div class='header-info'>")
+ [void]$html.AppendLine(" <div class='header-info-item'><div class='header-info-label'>Hostname</div><div class='header-info-value'>$($ReportData.Hostname)</div></div>")
+ [void]$html.AppendLine(" <div class='header-info-item'><div class='header-info-label'>Domain</div><div class='header-info-value'>$($ReportData.DomainName)</div></div>")
+ [void]$html.AppendLine(" <div class='header-info-item'><div class='header-info-label'>User</div><div class='header-info-value'>$($ReportData.Username)</div></div>")
+ [void]$html.AppendLine(" <div class='header-info-item'><div class='header-info-label'>Generated</div><div class='header-info-value'>$($ReportData.GeneratedDate)</div></div>")
+ [void]$html.AppendLine(" <div class='header-info-item'><div class='header-info-label'>Data Source</div><div class='header-info-value'>$($ReportData.DataSource)</div></div>")
+ [void]$html.AppendLine(" <div class='header-info-item'><div class='header-info-label'>Sections</div><div class='header-info-value'>$($ReportData.CollectedCount)/$($ReportData.SectionCount) collected</div></div>")
+ [void]$html.AppendLine(" </div>")
+ [void]$html.AppendLine(" </div>")
+
+ # ============================================
+ # SUMMARY CARD GRID
+ # ============================================
+ [void]$html.AppendLine(" <div class='grid'>")
+
+ # Overall Score Card
+ [void]$html.AppendLine(" <div class='card'>")
+ [void]$html.AppendLine(" <div class='large-metric'>")
+ [void]$html.AppendLine(" <div class='large-metric-value' style='color: $scoreColor;'>$scoreDisplay</div>")
+ [void]$html.AppendLine(" <div class='large-metric-label'>Overall Security Score</div>")
+ [void]$html.AppendLine(" </div>")
+ [void]$html.AppendLine(" </div>")
+
+ # Total Findings Card
+ [void]$html.AppendLine(" <div class='card'>")
+ [void]$html.AppendLine(" <div class='large-metric'>")
+ [void]$html.AppendLine(" <div class='large-metric-value' style='color: $accentColor;'>$($ReportData.GrandTotal)</div>")
+ [void]$html.AppendLine(" <div class='large-metric-label'>Total Findings</div>")
+ [void]$html.AppendLine(" </div>")
+ [void]$html.AppendLine(" </div>")
+
+ # Findings by Severity Card
+ [void]$html.AppendLine(" <div class='card'>")
+ [void]$html.AppendLine(" <div class='card-header'>Findings by Severity</div>")
+ [void]$html.AppendLine(" <div class='metric'><span class='metric-label'>Critical</span><span class='metric-value critical'>$($ReportData.TotalFindings.Critical)</span></div>")
+ [void]$html.AppendLine(" <div class='metric'><span class='metric-label'>High</span><span class='metric-value high'>$($ReportData.TotalFindings.High)</span></div>")
+ [void]$html.AppendLine(" <div class='metric'><span class='metric-label'>Medium</span><span class='metric-value medium'>$($ReportData.TotalFindings.Medium)</span></div>")
+ [void]$html.AppendLine(" <div class='metric'><span class='metric-label'>Low</span><span class='metric-value low'>$($ReportData.TotalFindings.Low)</span></div>")
+ [void]$html.AppendLine(" </div>")
+
+ # Collection Status Card
+ [void]$html.AppendLine(" <div class='card'>")
+ [void]$html.AppendLine(" <div class='card-header'>Collection Status</div>")
+ foreach ($section in $ReportData.SectionOrder) {
+ $sectionResult = $ReportData.Sections[$section]
+ $statusText = "$($sectionResult.Status)"
+ $badgeClass = $(if ($statusText -eq 'Not collected') { 'status-none' } else { 'status-ok' })
+ [void]$html.AppendLine(" <div class='metric'><span class='metric-label'>$section</span><span class='status-badge $badgeClass'>$statusText</span></div>")
+ }
+ [void]$html.AppendLine(" </div>")
+
+ [void]$html.AppendLine(" </div>")
+
+ # ============================================
+ # CHARTS
+ # ============================================
+ [void]$html.AppendLine(" <h2>Visual Analytics</h2>")
+ [void]$html.AppendLine(" <div class='grid'>")
+ [void]$html.AppendLine(" <div class='card'>")
+ [void]$html.AppendLine(" <div class='card-header'>Findings by Severity</div>")
+ [void]$html.AppendLine(" <div class='chart-container'><canvas id='severityChart'></canvas></div>")
+ [void]$html.AppendLine(" </div>")
+ [void]$html.AppendLine(" <div class='card'>")
+ [void]$html.AppendLine(" <div class='card-header'>Category Scores</div>")
+ [void]$html.AppendLine(" <div class='chart-container'><canvas id='categoryChart'></canvas></div>")
+ [void]$html.AppendLine(" </div>")
+ [void]$html.AppendLine(" </div>")
+
+ # Chart.js initialization
+ [void]$html.AppendLine(" <script>")
+ [void]$html.AppendLine(" const sCtx = document.getElementById('severityChart').getContext('2d');")
+ [void]$html.AppendLine(" new Chart(sCtx, {")
+ [void]$html.AppendLine(" type: 'doughnut',")
+ [void]$html.AppendLine(" data: {")
+ [void]$html.AppendLine(" labels: [$severityLabels],")
+ [void]$html.AppendLine(" datasets: [{")
+ [void]$html.AppendLine(" data: [$severityValues],")
+ [void]$html.AppendLine(" backgroundColor: ['$criticalColor', '$highColor', '$mediumColor', '$lowColor']")
+ [void]$html.AppendLine(" }]")
+ [void]$html.AppendLine(" },")
+ [void]$html.AppendLine(" options: {")
+ [void]$html.AppendLine(" responsive: true,")
+ [void]$html.AppendLine(" maintainAspectRatio: false,")
+ [void]$html.AppendLine(" plugins: { legend: { position: 'bottom' } }")
+ [void]$html.AppendLine(" }")
+ [void]$html.AppendLine(" });")
+ [void]$html.AppendLine(" const cCtx = document.getElementById('categoryChart').getContext('2d');")
+ [void]$html.AppendLine(" new Chart(cCtx, {")
+ [void]$html.AppendLine(" type: 'bar',")
+ [void]$html.AppendLine(" data: {")
+ [void]$html.AppendLine(" labels: [$categoryLabels],")
+ [void]$html.AppendLine(" datasets: [{")
+ [void]$html.AppendLine(" label: 'Category Score',")
+ [void]$html.AppendLine(" data: [$categoryValues],")
+ [void]$html.AppendLine(" backgroundColor: '$accentColor'")
+ [void]$html.AppendLine(" }]")
+ [void]$html.AppendLine(" },")
+ [void]$html.AppendLine(" options: {")
+ [void]$html.AppendLine(" responsive: true,")
+ [void]$html.AppendLine(" maintainAspectRatio: false,")
+ [void]$html.AppendLine(" plugins: { legend: { display: false } },")
+ [void]$html.AppendLine(" scales: { y: { beginAtZero: true, max: 100 } }")
+ [void]$html.AppendLine(" }")
+ [void]$html.AppendLine(" });")
+ [void]$html.AppendLine(" </script>")
+
+ # ============================================
+ # PER-SECTION DETAIL CARDS
+ # ============================================
+ [void]$html.AppendLine(" <h2>Section Details</h2>")
+ [void]$html.AppendLine(" <div class='grid'>")
+
+ foreach ($section in $ReportData.SectionOrder) {
+ $sectionResult = $ReportData.Sections[$section]
+ $statusText = "$($sectionResult.Status)"
+ $badgeClass = $(if ($statusText -eq 'Not collected') { 'status-none' } else { 'status-ok' })
+
+ [void]$html.AppendLine(" <div class='card'>")
+ [void]$html.AppendLine(" <div class='card-header'>$section <span class='status-badge $badgeClass' style='float: right;'>$statusText</span></div>")
+
+ if ($null -ne $sectionResult.Score) {
+ [void]$html.AppendLine(" <div class='metric'><span class='metric-label'>Score</span><span class='metric-value'>$($sectionResult.Score)%</span></div>")
+ }
+
+ $sectionFindings = $sectionResult.Findings
+ $sectionTotal = $sectionFindings.Critical + $sectionFindings.High + $sectionFindings.Medium + $sectionFindings.Low
+ [void]$html.AppendLine(" <div class='metric'><span class='metric-label'>Findings</span><span class='metric-value'>$sectionTotal</span></div>")
+
+ # Best-effort scalar highlights from the raw collector output
+ foreach ($highlight in @($sectionResult.Highlights)) {
+ $label = "$($highlight.Label)" -replace '<', '&lt;' -replace '>', '&gt;'
+ $value = "$($highlight.Value)" -replace '<', '&lt;' -replace '>', '&gt;'
+ [void]$html.AppendLine(" <div class='metric'><span class='metric-label'>$label</span><span class='metric-value' style='font-size: 13px;'>$value</span></div>")
+ }
+
+ [void]$html.AppendLine(" </div>")
+ }
+
+ [void]$html.AppendLine(" </div>")
+
+ # Footer
+ [void]$html.AppendLine(" <div class='footer'>")
+ [void]$html.AppendLine(" <p><strong>WindowsSecurityAudit Module - Consolidated Security Report</strong></p>")
+ [void]$html.AppendLine(" <p>Generated: $($ReportData.GeneratedDate) | Host: $($ReportData.Hostname) | Data Source: $($ReportData.DataSource) | Sections: $($ReportData.CollectedCount)/$($ReportData.SectionCount)</p>")
+ [void]$html.AppendLine(" <p>Charts powered by Chart.js (jsDelivr CDN) - internet access required for chart rendering</p>")
+ [void]$html.AppendLine(" </div>")
+
+ [void]$html.AppendLine(" </div>")
+ [void]$html.AppendLine("</body>")
+ [void]$html.AppendLine("</html>")
+
+ # Save HTML to file
+ $html.ToString() | Out-File -FilePath $OutputFile -Encoding UTF8 -Force
+}
diff --git a/Reporting/New-ExecutiveReport.ps1 b/Reporting/New-ExecutiveReport.ps1
index a6064d6..6bccf94 100644
--- a/Reporting/New-ExecutiveReport.ps1
+++ b/Reporting/New-ExecutiveReport.ps1
@@ -65,7 +65,7 @@ function New-ExecutiveReport {
.PARAMETER CustomLogo
Path to a custom logo image file to include in the report header
- Supported formats: PNG, JPG
+ Supported formats: PNG, JPG, SVG
.EXAMPLE
New-ExecutiveReport -MetricsFile "C:\Reports\SecurityMetrics_20251008.json" -OutputPath "C:\Reports" -OutputFormat HTML
@@ -119,7 +119,7 @@ function New-ExecutiveReport {
[CmdletBinding()]
param(
[Parameter()]
- [string]$MetricsFile,
+ [object]$MetricsFile,
[Parameter()]
[string]$OutputPath = ".",
@@ -187,6 +187,44 @@ function New-ExecutiveReport {
Write-Host "Output Path: $OutputPath" -ForegroundColor Gray
Write-Host "Output Format: $OutputFormat" -ForegroundColor Gray
Write-Host "Audience: $Audience" -ForegroundColor Gray
+
+ # Prepare custom logo as base64 data URI (falls back to text header)
+ $logoDataUri = $null
+ if ($CustomLogo) {
+ try {
+ if (Test-Path $CustomLogo) {
+ $logoItem = Get-Item $CustomLogo
+ $extension = $logoItem.Extension.ToLower()
+ $mimeTypes = @{
+ '.png' = 'image/png'
+ '.jpg' = 'image/jpeg'
+ '.jpeg' = 'image/jpeg'
+ '.svg' = 'image/svg+xml'
+ }
+
+ if ($mimeTypes.ContainsKey($extension)) {
+ if ($logoItem.Length -le 2MB) {
+ $logoBytes = [System.IO.File]::ReadAllBytes($logoItem.FullName)
+ $logoDataUri = "data:$($mimeTypes[$extension]);base64,$([Convert]::ToBase64String($logoBytes))"
+ Write-Host "Custom Logo: $($logoItem.Name) ($([math]::Round($logoItem.Length / 1KB, 2)) KB)" -ForegroundColor Gray
+ }
+ else {
+ Write-Warning "Custom logo exceeds 2 MB size limit - using text header"
+ }
+ }
+ else {
+ Write-Warning "Custom logo format '$extension' not supported (use PNG, JPG, or SVG) - using text header"
+ }
+ }
+ else {
+ Write-Warning "Custom logo not found: $CustomLogo - using text header"
+ }
+ }
+ catch {
+ Write-Warning "Could not read custom logo '$CustomLogo' - using text header"
+ $logoDataUri = $null
+ }
+ }
}
process {
@@ -197,6 +235,14 @@ function New-ExecutiveReport {
function Get-SafeProperty {
param($Object, $PropertyName, $Default = $null)
if ($null -eq $Object) { return $Default }
+ if ($Object -is [System.Collections.IDictionary]) {
+ if ($Object.Contains($PropertyName)) {
+ $value = $Object[$PropertyName]
+ if ($null -eq $value) { return $Default }
+ return $value
+ }
+ return $Default
+ }
if ($Object.PSObject.Properties[$PropertyName]) {
$value = $Object.$PropertyName
if ($null -eq $value) { return $Default }
@@ -278,6 +324,7 @@ function New-ExecutiveReport {
CompanyName = $CompanyName
Confidential = $Confidential
Audience = $Audience
+ LogoDataUri = $logoDataUri
# Source Metrics
Metrics = $metrics
@@ -903,10 +950,10 @@ function New-ExecutiveReport {
)
$reportData.RemediationRoadmap.ResourceEstimate.EstimatedCost =
- if ($riskLevel -eq 'Critical') { "$$$$$ - Significant investment required" }
- elseif ($riskLevel -eq 'High') { "$$$$ - Substantial investment needed" }
- elseif ($riskLevel -eq 'Medium') { "$$$ - Moderate investment" }
- else { "$$ - Limited investment" }
+ if ($riskLevel -eq 'Critical') { '$$$$$ - Significant investment required' }
+ elseif ($riskLevel -eq 'High') { '$$$$ - Substantial investment needed' }
+ elseif ($riskLevel -eq 'Medium') { '$$$ - Moderate investment' }
+ else { '$$ - Limited investment' }
# ============================================
# BUILD TREND ANALYSIS
@@ -1096,7 +1143,7 @@ function Generate-HTMLReport {
param($Array)
if ($null -eq $Array) { return 0 }
if ($Array -is [array]) { return $Array.Count }
- if ($Array.Count) { return $Array.Count }
+ if ($Array.PSObject.Properties['Count']) { return $Array.Count }
return 1 # Single item
}
@@ -1327,6 +1374,9 @@ function Generate-HTMLReport {
})
<div class="header">
+ $(if ($ReportData.LogoDataUri) {
+ "<img src='$($ReportData.LogoDataUri)' alt='$($ReportData.CompanyName) Logo' style='max-height: 80px; max-width: 300px; margin-bottom: 15px;' />"
+ })
<h1>$($ReportData.ReportTitle)</h1>
<div class="subtitle">$($ReportData.CompanyName)</div>
<div class="subtitle">Generated: $($ReportData.GeneratedDate)</div>
@@ -1675,7 +1725,7 @@ function Generate-ExecutiveSummary {
param($Array)
if ($null -eq $Array) { return 0 }
if ($Array -is [array]) { return $Array.Count }
- if ($Array.Count) { return $Array.Count }
+ if ($Array.PSObject.Properties['Count']) { return $Array.Count }
return 1 # Single item
}
diff --git a/Reporting/New-SecurityDashboard.ps1 b/Reporting/New-SecurityDashboard.ps1
index d494f10..f9a6e02 100644
--- a/Reporting/New-SecurityDashboard.ps1
+++ b/Reporting/New-SecurityDashboard.ps1
@@ -269,6 +269,16 @@ function New-SecurityDashboard {
$functionCount = 0
+ # Per-category threat counts (populated by the Detection module)
+ $persistenceCount = 0
+ $processCount = 0
+ $authCount = 0
+ $lateralCount = 0
+ $aptCount = 0
+ $lolbinsCount = 0
+ $exfilCount = 0
+ $networkCount = 0
+
# ============================================
# CORE MODULE (4 functions)
# ============================================
@@ -391,15 +401,23 @@ function New-SecurityDashboard {
}
# Calculate total threats
+ $persistenceCount = if ($script:dashboardData.Detection.PersistenceMechanisms.PSObject.Properties['SuspiciousCount']) { $script:dashboardData.Detection.PersistenceMechanisms.SuspiciousCount } else { @($script:dashboardData.Detection.PersistenceMechanisms).Count }
+ $processCount = @($script:dashboardData.Detection.SuspiciousProcesses).Count
+ $authCount = if ($script:dashboardData.Detection.SuspiciousAuthentications.PSObject.Properties['Statistics'] -and $script:dashboardData.Detection.SuspiciousAuthentications.Statistics) {
+ $script:dashboardData.Detection.SuspiciousAuthentications.Statistics.TotalFailedLogons +
+ $script:dashboardData.Detection.SuspiciousAuthentications.Statistics.TotalLockouts +
+ $script:dashboardData.Detection.SuspiciousAuthentications.Statistics.TotalPrivilegeUse +
+ $script:dashboardData.Detection.SuspiciousAuthentications.Statistics.TotalExplicitCreds
+ } else { @($script:dashboardData.Detection.SuspiciousAuthentications).Count }
+ $lateralCount = if ($script:dashboardData.Detection.LateralMovement.PSObject.Properties['Summary'] -and $script:dashboardData.Detection.LateralMovement.Summary) { $script:dashboardData.Detection.LateralMovement.Summary.TotalIndicators } else { @($script:dashboardData.Detection.LateralMovement).Count }
+ $aptCount = if ($script:dashboardData.Detection.APTIndicators.PSObject.Properties['Summary'] -and $script:dashboardData.Detection.APTIndicators.Summary) { $script:dashboardData.Detection.APTIndicators.Summary.TotalIndicators } else { @($script:dashboardData.Detection.APTIndicators).Count }
+ $lolbinsCount = if ($script:dashboardData.Detection.LivingOffLand.PSObject.Properties['Summary'] -and $script:dashboardData.Detection.LivingOffLand.Summary) { $script:dashboardData.Detection.LivingOffLand.Summary.TotalDetections } else { @($script:dashboardData.Detection.LivingOffLand).Count }
+ $exfilCount = if ($script:dashboardData.Detection.DataExfiltration.PSObject.Properties['Summary'] -and $script:dashboardData.Detection.DataExfiltration.Summary) { $script:dashboardData.Detection.DataExfiltration.Summary.TotalIndicators } else { @($script:dashboardData.Detection.DataExfiltration).Count }
+ $networkCount = if ($script:dashboardData.Detection.NetworkAnomalies.PSObject.Properties['TotalAnomalies']) { $script:dashboardData.Detection.NetworkAnomalies.TotalAnomalies } else { @($script:dashboardData.Detection.NetworkAnomalies).Count }
+
$script:dashboardData.Detection.TotalThreats =
- @($script:dashboardData.Detection.PersistenceMechanisms).Count +
- @($script:dashboardData.Detection.SuspiciousProcesses).Count +
- @($script:dashboardData.Detection.SuspiciousAuthentications).Count +
- @($script:dashboardData.Detection.LateralMovement).Count +
- @($script:dashboardData.Detection.APTIndicators).Count +
- @($script:dashboardData.Detection.LivingOffLand).Count +
- @($script:dashboardData.Detection.DataExfiltration).Count +
- @($script:dashboardData.Detection.NetworkAnomalies).Count
+ $persistenceCount + $processCount + $authCount + $lateralCount +
+ $aptCount + $lolbinsCount + $exfilCount + $networkCount
$script:dashboardData.Performance.ModuleExecutionTimes['Detection'] = ((Get-Date) - $detStart).TotalSeconds
Write-Host " Total threats detected: $($script:dashboardData.Detection.TotalThreats)" -ForegroundColor $(if ($script:dashboardData.Detection.TotalThreats -gt 0) { 'Yellow' } else { 'Green' })
@@ -478,6 +496,9 @@ function New-SecurityDashboard {
try {
$c = Test-CISBenchmark -ErrorAction Stop
+ if (-not $c.PSObject.Properties['ComplianceScore'] -and $c.PSObject.Properties['Summary'] -and $c.Summary) {
+ $c | Add-Member -NotePropertyName ComplianceScore -NotePropertyValue $c.Summary.CompliancePercentage
+ }
$script:dashboardData.Compliance.CIS = $c
$functionCount++
Write-Host " [19/54] Test-CISBenchmark: $($c.ComplianceScore)%" -ForegroundColor Green
@@ -488,6 +509,9 @@ function New-SecurityDashboard {
try {
$c = Test-NISTCompliance -ErrorAction Stop
+ if (-not $c.PSObject.Properties['ComplianceScore'] -and $c.PSObject.Properties['Summary'] -and $c.Summary) {
+ $c | Add-Member -NotePropertyName ComplianceScore -NotePropertyValue $c.Summary.CompliancePercentage
+ }
$script:dashboardData.Compliance.NIST = $c
$functionCount++
Write-Host " [20/54] Test-NISTCompliance: $($c.ComplianceScore)%" -ForegroundColor Green
@@ -498,6 +522,9 @@ function New-SecurityDashboard {
try {
$c = Test-PCI-DSS -ErrorAction Stop
+ if (-not $c.PSObject.Properties['ComplianceScore'] -and $c.PSObject.Properties['Summary'] -and $c.Summary) {
+ $c | Add-Member -NotePropertyName ComplianceScore -NotePropertyValue $c.Summary.CompliancePercentage
+ }
$script:dashboardData.Compliance.PCIDSS = $c
$functionCount++
Write-Host " [21/54] Test-PCI-DSS: $($c.ComplianceScore)%" -ForegroundColor Green
@@ -648,8 +675,10 @@ function New-SecurityDashboard {
try {
$v = Get-VulnerabilityAssessment -ErrorAction Stop
$script:dashboardData.Vulnerability.Assessment = $v
- if ($v -and $v.Summary -and $v.Summary.TotalVulnerabilities) {
- $script:dashboardData.Vulnerability.TotalVulnerabilities = $v.Summary.TotalVulnerabilities
+ if ($v -and $v.Summary) {
+ $script:dashboardData.Vulnerability.TotalVulnerabilities =
+ $v.Summary.CriticalVulnerabilities + $v.Summary.HighVulnerabilities +
+ $v.Summary.MediumVulnerabilities + $v.Summary.LowVulnerabilities
}
$functionCount++
Write-Host " [33/54] Get-VulnerabilityAssessment: Found $($script:dashboardData.Vulnerability.TotalVulnerabilities)" -ForegroundColor Green
@@ -742,7 +771,7 @@ function New-SecurityDashboard {
if ($DetailLevel -eq 'Detailed') {
try {
- $script:dashboardData.Forensics.ForensicCollection = Invoke-ForensicCollection -ErrorAction Stop
+ $script:dashboardData.Forensics.ForensicCollection = Invoke-ForensicCollection -CollectionType Quick -OutputPath $ExportPath -ErrorAction Stop
$functionCount++
Write-Host " [41/54] Invoke-ForensicCollection: OK" -ForegroundColor Green
} catch {
@@ -882,7 +911,7 @@ function New-SecurityDashboard {
$respStart = Get-Date
try {
- $script:dashboardData.Response.IncidentResponse = Invoke-IncidentResponse -WhatIf -ErrorAction Stop
+ $script:dashboardData.Response.IncidentResponse = Invoke-IncidentResponse -Severity Low -WhatIf -ErrorAction Stop
$functionCount++
Write-Host " [52/54] Invoke-IncidentResponse (Check): OK" -ForegroundColor Green
} catch {
@@ -983,11 +1012,11 @@ function New-SecurityDashboard {
# Threat distribution
$script:dashboardData.ChartsData.ThreatDistribution = @(
- @{ Category = "Persistence"; Count = @($script:dashboardData.Detection.PersistenceMechanisms).Count }
- @{ Category = "Processes"; Count = @($script:dashboardData.Detection.SuspiciousProcesses).Count }
- @{ Category = "Auth"; Count = @($script:dashboardData.Detection.SuspiciousAuthentications).Count }
- @{ Category = "Lateral"; Count = @($script:dashboardData.Detection.LateralMovement).Count }
- @{ Category = "APT"; Count = @($script:dashboardData.Detection.APTIndicators).Count }
+ @{ Category = "Persistence"; Count = $persistenceCount }
+ @{ Category = "Processes"; Count = $processCount }
+ @{ Category = "Auth"; Count = $authCount }
+ @{ Category = "Lateral"; Count = $lateralCount }
+ @{ Category = "APT"; Count = $aptCount }
)
# Module status
@@ -1247,13 +1276,13 @@ function Generate-DashboardHTML {
[void]$html.AppendLine(" </div>")
# Detection Module Results
- if ($Data.Detection.TotalThreats -ne $null) {
+ if ($null -ne $Data.Detection.TotalThreats) {
[void]$html.AppendLine(" <h2>Threat Detection (Total: $($Data.Detection.TotalThreats))</h2>")
[void]$html.AppendLine(" <div class='grid'>")
- [void]$html.AppendLine(" <div class='card'><div class='card-header'>Persistence Mechanisms</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(@($Data.Detection.PersistenceMechanisms).Count)</span></div></div>")
+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>Persistence Mechanisms</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(if ($Data.Detection.PersistenceMechanisms.PSObject.Properties['SuspiciousCount']) { $Data.Detection.PersistenceMechanisms.SuspiciousCount } else { @($Data.Detection.PersistenceMechanisms).Count })</span></div></div>")
[void]$html.AppendLine(" <div class='card'><div class='card-header'>Suspicious Processes</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(@($Data.Detection.SuspiciousProcesses).Count)</span></div></div>")
- [void]$html.AppendLine(" <div class='card'><div class='card-header'>Authentication Anomalies</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(@($Data.Detection.SuspiciousAuthentications).Count)</span></div></div>")
- [void]$html.AppendLine(" <div class='card'><div class='card-header'>APT Indicators</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(@($Data.Detection.APTIndicators).Count)</span></div></div>")
+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>Authentication Anomalies</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(if ($Data.Detection.SuspiciousAuthentications.PSObject.Properties['Statistics'] -and $Data.Detection.SuspiciousAuthentications.Statistics) { $Data.Detection.SuspiciousAuthentications.Statistics.TotalFailedLogons + $Data.Detection.SuspiciousAuthentications.Statistics.TotalLockouts + $Data.Detection.SuspiciousAuthentications.Statistics.TotalPrivilegeUse + $Data.Detection.SuspiciousAuthentications.Statistics.TotalExplicitCreds } else { @($Data.Detection.SuspiciousAuthentications).Count })</span></div></div>")
+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>APT Indicators</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(if ($Data.Detection.APTIndicators.PSObject.Properties['Summary'] -and $Data.Detection.APTIndicators.Summary) { $Data.Detection.APTIndicators.Summary.TotalIndicators } else { @($Data.Detection.APTIndicators).Count })</span></div></div>")
[void]$html.AppendLine(" </div>")
}
diff --git a/Response/Export-SecurityReport.ps1 b/Response/Export-SecurityReport.ps1
index 8cddef5..85432c2 100644
--- a/Response/Export-SecurityReport.ps1
+++ b/Response/Export-SecurityReport.ps1
@@ -115,7 +115,7 @@ function Export-SecurityReport {
}
}
- if ($processes.Count -gt 0) {
+ if (@($processes).Count -gt 0) {
$processArray = @($processes)
$highSeverityProcs = @($processArray | Where-Object { $_.SuspicionScore -ge 70 })
if ($highSeverityProcs.Count -gt 0) {
@@ -207,6 +207,45 @@ if ($highSeverityProcs.Count -gt 0) {
if ($Format -in @('HTML', 'All')) {
Write-Host "Generating HTML report..." -ForegroundColor Yellow
+ # Build findings-by-severity bar chart (inline SVG) if requested
+ $chartHtml = ''
+ if ($IncludeCharts) {
+ $severityData = @(
+ @{ Label = 'Critical'; Count = $reportData.Summary.CriticalFindings; Color = '#e74c3c' }
+ @{ Label = 'High'; Count = $reportData.Summary.HighFindings; Color = '#e67e22' }
+ @{ Label = 'Medium'; Count = $reportData.Summary.MediumFindings; Color = '#f39c12' }
+ @{ Label = 'Low'; Count = $reportData.Summary.LowFindings; Color = '#95a5a6' }
+ )
+
+ $maxCount = ($severityData | ForEach-Object { $_.Count } | Measure-Object -Maximum).Maximum
+ if ($null -eq $maxCount -or $maxCount -lt 1) { $maxCount = 1 }
+
+ $chartWidth = 500
+ $barHeight = 30
+ $barSpacing = 15
+ $labelWidth = 80
+ $maxBarWidth = $chartWidth - $labelWidth - 50
+ $chartHeight = ($barHeight + $barSpacing) * $severityData.Count + 10
+
+ $chartHtml = "<div class='summary'><h2>Findings by Severity</h2>`n"
+ $chartHtml += "<svg width='$chartWidth' height='$chartHeight' xmlns='http://www.w3.org/2000/svg' role='img' aria-label='Findings by severity bar chart'>`n"
+
+ $barY = 5
+ foreach ($item in $severityData) {
+ $barWidth = [math]::Round(($item.Count / $maxCount) * $maxBarWidth)
+ if ($item.Count -gt 0 -and $barWidth -lt 2) { $barWidth = 2 }
+ if ($barWidth -lt 0) { $barWidth = 0 }
+
+ $chartHtml += "<text x='0' y='$($barY + 20)' font-size='13' fill='#333'>$($item.Label)</text>`n"
+ $chartHtml += "<rect x='$labelWidth' y='$barY' width='$barWidth' height='$barHeight' fill='$($item.Color)' rx='3' />`n"
+ $chartHtml += "<text x='$($labelWidth + $barWidth + 8)' y='$($barY + 20)' font-size='13' font-weight='bold' fill='#333'>$($item.Count)</text>`n"
+
+ $barY += $barHeight + $barSpacing
+ }
+
+ $chartHtml += "</svg></div>"
+ }
+
# Create HTML report
$htmlContent = @"
<!DOCTYPE html>
@@ -264,6 +303,8 @@ if ($highSeverityProcs.Count -gt 0) {
</table>
</div>
+ $chartHtml
+
<div class="summary">
<h2>Key Findings</h2>
$($reportData.Findings | ForEach-Object {
@@ -288,9 +329,9 @@ if ($highSeverityProcs.Count -gt 0) {
<h2>System Details</h2>
<table>
<tr><th>Component</th><th>Status</th></tr>
- <tr><td>Windows Defender</td><td>$($baseline.WindowsDefender.RealTimeProtectionEnabled)</td></tr>
- <tr><td>Firewall</td><td>$($baseline.Firewall[0].Enabled)</td></tr>
- <tr><td>UAC</td><td>$($baseline.UAC.EnableLUA -eq 1)</td></tr>
+ <tr><td>Windows Defender</td><td>$(if ($baseline.WindowsDefender -is [PSCustomObject]) { $baseline.WindowsDefender.RealTimeProtectionEnabled } else { $baseline.WindowsDefender })</td></tr>
+ <tr><td>Firewall</td><td>$(if ($baseline.Firewall -is [array] -and $baseline.Firewall.Count -gt 0) { $baseline.Firewall[0].Enabled } else { $baseline.Firewall })</td></tr>
+ <tr><td>UAC</td><td>$(if ($baseline.UAC -is [PSCustomObject]) { $baseline.UAC.EnableLUA -eq 1 } else { $baseline.UAC })</td></tr>
<tr><td>Persistence Mechanisms</td><td>$($persistence.TotalFindings) total ($($persistence.SuspiciousCount) suspicious)</td></tr>
<tr><td>Network Anomalies</td><td>$($network.TotalAnomalies)</td></tr>
<tr><td>Failed Logons</td><td>$($auth.Statistics.TotalFailedLogons)</td></tr>
diff --git a/Response/Invoke-ForensicCollection.ps1 b/Response/Invoke-ForensicCollection.ps1
index 273b7a9..0087dc2 100644
--- a/Response/Invoke-ForensicCollection.ps1
+++ b/Response/Invoke-ForensicCollection.ps1
@@ -132,9 +132,10 @@ function Invoke-ForensicCollection {
# Process modules
$procModules = Get-Process | ForEach-Object {
+ $proc = $_
try {
- $_.Modules | Select-Object @{N='ProcessName';E={$_.ProcessName}},
- @{N='ProcessId';E={$_.Id}},
+ $_.Modules | Select-Object @{N='ProcessName';E={$proc.ProcessName}},
+ @{N='ProcessId';E={$proc.Id}},
ModuleName, FileName, Size
} catch {}
}
@@ -389,13 +390,17 @@ Please use appropriate forensic tools for memory acquisition.
$timeline = @()
# Process start times
- Get-Process | Where-Object { $_.StartTime } | ForEach-Object {
- $timeline += [PSCustomObject]@{
- Timestamp = $_.StartTime
- Type = 'ProcessStart'
- Description = "$($_.ProcessName) (PID: $($_.Id))"
- Details = $_.Path
- }
+ Get-Process | ForEach-Object {
+ try {
+ if ($_.StartTime) {
+ $timeline += [PSCustomObject]@{
+ Timestamp = $_.StartTime
+ Type = 'ProcessStart'
+ Description = "$($_.ProcessName) (PID: $($_.Id))"
+ Details = $_.Path
+ }
+ }
+ } catch {}
}
# Recent file modifications
diff --git a/Response/Invoke-IncidentResponse.ps1 b/Response/Invoke-IncidentResponse.ps1
index 668a451..bd966ef 100644
--- a/Response/Invoke-IncidentResponse.ps1
+++ b/Response/Invoke-IncidentResponse.ps1
@@ -115,8 +115,8 @@ function Invoke-IncidentResponse {
$suspiciousProcs = Find-SuspiciousProcesses -CheckSignatures
if ($suspiciousProcs) {
$threats += $suspiciousProcs
- $results.Findings += "$($suspiciousProcs.Count) suspicious processes detected"
- Write-IRLog "$($suspiciousProcs.Count) suspicious processes found" 'WARNING'
+ $results.Findings += "$(@($suspiciousProcs).Count) suspicious processes detected"
+ Write-IRLog "$(@($suspiciousProcs).Count) suspicious processes found" 'WARNING'
}
}
catch {
diff --git a/ThreatHunting/Export-AttackNavigatorLayer.ps1 b/ThreatHunting/Export-AttackNavigatorLayer.ps1
new file mode 100644
index 0000000..8d11301
--- /dev/null
+++ b/ThreatHunting/Export-AttackNavigatorLayer.ps1
@@ -0,0 +1,551 @@
+function Export-AttackNavigatorLayer {
+ <#
+ .SYNOPSIS
+ Exports threat hunting findings as a MITRE ATT&CK Navigator layer
+ .DESCRIPTION
+ Converts findings from WindowsSecurityAudit threat hunting functions (such as
+ Get-MITREAttackMapping or Find-APTIndicators) into the MITRE ATT&CK Navigator
+ layer JSON format (v4.x) so SOC teams can visualize technique coverage at
+ https://mitre-attack.github.io/attack-navigator/.
+
+ Input can be supplied directly via the pipeline (-InputObject) or loaded from
+ a previously saved JSON file (-InputPath). Technique scores are derived from
+ finding severity and detection counts and rendered with a red-yellow gradient.
+ The generated file is validated to ensure it parses as JSON and contains all
+ keys required by ATT&CK Navigator.
+ .PARAMETER InputObject
+ Findings object(s), typically the output of Get-MITREAttackMapping,
+ Find-APTIndicators, or any object exposing TechniqueID properties.
+ Accepts pipeline input.
+ .PARAMETER InputPath
+ Path to a JSON file previously saved from a threat hunting function
+ (e.g. Get-MITREAttackMapping -FullAnalysis | ConvertTo-Json -Depth 10 | Set-Content findings.json)
+ .PARAMETER OutputPath
+ Path of the ATT&CK Navigator layer file to create. If an existing directory
+ is supplied, a timestamped .json file is created inside it.
+ .PARAMETER LayerName
+ Display name of the layer in ATT&CK Navigator.
+ Defaults to 'WindowsSecurityAudit Findings'.
+ .PARAMETER Score
+ Fixed score (0-100) applied to every technique. When omitted, each technique
+ is scored automatically from its highest severity and detection count.
+ .EXAMPLE
+ Get-MITREAttackMapping -FullAnalysis | Export-AttackNavigatorLayer -OutputPath C:\Reports\layer.json
+ .EXAMPLE
+ Export-AttackNavigatorLayer -InputPath C:\Reports\findings.json -OutputPath C:\Reports\layer.json -LayerName "Workstation Hunt"
+ .EXAMPLE
+ Find-APTIndicators -DeepScan | Export-AttackNavigatorLayer -OutputPath C:\Reports -Score 80
+ .OUTPUTS
+ PSCustomObject with export details (OutputPath, TechniqueCount, DetectionCount)
+ #>
+
+ [CmdletBinding()]
+ param(
+ [Parameter(ParameterSetName = 'Pipeline', Position = 0, ValueFromPipeline = $true)]
+ [AllowNull()]
+ [object[]]$InputObject,
+
+ [Parameter(ParameterSetName = 'File', Mandatory = $true)]
+ [ValidateNotNullOrEmpty()]
+ [string]$InputPath,
+
+ [Parameter(Mandatory = $true)]
+ [ValidateNotNullOrEmpty()]
+ [string]$OutputPath,
+
+ [Parameter()]
+ [ValidateNotNullOrEmpty()]
+ [string]$LayerName = 'WindowsSecurityAudit Findings',
+
+ [Parameter()]
+ [ValidateRange(0, 100)]
+ [int]$Score
+ )
+
+ begin {
+ Write-Host "=== ATT&CK NAVIGATOR LAYER EXPORT ===" -ForegroundColor Cyan
+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow
+ Write-Host "Input Mode: $($PSCmdlet.ParameterSetName)" -ForegroundColor Yellow
+
+ $useFixedScore = $PSBoundParameters.ContainsKey('Score')
+
+ # Severity weights used to score techniques on a 0-100 scale
+ $severityScores = @{
+ 'Critical' = 100
+ 'High' = 75
+ 'Medium' = 50
+ 'Low' = 25
+ }
+ $defaultSeverityScore = 10
+
+ # Map module tactic names to ATT&CK Navigator kebab-case tactic names
+ $tacticNameMap = @{
+ 'InitialAccess' = 'initial-access'
+ 'Execution' = 'execution'
+ 'Persistence' = 'persistence'
+ 'PrivilegeEscalation'= 'privilege-escalation'
+ 'DefenseEvasion' = 'defense-evasion'
+ 'CredentialAccess' = 'credential-access'
+ 'Discovery' = 'discovery'
+ 'LateralMovement' = 'lateral-movement'
+ 'Collection' = 'collection'
+ 'CommandAndControl' = 'command-and-control'
+ 'Exfiltration' = 'exfiltration'
+ 'Impact' = 'impact'
+ }
+
+ # Red-yellow gradient endpoint interpolation (yellow #FFE766 -> red #FF6666)
+ $getGradientColor = {
+ param([int]$Value)
+ $clamped = [Math]::Min(100, [Math]::Max(0, $Value))
+ $ratio = $clamped / 100.0
+ $red = 255
+ $green = [int](231 + ((102 - 231) * $ratio))
+ $blue = [int](102 + ((102 - 102) * $ratio))
+ return ('#{0:X2}{1:X2}{2:X2}' -f $red, $green, $blue)
+ }
+
+ $detectionRecords = [System.Collections.ArrayList]@()
+
+ function New-TechniqueRecord {
+ param(
+ [string]$Id,
+ [string]$Name,
+ [string]$Tactic,
+ [string]$Severity,
+ [string]$Evidence,
+ [string]$Source
+ )
+ return [PSCustomObject]@{
+ TechniqueID = $Id
+ TechniqueName = $Name
+ Tactic = $Tactic
+ Severity = $Severity
+ Evidence = $Evidence
+ DetectionSource = $Source
+ }
+ }
+
+ function Get-TechniqueRecord {
+ param([AllowNull()][object]$Item)
+
+ $records = @()
+
+ if ($null -eq $Item) {
+ return $records
+ }
+
+ # Plain strings: scan for ATT&CK technique ID references
+ if ($Item -is [string]) {
+ foreach ($match in [regex]::Matches($Item, 'T\d{4}(\.\d{3})?')) {
+ $records += New-TechniqueRecord -Id $match.Value -Name '' -Tactic '' -Severity '' -Evidence 'Text reference' -Source 'Raw'
+ }
+ return $records
+ }
+
+ # Hashtable / dictionary containers
+ if ($Item -is [System.Collections.IDictionary]) {
+ if ($Item.Contains('DetectedTechniques') -and $null -ne $Item['DetectedTechniques']) {
+ foreach ($subItem in @($Item['DetectedTechniques'])) {
+ $records += @(Get-TechniqueRecord -Item $subItem)
+ }
+ return $records
+ }
+ if ($Item.Contains('TechniqueID') -and $null -ne $Item['TechniqueID']) {
+ $dictId = [string]$Item['TechniqueID']
+ if ($dictId -match '^T\d{4}(\.\d{3})?$') {
+ $records += New-TechniqueRecord -Id $dictId `
+ -Name $(if ($Item.Contains('TechniqueName')) { [string]$Item['TechniqueName'] } else { '' }) `
+ -Tactic $(if ($Item.Contains('Tactic')) { [string]$Item['Tactic'] } else { '' }) `
+ -Severity $(if ($Item.Contains('Severity')) { [string]$Item['Severity'] } else { '' }) `
+ -Evidence $(if ($Item.Contains('Evidence')) { [string]$Item['Evidence'] } else { '' }) `
+ -Source $(if ($Item.Contains('DetectionSource')) { [string]$Item['DetectionSource'] } else { '' })
+ }
+ return $records
+ }
+ # Fallback: scan string values for technique ID references
+ foreach ($key in @($Item.Keys)) {
+ if ($Item[$key] -is [string]) {
+ foreach ($match in [regex]::Matches($Item[$key], 'T\d{4}(\.\d{3})?')) {
+ $records += New-TechniqueRecord -Id $match.Value -Name '' -Tactic '' -Severity '' -Evidence "$key reference" -Source 'Raw'
+ }
+ }
+ }
+ return $records
+ }
+
+ $props = $Item.PSObject.Properties
+
+ # Get-MITREAttackMapping style container: recurse into DetectedTechniques
+ if ($null -ne $props['DetectedTechniques'] -and $null -ne $Item.DetectedTechniques) {
+ foreach ($subItem in @($Item.DetectedTechniques)) {
+ $records += @(Get-TechniqueRecord -Item $subItem)
+ }
+ return $records
+ }
+
+ # Find-APTIndicators style container: recurse into Indicators members
+ if ($null -ne $props['Indicators'] -and $null -ne $Item.Indicators) {
+ $indicatorContainer = $Item.Indicators
+ if ($indicatorContainer -is [System.Collections.IDictionary]) {
+ foreach ($key in @($indicatorContainer.Keys)) {
+ foreach ($subItem in @($indicatorContainer[$key])) {
+ $records += @(Get-TechniqueRecord -Item $subItem)
+ }
+ }
+ }
+ else {
+ foreach ($containerProp in @($indicatorContainer.PSObject.Properties)) {
+ foreach ($subItem in @($containerProp.Value)) {
+ $records += @(Get-TechniqueRecord -Item $subItem)
+ }
+ }
+ }
+ return $records
+ }
+
+ # Detection object exposing a TechniqueID property
+ if ($null -ne $props['TechniqueID'] -and $null -ne $Item.TechniqueID) {
+ $id = [string]$Item.TechniqueID
+ if ($id -match '^T\d{4}(\.\d{3})?$') {
+ $records += New-TechniqueRecord -Id $id `
+ -Name $(if ($null -ne $props['TechniqueName']) { [string]$Item.TechniqueName } else { '' }) `
+ -Tactic $(if ($null -ne $props['Tactic']) { [string]$Item.Tactic } else { '' }) `
+ -Severity $(if ($null -ne $props['Severity']) { [string]$Item.Severity } else { '' }) `
+ -Evidence $(if ($null -ne $props['Evidence']) { [string]$Item.Evidence } else { '' }) `
+ -Source $(if ($null -ne $props['DetectionSource']) { [string]$Item.DetectionSource } else { '' })
+ }
+ return $records
+ }
+
+ # Fallback: scan string properties for technique ID references
+ $itemSeverity = ''
+ if ($null -ne $props['Severity'] -and $null -ne $Item.Severity) {
+ $itemSeverity = [string]$Item.Severity
+ }
+ foreach ($prop in $props) {
+ if ($prop.Value -is [string]) {
+ foreach ($match in [regex]::Matches($prop.Value, 'T\d{4}(\.\d{3})?')) {
+ $records += New-TechniqueRecord -Id $match.Value -Name '' -Tactic '' -Severity $itemSeverity -Evidence "$($prop.Name) reference" -Source 'Raw'
+ }
+ }
+ }
+ return $records
+ }
+
+ # Load findings from a previously saved JSON file
+ if ($PSCmdlet.ParameterSetName -eq 'File') {
+ if (-not (Test-Path -LiteralPath $InputPath -PathType Leaf)) {
+ Write-Error "Input file not found: $InputPath"
+ throw "Input file not found: $InputPath"
+ }
+ try {
+ $rawJson = Get-Content -LiteralPath $InputPath -Raw -ErrorAction Stop
+ $loadedFindings = $rawJson | ConvertFrom-Json -ErrorAction Stop
+ foreach ($loadedItem in @($loadedFindings)) {
+ foreach ($record in @(Get-TechniqueRecord -Item $loadedItem)) {
+ [void]$detectionRecords.Add($record)
+ }
+ }
+ Write-Host "Loaded findings from: $InputPath" -ForegroundColor Yellow
+ }
+ catch {
+ Write-Error "Failed to read or parse input file '$InputPath': $_"
+ throw
+ }
+ }
+ }
+
+ process {
+ if ($null -ne $InputObject) {
+ foreach ($item in $InputObject) {
+ if ($null -eq $item) {
+ continue
+ }
+ try {
+ foreach ($record in @(Get-TechniqueRecord -Item $item)) {
+ [void]$detectionRecords.Add($record)
+ }
+ }
+ catch {
+ Write-Warning "Error extracting technique data from input item: $_"
+ }
+ }
+ }
+ }
+
+ end {
+ try {
+ Write-Host "`nBuilding ATT&CK Navigator layer..." -ForegroundColor Cyan
+
+ # Aggregate detections per technique ID
+ $techniqueMap = [ordered]@{}
+ foreach ($record in $detectionRecords) {
+ if ($null -eq $record) {
+ continue
+ }
+ $id = $record.TechniqueID
+ if ([string]::IsNullOrWhiteSpace($id)) {
+ continue
+ }
+
+ if (-not $techniqueMap.Contains($id)) {
+ $techniqueMap[$id] = @{
+ Detections = 0
+ BestSeverity = ''
+ BestSeverityScore = 0
+ Names = @()
+ Tactic = ''
+ Sources = @()
+ Evidences = @()
+ }
+ }
+ $entry = $techniqueMap[$id]
+ $entry.Detections++
+
+ if ($severityScores.ContainsKey($record.Severity)) {
+ $recordSeverityScore = $severityScores[$record.Severity]
+ }
+ else {
+ $recordSeverityScore = $defaultSeverityScore
+ }
+ if ($recordSeverityScore -gt $entry.BestSeverityScore) {
+ $entry.BestSeverityScore = $recordSeverityScore
+ $entry.BestSeverity = $record.Severity
+ }
+
+ if (-not [string]::IsNullOrWhiteSpace($record.TechniqueName) -and
+ $entry.Names -notcontains $record.TechniqueName -and
+ $entry.Names.Count -lt 3) {
+ $entry.Names += $record.TechniqueName
+ }
+
+ if (-not [string]::IsNullOrWhiteSpace($record.Tactic) -and
+ [string]::IsNullOrWhiteSpace($entry.Tactic)) {
+ $entry.Tactic = $record.Tactic
+ }
+
+ if (-not [string]::IsNullOrWhiteSpace($record.DetectionSource) -and
+ $entry.Sources -notcontains $record.DetectionSource) {
+ $entry.Sources += $record.DetectionSource
+ }
+
+ if (-not [string]::IsNullOrWhiteSpace($record.Evidence) -and
+ $entry.Evidences -notcontains $record.Evidence -and
+ $entry.Evidences.Count -lt 3) {
+ $evidence = $record.Evidence
+ if ($evidence.Length -gt 120) {
+ $evidence = $evidence.Substring(0, 117) + '...'
+ }
+ $entry.Evidences += $evidence
+ }
+ }
+
+ # Build technique entries with severity-based gradient scores
+ $techniques = @()
+ $severitiesSeen = @{}
+
+ foreach ($id in @($techniqueMap.Keys)) {
+ $entry = $techniqueMap[$id]
+
+ if ($useFixedScore) {
+ $scoreValue = $Score
+ }
+ else {
+ $scoreValue = [Math]::Min(100, $entry.BestSeverityScore + (($entry.Detections - 1) * 5))
+ }
+
+ $commentParts = @("Detections: $($entry.Detections)")
+ if (-not [string]::IsNullOrWhiteSpace($entry.BestSeverity)) {
+ $commentParts += "Highest severity: $($entry.BestSeverity)"
+ }
+ if ($entry.Names.Count -gt 0) {
+ $commentParts += ($entry.Names -join ' / ')
+ }
+ if (-not [string]::IsNullOrWhiteSpace($entry.Tactic)) {
+ $commentParts += "Tactic: $($entry.Tactic)"
+ }
+ if ($entry.Sources.Count -gt 0) {
+ $commentParts += "Sources: $($entry.Sources -join ', ')"
+ }
+ if ($entry.Evidences.Count -gt 0) {
+ $commentParts += "Evidence: $($entry.Evidences -join '; ')"
+ }
+ $comment = $commentParts -join ' | '
+ if ($comment.Length -gt 500) {
+ $comment = $comment.Substring(0, 497) + '...'
+ }
+
+ $techniqueEntry = [ordered]@{
+ techniqueID = $id
+ score = $scoreValue
+ color = (& $getGradientColor $scoreValue)
+ comment = $comment
+ enabled = $true
+ links = @()
+ metadata = @()
+ }
+ if (-not [string]::IsNullOrWhiteSpace($entry.Tactic) -and $tacticNameMap.ContainsKey($entry.Tactic)) {
+ $techniqueEntry['tactic'] = $tacticNameMap[$entry.Tactic]
+ }
+ $techniques += $techniqueEntry
+
+ if (-not [string]::IsNullOrWhiteSpace($entry.BestSeverity)) {
+ $severitiesSeen[$entry.BestSeverity] = $true
+ }
+ }
+
+ # Sort techniques by score (descending), then technique ID
+ $techniques = @($techniques | Sort-Object -Property @{ Expression = 'score'; Descending = $true }, @{ Expression = 'techniqueID'; Descending = $false })
+
+ if ($techniques.Count -eq 0) {
+ Write-Warning "No ATT&CK technique IDs found in the input. An empty layer will be exported."
+ }
+
+ # Legend items for observed severities
+ $severityLegendColors = @{
+ 'Critical' = '#FF6666'
+ 'High' = '#FFB366'
+ 'Medium' = '#FFE766'
+ 'Low' = '#FFFFB3'
+ }
+ $legendItems = @()
+ foreach ($severityName in @('Critical', 'High', 'Medium', 'Low')) {
+ if ($severitiesSeen.ContainsKey($severityName)) {
+ $legendItems += [ordered]@{
+ label = "$severityName severity detections"
+ color = $severityLegendColors[$severityName]
+ }
+ }
+ }
+ if ($useFixedScore) {
+ $legendItems += [ordered]@{ label = "Fixed score applied: $Score"; color = '' }
+ }
+ else {
+ $legendItems += [ordered]@{ label = 'Score = severity weight + detection count'; color = '' }
+ }
+
+ # ATT&CK Navigator layer format v4.x
+ $layer = [ordered]@{
+ name = $LayerName
+ versions = [ordered]@{
+ attack = '16'
+ navigator = '5.1.0'
+ layer = '4.5'
+ }
+ domain = 'enterprise-attack'
+ description = "Generated by the WindowsSecurityAudit module on $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss'). $($detectionRecords.Count) detection(s) across $($techniqueMap.Count) unique technique(s)."
+ filters = [ordered]@{
+ platforms = @('Windows')
+ }
+ sorting = 3
+ layout = [ordered]@{
+ layout = 'side'
+ aggregateFunction = 'average'
+ showID = $false
+ showName = $true
+ showAggregateScores = $false
+ countUnscored = $false
+ }
+ hideDisabled = $false
+ techniques = $techniques
+ gradient = [ordered]@{
+ colors = @('#FFE766', '#FF6666')
+ minValue = 0
+ maxValue = 100
+ }
+ legendItems = $legendItems
+ metadata = @(
+ [ordered]@{ name = 'Generated by'; value = 'WindowsSecurityAudit module' }
+ [ordered]@{ name = 'Total detections'; value = "$($detectionRecords.Count)" }
+ [ordered]@{ name = 'Unique techniques'; value = "$($techniqueMap.Count)" }
+ )
+ links = @()
+ showTacticRowBackground = $false
+ tacticRowBackground = '#DDDDDD'
+ selectTechniquesAcrossTactics = $true
+ selectSubtechniquesWithParent = $false
+ }
+
+ # Resolve output path (accept a directory or a file path)
+ $resolvedOutput = $OutputPath
+ if (Test-Path -LiteralPath $resolvedOutput -PathType Container) {
+ $resolvedOutput = Join-Path -Path $resolvedOutput -ChildPath ("AttackNavigatorLayer_{0}.json" -f (Get-Date -Format 'yyyyMMdd_HHmmss'))
+ }
+ if ([System.IO.Path]::GetExtension($resolvedOutput) -ne '.json') {
+ $resolvedOutput += '.json'
+ }
+ if ([System.IO.Path]::IsPathRooted($resolvedOutput)) {
+ $fullPath = $resolvedOutput
+ }
+ else {
+ $fullPath = Join-Path -Path (Get-Location).Path -ChildPath $resolvedOutput
+ }
+
+ $parentDir = Split-Path -Path $fullPath -Parent
+ if (-not [string]::IsNullOrWhiteSpace($parentDir) -and -not (Test-Path -LiteralPath $parentDir)) {
+ New-Item -Path $parentDir -ItemType Directory -Force | Out-Null
+ }
+
+ # Write layer JSON (UTF-8 without BOM for ATT&CK Navigator compatibility)
+ $layerJson = $layer | ConvertTo-Json -Depth 10
+ [System.IO.File]::WriteAllText($fullPath, $layerJson)
+
+ # Validate the exported layer parses as JSON and contains required keys
+ Write-Host "Validating exported layer..." -ForegroundColor Cyan
+ try {
+ $savedJson = [System.IO.File]::ReadAllText($fullPath)
+ $parsedLayer = $savedJson | ConvertFrom-Json -ErrorAction Stop
+
+ $requiredKeys = @('name', 'versions', 'domain', 'techniques', 'gradient', 'legendItems')
+ foreach ($key in $requiredKeys) {
+ if ($null -eq $parsedLayer.PSObject.Properties[$key]) {
+ throw "Missing required layer key: $key"
+ }
+ }
+ foreach ($versionKey in @('attack', 'navigator', 'layer')) {
+ if ($null -eq $parsedLayer.versions.PSObject.Properties[$versionKey]) {
+ throw "Missing required versions key: $versionKey"
+ }
+ }
+ if ($parsedLayer.domain -ne 'enterprise-attack') {
+ throw "Unexpected domain value: $($parsedLayer.domain)"
+ }
+ Write-Host "Layer validated: JSON parses and contains all required keys" -ForegroundColor Green
+ }
+ catch {
+ Write-Error "Generated layer file failed validation: $_"
+ throw
+ }
+
+ Write-Host "`n=== EXPORT COMPLETE ===" -ForegroundColor Green
+ Write-Host "`nLayer Summary:" -ForegroundColor Cyan
+ Write-Host " Layer Name: $LayerName" -ForegroundColor White
+ Write-Host " Unique Techniques: $($techniqueMap.Count)" -ForegroundColor White
+ Write-Host " Total Detections: $($detectionRecords.Count)" -ForegroundColor White
+ Write-Host " Output File: $fullPath" -ForegroundColor White
+
+ if ($techniques.Count -gt 0) {
+ Write-Host "`nTop Scored Techniques:" -ForegroundColor Cyan
+ $techniques | Select-Object -First 5 | ForEach-Object {
+ Write-Host " $($_.techniqueID) [Score: $($_.score)]" -ForegroundColor Yellow
+ }
+ }
+
+ Write-Host "`nImport the layer into ATT&CK Navigator:" -ForegroundColor Cyan
+ Write-Host " https://mitre-attack.github.io/attack-navigator/" -ForegroundColor Gray
+
+ return [PSCustomObject]@{
+ LayerName = $LayerName
+ OutputPath = $fullPath
+ TechniqueCount = $techniqueMap.Count
+ DetectionCount = $detectionRecords.Count
+ NavigatorUrl = 'https://mitre-attack.github.io/attack-navigator/'
+ }
+ }
+ catch {
+ Write-Error "Error exporting ATT&CK Navigator layer: $_"
+ throw
+ }
+ }
+}
diff --git a/ThreatHunting/Find-APTIndicators.ps1 b/ThreatHunting/Find-APTIndicators.ps1
index 2ba4b2b..1bf7b48 100644
--- a/ThreatHunting/Find-APTIndicators.ps1
+++ b/ThreatHunting/Find-APTIndicators.ps1
@@ -118,7 +118,7 @@ function Find-APTIndicators {
# Suspicious locations - using single quotes for $Recycle to avoid variable expansion
$suspiciousLocations = @(
"$env:TEMP",
- "$env:APPDATA\Local\Temp",
+ "$env:LOCALAPPDATA\Temp",
"C:\Users\Public",
"C:\Windows\Temp",
"C:\Temp",
@@ -311,7 +311,7 @@ function Find-APTIndicators {
TaskPath = $task.TaskPath
State = $task.State
Actions = ($actionDetails -join '; ')
- RunAs = $task.Principal.UserId
+ RunAs = if ($task.Principal) { $task.Principal.UserId } else { $null }
SuspiciousScore = $suspiciousScore
Reasons = $reasons -join '; '
}
@@ -353,6 +353,10 @@ function Find-APTIndicators {
if (Test-Path $keyPath) {
$values = Get-ItemProperty -Path $keyPath -ErrorAction SilentlyContinue
+ if (-not $values) {
+ continue
+ }
+
foreach ($property in $values.PSObject.Properties) {
# Skip PowerShell default properties
if ($property.Name -match "^PS") {
diff --git a/ThreatHunting/Find-DataExfiltration.ps1 b/ThreatHunting/Find-DataExfiltration.ps1
index e196d90..ba1d947 100644
--- a/ThreatHunting/Find-DataExfiltration.ps1
+++ b/ThreatHunting/Find-DataExfiltration.ps1
@@ -96,45 +96,35 @@ function Find-DataExfiltration {
Write-Host "`n[1/4] Checking network transfers..." -ForegroundColor Cyan
try {
- # Get network interface statistics
- $networkStats = Get-NetAdapterStatistics -ErrorAction SilentlyContinue
+ # Check active connections with high data transfer
+ $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue |
+ Where-Object { $_.RemoteAddress -notmatch '^(127\.|::1|0\.0\.0\.0)' }
- if ($networkStats) {
- foreach ($adapter in $networkStats) {
- $sentGB = [math]::Round($adapter.SentBytes / 1GB, 2)
- $receivedGB = [math]::Round($adapter.ReceivedBytes / 1GB, 2)
-
- # Check active connections with high data transfer
- $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue |
- Where-Object { $_.RemoteAddress -notmatch '^(127\.|::1|0\.0\.0\.0)' }
+ foreach ($conn in $connections | Select-Object -First 10) {
+ $process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue
+
+ if ($process) {
+ # Skip browsers and common legitimate processes
+ if ($process.Name -match 'chrome|firefox|edge|teams|zoom|onedrive') {
+ continue
+ }
- foreach ($conn in $connections | Select-Object -First 10) {
- $process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue
-
- if ($process) {
- # Skip browsers and common legitimate processes
- if ($process.Name -match 'chrome|firefox|edge|teams|zoom|onedrive') {
- continue
- }
-
- $indicator = [PSCustomObject]@{
- Type = 'NetworkTransfer'
- Process = $process.Name
- ProcessId = $conn.OwningProcess
- RemoteAddress = $conn.RemoteAddress
- RemotePort = $conn.RemotePort
- LocalPort = $conn.LocalPort
- Severity = 'Medium'
- Description = "Active connection from $($process.Name) to $($conn.RemoteAddress)"
- Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
- }
-
- $results.Indicators.LargeTransfers += $indicator
- $results.Summary.MediumFindings++
-
- Write-Host " [!] Active: $($process.Name) -> $($conn.RemoteAddress):$($conn.RemotePort)" -ForegroundColor Yellow
- }
+ $indicator = [PSCustomObject]@{
+ Type = 'NetworkTransfer'
+ Process = $process.Name
+ ProcessId = $conn.OwningProcess
+ RemoteAddress = $conn.RemoteAddress
+ RemotePort = $conn.RemotePort
+ LocalPort = $conn.LocalPort
+ Severity = 'Medium'
+ Description = "Active connection from $($process.Name) to $($conn.RemoteAddress)"
+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
}
+
+ $results.Indicators.LargeTransfers += $indicator
+ $results.Summary.MediumFindings++
+
+ Write-Host " [!] Active: $($process.Name) -> $($conn.RemoteAddress):$($conn.RemotePort)" -ForegroundColor Yellow
}
}
@@ -170,6 +160,10 @@ function Find-DataExfiltration {
if ($hostname -like "*$cloudService*") {
$process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue
+ if (-not $process) {
+ break
+ }
+
# Skip if it's a browser (expected behavior)
if ($process.Name -match 'chrome|firefox|edge|msedge') {
continue
diff --git a/ThreatHunting/Find-LateralMovement.ps1 b/ThreatHunting/Find-LateralMovement.ps1
index 44e5589..ec1fd15 100644
--- a/ThreatHunting/Find-LateralMovement.ps1
+++ b/ThreatHunting/Find-LateralMovement.ps1
@@ -98,6 +98,10 @@ function Find-LateralMovement {
if ($conn.RemotePort -in $suspiciousPorts.Keys) {
$process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue
+ if (-not $process) {
+ continue
+ }
+
# Skip if it's a standard system process in expected scenarios
if ($process.Name -in @('svchost', 'System')) {
continue
@@ -152,7 +156,7 @@ function Find-LateralMovement {
if ($remoteEvents) {
$groupedEvents = $remoteEvents | Group-Object -Property {
- $_.Properties[5].Value
+ $_.Properties[7].Value
} | Sort-Object Count -Descending
foreach ($group in $groupedEvents | Select-Object -First 5) {
@@ -162,11 +166,11 @@ function Find-LateralMovement {
Type = 'RemoteExecution'
Process = 'N/A'
ProcessId = 'N/A'
- TargetServer = $event.Properties[5].Value
+ TargetServer = $event.Properties[7].Value
Account = $event.Properties[1].Value
Count = $group.Count
Severity = if ($group.Count -gt 10) { 'High' } else { 'Medium' }
- Description = "Explicit credential logon to $($event.Properties[5].Value) - $($group.Count) times"
+ Description = "Explicit credential logon to $($event.Properties[7].Value) - $($group.Count) times"
Timestamp = $event.TimeCreated.ToString("yyyy-MM-dd HH:mm:ss")
}
@@ -178,7 +182,7 @@ function Find-LateralMovement {
$results.Summary.MediumFindings++
}
- Write-Host " [!] Explicit credential logon: $($event.Properties[5].Value) ($($group.Count) times)" -ForegroundColor Yellow
+ Write-Host " [!] Explicit credential logon: $($event.Properties[7].Value) ($($group.Count) times)" -ForegroundColor Yellow
}
}
else {
@@ -277,13 +281,13 @@ function Find-LateralMovement {
if ($shareEvents) {
# Filter for non-admin shares
$suspiciousShares = $shareEvents | Where-Object {
- $shareName = $_.Properties[3].Value
+ $shareName = $_.Properties[7].Value
$shareName -notmatch 'IPC\$|ADMIN\$|C\$'
}
if ($suspiciousShares) {
$groupedShares = $suspiciousShares | Group-Object -Property {
- "$($_.Properties[1].Value)|$($_.Properties[3].Value)"
+ "$($_.Properties[1].Value)|$($_.Properties[7].Value)"
} | Sort-Object Count -Descending
foreach ($group in $groupedShares | Select-Object -First 5) {
diff --git a/ThreatHunting/Find-LivingOffLand.ps1 b/ThreatHunting/Find-LivingOffLand.ps1
index c4b31ec..7d250ca 100644
--- a/ThreatHunting/Find-LivingOffLand.ps1
+++ b/ThreatHunting/Find-LivingOffLand.ps1
@@ -198,7 +198,7 @@ function Find-LivingOffLand {
try {
$processes = Get-CimInstance Win32_Process |
- Where-Object { $_.CommandLine -ne $null } |
+ Where-Object { $null -ne $_.CommandLine } |
Select-Object Name, ProcessId, ExecutablePath, CommandLine
foreach ($process in $processes) {
diff --git a/ThreatHunting/Get-MITREAttackMapping.ps1 b/ThreatHunting/Get-MITREAttackMapping.ps1
index 5fc04f0..d6660a9 100644
--- a/ThreatHunting/Get-MITREAttackMapping.ps1
+++ b/ThreatHunting/Get-MITREAttackMapping.ps1
@@ -416,11 +416,12 @@ function Get-MITREAttackMapping {
if ($conn.RemotePort -in $nonStandardPorts) {
$process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue
+ $processName = if ($process) { $process.Name } else { "PID $($conn.OwningProcess)" }
# Skip if it's a known legitimate process
$isLegitimate = $false
foreach ($legitProc in $legitimateProcesses) {
- if ($process.Name -like "*$legitProc*") {
+ if ($processName -like "*$legitProc*") {
$isLegitimate = $true
break
}
@@ -433,7 +434,7 @@ function Get-MITREAttackMapping {
Tactic = 'CommandAndControl'
Severity = 'High'
DetectionSource = 'Network'
- Evidence = "Non-standard port $($conn.RemotePort) used by $($process.Name) -> $($conn.RemoteAddress)"
+ Evidence = "Non-standard port $($conn.RemotePort) used by $processName -> $($conn.RemoteAddress)"
CommandLine = "N/A"
Description = $mitreDB['T1571'].Description
Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
diff --git a/ThreatHunting/Get-ThreatIntelligence.ps1 b/ThreatHunting/Get-ThreatIntelligence.ps1
index d67e2ab..b099bf9 100644
--- a/ThreatHunting/Get-ThreatIntelligence.ps1
+++ b/ThreatHunting/Get-ThreatIntelligence.ps1
@@ -114,6 +114,24 @@ function Get-ThreatIntelligence {
Write-Host "Loading custom IOCs from: $IOCFile" -ForegroundColor Yellow
try {
$customIOCs = Get-Content $IOCFile -Raw | ConvertFrom-Json
+ foreach ($section in 'MaliciousProcesses', 'MaliciousIPs', 'MaliciousHashes') {
+ if ($customIOCs.PSObject.Properties[$section]) {
+ foreach ($entry in $customIOCs.$section.PSObject.Properties) {
+ $key = if ($section -eq 'MaliciousProcesses') { $entry.Name.ToLower() } else { $entry.Name }
+ $iocDatabase[$section][$key] = @{
+ Severity = if ($entry.Value.PSObject.Properties['Severity']) { $entry.Value.Severity } else { 'Medium' }
+ Description = if ($entry.Value.PSObject.Properties['Description']) { $entry.Value.Description } else { 'Custom IOC' }
+ }
+ }
+ }
+ }
+ if ($customIOCs.PSObject.Properties['SuspiciousPatterns']) {
+ foreach ($patternGroup in 'ProcessCommandLine', 'FilePaths') {
+ if ($customIOCs.SuspiciousPatterns.PSObject.Properties[$patternGroup]) {
+ $iocDatabase.SuspiciousPatterns[$patternGroup] += @($customIOCs.SuspiciousPatterns.$patternGroup)
+ }
+ }
+ }
Write-Host "Custom IOCs loaded successfully" -ForegroundColor Green
}
catch {
@@ -130,7 +148,7 @@ function Get-ThreatIntelligence {
try {
$processes = Get-CimInstance Win32_Process |
- Where-Object { $_.CommandLine -ne $null } |
+ Where-Object { $null -ne $_.CommandLine } |
Select-Object Name, ProcessId, ExecutablePath, CommandLine
$foundCount = 0
@@ -220,16 +238,19 @@ function Get-ThreatIntelligence {
$foundCount = 0
foreach ($conn in $connections) {
+ $remoteAddress = $conn.RemoteAddress.ToString()
+
# Check against malicious IPs
- if ($iocDatabase.MaliciousIPs.ContainsKey($conn.RemoteAddress)) {
- $ioc = $iocDatabase.MaliciousIPs[$conn.RemoteAddress]
+ if ($iocDatabase.MaliciousIPs.ContainsKey($remoteAddress)) {
+ $ioc = $iocDatabase.MaliciousIPs[$remoteAddress]
$process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue
+ $processName = if ($process) { $process.Name } else { "PID $($conn.OwningProcess)" }
$match = [PSCustomObject]@{
Type = 'Network'
IOCType = 'MaliciousIP'
Indicator = $conn.RemoteAddress
- ProcessName = $process.Name
+ ProcessName = $processName
ProcessId = $conn.OwningProcess
LocalAddress = "$($conn.LocalAddress):$($conn.LocalPort)"
RemoteAddress = "$($conn.RemoteAddress):$($conn.RemotePort)"
@@ -247,7 +268,7 @@ function Get-ThreatIntelligence {
'Medium' { $results.Summary.MediumMatches++ }
}
- Write-Host " [!] MATCH: Malicious IP $($conn.RemoteAddress) via $($process.Name)" -ForegroundColor Red
+ Write-Host " [!] MATCH: Malicious IP $($conn.RemoteAddress) via $processName" -ForegroundColor Red
}
}
diff --git a/Vulnerability/Find-EOLSoftware.ps1 b/Vulnerability/Find-EOLSoftware.ps1
index 108c713..1e947cd 100644
--- a/Vulnerability/Find-EOLSoftware.ps1
+++ b/Vulnerability/Find-EOLSoftware.ps1
@@ -233,7 +233,7 @@ function Find-EOLSoftware {
}
}
- $installedSoftware = $installedSoftware | Sort-Object DisplayName -Unique
+ $installedSoftware = @($installedSoftware | Sort-Object DisplayName -Unique)
$findings.TotalSoftware = $installedSoftware.Count
Write-Host " Found $($installedSoftware.Count) installed applications" -ForegroundColor Gray
diff --git a/Vulnerability/Get-ExposedServices.ps1 b/Vulnerability/Get-ExposedServices.ps1
index b70ff4c..42d9de8 100644
--- a/Vulnerability/Get-ExposedServices.ps1
+++ b/Vulnerability/Get-ExposedServices.ps1
@@ -46,6 +46,7 @@ function Get-ExposedServices {
Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow
Write-Host "Scan Mode: $(if($IncludeAllPorts){'Full Port Scan'}else{'High-Risk Ports Only'})" -ForegroundColor Yellow
Write-Host "Check Firewall: $(if($CheckFirewall){'Yes'}else{'No'})" -ForegroundColor Yellow
+ Write-Host "Custom Ports: $(if($CustomPorts){$CustomPorts -join ', '}else{'None'})" -ForegroundColor Yellow
$findings = [PSCustomObject]@{
ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
@@ -88,6 +89,15 @@ function Get-ExposedServices {
8080 = @{Service='HTTP-Alt'; Risk='Medium'; Description='Alternative web server'}
8443 = @{Service='HTTPS-Alt'; Risk='Low'; Description='Alternative secure web'}
}
+
+ # Merge user-specified custom ports into the assessed port database
+ if ($CustomPorts) {
+ foreach ($customPort in $CustomPorts) {
+ if (-not $highRiskPorts.ContainsKey($customPort)) {
+ $highRiskPorts[$customPort] = @{Service='Custom'; Risk='Medium'; Description='User-specified custom port'}
+ }
+ }
+ }
}
process {
diff --git a/Vulnerability/Get-SecurityMisconfigurations.ps1 b/Vulnerability/Get-SecurityMisconfigurations.ps1
index a852951..cef8b3f 100644
--- a/Vulnerability/Get-SecurityMisconfigurations.ps1
+++ b/Vulnerability/Get-SecurityMisconfigurations.ps1
@@ -205,7 +205,7 @@ function Get-SecurityMisconfigurations {
try {
$publicProfile = Get-NetConnectionProfile | Where-Object { $_.NetworkCategory -eq 'Public' }
if (-not $publicProfile) {
- $privateCount = (Get-NetConnectionProfile | Where-Object { $_.NetworkCategory -eq 'Private' }).Count
+ $privateCount = @(Get-NetConnectionProfile | Where-Object { $_.NetworkCategory -eq 'Private' }).Count
if ($privateCount -gt 0) {
$findings.Misconfigurations += [PSCustomObject]@{
Category = 'Network'
@@ -228,7 +228,7 @@ function Get-SecurityMisconfigurations {
# Check for SMBv1
try {
$smbv1 = Get-WindowsOptionalFeature -Online -FeatureName SMB1Protocol -ErrorAction SilentlyContinue
- if ($smbv1.State -eq 'Enabled') {
+ if ($smbv1 -and $smbv1.State -eq 'Enabled') {
$findings.Misconfigurations += [PSCustomObject]@{
Category = 'Network'
Finding = 'SMBv1 Protocol Enabled'
diff --git a/Vulnerability/Get-VulnerabilityAssessment.ps1 b/Vulnerability/Get-VulnerabilityAssessment.ps1
index c105228..daae96d 100644
--- a/Vulnerability/Get-VulnerabilityAssessment.ps1
+++ b/Vulnerability/Get-VulnerabilityAssessment.ps1
@@ -159,12 +159,12 @@ function Get-VulnerabilityAssessment {
}
# Remove duplicates
- $installedSoftware = $installedSoftware |
+ $installedSoftware = @($installedSoftware |
Sort-Object DisplayName -Unique |
Where-Object {
$_.DisplayName -notlike "KB*" -and
$_.DisplayName -notlike "Update for*"
- }
+ })
$assessment.Summary.TotalApplications = $installedSoftware.Count
Write-Host " Found $($installedSoftware.Count) installed applications" -ForegroundColor Gray
diff --git a/WindowsDefender/Get-DefenderStatus.ps1 b/WindowsDefender/Get-DefenderStatus.ps1
index 1687537..25bacb6 100644
--- a/WindowsDefender/Get-DefenderStatus.ps1
+++ b/WindowsDefender/Get-DefenderStatus.ps1
@@ -69,7 +69,7 @@ function Get-DefenderStatus {
AntivirusSignatureLastUpdated = $mpStatus.AntivirusSignatureLastUpdated
AntispywareSignatureLastUpdated = $mpStatus.AntispywareSignatureLastUpdated
NISSignatureLastUpdated = $mpStatus.NISSignatureLastUpdated
- SignatureAge = (Get-Date) - $mpStatus.AntivirusSignatureLastUpdated
+ SignatureAge = if ($mpStatus.AntivirusSignatureLastUpdated) { (Get-Date) - $mpStatus.AntivirusSignatureLastUpdated } else { $null }
}
# Scan History
@@ -146,8 +146,10 @@ function Get-DefenderStatus {
if ($status.ProtectionStatus.NISEnabled) { $healthScore += 15 } else { $status.Recommendations += "Enable Network Inspection System" }
# Check signature age (20 points)
- $signatureAge = $status.SignatureStatus.SignatureAge.Days
- if ($signatureAge -le 1) {
+ $signatureAge = if ($status.SignatureStatus.SignatureAge) { $status.SignatureStatus.SignatureAge.Days } else { $null }
+ if ($null -eq $signatureAge) {
+ $status.Recommendations += "Update virus definitions (signature update date unavailable)"
+ } elseif ($signatureAge -le 1) {
$healthScore += 20
} elseif ($signatureAge -le 3) {
$healthScore += 15
@@ -234,11 +236,15 @@ function Get-DefenderStatus {
Write-Host "`nSignatures:" -ForegroundColor Cyan
Write-Host " Version: $($status.SignatureStatus.AntivirusSignatureVersion)"
Write-Host " Last Updated: $($status.SignatureStatus.AntivirusSignatureLastUpdated)"
- Write-Host " Age: $($status.SignatureStatus.SignatureAge.Days) days" -ForegroundColor $(
- if ($status.SignatureStatus.SignatureAge.Days -le 1) { 'Green' }
- elseif ($status.SignatureStatus.SignatureAge.Days -le 3) { 'Yellow' }
- else { 'Red' }
- )
+ if ($status.SignatureStatus.SignatureAge) {
+ Write-Host " Age: $($status.SignatureStatus.SignatureAge.Days) days" -ForegroundColor $(
+ if ($status.SignatureStatus.SignatureAge.Days -le 1) { 'Green' }
+ elseif ($status.SignatureStatus.SignatureAge.Days -le 3) { 'Yellow' }
+ else { 'Red' }
+ )
+ } else {
+ Write-Host " Age: Unknown" -ForegroundColor Red
+ }
Write-Host "`nLast Scans:" -ForegroundColor Cyan
Write-Host " Quick Scan: " -NoNewline
diff --git a/WindowsDefender/Invoke-DefenderScan.ps1 b/WindowsDefender/Invoke-DefenderScan.ps1
index 122ab2d..0a47224 100644
--- a/WindowsDefender/Invoke-DefenderScan.ps1
+++ b/WindowsDefender/Invoke-DefenderScan.ps1
@@ -211,7 +211,7 @@ function Invoke-DefenderScan {
# Get threat detections
$threats = Get-MpThreat
- $results.ThreatsDetected = $threats.Count
+ $results.ThreatsDetected = @($threats).Count
foreach ($threat in $threats) {
$results.ThreatDetails += [PSCustomObject]@{
@@ -236,13 +236,13 @@ function Invoke-DefenderScan {
switch ($ScanType) {
'Quick' {
$results.EndTime = $mpStatus.QuickScanEndTime
- if ($mpStatus.QuickScanStartTime) {
+ if ($mpStatus.QuickScanStartTime -and $mpStatus.QuickScanEndTime) {
$results.Duration = ($mpStatus.QuickScanEndTime - $mpStatus.QuickScanStartTime).ToString()
}
}
'Full' {
$results.EndTime = $mpStatus.FullScanEndTime
- if ($mpStatus.FullScanStartTime) {
+ if ($mpStatus.FullScanStartTime -and $mpStatus.FullScanEndTime) {
$results.Duration = ($mpStatus.FullScanEndTime - $mpStatus.FullScanStartTime).ToString()
}
}
diff --git a/WindowsDefender/Update-DefenderConfiguration.ps1 b/WindowsDefender/Update-DefenderConfiguration.ps1
index 052ddfc..5aba7c9 100644
--- a/WindowsDefender/Update-DefenderConfiguration.ps1
+++ b/WindowsDefender/Update-DefenderConfiguration.ps1
@@ -98,7 +98,16 @@ function Update-DefenderConfiguration {
Changes = @()
Errors = @()
BeforeConfiguration = @{}
- AfterConfiguration = @{}
+ AfterConfiguration = [PSCustomObject]@{
+ RealTimeProtectionEnabled = $null
+ CloudProtection = $null
+ SampleSubmission = $null
+ PUAProtection = $null
+ ScanScheduleDay = $null
+ ScanScheduleTime = $null
+ ExclusionPaths = $null
+ ExclusionExtensions = $null
+ }
}
# Get current configuration
diff --git a/WindowsSecurityAudit.psd1 b/WindowsSecurityAudit.psd1
index d64635b..0af23b4 100644
--- a/WindowsSecurityAudit.psd1
+++ b/WindowsSecurityAudit.psd1
@@ -1,6 +1,6 @@
@{
RootModule = 'WindowsSecurityAudit.psm1'
- ModuleVersion = '1.0.0'
+ ModuleVersion = '1.1.0'
GUID = 'a8d7c4e5-3b2f-4e8a-9c1d-6f5a8b9d2e7c'
Author = 'Security Team'
CompanyName = 'Your Organization'
diff --git a/WindowsSecurityAudit.psm1 b/WindowsSecurityAudit.psm1
index edfe45c..c477fc2 100644
--- a/WindowsSecurityAudit.psm1
+++ b/WindowsSecurityAudit.psm1
@@ -14,7 +14,7 @@ Set-StrictMode -Version Latest
# Module variables
$script:ModuleRoot = $PSScriptRoot
-$script:ModuleVersion = '1.0.0'
+$script:ModuleVersion = '1.1.0'
# Import all function files
$Public = @(Get-ChildItem -Path "$PSScriptRoot\Core\*.ps1" -ErrorAction SilentlyContinue)
diff --git a/tests/WindowsSecurityAudit.Tests.ps1 b/tests/WindowsSecurityAudit.Tests.ps1
new file mode 100644
index 0000000..460dbd0
--- /dev/null
+++ b/tests/WindowsSecurityAudit.Tests.ps1
@@ -0,0 +1,157 @@
+#Requires -Modules @{ ModuleName = 'Pester'; ModuleVersion = '5.0.0' }
+
+<#
+.SYNOPSIS
+ Pester 5 structural tests for the WindowsSecurityAudit module.
+.DESCRIPTION
+ Cross-platform tests (run on any OS with Pester 5+):
+
+ * The module imports and exports exactly one function per .ps1 file found
+ in the category folders dot-sourced by WindowsSecurityAudit.psm1
+ (the expected count is computed from the files on disk, not hardcoded).
+ * Every exported function ships comment-based help with .SYNOPSIS and at
+ least one .EXAMPLE (verified through Get-Help).
+ * Every .ps1 file in the repository parses without errors.
+ * No function file assigns to the automatic variables $PID or $Host.
+ * No file invokes Invoke-Expression (or the IEX alias).
+
+ 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'
+ $script:ModulePath = Join-Path -Path $script:ModuleRoot -ChildPath "$script:ModuleName.psm1"
+
+ # Category folders dot-sourced by WindowsSecurityAudit.psm1 (kept in sync with the psm1)
+ $script:CategoryFolders = @(
+ 'Core', 'Detection', 'Analysis', 'Response', 'Enterprise', 'Hardening',
+ 'WindowsDefender', 'ThreatHunting', 'Compliance', 'ActiveDirectory',
+ 'Vulnerability', 'Forensics', 'CloudSecurity', 'Reporting'
+ )
+
+ # One exported function is expected per .ps1 file in these folders
+ $script:FunctionFiles = @(
+ foreach ($folder in $script:CategoryFolders) {
+ $folderPath = Join-Path -Path $script:ModuleRoot -ChildPath $folder
+ if (Test-Path -Path $folderPath) {
+ Get-ChildItem -Path $folderPath -Filter '*.ps1' -File
+ }
+ }
+ )
+
+ # Structural checks (parse / Invoke-Expression) cover every .ps1 file in the repo
+ $script:AllScriptFiles = @(
+ Get-ChildItem -Path $script:ModuleRoot -Filter '*.ps1' -Recurse -File |
+ Where-Object { $_.FullName -notmatch '[\\/]\.git[\\/]' }
+ )
+}
+
+BeforeAll {
+ $script:ModuleRoot = Split-Path -Parent $PSScriptRoot
+ $script:ModuleName = 'WindowsSecurityAudit'
+ $script:ModulePath = Join-Path -Path $script:ModuleRoot -ChildPath "$script:ModuleName.psm1"
+
+ $script:CategoryFolders = @(
+ 'Core', 'Detection', 'Analysis', 'Response', 'Enterprise', 'Hardening',
+ 'WindowsDefender', 'ThreatHunting', 'Compliance', 'ActiveDirectory',
+ 'Vulnerability', 'Forensics', 'CloudSecurity', 'Reporting'
+ )
+
+ $script:FunctionFiles = @(
+ foreach ($folder in $script:CategoryFolders) {
+ $folderPath = Join-Path -Path $script:ModuleRoot -ChildPath $folder
+ if (Test-Path -Path $folderPath) {
+ Get-ChildItem -Path $folderPath -Filter '*.ps1' -File
+ }
+ }
+ )
+
+ Import-Module -Name $script:ModulePath -Force -DisableNameChecking
+ $script:ExportedFunctions = @(Get-Command -Module $script:ModuleName -CommandType Function)
+
+ function Get-ScriptFileAst {
+ param([Parameter(Mandatory)][string]$Path)
+ $tokens = $null
+ $parseErrors = $null
+ $ast = [System.Management.Automation.Language.Parser]::ParseFile($Path, [ref]$tokens, [ref]$parseErrors)
+ [PSCustomObject]@{ Ast = $ast; Errors = @($parseErrors) }
+ }
+}
+
+AfterAll {
+ Remove-Module -Name $script:ModuleName -Force -ErrorAction SilentlyContinue
+}
+
+Describe 'Module import and exported functions' {
+ It 'imports without throwing' {
+ { Import-Module -Name $script:ModulePath -Force -DisableNameChecking -ErrorAction Stop } |
+ Should -Not -Throw
+ }
+
+ It 'exports one function per .ps1 file in the category folders' {
+ # Expected count is derived from the files on disk, never hardcoded
+ $script:ExportedFunctions.Count | Should -Be $script:FunctionFiles.Count
+ }
+
+ It 'exports <Name>' -ForEach $script:FunctionFiles {
+ @($script:ExportedFunctions).Name | Should -Contain $_.BaseName
+ }
+}
+
+Describe 'Comment-based help' {
+ It '<Name> has .SYNOPSIS and at least one .EXAMPLE' -ForEach $script:FunctionFiles {
+ $help = Get-Help -Name $_.BaseName -Full
+
+ # Without comment-based help Get-Help falls back to an auto-generated
+ # syntax line ("<Name> [[-Param] ...]") as the synopsis
+ $help.Synopsis | Should -Not -BeNullOrEmpty
+ $help.Synopsis | Should -Not -Match ('^' + [regex]::Escape($_.BaseName) + '\s*\[')
+
+ $examples = @($help.Examples.Example | Where-Object { $null -ne $_ })
+ $examples.Count | Should -BeGreaterOrEqual 1
+ }
+}
+
+Describe 'Script parsing' {
+ It '<Name> parses without errors' -ForEach $script:AllScriptFiles {
+ $result = Get-ScriptFileAst -Path $_.FullName
+ $messages = @($result.Errors | ForEach-Object { $_.Message }) -join '; '
+ $result.Errors.Count | Should -Be 0 -Because $messages
+ }
+}
+
+Describe 'Static safety checks' {
+ It '<Name> does not assign to $PID or $Host' -ForEach $script:FunctionFiles {
+ $result = Get-ScriptFileAst -Path $_.FullName
+ $assignments = @($result.Ast.FindAll({
+ param($node)
+ $node -is [System.Management.Automation.Language.AssignmentStatementAst]
+ }, $true))
+
+ $badAssignments = @($assignments | Where-Object {
+ $left = $_.Left
+ $left -is [System.Management.Automation.Language.VariableExpressionAst] -and
+ $left.VariablePath.UserPath -in @('PID', 'Host')
+ })
+ $badAssignments.Count | Should -Be 0
+ }
+
+ It '<Name> does not invoke Invoke-Expression or IEX' -ForEach $script:AllScriptFiles {
+ $result = Get-ScriptFileAst -Path $_.FullName
+ $commands = @($result.Ast.FindAll({
+ param($node)
+ $node -is [System.Management.Automation.Language.CommandAst]
+ }, $true))
+
+ # AST-based check: string literals mentioning IEX (e.g. detection
+ # signatures) do not count, only actual command invocations
+ $badCommands = @($commands | Where-Object {
+ $commandName = $_.GetCommandName()
+ $null -ne $commandName -and
+ ($commandName -eq 'Invoke-Expression' -or $commandName -eq 'iex')
+ })
+ $badCommands.Count | Should -Be 0
+ }
+}