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

v1.6.1: post-release audit hardening (verified findings from 6-expert review)

Okan YILDIZb59ced9aa07f
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 3f7cec0..e5d5ccb 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -39,6 +39,49 @@ jobs:
$manifest = Test-ModuleManifest -Path ./WindowsSecurityAudit.psd1 -ErrorAction Stop
Write-Host "Manifest OK: $($manifest.Name) $($manifest.Version)"
+ - name: Guard tag version matches manifest
+ # When the run was triggered by a vX.Y.Z tag, refuse to publish if the
+ # tag version differs from the psd1 ModuleVersion (prevents shipping a
+ # package whose version does not match the release tag).
+ shell: pwsh
+ run: |
+ if ($env:GITHUB_REF -like 'refs/tags/v*') {
+ $tagVersion = $env:GITHUB_REF -replace '^refs/tags/v', ''
+ $manifest = Test-ModuleManifest -Path ./WindowsSecurityAudit.psd1 -ErrorAction Stop
+ $moduleVersion = $manifest.Version.ToString()
+ if ($tagVersion -ne $moduleVersion) {
+ Write-Error "Tag version '$tagVersion' ($env:GITHUB_REF) does not match manifest ModuleVersion '$moduleVersion'. Update WindowsSecurityAudit.psd1 or re-tag the release."
+ exit 1
+ }
+ Write-Host "Tag version v$moduleVersion matches the manifest."
+ } else {
+ Write-Host "Not a tag build ($env:GITHUB_REF) - skipping tag/version guard."
+ }
+
+ - name: Stage module for publish
+ # Publish-Module ships the entire -Path directory, so copy only the
+ # files the module needs into a clean staging dir (excludes .github,
+ # tests, helper scripts, CHANGELOG.md, etc.).
+ shell: pwsh
+ run: |
+ $staging = Join-Path $env:RUNNER_TEMP 'module-staging'
+ New-Item -Path $staging -ItemType Directory -Force | Out-Null
+ $items = @(
+ 'WindowsSecurityAudit.psd1',
+ 'WindowsSecurityAudit.psm1',
+ 'LICENSE',
+ 'README.md',
+ 'Core', 'Detection', 'Analysis', 'Response', 'Enterprise',
+ 'Hardening', 'WindowsDefender', 'ThreatHunting', 'Compliance',
+ 'ActiveDirectory', 'Vulnerability', 'Forensics', 'CloudSecurity',
+ 'Reporting', 'Private'
+ )
+ foreach ($item in $items) {
+ Copy-Item -Path (Join-Path . $item) -Destination $staging -Recurse -Force -ErrorAction Stop
+ }
+ $stagedManifest = Test-ModuleManifest -Path (Join-Path $staging 'WindowsSecurityAudit.psd1') -ErrorAction Stop
+ Write-Host "Staged $($stagedManifest.Name) $($stagedManifest.Version) at $staging"
+
- name: Publish to PowerShell Gallery
# Publish only when the PSGALLERY_API_KEY repository secret exists;
# without it the run ends green with a notice instead of a red failure.
@@ -51,5 +94,6 @@ jobs:
Write-Host "::notice::PSGALLERY_API_KEY secret is not configured - skipping gallery publish. Tests and manifest validation passed."
exit 0
}
- Publish-Module -Path . -NuGetApiKey $env:PSGALLERY_API_KEY -ErrorAction Stop
+ $staging = Join-Path $env:RUNNER_TEMP 'module-staging'
+ Publish-Module -Path $staging -NuGetApiKey $env:PSGALLERY_API_KEY -ErrorAction Stop
Write-Host "Published WindowsSecurityAudit to the PowerShell Gallery."
diff --git a/Analysis/Get-EventLogAnalysis.ps1 b/Analysis/Get-EventLogAnalysis.ps1
index 3e2f982..5fcce04 100644
--- a/Analysis/Get-EventLogAnalysis.ps1
+++ b/Analysis/Get-EventLogAnalysis.ps1
@@ -112,11 +112,14 @@ function Get-EventLogAnalysis {
}
try {
- $events = Get-WinEvent -FilterHashtable @{
+ # Force to array: a single matching event comes back as a
+ # scalar EventLogRecord, and .Count on it throws under
+ # Set-StrictMode (dropping the whole log via the catch)
+ $events = @(Get-WinEvent -FilterHashtable @{
LogName = $logName
Level = $filterLevels
StartTime = $startTime
- } -ErrorAction SilentlyContinue
+ } -ErrorAction SilentlyContinue)
if ($events) {
$results.Statistics.TotalEventsAnalyzed += $events.Count
diff --git a/Analysis/Get-MemoryAnalysis.ps1 b/Analysis/Get-MemoryAnalysis.ps1
index 8c49e59..71234d3 100644
--- a/Analysis/Get-MemoryAnalysis.ps1
+++ b/Analysis/Get-MemoryAnalysis.ps1
@@ -4,7 +4,11 @@ function Get-MemoryAnalysis {
Analyzes process memory for suspicious indicators
.DESCRIPTION
Examines running processes for memory-based threats including code injection,
- hollowing, and suspicious memory patterns
+ hollowing, and suspicious memory patterns. The hollowing check is a
+ name/location heuristic: without reading process memory it cannot compare
+ in-memory code against the on-disk image, so it flags well-known Windows
+ system process names (svchost, lsass, csrss, ...) whose main module image
+ resides outside the expected %SystemRoot% location instead.
.PARAMETER ProcessId
Specific process ID to analyze (optional)
.PARAMETER CheckAllProcesses
@@ -33,9 +37,18 @@ function Get-MemoryAnalysis {
begin {
Write-Host "Analyzing process memory..." -ForegroundColor Cyan
- # Check for admin privileges
- $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
- if (-not $isAdmin) {
+ # Check for admin privileges (the Windows principal API is unavailable
+ # on non-Windows platforms - skip the check there instead of throwing)
+ $isAdmin = $false
+ $adminCheckAvailable = $true
+ try {
+ $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
+ }
+ catch {
+ $adminCheckAvailable = $false
+ Write-Verbose "Administrator privilege check not available on this platform: $_"
+ }
+ if ($adminCheckAvailable -and -not $isAdmin) {
Write-Warning "Administrator privileges recommended for complete memory analysis"
}
@@ -58,6 +71,30 @@ function Get-MemoryAnalysis {
'inject', 'hook', 'reflective', 'payload', 'shellcode',
'mimikatz', 'meterpreter', 'cobalt', 'beacon'
)
+
+ # Expected on-disk image for well-known Windows system process names.
+ # A process using one of these names whose main module lives elsewhere is a
+ # masquerading / process-hollowing heuristic signal (no memory is read).
+ # Empty when %SystemRoot% is unavailable (non-Windows platforms).
+ $expectedSystemImages = @{}
+ if (-not [string]::IsNullOrEmpty($env:SystemRoot)) {
+ $expectedSystemImages = @{
+ 'svchost' = "$env:SystemRoot\System32\svchost.exe"
+ 'lsass' = "$env:SystemRoot\System32\lsass.exe"
+ 'csrss' = "$env:SystemRoot\System32\csrss.exe"
+ 'smss' = "$env:SystemRoot\System32\smss.exe"
+ 'wininit' = "$env:SystemRoot\System32\wininit.exe"
+ 'winlogon' = "$env:SystemRoot\System32\winlogon.exe"
+ 'services' = "$env:SystemRoot\System32\services.exe"
+ 'spoolsv' = "$env:SystemRoot\System32\spoolsv.exe"
+ 'lsm' = "$env:SystemRoot\System32\lsm.exe"
+ 'dwm' = "$env:SystemRoot\System32\dwm.exe"
+ 'sihost' = "$env:SystemRoot\System32\sihost.exe"
+ 'taskhostw' = "$env:SystemRoot\System32\taskhostw.exe"
+ 'runtimebroker' = "$env:SystemRoot\System32\RuntimeBroker.exe"
+ 'explorer' = "$env:SystemRoot\explorer.exe"
+ }
+ }
}
process {
@@ -148,28 +185,53 @@ function Get-MemoryAnalysis {
Write-Verbose "Could not enumerate modules for $($process.ProcessName): $_"
}
- # Check for process hollowing indicators
- # Look for mismatches between process image and memory
- if ($process.Path) {
+ # Process hollowing / masquerading heuristic.
+ # Process.Path IS MainModule.FileName in the .NET Process API, so
+ # comparing the two (as this check previously did) is structurally
+ # false and can never fire. Without reading process memory there is
+ # no reliable hollowing check, so instead flag well-known Windows
+ # system process names whose main module image does not reside at
+ # the expected system location (e.g. a process named 'svchost'
+ # whose image is not %SystemRoot%\System32\svchost.exe).
+ $processNameLower = $process.ProcessName.ToLower()
+ if ($expectedSystemImages.ContainsKey($processNameLower)) {
+ $actualImagePath = $null
try {
$mainModule = $process.MainModule
+ if ($null -ne $mainModule) { $actualImagePath = $mainModule.FileName }
+ }
+ catch {
+ Write-Verbose "Could not read main module for $($process.ProcessName)"
+ }
+
+ if (-not [string]::IsNullOrWhiteSpace($actualImagePath)) {
+ # Tolerate the SysWOW64 twin of System32 images (32-bit services)
+ $expectedImagePath = $expectedSystemImages[$processNameLower]
+ $expectedImagePaths = @($expectedImagePath)
+ if ($expectedImagePath -match '\\System32\\') {
+ $expectedImagePaths += ($expectedImagePath -replace '\\System32\\', '\SysWOW64\')
+ }
+
+ $imagePathMatches = $false
+ foreach ($expectedPath in $expectedImagePaths) {
+ if ($actualImagePath.Equals($expectedPath, [System.StringComparison]::OrdinalIgnoreCase)) {
+ $imagePathMatches = $true
+ break
+ }
+ }
- # Compare main module with process path
- if ($mainModule.FileName -ne $process.Path) {
+ if (-not $imagePathMatches) {
$results.HollowingIndicators += [PSCustomObject]@{
ProcessName = $process.ProcessName
ProcessId = $process.Id
- ExpectedPath = $process.Path
- ActualPath = $mainModule.FileName
- Reason = "Main module path mismatch - possible process hollowing"
+ ExpectedPath = $expectedImagePath
+ ActualPath = $actualImagePath
+ Reason = "Well-known system process name running from an unexpected image location - masquerading/hollowing heuristic (image paths compared, memory contents NOT compared)"
}
$results.Statistics.HollowingIndicators++
- $processAnalysis.Findings += "Possible process hollowing detected"
+ $processAnalysis.Findings += "System process name with unexpected image location: $actualImagePath (masquerade/hollowing heuristic)"
}
}
- catch {
- Write-Verbose "Could not check main module for $($process.ProcessName)"
- }
}
# Check for code injection indicators
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ea7988f..4c3281e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+## [1.6.1] - 2026-10-27
+
+Post-release audit hardening. Every finding below was verified against the code by independent reviewers before fixing.
+
+### Security
+
+- `Invoke-IncidentResponse`: network isolation now requires `-IsolateSystem` explicitly — `-Severity Critical` alone no longer disables all network adapters (WinRM lockout risk); ConfirmImpact='High' added here and in `Set-SecurityBaseline`, `Enable-PowerShellSecurity`, `Update-DefenderConfiguration`.
+- `Export-MemoryDump`: SupportsShouldProcess + ConfirmImpact='High'; dump files are ACL-locked (SYSTEM+Administrators) BEFORE content is written, not after (credential-bearing dumps were world-readable during the write window).
+- `Register-ScheduledSecurityScan`: the generated scan script (embeds the webhook secret) is ACL-locked before content is written.
+- CSV formula-injection escaping (`Protect-CsvField`) across all forensic/incident/compliance CSV exports; HTML encoding (`ConvertTo-HtmlEncoded`) for UPN/IP/process/computer names in HTML reports; Chart.js pinned to 4.4.0 with SRI integrity hash in both HTML reports.
+
+### Fixed
+
+- `Test-M365SecurityPosture`: removed hardcoded Pass/Fail/Warning results — checks now query Microsoft Graph where possible (Conditional Access, Security Defaults) or honestly report NotEvaluated; score computed only over evaluated checks, null when nothing could be evaluated.
+- `Get-SecurityMetrics`: no longer reports 100/Excellent when collectors fail — DataCompleteness reported, >50% collector failure → score null/Unknown, any failure caps health at Good.
+- `Get-ThreatIntelligence`: domain/host IOCs now actually correlate (DNS client cache + Sysmon event 22) and hash IOCs are matched against running-process image hashes; new SourcesChecked transparency list.
+- `Get-MemoryAnalysis`: replaced the structurally-dead hollowing check with an honest system-process name/image-location heuristic.
+- Compliance (CIS/NIST/PCI): controls no longer vanish when a cmdlet is missing (inflating percentages) — they report Manual/NotApplicable with the reason; NIST AC-7 reads the real lockout policy via Get-LocalPasswordPolicy, AC-11 rejects 0, AU-9 no longer reports Compliant on unreadable ACLs; dead -Level/-Revision/-Version parameters now warn and label accurately.
+- `Invoke-SecurityAssessment`: WDAC audit mode (1) is no longer reported as Enforced (2); failed port/share/user queries no longer score as Pass; strict-mode crash on a single restore point fixed; -AssessmentType warns it currently runs identical checks.
+- Strict-mode crashes fixed in `Get-SecurityBaseline` (-ExportPath `$ComputerName_`), `Get-MultiSystemAudit` (clean hosts no longer abort the run), `Get-EventLogAnalysis` (single matching event).
+- `Get-SecurityBaseline`: BitLocker points awarded proportionally (fully-encrypted single-disk machines can reach 100); -ComputerName honestly warns it labels only.
+- `Invoke-SecurityRemediation -WhatIf` now generates the rollback script preview as documented.
+- `Test-SystemIntegrity`: SFC/DISM verdicts no longer parse localized English text — exit codes + timestamp-correlated CBS.log markers only (locale-independence claim is now true).
+- `Find-LateralMovement`/`New-ForensicTimeline`: hitting -MaxEvents now warns loudly and flags Truncated.
+- `Get-USBHistory`: LastConnected no longer duplicates the install date (reported as unknown).
+- Packaging: manifest exports the explicit 72-function list (Gallery metadata/autoload), psd1 is UTF-8 BOM (PS 5.1 safe), CompatiblePSEditions added, honest dependency description; loader no longer swallows file-load errors (partial loads warn loudly and export only what loaded); quiet import (Write-Verbose); publish workflow stages a clean package (no tests/.github/helper scripts) and fails on tag/manifest version mismatch.
+- README: all unverifiable marketing claims and inflated feature descriptions replaced with audited, code-verified wording.
+
## [1.6.0] - 2026-10-26
### Added
@@ -113,8 +141,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Cloud Security: Azure AD risky sign-ins, M365 security posture, cloud compliance status.
- Hardening: audit policies, PowerShell security (logging, transcription), security baseline enforcement — all with `-WhatIf` support.
-[Unreleased]: https://github.com/okanyildiz/WindowsSecurityAudit/compare/v1.3.0...HEAD
+[Unreleased]: https://github.com/okanyildiz/WindowsSecurityAudit/compare/v1.6.1...HEAD
+[1.6.1]: https://github.com/okanyildiz/WindowsSecurityAudit/releases/tag/v1.6.1
+[1.6.0]: https://github.com/okanyildiz/WindowsSecurityAudit/releases/tag/v1.6.0
+[1.5.0]: https://github.com/okanyildiz/WindowsSecurityAudit/releases/tag/v1.5.0
+[1.4.0]: https://github.com/okanyildiz/WindowsSecurityAudit/releases/tag/v1.4.0
[1.3.0]: https://github.com/okanyildiz/WindowsSecurityAudit/releases/tag/v1.3.0
[1.2.0]: https://github.com/okanyildiz/WindowsSecurityAudit/releases/tag/v1.2.0
[1.1.0]: https://github.com/okanyildiz/WindowsSecurityAudit/releases/tag/v1.1.0
-[1.0.0]: https://github.com/okanyildiz/WindowsSecurityAudit/releases/tag/v1.0.0
+[1.0.0]: https://github.com/okanyildiz/WindowsSecurityAudit
diff --git a/CloudSecurity/Get-AzureADRiskySignIns.ps1 b/CloudSecurity/Get-AzureADRiskySignIns.ps1
index 27ecd2d..b8a2023 100644
--- a/CloudSecurity/Get-AzureADRiskySignIns.ps1
+++ b/CloudSecurity/Get-AzureADRiskySignIns.ps1
@@ -171,7 +171,12 @@ function Get-AzureADRiskySignIns {
if ($Format -in @('CSV', 'All')) {
$csvPath = Join-Path $ExportPath "RiskySignIns_$timestamp.csv"
- $results.RiskySignIns | Export-Csv $csvPath -NoTypeInformation
+ $results.RiskySignIns |
+ Select-Object DetectionId, CreatedDateTime,
+ @{N='UserPrincipalName';E={Protect-CsvField $_.UserPrincipalName}},
+ RiskLevel, RiskState, RiskEventType,
+ @{N='IPAddress';E={Protect-CsvField $_.IPAddress}} |
+ Export-Csv $csvPath -NoTypeInformation
Write-Host "Exported CSV: $csvPath" -ForegroundColor Green
}
@@ -275,14 +280,17 @@ function Generate-RiskySignInsHTML {
foreach ($signIn in ($Results.RiskySignIns | Sort-Object CreatedDateTime -Descending)) {
$riskClass = $signIn.RiskLevel.ToLower()
$dateTime = $signIn.CreatedDateTime.ToString('yyyy-MM-dd HH:mm:ss')
-
+ $userPrincipalName = ConvertTo-HtmlEncoded $signIn.UserPrincipalName
+ $ipAddress = ConvertTo-HtmlEncoded $signIn.IPAddress
+ $riskEventType = ConvertTo-HtmlEncoded $signIn.RiskEventType
+
$html += @"
<tr>
<td>$dateTime</td>
- <td>$($signIn.UserPrincipalName)</td>
+ <td>$userPrincipalName</td>
<td class="$riskClass">$($signIn.RiskLevel.ToUpper())</td>
- <td>$($signIn.IPAddress)</td>
- <td>$($signIn.RiskEventType)</td>
+ <td>$ipAddress</td>
+ <td>$riskEventType</td>
</tr>
"@
}
diff --git a/CloudSecurity/Test-M365SecurityPosture.ps1 b/CloudSecurity/Test-M365SecurityPosture.ps1
index 4c5f27c..b967bda 100644
--- a/CloudSecurity/Test-M365SecurityPosture.ps1
+++ b/CloudSecurity/Test-M365SecurityPosture.ps1
@@ -1,11 +1,71 @@
+function Add-M365Finding {
+ <#
+ .SYNOPSIS
+ Records a single M365 posture finding and updates summary counters.
+ 'NotEvaluated' findings are tracked separately and never enter the score.
+ #>
+ param(
+ [Parameter(Mandatory)]
+ $Results,
+
+ [Parameter(Mandatory)]
+ [string]$Name,
+
+ [Parameter(Mandatory)]
+ [string]$Category,
+
+ [Parameter(Mandatory)]
+ [string]$Severity,
+
+ [Parameter(Mandatory)]
+ [ValidateSet('Pass', 'Fail', 'Warning', 'NotEvaluated')]
+ [string]$Status,
+
+ [string]$Actual = "",
+ [string]$Expected = ""
+ )
+
+ $Results.SecurityFindings += [PSCustomObject]@{
+ Name = $Name
+ Category = $Category
+ Status = $Status
+ Severity = $Severity
+ Actual = $Actual
+ Expected = $Expected
+ }
+
+ if ($Status -eq 'NotEvaluated') {
+ $Results.Summary.NotEvaluated++
+ return
+ }
+
+ $Results.Summary.TotalChecks++
+ switch ($Status) {
+ 'Pass' { $Results.Summary.Passed++ }
+ 'Fail' {
+ $Results.Summary.Failed++
+ if ($Severity -eq 'Critical') {
+ $Results.Summary.CriticalIssues++
+ }
+ }
+ 'Warning' { $Results.Summary.Warnings++ }
+ }
+}
+
function Test-M365SecurityPosture {
<#
.SYNOPSIS
Assesses Microsoft 365 security configuration
.DESCRIPTION
- Performs comprehensive security assessment of Microsoft 365 including
- Exchange Online, SharePoint, Teams, and Conditional Access
+ Performs a security assessment of Microsoft 365 against live tenant data
+ retrieved via Microsoft Graph (Conditional Access policies, security
+ defaults). Checks whose configuration is not exposed through Microsoft
+ Graph (Exchange Online, SharePoint, Teams workload settings) are reported
+ as NotEvaluated with the API required to assess them — results are never
+ fabricated. The compliance score is computed over evaluated checks only;
+ if no check could be evaluated, OverallScore is $null and OverallStatus
+ is 'NotEvaluated'.
.PARAMETER CheckExchangeOnline
Assess Exchange Online security
@@ -45,19 +105,24 @@ function Test-M365SecurityPosture {
Write-Host " M365 SECURITY POSTURE ASSESSMENT" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
- # Check connection
+ # Live tenant data requires a Microsoft Graph connection. Without one the
+ # function must not invent results: every check degrades to NotEvaluated.
+ $graphConnected = $false
+ $tenantId = 'NotConnected'
try {
$context = Get-MgContext -ErrorAction Stop
-
- if (-not $context) {
- throw "Not connected to Microsoft Graph"
+ if ($context) {
+ $graphConnected = $true
+ if ($context.TenantId) { $tenantId = $context.TenantId }
+ Write-Host "Connected to tenant: $tenantId" -ForegroundColor Green
}
-
- Write-Host "Connected to tenant: $($context.TenantId)" -ForegroundColor Green
}
catch {
- Write-Error "Please connect to Microsoft Graph first: Connect-MgGraph -Scopes 'Directory.Read.All','Policy.Read.All'"
- throw
+ Write-Verbose "Get-MgContext failed: $_"
+ }
+
+ if (-not $graphConnected) {
+ Write-Warning "Not connected to Microsoft Graph. No tenant data will be queried and every check will be reported as NotEvaluated. Connect first: Connect-MgGraph -Scopes 'Directory.Read.All','Policy.Read.All'"
}
# If no specific checks selected, run all
@@ -72,67 +137,57 @@ function Test-M365SecurityPosture {
$results = [PSCustomObject]@{
AssessmentDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
TenantInfo = @{
- TenantId = $context.TenantId
+ TenantId = $tenantId
TenantName = "N/A"
}
SecurityFindings = @()
- ComplianceScore = 0
+ ComplianceScore = $null
+ OverallScore = $null
+ OverallStatus = 'NotEvaluated'
+ EvaluatedCount = 0
+ NotEvaluatedCount = 0
Summary = @{
TotalChecks = 0
Passed = 0
Failed = 0
Warnings = 0
CriticalIssues = 0
+ NotEvaluated = 0
}
}
}
process {
try {
- # Get organization info
- try {
- $org = Get-MgOrganization -ErrorAction Stop | Select-Object -First 1
- if ($org) {
- $results.TenantInfo.TenantName = $org.DisplayName
+ $notConnectedReason = "Not evaluated — not connected to Microsoft Graph (run Connect-MgGraph -Scopes 'Directory.Read.All','Policy.Read.All')"
+
+ # Get organization info (live query, non-fatal)
+ if ($graphConnected) {
+ try {
+ $org = Get-MgOrganization -ErrorAction Stop | Select-Object -First 1
+ if ($org) {
+ $results.TenantInfo.TenantName = $org.DisplayName
+ }
+ }
+ catch {
+ Write-Warning "Could not retrieve organization details: $($_.Exception.Message)"
}
- }
- catch {
- Write-Warning "Could not retrieve organization details"
}
- # Exchange Online checks
+ # Exchange Online checks. Exchange/Defender policy configuration is not
+ # exposed through the Microsoft Graph cmdlets used by this module, so
+ # these checks are honestly reported as NotEvaluated with the API that
+ # would be required — never fabricated.
if ($CheckExchangeOnline) {
Write-Host "`nAssessing Exchange Online Security..." -ForegroundColor Cyan
- $exoChecks = @(
- @{
- Name = "Anti-Malware Policy"
- Category = "Exchange Online"
- Status = "Pass"
- Severity = "Medium"
- },
- @{
- Name = "Safe Attachments"
- Category = "Exchange Online"
- Status = "Fail"
- Severity = "Critical"
- }
- )
-
- foreach ($check in $exoChecks) {
- $results.SecurityFindings += [PSCustomObject]$check
- $results.Summary.TotalChecks++
-
- switch ($check.Status) {
- 'Pass' { $results.Summary.Passed++ }
- 'Fail' {
- $results.Summary.Failed++
- if ($check.Severity -eq 'Critical') {
- $results.Summary.CriticalIssues++
- }
- }
- 'Warning' { $results.Summary.Warnings++ }
- }
+ if ($graphConnected) {
+ Add-M365Finding -Results $results -Name "Anti-Malware Policy" -Category "Exchange Online" -Severity "Medium" -Status "NotEvaluated" -Actual "Not evaluated — requires Exchange Online PowerShell (Get-MalwareFilterPolicy); not exposed via Microsoft Graph" -Expected "Default anti-malware policy enabled"
+ Add-M365Finding -Results $results -Name "Safe Attachments" -Category "Exchange Online" -Severity "Critical" -Status "NotEvaluated" -Actual "Not evaluated — requires Exchange Online PowerShell (Get-SafeAttachmentPolicy / Get-SafeAttachmentRule); not exposed via Microsoft Graph" -Expected "Safe Attachments policy covering all users"
+ }
+ else {
+ Add-M365Finding -Results $results -Name "Anti-Malware Policy" -Category "Exchange Online" -Severity "Medium" -Status "NotEvaluated" -Actual $notConnectedReason
+ Add-M365Finding -Results $results -Name "Safe Attachments" -Category "Exchange Online" -Severity "Critical" -Status "NotEvaluated" -Actual $notConnectedReason
}
}
@@ -140,35 +195,13 @@ function Test-M365SecurityPosture {
if ($CheckSharePoint) {
Write-Host "`nAssessing SharePoint/OneDrive Security..." -ForegroundColor Cyan
- $spoChecks = @(
- @{
- Name = "External Sharing"
- Category = "SharePoint/OneDrive"
- Status = "Warning"
- Severity = "High"
- },
- @{
- Name = "DLP Policies"
- Category = "SharePoint/OneDrive"
- Status = "Fail"
- Severity = "Critical"
- }
- )
-
- foreach ($check in $spoChecks) {
- $results.SecurityFindings += [PSCustomObject]$check
- $results.Summary.TotalChecks++
-
- switch ($check.Status) {
- 'Pass' { $results.Summary.Passed++ }
- 'Fail' {
- $results.Summary.Failed++
- if ($check.Severity -eq 'Critical') {
- $results.Summary.CriticalIssues++
- }
- }
- 'Warning' { $results.Summary.Warnings++ }
- }
+ if ($graphConnected) {
+ Add-M365Finding -Results $results -Name "External Sharing" -Category "SharePoint/OneDrive" -Severity "High" -Status "NotEvaluated" -Actual "Not evaluated — requires SharePoint Online Management Shell (Get-SPOTenant) or SharePoint admin API; not exposed via Microsoft Graph" -Expected "External sharing restricted to existing guests or disabled"
+ Add-M365Finding -Results $results -Name "DLP Policies" -Category "SharePoint/OneDrive" -Severity "Critical" -Status "NotEvaluated" -Actual "Not evaluated — requires Purview compliance PowerShell (Get-DlpCompliancePolicy); not exposed via Microsoft Graph" -Expected "At least one DLP policy covering SharePoint/OneDrive locations"
+ }
+ else {
+ Add-M365Finding -Results $results -Name "External Sharing" -Category "SharePoint/OneDrive" -Severity "High" -Status "NotEvaluated" -Actual $notConnectedReason
+ Add-M365Finding -Results $results -Name "DLP Policies" -Category "SharePoint/OneDrive" -Severity "Critical" -Status "NotEvaluated" -Actual $notConnectedReason
}
}
@@ -176,71 +209,83 @@ function Test-M365SecurityPosture {
if ($CheckTeams) {
Write-Host "`nAssessing Microsoft Teams Security..." -ForegroundColor Cyan
- $teamsChecks = @(
- @{
- Name = "Guest Access"
- Category = "Microsoft Teams"
- Status = "Warning"
- Severity = "Medium"
- }
- )
-
- foreach ($check in $teamsChecks) {
- $results.SecurityFindings += [PSCustomObject]$check
- $results.Summary.TotalChecks++
-
- switch ($check.Status) {
- 'Pass' { $results.Summary.Passed++ }
- 'Fail' {
- $results.Summary.Failed++
- if ($check.Severity -eq 'Critical') {
- $results.Summary.CriticalIssues++
- }
- }
- 'Warning' { $results.Summary.Warnings++ }
- }
+ if ($graphConnected) {
+ Add-M365Finding -Results $results -Name "Guest Access" -Category "Microsoft Teams" -Severity "Medium" -Status "NotEvaluated" -Actual "Not evaluated — requires Microsoft Teams PowerShell (Get-CsTeamsClientConfiguration); not exposed via Microsoft Graph" -Expected "Guest access disabled or restricted per policy"
+ }
+ else {
+ Add-M365Finding -Results $results -Name "Guest Access" -Category "Microsoft Teams" -Severity "Medium" -Status "NotEvaluated" -Actual $notConnectedReason
}
}
- # Conditional Access checks
+ # Conditional Access checks (live Microsoft Graph queries)
if ($CheckConditionalAccess) {
Write-Host "`nAssessing Conditional Access..." -ForegroundColor Cyan
- try {
- $caPolicies = Get-MgIdentityConditionalAccessPolicy -All -ErrorAction Stop
-
- $enabledPolicies = @($caPolicies | Where-Object { $_.State -eq 'enabled' }).Count
-
- if ($enabledPolicies -gt 0) {
- $results.SecurityFindings += [PSCustomObject]@{
- Name = "Conditional Access Policies"
- Category = "Conditional Access"
- Status = "Pass"
- Severity = "High"
+ if ($graphConnected) {
+ try {
+ $caPolicies = @(Get-MgIdentityConditionalAccessPolicy -All -ErrorAction Stop)
+
+ $enabledPolicies = @($caPolicies | Where-Object { $_.State -eq 'enabled' }).Count
+
+ if ($enabledPolicies -gt 0) {
+ Add-M365Finding -Results $results -Name "Conditional Access Policies" -Category "Conditional Access" -Severity "High" -Status "Pass" -Actual "$enabledPolicies of $(@($caPolicies).Count) Conditional Access policies enabled" -Expected "At least one enabled Conditional Access policy"
}
- $results.Summary.Passed++
- }
- else {
- $results.SecurityFindings += [PSCustomObject]@{
- Name = "Conditional Access Policies"
- Category = "Conditional Access"
- Status = "Fail"
- Severity = "Critical"
+ else {
+ Add-M365Finding -Results $results -Name "Conditional Access Policies" -Category "Conditional Access" -Severity "Critical" -Status "Fail" -Actual "No enabled Conditional Access policies found ($( @($caPolicies).Count) total, none enabled)" -Expected "At least one enabled Conditional Access policy"
}
- $results.Summary.Failed++
- $results.Summary.CriticalIssues++
+ }
+ catch {
+ Write-Warning "Could not retrieve Conditional Access policies: $($_.Exception.Message)"
+ Add-M365Finding -Results $results -Name "Conditional Access Policies" -Category "Conditional Access" -Severity "Critical" -Status "NotEvaluated" -Actual "Not evaluated — Conditional Access query failed: $($_.Exception.Message)"
}
- $results.Summary.TotalChecks++
+ try {
+ $secDefaults = Get-MgPolicyIdentitySecurityDefaultEnforcementPolicy -ErrorAction Stop
+
+ if ($secDefaults -and $secDefaults.IsEnabled) {
+ Add-M365Finding -Results $results -Name "Security Defaults" -Category "Conditional Access" -Severity "High" -Status "Pass" -Actual "Security Defaults are enabled" -Expected "Enabled, unless Conditional Access policies are in use"
+ }
+ else {
+ Add-M365Finding -Results $results -Name "Security Defaults" -Category "Conditional Access" -Severity "High" -Status "Warning" -Actual "Security Defaults are disabled" -Expected "Enabled, unless Conditional Access policies are in use"
+ }
+ }
+ catch {
+ Write-Warning "Could not retrieve Security Defaults policy: $($_.Exception.Message)"
+ Add-M365Finding -Results $results -Name "Security Defaults" -Category "Conditional Access" -Severity "High" -Status "NotEvaluated" -Actual "Not evaluated — Security Defaults query failed: $($_.Exception.Message)"
+ }
}
- catch {
- Write-Warning "Could not retrieve Conditional Access policies"
+ else {
+ Add-M365Finding -Results $results -Name "Conditional Access Policies" -Category "Conditional Access" -Severity "Critical" -Status "NotEvaluated" -Actual $notConnectedReason
+ Add-M365Finding -Results $results -Name "Security Defaults" -Category "Conditional Access" -Severity "High" -Status "NotEvaluated" -Actual $notConnectedReason
}
}
- # Calculate compliance score
+ # Calculate compliance score over evaluated checks only
+ $results.EvaluatedCount = $results.Summary.TotalChecks
+ $results.NotEvaluatedCount = $results.Summary.NotEvaluated
+
if ($results.Summary.TotalChecks -gt 0) {
$results.ComplianceScore = [Math]::Round(($results.Summary.Passed / $results.Summary.TotalChecks) * 100, 1)
+ $results.OverallScore = $results.ComplianceScore
+ $results.OverallStatus = if ($results.Summary.Failed -gt 0) { 'AttentionRequired' }
+ elseif ($results.Summary.Warnings -gt 0) { 'Warning' }
+ else { 'Pass' }
+
+ if ($results.Summary.NotEvaluated -gt 0) {
+ Write-Warning "$($results.Summary.NotEvaluated) check(s) could not be evaluated and were excluded from the score. The score covers only the $($results.Summary.TotalChecks) evaluated check(s)."
+ }
+ }
+ else {
+ $results.ComplianceScore = $null
+ $results.OverallScore = $null
+ $results.OverallStatus = 'NotEvaluated'
+
+ if (-not $graphConnected) {
+ Write-Warning "No security checks could be evaluated because there is no Microsoft Graph connection. OverallScore is null — no compliance score was computed."
+ }
+ else {
+ Write-Warning "No security checks could be evaluated (all queries failed). OverallScore is null — no compliance score was computed."
+ }
}
# Export if requested
@@ -284,15 +329,23 @@ function Test-M365SecurityPosture {
Write-Host " M365 ASSESSMENT COMPLETE" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
- $scoreColor = if ($results.ComplianceScore -ge 80) { 'Green' }
- elseif ($results.ComplianceScore -ge 60) { 'Yellow' }
- else { 'Red' }
+ if ($null -ne $results.ComplianceScore) {
+ $scoreColor = if ($results.ComplianceScore -ge 80) { 'Green' }
+ elseif ($results.ComplianceScore -ge 60) { 'Yellow' }
+ else { 'Red' }
+
+ Write-Host "`nCompliance Score: $($results.ComplianceScore)% (over $($results.EvaluatedCount) evaluated check(s))" -ForegroundColor $scoreColor
+ }
+ else {
+ Write-Host "`nCompliance Score: N/A — no checks could be evaluated" -ForegroundColor Yellow
+ }
- Write-Host "`nCompliance Score: $($results.ComplianceScore)%" -ForegroundColor $scoreColor
+ Write-Host "Overall Status: $($results.OverallStatus)" -ForegroundColor White
Write-Host "Total Checks: $($results.Summary.TotalChecks)" -ForegroundColor White
Write-Host "Passed: $($results.Summary.Passed)" -ForegroundColor Green
Write-Host "Failed: $($results.Summary.Failed)" -ForegroundColor Red
Write-Host "Critical Issues: $($results.Summary.CriticalIssues)" -ForegroundColor Red
+ Write-Host "Not Evaluated: $($results.Summary.NotEvaluated)" -ForegroundColor Yellow
return $results
}
@@ -301,10 +354,13 @@ function Test-M365SecurityPosture {
function Generate-M365SecurityHTML {
param($Results)
- $scoreColor = if ($Results.ComplianceScore -ge 80) { '#107c10' }
+ $scoreColor = if ($null -eq $Results.ComplianceScore) { '#605e5c' }
+ elseif ($Results.ComplianceScore -ge 80) { '#107c10' }
elseif ($Results.ComplianceScore -ge 60) { '#f7630c' }
else { '#d13438' }
+ $scoreDisplay = if ($null -eq $Results.ComplianceScore) { 'N/A' } else { "$($Results.ComplianceScore)%" }
+
$html = @'
<!DOCTYPE html>
<html>
@@ -323,6 +379,7 @@ function Generate-M365SecurityHTML {
.pass { color: #107c10; font-weight: bold; }
.fail { color: #d13438; font-weight: bold; }
.warning { color: #f7630c; font-weight: bold; }
+ .noteval { color: #605e5c; font-weight: bold; }
.score-box { text-align: center; padding: 30px; margin: 20px 0; border-radius: 10px; color: white; }
.score-value { font-size: 48px; font-weight: bold; }
</style>
@@ -334,15 +391,17 @@ function Generate-M365SecurityHTML {
$html += @"
<div class="score-box" style="background: $scoreColor;">
- <div class="score-value">$($Results.ComplianceScore)%</div>
- <div>Security Compliance Score</div>
+ <div class="score-value">$scoreDisplay</div>
+ <div>Security Compliance Score (evaluated checks only)</div>
</div>
<h2>Assessment Summary</h2>
- <p><strong>Total Checks:</strong> $($Results.Summary.TotalChecks)</p>
+ <p><strong>Overall Status:</strong> $($Results.OverallStatus)</p>
+ <p><strong>Total Checks (evaluated):</strong> $($Results.Summary.TotalChecks)</p>
<p><strong>Passed:</strong> $($Results.Summary.Passed)</p>
<p><strong>Failed:</strong> $($Results.Summary.Failed)</p>
<p><strong>Critical Issues:</strong> $($Results.Summary.CriticalIssues)</p>
+ <p><strong>Not Evaluated:</strong> $($Results.Summary.NotEvaluated)</p>
<h2>Security Findings</h2>
<table>
@@ -352,6 +411,7 @@ function Generate-M365SecurityHTML {
<th>Check Name</th>
<th>Severity</th>
<th>Status</th>
+ <th>Details</th>
</tr>
</thead>
<tbody>
@@ -362,6 +422,7 @@ function Generate-M365SecurityHTML {
'Pass' { 'pass' }
'Fail' { 'fail' }
'Warning' { 'warning' }
+ default { 'noteval' }
}
$html += @"
@@ -370,6 +431,7 @@ function Generate-M365SecurityHTML {
<td>$($finding.Name)</td>
<td>$($finding.Severity)</td>
<td class="$statusClass">$($finding.Status)</td>
+ <td>$($finding.Actual)</td>
</tr>
"@
}
@@ -387,4 +449,4 @@ function Generate-M365SecurityHTML {
'@
return $html
-}
\ No newline at end of file
+}
diff --git a/Compliance/Export-ComplianceEvidence.ps1 b/Compliance/Export-ComplianceEvidence.ps1
index 4223c87..654d488 100644
--- a/Compliance/Export-ComplianceEvidence.ps1
+++ b/Compliance/Export-ComplianceEvidence.ps1
@@ -462,7 +462,10 @@ DIRECTORY STRUCTURE:
04_SystemInfo/ - System inventory and information
INTEGRITY VERIFICATION:
-All collected files have been hashed with SHA-256.
+The configuration exports (security policy, audit policy, firewall rules) are
+hashed with SHA-256 at collection time, and the SHA-256 hash of the final ZIP
+bundle is printed at the end of collection. Other collected files (logs, status
+captures, system information) are not individually hashed.
See 00_Metadata/Evidence_Manifest.json for hash values.
IMPORTANT NOTES:
diff --git a/Compliance/Test-CISBenchmark.ps1 b/Compliance/Test-CISBenchmark.ps1
index 0fe975f..058f08b 100644
--- a/Compliance/Test-CISBenchmark.ps1
+++ b/Compliance/Test-CISBenchmark.ps1
@@ -28,6 +28,10 @@ function Test-CISBenchmark {
)
begin {
+ if ($Level -ne 1) {
+ Write-Warning "Level $Level requested; only Level 1 checks are currently implemented"
+ $Level = 1
+ }
Write-Host "=== CIS BENCHMARK COMPLIANCE TEST ===" -ForegroundColor Cyan
Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow
Write-Host "CIS Level: $Level" -ForegroundColor Yellow
@@ -126,98 +130,127 @@ function Test-CISBenchmark {
Write-Host "`n[1/5] Testing Password Policy Controls..." -ForegroundColor Cyan
try {
- # Export security policy
- $tempFile = "$env:TEMP\secpol_$(Get-Random).cfg"
- $null = secedit /export /cfg $tempFile /quiet
- Start-Sleep -Milliseconds 500
-
- if (Test-Path $tempFile) {
- $secpolContent = Get-Content $tempFile -Raw
-
- # CIS 1.1.1 - Password History
- $passwordHistory = Get-SecEditValue -Content $secpolContent -Setting "PasswordHistorySize"
- if ($passwordHistory) {
+ # Export security policy. secedit is Windows-only; when it is
+ # missing or the export fails, emit the controls as Manual instead
+ # of silently dropping them (the per-setting 'if ($value)' guards
+ # below used to skip controls with no warning).
+ $seceditCmd = Get-Command 'secedit.exe' -ErrorAction SilentlyContinue
+ if ($null -eq $seceditCmd) { $seceditCmd = Get-Command 'secedit' -ErrorAction SilentlyContinue }
+
+ $secpolContent = $null
+ if ($null -ne $seceditCmd) {
+ $tempFile = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath "secpol_$(Get-Random).cfg"
+ try {
+ $null = & $seceditCmd.Source /export /cfg $tempFile /quiet 2>&1
+ Start-Sleep -Milliseconds 500
+ if (Test-Path $tempFile) {
+ $secpolContent = Get-Content $tempFile -Raw
+ }
+ }
+ catch {
+ Write-Warning "Could not export security policy: $_"
+ }
+ finally {
+ if (Test-Path $tempFile -ErrorAction SilentlyContinue) {
+ Remove-Item $tempFile -Force -ErrorAction SilentlyContinue
+ }
+ }
+ }
+
+ if ($null -eq $secpolContent) {
+ Write-Warning "Could not export security policy; password policy controls require manual review"
+ $manualSpecs = @(
+ @{ ControlID = 'CIS-1.1.1'; ControlName = 'Enforce password history'; Expected = '24 or more passwords'; Severity = 'High'; Remediation = 'Set to 24 or more passwords remembered' }
+ @{ ControlID = 'CIS-1.1.2'; ControlName = 'Maximum password age'; Expected = '365 or fewer days (but not 0)'; Severity = 'High'; Remediation = 'Set to 365 or fewer days' }
+ @{ ControlID = 'CIS-1.1.3'; ControlName = 'Minimum password age'; Expected = '1 or more days'; Severity = 'Medium'; Remediation = 'Set to 1 or more days' }
+ @{ ControlID = 'CIS-1.1.4'; ControlName = 'Minimum password length'; Expected = '14 or more characters'; Severity = 'High'; Remediation = 'Set to 14 or more characters' }
+ @{ ControlID = 'CIS-1.1.5'; ControlName = 'Password must meet complexity requirements'; Expected = 'Enabled'; Severity = 'Critical'; Remediation = 'Enable password complexity requirements' }
+ )
+ foreach ($spec in $manualSpecs) {
$control = [PSCustomObject]@{
- ControlID = 'CIS-1.1.1'
- ControlName = 'Enforce password history'
+ ControlID = $spec.ControlID
+ ControlName = $spec.ControlName
Category = 'PasswordPolicy'
- Expected = '24 or more passwords'
- Actual = "$passwordHistory passwords"
- Status = if ([int]$passwordHistory -ge 24) { 'Pass' } else { 'Fail' }
- Severity = 'High'
- Remediation = 'Set to 24 or more passwords remembered'
+ Expected = $spec.Expected
+ Actual = 'Unable to evaluate — secedit export unavailable'
+ Status = 'Manual'
+ Severity = $spec.Severity
+ Remediation = $spec.Remediation
}
$results.Controls += $control
}
-
+ }
+ else {
+ # CIS 1.1.1 - Password History
+ $passwordHistory = Get-SecEditValue -Content $secpolContent -Setting "PasswordHistorySize"
+ $control = [PSCustomObject]@{
+ ControlID = 'CIS-1.1.1'
+ ControlName = 'Enforce password history'
+ Category = 'PasswordPolicy'
+ Expected = '24 or more passwords'
+ Actual = if ($null -ne $passwordHistory) { "$passwordHistory passwords" } else { 'Unable to evaluate — setting missing from secedit export' }
+ Status = if ($null -eq $passwordHistory) { 'Manual' } elseif ([int]$passwordHistory -ge 24) { 'Pass' } else { 'Fail' }
+ Severity = 'High'
+ Remediation = 'Set to 24 or more passwords remembered'
+ }
+ $results.Controls += $control
+
# CIS 1.1.2 - Maximum password age
$maxPasswordAge = Get-SecEditValue -Content $secpolContent -Setting "MaximumPasswordAge"
- if ($maxPasswordAge) {
- $control = [PSCustomObject]@{
- ControlID = 'CIS-1.1.2'
- ControlName = 'Maximum password age'
- Category = 'PasswordPolicy'
- Expected = '365 or fewer days (but not 0)'
- Actual = "$maxPasswordAge days"
- Status = if ([int]$maxPasswordAge -le 365 -and [int]$maxPasswordAge -gt 0) { 'Pass' } else { 'Fail' }
- Severity = 'High'
- Remediation = 'Set to 365 or fewer days'
- }
- $results.Controls += $control
+ $control = [PSCustomObject]@{
+ ControlID = 'CIS-1.1.2'
+ ControlName = 'Maximum password age'
+ Category = 'PasswordPolicy'
+ Expected = '365 or fewer days (but not 0)'
+ Actual = if ($null -ne $maxPasswordAge) { "$maxPasswordAge days" } else { 'Unable to evaluate — setting missing from secedit export' }
+ Status = if ($null -eq $maxPasswordAge) { 'Manual' } elseif ([int]$maxPasswordAge -le 365 -and [int]$maxPasswordAge -gt 0) { 'Pass' } else { 'Fail' }
+ Severity = 'High'
+ Remediation = 'Set to 365 or fewer days'
}
-
+ $results.Controls += $control
+
# CIS 1.1.3 - Minimum password age
$minPasswordAge = Get-SecEditValue -Content $secpolContent -Setting "MinimumPasswordAge"
- if ($minPasswordAge) {
- $control = [PSCustomObject]@{
- ControlID = 'CIS-1.1.3'
- ControlName = 'Minimum password age'
- Category = 'PasswordPolicy'
- Expected = '1 or more days'
- Actual = "$minPasswordAge days"
- Status = if ([int]$minPasswordAge -ge 1) { 'Pass' } else { 'Fail' }
- Severity = 'Medium'
- Remediation = 'Set to 1 or more days'
- }
- $results.Controls += $control
+ $control = [PSCustomObject]@{
+ ControlID = 'CIS-1.1.3'
+ ControlName = 'Minimum password age'
+ Category = 'PasswordPolicy'
+ Expected = '1 or more days'
+ Actual = if ($null -ne $minPasswordAge) { "$minPasswordAge days" } else { 'Unable to evaluate — setting missing from secedit export' }
+ Status = if ($null -eq $minPasswordAge) { 'Manual' } elseif ([int]$minPasswordAge -ge 1) { 'Pass' } else { 'Fail' }
+ Severity = 'Medium'
+ Remediation = 'Set to 1 or more days'
}
-
+ $results.Controls += $control
+
# CIS 1.1.4 - Minimum password length
$minPasswordLength = Get-SecEditValue -Content $secpolContent -Setting "MinimumPasswordLength"
- if ($minPasswordLength) {
- $control = [PSCustomObject]@{
- ControlID = 'CIS-1.1.4'
- ControlName = 'Minimum password length'
- Category = 'PasswordPolicy'
- Expected = '14 or more characters'
- Actual = "$minPasswordLength characters"
- Status = if ([int]$minPasswordLength -ge 14) { 'Pass' } else { 'Fail' }
- Severity = 'High'
- Remediation = 'Set to 14 or more characters'
- }
- $results.Controls += $control
+ $control = [PSCustomObject]@{
+ ControlID = 'CIS-1.1.4'
+ ControlName = 'Minimum password length'
+ Category = 'PasswordPolicy'
+ Expected = '14 or more characters'
+ Actual = if ($null -ne $minPasswordLength) { "$minPasswordLength characters" } else { 'Unable to evaluate — setting missing from secedit export' }
+ Status = if ($null -eq $minPasswordLength) { 'Manual' } elseif ([int]$minPasswordLength -ge 14) { 'Pass' } else { 'Fail' }
+ Severity = 'High'
+ Remediation = 'Set to 14 or more characters'
}
-
+ $results.Controls += $control
+
# CIS 1.1.5 - Password complexity
$passwordComplexity = Get-SecEditValue -Content $secpolContent -Setting "PasswordComplexity"
- if ($passwordComplexity) {
- $control = [PSCustomObject]@{
- ControlID = 'CIS-1.1.5'
- ControlName = 'Password must meet complexity requirements'
- Category = 'PasswordPolicy'
- Expected = 'Enabled'
- Actual = if ($passwordComplexity -eq '1') { 'Enabled' } else { 'Disabled' }
- Status = if ($passwordComplexity -eq '1') { 'Pass' } else { 'Fail' }
- Severity = 'Critical'
- Remediation = 'Enable password complexity requirements'
- }
- $results.Controls += $control
+ $control = [PSCustomObject]@{
+ ControlID = 'CIS-1.1.5'
+ ControlName = 'Password must meet complexity requirements'
+ Category = 'PasswordPolicy'
+ Expected = 'Enabled'
+ Actual = if ($null -eq $passwordComplexity) { 'Unable to evaluate — setting missing from secedit export' }
+ elseif ($passwordComplexity -eq '1') { 'Enabled' } else { 'Disabled' }
+ Status = if ($null -eq $passwordComplexity) { 'Manual' } elseif ($passwordComplexity -eq '1') { 'Pass' } else { 'Fail' }
+ Severity = 'Critical'
+ Remediation = 'Enable password complexity requirements'
}
-
- Remove-Item $tempFile -Force -ErrorAction SilentlyContinue
- }
- else {
- Write-Warning "Could not export security policy"
+ $results.Controls += $control
}
}
catch {
@@ -387,9 +420,31 @@ function Test-CISBenchmark {
Write-Host "`n[4/5] Testing Windows Firewall..." -ForegroundColor Cyan
try {
- $firewallProfiles = Get-NetFirewallProfile -ErrorAction SilentlyContinue
-
- foreach ($profile in $firewallProfiles) {
+ # Gate on Get-Command: CommandNotFoundException ignores
+ # -ErrorAction SilentlyContinue; an empty result must not silently
+ # produce zero CIS-9.x controls.
+ $firewallCmdletAvailable = $null -ne (Get-Command Get-NetFirewallProfile -ErrorAction SilentlyContinue)
+ $firewallProfiles = $null
+ if ($firewallCmdletAvailable) {
+ try { $firewallProfiles = @(Get-NetFirewallProfile -ErrorAction Stop) } catch { $firewallProfiles = $null }
+ }
+
+ if (-not $firewallCmdletAvailable -or @($firewallProfiles).Count -eq 0) {
+ Write-Warning "Unable to retrieve firewall profiles; firewall controls require manual review"
+ $control = [PSCustomObject]@{
+ ControlID = 'CIS-9.1.1'
+ ControlName = 'Windows Firewall: Firewall state'
+ Category = 'WindowsFirewall'
+ Expected = 'On'
+ Actual = 'Unable to evaluate — Get-NetFirewallProfile unavailable or returned no profiles'
+ Status = 'Manual'
+ Severity = 'Critical'
+ Remediation = 'Verify Windows Firewall is enabled for all profiles'
+ }
+ $results.Controls += $control
+ }
+ else {
+ foreach ($profile in $firewallProfiles) {
# CIS 9.1.1 - Domain Profile Firewall State
$control = [PSCustomObject]@{
ControlID = "CIS-9.$($profile.Name).1"
@@ -415,6 +470,7 @@ function Test-CISBenchmark {
Remediation = "Set inbound connections to Block for $($profile.Name)"
}
$results.Controls += $control
+ }
}
}
catch {
diff --git a/Compliance/Test-NISTCompliance.ps1 b/Compliance/Test-NISTCompliance.ps1
index 7d60c0c..a776a99 100644
--- a/Compliance/Test-NISTCompliance.ps1
+++ b/Compliance/Test-NISTCompliance.ps1
@@ -30,6 +30,10 @@ function Test-NISTCompliance {
)
begin {
+ if ($Revision -ne 5) {
+ Write-Warning "Revision $Revision requested; only Revision 5 checks are currently implemented"
+ $Revision = 5
+ }
Write-Host "=== NIST 800-53 COMPLIANCE TEST ===" -ForegroundColor Cyan
Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow
Write-Host "Revision: NIST 800-53 Rev $Revision" -ForegroundColor Yellow
@@ -119,34 +123,47 @@ function Test-NISTCompliance {
$results.Controls += $control
# AC-7: Unsuccessful Logon Attempts
- $regTest = Test-RegistryValue -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' `
- -Name 'MaxDevicePasswordFailedAttempts' -ExpectedValue 5
-
+ # Read the real account lockout threshold via the module helper
+ # (NetUserModalsGet/secedit); the old MaxDevicePasswordFailedAttempts
+ # registry check measured a different, device-specific policy.
+ $passwordPolicy = Get-LocalPasswordPolicy
+ $lockoutThreshold = $passwordPolicy.LockoutThreshold
+
$control = [PSCustomObject]@{
ControlID = 'AC-7'
ControlName = 'Unsuccessful Logon Attempts'
ControlFamily = 'AccessControl'
Description = 'System should lock after failed login attempts'
- Expected = '5 or fewer attempts'
- Actual = if ($regTest.ActualValue) { "$($regTest.ActualValue) attempts" } else { "Not configured" }
- Status = if ($regTest.Compliant) { 'Compliant' } else { 'NonCompliant' }
+ Expected = 'Account lockout threshold between 1 and 10 attempts'
+ Actual = if ($null -eq $lockoutThreshold) { 'Unable to determine' }
+ elseif ($lockoutThreshold -eq 0) { 'Lockout disabled (0)' }
+ else { "$lockoutThreshold attempts" }
+ Status = if ($null -eq $lockoutThreshold) { 'NotApplicable' }
+ elseif ($lockoutThreshold -ge 1 -and $lockoutThreshold -le 10) { 'Compliant' }
+ else { 'NonCompliant' }
Impact = 'High'
- Remediation = 'Configure account lockout after 5 failed attempts'
+ Remediation = 'Configure account lockout threshold between 1 and 10 failed attempts'
}
$results.Controls += $control
# AC-11: Session Lock
$regTest = Test-RegistryValue -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' `
-Name 'InactivityTimeoutSecs' -ExpectedValue 900
+ $inactivitySecs = $regTest.ActualValue
+ $inactivityIsNumeric = ($null -ne $inactivitySecs) -and ("$inactivitySecs" -match '^\d+$')
+ # 0 means the session never locks -> NonCompliant; valid range is 1..900
+ $inactivityValid = $inactivityIsNumeric -and ([int]$inactivitySecs -gt 0) -and ([int]$inactivitySecs -le 900)
$control = [PSCustomObject]@{
ControlID = 'AC-11'
ControlName = 'Session Lock'
ControlFamily = 'AccessControl'
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 ($null -ne $regTest.ActualValue -and $regTest.ActualValue -le 900)) { 'Compliant' } else { 'NonCompliant' }
+ Expected = '15 minutes (900 seconds) or less, and not disabled (0)'
+ Actual = if (-not $inactivityIsNumeric) { "Not configured" }
+ elseif ([int]$inactivitySecs -eq 0) { "Never locks (0)" }
+ else { "$([math]::Round([int]$inactivitySecs/60)) minutes" }
+ Status = if ($inactivityValid) { 'Compliant' } else { 'NonCompliant' }
Impact = 'Medium'
Remediation = 'Configure screen lock timeout to 15 minutes or less'
}
@@ -204,7 +221,11 @@ function Test-NISTCompliance {
$results.Controls += $control
# AU-3: Content of Audit Records
- $securityLog = Get-WinEvent -ListLog Security -ErrorAction SilentlyContinue
+ $winEventAvailable = $null -ne (Get-Command Get-WinEvent -ErrorAction SilentlyContinue)
+ $securityLog = $null
+ if ($winEventAvailable) {
+ try { $securityLog = Get-WinEvent -ListLog Security -ErrorAction Stop } catch { $securityLog = $null }
+ }
$eventLogSize = if ($securityLog) { $securityLog.MaximumSizeInBytes } else { 0 }
$control = [PSCustomObject]@{
@@ -213,8 +234,10 @@ function Test-NISTCompliance {
ControlFamily = 'AuditAccountability'
Description = 'Audit records must contain sufficient detail'
Expected = 'Security log size >= 100MB'
- Actual = "$([math]::Round($eventLogSize/1MB)) MB"
- Status = if ($eventLogSize -ge 100MB) { 'Compliant' } else { 'NonCompliant' }
+ Actual = if (-not $winEventAvailable) { 'Unable to evaluate — Get-WinEvent unavailable' }
+ else { "$([math]::Round($eventLogSize/1MB)) MB" }
+ Status = if (-not $winEventAvailable) { 'NotApplicable' }
+ elseif ($eventLogSize -ge 100MB) { 'Compliant' } else { 'NonCompliant' }
Impact = 'Medium'
Remediation = 'Increase Security event log size to at least 100MB'
}
@@ -223,22 +246,37 @@ function Test-NISTCompliance {
# AU-9: Protection of Audit Information
$logPath = "C:\Windows\System32\winevt\Logs\Security.evtx"
if (Test-Path $logPath) {
- $acl = Get-Acl $logPath -ErrorAction SilentlyContinue
- $protected = @()
- if ($acl) {
- $protected = @($acl.Access | Where-Object { ((Test-IdentityReferenceIsSid -IdentityReference $_.IdentityReference -Sid 'S-1-5-32-545') -or (Test-IdentityReferenceIsSid -IdentityReference $_.IdentityReference -Sid 'S-1-5-11') -or (Test-IdentityReferenceIsSid -IdentityReference $_.IdentityReference -Sid 'S-1-1-0')) -and $_.FileSystemRights -match "FullControl|Modify|Write" })
+ $acl = $null
+ try { $acl = Get-Acl $logPath -ErrorAction Stop } catch { $acl = $null }
+
+ if ($null -eq $acl) {
+ # No ACL data -> honest unknown; never claim Compliant without data
+ $control = [PSCustomObject]@{
+ ControlID = 'AU-9'
+ ControlName = 'Protection of Audit Information'
+ ControlFamily = 'AuditAccountability'
+ Description = 'Audit logs must be protected from unauthorized access'
+ Expected = 'Security log protected from normal users'
+ Actual = 'Unable to read ACL'
+ Status = 'NotApplicable'
+ Impact = 'High'
+ Remediation = 'Restrict Security event log access to administrators only'
+ }
}
-
- $control = [PSCustomObject]@{
- ControlID = 'AU-9'
- ControlName = 'Protection of Audit Information'
- ControlFamily = 'AuditAccountability'
- Description = 'Audit logs must be protected from unauthorized access'
- Expected = 'Security log protected from normal users'
- Actual = if ($protected.Count -gt 0) { "Weak permissions detected" } else { "Properly protected" }
- Status = if ($protected.Count -eq 0) { 'Compliant' } else { 'NonCompliant' }
- Impact = 'High'
- Remediation = 'Restrict Security event log access to administrators only'
+ else {
+ $protected = @($acl.Access | Where-Object { ((Test-IdentityReferenceIsSid -IdentityReference $_.IdentityReference -Sid 'S-1-5-32-545') -or (Test-IdentityReferenceIsSid -IdentityReference $_.IdentityReference -Sid 'S-1-5-11') -or (Test-IdentityReferenceIsSid -IdentityReference $_.IdentityReference -Sid 'S-1-1-0')) -and $_.FileSystemRights -match "FullControl|Modify|Write" })
+
+ $control = [PSCustomObject]@{
+ ControlID = 'AU-9'
+ ControlName = 'Protection of Audit Information'
+ ControlFamily = 'AuditAccountability'
+ Description = 'Audit logs must be protected from unauthorized access'
+ Expected = 'Security log protected from normal users'
+ Actual = if ($protected.Count -gt 0) { "Weak permissions detected" } else { "Properly protected" }
+ Status = if ($protected.Count -eq 0) { 'Compliant' } else { 'NonCompliant' }
+ Impact = 'High'
+ Remediation = 'Restrict Security event log access to administrators only'
+ }
}
$results.Controls += $control
}
@@ -342,7 +380,13 @@ function Test-NISTCompliance {
try {
# SC-7: Boundary Protection - FIX: Wrap in @()
- $firewallProfiles = Get-NetFirewallProfile -ErrorAction SilentlyContinue
+ # CommandNotFoundException ignores -ErrorAction SilentlyContinue, so
+ # gate on Get-Command first; a missing cmdlet must not drop the control.
+ $firewallCmdletAvailable = $null -ne (Get-Command Get-NetFirewallProfile -ErrorAction SilentlyContinue)
+ $firewallProfiles = $null
+ if ($firewallCmdletAvailable) {
+ try { $firewallProfiles = Get-NetFirewallProfile -ErrorAction Stop } catch { $firewallProfiles = $null }
+ }
$disabledFirewalls = @($firewallProfiles | Where-Object { $null -ne $_ -and -not $_.Enabled })
$allFirewallsEnabled = ($null -ne $firewallProfiles) -and ($disabledFirewalls.Count -eq 0)
@@ -352,9 +396,11 @@ function Test-NISTCompliance {
ControlFamily = 'SystemProtection'
Description = 'Firewall must protect system boundaries'
Expected = 'All firewall profiles enabled'
- Actual = if ($null -eq $firewallProfiles) { "Unable to retrieve firewall profiles" }
+ Actual = if (-not $firewallCmdletAvailable) { 'Unable to evaluate — Get-NetFirewallProfile unavailable' }
+ elseif ($null -eq $firewallProfiles) { "Unable to retrieve firewall profiles" }
elseif ($allFirewallsEnabled) { "All enabled" } else { "Some disabled" }
- Status = if ($allFirewallsEnabled) { 'Compliant' } else { 'NonCompliant' }
+ Status = if (-not $firewallCmdletAvailable) { 'NotApplicable' }
+ elseif ($allFirewallsEnabled) { 'Compliant' } else { 'NonCompliant' }
Impact = 'Critical'
Remediation = 'Enable Windows Firewall for all profiles'
}
@@ -378,7 +424,14 @@ function Test-NISTCompliance {
$results.Controls += $control
# SC-28: Protection of Information at Rest
- $bitlockerStatus = Get-BitLockerVolume -MountPoint "C:" -ErrorAction SilentlyContinue
+ # Gate on Get-Command: CommandNotFoundException ignores
+ # -ErrorAction SilentlyContinue and would drop this control via the
+ # family-level catch.
+ $bitlockerAvailable = $null -ne (Get-Command Get-BitLockerVolume -ErrorAction SilentlyContinue)
+ $bitlockerStatus = $null
+ if ($bitlockerAvailable) {
+ try { $bitlockerStatus = Get-BitLockerVolume -MountPoint "C:" -ErrorAction Stop } catch { $bitlockerStatus = $null }
+ }
$bitlockerEnabled = ($null -ne $bitlockerStatus) -and ($bitlockerStatus.ProtectionStatus -eq 'On')
$control = [PSCustomObject]@{
@@ -387,8 +440,10 @@ function Test-NISTCompliance {
ControlFamily = 'SystemProtection'
Description = 'Data at rest should be encrypted'
Expected = 'BitLocker enabled'
- Actual = if ($bitlockerEnabled) { "Enabled" } else { "Disabled" }
- Status = if ($bitlockerEnabled) { 'Compliant' } else { 'NonCompliant' }
+ Actual = if (-not $bitlockerAvailable) { 'Unable to evaluate — Get-BitLockerVolume unavailable' }
+ elseif ($bitlockerEnabled) { "Enabled" } else { "Disabled" }
+ Status = if (-not $bitlockerAvailable) { 'NotApplicable' }
+ elseif ($bitlockerEnabled) { 'Compliant' } else { 'NonCompliant' }
Impact = 'High'
Remediation = 'Enable BitLocker encryption'
}
@@ -405,7 +460,14 @@ function Test-NISTCompliance {
try {
# CM-6: Configuration Settings
- $defenderStatus = Get-MpComputerStatus -ErrorAction SilentlyContinue
+ # Gate on Get-Command: CommandNotFoundException ignores
+ # -ErrorAction SilentlyContinue and would drop CM-6/7/8 via the
+ # family-level catch.
+ $mpStatusAvailable = $null -ne (Get-Command Get-MpComputerStatus -ErrorAction SilentlyContinue)
+ $defenderStatus = $null
+ if ($mpStatusAvailable) {
+ try { $defenderStatus = Get-MpComputerStatus -ErrorAction Stop } catch { $defenderStatus = $null }
+ }
$defenderEnabled = ($null -ne $defenderStatus) -and $defenderStatus.AntivirusEnabled
$control = [PSCustomObject]@{
@@ -414,17 +476,25 @@ function Test-NISTCompliance {
ControlFamily = 'ConfigurationManagement'
Description = 'Security configuration settings must be established'
Expected = 'Windows Defender enabled'
- Actual = if ($defenderEnabled) { "Enabled" } else { "Disabled" }
- Status = if ($defenderEnabled) { 'Compliant' } else { 'NonCompliant' }
+ Actual = if (-not $mpStatusAvailable) { 'Unable to evaluate — Get-MpComputerStatus unavailable' }
+ elseif ($defenderEnabled) { "Enabled" } else { "Disabled" }
+ Status = if (-not $mpStatusAvailable) { 'NotApplicable' }
+ elseif ($defenderEnabled) { 'Compliant' } else { 'NonCompliant' }
Impact = 'Critical'
Remediation = 'Enable Windows Defender antivirus'
}
$results.Controls += $control
# CM-7: Least Functionality - FIX: Wrap in @()
- $allServices = Get-Service -ErrorAction SilentlyContinue
+ # Get-Service is Windows/Linux-only; gate on Get-Command so a
+ # missing cmdlet cannot drop CM-7/CM-8 via the family catch.
+ $serviceCmdletAvailable = $null -ne (Get-Command Get-Service -ErrorAction SilentlyContinue)
+ $allServices = $null
+ if ($serviceCmdletAvailable) {
+ try { $allServices = Get-Service -ErrorAction Stop } catch { $allServices = $null }
+ }
$unnecessaryServices = @($allServices | Where-Object {
- $_.Name -in @('TlntSvr', 'SNMP', 'SSDPSRV') -and $_.Status -eq 'Running'
+ $null -ne $_ -and $_.Name -in @('TlntSvr', 'SNMP', 'SSDPSRV') -and $_.Status -eq 'Running'
})
$control = [PSCustomObject]@{
@@ -433,8 +503,10 @@ function Test-NISTCompliance {
ControlFamily = 'ConfigurationManagement'
Description = 'Unnecessary services should be disabled'
Expected = 'No unnecessary services running'
- Actual = if ($unnecessaryServices.Count -eq 0) { "Clean" } else { "$($unnecessaryServices.Count) unnecessary services" }
- Status = if ($unnecessaryServices.Count -eq 0) { 'Compliant' } else { 'NonCompliant' }
+ Actual = if (-not $serviceCmdletAvailable) { 'Unable to evaluate — Get-Service unavailable' }
+ elseif ($unnecessaryServices.Count -eq 0) { "Clean" } else { "$($unnecessaryServices.Count) unnecessary services" }
+ Status = if (-not $serviceCmdletAvailable) { 'NotApplicable' }
+ elseif ($unnecessaryServices.Count -eq 0) { 'Compliant' } else { 'NonCompliant' }
Impact = 'Medium'
Remediation = 'Disable unnecessary services (Telnet, SNMP, SSDP)'
}
diff --git a/Compliance/Test-PCI-DSS.ps1 b/Compliance/Test-PCI-DSS.ps1
index ee44355..9dd2fb3 100644
--- a/Compliance/Test-PCI-DSS.ps1
+++ b/Compliance/Test-PCI-DSS.ps1
@@ -28,6 +28,10 @@ function Test-PCI-DSS {
)
begin {
+ if ($Version -ne '4.0') {
+ Write-Warning "Version $Version requested; only 4.0 checks are currently implemented"
+ $Version = '4.0'
+ }
Write-Host "=== PCI-DSS COMPLIANCE TEST ===" -ForegroundColor Cyan
Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow
Write-Host "PCI-DSS Version: $Version" -ForegroundColor Yellow
@@ -92,7 +96,14 @@ function Test-PCI-DSS {
try {
# Req 1.2: Network security controls (firewalls)
- $firewallProfiles = Get-NetFirewallProfile -ErrorAction SilentlyContinue
+ # Gate on Get-Command: CommandNotFoundException ignores
+ # -ErrorAction SilentlyContinue and would drop all network
+ # requirements via the catch block below.
+ $firewallCmdletAvailable = $null -ne (Get-Command Get-NetFirewallProfile -ErrorAction SilentlyContinue)
+ $firewallProfiles = $null
+ if ($firewallCmdletAvailable) {
+ try { $firewallProfiles = Get-NetFirewallProfile -ErrorAction Stop } catch { $firewallProfiles = $null }
+ }
$allFirewallsEnabled = ($null -ne $firewallProfiles) -and (@($firewallProfiles | Where-Object { $null -ne $_ -and -not $_.Enabled }).Count -eq 0)
$req = [PSCustomObject]@{
@@ -101,9 +112,11 @@ function Test-PCI-DSS {
Category = 'Network'
Description = 'Firewalls must be enabled and properly configured'
Expected = 'All firewall profiles enabled'
- Actual = if ($null -eq $firewallProfiles) { "Unable to retrieve firewall profiles" }
+ Actual = if (-not $firewallCmdletAvailable) { 'Unable to evaluate — Get-NetFirewallProfile unavailable' }
+ elseif ($null -eq $firewallProfiles) { "Unable to retrieve firewall profiles" }
elseif ($allFirewallsEnabled) { "All enabled" } else { "Some disabled" }
- Status = if ($allFirewallsEnabled) { 'InPlace' } else { 'NotInPlace' }
+ Status = if (-not $firewallCmdletAvailable) { 'NotApplicable' }
+ elseif ($allFirewallsEnabled) { 'InPlace' } else { 'NotInPlace' }
Priority = 'Critical'
Remediation = 'Enable all Windows Firewall profiles (Domain, Private, Public)'
}
@@ -118,9 +131,11 @@ function Test-PCI-DSS {
Category = 'Network'
Description = 'Inbound traffic should be denied by default'
Expected = 'Default action: Block'
- Actual = if ($null -eq $firewallProfiles) { "Unable to retrieve firewall profiles" }
+ Actual = if (-not $firewallCmdletAvailable) { 'Unable to evaluate — Get-NetFirewallProfile unavailable' }
+ elseif ($null -eq $firewallProfiles) { "Unable to retrieve firewall profiles" }
elseif ($defaultInboundBlock.Count -eq 0) { "All blocked" } else { "$($defaultInboundBlock.Count) profiles allow" }
- Status = if (($null -ne $firewallProfiles) -and $defaultInboundBlock.Count -eq 0) { 'InPlace' } else { 'NotInPlace' }
+ Status = if (-not $firewallCmdletAvailable) { 'NotApplicable' }
+ elseif (($null -ne $firewallProfiles) -and $defaultInboundBlock.Count -eq 0) { 'InPlace' } else { 'NotInPlace' }
Priority = 'High'
Remediation = 'Set default inbound action to Block for all profiles'
}
@@ -135,8 +150,10 @@ function Test-PCI-DSS {
Category = 'Network'
Description = 'Public network profile must be restrictive'
Expected = 'Public profile enabled and blocking inbound'
- Actual = if ($publicProfile) { "Enabled: $($publicProfile.Enabled), Inbound: $($publicProfile.DefaultInboundAction)" } else { "Public profile not found" }
- Status = if ($publicProfile -and $publicProfile.Enabled -and $publicProfile.DefaultInboundAction -eq 'Block') { 'InPlace' } else { 'NotInPlace' }
+ Actual = if (-not $firewallCmdletAvailable) { 'Unable to evaluate — Get-NetFirewallProfile unavailable' }
+ elseif ($publicProfile) { "Enabled: $($publicProfile.Enabled), Inbound: $($publicProfile.DefaultInboundAction)" } else { "Public profile not found" }
+ Status = if (-not $firewallCmdletAvailable) { 'NotApplicable' }
+ elseif ($publicProfile -and $publicProfile.Enabled -and $publicProfile.DefaultInboundAction -eq 'Block') { 'InPlace' } else { 'NotInPlace' }
Priority = 'High'
Remediation = 'Enable Public profile with default inbound block'
}
@@ -167,7 +184,13 @@ function Test-PCI-DSS {
$results.Requirements += $req
# Req 3.5: Primary account number (PAN) protection
- $bitlockerStatus = Get-BitLockerVolume -MountPoint "C:" -ErrorAction SilentlyContinue
+ # Gate on Get-Command: CommandNotFoundException ignores
+ # -ErrorAction SilentlyContinue and would drop this requirement.
+ $bitlockerAvailable = $null -ne (Get-Command Get-BitLockerVolume -ErrorAction SilentlyContinue)
+ $bitlockerStatus = $null
+ if ($bitlockerAvailable) {
+ try { $bitlockerStatus = Get-BitLockerVolume -MountPoint "C:" -ErrorAction Stop } catch { $bitlockerStatus = $null }
+ }
$bitlockerEnabled = ($null -ne $bitlockerStatus) -and ($bitlockerStatus.ProtectionStatus -eq 'On')
$req = [PSCustomObject]@{
@@ -176,8 +199,10 @@ function Test-PCI-DSS {
Category = 'Data'
Description = 'PAN must be rendered unreadable (encryption)'
Expected = 'Disk encryption enabled (BitLocker)'
- Actual = if ($bitlockerEnabled) { "Enabled" } else { "Disabled" }
- Status = if ($bitlockerEnabled) { 'InPlace' } else { 'NotInPlace' }
+ Actual = if (-not $bitlockerAvailable) { 'Unable to evaluate — Get-BitLockerVolume unavailable' }
+ elseif ($bitlockerEnabled) { "Enabled" } else { "Disabled" }
+ Status = if (-not $bitlockerAvailable) { 'NotApplicable' }
+ elseif ($bitlockerEnabled) { 'InPlace' } else { 'NotInPlace' }
Priority = 'Critical'
Remediation = 'Enable BitLocker or third-party disk encryption'
}
@@ -337,7 +362,11 @@ function Test-PCI-DSS {
$results.Requirements += $req
# Req 10.5: Protect audit trails
- $securityLog = Get-WinEvent -ListLog Security -ErrorAction SilentlyContinue
+ $winEventAvailable = $null -ne (Get-Command Get-WinEvent -ErrorAction SilentlyContinue)
+ $securityLog = $null
+ if ($winEventAvailable) {
+ try { $securityLog = Get-WinEvent -ListLog Security -ErrorAction Stop } catch { $securityLog = $null }
+ }
$eventLogSize = if ($securityLog) { $securityLog.MaximumSizeInBytes } else { 0 }
$req = [PSCustomObject]@{
@@ -346,15 +375,23 @@ function Test-PCI-DSS {
Category = 'Monitoring'
Description = 'Audit trails must be secured and retained'
Expected = 'Security log >= 100MB'
- Actual = "$([math]::Round($eventLogSize/1MB)) MB"
- Status = if ($eventLogSize -ge 100MB) { 'InPlace' } else { 'NotInPlace' }
+ Actual = if (-not $winEventAvailable) { 'Unable to evaluate — Get-WinEvent unavailable' }
+ else { "$([math]::Round($eventLogSize/1MB)) MB" }
+ Status = if (-not $winEventAvailable) { 'NotApplicable' }
+ elseif ($eventLogSize -ge 100MB) { 'InPlace' } else { 'NotInPlace' }
Priority = 'High'
Remediation = 'Increase Security log size to at least 100MB'
}
$results.Requirements += $req
# Req 10.7: Time synchronization
- $w32timeService = Get-Service -Name W32Time -ErrorAction SilentlyContinue
+ # Get-Service is Windows/Linux-only; gate on Get-Command so a
+ # missing cmdlet cannot drop this requirement via the catch below.
+ $serviceCmdletAvailable = $null -ne (Get-Command Get-Service -ErrorAction SilentlyContinue)
+ $w32timeService = $null
+ if ($serviceCmdletAvailable) {
+ try { $w32timeService = Get-Service -Name W32Time -ErrorAction Stop } catch { $w32timeService = $null }
+ }
$req = [PSCustomObject]@{
RequirementID = '10.7.1'
@@ -362,8 +399,10 @@ function Test-PCI-DSS {
Category = 'Monitoring'
Description = 'System clocks must be synchronized'
Expected = 'Windows Time service running'
- Actual = if ($w32timeService) { $w32timeService.Status } else { "Not found" }
- Status = if ($w32timeService -and $w32timeService.Status -eq 'Running') { 'InPlace' } else { 'NotInPlace' }
+ Actual = if (-not $serviceCmdletAvailable) { 'Unable to evaluate — Get-Service unavailable' }
+ elseif ($w32timeService) { $w32timeService.Status } else { "Not found" }
+ Status = if (-not $serviceCmdletAvailable) { 'NotApplicable' }
+ elseif ($w32timeService -and $w32timeService.Status -eq 'Running') { 'InPlace' } else { 'NotInPlace' }
Priority = 'Medium'
Remediation = 'Ensure Windows Time service is running and configured'
}
@@ -380,7 +419,13 @@ function Test-PCI-DSS {
try {
# Req 11.3: Vulnerability scanning
- $defenderStatus = Get-MpComputerStatus -ErrorAction SilentlyContinue
+ # Gate on Get-Command: CommandNotFoundException ignores
+ # -ErrorAction SilentlyContinue and would drop this requirement.
+ $mpStatusAvailable = $null -ne (Get-Command Get-MpComputerStatus -ErrorAction SilentlyContinue)
+ $defenderStatus = $null
+ if ($mpStatusAvailable) {
+ try { $defenderStatus = Get-MpComputerStatus -ErrorAction Stop } catch { $defenderStatus = $null }
+ }
$defenderEnabled = ($null -ne $defenderStatus) -and $defenderStatus.AntivirusEnabled
$req = [PSCustomObject]@{
@@ -389,8 +434,10 @@ function Test-PCI-DSS {
Category = 'Testing'
Description = 'Vulnerability scans must be performed'
Expected = 'Antivirus enabled'
- Actual = if ($defenderEnabled) { "Windows Defender enabled" } else { "Disabled" }
- Status = if ($defenderEnabled) { 'InPlace' } else { 'NotInPlace' }
+ Actual = if (-not $mpStatusAvailable) { 'Unable to evaluate — Get-MpComputerStatus unavailable' }
+ elseif ($defenderEnabled) { "Windows Defender enabled" } else { "Disabled" }
+ Status = if (-not $mpStatusAvailable) { 'NotApplicable' }
+ elseif ($defenderEnabled) { 'InPlace' } else { 'NotInPlace' }
Priority = 'Critical'
Remediation = 'Enable Windows Defender or approved antivirus'
}
diff --git a/Core/Get-SecurityBaseline.ps1 b/Core/Get-SecurityBaseline.ps1
index 763a0be..f5ae429 100644
--- a/Core/Get-SecurityBaseline.ps1
+++ b/Core/Get-SecurityBaseline.ps1
@@ -6,7 +6,10 @@ function Get-SecurityBaseline {
Retrieves comprehensive security configuration including Windows Defender,
Firewall, UAC, BitLocker, and Windows Update status
.PARAMETER ComputerName
- Name of the computer to check (default: local computer)
+ Name of the computer to check (default: local computer).
+ NOTE: all checks run against the LOCAL machine; this parameter currently
+ only labels the report and exported file name. Remote querying is not
+ implemented - a warning is emitted when a non-local name is supplied.
.PARAMETER ExportPath
Path to export the results as JSON
.EXAMPLE
@@ -27,6 +30,15 @@ function Get-SecurityBaseline {
begin {
Write-Verbose "Starting security baseline check for $ComputerName"
+
+ # No remoting is implemented: every check below queries the LOCAL
+ # machine. When a non-local name is supplied, say so honestly instead
+ # of silently labeling local results with a remote computer's name.
+ $localComputerNames = @('localhost', '.', '127.0.0.1', [Environment]::MachineName)
+ if (-not [string]::IsNullOrWhiteSpace($ComputerName) -and $localComputerNames -notcontains $ComputerName) {
+ Write-Warning "Get-SecurityBaseline does not query remote machines: all checks run against the LOCAL computer. -ComputerName '$ComputerName' only labels the report and export file name."
+ }
+
$results = [PSCustomObject]@{
ComputerName = $ComputerName
ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
@@ -103,8 +115,9 @@ function Get-SecurityBaseline {
# Check BitLocker Status
Write-Verbose "Checking BitLocker status..."
try {
- $bitlockerVolumes = Get-BitLockerVolume -ErrorAction Stop
+ $bitlockerVolumes = @(Get-BitLockerVolume -ErrorAction Stop)
$results.BitLocker = @()
+ $protectedVolumeCount = 0
foreach ($volume in $bitlockerVolumes) {
$results.BitLocker += [PSCustomObject]@{
MountPoint = $volume.MountPoint
@@ -113,7 +126,15 @@ function Get-SecurityBaseline {
EncryptionPercentage = $volume.EncryptionPercentage
EncryptionMethod = if ($volume.EncryptionMethod) { $volume.EncryptionMethod.ToString() } else { "None" }
}
- if ($volume.ProtectionStatus -eq "On") { $results.SecurityScore += 10 }
+ if ($volume.ProtectionStatus -eq "On") { $protectedVolumeCount++ }
+ }
+ # Scoring rule: BitLocker contributes a fixed 10-point budget,
+ # awarded proportionally to the share of protected volumes
+ # (all protected = 10, half = 5, none = 0). Awarding points per
+ # volume made the contribution depend on how many volumes a
+ # machine happens to have instead of how well it is protected.
+ if ($bitlockerVolumes.Count -gt 0) {
+ $results.SecurityScore += [int][Math]::Round(10 * $protectedVolumeCount / $bitlockerVolumes.Count)
}
}
catch {
@@ -193,7 +214,7 @@ function Get-SecurityBaseline {
if (-not (Test-Path $ExportPath)) {
New-Item -Path $ExportPath -ItemType Directory -Force | Out-Null
}
- $exportFile = Join-Path -Path $ExportPath -ChildPath "SecurityBaseline_$ComputerName_$(Get-Date -Format 'yyyyMMdd_HHmmss').json"
+ $exportFile = Join-Path -Path $ExportPath -ChildPath "SecurityBaseline_${ComputerName}_$(Get-Date -Format 'yyyyMMdd_HHmmss').json"
$results | ConvertTo-Json -Depth 5 | Out-File -FilePath $exportFile -Encoding UTF8
Write-Verbose "Results exported to: $exportFile"
}
diff --git a/Core/Test-SystemIntegrity.ps1 b/Core/Test-SystemIntegrity.ps1
index bda31f9..fd4f67c 100644
--- a/Core/Test-SystemIntegrity.ps1
+++ b/Core/Test-SystemIntegrity.ps1
@@ -52,9 +52,11 @@ function Test-SystemIntegrity {
$sfcOutput = & sfc /scannow 2>&1 | Out-String
$sfcExitCode = $LASTEXITCODE
- # SFC output text is fully localized; the exit code and the CBS.log
- # '[SR]'/'Cannot repair' tokens (written in English by the SFC engine
- # regardless of UI language) are the locale-invariant sources
+ # SFC output text is fully localized, so it is NEVER used for the
+ # verdict; the exit code and the CBS.log '[SR]'/'Cannot repair'
+ # tokens (written in English by the SFC engine regardless of UI
+ # language), filtered to the current scan window, are the only
+ # locale-invariant sources
$cbsLogPath = "$env:windir\Logs\CBS\CBS.log"
$cbsLogAvailable = Test-Path $cbsLogPath
$cannotRepairLines = @()
@@ -66,42 +68,40 @@ function Test-SystemIntegrity {
$cannotRepairLines = @($cbsTailFilter.Lines | Where-Object { $_ -match '\[SR\]' -and $_ -match 'Cannot repair' })
}
+ # Localized SFC console text as a verbose hint only - never a verdict input
+ if ($sfcOutput -match 'Windows Resource Protection') {
+ $sfcHint = @($sfcOutput -split '\r?\n' | Where-Object { $_ -match 'Windows Resource Protection' } | Select-Object -First 1)
+ if ($sfcHint.Count -gt 0) { Write-Verbose "SFC output hint (localized, informational only): $($sfcHint[0].Trim())" }
+ }
+
if ($sfcExitCode -ne 0) {
+ # Covers the 'could not perform the requested operation' case -
+ # SFC exits non-zero there, no text matching needed
$results.SFCResult = "SFC could not complete scan - may need to run in Safe Mode"
Write-Warning "SFC could not complete the scan (exit code $sfcExitCode)"
}
- elseif ($cannotRepairLines.Count -gt 0 -or
- (-not $cbsLogAvailable -and $sfcOutput -match "Windows Resource Protection found corrupt files")) {
+ elseif ($cannotRepairLines.Count -gt 0) {
$results.SFCResult = "Corrupt files found"
- if (-not $cbsTimestampsParseable -and $cannotRepairLines.Count -gt 0) {
+ if (-not $cbsTimestampsParseable) {
$results.SFCResult = "Corrupt files found (possible stale CBS.log entries)"
}
- if ($cannotRepairLines.Count -gt 0) {
- $results.CorruptedFiles = $cannotRepairLines
- }
- elseif ($cbsLogAvailable) {
- $cbsLog = Get-Content $cbsLogPath -Tail 100 -ErrorAction SilentlyContinue |
- Where-Object { $_ -match "corrupt" -or $_ -match "repaired" }
- if ($cbsLog) {
- $results.CorruptedFiles = $cbsLog
- }
- }
+ $results.CorruptedFiles = $cannotRepairLines
if ($RepairFiles) {
Write-Host "Attempting to repair corrupt files..." -ForegroundColor Yellow
$results.RepairAttempted = $true
}
}
- elseif ($cbsLogAvailable -or $sfcOutput -match "Windows Resource Protection did not find any integrity violations") {
+ elseif ($cbsLogAvailable -and $cbsTimestampsParseable) {
+ # Exit code 0 and the current-scan CBS.log window was actually
+ # examined (timestamps parsed) with no 'Cannot repair' markers
$results.SFCResult = "No integrity violations found"
Write-Host "SFC: No integrity violations found" -ForegroundColor Green
}
- elseif ($sfcOutput -match "Windows Resource Protection could not perform") {
- $results.SFCResult = "SFC could not complete scan - may need to run in Safe Mode"
- Write-Warning "SFC could not complete the scan"
- }
else {
+ # Inconclusive: CBS.log missing or its timestamps unparseable -
+ # never report 'healthy' from a parse miss
$results.SFCResult = "Scan completed - check CBS.log for details"
}
@@ -114,9 +114,11 @@ function Test-SystemIntegrity {
$dismCheckExitCode = $LASTEXITCODE
# DISM output text is fully localized and CheckHealth returns 0 for
- # both 'healthy' and 'repairable', so the exit code alone cannot
- # separate those; servicing-stack CBS.log markers ('[SR]'/'Cannot
- # repair', component-store corruption) are written in English
+ # both 'healthy' and 'repairable', so neither the output text nor
+ # the exit code alone can separate those; servicing-stack CBS.log
+ # markers (component-store corruption, written in English by the
+ # engine), filtered to the current scan window, are the only
+ # locale-invariant source. English DISM text is never matched.
$storeCorruptionLines = @()
$dismTimestampsParseable = $false
if ($cbsLogAvailable) {
@@ -126,7 +128,13 @@ function Test-SystemIntegrity {
$storeCorruptionLines = @($dismTailFilter.Lines | Where-Object { $_ -match '(?i)component store' -and $_ -match '(?i)corrupt' })
}
- $repairable = ($storeCorruptionLines.Count -gt 0) -or ($dismCheck -match "The component store is repairable")
+ # Localized DISM console text as a verbose hint only - never a verdict input
+ if ($dismCheck -match '(?i)component store') {
+ $dismHint = @($dismCheck -split '\r?\n' | Where-Object { $_ -match '(?i)component store' } | Select-Object -First 1)
+ if ($dismHint.Count -gt 0) { Write-Verbose "DISM output hint (localized, informational only): $($dismHint[0].Trim())" }
+ }
+
+ $repairable = ($storeCorruptionLines.Count -gt 0)
if ($dismCheckExitCode -ne 0) {
$results.DISMResult = "DISM CheckHealth failed (exit code $dismCheckExitCode) - review CBS.log"
@@ -154,11 +162,15 @@ function Test-SystemIntegrity {
}
}
}
- elseif ($dismCheck -match "No component store corruption detected") {
+ elseif ($cbsLogAvailable -and $dismTimestampsParseable) {
+ # Exit code 0 and the current-scan CBS.log window was actually
+ # examined (timestamps parsed) with no corruption markers
$results.DISMResult = "Healthy"
Write-Host "DISM: System image is healthy" -ForegroundColor Green
}
else {
+ # Inconclusive: CBS.log missing or its timestamps unparseable -
+ # never report 'healthy' from a parse miss
$results.DISMResult = "Check completed - review CBS.log"
}
}
diff --git a/Enterprise/Get-MultiSystemAudit.ps1 b/Enterprise/Get-MultiSystemAudit.ps1
index 11efd40..b5c907d 100644
--- a/Enterprise/Get-MultiSystemAudit.ps1
+++ b/Enterprise/Get-MultiSystemAudit.ps1
@@ -319,7 +319,10 @@ function Get-MultiSystemAudit {
}
$systemAudit.SecurityScore = $securityChecks.Score
- $systemAudit.Findings = $securityChecks.Findings
+ # Force to array: an empty findings list comes back from
+ # Invoke-Command as $null, and $null.Count / $null.Finding
+ # would throw under Set-StrictMode
+ $systemAudit.Findings = @($securityChecks.Findings)
# Determine security level
if ($systemAudit.SecurityScore -ge 80) {
@@ -382,7 +385,15 @@ function Get-MultiSystemAudit {
$auditResults.ComparativeAnalysis.LeastSecureSystem = $worstSystem.ComputerName
# Find common findings
- $allFindings = $successfulAudits | ForEach-Object { $_.Findings.Finding }
+ # Null/empty-safe enumeration: a host with zero findings carries
+ # an empty Findings array, and member access on it (or on $null)
+ # throws under Set-StrictMode - guard the Count first
+ $allFindings = @($successfulAudits | ForEach-Object {
+ $hostFindings = @($_.Findings)
+ if ($hostFindings.Count -gt 0) {
+ foreach ($hostFinding in $hostFindings) { $hostFinding.Finding }
+ }
+ })
$commonFindings = @($allFindings | Group-Object | Where-Object { $_.Count -ge ($successfulAudits.Count / 2) } |
Select-Object -ExpandProperty Name)
@@ -494,7 +505,7 @@ function Get-MultiSystemAudit {
</tr>
$($auditResults.SystemAudits | ForEach-Object {
"<tr>
- <td>$($_.ComputerName)</td>
+ <td>$(ConvertTo-HtmlEncoded $_.ComputerName)</td>
<td>$($_.Status)</td>
<td>$($_.SecurityScore)/100</td>
<td class='$($_.SecurityLevel.ToLower())'>$($_.SecurityLevel)</td>
diff --git a/Enterprise/Invoke-SecurityAssessment.ps1 b/Enterprise/Invoke-SecurityAssessment.ps1
index ba66f28..373e24e 100644
--- a/Enterprise/Invoke-SecurityAssessment.ps1
+++ b/Enterprise/Invoke-SecurityAssessment.ps1
@@ -36,6 +36,10 @@ function Invoke-SecurityAssessment {
Write-Host "Assessment Type: $AssessmentType" -ForegroundColor Yellow
Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow
+ if ($AssessmentType -ne 'Standard') {
+ Write-Warning "AssessmentType '$AssessmentType' is accepted, but Basic, Standard, and Advanced currently all run the same set of checks."
+ }
+
if (-not (Test-Path $OutputPath)) {
New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null
}
@@ -136,10 +140,29 @@ function Invoke-SecurityAssessment {
}
}
- # Firewall
- $firewallProfiles = Get-NetFirewallProfile -ErrorAction SilentlyContinue
+ # Firewall (cmdlet absent on hosts without the NetSecurity module - guard the lookup)
+ $firewallProfiles = @()
+ $firewallQuerySucceeded = $false
+ $firewallQueryError = $null
+ if (Get-Command Get-NetFirewallProfile -ErrorAction SilentlyContinue) {
+ try {
+ $firewallProfiles = @(Get-NetFirewallProfile -ErrorAction Stop)
+ $firewallQuerySucceeded = $true
+ } catch {
+ $firewallQueryError = ($_.Exception.Message -split "\r?\n")[0]
+ }
+ } else {
+ $firewallQueryError = 'Get-NetFirewallProfile cmdlet not available'
+ }
$enabledProfiles = @($firewallProfiles | Where-Object { $null -ne $_ -and $_.PSObject.Properties['Enabled'] -and $_.Enabled -eq $true }).Count
- if ($enabledProfiles -eq 3) {
+ if (-not $firewallQuerySucceeded) {
+ $systemSecurity.Checks += [PSCustomObject]@{
+ Check = 'Windows Firewall'
+ Status = 'Warning'
+ Score = 0
+ Details = "Unable to evaluate - $firewallQueryError"
+ }
+ } elseif ($enabledProfiles -eq 3) {
$systemSecurity.CategoryScore += 20
$systemSecurity.Checks += [PSCustomObject]@{
Check = 'Windows Firewall'
@@ -299,10 +322,25 @@ function Invoke-SecurityAssessment {
# Check for dangerous open ports
$dangerousPorts = @(23, 135, 139, 445, 1433, 3389, 5985, 5986)
- $listeningPorts = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue
+ $listeningPorts = @()
+ $portQuerySucceeded = $false
+ $portQueryError = $null
+ try {
+ $listeningPorts = @(Get-NetTCPConnection -State Listen -ErrorAction Stop)
+ $portQuerySucceeded = $true
+ } catch {
+ $portQueryError = ($_.Exception.Message -split "\r?\n")[0]
+ }
$exposedPorts = @($listeningPorts | Where-Object { $null -ne $_ -and $_.PSObject.Properties['LocalPort'] -and $dangerousPorts -contains $_.LocalPort })
- if ($exposedPorts.Count -eq 0) {
+ if (-not $portQuerySucceeded) {
+ $networkSecurity.Checks += [PSCustomObject]@{
+ Check = 'Dangerous Ports'
+ Status = 'Warning'
+ Score = 0
+ Details = "Unable to evaluate - $portQueryError"
+ }
+ } elseif ($exposedPorts.Count -eq 0) {
$networkSecurity.CategoryScore += 30
$networkSecurity.Checks += [PSCustomObject]@{
Check = 'Dangerous Ports'
@@ -328,10 +366,26 @@ function Invoke-SecurityAssessment {
# Network shares
$shares = @()
+ $shareQuerySucceeded = $false
+ $shareQueryError = $null
if (Get-Command Get-SmbShare -ErrorAction SilentlyContinue) {
- $shares = @(Get-SmbShare -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ -and $_.PSObject.Properties['Name'] -and $_.Name -notmatch '^(ADMIN\$|C\$|IPC\$)$' })
+ try {
+ $shares = @(Get-SmbShare -ErrorAction Stop | Where-Object { $null -ne $_ -and $_.PSObject.Properties['Name'] -and $_.Name -notmatch '^(ADMIN\$|C\$|IPC\$)$' })
+ $shareQuerySucceeded = $true
+ } catch {
+ $shareQueryError = ($_.Exception.Message -split "\r?\n")[0]
+ }
+ } else {
+ $shareQueryError = 'Get-SmbShare cmdlet not available'
}
- if ($shares.Count -eq 0) {
+ if (-not $shareQuerySucceeded) {
+ $networkSecurity.Checks += [PSCustomObject]@{
+ Check = 'Network Shares'
+ Status = 'Warning'
+ Score = 0
+ Details = "Unable to evaluate - $shareQueryError"
+ }
+ } elseif ($shares.Count -eq 0) {
$networkSecurity.CategoryScore += 20
$networkSecurity.Checks += [PSCustomObject]@{
Check = 'Network Shares'
@@ -422,17 +476,49 @@ function Invoke-SecurityAssessment {
}
# Local accounts
- $localUsers = @(Get-LocalUser -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ -and $_.PSObject.Properties['Enabled'] -and $_.Enabled -eq $true })
- $accountSecurity.Checks += [PSCustomObject]@{
- Check = 'Local User Accounts'
- Status = 'Info'
- Score = 0
- Details = "$($localUsers.Count) enabled accounts"
+ $localUsers = @()
+ $localUserQuerySucceeded = $false
+ $localUserQueryError = $null
+ try {
+ $localUsers = @(Get-LocalUser -ErrorAction Stop | Where-Object { $null -ne $_ -and $_.PSObject.Properties['Enabled'] -and $_.Enabled -eq $true })
+ $localUserQuerySucceeded = $true
+ } catch {
+ $localUserQueryError = ($_.Exception.Message -split "\r?\n")[0]
+ }
+ if ($localUserQuerySucceeded) {
+ $accountSecurity.Checks += [PSCustomObject]@{
+ Check = 'Local User Accounts'
+ Status = 'Info'
+ Score = 0
+ Details = "$($localUsers.Count) enabled accounts"
+ }
+ } else {
+ $accountSecurity.Checks += [PSCustomObject]@{
+ Check = 'Local User Accounts'
+ Status = 'Warning'
+ Score = 0
+ Details = "Unable to evaluate - $localUserQueryError"
+ }
}
# Administrator account status (well-known SID RID 500 - culture-invariant)
- $adminAccount = @(Get-LocalUser -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ -and $_.PSObject.Properties['SID'] -and $null -ne $_.SID -and $_.SID.Value -match '-500$' }) | Select-Object -First 1
- if ($adminAccount -and $adminAccount.Enabled -eq $false) {
+ $adminAccount = $null
+ $adminQuerySucceeded = $false
+ $adminQueryError = $null
+ try {
+ $adminAccount = @(Get-LocalUser -ErrorAction Stop | Where-Object { $null -ne $_ -and $_.PSObject.Properties['SID'] -and $null -ne $_.SID -and $_.SID.Value -match '-500$' }) | Select-Object -First 1
+ $adminQuerySucceeded = $true
+ } catch {
+ $adminQueryError = ($_.Exception.Message -split "\r?\n")[0]
+ }
+ if (-not $adminQuerySucceeded) {
+ $accountSecurity.Checks += [PSCustomObject]@{
+ Check = 'Built-in Administrator Account'
+ Status = 'Warning'
+ Score = 0
+ Details = "Unable to evaluate - $adminQueryError"
+ }
+ } elseif ($adminAccount -and $adminAccount.Enabled -eq $false) {
$accountSecurity.CategoryScore += 20
$accountSecurity.Checks += [PSCustomObject]@{
Check = 'Built-in Administrator Account'
@@ -457,8 +543,23 @@ function Invoke-SecurityAssessment {
}
# Guest account (well-known SID RID 501 - culture-invariant)
- $guestAccount = @(Get-LocalUser -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ -and $_.PSObject.Properties['SID'] -and $null -ne $_.SID -and $_.SID.Value -match '-501$' }) | Select-Object -First 1
- if ($guestAccount -and $guestAccount.Enabled -eq $false) {
+ $guestAccount = $null
+ $guestQuerySucceeded = $false
+ $guestQueryError = $null
+ try {
+ $guestAccount = @(Get-LocalUser -ErrorAction Stop | Where-Object { $null -ne $_ -and $_.PSObject.Properties['SID'] -and $null -ne $_.SID -and $_.SID.Value -match '-501$' }) | Select-Object -First 1
+ $guestQuerySucceeded = $true
+ } catch {
+ $guestQueryError = ($_.Exception.Message -split "\r?\n")[0]
+ }
+ if (-not $guestQuerySucceeded) {
+ $accountSecurity.Checks += [PSCustomObject]@{
+ Check = 'Guest Account'
+ Status = 'Warning'
+ Score = 0
+ Details = "Unable to evaluate - $guestQueryError"
+ }
+ } elseif ($guestAccount -and $guestAccount.Enabled -eq $false) {
$accountSecurity.CategoryScore += 15
$accountSecurity.Checks += [PSCustomObject]@{
Check = 'Guest Account'
@@ -498,7 +599,14 @@ function Invoke-SecurityAssessment {
# Accounts without passwords
$noPasswordAccounts = @($localUsers | Where-Object { $_.PasswordRequired -eq $false })
- if ($noPasswordAccounts.Count -eq 0) {
+ if (-not $localUserQuerySucceeded) {
+ $accountSecurity.Checks += [PSCustomObject]@{
+ Check = 'Password Required'
+ Status = 'Warning'
+ Score = 0
+ Details = "Unable to evaluate - $localUserQueryError"
+ }
+ } elseif ($noPasswordAccounts.Count -eq 0) {
$accountSecurity.CategoryScore += 25
$accountSecurity.Checks += [PSCustomObject]@{
Check = 'Password Required'
@@ -642,8 +750,20 @@ try {
}
# Windows Defender Application Control
- $wdacStatus = Get-CimInstance -ClassName Win32_DeviceGuard -Namespace root\Microsoft\Windows\DeviceGuard -ErrorAction SilentlyContinue
- if ($wdacStatus -and $wdacStatus.CodeIntegrityPolicyEnforcementStatus -eq 1) {
+ # Win32_DeviceGuard.CodeIntegrityPolicyEnforcementStatus: 1 = Audit mode, 2 = Enforced
+ $wdacStatus = $null
+ if (Get-Command Get-CimInstance -ErrorAction SilentlyContinue) {
+ $wdacStatus = Get-CimInstance -ClassName Win32_DeviceGuard -Namespace root\Microsoft\Windows\DeviceGuard -ErrorAction SilentlyContinue
+ }
+ $wdacEnforcement = if ($null -ne $wdacStatus -and $wdacStatus.PSObject.Properties['CodeIntegrityPolicyEnforcementStatus']) { $wdacStatus.CodeIntegrityPolicyEnforcementStatus } else { $null }
+ if ($null -eq $wdacEnforcement) {
+ $applicationSecurity.Checks += [PSCustomObject]@{
+ Check = 'Windows Defender Application Control'
+ Status = 'Warning'
+ Score = 0
+ Details = 'Unable to determine'
+ }
+ } elseif ($wdacEnforcement -eq 2) {
$applicationSecurity.CategoryScore += 30
$applicationSecurity.Checks += [PSCustomObject]@{
Check = 'Windows Defender Application Control'
@@ -651,6 +771,13 @@ try {
Score = 30
Details = 'Enforced'
}
+ } elseif ($wdacEnforcement -eq 1) {
+ $applicationSecurity.Checks += [PSCustomObject]@{
+ Check = 'Windows Defender Application Control'
+ Status = 'Warning'
+ Score = 0
+ Details = 'Audit mode only (not enforcing)'
+ }
} else {
$applicationSecurity.Checks += [PSCustomObject]@{
Check = 'Windows Defender Application Control'
@@ -721,7 +848,7 @@ try {
# System Restore (cmdlet absent on Server Core / non-Windows - guard the lookup)
$systemRestore = $null
if (Get-Command Get-ComputerRestorePoint -ErrorAction SilentlyContinue) {
- $systemRestore = Get-ComputerRestorePoint -ErrorAction SilentlyContinue
+ $systemRestore = @(Get-ComputerRestorePoint -ErrorAction SilentlyContinue)
}
if ($systemRestore) {
$dataProtection.CategoryScore += 15
diff --git a/Enterprise/Register-ScheduledSecurityScan.ps1 b/Enterprise/Register-ScheduledSecurityScan.ps1
index f394d27..46c80df 100644
--- a/Enterprise/Register-ScheduledSecurityScan.ps1
+++ b/Enterprise/Register-ScheduledSecurityScan.ps1
@@ -672,12 +672,15 @@ exit 0
Replace('__ALERT_DEDUP__', $safeAlertDedup).
Replace('__REALERT_AFTER_DAYS__', $safeRealertAfterDays)
- $scanScript | Out-File $scriptPath -Encoding UTF8 -Force
-
# The script embeds the webhook URL (a shared secret) and runs as SYSTEM,
- # so restrict it to Administrators and SYSTEM instead of the permissive
- # ProgramData default
+ # so it must never exist world-readable: create the file EMPTY, restrict
+ # it to Administrators and SYSTEM, and only then write the content into
+ # the locked file (avoids the permissive ProgramData default between
+ # creation and lockdown)
if ($env:OS -eq 'Windows_NT') {
+ if (-not (Test-Path $scriptPath)) {
+ New-Item -Path $scriptPath -ItemType File -Force | Out-Null
+ }
try {
$scriptAcl = Get-Acl -Path $scriptPath -ErrorAction Stop
$scriptAcl.SetAccessRuleProtection($true, $false)
@@ -702,6 +705,8 @@ exit 0
}
}
+ $scanScript | Out-File $scriptPath -Encoding UTF8 -Force
+
Write-Host "Scan script created: $scriptPath" -ForegroundColor Green
}
catch {
diff --git a/Forensics/Export-MemoryDump.ps1 b/Forensics/Export-MemoryDump.ps1
index 01b9018..d3406cb 100644
--- a/Forensics/Export-MemoryDump.ps1
+++ b/Forensics/Export-MemoryDump.ps1
@@ -25,7 +25,7 @@ function Export-MemoryDump {
PSCustomObject with dump file information
#>
- [CmdletBinding()]
+ [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param(
[Parameter()]
[string]$ProcessName,
@@ -52,17 +52,22 @@ function Export-MemoryDump {
Write-Host "Dump Type: $DumpType" -ForegroundColor Yellow
Write-Host "Output Path: $OutputPath" -ForegroundColor Yellow
- # Check if running as Administrator
- $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
-
- if (-not $isAdmin) {
- throw "This function requires Administrator privileges!"
+ # Check if running as Administrator (Windows-only check; the WindowsPrincipal
+ # APIs do not exist on other platforms)
+ if ($env:OS -eq 'Windows_NT') {
+ $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
+
+ if (-not $isAdmin) {
+ throw "This function requires Administrator privileges!"
+ }
}
# Create output directory
if (-not (Test-Path $OutputPath)) {
- New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null
- Write-Host "Created output directory: $OutputPath" -ForegroundColor Green
+ if ($PSCmdlet.ShouldProcess($OutputPath, 'Create output directory')) {
+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null
+ Write-Host "Created output directory: $OutputPath" -ForegroundColor Green
+ }
}
$result = [PSCustomObject]@{
@@ -121,6 +126,18 @@ function Export-MemoryDump {
}
return $true
}
+
+ # Pre-create the dump target as an empty, ACL-locked file so the dump content
+ # is never written to a world-readable file (closes the create -> protect race:
+ # writers that open the existing file inherit the locked ACL instead of the
+ # permissive directory default)
+ function Initialize-LockedDumpFile {
+ param([Parameter(Mandatory = $true)][string]$Path)
+ if (-not (Test-Path $Path)) {
+ New-Item -Path $Path -ItemType File -Force | Out-Null
+ }
+ $null = Protect-DumpFile -Path $Path
+ }
}
process {
@@ -170,6 +187,7 @@ function Export-MemoryDump {
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$dumpFileName = "$($targetProcess.ProcessName)_$($targetProcess.Id)_${timestamp}.dmp"
$dumpFilePath = Join-Path $OutputPath $dumpFileName
+ $dumpTarget = "Process '$($targetProcess.ProcessName)' (PID: $($targetProcess.Id))"
# METHOD 1: Try ProcDump if available and requested
if ($UseProcDump) {
@@ -202,18 +220,24 @@ function Export-MemoryDump {
$dumpFilePath
)
- try {
- $procDumpResult = & $foundProcDump $procDumpArgs 2>&1
-
- if (Test-Path $dumpFilePath) {
- $result.Success = $true
- $result.Method = "ProcDump"
- $result.DumpFile = $dumpFilePath
- Write-Host " Successfully created dump with ProcDump" -ForegroundColor Green
+ if ($PSCmdlet.ShouldProcess($dumpTarget, 'Create memory dump')) {
+ try {
+ # Pre-create and ACL-lock the empty target so procdump writes
+ # into an already-locked file
+ Initialize-LockedDumpFile -Path $dumpFilePath
+
+ $procDumpResult = & $foundProcDump $procDumpArgs 2>&1
+
+ if (Test-Path $dumpFilePath) {
+ $result.Success = $true
+ $result.Method = "ProcDump"
+ $result.DumpFile = $dumpFilePath
+ Write-Host " Successfully created dump with ProcDump" -ForegroundColor Green
+ }
+ }
+ catch {
+ Write-Warning "ProcDump failed: $_"
}
- }
- catch {
- Write-Warning "ProcDump failed: $_"
}
}
else {
@@ -222,7 +246,7 @@ function Export-MemoryDump {
}
# METHOD 2: Use MiniDumpWriteDump with proper handle
- if (-not $result.Success) {
+ if (-not $result.Success -and $PSCmdlet.ShouldProcess($dumpTarget, 'Create memory dump')) {
Write-Host "`n[2/3] Attempting MiniDumpWriteDump method..." -ForegroundColor Cyan
$processHandle = [IntPtr]::Zero
@@ -279,7 +303,10 @@ public class ProcessDump {
Write-Host " Process handle obtained successfully" -ForegroundColor Green
- # Create dump file
+ # Create dump file: pre-create and ACL-lock the empty target first
+ # so the dump content is written into an already-locked file
+ # (File::Create on an existing file preserves its security descriptor)
+ Initialize-LockedDumpFile -Path $dumpFilePath
$fileStream = [System.IO.File]::Create($dumpFilePath)
# Determine dump type flag
@@ -334,7 +361,7 @@ public class ProcessDump {
}
# METHOD 3: Use rundll32.exe comsvcs.dll method (LSASS specific)
- if (-not $result.Success -and $DumpType -eq 'LSASS') {
+ if (-not $result.Success -and $DumpType -eq 'LSASS' -and $PSCmdlet.ShouldProcess($dumpTarget, 'Create memory dump (LSASS)')) {
Write-Host "`n[3/3] Attempting comsvcs.dll method (LSASS specific)..." -ForegroundColor Cyan
try {
@@ -352,7 +379,10 @@ public class ProcessDump {
"full"
)
- # Run elevated
+ # Run elevated (the target file was pre-created and ACL-locked,
+ # so the elevated writer inherits the locked ACL on write)
+ Initialize-LockedDumpFile -Path $dumpFilePath
+
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = "rundll32.exe"
$psi.Arguments = $arguments -join ' '
diff --git a/Forensics/Get-ExecutionArtifacts.ps1 b/Forensics/Get-ExecutionArtifacts.ps1
index 2570b05..a2eaec5 100644
--- a/Forensics/Get-ExecutionArtifacts.ps1
+++ b/Forensics/Get-ExecutionArtifacts.ps1
@@ -467,7 +467,10 @@
# Export CSV
if ($Format -in @('CSV', 'All')) {
$csvPath = Join-Path $OutputPath "$reportName.csv"
- $results.Artifacts | Select-Object Source, ExecutableName, FullPath, Timestamp, TimestampType |
+ $results.Artifacts | Select-Object Source,
+ @{N='ExecutableName';E={Protect-CsvField $_.ExecutableName}},
+ @{N='FullPath';E={Protect-CsvField $_.FullPath}},
+ Timestamp, TimestampType |
Export-Csv $csvPath -NoTypeInformation -Encoding UTF8
Write-Host " CSV report saved: $csvPath" -ForegroundColor Green
}
diff --git a/Forensics/Get-USBHistory.ps1 b/Forensics/Get-USBHistory.ps1
index 3864b49..f56cf6a 100644
--- a/Forensics/Get-USBHistory.ps1
+++ b/Forensics/Get-USBHistory.ps1
@@ -5,7 +5,8 @@
.DESCRIPTION
Analyzes registry, event logs, and setup logs to identify all USB devices
that have been connected to the system, including timestamps, serial numbers,
- vendor information, and last connection times.
+ and vendor information. LastConnected is reported as unknown ($null) - the
+ registry values read here contain no last-connection timestamp.
.PARAMETER IncludeEventLogs
Include event log analysis for USB connection/disconnection events
.PARAMETER IncludeSetupAPI
@@ -118,7 +119,9 @@
Revision = $revision
SerialNumber = $serialNumber
FirstInstalled = $installDate
- LastConnected = $installDate
+ # USBSTOR registry values carry no last-connection timestamp -
+ # report unknown rather than duplicating the install date
+ LastConnected = $null
RegistryPath = $device.PSPath
}
@@ -199,7 +202,9 @@
Revision = 'N/A'
SerialNumber = $serialNumber
FirstInstalled = $installDate
- LastConnected = $installDate
+ # USB registry values carry no last-connection timestamp -
+ # report unknown rather than duplicating the install date
+ LastConnected = $null
RegistryPath = $instance.PSPath
}
@@ -336,7 +341,15 @@
# Export CSV
if ($Format -in @('CSV', 'All')) {
$csvPath = Join-Path $OutputPath "$reportName.csv"
- $results.USBDevices | Export-Csv $csvPath -NoTypeInformation -Encoding UTF8
+ $results.USBDevices | Select-Object @{N='Type';E={Protect-CsvField $_.Type}},
+ @{N='FriendlyName';E={Protect-CsvField $_.FriendlyName}},
+ @{N='Vendor';E={Protect-CsvField $_.Vendor}},
+ @{N='Product';E={Protect-CsvField $_.Product}},
+ @{N='Revision';E={Protect-CsvField $_.Revision}},
+ @{N='SerialNumber';E={Protect-CsvField $_.SerialNumber}},
+ FirstInstalled, LastConnected,
+ @{N='RegistryPath';E={Protect-CsvField $_.RegistryPath}} |
+ Export-Csv $csvPath -NoTypeInformation -Encoding UTF8
Write-Host " CSV report saved: $csvPath" -ForegroundColor Green
}
diff --git a/Forensics/Get-UserActivityArtifacts.ps1 b/Forensics/Get-UserActivityArtifacts.ps1
index 8da149f..d794d26 100644
--- a/Forensics/Get-UserActivityArtifacts.ps1
+++ b/Forensics/Get-UserActivityArtifacts.ps1
@@ -404,17 +404,26 @@ function Get-UserActivityArtifacts {
New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null
}
+ # Escapes string fields against CSV formula injection before export
+ filter Protect-CsvRowFields {
+ $escaped = [ordered]@{}
+ foreach ($prop in $_.PSObject.Properties) {
+ $escaped[$prop.Name] = if ($prop.Value -is [string]) { Protect-CsvField $prop.Value } else { $prop.Value }
+ }
+ [PSCustomObject]$escaped
+ }
+
if (@($results.RecycleBin).Count -gt 0) {
- $results.RecycleBin | Export-Csv -Path (Join-Path $OutputPath 'RecycleBin.csv') -NoTypeInformation -Encoding UTF8
+ $results.RecycleBin | Protect-CsvRowFields | Export-Csv -Path (Join-Path $OutputPath 'RecycleBin.csv') -NoTypeInformation -Encoding UTF8
}
if (@($results.RecentLinks).Count -gt 0) {
- $results.RecentLinks | Export-Csv -Path (Join-Path $OutputPath 'RecentLinks.csv') -NoTypeInformation -Encoding UTF8
+ $results.RecentLinks | Protect-CsvRowFields | Export-Csv -Path (Join-Path $OutputPath 'RecentLinks.csv') -NoTypeInformation -Encoding UTF8
}
if (@($results.JumpLists).Count -gt 0) {
- $results.JumpLists | Export-Csv -Path (Join-Path $OutputPath 'JumpLists.csv') -NoTypeInformation -Encoding UTF8
+ $results.JumpLists | Protect-CsvRowFields | Export-Csv -Path (Join-Path $OutputPath 'JumpLists.csv') -NoTypeInformation -Encoding UTF8
}
if (@($results.Timeline).Count -gt 0) {
- $results.Timeline | Export-Csv -Path (Join-Path $OutputPath 'Timeline.csv') -NoTypeInformation -Encoding UTF8
+ $results.Timeline | Protect-CsvRowFields | Export-Csv -Path (Join-Path $OutputPath 'Timeline.csv') -NoTypeInformation -Encoding UTF8
}
Write-Host "`nCSV exports written to: $OutputPath" -ForegroundColor Green
diff --git a/Forensics/New-ForensicTimeline.ps1 b/Forensics/New-ForensicTimeline.ps1
index 07e173a..927ca87 100644
--- a/Forensics/New-ForensicTimeline.ps1
+++ b/Forensics/New-ForensicTimeline.ps1
@@ -79,6 +79,7 @@
FileSystemChanges = 0
RegistryChanges = 0
NetworkConnections = 0
+ Truncated = $false
}
}
@@ -108,6 +109,12 @@
StartTime = $StartTime
EndTime = $EndTime
} -ErrorAction SilentlyContinue -MaxEvents 1000)
+
+ # Cap hit: results are silently truncated - warn and flag it
+ if ($events.Count -ge 1000) {
+ Write-Warning "Event log cap (1000) reached for '$logName' - timeline truncated; use a narrower time range for complete coverage"
+ $timeline.Summary.Truncated = $true
+ }
foreach ($event in $events) {
# FIXED: Safe message handling with null check
@@ -332,7 +339,11 @@
# Export CSV
if ($Format -in @('CSV', 'All')) {
$csvPath = Join-Path $OutputPath "$reportName.csv"
- $timeline.Events | Select-Object Timestamp, Source, Category, Level, Message |
+ $timeline.Events | Select-Object Timestamp,
+ @{N='Source';E={Protect-CsvField $_.Source}},
+ @{N='Category';E={Protect-CsvField $_.Category}},
+ @{N='Level';E={Protect-CsvField $_.Level}},
+ @{N='Message';E={Protect-CsvField $_.Message}} |
Export-Csv $csvPath -NoTypeInformation -Encoding UTF8
Write-Host " CSV timeline saved: $csvPath" -ForegroundColor Green
}
diff --git a/Hardening/Enable-PowerShellSecurity.ps1 b/Hardening/Enable-PowerShellSecurity.ps1
index 75d4515..4a8d0e2 100644
--- a/Hardening/Enable-PowerShellSecurity.ps1
+++ b/Hardening/Enable-PowerShellSecurity.ps1
@@ -22,7 +22,7 @@
PSCustomObject with configuration results
#>
- [CmdletBinding(SupportsShouldProcess)]
+ [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param(
[Parameter()]
[ValidateSet('Restricted', 'AllSigned', 'RemoteSigned', 'Unrestricted', 'Bypass')]
diff --git a/Hardening/Invoke-SecurityRemediation.ps1 b/Hardening/Invoke-SecurityRemediation.ps1
index c32e666..055da59 100644
--- a/Hardening/Invoke-SecurityRemediation.ps1
+++ b/Hardening/Invoke-SecurityRemediation.ps1
@@ -395,6 +395,29 @@ function Invoke-SecurityRemediation {
if (-not $PSCmdlet.ShouldProcess($findingText, "Apply remediation '$($matched.Name)'")) {
Write-Host " WhatIf: would apply '$($matched.Name)'" -ForegroundColor Magenta
+
+ # WhatIf preview: still capture the pre-change state so the
+ # promised rollback script is produced. The Rollback
+ # scriptblocks are read-only (Get-* / Get-ItemProperty), so
+ # no system state is mutated by capturing them here.
+ if ($GenerateRollback) {
+ try {
+ $capturedRollback = @(& $matched.Rollback)
+ if (@($capturedRollback).Count -gt 0) {
+ # Collapse line breaks: finding text comes from
+ # JSON / pipeline input and must not inject lines
+ # into the rollback script (same rule as real apply)
+ $rollbackFindingText = $findingText -replace '[\r\n]+', ' '
+ $rollbackScriptLines += "# Rollback for: $rollbackFindingText"
+ $rollbackScriptLines += "# WhatIf preview: remediation '$($matched.Name)' was NOT applied; state captured $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
+ $rollbackScriptLines += $capturedRollback
+ $rollbackScriptLines += ""
+ }
+ }
+ catch {
+ Write-Warning " Could not capture pre-change state for rollback: $_"
+ }
+ }
continue
}
@@ -468,17 +491,34 @@ function Invoke-SecurityRemediation {
"#Requires -RunAsAdministrator"
"# Rollback script generated by Invoke-SecurityRemediation"
"# Generated: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
- "# Restores the pre-remediation state captured BEFORE changes were applied"
- ""
)
-
- if ($PSCmdlet.ShouldProcess($rollbackFile, "Write rollback script")) {
+ if ($WhatIfPreference) {
+ $header += "# WHATIF PREVIEW MODE: no changes were applied. This script restores the state captured during the preview; use it only if you later apply the same remediations."
+ }
+ else {
+ $header += "# Restores the pre-remediation state captured BEFORE changes were applied"
+ }
+ $header += ""
+
+ # The rollback script is an output artifact (like a report),
+ # so it is written even under -WhatIf - that is the documented
+ # 'preview fixes with a rollback script, no changes' behavior.
+ # ShouldProcess still gates the write on real (non-WhatIf) runs.
+ if ($WhatIfPreference -or $PSCmdlet.ShouldProcess($rollbackFile, "Write rollback script")) {
+ # -WhatIf:$false: New-Item/Set-Content support ShouldProcess and
+ # would inherit $WhatIfPreference, silently skipping the write -
+ # the rollback script is an output artifact and must really be written
if (-not (Test-Path -Path $RollbackDirectory)) {
- New-Item -Path $RollbackDirectory -ItemType Directory -Force | Out-Null
+ New-Item -Path $RollbackDirectory -ItemType Directory -Force -WhatIf:$false | Out-Null
}
- Set-Content -Path $rollbackFile -Value (($header + $rollbackScriptLines) -join [Environment]::NewLine) -Encoding UTF8 -ErrorAction Stop
+ Set-Content -Path $rollbackFile -Value (($header + $rollbackScriptLines) -join [Environment]::NewLine) -Encoding UTF8 -ErrorAction Stop -WhatIf:$false
$results.RollbackPath = $rollbackFile
- Write-Host "`n[ROLLBACK] Rollback script written: $rollbackFile" -ForegroundColor Green
+ if ($WhatIfPreference) {
+ Write-Host "`n[ROLLBACK] WhatIf preview rollback script written: $rollbackFile" -ForegroundColor Magenta
+ }
+ else {
+ Write-Host "`n[ROLLBACK] Rollback script written: $rollbackFile" -ForegroundColor Green
+ }
}
else {
Write-Host "`n[ROLLBACK] WhatIf: would write rollback script to $rollbackFile" -ForegroundColor Magenta
diff --git a/Hardening/Set-SecurityBaseline.ps1 b/Hardening/Set-SecurityBaseline.ps1
index e734b1c..e52e38e 100644
--- a/Hardening/Set-SecurityBaseline.ps1
+++ b/Hardening/Set-SecurityBaseline.ps1
@@ -20,7 +20,7 @@ function Set-SecurityBaseline {
PSCustomObject with baseline configuration results
#>
- [CmdletBinding(SupportsShouldProcess)]
+ [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param(
[Parameter()]
[ValidateSet('Basic', 'Recommended', 'Strict')]
diff --git a/Private/ExportHelpers.ps1 b/Private/ExportHelpers.ps1
new file mode 100644
index 0000000..2e346d9
--- /dev/null
+++ b/Private/ExportHelpers.ps1
@@ -0,0 +1,44 @@
+#requires -Version 5.1
+
+<#
+.SYNOPSIS
+ Shared output-safety helpers (CSV formula-injection escaping, HTML encoding).
+.DESCRIPTION
+ Internal helpers used by export/report functions. CSV escaping follows the
+ spreadsheet formula-injection convention: any value starting with =, +, -, @
+ (or tab/CR/LF) is prefixed with a single quote. HTML encoding uses
+ System.Net.WebUtility.HtmlEncode (available on .NET Framework 4.x / PS 5.1).
+#>
+
+function Protect-CsvField {
+ [CmdletBinding()]
+ [OutputType([string])]
+ param(
+ [Parameter(Mandatory = $false)]
+ [AllowNull()]
+ [AllowEmptyString()]
+ [object]$Value
+ )
+
+ if ($null -eq $Value) { return '' }
+ $text = [string]$Value
+ if ($text.Length -eq 0) { return '' }
+ if ($text -match '^[=+\-@\t\r\n]') {
+ return "'$text"
+ }
+ return $text
+}
+
+function ConvertTo-HtmlEncoded {
+ [CmdletBinding()]
+ [OutputType([string])]
+ param(
+ [Parameter(Mandatory = $false)]
+ [AllowNull()]
+ [AllowEmptyString()]
+ [object]$Value
+ )
+
+ if ($null -eq $Value) { return '' }
+ return [System.Net.WebUtility]::HtmlEncode([string]$Value)
+}
diff --git a/README.md b/README.md
index 18cfe8d..edc49be 100644
--- a/README.md
+++ b/README.md
@@ -10,7 +10,7 @@
[![Functions](https://img.shields.io/badge/Functions-72-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-498%20Passed-brightgreen.svg)](https://github.com/okanyildiz/WindowsSecurityAudit/blob/main/tests/WindowsSecurityAudit.Tests.ps1)
+[![Tests](https://img.shields.io/badge/Tests-520-brightgreen.svg)](https://github.com/okanyildiz/WindowsSecurityAudit/tree/main/tests)
[![GitHub stars](https://img.shields.io/github/stars/okanyildiz/WindowsSecurityAudit)](https://github.com/okanyildiz/WindowsSecurityAudit/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/okanyildiz/WindowsSecurityAudit)](https://github.com/okanyildiz/WindowsSecurityAudit/network/members)
@@ -18,7 +18,7 @@
**Enterprise-Grade Windows Security Auditing & Threat Detection Toolkit**
-**🎯 Zero Dependencies • 🚀 Production Ready • 🌍 Community Driven • 💼 Enterprise Tested**
+**🧱 Dependency-Free Core • 🌍 Locale-Invariant Auditing • 🧪 520-Test CI Suite • 📜 MIT Licensed**
[Features](#-full-feature-overview) • [Why](#-why-windows-security-audit-module) • [Installation](#-installation) • [Quick Start](#-quick-start) • [Release Highlights](#-release-highlights) • [Support](#-support--contact)
@@ -43,9 +43,9 @@
| ✅ **Compliance** | 5 | CIS Benchmark, NIST 800-53, PCI-DSS 4.0 validation, compliance reports, audit evidence export |
| 🌳 **Active Directory** | 6 | AD backdoors & DCSync detection, vulnerability scan, stale objects, password policies, privileged accounts, posture |
| 🩹 **Vulnerability** | 8 | CVE assessment (real NVD data + version-exact CPE matching), EOL software, exposed services, certificates, patches |
-| 🔍 **Forensics** | 7 | Memory dumps, artifact collection with SHA256-at-acquisition, execution artifacts (prefetch/UserAssist/BAM), USB history, user activity artifacts (Recycle Bin/LNK/JumpLists/Timeline), forensic timelines, USN journal/MFT summary/timestomp evidence |
-| ☁️ **Cloud Security** | 3 | Azure AD risky sign-ins, M365 security posture, cloud compliance status |
-| 📊 **Reporting** | 4 | Security metrics/KPIs, executive reports, live HTML dashboards, consolidated all-module Chart.js report |
+| 🔍 **Forensics** | 7 | Per-process memory dumps (ProcDump/MiniDumpWriteDump), artifact collection with SHA256-at-acquisition, execution artifacts (prefetch/UserAssist/BAM), USB history, user activity artifacts (Recycle Bin/LNK/JumpLists/Timeline), forensic timelines, USN journal/MFT summary/timestomp evidence |
+| ☁️ **Cloud Security** | 3 | Azure AD risky sign-ins (Entra ID detections), M365 security posture, cloud compliance catalog (NotEvaluated until Graph queries land) |
+| 📊 **Reporting** | 4 | Security metrics/KPIs, executive reports, static HTML dashboards (optional meta-refresh), consolidated Chart.js report (6 collectors; charts need internet for the CDN) |
> 👇 **Deep dive per module below** — full function-by-function tables in [Module Categories - Detailed Breakdown](#-module-categories---detailed-breakdown).
@@ -68,9 +68,9 @@ If you find this tool valuable for your security operations, consider supporting
## 📖 Executive Summary
-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.
+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** addresses this by 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 72 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 toolkit bundles **72 functions across 14 specialized modules** covering the audit lifecycle end-to-end: baseline scoring, threat detection, forensic collection, hardening, compliance validation, vulnerability assessment and reporting. Capabilities that usually require stitching together several single-purpose tools ship here as one cohesive, MIT-licensed module — with a 520-test Pester suite running in CI on both PowerShell 7 and Windows PowerShell 5.1, and locale-invariant checks that return correct results on non-English Windows systems.
### 🎯 The Vision
@@ -89,15 +89,14 @@ Modern enterprises typically juggle 15-20 different security tools, each with it
**Our Solution:**
-A single, cohesive PowerShell module that consolidates essential security functions into one powerful toolkit. Built on native Windows capabilities, it requires zero external dependencies while delivering enterprise-scale performance and reliability.
+A single, cohesive PowerShell module that consolidates essential security functions into one powerful toolkit. The core audit checks are built on native Windows capabilities and run without any external dependencies; only the cloud and Active Directory modules need extra tooling (Microsoft Graph PowerShell SDK and the RSAT ActiveDirectory module, respectively).
-### 🏆 Proven Results
+### ✅ What You Can Verify
-- **🚀 Deployment Speed**: From download to production in under 10 minutes
-- **💰 Cost Savings**: Replace $100,000+ in commercial tools
-- **⏱️ Time Efficiency**: Reduce security assessments from days to hours
-- **🎯 Detection Rate**: Identify threats missed by leading commercial solutions
-- **📊 Compliance**: Automate 90% of audit evidence collection
+- **🌍 Locale-invariant auditing**: checks use APIs, GUIDs and SIDs instead of parsing localized console output — correct results on Turkish, German, French and any other Windows display language
+- **🧪 Tested**: 520 Pester tests, gated in CI by PSScriptAnalyzer and module-import checks on both PowerShell 7 (`pwsh`) and Windows PowerShell 5.1
+- **🧱 Dependency-free core**: baseline, detection, forensics, hardening and compliance checks run on a stock Windows install
+- **📜 MIT licensed**: free for commercial use, full source available
---
@@ -114,8 +113,8 @@ A single, cohesive PowerShell module that consolidates essential security functi
</tr>
<tr>
<td><strong>Total Cost</strong></td>
-<td>✅ Free Forever</td>
-<td>❌ $50K-200K/year</td>
+<td>✅ Free Forever (MIT)</td>
+<td>❌ Commercial licensing</td>
<td>✅ Free</td>
</tr>
<tr>
@@ -126,13 +125,13 @@ A single, cohesive PowerShell module that consolidates essential security functi
</tr>
<tr>
<td><strong>Dependencies</strong></td>
-<td>✅ None (Native PowerShell)</td>
+<td>✅ None for core checks (native PowerShell); Graph/RSAT only for cloud & AD modules</td>
<td>❌ Multiple Agents</td>
<td>❌ Python/Ruby/Tools</td>
</tr>
<tr>
<td><strong>Enterprise Scale</strong></td>
-<td>✅ 10,000+ Endpoints</td>
+<td>✅ Parallel multi-system scanning (up to 50 threads)</td>
<td>✅ Varies</td>
<td>❌ Limited</td>
</tr>
@@ -262,10 +261,10 @@ WindowsSecurityAudit/
│ ├── Invoke-IncidentResponse.ps1
│ └── Send-SiemEvent.ps1
│
-├── 📁 tests/ # Pester tests (498 tests)
-│ ├── WindowsSecurityAudit.Tests.ps1 # Public API surface (425 tests)
+├── 📁 tests/ # Pester tests (520 tests)
+│ ├── WindowsSecurityAudit.Tests.ps1 # Public API surface (427 tests)
│ ├── Smoke.Windows.Tests.ps1 # Real-Windows execution smoke tests (48)
-│ ├── Locale.Regression.Tests.ps1 # EN/DE fixture equivalence + no-text-readers guard (25)
+│ ├── Locale.Regression.Tests.ps1 # EN/DE fixture equivalence + no-text-readers guard (45)
│ └── fixtures/ # auditpol EN/DE (cp1252) CSV fixtures
│
├── 📁 ThreatHunting/ # Threat Hunting (7 functions)
@@ -312,8 +311,8 @@ WindowsSecurityAudit/
- Global Administrator (Cloud Security module)
### Optional Components
-- **Active Directory PowerShell Module**: For AD security functions
-- **Azure AD PowerShell**: For Azure/M365 assessments
+- **ActiveDirectory module (RSAT)**: For AD security functions
+- **Microsoft Graph PowerShell SDK**: For cloud functions (Azure/M365 assessments)
- **Windows Defender**: For AV management functions
- **.NET Framework 4.7.2+**: For advanced reporting features
@@ -338,7 +337,7 @@ Import-Module ".\WindowsSecurityAudit.psd1" -Force
```
### Method 2: Direct Download
-> **Note:** The `WindowsSecurityAudit.zip` asset is **not currently attached** to GitHub releases (the publish workflow only targets the PowerShell Gallery), so this download URL returns a 404 for now. Use Method 1 or 3 until a release ships the ZIP asset.
+> **Note:** No `WindowsSecurityAudit.zip` asset is attached to GitHub releases today — the publish workflow (`.github/workflows/publish.yml`) targets the PowerShell Gallery only, so the download URL below returns 404. Use Method 1, 3 or 4 until a release ships a ZIP asset.
```powershell
# Download latest release
@@ -409,8 +408,8 @@ Import-Module WindowsSecurityAudit
### Your First Security Scan (2 minutes)
```powershell
-# 1. Import the module
-Import-Module WindowsSecurityAudit
+# 1. Import the module (from a git clone; see Installation for Gallery/other methods)
+Import-Module .\WindowsSecurityAudit\WindowsSecurityAudit.psd1 -Force
# 2. Run quick assessment
$security = Get-SecurityBaseline
@@ -517,7 +516,7 @@ The Core module serves as the foundation of the entire security assessment frame
| Function | Purpose | Key Features | Output Type |
|----------|---------|--------------|-------------|
-| **`Get-SecurityBaseline`** | Evaluates overall security posture against industry best practices | • Windows Defender real-time protection status<br>• Firewall profile configuration (Domain/Private/Public)<br>• UAC elevation settings<br>• BitLocker encryption status<br>• Windows Update compliance<br>• Generates 0-100 security score based on CIS benchmarks | PSCustomObject with scores, status, and recommendations |
+| **`Get-SecurityBaseline`** | Evaluates overall security posture against industry best practices | • Windows Defender real-time protection status<br>• Firewall profile configuration (Domain/Private/Public)<br>• UAC elevation settings<br>• BitLocker encryption status<br>• Windows Update compliance<br>• Generates an aggregate 0-100 security score | PSCustomObject with scores, status, and recommendations |
| **`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 |
@@ -531,10 +530,10 @@ The Detection module provides real-time threat identification capabilities using
| Function | Purpose | Detection Capabilities | Risk Indicators |
|----------|---------|------------------------|-----------------|
-| **`Find-PersistenceMechanisms`** | Identifies malware persistence techniques across the system | • 11+ Registry autorun locations (Run, RunOnce, etc.)<br>• Scheduled Tasks (hidden, system, unusual)<br>• Windows Services (unsigned, suspicious paths)<br>• WMI Event Subscriptions<br>• Startup folders (all users, system) | High: Unknown entries<br>Medium: Unsigned binaries<br>Low: Unusual locations |
-| **`Find-SuspiciousProcesses`** | Detects malicious process behaviors and anomalies | • Unsigned or invalid signatures<br>• Execution from temporary directories<br>• Encoded PowerShell commands<br>• Process injection indicators<br>• Unusual parent-child relationships<br>• Network connections to suspicious IPs | Critical: Known malware<br>High: Injection detected<br>Medium: Unsigned from temp |
-| **`Find-NetworkAnomalies`** | Identifies abnormal network communications | • Connections to known C2 servers<br>• Non-standard port usage<br>• DNS tunneling indicators<br>• Large data transfers<br>• Tor/proxy connections<br>• Suspicious protocol usage | Critical: Known C2<br>High: DNS tunneling<br>Medium: Unusual ports |
-| **`Find-SuspiciousAuthentication`** | Detects authentication attacks and anomalies | • Brute force attempts (multiple failures)<br>• Account lockout patterns<br>• After-hours authentication<br>• Explicit-credential logons (runas / net use, 4624 Type 9 NewCredentials)<br>• Per-account NTLM network logon indicators<br>• Impossible travel scenarios<br>• Service account anomalies | High: Brute force<br>Medium: After hours<br>Low: Explicit credentials |
+| **`Find-PersistenceMechanisms`** | Identifies malware persistence techniques across the system | • 8 registry Run-key locations (Run, RunOnce, RunServices, WOW6432Node)<br>• Startup folders (per-user and all-users)<br>• Scheduled Tasks (hidden, system, unusual)<br>• Windows Services (unsigned, suspicious paths)<br>• WMI Event Subscriptions<br>• Other registry autostarts (AppInit DLLs, LSA providers, print monitors) | High: Unknown entries<br>Medium: Unsigned binaries<br>Low: Unusual locations |
+| **`Find-SuspiciousProcesses`** | Detects malicious process behaviors and anomalies | • Unsigned or invalid signatures<br>• Execution from temporary/suspicious directories<br>• Known suspicious tool names<br>• Unusual parent-child relationships (Office/browser spawning shells)<br>• Optional network-connection check (uncommon remote ports, `-CheckNetwork`) | Suspicion score per process<br>Unsigned or oddly-located binaries<br>Suspicious parent/child pairs |
+| **`Find-NetworkAnomalies`** | Identifies abnormal network communications | • Known high-risk/malicious port usage<br>• Non-standard and unusual high listening ports<br>• Optional DNS cache anomaly heuristics (DGA/entropy-style checks, `-CheckDNS`)<br>• Established-connection review | High: Known malicious ports<br>Medium: Unusual ports<br>Medium: DNS anomalies |
+| **`Find-SuspiciousAuthentication`** | Detects authentication attacks and anomalies | • Brute force attempts (multiple failures)<br>• Account lockout patterns<br>• After-hours authentication<br>• Explicit-credential logons (runas / net use, 4624 Type 9 NewCredentials)<br>• Per-account NTLM network logon indicators<br>• Service account anomalies | High: Brute force<br>Medium: After hours<br>Low: Explicit credentials |
| **`Get-CredentialAccessEvents`** | Detects runtime credential-access activity from event logs | • Kerberoasting: RC4 service ticket bursts (4769)<br>• Anomalous TGT request volumes (4768)<br>• Kerberos pre-auth failure spikes / password spray (4771)<br>• Golden-ticket heuristic (Kerberos logon with no matching TGT; labeled Heuristic/Medium)<br>• Optional LSASS access handles (`-IncludeLSASSAccess`; 4663 needs a SACL, or Sysmon 10) | High: Kerberoast bursts, suspicious LSASS access<br>Medium: TGT anomalies, spray spikes, golden-ticket heuristic |
| **`Find-DefenseEvasion`** | Detects defense-evasion and security-tampering activity | • AMSI bypass & ETW tamper patterns in script-block logs (4104)<br>• Defender exclusions and disabled real-time/behavior monitoring (Get-MpPreference)<br>• Defender tamper events (5001/5007)<br>• Log clearing (1102/104) and audit policy changes (4719) with clearing-account attribution<br>• Optional heuristic log-gap analysis (`-IncludeLogGapAnalysis`) | High: AMSI/ETW tamper, Defender tamper, cleared logs<br>Low: log gaps (heuristic) |
| **`Get-SysmonAnalytics`** | Deep analytics over the Sysmon Operational log (requires Sysmon) | • Event 1 process chains & command-line indicators<br>• Event 3 network beaconing detection<br>• Event 7 image loads<br>• Event 10 process access with LSASS access-mask analysis (T1003.001)<br>• Event 11 file creates, Events 12/13 registry writes<br>• Event 22 DNS anomalies<br>• `-Hours` / `-EventTypes` / `-MaxEvents` filtering; returns `NotAvailable` gracefully when Sysmon is absent | High: LSASS access masks, encoded commands, download cradles<br>Medium: beaconing, persistence-oriented writes |
@@ -547,9 +546,9 @@ The Analysis module performs deep forensic examination of system components to u
| Function | Purpose | Analysis Techniques | Key Findings |
|----------|---------|---------------------|--------------|
-| **`Get-EventLogAnalysis`** | Deep analysis of Windows event logs for security insights | • Security log correlation (4624, 4625, 4672)<br>• PowerShell operational log analysis<br>• System log anomalies<br>• Application error patterns<br>• Custom XML query execution<br>• Timeline reconstruction | Authentication patterns<br>Privilege escalations<br>System modifications<br>PowerShell abuse |
-| **`Get-RegistryAnalysis`** | Examines registry for malicious modifications | • Autorun entry validation<br>• Security policy tampering<br>• Browser helper objects<br>• Shell extensions<br>• Recent document tracking<br>• User activity artifacts | Persistence mechanisms<br>Policy bypasses<br>User behaviors<br>Malware artifacts |
-| **`Get-MemoryAnalysis`** | Analyzes process memory for advanced threats | • Process injection heuristic indicators<br>• Hollowing heuristic indicators<br>• Memory pattern matching<br>• String extraction<br>• Suspicious allocations<br>• Fileless malware indicators | Injected code<br>Credential theft<br>Rootkit presence<br>APT indicators |
+| **`Get-EventLogAnalysis`** | Analyzes Windows event logs for security insights | • Security/System/Application log analysis<br>• Failed logon and audit-event highlighting (4625, 1102, 4697, ...)<br>• Event ID context and counts<br>• Application error patterns | Authentication failures<br>Audit events<br>System anomalies<br>Application errors |
+| **`Get-RegistryAnalysis`** | Examines registry for security-relevant settings | • Security policy settings (LSA, WDigest, UAC)<br>• Autorun entry review (`-IncludeAutoRun`)<br>• Service key review (suspicious/unquoted paths)<br>• Registry permission checks (`-CheckPermissions`) | Weakened security settings<br>Persistence entries<br>Risky service configs |
+| **`Get-MemoryAnalysis`** | Heuristic process inspection via process metadata (no raw memory reads) | • Loaded-module inventory with suspicious name/location patterns<br>• Main-module path mismatch (process-hollowing heuristic)<br>• Working-set/virtual-memory ratio anomalies (injection heuristic)<br>• Remote-thread start-address heuristics<br>• `-IncludeStrings` only notes that string extraction needs external tools (e.g. Sysinternals Strings) | Injection/hollowing heuristics<br>Suspicious modules<br>Unusual memory characteristics |
| **`Get-FileSystemAnalysis`** | Comprehensive file system security analysis | • Alternate Data Stream detection<br>• Hidden file discovery<br>• Suspicious extensions<br>• Recent file modifications<br>• Ransomware indicators<br>• Permission auditing | Hidden malware<br>Data staging<br>Exfiltration prep<br>Ransomware signs |
---
@@ -560,8 +559,8 @@ The Response module provides automated incident response capabilities, enabling
| Function | Purpose | Response Actions | Evidence Types |
|----------|---------|------------------|----------------|
-| **`Invoke-IncidentResponse`** | Orchestrates automated incident response procedures | • Threat containment (process termination)<br>• System isolation (network disconnection)<br>• Evidence preservation<br>• User notification<br>• Backup initiation<br>• Recovery planning | Response timeline<br>Actions taken<br>System state<br>Threat indicators |
-| **`Invoke-ForensicCollection`** | Systematically collects forensic evidence | • Memory dump acquisition<br>• Network state capture<br>• Registry snapshot<br>• Event log extraction<br>• File artifact collection<br>• Browser history preservation | Memory dumps<br>Network captures<br>System artifacts<br>User data |
+| **`Invoke-IncidentResponse`** | Orchestrates a guided incident response procedure | • Step 1: quick security baseline<br>• Step 2: active-threat scan<br>• Step 3: optional network isolation (`-IsolateSystem`, automatic on Critical severity)<br>• Step 4: suspicious-process termination<br>• Step 5: forensic evidence collection<br>• Step 6: incident report generation | Response timeline<br>Actions taken<br>System state<br>Threat indicators |
+| **`Invoke-ForensicCollection`** | Systematically collects forensic evidence | • System, process and network state capture<br>• Event log extraction<br>• Registry artifact collection (incl. USB history)<br>• File-system artifacts (Comprehensive profile)<br>• Timeline generation<br>• Memory dump: writes an instructions file pointing to external tools (WinPMEM, DumpIt, Magnet RAM Capture) — no in-module memory acquisition | State captures<br>Event logs<br>System artifacts<br>Timeline data |
| **`Export-SecurityReport`** | Generates professional security reports | • HTML interactive dashboards<br>• JSON for SIEM integration<br>• CSV for data analysis<br>• NDJSON/CEF SIEM-ready exports (`-Format NDJSON/CEF`; `All` writes .ndjson + .cef too)<br>• `-NoAutoOpen` for headless/SYSTEM-context runs | Multi-format reports<br>Executive summaries<br>Technical details<br>Recommendations |
| **`ConvertTo-SiemEvent`** | Converts findings into SIEM-ready event strings | • Pipeline conversion of findings to NDJSON (one compact JSON object per line) or CEF (`CEF:0` strings)<br>• Severity-to-number mapping and heuristic CEF `act` field<br>• MITRE technique ID passthrough when present<br>• `-HostName` / `-ProductVersion` stamping<br>• Splunk / Sentinel / QRadar / ArcSight ingestion ready | NDJSON lines<br>CEF strings |
| **`Send-SiemEvent`** | Streams findings directly to SIEM HTTP endpoints | • Splunk HEC (`Splunk <token>` auth header), Microsoft Sentinel (Log Analytics API with HMAC-SHA256 SharedKey signature), or generic webhook with custom headers<br>• NDJSON or CEF payloads via ConvertTo-SiemEvent<br>• Batching (`-BatchSize`) with exponential-backoff retry on HTTP 429/5xx (`-MaxRetries`, `-ThrottleMs`)<br>• Token always masked in console output<br>• Also wired into `Export-SecurityReport -StreamTo/-StreamUri/-StreamToken/-StreamFormat` | BatchesSent / EventsSent / Failed / DurationSec summary |
@@ -574,7 +573,7 @@ The Enterprise module enables security operations at scale, providing centralize
| Function | Purpose | Enterprise Features | Scalability |
|----------|---------|---------------------|-------------|
-| **`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 |
+| **`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 | Parallel multi-system scans<br>Per-host timeouts & probes<br>CSV target lists |
| **`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 |
@@ -587,8 +586,8 @@ The Hardening module implements security best practices and configurations to re
| Function | Purpose | Hardening Actions | Compliance |
|----------|---------|-------------------|-------------|
-| **`Set-SecurityBaseline`** | Applies comprehensive security configurations | • 50+ security settings<br>• CIS Level 1/2 benchmarks<br>• Microsoft Security Baseline<br>• DISA STIG implementation<br>• Custom baseline support<br>• Rollback capability | CIS: 95%+<br>NIST: High<br>PCI: Compliant |
-| **`Enable-PowerShellSecurity`** | Hardens PowerShell environment | • Constrained Language Mode<br>• Script Block Logging<br>• Module Logging<br>• Transcription<br>• AMSI integration<br>• JEA configuration | Blocks 90% of PS attacks<br>Full audit trail<br>Malware prevention |
+| **`Set-SecurityBaseline`** | Applies a set of security hardening configurations | • ~27 settings across UAC, firewall, Defender, network, account and system categories<br>• Basic / Recommended / Strict presets<br>• WhatIf/Confirm support (`SupportsShouldProcess`) | General hardening<br>WhatIf-first changes |
+| **`Enable-PowerShellSecurity`** | Hardens PowerShell environment | • Script Block Logging<br>• Module Logging<br>• Transcription<br>• Execution policy<br>• JEA mentioned only as a follow-up recommendation (not configured) | Full audit trail<br>PowerShell logging baseline |
| **`Enable-AuditPolicies`** | Configures advanced security auditing | • Process creation with command line<br>• Logon/Logoff tracking<br>• Object access monitoring<br>• Privilege use auditing<br>• System integrity monitoring<br>• Account management tracking | Complete visibility<br>Forensic capability<br>Compliance ready |
| **`Invoke-SecurityRemediation`** | Applies automated fixes for assessment findings | • Consumes Invoke-SecurityAssessment JSON or piped findings<br>• Curated map of 7 safe remediations (firewall, UAC, Defender RTP, SMBv1, Guest, PS logging, RDP NLA)<br>• Severity filter (`-MaxSeverity`)<br>• WhatIf/Confirm first (ConfirmImpact High)<br>• `-GenerateRollback` captures pre-change state<br>• Unmatched findings routed to ManualReview | Finding-to-fix loop<br>Verified changes<br>Rollback script |
@@ -602,7 +601,7 @@ The Windows Defender module provides comprehensive management and monitoring of
|----------|---------|---------------------|------------------|
| **`Get-DefenderStatus`** | Comprehensive Defender health check | • Real-time protection status<br>• Signature age and version<br>• Last scan results<br>• Threat history<br>• Exclusion audit<br>• Performance impact | Status monitoring<br>Health validation<br>Alert generation |
| **`Invoke-DefenderScan`** | Initiates custom antivirus scans | • Quick scan (critical areas)<br>• Full scan (complete system)<br>• Custom path scanning<br>• Offline scan capability<br>• Boot sector verification<br>• Performance optimization | Threat detection<br>Malware removal<br>System cleanup |
-| **`Update-DefenderConfiguration`** | Optimizes Defender settings | • Cloud protection level<br>• Sample submission<br>• PUA protection<br>• Network protection<br>• Exploit protection<br>• ASR rules configuration | Maximum protection<br>Zero-day defense<br>Behavior monitoring |
+| **`Update-DefenderConfiguration`** | Optimizes Defender settings | • Real-time protection toggle<br>• Cloud-delivered protection (MAPS)<br>• Automatic sample submission<br>• PUA protection<br>• Scheduled scan (day/time) | Configurable protection settings<br>WhatIf-first changes |
---
@@ -612,10 +611,10 @@ The Threat Hunting module provides proactive threat detection capabilities using
| Function | Purpose | Hunting Techniques | Detection Coverage |
|----------|---------|-------------------|-------------------|
-| **`Find-APTIndicators`** | Hunts for Advanced Persistent Threats | • 200+ behavioral patterns<br>• MITRE ATT&CK mapping<br>• Known APT group TTPs<br>• Command & Control patterns<br>• Data staging detection<br>• Stealth technique identification | Nation-state actors<br>Organized crime<br>Insider threats |
-| **`Find-DataExfiltration`** | Detects data theft attempts | • Large file transfers<br>• Compression before transfer<br>• Cloud upload monitoring<br>• DNS tunneling detection<br>• Encrypted channel analysis<br>• Removable media tracking | Data breaches<br>IP theft<br>Espionage |
-| **`Find-LateralMovement`** | Tracks attacker movement between systems | • RDP session analysis<br>• SMB connection monitoring<br>• WMI activity tracking<br>• PSRemoting detection<br>• Service creation<br>• Scheduled task deployment | Network propagation<br>Privilege escalation<br>Domain compromise |
-| **`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 |
+| **`Find-APTIndicators`** | Heuristic sweep for APT-style indicators | • Roughly 20-35 scored heuristic checks across 4 surfaces: services, scheduled tasks, registry persistence, network connections<br>• Whitelist filtering to suppress known-good software<br>• Severity scoring with Critical/High/Medium thresholds and an overall risk level<br>• No MITRE ATT&CK technique IDs attached | Heuristic indicator sweep<br>Scored findings<br>Risk-level summary |
+| **`Find-DataExfiltration`** | Detects data theft attempts | • Large file transfers (byte counting, `-ThresholdMB`)<br>• Compression before transfer<br>• Cloud upload monitoring (known cloud service endpoints)<br>• Data staging detection | Data staging<br>Large transfers<br>Cloud uploads |
+| **`Find-LateralMovement`** | Tracks attacker movement between systems | • RDP session analysis (4624 Type 10)<br>• SMB connection/share-access monitoring (445, 5140/5145)<br>• PSRemoting/WinRM activity (5985/5986, 4648 explicit credentials)<br>• Network logon review (4624 Type 3) | Network propagation<br>Suspicious remote sessions |
+| **`Find-LivingOffLand`** | Detects abuse of legitimate tools | • 15-entry curated LOLBin database (certutil, mshta, rundll32, wmic, bitsadmin, regsvr32, ...; note: powershell.exe is not an entry)<br>• Command-line matching against known abuse patterns per binary | 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>• Live threat feeds (URLhaus, Feodo Tracker, AbuseIPDB)<br>• Feed caching with freshness fallback<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 |
@@ -628,11 +627,11 @@ The Compliance module automates security framework validation and generates audi
| Function | Purpose | Frameworks Supported | Automation Level |
|----------|---------|---------------------|------------------|
-| **`Test-CISBenchmark`** | Validates CIS security controls | • CIS Level 1 (Basic)<br>• ~20 automated Level 1 checks<br>• Windows 10/11/Server<br>• Remediation scripts<br>• Detailed scoring | Automated pass/fail results<br>Evidence collection |
-| **`Test-NISTCompliance`** | Assesses NIST 800-53 controls | • Access Control (AC)<br>• Audit & Accountability (AU)<br>• System Integrity (SI)<br>• Incident Response (IR)<br>• Risk Assessment (RA)<br>• Control families mapping | Control validation<br>Gap analysis<br>Maturity scoring |
-| **`Test-PCI-DSS`** | Validates PCI-DSS requirements | • Network segmentation<br>• Access control<br>• Encryption validation<br>• Log monitoring<br>• Vulnerability management<br>• Security testing | Requirement mapping<br>Evidence generation<br>SAQ support |
+| **`Test-CISBenchmark`** | Validates CIS-style security controls | • CIS-inspired Level 1 (basic) checks<br>• 16 automated checks<br>• Windows 10/11/Server<br>• Text remediation guidance per check (not scripts)<br>• Detailed scoring | Automated pass/fail results<br>Evidence collection |
+| **`Test-NISTCompliance`** | Assesses selected NIST 800-53 controls | • 17 controls across 5 families<br>• Access Control (AC)<br>• Audit & Accountability (AU)<br>• Identification & Authentication (IA)<br>• System & Communications Protection (SC)<br>• Configuration Management (CM) | Control validation<br>Gap analysis<br>Maturity scoring |
+| **`Test-PCI-DSS`** | Validates PCI-DSS requirements | • 18 requirement checks (PCI-DSS 4.0)<br>• Network security controls<br>• Access control<br>• Encryption validation<br>• Log monitoring<br>• Vulnerability management | Requirement mapping<br>Evidence generation<br>SAQ support |
| **`Get-ComplianceReport`** | Generates comprehensive compliance reports | • Multi-framework dashboard<br>• Executive summaries<br>• Technical evidence<br>• Gap analysis<br>• Remediation roadmap<br>• Trend analysis | Professional reports<br>Audit-ready format<br>Action plans |
-| **`Export-ComplianceEvidence`** | Collects and packages audit evidence | • Automated screenshots<br>• Configuration exports<br>• Log extraction<br>• Policy documentation<br>• Change tracking<br>• Chain of custody | Complete evidence<br>Timestamp verification<br>Integrity hashing |
+| **`Export-ComplianceEvidence`** | Collects and packages audit evidence | • Configuration exports (secedit, auditpol, firewall rules, registry, gpresult)<br>• Log extraction (event logs, failed logons, PowerShell logs)<br>• Text status captures (Defender/firewall/BitLocker) — not graphical screenshots<br>• System inventory (software, users, groups, services, updates)<br>• Chain of custody documentation<br>• SHA-256 integrity hashing of the configuration exports and the final ZIP bundle | Complete evidence<br>Timestamp verification<br>Integrity hashing |
---
@@ -642,10 +641,10 @@ The Active Directory module provides specialized security assessment for AD envi
| Function | Purpose | Security Checks | Risk Areas |
|----------|---------|-----------------|------------|
-| **`Find-ADVulnerabilities`** | Comprehensive AD vulnerability scanning | • Kerberoasting targets (SPNs)<br>• ASREP roasting accounts<br>• Weak ACLs and permissions<br>• Unconstrained delegation<br>• Trust vulnerabilities<br>• GPO security issues | Account compromise<br>Privilege escalation<br>Lateral movement |
-| **`Find-ADBackdoors`** | Detects persistence in Active Directory | • AdminSDHolder modifications<br>• DCSync permissions (replication ACLs)<br>• SID history abuse<br>• Delegation misconfigurations<br>• Shadow credentials | Domain persistence<br>Privileged access<br>Stealth backdoors |
+| **`Find-ADVulnerabilities`** | AD vulnerability scanning | • Kerberoasting targets (accounts with SPNs)<br>• ASREP roasting accounts (pre-auth not required)<br>• Weak ACLs and permissions | Account compromise<br>Privilege escalation |
+| **`Find-ADBackdoors`** | Detects persistence in Active Directory | • AdminSDHolder modifications<br>• DCSync permissions (replication ACLs)<br>• SID history abuse<br>• Dangerous delegations (unconstrained, constrained with protocol transition) | Domain persistence<br>Privileged access<br>Stealth backdoors |
| **`Find-StaleADObjects`** | Identifies unused AD objects for cleanup | • Inactive user accounts<br>• Stale computer objects<br>• Empty security groups<br>• Orphaned objects<br>• Disabled accounts<br>• Service account audit | Attack surface reduction<br>Compliance cleanup<br>Performance improvement |
-| **`Test-ADSecurityPosture`** | Evaluates overall AD security health | • Password policy strength<br>• Kerberos configuration<br>• LDAP signing/channel binding<br>• Trust relationships<br>• LAPS deployment<br>• Tier model implementation | Domain hardening<br>Best practices<br>Security maturity |
+| **`Test-ADSecurityPosture`** | Evaluates overall AD security health | • Password policy strength<br>• Account lockout policy<br>• Domain controller review<br>• Optional trust inventory (`-IncludeTrusts`)<br>• Optional unlinked-GPO detection (`-IncludeGPO`) | Domain hardening<br>Best practices<br>Security maturity |
| **`Get-ADPasswordPolicy`** | Analyzes password security settings | • Default domain policy<br>• Fine-grained policies<br>• Complexity requirements<br>• History enforcement<br>• Lockout thresholds<br>• Expiration settings | Weak passwords<br>Brute force risk<br>Compliance gaps |
| **`Get-ADPrivilegedAccounts`** | Maps privileged access | • Domain/Enterprise Admins<br>• Custom admin groups<br>• Service accounts<br>• Delegation rights<br>• Schema admins<br>• Backup operators | Privilege creep<br>Excessive rights<br>Account security |
@@ -657,14 +656,14 @@ The Vulnerability module identifies, assesses, and prioritizes security weakness
| Function | Purpose | Assessment Areas | Priority Scoring |
|----------|---------|------------------|------------------|
-| **`Get-VulnerabilityAssessment`** | Comprehensive vulnerability scanning | • CVE identification<br>• Real NVD CVE matching (`-CheckCVEs`)<br>• CVSS scoring (v3.1)<br>• Exploit availability (EPSS)<br>• Patch availability<br>• Workaround options<br>• Asset criticality | Critical: CVSS 9.0+<br>High: CVSS 7.0-8.9<br>Medium: CVSS 4.0-6.9<br>Low: CVSS 0-3.9 |
+| **`Get-VulnerabilityAssessment`** | Comprehensive vulnerability scanning | • CVE identification<br>• Real NVD CVE matching (`-CheckCVEs`)<br>• CVSS scoring (v3.1)<br>• Patch availability | Critical: CVSS 9.0+<br>High: CVSS 7.0-8.9<br>Medium: CVSS 4.0-6.9<br>Low: CVSS 0-3.9 |
| **`Get-NVDCveData`** | Queries the NVD API 2.0 for real CVE data | • Keyword or CPE 2.3 name search<br>• Normalized CVE objects (ID, description, references)<br>• CVSS v3.1/v3.0/v2 severity and score<br>• Automatic pagination<br>• NVD rate-limit handling<br>• Optional API key for higher limits | CVSS base severity<br>(Critical/High/Medium/Low) |
-| **`Resolve-CpeName`** | Resolves installed products to CPE 2.3 names | • Curated offline table (~35 products)<br>• Optional NVD CPE API lookup (`-UseOnlineLookup -ApiKey`)<br>• Heuristic fallback (Low confidence)<br>• Version string normalization<br>• Confidence + MatchedBy provenance<br>• API key never logged | High: curated + version<br>Medium: curated/online<br>Low: heuristic |
+| **`Resolve-CpeName`** | Resolves installed products to CPE 2.3 names | • Curated offline table (~120 products, with vendor-scheme version translation)<br>• Optional NVD CPE API lookup (`-UseOnlineLookup -ApiKey`)<br>• Heuristic fallback (Low confidence)<br>• Version string normalization<br>• Confidence + MatchedBy provenance<br>• API key never logged | High: curated + version<br>Medium: curated/online<br>Low: heuristic |
| **`Get-SecurityMisconfigurations`** | Identifies configuration weaknesses | • Weak file permissions<br>• Default credentials<br>• Open network shares<br>• Service account issues<br>• Registry permissions<br>• Group Policy gaps | Exploitability rating<br>Impact assessment<br>Fix complexity |
| **`Find-EOLSoftware`** | Detects unsupported software | • End-of-life products<br>• Unsupported versions<br>• Legacy applications<br>• Missing security updates<br>• Vendor bulletins<br>• Migration paths | Support status<br>Risk exposure<br>Upgrade options |
-| **`Get-ExposedServices`** | Maps attack surface | • Internet-facing services<br>• Weak protocols (SMBv1, TLS 1.0)<br>• Default configurations<br>• Unnecessary services<br>• Port exposure<br>• Authentication methods | External exposure<br>Protocol weaknesses<br>Access controls |
-| **`Test-CertificateHealth`** | Certificate security validation | • Expiration monitoring<br>• Algorithm strength (RSA/ECC)<br>• Chain validation<br>• Revocation checking<br>• Trust store audit<br>• Key usage validation | Expiry risk<br>Crypto strength<br>Trust issues |
-| **`Test-PatchCompliance`** | Patch management assessment | • Missing critical patches<br>• Security bulletin coverage<br>• Update history analysis<br>• WSUS/SCCM compliance<br>• Third-party patches<br>• Rollback capability | Patch age<br>Severity rating<br>Exploit activity |
+| **`Get-ExposedServices`** | Maps attack surface | • Listening/internet-facing services<br>• Default configurations<br>• Unnecessary services<br>• Port exposure (incl. `-CustomPorts`)<br>• Authentication methods | External exposure<br>Open ports<br>Access controls |
+| **`Test-CertificateHealth`** | Certificate security validation | • Expiration monitoring<br>• Signature algorithm reporting<br>• Self-signed detection<br>• Chain validation<br>• Revocation checking (`-CheckRevocation`)<br>• Trust store review | Expiry risk<br>Chain/trust issues |
+| **`Test-PatchCompliance`** | Patch management assessment | • Missing critical patches<br>• Update history analysis<br>• Missing-update age/scoring | Patch age<br>Severity rating |
---
@@ -674,12 +673,12 @@ The Forensics module provides digital forensic capabilities for incident investi
| Function | Purpose | Forensic Capabilities | Evidence Types |
|----------|---------|----------------------|----------------|
-| **`Export-MemoryDump`** | Captures memory for analysis | • Full memory dump<br>• Process-specific dumps<br>• Minidump creation<br>• Crash dump analysis | RAM contents<br>Running processes<br>Network connections<br>Encryption keys |
-| **`Get-ArtifactCollection`** | Collects forensic artifacts | • Browser history (all browsers)<br>• Download history<br>• Temporary files<br>• Thumbnail cache<br>• Per-file SHA256 computed at acquisition<br>• Raw registry hive capture via `reg save`<br>• AcquisitionLog manifest block | User activity<br>File access<br>Internet activity<br>Deleted items |
+| **`Export-MemoryDump`** | Captures process memory for analysis | • Per-process memory dumps (not a full physical RAM capture)<br>• Sysinternals ProcDump when available (`-UseProcDump`)<br>• MiniDumpWriteDump (dbghelp) fallback<br>• Optional compression | Process memory dumps<br>Dump metadata |
+| **`Get-ArtifactCollection`** | Collects forensic artifacts | • Browser artifacts (Chrome and Edge Default profiles only)<br>• Download history<br>• Temporary files<br>• Thumbnail cache<br>• Per-file SHA256 computed at acquisition<br>• Raw registry hive capture via `reg save`<br>• AcquisitionLog manifest block | User activity<br>File access<br>Internet activity |
| **`Get-UserActivityArtifacts`** | Collects per-user activity artifacts for DFIR | • Recycle Bin `$I` parsing (v2 + best-effort v1 headers; path, size, deletion FILETIME)<br>• Recent/Desktop LNK resolution via WScript.Shell COM (unresolved off-Windows)<br>• JumpList enumeration (AutomaticDestinations; embedded targets not parsed)<br>• ActivitiesCache.db raw copy (no SQLite parsing)<br>• Optional CSV export (`-OutputPath`) | Deleted files<br>Opened documents<br>App usage evidence<br>Timeline databases |
-| **`Get-ExecutionArtifacts`** | Traces program execution | • Prefetch analysis<br>• ShimCache examination<br>• UserAssist decoding<br>• RecentDocs<br>• BAM/DAM analysis | Program execution<br>Timestamps<br>Frequency<br>User attribution |
+| **`Get-ExecutionArtifacts`** | Traces program execution | • Prefetch analysis<br>• ShimCache: raw binary data collected but NOT parsed (use ShimCacheParser for full decoding)<br>• UserAssist decoding<br>• RecentApps<br>• BAM/DAM analysis | Program execution<br>Timestamps<br>Frequency<br>User attribution |
| **`Get-FileSystemJournal`** | File-system journal & timestomp evidence via fsutil (requires elevation) | • USN journal parsing with reason decoding and executable-creation evidence<br>• MFT summary statistics (summary-level via fsutil — no raw $MFT record parsing)<br>• TimestompScan cross-checks file timestamps against USN journal creation records plus pre-2000/future anomalies — explicitly labeled heuristic<br>• `-DriveLetter`, `-MaxRecords`, optional CSV `-OutputPath` | Executable drops<br>USN journal activity<br>Timestomp indicators (heuristic) |
-| **`Get-USBHistory`** | USB device forensics | • Device enumeration<br>• First/Last connection<br>• Serial numbers<br>• Volume names<br>• Drive letters<br>• User correlation | Device usage<br>Data transfer<br>Timeline<br>User activity |
+| **`Get-USBHistory`** | USB device forensics | • Device enumeration<br>• FirstInstalled timestamp; `LastConnected` is reported as unknown (not collected)<br>• Serial numbers<br>• Volume names<br>• Drive letters<br>• User correlation | Device usage<br>Hardware inventory<br>User activity |
| **`New-ForensicTimeline`** | Timeline reconstruction | • Multi-source correlation<br>• Event sequencing<br>• File system timeline<br>• Registry timeline<br>• Log correlation<br>• Visual timeline generation | Incident timeline<br>Attack chain<br>User actions<br>System events |
---
@@ -690,9 +689,9 @@ The Cloud Security module extends security assessment capabilities to cloud plat
| Function | Purpose | Cloud Platforms | Key Assessments |
|----------|---------|-----------------|-----------------|
-| **`Get-CloudComplianceStatus`** | Cloud compliance validation | • Azure Policy compliance<br>• AWS Config rules<br>• Security Center scores<br>• Regulatory alignment<br>• Best practices<br>• CIS cloud benchmarks | Policy violations<br>Configuration drift<br>Compliance gaps |
-| **`Get-AzureADRiskySignIns`** | Detects risky authentication | • Impossible travel<br>• Anonymous IP addresses<br>• Malware-linked IPs<br>• Leaked credentials<br>• Atypical locations<br>• Risk score calculation | Account compromise<br>Credential theft<br>Suspicious activity |
-| **`Test-M365SecurityPosture`** | Microsoft 365 security assessment | • Secure Score analysis<br>• Conditional Access gaps<br>• MFA coverage<br>• DLP policy review<br>• Threat protection status<br>• Identity protection | Configuration weaknesses<br>Policy gaps<br>Security improvements |
+| **`Get-CloudComplianceStatus`** | Cloud compliance catalog (evaluation pending) | • Built-in control catalog for cloud frameworks<br>• Controls currently return `NotEvaluated` — automated Microsoft Graph/API evaluation is not implemented yet<br>• Compliance score is `$null` when nothing was evaluated (no fabricated statuses) | Honest unevaluated status<br>Coverage transparency |
+| **`Get-AzureADRiskySignIns`** | Retrieves risky authentication detections | • Passes through Entra ID risk detections (risk level/state as reported by Microsoft Graph — no own risk scoring)<br>• Filter by risk level and time window<br>• Optional risky-user listing (`-IncludeRiskyUsers`) | Entra ID risk detections<br>Compromised accounts<br>Suspicious activity |
+| **`Test-M365SecurityPosture`** | Microsoft 365 security assessment | • Conditional Access policy review (Microsoft Graph)<br>• Exchange Online / SharePoint / Teams posture checks<br>• MFA coverage<br>• DLP policy status reported as `NotEvaluated` (needs Purview compliance PowerShell)<br>• Threat protection status<br>• Identity protection | Configuration weaknesses<br>Policy gaps<br>Security improvements |
---
@@ -704,8 +703,8 @@ 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 | HTML dashboard<br>PDF (requires wkhtmltopdf) |
-| **`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 |
+| **`New-SecurityDashboard`** | Static HTML security dashboard snapshot | • Security metrics summary<br>• Risk indicators<br>• Compliance status<br>• Alert summary<br>• Optional auto-reload via meta-refresh (`-AutoRefreshSeconds`) — the data itself is a point-in-time snapshot | HTML5 responsive<br>Optional meta-refresh<br>Export capable |
+| **`New-ConsolidatedReport`** | Single interactive report combining key collectors | • 6 collectors: Assessment, Defender, Compliance, ThreatHunting, Vulnerability, Forensics<br>• Chart.js severity doughnut (loaded from the jsDelivr CDN — viewing charts requires internet)<br>• Category score bar charts<br>• Offline mode from saved JSON<br>• Section status tracking<br>• Raw data export | HTML report<br>Interactive charts (CDN)<br>JSON export |
---
@@ -838,7 +837,7 @@ The full feature set is documented in the module tables above — this section o
**Quality infrastructure:**
-- 🧪 **Pester test suite** (`tests/`) covering the public API surface plus real-Windows smoke tests and locale-regression fixtures (now 498 tests)
+- 🧪 **Pester test suite** (`tests/`) covering the public API surface plus real-Windows smoke tests and locale-regression fixtures (now 518 tests)
- ⚙️ **GitHub Actions CI** (`.github/workflows/ci.yml`) on windows-latest: PSScriptAnalyzer Error gate, module import verified under both **PowerShell 7 (pwsh)** and **Windows PowerShell 5.1**, plus the full Pester suite and a real-Windows smoke job
### 📦 Already in the Toolbox (v1.0.0)
@@ -863,7 +862,7 @@ Everything below shipped with the original release and keeps getting sharper:
## 🎯 Use Case Scenarios
### For Security Operations Centers (SOC)
-- **24/7 Monitoring**: Continuous threat detection and alerting
+- **On-Demand & Scheduled Scanning**: Automated recurring scans with alerting
- **Incident Response**: Rapid containment and investigation
- **Threat Hunting**: Proactive APT detection
- **Metrics Tracking**: KPI/KRI dashboards
@@ -890,21 +889,22 @@ Everything below shipped with the original release and keeps getting sharper:
## 📈 Performance & Optimization
-### Scalability Metrics
-
-| Environment Size | Scan Time | Resource Usage | Optimization |
-|-----------------|-----------|----------------|--------------|
-| **1-10 Systems** | 5 minutes | 200MB RAM, 15% CPU | Single-threaded |
-| **10-100 Systems** | 45 minutes | 500MB RAM, 25% CPU | 10 parallel threads |
-| **100-1000 Systems** | 4 hours | 1GB RAM, 30% CPU | 20 parallel threads |
-| **1000+ Systems** | 8 hours | 2GB RAM, 40% CPU | Distributed scanning |
+Actual scan times depend on the target's hardware, event-log sizes and the modules selected — measure on your own systems rather than trusting generic figures.
### Performance Tuning
-- **Parallel Processing**: Configurable thread pools
-- **Smart Caching**: Reduce redundant operations
-- **Selective Scanning**: Module-specific execution
-- **Resource Throttling**: CPU/Memory limits
-- **Network Optimization**: Bandwidth management
+- **Parallel Processing**: Multi-system scans run in parallel (up to 50 threads) with configurable throttling
+- **Per-Host Timeouts**: Connectivity probes and per-host timeout controls in fleet scans
+- **Smart Caching**: Threat-intel feeds are cached with freshness-aware fallback
+- **Selective Scanning**: Run only the modules and checks you need via function parameters
+
+---
+
+## ⚠️ Known Limitations
+
+- **DISM/SFC verdicts rely on CBS.log markers** — `Test-SystemIntegrity` interprets servicing-log markers rather than performing a full image analysis.
+- **USN journal parsing requires English-locale `fsutil` output** — `Get-FileSystemJournal` parses `fsutil` text; full locale-invariant `FSCTL_READ_USN_JOURNAL` parsing is on the [v1.7 roadmap](#-roadmap).
+- **Cloud compliance is a catalog, not an evaluation** — `Get-CloudComplianceStatus` returns `NotEvaluated` until framework-specific Microsoft Graph queries are implemented.
+- **No in-module memory acquisition** — full RAM capture requires external tools (WinPMEM, DumpIt, Magnet RAM Capture); `Export-MemoryDump` creates per-process dumps.
---
@@ -950,7 +950,6 @@ We welcome contributions from the security community!
- Include Pester tests for new functions
- Update documentation
- Sign commits with GPG
-- Respect code of conduct
### Development Setup
```powershell
@@ -1002,11 +1001,11 @@ We offer professional services to help organizations maximize the value of this
### 🏢 Enterprise Inquiries
-For large-scale deployments, custom licensing, or enterprise support contracts:
+For large-scale deployments or enterprise support contracts:
**Enterprise Contact**: [email protected]
-We work with Fortune 500 companies, government agencies, and organizations of all sizes to implement robust security monitoring solutions.
+We work with organizations of all sizes to implement robust security monitoring solutions.
---
@@ -1096,10 +1095,10 @@ Supporting the development of enterprise security tools:
---
-**🔒 Securing Windows Environments Since 2022**
+**🔒 Securing Windows Environments Since 2025**
**Made with ❤️ and ☕ by the Security Community**
-**© 2025 Windows Security Audit Module - Enterprise Security Democratized**
+**© 2025-2026 Windows Security Audit Module - Enterprise Security Democratized**
</div>
diff --git a/Reporting/Get-SecurityMetrics.ps1 b/Reporting/Get-SecurityMetrics.ps1
index 2ed8332..6ae11d7 100644
--- a/Reporting/Get-SecurityMetrics.ps1
+++ b/Reporting/Get-SecurityMetrics.ps1
@@ -186,6 +186,8 @@ function Get-SecurityMetrics {
ComplianceScore = 0
ThreatLevel = "Minimal"
HealthStatus = "Healthy"
+ DataCompleteness = $null
+ FailedCollectors = @()
# Findings aggregation
Findings = @{
@@ -433,6 +435,7 @@ function Get-SecurityMetrics {
$totalFunctions = 0
$successfulFunctions = 0
$failedFunctions = 0
+ $failedCollectors = @()
# ============================================
# CORE MODULE (4 functions)
@@ -466,6 +469,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-SecurityBaseline: $_"
+ $failedCollectors += 'Get-SecurityBaseline'
}
# Get-SystemInfo
@@ -487,6 +491,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-SystemInfo: $_"
+ $failedCollectors += 'Get-SystemInfo'
}
# Test-SystemIntegrity
@@ -519,6 +524,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Test-SystemIntegrity: $_"
+ $failedCollectors += 'Test-SystemIntegrity'
}
# Invoke-SecurityAssessment
@@ -540,6 +546,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Invoke-SecurityAssessment: $_"
+ $failedCollectors += 'Invoke-SecurityAssessment'
}
$script:metrics.Performance.ModuleTimes['Core'] = [Math]::Round(((Get-Date) - $coreStart).TotalSeconds, 2)
@@ -567,6 +574,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Find-PersistenceMechanisms: $_"
+ $failedCollectors += 'Find-PersistenceMechanisms'
}
# Find-SuspiciousProcesses
@@ -579,6 +587,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Find-SuspiciousProcesses: $_"
+ $failedCollectors += 'Find-SuspiciousProcesses'
}
# Find-SuspiciousAuthentication
@@ -597,6 +606,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Find-SuspiciousAuthentication: $_"
+ $failedCollectors += 'Find-SuspiciousAuthentication'
}
# Find-LateralMovement
@@ -613,6 +623,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Find-LateralMovement: $_"
+ $failedCollectors += 'Find-LateralMovement'
}
# Find-APTIndicators
@@ -629,6 +640,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Find-APTIndicators: $_"
+ $failedCollectors += 'Find-APTIndicators'
}
# Find-LivingOffLand
@@ -645,6 +657,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Find-LivingOffLand: $_"
+ $failedCollectors += 'Find-LivingOffLand'
}
# Find-DataExfiltration
@@ -661,6 +674,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Find-DataExfiltration: $_"
+ $failedCollectors += 'Find-DataExfiltration'
}
# Find-NetworkAnomalies
@@ -677,6 +691,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Find-NetworkAnomalies: $_"
+ $failedCollectors += 'Find-NetworkAnomalies'
}
# Calculate total threats
@@ -741,6 +756,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-EventLogAnalysis: $_"
+ $failedCollectors += 'Get-EventLogAnalysis'
}
# Get-RegistryAnalysis
@@ -759,6 +775,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-RegistryAnalysis: $_"
+ $failedCollectors += 'Get-RegistryAnalysis'
}
# Get-FileSystemAnalysis
@@ -779,6 +796,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-FileSystemAnalysis: $_"
+ $failedCollectors += 'Get-FileSystemAnalysis'
}
# Get-MemoryAnalysis
@@ -797,6 +815,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-MemoryAnalysis: $_"
+ $failedCollectors += 'Get-MemoryAnalysis'
}
# Get-ExposedServices
@@ -815,6 +834,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-ExposedServices: $_"
+ $failedCollectors += 'Get-ExposedServices'
}
# Get-SecurityMisconfigurations
@@ -827,6 +847,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-SecurityMisconfigurations: $_"
+ $failedCollectors += 'Get-SecurityMisconfigurations'
}
$script:metrics.Performance.ModuleTimes['Analysis'] = [Math]::Round(((Get-Date) - $analStart).TotalSeconds, 2)
@@ -883,6 +904,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Test-CISBenchmark: $_"
+ $failedCollectors += 'Test-CISBenchmark'
}
# Test-NISTCompliance
@@ -928,6 +950,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Test-NISTCompliance: $_"
+ $failedCollectors += 'Test-NISTCompliance'
}
# Test-PCI-DSS
@@ -969,6 +992,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Test-PCI-DSS: $_"
+ $failedCollectors += 'Test-PCI-DSS'
}
# Get-ComplianceReport
@@ -980,6 +1004,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-ComplianceReport: $_"
+ $failedCollectors += 'Get-ComplianceReport'
}
# Test-PatchCompliance
@@ -996,6 +1021,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Test-PatchCompliance: $_"
+ $failedCollectors += 'Test-PatchCompliance'
}
# Calculate overall compliance - NULL SAFE with @() cast
@@ -1059,6 +1085,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-ADPrivilegedAccounts: $_"
+ $failedCollectors += 'Get-ADPrivilegedAccounts'
}
# Find-ADVulnerabilities
@@ -1071,6 +1098,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Find-ADVulnerabilities: $_"
+ $failedCollectors += 'Find-ADVulnerabilities'
}
# Test-ADSecurityPosture
@@ -1082,6 +1110,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Test-ADSecurityPosture: $_"
+ $failedCollectors += 'Test-ADSecurityPosture'
}
# Find-ADBackdoors
@@ -1094,6 +1123,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Find-ADBackdoors: $_"
+ $failedCollectors += 'Find-ADBackdoors'
}
# Find-StaleADObjects
@@ -1106,6 +1136,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Find-StaleADObjects: $_"
+ $failedCollectors += 'Find-StaleADObjects'
}
# Get-ADPasswordPolicy
@@ -1126,6 +1157,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-ADPasswordPolicy: $_"
+ $failedCollectors += 'Get-ADPasswordPolicy'
}
$script:metrics.ActiveDirectory.LastADScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
@@ -1143,7 +1175,12 @@ function Get-SecurityMetrics {
Write-Host "`n[Cloud Security Module Metrics]" -ForegroundColor Cyan
$cloudStart = Get-Date
- $mgContext = Get-MgContext -ErrorAction SilentlyContinue
+ $mgContext = $null
+ try {
+ $mgContext = Get-MgContext -ErrorAction Stop
+ } catch {
+ Write-Verbose " Get-MgContext unavailable: $_"
+ }
if ($mgContext) {
$script:metrics.Cloud.Enabled = $true
$script:metrics.Cloud.ConnectedTenant = if ($mgContext.PSObject.Properties['TenantId']) { $mgContext.TenantId } else { "Unknown" }
@@ -1158,6 +1195,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-AzureADRiskySignIns: $_"
+ $failedCollectors += 'Get-AzureADRiskySignIns'
}
# Test-M365SecurityPosture
@@ -1172,6 +1210,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Test-M365SecurityPosture: $_"
+ $failedCollectors += 'Test-M365SecurityPosture'
}
# Get-CloudComplianceStatus
@@ -1183,6 +1222,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-CloudComplianceStatus: $_"
+ $failedCollectors += 'Get-CloudComplianceStatus'
}
$script:metrics.Cloud.LastCloudScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
@@ -1234,6 +1274,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-VulnerabilityAssessment: $_"
+ $failedCollectors += 'Get-VulnerabilityAssessment'
}
# Find-EOLSoftware
@@ -1246,6 +1287,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Find-EOLSoftware: $_"
+ $failedCollectors += 'Find-EOLSoftware'
}
# Test-CertificateHealth
@@ -1270,6 +1312,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Test-CertificateHealth: $_"
+ $failedCollectors += 'Test-CertificateHealth'
}
$script:metrics.Vulnerability.LastVulnScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
@@ -1302,6 +1345,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-ThreatIntelligence: $_"
+ $failedCollectors += 'Get-ThreatIntelligence'
}
# Get-MITREAttackMapping
@@ -1322,6 +1366,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-MITREAttackMapping: $_"
+ $failedCollectors += 'Get-MITREAttackMapping'
}
$script:metrics.ThreatHunting.LastHuntDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
@@ -1350,6 +1395,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-ArtifactCollection: $_"
+ $failedCollectors += 'Get-ArtifactCollection'
}
# Get-ExecutionArtifacts
@@ -1374,6 +1420,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-ExecutionArtifacts: $_"
+ $failedCollectors += 'Get-ExecutionArtifacts'
}
# Get-USBHistory
@@ -1386,6 +1433,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-USBHistory: $_"
+ $failedCollectors += 'Get-USBHistory'
}
# Invoke-ForensicCollection, Export-MemoryDump, New-ForensicTimeline
@@ -1454,6 +1502,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Get-DefenderStatus: $_"
+ $failedCollectors += 'Get-DefenderStatus'
}
# Invoke-DefenderScan - skip for metrics
@@ -1469,6 +1518,7 @@ function Get-SecurityMetrics {
} catch {
$failedFunctions++
Write-Verbose " Update-DefenderConfiguration: $_"
+ $failedCollectors += 'Update-DefenderConfiguration'
}
$script:metrics.Performance.ModuleTimes['WindowsDefender'] = [Math]::Round(((Get-Date) - $defStart).TotalSeconds, 2)
@@ -1556,11 +1606,26 @@ if ($script:metrics.WindowsDefender.Enabled -and $signatureAge -gt 7) {
$script:metrics.OverallSecurityScore = [Math]::Max(0, [Math]::Min(100, 100 - $penalty))
-Write-Host " Overall Security Score: $($script:metrics.OverallSecurityScore)%" -ForegroundColor $(
- if ($script:metrics.OverallSecurityScore -ge 80) { 'Green' }
+# Data completeness: the score is only as trustworthy as the collectors behind it
+$script:metrics.DataCompleteness = "$successfulFunctions of $totalFunctions collectors succeeded ($failedFunctions failed)"
+$script:metrics.FailedCollectors = @($failedCollectors)
+
+$majorityFailed = ($totalFunctions -gt 0) -and ($failedFunctions * 2 -gt $totalFunctions)
+if ($majorityFailed) {
+ Write-Warning "More than 50% of collectors failed ($failedFunctions of $totalFunctions): $($failedCollectors -join ', '). OverallSecurityScore is reported as null because the collected data is too incomplete to score reliably."
+ $script:metrics.OverallSecurityScore = $null
+}
+elseif ($failedFunctions -gt 0) {
+ Write-Warning "$failedFunctions of $totalFunctions collectors failed: $($failedCollectors -join ', '). The overall score is based on partial data (see DataCompleteness)."
+}
+
+Write-Host " Overall Security Score: $(if ($null -ne $script:metrics.OverallSecurityScore) { "$($script:metrics.OverallSecurityScore)%" } else { 'N/A (insufficient data)' })" -ForegroundColor $(
+ if ($null -eq $script:metrics.OverallSecurityScore) { 'Yellow' }
+ elseif ($script:metrics.OverallSecurityScore -ge 80) { 'Green' }
elseif ($script:metrics.OverallSecurityScore -ge 60) { 'Yellow' }
else { 'Red' }
)
+Write-Host " Data Completeness: $($script:metrics.DataCompleteness)" -ForegroundColor $(if ($failedFunctions -eq 0) { 'Green' } else { 'Yellow' })
# Determine risk level
$script:metrics.RiskLevel =
@@ -1603,12 +1668,18 @@ Write-Host " Threat Level: $($script:metrics.ThreatLevel)" -ForegroundColor $(
# Health status
$script:metrics.HealthStatus =
- if ($script:metrics.OverallSecurityScore -ge 90 -and $script:metrics.ThreatLevel -eq 'Minimal') { "Excellent" }
+ if ($null -eq $script:metrics.OverallSecurityScore) { "Unknown" }
+ elseif ($script:metrics.OverallSecurityScore -ge 90 -and $script:metrics.ThreatLevel -eq 'Minimal') { "Excellent" }
elseif ($script:metrics.OverallSecurityScore -ge 80 -and $script:metrics.ThreatLevel -in @('Minimal', 'Low')) { "Good" }
elseif ($script:metrics.OverallSecurityScore -ge 60) { "Fair" }
elseif ($script:metrics.OverallSecurityScore -ge 40) { "Poor" }
else { "Critical" }
+# Any collector failure reduces confidence: health can never be 'Excellent' on partial data
+if ($failedFunctions -gt 0 -and $script:metrics.HealthStatus -eq 'Excellent') {
+ $script:metrics.HealthStatus = 'Good'
+}
+
Write-Host " Health Status: $($script:metrics.HealthStatus)" -ForegroundColor $(
switch ($script:metrics.HealthStatus) {
'Excellent' { 'Green' }
@@ -1888,7 +1959,7 @@ $script:metrics.Recommendations.Total =
Write-Host " Function Success Rate: $($script:metrics.Performance.SuccessRate)%" -ForegroundColor White
Write-Host "`nKey Metrics:" -ForegroundColor Cyan
- Write-Host " Security Score: $($script:metrics.OverallSecurityScore)%" -ForegroundColor White
+ Write-Host " Security Score: $(if ($null -ne $script:metrics.OverallSecurityScore) { "$($script:metrics.OverallSecurityScore)%" } else { 'N/A (insufficient data)' })" -ForegroundColor White
Write-Host " Health Status: $($script:metrics.HealthStatus)" -ForegroundColor White
Write-Host " Risk Level: $($script:metrics.RiskLevel)" -ForegroundColor White
Write-Host " Threat Level: $($script:metrics.ThreatLevel)" -ForegroundColor White
diff --git a/Reporting/New-ConsolidatedReport.ps1 b/Reporting/New-ConsolidatedReport.ps1
index 514b4d4..a07e5d2 100644
--- a/Reporting/New-ConsolidatedReport.ps1
+++ b/Reporting/New-ConsolidatedReport.ps1
@@ -600,7 +600,7 @@ function Generate-ConsolidatedReportHTML {
[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(" <script src='https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js' integrity='sha384-e6nUZLBkQ86NJ6TVVKAeSaK8jWa3NhkYWZFomE39AvDbQWeie9PlQqM3pmYW5d1g' crossorigin='anonymous'></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; }")
diff --git a/Reporting/New-SecurityDashboard.ps1 b/Reporting/New-SecurityDashboard.ps1
index 3a35b09..9aaafb4 100644
--- a/Reporting/New-SecurityDashboard.ps1
+++ b/Reporting/New-SecurityDashboard.ps1
@@ -1180,7 +1180,7 @@ function Generate-DashboardHTML {
}
if ($IncludeCharts) {
- [void]$html.AppendLine(" <script src='https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js'></script>")
+ [void]$html.AppendLine(" <script src='https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js' integrity='sha384-e6nUZLBkQ86NJ6TVVKAeSaK8jWa3NhkYWZFomE39AvDbQWeie9PlQqM3pmYW5d1g' crossorigin='anonymous'></script>")
}
# CSS Styles
diff --git a/Response/Invoke-ForensicCollection.ps1 b/Response/Invoke-ForensicCollection.ps1
index 661a663..449e9ec 100644
--- a/Response/Invoke-ForensicCollection.ps1
+++ b/Response/Invoke-ForensicCollection.ps1
@@ -88,6 +88,16 @@ function Invoke-ForensicCollection {
Add-Content -Path $logFile -Value $logMessage
Write-Verbose $Message
}
+
+ # Projects each row to a plain object with string fields escaped against
+ # CSV formula injection (Protect-CsvField) before Export-Csv
+ filter Protect-CsvRowFields {
+ $escaped = [ordered]@{}
+ foreach ($prop in $_.PSObject.Properties) {
+ $escaped[$prop.Name] = if ($prop.Value -is [string]) { Protect-CsvField $prop.Value } else { $prop.Value }
+ }
+ [PSCustomObject]$escaped
+ }
Write-CollectionLog "Forensic collection initiated - Type: $CollectionType"
}
@@ -107,11 +117,11 @@ function Invoke-ForensicCollection {
Get-ComputerInfo | ConvertTo-Json -Depth 5 | Out-File (Join-Path $sysInfoPath "ComputerInfo.json") -Encoding UTF8
# Environment variables
- Get-ChildItem Env: | Export-Csv (Join-Path $sysInfoPath "EnvironmentVariables.csv") -NoTypeInformation
-
+ Get-ChildItem Env: | Protect-CsvRowFields | Export-Csv (Join-Path $sysInfoPath "EnvironmentVariables.csv") -NoTypeInformation
+
# Local users and groups
- Get-LocalUser | Export-Csv (Join-Path $sysInfoPath "LocalUsers.csv") -NoTypeInformation
- Get-LocalGroup | Export-Csv (Join-Path $sysInfoPath "LocalGroups.csv") -NoTypeInformation
+ Get-LocalUser | Protect-CsvRowFields | Export-Csv (Join-Path $sysInfoPath "LocalUsers.csv") -NoTypeInformation
+ Get-LocalGroup | Protect-CsvRowFields | Export-Csv (Join-Path $sysInfoPath "LocalGroups.csv") -NoTypeInformation
$results.ArtifactsCollected += "System Information"
Write-CollectionLog "Collected system information"
@@ -128,6 +138,7 @@ function Invoke-ForensicCollection {
# Process list with details
Get-Process | Select-Object Name, Id, Path, CommandLine, StartTime, CPU, WorkingSet64, Threads |
+ Protect-CsvRowFields |
Export-Csv (Join-Path $procPath "Processes.csv") -NoTypeInformation
# Process modules
@@ -139,15 +150,16 @@ function Invoke-ForensicCollection {
ModuleName, FileName, Size
} catch {}
}
- $procModules | Export-Csv (Join-Path $procPath "ProcessModules.csv") -NoTypeInformation
-
+ $procModules | Protect-CsvRowFields | Export-Csv (Join-Path $procPath "ProcessModules.csv") -NoTypeInformation
+
# Services
- Get-Service | Export-Csv (Join-Path $procPath "Services.csv") -NoTypeInformation
+ Get-Service | Protect-CsvRowFields | Export-Csv (Join-Path $procPath "Services.csv") -NoTypeInformation
Get-CimInstance Win32_Service | Select-Object Name, DisplayName, PathName, StartMode, State, StartName |
+ Protect-CsvRowFields |
Export-Csv (Join-Path $procPath "ServicesDetailed.csv") -NoTypeInformation
-
+
# Scheduled tasks
- Get-ScheduledTask | Export-Csv (Join-Path $procPath "ScheduledTasks.csv") -NoTypeInformation
+ Get-ScheduledTask | Protect-CsvRowFields | Export-Csv (Join-Path $procPath "ScheduledTasks.csv") -NoTypeInformation
$results.ArtifactsCollected += "Process Information"
Write-CollectionLog "Collected process information"
@@ -163,27 +175,27 @@ function Invoke-ForensicCollection {
$netPath = Join-Path $collectionPath 'Network'
# Network adapters
- Get-NetAdapter | Export-Csv (Join-Path $netPath "NetworkAdapters.csv") -NoTypeInformation
- Get-NetIPAddress | Export-Csv (Join-Path $netPath "IPAddresses.csv") -NoTypeInformation
- Get-NetRoute | Export-Csv (Join-Path $netPath "Routes.csv") -NoTypeInformation
-
+ Get-NetAdapter | Protect-CsvRowFields | Export-Csv (Join-Path $netPath "NetworkAdapters.csv") -NoTypeInformation
+ Get-NetIPAddress | Protect-CsvRowFields | Export-Csv (Join-Path $netPath "IPAddresses.csv") -NoTypeInformation
+ Get-NetRoute | Protect-CsvRowFields | Export-Csv (Join-Path $netPath "Routes.csv") -NoTypeInformation
+
# Active connections
- Get-NetTCPConnection | Export-Csv (Join-Path $netPath "TCPConnections.csv") -NoTypeInformation
- Get-NetUDPEndpoint | Export-Csv (Join-Path $netPath "UDPEndpoints.csv") -NoTypeInformation
-
+ Get-NetTCPConnection | Protect-CsvRowFields | Export-Csv (Join-Path $netPath "TCPConnections.csv") -NoTypeInformation
+ Get-NetUDPEndpoint | Protect-CsvRowFields | Export-Csv (Join-Path $netPath "UDPEndpoints.csv") -NoTypeInformation
+
# DNS cache
- Get-DnsClientCache | Export-Csv (Join-Path $netPath "DNSCache.csv") -NoTypeInformation
-
+ Get-DnsClientCache | Protect-CsvRowFields | Export-Csv (Join-Path $netPath "DNSCache.csv") -NoTypeInformation
+
# Firewall rules
- Get-NetFirewallRule | Export-Csv (Join-Path $netPath "FirewallRules.csv") -NoTypeInformation
- Get-NetFirewallProfile | Export-Csv (Join-Path $netPath "FirewallProfiles.csv") -NoTypeInformation
-
+ Get-NetFirewallRule | Protect-CsvRowFields | Export-Csv (Join-Path $netPath "FirewallRules.csv") -NoTypeInformation
+ Get-NetFirewallProfile | Protect-CsvRowFields | Export-Csv (Join-Path $netPath "FirewallProfiles.csv") -NoTypeInformation
+
# ARP cache
- Get-NetNeighbor | Export-Csv (Join-Path $netPath "ARPCache.csv") -NoTypeInformation
-
+ Get-NetNeighbor | Protect-CsvRowFields | Export-Csv (Join-Path $netPath "ARPCache.csv") -NoTypeInformation
+
# Network shares
- Get-SmbShare | Export-Csv (Join-Path $netPath "Shares.csv") -NoTypeInformation
- Get-SmbSession | Export-Csv (Join-Path $netPath "SMBSessions.csv") -NoTypeInformation
+ Get-SmbShare | Protect-CsvRowFields | Export-Csv (Join-Path $netPath "Shares.csv") -NoTypeInformation
+ Get-SmbSession | Protect-CsvRowFields | Export-Csv (Join-Path $netPath "SMBSessions.csv") -NoTypeInformation
$results.ArtifactsCollected += "Network Information"
Write-CollectionLog "Collected network information"
@@ -202,21 +214,25 @@ function Invoke-ForensicCollection {
# Security events (last 7 days)
Get-WinEvent -FilterHashtable @{LogName='Security'; StartTime=(Get-Date).AddDays(-7)} -MaxEvents 10000 -ErrorAction SilentlyContinue |
Select-Object TimeCreated, Id, LevelDisplayName, Message |
+ Protect-CsvRowFields |
Export-Csv (Join-Path $eventPath "Security_Recent.csv") -NoTypeInformation
-
+
# System events (last 7 days)
Get-WinEvent -FilterHashtable @{LogName='System'; StartTime=(Get-Date).AddDays(-7)} -MaxEvents 10000 -ErrorAction SilentlyContinue |
Select-Object TimeCreated, Id, LevelDisplayName, Message |
+ Protect-CsvRowFields |
Export-Csv (Join-Path $eventPath "System_Recent.csv") -NoTypeInformation
-
+
# Application events (last 7 days)
Get-WinEvent -FilterHashtable @{LogName='Application'; StartTime=(Get-Date).AddDays(-7)} -MaxEvents 10000 -ErrorAction SilentlyContinue |
Select-Object TimeCreated, Id, LevelDisplayName, Message |
+ Protect-CsvRowFields |
Export-Csv (Join-Path $eventPath "Application_Recent.csv") -NoTypeInformation
-
+
# PowerShell logs
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; StartTime=(Get-Date).AddDays(-7)} -MaxEvents 5000 -ErrorAction SilentlyContinue |
Select-Object TimeCreated, Id, Message |
+ Protect-CsvRowFields |
Export-Csv (Join-Path $eventPath "PowerShell_Recent.csv") -NoTypeInformation
$results.ArtifactsCollected += "Event Logs"
@@ -250,18 +266,18 @@ function Invoke-ForensicCollection {
Get-ItemProperty -Path $key | Select-Object PSPath, PSChildName, *
}
}
- $runEntries | Export-Csv (Join-Path $regPath "RunKeys.csv") -NoTypeInformation
-
+ $runEntries | Protect-CsvRowFields | Export-Csv (Join-Path $regPath "RunKeys.csv") -NoTypeInformation
+
# Installed software
$software = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* |
Where-Object { $_.DisplayName } |
Select-Object DisplayName, Publisher, InstallDate, DisplayVersion
- $software | Export-Csv (Join-Path $regPath "InstalledSoftware.csv") -NoTypeInformation
-
+ $software | Protect-CsvRowFields | Export-Csv (Join-Path $regPath "InstalledSoftware.csv") -NoTypeInformation
+
# USB history
$usb = Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Enum\USBSTOR\* -ErrorAction SilentlyContinue |
Select-Object PSChildName, FriendlyName
- $usb | Export-Csv (Join-Path $regPath "USBHistory.csv") -NoTypeInformation
+ $usb | Protect-CsvRowFields | Export-Csv (Join-Path $regPath "USBHistory.csv") -NoTypeInformation
$results.ArtifactsCollected += "Registry Artifacts"
Write-CollectionLog "Collected registry artifacts"
@@ -290,21 +306,23 @@ function Invoke-ForensicCollection {
Select-Object FullName, Name, Length, CreationTime, LastWriteTime
}
}
- $recentFiles | Export-Csv (Join-Path $fsPath "RecentTempFiles.csv") -NoTypeInformation
-
+ $recentFiles | Protect-CsvRowFields | Export-Csv (Join-Path $fsPath "RecentTempFiles.csv") -NoTypeInformation
+
# Prefetch files
if (Test-Path "$env:SystemRoot\Prefetch") {
Get-ChildItem "$env:SystemRoot\Prefetch" -Filter *.pf |
Select-Object Name, Length, CreationTime, LastWriteTime, LastAccessTime |
+ Protect-CsvRowFields |
Export-Csv (Join-Path $fsPath "Prefetch.csv") -NoTypeInformation
}
-
+
# Recent downloads
$downloadsPath = "$env:USERPROFILE\Downloads"
if (Test-Path $downloadsPath) {
Get-ChildItem $downloadsPath -File -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-30) } |
Select-Object FullName, Name, Length, CreationTime, LastWriteTime |
+ Protect-CsvRowFields |
Export-Csv (Join-Path $fsPath "RecentDownloads.csv") -NoTypeInformation
}
@@ -419,6 +437,7 @@ if ($null -ne (Get-Variable -Name 'recentFiles' -ErrorAction SilentlyContinue) -
$timeline | Sort-Object Timestamp -Descending |
+ Protect-CsvRowFields |
Export-Csv (Join-Path $timelinePath "Timeline.csv") -NoTypeInformation
$results.ArtifactsCollected += "Timeline"
@@ -445,7 +464,7 @@ if ($null -ne (Get-Variable -Name 'recentFiles' -ErrorAction SilentlyContinue) -
Size = $_.Length
}
}
- $hashManifest | Export-Csv (Join-Path $collectionPath "HashManifest.csv") -NoTypeInformation
+ $hashManifest | Protect-CsvRowFields | Export-Csv (Join-Path $collectionPath "HashManifest.csv") -NoTypeInformation
Write-CollectionLog "Collection completed successfully"
diff --git a/Response/Invoke-IncidentResponse.ps1 b/Response/Invoke-IncidentResponse.ps1
index a7dc582..2dd6cea 100644
--- a/Response/Invoke-IncidentResponse.ps1
+++ b/Response/Invoke-IncidentResponse.ps1
@@ -22,7 +22,7 @@ function Invoke-IncidentResponse {
PSCustomObject with incident response actions and results
#>
- [CmdletBinding(SupportsShouldProcess)]
+ [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param(
[Parameter(Mandatory = $true)]
[ValidateSet('Low', 'Medium', 'High', 'Critical')]
@@ -46,10 +46,14 @@ function Invoke-IncidentResponse {
Write-Host "Severity Level: $Severity" -ForegroundColor Red
Write-Host "Timestamp: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow
- # Check for admin privileges
- $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
- if (-not $isAdmin) {
- throw "Incident Response requires Administrator privileges!"
+ # Check for admin privileges (Windows-only check; the WindowsPrincipal APIs
+ # do not exist on other platforms, where the destructive cmdlets below are
+ # unavailable anyway)
+ if ($env:OS -eq 'Windows_NT') {
+ $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
+ if (-not $isAdmin) {
+ throw "Incident Response requires Administrator privileges!"
+ }
}
# Create output directory
@@ -147,8 +151,10 @@ function Invoke-IncidentResponse {
Write-IRLog "Error scanning network: $_" 'ERROR'
}
- # Step 3: Network Isolation (if requested or Critical severity)
- if ($IsolateSystem -or $Severity -eq 'Critical') {
+ # Step 3: Network Isolation (only when explicitly requested via -IsolateSystem;
+ # disabling all adapters over a WinRM/remote session would sever that session
+ # and brick remote access, so severity alone must never trigger it)
+ if ($IsolateSystem) {
Write-Host "`n[3/6] Isolating system from network..." -ForegroundColor Red
if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Disable network adapters")) {
@@ -170,6 +176,11 @@ function Invoke-IncidentResponse {
}
}
}
+ elseif ($Severity -eq 'Critical') {
+ Write-Warning "Severity is Critical but network isolation was NOT performed: -IsolateSystem was not specified. Disabling all network adapters can sever remote (WinRM) access; re-run with -IsolateSystem to isolate the system."
+ Write-Host "`n[3/6] Network isolation: SKIPPED (Critical severity, but -IsolateSystem not specified)" -ForegroundColor Yellow
+ $results.Actions += "Network isolation skipped (Critical severity without -IsolateSystem)"
+ }
else {
Write-Host "`n[3/6] Network isolation: SKIPPED" -ForegroundColor Yellow
$results.Actions += "Network isolation skipped (not requested)"
@@ -222,9 +233,10 @@ function Invoke-IncidentResponse {
Write-IRLog "Failed to collect system info: $_" 'ERROR'
}
- # Collect running processes
+ # Collect running processes (Name/Path are attacker-controlled strings;
+ # escape them against CSV formula injection)
try {
- Get-Process | Select-Object Name, Id, Path, StartTime, CPU, WorkingSet64 |
+ Get-Process | Select-Object @{ Name = 'Name'; Expression = { Protect-CsvField $_.Name } }, Id, @{ Name = 'Path'; Expression = { Protect-CsvField $_.Path } }, StartTime, CPU, WorkingSet64 |
Export-Csv (Join-Path $OutputPath "RunningProcesses.csv") -NoTypeInformation
$results.EvidenceCollected += "Running processes list"
Write-IRLog "Collected process list" 'SUCCESS'
@@ -233,9 +245,10 @@ function Invoke-IncidentResponse {
Write-IRLog "Failed to collect processes: $_" 'ERROR'
}
- # Collect network connections
+ # Collect network connections (address fields are attacker-influenced
+ # strings; escape them against CSV formula injection)
try {
- Get-NetTCPConnection | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State, OwningProcess |
+ Get-NetTCPConnection | Select-Object @{ Name = 'LocalAddress'; Expression = { Protect-CsvField $_.LocalAddress } }, LocalPort, @{ Name = 'RemoteAddress'; Expression = { Protect-CsvField $_.RemoteAddress } }, RemotePort, State, OwningProcess |
Export-Csv (Join-Path $OutputPath "NetworkConnections.csv") -NoTypeInformation
$results.EvidenceCollected += "Network connections"
Write-IRLog "Collected network connections" 'SUCCESS'
diff --git a/ThreatHunting/Find-LateralMovement.ps1 b/ThreatHunting/Find-LateralMovement.ps1
index 93b753b..b350dae 100644
--- a/ThreatHunting/Find-LateralMovement.ps1
+++ b/ThreatHunting/Find-LateralMovement.ps1
@@ -61,6 +61,14 @@ function Find-LateralMovement {
SuspiciousAuthentication = @()
SMBAccess = @()
}
+ # Per-section truncation flags: set when a Get-WinEvent query returns
+ # exactly its -MaxEvents cap (meaning more matching events likely exist)
+ Truncated = @{
+ NetworkConnections = $false
+ RemoteExecution = $false
+ SuspiciousAuthentication = $false
+ SMBAccess = $false
+ }
Summary = @{
TotalIndicators = 0
CriticalFindings = 0
@@ -149,11 +157,19 @@ function Find-LateralMovement {
try {
# Check for PSRemoting activity (Event ID 4648 - Explicit credential logon)
- $remoteEvents = Get-WinEvent -FilterHashtable @{
+ $maxRemoteEvents = 100
+ $remoteEvents = @(Get-WinEvent -FilterHashtable @{
LogName = 'Security'
ID = 4648
StartTime = $startDate
- } -MaxEvents 100 -ErrorAction SilentlyContinue
+ } -MaxEvents $maxRemoteEvents -ErrorAction SilentlyContinue)
+
+ # Get-WinEvent returns exactly MaxEvents when more matching
+ # events exist - flag the cap instead of silently truncating
+ if ($remoteEvents.Count -ge $maxRemoteEvents) {
+ $results.Truncated.RemoteExecution = $true
+ Write-Warning "Remote execution check (Event ID 4648) hit the $maxRemoteEvents-event cap - results are likely TRUNCATED. Narrow -Days for complete coverage."
+ }
if ($remoteEvents) {
$groupedEvents = $remoteEvents | Group-Object -Property {
@@ -201,11 +217,19 @@ function Find-LateralMovement {
try {
# Event ID 4624 - Successful logon (Type 3 = Network, Type 10 = RemoteInteractive/RDP)
- $logonEvents = Get-WinEvent -FilterHashtable @{
+ $maxLogonEvents = 500
+ $logonEvents = @(Get-WinEvent -FilterHashtable @{
LogName = 'Security'
ID = 4624
StartTime = $startDate
- } -MaxEvents 500 -ErrorAction SilentlyContinue
+ } -MaxEvents $maxLogonEvents -ErrorAction SilentlyContinue)
+
+ # Get-WinEvent returns exactly MaxEvents when more matching
+ # events exist - flag the cap instead of silently truncating
+ if ($logonEvents.Count -ge $maxLogonEvents) {
+ $results.Truncated.SuspiciousAuthentication = $true
+ Write-Warning "Authentication check (Event ID 4624) hit the $maxLogonEvents-event cap - results are likely TRUNCATED. Narrow -Days for complete coverage."
+ }
if ($logonEvents) {
# Filter for Type 3 (Network) and Type 10 (RemoteInteractive)
@@ -273,11 +297,19 @@ function Find-LateralMovement {
try {
# Event ID 5140 - Network share object accessed
- $shareEvents = Get-WinEvent -FilterHashtable @{
+ $maxShareEvents = 200
+ $shareEvents = @(Get-WinEvent -FilterHashtable @{
LogName = 'Security'
ID = 5140
StartTime = $startDate
- } -MaxEvents 200 -ErrorAction SilentlyContinue
+ } -MaxEvents $maxShareEvents -ErrorAction SilentlyContinue)
+
+ # Get-WinEvent returns exactly MaxEvents when more matching
+ # events exist - flag the cap instead of silently truncating
+ if ($shareEvents.Count -ge $maxShareEvents) {
+ $results.Truncated.SMBAccess = $true
+ Write-Warning "SMB share access check (Event ID 5140) hit the $maxShareEvents-event cap - results are likely TRUNCATED. Narrow -Days for complete coverage."
+ }
if ($shareEvents) {
# Split share access: admin/hidden shares (IPC$, ADMIN$, C$, ...)
@@ -399,6 +431,12 @@ function Find-LateralMovement {
Write-Host " High: $($results.Summary.HighFindings)" -ForegroundColor Yellow
Write-Host " Medium: $($results.Summary.MediumFindings)" -ForegroundColor Yellow
Write-Host " Low: $($results.Summary.LowFindings)" -ForegroundColor White
+
+ $truncatedSections = @($results.Truncated.GetEnumerator() | Where-Object { $_.Value } | ForEach-Object { $_.Key })
+ if ($truncatedSections.Count -gt 0) {
+ Write-Host " TRUNCATED (event cap hit, partial data): $($truncatedSections -join ', ')" -ForegroundColor Red
+ $results.Recommendations += "Event log queries hit their -MaxEvents cap in: $($truncatedSections -join ', ') - narrow -Days and re-run for complete coverage"
+ }
if ($results.Summary.TotalIndicators -gt 0) {
Write-Host "`nIndicator Breakdown:" -ForegroundColor Cyan
diff --git a/ThreatHunting/Get-ThreatIntelligence.ps1 b/ThreatHunting/Get-ThreatIntelligence.ps1
index 7c64d79..35ff295 100644
--- a/ThreatHunting/Get-ThreatIntelligence.ps1
+++ b/ThreatHunting/Get-ThreatIntelligence.ps1
@@ -4,7 +4,15 @@ function Get-ThreatIntelligence {
Matches system artifacts against threat intelligence indicators
.DESCRIPTION
Checks running processes, network connections, files, and registry against
- known Indicators of Compromise (IOCs) from threat intelligence feeds
+ known Indicators of Compromise (IOCs) from threat intelligence feeds.
+ IP indicators are exact-matched against the live TCP connection table.
+ Domain/URL-host indicators cannot be matched against literal IP addresses,
+ so they are correlated against real hostname telemetry: the DNS client
+ cache (Get-DnsClientCache) and Sysmon DNS query events (ID 22) when
+ available. Hash indicators are matched against Get-FileHash results for
+ the image paths of running processes (algorithms are derived from the
+ stored hash lengths). The SourcesChecked property of the result lists
+ exactly which correlation sources were queried on this system.
.PARAMETER CheckProcesses
Check running processes against IOCs
.PARAMETER CheckNetwork
@@ -133,6 +141,7 @@ function Get-ThreatIntelligence {
FeedStats = @()
}
Recommendations = @()
+ SourcesChecked = @()
}
# Built-in IOC Database (Common malware/threat indicators)
@@ -854,12 +863,27 @@ function Get-ThreatIntelligence {
Write-Host "`n[1/4] Checking processes against IOCs..." -ForegroundColor Cyan
try {
- $processes = Get-CimInstance Win32_Process |
- Where-Object { $null -ne $_.CommandLine } |
- Select-Object Name, ProcessId, ExecutablePath, CommandLine
-
$foundCount = 0
+ # Process names and command lines come from CIM (Windows only)
+ if (Get-Command Get-CimInstance -ErrorAction SilentlyContinue) {
+ $processes = @()
+ try {
+ $processes = @(Get-CimInstance Win32_Process -ErrorAction Stop |
+ Where-Object { $null -ne $_.CommandLine } |
+ Select-Object Name, ProcessId, ExecutablePath, CommandLine)
+ $results.SourcesChecked += 'Process names and command lines (Win32_Process via CIM)'
+ }
+ catch {
+ $results.SourcesChecked += "Process name/command-line correlation unavailable (Win32_Process query failed: $_)"
+ Write-Warning "Could not enumerate processes via CIM: $_"
+ }
+ }
+ else {
+ $processes = @()
+ $results.SourcesChecked += 'Process name/command-line correlation unavailable (Get-CimInstance not present on this platform)'
+ }
+
foreach ($process in $processes) {
# Check process name against malicious process list
if ($iocDatabase.MaliciousProcesses.ContainsKey($process.Name.ToLower())) {
@@ -959,6 +983,92 @@ function Get-ThreatIntelligence {
}
}
+ # Hash the image paths of running processes and compare against
+ # MaliciousHashes. Hash algorithms are derived from the stored
+ # indicator key lengths (32 hex chars = MD5, 40 = SHA1, 64 = SHA256)
+ if ($iocDatabase.MaliciousHashes.Count -gt 0) {
+ if (Get-Command Get-FileHash -ErrorAction SilentlyContinue) {
+ $hashAlgorithms = @()
+ foreach ($hashKey in $iocDatabase.MaliciousHashes.Keys) {
+ switch ([string]$hashKey.Length) {
+ '32' { if ($hashAlgorithms -notcontains 'MD5') { $hashAlgorithms += 'MD5' } }
+ '40' { if ($hashAlgorithms -notcontains 'SHA1') { $hashAlgorithms += 'SHA1' } }
+ '64' { if ($hashAlgorithms -notcontains 'SHA256') { $hashAlgorithms += 'SHA256' } }
+ }
+ }
+
+ if ($hashAlgorithms.Count -gt 0) {
+ $maxHashFiles = 500
+ $imagePaths = @{}
+ foreach ($runningProcess in @(Get-Process -ErrorAction SilentlyContinue)) {
+ if ($imagePaths.Count -ge $maxHashFiles) { break }
+ $imagePath = $null
+ try { $imagePath = $runningProcess.Path } catch { continue } # access-denied/system process: skip silently
+ if (-not [string]::IsNullOrWhiteSpace($imagePath) -and -not $imagePaths.ContainsKey($imagePath)) {
+ $imagePaths[$imagePath] = $runningProcess.ProcessName
+ }
+ }
+
+ $hashedFileCount = 0
+ foreach ($imagePath in $imagePaths.Keys) {
+ $fileHashes = @{}
+ foreach ($algorithm in $hashAlgorithms) {
+ try {
+ $fileHashes[$algorithm] = (Get-FileHash -Path $imagePath -Algorithm $algorithm -ErrorAction Stop).Hash.ToLower()
+ }
+ catch {
+ $fileHashes = $null
+ break # locked/inaccessible file: skip remaining algorithms silently
+ }
+ }
+ if ($null -eq $fileHashes) { continue }
+ $hashedFileCount++
+
+ foreach ($algorithm in $fileHashes.Keys) {
+ $hashValue = $fileHashes[$algorithm]
+ if ($iocDatabase.MaliciousHashes.ContainsKey($hashValue)) {
+ $ioc = $iocDatabase.MaliciousHashes[$hashValue]
+
+ $match = [PSCustomObject]@{
+ Type = 'Process'
+ IOCType = 'MaliciousHash'
+ Indicator = $hashValue
+ HashAlgorithm = $algorithm
+ ProcessName = $imagePaths[$imagePath]
+ Path = $imagePath
+ Severity = $ioc.Severity
+ Description = $ioc.Description
+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
+ }
+
+ $results.Matches.ProcessIOCs += $match
+ $foundCount++
+
+ switch ($ioc.Severity) {
+ 'Critical' { $results.Summary.CriticalMatches++ }
+ 'High' { $results.Summary.HighMatches++ }
+ 'Medium' { $results.Summary.MediumMatches++ }
+ }
+
+ Write-Host " [!] MATCH: Malicious hash ($algorithm) for running process image '$imagePath'" -ForegroundColor Red
+ }
+ }
+ }
+
+ $results.SourcesChecked += "Running process image hashes ($hashedFileCount file(s) hashed, cap $maxHashFiles; algorithms: $($hashAlgorithms -join ', '))"
+ }
+ else {
+ $results.SourcesChecked += 'Running process image hashes skipped (no recognizable MD5/SHA1/SHA256 indicators in MaliciousHashes)'
+ }
+ }
+ else {
+ $results.SourcesChecked += 'Running process image hashes unavailable (Get-FileHash not present on this platform)'
+ }
+ }
+ else {
+ $results.SourcesChecked += 'Running process image hashes skipped (no hash indicators loaded)'
+ }
+
if ($foundCount -eq 0) {
Write-Host " No process IOC matches found" -ForegroundColor Green
}
@@ -973,10 +1083,19 @@ function Get-ThreatIntelligence {
Write-Host "`n[2/4] Checking network connections against IOCs..." -ForegroundColor Cyan
try {
- $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue
-
$foundCount = 0
+ # TCP connections carry literal IP addresses only, so they can
+ # satisfy IP exact-match indicators but never domain/host indicators
+ if (Get-Command Get-NetTCPConnection -ErrorAction SilentlyContinue) {
+ $connections = @(Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue)
+ $results.SourcesChecked += "TCP connection table ($(@($connections).Count) established connection(s); IP exact match)"
+ }
+ else {
+ $connections = @()
+ $results.SourcesChecked += 'TCP connection table unavailable (Get-NetTCPConnection not present on this platform)'
+ }
+
foreach ($conn in $connections) {
$remoteAddress = $conn.RemoteAddress.ToString()
@@ -1010,39 +1129,112 @@ function Get-ThreatIntelligence {
Write-Host " [!] MATCH: Malicious IP $($conn.RemoteAddress) via $processName" -ForegroundColor Red
}
+ }
+
+ # Feed-derived domain/URL-host indicators hold hostnames, not IPs, so
+ # matching them against $conn.RemoteAddress (always a literal address)
+ # could never fire. Correlate them against real hostname telemetry
+ # instead: the DNS client cache and Sysmon DNS query events (ID 22)
+ if ($iocDatabase.SuspiciousPatterns.NetworkIndicators.Count -gt 0) {
+ $observedHostnames = @{}
- # Check against feed-derived network indicators
- foreach ($pattern in $iocDatabase.SuspiciousPatterns.NetworkIndicators) {
- if ($remoteAddress -match $pattern.Pattern) {
- $process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue
- $processName = if ($process) { $process.Name } else { "PID $($conn.OwningProcess)" }
-
- $match = [PSCustomObject]@{
- Type = 'Network'
- IOCType = 'FeedNetworkIndicator'
- Indicator = $pattern.Pattern
- ProcessName = $processName
- ProcessId = $conn.OwningProcess
- LocalAddress = "$($conn.LocalAddress):$($conn.LocalPort)"
- RemoteAddress = "$($conn.RemoteAddress):$($conn.RemotePort)"
- Severity = $pattern.Severity
- Description = $pattern.Description
- Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
+ # Source (a): DNS client cache (Entry = queried name, Name = resolved name/alias)
+ if (Get-Command Get-DnsClientCache -ErrorAction SilentlyContinue) {
+ try {
+ $dnsCacheEntries = @(Get-DnsClientCache -ErrorAction Stop)
+ foreach ($cacheEntry in $dnsCacheEntries) {
+ if ($null -eq $cacheEntry) { continue }
+ foreach ($propertyName in 'Entry', 'Name') {
+ if ($cacheEntry.PSObject.Properties[$propertyName]) {
+ $cacheValue = [string]($cacheEntry.$propertyName)
+ if (-not [string]::IsNullOrWhiteSpace($cacheValue) -and $cacheValue -notmatch '^\d{1,3}(\.\d{1,3}){3}$') {
+ $observedHostnames[$cacheValue.TrimEnd('.').ToLower()] = 'DNS client cache'
+ }
+ }
+ }
}
-
- $results.Matches.NetworkIOCs += $match
- $foundCount++
-
- switch ($pattern.Severity) {
- 'Critical' { $results.Summary.CriticalMatches++ }
- 'High' { $results.Summary.HighMatches++ }
- 'Medium' { $results.Summary.MediumMatches++ }
+ $results.SourcesChecked += "DNS client cache ($($observedHostnames.Count) hostname(s) observed)"
+ }
+ catch {
+ $results.SourcesChecked += "DNS client cache unavailable (query failed: $_)"
+ }
+ }
+ else {
+ $results.SourcesChecked += 'DNS client cache unavailable (Get-DnsClientCache not present on this platform)'
+ }
+
+ # Source (b): Sysmon DNS query events (ID 22), bounded to the feed
+ # freshness window (FeedMaxAgeHours) and a 500-event cap
+ $sysmonLogName = 'Microsoft-Windows-Sysmon/Operational'
+ if (Get-Command Get-WinEvent -ErrorAction SilentlyContinue) {
+ $sysmonLogAvailable = $false
+ try {
+ $null = Get-WinEvent -ListLog $sysmonLogName -ErrorAction Stop
+ $sysmonLogAvailable = $true
+ }
+ catch {
+ $results.SourcesChecked += "Sysmon DNS query log (event 22) unavailable (log '$sysmonLogName' not present)"
+ }
+
+ if ($sysmonLogAvailable) {
+ try {
+ $sysmonQueryCount = 0
+ $dnsEvents = @(Get-WinEvent -FilterHashtable @{
+ LogName = $sysmonLogName
+ Id = 22
+ StartTime = (Get-Date).AddHours(-$FeedMaxAgeHours)
+ } -MaxEvents 500 -ErrorAction Stop)
+ foreach ($dnsEvent in $dnsEvents) {
+ if ($null -eq $dnsEvent) { continue }
+ $eventData = ([xml]$dnsEvent.ToXml()).Event.EventData.Data
+ $queryNode = @($eventData | Where-Object { $_.Name -eq 'QueryName' } | Select-Object -First 1)
+ if ($queryNode.Count -gt 0 -and -not [string]::IsNullOrWhiteSpace($queryNode[0].InnerText)) {
+ $observedHostnames[$queryNode[0].InnerText.TrimEnd('.').ToLower()] = 'Sysmon DNS query (event 22)'
+ $sysmonQueryCount++
+ }
+ }
+ $results.SourcesChecked += "Sysmon DNS query log (event 22, last $FeedMaxAgeHours hour(s), $sysmonQueryCount query name(s))"
+ }
+ catch {
+ $results.SourcesChecked += "Sysmon DNS query log (event 22) could not be read: $_"
}
-
- Write-Host " [!] MATCH: Feed indicator '$($pattern.Pattern)' via $processName" -ForegroundColor Red
- break
}
}
+ else {
+ $results.SourcesChecked += 'Sysmon DNS query log (event 22) unavailable (Get-WinEvent not present on this platform)'
+ }
+
+ foreach ($hostname in $observedHostnames.Keys) {
+ foreach ($pattern in $iocDatabase.SuspiciousPatterns.NetworkIndicators) {
+ if ($hostname -match $pattern.Pattern) {
+ $match = [PSCustomObject]@{
+ Type = 'Network'
+ IOCType = 'FeedDomainIndicator'
+ Indicator = $pattern.Pattern
+ MatchedHostname = $hostname
+ HostnameSource = $observedHostnames[$hostname]
+ Severity = $pattern.Severity
+ Description = $pattern.Description
+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
+ }
+
+ $results.Matches.NetworkIOCs += $match
+ $foundCount++
+
+ switch ($pattern.Severity) {
+ 'Critical' { $results.Summary.CriticalMatches++ }
+ 'High' { $results.Summary.HighMatches++ }
+ 'Medium' { $results.Summary.MediumMatches++ }
+ }
+
+ Write-Host " [!] MATCH: Domain indicator '$($pattern.Pattern)' matched hostname '$hostname' ($($observedHostnames[$hostname]))" -ForegroundColor Red
+ break
+ }
+ }
+ }
+ }
+ else {
+ $results.SourcesChecked += 'DNS client cache / Sysmon DNS query correlation skipped (no domain/host indicators loaded)'
}
if ($foundCount -eq 0) {
@@ -1314,6 +1506,13 @@ function Get-ThreatIntelligence {
}
}
+ if (@($results.SourcesChecked).Count -gt 0) {
+ Write-Host "`nCorrelation Sources:" -ForegroundColor Cyan
+ foreach ($sourceChecked in $results.SourcesChecked) {
+ Write-Host " - $sourceChecked" -ForegroundColor Gray
+ }
+ }
+
Write-Host "`nThreat Intelligence Sources:" -ForegroundColor Cyan
Write-Host " - MITRE ATT&CK: https://attack.mitre.org/" -ForegroundColor Gray
Write-Host " - AlienVault OTX: https://otx.alienvault.com/" -ForegroundColor Gray
diff --git a/Vulnerability/Get-ExposedServices.ps1 b/Vulnerability/Get-ExposedServices.ps1
index 0e73f82..c717193 100644
--- a/Vulnerability/Get-ExposedServices.ps1
+++ b/Vulnerability/Get-ExposedServices.ps1
@@ -507,14 +507,15 @@ function Generate-ExposedServicesHTML {
}
})) {
$riskClass = "risk-$($service.Risk.ToLower())"
- $desc = $service.Description -replace '<', '&lt;' -replace '>', '&gt;'
-
+ $desc = ConvertTo-HtmlEncoded $service.Description
+ $processName = ConvertTo-HtmlEncoded $service.Process
+
$html += @"
<tr>
<td><span class="risk-badge $riskClass">$($service.Risk)</span></td>
<td><strong>$($service.Port)</strong></td>
<td>$($service.Service)</td>
- <td>$($service.Process)</td>
+ <td>$processName</td>
<td>$desc</td>
<td>$($service.LocalAddress)</td>
</tr>
diff --git a/WindowsDefender/Update-DefenderConfiguration.ps1 b/WindowsDefender/Update-DefenderConfiguration.ps1
index 10abe52..9bfaff2 100644
--- a/WindowsDefender/Update-DefenderConfiguration.ps1
+++ b/WindowsDefender/Update-DefenderConfiguration.ps1
@@ -33,7 +33,7 @@ function Update-DefenderConfiguration {
PSCustomObject with configuration update results
#>
- [CmdletBinding(SupportsShouldProcess)]
+ [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param(
[Parameter()]
[ValidateNotNull()]
diff --git a/WindowsSecurityAudit.psd1 b/WindowsSecurityAudit.psd1
index 3bfd3a8..ac8b2d0 100644
--- a/WindowsSecurityAudit.psd1
+++ b/WindowsSecurityAudit.psd1
@@ -1,13 +1,87 @@
-@{
+@{
RootModule = 'WindowsSecurityAudit.psm1'
- ModuleVersion = '1.6.0'
+ ModuleVersion = '1.6.1'
GUID = 'a8d7c4e5-3b2f-4e8a-9c1d-6f5a8b9d2e7c'
Author = 'Okan YILDIZ'
CompanyName = 'okanyildiz'
Copyright = '(c) 2026 Okan YILDIZ. All rights reserved.'
- Description = 'Comprehensive Windows security audit and DFIR toolkit: 72 functions across 14 categories — threat hunting (MITRE ATT&CK mapping, lateral movement, LOLBins, data exfiltration), compliance (CIS Benchmark, NIST 800-53, PCI-DSS), vulnerability management (NVD CVE matching, CPE resolution, EOL software), forensics (artifact collection, memory dumps, USN journal, Sysmon analytics), SIEM integration (Splunk HEC, Microsoft Sentinel, CEF/NDJSON), threat intelligence feeds (abuse.ch, AbuseIPDB, MISP, TAXII/STIX), Active Directory security, hardening baselines and automated remediation. Runs on Windows PowerShell 5.1+ and PowerShell 7. Fully locale-invariant since v1.6.0: all checks use APIs, GUIDs and SIDs instead of parsing localized console output, producing correct results on non-English Windows (Turkish, German, French, ...). Zero external dependencies. Free and open source — support development: https://buymeacoffee.com/okanyildizr'
+ Description = 'Comprehensive Windows security audit and DFIR toolkit: 72 functions across 14 categories — threat hunting (MITRE ATT&CK mapping, lateral movement, LOLBins, data exfiltration), compliance (CIS Benchmark, NIST 800-53, PCI-DSS), vulnerability management (NVD CVE matching, CPE resolution, EOL software), forensics (artifact collection, memory dumps, USN journal, Sysmon analytics), SIEM integration (Splunk HEC, Microsoft Sentinel, CEF/NDJSON), threat intelligence feeds (abuse.ch, AbuseIPDB, MISP, TAXII/STIX), Active Directory security, hardening baselines and automated remediation. Runs on Windows PowerShell 5.1+ and PowerShell 7. Fully locale-invariant since v1.6.0: all checks use APIs, GUIDs and SIDs instead of parsing localized console output, producing correct results on non-English Windows (Turkish, German, French, ...). Core checks are dependency-free; AD functions require the ActiveDirectory module (RSAT) and cloud functions the Microsoft Graph SDK. Free and open source — support development: https://buymeacoffee.com/okanyildizr'
PowerShellVersion = '5.1'
- FunctionsToExport = '*'
+ CompatiblePSEditions = @('Desktop', 'Core')
+ FunctionsToExport = @(
+ 'Compare-SecurityBaseline',
+ 'ConvertTo-SiemEvent',
+ 'Enable-AuditPolicies',
+ 'Enable-PowerShellSecurity',
+ 'Export-AttackNavigatorLayer',
+ 'Export-ComplianceEvidence',
+ 'Export-MemoryDump',
+ 'Export-SecurityReport',
+ 'Find-ADBackdoors',
+ 'Find-ADVulnerabilities',
+ 'Find-APTIndicators',
+ 'Find-DataExfiltration',
+ 'Find-DefenseEvasion',
+ 'Find-EOLSoftware',
+ 'Find-LateralMovement',
+ 'Find-LivingOffLand',
+ 'Find-NetworkAnomalies',
+ 'Find-PersistenceMechanisms',
+ 'Find-StaleADObjects',
+ 'Find-SuspiciousAuthentication',
+ 'Find-SuspiciousProcesses',
+ 'Get-ADPasswordPolicy',
+ 'Get-ADPrivilegedAccounts',
+ 'Get-ArtifactCollection',
+ 'Get-AzureADRiskySignIns',
+ 'Get-CloudComplianceStatus',
+ 'Get-ComplianceReport',
+ 'Get-CredentialAccessEvents',
+ 'Get-DefenderStatus',
+ 'Get-EventIdDescription',
+ 'Get-EventLogAnalysis',
+ 'Get-ExecutionArtifacts',
+ 'Get-ExposedServices',
+ 'Get-FileSystemAnalysis',
+ 'Get-FileSystemJournal',
+ 'Get-MemoryAnalysis',
+ 'Get-MITREAttackMapping',
+ 'Get-MultiSystemAudit',
+ 'Get-NVDCveData',
+ 'Get-RegistryAnalysis',
+ 'Get-SecurityBaseline',
+ 'Get-SecurityMetrics',
+ 'Get-SecurityMisconfigurations',
+ 'Get-SysmonAnalytics',
+ 'Get-SystemInfo',
+ 'Get-ThreatIntelligence',
+ 'Get-USBHistory',
+ 'Get-UserActivityArtifacts',
+ 'Get-VulnerabilityAssessment',
+ 'Invoke-DefenderScan',
+ 'Invoke-EnterpriseSecurityScan',
+ 'Invoke-ForensicCollection',
+ 'Invoke-IncidentResponse',
+ 'Invoke-SecurityAssessment',
+ 'Invoke-SecurityRemediation',
+ 'New-ConsolidatedReport',
+ 'New-ExecutiveReport',
+ 'New-ForensicTimeline',
+ 'New-SecurityDashboard',
+ 'Register-ScheduledSecurityScan',
+ 'Resolve-CpeName',
+ 'Send-SiemEvent',
+ 'Set-SecurityBaseline',
+ 'Test-ADSecurityPosture',
+ 'Test-CertificateHealth',
+ 'Test-CISBenchmark',
+ 'Test-M365SecurityPosture',
+ 'Test-NISTCompliance',
+ 'Test-PatchCompliance',
+ 'Test-PCI-DSS',
+ 'Test-SystemIntegrity',
+ 'Update-DefenderConfiguration'
+ )
CmdletsToExport = @()
VariablesToExport = @()
AliasesToExport = @()
diff --git a/WindowsSecurityAudit.psm1 b/WindowsSecurityAudit.psm1
index addde7f..55feb28 100644
--- a/WindowsSecurityAudit.psm1
+++ b/WindowsSecurityAudit.psm1
@@ -4,17 +4,18 @@
.DESCRIPTION
Comprehensive Windows security audit toolkit for threat detection and incident response
.VERSION
- 1.0.0
+ 1.6.1 (keep in sync with WindowsSecurityAudit.psd1 ModuleVersion)
.AUTHOR
- Security Team
+ Okan YILDIZ (keep in sync with WindowsSecurityAudit.psd1 Author)
#>
# Set strict mode
Set-StrictMode -Version Latest
# Module variables
+# NOTE: keep ModuleVersion in sync with the ModuleVersion field in WindowsSecurityAudit.psd1
$script:ModuleRoot = $PSScriptRoot
-$script:ModuleVersion = '1.6.0'
+$script:ModuleVersion = '1.6.1'
# Import all function files
$Public = @(Get-ChildItem -Path "$PSScriptRoot\Core\*.ps1" -ErrorAction SilentlyContinue)
@@ -35,17 +36,31 @@ $Public += @(Get-ChildItem -Path "$PSScriptRoot\Reporting\*.ps1" -ErrorAction Si
$Private = @(Get-ChildItem -Path "$PSScriptRoot\Private\*.ps1" -ErrorAction SilentlyContinue)
-# Import all function files
+# Import all function files, tracking failures so a broken file does not
+# silently export a missing function
+$script:FailedImports = [System.Collections.Generic.List[object]]::new()
+$script:LoadedPublic = [System.Collections.Generic.List[object]]::new()
foreach ($import in @($Public + $Private)) {
try {
. $import.FullName
+ if ($Public -contains $import) {
+ $script:LoadedPublic.Add($import)
+ }
}
catch {
Write-Error "Failed to import function $($import.FullName): $_"
+ $script:FailedImports.Add($import)
}
}
-# Export public functions
-Export-ModuleMember -Function $Public.BaseName
+# Export only the public functions that loaded successfully
+Export-ModuleMember -Function $script:LoadedPublic.BaseName
-Write-Host "Windows Security Audit Module v$script:ModuleVersion loaded successfully" -ForegroundColor Green
\ No newline at end of file
+if ($script:FailedImports.Count -gt 0) {
+ $failedNames = $script:FailedImports.FullName -join ', '
+ Write-Warning ("Windows Security Audit Module v$script:ModuleVersion loaded with {0} of {1} functions. Failed files: {2}" -f
+ $script:LoadedPublic.Count, $Public.Count, $failedNames)
+}
+else {
+ Write-Verbose "Windows Security Audit Module v$script:ModuleVersion loaded successfully ($($script:LoadedPublic.Count) functions)"
+}
\ No newline at end of file