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
Adversarial round: fuzzing, collision census, math audit, PS 5.1 realism
Okan YILDIZaee6fc9e1377
diff --git a/ActiveDirectory/Get-ADPrivilegedAccounts.ps1 b/ActiveDirectory/Get-ADPrivilegedAccounts.ps1index 99864c4..0eedc6a 100644--- a/ActiveDirectory/Get-ADPrivilegedAccounts.ps1+++ b/ActiveDirectory/Get-ADPrivilegedAccounts.ps1@@ -1,4 +1,4 @@-function Get-ADPrivilegedAccounts {+function Get-ADPrivilegedAccounts {<#.SYNOPSISIdentifies and analyzes privileged accounts in Active Directorydiff --git a/Compliance/Export-ComplianceEvidence.ps1 b/Compliance/Export-ComplianceEvidence.ps1index f51df08..4223c87 100644--- a/Compliance/Export-ComplianceEvidence.ps1+++ b/Compliance/Export-ComplianceEvidence.ps1@@ -322,6 +322,7 @@ function Export-ComplianceEvidence {$localGroups = @(Get-LocalGroup -ErrorAction SilentlyContinue)foreach ($group in $localGroups) {+ if ($null -eq $group) { continue }try {$members = @(Get-LocalGroupMember -Group $group.Name -ErrorAction SilentlyContinue)$groupData += [PSCustomObject]@{@@ -400,6 +401,9 @@ function Export-ComplianceEvidence {$custodyPath = Join-Path $directories.Metadata "Chain_of_Custody.txt"$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' }+ $osCaptionCustody = $null+ try { $osCaptionCustody = (Get-CimInstance Win32_OperatingSystem -ErrorAction Stop).Caption } catch { $osCaptionCustody = $null }+ if ($null -eq $osCaptionCustody) { $osCaptionCustody = 'Unknown' }$custody = @"CHAIN OF CUSTODY DOCUMENTATION================================@@ -412,7 +416,7 @@ SYSTEM INFORMATION:Computer Name: $($env:COMPUTERNAME)Domain: $($env:USERDOMAIN)IP Address: $ipAddress-Operating System: $((Get-CimInstance Win32_OperatingSystem).Caption)+Operating System: $osCaptionCustodyEVIDENCE COLLECTOR:Name: $AuditorNamediff --git a/Core/Compare-SecurityBaseline.ps1 b/Core/Compare-SecurityBaseline.ps1index 0667e6f..aeebda5 100644--- a/Core/Compare-SecurityBaseline.ps1+++ b/Core/Compare-SecurityBaseline.ps1@@ -132,7 +132,10 @@ function Compare-SecurityBaseline {# Load the saved baselineWrite-Host "Loading baseline from: $BaselinePath" -ForegroundColor Yellowtry {- $baselineJson = Get-Content -Path $BaselinePath -Raw -ErrorAction Stop+ $baselineJson = Get-Content -Path $BaselinePath -Raw -Encoding UTF8 -ErrorAction Stop+ if ([string]::IsNullOrWhiteSpace($baselineJson)) {+ throw "Baseline file '$BaselinePath' is empty or contains only whitespace - not valid JSON"+ }$baseline = $baselineJson | ConvertFrom-Json -ErrorAction Stop}catch {@@ -147,7 +150,10 @@ function Compare-SecurityBaseline {$currentSource = $CurrentPathWrite-Host "Loading current state from: $CurrentPath" -ForegroundColor Yellowtry {- $currentJson = Get-Content -Path $CurrentPath -Raw -ErrorAction Stop+ $currentJson = Get-Content -Path $CurrentPath -Raw -Encoding UTF8 -ErrorAction Stop+ if ([string]::IsNullOrWhiteSpace($currentJson)) {+ throw "Current state file '$CurrentPath' is empty or contains only whitespace - not valid JSON"+ }$current = $currentJson | ConvertFrom-Json -ErrorAction Stop}catch {diff --git a/Core/Get-SystemInfo.ps1 b/Core/Get-SystemInfo.ps1index 14be461..a52f0b0 100644--- a/Core/Get-SystemInfo.ps1+++ b/Core/Get-SystemInfo.ps1@@ -42,46 +42,50 @@ function Get-SystemInfo {process {try {# Computer System Information- $cs = Get-CimInstance -ClassName Win32_ComputerSystem- $info.ComputerSystem = [PSCustomObject]@{- Name = $cs.Name- Domain = $cs.Domain- Manufacturer = $cs.Manufacturer- Model = $cs.Model- SystemType = $cs.SystemType- TotalPhysicalMemory = [math]::Round($cs.TotalPhysicalMemory / 1GB, 2)- NumberOfProcessors = $cs.NumberOfProcessors- NumberOfLogicalProcessors = $cs.NumberOfLogicalProcessors- PrimaryOwnerName = $cs.PrimaryOwnerName- BootupState = $cs.BootupState+ $cs = Get-CimInstance -ClassName Win32_ComputerSystem -ErrorAction SilentlyContinue+ if ($null -ne $cs) {+ $info.ComputerSystem = [PSCustomObject]@{+ Name = $cs.Name+ Domain = $cs.Domain+ Manufacturer = $cs.Manufacturer+ Model = $cs.Model+ SystemType = $cs.SystemType+ TotalPhysicalMemory = [math]::Round($cs.TotalPhysicalMemory / 1GB, 2)+ NumberOfProcessors = $cs.NumberOfProcessors+ NumberOfLogicalProcessors = $cs.NumberOfLogicalProcessors+ PrimaryOwnerName = $cs.PrimaryOwnerName+ BootupState = $cs.BootupState+ }}# Operating System Information- $os = Get-CimInstance -ClassName Win32_OperatingSystem- $info.OperatingSystem = [PSCustomObject]@{- Caption = $os.Caption- Version = $os.Version- BuildNumber = $os.BuildNumber- Architecture = $os.OSArchitecture- InstallDate = $os.InstallDate- LastBootUpTime = $os.LastBootUpTime- LocalDateTime = $os.LocalDateTime- NumberOfUsers = $os.NumberOfUsers- NumberOfProcesses = $os.NumberOfProcesses- ServicePackMajorVersion = $os.ServicePackMajorVersion- RegisteredUser = $os.RegisteredUser- Organization = $os.Organization- WindowsDirectory = $os.WindowsDirectory- SystemDirectory = $os.SystemDirectory+ $os = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction SilentlyContinue+ if ($null -ne $os) {+ $info.OperatingSystem = [PSCustomObject]@{+ Caption = $os.Caption+ Version = $os.Version+ BuildNumber = $os.BuildNumber+ Architecture = $os.OSArchitecture+ InstallDate = $os.InstallDate+ LastBootUpTime = $os.LastBootUpTime+ LocalDateTime = $os.LocalDateTime+ NumberOfUsers = $os.NumberOfUsers+ NumberOfProcesses = $os.NumberOfProcesses+ ServicePackMajorVersion = $os.ServicePackMajorVersion+ RegisteredUser = $os.RegisteredUser+ Organization = $os.Organization+ WindowsDirectory = $os.WindowsDirectory+ SystemDirectory = $os.SystemDirectory+ }}# Hardware Information- $cpu = Get-CimInstance -ClassName Win32_Processor- $disk = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=3"+ $cpu = Get-CimInstance -ClassName Win32_Processor -ErrorAction SilentlyContinue+ $disk = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=3" -ErrorAction SilentlyContinue$info.Hardware = [PSCustomObject]@{- CPU = $cpu | Select-Object Name, MaxClockSpeed, NumberOfCores, NumberOfLogicalProcessors- Disks = $disk | ForEach-Object {+ CPU = @($cpu | Where-Object { $null -ne $_ } | Select-Object Name, MaxClockSpeed, NumberOfCores, NumberOfLogicalProcessors)+ Disks = @($disk | Where-Object { $null -ne $_ } | ForEach-Object {[PSCustomObject]@{DeviceID = $_.DeviceIDVolumeName = $_.VolumeName@@ -90,30 +94,31 @@ function Get-SystemInfo {FreeSpace = [math]::Round($_.FreeSpace / 1GB, 2)PercentFree = if ($_.Size) { [math]::Round(($_.FreeSpace / $_.Size) * 100, 2) } else { $null }}- }+ })}# Network Configuration- $netAdapters = Get-NetAdapter | Where-Object { $_.Status -eq 'Up' }- $netIP = Get-NetIPAddress | Where-Object { $_.AddressFamily -eq 'IPv4' -and $_.PrefixOrigin -ne 'WellKnown' }+ $netAdapters = Get-NetAdapter -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ -and $_.Status -eq 'Up' }+ $netIP = Get-NetIPAddress -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ -and $_.AddressFamily -eq 'IPv4' -and $_.PrefixOrigin -ne 'WellKnown' }$defaultRoute = Get-NetRoute -DestinationPrefix "0.0.0.0/0" -ErrorAction SilentlyContinue | Select-Object -First 1$info.Network = [PSCustomObject]@{- Adapters = $netAdapters | Select-Object Name, InterfaceDescription, MacAddress, LinkSpeed, Status- IPAddresses = $netIP | Select-Object InterfaceAlias, IPAddress, PrefixLength- DNSServers = Get-DnsClientServerAddress | Where-Object { $_.AddressFamily -eq 2 } |- Select-Object InterfaceAlias, ServerAddresses+ Adapters = @($netAdapters | Select-Object Name, InterfaceDescription, MacAddress, LinkSpeed, Status)+ IPAddresses = @($netIP | Select-Object InterfaceAlias, IPAddress, PrefixLength)+ DNSServers = @(Get-DnsClientServerAddress -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ -and $_.AddressFamily -eq 2 } |+ Select-Object InterfaceAlias, ServerAddresses)DefaultGateway = if ($defaultRoute) { $defaultRoute.NextHop } else { $null }}# Security Settings# Security Settings+$localUsers = @(Get-LocalUser -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ })$info.Security = [PSCustomObject]@{- LocalUsers = (@(Get-LocalUser)).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+ LocalUsers = $localUsers.Count+ LocalAdministrators = (@(Get-LocalGroupMember -SID 'S-1-5-32-544' -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ })).Count+ PasswordPolicy = @($localUsers | Where-Object { $_.PSObject.Properties['PasswordRequired'] -and $_.PasswordRequired -eq $false } |+ Select-Object Name, Enabled)+ FirewallProfiles = @(Get-NetFirewallProfile -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ } | Select-Object Name, Enabled)AntivirusProduct = "Not detected"}@@ -150,8 +155,8 @@ if ($IncludeInstalledSoftware) {# Installed Hotfixesif ($IncludeHotfixes) {Write-Verbose "Gathering installed hotfixes..."- $info.Hotfixes = Get-HotFix | Select-Object HotFixID, Description, InstalledOn, InstalledBy |- Sort-Object InstalledOn -Descending+ $info.Hotfixes = @(Get-HotFix -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ } | Select-Object HotFixID, Description, InstalledOn, InstalledBy |+ Sort-Object InstalledOn -Descending)}}diff --git a/Detection/Find-PersistenceMechanisms.ps1 b/Detection/Find-PersistenceMechanisms.ps1index e65824b..686c4b5 100644--- a/Detection/Find-PersistenceMechanisms.ps1+++ b/Detection/Find-PersistenceMechanisms.ps1@@ -129,7 +129,7 @@ function Find-PersistenceMechanisms {# 3. Scheduled TasksWrite-Verbose "Checking Scheduled Tasks..."- $tasks = Get-ScheduledTask | Where-Object { $_.State -ne 'Disabled' }+ $tasks = Get-ScheduledTask -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ -and $_.PSObject.Properties['State'] -and $_.State -ne 'Disabled' }foreach ($task in $tasks) {try {diff --git a/Detection/Find-SuspiciousAuthentication.ps1 b/Detection/Find-SuspiciousAuthentication.ps1index cda4385..d77ecdd 100644--- a/Detection/Find-SuspiciousAuthentication.ps1+++ b/Detection/Find-SuspiciousAuthentication.ps1@@ -90,8 +90,15 @@ function Find-SuspiciousAuthentication {$results.Statistics.TotalFailedLogons = $failedLogons.Countforeach ($event in $failedLogons) {- $xml = [xml]$event.ToXml()- $eventData = $xml.Event.EventData.Data+ if ($null -eq $event) { continue }+ try {+ $xml = [xml]$event.ToXml()+ $eventData = $xml.Event.EventData.Data+ }+ catch {+ Write-Verbose "Skipping unreadable event: $_"+ continue+ }$targetAccount = & $getEventValue $eventData 'TargetUserName'$targetDomain = & $getEventValue $eventData 'TargetDomainName'@@ -165,8 +172,15 @@ function Find-SuspiciousAuthentication {$results.Statistics.TotalLockouts = $lockouts.Countforeach ($event in $lockouts) {- $xml = [xml]$event.ToXml()- $eventData = $xml.Event.EventData.Data+ if ($null -eq $event) { continue }+ try {+ $xml = [xml]$event.ToXml()+ $eventData = $xml.Event.EventData.Data+ }+ catch {+ Write-Verbose "Skipping unreadable event: $_"+ continue+ }$targetAccount = & $getEventValue $eventData 'TargetUserName'$callerComputer = & $getEventValue $eventData 'TargetDomainName'@@ -192,8 +206,15 @@ function Find-SuspiciousAuthentication {# Look for unusual privilege assignmentsforeach ($event in $privEvents) {- $xml = [xml]$event.ToXml()- $eventData = $xml.Event.EventData.Data+ if ($null -eq $event) { continue }+ try {+ $xml = [xml]$event.ToXml()+ $eventData = $xml.Event.EventData.Data+ }+ catch {+ Write-Verbose "Skipping unreadable event: $_"+ continue+ }$subjectAccount = & $getEventValue $eventData 'SubjectUserName'$subjectDomain = & $getEventValue $eventData 'SubjectDomainName'@@ -222,8 +243,15 @@ function Find-SuspiciousAuthentication {$results.Statistics.TotalExplicitCreds = $explicitCreds.Countforeach ($event in $explicitCreds) {- $xml = [xml]$event.ToXml()- $eventData = $xml.Event.EventData.Data+ if ($null -eq $event) { continue }+ try {+ $xml = [xml]$event.ToXml()+ $eventData = $xml.Event.EventData.Data+ }+ catch {+ Write-Verbose "Skipping unreadable event: $_"+ continue+ }$subjectAccount = & $getEventValue $eventData 'SubjectUserName'$targetAccount = & $getEventValue $eventData 'TargetUserName'@@ -252,8 +280,15 @@ function Find-SuspiciousAuthentication {$ntlmNetworkByAccount = @{}foreach ($event in $successfulLogons) {- $xml = [xml]$event.ToXml()- $eventData = $xml.Event.EventData.Data+ if ($null -eq $event) { continue }+ try {+ $xml = [xml]$event.ToXml()+ $eventData = $xml.Event.EventData.Data+ }+ catch {+ Write-Verbose "Skipping unreadable event: $_"+ continue+ }$targetAccount = & $getEventValue $eventData 'TargetUserName'$targetDomain = & $getEventValue $eventData 'TargetDomainName'diff --git a/Detection/Find-SuspiciousProcesses.ps1 b/Detection/Find-SuspiciousProcesses.ps1index ca9d5c6..5d38f44 100644--- a/Detection/Find-SuspiciousProcesses.ps1+++ b/Detection/Find-SuspiciousProcesses.ps1@@ -67,6 +67,7 @@ function Find-SuspiciousProcesses {}foreach ($proc in $processes) {+ if ($null -eq $proc) { continue }$suspicionScore = 0$suspicionReasons = @()@@ -226,7 +227,8 @@ function Find-SuspiciousProcesses {}}catch {- Write-Verbose "Error processing process $($proc.ProcessName): $_"+ $failedProcName = if ($null -ne $proc -and $proc.PSObject.Properties['ProcessName']) { $proc.ProcessName } else { 'unknown' }+ Write-Verbose "Error processing process ${failedProcName}: $_"}}diff --git a/Enterprise/Get-MultiSystemAudit.ps1 b/Enterprise/Get-MultiSystemAudit.ps1index 856aae9..d139d4a 100644--- a/Enterprise/Get-MultiSystemAudit.ps1+++ b/Enterprise/Get-MultiSystemAudit.ps1@@ -62,6 +62,7 @@ function Get-MultiSystemAudit {CriticalFindings = 0HighFindings = 0MediumFindings = 0+ LowFindings = 0SystemsAudited = 0SystemsFailed = 0}@@ -307,6 +308,7 @@ function Get-MultiSystemAudit {'Critical' { $auditResults.Summary.CriticalFindings++ }'High' { $auditResults.Summary.HighFindings++ }'Medium' { $auditResults.Summary.MediumFindings++ }+ 'Low' { $auditResults.Summary.LowFindings++ }}}@@ -384,6 +386,7 @@ function Get-MultiSystemAudit {Write-Host " Critical: $($auditResults.Summary.CriticalFindings)" -ForegroundColor RedWrite-Host " High: $($auditResults.Summary.HighFindings)" -ForegroundColor YellowWrite-Host " Medium: $($auditResults.Summary.MediumFindings)" -ForegroundColor Yellow+ Write-Host " Low: $($auditResults.Summary.LowFindings)" -ForegroundColor Whiteif ($auditResults.ComparativeAnalysis.CommonFindings.Count -gt 0) {Write-Host "`nCommon Issues (affecting 50%+ of systems):" -ForegroundColor Yellow@@ -393,7 +396,7 @@ function Get-MultiSystemAudit {}# Save results- $auditResults | ConvertTo-Json -Depth 10 | Out-File (Join-Path $OutputPath "MultiSystemAudit.json")+ $auditResults | ConvertTo-Json -Depth 10 | Out-File (Join-Path $OutputPath "MultiSystemAudit.json") -Encoding UTF8# Export system summary$auditResults.SystemAudits | Select-Object ComputerName, Status, SecurityScore, SecurityLevel, @{N='FindingsCount';E={$_.Findings.Count}} |diff --git a/Enterprise/Invoke-EnterpriseSecurityScan.ps1 b/Enterprise/Invoke-EnterpriseSecurityScan.ps1index d8cdea5..a0d3236 100644--- a/Enterprise/Invoke-EnterpriseSecurityScan.ps1+++ b/Enterprise/Invoke-EnterpriseSecurityScan.ps1@@ -293,7 +293,8 @@ function Invoke-EnterpriseSecurityScan {# UAC check$uacKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"- $uacEnabled = (Get-ItemProperty -Path $uacKey -ErrorAction SilentlyContinue).EnableLUA+ $uacProps = Get-ItemProperty -Path $uacKey -ErrorAction SilentlyContinue+ $uacEnabled = if ($null -ne $uacProps -and $uacProps.PSObject.Properties['EnableLUA']) { $uacProps.EnableLUA } else { $null }$result.SecurityScore += if ($uacEnabled -eq 1) { 15 } else { 0 }$result.Details.UACEnabled = ($uacEnabled -eq 1)@@ -891,7 +892,7 @@ function Invoke-EnterpriseSecurityScan {# Save resultsif ($PSCmdlet.ShouldProcess($OutputPath, 'Save enterprise scan results (JSON/CSV)')) {- $results | ConvertTo-Json -Depth 10 | Out-File (Join-Path $OutputPath "EnterpriseScan_Results.json")+ $results | ConvertTo-Json -Depth 10 | Out-File (Join-Path $OutputPath "EnterpriseScan_Results.json") -Encoding UTF8# Create CSV summary$results.SystemResults | Select-Object ComputerName, Status, SecurityScore, @{N='FindingsCount';E={$_.Findings.Count}} |diff --git a/Enterprise/Invoke-SecurityAssessment.ps1 b/Enterprise/Invoke-SecurityAssessment.ps1index 9b96242..10ba55b 100644--- a/Enterprise/Invoke-SecurityAssessment.ps1+++ b/Enterprise/Invoke-SecurityAssessment.ps1@@ -70,8 +70,11 @@ function Invoke-SecurityAssessment {Checks = @()}- # Windows Defender- $defender = Get-MpComputerStatus -ErrorAction SilentlyContinue+ # Windows Defender (cmdlet absent on hosts without the Defender feature - guard the lookup)+ $defender = $null+ if (Get-Command Get-MpComputerStatus -ErrorAction SilentlyContinue) {+ $defender = Get-MpComputerStatus -ErrorAction SilentlyContinue+ }if ($defender) {if ($defender.RealTimeProtectionEnabled) {$systemSecurity.CategoryScore += 20@@ -134,8 +137,8 @@ function Invoke-SecurityAssessment {}# Firewall- $firewallProfiles = Get-NetFirewallProfile- $enabledProfiles = @($firewallProfiles | Where-Object { $_.Enabled -eq $true }).Count+ $firewallProfiles = Get-NetFirewallProfile -ErrorAction SilentlyContinue+ $enabledProfiles = @($firewallProfiles | Where-Object { $null -ne $_ -and $_.PSObject.Properties['Enabled'] -and $_.Enabled -eq $true }).Countif ($enabledProfiles -eq 3) {$systemSecurity.CategoryScore += 20$systemSecurity.Checks += [PSCustomObject]@{@@ -148,7 +151,7 @@ function Invoke-SecurityAssessment {$systemSecurity.Checks += [PSCustomObject]@{Check = 'Windows Firewall'Status = 'Fail'- Score = ($enabledProfiles * 7)+ Score = 0Details = "Only $enabledProfiles profiles enabled"}$assessment.Findings += [PSCustomObject]@{@@ -162,7 +165,8 @@ function Invoke-SecurityAssessment {# UAC$uacKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"- $uacEnabled = (Get-ItemProperty -Path $uacKey -ErrorAction SilentlyContinue).EnableLUA+ $uacProps = Get-ItemProperty -Path $uacKey -ErrorAction SilentlyContinue+ $uacEnabled = if ($null -ne $uacProps -and $uacProps.PSObject.Properties['EnableLUA']) { $uacProps.EnableLUA } else { $null }if ($uacEnabled -eq 1) {$systemSecurity.CategoryScore += 15$systemSecurity.Checks += [PSCustomObject]@{@@ -187,8 +191,11 @@ function Invoke-SecurityAssessment {}}- # BitLocker- $bitlocker = Get-BitLockerVolume -MountPoint "C:" -ErrorAction SilentlyContinue+ # BitLocker (module absent on hosts without the BitLocker feature - guard the lookup)+ $bitlocker = $null+ if (Get-Command Get-BitLockerVolume -ErrorAction SilentlyContinue) {+ $bitlocker = Get-BitLockerVolume -MountPoint "C:" -ErrorAction SilentlyContinue+ }if ($bitlocker -and $bitlocker.ProtectionStatus -eq 'On') {$systemSecurity.CategoryScore += 15$systemSecurity.Checks += [PSCustomObject]@{@@ -293,7 +300,7 @@ function Invoke-SecurityAssessment {# Check for dangerous open ports$dangerousPorts = @(23, 135, 139, 445, 1433, 3389, 5985, 5986)$listeningPorts = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue- $exposedPorts = @($listeningPorts | Where-Object { $dangerousPorts -contains $_.LocalPort })+ $exposedPorts = @($listeningPorts | Where-Object { $null -ne $_ -and $_.PSObject.Properties['LocalPort'] -and $dangerousPorts -contains $_.LocalPort })if ($exposedPorts.Count -eq 0) {$networkSecurity.CategoryScore += 30@@ -320,7 +327,10 @@ function Invoke-SecurityAssessment {}# Network shares- $shares = @(Get-SmbShare | Where-Object { $_.Name -notmatch '^(ADMIN\$|C\$|IPC\$)$' })+ $shares = @()+ if (Get-Command Get-SmbShare -ErrorAction SilentlyContinue) {+ $shares = @(Get-SmbShare -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ -and $_.PSObject.Properties['Name'] -and $_.Name -notmatch '^(ADMIN\$|C\$|IPC\$)$' })+ }if ($shares.Count -eq 0) {$networkSecurity.CategoryScore += 20$networkSecurity.Checks += [PSCustomObject]@{@@ -339,9 +349,12 @@ function Invoke-SecurityAssessment {}}- # SMB version- $smbConfig = Get-SmbServerConfiguration- if ($smbConfig.EnableSMB1Protocol -eq $false) {+ # SMB version (cmdlet absent without the SmbShare module - guard the lookup)+ $smbConfig = $null+ if (Get-Command Get-SmbServerConfiguration -ErrorAction SilentlyContinue) {+ $smbConfig = Get-SmbServerConfiguration -ErrorAction SilentlyContinue+ }+ if ($null -ne $smbConfig -and $smbConfig.EnableSMB1Protocol -eq $false) {$networkSecurity.CategoryScore += 25$networkSecurity.Checks += [PSCustomObject]@{Check = 'SMBv1 Protocol'@@ -365,8 +378,11 @@ function Invoke-SecurityAssessment {}}- # WiFi security (if applicable)- $wifiProfiles = netsh wlan show profiles | Select-String "All User Profile"+ # WiFi security (if applicable; netsh absent on non-Windows or Server Core - guard the lookup)+ $wifiProfiles = $null+ if (Get-Command netsh -ErrorAction SilentlyContinue) {+ $wifiProfiles = netsh wlan show profiles | Select-String "All User Profile"+ }if ($wifiProfiles) {$networkSecurity.CategoryScore += 10$networkSecurity.Checks += [PSCustomObject]@{@@ -378,7 +394,8 @@ function Invoke-SecurityAssessment {}# Network Level Authentication for RDP- $rdpNLA = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" -ErrorAction SilentlyContinue).UserAuthentication+ $rdpNLAProps = Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" -ErrorAction SilentlyContinue+ $rdpNLA = if ($null -ne $rdpNLAProps -and $rdpNLAProps.PSObject.Properties['UserAuthentication']) { $rdpNLAProps.UserAuthentication } else { $null }if ($rdpNLA -eq 1) {$networkSecurity.CategoryScore += 15$networkSecurity.Checks += [PSCustomObject]@{@@ -408,7 +425,7 @@ function Invoke-SecurityAssessment {}# Local accounts- $localUsers = @(Get-LocalUser | Where-Object { $_.Enabled -eq $true })+ $localUsers = @(Get-LocalUser -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ -and $_.PSObject.Properties['Enabled'] -and $_.Enabled -eq $true })$accountSecurity.Checks += [PSCustomObject]@{Check = 'Local User Accounts'Status = 'Info'@@ -417,7 +434,7 @@ function Invoke-SecurityAssessment {}# 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+ $adminAccount = @(Get-LocalUser -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ -and $_.PSObject.Properties['SID'] -and $null -ne $_.SID -and $_.SID.Value -match '-500$' }) | Select-Object -First 1if ($adminAccount -and $adminAccount.Enabled -eq $false) {$accountSecurity.CategoryScore += 20$accountSecurity.Checks += [PSCustomObject]@{@@ -443,7 +460,7 @@ function Invoke-SecurityAssessment {}# 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+ $guestAccount = @(Get-LocalUser -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ -and $_.PSObject.Properties['SID'] -and $null -ne $_.SID -and $_.SID.Value -match '-501$' }) | Select-Object -First 1if ($guestAccount -and $guestAccount.Enabled -eq $false) {$accountSecurity.CategoryScore += 15$accountSecurity.Checks += [PSCustomObject]@{@@ -461,8 +478,11 @@ function Invoke-SecurityAssessment {}}- # Password policy- $passwordPolicy = net accounts+ # Password policy (net.exe absent on non-Windows - guard the lookup)+ $passwordPolicy = $null+ if (Get-Command net -ErrorAction SilentlyContinue) {+ $passwordPolicy = net accounts+ }$accountSecurity.CategoryScore += 20$accountSecurity.Checks += [PSCustomObject]@{Check = 'Password Policy'@@ -657,8 +677,11 @@ try {}}- # Backup status- $backupStatus = Get-WmiObject -Namespace root\Microsoft\Windows\Backup -Class MSFT_WBBackupSet -ErrorAction SilentlyContinue+ # Backup status (Get-WmiObject exists only in Windows PowerShell 5.1 - guard the lookup)+ $backupStatus = $null+ if (Get-Command Get-WmiObject -ErrorAction SilentlyContinue) {+ $backupStatus = Get-WmiObject -Namespace root\Microsoft\Windows\Backup -Class MSFT_WBBackupSet -ErrorAction SilentlyContinue+ }if ($backupStatus) {$dataProtection.CategoryScore += 30$dataProtection.Checks += [PSCustomObject]@{@@ -683,8 +706,11 @@ try {}}- # System Restore- $systemRestore = Get-ComputerRestorePoint -ErrorAction SilentlyContinue+ # System Restore (cmdlet absent on Server Core / non-Windows - guard the lookup)+ $systemRestore = $null+ if (Get-Command Get-ComputerRestorePoint -ErrorAction SilentlyContinue) {+ $systemRestore = Get-ComputerRestorePoint -ErrorAction SilentlyContinue+ }if ($systemRestore) {$dataProtection.CategoryScore += 15$dataProtection.Checks += [PSCustomObject]@{@@ -702,8 +728,11 @@ try {}}- # Audit logging- $auditPolicy = auditpol /get /category:* 2>&1+ # Audit logging (auditpol absent on non-Windows - guard the lookup)+ $auditPolicy = $null+ if (Get-Command auditpol -ErrorAction SilentlyContinue) {+ $auditPolicy = auditpol /get /category:* 2>&1+ }if ($auditPolicy -match 'Success') {$dataProtection.CategoryScore += 15$dataProtection.Checks += [PSCustomObject]@{@@ -976,7 +1005,7 @@ foreach ($categoryName in $assessment.Categories.Keys) {}# Save results- $assessment | ConvertTo-Json -Depth 10 | Out-File (Join-Path $OutputPath "SecurityAssessment.json")+ $assessment | ConvertTo-Json -Depth 10 | Out-File (Join-Path $OutputPath "SecurityAssessment.json") -Encoding UTF8# Export findingsif ($assessment.Findings.Count -gt 0) {diff --git a/Forensics/Get-ArtifactCollection.ps1 b/Forensics/Get-ArtifactCollection.ps1index 3287744..e288791 100644--- a/Forensics/Get-ArtifactCollection.ps1+++ b/Forensics/Get-ArtifactCollection.ps1@@ -157,31 +157,31 @@ function Get-ArtifactCollection {try {# Computer info$computerInfo = Get-ComputerInfo -ErrorAction SilentlyContinue- $computerInfo | ConvertTo-Json -Depth 5 | Out-File (Join-Path $paths.SystemInfo "ComputerInfo.json")+ $computerInfo | ConvertTo-Json -Depth 5 | Out-File (Join-Path $paths.SystemInfo "ComputerInfo.json") -Encoding UTF8# OS InfoGet-CimInstance Win32_OperatingSystem |Select-Object Caption, Version, BuildNumber, OSArchitecture, InstallDate, LastBootUpTime |- ConvertTo-Json | Out-File (Join-Path $paths.SystemInfo "OSInfo.json")+ ConvertTo-Json | Out-File (Join-Path $paths.SystemInfo "OSInfo.json") -Encoding UTF8# Hardware InfoGet-CimInstance Win32_ComputerSystem |Select-Object Manufacturer, Model, TotalPhysicalMemory, NumberOfProcessors |- ConvertTo-Json | Out-File (Join-Path $paths.SystemInfo "Hardware.json")+ ConvertTo-Json | Out-File (Join-Path $paths.SystemInfo "Hardware.json") -Encoding UTF8# Disk InfoGet-PSDrive -PSProvider FileSystem |Select-Object Name, Used, Free, @{N='TotalGB';E={[Math]::Round($_.Used/1GB + $_.Free/1GB,2)}} |- ConvertTo-Json | Out-File (Join-Path $paths.SystemInfo "Disks.json")+ ConvertTo-Json | Out-File (Join-Path $paths.SystemInfo "Disks.json") -Encoding UTF8# Installed SoftwareGet-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* -ErrorAction SilentlyContinue |Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |Where-Object { $_.DisplayName } |- ConvertTo-Json | Out-File (Join-Path $paths.SystemInfo "InstalledSoftware.json")+ ConvertTo-Json | Out-File (Join-Path $paths.SystemInfo "InstalledSoftware.json") -Encoding UTF8# Environment Variables- Get-ChildItem Env: | ConvertTo-Json | Out-File (Join-Path $paths.SystemInfo "Environment.json")+ Get-ChildItem Env: | ConvertTo-Json | Out-File (Join-Path $paths.SystemInfo "Environment.json") -Encoding UTF8Write-Host " System information collected" -ForegroundColor Green$results.ArtifactsCollected += "System Information"@@ -344,7 +344,7 @@ function Get-ArtifactCollection {try {# Network adapters- Get-NetAdapter | ConvertTo-Json | Out-File (Join-Path $paths.Network "Adapters.json")+ Get-NetAdapter | ConvertTo-Json | Out-File (Join-Path $paths.Network "Adapters.json") -Encoding UTF8# IP configurationipconfig /all | Out-File (Join-Path $paths.Network "ipconfig.txt")@@ -359,7 +359,7 @@ function Get-ArtifactCollection {ipconfig /displaydns | Out-File (Join-Path $paths.Network "dns_cache.txt")# Active connections- Get-NetTCPConnection | ConvertTo-Json | Out-File (Join-Path $paths.Network "tcp_connections.json")+ Get-NetTCPConnection | ConvertTo-Json | Out-File (Join-Path $paths.Network "tcp_connections.json") -Encoding UTF8# Listening portsnetstat -ano | Out-File (Join-Path $paths.Network "netstat.txt")@@ -383,20 +383,20 @@ function Get-ArtifactCollection {try {# Running processesGet-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")+ ConvertTo-Json | Out-File (Join-Path $paths.Execution "Processes.json") -Encoding UTF8# ServicesGet-Service | Select-Object Name, DisplayName, Status, StartType |- ConvertTo-Json | Out-File (Join-Path $paths.Execution "Services.json")+ ConvertTo-Json | Out-File (Join-Path $paths.Execution "Services.json") -Encoding UTF8# Scheduled tasksGet-ScheduledTask | Select-Object TaskName, TaskPath, State, @{N='LastRunTime';E={($_ | Get-ScheduledTaskInfo).LastRunTime}} |- ConvertTo-Json | Out-File (Join-Path $paths.Execution "ScheduledTasks.json")+ ConvertTo-Json | Out-File (Join-Path $paths.Execution "ScheduledTasks.json") -Encoding UTF8# Startup programsGet-CimInstance Win32_StartupCommand |Select-Object Name, Command, Location, User |- ConvertTo-Json | Out-File (Join-Path $paths.Execution "StartupPrograms.json")+ ConvertTo-Json | Out-File (Join-Path $paths.Execution "StartupPrograms.json") -Encoding UTF8Write-Host " Execution artifacts collected" -ForegroundColor Green$results.ArtifactsCollected += "Execution Artifacts"@@ -413,10 +413,10 @@ function Get-ArtifactCollection {try {# Local usersGet-LocalUser | Select-Object Name, Enabled, LastLogon, PasswordLastSet |- ConvertTo-Json | Out-File (Join-Path $paths.Users "LocalUsers.json")+ ConvertTo-Json | Out-File (Join-Path $paths.Users "LocalUsers.json") -Encoding UTF8# Local groups- Get-LocalGroup | ConvertTo-Json | Out-File (Join-Path $paths.Users "LocalGroups.json")+ Get-LocalGroup | ConvertTo-Json | Out-File (Join-Path $paths.Users "LocalGroups.json") -Encoding UTF8# Logged on usersquser 2>&1 | Out-File (Join-Path $paths.Users "LoggedOnUsers.txt")@@ -424,7 +424,7 @@ function Get-ArtifactCollection {# User profilesGet-ChildItem "C:\Users" -Directory -ErrorAction SilentlyContinue |Select-Object Name, CreationTime, LastWriteTime |- ConvertTo-Json | Out-File (Join-Path $paths.Users "UserProfiles.json")+ ConvertTo-Json | Out-File (Join-Path $paths.Users "UserProfiles.json") -Encoding UTF8Write-Host " User information collected" -ForegroundColor Green$results.ArtifactsCollected += "User Information"@@ -488,7 +488,7 @@ function Get-ArtifactCollection {Files = $fileManifest}- $manifest | ConvertTo-Json -Depth 5 | Out-File (Join-Path $collectionRoot "MANIFEST.json")+ $manifest | ConvertTo-Json -Depth 5 | Out-File (Join-Path $collectionRoot "MANIFEST.json") -Encoding UTF8Write-Host "`nCollection manifest created" -ForegroundColor Green# COMPRESS OUTPUTdiff --git a/Forensics/Get-ExecutionArtifacts.ps1 b/Forensics/Get-ExecutionArtifacts.ps1index 01f1dd5..2570b05 100644--- a/Forensics/Get-ExecutionArtifacts.ps1+++ b/Forensics/Get-ExecutionArtifacts.ps1@@ -1,4 +1,4 @@-function Get-ExecutionArtifacts {+function Get-ExecutionArtifacts {<#.SYNOPSISExtracts program execution artifacts from Windows forensic sourcesdiff --git a/Forensics/Get-USBHistory.ps1 b/Forensics/Get-USBHistory.ps1index 6e79fae..3864b49 100644--- a/Forensics/Get-USBHistory.ps1+++ b/Forensics/Get-USBHistory.ps1@@ -1,4 +1,4 @@-function Get-USBHistory {+function Get-USBHistory {<#.SYNOPSISRetrieves USB device connection history from Windows artifactsdiff --git a/Forensics/New-ForensicTimeline.ps1 b/Forensics/New-ForensicTimeline.ps1index b8b4543..07e173a 100644--- a/Forensics/New-ForensicTimeline.ps1+++ b/Forensics/New-ForensicTimeline.ps1@@ -1,4 +1,4 @@-function New-ForensicTimeline {+function New-ForensicTimeline {<#.SYNOPSISCreates a forensic timeline from multiple artifact sourcesdiff --git a/Hardening/Enable-PowerShellSecurity.ps1 b/Hardening/Enable-PowerShellSecurity.ps1index 037a6d9..75d4515 100644--- a/Hardening/Enable-PowerShellSecurity.ps1+++ b/Hardening/Enable-PowerShellSecurity.ps1@@ -1,4 +1,4 @@-function Enable-PowerShellSecurity {+function Enable-PowerShellSecurity {<#.SYNOPSISHardens PowerShell security settingsdiff --git a/Hardening/Invoke-SecurityRemediation.ps1 b/Hardening/Invoke-SecurityRemediation.ps1index 8eb67f8..c32e666 100644--- a/Hardening/Invoke-SecurityRemediation.ps1+++ b/Hardening/Invoke-SecurityRemediation.ps1@@ -307,7 +307,7 @@ function Invoke-SecurityRemediation {if ($PSCmdlet.ParameterSetName -eq 'File') {Write-Host "`n[LOAD] Reading assessment from: $AssessmentPath" -ForegroundColor Cyantry {- $rawInput = @(Get-Content -Path $AssessmentPath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop)+ $rawInput = @(Get-Content -Path $AssessmentPath -Raw -Encoding UTF8 -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop)}catch {Write-Error "Failed to read or parse assessment file '$AssessmentPath': $_"diff --git a/Hardening/Set-SecurityBaseline.ps1 b/Hardening/Set-SecurityBaseline.ps1index 1874623..a21590d 100644--- a/Hardening/Set-SecurityBaseline.ps1+++ b/Hardening/Set-SecurityBaseline.ps1@@ -214,13 +214,15 @@ function Set-SecurityBaseline {$results.Changes += "SMB encryption enabled"}- # Disable NetBIOS over TCP/IP+ # Disable NetBIOS over TCP/IP (Get-WmiObject exists only in Windows PowerShell 5.1 - guard the lookup)if ($BaselineLevel -eq 'Strict') {- $adapters = Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object { $_.IPEnabled }- foreach ($adapter in $adapters) {- $adapter.SetTcpipNetbios(2) | Out-Null # 2 = Disable NetBIOS+ if (Get-Command Get-WmiObject -ErrorAction SilentlyContinue) {+ $adapters = Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object { $null -ne $_ -and $_.IPEnabled }+ foreach ($adapter in $adapters) {+ $adapter.SetTcpipNetbios(2) | Out-Null # 2 = Disable NetBIOS+ }+ $results.Changes += "NetBIOS over TCP/IP disabled"}- $results.Changes += "NetBIOS over TCP/IP disabled"}# Disable LLMNRdiff --git a/Reporting/Get-SecurityMetrics.ps1 b/Reporting/Get-SecurityMetrics.ps1index 5ce7b85..2ed8332 100644--- a/Reporting/Get-SecurityMetrics.ps1+++ b/Reporting/Get-SecurityMetrics.ps1@@ -261,19 +261,19 @@ function Get-SecurityMetrics {Enabled = $falseFrameworks = @{CIS = @{- Score = 0+ Score = $nullTotalControls = 0PassedControls = 0FailedControls = 0}NIST = @{- Score = 0+ Score = $nullTotalControls = 0CompliantControls = 0NonCompliantControls = 0}PCIDSS = @{- Score = 0+ Score = $nullTotalRequirements = 0InPlace = 0NotInPlace = 0@@ -999,11 +999,14 @@ function Get-SecurityMetrics {}# Calculate overall compliance - NULL SAFE with @() cast+ # A genuinely collected 0% score is included in the average (same+ # convention as New-SecurityDashboard); a failed collector leaves a+ # $null score and is excluded$compScores = @($script:metrics.Compliance.Frameworks.CIS.Score,$script:metrics.Compliance.Frameworks.NIST.Score,$script:metrics.Compliance.Frameworks.PCIDSS.Score- ) | Where-Object { $_ -gt 0 }+ ) | Where-Object { $null -ne $_ }if (@($compScores).Count -gt 0) {$script:metrics.Compliance.OverallScore = [Math]::Round(($compScores | Measure-Object -Average).Average, 1)@@ -1807,15 +1810,22 @@ $script:metrics.Recommendations.Total =# Keep only last N days$cutoffDate = (Get-Date).AddDays(-$HistoryDays)- $history = @($history) | Where-Object {+ $history = @($history | Where-Object {try { [DateTime]$_.Timestamp -gt $cutoffDate } catch { $false }- }+ })# Add current metrics$history += $script:metrics- # Save- $history | ConvertTo-Json -Depth 10 | Out-File $historyPath -Encoding UTF8 -Force+ # Save atomically: write to a unique temp file, then replace the shared+ # history file so concurrent readers never observe a torn write+ $tempHistoryPath = "$historyPath.$(Get-Random).tmp"+ $history | ConvertTo-Json -Depth 10 | Out-File $tempHistoryPath -Encoding UTF8 -Force+ if (Test-Path $historyPath) {+ [System.IO.File]::Replace($tempHistoryPath, $historyPath, [NullString]::Value)+ } else {+ [System.IO.File]::Move($tempHistoryPath, $historyPath)+ }Write-Host " History saved: $historyPath" -ForegroundColor GreenWrite-Host " History entries: $(@($history).Count)" -ForegroundColor Graydiff --git a/Reporting/New-ConsolidatedReport.ps1 b/Reporting/New-ConsolidatedReport.ps1index e36f8d7..514b4d4 100644--- a/Reporting/New-ConsolidatedReport.ps1+++ b/Reporting/New-ConsolidatedReport.ps1@@ -196,6 +196,9 @@ function New-ConsolidatedReport {# Case 1: array of finding objects with a Severity propertyif ($Data -is [array]) {foreach ($item in $Data) {+ # Control-style entries that passed or need manual review are not findings+ $itemStatus = "$(Get-SafeProperty $item 'Status' '')"+ if ($itemStatus -in @('Pass', 'Passed', 'Compliant', 'InPlace', 'Manual', 'NotApplicable')) { continue }$sev = Get-SafeProperty $item 'Severity' ''switch -Regex ("$sev") {'^Critical' { $counts.Critical++ }@@ -209,12 +212,14 @@ function New-ConsolidatedReport {# Case 2: object (or nested Summary) with numeric severity properties# Array-valued properties (e.g. Findings) are inspected recursively+ $arrayFindings = 0$containers = @($Data)$summary = Get-SafeProperty $Data 'Summary' $nullif ($null -ne $summary) { $containers += $summary }foreach ($container in $containers) {if ($null -eq $container) { continue }+ $isSummaryContainer = ($container -eq $summary -and $null -ne $summary)$memberPairs = @()if ($container -is [System.Collections.IDictionary]) {foreach ($name in @($container.Keys)) {@@ -233,8 +238,12 @@ function New-ConsolidatedReport {$counts.High += $nested.High$counts.Medium += $nested.Medium$counts.Low += $nested.Low+ $arrayFindings += $nested.Critical + $nested.High + $nested.Medium + $nested.Lowcontinue}+ # Summary severity counters aggregate the same findings arrays already+ # counted above; using both would double count every finding+ if ($isSummaryContainer -and $arrayFindings -gt 0) { continue }$num = $value -as [int]if ($null -eq $num) { continue }if ($member.Name -match 'Total|Score|Percent') { continue }@@ -317,7 +326,7 @@ function New-ConsolidatedReport {if ($FromJsonPath) {Write-Host "`n[LOADING JSON DATA]" -ForegroundColor Cyantry {- $jsonData = Get-Content $FromJsonPath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop+ $jsonData = Get-Content $FromJsonPath -Raw -Encoding UTF8 -ErrorAction Stop | ConvertFrom-Json -ErrorAction StopWrite-Host " Loaded: $FromJsonPath" -ForegroundColor Green}catch {diff --git a/Reporting/New-ExecutiveReport.ps1 b/Reporting/New-ExecutiveReport.ps1index 6f8ee31..c4d5213 100644--- a/Reporting/New-ExecutiveReport.ps1+++ b/Reporting/New-ExecutiveReport.ps1@@ -264,7 +264,7 @@ function New-ExecutiveReport {if ($MetricsFile -is [string] -and -not [string]::IsNullOrWhiteSpace($MetricsFile)) {if (Test-Path $MetricsFile) {try {- $metrics = Get-Content $MetricsFile -Raw | ConvertFrom-Json+ $metrics = Get-Content $MetricsFile -Raw -Encoding UTF8 | ConvertFrom-JsonWrite-Host " Loaded metrics from: $MetricsFile" -ForegroundColor Green} catch {Write-Error "Failed to load metrics file: $_"diff --git a/Reporting/New-SecurityDashboard.ps1 b/Reporting/New-SecurityDashboard.ps1index 2659f55..3a35b09 100644--- a/Reporting/New-SecurityDashboard.ps1+++ b/Reporting/New-SecurityDashboard.ps1@@ -400,20 +400,22 @@ function New-SecurityDashboard {Write-Warning " Find-NetworkAnomalies failed: $_"}- # Calculate total threats- $persistenceCount = if ($script:dashboardData.Detection.PersistenceMechanisms.PSObject.Properties['SuspiciousCount']) { $script:dashboardData.Detection.PersistenceMechanisms.SuspiciousCount } else { @($script:dashboardData.Detection.PersistenceMechanisms).Count }- $processCount = @($script:dashboardData.Detection.SuspiciousProcesses).Count- $authCount = if ($script:dashboardData.Detection.SuspiciousAuthentications.PSObject.Properties['Statistics'] -and $script:dashboardData.Detection.SuspiciousAuthentications.Statistics) {- $script:dashboardData.Detection.SuspiciousAuthentications.Statistics.TotalFailedLogons +- $script:dashboardData.Detection.SuspiciousAuthentications.Statistics.TotalLockouts +- $script:dashboardData.Detection.SuspiciousAuthentications.Statistics.TotalPrivilegeUse +- $script:dashboardData.Detection.SuspiciousAuthentications.Statistics.TotalExplicitCreds- } else { @($script:dashboardData.Detection.SuspiciousAuthentications).Count }- $lateralCount = if ($script:dashboardData.Detection.LateralMovement.PSObject.Properties['Summary'] -and $script:dashboardData.Detection.LateralMovement.Summary) { $script:dashboardData.Detection.LateralMovement.Summary.TotalIndicators } else { @($script:dashboardData.Detection.LateralMovement).Count }- $aptCount = if ($script:dashboardData.Detection.APTIndicators.PSObject.Properties['Summary'] -and $script:dashboardData.Detection.APTIndicators.Summary) { $script:dashboardData.Detection.APTIndicators.Summary.TotalIndicators } else { @($script:dashboardData.Detection.APTIndicators).Count }- $lolbinsCount = if ($script:dashboardData.Detection.LivingOffLand.PSObject.Properties['Summary'] -and $script:dashboardData.Detection.LivingOffLand.Summary) { $script:dashboardData.Detection.LivingOffLand.Summary.TotalDetections } else { @($script:dashboardData.Detection.LivingOffLand).Count }- $exfilCount = if ($script:dashboardData.Detection.DataExfiltration.PSObject.Properties['Summary'] -and $script:dashboardData.Detection.DataExfiltration.Summary) { $script:dashboardData.Detection.DataExfiltration.Summary.TotalIndicators } else { @($script:dashboardData.Detection.DataExfiltration).Count }- $networkCount = if ($script:dashboardData.Detection.NetworkAnomalies.PSObject.Properties['TotalAnomalies']) { $script:dashboardData.Detection.NetworkAnomalies.TotalAnomalies } else { @($script:dashboardData.Detection.NetworkAnomalies).Count }+ # Calculate total threats (null-first guards: a collector that returns+ # $null without throwing must not crash the .PSObject.Properties checks)+ $detData = $script:dashboardData.Detection+ $persistenceCount = if ($null -ne $detData.PersistenceMechanisms -and $detData.PersistenceMechanisms.PSObject.Properties['SuspiciousCount']) { $detData.PersistenceMechanisms.SuspiciousCount } else { @($detData.PersistenceMechanisms).Count }+ $processCount = @($detData.SuspiciousProcesses).Count+ $authCount = if ($null -ne $detData.SuspiciousAuthentications -and $detData.SuspiciousAuthentications.PSObject.Properties['Statistics'] -and $detData.SuspiciousAuthentications.Statistics) {+ $detData.SuspiciousAuthentications.Statistics.TotalFailedLogons ++ $detData.SuspiciousAuthentications.Statistics.TotalLockouts ++ $detData.SuspiciousAuthentications.Statistics.TotalPrivilegeUse ++ $detData.SuspiciousAuthentications.Statistics.TotalExplicitCreds+ } else { @($detData.SuspiciousAuthentications).Count }+ $lateralCount = if ($null -ne $detData.LateralMovement -and $detData.LateralMovement.PSObject.Properties['Summary'] -and $detData.LateralMovement.Summary) { $detData.LateralMovement.Summary.TotalIndicators } else { @($detData.LateralMovement).Count }+ $aptCount = if ($null -ne $detData.APTIndicators -and $detData.APTIndicators.PSObject.Properties['Summary'] -and $detData.APTIndicators.Summary) { $detData.APTIndicators.Summary.TotalIndicators } else { @($detData.APTIndicators).Count }+ $lolbinsCount = if ($null -ne $detData.LivingOffLand -and $detData.LivingOffLand.PSObject.Properties['Summary'] -and $detData.LivingOffLand.Summary) { $detData.LivingOffLand.Summary.TotalDetections } else { @($detData.LivingOffLand).Count }+ $exfilCount = if ($null -ne $detData.DataExfiltration -and $detData.DataExfiltration.PSObject.Properties['Summary'] -and $detData.DataExfiltration.Summary) { $detData.DataExfiltration.Summary.TotalIndicators } else { @($detData.DataExfiltration).Count }+ $networkCount = if ($null -ne $detData.NetworkAnomalies -and $detData.NetworkAnomalies.PSObject.Properties['TotalAnomalies']) { $detData.NetworkAnomalies.TotalAnomalies } else { @($detData.NetworkAnomalies).Count }$script:dashboardData.Detection.TotalThreats =$persistenceCount + $processCount + $authCount + $lateralCount +@@ -1281,10 +1283,10 @@ function Generate-DashboardHTML {if ($null -ne $Data.Detection.TotalThreats) {[void]$html.AppendLine(" <h2>Threat Detection (Total: $($Data.Detection.TotalThreats))</h2>")[void]$html.AppendLine(" <div class='grid'>")- [void]$html.AppendLine(" <div class='card'><div class='card-header'>Persistence Mechanisms</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(if ($Data.Detection.PersistenceMechanisms.PSObject.Properties['SuspiciousCount']) { $Data.Detection.PersistenceMechanisms.SuspiciousCount } else { @($Data.Detection.PersistenceMechanisms).Count })</span></div></div>")+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>Persistence Mechanisms</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(if ($null -ne $Data.Detection.PersistenceMechanisms -and $Data.Detection.PersistenceMechanisms.PSObject.Properties['SuspiciousCount']) { $Data.Detection.PersistenceMechanisms.SuspiciousCount } else { @($Data.Detection.PersistenceMechanisms).Count })</span></div></div>")[void]$html.AppendLine(" <div class='card'><div class='card-header'>Suspicious Processes</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(@($Data.Detection.SuspiciousProcesses).Count)</span></div></div>")- [void]$html.AppendLine(" <div class='card'><div class='card-header'>Authentication Anomalies</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(if ($Data.Detection.SuspiciousAuthentications.PSObject.Properties['Statistics'] -and $Data.Detection.SuspiciousAuthentications.Statistics) { $Data.Detection.SuspiciousAuthentications.Statistics.TotalFailedLogons + $Data.Detection.SuspiciousAuthentications.Statistics.TotalLockouts + $Data.Detection.SuspiciousAuthentications.Statistics.TotalPrivilegeUse + $Data.Detection.SuspiciousAuthentications.Statistics.TotalExplicitCreds } else { @($Data.Detection.SuspiciousAuthentications).Count })</span></div></div>")- [void]$html.AppendLine(" <div class='card'><div class='card-header'>APT Indicators</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(if ($Data.Detection.APTIndicators.PSObject.Properties['Summary'] -and $Data.Detection.APTIndicators.Summary) { $Data.Detection.APTIndicators.Summary.TotalIndicators } else { @($Data.Detection.APTIndicators).Count })</span></div></div>")+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>Authentication Anomalies</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(if ($null -ne $Data.Detection.SuspiciousAuthentications -and $Data.Detection.SuspiciousAuthentications.PSObject.Properties['Statistics'] -and $Data.Detection.SuspiciousAuthentications.Statistics) { $Data.Detection.SuspiciousAuthentications.Statistics.TotalFailedLogons + $Data.Detection.SuspiciousAuthentications.Statistics.TotalLockouts + $Data.Detection.SuspiciousAuthentications.Statistics.TotalPrivilegeUse + $Data.Detection.SuspiciousAuthentications.Statistics.TotalExplicitCreds } else { @($Data.Detection.SuspiciousAuthentications).Count })</span></div></div>")+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>APT Indicators</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(if ($null -ne $Data.Detection.APTIndicators -and $Data.Detection.APTIndicators.PSObject.Properties['Summary'] -and $Data.Detection.APTIndicators.Summary) { $Data.Detection.APTIndicators.Summary.TotalIndicators } else { @($Data.Detection.APTIndicators).Count })</span></div></div>")[void]$html.AppendLine(" </div>")}diff --git a/Response/Export-SecurityReport.ps1 b/Response/Export-SecurityReport.ps1index dd84cab..74986e4 100644--- a/Response/Export-SecurityReport.ps1+++ b/Response/Export-SecurityReport.ps1@@ -93,16 +93,57 @@ function Export-SecurityReport {process {try {Write-Host "Collecting security data..." -ForegroundColor Yellow-- # Collect all security data- $baseline = Get-SecurityBaseline- $systemInfo = Get-SystemInfo- $persistence = Find-PersistenceMechanisms- $processes = Find-SuspiciousProcesses- $network = Find-NetworkAnomalies -IncludeEstablished- $auth = Find-SuspiciousAuthentication -Hours 168- $eventLog = Get-EventLogAnalysis -Hours 168- $registry = Get-RegistryAnalysis -IncludeAutoRun++ # Null-safe property reader (same shape as New-ConsolidatedReport/Get-SafeProperty)+ function Get-SafeProperty {+ param($Object, $PropertyName, $Default = $null)+ if ($null -eq $Object) { return $Default }+ if ($Object -is [System.Collections.IDictionary]) {+ if ($Object.Contains($PropertyName)) {+ $value = $Object[$PropertyName]+ if ($null -eq $value) { return $Default }+ return $value+ }+ return $Default+ }+ if ($Object.PSObject.Properties[$PropertyName]) {+ $value = $Object.$PropertyName+ if ($null -eq $value) { return $Default }+ return $value+ }+ return $Default+ }++ # Collect all security data - each collector is isolated so a single+ # failing collector degrades its section instead of aborting the report+ $baseline = $null+ try { $baseline = Get-SecurityBaseline -ErrorAction Stop } catch { Write-Warning "Get-SecurityBaseline failed: $_" }+ $systemInfo = $null+ try { $systemInfo = Get-SystemInfo -ErrorAction Stop } catch { Write-Warning "Get-SystemInfo failed: $_" }+ $persistence = $null+ try { $persistence = Find-PersistenceMechanisms -ErrorAction Stop } catch { Write-Warning "Find-PersistenceMechanisms failed: $_" }+ $processes = $null+ try { $processes = Find-SuspiciousProcesses -ErrorAction Stop } catch { Write-Warning "Find-SuspiciousProcesses failed: $_" }+ $network = $null+ try { $network = Find-NetworkAnomalies -IncludeEstablished -ErrorAction Stop } catch { Write-Warning "Find-NetworkAnomalies failed: $_" }+ $auth = $null+ try { $auth = Find-SuspiciousAuthentication -Hours 168 -ErrorAction Stop } catch { Write-Warning "Find-SuspiciousAuthentication failed: $_" }+ $eventLog = $null+ try { $eventLog = Get-EventLogAnalysis -Hours 168 -ErrorAction Stop } catch { Write-Warning "Get-EventLogAnalysis failed: $_" }+ $registry = $null+ try { $registry = Get-RegistryAnalysis -IncludeAutoRun -ErrorAction Stop } catch { Write-Warning "Get-RegistryAnalysis failed: $_" }++ # Safe scalar views of collector output (strict-mode safe for null/malformed results)+ $baselineScore = Get-SafeProperty $baseline 'SecurityScore' $null+ $baselineDefender = Get-SafeProperty $baseline 'WindowsDefender' $null+ $baselineFirewall = Get-SafeProperty $baseline 'Firewall' $null+ $baselineUac = Get-SafeProperty $baseline 'UAC' $null+ $persistenceSuspicious = Get-SafeProperty $persistence 'SuspiciousCount' 0+ $persistenceTotal = Get-SafeProperty $persistence 'TotalFindings' 0+ $authStats = Get-SafeProperty $auth 'Statistics' $null+ $authLockouts = Get-SafeProperty $authStats 'TotalLockouts' 0+ $authFailedLogons = Get-SafeProperty $authStats 'TotalFailedLogons' 0+ $networkAnomalies = Get-SafeProperty $network 'TotalAnomalies' 0# Build report data structure$reportData = [PSCustomObject]@{@@ -110,7 +151,7 @@ function Export-SecurityReport {GeneratedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"ComputerName = $env:COMPUTERNAMEGeneratedBy = $env:USERNAME- SecurityScore = $baseline.SecurityScore+ SecurityScore = $baselineScoreSummary = @{CriticalFindings = 0HighFindings = 0@@ -134,24 +175,25 @@ function Export-SecurityReport {# Analyze findings and create recommendationsWrite-Host "Analyzing findings..." -ForegroundColor Yellow- # Critical findings- if ($baseline.SecurityScore -lt 50) {+ # Critical findings (only when a baseline score was actually collected -+ # a failed collector must not fabricate a "critically low" finding)+ if ($null -ne $baselineScore -and $baselineScore -lt 50) {$reportData.Summary.CriticalFindings++$reportData.Findings += [PSCustomObject]@{Severity = 'Critical'Category = 'Security Baseline'- Finding = "Security score is critically low: $($baseline.SecurityScore)/100"+ Finding = "Security score is critically low: $baselineScore/100"Impact = 'System is highly vulnerable to attacks'Recommendation = 'Immediate remediation required'}}- if ($persistence.SuspiciousCount -gt 5) {+ if ($persistenceSuspicious -gt 5) {$reportData.Summary.HighFindings++$reportData.Findings += [PSCustomObject]@{Severity = 'High'Category = 'Persistence'- Finding = "$($persistence.SuspiciousCount) suspicious persistence mechanisms detected"+ Finding = "$persistenceSuspicious suspicious persistence mechanisms detected"Impact = 'Potential malware or unauthorized software present'Recommendation = 'Review and remove unauthorized persistence mechanisms'}@@ -159,7 +201,7 @@ function Export-SecurityReport {if (@($processes).Count -gt 0) {$processArray = @($processes)-$highSeverityProcs = @($processArray | Where-Object { $_.SuspicionScore -ge 70 })+$highSeverityProcs = @($processArray | Where-Object { $null -ne $_ -and $_.PSObject.Properties['SuspicionScore'] -and $_.SuspicionScore -ge 70 })if ($highSeverityProcs.Count -gt 0) {$reportData.Summary.HighFindings++$reportData.Findings += [PSCustomObject]@{@@ -172,23 +214,23 @@ if ($highSeverityProcs.Count -gt 0) {}}- if ($auth.Statistics.TotalLockouts -gt 0) {+ if ($authLockouts -gt 0) {$reportData.Summary.MediumFindings++$reportData.Findings += [PSCustomObject]@{Severity = 'Medium'Category = 'Authentication'- Finding = "$($auth.Statistics.TotalLockouts) account lockouts detected"+ Finding = "$authLockouts account lockouts detected"Impact = 'Possible brute force attempts'Recommendation = 'Review failed authentication events and implement MFA'}}- if ($network.TotalAnomalies -gt 10) {+ if ($networkAnomalies -gt 10) {$reportData.Summary.MediumFindings++$reportData.Findings += [PSCustomObject]@{Severity = 'Medium'Category = 'Network'- Finding = "$($network.TotalAnomalies) network anomalies detected"+ Finding = "$networkAnomalies network anomalies detected"Impact = 'Unusual network activity may indicate compromise'Recommendation = 'Review network connections and implement network monitoring'}@@ -197,7 +239,7 @@ if ($highSeverityProcs.Count -gt 0) {# Generate recommendations based on report typeif ($ReportType -eq 'Executive') {$reportData.Recommendations = @(- "Overall Security Score: $($baseline.SecurityScore)/100 - $(if ($baseline.SecurityScore -ge 80) { 'Good' } elseif ($baseline.SecurityScore -ge 60) { 'Fair' } else { 'Poor' })",+ "$(if ($null -ne $baselineScore) { "Overall Security Score: $baselineScore/100 - $(if ($baselineScore -ge 80) { 'Good' } elseif ($baselineScore -ge 60) { 'Fair' } else { 'Poor' })" } else { 'Overall Security Score: N/A - baseline collection failed' })","Critical Issues: $($reportData.Summary.CriticalFindings)","High Priority Issues: $($reportData.Summary.HighFindings)","Immediate action required on critical and high priority items",@@ -397,12 +439,12 @@ 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 ($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 ($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>+ <tr><td>Windows Defender</td><td>$(if ($null -ne $baselineDefender -and $baselineDefender.PSObject.Properties['RealTimeProtectionEnabled']) { $baselineDefender.RealTimeProtectionEnabled } else { $baselineDefender })</td></tr>+ <tr><td>Firewall</td><td>$(if ($baselineFirewall -is [array] -and $baselineFirewall.Count -gt 0) { $baselineFirewall[0].Enabled } else { $baselineFirewall })</td></tr>+ <tr><td>UAC</td><td>$(if ($null -ne $baselineUac -and $baselineUac.PSObject.Properties['EnableLUA']) { $baselineUac.EnableLUA -eq 1 } else { $baselineUac })</td></tr>+ <tr><td>Persistence Mechanisms</td><td>$persistenceTotal total ($persistenceSuspicious suspicious)</td></tr>+ <tr><td>Network Anomalies</td><td>$networkAnomalies</td></tr>+ <tr><td>Failed Logons</td><td>$authFailedLogons</td></tr></table></div>diff --git a/Response/Invoke-ForensicCollection.ps1 b/Response/Invoke-ForensicCollection.ps1index 0087dc2..661a663 100644--- a/Response/Invoke-ForensicCollection.ps1+++ b/Response/Invoke-ForensicCollection.ps1@@ -101,10 +101,10 @@ function Invoke-ForensicCollection {# Basic system info$sysInfo = Get-SystemInfo -IncludeInstalledSoftware -IncludeHotfixes- $sysInfo | ConvertTo-Json -Depth 5 | Out-File (Join-Path $sysInfoPath "SystemInfo.json")+ $sysInfo | ConvertTo-Json -Depth 5 | Out-File (Join-Path $sysInfoPath "SystemInfo.json") -Encoding UTF8# Computer information- Get-ComputerInfo | ConvertTo-Json -Depth 5 | Out-File (Join-Path $sysInfoPath "ComputerInfo.json")+ Get-ComputerInfo | ConvertTo-Json -Depth 5 | Out-File (Join-Path $sysInfoPath "ComputerInfo.json") -Encoding UTF8# Environment variablesGet-ChildItem Env: | Export-Csv (Join-Path $sysInfoPath "EnvironmentVariables.csv") -NoTypeInformation@@ -329,15 +329,15 @@ function Invoke-ForensicCollection {# Persistence mechanisms$persistence = Find-PersistenceMechanisms- $persistence | ConvertTo-Json -Depth 5 | Out-File (Join-Path $secPath "Persistence.json")+ $persistence | ConvertTo-Json -Depth 5 | Out-File (Join-Path $secPath "Persistence.json") -Encoding UTF8# Network anomalies$network = Find-NetworkAnomalies -IncludeEstablished- $network | ConvertTo-Json -Depth 5 | Out-File (Join-Path $secPath "NetworkAnomalies.json")+ $network | ConvertTo-Json -Depth 5 | Out-File (Join-Path $secPath "NetworkAnomalies.json") -Encoding UTF8# Authentication analysis$auth = Find-SuspiciousAuthentication -Hours 168- $auth | ConvertTo-Json -Depth 5 | Out-File (Join-Path $secPath "Authentication.json")+ $auth | ConvertTo-Json -Depth 5 | Out-File (Join-Path $secPath "Authentication.json") -Encoding UTF8$results.ArtifactsCollected += "Security Analysis"Write-CollectionLog "Completed security analysis"diff --git a/Response/Invoke-IncidentResponse.ps1 b/Response/Invoke-IncidentResponse.ps1index bd966ef..a7dc582 100644--- a/Response/Invoke-IncidentResponse.ps1+++ b/Response/Invoke-IncidentResponse.ps1@@ -214,7 +214,7 @@ function Invoke-IncidentResponse {# Collect system informationtry {$sysInfo = Get-SystemInfo -IncludeInstalledSoftware -IncludeHotfixes- $sysInfo | ConvertTo-Json -Depth 5 | Out-File (Join-Path $OutputPath "SystemInfo.json")+ $sysInfo | ConvertTo-Json -Depth 5 | Out-File (Join-Path $OutputPath "SystemInfo.json") -Encoding UTF8$results.EvidenceCollected += "System information"Write-IRLog "Collected system information" 'SUCCESS'}@@ -247,7 +247,7 @@ function Invoke-IncidentResponse {# Collect event logstry {$eventAnalysis = Get-EventLogAnalysis -Hours 48- $eventAnalysis | ConvertTo-Json -Depth 5 | Out-File (Join-Path $OutputPath "EventLogAnalysis.json")+ $eventAnalysis | ConvertTo-Json -Depth 5 | Out-File (Join-Path $OutputPath "EventLogAnalysis.json") -Encoding UTF8$results.EvidenceCollected += "Event log analysis"Write-IRLog "Collected event logs" 'SUCCESS'}@@ -258,7 +258,7 @@ function Invoke-IncidentResponse {# Collect registry analysistry {$regAnalysis = Get-RegistryAnalysis -IncludeAutoRun- $regAnalysis | ConvertTo-Json -Depth 5 | Out-File (Join-Path $OutputPath "RegistryAnalysis.json")+ $regAnalysis | ConvertTo-Json -Depth 5 | Out-File (Join-Path $OutputPath "RegistryAnalysis.json") -Encoding UTF8$results.EvidenceCollected += "Registry analysis"Write-IRLog "Collected registry analysis" 'SUCCESS'}@@ -278,7 +278,7 @@ function Invoke-IncidentResponse {Write-IRLog "Generating final report" 'INFO'$results.Status = 'Completed'- $results | ConvertTo-Json -Depth 5 | Out-File (Join-Path $OutputPath "IncidentResponse_Report.json")+ $results | ConvertTo-Json -Depth 5 | Out-File (Join-Path $OutputPath "IncidentResponse_Report.json") -Encoding UTF8# Create summary report$summary = @"diff --git a/ThreatHunting/Export-AttackNavigatorLayer.ps1 b/ThreatHunting/Export-AttackNavigatorLayer.ps1index 8d11301..92f91db 100644--- a/ThreatHunting/Export-AttackNavigatorLayer.ps1+++ b/ThreatHunting/Export-AttackNavigatorLayer.ps1@@ -240,7 +240,7 @@ function Export-AttackNavigatorLayer {throw "Input file not found: $InputPath"}try {- $rawJson = Get-Content -LiteralPath $InputPath -Raw -ErrorAction Stop+ $rawJson = Get-Content -LiteralPath $InputPath -Raw -Encoding UTF8 -ErrorAction Stop$loadedFindings = $rawJson | ConvertFrom-Json -ErrorAction Stopforeach ($loadedItem in @($loadedFindings)) {foreach ($record in @(Get-TechniqueRecord -Item $loadedItem)) {diff --git a/ThreatHunting/Find-LateralMovement.ps1 b/ThreatHunting/Find-LateralMovement.ps1index b3aee03..93b753b 100644--- a/ThreatHunting/Find-LateralMovement.ps1+++ b/ThreatHunting/Find-LateralMovement.ps1@@ -66,6 +66,7 @@ function Find-LateralMovement {CriticalFindings = 0HighFindings = 0MediumFindings = 0+ LowFindings = 0}Recommendations = @()}@@ -331,6 +332,7 @@ function Find-LateralMovement {Write-Host " [!] ADMIN SHARE: $($parts[1]) by $($parts[0]) ($($group.Count) times)" -ForegroundColor Red}else {+ $results.Summary.LowFindings++Write-Host " [!] Share: $($parts[1]) by $($parts[0]) ($($group.Count) times)" -ForegroundColor Yellow}}@@ -396,6 +398,7 @@ function Find-LateralMovement {Write-Host " Critical: $($results.Summary.CriticalFindings)" -ForegroundColor RedWrite-Host " High: $($results.Summary.HighFindings)" -ForegroundColor YellowWrite-Host " Medium: $($results.Summary.MediumFindings)" -ForegroundColor Yellow+ Write-Host " Low: $($results.Summary.LowFindings)" -ForegroundColor Whiteif ($results.Summary.TotalIndicators -gt 0) {Write-Host "`nIndicator Breakdown:" -ForegroundColor Cyandiff --git a/ThreatHunting/Get-ThreatIntelligence.ps1 b/ThreatHunting/Get-ThreatIntelligence.ps1index 2854d1a..7c64d79 100644--- a/ThreatHunting/Get-ThreatIntelligence.ps1+++ b/ThreatHunting/Get-ThreatIntelligence.ps1@@ -524,7 +524,7 @@ function Get-ThreatIntelligence {} | ConvertTo-Json$mispResponse = Invoke-RestMethod -Method Post -Uri "$($MISPUrl.TrimEnd('/'))/attributes/restSearch" -Headers @{ 'Authorization' = $MISPApiKey; 'Accept' = 'application/json' } -Body $mispBody -ContentType 'application/json' -TimeoutSec 60 -ErrorAction Stopif ($null -eq $mispResponse) { throw "MISP returned an empty response" }- ($mispResponse | ConvertTo-Json -Depth 10) | Set-Content -Path $mispCacheFile -ErrorAction Stop+ ($mispResponse | ConvertTo-Json -Depth 10) | Set-Content -Path $mispCacheFile -Encoding UTF8 -ErrorAction Stop$mispSource = 'download'$mispCacheItem = Get-Item $mispCacheFile$mispCacheAgeHours = [math]::Max(0, [math]::Round(((Get-Date) - $mispCacheItem.LastWriteTime).TotalHours, 1))@@ -696,7 +696,7 @@ function Get-ThreatIntelligence {if ($taxiiMorePages -and $taxiiPagesFetched -ge $taxiiMaxPages) {Write-Warning "TAXII page cap ($taxiiMaxPages) reached - using indicators from the first $taxiiPagesFetched pages"}- ($taxiiObjects | ConvertTo-Json -Depth 10) | Set-Content -Path $taxiiCacheFile -ErrorAction Stop+ ($taxiiObjects | ConvertTo-Json -Depth 10) | Set-Content -Path $taxiiCacheFile -Encoding UTF8 -ErrorAction Stop$taxiiSource = 'download'$taxiiCacheItem = Get-Item $taxiiCacheFile$taxiiCacheAgeHours = [math]::Max(0, [math]::Round(((Get-Date) - $taxiiCacheItem.LastWriteTime).TotalHours, 1))@@ -772,7 +772,7 @@ function Get-ThreatIntelligence {if (Test-Path $StixFilePath) {try {- $stixBundle = Get-Content $StixFilePath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop+ $stixBundle = Get-Content $StixFilePath -Raw -Encoding UTF8 -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop$stixObjects = @()if ($null -ne $stixBundle -and $stixBundle.PSObject.Properties['objects'] -and $null -ne $stixBundle.objects) {$stixObjects = @($stixBundle.objects)@@ -820,7 +820,7 @@ function Get-ThreatIntelligence {if ($IOCFile -and (Test-Path $IOCFile)) {Write-Host "Loading custom IOCs from: $IOCFile" -ForegroundColor Yellowtry {- $customIOCs = Get-Content $IOCFile -Raw | ConvertFrom-Json+ $customIOCs = Get-Content $IOCFile -Raw -Encoding UTF8 | ConvertFrom-Jsonforeach ($section in 'MaliciousProcesses', 'MaliciousIPs', 'MaliciousHashes') {if ($customIOCs.PSObject.Properties[$section]) {foreach ($entry in $customIOCs.$section.PSObject.Properties) {diff --git a/Vulnerability/Get-ExposedServices.ps1 b/Vulnerability/Get-ExposedServices.ps1index 42d9de8..0e73f82 100644--- a/Vulnerability/Get-ExposedServices.ps1+++ b/Vulnerability/Get-ExposedServices.ps1@@ -123,6 +123,16 @@ function Get-ExposedServices {Write-Warning "Could not retrieve network adapters"}+ # Ensure TLS 1.2 on Windows PowerShell 5.1 (idempotent, only if the type exists)+ try {+ if ($null -ne ([Net.SecurityProtocolType] -as [type])) {+ [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12+ }+ }+ catch {+ Write-Verbose "Could not enforce TLS 1.2: $_"+ }+# Try to get public IPtry {Write-Host " Detecting public IP..." -ForegroundColor Graydiff --git a/Vulnerability/Get-SecurityMisconfigurations.ps1 b/Vulnerability/Get-SecurityMisconfigurations.ps1index 61260b4..95bccd3 100644--- a/Vulnerability/Get-SecurityMisconfigurations.ps1+++ b/Vulnerability/Get-SecurityMisconfigurations.ps1@@ -45,10 +45,13 @@ function Get-SecurityMisconfigurations {Write-Host "Scan Category: $Category" -ForegroundColor YellowWrite-Host "Severity Filter: $SeverityLevel" -ForegroundColor Yellow+ $osCaption = $null+ try { $osCaption = (Get-CimInstance Win32_OperatingSystem -ErrorAction Stop).Caption } catch { $osCaption = $null }+$findings = [PSCustomObject]@{ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"ComputerName = $env:COMPUTERNAME- OSVersion = (Get-CimInstance Win32_OperatingSystem).Caption+ OSVersion = $osCaptionMisconfigurations = @()Summary = @{TotalFindings = 0@@ -70,12 +73,14 @@ function Get-SecurityMisconfigurations {# Password Policytry {$secpol = @{}- secedit /export /cfg "$env:TEMP\secpol.cfg" /quiet | Out-Null- Get-Content "$env:TEMP\secpol.cfg" | Where-Object { $_ -match '=' } | ForEach-Object {+ # Randomized temp name so concurrent runs cannot clobber each other (matches Test-CISBenchmark)+ $secpolPath = "$env:TEMP\secpol_$(Get-Random).cfg"+ secedit /export /cfg $secpolPath /quiet | Out-Null+ Get-Content $secpolPath | Where-Object { $_ -match '=' } | ForEach-Object {$parts = $_ -split '=', 2$secpol[$parts[0].Trim()] = $parts[1].Trim()}- Remove-Item "$env:TEMP\secpol.cfg" -Force -ErrorAction SilentlyContinue+ Remove-Item $secpolPath -Force -ErrorAction SilentlyContinue# Check minimum password length$minPwdLength = [int]$secpol['MinimumPasswordLength']diff --git a/Vulnerability/Get-VulnerabilityAssessment.ps1 b/Vulnerability/Get-VulnerabilityAssessment.ps1index 2bcf2ba..16ccddd 100644--- a/Vulnerability/Get-VulnerabilityAssessment.ps1+++ b/Vulnerability/Get-VulnerabilityAssessment.ps1@@ -275,7 +275,7 @@ function Get-VulnerabilityAssessment {if ($ScanDepth -in @('Standard', 'Deep')) {Write-Host "`n[3/5] Scanning services..." -ForegroundColor Cyan- $services = Get-Service | Where-Object { $_.Status -eq 'Running' } |+ $services = Get-Service -ErrorAction SilentlyContinue | Where-Object { $null -ne $_ -and $_.PSObject.Properties['Status'] -and $_.Status -eq 'Running' } |Select-Object Name, DisplayName, StartType# Check for potentially vulnerable servicesdiff --git a/Vulnerability/Resolve-CpeName.ps1 b/Vulnerability/Resolve-CpeName.ps1index d5b313b..8ad2870 100644--- a/Vulnerability/Resolve-CpeName.ps1+++ b/Vulnerability/Resolve-CpeName.ps1@@ -1,4 +1,4 @@-function Resolve-CpeName {+function Resolve-CpeName {<#.SYNOPSISResolves an installed product to a CPE 2.3 name for version-exact CVE matchingdiff --git a/Vulnerability/Test-PatchCompliance.ps1 b/Vulnerability/Test-PatchCompliance.ps1index 762c1fb..735a1a1 100644--- a/Vulnerability/Test-PatchCompliance.ps1+++ b/Vulnerability/Test-PatchCompliance.ps1@@ -42,11 +42,14 @@ function Test-PatchCompliance {Write-Host "Include Optional Updates: $(if($IncludeOptional){'Yes'}else{'No'})" -ForegroundColor YellowWrite-Host "Critical Age Threshold: $DaysOld days" -ForegroundColor Yellow+ $osInfo = $null+ try { $osInfo = Get-CimInstance Win32_OperatingSystem -ErrorAction Stop } catch { $osInfo = $null }+$compliance = [PSCustomObject]@{ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"ComputerName = $env:COMPUTERNAME- OSVersion = (Get-CimInstance Win32_OperatingSystem).Caption- LastBootTime = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime+ OSVersion = $(if ($null -ne $osInfo) { $osInfo.Caption } else { $null })+ LastBootTime = $(if ($null -ne $osInfo) { $osInfo.LastBootUpTime } else { $null })WindowsUpdateEnabled = $falseAutoUpdateEnabled = $falseInstalledUpdates = @()diff --git a/WindowsDefender/Get-DefenderStatus.ps1 b/WindowsDefender/Get-DefenderStatus.ps1index c855eda..e025882 100644--- a/WindowsDefender/Get-DefenderStatus.ps1+++ b/WindowsDefender/Get-DefenderStatus.ps1@@ -47,7 +47,10 @@ function Get-DefenderStatus {# Get main Defender statusWrite-Host "Collecting Defender status..." -ForegroundColor Yellow- $mpStatus = Get-MpComputerStatus+ $mpStatus = Get-MpComputerStatus -ErrorAction SilentlyContinue+ if ($null -eq $mpStatus) {+ throw "Get-MpComputerStatus returned no data - Windows Defender is unavailable on this system"+ }# Protection Status$status.ProtectionStatus = [PSCustomObject]@{@@ -83,7 +86,10 @@ function Get-DefenderStatus {}# Get Defender preferences/configuration- $mpPreferences = Get-MpPreference+ $mpPreferences = Get-MpPreference -ErrorAction SilentlyContinue+ if ($null -eq $mpPreferences) {+ throw "Get-MpPreference returned no data - Windows Defender preferences are unavailable on this system"+ }$status.Configuration = [PSCustomObject]@{DisableAutoExclusions = $mpPreferences.DisableAutoExclusions