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

Zero-defect audit: ~30 subtle fixes across all modules

Okan YILDIZd820b917aec8
diff --git a/ActiveDirectory/Find-ADBackdoors.ps1 b/ActiveDirectory/Find-ADBackdoors.ps1
index f5d9c77..d8e7202 100644
--- a/ActiveDirectory/Find-ADBackdoors.ps1
+++ b/ActiveDirectory/Find-ADBackdoors.ps1
@@ -174,7 +174,7 @@ function Find-ADBackdoors {
if ($account) {
# Check if it's a legitimate DC or admin account
- $isLegitimate = $account.Name -match "Domain Controllers|Enterprise Admins|Administrators"
+ $isLegitimate = $account.Name -match "Domain Controllers|Enterprise Admins|Domain Admins|^Administrators$"
if (-not $isLegitimate) {
$results.Backdoors.DCSync += [PSCustomObject]@{
@@ -258,11 +258,13 @@ function Find-ADBackdoors {
try {
# Check for unconstrained delegation
- $unconstrainedDelegation = Get-ADComputer -Filter {TrustedForDelegation -eq $true} -Properties TrustedForDelegation -Server $Domain
+ $unconstrainedDelegation = Get-ADComputer -Filter {TrustedForDelegation -eq $true} -Properties TrustedForDelegation, PrimaryGroupID -Server $Domain
foreach ($computer in $unconstrainedDelegation) {
- # Domain Controllers are expected to have this
- if ($computer.Name -notmatch "DC|Domain Controller") {
+ # Domain Controllers are expected to have this (PrimaryGroupID 516 = RWDC, 521 = RODC);
+ # matching on the computer name would miss DCs with arbitrary names and
+ # falsely excuse non-DCs whose names merely contain "DC"
+ if ($computer.PrimaryGroupID -notin @(516, 521)) {
$results.Backdoors.DangerousDelegations += [PSCustomObject]@{
Severity = 'High'
Object = $computer.Name
diff --git a/ActiveDirectory/Find-ADVulnerabilities.ps1 b/ActiveDirectory/Find-ADVulnerabilities.ps1
index de42e62..cc9a8c5 100644
--- a/ActiveDirectory/Find-ADVulnerabilities.ps1
+++ b/ActiveDirectory/Find-ADVulnerabilities.ps1
@@ -81,8 +81,8 @@ function Find-ADVulnerabilities {
Write-Host "`n[1/3] Checking for Kerberoastable accounts..." -ForegroundColor Cyan
try {
- # Find accounts with SPN set
- $kerberoastableUsers = Get-ADUser -Filter {ServicePrincipalName -like "*"} -Properties ServicePrincipalName, PasswordLastSet, Enabled, AdminCount -Server $Domain
+ # Find accounts with SPN set (@() wraps $null so .Count is safe under strict mode)
+ $kerberoastableUsers = @(Get-ADUser -Filter {ServicePrincipalName -like "*"} -Properties ServicePrincipalName, PasswordLastSet, Enabled, AdminCount -Server $Domain)
foreach ($user in $kerberoastableUsers) {
$severity = 'Medium'
@@ -136,8 +136,8 @@ function Find-ADVulnerabilities {
Write-Host "`n[2/3] Checking for AS-REP Roastable accounts..." -ForegroundColor Cyan
try {
- # Find accounts with "Do not require Kerberos preauthentication"
- $asrepUsers = Get-ADUser -Filter {DoesNotRequirePreAuth -eq $true} -Properties DoesNotRequirePreAuth, PasswordLastSet, Enabled, AdminCount -Server $Domain
+ # Find accounts with "Do not require Kerberos preauthentication" (@() wraps $null so .Count is safe under strict mode)
+ $asrepUsers = @(Get-ADUser -Filter {DoesNotRequirePreAuth -eq $true} -Properties DoesNotRequirePreAuth, PasswordLastSet, Enabled, AdminCount -Server $Domain)
foreach ($user in $asrepUsers) {
$severity = 'High'
@@ -189,7 +189,7 @@ function Find-ADVulnerabilities {
try {
# Check for users with "Password Never Expires"
Write-Host " Checking password policies..." -ForegroundColor Yellow
- $neverExpireUsers = Get-ADUser -Filter {PasswordNeverExpires -eq $true -and Enabled -eq $true} -Properties PasswordNeverExpires, AdminCount -Server $Domain
+ $neverExpireUsers = @(Get-ADUser -Filter {PasswordNeverExpires -eq $true -and Enabled -eq $true} -Properties PasswordNeverExpires, AdminCount -Server $Domain)
foreach ($user in $neverExpireUsers) {
$severity = if ($user.AdminCount -eq 1) { 'High' } else { 'Medium' }
diff --git a/ActiveDirectory/Find-StaleADObjects.ps1 b/ActiveDirectory/Find-StaleADObjects.ps1
index 181b79b..0275e55 100644
--- a/ActiveDirectory/Find-StaleADObjects.ps1
+++ b/ActiveDirectory/Find-StaleADObjects.ps1
@@ -82,11 +82,11 @@ function Find-StaleADObjects {
Write-Host "`n[1/3] Scanning for stale user accounts..." -ForegroundColor Cyan
try {
- # Get users that haven't logged on in X days
- $staleUsers = Get-ADUser -Filter {
+ # Get users that haven't logged on in X days (@() wraps $null so .Count is safe under strict mode)
+ $staleUsers = @(Get-ADUser -Filter {
Enabled -eq $true -and
LastLogonDate -lt $cutoffDate
- } -Properties LastLogonDate, PasswordLastSet, whenCreated, Description -Server $Domain
+ } -Properties LastLogonDate, PasswordLastSet, whenCreated, Description -Server $Domain)
foreach ($user in $staleUsers) {
$daysSinceLogon = if ($user.LastLogonDate) {
@@ -139,11 +139,11 @@ function Find-StaleADObjects {
Write-Host "`n[2/3] Scanning for stale computer accounts..." -ForegroundColor Cyan
try {
- # Get computers that haven't connected in X days
- $staleComputers = Get-ADComputer -Filter {
+ # Get computers that haven't connected in X days (@() wraps $null so .Count is safe under strict mode)
+ $staleComputers = @(Get-ADComputer -Filter {
Enabled -eq $true -and
LastLogonDate -lt $cutoffDate
- } -Properties LastLogonDate, OperatingSystem, whenCreated, Description -Server $Domain
+ } -Properties LastLogonDate, OperatingSystem, whenCreated, Description -Server $Domain)
foreach ($computer in $staleComputers) {
$daysSinceLogon = if ($computer.LastLogonDate) {
@@ -198,7 +198,9 @@ function Find-StaleADObjects {
foreach ($group in $allGroups) {
$members = Get-ADGroupMember -Identity $group -Server $Domain -ErrorAction SilentlyContinue
- if ($members.Count -eq 0) {
+ # Get-ADGroupMember returns $null (not an empty array) for empty
+ # groups, and $null.Count is $null, so a .Count -eq 0 check never fires
+ if (-not $members) {
$groupAge = (New-TimeSpan -Start $group.whenCreated -End (Get-Date)).Days
$results.StaleGroups += [PSCustomObject]@{
diff --git a/ActiveDirectory/Get-ADPasswordPolicy.ps1 b/ActiveDirectory/Get-ADPasswordPolicy.ps1
index 40e148d..c3566e4 100644
--- a/ActiveDirectory/Get-ADPasswordPolicy.ps1
+++ b/ActiveDirectory/Get-ADPasswordPolicy.ps1
@@ -219,7 +219,7 @@ function Get-ADPasswordPolicy {
Write-Host " Found $($psos.Count) Fine-Grained Password Policies" -ForegroundColor Yellow
foreach ($pso in $psos) {
- $appliesTo = Get-ADFineGrainedPasswordPolicySubject -Identity $pso -Server $Domain
+ $appliesTo = @(Get-ADFineGrainedPasswordPolicySubject -Identity $pso -Server $Domain)
$psoInfo = [PSCustomObject]@{
Name = $pso.Name
@@ -230,7 +230,7 @@ function Get-ADPasswordPolicy {
MaxPasswordAge = $pso.MaxPasswordAge.Days
LockoutThreshold = $pso.LockoutThreshold
AppliesTo = $appliesTo.Count
- AppliesToObjects = if ($appliesTo) { $appliesTo.Name -join ', ' } else { 'None' }
+ AppliesToObjects = if ($appliesTo.Count -gt 0) { $appliesTo.Name -join ', ' } else { 'None' }
}
$analysis.FineGrainedPolicies += $psoInfo
diff --git a/ActiveDirectory/Test-ADSecurityPosture.ps1 b/ActiveDirectory/Test-ADSecurityPosture.ps1
index a3472a1..3cc8a0d 100644
--- a/ActiveDirectory/Test-ADSecurityPosture.ps1
+++ b/ActiveDirectory/Test-ADSecurityPosture.ps1
@@ -158,7 +158,7 @@ function Test-ADSecurityPosture {
# 3. Domain Controllers
Write-Host "`n[3/5] Checking Domain Controllers..." -ForegroundColor Cyan
- $dcs = Get-ADDomainController -Filter * -Server $Domain
+ $dcs = @(Get-ADDomainController -Filter * -Server $Domain)
$dcScore = 0
$maxDCScore = 20
@@ -202,7 +202,7 @@ function Test-ADSecurityPosture {
if ($IncludeTrusts) {
Write-Host "`n[4/5] Analyzing Domain Trusts..." -ForegroundColor Cyan
- $trusts = Get-ADTrust -Filter * -Server $Domain
+ $trusts = @(Get-ADTrust -Filter * -Server $Domain)
$trustScore = 0
$maxTrustScore = 20
@@ -244,7 +244,7 @@ function Test-ADSecurityPosture {
if ($IncludeGPO) {
Write-Host "`n[5/5] Analyzing Group Policy Objects..." -ForegroundColor Cyan
- $gpos = Get-GPO -All -Domain $Domain
+ $gpos = @(Get-GPO -All -Domain $Domain)
$gpoScore = 0
$maxGPOScore = 20
diff --git a/CloudSecurity/Get-AzureADRiskySignIns.ps1 b/CloudSecurity/Get-AzureADRiskySignIns.ps1
index 9a0d018..27ecd2d 100644
--- a/CloudSecurity/Get-AzureADRiskySignIns.ps1
+++ b/CloudSecurity/Get-AzureADRiskySignIns.ps1
@@ -102,13 +102,13 @@ function Get-AzureADRiskySignIns {
# Get risky sign-ins
Write-Host "`nRetrieving risky sign-in events..." -ForegroundColor Cyan
- $startDate = (Get-Date).AddDays(-$DaysBack)
+ $startDate = (Get-Date).ToUniversalTime().AddDays(-$DaysBack)
$filterDate = $startDate.ToString('yyyy-MM-ddTHH:mm:ssZ')
$riskyDetections = Get-MgRiskDetection -Filter "detectedDateTime ge $filterDate" -All -ErrorAction Stop
if ($riskyDetections) {
- Write-Host "Found $($riskyDetections.Count) risk detections" -ForegroundColor Yellow
+ Write-Host "Found $(@($riskyDetections).Count) risk detections" -ForegroundColor Yellow
foreach ($detection in $riskyDetections) {
if ($RiskLevel -ne 'All' -and $detection.RiskLevel -ne $RiskLevel.ToLower()) {
@@ -149,9 +149,9 @@ function Get-AzureADRiskySignIns {
# Calculate summary
$results.Summary.TotalRiskySignIns = $results.RiskySignIns.Count
- $results.Summary.HighRisk = ($results.RiskySignIns | Where-Object { $_.RiskLevel -eq 'high' }).Count
- $results.Summary.MediumRisk = ($results.RiskySignIns | Where-Object { $_.RiskLevel -eq 'medium' }).Count
- $results.Summary.LowRisk = ($results.RiskySignIns | Where-Object { $_.RiskLevel -eq 'low' }).Count
+ $results.Summary.HighRisk = @($results.RiskySignIns | Where-Object { $_.RiskLevel -eq 'high' }).Count
+ $results.Summary.MediumRisk = @($results.RiskySignIns | Where-Object { $_.RiskLevel -eq 'medium' }).Count
+ $results.Summary.LowRisk = @($results.RiskySignIns | Where-Object { $_.RiskLevel -eq 'low' }).Count
# Export if requested
if ($ExportPath -and $results.RiskySignIns.Count -gt 0) {
diff --git a/CloudSecurity/Test-M365SecurityPosture.ps1 b/CloudSecurity/Test-M365SecurityPosture.ps1
index 7f2d8bf..4c5f27c 100644
--- a/CloudSecurity/Test-M365SecurityPosture.ps1
+++ b/CloudSecurity/Test-M365SecurityPosture.ps1
@@ -209,7 +209,7 @@ function Test-M365SecurityPosture {
try {
$caPolicies = Get-MgIdentityConditionalAccessPolicy -All -ErrorAction Stop
- $enabledPolicies = ($caPolicies | Where-Object { $_.State -eq 'enabled' }).Count
+ $enabledPolicies = @($caPolicies | Where-Object { $_.State -eq 'enabled' }).Count
if ($enabledPolicies -gt 0) {
$results.SecurityFindings += [PSCustomObject]@{
diff --git a/Compliance/Export-ComplianceEvidence.ps1 b/Compliance/Export-ComplianceEvidence.ps1
index 28a0866..f51df08 100644
--- a/Compliance/Export-ComplianceEvidence.ps1
+++ b/Compliance/Export-ComplianceEvidence.ps1
@@ -398,7 +398,7 @@ function Export-ComplianceEvidence {
# Generate Chain of Custody
$custodyPath = Join-Path $directories.Metadata "Chain_of_Custody.txt"
- $ipInfo = Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object {$_.InterfaceAlias -notlike '*Loopback*'} | Select-Object -First 1
+ $ipInfo = Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object {$null -ne $_ -and $_.InterfaceAlias -notlike '*Loopback*'} | Select-Object -First 1
$ipAddress = if ($ipInfo) { $ipInfo.IPAddress } else { 'N/A' }
$custody = @"
CHAIN OF CUSTODY DOCUMENTATION
diff --git a/Compliance/Test-NISTCompliance.ps1 b/Compliance/Test-NISTCompliance.ps1
index 26545cd..76a471a 100644
--- a/Compliance/Test-NISTCompliance.ps1
+++ b/Compliance/Test-NISTCompliance.ps1
@@ -332,8 +332,8 @@ function Test-NISTCompliance {
try {
# SC-7: Boundary Protection - FIX: Wrap in @()
$firewallProfiles = Get-NetFirewallProfile -ErrorAction SilentlyContinue
- $disabledFirewalls = @($firewallProfiles | Where-Object { -not $_.Enabled })
- $allFirewallsEnabled = $disabledFirewalls.Count -eq 0
+ $disabledFirewalls = @($firewallProfiles | Where-Object { $null -ne $_ -and -not $_.Enabled })
+ $allFirewallsEnabled = ($null -ne $firewallProfiles) -and ($disabledFirewalls.Count -eq 0)
$control = [PSCustomObject]@{
ControlID = 'SC-7'
@@ -341,7 +341,8 @@ function Test-NISTCompliance {
ControlFamily = 'SystemProtection'
Description = 'Firewall must protect system boundaries'
Expected = 'All firewall profiles enabled'
- Actual = if ($allFirewallsEnabled) { "All enabled" } else { "Some disabled" }
+ Actual = if ($null -eq $firewallProfiles) { "Unable to retrieve firewall profiles" }
+ elseif ($allFirewallsEnabled) { "All enabled" } else { "Some disabled" }
Status = if ($allFirewallsEnabled) { 'Compliant' } else { 'NonCompliant' }
Impact = 'Critical'
Remediation = 'Enable Windows Firewall for all profiles'
diff --git a/Compliance/Test-PCI-DSS.ps1 b/Compliance/Test-PCI-DSS.ps1
index f877d66..dd6a77a 100644
--- a/Compliance/Test-PCI-DSS.ps1
+++ b/Compliance/Test-PCI-DSS.ps1
@@ -93,7 +93,7 @@ function Test-PCI-DSS {
try {
# Req 1.2: Network security controls (firewalls)
$firewallProfiles = Get-NetFirewallProfile -ErrorAction SilentlyContinue
- $allFirewallsEnabled = @($firewallProfiles | Where-Object { -not $_.Enabled }).Count -eq 0
+ $allFirewallsEnabled = ($null -ne $firewallProfiles) -and (@($firewallProfiles | Where-Object { $null -ne $_ -and -not $_.Enabled }).Count -eq 0)
$req = [PSCustomObject]@{
RequirementID = '1.2.1'
@@ -101,7 +101,8 @@ function Test-PCI-DSS {
Category = 'Network'
Description = 'Firewalls must be enabled and properly configured'
Expected = 'All firewall profiles enabled'
- Actual = if ($allFirewallsEnabled) { "All enabled" } else { "Some disabled" }
+ Actual = if ($null -eq $firewallProfiles) { "Unable to retrieve firewall profiles" }
+ elseif ($allFirewallsEnabled) { "All enabled" } else { "Some disabled" }
Status = if ($allFirewallsEnabled) { 'InPlace' } else { 'NotInPlace' }
Priority = 'Critical'
Remediation = 'Enable all Windows Firewall profiles (Domain, Private, Public)'
@@ -109,7 +110,7 @@ function Test-PCI-DSS {
$results.Requirements += $req
# Req 1.3: Inbound traffic restrictions
- $defaultInboundBlock = @($firewallProfiles | Where-Object { $_.DefaultInboundAction -ne 'Block' })
+ $defaultInboundBlock = @($firewallProfiles | Where-Object { $null -ne $_ -and $_.DefaultInboundAction -ne 'Block' })
$req = [PSCustomObject]@{
RequirementID = '1.3.1'
@@ -117,15 +118,16 @@ function Test-PCI-DSS {
Category = 'Network'
Description = 'Inbound traffic should be denied by default'
Expected = 'Default action: Block'
- Actual = if ($defaultInboundBlock.Count -eq 0) { "All blocked" } else { "$($defaultInboundBlock.Count) profiles allow" }
- Status = if ($defaultInboundBlock.Count -eq 0) { 'InPlace' } else { 'NotInPlace' }
+ Actual = if ($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' }
Priority = 'High'
Remediation = 'Set default inbound action to Block for all profiles'
}
$results.Requirements += $req
# Req 1.4: Restrict connections between untrusted networks
- $publicProfile = $firewallProfiles | Where-Object { $_.Name -eq 'Public' }
+ $publicProfile = $firewallProfiles | Where-Object { $null -ne $_ -and $_.Name -eq 'Public' }
$req = [PSCustomObject]@{
RequirementID = '1.4.1'
@@ -133,8 +135,8 @@ function Test-PCI-DSS {
Category = 'Network'
Description = 'Public network profile must be restrictive'
Expected = 'Public profile enabled and blocking inbound'
- Actual = "Enabled: $($publicProfile.Enabled), Inbound: $($publicProfile.DefaultInboundAction)"
- Status = if ($publicProfile.Enabled -and $publicProfile.DefaultInboundAction -eq 'Block') { 'InPlace' } else { 'NotInPlace' }
+ 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' }
Priority = 'High'
Remediation = 'Enable Public profile with default inbound block'
}
diff --git a/Core/Get-SystemInfo.ps1 b/Core/Get-SystemInfo.ps1
index 6ba5780..14be461 100644
--- a/Core/Get-SystemInfo.ps1
+++ b/Core/Get-SystemInfo.ps1
@@ -110,7 +110,7 @@ function Get-SystemInfo {
# Security Settings
$info.Security = [PSCustomObject]@{
LocalUsers = (@(Get-LocalUser)).Count
- LocalAdministrators = (@(Get-LocalGroupMember -Group "Administrators" -ErrorAction SilentlyContinue)).Count
+ LocalAdministrators = (@(Get-LocalGroupMember -SID 'S-1-5-32-544' -ErrorAction SilentlyContinue)).Count
PasswordPolicy = Get-LocalUser | Where-Object { $_.PasswordRequired -eq $false } |
Select-Object Name, Enabled
FirewallProfiles = Get-NetFirewallProfile | Select-Object Name, Enabled
diff --git a/Detection/Find-SuspiciousAuthentication.ps1 b/Detection/Find-SuspiciousAuthentication.ps1
index a20469b..cda4385 100644
--- a/Detection/Find-SuspiciousAuthentication.ps1
+++ b/Detection/Find-SuspiciousAuthentication.ps1
@@ -80,26 +80,26 @@ function Find-SuspiciousAuthentication {
# 1. Analyze Failed Logons (Event ID 4625)
Write-Verbose "Analyzing failed logon attempts..."
- $failedLogons = Get-WinEvent -FilterHashtable @{
+ $failedLogons = @(Get-WinEvent -FilterHashtable @{
LogName = 'Security'
ID = 4625
StartTime = $startTime
- } -ErrorAction SilentlyContinue
-
- if ($failedLogons) {
+ } -ErrorAction SilentlyContinue)
+
+ if ($failedLogons.Count -gt 0) {
$results.Statistics.TotalFailedLogons = $failedLogons.Count
-
+
foreach ($event in $failedLogons) {
$xml = [xml]$event.ToXml()
$eventData = $xml.Event.EventData.Data
-
- $targetAccount = ($eventData | Where-Object { $_.Name -eq 'TargetUserName' }).'#text'
- $targetDomain = ($eventData | Where-Object { $_.Name -eq 'TargetDomainName' }).'#text'
- $workstation = ($eventData | Where-Object { $_.Name -eq 'WorkstationName' }).'#text'
- $sourceIP = ($eventData | Where-Object { $_.Name -eq 'IpAddress' }).'#text'
- $logonType = ($eventData | Where-Object { $_.Name -eq 'LogonType' }).'#text'
- $status = ($eventData | Where-Object { $_.Name -eq 'Status' }).'#text'
- $subStatus = ($eventData | Where-Object { $_.Name -eq 'SubStatus' }).'#text'
+
+ $targetAccount = & $getEventValue $eventData 'TargetUserName'
+ $targetDomain = & $getEventValue $eventData 'TargetDomainName'
+ $workstation = & $getEventValue $eventData 'WorkstationName'
+ $sourceIP = & $getEventValue $eventData 'IpAddress'
+ $logonType = & $getEventValue $eventData 'LogonType'
+ $status = & $getEventValue $eventData 'Status'
+ $subStatus = & $getEventValue $eventData 'SubStatus'
$results.FailedLogons += [PSCustomObject]@{
TimeCreated = $event.TimeCreated
@@ -146,7 +146,7 @@ function Find-SuspiciousAuthentication {
$failedArray = @($results.FailedLogons)
if ($failedArray.Count -gt 0) {
$results.Statistics.UniqueFailedAccounts = (@($failedArray.Account | Select-Object -Unique)).Count
- $results.Statistics.UniqueSourceIPs = (@($failedArray | Where-Object { $_.SourceIP -ne '-' } | Select-Object -ExpandProperty SourceIP -Unique)).Count
+ $results.Statistics.UniqueSourceIPs = (@($failedArray | Where-Object { -not [string]::IsNullOrEmpty($_.SourceIP) -and $_.SourceIP -ne '-' } | Select-Object -ExpandProperty SourceIP -Unique)).Count
}
} catch {
Write-Verbose "Could not calculate unique statistics"
@@ -155,21 +155,21 @@ function Find-SuspiciousAuthentication {
# 2. Account Lockouts (Event ID 4740)
Write-Verbose "Checking account lockouts..."
- $lockouts = Get-WinEvent -FilterHashtable @{
+ $lockouts = @(Get-WinEvent -FilterHashtable @{
LogName = 'Security'
ID = 4740
StartTime = $startTime
- } -ErrorAction SilentlyContinue
-
- if ($lockouts) {
+ } -ErrorAction SilentlyContinue)
+
+ if ($lockouts.Count -gt 0) {
$results.Statistics.TotalLockouts = $lockouts.Count
-
+
foreach ($event in $lockouts) {
$xml = [xml]$event.ToXml()
$eventData = $xml.Event.EventData.Data
-
- $targetAccount = ($eventData | Where-Object { $_.Name -eq 'TargetUserName' }).'#text'
- $callerComputer = ($eventData | Where-Object { $_.Name -eq 'TargetDomainName' }).'#text'
+
+ $targetAccount = & $getEventValue $eventData 'TargetUserName'
+ $callerComputer = & $getEventValue $eventData 'TargetDomainName'
$results.AccountLockouts += [PSCustomObject]@{
TimeCreated = $event.TimeCreated
@@ -181,23 +181,23 @@ function Find-SuspiciousAuthentication {
# 3. Special Privileges Assigned (Event ID 4672)
Write-Verbose "Analyzing privilege escalations..."
- $privEvents = Get-WinEvent -FilterHashtable @{
+ $privEvents = @(Get-WinEvent -FilterHashtable @{
LogName = 'Security'
ID = 4672
StartTime = $startTime
- } -ErrorAction SilentlyContinue
-
- if ($privEvents) {
+ } -ErrorAction SilentlyContinue)
+
+ if ($privEvents.Count -gt 0) {
$results.Statistics.TotalPrivilegeUse = $privEvents.Count
-
+
# Look for unusual privilege assignments
foreach ($event in $privEvents) {
$xml = [xml]$event.ToXml()
$eventData = $xml.Event.EventData.Data
-
- $subjectAccount = ($eventData | Where-Object { $_.Name -eq 'SubjectUserName' }).'#text'
- $subjectDomain = ($eventData | Where-Object { $_.Name -eq 'SubjectDomainName' }).'#text'
- $privileges = ($eventData | Where-Object { $_.Name -eq 'PrivilegeList' }).'#text'
+
+ $subjectAccount = & $getEventValue $eventData 'SubjectUserName'
+ $subjectDomain = & $getEventValue $eventData 'SubjectDomainName'
+ $privileges = & $getEventValue $eventData 'PrivilegeList'
# Flag if not a well-known admin account
if ($subjectAccount -notmatch '(SYSTEM|LOCAL SERVICE|NETWORK SERVICE|Administrator|DWM-\d+|UMFD-\d+)') {
@@ -212,23 +212,23 @@ function Find-SuspiciousAuthentication {
# 4. Explicit Credentials Usage (Event ID 4648)
Write-Verbose "Checking explicit credential usage..."
- $explicitCreds = Get-WinEvent -FilterHashtable @{
+ $explicitCreds = @(Get-WinEvent -FilterHashtable @{
LogName = 'Security'
ID = 4648
StartTime = $startTime
- } -ErrorAction SilentlyContinue
-
- if ($explicitCreds) {
+ } -ErrorAction SilentlyContinue)
+
+ if ($explicitCreds.Count -gt 0) {
$results.Statistics.TotalExplicitCreds = $explicitCreds.Count
-
+
foreach ($event in $explicitCreds) {
$xml = [xml]$event.ToXml()
$eventData = $xml.Event.EventData.Data
-
- $subjectAccount = ($eventData | Where-Object { $_.Name -eq 'SubjectUserName' }).'#text'
- $targetAccount = ($eventData | Where-Object { $_.Name -eq 'TargetUserName' }).'#text'
- $targetServer = ($eventData | Where-Object { $_.Name -eq 'TargetServerName' }).'#text'
- $processName = ($eventData | Where-Object { $_.Name -eq 'ProcessName' }).'#text'
+
+ $subjectAccount = & $getEventValue $eventData 'SubjectUserName'
+ $targetAccount = & $getEventValue $eventData 'TargetUserName'
+ $targetServer = & $getEventValue $eventData 'TargetServerName'
+ $processName = & $getEventValue $eventData 'ProcessName'
$results.ExplicitCredentials += [PSCustomObject]@{
TimeCreated = $event.TimeCreated
@@ -304,7 +304,7 @@ function Find-SuspiciousAuthentication {
$reason = ""
# Check for after-hours logon (outside 7 AM - 7 PM)
- if ($hour -lt 7 -or $hour -gt 19) {
+ if ($hour -lt 7 -or $hour -ge 19) {
$isUnusual = $true
$reason = "After-hours logon"
}
diff --git a/Detection/Find-SuspiciousProcesses.ps1 b/Detection/Find-SuspiciousProcesses.ps1
index 711dd87..ca9d5c6 100644
--- a/Detection/Find-SuspiciousProcesses.ps1
+++ b/Detection/Find-SuspiciousProcesses.ps1
@@ -50,14 +50,21 @@ function Find-SuspiciousProcesses {
# Legitimate system processes that should only run from System32
$systemProcesses = @(
'svchost', 'lsass', 'services', 'csrss', 'winlogon',
- 'smss', 'wininit', 'taskhost', 'dwm', 'explorer'
+ 'smss', 'wininit', 'taskhost', 'dwm'
)
}
process {
try {
# Get all running processes with detailed info
- $processes = Get-Process -IncludeUserName -ErrorAction SilentlyContinue
+ # -IncludeUserName requires elevation; fall back to a plain listing so a
+ # non-elevated run still scans processes instead of silently returning nothing
+ $processes = @(Get-Process -IncludeUserName -ErrorAction SilentlyContinue)
+ $includeUserNames = $true
+ if ($processes.Count -eq 0) {
+ $processes = @(Get-Process -ErrorAction SilentlyContinue)
+ $includeUserNames = $false
+ }
foreach ($proc in $processes) {
$suspicionScore = 0
@@ -196,14 +203,21 @@ function Find-SuspiciousProcesses {
# If suspicion score is high enough, add to results
if ($suspicionScore -ge 40) {
+ # StartTime/CPU getters throw for protected processes; capture them
+ # safely so an inaccessible property never drops a flagged process
+ $procStartTime = $null
+ try { $procStartTime = $proc.StartTime } catch { $procStartTime = $null }
+ $procCpu = $null
+ try { $procCpu = $proc.CPU } catch { $procCpu = $null }
+
$suspiciousProcesses += [PSCustomObject]@{
ProcessName = $proc.ProcessName
ProcessId = $proc.Id
Path = $processPath
CommandLine = if ($cimProcess) { $cimProcess.CommandLine } else { 'N/A' }
- UserName = $proc.UserName
- StartTime = $proc.StartTime
- CPU = [math]::Round($proc.CPU, 2)
+ UserName = if ($includeUserNames) { $proc.UserName } else { 'N/A' }
+ StartTime = $procStartTime
+ CPU = if ($null -ne $procCpu) { [math]::Round($procCpu, 2) } else { $null }
WorkingSet = [math]::Round($proc.WorkingSet64 / 1MB, 2)
SuspicionScore = $suspicionScore
Reasons = ($suspicionReasons -join '; ')
diff --git a/Detection/Get-CredentialAccessEvents.ps1 b/Detection/Get-CredentialAccessEvents.ps1
index e41a773..2e94585 100644
--- a/Detection/Get-CredentialAccessEvents.ps1
+++ b/Detection/Get-CredentialAccessEvents.ps1
@@ -53,7 +53,9 @@ function Get-CredentialAccessEvents {
$startTime = (Get-Date).AddHours(-$Hours)
# Granted-access masks that are normal for DLL loads / telemetry against lsass.exe
- $normalAccessMasks = @('0x1000', '0x1400', '0x1410')
+ # (masks containing PROCESS_VM_READ 0x0010 never reach this list - the bit test
+ # below classifies them as suspicious first)
+ $normalAccessMasks = @('0x1000', '0x1400')
# PROCESS_VM_READ (0x0010) or broad rights (PROCESS_ALL_ACCESS style) are suspicious
$suspiciousAccessMasks = @('0x1010', '0x101a', '0x103a', '0x143a', '0x1f0fff', '0x1fffff')
diff --git a/Enterprise/Invoke-EnterpriseSecurityScan.ps1 b/Enterprise/Invoke-EnterpriseSecurityScan.ps1
index a486018..df081ab 100644
--- a/Enterprise/Invoke-EnterpriseSecurityScan.ps1
+++ b/Enterprise/Invoke-EnterpriseSecurityScan.ps1
@@ -12,7 +12,7 @@ function Invoke-EnterpriseSecurityScan {
.PARAMETER ScanType
Type of scan: Quick, Standard, or Comprehensive
.PARAMETER MaxThreads
- Maximum number of concurrent scans (default: 10)
+ Maximum number of concurrent scans (1-512, default: 10)
.PARAMETER OutputPath
Path to save scan results
.EXAMPLE
@@ -35,6 +35,7 @@ function Invoke-EnterpriseSecurityScan {
[string]$ScanType = 'Standard',
[Parameter()]
+ [ValidateRange(1, 512)]
[int]$MaxThreads = 10,
[Parameter()]
@@ -196,12 +197,14 @@ function Invoke-EnterpriseSecurityScan {
# Check disk space
$drives = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=3"
foreach ($drive in $drives) {
- $freePercent = ($drive.FreeSpace / $drive.Size) * 100
- if ($freePercent -lt 10) {
- $result.Findings += [PSCustomObject]@{
- Severity = 'High'
- Category = 'Disk Space'
- Finding = "Drive $($drive.DeviceID) has less than 10% free space"
+ if ($drive.Size -gt 0) {
+ $freePercent = ($drive.FreeSpace / $drive.Size) * 100
+ if ($freePercent -lt 10) {
+ $result.Findings += [PSCustomObject]@{
+ Severity = 'High'
+ Category = 'Disk Space'
+ Finding = "Drive $($drive.DeviceID) has less than 10% free space"
+ }
}
}
}
@@ -225,13 +228,14 @@ function Invoke-EnterpriseSecurityScan {
}
process {
+ $runspacePool = $null
+ $jobs = @()
try {
Write-Host "`nStarting parallel scan of $($ComputerName.Count) systems..." -ForegroundColor Cyan
# Create runspace pool for parallel execution
$runspacePool = [runspacefactory]::CreateRunspacePool(1, $MaxThreads)
$runspacePool.Open()
- $jobs = @()
foreach ($computer in $ComputerName) {
Write-Verbose "Queuing scan for: $computer"
@@ -360,15 +364,27 @@ function Invoke-EnterpriseSecurityScan {
}
}
- # Close runspace pool
- $runspacePool.Close()
- $runspacePool.Dispose()
+ # Runspace pool is closed/disposed in the finally block below
}
catch {
Write-Error "Error during enterprise scan: $_"
throw
}
+ finally {
+ # Guarantee cleanup of async pipelines and the runspace pool, even on failure
+ foreach ($job in $jobs) {
+ if ($null -ne $job.Pipeline) {
+ $job.Pipeline.Dispose()
+ }
+ }
+ if ($null -ne $runspacePool) {
+ if ($runspacePool.RunspacePoolStateInfo.State -eq 'Opened') {
+ $runspacePool.Close()
+ }
+ $runspacePool.Dispose()
+ }
+ }
}
end {
diff --git a/Enterprise/Invoke-SecurityAssessment.ps1 b/Enterprise/Invoke-SecurityAssessment.ps1
index d6c4f08..9b96242 100644
--- a/Enterprise/Invoke-SecurityAssessment.ps1
+++ b/Enterprise/Invoke-SecurityAssessment.ps1
@@ -416,8 +416,8 @@ function Invoke-SecurityAssessment {
Details = "$($localUsers.Count) enabled accounts"
}
- # Administrator account status
- $adminAccount = Get-LocalUser -Name "Administrator" -ErrorAction SilentlyContinue
+ # Administrator account status (well-known SID RID 500 - culture-invariant)
+ $adminAccount = @(Get-LocalUser -ErrorAction SilentlyContinue | Where-Object { $null -ne $_.SID -and $_.SID.Value -match '-500$' }) | Select-Object -First 1
if ($adminAccount -and $adminAccount.Enabled -eq $false) {
$accountSecurity.CategoryScore += 20
$accountSecurity.Checks += [PSCustomObject]@{
@@ -442,8 +442,8 @@ function Invoke-SecurityAssessment {
}
}
- # Guest account
- $guestAccount = Get-LocalUser -Name "Guest" -ErrorAction SilentlyContinue
+ # Guest account (well-known SID RID 501 - culture-invariant)
+ $guestAccount = @(Get-LocalUser -ErrorAction SilentlyContinue | Where-Object { $null -ne $_.SID -and $_.SID.Value -match '-501$' }) | Select-Object -First 1
if ($guestAccount -and $guestAccount.Enabled -eq $false) {
$accountSecurity.CategoryScore += 15
$accountSecurity.Checks += [PSCustomObject]@{
diff --git a/Forensics/Export-MemoryDump.ps1 b/Forensics/Export-MemoryDump.ps1
index c634e46..484f4bd 100644
--- a/Forensics/Export-MemoryDump.ps1
+++ b/Forensics/Export-MemoryDump.ps1
@@ -179,6 +179,9 @@ function Export-MemoryDump {
if (-not $result.Success) {
Write-Host "`n[2/3] Attempting MiniDumpWriteDump method..." -ForegroundColor Cyan
+ $processHandle = [IntPtr]::Zero
+ $fileStream = $null
+
try {
# FIXED: Define complete P/Invoke signatures with proper types
Add-Type -TypeDefinition @"
@@ -254,7 +257,9 @@ public class ProcessDump {
)
$fileStream.Close()
+ $fileStream = $null
[ProcessDump]::CloseHandle($processHandle) | Out-Null
+ $processHandle = [IntPtr]::Zero
if ($success -and (Test-Path $dumpFilePath)) {
$result.Success = $true
@@ -271,6 +276,10 @@ public class ProcessDump {
Write-Warning "MiniDumpWriteDump failed: $_"
$result.ErrorMessage = $_.Exception.Message
+ # Release resources if the attempt failed after they were acquired
+ if ($null -ne $fileStream) { $fileStream.Dispose() }
+ if ($processHandle -ne [IntPtr]::Zero) { [ProcessDump]::CloseHandle($processHandle) | Out-Null }
+
# Clean up failed dump file
if (Test-Path $dumpFilePath) {
Remove-Item $dumpFilePath -Force -ErrorAction SilentlyContinue
diff --git a/Forensics/Get-ArtifactCollection.ps1 b/Forensics/Get-ArtifactCollection.ps1
index 1689d5a..3287744 100644
--- a/Forensics/Get-ArtifactCollection.ps1
+++ b/Forensics/Get-ArtifactCollection.ps1
@@ -204,8 +204,8 @@ function Get-ArtifactCollection {
$safeName = $logName -replace '/', '-'
$logPath = Join-Path $paths.EventLogs "$safeName.evtx"
- # Export using wevtutil
- wevtutil epl $logName $logPath /ow:true 2>&1 | Out-Null
+ # Export using wevtutil (quote the destination: output path may contain spaces)
+ wevtutil epl $logName "$logPath" /ow:true 2>&1 | Out-Null
if (Test-Path $logPath) {
Write-Host " Exported successfully" -ForegroundColor Green
@@ -241,7 +241,7 @@ function Get-ArtifactCollection {
$savePath = Join-Path $paths.Registry $hive.Name
- $regOutput = reg save $hive.RegPath $savePath /y 2>&1
+ $regOutput = reg save $hive.RegPath "$savePath" /y 2>&1
if (Test-Path $savePath) {
Write-Host " Saved successfully" -ForegroundColor Green
@@ -382,7 +382,7 @@ function Get-ArtifactCollection {
try {
# Running processes
- Get-Process | Select-Object Name, Id, Path, StartTime, @{N='WorkingSetMB';E={[Math]::Round($_.WorkingSet/1MB,2)}} |
+ Get-Process | Select-Object Name, Id, Path, StartTime, @{N='WorkingSetMB';E={[Math]::Round($_.WorkingSet64/1MB,2)}} |
ConvertTo-Json | Out-File (Join-Path $paths.Execution "Processes.json")
# Services
@@ -503,7 +503,10 @@ function Get-ArtifactCollection {
if (Test-Path $zipPath) {
$zipFile = Get-Item $zipPath
$zipSizeMB = [Math]::Round($zipFile.Length / 1MB, 2)
- $compressionRatio = [Math]::Round((1 - ($zipFile.Length / $results.Summary.TotalSize)) * 100, 1)
+ # TotalSize can be 0/$null when every collector produced no files
+ $compressionRatio = if ($results.Summary.TotalSize -gt 0) {
+ [Math]::Round((1 - ($zipFile.Length / $results.Summary.TotalSize)) * 100, 1)
+ } else { 0 }
Write-Host " Archive created: $zipPath" -ForegroundColor Green
Write-Host " Compressed Size: $zipSizeMB MB" -ForegroundColor Cyan
diff --git a/Forensics/Get-ExecutionArtifacts.ps1 b/Forensics/Get-ExecutionArtifacts.ps1
index b222569..01f1dd5 100644
--- a/Forensics/Get-ExecutionArtifacts.ps1
+++ b/Forensics/Get-ExecutionArtifacts.ps1
@@ -93,12 +93,14 @@ function Get-ExecutionArtifacts {
$prefetchFiles = @(Get-ChildItem -Path $prefetchPath -Filter "*.pf" -ErrorAction SilentlyContinue)
foreach ($file in $prefetchFiles) {
- # Extract executable name from prefetch filename (format: EXECUTABLE-HASH.pf)
- $executableName = ($file.BaseName -split '-')[0]
+ # Prefetch filename format: EXECUTABLE.EXE-8HEXDIGITS.pf. The executable
+ # name itself may contain hyphens, so strip only the trailing hash suffix
+ # instead of splitting on the first hyphen
+ $executableName = $file.BaseName -replace '-[0-9A-Fa-f]{8}$', ''
$results.Artifacts += [PSCustomObject]@{
Source = 'Prefetch'
- ExecutableName = "$executableName.exe"
+ ExecutableName = $executableName
FullPath = $null
Timestamp = $file.LastWriteTime
TimestampType = 'Last Executed (Approximate)'
@@ -246,11 +248,12 @@ function Get-ExecutionArtifacts {
Source = 'ShimCache'
ExecutableName = 'ShimCache Binary Data'
FullPath = $shimCachePath
- Timestamp = Get-Date
+ Timestamp = $null # No timestamp extracted - do not fabricate scan time
TimestampType = 'Registry Key'
Details = @{
Note = 'Binary data present - use ShimCacheParser.exe for full analysis'
DataSize = $shimData.AppCompatCache.Length
+ TimestampNote = 'Timestamp not extracted (binary parsing not implemented)'
}
}
@@ -465,7 +468,7 @@ function Get-ExecutionArtifacts {
if ($Format -in @('CSV', 'All')) {
$csvPath = Join-Path $OutputPath "$reportName.csv"
$results.Artifacts | Select-Object Source, ExecutableName, FullPath, Timestamp, TimestampType |
- Export-Csv $csvPath -NoTypeInformation
+ Export-Csv $csvPath -NoTypeInformation -Encoding UTF8
Write-Host " CSV report saved: $csvPath" -ForegroundColor Green
}
@@ -525,7 +528,9 @@ function ConvertFrom-ROT13 {
$result = ""
foreach ($char in $Text.ToCharArray()) {
if ($char -match '[A-Za-z]') {
- $base = if ($char -match '[A-Z]') { 65 } else { 97 }
+ # -cmatch is mandatory here: -match is case-insensitive, which would
+ # pin $base to 65 and corrupt every lowercase letter
+ $base = if ($char -cmatch '[A-Z]') { 65 } else { 97 }
$result += [char](($([int]$char - $base + 13) % 26) + $base)
}
else {
@@ -610,8 +615,13 @@ function Generate-ExecutionArtifactsHTML {
foreach ($artifact in $Results.Artifacts) {
$sourceClass = "source-$($artifact.Source.ToLower())"
$timestamp = if ($null -ne $artifact.Timestamp) { $artifact.Timestamp.ToString('yyyy-MM-dd HH:mm:ss') } else { 'N/A' }
+ $executableName = if ($artifact.ExecutableName) {
+ $artifact.ExecutableName -replace '&', '&amp;' -replace '<', '&lt;' -replace '>', '&gt;'
+ } else {
+ 'N/A'
+ }
$fullPath = if ($artifact.FullPath) {
- $artifact.FullPath -replace '<', '&lt;' -replace '>', '&gt;'
+ $artifact.FullPath -replace '&', '&amp;' -replace '<', '&lt;' -replace '>', '&gt;'
} else {
'N/A'
}
@@ -619,7 +629,7 @@ function Generate-ExecutionArtifactsHTML {
$html += @"
<tr>
<td><span class="source-badge $sourceClass">$($artifact.Source)</span></td>
- <td><strong>$($artifact.ExecutableName)</strong></td>
+ <td><strong>$executableName</strong></td>
<td><span class="path">$fullPath</span></td>
<td>$timestamp</td>
<td><small>$($artifact.TimestampType)</small></td>
diff --git a/Forensics/Get-USBHistory.ps1 b/Forensics/Get-USBHistory.ps1
index 59a996e..6e79fae 100644
--- a/Forensics/Get-USBHistory.ps1
+++ b/Forensics/Get-USBHistory.ps1
@@ -98,6 +98,18 @@ function Get-USBHistory {
$installDate = $props.FirstInstallDate
}
+ # Registry date values are REG_SZ strings, not DateTime - coerce so
+ # date sorting and .ToString('yyyy-MM-dd HH:mm:ss') rendering stay safe
+ if ($null -ne $installDate -and $installDate -isnot [DateTime]) {
+ $parsedInstallDate = [DateTime]::MinValue
+ if ([DateTime]::TryParse([string]$installDate, [ref]$parsedInstallDate)) {
+ $installDate = $parsedInstallDate
+ }
+ else {
+ $installDate = $null
+ }
+ }
+
$deviceInfo = [PSCustomObject]@{
Type = 'Storage'
FriendlyName = $friendlyName
@@ -167,6 +179,18 @@ function Get-USBHistory {
# Timestamp not available
}
+ # Registry date values are REG_SZ strings, not DateTime - coerce so
+ # date sorting and .ToString('yyyy-MM-dd HH:mm:ss') rendering stay safe
+ if ($null -ne $installDate -and $installDate -isnot [DateTime]) {
+ $parsedInstallDate = [DateTime]::MinValue
+ if ([DateTime]::TryParse([string]$installDate, [ref]$parsedInstallDate)) {
+ $installDate = $parsedInstallDate
+ }
+ else {
+ $installDate = $null
+ }
+ }
+
$deviceInfo = [PSCustomObject]@{
Type = 'USB Device'
FriendlyName = $props.FriendlyName
@@ -312,7 +336,7 @@ function Get-USBHistory {
# Export CSV
if ($Format -in @('CSV', 'All')) {
$csvPath = Join-Path $OutputPath "$reportName.csv"
- $results.USBDevices | Export-Csv $csvPath -NoTypeInformation
+ $results.USBDevices | Export-Csv $csvPath -NoTypeInformation -Encoding UTF8
Write-Host " CSV report saved: $csvPath" -ForegroundColor Green
}
@@ -431,15 +455,19 @@ function Generate-USBHistoryHTML {
} else {
'Unknown'
}
- $friendlyName = $device.FriendlyName -replace '<', '&lt;' -replace '>', '&gt;'
+ $friendlyName = $device.FriendlyName -replace '&', '&amp;' -replace '<', '&lt;' -replace '>', '&gt;'
+ # Device instance IDs legitimately contain '&' (e.g. "...&0") - escape for HTML
+ $vendor = $device.Vendor -replace '&', '&amp;' -replace '<', '&lt;' -replace '>', '&gt;'
+ $product = $device.Product -replace '&', '&amp;' -replace '<', '&lt;' -replace '>', '&gt;'
+ $serialNumber = $device.SerialNumber -replace '&', '&amp;' -replace '<', '&lt;' -replace '>', '&gt;'
$html += @"
<tr>
<td><span class="device-type $typeClass">$($device.Type)</span></td>
<td><strong>$friendlyName</strong></td>
- <td>$($device.Vendor)</td>
- <td>$($device.Product)</td>
- <td><span class="serial">$($device.SerialNumber)</span></td>
+ <td>$vendor</td>
+ <td>$product</td>
+ <td><span class="serial">$serialNumber</span></td>
<td>$lastConnected</td>
</tr>
"@
@@ -466,7 +494,7 @@ function Generate-USBHistoryHTML {
} else {
'N/A'
}
- $message = $event.Message -replace '<', '&lt;' -replace '>', '&gt;'
+ $message = $event.Message -replace '&', '&amp;' -replace '<', '&lt;' -replace '>', '&gt;'
$html += @"
<tr>
diff --git a/Forensics/Get-UserActivityArtifacts.ps1 b/Forensics/Get-UserActivityArtifacts.ps1
index 5c586de..8da149f 100644
--- a/Forensics/Get-UserActivityArtifacts.ps1
+++ b/Forensics/Get-UserActivityArtifacts.ps1
@@ -405,16 +405,16 @@ function Get-UserActivityArtifacts {
}
if (@($results.RecycleBin).Count -gt 0) {
- $results.RecycleBin | Export-Csv -Path (Join-Path $OutputPath 'RecycleBin.csv') -NoTypeInformation
+ $results.RecycleBin | 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
+ $results.RecentLinks | 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
+ $results.JumpLists | 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
+ $results.Timeline | 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 bb395a1..b8b4543 100644
--- a/Forensics/New-ForensicTimeline.ps1
+++ b/Forensics/New-ForensicTimeline.ps1
@@ -333,7 +333,7 @@ function New-ForensicTimeline {
if ($Format -in @('CSV', 'All')) {
$csvPath = Join-Path $OutputPath "$reportName.csv"
$timeline.Events | Select-Object Timestamp, Source, Category, Level, Message |
- Export-Csv $csvPath -NoTypeInformation
+ Export-Csv $csvPath -NoTypeInformation -Encoding UTF8
Write-Host " CSV timeline saved: $csvPath" -ForegroundColor Green
}
@@ -495,7 +495,7 @@ function Generate-TimelineHTML {
$sourceClass = "source-$($event.Source.ToLower())"
$timestamp = if ($event.Timestamp) { $event.Timestamp.ToString('yyyy-MM-dd HH:mm:ss') } else { 'N/A' }
$message = if ($event.Message) {
- $event.Message -replace '<', '&lt;' -replace '>', '&gt;'
+ $event.Message -replace '&', '&amp;' -replace '<', '&lt;' -replace '>', '&gt;'
} else {
'No message available'
}
diff --git a/Hardening/Enable-AuditPolicies.ps1 b/Hardening/Enable-AuditPolicies.ps1
index f178a40..f09bbdd 100644
--- a/Hardening/Enable-AuditPolicies.ps1
+++ b/Hardening/Enable-AuditPolicies.ps1
@@ -139,9 +139,11 @@ function Enable-AuditPolicies {
# Force audit policy subcategory settings
try {
$regPath = "HKLM:\System\CurrentControlSet\Control\Lsa"
- Set-ItemProperty -Path $regPath -Name "SCENoApplyLegacyAuditPolicy" -Value 1 -Type DWord -Force
- Write-Host " + Advanced audit policy mode enabled" -ForegroundColor Green
- $results.PoliciesConfigured += "Advanced Audit Policy Mode"
+ if ($PSCmdlet.ShouldProcess($regPath, "Enable advanced audit policy mode (SCENoApplyLegacyAuditPolicy)")) {
+ Set-ItemProperty -Path $regPath -Name "SCENoApplyLegacyAuditPolicy" -Value 1 -Type DWord -Force
+ Write-Host " + Advanced audit policy mode enabled" -ForegroundColor Green
+ $results.PoliciesConfigured += "Advanced Audit Policy Mode"
+ }
}
catch {
$results.Errors += "Failed to enable advanced audit mode: $_"
@@ -151,14 +153,16 @@ function Enable-AuditPolicies {
# Increase Security event log size
try {
$logName = 'Security'
- $log = Get-WinEvent -ListLog $logName
-
- # Set to 1GB
- $log.MaximumSizeInBytes = 1GB
- $log.SaveChanges()
-
- Write-Host " + Security log size increased to 1GB" -ForegroundColor Green
- $results.PoliciesConfigured += "Security Log Size: 1GB"
+ if ($PSCmdlet.ShouldProcess($logName, "Set Security event log maximum size to 1GB")) {
+ $log = Get-WinEvent -ListLog $logName
+
+ # Set to 1GB
+ $log.MaximumSizeInBytes = 1GB
+ $log.SaveChanges()
+
+ Write-Host " + Security log size increased to 1GB" -ForegroundColor Green
+ $results.PoliciesConfigured += "Security Log Size: 1GB"
+ }
}
catch {
$results.Errors += "Failed to increase log size: $_"
@@ -167,9 +171,11 @@ function Enable-AuditPolicies {
# Enable log retention
try {
- wevtutil sl Security /rt:false /ab:true
- Write-Host " + Security log retention enabled" -ForegroundColor Green
- $results.PoliciesConfigured += "Security Log Retention"
+ if ($PSCmdlet.ShouldProcess("Security", "Configure Security log retention (archive full log, no overwrite)")) {
+ wevtutil sl Security /rt:false /ab:true
+ Write-Host " + Security log retention enabled" -ForegroundColor Green
+ $results.PoliciesConfigured += "Security Log Retention"
+ }
}
catch {
$results.Errors += "Failed to configure log retention: $_"
@@ -180,12 +186,14 @@ function Enable-AuditPolicies {
Write-Host "`n[PROCESS] Enabling command line process auditing..." -ForegroundColor Cyan
try {
$regPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit"
- if (-not (Test-Path $regPath)) {
- New-Item -Path $regPath -Force | Out-Null
+ if ($PSCmdlet.ShouldProcess($regPath, "Enable command line process auditing")) {
+ if (-not (Test-Path $regPath)) {
+ New-Item -Path $regPath -Force | Out-Null
+ }
+ Set-ItemProperty -Path $regPath -Name "ProcessCreationIncludeCmdLine_Enabled" -Value 1 -Type DWord -Force
+ Write-Host " + Command line auditing enabled" -ForegroundColor Green
+ $results.PoliciesConfigured += "Command Line Process Auditing"
}
- Set-ItemProperty -Path $regPath -Name "ProcessCreationIncludeCmdLine_Enabled" -Value 1 -Type DWord -Force
- Write-Host " + Command line auditing enabled" -ForegroundColor Green
- $results.PoliciesConfigured += "Command Line Process Auditing"
}
catch {
$results.Errors += "Failed to enable command line auditing: $_"
@@ -203,33 +211,39 @@ function Enable-AuditPolicies {
"$env:USERPROFILE\Documents"
)
+ $fileAuditApplied = $false
foreach ($path in $pathsToAudit) {
if (Test-Path $path) {
try {
- # Get current ACL
- $acl = Get-Acl $path
-
- # Create audit rule for Everyone - Track both Success and Failure
- $auditRule = New-Object System.Security.AccessControl.FileSystemAuditRule(
- "Everyone",
- "Delete,DeleteSubdirectoriesAndFiles,ChangePermissions,TakeOwnership",
- "ContainerInherit,ObjectInherit",
- "None",
- "Success,Failure"
- )
-
- # Add audit rule
- $acl.AddAuditRule($auditRule)
- Set-Acl -Path $path -AclObject $acl
-
- Write-Host " + Auditing enabled on: $path" -ForegroundColor Green
+ if ($PSCmdlet.ShouldProcess($path, "Add file system audit rule (Everyone: Delete/ChangePermissions/TakeOwnership)")) {
+ # Get current ACL
+ $acl = Get-Acl $path
+
+ # Create audit rule for Everyone - Track both Success and Failure
+ $auditRule = New-Object System.Security.AccessControl.FileSystemAuditRule(
+ "Everyone",
+ "Delete,DeleteSubdirectoriesAndFiles,ChangePermissions,TakeOwnership",
+ "ContainerInherit,ObjectInherit",
+ "None",
+ "Success,Failure"
+ )
+
+ # Add audit rule
+ $acl.AddAuditRule($auditRule)
+ Set-Acl -Path $path -AclObject $acl
+
+ Write-Host " + Auditing enabled on: $path" -ForegroundColor Green
+ $fileAuditApplied = $true
+ }
}
catch {
Write-Warning " - Failed to audit: $path"
}
}
}
- $results.PoliciesConfigured += "File System Auditing"
+ if ($fileAuditApplied) {
+ $results.PoliciesConfigured += "File System Auditing"
+ }
}
# Registry Auditing
@@ -242,30 +256,36 @@ function Enable-AuditPolicies {
"HKLM:\SYSTEM\CurrentControlSet\Services"
)
+ $registryAuditApplied = $false
foreach ($regKey in $regKeysToAudit) {
if (Test-Path $regKey) {
try {
- $acl = Get-Acl $regKey
-
- $auditRule = New-Object System.Security.AccessControl.RegistryAuditRule(
- "Everyone",
- "SetValue,CreateSubKey,Delete",
- "ContainerInherit",
- "None",
- "Success,Failure"
- )
-
- $acl.AddAuditRule($auditRule)
- Set-Acl -Path $regKey -AclObject $acl
-
- Write-Host " + Auditing enabled on: $regKey" -ForegroundColor Green
+ if ($PSCmdlet.ShouldProcess($regKey, "Add registry audit rule (Everyone: SetValue/CreateSubKey/Delete)")) {
+ $acl = Get-Acl $regKey
+
+ $auditRule = New-Object System.Security.AccessControl.RegistryAuditRule(
+ "Everyone",
+ "SetValue,CreateSubKey,Delete",
+ "ContainerInherit",
+ "None",
+ "Success,Failure"
+ )
+
+ $acl.AddAuditRule($auditRule)
+ Set-Acl -Path $regKey -AclObject $acl
+
+ Write-Host " + Auditing enabled on: $regKey" -ForegroundColor Green
+ $registryAuditApplied = $true
+ }
}
catch {
Write-Warning " - Failed to audit: $regKey"
}
}
}
- $results.PoliciesConfigured += "Registry Auditing"
+ if ($registryAuditApplied) {
+ $results.PoliciesConfigured += "Registry Auditing"
+ }
}
}
diff --git a/Hardening/Enable-PowerShellSecurity.ps1 b/Hardening/Enable-PowerShellSecurity.ps1
index 9cea56f..037a6d9 100644
--- a/Hardening/Enable-PowerShellSecurity.ps1
+++ b/Hardening/Enable-PowerShellSecurity.ps1
@@ -214,14 +214,16 @@ function Enable-PowerShellSecurity {
Write-Host "`n[WSMAN] Configuring Windows Remote Management Security..." -ForegroundColor Cyan
try {
- # Disable Basic Authentication
- Set-Item WSMan:\localhost\Service\Auth\Basic -Value $false -Force
- $results.Changes += "WSMAN Basic Authentication disabled"
- Write-Host " WSMAN Basic Auth: Disabled" -ForegroundColor Green
-
- # Enable Kerberos
- Set-Item WSMan:\localhost\Service\Auth\Kerberos -Value $true -Force
- Write-Host " WSMAN Kerberos: Enabled" -ForegroundColor Green
+ if ($PSCmdlet.ShouldProcess("WSMAN Service", "Disable Basic authentication and enable Kerberos")) {
+ # Disable Basic Authentication
+ Set-Item WSMan:\localhost\Service\Auth\Basic -Value $false -Force
+ $results.Changes += "WSMAN Basic Authentication disabled"
+ Write-Host " WSMAN Basic Auth: Disabled" -ForegroundColor Green
+
+ # Enable Kerberos
+ Set-Item WSMan:\localhost\Service\Auth\Kerberos -Value $true -Force
+ Write-Host " WSMAN Kerberos: Enabled" -ForegroundColor Green
+ }
} catch {
Write-Warning " Could not configure WSMAN: $_"
diff --git a/Hardening/Invoke-SecurityRemediation.ps1 b/Hardening/Invoke-SecurityRemediation.ps1
index fd060e4..216d80b 100644
--- a/Hardening/Invoke-SecurityRemediation.ps1
+++ b/Hardening/Invoke-SecurityRemediation.ps1
@@ -203,23 +203,32 @@ function Invoke-SecurityRemediation {
FindingPattern = 'guest account|guest user'
RequiresAdmin = $true
Action = {
- Disable-LocalUser -Name "Guest" -ErrorAction Stop
+ # Look up the built-in Guest account by well-known SID RID 501 (culture-invariant)
+ $guestAccount = @(Get-LocalUser -ErrorAction Stop | Where-Object { $null -ne $_.SID -and $_.SID.Value -match '-501$' }) | Select-Object -First 1
+ if ($null -eq $guestAccount) {
+ throw "Built-in Guest account (RID 501) was not found on this system."
+ }
+ Disable-LocalUser -SID $guestAccount.SID -ErrorAction Stop
}
Verify = {
- $guest = Get-LocalUser -Name "Guest" -ErrorAction Stop
- return (-not $guest.Enabled)
+ $guest = @(Get-LocalUser -ErrorAction Stop | Where-Object { $null -ne $_.SID -and $_.SID.Value -match '-501$' }) | Select-Object -First 1
+ return ($null -ne $guest -and -not $guest.Enabled)
}
Rollback = {
$wasEnabled = $false
+ $guestSid = $null
try {
- $guest = Get-LocalUser -Name "Guest" -ErrorAction Stop
- $wasEnabled = [bool]$guest.Enabled
+ $guest = @(Get-LocalUser -ErrorAction Stop | Where-Object { $null -ne $_.SID -and $_.SID.Value -match '-501$' }) | Select-Object -First 1
+ if ($null -ne $guest) {
+ $wasEnabled = [bool]$guest.Enabled
+ $guestSid = $guest.SID.Value
+ }
}
catch {
$wasEnabled = $false
}
- if ($wasEnabled) {
- return @("Enable-LocalUser -Name 'Guest'")
+ if ($wasEnabled -and $guestSid) {
+ return @("Enable-LocalUser -SID '$guestSid'")
}
return @("# Guest account was already disabled; no rollback action required")
}
@@ -319,6 +328,10 @@ function Invoke-SecurityRemediation {
elseif ($null -ne $item.PSObject.Properties['Finding']) {
$allFindings += $item
}
+ elseif ($item -is [System.Collections.IEnumerable] -and $item -isnot [string] -and $item -isnot [hashtable]) {
+ # A bare findings array bound directly to -InputObject (pipeline input arrives item-by-item)
+ $allFindings += @($item)
+ }
}
$results.FindingsProcessed = @($allFindings).Count
@@ -445,9 +458,6 @@ function Invoke-SecurityRemediation {
# --- Write rollback script (captured pre-change values only) ---
if ($GenerateRollback -and @($rollbackScriptLines).Count -gt 0) {
try {
- if (-not (Test-Path -Path $RollbackDirectory)) {
- New-Item -Path $RollbackDirectory -ItemType Directory -Force | Out-Null
- }
$rollbackFile = Join-Path -Path $RollbackDirectory -ChildPath "SecurityRemediation_Rollback_$(Get-Date -Format 'yyyyMMdd_HHmmss').ps1"
$header = @(
@@ -459,6 +469,9 @@ function Invoke-SecurityRemediation {
)
if ($PSCmdlet.ShouldProcess($rollbackFile, "Write rollback script")) {
+ if (-not (Test-Path -Path $RollbackDirectory)) {
+ New-Item -Path $RollbackDirectory -ItemType Directory -Force | Out-Null
+ }
Set-Content -Path $rollbackFile -Value (($header + $rollbackScriptLines) -join [Environment]::NewLine) -Encoding UTF8 -ErrorAction Stop
$results.RollbackPath = $rollbackFile
Write-Host "`n[ROLLBACK] Rollback script written: $rollbackFile" -ForegroundColor Green
diff --git a/Hardening/Set-SecurityBaseline.ps1 b/Hardening/Set-SecurityBaseline.ps1
index 92ee4a3..1874623 100644
--- a/Hardening/Set-SecurityBaseline.ps1
+++ b/Hardening/Set-SecurityBaseline.ps1
@@ -72,6 +72,7 @@ function Set-SecurityBaseline {
$uacPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
+ if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Apply UAC hardening settings")) {
try {
# Enable UAC
Set-ItemProperty -Path $uacPath -Name "EnableLUA" -Value 1 -Type DWord -Force
@@ -103,11 +104,13 @@ function Set-SecurityBaseline {
$results.Errors += "UAC configuration failed: $_"
Write-Warning " UAC configuration failed: $_"
}
+ }
# Category 2: Windows Firewall
Write-Host "`n[2/7] Configuring Windows Firewall..." -ForegroundColor Cyan
if ($ConfigureFirewall -or $BaselineLevel -in @('Recommended', 'Strict')) {
+ if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Apply Windows Firewall baseline settings")) {
try {
# Enable firewall for all profiles
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True
@@ -140,6 +143,7 @@ function Set-SecurityBaseline {
$results.Errors += "Firewall configuration failed: $_"
Write-Warning " Firewall configuration failed: $_"
}
+ }
}
else {
Write-Host " Firewall: Skipped" -ForegroundColor Yellow
@@ -148,6 +152,7 @@ function Set-SecurityBaseline {
# Category 3: Windows Defender
Write-Host "`n[3/7] Configuring Windows Defender..." -ForegroundColor Cyan
+ if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Apply Windows Defender baseline settings")) {
try {
# Enable Real-Time Protection
Set-MpPreference -DisableRealtimeMonitoring $false -ErrorAction Stop
@@ -188,10 +193,12 @@ function Set-SecurityBaseline {
$results.Errors += "Windows Defender configuration failed: $_"
Write-Warning " Windows Defender configuration failed: $_"
}
+ }
# Category 4: Network Security
Write-Host "`n[4/7] Configuring Network Security..." -ForegroundColor Cyan
+ if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Apply network security baseline settings")) {
try {
# Disable SMBv1
if ($DisableSMBv1 -or $BaselineLevel -in @('Recommended', 'Strict')) {
@@ -237,14 +244,19 @@ function Set-SecurityBaseline {
$results.Errors += "Network security configuration failed: $_"
Write-Warning " Network security configuration failed: $_"
}
+ }
# Category 5: Account Security
Write-Host "`n[5/7] Configuring Account Security..." -ForegroundColor Cyan
+ if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Apply account security baseline settings")) {
try {
- # Disable Guest account
- Disable-LocalUser -Name "Guest" -ErrorAction SilentlyContinue
- $results.Changes += "Guest account disabled"
+ # Disable Guest account (well-known SID RID 501 - culture-invariant)
+ $guestToDisable = @(Get-LocalUser -ErrorAction SilentlyContinue | Where-Object { $null -ne $_.SID -and $_.SID.Value -match '-501$' }) | Select-Object -First 1
+ if ($null -ne $guestToDisable -and $guestToDisable.Enabled) {
+ Disable-LocalUser -SID $guestToDisable.SID -ErrorAction SilentlyContinue
+ $results.Changes += "Guest account disabled"
+ }
# Rename Administrator account (if desired in Strict mode)
if ($BaselineLevel -eq 'Strict') {
@@ -275,10 +287,12 @@ function Set-SecurityBaseline {
$results.Errors += "Account security configuration failed: $_"
Write-Warning " Account security configuration failed: $_"
}
+ }
# Category 6: System Security
Write-Host "`n[6/7] Configuring System Security..." -ForegroundColor Cyan
+ if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Apply system security baseline settings")) {
try {
# Disable AutoRun/AutoPlay
$autorunPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer"
@@ -340,11 +354,13 @@ function Set-SecurityBaseline {
$results.Errors += "System security configuration failed: $_"
Write-Warning " System security configuration failed: $_"
}
+ }
# Category 7: BitLocker Encryption
Write-Host "`n[7/7] Configuring BitLocker..." -ForegroundColor Cyan
if ($EnableBitLocker) {
+ if ($PSCmdlet.ShouldProcess("C:", "Enable BitLocker encryption on the system drive")) {
try {
$volume = Get-BitLockerVolume -MountPoint "C:" -ErrorAction Stop
@@ -373,6 +389,7 @@ function Set-SecurityBaseline {
Write-Warning " BitLocker failed: $_"
Write-Warning " Note: TPM may be required, or device may not support BitLocker"
}
+ }
}
else {
Write-Host " BitLocker: Skipped" -ForegroundColor Yellow
diff --git a/Reporting/Get-SecurityMetrics.ps1 b/Reporting/Get-SecurityMetrics.ps1
index 72fc81a..5ce7b85 100644
--- a/Reporting/Get-SecurityMetrics.ps1
+++ b/Reporting/Get-SecurityMetrics.ps1
@@ -1541,13 +1541,13 @@ $penalty += ($script:metrics.Findings.Medium * 5)
$penalty += ($script:metrics.Findings.Low * 2)
$penalty += ((ConvertTo-SafeInt $script:metrics.Core.PendingUpdates) * 2)
-# Add penalties based on conditions
-if (-not $script:metrics.WindowsDefender.ProtectionEnabled) {
+# Add penalties based on conditions (only for modules that were actually collected)
+if ($script:metrics.WindowsDefender.Enabled -and -not $script:metrics.WindowsDefender.ProtectionEnabled) {
$penalty += 15
}
$signatureAge = ConvertTo-SafeInt $script:metrics.WindowsDefender.SignatureAge
-if ($signatureAge -gt 7) {
+if ($script:metrics.WindowsDefender.Enabled -and $signatureAge -gt 7) {
$penalty += 10
}
@@ -1623,7 +1623,7 @@ if ($script:metrics.Findings.Critical -gt 0) {
if ($script:metrics.Vulnerability.EOLSoftware -gt 0) {
$script:metrics.Recommendations.Critical += "Replace or upgrade $($script:metrics.Vulnerability.EOLSoftware) end-of-life software packages"
}
-if (-not $script:metrics.WindowsDefender.ProtectionEnabled) {
+if ($script:metrics.WindowsDefender.Enabled -and -not $script:metrics.WindowsDefender.ProtectionEnabled) {
$script:metrics.Recommendations.Critical += "Enable Windows Defender real-time protection immediately"
}
if ($script:metrics.Detection.APTIndicators -gt 0) {
@@ -1636,10 +1636,10 @@ if ($script:metrics.Findings.High -gt 0) {
if ($script:metrics.Core.PendingUpdates -gt 0) {
$script:metrics.Recommendations.High += "Install $($script:metrics.Core.PendingUpdates) pending security updates"
}
-if ($script:metrics.WindowsDefender.SignatureAge -gt 7) {
+if ($script:metrics.WindowsDefender.Enabled -and $script:metrics.WindowsDefender.SignatureAge -gt 7) {
$script:metrics.Recommendations.High += "Update Windows Defender signatures (currently $($script:metrics.WindowsDefender.SignatureAge) days old)"
}
-if ($script:metrics.ComplianceScore -lt 70) {
+if ($script:metrics.Compliance.Enabled -and $script:metrics.ComplianceScore -lt 70) {
$script:metrics.Recommendations.High += "Improve compliance score (currently $($script:metrics.ComplianceScore)% - target: 80%+)"
}
diff --git a/Reporting/New-ConsolidatedReport.ps1 b/Reporting/New-ConsolidatedReport.ps1
index 6d9885f..e36f8d7 100644
--- a/Reporting/New-ConsolidatedReport.ps1
+++ b/Reporting/New-ConsolidatedReport.ps1
@@ -253,8 +253,11 @@ function New-ConsolidatedReport {
if ($null -eq $Data) { return $null }
# Direct score properties in priority order
+ # NOTE: $null -as [double] yields 0, so null must be filtered BEFORE
+ # the numeric cast or every missing property would score as 0
foreach ($name in @('OverallSecurityScore', 'SecurityScore', 'ComplianceScore', 'Score')) {
$value = Get-SafeProperty $Data $name $null
+ if ($null -eq $value) { continue }
$num = $value -as [double]
if ($null -ne $num) { return [Math]::Round($num, 1) }
}
@@ -264,6 +267,7 @@ function New-ConsolidatedReport {
if ($null -ne $summary) {
foreach ($name in @('OverallSecurityScore', 'SecurityScore', 'ComplianceScore', 'CompliancePercentage', 'Score')) {
$value = Get-SafeProperty $summary $name $null
+ if ($null -eq $value) { continue }
$num = $value -as [double]
if ($null -ne $num) { return [Math]::Round($num, 1) }
}
@@ -413,16 +417,18 @@ function New-ConsolidatedReport {
$totalFindings.Low += $result.Findings.Low
$categoryScores += @{
- Section = $section
- Score = $(if ($null -ne $result.Score) { $result.Score } else { 0 })
- Status = $result.Status
+ Section = $section
+ Score = $(if ($null -ne $result.Score) { $result.Score } else { 0 })
+ HasScore = ($null -ne $result.Score)
+ Status = $result.Status
}
}
$grandTotal = $totalFindings.Critical + $totalFindings.High + $totalFindings.Medium + $totalFindings.Low
- # Overall score: average of known section scores, $null if none collected
- $knownScores = @($categoryScores | Where-Object { $_.Status -ne 'Not collected' } | ForEach-Object { $_.Score } | Where-Object { $_ -gt 0 })
+ # Overall score: average of sections that produced a score, $null if none did
+ # (HasScore distinguishes a genuinely collected 0 from "no score available")
+ $knownScores = @($categoryScores | Where-Object { $_.Status -ne 'Not collected' -and $_.HasScore } | ForEach-Object { $_.Score })
$overallScore = $null
if (@($knownScores).Count -gt 0) {
$overallScore = [Math]::Round(($knownScores | Measure-Object -Average).Average, 1)
diff --git a/Reporting/New-ExecutiveReport.ps1 b/Reporting/New-ExecutiveReport.ps1
index 6bccf94..6f8ee31 100644
--- a/Reporting/New-ExecutiveReport.ps1
+++ b/Reporting/New-ExecutiveReport.ps1
@@ -258,21 +258,30 @@ function New-ExecutiveReport {
$metrics = $null
- # If MetricsFile is actually a PSCustomObject (piped from Get-SecurityMetrics)
- if ($MetricsFile -is [PSCustomObject]) {
- $metrics = $MetricsFile
- Write-Host " Using provided metrics object" -ForegroundColor Green
- }
- # If MetricsFile is a path to JSON file
- elseif ($MetricsFile -and (Test-Path $MetricsFile)) {
- try {
- $metrics = Get-Content $MetricsFile -Raw | ConvertFrom-Json
- Write-Host " Loaded metrics from: $MetricsFile" -ForegroundColor Green
- } catch {
- Write-Error "Failed to load metrics file: $_"
+ # A string is always a file path - this check must come FIRST:
+ # '-is [PSCustomObject]' is unreliable for cmdlet-emitted values
+ # (they can test as PSCustomObject regardless of their real type)
+ if ($MetricsFile -is [string] -and -not [string]::IsNullOrWhiteSpace($MetricsFile)) {
+ if (Test-Path $MetricsFile) {
+ try {
+ $metrics = Get-Content $MetricsFile -Raw | ConvertFrom-Json
+ Write-Host " Loaded metrics from: $MetricsFile" -ForegroundColor Green
+ } catch {
+ Write-Error "Failed to load metrics file: $_"
+ return
+ }
+ } else {
+ # An explicit path was provided but does not exist - never
+ # silently fall back to unrelated history data
+ Write-Error "Metrics file not found: $MetricsFile"
return
}
}
+ # If MetricsFile is an in-memory metrics object (piped from Get-SecurityMetrics)
+ elseif ($MetricsFile) {
+ $metrics = $MetricsFile
+ Write-Host " Using provided metrics object" -ForegroundColor Green
+ }
# Try to load most recent from history
else {
$historyPath = Join-Path $env:TEMP "SecurityMetricsHistory.json"
@@ -1022,16 +1031,26 @@ function New-ExecutiveReport {
$pdfFile = Join-Path $OutputPath "SecurityReport_$timestamp.pdf"
$htmlFile = Join-Path $OutputPath "SecurityReport_$timestamp.html"
- if (Test-Path $htmlFile) {
- # Try to use wkhtmltopdf if available
- $wkhtmltopdf = Get-Command wkhtmltopdf -ErrorAction SilentlyContinue
- if ($wkhtmltopdf) {
- & wkhtmltopdf $htmlFile $pdfFile
+ # PDF-only runs still need the intermediate HTML - generate it if the
+ # HTML format was not requested
+ if (-not (Test-Path $htmlFile)) {
+ Write-Host " Generating intermediate HTML for PDF conversion..." -ForegroundColor Gray
+ $pdfHtmlContent = Generate-HTMLReport -ReportData $reportData
+ $pdfHtmlContent | Out-File $htmlFile -Encoding UTF8 -Force
+ }
+
+ # Try to use wkhtmltopdf if available
+ $wkhtmltopdf = Get-Command wkhtmltopdf -ErrorAction SilentlyContinue
+ if ($wkhtmltopdf) {
+ & wkhtmltopdf "$htmlFile" "$pdfFile"
+ if (Test-Path $pdfFile) {
$outputFiles += $pdfFile
Write-Host " PDF report saved: $pdfFile" -ForegroundColor Green
} else {
- Write-Warning " wkhtmltopdf not found - install from: https://wkhtmltopdf.org/"
+ Write-Warning " wkhtmltopdf did not produce a PDF file"
}
+ } else {
+ Write-Warning " wkhtmltopdf not found - install from: https://wkhtmltopdf.org/"
}
} catch {
Write-Warning " Failed to generate PDF report: $_"
@@ -1147,13 +1166,17 @@ function Generate-HTMLReport {
return 1 # Single item
}
+ # HTML-encode caller-supplied strings before embedding them in markup
+ $safeTitle = [System.Net.WebUtility]::HtmlEncode("$($ReportData.ReportTitle)")
+ $safeCompany = [System.Net.WebUtility]::HtmlEncode("$($ReportData.CompanyName)")
+
$html = @"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>$($ReportData.ReportTitle)</title>
+ <title>$safeTitle</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
@@ -1375,10 +1398,10 @@ function Generate-HTMLReport {
<div class="header">
$(if ($ReportData.LogoDataUri) {
- "<img src='$($ReportData.LogoDataUri)' alt='$($ReportData.CompanyName) Logo' style='max-height: 80px; max-width: 300px; margin-bottom: 15px;' />"
+ "<img src='$($ReportData.LogoDataUri)' alt='$safeCompany Logo' style='max-height: 80px; max-width: 300px; margin-bottom: 15px;' />"
})
- <h1>$($ReportData.ReportTitle)</h1>
- <div class="subtitle">$($ReportData.CompanyName)</div>
+ <h1>$safeTitle</h1>
+ <div class="subtitle">$safeCompany</div>
<div class="subtitle">Generated: $($ReportData.GeneratedDate)</div>
</div>
@@ -1702,7 +1725,7 @@ function Generate-HTMLReport {
})
<div class="footer">
- <p><strong>$($ReportData.CompanyName) - Security Assessment Report</strong></p>
+ <p><strong>$safeCompany - Security Assessment Report</strong></p>
<p>Generated: $($ReportData.GeneratedDate)</p>
<p>WindowsSecurityAudit Module v1.2.0</p>
$(if ($ReportData.Confidential) {
@@ -1730,11 +1753,13 @@ function Generate-ExecutiveSummary {
}
# Simplified 1-page executive summary
+ $safeCompany = [System.Net.WebUtility]::HtmlEncode("$($ReportData.CompanyName)")
+
$html = @"
<!DOCTYPE html>
<html>
<head>
- <title>Executive Summary - $($ReportData.CompanyName)</title>
+ <title>Executive Summary - $safeCompany</title>
<style>
body { font-family: 'Segoe UI', sans-serif; padding: 40px; max-width: 800px; margin: 0 auto; }
h1 { color: #667eea; border-bottom: 3px solid #667eea; padding-bottom: 10px; }
@@ -1748,7 +1773,7 @@ function Generate-ExecutiveSummary {
</head>
<body>
<h1>Executive Summary</h1>
- <p><strong>$($ReportData.CompanyName)</strong> | $($ReportData.GeneratedDate)</p>
+ <p><strong>$safeCompany</strong> | $($ReportData.GeneratedDate)</p>
<div class="summary-box">
<h2>Overall Security Posture</h2>
diff --git a/Reporting/New-SecurityDashboard.ps1 b/Reporting/New-SecurityDashboard.ps1
index f9a6e02..dad2f85 100644
--- a/Reporting/New-SecurityDashboard.ps1
+++ b/Reporting/New-SecurityDashboard.ps1
@@ -504,7 +504,7 @@ function New-SecurityDashboard {
Write-Host " [19/54] Test-CISBenchmark: $($c.ComplianceScore)%" -ForegroundColor Green
} catch {
Write-Warning " Test-CISBenchmark failed: $_"
- $script:dashboardData.Compliance.CIS = @{ ComplianceScore = 0; Status = "Error" }
+ $script:dashboardData.Compliance.CIS = @{ ComplianceScore = $null; Status = "Error" }
}
try {
@@ -517,7 +517,7 @@ function New-SecurityDashboard {
Write-Host " [20/54] Test-NISTCompliance: $($c.ComplianceScore)%" -ForegroundColor Green
} catch {
Write-Warning " Test-NISTCompliance failed: $_"
- $script:dashboardData.Compliance.NIST = @{ ComplianceScore = 0; Status = "Error" }
+ $script:dashboardData.Compliance.NIST = @{ ComplianceScore = $null; Status = "Error" }
}
try {
@@ -530,7 +530,7 @@ function New-SecurityDashboard {
Write-Host " [21/54] Test-PCI-DSS: $($c.ComplianceScore)%" -ForegroundColor Green
} catch {
Write-Warning " Test-PCI-DSS failed: $_"
- $script:dashboardData.Compliance.PCIDSS = @{ ComplianceScore = 0; Status = "Error" }
+ $script:dashboardData.Compliance.PCIDSS = @{ ComplianceScore = $null; Status = "Error" }
}
try {
@@ -953,15 +953,17 @@ function New-SecurityDashboard {
$script:dashboardData.ExecutiveSummary.TotalFindings += $adVulns
}
- # Compliance score with proper null checks
+ # Compliance score with proper null checks (a genuine 0% score is
+ # included in the average; failed collectors carry a $null score and
+ # are excluded)
$scores = @()
- if ($script:dashboardData.Compliance.CIS -and $script:dashboardData.Compliance.CIS.ComplianceScore) {
+ if ($script:dashboardData.Compliance.CIS -and $null -ne $script:dashboardData.Compliance.CIS.ComplianceScore) {
$scores += $script:dashboardData.Compliance.CIS.ComplianceScore
}
- if ($script:dashboardData.Compliance.NIST -and $script:dashboardData.Compliance.NIST.ComplianceScore) {
+ if ($script:dashboardData.Compliance.NIST -and $null -ne $script:dashboardData.Compliance.NIST.ComplianceScore) {
$scores += $script:dashboardData.Compliance.NIST.ComplianceScore
}
- if ($script:dashboardData.Compliance.PCIDSS -and $script:dashboardData.Compliance.PCIDSS.ComplianceScore) {
+ if ($script:dashboardData.Compliance.PCIDSS -and $null -ne $script:dashboardData.Compliance.PCIDSS.ComplianceScore) {
$scores += $script:dashboardData.Compliance.PCIDSS.ComplianceScore
}
diff --git a/Response/ConvertTo-SiemEvent.ps1 b/Response/ConvertTo-SiemEvent.ps1
index 3c04c4c..b482447 100644
--- a/Response/ConvertTo-SiemEvent.ps1
+++ b/Response/ConvertTo-SiemEvent.ps1
@@ -178,7 +178,7 @@ function ConvertTo-SiemEvent {
$extension += ' cs3={0} cs3Label=TechniqueId' -f (ConvertTo-CefExtensionEscaped $techniqueId)
}
- Write-Output ($header + '| ' + $extension)
+ Write-Output ($header + '|' + $extension)
}
}
catch {
diff --git a/Response/Export-SecurityReport.ps1 b/Response/Export-SecurityReport.ps1
index 45fdb25..1f9ffe1 100644
--- a/Response/Export-SecurityReport.ps1
+++ b/Response/Export-SecurityReport.ps1
@@ -363,9 +363,9 @@ if ($highSeverityProcs.Count -gt 0) {
<h2>System Details</h2>
<table>
<tr><th>Component</th><th>Status</th></tr>
- <tr><td>Windows Defender</td><td>$(if ($baseline.WindowsDefender -is [PSCustomObject]) { $baseline.WindowsDefender.RealTimeProtectionEnabled } else { $baseline.WindowsDefender })</td></tr>
+ <tr><td>Windows Defender</td><td>$(if ($null -ne $baseline.WindowsDefender -and $baseline.WindowsDefender.PSObject.Properties['RealTimeProtectionEnabled']) { $baseline.WindowsDefender.RealTimeProtectionEnabled } else { $baseline.WindowsDefender })</td></tr>
<tr><td>Firewall</td><td>$(if ($baseline.Firewall -is [array] -and $baseline.Firewall.Count -gt 0) { $baseline.Firewall[0].Enabled } else { $baseline.Firewall })</td></tr>
- <tr><td>UAC</td><td>$(if ($baseline.UAC -is [PSCustomObject]) { $baseline.UAC.EnableLUA -eq 1 } else { $baseline.UAC })</td></tr>
+ <tr><td>UAC</td><td>$(if ($null -ne $baseline.UAC -and $baseline.UAC.PSObject.Properties['EnableLUA']) { $baseline.UAC.EnableLUA -eq 1 } else { $baseline.UAC })</td></tr>
<tr><td>Persistence Mechanisms</td><td>$($persistence.TotalFindings) total ($($persistence.SuspiciousCount) suspicious)</td></tr>
<tr><td>Network Anomalies</td><td>$($network.TotalAnomalies)</td></tr>
<tr><td>Failed Logons</td><td>$($auth.Statistics.TotalFailedLogons)</td></tr>
diff --git a/ThreatHunting/Find-DataExfiltration.ps1 b/ThreatHunting/Find-DataExfiltration.ps1
index ba1d947..aea252e 100644
--- a/ThreatHunting/Find-DataExfiltration.ps1
+++ b/ThreatHunting/Find-DataExfiltration.ps1
@@ -71,6 +71,10 @@ function Find-DataExfiltration {
Recommendations = @()
}
+ # Track file paths already counted toward TotalDataMB (Compression and Staging
+ # scan overlapping locations such as $env:TEMP)
+ $countedDataPaths = @{}
+
# Known cloud services and upload endpoints
$cloudServices = @(
'dropbox.com',
@@ -98,7 +102,7 @@ function Find-DataExfiltration {
try {
# Check active connections with high data transfer
$connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue |
- Where-Object { $_.RemoteAddress -notmatch '^(127\.|::1|0\.0\.0\.0)' }
+ Where-Object { $null -ne $_ -and $_.RemoteAddress -notmatch '^(127\.|::1|0\.0\.0\.0)' }
foreach ($conn in $connections | Select-Object -First 10) {
$process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue
@@ -262,7 +266,10 @@ function Find-DataExfiltration {
}
$results.Indicators.Compression += $indicator
- $results.Summary.TotalDataMB += $sizeMB
+ if (-not $countedDataPaths.ContainsKey($archive.FullName)) {
+ $countedDataPaths[$archive.FullName] = $true
+ $results.Summary.TotalDataMB += $sizeMB
+ }
if ($sizeMB -gt 500) {
$results.Summary.HighFindings++
@@ -330,7 +337,10 @@ function Find-DataExfiltration {
}
$results.Indicators.Staging += $indicator
- $results.Summary.TotalDataMB += $sizeMB
+ if (-not $countedDataPaths.ContainsKey($file.FullName)) {
+ $countedDataPaths[$file.FullName] = $true
+ $results.Summary.TotalDataMB += $sizeMB
+ }
if ($sizeMB -gt 500) {
$results.Summary.HighFindings++
diff --git a/ThreatHunting/Find-LateralMovement.ps1 b/ThreatHunting/Find-LateralMovement.ps1
index 4b8a73b..b3aee03 100644
--- a/ThreatHunting/Find-LateralMovement.ps1
+++ b/ThreatHunting/Find-LateralMovement.ps1
@@ -156,7 +156,7 @@ function Find-LateralMovement {
if ($remoteEvents) {
$groupedEvents = $remoteEvents | Group-Object -Property {
- $_.Properties[7].Value
+ $_.Properties[8].Value
} | Sort-Object Count -Descending
foreach ($group in $groupedEvents | Select-Object -First 5) {
@@ -166,11 +166,11 @@ function Find-LateralMovement {
Type = 'RemoteExecution'
Process = 'N/A'
ProcessId = 'N/A'
- TargetServer = $event.Properties[7].Value
+ TargetServer = $event.Properties[8].Value
Account = $event.Properties[1].Value
Count = $group.Count
Severity = if ($group.Count -gt 10) { 'High' } else { 'Medium' }
- Description = "Explicit credential logon to $($event.Properties[7].Value) - $($group.Count) times"
+ Description = "Explicit credential logon to $($event.Properties[8].Value) - $($group.Count) times"
Timestamp = $event.TimeCreated.ToString("yyyy-MM-dd HH:mm:ss")
}
@@ -182,7 +182,7 @@ function Find-LateralMovement {
$results.Summary.MediumFindings++
}
- Write-Host " [!] Explicit credential logon: $($event.Properties[7].Value) ($($group.Count) times)" -ForegroundColor Yellow
+ Write-Host " [!] Explicit credential logon: $($event.Properties[8].Value) ($($group.Count) times)" -ForegroundColor Yellow
}
}
else {
diff --git a/ThreatHunting/Find-LivingOffLand.ps1 b/ThreatHunting/Find-LivingOffLand.ps1
index 7d250ca..261f67c 100644
--- a/ThreatHunting/Find-LivingOffLand.ps1
+++ b/ThreatHunting/Find-LivingOffLand.ps1
@@ -276,9 +276,8 @@ function Find-LivingOffLand {
$fileName = $file.Name.ToLower()
foreach ($lolbin in $lolbinsDB.Keys) {
- $binaryName = $lolbin.Replace('.exe', '')
-
- if ($fileName -like "$binaryName-*") {
+ # Prefetch files are named "<BINARY>-<hash>.pf" (e.g. CERTUTIL.EXE-1A2B3C4D.pf)
+ if ($fileName -like "$lolbin-*") {
$detection = [PSCustomObject]@{
DetectionType = 'RecentExecution'
Binary = $lolbin
diff --git a/ThreatHunting/Get-MITREAttackMapping.ps1 b/ThreatHunting/Get-MITREAttackMapping.ps1
index d6660a9..f872fbf 100644
--- a/ThreatHunting/Get-MITREAttackMapping.ps1
+++ b/ThreatHunting/Get-MITREAttackMapping.ps1
@@ -267,16 +267,18 @@ function Get-MITREAttackMapping {
continue
}
- # Skip if no process name defined
- if (-not $technique.ContainsKey('ProcessName')) {
- continue
+ # Techniques without a ProcessName anchor (e.g. T1055, T1027, T1486)
+ # match any non-whitelisted process by command line
+ $nameMatches = $true
+ if ($technique.ContainsKey('ProcessName')) {
+ $nameMatches = ($process.Name -match $technique.ProcessName)
}
$matched = $false
$matchedIndicator = ""
# Check if process name matches
- if ($process.Name -match $technique.ProcessName) {
+ if ($nameMatches) {
# If technique requires command line analysis
if ($technique.RequiresCommandLine) {
if ($process.CommandLine) {
@@ -487,7 +489,7 @@ function Get-MITREAttackMapping {
$results.TacticBreakdown.DefenseEvasion += $detection
}
- Write-Host " [!] Detected: T1070.001 - Event Log Clearing ($($logCleared.Count) events)" -ForegroundColor Red
+ Write-Host " [!] Detected: T1070.001 - Event Log Clearing ($(@($logCleared).Count) events)" -ForegroundColor Red
}
else {
Write-Host " No suspicious event log activity detected" -ForegroundColor Green
diff --git a/ThreatHunting/Get-ThreatIntelligence.ps1 b/ThreatHunting/Get-ThreatIntelligence.ps1
index daf680e..a56fd29 100644
--- a/ThreatHunting/Get-ThreatIntelligence.ps1
+++ b/ThreatHunting/Get-ThreatIntelligence.ps1
@@ -225,6 +225,15 @@ function Get-ThreatIntelligence {
return 1
}
}
+ elseif ($Kind -eq 'ipv6') {
+ $ipv6Value = $Value.ToLower()
+ if ($ipv6Value -notmatch '^[0-9a-f:]+$' -or $ipv6Value -notmatch ':') { return 0 }
+ if (-not $iocDatabase.MaliciousIPs.ContainsKey($ipv6Value)) {
+ $iocDatabase.MaliciousIPs[$ipv6Value] = @{ Severity = $Severity; Description = $Description }
+ $feedEntryCount++
+ return 1
+ }
+ }
elseif ($Kind -eq 'domain') {
$escapedHost = [regex]::Escape($Value)
if (-not $networkIndicatorKeys.ContainsKey($escapedHost)) {
@@ -282,6 +291,10 @@ function Get-ThreatIntelligence {
$matchedAny = $true
$extracted += @{ Kind = 'ip'; Value = $regexMatch.Groups[1].Value; Label = 'ipv4-addr' }
}
+ foreach ($regexMatch in [regex]::Matches($Pattern, "\[ipv6-addr:value\s*=\s*'([^']+)'\]")) {
+ $matchedAny = $true
+ $extracted += @{ Kind = 'ipv6'; Value = $regexMatch.Groups[1].Value; Label = 'ipv6-addr' }
+ }
foreach ($regexMatch in [regex]::Matches($Pattern, "\[domain-name:value\s*=\s*'([^']+)'\]")) {
$matchedAny = $true
$extracted += @{ Kind = 'domain'; Value = $regexMatch.Groups[1].Value; Label = 'domain-name' }
@@ -294,7 +307,7 @@ function Get-ThreatIntelligence {
$matchedAny = $true
$extracted += @{ Kind = 'sha256'; Value = $regexMatch.Groups[1].Value; Label = 'SHA-256' }
}
- foreach ($regexMatch in [regex]::Matches($Pattern, "\[file:hashes\.MD5\s*=\s*'([^']+)'\]")) {
+ foreach ($regexMatch in [regex]::Matches($Pattern, "\[file:hashes\.'?MD5'?\s*=\s*'([^']+)'\]")) {
$matchedAny = $true
$extracted += @{ Kind = 'md5'; Value = $regexMatch.Groups[1].Value; Label = 'MD5' }
}
@@ -347,7 +360,7 @@ function Get-ThreatIntelligence {
if ($cacheExists) {
$cacheItem = Get-Item $cacheFile
- $cacheAgeHours = [math]::Round(((Get-Date) - $cacheItem.LastWriteTime).TotalHours, 1)
+ $cacheAgeHours = [math]::Max(0, [math]::Round(((Get-Date) - $cacheItem.LastWriteTime).TotalHours, 1))
}
$shouldDownload = $UpdateFeeds -and (-not $cacheExists -or $cacheAgeHours -ge $FeedMaxAgeHours)
@@ -369,7 +382,7 @@ function Get-ThreatIntelligence {
$content = Get-Content $cacheFile -ErrorAction Stop
$source = 'download'
$cacheItem = Get-Item $cacheFile
- $cacheAgeHours = [math]::Round(((Get-Date) - $cacheItem.LastWriteTime).TotalHours, 1)
+ $cacheAgeHours = [math]::Max(0, [math]::Round(((Get-Date) - $cacheItem.LastWriteTime).TotalHours, 1))
}
catch {
if ($cacheExists) {
@@ -457,7 +470,7 @@ function Get-ThreatIntelligence {
if ($mispCacheExists) {
$mispCacheItem = Get-Item $mispCacheFile
- $mispCacheAgeHours = [math]::Round(((Get-Date) - $mispCacheItem.LastWriteTime).TotalHours, 1)
+ $mispCacheAgeHours = [math]::Max(0, [math]::Round(((Get-Date) - $mispCacheItem.LastWriteTime).TotalHours, 1))
}
$mispShouldDownload = $UpdateFeeds -and (-not $mispCacheExists -or $mispCacheAgeHours -ge $FeedMaxAgeHours)
@@ -475,7 +488,7 @@ function Get-ThreatIntelligence {
($mispResponse | ConvertTo-Json -Depth 10) | Set-Content -Path $mispCacheFile -ErrorAction Stop
$mispSource = 'download'
$mispCacheItem = Get-Item $mispCacheFile
- $mispCacheAgeHours = [math]::Round(((Get-Date) - $mispCacheItem.LastWriteTime).TotalHours, 1)
+ $mispCacheAgeHours = [math]::Max(0, [math]::Round(((Get-Date) - $mispCacheItem.LastWriteTime).TotalHours, 1))
}
catch {
if ($mispCacheExists) {
@@ -561,7 +574,7 @@ function Get-ThreatIntelligence {
if ($taxiiCacheExists) {
$taxiiCacheItem = Get-Item $taxiiCacheFile
- $taxiiCacheAgeHours = [math]::Round(((Get-Date) - $taxiiCacheItem.LastWriteTime).TotalHours, 1)
+ $taxiiCacheAgeHours = [math]::Max(0, [math]::Round(((Get-Date) - $taxiiCacheItem.LastWriteTime).TotalHours, 1))
}
$taxiiShouldDownload = $UpdateFeeds -and (-not $taxiiCacheExists -or $taxiiCacheAgeHours -ge $FeedMaxAgeHours)
@@ -615,7 +628,7 @@ function Get-ThreatIntelligence {
($taxiiObjects | ConvertTo-Json -Depth 10) | Set-Content -Path $taxiiCacheFile -ErrorAction Stop
$taxiiSource = 'download'
$taxiiCacheItem = Get-Item $taxiiCacheFile
- $taxiiCacheAgeHours = [math]::Round(((Get-Date) - $taxiiCacheItem.LastWriteTime).TotalHours, 1)
+ $taxiiCacheAgeHours = [math]::Max(0, [math]::Round(((Get-Date) - $taxiiCacheItem.LastWriteTime).TotalHours, 1))
}
catch {
if ($taxiiCacheExists) {
diff --git a/Vulnerability/Find-EOLSoftware.ps1 b/Vulnerability/Find-EOLSoftware.ps1
index 1e947cd..dac3781 100644
--- a/Vulnerability/Find-EOLSoftware.ps1
+++ b/Vulnerability/Find-EOLSoftware.ps1
@@ -547,6 +547,7 @@ function Generate-EOLSoftwareHTML {
}, DaysSinceEOL -Descending)) {
$severityClass = "severity-$($software.Severity.ToLower())"
$name = $software.Name -replace '<', '&lt;' -replace '>', '&gt;'
+ $version = "$($software.Version)" -replace '<', '&lt;' -replace '>', '&gt;'
$replacement = $software.Replacement -replace '<', '&lt;' -replace '>', '&gt;'
$notes = $software.Notes -replace '<', '&lt;' -replace '>', '&gt;'
@@ -554,7 +555,7 @@ function Generate-EOLSoftwareHTML {
<tr>
<td><span class="severity-badge $severityClass">$($software.Severity)</span></td>
<td><strong>$name</strong></td>
- <td>$($software.Version)</td>
+ <td>$version</td>
<td>$($software.EOLDate)</td>
<td>$($software.DaysSinceEOL)</td>
<td>$replacement</td>
diff --git a/Vulnerability/Get-SecurityMisconfigurations.ps1 b/Vulnerability/Get-SecurityMisconfigurations.ps1
index cef8b3f..61260b4 100644
--- a/Vulnerability/Get-SecurityMisconfigurations.ps1
+++ b/Vulnerability/Get-SecurityMisconfigurations.ps1
@@ -488,18 +488,24 @@ function Get-SecurityMisconfigurations {
}
}
- # Calculate total findings
- $findings.Summary.TotalFindings = $findings.Misconfigurations.Count
-
# Filter by severity level if specified
if ($SeverityLevel -ne 'All') {
$severityOrder = @('Critical', 'High', 'Medium', 'Low')
$minIndex = $severityOrder.IndexOf($SeverityLevel)
- $findings.Misconfigurations = $findings.Misconfigurations | Where-Object {
+ $findings.Misconfigurations = @($findings.Misconfigurations | Where-Object {
$severityOrder.IndexOf($_.Severity) -le $minIndex
- }
+ })
+
+ # Recompute the per-severity counters so the summary matches the filtered list
+ $findings.Summary.Critical = @($findings.Misconfigurations | Where-Object { $_.Severity -eq 'Critical' }).Count
+ $findings.Summary.High = @($findings.Misconfigurations | Where-Object { $_.Severity -eq 'High' }).Count
+ $findings.Summary.Medium = @($findings.Misconfigurations | Where-Object { $_.Severity -eq 'Medium' }).Count
+ $findings.Summary.Low = @($findings.Misconfigurations | Where-Object { $_.Severity -eq 'Low' }).Count
}
+ # Calculate total findings (after the severity filter so the count matches the list)
+ $findings.Summary.TotalFindings = $findings.Misconfigurations.Count
+
# Generate recommendations
Write-Host "`n[*] Generating recommendations..." -ForegroundColor Cyan
diff --git a/Vulnerability/Resolve-CpeName.ps1 b/Vulnerability/Resolve-CpeName.ps1
index b406e61..1287c37 100644
--- a/Vulnerability/Resolve-CpeName.ps1
+++ b/Vulnerability/Resolve-CpeName.ps1
@@ -162,6 +162,11 @@ function Resolve-CpeName {
$normalized = $normalized -replace '[+].*$', ''
$normalized = $normalized -replace '[-].*$', ''
+ # Keep only characters valid unescaped in a CPE 2.3 formatted-string
+ # component; anything else (e.g. '/', ':', ';') would produce an
+ # invalid CPE that the NVD API rejects
+ $normalized = $normalized -replace '[^0-9A-Za-z._~]', ''
+
# Require at least one digit, otherwise treat as unusable
if ($normalized -notmatch '\d') {
return $null
diff --git a/Vulnerability/Test-CertificateHealth.ps1 b/Vulnerability/Test-CertificateHealth.ps1
index 4ecf60d..e79138a 100644
--- a/Vulnerability/Test-CertificateHealth.ps1
+++ b/Vulnerability/Test-CertificateHealth.ps1
@@ -319,7 +319,14 @@ function Test-CertificateHealth {
}
}
- $results.HealthyCertificates = $results.TotalCertificates - $results.Issues.Count
+ # Count distinct unhealthy certificates: a certificate can raise several
+ # issues (e.g. expired AND weak signature), so Total - Issues.Count can
+ # go negative. 'Duplicate' issues are not a health problem.
+ $unhealthyCertificates = @($results.Issues |
+ Where-Object { $_.Category -ne 'Duplicate' } |
+ ForEach-Object { "$($_.Store)|$($_.Thumbprint)" } |
+ Select-Object -Unique)
+ $results.HealthyCertificates = [Math]::Max(0, $results.TotalCertificates - $unhealthyCertificates.Count)
# 3. GENERATE RECOMMENDATIONS
Write-Host "`n[3/3] Generating recommendations..." -ForegroundColor Cyan
diff --git a/WindowsDefender/Get-DefenderStatus.ps1 b/WindowsDefender/Get-DefenderStatus.ps1
index 25bacb6..c855eda 100644
--- a/WindowsDefender/Get-DefenderStatus.ps1
+++ b/WindowsDefender/Get-DefenderStatus.ps1
@@ -76,10 +76,10 @@ function Get-DefenderStatus {
$status.ScanHistory = [PSCustomObject]@{
QuickScanStartTime = $mpStatus.QuickScanStartTime
QuickScanEndTime = $mpStatus.QuickScanEndTime
- QuickScanAge = if ($mpStatus.QuickScanAge) { $mpStatus.QuickScanAge } else { "Never" }
+ QuickScanAge = if ($null -ne $mpStatus.QuickScanEndTime -and $null -ne $mpStatus.QuickScanAge) { $mpStatus.QuickScanAge } else { "Never" }
FullScanStartTime = $mpStatus.FullScanStartTime
FullScanEndTime = $mpStatus.FullScanEndTime
- FullScanAge = if ($mpStatus.FullScanAge) { $mpStatus.FullScanAge } else { "Never" }
+ FullScanAge = if ($null -ne $mpStatus.FullScanEndTime -and $null -ne $mpStatus.FullScanAge) { $mpStatus.FullScanAge } else { "Never" }
}
# Get Defender preferences/configuration
diff --git a/WindowsDefender/Invoke-DefenderScan.ps1 b/WindowsDefender/Invoke-DefenderScan.ps1
index 0a47224..c653ab0 100644
--- a/WindowsDefender/Invoke-DefenderScan.ps1
+++ b/WindowsDefender/Invoke-DefenderScan.ps1
@@ -21,7 +21,7 @@ function Invoke-DefenderScan {
PSCustomObject with scan results
#>
- [CmdletBinding()]
+ [CmdletBinding(SupportsShouldProcess = $true)]
param(
[Parameter(Mandatory = $true)]
[ValidateSet('Quick', 'Full', 'Custom', 'Offline')]
@@ -81,22 +81,28 @@ function Invoke-DefenderScan {
# Update signatures if requested
if ($UpdateSignatures) {
Write-Host "`nUpdating virus definitions..." -ForegroundColor Cyan
- try {
- Update-MpSignature -ErrorAction Stop
- $mpStatus = Get-MpComputerStatus
- $results.SignatureUpdate.Updated = $true
- $results.SignatureUpdate.Version = $mpStatus.AntivirusSignatureVersion
- Write-Host "Signatures updated to version: $($mpStatus.AntivirusSignatureVersion)" -ForegroundColor Green
- }
- catch {
- $results.SignatureUpdate.Error = $_.Exception.Message
- Write-Warning "Failed to update signatures: $_"
+ if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Update Defender signatures")) {
+ try {
+ Update-MpSignature -ErrorAction Stop
+ $mpStatus = Get-MpComputerStatus
+ $results.SignatureUpdate.Updated = $true
+ $results.SignatureUpdate.Version = $mpStatus.AntivirusSignatureVersion
+ Write-Host "Signatures updated to version: $($mpStatus.AntivirusSignatureVersion)" -ForegroundColor Green
+ }
+ catch {
+ $results.SignatureUpdate.Error = $_.Exception.Message
+ Write-Warning "Failed to update signatures: $_"
+ }
}
}
# Start the scan
Write-Host "`nStarting $ScanType scan..." -ForegroundColor Cyan
+ if (-not $PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Start $ScanType scan")) {
+ $results.Status = 'WhatIf'
+ }
+ else {
switch ($ScanType) {
'Quick' {
Write-Host "This may take a few minutes..." -ForegroundColor Yellow
@@ -104,12 +110,13 @@ function Invoke-DefenderScan {
if ($Priority -eq 'Low') {
Start-MpScan -ScanType QuickScan -AsJob | Out-Null
Write-Host "Quick scan started as background job" -ForegroundColor Green
+ $results.Status = 'Started'
}
else {
Start-MpScan -ScanType QuickScan
Write-Host "Quick scan completed" -ForegroundColor Green
+ $results.Status = 'Completed'
}
- $results.Status = 'Completed'
}
catch {
$results.Status = 'Failed'
@@ -126,6 +133,7 @@ function Invoke-DefenderScan {
Start-MpScan -ScanType FullScan -AsJob | Out-Null
Write-Host "Full scan started as background job" -ForegroundColor Green
Write-Host "Use Get-MpThreat to check results later" -ForegroundColor Yellow
+ $results.Status = 'Started'
}
else {
$job = Start-MpScan -ScanType FullScan -AsJob
@@ -149,6 +157,9 @@ function Invoke-DefenderScan {
Write-Warning "Scan job state: $($job.State)"
$results.Status = $job.State
}
+
+ # Clean up the completed scan job so it does not linger in the session
+ Remove-Job -Job $job -Force -ErrorAction SilentlyContinue
}
}
catch {
@@ -195,6 +206,7 @@ function Invoke-DefenderScan {
}
}
}
+ }
# Wait a moment for scan results to be processed
if ($results.Status -eq 'Completed') {
@@ -276,6 +288,7 @@ function Invoke-DefenderScan {
switch ($results.Status) {
'Completed' { 'Green' }
'Running' { 'Yellow' }
+ 'Started' { 'Yellow' }
'Failed' { 'Red' }
'Cancelled' { 'Yellow' }
'Initiated' { 'Green' }
@@ -324,7 +337,7 @@ function Invoke-DefenderScan {
Write-Host " 3. Review detected threats in Windows Security" -ForegroundColor White
Write-Host " 4. Schedule regular scans during off-peak hours" -ForegroundColor White
- if ($Priority -eq 'Low' -and $results.Status -eq 'Completed') {
+ if ($Priority -eq 'Low' -and $results.Status -eq 'Started') {
Write-Host "`nNote: Background scan may still be running. Check Windows Security for status." -ForegroundColor Yellow
}
diff --git a/WindowsDefender/Update-DefenderConfiguration.ps1 b/WindowsDefender/Update-DefenderConfiguration.ps1
index 5aba7c9..10abe52 100644
--- a/WindowsDefender/Update-DefenderConfiguration.ps1
+++ b/WindowsDefender/Update-DefenderConfiguration.ps1
@@ -311,23 +311,25 @@ function Update-DefenderConfiguration {
Write-Host "`n[ADDITIONAL] Applying recommended settings..." -ForegroundColor Cyan
try {
- # Enable behavior monitoring
- Set-MpPreference -DisableBehaviorMonitoring $false
- Write-Host " + Behavior Monitoring enabled" -ForegroundColor Green
-
- # Enable IOAV protection
- Set-MpPreference -DisableIOAVProtection $false
- Write-Host " + IOAV Protection enabled" -ForegroundColor Green
-
- # Enable script scanning
- Set-MpPreference -DisableScriptScanning $false
- Write-Host " + Script Scanning enabled" -ForegroundColor Green
-
- # Check for signatures before scan
- Set-MpPreference -CheckForSignaturesBeforeRunningScan $true
- Write-Host " + Check signatures before scan enabled" -ForegroundColor Green
-
- $results.Changes += "Additional protections enabled"
+ if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Enable recommended Defender protections (behavior monitoring, IOAV, script scanning, signature check before scan)")) {
+ # Enable behavior monitoring
+ Set-MpPreference -DisableBehaviorMonitoring $false
+ Write-Host " + Behavior Monitoring enabled" -ForegroundColor Green
+
+ # Enable IOAV protection
+ Set-MpPreference -DisableIOAVProtection $false
+ Write-Host " + IOAV Protection enabled" -ForegroundColor Green
+
+ # Enable script scanning
+ Set-MpPreference -DisableScriptScanning $false
+ Write-Host " + Script Scanning enabled" -ForegroundColor Green
+
+ # Check for signatures before scan
+ Set-MpPreference -CheckForSignaturesBeforeRunningScan $true
+ Write-Host " + Check signatures before scan enabled" -ForegroundColor Green
+
+ $results.Changes += "Additional protections enabled"
+ }
}
catch {
Write-Verbose "Some additional settings could not be configured: $_"