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 version-exact CVE matching, MISP/TAXII feeds, auto-remediation (v1.3.0)
Okan YILDIZ82af19606de5
diff --git a/Hardening/Invoke-SecurityRemediation.ps1 b/Hardening/Invoke-SecurityRemediation.ps1new file mode 100644index 0000000..fd060e4--- /dev/null+++ b/Hardening/Invoke-SecurityRemediation.ps1@@ -0,0 +1,519 @@+function Invoke-SecurityRemediation {+ <#+ .SYNOPSIS+ Applies automated remediations for findings produced by Invoke-SecurityAssessment+ .DESCRIPTION+ Closes the loop from finding to fix: consumes a saved assessment JSON file (or a piped+ assessment/findings object), filters findings by severity, matches each finding against a+ curated map of safe, automatable remediations, and applies the fix with SupportsShouldProcess+ (-WhatIf/-Confirm). Findings with no matching remediation are reported as ManualReview and+ are never improvised. Optionally writes a rollback script capturing pre-change state.+ .PARAMETER AssessmentPath+ Path to a JSON file previously saved by Invoke-SecurityAssessment+ .PARAMETER InputObject+ Assessment object (or findings array / single finding) accepted from the pipeline+ .PARAMETER MaxSeverity+ Only remediate findings at or above this severity: Critical, High, Medium, or Low (default: High)+ .PARAMETER GenerateRollback+ Write a rollback .ps1 script that captures current values BEFORE they are changed+ .PARAMETER RollbackDirectory+ Directory where the rollback script is written (default: current location)+ .EXAMPLE+ Invoke-SecurityRemediation -AssessmentPath "C:\Assessments\AssessmentResults.json" -WhatIf+ Preview every remediation that would be applied without changing any state+ .EXAMPLE+ Invoke-SecurityRemediation -AssessmentPath "C:\Assessments\AssessmentResults.json" -MaxSeverity Critical -GenerateRollback+ Remediate only Critical findings and write a rollback script with pre-change values+ .EXAMPLE+ Invoke-SecurityAssessment -OutputPath "C:\Assessments" | Invoke-SecurityRemediation -GenerateRollback -Confirm+ Pipe an assessment object directly into remediation with confirmation prompts+ .OUTPUTS+ PSCustomObject with FindingsProcessed, Remediated, ManualReview, Failed, and RollbackPath+ #>++ [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High', DefaultParameterSetName = 'File')]+ param(+ [Parameter(Mandatory, ParameterSetName = 'File', Position = 0)]+ [ValidateScript({ Test-Path -Path $_ -PathType Leaf })]+ [string]$AssessmentPath,++ [Parameter(Mandatory, ParameterSetName = 'Object', ValueFromPipeline)]+ [AllowNull()]+ [object]$InputObject,++ [Parameter()]+ [ValidateSet('Critical', 'High', 'Medium', 'Low')]+ [string]$MaxSeverity = 'High',++ [Parameter()]+ [switch]$GenerateRollback,++ [Parameter()]+ [string]$RollbackDirectory = (Get-Location).Path+ )++ begin {+ Write-Host "=== AUTOMATED SECURITY REMEDIATION ===" -ForegroundColor Cyan+ Write-Host "Max Severity: $MaxSeverity" -ForegroundColor Yellow+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ if ($WhatIfPreference) {+ Write-Host "MODE: WhatIf (no changes will be made)" -ForegroundColor Magenta+ }++ # Check for admin privileges+ $isAdmin = $false+ try {+ $currentPrincipal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()+ $isAdmin = $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ }+ catch {+ Write-Warning "Could not determine elevation status on this platform; remediation cmdlets may fail without Administrator privileges."+ $isAdmin = $true+ }+ if (-not $isAdmin) {+ Write-Error "Invoke-SecurityRemediation requires Administrator privileges. Re-run from an elevated PowerShell session."+ throw "This function requires Administrator privileges!"+ }++ $severityRank = @{+ Critical = 4+ High = 3+ Medium = 2+ Low = 1+ }+ $threshold = $severityRank[$MaxSeverity]++ $collectedFindings = @()++ $results = [PSCustomObject]@{+ RemediationDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ MaxSeverity = $MaxSeverity+ WhatIf = [bool]$WhatIfPreference+ FindingsProcessed = 0+ SkippedBelowThreshold = 0+ Remediated = @()+ ManualReview = @()+ Failed = @()+ RollbackPath = $null+ }++ $rollbackScriptLines = @()++ # Remediation map: curated, safe, automatable fixes. Anything unmatched -> ManualReview.+ $uacRegistryPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"+ $psLoggingPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"+ $rdpTcpPath = "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp"++ $remediationMap = @(+ [PSCustomObject]@{+ Name = 'Enable Windows Firewall profiles'+ FindingPattern = 'firewall'+ RequiresAdmin = $true+ Action = {+ Set-NetFirewallProfile -Profile Domain, Public, Private -Enabled True -ErrorAction Stop+ }+ Verify = {+ $disabled = @(Get-NetFirewallProfile -ErrorAction Stop | Where-Object { -not $_.Enabled })+ return (@($disabled).Count -eq 0)+ }+ Rollback = {+ $lines = @()+ $fwProfiles = @(Get-NetFirewallProfile -ErrorAction Stop | Select-Object Name, Enabled)+ foreach ($fwProfile in $fwProfiles) {+ $lines += "Set-NetFirewallProfile -Profile '$($fwProfile.Name)' -Enabled `$$($fwProfile.Enabled)"+ }+ return $lines+ }+ }+ [PSCustomObject]@{+ Name = 'Enable User Account Control (UAC)'+ FindingPattern = 'user account control|\buac\b'+ RequiresAdmin = $true+ Action = {+ Set-ItemProperty -Path $uacRegistryPath -Name "EnableLUA" -Value 1 -Type DWord -Force -ErrorAction Stop+ }+ Verify = {+ $current = Get-ItemProperty -Path $uacRegistryPath -Name "EnableLUA" -ErrorAction Stop+ return ($current.EnableLUA -eq 1)+ }+ Rollback = {+ $previous = 0+ try {+ $current = Get-ItemProperty -Path $uacRegistryPath -Name "EnableLUA" -ErrorAction Stop+ if ($null -ne $current.EnableLUA) { $previous = $current.EnableLUA }+ }+ catch {+ $previous = 'NOT_PRESENT'+ }+ if ($previous -eq 'NOT_PRESENT') {+ return @("Remove-ItemProperty -Path '$uacRegistryPath' -Name 'EnableLUA' -ErrorAction SilentlyContinue")+ }+ return @("Set-ItemProperty -Path '$uacRegistryPath' -Name 'EnableLUA' -Value $previous -Type DWord -Force")+ }+ }+ [PSCustomObject]@{+ Name = 'Enable Defender real-time protection'+ FindingPattern = 'real-?time protection|realtimemonitoring'+ RequiresAdmin = $true+ Action = {+ Set-MpPreference -DisableRealtimeMonitoring $false -ErrorAction Stop+ }+ Verify = {+ $prefs = Get-MpPreference -ErrorAction Stop+ return (-not $prefs.DisableRealtimeMonitoring)+ }+ Rollback = {+ $previous = $false+ try {+ $prefs = Get-MpPreference -ErrorAction Stop+ if ($null -ne $prefs.DisableRealtimeMonitoring) { $previous = [bool]$prefs.DisableRealtimeMonitoring }+ }+ catch {+ $previous = $false+ }+ return @("Set-MpPreference -DisableRealtimeMonitoring `$$previous")+ }+ }+ [PSCustomObject]@{+ Name = 'Disable SMBv1 protocol'+ FindingPattern = 'smb\s?v1|smb version 1|smb 1\.0'+ RequiresAdmin = $true+ Action = {+ Set-SmbServerConfiguration -EnableSMB1Protocol $false -Force -ErrorAction Stop+ }+ Verify = {+ $config = Get-SmbServerConfiguration -ErrorAction Stop+ return (-not $config.EnableSMB1Protocol)+ }+ Rollback = {+ $previous = $true+ try {+ $config = Get-SmbServerConfiguration -ErrorAction Stop+ if ($null -ne $config.EnableSMB1Protocol) { $previous = [bool]$config.EnableSMB1Protocol }+ }+ catch {+ $previous = $true+ }+ return @("Set-SmbServerConfiguration -EnableSMB1Protocol `$$previous -Force")+ }+ }+ [PSCustomObject]@{+ Name = 'Disable Guest account'+ FindingPattern = 'guest account|guest user'+ RequiresAdmin = $true+ Action = {+ Disable-LocalUser -Name "Guest" -ErrorAction Stop+ }+ Verify = {+ $guest = Get-LocalUser -Name "Guest" -ErrorAction Stop+ return (-not $guest.Enabled)+ }+ Rollback = {+ $wasEnabled = $false+ try {+ $guest = Get-LocalUser -Name "Guest" -ErrorAction Stop+ $wasEnabled = [bool]$guest.Enabled+ }+ catch {+ $wasEnabled = $false+ }+ if ($wasEnabled) {+ return @("Enable-LocalUser -Name 'Guest'")+ }+ return @("# Guest account was already disabled; no rollback action required")+ }+ }+ [PSCustomObject]@{+ Name = 'Enable PowerShell script block logging'+ FindingPattern = 'script block logging|scriptblocklogging|powershell logging'+ RequiresAdmin = $true+ Action = {+ if (-not (Test-Path $psLoggingPath)) {+ New-Item -Path $psLoggingPath -Force -ErrorAction Stop | Out-Null+ }+ Set-ItemProperty -Path $psLoggingPath -Name "EnableScriptBlockLogging" -Value 1 -Type DWord -Force -ErrorAction Stop+ }+ Verify = {+ $current = Get-ItemProperty -Path $psLoggingPath -Name "EnableScriptBlockLogging" -ErrorAction Stop+ return ($current.EnableScriptBlockLogging -eq 1)+ }+ Rollback = {+ $previous = 0+ $existed = $false+ try {+ $current = Get-ItemProperty -Path $psLoggingPath -Name "EnableScriptBlockLogging" -ErrorAction Stop+ if ($null -ne $current.EnableScriptBlockLogging) {+ $previous = $current.EnableScriptBlockLogging+ $existed = $true+ }+ }+ catch {+ $existed = $false+ }+ if ($existed) {+ return @("Set-ItemProperty -Path '$psLoggingPath' -Name 'EnableScriptBlockLogging' -Value $previous -Type DWord -Force")+ }+ return @("Remove-ItemProperty -Path '$psLoggingPath' -Name 'EnableScriptBlockLogging' -ErrorAction SilentlyContinue")+ }+ }+ [PSCustomObject]@{+ Name = 'Enable RDP Network Level Authentication'+ FindingPattern = 'network level authentication|\bnla\b'+ RequiresAdmin = $true+ Action = {+ Set-ItemProperty -Path $rdpTcpPath -Name "UserAuthentication" -Value 1 -Type DWord -Force -ErrorAction Stop+ }+ Verify = {+ $current = Get-ItemProperty -Path $rdpTcpPath -Name "UserAuthentication" -ErrorAction Stop+ return ($current.UserAuthentication -eq 1)+ }+ Rollback = {+ $previous = 0+ try {+ $current = Get-ItemProperty -Path $rdpTcpPath -Name "UserAuthentication" -ErrorAction Stop+ if ($null -ne $current.UserAuthentication) { $previous = $current.UserAuthentication }+ }+ catch {+ $previous = 0+ }+ return @("Set-ItemProperty -Path '$rdpTcpPath' -Name 'UserAuthentication' -Value $previous -Type DWord -Force")+ }+ }+ )+ }++ process {+ if ($PSCmdlet.ParameterSetName -eq 'Object') {+ if ($null -ne $InputObject) {+ $collectedFindings += $InputObject+ }+ }+ }++ end {+ try {+ # --- Gather findings ---+ $rawInput = @()+ if ($PSCmdlet.ParameterSetName -eq 'File') {+ Write-Host "`n[LOAD] Reading assessment from: $AssessmentPath" -ForegroundColor Cyan+ try {+ $rawInput = @(Get-Content -Path $AssessmentPath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop)+ }+ catch {+ Write-Error "Failed to read or parse assessment file '$AssessmentPath': $_"+ throw+ }+ }+ else {+ $rawInput = $collectedFindings+ }++ # Unwrap: an assessment object carries a Findings array; a bare finding carries Finding text+ $allFindings = @()+ foreach ($item in $rawInput) {+ if ($null -eq $item) { continue }+ if ($null -ne $item.PSObject.Properties['Findings'] -and $null -ne $item.Findings) {+ $allFindings += @($item.Findings)+ }+ elseif ($null -ne $item.PSObject.Properties['Finding']) {+ $allFindings += $item+ }+ }++ $results.FindingsProcessed = @($allFindings).Count+ Write-Host "[LOAD] Findings loaded: $($results.FindingsProcessed)" -ForegroundColor Yellow++ # --- Per-finding remediation ---+ $findingIndex = 0+ foreach ($finding in $allFindings) {+ $findingIndex++++ $findingText = ''+ if ($null -ne $finding.PSObject.Properties['Finding'] -and $null -ne $finding.Finding) {+ $findingText = [string]$finding.Finding+ }++ $severityText = ''+ if ($null -ne $finding.PSObject.Properties['Severity'] -and $null -ne $finding.Severity) {+ $severityText = [string]$finding.Severity+ }++ # Severity gate: findings with unrecognized severity are never auto-remediated+ if ([string]::IsNullOrWhiteSpace($severityText) -or -not $severityRank.ContainsKey($severityText)) {+ Write-Host "`n[$findingIndex] Unrecognized severity - routed to manual review: $findingText" -ForegroundColor Yellow+ $results.ManualReview += [PSCustomObject]@{+ Finding = $findingText+ Severity = $severityText+ Reason = 'Severity missing or unrecognized; not eligible for automated remediation'+ }+ continue+ }++ if ($severityRank[$severityText] -lt $threshold) {+ $results.SkippedBelowThreshold+++ Write-Verbose "[$findingIndex] Skipped (severity $severityText below threshold $MaxSeverity): $findingText"+ continue+ }++ # Match against the curated remediation map - first match wins+ $matched = $null+ if (-not [string]::IsNullOrWhiteSpace($findingText)) {+ foreach ($entry in $remediationMap) {+ if ($findingText -match $entry.FindingPattern) {+ $matched = $entry+ break+ }+ }+ }++ if ($null -eq $matched) {+ Write-Host "`n[$findingIndex] No automated remediation available: $findingText" -ForegroundColor Yellow+ $results.ManualReview += [PSCustomObject]@{+ Finding = $findingText+ Severity = $severityText+ Reason = 'No matching remediation in the curated map; manual review required'+ }+ continue+ }++ Write-Host "`n[$findingIndex] [$severityText] $findingText" -ForegroundColor Cyan+ Write-Host " Remediation: $($matched.Name) (RequiresAdmin: $($matched.RequiresAdmin))" -ForegroundColor White++ if (-not $PSCmdlet.ShouldProcess($findingText, "Apply remediation '$($matched.Name)'")) {+ Write-Host " WhatIf: would apply '$($matched.Name)'" -ForegroundColor Magenta+ continue+ }++ # Capture pre-change state BEFORE applying the fix (for the rollback script)+ $capturedRollback = @()+ if ($GenerateRollback) {+ try {+ $capturedRollback = @(& $matched.Rollback)+ }+ catch {+ Write-Warning " Could not capture pre-change state for rollback: $_"+ $capturedRollback = @("# WARNING: pre-change state could not be captured: $($_.Exception.Message)")+ }+ }++ try {+ & $matched.Action++ # Verify-after-fix where cheap (re-read the setting)+ $verified = $false+ try {+ $verified = [bool](& $matched.Verify)+ }+ catch {+ Write-Verbose " Verification check failed: $_"+ $verified = $false+ }++ $results.Remediated += [PSCustomObject]@{+ Finding = $findingText+ Severity = $severityText+ Remediation = $matched.Name+ Verified = $verified+ }++ if ($verified) {+ Write-Host " + Remediated and verified" -ForegroundColor Green+ }+ else {+ Write-Host " + Remediated (verification inconclusive)" -ForegroundColor Yellow+ }++ if ($GenerateRollback -and @($capturedRollback).Count -gt 0) {+ $rollbackScriptLines += "# Rollback for: $findingText"+ $rollbackScriptLines += "# Remediation applied: $($matched.Name) on $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"+ $rollbackScriptLines += $capturedRollback+ $rollbackScriptLines += ""+ }+ }+ catch {+ $results.Failed += [PSCustomObject]@{+ Finding = $findingText+ Severity = $severityText+ Remediation = $matched.Name+ Error = $_.Exception.Message+ }+ Write-Warning " Remediation failed: $($_.Exception.Message)"+ }+ }++ # --- Write rollback script (captured pre-change values only) ---+ if ($GenerateRollback -and @($rollbackScriptLines).Count -gt 0) {+ try {+ if (-not (Test-Path -Path $RollbackDirectory)) {+ New-Item -Path $RollbackDirectory -ItemType Directory -Force | Out-Null+ }+ $rollbackFile = Join-Path -Path $RollbackDirectory -ChildPath "SecurityRemediation_Rollback_$(Get-Date -Format 'yyyyMMdd_HHmmss').ps1"++ $header = @(+ "#Requires -RunAsAdministrator"+ "# Rollback script generated by Invoke-SecurityRemediation"+ "# Generated: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"+ "# Restores the pre-remediation state captured BEFORE changes were applied"+ ""+ )++ if ($PSCmdlet.ShouldProcess($rollbackFile, "Write rollback script")) {+ Set-Content -Path $rollbackFile -Value (($header + $rollbackScriptLines) -join [Environment]::NewLine) -Encoding UTF8 -ErrorAction Stop+ $results.RollbackPath = $rollbackFile+ Write-Host "`n[ROLLBACK] Rollback script written: $rollbackFile" -ForegroundColor Green+ }+ else {+ Write-Host "`n[ROLLBACK] WhatIf: would write rollback script to $rollbackFile" -ForegroundColor Magenta+ }+ }+ catch {+ Write-Warning "Failed to write rollback script: $_"+ }+ }+ elseif ($GenerateRollback) {+ Write-Host "`n[ROLLBACK] No changes were applied; rollback script not needed" -ForegroundColor Yellow+ }+ }+ catch {+ Write-Error "Error during security remediation: $_"+ throw+ }++ Write-Host "`n=== REMEDIATION COMPLETE ===" -ForegroundColor Green++ Write-Host "`nFindings Processed: $($results.FindingsProcessed)" -ForegroundColor Cyan+ Write-Host " Remediated: $(@($results.Remediated).Count)" -ForegroundColor Green+ Write-Host " Manual Review: $(@($results.ManualReview).Count)" -ForegroundColor Yellow+ Write-Host " Failed: $(@($results.Failed).Count)" -ForegroundColor Red+ Write-Host " Skipped (below $MaxSeverity): $($results.SkippedBelowThreshold)" -ForegroundColor White++ if (@($results.ManualReview).Count -gt 0) {+ Write-Host "`nFindings requiring manual review:" -ForegroundColor Yellow+ $results.ManualReview | ForEach-Object {+ Write-Host " - [$($_.Severity)] $($_.Finding)" -ForegroundColor White+ }+ }++ if (@($results.Failed).Count -gt 0) {+ Write-Host "`nFailed remediations:" -ForegroundColor Red+ $results.Failed | ForEach-Object {+ Write-Host " - $($_.Finding): $($_.Error)" -ForegroundColor Red+ }+ }++ if ($null -ne $results.RollbackPath) {+ Write-Host "`nRollback script: $($results.RollbackPath)" -ForegroundColor Cyan+ Write-Host " Run it from an elevated session to restore pre-remediation state" -ForegroundColor White+ }++ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ Write-Host " 1. Review the ManualReview findings - no automated fix was attempted for them" -ForegroundColor White+ Write-Host " 2. Test system and application functionality after remediation" -ForegroundColor White+ Write-Host " 3. Keep the rollback script until changes are validated" -ForegroundColor White+ Write-Host " 4. Re-run Invoke-SecurityAssessment to confirm findings are resolved" -ForegroundColor White+ Write-Host " 5. Some changes (e.g. SMBv1) may require a reboot to take full effect" -ForegroundColor White++ return $results+ }+}diff --git a/README.md b/README.mdindex 6a73130..8c8d95e 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)[](https://github.com/okanyildiz/WindowsSecurityAudit/stargazers)@@ -28,7 +28,27 @@## ✨ What's New-### 🆕 v1.2.0 — Live Threat Feeds & Real CVE Integration+### 🆕 v1.3.0 — Version-Exact CVEs, MISP/TAXII & Auto-Remediation++**2 new functions** — bringing the toolkit to **65 functions across 14 modules**:++| Function | Module | What It Does |+|----------|--------|--------------|+| **`Resolve-CpeName`** | Vulnerability | Resolve an installed product to a **CPE 2.3 name** via a curated offline mapping table (~35 common products), an optional **NVD CPE API** lookup (`-UseOnlineLookup -ApiKey`), or a heuristic guess (always **Low** confidence) — returns `CpeName`, `MatchedBy`, `Confidence` and `Version` |+| **`Invoke-SecurityRemediation`** | Hardening | Close the finding→fix loop: consume an `Invoke-SecurityAssessment` JSON (or piped findings), apply a **curated map of 7 safe remediations** (firewall profiles, UAC, Defender RTP, SMBv1, Guest account, PS script block logging, RDP NLA) **WhatIf-first** with `SupportsShouldProcess`/`ConfirmImpact=High`, optional `-GenerateRollback` script capturing pre-change state — unmatched findings go to `ManualReview`, never improvised |++**Wired-up parameters on existing functions:**++- `Get-VulnerabilityAssessment -ExactCVEMatch` — resolve each installed product to a CPE name and query NVD for **version-exact CVE matches** (implies `-CheckCVEs`, reuses `-NVDApiKey`/`-MaxCVEChecks`); High/Medium-confidence CPE matches query via `Get-NVDCveData -CpeName`, results attach as `ExactCVEs` per application with `MatchStatus` (`CpeMatched`/`NoCpeMapping`) plus `TotalExactCVEs` and per-severity counts in the summary+- `Get-ThreatIntelligence -MISPUrl -MISPApiKey` — pull indicators from a **MISP** instance via `attributes/restSearch` (key sent only as a request header)+- `Get-ThreatIntelligence -TaxiiServerUrl -TaxiiCollection [-TaxiiUsername -TaxiiPassword]` — pull STIX indicators from a **TAXII 2.x** server (discovery → collections → objects; password is a `SecureString`, sent only as a Basic auth header)+- `Get-ThreatIntelligence -StixFilePath` — import a local **STIX 2.x bundle** fully offline; regex extraction of ipv4-addr/domain-name/url/file-hash patterns — all sources share the existing cache, entry-cap and provenance machinery++**Quality infrastructure:**++- 🧪 **353 Pester tests** (`tests/WindowsSecurityAudit.Tests.ps1`) — new coverage for v1.3 parameter help, secret-handling AST checks (no API keys in log output, `SecureString` TAXII password), and remediation safety (ShouldProcess gating, ManualReview routing)++### v1.2.0 — Live Threat Feeds & Real CVE Integration**1 new function** — bringing the toolkit to **63 functions across 14 modules**:@@ -107,7 +127,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 63 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 65 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@@ -157,7 +177,7 @@ A single, cohesive PowerShell module that consolidates essential security functi</tr><tr><td><strong>Functions</strong></td>-<td>✅ 63 Comprehensive</td>+<td>✅ 65 Comprehensive</td><td>⚠️ 20-30 Limited</td><td>⚠️ 5-15 Basic</td></tr>@@ -260,9 +280,10 @@ WindowsSecurityAudit/│ ├── Get-USBHistory.ps1│ └── New-ForensicTimeline.ps1│-├── 📁 Hardening/ # Security Hardening (3 functions)+├── 📁 Hardening/ # Security Hardening (4 functions)│ ├── Enable-AuditPolicies.ps1│ ├── Enable-PowerShellSecurity.ps1+│ ├── Invoke-SecurityRemediation.ps1│ └── Set-SecurityBaseline.ps1│├── 📁 Private/ # Internal functions (hidden)@@ -278,7 +299,7 @@ WindowsSecurityAudit/│ ├── Invoke-ForensicCollection.ps1│ └── Invoke-IncidentResponse.ps1│-├── 📁 tests/ # Pester tests (333 tests)+├── 📁 tests/ # Pester tests (353 tests)│ └── WindowsSecurityAudit.Tests.ps1│├── 📁 ThreatHunting/ # Threat Hunting (7 functions)@@ -290,12 +311,13 @@ WindowsSecurityAudit/│ ├── Get-MITREAttackMapping.ps1│ └── Get-ThreatIntelligence.ps1│-├── 📁 Vulnerability/ # Vulnerability Management (7 functions)+├── 📁 Vulnerability/ # Vulnerability Management (8 functions)│ ├── Find-EOLSoftware.ps1│ ├── Get-ExposedServices.ps1│ ├── Get-NVDCveData.ps1│ ├── Get-SecurityMisconfigurations.ps1│ ├── Get-VulnerabilityAssessment.ps1+│ ├── Resolve-CpeName.ps1│ ├── Test-CertificateHealth.ps1│ └── Test-PatchCompliance.ps1│@@ -340,7 +362,7 @@ Install-Module -Name WindowsSecurityAudit -Scope CurrentUser -Force# Import the moduleImport-Module WindowsSecurityAudit-# Verify installation - should return 63+# Verify installation - should return 65(Get-Command -Module WindowsSecurityAudit).Count```@@ -454,6 +476,19 @@ Get-VulnerabilityAssessment -CheckCVEs -NVDApiKey $keyGet-ThreatIntelligence -CheckNetwork -UpdateFeeds```+### Version-Exact CVEs & Automated Remediation (New in v1.3.0)+```powershell+# Version-exact CVE matching: resolve installed products to CPE names first+Get-VulnerabilityAssessment -ExactCVEMatch -NVDApiKey $key++# Import a STIX 2.x bundle fully offline, or pull from MISP/TAXII+Get-ThreatIntelligence -CheckNetwork -StixFilePath "C:\intel\bundle.json"++# Assess, then preview automated fixes with a rollback script (no changes yet)+Invoke-SecurityAssessment -OutputPath "C:\Assessments"+Invoke-SecurityRemediation -AssessmentPath "C:\Assessments\SecurityAssessment.json" -GenerateRollback -WhatIf+```+### 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@@ -543,7 +578,7 @@ The Enterprise module enables security operations at scale, providing centralize----### 6️⃣ Hardening Module (3 Functions)+### 6️⃣ Hardening Module (4 Functions)The Hardening module implements security best practices and configurations to reduce attack surface and improve system resilience. These functions apply industry-standard security baselines and monitoring configurations.@@ -552,6 +587,7 @@ The Hardening module implements security best practices and configurations to re| **`Set-SecurityBaseline`** | Applies comprehensive security configurations | • 50+ security settings<br>• CIS Level 1/2 benchmarks<br>• Microsoft Security Baseline<br>• DISA STIG implementation<br>• Custom baseline support<br>• Rollback capability | CIS: 95%+<br>NIST: High<br>PCI: Compliant || **`Enable-PowerShellSecurity`** | Hardens PowerShell environment | • Constrained Language Mode<br>• Script Block Logging<br>• Module Logging<br>• Transcription<br>• AMSI integration<br>• JEA configuration | Blocks 90% of PS attacks<br>Full audit trail<br>Malware prevention || **`Enable-AuditPolicies`** | Configures advanced security auditing | • Process creation with command line<br>• Logon/Logoff tracking<br>• Object access monitoring<br>• Privilege use auditing<br>• System integrity monitoring<br>• Account management tracking | Complete visibility<br>Forensic capability<br>Compliance ready |+| **`Invoke-SecurityRemediation`** | Applies automated fixes for assessment findings | • Consumes Invoke-SecurityAssessment JSON or piped findings<br>• Curated map of 7 safe remediations (firewall, UAC, Defender RTP, SMBv1, Guest, PS logging, RDP NLA)<br>• Severity filter (`-MaxSeverity`)<br>• WhatIf/Confirm first (ConfirmImpact High)<br>• `-GenerateRollback` captures pre-change state<br>• Unmatched findings routed to ManualReview | Finding-to-fix loop<br>Verified changes<br>Rollback script |---@@ -612,7 +648,7 @@ The Active Directory module provides specialized security assessment for AD envi----### 1️⃣1️⃣ Vulnerability Module (7 Functions)+### 1️⃣1️⃣ Vulnerability Module (8 Functions)The Vulnerability module identifies, assesses, and prioritizes security weaknesses across the environment, providing actionable remediation guidance based on exploitability and business impact.@@ -620,6 +656,7 @@ The Vulnerability module identifies, assesses, and prioritizes security weakness|----------|---------|------------------|------------------|| **`Get-VulnerabilityAssessment`** | Comprehensive vulnerability scanning | • CVE identification<br>• Real NVD CVE matching (`-CheckCVEs`)<br>• CVSS scoring (v3.1)<br>• Exploit availability (EPSS)<br>• Patch availability<br>• Workaround options<br>• Asset criticality | Critical: CVSS 9.0+<br>High: CVSS 7.0-8.9<br>Medium: CVSS 4.0-6.9<br>Low: CVSS 0-3.9 || **`Get-NVDCveData`** | Queries the NVD API 2.0 for real CVE data | • Keyword or CPE 2.3 name search<br>• Normalized CVE objects (ID, description, references)<br>• CVSS v3.1/v3.0/v2 severity and score<br>• Automatic pagination<br>• NVD rate-limit handling<br>• Optional API key for higher limits | CVSS base severity<br>(Critical/High/Medium/Low) |+| **`Resolve-CpeName`** | Resolves installed products to CPE 2.3 names | • Curated offline table (~35 products)<br>• Optional NVD CPE API lookup (`-UseOnlineLookup -ApiKey`)<br>• Heuristic fallback (Low confidence)<br>• Version string normalization<br>• Confidence + MatchedBy provenance<br>• API key never logged | High: curated + version<br>Medium: curated/online<br>Low: heuristic || **`Get-SecurityMisconfigurations`** | Identifies configuration weaknesses | • Weak file permissions<br>• Default credentials<br>• Open network shares<br>• Service account issues<br>• Registry permissions<br>• Group Policy gaps | Exploitability rating<br>Impact assessment<br>Fix complexity || **`Find-EOLSoftware`** | Detects unsupported software | • End-of-life products<br>• Unsupported versions<br>• Legacy applications<br>• Missing security updates<br>• Vendor bulletins<br>• Migration paths | Support status<br>Risk exposure<br>Upgrade options || **`Get-ExposedServices`** | Maps attack surface | • Internet-facing services<br>• Weak protocols (SMBv1, TLS 1.0)<br>• Default configurations<br>• Unnecessary services<br>• Port exposure<br>• Authentication methods | External exposure<br>Protocol weaknesses<br>Access controls |@@ -719,7 +756,7 @@ The Reporting module transforms raw security data into actionable intelligence t### Community Edition - Forever FREE- ✅ **Price**: 100% FREE - No hidden costs-- ✅ **Functions**: All 63 functions included+- ✅ **Functions**: All 65 functions included- ✅ **Source Code**: Full access on GitHub- ✅ **Updates**: Regular security updates- ✅ **License**: MIT (commercial use allowed)@@ -819,10 +856,10 @@ We work with Fortune 500 companies, government agencies, and organizations of al## 🚀 Roadmap-### Version 1.3 (Next)-- [ ] **Version-exact CVE matching (CPE-based)** — honest note: the v1.2.0 NVD integration performs *keyword-based candidate matching* (vendor + product name). It surfaces likely-relevant CVEs, not definitive "your exact version is vulnerable" verdicts. Precise matching requires mapping installed software to CPE identifiers (vendor/product/version tuples), which the registry inventory does not provide today — v1.3 aims to build that CPE dictionary layer-- [ ] Additional threat feeds (MISP, STIX/TAXII sources)-- [ ] Automated remediation workflows+### Version 1.4 (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### Version 2.0 (Future)- [ ] Web-based GUI dashboarddiff --git a/ThreatHunting/Get-ThreatIntelligence.ps1 b/ThreatHunting/Get-ThreatIntelligence.ps1index c4d6080..daf680e 100644--- a/ThreatHunting/Get-ThreatIntelligence.ps1+++ b/ThreatHunting/Get-ThreatIntelligence.ps1@@ -25,10 +25,27 @@ function Get-ThreatIntelligence {Maximum number of feed-derived indicators merged into the IOC database (default: 5000).PARAMETER AbuseIPDBApiKeyOptional AbuseIPDB API key; enables the AbuseIPDB blacklist feed (sent only as a request header)+ .PARAMETER MISPUrl+ Base URL of a MISP instance (requires -MISPApiKey); attributes are pulled via attributes/restSearch+ .PARAMETER MISPApiKey+ MISP API auth key (requires -MISPUrl); sent only as the Authorization request header and never logged+ .PARAMETER TaxiiServerUrl+ Base 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)+ .PARAMETER TaxiiUsername+ Optional TAXII username; sent only as a Basic auth request header together with -TaxiiPassword+ .PARAMETER TaxiiPassword+ Optional TAXII password (SecureString); sent only as a Basic auth request header together with -TaxiiUsername+ .PARAMETER StixFilePath+ Path to a local STIX 2.x JSON bundle file; indicators are imported fully offline.EXAMPLEGet-ThreatIntelligence -CheckProcesses -CheckNetworkGet-ThreatIntelligence -CheckProcesses -CheckNetwork -CheckFiles -IOCFile "C:\iocs.json"Get-ThreatIntelligence -CheckNetwork -UpdateFeeds -FeedMaxAgeHours 12+ Get-ThreatIntelligence -CheckNetwork -UpdateFeeds -MISPUrl "https://misp.example.com" -MISPApiKey "your-api-key"+ Get-ThreatIntelligence -CheckNetwork -UpdateFeeds -TaxiiServerUrl "https://taxii.example.com" -TaxiiCollection "12345678-1234-1234-1234-123456789012"+ Get-ThreatIntelligence -CheckNetwork -StixFilePath "C:\intel\bundle.json".OUTPUTSPSCustomObject with IOC match results#>@@ -63,7 +80,28 @@ function Get-ThreatIntelligence {[int]$MaxFeedEntries = 5000,[Parameter()]- [string]$AbuseIPDBApiKey+ [string]$AbuseIPDBApiKey,++ [Parameter()]+ [string]$MISPUrl,++ [Parameter()]+ [string]$MISPApiKey,++ [Parameter()]+ [string]$TaxiiServerUrl,++ [Parameter()]+ [string]$TaxiiCollection,++ [Parameter()]+ [string]$TaxiiUsername,++ [Parameter()]+ [SecureString]$TaxiiPassword,++ [Parameter()]+ [string]$StixFilePath)begin {@@ -140,6 +178,132 @@ function Get-ThreatIntelligence {# Live threat intelligence feeds$feedStats = @()+ $feedEntryCount = 0+ $networkIndicatorKeys = @{}++ $mispEnabled = $false+ if (-not [string]::IsNullOrWhiteSpace($MISPUrl) -or -not [string]::IsNullOrWhiteSpace($MISPApiKey)) {+ if ([string]::IsNullOrWhiteSpace($MISPUrl) -or [string]::IsNullOrWhiteSpace($MISPApiKey)) {+ Write-Warning "-MISPUrl and -MISPApiKey must be provided together - skipping MISP feed"+ }+ else {+ $mispEnabled = $true+ }+ }++ $taxiiEnabled = $false+ if (-not [string]::IsNullOrWhiteSpace($TaxiiServerUrl) -or -not [string]::IsNullOrWhiteSpace($TaxiiCollection)) {+ if ([string]::IsNullOrWhiteSpace($TaxiiServerUrl) -or [string]::IsNullOrWhiteSpace($TaxiiCollection)) {+ Write-Warning "-TaxiiServerUrl and -TaxiiCollection must be provided together - skipping TAXII feed"+ }+ else {+ $taxiiEnabled = $true+ $hasTaxiiPassword = ($null -ne $TaxiiPassword -and $TaxiiPassword.Length -gt 0)+ if ([string]::IsNullOrWhiteSpace($TaxiiUsername) -ne (-not $hasTaxiiPassword)) {+ Write-Warning "-TaxiiUsername and -TaxiiPassword must be provided together - continuing without TAXII authentication"+ $TaxiiUsername = $null+ $TaxiiPassword = $null+ }+ }+ }++ $addFeedIndicator = {+ param(+ [string]$Kind,+ [string]$Value,+ [string]$Severity,+ [string]$Description+ )+ if ($feedEntryCount -ge $MaxFeedEntries) { return 0 }+ if ([string]::IsNullOrWhiteSpace($Value)) { return 0 }++ if ($Kind -eq 'ip') {+ if ($Value -notmatch '^\d{1,3}(\.\d{1,3}){3}$') { return 0 }+ if (-not $iocDatabase.MaliciousIPs.ContainsKey($Value)) {+ $iocDatabase.MaliciousIPs[$Value] = @{ Severity = $Severity; Description = $Description }+ $feedEntryCount+++ return 1+ }+ }+ elseif ($Kind -eq 'domain') {+ $escapedHost = [regex]::Escape($Value)+ if (-not $networkIndicatorKeys.ContainsKey($escapedHost)) {+ $networkIndicatorKeys[$escapedHost] = $true+ $iocDatabase.SuspiciousPatterns.NetworkIndicators += @{ Pattern = $escapedHost; Severity = $Severity; Description = $Description }+ $feedEntryCount+++ return 1+ }+ }+ elseif ($Kind -eq 'url') {+ $indicatorUri = $null+ try { $indicatorUri = [System.Uri]$Value } catch { return 0 }+ if ($null -eq $indicatorUri) { return 0 }+ $indicatorHost = $indicatorUri.Host+ if ([string]::IsNullOrWhiteSpace($indicatorHost)) { return 0 }+ if ($indicatorHost -match '^\d{1,3}(\.\d{1,3}){3}$') {+ if (-not $iocDatabase.MaliciousIPs.ContainsKey($indicatorHost)) {+ $iocDatabase.MaliciousIPs[$indicatorHost] = @{ Severity = $Severity; Description = "$Description host" }+ $feedEntryCount+++ return 1+ }+ }+ else {+ $escapedHost = [regex]::Escape($indicatorHost)+ if (-not $networkIndicatorKeys.ContainsKey($escapedHost)) {+ $networkIndicatorKeys[$escapedHost] = $true+ $iocDatabase.SuspiciousPatterns.NetworkIndicators += @{ Pattern = $escapedHost; Severity = $Severity; Description = "$Description host" }+ $feedEntryCount+++ return 1+ }+ }+ }+ elseif ($Kind -eq 'md5' -or $Kind -eq 'sha256') {+ $hashValue = $Value.ToLower()+ if ($hashValue -notmatch '^[0-9a-f]+$') { return 0 }+ if (-not $iocDatabase.MaliciousHashes.ContainsKey($hashValue)) {+ $iocDatabase.MaliciousHashes[$hashValue] = @{ Severity = $Severity; Description = $Description }+ $feedEntryCount+++ return 1+ }+ }+ return 0+ }++ $extractStixIndicators = {+ param(+ [string]$Pattern,+ [string]$SourceName+ )+ $extracted = @()+ if ([string]::IsNullOrWhiteSpace($Pattern)) { return $extracted }+ $matchedAny = $false++ foreach ($regexMatch in [regex]::Matches($Pattern, "\[ipv4-addr:value\s*=\s*'([^']+)'\]")) {+ $matchedAny = $true+ $extracted += @{ Kind = 'ip'; Value = $regexMatch.Groups[1].Value; Label = 'ipv4-addr' }+ }+ foreach ($regexMatch in [regex]::Matches($Pattern, "\[domain-name:value\s*=\s*'([^']+)'\]")) {+ $matchedAny = $true+ $extracted += @{ Kind = 'domain'; Value = $regexMatch.Groups[1].Value; Label = 'domain-name' }+ }+ foreach ($regexMatch in [regex]::Matches($Pattern, "\[url:value\s*=\s*'([^']+)'\]")) {+ $matchedAny = $true+ $extracted += @{ Kind = 'url'; Value = $regexMatch.Groups[1].Value; Label = 'url' }+ }+ foreach ($regexMatch in [regex]::Matches($Pattern, "\[file:hashes\.'SHA-256'\s*=\s*'([^']+)'\]")) {+ $matchedAny = $true+ $extracted += @{ Kind = 'sha256'; Value = $regexMatch.Groups[1].Value; Label = 'SHA-256' }+ }+ foreach ($regexMatch in [regex]::Matches($Pattern, "\[file:hashes\.MD5\s*=\s*'([^']+)'\]")) {+ $matchedAny = $true+ $extracted += @{ Kind = 'md5'; Value = $regexMatch.Groups[1].Value; Label = 'MD5' }+ }++ if (-not $matchedAny) {+ Write-Verbose "Unrecognized STIX pattern from ${SourceName}: $Pattern"+ }+ return $extracted+ }if ($UpdateFeeds -or (Test-Path $FeedCachePath)) {Write-Host "`nProcessing live threat intelligence feeds..." -ForegroundColor Cyan@@ -169,9 +333,6 @@ function Get-ThreatIntelligence {}}- $feedEntryCount = 0- $networkIndicatorKeys = @{}-foreach ($feed in $feedDefinitions) {if ($feedEntryCount -ge $MaxFeedEntries) {Write-Warning "Feed entry cap ($MaxFeedEntries) reached - skipping remaining feeds"@@ -283,6 +444,234 @@ function Get-ThreatIntelligence {}}+ if ($mispEnabled) {+ if ($feedEntryCount -ge $MaxFeedEntries) {+ Write-Warning "Feed entry cap ($MaxFeedEntries) reached - skipping MISP feed"+ }+ else {+ $mispCacheFile = Join-Path $FeedCachePath 'misp_attributes.json'+ $mispResponse = $null+ $mispSource = 'none'+ $mispCacheAgeHours = $null+ $mispCacheExists = Test-Path $mispCacheFile++ if ($mispCacheExists) {+ $mispCacheItem = Get-Item $mispCacheFile+ $mispCacheAgeHours = [math]::Round(((Get-Date) - $mispCacheItem.LastWriteTime).TotalHours, 1)+ }++ $mispShouldDownload = $UpdateFeeds -and (-not $mispCacheExists -or $mispCacheAgeHours -ge $FeedMaxAgeHours)++ if ($mispShouldDownload) {+ try {+ Write-Host " Querying MISP instance at $MISPUrl..." -ForegroundColor Yellow+ $mispBody = @{+ returnFormat = 'json'+ type = @('ip-dst', 'domain', 'url', 'md5', 'sha256')+ 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+ if ($null -eq $mispResponse) { throw "MISP returned an empty response" }+ ($mispResponse | ConvertTo-Json -Depth 10) | Set-Content -Path $mispCacheFile -ErrorAction Stop+ $mispSource = 'download'+ $mispCacheItem = Get-Item $mispCacheFile+ $mispCacheAgeHours = [math]::Round(((Get-Date) - $mispCacheItem.LastWriteTime).TotalHours, 1)+ }+ catch {+ if ($mispCacheExists) {+ Write-Warning "Failed to query MISP - falling back to cached copy ($mispCacheAgeHours hours old): $_"+ try {+ $mispResponse = Get-Content $mispCacheFile -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop+ $mispSource = 'cache'+ }+ catch {+ Write-Warning "Could not read MISP cache file: $_"+ }+ }+ else {+ Write-Warning "Failed to query MISP and no cache available - using built-in IOCs only: $_"+ }+ }+ }+ elseif ($mispCacheExists) {+ try {+ $mispResponse = Get-Content $mispCacheFile -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop+ $mispSource = 'cache'+ }+ catch {+ Write-Warning "Could not read MISP cache file: $_"+ }+ if ($null -ne $mispCacheAgeHours -and $mispCacheAgeHours -ge $FeedMaxAgeHours) {+ Write-Host " MISP cache is $mispCacheAgeHours hours old - run with -UpdateFeeds to refresh" -ForegroundColor Yellow+ }+ }++ $mispEntriesAdded = 0++ if ($null -ne $mispResponse) {+ $mispAttributes = @()+ if ($mispResponse.PSObject.Properties['response'] -and $null -ne $mispResponse.response -and $mispResponse.response.PSObject.Properties['Attribute']) {+ $mispAttributes = @($mispResponse.response.Attribute)+ }++ foreach ($attribute in $mispAttributes) {+ if ($feedEntryCount -ge $MaxFeedEntries) { break }+ if ($null -eq $attribute) { continue }+ if (-not $attribute.PSObject.Properties['type'] -or -not $attribute.PSObject.Properties['value']) { continue }+ $attributeType = [string]$attribute.type+ $attributeValue = [string]$attribute.value+ if ([string]::IsNullOrWhiteSpace($attributeValue)) { continue }++ $indicatorKind = $null+ switch ($attributeType) {+ 'ip-dst' { $indicatorKind = 'ip' }+ 'domain' { $indicatorKind = 'domain' }+ 'url' { $indicatorKind = 'url' }+ 'md5' { $indicatorKind = 'md5' }+ 'sha256' { $indicatorKind = 'sha256' }+ }+ if ($null -eq $indicatorKind) {+ Write-Verbose "Skipping unsupported MISP attribute type: $attributeType"+ continue+ }++ $mispEntriesAdded += (. $addFeedIndicator -Kind $indicatorKind -Value $attributeValue -Severity 'High' -Description "MISP attribute ($attributeType)")+ }+ }++ $feedStats += [PSCustomObject]@{+ Feed = 'MISP'+ EntryCount = $mispEntriesAdded+ CacheAgeHours = $mispCacheAgeHours+ Source = $mispSource+ }+ }+ }++ if ($taxiiEnabled) {+ if ($feedEntryCount -ge $MaxFeedEntries) {+ Write-Warning "Feed entry cap ($MaxFeedEntries) reached - skipping TAXII feed"+ }+ else {+ $taxiiCacheFile = Join-Path $FeedCachePath 'taxii_indicators.json'+ $taxiiObjects = $null+ $taxiiSource = 'none'+ $taxiiCacheAgeHours = $null+ $taxiiCacheExists = Test-Path $taxiiCacheFile++ if ($taxiiCacheExists) {+ $taxiiCacheItem = Get-Item $taxiiCacheFile+ $taxiiCacheAgeHours = [math]::Round(((Get-Date) - $taxiiCacheItem.LastWriteTime).TotalHours, 1)+ }++ $taxiiShouldDownload = $UpdateFeeds -and (-not $taxiiCacheExists -or $taxiiCacheAgeHours -ge $FeedMaxAgeHours)++ if ($taxiiShouldDownload) {+ try {+ Write-Host " Querying TAXII server at $TaxiiServerUrl (collection '$TaxiiCollection')..." -ForegroundColor Yellow+ $taxiiHeaders = @{ 'Accept' = 'application/taxii+json;version=2.1' }+ if (-not [string]::IsNullOrWhiteSpace($TaxiiUsername) -and $null -ne $TaxiiPassword) {+ $taxiiPasswordPlain = [System.Net.NetworkCredential]::new([string]::Empty, $TaxiiPassword).Password+ $credentialPair = "$($TaxiiUsername):$taxiiPasswordPlain"+ $taxiiHeaders['Authorization'] = 'Basic ' + [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($credentialPair))+ }++ $taxiiBase = $TaxiiServerUrl.TrimEnd('/')+ $discovery = Invoke-RestMethod -Method Get -Uri "$taxiiBase/taxii2/" -Headers $taxiiHeaders -TimeoutSec 30 -ErrorAction Stop+ $apiRoots = @()+ if ($null -ne $discovery -and $discovery.PSObject.Properties['api_roots'] -and $null -ne $discovery.api_roots) {+ $apiRoots = @($discovery.api_roots)+ }+ if ($apiRoots.Count -eq 0) { throw "TAXII discovery returned no API roots" }++ $apiRoot = ([string]$apiRoots[0]).TrimEnd('/')+ if ($apiRoot -notmatch '^https?://') {+ $apiRoot = "$taxiiBase/$($apiRoot.TrimStart('/'))"+ }++ $collectionsResponse = Invoke-RestMethod -Method Get -Uri "$apiRoot/collections" -Headers $taxiiHeaders -TimeoutSec 30 -ErrorAction Stop+ $collections = @()+ if ($null -ne $collectionsResponse -and $collectionsResponse.PSObject.Properties['collections'] -and $null -ne $collectionsResponse.collections) {+ $collections = @($collectionsResponse.collections)+ }++ $targetCollectionId = $null+ foreach ($collection in $collections) {+ if ($null -eq $collection) { continue }+ $collectionId = if ($collection.PSObject.Properties['id']) { [string]$collection.id } else { $null }+ $collectionTitle = if ($collection.PSObject.Properties['title']) { [string]$collection.title } else { $null }+ if ($collectionId -eq $TaxiiCollection -or $collectionTitle -eq $TaxiiCollection) {+ $targetCollectionId = $collectionId+ break+ }+ }+ 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)+ }+ ($taxiiObjects | ConvertTo-Json -Depth 10) | Set-Content -Path $taxiiCacheFile -ErrorAction Stop+ $taxiiSource = 'download'+ $taxiiCacheItem = Get-Item $taxiiCacheFile+ $taxiiCacheAgeHours = [math]::Round(((Get-Date) - $taxiiCacheItem.LastWriteTime).TotalHours, 1)+ }+ catch {+ if ($taxiiCacheExists) {+ Write-Warning "Failed to query TAXII server - falling back to cached copy ($taxiiCacheAgeHours hours old): $_"+ try {+ $taxiiObjects = @(Get-Content $taxiiCacheFile -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop)+ $taxiiSource = 'cache'+ }+ catch {+ Write-Warning "Could not read TAXII cache file: $_"+ }+ }+ else {+ Write-Warning "Failed to query TAXII server and no cache available - using built-in IOCs only: $_"+ }+ }+ }+ elseif ($taxiiCacheExists) {+ try {+ $taxiiObjects = @(Get-Content $taxiiCacheFile -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop)+ $taxiiSource = 'cache'+ }+ catch {+ Write-Warning "Could not read TAXII cache file: $_"+ }+ if ($null -ne $taxiiCacheAgeHours -and $taxiiCacheAgeHours -ge $FeedMaxAgeHours) {+ Write-Host " TAXII cache is $taxiiCacheAgeHours hours old - run with -UpdateFeeds to refresh" -ForegroundColor Yellow+ }+ }++ $taxiiEntriesAdded = 0++ if ($null -ne $taxiiObjects) {+ foreach ($stixObject in $taxiiObjects) {+ if ($feedEntryCount -ge $MaxFeedEntries) { break }+ if ($null -eq $stixObject) { continue }+ $objectType = if ($stixObject.PSObject.Properties['type']) { [string]$stixObject.type } else { $null }+ if ($objectType -ne 'indicator') { continue }+ if (-not $stixObject.PSObject.Properties['pattern']) { continue }++ $extracted = @(& $extractStixIndicators -Pattern ([string]$stixObject.pattern) -SourceName 'TAXII')+ foreach ($indicator in $extracted) {+ $taxiiEntriesAdded += (. $addFeedIndicator -Kind $indicator['Kind'] -Value $indicator['Value'] -Severity 'High' -Description "TAXII indicator ($($indicator['Label']))")+ }+ }+ }++ $feedStats += [PSCustomObject]@{+ Feed = 'TAXII'+ EntryCount = $taxiiEntriesAdded+ CacheAgeHours = $taxiiCacheAgeHours+ Source = $taxiiSource+ }+ }+ }+if ($feedEntryCount -gt 0) {Write-Host " Loaded $feedEntryCount indicators from live feeds" -ForegroundColor Green}@@ -291,6 +680,54 @@ function Get-ThreatIntelligence {}}+ # Import indicators from a local STIX 2.x bundle (works fully offline)+ if (-not [string]::IsNullOrWhiteSpace($StixFilePath)) {+ Write-Host "`nImporting STIX bundle from: $StixFilePath" -ForegroundColor Cyan++ if (Test-Path $StixFilePath) {+ try {+ $stixBundle = Get-Content $StixFilePath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop+ $stixObjects = @()+ if ($null -ne $stixBundle -and $stixBundle.PSObject.Properties['objects'] -and $null -ne $stixBundle.objects) {+ $stixObjects = @($stixBundle.objects)+ }++ $stixEntriesAdded = 0++ foreach ($stixObject in $stixObjects) {+ if ($feedEntryCount -ge $MaxFeedEntries) {+ Write-Warning "Feed entry cap ($MaxFeedEntries) reached - skipping remaining STIX file indicators"+ break+ }+ if ($null -eq $stixObject) { continue }+ $objectType = if ($stixObject.PSObject.Properties['type']) { [string]$stixObject.type } else { $null }+ if ($objectType -ne 'indicator') { continue }+ if (-not $stixObject.PSObject.Properties['pattern']) { continue }++ $extracted = @(& $extractStixIndicators -Pattern ([string]$stixObject.pattern) -SourceName 'STIX file')+ foreach ($indicator in $extracted) {+ $stixEntriesAdded += (. $addFeedIndicator -Kind $indicator['Kind'] -Value $indicator['Value'] -Severity 'High' -Description "STIX file indicator ($($indicator['Label']))")+ }+ }++ $feedStats += [PSCustomObject]@{+ Feed = 'STIX File'+ EntryCount = $stixEntriesAdded+ CacheAgeHours = $null+ Source = 'file'+ }++ Write-Host " Imported $stixEntriesAdded indicators from STIX file" -ForegroundColor Green+ }+ catch {+ Write-Warning "Failed to import STIX file '$StixFilePath': $_"+ }+ }+ else {+ Write-Warning "STIX file not found: $StixFilePath"+ }+ }+$results.Summary.FeedStats = $feedStats# Load custom IOCs if provideddiff --git a/Vulnerability/Get-VulnerabilityAssessment.ps1 b/Vulnerability/Get-VulnerabilityAssessment.ps1index 25e249d..2bcf2ba 100644--- a/Vulnerability/Get-VulnerabilityAssessment.ps1+++ b/Vulnerability/Get-VulnerabilityAssessment.ps1@@ -11,6 +11,11 @@ function Get-VulnerabilityAssessment {Query online CVE databases (requires internet).PARAMETER CheckCVEsQuery the NVD API 2.0 for real CVE matches per installed product (requires internet)+ .PARAMETER ExactCVEMatch+ Resolve each installed product to a CPE 2.3 name via Resolve-CpeName and query+ the NVD API 2.0 for version-exact CVE matches (implies -CheckCVEs behavior,+ requires internet). Results are attached as ExactCVEs per application and the+ summary gains TotalExactCVEs plus per-severity exact counts.PARAMETER NVDApiKeyOptional NVD API key for higher rate limits (sent only as a request header).PARAMETER MaxCVEChecks@@ -38,6 +43,9 @@ function Get-VulnerabilityAssessment {[Parameter()][switch]$CheckCVEs,+ [Parameter()]+ [switch]$ExactCVEMatch,+[Parameter()][string]$NVDApiKey,@@ -57,9 +65,10 @@ function Get-VulnerabilityAssessment {Write-Host "=== VULNERABILITY ASSESSMENT ===" -ForegroundColor CyanWrite-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor YellowWrite-Host "Scan Depth: $ScanDepth" -ForegroundColor Yellow- Write-Host "CVE Lookup: $(if($CheckCVEs -or $IncludeCVELookup){'Enabled'}else{'Disabled'})" -ForegroundColor Yellow- if ($CheckCVEs) {+ Write-Host "CVE Lookup: $(if($CheckCVEs -or $IncludeCVELookup -or $ExactCVEMatch){'Enabled'}else{'Disabled'})" -ForegroundColor Yellow+ if ($CheckCVEs -or $ExactCVEMatch) {Write-Host "Max CVE Checks: $MaxCVEChecks" -ForegroundColor Yellow+ Write-Host "Exact CVE Match (CPE): $(if($ExactCVEMatch){'Enabled'}else{'Disabled'})" -ForegroundColor YellowWrite-Host "NVD API Key: $(if($NVDApiKey){'Provided'}else{'Not provided (public rate limits apply)'})" -ForegroundColor Yellow}@@ -298,7 +307,7 @@ function Get-VulnerabilityAssessment {}# 4. CVE ONLINE LOOKUP (if enabled)- if ($CheckCVEs -or $IncludeCVELookup) {+ if ($CheckCVEs -or $IncludeCVELookup -or $ExactCVEMatch) {Write-Host "`n[4/5] Performing online CVE lookup via NVD API..." -ForegroundColor CyanWrite-Host " Note: This may take several minutes (NVD rate limits)..." -ForegroundColor Gray@@ -308,6 +317,14 @@ function Get-VulnerabilityAssessment {$assessment.Summary.MediumCVEs = 0$assessment.Summary.LowCVEs = 0+ if ($ExactCVEMatch) {+ $assessment.Summary.TotalExactCVEs = 0+ $assessment.Summary.CriticalExactCVEs = 0+ $assessment.Summary.HighExactCVEs = 0+ $assessment.Summary.MediumExactCVEs = 0+ $assessment.Summary.LowExactCVEs = 0+ }+$nvdParams = @{}if ($NVDApiKey) {$nvdParams['ApiKey'] = $NVDApiKey@@ -359,6 +376,73 @@ function Get-VulnerabilityAssessment {if ($realCVEs.Count -gt 0) {Write-Host " Found $($realCVEs.Count) real CVE(s)" -ForegroundColor Yellow}++ if ($ExactCVEMatch) {+ try {+ $resolveParams = @{+ ProductName = $app.Name+ }+ if ($app.Publisher -and $app.Publisher -ne 'Unknown') {+ $resolveParams['Vendor'] = $app.Publisher+ }+ if ($app.Version -and $app.Version -ne 'Unknown') {+ $resolveParams['Version'] = $app.Version+ }+ if ($NVDApiKey) {+ $resolveParams['UseOnlineLookup'] = $true+ $resolveParams['ApiKey'] = $NVDApiKey+ }++ $cpeResolution = Resolve-CpeName @resolveParams+ $app | Add-Member -NotePropertyName CpeResolution -NotePropertyValue $cpeResolution -Force++ $hasUsableCpe = $false+ if ($null -ne $cpeResolution -and+ $null -ne $cpeResolution.PSObject.Properties['CpeName'] -and+ $null -ne $cpeResolution.CpeName -and+ $null -ne $cpeResolution.PSObject.Properties['Confidence'] -and+ $cpeResolution.Confidence -in @('High', 'Medium')) {+ $hasUsableCpe = $true+ }++ if ($hasUsableCpe) {+ $app | Add-Member -NotePropertyName MatchStatus -NotePropertyValue 'CpeMatched' -Force++ Start-Sleep -Seconds $nvdSleepSeconds+ Write-Host " Checking exact CVEs for CPE: $($cpeResolution.CpeName)..." -ForegroundColor Gray++ $exactCVEs = @(Get-NVDCveData -CpeName $cpeResolution.CpeName @nvdParams)++ $app | Add-Member -NotePropertyName ExactCVEs -NotePropertyValue $exactCVEs -Force++ foreach ($cve in $exactCVEs) {+ $assessment.Summary.TotalExactCVEs+++ if ($null -ne $cve.PSObject.Properties['Severity'] -and $null -ne $cve.Severity) {+ switch ($cve.Severity) {+ 'Critical' { $assessment.Summary.CriticalExactCVEs++ }+ 'High' { $assessment.Summary.HighExactCVEs++ }+ 'Medium' { $assessment.Summary.MediumExactCVEs++ }+ 'Low' { $assessment.Summary.LowExactCVEs++ }+ }+ }+ }++ if ($exactCVEs.Count -gt 0) {+ Write-Host " Found $($exactCVEs.Count) exact CVE(s)" -ForegroundColor Yellow+ }+ }+ else {+ $app | Add-Member -NotePropertyName MatchStatus -NotePropertyValue 'NoCpeMapping' -Force+ Write-Host " No reliable CPE mapping for: $($app.Name)" -ForegroundColor Gray+ }+ }+ catch {+ Write-Warning "Could not resolve CPE for $($app.Name): $_"+ if ($null -eq $app.PSObject.Properties['MatchStatus']) {+ $app | Add-Member -NotePropertyName MatchStatus -NotePropertyValue 'NoCpeMapping' -Force+ }+ }+ }}catch {Write-Warning "Could not check CVEs for $($app.Name): $_"@@ -369,7 +453,14 @@ function Get-VulnerabilityAssessment {$assessment.Recommendations += "NVD: $($assessment.Summary.TotalRealCVEs) real CVE(s) matched installed software - review RealCVEs details per application"}+ if ($ExactCVEMatch -and $assessment.Summary.TotalExactCVEs -gt 0) {+ $assessment.Recommendations += "NVD (exact/CPE): $($assessment.Summary.TotalExactCVEs) version-exact CVE(s) confirmed against installed versions - prioritize these for patching"+ }+Write-Host " Checked $checkedApps application(s) against NVD, matched $($assessment.Summary.TotalRealCVEs) real CVE(s)" -ForegroundColor Gray+ if ($ExactCVEMatch) {+ Write-Host " Matched $($assessment.Summary.TotalExactCVEs) version-exact CVE(s) via CPE" -ForegroundColor Gray+ }}else {Write-Host "`n[4/5] Skipping online CVE lookup (disabled)" -ForegroundColor Gray@@ -472,6 +563,18 @@ function Get-VulnerabilityAssessment {if ($assessment.Summary.HighCVEs -gt 0) { 'Yellow' } else { 'Gray' })}++ if ($assessment.Summary.ContainsKey('TotalExactCVEs')) {+ Write-Host " Exact CVEs (NVD/CPE): $($assessment.Summary.TotalExactCVEs)" -ForegroundColor $(+ if ($assessment.Summary.TotalExactCVEs -gt 0) { 'Yellow' } else { 'Gray' }+ )+ Write-Host " Critical Exact CVEs: $($assessment.Summary.CriticalExactCVEs)" -ForegroundColor $(+ if ($assessment.Summary.CriticalExactCVEs -gt 0) { 'Red' } else { 'Gray' }+ )+ Write-Host " High Exact CVEs: $($assessment.Summary.HighExactCVEs)" -ForegroundColor $(+ if ($assessment.Summary.HighExactCVEs -gt 0) { 'Yellow' } else { 'Gray' }+ )+ }if ($assessment.Vulnerabilities.Count -gt 0) {Write-Host "`nTop Vulnerabilities:" -ForegroundColor Cyandiff --git a/Vulnerability/Resolve-CpeName.ps1 b/Vulnerability/Resolve-CpeName.ps1new file mode 100644index 0000000..b406e61--- /dev/null+++ b/Vulnerability/Resolve-CpeName.ps1@@ -0,0 +1,371 @@+function Resolve-CpeName {+ <#+ .SYNOPSIS+ Resolves an installed product to a CPE 2.3 name for version-exact CVE matching+ .DESCRIPTION+ 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).+ 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+ Get-NVDCveData; failures warn and continue.+ 3. A heuristic guess that derives vendor/product tokens from the+ sanitized product and vendor names (always Low confidence).+ The registry version string is normalized (architecture and bitness+ noise such as 'x64' or '(64-bit)' removed, build metadata stripped;+ trailing '.0' segments are preserved so version-exact queries stay+ exact) and embedded as the version component of+ cpe:2.3:a:vendor:product:version:*:*:*:*:*:*:*+ .PARAMETER ProductName+ Product display name, e.g. the registry DisplayName value+ .PARAMETER Vendor+ Optional vendor/publisher name, e.g. the registry Publisher value+ .PARAMETER Version+ Optional product version string, e.g. the registry DisplayVersion value+ .PARAMETER UseOnlineLookup+ Query the NVD CPE API 2.0 when the curated table has no match (requires -ApiKey)+ .PARAMETER ApiKey+ Optional NVD API key. Sent only as the 'apiKey' request header, never logged.+ .EXAMPLE+ Resolve-CpeName -ProductName "Google Chrome" -Vendor "Google LLC" -Version "120.0.6099.130"+ .EXAMPLE+ Resolve-CpeName -ProductName "7-Zip 23.01 (x64)" -Version "23.01" -UseOnlineLookup -ApiKey $key+ .OUTPUTS+ PSCustomObject with CpeName, MatchedBy (CuratedTable/OnlineLookup/Heuristic/None),+ Confidence (High/Medium/Low) and Version+ #>++ [CmdletBinding()]+ param(+ [Parameter(Mandatory = $true)]+ [ValidateNotNullOrEmpty()]+ [string]$ProductName,++ [Parameter()]+ [string]$Vendor,++ [Parameter()]+ [string]$Version,++ [Parameter()]+ [switch]$UseOnlineLookup,++ [Parameter()]+ [string]$ApiKey+ )++ begin {+ Write-Host "=== CPE NAME RESOLUTION ===" -ForegroundColor Cyan+ Write-Host "Product: $ProductName" -ForegroundColor Yellow+ if ($Vendor) { Write-Host "Vendor: $Vendor" -ForegroundColor Yellow }+ if ($Version) { Write-Host "Version: $Version" -ForegroundColor Yellow }+ Write-Host "Online Lookup: $(if($UseOnlineLookup -and $ApiKey){'Enabled'}else{'Disabled (curated table / heuristic only)'})" -ForegroundColor Yellow+ Write-Host "API Key: $(if($ApiKey){'Provided'}else{'Not provided (public rate limits apply)'})" -ForegroundColor Yellow++ # Ensure TLS 1.2 on Windows PowerShell 5.1 (idempotent, only if the type exists)+ try {+ if ($null -ne ([Net.SecurityProtocolType] -as [type])) {+ [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12+ }+ }+ catch {+ Write-Verbose "Could not enforce TLS 1.2: $_"+ }++ # Curated mapping table: ordered, most specific first.+ # Patterns are matched as case-insensitive substrings of the product name.+ $curatedTable = @(+ @{ Patterns = @('Adobe Acrobat Reader DC', 'Acrobat Reader DC'); Vendor = 'adobe'; Product = 'acrobat_reader_dc'; PublisherHints = @('Adobe') }+ @{ Patterns = @('Adobe Acrobat'); Vendor = 'adobe'; Product = 'acrobat'; PublisherHints = @('Adobe') }+ @{ Patterns = @('Google Chrome'); Vendor = 'google'; Product = 'chrome'; PublisherHints = @('Google') }+ @{ 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 Office', 'Microsoft 365'); Vendor = 'microsoft'; Product = 'office'; PublisherHints = @('Microsoft') }+ @{ Patterns = @('Microsoft SQL Server'); Vendor = 'microsoft'; Product = 'sql_server'; 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 = @('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 = @('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 = @('OpenSSH'); Vendor = 'openbsd'; Product = 'openssh'; PublisherHints = @('OpenBSD') }+ @{ 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 = @('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 = @('KeePass'); Vendor = 'keepass'; Product = 'keepass'; PublisherHints = @('Dominik Reichl') }+ @{ Patterns = @('OpenSSL'); Vendor = 'openssl'; Product = 'openssl'; PublisherHints = @('OpenSSL') }+ )++ $nvdCpeApiBase = 'https://services.nvd.nist.gov/rest/json/cpes/2.0'+ $requestHeaders = @{}+ if ($ApiKey) {+ $requestHeaders['apiKey'] = $ApiKey+ }++ # NVD rate limits: 5 requests / 30s public, 50 requests / 30s with API key+ $sleepSeconds = if ($ApiKey) { 0.6 } else { 6 }++ $result = $null+ }++ process {+ try {+ function ConvertTo-NormalizedCpeVersion {+ param([string]$RawVersion)++ if ([string]::IsNullOrWhiteSpace($RawVersion)) {+ return $null+ }++ $normalized = $RawVersion.Trim()+ if ($normalized -eq 'Unknown') {+ return $null+ }++ # Strip parenthetical/bracket noise such as '(64-bit)' or '[x64]'+ $normalized = $normalized -replace '\([^)]*\)', ''+ $normalized = $normalized -replace '\[[^\]]*\]', ''++ # Strip architecture/bitness tokens+ $normalized = $normalized -replace '(?i)\b(x64|x86|amd64|arm64|64-bit|32-bit|64bit|32bit)\b', ''++ # Keep only the first whitespace/comma-separated token+ $normalized = ($normalized -split '[\s,]+' | Where-Object { $_ -ne '' } | Select-Object -First 1)++ if ([string]::IsNullOrWhiteSpace($normalized)) {+ return $null+ }++ # Strip a leading 'v' and build metadata / pre-release suffixes+ $normalized = $normalized -replace '^[vV]', ''+ $normalized = $normalized -replace '[+].*$', ''+ $normalized = $normalized -replace '[-].*$', ''++ # Require at least one digit, otherwise treat as unusable+ if ($normalized -notmatch '\d') {+ return $null+ }++ return $normalized+ }++ function ConvertTo-CpeToken {+ param([string]$RawValue)++ if ([string]::IsNullOrWhiteSpace($RawValue)) {+ return $null+ }++ $token = $RawValue.Trim().ToLower()+ $token = $token -replace '\([^)]*\)', ''+ $token = $token -replace '[™®]', ''+ $token = $token -replace '\s+', '_'+ $token = $token -replace '[^a-z0-9._+-]', ''+ $token = $token.Trim('_')++ if ([string]::IsNullOrWhiteSpace($token)) {+ return $null+ }++ return $token+ }++ function New-CpeName {+ param(+ [string]$VendorToken,+ [string]$ProductToken,+ [string]$VersionToken+ )++ if ([string]::IsNullOrWhiteSpace($VersionToken)) {+ $VersionToken = '*'+ }++ return "cpe:2.3:a:$($VendorToken):$($ProductToken):$($VersionToken):*:*:*:*:*:*:*"+ }++ $normalizedVersion = ConvertTo-NormalizedCpeVersion -RawVersion $Version++ # 1. CURATED TABLE+ $curatedMatch = $null+ foreach ($entry in $curatedTable) {+ foreach ($pattern in $entry.Patterns) {+ if ($ProductName.IndexOf($pattern, [StringComparison]::OrdinalIgnoreCase) -ge 0) {+ $curatedMatch = $entry+ break+ }+ }+ if ($null -ne $curatedMatch) {+ break+ }+ }++ if ($null -ne $curatedMatch) {+ $cpeName = New-CpeName -VendorToken $curatedMatch.Vendor -ProductToken $curatedMatch.Product -VersionToken $normalizedVersion+ $confidence = 'Medium'+ if ($null -ne $normalizedVersion) {+ $confidence = 'High'+ }++ Write-Host " Curated table match: $($curatedMatch.Vendor):$($curatedMatch.Product)" -ForegroundColor Gray++ $result = [PSCustomObject]@{+ CpeName = $cpeName+ MatchedBy = 'CuratedTable'+ Confidence = $confidence+ Version = $normalizedVersion+ }+ return+ }++ # 2. ONLINE LOOKUP (NVD CPE API 2.0)+ if ($UseOnlineLookup -and $ApiKey) {+ try {+ Write-Verbose "Rate limit pause: $sleepSeconds second(s) before CPE request"+ Start-Sleep -Seconds $sleepSeconds++ $requestUri = "$nvdCpeApiBase`?keywordSearch=$([System.Uri]::EscapeDataString($ProductName))&resultsPerPage=10"+ Write-Host " Querying NVD CPE API for: $ProductName..." -ForegroundColor Gray++ $response = $null+ try {+ $response = Invoke-RestMethod -Uri $requestUri -Method Get -Headers $requestHeaders -TimeoutSec 60 -ErrorAction Stop+ }+ catch {+ Write-Warning "NVD CPE API request failed: $($_.Exception.Message)"+ $response = $null+ }++ if ($null -ne $response -and+ $null -ne $response.PSObject.Properties['products'] -and+ $null -ne $response.products -and+ @($response.products).Count -gt 0) {++ $onlineCpeName = $null+ foreach ($productEntry in @($response.products)) {+ if ($null -eq $productEntry.PSObject.Properties['cpe'] -or $null -eq $productEntry.cpe) {+ continue+ }+ $cpeObject = $productEntry.cpe++ $isDeprecated = $false+ if ($null -ne $cpeObject.PSObject.Properties['deprecated'] -and $true -eq $cpeObject.deprecated) {+ $isDeprecated = $true+ }++ if ($null -ne $cpeObject.PSObject.Properties['cpeName'] -and+ $null -ne $cpeObject.cpeName -and+ -not $isDeprecated -and+ [string]$cpeObject.cpeName -like 'cpe:2.3:a:*') {+ $onlineCpeName = [string]$cpeObject.cpeName+ break+ }+ }++ if ($null -ne $onlineCpeName) {+ $cpeParts = $onlineCpeName.Split(':')+ if ($cpeParts.Count -ge 6) {+ $vendorToken = $cpeParts[3]+ $productToken = $cpeParts[4]++ $cpeName = New-CpeName -VendorToken $vendorToken -ProductToken $productToken -VersionToken $normalizedVersion+ $confidence = 'Medium'+ if ($null -ne $normalizedVersion) {+ $confidence = 'High'+ }++ $result = [PSCustomObject]@{+ CpeName = $cpeName+ MatchedBy = 'OnlineLookup'+ Confidence = $confidence+ Version = $normalizedVersion+ }+ return+ }+ }++ Write-Verbose "NVD CPE API returned no usable application CPE for '$ProductName'"+ }+ else {+ Write-Verbose "NVD CPE API returned no products for '$ProductName'"+ }+ }+ catch {+ Write-Warning "Online CPE lookup failed for '$ProductName': $_"+ }+ }+ elseif ($UseOnlineLookup -and -not $ApiKey) {+ Write-Warning "-UseOnlineLookup requires -ApiKey; skipping online CPE lookup for '$ProductName'"+ }++ # 3. HEURISTIC GUESS+ $vendorToken = ConvertTo-CpeToken -RawValue $Vendor+ $productToken = ConvertTo-CpeToken -RawValue $ProductName++ if ($null -ne $productToken) {+ if ($null -eq $vendorToken) {+ $firstWord = ($ProductName -split '\s+' | Where-Object { $_ -ne '' } | Select-Object -First 1)+ $vendorToken = ConvertTo-CpeToken -RawValue $firstWord+ }++ if ($null -ne $vendorToken) {+ $cpeName = New-CpeName -VendorToken $vendorToken -ProductToken $productToken -VersionToken $normalizedVersion++ Write-Host " Heuristic guess: $($vendorToken):$($productToken) (Low confidence)" -ForegroundColor Gray++ $result = [PSCustomObject]@{+ CpeName = $cpeName+ MatchedBy = 'Heuristic'+ Confidence = 'Low'+ Version = $normalizedVersion+ }+ return+ }+ }++ Write-Warning "Could not resolve a CPE name for '$ProductName'"+ $result = [PSCustomObject]@{+ CpeName = $null+ MatchedBy = 'None'+ Confidence = 'Low'+ Version = $normalizedVersion+ }+ }+ catch {+ Write-Error "Error during CPE name resolution: $_"+ throw+ }+ }++ end {+ Write-Host "=== CPE NAME RESOLUTION COMPLETE ===" -ForegroundColor $(+ if ($null -ne $result -and $null -ne $result.CpeName) { 'Green' } else { 'Gray' }+ )+ if ($null -ne $result) {+ Write-Host " CPE Name: $(if($result.CpeName){$result.CpeName}else{'(none)'})" -ForegroundColor White+ Write-Host " Matched By: $($result.MatchedBy) | Confidence: $($result.Confidence)" -ForegroundColor White+ }+ return $result+ }+}diff --git a/WindowsSecurityAudit.psd1 b/WindowsSecurityAudit.psd1index e220518..9614948 100644--- a/WindowsSecurityAudit.psd1+++ b/WindowsSecurityAudit.psd1@@ -1,6 +1,6 @@@{RootModule = 'WindowsSecurityAudit.psm1'- ModuleVersion = '1.2.0'+ ModuleVersion = '1.3.0'GUID = 'a8d7c4e5-3b2f-4e8a-9c1d-6f5a8b9d2e7c'Author = 'Security Team'CompanyName = 'Your Organization'diff --git a/WindowsSecurityAudit.psm1 b/WindowsSecurityAudit.psm1index 71320b2..1319af0 100644--- a/WindowsSecurityAudit.psm1+++ b/WindowsSecurityAudit.psm1@@ -14,7 +14,7 @@ Set-StrictMode -Version Latest# Module variables$script:ModuleRoot = $PSScriptRoot-$script:ModuleVersion = '1.2.0'+$script:ModuleVersion = '1.3.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 6992cbf..b537fbb 100644--- a/tests/WindowsSecurityAudit.Tests.ps1+++ b/tests/WindowsSecurityAudit.Tests.ps1@@ -283,3 +283,130 @@ Describe 'Threat Intelligence and CVE Integration' {}}}++Describe 'v1.3 Features' {+ Context 'Comment-based help for new parameters' {+ It 'Get-VulnerabilityAssessment help documents ExactCVEMatch' {+ $help = Get-Help -Name 'Get-VulnerabilityAssessment' -Full+ $parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })+ $parameterNames | Should -Contain 'ExactCVEMatch'+ }++ It 'Get-ThreatIntelligence help documents the MISP/TAXII/STIX parameters' {+ $help = Get-Help -Name 'Get-ThreatIntelligence' -Full+ $parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })+ foreach ($expected in 'MISPUrl', 'MISPApiKey', 'TaxiiServerUrl', 'TaxiiCollection', 'StixFilePath') {+ $parameterNames | Should -Contain $expected+ }+ }++ It 'Resolve-CpeName help documents UseOnlineLookup and ApiKey' {+ $help = Get-Help -Name 'Resolve-CpeName' -Full+ $parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })+ foreach ($expected in 'UseOnlineLookup', 'ApiKey') {+ $parameterNames | Should -Contain $expected+ }+ }++ It 'Invoke-SecurityRemediation help documents the remediation parameters' {+ $help = Get-Help -Name 'Invoke-SecurityRemediation' -Full+ $parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })+ foreach ($expected in 'MaxSeverity', 'GenerateRollback', 'AssessmentPath', 'InputObject') {+ $parameterNames | Should -Contain $expected+ }+ }+ }++ Context 'Secret handling' {+ It '<_> never interpolates an API key value into Write-Host or Write-Verbose output' -ForEach @(+ 'Vulnerability/Resolve-CpeName.ps1'+ 'ThreatHunting/Get-ThreatIntelligence.ps1'+ ) {+ $Path = Join-Path -Path $script:ModuleRoot -ChildPath $_+ $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 "$variable" interpolation shows up as a VariableExpressionAst+ # in the string's NestedExpressions. Values referenced only inside a+ # $(...) subexpression (e.g. "$(if($ApiKey){'Provided'}else{...})")+ # are SubExpressionAst nodes and never emit the key 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)(apikey|secret|token|^key$|api_key)'+ })+ }+ }+ $leaks.Count | Should -Be 0 -Because 'API keys must only travel in request headers, never in log output'+ }++ It 'Get-ThreatIntelligence types -TaxiiPassword as [SecureString]' {+ $Path = Join-Path -Path $script:ModuleRoot -ChildPath 'ThreatHunting/Get-ThreatIntelligence.ps1'+ $result = Get-ScriptFileAst -Path $Path+ $functionAst = $result.Ast.Find({+ param($node)+ $node -is [System.Management.Automation.Language.FunctionDefinitionAst] -and+ $node.Name -eq 'Get-ThreatIntelligence'+ }, $true)+ $parameterAst = @($functionAst.Body.ParamBlock.Parameters | Where-Object {+ $_.Name.VariablePath.UserPath -eq 'TaxiiPassword'+ })+ $parameterAst.Count | Should -Be 1+ $parameterAst[0].StaticType.Name | Should -Be 'SecureString' -Because 'passwords must never be accepted as plain strings'+ }+ }++ Context 'Invoke-SecurityRemediation safety' {+ BeforeAll {+ $script:RemediationPath = Join-Path -Path $script:ModuleRoot -ChildPath 'Hardening/Invoke-SecurityRemediation.ps1'+ $script:RemediationContent = Get-Content -Path $script:RemediationPath -Raw+ $script:RemediationAst = (Get-ScriptFileAst -Path $script:RemediationPath).Ast+ }++ It 'declares SupportsShouldProcess with ConfirmImpact High in its CmdletBinding' {+ $functionAst = $script:RemediationAst.Find({+ param($node)+ $node -is [System.Management.Automation.Language.FunctionDefinitionAst] -and+ $node.Name -eq 'Invoke-SecurityRemediation'+ }, $true)+ $cmdletBinding = @($functionAst.Body.ParamBlock.Attributes | Where-Object {+ $_.TypeName.Name -eq 'CmdletBinding'+ })+ $cmdletBinding.Count | Should -Be 1++ $namedArguments = $cmdletBinding[0].NamedArguments++ $shouldProcess = @($namedArguments | Where-Object { $_.ArgumentName -eq 'SupportsShouldProcess' })+ $shouldProcess.Count | Should -Be 1+ # A bare 'SupportsShouldProcess' has ExpressionOmitted = $true (defaults to $true)+ $shouldProcessEnabled = $shouldProcess[0].ExpressionOmitted -or $shouldProcess[0].Argument.SafeGetValue() -eq $true+ $shouldProcessEnabled | Should -BeTrue -Because 'remediation must support -WhatIf and -Confirm'++ $confirmImpact = @($namedArguments | Where-Object { $_.ArgumentName -eq 'ConfirmImpact' })+ $confirmImpact.Count | Should -Be 1+ $confirmImpact[0].Argument.SafeGetValue() | Should -Be 'High'+ }++ It 'routes state-changing calls through ShouldProcess' {+ $occurrences = [regex]::Matches($script:RemediationContent, [regex]::Escape('$PSCmdlet.ShouldProcess('))+ $occurrences.Count | Should -BeGreaterOrEqual 2 -Because 'both remediation actions and rollback script writes must be gated behind ShouldProcess'+ }++ It 'routes unmatched findings to ManualReview' {+ $script:RemediationContent | Should -Match 'ManualReview'+ }+ }+}