Skip to content

A comprehensive Windows security auditing and threat detection toolkit. Features 58 production-ready PowerShell functions organized into 14 modules for enterprise-grade security assessment, compliance validation, and incident response.

PowerShell

Add SIEM export, credential/evasion detection, forensic integrity (v1.4.0)

Okan YILDIZ7b1830d4a323
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
index dd84ea7..1d88dc4 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.md
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -1,8 +1,8 @@
---
name: Bug report
-about: Create a report to help us improve
+about: Report a problem with the WindowsSecurityAudit module
title: ''
-labels: ''
+labels: bug
assignees: ''
---
@@ -10,29 +10,31 @@ assignees: ''
**Describe the bug**
A clear and concise description of what the bug is.
-**To Reproduce**
-Steps to reproduce the behavior:
-1. Go to '...'
-2. Click on '....'
-3. Scroll down to '....'
-4. See error
+**Environment**
+- Module version: [output of `Get-Module WindowsSecurityAudit` after importing, e.g. `1.3.0`]
+- PowerShell version: [output of `$PSVersionTable.PSVersion`, e.g. `5.1.22621.2506` or `7.4.2`]
+- Windows build: [output of `[System.Environment]::OSVersion.Version` or `winver`, e.g. `10.0.22631`]
+- Execution context: [e.g. elevated prompt, scheduled task, remote session]
+
+**Command run**
+The exact command you ran, including all parameters:
+
+```powershell
+# e.g. Invoke-SecurityAssessment -IncludeCompliance -ExportPath C:\Reports
+```
**Expected behavior**
-A clear and concise description of what you expected to happen.
+What you expected the command to do.
-**Screenshots**
-If applicable, add screenshots to help explain your problem.
+**Actual behavior**
+What actually happened, including the full error text if any:
-**Desktop (please complete the following information):**
- - OS: [e.g. iOS]
- - Browser [e.g. chrome, safari]
- - Version [e.g. 22]
+```text
+# paste error record or $Error[0] | Format-List * -Force output here
+```
-**Smartphone (please complete the following information):**
- - Device: [e.g. iPhone6]
- - OS: [e.g. iOS8.1]
- - Browser [e.g. stock browser, safari]
- - Version [e.g. 22]
+**Sanitized output**
+If relevant, attach or paste the function's output (objects, exported report snippets). Remove hostnames, usernames, tenant IDs, IP addresses, API keys, and any other sensitive data before posting.
**Additional context**
Add any other context about the problem here.
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
new file mode 100644
index 0000000..d50de95
--- /dev/null
+++ b/.github/workflows/publish.yml
@@ -0,0 +1,50 @@
+name: Publish to PowerShell Gallery
+
+on:
+ workflow_dispatch:
+ release:
+ types: [published]
+
+jobs:
+ publish:
+ name: Test and publish
+ # The module only works on Windows (CIM/WMI, event logs, registry), so the
+ # test gate and the publish step both run on windows-latest.
+ runs-on: windows-latest
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Install Pester
+ shell: pwsh
+ run: |
+ Set-PSRepository -Name PSGallery -InstallationPolicy Trusted
+ Install-Module -Name Pester -MinimumVersion 5.5.0 -Force -Scope CurrentUser -SkipPublisherCheck
+
+ - name: Run Pester tests (publish gate)
+ # The full suite must pass before anything is published; a failing test
+ # exits with code 1 and stops the workflow before Publish-Module runs.
+ shell: pwsh
+ run: |
+ $config = New-PesterConfiguration
+ $config.Run.Path = './tests'
+ $config.Run.Exit = $true
+ $config.Output.Verbosity = 'Detailed'
+ Invoke-Pester -Configuration $config
+
+ - name: Validate module manifest
+ shell: pwsh
+ run: |
+ $manifest = Test-ModuleManifest -Path ./WindowsSecurityAudit.psd1 -ErrorAction Stop
+ Write-Host "Manifest OK: $($manifest.Name) $($manifest.Version)"
+
+ - name: Publish to PowerShell Gallery
+ # IMPORTANT: this step requires a repository secret named PSGALLERY_API_KEY
+ # containing a PowerShell Gallery API key scoped to this module. Create it
+ # under Settings > Secrets and variables > Actions in the repository.
+ # Without the secret this step fails; the key is never logged.
+ shell: pwsh
+ run: |
+ Publish-Module -Path . -NuGetApiKey ${{ secrets.PSGALLERY_API_KEY }} -ErrorAction Stop
+ Write-Host "Published WindowsSecurityAudit to the PowerShell Gallery."
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..a877376
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,74 @@
+# Changelog
+
+All notable changes to this project are documented in this file.
+
+The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+
+## [Unreleased]
+
+### Added
+
+- `CHANGELOG.md`, `SECURITY.md`, and a PowerShell Gallery publish workflow (`.github/workflows/publish.yml`).
+- Real module manifest metadata (author, license/project URIs, gallery tags) in `WindowsSecurityAudit.psd1`.
+
+### Changed
+
+- `Get-CloudComplianceStatus` no longer reports fabricated `Compliant`/`Non-Compliant` results. Controls are returned with `Status = 'NotEvaluated'` until framework-specific Microsoft Graph/API evaluation is implemented, and the compliance score is `$null` when no controls were actually evaluated.
+
+## [1.3.0] - 2026-10-25
+
+### Added
+
+- `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).
+- `Invoke-SecurityRemediation` (Hardening): apply a curated map of 7 safe remediations (firewall profiles, UAC, Defender real-time protection, SMBv1, Guest account, PowerShell script block logging, RDP NLA) from assessment findings, WhatIf-first with `SupportsShouldProcess`, optional `-GenerateRollback` script; unmatched findings go to `ManualReview`.
+- `Get-VulnerabilityAssessment -ExactCVEMatch`: version-exact NVD CVE matching via CPE names, with per-application `ExactCVEs` and summary counts.
+- `Get-ThreatIntelligence` MISP (`-MISPUrl -MISPApiKey`), TAXII 2.x (`-TaxiiServerUrl -TaxiiCollection`, `SecureString` password), and offline STIX 2.x bundle (`-StixFilePath`) indicator sources.
+- Pester suite grew to 353 tests, covering v1.3 parameter help, secret-handling AST checks, and remediation safety.
+
+## [1.2.0] - 2026-10-25
+
+### Added
+
+- `Get-NVDCveData` (Vulnerability): query the NVD API 2.0 by keyword or CPE name with pagination, rate-limit handling, and an optional API key.
+- `Get-VulnerabilityAssessment -CheckCVEs -NVDApiKey -MaxCVEChecks`: match installed software against real NVD CVE data (keyword-based candidate matching); matched CVEs attach as `RealCVEs` per application.
+- `Get-ThreatIntelligence -UpdateFeeds`: merge live abuse.ch feeds (URLhaus payload URLs, Feodo Tracker C2 IPs) plus an optional AbuseIPDB blacklist into the IOC database, with freshness-aware caching, offline fallback, and per-feed statistics.
+- Pester suite grew to 333 tests.
+
+## [1.1.0] - 2026-10-25
+
+### Added
+
+- `Compare-SecurityBaseline` (Core): detect configuration drift between two security baselines with Improved/Degraded/New/Removed classification and JSON/CSV export.
+- `Register-ScheduledSecurityScan` (Enterprise): recurring daily/weekly/monthly scans via Scheduled Tasks with Teams/Slack webhook and email alerting on Critical findings.
+- `Export-AttackNavigatorLayer` (Threat Hunting): export hunt findings as a MITRE ATT&CK Navigator layer (JSON v4.x) with severity-based scoring and colors.
+- `New-ConsolidatedReport` (Reporting): single interactive Chart.js HTML report combining results from all modules, with offline mode from saved JSON.
+- `Invoke-SecurityAssessment -IncludeCompliance`, `Get-ExposedServices -CustomPorts`, `Get-ComplianceReport -IncludeEvidence`, `New-ExecutiveReport -CustomLogo`, `Export-SecurityReport -IncludeCharts`.
+- Pester test suite (`tests/WindowsSecurityAudit.Tests.ps1`) covering the public API surface.
+- GitHub Actions CI (`.github/workflows/ci.yml`) on windows-latest: PSScriptAnalyzer Error gate and module import verified under both PowerShell 7 and Windows PowerShell 5.1.
+
+### Fixed
+
+- Approximately 100 strict-mode and runtime bugs across the module.
+
+## [1.0.0] - 2025-10-10
+
+### Added
+
+- Initial release: 58 functions across 14 category modules, dot-sourced by `WindowsSecurityAudit.psm1`, targeting Windows PowerShell 5.1+.
+- Core Security: `Get-SecurityBaseline` (0-100 posture score), `Get-SystemInfo`, `Test-SystemIntegrity` (SFC/DISM), `Get-EventIdDescription`.
+- Threat Detection: persistence mechanisms, suspicious processes, network anomalies, authentication attack detection (brute force, lockouts, after-hours).
+- Threat Hunting: APT indicators, data exfiltration, lateral movement, LOLBins abuse, MITRE ATT&CK mapping, IOC matching (incl. custom IOC files).
+- Compliance: CIS Benchmark, NIST 800-53, and PCI-DSS 4.0 validation with audit-ready evidence export.
+- Vulnerability Management: CVE assessment, EOL software, exposed services, certificate health, patch compliance.
+- Active Directory: backdoor and DCSync detection, privileged account audit, stale objects, password policies, security posture.
+- Forensics & Response: memory dumps, USB history, execution artifacts, forensic timelines, one-command incident response.
+- Enterprise & Reporting: multi-system parallel scanning, executive reports, live HTML dashboards, security metrics and KPIs.
+- Cloud Security: Azure AD risky sign-ins, M365 security posture, cloud compliance status.
+- Hardening: audit policies, PowerShell security (logging, transcription), security baseline enforcement — all with `-WhatIf` support.
+
+[Unreleased]: https://github.com/okanyildiz/WindowsSecurityAudit/compare/v1.3.0...HEAD
+[1.3.0]: https://github.com/okanyildiz/WindowsSecurityAudit/releases/tag/v1.3.0
+[1.2.0]: https://github.com/okanyildiz/WindowsSecurityAudit/releases/tag/v1.2.0
+[1.1.0]: https://github.com/okanyildiz/WindowsSecurityAudit/releases/tag/v1.1.0
+[1.0.0]: https://github.com/okanyildiz/WindowsSecurityAudit/releases/tag/v1.0.0
diff --git a/CloudSecurity/Get-CloudComplianceStatus.ps1 b/CloudSecurity/Get-CloudComplianceStatus.ps1
index 3f07a56..8361fa5 100644
--- a/CloudSecurity/Get-CloudComplianceStatus.ps1
+++ b/CloudSecurity/Get-CloudComplianceStatus.ps1
@@ -2,27 +2,36 @@ function Get-CloudComplianceStatus {
<#
.SYNOPSIS
Retrieves cloud compliance status against regulatory frameworks
-
+
.DESCRIPTION
- Evaluates cloud environment compliance against various frameworks:
- CIS, ISO27001, NIST, GDPR, HIPAA, SOC2, AzureSecurityBenchmark
-
+ Reports cloud environment compliance against various frameworks:
+ CIS, ISO27001, NIST, GDPR, HIPAA, SOC2, AzureSecurityBenchmark.
+
+ Automated evaluation of these controls requires framework-specific
+ Microsoft Graph/API queries that are not yet implemented. Controls in
+ the built-in catalog are therefore returned with Status 'NotEvaluated'
+ and the ComplianceScore is $null when no control was actually evaluated.
+
.PARAMETER Framework
Compliance framework (Default: CIS)
-
+
.PARAMETER IncludeRemediation
Include remediation steps
-
+
.PARAMETER ExportPath
Path to save compliance report
-
+
.PARAMETER Format
Report format: HTML, JSON, CSV, or All (Default: HTML)
-
+
.EXAMPLE
Get-CloudComplianceStatus -Framework CIS
+
+ .OUTPUTS
+ PSCustomObject with Framework, Controls, Summary, and ComplianceScore
+ ($null when no controls were evaluated).
#>
-
+
[CmdletBinding()]
param(
[ValidateSet('CIS', 'ISO27001', 'NIST', 'GDPR', 'HIPAA', 'SOC2', 'AzureSecurityBenchmark')]
@@ -32,44 +41,46 @@ function Get-CloudComplianceStatus {
[ValidateSet('HTML', 'JSON', 'CSV', 'All')]
[string]$Format = 'HTML'
)
-
+
begin {
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " CLOUD COMPLIANCE ASSESSMENT" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "Framework: $Framework" -ForegroundColor Yellow
-
+
# Initialize results
$results = [PSCustomObject]@{
AssessmentDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Framework = $Framework
FrameworkVersion = "Latest"
Controls = @()
- ComplianceScore = 0
+ ComplianceScore = $null
Summary = @{
TotalControls = 0
+ Evaluated = 0
+ NotEvaluated = 0
Compliant = 0
NonCompliant = 0
PartiallyCompliant = 0
}
}
}
-
+
process {
try {
- Write-Host "`nLoading $Framework controls..." -ForegroundColor Cyan
-
- $controls = @()
-
- # Load framework-specific controls
+ Write-Host "`nLoading $Framework control catalog..." -ForegroundColor Cyan
+
+ $catalog = @()
+
+ # Catalog of framework control references. These entries identify the
+ # controls only; their compliance status is NOT evaluated (see below).
switch ($Framework) {
'CIS' {
- $controls = @(
+ $catalog = @(
@{
ControlId = "1.1.1"
Title = "Ensure multifactor authentication is enabled"
Category = "Identity"
- Status = "Non-Compliant"
Severity = "Critical"
Remediation = "Enable MFA via Conditional Access"
},
@@ -77,101 +88,97 @@ function Get-CloudComplianceStatus {
ControlId = "1.1.2"
Title = "Ensure global admins are limited"
Category = "Identity"
- Status = "Compliant"
Severity = "High"
Remediation = "N/A"
}
)
}
-
+
'GDPR' {
- $controls = @(
+ $catalog = @(
@{
ControlId = "Art. 32"
Title = "Security of processing"
Category = "Technical Measures"
- Status = "Compliant"
Severity = "Critical"
Remediation = "N/A"
}
)
}
-
+
'NIST' {
- $controls = @(
+ $catalog = @(
@{
ControlId = "ID.AM-1"
Title = "Physical devices inventoried"
Category = "Identify"
- Status = "Compliant"
Severity = "Medium"
Remediation = "N/A"
}
)
}
-
+
default {
- $controls = @(
- @{
- ControlId = "GEN-001"
- Title = "General security control"
- Category = "General"
- Status = "Compliant"
- Severity = "Medium"
- Remediation = "N/A"
- }
- )
+ $catalog = @()
}
}
-
+
+ if (@($catalog).Count -eq 0) {
+ Write-Warning "No control catalog is defined for framework '$Framework'."
+ }
+
+ Write-Warning "Automated evaluation of $Framework controls is not implemented: it requires framework-specific Microsoft Graph/API queries. All listed controls are returned with Status 'NotEvaluated' and are excluded from the compliance score."
+
# Process controls
- foreach ($control in $controls) {
+ $notEvaluatedNote = "Not evaluated: automated cloud compliance evaluation of this control requires framework-specific Microsoft Graph/API queries that are not yet implemented."
+
+ foreach ($control in $catalog) {
$results.Controls += [PSCustomObject]@{
ControlId = $control.ControlId
Title = $control.Title
Category = $control.Category
- Status = $control.Status
+ Status = "NotEvaluated"
Severity = $control.Severity
+ Note = $notEvaluatedNote
Remediation = if ($IncludeRemediation) { $control.Remediation } else { $null }
}
-
+
$results.Summary.TotalControls++
-
- switch ($control.Status) {
- 'Compliant' { $results.Summary.Compliant++ }
- 'Non-Compliant' { $results.Summary.NonCompliant++ }
- 'Partially Compliant' { $results.Summary.PartiallyCompliant++ }
- }
+ $results.Summary.NotEvaluated++
}
-
- # Calculate score
- if ($results.Summary.TotalControls -gt 0) {
+
+ # Calculate score from evaluated controls only; with none evaluated the
+ # score stays $null instead of implying a pass rate that was never measured.
+ $evaluatedCount = $results.Summary.Compliant + $results.Summary.NonCompliant + $results.Summary.PartiallyCompliant
+ $results.Summary.Evaluated = $evaluatedCount
+
+ if ($evaluatedCount -gt 0) {
$compliantCount = $results.Summary.Compliant + ($results.Summary.PartiallyCompliant * 0.5)
- $results.ComplianceScore = [Math]::Round(($compliantCount / $results.Summary.TotalControls) * 100, 1)
+ $results.ComplianceScore = [Math]::Round(($compliantCount / $evaluatedCount) * 100, 1)
}
-
+
# Export if requested
if ($ExportPath) {
Write-Host "`nExporting reports..." -ForegroundColor Cyan
-
+
if (-not (Test-Path $ExportPath)) {
New-Item -Path $ExportPath -ItemType Directory -Force | Out-Null
}
-
+
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
-
+
if ($Format -in @('JSON', 'All')) {
$jsonPath = Join-Path $ExportPath "Compliance_${Framework}_$timestamp.json"
$results | ConvertTo-Json -Depth 10 | Out-File $jsonPath -Encoding UTF8
Write-Host "Exported JSON: $jsonPath" -ForegroundColor Green
}
-
+
if ($Format -in @('CSV', 'All')) {
$csvPath = Join-Path $ExportPath "Compliance_${Framework}_$timestamp.csv"
$results.Controls | Export-Csv $csvPath -NoTypeInformation
Write-Host "Exported CSV: $csvPath" -ForegroundColor Green
}
-
+
if ($Format -in @('HTML', 'All')) {
$htmlPath = Join-Path $ExportPath "Compliance_${Framework}_$timestamp.html"
$htmlContent = Generate-ComplianceHTML -Results $results
@@ -185,33 +192,49 @@ function Get-CloudComplianceStatus {
throw
}
}
-
+
end {
Write-Host "`n========================================" -ForegroundColor Green
Write-Host " COMPLIANCE ASSESSMENT COMPLETE" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
-
- $scoreColor = if ($results.ComplianceScore -ge 80) { 'Green' }
- elseif ($results.ComplianceScore -ge 60) { 'Yellow' }
- else { 'Red' }
-
- Write-Host "`nCompliance Score: $($results.ComplianceScore)%" -ForegroundColor $scoreColor
+
+ if ($null -ne $results.ComplianceScore) {
+ $scoreColor = if ($results.ComplianceScore -ge 80) { 'Green' }
+ elseif ($results.ComplianceScore -ge 60) { 'Yellow' }
+ else { 'Red' }
+ Write-Host "`nCompliance Score: $($results.ComplianceScore)%" -ForegroundColor $scoreColor
+ }
+ else {
+ Write-Host "`nCompliance Score: N/A (no controls were evaluated)" -ForegroundColor Yellow
+ }
+
Write-Host "Framework: $($results.Framework)" -ForegroundColor Cyan
Write-Host "Total Controls: $($results.Summary.TotalControls)" -ForegroundColor White
+ Write-Host "Evaluated: $($results.Summary.Evaluated)" -ForegroundColor White
+ Write-Host "Not Evaluated: $($results.Summary.NotEvaluated)" -ForegroundColor Yellow
Write-Host "Compliant: $($results.Summary.Compliant)" -ForegroundColor Green
Write-Host "Non-Compliant: $($results.Summary.NonCompliant)" -ForegroundColor Red
-
+
return $results
}
}
function Generate-ComplianceHTML {
param($Results)
-
- $scoreColor = if ($Results.ComplianceScore -ge 80) { '#107c10' }
- elseif ($Results.ComplianceScore -ge 60) { '#f7630c' }
- else { '#d13438' }
-
+
+ $hasScore = ($null -ne $Results) -and ($null -ne $Results.ComplianceScore)
+
+ if ($hasScore) {
+ $scoreColor = if ($Results.ComplianceScore -ge 80) { '#107c10' }
+ elseif ($Results.ComplianceScore -ge 60) { '#f7630c' }
+ else { '#d13438' }
+ $scoreDisplay = "$($Results.ComplianceScore)%"
+ }
+ else {
+ $scoreColor = '#605e5c'
+ $scoreDisplay = "N/A"
+ }
+
$html = @'
<!DOCTYPE html>
<html>
@@ -230,6 +253,7 @@ function Generate-ComplianceHTML {
.compliant { color: #107c10; font-weight: bold; }
.non-compliant { color: #d13438; font-weight: bold; }
.partial { color: #f7630c; font-weight: bold; }
+ .not-evaluated { color: #605e5c; font-weight: bold; }
.score-box { text-align: center; padding: 30px; margin: 20px 0; border-radius: 10px; color: white; }
.score-value { font-size: 48px; font-weight: bold; }
</style>
@@ -238,23 +262,25 @@ function Generate-ComplianceHTML {
<div class="container">
<h1>Cloud Compliance Status Report</h1>
'@
-
+
$html += @"
<div class="score-box" style="background: $scoreColor;">
- <div class="score-value">$($Results.ComplianceScore)%</div>
+ <div class="score-value">$scoreDisplay</div>
<div>Compliance Score</div>
</div>
-
+
<h2>Framework Information</h2>
<p><strong>Framework:</strong> $($Results.Framework)</p>
<p><strong>Version:</strong> $($Results.FrameworkVersion)</p>
<p><strong>Assessment Date:</strong> $($Results.AssessmentDate)</p>
-
+
<h2>Control Summary</h2>
<p><strong>Total Controls:</strong> $($Results.Summary.TotalControls)</p>
+ <p><strong>Evaluated:</strong> $($Results.Summary.Evaluated)</p>
+ <p><strong>Not Evaluated:</strong> $($Results.Summary.NotEvaluated)</p>
<p><strong>Compliant:</strong> $($Results.Summary.Compliant)</p>
<p><strong>Non-Compliant:</strong> $($Results.Summary.NonCompliant)</p>
-
+
<h2>Compliance Controls</h2>
<table>
<thead>
@@ -268,14 +294,15 @@ function Generate-ComplianceHTML {
</thead>
<tbody>
"@
-
+
foreach ($control in $Results.Controls) {
$statusClass = switch ($control.Status) {
'Compliant' { 'compliant' }
'Non-Compliant' { 'non-compliant' }
'Partially Compliant' { 'partial' }
+ default { 'not-evaluated' }
}
-
+
$html += @"
<tr>
<td>$($control.ControlId)</td>
@@ -286,11 +313,11 @@ function Generate-ComplianceHTML {
</tr>
"@
}
-
+
$html += @'
</tbody>
</table>
-
+
<div style="margin-top: 40px; padding-top: 20px; border-top: 2px solid #ddd; text-align: center; color: #605e5c; font-size: 12px;">
<p>Generated by WindowsSecurityAudit Module</p>
</div>
@@ -298,6 +325,6 @@ function Generate-ComplianceHTML {
</body>
</html>
'@
-
+
return $html
-}
\ No newline at end of file
+}
diff --git a/Detection/Find-DefenseEvasion.ps1 b/Detection/Find-DefenseEvasion.ps1
new file mode 100644
index 0000000..86a08e3
--- /dev/null
+++ b/Detection/Find-DefenseEvasion.ps1
@@ -0,0 +1,639 @@
+function Find-DefenseEvasion {
+ <#
+ .SYNOPSIS
+ Detects defense-evasion and security-tampering activity
+ .DESCRIPTION
+ Scans for indicators that attackers attempted to blind or weaken host defenses:
+ AMSI bypass patterns in PowerShell script-block logging (4104), ETW tampering,
+ Windows Defender tampering (exclusions, disabled real-time monitoring, 5001/5007
+ events), event log tampering (1102/104/4719), and optional heuristic log-gap
+ analysis across major logs
+ .PARAMETER Hours
+ Number of hours to look back in event logs (default: 24)
+ .PARAMETER IncludeLogGapAnalysis
+ Perform heuristic analysis of time gaps between consecutive events in major logs
+ .EXAMPLE
+ Find-DefenseEvasion
+ Find-DefenseEvasion -Hours 48 -IncludeLogGapAnalysis
+ .OUTPUTS
+ PSCustomObject with EvasionFindings, Summary, Recommendations, and per-check status
+ #>
+
+ [CmdletBinding()]
+ param(
+ [Parameter()]
+ [int]$Hours = 24,
+
+ [Parameter()]
+ [switch]$IncludeLogGapAnalysis
+ )
+
+ begin {
+ Write-Host "Scanning for defense-evasion and tampering activity (last $Hours hours)..." -ForegroundColor Cyan
+
+ $results = [PSCustomObject]@{
+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
+ ComputerName = $env:COMPUTERNAME
+ TimeRange = "$Hours hours"
+ EvasionFindings = @()
+ Summary = [PSCustomObject]@{
+ TotalFindings = 0
+ Critical = 0
+ High = 0
+ Medium = 0
+ Low = 0
+ Info = 0
+ ChecksRun = 0
+ }
+ CheckStatus = [PSCustomObject]@{
+ ScriptBlockLogQuery = 'Unknown'
+ AmsiProviderCheck = 'Unknown'
+ AmsiPatternScan = 'Unknown'
+ EtwPatternScan = 'Unknown'
+ PowerShellLoggingGpo= 'Unknown'
+ DefenderPreferences = 'Unknown'
+ DefenderStatus = 'Unknown'
+ DefenderEvents = 'Unknown'
+ SecurityLogCleared = 'Unknown'
+ SystemLogCleared = 'Unknown'
+ AuditPolicyChanged = 'Unknown'
+ LogGapAnalysis = 'NotRequested'
+ }
+ Recommendations = @()
+ }
+
+ $startTime = (Get-Date).AddHours(-$Hours)
+
+ function Get-EventDataValue {
+ param(
+ [Parameter()]
+ $WinEvent,
+
+ [Parameter()]
+ [string]$Name
+ )
+ try {
+ if ($null -eq $WinEvent) { return $null }
+ $xml = [xml]$WinEvent.ToXml()
+ if ($null -eq $xml -or $null -eq $xml.Event -or $null -eq $xml.Event.EventData) { return $null }
+ $data = $xml.Event.EventData.Data
+ if ($null -eq $data) { return $null }
+ $item = @($data | Where-Object { $null -ne $_.Name -and $_.Name -eq $Name } | Select-Object -First 1)
+ if ($item.Count -eq 0) { return $null }
+ $node = $item[0]
+ if ($node.PSObject.Properties['#text']) { return $node.'#text' }
+ return [string]$node
+ }
+ catch {
+ return $null
+ }
+ }
+
+ function Get-EventMessage {
+ param(
+ [Parameter()]
+ $WinEvent
+ )
+ if ($null -eq $WinEvent) { return $null }
+ if ($WinEvent.PSObject.Properties['Message'] -and $WinEvent.Message) { return [string]$WinEvent.Message }
+ return $null
+ }
+
+ function Get-EventTimestamp {
+ param(
+ [Parameter()]
+ $WinEvent
+ )
+ if ($null -eq $WinEvent) { return $null }
+ if ($WinEvent.PSObject.Properties['TimeCreated']) { return $WinEvent.TimeCreated }
+ return $null
+ }
+
+ function Get-MessageSnippet {
+ param(
+ [Parameter()]
+ [string]$Message,
+
+ [Parameter()]
+ [int]$MaxLength = 200
+ )
+ if ([string]::IsNullOrEmpty($Message)) { return '' }
+ if ($Message.Length -gt $MaxLength) {
+ return ($Message.Substring(0, $MaxLength) + '...')
+ }
+ return $Message
+ }
+
+ # AMSI bypass indicator patterns (T1562.001 - Impair Defenses: Disable or Modify Tools)
+ $amsiPatterns = @(
+ [PSCustomObject]@{ Name = 'AmsiScanBuffer patch/reference'; Pattern = 'AmsiScanBuffer'; Combo = $null; Severity = 'High' }
+ [PSCustomObject]@{ Name = 'amsiInitFailed forced'; Pattern = 'amsiInitFailed'; Combo = $null; Severity = 'High' }
+ [PSCustomObject]@{ Name = 'amsi.dll memory patch'; Pattern = 'amsi\.dll'; Combo = '(?i)(patch|VirtualProtect|WriteProcessMemory|Marshal)'; Severity = 'High' }
+ [PSCustomObject]@{ Name = 'Reflection-based amsiUtils tamper'; Pattern = '\[Ref\]\.Assembly\.GetType'; Combo = '(?i)amsiUtils'; Severity = 'High' }
+ [PSCustomObject]@{ Name = 'Marshal::Copy near AMSI'; Pattern = 'Marshal::Copy'; Combo = '(?i)amsi'; Severity = 'Medium' }
+ )
+
+ # ETW tamper indicator patterns (T1562.006 - Impair Defenses: Indicator Blocking)
+ $etwPatterns = @(
+ [PSCustomObject]@{ Name = 'EtwEventWrite patch'; Pattern = 'EtwEventWrite'; Combo = '(?i)(patch|VirtualProtect|Marshal|GetProcAddress)'; Severity = 'High' }
+ [PSCustomObject]@{ Name = 'Generic ETW patch reference'; Pattern = '(?i)etw'; Combo = '(?i)patch'; Severity = 'Medium' }
+ )
+
+ $scriptBlockEvents = $null
+ }
+
+ process {
+ try {
+ # Shared query: PowerShell script-block logging events (4104)
+ try {
+ $scriptBlockEvents = @(Get-WinEvent -FilterHashtable @{
+ LogName = 'Microsoft-Windows-PowerShell/Operational'
+ ID = 4104
+ StartTime = $startTime
+ } -ErrorAction SilentlyContinue)
+ $results.CheckStatus.ScriptBlockLogQuery = 'OK'
+ $results.Summary.ChecksRun++
+ }
+ catch {
+ Write-Warning "Could not query PowerShell Operational log (4104): $_"
+ $results.CheckStatus.ScriptBlockLogQuery = 'Unknown'
+ }
+
+ # 1a. AMSI provider registration (informational baseline)
+ Write-Verbose "Checking AMSI provider registration..."
+ try {
+ $results.Summary.ChecksRun++
+ $amsiProviderPath = 'HKLM:\SOFTWARE\Microsoft\AMSI\Providers'
+ $providerKeyExists = $false
+ try { $providerKeyExists = Test-Path $amsiProviderPath -ErrorAction SilentlyContinue } catch { $providerKeyExists = $false }
+
+ if ($providerKeyExists) {
+ $providers = @(Get-ChildItem -Path $amsiProviderPath -ErrorAction SilentlyContinue)
+ $results.EvasionFindings += [PSCustomObject]@{
+ Technique = 'T1562.001'
+ Severity = 'Info'
+ Evidence = "AMSI provider registration present with $($providers.Count) provider(s) - AMSI appears registered (informational baseline)"
+ Timestamp = $null
+ }
+ }
+ else {
+ $results.EvasionFindings += [PSCustomObject]@{
+ Technique = 'T1562.001'
+ Severity = 'Info'
+ Evidence = 'AMSI provider registry key not found - AMSI providers absent or AMSI unavailable on this host (informational baseline)'
+ Timestamp = $null
+ }
+ }
+ $results.CheckStatus.AmsiProviderCheck = 'OK'
+ }
+ catch {
+ Write-Warning "Could not check AMSI provider registration: $_"
+ $results.CheckStatus.AmsiProviderCheck = 'Unknown'
+ }
+
+ # 1b. AMSI bypass patterns in script-block logs
+ Write-Verbose "Scanning script blocks for AMSI bypass patterns..."
+ try {
+ $results.Summary.ChecksRun++
+ if ($results.CheckStatus.ScriptBlockLogQuery -eq 'OK') {
+ foreach ($evt in $scriptBlockEvents) {
+ $msg = Get-EventMessage -WinEvent $evt
+ if ([string]::IsNullOrEmpty($msg)) { continue }
+
+ foreach ($indicator in $amsiPatterns) {
+ $matched = $false
+ if ($msg -match $indicator.Pattern) {
+ if ($null -eq $indicator.Combo -or $msg -match $indicator.Combo) {
+ $matched = $true
+ }
+ }
+ if ($matched) {
+ $results.EvasionFindings += [PSCustomObject]@{
+ Technique = 'T1562.001'
+ Severity = $indicator.Severity
+ Evidence = "AMSI bypass indicator '$($indicator.Name)' in PowerShell script block (4104): $(Get-MessageSnippet -Message $msg)"
+ Timestamp = Get-EventTimestamp -WinEvent $evt
+ }
+ break
+ }
+ }
+ }
+ $results.CheckStatus.AmsiPatternScan = 'OK'
+ }
+ else {
+ $results.CheckStatus.AmsiPatternScan = 'Unknown'
+ }
+ }
+ catch {
+ Write-Warning "Error scanning script blocks for AMSI bypass patterns: $_"
+ $results.CheckStatus.AmsiPatternScan = 'Unknown'
+ }
+
+ # 2a. ETW tamper patterns in script-block logs
+ Write-Verbose "Scanning script blocks for ETW tamper patterns..."
+ try {
+ $results.Summary.ChecksRun++
+ if ($results.CheckStatus.ScriptBlockLogQuery -eq 'OK') {
+ foreach ($evt in $scriptBlockEvents) {
+ $msg = Get-EventMessage -WinEvent $evt
+ if ([string]::IsNullOrEmpty($msg)) { continue }
+
+ foreach ($indicator in $etwPatterns) {
+ $matched = $false
+ if ($msg -match $indicator.Pattern) {
+ if ($null -eq $indicator.Combo -or $msg -match $indicator.Combo) {
+ $matched = $true
+ }
+ }
+ if ($matched) {
+ $results.EvasionFindings += [PSCustomObject]@{
+ Technique = 'T1562.006'
+ Severity = $indicator.Severity
+ Evidence = "ETW tamper indicator '$($indicator.Name)' in PowerShell script block (4104): $(Get-MessageSnippet -Message $msg)"
+ Timestamp = Get-EventTimestamp -WinEvent $evt
+ }
+ break
+ }
+ }
+ }
+ $results.CheckStatus.EtwPatternScan = 'OK'
+ }
+ else {
+ $results.CheckStatus.EtwPatternScan = 'Unknown'
+ }
+ }
+ catch {
+ Write-Warning "Error scanning script blocks for ETW tamper patterns: $_"
+ $results.CheckStatus.EtwPatternScan = 'Unknown'
+ }
+
+ # 2b. PowerShell script-block logging GPO state (current-state check; cannot establish when it changed)
+ Write-Verbose "Checking PowerShell logging GPO state..."
+ try {
+ $results.Summary.ChecksRun++
+ $gpoPath = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging'
+ $gpoExists = $false
+ try { $gpoExists = Test-Path $gpoPath -ErrorAction SilentlyContinue } catch { $gpoExists = $false }
+
+ if ($gpoExists) {
+ $gpo = Get-ItemProperty -Path $gpoPath -ErrorAction SilentlyContinue
+ $sblEnabled = $null
+ if ($null -ne $gpo -and $gpo.PSObject.Properties['EnableScriptBlockLogging']) {
+ $sblEnabled = $gpo.EnableScriptBlockLogging
+ }
+ if ($null -ne $sblEnabled -and 0 -eq [int]$sblEnabled) {
+ $results.EvasionFindings += [PSCustomObject]@{
+ Technique = 'T1562.002'
+ Severity = 'Medium'
+ Evidence = 'PowerShell script-block logging explicitly disabled via GPO (EnableScriptBlockLogging=0) - current-state check, change time unknown'
+ Timestamp = $null
+ }
+ }
+ elseif ($null -ne $sblEnabled -and 1 -eq [int]$sblEnabled) {
+ $results.EvasionFindings += [PSCustomObject]@{
+ Technique = 'T1562.002'
+ Severity = 'Info'
+ Evidence = 'PowerShell script-block logging enabled via GPO (informational baseline)'
+ Timestamp = $null
+ }
+ }
+ }
+ else {
+ Write-Verbose "PowerShell logging GPO key not present (default state)"
+ }
+ $results.CheckStatus.PowerShellLoggingGpo = 'OK'
+ }
+ catch {
+ Write-Warning "Could not check PowerShell logging GPO state: $_"
+ $results.CheckStatus.PowerShellLoggingGpo = 'Unknown'
+ }
+
+ # 3a. Defender preference tampering
+ Write-Verbose "Checking Windows Defender preferences..."
+ try {
+ $results.Summary.ChecksRun++
+ $mpPref = Get-MpPreference -ErrorAction Stop
+ $results.CheckStatus.DefenderPreferences = 'OK'
+
+ $exclusionPaths = @()
+ $exclusionProcesses = @()
+ $exclusionExtensions = @()
+ if ($null -ne $mpPref) {
+ if ($mpPref.PSObject.Properties['ExclusionPath'] -and $null -ne $mpPref.ExclusionPath) { $exclusionPaths = @($mpPref.ExclusionPath) }
+ if ($mpPref.PSObject.Properties['ExclusionProcess'] -and $null -ne $mpPref.ExclusionProcess) { $exclusionProcesses = @($mpPref.ExclusionProcess) }
+ if ($mpPref.PSObject.Properties['ExclusionExtension'] -and $null -ne $mpPref.ExclusionExtension) { $exclusionExtensions = @($mpPref.ExclusionExtension) }
+ }
+
+ $totalExclusions = $exclusionPaths.Count + $exclusionProcesses.Count + $exclusionExtensions.Count
+ if ($totalExclusions -gt 0) {
+ $exclSeverity = 'Medium'
+ if ($totalExclusions -gt 3) { $exclSeverity = 'High' }
+
+ $evidenceParts = @()
+ if ($exclusionPaths.Count -gt 0) { $evidenceParts += "Paths: $($exclusionPaths -join ', ')" }
+ if ($exclusionProcesses.Count -gt 0) { $evidenceParts += "Processes: $($exclusionProcesses -join ', ')" }
+ if ($exclusionExtensions.Count -gt 0) { $evidenceParts += "Extensions: $($exclusionExtensions -join ', ')" }
+
+ $results.EvasionFindings += [PSCustomObject]@{
+ Technique = 'T1562.001'
+ Severity = $exclSeverity
+ Evidence = "Windows Defender exclusions configured ($totalExclusions total) - $($evidenceParts -join '; ')"
+ Timestamp = $null
+ }
+ }
+
+ if ($null -ne $mpPref -and $mpPref.PSObject.Properties['DisableRealtimeMonitoring'] -and $mpPref.DisableRealtimeMonitoring -eq $true) {
+ $results.EvasionFindings += [PSCustomObject]@{
+ Technique = 'T1562.001'
+ Severity = 'High'
+ Evidence = 'DisableRealtimeMonitoring is set to true in Defender preferences'
+ Timestamp = $null
+ }
+ }
+ if ($null -ne $mpPref -and $mpPref.PSObject.Properties['DisableBehaviorMonitoring'] -and $mpPref.DisableBehaviorMonitoring -eq $true) {
+ $results.EvasionFindings += [PSCustomObject]@{
+ Technique = 'T1562.001'
+ Severity = 'High'
+ Evidence = 'DisableBehaviorMonitoring is set to true in Defender preferences'
+ Timestamp = $null
+ }
+ }
+ }
+ catch {
+ Write-Warning "Could not query Windows Defender preferences: $_"
+ $results.CheckStatus.DefenderPreferences = 'Unknown'
+ }
+
+ # 3b. Defender real-time protection status
+ Write-Verbose "Checking Windows Defender real-time protection status..."
+ try {
+ $results.Summary.ChecksRun++
+ $mpStatus = Get-MpComputerStatus -ErrorAction Stop
+ if ($null -ne $mpStatus -and $mpStatus.PSObject.Properties['RealTimeProtectionEnabled'] -and $mpStatus.RealTimeProtectionEnabled -eq $false) {
+ $results.EvasionFindings += [PSCustomObject]@{
+ Technique = 'T1562.001'
+ Severity = 'High'
+ Evidence = 'Windows Defender real-time protection is currently disabled'
+ Timestamp = $null
+ }
+ }
+ $results.CheckStatus.DefenderStatus = 'OK'
+ }
+ catch {
+ Write-Warning "Could not query Windows Defender computer status: $_"
+ $results.CheckStatus.DefenderStatus = 'Unknown'
+ }
+
+ # 3c. Defender Operational events 5001 (real-time protection disabled) / 5007 (configuration changed)
+ Write-Verbose "Checking Defender Operational log for tampering events..."
+ try {
+ $results.Summary.ChecksRun++
+ $defenderEvents = @(Get-WinEvent -FilterHashtable @{
+ LogName = 'Microsoft-Windows-Windows Defender/Operational'
+ ID = 5001, 5007
+ StartTime = $startTime
+ } -ErrorAction SilentlyContinue)
+
+ foreach ($evt in $defenderEvents) {
+ $msg = Get-EventMessage -WinEvent $evt
+ $eventId = $null
+ if ($null -ne $evt -and $evt.PSObject.Properties['Id']) { $eventId = $evt.Id }
+
+ if (5001 -eq $eventId) {
+ $results.EvasionFindings += [PSCustomObject]@{
+ Technique = 'T1562.001'
+ Severity = 'High'
+ Evidence = "Defender event 5001 - real-time protection disabled: $(Get-MessageSnippet -Message $msg)"
+ Timestamp = Get-EventTimestamp -WinEvent $evt
+ }
+ }
+ elseif (5007 -eq $eventId) {
+ $sev = 'Medium'
+ $desc = 'Defender configuration changed'
+ if (-not [string]::IsNullOrEmpty($msg) -and $msg -match '(?i)exclusion') {
+ $sev = 'High'
+ $desc = 'Defender exclusion changed'
+ }
+ $results.EvasionFindings += [PSCustomObject]@{
+ Technique = 'T1562.001'
+ Severity = $sev
+ Evidence = "Defender event 5007 - ${desc}: $(Get-MessageSnippet -Message $msg)"
+ Timestamp = Get-EventTimestamp -WinEvent $evt
+ }
+ }
+ }
+ $results.CheckStatus.DefenderEvents = 'OK'
+ }
+ catch {
+ Write-Warning "Could not query Defender Operational log: $_"
+ $results.CheckStatus.DefenderEvents = 'Unknown'
+ }
+
+ # 4a. Security log cleared (1102)
+ Write-Verbose "Checking for Security log cleared events (1102)..."
+ try {
+ $results.Summary.ChecksRun++
+ $clearedSecurity = @(Get-WinEvent -FilterHashtable @{
+ LogName = 'Security'
+ ID = 1102
+ StartTime = $startTime
+ } -ErrorAction SilentlyContinue)
+
+ foreach ($evt in $clearedSecurity) {
+ $subjectUser = Get-EventDataValue -WinEvent $evt -Name 'SubjectUserName'
+ $subjectDomain = Get-EventDataValue -WinEvent $evt -Name 'SubjectDomainName'
+ $who = 'Unknown'
+ if (-not [string]::IsNullOrEmpty($subjectUser)) {
+ if (-not [string]::IsNullOrEmpty($subjectDomain)) { $who = "$subjectDomain\$subjectUser" }
+ else { $who = $subjectUser }
+ }
+ $results.EvasionFindings += [PSCustomObject]@{
+ Technique = 'T1070.001'
+ Severity = 'High'
+ Evidence = "Security event log was cleared (event 1102) by '$who'"
+ Timestamp = Get-EventTimestamp -WinEvent $evt
+ }
+ }
+ $results.CheckStatus.SecurityLogCleared = 'OK'
+ }
+ catch {
+ Write-Warning "Could not query Security log for 1102 events: $_"
+ $results.CheckStatus.SecurityLogCleared = 'Unknown'
+ }
+
+ # 4b. System log cleared (104)
+ Write-Verbose "Checking for System log cleared events (104)..."
+ try {
+ $results.Summary.ChecksRun++
+ $clearedSystem = @(Get-WinEvent -FilterHashtable @{
+ LogName = 'System'
+ ID = 104
+ StartTime = $startTime
+ } -ErrorAction SilentlyContinue)
+
+ foreach ($evt in $clearedSystem) {
+ $subjectUser = Get-EventDataValue -WinEvent $evt -Name 'SubjectUserName'
+ $subjectDomain = Get-EventDataValue -WinEvent $evt -Name 'SubjectDomainName'
+ $who = 'Unknown'
+ if (-not [string]::IsNullOrEmpty($subjectUser)) {
+ if (-not [string]::IsNullOrEmpty($subjectDomain)) { $who = "$subjectDomain\$subjectUser" }
+ else { $who = $subjectUser }
+ }
+ $results.EvasionFindings += [PSCustomObject]@{
+ Technique = 'T1070.001'
+ Severity = 'High'
+ Evidence = "System event log was cleared (event 104) by '$who'"
+ Timestamp = Get-EventTimestamp -WinEvent $evt
+ }
+ }
+ $results.CheckStatus.SystemLogCleared = 'OK'
+ }
+ catch {
+ Write-Warning "Could not query System log for 104 events: $_"
+ $results.CheckStatus.SystemLogCleared = 'Unknown'
+ }
+
+ # 4c. Audit policy changed (4719)
+ Write-Verbose "Checking for audit policy change events (4719)..."
+ try {
+ $results.Summary.ChecksRun++
+ $auditChanges = @(Get-WinEvent -FilterHashtable @{
+ LogName = 'Security'
+ ID = 4719
+ StartTime = $startTime
+ } -ErrorAction SilentlyContinue)
+
+ foreach ($evt in $auditChanges) {
+ $subjectUser = Get-EventDataValue -WinEvent $evt -Name 'SubjectUserName'
+ $subjectDomain = Get-EventDataValue -WinEvent $evt -Name 'SubjectDomainName'
+ $category = Get-EventDataValue -WinEvent $evt -Name 'CategoryId'
+ $who = 'Unknown'
+ if (-not [string]::IsNullOrEmpty($subjectUser)) {
+ if (-not [string]::IsNullOrEmpty($subjectDomain)) { $who = "$subjectDomain\$subjectUser" }
+ else { $who = $subjectUser }
+ }
+ $catText = 'Unknown category'
+ if (-not [string]::IsNullOrEmpty($category)) { $catText = "category $category" }
+ $results.EvasionFindings += [PSCustomObject]@{
+ Technique = 'T1562.002'
+ Severity = 'High'
+ Evidence = "System audit policy was changed (event 4719, $catText) by '$who'"
+ Timestamp = Get-EventTimestamp -WinEvent $evt
+ }
+ }
+ $results.CheckStatus.AuditPolicyChanged = 'OK'
+ }
+ catch {
+ Write-Warning "Could not query Security log for 4719 events: $_"
+ $results.CheckStatus.AuditPolicyChanged = 'Unknown'
+ }
+
+ # 5. Log-gap analysis (heuristic)
+ if ($IncludeLogGapAnalysis) {
+ Write-Verbose "Performing heuristic log-gap analysis..."
+ $gapLogs = @('Security', 'System', 'Microsoft-Windows-PowerShell/Operational')
+ $gapStatus = 'OK'
+
+ foreach ($logName in $gapLogs) {
+ try {
+ $results.Summary.ChecksRun++
+ $logEvents = @(Get-WinEvent -FilterHashtable @{
+ LogName = $logName
+ StartTime = $startTime
+ } -ErrorAction SilentlyContinue)
+
+ $timedEvents = @($logEvents | Where-Object {
+ $null -ne $_ -and $_.PSObject.Properties['TimeCreated'] -and $null -ne $_.TimeCreated
+ })
+ if ($timedEvents.Count -lt 5) {
+ Write-Verbose "Not enough events in '$logName' for gap analysis ($($timedEvents.Count) events)"
+ continue
+ }
+
+ $sorted = @($timedEvents | Sort-Object -Property TimeCreated)
+
+ $maxGapHours = 0.0
+ $gapStart = $null
+ $gapEnd = $null
+ $gapIndex = -1
+ for ($i = 1; $i -lt $sorted.Count; $i++) {
+ $gapHours = ($sorted[$i].TimeCreated - $sorted[$i - 1].TimeCreated).TotalHours
+ if ($gapHours -gt $maxGapHours) {
+ $maxGapHours = $gapHours
+ $gapStart = $sorted[$i - 1].TimeCreated
+ $gapEnd = $sorted[$i].TimeCreated
+ $gapIndex = $i
+ }
+ }
+
+ $activeBefore = ($gapIndex -ge 2)
+ $activeAfter = (($sorted.Count - $gapIndex) -ge 2)
+
+ if ($maxGapHours -gt 2 -and $activeBefore -and $activeAfter) {
+ $results.EvasionFindings += [PSCustomObject]@{
+ Technique = 'T1070'
+ Severity = 'Low'
+ Evidence = "Suspicious gap (heuristic): largest gap of $([math]::Round($maxGapHours, 2)) hours with no events in '$logName' between $gapStart and $gapEnd during an otherwise-active period - may indicate log tampering or service downtime"
+ Timestamp = $gapEnd
+ }
+ }
+ }
+ catch {
+ Write-Warning "Could not perform gap analysis on '$logName': $_"
+ $gapStatus = 'Unknown'
+ }
+ }
+ $results.CheckStatus.LogGapAnalysis = $gapStatus
+ }
+ }
+ catch {
+ Write-Error "Error during defense-evasion scan: $_"
+ throw
+ }
+ }
+
+ end {
+ # Summarize findings by severity
+ $allFindings = @($results.EvasionFindings)
+ $results.Summary.TotalFindings = $allFindings.Count
+ $results.Summary.Critical = @($allFindings | Where-Object { $_.Severity -eq 'Critical' }).Count
+ $results.Summary.High = @($allFindings | Where-Object { $_.Severity -eq 'High' }).Count
+ $results.Summary.Medium = @($allFindings | Where-Object { $_.Severity -eq 'Medium' }).Count
+ $results.Summary.Low = @($allFindings | Where-Object { $_.Severity -eq 'Low' }).Count
+ $results.Summary.Info = @($allFindings | Where-Object { $_.Severity -eq 'Info' }).Count
+
+ # Build recommendations
+ $recommendations = @(
+ 'Enable and centrally forward PowerShell script-block logging (4104), Defender Operational, and Security/System logs to a tamper-resistant SIEM'
+ 'Enable Windows Defender Tamper Protection to prevent unauthorized changes to exclusions and real-time monitoring'
+ 'Alert on event IDs 1102 (Security log cleared), 104 (System log cleared), and 4719 (audit policy changed) as high-priority detections'
+ )
+
+ if (@($allFindings | Where-Object { $_.Technique -eq 'T1562.001' -and $_.Severity -in @('High', 'Medium') }).Count -gt 0) {
+ $recommendations += 'Investigate AMSI/Defender tampering findings: review the flagged script blocks and validate every Defender exclusion against change records'
+ }
+ if (@($allFindings | Where-Object { $_.Technique -eq 'T1562.006' }).Count -gt 0) {
+ $recommendations += 'Investigate ETW tampering indicators and consider deploying ETW-based tamper detection (e.g., monitoring for EtwEventWrite patching)'
+ }
+ if (@($allFindings | Where-Object { $_.Technique -eq 'T1070.001' }).Count -gt 0) {
+ $recommendations += 'Treat cleared event logs as a potential intrusion in progress: identify the clearing account, review activity around the clear time, and verify log-forwarding coverage'
+ }
+ if (@($allFindings | Where-Object { $_.Technique -eq 'T1562.002' }).Count -gt 0) {
+ $recommendations += 'Review audit policy and PowerShell logging GPO changes; re-enable logging and investigate who disabled it'
+ }
+ if (@($allFindings | Where-Object { $_.Technique -eq 'T1070' }).Count -gt 0) {
+ $recommendations += 'Log-gap findings are heuristic only: corroborate gaps with service uptime and SIEM ingestion health before treating them as tampering'
+ }
+ $results.Recommendations = $recommendations
+
+ Write-Host "`nDefense-evasion scan complete!" -ForegroundColor Green
+ Write-Host "Total findings: $($results.Summary.TotalFindings)" -ForegroundColor $(if ($results.Summary.TotalFindings -gt 0) { 'Yellow' } else { 'Green' })
+ Write-Host " High: $($results.Summary.High)" -ForegroundColor $(if ($results.Summary.High -gt 0) { 'Red' } else { 'Green' })
+ Write-Host " Medium: $($results.Summary.Medium)" -ForegroundColor $(if ($results.Summary.Medium -gt 0) { 'Yellow' } else { 'Green' })
+ Write-Host " Low: $($results.Summary.Low)" -ForegroundColor Cyan
+ Write-Host " Info: $($results.Summary.Info)" -ForegroundColor Cyan
+ Write-Host "Checks run: $($results.Summary.ChecksRun)" -ForegroundColor Cyan
+
+ return $results
+ }
+}
diff --git a/Detection/Find-SuspiciousAuthentication.ps1 b/Detection/Find-SuspiciousAuthentication.ps1
index 2d8166b..a20469b 100644
--- a/Detection/Find-SuspiciousAuthentication.ps1
+++ b/Detection/Find-SuspiciousAuthentication.ps1
@@ -4,7 +4,8 @@ function Find-SuspiciousAuthentication {
Detects suspicious authentication events and patterns
.DESCRIPTION
Analyzes Windows Security event logs for suspicious authentication activities including
- brute force attempts, unusual logon patterns, credential dumping, and privilege escalation
+ brute force attempts, unusual logon patterns, NewCredentials (runas /netonly) logons,
+ NTLM network logon usage, credential dumping, and privilege escalation
.PARAMETER Hours
Number of hours to look back in event logs (default: 24)
.PARAMETER IncludeSuccessful
@@ -41,18 +42,30 @@ function Find-SuspiciousAuthentication {
PrivilegeEscalations = @()
UnusualLogons = @()
ExplicitCredentials = @()
+ NewCredentialLogons = @()
+ NtlmNetworkLogonIndicators = @()
BruteForceIndicators = @()
Statistics = @{
TotalFailedLogons = 0
TotalLockouts = 0
TotalPrivilegeUse = 0
TotalExplicitCreds = 0
+ TotalNewCredentialLogons = 0
+ NtlmNetworkLogonAccounts = 0
UniqueFailedAccounts = 0
UniqueSourceIPs = 0
}
}
$startTime = (Get-Date).AddHours(-$Hours)
+
+ $getEventValue = {
+ param($EventData, [string]$Name)
+ if ($null -eq $EventData) { return $null }
+ $node = $EventData | Where-Object { $_.Name -eq $Name }
+ if ($null -ne $node) { return $node.InnerText }
+ return $null
+ }
}
process {
@@ -227,48 +240,87 @@ function Find-SuspiciousAuthentication {
}
}
- # 5. Successful Logons Analysis (if requested)
- if ($IncludeSuccessful) {
- Write-Verbose "Analyzing successful logons..."
- $successfulLogons = Get-WinEvent -FilterHashtable @{
- LogName = 'Security'
- ID = 4624
- StartTime = $startTime
- } -ErrorAction SilentlyContinue
-
- if ($successfulLogons) {
- foreach ($event in $successfulLogons) {
- $xml = [xml]$event.ToXml()
- $eventData = $xml.Event.EventData.Data
-
- $targetAccount = ($eventData | Where-Object { $_.Name -eq 'TargetUserName' }).'#text'
- $logonType = ($eventData | Where-Object { $_.Name -eq 'LogonType' }).'#text'
- $sourceIP = ($eventData | Where-Object { $_.Name -eq 'IpAddress' }).'#text'
- $workstation = ($eventData | Where-Object { $_.Name -eq 'WorkstationName' }).'#text'
-
+ # 5. Successful Logons Analysis (Event ID 4624)
+ Write-Verbose "Analyzing successful logons..."
+ $successfulLogons = Get-WinEvent -FilterHashtable @{
+ LogName = 'Security'
+ ID = 4624
+ StartTime = $startTime
+ } -ErrorAction SilentlyContinue
+
+ if ($successfulLogons) {
+ $ntlmNetworkByAccount = @{}
+
+ foreach ($event in $successfulLogons) {
+ $xml = [xml]$event.ToXml()
+ $eventData = $xml.Event.EventData.Data
+
+ $targetAccount = & $getEventValue $eventData 'TargetUserName'
+ $targetDomain = & $getEventValue $eventData 'TargetDomainName'
+ $logonType = & $getEventValue $eventData 'LogonType'
+ $sourceIP = & $getEventValue $eventData 'IpAddress'
+ $workstation = & $getEventValue $eventData 'WorkstationName'
+ $authPackage = & $getEventValue $eventData 'AuthenticationPackageName'
+ $processName = & $getEventValue $eventData 'ProcessName'
+
+ # LogonType 9 = NewCredentials (runas /netonly) - pass-the-hash / explicit credential reuse indicator
+ if ($logonType -eq '9' -and $targetAccount -and $targetAccount -notmatch '\$$') {
+ $results.NewCredentialLogons += [PSCustomObject]@{
+ TimeCreated = $event.TimeCreated
+ Account = "$targetDomain\$targetAccount"
+ Workstation = $workstation
+ SourceIP = $sourceIP
+ Process = $processName
+ Severity = 'Medium'
+ Indicator = 'NewCredentials logon (runas /netonly style) - possible pass-the-hash or explicit credential reuse'
+ }
+ }
+
+ # NTLM network logons where Kerberos is normally expected - aggregated per account to keep noise down
+ if ($logonType -eq '3' -and $authPackage -eq 'NTLM' -and $targetAccount -and
+ $targetAccount -notmatch '\$$' -and $targetAccount -ne 'ANONYMOUS LOGON') {
+ $accountKey = "$targetDomain\$targetAccount"
+ if (-not $ntlmNetworkByAccount.ContainsKey($accountKey)) {
+ $ntlmNetworkByAccount[$accountKey] = [PSCustomObject]@{
+ Account = $accountKey
+ Count = 0
+ SourceIPs = @()
+ LastSeen = $event.TimeCreated
+ }
+ }
+ $ntlmNetworkByAccount[$accountKey].Count++
+ if ($sourceIP -and $sourceIP -ne '-' -and $ntlmNetworkByAccount[$accountKey].SourceIPs -notcontains $sourceIP) {
+ $ntlmNetworkByAccount[$accountKey].SourceIPs += $sourceIP
+ }
+ if ($null -ne $event.TimeCreated -and $event.TimeCreated -gt $ntlmNetworkByAccount[$accountKey].LastSeen) {
+ $ntlmNetworkByAccount[$accountKey].LastSeen = $event.TimeCreated
+ }
+ }
+
+ if ($IncludeSuccessful) {
# Flag unusual logon types or times
$hour = $event.TimeCreated.Hour
$isUnusual = $false
$reason = ""
-
+
# Check for after-hours logon (outside 7 AM - 7 PM)
if ($hour -lt 7 -or $hour -gt 19) {
$isUnusual = $true
$reason = "After-hours logon"
}
-
+
# Type 10 = RemoteInteractive (RDP)
if ($logonType -eq '10' -and $sourceIP -ne '127.0.0.1' -and $sourceIP -ne '-') {
$isUnusual = $true
$reason += "; Remote desktop logon from $sourceIP"
}
-
+
# Type 3 = Network logon to admin shares
if ($logonType -eq '3' -and $targetAccount -match 'admin') {
$isUnusual = $true
$reason += "; Network logon with admin account"
}
-
+
if ($isUnusual) {
$results.UnusualLogons += [PSCustomObject]@{
TimeCreated = $event.TimeCreated
@@ -281,6 +333,21 @@ function Find-SuspiciousAuthentication {
}
}
}
+
+ $results.Statistics.TotalNewCredentialLogons = @($results.NewCredentialLogons).Count
+
+ foreach ($accountKey in $ntlmNetworkByAccount.Keys) {
+ $ntlmInfo = $ntlmNetworkByAccount[$accountKey]
+ $results.NtlmNetworkLogonIndicators += [PSCustomObject]@{
+ Account = $ntlmInfo.Account
+ LogonCount = $ntlmInfo.Count
+ SourceIPs = ($ntlmInfo.SourceIPs -join ', ')
+ LastSeen = $ntlmInfo.LastSeen
+ Severity = 'Low'
+ Indicator = 'NTLM network logon where Kerberos is normally expected (informational)'
+ }
+ }
+ $results.Statistics.NtlmNetworkLogonAccounts = @($results.NtlmNetworkLogonIndicators).Count
}
}
@@ -298,6 +365,8 @@ function Find-SuspiciousAuthentication {
Write-Host "Account lockouts: $($results.Statistics.TotalLockouts)" -ForegroundColor $(if ($results.Statistics.TotalLockouts -gt 0) { 'Red' } else { 'Green' })
Write-Host "Privilege escalations: $($results.PrivilegeEscalations.Count)" -ForegroundColor Yellow
Write-Host "Explicit credential usage: $($results.Statistics.TotalExplicitCreds)" -ForegroundColor Yellow
+ Write-Host "NewCredentials (type 9) logons: $($results.Statistics.TotalNewCredentialLogons)" -ForegroundColor $(if ($results.Statistics.TotalNewCredentialLogons -gt 0) { 'Red' } else { 'Green' })
+ Write-Host "Accounts with NTLM network logons: $($results.Statistics.NtlmNetworkLogonAccounts)" -ForegroundColor Yellow
Write-Host "Brute force indicators: $($results.BruteForceIndicators.Count)" -ForegroundColor $(if ($results.BruteForceIndicators.Count -gt 0) { 'Red' } else { 'Green' })
if ($IncludeSuccessful) {
diff --git a/Detection/Get-CredentialAccessEvents.ps1 b/Detection/Get-CredentialAccessEvents.ps1
new file mode 100644
index 0000000..e41a773
--- /dev/null
+++ b/Detection/Get-CredentialAccessEvents.ps1
@@ -0,0 +1,487 @@
+function Get-CredentialAccessEvents {
+ <#
+ .SYNOPSIS
+ Detects runtime credential-access activity from Windows event logs
+ .DESCRIPTION
+ Analyzes Windows Security (and optionally Sysmon) event logs for credential-access
+ techniques: Kerberoasting (RC4 service ticket bursts), anomalous TGT request volumes,
+ Kerberos pre-authentication failure spikes (brute force / password spray), a best-effort
+ golden-ticket heuristic (Kerberos logons with no matching TGT request in the window),
+ and optionally processes with open access handles to lsass.exe (4663 or Sysmon 10).
+ Heuristic detections are labeled as such and should be validated manually.
+ .PARAMETER Hours
+ Number of hours to look back in event logs (default: 24)
+ .PARAMETER IncludeLSASSAccess
+ Also enumerate processes with open access handles to lsass.exe. Uses Security event
+ 4663 (requires Object Access auditing with a SACL on lsass.exe) and Sysmon event ID 10
+ when the Sysmon Operational log is present
+ .EXAMPLE
+ Get-CredentialAccessEvents
+ Get-CredentialAccessEvents -Hours 48 -IncludeLSASSAccess
+ .OUTPUTS
+ PSCustomObject with Events, Summary, and Recommendations
+ #>
+
+ [CmdletBinding()]
+ param(
+ [Parameter()]
+ [int]$Hours = 24,
+
+ [Parameter()]
+ [switch]$IncludeLSASSAccess
+ )
+
+ begin {
+ Write-Host "Analyzing credential-access events (last $Hours hours)..." -ForegroundColor Cyan
+
+ $results = [PSCustomObject]@{
+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
+ TimeRange = "$Hours hours"
+ Events = @()
+ Summary = @{
+ RC4ServiceTicketRequests = 0
+ KerberoastBursts = 0
+ TGTAnomalies = 0
+ KerberosFailureSpikes = 0
+ GoldenTicketHeuristics = 0
+ LSASSAccessEvents = 0
+ SuspiciousLSASSAccess = 0
+ }
+ Recommendations = @()
+ }
+
+ $startTime = (Get-Date).AddHours(-$Hours)
+
+ # Granted-access masks that are normal for DLL loads / telemetry against lsass.exe
+ $normalAccessMasks = @('0x1000', '0x1400', '0x1410')
+ # PROCESS_VM_READ (0x0010) or broad rights (PROCESS_ALL_ACCESS style) are suspicious
+ $suspiciousAccessMasks = @('0x1010', '0x101a', '0x103a', '0x143a', '0x1f0fff', '0x1fffff')
+
+ $getEventValue = {
+ param($EventData, [string]$Name)
+ if ($null -eq $EventData) { return $null }
+ $node = $EventData | Where-Object { $_.Name -eq $Name }
+ if ($null -ne $node) { return $node.InnerText }
+ return $null
+ }
+ }
+
+ process {
+ # 1. Kerberoasting: RC4-encrypted service ticket requests (Event ID 4769, TicketEncryptionType 0x17)
+ $rc4ByAccount = @{}
+ try {
+ Write-Verbose "Analyzing service ticket requests (4769)..."
+ $ticketEvents = Get-WinEvent -FilterHashtable @{
+ LogName = 'Security'
+ ID = 4769
+ StartTime = $startTime
+ } -ErrorAction SilentlyContinue
+
+ foreach ($event in @($ticketEvents)) {
+ if ($null -eq $event) { continue }
+ $eventData = ([xml]$event.ToXml()).Event.EventData.Data
+
+ $targetAccount = & $getEventValue $eventData 'TargetUserName'
+ $serviceName = & $getEventValue $eventData 'ServiceName'
+ $encryptionType = & $getEventValue $eventData 'TicketEncryptionType'
+ $sourceIP = & $getEventValue $eventData 'IpAddress'
+
+ if ($encryptionType -ne '0x17') { continue }
+ if (-not $targetAccount -or $targetAccount -match '\$$') { continue }
+ if (-not $serviceName -or $serviceName -match '\$$' -or $serviceName -eq 'krbtgt') { continue }
+
+ $results.Summary.RC4ServiceTicketRequests++
+
+ if (-not $rc4ByAccount.ContainsKey($targetAccount)) {
+ $rc4ByAccount[$targetAccount] = [PSCustomObject]@{
+ Account = $targetAccount
+ Count = 0
+ Services = @()
+ SourceIPs = @()
+ FirstSeen = $event.TimeCreated
+ LastSeen = $event.TimeCreated
+ }
+ }
+ $rc4ByAccount[$targetAccount].Count++
+ if ($serviceName -and $rc4ByAccount[$targetAccount].Services -notcontains $serviceName) {
+ $rc4ByAccount[$targetAccount].Services += $serviceName
+ }
+ if ($sourceIP -and $sourceIP -ne '-' -and $rc4ByAccount[$targetAccount].SourceIPs -notcontains $sourceIP) {
+ $rc4ByAccount[$targetAccount].SourceIPs += $sourceIP
+ }
+ if ($null -ne $event.TimeCreated) {
+ if ($null -eq $rc4ByAccount[$targetAccount].FirstSeen -or $event.TimeCreated -lt $rc4ByAccount[$targetAccount].FirstSeen) { $rc4ByAccount[$targetAccount].FirstSeen = $event.TimeCreated }
+ if ($null -eq $rc4ByAccount[$targetAccount].LastSeen -or $event.TimeCreated -gt $rc4ByAccount[$targetAccount].LastSeen) { $rc4ByAccount[$targetAccount].LastSeen = $event.TimeCreated }
+ }
+ }
+
+ foreach ($accountName in $rc4ByAccount.Keys) {
+ $rc4Info = $rc4ByAccount[$accountName]
+ if ($rc4Info.Count -gt 5) {
+ $results.Summary.KerberoastBursts++
+ $results.Events += [PSCustomObject]@{
+ TimeCreated = $rc4Info.LastSeen
+ Category = 'KerberoastBurst'
+ Severity = 'High'
+ Account = $rc4Info.Account
+ Source = ($rc4Info.SourceIPs -join ', ')
+ Details = "$($rc4Info.Count) RC4-encrypted service ticket requests in window for $($rc4Info.Services.Count) distinct service(s): $($rc4Info.Services -join ', ')"
+ DetectionMethod = 'Threshold'
+ Confidence = 'High'
+ }
+ }
+ else {
+ $results.Events += [PSCustomObject]@{
+ TimeCreated = $rc4Info.LastSeen
+ Category = 'RC4ServiceTicketRequest'
+ Severity = 'Low'
+ Account = $rc4Info.Account
+ Source = ($rc4Info.SourceIPs -join ', ')
+ Details = "$($rc4Info.Count) RC4-encrypted service ticket request(s) for: $($rc4Info.Services -join ', ') (informational - may be legacy clients)"
+ DetectionMethod = 'Signature'
+ Confidence = 'Low'
+ }
+ }
+ }
+ }
+ catch {
+ Write-Warning "Service ticket (4769) analysis not available: $_"
+ $results.Recommendations += 'Service ticket auditing (4769) was not available - verify the Security log is accessible and Kerberos service ticket auditing is enabled'
+ }
+
+ # 2. Anomalous TGT request volumes (Event ID 4768) - per-account counts also feed the golden-ticket heuristic
+ $tgtCountByAccount = @{}
+ try {
+ Write-Verbose "Analyzing TGT requests (4768)..."
+ $tgtEvents = Get-WinEvent -FilterHashtable @{
+ LogName = 'Security'
+ ID = 4768
+ StartTime = $startTime
+ } -ErrorAction SilentlyContinue
+
+ foreach ($event in @($tgtEvents)) {
+ if ($null -eq $event) { continue }
+ $eventData = ([xml]$event.ToXml()).Event.EventData.Data
+
+ $targetAccount = & $getEventValue $eventData 'TargetUserName'
+ if (-not $targetAccount -or $targetAccount -match '\$$') { continue }
+
+ if (-not $tgtCountByAccount.ContainsKey($targetAccount)) {
+ $tgtCountByAccount[$targetAccount] = [PSCustomObject]@{
+ Account = $targetAccount
+ Count = 0
+ SourceIPs = @()
+ LastSeen = $event.TimeCreated
+ }
+ }
+ $tgtCountByAccount[$targetAccount].Count++
+ $sourceIP = & $getEventValue $eventData 'IpAddress'
+ if ($sourceIP -and $sourceIP -ne '-' -and $tgtCountByAccount[$targetAccount].SourceIPs -notcontains $sourceIP) {
+ $tgtCountByAccount[$targetAccount].SourceIPs += $sourceIP
+ }
+ if ($null -ne $event.TimeCreated -and ($null -eq $tgtCountByAccount[$targetAccount].LastSeen -or $event.TimeCreated -gt $tgtCountByAccount[$targetAccount].LastSeen)) {
+ $tgtCountByAccount[$targetAccount].LastSeen = $event.TimeCreated
+ }
+ }
+
+ foreach ($accountName in $tgtCountByAccount.Keys) {
+ $tgtInfo = $tgtCountByAccount[$accountName]
+ if ($tgtInfo.Count -gt 20) {
+ $results.Summary.TGTAnomalies++
+ $results.Events += [PSCustomObject]@{
+ TimeCreated = $tgtInfo.LastSeen
+ Category = 'TGTAnomaly'
+ Severity = 'Medium'
+ Account = $tgtInfo.Account
+ Source = ($tgtInfo.SourceIPs -join ', ')
+ Details = "$($tgtInfo.Count) TGT requests in a $Hours-hour window (threshold: 20) - unusually high volume"
+ DetectionMethod = 'Threshold'
+ Confidence = 'Medium'
+ }
+ }
+ }
+ }
+ catch {
+ Write-Warning "TGT request (4768) analysis not available: $_"
+ $results.Recommendations += 'TGT auditing (4768) was not available - verify the Security log is accessible and Kerberos authentication service auditing is enabled'
+ }
+
+ # 3. Kerberos pre-authentication failure spikes (Event ID 4771) - brute force / password spray
+ try {
+ Write-Verbose "Analyzing Kerberos pre-authentication failures (4771)..."
+ $krbFailEvents = Get-WinEvent -FilterHashtable @{
+ LogName = 'Security'
+ ID = 4771
+ StartTime = $startTime
+ } -ErrorAction SilentlyContinue
+
+ $failByAccount = @{}
+ foreach ($event in @($krbFailEvents)) {
+ if ($null -eq $event) { continue }
+ $eventData = ([xml]$event.ToXml()).Event.EventData.Data
+
+ $targetAccount = & $getEventValue $eventData 'TargetUserName'
+ if (-not $targetAccount -or $targetAccount -match '\$$') { continue }
+
+ if (-not $failByAccount.ContainsKey($targetAccount)) {
+ $failByAccount[$targetAccount] = [PSCustomObject]@{
+ Account = $targetAccount
+ Count = 0
+ SourceIPs = @()
+ FailureCodes = @()
+ LastSeen = $event.TimeCreated
+ }
+ }
+ $failByAccount[$targetAccount].Count++
+ $sourceIP = & $getEventValue $eventData 'IpAddress'
+ $failureCode = & $getEventValue $eventData 'FailureCode'
+ if ($sourceIP -and $sourceIP -ne '-' -and $failByAccount[$targetAccount].SourceIPs -notcontains $sourceIP) {
+ $failByAccount[$targetAccount].SourceIPs += $sourceIP
+ }
+ if ($failureCode -and $failByAccount[$targetAccount].FailureCodes -notcontains $failureCode) {
+ $failByAccount[$targetAccount].FailureCodes += $failureCode
+ }
+ if ($null -ne $event.TimeCreated -and ($null -eq $failByAccount[$targetAccount].LastSeen -or $event.TimeCreated -gt $failByAccount[$targetAccount].LastSeen)) {
+ $failByAccount[$targetAccount].LastSeen = $event.TimeCreated
+ }
+ }
+
+ foreach ($accountName in $failByAccount.Keys) {
+ $failInfo = $failByAccount[$accountName]
+ if ($failInfo.Count -ge 5) {
+ $severity = if ($failInfo.Count -ge 10) { 'High' } else { 'Medium' }
+ $results.Summary.KerberosFailureSpikes++
+ $results.Events += [PSCustomObject]@{
+ TimeCreated = $failInfo.LastSeen
+ Category = 'KerberosFailureSpike'
+ Severity = $severity
+ Account = $failInfo.Account
+ Source = ($failInfo.SourceIPs -join ', ')
+ Details = "$($failInfo.Count) Kerberos pre-authentication failures in window (failure codes: $($failInfo.FailureCodes -join ', ')) - possible brute force or password spray"
+ DetectionMethod = 'Threshold'
+ Confidence = 'Medium'
+ }
+ }
+ }
+ }
+ catch {
+ Write-Warning "Kerberos failure (4771) analysis not available: $_"
+ $results.Recommendations += 'Kerberos failure auditing (4771) was not available - verify the Security log is accessible and credential validation auditing is enabled'
+ }
+
+ # 4. Golden-ticket heuristic: Kerberos logons (4624) for accounts with no matching 4768 TGT request in the window
+ try {
+ Write-Verbose "Correlating logons (4624) against TGT requests (golden-ticket heuristic)..."
+ $logonEvents = Get-WinEvent -FilterHashtable @{
+ LogName = 'Security'
+ ID = 4624
+ StartTime = $startTime
+ } -ErrorAction SilentlyContinue
+
+ $flaggedAccounts = @{}
+ foreach ($event in @($logonEvents)) {
+ if ($null -eq $event) { continue }
+ $eventData = ([xml]$event.ToXml()).Event.EventData.Data
+
+ $targetAccount = & $getEventValue $eventData 'TargetUserName'
+ $logonType = & $getEventValue $eventData 'LogonType'
+ $authPackage = & $getEventValue $eventData 'AuthenticationPackageName'
+ $sourceIP = & $getEventValue $eventData 'IpAddress'
+ $workstation = & $getEventValue $eventData 'WorkstationName'
+
+ if ($logonType -ne '3' -or $authPackage -ne 'Kerberos') { continue }
+ if (-not $targetAccount -or $targetAccount -match '\$$' -or $targetAccount -match '^(SYSTEM|ANONYMOUS LOGON)$') { continue }
+ if ($tgtCountByAccount.ContainsKey($targetAccount)) { continue }
+ if ($flaggedAccounts.ContainsKey($targetAccount)) { continue }
+
+ $flaggedAccounts[$targetAccount] = $true
+ $results.Summary.GoldenTicketHeuristics++
+ $results.Events += [PSCustomObject]@{
+ TimeCreated = $event.TimeCreated
+ Category = 'GoldenTicketHeuristic'
+ Severity = 'Medium'
+ Account = $targetAccount
+ Source = if ($sourceIP -and $sourceIP -ne '-') { $sourceIP } else { $workstation }
+ Details = 'Kerberos network logon with no matching TGT request (4768) for this account in the analysis window - HEURISTIC: may also result from log sampling gaps, cross-domain logons, or tickets issued before the window'
+ DetectionMethod = 'Heuristic'
+ Confidence = 'Medium'
+ }
+ }
+ }
+ catch {
+ Write-Warning "Golden-ticket heuristic correlation not available: $_"
+ $results.Recommendations += 'Logon correlation (4624/4768) was not available - verify the Security log is accessible'
+ }
+
+ # 5. LSASS access handle enumeration (optional): Security 4663 and/or Sysmon 10
+ if ($IncludeLSASSAccess) {
+ $lsassFound = $false
+
+ try {
+ Write-Verbose "Checking Sysmon Operational log availability..."
+ $sysmonAvailable = $false
+ try {
+ $null = Get-WinEvent -ListLog 'Microsoft-Windows-Sysmon/Operational' -ErrorAction Stop
+ $sysmonAvailable = $true
+ }
+ catch {
+ $sysmonAvailable = $false
+ }
+
+ Write-Verbose "Enumerating LSASS access events (4663)..."
+ $handleEvents = Get-WinEvent -FilterHashtable @{
+ LogName = 'Security'
+ ID = 4663
+ StartTime = $startTime
+ } -ErrorAction SilentlyContinue
+
+ foreach ($event in @($handleEvents)) {
+ if ($null -eq $event) { continue }
+ $eventData = ([xml]$event.ToXml()).Event.EventData.Data
+
+ $objectName = & $getEventValue $eventData 'ObjectName'
+ if (-not $objectName -or $objectName -notmatch 'lsass\.exe$') { continue }
+
+ $lsassFound = $true
+ $processName = & $getEventValue $eventData 'ProcessName'
+ $subjectAccount = & $getEventValue $eventData 'SubjectUserName'
+ $accessMask = & $getEventValue $eventData 'AccessMask'
+
+ $classification = 'Review'
+ $severity = 'Medium'
+ $maskValue = $null
+ if ($accessMask) {
+ try { $maskValue = [Convert]::ToInt64($accessMask, 16) } catch { $maskValue = $null }
+ }
+ if ($null -ne $maskValue) {
+ if (($maskValue -band 0x10) -ne 0 -or $suspiciousAccessMasks -contains $accessMask.ToLower()) {
+ $classification = 'Suspicious'
+ $severity = 'High'
+ }
+ elseif ($normalAccessMasks -contains $accessMask.ToLower()) {
+ $classification = 'Normal'
+ $severity = 'Info'
+ }
+ }
+
+ if ($classification -eq 'Normal') { continue }
+
+ $results.Summary.LSASSAccessEvents++
+ if ($classification -eq 'Suspicious') { $results.Summary.SuspiciousLSASSAccess++ }
+ $results.Events += [PSCustomObject]@{
+ TimeCreated = $event.TimeCreated
+ Category = 'LSASSAccess'
+ Severity = $severity
+ Account = $subjectAccount
+ Source = $processName
+ Details = "Process accessed lsass.exe with access mask $accessMask ($classification) - PROCESS_VM_READ (0x10) or broad rights may indicate credential dumping"
+ DetectionMethod = 'Signature'
+ Confidence = if ($classification -eq 'Suspicious') { 'High' } else { 'Low' }
+ }
+ }
+
+ if ($sysmonAvailable) {
+ $sysmonEvents = Get-WinEvent -FilterHashtable @{
+ LogName = 'Microsoft-Windows-Sysmon/Operational'
+ ID = 10
+ StartTime = $startTime
+ } -ErrorAction SilentlyContinue
+
+ foreach ($event in @($sysmonEvents)) {
+ if ($null -eq $event) { continue }
+ $eventData = ([xml]$event.ToXml()).Event.EventData.Data
+
+ $targetImage = & $getEventValue $eventData 'TargetImage'
+ if (-not $targetImage -or $targetImage -notmatch 'lsass\.exe$') { continue }
+
+ $lsassFound = $true
+ $sourceImage = & $getEventValue $eventData 'SourceImage'
+ $grantedAccess = & $getEventValue $eventData 'GrantedAccess'
+
+ $classification = 'Review'
+ $severity = 'Medium'
+ $maskValue = $null
+ if ($grantedAccess) {
+ try { $maskValue = [Convert]::ToInt64($grantedAccess, 16) } catch { $maskValue = $null }
+ }
+ if ($null -ne $maskValue) {
+ if (($maskValue -band 0x10) -ne 0 -or $suspiciousAccessMasks -contains $grantedAccess.ToLower()) {
+ $classification = 'Suspicious'
+ $severity = 'High'
+ }
+ elseif ($normalAccessMasks -contains $grantedAccess.ToLower()) {
+ $classification = 'Normal'
+ $severity = 'Info'
+ }
+ }
+
+ if ($classification -eq 'Normal') { continue }
+
+ $results.Summary.LSASSAccessEvents++
+ if ($classification -eq 'Suspicious') { $results.Summary.SuspiciousLSASSAccess++ }
+ $results.Events += [PSCustomObject]@{
+ TimeCreated = $event.TimeCreated
+ Category = 'LSASSAccess'
+ Severity = $severity
+ Account = ''
+ Source = $sourceImage
+ Details = "Sysmon ProcessAccess: $sourceImage opened lsass.exe with granted access $grantedAccess ($classification) - PROCESS_VM_READ (0x10) or broad rights may indicate credential dumping"
+ DetectionMethod = 'Signature'
+ Confidence = if ($classification -eq 'Suspicious') { 'High' } else { 'Low' }
+ }
+ }
+ }
+
+ if (-not $lsassFound) {
+ Write-Verbose "No LSASS access events found"
+ $results.Recommendations += 'No lsass.exe access-handle events found - enable Object Access auditing with a SACL on lsass.exe (Security 4663) or deploy Sysmon with ProcessAccess (ID 10) logging for LSASS access visibility'
+ }
+ }
+ catch {
+ Write-Warning "LSASS access analysis not available: $_"
+ $results.Recommendations += 'LSASS access monitoring not available - enable Object Access auditing on lsass.exe or install Sysmon with ProcessAccess events'
+ }
+ }
+
+ # Recommendations based on findings
+ if ($results.Summary.KerberoastBursts -gt 0) {
+ $results.Recommendations += 'Investigate accounts with RC4 service-ticket bursts (possible Kerberoasting); prefer AES for service accounts, use gMSA or long random service account passwords, and rotate exposed credentials'
+ }
+ if ($results.Summary.KerberosFailureSpikes -gt 0) {
+ $results.Recommendations += 'Investigate Kerberos pre-authentication failure spikes for brute force or password spray; enforce lockout policies and MFA'
+ }
+ if ($results.Summary.TGTAnomalies -gt 0) {
+ $results.Recommendations += 'Review accounts with unusually high TGT request volumes; correlate with expected application behavior before treating as malicious'
+ }
+ if ($results.Summary.GoldenTicketHeuristics -gt 0) {
+ $results.Recommendations += 'Golden-ticket heuristic hits require manual validation - verify log coverage for 4768 on all DCs before concluding ticket forgery (heuristic, Medium confidence)'
+ }
+ if ($results.Summary.SuspiciousLSASSAccess -gt 0) {
+ $results.Recommendations += 'Suspicious lsass.exe access detected - isolate the host, capture memory for analysis, and reset credentials that may have been exposed'
+ }
+ }
+
+ end {
+ Write-Host "`nCredential-Access Analysis Complete!" -ForegroundColor Green
+ Write-Host "`n=== Summary ===" -ForegroundColor Cyan
+ Write-Host "RC4 service ticket requests: $($results.Summary.RC4ServiceTicketRequests)" -ForegroundColor Yellow
+ Write-Host "Kerberoast bursts (>5 RC4 tickets per account): $($results.Summary.KerberoastBursts)" -ForegroundColor $(if ($results.Summary.KerberoastBursts -gt 0) { 'Red' } else { 'Green' })
+ Write-Host "TGT request anomalies: $($results.Summary.TGTAnomalies)" -ForegroundColor $(if ($results.Summary.TGTAnomalies -gt 0) { 'Yellow' } else { 'Green' })
+ Write-Host "Kerberos failure spikes: $($results.Summary.KerberosFailureSpikes)" -ForegroundColor $(if ($results.Summary.KerberosFailureSpikes -gt 0) { 'Red' } else { 'Green' })
+ Write-Host "Golden-ticket heuristic hits: $($results.Summary.GoldenTicketHeuristics)" -ForegroundColor $(if ($results.Summary.GoldenTicketHeuristics -gt 0) { 'Yellow' } else { 'Green' })
+
+ if ($IncludeLSASSAccess) {
+ Write-Host "LSASS access events flagged: $($results.Summary.LSASSAccessEvents)" -ForegroundColor Yellow
+ Write-Host "Suspicious LSASS access: $($results.Summary.SuspiciousLSASSAccess)" -ForegroundColor $(if ($results.Summary.SuspiciousLSASSAccess -gt 0) { 'Red' } else { 'Green' })
+ }
+
+ if (@($results.Recommendations).Count -gt 0) {
+ Write-Host "`n=== Recommendations ===" -ForegroundColor Cyan
+ foreach ($recommendation in $results.Recommendations) {
+ Write-Host "- $recommendation" -ForegroundColor Yellow
+ }
+ }
+
+ return $results
+ }
+}
diff --git a/Forensics/Get-ArtifactCollection.ps1 b/Forensics/Get-ArtifactCollection.ps1
index b1e41fc..1689d5a 100644
--- a/Forensics/Get-ArtifactCollection.ps1
+++ b/Forensics/Get-ArtifactCollection.ps1
@@ -77,7 +77,14 @@ function Get-ArtifactCollection {
if (-not $isAdmin) {
Write-Warning "Administrator privileges recommended for complete collection!"
}
-
+
+ $acquisitionStartUtc = [DateTime]::UtcNow
+
+ $moduleVersion = 'Unknown'
+ if ($null -ne $MyInvocation.MyCommand.Module -and $null -ne $MyInvocation.MyCommand.Module.Version) {
+ $moduleVersion = $MyInvocation.MyCommand.Module.Version.ToString()
+ }
+
# Set collection flags based on profile
switch ($CollectionProfile) {
'Quick' {
@@ -215,42 +222,39 @@ function Get-ArtifactCollection {
# 3. COLLECT REGISTRY ARTIFACTS
if ($IncludeRegistry) {
Write-Host "`n[3/8] Collecting Registry Artifacts..." -ForegroundColor Cyan
-
+
try {
- # Export key registry hives
- $registryKeys = @(
- @{Path='HKLM:\SOFTWARE'; Name='SOFTWARE'},
- @{Path='HKLM:\SYSTEM'; Name='SYSTEM'},
- @{Path='HKLM:\SAM'; Name='SAM'},
- @{Path='HKLM:\SECURITY'; Name='SECURITY'},
- @{Path='HKCU:\'; Name='NTUSER'}
+ # Save raw registry hives (reg save preserves the binary hive
+ # format, unlike reg export which produces lossy text).
+ # reg save requires elevation (SeBackupPrivilege).
+ $registryHives = @(
+ @{RegPath='HKLM\SOFTWARE'; Name='HKLM_SOFTWARE.hiv'},
+ @{RegPath='HKLM\SYSTEM'; Name='HKLM_SYSTEM.hiv'},
+ @{RegPath='HKLM\SAM'; Name='HKLM_SAM.hiv'},
+ @{RegPath='HKLM\SECURITY'; Name='HKLM_SECURITY.hiv'},
+ @{RegPath='HKCU'; Name='HKCU_NTUSER.hiv'}
)
-
- foreach ($key in $registryKeys) {
+
+ foreach ($hive in $registryHives) {
try {
- Write-Host " Exporting: $($key.Name)..." -ForegroundColor Gray
-
- $exportPath = Join-Path $paths.Registry "$($key.Name).reg"
-
- # Export using reg.exe
- if ($key.Path -like 'HKLM*') {
- $regPath = $key.Path -replace 'HKLM:\\', 'HKLM\'
- reg export $regPath $exportPath /y 2>&1 | Out-Null
+ Write-Host " Saving hive: $($hive.RegPath)..." -ForegroundColor Gray
+
+ $savePath = Join-Path $paths.Registry $hive.Name
+
+ $regOutput = reg save $hive.RegPath $savePath /y 2>&1
+
+ if (Test-Path $savePath) {
+ Write-Host " Saved successfully" -ForegroundColor Green
}
- elseif ($key.Path -like 'HKCU*') {
- $regPath = $key.Path -replace 'HKCU:\\', 'HKCU\'
- reg export $regPath $exportPath /y 2>&1 | Out-Null
- }
-
- if (Test-Path $exportPath) {
- Write-Host " Exported successfully" -ForegroundColor Green
+ else {
+ Write-Warning "Could not save registry hive $($hive.RegPath) (elevation required) - $regOutput"
}
}
catch {
- Write-Warning "Could not export registry key: $($key.Name)"
+ Write-Warning "Could not save registry hive: $($hive.RegPath) - $_"
}
}
-
+
$results.ArtifactsCollected += "Registry Hives"
}
catch {
@@ -432,10 +436,32 @@ function Get-ArtifactCollection {
# CALCULATE COLLECTION SIZE
Write-Host "`n[*] Calculating collection statistics..." -ForegroundColor Cyan
-
+
$collectedFiles = @(Get-ChildItem -Path $collectionRoot -Recurse -File -ErrorAction SilentlyContinue)
$results.Summary.TotalFiles = $collectedFiles.Count
$results.Summary.TotalSize = ($collectedFiles | Measure-Object -Property Length -Sum).Sum
+
+ # EVIDENCE INTEGRITY: SHA256 hash for every collected file
+ Write-Host "`n[*] Hashing collected files (SHA256)..." -ForegroundColor Cyan
+
+ $fileManifest = @()
+ foreach ($collectedFile in $collectedFiles) {
+ $sha256Hash = $null
+ try {
+ $sha256Hash = (Get-FileHash -Path $collectedFile.FullName -Algorithm SHA256 -ErrorAction Stop).Hash
+ }
+ catch {
+ Write-Verbose "Could not hash file: $($collectedFile.FullName) - $_"
+ }
+
+ $fileManifest += [PSCustomObject]@{
+ Path = $collectedFile.FullName.Substring($collectionRoot.Length).TrimStart('\', '/')
+ SizeBytes = $collectedFile.Length
+ SHA256 = $sha256Hash
+ }
+ }
+
+ Write-Host " Hashed $(@($fileManifest | Where-Object { $null -ne $_.SHA256 }).Count) of $($collectedFiles.Count) files" -ForegroundColor Green
$totalSizeMB = [Math]::Round($results.Summary.TotalSize / 1MB, 2)
Write-Host " Total Files: $($results.Summary.TotalFiles)" -ForegroundColor Green
@@ -451,6 +477,15 @@ function Get-ArtifactCollection {
TotalFiles = $results.Summary.TotalFiles
TotalSizeMB = $totalSizeMB
Errors = $results.Summary.Errors
+ AcquisitionLog = @{
+ Tool = 'WindowsSecurityAudit'
+ ToolVersion = $moduleVersion
+ Operator = $env:USERNAME
+ Hostname = $env:COMPUTERNAME
+ StartTimeUtc = $acquisitionStartUtc.ToString('o')
+ EndTimeUtc = ([DateTime]::UtcNow).ToString('o')
+ }
+ Files = $fileManifest
}
$manifest | ConvertTo-Json -Depth 5 | Out-File (Join-Path $collectionRoot "MANIFEST.json")
@@ -521,7 +556,7 @@ function Get-ArtifactCollection {
Write-Host " 1. Review MANIFEST.json for collection details" -ForegroundColor Gray
Write-Host " 2. Analyze collected artifacts with forensic tools" -ForegroundColor Gray
Write-Host " 3. Store evidence securely with chain of custody" -ForegroundColor Gray
- Write-Host " 4. Calculate file hash for integrity verification" -ForegroundColor Gray
+ Write-Host " 4. Verify evidence integrity with the SHA256 hashes in MANIFEST.json" -ForegroundColor Gray
return $results
}
diff --git a/Forensics/Get-UserActivityArtifacts.ps1 b/Forensics/Get-UserActivityArtifacts.ps1
new file mode 100644
index 0000000..5c586de
--- /dev/null
+++ b/Forensics/Get-UserActivityArtifacts.ps1
@@ -0,0 +1,439 @@
+function Get-UserActivityArtifacts {
+ <#
+ .SYNOPSIS
+ Collects user activity forensic artifacts from Windows user profiles
+ .DESCRIPTION
+ Gathers per-user activity evidence for DFIR investigations:
+ - Recycle Bin $I metadata files (header version 2 / Windows 10+): decodes
+ original path, file size, and deletion time (FILETIME UTC). Version 1
+ headers are decoded best-effort. Unknown versions or malformed headers
+ are skipped with Verbose output.
+ - Recent + Desktop LNK shortcuts: resolves target path, arguments, and
+ working directory via WScript.Shell COM (per-file try/catch; targets
+ are reported as unresolved off-Windows or when COM is unavailable).
+ - JumpLists: enumerates AutomaticDestinations files with timestamps only.
+ Embedded targets are NOT parsed - this is enumeration, labeled as such.
+ - Windows Timeline (ActivitiesCache.db): copies the database with a raw
+ FileStream (FileShare.ReadWrite fallback for locked files) and reports
+ size/mtime only. No SQLite parsing is performed (no dependency).
+ MITRE ATT&CK references are heuristic mappings, not assertions.
+ .PARAMETER UserProfile
+ One or more user profile paths (default: all profiles under C:\Users)
+ .PARAMETER RecycleBinRoot
+ Root of the Recycle Bin to scan for $I files (default: C:\$Recycle.Bin)
+ .PARAMETER OutputPath
+ Optional directory for CSV export (RecycleBin.csv, RecentLinks.csv,
+ JumpLists.csv, Timeline.csv) and Timeline database copies
+ .EXAMPLE
+ Get-UserActivityArtifacts
+ Get-UserActivityArtifacts -UserProfile "C:\Users\jdoe" -OutputPath "E:\Evidence\UserActivity"
+ .OUTPUTS
+ PSCustomObject with RecycleBin, RecentLinks, JumpLists, Timeline and Summary
+ #>
+
+ [CmdletBinding()]
+ param(
+ [Parameter()]
+ [string[]]$UserProfile,
+
+ [Parameter()]
+ [string]$RecycleBinRoot = 'C:\$Recycle.Bin',
+
+ [Parameter()]
+ [string]$OutputPath
+ )
+
+ begin {
+ Write-Host "=== USER ACTIVITY ARTIFACTS ===" -ForegroundColor Cyan
+ Write-Host "Scan Date: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow
+
+ $results = [PSCustomObject]@{
+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
+ ComputerName = $env:COMPUTERNAME
+ ProfilesAnalyzed = @()
+ RecycleBin = @()
+ RecentLinks = @()
+ JumpLists = @()
+ Timeline = @()
+ Summary = @{
+ ProfilesAnalyzed = 0
+ RecycleBinEntries = 0
+ RecentLinks = 0
+ ResolvedLinks = 0
+ JumpListFiles = 0
+ TimelineDatabases = 0
+ Errors = 0
+ }
+ }
+
+ # Resolve target profiles
+ $profiles = @()
+ if ($UserProfile) {
+ foreach ($profile in $UserProfile) {
+ if (Test-Path $profile -PathType Container) {
+ $profiles += (Get-Item $profile).FullName
+ }
+ else {
+ Write-Warning "User profile not found: $profile"
+ }
+ }
+ }
+ else {
+ if (Test-Path 'C:\Users' -PathType Container) {
+ $profiles = @(Get-ChildItem 'C:\Users' -Directory -ErrorAction SilentlyContinue |
+ Select-Object -ExpandProperty FullName)
+ }
+ else {
+ Write-Verbose "Default profile root C:\Users not found - no profiles to analyze"
+ }
+ }
+
+ # WScript.Shell COM for LNK resolution (Windows only)
+ $shellCom = $null
+ $lnkResolutionAvailable = $false
+ try {
+ $shellCom = New-Object -ComObject WScript.Shell -ErrorAction Stop
+ $lnkResolutionAvailable = $true
+ }
+ catch {
+ Write-Verbose "WScript.Shell COM unavailable (non-Windows host or restricted) - LNK targets will be reported as unresolved"
+ }
+
+ function Read-RecycleBinMetadata {
+ param([string]$Path)
+
+ $stream = $null
+ $reader = $null
+ try {
+ $stream = New-Object System.IO.FileStream($Path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)
+ if ($stream.Length -lt 24) {
+ Write-Verbose "Skipping $Path - file too small for an `$I header ($($stream.Length) bytes)"
+ return
+ }
+
+ $reader = New-Object System.IO.BinaryReader($stream)
+ $headerVersion = $reader.ReadInt64()
+ $fileSizeBytes = $reader.ReadInt64()
+ $deletionFileTime = $reader.ReadInt64()
+
+ $originalPath = $null
+ if ($headerVersion -eq 2) {
+ if ($stream.Length -lt 28) {
+ Write-Verbose "Skipping $Path - truncated version 2 header"
+ return
+ }
+ $pathCharCount = $reader.ReadInt32()
+ if ($pathCharCount -le 0 -or $pathCharCount -gt 32767) {
+ Write-Verbose "Skipping $Path - implausible path length $pathCharCount in version 2 header"
+ return
+ }
+ $pathBytes = $reader.ReadBytes($pathCharCount * 2)
+ if ($pathBytes.Length -lt ($pathCharCount * 2)) {
+ Write-Verbose "Skipping $Path - truncated path data in version 2 header"
+ return
+ }
+ $originalPath = [System.Text.Encoding]::Unicode.GetString($pathBytes).TrimEnd([char]0)
+ }
+ elseif ($headerVersion -eq 1) {
+ if ($stream.Length -lt 544) {
+ Write-Verbose "Skipping $Path - truncated version 1 header"
+ return
+ }
+ $pathBytes = $reader.ReadBytes(520)
+ $rawPath = [System.Text.Encoding]::Unicode.GetString($pathBytes)
+ $nullIndex = $rawPath.IndexOf([char]0)
+ if ($nullIndex -ge 0) {
+ $originalPath = $rawPath.Substring(0, $nullIndex)
+ }
+ else {
+ $originalPath = $rawPath
+ }
+ }
+ else {
+ Write-Verbose "Skipping $Path - unsupported `$I header version $headerVersion"
+ return
+ }
+
+ $deletionTimeUtc = $null
+ try {
+ $deletionTimeUtc = [DateTime]::FromFileTimeUtc($deletionFileTime)
+ }
+ catch {
+ Write-Verbose "Skipping deletion time in $Path - invalid FILETIME value $deletionFileTime"
+ }
+
+ return [PSCustomObject]@{
+ OriginalPath = $originalPath
+ FileSizeBytes = $fileSizeBytes
+ DeletionTimeUtc = $deletionTimeUtc
+ HeaderVersion = $headerVersion
+ }
+ }
+ catch {
+ Write-Verbose "Could not parse $Path - $_"
+ return
+ }
+ finally {
+ if ($null -ne $reader) { $reader.Dispose() }
+ if ($null -ne $stream) { $stream.Dispose() }
+ }
+ }
+ }
+
+ process {
+ try {
+ # 1. RECYCLE BIN $I FILES (system-wide, tagged by owner SID folder)
+ Write-Host "`n[1/4] Parsing Recycle Bin `$I metadata files..." -ForegroundColor Cyan
+
+ try {
+ if (Test-Path $RecycleBinRoot -PathType Container) {
+ $sidFolders = @(Get-ChildItem -Path $RecycleBinRoot -Directory -Force -ErrorAction SilentlyContinue)
+ $iFiles = @()
+ foreach ($sidFolder in $sidFolders) {
+ $iFiles += @(Get-ChildItem -Path $sidFolder.FullName -Filter '$I*' -File -Force -ErrorAction SilentlyContinue |
+ ForEach-Object { [PSCustomObject]@{ File = $_; OwnerSid = $sidFolder.Name } })
+ }
+
+ foreach ($entry in $iFiles) {
+ $metadata = Read-RecycleBinMetadata -Path $entry.File.FullName
+ if ($null -eq $metadata) {
+ continue
+ }
+
+ $results.RecycleBin += [PSCustomObject]@{
+ MetadataFile = $entry.File.FullName
+ OwnerSid = $entry.OwnerSid
+ OriginalPath = $metadata.OriginalPath
+ FileSizeBytes = $metadata.FileSizeBytes
+ DeletionTimeUtc = $metadata.DeletionTimeUtc
+ HeaderVersion = $metadata.HeaderVersion
+ MitreAttack = 'T1074.001 (heuristic - locally staged/deleted data)'
+ }
+ }
+
+ Write-Host " Decoded $(@($results.RecycleBin).Count) `$I files ($($iFiles.Count) found)" -ForegroundColor Green
+ }
+ else {
+ Write-Host " Recycle Bin root not found: $RecycleBinRoot" -ForegroundColor Gray
+ }
+ }
+ catch {
+ Write-Warning "Error parsing Recycle Bin artifacts - $_"
+ $results.Summary.Errors++
+ }
+
+ # 2. RECENT + DESKTOP LNK SHORTCUTS
+ Write-Host "`n[2/4] Analyzing Recent and Desktop shortcuts..." -ForegroundColor Cyan
+
+ foreach ($profile in $profiles) {
+ try {
+ $lnkLocations = @(
+ (Join-Path $profile 'AppData\Roaming\Microsoft\Windows\Recent'),
+ (Join-Path $profile 'Desktop')
+ )
+
+ foreach ($location in $lnkLocations) {
+ if (-not (Test-Path $location -PathType Container)) {
+ continue
+ }
+
+ $lnkFiles = @(Get-ChildItem -Path $location -Filter '*.lnk' -File -Force -ErrorAction SilentlyContinue)
+
+ foreach ($lnkFile in $lnkFiles) {
+ $targetPath = $null
+ $targetArguments = $null
+ $workingDirectory = $null
+ $resolved = $false
+
+ if ($lnkResolutionAvailable) {
+ try {
+ $shortcut = $shellCom.CreateShortcut($lnkFile.FullName)
+ if ($null -ne $shortcut) {
+ if ($shortcut.PSObject.Properties['TargetPath']) { $targetPath = $shortcut.TargetPath }
+ if ($shortcut.PSObject.Properties['Arguments']) { $targetArguments = $shortcut.Arguments }
+ if ($shortcut.PSObject.Properties['WorkingDirectory']) { $workingDirectory = $shortcut.WorkingDirectory }
+ }
+ if (-not [string]::IsNullOrEmpty($targetPath)) {
+ $resolved = $true
+ }
+ }
+ catch {
+ Write-Verbose "Could not resolve shortcut $($lnkFile.FullName) - $_"
+ }
+ }
+
+ $results.RecentLinks += [PSCustomObject]@{
+ Profile = $profile
+ Location = $(if ($location -like '*\Recent') { 'Recent' } else { 'Desktop' })
+ LinkFile = $lnkFile.FullName
+ LinkLastWriteTime = $lnkFile.LastWriteTime
+ TargetPath = $targetPath
+ TargetArguments = $targetArguments
+ WorkingDirectory = $workingDirectory
+ Resolved = $resolved
+ ResolutionMethod = $(if ($lnkResolutionAvailable) { 'WScript.Shell COM' } else { 'Unavailable (COM not present)' })
+ MitreAttack = 'T1547 (heuristic - shortcut-based persistence indicator)'
+ }
+ }
+ }
+ }
+ catch {
+ Write-Warning "Error analyzing shortcuts for profile $profile - $_"
+ $results.Summary.Errors++
+ }
+ }
+
+ $results.Summary.RecentLinks = @($results.RecentLinks).Count
+ $results.Summary.ResolvedLinks = @($results.RecentLinks | Where-Object { $_.Resolved }).Count
+ Write-Host " Processed $($results.Summary.RecentLinks) shortcuts ($($results.Summary.ResolvedLinks) resolved)" -ForegroundColor Green
+
+ # 3. JUMPLISTS (AutomaticDestinations enumeration only)
+ Write-Host "`n[3/4] Enumerating JumpList files..." -ForegroundColor Cyan
+
+ foreach ($profile in $profiles) {
+ try {
+ $jumpListPath = Join-Path $profile 'AppData\Roaming\Microsoft\Windows\Recent\AutomaticDestinations'
+
+ if (Test-Path $jumpListPath -PathType Container) {
+ $jumpListFiles = @(Get-ChildItem -Path $jumpListPath -Filter '*.automaticDestinations-ms' -File -Force -ErrorAction SilentlyContinue)
+
+ foreach ($jumpListFile in $jumpListFiles) {
+ $results.JumpLists += [PSCustomObject]@{
+ Profile = $profile
+ JumpListFile = $jumpListFile.FullName
+ AppId = $jumpListFile.BaseName
+ SizeBytes = $jumpListFile.Length
+ LastWriteTime = $jumpListFile.LastWriteTime
+ Note = 'Enumeration only - embedded JumpList targets not parsed'
+ MitreAttack = 'T1074.001 (heuristic - user file interaction evidence)'
+ }
+ }
+ }
+ }
+ catch {
+ Write-Warning "Error enumerating JumpLists for profile $profile - $_"
+ $results.Summary.Errors++
+ }
+ }
+
+ $results.Summary.JumpListFiles = @($results.JumpLists).Count
+ Write-Host " Found $($results.Summary.JumpListFiles) JumpList files" -ForegroundColor Green
+
+ # 4. WINDOWS TIMELINE (ActivitiesCache.db copy, size/mtime only)
+ Write-Host "`n[4/4] Collecting Windows Timeline databases..." -ForegroundColor Cyan
+
+ foreach ($profile in $profiles) {
+ try {
+ $timelineRoot = Join-Path $profile 'AppData\Local\ConnectedDevicesPlatform'
+
+ if (Test-Path $timelineRoot -PathType Container) {
+ $timelineDbs = @(Get-ChildItem -Path $timelineRoot -Filter 'ActivitiesCache.db' -File -Recurse -Force -ErrorAction SilentlyContinue)
+
+ foreach ($db in $timelineDbs) {
+ $copiedTo = $null
+ $copySucceeded = $false
+ $copyNote = 'Not copied (no OutputPath specified)'
+
+ if ($OutputPath) {
+ $timelineCopyDir = Join-Path $OutputPath 'TimelineCopies'
+ if (-not (Test-Path $timelineCopyDir -PathType Container)) {
+ New-Item -Path $timelineCopyDir -ItemType Directory -Force | Out-Null
+ }
+
+ $profileName = Split-Path $profile -Leaf
+ $destFile = Join-Path $timelineCopyDir "$($profileName)_$($db.Directory.Name)_ActivitiesCache.db"
+
+ $sourceStream = $null
+ $destStream = $null
+ try {
+ # Raw FileStream copy with ReadWrite share to handle locked database
+ $sourceStream = New-Object System.IO.FileStream($db.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [System.IO.FileShare]::ReadWrite)
+ $destStream = New-Object System.IO.FileStream($destFile, [System.IO.FileMode]::Create, [System.IO.FileAccess]::Write, [System.IO.FileShare]::None)
+ $sourceStream.CopyTo($destStream)
+ $copiedTo = $destFile
+ $copySucceeded = $true
+ $copyNote = 'Copied via raw FileStream (FileShare.ReadWrite)'
+ }
+ catch {
+ Write-Warning "ActivitiesCache.db locked or unreadable - skipping copy: $($db.FullName)"
+ $copyNote = "Copy failed (locked or unreadable): $_"
+ }
+ finally {
+ if ($null -ne $destStream) { $destStream.Dispose() }
+ if ($null -ne $sourceStream) { $sourceStream.Dispose() }
+ }
+ }
+
+ $results.Timeline += [PSCustomObject]@{
+ Profile = $profile
+ DatabasePath = $db.FullName
+ SizeBytes = $db.Length
+ LastWriteTime = $db.LastWriteTime
+ CopiedTo = $copiedTo
+ CopySucceeded = $copySucceeded
+ Note = "Raw copy and metadata only - SQLite parsing not performed (no dependency). $copyNote"
+ MitreAttack = 'T1074.001 (heuristic - user activity timeline evidence)'
+ }
+ }
+ }
+ }
+ catch {
+ Write-Warning "Error collecting Timeline for profile $profile - $_"
+ $results.Summary.Errors++
+ }
+ }
+
+ $results.Summary.TimelineDatabases = @($results.Timeline).Count
+ Write-Host " Found $($results.Summary.TimelineDatabases) Timeline databases" -ForegroundColor Green
+ }
+ catch {
+ Write-Error "Error during user activity artifact collection: $_"
+ throw
+ }
+ }
+
+ end {
+ $results.ProfilesAnalyzed = @($profiles)
+ $results.Summary.ProfilesAnalyzed = @($profiles).Count
+ $results.Summary.RecycleBinEntries = @($results.RecycleBin).Count
+
+ # CSV export
+ if ($OutputPath) {
+ try {
+ if (-not (Test-Path $OutputPath -PathType Container)) {
+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null
+ }
+
+ if (@($results.RecycleBin).Count -gt 0) {
+ $results.RecycleBin | Export-Csv -Path (Join-Path $OutputPath 'RecycleBin.csv') -NoTypeInformation
+ }
+ if (@($results.RecentLinks).Count -gt 0) {
+ $results.RecentLinks | Export-Csv -Path (Join-Path $OutputPath 'RecentLinks.csv') -NoTypeInformation
+ }
+ if (@($results.JumpLists).Count -gt 0) {
+ $results.JumpLists | Export-Csv -Path (Join-Path $OutputPath 'JumpLists.csv') -NoTypeInformation
+ }
+ if (@($results.Timeline).Count -gt 0) {
+ $results.Timeline | Export-Csv -Path (Join-Path $OutputPath 'Timeline.csv') -NoTypeInformation
+ }
+
+ Write-Host "`nCSV exports written to: $OutputPath" -ForegroundColor Green
+ }
+ catch {
+ Write-Warning "Could not export CSV files to $OutputPath - $_"
+ }
+ }
+
+ Write-Host "`n========================================" -ForegroundColor Green
+ Write-Host " USER ACTIVITY ANALYSIS COMPLETE" -ForegroundColor Green
+ Write-Host "========================================" -ForegroundColor Green
+ Write-Host " Profiles analyzed: $($results.Summary.ProfilesAnalyzed)" -ForegroundColor White
+ Write-Host " Recycle Bin entries: $($results.Summary.RecycleBinEntries)" -ForegroundColor White
+ Write-Host " Recent/Desktop links: $($results.Summary.RecentLinks) ($($results.Summary.ResolvedLinks) resolved)" -ForegroundColor White
+ Write-Host " JumpList files: $($results.Summary.JumpListFiles)" -ForegroundColor White
+ Write-Host " Timeline databases: $($results.Summary.TimelineDatabases)" -ForegroundColor White
+ Write-Host " Errors: $($results.Summary.Errors)" -ForegroundColor $(if($results.Summary.Errors -gt 0){'Yellow'}else{'White'})
+
+ return $results
+ }
+}
diff --git a/README.md b/README.md
index d6d4bdf..3f15e74 100644
--- a/README.md
+++ b/README.md
@@ -5,11 +5,11 @@
[![PowerShell](https://img.shields.io/badge/PowerShell-5.1%2B-blue.svg)](https://github.com/PowerShell/PowerShell)
[![Windows](https://img.shields.io/badge/Windows-10%2F11%2FServer%202016%2B-blue.svg)](https://www.microsoft.com/windows)
[![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
-[![Version](https://img.shields.io/badge/Version-1.3.0-orange.svg)](https://github.com/okanyildiz/WindowsSecurityAudit/releases)
-[![Functions](https://img.shields.io/badge/Functions-65-brightgreen.svg)](https://github.com/okanyildiz/WindowsSecurityAudit)
+[![Version](https://img.shields.io/badge/Version-1.4.0-orange.svg)](https://github.com/okanyildiz/WindowsSecurityAudit/releases)
+[![Functions](https://img.shields.io/badge/Functions-69-brightgreen.svg)](https://github.com/okanyildiz/WindowsSecurityAudit)
[![Modules](https://img.shields.io/badge/Modules-14-blue.svg)](https://github.com/okanyildiz/WindowsSecurityAudit)
[![CI](https://github.com/okanyildiz/WindowsSecurityAudit/actions/workflows/ci.yml/badge.svg)](https://github.com/okanyildiz/WindowsSecurityAudit/actions/workflows/ci.yml)
-[![Tests](https://img.shields.io/badge/Tests-353%20Passed-brightgreen.svg)](https://github.com/okanyildiz/WindowsSecurityAudit/blob/main/tests/WindowsSecurityAudit.Tests.ps1)
+[![Tests](https://img.shields.io/badge/Tests-385%20Passed-brightgreen.svg)](https://github.com/okanyildiz/WindowsSecurityAudit/blob/main/tests/WindowsSecurityAudit.Tests.ps1)
[![GitHub stars](https://img.shields.io/github/stars/okanyildiz/WindowsSecurityAudit)](https://github.com/okanyildiz/WindowsSecurityAudit/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/okanyildiz/WindowsSecurityAudit)](https://github.com/okanyildiz/WindowsSecurityAudit/network/members)
@@ -27,14 +27,14 @@
## 🧰 Full Feature Overview
-**65 functions across 14 modules** — the complete toolkit at a glance:
+**69 functions across 14 modules** — the complete toolkit at a glance:
| Module | Functions | Scope |
|--------|:---------:|-------|
| 🧱 **Core Security** | 5 | Security baseline scoring (0-100), system inventory, SFC/DISM integrity checks, Event ID context, baseline drift diffing |
-| 🕵️ **Detection** | 4 | Persistence mechanisms, suspicious processes, network anomalies, authentication attacks |
+| 🕵️ **Detection** | 6 | Persistence mechanisms, suspicious processes, network anomalies, authentication attacks, credential-access events (Kerberoasting/spray/golden-ticket heuristic), defense-evasion & tamper detection |
| 🔬 **Analysis** | 4 | Deep-dive analysis of event logs, registry, process memory, and file system |
-| 🚨 **Response** | 3 | Incident response orchestration, forensic evidence collection, HTML/JSON/CSV report export |
+| 🚨 **Response** | 4 | Incident response orchestration, forensic evidence collection, HTML/JSON/CSV/NDJSON/CEF report export, SIEM event conversion |
| 🏢 **Enterprise** | 4 | Multi-system parallel scanning, full assessment orchestration, scheduled scans with Teams/Slack/email alerts |
| 🔒 **Hardening** | 4 | Audit policies, PowerShell security, baseline enforcement, curated auto-remediation (WhatIf-first, with rollback) |
| 🛡️ **Windows Defender** | 3 | Defender health monitoring, custom scans, configuration optimization |
@@ -42,7 +42,7 @@
| ✅ **Compliance** | 5 | CIS Benchmark, NIST 800-53, PCI-DSS 4.0 validation, compliance reports, audit evidence export |
| 🌳 **Active Directory** | 6 | AD backdoors & DCSync detection, vulnerability scan, stale objects, password policies, privileged accounts, posture |
| 🩹 **Vulnerability** | 8 | CVE assessment (real NVD data + version-exact CPE matching), EOL software, exposed services, certificates, patches |
-| 🔍 **Forensics** | 5 | Memory dumps, artifact collection, execution artifacts (prefetch/UserAssist/BAM), USB history, forensic timelines |
+| 🔍 **Forensics** | 6 | Memory dumps, artifact collection with SHA256-at-acquisition, execution artifacts (prefetch/UserAssist/BAM), USB history, user activity artifacts (Recycle Bin/LNK/JumpLists/Timeline), forensic timelines |
| ☁️ **Cloud Security** | 3 | Azure AD risky sign-ins, M365 security posture, cloud compliance status |
| 📊 **Reporting** | 4 | Security metrics/KPIs, executive reports, live HTML dashboards, consolidated all-module Chart.js report |
@@ -69,7 +69,7 @@ If you find this tool valuable for your security operations, consider supporting
In 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 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.
+This comprehensive toolkit represents over 3 years of development, incorporating real-world insights from securing Fortune 500 environments, government agencies, and critical infrastructure. With 69 meticulously crafted functions organized into 14 specialized modules, it delivers capabilities typically found only in solutions costing $50,000+ annually - completely free and open source.
### 🎯 The Vision
@@ -119,7 +119,7 @@ A single, cohesive PowerShell module that consolidates essential security functi
</tr>
<tr>
<td><strong>Functions</strong></td>
-<td>✅ 65 Comprehensive</td>
+<td>✅ 69 Comprehensive</td>
<td>⚠️ 20-30 Limited</td>
<td>⚠️ 5-15 Basic</td>
</tr>
@@ -166,9 +166,12 @@ WindowsSecurityAudit/
├── 📄 WindowsSecurityAudit.psm1 # Module loader
├── 📄 CreateProjectFolderStructure.ps1 # Setup script
├── 📄 Test-Module.ps1 # Testing script
+├── 📄 CHANGELOG.md # Version history
+├── 📄 SECURITY.md # Security policy & disclosure
│
-├── 📁 .github/workflows/ # CI: PSScriptAnalyzer + Pester (PS 5.1 & 7)
-│ └── ci.yml
+├── 📁 .github/workflows/ # CI: PSScriptAnalyzer + Pester (PS 5.1 & 7); release: gallery publish
+│ ├── ci.yml
+│ └── publish.yml
│
├── 📁 ActiveDirectory/ # AD Security (6 functions)
│ ├── Find-ADBackdoors.ps1
@@ -203,11 +206,13 @@ WindowsSecurityAudit/
│ ├── Get-SystemInfo.ps1
│ └── Test-SystemIntegrity.ps1
│
-├── 📁 Detection/ # Threat Detection (4 functions)
+├── 📁 Detection/ # Threat Detection (6 functions)
+│ ├── Find-DefenseEvasion.ps1
│ ├── Find-NetworkAnomalies.ps1
│ ├── Find-PersistenceMechanisms.ps1
│ ├── Find-SuspiciousAuthentication.ps1
-│ └── Find-SuspiciousProcesses.ps1
+│ ├── Find-SuspiciousProcesses.ps1
+│ └── Get-CredentialAccessEvents.ps1
│
├── 📁 Enterprise/ # Enterprise (4 functions)
│ ├── Get-MultiSystemAudit.ps1
@@ -215,11 +220,12 @@ WindowsSecurityAudit/
│ ├── Invoke-SecurityAssessment.ps1
│ └── Register-ScheduledSecurityScan.ps1
│
-├── 📁 Forensics/ # Digital Forensics (5 functions)
+├── 📁 Forensics/ # Digital Forensics (6 functions)
│ ├── Export-MemoryDump.ps1
│ ├── Get-ArtifactCollection.ps1
│ ├── Get-ExecutionArtifacts.ps1
│ ├── Get-USBHistory.ps1
+│ ├── Get-UserActivityArtifacts.ps1
│ └── New-ForensicTimeline.ps1
│
├── 📁 Hardening/ # Security Hardening (4 functions)
@@ -236,12 +242,13 @@ WindowsSecurityAudit/
│ ├── New-ExecutiveReport.ps1
│ └── New-SecurityDashboard.ps1
│
-├── 📁 Response/ # Incident Response (3 functions)
+├── 📁 Response/ # Incident Response (4 functions)
+│ ├── ConvertTo-SiemEvent.ps1
│ ├── Export-SecurityReport.ps1
│ ├── Invoke-ForensicCollection.ps1
│ └── Invoke-IncidentResponse.ps1
│
-├── 📁 tests/ # Pester tests (353 tests)
+├── 📁 tests/ # Pester tests (385 tests)
│ └── WindowsSecurityAudit.Tests.ps1
│
├── 📁 ThreatHunting/ # Threat Hunting (7 functions)
@@ -308,7 +315,7 @@ Import-Module ".\WindowsSecurityAudit.psd1" -Force
# Or run the smoke test
.\Test-Module.ps1
-# Verify installation - should return 65
+# Verify installation - should return 69
(Get-Command -Module WindowsSecurityAudit).Count
```
@@ -433,6 +440,21 @@ Invoke-SecurityAssessment -OutputPath "C:\Assessments"
Invoke-SecurityRemediation -AssessmentPath "C:\Assessments\SecurityAssessment.json" -GenerateRollback -WhatIf
```
+### SIEM & Evasion Hunting (New in v1.4.0)
+```powershell
+# Detect AMSI/ETW tampering, Defender tampering, and cleared logs;
+# include heuristic log-gap analysis across major logs
+Find-DefenseEvasion -IncludeLogGapAnalysis
+
+# Hunt Kerberoasting, password spray, and golden-ticket heuristics;
+# -IncludeLSASSAccess needs a SACL on lsass.exe (4663) or Sysmon 10
+Get-CredentialAccessEvents -IncludeLSASSAccess
+
+# Export findings as SIEM-ready NDJSON without opening a browser
+$report = Invoke-SecurityAssessment
+$report | Export-SecurityReport -Format NDJSON -NoAutoOpen
+```
+
### 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
@@ -471,7 +493,7 @@ The Core module serves as the foundation of the entire security assessment frame
---
-### 2️⃣ Detection Module (4 Functions)
+### 2️⃣ Detection Module (6 Functions)
The Detection module provides real-time threat identification capabilities using both signature-based and behavioral analysis techniques. These functions are designed to identify active threats, suspicious behaviors, and potential compromises that traditional antivirus might miss.
@@ -480,7 +502,9 @@ The Detection module provides real-time threat identification capabilities using
| **`Find-PersistenceMechanisms`** | Identifies malware persistence techniques across the system | • 11+ Registry autorun locations (Run, RunOnce, etc.)<br>• Scheduled Tasks (hidden, system, unusual)<br>• Windows Services (unsigned, suspicious paths)<br>• WMI Event Subscriptions<br>• Startup folders (all users, system) | High: Unknown entries<br>Medium: Unsigned binaries<br>Low: Unusual locations |
| **`Find-SuspiciousProcesses`** | Detects malicious process behaviors and anomalies | • Unsigned or invalid signatures<br>• Execution from temporary directories<br>• Encoded PowerShell commands<br>• Process injection indicators<br>• Unusual parent-child relationships<br>• Network connections to suspicious IPs | Critical: Known malware<br>High: Injection detected<br>Medium: Unsigned from temp |
| **`Find-NetworkAnomalies`** | Identifies abnormal network communications | • Connections to known C2 servers<br>• Non-standard port usage<br>• DNS tunneling indicators<br>• Large data transfers<br>• Tor/proxy connections<br>• Suspicious protocol usage | Critical: Known C2<br>High: DNS tunneling<br>Medium: Unusual ports |
-| **`Find-SuspiciousAuthentication`** | Detects authentication attacks and anomalies | • Brute force attempts (multiple failures)<br>• Account lockout patterns<br>• After-hours authentication<br>• Explicit-credential logons (runas / net use)<br>• Impossible travel scenarios<br>• Service account anomalies | High: Brute force<br>Medium: After hours<br>Low: Explicit credentials |
+| **`Find-SuspiciousAuthentication`** | Detects authentication attacks and anomalies | • Brute force attempts (multiple failures)<br>• Account lockout patterns<br>• After-hours authentication<br>• Explicit-credential logons (runas / net use, 4624 Type 9 NewCredentials)<br>• Per-account NTLM network logon indicators<br>• Impossible travel scenarios<br>• Service account anomalies | High: Brute force<br>Medium: After hours<br>Low: Explicit credentials |
+| **`Get-CredentialAccessEvents`** | Detects runtime credential-access activity from event logs | • Kerberoasting: RC4 service ticket bursts (4769)<br>• Anomalous TGT request volumes (4768)<br>• Kerberos pre-auth failure spikes / password spray (4771)<br>• Golden-ticket heuristic (Kerberos logon with no matching TGT; labeled Heuristic/Medium)<br>• Optional LSASS access handles (`-IncludeLSASSAccess`; 4663 needs a SACL, or Sysmon 10) | High: Kerberoast bursts, suspicious LSASS access<br>Medium: TGT anomalies, spray spikes, golden-ticket heuristic |
+| **`Find-DefenseEvasion`** | Detects defense-evasion and security-tampering activity | • AMSI bypass & ETW tamper patterns in script-block logs (4104)<br>• Defender exclusions and disabled real-time/behavior monitoring (Get-MpPreference)<br>• Defender tamper events (5001/5007)<br>• Log clearing (1102/104) and audit policy changes (4719) with clearing-account attribution<br>• Optional heuristic log-gap analysis (`-IncludeLogGapAnalysis`) | High: AMSI/ETW tamper, Defender tamper, cleared logs<br>Low: log gaps (heuristic) |
---
@@ -497,7 +521,7 @@ The Analysis module performs deep forensic examination of system components to u
---
-### 4️⃣ Response Module (3 Functions)
+### 4️⃣ Response Module (4 Functions)
The Response module provides automated incident response capabilities, enabling rapid containment of threats and systematic evidence collection. These functions follow industry-standard incident response procedures while maintaining forensic integrity.
@@ -505,7 +529,8 @@ The Response module provides automated incident response capabilities, enabling
|----------|---------|------------------|----------------|
| **`Invoke-IncidentResponse`** | Orchestrates automated incident response procedures | • Threat containment (process termination)<br>• System isolation (network disconnection)<br>• Evidence preservation<br>• User notification<br>• Backup initiation<br>• Recovery planning | Response timeline<br>Actions taken<br>System state<br>Threat indicators |
| **`Invoke-ForensicCollection`** | Systematically collects forensic evidence | • Memory dump acquisition<br>• Network state capture<br>• Registry snapshot<br>• Event log extraction<br>• File artifact collection<br>• Browser history preservation | Memory dumps<br>Network captures<br>System artifacts<br>User data |
-| **`Export-SecurityReport`** | Generates professional security reports | • HTML interactive dashboards<br>• JSON for SIEM integration<br>• CSV for data analysis | Multi-format reports<br>Executive summaries<br>Technical details<br>Recommendations |
+| **`Export-SecurityReport`** | Generates professional security reports | • HTML interactive dashboards<br>• JSON for SIEM integration<br>• CSV for data analysis<br>• NDJSON/CEF SIEM-ready exports (`-Format NDJSON/CEF`; `All` writes .ndjson + .cef too)<br>• `-NoAutoOpen` for headless/SYSTEM-context runs | Multi-format reports<br>Executive summaries<br>Technical details<br>Recommendations |
+| **`ConvertTo-SiemEvent`** | Converts findings into SIEM-ready event strings | • Pipeline conversion of findings to NDJSON (one compact JSON object per line) or CEF (`CEF:0` strings)<br>• Severity-to-number mapping and heuristic CEF `act` field<br>• MITRE technique ID passthrough when present<br>• `-HostName` / `-ProductVersion` stamping<br>• Splunk / Sentinel / QRadar / ArcSight ingestion ready | NDJSON lines<br>CEF strings |
---
@@ -609,14 +634,15 @@ The Vulnerability module identifies, assesses, and prioritizes security weakness
---
-### 1️⃣2️⃣ Forensics Module (5 Functions)
+### 1️⃣2️⃣ Forensics Module (6 Functions)
The Forensics module provides digital forensic capabilities for incident investigation, evidence collection, and timeline reconstruction while maintaining chain of custody and legal admissibility.
| Function | Purpose | Forensic Capabilities | Evidence Types |
|----------|---------|----------------------|----------------|
| **`Export-MemoryDump`** | Captures memory for analysis | • Full memory dump<br>• Process-specific dumps<br>• Minidump creation<br>• Crash dump analysis | RAM contents<br>Running processes<br>Network connections<br>Encryption keys |
-| **`Get-ArtifactCollection`** | Collects forensic artifacts | • Browser history (all browsers)<br>• Download history<br>• Temporary files<br>• Thumbnail cache | User activity<br>File access<br>Internet activity<br>Deleted items |
+| **`Get-ArtifactCollection`** | Collects forensic artifacts | • Browser history (all browsers)<br>• Download history<br>• Temporary files<br>• Thumbnail cache<br>• Per-file SHA256 computed at acquisition<br>• Raw registry hive capture via `reg save`<br>• AcquisitionLog manifest block | User activity<br>File access<br>Internet activity<br>Deleted items |
+| **`Get-UserActivityArtifacts`** | Collects per-user activity artifacts for DFIR | • Recycle Bin `$I` parsing (v2 + best-effort v1 headers; path, size, deletion FILETIME)<br>• Recent/Desktop LNK resolution via WScript.Shell COM (unresolved off-Windows)<br>• JumpList enumeration (AutomaticDestinations; embedded targets not parsed)<br>• ActivitiesCache.db raw copy (no SQLite parsing)<br>• Optional CSV export (`-OutputPath`) | Deleted files<br>Opened documents<br>App usage evidence<br>Timeline databases |
| **`Get-ExecutionArtifacts`** | Traces program execution | • Prefetch analysis<br>• ShimCache examination<br>• UserAssist decoding<br>• RecentDocs<br>• BAM/DAM analysis | Program execution<br>Timestamps<br>Frequency<br>User attribution |
| **`Get-USBHistory`** | USB device forensics | • Device enumeration<br>• First/Last connection<br>• Serial numbers<br>• Volume names<br>• Drive letters<br>• User correlation | Device usage<br>Data transfer<br>Timeline<br>User activity |
| **`New-ForensicTimeline`** | Timeline reconstruction | • Multi-source correlation<br>• Event sequencing<br>• File system timeline<br>• Registry timeline<br>• Log correlation<br>• Visual timeline generation | Incident timeline<br>Attack chain<br>User actions<br>System events |
@@ -652,7 +678,35 @@ The Reporting module transforms raw security data into actionable intelligence t
The full feature set is documented in the module tables above — this section only covers what changed per release, newest first:
-### 🆕 v1.3.0 — Version-Exact CVEs, MISP/TAXII & Auto-Remediation
+### 🆕 v1.4.0 — SIEM Integration, Credential & Evasion Detection, Forensic Integrity
+
+**4 new functions** — bringing the toolkit to **69 functions across 14 modules**:
+
+| Function | Module | What It Does |
+|----------|--------|--------------|
+| **`ConvertTo-SiemEvent`** | Response | Pipe findings straight into your SIEM: converts finding objects to **NDJSON** (one compact JSON object per line) or **CEF** (`CEF:0` strings) for Splunk, Microsoft Sentinel, QRadar and ArcSight — with `-HostName`/`-ProductVersion` stamping, severity mapping, and MITRE technique ID passthrough when a finding exposes one |
+| **`Get-CredentialAccessEvents`** | Detection | Runtime credential-access detection: **Kerberoasting** (4769 RC4 service-ticket bursts), anomalous **TGT request volumes** (4768), Kerberos pre-auth failure spikes / **password spray** (4771), and a best-effort **golden-ticket heuristic** (Kerberos logons with no matching TGT in the window — explicitly labeled `Heuristic`/`Medium` confidence), plus optional **LSASS access** enumeration (`-IncludeLSASSAccess`; Security 4663 requires Object Access auditing with a SACL on lsass.exe, or Sysmon event 10) |
+| **`Find-DefenseEvasion`** | Detection | Defense-evasion & tamper detection: **AMSI bypass and ETW tamper patterns** in PowerShell script-block logs (4104), **Defender tampering** (exclusions, disabled real-time/behavior monitoring, 5001/5007 events), **log clearing** (1102/104) and audit policy changes (4719) **with clearing-account attribution**, and optional heuristic **log-gap analysis** (`-IncludeLogGapAnalysis`) — every finding carries a MITRE ATT&CK `Technique` property |
+| **`Get-UserActivityArtifacts`** | Forensics | Per-user DFIR artifacts: **Recycle Bin `$I` parsing** (v2 headers fully decoded, v1 best-effort; original path, size, deletion FILETIME), **LNK shortcut resolution** via WScript.Shell COM, **JumpList enumeration** (AutomaticDestinations — enumeration-level only, embedded targets are *not* parsed), and **ActivitiesCache.db raw copies** (metadata only, no SQLite parsing) with optional CSV export |
+
+**Extended parameters on existing functions:**
+
+- `Export-SecurityReport -Format NDJSON/CEF` — export findings in SIEM-ready formats via `ConvertTo-SiemEvent` (`All` now writes `.ndjson` + `.cef` alongside HTML/JSON/CSV); new `-NoAutoOpen` switch skips opening the HTML report for headless/SYSTEM-context runs
+- `Find-SuspiciousAuthentication` — now also flags **4624 Type 9 (NewCredentials)** explicit-credential logons and **per-account NTLM network logon indicators**
+- `Get-ArtifactCollection` — **per-file SHA256 at acquisition time**, raw registry hive capture via `reg save`, and an **AcquisitionLog manifest block** for chain of custody
+- `Get-CloudComplianceStatus` — now honest about coverage: checks that can't be evaluated report **`NotEvaluated`** instead of fabricated statuses, and the compliance score is `$null` when nothing was evaluated
+
+**Distribution & trust:**
+
+- 📜 **CHANGELOG.md** and **SECURITY.md** (vulnerability disclosure policy) added to the repo
+- 🚀 **PowerShell Gallery publish workflow** (`.github/workflows/publish.yml`) — publishes on release once a gallery API key is configured
+- 📦 Real module metadata in `WindowsSecurityAudit.psd1`
+
+**Quality infrastructure:**
+
+- 🧪 **385 Pester tests** (`tests/WindowsSecurityAudit.Tests.ps1`) — new coverage for v1.4 parameter help, hardcoded-secret AST checks on the new files, MITRE `Technique` attachment, heuristic labeling, and timestamp provenance (artifacts never fabricate timestamps)
+
+### v1.3.0 — Version-Exact CVEs, MISP/TAXII & Auto-Remediation
**2 new functions** — bringing the toolkit to **65 functions across 14 modules**:
@@ -784,7 +838,7 @@ Everything below shipped with the original release and keeps getting sharper:
### Community Edition - Forever FREE
- ✅ **Price**: 100% FREE - No hidden costs
-- ✅ **Functions**: All 65 functions included
+- ✅ **Functions**: All 69 functions included
- ✅ **Source Code**: Full access on GitHub
- ✅ **Updates**: Regular security updates
- ✅ **License**: MIT (commercial use allowed)
@@ -884,10 +938,15 @@ We work with Fortune 500 companies, government agencies, and organizations of al
## 🚀 Roadmap
-### Version 1.4 (Next)
+### Version 1.5 (Next)
- [ ] **TAXII pagination** — pull large collections beyond the first objects page
- [ ] **Broader CPE coverage** — grow the curated CPE table and add vendor-scheme translation for heuristic matches
- [ ] **MISP attribute-type expansion** — support more attribute types beyond ip-dst/domain/url/md5/sha256
+- [ ] **SIEM live streaming** — ship NDJSON/CEF events directly to HTTP Event Collectors (HEC) instead of files
+- [ ] **Remote module execution** — fan out detection/forensics functions for fleet-wide scans
+- [ ] **Alert state dedup** — suppress repeat alerts across scheduled scan runs
+- [ ] **Sysmon-native analytics** — deeper detections from Sysmon process/network events
+- [ ] **$MFT / USN journal parsing** — file-system timeline evidence for the Forensics module
### Version 2.0 (Future)
- [ ] Web-based GUI dashboard
diff --git a/Response/ConvertTo-SiemEvent.ps1 b/Response/ConvertTo-SiemEvent.ps1
new file mode 100644
index 0000000..3c04c4c
--- /dev/null
+++ b/Response/ConvertTo-SiemEvent.ps1
@@ -0,0 +1,191 @@
+function ConvertTo-SiemEvent {
+ <#
+ .SYNOPSIS
+ Converts security findings into SIEM-ready event strings
+ .DESCRIPTION
+ Transforms finding objects (Severity/Category/Finding/Impact/Recommendation) or any
+ PSCustomObject into newline-delimited JSON (NDJSON) or Common Event Format (CEF)
+ strings suitable for ingestion by SIEM platforms (Splunk, Microsoft Sentinel,
+ QRadar, ArcSight). One line is emitted per input object, so the output can be
+ written directly to a .ndjson or .cef file or streamed to a collector.
+
+ Objects that do not match the expected finding shape degrade to a generic
+ informational event instead of throwing. Technique ID discovery (MITRE ATT&CK)
+ is a heuristic: technique_id is populated only when the input object exposes a
+ recognizable technique property (TechniqueId, Technique, MitreTechnique, etc.).
+ The CEF 'act' field is also heuristic: 'Remediate' for High/Critical severity,
+ 'Review' otherwise. Timestamps reflect the UTC time of conversion, not the time
+ the finding was originally detected.
+ .PARAMETER InputObject
+ Finding object(s) to convert. Accepts pipeline input.
+ .PARAMETER Format
+ Output format: NDJSON (one compact JSON object per line) or CEF (CEF:0 string).
+ .PARAMETER HostName
+ Host value embedded in each event. Defaults to the local machine name.
+ .PARAMETER ProductVersion
+ Product version string embedded in each event. Defaults to '1.4.0'.
+ .EXAMPLE
+ $report.Findings | ConvertTo-SiemEvent -Format NDJSON | Out-File findings.ndjson -Encoding UTF8
+ .EXAMPLE
+ ConvertTo-SiemEvent -InputObject $finding -Format CEF -HostName "WS01.contoso.com"
+ .OUTPUTS
+ String. One NDJSON line or CEF string per input object.
+ #>
+
+ [CmdletBinding()]
+ param(
+ [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
+ [AllowNull()]
+ [object]$InputObject,
+
+ [Parameter(Mandatory = $true)]
+ [ValidateSet('NDJSON', 'CEF')]
+ [string]$Format,
+
+ [Parameter()]
+ [string]$HostName = [Environment]::MachineName,
+
+ [Parameter()]
+ [string]$ProductVersion = '1.4.0'
+ )
+
+ begin {
+ Write-Host "Converting findings to $Format events (host: $HostName)..." -ForegroundColor Cyan
+
+ if ([string]::IsNullOrWhiteSpace($HostName)) {
+ $HostName = 'unknown-host'
+ }
+
+ $severityMap = @{
+ 'Critical' = 10
+ 'High' = 7
+ 'Medium' = 5
+ 'Low' = 3
+ 'Info' = 1
+ }
+
+ function Get-ObjectPropertyValue {
+ param(
+ [object]$Object,
+ [string[]]$Names
+ )
+ if ($null -eq $Object) { return $null }
+ foreach ($name in $Names) {
+ $prop = $Object.PSObject.Properties[$name]
+ if ($null -ne $prop -and $null -ne $prop.Value) {
+ return $prop.Value
+ }
+ }
+ return $null
+ }
+
+ function Get-SeverityNumber {
+ param(
+ [string]$SeverityName,
+ [hashtable]$Map
+ )
+ foreach ($key in @($Map.Keys)) {
+ if ($key -ieq $SeverityName) { return $Map[$key] }
+ }
+ return 1
+ }
+
+ function ConvertTo-CefHeaderEscaped {
+ param([AllowNull()][object]$Value)
+ if ($null -eq $Value) { return '' }
+ $text = [string]$Value
+ $text = $text -replace '\\', '\\' -replace '\|', '\|'
+ return ($text -replace "[`r`n]", ' ')
+ }
+
+ function ConvertTo-CefExtensionEscaped {
+ param([AllowNull()][object]$Value)
+ if ($null -eq $Value) { return '' }
+ $text = [string]$Value
+ $text = $text -replace '\\', '\\' -replace '=', '\='
+ return ($text -replace "`r", '\r' -replace "`n", '\n')
+ }
+ }
+
+ process {
+ try {
+ $severity = Get-ObjectPropertyValue -Object $InputObject -Names @('Severity')
+ $category = Get-ObjectPropertyValue -Object $InputObject -Names @('Category')
+ $message = Get-ObjectPropertyValue -Object $InputObject -Names @('Finding', 'Message', 'Description', 'Name', 'Title')
+ $impact = Get-ObjectPropertyValue -Object $InputObject -Names @('Impact')
+ $recommendation = Get-ObjectPropertyValue -Object $InputObject -Names @('Recommendation', 'Remediation')
+ $techniqueId = Get-ObjectPropertyValue -Object $InputObject -Names @('TechniqueId', 'TechniqueID', 'Technique', 'MitreTechnique', 'MITRETechnique', 'AttackTechnique')
+
+ if ($null -eq $InputObject) {
+ Write-Warning "Null input object received; emitting generic event."
+ }
+
+ if ($null -eq $severity) { $severity = 'Info' }
+ if ($null -eq $category) { $category = 'Generic' }
+ if ($null -eq $message) {
+ if ($null -ne $InputObject) {
+ $message = "$InputObject"
+ if ([string]::IsNullOrWhiteSpace($message)) {
+ $message = ($InputObject | ConvertTo-Json -Compress -Depth 3)
+ }
+ }
+ if ([string]::IsNullOrWhiteSpace([string]$message) -or $message -eq '{}') {
+ $message = 'Unspecified event'
+ }
+ }
+
+ $severityNumber = Get-SeverityNumber -SeverityName ([string]$severity) -Map $severityMap
+
+ $action = 'Review'
+ if ($severityNumber -ge 7) { $action = 'Remediate' }
+
+ $timestampUtc = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ')
+
+ if ($Format -eq 'NDJSON') {
+ $eventData = [ordered]@{
+ timestamp = $timestampUtc
+ host = $HostName
+ product = 'WindowsSecurityAudit'
+ severity = [string]$severity
+ category = [string]$category
+ message = [string]$message
+ impact = $(if ($null -ne $impact) { [string]$impact } else { '' })
+ recommendation = $(if ($null -ne $recommendation) { [string]$recommendation } else { '' })
+ }
+ if ($null -ne $techniqueId) {
+ $eventData['technique_id'] = [string]$techniqueId
+ }
+
+ Write-Output ($eventData | ConvertTo-Json -Compress)
+ }
+ else {
+ $header = 'CEF:0|{0}|{1}|{2}|{3}|{4}|{5}' -f `
+ 'okanyildiz', `
+ 'WindowsSecurityAudit', `
+ (ConvertTo-CefHeaderEscaped $ProductVersion), `
+ (ConvertTo-CefHeaderEscaped $category), `
+ (ConvertTo-CefHeaderEscaped $message), `
+ $severityNumber
+
+ $extension = 'rt={0} shost={1} act={2} cs1={3} cs1Label=Impact cs2={4} cs2Label=Recommendation' -f `
+ $timestampUtc, `
+ (ConvertTo-CefExtensionEscaped $HostName), `
+ (ConvertTo-CefExtensionEscaped $action), `
+ (ConvertTo-CefExtensionEscaped $impact), `
+ (ConvertTo-CefExtensionEscaped $recommendation)
+
+ if ($null -ne $techniqueId) {
+ $extension += ' cs3={0} cs3Label=TechniqueId' -f (ConvertTo-CefExtensionEscaped $techniqueId)
+ }
+
+ Write-Output ($header + '| ' + $extension)
+ }
+ }
+ catch {
+ Write-Warning "Failed to convert object to $Format event: $_"
+ }
+ }
+
+ end {
+ }
+}
diff --git a/Response/Export-SecurityReport.ps1 b/Response/Export-SecurityReport.ps1
index 85432c2..45fdb25 100644
--- a/Response/Export-SecurityReport.ps1
+++ b/Response/Export-SecurityReport.ps1
@@ -3,19 +3,24 @@ function Export-SecurityReport {
.SYNOPSIS
Generates comprehensive security assessment reports
.DESCRIPTION
- Creates detailed security reports in multiple formats (HTML, PDF, CSV, JSON)
- with findings, recommendations, and executive summaries
+ Creates detailed security reports in multiple formats (HTML, JSON, CSV, NDJSON, CEF)
+ with findings, recommendations, and executive summaries. NDJSON and CEF formats
+ produce SIEM-ready finding exports via ConvertTo-SiemEvent (.ndjson / .cef files).
.PARAMETER ReportType
Type of report: Executive, Technical, or Compliance
.PARAMETER Format
- Output format: HTML, JSON, CSV, or All
+ Output format: HTML, JSON, CSV, NDJSON, CEF, or All
.PARAMETER OutputPath
Path to save the report
.PARAMETER IncludeCharts
Include visual charts and graphs in HTML reports
+ .PARAMETER NoAutoOpen
+ Do not automatically open the HTML report after generation.
+ Use for headless or SYSTEM-context runs where no interactive session exists.
.EXAMPLE
Export-SecurityReport -ReportType Technical -Format HTML -OutputPath "C:\Reports"
Export-SecurityReport -ReportType Executive -Format All -IncludeCharts
+ Export-SecurityReport -ReportType Technical -Format NDJSON -NoAutoOpen
.OUTPUTS
String path to generated report
#>
@@ -27,14 +32,17 @@ function Export-SecurityReport {
[string]$ReportType,
[Parameter()]
- [ValidateSet('HTML', 'JSON', 'CSV', 'All')]
+ [ValidateSet('HTML', 'JSON', 'CSV', 'NDJSON', 'CEF', 'All')]
[string]$Format = 'HTML',
[Parameter()]
[string]$OutputPath = "C:\SecurityReports",
[Parameter()]
- [switch]$IncludeCharts
+ [switch]$IncludeCharts,
+
+ [Parameter()]
+ [switch]$NoAutoOpen
)
begin {
@@ -204,6 +212,32 @@ if ($highSeverityProcs.Count -gt 0) {
$generatedFiles += $csvPath
}
+ if ($Format -in @('NDJSON', 'All')) {
+ Write-Host "Generating NDJSON SIEM export..." -ForegroundColor Yellow
+ try {
+ $ndjsonPath = Join-Path $OutputPath "${reportBaseName}_findings.ndjson"
+ $ndjsonLines = @($reportData.Findings | ConvertTo-SiemEvent -Format NDJSON)
+ $ndjsonLines | Out-File $ndjsonPath -Encoding UTF8
+ $generatedFiles += $ndjsonPath
+ }
+ catch {
+ Write-Warning "Could not generate NDJSON export: $_"
+ }
+ }
+
+ if ($Format -in @('CEF', 'All')) {
+ Write-Host "Generating CEF SIEM export..." -ForegroundColor Yellow
+ try {
+ $cefPath = Join-Path $OutputPath "${reportBaseName}_findings.cef"
+ $cefLines = @($reportData.Findings | ConvertTo-SiemEvent -Format CEF)
+ $cefLines | Out-File $cefPath -Encoding UTF8
+ $generatedFiles += $cefPath
+ }
+ catch {
+ Write-Warning "Could not generate CEF export: $_"
+ }
+ }
+
if ($Format -in @('HTML', 'All')) {
Write-Host "Generating HTML report..." -ForegroundColor Yellow
@@ -365,9 +399,14 @@ if ($highSeverityProcs.Count -gt 0) {
}
# Open HTML report if generated
- if ($generatedFiles -match '\.html$') {
- $htmlFile = $generatedFiles | Where-Object { $_ -match '\.html$' } | Select-Object -First 1
- Start-Process $htmlFile
+ if (-not $NoAutoOpen -and @($generatedFiles | Where-Object { $_ -match '\.html$' }).Count -gt 0) {
+ $htmlFile = @($generatedFiles | Where-Object { $_ -match '\.html$' }) | Select-Object -First 1
+ try {
+ Start-Process $htmlFile
+ }
+ catch {
+ Write-Warning "Could not auto-open HTML report: $_"
+ }
}
return $generatedFiles
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..0e4fc0d
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,44 @@
+# Security Policy
+
+## Supported Versions
+
+Only the latest release of WindowsSecurityAudit receives security fixes. Older versions are not maintained; please upgrade before reporting or after a fix is published.
+
+| Version | Supported |
+| -------- | ------------------ |
+| Latest | :white_check_mark: |
+| < Latest | :x: |
+
+## Reporting a Vulnerability
+
+Please report security vulnerabilities **privately** — do not open a public GitHub issue.
+
+Preferred channels, in order:
+
+1. **GitHub Security Advisories**: open a private advisory at
+ <https://github.com/okanyildiz/WindowsSecurityAudit/security/advisories/new>
+2. **Maintainer contact**: use the contact options published at <https://github.com/okanyildiz> if you cannot use Security Advisories.
+
+### What to include
+
+- A description of the vulnerability and its potential impact.
+- The module version and PowerShell version affected.
+- Steps to reproduce or a proof of concept, if available.
+- Any suggested remediation, if you have one.
+
+### Response expectations
+
+- **Acknowledgement**: within 7 days of the report.
+- **Initial assessment**: within 30 days, including whether the report is accepted or declined and why.
+- **Resolution**: fixes are shipped in the next release when feasible; confirmed vulnerabilities are disclosed through a GitHub Security Advisory after a fix is available.
+
+## Scope
+
+WindowsSecurityAudit is a defensive auditing toolkit: its functions run read-oriented security checks against Windows systems and cloud tenants. Findings about the module's own code are in scope, for example:
+
+- Credential or API-key exposure (keys written to logs, exported reports, or error output).
+- Unsafe handling of untrusted input (feed data, STIX bundles, imported baselines).
+- Fabricated audit results presented as real measurements.
+- Remediation functions that change system state beyond their documented, `-WhatIf`-gated behavior.
+
+Findings about the security posture of systems the tool *scans* are the tool's intended output, not vulnerabilities in the tool itself — please route those to the owners of the scanned systems.
diff --git a/WindowsSecurityAudit.psd1 b/WindowsSecurityAudit.psd1
index 9614948..fa48616 100644
--- a/WindowsSecurityAudit.psd1
+++ b/WindowsSecurityAudit.psd1
@@ -1,14 +1,22 @@
@{
RootModule = 'WindowsSecurityAudit.psm1'
- ModuleVersion = '1.3.0'
+ ModuleVersion = '1.4.0'
GUID = 'a8d7c4e5-3b2f-4e8a-9c1d-6f5a8b9d2e7c'
- Author = 'Security Team'
- CompanyName = 'Your Organization'
- Copyright = '(c) 2024. All rights reserved.'
+ Author = 'Okan YILDIZ'
+ CompanyName = 'okanyildiz'
+ Copyright = '(c) 2026 Okan YILDIZ. All rights reserved.'
Description = 'Windows Security Audit Module'
PowerShellVersion = '5.1'
FunctionsToExport = '*'
CmdletsToExport = @()
VariablesToExport = @()
AliasesToExport = @()
-}
\ No newline at end of file
+ PrivateData = @{
+ PSData = @{
+ Tags = @('Security', 'Audit', 'DFIR', 'ThreatHunting', 'Compliance', 'MITRE', 'IncidentResponse', 'Vulnerability', 'Windows', 'BlueTeam')
+ LicenseUri = 'https://github.com/okanyildiz/WindowsSecurityAudit/blob/main/LICENSE'
+ ProjectUri = 'https://github.com/okanyildiz/WindowsSecurityAudit'
+ ReleaseNotes = 'https://github.com/okanyildiz/WindowsSecurityAudit/releases'
+ }
+ }
+}
diff --git a/WindowsSecurityAudit.psm1 b/WindowsSecurityAudit.psm1
index 1319af0..c3bbd12 100644
--- a/WindowsSecurityAudit.psm1
+++ b/WindowsSecurityAudit.psm1
@@ -14,7 +14,7 @@ Set-StrictMode -Version Latest
# Module variables
$script:ModuleRoot = $PSScriptRoot
-$script:ModuleVersion = '1.3.0'
+$script:ModuleVersion = '1.4.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.ps1
index b537fbb..3283964 100644
--- a/tests/WindowsSecurityAudit.Tests.ps1
+++ b/tests/WindowsSecurityAudit.Tests.ps1
@@ -410,3 +410,89 @@ Describe 'v1.3 Features' {
}
}
}
+
+Describe 'v1.4 Features' {
+ Context 'Comment-based help for new parameters' {
+ It 'ConvertTo-SiemEvent help documents Format and HostName' {
+ $help = Get-Help -Name 'ConvertTo-SiemEvent' -Full
+ $parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })
+ foreach ($expected in 'Format', 'HostName') {
+ $parameterNames | Should -Contain $expected
+ }
+ }
+
+ It 'Get-CredentialAccessEvents help documents Hours and IncludeLSASSAccess' {
+ $help = Get-Help -Name 'Get-CredentialAccessEvents' -Full
+ $parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })
+ foreach ($expected in 'Hours', 'IncludeLSASSAccess') {
+ $parameterNames | Should -Contain $expected
+ }
+ }
+
+ It 'Find-DefenseEvasion help documents Hours and IncludeLogGapAnalysis' {
+ $help = Get-Help -Name 'Find-DefenseEvasion' -Full
+ $parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })
+ foreach ($expected in 'Hours', 'IncludeLogGapAnalysis') {
+ $parameterNames | Should -Contain $expected
+ }
+ }
+
+ It 'Get-UserActivityArtifacts help documents UserProfile and OutputPath' {
+ $help = Get-Help -Name 'Get-UserActivityArtifacts' -Full
+ $parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })
+ foreach ($expected in 'UserProfile', 'OutputPath') {
+ $parameterNames | Should -Contain $expected
+ }
+ }
+
+ It 'Export-SecurityReport help documents NoAutoOpen' {
+ $help = Get-Help -Name 'Export-SecurityReport' -Full
+ $parameterNames = @($help.parameters.parameter | ForEach-Object { $_.Name })
+ $parameterNames | Should -Contain 'NoAutoOpen'
+ }
+ }
+
+ Context 'Static safety checks' {
+ # -ForEach data must exist at discovery time, so relative paths are used
+ # here and resolved against $script:ModuleRoot (set in BeforeAll) at runtime
+ It '<_> contains no hardcoded keys, secrets, tokens or passwords' -ForEach @(
+ 'Detection/Get-CredentialAccessEvents.ps1'
+ 'Detection/Find-DefenseEvasion.ps1'
+ 'Response/ConvertTo-SiemEvent.ps1'
+ 'Forensics/Get-UserActivityArtifacts.ps1'
+ ) {
+ $Path = Join-Path -Path $script:ModuleRoot -ChildPath $_
+ $result = Get-ScriptFileAst -Path $Path
+ $assignments = @($result.Ast.FindAll({
+ param($node)
+ $node -is [System.Management.Automation.Language.AssignmentStatementAst]
+ }, $true))
+
+ $hardcoded = @($assignments | Where-Object {
+ $_.Left -is [System.Management.Automation.Language.VariableExpressionAst] -and
+ $_.Left.VariablePath.UserPath -match '(?i)(key|secret|token|password)' -and
+ $_.Right -is [System.Management.Automation.Language.StringConstantExpressionAst] -and
+ -not [string]::IsNullOrWhiteSpace($_.Right.Value)
+ })
+ $hardcoded.Count | Should -Be 0 -Because 'credentials must come from parameters, never from string literals'
+ }
+
+ It 'Find-DefenseEvasion attaches a Technique property to findings' {
+ $Path = Join-Path -Path $script:ModuleRoot -ChildPath 'Detection/Find-DefenseEvasion.ps1'
+ $content = Get-Content -Path $Path -Raw
+ $content | Should -Match 'Technique'
+ }
+
+ It 'Get-CredentialAccessEvents labels the golden-ticket detection as a heuristic' {
+ $Path = Join-Path -Path $script:ModuleRoot -ChildPath 'Detection/Get-CredentialAccessEvents.ps1'
+ $content = Get-Content -Path $Path -Raw
+ $content | Should -Match 'Heuristic'
+ }
+
+ It 'Get-UserActivityArtifacts never fabricates timestamps' {
+ $Path = Join-Path -Path $script:ModuleRoot -ChildPath 'Forensics/Get-UserActivityArtifacts.ps1'
+ $content = Get-Content -Path $Path -Raw
+ $content.Contains('Timestamp = Get-Date') | Should -BeFalse -Because 'artifact timestamps must come from the evidence (FILETIME, file metadata), never from the scan time'
+ }
+ }
+}