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
Add fleet scans, Sysmon analytics, SIEM streaming, smart alerts (v1.5.0)
Okan YILDIZ73534f8b3ccf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a877376..abc1065 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,14 +7,36 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+## [1.5.0] - 2026-10-25++### Added++- `Send-SiemEvent`: live streaming of findings to Splunk HEC, Microsoft Sentinel (HMAC-SHA256 SharedKey signature), or generic webhooks, with batching and exponential-backoff retries; `Export-SecurityReport -StreamTo` integration.+- `Get-SysmonAnalytics`: Sysmon Operational log detections (process chains, network beaconing, image loads, LSASS access, file creates, registry events, DNS).+- `Get-FileSystemJournal`: USN journal parsing, MFT summary, and heuristic timestomp detection via fsutil.+- `Invoke-EnterpriseSecurityScan -UseModuleFunctions`: deploys and runs the real module functions on remote hosts (`-RemoteFunctionSet Quick/Standard/Deep`), parallel connectivity probes, per-host timeouts, `-TargetFile` input.+- Alert deduplication in `Register-ScheduledSecurityScan`: fingerprint state file, New/Persisting/Resolved classification, `-RealertAfterDays`, `-DisableAlertDedup`.+- TAXII 2.x pagination and MISP attribute expansion to 12 types in `Get-ThreatIntelligence`.+- `Resolve-CpeName`: curated table grown to ~120 products, vendor version-scheme translation (Java/.NET/Python).++### Security++- Refuse to send SIEM tokens over cleartext HTTP; TLS 1.2 floor in the generated scheduled-scan script; generated scan script ACL-locked to SYSTEM + Administrators (webhook secret protection); remote temp-path validation before remote copy/cleanup; CSV formula-injection escaping in forensic exports.++## [1.4.0] - 2026-10-25+### Added-- `CHANGELOG.md`, `SECURITY.md`, and a PowerShell Gallery publish workflow (`.github/workflows/publish.yml`).-- Real module manifest metadata (author, license/project URIs, gallery tags) in `WindowsSecurityAudit.psd1`.+- `ConvertTo-SiemEvent` and `Export-SecurityReport -Format NDJSON|CEF` (one event per finding) plus `-NoAutoOpen`.+- `Get-CredentialAccessEvents`: Kerberoasting, TGT anomalies, 4771 spray, golden-ticket heuristic, optional LSASS access monitoring; `Find-SuspiciousAuthentication` 4624 Type 9 and NTLM indicators.+- `Find-DefenseEvasion`: AMSI/ETW tamper patterns, Defender exclusion/tamper changes, log-clearing attribution, log-gap analysis.+- `Get-UserActivityArtifacts`: Recycle Bin $I parsing, LNK resolution, JumpList enumeration, Timeline DB copy; `Get-ArtifactCollection` SHA256-at-acquisition, raw registry hives, acquisition log.+- `CHANGELOG.md`, `SECURITY.md`, gallery publish workflow, real manifest metadata.### Changed-- `Get-CloudComplianceStatus` no longer reports fabricated `Compliant`/`Non-Compliant` results. Controls are returned with `Status = 'NotEvaluated'` until framework-specific Microsoft Graph/API evaluation is implemented, and the compliance score is `$null` when no controls were actually evaluated.+- `Get-CloudComplianceStatus` no longer fabricates compliance statuses (honest NotEvaluated).+- ~30 zero-defect audit fixes across all modules (strict-mode scalar counts, ROT13 decoder, DCSync whitelist, event indexes, ShouldProcess coverage, localization-safe account lookups).## [1.3.0] - 2026-10-25diff --git a/Detection/Get-SysmonAnalytics.ps1 b/Detection/Get-SysmonAnalytics.ps1new file mode 100644index 0000000..513c5f6--- /dev/null+++ b/Detection/Get-SysmonAnalytics.ps1@@ -0,0 +1,729 @@+function Get-SysmonAnalytics {+ <#+ .SYNOPSIS+ Sysmon-native threat analytics across key Sysmon event types+ .DESCRIPTION+ Analyzes the Microsoft-Windows-Sysmon/Operational log for suspicious activity:+ process-creation chains and encoded/obfuscated command lines (Event ID 1),+ network connections from unexpected processes and beaconing patterns (ID 3),+ suspicious image loads into critical system processes (ID 7),+ lsass.exe process-access attempts with read-capable masks (ID 10),+ executable drops into startup/temp locations (ID 11),+ persistence-oriented registry writes (IDs 12/13), and+ anomalous DNS queries (ID 22).+ Every finding carries a MITRE ATT&CK technique ID. Behavioral checks are+ heuristics and are labeled as such - validate findings manually before+ treating them as confirmed malicious. If Sysmon is not installed, the+ function returns gracefully with Status 'NotAvailable'.+ .PARAMETER Hours+ Number of hours to look back in the Sysmon log (default: 24)+ .PARAMETER EventTypes+ Sysmon event categories to analyze. Valid values: ProcessCreation,+ NetworkConnection, ImageLoad, ProcessAccess, FileCreate, RegistryEvent,+ DnsQuery. Defaults to all categories+ .PARAMETER MaxEvents+ Maximum number of Sysmon events to load across all categories (default: 5000).+ Guards against excessive memory usage on busy systems; when the cap is hit,+ remaining categories are skipped and the cap is reported in the summary+ .EXAMPLE+ Get-SysmonAnalytics+ Get-SysmonAnalytics -Hours 48 -EventTypes ProcessCreation, NetworkConnection+ .OUTPUTS+ PSCustomObject with Findings, Summary, and Recommendations+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [int]$Hours = 24,++ [Parameter()]+ [ValidateSet('ProcessCreation', 'NetworkConnection', 'ImageLoad', 'ProcessAccess', 'FileCreate', 'RegistryEvent', 'DnsQuery')]+ [string[]]$EventTypes = @('ProcessCreation', 'NetworkConnection', 'ImageLoad', 'ProcessAccess', 'FileCreate', 'RegistryEvent', 'DnsQuery'),++ [Parameter()]+ [int]$MaxEvents = 5000+ )++ begin {+ Write-Host "Analyzing Sysmon telemetry (last $Hours hours)..." -ForegroundColor Cyan++ $sysmonLog = 'Microsoft-Windows-Sysmon/Operational'+ $startTime = (Get-Date).AddHours(-$Hours)++ $results = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ TimeRange = "$Hours hours"+ Status = 'OK'+ Findings = @()+ Summary = [PSCustomObject]@{+ TotalFindings = 0+ Critical = 0+ High = 0+ Medium = 0+ Low = 0+ Info = 0+ SysmonPresent = $false+ EventsScanned = 0+ MaxEventsReached = $false+ }+ Recommendations = @()+ }++ $eventIdMap = @{+ ProcessCreation = @(1)+ NetworkConnection = @(3)+ ImageLoad = @(7)+ ProcessAccess = @(10)+ FileCreate = @(11)+ RegistryEvent = @(12, 13)+ DnsQuery = @(22)+ }++ # Null-safe EventData field extraction (Sysmon schema varies by version;+ # missing Data nodes return $null instead of throwing)+ $getEventValue = {+ param($EventData, [string]$Name)+ if ($null -eq $EventData) { return $null }+ $node = $EventData | Where-Object { $_.Name -eq $Name }+ if ($null -ne $node) { return $node.InnerText }+ return $null+ }++ $getFileName = {+ param([string]$Path)+ if ([string]::IsNullOrEmpty($Path)) { return '' }+ if ($Path -match '([^\\/]+)$') { return $Matches[1] }+ return $Path+ }++ $isPrivateIP = {+ param([string]$IP)+ if ([string]::IsNullOrEmpty($IP) -or $IP -eq '-') { return $true }+ if ($IP -match '^(10\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[0-1])\.|127\.|169\.254\.|::1$|fe80:|fc00:|fd)') { return $true }+ return $false+ }++ # Shannon entropy helper for DGA-style label detection (heuristic)+ $getEntropy = {+ param([string]$Text)+ if ([string]::IsNullOrEmpty($Text)) { return 0.0 }+ $freq = @{}+ foreach ($char in $Text.ToCharArray()) {+ $key = [string]$char+ if ($freq.ContainsKey($key)) { $freq[$key]++ } else { $freq[$key] = 1 }+ }+ $length = $Text.Length+ $entropy = 0.0+ foreach ($k in $freq.Keys) {+ $p = $freq[$k] / $length+ $entropy -= $p * [math]::Log($p, 2)+ }+ return [math]::Round($entropy, 2)+ }++ # Granted-access mask classification aligned with Get-CredentialAccessEvents:+ # PROCESS_VM_READ (0x0010) or broad rights are suspicious for lsass handles+ $normalAccessMasks = @('0x1000', '0x1400')+ $suspiciousAccessMasks = @('0x1010', '0x101a', '0x103a', '0x143a', '0x1f0fff', '0x1fffff')++ $officeParents = @('winword.exe', 'excel.exe', 'powerpnt.exe', 'outlook.exe', 'mspub.exe', 'visio.exe', 'msaccess.exe')+ $scriptChildren = @('cmd.exe', 'powershell.exe', 'pwsh.exe', 'wscript.exe', 'cscript.exe', 'mshta.exe', 'rundll32.exe', 'regsvr32.exe')+ $networkAbuseProcs = @('powershell.exe', 'pwsh.exe', 'rundll32.exe', 'regsvr32.exe', 'mshta.exe', 'wscript.exe', 'cscript.exe', 'certutil.exe', 'bitsadmin.exe', 'cmd.exe', 'hh.exe')+ $criticalSystemProcs = @('lsass.exe', 'winlogon.exe', 'csrss.exe', 'services.exe', 'smss.exe', 'wininit.exe')+ $userWritablePathPattern = '(\\Temp\\|\\AppData\\|\\Users\\Public\\|\\Downloads\\|\\Windows\\Tasks\\)'+ $commonPorts = @(80, 443, 53, 22, 21, 25, 110, 143, 993, 995, 3389, 445, 139, 135, 587, 465, 853)++ # Processes that legitimately issue large volumes of DNS queries (browsers,+ # system services, common collaboration tools) - used by the Event 22+ # process-mismatch heuristic+ $dnsExpectedProcs = @(+ 'svchost.exe', 'chrome.exe', 'firefox.exe', 'msedge.exe', 'iexplore.exe', 'brave.exe', 'opera.exe',+ 'outlook.exe', 'teams.exe', 'slack.exe', 'zoom.exe', 'onedrive.exe', 'dropbox.exe', 'code.exe',+ 'wmiprvse.exe', 'dns.exe', 'lsass.exe', 'smartscreen.exe', 'searchui.exe', 'backgroundtaskhost.exe',+ 'dllhost.exe', 'msmpeng.exe', 'system', 'spoolsv.exe', 'officeclicktorun.exe'+ )++ # Known-abused TLDs (heuristic signal only - many legitimate sites use these)+ $suspiciousTldPattern = '\.(top|xyz|club|online|site|buzz|tk|ml|ga|cf|gq|loan|work|click|link|pw|quest|icu|cam|rest|monster)\.?$'++ # Encoded / obfuscated command-line indicators (matching the pattern style+ # used across the module's script-block analytics)+ $encodedCommandPatterns = @(+ [PSCustomObject]@{ Name = 'Base64-encoded command argument'; Pattern = '(?i)-e(nc|ncodedcommand)?\s+[A-Za-z0-9+/=]{40,}'; Severity = 'High'; Technique = 'T1027' }+ [PSCustomObject]@{ Name = 'Runtime decoding primitive'; Pattern = '(?i)frombase64string|fromcharcode|\[char\]\s*\d+'; Severity = 'High'; Technique = 'T1027' }+ [PSCustomObject]@{ Name = 'Download cradle'; Pattern = '(?i)downloadstring|downloadfile|invoke-webrequest|\biwr\b|start-bitstransfer|certutil\s+.*-urlcache|bitsadmin\s+.*/transfer'; Severity = 'High'; Technique = 'T1105' }+ [PSCustomObject]@{ Name = 'Dynamic evaluation (IEX)'; Pattern = '(?i)\biex\b|invoke-expression'; Severity = 'Medium'; Technique = 'T1059.001' }+ [PSCustomObject]@{ Name = 'Hidden window execution'; Pattern = '(?i)-w(indowstyle)?\s+hidden'; Severity = 'Medium'; Technique = 'T1564.003' }+ [PSCustomObject]@{ Name = 'Execution-policy bypass'; Pattern = '(?i)-ep\s+bypass|-executionpolicy\s+bypass'; Severity = 'Medium'; Technique = 'T1059.001' }+ )++ $addFinding = {+ param(+ [Parameter(Mandatory)]$Results,+ [Parameter(Mandatory)][string]$EventType,+ [Parameter(Mandatory)][string]$Technique,+ [Parameter(Mandatory)][string]$Severity,+ [Parameter(Mandatory)]$Evidence,+ $Timestamp+ )+ $Results.Findings += [PSCustomObject]@{+ EventType = $EventType+ Technique = $Technique+ Severity = $Severity+ Evidence = $Evidence+ Timestamp = $Timestamp+ }+ switch ($Severity) {+ 'Critical' { $Results.Summary.Critical++ }+ 'High' { $Results.Summary.High++ }+ 'Medium' { $Results.Summary.Medium++ }+ 'Low' { $Results.Summary.Low++ }+ default { $Results.Summary.Info++ }+ }+ }+ }++ process {+ # Sysmon presence gate - return gracefully when the log does not exist+ try {+ $null = Get-WinEvent -ListLog $sysmonLog -ErrorAction Stop+ $results.Summary.SysmonPresent = $true+ }+ catch {+ $results.Summary.SysmonPresent = $false+ $results.Status = 'NotAvailable'+ $results.Recommendations += 'Sysmon not installed; enable for deep visibility - deploy Sysmon with a community-hardened configuration (e.g. SwiftOnSecurity/sysmon-config or Olaf Hartong''s sysmon-modular) to gain process, network, image-load, registry, and DNS telemetry'+ }++ if (-not $results.Summary.SysmonPresent) {+ return+ }++ # Load events for the selected categories, honoring the MaxEvents budget+ $eventsByType = @{}+ foreach ($eventType in $EventTypes) {+ $remaining = $MaxEvents - $results.Summary.EventsScanned+ if ($remaining -le 0) {+ $results.Summary.MaxEventsReached = $true+ Write-Warning "MaxEvents cap ($MaxEvents) reached - skipping remaining event categories: $($EventTypes | Where-Object { -not $eventsByType.ContainsKey($_) })"+ break+ }+ try {+ $categoryEvents = @(Get-WinEvent -FilterHashtable @{+ LogName = $sysmonLog+ ID = $eventIdMap[$eventType]+ StartTime = $startTime+ } -MaxEvents $remaining -ErrorAction SilentlyContinue)+ $eventsByType[$eventType] = $categoryEvents+ $results.Summary.EventsScanned += @($categoryEvents).Count+ }+ catch {+ Write-Warning "Could not query Sysmon events for $eventType`: $_"+ $eventsByType[$eventType] = @()+ $results.Recommendations += "Sysmon $eventType events were not queryable - verify the Sysmon service is running and the configuration enables this event type"+ }+ }+ if ($results.Summary.EventsScanned -ge $MaxEvents) {+ $results.Summary.MaxEventsReached = $true+ }++ # 1. Process creation (Event ID 1): parent-child chains, encoded command lines,+ # unsigned binaries in user-writable paths spawning children+ if ($eventsByType.ContainsKey('ProcessCreation')) {+ try {+ Write-Verbose "Analyzing process creation events (ID 1)..."+ $processEvents = @($eventsByType['ProcessCreation'])++ $parentImages = @{}+ foreach ($event in $processEvents) {+ if ($null -eq $event) { continue }+ $eventData = ([xml]$event.ToXml()).Event.EventData.Data+ $parentImage = & $getEventValue $eventData 'ParentImage'+ if ($parentImage) { $parentImages[$parentImage.ToLower()] = $true }+ }++ foreach ($event in $processEvents) {+ if ($null -eq $event) { continue }+ $eventData = ([xml]$event.ToXml()).Event.EventData.Data++ $image = & $getEventValue $eventData 'Image'+ $commandLine = & $getEventValue $eventData 'CommandLine'+ $parentImage = & $getEventValue $eventData 'ParentImage'+ $parentCommandLine = & $getEventValue $eventData 'ParentCommandLine'+ $user = & $getEventValue $eventData 'User'+ $signed = & $getEventValue $eventData 'Signed'+ $signatureStatus = & $getEventValue $eventData 'SignatureStatus'+ $imageName = (& $getFileName $image).ToLower()+ $parentName = (& $getFileName $parentImage).ToLower()+ $timestamp = $null+ if ($null -ne $event -and $null -ne ($event.PSObject.Properties['TimeCreated']) -and $null -ne $event.TimeCreated) {+ $timestamp = $event.TimeCreated+ }++ # Office application spawning a scripting engine (T1204.002)+ if ($officeParents -contains $parentName -and $scriptChildren -contains $imageName) {+ & $addFinding $results 'ProcessCreation' 'T1204.002' 'High' ([PSCustomObject]@{+ Indicator = 'Office application spawned a scripting engine'+ ParentImage = $parentImage+ Image = $image+ CommandLine = $commandLine+ User = $user+ Note = 'Classic malicious-document execution chain - inspect the parent document'+ }) $timestamp+ }++ # services.exe spawning unusual children (T1569.002)+ if ($parentName -eq 'services.exe' -and $imageName -notin @('svchost.exe', 'msiexec.exe', 'tiworker.exe', 'trustedinstaller.exe', 'wmiprvse.exe', 'sppsvc.exe', 'sihost.exe')) {+ & $addFinding $results 'ProcessCreation' 'T1569.002' 'Medium' ([PSCustomObject]@{+ Indicator = 'services.exe spawned an unusual child process'+ ParentImage = $parentImage+ ParentCommandLine = $parentCommandLine+ Image = $image+ CommandLine = $commandLine+ User = $user+ Note = 'May indicate malicious service execution - verify the child against installed services'+ }) $timestamp+ }++ # Encoded / obfuscated command lines on script-capable hosts+ if ($commandLine -and $scriptChildren -contains $imageName) {+ foreach ($indicator in $encodedCommandPatterns) {+ if ($commandLine -match $indicator.Pattern) {+ & $addFinding $results 'ProcessCreation' $indicator.Technique $indicator.Severity ([PSCustomObject]@{+ Indicator = $indicator.Name+ Image = $image+ ParentImage = $parentImage+ CommandLine = $commandLine+ User = $user+ Note = 'Obfuscation indicators are heuristics - confirm intent by decoding the command line'+ }) $timestamp+ }+ }+ }++ # Binaries in user-writable paths that spawn children; signature+ # fields are schema-dependent, so absence downgrades to heuristic+ if ($image -and $image -match $userWritablePathPattern -and $parentImages.ContainsKey($image.ToLower())) {+ $signatureNote = 'Signature fields absent from event schema - unsigned status inferred heuristically from the path'+ $severity = 'Medium'+ $isUnsigned = $false+ if ($signed -and $signed -match '^(?i:false)$') { $isUnsigned = $true }+ if ($signatureStatus -and $signatureStatus -match '^(?i:unavailable|invalid|notsigned)$') { $isUnsigned = $true }+ if ($isUnsigned) {+ $signatureNote = "Unsigned binary (Signed=$signed, SignatureStatus=$signatureStatus)"+ $severity = 'High'+ }+ & $addFinding $results 'ProcessCreation' 'T1036' $severity ([PSCustomObject]@{+ Indicator = 'Binary in user-writable path spawning child processes'+ Image = $image+ CommandLine = $commandLine+ User = $user+ SignatureNote = $signatureNote+ Note = 'HEURISTIC when signature fields are absent - legitimate updaters can share this shape'+ }) $timestamp+ }+ }+ }+ catch {+ Write-Warning "Process creation (ID 1) analysis failed: $_"+ }+ }++ # 2. Network connections (Event ID 3): script-capable processes reaching+ # external IPs, and rare-port beaconing (same dest ip+port > 10x in window)+ if ($eventsByType.ContainsKey('NetworkConnection')) {+ try {+ Write-Verbose "Analyzing network connection events (ID 3)..."+ $destinationCounts = @{}++ foreach ($event in @($eventsByType['NetworkConnection'])) {+ if ($null -eq $event) { continue }+ $eventData = ([xml]$event.ToXml()).Event.EventData.Data++ $image = & $getEventValue $eventData 'Image'+ $destIP = & $getEventValue $eventData 'DestinationIp'+ $destPort = & $getEventValue $eventData 'DestinationPort'+ $destHost = & $getEventValue $eventData 'DestinationHostname'+ $user = & $getEventValue $eventData 'User'+ $imageName = (& $getFileName $image).ToLower()+ $timestamp = $null+ if ($null -ne $event -and $null -ne ($event.PSObject.Properties['TimeCreated']) -and $null -ne $event.TimeCreated) {+ $timestamp = $event.TimeCreated+ }++ if (-not $destIP -or $destIP -eq '-') { continue }++ $portNumber = 0+ if ($destPort) { try { $portNumber = [int]$destPort } catch { $portNumber = 0 } }+ $destKey = "${destIP}:$portNumber"+ if (-not $destinationCounts.ContainsKey($destKey)) {+ $destinationCounts[$destKey] = [PSCustomObject]@{ Count = 0; Images = @(); LastSeen = $timestamp; Port = $portNumber; DestinationHostname = $destHost }+ }+ $destinationCounts[$destKey].Count+++ if ($image -and $destinationCounts[$destKey].Images -notcontains $image) {+ $destinationCounts[$destKey].Images += $image+ }+ if ($null -ne $timestamp -and ($null -eq $destinationCounts[$destKey].LastSeen -or $timestamp -gt $destinationCounts[$destKey].LastSeen)) {+ $destinationCounts[$destKey].LastSeen = $timestamp+ }++ # Script-capable process connecting to a non-RFC1918 address+ if ($networkAbuseProcs -contains $imageName -and -not (& $isPrivateIP $destIP)) {+ $severity = 'Medium'+ if ($imageName -in @('powershell.exe', 'pwsh.exe', 'rundll32.exe', 'regsvr32.exe')) { $severity = 'High' }+ & $addFinding $results 'NetworkConnection' 'T1071' $severity ([PSCustomObject]@{+ Indicator = 'Script-capable or proxy-execution binary made an outbound connection to an external address'+ Image = $image+ DestinationIp = $destIP+ DestinationPort = $portNumber+ DestinationHostname = $destHost+ User = $user+ Note = 'HEURISTIC - legitimate admin scripts also match; correlate with the process command line (Event ID 1)'+ }) $timestamp+ }+ }++ # Beaconing: same destination ip+port more than 10 times in the window+ foreach ($destKey in $destinationCounts.Keys) {+ $destInfo = $destinationCounts[$destKey]+ if ($destInfo.Count -gt 10) {+ $technique = 'T1071.001'+ if ($destInfo.Port -gt 0 -and $commonPorts -notcontains $destInfo.Port) { $technique = 'T1571' }+ & $addFinding $results 'NetworkConnection' $technique 'Medium' ([PSCustomObject]@{+ Indicator = "Beaconing pattern: $($destInfo.Count) connections to $destKey within the analysis window"+ Destination = $destKey+ DestinationHostname = $destInfo.DestinationHostname+ ConnectionCount = $destInfo.Count+ Images = ($destInfo.Images -join ', ')+ Note = 'HEURISTIC threshold (>10 connections) - software update agents can produce similar cadence'+ }) $destInfo.LastSeen+ }+ }+ }+ catch {+ Write-Warning "Network connection (ID 3) analysis failed: $_"+ }+ }++ # 3. Image loads (Event ID 7): unsigned DLLs into lsass/winlogon (T1547.008 style),+ # DLLs from temp/appdata into system processes (T1574)+ if ($eventsByType.ContainsKey('ImageLoad')) {+ try {+ Write-Verbose "Analyzing image load events (ID 7)..."++ foreach ($event in @($eventsByType['ImageLoad'])) {+ if ($null -eq $event) { continue }+ $eventData = ([xml]$event.ToXml()).Event.EventData.Data++ $image = & $getEventValue $eventData 'Image'+ $imageLoaded = & $getEventValue $eventData 'ImageLoaded'+ $signed = & $getEventValue $eventData 'Signed'+ $signatureStatus = & $getEventValue $eventData 'SignatureStatus'+ $imageName = (& $getFileName $image).ToLower()+ $timestamp = $null+ if ($null -ne $event -and $null -ne ($event.PSObject.Properties['TimeCreated']) -and $null -ne $event.TimeCreated) {+ $timestamp = $event.TimeCreated+ }++ if (-not $imageLoaded) { continue }++ $isUnsigned = $false+ if ($signed -and $signed -match '^(?i:false)$') { $isUnsigned = $true }+ if ($signatureStatus -and $signatureStatus -match '^(?i:unavailable|invalid|notsigned)$') { $isUnsigned = $true }++ # Unsigned module loaded into lsass.exe / winlogon.exe+ if ($imageName -in @('lsass.exe', 'winlogon.exe') -and ($isUnsigned -or $imageLoaded -notmatch '\\Windows\\System32\\')) {+ & $addFinding $results 'ImageLoad' 'T1547.008' 'High' ([PSCustomObject]@{+ Indicator = 'Unsigned or non-System32 module loaded into a critical logon process'+ Image = $image+ ImageLoaded = $imageLoaded+ Signed = $signed+ SignatureStatus = $signatureStatus+ Note = 'LSA authentication-package / SSP style load - verify the DLL against a known-good baseline'+ }) $timestamp+ continue+ }++ # DLL loaded from temp/appdata into a system process+ if ($criticalSystemProcs -contains $imageName -and $imageLoaded -match $userWritablePathPattern) {+ & $addFinding $results 'ImageLoad' 'T1574.002' 'High' ([PSCustomObject]@{+ Indicator = 'DLL loaded from a user-writable directory into a system process'+ Image = $image+ ImageLoaded = $imageLoaded+ Signed = $signed+ SignatureStatus = $signatureStatus+ Note = 'Consistent with DLL side-loading / search-order hijacking into a privileged process'+ }) $timestamp+ }+ }+ }+ catch {+ Write-Warning "Image load (ID 7) analysis failed: $_"+ }+ }++ # 4. Process access (Event ID 10): lsass.exe targets with VM_READ-capable masks+ # (mask classification aligned with Get-CredentialAccessEvents)+ if ($eventsByType.ContainsKey('ProcessAccess')) {+ try {+ Write-Verbose "Analyzing process access events (ID 10)..."++ foreach ($event in @($eventsByType['ProcessAccess'])) {+ if ($null -eq $event) { continue }+ $eventData = ([xml]$event.ToXml()).Event.EventData.Data++ $targetImage = & $getEventValue $eventData 'TargetImage'+ if (-not $targetImage -or $targetImage -notmatch 'lsass\.exe$') { continue }++ $sourceImage = & $getEventValue $eventData 'SourceImage'+ $sourceUser = & $getEventValue $eventData 'SourceUser'+ $grantedAccess = & $getEventValue $eventData 'GrantedAccess'+ $timestamp = $null+ if ($null -ne $event -and $null -ne ($event.PSObject.Properties['TimeCreated']) -and $null -ne $event.TimeCreated) {+ $timestamp = $event.TimeCreated+ }++ $classification = 'Review'+ $severity = 'Medium'+ $maskValue = $null+ if ($grantedAccess) {+ try { $maskValue = [Convert]::ToInt64($grantedAccess, 16) } catch { $maskValue = $null }+ }+ if ($null -ne $maskValue) {+ if (($maskValue -band 0x10) -ne 0 -or $suspiciousAccessMasks -contains $grantedAccess.ToLower()) {+ $classification = 'Suspicious'+ $severity = 'High'+ }+ elseif ($normalAccessMasks -contains $grantedAccess.ToLower()) {+ $classification = 'Normal'+ $severity = 'Info'+ }+ }++ if ($classification -eq 'Normal') { continue }++ & $addFinding $results 'ProcessAccess' 'T1003.001' $severity ([PSCustomObject]@{+ Indicator = "Process opened lsass.exe with granted access $grantedAccess ($classification)"+ SourceImage = $sourceImage+ SourceUser = $sourceUser+ TargetImage = $targetImage+ GrantedAccess = $grantedAccess+ Note = 'PROCESS_VM_READ (0x10) or broad rights against lsass may indicate credential dumping (T1003.001)'+ }) $timestamp+ }+ }+ catch {+ Write-Warning "Process access (ID 10) analysis failed: $_"+ }+ }++ # 5. File create (Event ID 11): executables dropped into Startup/Prefetch/Temp+ # by non-installer parents (T1547.001 / T1105)+ if ($eventsByType.ContainsKey('FileCreate')) {+ try {+ Write-Verbose "Analyzing file create events (ID 11)..."+ $installerParents = @('msiexec.exe', 'setup.exe', 'tiworker.exe', 'trustedinstaller.exe', 'wuauclt.exe', 'musnotification.exe', 'officeclicktorun.exe', 'msedgeupdate.exe', 'googleupdate.exe', 'svchost.exe')+ $executableExtensionPattern = '\.(exe|dll|scr|bat|cmd|ps1|vbs|js|jse|hta|msi)$'++ foreach ($event in @($eventsByType['FileCreate'])) {+ if ($null -eq $event) { continue }+ $eventData = ([xml]$event.ToXml()).Event.EventData.Data++ $image = & $getEventValue $eventData 'Image'+ $targetFilename = & $getEventValue $eventData 'TargetFilename'+ $imageName = (& $getFileName $image).ToLower()+ $timestamp = $null+ if ($null -ne $event -and $null -ne ($event.PSObject.Properties['TimeCreated']) -and $null -ne $event.TimeCreated) {+ $timestamp = $event.TimeCreated+ }++ if (-not $targetFilename -or $targetFilename -notmatch $executableExtensionPattern) { continue }+ if ($targetFilename -notmatch '(\\Start Menu\\Programs\\Startup\\|\\Prefetch\\|\\Temp\\|\\Windows\\Tasks\\)') { continue }+ if ($installerParents -contains $imageName) { continue }++ $technique = 'T1105'+ if ($targetFilename -match '\\Start Menu\\Programs\\Startup\\') { $technique = 'T1547.001' }++ & $addFinding $results 'FileCreate' $technique 'Medium' ([PSCustomObject]@{+ Indicator = 'Executable dropped into a startup, prefetch, or temp location by a non-installer process'+ Image = $image+ TargetFilename = $targetFilename+ Note = 'HEURISTIC - browsers and build tools also write executables to temp paths; verify the file hash'+ }) $timestamp+ }+ }+ catch {+ Write-Warning "File create (ID 11) analysis failed: $_"+ }+ }++ # 6. Registry events (IDs 12/13): Run-key writes, IFEO debugger sets, LSA+ # package changes (patterns consistent with Find-PersistenceMechanisms)+ if ($eventsByType.ContainsKey('RegistryEvent')) {+ try {+ Write-Verbose "Analyzing registry events (IDs 12/13)..."++ foreach ($event in @($eventsByType['RegistryEvent'])) {+ if ($null -eq $event) { continue }+ $eventData = ([xml]$event.ToXml()).Event.EventData.Data++ $image = & $getEventValue $eventData 'Image'+ $targetObject = & $getEventValue $eventData 'TargetObject'+ $details = & $getEventValue $eventData 'Details'+ $timestamp = $null+ if ($null -ne $event -and $null -ne ($event.PSObject.Properties['TimeCreated']) -and $null -ne $event.TimeCreated) {+ $timestamp = $event.TimeCreated+ }++ if (-not $targetObject) { continue }++ # Run / RunOnce key writes (same key families as Find-PersistenceMechanisms)+ if ($targetObject -match '(?i)\\(Software|SOFTWARE)\\(Microsoft\\)?Windows\\CurrentVersion\\Run(Once|Services|ServicesOnce)?(\\|$)') {+ & $addFinding $results 'RegistryEvent' 'T1547.001' 'High' ([PSCustomObject]@{+ Indicator = 'Write to a Run/RunOnce autostart registry key'+ Image = $image+ TargetObject = $targetObject+ Details = $details+ Note = 'New or modified autostart entry - compare with the persistence baseline from Find-PersistenceMechanisms'+ }) $timestamp+ continue+ }++ # IFEO debugger hijack+ if ($targetObject -match '(?i)\\Image File Execution Options\\[^\\]+\\Debugger$') {+ & $addFinding $results 'RegistryEvent' 'T1546.012' 'High' ([PSCustomObject]@{+ Indicator = 'Image File Execution Options debugger value set'+ Image = $image+ TargetObject = $targetObject+ Details = $details+ Note = 'IFEO debuggers redirect execution of the named binary - a classic persistence / privilege-escalation primitive'+ }) $timestamp+ continue+ }++ # LSA authentication / security package changes+ if ($targetObject -match '(?i)\\SYSTEM\\CurrentControlSet\\Control\\Lsa\\(Authentication Packages|Security Packages|Notification Packages)$' -or+ ($targetObject -match '(?i)\\Control\\Lsa$' -and $details -match '(?i)Authentication Packages|Security Packages|Notification Packages')) {+ & $addFinding $results 'RegistryEvent' 'T1547.005' 'High' ([PSCustomObject]@{+ Indicator = 'LSA authentication/security package configuration modified'+ Image = $image+ TargetObject = $targetObject+ Details = $details+ Note = 'Custom SSP/AP DLLs load into lsass at boot and can capture credentials - validate the package list against msv1_0/scecli/rassfm defaults'+ }) $timestamp+ }+ }+ }+ catch {+ Write-Warning "Registry event (ID 12/13) analysis failed: $_"+ }+ }++ # 7. DNS queries (Event ID 22): DGA-ish high-entropy labels, known-abused TLDs,+ # queries issued by unexpected processes (all heuristics)+ if ($eventsByType.ContainsKey('DnsQuery')) {+ try {+ Write-Verbose "Analyzing DNS query events (ID 22)..."++ foreach ($event in @($eventsByType['DnsQuery'])) {+ if ($null -eq $event) { continue }+ $eventData = ([xml]$event.ToXml()).Event.EventData.Data++ $image = & $getEventValue $eventData 'Image'+ $queryName = & $getEventValue $eventData 'QueryName'+ $queryResults = & $getEventValue $eventData 'QueryResults'+ $imageName = (& $getFileName $image).ToLower()+ $timestamp = $null+ if ($null -ne $event -and $null -ne ($event.PSObject.Properties['TimeCreated']) -and $null -ne $event.TimeCreated) {+ $timestamp = $event.TimeCreated+ }++ if (-not $queryName) { continue }++ # DGA-style label: long label with high Shannon entropy (heuristic)+ $labels = $queryName.TrimEnd('.') -split '\.'+ foreach ($label in $labels) {+ if ($label.Length -ge 20) {+ $entropy = & $getEntropy $label+ if ($entropy -gt 3.8 -or $label.Length -ge 30) {+ & $addFinding $results 'DnsQuery' 'T1568.002' 'Medium' ([PSCustomObject]@{+ Indicator = "High-entropy DNS label (length $($label.Length), entropy $entropy) - DGA-style heuristic"+ Image = $image+ QueryName = $queryName+ QueryResults = $queryResults+ Note = 'HEURISTIC - CDN and telemetry domains can also produce long high-entropy labels'+ }) $timestamp+ }+ break+ }+ }++ # Known-abused TLD (heuristic)+ if ($queryName -match $suspiciousTldPattern) {+ & $addFinding $results 'DnsQuery' 'T1071.004' 'Low' ([PSCustomObject]@{+ Indicator = 'Query for a domain on a frequently abused TLD'+ Image = $image+ QueryName = $queryName+ QueryResults = $queryResults+ Note = 'HEURISTIC - these TLDs also host legitimate services; combine with other signals before blocking'+ }) $timestamp+ }++ # Query issued by a process that does not normally resolve DNS+ if ($imageName -and $dnsExpectedProcs -notcontains $imageName -and $image -notmatch '(?i)\\Windows\\System32\\|\\Program Files') {+ & $addFinding $results 'DnsQuery' 'T1071.004' 'Low' ([PSCustomObject]@{+ Indicator = 'DNS query issued by an unexpected process (not a browser/system service and outside System32/Program Files)'+ Image = $image+ QueryName = $queryName+ QueryResults = $queryResults+ Note = 'HEURISTIC - portable applications legitimately resolve DNS; prioritize when combined with DGA or TLD signals'+ }) $timestamp+ }+ }+ }+ catch {+ Write-Warning "DNS query (ID 22) analysis failed: $_"+ }+ }++ $results.Summary.TotalFindings = @($results.Findings).Count++ # Recommendations based on findings+ if ($results.Summary.MaxEventsReached) {+ $results.Recommendations += "MaxEvents cap ($MaxEvents) was reached - re-run with a higher -MaxEvents or a smaller -Hours window for complete coverage"+ }+ if ($results.Summary.High -gt 0 -or $results.Summary.Critical -gt 0) {+ $results.Recommendations += 'High-severity Sysmon findings present - isolate affected hosts, preserve the Sysmon log, and validate each finding against the referenced MITRE technique before remediation'+ }+ if (@($results.Findings | Where-Object { $_.Technique -eq 'T1003.001' }).Count -gt 0) {+ $results.Recommendations += 'lsass.exe access with read-capable masks detected (T1003.001) - treat as potential credential theft; capture memory and reset exposed credentials'+ }+ if (@($results.Findings | Where-Object { $_.Technique -match '^T1547|^T1546' }).Count -gt 0) {+ $results.Recommendations += 'Persistence-oriented writes detected - cross-check with Find-PersistenceMechanisms to confirm the mechanism is active and remove unauthorized autostart entries'+ }+ if ($results.Summary.TotalFindings -eq 0) {+ $results.Recommendations += 'No suspicious Sysmon activity detected in the window - maintain Sysmon with a hardened configuration and forward the Operational log to a SIEM for long-term correlation'+ }+ }++ end {+ Write-Host "`nSysmon Analytics Complete!" -ForegroundColor Green+ Write-Host "`n=== Summary ===" -ForegroundColor Cyan+ Write-Host "Sysmon present: $($results.Summary.SysmonPresent)" -ForegroundColor Yellow+ Write-Host "Events scanned: $($results.Summary.EventsScanned)" -ForegroundColor Yellow+ Write-Host "Total findings: $($results.Summary.TotalFindings)" -ForegroundColor $(if ($results.Summary.TotalFindings -gt 0) { 'Red' } else { 'Green' })+ Write-Host "High/Critical: $($results.Summary.High + $results.Summary.Critical)" -ForegroundColor $(if (($results.Summary.High + $results.Summary.Critical) -gt 0) { 'Red' } else { 'Green' })+ Write-Host "Medium: $($results.Summary.Medium)" -ForegroundColor $(if ($results.Summary.Medium -gt 0) { 'Yellow' } else { 'Green' })+ Write-Host "Low: $($results.Summary.Low)" -ForegroundColor Yellow++ if (@($results.Recommendations).Count -gt 0) {+ Write-Host "`n=== Recommendations ===" -ForegroundColor Cyan+ foreach ($recommendation in $results.Recommendations) {+ Write-Host "- $recommendation" -ForegroundColor Yellow+ }+ }++ return $results+ }+}diff --git a/Enterprise/Invoke-EnterpriseSecurityScan.ps1 b/Enterprise/Invoke-EnterpriseSecurityScan.ps1index df081ab..d8cdea5 100644--- a/Enterprise/Invoke-EnterpriseSecurityScan.ps1+++ b/Enterprise/Invoke-EnterpriseSecurityScan.ps1@@ -4,13 +4,56 @@ function Invoke-EnterpriseSecurityScan {Performs security scans across multiple systems in an enterprise environment.DESCRIPTIONExecutes comprehensive security assessments on multiple remote computers simultaneously,- collecting and aggregating results for enterprise-wide security analysis+ collecting and aggregating results for enterprise-wide security analysis.++ Two execution modes are available:++ Built-in checks (default): a fixed set of native-cmdlet checks (Defender, firewall,+ UAC, updates, local admins, event log and disk health) runs on each target and a+ SecurityScore (0-100) is computed per system.++ Module function deployment (-UseModuleFunctions): the WindowsSecurityAudit module is+ packaged into a temporary zip archive, copied to each reachable target over a PowerShell+ session (Copy-Item -ToSession) into a remote temp directory, imported there, and the+ curated function bundle selected via -RemoteFunctionSet (Quick, Standard, or Deep) is+ executed with default parameters. The remote temp directory is removed again in a+ finally block on every path. Results are returned verbatim under Details.ModuleResults.+ The SecurityScore is only meaningful for the built-in checks; for module deployments+ any 'Findings' collections emitted by the module functions are rolled up heuristically+ (severity/category tagging) into the per-system Findings list - this roll-up is a+ heuristic convenience, not a detection guarantee. Remote targets require PowerShell+ 5.1+ with remoting enabled and Expand-Archive available.++ Fleet hardening: connectivity is probed in parallel through the runspace pool before+ any scan job is queued (-ProbeTimeoutSec bounds each probe), and every scan job is+ bounded by -HostTimeoutSec; jobs exceeding the limit are stopped, disposed, and+ reported with Status 'Timeout'. Per-host failures never abort the fleet run..PARAMETER ComputerName- Array of computer names or IP addresses to scan+ Array of computer names or IP addresses to scan. Optional when -TargetFile is used+ .PARAMETER TargetFile+ Path to a CSV file containing a 'ComputerName' column with the targets to scan.+ Entries are combined with -ComputerName and de-duplicated.PARAMETER Credential- PSCredential object for remote authentication+ PSCredential object for remote authentication. Never written to logs or output.PARAMETER ScanType- Type of scan: Quick, Standard, or Comprehensive+ Type of built-in scan: Quick, Standard, or Comprehensive+ .PARAMETER UseModuleFunctions+ Deploy the WindowsSecurityAudit module to each target and run the real module+ functions selected by -RemoteFunctionSet instead of the built-in native-cmdlet checks+ .PARAMETER RemoteFunctionSet+ Curated module function bundle to run remotely: Quick (Get-SecurityBaseline,+ Get-DefenderStatus), Standard (Quick + Find-SuspiciousProcesses,+ Find-PersistenceMechanisms, Get-SystemInfo), or Deep (Standard ++ Get-CredentialAccessEvents, Find-DefenseEvasion, Find-LateralMovement,+ Get-VulnerabilityAssessment). Default: Standard+ .PARAMETER ModulePath+ Explicit path to the WindowsSecurityAudit module root to package. When omitted, the+ root is resolved from the running module (or the parent of this script's folder)+ .PARAMETER ProbeTimeoutSec+ Maximum seconds to wait for each parallel connectivity probe (default: 3)+ .PARAMETER HostTimeoutSec+ Maximum seconds each per-host scan job may run before it is stopped, disposed, and+ marked with Status 'Timeout' (default: 300).PARAMETER MaxThreadsMaximum number of concurrent scans (1-512, default: 10).PARAMETER OutputPath@@ -18,56 +61,128 @@ function Invoke-EnterpriseSecurityScan {.EXAMPLEInvoke-EnterpriseSecurityScan -ComputerName "SERVER01","SERVER02" -ScanType StandardInvoke-EnterpriseSecurityScan -ComputerName (Get-Content servers.txt) -Credential $cred -MaxThreads 20+ .EXAMPLE+ Invoke-EnterpriseSecurityScan -TargetFile targets.csv -UseModuleFunctions -RemoteFunctionSet Deep -Credential $cred -HostTimeoutSec 600+ Deploys the module to every host listed in targets.csv and runs the Deep function bundle+ .EXAMPLE+ Invoke-EnterpriseSecurityScan -ComputerName "SERVER01" -UseModuleFunctions -WhatIf+ Shows what would be packaged, deployed, and executed without changing anything.OUTPUTSPSCustomObject with enterprise scan results#>-- [CmdletBinding()]++ [CmdletBinding(SupportsShouldProcess = $true)]param(- [Parameter(Mandatory = $true)]+ [Parameter()][string[]]$ComputerName,-++ [Parameter()]+ [string]$TargetFile,+[Parameter()][PSCredential]$Credential,-+[Parameter()][ValidateSet('Quick', 'Standard', 'Comprehensive')][string]$ScanType = 'Standard',-++ [Parameter()]+ [switch]$UseModuleFunctions,++ [Parameter()]+ [ValidateSet('Quick', 'Standard', 'Deep')]+ [string]$RemoteFunctionSet = 'Standard',++ [Parameter()]+ [string]$ModulePath,++ [Parameter()]+ [ValidateRange(1, 3600)]+ [int]$ProbeTimeoutSec = 3,++ [Parameter()]+ [ValidateRange(1, 86400)]+ [int]$HostTimeoutSec = 300,+[Parameter()][ValidateRange(1, 512)][int]$MaxThreads = 10,-+[Parameter()][string]$OutputPath = "C:\EnterpriseScan_$(Get-Date -Format 'yyyyMMdd_HHmmss')")-+begin {+ $zipPath = $null+ $zipLeafName = $null+ $moduleRoot = $null+ $remoteFunctions = @()++ # Assemble the target list from -ComputerName and/or -TargetFile+ $targetComputers = @()+ if ($null -ne $ComputerName) {+ $targetComputers += $ComputerName+ }+ if (-not [string]::IsNullOrWhiteSpace($TargetFile)) {+ if (-not (Test-Path -Path $TargetFile -PathType Leaf)) {+ Write-Error "Target file not found: $TargetFile"+ throw "Target file not found: $TargetFile"+ }+ try {+ $targetRows = @(Import-Csv -Path $TargetFile -ErrorAction Stop)+ }+ catch {+ Write-Error "Could not parse target file '$TargetFile': $_"+ throw+ }+ if ($targetRows.Count -eq 0) {+ Write-Error "Target file '$TargetFile' contains no rows"+ throw "Target file '$TargetFile' contains no rows"+ }+ if ($null -eq $targetRows[0].PSObject.Properties['ComputerName']) {+ Write-Error "Target file '$TargetFile' must contain a 'ComputerName' column"+ throw "Target file '$TargetFile' must contain a 'ComputerName' column"+ }+ foreach ($row in $targetRows) {+ if (-not [string]::IsNullOrWhiteSpace($row.ComputerName)) {+ $targetComputers += $row.ComputerName.Trim()+ }+ }+ }+ $targetComputers = @($targetComputers | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -Unique)+ if ($targetComputers.Count -eq 0) {+ Write-Error "No target computers specified. Provide -ComputerName and/or -TargetFile."+ throw "No target computers specified"+ }+Write-Host "=== ENTERPRISE SECURITY SCAN ===" -ForegroundColor Cyan- Write-Host "Target Systems: $($ComputerName.Count)" -ForegroundColor Yellow+ Write-Host "Target Systems: $($targetComputers.Count)" -ForegroundColor YellowWrite-Host "Scan Type: $ScanType" -ForegroundColor YellowWrite-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow-+# Check if testing locally- $isLocalTest = $ComputerName.Count -eq 1 -and ($ComputerName[0] -eq $env:COMPUTERNAME -or $ComputerName[0] -eq 'localhost' -or $ComputerName[0] -eq '127.0.0.1')-+ $isLocalTest = $targetComputers.Count -eq 1 -and ($targetComputers[0] -eq $env:COMPUTERNAME -or $targetComputers[0] -eq 'localhost' -or $targetComputers[0] -eq '127.0.0.1')+if ($isLocalTest) {Write-Warning "Local testing detected. Ensure PSRemoting is enabled with 'Enable-PSRemoting -Force'"}-+# Create output directoryif (-not (Test-Path $OutputPath)) {- New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ if ($PSCmdlet.ShouldProcess($OutputPath, 'Create output directory')) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ }}-+$results = [PSCustomObject]@{ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"ScanType = $ScanType- TotalSystems = $ComputerName.Count+ TotalSystems = $targetComputers.CountSystemResults = @()Summary = @{Successful = 0Failed = 0+ TimedOut = 0CriticalFindings = 0HighFindings = 0MediumFindings = 0@@ -75,11 +190,68 @@ function Invoke-EnterpriseSecurityScan {}FailedSystems = @()}-- # Script block for remote execution++ # Curated module function bundles for -UseModuleFunctions+ $quickFunctions = @('Get-SecurityBaseline', 'Get-DefenderStatus')+ $standardFunctions = @($quickFunctions) + @('Find-SuspiciousProcesses', 'Find-PersistenceMechanisms', 'Get-SystemInfo')+ $deepFunctions = @($standardFunctions) + @('Get-CredentialAccessEvents', 'Find-DefenseEvasion', 'Find-LateralMovement', 'Get-VulnerabilityAssessment')+ switch ($RemoteFunctionSet) {+ 'Quick' { $remoteFunctions = $quickFunctions }+ 'Standard' { $remoteFunctions = $standardFunctions }+ 'Deep' { $remoteFunctions = $deepFunctions }+ }++ if ($UseModuleFunctions) {+ Write-Host "Mode: Module function deployment ($RemoteFunctionSet set)" -ForegroundColor Yellow+ Write-Host "Remote Functions: $($remoteFunctions -join ', ')" -ForegroundColor Yellow++ # Resolve the module root from -ModulePath, the running module, or this script's parent folder+ if (-not [string]::IsNullOrWhiteSpace($ModulePath)) {+ $moduleRoot = $ModulePath+ }+ else {+ $owningModule = $MyInvocation.MyCommand.Module+ if ($null -ne $owningModule -and -not [string]::IsNullOrEmpty($owningModule.ModuleBase)) {+ $moduleRoot = $owningModule.ModuleBase+ }+ elseif (-not [string]::IsNullOrEmpty($PSScriptRoot)) {+ $moduleRoot = Split-Path -Path $PSScriptRoot -Parent+ }+ }++ if ([string]::IsNullOrEmpty($moduleRoot) -or -not (Test-Path -Path $moduleRoot -PathType Container)) {+ Write-Error "Unable to locate the WindowsSecurityAudit module root. Provide -ModulePath."+ throw "Module root not found"+ }++ $moduleEntryPoints = @(Get-ChildItem -Path $moduleRoot -File -ErrorAction SilentlyContinue | Where-Object { $_.Extension -in @('.psd1', '.psm1') })+ if ($moduleEntryPoints.Count -eq 0) {+ Write-Error "No .psd1 or .psm1 found under module root '$moduleRoot'"+ throw "No module entry point found under '$moduleRoot'"+ }++ # Package the module into a temporary zip archive for deployment+ $zipLeafName = "WindowsSecurityAudit_$([guid]::NewGuid().ToString('N')).zip"+ $candidateZipPath = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath $zipLeafName+ if ($PSCmdlet.ShouldProcess($moduleRoot, "Package module to temporary archive '$candidateZipPath' for deployment to $($targetComputers.Count) system(s)")) {+ try {+ $moduleContent = @(Get-ChildItem -Path $moduleRoot -Force -ErrorAction Stop | Where-Object { $_.Name -ne '.git' })+ Compress-Archive -Path $moduleContent.FullName -DestinationPath $candidateZipPath -Force -ErrorAction Stop+ $zipPath = $candidateZipPath+ $zipSizeKB = [math]::Round((Get-Item -Path $zipPath).Length / 1KB, 1)+ Write-Host "Module packaged: $zipPath ($zipSizeKB KB)" -ForegroundColor Yellow+ }+ catch {+ Write-Error "Failed to package module from '$moduleRoot': $_"+ throw+ }+ }+ }++ # Script block for remote execution of the built-in native-cmdlet checks$scanScriptBlock = {param($ScanType)-+$result = [PSCustomObject]@{ComputerName = $env:COMPUTERNAMEScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"@@ -88,14 +260,14 @@ function Invoke-EnterpriseSecurityScan {Findings = @()Details = @{}}-+try {# Quick baseline check$baseline = Get-MpComputerStatus -ErrorAction SilentlyContinueif ($baseline) {$result.SecurityScore += if ($baseline.RealTimeProtectionEnabled) { 20 } else { 0 }$result.Details.WindowsDefender = $baseline.RealTimeProtectionEnabled-+if (-not $baseline.RealTimeProtectionEnabled) {$result.Findings += [PSCustomObject]@{Severity = 'Critical'@@ -104,13 +276,13 @@ function Invoke-EnterpriseSecurityScan {}}}-+# Firewall check$firewall = Get-NetFirewallProfile -ErrorAction SilentlyContinue$firewallEnabled = @($firewall | Where-Object { $_.Enabled -eq $true }).Count$result.SecurityScore += ($firewallEnabled * 10)$result.Details.FirewallProfiles = $firewallEnabled-+if ($firewallEnabled -lt 3) {$result.Findings += [PSCustomObject]@{Severity = 'High'@@ -118,13 +290,13 @@ function Invoke-EnterpriseSecurityScan {Finding = "Only $firewallEnabled firewall profiles enabled"}}-+# UAC check$uacKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"$uacEnabled = (Get-ItemProperty -Path $uacKey -ErrorAction SilentlyContinue).EnableLUA$result.SecurityScore += if ($uacEnabled -eq 1) { 15 } else { 0 }$result.Details.UACEnabled = ($uacEnabled -eq 1)-+if ($uacEnabled -ne 1) {$result.Findings += [PSCustomObject]@{Severity = 'High'@@ -132,14 +304,14 @@ function Invoke-EnterpriseSecurityScan {Finding = 'User Account Control is disabled'}}-+# Windows Update checktry {$updateSession = New-Object -ComObject Microsoft.Update.Session$updateSearcher = $updateSession.CreateUpdateSearcher()$pendingUpdates = $updateSearcher.Search("IsInstalled=0").Updates.Count$result.Details.PendingUpdates = $pendingUpdates-+if ($pendingUpdates -eq 0) {$result.SecurityScore += 15} else {@@ -152,13 +324,13 @@ function Invoke-EnterpriseSecurityScan {} catch {$result.Details.PendingUpdates = "Unable to check"}-+# Additional checks for Standard/Comprehensive scansif ($ScanType -in @('Standard', 'Comprehensive')) {# Check for admin accounts$adminCount = @(Get-LocalGroupMember -Group "Administrators" -ErrorAction SilentlyContinue).Count$result.Details.AdminAccounts = $adminCount-+if ($adminCount -gt 3) {$result.Findings += [PSCustomObject]@{Severity = 'Medium'@@ -166,14 +338,14 @@ function Invoke-EnterpriseSecurityScan {Finding = "$adminCount administrator accounts (excessive)"}}-+# Check for suspicious services$suspiciousServices = @(Get-Service | Where-Object {- $_.StartType -eq 'Automatic' -and+ $_.StartType -eq 'Automatic' -and$_.Status -eq 'Running' -and$_.ServiceName -notmatch '^(Win|Dhcp|Dns|W3SVC|MSSQL|SQL)'})-+if ($suspiciousServices.Count -gt 50) {$result.Findings += [PSCustomObject]@{Severity = 'Low'@@ -182,7 +354,7 @@ function Invoke-EnterpriseSecurityScan {}}}-+# Comprehensive scan additionsif ($ScanType -eq 'Comprehensive') {# Check event logs@@ -191,9 +363,9 @@ function Invoke-EnterpriseSecurityScan {Level = 2StartTime = (Get-Date).AddDays(-1)} -MaxEvents 100 -ErrorAction SilentlyContinue)-+$result.Details.RecentErrors = $recentErrors.Count-+# Check disk space$drives = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=3"foreach ($drive in $drives) {@@ -209,10 +381,10 @@ function Invoke-EnterpriseSecurityScan {}}}-+# Calculate final score$result.SecurityScore = [Math]::Min($result.SecurityScore, 100)-+}catch {$result.Status = 'Error'@@ -222,41 +394,308 @@ function Invoke-EnterpriseSecurityScan {Finding = $_.Exception.Message}}-++ return $result+ }++ # Worker for one host: deploy the module over a PS session, run the selected module+ # functions remotely, and remove the remote temp directory on every path+ $moduleWorker = {+ param($Computer, $Cred, [bool]$HasCredential, $ZipPath, $ZipFileName, [string[]]$FunctionNames)++ $result = [PSCustomObject]@{+ ComputerName = $Computer+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ Status = 'Success'+ SecurityScore = 0+ Findings = @()+ Details = @{}+ }++ $session = $null+ $remoteTempDir = $null+ try {+ $sessionParams = @{ ComputerName = $Computer; ErrorAction = 'Stop' }+ if ($HasCredential) { $sessionParams['Credential'] = $Cred }+ $session = New-PSSession @sessionParams++ $remoteTempDir = Invoke-Command -Session $session -ErrorAction Stop -ScriptBlock {+ $dir = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath ("WSA_Scan_" + [guid]::NewGuid().ToString('N'))+ New-Item -Path $dir -ItemType Directory -Force | Out-Null+ $dir+ }++ # Never feed a host-supplied path straight into Copy-Item or Remove-Item:+ # only accept the exact temp shape this script asked the host to create+ if ($remoteTempDir -isnot [string] -or $remoteTempDir -notmatch 'WSA_Scan_[0-9a-fA-F]{32}$') {+ $remoteTempDir = $null+ throw "Remote host returned an unexpected temp path; aborting deployment before any copy or cleanup runs."+ }++ Copy-Item -Path $ZipPath -Destination $remoteTempDir -ToSession $session -Force -ErrorAction Stop++ $remoteResult = Invoke-Command -Session $session -ErrorAction Stop -ScriptBlock {+ param($TempDir, $ZipFileName, $FunctionNames)++ $runOutput = [PSCustomObject]@{ Results = [ordered]@{}; Errors = @() }+ try {+ $zipFile = Join-Path -Path $TempDir -ChildPath $ZipFileName+ $extractDir = Join-Path -Path $TempDir -ChildPath 'Module'+ Expand-Archive -Path $zipFile -DestinationPath $extractDir -Force -ErrorAction Stop++ $manifest = @(Get-ChildItem -Path $extractDir -Filter '*.psd1' -Recurse -File | Select-Object -First 1)+ $rootModule = @(Get-ChildItem -Path $extractDir -Filter '*.psm1' -Recurse -File | Select-Object -First 1)+ $importTarget = $null+ if ($manifest.Count -gt 0) { $importTarget = $manifest[0].FullName }+ elseif ($rootModule.Count -gt 0) { $importTarget = $rootModule[0].FullName }+ if ($null -eq $importTarget) { throw "No .psd1 or .psm1 found in the deployed module archive" }++ Import-Module $importTarget -Force -ErrorAction Stop++ foreach ($functionName in $FunctionNames) {+ try {+ $runOutput.Results[$functionName] = & $functionName+ }+ catch {+ $runOutput.Errors += ("{0}: {1}" -f $functionName, $_.Exception.Message)+ }+ }+ }+ finally {+ Remove-Item -Path $TempDir -Recurse -Force -ErrorAction SilentlyContinue+ }+ return $runOutput+ } -ArgumentList $remoteTempDir, $ZipFileName, $FunctionNames++ $moduleResults = $null+ $functionErrors = @()+ if ($null -ne $remoteResult) {+ if ($null -ne $remoteResult.PSObject.Properties['Results']) { $moduleResults = $remoteResult.Results }+ if ($null -ne $remoteResult.PSObject.Properties['Errors'] -and $null -ne $remoteResult.Errors) { $functionErrors = @($remoteResult.Errors) }+ }++ $result.Details.ModuleDeployed = $true+ $result.Details.RemoteFunctionSet = ($FunctionNames -join ', ')+ $result.Details.ModuleResults = $moduleResults+ $result.Details.FunctionErrors = $functionErrors+ $result.Details.SecurityScoreNote = 'SecurityScore applies only to the built-in native-cmdlet scan; module function output is returned verbatim under Details.ModuleResults'++ # Heuristic roll-up: merge any Findings collections emitted by the module+ # functions and tag them with the source function name+ if ($null -ne $moduleResults) {+ foreach ($functionName in $FunctionNames) {+ $functionResult = $null+ if ($moduleResults -is [System.Collections.IDictionary]) {+ $functionResult = $moduleResults[$functionName]+ }+ elseif ($null -ne $moduleResults.PSObject.Properties[$functionName]) {+ $functionResult = $moduleResults.PSObject.Properties[$functionName].Value+ }+ if ($null -eq $functionResult) { continue }+ $findingsProperty = $functionResult.PSObject.Properties['Findings']+ if ($null -eq $findingsProperty -or $null -eq $findingsProperty.Value) { continue }+ foreach ($finding in @($findingsProperty.Value)) {+ if ($null -eq $finding) { continue }+ $severityValue = 'Informational'+ if ($null -ne $finding.PSObject.Properties['Severity'] -and -not [string]::IsNullOrEmpty("$($finding.Severity)")) {+ $severityValue = "$($finding.Severity)"+ }+ $categoryValue = $functionName+ if ($null -ne $finding.PSObject.Properties['Category'] -and -not [string]::IsNullOrEmpty("$($finding.Category)")) {+ $categoryValue = "$($finding.Category)"+ }+ $findingText = ($finding | Out-String).Trim()+ if ($null -ne $finding.PSObject.Properties['Finding'] -and -not [string]::IsNullOrEmpty("$($finding.Finding)")) {+ $findingText = "$($finding.Finding)"+ }+ $result.Findings += [PSCustomObject]@{+ Severity = $severityValue+ Category = $categoryValue+ Finding = $findingText+ }+ }+ }+ }+ }+ catch {+ $result.Status = 'Failed'+ $result.Details.Error = $_.Exception.Message+ $result.Findings += [PSCustomObject]@{+ Severity = 'Critical'+ Category = 'Connection'+ Finding = $_.Exception.Message+ }+ }+ finally {+ if ($null -ne $session) {+ if (-not [string]::IsNullOrEmpty($remoteTempDir)) {+ try {+ $null = Invoke-Command -Session $session -ErrorAction SilentlyContinue -ScriptBlock {+ param($Dir)+ Remove-Item -Path $Dir -Recurse -Force -ErrorAction SilentlyContinue+ } -ArgumentList $remoteTempDir+ }+ catch {+ Write-Verbose "Remote cleanup invocation failed for ${Computer}: $_"+ }+ }+ Remove-PSSession $session+ }+ }+return $result}}-+process {$runspacePool = $null$jobs = @()+ $probeJobs = @()try {- Write-Host "`nStarting parallel scan of $($ComputerName.Count) systems..." -ForegroundColor Cyan-- # Create runspace pool for parallel execution- $runspacePool = [runspacefactory]::CreateRunspacePool(1, $MaxThreads)+ Write-Host "`nStarting parallel scan of $($targetComputers.Count) systems..." -ForegroundColor Cyan++ # Propagate caller-defined function overrides (for example test doubles) for the+ # remoting cmdlets into the pool runspaces; in normal operation these commands are+ # cmdlets and nothing is propagated+ $shadowedCommands = @()+ foreach ($commandName in @('Test-Connection', 'New-PSSession', 'Copy-Item', 'Invoke-Command', 'Remove-PSSession')) {+ $functionCommand = @(Get-Command -Name $commandName -CommandType Function -ErrorAction SilentlyContinue | Select-Object -First 1)+ if ($functionCommand.Count -gt 0) { $shadowedCommands += $functionCommand[0] }+ }++ if ($shadowedCommands.Count -gt 0) {+ $initialState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()+ foreach ($functionCommand in $shadowedCommands) {+ $initialState.Commands.Add((New-Object System.Management.Automation.Runspaces.SessionStateFunctionEntry($functionCommand.Name, $functionCommand.ScriptBlock)))+ }+ $runspacePool = [runspacefactory]::CreateRunspacePool(1, $MaxThreads, $initialState, $Host)+ }+ else {+ $runspacePool = [runspacefactory]::CreateRunspacePool(1, $MaxThreads)+ }$runspacePool.Open()-- foreach ($computer in $ComputerName) {- Write-Verbose "Queuing scan for: $computer"-- # Test connectivity first- $pingTest = Test-Connection -ComputerName $computer -Count 1 -Quiet -ErrorAction SilentlyContinue-- if (-not $pingTest) {- Write-Warning "Cannot reach $computer - skipping"- $results.FailedSystems += [PSCustomObject]@{- ComputerName = $computer- Reason = 'Unreachable'++ # Phase 1: parallel connectivity probe for every target before any scan job is queued+ $reachableHosts = @()+ $probeApproved = $true+ if ($UseModuleFunctions) {+ $probeApproved = $PSCmdlet.ShouldProcess(($targetComputers -join ', '), "Probe connectivity with ${ProbeTimeoutSec}s per-host timeout")+ }++ if ($probeApproved) {+ Write-Host "Probing connectivity ($ProbeTimeoutSec s per-host timeout)..." -ForegroundColor Yellow++ foreach ($computer in $targetComputers) {+ Write-Verbose "Queuing connectivity probe for: $computer"+ $probe = [powershell]::Create()+ $probe.RunspacePool = $runspacePool+ $probe.AddScript({+ param($Computer)+ Test-Connection -ComputerName $Computer -Count 1 -Quiet -ErrorAction SilentlyContinue+ }).AddArgument($computer) | Out-Null++ $probeJobs += [PSCustomObject]@{+ Computer = $computer+ Pipeline = $probe+ Status = $probe.BeginInvoke()+ StartTime = Get-Date+ }+ }++ $pendingProbes = @($probeJobs)+ while ($pendingProbes.Count -gt 0) {+ $stillPending = @()+ foreach ($probeJob in $pendingProbes) {+ if ($probeJob.Status.IsCompleted) {+ $isReachable = $false+ try {+ $isReachable = @($probeJob.Pipeline.EndInvoke($probeJob.Status))[0]+ }+ catch {+ Write-Verbose "Probe failed for $($probeJob.Computer): $_"+ $isReachable = $false+ }+ $probeJob.Pipeline.Dispose()+ $probeJob.Pipeline = $null++ if ($true -eq $isReachable) {+ $reachableHosts += $probeJob.Computer+ }+ else {+ Write-Warning "Cannot reach $($probeJob.Computer) - skipping"+ $results.FailedSystems += [PSCustomObject]@{+ ComputerName = $probeJob.Computer+ Reason = 'Unreachable'+ }+ $results.Summary.Failed+++ }+ }+ elseif (((Get-Date) - $probeJob.StartTime).TotalSeconds -gt $ProbeTimeoutSec) {+ try { $probeJob.Pipeline.Stop() } catch { Write-Verbose "Probe stop failed for $($probeJob.Computer): $_" }+ $probeJob.Pipeline.Dispose()+ $probeJob.Pipeline = $null+ Write-Warning "Connectivity probe timed out for $($probeJob.Computer) - skipping"+ $results.FailedSystems += [PSCustomObject]@{+ ComputerName = $probeJob.Computer+ Reason = "Unreachable (probe timeout after $ProbeTimeoutSec s)"+ }+ $results.Summary.Failed+++ }+ else {+ $stillPending += $probeJob+ }+ }+ if ($stillPending.Count -gt 0) { Start-Sleep -Milliseconds 100 }+ $pendingProbes = $stillPending+ }+ }+ else {+ $reachableHosts = $targetComputers+ }++ # Phase 2: queue one scan job per reachable host+ foreach ($computer in $reachableHosts) {+ if ($UseModuleFunctions) {+ if (-not $PSCmdlet.ShouldProcess($computer, "Deploy WindowsSecurityAudit module and run '$RemoteFunctionSet' function set ($($remoteFunctions -join ', '))")) {+ $results.SystemResults += [PSCustomObject]@{+ ComputerName = $computer+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ Status = 'WhatIf'+ SecurityScore = 0+ Findings = @()+ Details = @{+ PlannedAction = "Deploy module archive and run '$RemoteFunctionSet' function set"+ Functions = ($remoteFunctions -join ', ')+ }+ }+ continue+ }+ Write-Verbose "Queuing module deployment scan for: $computer"+ $powershell = [powershell]::Create()+ $powershell.RunspacePool = $runspacePool+ $powershell.AddScript($moduleWorker).+ AddArgument($computer).+ AddArgument($Credential).+ AddArgument(($null -ne $Credential)).+ AddArgument($zipPath).+ AddArgument($zipLeafName).+ AddArgument([string[]]$remoteFunctions) | Out-Null++ $jobs += [PSCustomObject]@{+ Computer = $computer+ Pipeline = $powershell+ Status = $powershell.BeginInvoke()+ StartTime = Get-Date}- $results.Summary.Failed++continue}-++ Write-Verbose "Queuing scan for: $computer"+# Create PowerShell instance$powershell = [powershell]::Create()$powershell.RunspacePool = $runspacePool-+# Add script and parametersif ($Credential) {$powershell.AddScript({@@ -298,74 +737,119 @@ function Invoke-EnterpriseSecurityScan {}}).AddArgument($computer).AddArgument($scanScriptBlock).AddArgument($ScanType) | Out-Null}-+# Start async execution$jobs += [PSCustomObject]@{Computer = $computerPipeline = $powershellStatus = $powershell.BeginInvoke()+ StartTime = Get-Date}}-- # Wait for all jobs to complete++ # Collect results as jobs complete, enforcing the per-host execution timeoutWrite-Host "Scanning in progress..." -ForegroundColor Yellow$completed = 0$totalJobs = @($jobs).Count-- while (@($jobs | Where-Object { -not $_.Status.IsCompleted }).Count -gt 0) {- $completedNow = @($jobs | Where-Object { $_.Status.IsCompleted }).Count- if ($completedNow -ne $completed) {- $completed = $completedNow- if ($totalJobs -gt 0) {- Write-Progress -Activity "Enterprise Security Scan" -Status "Completed: $completed / $totalJobs" -PercentComplete (($completed / $totalJobs) * 100)- }- }- Start-Sleep -Milliseconds 500- }-- Write-Progress -Activity "Enterprise Security Scan" -Completed-- # Collect results- Write-Host "Collecting results..." -ForegroundColor Yellow-- foreach ($job in $jobs) {- try {- $result = @($job.Pipeline.EndInvoke($job.Status))[0]-- if ($result.Status -eq 'Success') {- $results.Summary.Successful++-- # Count findings by severity- foreach ($finding in $result.Findings) {- switch ($finding.Severity) {- 'Critical' { $results.Summary.CriticalFindings++ }- 'High' { $results.Summary.HighFindings++ }- 'Medium' { $results.Summary.MediumFindings++ }- 'Low' { $results.Summary.LowFindings++ }+ $pendingJobs = @($jobs)++ while ($pendingJobs.Count -gt 0) {+ $stillPending = @()+ foreach ($job in $pendingJobs) {+ if ($job.Status.IsCompleted) {+ try {+ $result = @(@($job.Pipeline.EndInvoke($job.Status)) | Where-Object { $null -ne $_ } | Select-Object -Last 1)+ if ($result.Count -gt 0) { $result = $result[0] } else { $result = $null }++ if ($null -eq $result) {+ $results.Summary.Failed+++ $results.FailedSystems += [PSCustomObject]@{+ ComputerName = $job.Computer+ Reason = 'No result returned'+ }}+ else {+ $statusValue = 'Failed'+ if ($null -ne $result.PSObject.Properties['Status'] -and -not [string]::IsNullOrEmpty("$($result.Status)")) {+ $statusValue = "$($result.Status)"+ }++ if ($statusValue -eq 'Success') {+ $results.Summary.Successful++++ # Count findings by severity+ $findingsProperty = $result.PSObject.Properties['Findings']+ if ($null -ne $findingsProperty -and $null -ne $findingsProperty.Value) {+ foreach ($finding in @($findingsProperty.Value)) {+ if ($null -eq $finding -or $null -eq $finding.PSObject.Properties['Severity']) { continue }+ switch ("$($finding.Severity)") {+ 'Critical' { $results.Summary.CriticalFindings++ }+ 'High' { $results.Summary.HighFindings++ }+ 'Medium' { $results.Summary.MediumFindings++ }+ 'Low' { $results.Summary.LowFindings++ }+ }+ }+ }+ }+ else {+ $results.Summary.Failed+++ $results.FailedSystems += [PSCustomObject]@{+ ComputerName = $job.Computer+ Reason = 'Scan failed'+ }+ }++ $results.SystemResults += $result+ }+ }+ catch {+ Write-Warning "Error collecting results from $($job.Computer): $_"+ $results.Summary.Failed++}+ finally {+ $job.Pipeline.Dispose()+ $job.Pipeline = $null+ }+ $completed++}- else {+ elseif (((Get-Date) - $job.StartTime).TotalSeconds -gt $HostTimeoutSec) {+ try { $job.Pipeline.Stop() } catch { Write-Verbose "Stop failed for $($job.Computer): $_" }+ $job.Pipeline.Dispose()+ $job.Pipeline = $null++ Write-Warning "Scan of $($job.Computer) timed out after $HostTimeoutSec seconds"$results.Summary.Failed+++ $results.Summary.TimedOut++$results.FailedSystems += [PSCustomObject]@{ComputerName = $job.Computer- Reason = 'Scan failed'+ Reason = "Timeout after $HostTimeoutSec seconds"}+ $results.SystemResults += [PSCustomObject]@{+ ComputerName = $job.Computer+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ Status = 'Timeout'+ SecurityScore = 0+ Findings = @()+ Details = @{ Error = "Host execution exceeded the $HostTimeoutSec second limit" }+ }+ $completed+++ }+ else {+ $stillPending += $job}-- $results.SystemResults += $result- }- catch {- Write-Warning "Error collecting results from $($job.Computer): $_"- $results.Summary.Failed++}- finally {- $job.Pipeline.Dispose()++ if ($totalJobs -gt 0) {+ Write-Progress -Activity "Enterprise Security Scan" -Status "Completed: $completed / $totalJobs" -PercentComplete (($completed / $totalJobs) * 100)}+ if ($stillPending.Count -gt 0) { Start-Sleep -Milliseconds 500 }+ $pendingJobs = $stillPending}-++ Write-Progress -Activity "Enterprise Security Scan" -Completed+# Runspace pool is closed/disposed in the finally block below-+}catch {Write-Error "Error during enterprise scan: $_"@@ -373,7 +857,7 @@ function Invoke-EnterpriseSecurityScan {}finally {# Guarantee cleanup of async pipelines and the runspace pool, even on failure- foreach ($job in $jobs) {+ foreach ($job in @($jobs) + @($probeJobs)) {if ($null -ne $job.Pipeline) {$job.Pipeline.Dispose()}@@ -384,40 +868,48 @@ function Invoke-EnterpriseSecurityScan {}$runspacePool.Dispose()}+ if (-not [string]::IsNullOrEmpty($zipPath) -and (Test-Path -Path $zipPath -PathType Leaf)) {+ Remove-Item -Path $zipPath -Force -ErrorAction SilentlyContinue+ }}}-+end {# Generate summary reportWrite-Host "`n=== SCAN COMPLETE ===" -ForegroundColor GreenWrite-Host "Total Systems: $($results.TotalSystems)" -ForegroundColor CyanWrite-Host "Successful: $($results.Summary.Successful)" -ForegroundColor GreenWrite-Host "Failed: $($results.Summary.Failed)" -ForegroundColor Red+ if ($results.Summary.TimedOut -gt 0) {+ Write-Host "Timed Out: $($results.Summary.TimedOut)" -ForegroundColor Red+ }Write-Host "`nFindings Summary:" -ForegroundColor CyanWrite-Host " Critical: $($results.Summary.CriticalFindings)" -ForegroundColor RedWrite-Host " High: $($results.Summary.HighFindings)" -ForegroundColor YellowWrite-Host " Medium: $($results.Summary.MediumFindings)" -ForegroundColor YellowWrite-Host " Low: $($results.Summary.LowFindings)" -ForegroundColor White-+# Save results- $results | ConvertTo-Json -Depth 10 | Out-File (Join-Path $OutputPath "EnterpriseScan_Results.json")-- # Create CSV summary- $results.SystemResults | Select-Object ComputerName, Status, SecurityScore, @{N='FindingsCount';E={$_.Findings.Count}} |- Export-Csv (Join-Path $OutputPath "EnterpriseScan_Summary.csv") -NoTypeInformation-- # Export detailed findings- $allFindings = @($results.SystemResults | ForEach-Object {- $computer = $_.ComputerName- $_.Findings | Select-Object @{N='Computer';E={$computer}}, Severity, Category, Finding- })-- if ($allFindings.Count -gt 0) {- $allFindings | Export-Csv (Join-Path $OutputPath "EnterpriseScan_Findings.csv") -NoTypeInformation+ if ($PSCmdlet.ShouldProcess($OutputPath, 'Save enterprise scan results (JSON/CSV)')) {+ $results | ConvertTo-Json -Depth 10 | Out-File (Join-Path $OutputPath "EnterpriseScan_Results.json")++ # Create CSV summary+ $results.SystemResults | Select-Object ComputerName, Status, SecurityScore, @{N='FindingsCount';E={$_.Findings.Count}} |+ Export-Csv (Join-Path $OutputPath "EnterpriseScan_Summary.csv") -NoTypeInformation++ # Export detailed findings+ $allFindings = @($results.SystemResults | ForEach-Object {+ $computer = $_.ComputerName+ $_.Findings | Select-Object @{N='Computer';E={$computer}}, Severity, Category, Finding+ })++ if ($allFindings.Count -gt 0) {+ $allFindings | Export-Csv (Join-Path $OutputPath "EnterpriseScan_Findings.csv") -NoTypeInformation+ }++ Write-Host "`nResults saved to: $OutputPath" -ForegroundColor Cyan}-- Write-Host "`nResults saved to: $OutputPath" -ForegroundColor Cyan-+return $results}-}\ No newline at end of file+}diff --git a/Enterprise/Register-ScheduledSecurityScan.ps1 b/Enterprise/Register-ScheduledSecurityScan.ps1index 7e2c809..2afa10b 100644--- a/Enterprise/Register-ScheduledSecurityScan.ps1+++ b/Enterprise/Register-ScheduledSecurityScan.ps1@@ -9,6 +9,18 @@ function Register-ScheduledSecurityScan {findings are detected. The script is then registered as a Scheduled Taskrunning as SYSTEM at the chosen cadence (Daily, Weekly on Monday, orMonthly on the 1st). Use -Unregister to remove the scheduled task.+ The generated script embeds the webhook URL (a shared secret), so on+ Windows its file permissions are restricted to Administrators and SYSTEM.++ Alert deduplication is enabled by default: the generated script persists a+ stable SHA256 fingerprint (first 16 hex chars over Category + Finding text)+ of each finding to State\last-findings.json under the output path. On+ subsequent runs findings are classified as New, Persisting, or Resolved.+ An alarm is sent only for new Critical/High findings or persisting+ Critical/High findings older than -RealertAfterDays; a quiet resolved note+ (no alarm tone) is sent when findings disappear. The first run, a broken or+ missing state file, and -DisableAlertDedup all fall back to alerting on any+ Critical finding. State write failures never suppress alerts..PARAMETER ScanTypeType of scan to schedule: Quick, Standard, or Full (default: Standard).Mapped to Invoke-SecurityAssessment as Quick=Basic, Standard=Standard, Full=Advanced.@@ -28,6 +40,14 @@ function Register-ScheduledSecurityScan {Optional sender address for email alerts (requires EmailTo and SmtpServer).PARAMETER SmtpServerOptional SMTP server for email alerts (requires EmailTo and EmailFrom)+ .PARAMETER DisableAlertDedup+ Turns off alert deduplication in the generated scan script. With dedup+ disabled the script alerts on every run whenever a Critical finding+ exists (the pre-dedup behavior)+ .PARAMETER RealertAfterDays+ Number of days after which a persisting Critical/High finding (first seen+ this many days ago or more) triggers a repeat alert (default: 7, range+ 1-3650). Only used when alert deduplication is enabled.PARAMETER UnregisterRemoves the scheduled security scan task and exits without registering anything.PARAMETER WhatIf@@ -43,6 +63,9 @@ function Register-ScheduledSecurityScan {.EXAMPLERegister-ScheduledSecurityScan -ScanType Quick -Frequency Monthly -EmailTo [email protected] -EmailFrom [email protected] -SmtpServer smtp.contoso.comRegisters a monthly Quick scan that emails an alert when Critical findings exist+ .EXAMPLE+ Register-ScheduledSecurityScan -Frequency Daily -WebhookUrl 'https://outlook.office.com/webhook/...' -RealertAfterDays 14+ Registers a daily scan with alert deduplication (on by default) that re-alerts on Critical/High findings persisting for 14 days or more.EXAMPLERegister-ScheduledSecurityScan -Unregister -Confirm:$falseRemoves the scheduled security scan task@@ -78,6 +101,13 @@ function Register-ScheduledSecurityScan {[Parameter()][string]$SmtpServer,+ [Parameter()]+ [switch]$DisableAlertDedup,++ [Parameter()]+ [ValidateRange(1, 3650)]+ [int]$RealertAfterDays = 7,+[Parameter()][switch]$Unregister)@@ -112,6 +142,12 @@ function Register-ScheduledSecurityScan {}$webhookConfigured = (-not [string]::IsNullOrWhiteSpace($WebhookUrl))++ # Alert dedup is opt-out; the generated script embeds both values+ $alertDedupEnabled = (-not $DisableAlertDedup)+ if ($DisableAlertDedup -and $PSBoundParameters.ContainsKey('RealertAfterDays')) {+ Write-Warning "RealertAfterDays is ignored because alert deduplication is disabled."+ }}process {@@ -169,6 +205,7 @@ function Register-ScheduledSecurityScan {Write-Host "Output Path: $OutputPath" -ForegroundColor YellowWrite-Host "Webhook Alerts: $webhookConfigured" -ForegroundColor YellowWrite-Host "Email Alerts: $emailConfigured" -ForegroundColor Yellow+ Write-Host "Alert Dedup: $(if ($alertDedupEnabled) { "True (re-alert after $RealertAfterDays days)" } else { 'False' })" -ForegroundColor Yellow$scriptPath = Join-Path $OutputPath 'Invoke-ScheduledSecurityScan.ps1'@@ -179,6 +216,8 @@ function Register-ScheduledSecurityScan {$safeEmailTo = if ($emailConfigured) { $EmailTo -replace "'", "''" } else { '' }$safeEmailFrom = if ($emailConfigured) { $EmailFrom -replace "'", "''" } else { '' }$safeSmtpServer = if ($emailConfigured) { $SmtpServer -replace "'", "''" } else { '' }+ $safeAlertDedup = if ($alertDedupEnabled) { '$true' } else { '$false' }+ $safeRealertAfterDays = "$RealertAfterDays"$scanScriptTemplate = @'# ============================================================================@@ -190,17 +229,43 @@ function Register-ScheduledSecurityScan {$ErrorActionPreference = 'Continue'-$modulePath = '__MODULE_PATH__'-$scanOutputRoot = '__OUTPUT_PATH__'-$assessmentType = '__ASSESSMENT_TYPE__'-$webhookUrl = '__WEBHOOK_URL__'-$emailTo = '__EMAIL_TO__'-$emailFrom = '__EMAIL_FROM__'-$smtpServer = '__SMTP_SERVER__'+try {+ [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12+}+catch {+ Write-Verbose "Could not enforce TLS 1.2: $_"+}++$modulePath = '__MODULE_PATH__'+$scanOutputRoot = '__OUTPUT_PATH__'+$assessmentType = '__ASSESSMENT_TYPE__'+$webhookUrl = '__WEBHOOK_URL__'+$emailTo = '__EMAIL_TO__'+$emailFrom = '__EMAIL_FROM__'+$smtpServer = '__SMTP_SERVER__'+$alertDedup = __ALERT_DEDUP__+$realertAfterDays = __REALERT_AFTER_DAYS__$runStamp = Get-Date -Format 'yyyyMMdd_HHmmss'$runPath = Join-Path $scanOutputRoot "Scan_$runStamp"+# Stable fingerprint of a finding: first 16 hex chars of SHA256 over Category + Finding text+function Get-FindingFingerprint {+ param(+ [string]$Category,+ [string]$Finding+ )++ $sha256 = [System.Security.Cryptography.SHA256]::Create()+ try {+ $hashBytes = $sha256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes("$Category`n$Finding"))+ return (([System.BitConverter]::ToString($hashBytes)) -replace '-', '').Substring(0, 16).ToLowerInvariant()+ }+ finally {+ $sha256.Dispose()+ }+}+try {if (-not (Test-Path $runPath)) {New-Item -Path $runPath -ItemType Directory -Force | Out-Null@@ -223,23 +288,152 @@ try {$overallScore = "$($assessment.OverallScore)"}+ $runNow = Get-Date+ $runStampText = $runNow.ToString('yyyy-MM-dd HH:mm:ss')++ # Fingerprint the current findings (first occurrence wins for duplicates)+ $currentFingerprints = @{}+ foreach ($finding in $findings) {+ $fCat = ''+ $fTxt = ''+ $fSev = ''+ if ($null -ne $finding.PSObject.Properties['Category']) { $fCat = "$($finding.Category)" }+ if ($null -ne $finding.PSObject.Properties['Finding']) { $fTxt = "$($finding.Finding)" }+ if ($null -ne $finding.PSObject.Properties['Severity']) { $fSev = "$($finding.Severity)" }+ $fingerprint = Get-FindingFingerprint -Category $fCat -Finding $fTxt+ if (-not $currentFingerprints.ContainsKey($fingerprint)) {+ $currentFingerprints[$fingerprint] = [PSCustomObject]@{+ Fingerprint = $fingerprint+ Category = $fCat+ Finding = $fTxt+ Severity = $fSev+ }+ }+ }++ # Load the previous dedup state; a missing or broken state degrades to normal alerting+ $stateDir = Join-Path $scanOutputRoot 'State'+ $stateFile = Join-Path $stateDir 'last-findings.json'+ $previousState = @{}+ $stateLoaded = $false++ if ($alertDedup -and (Test-Path $stateFile)) {+ try {+ $parsedState = Get-Content -Path $stateFile -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop+ if ($null -eq $parsedState -or $null -eq $parsedState.PSObject.Properties['Findings'] -or $null -eq $parsedState.Findings) {+ Write-Warning "Alert dedup state file '$stateFile' has no findings data. Alerting without dedup for this run."+ }+ else {+ foreach ($stateEntry in @($parsedState.Findings)) {+ if ($null -eq $stateEntry.PSObject.Properties['Fingerprint'] -or [string]::IsNullOrWhiteSpace("$($stateEntry.Fingerprint)")) { continue }+ $sCat = ''+ $sTxt = ''+ $sSev = ''+ $sFirstSeen = $null+ if ($null -ne $stateEntry.PSObject.Properties['Category']) { $sCat = "$($stateEntry.Category)" }+ if ($null -ne $stateEntry.PSObject.Properties['Finding']) { $sTxt = "$($stateEntry.Finding)" }+ if ($null -ne $stateEntry.PSObject.Properties['Severity']) { $sSev = "$($stateEntry.Severity)" }+ if ($null -ne $stateEntry.PSObject.Properties['FirstSeen'] -and -not [string]::IsNullOrWhiteSpace("$($stateEntry.FirstSeen)")) {+ $parsedDate = [datetime]::MinValue+ if ([datetime]::TryParseExact("$($stateEntry.FirstSeen)", 'yyyy-MM-dd HH:mm:ss', [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref]$parsedDate)) {+ $sFirstSeen = $parsedDate+ }+ }+ $previousState["$($stateEntry.Fingerprint)"] = [PSCustomObject]@{+ Fingerprint = "$($stateEntry.Fingerprint)"+ Category = $sCat+ Finding = $sTxt+ Severity = $sSev+ FirstSeen = $sFirstSeen+ }+ }+ $stateLoaded = $true+ }+ }+ catch {+ Write-Warning "Could not load alert dedup state file '$stateFile': $($_.Exception.Message). Alerting without dedup for this run."+ }+ }++ # Classify current findings against the previous state+ $newFindings = @()+ $persistingFindings = @()+ $resolvedFindings = @()++ if ($alertDedup) {+ foreach ($fingerprint in @($currentFingerprints.Keys)) {+ if ($stateLoaded -and $previousState.ContainsKey($fingerprint)) {+ $persistingFindings += [PSCustomObject]@{+ Fingerprint = $fingerprint+ Category = $currentFingerprints[$fingerprint].Category+ Finding = $currentFingerprints[$fingerprint].Finding+ Severity = $currentFingerprints[$fingerprint].Severity+ FirstSeen = $previousState[$fingerprint].FirstSeen+ }+ }+ else {+ $newFindings += $currentFingerprints[$fingerprint]+ }+ }+ if ($stateLoaded) {+ foreach ($fingerprint in @($previousState.Keys)) {+ if (-not $currentFingerprints.ContainsKey($fingerprint)) {+ $resolvedFindings += $previousState[$fingerprint]+ }+ }+ }+ }++ # Decide whether and how to alert+ $alertFindings = @()+ $alertReason = 'None'++ if ($alertDedup -and $stateLoaded) {+ $newAlerts = @($newFindings | Where-Object { $_.Severity -eq 'Critical' -or $_.Severity -eq 'High' })+ $realerts = @($persistingFindings | Where-Object {+ if ($_.Severity -ne 'Critical' -and $_.Severity -ne 'High') { return $false }+ if ($null -eq $_.FirstSeen) { return $true }+ return (($runNow - $_.FirstSeen).TotalDays -ge $realertAfterDays)+ })+ $alertFindings = @($newAlerts) + @($realerts)+ if ($alertFindings.Count -gt 0) {+ $alertReason = 'Alarm'+ }+ elseif ($resolvedFindings.Count -gt 0) {+ $alertReason = 'Resolved'+ }+ }+ else {+ # First run, dedup disabled, or unreadable state: alert on any Critical finding+ $alertFindings = $criticalFindings+ if ($criticalFindings.Count -gt 0) {+ $alertReason = 'Alarm'+ }+ }+$runSummary = [PSCustomObject]@{ComputerName = $env:COMPUTERNAME- RunDate = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'+ RunDate = $runStampTextAssessmentType = $assessmentTypeOverallScore = $overallScoreTotalFindings = $findings.CountCriticalFindings = $criticalFindings.CountHighFindings = $highFindings.Count+ NewFindings = $newFindings.Count+ PersistingFindings = $persistingFindings.Count+ ResolvedFindings = $resolvedFindings.Count+ AlertDedup = $alertDedup+ RealertAfterDays = $realertAfterDays+ AlertReason = $alertReasonReportPath = $runPathAlertSent = $false}- if ($criticalFindings.Count -gt 0) {+ if ($alertReason -eq 'Alarm') {# ---------- Webhook alert (Teams/Slack-style incoming webhook) ----------if (-not [string]::IsNullOrWhiteSpace($webhookUrl)) {try {- $factBlocks = @($criticalFindings | ForEach-Object {+ $factBlocks = @($alertFindings | ForEach-Object {$cat = ''$txt = ''if ($null -ne $_.PSObject.Properties['Category']) { $cat = "$($_.Category)" }@@ -247,6 +441,20 @@ try {@{ title = $cat; value = $txt }})+ $alertFacts = @(+ @{ title = 'Computer'; value = "$env:COMPUTERNAME" }+ @{ title = 'Scan Time'; value = $runStampText }+ @{ title = 'Overall Score'; value = $overallScore }+ @{ title = 'Critical'; value = "$($criticalFindings.Count)" }+ @{ title = 'High'; value = "$($highFindings.Count)" }+ @{ title = 'Report'; value = "$runPath" }+ )+ if ($alertDedup) {+ $alertFacts += @{ title = 'Since Last Run: New'; value = "$($newFindings.Count)" }+ $alertFacts += @{ title = 'Since Last Run: Persisting'; value = "$($persistingFindings.Count)" }+ $alertFacts += @{ title = 'Since Last Run: Resolved'; value = "$($resolvedFindings.Count)" }+ }+$payload = @{type = 'message'attachments = @(@@ -258,15 +466,8 @@ try {version = '1.2'body = @(@{ type = 'TextBlock'; size = 'Large'; weight = 'Bolder'; color = 'Attention'; text = "CRITICAL Security Findings - $env:COMPUTERNAME" }- @{ type = 'TextBlock'; text = "Scheduled $assessmentType security scan completed with $($criticalFindings.Count) critical finding(s)."; wrap = $true }- @{ type = 'FactSet'; facts = @(- @{ title = 'Computer'; value = "$env:COMPUTERNAME" }- @{ title = 'Scan Time'; value = (Get-Date -Format 'yyyy-MM-dd HH:mm:ss') }- @{ title = 'Overall Score'; value = $overallScore }- @{ title = 'Critical'; value = "$($criticalFindings.Count)" }- @{ title = 'High'; value = "$($highFindings.Count)" }- @{ title = 'Report'; value = "$runPath" }- ) + $factBlocks }+ @{ type = 'TextBlock'; text = "Scheduled $assessmentType security scan completed with $($alertFindings.Count) critical/high finding(s) requiring attention."; wrap = $true }+ @{ type = 'FactSet'; facts = @($alertFacts) + $factBlocks }@{ type = 'TextBlock'; text = 'Review the full report and remediate the critical findings as soon as possible.'; wrap = $true })}@@ -286,7 +487,7 @@ try {# ---------- Email alert ----------if (-not [string]::IsNullOrWhiteSpace($emailTo) -and -not [string]::IsNullOrWhiteSpace($emailFrom) -and -not [string]::IsNullOrWhiteSpace($smtpServer)) {try {- $mailRows = ($criticalFindings | ForEach-Object {+ $mailRows = ($alertFindings | ForEach-Object {$cat = ''$txt = ''if ($null -ne $_.PSObject.Properties['Category']) { $cat = "$($_.Category)" }@@ -294,10 +495,16 @@ try {"<tr><td style='padding:6px;border:1px solid #ccc;'>$cat</td><td style='padding:6px;border:1px solid #ccc;'>$txt</td></tr>"}) -join "`n"+ $dedupSummaryHtml = ''+ if ($alertDedup) {+ $dedupSummaryHtml = "<p>Since last run: <b>$($newFindings.Count)</b> new, <b>$($persistingFindings.Count)</b> persisting, <b>$($resolvedFindings.Count)</b> resolved finding(s).</p>"+ }+$mailBody = @"<html><body style='font-family:Arial;'><h2 style='color:#c00;'>Critical Security Findings - $env:COMPUTERNAME</h2>-<p>Scheduled <b>$assessmentType</b> scan on <b>$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')</b> found <b>$($criticalFindings.Count)</b> critical and <b>$($highFindings.Count)</b> high finding(s). Overall score: <b>$overallScore</b>.</p>+<p>Scheduled <b>$assessmentType</b> scan on <b>$runStampText</b> found <b>$($criticalFindings.Count)</b> critical and <b>$($highFindings.Count)</b> high finding(s). Overall score: <b>$overallScore</b>.</p>+$dedupSummaryHtml<table style='border-collapse:collapse;'><tr><th style='padding:6px;border:1px solid #ccc;background:#333;color:#fff;'>Category</th><th style='padding:6px;border:1px solid #ccc;background:#333;color:#fff;'>Finding</th></tr>$mailRows@@ -306,7 +513,80 @@ $mailRows</body></html>"@- Send-MailMessage -To $emailTo -From $emailFrom -SmtpServer $smtpServer -Subject "[SECURITY ALERT] $($criticalFindings.Count) critical finding(s) on $env:COMPUTERNAME" -Body $mailBody -BodyAsHtml -Encoding UTF8 -ErrorAction Stop+ Send-MailMessage -To $emailTo -From $emailFrom -SmtpServer $smtpServer -Subject "[SECURITY ALERT] $($alertFindings.Count) critical/high finding(s) on $env:COMPUTERNAME" -Body $mailBody -BodyAsHtml -Encoding UTF8 -ErrorAction Stop+ $runSummary.AlertSent = $true+ }+ catch {+ Write-Warning "Failed to send email alert: $($_.Exception.Message)"+ }+ }+ }+ elseif ($alertReason -eq 'Resolved') {+ # ---------- Resolved note (informational, no alarm tone) ----------+ if (-not [string]::IsNullOrWhiteSpace($webhookUrl)) {+ try {+ $resolvedFacts = @(+ @{ title = 'Computer'; value = "$env:COMPUTERNAME" }+ @{ title = 'Scan Time'; value = $runStampText }+ @{ title = 'Overall Score'; value = $overallScore }+ @{ title = 'Since Last Run: New'; value = "$($newFindings.Count)" }+ @{ title = 'Since Last Run: Persisting'; value = "$($persistingFindings.Count)" }+ @{ title = 'Since Last Run: Resolved'; value = "$($resolvedFindings.Count)" }+ @{ title = 'Report'; value = "$runPath" }+ )++ $payload = @{+ type = 'message'+ attachments = @(+ @{+ contentType = 'application/vnd.microsoft.card.adaptive'+ content = @{+ '$schema' = 'http://adaptivecards.io/schemas/adaptive-card.json'+ type = 'AdaptiveCard'+ version = '1.2'+ body = @(+ @{ type = 'TextBlock'; size = 'Large'; weight = 'Bolder'; color = 'Good'; text = "Security Findings Resolved - $env:COMPUTERNAME" }+ @{ type = 'TextBlock'; text = "Scheduled $assessmentType security scan: $($resolvedFindings.Count) finding(s) resolved since the last run. No new critical or high findings."; wrap = $true }+ @{ type = 'FactSet'; facts = $resolvedFacts }+ )+ }+ }+ )+ }++ $jsonBody = $payload | ConvertTo-Json -Depth 12+ Invoke-RestMethod -Uri $webhookUrl -Method Post -Body $jsonBody -ContentType 'application/json; charset=utf-8' -ErrorAction Stop+ $runSummary.AlertSent = $true+ }+ catch {+ Write-Warning "Failed to send webhook alert: $($_.Exception.Message)"+ }+ }++ if (-not [string]::IsNullOrWhiteSpace($emailTo) -and -not [string]::IsNullOrWhiteSpace($emailFrom) -and -not [string]::IsNullOrWhiteSpace($smtpServer)) {+ try {+ $resolvedRows = ($resolvedFindings | ForEach-Object {+ $cat = ''+ $txt = ''+ if ($null -ne $_.PSObject.Properties['Category']) { $cat = "$($_.Category)" }+ if ($null -ne $_.PSObject.Properties['Finding']) { $txt = "$($_.Finding)" }+ "<tr><td style='padding:6px;border:1px solid #ccc;'>$cat</td><td style='padding:6px;border:1px solid #ccc;'>$txt</td></tr>"+ }) -join "`n"++ $mailBody = @"+<html><body style='font-family:Arial;'>+<h2 style='color:#080;'>Security Findings Resolved - $env:COMPUTERNAME</h2>+<p>Scheduled <b>$assessmentType</b> scan on <b>$runStampText</b>: <b>$($resolvedFindings.Count)</b> finding(s) resolved since the last run. No new critical or high findings. Overall score: <b>$overallScore</b>.</p>+<p>Since last run: <b>$($newFindings.Count)</b> new, <b>$($persistingFindings.Count)</b> persisting, <b>$($resolvedFindings.Count)</b> resolved finding(s).</p>+<table style='border-collapse:collapse;'>+<tr><th style='padding:6px;border:1px solid #ccc;background:#333;color:#fff;'>Category</th><th style='padding:6px;border:1px solid #ccc;background:#333;color:#fff;'>Resolved Finding</th></tr>+$resolvedRows+</table>+<p>Full report: $runPath</p>+</body></html>+"@++ Send-MailMessage -To $emailTo -From $emailFrom -SmtpServer $smtpServer -Subject "[SECURITY UPDATE] $($resolvedFindings.Count) finding(s) resolved on $env:COMPUTERNAME" -Body $mailBody -BodyAsHtml -Encoding UTF8 -ErrorAction Stop$runSummary.AlertSent = $true}catch {@@ -315,6 +595,39 @@ $mailRows}}+ # Persist the dedup state after every run; write failures never suppress alerts+ if ($alertDedup) {+ try {+ if (-not (Test-Path $stateDir)) {+ New-Item -Path $stateDir -ItemType Directory -Force | Out-Null+ }+ $stateFindings = @()+ foreach ($fingerprint in @($currentFingerprints.Keys)) {+ $currentEntry = $currentFingerprints[$fingerprint]+ $firstSeenText = $runStampText+ if ($previousState.ContainsKey($fingerprint) -and $null -ne $previousState[$fingerprint].FirstSeen) {+ $firstSeenText = $previousState[$fingerprint].FirstSeen.ToString('yyyy-MM-dd HH:mm:ss')+ }+ $stateFindings += [PSCustomObject]@{+ Fingerprint = $fingerprint+ Category = $currentEntry.Category+ Finding = $currentEntry.Finding+ Severity = $currentEntry.Severity+ FirstSeen = $firstSeenText+ LastSeen = $runStampText+ }+ }+ [PSCustomObject]@{+ ComputerName = $env:COMPUTERNAME+ RunTimestamp = $runStampText+ Findings = $stateFindings+ } | ConvertTo-Json -Depth 5 | Out-File -FilePath $stateFile -Encoding UTF8 -Force+ }+ catch {+ Write-Warning "Could not write alert dedup state file '$stateFile': $($_.Exception.Message). Alerting is not affected."+ }+ }+$runSummary | ConvertTo-Json -Depth 5 | Out-File (Join-Path $runPath 'RunSummary.json') -Encoding UTF8}catch {@@ -355,9 +668,36 @@ exit 0Replace('__WEBHOOK_URL__', $safeWebhookUrl).Replace('__EMAIL_TO__', $safeEmailTo).Replace('__EMAIL_FROM__', $safeEmailFrom).- Replace('__SMTP_SERVER__', $safeSmtpServer)+ Replace('__SMTP_SERVER__', $safeSmtpServer).+ Replace('__ALERT_DEDUP__', $safeAlertDedup).+ Replace('__REALERT_AFTER_DAYS__', $safeRealertAfterDays)$scanScript | Out-File $scriptPath -Encoding UTF8 -Force++ # The script embeds the webhook URL (a shared secret) and runs as SYSTEM,+ # so restrict it to Administrators and SYSTEM instead of the permissive+ # ProgramData default+ if ($env:OS -eq 'Windows_NT') {+ try {+ $scriptAcl = Get-Acl -Path $scriptPath -ErrorAction Stop+ $scriptAcl.SetAccessRuleProtection($true, $false)+ foreach ($existingRule in @($scriptAcl.Access)) {+ $null = $scriptAcl.RemoveAccessRule($existingRule)+ }+ foreach ($identity in @('NT AUTHORITY\SYSTEM', 'BUILTIN\Administrators')) {+ $accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule(+ $identity,+ [System.Security.AccessControl.FileSystemRights]::FullControl,+ [System.Security.AccessControl.AccessControlType]::Allow)+ $scriptAcl.AddAccessRule($accessRule)+ }+ Set-Acl -Path $scriptPath -AclObject $scriptAcl -ErrorAction Stop+ }+ catch {+ Write-Warning "Could not restrict permissions on '$scriptPath'; the file contains the webhook URL and may be readable by other local users: $_"+ }+ }+Write-Host "Scan script created: $scriptPath" -ForegroundColor Green}catch {@@ -399,7 +739,8 @@ exit 0'Weekly' { 'every Monday' }'Monthly' { 'on the 1st of every month' }}- $taskDescription = "WindowsSecurityAudit $ScanType scan ($assessmentType) runs $frequencyNote at $($Time.ToString('HH:mm')). Alerts on Critical findings. Managed by Register-ScheduledSecurityScan."+ $dedupNote = if ($alertDedupEnabled) { "on, re-alert after $RealertAfterDays days" } else { 'off' }+ $taskDescription = "WindowsSecurityAudit $ScanType scan ($assessmentType) runs $frequencyNote at $($Time.ToString('HH:mm')). Alerts on Critical findings (alert dedup: $dedupNote). Managed by Register-ScheduledSecurityScan."Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description $taskDescription -Force -ErrorAction Stop | Out-Null@@ -425,6 +766,8 @@ exit 0OutputPath = $OutputPathWebhookAlertEnabled = $webhookConfiguredEmailAlertEnabled = $emailConfigured+ AlertDedupEnabled = $alertDedupEnabled+ RealertAfterDays = $RealertAfterDays}}else {@@ -443,6 +786,8 @@ exit 0OutputPath = $OutputPathWebhookAlertEnabled = $webhookConfiguredEmailAlertEnabled = $emailConfigured+ AlertDedupEnabled = $alertDedupEnabled+ RealertAfterDays = $RealertAfterDays}}}@@ -458,6 +803,7 @@ exit 0Write-Host "Schedule: $($scanResult.Frequency) at $($scanResult.ScheduledTime)" -ForegroundColor CyanWrite-Host "Script: $($scanResult.ScriptPath)" -ForegroundColor CyanWrite-Host "Reports: $($scanResult.OutputPath)" -ForegroundColor Cyan+ Write-Host "Alert Dedup: $($scanResult.AlertDedupEnabled)" -ForegroundColor Cyanif ($scanResult.Status -eq 'Registered' -and -not $scanResult.WebhookAlertEnabled -and -not $scanResult.EmailAlertEnabled) {Write-Warning "No alerting configured. Critical findings will be logged but no webhook or email alert will be sent."diff --git a/Forensics/Get-FileSystemJournal.ps1 b/Forensics/Get-FileSystemJournal.ps1new file mode 100644index 0000000..b213174--- /dev/null+++ b/Forensics/Get-FileSystemJournal.ps1@@ -0,0 +1,803 @@+function Get-FileSystemJournal {+ <#+ .SYNOPSIS+ Parses NTFS USN change journal and file-system metadata for forensic analysis+ .DESCRIPTION+ Reads the NTFS USN change journal via fsutil to surface file creation,+ deletion, and rename activity, summarizes MFT statistics from volume+ metadata, and scans targeted paths for timestomp indicators by comparing+ StandardInformation timestamps against journal creation records.+ Raw $MFT record carving is out of scope; this function operates at the+ summary level exposed by fsutil.+ .PARAMETER DriveLetter+ NTFS volume to analyze (default: C)+ .PARAMETER Mode+ Analysis mode: USNJournal, MFTSummary, or TimestompScan (default: USNJournal)+ .PARAMETER MaxRecords+ Maximum journal records to parse or files to scan (default: 10000)+ .PARAMETER ScanPaths+ Paths scanned in TimestompScan mode (default: user Desktop, Downloads, Temp)+ .PARAMETER OutputPath+ Optional CSV file path for exporting collected records+ .EXAMPLE+ Get-FileSystemJournal -DriveLetter C -Mode USNJournal -MaxRecords 5000+ .EXAMPLE+ Get-FileSystemJournal -Mode TimestompScan -ScanPaths "C:\Users\victim\Downloads" -OutputPath "C:\IR\timestomp.csv"+ .OUTPUTS+ PSCustomObject with Mode, Records, Summary, Notes, and Recommendations+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [ValidateNotNullOrEmpty()]+ [string]$DriveLetter = 'C',++ [Parameter()]+ [ValidateSet('USNJournal', 'MFTSummary', 'TimestompScan')]+ [string]$Mode = 'USNJournal',++ [Parameter()]+ [ValidateRange(1, 1000000)]+ [int]$MaxRecords = 10000,++ [Parameter()]+ [string[]]$ScanPaths,++ [Parameter()]+ [string]$OutputPath+ )++ begin {+ Write-Host "========================================" -ForegroundColor Cyan+ Write-Host " FILE SYSTEM JOURNAL FORENSICS" -ForegroundColor Cyan+ Write-Host " USN Journal / MFT / Timestomp Analysis" -ForegroundColor Cyan+ Write-Host "========================================" -ForegroundColor Cyan+ Write-Host "Mode: $Mode" -ForegroundColor Yellow+ Write-Host "Drive: $DriveLetter" -ForegroundColor Yellow+ Write-Host "Max Records: $MaxRecords" -ForegroundColor Yellow+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ $drive = $DriveLetter.Trim().TrimEnd(':', '\').ToUpper()++ $isWindowsPlatform = ($env:OS -eq 'Windows_NT')++ $isAdmin = $false+ if ($isWindowsPlatform) {+ $isAdmin = Test-JournalElevation+ }++ $result = [PSCustomObject]@{+ CollectionDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ DriveLetter = $drive+ Mode = $Mode+ IsElevated = $isAdmin+ Records = @()+ Summary = @{}+ Notes = @()+ Recommendations = @()+ }++ if (-not $isWindowsPlatform) {+ Write-Warning "Get-FileSystemJournal requires Windows (NTFS volume + fsutil.exe). Current platform is not Windows."+ }+ elseif (-not $isAdmin) {+ Write-Warning "Administrator privileges are required to read the USN journal and volume metadata. Some sections will be skipped."+ }++ if ($Mode -eq 'TimestompScan' -and (-not $ScanPaths -or @($ScanPaths).Count -eq 0)) {+ $defaultPaths = @()+ if ($env:USERPROFILE) {+ $defaultPaths += (Join-Path $env:USERPROFILE 'Desktop')+ $defaultPaths += (Join-Path $env:USERPROFILE 'Downloads')+ }+ if ($env:TEMP) {+ $defaultPaths += $env:TEMP+ }+ $ScanPaths = $defaultPaths+ }+ }++ process {+ try {+ if (-not $isWindowsPlatform) {+ $result.Notes += "Platform check failed: NTFS journal and fsutil.exe are only available on Windows. No data was collected."+ $result.Recommendations += "Run this function on a Windows host against an NTFS volume."+ }+ else {+ switch ($Mode) {++ 'USNJournal' {+ Write-Host "`n[*] Reading USN change journal on $drive`:..." -ForegroundColor Cyan++ try {+ $rawLines = @(Get-FsutilOutput -Arguments @('usn', 'readjournal', "$drive`:"))++ $denied = @($rawLines | Where-Object { $_ -match '(?i)administrative privileges|access is denied|requires elevation' })+ if ($denied.Count -gt 0) {+ Write-Warning "fsutil denied access to the USN journal. Rerun from an elevated prompt."+ $result.Notes += "USN journal read failed: fsutil requires administrative privileges."+ }+ else {+ $journalRecords = @(ConvertFrom-UsnJournalOutput -Lines $rawLines -MaxRecords $MaxRecords)+ Write-Host " Parsed $($journalRecords.Count) journal records" -ForegroundColor Green++ $resolveCap = 250+ $resolveCount = 0+ $pathCache = @{}+ foreach ($record in $journalRecords) {+ if ($null -eq $record.FileReferenceNumber) { continue }+ if ($pathCache.ContainsKey($record.FileReferenceNumber)) {+ $record.FullPath = $pathCache[$record.FileReferenceNumber]+ continue+ }+ if ($resolveCount -ge $resolveCap) { continue }+ $resolveCount+++ $resolvedPath = Resolve-UsnJournalPath -DriveLetter $drive -FileReferenceNumber $record.FileReferenceNumber+ $pathCache[$record.FileReferenceNumber] = $resolvedPath+ if ($resolvedPath) {+ $record.FullPath = $resolvedPath+ }+ }+ Write-Verbose "Resolved full paths for $resolveCount unique file reference numbers (cap $resolveCap)."+ if ($journalRecords.Count -gt $resolveCap) {+ $result.Notes += "Full-path resolution was capped at $resolveCap unique file reference numbers; the USN journal stores names, not paths, so remaining records have no directory context."+ }++ $result.Records = $journalRecords++ $createdRecords = @($journalRecords | Where-Object { $_.ReasonFlags -contains 'FILE_CREATE' })+ $deletedCount = @($journalRecords | Where-Object { $_.ReasonFlags -contains 'FILE_DELETE' }).Count+ $renamedCount = @($journalRecords | Where-Object { $_.ReasonFlags -contains 'RENAME_OLD_NAME' }).Count++ $executableExtensions = @('.exe', '.dll', '.ps1', '.bat')+ $executableCreations = @($createdRecords | Where-Object {+ $null -ne $_.FileName -and+ $executableExtensions -contains ([System.IO.Path]::GetExtension($_.FileName)).ToLower()+ })++ $topDirectories = @($journalRecords |+ Where-Object { $_.FullPath } |+ ForEach-Object {+ try { Split-Path -Path $_.FullPath -Parent -ErrorAction Stop } catch { $null }+ } |+ Where-Object { $_ } |+ Group-Object |+ Sort-Object Count -Descending |+ Select-Object -First 10 |+ ForEach-Object { [PSCustomObject]@{ Directory = $_.Name; ChangeCount = $_.Count } })++ if ($topDirectories.Count -eq 0) {+ $result.Notes += "Top-directory ranking unavailable: journal records could not be resolved to full paths (deleted files and non-elevated runs commonly fail resolution)."+ }++ $result.Summary = @{+ TotalRecords = $journalRecords.Count+ FilesCreated = $createdRecords.Count+ FilesDeleted = $deletedCount+ FilesRenamed = $renamedCount+ ExecutableCreations = @($executableCreations | ForEach-Object {+ [PSCustomObject]@{+ FileName = $_.FileName+ FullPath = $_.FullPath+ TimeStamp = if ($_.TimeStamp) { $_.TimeStamp.ToString('yyyy-MM-dd HH:mm:ss') } else { $_.TimeStampText }+ ReasonFlags = @($_.ReasonFlags) -join '|'+ }+ })+ TopDirectories = $topDirectories+ }++ $result.Notes += "Journal output is text-parsed from 'fsutil usn readjournal'; fields are limited to what fsutil prints (file name, reason bitmask, time stamp, USN, file reference number)."+ $result.Notes += "The journal is circular; records shown cover only the window fsutil returned and older history may already be overwritten."++ $result.Recommendations += "Review executable creation events for unexpected binaries consistent with ingress tool transfer (MITRE ATT&CK T1105)."+ $result.Recommendations += "Export and preserve the journal promptly during incident response before rollover destroys older records."+ $result.Recommendations += "Correlate FILE_CREATE/RENAME sequences with process and network telemetry before attributing malicious intent."++ Write-Host " Files created: $($createdRecords.Count), deleted: $deletedCount, renamed: $renamedCount" -ForegroundColor Gray+ if ($executableCreations.Count -gt 0) {+ Write-Host "`n Executable creation events (T1105-style evidence):" -ForegroundColor Yellow+ foreach ($exe in $executableCreations) {+ $exeTime = if ($exe.TimeStamp) { $exe.TimeStamp.ToString('yyyy-MM-dd HH:mm:ss') } else { $exe.TimeStampText }+ $exePath = if ($exe.FullPath) { $exe.FullPath } else { $exe.FileName }+ Write-Host " [$exeTime] $exePath" -ForegroundColor Red+ }+ }+ if ($topDirectories.Count -gt 0) {+ Write-Host "`n Top directories by change count:" -ForegroundColor Gray+ foreach ($dir in $topDirectories) {+ Write-Host " $($dir.ChangeCount)x $($dir.Directory)" -ForegroundColor Gray+ }+ }+ }+ }+ catch {+ Write-Warning "Failed to read or parse the USN journal - $_"+ $result.Notes += "USN journal collection failed: $_"+ }+ }++ 'MFTSummary' {+ Write-Host "`n[*] Collecting MFT summary for $drive`:..." -ForegroundColor Cyan++ try {+ $ntfsLines = @(Get-FsutilOutput -Arguments @('fsinfo', 'ntfsinfo', "$drive`:"))++ $denied = @($ntfsLines | Where-Object { $_ -match '(?i)administrative privileges|access is denied|requires elevation' })+ if ($denied.Count -gt 0) {+ Write-Warning "fsutil denied access to volume metadata. Rerun from an elevated prompt."+ $result.Notes += "MFT summary collection failed: fsutil requires administrative privileges."+ }+ else {+ $volumeInfo = @{}+ foreach ($line in $ntfsLines) {+ if ($null -eq $line -or $line -match '^\s*$') { continue }+ if ($line -match '^\s*(?<key>[^:=]+?)\s*:\s*(?<value>.*)$') {+ $volumeInfo[$Matches.key.Trim()] = $Matches.value.Trim()+ }+ else {+ Write-Verbose "Skipping unrecognized ntfsinfo line: $line"+ }+ }++ $mftValidBytes = $null+ if ($volumeInfo.ContainsKey('Mft Valid Data Length')) {+ $mftValidBytes = ConvertFrom-JournalNumericText -Text $volumeInfo['Mft Valid Data Length']+ }+ $recordSizeBytes = $null+ if ($volumeInfo.ContainsKey('Bytes Per FileRecord Segment')) {+ $recordSizeBytes = ConvertFrom-JournalNumericText -Text $volumeInfo['Bytes Per FileRecord Segment']+ }++ $estimatedRecords = $null+ if ($null -ne $mftValidBytes -and $null -ne $recordSizeBytes -and $recordSizeBytes -gt 0) {+ $estimatedRecords = [Math]::Floor($mftValidBytes / $recordSizeBytes)+ }++ $infoRecords = @($volumeInfo.GetEnumerator() | Sort-Object Name | ForEach-Object {+ [PSCustomObject]@{ Property = $_.Key; Value = $_.Value }+ })+ $result.Records = $infoRecords++ $result.Summary = @{+ MftSizeBytes = $mftValidBytes+ MftSizeMB = if ($null -ne $mftValidBytes) { [Math]::Round($mftValidBytes / 1MB, 2) } else { $null }+ MftRecordSizeBytes = $recordSizeBytes+ EstimatedMftRecords = $estimatedRecords+ MftStartLcn = if ($volumeInfo.ContainsKey('Mft Start Lcn')) { $volumeInfo['Mft Start Lcn'] } else { $null }+ Mft2StartLcn = if ($volumeInfo.ContainsKey('Mft2 Start Lcn')) { $volumeInfo['Mft2 Start Lcn'] } else { $null }+ MftZoneStart = if ($volumeInfo.ContainsKey('Mft Zone Start')) { $volumeInfo['Mft Zone Start'] } else { $null }+ MftZoneEnd = if ($volumeInfo.ContainsKey('Mft Zone End')) { $volumeInfo['Mft Zone End'] } else { $null }+ PropertiesReported = $infoRecords.Count+ }++ $result.Notes += "Summary-level view only: values come from 'fsutil fsinfo ntfsinfo' volume metadata."+ $result.Notes += "Raw `$MFT record parsing (per-entry `$SI/`$FN attribute decoding) requires direct disk access or third-party libraries and is intentionally out of scope for this function."++ $result.Recommendations += "For per-record `$MFT analysis, pair this summary with a dedicated parser (e.g., MFTECmd) run against an acquired `$MFT copy."+ $result.Recommendations += "A large or rapidly growing MFT valid data length relative to expectations can indicate mass file creation (staging or encryption activity); baseline before alerting."++ if ($null -ne $mftValidBytes) {+ Write-Host " MFT valid data: $([Math]::Round($mftValidBytes / 1MB, 2)) MB" -ForegroundColor Green+ }+ if ($null -ne $estimatedRecords) {+ Write-Host " Estimated MFT records: $estimatedRecords" -ForegroundColor Green+ }+ }+ }+ catch {+ Write-Warning "Failed to collect MFT summary - $_"+ $result.Notes += "MFT summary collection failed: $_"+ }+ }++ 'TimestompScan' {+ Write-Host "`n[*] Scanning for timestomp indicators..." -ForegroundColor Cyan++ $creationRecords = @()+ if ($isAdmin) {+ try {+ Write-Host " Reading USN journal for creation-record comparison..." -ForegroundColor Gray+ $rawLines = @(Get-FsutilOutput -Arguments @('usn', 'readjournal', "$drive`:"))+ $denied = @($rawLines | Where-Object { $_ -match '(?i)administrative privileges|access is denied|requires elevation' })+ if ($denied.Count -gt 0) {+ Write-Warning "fsutil denied access to the USN journal; journal comparison will be skipped."+ $result.Notes += "USN journal comparison skipped: fsutil requires administrative privileges."+ }+ else {+ $creationRecords = @(ConvertFrom-UsnJournalOutput -Lines $rawLines -MaxRecords $MaxRecords |+ Where-Object { $_.ReasonFlags -contains 'FILE_CREATE' -and $null -ne $_.TimeStamp })+ Write-Host " Loaded $($creationRecords.Count) journal creation records" -ForegroundColor Gray+ }+ }+ catch {+ Write-Warning "Could not read the USN journal for comparison - $_"+ $result.Notes += "USN journal comparison skipped: $_"+ }+ }+ else {+ $result.Notes += "USN journal comparison skipped: elevation required. Only pre-2000/future timestamp anomalies are reported."+ }++ $filesScanned = 0+ $suspicious = @()++ foreach ($scanPath in @($ScanPaths)) {+ if ($null -eq $scanPath) { continue }+ if (-not (Test-Path $scanPath)) {+ Write-Verbose "Scan path not found: $scanPath"+ continue+ }++ try {+ Write-Host " Scanning: $scanPath..." -ForegroundColor Gray++ $files = @(Get-ChildItem -Path $scanPath -Recurse -File -ErrorAction SilentlyContinue |+ Select-Object -First $MaxRecords)++ foreach ($file in $files) {+ if ($filesScanned -ge $MaxRecords) { break }+ $filesScanned++++ $evaluation = Test-TimestompSignature -FileInfo $file -CreationRecords $creationRecords++ if ($evaluation.Indicators.Count -gt 0) {+ $suspicious += [PSCustomObject]@{+ FileName = $file.Name+ FullPath = $file.FullName+ LastWriteTime = $file.LastWriteTime+ CreationTime = $file.CreationTime+ JournalCreationTime = $evaluation.JournalCreationTime+ Indicators = $evaluation.Indicators+ Assessment = 'Heuristic finding - validate with $MFT $FN timestamps before concluding timestomping'+ }+ }+ }++ Write-Host " Scanned $($files.Count) files" -ForegroundColor Gray+ }+ catch {+ Write-Warning "Could not scan $scanPath - $_"+ }+ }++ $result.Records = $suspicious++ $backdatedCount = @($suspicious | Where-Object { $_.Indicators -contains 'BACKDATED_SI_TIMESTAMP' }).Count+ $pre2000Count = @($suspicious | Where-Object { $_.Indicators -contains 'PRE_2000_TIMESTAMP' }).Count+ $futureCount = @($suspicious | Where-Object { $_.Indicators -contains 'FUTURE_TIMESTAMP' }).Count++ $result.Summary = @{+ FilesScanned = $filesScanned+ SuspiciousFiles = $suspicious.Count+ BackdatedSiCount = $backdatedCount+ Pre2000TimestampCount = $pre2000Count+ FutureTimestampCount = $futureCount+ JournalCreationRecords = $creationRecords.Count+ ScanPaths = @($ScanPaths)+ }++ $result.Notes += "Timestomp detection is a HEURISTIC: a `$SI LastWriteTime earlier than the file's USN journal creation record is a classic timestomp signature, but legitimate tools (archivers, installers, backup restore) also rewrite timestamps."+ $result.Notes += "Journal records are matched to scanned files by full path when resolvable, otherwise by file name only; name-only matches can produce false positives for files sharing a name in different directories."++ $result.Recommendations += "Validate flagged files against `$MFT `$FN attribute timestamps before concluding anti-forensic activity (MITRE ATT&CK T1070.006)."+ $result.Recommendations += "Preserve flagged files and the volume journal before remediation; re-scanning after cleanup destroys evidence."++ Write-Host "`n Files scanned: $filesScanned" -ForegroundColor Green+ Write-Host " Suspicious files: $($suspicious.Count)" -ForegroundColor $(if ($suspicious.Count -gt 0) { 'Yellow' } else { 'Green' })++ if ($suspicious.Count -gt 0) {+ Write-Host "`n Timestomp indicators (heuristic):" -ForegroundColor Yellow+ foreach ($hit in ($suspicious | Select-Object -First 25)) {+ Write-Host " $($hit.FullPath)" -ForegroundColor Red+ Write-Host " `$SI LastWriteTime: $($hit.LastWriteTime) | Journal creation: $($hit.JournalCreationTime) | $($hit.Indicators -join ', ')" -ForegroundColor Gray+ }+ if ($suspicious.Count -gt 25) {+ Write-Host " ... and $($suspicious.Count - 25) more (see Records / CSV export)" -ForegroundColor Gray+ }+ }+ }+ }++ if ($OutputPath) {+ Write-Host "`n[*] Exporting records to CSV..." -ForegroundColor Cyan++ try {+ $csvPath = $OutputPath+ if ($csvPath -notmatch '(?i)\.csv$') {+ $csvPath = "$csvPath.csv"+ }+ $parentDir = Split-Path -Path $csvPath -Parent+ if ($parentDir -and -not (Test-Path $parentDir)) {+ New-Item -Path $parentDir -ItemType Directory -Force | Out-Null+ }++ $exportRows = @($result.Records | ForEach-Object {+ $row = $_+ $flattened = [ordered]@{}+ foreach ($prop in $row.PSObject.Properties) {+ $value = $prop.Value+ if ($null -ne $value -and $value -is [System.Collections.IEnumerable] -and $value -isnot [string]) {+ $flattened[$prop.Name] = (@($value) -join '|')+ }+ elseif ($value -is [datetime]) {+ $flattened[$prop.Name] = $value.ToString('yyyy-MM-dd HH:mm:ss')+ }+ elseif ($value -is [string] -and $value -match '^[=+\-@\t\r\n]') {+ # Prefix formula-leading characters so attacker-controlled+ # file names cannot execute when the CSV is opened in a+ # spreadsheet application; in-memory records stay pristine+ $flattened[$prop.Name] = "'" + $value+ }+ else {+ $flattened[$prop.Name] = $value+ }+ }+ [PSCustomObject]$flattened+ })++ @($exportRows) | Export-Csv -Path $csvPath -NoTypeInformation -Encoding UTF8+ Write-Host " CSV export saved: $csvPath" -ForegroundColor Green+ }+ catch {+ Write-Warning "CSV export failed - $_"+ }+ }+ }+ }+ catch {+ Write-Error "Error during file system journal analysis - $_"+ throw+ }+ }++ end {+ Write-Host "`n========================================" -ForegroundColor Green+ Write-Host " FILE SYSTEM JOURNAL ANALYSIS COMPLETE" -ForegroundColor Green+ Write-Host "========================================" -ForegroundColor Green++ Write-Host "`nMode: $($result.Mode)" -ForegroundColor Cyan+ Write-Host " Records collected: $(@($result.Records).Count)" -ForegroundColor White+ Write-Host " Elevated: $($result.IsElevated)" -ForegroundColor $(if ($result.IsElevated) { 'White' } else { 'Yellow' })++ if ($result.Notes.Count -gt 0) {+ Write-Host "`nCapability Notes:" -ForegroundColor Cyan+ foreach ($note in $result.Notes) {+ Write-Host " - $note" -ForegroundColor Gray+ }+ }++ if ($result.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Yellow+ foreach ($recommendation in $result.Recommendations) {+ Write-Host " - $recommendation" -ForegroundColor Gray+ }+ }++ return $result+ }+}++function Get-FsutilOutput {+ [CmdletBinding()]+ param(+ [Parameter(Mandatory = $true)]+ [string[]]$Arguments+ )++ $output = @(& fsutil @Arguments 2>&1)+ return @($output | ForEach-Object { "$_" })+}++function Test-JournalElevation {+ [CmdletBinding()]+ param()++ try {+ return ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ }+ catch {+ return $false+ }+}++function ConvertFrom-UsnJournalOutput {+ [CmdletBinding()]+ param(+ [Parameter()]+ [AllowEmptyCollection()]+ [string[]]$Lines = @(),++ [Parameter()]+ [ValidateRange(1, 1000000)]+ [int]$MaxRecords = 10000+ )++ $records = @()+ $current = $null++ foreach ($line in $Lines) {+ if ($records.Count -ge $MaxRecords) { break }+ if ($null -eq $line -or $line -match '^\s*$') { continue }++ if ($line -match '(?i)USN_RECORD') {+ if ($null -ne $current) {+ $records += (New-UsnJournalRecord -Fields $current)+ }+ $current = @{}+ continue+ }++ if ($line -notmatch '^\s*(?<key>[^:=]+?)\s*:\s*(?<value>.*)$') {+ Write-Verbose "Skipping unrecognized journal line: $line"+ continue+ }++ $rawKey = $Matches.key.Trim()+ $value = $Matches.value.Trim()++ $normalizedKey = $null+ if ($rawKey -match '^(?i)file name$') { $normalizedKey = 'FileName' }+ elseif ($rawKey -match '^(?i)reason$') { $normalizedKey = 'Reason' }+ elseif ($rawKey -match '^(?i)time stamp$') { $normalizedKey = 'TimeStamp' }+ elseif ($rawKey -match '^(?i)usn$') { $normalizedKey = 'Usn' }+ elseif ($rawKey -match '^(?i)file reference number$') { $normalizedKey = 'FileReferenceNumber' }++ if ($null -eq $normalizedKey) {+ Write-Verbose "Skipping unrecognized journal field '$rawKey' in line: $line"+ continue+ }++ if ($null -eq $current) {+ $current = @{}+ }++ if ($current.ContainsKey($normalizedKey)) {+ $records += (New-UsnJournalRecord -Fields $current)+ if ($records.Count -ge $MaxRecords) { break }+ $current = @{}+ }++ $current[$normalizedKey] = $value+ }++ if ($null -ne $current -and $records.Count -lt $MaxRecords -and @($current.Keys).Count -gt 0) {+ $records += (New-UsnJournalRecord -Fields $current)+ }++ return @($records)+}++function New-UsnJournalRecord {+ [CmdletBinding()]+ param(+ [Parameter(Mandatory = $true)]+ [hashtable]$Fields+ )++ $fileName = if ($Fields.ContainsKey('FileName')) { $Fields['FileName'] } else { $null }+ $reasonText = if ($Fields.ContainsKey('Reason')) { $Fields['Reason'] } else { '' }+ $timeStampText = if ($Fields.ContainsKey('TimeStamp')) { $Fields['TimeStamp'] } else { $null }+ $usnText = if ($Fields.ContainsKey('Usn')) { $Fields['Usn'] } else { $null }+ $fileReference = if ($Fields.ContainsKey('FileReferenceNumber')) { $Fields['FileReferenceNumber'] } else { $null }++ $reasonMask = $null+ $maskMatch = [regex]::Match($reasonText, '0x(?<hex>[0-9A-Fa-f]+)')+ if ($maskMatch.Success) {+ try {+ $reasonMask = [Convert]::ToUInt32($maskMatch.Groups['hex'].Value, 16)+ }+ catch {+ $reasonMask = $null+ }+ }++ $reasonFlags = @()+ if ($null -ne $reasonMask) {+ $reasonFlags = @(Get-UsnReasonFlagNames -Mask $reasonMask)+ }+ if ($reasonFlags.Count -eq 0 -and $reasonText) {+ $reasonFlags = @(Get-UsnReasonFlagNames -ReasonText $reasonText)+ }++ $timeStamp = $null+ if ($timeStampText) {+ $parsedDate = [datetime]::MinValue+ if ([datetime]::TryParse($timeStampText, [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref]$parsedDate)) {+ $timeStamp = $parsedDate+ }+ elseif ([datetime]::TryParse($timeStampText, [ref]$parsedDate)) {+ $timeStamp = $parsedDate+ }+ else {+ Write-Verbose "Could not parse journal time stamp: $timeStampText"+ }+ }++ return [PSCustomObject]@{+ FileName = $fileName+ FullPath = $null+ Reason = $reasonText+ ReasonMask = $reasonMask+ ReasonFlags = $reasonFlags+ TimeStamp = $timeStamp+ TimeStampText = $timeStampText+ Usn = $usnText+ FileReferenceNumber = $fileReference+ }+}++function Get-UsnReasonFlagNames {+ [CmdletBinding()]+ param(+ [Parameter()]+ [uint32]$Mask = 0,++ [Parameter()]+ [string]$ReasonText+ )++ $flagMap = [ordered]@{+ 'DATA_OVERWRITE' = [uint32]0x00000001+ 'DATA_EXTEND' = [uint32]0x00000002+ 'DATA_TRUNCATION' = [uint32]0x00000004+ 'NAMED_DATA_OVERWRITE' = [uint32]0x00000010+ 'NAMED_DATA_EXTEND' = [uint32]0x00000020+ 'NAMED_DATA_TRUNCATION' = [uint32]0x00000040+ 'FILE_CREATE' = [uint32]0x00000100+ 'FILE_DELETE' = [uint32]0x00000200+ 'EA_CHANGE' = [uint32]0x00000400+ 'SECURITY_CHANGE' = [uint32]0x00000800+ 'RENAME_OLD_NAME' = [uint32]0x00001000+ 'RENAME_NEW_NAME' = [uint32]0x00002000+ 'INDEXABLE_CHANGE' = [uint32]0x00004000+ 'BASIC_INFO_CHANGE' = [uint32]0x00008000+ 'HARD_LINK_CHANGE' = [uint32]0x00010000+ 'COMPRESSION_CHANGE' = [uint32]0x00020000+ 'ENCRYPTION_CHANGE' = [uint32]0x00040000+ 'OBJECT_ID_CHANGE' = [uint32]0x00080000+ 'REPARSE_POINT_CHANGE' = [uint32]0x00100000+ 'STREAM_CHANGE' = [uint32]0x00200000+ 'CLOSE' = [uint32]2147483648+ }++ $names = @()++ if ($Mask -ne 0) {+ foreach ($flagName in $flagMap.Keys) {+ if (($Mask -band $flagMap[$flagName]) -eq $flagMap[$flagName]) {+ $names += $flagName+ }+ }+ }+ elseif ($ReasonText) {+ $haystack = ($ReasonText.ToUpper() -replace '[^A-Z0-9]', '')+ foreach ($flagName in $flagMap.Keys) {+ $needle = $flagName -replace '_', ''+ if ($haystack.Contains($needle)) {+ $names += $flagName+ }+ }+ }++ return @($names)+}++function Resolve-UsnJournalPath {+ [CmdletBinding()]+ param(+ [Parameter()]+ [ValidateNotNullOrEmpty()]+ [string]$DriveLetter = 'C',++ [Parameter(Mandatory = $true)]+ [ValidateNotNullOrEmpty()]+ [string]$FileReferenceNumber+ )++ try {+ $drive = $DriveLetter.Trim().TrimEnd(':', '\').ToUpper()+ $output = @(Get-FsutilOutput -Arguments @('file', 'queryfilenamebyid', "$drive`:\", $FileReferenceNumber))++ foreach ($line in $output) {+ if ($null -ne $line -and $line -match '\\\\\?\\(?<path>.+?)\s*$') {+ return $Matches.path+ }+ }++ Write-Verbose "No path returned for file reference number $FileReferenceNumber (file may be deleted)."+ }+ catch {+ Write-Verbose "Path resolution failed for file reference number $FileReferenceNumber - $_"+ }++ return $null+}++function ConvertFrom-JournalNumericText {+ [CmdletBinding()]+ param(+ [Parameter()]+ [AllowNull()]+ [AllowEmptyString()]+ [string]$Text+ )++ if ([string]::IsNullOrWhiteSpace($Text)) {+ return $null+ }++ $cleaned = $Text.Trim()+ try {+ if ($cleaned -match '0x(?<hex>[0-9A-Fa-f]+)') {+ return [Convert]::ToUInt64($Matches.hex, 16)+ }+ $digitsOnly = $cleaned -replace '[^0-9]', ''+ if ($digitsOnly) {+ return [Convert]::ToUInt64($digitsOnly, 10)+ }+ }+ catch {+ Write-Verbose "Could not parse numeric value: $Text"+ }++ return $null+}++function Test-TimestompSignature {+ [CmdletBinding()]+ param(+ [Parameter(Mandatory = $true)]+ [object]$FileInfo,++ [Parameter()]+ [AllowEmptyCollection()]+ [object[]]$CreationRecords = @()+ )++ $indicators = @()++ $lastWrite = $null+ if ($null -ne $FileInfo.PSObject.Properties['LastWriteTime'] -and $null -ne $FileInfo.LastWriteTime) {+ $lastWrite = $FileInfo.LastWriteTime+ }++ $fileName = $null+ if ($null -ne $FileInfo.PSObject.Properties['Name']) {+ $fileName = $FileInfo.Name+ }+ $fullName = $null+ if ($null -ne $FileInfo.PSObject.Properties['FullName']) {+ $fullName = $FileInfo.FullName+ }++ $journalCreationTime = $null+ foreach ($record in @($CreationRecords)) {+ if ($null -eq $record -or $null -eq $record.TimeStamp) { continue }++ $pathMatch = ($null -ne $record.FullPath -and $null -ne $fullName -and $record.FullPath -ieq $fullName)+ $nameMatch = ($null -eq $record.FullPath -and $null -ne $record.FileName -and $null -ne $fileName -and $record.FileName -ieq $fileName)++ if (($pathMatch -or $nameMatch) -and ($null -eq $journalCreationTime -or $record.TimeStamp -gt $journalCreationTime)) {+ $journalCreationTime = $record.TimeStamp+ }+ }++ if ($null -ne $lastWrite) {+ if ($null -ne $journalCreationTime -and $lastWrite -lt $journalCreationTime) {+ $indicators += 'BACKDATED_SI_TIMESTAMP'+ }+ if ($lastWrite -lt [datetime]'2000-01-01') {+ $indicators += 'PRE_2000_TIMESTAMP'+ }+ if ($lastWrite -gt (Get-Date)) {+ $indicators += 'FUTURE_TIMESTAMP'+ }+ }++ return [PSCustomObject]@{+ Indicators = @($indicators)+ JournalCreationTime = $journalCreationTime+ }+}diff --git a/README.md b/README.mdindex 3f15e74..a2d5a12 100644--- a/README.md+++ b/README.md@@ -5,11 +5,11 @@[](https://github.com/PowerShell/PowerShell)[](https://www.microsoft.com/windows)[](LICENSE)-[](https://github.com/okanyildiz/WindowsSecurityAudit/releases)-[](https://github.com/okanyildiz/WindowsSecurityAudit)+[](https://github.com/okanyildiz/WindowsSecurityAudit/releases)+[](https://github.com/okanyildiz/WindowsSecurityAudit)[](https://github.com/okanyildiz/WindowsSecurityAudit)[](https://github.com/okanyildiz/WindowsSecurityAudit/actions/workflows/ci.yml)-[](https://github.com/okanyildiz/WindowsSecurityAudit/blob/main/tests/WindowsSecurityAudit.Tests.ps1)+[](https://github.com/okanyildiz/WindowsSecurityAudit/blob/main/tests/WindowsSecurityAudit.Tests.ps1)[](https://github.com/okanyildiz/WindowsSecurityAudit/stargazers)[](https://github.com/okanyildiz/WindowsSecurityAudit/network/members)@@ -27,14 +27,14 @@## 🧰 Full Feature Overview-**69 functions across 14 modules** — the complete toolkit at a glance:+**72 functions across 14 modules** — the complete toolkit at a glance:| Module | Functions | Scope ||--------|:---------:|-------|| 🧱 **Core Security** | 5 | Security baseline scoring (0-100), system inventory, SFC/DISM integrity checks, Event ID context, baseline drift diffing |-| 🕵️ **Detection** | 6 | Persistence mechanisms, suspicious processes, network anomalies, authentication attacks, credential-access events (Kerberoasting/spray/golden-ticket heuristic), defense-evasion & tamper detection |+| 🕵️ **Detection** | 7 | Persistence mechanisms, suspicious processes, network anomalies, authentication attacks, credential-access events (Kerberoasting/spray/golden-ticket heuristic), defense-evasion & tamper detection, Sysmon log analytics (process chains/beaconing/LSASS access) || 🔬 **Analysis** | 4 | Deep-dive analysis of event logs, registry, process memory, and file system |-| 🚨 **Response** | 4 | Incident response orchestration, forensic evidence collection, HTML/JSON/CSV/NDJSON/CEF report export, SIEM event conversion |+| 🚨 **Response** | 5 | Incident response orchestration, forensic evidence collection, HTML/JSON/CSV/NDJSON/CEF report export, SIEM event conversion, SIEM live streaming (Splunk HEC/Sentinel/webhook) || 🏢 **Enterprise** | 4 | Multi-system parallel scanning, full assessment orchestration, scheduled scans with Teams/Slack/email alerts || 🔒 **Hardening** | 4 | Audit policies, PowerShell security, baseline enforcement, curated auto-remediation (WhatIf-first, with rollback) || 🛡️ **Windows Defender** | 3 | Defender health monitoring, custom scans, configuration optimization |@@ -42,7 +42,7 @@| ✅ **Compliance** | 5 | CIS Benchmark, NIST 800-53, PCI-DSS 4.0 validation, compliance reports, audit evidence export || 🌳 **Active Directory** | 6 | AD backdoors & DCSync detection, vulnerability scan, stale objects, password policies, privileged accounts, posture || 🩹 **Vulnerability** | 8 | CVE assessment (real NVD data + version-exact CPE matching), EOL software, exposed services, certificates, patches |-| 🔍 **Forensics** | 6 | Memory dumps, artifact collection with SHA256-at-acquisition, execution artifacts (prefetch/UserAssist/BAM), USB history, user activity artifacts (Recycle Bin/LNK/JumpLists/Timeline), forensic timelines |+| 🔍 **Forensics** | 7 | Memory dumps, artifact collection with SHA256-at-acquisition, execution artifacts (prefetch/UserAssist/BAM), USB history, user activity artifacts (Recycle Bin/LNK/JumpLists/Timeline), forensic timelines, USN journal/MFT summary/timestomp evidence || ☁️ **Cloud Security** | 3 | Azure AD risky sign-ins, M365 security posture, cloud compliance status || 📊 **Reporting** | 4 | Security metrics/KPIs, executive reports, live HTML dashboards, consolidated all-module Chart.js report |@@ -69,7 +69,7 @@ If you find this tool valuable for your security operations, consider supportingIn today's rapidly evolving threat landscape, organizations face unprecedented challenges in maintaining robust security postures across their Windows infrastructure. Traditional security tools often fall short, requiring multiple expensive licenses, complex integrations, and specialized expertise. The **Windows Security Audit Module** emerges as a game-changing solution, offering enterprise-grade security capabilities through a unified, open-source PowerShell framework.-This comprehensive toolkit represents over 3 years of development, incorporating real-world insights from securing Fortune 500 environments, government agencies, and critical infrastructure. With 69 meticulously crafted functions organized into 14 specialized modules, it delivers capabilities typically found only in solutions costing $50,000+ annually - completely free and open source.+This comprehensive toolkit represents over 3 years of development, incorporating real-world insights from securing Fortune 500 environments, government agencies, and critical infrastructure. With 72 meticulously crafted functions organized into 14 specialized modules, it delivers capabilities typically found only in solutions costing $50,000+ annually - completely free and open source.### 🎯 The Vision@@ -119,7 +119,7 @@ A single, cohesive PowerShell module that consolidates essential security functi</tr><tr><td><strong>Functions</strong></td>-<td>✅ 69 Comprehensive</td>+<td>✅ 72 Comprehensive</td><td>⚠️ 20-30 Limited</td><td>⚠️ 5-15 Basic</td></tr>@@ -206,13 +206,14 @@ WindowsSecurityAudit/│ ├── Get-SystemInfo.ps1│ └── Test-SystemIntegrity.ps1│-├── 📁 Detection/ # Threat Detection (6 functions)+├── 📁 Detection/ # Threat Detection (7 functions)│ ├── Find-DefenseEvasion.ps1│ ├── Find-NetworkAnomalies.ps1│ ├── Find-PersistenceMechanisms.ps1│ ├── Find-SuspiciousAuthentication.ps1│ ├── Find-SuspiciousProcesses.ps1-│ └── Get-CredentialAccessEvents.ps1+│ ├── Get-CredentialAccessEvents.ps1+│ └── Get-SysmonAnalytics.ps1│├── 📁 Enterprise/ # Enterprise (4 functions)│ ├── Get-MultiSystemAudit.ps1@@ -220,10 +221,11 @@ WindowsSecurityAudit/│ ├── Invoke-SecurityAssessment.ps1│ └── Register-ScheduledSecurityScan.ps1│-├── 📁 Forensics/ # Digital Forensics (6 functions)+├── 📁 Forensics/ # Digital Forensics (7 functions)│ ├── Export-MemoryDump.ps1│ ├── Get-ArtifactCollection.ps1│ ├── Get-ExecutionArtifacts.ps1+│ ├── Get-FileSystemJournal.ps1│ ├── Get-USBHistory.ps1│ ├── Get-UserActivityArtifacts.ps1│ └── New-ForensicTimeline.ps1@@ -242,13 +244,14 @@ WindowsSecurityAudit/│ ├── New-ExecutiveReport.ps1│ └── New-SecurityDashboard.ps1│-├── 📁 Response/ # Incident Response (4 functions)+├── 📁 Response/ # Incident Response (5 functions)│ ├── ConvertTo-SiemEvent.ps1│ ├── Export-SecurityReport.ps1│ ├── Invoke-ForensicCollection.ps1-│ └── Invoke-IncidentResponse.ps1+│ ├── Invoke-IncidentResponse.ps1+│ └── Send-SiemEvent.ps1│-├── 📁 tests/ # Pester tests (385 tests)+├── 📁 tests/ # Pester tests (413 tests)│ └── WindowsSecurityAudit.Tests.ps1│├── 📁 ThreatHunting/ # Threat Hunting (7 functions)@@ -315,7 +318,7 @@ Import-Module ".\WindowsSecurityAudit.psd1" -Force# Or run the smoke test.\Test-Module.ps1-# Verify installation - should return 69+# Verify installation - should return 72(Get-Command -Module WindowsSecurityAudit).Count```@@ -455,6 +458,19 @@ $report = Invoke-SecurityAssessment$report | Export-SecurityReport -Format NDJSON -NoAutoOpen```+### Fleet Scanning & Smart Alerts (New in v1.5.0)+```powershell+# Deploy the module to remote hosts and run a curated function set+# (zip -> Copy-Item -ToSession -> remote Import-Module)+Invoke-EnterpriseSecurityScan -ComputerName srv1, srv2 -UseModuleFunctions -RemoteFunctionSet Standard++# Schedule a daily full scan with webhook alerts. Alert dedup is ON by+# default: findings are fingerprinted (State\last-findings.json) and+# classified New/Persisting/Resolved, so repeat alerts are suppressed+# until -RealertAfterDays (default 7) elapses+Register-ScheduledSecurityScan -ScanType Full -Frequency Daily -WebhookUrl $url+```+### One Report to Rule Them All (New in v1.1.0)```powershell# Collect results from ALL modules into a single interactive Chart.js HTML report@@ -493,7 +509,7 @@ The Core module serves as the foundation of the entire security assessment frame----### 2️⃣ Detection Module (6 Functions)+### 2️⃣ Detection Module (7 Functions)The Detection module provides real-time threat identification capabilities using both signature-based and behavioral analysis techniques. These functions are designed to identify active threats, suspicious behaviors, and potential compromises that traditional antivirus might miss.@@ -505,6 +521,7 @@ The Detection module provides real-time threat identification capabilities using| **`Find-SuspiciousAuthentication`** | Detects authentication attacks and anomalies | • Brute force attempts (multiple failures)<br>• Account lockout patterns<br>• After-hours authentication<br>• Explicit-credential logons (runas / net use, 4624 Type 9 NewCredentials)<br>• Per-account NTLM network logon indicators<br>• Impossible travel scenarios<br>• Service account anomalies | High: Brute force<br>Medium: After hours<br>Low: Explicit credentials || **`Get-CredentialAccessEvents`** | Detects runtime credential-access activity from event logs | • Kerberoasting: RC4 service ticket bursts (4769)<br>• Anomalous TGT request volumes (4768)<br>• Kerberos pre-auth failure spikes / password spray (4771)<br>• Golden-ticket heuristic (Kerberos logon with no matching TGT; labeled Heuristic/Medium)<br>• Optional LSASS access handles (`-IncludeLSASSAccess`; 4663 needs a SACL, or Sysmon 10) | High: Kerberoast bursts, suspicious LSASS access<br>Medium: TGT anomalies, spray spikes, golden-ticket heuristic || **`Find-DefenseEvasion`** | Detects defense-evasion and security-tampering activity | • AMSI bypass & ETW tamper patterns in script-block logs (4104)<br>• Defender exclusions and disabled real-time/behavior monitoring (Get-MpPreference)<br>• Defender tamper events (5001/5007)<br>• Log clearing (1102/104) and audit policy changes (4719) with clearing-account attribution<br>• Optional heuristic log-gap analysis (`-IncludeLogGapAnalysis`) | High: AMSI/ETW tamper, Defender tamper, cleared logs<br>Low: log gaps (heuristic) |+| **`Get-SysmonAnalytics`** | Deep analytics over the Sysmon Operational log (requires Sysmon) | • Event 1 process chains & command-line indicators<br>• Event 3 network beaconing detection<br>• Event 7 image loads<br>• Event 10 process access with LSASS access-mask analysis (T1003.001)<br>• Event 11 file creates, Events 12/13 registry writes<br>• Event 22 DNS anomalies<br>• `-Hours` / `-EventTypes` / `-MaxEvents` filtering; returns `NotAvailable` gracefully when Sysmon is absent | High: LSASS access masks, encoded commands, download cradles<br>Medium: beaconing, persistence-oriented writes |---@@ -521,7 +538,7 @@ The Analysis module performs deep forensic examination of system components to u----### 4️⃣ Response Module (4 Functions)+### 4️⃣ Response Module (5 Functions)The Response module provides automated incident response capabilities, enabling rapid containment of threats and systematic evidence collection. These functions follow industry-standard incident response procedures while maintaining forensic integrity.@@ -531,6 +548,7 @@ The Response module provides automated incident response capabilities, enabling| **`Invoke-ForensicCollection`** | Systematically collects forensic evidence | • Memory dump acquisition<br>• Network state capture<br>• Registry snapshot<br>• Event log extraction<br>• File artifact collection<br>• Browser history preservation | Memory dumps<br>Network captures<br>System artifacts<br>User data || **`Export-SecurityReport`** | Generates professional security reports | • HTML interactive dashboards<br>• JSON for SIEM integration<br>• CSV for data analysis<br>• NDJSON/CEF SIEM-ready exports (`-Format NDJSON/CEF`; `All` writes .ndjson + .cef too)<br>• `-NoAutoOpen` for headless/SYSTEM-context runs | Multi-format reports<br>Executive summaries<br>Technical details<br>Recommendations || **`ConvertTo-SiemEvent`** | Converts findings into SIEM-ready event strings | • Pipeline conversion of findings to NDJSON (one compact JSON object per line) or CEF (`CEF:0` strings)<br>• Severity-to-number mapping and heuristic CEF `act` field<br>• MITRE technique ID passthrough when present<br>• `-HostName` / `-ProductVersion` stamping<br>• Splunk / Sentinel / QRadar / ArcSight ingestion ready | NDJSON lines<br>CEF strings |+| **`Send-SiemEvent`** | Streams findings directly to SIEM HTTP endpoints | • Splunk HEC (`Splunk <token>` auth header), Microsoft Sentinel (Log Analytics API with HMAC-SHA256 SharedKey signature), or generic webhook with custom headers<br>• NDJSON or CEF payloads via ConvertTo-SiemEvent<br>• Batching (`-BatchSize`) with exponential-backoff retry on HTTP 429/5xx (`-MaxRetries`, `-ThrottleMs`)<br>• Token always masked in console output<br>• Also wired into `Export-SecurityReport -StreamTo/-StreamUri/-StreamToken/-StreamFormat` | BatchesSent / EventsSent / Failed / DurationSec summary |---@@ -634,7 +652,7 @@ The Vulnerability module identifies, assesses, and prioritizes security weakness----### 1️⃣2️⃣ Forensics Module (6 Functions)+### 1️⃣2️⃣ Forensics Module (7 Functions)The Forensics module provides digital forensic capabilities for incident investigation, evidence collection, and timeline reconstruction while maintaining chain of custody and legal admissibility.@@ -644,6 +662,7 @@ The Forensics module provides digital forensic capabilities for incident investi| **`Get-ArtifactCollection`** | Collects forensic artifacts | • Browser history (all browsers)<br>• Download history<br>• Temporary files<br>• Thumbnail cache<br>• Per-file SHA256 computed at acquisition<br>• Raw registry hive capture via `reg save`<br>• AcquisitionLog manifest block | User activity<br>File access<br>Internet activity<br>Deleted items || **`Get-UserActivityArtifacts`** | Collects per-user activity artifacts for DFIR | • Recycle Bin `$I` parsing (v2 + best-effort v1 headers; path, size, deletion FILETIME)<br>• Recent/Desktop LNK resolution via WScript.Shell COM (unresolved off-Windows)<br>• JumpList enumeration (AutomaticDestinations; embedded targets not parsed)<br>• ActivitiesCache.db raw copy (no SQLite parsing)<br>• Optional CSV export (`-OutputPath`) | Deleted files<br>Opened documents<br>App usage evidence<br>Timeline databases || **`Get-ExecutionArtifacts`** | Traces program execution | • Prefetch analysis<br>• ShimCache examination<br>• UserAssist decoding<br>• RecentDocs<br>• BAM/DAM analysis | Program execution<br>Timestamps<br>Frequency<br>User attribution |+| **`Get-FileSystemJournal`** | File-system journal & timestomp evidence via fsutil (requires elevation) | • USN journal parsing with reason decoding and executable-creation evidence<br>• MFT summary statistics (summary-level via fsutil — no raw $MFT record parsing)<br>• TimestompScan cross-checks file timestamps against USN journal creation records plus pre-2000/future anomalies — explicitly labeled heuristic<br>• `-DriveLetter`, `-MaxRecords`, optional CSV `-OutputPath` | Executable drops<br>USN journal activity<br>Timestomp indicators (heuristic) || **`Get-USBHistory`** | USB device forensics | • Device enumeration<br>• First/Last connection<br>• Serial numbers<br>• Volume names<br>• Drive letters<br>• User correlation | Device usage<br>Data transfer<br>Timeline<br>User activity || **`New-ForensicTimeline`** | Timeline reconstruction | • Multi-source correlation<br>• Event sequencing<br>• File system timeline<br>• Registry timeline<br>• Log correlation<br>• Visual timeline generation | Incident timeline<br>Attack chain<br>User actions<br>System events |@@ -678,7 +697,29 @@ The Reporting module transforms raw security data into actionable intelligence tThe full feature set is documented in the module tables above — this section only covers what changed per release, newest first:-### 🆕 v1.4.0 — SIEM Integration, Credential & Evasion Detection, Forensic Integrity+### 🆕 v1.5.0 — Fleet Scans, Sysmon Analytics, SIEM Streaming & Smart Alerts++**3 new functions** — bringing the toolkit to **72 functions across 14 modules**:++| Function | Module | What It Does |+|----------|--------|--------------|+| **`Send-SiemEvent`** | Response | Stream findings directly to your SIEM over HTTP: **Splunk HEC** (`Splunk <token>` auth header), **Microsoft Sentinel** (Log Analytics Data Collector API with the documented HMAC-SHA256 **SharedKey signature**), or a **generic webhook** with custom headers — in **NDJSON or CEF** with batching (`-BatchSize`), exponential-backoff retry on HTTP 429/5xx (`-MaxRetries`, `-ThrottleMs`), and the token **masked** in all console output |+| **`Get-SysmonAnalytics`** | Detection | Deep **Sysmon Operational log analytics** (requires Sysmon; returns `NotAvailable` gracefully when absent): Event 1 process chains & command-line indicators, Event 3 network **beaconing**, Event 7 image loads, Event 10 process access with **LSASS access-mask** analysis (T1003.001), Event 11 file creates, Events 12/13 registry writes, Event 22 DNS anomalies — every finding carries a MITRE ATT&CK `Technique` property; `-Hours`, `-EventTypes`, `-MaxEvents` filtering |+| **`Get-FileSystemJournal`** | Forensics | File-system journal evidence via **fsutil** (requires elevation): **USN journal** parsing with reason decoding and **executable-creation evidence**, **MFT summary** statistics (summary-level only — no raw $MFT record parsing), and a **TimestompScan** mode that cross-checks file timestamps against journal creation records and is explicitly labeled **heuristic**; `-DriveLetter`, `-MaxRecords`, CSV `-OutputPath` |++**Extended parameters on existing functions:**++- `Invoke-EnterpriseSecurityScan -UseModuleFunctions -RemoteFunctionSet Quick/Standard/Deep` — **deploy the module to remote hosts** (zip → `Copy-Item -ToSession` → remote `Import-Module`) instead of shipping embedded script blocks; plus a parallel **connectivity probe** (`-ProbeTimeoutSec`), **per-host timeout** (`-HostTimeoutSec`), **CSV target input** (`-TargetFile`), a `-WhatIf` deployment preview, and `finally`-block session disposal+- `Register-ScheduledSecurityScan` — **alert dedup is now on by default**: findings are fingerprinted into `State\last-findings.json` and classified **New / Persisting / Resolved**, so repeat alerts are suppressed until `-RealertAfterDays` (default 7) elapses; opt out with `-DisableAlertDedup`; a broken state file degrades to normal alerting, never to silence+- `Get-ThreatIntelligence` — **TAXII pagination** (follows `more`/`next` up to a 20-page cap, reporting `PagesFetched`/`ObjectsFetched`) and **MISP attribute types expanded to 12** (adds hostname, uri, sha1, email-src, email-dst, filename, mutex → new `EmailIndicators`, `FileNameIndicators`, `MutexIndicators` lists)+- `Resolve-CpeName` — curated offline table grown to **~120 products** plus **vendor-scheme translation** for version schemes (Java/.NET/Python and friends), surfaced as `MatchedBy = 'SchemeTranslation'` with an `OriginalVersion` property+- `Export-SecurityReport -StreamTo/-StreamUri/-StreamToken/-StreamFormat` — **stream findings to a SIEM** right after report export via `Send-SiemEvent`++**Quality infrastructure:**++- 🧪 **413 Pester tests** (`tests/WindowsSecurityAudit.Tests.ps1`) — new coverage for v1.5 parameter help, SIEM token-masking AST checks, hardcoded-secret checks on the new files, MITRE `Technique` attachment, heuristic timestomp labeling, and the fingerprint state logic embedded in the generated scan script++### v1.4.0 — SIEM Integration, Credential & Evasion Detection, Forensic Integrity**4 new functions** — bringing the toolkit to **69 functions across 14 modules**:@@ -838,7 +879,7 @@ Everything below shipped with the original release and keeps getting sharper:### Community Edition - Forever FREE- ✅ **Price**: 100% FREE - No hidden costs-- ✅ **Functions**: All 69 functions included+- ✅ **Functions**: All 72 functions included- ✅ **Source Code**: Full access on GitHub- ✅ **Updates**: Regular security updates- ✅ **License**: MIT (commercial use allowed)@@ -938,15 +979,12 @@ We work with Fortune 500 companies, government agencies, and organizations of al## 🚀 Roadmap-### Version 1.5 (Next)-- [ ] **TAXII pagination** — pull large collections beyond the first objects page-- [ ] **Broader CPE coverage** — grow the curated CPE table and add vendor-scheme translation for heuristic matches-- [ ] **MISP attribute-type expansion** — support more attribute types beyond ip-dst/domain/url/md5/sha256-- [ ] **SIEM live streaming** — ship NDJSON/CEF events directly to HTTP Event Collectors (HEC) instead of files-- [ ] **Remote module execution** — fan out detection/forensics functions for fleet-wide scans-- [ ] **Alert state dedup** — suppress repeat alerts across scheduled scan runs-- [ ] **Sysmon-native analytics** — deeper detections from Sysmon process/network events-- [ ] **$MFT / USN journal parsing** — file-system timeline evidence for the Forensics module+### Version 1.6 (Next)+- [ ] **Locale-invariant parsing** — make `auditpol` / `net accounts` parsing robust on non-English Windows+- [ ] **Raw $MFT record parsing** — go beyond fsutil summary output for full file-system timelines+- [ ] **JEA endpoint support** — run remote scans through Just Enough Administration constrained endpoints+- [ ] **Alert webhook DPAPI protection** — encrypt stored webhook URLs at rest+- [ ] **SIEM streaming auth profiles** — named credential profiles and OAuth flows for Send-SiemEvent### Version 2.0 (Future)- [ ] Web-based GUI dashboarddiff --git a/Response/Export-SecurityReport.ps1 b/Response/Export-SecurityReport.ps1index 1f9ffe1..dd84cab 100644--- a/Response/Export-SecurityReport.ps1+++ b/Response/Export-SecurityReport.ps1@@ -6,6 +6,11 @@ function Export-SecurityReport {Creates detailed security reports in multiple formats (HTML, JSON, CSV, NDJSON, CEF)with findings, recommendations, and executive summaries. NDJSON and CEF formatsproduce SIEM-ready finding exports via ConvertTo-SiemEvent (.ndjson / .cef files).+ When -StreamTo is specified, findings are additionally streamed live to a SIEM+ HTTP endpoint (Splunk HEC, Microsoft Sentinel, or a generic webhook) via+ Send-SiemEvent after the report files are written. A streaming failure never+ fails report generation; the outcome is noted on the console and in the+ StreamResult property of the output..PARAMETER ReportTypeType of report: Executive, Technical, or Compliance.PARAMETER Format@@ -17,12 +22,26 @@ function Export-SecurityReport {.PARAMETER NoAutoOpenDo not automatically open the HTML report after generation.Use for headless or SYSTEM-context runs where no interactive session exists.+ .PARAMETER StreamTo+ Optional SIEM destination type to stream findings to after the report files are+ written: SplunkHEC, Sentinel, or GenericWebhook. Requires -StreamUri.+ .PARAMETER StreamUri+ SIEM endpoint URL used with -StreamTo.+ .PARAMETER StreamToken+ Credential for the streaming endpoint (Splunk HEC token or Sentinel shared key).+ Sent only in request headers, never logged in full.+ .PARAMETER StreamFormat+ Event format for streaming: NDJSON (default) or CEF..EXAMPLEExport-SecurityReport -ReportType Technical -Format HTML -OutputPath "C:\Reports"Export-SecurityReport -ReportType Executive -Format All -IncludeChartsExport-SecurityReport -ReportType Technical -Format NDJSON -NoAutoOpen+ Export-SecurityReport -ReportType Technical -Format JSON -NoAutoOpen -StreamTo SplunkHEC -StreamUri "https://splunk.contoso.com:8088/services/collector" -StreamToken $hecToken.OUTPUTS- String path to generated report+ String path(s) to generated report files. When -StreamTo is specified, returns a+ PSCustomObject with Files (string array) and StreamResult (PSCustomObject with+ BatchesSent, EventsSent, Failed, DurationSec; $null if streaming did not run)+ properties.#>[CmdletBinding()]@@ -42,7 +61,21 @@ function Export-SecurityReport {[switch]$IncludeCharts,[Parameter()]- [switch]$NoAutoOpen+ [switch]$NoAutoOpen,++ [Parameter()]+ [ValidateSet('SplunkHEC', 'Sentinel', 'GenericWebhook')]+ [string]$StreamTo,++ [Parameter()]+ [string]$StreamUri,++ [Parameter()]+ [string]$StreamToken,++ [Parameter()]+ [ValidateSet('NDJSON', 'CEF')]+ [string]$StreamFormat = 'NDJSON')begin {@@ -54,6 +87,7 @@ function Export-SecurityReport {$timestamp = Get-Date -Format 'yyyyMMdd_HHmmss'$reportBaseName = "SecurityReport_${ReportType}_$timestamp"+ $streamResult = $null}process {@@ -383,7 +417,31 @@ if ($highSeverityProcs.Count -gt 0) {$htmlContent | Out-File $htmlPath -Encoding UTF8$generatedFiles += $htmlPath}-++ if (-not [string]::IsNullOrWhiteSpace($StreamTo)) {+ Write-Host "Streaming findings to $StreamTo endpoint..." -ForegroundColor Yellow+ try {+ if ([string]::IsNullOrWhiteSpace($StreamUri)) {+ Write-Warning "StreamTo was specified without StreamUri; skipping SIEM streaming."+ }+ else {+ $streamParams = @{+ Destination = $StreamTo+ Uri = $StreamUri+ Format = $StreamFormat+ }+ if (-not [string]::IsNullOrWhiteSpace($StreamToken)) {+ $streamParams['Token'] = $StreamToken+ }+ $streamResult = @($reportData.Findings) | Send-SiemEvent @streamParams+ Write-Host "Streamed $($streamResult.EventsSent) of $(@($reportData.Findings).Count) finding event(s) to $StreamTo ($($streamResult.Failed) failed)." -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "SIEM streaming failed; report files were still generated: $_"+ }+ }+}catch {Write-Error "Error generating report: $_"@@ -397,6 +455,15 @@ if ($highSeverityProcs.Count -gt 0) {foreach ($file in $generatedFiles) {Write-Host " - $file" -ForegroundColor White}++ if (-not [string]::IsNullOrWhiteSpace($StreamTo)) {+ if ($null -ne $streamResult) {+ Write-Host "SIEM Stream ($StreamTo): $($streamResult.EventsSent) event(s) sent in $($streamResult.BatchesSent) batch(es), $($streamResult.Failed) failed, $($streamResult.DurationSec)s" -ForegroundColor Cyan+ }+ else {+ Write-Host "SIEM Stream ($StreamTo): not delivered (see warnings above)" -ForegroundColor Yellow+ }+ }# Open HTML report if generatedif (-not $NoAutoOpen -and @($generatedFiles | Where-Object { $_ -match '\.html$' }).Count -gt 0) {@@ -409,6 +476,13 @@ if ($highSeverityProcs.Count -gt 0) {}}+ if (-not [string]::IsNullOrWhiteSpace($StreamTo)) {+ return [PSCustomObject]@{+ Files = $generatedFiles+ StreamResult = $streamResult+ }+ }+return $generatedFiles}}\ No newline at end of filediff --git a/Response/Send-SiemEvent.ps1 b/Response/Send-SiemEvent.ps1new file mode 100644index 0000000..615ddec--- /dev/null+++ b/Response/Send-SiemEvent.ps1@@ -0,0 +1,451 @@+function Send-SiemEvent {+ <#+ .SYNOPSIS+ Streams security findings directly to SIEM HTTP endpoints+ .DESCRIPTION+ Converts finding objects to NDJSON or CEF via ConvertTo-SiemEvent and streams them+ in batches to a SIEM HTTP endpoint: Splunk HTTP Event Collector (HEC), Microsoft+ Sentinel (Log Analytics Data Collector API), or a generic webhook.++ SplunkHEC wraps each NDJSON event one JSON object per line with+ {"time":<epoch>,"host":<host>,"sourcetype":"windowsecurityaudit:finding","event":{...}}+ and authenticates with the 'Splunk <token>' Authorization header. CEF events are+ delivered as the raw string value of the 'event' field.++ Sentinel posts a JSON array to the Log Analytics Data Collector API and builds the+ documented HMAC-SHA256 SharedKey signature from the string-to-sign+ "POST\n<contentLength>\napplication/json\nx-ms-date:<rfc1123date>\n/api/logs".+ -Token supplies the shared key; the workspace ID comes from -WorkspaceId or is+ parsed from the data collector endpoint in -Uri.++ GenericWebhook posts the raw NDJSON/CEF body with optional custom -Headers.++ Transient failures (HTTP 429 or 5xx) are retried per batch with exponential+ backoff up to -MaxRetries times; a batch that still fails is counted in Failed and+ streaming continues with the next batch. Tokens are never written to output in+ full: console output shows only the first four characters followed by '...'.+ Cleartext http:// endpoints are rejected when -Token is supplied, and warned+ about otherwise, so credentials are never sent unencrypted.++ Event timestamps reflect the UTC time of conversion (produced by+ ConvertTo-SiemEvent), not the time the finding was originally detected.+ .PARAMETER InputObject+ Finding object(s) to stream. Accepts pipeline input.+ .PARAMETER Format+ Event format: NDJSON (one compact JSON object per line) or CEF (CEF:0 string).+ .PARAMETER Destination+ Target endpoint type: SplunkHEC, Sentinel, or GenericWebhook.+ .PARAMETER Uri+ Endpoint URL. For Sentinel, either the full data collector URL+ (https://<workspaceId>.ods.opinsights.azure.com/api/logs?api-version=2016-04-01)+ or use -WorkspaceId with the same base URL.+ .PARAMETER Token+ Credential for the endpoint: the HEC token for SplunkHEC, the shared key for+ Sentinel. Sent only in request headers, never logged in full.+ .PARAMETER Headers+ Additional HTTP headers (hashtable), intended for GenericWebhook endpoints.+ .PARAMETER WorkspaceId+ Log Analytics workspace ID for Sentinel. Optional when the workspace ID can be+ parsed from -Uri.+ .PARAMETER LogType+ Log Analytics custom log type (Log-Type header) for Sentinel. Defaults to+ 'WindowsSecurityAudit'.+ .PARAMETER HostName+ Host value embedded in each event. Defaults to the local machine name.+ .PARAMETER BatchSize+ Number of events per HTTP POST. Defaults to 100.+ .PARAMETER MaxRetries+ Maximum retries per batch on transient errors (HTTP 429/5xx) with exponential+ backoff. Defaults to 3.+ .PARAMETER ThrottleMs+ Base delay in milliseconds between batches; also the base of the exponential+ retry backoff (ThrottleMs * 2^attempt). Defaults to 250.+ .EXAMPLE+ $report.Findings | Send-SiemEvent -Destination SplunkHEC -Uri "https://splunk.contoso.com:8088/services/collector" -Token $hecToken+ .EXAMPLE+ Find-SuspiciousProcesses | Send-SiemEvent -Destination Sentinel -Uri "https://<workspaceId>.ods.opinsights.azure.com/api/logs?api-version=2016-04-01" -Token $sharedKey+ .EXAMPLE+ $findings | Send-SiemEvent -Destination GenericWebhook -Uri "https://siem.contoso.com/ingest" -Format CEF -Headers @{ 'X-Api-Key' = $apiKey }+ .OUTPUTS+ PSCustomObject with BatchesSent, EventsSent, Failed, and DurationSec properties.+ #>++ [CmdletBinding()]+ param(+ [Parameter(Mandatory = $true, ValueFromPipeline = $true)]+ [AllowNull()]+ [object]$InputObject,++ [Parameter()]+ [ValidateSet('NDJSON', 'CEF')]+ [string]$Format = 'NDJSON',++ [Parameter(Mandatory = $true)]+ [ValidateSet('SplunkHEC', 'Sentinel', 'GenericWebhook')]+ [string]$Destination,++ [Parameter(Mandatory = $true)]+ [string]$Uri,++ [Parameter()]+ [string]$Token,++ [Parameter()]+ [hashtable]$Headers,++ [Parameter()]+ [string]$WorkspaceId,++ [Parameter()]+ [string]$LogType = 'WindowsSecurityAudit',++ [Parameter()]+ [string]$HostName = [Environment]::MachineName,++ [Parameter()]+ [ValidateRange(1, 10000)]+ [int]$BatchSize = 100,++ [Parameter()]+ [ValidateRange(0, 10)]+ [int]$MaxRetries = 3,++ [Parameter()]+ [ValidateRange(0, 60000)]+ [int]$ThrottleMs = 250+ )++ begin {+ function ConvertTo-MaskedToken {+ param([AllowNull()][string]$Secret)+ if ([string]::IsNullOrEmpty($Secret)) { return '(not provided)' }+ if ($Secret.Length -le 4) { return '****' }+ return ($Secret.Substring(0, 4) + '...')+ }++ function Get-UnixEpochSeconds {+ param([AllowNull()][object]$Timestamp)+ $unixEpoch = [DateTimeOffset]'1970-01-01T00:00:00Z'+ $parsed = $null+ if ($null -ne $Timestamp) {+ try {+ $parsed = [DateTimeOffset]::Parse([string]$Timestamp, [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::AssumeUniversal)+ }+ catch {+ $parsed = $null+ }+ }+ if ($null -eq $parsed) { $parsed = [DateTimeOffset]::UtcNow }+ return [long][math]::Floor(($parsed.ToUniversalTime() - $unixEpoch).TotalSeconds)+ }++ function Get-HttpStatusCodeFromException {+ param([AllowNull()][object]$Exception)+ if ($null -eq $Exception) { return $null }+ $responseProp = $Exception.PSObject.Properties['Response']+ if ($null -eq $responseProp -or $null -eq $responseProp.Value) { return $null }+ $statusProp = $responseProp.Value.PSObject.Properties['StatusCode']+ if ($null -eq $statusProp -or $null -eq $statusProp.Value) { return $null }+ try {+ return [int]$statusProp.Value+ }+ catch {+ return $null+ }+ }++ function New-SentinelSharedKeySignature {+ param(+ [Parameter(Mandatory = $true)]+ [string]$WorkspaceId,+ [Parameter(Mandatory = $true)]+ [string]$SharedKey,+ [Parameter(Mandatory = $true)]+ [int]$ContentLength,+ [Parameter(Mandatory = $true)]+ [string]$Rfc1123Date+ )+ $stringToSign = "POST`n$ContentLength`napplication/json`nx-ms-date:$Rfc1123Date`n/api/logs"+ $keyBytes = [Convert]::FromBase64String($SharedKey)+ $hmac = New-Object System.Security.Cryptography.HMACSHA256 -ArgumentList (, $keyBytes)+ try {+ $signatureBytes = $hmac.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($stringToSign))+ }+ finally {+ $hmac.Dispose()+ }+ $signature = [Convert]::ToBase64String($signatureBytes)+ return "SharedKey ${WorkspaceId}:$signature"+ }++ Write-Host "Streaming findings to $Destination endpoint..." -ForegroundColor Cyan+ Write-Host " Endpoint: $Uri" -ForegroundColor Yellow+ Write-Host " Format: $Format | Batch size: $BatchSize | Max retries: $MaxRetries" -ForegroundColor Yellow+ if (-not [string]::IsNullOrWhiteSpace($Token)) {+ Write-Host " Token: $(ConvertTo-MaskedToken -Secret $Token)" -ForegroundColor Yellow+ }++ try {+ [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12+ }+ catch {+ Write-Verbose "Could not enforce TLS 1.2: $_"+ }++ $validatedUri = $null+ if (-not [System.Uri]::TryCreate($Uri, [System.UriKind]::Absolute, [ref]$validatedUri) -or ($validatedUri.Scheme -ne 'https' -and $validatedUri.Scheme -ne 'http')) {+ Write-Error "Uri '$Uri' is not a valid absolute HTTP(S) endpoint."+ throw "Invalid SIEM endpoint Uri."+ }++ if ($validatedUri.Scheme -eq 'http') {+ if (-not [string]::IsNullOrWhiteSpace($Token)) {+ Write-Error "Refusing to send -Token credentials to the cleartext HTTP endpoint '$Uri'. Use HTTPS."+ throw "Cleartext HTTP endpoint rejected."+ }+ Write-Warning "Endpoint '$Uri' uses cleartext HTTP; event data and any custom headers (including API keys) will be sent unencrypted."+ }++ if ($Destination -eq 'SplunkHEC' -and [string]::IsNullOrWhiteSpace($Token)) {+ Write-Error "SplunkHEC requires -Token (HEC token) for the 'Splunk <token>' Authorization header."+ throw "Missing Splunk HEC token."+ }++ if ($Destination -eq 'Sentinel') {+ if ([string]::IsNullOrWhiteSpace($Token)) {+ Write-Error "Sentinel requires -Token containing the Log Analytics shared key."+ throw "Missing Sentinel shared key."+ }+ if ([string]::IsNullOrWhiteSpace($WorkspaceId)) {+ $workspaceMatch = [regex]::Match($Uri, '^https?://([A-Za-z0-9-]+)\.ods\.opinsights\.azure\.')+ if ($workspaceMatch.Success) {+ $WorkspaceId = $workspaceMatch.Groups[1].Value+ }+ }+ if ([string]::IsNullOrWhiteSpace($WorkspaceId)) {+ Write-Error "Sentinel requires -WorkspaceId or a -Uri of the form https://<workspaceId>.ods.opinsights.azure.com/api/logs."+ throw "Missing Sentinel workspace ID."+ }+ }++ if ([string]::IsNullOrWhiteSpace($HostName)) {+ $HostName = 'unknown-host'+ }++ $staticHeaders = @{}+ if ($null -ne $Headers) {+ foreach ($headerName in @($Headers.Keys)) {+ $staticHeaders[$headerName] = $Headers[$headerName]+ }+ }+ if ($Destination -eq 'SplunkHEC') {+ $staticHeaders['Authorization'] = "Splunk $Token"+ }++ $contentType = 'application/x-ndjson; charset=utf-8'+ if ($Destination -eq 'SplunkHEC' -or $Destination -eq 'Sentinel') {+ $contentType = 'application/json'+ }+ elseif ($Destination -eq 'GenericWebhook' -and $Format -eq 'CEF') {+ $contentType = 'text/plain; charset=utf-8'+ }++ $pending = @()+ $batchesSent = 0+ $eventsSent = 0+ $failedEvents = 0+ $startTime = Get-Date+ }++ process {+ $pending += $InputObject+ }++ end {+ if (@($pending).Count -eq 0) {+ Write-Warning "No findings received; nothing to stream."+ return [PSCustomObject]@{+ BatchesSent = 0+ EventsSent = 0+ Failed = 0+ DurationSec = 0+ }+ }++ $eventLines = @($pending | ConvertTo-SiemEvent -Format $Format -HostName $HostName)+ $totalEvents = @($eventLines).Count++ if ($totalEvents -eq 0) {+ Write-Warning "No findings could be converted to $Format events; nothing to stream."+ return [PSCustomObject]@{+ BatchesSent = 0+ EventsSent = 0+ Failed = 0+ DurationSec = 0+ }+ }++ $totalBatches = [int][math]::Ceiling($totalEvents / $BatchSize)+ Write-Host "Sending $totalEvents event(s) in $totalBatches batch(es)..." -ForegroundColor Yellow++ for ($batchIndex = 0; $batchIndex -lt $totalBatches; $batchIndex++) {+ $batchNumber = $batchIndex + 1+ $rangeStart = $batchIndex * $BatchSize+ $rangeEnd = [math]::Min($rangeStart + $BatchSize, $totalEvents) - 1+ $batchLines = @($eventLines[$rangeStart..$rangeEnd])+ $batchCount = @($batchLines).Count++ $body = $null+ $bodyBytes = $null+ $requestHeaders = @{}+ foreach ($headerName in @($staticHeaders.Keys)) {+ $requestHeaders[$headerName] = $staticHeaders[$headerName]+ }++ try {+ switch ($Destination) {+ 'SplunkHEC' {+ $hecLines = @()+ foreach ($line in $batchLines) {+ $eventObject = $null+ $eventTime = $null+ $eventHost = $HostName+ if ($Format -eq 'NDJSON') {+ try {+ $eventObject = ($line | ConvertFrom-Json -ErrorAction Stop)+ }+ catch {+ $eventObject = $null+ }+ }+ if ($null -ne $eventObject) {+ $timestampProp = $eventObject.PSObject.Properties['timestamp']+ if ($null -ne $timestampProp -and $null -ne $timestampProp.Value) {+ $eventTime = $timestampProp.Value+ }+ $hostProp = $eventObject.PSObject.Properties['host']+ if ($null -ne $hostProp -and -not [string]::IsNullOrWhiteSpace([string]$hostProp.Value)) {+ $eventHost = [string]$hostProp.Value+ }+ $hecLines += ([ordered]@{+ time = (Get-UnixEpochSeconds -Timestamp $eventTime)+ host = $eventHost+ sourcetype = 'windowsecurityaudit:finding'+ event = $eventObject+ } | ConvertTo-Json -Compress -Depth 10)+ }+ else {+ $hecLines += ([ordered]@{+ time = (Get-UnixEpochSeconds -Timestamp $null)+ host = $eventHost+ sourcetype = 'windowsecurityaudit:finding'+ event = $line+ } | ConvertTo-Json -Compress -Depth 10)+ }+ }+ $body = ($hecLines -join "`n")+ }+ 'Sentinel' {+ if ($Format -eq 'NDJSON') {+ $body = '[' + ($batchLines -join ',') + ']'+ }+ else {+ $cefObjects = @()+ foreach ($line in $batchLines) {+ $cefObjects += ([ordered]@{+ timestamp = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ')+ host = $HostName+ message = $line+ } | ConvertTo-Json -Compress -Depth 5)+ }+ $body = '[' + ($cefObjects -join ',') + ']'+ }+ $bodyBytes = [System.Text.Encoding]::UTF8.GetBytes($body)+ $rfc1123Date = [DateTime]::UtcNow.ToString('r', [System.Globalization.CultureInfo]::InvariantCulture)+ $requestHeaders['Authorization'] = New-SentinelSharedKeySignature -WorkspaceId $WorkspaceId -SharedKey $Token -ContentLength $bodyBytes.Length -Rfc1123Date $rfc1123Date+ $requestHeaders['x-ms-date'] = $rfc1123Date+ $requestHeaders['Log-Type'] = $LogType+ }+ 'GenericWebhook' {+ $body = ($batchLines -join "`n")+ }+ }+ }+ catch {+ Write-Error "Failed to build $Destination request payload: $_"+ throw+ }++ $requestParams = @{+ Uri = $Uri+ Method = 'Post'+ ContentType = $contentType+ TimeoutSec = 100+ UseBasicParsing = $true+ ErrorAction = 'Stop'+ }+ if ($null -ne $bodyBytes) {+ $requestParams['Body'] = $bodyBytes+ }+ else {+ $requestParams['Body'] = $body+ }+ if ($requestHeaders.Count -gt 0) {+ $requestParams['Headers'] = $requestHeaders+ }+ if ($requestHeaders.ContainsKey('Content-Type')) {+ $requestParams.Remove('ContentType')+ }++ $attempt = 0+ $delivered = $false+ $lastErrorMessage = ''+ while (-not $delivered -and $attempt -le $MaxRetries) {+ $attempt+++ try {+ $null = Invoke-RestMethod @requestParams+ $delivered = $true+ }+ catch {+ $lastErrorMessage = $_.Exception.Message+ $statusCode = Get-HttpStatusCodeFromException -Exception $_.Exception+ $isTransient = ($null -ne $statusCode) -and (($statusCode -eq 429) -or ($statusCode -ge 500 -and $statusCode -le 599))+ if ($isTransient -and $attempt -le $MaxRetries) {+ $backoffMs = $ThrottleMs * [int][math]::Pow(2, $attempt)+ Write-Warning "Batch $batchNumber transient failure (HTTP $statusCode); retry $attempt of $MaxRetries in $backoffMs ms."+ if ($backoffMs -gt 0) {+ Start-Sleep -Milliseconds $backoffMs+ }+ }+ else {+ break+ }+ }+ }++ if ($delivered) {+ $batchesSent+++ $eventsSent += $batchCount+ Write-Verbose "Batch $batchNumber of $totalBatches delivered ($batchCount event(s))."+ }+ else {+ $failedEvents += $batchCount+ Write-Warning "Batch $batchNumber of $totalBatches failed after $attempt attempt(s) and was skipped: $lastErrorMessage"+ }++ if ($batchIndex -lt ($totalBatches - 1) -and $ThrottleMs -gt 0) {+ Start-Sleep -Milliseconds $ThrottleMs+ }+ }++ $durationSec = [math]::Round(((Get-Date) - $startTime).TotalSeconds, 2)+ Write-Host "SIEM stream complete: $eventsSent event(s) sent in $batchesSent batch(es); $failedEvents event(s) failed ($durationSec s)." -ForegroundColor Green++ return [PSCustomObject]@{+ BatchesSent = $batchesSent+ EventsSent = $eventsSent+ Failed = $failedEvents+ DurationSec = $durationSec+ }+ }+}diff --git a/ThreatHunting/Get-ThreatIntelligence.ps1 b/ThreatHunting/Get-ThreatIntelligence.ps1index a56fd29..2854d1a 100644--- a/ThreatHunting/Get-ThreatIntelligence.ps1+++ b/ThreatHunting/Get-ThreatIntelligence.ps1@@ -27,12 +27,14 @@ function Get-ThreatIntelligence {Optional AbuseIPDB API key; enables the AbuseIPDB blacklist feed (sent only as a request header).PARAMETER MISPUrlBase URL of a MISP instance (requires -MISPApiKey); attributes are pulled via attributes/restSearch+ (types: ip-dst, domain, hostname, url, uri, md5, sha1, sha256, email-src, email-dst, filename, mutex).PARAMETER MISPApiKeyMISP API auth key (requires -MISPUrl); sent only as the Authorization request header and never logged.PARAMETER TaxiiServerUrlBase URL of a TAXII 2.x server (requires -TaxiiCollection); indicator objects are pulled from the collection.PARAMETER TaxiiCollection- TAXII collection ID or title to pull STIX indicators from (requires -TaxiiServerUrl)+ TAXII collection ID or title to pull STIX indicators from (requires -TaxiiServerUrl);+ paginated envelopes are followed automatically via the 'more'/'next' pattern (up to 20 pages).PARAMETER TaxiiUsernameOptional TAXII username; sent only as a Basic auth request header together with -TaxiiPassword.PARAMETER TaxiiPassword@@ -173,6 +175,12 @@ function Get-ThreatIntelligence {)NetworkIndicators = @()++ EmailIndicators = @()++ FileNameIndicators = @()++ MutexIndicators = @()}}@@ -180,6 +188,9 @@ function Get-ThreatIntelligence {$feedStats = @()$feedEntryCount = 0$networkIndicatorKeys = @{}+ $emailIndicatorKeys = @{}+ $fileNameIndicatorKeys = @{}+ $mutexIndicatorKeys = @{}$mispEnabled = $falseif (-not [string]::IsNullOrWhiteSpace($MISPUrl) -or -not [string]::IsNullOrWhiteSpace($MISPApiKey)) {@@ -266,7 +277,7 @@ function Get-ThreatIntelligence {}}}- elseif ($Kind -eq 'md5' -or $Kind -eq 'sha256') {+ elseif ($Kind -eq 'md5' -or $Kind -eq 'sha1' -or $Kind -eq 'sha256') {$hashValue = $Value.ToLower()if ($hashValue -notmatch '^[0-9a-f]+$') { return 0 }if (-not $iocDatabase.MaliciousHashes.ContainsKey($hashValue)) {@@ -275,6 +286,34 @@ function Get-ThreatIntelligence {return 1}}+ elseif ($Kind -eq 'email') {+ if ($Value -notmatch '^[^@\s]+@[^@\s]+$') { return 0 }+ $escapedEmail = [regex]::Escape($Value)+ if (-not $emailIndicatorKeys.ContainsKey($escapedEmail)) {+ $emailIndicatorKeys[$escapedEmail] = $true+ $iocDatabase.SuspiciousPatterns.EmailIndicators += @{ Pattern = $escapedEmail; Severity = $Severity; Description = $Description }+ $feedEntryCount+++ return 1+ }+ }+ elseif ($Kind -eq 'filename') {+ if ($Value -match '[\\/]') { return 0 }+ $escapedFileName = [regex]::Escape($Value)+ if (-not $fileNameIndicatorKeys.ContainsKey($escapedFileName)) {+ $fileNameIndicatorKeys[$escapedFileName] = $true+ $iocDatabase.SuspiciousPatterns.FileNameIndicators += @{ Pattern = $escapedFileName; Severity = $Severity; Description = $Description }+ $feedEntryCount+++ return 1+ }+ }+ elseif ($Kind -eq 'mutex') {+ if (-not $mutexIndicatorKeys.ContainsKey($Value)) {+ $mutexIndicatorKeys[$Value] = $true+ $iocDatabase.SuspiciousPatterns.MutexIndicators += @{ Name = $Value; Severity = $Severity; Description = "$Description (cataloged only - no live mutex check)" }+ $feedEntryCount+++ return 1+ }+ }return 0}@@ -480,7 +519,7 @@ function Get-ThreatIntelligence {Write-Host " Querying MISP instance at $MISPUrl..." -ForegroundColor Yellow$mispBody = @{returnFormat = 'json'- type = @('ip-dst', 'domain', 'url', 'md5', 'sha256')+ type = @('ip-dst', 'domain', 'hostname', 'url', 'uri', 'md5', 'sha1', 'sha256', 'email-src', 'email-dst', 'filename', 'mutex')to_ids = 'yes'} | 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 Stop@@ -537,11 +576,18 @@ function Get-ThreatIntelligence {$indicatorKind = $nullswitch ($attributeType) {- 'ip-dst' { $indicatorKind = 'ip' }- 'domain' { $indicatorKind = 'domain' }- 'url' { $indicatorKind = 'url' }- 'md5' { $indicatorKind = 'md5' }- 'sha256' { $indicatorKind = 'sha256' }+ 'ip-dst' { $indicatorKind = 'ip' }+ 'domain' { $indicatorKind = 'domain' }+ 'hostname' { $indicatorKind = 'domain' }+ 'url' { $indicatorKind = 'url' }+ 'uri' { $indicatorKind = 'url' }+ 'md5' { $indicatorKind = 'md5' }+ 'sha1' { $indicatorKind = 'sha1' }+ 'sha256' { $indicatorKind = 'sha256' }+ 'email-src' { $indicatorKind = 'email' }+ 'email-dst' { $indicatorKind = 'email' }+ 'filename' { $indicatorKind = 'filename' }+ 'mutex' { $indicatorKind = 'mutex' }}if ($null -eq $indicatorKind) {Write-Verbose "Skipping unsupported MISP attribute type: $attributeType"@@ -570,6 +616,8 @@ function Get-ThreatIntelligence {$taxiiObjects = $null$taxiiSource = 'none'$taxiiCacheAgeHours = $null+ $taxiiPagesFetched = 0+ $taxiiMaxPages = 20$taxiiCacheExists = Test-Path $taxiiCacheFileif ($taxiiCacheExists) {@@ -620,10 +668,33 @@ function Get-ThreatIntelligence {}if ($null -eq $targetCollectionId) { throw "TAXII collection '$TaxiiCollection' not found on server" }- $objectsResponse = Invoke-RestMethod -Method Get -Uri "$apiRoot/collections/$targetCollectionId/objects?types=indicator" -Headers $taxiiHeaders -TimeoutSec 60 -ErrorAction Stop$taxiiObjects = @()- if ($null -ne $objectsResponse -and $objectsResponse.PSObject.Properties['objects'] -and $null -ne $objectsResponse.objects) {- $taxiiObjects = @($objectsResponse.objects)+ $taxiiNextToken = $null+ $taxiiMorePages = $true+ while ($taxiiMorePages -and $taxiiPagesFetched -lt $taxiiMaxPages) {+ $objectsUri = "$apiRoot/collections/$targetCollectionId/objects?types=indicator"+ if (-not [string]::IsNullOrWhiteSpace($taxiiNextToken)) {+ $objectsUri += "&next=$([System.Uri]::EscapeDataString($taxiiNextToken))"+ }+ $objectsResponse = Invoke-RestMethod -Method Get -Uri $objectsUri -Headers $taxiiHeaders -TimeoutSec 60 -ErrorAction Stop+ $taxiiPagesFetched+++ if ($null -ne $objectsResponse -and $objectsResponse.PSObject.Properties['objects'] -and $null -ne $objectsResponse.objects) {+ $taxiiObjects += @($objectsResponse.objects)+ }+ $taxiiMorePages = $false+ if ($null -ne $objectsResponse -and $objectsResponse.PSObject.Properties['more'] -and $true -eq $objectsResponse.more) {+ $nextPageToken = if ($objectsResponse.PSObject.Properties['next']) { [string]$objectsResponse.next } else { $null }+ if (-not [string]::IsNullOrWhiteSpace($nextPageToken)) {+ $taxiiNextToken = $nextPageToken+ $taxiiMorePages = $true+ }+ else {+ Write-Warning "TAXII server indicated more pages but returned no 'next' token - stopping pagination"+ }+ }+ }+ 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$taxiiSource = 'download'@@ -679,6 +750,8 @@ function Get-ThreatIntelligence {$feedStats += [PSCustomObject]@{Feed = 'TAXII'EntryCount = $taxiiEntriesAdded+ ObjectsFetched = if ($null -ne $taxiiObjects) { @($taxiiObjects).Count } else { 0 }+ PagesFetched = $taxiiPagesFetchedCacheAgeHours = $taxiiCacheAgeHoursSource = $taxiiSource}@@ -850,6 +923,39 @@ function Get-ThreatIntelligence {break}}++ # Check against feed-derived email indicators (heuristic: malicious mailboxes can appear in commands)+ foreach ($pattern in $iocDatabase.SuspiciousPatterns.EmailIndicators) {+ if ($process.CommandLine -match $pattern.Pattern) {+ $match = [PSCustomObject]@{+ Type = 'Process'+ IOCType = 'FeedEmailIndicator'+ Indicator = $pattern.Pattern+ ProcessId = $process.ProcessId+ ProcessName = $process.Name+ CommandLine = if ($process.CommandLine.Length -gt 200) {+ $process.CommandLine.Substring(0, 200) + "..."+ } else {+ $process.CommandLine+ }+ Severity = $pattern.Severity+ Description = $pattern.Description+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.Matches.ProcessIOCs += $match+ $foundCount++++ switch ($pattern.Severity) {+ 'Critical' { $results.Summary.CriticalMatches++ }+ 'High' { $results.Summary.HighMatches++ }+ 'Medium' { $results.Summary.MediumMatches++ }+ }++ Write-Host " [!] MATCH: Email indicator '$($pattern.Pattern)' in $($process.Name)" -ForegroundColor Red+ break+ }+ }}}@@ -999,6 +1105,36 @@ function Get-ThreatIntelligence {break}}++ # Check file name against feed-derived filename indicators+ foreach ($pattern in $iocDatabase.SuspiciousPatterns.FileNameIndicators) {+ if ($file.Name -match $pattern.Pattern) {+ $match = [PSCustomObject]@{+ Type = 'File'+ IOCType = 'FeedFileNameIndicator'+ Indicator = $pattern.Pattern+ FilePath = $file.FullName+ FileName = $file.Name+ Size = $file.Length+ Created = $file.CreationTime.ToString("yyyy-MM-dd HH:mm:ss")+ Severity = $pattern.Severity+ Description = $pattern.Description+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.Matches.FileIOCs += $match+ $foundCount++++ switch ($pattern.Severity) {+ 'Critical' { $results.Summary.CriticalMatches++ }+ 'High' { $results.Summary.HighMatches++ }+ 'Medium' { $results.Summary.MediumMatches++ }+ }++ Write-Host " [!] MATCH: Filename indicator '$($file.Name)'" -ForegroundColor Red+ break+ }+ }}}}@@ -1170,7 +1306,11 @@ function Get-ThreatIntelligence {Write-Host "`nThreat Intelligence Feeds:" -ForegroundColor Cyanforeach ($stat in $results.Summary.FeedStats) {$ageText = if ($null -ne $stat.CacheAgeHours) { "$($stat.CacheAgeHours)h old" } else { 'not cached' }- Write-Host " - $($stat.Feed): $($stat.EntryCount) entries ($($stat.Source), $ageText)" -ForegroundColor Gray+ $pageText = ''+ if ($stat.PSObject.Properties['PagesFetched'] -and $null -ne $stat.PagesFetched -and $stat.PagesFetched -gt 0) {+ $pageText = ", $($stat.PagesFetched) page(s)"+ }+ Write-Host " - $($stat.Feed): $($stat.EntryCount) entries ($($stat.Source)$pageText, $ageText)" -ForegroundColor Gray}}diff --git a/Vulnerability/Resolve-CpeName.ps1 b/Vulnerability/Resolve-CpeName.ps1index 1287c37..d5b313b 100644--- a/Vulnerability/Resolve-CpeName.ps1+++ b/Vulnerability/Resolve-CpeName.ps1@@ -6,7 +6,18 @@ function Resolve-CpeName {Maps an installed software product (registry DisplayName / Publisher /DisplayVersion) to a CPE 2.3 formatted string. Resolution strategy, in order:1. A built-in curated mapping table of common products with known- vendor/product CPE tokens (works fully offline).+ vendor/product CPE tokens (works fully offline). When a curated+ entry declares a version-scheme translator (Java, .NET Framework,+ Chrome-style, Python, Qt-based applications), the normalized+ registry version is translated into the scheme NVD uses for that+ vendor's CPEs before the CPE is built. A translation only fires+ when the scheme actually changes the value; otherwise the version+ passes through untouched. This prevents downstream NVD queries+ from returning NoMatch purely because of the version format+ (e.g. Java '1.8.0_391' vs NVD '8.0.391'). Translated matches are+ reported with MatchedBy 'SchemeTranslation', Confidence Medium and+ the untouched registry value in OriginalVersion. The translators+ are heuristics based on documented vendor versioning conventions.2. An optional online lookup against the NVD CPE API 2.0(keywordSearch) when -UseOnlineLookup and -ApiKey are supplied.Applies the same TLS 1.2 and rate-limit conventions as@@ -18,6 +29,11 @@ function Resolve-CpeName {trailing '.0' segments are preserved so version-exact queries stayexact) and embedded as the version component ofcpe:2.3:a:vendor:product:version:*:*:*:*:*:*:*+ Capability limits: every resolved CPE uses the application part+ ('a'); a few curated entries (e.g. VMware ESXi, which NVD classifies+ as an operating system) may belong to a different CPE part and are+ best-effort hints. Curated vendor/product tokens are maintained by+ hand and can drift from NVD naming over time..PARAMETER ProductNameProduct display name, e.g. the registry DisplayName value.PARAMETER Vendor@@ -32,9 +48,14 @@ function Resolve-CpeName {Resolve-CpeName -ProductName "Google Chrome" -Vendor "Google LLC" -Version "120.0.6099.130".EXAMPLEResolve-CpeName -ProductName "7-Zip 23.01 (x64)" -Version "23.01" -UseOnlineLookup -ApiKey $key+ .EXAMPLE+ Resolve-CpeName -ProductName "Java SE Development Kit 8 Update 391" -Vendor "Oracle" -Version "1.8.0_391"+ Translates the legacy Java version scheme and returns+ cpe:2.3:a:oracle:jdk:8.0.391:*:*:*:*:*:*:* with MatchedBy 'SchemeTranslation'.OUTPUTS- PSCustomObject with CpeName, MatchedBy (CuratedTable/OnlineLookup/Heuristic/None),- Confidence (High/Medium/Low) and Version+ PSCustomObject with CpeName, MatchedBy (CuratedTable/SchemeTranslation/+ OnlineLookup/Heuristic/None), Confidence (High/Medium/Low), Version and+ OriginalVersion (the raw registry version string, empty when not supplied)#>[CmdletBinding()]@@ -76,47 +97,168 @@ function Resolve-CpeName {# Curated mapping table: ordered, most specific first.# Patterns are matched as case-insensitive substrings of the product name.+ # 'Scheme' marks entries whose vendor CPE version scheme differs from the+ # raw registry version format; see $schemeTranslators below.$curatedTable = @(@{ Patterns = @('Adobe Acrobat Reader DC', 'Acrobat Reader DC'); Vendor = 'adobe'; Product = 'acrobat_reader_dc'; PublisherHints = @('Adobe') }+ @{ Patterns = @('Adobe Photoshop'); Vendor = 'adobe'; Product = 'photoshop'; PublisherHints = @('Adobe') }+ @{ Patterns = @('Adobe Illustrator'); Vendor = 'adobe'; Product = 'illustrator'; PublisherHints = @('Adobe') }+ @{ Patterns = @('Adobe Premiere Pro'); Vendor = 'adobe'; Product = 'premiere_pro'; PublisherHints = @('Adobe') }+ @{ Patterns = @('Adobe After Effects'); Vendor = 'adobe'; Product = 'after_effects'; PublisherHints = @('Adobe') }+ @{ Patterns = @('Adobe InDesign'); Vendor = 'adobe'; Product = 'indesign'; PublisherHints = @('Adobe') }+ @{ Patterns = @('Adobe Lightroom'); Vendor = 'adobe'; Product = 'lightroom'; PublisherHints = @('Adobe') }+ @{ Patterns = @('Adobe Creative Cloud'); Vendor = 'adobe'; Product = 'creative_cloud'; PublisherHints = @('Adobe') }@{ Patterns = @('Adobe Acrobat'); Vendor = 'adobe'; Product = 'acrobat'; PublisherHints = @('Adobe') }- @{ Patterns = @('Google Chrome'); Vendor = 'google'; Product = 'chrome'; PublisherHints = @('Google') }+ @{ Patterns = @('Google Chrome'); Vendor = 'google'; Product = 'chrome'; PublisherHints = @('Google'); Scheme = 'Chrome' }@{ Patterns = @('Mozilla Firefox'); Vendor = 'mozilla'; Product = 'firefox'; PublisherHints = @('Mozilla') }@{ Patterns = @('Mozilla Thunderbird'); Vendor = 'mozilla'; Product = 'thunderbird'; PublisherHints = @('Mozilla') }- @{ Patterns = @('Microsoft Edge'); Vendor = 'microsoft'; Product = 'edge'; PublisherHints = @('Microsoft') }+ @{ Patterns = @('Microsoft Edge'); Vendor = 'microsoft'; Product = 'edge'; PublisherHints = @('Microsoft'); Scheme = 'Chrome' }+ @{ Patterns = @('Brave'); Vendor = 'brave'; Product = 'brave'; PublisherHints = @('Brave'); Scheme = 'Chrome' }+ @{ Patterns = @('Opera'); Vendor = 'opera'; Product = 'opera'; PublisherHints = @('Opera'); Scheme = 'Chrome' }@{ Patterns = @('Microsoft Office', 'Microsoft 365'); Vendor = 'microsoft'; Product = 'office'; PublisherHints = @('Microsoft') }@{ Patterns = @('Microsoft SQL Server'); Vendor = 'microsoft'; Product = 'sql_server'; PublisherHints = @('Microsoft') }+ @{ Patterns = @('Visual Studio Code'); Vendor = 'microsoft'; Product = 'visual_studio_code'; PublisherHints = @('Microsoft') }@{ Patterns = @('Microsoft Visual Studio'); Vendor = 'microsoft'; Product = 'visual_studio'; PublisherHints = @('Microsoft') }- @{ Patterns = @('7-Zip'); Vendor = '7-zip'; Product = '7-zip'; PublisherHints = @('Igor Pavlov', '7-Zip') }- @{ Patterns = @('Java SE Development Kit', 'JDK'); Vendor = 'oracle'; Product = 'jdk'; PublisherHints = @('Oracle') }- @{ Patterns = @('Java(TM)', 'Java 8', 'Java(TM) SE Runtime', 'Java Runtime'); Vendor = 'oracle'; Product = 'jre'; PublisherHints = @('Oracle') }- @{ Patterns = @('Python'); Vendor = 'python'; Product = 'python'; PublisherHints = @('Python Software Foundation') }+ @{ Patterns = @('Visual C++'); Vendor = 'microsoft'; Product = 'visual_c++'; PublisherHints = @('Microsoft') }+ @{ Patterns = @('Microsoft .NET Framework'); Vendor = 'microsoft'; Product = '.net_framework'; PublisherHints = @('Microsoft'); Scheme = 'DotNet' }+ @{ Patterns = @('Microsoft .NET'); Vendor = 'microsoft'; Product = '.net'; PublisherHints = @('Microsoft') }+ @{ Patterns = @('PowerShell'); Vendor = 'microsoft'; Product = 'powershell'; PublisherHints = @('Microsoft') }+ @{ Patterns = @('Microsoft Teams'); Vendor = 'microsoft'; Product = 'teams'; PublisherHints = @('Microsoft') }+ @{ Patterns = @('Azure CLI'); Vendor = 'microsoft'; Product = 'azure_cli'; PublisherHints = @('Microsoft') }+ @{ Patterns = @('Sysinternals'); Vendor = 'microsoft'; Product = 'sysinternals'; PublisherHints = @('Microsoft') }+ @{ Patterns = @('Microsoft OpenJDK'); Vendor = 'microsoft'; Product = 'openjdk'; PublisherHints = @('Microsoft'); Scheme = 'Java' }+ @{ Patterns = @('Eclipse Temurin', 'AdoptOpenJDK'); Vendor = 'eclipse'; Product = 'temurin'; PublisherHints = @('Eclipse', 'Adoptium'); Scheme = 'Java' }+ @{ Patterns = @('Amazon Corretto'); Vendor = 'amazon'; Product = 'corretto'; PublisherHints = @('Amazon'); Scheme = 'Java' }+ @{ Patterns = @('Azul Zulu'); Vendor = 'azul'; Product = 'zulu'; PublisherHints = @('Azul'); Scheme = 'Java' }+ @{ Patterns = @('Java SE Development Kit', 'JDK'); Vendor = 'oracle'; Product = 'jdk'; PublisherHints = @('Oracle'); Scheme = 'Java' }+ @{ Patterns = @('Java(TM)', 'Java 8', 'Java(TM) SE Runtime', 'Java Runtime'); Vendor = 'oracle'; Product = 'jre'; PublisherHints = @('Oracle'); Scheme = 'Java' }+ @{ Patterns = @('Miniconda'); Vendor = 'anaconda'; Product = 'miniconda'; PublisherHints = @('Anaconda') }+ @{ Patterns = @('Anaconda'); Vendor = 'anaconda'; Product = 'anaconda'; PublisherHints = @('Anaconda') }+ @{ Patterns = @('Python'); Vendor = 'python'; Product = 'python'; PublisherHints = @('Python Software Foundation'); Scheme = 'Python' }@{ Patterns = @('Node.js'); Vendor = 'nodejs'; Product = 'node.js'; PublisherHints = @('Node.js', 'OpenJS') }- @{ Patterns = @('PuTTY'); Vendor = 'putty'; Product = 'putty'; PublisherHints = @('Simon Tatham') }- @{ Patterns = @('WinRAR'); Vendor = 'rarlab'; Product = 'winrar'; PublisherHints = @('win.rar', 'RARLAB') }+ @{ Patterns = @('RubyMine'); Vendor = 'jetbrains'; Product = 'rubymine'; PublisherHints = @('JetBrains') }+ @{ Patterns = @('Ruby'); Vendor = 'ruby-lang'; Product = 'ruby'; PublisherHints = @('Ruby') }+ @{ Patterns = @('PhpStorm'); Vendor = 'jetbrains'; Product = 'phpstorm'; PublisherHints = @('JetBrains') }+ @{ Patterns = @('PHP'); Vendor = 'php'; Product = 'php'; PublisherHints = @('The PHP Group') }+ @{ Patterns = @('Strawberry Perl'); Vendor = 'strawberryperl'; Product = 'strawberry_perl'; PublisherHints = @('Strawberry Perl') }+ @{ Patterns = @('Perl'); Vendor = 'perl'; Product = 'perl'; PublisherHints = @('Perl') }+ @{ Patterns = @('Go Programming Language', 'Golang'); Vendor = 'golang'; Product = 'go'; PublisherHints = @('Go') }+ @{ Patterns = @('Rustup', 'Rust Programming'); Vendor = 'rust-lang'; Product = 'rust'; PublisherHints = @('Rust') }+ @{ Patterns = @('IntelliJ IDEA'); Vendor = 'jetbrains'; Product = 'intellij_idea'; PublisherHints = @('JetBrains') }+ @{ Patterns = @('PyCharm'); Vendor = 'jetbrains'; Product = 'pycharm'; PublisherHints = @('JetBrains') }+ @{ Patterns = @('WebStorm'); Vendor = 'jetbrains'; Product = 'webstorm'; PublisherHints = @('JetBrains') }@{ Patterns = @('Notepad++'); Vendor = 'notepad-plus-plus'; Product = 'notepad++'; PublisherHints = @('Notepad++') }- @{ Patterns = @('VLC media player'); Vendor = 'videolan'; Product = 'vlc_media_player'; PublisherHints = @('VideoLAN') }- @{ Patterns = @('Wireshark'); Vendor = 'wireshark'; Product = 'wireshark'; PublisherHints = @('Wireshark') }- @{ Patterns = @('TortoiseGit'); Vendor = 'tortoisegit'; Product = 'tortoisegit'; PublisherHints = @('TortoiseGit') }- @{ Patterns = @('TortoiseSVN'); Vendor = 'tortoisesvn'; Product = 'tortoisesvn'; PublisherHints = @('TortoiseSVN') }- @{ Patterns = @('Git'); Vendor = 'git-scm'; Product = 'git'; PublisherHints = @('The Git Development Community') }+ @{ Patterns = @('Sublime Text'); Vendor = 'sublimetext'; Product = 'sublime_text'; PublisherHints = @('Sublime') }+ @{ Patterns = @('7-Zip'); Vendor = '7-zip'; Product = '7-zip'; PublisherHints = @('Igor Pavlov', '7-Zip') }+ @{ Patterns = @('WinRAR'); Vendor = 'rarlab'; Product = 'winrar'; PublisherHints = @('win.rar', 'RARLAB') }+ @{ Patterns = @('PuTTY'); Vendor = 'putty'; Product = 'putty'; PublisherHints = @('Simon Tatham') }+ @{ Patterns = @('KiTTY'); Vendor = 'kitty'; Product = 'kitty'; PublisherHints = @('9bis') }+ @{ Patterns = @('WinSCP'); Vendor = 'winscp'; Product = 'winscp'; PublisherHints = @('Martin Prikryl') }@{ Patterns = @('OpenSSH'); Vendor = 'openbsd'; Product = 'openssh'; PublisherHints = @('OpenBSD') }+ @{ Patterns = @('OpenVPN'); Vendor = 'openvpn'; Product = 'openvpn'; PublisherHints = @('OpenVPN') }+ @{ Patterns = @('FortiClient'); Vendor = 'fortinet'; Product = 'forticlient'; PublisherHints = @('Fortinet') }+ @{ Patterns = @('GlobalProtect'); Vendor = 'palo_alto_networks'; Product = 'globalprotect'; PublisherHints = @('Palo Alto Networks') }+ @{ Patterns = @('Cisco AnyConnect'); Vendor = 'cisco'; Product = 'anyconnect_secure_mobility_client'; PublisherHints = @('Cisco') }+ @{ Patterns = @('WireGuard'); Vendor = 'wireguard'; Product = 'wireguard'; PublisherHints = @('WireGuard') }@{ Patterns = @('FileZilla Server'); Vendor = 'filezilla'; Product = 'filezilla_server'; PublisherHints = @('FileZilla') }@{ Patterns = @('FileZilla'); Vendor = 'filezilla'; Product = 'filezilla'; PublisherHints = @('FileZilla') }- @{ Patterns = @('WinSCP'); Vendor = 'winscp'; Product = 'winscp'; PublisherHints = @('Martin Prikryl') }- @{ Patterns = @('TeamViewer'); Vendor = 'teamviewer'; Product = 'teamviewer'; PublisherHints = @('TeamViewer') }- @{ Patterns = @('Zoom'); Vendor = 'zoom'; Product = 'zoom'; PublisherHints = @('Zoom') }- @{ Patterns = @('Cisco AnyConnect'); Vendor = 'cisco'; Product = 'anyconnect_secure_mobility_client'; PublisherHints = @('Cisco') }- @{ Patterns = @('VMware Workstation'); Vendor = 'vmware'; Product = 'workstation'; PublisherHints = @('VMware') }- @{ Patterns = @('VirtualBox'); Vendor = 'oracle'; Product = 'vm_virtualbox'; PublisherHints = @('Oracle') }- @{ Patterns = @('Docker Desktop'); Vendor = 'docker'; Product = 'desktop'; PublisherHints = @('Docker') }+ @{ Patterns = @('TortoiseGit'); Vendor = 'tortoisegit'; Product = 'tortoisegit'; PublisherHints = @('TortoiseGit') }+ @{ Patterns = @('TortoiseSVN'); Vendor = 'tortoisesvn'; Product = 'tortoisesvn'; PublisherHints = @('TortoiseSVN') }+ @{ Patterns = @('GitHub Desktop'); Vendor = 'github'; Product = 'github_desktop'; PublisherHints = @('GitHub') }+ @{ Patterns = @('Git'); Vendor = 'git-scm'; Product = 'git'; PublisherHints = @('The Git Development Community') }+ @{ Patterns = @('VLC media player'); Vendor = 'videolan'; Product = 'vlc_media_player'; PublisherHints = @('VideoLAN') }+ @{ Patterns = @('GIMP'); Vendor = 'gimp'; Product = 'gimp'; PublisherHints = @('GIMP') }+ @{ Patterns = @('Inkscape'); Vendor = 'inkscape'; Product = 'inkscape'; PublisherHints = @('Inkscape') }+ @{ Patterns = @('OBS Studio'); Vendor = 'obsproject'; Product = 'obs_studio'; PublisherHints = @('OBS'); Scheme = 'Qt' }+ @{ Patterns = @('Audacity'); Vendor = 'audacityteam'; Product = 'audacity'; PublisherHints = @('Audacity') }+ @{ Patterns = @('HandBrake'); Vendor = 'handbrake'; Product = 'handbrake'; PublisherHints = @('HandBrake') }+ @{ Patterns = @('LibreOffice'); Vendor = 'libreoffice'; Product = 'libreoffice'; PublisherHints = @('The Document Foundation') }+ @{ Patterns = @('OpenOffice'); Vendor = 'apache'; Product = 'openoffice'; PublisherHints = @('Apache') }+ @{ Patterns = @('Foxit PDF Reader', 'Foxit Reader'); Vendor = 'foxitsoftware'; Product = 'foxit_reader'; PublisherHints = @('Foxit') }@{ Patterns = @('iTunes'); Vendor = 'apple'; Product = 'itunes'; PublisherHints = @('Apple') }@{ Patterns = @('Skype'); Vendor = 'skype'; Product = 'skype'; PublisherHints = @('Skype', 'Microsoft') }- @{ Patterns = @('Slack'); Vendor = 'slack'; Product = 'slack'; PublisherHints = @('Slack') }- @{ Patterns = @('Foxit PDF Reader', 'Foxit Reader'); Vendor = 'foxitsoftware'; Product = 'foxit_reader'; PublisherHints = @('Foxit') }+ @{ Patterns = @('KeePassXC'); Vendor = 'keepassxc'; Product = 'keepassxc'; PublisherHints = @('KeePassXC'); Scheme = 'Qt' }@{ Patterns = @('KeePass'); Vendor = 'keepass'; Product = 'keepass'; PublisherHints = @('Dominik Reichl') }+ @{ Patterns = @('VeraCrypt'); Vendor = 'veracrypt'; Product = 'veracrypt'; PublisherHints = @('IDRIX') }+ @{ Patterns = @('1Password'); Vendor = 'agilebits'; Product = '1password'; PublisherHints = @('AgileBits') }+ @{ Patterns = @('Bitwarden'); Vendor = 'bitwarden'; Product = 'bitwarden'; PublisherHints = @('Bitwarden') }+ @{ Patterns = @('LastPass'); Vendor = 'lastpass'; Product = 'lastpass'; PublisherHints = @('LastPass') }+ @{ Patterns = @('Malwarebytes'); Vendor = 'malwarebytes'; Product = 'malwarebytes'; PublisherHints = @('Malwarebytes') }@{ Patterns = @('OpenSSL'); Vendor = 'openssl'; Product = 'openssl'; PublisherHints = @('OpenSSL') }+ @{ Patterns = @('Zoom'); Vendor = 'zoom'; Product = 'zoom'; PublisherHints = @('Zoom') }+ @{ Patterns = @('Cisco Webex', 'Webex'); Vendor = 'cisco'; Product = 'webex'; PublisherHints = @('Cisco') }+ @{ Patterns = @('Slack'); Vendor = 'slack'; Product = 'slack'; PublisherHints = @('Slack') }+ @{ Patterns = @('Discord'); Vendor = 'discord'; Product = 'discord'; PublisherHints = @('Discord') }+ @{ Patterns = @('TeamViewer'); Vendor = 'teamviewer'; Product = 'teamviewer'; PublisherHints = @('TeamViewer') }+ @{ Patterns = @('AnyDesk'); Vendor = 'anydesk'; Product = 'anydesk'; PublisherHints = @('AnyDesk') }+ @{ Patterns = @('Splashtop'); Vendor = 'splashtop'; Product = 'splashtop'; PublisherHints = @('Splashtop') }+ @{ Patterns = @('nginx'); Vendor = 'nginx'; Product = 'nginx'; PublisherHints = @('nginx') }+ @{ Patterns = @('Apache HTTP Server', 'Apache HTTPD'); Vendor = 'apache'; Product = 'http_server'; PublisherHints = @('Apache') }+ @{ Patterns = @('PostgreSQL'); Vendor = 'postgresql'; Product = 'postgresql'; PublisherHints = @('PostgreSQL') }+ @{ Patterns = @('MySQL Workbench'); Vendor = 'oracle'; Product = 'mysql_workbench'; PublisherHints = @('Oracle', 'MySQL') }+ @{ Patterns = @('MySQL'); Vendor = 'oracle'; Product = 'mysql'; PublisherHints = @('Oracle', 'MySQL') }+ @{ Patterns = @('MongoDB'); Vendor = 'mongodb'; Product = 'mongodb'; PublisherHints = @('MongoDB') }+ @{ Patterns = @('SQLite'); Vendor = 'sqlite'; Product = 'sqlite'; PublisherHints = @('SQLite') }+ @{ Patterns = @('Redis'); Vendor = 'redis'; Product = 'redis'; PublisherHints = @('Redis') }+ @{ Patterns = @('Elasticsearch'); Vendor = 'elastic'; Product = 'elasticsearch'; PublisherHints = @('Elastic') }+ @{ Patterns = @('Grafana'); Vendor = 'grafana'; Product = 'grafana'; PublisherHints = @('Grafana') }+ @{ Patterns = @('VMware Tools'); Vendor = 'vmware'; Product = 'tools'; PublisherHints = @('VMware') }+ @{ Patterns = @('VMware ESXi'); Vendor = 'vmware'; Product = 'esxi'; PublisherHints = @('VMware') }+ @{ Patterns = @('VMware Workstation'); Vendor = 'vmware'; Product = 'workstation'; PublisherHints = @('VMware') }+ @{ Patterns = @('VirtualBox'); Vendor = 'oracle'; Product = 'vm_virtualbox'; PublisherHints = @('Oracle') }+ @{ Patterns = @('Docker Desktop'); Vendor = 'docker'; Product = 'desktop'; PublisherHints = @('Docker') }+ @{ Patterns = @('Podman'); Vendor = 'podman'; Product = 'podman'; PublisherHints = @('Podman') }+ @{ Patterns = @('Docker'); Vendor = 'docker'; Product = 'docker'; PublisherHints = @('Docker') }+ @{ Patterns = @('kubectl'); Vendor = 'kubernetes'; Product = 'kubectl'; PublisherHints = @('Kubernetes') }+ @{ Patterns = @('Terraform'); Vendor = 'hashicorp'; Product = 'terraform'; PublisherHints = @('HashiCorp') }+ @{ Patterns = @('AWS Command Line Interface', 'AWS CLI'); Vendor = 'amazon'; Product = 'aws_cli'; PublisherHints = @('Amazon') }+ @{ Patterns = @('Wireshark'); Vendor = 'wireshark'; Product = 'wireshark'; PublisherHints = @('Wireshark'); Scheme = 'Qt' }+ @{ Patterns = @('Nmap'); Vendor = 'nmap'; Product = 'nmap'; PublisherHints = @('Nmap') }+ @{ Patterns = @('Citrix Workspace'); Vendor = 'citrix'; Product = 'workspace_app'; PublisherHints = @('Citrix') }+ @{ Patterns = @('Cygwin'); Vendor = 'cygwin'; Product = 'cygwin'; PublisherHints = @('Cygwin') }+ @{ Patterns = @('MSYS2'); Vendor = 'msys2'; Product = 'msys2'; PublisherHints = @('MSYS2') }+ @{ Patterns = @('MinGW'); Vendor = 'mingw'; Product = 'mingw'; PublisherHints = @('MinGW') })+ # Vendor version-scheme translators (heuristics): rewrite a normalized+ # registry version into the scheme NVD uses for that vendor's CPEs.+ # Each returns the input unchanged when the scheme already matches+ # (passthrough), so a translation only fires when the value changes.+ $schemeTranslators = @{+ Java = {+ param([string]$V)+ # Legacy '1.8.0_391' / '8u391' schemes map to NVD '8.0.391';+ # modern schemes ('11.0.x', '17.0.x') pass through unchanged+ if ($V -match '^1\.(\d+)\.0[_\.](\d+)$') { return ('{0}.0.{1}' -f $Matches[1], $Matches[2]) }+ if ($V -match '^(\d+)u(\d+)$') { return ('{0}.0.{1}' -f $Matches[1], $Matches[2]) }+ return $V+ }+ DotNet = {+ param([string]$V)+ # .NET Framework registry versions carry a build ('4.8.09037');+ # NVD tracks the framework as major.minor ('4.8')+ if ($V -match '^(\d+\.\d+)(\.\d+)+$') { return $Matches[1] }+ return $V+ }+ Chrome = {+ param([string]$V)+ # Chrome-style four-part versions are already CPE-compatible+ return $V+ }+ Python = {+ param([string]$V)+ # NVD tracks CPython as major.minor when the patch level is 0+ if ($V -match '^(\d+\.\d+)\.0+$') { return $Matches[1] }+ return $V+ }+ Qt = {+ param([string]$V)+ # Qt-based builds sometimes use underscore-separated versions+ if ($V -match '^\d+(_\d+)+$') { return ($V -replace '_', '.') }+ return $V+ }+ }+$nvdCpeApiBase = 'https://services.nvd.nist.gov/rest/json/cpes/2.0'$requestHeaders = @{}if ($ApiKey) {@@ -227,19 +369,38 @@ function Resolve-CpeName {}if ($null -ne $curatedMatch) {- $cpeName = New-CpeName -VendorToken $curatedMatch.Vendor -ProductToken $curatedMatch.Product -VersionToken $normalizedVersion+ $effectiveVersion = $normalizedVersion+ $matchedBy = 'CuratedTable'$confidence = 'Medium'if ($null -ne $normalizedVersion) {$confidence = 'High'}+ if ($null -ne $normalizedVersion -and $curatedMatch.ContainsKey('Scheme')) {+ $schemeName = [string]$curatedMatch['Scheme']+ if ($schemeTranslators.ContainsKey($schemeName)) {+ $translatedVersion = & $schemeTranslators[$schemeName] $normalizedVersion+ if ($null -ne $translatedVersion -and+ $translatedVersion -ne $normalizedVersion -and+ $translatedVersion -match '^[0-9A-Za-z._~]+$') {+ Write-Host " Version scheme translation ($schemeName): $normalizedVersion -> $translatedVersion" -ForegroundColor Gray+ $effectiveVersion = $translatedVersion+ $matchedBy = 'SchemeTranslation'+ $confidence = 'Medium'+ }+ }+ }++ $cpeName = New-CpeName -VendorToken $curatedMatch.Vendor -ProductToken $curatedMatch.Product -VersionToken $effectiveVersion+Write-Host " Curated table match: $($curatedMatch.Vendor):$($curatedMatch.Product)" -ForegroundColor Gray$result = [PSCustomObject]@{- CpeName = $cpeName- MatchedBy = 'CuratedTable'- Confidence = $confidence- Version = $normalizedVersion+ CpeName = $cpeName+ MatchedBy = $matchedBy+ Confidence = $confidence+ Version = $effectiveVersion+ OriginalVersion = $Version}return}@@ -301,10 +462,11 @@ function Resolve-CpeName {}$result = [PSCustomObject]@{- CpeName = $cpeName- MatchedBy = 'OnlineLookup'- Confidence = $confidence- Version = $normalizedVersion+ CpeName = $cpeName+ MatchedBy = 'OnlineLookup'+ Confidence = $confidence+ Version = $normalizedVersion+ OriginalVersion = $Version}return}@@ -340,10 +502,11 @@ function Resolve-CpeName {Write-Host " Heuristic guess: $($vendorToken):$($productToken) (Low confidence)" -ForegroundColor Gray$result = [PSCustomObject]@{- CpeName = $cpeName- MatchedBy = 'Heuristic'- Confidence = 'Low'- Version = $normalizedVersion+ CpeName = $cpeName+ MatchedBy = 'Heuristic'+ Confidence = 'Low'+ Version = $normalizedVersion+ OriginalVersion = $Version}return}@@ -351,10 +514,11 @@ function Resolve-CpeName {Write-Warning "Could not resolve a CPE name for '$ProductName'"$result = [PSCustomObject]@{- CpeName = $null- MatchedBy = 'None'- Confidence = 'Low'- Version = $normalizedVersion+ CpeName = $null+ MatchedBy = 'None'+ Confidence = 'Low'+ Version = $normalizedVersion+ OriginalVersion = $Version}}catch {diff --git a/WindowsSecurityAudit.psd1 b/WindowsSecurityAudit.psd1index fa48616..da06520 100644--- a/WindowsSecurityAudit.psd1+++ b/WindowsSecurityAudit.psd1@@ -1,6 +1,6 @@@{RootModule = 'WindowsSecurityAudit.psm1'- ModuleVersion = '1.4.0'+ ModuleVersion = '1.5.0'GUID = 'a8d7c4e5-3b2f-4e8a-9c1d-6f5a8b9d2e7c'Author = 'Okan YILDIZ'CompanyName = 'okanyildiz'diff --git a/WindowsSecurityAudit.psm1 b/WindowsSecurityAudit.psm1index c3bbd12..f4e8601 100644--- a/WindowsSecurityAudit.psm1+++ b/WindowsSecurityAudit.psm1@@ -14,7 +14,7 @@ Set-StrictMode -Version Latest# Module variables$script:ModuleRoot = $PSScriptRoot-$script:ModuleVersion = '1.4.0'+$script:ModuleVersion = '1.5.0'# Import all function files$Public = @(Get-ChildItem -Path "$PSScriptRoot\Core\*.ps1" -ErrorAction SilentlyContinue)diff --git a/tests/WindowsSecurityAudit.Tests.ps1 b/tests/WindowsSecurityAudit.Tests.ps1index 3283964..cae04b9 100644--- a/tests/WindowsSecurityAudit.Tests.ps1+++ b/tests/WindowsSecurityAudit.Tests.ps1@@ -234,6 +234,11 @@ Describe 'Threat Intelligence and CVE Integration' {$parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })foreach ($expected in 'UpdateFeeds', 'FeedCachePath', 'FeedMaxAgeHours', 'MaxFeedEntries', 'AbuseIPDBApiKey') {$parameterNames | Should -Contain $expected+ # Get-Help derives a bare parameter list from the param block even without+ # comment-based help, so assert the .PARAMETER text itself is present+ $helpParameter = @($help.parameters.parameter | Where-Object { $_.Name -eq $expected })[0]+ @($helpParameter.description | Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace("$($_.Text)") }).Count |+ Should -BeGreaterThan 0 -Because 'the parameter must carry comment-based help text, not just exist in the param block'}}@@ -242,6 +247,11 @@ Describe 'Threat Intelligence and CVE Integration' {$parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })foreach ($expected in 'CheckCVEs', 'NVDApiKey', 'MaxCVEChecks') {$parameterNames | Should -Contain $expected+ # Get-Help derives a bare parameter list from the param block even without+ # comment-based help, so assert the .PARAMETER text itself is present+ $helpParameter = @($help.parameters.parameter | Where-Object { $_.Name -eq $expected })[0]+ @($helpParameter.description | Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace("$($_.Text)") }).Count |+ Should -BeGreaterThan 0 -Because 'the parameter must carry comment-based help text, not just exist in the param block'}}}@@ -297,6 +307,11 @@ Describe 'v1.3 Features' {$parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })foreach ($expected in 'MISPUrl', 'MISPApiKey', 'TaxiiServerUrl', 'TaxiiCollection', 'StixFilePath') {$parameterNames | Should -Contain $expected+ # Get-Help derives a bare parameter list from the param block even without+ # comment-based help, so assert the .PARAMETER text itself is present+ $helpParameter = @($help.parameters.parameter | Where-Object { $_.Name -eq $expected })[0]+ @($helpParameter.description | Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace("$($_.Text)") }).Count |+ Should -BeGreaterThan 0 -Because 'the parameter must carry comment-based help text, not just exist in the param block'}}@@ -305,6 +320,11 @@ Describe 'v1.3 Features' {$parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })foreach ($expected in 'UseOnlineLookup', 'ApiKey') {$parameterNames | Should -Contain $expected+ # Get-Help derives a bare parameter list from the param block even without+ # comment-based help, so assert the .PARAMETER text itself is present+ $helpParameter = @($help.parameters.parameter | Where-Object { $_.Name -eq $expected })[0]+ @($helpParameter.description | Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace("$($_.Text)") }).Count |+ Should -BeGreaterThan 0 -Because 'the parameter must carry comment-based help text, not just exist in the param block'}}@@ -313,6 +333,11 @@ Describe 'v1.3 Features' {$parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })foreach ($expected in 'MaxSeverity', 'GenerateRollback', 'AssessmentPath', 'InputObject') {$parameterNames | Should -Contain $expected+ # Get-Help derives a bare parameter list from the param block even without+ # comment-based help, so assert the .PARAMETER text itself is present+ $helpParameter = @($help.parameters.parameter | Where-Object { $_.Name -eq $expected })[0]+ @($helpParameter.description | Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace("$($_.Text)") }).Count |+ Should -BeGreaterThan 0 -Because 'the parameter must carry comment-based help text, not just exist in the param block'}}}@@ -418,6 +443,11 @@ Describe 'v1.4 Features' {$parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })foreach ($expected in 'Format', 'HostName') {$parameterNames | Should -Contain $expected+ # Get-Help derives a bare parameter list from the param block even without+ # comment-based help, so assert the .PARAMETER text itself is present+ $helpParameter = @($help.parameters.parameter | Where-Object { $_.Name -eq $expected })[0]+ @($helpParameter.description | Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace("$($_.Text)") }).Count |+ Should -BeGreaterThan 0 -Because 'the parameter must carry comment-based help text, not just exist in the param block'}}@@ -426,6 +456,11 @@ Describe 'v1.4 Features' {$parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })foreach ($expected in 'Hours', 'IncludeLSASSAccess') {$parameterNames | Should -Contain $expected+ # Get-Help derives a bare parameter list from the param block even without+ # comment-based help, so assert the .PARAMETER text itself is present+ $helpParameter = @($help.parameters.parameter | Where-Object { $_.Name -eq $expected })[0]+ @($helpParameter.description | Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace("$($_.Text)") }).Count |+ Should -BeGreaterThan 0 -Because 'the parameter must carry comment-based help text, not just exist in the param block'}}@@ -434,6 +469,11 @@ Describe 'v1.4 Features' {$parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })foreach ($expected in 'Hours', 'IncludeLogGapAnalysis') {$parameterNames | Should -Contain $expected+ # Get-Help derives a bare parameter list from the param block even without+ # comment-based help, so assert the .PARAMETER text itself is present+ $helpParameter = @($help.parameters.parameter | Where-Object { $_.Name -eq $expected })[0]+ @($helpParameter.description | Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace("$($_.Text)") }).Count |+ Should -BeGreaterThan 0 -Because 'the parameter must carry comment-based help text, not just exist in the param block'}}@@ -442,6 +482,11 @@ Describe 'v1.4 Features' {$parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })foreach ($expected in 'UserProfile', 'OutputPath') {$parameterNames | Should -Contain $expected+ # Get-Help derives a bare parameter list from the param block even without+ # comment-based help, so assert the .PARAMETER text itself is present+ $helpParameter = @($help.parameters.parameter | Where-Object { $_.Name -eq $expected })[0]+ @($helpParameter.description | Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace("$($_.Text)") }).Count |+ Should -BeGreaterThan 0 -Because 'the parameter must carry comment-based help text, not just exist in the param block'}}@@ -496,3 +541,166 @@ Describe 'v1.4 Features' {}}}++Describe 'v1.5 Features' {+ Context 'Comment-based help for new parameters' {+ It 'Send-SiemEvent help documents the streaming parameters' {+ $help = Get-Help -Name 'Send-SiemEvent' -Full+ $parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })+ foreach ($expected in 'Destination', 'Uri', 'BatchSize', 'MaxRetries') {+ $parameterNames | Should -Contain $expected+ # Get-Help derives a bare parameter list from the param block even without+ # comment-based help, so assert the .PARAMETER text itself is present+ $helpParameter = @($help.parameters.parameter | Where-Object { $_.Name -eq $expected })[0]+ @($helpParameter.description | Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace("$($_.Text)") }).Count |+ Should -BeGreaterThan 0 -Because 'the parameter must carry comment-based help text, not just exist in the param block'+ }+ }++ It 'Get-SysmonAnalytics help documents Hours, EventTypes and MaxEvents' {+ $help = Get-Help -Name 'Get-SysmonAnalytics' -Full+ $parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })+ foreach ($expected in 'Hours', 'EventTypes', 'MaxEvents') {+ $parameterNames | Should -Contain $expected+ # Get-Help derives a bare parameter list from the param block even without+ # comment-based help, so assert the .PARAMETER text itself is present+ $helpParameter = @($help.parameters.parameter | Where-Object { $_.Name -eq $expected })[0]+ @($helpParameter.description | Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace("$($_.Text)") }).Count |+ Should -BeGreaterThan 0 -Because 'the parameter must carry comment-based help text, not just exist in the param block'+ }+ }++ It 'Get-FileSystemJournal help documents Mode, DriveLetter and MaxRecords' {+ $help = Get-Help -Name 'Get-FileSystemJournal' -Full+ $parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })+ foreach ($expected in 'Mode', 'DriveLetter', 'MaxRecords') {+ $parameterNames | Should -Contain $expected+ # Get-Help derives a bare parameter list from the param block even without+ # comment-based help, so assert the .PARAMETER text itself is present+ $helpParameter = @($help.parameters.parameter | Where-Object { $_.Name -eq $expected })[0]+ @($helpParameter.description | Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace("$($_.Text)") }).Count |+ Should -BeGreaterThan 0 -Because 'the parameter must carry comment-based help text, not just exist in the param block'+ }+ }++ It 'Invoke-EnterpriseSecurityScan help documents the remote deployment parameters' {+ $help = Get-Help -Name 'Invoke-EnterpriseSecurityScan' -Full+ $parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })+ foreach ($expected in 'UseModuleFunctions', 'RemoteFunctionSet', 'HostTimeoutSec', 'ProbeTimeoutSec', 'TargetFile') {+ $parameterNames | Should -Contain $expected+ # Get-Help derives a bare parameter list from the param block even without+ # comment-based help, so assert the .PARAMETER text itself is present+ $helpParameter = @($help.parameters.parameter | Where-Object { $_.Name -eq $expected })[0]+ @($helpParameter.description | Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace("$($_.Text)") }).Count |+ Should -BeGreaterThan 0 -Because 'the parameter must carry comment-based help text, not just exist in the param block'+ }+ }++ It 'Register-ScheduledSecurityScan help documents the alert dedup parameters' {+ $help = Get-Help -Name 'Register-ScheduledSecurityScan' -Full+ $parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })+ foreach ($expected in 'RealertAfterDays', 'DisableAlertDedup') {+ $parameterNames | Should -Contain $expected+ # Get-Help derives a bare parameter list from the param block even without+ # comment-based help, so assert the .PARAMETER text itself is present+ $helpParameter = @($help.parameters.parameter | Where-Object { $_.Name -eq $expected })[0]+ @($helpParameter.description | Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace("$($_.Text)") }).Count |+ Should -BeGreaterThan 0 -Because 'the parameter must carry comment-based help text, not just exist in the param block'+ }+ }++ It 'Export-SecurityReport help documents the SIEM streaming parameters' {+ $help = Get-Help -Name 'Export-SecurityReport' -Full+ $parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })+ foreach ($expected in 'StreamTo', 'StreamUri') {+ $parameterNames | Should -Contain $expected+ # Get-Help derives a bare parameter list from the param block even without+ # comment-based help, so assert the .PARAMETER text itself is present+ $helpParameter = @($help.parameters.parameter | Where-Object { $_.Name -eq $expected })[0]+ @($helpParameter.description | Where-Object { $null -ne $_ -and -not [string]::IsNullOrWhiteSpace("$($_.Text)") }).Count |+ Should -BeGreaterThan 0 -Because 'the parameter must carry comment-based help text, not just exist in the param block'+ }+ }+ }++ Context 'Static safety checks' {+ # -ForEach data must exist at discovery time, so relative paths are used+ # here and resolved against $script:ModuleRoot (set in BeforeAll) at runtime+ It 'Send-SiemEvent never interpolates the token into Write-Host or Write-Verbose output' {+ $Path = Join-Path -Path $script:ModuleRoot -ChildPath 'Response/Send-SiemEvent.ps1'+ $result = Get-ScriptFileAst -Path $Path+ $loggingCommands = @($result.Ast.FindAll({+ param($node)+ $node -is [System.Management.Automation.Language.CommandAst]+ }, $true) | Where-Object {+ $commandName = $_.GetCommandName()+ $commandName -eq 'Write-Host' -or $commandName -eq 'Write-Verbose'+ })++ # A direct "$Token" interpolation shows up as a VariableExpressionAst+ # in the string's NestedExpressions. The masked form+ # "$(ConvertTo-MaskedToken -Secret $Token)" is a SubExpressionAst node+ # and never emits the token itself+ $leaks = @()+ foreach ($command in $loggingCommands) {+ $strings = @($command.FindAll({+ param($node)+ $node -is [System.Management.Automation.Language.StringConstantExpressionAst] -and+ $node.StringConstantType -eq [System.Management.Automation.Language.StringConstantType]::DoubleQuoted+ }, $true))+ foreach ($string in $strings) {+ $leaks += @($string.NestedExpressions | Where-Object {+ $_ -is [System.Management.Automation.Language.VariableExpressionAst] -and+ $_.VariablePath.UserPath -match '(?i)(token|secret|sharedkey)'+ })+ }+ # A bare variable argument (Write-Host $Token) contains no double-quoted+ # string at all, so it must be caught at the command-element level+ $leaks += @($command.CommandElements | Where-Object {+ $_ -is [System.Management.Automation.Language.VariableExpressionAst] -and+ $_.VariablePath.UserPath -match '(?i)(token|secret|sharedkey)'+ })+ }+ $leaks.Count | Should -Be 0 -Because 'SIEM tokens must be masked before they reach any log output'+ }++ It '<_> contains no hardcoded keys, secrets, tokens or passwords' -ForEach @(+ 'Response/Send-SiemEvent.ps1'+ 'Detection/Get-SysmonAnalytics.ps1'+ 'Forensics/Get-FileSystemJournal.ps1'+ ) {+ $Path = Join-Path -Path $script:ModuleRoot -ChildPath $_+ $result = Get-ScriptFileAst -Path $Path+ $assignments = @($result.Ast.FindAll({+ param($node)+ $node -is [System.Management.Automation.Language.AssignmentStatementAst]+ }, $true))++ $hardcoded = @($assignments | Where-Object {+ $_.Left -is [System.Management.Automation.Language.VariableExpressionAst] -and+ $_.Left.VariablePath.UserPath -match '(?i)(key|secret|token|password)' -and+ $_.Right -is [System.Management.Automation.Language.StringConstantExpressionAst] -and+ -not [string]::IsNullOrWhiteSpace($_.Right.Value)+ })+ $hardcoded.Count | Should -Be 0 -Because 'credentials must come from parameters, never from string literals'+ }++ It 'Get-SysmonAnalytics attaches a Technique property to findings' {+ $Path = Join-Path -Path $script:ModuleRoot -ChildPath 'Detection/Get-SysmonAnalytics.ps1'+ $content = Get-Content -Path $Path -Raw+ $content | Should -Match 'Technique'+ }++ It 'Get-FileSystemJournal labels timestomp detection as a heuristic' {+ $Path = Join-Path -Path $script:ModuleRoot -ChildPath 'Forensics/Get-FileSystemJournal.ps1'+ $content = Get-Content -Path $Path -Raw+ $content | Should -Match 'euristic'+ }++ It 'Register-ScheduledSecurityScan embeds the fingerprint state logic in the scan script' {+ $Path = Join-Path -Path $script:ModuleRoot -ChildPath 'Enterprise/Register-ScheduledSecurityScan.ps1'+ $content = Get-Content -Path $Path -Raw+ $content | Should -Match 'last-findings'+ }+ }+}