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 live threat feeds and real NVD CVE matching (v1.2.0)
Okan YILDIZ7d76542e5d54
diff --git a/README.md b/README.mdindex 236a588..a42cb35 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)@@ -20,15 +20,34 @@**🎯 Zero Dependencies • 🚀 Production Ready • 🌍 Community Driven • 💼 Enterprise Tested**-[What's New](#-whats-new-in-v110) • [Features](#-why-windows-security-audit-module) • [Installation](#-installation) • [Quick Start](#-quick-start) • [Support](#-support--contact)+[What's New](#-whats-new) • [Features](#-why-windows-security-audit-module) • [Installation](#-installation) • [Quick Start](#-quick-start) • [Support](#-support--contact)</div>----## ✨ What's New in v1.1.0+## ✨ What's New-**4 new functions** — bringing the toolkit to **62 functions across 14 modules**:+### 🆕 v1.2.0 — Live Threat Feeds & Real CVE Integration++**1 new function** — bringing the toolkit to **63 functions across 14 modules**:++| Function | Module | What It Does |+|----------|--------|--------------|+| **`Get-NVDCveData`** | Vulnerability | Query the **NVD API 2.0** by keyword or CPE name and get normalized CVE objects (ID, severity, CVSS score, dates, references) — with pagination, rate-limit handling and optional API key for higher limits |++**Wired-up parameters on existing functions:**++- `Get-VulnerabilityAssessment -CheckCVEs -NVDApiKey -MaxCVEChecks` — match installed software against **real NVD CVE data** (keyword-based candidate matching, capped by `-MaxCVEChecks`, default 10); matched CVEs attach as `RealCVEs` on each Software item plus summary counts+- `Get-ThreatIntelligence -UpdateFeeds -FeedCachePath -FeedMaxAgeHours -MaxFeedEntries -AbuseIPDBApiKey` — merge **live abuse.ch feeds** (URLhaus payload URLs, Feodo Tracker C2 IPs) plus the optional **AbuseIPDB** blacklist (with API key) into the IOC database, with freshness-aware caching, offline fallback and per-feed `Summary.FeedStats`++**Quality infrastructure:**++- 🧪 **333 Pester tests** (`tests/WindowsSecurityAudit.Tests.ps1`) covering the public API surface, API-key hygiene, and offline feed behavior++### v1.1.0 — Baseline Drift, Scheduled Scans, ATT&CK Navigator & Consolidated Reports++**4 new functions** added to the toolkit:| Function | Module | What It Does ||----------|--------|--------------|@@ -47,7 +66,7 @@**Quality infrastructure:**-- 🧪 **318 Pester tests** (`tests/WindowsSecurityAudit.Tests.ps1`) covering the public API surface+- 🧪 **Pester test suite** (`tests/WindowsSecurityAudit.Tests.ps1`) covering the public API surface (now 333 tests)- ⚙️ **GitHub Actions CI** (`.github/workflows/ci.yml`) on windows-latest: PSScriptAnalyzer Error gate, module import verified under both **PowerShell 7 (pwsh)** and **Windows PowerShell 5.1**, plus the full Pester suite### 📦 Already in the Toolbox (v1.0.0)@@ -88,7 +107,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 62 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 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.### 🎯 The Vision@@ -138,7 +157,7 @@ A single, cohesive PowerShell module that consolidates essential security functi</tr><tr><td><strong>Functions</strong></td>-<td>✅ 62 Comprehensive</td>+<td>✅ 63 Comprehensive</td><td>⚠️ 20-30 Limited</td><td>⚠️ 5-15 Basic</td></tr>@@ -259,7 +278,7 @@ WindowsSecurityAudit/│ ├── Invoke-ForensicCollection.ps1│ └── Invoke-IncidentResponse.ps1│-├── 📁 tests/ # Pester tests (318 tests)+├── 📁 tests/ # Pester tests (333 tests)│ └── WindowsSecurityAudit.Tests.ps1│├── 📁 ThreatHunting/ # Threat Hunting (7 functions)@@ -271,9 +290,10 @@ WindowsSecurityAudit/│ ├── Get-MITREAttackMapping.ps1│ └── Get-ThreatIntelligence.ps1│-├── 📁 Vulnerability/ # Vulnerability Management (6 functions)+├── 📁 Vulnerability/ # Vulnerability Management (7 functions)│ ├── Find-EOLSoftware.ps1│ ├── Get-ExposedServices.ps1+│ ├── Get-NVDCveData.ps1│ ├── Get-SecurityMisconfigurations.ps1│ ├── Get-VulnerabilityAssessment.ps1│ ├── Test-CertificateHealth.ps1@@ -320,7 +340,7 @@ Install-Module -Name WindowsSecurityAudit -Scope CurrentUser -Force# Import the moduleImport-Module WindowsSecurityAudit-# Verify installation - should return 62+# Verify installation - should return 63(Get-Command -Module WindowsSecurityAudit).Count```@@ -423,6 +443,17 @@ $report | Export-SecurityReport -Format HTML -Path "C:\SecurityReports"Start-Process "C:\SecurityReports\SecurityReport.html"```+### Real CVEs & Live Threat Feeds (New in v1.2.0)+```powershell+# Match installed software against real NVD CVE data+# (keyword-based candidate matching; add -NVDApiKey for higher rate limits)+Get-VulnerabilityAssessment -CheckCVEs -NVDApiKey $key++# Pull live abuse.ch feeds (URLhaus + Feodo Tracker) and check network+# connections against them; add -AbuseIPDBApiKey to include AbuseIPDB+Get-ThreatIntelligence -CheckNetwork -UpdateFeeds+```+### 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@@ -547,7 +578,7 @@ The Threat Hunting module provides proactive threat detection capabilities using| **`Find-LateralMovement`** | Tracks attacker movement between systems | • RDP session analysis<br>• SMB connection monitoring<br>• WMI activity tracking<br>• PSRemoting detection<br>• Service creation<br>• Scheduled task deployment | Network propagation<br>Privilege escalation<br>Domain compromise || **`Find-LivingOffLand`** | Detects abuse of legitimate tools | • PowerShell exploitation<br>• WMI weaponization<br>• LOLBins detection<br>• Script host abuse<br>• Certutil misuse<br>• Mshta execution | Fileless attacks<br>Evasion techniques<br>Stealth persistence || **`Get-MITREAttackMapping`** | Maps findings to ATT&CK framework | • Technique classification<br>• Tactic identification<br>• Kill chain mapping<br>• Detection gap analysis<br>• Priority scoring<br>• Coverage reporting | Framework alignment<br>Gap identification<br>Defense planning |-| **`Get-ThreatIntelligence`** | Analyzes threat intelligence indicators | • IOC matching<br>• Threat feed integration<br>• Reputation checking<br>• Hash validation<br>• Domain analysis<br>• IP geolocation | Known threats<br>Emerging campaigns<br>Zero-day indicators |+| **`Get-ThreatIntelligence`** | Analyzes threat intelligence indicators | • IOC matching<br>• Live threat feeds (URLhaus, Feodo Tracker, AbuseIPDB)<br>• Feed caching with freshness fallback<br>• Reputation checking<br>• Hash validation<br>• Domain analysis<br>• IP geolocation | Known threats<br>Emerging campaigns<br>Zero-day indicators || **`Export-AttackNavigatorLayer`** | Exports findings as a MITRE ATT&CK Navigator layer | • Navigator layer JSON v4.x<br>• Severity-based scoring and colors<br>• Detection count aggregation<br>• Evidence embedded in comments<br>• Pipeline input from hunting functions<br>• Output validation | ATT&CK Navigator<br>visualization |---@@ -581,13 +612,14 @@ The Active Directory module provides specialized security assessment for AD envi----### 1️⃣1️⃣ Vulnerability Module (6 Functions)+### 1️⃣1️⃣ Vulnerability Module (7 Functions)The Vulnerability module identifies, assesses, and prioritizes security weaknesses across the environment, providing actionable remediation guidance based on exploitability and business impact.| Function | Purpose | Assessment Areas | Priority Scoring ||----------|---------|------------------|------------------|-| **`Get-VulnerabilityAssessment`** | Comprehensive vulnerability scanning | • CVE identification<br>• CVSS scoring (v3.1)<br>• Exploit availability (EPSS)<br>• Patch availability<br>• Workaround options<br>• Asset criticality | Critical: CVSS 9.0+<br>High: CVSS 7.0-8.9<br>Medium: CVSS 4.0-6.9<br>Low: CVSS 0-3.9 |+| **`Get-VulnerabilityAssessment`** | Comprehensive vulnerability scanning | • CVE identification<br>• Real NVD CVE matching (`-CheckCVEs`)<br>• CVSS scoring (v3.1)<br>• 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) || **`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 |@@ -687,7 +719,7 @@ The Reporting module transforms raw security data into actionable intelligence t### Community Edition - Forever FREE- ✅ **Price**: 100% FREE - No hidden costs-- ✅ **Functions**: All 62 functions included+- ✅ **Functions**: All 63 functions included- ✅ **Source Code**: Full access on GitHub- ✅ **Updates**: Regular security updates- ✅ **License**: MIT (commercial use allowed)diff --git a/ThreatHunting/Get-ThreatIntelligence.ps1 b/ThreatHunting/Get-ThreatIntelligence.ps1index b099bf9..c4d6080 100644--- a/ThreatHunting/Get-ThreatIntelligence.ps1+++ b/ThreatHunting/Get-ThreatIntelligence.ps1@@ -15,9 +15,20 @@ function Get-ThreatIntelligence {Check registry against IOCs.PARAMETER IOCFilePath to custom IOC file (JSON format)+ .PARAMETER UpdateFeeds+ Download or refresh live threat intelligence feeds (URLhaus, Feodo Tracker, optional AbuseIPDB)+ .PARAMETER FeedCachePath+ Directory used to cache downloaded feed data (default: $env:LOCALAPPDATA\WindowsSecurityAudit\ThreatIntel)+ .PARAMETER FeedMaxAgeHours+ Maximum age in hours before a cached feed is downloaded again with -UpdateFeeds (default: 24)+ .PARAMETER MaxFeedEntries+ Maximum number of feed-derived indicators merged into the IOC database (default: 5000)+ .PARAMETER AbuseIPDBApiKey+ Optional AbuseIPDB API key; enables the AbuseIPDB blacklist feed (sent only as a request header).EXAMPLEGet-ThreatIntelligence -CheckProcesses -CheckNetworkGet-ThreatIntelligence -CheckProcesses -CheckNetwork -CheckFiles -IOCFile "C:\iocs.json"+ Get-ThreatIntelligence -CheckNetwork -UpdateFeeds -FeedMaxAgeHours 12.OUTPUTSPSCustomObject with IOC match results#>@@ -37,7 +48,22 @@ function Get-ThreatIntelligence {[switch]$CheckRegistry,[Parameter()]- [string]$IOCFile+ [string]$IOCFile,++ [Parameter()]+ [switch]$UpdateFeeds,++ [Parameter()]+ [string]$FeedCachePath = "$env:LOCALAPPDATA\WindowsSecurityAudit\ThreatIntel",++ [Parameter()]+ [int]$FeedMaxAgeHours = 24,++ [Parameter()]+ [int]$MaxFeedEntries = 5000,++ [Parameter()]+ [string]$AbuseIPDBApiKey)begin {@@ -64,6 +90,7 @@ function Get-ThreatIntelligence {CriticalMatches = 0HighMatches = 0MediumMatches = 0+ FeedStats = @()}Recommendations = @()}@@ -106,9 +133,166 @@ function Get-ThreatIntelligence {@{ Pattern = 'C:\\Users\\Public\\.*\.exe'; Severity = 'High'; Description = 'Executable in Public folder' }@{ Pattern = 'C:\\ProgramData\\.*\.ps1'; Severity = 'Medium'; Description = 'PowerShell script in ProgramData' })++ NetworkIndicators = @()}}+ # Live threat intelligence feeds+ $feedStats = @()++ if ($UpdateFeeds -or (Test-Path $FeedCachePath)) {+ Write-Host "`nProcessing live threat intelligence feeds..." -ForegroundColor Cyan++ try {+ [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12+ }+ catch {+ Write-Verbose "Could not enforce TLS 1.2: $_"+ }++ $feedDefinitions = @(+ @{ Name = 'Feodo Tracker'; Url = 'https://feodotracker.abuse.ch/downloads/ipblocklist.txt'; FileName = 'feodo_ipblocklist.txt'; Format = 'IpList'; Severity = 'Critical'; Description = 'Feodo Tracker C2' }+ @{ Name = 'URLhaus'; Url = 'https://urlhaus.abuse.ch/downloads/csv_recent.txt'; FileName = 'urlhaus_recent.csv'; Format = 'URLhausCsv'; Severity = 'High'; Description = 'URLhaus payload URL' }+ )++ if (-not [string]::IsNullOrWhiteSpace($AbuseIPDBApiKey)) {+ $feedDefinitions += @{ Name = 'AbuseIPDB'; Url = 'https://api.abuseipdb.com/api/v2/blacklist?plaintext'; FileName = 'abuseipdb_blacklist.txt'; Format = 'IpList'; Severity = 'High'; Description = 'AbuseIPDB blacklist' }+ }++ if (-not (Test-Path $FeedCachePath)) {+ try {+ $null = New-Item -ItemType Directory -Path $FeedCachePath -Force -ErrorAction Stop+ }+ catch {+ Write-Warning "Could not create feed cache directory '$FeedCachePath': $_"+ }+ }++ $feedEntryCount = 0+ $networkIndicatorKeys = @{}++ foreach ($feed in $feedDefinitions) {+ if ($feedEntryCount -ge $MaxFeedEntries) {+ Write-Warning "Feed entry cap ($MaxFeedEntries) reached - skipping remaining feeds"+ break+ }++ $cacheFile = Join-Path $FeedCachePath $feed.FileName+ $content = $null+ $source = 'none'+ $cacheAgeHours = $null+ $cacheExists = Test-Path $cacheFile++ if ($cacheExists) {+ $cacheItem = Get-Item $cacheFile+ $cacheAgeHours = [math]::Round(((Get-Date) - $cacheItem.LastWriteTime).TotalHours, 1)+ }++ $shouldDownload = $UpdateFeeds -and (-not $cacheExists -or $cacheAgeHours -ge $FeedMaxAgeHours)++ if ($shouldDownload) {+ try {+ Write-Host " Downloading $($feed.Name) feed..." -ForegroundColor Yellow+ $requestParams = @{+ Uri = $feed.Url+ OutFile = $cacheFile+ UseBasicParsing = $true+ TimeoutSec = 30+ ErrorAction = 'Stop'+ }+ if ($feed.Name -eq 'AbuseIPDB') {+ $requestParams['Headers'] = @{ 'Key' = $AbuseIPDBApiKey; 'Accept' = 'text/plain' }+ }+ Invoke-WebRequest @requestParams+ $content = Get-Content $cacheFile -ErrorAction Stop+ $source = 'download'+ $cacheItem = Get-Item $cacheFile+ $cacheAgeHours = [math]::Round(((Get-Date) - $cacheItem.LastWriteTime).TotalHours, 1)+ }+ catch {+ if ($cacheExists) {+ Write-Warning "Failed to download $($feed.Name) feed - falling back to cached copy ($cacheAgeHours hours old): $_"+ $content = Get-Content $cacheFile -ErrorAction SilentlyContinue+ $source = 'cache'+ }+ else {+ Write-Warning "Failed to download $($feed.Name) feed and no cache available - using built-in IOCs only: $_"+ }+ }+ }+ elseif ($cacheExists) {+ $content = Get-Content $cacheFile -ErrorAction SilentlyContinue+ $source = 'cache'+ if ($cacheAgeHours -ge $FeedMaxAgeHours) {+ Write-Host " $($feed.Name) cache is $cacheAgeHours hours old - run with -UpdateFeeds to refresh" -ForegroundColor Yellow+ }+ }++ $entriesAdded = 0++ if ($null -ne $content) {+ foreach ($line in $content) {+ if ($feedEntryCount -ge $MaxFeedEntries) { break }+ if ([string]::IsNullOrWhiteSpace($line) -or $line.StartsWith('#')) { continue }++ if ($feed.Format -eq 'IpList') {+ $ip = $line.Trim()+ if ($ip -notmatch '^\d{1,3}(\.\d{1,3}){3}$') { continue }+ if (-not $iocDatabase.MaliciousIPs.ContainsKey($ip)) {+ $iocDatabase.MaliciousIPs[$ip] = @{ Severity = $feed.Severity; Description = $feed.Description }+ $feedEntryCount+++ $entriesAdded+++ }+ }+ elseif ($feed.Format -eq 'URLhausCsv') {+ $fields = $line -split ','+ if ($fields.Count -lt 6) { continue }+ $url = $fields[2].Trim().Trim('"')+ $uri = $null+ try { $uri = [System.Uri]$url } catch { continue }+ if ($null -eq $uri) { continue }+ $hostName = $uri.Host+ if ([string]::IsNullOrWhiteSpace($hostName)) { continue }++ if ($hostName -match '^\d{1,3}(\.\d{1,3}){3}$') {+ if (-not $iocDatabase.MaliciousIPs.ContainsKey($hostName)) {+ $iocDatabase.MaliciousIPs[$hostName] = @{ Severity = $feed.Severity; Description = "$($feed.Description) host" }+ $feedEntryCount+++ $entriesAdded+++ }+ }+ else {+ $pattern = [regex]::Escape($hostName)+ if (-not $networkIndicatorKeys.ContainsKey($pattern)) {+ $networkIndicatorKeys[$pattern] = $true+ $iocDatabase.SuspiciousPatterns.NetworkIndicators += @{ Pattern = $pattern; Severity = $feed.Severity; Description = "$($feed.Description) host" }+ $feedEntryCount+++ $entriesAdded+++ }+ }+ }+ }+ }++ $feedStats += [PSCustomObject]@{+ Feed = $feed.Name+ EntryCount = $entriesAdded+ CacheAgeHours = $cacheAgeHours+ Source = $source+ }+ }++ if ($feedEntryCount -gt 0) {+ Write-Host " Loaded $feedEntryCount indicators from live feeds" -ForegroundColor Green+ }+ else {+ Write-Host " No live feed indicators loaded - using built-in IOCs only" -ForegroundColor Yellow+ }+ }++ $results.Summary.FeedStats = $feedStats+# Load custom IOCs if providedif ($IOCFile -and (Test-Path $IOCFile)) {Write-Host "Loading custom IOCs from: $IOCFile" -ForegroundColor Yellow@@ -270,6 +454,39 @@ function Get-ThreatIntelligence {Write-Host " [!] MATCH: Malicious IP $($conn.RemoteAddress) via $processName" -ForegroundColor Red}++ # Check against feed-derived network indicators+ foreach ($pattern in $iocDatabase.SuspiciousPatterns.NetworkIndicators) {+ if ($remoteAddress -match $pattern.Pattern) {+ $process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue+ $processName = if ($process) { $process.Name } else { "PID $($conn.OwningProcess)" }++ $match = [PSCustomObject]@{+ Type = 'Network'+ IOCType = 'FeedNetworkIndicator'+ Indicator = $pattern.Pattern+ ProcessName = $processName+ ProcessId = $conn.OwningProcess+ LocalAddress = "$($conn.LocalAddress):$($conn.LocalPort)"+ RemoteAddress = "$($conn.RemoteAddress):$($conn.RemotePort)"+ Severity = $pattern.Severity+ Description = $pattern.Description+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.Matches.NetworkIOCs += $match+ $foundCount++++ switch ($pattern.Severity) {+ 'Critical' { $results.Summary.CriticalMatches++ }+ 'High' { $results.Summary.HighMatches++ }+ 'Medium' { $results.Summary.MediumMatches++ }+ }++ Write-Host " [!] MATCH: Feed indicator '$($pattern.Pattern)' via $processName" -ForegroundColor Red+ break+ }+ }}if ($foundCount -eq 0) {@@ -499,10 +716,20 @@ function Get-ThreatIntelligence {}}+ if (@($results.Summary.FeedStats).Count -gt 0) {+ Write-Host "`nThreat Intelligence Feeds:" -ForegroundColor Cyan+ foreach ($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+ }+ }+Write-Host "`nThreat Intelligence Sources:" -ForegroundColor CyanWrite-Host " - MITRE ATT&CK: https://attack.mitre.org/" -ForegroundColor GrayWrite-Host " - AlienVault OTX: https://otx.alienvault.com/" -ForegroundColor GrayWrite-Host " - VirusTotal: https://www.virustotal.com/" -ForegroundColor Gray+ Write-Host " - abuse.ch URLhaus/Feodo Tracker: https://urlhaus.abuse.ch/ | https://feodotracker.abuse.ch/" -ForegroundColor Gray+ Write-Host " - AbuseIPDB: https://www.abuseipdb.com/" -ForegroundColor Grayreturn $results}diff --git a/Vulnerability/Get-NVDCveData.ps1 b/Vulnerability/Get-NVDCveData.ps1new file mode 100644index 0000000..5f721f2--- /dev/null+++ b/Vulnerability/Get-NVDCveData.ps1@@ -0,0 +1,271 @@+function Get-NVDCveData {+ <#+ .SYNOPSIS+ Queries the NVD API 2.0 for real CVE data+ .DESCRIPTION+ Queries the National Vulnerability Database (NVD) API 2.0 by keyword or+ CPE name and returns normalized CVE objects with severity, CVSS score,+ dates and reference URLs. Handles pagination, NVD rate limits and+ network failures gracefully (empty result on unreachable feed).+ .PARAMETER Keyword+ Free-text keyword search (keywordSearch parameter), e.g. 'Microsoft Edge'+ .PARAMETER CpeName+ CPE 2.3 name to match exactly (cpeName parameter)+ .PARAMETER ApiKey+ Optional NVD API key. Sent only as the 'apiKey' request header, never logged.+ .PARAMETER ResultsPerPage+ Results per page (default: 20, max: 2000)+ .EXAMPLE+ Get-NVDCveData -Keyword "Google Chrome" -ResultsPerPage 20+ Get-NVDCveData -CpeName "cpe:2.3:a:microsoft:edge:*:*:*:*:*:*:*:*" -ApiKey $key+ .OUTPUTS+ PSCustomObject list with CVEId, Description, Severity, CvssScore,+ PublishedDate, LastModified and References+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [string]$Keyword,++ [Parameter()]+ [string]$CpeName,++ [Parameter()]+ [string]$ApiKey,++ [Parameter()]+ [ValidateRange(1, 2000)]+ [int]$ResultsPerPage = 20+ )++ begin {+ Write-Host "=== NVD CVE LOOKUP ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow+ if ($Keyword) { Write-Host "Keyword: $Keyword" -ForegroundColor Yellow }+ if ($CpeName) { Write-Host "CPE Name: $CpeName" -ForegroundColor Yellow }+ Write-Host "API Key: $(if($ApiKey){'Provided'}else{'Not provided (public rate limits apply)'})" -ForegroundColor Yellow++ if (-not $Keyword -and -not $CpeName) {+ Write-Error "Either -Keyword or -CpeName must be specified"+ throw "Either -Keyword or -CpeName must be specified"+ }++ # 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: $_"+ }++ $nvdApiBase = 'https://services.nvd.nist.gov/rest/json/cves/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 }++ $cveList = @()+ }++ process {+ try {+ $startIndex = 0+ $totalResults = 0+ $pageCount = 0++ do {+ if ($pageCount -gt 0) {+ Write-Verbose "Rate limit pause: $sleepSeconds second(s) between paged requests"+ Start-Sleep -Seconds $sleepSeconds+ }++ $queryParams = @("resultsPerPage=$ResultsPerPage", "startIndex=$startIndex")+ if ($Keyword) {+ $queryParams += "keywordSearch=$([System.Uri]::EscapeDataString($Keyword))"+ }+ if ($CpeName) {+ $queryParams += "cpeName=$([System.Uri]::EscapeDataString($CpeName))"+ }+ $requestUri = "$nvdApiBase`?$($queryParams -join '&')"++ Write-Host " Querying NVD (page $($pageCount + 1), start index $startIndex)..." -ForegroundColor Gray++ $response = $null+ try {+ $response = Invoke-RestMethod -Uri $requestUri -Method Get -Headers $requestHeaders -TimeoutSec 60 -ErrorAction Stop+ }+ catch {+ Write-Warning "NVD API request failed: $($_.Exception.Message)"+ return+ }++ if ($null -eq $response -or+ $null -eq $response.PSObject.Properties['vulnerabilities'] -or+ $null -eq $response.vulnerabilities) {+ Write-Warning "NVD API returned no vulnerability data"+ return+ }++ if ($null -ne $response.PSObject.Properties['totalResults'] -and+ $null -ne $response.totalResults) {+ $totalResults = [int]$response.totalResults+ }++ $vulnerabilities = @($response.vulnerabilities)+ foreach ($item in $vulnerabilities) {+ try {+ if ($null -eq $item.PSObject.Properties['cve'] -or $null -eq $item.cve) {+ continue+ }+ $cve = $item.cve++ $cveId = 'Unknown'+ if ($null -ne $cve.PSObject.Properties['id'] -and $null -ne $cve.id) {+ $cveId = [string]$cve.id+ }++ $description = ''+ if ($null -ne $cve.PSObject.Properties['descriptions'] -and $null -ne $cve.descriptions) {+ $englishDescription = @($cve.descriptions) | Where-Object {+ $null -ne $_.PSObject.Properties['lang'] -and $_.lang -eq 'en'+ } | Select-Object -First 1+ if ($null -ne $englishDescription -and+ $null -ne $englishDescription.PSObject.Properties['value'] -and+ $null -ne $englishDescription.value) {+ $description = [string]$englishDescription.value+ }+ elseif (@($cve.descriptions).Count -gt 0) {+ $firstDescription = @($cve.descriptions)[0]+ if ($null -ne $firstDescription.PSObject.Properties['value'] -and+ $null -ne $firstDescription.value) {+ $description = [string]$firstDescription.value+ }+ }+ }++ $severity = 'Unknown'+ $cvssScore = $null+ if ($null -ne $cve.PSObject.Properties['metrics'] -and $null -ne $cve.metrics) {+ $metrics = $cve.metrics++ if ($null -ne $metrics.PSObject.Properties['cvssMetricV31'] -and+ $null -ne $metrics.cvssMetricV31 -and+ @($metrics.cvssMetricV31).Count -gt 0) {+ $metric = @($metrics.cvssMetricV31)[0]+ if ($null -ne $metric.PSObject.Properties['cvssData'] -and $null -ne $metric.cvssData) {+ if ($null -ne $metric.cvssData.PSObject.Properties['baseSeverity'] -and+ $null -ne $metric.cvssData.baseSeverity) {+ $severity = [string]$metric.cvssData.baseSeverity+ }+ if ($null -ne $metric.cvssData.PSObject.Properties['baseScore'] -and+ $null -ne $metric.cvssData.baseScore) {+ $cvssScore = [double]$metric.cvssData.baseScore+ }+ }+ }+ elseif ($null -ne $metrics.PSObject.Properties['cvssMetricV30'] -and+ $null -ne $metrics.cvssMetricV30 -and+ @($metrics.cvssMetricV30).Count -gt 0) {+ $metric = @($metrics.cvssMetricV30)[0]+ if ($null -ne $metric.PSObject.Properties['cvssData'] -and $null -ne $metric.cvssData) {+ if ($null -ne $metric.cvssData.PSObject.Properties['baseSeverity'] -and+ $null -ne $metric.cvssData.baseSeverity) {+ $severity = [string]$metric.cvssData.baseSeverity+ }+ if ($null -ne $metric.cvssData.PSObject.Properties['baseScore'] -and+ $null -ne $metric.cvssData.baseScore) {+ $cvssScore = [double]$metric.cvssData.baseScore+ }+ }+ }+ elseif ($null -ne $metrics.PSObject.Properties['cvssMetricV2'] -and+ $null -ne $metrics.cvssMetricV2 -and+ @($metrics.cvssMetricV2).Count -gt 0) {+ $metric = @($metrics.cvssMetricV2)[0]+ if ($null -ne $metric.PSObject.Properties['cvssData'] -and $null -ne $metric.cvssData) {+ if ($null -ne $metric.cvssData.PSObject.Properties['baseScore'] -and+ $null -ne $metric.cvssData.baseScore) {+ $cvssScore = [double]$metric.cvssData.baseScore+ }+ }+ if ($null -ne $metric.PSObject.Properties['baseSeverity'] -and+ $null -ne $metric.baseSeverity) {+ $severity = [string]$metric.baseSeverity+ }+ elseif ($null -ne $cvssScore) {+ if ($cvssScore -ge 7.0) { $severity = 'HIGH' }+ elseif ($cvssScore -ge 4.0) { $severity = 'MEDIUM' }+ else { $severity = 'LOW' }+ }+ }+ }++ $publishedDate = $null+ if ($null -ne $cve.PSObject.Properties['published'] -and $null -ne $cve.published) {+ if ($cve.published -is [DateTime]) {+ $publishedDate = $cve.published.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fff")+ }+ else {+ $publishedDate = [string]$cve.published+ }+ }++ $lastModified = $null+ if ($null -ne $cve.PSObject.Properties['lastModified'] -and $null -ne $cve.lastModified) {+ if ($cve.lastModified -is [DateTime]) {+ $lastModified = $cve.lastModified.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fff")+ }+ else {+ $lastModified = [string]$cve.lastModified+ }+ }++ $references = @()+ if ($null -ne $cve.PSObject.Properties['references'] -and $null -ne $cve.references) {+ foreach ($reference in @($cve.references)) {+ if ($null -ne $reference.PSObject.Properties['url'] -and $null -ne $reference.url) {+ $references += [string]$reference.url+ }+ }+ }++ $cveList += [PSCustomObject]@{+ CVEId = $cveId+ Description = $description+ Severity = $severity+ CvssScore = $cvssScore+ PublishedDate = $publishedDate+ LastModified = $lastModified+ References = $references+ }+ }+ catch {+ Write-Warning "Could not parse CVE entry: $_"+ }+ }++ $pageCount+++ $startIndex += @($vulnerabilities).Count+ }+ while (@($vulnerabilities).Count -gt 0 -and $startIndex -lt $totalResults)++ Write-Host " Retrieved $($cveList.Count) CVE(s) of $totalResults total result(s)" -ForegroundColor Gray+ }+ catch {+ Write-Error "Error during NVD CVE lookup: $_"+ throw+ }+ }++ end {+ Write-Host "=== NVD CVE LOOKUP COMPLETE ===" -ForegroundColor $(if ($cveList.Count -gt 0) { 'Green' } else { 'Gray' })+ Write-Host " CVEs returned: $($cveList.Count)" -ForegroundColor White+ return $cveList+ }+}diff --git a/Vulnerability/Get-VulnerabilityAssessment.ps1 b/Vulnerability/Get-VulnerabilityAssessment.ps1index daae96d..25e249d 100644--- a/Vulnerability/Get-VulnerabilityAssessment.ps1+++ b/Vulnerability/Get-VulnerabilityAssessment.ps1@@ -9,26 +9,42 @@ function Get-VulnerabilityAssessment {Scan depth: Quick (installed apps only), Standard (+ services), Deep (+ drivers).PARAMETER IncludeCVELookupQuery online CVE databases (requires internet)+ .PARAMETER CheckCVEs+ Query the NVD API 2.0 for real CVE matches per installed product (requires internet)+ .PARAMETER NVDApiKey+ Optional NVD API key for higher rate limits (sent only as a request header)+ .PARAMETER MaxCVEChecks+ Maximum number of unique products to check against the NVD API (default: 10).PARAMETER OutputPathPath to save vulnerability report.PARAMETER FormatReport format: HTML, JSON, CSV, or All.EXAMPLEGet-VulnerabilityAssessment -ScanDepth Standard- Get-VulnerabilityAssessment -IncludeCVELookup -OutputPath "C:\Reports"+ Get-VulnerabilityAssessment -CheckCVEs -MaxCVEChecks 5 -OutputPath "C:\Reports".OUTPUTSPSCustomObject with vulnerability assessment results#>-+[CmdletBinding()]param([Parameter()][ValidateSet('Quick', 'Standard', 'Deep')][string]$ScanDepth = 'Standard',-+[Parameter()][switch]$IncludeCVELookup,-++ [Parameter()]+ [switch]$CheckCVEs,++ [Parameter()]+ [string]$NVDApiKey,++ [Parameter()]+ [ValidateRange(1, 100)]+ [int]$MaxCVEChecks = 10,+[Parameter()][string]$OutputPath,@@ -41,7 +57,11 @@ 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($IncludeCVELookup){'Enabled'}else{'Disabled'})" -ForegroundColor Yellow+ Write-Host "CVE Lookup: $(if($CheckCVEs -or $IncludeCVELookup){'Enabled'}else{'Disabled'})" -ForegroundColor Yellow+ if ($CheckCVEs) {+ Write-Host "Max CVE Checks: $MaxCVEChecks" -ForegroundColor Yellow+ Write-Host "NVD API Key: $(if($NVDApiKey){'Provided'}else{'Not provided (public rate limits apply)'})" -ForegroundColor Yellow+ }$assessment = [PSCustomObject]@{ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"@@ -278,32 +298,78 @@ function Get-VulnerabilityAssessment {}# 4. CVE ONLINE LOOKUP (if enabled)- if ($IncludeCVELookup) {- Write-Host "`n[4/5] Performing online CVE lookup..." -ForegroundColor Cyan- Write-Host " Note: This may take several minutes..." -ForegroundColor Gray-- # NVD API endpoint (free, no key required for basic queries)- $nvdApiBase = "https://services.nvd.nist.gov/rest/json/cves/2.0"-+ if ($CheckCVEs -or $IncludeCVELookup) {+ Write-Host "`n[4/5] Performing online CVE lookup via NVD API..." -ForegroundColor Cyan+ Write-Host " Note: This may take several minutes (NVD rate limits)..." -ForegroundColor Gray++ $assessment.Summary.TotalRealCVEs = 0+ $assessment.Summary.CriticalCVEs = 0+ $assessment.Summary.HighCVEs = 0+ $assessment.Summary.MediumCVEs = 0+ $assessment.Summary.LowCVEs = 0++ $nvdParams = @{}+ if ($NVDApiKey) {+ $nvdParams['ApiKey'] = $NVDApiKey+ }+ $nvdSleepSeconds = if ($NVDApiKey) { 0.6 } else { 6 }++ $uniqueProducts = @($assessment.Software |+ Sort-Object Name -Unique |+ Select-Object -First $MaxCVEChecks)+$checkedApps = 0- foreach ($app in $vulnerableApps | Select-Object -First 5) {+ foreach ($app in $uniqueProducts) {try {+ $keywordParts = @()+ if ($app.Publisher -and $app.Publisher -ne 'Unknown') {+ $keywordParts += $app.Publisher+ }+ if ($app.Name) {+ $keywordParts += $app.Name+ }+ if ($keywordParts.Count -eq 0) {+ continue+ }+ $searchKeyword = ($keywordParts -join ' ') -replace '\s+', ' '++ if ($checkedApps -gt 0) {+ Start-Sleep -Seconds $nvdSleepSeconds+ }$checkedApps++- $searchQuery = $app.Name -replace '\s+', '+'-- Write-Host " Checking CVE for: $($app.Name)..." -ForegroundColor Gray-- # Note: Real implementation would need proper API key and rate limiting- # This is a placeholder for the structure-- Start-Sleep -Milliseconds 500 # Rate limiting++ Write-Host " Checking CVEs for: $searchKeyword..." -ForegroundColor Gray++ $realCVEs = @(Get-NVDCveData -Keyword $searchKeyword @nvdParams)++ $app | Add-Member -NotePropertyName RealCVEs -NotePropertyValue $realCVEs -Force++ foreach ($cve in $realCVEs) {+ $assessment.Summary.TotalRealCVEs+++ if ($null -ne $cve.PSObject.Properties['Severity'] -and $null -ne $cve.Severity) {+ switch ($cve.Severity) {+ 'Critical' { $assessment.Summary.CriticalCVEs++ }+ 'High' { $assessment.Summary.HighCVEs++ }+ 'Medium' { $assessment.Summary.MediumCVEs++ }+ 'Low' { $assessment.Summary.LowCVEs++ }+ }+ }+ }++ if ($realCVEs.Count -gt 0) {+ Write-Host " Found $($realCVEs.Count) real CVE(s)" -ForegroundColor Yellow+ }}catch {- Write-Warning "Could not check CVE for $($app.Name): $_"+ Write-Warning "Could not check CVEs for $($app.Name): $_"}}-- Write-Host " Checked $checkedApps applications against CVE database" -ForegroundColor Gray++ if ($assessment.Summary.TotalRealCVEs -gt 0) {+ $assessment.Recommendations += "NVD: $($assessment.Summary.TotalRealCVEs) real CVE(s) matched installed software - review RealCVEs details per application"+ }++ Write-Host " Checked $checkedApps application(s) against NVD, matched $($assessment.Summary.TotalRealCVEs) real CVE(s)" -ForegroundColor Gray}else {Write-Host "`n[4/5] Skipping online CVE lookup (disabled)" -ForegroundColor Gray@@ -394,6 +460,18 @@ function Get-VulnerabilityAssessment {)Write-Host " Medium Vulnerabilities: $($assessment.Summary.MediumVulnerabilities)" -ForegroundColor GrayWrite-Host " Low Vulnerabilities: $($assessment.Summary.LowVulnerabilities)" -ForegroundColor Gray++ if ($assessment.Summary.ContainsKey('TotalRealCVEs')) {+ Write-Host " Real CVEs (NVD): $($assessment.Summary.TotalRealCVEs)" -ForegroundColor $(+ if ($assessment.Summary.TotalRealCVEs -gt 0) { 'Yellow' } else { 'Gray' }+ )+ Write-Host " Critical CVEs (NVD): $($assessment.Summary.CriticalCVEs)" -ForegroundColor $(+ if ($assessment.Summary.CriticalCVEs -gt 0) { 'Red' } else { 'Gray' }+ )+ Write-Host " High CVEs (NVD): $($assessment.Summary.HighCVEs)" -ForegroundColor $(+ if ($assessment.Summary.HighCVEs -gt 0) { 'Yellow' } else { 'Gray' }+ )+ }if ($assessment.Vulnerabilities.Count -gt 0) {Write-Host "`nTop Vulnerabilities:" -ForegroundColor Cyandiff --git a/WindowsSecurityAudit.psd1 b/WindowsSecurityAudit.psd1index 0af23b4..e220518 100644--- a/WindowsSecurityAudit.psd1+++ b/WindowsSecurityAudit.psd1@@ -1,6 +1,6 @@@{RootModule = 'WindowsSecurityAudit.psm1'- ModuleVersion = '1.1.0'+ ModuleVersion = '1.2.0'GUID = 'a8d7c4e5-3b2f-4e8a-9c1d-6f5a8b9d2e7c'Author = 'Security Team'CompanyName = 'Your Organization'diff --git a/WindowsSecurityAudit.psm1 b/WindowsSecurityAudit.psm1index c477fc2..71320b2 100644--- a/WindowsSecurityAudit.psm1+++ b/WindowsSecurityAudit.psm1@@ -14,7 +14,7 @@ Set-StrictMode -Version Latest# Module variables$script:ModuleRoot = $PSScriptRoot-$script:ModuleVersion = '1.1.0'+$script:ModuleVersion = '1.2.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 460dbd0..6992cbf 100644--- a/tests/WindowsSecurityAudit.Tests.ps1+++ b/tests/WindowsSecurityAudit.Tests.ps1@@ -155,3 +155,131 @@ Describe 'Static safety checks' {$badCommands.Count | Should -Be 0}}++Describe 'Threat Intelligence and CVE Integration' {+ # Get-NVDCveData export and its .SYNOPSIS/.EXAMPLE help are already covered+ # dynamically by the data-driven Describes above (they iterate every .ps1+ # file on disk), so only the gaps are tested here.+ # -ForEach data must exist at discovery time, so relative paths are used+ # here and resolved against $script:ModuleRoot (set in BeforeAll) at runtime+ Context 'API key handling' {+ It '<_> never interpolates an API key value into Write-Host or Write-Verbose output' -ForEach @(+ 'Vulnerability/Get-NVDCveData.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 '<_> enforces TLS 1.2 before making network calls' -ForEach @(+ 'Vulnerability/Get-NVDCveData.ps1'+ 'ThreatHunting/Get-ThreatIntelligence.ps1'+ ) {+ $Path = Join-Path -Path $script:ModuleRoot -ChildPath $_+ $content = Get-Content -Path $Path -Raw+ $content | Should -Match 'Tls12'+ }++ It '<_> contains no hardcoded API keys or secrets' -ForEach @(+ 'Vulnerability/Get-NVDCveData.ps1'+ 'ThreatHunting/Get-ThreatIntelligence.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)(apikey|secret|token|password|api_key)' -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'+ }+ }++ Context 'Comment-based help for new parameters' {+ It 'Get-ThreatIntelligence help documents the live feed parameters' {+ $help = Get-Help -Name 'Get-ThreatIntelligence' -Full+ $parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })+ foreach ($expected in 'UpdateFeeds', 'FeedCachePath', 'FeedMaxAgeHours', 'MaxFeedEntries', 'AbuseIPDBApiKey') {+ $parameterNames | Should -Contain $expected+ }+ }++ It 'Get-VulnerabilityAssessment help documents the NVD CVE parameters' {+ $help = Get-Help -Name 'Get-VulnerabilityAssessment' -Full+ $parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })+ foreach ($expected in 'CheckCVEs', 'NVDApiKey', 'MaxCVEChecks') {+ $parameterNames | Should -Contain $expected+ }+ }+ }++ Context 'Offline feed behavior' {+ BeforeAll {+ $script:ThreatIntelPath = Join-Path -Path $script:ModuleRoot -ChildPath 'ThreatHunting/Get-ThreatIntelligence.ps1'+ $script:ThreatIntelAst = (Get-ScriptFileAst -Path $script:ThreatIntelPath).Ast+ $script:FeedGate = @($script:ThreatIntelAst.FindAll({+ param($node)+ $node -is [System.Management.Automation.Language.IfStatementAst]+ }, $true) | Where-Object {+ $conditionText = $_.Clauses[0].Item1.Extent.Text+ $conditionText -match '\$UpdateFeeds' -and+ $conditionText -match 'Test-Path\s+\$FeedCachePath'+ })+ }++ It 'gates live feed processing on -UpdateFeeds or an existing -FeedCachePath' {+ $script:FeedGate.Count | Should -BeGreaterOrEqual 1 -Because 'feed processing must be skipped entirely when -UpdateFeeds is absent and the cache directory does not exist'+ }++ It 'keeps feed downloads inside that gate (no network calls when offline)' {+ $script:FeedGate.Count | Should -BeGreaterOrEqual 1+ $downloads = @($script:ThreatIntelAst.FindAll({+ param($node)+ $node -is [System.Management.Automation.Language.CommandAst]+ }, $true) | Where-Object {+ $_.GetCommandName() -eq 'Invoke-WebRequest'+ })+ $downloads.Count | Should -BeGreaterOrEqual 1 -Because 'the live feed feature is expected to download feed files'+ foreach ($download in $downloads) {+ $insideGate = @($script:FeedGate | Where-Object {+ $download.Extent.StartOffset -gt $_.Extent.StartOffset -and+ $download.Extent.EndOffset -lt $_.Extent.EndOffset+ })+ $insideGate.Count | Should -BeGreaterOrEqual 1 -Because 'Invoke-WebRequest must only run when -UpdateFeeds is set or a feed cache exists'+ }+ }+ }+}