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
Initial WindowsSecurityAudit release - 14 modules and 58 functions
Okan YILDIZ385be5998890
diff --git a/ActiveDirectory/Find-ADBackdoors.ps1 b/ActiveDirectory/Find-ADBackdoors.ps1new file mode 100644index 0000000..f26c17d--- /dev/null+++ b/ActiveDirectory/Find-ADBackdoors.ps1@@ -0,0 +1,380 @@+function Find-ADBackdoors {+ <#+ .SYNOPSIS+ Detects potential backdoors and persistence mechanisms in Active Directory+ .DESCRIPTION+ Scans for AD backdoors including AdminSDHolder abuse, DCSync permissions,+ SIDHistory manipulation, and other persistence mechanisms+ .PARAMETER CheckAdminSDHolder+ Check for AdminSDHolder tampering+ .PARAMETER CheckDCSync+ Check for DCSync permissions+ .PARAMETER CheckSIDHistory+ Check for SIDHistory abuse+ .PARAMETER CheckDelegation+ Check for dangerous delegations+ .PARAMETER Domain+ Target domain+ .EXAMPLE+ Find-ADBackdoors -CheckAdminSDHolder -CheckDCSync -CheckSIDHistory+ Find-ADBackdoors -CheckDelegation -Domain "contoso.com"+ .OUTPUTS+ PSCustomObject with backdoor findings+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$CheckAdminSDHolder,++ [Parameter()]+ [switch]$CheckDCSync,++ [Parameter()]+ [switch]$CheckSIDHistory,++ [Parameter()]+ [switch]$CheckDelegation,++ [Parameter()]+ [string]$Domain+ )++ begin {+ Write-Host "=== AD BACKDOOR DETECTION ===" -ForegroundColor Cyan++ if (-not (Get-Module -ListAvailable -Name ActiveDirectory)) {+ throw "ActiveDirectory module required"+ }++ Import-Module ActiveDirectory -ErrorAction Stop++ if (-not $Domain) {+ $Domain = (Get-ADDomain).DNSRoot+ }++ Write-Host "Domain: $Domain" -ForegroundColor Yellow+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ $results = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ Domain = $Domain+ Backdoors = @{+ AdminSDHolder = @()+ DCSync = @()+ SIDHistory = @()+ DangerousDelegations = @()+ }+ Summary = @{+ TotalBackdoors = 0+ CriticalFindings = 0+ HighFindings = 0+ }+ Recommendations = @()+ }+ }++ process {+ try {+ # 1. Check AdminSDHolder+ if ($CheckAdminSDHolder) {+ Write-Host "`n[1/4] Checking AdminSDHolder..." -ForegroundColor Cyan++ try {+ # Get AdminSDHolder object+ $adminSDHolder = Get-ADObject -Filter {Name -eq "AdminSDHolder"} -SearchBase "CN=System,$((Get-ADDomain -Server $Domain).DistinguishedName)" -Properties ntSecurityDescriptor -Server $Domain++ if ($adminSDHolder) {+ # Check users with AdminCount=1 who shouldn't have it+ $adminCountUsers = Get-ADUser -Filter {AdminCount -eq 1} -Properties AdminCount, MemberOf -Server $Domain++ # Get actual privileged group members+ $privilegedGroups = @(+ 'Domain Admins',+ 'Enterprise Admins',+ 'Schema Admins',+ 'Administrators',+ 'Account Operators',+ 'Backup Operators',+ 'Server Operators',+ 'Print Operators'+ )++ $legitimatePrivilegedUsers = @()+ foreach ($groupName in $privilegedGroups) {+ try {+ $group = Get-ADGroup -Filter "Name -eq '$groupName'" -Server $Domain -ErrorAction SilentlyContinue+ if ($group) {+ $members = Get-ADGroupMember -Identity $group -Recursive -Server $Domain -ErrorAction SilentlyContinue+ $legitimatePrivilegedUsers += $members.SamAccountName+ }+ }+ catch {+ Write-Verbose "Could not check group: $groupName"+ }+ }++ # Find suspicious AdminCount users+ foreach ($user in $adminCountUsers) {+ if ($user.SamAccountName -notin $legitimatePrivilegedUsers) {+ $results.Backdoors.AdminSDHolder += [PSCustomObject]@{+ Severity = 'Critical'+ Username = $user.SamAccountName+ DisplayName = $user.Name+ Issue = 'AdminCount=1 but not in privileged groups'+ Description = 'Possible AdminSDHolder abuse for persistence'+ }++ $results.Summary.CriticalFindings+++ Write-Host " [!] Suspicious: $($user.SamAccountName)" -ForegroundColor Red+ }+ }++ if ($results.Backdoors.AdminSDHolder.Count -eq 0) {+ Write-Host " No AdminSDHolder abuse detected" -ForegroundColor Green+ }+ }+ }+ catch {+ Write-Warning "Error checking AdminSDHolder: $_"+ }+ }++ # 2. Check DCSync Permissions+ if ($CheckDCSync) {+ Write-Host "`n[2/4] Checking DCSync permissions..." -ForegroundColor Cyan++ try {+ # Get domain root+ $domainDN = (Get-ADDomain -Server $Domain).DistinguishedName+ $domainObject = Get-ADObject -Identity $domainDN -Properties ntSecurityDescriptor -Server $Domain++ # DCSync requires these rights:+ # - DS-Replication-Get-Changes (GUID: 1131f6aa-9c07-11d1-f79f-00c04fc2dcd2)+ # - DS-Replication-Get-Changes-All (GUID: 1131f6ad-9c07-11d1-f79f-00c04fc2dcd2)++ $acl = $domainObject.ntSecurityDescriptor++ $dcsyncRights = @(+ '1131f6aa-9c07-11d1-f79f-00c04fc2dcd2', # DS-Replication-Get-Changes+ '1131f6ad-9c07-11d1-f79f-00c04fc2dcd2' # DS-Replication-Get-Changes-All+ )++ foreach ($ace in $acl.Access) {+ if ($ace.ObjectType -in $dcsyncRights) {+ # Resolve SID to account+ try {+ $account = Get-ADObject -Filter "objectSid -eq '$($ace.IdentityReference)'" -Server $Domain -ErrorAction SilentlyContinue++ if ($account) {+ # Check if it's a legitimate DC or admin account+ $isLegitimate = $account.Name -match "Domain Controllers|Enterprise Admins|Administrators"++ if (-not $isLegitimate) {+ $results.Backdoors.DCSync += [PSCustomObject]@{+ Severity = 'Critical'+ Account = $account.Name+ AccountType = $account.ObjectClass+ Permission = 'DCSync'+ Issue = 'Non-standard account has DCSync permissions'+ Description = 'Can replicate password hashes from domain'+ }++ $results.Summary.CriticalFindings+++ Write-Host " [!] DCSync: $($account.Name)" -ForegroundColor Red+ }+ }+ }+ catch {+ Write-Verbose "Could not resolve SID: $($ace.IdentityReference)"+ }+ }+ }++ if ($results.Backdoors.DCSync.Count -eq 0) {+ Write-Host " No suspicious DCSync permissions found" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking DCSync permissions: $_"+ }+ }++ # 3. Check SIDHistory+ if ($CheckSIDHistory) {+ Write-Host "`n[3/4] Checking SIDHistory abuse..." -ForegroundColor Cyan++ try {+ # Find users with SIDHistory+ $usersWithSIDHistory = Get-ADUser -Filter {SIDHistory -like "*"} -Properties SIDHistory, MemberOf -Server $Domain++ foreach ($user in $usersWithSIDHistory) {+ # SIDHistory is legitimate in migration scenarios, but can be abused+ $sidHistoryCount = $user.SIDHistory.Count++ # Check if any SID in history is from a privileged group+ foreach ($sid in $user.SIDHistory) {+ try {+ $sidObject = Get-ADObject -Filter "objectSid -eq '$sid'" -Server $Domain -ErrorAction SilentlyContinue++ if ($sidObject) {+ $results.Backdoors.SIDHistory += [PSCustomObject]@{+ Severity = 'High'+ Username = $user.SamAccountName+ SIDHistoryObject = $sidObject.Name+ SIDHistoryCount = $sidHistoryCount+ Issue = 'User has SIDHistory attribute set'+ Description = 'Can be used for privilege escalation'+ }++ $results.Summary.HighFindings+++ Write-Host " [!] SIDHistory: $($user.SamAccountName) -> $($sidObject.Name)" -ForegroundColor Yellow+ }+ }+ catch {+ Write-Verbose "Could not resolve SID: $sid"+ }+ }+ }++ if ($results.Backdoors.SIDHistory.Count -eq 0) {+ Write-Host " No SIDHistory abuse detected" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking SIDHistory: $_"+ }+ }++ # 4. Check Dangerous Delegations+ if ($CheckDelegation) {+ Write-Host "`n[4/4] Checking dangerous delegations..." -ForegroundColor Cyan++ try {+ # Check for unconstrained delegation+ $unconstrainedDelegation = Get-ADComputer -Filter {TrustedForDelegation -eq $true} -Properties TrustedForDelegation -Server $Domain++ foreach ($computer in $unconstrainedDelegation) {+ # Domain Controllers are expected to have this+ if ($computer.Name -notmatch "DC|Domain Controller") {+ $results.Backdoors.DangerousDelegations += [PSCustomObject]@{+ Severity = 'High'+ Object = $computer.Name+ ObjectType = 'Computer'+ DelegationType = 'Unconstrained'+ Issue = 'Computer has unconstrained delegation enabled'+ Description = 'Can impersonate any user to any service'+ }++ $results.Summary.HighFindings+++ Write-Host " [!] Unconstrained Delegation: $($computer.Name)" -ForegroundColor Yellow+ }+ }++ # Check for constrained delegation with protocol transition+ $constrainedDelegation = Get-ADObject -Filter {msDS-AllowedToDelegateTo -like "*"} -Properties msDS-AllowedToDelegateTo, TrustedToAuthForDelegation -Server $Domain++ foreach ($object in $constrainedDelegation) {+ if ($object.TrustedToAuthForDelegation) {+ $results.Backdoors.DangerousDelegations += [PSCustomObject]@{+ Severity = 'Medium'+ Object = $object.Name+ ObjectType = $object.ObjectClass+ DelegationType = 'Constrained with Protocol Transition'+ DelegateTo = $object.'msDS-AllowedToDelegateTo' -join ', '+ Issue = 'Protocol transition enabled'+ Description = 'Can obtain service tickets without user credentials'+ }++ Write-Host " [!] Protocol Transition: $($object.Name)" -ForegroundColor Yellow+ }+ }++ if ($results.Backdoors.DangerousDelegations.Count -eq 0) {+ Write-Host " No dangerous delegations found" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking delegations: $_"+ }+ }++ # Calculate total backdoors+ $results.Summary.TotalBackdoors =+ $results.Backdoors.AdminSDHolder.Count ++ $results.Backdoors.DCSync.Count ++ $results.Backdoors.SIDHistory.Count ++ $results.Backdoors.DangerousDelegations.Count++ # Generate recommendations+ if ($results.Backdoors.AdminSDHolder.Count -gt 0) {+ $results.Recommendations += "Review and remove AdminCount attribute from non-privileged accounts"+ $results.Recommendations += "Investigate how AdminCount was set on these accounts"+ }++ if ($results.Backdoors.DCSync.Count -gt 0) {+ $results.Recommendations += "Remove DCSync permissions from non-administrative accounts immediately"+ $results.Recommendations += "Audit replication activities"+ }++ if ($results.Backdoors.SIDHistory.Count -gt 0) {+ $results.Recommendations += "Clear SIDHistory for accounts not in active migration"+ $results.Recommendations += "Monitor SIDHistory changes"+ }++ if ($results.Backdoors.DangerousDelegations.Count -gt 0) {+ $results.Recommendations += "Review and restrict delegation configurations"+ $results.Recommendations += "Use constrained delegation instead of unconstrained"+ }++ $results.Recommendations += "Implement regular AD security audits"+ $results.Recommendations += "Enable advanced audit policies for privilege use"+ $results.Recommendations += "Monitor for Golden Ticket indicators"++ }+ catch {+ Write-Error "Error during backdoor detection: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== SCAN COMPLETE ===" -ForegroundColor Green++ Write-Host "`nBackdoor Summary:" -ForegroundColor Cyan+ Write-Host " Total Backdoors Found: $($results.Summary.TotalBackdoors)" -ForegroundColor $(+ if ($results.Summary.TotalBackdoors -gt 0) { 'Red' } else { 'Green' }+ )+ Write-Host " Critical Findings: $($results.Summary.CriticalFindings)" -ForegroundColor Red+ Write-Host " High Findings: $($results.Summary.HighFindings)" -ForegroundColor Yellow++ if ($results.Backdoors.AdminSDHolder.Count -gt 0) {+ Write-Host "`nAdminSDHolder Abuse: $($results.Backdoors.AdminSDHolder.Count)" -ForegroundColor Red+ }++ if ($results.Backdoors.DCSync.Count -gt 0) {+ Write-Host "DCSync Permissions: $($results.Backdoors.DCSync.Count)" -ForegroundColor Red+ }++ if ($results.Backdoors.SIDHistory.Count -gt 0) {+ Write-Host "SIDHistory Abuse: $($results.Backdoors.SIDHistory.Count)" -ForegroundColor Yellow+ }++ if ($results.Backdoors.DangerousDelegations.Count -gt 0) {+ Write-Host "Dangerous Delegations: $($results.Backdoors.DangerousDelegations.Count)" -ForegroundColor Yellow+ }++ if ($results.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $results.Recommendations | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ if ($results.Summary.TotalBackdoors -gt 0) {+ Write-Host "`n[!!!] BACKDOORS DETECTED - IMMEDIATE ACTION REQUIRED [!!!]" -ForegroundColor Red -BackgroundColor Black+ }++ return $results+ }+}\ No newline at end of filediff --git a/ActiveDirectory/Find-ADVulnerabilities.ps1 b/ActiveDirectory/Find-ADVulnerabilities.ps1new file mode 100644index 0000000..c84ab4c--- /dev/null+++ b/ActiveDirectory/Find-ADVulnerabilities.ps1@@ -0,0 +1,320 @@+function Find-ADVulnerabilities {+ <#+ .SYNOPSIS+ Detects common Active Directory vulnerabilities and misconfigurations+ .DESCRIPTION+ Scans for AD vulnerabilities including Kerberoasting, AS-REP Roasting,+ weak permissions, and dangerous configurations+ .PARAMETER CheckKerberoasting+ Check for Kerberoastable accounts+ .PARAMETER CheckASREPRoasting+ Check for AS-REP Roastable accounts+ .PARAMETER CheckWeakPermissions+ Check for weak ACL permissions+ .PARAMETER Domain+ Target domain (default: current domain)+ .EXAMPLE+ Find-ADVulnerabilities -CheckKerberoasting -CheckASREPRoasting+ Find-ADVulnerabilities -CheckWeakPermissions -Domain "contoso.com"+ .OUTPUTS+ PSCustomObject with vulnerability findings+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$CheckKerberoasting,++ [Parameter()]+ [switch]$CheckASREPRoasting,++ [Parameter()]+ [switch]$CheckWeakPermissions,++ [Parameter()]+ [string]$Domain+ )++ begin {+ Write-Host "=== ACTIVE DIRECTORY VULNERABILITY SCAN ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ # Check if ActiveDirectory module is available+ if (-not (Get-Module -ListAvailable -Name ActiveDirectory)) {+ Write-Warning "ActiveDirectory module not found. Install RSAT tools."+ Write-Host "To install: Add-WindowsCapability -Online -Name Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0" -ForegroundColor Yellow+ throw "ActiveDirectory module required"+ }++ Import-Module ActiveDirectory -ErrorAction Stop++ # If no domain specified, use current+ if (-not $Domain) {+ $Domain = (Get-ADDomain).DNSRoot+ }++ Write-Host "Target Domain: $Domain" -ForegroundColor Yellow++ $results = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ Domain = $Domain+ Vulnerabilities = @{+ Kerberoasting = @()+ ASREPRoasting = @()+ WeakPermissions = @()+ DangerousConfigurations = @()+ }+ Summary = @{+ TotalVulnerabilities = 0+ CriticalFindings = 0+ HighFindings = 0+ MediumFindings = 0+ }+ Recommendations = @()+ }+ }++ process {+ try {+ # 1. Check for Kerberoastable accounts+ if ($CheckKerberoasting) {+ Write-Host "`n[1/3] Checking for Kerberoastable accounts..." -ForegroundColor Cyan++ try {+ # Find accounts with SPN set+ $kerberoastableUsers = Get-ADUser -Filter {ServicePrincipalName -like "*"} -Properties ServicePrincipalName, PasswordLastSet, Enabled, AdminCount -Server $Domain++ foreach ($user in $kerberoastableUsers) {+ $severity = 'Medium'++ # Elevated severity for privileged accounts+ if ($user.AdminCount -eq 1) {+ $severity = 'Critical'+ $results.Summary.CriticalFindings+++ } else {+ $results.Summary.MediumFindings+++ }++ # Check password age+ $passwordAge = if ($user.PasswordLastSet) {+ (New-TimeSpan -Start $user.PasswordLastSet -End (Get-Date)).Days+ } else {+ "Never changed"+ }++ $results.Vulnerabilities.Kerberoasting += [PSCustomObject]@{+ Severity = $severity+ Username = $user.SamAccountName+ DisplayName = $user.Name+ Enabled = $user.Enabled+ IsPrivileged = ($user.AdminCount -eq 1)+ SPNs = $user.ServicePrincipalName -join ', '+ PasswordAge = $passwordAge+ Description = "Account has SPN set and is vulnerable to Kerberoasting attack"+ }++ Write-Host " Found: $($user.SamAccountName) - Severity: $severity" -ForegroundColor $(+ if ($severity -eq 'Critical') { 'Red' } else { 'Yellow' }+ )+ }++ if ($kerberoastableUsers.Count -eq 0) {+ Write-Host " No Kerberoastable accounts found" -ForegroundColor Green+ } else {+ $results.Recommendations += "Review and remove unnecessary SPNs from accounts"+ $results.Recommendations += "Use long, complex passwords for accounts with SPNs"+ $results.Recommendations += "Consider using Group Managed Service Accounts (gMSA)"+ }+ }+ catch {+ Write-Warning "Error checking Kerberoasting: $_"+ }+ }++ # 2. Check for AS-REP Roastable accounts+ if ($CheckASREPRoasting) {+ Write-Host "`n[2/3] Checking for AS-REP Roastable accounts..." -ForegroundColor Cyan++ try {+ # Find accounts with "Do not require Kerberos preauthentication"+ $asrepUsers = Get-ADUser -Filter {DoesNotRequirePreAuth -eq $true} -Properties DoesNotRequirePreAuth, PasswordLastSet, Enabled, AdminCount -Server $Domain++ foreach ($user in $asrepUsers) {+ $severity = 'High'++ if ($user.AdminCount -eq 1) {+ $severity = 'Critical'+ $results.Summary.CriticalFindings+++ } else {+ $results.Summary.HighFindings+++ }++ $passwordAge = if ($user.PasswordLastSet) {+ (New-TimeSpan -Start $user.PasswordLastSet -End (Get-Date)).Days+ } else {+ "Never changed"+ }++ $results.Vulnerabilities.ASREPRoasting += [PSCustomObject]@{+ Severity = $severity+ Username = $user.SamAccountName+ DisplayName = $user.Name+ Enabled = $user.Enabled+ IsPrivileged = ($user.AdminCount -eq 1)+ PasswordAge = $passwordAge+ Description = "Account does not require Kerberos pre-authentication (AS-REP Roasting)"+ }++ Write-Host " Found: $($user.SamAccountName) - Severity: $severity" -ForegroundColor $(+ if ($severity -eq 'Critical') { 'Red' } else { 'Yellow' }+ )+ }++ if ($asrepUsers.Count -eq 0) {+ Write-Host " No AS-REP Roastable accounts found" -ForegroundColor Green+ } else {+ $results.Recommendations += "Enable Kerberos pre-authentication for all accounts"+ $results.Recommendations += "Review accounts with DoesNotRequirePreAuth enabled"+ }+ }+ catch {+ Write-Warning "Error checking AS-REP Roasting: $_"+ }+ }++ # 3. Check for weak permissions and dangerous configurations+ if ($CheckWeakPermissions) {+ Write-Host "`n[3/3] Checking for weak permissions..." -ForegroundColor Cyan++ try {+ # Check for users with "Password Never Expires"+ Write-Host " Checking password policies..." -ForegroundColor Yellow+ $neverExpireUsers = Get-ADUser -Filter {PasswordNeverExpires -eq $true -and Enabled -eq $true} -Properties PasswordNeverExpires, AdminCount -Server $Domain++ foreach ($user in $neverExpireUsers) {+ $severity = if ($user.AdminCount -eq 1) { 'High' } else { 'Medium' }++ if ($severity -eq 'High') {+ $results.Summary.HighFindings+++ } else {+ $results.Summary.MediumFindings+++ }++ $results.Vulnerabilities.WeakPermissions += [PSCustomObject]@{+ Severity = $severity+ Type = 'Password Policy'+ Object = $user.SamAccountName+ Issue = 'Password Never Expires'+ IsPrivileged = ($user.AdminCount -eq 1)+ Description = "Account password is set to never expire"+ }+ }++ Write-Host " Found $($neverExpireUsers.Count) accounts with non-expiring passwords" -ForegroundColor $(+ if ($neverExpireUsers.Count -gt 0) { 'Yellow' } else { 'Green' }+ )++ # Check for disabled password complexity+ Write-Host " Checking domain password policy..." -ForegroundColor Yellow+ $domainPolicy = Get-ADDefaultDomainPasswordPolicy -Server $Domain++ if ($domainPolicy.ComplexityEnabled -eq $false) {+ $results.Vulnerabilities.DangerousConfigurations += [PSCustomObject]@{+ Severity = 'Critical'+ Type = 'Password Policy'+ Issue = 'Password Complexity Disabled'+ Description = 'Domain password policy does not require complex passwords'+ }+ $results.Summary.CriticalFindings+++ Write-Host " [!] Password complexity is DISABLED" -ForegroundColor Red+ }++ if ($domainPolicy.MinPasswordLength -lt 12) {+ $results.Vulnerabilities.DangerousConfigurations += [PSCustomObject]@{+ Severity = 'High'+ Type = 'Password Policy'+ Issue = "Minimum Password Length: $($domainPolicy.MinPasswordLength)"+ Description = 'Minimum password length is less than 12 characters'+ }+ $results.Summary.HighFindings+++ Write-Host " [!] Minimum password length is only $($domainPolicy.MinPasswordLength) characters" -ForegroundColor Yellow+ }++ # Check for accounts with reversible encryption+ Write-Host " Checking for reversible encryption..." -ForegroundColor Yellow+ $reversibleUsers = Get-ADUser -Filter {AllowReversiblePasswordEncryption -eq $true} -Properties AllowReversiblePasswordEncryption -Server $Domain++ foreach ($user in $reversibleUsers) {+ $results.Vulnerabilities.DangerousConfigurations += [PSCustomObject]@{+ Severity = 'Critical'+ Type = 'Password Storage'+ Object = $user.SamAccountName+ Issue = 'Reversible Encryption Enabled'+ Description = 'Password stored with reversible encryption (plaintext equivalent)'+ }+ $results.Summary.CriticalFindings+++ Write-Host " [!] $($user.SamAccountName) has reversible encryption enabled" -ForegroundColor Red+ }++ if (-not $results.Recommendations -contains "Enforce strong password policies") {+ $results.Recommendations += "Enforce strong password policies (min 12 chars, complexity enabled)"+ $results.Recommendations += "Regular password rotation for privileged accounts"+ $results.Recommendations += "Disable reversible encryption for all accounts"+ }+ }+ catch {+ Write-Warning "Error checking weak permissions: $_"+ }+ }++ # Calculate total vulnerabilities+ $results.Summary.TotalVulnerabilities = $results.Summary.CriticalFindings ++ $results.Summary.HighFindings ++ $results.Summary.MediumFindings++ }+ catch {+ Write-Error "Error during AD vulnerability scan: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== SCAN COMPLETE ===" -ForegroundColor Green++ Write-Host "`nVulnerability Summary:" -ForegroundColor Cyan+ Write-Host " Total Vulnerabilities: $($results.Summary.TotalVulnerabilities)" -ForegroundColor White+ Write-Host " Critical: $($results.Summary.CriticalFindings)" -ForegroundColor Red+ Write-Host " High: $($results.Summary.HighFindings)" -ForegroundColor Yellow+ Write-Host " Medium: $($results.Summary.MediumFindings)" -ForegroundColor Yellow++ if ($results.Vulnerabilities.Kerberoasting.Count -gt 0) {+ Write-Host "`nKerberoastable Accounts: $($results.Vulnerabilities.Kerberoasting.Count)" -ForegroundColor Yellow+ $results.Vulnerabilities.Kerberoasting | Select-Object -First 5 | ForEach-Object {+ Write-Host " - $($_.Username) [$($_.Severity)]" -ForegroundColor $(+ if ($_.Severity -eq 'Critical') { 'Red' } else { 'Yellow' }+ )+ }+ }++ if ($results.Vulnerabilities.ASREPRoasting.Count -gt 0) {+ Write-Host "`nAS-REP Roastable Accounts: $($results.Vulnerabilities.ASREPRoasting.Count)" -ForegroundColor Yellow+ $results.Vulnerabilities.ASREPRoasting | Select-Object -First 5 | ForEach-Object {+ Write-Host " - $($_.Username) [$($_.Severity)]" -ForegroundColor $(+ if ($_.Severity -eq 'Critical') { 'Red' } else { 'Yellow' }+ )+ }+ }++ if ($results.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $results.Recommendations | Select-Object -Unique | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ Write-Host "`nNote: This scan requires domain connectivity and RSAT tools" -ForegroundColor Gray++ return $results+ }+}\ No newline at end of filediff --git a/ActiveDirectory/Find-StaleADObjects.ps1 b/ActiveDirectory/Find-StaleADObjects.ps1new file mode 100644index 0000000..181b79b--- /dev/null+++ b/ActiveDirectory/Find-StaleADObjects.ps1@@ -0,0 +1,293 @@+function Find-StaleADObjects {+ <#+ .SYNOPSIS+ Identifies inactive and stale objects in Active Directory+ .DESCRIPTION+ Finds stale user accounts, computer accounts, and groups that haven't been+ used within specified time periods+ .PARAMETER InactiveDays+ Number of days to consider an object stale (default: 90)+ .PARAMETER IncludeUsers+ Check for stale user accounts+ .PARAMETER IncludeComputers+ Check for stale computer accounts+ .PARAMETER IncludeGroups+ Check for empty/unused groups+ .PARAMETER Domain+ Target domain+ .EXAMPLE+ Find-StaleADObjects -InactiveDays 90 -IncludeUsers -IncludeComputers+ Find-StaleADObjects -InactiveDays 180 -IncludeUsers -IncludeComputers -IncludeGroups+ .OUTPUTS+ PSCustomObject with stale object information+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [int]$InactiveDays = 90,++ [Parameter()]+ [switch]$IncludeUsers,++ [Parameter()]+ [switch]$IncludeComputers,++ [Parameter()]+ [switch]$IncludeGroups,++ [Parameter()]+ [string]$Domain+ )++ begin {+ Write-Host "=== STALE AD OBJECTS SCAN ===" -ForegroundColor Cyan++ if (-not (Get-Module -ListAvailable -Name ActiveDirectory)) {+ throw "ActiveDirectory module required"+ }++ Import-Module ActiveDirectory -ErrorAction Stop++ if (-not $Domain) {+ $Domain = (Get-ADDomain).DNSRoot+ }++ Write-Host "Domain: $Domain" -ForegroundColor Yellow+ Write-Host "Inactive Threshold: $InactiveDays days" -ForegroundColor Yellow++ $cutoffDate = (Get-Date).AddDays(-$InactiveDays)++ $results = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ Domain = $Domain+ InactiveDays = $InactiveDays+ StaleUsers = @()+ StaleComputers = @()+ StaleGroups = @()+ Statistics = @{+ TotalStaleUsers = 0+ TotalStaleComputers = 0+ EmptyGroups = 0+ TotalObjectsToReview = 0+ }+ Recommendations = @()+ }+ }++ process {+ try {+ # 1. Find Stale User Accounts+ if ($IncludeUsers) {+ Write-Host "`n[1/3] Scanning for stale user accounts..." -ForegroundColor Cyan++ try {+ # Get users that haven't logged on in X days+ $staleUsers = Get-ADUser -Filter {+ Enabled -eq $true -and+ LastLogonDate -lt $cutoffDate+ } -Properties LastLogonDate, PasswordLastSet, whenCreated, Description -Server $Domain++ foreach ($user in $staleUsers) {+ $daysSinceLogon = if ($user.LastLogonDate) {+ (New-TimeSpan -Start $user.LastLogonDate -End (Get-Date)).Days+ } else {+ "Never"+ }++ $accountAge = (New-TimeSpan -Start $user.whenCreated -End (Get-Date)).Days++ $results.StaleUsers += [PSCustomObject]@{+ Username = $user.SamAccountName+ DisplayName = $user.Name+ Description = $user.Description+ Enabled = $user.Enabled+ LastLogon = $user.LastLogonDate+ DaysSinceLogon = $daysSinceLogon+ PasswordLastSet = $user.PasswordLastSet+ Created = $user.whenCreated+ AccountAge = $accountAge+ DistinguishedName = $user.DistinguishedName+ }+ }++ $results.Statistics.TotalStaleUsers = $staleUsers.Count++ Write-Host " Found $($staleUsers.Count) stale user accounts" -ForegroundColor $(+ if ($staleUsers.Count -gt 0) { 'Yellow' } else { 'Green' }+ )++ if ($staleUsers.Count -gt 0) {+ Write-Host " Top 5 oldest:" -ForegroundColor Yellow+ $staleUsers | Sort-Object LastLogonDate | Select-Object -First 5 | ForEach-Object {+ $lastLogon = if ($_.LastLogonDate) {+ $_.LastLogonDate.ToString("yyyy-MM-dd")+ } else {+ "Never"+ }+ Write-Host " - $($_.SamAccountName) (Last: $lastLogon)" -ForegroundColor White+ }+ }+ }+ catch {+ Write-Warning "Error scanning stale users: $_"+ }+ }++ # 2. Find Stale Computer Accounts+ if ($IncludeComputers) {+ Write-Host "`n[2/3] Scanning for stale computer accounts..." -ForegroundColor Cyan++ try {+ # Get computers that haven't connected in X days+ $staleComputers = Get-ADComputer -Filter {+ Enabled -eq $true -and+ LastLogonDate -lt $cutoffDate+ } -Properties LastLogonDate, OperatingSystem, whenCreated, Description -Server $Domain++ foreach ($computer in $staleComputers) {+ $daysSinceLogon = if ($computer.LastLogonDate) {+ (New-TimeSpan -Start $computer.LastLogonDate -End (Get-Date)).Days+ } else {+ "Never"+ }++ $results.StaleComputers += [PSCustomObject]@{+ ComputerName = $computer.Name+ Description = $computer.Description+ OperatingSystem = $computer.OperatingSystem+ Enabled = $computer.Enabled+ LastLogon = $computer.LastLogonDate+ DaysSinceLogon = $daysSinceLogon+ Created = $computer.whenCreated+ DistinguishedName = $computer.DistinguishedName+ }+ }++ $results.Statistics.TotalStaleComputers = $staleComputers.Count++ Write-Host " Found $($staleComputers.Count) stale computer accounts" -ForegroundColor $(+ if ($staleComputers.Count -gt 0) { 'Yellow' } else { 'Green' }+ )++ if ($staleComputers.Count -gt 0) {+ Write-Host " Top 5 oldest:" -ForegroundColor Yellow+ $staleComputers | Sort-Object LastLogonDate | Select-Object -First 5 | ForEach-Object {+ $lastLogon = if ($_.LastLogonDate) {+ $_.LastLogonDate.ToString("yyyy-MM-dd")+ } else {+ "Never"+ }+ Write-Host " - $($_.Name) (Last: $lastLogon)" -ForegroundColor White+ }+ }+ }+ catch {+ Write-Warning "Error scanning stale computers: $_"+ }+ }++ # 3. Find Empty/Unused Groups+ if ($IncludeGroups) {+ Write-Host "`n[3/3] Scanning for empty/unused groups..." -ForegroundColor Cyan++ try {+ # Get all groups+ $allGroups = Get-ADGroup -Filter * -Properties Members, whenCreated, Description -Server $Domain++ foreach ($group in $allGroups) {+ $members = Get-ADGroupMember -Identity $group -Server $Domain -ErrorAction SilentlyContinue++ if ($members.Count -eq 0) {+ $groupAge = (New-TimeSpan -Start $group.whenCreated -End (Get-Date)).Days++ $results.StaleGroups += [PSCustomObject]@{+ GroupName = $group.Name+ Description = $group.Description+ MemberCount = 0+ Created = $group.whenCreated+ GroupAge = $groupAge+ GroupScope = $group.GroupScope+ GroupCategory = $group.GroupCategory+ DistinguishedName = $group.DistinguishedName+ }+ }+ }++ $results.Statistics.EmptyGroups = $results.StaleGroups.Count++ Write-Host " Found $($results.StaleGroups.Count) empty groups" -ForegroundColor $(+ if ($results.StaleGroups.Count -gt 0) { 'Yellow' } else { 'Green' }+ )++ if ($results.StaleGroups.Count -gt 0) {+ Write-Host " Top 5 oldest empty groups:" -ForegroundColor Yellow+ $results.StaleGroups | Sort-Object Created | Select-Object -First 5 | ForEach-Object {+ Write-Host " - $($_.GroupName) (Created: $($_.Created.ToString('yyyy-MM-dd')))" -ForegroundColor White+ }+ }+ }+ catch {+ Write-Warning "Error scanning groups: $_"+ }+ }++ # Calculate total objects to review+ $results.Statistics.TotalObjectsToReview =+ $results.Statistics.TotalStaleUsers ++ $results.Statistics.TotalStaleComputers ++ $results.Statistics.EmptyGroups++ # Generate recommendations+ if ($results.Statistics.TotalStaleUsers -gt 0) {+ $results.Recommendations += "Review and disable $($results.Statistics.TotalStaleUsers) stale user accounts"+ $results.Recommendations += "Move disabled accounts to separate OU after 30 days"+ $results.Recommendations += "Delete disabled accounts after 90 days (with backup)"+ }++ if ($results.Statistics.TotalStaleComputers -gt 0) {+ $results.Recommendations += "Remove $($results.Statistics.TotalStaleComputers) stale computer accounts"+ }++ if ($results.Statistics.EmptyGroups -gt 0) {+ $results.Recommendations += "Review and remove $($results.Statistics.EmptyGroups) empty groups"+ }++ $results.Recommendations += "Implement automated stale object cleanup policy"+ $results.Recommendations += "Schedule monthly stale object reviews"++ }+ catch {+ Write-Error "Error scanning for stale objects: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== SCAN COMPLETE ===" -ForegroundColor Green++ Write-Host "`nStatistics:" -ForegroundColor Cyan+ Write-Host " Stale Users: $($results.Statistics.TotalStaleUsers)" -ForegroundColor White+ Write-Host " Stale Computers: $($results.Statistics.TotalStaleComputers)" -ForegroundColor White+ Write-Host " Empty Groups: $($results.Statistics.EmptyGroups)" -ForegroundColor White+ Write-Host " Total Objects to Review: $($results.Statistics.TotalObjectsToReview)" -ForegroundColor $(+ if ($results.Statistics.TotalObjectsToReview -gt 0) { 'Yellow' } else { 'Green' }+ )++ if ($results.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $results.Recommendations | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ Write-Host "`nCleanup Impact:" -ForegroundColor Cyan+ if ($results.Statistics.TotalObjectsToReview -gt 0) {+ Write-Host " Removing stale objects will improve AD performance" -ForegroundColor White+ Write-Host " Reduce AD replication traffic" -ForegroundColor White+ Write-Host " Improve security posture" -ForegroundColor White+ }++ return $results+ }+}\ No newline at end of filediff --git a/ActiveDirectory/Get-ADPasswordPolicy.ps1 b/ActiveDirectory/Get-ADPasswordPolicy.ps1new file mode 100644index 0000000..73e150e--- /dev/null+++ b/ActiveDirectory/Get-ADPasswordPolicy.ps1@@ -0,0 +1,315 @@+function Get-ADPasswordPolicy {+ <#+ .SYNOPSIS+ Retrieves and analyzes Active Directory password policies+ .DESCRIPTION+ Gets domain default password policy and fine-grained password policies (PSOs)+ with security analysis and recommendations+ .PARAMETER Domain+ Target domain+ .PARAMETER IncludeFineGrained+ Include Fine-Grained Password Policies (PSOs)+ .EXAMPLE+ Get-ADPasswordPolicy+ Get-ADPasswordPolicy -IncludeFineGrained -Domain "contoso.com"+ .OUTPUTS+ PSCustomObject with password policy information+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [string]$Domain,++ [Parameter()]+ [switch]$IncludeFineGrained+ )++ begin {+ Write-Host "=== AD PASSWORD POLICY ANALYSIS ===" -ForegroundColor Cyan++ if (-not (Get-Module -ListAvailable -Name ActiveDirectory)) {+ throw "ActiveDirectory module required"+ }++ Import-Module ActiveDirectory -ErrorAction Stop++ if (-not $Domain) {+ $Domain = (Get-ADDomain).DNSRoot+ }++ Write-Host "Domain: $Domain" -ForegroundColor Yellow++ $analysis = [PSCustomObject]@{+ AnalysisDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ Domain = $Domain+ DefaultPolicy = @{}+ FineGrainedPolicies = @()+ SecurityScore = 0+ MaxScore = 100+ Findings = @()+ Recommendations = @()+ }+ }++ process {+ try {+ # 1. Get Default Domain Password Policy+ Write-Host "`nAnalyzing Default Password Policy..." -ForegroundColor Cyan++ $policy = Get-ADDefaultDomainPasswordPolicy -Server $Domain++ $score = 0++ # Complexity (20 points)+ if ($policy.ComplexityEnabled) {+ $score += 20+ Write-Host " + Complexity Enabled: Yes" -ForegroundColor Green+ } else {+ Write-Host " - Complexity Enabled: No" -ForegroundColor Red+ $analysis.Findings += [PSCustomObject]@{+ Severity = 'Critical'+ Finding = 'Password complexity is disabled'+ Impact = 'Weak passwords can be set'+ }+ }++ # Min Length (25 points)+ Write-Host " Min Password Length: $($policy.MinPasswordLength)" -ForegroundColor $(+ if ($policy.MinPasswordLength -ge 14) { 'Green' }+ elseif ($policy.MinPasswordLength -ge 12) { 'Yellow' }+ else { 'Red' }+ )++ if ($policy.MinPasswordLength -ge 14) {+ $score += 25+ } elseif ($policy.MinPasswordLength -ge 12) {+ $score += 20+ $analysis.Findings += [PSCustomObject]@{+ Severity = 'Medium'+ Finding = "Minimum password length is $($policy.MinPasswordLength) (recommended: 14+)"+ Impact = 'Increased vulnerability to brute force'+ }+ } elseif ($policy.MinPasswordLength -ge 8) {+ $score += 10+ $analysis.Findings += [PSCustomObject]@{+ Severity = 'High'+ Finding = "Minimum password length is only $($policy.MinPasswordLength)"+ Impact = 'Significant vulnerability to brute force'+ }+ } else {+ $analysis.Findings += [PSCustomObject]@{+ Severity = 'Critical'+ Finding = "Minimum password length is critically low ($($policy.MinPasswordLength))"+ Impact = 'Extremely vulnerable to brute force'+ }+ }++ # Password History (10 points)+ Write-Host " Password History: $($policy.PasswordHistoryCount)" -ForegroundColor $(+ if ($policy.PasswordHistoryCount -ge 24) { 'Green' }+ elseif ($policy.PasswordHistoryCount -ge 12) { 'Yellow' }+ else { 'Red' }+ )++ if ($policy.PasswordHistoryCount -ge 24) {+ $score += 10+ } elseif ($policy.PasswordHistoryCount -ge 12) {+ $score += 7+ $analysis.Findings += [PSCustomObject]@{+ Severity = 'Low'+ Finding = "Password history count is $($policy.PasswordHistoryCount) (recommended: 24)"+ Impact = 'Users can reuse passwords more frequently'+ }+ } else {+ $score += 3+ $analysis.Findings += [PSCustomObject]@{+ Severity = 'Medium'+ Finding = "Password history count is only $($policy.PasswordHistoryCount)"+ Impact = 'Password reuse is not adequately prevented'+ }+ }++ # Max Password Age (15 points)+ Write-Host " Max Password Age: $($policy.MaxPasswordAge.Days) days" -ForegroundColor $(+ if ($policy.MaxPasswordAge.Days -le 90 -and $policy.MaxPasswordAge.Days -gt 0) { 'Green' }+ elseif ($policy.MaxPasswordAge.Days -le 180) { 'Yellow' }+ else { 'Red' }+ )++ if ($policy.MaxPasswordAge.Days -le 90 -and $policy.MaxPasswordAge.Days -gt 0) {+ $score += 15+ } elseif ($policy.MaxPasswordAge.Days -le 180) {+ $score += 10+ } else {+ $analysis.Findings += [PSCustomObject]@{+ Severity = 'Medium'+ Finding = "Password max age is $($policy.MaxPasswordAge.Days) days"+ Impact = 'Passwords not rotated frequently enough'+ }+ }++ # Lockout Policy (20 points)+ if ($policy.LockoutThreshold -gt 0) {+ Write-Host " Lockout Threshold: $($policy.LockoutThreshold) attempts" -ForegroundColor $(+ if ($policy.LockoutThreshold -le 5) { 'Green' } else { 'Yellow' }+ )++ if ($policy.LockoutThreshold -le 5) {+ $score += 15+ } else {+ $score += 10+ $analysis.Findings += [PSCustomObject]@{+ Severity = 'Low'+ Finding = "Lockout threshold is $($policy.LockoutThreshold) (recommended: 5 or less)"+ Impact = 'More attempts allowed for password guessing'+ }+ }++ Write-Host " Lockout Duration: $($policy.LockoutDuration.TotalMinutes) minutes" -ForegroundColor Green++ if ($policy.LockoutDuration.TotalMinutes -ge 15) {+ $score += 5+ }+ } else {+ Write-Host " - Lockout Policy: Disabled" -ForegroundColor Red+ $analysis.Findings += [PSCustomObject]@{+ Severity = 'High'+ Finding = 'Account lockout policy is disabled'+ Impact = 'No protection against brute force attacks'+ }+ }++ # Reversible Encryption (10 points)+ if ($policy.ReversibleEncryptionEnabled -eq $false) {+ $score += 10+ Write-Host " + Reversible Encryption: Disabled" -ForegroundColor Green+ } else {+ Write-Host " - Reversible Encryption: Enabled" -ForegroundColor Red+ $analysis.Findings += [PSCustomObject]@{+ Severity = 'Critical'+ Finding = 'Reversible encryption is enabled'+ Impact = 'Passwords stored in plaintext-equivalent form'+ }+ }++ $analysis.SecurityScore = $score++ $analysis.DefaultPolicy = [PSCustomObject]@{+ ComplexityEnabled = $policy.ComplexityEnabled+ MinPasswordLength = $policy.MinPasswordLength+ PasswordHistoryCount = $policy.PasswordHistoryCount+ MaxPasswordAge = $policy.MaxPasswordAge.Days+ MinPasswordAge = $policy.MinPasswordAge.Days+ LockoutThreshold = $policy.LockoutThreshold+ LockoutDuration = $policy.LockoutDuration.TotalMinutes+ LockoutObservationWindow = $policy.LockoutObservationWindow.TotalMinutes+ ReversibleEncryptionEnabled = $policy.ReversibleEncryptionEnabled+ DistinguishedName = $policy.DistinguishedName+ }++ # 2. Get Fine-Grained Password Policies+ if ($IncludeFineGrained) {+ Write-Host "`nAnalyzing Fine-Grained Password Policies (PSOs)..." -ForegroundColor Cyan++ try {+ $psos = Get-ADFineGrainedPasswordPolicy -Filter * -Server $Domain++ if ($psos) {+ Write-Host " Found $($psos.Count) Fine-Grained Password Policies" -ForegroundColor Yellow++ foreach ($pso in $psos) {+ $appliesTo = Get-ADFineGrainedPasswordPolicySubject -Identity $pso -Server $Domain++ $psoInfo = [PSCustomObject]@{+ Name = $pso.Name+ Precedence = $pso.Precedence+ ComplexityEnabled = $pso.ComplexityEnabled+ MinPasswordLength = $pso.MinPasswordLength+ PasswordHistoryCount = $pso.PasswordHistoryCount+ MaxPasswordAge = $pso.MaxPasswordAge.Days+ LockoutThreshold = $pso.LockoutThreshold+ AppliesTo = $appliesTo.Count+ AppliesToObjects = $appliesTo.Name -join ', '+ }++ $analysis.FineGrainedPolicies += $psoInfo++ Write-Host "`n PSO: $($pso.Name)" -ForegroundColor White+ Write-Host " Precedence: $($pso.Precedence)" -ForegroundColor Gray+ Write-Host " Min Length: $($pso.MinPasswordLength)" -ForegroundColor Gray+ Write-Host " Applies To: $($appliesTo.Count) objects" -ForegroundColor Gray+ }+ } else {+ Write-Host " No Fine-Grained Password Policies configured" -ForegroundColor Gray+ }+ }+ catch {+ Write-Warning "Could not retrieve Fine-Grained Password Policies: $_"+ }+ }++ # Generate recommendations+ if ($policy.MinPasswordLength -lt 14) {+ $analysis.Recommendations += "Increase minimum password length to 14+ characters"+ }++ if (-not $policy.ComplexityEnabled) {+ $analysis.Recommendations += "Enable password complexity requirements immediately"+ }++ if ($policy.LockoutThreshold -eq 0) {+ $analysis.Recommendations += "Enable account lockout policy (5 attempts recommended)"+ }++ if ($policy.PasswordHistoryCount -lt 24) {+ $analysis.Recommendations += "Increase password history to 24 remembered passwords"+ }++ if ($policy.ReversibleEncryptionEnabled) {+ $analysis.Recommendations += "Disable reversible encryption immediately"+ }++ $analysis.Recommendations += "Consider implementing Fine-Grained Password Policies for privileged accounts"+ $analysis.Recommendations += "Regular password policy audits (quarterly)"++ }+ catch {+ Write-Error "Error analyzing password policies: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== ANALYSIS COMPLETE ===" -ForegroundColor Green++ Write-Host "`nPassword Policy Security Score: $($analysis.SecurityScore)/100" -ForegroundColor $(+ if ($analysis.SecurityScore -ge 80) { 'Green' }+ elseif ($analysis.SecurityScore -ge 60) { 'Yellow' }+ else { 'Red' }+ )++ if ($analysis.Findings.Count -gt 0) {+ Write-Host "`nFindings: $($analysis.Findings.Count)" -ForegroundColor Yellow+ $analysis.Findings | Group-Object Severity | ForEach-Object {+ Write-Host " $($_.Name): $($_.Count)" -ForegroundColor $(+ switch ($_.Name) {+ 'Critical' { 'Red' }+ 'High' { 'Red' }+ 'Medium' { 'Yellow' }+ default { 'White' }+ }+ )+ }+ }++ if ($analysis.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $analysis.Recommendations | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ return $analysis+ }+}\ No newline at end of filediff --git a/ActiveDirectory/Get-ADPrivilegedAccounts.ps1 b/ActiveDirectory/Get-ADPrivilegedAccounts.ps1new file mode 100644index 0000000..99864c4--- /dev/null+++ b/ActiveDirectory/Get-ADPrivilegedAccounts.ps1@@ -0,0 +1,297 @@+function Get-ADPrivilegedAccounts {+ <#+ .SYNOPSIS+ Identifies and analyzes privileged accounts in Active Directory+ .DESCRIPTION+ Discovers privileged accounts including Domain Admins, Enterprise Admins,+ and other high-privilege groups with detailed analysis+ .PARAMETER IncludeNested+ Include nested group memberships+ .PARAMETER CheckLastLogon+ Check last logon time for privileged accounts+ .PARAMETER Domain+ Target domain (default: current domain)+ .EXAMPLE+ Get-ADPrivilegedAccounts+ Get-ADPrivilegedAccounts -IncludeNested -CheckLastLogon+ .OUTPUTS+ PSCustomObject with privileged account information+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$IncludeNested,++ [Parameter()]+ [switch]$CheckLastLogon,++ [Parameter()]+ [string]$Domain+ )++ begin {+ Write-Host "=== PRIVILEGED ACCOUNTS ANALYSIS ===" -ForegroundColor Cyan++ if (-not (Get-Module -ListAvailable -Name ActiveDirectory)) {+ throw "ActiveDirectory module required. Install RSAT tools."+ }++ Import-Module ActiveDirectory -ErrorAction Stop++ if (-not $Domain) {+ $Domain = (Get-ADDomain).DNSRoot+ }++ Write-Host "Domain: $Domain" -ForegroundColor Yellow+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ # Define privileged groups+ $privilegedGroups = @(+ 'Domain Admins',+ 'Enterprise Admins',+ 'Schema Admins',+ 'Administrators',+ 'Account Operators',+ 'Backup Operators',+ 'Server Operators',+ 'Print Operators',+ 'DnsAdmins',+ 'Group Policy Creator Owners'+ )++ $results = [PSCustomObject]@{+ AnalysisDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ Domain = $Domain+ PrivilegedGroups = @()+ PrivilegedAccounts = @()+ Statistics = @{+ TotalPrivilegedAccounts = 0+ EnabledAccounts = 0+ DisabledAccounts = 0+ StaleAccounts = 0+ AccountsWithoutLogon = 0+ }+ Findings = @()+ Recommendations = @()+ }+ }++ process {+ try {+ Write-Host "`nAnalyzing privileged groups..." -ForegroundColor Cyan++ $allPrivilegedUsers = @{}++ foreach ($groupName in $privilegedGroups) {+ try {+ Write-Host "`nChecking: $groupName" -ForegroundColor Yellow++ $group = Get-ADGroup -Filter "Name -eq '$groupName'" -Server $Domain -ErrorAction SilentlyContinue++ if (-not $group) {+ Write-Verbose "Group not found: $groupName"+ continue+ }++ # Get group members+ if ($IncludeNested) {+ $members = Get-ADGroupMember -Identity $group -Recursive -Server $Domain -ErrorAction SilentlyContinue+ } else {+ $members = Get-ADGroupMember -Identity $group -Server $Domain -ErrorAction SilentlyContinue+ }++ $userMembers = @($members | Where-Object { $_.objectClass -eq 'user' })++ Write-Host " Members: $($userMembers.Count)" -ForegroundColor White++ $groupInfo = [PSCustomObject]@{+ GroupName = $groupName+ MemberCount = $userMembers.Count+ Members = @()+ }++ foreach ($member in $userMembers) {+ # Get detailed user info+ $user = Get-ADUser -Identity $member -Properties Enabled, PasswordLastSet, LastLogonDate, whenCreated, AdminCount -Server $Domain++ # Track unique users+ if (-not $allPrivilegedUsers.ContainsKey($user.SamAccountName)) {+ $allPrivilegedUsers[$user.SamAccountName] = @{+ User = $user+ Groups = @()+ }+ }+ $allPrivilegedUsers[$user.SamAccountName].Groups += $groupName++ $memberInfo = [PSCustomObject]@{+ Username = $user.SamAccountName+ DisplayName = $user.Name+ Enabled = $user.Enabled+ Created = $user.whenCreated+ PasswordLastSet = $user.PasswordLastSet+ LastLogon = $user.LastLogonDate+ }++ $groupInfo.Members += $memberInfo++ # Check for issues+ if (-not $user.Enabled) {+ $results.Statistics.DisabledAccounts+++ } else {+ $results.Statistics.EnabledAccounts+++ }++ if ($CheckLastLogon -and $user.LastLogonDate) {+ $daysSinceLogon = (New-TimeSpan -Start $user.LastLogonDate -End (Get-Date)).Days+ if ($daysSinceLogon -gt 90) {+ $results.Statistics.StaleAccounts+++ $results.Findings += [PSCustomObject]@{+ Severity = 'Medium'+ Type = 'Stale Account'+ Account = $user.SamAccountName+ Group = $groupName+ Issue = "Last logon: $daysSinceLogon days ago"+ }+ }+ }++ if (-not $user.LastLogonDate) {+ $results.Statistics.AccountsWithoutLogon+++ }+ }++ $results.PrivilegedGroups += $groupInfo++ # Warn if group has too many members+ if ($groupName -in @('Domain Admins', 'Enterprise Admins') -and $userMembers.Count -gt 5) {+ $results.Findings += [PSCustomObject]@{+ Severity = 'High'+ Type = 'Excessive Membership'+ Group = $groupName+ Issue = "$($userMembers.Count) members (recommended: ≤5)"+ }+ }+ }+ catch {+ Write-Warning "Error processing group $groupName : $_"+ }+ }++ # Process unique privileged accounts+ Write-Host "`nProcessing privileged accounts..." -ForegroundColor Cyan++ foreach ($username in $allPrivilegedUsers.Keys) {+ $userInfo = $allPrivilegedUsers[$username]+ $user = $userInfo.User++ $passwordAge = if ($user.PasswordLastSet) {+ (New-TimeSpan -Start $user.PasswordLastSet -End (Get-Date)).Days+ } else {+ $null+ }++ $lastLogonAge = if ($user.LastLogonDate) {+ (New-TimeSpan -Start $user.LastLogonDate -End (Get-Date)).Days+ } else {+ "Never"+ }++ $accountInfo = [PSCustomObject]@{+ Username = $user.SamAccountName+ DisplayName = $user.Name+ Enabled = $user.Enabled+ Groups = $userInfo.Groups -join ', '+ GroupCount = $userInfo.Groups.Count+ PasswordAge = $passwordAge+ LastLogon = $user.LastLogonDate+ LastLogonAge = $lastLogonAge+ Created = $user.whenCreated+ AdminCount = $user.AdminCount+ }++ $results.PrivilegedAccounts += $accountInfo++ # Check for anomalies+ if ($user.Enabled -and $passwordAge -gt 180) {+ $results.Findings += [PSCustomObject]@{+ Severity = 'High'+ Type = 'Old Password'+ Account = $user.SamAccountName+ Issue = "Password not changed in $passwordAge days"+ }+ }++ if ($userInfo.Groups.Count -gt 3) {+ $results.Findings += [PSCustomObject]@{+ Severity = 'Medium'+ Type = 'Excessive Privileges'+ Account = $user.SamAccountName+ Issue = "Member of $($userInfo.Groups.Count) privileged groups"+ }+ }+ }++ $results.Statistics.TotalPrivilegedAccounts = $allPrivilegedUsers.Count++ # Generate recommendations+ if ($results.Statistics.DisabledAccounts -gt 0) {+ $results.Recommendations += "Remove $($results.Statistics.DisabledAccounts) disabled accounts from privileged groups"+ }++ if ($results.Statistics.StaleAccounts -gt 0) {+ $results.Recommendations += "Review $($results.Statistics.StaleAccounts) stale privileged accounts (90+ days inactive)"+ }++ if ($results.Statistics.TotalPrivilegedAccounts -gt 20) {+ $results.Recommendations += "Reduce total privileged accounts (current: $($results.Statistics.TotalPrivilegedAccounts))"+ }++ $results.Recommendations += "Implement privileged access workstations (PAWs)"+ $results.Recommendations += "Enable MFA for all privileged accounts"+ $results.Recommendations += "Regular privileged account audits (quarterly)"++ }+ catch {+ Write-Error "Error analyzing privileged accounts: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== ANALYSIS COMPLETE ===" -ForegroundColor Green++ Write-Host "`nStatistics:" -ForegroundColor Cyan+ Write-Host " Total Privileged Accounts: $($results.Statistics.TotalPrivilegedAccounts)" -ForegroundColor White+ Write-Host " Enabled: $($results.Statistics.EnabledAccounts)" -ForegroundColor Green+ Write-Host " Disabled: $($results.Statistics.DisabledAccounts)" -ForegroundColor Yellow+ Write-Host " Stale (90+ days): $($results.Statistics.StaleAccounts)" -ForegroundColor Red++ Write-Host "`nTop Privileged Groups:" -ForegroundColor Cyan+ $results.PrivilegedGroups | Sort-Object -Property MemberCount -Descending | Select-Object -First 5 | ForEach-Object {+ Write-Host " $($_.GroupName): $($_.MemberCount) members" -ForegroundColor White+ }++ if ($results.Findings.Count -gt 0) {+ Write-Host "`nFindings: $($results.Findings.Count)" -ForegroundColor Yellow+ $results.Findings | Group-Object Severity | ForEach-Object {+ Write-Host " $($_.Name): $($_.Count)" -ForegroundColor $(+ switch ($_.Name) {+ 'High' { 'Red' }+ 'Medium' { 'Yellow' }+ default { 'White' }+ }+ )+ }+ }++ if ($results.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $results.Recommendations | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ return $results+ }+}\ No newline at end of filediff --git a/ActiveDirectory/Test-ADSecurityPosture.ps1 b/ActiveDirectory/Test-ADSecurityPosture.ps1new file mode 100644index 0000000..8488ef6--- /dev/null+++ b/ActiveDirectory/Test-ADSecurityPosture.ps1@@ -0,0 +1,341 @@+function Test-ADSecurityPosture {+ <#+ .SYNOPSIS+ Performs comprehensive Active Directory security assessment+ .DESCRIPTION+ Tests AD security posture including domain policies, GPO settings,+ trust relationships, and overall security configuration+ .PARAMETER Domain+ Target domain+ .PARAMETER IncludeTrusts+ Check domain trusts+ .PARAMETER IncludeGPO+ Analyze Group Policy Objects+ .EXAMPLE+ Test-ADSecurityPosture+ Test-ADSecurityPosture -IncludeTrusts -IncludeGPO+ .OUTPUTS+ PSCustomObject with security posture assessment+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [string]$Domain,++ [Parameter()]+ [switch]$IncludeTrusts,++ [Parameter()]+ [switch]$IncludeGPO+ )++ begin {+ Write-Host "=== AD SECURITY POSTURE ASSESSMENT ===" -ForegroundColor Cyan++ if (-not (Get-Module -ListAvailable -Name ActiveDirectory)) {+ throw "ActiveDirectory module required"+ }++ Import-Module ActiveDirectory -ErrorAction Stop++ if (-not $Domain) {+ $Domain = (Get-ADDomain).DNSRoot+ }++ Write-Host "Domain: $Domain" -ForegroundColor Yellow++ $assessment = [PSCustomObject]@{+ AssessmentDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ Domain = $Domain+ SecurityScore = 0+ MaxScore = 100+ Categories = @{+ PasswordPolicy = @{}+ AccountPolicy = @{}+ DomainControllers = @{}+ Trusts = @{}+ GPOs = @{}+ }+ Findings = @()+ Recommendations = @()+ }+ }++ process {+ try {+ # 1. Password Policy Assessment+ Write-Host "`n[1/5] Assessing Password Policy..." -ForegroundColor Cyan++ $passwordPolicy = Get-ADDefaultDomainPasswordPolicy -Server $Domain+ $score = 0+ $maxPolicyScore = 25++ if ($passwordPolicy.ComplexityEnabled) {+ $score += 10+ Write-Host " + Complexity: Enabled" -ForegroundColor Green+ } else {+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'Critical'+ Category = 'Password Policy'+ Finding = 'Password complexity is disabled'+ }+ Write-Host " - Complexity: Disabled" -ForegroundColor Red+ }++ if ($passwordPolicy.MinPasswordLength -ge 14) {+ $score += 10+ Write-Host " + Min Length: $($passwordPolicy.MinPasswordLength) chars" -ForegroundColor Green+ } elseif ($passwordPolicy.MinPasswordLength -ge 12) {+ $score += 7+ Write-Host " ~ Min Length: $($passwordPolicy.MinPasswordLength) chars (recommended: 14+)" -ForegroundColor Yellow+ } else {+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'High'+ Category = 'Password Policy'+ Finding = "Minimum password length is only $($passwordPolicy.MinPasswordLength) characters"+ }+ Write-Host " - Min Length: $($passwordPolicy.MinPasswordLength) chars" -ForegroundColor Red+ }++ if ($passwordPolicy.MaxPasswordAge.Days -le 90 -and $passwordPolicy.MaxPasswordAge.Days -gt 0) {+ $score += 5+ Write-Host " + Max Age: $($passwordPolicy.MaxPasswordAge.Days) days" -ForegroundColor Green+ } else {+ Write-Host " ~ Max Age: $($passwordPolicy.MaxPasswordAge.Days) days" -ForegroundColor Yellow+ }++ $assessment.Categories.PasswordPolicy = @{+ Score = $score+ MaxScore = $maxPolicyScore+ ComplexityEnabled = $passwordPolicy.ComplexityEnabled+ MinPasswordLength = $passwordPolicy.MinPasswordLength+ MaxPasswordAge = $passwordPolicy.MaxPasswordAge.Days+ MinPasswordAge = $passwordPolicy.MinPasswordAge.Days+ PasswordHistoryCount = $passwordPolicy.PasswordHistoryCount+ }++ $assessment.SecurityScore += $score++ # 2. Account Lockout Policy+ Write-Host "`n[2/5] Assessing Account Lockout Policy..." -ForegroundColor Cyan++ $lockoutScore = 0+ $maxLockoutScore = 15++ if ($passwordPolicy.LockoutThreshold -gt 0) {+ if ($passwordPolicy.LockoutThreshold -le 5) {+ $lockoutScore += 10+ Write-Host " + Lockout Threshold: $($passwordPolicy.LockoutThreshold) attempts" -ForegroundColor Green+ } else {+ $lockoutScore += 5+ Write-Host " ~ Lockout Threshold: $($passwordPolicy.LockoutThreshold) attempts" -ForegroundColor Yellow+ }++ if ($passwordPolicy.LockoutDuration.TotalMinutes -ge 15) {+ $lockoutScore += 5+ Write-Host " + Lockout Duration: $($passwordPolicy.LockoutDuration.TotalMinutes) minutes" -ForegroundColor Green+ }+ } else {+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'High'+ Category = 'Account Policy'+ Finding = 'Account lockout is disabled'+ }+ Write-Host " - Account Lockout: Disabled" -ForegroundColor Red+ }++ $assessment.Categories.AccountPolicy = @{+ Score = $lockoutScore+ MaxScore = $maxLockoutScore+ LockoutThreshold = $passwordPolicy.LockoutThreshold+ LockoutDuration = $passwordPolicy.LockoutDuration.TotalMinutes+ LockoutWindow = $passwordPolicy.LockoutObservationWindow.TotalMinutes+ }++ $assessment.SecurityScore += $lockoutScore++ # 3. Domain Controllers+ Write-Host "`n[3/5] Checking Domain Controllers..." -ForegroundColor Cyan++ $dcs = Get-ADDomainController -Filter * -Server $Domain+ $dcScore = 0+ $maxDCScore = 20++ Write-Host " Found $($dcs.Count) Domain Controllers" -ForegroundColor White++ foreach ($dc in $dcs) {+ if ($dc.IsReadOnly) {+ Write-Host " ~ $($dc.Name) [RODC]" -ForegroundColor Yellow+ } else {+ Write-Host " + $($dc.Name)" -ForegroundColor Green+ }+ }++ if ($dcs.Count -ge 2) {+ $dcScore += 10+ }++ # Check for Server 2012 or older+ foreach ($dc in $dcs) {+ $os = $dc.OperatingSystem+ if ($os -match "2012|2008") {+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'High'+ Category = 'Domain Controllers'+ Finding = "$($dc.Name) running unsupported OS: $os"+ }+ }+ }++ $dcScore += 10+ $assessment.Categories.DomainControllers = @{+ Score = $dcScore+ MaxScore = $maxDCScore+ Count = $dcs.Count+ Controllers = $dcs.Name+ }++ $assessment.SecurityScore += $dcScore++ # 4. Domain Trusts+ if ($IncludeTrusts) {+ Write-Host "`n[4/5] Analyzing Domain Trusts..." -ForegroundColor Cyan++ $trusts = Get-ADTrust -Filter * -Server $Domain+ $trustScore = 0+ $maxTrustScore = 20++ if ($trusts) {+ Write-Host " Found $($trusts.Count) trust(s)" -ForegroundColor White++ foreach ($trust in $trusts) {+ $trustType = $trust.Direction+ $trustColor = if ($trust.Direction -eq 'Bidirectional') { 'Yellow' } else { 'Green' }++ Write-Host " $($trust.Name) [$trustType]" -ForegroundColor $trustColor++ if ($trust.Direction -eq 'Bidirectional') {+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'Medium'+ Category = 'Trusts'+ Finding = "Bidirectional trust with $($trust.Name)"+ }+ }+ }++ $trustScore += 10+ } else {+ Write-Host " No domain trusts configured" -ForegroundColor Green+ $trustScore += 20+ }++ $assessment.Categories.Trusts = @{+ Score = $trustScore+ MaxScore = $maxTrustScore+ Count = $trusts.Count+ Trusts = $trusts+ }++ $assessment.SecurityScore += $trustScore+ }++ # 5. GPO Analysis+ if ($IncludeGPO) {+ Write-Host "`n[5/5] Analyzing Group Policy Objects..." -ForegroundColor Cyan++ $gpos = Get-GPO -All -Domain $Domain+ $gpoScore = 0+ $maxGPOScore = 20++ Write-Host " Found $($gpos.Count) GPOs" -ForegroundColor White++ # Check for unlinked GPOs+ $unlinkedGPOs = @($gpos | Where-Object {+ (Get-GPOReport -Guid $_.Id -ReportType Xml -Domain $Domain) -notmatch '<LinksTo>'+ })++ if ($unlinkedGPOs.Count -gt 0) {+ Write-Host " ~ $($unlinkedGPOs.Count) unlinked GPOs found" -ForegroundColor Yellow+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'Low'+ Category = 'GPO'+ Finding = "$($unlinkedGPOs.Count) unlinked GPOs (cleanup recommended)"+ }+ }++ $gpoScore += 20+ $assessment.Categories.GPOs = @{+ Score = $gpoScore+ MaxScore = $maxGPOScore+ TotalCount = $gpos.Count+ UnlinkedCount = $unlinkedGPOs.Count+ }++ $assessment.SecurityScore += $gpoScore+ }++ # Calculate final score+ $assessment.SecurityScore = [math]::Round(($assessment.SecurityScore / $assessment.MaxScore) * 100, 0)++ # Generate recommendations+ if ($passwordPolicy.MinPasswordLength -lt 14) {+ $assessment.Recommendations += "Increase minimum password length to 14+ characters"+ }++ if ($passwordPolicy.LockoutThreshold -eq 0) {+ $assessment.Recommendations += "Enable account lockout policy (5 attempts recommended)"+ }++ $assessment.Recommendations += "Implement tiered administrative model"+ $assessment.Recommendations += "Enable audit policies for AD changes"+ $assessment.Recommendations += "Regular security assessments (quarterly)"++ }+ catch {+ Write-Error "Error during AD security assessment: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== ASSESSMENT COMPLETE ===" -ForegroundColor Green++ Write-Host "`nSecurity Score: $($assessment.SecurityScore)/100" -ForegroundColor $(+ if ($assessment.SecurityScore -ge 80) { 'Green' }+ elseif ($assessment.SecurityScore -ge 60) { 'Yellow' }+ else { 'Red' }+ )++ Write-Host "`nCategory Scores:" -ForegroundColor Cyan+ foreach ($category in $assessment.Categories.PSObject.Properties) {+ if ($category.Value.Score -ne $null) {+ $percentage = [math]::Round(($category.Value.Score / $category.Value.MaxScore) * 100, 0)+ Write-Host " $($category.Name): $percentage%" -ForegroundColor White+ }+ }++ if ($assessment.Findings.Count -gt 0) {+ Write-Host "`nFindings: $($assessment.Findings.Count)" -ForegroundColor Yellow+ $assessment.Findings | Group-Object Severity | ForEach-Object {+ Write-Host " $($_.Name): $($_.Count)" -ForegroundColor $(+ switch ($_.Name) {+ 'Critical' { 'Red' }+ 'High' { 'Red' }+ 'Medium' { 'Yellow' }+ default { 'White' }+ }+ )+ }+ }++ if ($assessment.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $assessment.Recommendations | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ return $assessment+ }+}\ No newline at end of filediff --git a/Analysis/Get-EventLogAnalysis.ps1 b/Analysis/Get-EventLogAnalysis.ps1new file mode 100644index 0000000..7cb11f0--- /dev/null+++ b/Analysis/Get-EventLogAnalysis.ps1@@ -0,0 +1,224 @@+function Get-EventLogAnalysis {+ <#+ .SYNOPSIS+ Performs comprehensive analysis of Windows Event Logs+ .DESCRIPTION+ Analyzes Security, System, and Application event logs for security-relevant events,+ anomalies, and patterns indicating potential compromise+ .PARAMETER Hours+ Number of hours to analyze (default: 24)+ .PARAMETER LogNames+ Specific log names to analyze (default: Security, System, Application)+ .PARAMETER IncludeWarnings+ Include warning-level events in analysis+ .PARAMETER ExportPath+ Path to export detailed results+ .EXAMPLE+ Get-EventLogAnalysis+ Get-EventLogAnalysis -Hours 48 -IncludeWarnings -ExportPath "C:\Audits"+ .OUTPUTS+ PSCustomObject with event log analysis results+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [int]$Hours = 24,++ [Parameter()]+ [string[]]$LogNames = @('Security', 'System', 'Application'),++ [Parameter()]+ [switch]$IncludeWarnings,++ [Parameter()]+ [string]$ExportPath+ )++ begin {+ Write-Host "Analyzing event logs (last $Hours hours)..." -ForegroundColor Cyan++ $results = [PSCustomObject]@{+ AnalysisDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ TimeRange = "$Hours hours"+ SecurityEvents = @()+ SystemEvents = @()+ ApplicationEvents = @()+ CriticalErrors = @()+ ServiceChanges = @()+ PolicyChanges = @()+ AccountChanges = @()+ Statistics = @{+ TotalEventsAnalyzed = 0+ CriticalEvents = 0+ ErrorEvents = 0+ WarningEvents = 0+ SecurityAlerts = 0+ }+ }++ $startTime = (Get-Date).AddHours(-$Hours)++ # Critical Event IDs to monitor+ $criticalEventIDs = @{+ # Security Events+ 1102 = 'Audit log cleared'+ 4719 = 'System audit policy changed'+ 4720 = 'User account created'+ 4722 = 'User account enabled'+ 4724 = 'Password reset attempted'+ 4725 = 'User account disabled'+ 4726 = 'User account deleted'+ 4732 = 'Member added to security group'+ 4733 = 'Member removed from security group'+ 4738 = 'User account changed'+ 4740 = 'User account locked out'+ 4756 = 'Member added to universal security group'+ 4625 = 'Failed logon'+ 4648 = 'Logon with explicit credentials'+ 4697 = 'Service installed'+ 4698 = 'Scheduled task created'+ 4699 = 'Scheduled task deleted'+ 4700 = 'Scheduled task enabled'+ 4701 = 'Scheduled task disabled'++ # System Events+ 7045 = 'Service installed'+ 7040 = 'Service start type changed'+ 7036 = 'Service state changed'+ 6005 = 'Event log service started'+ 6006 = 'Event log service stopped'+ 1074 = 'System shutdown/restart'+ 6008 = 'Unexpected shutdown'+ 41 = 'System rebooted without clean shutdown'+ }+ }++ process {+ try {+ foreach ($logName in $LogNames) {+ Write-Verbose "Analyzing $logName log..."++ # Get events based on severity+ $filterLevels = @(1, 2) # Critical and Error+ if ($IncludeWarnings) {+ $filterLevels += 3 # Warning+ }++ try {+ $events = Get-WinEvent -FilterHashtable @{+ LogName = $logName+ Level = $filterLevels+ StartTime = $startTime+ } -ErrorAction SilentlyContinue++ if ($events) {+ $results.Statistics.TotalEventsAnalyzed += $events.Count++ foreach ($event in $events) {+ # Count by level+ switch ($event.Level) {+ 1 { $results.Statistics.CriticalEvents++ }+ 2 { $results.Statistics.ErrorEvents++ }+ 3 { $results.Statistics.WarningEvents++ }+ }++ # Check if this is a critical event ID+ $isCritical = $criticalEventIDs.ContainsKey($event.Id)++ $eventObj = [PSCustomObject]@{+ TimeCreated = $event.TimeCreated+ LogName = $event.LogName+ Source = $event.ProviderName+ EventId = $event.Id+ Level = switch ($event.Level) {+ 1 { 'Critical' }+ 2 { 'Error' }+ 3 { 'Warning' }+ 4 { 'Information' }+ default { 'Unknown' }+ }+ Message = $event.Message+ Description = if ($isCritical) { $criticalEventIDs[$event.Id] } else { $null }+ IsCritical = $isCritical+ }++ # Categorize events+ if ($logName -eq 'Security') {+ $results.SecurityEvents += $eventObj++ # Specific categorization for security events+ switch ($event.Id) {+ { $_ -in @(4720, 4722, 4724, 4725, 4726, 4738, 4740) } {+ $results.AccountChanges += $eventObj+ $results.Statistics.SecurityAlerts+++ }+ { $_ -in @(4719, 1102) } {+ $results.PolicyChanges += $eventObj+ $results.Statistics.SecurityAlerts+++ }+ { $_ -in @(4697, 7045) } {+ $results.ServiceChanges += $eventObj+ $results.Statistics.SecurityAlerts+++ }+ }+ }+ elseif ($logName -eq 'System') {+ $results.SystemEvents += $eventObj++ # Service changes+ if ($event.Id -in @(7045, 7040, 7036)) {+ $results.ServiceChanges += $eventObj+ }+ }+ elseif ($logName -eq 'Application') {+ $results.ApplicationEvents += $eventObj+ }++ # Critical errors+ if ($event.Level -eq 1 -or $isCritical) {+ $results.CriticalErrors += $eventObj+ }+ }+ }+ }+ catch {+ Write-Warning "Could not access $logName log: $_"+ }+ }++ }+ catch {+ Write-Error "Error during event log analysis: $_"+ throw+ }+ }++ end {+ # Display summary+ Write-Host "`nEvent Log Analysis Complete!" -ForegroundColor Green+ Write-Host "`n=== Statistics ===" -ForegroundColor Cyan+ Write-Host "Total events analyzed: $($results.Statistics.TotalEventsAnalyzed)" -ForegroundColor Yellow+ Write-Host "Critical events: $($results.Statistics.CriticalEvents)" -ForegroundColor Red+ Write-Host "Error events: $($results.Statistics.ErrorEvents)" -ForegroundColor Yellow+ Write-Host "Warning events: $($results.Statistics.WarningEvents)" -ForegroundColor Yellow+ Write-Host "Security alerts: $($results.Statistics.SecurityAlerts)" -ForegroundColor $(if ($results.Statistics.SecurityAlerts -gt 0) { 'Red' } else { 'Green' })++ Write-Host "`n=== Critical Findings ===" -ForegroundColor Cyan+ Write-Host "Account changes: $($results.AccountChanges.Count)" -ForegroundColor Yellow+ Write-Host "Policy changes: $($results.PolicyChanges.Count)" -ForegroundColor Yellow+ Write-Host "Service changes: $($results.ServiceChanges.Count)" -ForegroundColor Yellow++ # Export if requested+ if ($ExportPath) {+ if (-not (Test-Path $ExportPath)) {+ New-Item -Path $ExportPath -ItemType Directory -Force | Out-Null+ }+ $exportFile = Join-Path -Path $ExportPath -ChildPath "EventLogAnalysis_$(Get-Date -Format 'yyyyMMdd_HHmmss').json"+ $results | ConvertTo-Json -Depth 5 | Out-File -FilePath $exportFile -Encoding UTF8+ Write-Host "`nResults exported to: $exportFile" -ForegroundColor Cyan+ }++ return $results+ }+}\ No newline at end of filediff --git a/Analysis/Get-FileSystemAnalysis.ps1 b/Analysis/Get-FileSystemAnalysis.ps1new file mode 100644index 0000000..de551f7--- /dev/null+++ b/Analysis/Get-FileSystemAnalysis.ps1@@ -0,0 +1,279 @@+function Get-FileSystemAnalysis {+ <#+ .SYNOPSIS+ Analyzes file system for suspicious files and activities+ .DESCRIPTION+ Scans directories for malicious files, unauthorized changes, and suspicious patterns+ .PARAMETER Path+ Path to scan (default: system-critical directories)+ .PARAMETER Recursive+ Scan subdirectories recursively+ .PARAMETER CheckRecent+ Check for recently created/modified files+ .PARAMETER Hours+ Hours to look back for recent files (default: 24)+ .PARAMETER ExportPath+ Path to export detailed results+ .EXAMPLE+ Get-FileSystemAnalysis+ Get-FileSystemAnalysis -Path "C:\Windows\System32" -Recursive -CheckRecent -Hours 48+ .OUTPUTS+ PSCustomObject with file system analysis results+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [string]$Path,++ [Parameter()]+ [switch]$Recursive,++ [Parameter()]+ [switch]$CheckRecent,++ [Parameter()]+ [int]$Hours = 24,++ [Parameter()]+ [string]$ExportPath+ )++ begin {+ Write-Host "Analyzing file system..." -ForegroundColor Cyan++ $results = [PSCustomObject]@{+ AnalysisDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ SuspiciousFiles = @()+ RecentFiles = @()+ HiddenFiles = @()+ ExecutablesInTemp = @()+ AlternateDataStreams = @()+ Statistics = @{+ FilesScanned = 0+ SuspiciousFiles = 0+ RecentFiles = 0+ HiddenFiles = 0+ ADSFound = 0+ }+ }++ # Default critical paths to scan if none specified+ if (-not $Path) {+ $scanPaths = @(+ "$env:SystemRoot\Temp",+ "$env:TEMP",+ "$env:LOCALAPPDATA\Temp",+ "$env:PUBLIC",+ "$env:ProgramData"+ )+ }+ else {+ $scanPaths = @($Path)+ }++ # Suspicious file extensions+ $suspiciousExtensions = @(+ '.exe', '.dll', '.bat', '.cmd', '.vbs', '.js', '.ps1',+ '.scr', '.com', '.pif', '.hta', '.msi', '.jar'+ )++ # Known malicious file names+ $maliciousNames = @(+ 'mimikatz', 'procdump', 'psexec', 'netcat', 'nc.exe',+ 'pwdump', 'fgdump', 'wce.exe', 'gsecdump', 'lsass.dmp'+ )++ $startTime = (Get-Date).AddHours(-$Hours)+ }++ process {+ try {+ foreach ($scanPath in $scanPaths) {+ if (-not (Test-Path $scanPath)) {+ Write-Warning "Path does not exist: $scanPath"+ continue+ }++ Write-Verbose "Scanning path: $scanPath"++ # Get files+ $getChildParams = @{+ Path = $scanPath+ File = $true+ Force = $true+ ErrorAction = 'SilentlyContinue'+ }++ if ($Recursive) {+ $getChildParams.Recurse = $true+ }++ $files = Get-ChildItem @getChildParams++ foreach ($file in $files) {+ try {+ $results.Statistics.FilesScanned++++ $isSuspicious = $false+ $reasons = @()++ # Check 1: Hidden files+ if ($file.Attributes -match 'Hidden') {+ $results.HiddenFiles += [PSCustomObject]@{+ Path = $file.FullName+ Name = $file.Name+ Size = [math]::Round($file.Length / 1KB, 2)+ Created = $file.CreationTime+ Modified = $file.LastWriteTime+ }+ $results.Statistics.HiddenFiles+++ $isSuspicious = $true+ $reasons += "Hidden file attribute"+ }++ # Check 2: Malicious file names+ foreach ($malName in $maliciousNames) {+ if ($file.Name -match $malName) {+ $isSuspicious = $true+ $reasons += "Matches known malicious filename: $malName"+ break+ }+ }++ # Check 3: Executables in temp directories+ if ($file.Extension -in $suspiciousExtensions -and+ $file.DirectoryName -match '(Temp|tmp|Temporary)') {+ $results.ExecutablesInTemp += [PSCustomObject]@{+ Path = $file.FullName+ Name = $file.Name+ Extension = $file.Extension+ Size = [math]::Round($file.Length / 1KB, 2)+ Created = $file.CreationTime+ }+ $isSuspicious = $true+ $reasons += "Executable in temporary directory"+ }++ # Check 4: Double extensions+ if ($file.Name -match '\.[^.]+\.[^.]+$') {+ $extensions = $file.Name -split '\.'+ if ($extensions.Count -gt 2) {+ $isSuspicious = $true+ $reasons += "Multiple file extensions (possible masquerading)"+ }+ }++ # Check 5: Very recent files+ if ($CheckRecent -and $file.CreationTime -gt $startTime) {+ $results.RecentFiles += [PSCustomObject]@{+ Path = $file.FullName+ Name = $file.Name+ Size = [math]::Round($file.Length / 1KB, 2)+ Created = $file.CreationTime+ Modified = $file.LastWriteTime+ }+ $results.Statistics.RecentFiles+++ }++ # Check 6: Alternate Data Streams (ADS)+ try {+ $streams = Get-Item -Path $file.FullName -Stream * -ErrorAction SilentlyContinue |+ Where-Object { $_.Stream -ne ':$DATA' }++ if ($streams) {+ foreach ($stream in $streams) {+ $results.AlternateDataStreams += [PSCustomObject]@{+ FilePath = $file.FullName+ FileName = $file.Name+ StreamName = $stream.Stream+ StreamSize = $stream.Length+ }+ $results.Statistics.ADSFound+++ $isSuspicious = $true+ $reasons += "Contains alternate data stream: $($stream.Stream)"+ }+ }+ }+ catch {+ # ADS check failed+ }++ # Check 7: Suspicious size (very small or very large executables)+ if ($file.Extension -in @('.exe', '.dll')) {+ if ($file.Length -lt 10KB) {+ $isSuspicious = $true+ $reasons += "Unusually small executable (<10KB)"+ }+ elseif ($file.Length -gt 50MB) {+ $isSuspicious = $true+ $reasons += "Unusually large executable (>50MB)"+ }+ }++ # Check 8: No company/product information+ if ($file.Extension -in @('.exe', '.dll')) {+ try {+ $versionInfo = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($file.FullName)+ if ([string]::IsNullOrEmpty($versionInfo.CompanyName) -and+ [string]::IsNullOrEmpty($versionInfo.ProductName)) {+ $isSuspicious = $true+ $reasons += "No company or product information"+ }+ }+ catch {+ # Version info check failed+ }+ }++ # Add to suspicious files if flagged+ if ($isSuspicious) {+ $results.SuspiciousFiles += [PSCustomObject]@{+ Path = $file.FullName+ Name = $file.Name+ Extension = $file.Extension+ Size = [math]::Round($file.Length / 1KB, 2)+ Created = $file.CreationTime+ Modified = $file.LastWriteTime+ Attributes = $file.Attributes+ Reasons = ($reasons -join '; ')+ }+ $results.Statistics.SuspiciousFiles+++ }++ }+ catch {+ Write-Verbose "Error analyzing file $($file.Name): $_"+ }+ }+ }++ }+ catch {+ Write-Error "Error during file system analysis: $_"+ throw+ }+ }++ end {+ Write-Host "`nFile System Analysis Complete!" -ForegroundColor Green+ Write-Host "`n=== Statistics ===" -ForegroundColor Cyan+ Write-Host "Files scanned: $($results.Statistics.FilesScanned)" -ForegroundColor Yellow+ Write-Host "Suspicious files: $($results.Statistics.SuspiciousFiles)" -ForegroundColor $(if ($results.Statistics.SuspiciousFiles -gt 0) { 'Red' } else { 'Green' })+ Write-Host "Hidden files: $($results.Statistics.HiddenFiles)" -ForegroundColor Yellow+ Write-Host "Recent files: $($results.Statistics.RecentFiles)" -ForegroundColor Yellow+ Write-Host "Alternate data streams: $($results.Statistics.ADSFound)" -ForegroundColor $(if ($results.Statistics.ADSFound -gt 0) { 'Yellow' } else { 'Green' })++ # Export if requested+ if ($ExportPath) {+ if (-not (Test-Path $ExportPath)) {+ New-Item -Path $ExportPath -ItemType Directory -Force | Out-Null+ }+ $exportFile = Join-Path -Path $ExportPath -ChildPath "FileSystemAnalysis_$(Get-Date -Format 'yyyyMMdd_HHmmss').json"+ $results | ConvertTo-Json -Depth 5 | Out-File -FilePath $exportFile -Encoding UTF8+ Write-Host "`nResults exported to: $exportFile" -ForegroundColor Cyan+ }++ return $results+ }+}\ No newline at end of filediff --git a/Analysis/Get-MemoryAnalysis.ps1 b/Analysis/Get-MemoryAnalysis.ps1new file mode 100644index 0000000..9fc96e0--- /dev/null+++ b/Analysis/Get-MemoryAnalysis.ps1@@ -0,0 +1,261 @@+function Get-MemoryAnalysis {+ <#+ .SYNOPSIS+ Analyzes process memory for suspicious indicators+ .DESCRIPTION+ Examines running processes for memory-based threats including code injection,+ hollowing, and suspicious memory patterns+ .PARAMETER ProcessId+ Specific process ID to analyze (optional)+ .PARAMETER CheckAllProcesses+ Analyze all running processes+ .PARAMETER IncludeStrings+ Extract suspicious strings from process memory+ .EXAMPLE+ Get-MemoryAnalysis -CheckAllProcesses+ Get-MemoryAnalysis -ProcessId 1234 -IncludeStrings+ .OUTPUTS+ PSCustomObject with memory analysis results+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [int]$ProcessId,++ [Parameter()]+ [switch]$CheckAllProcesses,++ [Parameter()]+ [switch]$IncludeStrings+ )++ begin {+ Write-Host "Analyzing process memory..." -ForegroundColor Cyan++ # Check for admin privileges+ $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ if (-not $isAdmin) {+ Write-Warning "Administrator privileges recommended for complete memory analysis"+ }++ $results = [PSCustomObject]@{+ AnalysisDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ProcessAnalysis = @()+ InjectionIndicators = @()+ HollowingIndicators = @()+ SuspiciousModules = @()+ Statistics = @{+ ProcessesAnalyzed = 0+ InjectionIndicators = 0+ HollowingIndicators = 0+ SuspiciousModules = 0+ }+ }++ # Suspicious module names+ $suspiciousModulePatterns = @(+ 'inject', 'hook', 'reflective', 'payload', 'shellcode',+ 'mimikatz', 'meterpreter', 'cobalt', 'beacon'+ )+ }++ process {+ try {+ $processesToAnalyze = @()++ if ($ProcessId) {+ $proc = Get-Process -Id $ProcessId -ErrorAction SilentlyContinue+ if ($proc) {+ $processesToAnalyze += $proc+ }+ else {+ Write-Error "Process with ID $ProcessId not found"+ return+ }+ }+ elseif ($CheckAllProcesses) {+ $processesToAnalyze = Get-Process | Where-Object { $_.Id -ne 0 -and $_.Id -ne 4 }+ }+ else {+ Write-Warning "No process specified. Use -ProcessId or -CheckAllProcesses"+ return+ }++ foreach ($process in $processesToAnalyze) {+ try {+ $results.Statistics.ProcessesAnalyzed+++ Write-Verbose "Analyzing process: $($process.ProcessName) (PID: $($process.Id))"++ $processAnalysis = [PSCustomObject]@{+ ProcessName = $process.ProcessName+ ProcessId = $process.Id+ Path = $process.Path+ StartTime = $process.StartTime+ Threads = $process.Threads.Count+ Modules = @()+ MemorySize = [math]::Round($process.WorkingSet64 / 1MB, 2)+ VirtualMemorySize = [math]::Round($process.VirtualMemorySize64 / 1MB, 2)+ PrivateMemorySize = [math]::Round($process.PrivateMemorySize64 / 1MB, 2)+ Findings = @()+ }++ # Get loaded modules+ try {+ $modules = $process.Modules+ foreach ($module in $modules) {+ $moduleName = $module.ModuleName.ToLower()+ $modulePath = $module.FileName++ # Check for suspicious modules+ $isSuspicious = $false+ $reason = ""++ foreach ($pattern in $suspiciousModulePatterns) {+ if ($moduleName -match $pattern) {+ $isSuspicious = $true+ $reason = "Module name matches suspicious pattern: $pattern"+ break+ }+ }++ # Check for modules loaded from suspicious locations+ if ($modulePath -match '(temp|appdata\\local\\temp|users\\public)') {+ $isSuspicious = $true+ $reason = "Module loaded from suspicious location"+ }++ if ($isSuspicious) {+ $results.SuspiciousModules += [PSCustomObject]@{+ ProcessName = $process.ProcessName+ ProcessId = $process.Id+ ModuleName = $moduleName+ ModulePath = $modulePath+ Reason = $reason+ }+ $results.Statistics.SuspiciousModules+++ }++ $processAnalysis.Modules += [PSCustomObject]@{+ Name = $moduleName+ Path = $modulePath+ Size = [math]::Round($module.Size / 1KB, 2)+ Suspicious = $isSuspicious+ }+ }+ }+ catch {+ Write-Verbose "Could not enumerate modules for $($process.ProcessName): $_"+ }++ # Check for process hollowing indicators+ # Look for mismatches between process image and memory+ if ($process.Path) {+ try {+ $mainModule = $process.MainModule++ # Compare main module with process path+ if ($mainModule.FileName -ne $process.Path) {+ $results.HollowingIndicators += [PSCustomObject]@{+ ProcessName = $process.ProcessName+ ProcessId = $process.Id+ ExpectedPath = $process.Path+ ActualPath = $mainModule.FileName+ Reason = "Main module path mismatch - possible process hollowing"+ }+ $results.Statistics.HollowingIndicators+++ $processAnalysis.Findings += "Possible process hollowing detected"+ }+ }+ catch {+ Write-Verbose "Could not check main module for $($process.ProcessName)"+ }+ }++ # Check for code injection indicators+ # Unusual memory characteristics+ $memoryRatio = if ($process.VirtualMemorySize64 -gt 0) {+ $process.WorkingSet64 / $process.VirtualMemorySize64+ } else { 0 }++ if ($memoryRatio -gt 0.9) {+ $results.InjectionIndicators += [PSCustomObject]@{+ ProcessName = $process.ProcessName+ ProcessId = $process.Id+ Indicator = "High memory ratio"+ Value = [math]::Round($memoryRatio, 2)+ Reason = "Unusually high working set to virtual memory ratio - possible injection"+ }+ $results.Statistics.InjectionIndicators+++ $processAnalysis.Findings += "Unusual memory characteristics"+ }++ # Check for suspicious thread count+ $threadCount = $process.Threads.Count+ if ($threadCount -gt 100) {+ $processAnalysis.Findings += "Unusually high thread count: $threadCount"+ }++ # Check for remote threads+ try {+ foreach ($thread in $process.Threads) {+ # Remote threads often have start addresses outside main module+ if ($thread.StartAddress -and $process.MainModule) {+ $moduleBase = $process.MainModule.BaseAddress.ToInt64()+ $moduleEnd = $moduleBase + $process.MainModule.ModuleMemorySize+ $startAddr = $thread.StartAddress.ToInt64()++ if ($startAddr -lt $moduleBase -or $startAddr -gt $moduleEnd) {+ $results.InjectionIndicators += [PSCustomObject]@{+ ProcessName = $process.ProcessName+ ProcessId = $process.Id+ Indicator = "Remote thread detected"+ ThreadId = $thread.Id+ Reason = "Thread start address outside main module - possible remote injection"+ }+ $results.Statistics.InjectionIndicators+++ break # Only report once per process+ }+ }+ }+ }+ catch {+ Write-Verbose "Could not analyze threads for $($process.ProcessName)"+ }++ # Extract strings from memory if requested (basic implementation)+ if ($IncludeStrings) {+ try {+ # This is a simplified version - full string extraction requires more complex memory reading+ $processAnalysis.Findings += "String extraction requires external tools like Sysinternals Strings"+ }+ catch {+ Write-Verbose "Could not extract strings from $($process.ProcessName)"+ }+ }++ $results.ProcessAnalysis += $processAnalysis+ }+ catch {+ Write-Verbose "Error analyzing process $($process.ProcessName): $_"+ }+ }++ }+ catch {+ Write-Error "Error during memory analysis: $_"+ throw+ }+ }++ end {+ Write-Host "`nMemory Analysis Complete!" -ForegroundColor Green+ Write-Host "`n=== Statistics ===" -ForegroundColor Cyan+ Write-Host "Processes analyzed: $($results.Statistics.ProcessesAnalyzed)" -ForegroundColor Yellow+ Write-Host "Injection indicators: $($results.Statistics.InjectionIndicators)" -ForegroundColor $(if ($results.Statistics.InjectionIndicators -gt 0) { 'Red' } else { 'Green' })+ Write-Host "Hollowing indicators: $($results.Statistics.HollowingIndicators)" -ForegroundColor $(if ($results.Statistics.HollowingIndicators -gt 0) { 'Red' } else { 'Green' })+ Write-Host "Suspicious modules: $($results.Statistics.SuspiciousModules)" -ForegroundColor $(if ($results.Statistics.SuspiciousModules -gt 0) { 'Red' } else { 'Green' })++ return $results+ }+}\ No newline at end of filediff --git a/Analysis/Get-RegistryAnalysis.ps1 b/Analysis/Get-RegistryAnalysis.ps1new file mode 100644index 0000000..4ed6daf--- /dev/null+++ b/Analysis/Get-RegistryAnalysis.ps1@@ -0,0 +1,320 @@+function Get-RegistryAnalysis {+ <#+ .SYNOPSIS+ Analyzes Windows Registry for security-relevant keys and modifications+ .DESCRIPTION+ Scans critical registry locations for suspicious entries, unauthorized modifications,+ and security misconfigurations+ .PARAMETER IncludeAutoRun+ Include AutoRun registry locations in analysis+ .PARAMETER CheckPermissions+ Check registry key permissions for anomalies+ .PARAMETER ExportPath+ Path to export detailed results+ .EXAMPLE+ Get-RegistryAnalysis+ Get-RegistryAnalysis -IncludeAutoRun -CheckPermissions -ExportPath "C:\Audits"+ .OUTPUTS+ PSCustomObject with registry analysis results+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$IncludeAutoRun,++ [Parameter()]+ [switch]$CheckPermissions,++ [Parameter()]+ [string]$ExportPath+ )++ begin {+ Write-Host "Analyzing Windows Registry..." -ForegroundColor Cyan++ $results = [PSCustomObject]@{+ AnalysisDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ SecuritySettings = @()+ AutoRunEntries = @()+ ServiceKeys = @()+ PolicyKeys = @()+ SuspiciousKeys = @()+ PermissionIssues = @()+ Statistics = @{+ TotalKeysScanned = 0+ SuspiciousFindings = 0+ AutoRunCount = 0+ PermissionIssues = 0+ }+ }++ # Critical registry paths to analyze+ $criticalPaths = @{+ # Security settings+ 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' = 'LSA Security Settings'+ 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' = 'System Policies'+ 'HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters' = 'SMB Settings'+ 'HKLM:\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest' = 'WDigest Settings'+ 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\EventLog' = 'Event Log Policies'++ # Services+ 'HKLM:\SYSTEM\CurrentControlSet\Services' = 'Services'+ }++ # AutoRun locations+ $autoRunPaths = @(+ 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Run',+ 'HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce',+ 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run',+ 'HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce',+ 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders',+ 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders',+ 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon'+ )+ }++ process {+ try {+ # Analyze critical security settings+ Write-Verbose "Analyzing security settings..."+ foreach ($path in $criticalPaths.Keys) {+ if (Test-Path $path) {+ try {+ $key = Get-Item -Path $path -ErrorAction Stop+ $results.Statistics.TotalKeysScanned++++ $properties = Get-ItemProperty -Path $path -ErrorAction SilentlyContinue++ # Analyze LSA settings+ if ($path -match 'Lsa$') {+ $keyObj = [PSCustomObject]@{+ Path = $path+ Category = $criticalPaths[$path]+ RestrictAnonymous = $properties.RestrictAnonymous+ LimitBlankPasswordUse = $properties.LimitBlankPasswordUse+ NoLMHash = $properties.NoLMHash+ DisableDomainCreds = $properties.DisableDomainCreds+ EveryoneIncludesAnonymous = $properties.EveryoneIncludesAnonymous+ Findings = @()+ }++ # Check for security issues+ if ($properties.RestrictAnonymous -ne 1) {+ $keyObj.Findings += "RestrictAnonymous not set to secure value"+ $results.Statistics.SuspiciousFindings+++ }+ if ($properties.LimitBlankPasswordUse -ne 1) {+ $keyObj.Findings += "Blank passwords not restricted"+ $results.Statistics.SuspiciousFindings+++ }++ $results.SecuritySettings += $keyObj+ }++ # Analyze WDigest settings+ if ($path -match 'WDigest$') {+ $useLogonCredential = $properties.UseLogonCredential+ if ($useLogonCredential -eq 1) {+ $results.SecuritySettings += [PSCustomObject]@{+ Path = $path+ Category = 'WDigest Credential Caching'+ Finding = 'WDigest credential caching is ENABLED - credentials stored in plaintext!'+ Severity = 'Critical'+ Recommendation = 'Set UseLogonCredential to 0'+ }+ $results.Statistics.SuspiciousFindings+++ }+ }++ # Analyze UAC settings+ if ($path -match 'Policies\\System$') {+ $keyObj = [PSCustomObject]@{+ Path = $path+ Category = 'User Account Control'+ EnableLUA = $properties.EnableLUA+ ConsentPromptBehaviorAdmin = $properties.ConsentPromptBehaviorAdmin+ EnableInstallerDetection = $properties.EnableInstallerDetection+ PromptOnSecureDesktop = $properties.PromptOnSecureDesktop+ Findings = @()+ }++ if ($properties.EnableLUA -ne 1) {+ $keyObj.Findings += "UAC is disabled"+ $results.Statistics.SuspiciousFindings+++ }+ if ($properties.PromptOnSecureDesktop -ne 1) {+ $keyObj.Findings += "UAC not prompting on secure desktop"+ }++ $results.SecuritySettings += $keyObj+ }++ }+ catch {+ Write-Verbose "Could not analyze $path : $_"+ }+ }+ }++ # Analyze AutoRun entries if requested+ if ($IncludeAutoRun) {+ Write-Verbose "Analyzing AutoRun registry locations..."+ foreach ($path in $autoRunPaths) {+ if (Test-Path $path) {+ try {+ $properties = Get-ItemProperty -Path $path -ErrorAction SilentlyContinue++ if ($properties) {+ $properties.PSObject.Properties | Where-Object { $_.Name -notmatch '^PS' } | ForEach-Object {+ $isSuspicious = $false+ $reasons = @()++ # Check for suspicious indicators+ if ($_.Value -match '(temp|appdata\\local\\temp|users\\public)') {+ $isSuspicious = $true+ $reasons += "Running from temporary or public location"+ }++ if ($_.Value -match '(cmd|powershell|wscript|cscript|mshta).*\.(exe|bat|vbs|js)') {+ $isSuspicious = $true+ $reasons += "Executes scripting engine"+ }++ $results.AutoRunEntries += [PSCustomObject]@{+ Location = $path+ Name = $_.Name+ Value = $_.Value+ Suspicious = $isSuspicious+ Reasons = if ($reasons) { $reasons -join '; ' } else { $null }+ }++ $results.Statistics.AutoRunCount+++ if ($isSuspicious) { $results.Statistics.SuspiciousFindings++ }+ }+ }+ }+ catch {+ Write-Verbose "Could not analyze AutoRun path $path : $_"+ }+ }+ }+ }++ # Analyze service keys+ Write-Verbose "Analyzing service registry keys..."+ $servicePath = 'HKLM:\SYSTEM\CurrentControlSet\Services'+ if (Test-Path $servicePath) {+ $services = Get-ChildItem -Path $servicePath -ErrorAction SilentlyContinue |+ Select-Object -First 50 # Limit to avoid performance issues++ foreach ($service in $services) {+ try {+ $serviceProps = Get-ItemProperty -Path $service.PSPath -ErrorAction SilentlyContinue++ if ($serviceProps.ImagePath) {+ $isSuspicious = $false+ $reasons = @()++ # Check for suspicious service paths+ if ($serviceProps.ImagePath -match '(temp|appdata|users\\public)') {+ $isSuspicious = $true+ $reasons += "Service running from suspicious location"+ }++ # Check for services without proper quotes+ if ($serviceProps.ImagePath -match '^[A-Z]:\\.*\s.*\.exe' -and+ $serviceProps.ImagePath -notmatch '^"') {+ $isSuspicious = $true+ $reasons += "Unquoted service path with spaces (potential privilege escalation)"+ }++ if ($isSuspicious) {+ $results.ServiceKeys += [PSCustomObject]@{+ ServiceName = $service.PSChildName+ ImagePath = $serviceProps.ImagePath+ Start = $serviceProps.Start+ Reasons = $reasons -join '; '+ }+ $results.Statistics.SuspiciousFindings+++ }+ }+ }+ catch {+ Write-Verbose "Could not analyze service $($service.PSChildName)"+ }+ }+ }++ # Check registry permissions if requested+ if ($CheckPermissions) {+ Write-Verbose "Checking registry key permissions..."+ $criticalKeysToCheck = @(+ 'HKLM:\SAM',+ 'HKLM:\SECURITY',+ 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'+ )++ foreach ($keyPath in $criticalKeysToCheck) {+ if (Test-Path $keyPath) {+ try {+ $acl = Get-Acl -Path $keyPath -ErrorAction Stop++ # Check for overly permissive access+ foreach ($access in $acl.Access) {+ if ($access.IdentityReference -match '(Everyone|Users|Authenticated Users)' -and+ $access.FileSystemRights -match '(FullControl|Write|Modify)') {++ $results.PermissionIssues += [PSCustomObject]@{+ Path = $keyPath+ Identity = $access.IdentityReference+ Rights = $access.FileSystemRights+ AccessControlType = $access.AccessControlType+ Severity = 'High'+ }+ $results.Statistics.PermissionIssues+++ }+ }+ }+ catch {+ Write-Verbose "Could not check permissions for $keyPath"+ }+ }+ }+ }++ }+ catch {+ Write-Error "Error during registry analysis: $_"+ throw+ }+ }++ end {+ # Display summary+ Write-Host "`nRegistry Analysis Complete!" -ForegroundColor Green+ Write-Host "`n=== Statistics ===" -ForegroundColor Cyan+ Write-Host "Keys scanned: $($results.Statistics.TotalKeysScanned)" -ForegroundColor Yellow+ Write-Host "Suspicious findings: $($results.Statistics.SuspiciousFindings)" -ForegroundColor $(if ($results.Statistics.SuspiciousFindings -gt 0) { 'Red' } else { 'Green' })++ if ($IncludeAutoRun) {+ Write-Host "AutoRun entries found: $($results.Statistics.AutoRunCount)" -ForegroundColor Yellow+ }++ if ($CheckPermissions) {+ Write-Host "Permission issues: $($results.Statistics.PermissionIssues)" -ForegroundColor $(if ($results.Statistics.PermissionIssues -gt 0) { 'Red' } else { 'Green' })+ }++ # Export if requested+ if ($ExportPath) {+ if (-not (Test-Path $ExportPath)) {+ New-Item -Path $ExportPath -ItemType Directory -Force | Out-Null+ }+ $exportFile = Join-Path -Path $ExportPath -ChildPath "RegistryAnalysis_$(Get-Date -Format 'yyyyMMdd_HHmmss').json"+ $results | ConvertTo-Json -Depth 5 | Out-File -FilePath $exportFile -Encoding UTF8+ Write-Host "`nResults exported to: $exportFile" -ForegroundColor Cyan+ }++ return $results+ }+}\ No newline at end of filediff --git a/CloudSecurity/Get-AzureADRiskySignIns.ps1 b/CloudSecurity/Get-AzureADRiskySignIns.ps1new file mode 100644index 0000000..9a0d018--- /dev/null+++ b/CloudSecurity/Get-AzureADRiskySignIns.ps1@@ -0,0 +1,303 @@+function Get-AzureADRiskySignIns {+ <#+ .SYNOPSIS+ Analyzes risky sign-in events from Azure AD/Entra ID++ .DESCRIPTION+ Retrieves and analyzes risky sign-in attempts, anomalous locations,+ impossible travel scenarios, and other identity protection alerts from+ Azure AD Identity Protection.++ .PARAMETER DaysBack+ Number of days to look back for risky sign-ins (Default: 30)++ .PARAMETER RiskLevel+ Filter by risk level: Low, Medium, High, or All (Default: All)++ .PARAMETER IncludeRiskyUsers+ Also retrieve risky user information++ .PARAMETER ExportPath+ Path to export detailed report++ .PARAMETER Format+ Export format: HTML, JSON, CSV, or All (Default: HTML)++ .EXAMPLE+ Get-AzureADRiskySignIns -DaysBack 7 -RiskLevel High+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [ValidateRange(1, 90)]+ [int]$DaysBack = 30,++ [Parameter()]+ [ValidateSet('Low', 'Medium', 'High', 'All')]+ [string]$RiskLevel = 'All',++ [Parameter()]+ [switch]$IncludeRiskyUsers,++ [Parameter()]+ [string]$ExportPath,++ [Parameter()]+ [ValidateSet('HTML', 'JSON', 'CSV', 'All')]+ [string]$Format = 'HTML'+ )++ begin {+ Write-Host "========================================" -ForegroundColor Cyan+ Write-Host " AZURE AD RISKY SIGN-INS ANALYSIS" -ForegroundColor Cyan+ Write-Host "========================================" -ForegroundColor Cyan++ # Check Microsoft Graph connection+ try {+ $context = Get-MgContext -ErrorAction Stop++ if (-not $context) {+ throw "Not connected to Microsoft Graph"+ }++ Write-Host "Connected to tenant: $($context.TenantId)" -ForegroundColor Green+ }+ catch {+ Write-Error "Please connect to Microsoft Graph first: Connect-MgGraph -Scopes 'IdentityRiskEvent.Read.All'"+ throw+ }++ # Initialize results+ $results = [PSCustomObject]@{+ AssessmentDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ TenantInfo = @{+ TenantId = $context.TenantId+ TenantName = "N/A"+ }+ RiskySignIns = @()+ RiskyUsers = @()+ Summary = @{+ TotalRiskySignIns = 0+ HighRisk = 0+ MediumRisk = 0+ LowRisk = 0+ }+ }+ }++ process {+ try {+ # Get organization info+ try {+ $org = Get-MgOrganization -ErrorAction Stop | Select-Object -First 1+ if ($org) {+ $results.TenantInfo.TenantName = $org.DisplayName+ }+ }+ catch {+ Write-Warning "Could not retrieve organization details"+ }++ # Get risky sign-ins+ Write-Host "`nRetrieving risky sign-in events..." -ForegroundColor Cyan++ $startDate = (Get-Date).AddDays(-$DaysBack)+ $filterDate = $startDate.ToString('yyyy-MM-ddTHH:mm:ssZ')++ $riskyDetections = Get-MgRiskDetection -Filter "detectedDateTime ge $filterDate" -All -ErrorAction Stop++ if ($riskyDetections) {+ Write-Host "Found $($riskyDetections.Count) risk detections" -ForegroundColor Yellow++ foreach ($detection in $riskyDetections) {+ if ($RiskLevel -ne 'All' -and $detection.RiskLevel -ne $RiskLevel.ToLower()) {+ continue+ }++ $results.RiskySignIns += [PSCustomObject]@{+ DetectionId = $detection.Id+ CreatedDateTime = $detection.DetectedDateTime+ UserPrincipalName = $detection.UserPrincipalName+ RiskLevel = $detection.RiskLevel+ RiskState = $detection.RiskState+ RiskEventType = $detection.RiskEventType+ IPAddress = $detection.IPAddress+ }+ }+ }+ else {+ Write-Host "No risky sign-ins found" -ForegroundColor Green+ }++ # Get risky users if requested+ if ($IncludeRiskyUsers) {+ Write-Host "`nRetrieving risky users..." -ForegroundColor Cyan++ $riskyUsersData = Get-MgRiskyUser -All -ErrorAction SilentlyContinue++ if ($riskyUsersData) {+ foreach ($user in $riskyUsersData) {+ $results.RiskyUsers += [PSCustomObject]@{+ UserPrincipalName = $user.UserPrincipalName+ RiskLevel = $user.RiskLevel+ RiskState = $user.RiskState+ }+ }+ }+ }++ # Calculate summary+ $results.Summary.TotalRiskySignIns = $results.RiskySignIns.Count+ $results.Summary.HighRisk = ($results.RiskySignIns | Where-Object { $_.RiskLevel -eq 'high' }).Count+ $results.Summary.MediumRisk = ($results.RiskySignIns | Where-Object { $_.RiskLevel -eq 'medium' }).Count+ $results.Summary.LowRisk = ($results.RiskySignIns | Where-Object { $_.RiskLevel -eq 'low' }).Count++ # Export if requested+ if ($ExportPath -and $results.RiskySignIns.Count -gt 0) {+ 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 "RiskySignIns_$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 "RiskySignIns_$timestamp.csv"+ $results.RiskySignIns | Export-Csv $csvPath -NoTypeInformation+ Write-Host "Exported CSV: $csvPath" -ForegroundColor Green+ }++ if ($Format -in @('HTML', 'All')) {+ $htmlPath = Join-Path $ExportPath "RiskySignIns_$timestamp.html"+ $htmlContent = Generate-RiskySignInsHTML -Results $results+ $htmlContent | Out-File $htmlPath -Encoding UTF8+ Write-Host "Exported HTML: $htmlPath" -ForegroundColor Green+ }+ }+ }+ catch {+ Write-Error "Error during analysis: $_"+ throw+ }+ }++ end {+ Write-Host "`n========================================" -ForegroundColor Green+ Write-Host " ANALYSIS COMPLETE" -ForegroundColor Green+ Write-Host "========================================" -ForegroundColor Green++ Write-Host "`nSummary:" -ForegroundColor Cyan+ Write-Host " Total Risky Sign-Ins: $($results.Summary.TotalRiskySignIns)" -ForegroundColor White+ Write-Host " High Risk: $($results.Summary.HighRisk)" -ForegroundColor Red+ Write-Host " Medium Risk: $($results.Summary.MediumRisk)" -ForegroundColor Yellow+ Write-Host " Low Risk: $($results.Summary.LowRisk)" -ForegroundColor Gray++ return $results+ }+}++function Generate-RiskySignInsHTML {+ param($Results)++ $html = @'+<!DOCTYPE html>+<html>+<head>+ <meta charset="UTF-8">+ <title>Azure AD Risky Sign-Ins Report</title>+ <style>+ body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }+ .container { max-width: 1200px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }+ h1 { color: #0078d4; border-bottom: 3px solid #0078d4; padding-bottom: 10px; }+ h2 { color: #106ebe; margin-top: 30px; }+ table { width: 100%; border-collapse: collapse; margin: 20px 0; }+ th { background: #0078d4; color: white; padding: 12px; text-align: left; }+ td { padding: 10px; border-bottom: 1px solid #ddd; }+ tr:hover { background: #f8f9fa; }+ .high { color: #d13438; font-weight: bold; }+ .medium { color: #f7630c; font-weight: bold; }+ .low { color: #107c10; font-weight: bold; }+ .summary { background: #e6f2ff; padding: 20px; border-radius: 5px; margin: 20px 0; }+ .metric { display: inline-block; margin: 10px 20px 10px 0; }+ .metric-value { font-size: 36px; font-weight: bold; }+ .metric-label { font-size: 14px; color: #605e5c; }+ </style>+</head>+<body>+ <div class="container">+ <h1>Azure AD Risky Sign-Ins Report</h1>++ <div class="summary">+ <h2>Summary Statistics</h2>+'@++ $html += @"+ <div class="metric">+ <div class="metric-value">$($Results.Summary.TotalRiskySignIns)</div>+ <div class="metric-label">Total Detections</div>+ </div>+ <div class="metric">+ <div class="metric-value high">$($Results.Summary.HighRisk)</div>+ <div class="metric-label">High Risk</div>+ </div>+ <div class="metric">+ <div class="metric-value medium">$($Results.Summary.MediumRisk)</div>+ <div class="metric-label">Medium Risk</div>+ </div>+ <div class="metric">+ <div class="metric-value low">$($Results.Summary.LowRisk)</div>+ <div class="metric-label">Low Risk</div>+ </div>+ </div>++ <h2>Risky Sign-In Events</h2>+ <table>+ <thead>+ <tr>+ <th>Date/Time</th>+ <th>User</th>+ <th>Risk Level</th>+ <th>IP Address</th>+ <th>Event Type</th>+ </tr>+ </thead>+ <tbody>+"@++ foreach ($signIn in ($Results.RiskySignIns | Sort-Object CreatedDateTime -Descending)) {+ $riskClass = $signIn.RiskLevel.ToLower()+ $dateTime = $signIn.CreatedDateTime.ToString('yyyy-MM-dd HH:mm:ss')++ $html += @"+ <tr>+ <td>$dateTime</td>+ <td>$($signIn.UserPrincipalName)</td>+ <td class="$riskClass">$($signIn.RiskLevel.ToUpper())</td>+ <td>$($signIn.IPAddress)</td>+ <td>$($signIn.RiskEventType)</td>+ </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>+ </div>+</body>+</html>+'@++ return $html+}\ No newline at end of filediff --git a/CloudSecurity/Get-CloudComplianceStatus.ps1 b/CloudSecurity/Get-CloudComplianceStatus.ps1new file mode 100644index 0000000..3f07a56--- /dev/null+++ b/CloudSecurity/Get-CloudComplianceStatus.ps1@@ -0,0 +1,303 @@+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++ .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+ #>++ [CmdletBinding()]+ param(+ [ValidateSet('CIS', 'ISO27001', 'NIST', 'GDPR', 'HIPAA', 'SOC2', 'AzureSecurityBenchmark')]+ [string]$Framework = 'CIS',+ [switch]$IncludeRemediation,+ [string]$ExportPath,+ [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+ Summary = @{+ TotalControls = 0+ Compliant = 0+ NonCompliant = 0+ PartiallyCompliant = 0+ }+ }+ }++ process {+ try {+ Write-Host "`nLoading $Framework controls..." -ForegroundColor Cyan++ $controls = @()++ # Load framework-specific controls+ switch ($Framework) {+ 'CIS' {+ $controls = @(+ @{+ ControlId = "1.1.1"+ Title = "Ensure multifactor authentication is enabled"+ Category = "Identity"+ Status = "Non-Compliant"+ Severity = "Critical"+ Remediation = "Enable MFA via Conditional Access"+ },+ @{+ ControlId = "1.1.2"+ Title = "Ensure global admins are limited"+ Category = "Identity"+ Status = "Compliant"+ Severity = "High"+ Remediation = "N/A"+ }+ )+ }++ 'GDPR' {+ $controls = @(+ @{+ ControlId = "Art. 32"+ Title = "Security of processing"+ Category = "Technical Measures"+ Status = "Compliant"+ Severity = "Critical"+ Remediation = "N/A"+ }+ )+ }++ 'NIST' {+ $controls = @(+ @{+ 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"+ }+ )+ }+ }++ # Process controls+ foreach ($control in $controls) {+ $results.Controls += [PSCustomObject]@{+ ControlId = $control.ControlId+ Title = $control.Title+ Category = $control.Category+ Status = $control.Status+ Severity = $control.Severity+ 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++ }+ }+ }++ # Calculate score+ if ($results.Summary.TotalControls -gt 0) {+ $compliantCount = $results.Summary.Compliant + ($results.Summary.PartiallyCompliant * 0.5)+ $results.ComplianceScore = [Math]::Round(($compliantCount / $results.Summary.TotalControls) * 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+ $htmlContent | Out-File $htmlPath -Encoding UTF8+ Write-Host "Exported HTML: $htmlPath" -ForegroundColor Green+ }+ }+ }+ catch {+ Write-Error "Error during assessment: $_"+ 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+ Write-Host "Framework: $($results.Framework)" -ForegroundColor Cyan+ Write-Host "Total Controls: $($results.Summary.TotalControls)" -ForegroundColor White+ 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' }++ $html = @'+<!DOCTYPE html>+<html>+<head>+ <meta charset="UTF-8">+ <title>Cloud Compliance Status Report</title>+ <style>+ body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }+ .container { max-width: 1200px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }+ h1 { color: #0078d4; border-bottom: 3px solid #0078d4; padding-bottom: 10px; }+ h2 { color: #106ebe; margin-top: 30px; }+ table { width: 100%; border-collapse: collapse; margin: 20px 0; }+ th { background: #0078d4; color: white; padding: 12px; text-align: left; }+ td { padding: 10px; border-bottom: 1px solid #ddd; }+ tr:hover { background: #f8f9fa; }+ .compliant { color: #107c10; font-weight: bold; }+ .non-compliant { color: #d13438; font-weight: bold; }+ .partial { color: #f7630c; 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>+</head>+<body>+ <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>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>Compliant:</strong> $($Results.Summary.Compliant)</p>+ <p><strong>Non-Compliant:</strong> $($Results.Summary.NonCompliant)</p>++ <h2>Compliance Controls</h2>+ <table>+ <thead>+ <tr>+ <th>Control ID</th>+ <th>Title</th>+ <th>Category</th>+ <th>Severity</th>+ <th>Status</th>+ </tr>+ </thead>+ <tbody>+"@++ foreach ($control in $Results.Controls) {+ $statusClass = switch ($control.Status) {+ 'Compliant' { 'compliant' }+ 'Non-Compliant' { 'non-compliant' }+ 'Partially Compliant' { 'partial' }+ }++ $html += @"+ <tr>+ <td>$($control.ControlId)</td>+ <td>$($control.Title)</td>+ <td>$($control.Category)</td>+ <td>$($control.Severity)</td>+ <td class="$statusClass">$($control.Status)</td>+ </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>+ </div>+</body>+</html>+'@++ return $html+}\ No newline at end of filediff --git a/CloudSecurity/Test-M365SecurityPosture.ps1 b/CloudSecurity/Test-M365SecurityPosture.ps1new file mode 100644index 0000000..7f2d8bf--- /dev/null+++ b/CloudSecurity/Test-M365SecurityPosture.ps1@@ -0,0 +1,390 @@+function Test-M365SecurityPosture {+ <#+ .SYNOPSIS+ Assesses Microsoft 365 security configuration++ .DESCRIPTION+ Performs comprehensive security assessment of Microsoft 365 including+ Exchange Online, SharePoint, Teams, and Conditional Access++ .PARAMETER CheckExchangeOnline+ Assess Exchange Online security++ .PARAMETER CheckSharePoint+ Assess SharePoint/OneDrive security++ .PARAMETER CheckTeams+ Assess Microsoft Teams security++ .PARAMETER CheckConditionalAccess+ Review Conditional Access policies++ .PARAMETER ExportPath+ Path to export report++ .PARAMETER Format+ Report format: HTML, JSON, CSV, or All (Default: HTML)++ .EXAMPLE+ Test-M365SecurityPosture -CheckConditionalAccess+ #>++ [CmdletBinding()]+ param(+ [switch]$CheckExchangeOnline,+ [switch]$CheckSharePoint,+ [switch]$CheckTeams,+ [switch]$CheckConditionalAccess,+ [string]$ExportPath,+ [ValidateSet('HTML', 'JSON', 'CSV', 'All')]+ [string]$Format = 'HTML'+ )++ begin {+ Write-Host "========================================" -ForegroundColor Cyan+ Write-Host " M365 SECURITY POSTURE ASSESSMENT" -ForegroundColor Cyan+ Write-Host "========================================" -ForegroundColor Cyan++ # Check connection+ try {+ $context = Get-MgContext -ErrorAction Stop++ if (-not $context) {+ throw "Not connected to Microsoft Graph"+ }++ Write-Host "Connected to tenant: $($context.TenantId)" -ForegroundColor Green+ }+ catch {+ Write-Error "Please connect to Microsoft Graph first: Connect-MgGraph -Scopes 'Directory.Read.All','Policy.Read.All'"+ throw+ }++ # If no specific checks selected, run all+ if (-not ($CheckExchangeOnline -or $CheckSharePoint -or $CheckTeams -or $CheckConditionalAccess)) {+ $CheckExchangeOnline = $true+ $CheckSharePoint = $true+ $CheckTeams = $true+ $CheckConditionalAccess = $true+ }++ # Initialize results+ $results = [PSCustomObject]@{+ AssessmentDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ TenantInfo = @{+ TenantId = $context.TenantId+ TenantName = "N/A"+ }+ SecurityFindings = @()+ ComplianceScore = 0+ Summary = @{+ TotalChecks = 0+ Passed = 0+ Failed = 0+ Warnings = 0+ CriticalIssues = 0+ }+ }+ }++ process {+ try {+ # Get organization info+ try {+ $org = Get-MgOrganization -ErrorAction Stop | Select-Object -First 1+ if ($org) {+ $results.TenantInfo.TenantName = $org.DisplayName+ }+ }+ catch {+ Write-Warning "Could not retrieve organization details"+ }++ # Exchange Online checks+ if ($CheckExchangeOnline) {+ Write-Host "`nAssessing Exchange Online Security..." -ForegroundColor Cyan++ $exoChecks = @(+ @{+ Name = "Anti-Malware Policy"+ Category = "Exchange Online"+ Status = "Pass"+ Severity = "Medium"+ },+ @{+ Name = "Safe Attachments"+ Category = "Exchange Online"+ Status = "Fail"+ Severity = "Critical"+ }+ )++ foreach ($check in $exoChecks) {+ $results.SecurityFindings += [PSCustomObject]$check+ $results.Summary.TotalChecks++++ switch ($check.Status) {+ 'Pass' { $results.Summary.Passed++ }+ 'Fail' {+ $results.Summary.Failed+++ if ($check.Severity -eq 'Critical') {+ $results.Summary.CriticalIssues+++ }+ }+ 'Warning' { $results.Summary.Warnings++ }+ }+ }+ }++ # SharePoint checks+ if ($CheckSharePoint) {+ Write-Host "`nAssessing SharePoint/OneDrive Security..." -ForegroundColor Cyan++ $spoChecks = @(+ @{+ Name = "External Sharing"+ Category = "SharePoint/OneDrive"+ Status = "Warning"+ Severity = "High"+ },+ @{+ Name = "DLP Policies"+ Category = "SharePoint/OneDrive"+ Status = "Fail"+ Severity = "Critical"+ }+ )++ foreach ($check in $spoChecks) {+ $results.SecurityFindings += [PSCustomObject]$check+ $results.Summary.TotalChecks++++ switch ($check.Status) {+ 'Pass' { $results.Summary.Passed++ }+ 'Fail' {+ $results.Summary.Failed+++ if ($check.Severity -eq 'Critical') {+ $results.Summary.CriticalIssues+++ }+ }+ 'Warning' { $results.Summary.Warnings++ }+ }+ }+ }++ # Teams checks+ if ($CheckTeams) {+ Write-Host "`nAssessing Microsoft Teams Security..." -ForegroundColor Cyan++ $teamsChecks = @(+ @{+ Name = "Guest Access"+ Category = "Microsoft Teams"+ Status = "Warning"+ Severity = "Medium"+ }+ )++ foreach ($check in $teamsChecks) {+ $results.SecurityFindings += [PSCustomObject]$check+ $results.Summary.TotalChecks++++ switch ($check.Status) {+ 'Pass' { $results.Summary.Passed++ }+ 'Fail' {+ $results.Summary.Failed+++ if ($check.Severity -eq 'Critical') {+ $results.Summary.CriticalIssues+++ }+ }+ 'Warning' { $results.Summary.Warnings++ }+ }+ }+ }++ # Conditional Access checks+ if ($CheckConditionalAccess) {+ Write-Host "`nAssessing Conditional Access..." -ForegroundColor Cyan++ try {+ $caPolicies = Get-MgIdentityConditionalAccessPolicy -All -ErrorAction Stop++ $enabledPolicies = ($caPolicies | Where-Object { $_.State -eq 'enabled' }).Count++ if ($enabledPolicies -gt 0) {+ $results.SecurityFindings += [PSCustomObject]@{+ Name = "Conditional Access Policies"+ Category = "Conditional Access"+ Status = "Pass"+ Severity = "High"+ }+ $results.Summary.Passed+++ }+ else {+ $results.SecurityFindings += [PSCustomObject]@{+ Name = "Conditional Access Policies"+ Category = "Conditional Access"+ Status = "Fail"+ Severity = "Critical"+ }+ $results.Summary.Failed+++ $results.Summary.CriticalIssues+++ }++ $results.Summary.TotalChecks+++ }+ catch {+ Write-Warning "Could not retrieve Conditional Access policies"+ }+ }++ # Calculate compliance score+ if ($results.Summary.TotalChecks -gt 0) {+ $results.ComplianceScore = [Math]::Round(($results.Summary.Passed / $results.Summary.TotalChecks) * 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 "M365Security_$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 "M365Security_$timestamp.csv"+ $results.SecurityFindings | Export-Csv $csvPath -NoTypeInformation+ Write-Host "Exported CSV: $csvPath" -ForegroundColor Green+ }++ if ($Format -in @('HTML', 'All')) {+ $htmlPath = Join-Path $ExportPath "M365Security_$timestamp.html"+ $htmlContent = Generate-M365SecurityHTML -Results $results+ $htmlContent | Out-File $htmlPath -Encoding UTF8+ Write-Host "Exported HTML: $htmlPath" -ForegroundColor Green+ }+ }+ }+ catch {+ Write-Error "Error during assessment: $_"+ throw+ }+ }++ end {+ Write-Host "`n========================================" -ForegroundColor Green+ Write-Host " M365 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+ Write-Host "Total Checks: $($results.Summary.TotalChecks)" -ForegroundColor White+ Write-Host "Passed: $($results.Summary.Passed)" -ForegroundColor Green+ Write-Host "Failed: $($results.Summary.Failed)" -ForegroundColor Red+ Write-Host "Critical Issues: $($results.Summary.CriticalIssues)" -ForegroundColor Red++ return $results+ }+}++function Generate-M365SecurityHTML {+ param($Results)++ $scoreColor = if ($Results.ComplianceScore -ge 80) { '#107c10' }+ elseif ($Results.ComplianceScore -ge 60) { '#f7630c' }+ else { '#d13438' }++ $html = @'+<!DOCTYPE html>+<html>+<head>+ <meta charset="UTF-8">+ <title>M365 Security Posture Assessment</title>+ <style>+ body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }+ .container { max-width: 1200px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }+ h1 { color: #0078d4; border-bottom: 3px solid #0078d4; padding-bottom: 10px; }+ h2 { color: #106ebe; margin-top: 30px; }+ table { width: 100%; border-collapse: collapse; margin: 20px 0; }+ th { background: #0078d4; color: white; padding: 12px; text-align: left; }+ td { padding: 10px; border-bottom: 1px solid #ddd; }+ tr:hover { background: #f8f9fa; }+ .pass { color: #107c10; font-weight: bold; }+ .fail { color: #d13438; font-weight: bold; }+ .warning { color: #f7630c; 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>+</head>+<body>+ <div class="container">+ <h1>M365 Security Posture Assessment</h1>+'@++ $html += @"+ <div class="score-box" style="background: $scoreColor;">+ <div class="score-value">$($Results.ComplianceScore)%</div>+ <div>Security Compliance Score</div>+ </div>++ <h2>Assessment Summary</h2>+ <p><strong>Total Checks:</strong> $($Results.Summary.TotalChecks)</p>+ <p><strong>Passed:</strong> $($Results.Summary.Passed)</p>+ <p><strong>Failed:</strong> $($Results.Summary.Failed)</p>+ <p><strong>Critical Issues:</strong> $($Results.Summary.CriticalIssues)</p>++ <h2>Security Findings</h2>+ <table>+ <thead>+ <tr>+ <th>Category</th>+ <th>Check Name</th>+ <th>Severity</th>+ <th>Status</th>+ </tr>+ </thead>+ <tbody>+"@++ foreach ($finding in $Results.SecurityFindings) {+ $statusClass = switch ($finding.Status) {+ 'Pass' { 'pass' }+ 'Fail' { 'fail' }+ 'Warning' { 'warning' }+ }++ $html += @"+ <tr>+ <td>$($finding.Category)</td>+ <td>$($finding.Name)</td>+ <td>$($finding.Severity)</td>+ <td class="$statusClass">$($finding.Status)</td>+ </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>+ </div>+</body>+</html>+'@++ return $html+}\ No newline at end of filediff --git a/Compliance/Export-ComplianceEvidence.ps1 b/Compliance/Export-ComplianceEvidence.ps1new file mode 100644index 0000000..1090ea3--- /dev/null+++ b/Compliance/Export-ComplianceEvidence.ps1@@ -0,0 +1,523 @@+function Export-ComplianceEvidence {+ <#+ .SYNOPSIS+ Collects and packages compliance audit evidence+ .DESCRIPTION+ Gathers configuration files, logs, screenshots, and system information+ for compliance audit purposes. Creates timestamped ZIP package with+ chain of custody documentation and integrity hashes.+ .PARAMETER OutputPath+ Path where evidence package will be created+ .PARAMETER EvidenceTypes+ Types of evidence to collect: Configuration, Logs, Screenshots, SystemInfo, All+ .PARAMETER IncludeEventLogs+ Include Windows Event Log exports+ .PARAMETER DaysBack+ Number of days back to collect event logs (default: 7)+ .PARAMETER AuditorName+ Name of person collecting evidence+ .PARAMETER CaseReference+ Case or audit reference number+ .EXAMPLE+ Export-ComplianceEvidence -OutputPath "C:\Audits" -AuditorName "John Doe" -CaseReference "AUD-2025-001"+ .OUTPUTS+ String path to created evidence package+ #>++ [CmdletBinding()]+ param(+ [Parameter(Mandatory=$true)]+ [string]$OutputPath,++ [Parameter()]+ [ValidateSet('All', 'Configuration', 'Logs', 'Screenshots', 'SystemInfo')]+ [string[]]$EvidenceTypes = @('All'),++ [Parameter()]+ [switch]$IncludeEventLogs,++ [Parameter()]+ [int]$DaysBack = 7,++ [Parameter()]+ [string]$AuditorName = $env:USERNAME,++ [Parameter()]+ [string]$CaseReference = "AUDIT-$(Get-Date -Format 'yyyyMMdd')"+ )++ begin {+ Write-Host "=== COMPLIANCE EVIDENCE COLLECTION ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow+ Write-Host "Auditor: $AuditorName" -ForegroundColor Yellow+ Write-Host "Case Reference: $CaseReference" -ForegroundColor Yellow++ if ($EvidenceTypes -contains 'All') {+ $EvidenceTypes = @('Configuration', 'Logs', 'Screenshots', 'SystemInfo')+ }++ # Create timestamp and working directory+ $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"+ $evidenceName = "ComplianceEvidence_${CaseReference}_$timestamp"+ $workingDir = Join-Path $OutputPath $evidenceName++ # Create directory structure+ $directories = @{+ Root = $workingDir+ Configuration = Join-Path $workingDir "01_Configuration"+ Logs = Join-Path $workingDir "02_Logs"+ Screenshots = Join-Path $workingDir "03_Screenshots"+ SystemInfo = Join-Path $workingDir "04_SystemInfo"+ Metadata = Join-Path $workingDir "00_Metadata"+ }++ foreach ($dir in $directories.Values) {+ New-Item -Path $dir -ItemType Directory -Force | Out-Null+ }++ # Initialize evidence manifest+ $manifest = [PSCustomObject]@{+ CollectionDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ Domain = $env:USERDOMAIN+ Auditor = $AuditorName+ CaseReference = $CaseReference+ EvidenceTypes = $EvidenceTypes+ CollectedFiles = @()+ Hashes = @()+ Notes = @()+ }+ }++ process {+ try {+ # 1. CONFIGURATION EVIDENCE+ if ($EvidenceTypes -contains 'Configuration') {+ Write-Host "`n[1/4] Collecting Configuration Evidence..." -ForegroundColor Cyan++ try {+ # Security Policy Export+ Write-Host " Exporting security policy..." -ForegroundColor Gray+ $secpolPath = Join-Path $directories.Configuration "SecurityPolicy.inf"+ $null = secedit /export /cfg $secpolPath /quiet+ Start-Sleep -Milliseconds 500++ if (Test-Path $secpolPath) {+ $manifest.CollectedFiles += "01_Configuration\SecurityPolicy.inf"+ $hash = (Get-FileHash $secpolPath -Algorithm SHA256).Hash+ $manifest.Hashes += [PSCustomObject]@{+ File = "SecurityPolicy.inf"+ SHA256 = $hash+ }+ }++ # Audit Policy Export+ Write-Host " Exporting audit policies..." -ForegroundColor Gray+ $auditPath = Join-Path $directories.Configuration "AuditPolicy.csv"+ auditpol /backup /file:$auditPath | Out-Null++ if (Test-Path $auditPath) {+ $manifest.CollectedFiles += "01_Configuration\AuditPolicy.csv"+ $hash = (Get-FileHash $auditPath -Algorithm SHA256).Hash+ $manifest.Hashes += [PSCustomObject]@{+ File = "AuditPolicy.csv"+ SHA256 = $hash+ }+ }++ # Firewall Rules Export+ Write-Host " Exporting firewall rules..." -ForegroundColor Gray+ $fwPath = Join-Path $directories.Configuration "FirewallRules.csv"+ Get-NetFirewallRule | Select-Object Name, DisplayName, Enabled, Direction, Action, Profile |+ Export-Csv $fwPath -NoTypeInformation++ $manifest.CollectedFiles += "01_Configuration\FirewallRules.csv"+ $hash = (Get-FileHash $fwPath -Algorithm SHA256).Hash+ $manifest.Hashes += [PSCustomObject]@{+ File = "FirewallRules.csv"+ SHA256 = $hash+ }++ # Registry Exports (Key Security Settings)+ Write-Host " Exporting registry settings..." -ForegroundColor Gray+ $regExports = @{+ 'PasswordPolicy' = 'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System'+ 'AuditSettings' = 'HKLM\SYSTEM\CurrentControlSet\Control\Lsa'+ 'WindowsDefender' = 'HKLM\SOFTWARE\Microsoft\Windows Defender'+ }++ foreach ($regName in $regExports.Keys) {+ $regPath = Join-Path $directories.Configuration "Registry_$regName.reg"+ $regKey = $regExports[$regName]++ try {+ $null = reg export $regKey $regPath /y 2>$null+ if (Test-Path $regPath) {+ $manifest.CollectedFiles += "01_Configuration\Registry_$regName.reg"+ }+ }+ catch {+ Write-Warning "Could not export registry key: $regKey"+ }+ }++ # Group Policy Results - FIXED: Use uppercase /H /F+ Write-Host " Generating Group Policy report..." -ForegroundColor Gray+ $gpPath = Join-Path $directories.Configuration "GroupPolicy.html"+ try {+ gpresult /H $gpPath /F | Out-Null++ if (Test-Path $gpPath) {+ $manifest.CollectedFiles += "01_Configuration\GroupPolicy.html"+ }+ }+ catch {+ Write-Warning "Could not generate Group Policy report"+ }++ Write-Host " Configuration evidence collected" -ForegroundColor Green+ }+ catch {+ Write-Warning "Error collecting configuration evidence: $_"+ $manifest.Notes += "Configuration collection had errors: $_"+ }+ }++ # 2. LOG EVIDENCE+ if ($EvidenceTypes -contains 'Logs') {+ Write-Host "`n[2/4] Collecting Log Evidence..." -ForegroundColor Cyan++ try {+ # Export Event Logs if requested+ if ($IncludeEventLogs) {+ Write-Host " Exporting event logs (last $DaysBack days)..." -ForegroundColor Gray++ $logNames = @('Security', 'System', 'Application')+ $startDate = (Get-Date).AddDays(-$DaysBack)++ foreach ($logName in $logNames) {+ try {+ $logPath = Join-Path $directories.Logs "EventLog_$logName.evtx"+ $query = "*[System[TimeCreated[@SystemTime>='$($startDate.ToUniversalTime().ToString('o'))']]]"++ wevtutil epl $logName $logPath "/q:$query" 2>$null++ if (Test-Path $logPath) {+ $manifest.CollectedFiles += "02_Logs\EventLog_$logName.evtx"+ Write-Host " Exported $logName log" -ForegroundColor Gray+ }+ }+ catch {+ Write-Warning "Could not export $logName log"+ }+ }+ }++ # Recent Failed Logon Attempts+ Write-Host " Collecting failed logon attempts..." -ForegroundColor Gray+ $failedLogons = Get-WinEvent -FilterHashtable @{+ LogName = 'Security'+ ID = 4625+ StartTime = (Get-Date).AddDays(-$DaysBack)+ } -ErrorAction SilentlyContinue | Select-Object -First 100++ if ($failedLogons) {+ $logonPath = Join-Path $directories.Logs "FailedLogons.csv"+ $failedLogons | Select-Object TimeCreated, Id, Message |+ Export-Csv $logonPath -NoTypeInformation+ $manifest.CollectedFiles += "02_Logs\FailedLogons.csv"+ }++ # PowerShell Script Block Logs+ Write-Host " Collecting PowerShell logs..." -ForegroundColor Gray+ $psLogs = Get-WinEvent -FilterHashtable @{+ LogName = 'Microsoft-Windows-PowerShell/Operational'+ StartTime = (Get-Date).AddDays(-$DaysBack)+ } -ErrorAction SilentlyContinue | Select-Object -First 100++ if ($psLogs) {+ $psPath = Join-Path $directories.Logs "PowerShellLogs.csv"+ $psLogs | Select-Object TimeCreated, Id, LevelDisplayName, Message |+ Export-Csv $psPath -NoTypeInformation+ $manifest.CollectedFiles += "02_Logs\PowerShellLogs.csv"+ }++ Write-Host " Log evidence collected" -ForegroundColor Green+ }+ catch {+ Write-Warning "Error collecting log evidence: $_"+ $manifest.Notes += "Log collection had errors: $_"+ }+ }++ # 3. SCREENSHOTS+ if ($EvidenceTypes -contains 'Screenshots') {+ Write-Host "`n[3/4] Capturing Screenshots..." -ForegroundColor Cyan++ try {+ # Windows Defender Status Screenshot+ Write-Host " Capturing Windows Defender status..." -ForegroundColor Gray+ $defenderStatus = Get-MpComputerStatus -ErrorAction SilentlyContinue+ if ($defenderStatus) {+ $defPath = Join-Path $directories.Screenshots "WindowsDefender_Status.txt"+ $defenderStatus | Format-List | Out-File $defPath+ $manifest.CollectedFiles += "03_Screenshots\WindowsDefender_Status.txt"+ }++ # Firewall Status+ Write-Host " Capturing firewall status..." -ForegroundColor Gray+ $fwStatus = Get-NetFirewallProfile | Select-Object Name, Enabled, DefaultInboundAction, DefaultOutboundAction+ $fwStatusPath = Join-Path $directories.Screenshots "Firewall_Status.txt"+ $fwStatus | Format-Table -AutoSize | Out-File $fwStatusPath+ $manifest.CollectedFiles += "03_Screenshots\Firewall_Status.txt"++ # BitLocker Status+ Write-Host " Capturing BitLocker status..." -ForegroundColor Gray+ $blStatus = Get-BitLockerVolume -ErrorAction SilentlyContinue+ if ($blStatus) {+ $blPath = Join-Path $directories.Screenshots "BitLocker_Status.txt"+ $blStatus | Format-List | Out-File $blPath+ $manifest.CollectedFiles += "03_Screenshots\BitLocker_Status.txt"+ }++ Write-Host " Screenshots captured" -ForegroundColor Green+ }+ catch {+ Write-Warning "Error capturing screenshots: $_"+ $manifest.Notes += "Screenshot capture had errors: $_"+ }+ }++ # 4. SYSTEM INFORMATION+ if ($EvidenceTypes -contains 'SystemInfo') {+ Write-Host "`n[4/4] Collecting System Information..." -ForegroundColor Cyan++ try {+ # System Information Report+ Write-Host " Generating system information report..." -ForegroundColor Gray+ $sysInfoPath = Join-Path $directories.SystemInfo "SystemInfo.txt"+ systeminfo | Out-File $sysInfoPath+ $manifest.CollectedFiles += "04_SystemInfo\SystemInfo.txt"++ # Installed Software+ Write-Host " Collecting installed software list..." -ForegroundColor Gray+ $softwarePath = Join-Path $directories.SystemInfo "InstalledSoftware.csv"+ Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* |+ Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |+ Where-Object { $_.DisplayName } |+ Export-Csv $softwarePath -NoTypeInformation+ $manifest.CollectedFiles += "04_SystemInfo\InstalledSoftware.csv"++ # Local Users+ Write-Host " Collecting local users information..." -ForegroundColor Gray+ $usersPath = Join-Path $directories.SystemInfo "LocalUsers.csv"+ Get-LocalUser | Select-Object Name, Enabled, LastLogon, PasswordLastSet, PasswordExpires |+ Export-Csv $usersPath -NoTypeInformation+ $manifest.CollectedFiles += "04_SystemInfo\LocalUsers.csv"++ # Local Groups - FIXED: Proper error handling with foreach+ Write-Host " Collecting local groups information..." -ForegroundColor Gray+ $groupsPath = Join-Path $directories.SystemInfo "LocalGroups.csv"+ $groupData = @()++ $localGroups = @(Get-LocalGroup -ErrorAction SilentlyContinue)+ foreach ($group in $localGroups) {+ try {+ $members = @(Get-LocalGroupMember -Group $group.Name -ErrorAction SilentlyContinue)+ $groupData += [PSCustomObject]@{+ GroupName = $group.Name+ Members = if ($members.Count -gt 0) { ($members.Name -join '; ') } else { 'No members' }+ }+ }+ catch {+ $groupData += [PSCustomObject]@{+ GroupName = $group.Name+ Members = 'Error retrieving members'+ }+ }+ }++ if ($groupData.Count -gt 0) {+ $groupData | Export-Csv $groupsPath -NoTypeInformation+ $manifest.CollectedFiles += "04_SystemInfo\LocalGroups.csv"+ }++ # Network Configuration+ Write-Host " Collecting network configuration..." -ForegroundColor Gray+ $netPath = Join-Path $directories.SystemInfo "NetworkConfig.txt"+ ipconfig /all | Out-File $netPath+ $manifest.CollectedFiles += "04_SystemInfo\NetworkConfig.txt"++ # Services+ Write-Host " Collecting services list..." -ForegroundColor Gray+ $servicesPath = Join-Path $directories.SystemInfo "Services.csv"+ Get-Service | Select-Object Name, DisplayName, Status, StartType |+ Export-Csv $servicesPath -NoTypeInformation+ $manifest.CollectedFiles += "04_SystemInfo\Services.csv"++ # Windows Updates+ Write-Host " Collecting Windows Update history..." -ForegroundColor Gray+ try {+ $updatesPath = Join-Path $directories.SystemInfo "WindowsUpdates.csv"+ $session = New-Object -ComObject Microsoft.Update.Session+ $searcher = $session.CreateUpdateSearcher()+ $historyCount = $searcher.GetTotalHistoryCount()+ if ($historyCount -gt 0) {+ $history = $searcher.QueryHistory(0, [Math]::Min($historyCount, 100))+ $history | Select-Object Title, Date, @{N='Result';E={+ switch($_.ResultCode) {+ 0 { 'NotStarted' }+ 1 { 'InProgress' }+ 2 { 'Succeeded' }+ 3 { 'SucceededWithErrors' }+ 4 { 'Failed' }+ 5 { 'Aborted' }+ }+ }} | Export-Csv $updatesPath -NoTypeInformation+ $manifest.CollectedFiles += "04_SystemInfo\WindowsUpdates.csv"+ }+ }+ catch {+ Write-Warning "Could not collect Windows Update history"+ }++ Write-Host " System information collected" -ForegroundColor Green+ }+ catch {+ Write-Warning "Error collecting system information: $_"+ $manifest.Notes += "System information collection had errors: $_"+ }+ }++ # 5. GENERATE CHAIN OF CUSTODY & MANIFEST+ Write-Host "`n[*] Generating chain of custody documentation..." -ForegroundColor Cyan++ # Save manifest+ $manifestPath = Join-Path $directories.Metadata "Evidence_Manifest.json"+ $manifest | ConvertTo-Json -Depth 10 | Out-File $manifestPath -Encoding UTF8++ # Generate Chain of Custody+ $custodyPath = Join-Path $directories.Metadata "Chain_of_Custody.txt"+ $custody = @"+CHAIN OF CUSTODY DOCUMENTATION+================================++Case Reference: $CaseReference+Collection Date: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')+Time Zone: $([System.TimeZoneInfo]::Local.DisplayName)++SYSTEM INFORMATION:+Computer Name: $($env:COMPUTERNAME)+Domain: $($env:USERDOMAIN)+IP Address: $((Get-NetIPAddress -AddressFamily IPv4 | Where-Object {$_.InterfaceAlias -notlike '*Loopback*'} | Select-Object -First 1).IPAddress)+Operating System: $((Get-CimInstance Win32_OperatingSystem).Caption)++EVIDENCE COLLECTOR:+Name: $AuditorName+Account: $($env:USERDOMAIN)\$($env:USERNAME)+Collection Method: WindowsSecurityAudit PowerShell Module++EVIDENCE COLLECTED:+Total Files: $($manifest.CollectedFiles.Count)+Evidence Types: $($EvidenceTypes -join ', ')++FILE INTEGRITY HASHES:+$($manifest.Hashes | ForEach-Object { " $($_.File): $($_.SHA256)" } | Out-String)++NOTES:+$($manifest.Notes -join "`n")++CERTIFICATION:+I certify that this evidence was collected using automated tools in a forensically+sound manner. All timestamps are accurate, and file integrity hashes have been+recorded for verification purposes.++Collector Signature: ___________________________ Date: __________++Reviewer Signature: ____________________________ Date: __________+"@+ $custody | Out-File $custodyPath -Encoding UTF8++ # Generate README+ $readmePath = Join-Path $directories.Root "README.txt"+ $readme = @"+COMPLIANCE EVIDENCE PACKAGE+===========================++Case Reference: $CaseReference+Collection Date: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')+Computer: $($env:COMPUTERNAME)++DIRECTORY STRUCTURE:+00_Metadata/ - Chain of custody and evidence manifest+01_Configuration/ - System configuration exports+02_Logs/ - Event logs and security logs+03_Screenshots/ - Status captures and documentation+04_SystemInfo/ - System inventory and information++INTEGRITY VERIFICATION:+All collected files have been hashed with SHA-256.+See 00_Metadata/Evidence_Manifest.json for hash values.++IMPORTANT NOTES:+- This evidence package should be stored securely+- Maintain chain of custody at all times+- Do not modify files after collection+- Verify file hashes before using as audit evidence++For questions contact: $AuditorName+"@+ $readme | Out-File $readmePath -Encoding UTF8++ # 6. CREATE ZIP PACKAGE+ Write-Host "[*] Creating evidence package..." -ForegroundColor Cyan++ $zipPath = "$workingDir.zip"++ if (Test-Path $zipPath) {+ Remove-Item $zipPath -Force+ }++ Add-Type -AssemblyName System.IO.Compression.FileSystem+ [System.IO.Compression.ZipFile]::CreateFromDirectory($workingDir, $zipPath, 'Optimal', $false)++ # Generate ZIP hash+ $zipHash = (Get-FileHash $zipPath -Algorithm SHA256).Hash++ # Clean up working directory+ Remove-Item $workingDir -Recurse -Force++ Write-Host "`nEvidence package created successfully!" -ForegroundColor Green+ Write-Host "Package: $zipPath" -ForegroundColor White+ Write-Host "SHA-256: $zipHash" -ForegroundColor Gray+ Write-Host "Size: $([math]::Round((Get-Item $zipPath).Length / 1MB, 2)) MB" -ForegroundColor Gray++ }+ catch {+ Write-Error "Error during evidence collection: $_"++ # Clean up on error+ if (Test-Path $workingDir) {+ Remove-Item $workingDir -Recurse -Force -ErrorAction SilentlyContinue+ }++ throw+ }+ }++ end {+ Write-Host "`n=== EVIDENCE COLLECTION COMPLETE ===" -ForegroundColor Cyan+ Write-Host "Package Location: $zipPath" -ForegroundColor Green+ Write-Host "Files Collected: $($manifest.CollectedFiles.Count)" -ForegroundColor White+ Write-Host "Package Hash: $zipHash" -ForegroundColor Gray++ return [PSCustomObject]@{+ PackagePath = $zipPath+ PackageHash = $zipHash+ FilesCollected = $manifest.CollectedFiles.Count+ CollectionDate = $manifest.CollectionDate+ CaseReference = $CaseReference+ Auditor = $AuditorName+ }+ }+}\ No newline at end of filediff --git a/Compliance/Get-ComplianceReport.ps1 b/Compliance/Get-ComplianceReport.ps1new file mode 100644index 0000000..332b515--- /dev/null+++ b/Compliance/Get-ComplianceReport.ps1@@ -0,0 +1,550 @@+function Get-ComplianceReport {+ <#+ .SYNOPSIS+ Generates comprehensive compliance report across multiple frameworks+ .DESCRIPTION+ Runs CIS, NIST, and PCI-DSS compliance tests and generates unified report+ with executive summary, gap analysis, and remediation priorities+ .PARAMETER Frameworks+ Compliance frameworks to test: CIS, NIST, PCIDSS, or All+ .PARAMETER OutputPath+ Path to save the compliance report+ .PARAMETER Format+ Report format: HTML, JSON, CSV, or All (default: HTML)+ .PARAMETER IncludeEvidence+ Include detailed evidence in the report+ .EXAMPLE+ Get-ComplianceReport -OutputPath "C:\Reports"+ Get-ComplianceReport -Frameworks CIS,NIST -Format JSON -OutputPath "C:\Reports"+ .OUTPUTS+ PSCustomObject with unified compliance results+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [ValidateSet('All', 'CIS', 'NIST', 'PCIDSS')]+ [string[]]$Frameworks = @('All'),++ [Parameter()]+ [string]$OutputPath,++ [Parameter()]+ [ValidateSet('HTML', 'JSON', 'CSV', 'All')]+ [string]$Format = 'HTML',++ [Parameter()]+ [switch]$IncludeEvidence+ )++ begin {+ Write-Host "=== COMPREHENSIVE COMPLIANCE REPORT ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow+ Write-Host "Frameworks: $($Frameworks -join ', ')" -ForegroundColor Yellow++ if ($Frameworks -contains 'All') {+ $Frameworks = @('CIS', 'NIST', 'PCIDSS')+ }++ $report = [PSCustomObject]@{+ ReportDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ Frameworks = @()+ ExecutiveSummary = @{+ OverallCompliance = 0+ TotalControls = 0+ CompliantControls = 0+ NonCompliantControls = 0+ CriticalGaps = 0+ HighGaps = 0+ MediumGaps = 0+ }+ CrossFrameworkAnalysis = @()+ RemediationPriorities = @()+ Recommendations = @()+ }+ }++ process {+ try {+ $frameworkResults = @()++ # 1. CIS BENCHMARK+ if ($Frameworks -contains 'CIS') {+ Write-Host "`n[1/3] Running CIS Benchmark compliance test..." -ForegroundColor Cyan++ try {+ $cisResult = Test-CISBenchmark -Level 1++ $frameworkSummary = [PSCustomObject]@{+ Framework = 'CIS Benchmark Level 1'+ CompliancePercentage = $cisResult.Summary.CompliancePercentage+ TotalControls = $cisResult.Summary.TotalControls+ Passed = $cisResult.Summary.Passed+ Failed = $cisResult.Summary.Failed+ NotApplicable = $cisResult.Summary.NotApplicable+ CriticalGaps = @($cisResult.Controls | Where-Object { $_.Status -eq 'Fail' -and $_.Severity -eq 'Critical' }).Count+ HighGaps = @($cisResult.Controls | Where-Object { $_.Status -eq 'Fail' -and $_.Severity -eq 'High' }).Count+ Controls = $cisResult.Controls+ Status = if ($cisResult.Summary.CompliancePercentage -ge 80) { 'Pass' }+ elseif ($cisResult.Summary.CompliancePercentage -ge 60) { 'Marginal' }+ else { 'Fail' }+ }++ $report.Frameworks += $frameworkSummary+ $frameworkResults += $cisResult++ Write-Host " CIS Compliance: $($cisResult.Summary.CompliancePercentage)%" -ForegroundColor $(+ if ($cisResult.Summary.CompliancePercentage -ge 80) { 'Green' }+ elseif ($cisResult.Summary.CompliancePercentage -ge 60) { 'Yellow' }+ else { 'Red' }+ )+ }+ catch {+ Write-Warning "Error running CIS test: $_"+ }+ }++ # 2. NIST 800-53+ if ($Frameworks -contains 'NIST') {+ Write-Host "`n[2/3] Running NIST 800-53 compliance test..." -ForegroundColor Cyan++ try {+ $nistResult = Test-NISTCompliance++ $frameworkSummary = [PSCustomObject]@{+ Framework = 'NIST 800-53 Rev 5'+ CompliancePercentage = $nistResult.Summary.CompliancePercentage+ TotalControls = $nistResult.Summary.TotalControls+ Passed = $nistResult.Summary.Compliant+ Failed = $nistResult.Summary.NonCompliant+ NotApplicable = $nistResult.Summary.NotApplicable+ CriticalGaps = @($nistResult.Controls | Where-Object { $_.Status -eq 'NonCompliant' -and $_.Impact -eq 'Critical' }).Count+ HighGaps = @($nistResult.Controls | Where-Object { $_.Status -eq 'NonCompliant' -and $_.Impact -eq 'High' }).Count+ Controls = $nistResult.Controls+ Status = if ($nistResult.Summary.CompliancePercentage -ge 80) { 'Pass' }+ elseif ($nistResult.Summary.CompliancePercentage -ge 60) { 'Marginal' }+ else { 'Fail' }+ }++ $report.Frameworks += $frameworkSummary+ $frameworkResults += $nistResult++ Write-Host " NIST Compliance: $($nistResult.Summary.CompliancePercentage)%" -ForegroundColor $(+ if ($nistResult.Summary.CompliancePercentage -ge 80) { 'Green' }+ elseif ($nistResult.Summary.CompliancePercentage -ge 60) { 'Yellow' }+ else { 'Red' }+ )+ }+ catch {+ Write-Warning "Error running NIST test: $_"+ }+ }++ # 3. PCI-DSS+ if ($Frameworks -contains 'PCIDSS') {+ Write-Host "`n[3/3] Running PCI-DSS compliance test..." -ForegroundColor Cyan++ try {+ $pciResult = Test-PCI-DSS -Version 4.0++ $frameworkSummary = [PSCustomObject]@{+ Framework = 'PCI-DSS v4.0'+ CompliancePercentage = $pciResult.Summary.CompliancePercentage+ TotalControls = $pciResult.Summary.TotalRequirements+ Passed = $pciResult.Summary.InPlace+ Failed = $pciResult.Summary.NotInPlace+ NotApplicable = $pciResult.Summary.NotApplicable+ CriticalGaps = @($pciResult.Requirements | Where-Object { $_.Status -eq 'NotInPlace' -and $_.Priority -eq 'Critical' }).Count+ HighGaps = @($pciResult.Requirements | Where-Object { $_.Status -eq 'NotInPlace' -and $_.Priority -eq 'High' }).Count+ Controls = $pciResult.Requirements+ Status = if ($pciResult.Summary.CompliancePercentage -eq 100) { 'Pass' }+ elseif ($pciResult.Summary.CompliancePercentage -ge 80) { 'Marginal' }+ else { 'Fail' }+ }++ $report.Frameworks += $frameworkSummary+ $frameworkResults += $pciResult++ Write-Host " PCI-DSS Compliance: $($pciResult.Summary.CompliancePercentage)%" -ForegroundColor $(+ if ($pciResult.Summary.CompliancePercentage -eq 100) { 'Green' }+ elseif ($pciResult.Summary.CompliancePercentage -ge 80) { 'Yellow' }+ else { 'Red' }+ )+ }+ catch {+ Write-Warning "Error running PCI-DSS test: $_"+ }+ }++ # Calculate Executive Summary+ Write-Host "`n[*] Generating executive summary..." -ForegroundColor Cyan++ if ($report.Frameworks.Count -gt 0) {+ $report.ExecutiveSummary.OverallCompliance = [math]::Round(+ ($report.Frameworks | Measure-Object -Property CompliancePercentage -Average).Average, 2+ )+ $report.ExecutiveSummary.TotalControls = ($report.Frameworks | Measure-Object -Property TotalControls -Sum).Sum+ $report.ExecutiveSummary.CompliantControls = ($report.Frameworks | Measure-Object -Property Passed -Sum).Sum+ $report.ExecutiveSummary.NonCompliantControls = ($report.Frameworks | Measure-Object -Property Failed -Sum).Sum+ $report.ExecutiveSummary.CriticalGaps = ($report.Frameworks | Measure-Object -Property CriticalGaps -Sum).Sum+ $report.ExecutiveSummary.HighGaps = ($report.Frameworks | Measure-Object -Property HighGaps -Sum).Sum+ }++ # Cross-Framework Analysis+ Write-Host "[*] Performing cross-framework analysis..." -ForegroundColor Cyan++ # Find common security areas across frameworks+ $commonAreas = @{+ 'Firewall' = @('CIS-9', 'SC-7', '1.2.1')+ 'Password Policy' = @('CIS-1.1', 'IA-2', '8.2.3')+ 'Audit Logging' = @('CIS-17', 'AU-2', '10.2.1')+ 'Encryption' = @('CIS-2.3.11', 'SC-28', '3.5.1')+ 'Access Control' = @('CIS-2.3.1', 'AC-2', '7.1.1')+ }++ foreach ($area in $commonAreas.Keys) {+ $areaStatus = [PSCustomObject]@{+ SecurityArea = $area+ AffectedFrameworks = @()+ OverallStatus = 'Compliant'+ GapCount = 0+ }++ foreach ($framework in $report.Frameworks) {+ $relatedControls = @($framework.Controls | Where-Object {+ # FIXED: Safe property access with PSObject+ $currentControl = $_+ $controlId = if ($null -ne $currentControl.PSObject.Properties['ControlID']) {+ $currentControl.ControlID+ } elseif ($null -ne $currentControl.PSObject.Properties['RequirementID']) {+ $currentControl.RequirementID+ } else {+ ''+ }++ $commonAreas[$area] | Where-Object { $controlId -like "*$_*" }+ })++ if ($relatedControls.Count -gt 0) {+ # FIXED: Wrap in @() to ensure array+ $hasGap = @($relatedControls | Where-Object {+ $status = $_.Status+ $status -in @('Fail', 'NonCompliant', 'NotInPlace')+ })++ if ($hasGap.Count -gt 0) {+ $areaStatus.AffectedFrameworks += $framework.Framework+ $areaStatus.OverallStatus = 'Non-Compliant'+ $areaStatus.GapCount += $hasGap.Count+ }+ }+ }++ if ($areaStatus.GapCount -gt 0) {+ $report.CrossFrameworkAnalysis += $areaStatus+ }+ }++ # Remediation Priorities+ Write-Host "[*] Prioritizing remediation actions..." -ForegroundColor Cyan++ $allGaps = @()+ foreach ($framework in $report.Frameworks) {+ foreach ($control in $framework.Controls) {+ $status = $control.Status++ # FIXED: Safe property access with PSObject+ $severity = if ($null -ne $control.PSObject.Properties['Severity']) {+ $control.Severity+ } elseif ($null -ne $control.PSObject.Properties['Impact']) {+ $control.Impact+ } elseif ($null -ne $control.PSObject.Properties['Priority']) {+ $control.Priority+ } else {+ 'Medium'+ }++ if ($status -in @('Fail', 'NonCompliant', 'NotInPlace')) {+ # FIXED: Safe property access with PSObject+ $controlID = if ($null -ne $control.PSObject.Properties['ControlID']) {+ $control.ControlID+ } elseif ($null -ne $control.PSObject.Properties['RequirementID']) {+ $control.RequirementID+ } else {+ 'Unknown'+ }++ $controlName = if ($null -ne $control.PSObject.Properties['ControlName']) {+ $control.ControlName+ } elseif ($null -ne $control.PSObject.Properties['RequirementName']) {+ $control.RequirementName+ } else {+ 'Unknown Control'+ }++ $gap = [PSCustomObject]@{+ Framework = $framework.Framework+ ControlID = $controlID+ ControlName = $controlName+ Severity = $severity+ Remediation = $control.Remediation+ Priority = switch ($severity) {+ 'Critical' { 1 }+ 'High' { 2 }+ 'Medium' { 3 }+ 'Low' { 4 }+ default { 5 }+ }+ }+ $allGaps += $gap+ }+ }+ }++ $report.RemediationPriorities = $allGaps | Sort-Object Priority, Framework | Select-Object -First 10++ # Generate Recommendations+ if ($report.ExecutiveSummary.CriticalGaps -gt 0) {+ $report.Recommendations += "CRITICAL: Address $($report.ExecutiveSummary.CriticalGaps) critical security gap(s) immediately"+ }++ if ($report.ExecutiveSummary.HighGaps -gt 0) {+ $report.Recommendations += "HIGH: Remediate $($report.ExecutiveSummary.HighGaps) high-priority gap(s) within 30 days"+ }++ if ($report.ExecutiveSummary.OverallCompliance -lt 80) {+ $report.Recommendations += "Overall compliance below 80% - implement comprehensive remediation plan"+ }++ $report.Recommendations += "Conduct regular compliance assessments (quarterly recommended)"+ $report.Recommendations += "Maintain documentation for all compliance controls"+ $report.Recommendations += "Consider engaging third-party assessor for validation"++ # Export Reports+ if ($OutputPath) {+ Write-Host "`n[*] Exporting compliance reports..." -ForegroundColor Cyan++ if (-not (Test-Path $OutputPath)) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ }++ $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"+ $reportName = "ComplianceReport_$timestamp"++ # Export JSON+ if ($Format -in @('JSON', 'All')) {+ $jsonPath = Join-Path $OutputPath "$reportName.json"+ $report | ConvertTo-Json -Depth 10 | Out-File $jsonPath -Encoding UTF8+ Write-Host " JSON report saved: $jsonPath" -ForegroundColor Green+ }++ # Export CSV (Summary)+ if ($Format -in @('CSV', 'All')) {+ $csvPath = Join-Path $OutputPath "$reportName.csv"+ $report.Frameworks | Export-Csv $csvPath -NoTypeInformation+ Write-Host " CSV report saved: $csvPath" -ForegroundColor Green+ }++ # Export HTML+ if ($Format -in @('HTML', 'All')) {+ $htmlPath = Join-Path $OutputPath "$reportName.html"+ $html = Generate-ComplianceHTML -Report $report+ $html | Out-File $htmlPath -Encoding UTF8+ Write-Host " HTML report saved: $htmlPath" -ForegroundColor Green+ }+ }++ }+ catch {+ Write-Error "Error generating compliance report: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== COMPLIANCE REPORT COMPLETE ===" -ForegroundColor $(+ if ($report.ExecutiveSummary.OverallCompliance -ge 80) { 'Green' }+ elseif ($report.ExecutiveSummary.OverallCompliance -ge 60) { 'Yellow' }+ else { 'Red' }+ )++ Write-Host "`nExecutive Summary:" -ForegroundColor Cyan+ Write-Host " Overall Compliance: $($report.ExecutiveSummary.OverallCompliance)%" -ForegroundColor White+ Write-Host " Total Controls: $($report.ExecutiveSummary.TotalControls)" -ForegroundColor White+ Write-Host " Compliant: $($report.ExecutiveSummary.CompliantControls)" -ForegroundColor Green+ Write-Host " Non-Compliant: $($report.ExecutiveSummary.NonCompliantControls)" -ForegroundColor Red+ Write-Host " Critical Gaps: $($report.ExecutiveSummary.CriticalGaps)" -ForegroundColor Red+ Write-Host " High Gaps: $($report.ExecutiveSummary.HighGaps)" -ForegroundColor Yellow++ Write-Host "`nFramework Results:" -ForegroundColor Cyan+ foreach ($framework in $report.Frameworks) {+ Write-Host " $($framework.Framework): $($framework.CompliancePercentage)% [$($framework.Status)]" -ForegroundColor $(+ if ($framework.Status -eq 'Pass') { 'Green' }+ elseif ($framework.Status -eq 'Marginal') { 'Yellow' }+ else { 'Red' }+ )+ }++ if ($report.CrossFrameworkAnalysis.Count -gt 0) {+ Write-Host "`nCross-Framework Gaps:" -ForegroundColor Cyan+ $report.CrossFrameworkAnalysis | ForEach-Object {+ Write-Host " $($_.SecurityArea): $($_.GapCount) gap(s) across $($_.AffectedFrameworks.Count) framework(s)" -ForegroundColor Yellow+ }+ }++ if ($report.RemediationPriorities.Count -gt 0) {+ Write-Host "`nTop Remediation Priorities:" -ForegroundColor Cyan+ $report.RemediationPriorities | Select-Object -First 5 | ForEach-Object {+ Write-Host " [$($_.Severity)] $($_.ControlID) - $($_.ControlName)" -ForegroundColor White+ }+ }++ if ($report.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $report.Recommendations | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ return $report+ }+}++# Helper function to generate HTML report+function Generate-ComplianceHTML {+ param($Report)++ $html = @"+<!DOCTYPE html>+<html>+<head>+ <title>Compliance Report - $($Report.ComputerName)</title>+ <style>+ body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }+ .container { max-width: 1200px; margin: 0 auto; background: white; padding: 30px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }+ h1 { color: #2c3e50; border-bottom: 3px solid #3498db; padding-bottom: 10px; }+ h2 { color: #34495e; margin-top: 30px; }+ .summary { background: #ecf0f1; padding: 20px; border-radius: 5px; margin: 20px 0; }+ .metric { display: inline-block; margin: 10px 20px 10px 0; }+ .metric-label { font-weight: bold; color: #7f8c8d; }+ .metric-value { font-size: 24px; font-weight: bold; }+ .pass { color: #27ae60; }+ .marginal { color: #f39c12; }+ .fail { color: #e74c3c; }+ table { width: 100%; border-collapse: collapse; margin: 20px 0; }+ th { background: #34495e; color: white; padding: 12px; text-align: left; }+ td { padding: 10px; border-bottom: 1px solid #ddd; }+ tr:hover { background: #f8f9fa; }+ .critical { background: #e74c3c; color: white; padding: 2px 8px; border-radius: 3px; }+ .high { background: #e67e22; color: white; padding: 2px 8px; border-radius: 3px; }+ .medium { background: #f39c12; color: white; padding: 2px 8px; border-radius: 3px; }+ .footer { margin-top: 40px; padding-top: 20px; border-top: 1px solid #ddd; color: #7f8c8d; font-size: 12px; }+ </style>+</head>+<body>+ <div class="container">+ <h1>Compliance Assessment Report</h1>+ <p><strong>Computer:</strong> $($Report.ComputerName) | <strong>Date:</strong> $($Report.ReportDate)</p>++ <div class="summary">+ <h2>Executive Summary</h2>+ <div class="metric">+ <div class="metric-label">Overall Compliance</div>+ <div class="metric-value $(if($Report.ExecutiveSummary.OverallCompliance -ge 80){'pass'}elseif($Report.ExecutiveSummary.OverallCompliance -ge 60){'marginal'}else{'fail'})">+ $($Report.ExecutiveSummary.OverallCompliance)%+ </div>+ </div>+ <div class="metric">+ <div class="metric-label">Total Controls</div>+ <div class="metric-value">$($Report.ExecutiveSummary.TotalControls)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Compliant</div>+ <div class="metric-value pass">$($Report.ExecutiveSummary.CompliantControls)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Non-Compliant</div>+ <div class="metric-value fail">$($Report.ExecutiveSummary.NonCompliantControls)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Critical Gaps</div>+ <div class="metric-value fail">$($Report.ExecutiveSummary.CriticalGaps)</div>+ </div>+ </div>++ <h2>Framework Results</h2>+ <table>+ <tr>+ <th>Framework</th>+ <th>Compliance</th>+ <th>Total Controls</th>+ <th>Passed</th>+ <th>Failed</th>+ <th>Status</th>+ </tr>+"@++ foreach ($fw in $Report.Frameworks) {+ $statusClass = if ($fw.Status -eq 'Pass') { 'pass' } elseif ($fw.Status -eq 'Marginal') { 'marginal' } else { 'fail' }+ $html += @"+ <tr>+ <td><strong>$($fw.Framework)</strong></td>+ <td class="$statusClass"><strong>$($fw.CompliancePercentage)%</strong></td>+ <td>$($fw.TotalControls)</td>+ <td class="pass">$($fw.Passed)</td>+ <td class="fail">$($fw.Failed)</td>+ <td class="$statusClass">$($fw.Status)</td>+ </tr>+"@+ }++ $html += @"+ </table>++ <h2>Top Remediation Priorities</h2>+ <table>+ <tr>+ <th>Priority</th>+ <th>Framework</th>+ <th>Control</th>+ <th>Remediation</th>+ </tr>+"@++ foreach ($priority in ($Report.RemediationPriorities | Select-Object -First 10)) {+ $severityClass = $priority.Severity.ToLower()+ $html += @"+ <tr>+ <td><span class="$severityClass">$($priority.Severity)</span></td>+ <td>$($priority.Framework)</td>+ <td><strong>$($priority.ControlID)</strong><br/>$($priority.ControlName)</td>+ <td>$($priority.Remediation)</td>+ </tr>+"@+ }++ $html += @"+ </table>++ <h2>Recommendations</h2>+ <ul>+"@++ foreach ($rec in $Report.Recommendations) {+ $html += " <li>$rec</li>`n"+ }++ $html += @"+ </ul>++ <div class="footer">+ Generated by WindowsSecurityAudit Module | $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')+ </div>+ </div>+</body>+</html>+"@++ return $html+}\ No newline at end of filediff --git a/Compliance/Test-CISBenchmark.ps1 b/Compliance/Test-CISBenchmark.ps1new file mode 100644index 0000000..5475948--- /dev/null+++ b/Compliance/Test-CISBenchmark.ps1@@ -0,0 +1,521 @@+function Test-CISBenchmark {+ <#+ .SYNOPSIS+ Tests system compliance against CIS Benchmark controls+ .DESCRIPTION+ Evaluates Windows system against CIS (Center for Internet Security) Benchmark+ recommendations for security configuration+ .PARAMETER Level+ CIS Benchmark Level: 1 (basic) or 2 (high security)+ .PARAMETER Category+ Specific category to test: All, PasswordPolicy, AuditPolicy, SecurityOptions, WindowsFirewall+ .EXAMPLE+ Test-CISBenchmark -Level 1+ Test-CISBenchmark -Level 2 -Category PasswordPolicy+ .OUTPUTS+ PSCustomObject with CIS compliance results+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [ValidateSet(1, 2)]+ [int]$Level = 1,++ [Parameter()]+ [ValidateSet('All', 'PasswordPolicy', 'AuditPolicy', 'SecurityOptions', 'WindowsFirewall', 'UserRights')]+ [string]$Category = 'All'+ )++ begin {+ Write-Host "=== CIS BENCHMARK COMPLIANCE TEST ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow+ Write-Host "CIS Level: $Level" -ForegroundColor Yellow+ Write-Host "Category: $Category" -ForegroundColor Yellow++ $results = [PSCustomObject]@{+ TestDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ CISLevel = $Level+ Category = $Category+ Controls = @()+ Summary = @{+ TotalControls = 0+ Passed = 0+ Failed = 0+ NotApplicable = 0+ CompliancePercentage = 0+ }+ Recommendations = @()+ }++ # Helper function to test registry value+ function Test-RegistryValue {+ param(+ [string]$Path,+ [string]$Name,+ [object]$ExpectedValue,+ [string]$Comparison = 'Equal'+ )++ try {+ if (Test-Path $Path) {+ $value = Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue | Select-Object -ExpandProperty $Name++ $result = switch ($Comparison) {+ 'Equal' { $value -eq $ExpectedValue }+ 'GreaterOrEqual' { $value -ge $ExpectedValue }+ 'LessOrEqual' { $value -le $ExpectedValue }+ 'NotEqual' { $value -ne $ExpectedValue }+ default { $false }+ }++ return @{+ Compliant = $result+ ActualValue = $value+ ExpectedValue = $ExpectedValue+ }+ }+ else {+ return @{+ Compliant = $false+ ActualValue = "Path not found"+ ExpectedValue = $ExpectedValue+ }+ }+ }+ catch {+ return @{+ Compliant = $false+ ActualValue = "Error: $_"+ ExpectedValue = $ExpectedValue+ }+ }+ }++ # Helper function to safely parse secedit value+ # Helper function to safely parse secedit value - FIXED+ function Get-SecEditValue {+ param(+ [string]$Content,+ [string]$Setting+ )++ try {+ # Split content into lines and search - FIX: regex match on lines+ $lines = $Content -split "`r?`n"+ $matchedLine = $lines | Where-Object { $_ -match "^\s*$Setting\s*=" } | Select-Object -First 1++ if ($matchedLine) {+ # Split on = and take second part, trim whitespace+ $value = ($matchedLine -split '=', 2)[1].Trim()+ return $value+ }+ return $null+ }+ catch {+ return $null+ }+ }+ }++ process {+ try {+ # 1. PASSWORD POLICY CONTROLS+ if ($Category -in @('All', 'PasswordPolicy')) {+ Write-Host "`n[1/5] Testing Password Policy Controls..." -ForegroundColor Cyan++ try {+ # Export security policy+ $tempFile = "$env:TEMP\secpol_$(Get-Random).cfg"+ $null = secedit /export /cfg $tempFile /quiet+ Start-Sleep -Milliseconds 500++ if (Test-Path $tempFile) {+ $secpolContent = Get-Content $tempFile -Raw++ # CIS 1.1.1 - Password History+ $passwordHistory = Get-SecEditValue -Content $secpolContent -Setting "PasswordHistorySize"+ if ($passwordHistory) {+ $control = [PSCustomObject]@{+ ControlID = 'CIS-1.1.1'+ ControlName = 'Enforce password history'+ Category = 'PasswordPolicy'+ Expected = '24 or more passwords'+ Actual = "$passwordHistory passwords"+ Status = if ([int]$passwordHistory -ge 24) { 'Pass' } else { 'Fail' }+ Severity = 'High'+ Remediation = 'Set to 24 or more passwords remembered'+ }+ $results.Controls += $control+ }++ # CIS 1.1.2 - Maximum password age+ $maxPasswordAge = Get-SecEditValue -Content $secpolContent -Setting "MaximumPasswordAge"+ if ($maxPasswordAge) {+ $control = [PSCustomObject]@{+ ControlID = 'CIS-1.1.2'+ ControlName = 'Maximum password age'+ Category = 'PasswordPolicy'+ Expected = '365 or fewer days (but not 0)'+ Actual = "$maxPasswordAge days"+ Status = if ([int]$maxPasswordAge -le 365 -and [int]$maxPasswordAge -gt 0) { 'Pass' } else { 'Fail' }+ Severity = 'High'+ Remediation = 'Set to 365 or fewer days'+ }+ $results.Controls += $control+ }++ # CIS 1.1.3 - Minimum password age+ $minPasswordAge = Get-SecEditValue -Content $secpolContent -Setting "MinimumPasswordAge"+ if ($minPasswordAge) {+ $control = [PSCustomObject]@{+ ControlID = 'CIS-1.1.3'+ ControlName = 'Minimum password age'+ Category = 'PasswordPolicy'+ Expected = '1 or more days'+ Actual = "$minPasswordAge days"+ Status = if ([int]$minPasswordAge -ge 1) { 'Pass' } else { 'Fail' }+ Severity = 'Medium'+ Remediation = 'Set to 1 or more days'+ }+ $results.Controls += $control+ }++ # CIS 1.1.4 - Minimum password length+ $minPasswordLength = Get-SecEditValue -Content $secpolContent -Setting "MinimumPasswordLength"+ if ($minPasswordLength) {+ $control = [PSCustomObject]@{+ ControlID = 'CIS-1.1.4'+ ControlName = 'Minimum password length'+ Category = 'PasswordPolicy'+ Expected = '14 or more characters'+ Actual = "$minPasswordLength characters"+ Status = if ([int]$minPasswordLength -ge 14) { 'Pass' } else { 'Fail' }+ Severity = 'High'+ Remediation = 'Set to 14 or more characters'+ }+ $results.Controls += $control+ }++ # CIS 1.1.5 - Password complexity+ $passwordComplexity = Get-SecEditValue -Content $secpolContent -Setting "PasswordComplexity"+ if ($passwordComplexity) {+ $control = [PSCustomObject]@{+ ControlID = 'CIS-1.1.5'+ ControlName = 'Password must meet complexity requirements'+ Category = 'PasswordPolicy'+ Expected = 'Enabled'+ Actual = if ($passwordComplexity -eq '1') { 'Enabled' } else { 'Disabled' }+ Status = if ($passwordComplexity -eq '1') { 'Pass' } else { 'Fail' }+ Severity = 'Critical'+ Remediation = 'Enable password complexity requirements'+ }+ $results.Controls += $control+ }++ Remove-Item $tempFile -Force -ErrorAction SilentlyContinue+ }+ else {+ Write-Warning "Could not export security policy"+ }+ }+ catch {+ Write-Warning "Error testing password policy: $_"+ }+ }++ # 2. AUDIT POLICY CONTROLS+ if ($Category -in @('All', 'AuditPolicy')) {+ Write-Host "`n[2/5] Testing Audit Policy Controls..." -ForegroundColor Cyan++ try {+ # CIS 17.1.1 - Audit Credential Validation+ $auditResult = auditpol /get /subcategory:"Credential Validation" 2>$null+ $auditStatus = if ($auditResult -match "Success and Failure") { "Success and Failure" } else { "Not Configured" }++ $control = [PSCustomObject]@{+ ControlID = 'CIS-17.1.1'+ ControlName = 'Audit Credential Validation'+ Category = 'AuditPolicy'+ Expected = 'Success and Failure'+ Actual = $auditStatus+ Status = if ($auditStatus -eq "Success and Failure") { 'Pass' } else { 'Fail' }+ Severity = 'High'+ Remediation = 'Configure to audit Success and Failure'+ }+ $results.Controls += $control++ # CIS 17.2.1 - Audit Application Group Management+ $auditResult = auditpol /get /subcategory:"Application Group Management" 2>$null+ $auditStatus = if ($auditResult -match "Success and Failure") { "Success and Failure" } else { "Not Configured" }++ $control = [PSCustomObject]@{+ ControlID = 'CIS-17.2.1'+ ControlName = 'Audit Application Group Management'+ Category = 'AuditPolicy'+ Expected = 'Success and Failure'+ Actual = $auditStatus+ Status = if ($auditStatus -eq "Success and Failure") { 'Pass' } else { 'Fail' }+ Severity = 'Medium'+ Remediation = 'Configure to audit Success and Failure'+ }+ $results.Controls += $control++ # CIS 17.5.1 - Audit Account Lockout+ $auditResult = auditpol /get /subcategory:"Account Lockout" 2>$null+ $auditStatus = if ($auditResult -match "Success|Failure") { "Configured" } else { "Not Configured" }++ $control = [PSCustomObject]@{+ ControlID = 'CIS-17.5.1'+ ControlName = 'Audit Account Lockout'+ Category = 'AuditPolicy'+ Expected = 'Success'+ Actual = $auditStatus+ Status = if ($auditStatus -eq "Configured") { 'Pass' } else { 'Fail' }+ Severity = 'Medium'+ Remediation = 'Configure to audit Success'+ }+ $results.Controls += $control+ }+ catch {+ Write-Warning "Error testing audit policy: $_"+ }+ }++ # 3. SECURITY OPTIONS+ if ($Category -in @('All', 'SecurityOptions')) {+ Write-Host "`n[3/5] Testing Security Options..." -ForegroundColor Cyan++ try {+ # CIS 2.3.1.1 - Accounts: Administrator account status+ $adminDisabled = (Get-LocalUser -Name "Administrator" -ErrorAction SilentlyContinue).Enabled+ $control = [PSCustomObject]@{+ ControlID = 'CIS-2.3.1.1'+ ControlName = 'Accounts: Administrator account status'+ Category = 'SecurityOptions'+ Expected = 'Disabled'+ Actual = if ($adminDisabled -eq $false) { 'Disabled' } else { 'Enabled' }+ Status = if ($adminDisabled -eq $false) { 'Pass' } else { 'Fail' }+ Severity = 'High'+ Remediation = 'Disable the built-in Administrator account'+ }+ $results.Controls += $control++ # CIS 2.3.1.5 - Accounts: Guest account status+ $guestDisabled = (Get-LocalUser -Name "Guest" -ErrorAction SilentlyContinue).Enabled+ $control = [PSCustomObject]@{+ ControlID = 'CIS-2.3.1.5'+ ControlName = 'Accounts: Guest account status'+ Category = 'SecurityOptions'+ Expected = 'Disabled'+ Actual = if ($guestDisabled -eq $false) { 'Disabled' } else { 'Enabled' }+ Status = if ($guestDisabled -eq $false) { 'Pass' } else { 'Fail' }+ Severity = 'High'+ Remediation = 'Disable the Guest account'+ }+ $results.Controls += $control++ # CIS 2.3.7.1 - Interactive logon: Do not display last user name+ $regTest = Test-RegistryValue -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' `+ -Name 'DontDisplayLastUserName' -ExpectedValue 1++ $control = [PSCustomObject]@{+ ControlID = 'CIS-2.3.7.1'+ ControlName = 'Interactive logon: Do not display last user name'+ Category = 'SecurityOptions'+ Expected = 'Enabled'+ Actual = if ($regTest.ActualValue -eq 1) { 'Enabled' } else { 'Disabled' }+ Status = if ($regTest.Compliant) { 'Pass' } else { 'Fail' }+ Severity = 'Medium'+ Remediation = 'Enable to hide last logged on user'+ }+ $results.Controls += $control++ # CIS 2.3.11.1 - Network security: Do not store LAN Manager hash+ $regTest = Test-RegistryValue -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' `+ -Name 'NoLMHash' -ExpectedValue 1++ $control = [PSCustomObject]@{+ ControlID = 'CIS-2.3.11.1'+ ControlName = 'Network security: Do not store LAN Manager hash'+ Category = 'SecurityOptions'+ Expected = 'Enabled'+ Actual = if ($regTest.ActualValue -eq 1) { 'Enabled' } else { 'Disabled' }+ Status = if ($regTest.Compliant) { 'Pass' } else { 'Fail' }+ Severity = 'High'+ Remediation = 'Enable to prevent storing weak LM hashes'+ }+ $results.Controls += $control+ }+ catch {+ Write-Warning "Error testing security options: $_"+ }+ }++ # 4. WINDOWS FIREWALL+ if ($Category -in @('All', 'WindowsFirewall')) {+ Write-Host "`n[4/5] Testing Windows Firewall..." -ForegroundColor Cyan++ try {+ $firewallProfiles = Get-NetFirewallProfile -ErrorAction SilentlyContinue++ foreach ($profile in $firewallProfiles) {+ # CIS 9.1.1 - Domain Profile Firewall State+ $control = [PSCustomObject]@{+ ControlID = "CIS-9.$($profile.Name).1"+ ControlName = "Windows Firewall: $($profile.Name): Firewall state"+ Category = 'WindowsFirewall'+ Expected = 'On'+ Actual = if ($profile.Enabled) { 'On' } else { 'Off' }+ Status = if ($profile.Enabled) { 'Pass' } else { 'Fail' }+ Severity = 'Critical'+ Remediation = "Enable Windows Firewall for $($profile.Name) profile"+ }+ $results.Controls += $control++ # CIS 9.1.2 - Inbound connections+ $control = [PSCustomObject]@{+ ControlID = "CIS-9.$($profile.Name).2"+ ControlName = "Windows Firewall: $($profile.Name): Inbound connections"+ Category = 'WindowsFirewall'+ Expected = 'Block (default)'+ Actual = $profile.DefaultInboundAction+ Status = if ($profile.DefaultInboundAction -eq 'Block') { 'Pass' } else { 'Fail' }+ Severity = 'High'+ Remediation = "Set inbound connections to Block for $($profile.Name)"+ }+ $results.Controls += $control+ }+ }+ catch {+ Write-Warning "Error testing Windows Firewall: $_"+ }+ }++ # 5. USER RIGHTS ASSIGNMENT+ if ($Category -in @('All', 'UserRights')) {+ Write-Host "`n[5/5] Testing User Rights Assignment..." -ForegroundColor Cyan++ try {+ # CIS 2.2.1 - Access this computer from the network+ $control = [PSCustomObject]@{+ ControlID = 'CIS-2.2.1'+ ControlName = 'Access this computer from the network'+ Category = 'UserRights'+ Expected = 'Administrators, Remote Desktop Users (for workstations)'+ Actual = 'Manual verification required'+ Status = 'Manual'+ Severity = 'Medium'+ Remediation = 'Limit to Administrators and Remote Desktop Users only'+ }+ $results.Controls += $control++ # CIS 2.2.3 - Allow log on locally+ $control = [PSCustomObject]@{+ ControlID = 'CIS-2.2.3'+ ControlName = 'Allow log on locally'+ Category = 'UserRights'+ Expected = 'Administrators, Users'+ Actual = 'Manual verification required'+ Status = 'Manual'+ Severity = 'Medium'+ Remediation = 'Review and restrict local logon rights'+ }+ $results.Controls += $control+ }+ catch {+ Write-Warning "Error testing user rights: $_"+ }+ }++ # Calculate summary - FIX: Use @() to ensure array+ $results.Summary.TotalControls = $results.Controls.Count+ $results.Summary.Passed = @($results.Controls | Where-Object { $_.Status -eq 'Pass' }).Count+ $results.Summary.Failed = @($results.Controls | Where-Object { $_.Status -eq 'Fail' }).Count+ $results.Summary.NotApplicable = @($results.Controls | Where-Object { $_.Status -eq 'Manual' }).Count++ if ($results.Summary.TotalControls -gt 0) {+ $testableControls = $results.Summary.TotalControls - $results.Summary.NotApplicable+ if ($testableControls -gt 0) {+ $results.Summary.CompliancePercentage = [math]::Round(+ ($results.Summary.Passed / $testableControls) * 100, 2+ )+ }+ }++ # Generate recommendations - FIX: Use @() to ensure array+ $failedCritical = @($results.Controls | Where-Object { $_.Status -eq 'Fail' -and $_.Severity -eq 'Critical' })+ $failedHigh = @($results.Controls | Where-Object { $_.Status -eq 'Fail' -and $_.Severity -eq 'High' })++ if ($failedCritical.Count -gt 0) {+ $results.Recommendations += "CRITICAL: $($failedCritical.Count) critical control(s) failed"+ $results.Recommendations += "Address critical failures immediately to reduce security risk"+ }++ if ($failedHigh.Count -gt 0) {+ $results.Recommendations += "HIGH: $($failedHigh.Count) high-severity control(s) failed"+ }++ if ($results.Summary.CompliancePercentage -lt 70) {+ $results.Recommendations += "Compliance below 70% - comprehensive security review required"+ }++ $results.Recommendations += "Review failed controls and implement remediation steps"+ $results.Recommendations += "Document exceptions for controls that cannot be implemented"++ }+ catch {+ Write-Error "Error during CIS benchmark testing: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== COMPLIANCE TEST COMPLETE ===" -ForegroundColor $(+ if ($results.Summary.CompliancePercentage -ge 80) { 'Green' }+ elseif ($results.Summary.CompliancePercentage -ge 60) { 'Yellow' }+ else { 'Red' }+ )++ Write-Host "`nCompliance Summary:" -ForegroundColor Cyan+ Write-Host " Total Controls Tested: $($results.Summary.TotalControls)" -ForegroundColor White+ Write-Host " Passed: $($results.Summary.Passed)" -ForegroundColor Green+ Write-Host " Failed: $($results.Summary.Failed)" -ForegroundColor Red+ Write-Host " Manual Review: $($results.Summary.NotApplicable)" -ForegroundColor Yellow+ Write-Host " Compliance: $($results.Summary.CompliancePercentage)%" -ForegroundColor $(+ if ($results.Summary.CompliancePercentage -ge 80) { 'Green' }+ elseif ($results.Summary.CompliancePercentage -ge 60) { 'Yellow' }+ else { 'Red' }+ )++ if ($results.Controls.Count -gt 0) {+ $failedControls = @($results.Controls | Where-Object { $_.Status -eq 'Fail' })+ if ($failedControls.Count -gt 0) {+ Write-Host "`nFailed Controls by Severity:" -ForegroundColor Cyan+ $failedBySeverity = $failedControls | Group-Object Severity+ foreach ($group in $failedBySeverity | Sort-Object Name) {+ Write-Host " $($group.Name): $($group.Count)" -ForegroundColor $(+ switch ($group.Name) {+ 'Critical' { 'Red' }+ 'High' { 'Red' }+ 'Medium' { 'Yellow' }+ default { 'White' }+ }+ )+ }+ }+ }++ if ($results.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $results.Recommendations | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ Write-Host "`nCIS Benchmarks: https://www.cisecurity.org/cis-benchmarks" -ForegroundColor Gray++ return $results+ }+}\ No newline at end of filediff --git a/Compliance/Test-NISTCompliance.ps1 b/Compliance/Test-NISTCompliance.ps1new file mode 100644index 0000000..48a53d3--- /dev/null+++ b/Compliance/Test-NISTCompliance.ps1@@ -0,0 +1,521 @@+function Test-NISTCompliance {+ <#+ .SYNOPSIS+ Tests system compliance against NIST 800-53 security controls+ .DESCRIPTION+ Evaluates Windows system against NIST (National Institute of Standards and Technology)+ SP 800-53 security and privacy controls for federal information systems+ .PARAMETER ControlFamily+ Specific control family to test: All, AccessControl, AuditAccountability,+ IdentificationAuthentication, SystemProtection, ConfigurationManagement+ .PARAMETER Revision+ NIST 800-53 revision: 4 or 5 (default: 5)+ .EXAMPLE+ Test-NISTCompliance+ Test-NISTCompliance -ControlFamily AccessControl -Revision 5+ .OUTPUTS+ PSCustomObject with NIST compliance results+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [ValidateSet('All', 'AccessControl', 'AuditAccountability', 'IdentificationAuthentication',+ 'SystemProtection', 'ConfigurationManagement')]+ [string]$ControlFamily = 'All',++ [Parameter()]+ [ValidateSet(4, 5)]+ [int]$Revision = 5+ )++ begin {+ Write-Host "=== NIST 800-53 COMPLIANCE TEST ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow+ Write-Host "Revision: NIST 800-53 Rev $Revision" -ForegroundColor Yellow+ Write-Host "Control Family: $ControlFamily" -ForegroundColor Yellow++ $results = [PSCustomObject]@{+ TestDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ NISTRevision = $Revision+ ControlFamily = $ControlFamily+ Controls = @()+ Summary = @{+ TotalControls = 0+ Compliant = 0+ NonCompliant = 0+ PartiallyCompliant = 0+ NotApplicable = 0+ CompliancePercentage = 0+ }+ Recommendations = @()+ }++ # Helper function to test registry value+ function Test-RegistryValue {+ param(+ [string]$Path,+ [string]$Name,+ [object]$ExpectedValue+ )++ try {+ if (Test-Path $Path) {+ $value = Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue |+ Select-Object -ExpandProperty $Name -ErrorAction SilentlyContinue++ return @{+ Compliant = ($value -eq $ExpectedValue)+ ActualValue = $value+ ExpectedValue = $ExpectedValue+ }+ }+ return @{+ Compliant = $false+ ActualValue = "Path not found"+ ExpectedValue = $ExpectedValue+ }+ }+ catch {+ return @{+ Compliant = $false+ ActualValue = "Error"+ ExpectedValue = $ExpectedValue+ }+ }+ }+ }++ process {+ try {+ # 1. ACCESS CONTROL (AC) FAMILY+ if ($ControlFamily -in @('All', 'AccessControl')) {+ Write-Host "`n[1/5] Testing Access Control (AC) Controls..." -ForegroundColor Cyan++ try {+ # AC-2: Account Management+ $guestDisabled = (Get-LocalUser -Name "Guest" -ErrorAction SilentlyContinue).Enabled -eq $false+ $adminDisabled = (Get-LocalUser -Name "Administrator" -ErrorAction SilentlyContinue).Enabled -eq $false++ $control = [PSCustomObject]@{+ ControlID = 'AC-2'+ ControlName = 'Account Management'+ ControlFamily = 'AccessControl'+ Description = 'Guest and default Administrator accounts should be disabled'+ Expected = 'Guest and Administrator accounts disabled'+ Actual = "Guest: $(if($guestDisabled){'Disabled'}else{'Enabled'}), Admin: $(if($adminDisabled){'Disabled'}else{'Enabled'})"+ Status = if ($guestDisabled -and $adminDisabled) { 'Compliant' }+ elseif ($guestDisabled -or $adminDisabled) { 'PartiallyCompliant' }+ else { 'NonCompliant' }+ Impact = 'High'+ Remediation = 'Disable built-in Guest and Administrator accounts'+ }+ $results.Controls += $control++ # AC-7: Unsuccessful Logon Attempts+ $regTest = Test-RegistryValue -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' `+ -Name 'MaxDevicePasswordFailedAttempts' -ExpectedValue 5++ $control = [PSCustomObject]@{+ ControlID = 'AC-7'+ ControlName = 'Unsuccessful Logon Attempts'+ ControlFamily = 'AccessControl'+ Description = 'System should lock after failed login attempts'+ Expected = '5 or fewer attempts'+ Actual = if ($regTest.ActualValue) { "$($regTest.ActualValue) attempts" } else { "Not configured" }+ Status = if ($regTest.Compliant) { 'Compliant' } else { 'NonCompliant' }+ Impact = 'High'+ Remediation = 'Configure account lockout after 5 failed attempts'+ }+ $results.Controls += $control++ # AC-11: Session Lock+ $regTest = Test-RegistryValue -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' `+ -Name 'InactivityTimeoutSecs' -ExpectedValue 900++ $control = [PSCustomObject]@{+ ControlID = 'AC-11'+ ControlName = 'Session Lock'+ ControlFamily = 'AccessControl'+ Description = 'Automatic screen lock after inactivity'+ Expected = '15 minutes (900 seconds) or less'+ Actual = if ($regTest.ActualValue) { "$([math]::Round($regTest.ActualValue/60)) minutes" } else { "Not configured" }+ Status = if ($regTest.Compliant -or $regTest.ActualValue -le 900) { 'Compliant' } else { 'NonCompliant' }+ Impact = 'Medium'+ Remediation = 'Configure screen lock timeout to 15 minutes or less'+ }+ $results.Controls += $control++ # AC-17: Remote Access+ $rdpEnabled = (Get-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name 'fDenyTSConnections' -ErrorAction SilentlyContinue).fDenyTSConnections++ $control = [PSCustomObject]@{+ ControlID = 'AC-17'+ ControlName = 'Remote Access'+ ControlFamily = 'AccessControl'+ Description = 'Remote access should be controlled and monitored'+ Expected = 'RDP disabled or properly secured'+ Actual = if ($rdpEnabled -eq 1) { "Disabled" } else { "Enabled" }+ Status = if ($rdpEnabled -eq 1) { 'Compliant' } else { 'PartiallyCompliant' }+ Impact = 'High'+ Remediation = 'Disable RDP if not needed, or ensure NLA and firewall rules'+ }+ $results.Controls += $control+ }+ catch {+ Write-Warning "Error testing Access Control: $_"+ }+ }++ # 2. AUDIT AND ACCOUNTABILITY (AU) FAMILY+ if ($ControlFamily -in @('All', 'AuditAccountability')) {+ Write-Host "`n[2/5] Testing Audit and Accountability (AU) Controls..." -ForegroundColor Cyan++ try {+ # AU-2: Audit Events+ $auditLogons = auditpol /get /subcategory:"Logon" 2>$null+ $auditConfigured = $auditLogons -match "Success and Failure|Success|Failure"++ $control = [PSCustomObject]@{+ ControlID = 'AU-2'+ ControlName = 'Audit Events'+ ControlFamily = 'AuditAccountability'+ Description = 'System must audit significant security events'+ Expected = 'Audit policies configured'+ Actual = if ($auditConfigured) { "Configured" } else { "Not configured" }+ Status = if ($auditConfigured) { 'Compliant' } else { 'NonCompliant' }+ Impact = 'High'+ Remediation = 'Enable audit policies for security events'+ }+ $results.Controls += $control++ # AU-3: Content of Audit Records+ $eventLogSize = (Get-WinEvent -ListLog Security -ErrorAction SilentlyContinue).MaximumSizeInBytes++ $control = [PSCustomObject]@{+ ControlID = 'AU-3'+ ControlName = 'Content of Audit Records'+ ControlFamily = 'AuditAccountability'+ Description = 'Audit records must contain sufficient detail'+ Expected = 'Security log size >= 100MB'+ Actual = "$([math]::Round($eventLogSize/1MB)) MB"+ Status = if ($eventLogSize -ge 100MB) { 'Compliant' } else { 'NonCompliant' }+ Impact = 'Medium'+ Remediation = 'Increase Security event log size to at least 100MB'+ }+ $results.Controls += $control++ # AU-9: Protection of Audit Information+ $logPath = "C:\Windows\System32\winevt\Logs\Security.evtx"+ if (Test-Path $logPath) {+ $acl = Get-Acl $logPath -ErrorAction SilentlyContinue+ $protected = @($acl.Access | Where-Object { $_.IdentityReference -match "Users" -and $_.FileSystemRights -match "FullControl|Modify|Write" })++ $control = [PSCustomObject]@{+ ControlID = 'AU-9'+ ControlName = 'Protection of Audit Information'+ ControlFamily = 'AuditAccountability'+ Description = 'Audit logs must be protected from unauthorized access'+ Expected = 'Security log protected from normal users'+ Actual = if ($protected.Count -gt 0) { "Weak permissions detected" } else { "Properly protected" }+ Status = if ($protected.Count -eq 0) { 'Compliant' } else { 'NonCompliant' }+ Impact = 'High'+ Remediation = 'Restrict Security event log access to administrators only'+ }+ $results.Controls += $control+ }++ # AU-12: Audit Generation+ $auditProcessCreation = auditpol /get /subcategory:"Process Creation" 2>$null+ $processAuditConfigured = $auditProcessCreation -match "Success"++ $control = [PSCustomObject]@{+ ControlID = 'AU-12'+ ControlName = 'Audit Generation'+ ControlFamily = 'AuditAccountability'+ Description = 'System must generate audit records for defined events'+ Expected = 'Process creation auditing enabled'+ Actual = if ($processAuditConfigured) { "Enabled" } else { "Disabled" }+ Status = if ($processAuditConfigured) { 'Compliant' } else { 'NonCompliant' }+ Impact = 'Medium'+ Remediation = 'Enable process creation auditing'+ }+ $results.Controls += $control+ }+ catch {+ Write-Warning "Error testing Audit and Accountability: $_"+ }+ }++ # 3. IDENTIFICATION AND AUTHENTICATION (IA) FAMILY+ if ($ControlFamily -in @('All', 'IdentificationAuthentication')) {+ Write-Host "`n[3/5] Testing Identification and Authentication (IA) Controls..." -ForegroundColor Cyan++ try {+ # IA-2: Identification and Authentication+ $passwordPolicy = net accounts 2>$null+ $minPasswordLength = ($passwordPolicy | Select-String "Minimum password length").ToString().Split(':')[1].Trim()++ $control = [PSCustomObject]@{+ ControlID = 'IA-2'+ ControlName = 'Identification and Authentication'+ ControlFamily = 'IdentificationAuthentication'+ Description = 'System must uniquely identify and authenticate users'+ Expected = 'Minimum password length >= 14 characters'+ Actual = "$minPasswordLength characters"+ Status = if ([int]$minPasswordLength -ge 14) { 'Compliant' } else { 'NonCompliant' }+ Impact = 'High'+ Remediation = 'Set minimum password length to 14 characters'+ }+ $results.Controls += $control++ # IA-5: Authenticator Management+ $maxPasswordAge = ($passwordPolicy | Select-String "Maximum password age").ToString().Split(':')[1].Trim().Split(' ')[0]++ $control = [PSCustomObject]@{+ ControlID = 'IA-5'+ ControlName = 'Authenticator Management'+ ControlFamily = 'IdentificationAuthentication'+ Description = 'Authenticators must be managed securely'+ Expected = 'Maximum password age <= 60 days'+ Actual = "$maxPasswordAge days"+ Status = if ([int]$maxPasswordAge -le 60 -and [int]$maxPasswordAge -gt 0) { 'Compliant' } else { 'NonCompliant' }+ Impact = 'High'+ Remediation = 'Set maximum password age to 60 days or less'+ }+ $results.Controls += $control++ # IA-8: Identification and Authentication (Non-Organizational Users)+ $regTest = Test-RegistryValue -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' `+ -Name 'LimitBlankPasswordUse' -ExpectedValue 1++ $control = [PSCustomObject]@{+ ControlID = 'IA-8'+ ControlName = 'Non-Organizational User Authentication'+ ControlFamily = 'IdentificationAuthentication'+ Description = 'Blank passwords should not be allowed'+ Expected = 'Blank passwords disabled'+ Actual = if ($regTest.Compliant) { "Disabled" } else { "Allowed" }+ Status = if ($regTest.Compliant) { 'Compliant' } else { 'NonCompliant' }+ Impact = 'Critical'+ Remediation = 'Disable blank password usage'+ }+ $results.Controls += $control+ }+ catch {+ Write-Warning "Error testing Identification and Authentication: $_"+ }+ }++ # 4. SYSTEM AND COMMUNICATIONS PROTECTION (SC) FAMILY+ if ($ControlFamily -in @('All', 'SystemProtection')) {+ Write-Host "`n[4/5] Testing System and Communications Protection (SC) Controls..." -ForegroundColor Cyan++ try {+ # SC-7: Boundary Protection - FIX: Wrap in @()+ $firewallProfiles = Get-NetFirewallProfile -ErrorAction SilentlyContinue+ $disabledFirewalls = @($firewallProfiles | Where-Object { -not $_.Enabled })+ $allFirewallsEnabled = $disabledFirewalls.Count -eq 0++ $control = [PSCustomObject]@{+ ControlID = 'SC-7'+ ControlName = 'Boundary Protection'+ ControlFamily = 'SystemProtection'+ Description = 'Firewall must protect system boundaries'+ Expected = 'All firewall profiles enabled'+ Actual = if ($allFirewallsEnabled) { "All enabled" } else { "Some disabled" }+ Status = if ($allFirewallsEnabled) { 'Compliant' } else { 'NonCompliant' }+ Impact = 'Critical'+ Remediation = 'Enable Windows Firewall for all profiles'+ }+ $results.Controls += $control++ # SC-8: Transmission Confidentiality and Integrity+ $regTest = Test-RegistryValue -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' `+ -Name 'NoLMHash' -ExpectedValue 1++ $control = [PSCustomObject]@{+ ControlID = 'SC-8'+ ControlName = 'Transmission Confidentiality'+ ControlFamily = 'SystemProtection'+ Description = 'Weak LAN Manager hashes should not be stored'+ Expected = 'LM hash storage disabled'+ Actual = if ($regTest.Compliant) { "Disabled" } else { "Enabled" }+ Status = if ($regTest.Compliant) { 'Compliant' } else { 'NonCompliant' }+ Impact = 'High'+ Remediation = 'Disable LAN Manager hash storage'+ }+ $results.Controls += $control++ # SC-28: Protection of Information at Rest+ $bitlockerStatus = Get-BitLockerVolume -MountPoint "C:" -ErrorAction SilentlyContinue+ $bitlockerEnabled = $bitlockerStatus.ProtectionStatus -eq 'On'++ $control = [PSCustomObject]@{+ ControlID = 'SC-28'+ ControlName = 'Protection of Information at Rest'+ ControlFamily = 'SystemProtection'+ Description = 'Data at rest should be encrypted'+ Expected = 'BitLocker enabled'+ Actual = if ($bitlockerEnabled) { "Enabled" } else { "Disabled" }+ Status = if ($bitlockerEnabled) { 'Compliant' } else { 'NonCompliant' }+ Impact = 'High'+ Remediation = 'Enable BitLocker encryption'+ }+ $results.Controls += $control+ }+ catch {+ Write-Warning "Error testing System Protection: $_"+ }+ }++ # 5. CONFIGURATION MANAGEMENT (CM) FAMILY+ if ($ControlFamily -in @('All', 'ConfigurationManagement')) {+ Write-Host "`n[5/5] Testing Configuration Management (CM) Controls..." -ForegroundColor Cyan++ try {+ # CM-6: Configuration Settings+ $defenderStatus = Get-MpComputerStatus -ErrorAction SilentlyContinue+ $defenderEnabled = $defenderStatus.AntivirusEnabled++ $control = [PSCustomObject]@{+ ControlID = 'CM-6'+ ControlName = 'Configuration Settings'+ ControlFamily = 'ConfigurationManagement'+ Description = 'Security configuration settings must be established'+ Expected = 'Windows Defender enabled'+ Actual = if ($defenderEnabled) { "Enabled" } else { "Disabled" }+ Status = if ($defenderEnabled) { 'Compliant' } else { 'NonCompliant' }+ Impact = 'Critical'+ Remediation = 'Enable Windows Defender antivirus'+ }+ $results.Controls += $control++ # CM-7: Least Functionality - FIX: Wrap in @()+ $allServices = Get-Service -ErrorAction SilentlyContinue+ $unnecessaryServices = @($allServices | Where-Object {+ $_.Name -in @('TlntSvr', 'SNMP', 'SSDPSRV') -and $_.Status -eq 'Running'+ })++ $control = [PSCustomObject]@{+ ControlID = 'CM-7'+ ControlName = 'Least Functionality'+ ControlFamily = 'ConfigurationManagement'+ Description = 'Unnecessary services should be disabled'+ Expected = 'No unnecessary services running'+ Actual = if ($unnecessaryServices.Count -eq 0) { "Clean" } else { "$($unnecessaryServices.Count) unnecessary services" }+ Status = if ($unnecessaryServices.Count -eq 0) { 'Compliant' } else { 'NonCompliant' }+ Impact = 'Medium'+ Remediation = 'Disable unnecessary services (Telnet, SNMP, SSDP)'+ }+ $results.Controls += $control++ # CM-8: Information System Component Inventory+ $control = [PSCustomObject]@{+ ControlID = 'CM-8'+ ControlName = 'System Component Inventory'+ ControlFamily = 'ConfigurationManagement'+ Description = 'Maintain accurate inventory of system components'+ Expected = 'Inventory maintained'+ Actual = 'Manual verification required'+ Status = 'NotApplicable'+ Impact = 'Low'+ Remediation = 'Implement automated inventory management'+ }+ $results.Controls += $control+ }+ catch {+ Write-Warning "Error testing Configuration Management: $_"+ }+ }++ # Calculate summary - FIX: All wrapped in @()+ $results.Summary.TotalControls = $results.Controls.Count+ $results.Summary.Compliant = @($results.Controls | Where-Object { $_.Status -eq 'Compliant' }).Count+ $results.Summary.NonCompliant = @($results.Controls | Where-Object { $_.Status -eq 'NonCompliant' }).Count+ $results.Summary.PartiallyCompliant = @($results.Controls | Where-Object { $_.Status -eq 'PartiallyCompliant' }).Count+ $results.Summary.NotApplicable = @($results.Controls | Where-Object { $_.Status -eq 'NotApplicable' }).Count++ $testableControls = $results.Summary.TotalControls - $results.Summary.NotApplicable+ if ($testableControls -gt 0) {+ $compliantCount = $results.Summary.Compliant + ($results.Summary.PartiallyCompliant * 0.5)+ $results.Summary.CompliancePercentage = [math]::Round(($compliantCount / $testableControls) * 100, 2)+ }++ # Generate recommendations - FIX: All wrapped in @()+ $criticalFailed = @($results.Controls | Where-Object { $_.Status -eq 'NonCompliant' -and $_.Impact -eq 'Critical' })+ $highFailed = @($results.Controls | Where-Object { $_.Status -eq 'NonCompliant' -and $_.Impact -eq 'High' })++ if ($criticalFailed.Count -gt 0) {+ $results.Recommendations += "CRITICAL: $($criticalFailed.Count) critical control(s) non-compliant"+ $results.Recommendations += "Address critical controls immediately"+ }++ if ($highFailed.Count -gt 0) {+ $results.Recommendations += "HIGH: $($highFailed.Count) high-impact control(s) non-compliant"+ }++ if ($results.Summary.CompliancePercentage -lt 80) {+ $results.Recommendations += "Compliance below 80% - implement remediation plan"+ }++ $results.Recommendations += "Review all non-compliant controls"+ $results.Recommendations += "Document compensating controls where applicable"++ }+ catch {+ Write-Error "Error during NIST compliance testing: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== COMPLIANCE TEST COMPLETE ===" -ForegroundColor $(+ if ($results.Summary.CompliancePercentage -ge 80) { 'Green' }+ elseif ($results.Summary.CompliancePercentage -ge 60) { 'Yellow' }+ else { 'Red' }+ )++ Write-Host "`nCompliance Summary:" -ForegroundColor Cyan+ Write-Host " Total Controls Tested: $($results.Summary.TotalControls)" -ForegroundColor White+ Write-Host " Compliant: $($results.Summary.Compliant)" -ForegroundColor Green+ Write-Host " Non-Compliant: $($results.Summary.NonCompliant)" -ForegroundColor Red+ Write-Host " Partially Compliant: $($results.Summary.PartiallyCompliant)" -ForegroundColor Yellow+ Write-Host " Not Applicable: $($results.Summary.NotApplicable)" -ForegroundColor Gray+ Write-Host " Compliance: $($results.Summary.CompliancePercentage)%" -ForegroundColor $(+ if ($results.Summary.CompliancePercentage -ge 80) { 'Green' }+ elseif ($results.Summary.CompliancePercentage -ge 60) { 'Yellow' }+ else { 'Red' }+ )++ if ($results.Controls.Count -gt 0) {+ $nonCompliant = @($results.Controls | Where-Object { $_.Status -eq 'NonCompliant' })+ if ($nonCompliant.Count -gt 0) {+ Write-Host "`nNon-Compliant Controls by Impact:" -ForegroundColor Cyan+ $failedByImpact = $nonCompliant | Group-Object Impact+ foreach ($group in $failedByImpact | Sort-Object Name) {+ Write-Host " $($group.Name): $($group.Count)" -ForegroundColor $(+ switch ($group.Name) {+ 'Critical' { 'Red' }+ 'High' { 'Red' }+ 'Medium' { 'Yellow' }+ default { 'White' }+ }+ )+ }+ }+ }++ if ($results.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $results.Recommendations | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ Write-Host "`nNIST SP 800-53: https://csrc.nist.gov/publications/detail/sp/800-53/rev-5/final" -ForegroundColor Gray++ return $results+ }+}\ No newline at end of filediff --git a/Compliance/Test-PCI-DSS.ps1 b/Compliance/Test-PCI-DSS.ps1new file mode 100644index 0000000..62ce0fb--- /dev/null+++ b/Compliance/Test-PCI-DSS.ps1@@ -0,0 +1,519 @@+function Test-PCI-DSS {+ <#+ .SYNOPSIS+ Tests system compliance against PCI-DSS requirements+ .DESCRIPTION+ Evaluates Windows system against Payment Card Industry Data Security Standard (PCI-DSS)+ requirements for systems that store, process, or transmit cardholder data+ .PARAMETER Version+ PCI-DSS version: 3.2.1 or 4.0 (default: 4.0)+ .PARAMETER RequirementFilter+ Specific requirement to test: All, Network, Data, AccessControl, Monitoring, Testing+ .EXAMPLE+ Test-PCI-DSS+ Test-PCI-DSS -Version 4.0 -RequirementFilter Network+ .OUTPUTS+ PSCustomObject with PCI-DSS compliance results+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [ValidateSet('3.2.1', '4.0')]+ [string]$Version = '4.0',++ [Parameter()]+ [ValidateSet('All', 'Network', 'Data', 'AccessControl', 'Monitoring', 'Testing')]+ [string]$RequirementFilter = 'All'+ )++ begin {+ Write-Host "=== PCI-DSS COMPLIANCE TEST ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow+ Write-Host "PCI-DSS Version: $Version" -ForegroundColor Yellow+ Write-Host "Requirement: $RequirementFilter" -ForegroundColor Yellow++ $results = [PSCustomObject]@{+ TestDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ PCIDSSVersion = $Version+ RequirementFilter = $RequirementFilter+ Requirements = @()+ Summary = @{+ TotalRequirements = 0+ InPlace = 0+ NotInPlace = 0+ NotApplicable = 0+ CompliancePercentage = 0+ }+ Recommendations = @()+ }++ # Helper function to test registry value+ function Test-RegistryValue {+ param(+ [string]$Path,+ [string]$Name,+ [object]$ExpectedValue+ )++ try {+ if (Test-Path $Path) {+ $value = Get-ItemProperty -Path $Path -Name $Name -ErrorAction SilentlyContinue |+ Select-Object -ExpandProperty $Name -ErrorAction SilentlyContinue++ return @{+ Compliant = ($value -eq $ExpectedValue)+ ActualValue = $value+ ExpectedValue = $ExpectedValue+ }+ }+ return @{+ Compliant = $false+ ActualValue = "Path not found"+ ExpectedValue = $ExpectedValue+ }+ }+ catch {+ return @{+ Compliant = $false+ ActualValue = "Error"+ ExpectedValue = $ExpectedValue+ }+ }+ }+ }++ process {+ try {+ # 1. REQUIREMENT 1: Install and maintain network security controls+ if ($RequirementFilter -in @('All', 'Network')) {+ Write-Host "`n[1/6] Testing Requirement 1: Network Security Controls..." -ForegroundColor Cyan++ try {+ # Req 1.2: Network security controls (firewalls)+ $firewallProfiles = Get-NetFirewallProfile -ErrorAction SilentlyContinue+ $allFirewallsEnabled = @($firewallProfiles | Where-Object { -not $_.Enabled }).Count -eq 0++ $req = [PSCustomObject]@{+ RequirementID = '1.2.1'+ RequirementName = 'Firewall Configuration'+ Category = 'Network'+ Description = 'Firewalls must be enabled and properly configured'+ Expected = 'All firewall profiles enabled'+ Actual = if ($allFirewallsEnabled) { "All enabled" } else { "Some disabled" }+ Status = if ($allFirewallsEnabled) { 'InPlace' } else { 'NotInPlace' }+ Priority = 'Critical'+ Remediation = 'Enable all Windows Firewall profiles (Domain, Private, Public)'+ }+ $results.Requirements += $req++ # Req 1.3: Inbound traffic restrictions+ $defaultInboundBlock = @($firewallProfiles | Where-Object { $_.DefaultInboundAction -ne 'Block' })++ $req = [PSCustomObject]@{+ RequirementID = '1.3.1'+ RequirementName = 'Inbound Traffic Restriction'+ Category = 'Network'+ Description = 'Inbound traffic should be denied by default'+ Expected = 'Default action: Block'+ Actual = if ($defaultInboundBlock.Count -eq 0) { "All blocked" } else { "$($defaultInboundBlock.Count) profiles allow" }+ Status = if ($defaultInboundBlock.Count -eq 0) { 'InPlace' } else { 'NotInPlace' }+ Priority = 'High'+ Remediation = 'Set default inbound action to Block for all profiles'+ }+ $results.Requirements += $req++ # Req 1.4: Restrict connections between untrusted networks+ $publicProfile = $firewallProfiles | Where-Object { $_.Name -eq 'Public' }++ $req = [PSCustomObject]@{+ RequirementID = '1.4.1'+ RequirementName = 'Public Network Protection'+ Category = 'Network'+ Description = 'Public network profile must be restrictive'+ Expected = 'Public profile enabled and blocking inbound'+ Actual = "Enabled: $($publicProfile.Enabled), Inbound: $($publicProfile.DefaultInboundAction)"+ Status = if ($publicProfile.Enabled -and $publicProfile.DefaultInboundAction -eq 'Block') { 'InPlace' } else { 'NotInPlace' }+ Priority = 'High'+ Remediation = 'Enable Public profile with default inbound block'+ }+ $results.Requirements += $req+ }+ catch {+ Write-Warning "Error testing Network requirements: $_"+ }+ }++ # 2. REQUIREMENT 3: Protect stored account data+ if ($RequirementFilter -in @('All', 'Data')) {+ Write-Host "`n[2/6] Testing Requirement 3: Protect Stored Data..." -ForegroundColor Cyan++ try {+ # Req 3.3: Sensitive authentication data not retained+ $req = [PSCustomObject]@{+ RequirementID = '3.3.1'+ RequirementName = 'Sensitive Data Retention'+ Category = 'Data'+ Description = 'Sensitive authentication data must not be stored'+ Expected = 'No card data stored (manual verification)'+ Actual = 'Manual verification required'+ Status = 'NotApplicable'+ Priority = 'Critical'+ Remediation = 'Ensure no full track data, CVV2, or PIN blocks are stored'+ }+ $results.Requirements += $req++ # Req 3.5: Primary account number (PAN) protection+ $bitlockerStatus = Get-BitLockerVolume -MountPoint "C:" -ErrorAction SilentlyContinue+ $bitlockerEnabled = $bitlockerStatus.ProtectionStatus -eq 'On'++ $req = [PSCustomObject]@{+ RequirementID = '3.5.1'+ RequirementName = 'Data at Rest Encryption'+ Category = 'Data'+ Description = 'PAN must be rendered unreadable (encryption)'+ Expected = 'Disk encryption enabled (BitLocker)'+ Actual = if ($bitlockerEnabled) { "Enabled" } else { "Disabled" }+ Status = if ($bitlockerEnabled) { 'InPlace' } else { 'NotInPlace' }+ Priority = 'Critical'+ Remediation = 'Enable BitLocker or third-party disk encryption'+ }+ $results.Requirements += $req++ # Req 3.6: Cryptographic key management+ $req = [PSCustomObject]@{+ RequirementID = '3.6.1'+ RequirementName = 'Key Management'+ Category = 'Data'+ Description = 'Cryptographic keys must be managed securely'+ Expected = 'Key management procedures documented'+ Actual = 'Manual verification required'+ Status = 'NotApplicable'+ Priority = 'High'+ Remediation = 'Document and implement key management procedures'+ }+ $results.Requirements += $req+ }+ catch {+ Write-Warning "Error testing Data Protection requirements: $_"+ }+ }++ # 3. REQUIREMENT 7 & 8: Access Control+ if ($RequirementFilter -in @('All', 'AccessControl')) {+ Write-Host "`n[3/6] Testing Requirements 7 & 8: Access Control..." -ForegroundColor Cyan++ try {+ # Req 7.1: Limit access to system components+ $guestDisabled = (Get-LocalUser -Name "Guest" -ErrorAction SilentlyContinue).Enabled -eq $false++ $req = [PSCustomObject]@{+ RequirementID = '7.1.1'+ RequirementName = 'Access Limitations'+ Category = 'AccessControl'+ Description = 'Unnecessary accounts must be disabled'+ Expected = 'Guest account disabled'+ Actual = if ($guestDisabled) { "Disabled" } else { "Enabled" }+ Status = if ($guestDisabled) { 'InPlace' } else { 'NotInPlace' }+ Priority = 'High'+ Remediation = 'Disable Guest and other unnecessary accounts'+ }+ $results.Requirements += $req++ # Req 8.2: User identification and authentication+ $passwordPolicy = net accounts 2>$null+ $minPasswordLength = ($passwordPolicy | Select-String "Minimum password length").ToString().Split(':')[1].Trim()++ $req = [PSCustomObject]@{+ RequirementID = '8.2.3'+ RequirementName = 'Password Complexity'+ Category = 'AccessControl'+ Description = 'Passwords must meet minimum complexity'+ Expected = 'Minimum 12 characters (or 8 if MFA)'+ Actual = "$minPasswordLength characters"+ Status = if ([int]$minPasswordLength -ge 12) { 'InPlace' } else { 'NotInPlace' }+ Priority = 'Critical'+ Remediation = 'Set minimum password length to 12 characters'+ }+ $results.Requirements += $req++ # Req 8.2.4: Change passwords every 90 days+ $maxPasswordAge = ($passwordPolicy | Select-String "Maximum password age").ToString().Split(':')[1].Trim().Split(' ')[0]++ $req = [PSCustomObject]@{+ RequirementID = '8.2.4'+ RequirementName = 'Password Change Frequency'+ Category = 'AccessControl'+ Description = 'Passwords must be changed periodically'+ Expected = '90 days or less'+ Actual = "$maxPasswordAge days"+ Status = if ([int]$maxPasswordAge -le 90 -and [int]$maxPasswordAge -gt 0) { 'InPlace' } else { 'NotInPlace' }+ Priority = 'High'+ Remediation = 'Set maximum password age to 90 days'+ }+ $results.Requirements += $req++ # Req 8.3: Multi-factor authentication+ $req = [PSCustomObject]@{+ RequirementID = '8.3.1'+ RequirementName = 'Multi-Factor Authentication'+ Category = 'AccessControl'+ Description = 'MFA required for all access to CDE'+ Expected = 'MFA enabled for administrators'+ Actual = 'Manual verification required'+ Status = 'NotApplicable'+ Priority = 'Critical'+ Remediation = 'Implement MFA (Windows Hello, Smart Card, or third-party)'+ }+ $results.Requirements += $req+ }+ catch {+ Write-Warning "Error testing Access Control requirements: $_"+ }+ }++ # 4. REQUIREMENT 10: Log and monitor all access+ if ($RequirementFilter -in @('All', 'Monitoring')) {+ Write-Host "`n[4/6] Testing Requirement 10: Logging and Monitoring..." -ForegroundColor Cyan++ try {+ # Req 10.2: Audit logs for all users+ $auditLogons = auditpol /get /subcategory:"Logon" 2>$null+ $logonAuditEnabled = $auditLogons -match "Success and Failure"++ $req = [PSCustomObject]@{+ RequirementID = '10.2.1'+ RequirementName = 'User Access Logging'+ Category = 'Monitoring'+ Description = 'All access to system components must be logged'+ Expected = 'Logon auditing: Success and Failure'+ Actual = if ($logonAuditEnabled) { "Enabled" } else { "Not configured" }+ Status = if ($logonAuditEnabled) { 'InPlace' } else { 'NotInPlace' }+ Priority = 'Critical'+ Remediation = 'Enable audit policy for Logon events'+ }+ $results.Requirements += $req++ # Req 10.3: Audit trail content+ $auditObjectAccess = auditpol /get /subcategory:"File System" 2>$null+ $objectAuditEnabled = $auditObjectAccess -match "Success|Failure"++ $req = [PSCustomObject]@{+ RequirementID = '10.3.1'+ RequirementName = 'Audit Trail Details'+ Category = 'Monitoring'+ Description = 'Logs must contain sufficient detail'+ Expected = 'File system auditing enabled'+ Actual = if ($objectAuditEnabled) { "Enabled" } else { "Not configured" }+ Status = if ($objectAuditEnabled) { 'InPlace' } else { 'NotInPlace' }+ Priority = 'High'+ Remediation = 'Enable file system object access auditing'+ }+ $results.Requirements += $req++ # Req 10.5: Protect audit trails+ $eventLogSize = (Get-WinEvent -ListLog Security -ErrorAction SilentlyContinue).MaximumSizeInBytes++ $req = [PSCustomObject]@{+ RequirementID = '10.5.1'+ RequirementName = 'Audit Trail Protection'+ Category = 'Monitoring'+ Description = 'Audit trails must be secured and retained'+ Expected = 'Security log >= 100MB'+ Actual = "$([math]::Round($eventLogSize/1MB)) MB"+ Status = if ($eventLogSize -ge 100MB) { 'InPlace' } else { 'NotInPlace' }+ Priority = 'High'+ Remediation = 'Increase Security log size to at least 100MB'+ }+ $results.Requirements += $req++ # Req 10.7: Time synchronization+ $w32timeService = Get-Service -Name W32Time -ErrorAction SilentlyContinue++ $req = [PSCustomObject]@{+ RequirementID = '10.7.1'+ RequirementName = 'Time Synchronization'+ Category = 'Monitoring'+ Description = 'System clocks must be synchronized'+ Expected = 'Windows Time service running'+ Actual = if ($w32timeService) { $w32timeService.Status } else { "Not found" }+ Status = if ($w32timeService.Status -eq 'Running') { 'InPlace' } else { 'NotInPlace' }+ Priority = 'Medium'+ Remediation = 'Ensure Windows Time service is running and configured'+ }+ $results.Requirements += $req+ }+ catch {+ Write-Warning "Error testing Monitoring requirements: $_"+ }+ }++ # 5. REQUIREMENT 11: Test security systems regularly+ if ($RequirementFilter -in @('All', 'Testing')) {+ Write-Host "`n[5/6] Testing Requirement 11: Security Testing..." -ForegroundColor Cyan++ try {+ # Req 11.3: Vulnerability scanning+ $defenderStatus = Get-MpComputerStatus -ErrorAction SilentlyContinue+ $defenderEnabled = $defenderStatus.AntivirusEnabled++ $req = [PSCustomObject]@{+ RequirementID = '11.3.1'+ RequirementName = 'Vulnerability Management'+ Category = 'Testing'+ Description = 'Vulnerability scans must be performed'+ Expected = 'Antivirus enabled'+ Actual = if ($defenderEnabled) { "Windows Defender enabled" } else { "Disabled" }+ Status = if ($defenderEnabled) { 'InPlace' } else { 'NotInPlace' }+ Priority = 'Critical'+ Remediation = 'Enable Windows Defender or approved antivirus'+ }+ $results.Requirements += $req++ # Req 11.5: Change detection+ $req = [PSCustomObject]@{+ RequirementID = '11.5.1'+ RequirementName = 'File Integrity Monitoring'+ Category = 'Testing'+ Description = 'Implement file integrity monitoring'+ Expected = 'FIM solution deployed'+ Actual = 'Manual verification required'+ Status = 'NotApplicable'+ Priority = 'High'+ Remediation = 'Implement file integrity monitoring (FIM) solution'+ }+ $results.Requirements += $req+ }+ catch {+ Write-Warning "Error testing Security Testing requirements: $_"+ }+ }++ # 6. REQUIREMENT 12: Support information security with organizational policies+ if ($RequirementFilter -in @('All')) {+ Write-Host "`n[6/6] Testing Requirement 12: Security Policies..." -ForegroundColor Cyan++ try {+ # Req 12.1: Security policy+ $req = [PSCustomObject]@{+ RequirementID = '12.1.1'+ RequirementName = 'Information Security Policy'+ Category = 'Policy'+ Description = 'Establish security policy'+ Expected = 'Security policy documented and reviewed annually'+ Actual = 'Manual verification required'+ Status = 'NotApplicable'+ Priority = 'High'+ Remediation = 'Document and maintain information security policy'+ }+ $results.Requirements += $req++ # Req 12.10: Incident response plan+ $req = [PSCustomObject]@{+ RequirementID = '12.10.1'+ RequirementName = 'Incident Response Plan'+ Category = 'Policy'+ Description = 'Implement incident response plan'+ Expected = 'Incident response plan documented and tested'+ Actual = 'Manual verification required'+ Status = 'NotApplicable'+ Priority = 'Critical'+ Remediation = 'Create and test incident response procedures'+ }+ $results.Requirements += $req+ }+ catch {+ Write-Warning "Error testing Policy requirements: $_"+ }+ }++ # Calculate summary+ $results.Summary.TotalRequirements = $results.Requirements.Count+ $results.Summary.InPlace = @($results.Requirements | Where-Object { $_.Status -eq 'InPlace' }).Count+ $results.Summary.NotInPlace = @($results.Requirements | Where-Object { $_.Status -eq 'NotInPlace' }).Count+ $results.Summary.NotApplicable = @($results.Requirements | Where-Object { $_.Status -eq 'NotApplicable' }).Count++ $testableRequirements = $results.Summary.TotalRequirements - $results.Summary.NotApplicable+ if ($testableRequirements -gt 0) {+ $results.Summary.CompliancePercentage = [math]::Round(+ ($results.Summary.InPlace / $testableRequirements) * 100, 2+ )+ }++ # Generate recommendations+ $criticalNotInPlace = @($results.Requirements | Where-Object { $_.Status -eq 'NotInPlace' -and $_.Priority -eq 'Critical' })+ $highNotInPlace = @($results.Requirements | Where-Object { $_.Status -eq 'NotInPlace' -and $_.Priority -eq 'High' })++ if ($criticalNotInPlace.Count -gt 0) {+ $results.Recommendations += "CRITICAL: $($criticalNotInPlace.Count) critical requirement(s) not in place"+ $results.Recommendations += "Address critical gaps immediately to achieve compliance"+ }++ if ($highNotInPlace.Count -gt 0) {+ $results.Recommendations += "HIGH: $($highNotInPlace.Count) high-priority requirement(s) not in place"+ }++ if ($results.Summary.CompliancePercentage -lt 100) {+ $results.Recommendations += "Full PCI-DSS compliance requires all requirements to be in place"+ }++ $results.Recommendations += "Engage a Qualified Security Assessor (QSA) for formal validation"+ $results.Recommendations += "Review PCI-DSS Self-Assessment Questionnaire (SAQ) for your merchant level"++ }+ catch {+ Write-Error "Error during PCI-DSS compliance testing: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== COMPLIANCE TEST COMPLETE ===" -ForegroundColor $(+ if ($results.Summary.CompliancePercentage -eq 100) { 'Green' }+ elseif ($results.Summary.CompliancePercentage -ge 80) { 'Yellow' }+ else { 'Red' }+ )++ Write-Host "`nCompliance Summary:" -ForegroundColor Cyan+ Write-Host " Total Requirements Tested: $($results.Summary.TotalRequirements)" -ForegroundColor White+ Write-Host " In Place: $($results.Summary.InPlace)" -ForegroundColor Green+ Write-Host " Not In Place: $($results.Summary.NotInPlace)" -ForegroundColor Red+ Write-Host " Not Applicable: $($results.Summary.NotApplicable)" -ForegroundColor Gray+ Write-Host " Compliance: $($results.Summary.CompliancePercentage)%" -ForegroundColor $(+ if ($results.Summary.CompliancePercentage -eq 100) { 'Green' }+ elseif ($results.Summary.CompliancePercentage -ge 80) { 'Yellow' }+ else { 'Red' }+ )++ if ($results.Requirements.Count -gt 0) {+ $notInPlace = @($results.Requirements | Where-Object { $_.Status -eq 'NotInPlace' })+ if ($notInPlace.Count -gt 0) {+ Write-Host "`nGaps by Priority:" -ForegroundColor Cyan+ $gapsByPriority = $notInPlace | Group-Object Priority+ foreach ($group in $gapsByPriority | Sort-Object Name) {+ Write-Host " $($group.Name): $($group.Count)" -ForegroundColor $(+ switch ($group.Name) {+ 'Critical' { 'Red' }+ 'High' { 'Red' }+ 'Medium' { 'Yellow' }+ default { 'White' }+ }+ )+ }+ }+ }++ if ($results.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $results.Recommendations | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ Write-Host "`nPCI Security Standards: https://www.pcisecuritystandards.org/" -ForegroundColor Gray+ Write-Host "Note: This is a preliminary assessment. Formal PCI-DSS compliance requires QSA validation." -ForegroundColor Yellow++ return $results+ }+}\ No newline at end of filediff --git a/Core/Get-EventIdDescription.ps1 b/Core/Get-EventIdDescription.ps1new file mode 100644index 0000000..ce38be0--- /dev/null+++ b/Core/Get-EventIdDescription.ps1@@ -0,0 +1,292 @@+function Get-EventIdDescription {+ <#+ .SYNOPSIS+ Gets detailed description and context for Windows Event IDs+ .DESCRIPTION+ Provides comprehensive information about Windows Event IDs including+ security implications, MITRE ATT&CK mappings, and recommended actions+ .PARAMETER EventId+ Event ID to look up+ .PARAMETER Source+ Event source/provider name+ .EXAMPLE+ Get-EventIdDescription -EventId 4624+ Get-EventIdDescription -EventId 4625 -Source "Microsoft-Windows-Security-Auditing"+ .OUTPUTS+ PSCustomObject with event description and analysis+ #>++ [CmdletBinding()]+ param(+ [Parameter(Mandatory = $true, Position = 0)]+ [int]$EventId,++ [Parameter(Position = 1)]+ [string]$Source = "Security"+ )++ # Event ID database with security context+ $eventDatabase = @{+ # Authentication Events+ 4624 = @{+ Category = "Authentication"+ Description = "An account was successfully logged on"+ Severity = "Informational"+ MITREAttack = @("T1078 - Valid Accounts")+ SecurityImplication = "Normal login activity. Monitor for unusual times, sources, or logon types."+ RecommendedAction = "Review logon type, source IP, and time. Look for patterns."+ CommonLogonTypes = @{+ 2 = "Interactive (local logon)"+ 3 = "Network (e.g., shared folder access)"+ 4 = "Batch (scheduled task)"+ 5 = "Service"+ 7 = "Unlock (workstation unlock)"+ 8 = "NetworkCleartext (IIS basic auth)"+ 9 = "NewCredentials (RunAs)"+ 10 = "RemoteInteractive (RDP)"+ 11 = "CachedInteractive (cached credentials)"+ }+ }++ 4625 = @{+ Category = "Authentication"+ Description = "An account failed to log on"+ Severity = "Warning"+ MITREAttack = @("T1110 - Brute Force", "T1078 - Valid Accounts")+ SecurityImplication = "Failed login attempt. Multiple failures may indicate brute force attack or password spray."+ RecommendedAction = "Investigate source IP, account name, and failure reason. Check for patterns."+ CommonFailureReasons = @{+ "0xC000006D" = "Bad username or password"+ "0xC000006E" = "Account restriction"+ "0xC000006F" = "Logon outside allowed time"+ "0xC0000070" = "Workstation restriction"+ "0xC0000071" = "Password expired"+ "0xC0000072" = "Account disabled"+ "0xC0000193" = "Account expiration"+ "0xC0000224" = "Password change required"+ "0xC0000234" = "Account locked out"+ }+ }++ 4634 = @{+ Category = "Authentication"+ Description = "An account was logged off"+ Severity = "Informational"+ MITREAttack = @()+ SecurityImplication = "Normal logoff activity. Correlate with 4624 for session duration."+ RecommendedAction = "Use to establish user activity timelines."+ }++ 4648 = @{+ Category = "Authentication"+ Description = "A logon was attempted using explicit credentials"+ Severity = "Warning"+ MITREAttack = @("T1078 - Valid Accounts", "T1550 - Use Alternate Authentication Material")+ SecurityImplication = "RunAs or credential delegation. May indicate privilege escalation or lateral movement."+ RecommendedAction = "Verify the legitimacy of credential usage. Check target account and system."+ }++ 4672 = @{+ Category = "Privilege Use"+ Description = "Special privileges assigned to new logon"+ Severity = "Warning"+ MITREAttack = @("T1078.003 - Valid Accounts: Local Accounts")+ SecurityImplication = "Administrative privileges granted. Monitor for unauthorized admin access."+ RecommendedAction = "Verify user should have admin rights. Correlate with 4624."+ }++ 4688 = @{+ Category = "Process Tracking"+ Description = "A new process has been created"+ Severity = "Informational"+ MITREAttack = @("T1059 - Command and Scripting Interpreter")+ SecurityImplication = "Process creation tracking. Essential for detecting malicious execution."+ RecommendedAction = "Enable command-line logging. Monitor for suspicious processes."+ }++ 4697 = @{+ Category = "System"+ Description = "A service was installed in the system"+ Severity = "Warning"+ MITREAttack = @("T1543.003 - Create or Modify System Process: Windows Service")+ SecurityImplication = "New service creation. Common persistence mechanism."+ RecommendedAction = "Verify service legitimacy, check binary location and signature."+ }++ 4698 = @{+ Category = "Task Scheduler"+ Description = "A scheduled task was created"+ Severity = "Warning"+ MITREAttack = @("T1053.005 - Scheduled Task/Job: Scheduled Task")+ SecurityImplication = "Scheduled task creation. Common persistence and execution method."+ RecommendedAction = "Review task details, actions, and trigger conditions."+ }++ 4699 = @{+ Category = "Task Scheduler"+ Description = "A scheduled task was deleted"+ Severity = "Informational"+ MITREAttack = @("T1070.004 - Indicator Removal: File Deletion")+ SecurityImplication = "Task deletion may indicate cleanup after compromise."+ RecommendedAction = "Investigate why task was deleted and by whom."+ }++ 4700 = @{+ Category = "Task Scheduler"+ Description = "A scheduled task was enabled"+ Severity = "Warning"+ MITREAttack = @("T1053.005 - Scheduled Task/Job: Scheduled Task")+ SecurityImplication = "Task enabled - check if authorized."+ RecommendedAction = "Review task configuration and execution history."+ }++ 4701 = @{+ Category = "Task Scheduler"+ Description = "A scheduled task was disabled"+ Severity = "Warning"+ MITREAttack = @("T1562.001 - Impair Defenses: Disable or Modify Tools")+ SecurityImplication = "Task disabled - may disable security monitoring."+ RecommendedAction = "Verify legitimacy of task disabling."+ }++ 4719 = @{+ Category = "Policy Change"+ Description = "System audit policy was changed"+ Severity = "High"+ MITREAttack = @("T1562.002 - Impair Defenses: Disable Windows Event Logging")+ SecurityImplication = "Audit policy change. Attackers may disable logging."+ RecommendedAction = "Immediate investigation required. Verify authorization."+ }++ 4720 = @{+ Category = "Account Management"+ Description = "A user account was created"+ Severity = "Warning"+ MITREAttack = @("T1136.001 - Create Account: Local Account")+ SecurityImplication = "New account creation. Verify legitimacy."+ RecommendedAction = "Check account permissions and creation context."+ }++ 4722 = @{+ Category = "Account Management"+ Description = "A user account was enabled"+ Severity = "Warning"+ MITREAttack = @("T1098 - Account Manipulation")+ SecurityImplication = "Account enabled. May reactivate dormant account."+ RecommendedAction = "Verify authorization and account purpose."+ }++ 4724 = @{+ Category = "Account Management"+ Description = "An attempt was made to reset an account's password"+ Severity = "Warning"+ MITREAttack = @("T1098 - Account Manipulation")+ SecurityImplication = "Password reset attempt. May indicate account takeover."+ RecommendedAction = "Verify user initiated reset. Check for unauthorized access."+ }++ 4732 = @{+ Category = "Account Management"+ Description = "A member was added to a security-enabled local group"+ Severity = "High"+ MITREAttack = @("T1098 - Account Manipulation")+ SecurityImplication = "Group membership change. Critical for admin groups."+ RecommendedAction = "Verify authorization, especially for Administrators group."+ }++ 4738 = @{+ Category = "Account Management"+ Description = "A user account was changed"+ Severity = "Warning"+ MITREAttack = @("T1098 - Account Manipulation")+ SecurityImplication = "Account properties modified. Check for suspicious changes."+ RecommendedAction = "Review what was changed and by whom."+ }++ 4740 = @{+ Category = "Account Management"+ Description = "A user account was locked out"+ Severity = "Warning"+ MITREAttack = @("T1110 - Brute Force")+ SecurityImplication = "Account lockout. May indicate brute force attack."+ RecommendedAction = "Investigate source of failed attempts."+ }++ 5140 = @{+ Category = "File Share"+ Description = "A network share object was accessed"+ Severity = "Informational"+ MITREAttack = @("T1021.002 - Remote Services: SMB/Windows Admin Shares")+ SecurityImplication = "Share access. Monitor for lateral movement."+ RecommendedAction = "Review accessed shares and source systems."+ }++ 5145 = @{+ Category = "File Share"+ Description = "A network share object was checked to see whether client can be granted desired access"+ Severity = "Informational"+ MITREAttack = @("T1021.002 - Remote Services: SMB/Windows Admin Shares")+ SecurityImplication = "Detailed share access logging."+ RecommendedAction = "Use for forensic analysis of file access."+ }++ 7045 = @{+ Category = "System"+ Description = "A service was installed in the system"+ Severity = "High"+ MITREAttack = @("T1543.003 - Create or Modify System Process: Windows Service")+ SecurityImplication = "Service installation. Common malware persistence."+ RecommendedAction = "Verify service binary, path, and digital signature."+ }++ 1102 = @{+ Category = "System"+ Description = "The audit log was cleared"+ Severity = "Critical"+ MITREAttack = @("T1070.001 - Indicator Removal: Clear Windows Event Logs")+ SecurityImplication = "Log clearing. Strong indicator of compromise."+ RecommendedAction = "Immediate investigation. Check who cleared logs and why."+ }+ }++ # Look up event+ if ($eventDatabase.ContainsKey($EventId)) {+ $eventInfo = $eventDatabase[$EventId]++ $result = [PSCustomObject]@{+ EventId = $EventId+ Source = $Source+ Category = $eventInfo.Category+ Description = $eventInfo.Description+ Severity = $eventInfo.Severity+ MITREAttack = $eventInfo.MITREAttack+ SecurityImplication = $eventInfo.SecurityImplication+ RecommendedAction = $eventInfo.RecommendedAction+ AdditionalInfo = $null+ }++ # Add additional info if available+ if ($eventInfo.ContainsKey('CommonLogonTypes')) {+ $result.AdditionalInfo = $eventInfo.CommonLogonTypes+ }+ elseif ($eventInfo.ContainsKey('CommonFailureReasons')) {+ $result.AdditionalInfo = $eventInfo.CommonFailureReasons+ }++ return $result+ }+ else {+ # Return generic info for unknown events+ return [PSCustomObject]@{+ EventId = $EventId+ Source = $Source+ Category = "Unknown"+ Description = "Event ID not in database"+ Severity = "Unknown"+ MITREAttack = @()+ SecurityImplication = "Unknown event - requires manual research"+ RecommendedAction = "Check Microsoft documentation for event details"+ AdditionalInfo = $null+ }+ }+}\ No newline at end of filediff --git a/Core/Get-SecurityBaseline.ps1 b/Core/Get-SecurityBaseline.ps1new file mode 100644index 0000000..c23bf87--- /dev/null+++ b/Core/Get-SecurityBaseline.ps1@@ -0,0 +1,203 @@+function Get-SecurityBaseline {+ <#+ .SYNOPSIS+ Gets the current security baseline status of the Windows system+ .DESCRIPTION+ Retrieves comprehensive security configuration including Windows Defender,+ Firewall, UAC, BitLocker, and Windows Update status+ .PARAMETER ComputerName+ Name of the computer to check (default: local computer)+ .PARAMETER ExportPath+ Path to export the results as JSON+ .EXAMPLE+ Get-SecurityBaseline+ Get-SecurityBaseline -ComputerName "SERVER01" -ExportPath "C:\Audits"+ .OUTPUTS+ PSCustomObject with security baseline information+ #>++ [CmdletBinding()]+ param(+ [Parameter(Position = 0)]+ [string]$ComputerName = $env:COMPUTERNAME,++ [Parameter(Position = 1)]+ [string]$ExportPath+ )++ begin {+ Write-Verbose "Starting security baseline check for $ComputerName"+ $results = [PSCustomObject]@{+ ComputerName = $ComputerName+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ WindowsDefender = $null+ Firewall = $null+ UAC = $null+ BitLocker = $null+ WindowsUpdate = $null+ SecurityScore = 0+ }+ }++ process {+ try {+ # Check Windows Defender Status+ Write-Verbose "Checking Windows Defender status..."+ try {+ $defenderStatus = Get-MpComputerStatus -ErrorAction Stop+ $results.WindowsDefender = [PSCustomObject]@{+ AntivirusEnabled = $defenderStatus.AntivirusEnabled+ RealTimeProtectionEnabled = $defenderStatus.RealTimeProtectionEnabled+ BehaviorMonitorEnabled = $defenderStatus.BehaviorMonitorEnabled+ IoavProtectionEnabled = $defenderStatus.IoavProtectionEnabled+ SignatureLastUpdated = $defenderStatus.AntivirusSignatureLastUpdated+ SignatureVersion = $defenderStatus.AntivirusSignatureVersion+ }+ if ($defenderStatus.RealTimeProtectionEnabled) { $results.SecurityScore += 20 }+ }+ catch {+ Write-Warning "Could not retrieve Windows Defender status: $_"+ $results.WindowsDefender = "Not available or not installed"+ }++ # Check Firewall Status+ Write-Verbose "Checking Windows Firewall status..."+ try {+ $firewallProfiles = Get-NetFirewallProfile -ErrorAction Stop+ $results.Firewall = @()+ foreach ($profile in $firewallProfiles) {+ $results.Firewall += [PSCustomObject]@{+ Profile = $profile.Name+ Enabled = $profile.Enabled+ DefaultInboundAction = $profile.DefaultInboundAction.ToString()+ DefaultOutboundAction = $profile.DefaultOutboundAction.ToString()+ }+ if ($profile.Enabled) { $results.SecurityScore += 10 }+ }+ }+ catch {+ Write-Warning "Could not retrieve Firewall status: $_"+ $results.Firewall = "Error retrieving firewall status"+ }++ # Check UAC Settings+ Write-Verbose "Checking UAC settings..."+ try {+ $uacKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"+ $uacSettings = Get-ItemProperty -Path $uacKey -ErrorAction Stop+ $results.UAC = [PSCustomObject]@{+ EnableLUA = $uacSettings.EnableLUA+ ConsentPromptBehaviorAdmin = $uacSettings.ConsentPromptBehaviorAdmin+ ConsentPromptBehaviorUser = $uacSettings.ConsentPromptBehaviorUser+ EnableSecureUIAPaths = $uacSettings.EnableSecureUIAPaths+ EnableVirtualization = $uacSettings.EnableVirtualization+ }+ if ($uacSettings.EnableLUA -eq 1) { $results.SecurityScore += 15 }+ }+ catch {+ Write-Warning "Could not retrieve UAC settings: $_"+ $results.UAC = "Error retrieving UAC settings"+ }++ # Check BitLocker Status+ Write-Verbose "Checking BitLocker status..."+ try {+ $bitlockerVolumes = Get-BitLockerVolume -ErrorAction Stop+ $results.BitLocker = @()+ foreach ($volume in $bitlockerVolumes) {+ $results.BitLocker += [PSCustomObject]@{+ MountPoint = $volume.MountPoint+ VolumeStatus = $volume.VolumeStatus.ToString()+ ProtectionStatus = $volume.ProtectionStatus.ToString()+ EncryptionPercentage = $volume.EncryptionPercentage+ EncryptionMethod = if ($volume.EncryptionMethod) { $volume.EncryptionMethod.ToString() } else { "None" }+ }+ if ($volume.ProtectionStatus -eq "On") { $results.SecurityScore += 10 }+ }+ }+ catch {+ Write-Warning "Could not retrieve BitLocker status: $_"+ $results.BitLocker = "BitLocker not available or access denied"+ }++ # Check Windows Update Status+ Write-Verbose "Checking Windows Update status..."+ try {+ # Try to get pending updates count+ $updateSession = New-Object -ComObject Microsoft.Update.Session+ $updateSearcher = $updateSession.CreateUpdateSearcher()+ $searchResult = $updateSearcher.Search("IsInstalled=0")+ $pendingCount = $searchResult.Updates.Count++ # Try to get last update check date+ $lastCheck = $null+ try {+ $auKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\Results\Detect"+ if (Test-Path $auKey) {+ $lastCheckProp = Get-ItemProperty -Path $auKey -Name "LastSuccessTime" -ErrorAction SilentlyContinue+ if ($lastCheckProp -and $lastCheckProp.LastSuccessTime) {+ $lastCheck = $lastCheckProp.LastSuccessTime+ }+ }+ }+ catch {+ Write-Verbose "Could not retrieve last update check time"+ }++ # Check if auto updates are enabled+ $autoUpdateEnabled = $true+ try {+ $wuKey = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU"+ if (Test-Path $wuKey) {+ $auSettings = Get-ItemProperty -Path $wuKey -ErrorAction SilentlyContinue+ if ($auSettings -and $auSettings.NoAutoUpdate -eq 1) {+ $autoUpdateEnabled = $false+ }+ }+ }+ catch {+ Write-Verbose "Could not determine auto update settings"+ }++ $results.WindowsUpdate = [PSCustomObject]@{+ PendingUpdates = $pendingCount+ LastUpdateCheck = $lastCheck+ AutoUpdateEnabled = $autoUpdateEnabled+ }++ if ($pendingCount -eq 0) { $results.SecurityScore += 15 }+ }+ catch {+ Write-Warning "Could not retrieve Windows Update status: $_"+ $results.WindowsUpdate = [PSCustomObject]@{+ PendingUpdates = "Unable to determine"+ LastUpdateCheck = "Unknown"+ AutoUpdateEnabled = "Unknown"+ }+ }++ # Calculate final security score+ $results.SecurityScore = [Math]::Min($results.SecurityScore, 100)++ }+ catch {+ Write-Error "Error during security baseline check: $_"+ throw+ }+ }++ end {+ # Export results if path specified+ if ($ExportPath) {+ if (-not (Test-Path $ExportPath)) {+ New-Item -Path $ExportPath -ItemType Directory -Force | Out-Null+ }+ $exportFile = Join-Path -Path $ExportPath -ChildPath "SecurityBaseline_$ComputerName_$(Get-Date -Format 'yyyyMMdd_HHmmss').json"+ $results | ConvertTo-Json -Depth 5 | Out-File -FilePath $exportFile -Encoding UTF8+ Write-Verbose "Results exported to: $exportFile"+ }++ # Return results+ return $results+ }+}\ No newline at end of filediff --git a/Core/Get-SystemInfo.ps1 b/Core/Get-SystemInfo.ps1new file mode 100644index 0000000..26306e1--- /dev/null+++ b/Core/Get-SystemInfo.ps1@@ -0,0 +1,166 @@+function Get-SystemInfo {+ <#+ .SYNOPSIS+ Retrieves comprehensive system information for security analysis+ .DESCRIPTION+ Collects detailed system information including hardware, OS, network configuration,+ installed software, and security-relevant settings+ .PARAMETER IncludeInstalledSoftware+ Include list of installed software+ .PARAMETER IncludeHotfixes+ Include list of installed Windows updates+ .EXAMPLE+ Get-SystemInfo+ Get-SystemInfo -IncludeInstalledSoftware -IncludeHotfixes+ .OUTPUTS+ PSCustomObject with system information+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$IncludeInstalledSoftware,++ [Parameter()]+ [switch]$IncludeHotfixes+ )++ begin {+ Write-Verbose "Gathering system information..."+ $info = [PSCustomObject]@{+ CollectionDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerSystem = $null+ OperatingSystem = $null+ Hardware = $null+ Network = $null+ Security = $null+ InstalledSoftware = $null+ Hotfixes = $null+ }+ }++ process {+ try {+ # Computer System Information+ $cs = Get-CimInstance -ClassName Win32_ComputerSystem+ $info.ComputerSystem = [PSCustomObject]@{+ Name = $cs.Name+ Domain = $cs.Domain+ Manufacturer = $cs.Manufacturer+ Model = $cs.Model+ SystemType = $cs.SystemType+ TotalPhysicalMemory = [math]::Round($cs.TotalPhysicalMemory / 1GB, 2)+ NumberOfProcessors = $cs.NumberOfProcessors+ NumberOfLogicalProcessors = $cs.NumberOfLogicalProcessors+ PrimaryOwnerName = $cs.PrimaryOwnerName+ BootupState = $cs.BootupState+ }++ # Operating System Information+ $os = Get-CimInstance -ClassName Win32_OperatingSystem+ $info.OperatingSystem = [PSCustomObject]@{+ Caption = $os.Caption+ Version = $os.Version+ BuildNumber = $os.BuildNumber+ Architecture = $os.OSArchitecture+ InstallDate = $os.InstallDate+ LastBootUpTime = $os.LastBootUpTime+ LocalDateTime = $os.LocalDateTime+ NumberOfUsers = $os.NumberOfUsers+ NumberOfProcesses = $os.NumberOfProcesses+ ServicePackMajorVersion = $os.ServicePackMajorVersion+ RegisteredUser = $os.RegisteredUser+ Organization = $os.Organization+ WindowsDirectory = $os.WindowsDirectory+ SystemDirectory = $os.SystemDirectory+ }++ # Hardware Information+ $cpu = Get-CimInstance -ClassName Win32_Processor+ $disk = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=3"++ $info.Hardware = [PSCustomObject]@{+ CPU = $cpu | Select-Object Name, MaxClockSpeed, NumberOfCores, NumberOfLogicalProcessors+ Disks = $disk | ForEach-Object {+ [PSCustomObject]@{+ DeviceID = $_.DeviceID+ VolumeName = $_.VolumeName+ FileSystem = $_.FileSystem+ Size = [math]::Round($_.Size / 1GB, 2)+ FreeSpace = [math]::Round($_.FreeSpace / 1GB, 2)+ PercentFree = [math]::Round(($_.FreeSpace / $_.Size) * 100, 2)+ }+ }+ }++ # Network Configuration+ $netAdapters = Get-NetAdapter | Where-Object { $_.Status -eq 'Up' }+ $netIP = Get-NetIPAddress | Where-Object { $_.AddressFamily -eq 'IPv4' -and $_.PrefixOrigin -ne 'WellKnown' }++ $info.Network = [PSCustomObject]@{+ Adapters = $netAdapters | Select-Object Name, InterfaceDescription, MacAddress, LinkSpeed, Status+ IPAddresses = $netIP | Select-Object InterfaceAlias, IPAddress, PrefixLength+ DNSServers = Get-DnsClientServerAddress | Where-Object { $_.AddressFamily -eq 2 } |+ Select-Object InterfaceAlias, ServerAddresses+ DefaultGateway = (Get-NetRoute -DestinationPrefix "0.0.0.0/0" -ErrorAction SilentlyContinue).NextHop+ }++ # Security Settings+# Security Settings+$info.Security = [PSCustomObject]@{+ LocalUsers = (Get-LocalUser).Count+ LocalAdministrators = (Get-LocalGroupMember -Group "Administrators" -ErrorAction SilentlyContinue).Count+ PasswordPolicy = Get-LocalUser | Where-Object { $_.PasswordRequired -eq $false } |+ Select-Object Name, Enabled+ FirewallProfiles = Get-NetFirewallProfile | Select-Object Name, Enabled+ AntivirusProduct = "Not detected"+}++# Try to get AV separately to avoid property errors+try {+ $avQuery = Get-CimInstance -Namespace "root\SecurityCenter2" -ClassName AntiVirusProduct -ErrorAction Stop+ if ($avQuery) {+ $info.Security.AntivirusProduct = ($avQuery | Select-Object -First 1).displayName+ }+} catch {+ # AV info not available+}++ # Installed Software+ # Installed Software+if ($IncludeInstalledSoftware) {+ Write-Verbose "Gathering installed software list..."+ try {+ $software = @(Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* -ErrorAction SilentlyContinue |+ Where-Object { $_.DisplayName } |+ Select-Object @{N='DisplayName';E={$_.DisplayName}},+ @{N='Publisher';E={$_.Publisher}},+ @{N='InstallDate';E={$_.InstallDate}},+ @{N='DisplayVersion';E={$_.DisplayVersion}} |+ Sort-Object DisplayName)++ $info.InstalledSoftware = $software+ } catch {+ Write-Verbose "Could not retrieve installed software: $_"+ $info.InstalledSoftware = @()+ }+}++ # Installed Hotfixes+ if ($IncludeHotfixes) {+ Write-Verbose "Gathering installed hotfixes..."+ $info.Hotfixes = Get-HotFix | Select-Object HotFixID, Description, InstalledOn, InstalledBy |+ Sort-Object InstalledOn -Descending+ }++ }+ catch {+ Write-Error "Error gathering system information: $_"+ throw+ }+ }++ end {+ return $info+ }+}\ No newline at end of filediff --git a/Core/Test-SystemIntegrity.ps1 b/Core/Test-SystemIntegrity.ps1new file mode 100644index 0000000..f6f4db4--- /dev/null+++ b/Core/Test-SystemIntegrity.ps1@@ -0,0 +1,143 @@+function Test-SystemIntegrity {+ <#+ .SYNOPSIS+ Tests Windows system file integrity+ .DESCRIPTION+ Runs SFC and DISM commands to check and verify system file integrity+ .PARAMETER RepairFiles+ Attempt to repair corrupted files if found+ .PARAMETER DetailedScan+ Perform a more thorough system scan+ .EXAMPLE+ Test-SystemIntegrity+ Test-SystemIntegrity -RepairFiles -DetailedScan+ .OUTPUTS+ PSCustomObject with integrity check results+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$RepairFiles,++ [Parameter()]+ [switch]$DetailedScan+ )++ begin {+ # Check for admin privileges+ $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ if (-not $isAdmin) {+ throw "This function requires Administrator privileges. Please run PowerShell as Administrator."+ }++ Write-Host "Starting System Integrity Check..." -ForegroundColor Cyan+ $results = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ SFCResult = $null+ DISMResult = $null+ CorruptedFiles = @()+ RepairAttempted = $false+ RepairSuccessful = $false+ WindowsUpdateServices = @() # Added this property+ }+ }++ process {+ try {+ # Run SFC scan+ Write-Host "Running System File Checker (SFC)..." -ForegroundColor Yellow+ $sfcOutput = & sfc /scannow 2>&1 | Out-String++ # Parse SFC results+ if ($sfcOutput -match "Windows Resource Protection found corrupt files") {+ $results.SFCResult = "Corrupt files found"++ # Get CBS log details (with error handling)+ $cbsLogPath = "$env:windir\Logs\CBS\CBS.log"+ if (Test-Path $cbsLogPath) {+ $cbsLog = Get-Content $cbsLogPath -Tail 100 -ErrorAction SilentlyContinue |+ Where-Object { $_ -match "corrupt" -or $_ -match "repaired" }+ if ($cbsLog) {+ $results.CorruptedFiles = $cbsLog+ }+ }++ if ($RepairFiles) {+ Write-Host "Attempting to repair corrupt files..." -ForegroundColor Yellow+ $results.RepairAttempted = $true+ }+ }+ elseif ($sfcOutput -match "Windows Resource Protection did not find any integrity violations") {+ $results.SFCResult = "No integrity violations found"+ Write-Host "SFC: No integrity violations found" -ForegroundColor Green+ }+ elseif ($sfcOutput -match "Windows Resource Protection could not perform") {+ $results.SFCResult = "SFC could not complete scan - may need to run in Safe Mode"+ Write-Warning "SFC could not complete the scan"+ }+ else {+ $results.SFCResult = "Scan completed - check CBS.log for details"+ }++ # Run DISM if detailed scan requested+ if ($DetailedScan) {+ Write-Host "Running DISM health check..." -ForegroundColor Yellow++ # Check image health+ $dismCheck = & dism /Online /Cleanup-Image /CheckHealth 2>&1 | Out-String++ if ($dismCheck -match "No component store corruption detected") {+ $results.DISMResult = "Healthy"+ Write-Host "DISM: System image is healthy" -ForegroundColor Green+ }+ elseif ($dismCheck -match "The component store is repairable") {+ $results.DISMResult = "Repairable corruption detected"++ if ($RepairFiles) {+ Write-Host "Attempting DISM repair..." -ForegroundColor Yellow+ $dismRepair = & dism /Online /Cleanup-Image /RestoreHealth 2>&1 | Out-String++ if ($dismRepair -match "The restore operation completed successfully") {+ $results.RepairSuccessful = $true+ $results.DISMResult = "Repaired successfully"+ Write-Host "DISM repair completed successfully" -ForegroundColor Green+ }+ }+ }+ else {+ $results.DISMResult = "Check completed"+ }+ }++ # Check Windows Update components+ Write-Host "Checking Windows Update components..." -ForegroundColor Yellow+ $serviceNames = @('wuauserv', 'cryptSvc', 'bits', 'msiserver')+ $services = @()++ foreach ($serviceName in $serviceNames) {+ $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue+ if ($service) {+ $services += [PSCustomObject]@{+ Name = $service.Name+ DisplayName = $service.DisplayName+ Status = $service.Status+ StartType = $service.StartType+ }+ }+ }++ $results.WindowsUpdateServices = $services++ }+ catch {+ Write-Error "Error during system integrity check: $_"+ throw+ }+ }++ end {+ return $results+ }+}\ No newline at end of filediff --git a/CreateProjectFolderStructure.ps1 b/CreateProjectFolderStructure.ps1new file mode 100644index 0000000..d251300--- /dev/null+++ b/CreateProjectFolderStructure.ps1@@ -0,0 +1,26 @@+# Create main project folder+New-Item -Path "C:\WindowsSecurityAudit" -ItemType Directory -Force++# Create subfolders+$folders = @(+ "C:\WindowsSecurityAudit\Core",+ "C:\WindowsSecurityAudit\Detection",+ "C:\WindowsSecurityAudit\Analysis",+ "C:\WindowsSecurityAudit\Response",+ "C:\WindowsSecurityAudit\Enterprise",+ "C:\WindowsSecurityAudit\Hardening",+ "C:\WindowsSecurityAudit\WindowsDefender",+ "C:\WindowsSecurityAudit\Private",+ "C:\WindowsSecurityAudit\Tests",+ "C:\WindowsSecurityAudit\Reporting",+ "C:\WindowsSecurityAudit\CloudSecurity",+ "C:\WindowsSecurityAudit\Forensics",+ "C:\WindowsSecurityAudit\Vulnerability",+ "C:\WindowsSecurityAudit\Compliance",+ "C:\WindowsSecurityAudit\ThreatHunting",+ "C:\WindowsSecurityAudit\ActiveDirectory"+)++foreach ($folder in $folders) {+ New-Item -Path $folder -ItemType Directory -Force+}\ No newline at end of filediff --git a/Detection/Find-NetworkAnomalies.ps1 b/Detection/Find-NetworkAnomalies.ps1new file mode 100644index 0000000..03dae01--- /dev/null+++ b/Detection/Find-NetworkAnomalies.ps1@@ -0,0 +1,243 @@+function Find-NetworkAnomalies {+ <#+ .SYNOPSIS+ Detects suspicious network connections and activities+ .DESCRIPTION+ Identifies unusual network connections, listening ports, and network-based+ indicators of compromise+ .PARAMETER IncludeEstablished+ Include established connections in analysis+ .PARAMETER CheckDNS+ Perform DNS-based anomaly detection+ .EXAMPLE+ Find-NetworkAnomalies+ Find-NetworkAnomalies -IncludeEstablished -CheckDNS+ .OUTPUTS+ PSCustomObject with network anomaly findings+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$IncludeEstablished,++ [Parameter()]+ [switch]$CheckDNS+ )++ begin {+ Write-Host "Scanning for network anomalies..." -ForegroundColor Cyan++ $results = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ SuspiciousListeners = @()+ SuspiciousConnections = @()+ UnusualPorts = @()+ DNSAnomalies = @()+ TotalAnomalies = 0+ }++ # Known malicious ports+ $maliciousPorts = @(+ 4444, # Metasploit+ 5555, # Android Debug Bridge / Backdoors+ 6666, # IRC/Backdoors+ 6667, # IRC+ 31337, # Back Orifice+ 12345, # NetBus+ 1337, # Common backdoor+ 8888, # Common C2+ 9999 # Common backdoor+ )++ # Legitimate common ports+ $legitimatePorts = @(80, 443, 53, 22, 21, 25, 110, 143, 993, 995, 3389, 445, 139, 135)+ }++ process {+ try {+ # Check listening ports+ Write-Verbose "Checking listening ports..."+ $listeners = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue++ foreach ($listener in $listeners) {+ $suspicious = $false+ $reasons = @()++ # Check if port is known malicious+ if ($maliciousPorts -contains $listener.LocalPort) {+ $suspicious = $true+ $reasons += "Known malicious port: $($listener.LocalPort)"+ }++ # Check for unusual high ports+ if ($listener.LocalPort -gt 49152 -and $listener.LocalAddress -eq '0.0.0.0') {+ $suspicious = $true+ $reasons += "High port number listening on all interfaces"+ }++ # Get process info+ $process = Get-Process -Id $listener.OwningProcess -ErrorAction SilentlyContinue++ # Check for suspicious process listening+ if ($process) {+ $processPath = $process.Path+ if ($processPath -match '(Temp|AppData|Users\\Public)' -and $listener.LocalAddress -eq '0.0.0.0') {+ $suspicious = $true+ $reasons += "Suspicious process location listening on all interfaces"+ }+ }++ if ($suspicious) {+ $results.SuspiciousListeners += [PSCustomObject]@{+ LocalAddress = $listener.LocalAddress+ LocalPort = $listener.LocalPort+ ProcessName = if ($process) { $process.ProcessName } else { 'Unknown' }+ ProcessId = $listener.OwningProcess+ ProcessPath = if ($process) { $process.Path } else { 'Unknown' }+ Reasons = ($reasons -join '; ')+ }+ }+ }++ # Check established connections (if requested)+ if ($IncludeEstablished) {+ Write-Verbose "Checking established connections..."+ $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue++ foreach ($conn in $connections) {+ $suspicious = $false+ $reasons = @()++ # Check for connections to malicious ports+ if ($maliciousPorts -contains $conn.RemotePort) {+ $suspicious = $true+ $reasons += "Connection to known malicious port: $($conn.RemotePort)"+ }++ # Check for unusual remote ports+ if ($conn.RemotePort -notin $legitimatePorts -and $conn.RemotePort -lt 1024) {+ $suspicious = $true+ $reasons += "Connection to unusual low port: $($conn.RemotePort)"+ }++ # Get process info+ $process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue++ if ($process) {+ # Check for suspicious processes with network connections+ if ($process.ProcessName -match '(cmd|powershell|wscript|cscript)') {+ $suspicious = $true+ $reasons += "Scripting engine with network connection"+ }++ # Check process path+ if ($process.Path -match '(Temp|AppData\\Local\\Temp|Users\\Public)') {+ $suspicious = $true+ $reasons += "Process from suspicious location with network connection"+ }+ }++ if ($suspicious) {+ $results.SuspiciousConnections += [PSCustomObject]@{+ LocalAddress = $conn.LocalAddress+ LocalPort = $conn.LocalPort+ RemoteAddress = $conn.RemoteAddress+ RemotePort = $conn.RemotePort+ State = $conn.State+ ProcessName = if ($process) { $process.ProcessName } else { 'Unknown' }+ ProcessId = $conn.OwningProcess+ ProcessPath = if ($process) { $process.Path } else { 'Unknown' }+ Reasons = ($reasons -join '; ')+ }+ }+ }+ }++ # Check for unusual ports in use+ Write-Verbose "Analyzing port usage patterns..."+ $allConnections = Get-NetTCPConnection -ErrorAction SilentlyContinue+ $portGroups = $allConnections | Group-Object -Property LocalPort |+ Where-Object { $_.Count -gt 10 -and $_.Name -notin $legitimatePorts }++ foreach ($group in $portGroups) {+ $results.UnusualPorts += [PSCustomObject]@{+ Port = $group.Name+ ConnectionCount = $group.Count+ Reason = "Unusually high number of connections on non-standard port"+ }+ }++ # DNS anomaly detection (if requested)+ if ($CheckDNS) {+ Write-Verbose "Checking DNS cache for anomalies..."+ try {+ $dnsCache = Get-DnsClientCache -ErrorAction SilentlyContinue++ foreach ($entry in $dnsCache) {+ $suspicious = $false+ $reasons = @()++ # Check for unusual TLDs+ if ($entry.Name -match '\.(tk|ml|ga|cf|gq|xyz|top|work)$') {+ $suspicious = $true+ $reasons += "Suspicious TLD commonly used by malware"+ }++ # Check for very long domain names (possible DGA)+ if ($entry.Name.Length -gt 50) {+ $suspicious = $true+ $reasons += "Unusually long domain name (possible DGA)"+ }++ # Check for high entropy in subdomain (possible DGA)+ $subdomain = ($entry.Name -split '\.')[0]+ if ($subdomain.Length -gt 15 -and $subdomain -match '[a-z]{10,}') {+ # Simple entropy check+ $uniqueChars = ($subdomain.ToCharArray() | Select-Object -Unique).Count+ if ($uniqueChars -gt 10) {+ $suspicious = $true+ $reasons += "High entropy subdomain (possible DGA)"+ }+ }++ if ($suspicious) {+ $results.DNSAnomalies += [PSCustomObject]@{+ Name = $entry.Name+ Type = $entry.Type+ Data = $entry.Data+ TTL = $entry.TimeToLive+ Reasons = ($reasons -join '; ')+ }+ }+ }+ }+ catch {+ Write-Warning "Could not check DNS cache: $_"+ }+ }++ # Calculate total anomalies+ $results.TotalAnomalies = ($results.SuspiciousListeners.Count ++ $results.SuspiciousConnections.Count ++ $results.UnusualPorts.Count ++ $results.DNSAnomalies.Count)++ }+ catch {+ Write-Error "Error during network scan: $_"+ throw+ }+ }++ end {+ Write-Host "`nNetwork scan complete!" -ForegroundColor Green+ Write-Host "Total anomalies found: $($results.TotalAnomalies)" -ForegroundColor $(if ($results.TotalAnomalies -gt 0) { 'Yellow' } else { 'Green' })+ Write-Host " Suspicious listeners: $($results.SuspiciousListeners.Count)" -ForegroundColor Cyan+ Write-Host " Suspicious connections: $($results.SuspiciousConnections.Count)" -ForegroundColor Cyan+ Write-Host " Unusual ports: $($results.UnusualPorts.Count)" -ForegroundColor Cyan+ Write-Host " DNS anomalies: $($results.DNSAnomalies.Count)" -ForegroundColor Cyan++ return $results+ }+}\ No newline at end of filediff --git a/Detection/Find-PersistenceMechanisms.ps1 b/Detection/Find-PersistenceMechanisms.ps1new file mode 100644index 0000000..0c754c4--- /dev/null+++ b/Detection/Find-PersistenceMechanisms.ps1@@ -0,0 +1,320 @@+function Find-PersistenceMechanisms {+ <#+ .SYNOPSIS+ Detects common Windows persistence mechanisms used by malware+ .DESCRIPTION+ Scans for suspicious persistence mechanisms including Registry Run keys,+ Startup folder items, Scheduled Tasks, Services, WMI subscriptions, and more+ .PARAMETER IncludeKnownGood+ Include known legitimate persistence mechanisms in results+ .PARAMETER ExportPath+ Path to export detailed results+ .EXAMPLE+ Find-PersistenceMechanisms+ Find-PersistenceMechanisms -IncludeKnownGood -ExportPath "C:\Audits"+ .OUTPUTS+ PSCustomObject with detected persistence mechanisms+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$IncludeKnownGood,++ [Parameter()]+ [string]$ExportPath+ )++ begin {+ Write-Host "Scanning for persistence mechanisms..." -ForegroundColor Cyan++ $results = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ RegistryRunKeys = @()+ StartupFolder = @()+ ScheduledTasks = @()+ Services = @()+ WMISubscriptions = @()+ AppInitDLLs = @()+ LSAProviders = @()+ PrintMonitors = @()+ TotalFindings = 0+ SuspiciousCount = 0+ }++ # Known good paths/patterns to filter (if not including known good)+ $knownGoodPatterns = @(+ "Microsoft",+ "Windows Defender",+ "OneDrive",+ "Adobe",+ "Google\\Update",+ "Intel",+ "NVIDIA"+ )+ }++ process {+ try {+ # 1. Registry Run Keys+ Write-Verbose "Checking Registry Run keys..."+ $runKeyPaths = @(+ "HKLM:\Software\Microsoft\Windows\CurrentVersion\Run",+ "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce",+ "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run",+ "HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce",+ "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunServices",+ "HKLM:\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce",+ "HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Run",+ "HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\RunOnce"+ )++ foreach ($keyPath in $runKeyPaths) {+ if (Test-Path $keyPath) {+ $items = Get-ItemProperty -Path $keyPath -ErrorAction SilentlyContinue+ if ($items) {+ $items.PSObject.Properties | Where-Object { $_.Name -notmatch '^PS' } | ForEach-Object {+ $isSuspicious = $true+ if (-not $IncludeKnownGood) {+ foreach ($pattern in $knownGoodPatterns) {+ if ($_.Value -match $pattern) {+ $isSuspicious = $false+ break+ }+ }+ }++ if ($isSuspicious -or $IncludeKnownGood) {+ $results.RegistryRunKeys += [PSCustomObject]@{+ Location = $keyPath+ Name = $_.Name+ Value = $_.Value+ Suspicious = $isSuspicious+ }+ if ($isSuspicious) { $results.SuspiciousCount++ }+ }+ }+ }+ }+ }++ # 2. Startup Folders+ Write-Verbose "Checking Startup folders..."+ $startupPaths = @(+ "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\Startup",+ "$env:ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"+ )++ foreach ($path in $startupPaths) {+ if (Test-Path $path) {+ $items = Get-ChildItem -Path $path -File -ErrorAction SilentlyContinue+ foreach ($item in $items) {+ $isSuspicious = -not ($item.Name -match ($knownGoodPatterns -join '|'))++ if ($isSuspicious -or $IncludeKnownGood) {+ $results.StartupFolder += [PSCustomObject]@{+ Location = $path+ Name = $item.Name+ FullPath = $item.FullName+ Target = if ($item.LinkType -eq 'SymbolicLink') { $item.Target } else { 'N/A' }+ CreationTime = $item.CreationTime+ Suspicious = $isSuspicious+ }+ if ($isSuspicious) { $results.SuspiciousCount++ }+ }+ }+ }+ }++ # 3. Scheduled Tasks+ Write-Verbose "Checking Scheduled Tasks..."+ $tasks = Get-ScheduledTask | Where-Object { $_.State -ne 'Disabled' }++ foreach ($task in $tasks) {+ try {+ $taskInfo = Get-ScheduledTaskInfo -TaskName $task.TaskName -ErrorAction SilentlyContinue+ $actions = $task.Actions | ForEach-Object {+ if ($_.Execute) { $_.Execute }+ }++ $isSuspicious = $false+ # Check for suspicious indicators+ if ($task.Principal.UserId -eq 'SYSTEM' -and $task.TaskPath -notmatch '\\Microsoft\\') {+ $isSuspicious = $true+ }+ if ($actions -match '(powershell|cmd|wscript|cscript|mshta)' -and $task.TaskPath -notmatch '\\Microsoft\\') {+ $isSuspicious = $true+ }++ if ($isSuspicious -or $IncludeKnownGood) {+ $results.ScheduledTasks += [PSCustomObject]@{+ Name = $task.TaskName+ Path = $task.TaskPath+ State = $task.State+ Actions = if ($actions) { ($actions -join '; ') } else { 'N/A' }+ RunAsUser = $task.Principal.UserId+ LastRunTime = if ($taskInfo -and $taskInfo.LastRunTime) { $taskInfo.LastRunTime } else { 'Never' }+ NextRunTime = if ($taskInfo -and $taskInfo.NextRunTime) { $taskInfo.NextRunTime } else { 'Not scheduled' }+ Suspicious = $isSuspicious+ }+ if ($isSuspicious) { $results.SuspiciousCount++ }+ }+ }+ catch {+ Write-Verbose "Could not process task: $($task.TaskName)"+ }+ }++ # 4. Services+ Write-Verbose "Checking Services..."+ $services = Get-CimInstance -ClassName Win32_Service++ foreach ($service in $services) {+ $isSuspicious = $false++ # Check for suspicious indicators+ if ($service.PathName -match '(temp|appdata|programdata.*\\.\\)' -and $service.PathName -notmatch 'Microsoft') {+ $isSuspicious = $true+ }+ if ($service.StartMode -eq 'Auto' -and $service.PathName -notmatch '(System32|Program Files)') {+ $isSuspicious = $true+ }++ if ($isSuspicious -or $IncludeKnownGood) {+ $results.Services += [PSCustomObject]@{+ Name = $service.Name+ DisplayName = $service.DisplayName+ PathName = $service.PathName+ StartMode = $service.StartMode+ State = $service.State+ StartName = $service.StartName+ Suspicious = $isSuspicious+ }+ if ($isSuspicious) { $results.SuspiciousCount++ }+ }+ }++ # 5. WMI Event Subscriptions+ Write-Verbose "Checking WMI Event Subscriptions..."+ try {+ $wmiFilters = Get-CimInstance -Namespace root\subscription -ClassName __EventFilter -ErrorAction SilentlyContinue+ $wmiConsumers = Get-CimInstance -Namespace root\subscription -ClassName __EventConsumer -ErrorAction SilentlyContinue+ $wmiBindings = Get-CimInstance -Namespace root\subscription -ClassName __FilterToConsumerBinding -ErrorAction SilentlyContinue++ foreach ($binding in $wmiBindings) {+ $results.WMISubscriptions += [PSCustomObject]@{+ Filter = $binding.Filter+ Consumer = $binding.Consumer+ Suspicious = $true # All non-Microsoft WMI subscriptions are suspicious+ }+ $results.SuspiciousCount+++ }+ }+ catch {+ Write-Warning "Could not check WMI subscriptions: $_"+ }++ # 6. AppInit DLLs+ Write-Verbose "Checking AppInit DLLs..."+ $appInitPath = "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows"+ if (Test-Path $appInitPath) {+ $appInit = Get-ItemProperty -Path $appInitPath -ErrorAction SilentlyContinue+ if ($appInit.AppInit_DLLs) {+ $results.AppInitDLLs += [PSCustomObject]@{+ Value = $appInit.AppInit_DLLs+ LoadAppInit = $appInit.LoadAppInit_DLLs+ Suspicious = $true+ }+ $results.SuspiciousCount+++ }+ }++ # 7. LSA Authentication Packages+ Write-Verbose "Checking LSA providers..."+ $lsaPath = "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa"+ if (Test-Path $lsaPath) {+ $lsa = Get-ItemProperty -Path $lsaPath -ErrorAction SilentlyContinue++ # Check Authentication Packages+ if ($lsa.'Authentication Packages') {+ foreach ($pkg in $lsa.'Authentication Packages') {+ if ($pkg -notmatch '^msv1_0$') {+ $results.LSAProviders += [PSCustomObject]@{+ Type = "Authentication Package"+ Value = $pkg+ Suspicious = $true+ }+ $results.SuspiciousCount+++ }+ }+ }++ # Check Notification Packages+ if ($lsa.'Notification Packages') {+ foreach ($pkg in $lsa.'Notification Packages') {+ if ($pkg -notmatch '^(scecli|rassfm)$') {+ $results.LSAProviders += [PSCustomObject]@{+ Type = "Notification Package"+ Value = $pkg+ Suspicious = $true+ }+ $results.SuspiciousCount+++ }+ }+ }+ }++ # 8. Print Monitors+ Write-Verbose "Checking Print Monitors..."+ $monitorPath = "HKLM:\SYSTEM\CurrentControlSet\Control\Print\Monitors"+ if (Test-Path $monitorPath) {+ $monitors = Get-ChildItem -Path $monitorPath -ErrorAction SilentlyContinue+ foreach ($monitor in $monitors) {+ $driverValue = (Get-ItemProperty -Path $monitor.PSPath -ErrorAction SilentlyContinue).Driver+ if ($driverValue -and $driverValue -notmatch '(Microsoft|Windows)') {+ $results.PrintMonitors += [PSCustomObject]@{+ Name = $monitor.PSChildName+ Driver = $driverValue+ Suspicious = $true+ }+ $results.SuspiciousCount+++ }+ }+ }++ # Calculate total findings+ $results.TotalFindings = ($results.RegistryRunKeys.Count ++ $results.StartupFolder.Count ++ $results.ScheduledTasks.Count ++ $results.Services.Count ++ $results.WMISubscriptions.Count ++ $results.AppInitDLLs.Count ++ $results.LSAProviders.Count ++ $results.PrintMonitors.Count)++ }+ catch {+ Write-Error "Error during persistence scan: $_"+ throw+ }+ }++ end {+ Write-Host "`nScan complete!" -ForegroundColor Green+ Write-Host "Total findings: $($results.TotalFindings)" -ForegroundColor Yellow+ Write-Host "Suspicious items: $($results.SuspiciousCount)" -ForegroundColor $(if ($results.SuspiciousCount -gt 0) { 'Red' } else { 'Green' })++ # Export if requested+ if ($ExportPath) {+ if (-not (Test-Path $ExportPath)) {+ New-Item -Path $ExportPath -ItemType Directory -Force | Out-Null+ }+ $exportFile = Join-Path -Path $ExportPath -ChildPath "PersistenceScan_$($env:COMPUTERNAME)_$(Get-Date -Format 'yyyyMMdd_HHmmss').json"+ $results | ConvertTo-Json -Depth 5 | Out-File -FilePath $exportFile -Encoding UTF8+ Write-Host "Results exported to: $exportFile" -ForegroundColor Cyan+ }++ return $results+ }+}\ No newline at end of filediff --git a/Detection/Find-SuspiciousAuthentication.ps1 b/Detection/Find-SuspiciousAuthentication.ps1new file mode 100644index 0000000..28b6019--- /dev/null+++ b/Detection/Find-SuspiciousAuthentication.ps1@@ -0,0 +1,320 @@+function Find-SuspiciousAuthentication {+ <#+ .SYNOPSIS+ 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+ .PARAMETER Hours+ Number of hours to look back in event logs (default: 24)+ .PARAMETER IncludeSuccessful+ Include successful authentications in analysis+ .PARAMETER ExportPath+ Path to export detailed results+ .EXAMPLE+ Find-SuspiciousAuthentication+ Find-SuspiciousAuthentication -Hours 48 -IncludeSuccessful -ExportPath "C:\Audits"+ .OUTPUTS+ PSCustomObject with authentication analysis results+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [int]$Hours = 24,++ [Parameter()]+ [switch]$IncludeSuccessful,++ [Parameter()]+ [string]$ExportPath+ )++ begin {+ Write-Host "Analyzing authentication events (last $Hours hours)..." -ForegroundColor Cyan++ $results = [PSCustomObject]@{+ AnalysisDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ TimeRange = "$Hours hours"+ FailedLogons = @()+ AccountLockouts = @()+ PrivilegeEscalations = @()+ UnusualLogons = @()+ ExplicitCredentials = @()+ BruteForceIndicators = @()+ Statistics = @{+ TotalFailedLogons = 0+ TotalLockouts = 0+ TotalPrivilegeUse = 0+ TotalExplicitCreds = 0+ UniqueFailedAccounts = 0+ UniqueSourceIPs = 0+ }+ }++ $startTime = (Get-Date).AddHours(-$Hours)+ }++ process {+ try {+ # Event IDs to analyze+ # 4625 - Failed logon+ # 4740 - Account lockout+ # 4672 - Special privileges assigned+ # 4648 - Logon with explicit credentials+ # 4624 - Successful logon+ # 4634 - Logoff++ # 1. Analyze Failed Logons (Event ID 4625)+ Write-Verbose "Analyzing failed logon attempts..."+ $failedLogons = Get-WinEvent -FilterHashtable @{+ LogName = 'Security'+ ID = 4625+ StartTime = $startTime+ } -ErrorAction SilentlyContinue++ if ($failedLogons) {+ $results.Statistics.TotalFailedLogons = $failedLogons.Count++ foreach ($event in $failedLogons) {+ $xml = [xml]$event.ToXml()+ $eventData = $xml.Event.EventData.Data++ $targetAccount = ($eventData | Where-Object { $_.Name -eq 'TargetUserName' }).'#text'+ $targetDomain = ($eventData | Where-Object { $_.Name -eq 'TargetDomainName' }).'#text'+ $workstation = ($eventData | Where-Object { $_.Name -eq 'WorkstationName' }).'#text'+ $sourceIP = ($eventData | Where-Object { $_.Name -eq 'IpAddress' }).'#text'+ $logonType = ($eventData | Where-Object { $_.Name -eq 'LogonType' }).'#text'+ $status = ($eventData | Where-Object { $_.Name -eq 'Status' }).'#text'+ $subStatus = ($eventData | Where-Object { $_.Name -eq 'SubStatus' }).'#text'++ $results.FailedLogons += [PSCustomObject]@{+ TimeCreated = $event.TimeCreated+ Account = "$targetDomain\$targetAccount"+ Workstation = $workstation+ SourceIP = $sourceIP+ LogonType = $logonType+ FailureReason = switch ($subStatus) {+ '0xC0000064' { 'User name does not exist' }+ '0xC000006A' { 'Correct user name but wrong password' }+ '0xC000006D' { 'Bad user name or password' }+ '0xC000006E' { 'Account restriction' }+ '0xC000006F' { 'Logon outside allowed time' }+ '0xC0000070' { 'Workstation restriction' }+ '0xC0000071' { 'Password expired' }+ '0xC0000072' { 'Account disabled' }+ '0xC0000193' { 'Account expiration' }+ '0xC0000224' { 'Password must change' }+ '0xC0000234' { 'Account locked out' }+ default { "Unknown ($subStatus)" }+ }+ }+ }++ # Detect brute force patterns+ $failuresByAccount = $results.FailedLogons | Group-Object -Property Account+ foreach ($group in $failuresByAccount) {+ if ($group.Count -ge 5) {+ $timeSpan = ($group.Group | Measure-Object -Property TimeCreated -Maximum -Minimum)+ $duration = ($timeSpan.Maximum - $timeSpan.Minimum).TotalMinutes++ $results.BruteForceIndicators += [PSCustomObject]@{+ Account = $group.Name+ FailureCount = $group.Count+ TimeSpan = [math]::Round($duration, 2)+ SourceIPs = ($group.Group.SourceIP | Select-Object -Unique) -join ', '+ Severity = if ($group.Count -ge 10) { 'High' } elseif ($group.Count -ge 5) { 'Medium' } else { 'Low' }+ }+ }+ }++ # Calculate statistics safely+ # ESKI SATIRLARI SİLİN, BUNLARI KOYUN:+try {+ $failedArray = @($results.FailedLogons)+ if ($failedArray.Count -gt 0) {+ $results.Statistics.UniqueFailedAccounts = (@($failedArray.Account | Select-Object -Unique)).Count+ $results.Statistics.UniqueSourceIPs = (@($failedArray | Where-Object { $_.SourceIP -ne '-' } | Select-Object -ExpandProperty SourceIP -Unique)).Count+ }+} catch {+ Write-Verbose "Could not calculate unique statistics"+}+ }++ # 2. Account Lockouts (Event ID 4740)+ Write-Verbose "Checking account lockouts..."+ $lockouts = Get-WinEvent -FilterHashtable @{+ LogName = 'Security'+ ID = 4740+ StartTime = $startTime+ } -ErrorAction SilentlyContinue++ if ($lockouts) {+ $results.Statistics.TotalLockouts = $lockouts.Count++ foreach ($event in $lockouts) {+ $xml = [xml]$event.ToXml()+ $eventData = $xml.Event.EventData.Data++ $targetAccount = ($eventData | Where-Object { $_.Name -eq 'TargetUserName' }).'#text'+ $callerComputer = ($eventData | Where-Object { $_.Name -eq 'TargetDomainName' }).'#text'++ $results.AccountLockouts += [PSCustomObject]@{+ TimeCreated = $event.TimeCreated+ Account = $targetAccount+ CallerComputer = $callerComputer+ }+ }+ }++ # 3. Special Privileges Assigned (Event ID 4672)+ Write-Verbose "Analyzing privilege escalations..."+ $privEvents = Get-WinEvent -FilterHashtable @{+ LogName = 'Security'+ ID = 4672+ StartTime = $startTime+ } -ErrorAction SilentlyContinue++ if ($privEvents) {+ $results.Statistics.TotalPrivilegeUse = $privEvents.Count++ # Look for unusual privilege assignments+ foreach ($event in $privEvents) {+ $xml = [xml]$event.ToXml()+ $eventData = $xml.Event.EventData.Data++ $subjectAccount = ($eventData | Where-Object { $_.Name -eq 'SubjectUserName' }).'#text'+ $subjectDomain = ($eventData | Where-Object { $_.Name -eq 'SubjectDomainName' }).'#text'+ $privileges = ($eventData | Where-Object { $_.Name -eq 'PrivilegeList' }).'#text'++ # Flag if not a well-known admin account+ if ($subjectAccount -notmatch '(SYSTEM|LOCAL SERVICE|NETWORK SERVICE|Administrator|DWM-\d+|UMFD-\d+)') {+ $results.PrivilegeEscalations += [PSCustomObject]@{+ TimeCreated = $event.TimeCreated+ Account = "$subjectDomain\$subjectAccount"+ Privileges = $privileges+ }+ }+ }+ }++ # 4. Explicit Credentials Usage (Event ID 4648)+ Write-Verbose "Checking explicit credential usage..."+ $explicitCreds = Get-WinEvent -FilterHashtable @{+ LogName = 'Security'+ ID = 4648+ StartTime = $startTime+ } -ErrorAction SilentlyContinue++ if ($explicitCreds) {+ $results.Statistics.TotalExplicitCreds = $explicitCreds.Count++ foreach ($event in $explicitCreds) {+ $xml = [xml]$event.ToXml()+ $eventData = $xml.Event.EventData.Data++ $subjectAccount = ($eventData | Where-Object { $_.Name -eq 'SubjectUserName' }).'#text'+ $targetAccount = ($eventData | Where-Object { $_.Name -eq 'TargetUserName' }).'#text'+ $targetServer = ($eventData | Where-Object { $_.Name -eq 'TargetServerName' }).'#text'+ $processName = ($eventData | Where-Object { $_.Name -eq 'ProcessName' }).'#text'++ $results.ExplicitCredentials += [PSCustomObject]@{+ TimeCreated = $event.TimeCreated+ SourceAccount = $subjectAccount+ TargetAccount = $targetAccount+ TargetServer = $targetServer+ Process = $processName+ }+ }+ }++ # 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'++ # 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+ Account = $targetAccount+ LogonType = $logonType+ SourceIP = $sourceIP+ Workstation = $workstation+ Reason = $reason.TrimStart('; ')+ }+ }+ }+ }+ }++ }+ catch {+ Write-Error "Error during authentication analysis: $_"+ throw+ }+ }++ end {+ # Display summary+ Write-Host "`nAuthentication Analysis Complete!" -ForegroundColor Green+ Write-Host "`n=== Statistics ===" -ForegroundColor Cyan+ Write-Host "Failed logon attempts: $($results.Statistics.TotalFailedLogons)" -ForegroundColor Yellow+ 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 "Brute force indicators: $($results.BruteForceIndicators.Count)" -ForegroundColor $(if ($results.BruteForceIndicators.Count -gt 0) { 'Red' } else { 'Green' })++ if ($IncludeSuccessful) {+ Write-Host "Unusual successful logons: $($results.UnusualLogons.Count)" -ForegroundColor Yellow+ }++ # Export if requested+ if ($ExportPath) {+ if (-not (Test-Path $ExportPath)) {+ New-Item -Path $ExportPath -ItemType Directory -Force | Out-Null+ }+ $exportFile = Join-Path -Path $ExportPath -ChildPath "AuthenticationAnalysis_$(Get-Date -Format 'yyyyMMdd_HHmmss').json"+ $results | ConvertTo-Json -Depth 5 | Out-File -FilePath $exportFile -Encoding UTF8+ Write-Host "`nResults exported to: $exportFile" -ForegroundColor Cyan+ }++ return $results+ }+}\ No newline at end of filediff --git a/Detection/Find-SuspiciousProcesses.ps1 b/Detection/Find-SuspiciousProcesses.ps1new file mode 100644index 0000000..a498fda--- /dev/null+++ b/Detection/Find-SuspiciousProcesses.ps1@@ -0,0 +1,229 @@+function Find-SuspiciousProcesses {+ <#+ .SYNOPSIS+ Detects suspicious running processes on the system+ .DESCRIPTION+ Identifies potentially malicious processes based on various indicators including+ unsigned binaries, unusual locations, suspicious names, and abnormal behavior+ .PARAMETER CheckSignatures+ Verify digital signatures of process executables+ .PARAMETER CheckNetwork+ Include network connection analysis+ .EXAMPLE+ Find-SuspiciousProcesses+ Find-SuspiciousProcesses -CheckSignatures -CheckNetwork+ .OUTPUTS+ Array of suspicious process objects+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$CheckSignatures,++ [Parameter()]+ [switch]$CheckNetwork+ )++ begin {+ Write-Host "Scanning for suspicious processes..." -ForegroundColor Cyan++ $suspiciousProcesses = @()++ # Suspicious process names and patterns+ $suspiciousNames = @(+ 'mimikatz', 'procdump', 'pwdump', 'htran', 'psexec',+ 'netcat', 'ncat', 'nc64', 'nmap', 'tcpdump',+ 'wireshark', 'ettercap', 'cain', 'john', 'hashcat',+ 'meterpreter', 'cobalt', 'beacon', 'empire', 'covenant'+ )++ # Suspicious paths+ $suspiciousPaths = @(+ '\\Temp\\',+ '\\AppData\\Local\\Temp\\',+ '\\Users\\Public\\',+ '\\ProgramData\\.*\\.\\',+ '\\Windows\\Tasks\\'+ )++ # Legitimate system processes that should only run from System32+ $systemProcesses = @(+ 'svchost', 'lsass', 'services', 'csrss', 'winlogon',+ 'smss', 'wininit', 'taskhost', 'dwm', 'explorer'+ )+ }++ process {+ try {+ # Get all running processes with detailed info+ $processes = Get-Process -IncludeUserName -ErrorAction SilentlyContinue++ foreach ($proc in $processes) {+ $suspicionScore = 0+ $suspicionReasons = @()++ try {+ $processPath = $proc.Path+ $processName = $proc.ProcessName.ToLower()++ # Skip if no path (system processes)+ if (-not $processPath) {+ continue+ }++ # Check 1: Suspicious process names+ foreach ($suspName in $suspiciousNames) {+ if ($processName -match $suspName) {+ $suspicionScore += 50+ $suspicionReasons += "Matches known suspicious tool name: $suspName"+ break+ }+ }++ # Check 2: System process in wrong location+ if ($systemProcesses -contains $processName) {+ if ($processPath -notmatch '\\Windows\\System32\\') {+ $suspicionScore += 80+ $suspicionReasons += "System process running from non-standard location"+ }+ }++ # Check 3: Running from suspicious paths+ foreach ($suspPath in $suspiciousPaths) {+ if ($processPath -match $suspPath) {+ $suspicionScore += 40+ $suspicionReasons += "Running from suspicious location: $suspPath"+ break+ }+ }++ # Check 4: No file description+ try {+ $fileInfo = Get-Item -Path $processPath -ErrorAction Stop+ if (-not $fileInfo.VersionInfo.FileDescription) {+ $suspicionScore += 20+ $suspicionReasons += "No file description"+ }++ # Check 5: Very recent file creation (last 24 hours)+ if ($fileInfo.CreationTime -gt (Get-Date).AddDays(-1)) {+ $suspicionScore += 30+ $suspicionReasons += "Executable created within last 24 hours"+ }+ }+ catch {+ $suspicionScore += 30+ $suspicionReasons += "Cannot access executable file"+ }++ # Check 6: Unusual parent-child relationship+ try {+ $parentProcess = Get-Process -Id $proc.Parent.Id -ErrorAction Stop++ # PowerShell/cmd spawned by Office apps+ if ($parentProcess.ProcessName -match '(WINWORD|EXCEL|POWERPNT|OUTLOOK)' -and+ $processName -match '(powershell|cmd|wscript|cscript|mshta)') {+ $suspicionScore += 60+ $suspicionReasons += "Scripting engine spawned by Office application"+ }++ # Browser spawning suspicious processes+ if ($parentProcess.ProcessName -match '(chrome|firefox|iexplore|msedge)' -and+ $processName -match '(powershell|cmd|wscript|cscript)') {+ $suspicionScore += 50+ $suspicionReasons += "Scripting engine spawned by browser"+ }+ }+ catch {+ # Parent process no longer exists or inaccessible+ }++ # Check 7: High CPU or memory usage for unknown process+ if ($proc.CPU -gt 50 -and $processPath -notmatch '(Microsoft|Windows|Program Files)') {+ $suspicionScore += 20+ $suspicionReasons += "High CPU usage for non-standard process"+ }++ # Check 8: Multiple instances of same process with different paths+ $sameNameProcs = $processes | Where-Object {+ $_.ProcessName -eq $proc.ProcessName -and $_.Path -ne $proc.Path+ }+ if ($sameNameProcs) {+ $suspicionScore += 30+ $suspicionReasons += "Multiple instances with different paths"+ }++ # Check 9: Digital signature verification (if requested)+ if ($CheckSignatures) {+ try {+ $signature = Get-AuthenticodeSignature -FilePath $processPath -ErrorAction Stop+ if ($signature.Status -ne 'Valid') {+ $suspicionScore += 40+ $suspicionReasons += "Invalid or missing digital signature: $($signature.Status)"+ }+ }+ catch {+ $suspicionScore += 30+ $suspicionReasons += "Could not verify signature"+ }+ }++ # Check 10: Network connections (if requested)+ if ($CheckNetwork) {+ try {+ $connections = Get-NetTCPConnection -OwningProcess $proc.Id -ErrorAction SilentlyContinue |+ Where-Object { $_.State -eq 'Established' }++ if ($connections) {+ # Check for connections to uncommon ports+ $uncommonPorts = $connections | Where-Object {+ $_.RemotePort -notin @(80, 443, 53, 22, 21, 25, 110, 143, 993, 995, 3389)+ }++ if ($uncommonPorts) {+ $suspicionScore += 25+ $suspicionReasons += "Network connections to uncommon ports: $(($uncommonPorts.RemotePort -join ', '))"+ }+ }+ }+ catch {+ # Could not get network connections+ }+ }++ # If suspicion score is high enough, add to results+ if ($suspicionScore -ge 40) {+ $suspiciousProcesses += [PSCustomObject]@{+ ProcessName = $proc.ProcessName+ ProcessId = $proc.Id+ Path = $processPath+ CommandLine = (Get-CimInstance Win32_Process -Filter "ProcessId = $($proc.Id)" -ErrorAction SilentlyContinue).CommandLine+ UserName = $proc.UserName+ StartTime = $proc.StartTime+ CPU = [math]::Round($proc.CPU, 2)+ WorkingSet = [math]::Round($proc.WorkingSet64 / 1MB, 2)+ SuspicionScore = $suspicionScore+ Reasons = ($suspicionReasons -join '; ')+ ParentProcess = try { (Get-Process -Id $proc.Parent.Id -ErrorAction Stop).ProcessName } catch { 'N/A' }+ }+ }+ }+ catch {+ Write-Verbose "Error processing process $($proc.ProcessName): $_"+ }+ }++ }+ catch {+ Write-Error "Error during process scan: $_"+ throw+ }+ }++ end {+ Write-Host "`nFound $($suspiciousProcesses.Count) suspicious processes" -ForegroundColor $(if ($suspiciousProcesses.Count -gt 0) { 'Red' } else { 'Green' })++ return $suspiciousProcesses | Sort-Object -Property SuspicionScore -Descending+ }+}\ No newline at end of filediff --git a/Enterprise/Get-MultiSystemAudit.ps1 b/Enterprise/Get-MultiSystemAudit.ps1new file mode 100644index 0000000..5515777--- /dev/null+++ b/Enterprise/Get-MultiSystemAudit.ps1@@ -0,0 +1,490 @@+function Get-MultiSystemAudit {+ <#+ .SYNOPSIS+ Audits multiple systems and generates comparative analysis+ .DESCRIPTION+ Performs security audits on multiple computers and creates comparative reports+ showing security posture across the enterprise+ .PARAMETER ComputerName+ Array of computer names to audit+ .PARAMETER Credential+ Credentials for remote access+ .PARAMETER OutputPath+ Path to save audit results+ .PARAMETER GenerateReport+ Generate HTML comparison report+ .EXAMPLE+ Get-MultiSystemAudit -ComputerName "SERVER01","SERVER02","WS001" -GenerateReport+ Get-MultiSystemAudit -ComputerName (Get-Content servers.txt) -Credential $cred -OutputPath "C:\Audits"+ .OUTPUTS+ PSCustomObject with multi-system audit results+ #>++ [CmdletBinding()]+ param(+ [Parameter(Mandatory = $true)]+ [string[]]$ComputerName,++ [Parameter()]+ [PSCredential]$Credential,++ [Parameter()]+ [string]$OutputPath = "C:\MultiSystemAudit_$(Get-Date -Format 'yyyyMMdd_HHmmss')",++ [Parameter()]+ [switch]$GenerateReport+ )++ begin {+ Write-Host "=== MULTI-SYSTEM SECURITY AUDIT ===" -ForegroundColor Cyan+ Write-Host "Target Systems: $($ComputerName.Count)" -ForegroundColor Yellow+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ if (-not (Test-Path $OutputPath)) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ }++ $auditResults = [PSCustomObject]@{+ AuditDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ TotalSystems = $ComputerName.Count+ SystemAudits = @()+ ComparativeAnalysis = @{+ AverageSecurityScore = 0+ HighestScore = 0+ LowestScore = 100+ MostSecureSystem = ""+ LeastSecureSystem = ""+ CommonFindings = @()+ CriticalSystems = @()+ }+ Summary = @{+ TotalFindings = 0+ CriticalFindings = 0+ HighFindings = 0+ MediumFindings = 0+ SystemsAudited = 0+ SystemsFailed = 0+ }+ }+ }++ process {+ try {+ Write-Host "`nAuditing systems..." -ForegroundColor Cyan+ $progress = 0++ foreach ($computer in $ComputerName) {+ $progress+++ Write-Progress -Activity "Multi-System Audit" -Status "Auditing: $computer" -PercentComplete (($progress / $ComputerName.Count) * 100)++ Write-Host "`n[$progress/$($ComputerName.Count)] Auditing: $computer" -ForegroundColor Yellow++ $systemAudit = [PSCustomObject]@{+ ComputerName = $computer+ Status = 'Success'+ SecurityScore = 0+ SecurityLevel = 'Unknown'+ Findings = @()+ Details = @{}+ AuditDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ try {+ # Test connectivity+ $pingTest = Test-Connection -ComputerName $computer -Count 1 -Quiet -ErrorAction SilentlyContinue++ if (-not $pingTest) {+ $systemAudit.Status = 'Unreachable'+ $systemAudit.Details.Error = 'System is unreachable'+ $auditResults.Summary.SystemsFailed+++ $auditResults.SystemAudits += $systemAudit+ continue+ }++ # Collect basic system information+ $sysInfo = if ($Credential) {+ Invoke-Command -ComputerName $computer -Credential $Credential -ScriptBlock {+ [PSCustomObject]@{+ OSVersion = (Get-CimInstance Win32_OperatingSystem).Caption+ LastBoot = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime+ TotalMemory = [math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB, 2)+ DiskSpace = (Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" |+ Select-Object DeviceID, @{N='FreeGB';E={[math]::Round($_.FreeSpace/1GB,2)}},+ @{N='TotalGB';E={[math]::Round($_.Size/1GB,2)}})+ }+ } -ErrorAction Stop+ } else {+ Invoke-Command -ComputerName $computer -ScriptBlock {+ [PSCustomObject]@{+ OSVersion = (Get-CimInstance Win32_OperatingSystem).Caption+ LastBoot = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime+ TotalMemory = [math]::Round((Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB, 2)+ DiskSpace = (Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" |+ Select-Object DeviceID, @{N='FreeGB';E={[math]::Round($_.FreeSpace/1GB,2)}},+ @{N='TotalGB';E={[math]::Round($_.Size/1GB,2)}})+ }+ } -ErrorAction Stop+ }++ $systemAudit.Details = $sysInfo++ # Security checks+ $securityChecks = if ($Credential) {+ Invoke-Command -ComputerName $computer -Credential $Credential -ScriptBlock {+ $score = 0+ $findings = @()++ # Windows Defender+ $defender = Get-MpComputerStatus -ErrorAction SilentlyContinue+ if ($defender -and $defender.RealTimeProtectionEnabled) {+ $score += 25+ } else {+ $findings += [PSCustomObject]@{+ Severity = 'Critical'+ Finding = 'Windows Defender disabled'+ }+ }++ # Firewall+ $firewall = Get-NetFirewallProfile -ErrorAction SilentlyContinue+ $enabledProfiles = @($firewall | Where-Object { $_.Enabled }).Count+ if ($enabledProfiles -eq 3) {+ $score += 25+ } else {+ $findings += [PSCustomObject]@{+ Severity = 'High'+ Finding = "Only $enabledProfiles firewall profiles enabled"+ }+ }++ # UAC+ $uac = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -ErrorAction SilentlyContinue).EnableLUA+ if ($uac -eq 1) {+ $score += 15+ } else {+ $findings += [PSCustomObject]@{+ Severity = 'High'+ Finding = 'UAC disabled'+ }+ }++ # Updates+ try {+ $updateSession = New-Object -ComObject Microsoft.Update.Session+ $updateSearcher = $updateSession.CreateUpdateSearcher()+ $pendingUpdates = $updateSearcher.Search("IsInstalled=0").Updates.Count++ if ($pendingUpdates -eq 0) {+ $score += 20+ } else {+ $findings += [PSCustomObject]@{+ Severity = 'Medium'+ Finding = "$pendingUpdates pending updates"+ }+ }+ } catch {+ $findings += [PSCustomObject]@{+ Severity = 'Low'+ Finding = 'Cannot check updates'+ }+ }++ # Admin accounts+ $admins = @(Get-LocalGroupMember -Group "Administrators" -ErrorAction SilentlyContinue)+ if ($admins.Count -le 2) {+ $score += 15+ } else {+ $findings += [PSCustomObject]@{+ Severity = 'Medium'+ Finding = "$($admins.Count) administrator accounts"+ }+ }++ [PSCustomObject]@{+ Score = $score+ Findings = $findings+ }+ } -ErrorAction Stop+ } else {+ Invoke-Command -ComputerName $computer -ScriptBlock {+ $score = 0+ $findings = @()++ # Windows Defender+ $defender = Get-MpComputerStatus -ErrorAction SilentlyContinue+ if ($defender -and $defender.RealTimeProtectionEnabled) {+ $score += 25+ } else {+ $findings += [PSCustomObject]@{+ Severity = 'Critical'+ Finding = 'Windows Defender disabled'+ }+ }++ # Firewall+ $firewall = Get-NetFirewallProfile -ErrorAction SilentlyContinue+ $enabledProfiles = @($firewall | Where-Object { $_.Enabled }).Count+ if ($enabledProfiles -eq 3) {+ $score += 25+ } else {+ $findings += [PSCustomObject]@{+ Severity = 'High'+ Finding = "Only $enabledProfiles firewall profiles enabled"+ }+ }++ # UAC+ $uac = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -ErrorAction SilentlyContinue).EnableLUA+ if ($uac -eq 1) {+ $score += 15+ } else {+ $findings += [PSCustomObject]@{+ Severity = 'High'+ Finding = 'UAC disabled'+ }+ }++ # Updates+ try {+ $updateSession = New-Object -ComObject Microsoft.Update.Session+ $updateSearcher = $updateSession.CreateUpdateSearcher()+ $pendingUpdates = $updateSearcher.Search("IsInstalled=0").Updates.Count++ if ($pendingUpdates -eq 0) {+ $score += 20+ } else {+ $findings += [PSCustomObject]@{+ Severity = 'Medium'+ Finding = "$pendingUpdates pending updates"+ }+ }+ } catch {+ $findings += [PSCustomObject]@{+ Severity = 'Low'+ Finding = 'Cannot check updates'+ }+ }++ # Admin accounts+ $admins = @(Get-LocalGroupMember -Group "Administrators" -ErrorAction SilentlyContinue)+ if ($admins.Count -le 2) {+ $score += 15+ } else {+ $findings += [PSCustomObject]@{+ Severity = 'Medium'+ Finding = "$($admins.Count) administrator accounts"+ }+ }++ [PSCustomObject]@{+ Score = $score+ Findings = $findings+ }+ } -ErrorAction Stop+ }++ $systemAudit.SecurityScore = $securityChecks.Score+ $systemAudit.Findings = $securityChecks.Findings++ # Determine security level+ if ($systemAudit.SecurityScore -ge 80) {+ $systemAudit.SecurityLevel = 'High'+ } elseif ($systemAudit.SecurityScore -ge 60) {+ $systemAudit.SecurityLevel = 'Medium'+ } elseif ($systemAudit.SecurityScore -ge 40) {+ $systemAudit.SecurityLevel = 'Low'+ } else {+ $systemAudit.SecurityLevel = 'Critical'+ $auditResults.ComparativeAnalysis.CriticalSystems += $computer+ }++ $auditResults.Summary.SystemsAudited+++ $auditResults.Summary.TotalFindings += $systemAudit.Findings.Count++ # Count findings by severity+ foreach ($finding in $systemAudit.Findings) {+ switch ($finding.Severity) {+ 'Critical' { $auditResults.Summary.CriticalFindings++ }+ 'High' { $auditResults.Summary.HighFindings++ }+ 'Medium' { $auditResults.Summary.MediumFindings++ }+ }+ }++ Write-Host " Security Score: $($systemAudit.SecurityScore)/100" -ForegroundColor $(+ if ($systemAudit.SecurityScore -ge 80) { 'Green' }+ elseif ($systemAudit.SecurityScore -ge 60) { 'Yellow' }+ else { 'Red' }+ )++ }+ catch {+ $systemAudit.Status = 'Failed'+ $systemAudit.Details.Error = $_.Exception.Message+ $auditResults.Summary.SystemsFailed+++ Write-Warning " Failed to audit $computer : $_"+ }++ $auditResults.SystemAudits += $systemAudit+ }++ Write-Progress -Activity "Multi-System Audit" -Completed++ # Comparative analysis+ Write-Host "`nPerforming comparative analysis..." -ForegroundColor Cyan++ $successfulAudits = @($auditResults.SystemAudits | Where-Object { $_.Status -eq 'Success' })++ if ($successfulAudits.Count -gt 0) {+ $auditResults.ComparativeAnalysis.AverageSecurityScore = [math]::Round(($successfulAudits | Measure-Object -Property SecurityScore -Average).Average, 2)+ $auditResults.ComparativeAnalysis.HighestScore = ($successfulAudits | Measure-Object -Property SecurityScore -Maximum).Maximum+ $auditResults.ComparativeAnalysis.LowestScore = ($successfulAudits | Measure-Object -Property SecurityScore -Minimum).Minimum++ $bestSystem = $successfulAudits | Sort-Object -Property SecurityScore -Descending | Select-Object -First 1+ $worstSystem = $successfulAudits | Sort-Object -Property SecurityScore | Select-Object -First 1++ $auditResults.ComparativeAnalysis.MostSecureSystem = $bestSystem.ComputerName+ $auditResults.ComparativeAnalysis.LeastSecureSystem = $worstSystem.ComputerName++ # Find common findings+ $allFindings = $successfulAudits | ForEach-Object { $_.Findings.Finding }+ $commonFindings = $allFindings | Group-Object | Where-Object { $_.Count -ge ($successfulAudits.Count / 2) } |+ Select-Object -ExpandProperty Name++ $auditResults.ComparativeAnalysis.CommonFindings = $commonFindings+ }++ }+ catch {+ Write-Error "Error during multi-system audit: $_"+ throw+ }+ }++ end {+ # Display summary+ Write-Host "`n=== AUDIT COMPLETE ===" -ForegroundColor Green+ Write-Host "Total Systems: $($auditResults.TotalSystems)" -ForegroundColor Cyan+ Write-Host "Successfully Audited: $($auditResults.Summary.SystemsAudited)" -ForegroundColor Green+ Write-Host "Failed: $($auditResults.Summary.SystemsFailed)" -ForegroundColor Red++ Write-Host "`nComparative Analysis:" -ForegroundColor Cyan+ Write-Host " Average Security Score: $($auditResults.ComparativeAnalysis.AverageSecurityScore)/100" -ForegroundColor White+ Write-Host " Highest Score: $($auditResults.ComparativeAnalysis.HighestScore)/100 ($($auditResults.ComparativeAnalysis.MostSecureSystem))" -ForegroundColor Green+ Write-Host " Lowest Score: $($auditResults.ComparativeAnalysis.LowestScore)/100 ($($auditResults.ComparativeAnalysis.LeastSecureSystem))" -ForegroundColor Red++ if ($auditResults.ComparativeAnalysis.CriticalSystems.Count -gt 0) {+ Write-Host "`nCritical Systems (Score < 40):" -ForegroundColor Red+ $auditResults.ComparativeAnalysis.CriticalSystems | ForEach-Object {+ Write-Host " - $_" -ForegroundColor Red+ }+ }++ Write-Host "`nFindings Summary:" -ForegroundColor Cyan+ Write-Host " Total Findings: $($auditResults.Summary.TotalFindings)" -ForegroundColor White+ Write-Host " Critical: $($auditResults.Summary.CriticalFindings)" -ForegroundColor Red+ Write-Host " High: $($auditResults.Summary.HighFindings)" -ForegroundColor Yellow+ Write-Host " Medium: $($auditResults.Summary.MediumFindings)" -ForegroundColor Yellow++ if ($auditResults.ComparativeAnalysis.CommonFindings.Count -gt 0) {+ Write-Host "`nCommon Issues (affecting 50%+ of systems):" -ForegroundColor Yellow+ $auditResults.ComparativeAnalysis.CommonFindings | ForEach-Object {+ Write-Host " - $_" -ForegroundColor Yellow+ }+ }++ # Save results+ $auditResults | ConvertTo-Json -Depth 10 | Out-File (Join-Path $OutputPath "MultiSystemAudit.json")++ # Export system summary+ $auditResults.SystemAudits | Select-Object ComputerName, Status, SecurityScore, SecurityLevel, @{N='FindingsCount';E={$_.Findings.Count}} |+ Export-Csv (Join-Path $OutputPath "SystemSummary.csv") -NoTypeInformation++ # Export all findings+ $allFindings = @($auditResults.SystemAudits | ForEach-Object {+ $computer = $_.ComputerName+ $_.Findings | Select-Object @{N='Computer';E={$computer}}, Severity, Finding+ })++ if ($allFindings.Count -gt 0) {+ $allFindings | Export-Csv (Join-Path $OutputPath "AllFindings.csv") -NoTypeInformation+ }++ # Generate HTML report if requested+ if ($GenerateReport) {+ Write-Host "`nGenerating HTML report..." -ForegroundColor Cyan++ $htmlReport = @"+<!DOCTYPE html>+<html>+<head>+ <title>Multi-System Security Audit</title>+ <style>+ body { font-family: Arial; margin: 20px; background: #f5f5f5; }+ .header { background: #2c3e50; color: white; padding: 20px; border-radius: 5px; }+ .summary { background: white; padding: 20px; margin: 20px 0; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }+ table { width: 100%; border-collapse: collapse; background: white; }+ th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }+ th { background: #34495e; color: white; }+ .critical { color: #e74c3c; font-weight: bold; }+ .high { color: #e67e22; font-weight: bold; }+ .medium { color: #f39c12; }+ .low { color: #3498db; }+ </style>+</head>+<body>+ <div class="header">+ <h1>Multi-System Security Audit Report</h1>+ <p>Date: $($auditResults.AuditDate)</p>+ <p>Systems Audited: $($auditResults.Summary.SystemsAudited) / $($auditResults.TotalSystems)</p>+ </div>++ <div class="summary">+ <h2>Comparative Analysis</h2>+ <p>Average Security Score: $($auditResults.ComparativeAnalysis.AverageSecurityScore)/100</p>+ <p>Most Secure: $($auditResults.ComparativeAnalysis.MostSecureSystem) ($($auditResults.ComparativeAnalysis.HighestScore)/100)</p>+ <p>Least Secure: $($auditResults.ComparativeAnalysis.LeastSecureSystem) ($($auditResults.ComparativeAnalysis.LowestScore)/100)</p>+ </div>++ <div class="summary">+ <h2>System Audit Results</h2>+ <table>+ <tr>+ <th>Computer</th>+ <th>Status</th>+ <th>Security Score</th>+ <th>Security Level</th>+ <th>Findings</th>+ </tr>+ $($auditResults.SystemAudits | ForEach-Object {+ "<tr>+ <td>$($_.ComputerName)</td>+ <td>$($_.Status)</td>+ <td>$($_.SecurityScore)/100</td>+ <td class='$($_.SecurityLevel.ToLower())'>$($_.SecurityLevel)</td>+ <td>$($_.Findings.Count)</td>+ </tr>"+ } | Out-String)+ </table>+ </div>++ <div class="summary">+ <h2>Findings Summary</h2>+ <p class="critical">Critical: $($auditResults.Summary.CriticalFindings)</p>+ <p class="high">High: $($auditResults.Summary.HighFindings)</p>+ <p class="medium">Medium: $($auditResults.Summary.MediumFindings)</p>+ </div>+</body>+</html>+"@++ $htmlPath = Join-Path $OutputPath "MultiSystemAudit.html"+ $htmlReport | Out-File $htmlPath -Encoding UTF8+ Write-Host "HTML report generated: $htmlPath" -ForegroundColor Green+ Start-Process $htmlPath+ }++ Write-Host "`nResults saved to: $OutputPath" -ForegroundColor Cyan++ return $auditResults+ }+}\ No newline at end of filediff --git a/Enterprise/Invoke-EnterpriseSecurityScan.ps1 b/Enterprise/Invoke-EnterpriseSecurityScan.ps1new file mode 100644index 0000000..259c29d--- /dev/null+++ b/Enterprise/Invoke-EnterpriseSecurityScan.ps1@@ -0,0 +1,407 @@+function Invoke-EnterpriseSecurityScan {+ <#+ .SYNOPSIS+ Performs security scans across multiple systems in an enterprise environment+ .DESCRIPTION+ Executes comprehensive security assessments on multiple remote computers simultaneously,+ collecting and aggregating results for enterprise-wide security analysis+ .PARAMETER ComputerName+ Array of computer names or IP addresses to scan+ .PARAMETER Credential+ PSCredential object for remote authentication+ .PARAMETER ScanType+ Type of scan: Quick, Standard, or Comprehensive+ .PARAMETER MaxThreads+ Maximum number of concurrent scans (default: 10)+ .PARAMETER OutputPath+ Path to save scan results+ .EXAMPLE+ Invoke-EnterpriseSecurityScan -ComputerName "SERVER01","SERVER02" -ScanType Standard+ Invoke-EnterpriseSecurityScan -ComputerName (Get-Content servers.txt) -Credential $cred -MaxThreads 20+ .OUTPUTS+ PSCustomObject with enterprise scan results+ #>++ [CmdletBinding()]+ param(+ [Parameter(Mandatory = $true)]+ [string[]]$ComputerName,++ [Parameter()]+ [PSCredential]$Credential,++ [Parameter()]+ [ValidateSet('Quick', 'Standard', 'Comprehensive')]+ [string]$ScanType = 'Standard',++ [Parameter()]+ [int]$MaxThreads = 10,++ [Parameter()]+ [string]$OutputPath = "C:\EnterpriseScan_$(Get-Date -Format 'yyyyMMdd_HHmmss')"+ )++ begin {+ Write-Host "=== ENTERPRISE SECURITY SCAN ===" -ForegroundColor Cyan+ Write-Host "Target Systems: $($ComputerName.Count)" -ForegroundColor Yellow+ Write-Host "Scan Type: $ScanType" -ForegroundColor Yellow+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ # Check if testing locally+ $isLocalTest = $ComputerName.Count -eq 1 -and ($ComputerName[0] -eq $env:COMPUTERNAME -or $ComputerName[0] -eq 'localhost' -or $ComputerName[0] -eq '127.0.0.1')++ if ($isLocalTest) {+ Write-Warning "Local testing detected. Ensure PSRemoting is enabled with 'Enable-PSRemoting -Force'"+ }++ # Create output directory+ if (-not (Test-Path $OutputPath)) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ }++ $results = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ScanType = $ScanType+ TotalSystems = $ComputerName.Count+ SystemResults = @()+ Summary = @{+ Successful = 0+ Failed = 0+ CriticalFindings = 0+ HighFindings = 0+ MediumFindings = 0+ LowFindings = 0+ }+ FailedSystems = @()+ }++ # Script block for remote execution+ $scanScriptBlock = {+ param($ScanType)++ $result = [PSCustomObject]@{+ ComputerName = $env:COMPUTERNAME+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ Status = 'Success'+ SecurityScore = 0+ Findings = @()+ Details = @{}+ }++ try {+ # Quick baseline check+ $baseline = Get-MpComputerStatus -ErrorAction SilentlyContinue+ if ($baseline) {+ $result.SecurityScore += if ($baseline.RealTimeProtectionEnabled) { 20 } else { 0 }+ $result.Details.WindowsDefender = $baseline.RealTimeProtectionEnabled++ if (-not $baseline.RealTimeProtectionEnabled) {+ $result.Findings += [PSCustomObject]@{+ Severity = 'Critical'+ Category = 'Windows Defender'+ Finding = 'Real-time protection is disabled'+ }+ }+ }++ # Firewall check+ $firewall = Get-NetFirewallProfile -ErrorAction SilentlyContinue+ $firewallEnabled = @($firewall | Where-Object { $_.Enabled -eq $true }).Count+ $result.SecurityScore += ($firewallEnabled * 10)+ $result.Details.FirewallProfiles = $firewallEnabled++ if ($firewallEnabled -lt 3) {+ $result.Findings += [PSCustomObject]@{+ Severity = 'High'+ Category = 'Firewall'+ Finding = "Only $firewallEnabled firewall profiles enabled"+ }+ }++ # UAC check+ $uacKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"+ $uacEnabled = (Get-ItemProperty -Path $uacKey -ErrorAction SilentlyContinue).EnableLUA+ $result.SecurityScore += if ($uacEnabled -eq 1) { 15 } else { 0 }+ $result.Details.UACEnabled = ($uacEnabled -eq 1)++ if ($uacEnabled -ne 1) {+ $result.Findings += [PSCustomObject]@{+ Severity = 'High'+ Category = 'UAC'+ Finding = 'User Account Control is disabled'+ }+ }++ # Windows Update check+ try {+ $updateSession = New-Object -ComObject Microsoft.Update.Session+ $updateSearcher = $updateSession.CreateUpdateSearcher()+ $pendingUpdates = $updateSearcher.Search("IsInstalled=0").Updates.Count+ $result.Details.PendingUpdates = $pendingUpdates++ if ($pendingUpdates -eq 0) {+ $result.SecurityScore += 15+ } else {+ $result.Findings += [PSCustomObject]@{+ Severity = 'Medium'+ Category = 'Updates'+ Finding = "$pendingUpdates pending Windows updates"+ }+ }+ } catch {+ $result.Details.PendingUpdates = "Unable to check"+ }++ # Additional checks for Standard/Comprehensive scans+ if ($ScanType -in @('Standard', 'Comprehensive')) {+ # Check for admin accounts+ $adminCount = @(Get-LocalGroupMember -Group "Administrators" -ErrorAction SilentlyContinue).Count+ $result.Details.AdminAccounts = $adminCount++ if ($adminCount -gt 3) {+ $result.Findings += [PSCustomObject]@{+ Severity = 'Medium'+ Category = 'Accounts'+ Finding = "$adminCount administrator accounts (excessive)"+ }+ }++ # Check for suspicious services+ $suspiciousServices = @(Get-Service | Where-Object {+ $_.StartType -eq 'Automatic' -and+ $_.Status -eq 'Running' -and+ $_.ServiceName -notmatch '^(Win|Dhcp|Dns|W3SVC|MSSQL|SQL)'+ })++ if ($suspiciousServices.Count -gt 50) {+ $result.Findings += [PSCustomObject]@{+ Severity = 'Low'+ Category = 'Services'+ Finding = "$($suspiciousServices.Count) non-standard services running"+ }+ }+ }++ # Comprehensive scan additions+ if ($ScanType -eq 'Comprehensive') {+ # Check event logs+ $recentErrors = @(Get-WinEvent -FilterHashtable @{+ LogName = 'System'+ Level = 2+ StartTime = (Get-Date).AddDays(-1)+ } -MaxEvents 100 -ErrorAction SilentlyContinue)++ $result.Details.RecentErrors = $recentErrors.Count++ # Check disk space+ $drives = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=3"+ foreach ($drive in $drives) {+ $freePercent = ($drive.FreeSpace / $drive.Size) * 100+ if ($freePercent -lt 10) {+ $result.Findings += [PSCustomObject]@{+ Severity = 'High'+ Category = 'Disk Space'+ Finding = "Drive $($drive.DeviceID) has less than 10% free space"+ }+ }+ }+ }++ # Calculate final score+ $result.SecurityScore = [Math]::Min($result.SecurityScore, 100)++ }+ catch {+ $result.Status = 'Error'+ $result.Findings += [PSCustomObject]@{+ Severity = 'Critical'+ Category = 'Scan Error'+ Finding = $_.Exception.Message+ }+ }++ return $result+ }+ }++ process {+ try {+ Write-Host "`nStarting parallel scan of $($ComputerName.Count) systems..." -ForegroundColor Cyan++ # Create runspace pool for parallel execution+ $runspacePool = [runspacefactory]::CreateRunspacePool(1, $MaxThreads)+ $runspacePool.Open()+ $jobs = @()++ foreach ($computer in $ComputerName) {+ Write-Verbose "Queuing scan for: $computer"++ # Test connectivity first+ $pingTest = Test-Connection -ComputerName $computer -Count 1 -Quiet -ErrorAction SilentlyContinue++ if (-not $pingTest) {+ Write-Warning "Cannot reach $computer - skipping"+ $results.FailedSystems += [PSCustomObject]@{+ ComputerName = $computer+ Reason = 'Unreachable'+ }+ $results.Summary.Failed+++ continue+ }++ # Create PowerShell instance+ $powershell = [powershell]::Create()+ $powershell.RunspacePool = $runspacePool++ # Add script and parameters+ if ($Credential) {+ $powershell.AddScript({+ param($Computer, $Cred, $ScriptBlock, $ScanType)+ try {+ Invoke-Command -ComputerName $Computer -Credential $Cred -ScriptBlock $ScriptBlock -ArgumentList $ScanType -ErrorAction Stop+ } catch {+ [PSCustomObject]@{+ ComputerName = $Computer+ Status = 'Failed'+ SecurityScore = 0+ Findings = @([PSCustomObject]@{+ Severity = 'Critical'+ Category = 'Connection'+ Finding = $_.Exception.Message+ })+ Details = @{}+ }+ }+ }).AddArgument($computer).AddArgument($Credential).AddArgument($scanScriptBlock).AddArgument($ScanType) | Out-Null+ }+ else {+ $powershell.AddScript({+ param($Computer, $ScriptBlock, $ScanType)+ try {+ Invoke-Command -ComputerName $Computer -ScriptBlock $ScriptBlock -ArgumentList $ScanType -ErrorAction Stop+ } catch {+ [PSCustomObject]@{+ ComputerName = $Computer+ Status = 'Failed'+ SecurityScore = 0+ Findings = @([PSCustomObject]@{+ Severity = 'Critical'+ Category = 'Connection'+ Finding = $_.Exception.Message+ })+ Details = @{}+ }+ }+ }).AddArgument($computer).AddArgument($scanScriptBlock).AddArgument($ScanType) | Out-Null+ }++ # Start async execution+ $jobs += [PSCustomObject]@{+ Computer = $computer+ Pipeline = $powershell+ Status = $powershell.BeginInvoke()+ }+ }++ # Wait for all jobs to complete+ Write-Host "Scanning in progress..." -ForegroundColor Yellow+ $completed = 0+ $totalJobs = @($jobs).Count++ while (@($jobs | Where-Object { -not $_.Status.IsCompleted }).Count -gt 0) {+ $completedNow = @($jobs | Where-Object { $_.Status.IsCompleted }).Count+ if ($completedNow -ne $completed) {+ $completed = $completedNow+ if ($totalJobs -gt 0) {+ Write-Progress -Activity "Enterprise Security Scan" -Status "Completed: $completed / $totalJobs" -PercentComplete (($completed / $totalJobs) * 100)+ }+ }+ Start-Sleep -Milliseconds 500+ }++ Write-Progress -Activity "Enterprise Security Scan" -Completed++ # Collect results+ Write-Host "Collecting results..." -ForegroundColor Yellow++ foreach ($job in $jobs) {+ try {+ $result = $job.Pipeline.EndInvoke($job.Status)++ if ($result.Status -eq 'Success') {+ $results.Summary.Successful++++ # Count findings by severity+ foreach ($finding in $result.Findings) {+ switch ($finding.Severity) {+ 'Critical' { $results.Summary.CriticalFindings++ }+ 'High' { $results.Summary.HighFindings++ }+ 'Medium' { $results.Summary.MediumFindings++ }+ 'Low' { $results.Summary.LowFindings++ }+ }+ }+ }+ else {+ $results.Summary.Failed+++ $results.FailedSystems += [PSCustomObject]@{+ ComputerName = $job.Computer+ Reason = 'Scan failed'+ }+ }++ $results.SystemResults += $result+ }+ catch {+ Write-Warning "Error collecting results from $($job.Computer): $_"+ $results.Summary.Failed+++ }+ finally {+ $job.Pipeline.Dispose()+ }+ }++ # Close runspace pool+ $runspacePool.Close()+ $runspacePool.Dispose()++ }+ catch {+ Write-Error "Error during enterprise scan: $_"+ throw+ }+ }++ end {+ # Generate summary report+ Write-Host "`n=== SCAN COMPLETE ===" -ForegroundColor Green+ Write-Host "Total Systems: $($results.TotalSystems)" -ForegroundColor Cyan+ Write-Host "Successful: $($results.Summary.Successful)" -ForegroundColor Green+ Write-Host "Failed: $($results.Summary.Failed)" -ForegroundColor Red+ Write-Host "`nFindings Summary:" -ForegroundColor Cyan+ Write-Host " Critical: $($results.Summary.CriticalFindings)" -ForegroundColor Red+ Write-Host " High: $($results.Summary.HighFindings)" -ForegroundColor Yellow+ Write-Host " Medium: $($results.Summary.MediumFindings)" -ForegroundColor Yellow+ Write-Host " Low: $($results.Summary.LowFindings)" -ForegroundColor White++ # Save results+ $results | ConvertTo-Json -Depth 10 | Out-File (Join-Path $OutputPath "EnterpriseScan_Results.json")++ # Create CSV summary+ $results.SystemResults | Select-Object ComputerName, Status, SecurityScore, @{N='FindingsCount';E={$_.Findings.Count}} |+ Export-Csv (Join-Path $OutputPath "EnterpriseScan_Summary.csv") -NoTypeInformation++ # Export detailed findings+ $allFindings = @($results.SystemResults | ForEach-Object {+ $computer = $_.ComputerName+ $_.Findings | Select-Object @{N='Computer';E={$computer}}, Severity, Category, Finding+ })++ if ($allFindings.Count -gt 0) {+ $allFindings | Export-Csv (Join-Path $OutputPath "EnterpriseScan_Findings.csv") -NoTypeInformation+ }++ Write-Host "`nResults saved to: $OutputPath" -ForegroundColor Cyan++ return $results+ }+}\ No newline at end of filediff --git a/Enterprise/Invoke-SecurityAssessment.ps1 b/Enterprise/Invoke-SecurityAssessment.ps1new file mode 100644index 0000000..a5958b2--- /dev/null+++ b/Enterprise/Invoke-SecurityAssessment.ps1@@ -0,0 +1,834 @@+function Invoke-SecurityAssessment {+ <#+ .SYNOPSIS+ Performs comprehensive security assessment and generates detailed report+ .DESCRIPTION+ Conducts thorough security evaluation including baseline checks, vulnerability assessment,+ compliance validation, and provides actionable recommendations+ .PARAMETER AssessmentType+ Type of assessment: Basic, Standard, or Advanced+ .PARAMETER IncludeCompliance+ Include compliance checks (CIS, NIST, etc.)+ .PARAMETER OutputPath+ Path to save assessment report+ .EXAMPLE+ Invoke-SecurityAssessment -AssessmentType Standard+ Invoke-SecurityAssessment -AssessmentType Advanced -IncludeCompliance -OutputPath "C:\Assessments"+ .OUTPUTS+ PSCustomObject with assessment results+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [ValidateSet('Basic', 'Standard', 'Advanced')]+ [string]$AssessmentType = 'Standard',++ [Parameter()]+ [switch]$IncludeCompliance,++ [Parameter()]+ [string]$OutputPath = "C:\SecurityAssessment_$(Get-Date -Format 'yyyyMMdd_HHmmss')"+ )++ begin {+ Write-Host "=== SECURITY ASSESSMENT ===" -ForegroundColor Cyan+ Write-Host "Assessment Type: $AssessmentType" -ForegroundColor Yellow+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ if (-not (Test-Path $OutputPath)) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ }++ $assessment = [PSCustomObject]@{+ AssessmentDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ AssessmentType = $AssessmentType+ ComputerName = $env:COMPUTERNAME+ OverallScore = 0+ RiskLevel = 'Unknown'+ Categories = @{+ SystemSecurity = $null+ NetworkSecurity = $null+ AccountSecurity = $null+ ApplicationSecurity = $null+ DataProtection = $null+ }+ Findings = @()+ Recommendations = @()+ ComplianceChecks = @()+ }+ }++ process {+ try {+ # Category 1: System Security+ Write-Host "`n[1/5] Assessing System Security..." -ForegroundColor Cyan++ $systemSecurity = [PSCustomObject]@{+ CategoryScore = 0+ MaxScore = 100+ Checks = @()+ }++ # Windows Defender+ $defender = Get-MpComputerStatus -ErrorAction SilentlyContinue+ if ($defender) {+ if ($defender.RealTimeProtectionEnabled) {+ $systemSecurity.CategoryScore += 20+ $systemSecurity.Checks += [PSCustomObject]@{+ Check = 'Windows Defender Real-Time Protection'+ Status = 'Pass'+ Score = 20+ Details = 'Enabled'+ }+ } else {+ $systemSecurity.Checks += [PSCustomObject]@{+ Check = 'Windows Defender Real-Time Protection'+ Status = 'Fail'+ Score = 0+ Details = 'Disabled - Critical risk'+ }+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'Critical'+ Category = 'System Security'+ Finding = 'Windows Defender real-time protection is disabled'+ Impact = 'System vulnerable to malware and viruses'+ Recommendation = 'Enable Windows Defender real-time protection immediately'+ }+ }++ # Signature updates+ $signatureAge = (Get-Date) - $defender.AntivirusSignatureLastUpdated+ if ($signatureAge.Days -le 2) {+ $systemSecurity.CategoryScore += 10+ $systemSecurity.Checks += [PSCustomObject]@{+ Check = 'Antivirus Signatures'+ Status = 'Pass'+ Score = 10+ Details = "Updated $($signatureAge.Days) days ago"+ }+ } else {+ $systemSecurity.Checks += [PSCustomObject]@{+ Check = 'Antivirus Signatures'+ Status = 'Fail'+ Score = 0+ Details = "Outdated ($($signatureAge.Days) days old)"+ }+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'High'+ Category = 'System Security'+ Finding = 'Antivirus signatures are outdated'+ Impact = 'Cannot detect latest threats'+ Recommendation = 'Update Windows Defender definitions'+ }+ }+ }++ # Firewall+ $firewallProfiles = Get-NetFirewallProfile+ $enabledProfiles = @($firewallProfiles | Where-Object { $_.Enabled -eq $true }).Count+ if ($enabledProfiles -eq 3) {+ $systemSecurity.CategoryScore += 20+ $systemSecurity.Checks += [PSCustomObject]@{+ Check = 'Windows Firewall'+ Status = 'Pass'+ Score = 20+ Details = 'All profiles enabled'+ }+ } else {+ $systemSecurity.Checks += [PSCustomObject]@{+ Check = 'Windows Firewall'+ Status = 'Fail'+ Score = ($enabledProfiles * 7)+ Details = "Only $enabledProfiles profiles enabled"+ }+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'High'+ Category = 'System Security'+ Finding = "Only $enabledProfiles firewall profiles are enabled"+ Impact = 'Network-based attacks may succeed'+ Recommendation = 'Enable all firewall profiles'+ }+ }++ # UAC+ $uacKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"+ $uacEnabled = (Get-ItemProperty -Path $uacKey -ErrorAction SilentlyContinue).EnableLUA+ if ($uacEnabled -eq 1) {+ $systemSecurity.CategoryScore += 15+ $systemSecurity.Checks += [PSCustomObject]@{+ Check = 'User Account Control (UAC)'+ Status = 'Pass'+ Score = 15+ Details = 'Enabled'+ }+ } else {+ $systemSecurity.Checks += [PSCustomObject]@{+ Check = 'User Account Control (UAC)'+ Status = 'Fail'+ Score = 0+ Details = 'Disabled'+ }+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'High'+ Category = 'System Security'+ Finding = 'User Account Control is disabled'+ Impact = 'Malware can gain elevated privileges easily'+ Recommendation = 'Enable UAC'+ }+ }++ # BitLocker+ $bitlocker = Get-BitLockerVolume -MountPoint "C:" -ErrorAction SilentlyContinue+ if ($bitlocker -and $bitlocker.ProtectionStatus -eq 'On') {+ $systemSecurity.CategoryScore += 15+ $systemSecurity.Checks += [PSCustomObject]@{+ Check = 'BitLocker Encryption'+ Status = 'Pass'+ Score = 15+ Details = 'System drive encrypted'+ }+ } else {+ $systemSecurity.Checks += [PSCustomObject]@{+ Check = 'BitLocker Encryption'+ Status = 'Fail'+ Score = 0+ Details = 'System drive not encrypted'+ }+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'Medium'+ Category = 'Data Protection'+ Finding = 'System drive is not encrypted'+ Impact = 'Data vulnerable if device is lost or stolen'+ Recommendation = 'Enable BitLocker encryption'+ }+ }++ # Secure Boot+ try {+ $secureBoot = Confirm-SecureBootUEFI+ if ($secureBoot) {+ $systemSecurity.CategoryScore += 10+ $systemSecurity.Checks += [PSCustomObject]@{+ Check = 'Secure Boot'+ Status = 'Pass'+ Score = 10+ Details = 'Enabled'+ }+ } else {+ $systemSecurity.Checks += [PSCustomObject]@{+ Check = 'Secure Boot'+ Status = 'Fail'+ Score = 0+ Details = 'Disabled'+ }+ }+ } catch {+ $systemSecurity.Checks += [PSCustomObject]@{+ Check = 'Secure Boot'+ Status = 'Unknown'+ Score = 0+ Details = 'Cannot determine status'+ }+ }++ # Windows Updates+ try {+ $updateSession = New-Object -ComObject Microsoft.Update.Session+ $updateSearcher = $updateSession.CreateUpdateSearcher()+ $pendingUpdates = $updateSearcher.Search("IsInstalled=0").Updates.Count++ if ($pendingUpdates -eq 0) {+ $systemSecurity.CategoryScore += 10+ $systemSecurity.Checks += [PSCustomObject]@{+ Check = 'Windows Updates'+ Status = 'Pass'+ Score = 10+ Details = 'No pending updates'+ }+ } else {+ $systemSecurity.Checks += [PSCustomObject]@{+ Check = 'Windows Updates'+ Status = 'Fail'+ Score = 0+ Details = "$pendingUpdates pending updates"+ }+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'Medium'+ Category = 'System Security'+ Finding = "$pendingUpdates Windows updates pending"+ Impact = 'Known vulnerabilities not patched'+ Recommendation = 'Install pending Windows updates'+ }+ }+ } catch {+ $systemSecurity.Checks += [PSCustomObject]@{+ Check = 'Windows Updates'+ Status = 'Unknown'+ Score = 0+ Details = 'Cannot check update status'+ }+ }++ $assessment.Categories.SystemSecurity = $systemSecurity++ # Category 2: Network Security+ Write-Host "[2/5] Assessing Network Security..." -ForegroundColor Cyan++ $networkSecurity = [PSCustomObject]@{+ CategoryScore = 0+ MaxScore = 100+ Checks = @()+ }++ # Check for dangerous open ports+ $dangerousPorts = @(23, 135, 139, 445, 1433, 3389, 5985, 5986)+ $listeningPorts = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue+ $exposedPorts = @($listeningPorts | Where-Object { $dangerousPorts -contains $_.LocalPort })++ if ($exposedPorts.Count -eq 0) {+ $networkSecurity.CategoryScore += 30+ $networkSecurity.Checks += [PSCustomObject]@{+ Check = 'Dangerous Ports'+ Status = 'Pass'+ Score = 30+ Details = 'No commonly exploited ports exposed'+ }+ } else {+ $networkSecurity.Checks += [PSCustomObject]@{+ Check = 'Dangerous Ports'+ Status = 'Fail'+ Score = 0+ Details = "$($exposedPorts.Count) dangerous ports listening"+ }+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'High'+ Category = 'Network Security'+ Finding = "Dangerous ports exposed: $(($exposedPorts.LocalPort | Select-Object -Unique) -join ', ')"+ Impact = 'Network attack surface increased'+ Recommendation = 'Close unnecessary ports or restrict access'+ }+ }++ # Network shares+ $shares = @(Get-SmbShare | Where-Object { $_.Name -notmatch '^(ADMIN\$|C\$|IPC\$)$' })+ if ($shares.Count -eq 0) {+ $networkSecurity.CategoryScore += 20+ $networkSecurity.Checks += [PSCustomObject]@{+ Check = 'Network Shares'+ Status = 'Pass'+ Score = 20+ Details = 'No user shares configured'+ }+ } else {+ $networkSecurity.CategoryScore += 10+ $networkSecurity.Checks += [PSCustomObject]@{+ Check = 'Network Shares'+ Status = 'Warning'+ Score = 10+ Details = "$($shares.Count) shares configured"+ }+ }++ # SMB version+ $smbConfig = Get-SmbServerConfiguration+ if ($smbConfig.EnableSMB1Protocol -eq $false) {+ $networkSecurity.CategoryScore += 25+ $networkSecurity.Checks += [PSCustomObject]@{+ Check = 'SMBv1 Protocol'+ Status = 'Pass'+ Score = 25+ Details = 'Disabled (secure)'+ }+ } else {+ $networkSecurity.Checks += [PSCustomObject]@{+ Check = 'SMBv1 Protocol'+ Status = 'Fail'+ Score = 0+ Details = 'Enabled (insecure)'+ }+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'High'+ Category = 'Network Security'+ Finding = 'SMBv1 protocol is enabled'+ Impact = 'Vulnerable to WannaCry-style attacks'+ Recommendation = 'Disable SMBv1 protocol'+ }+ }++ # WiFi security (if applicable)+ $wifiProfiles = netsh wlan show profiles | Select-String "All User Profile"+ if ($wifiProfiles) {+ $networkSecurity.CategoryScore += 10+ $networkSecurity.Checks += [PSCustomObject]@{+ Check = 'WiFi Profiles'+ Status = 'Info'+ Score = 10+ Details = "$($wifiProfiles.Count) WiFi profiles configured"+ }+ }++ # Network Level Authentication for RDP+ $rdpNLA = (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" -ErrorAction SilentlyContinue).UserAuthentication+ if ($rdpNLA -eq 1) {+ $networkSecurity.CategoryScore += 15+ $networkSecurity.Checks += [PSCustomObject]@{+ Check = 'RDP Network Level Authentication'+ Status = 'Pass'+ Score = 15+ Details = 'Enabled'+ }+ } else {+ $networkSecurity.Checks += [PSCustomObject]@{+ Check = 'RDP Network Level Authentication'+ Status = 'Fail'+ Score = 0+ Details = 'Disabled'+ }+ }++ $assessment.Categories.NetworkSecurity = $networkSecurity++ # Category 3: Account Security+ Write-Host "[3/5] Assessing Account Security..." -ForegroundColor Cyan++ $accountSecurity = [PSCustomObject]@{+ CategoryScore = 0+ MaxScore = 100+ Checks = @()+ }++ # Local accounts+ $localUsers = @(Get-LocalUser | Where-Object { $_.Enabled -eq $true })+ $accountSecurity.Checks += [PSCustomObject]@{+ Check = 'Local User Accounts'+ Status = 'Info'+ Score = 0+ Details = "$($localUsers.Count) enabled accounts"+ }++ # Administrator account status+ $adminAccount = Get-LocalUser -Name "Administrator" -ErrorAction SilentlyContinue+ if ($adminAccount -and $adminAccount.Enabled -eq $false) {+ $accountSecurity.CategoryScore += 20+ $accountSecurity.Checks += [PSCustomObject]@{+ Check = 'Built-in Administrator Account'+ Status = 'Pass'+ Score = 20+ Details = 'Disabled'+ }+ } else {+ $accountSecurity.Checks += [PSCustomObject]@{+ Check = 'Built-in Administrator Account'+ Status = 'Fail'+ Score = 0+ Details = 'Enabled'+ }+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'Medium'+ Category = 'Account Security'+ Finding = 'Built-in Administrator account is enabled'+ Impact = 'Well-known account is attack target'+ Recommendation = 'Disable built-in Administrator account'+ }+ }++ # Guest account+ $guestAccount = Get-LocalUser -Name "Guest" -ErrorAction SilentlyContinue+ if ($guestAccount -and $guestAccount.Enabled -eq $false) {+ $accountSecurity.CategoryScore += 15+ $accountSecurity.Checks += [PSCustomObject]@{+ Check = 'Guest Account'+ Status = 'Pass'+ Score = 15+ Details = 'Disabled'+ }+ } else {+ $accountSecurity.Checks += [PSCustomObject]@{+ Check = 'Guest Account'+ Status = 'Fail'+ Score = 0+ Details = 'Enabled'+ }+ }++ # Password policy+ $passwordPolicy = net accounts+ $accountSecurity.CategoryScore += 20+ $accountSecurity.Checks += [PSCustomObject]@{+ Check = 'Password Policy'+ Status = 'Info'+ Score = 20+ Details = 'Configured'+ }++ # Accounts without passwords+ $noPasswordAccounts = @($localUsers | Where-Object { $_.PasswordRequired -eq $false })+ if ($noPasswordAccounts.Count -eq 0) {+ $accountSecurity.CategoryScore += 25+ $accountSecurity.Checks += [PSCustomObject]@{+ Check = 'Password Required'+ Status = 'Pass'+ Score = 25+ Details = 'All accounts require passwords'+ }+ } else {+ $accountSecurity.Checks += [PSCustomObject]@{+ Check = 'Password Required'+ Status = 'Fail'+ Score = 0+ Details = "$($noPasswordAccounts.Count) accounts without passwords"+ }+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'Critical'+ Category = 'Account Security'+ Finding = "$($noPasswordAccounts.Count) accounts do not require passwords"+ Impact = 'Unauthorized access possible'+ Recommendation = 'Require passwords for all accounts'+ }+ }++ # Administrator group members+ $admins = @(Get-LocalGroupMember -Group "Administrators" -ErrorAction SilentlyContinue)+ if ($admins.Count -le 2) {+ $accountSecurity.CategoryScore += 20+ $accountSecurity.Checks += [PSCustomObject]@{+ Check = 'Administrator Group Size'+ Status = 'Pass'+ Score = 20+ Details = "$($admins.Count) members (appropriate)"+ }+ } else {+ $accountSecurity.Checks += [PSCustomObject]@{+ Check = 'Administrator Group Size'+ Status = 'Warning'+ Score = 10+ Details = "$($admins.Count) members (excessive)"+ }+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'Medium'+ Category = 'Account Security'+ Finding = "$($admins.Count) users in Administrators group"+ Impact = 'Excessive privileged access'+ Recommendation = 'Limit administrator access to necessary personnel'+ }+ }++ $assessment.Categories.AccountSecurity = $accountSecurity++ # Category 4: Application Security+ Write-Host "[4/5] Assessing Application Security..." -ForegroundColor Cyan++ $applicationSecurity = [PSCustomObject]@{+ CategoryScore = 0+ MaxScore = 100+ Checks = @()+ }++ # PowerShell execution policy+ $executionPolicy = Get-ExecutionPolicy -Scope LocalMachine+ if ($executionPolicy -in @('AllSigned', 'RemoteSigned', 'Restricted')) {+ $applicationSecurity.CategoryScore += 25+ $applicationSecurity.Checks += [PSCustomObject]@{+ Check = 'PowerShell Execution Policy'+ Status = 'Pass'+ Score = 25+ Details = $executionPolicy+ }+ } else {+ $applicationSecurity.Checks += [PSCustomObject]@{+ Check = 'PowerShell Execution Policy'+ Status = 'Fail'+ Score = 0+ Details = "$executionPolicy (insecure)"+ }+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'Medium'+ Category = 'Application Security'+ Finding = "PowerShell execution policy is $executionPolicy"+ Impact = 'Malicious scripts can execute without restriction'+ Recommendation = 'Set execution policy to RemoteSigned or AllSigned'+ }+ }++ # PowerShell logging+ # PowerShell logging+$psLogging = Get-ItemProperty "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -ErrorAction SilentlyContinue+if ($psLogging -and $psLogging.EnableScriptBlockLogging -eq 1) {+ $applicationSecurity.CategoryScore += 20+ $applicationSecurity.Checks += [PSCustomObject]@{+ Check = 'PowerShell Script Block Logging'+ Status = 'Pass'+ Score = 20+ Details = 'Enabled'+ }+} else {+ $applicationSecurity.Checks += [PSCustomObject]@{+ Check = 'PowerShell Script Block Logging'+ Status = 'Fail'+ Score = 0+ Details = 'Disabled'+ }+}++ # AppLocker+ # AppLocker+try {+ $appLockerPolicies = Get-AppLockerPolicy -Effective -ErrorAction Stop+ if ($appLockerPolicies) {+ $applicationSecurity.CategoryScore += 25+ $applicationSecurity.Checks += [PSCustomObject]@{+ Check = 'AppLocker'+ Status = 'Pass'+ Score = 25+ Details = 'Configured'+ }+ } else {+ $applicationSecurity.Checks += [PSCustomObject]@{+ Check = 'AppLocker'+ Status = 'Fail'+ Score = 0+ Details = 'Not configured'+ }+ }+} catch {+ $applicationSecurity.Checks += [PSCustomObject]@{+ Check = 'AppLocker'+ Status = 'N/A'+ Score = 0+ Details = 'Not available (Windows Pro/Enterprise feature)'+ }+}++ # Windows Defender Application Control+ $wdacStatus = Get-CimInstance -ClassName Win32_DeviceGuard -Namespace root\Microsoft\Windows\DeviceGuard -ErrorAction SilentlyContinue+ if ($wdacStatus -and $wdacStatus.CodeIntegrityPolicyEnforcementStatus -eq 1) {+ $applicationSecurity.CategoryScore += 30+ $applicationSecurity.Checks += [PSCustomObject]@{+ Check = 'Windows Defender Application Control'+ Status = 'Pass'+ Score = 30+ Details = 'Enforced'+ }+ } else {+ $applicationSecurity.Checks += [PSCustomObject]@{+ Check = 'Windows Defender Application Control'+ Status = 'Info'+ Score = 0+ Details = 'Not enforced'+ }+ }++ $assessment.Categories.ApplicationSecurity = $applicationSecurity++ # Category 5: Data Protection+ Write-Host "[5/5] Assessing Data Protection..." -ForegroundColor Cyan++ $dataProtection = [PSCustomObject]@{+ CategoryScore = 0+ MaxScore = 100+ Checks = @()+ }++ # BitLocker (already checked, summarize)+ if ($bitlocker -and $bitlocker.ProtectionStatus -eq 'On') {+ $dataProtection.CategoryScore += 40+ $dataProtection.Checks += [PSCustomObject]@{+ Check = 'System Drive Encryption'+ Status = 'Pass'+ Score = 40+ Details = 'BitLocker enabled'+ }+ } else {+ $dataProtection.Checks += [PSCustomObject]@{+ Check = 'System Drive Encryption'+ Status = 'Fail'+ Score = 0+ Details = 'Not encrypted'+ }+ }++ # Backup status+ $backupStatus = Get-WmiObject -Namespace root\Microsoft\Windows\Backup -Class MSFT_WBBackupSet -ErrorAction SilentlyContinue+ if ($backupStatus) {+ $dataProtection.CategoryScore += 30+ $dataProtection.Checks += [PSCustomObject]@{+ Check = 'Windows Backup'+ Status = 'Pass'+ Score = 30+ Details = 'Configured'+ }+ } else {+ $dataProtection.Checks += [PSCustomObject]@{+ Check = 'Windows Backup'+ Status = 'Warning'+ Score = 0+ Details = 'Not configured'+ }+ $assessment.Findings += [PSCustomObject]@{+ Severity = 'Medium'+ Category = 'Data Protection'+ Finding = 'Windows Backup is not configured'+ Impact = 'Data loss risk in case of failure'+ Recommendation = 'Configure regular backups'+ }+ }++ # System Restore+ $systemRestore = Get-ComputerRestorePoint -ErrorAction SilentlyContinue+ if ($systemRestore) {+ $dataProtection.CategoryScore += 15+ $dataProtection.Checks += [PSCustomObject]@{+ Check = 'System Restore Points'+ Status = 'Pass'+ Score = 15+ Details = "$($systemRestore.Count) restore points available"+ }+ } else {+ $dataProtection.Checks += [PSCustomObject]@{+ Check = 'System Restore Points'+ Status = 'Warning'+ Score = 0+ Details = 'No restore points'+ }+ }++ # Audit logging+ $auditPolicy = auditpol /get /category:* 2>&1+ if ($auditPolicy -match 'Success') {+ $dataProtection.CategoryScore += 15+ $dataProtection.Checks += [PSCustomObject]@{+ Check = 'Audit Logging'+ Status = 'Pass'+ Score = 15+ Details = 'Configured'+ }+ } else {+ $dataProtection.Checks += [PSCustomObject]@{+ Check = 'Audit Logging'+ Status = 'Warning'+ Score = 0+ Details = 'Limited auditing'+ }+ }++ $assessment.Categories.DataProtection = $dataProtection++ # Calculate overall score+ # Calculate overall score+$totalScore = 0+$maxScore = 0+try {+ foreach ($category in $assessment.Categories.PSObject.Properties) {+ if ($category.Value) {+ try {+ if ($category.Value.PSObject.Properties.Name -contains 'CategoryScore') {+ $totalScore += [int]$category.Value.CategoryScore+ $maxScore += [int]$category.Value.MaxScore+ }+ } catch {+ Write-Verbose "Could not calculate score for category: $($category.Name)"+ }+ }+ }++ # Prevent division by zero+ if ($maxScore -gt 0) {+ $assessment.OverallScore = [math]::Round(($totalScore / $maxScore) * 100, 2)+ } else {+ $assessment.OverallScore = 0+ }+} catch {+ Write-Warning "Could not calculate overall score: $_"+ $assessment.OverallScore = 0+}++# Determine risk level+if ($assessment.OverallScore -ge 80) {+ $assessment.RiskLevel = 'Low'+} elseif ($assessment.OverallScore -ge 60) {+ $assessment.RiskLevel = 'Medium'+} elseif ($assessment.OverallScore -ge 40) {+ $assessment.RiskLevel = 'High'+} else {+ $assessment.RiskLevel = 'Critical'+}++ # Generate recommendations+ $assessment.Recommendations = @(+ "Overall Security Score: $($assessment.OverallScore)/100 - Risk Level: $($assessment.RiskLevel)",+ "Address all Critical severity findings immediately",+ "Implement a regular patch management schedule",+ "Enable all recommended security features",+ "Conduct security assessments quarterly",+ "Review and update security policies regularly"+ )++ }+ catch {+ Write-Error "Error during security assessment: $_"+ throw+ }+ }++ end {+ # Display summary+ Write-Host "`n=== ASSESSMENT COMPLETE ===" -ForegroundColor Green+ Write-Host "Overall Security Score: $($assessment.OverallScore)/100" -ForegroundColor $(+ if ($assessment.OverallScore -ge 80) { 'Green' }+ elseif ($assessment.OverallScore -ge 60) { 'Yellow' }+ else { 'Red' }+ )+ Write-Host "Risk Level: $($assessment.RiskLevel)" -ForegroundColor $(+ switch ($assessment.RiskLevel) {+ 'Low' { 'Green' }+ 'Medium' { 'Yellow' }+ 'High' { 'Red' }+ 'Critical' { 'Red' }+ }+ )++ Write-Host "`nCategory Scores:" -ForegroundColor Cyan+foreach ($category in $assessment.Categories.PSObject.Properties) {+ if ($category.Value -and $category.Value -is [PSCustomObject]) {+ try {+ if ($category.Value.PSObject.Properties.Name -contains 'CategoryScore' -and+ $category.Value.PSObject.Properties.Name -contains 'MaxScore') {+ $catScore = [int]$category.Value.CategoryScore+ $catMax = [int]$category.Value.MaxScore+ if ($catMax -gt 0) {+ $percentage = [math]::Round(($catScore / $catMax) * 100, 0)+ Write-Host " $($category.Name): $percentage%" -ForegroundColor White+ }+ }+ } catch {+ Write-Verbose "Could not display score for: $($category.Name)"+ }+ }+}++ Write-Host "`nFindings: $($assessment.Findings.Count)" -ForegroundColor Cyan+ $criticalCount = @($assessment.Findings | Where-Object { $_.Severity -eq 'Critical' }).Count+ $highCount = @($assessment.Findings | Where-Object { $_.Severity -eq 'High' }).Count+ $mediumCount = @($assessment.Findings | Where-Object { $_.Severity -eq 'Medium' }).Count++ Write-Host " Critical: $criticalCount" -ForegroundColor Red+ Write-Host " High: $highCount" -ForegroundColor Yellow+ Write-Host " Medium: $mediumCount" -ForegroundColor Yellow++ # Save results+ $assessment | ConvertTo-Json -Depth 10 | Out-File (Join-Path $OutputPath "SecurityAssessment.json")++ # Export findings+ if ($assessment.Findings.Count -gt 0) {+ $assessment.Findings | Export-Csv (Join-Path $OutputPath "SecurityFindings.csv") -NoTypeInformation+ }++ # Export recommendations+ $assessment.Recommendations | Out-File (Join-Path $OutputPath "Recommendations.txt")++ Write-Host "`nResults saved to: $OutputPath" -ForegroundColor Cyan++ return $assessment+ }+}\ No newline at end of filediff --git a/Forensics/Export-MemoryDump.ps1 b/Forensics/Export-MemoryDump.ps1new file mode 100644index 0000000..f3920c9--- /dev/null+++ b/Forensics/Export-MemoryDump.ps1@@ -0,0 +1,408 @@+function Export-MemoryDump {+ <#+ .SYNOPSIS+ Creates memory dumps for forensic analysis+ .DESCRIPTION+ Captures memory dumps of specific processes or full system memory using+ multiple methods. Supports live system memory acquisition, process dumps,+ and LSASS dumps for credential analysis.+ .PARAMETER ProcessName+ Name of specific process to dump (e.g., 'lsass', 'chrome')+ .PARAMETER ProcessId+ Process ID to dump+ .PARAMETER DumpType+ Type of dump: Full, Mini, or LSASS+ .PARAMETER OutputPath+ Path to save memory dump files (default: C:\MemoryDumps)+ .PARAMETER UseProcDump+ Use Sysinternals ProcDump if available (more reliable)+ .PARAMETER Compress+ Compress dump file after creation+ .EXAMPLE+ Export-MemoryDump -ProcessName lsass -OutputPath "C:\Forensics"+ Export-MemoryDump -ProcessId 1234 -DumpType Full+ .OUTPUTS+ PSCustomObject with dump file information+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [string]$ProcessName,++ [Parameter()]+ [int]$ProcessId,++ [Parameter()]+ [ValidateSet('Full', 'Mini', 'LSASS')]+ [string]$DumpType = 'Mini',++ [Parameter()]+ [string]$OutputPath = 'C:\MemoryDumps',++ [Parameter()]+ [switch]$UseProcDump,++ [Parameter()]+ [switch]$Compress+ )++ begin {+ Write-Host "=== MEMORY DUMP EXPORT ===" -ForegroundColor Cyan+ Write-Host "Dump Type: $DumpType" -ForegroundColor Yellow+ Write-Host "Output Path: $OutputPath" -ForegroundColor Yellow++ # Check if running as Administrator+ $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)++ if (-not $isAdmin) {+ Write-Warning "This function requires Administrator privileges!"+ Write-Host "Please run PowerShell as Administrator and try again." -ForegroundColor Red+ return+ }++ # Create output directory+ if (-not (Test-Path $OutputPath)) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ Write-Host "Created output directory: $OutputPath" -ForegroundColor Green+ }++ $result = [PSCustomObject]@{+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ DumpType = $DumpType+ ProcessName = $null+ ProcessId = $null+ DumpFile = $null+ FileSize = 0+ Success = $false+ Method = $null+ ErrorMessage = $null+ }+ }++ process {+ try {+ # Determine target process+ $targetProcess = $null++ if ($DumpType -eq 'LSASS') {+ Write-Host "`n[*] Targeting LSASS process for credential dump..." -ForegroundColor Cyan+ Write-Warning "LSASS dumps may trigger antivirus alerts!"++ $targetProcess = Get-Process -Name lsass -ErrorAction SilentlyContinue+ if (-not $targetProcess) {+ Write-Error "Could not find LSASS process"+ return+ }+ $ProcessName = 'lsass'+ }+ elseif ($ProcessId) {+ Write-Host "`n[*] Targeting Process ID: $ProcessId..." -ForegroundColor Cyan+ $targetProcess = Get-Process -Id $ProcessId -ErrorAction SilentlyContinue+ if (-not $targetProcess) {+ Write-Error "Process with ID $ProcessId not found. Use Get-Process to list running processes."+ return+ }+ $ProcessName = $targetProcess.ProcessName+ }+ elseif ($ProcessName) {+ Write-Host "`n[*] Targeting Process: $ProcessName..." -ForegroundColor Cyan+ $targetProcess = Get-Process -Name $ProcessName -ErrorAction SilentlyContinue | Select-Object -First 1+ if (-not $targetProcess) {+ Write-Error "Process '$ProcessName' not found. Use Get-Process to list running processes."+ return+ }+ }+ else {+ Write-Error "No process specified. Use -ProcessName, -ProcessId, or -DumpType LSASS"+ return+ }++ $result.ProcessName = $targetProcess.ProcessName+ $result.ProcessId = $targetProcess.Id++ Write-Host "Process: $($targetProcess.ProcessName) (PID: $($targetProcess.Id))" -ForegroundColor Green++ # Generate dump filename+ $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"+ $dumpFileName = "$($targetProcess.ProcessName)_$($targetProcess.Id)_${timestamp}.dmp"+ $dumpFilePath = Join-Path $OutputPath $dumpFileName++ # METHOD 1: Try ProcDump if available and requested+ if ($UseProcDump) {+ Write-Host "`n[1/3] Attempting ProcDump method..." -ForegroundColor Cyan++ $procDumpPaths = @(+ "C:\Tools\procdump.exe",+ "C:\Tools\procdump64.exe",+ "$env:TEMP\procdump.exe",+ ".\procdump.exe"+ )++ $foundProcDump = $null+ foreach ($path in $procDumpPaths) {+ if (Test-Path $path) {+ $foundProcDump = $path+ break+ }+ }++ if ($foundProcDump) {+ Write-Host " Found ProcDump: $foundProcDump" -ForegroundColor Green++ $procDumpArgs = @(+ "-accepteula",+ "-ma", # Full dump+ $targetProcess.Id,+ $dumpFilePath+ )++ try {+ $procDumpResult = & $foundProcDump $procDumpArgs 2>&1++ if (Test-Path $dumpFilePath) {+ $result.Success = $true+ $result.Method = "ProcDump"+ $result.DumpFile = $dumpFilePath+ Write-Host " Successfully created dump with ProcDump" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "ProcDump failed: $_"+ }+ }+ else {+ Write-Host " ProcDump not found, trying alternative methods..." -ForegroundColor Gray+ }+ }++ # METHOD 2: Use MiniDumpWriteDump with proper handle+ if (-not $result.Success) {+ Write-Host "`n[2/3] Attempting MiniDumpWriteDump method..." -ForegroundColor Cyan++ try {+ # FIXED: Define complete P/Invoke signatures with proper types+ Add-Type -TypeDefinition @"+using System;+using System.Runtime.InteropServices;++public class ProcessDump {+ [Flags]+ public enum ProcessAccessFlags : uint {+ PROCESS_ALL_ACCESS = 0x001F0FFF,+ PROCESS_VM_READ = 0x00000010,+ PROCESS_QUERY_INFORMATION = 0x00000400+ }++ [DllImport("kernel32.dll", SetLastError = true)]+ public static extern IntPtr OpenProcess(+ ProcessAccessFlags processAccess,+ bool bInheritHandle,+ int processId+ );++ [DllImport("kernel32.dll", SetLastError = true)]+ public static extern bool CloseHandle(IntPtr hObject);++ [DllImport("dbghelp.dll", SetLastError = true)]+ public static extern bool MiniDumpWriteDump(+ IntPtr hProcess,+ uint ProcessId,+ IntPtr hFile,+ uint DumpType,+ IntPtr ExceptionParam,+ IntPtr UserStreamParam,+ IntPtr CallbackParam+ );+}+"@ -ErrorAction SilentlyContinue++ # FIXED: Open process handle with OpenProcess API+ $processHandle = [ProcessDump]::OpenProcess(+ [ProcessDump+ProcessAccessFlags]::PROCESS_ALL_ACCESS,+ $false,+ $targetProcess.Id+ )++ if ($processHandle -eq [IntPtr]::Zero) {+ $lastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()+ throw "Failed to open process handle. Error code: $lastError (May need SeDebugPrivilege or SYSTEM access)"+ }++ Write-Host " Process handle obtained successfully" -ForegroundColor Green++ # Create dump file+ $fileStream = [System.IO.File]::Create($dumpFilePath)++ # Determine dump type flag+ $dumpTypeFlag = switch ($DumpType) {+ 'Full' { 2 } # MiniDumpWithFullMemory+ 'Mini' { 0 } # MiniDumpNormal+ 'LSASS' { 2 } # Full dump for LSASS+ }++ Write-Host " Creating dump file..." -ForegroundColor Gray++ # Create the dump+ $success = [ProcessDump]::MiniDumpWriteDump(+ $processHandle,+ [uint32]$targetProcess.Id,+ $fileStream.SafeFileHandle.DangerousGetHandle(),+ $dumpTypeFlag,+ [IntPtr]::Zero,+ [IntPtr]::Zero,+ [IntPtr]::Zero+ )++ $fileStream.Close()+ [ProcessDump]::CloseHandle($processHandle) | Out-Null++ if ($success -and (Test-Path $dumpFilePath)) {+ $result.Success = $true+ $result.Method = "MiniDumpWriteDump"+ $result.DumpFile = $dumpFilePath+ Write-Host " Successfully created dump with MiniDumpWriteDump" -ForegroundColor Green+ }+ else {+ $lastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error()+ throw "MiniDumpWriteDump failed with error code: $lastError"+ }+ }+ catch {+ Write-Warning "MiniDumpWriteDump failed: $_"+ $result.ErrorMessage = $_.Exception.Message++ # Clean up failed dump file+ if (Test-Path $dumpFilePath) {+ Remove-Item $dumpFilePath -Force -ErrorAction SilentlyContinue+ }+ }+ }++ # METHOD 3: Use rundll32.exe comsvcs.dll method (LSASS specific)+ if (-not $result.Success -and $DumpType -eq 'LSASS') {+ Write-Host "`n[3/3] Attempting comsvcs.dll method (LSASS specific)..." -ForegroundColor Cyan++ try {+ $comsvcsPath = "$env:SystemRoot\System32\comsvcs.dll"++ if (Test-Path $comsvcsPath) {+ Write-Host " Using rundll32.exe with comsvcs.dll..." -ForegroundColor Gray++ # Build command+ $arguments = @(+ $comsvcsPath,+ "MiniDump",+ $targetProcess.Id,+ "`"$dumpFilePath`"",+ "full"+ )++ # Run elevated+ $psi = New-Object System.Diagnostics.ProcessStartInfo+ $psi.FileName = "rundll32.exe"+ $psi.Arguments = $arguments -join ' '+ $psi.Verb = "runas"+ $psi.WindowStyle = "Hidden"++ $proc = [System.Diagnostics.Process]::Start($psi)+ $proc.WaitForExit(10000) # Wait 10 seconds++ # Wait a moment for dump to complete+ Start-Sleep -Seconds 2++ if (Test-Path $dumpFilePath) {+ $result.Success = $true+ $result.Method = "comsvcs.dll"+ $result.DumpFile = $dumpFilePath+ Write-Host " Successfully created LSASS dump with comsvcs.dll" -ForegroundColor Green+ }+ }+ }+ catch {+ Write-Warning "comsvcs.dll method failed: $_"+ }+ }++ # Check final result+ if ($result.Success -and (Test-Path $dumpFilePath)) {+ $dumpFile = Get-Item $dumpFilePath+ $result.FileSize = $dumpFile.Length++ $fileSizeMB = [Math]::Round($dumpFile.Length / 1MB, 2)+ Write-Host "`n[SUCCESS] Memory dump created!" -ForegroundColor Green+ Write-Host " File: $dumpFilePath" -ForegroundColor Cyan+ Write-Host " Size: $fileSizeMB MB" -ForegroundColor Cyan+ Write-Host " Method: $($result.Method)" -ForegroundColor Cyan++ # Compress if requested+ if ($Compress) {+ Write-Host "`n[*] Compressing dump file..." -ForegroundColor Cyan++ try {+ $zipPath = "$dumpFilePath.zip"+ Compress-Archive -Path $dumpFilePath -DestinationPath $zipPath -CompressionLevel Optimal++ if (Test-Path $zipPath) {+ $zipFile = Get-Item $zipPath+ $zipSizeMB = [Math]::Round($zipFile.Length / 1MB, 2)+ $compressionRatio = [Math]::Round((1 - ($zipFile.Length / $dumpFile.Length)) * 100, 1)++ Write-Host " Compressed: $zipPath" -ForegroundColor Green+ Write-Host " Compressed Size: $zipSizeMB MB" -ForegroundColor Cyan+ Write-Host " Compression Ratio: $compressionRatio%" -ForegroundColor Cyan++ # Optionally remove uncompressed file+ Write-Host "`n Remove original dump file? (Y/N)" -ForegroundColor Yellow -NoNewline+ $removeOriginal = Read-Host+ if ($removeOriginal -eq 'Y') {+ Remove-Item $dumpFilePath -Force+ Write-Host " Removed original dump file" -ForegroundColor Gray+ $result.DumpFile = $zipPath+ }+ }+ }+ catch {+ Write-Warning "Compression failed: $_"+ }+ }++ # Security recommendations+ Write-Host "`n[!] SECURITY RECOMMENDATIONS:" -ForegroundColor Yellow+ Write-Host " 1. Store dump files securely (contains sensitive data)" -ForegroundColor Yellow+ Write-Host " 2. Encrypt dump files before transferring" -ForegroundColor Yellow+ Write-Host " 3. Delete dump files after analysis" -ForegroundColor Yellow+ if ($DumpType -eq 'LSASS') {+ Write-Host " 4. LSASS dumps may contain plaintext credentials!" -ForegroundColor Red+ Write-Host " 5. Use Mimikatz or pypykatz for credential extraction" -ForegroundColor Yellow+ }+ }+ else {+ Write-Host "`n[FAILED] Could not create memory dump" -ForegroundColor Red+ Write-Host "Possible reasons:" -ForegroundColor Yellow+ Write-Host " - Insufficient permissions (need SeDebugPrivilege or SYSTEM)" -ForegroundColor Yellow+ Write-Host " - Process is protected (PPL - Protected Process Light)" -ForegroundColor Yellow+ Write-Host " - Antivirus/EDR blocking the operation" -ForegroundColor Yellow+ Write-Host " - Insufficient disk space" -ForegroundColor Yellow++ if ($DumpType -eq 'LSASS') {+ Write-Host "`nFor LSASS dumps, try:" -ForegroundColor Cyan+ Write-Host " - Using ProcDump: procdump.exe -accepteula -ma lsass.exe lsass.dmp" -ForegroundColor Gray+ Write-Host " - Task Manager: Right-click lsass.exe > Create dump file" -ForegroundColor Gray+ Write-Host " - Run PowerShell as SYSTEM: psexec -s -i powershell.exe" -ForegroundColor Gray+ }+ }++ }+ catch {+ Write-Error "Error during memory dump: $_"+ $result.Success = $false+ $result.ErrorMessage = $_.Exception.Message+ }+ }++ end {+ return $result+ }+}\ No newline at end of filediff --git a/Forensics/Get-ArtifactCollection.ps1 b/Forensics/Get-ArtifactCollection.ps1new file mode 100644index 0000000..a12f743--- /dev/null+++ b/Forensics/Get-ArtifactCollection.ps1@@ -0,0 +1,528 @@+function Get-ArtifactCollection {+ <#+ .SYNOPSIS+ Collects comprehensive forensic artifacts from Windows systems+ .DESCRIPTION+ KAPE-style artifact collection tool that gathers system information,+ event logs, registry hives, browser history, execution artifacts,+ and other forensic evidence for incident response and investigation.+ .PARAMETER OutputPath+ Root path for artifact collection (default: C:\ForensicCollection)+ .PARAMETER CollectionProfile+ Predefined collection profile: Quick, Standard, Full, or Custom+ .PARAMETER IncludeEventLogs+ Collect Windows event logs+ .PARAMETER IncludeRegistry+ Collect registry hives+ .PARAMETER IncludeBrowserHistory+ Collect browser artifacts+ .PARAMETER IncludeExecutionArtifacts+ Collect prefetch, UserAssist, etc.+ .PARAMETER IncludeNetworkInfo+ Collect network configuration and connections+ .PARAMETER CompressOutput+ Create ZIP archive of collected artifacts+ .PARAMETER RemoveSource+ Remove original files after compression+ .EXAMPLE+ Get-ArtifactCollection -CollectionProfile Standard+ Get-ArtifactCollection -OutputPath "E:\Evidence" -CollectionProfile Full -CompressOutput+ .OUTPUTS+ PSCustomObject with collection results+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [string]$OutputPath = "C:\ForensicCollection",++ [Parameter()]+ [ValidateSet('Quick', 'Standard', 'Full', 'Custom')]+ [string]$CollectionProfile = 'Standard',++ [Parameter()]+ [switch]$IncludeEventLogs,++ [Parameter()]+ [switch]$IncludeRegistry,++ [Parameter()]+ [switch]$IncludeBrowserHistory,++ [Parameter()]+ [switch]$IncludeExecutionArtifacts,++ [Parameter()]+ [switch]$IncludeNetworkInfo,++ [Parameter()]+ [switch]$CompressOutput,++ [Parameter()]+ [switch]$RemoveSource+ )++ begin {+ Write-Host "========================================" -ForegroundColor Cyan+ Write-Host " FORENSIC ARTIFACT COLLECTION TOOL" -ForegroundColor Cyan+ Write-Host " KAPE-Style Evidence Gathering" -ForegroundColor Cyan+ Write-Host "========================================" -ForegroundColor Cyan+ Write-Host "Collection Profile: $CollectionProfile" -ForegroundColor Yellow+ Write-Host "Output Path: $OutputPath" -ForegroundColor Yellow+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ # Check admin privileges+ $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)++ if (-not $isAdmin) {+ Write-Warning "Administrator privileges recommended for complete collection!"+ }++ # Set collection flags based on profile+ switch ($CollectionProfile) {+ 'Quick' {+ $IncludeEventLogs = $false+ $IncludeRegistry = $false+ $IncludeBrowserHistory = $false+ $IncludeExecutionArtifacts = $true+ $IncludeNetworkInfo = $true+ }+ 'Standard' {+ $IncludeEventLogs = $true+ $IncludeRegistry = $false+ $IncludeBrowserHistory = $true+ $IncludeExecutionArtifacts = $true+ $IncludeNetworkInfo = $true+ }+ 'Full' {+ $IncludeEventLogs = $true+ $IncludeRegistry = $true+ $IncludeBrowserHistory = $true+ $IncludeExecutionArtifacts = $true+ $IncludeNetworkInfo = $true+ }+ }++ # Create collection structure+ $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"+ $collectionRoot = Join-Path $OutputPath "Collection_$timestamp"++ $paths = @{+ Root = $collectionRoot+ SystemInfo = Join-Path $collectionRoot "1_SystemInfo"+ EventLogs = Join-Path $collectionRoot "2_EventLogs"+ Registry = Join-Path $collectionRoot "3_Registry"+ FileSystem = Join-Path $collectionRoot "4_FileSystem"+ Browser = Join-Path $collectionRoot "5_Browser"+ Network = Join-Path $collectionRoot "6_Network"+ Execution = Join-Path $collectionRoot "7_Execution"+ Users = Join-Path $collectionRoot "8_Users"+ }++ foreach ($path in $paths.Values) {+ if (-not (Test-Path $path)) {+ New-Item -Path $path -ItemType Directory -Force | Out-Null+ }+ }++ Write-Host "Collection directory created: $collectionRoot" -ForegroundColor Green++ $results = [PSCustomObject]@{+ CollectionDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ Profile = $CollectionProfile+ OutputPath = $collectionRoot+ ArtifactsCollected = @()+ Summary = @{+ TotalFiles = 0+ TotalSize = 0+ Errors = 0+ }+ CompressedArchive = $null+ }+ }++ process {+ try {+ # 1. COLLECT SYSTEM INFORMATION+ Write-Host "`n[1/8] Collecting System Information..." -ForegroundColor Cyan++ try {+ # Computer info+ $computerInfo = Get-ComputerInfo -ErrorAction SilentlyContinue+ $computerInfo | ConvertTo-Json -Depth 5 | Out-File (Join-Path $paths.SystemInfo "ComputerInfo.json")++ # OS Info+ Get-CimInstance Win32_OperatingSystem |+ Select-Object Caption, Version, BuildNumber, OSArchitecture, InstallDate, LastBootUpTime |+ ConvertTo-Json | Out-File (Join-Path $paths.SystemInfo "OSInfo.json")++ # Hardware Info+ Get-CimInstance Win32_ComputerSystem |+ Select-Object Manufacturer, Model, TotalPhysicalMemory, NumberOfProcessors |+ ConvertTo-Json | Out-File (Join-Path $paths.SystemInfo "Hardware.json")++ # Disk Info+ Get-PSDrive -PSProvider FileSystem |+ Select-Object Name, Used, Free, @{N='TotalGB';E={[Math]::Round($_.Used/1GB + $_.Free/1GB,2)}} |+ ConvertTo-Json | Out-File (Join-Path $paths.SystemInfo "Disks.json")++ # Installed Software+ Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* -ErrorAction SilentlyContinue |+ Select-Object DisplayName, DisplayVersion, Publisher, InstallDate |+ Where-Object { $_.DisplayName } |+ ConvertTo-Json | Out-File (Join-Path $paths.SystemInfo "InstalledSoftware.json")++ # Environment Variables+ Get-ChildItem Env: | ConvertTo-Json | Out-File (Join-Path $paths.SystemInfo "Environment.json")++ Write-Host " System information collected" -ForegroundColor Green+ $results.ArtifactsCollected += "System Information"+ }+ catch {+ Write-Warning "Error collecting system info: $_"+ $results.Summary.Errors+++ }++ # 2. COLLECT EVENT LOGS+ if ($IncludeEventLogs) {+ Write-Host "`n[2/8] Collecting Event Logs..." -ForegroundColor Cyan++ $logNames = @('Security', 'System', 'Application', 'Microsoft-Windows-PowerShell/Operational')++ foreach ($logName in $logNames) {+ try {+ Write-Host " Exporting: $logName..." -ForegroundColor Gray++ $safeName = $logName -replace '/', '-'+ $logPath = Join-Path $paths.EventLogs "$safeName.evtx"++ # Export using wevtutil+ wevtutil epl $logName $logPath /ow:true 2>&1 | Out-Null++ if (Test-Path $logPath) {+ Write-Host " Exported successfully" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Could not export log $logName"+ }+ }++ $results.ArtifactsCollected += "Event Logs"+ }++ # 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'}+ )++ foreach ($key in $registryKeys) {+ 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+ }+ 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+ }+ }+ catch {+ Write-Warning "Could not export registry key: $($key.Name)"+ }+ }++ $results.ArtifactsCollected += "Registry Hives"+ }+ catch {+ Write-Warning "Error collecting registry: $_"+ $results.Summary.Errors+++ }+ }++ # 4. COLLECT FILE SYSTEM ARTIFACTS+ Write-Host "`n[4/8] Collecting File System Artifacts..." -ForegroundColor Cyan++ try {+ # Prefetch files+ $prefetchPath = "$env:SystemRoot\Prefetch"+ if (Test-Path $prefetchPath) {+ $prefetchDest = Join-Path $paths.FileSystem "Prefetch"+ New-Item -Path $prefetchDest -ItemType Directory -Force | Out-Null+ Copy-Item "$prefetchPath\*.pf" -Destination $prefetchDest -Force -ErrorAction SilentlyContinue+ Write-Host " Prefetch files collected" -ForegroundColor Green+ }++ # Recent files+ $recentPath = "$env:APPDATA\Microsoft\Windows\Recent"+ if (Test-Path $recentPath) {+ $recentDest = Join-Path $paths.FileSystem "Recent"+ New-Item -Path $recentDest -ItemType Directory -Force | Out-Null+ Copy-Item "$recentPath\*" -Destination $recentDest -Force -Recurse -ErrorAction SilentlyContinue+ Write-Host " Recent files collected" -ForegroundColor Green+ }++ $results.ArtifactsCollected += "File System Artifacts"+ }+ catch {+ Write-Warning "Error collecting file system artifacts: $_"+ $results.Summary.Errors+++ }++ # 5. COLLECT BROWSER ARTIFACTS+ if ($IncludeBrowserHistory) {+ Write-Host "`n[5/8] Collecting Browser Artifacts..." -ForegroundColor Cyan++ try {+ # Chrome+ $chromePath = "$env:LOCALAPPDATA\Google\Chrome\User Data\Default"+ if (Test-Path $chromePath) {+ $chromeDest = Join-Path $paths.Browser "Chrome"+ New-Item -Path $chromeDest -ItemType Directory -Force | Out-Null++ # Copy History, Cookies, etc.+ $chromeFiles = @('History', 'Cookies', 'Web Data', 'Login Data')+ foreach ($file in $chromeFiles) {+ $srcFile = Join-Path $chromePath $file+ if (Test-Path $srcFile) {+ Copy-Item $srcFile -Destination $chromeDest -Force -ErrorAction SilentlyContinue+ }+ }+ Write-Host " Chrome artifacts collected" -ForegroundColor Green+ }++ # Edge+ $edgePath = "$env:LOCALAPPDATA\Microsoft\Edge\User Data\Default"+ if (Test-Path $edgePath) {+ $edgeDest = Join-Path $paths.Browser "Edge"+ New-Item -Path $edgeDest -ItemType Directory -Force | Out-Null++ $edgeFiles = @('History', 'Cookies', 'Web Data')+ foreach ($file in $edgeFiles) {+ $srcFile = Join-Path $edgePath $file+ if (Test-Path $srcFile) {+ Copy-Item $srcFile -Destination $edgeDest -Force -ErrorAction SilentlyContinue+ }+ }+ Write-Host " Edge artifacts collected" -ForegroundColor Green+ }++ $results.ArtifactsCollected += "Browser Artifacts"+ }+ catch {+ Write-Warning "Error collecting browser artifacts: $_"+ $results.Summary.Errors+++ }+ }++ # 6. COLLECT NETWORK INFORMATION+ if ($IncludeNetworkInfo) {+ Write-Host "`n[6/8] Collecting Network Information..." -ForegroundColor Cyan++ try {+ # Network adapters+ Get-NetAdapter | ConvertTo-Json | Out-File (Join-Path $paths.Network "Adapters.json")++ # IP configuration+ ipconfig /all | Out-File (Join-Path $paths.Network "ipconfig.txt")++ # Routing table+ route print | Out-File (Join-Path $paths.Network "routes.txt")++ # ARP cache+ arp -a | Out-File (Join-Path $paths.Network "arp.txt")++ # DNS cache+ ipconfig /displaydns | Out-File (Join-Path $paths.Network "dns_cache.txt")++ # Active connections+ Get-NetTCPConnection | ConvertTo-Json | Out-File (Join-Path $paths.Network "tcp_connections.json")++ # Listening ports+ netstat -ano | Out-File (Join-Path $paths.Network "netstat.txt")++ # Network shares+ net share | Out-File (Join-Path $paths.Network "shares.txt")++ Write-Host " Network information collected" -ForegroundColor Green+ $results.ArtifactsCollected += "Network Information"+ }+ catch {+ Write-Warning "Error collecting network info: $_"+ $results.Summary.Errors+++ }+ }++ # 7. COLLECT EXECUTION ARTIFACTS+ if ($IncludeExecutionArtifacts) {+ Write-Host "`n[7/8] Collecting Execution Artifacts..." -ForegroundColor Cyan++ try {+ # Running processes+ Get-Process | Select-Object Name, Id, Path, StartTime, @{N='WorkingSetMB';E={[Math]::Round($_.WorkingSet/1MB,2)}} |+ ConvertTo-Json | Out-File (Join-Path $paths.Execution "Processes.json")++ # Services+ Get-Service | Select-Object Name, DisplayName, Status, StartType |+ ConvertTo-Json | Out-File (Join-Path $paths.Execution "Services.json")++ # Scheduled tasks+ Get-ScheduledTask | Select-Object TaskName, TaskPath, State, @{N='LastRunTime';E={$_.LastRunTime}} |+ ConvertTo-Json | Out-File (Join-Path $paths.Execution "ScheduledTasks.json")++ # Startup programs+ Get-CimInstance Win32_StartupCommand |+ Select-Object Name, Command, Location, User |+ ConvertTo-Json | Out-File (Join-Path $paths.Execution "StartupPrograms.json")++ Write-Host " Execution artifacts collected" -ForegroundColor Green+ $results.ArtifactsCollected += "Execution Artifacts"+ }+ catch {+ Write-Warning "Error collecting execution artifacts: $_"+ $results.Summary.Errors+++ }+ }++ # 8. COLLECT USER INFORMATION+ Write-Host "`n[8/8] Collecting User Information..." -ForegroundColor Cyan++ try {+ # Local users+ Get-LocalUser | Select-Object Name, Enabled, LastLogon, PasswordLastSet |+ ConvertTo-Json | Out-File (Join-Path $paths.Users "LocalUsers.json")++ # Local groups+ Get-LocalGroup | ConvertTo-Json | Out-File (Join-Path $paths.Users "LocalGroups.json")++ # Logged on users+ quser 2>&1 | Out-File (Join-Path $paths.Users "LoggedOnUsers.txt")++ # User profiles+ Get-ChildItem "C:\Users" -Directory -ErrorAction SilentlyContinue |+ Select-Object Name, CreationTime, LastWriteTime |+ ConvertTo-Json | Out-File (Join-Path $paths.Users "UserProfiles.json")++ Write-Host " User information collected" -ForegroundColor Green+ $results.ArtifactsCollected += "User Information"+ }+ catch {+ Write-Warning "Error collecting user info: $_"+ $results.Summary.Errors+++ }++ # 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++ $totalSizeMB = [Math]::Round($results.Summary.TotalSize / 1MB, 2)+ Write-Host " Total Files: $($results.Summary.TotalFiles)" -ForegroundColor Green+ Write-Host " Total Size: $totalSizeMB MB" -ForegroundColor Green++ # CREATE COLLECTION MANIFEST+ $manifest = @{+ CollectionDate = $results.CollectionDate+ ComputerName = $results.ComputerName+ Profile = $results.Profile+ Collector = $env:USERNAME+ ArtifactsCollected = $results.ArtifactsCollected+ TotalFiles = $results.Summary.TotalFiles+ TotalSizeMB = $totalSizeMB+ Errors = $results.Summary.Errors+ }++ $manifest | ConvertTo-Json -Depth 5 | Out-File (Join-Path $collectionRoot "MANIFEST.json")+ Write-Host "`nCollection manifest created" -ForegroundColor Green++ # COMPRESS OUTPUT+ if ($CompressOutput) {+ Write-Host "`n[*] Compressing collection..." -ForegroundColor Cyan++ try {+ $zipPath = "$collectionRoot.zip"++ Compress-Archive -Path $collectionRoot -DestinationPath $zipPath -CompressionLevel Optimal++ if (Test-Path $zipPath) {+ $zipFile = Get-Item $zipPath+ $zipSizeMB = [Math]::Round($zipFile.Length / 1MB, 2)+ $compressionRatio = [Math]::Round((1 - ($zipFile.Length / $results.Summary.TotalSize)) * 100, 1)++ Write-Host " Archive created: $zipPath" -ForegroundColor Green+ Write-Host " Compressed Size: $zipSizeMB MB" -ForegroundColor Cyan+ Write-Host " Compression Ratio: $compressionRatio%" -ForegroundColor Cyan++ $results.CompressedArchive = $zipPath++ # Remove source if requested+ if ($RemoveSource) {+ Remove-Item $collectionRoot -Recurse -Force+ Write-Host " Original collection removed" -ForegroundColor Gray+ }+ }+ }+ catch {+ Write-Warning "Compression failed: $_"+ }+ }++ }+ catch {+ Write-Error "Error during artifact collection: $_"+ throw+ }+ }++ end {+ Write-Host "`n========================================" -ForegroundColor Green+ Write-Host " FORENSIC COLLECTION COMPLETE" -ForegroundColor Green+ Write-Host "========================================" -ForegroundColor Green++ Write-Host "`nCollection Summary:" -ForegroundColor Cyan+ Write-Host " Computer: $($results.ComputerName)" -ForegroundColor White+ Write-Host " Profile: $($results.Profile)" -ForegroundColor White+ Write-Host " Output Path: $($results.OutputPath)" -ForegroundColor White+ Write-Host " Total Files: $($results.Summary.TotalFiles)" -ForegroundColor White+ Write-Host " Total Size: $([Math]::Round($results.Summary.TotalSize/1MB,2)) MB" -ForegroundColor White+ Write-Host " Errors: $($results.Summary.Errors)" -ForegroundColor $(if($results.Summary.Errors -gt 0){'Yellow'}else{'White'})++ if ($results.CompressedArchive) {+ Write-Host " Archive: $($results.CompressedArchive)" -ForegroundColor Green+ }++ Write-Host "`nArtifacts Collected:" -ForegroundColor Cyan+ foreach ($artifact in $results.ArtifactsCollected) {+ Write-Host " - $artifact" -ForegroundColor Green+ }++ Write-Host "`nNext Steps:" -ForegroundColor Yellow+ 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++ return $results+ }+}\ No newline at end of filediff --git a/Forensics/Get-ExecutionArtifacts.ps1 b/Forensics/Get-ExecutionArtifacts.ps1new file mode 100644index 0000000..7d40bc9--- /dev/null+++ b/Forensics/Get-ExecutionArtifacts.ps1@@ -0,0 +1,560 @@+function Get-ExecutionArtifacts {+ <#+ .SYNOPSIS+ Extracts program execution artifacts from Windows forensic sources+ .DESCRIPTION+ Analyzes Prefetch files, UserAssist registry, ShimCache, RecentApps, and+ BAM/DAM for comprehensive program execution history. Critical for incident+ response and forensic investigations.+ .PARAMETER IncludePrefetch+ Parse Windows Prefetch files+ .PARAMETER IncludeUserAssist+ Extract UserAssist registry entries+ .PARAMETER IncludeShimCache+ Parse Application Compatibility Cache (ShimCache)+ .PARAMETER IncludeRecentApps+ Include recent applications from registry+ .PARAMETER IncludeBAM+ Parse Background Activity Moderator (Windows 10+)+ .PARAMETER OutputPath+ Path to save execution artifacts report+ .PARAMETER Format+ Report format: HTML, JSON, CSV, or All+ .EXAMPLE+ Get-ExecutionArtifacts+ Get-ExecutionArtifacts -IncludePrefetch -IncludeUserAssist -OutputPath "C:\Forensics"+ .OUTPUTS+ PSCustomObject with execution artifacts+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$IncludePrefetch,++ [Parameter()]+ [switch]$IncludeUserAssist,++ [Parameter()]+ [switch]$IncludeShimCache,++ [Parameter()]+ [switch]$IncludeRecentApps,++ [Parameter()]+ [switch]$IncludeBAM,++ [Parameter()]+ [string]$OutputPath,++ [Parameter()]+ [ValidateSet('HTML', 'JSON', 'CSV', 'All')]+ [string]$Format = 'HTML'+ )++ begin {+ Write-Host "=== EXECUTION ARTIFACTS ANALYSIS ===" -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+ Artifacts = @()+ Summary = @{+ TotalArtifacts = 0+ Prefetch = 0+ UserAssist = 0+ ShimCache = 0+ RecentApps = 0+ BAM = 0+ }+ }++ # If no specific sources selected, include common ones+ if (-not ($IncludePrefetch -or $IncludeUserAssist -or $IncludeShimCache -or $IncludeRecentApps -or $IncludeBAM)) {+ $IncludePrefetch = $true+ $IncludeUserAssist = $true+ $IncludeRecentApps = $true+ $IncludeBAM = $true+ Write-Host "No specific sources selected - including Prefetch, UserAssist, RecentApps, and BAM" -ForegroundColor Gray+ }+ }++ process {+ try {+ # 1. PARSE PREFETCH FILES+ if ($IncludePrefetch) {+ Write-Host "`n[1/5] Analyzing Prefetch files..." -ForegroundColor Cyan++ try {+ $prefetchPath = "$env:SystemRoot\Prefetch"++ if (Test-Path $prefetchPath) {+ $prefetchFiles = Get-ChildItem -Path $prefetchPath -Filter "*.pf" -ErrorAction SilentlyContinue++ foreach ($file in $prefetchFiles) {+ # Extract executable name from prefetch filename (format: EXECUTABLE-HASH.pf)+ $executableName = ($file.BaseName -split '-')[0]++ $results.Artifacts += [PSCustomObject]@{+ Source = 'Prefetch'+ ExecutableName = "$executableName.exe"+ FullPath = $null+ Timestamp = $file.LastWriteTime+ TimestampType = 'Last Executed (Approximate)'+ Details = @{+ PrefetchFile = $file.Name+ FilePath = $file.FullName+ FileSize = $file.Length+ Created = $file.CreationTime+ }+ }++ $results.Summary.Prefetch+++ }++ Write-Host " Found $($prefetchFiles.Count) Prefetch files" -ForegroundColor Green+ }+ else {+ Write-Host " Prefetch folder not found (may be disabled)" -ForegroundColor Gray+ }+ }+ catch {+ Write-Warning "Could not parse Prefetch files - $_"+ }+ }++ # 2. PARSE USERASSIST REGISTRY+ if ($IncludeUserAssist) {+ Write-Host "`n[2/5] Analyzing UserAssist registry..." -ForegroundColor Cyan++ try {+ # UserAssist is per-user, so check current user+ $userAssistPath = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\UserAssist'++ if (Test-Path $userAssistPath) {+ $guids = Get-ChildItem -Path $userAssistPath -ErrorAction SilentlyContinue++ foreach ($guid in $guids) {+ $countPath = Join-Path $guid.PSPath 'Count'++ if (Test-Path $countPath) {+ $entries = Get-Item -Path $countPath -ErrorAction SilentlyContinue |+ Select-Object -ExpandProperty Property++ foreach ($entry in $entries) {+ try {+ # Decode ROT13 encoded entry name+ $decodedName = ConvertFrom-ROT13 -Text $entry++ # Get execution data+ $value = Get-ItemProperty -Path $countPath -Name $entry -ErrorAction SilentlyContinue++ # Skip if not an executable path+ if ($decodedName -notmatch '\.(exe|bat|cmd|ps1|vbs|js)') {+ continue+ }++ $results.Artifacts += [PSCustomObject]@{+ Source = 'UserAssist'+ ExecutableName = Split-Path -Path $decodedName -Leaf+ FullPath = $decodedName+ Timestamp = Get-Date # UserAssist timestamp parsing is complex, using current time+ TimestampType = 'Tracked'+ Details = @{+ EncodedName = $entry+ DecodedPath = $decodedName+ }+ }++ $results.Summary.UserAssist+++ }+ catch {+ Write-Verbose "Could not decode UserAssist entry: $entry"+ }+ }+ }+ }++ Write-Host " Found $($results.Summary.UserAssist) UserAssist entries" -ForegroundColor Green+ }+ else {+ Write-Host " UserAssist registry not found" -ForegroundColor Gray+ }+ }+ catch {+ Write-Warning "Could not parse UserAssist - $_"+ }+ }++ # 3. PARSE SHIMCACHE+ if ($IncludeShimCache) {+ Write-Host "`n[3/5] Analyzing ShimCache (Application Compatibility)..." -ForegroundColor Cyan++ try {+ # ShimCache location+ $shimCachePath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\AppCompatCache'++ if (Test-Path $shimCachePath) {+ # ShimCache data is binary and complex to parse+ # This is a simplified approach - full parsing requires binary analysis+ $shimData = Get-ItemProperty -Path $shimCachePath -Name AppCompatCache -ErrorAction SilentlyContinue++ if ($shimData) {+ Write-Host " ShimCache data found (binary parsing not implemented)" -ForegroundColor Gray+ Write-Host " Note: Full ShimCache parsing requires specialized tools like ShimCacheParser" -ForegroundColor Yellow++ $results.Artifacts += [PSCustomObject]@{+ Source = 'ShimCache'+ ExecutableName = 'ShimCache Binary Data'+ FullPath = $shimCachePath+ Timestamp = Get-Date+ TimestampType = 'Registry Key'+ Details = @{+ Note = 'Binary data present - use ShimCacheParser.exe for full analysis'+ DataSize = $shimData.AppCompatCache.Length+ }+ }++ $results.Summary.ShimCache+++ }+ }+ else {+ Write-Host " ShimCache registry not found" -ForegroundColor Gray+ }+ }+ catch {+ Write-Warning "Could not access ShimCache - $_"+ }+ }++ # 4. PARSE RECENT APPS+ if ($IncludeRecentApps) {+ Write-Host "`n[4/5] Analyzing Recent Applications..." -ForegroundColor Cyan++ try {+ # Check multiple recent app locations+ $recentPaths = @(+ 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Search\RecentApps',+ 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FeatureUsage\AppSwitched'+ )++ foreach ($path in $recentPaths) {+ if (Test-Path $path) {+ $apps = Get-ChildItem -Path $path -ErrorAction SilentlyContinue++ foreach ($app in $apps) {+ try {+ $props = Get-ItemProperty -Path $app.PSPath -ErrorAction SilentlyContinue++ # Extract app path if available+ $appPath = $null+ $appName = $app.PSChildName++ if ($props.PSObject.Properties.Name -contains 'AppPath') {+ $appPath = $props.AppPath+ $appName = Split-Path -Path $appPath -Leaf+ }+ elseif ($props.PSObject.Properties.Name -contains 'RecentItems') {+ $appPath = $props.RecentItems+ }++ if ($appName -or $appPath) {+ $results.Artifacts += [PSCustomObject]@{+ Source = 'RecentApps'+ ExecutableName = $appName+ FullPath = $appPath+ Timestamp = Get-Date+ TimestampType = 'Recent Activity'+ Details = @{+ RegistryPath = $app.PSPath+ }+ }++ $results.Summary.RecentApps+++ }+ }+ catch {+ Write-Verbose "Could not read recent app: $($app.PSPath)"+ }+ }+ }+ }++ Write-Host " Found $($results.Summary.RecentApps) recent applications" -ForegroundColor Green+ }+ catch {+ Write-Warning "Could not parse recent apps - $_"+ }+ }++ # 5. PARSE BAM/DAM (Background Activity Moderator)+ if ($IncludeBAM) {+ Write-Host "`n[5/5] Analyzing BAM/DAM (Background Activity Moderator)..." -ForegroundColor Cyan++ try {+ # BAM location (Windows 10 1709+)+ $bamPath = 'HKLM:\SYSTEM\CurrentControlSet\Services\bam\State\UserSettings'++ if (Test-Path $bamPath) {+ $users = Get-ChildItem -Path $bamPath -ErrorAction SilentlyContinue++ foreach ($user in $users) {+ $entries = Get-ItemProperty -Path $user.PSPath -ErrorAction SilentlyContinue++ foreach ($property in $entries.PSObject.Properties) {+ # Skip non-path properties+ if ($property.Name -like 'PS*' -or $property.Name -eq 'SequenceNumber') {+ continue+ }++ $execPath = $property.Name++ # Extract timestamp from binary data (simplified)+ $timestamp = Get-Date # Full parsing requires binary conversion++ if ($execPath -match '\.(exe|bat|cmd|ps1)$') {+ $results.Artifacts += [PSCustomObject]@{+ Source = 'BAM'+ ExecutableName = Split-Path -Path $execPath -Leaf+ FullPath = $execPath+ Timestamp = $timestamp+ TimestampType = 'Last Execution (BAM)'+ Details = @{+ UserSID = Split-Path -Path $user.PSPath -Leaf+ }+ }++ $results.Summary.BAM+++ }+ }+ }++ Write-Host " Found $($results.Summary.BAM) BAM entries" -ForegroundColor Green+ }+ else {+ # Try DAM (older Windows 10)+ $damPath = 'HKLM:\SYSTEM\CurrentControlSet\Services\dam\State\UserSettings'++ if (Test-Path $damPath) {+ Write-Host " DAM found (older Windows 10 version)" -ForegroundColor Gray+ # Similar parsing as BAM+ }+ else {+ Write-Host " BAM/DAM not available (Windows 10 1709+ required)" -ForegroundColor Gray+ }+ }+ }+ catch {+ Write-Warning "Could not parse BAM/DAM - $_"+ }+ }++ # FINALIZE+ $results.Summary.TotalArtifacts = $results.Artifacts.Count++ # Sort artifacts by timestamp+ $results.Artifacts = $results.Artifacts |+ Sort-Object Timestamp -Descending++ # 6. EXPORT REPORTS+ if ($OutputPath) {+ Write-Host "`n[*] Exporting execution artifacts..." -ForegroundColor Cyan++ if (-not (Test-Path $OutputPath)) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ }++ $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"+ $reportName = "ExecutionArtifacts_$timestamp"++ # Export JSON+ if ($Format -in @('JSON', 'All')) {+ $jsonPath = Join-Path $OutputPath "$reportName.json"+ $results | ConvertTo-Json -Depth 10 | Out-File $jsonPath -Encoding UTF8+ Write-Host " JSON report saved: $jsonPath" -ForegroundColor Green+ }++ # Export CSV+ if ($Format -in @('CSV', 'All')) {+ $csvPath = Join-Path $OutputPath "$reportName.csv"+ $results.Artifacts | Select-Object Source, ExecutableName, FullPath, Timestamp, TimestampType |+ Export-Csv $csvPath -NoTypeInformation+ Write-Host " CSV report saved: $csvPath" -ForegroundColor Green+ }++ # Export HTML+ if ($Format -in @('HTML', 'All')) {+ $htmlPath = Join-Path $OutputPath "$reportName.html"+ $html = Generate-ExecutionArtifactsHTML -Results $results+ $html | Out-File $htmlPath -Encoding UTF8+ Write-Host " HTML report saved: $htmlPath" -ForegroundColor Green+ }+ }++ }+ catch {+ Write-Error "Error during execution artifacts analysis - $_"+ throw+ }+ }++ end {+ Write-Host "`n=== EXECUTION ARTIFACTS ANALYSIS COMPLETE ===" -ForegroundColor Green++ Write-Host "`nSummary:" -ForegroundColor Cyan+ Write-Host " Total Artifacts: $($results.Summary.TotalArtifacts)" -ForegroundColor White+ Write-Host " Prefetch Files: $($results.Summary.Prefetch)" -ForegroundColor Gray+ Write-Host " UserAssist Entries: $($results.Summary.UserAssist)" -ForegroundColor Gray+ Write-Host " ShimCache Entries: $($results.Summary.ShimCache)" -ForegroundColor Gray+ Write-Host " Recent Apps: $($results.Summary.RecentApps)" -ForegroundColor Gray+ Write-Host " BAM Entries: $($results.Summary.BAM)" -ForegroundColor Gray++ if ($results.Artifacts.Count -gt 0) {+ Write-Host "`nRecent Executions:" -ForegroundColor Cyan+ $results.Artifacts |+ Where-Object { $_.ExecutableName -notlike 'ShimCache*' } |+ Select-Object -First 15 |+ ForEach-Object {+ $timestamp = $_.Timestamp.ToString('yyyy-MM-dd HH:mm:ss')+ $color = switch ($_.Source) {+ 'Prefetch' { 'Cyan' }+ 'UserAssist' { 'Yellow' }+ 'BAM' { 'Green' }+ 'RecentApps' { 'Magenta' }+ default { 'White' }+ }+ Write-Host " [$timestamp] [$($_.Source)] $($_.ExecutableName)" -ForegroundColor $color+ }+ }++ return $results+ }+}++# Helper function to decode ROT13 (used by UserAssist)+function ConvertFrom-ROT13 {+ param([string]$Text)++ $result = ""+ foreach ($char in $Text.ToCharArray()) {+ if ($char -match '[A-Za-z]') {+ $base = if ($char -match '[A-Z]') { 65 } else { 97 }+ $result += [char](($([int]$char - $base + 13) % 26) + $base)+ }+ else {+ $result += $char+ }+ }+ return $result+}++# Helper function to generate HTML report+function Generate-ExecutionArtifactsHTML {+ param($Results)++ $html = @"+<!DOCTYPE html>+<html>+<head>+ <title>Execution Artifacts - $($Results.ComputerName)</title>+ <style>+ body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }+ .container { max-width: 1600px; margin: 0 auto; background: white; padding: 30px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }+ h1 { color: #2c3e50; border-bottom: 3px solid #e74c3c; padding-bottom: 10px; }+ h2 { color: #34495e; margin-top: 30px; }+ .summary { background: #ecf0f1; padding: 20px; border-radius: 5px; margin: 20px 0; }+ .metric { display: inline-block; margin: 10px 30px 10px 0; }+ .metric-label { font-weight: bold; color: #7f8c8d; }+ .metric-value { font-size: 24px; font-weight: bold; color: #e74c3c; }+ table { width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 13px; }+ th { background: #e74c3c; color: white; padding: 10px; text-align: left; }+ td { padding: 8px; border-bottom: 1px solid #ddd; vertical-align: top; }+ tr:hover { background: #f8f9fa; }+ .source-badge { padding: 3px 8px; border-radius: 3px; font-size: 11px; font-weight: bold; color: white; }+ .source-prefetch { background: #3498db; }+ .source-userassist { background: #f39c12; }+ .source-shimcache { background: #9b59b6; }+ .source-recentapps { background: #e91e63; }+ .source-bam { background: #27ae60; }+ .footer { margin-top: 40px; padding-top: 20px; border-top: 1px solid #ddd; color: #7f8c8d; font-size: 12px; }+ .path { font-family: monospace; font-size: 11px; color: #7f8c8d; }+ </style>+</head>+<body>+ <div class="container">+ <h1>⚡ Program Execution Artifacts</h1>+ <p><strong>Computer:</strong> $($Results.ComputerName) | <strong>Scan Date:</strong> $($Results.ScanDate)</p>++ <div class="summary">+ <h2>Summary</h2>+ <div class="metric">+ <div class="metric-label">Total Artifacts</div>+ <div class="metric-value">$($Results.Summary.TotalArtifacts)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Prefetch</div>+ <div class="metric-value">$($Results.Summary.Prefetch)</div>+ </div>+ <div class="metric">+ <div class="metric-label">UserAssist</div>+ <div class="metric-value">$($Results.Summary.UserAssist)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Recent Apps</div>+ <div class="metric-value">$($Results.Summary.RecentApps)</div>+ </div>+ <div class="metric">+ <div class="metric-label">BAM</div>+ <div class="metric-value">$($Results.Summary.BAM)</div>+ </div>+ </div>++ <h2>Execution History</h2>+ <table>+ <tr>+ <th style="width: 80px;">Source</th>+ <th style="width: 200px;">Executable</th>+ <th>Full Path</th>+ <th style="width: 150px;">Timestamp</th>+ <th style="width: 150px;">Type</th>+ </tr>+"@++ foreach ($artifact in $Results.Artifacts) {+ $sourceClass = "source-$($artifact.Source.ToLower())"+ $timestamp = $artifact.Timestamp.ToString('yyyy-MM-dd HH:mm:ss')+ $fullPath = if ($artifact.FullPath) {+ $artifact.FullPath -replace '<', '<' -replace '>', '>'+ } else {+ 'N/A'+ }++ $html += @"+ <tr>+ <td><span class="source-badge $sourceClass">$($artifact.Source)</span></td>+ <td><strong>$($artifact.ExecutableName)</strong></td>+ <td><span class="path">$fullPath</span></td>+ <td>$timestamp</td>+ <td><small>$($artifact.TimestampType)</small></td>+ </tr>+"@+ }++ $html += " </table>`n"++ $currentDate = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'++ $html += @"++ <div class="footer">+ Generated by WindowsSecurityAudit Module | Execution Artifacts Analysis | $currentDate+ <br><strong>Note:</strong> ShimCache requires specialized binary parsing tools for full analysis+ </div>+ </div>+</body>+</html>+"@++ return $html+}\ No newline at end of filediff --git a/Forensics/Get-USBHistory.ps1 b/Forensics/Get-USBHistory.ps1new file mode 100644index 0000000..fff335c--- /dev/null+++ b/Forensics/Get-USBHistory.ps1@@ -0,0 +1,496 @@+function Get-USBHistory {+ <#+ .SYNOPSIS+ Retrieves USB device connection history from Windows artifacts+ .DESCRIPTION+ Analyzes registry, event logs, and setup logs to identify all USB devices+ that have been connected to the system, including timestamps, serial numbers,+ vendor information, and last connection times.+ .PARAMETER IncludeEventLogs+ Include event log analysis for USB connection/disconnection events+ .PARAMETER IncludeSetupAPI+ Parse SetupAPI.dev.log for detailed device installation history+ .PARAMETER DaysBack+ Number of days to look back in event logs (default: 30)+ .PARAMETER OutputPath+ Path to save USB history report+ .PARAMETER Format+ Report format: HTML, JSON, CSV, or All+ .EXAMPLE+ Get-USBHistory+ Get-USBHistory -IncludeEventLogs -IncludeSetupAPI -OutputPath "C:\Forensics"+ .OUTPUTS+ PSCustomObject with USB device history+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$IncludeEventLogs,++ [Parameter()]+ [switch]$IncludeSetupAPI,++ [Parameter()]+ [int]$DaysBack = 30,++ [Parameter()]+ [string]$OutputPath,++ [Parameter()]+ [ValidateSet('HTML', 'JSON', 'CSV', 'All')]+ [string]$Format = 'HTML'+ )++ begin {+ Write-Host "=== USB DEVICE HISTORY ANALYSIS ===" -ForegroundColor Cyan+ Write-Host "Scan Date: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow+ Write-Host "Include Event Logs: $(if($IncludeEventLogs){'Yes'}else{'No'})" -ForegroundColor Yellow+ Write-Host "Include SetupAPI: $(if($IncludeSetupAPI){'Yes'}else{'No'})" -ForegroundColor Yellow++ $results = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ USBDevices = @()+ ConnectionEvents = @()+ Summary = @{+ TotalDevices = 0+ StorageDevices = 0+ OtherDevices = 0+ RecentConnections = 0+ }+ }+ }++ process {+ try {+ # 1. ANALYZE REGISTRY - USBSTOR (USB Storage Devices)+ Write-Host "`n[1/4] Scanning USB storage devices from registry..." -ForegroundColor Cyan++ try {+ $usbStorPath = 'HKLM:\SYSTEM\CurrentControlSet\Enum\USBSTOR'++ if (Test-Path $usbStorPath) {+ $vendors = Get-ChildItem -Path $usbStorPath -ErrorAction SilentlyContinue++ foreach ($vendor in $vendors) {+ $devices = Get-ChildItem -Path $vendor.PSPath -ErrorAction SilentlyContinue++ foreach ($device in $devices) {+ try {+ $props = Get-ItemProperty -Path $device.PSPath -ErrorAction SilentlyContinue++ # Extract device information+ $friendlyName = if ($props.FriendlyName) { $props.FriendlyName } else { $vendor.PSChildName }+ $serialNumber = $device.PSChildName++ # Parse vendor string (e.g., "Disk&Ven_SanDisk&Prod_Ultra&Rev_1.00")+ $vendorName = if ($vendor.PSChildName -match 'Ven_([^&]+)') { $matches[1] } else { 'Unknown' }+ $productName = if ($vendor.PSChildName -match 'Prod_([^&]+)') { $matches[1] } else { 'Unknown' }+ $revision = if ($vendor.PSChildName -match 'Rev_([^&]+)') { $matches[1] } else { 'Unknown' }++ # FIXED: Try to get install date from registry properties+ $installDate = $null+ if ($props.PSObject.Properties.Name -contains 'InstallDate') {+ $installDate = $props.InstallDate+ }+ elseif ($props.PSObject.Properties.Name -contains 'FirstInstallDate') {+ $installDate = $props.FirstInstallDate+ }++ $deviceInfo = [PSCustomObject]@{+ Type = 'Storage'+ FriendlyName = $friendlyName+ Vendor = $vendorName+ Product = $productName+ Revision = $revision+ SerialNumber = $serialNumber+ FirstInstalled = $installDate+ LastConnected = $installDate+ RegistryPath = $device.PSPath+ }++ $results.USBDevices += $deviceInfo+ $results.Summary.StorageDevices++++ Write-Host " Found: $vendorName $productName (SN: $serialNumber)" -ForegroundColor Gray+ }+ catch {+ Write-Verbose "Could not read device: $($device.PSPath)"+ }+ }+ }+ }++ Write-Host " Total USB storage devices: $($results.Summary.StorageDevices)" -ForegroundColor Green+ }+ catch {+ Write-Warning "Could not access USBSTOR registry key - $_"+ }++ # 2. ANALYZE REGISTRY - USB (All USB Devices)+ Write-Host "`n[2/4] Scanning all USB devices from registry..." -ForegroundColor Cyan++ try {+ $usbPath = 'HKLM:\SYSTEM\CurrentControlSet\Enum\USB'++ if (Test-Path $usbPath) {+ $usbDevices = Get-ChildItem -Path $usbPath -ErrorAction SilentlyContinue++ foreach ($usbDevice in $usbDevices) {+ $instances = Get-ChildItem -Path $usbDevice.PSPath -ErrorAction SilentlyContinue++ foreach ($instance in $instances) {+ try {+ $props = Get-ItemProperty -Path $instance.PSPath -ErrorAction SilentlyContinue++ # Skip if already captured in USBSTOR+ $serialNumber = $instance.PSChildName+ $alreadyExists = $results.USBDevices | Where-Object { $_.SerialNumber -eq $serialNumber }++ if (-not $alreadyExists -and $props.FriendlyName) {+ # Parse VID/PID from device name (e.g., "VID_046D&PID_C52B")+ $vid = if ($usbDevice.PSChildName -match 'VID_([0-9A-F]+)') { $matches[1] } else { 'Unknown' }+ $pid = if ($usbDevice.PSChildName -match 'PID_([0-9A-F]+)') { $matches[1] } else { 'Unknown' }++ # FIXED: Safe timestamp retrieval from registry properties+ $installDate = $null+ try {+ if ($props.PSObject.Properties.Name -contains 'InstallDate') {+ $installDate = $props.InstallDate+ }+ elseif ($props.PSObject.Properties.Name -contains 'FirstInstallDate') {+ $installDate = $props.FirstInstallDate+ }+ }+ catch {+ # Timestamp not available+ }++ $deviceInfo = [PSCustomObject]@{+ Type = 'USB Device'+ FriendlyName = $props.FriendlyName+ Vendor = "VID_$vid"+ Product = "PID_$pid"+ Revision = 'N/A'+ SerialNumber = $serialNumber+ FirstInstalled = $installDate+ LastConnected = $installDate+ RegistryPath = $instance.PSPath+ }++ $results.USBDevices += $deviceInfo+ $results.Summary.OtherDevices++++ Write-Host " Found: $($props.FriendlyName) (VID_$vid PID_$pid)" -ForegroundColor Gray+ }+ }+ catch {+ Write-Verbose "Could not read USB device: $($instance.PSPath)"+ }+ }+ }+ }++ Write-Host " Total other USB devices: $($results.Summary.OtherDevices)" -ForegroundColor Green+ }+ catch {+ Write-Warning "Could not access USB registry key - $_"+ }++ # 3. ANALYZE EVENT LOGS+ if ($IncludeEventLogs) {+ Write-Host "`n[3/4] Analyzing USB connection events..." -ForegroundColor Cyan++ try {+ $startTime = (Get-Date).AddDays(-$DaysBack)++ # Event ID 2003 = Device connected, Event ID 20001 = First-time device installation+ $eventLogs = @(+ @{LogName='Microsoft-Windows-DriverFrameworks-UserMode/Operational'; ID=2003},+ @{LogName='System'; ID=20001}+ )++ foreach ($logConfig in $eventLogs) {+ try {+ $events = Get-WinEvent -FilterHashtable @{+ LogName = $logConfig.LogName+ ID = $logConfig.ID+ StartTime = $startTime+ } -ErrorAction SilentlyContinue -MaxEvents 500++ foreach ($event in $events) {+ $message = if ($event.Message) { $event.Message } else { "USB Event $($event.Id)" }++ $results.ConnectionEvents += [PSCustomObject]@{+ Timestamp = $event.TimeCreated+ EventID = $event.Id+ LogName = $logConfig.LogName+ Message = $message.Substring(0, [Math]::Min(200, $message.Length))+ }++ $results.Summary.RecentConnections+++ }+ }+ catch {+ Write-Verbose "Could not read log: $($logConfig.LogName)"+ }+ }++ Write-Host " Total connection events: $($results.Summary.RecentConnections)" -ForegroundColor Green+ }+ catch {+ Write-Warning "Could not analyze event logs - $_"+ }+ }+ else {+ Write-Host "`n[3/4] Skipping event log analysis (disabled)" -ForegroundColor Gray+ }++ # 4. PARSE SETUPAPI LOG+ if ($IncludeSetupAPI) {+ Write-Host "`n[4/4] Parsing SetupAPI device log..." -ForegroundColor Cyan++ try {+ $setupApiPath = "$env:SystemRoot\inf\setupapi.dev.log"++ if (Test-Path $setupApiPath) {+ $setupContent = Get-Content $setupApiPath -ErrorAction SilentlyContinue |+ Select-String -Pattern "USB|USBSTOR" -Context 0,2 |+ Select-Object -First 100++ $usbEntries = $setupContent.Count+ Write-Host " Found $usbEntries USB-related entries in SetupAPI log" -ForegroundColor Green++ # Store sample entries+ foreach ($entry in ($setupContent | Select-Object -First 10)) {+ $results.ConnectionEvents += [PSCustomObject]@{+ Timestamp = $null+ EventID = 'SetupAPI'+ LogName = 'setupapi.dev.log'+ Message = $entry.Line+ }+ }+ }+ else {+ Write-Host " SetupAPI log not found" -ForegroundColor Gray+ }+ }+ catch {+ Write-Warning "Could not parse SetupAPI log - $_"+ }+ }+ else {+ Write-Host "`n[4/4] Skipping SetupAPI parsing (disabled)" -ForegroundColor Gray+ }++ # FINALIZE+ $results.Summary.TotalDevices = $results.USBDevices.Count++ # Sort devices by last connection (those with dates first)+ $results.USBDevices = $results.USBDevices |+ Sort-Object @{Expression={if($_.LastConnected){$_.LastConnected}else{[DateTime]::MinValue}}; Descending=$true}++ # 5. EXPORT REPORTS+ if ($OutputPath) {+ Write-Host "`n[*] Exporting USB history reports..." -ForegroundColor Cyan++ if (-not (Test-Path $OutputPath)) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ }++ $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"+ $reportName = "USBHistory_$timestamp"++ # Export JSON+ if ($Format -in @('JSON', 'All')) {+ $jsonPath = Join-Path $OutputPath "$reportName.json"+ $results | ConvertTo-Json -Depth 10 | Out-File $jsonPath -Encoding UTF8+ Write-Host " JSON report saved: $jsonPath" -ForegroundColor Green+ }++ # Export CSV+ if ($Format -in @('CSV', 'All')) {+ $csvPath = Join-Path $OutputPath "$reportName.csv"+ $results.USBDevices | Export-Csv $csvPath -NoTypeInformation+ Write-Host " CSV report saved: $csvPath" -ForegroundColor Green+ }++ # Export HTML+ if ($Format -in @('HTML', 'All')) {+ $htmlPath = Join-Path $OutputPath "$reportName.html"+ $html = Generate-USBHistoryHTML -Results $results+ $html | Out-File $htmlPath -Encoding UTF8+ Write-Host " HTML report saved: $htmlPath" -ForegroundColor Green+ }+ }++ }+ catch {+ Write-Error "Error during USB history analysis - $_"+ throw+ }+ }++ end {+ Write-Host "`n=== USB HISTORY ANALYSIS COMPLETE ===" -ForegroundColor Green++ Write-Host "`nSummary:" -ForegroundColor Cyan+ Write-Host " Total USB Devices: $($results.Summary.TotalDevices)" -ForegroundColor White+ Write-Host " Storage Devices: $($results.Summary.StorageDevices)" -ForegroundColor Gray+ Write-Host " Other USB Devices: $($results.Summary.OtherDevices)" -ForegroundColor Gray++ if ($IncludeEventLogs) {+ Write-Host " Recent Connection Events: $($results.Summary.RecentConnections)" -ForegroundColor Gray+ }++ if ($results.USBDevices.Count -gt 0) {+ Write-Host "`nRecent USB Devices:" -ForegroundColor Cyan+ $results.USBDevices |+ Select-Object -First 10 |+ ForEach-Object {+ $lastConnected = if ($_.LastConnected) {+ $_.LastConnected.ToString('yyyy-MM-dd HH:mm:ss')+ } else {+ 'Unknown'+ }+ Write-Host " [$lastConnected] $($_.Vendor) $($_.Product) - $($_.FriendlyName)" -ForegroundColor Cyan+ }+ }++ return $results+ }+}++# Helper function to generate HTML report+function Generate-USBHistoryHTML {+ param($Results)++ $html = @"+<!DOCTYPE html>+<html>+<head>+ <title>USB Device History - $($Results.ComputerName)</title>+ <style>+ body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }+ .container { max-width: 1400px; margin: 0 auto; background: white; padding: 30px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }+ h1 { color: #2c3e50; border-bottom: 3px solid #3498db; padding-bottom: 10px; }+ h2 { color: #34495e; margin-top: 30px; }+ .summary { background: #ecf0f1; padding: 20px; border-radius: 5px; margin: 20px 0; }+ .metric { display: inline-block; margin: 10px 30px 10px 0; }+ .metric-label { font-weight: bold; color: #7f8c8d; }+ .metric-value { font-size: 24px; font-weight: bold; color: #3498db; }+ table { width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 14px; }+ th { background: #3498db; color: white; padding: 12px; text-align: left; }+ td { padding: 10px; border-bottom: 1px solid #ddd; vertical-align: top; }+ tr:hover { background: #f8f9fa; }+ .device-type { padding: 4px 8px; border-radius: 3px; font-size: 11px; font-weight: bold; color: white; }+ .type-storage { background: #27ae60; }+ .type-usb { background: #9b59b6; }+ .footer { margin-top: 40px; padding-top: 20px; border-top: 1px solid #ddd; color: #7f8c8d; font-size: 12px; }+ .serial { font-family: monospace; font-size: 11px; color: #7f8c8d; }+ </style>+</head>+<body>+ <div class="container">+ <h1>🔌 USB Device History Report</h1>+ <p><strong>Computer:</strong> $($Results.ComputerName) | <strong>Scan Date:</strong> $($Results.ScanDate)</p>++ <div class="summary">+ <h2>Summary</h2>+ <div class="metric">+ <div class="metric-label">Total Devices</div>+ <div class="metric-value">$($Results.Summary.TotalDevices)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Storage Devices</div>+ <div class="metric-value">$($Results.Summary.StorageDevices)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Other USB Devices</div>+ <div class="metric-value">$($Results.Summary.OtherDevices)</div>+ </div>+ </div>++ <h2>USB Devices</h2>+ <table>+ <tr>+ <th style="width: 80px;">Type</th>+ <th style="width: 200px;">Device Name</th>+ <th style="width: 120px;">Vendor</th>+ <th style="width: 120px;">Product</th>+ <th style="width: 200px;">Serial Number</th>+ <th style="width: 150px;">Last Connected</th>+ </tr>+"@++ foreach ($device in $Results.USBDevices) {+ $typeClass = if ($device.Type -eq 'Storage') { 'type-storage' } else { 'type-usb' }+ $lastConnected = if ($device.LastConnected) {+ $device.LastConnected.ToString('yyyy-MM-dd HH:mm:ss')+ } else {+ 'Unknown'+ }+ $friendlyName = $device.FriendlyName -replace '<', '<' -replace '>', '>'++ $html += @"+ <tr>+ <td><span class="device-type $typeClass">$($device.Type)</span></td>+ <td><strong>$friendlyName</strong></td>+ <td>$($device.Vendor)</td>+ <td>$($device.Product)</td>+ <td><span class="serial">$($device.SerialNumber)</span></td>+ <td>$lastConnected</td>+ </tr>+"@+ }++ $html += " </table>`n"++ # Connection Events+ if ($Results.ConnectionEvents.Count -gt 0) {+ $html += @"++ <h2>Recent Connection Events</h2>+ <table>+ <tr>+ <th style="width: 150px;">Timestamp</th>+ <th style="width: 100px;">Event ID</th>+ <th>Message</th>+ </tr>+"@++ foreach ($event in ($Results.ConnectionEvents | Select-Object -First 50)) {+ $timestamp = if ($event.Timestamp) {+ $event.Timestamp.ToString('yyyy-MM-dd HH:mm:ss')+ } else {+ 'N/A'+ }+ $message = $event.Message -replace '<', '<' -replace '>', '>'++ $html += @"+ <tr>+ <td>$timestamp</td>+ <td>$($event.EventID)</td>+ <td><small>$message</small></td>+ </tr>+"@+ }++ $html += " </table>`n"+ }++ $currentDate = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'++ $html += @"++ <div class="footer">+ Generated by WindowsSecurityAudit Module | USB History Analysis | $currentDate+ </div>+ </div>+</body>+</html>+"@++ return $html+}\ No newline at end of filediff --git a/Forensics/New-ForensicTimeline.ps1 b/Forensics/New-ForensicTimeline.ps1new file mode 100644index 0000000..00d8a84--- /dev/null+++ b/Forensics/New-ForensicTimeline.ps1@@ -0,0 +1,529 @@+function New-ForensicTimeline {+ <#+ .SYNOPSIS+ Creates a forensic timeline from multiple artifact sources+ .DESCRIPTION+ Builds a comprehensive timeline combining event logs, file system changes,+ registry modifications, and network connections for incident investigation.+ .PARAMETER StartTime+ Timeline start time (default: 24 hours ago)+ .PARAMETER EndTime+ Timeline end time (default: now)+ .PARAMETER IncludeEventLogs+ Include Windows event logs in timeline+ .PARAMETER IncludeFileSystem+ Include file system changes (MFT analysis)+ .PARAMETER IncludeRegistry+ Include registry modifications+ .PARAMETER IncludeNetwork+ Include network connection history+ .PARAMETER TargetPaths+ Specific paths to analyze for file system timeline+ .PARAMETER OutputPath+ Path to save timeline report+ .PARAMETER Format+ Output format: HTML, CSV, JSON, or All+ .EXAMPLE+ New-ForensicTimeline -StartTime (Get-Date).AddHours(-24)+ New-ForensicTimeline -IncludeFileSystem -TargetPaths "C:\Users\*\Downloads" -OutputPath "C:\Forensics"+ .OUTPUTS+ PSCustomObject with timeline events+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [DateTime]$StartTime = (Get-Date).AddHours(-24),++ [Parameter()]+ [DateTime]$EndTime = (Get-Date),++ [Parameter()]+ [switch]$IncludeEventLogs,++ [Parameter()]+ [switch]$IncludeFileSystem,++ [Parameter()]+ [switch]$IncludeRegistry,++ [Parameter()]+ [switch]$IncludeNetwork,++ [Parameter()]+ [string[]]$TargetPaths = @('C:\Users\*\Downloads', 'C:\Users\*\Documents', 'C:\Temp'),++ [Parameter()]+ [string]$OutputPath,++ [Parameter()]+ [ValidateSet('HTML', 'CSV', 'JSON', 'All')]+ [string]$Format = 'HTML'+ )++ begin {+ Write-Host "=== FORENSIC TIMELINE CREATION ===" -ForegroundColor Cyan+ Write-Host "Start Time: $($StartTime.ToString('yyyy-MM-dd HH:mm:ss'))" -ForegroundColor Yellow+ Write-Host "End Time: $($EndTime.ToString('yyyy-MM-dd HH:mm:ss'))" -ForegroundColor Yellow+ Write-Host "Duration: $([Math]::Round(($EndTime - $StartTime).TotalHours, 2)) hours" -ForegroundColor Yellow++ $timeline = [PSCustomObject]@{+ CreatedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ StartTime = $StartTime.ToString('yyyy-MM-dd HH:mm:ss')+ EndTime = $EndTime.ToString('yyyy-MM-dd HH:mm:ss')+ Events = @()+ Summary = @{+ TotalEvents = 0+ EventLogEntries = 0+ FileSystemChanges = 0+ RegistryChanges = 0+ NetworkConnections = 0+ }+ }++ # If no specific sources selected, include all+ if (-not ($IncludeEventLogs -or $IncludeFileSystem -or $IncludeRegistry -or $IncludeNetwork)) {+ $IncludeEventLogs = $true+ $IncludeFileSystem = $true+ $IncludeRegistry = $true+ Write-Host "No specific sources selected - including Event Logs, File System, and Registry" -ForegroundColor Gray+ }+ }++ process {+ try {+ # 1. COLLECT EVENT LOG ENTRIES+ if ($IncludeEventLogs) {+ Write-Host "`n[1/4] Collecting event log entries..." -ForegroundColor Cyan++ $eventLogs = @('Security', 'System', 'Application', 'Microsoft-Windows-PowerShell/Operational')++ foreach ($logName in $eventLogs) {+ try {+ Write-Host " Scanning: $logName..." -ForegroundColor Gray++ $events = Get-WinEvent -FilterHashtable @{+ LogName = $logName+ StartTime = $StartTime+ EndTime = $EndTime+ } -ErrorAction SilentlyContinue -MaxEvents 1000++ foreach ($event in $events) {+ # FIXED: Safe message handling with null check+ $message = if ($event.Message) {+ $event.Message.Substring(0, [Math]::Min(200, $event.Message.Length))+ } else {+ "Event ID $($event.Id) - No message available"+ }++ $timeline.Events += [PSCustomObject]@{+ Timestamp = $event.TimeCreated+ Source = 'EventLog'+ Category = $logName+ EventID = $event.Id+ Level = $event.LevelDisplayName+ Message = $message+ Details = @{+ Provider = $event.ProviderName+ TaskDisplayName = $event.TaskDisplayName+ MachineName = $event.MachineName+ }+ }++ $timeline.Summary.EventLogEntries+++ }++ Write-Host " Found $($events.Count) events" -ForegroundColor Gray+ }+ catch {+ Write-Warning "Could not read log $logName - $_"+ }+ }++ Write-Host " Total event log entries: $($timeline.Summary.EventLogEntries)" -ForegroundColor Green+ }++ # 2. COLLECT FILE SYSTEM CHANGES+ if ($IncludeFileSystem) {+ Write-Host "`n[2/4] Analyzing file system changes..." -ForegroundColor Cyan++ foreach ($path in $TargetPaths) {+ if (Test-Path $path) {+ Write-Host " Scanning: $path..." -ForegroundColor Gray++ try {+ # FIXED: Safe array wrapping with @()+ $files = @(Get-ChildItem -Path $path -Recurse -File -ErrorAction SilentlyContinue |+ Where-Object {+ ($_.CreationTime -ge $StartTime -and $_.CreationTime -le $EndTime) -or+ ($_.LastWriteTime -ge $StartTime -and $_.LastWriteTime -le $EndTime) -or+ ($_.LastAccessTime -ge $StartTime -and $_.LastAccessTime -le $EndTime)+ } |+ Select-Object -First 500)++ foreach ($file in $files) {+ # Add creation event+ if ($file.CreationTime -ge $StartTime -and $file.CreationTime -le $EndTime) {+ $timeline.Events += [PSCustomObject]@{+ Timestamp = $file.CreationTime+ Source = 'FileSystem'+ Category = 'File Created'+ EventID = $null+ Level = 'Information'+ Message = "File created: $($file.FullName)"+ Details = @{+ FileName = $file.Name+ FilePath = $file.FullName+ Size = $file.Length+ Extension = $file.Extension+ }+ }++ $timeline.Summary.FileSystemChanges+++ }++ # Add modification event+ if ($file.LastWriteTime -ge $StartTime -and $file.LastWriteTime -le $EndTime -and+ $file.LastWriteTime -ne $file.CreationTime) {+ $timeline.Events += [PSCustomObject]@{+ Timestamp = $file.LastWriteTime+ Source = 'FileSystem'+ Category = 'File Modified'+ EventID = $null+ Level = 'Information'+ Message = "File modified: $($file.FullName)"+ Details = @{+ FileName = $file.Name+ FilePath = $file.FullName+ Size = $file.Length+ Extension = $file.Extension+ }+ }++ $timeline.Summary.FileSystemChanges+++ }+ }++ Write-Host " Found $($files.Count) files" -ForegroundColor Gray+ }+ catch {+ Write-Warning "Could not scan $path - $_"+ }+ }+ else {+ Write-Host " Path not found: $path" -ForegroundColor Gray+ }+ }++ Write-Host " Total file system changes: $($timeline.Summary.FileSystemChanges)" -ForegroundColor Green+ }++ # 3. COLLECT REGISTRY CHANGES+ if ($IncludeRegistry) {+ Write-Host "`n[3/4] Analyzing registry modifications..." -ForegroundColor Cyan++ # Check recent registry activity via event logs+ try {+ $regEvents = Get-WinEvent -FilterHashtable @{+ LogName = 'Security'+ ID = 4657 # Registry value modified+ StartTime = $StartTime+ EndTime = $EndTime+ } -ErrorAction SilentlyContinue -MaxEvents 500++ foreach ($event in $regEvents) {+ # FIXED: Safe message handling+ $message = if ($event.Message) {+ $event.Message.Substring(0, [Math]::Min(200, $event.Message.Length))+ } else {+ "Registry value modified"+ }++ $timeline.Events += [PSCustomObject]@{+ Timestamp = $event.TimeCreated+ Source = 'Registry'+ Category = 'Registry Modified'+ EventID = 4657+ Level = 'Information'+ Message = "Registry value modified"+ Details = @{+ EventID = $event.Id+ Message = $message+ }+ }++ $timeline.Summary.RegistryChanges+++ }++ Write-Host " Total registry changes: $($timeline.Summary.RegistryChanges)" -ForegroundColor Green+ }+ catch {+ Write-Host " Registry event auditing not enabled" -ForegroundColor Gray+ }+ }++ # 4. COLLECT NETWORK CONNECTIONS+ if ($IncludeNetwork) {+ Write-Host "`n[4/4] Analyzing network activity..." -ForegroundColor Cyan++ # Current connections+ try {+ $connections = Get-NetTCPConnection -ErrorAction SilentlyContinue |+ Select-Object -First 100++ foreach ($conn in $connections) {+ $process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue++ $timeline.Events += [PSCustomObject]@{+ Timestamp = Get-Date # Current snapshot+ Source = 'Network'+ Category = 'TCP Connection'+ EventID = $null+ Level = 'Information'+ Message = "Active connection: $($conn.LocalAddress):$($conn.LocalPort) -> $($conn.RemoteAddress):$($conn.RemotePort)"+ Details = @{+ LocalAddress = $conn.LocalAddress+ LocalPort = $conn.LocalPort+ RemoteAddress = $conn.RemoteAddress+ RemotePort = $conn.RemotePort+ State = $conn.State+ Process = if($process){$process.ProcessName}else{'Unknown'}+ PID = $conn.OwningProcess+ }+ }++ $timeline.Summary.NetworkConnections+++ }++ Write-Host " Total network connections: $($timeline.Summary.NetworkConnections)" -ForegroundColor Green+ }+ catch {+ Write-Warning "Could not retrieve network connections"+ }+ }++ # 5. SORT AND FINALIZE TIMELINE+ Write-Host "`n[*] Sorting timeline events..." -ForegroundColor Cyan++ $timeline.Events = $timeline.Events | Sort-Object Timestamp -Descending+ $timeline.Summary.TotalEvents = $timeline.Events.Count++ Write-Host " Total events in timeline: $($timeline.Summary.TotalEvents)" -ForegroundColor Green++ # 6. EXPORT REPORTS+ if ($OutputPath) {+ Write-Host "`n[*] Exporting forensic timeline..." -ForegroundColor Cyan++ if (-not (Test-Path $OutputPath)) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ }++ $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"+ $reportName = "ForensicTimeline_$timestamp"++ # Export JSON+ if ($Format -in @('JSON', 'All')) {+ $jsonPath = Join-Path $OutputPath "$reportName.json"+ $timeline | ConvertTo-Json -Depth 10 | Out-File $jsonPath -Encoding UTF8+ Write-Host " JSON timeline saved: $jsonPath" -ForegroundColor Green+ }++ # Export CSV+ if ($Format -in @('CSV', 'All')) {+ $csvPath = Join-Path $OutputPath "$reportName.csv"+ $timeline.Events | Select-Object Timestamp, Source, Category, Level, Message |+ Export-Csv $csvPath -NoTypeInformation+ Write-Host " CSV timeline saved: $csvPath" -ForegroundColor Green+ }++ # Export HTML+ if ($Format -in @('HTML', 'All')) {+ $htmlPath = Join-Path $OutputPath "$reportName.html"+ $html = Generate-TimelineHTML -Timeline $timeline+ $html | Out-File $htmlPath -Encoding UTF8+ Write-Host " HTML timeline saved: $htmlPath" -ForegroundColor Green+ }+ }++ }+ catch {+ Write-Error "Error during timeline creation - $_"+ throw+ }+ }++ end {+ Write-Host "`n=== FORENSIC TIMELINE COMPLETE ===" -ForegroundColor Green++ Write-Host "`nSummary:" -ForegroundColor Cyan+ Write-Host " Total Events: $($timeline.Summary.TotalEvents)" -ForegroundColor White+ Write-Host " Event Log Entries: $($timeline.Summary.EventLogEntries)" -ForegroundColor Gray+ Write-Host " File System Changes: $($timeline.Summary.FileSystemChanges)" -ForegroundColor Gray+ Write-Host " Registry Changes: $($timeline.Summary.RegistryChanges)" -ForegroundColor Gray+ Write-Host " Network Connections: $($timeline.Summary.NetworkConnections)" -ForegroundColor Gray++ if ($timeline.Events.Count -gt 0) {+ Write-Host "`nRecent Timeline Events:" -ForegroundColor Cyan+ $timeline.Events |+ Select-Object -First 10 |+ ForEach-Object {+ $color = switch ($_.Source) {+ 'EventLog' { 'Yellow' }+ 'FileSystem' { 'Cyan' }+ 'Registry' { 'Magenta' }+ 'Network' { 'Green' }+ default { 'White' }+ }++ # Safe message truncation+ $displayMessage = if ($_.Message) {+ $_.Message.Substring(0, [Math]::Min(80, $_.Message.Length))+ } else {+ "No message"+ }++ Write-Host " [$($_.Timestamp.ToString('yyyy-MM-dd HH:mm:ss'))] $($_.Source) - $($_.Category): $displayMessage" -ForegroundColor $color+ }+ }++ return $timeline+ }+}++# Helper function to generate HTML timeline+function Generate-TimelineHTML {+ param($Timeline)++ $html = @"+<!DOCTYPE html>+<html>+<head>+ <title>Forensic Timeline - $($Timeline.ComputerName)</title>+ <style>+ body { font-family: 'Segoe UI', Arial, sans-serif; margin: 20px; background: #1a1a1a; color: #e0e0e0; }+ .container { max-width: 1600px; margin: 0 auto; background: #2d2d2d; padding: 30px; box-shadow: 0 0 20px rgba(0,0,0,0.5); }+ h1 { color: #00d4ff; border-bottom: 3px solid #00d4ff; padding-bottom: 10px; }+ h2 { color: #00b8ff; margin-top: 30px; }+ .summary { background: #3a3a3a; padding: 20px; border-radius: 5px; margin: 20px 0; border-left: 4px solid #00d4ff; }+ .metric { display: inline-block; margin: 10px 30px 10px 0; }+ .metric-label { font-weight: bold; color: #888; font-size: 12px; }+ .metric-value { font-size: 28px; font-weight: bold; color: #00d4ff; }+ .timeline { margin: 30px 0; }+ .event { background: #3a3a3a; margin: 10px 0; padding: 15px; border-radius: 5px; border-left: 4px solid #555; }+ .event:hover { background: #444; border-left-color: #00d4ff; }+ .event-header { display: flex; justify-content: space-between; margin-bottom: 8px; }+ .event-time { color: #00d4ff; font-weight: bold; font-family: monospace; }+ .event-source { padding: 3px 8px; border-radius: 3px; font-size: 11px; font-weight: bold; }+ .source-eventlog { background: #ff6b35; color: white; }+ .source-filesystem { background: #00d4ff; color: black; }+ .source-registry { background: #a855f7; color: white; }+ .source-network { background: #10b981; color: white; }+ .event-message { color: #ccc; margin-top: 5px; }+ .footer { margin-top: 40px; padding-top: 20px; border-top: 1px solid #555; color: #888; font-size: 12px; }+ .filter-bar { background: #3a3a3a; padding: 15px; border-radius: 5px; margin: 20px 0; }+ .filter-btn { background: #555; color: white; border: none; padding: 8px 15px; margin: 5px; border-radius: 3px; cursor: pointer; }+ .filter-btn:hover { background: #00d4ff; color: black; }+ .filter-btn.active { background: #00d4ff; color: black; }+ </style>+ <script>+ function filterEvents(source) {+ const events = document.querySelectorAll('.event');+ const buttons = document.querySelectorAll('.filter-btn');++ buttons.forEach(btn => btn.classList.remove('active'));+ event.target.classList.add('active');++ if (source === 'all') {+ events.forEach(evt => evt.style.display = 'block');+ } else {+ events.forEach(evt => {+ if (evt.dataset.source === source) {+ evt.style.display = 'block';+ } else {+ evt.style.display = 'none';+ }+ });+ }+ }+ </script>+</head>+<body>+ <div class="container">+ <h1>🔍 Forensic Timeline Analysis</h1>+ <p><strong>Computer:</strong> $($Timeline.ComputerName) | <strong>Generated:</strong> $($Timeline.CreatedDate)</p>+ <p><strong>Time Range:</strong> $($Timeline.StartTime) → $($Timeline.EndTime)</p>++ <div class="summary">+ <h2>Summary</h2>+ <div class="metric">+ <div class="metric-label">TOTAL EVENTS</div>+ <div class="metric-value">$($Timeline.Summary.TotalEvents)</div>+ </div>+ <div class="metric">+ <div class="metric-label">EVENT LOGS</div>+ <div class="metric-value">$($Timeline.Summary.EventLogEntries)</div>+ </div>+ <div class="metric">+ <div class="metric-label">FILE CHANGES</div>+ <div class="metric-value">$($Timeline.Summary.FileSystemChanges)</div>+ </div>+ <div class="metric">+ <div class="metric-label">REGISTRY</div>+ <div class="metric-value">$($Timeline.Summary.RegistryChanges)</div>+ </div>+ <div class="metric">+ <div class="metric-label">NETWORK</div>+ <div class="metric-value">$($Timeline.Summary.NetworkConnections)</div>+ </div>+ </div>++ <div class="filter-bar">+ <strong>Filter by Source:</strong>+ <button class="filter-btn active" onclick="filterEvents('all')">All</button>+ <button class="filter-btn" onclick="filterEvents('EventLog')">Event Logs</button>+ <button class="filter-btn" onclick="filterEvents('FileSystem')">File System</button>+ <button class="filter-btn" onclick="filterEvents('Registry')">Registry</button>+ <button class="filter-btn" onclick="filterEvents('Network')">Network</button>+ </div>++ <h2>Timeline Events</h2>+ <div class="timeline">+"@++ foreach ($event in $Timeline.Events) {+ $sourceClass = "source-$($event.Source.ToLower())"+ $timestamp = if ($event.Timestamp) { $event.Timestamp.ToString('yyyy-MM-dd HH:mm:ss') } else { 'N/A' }+ $message = if ($event.Message) {+ $event.Message -replace '<', '<' -replace '>', '>'+ } else {+ 'No message available'+ }++ $html += @"+ <div class="event" data-source="$($event.Source)">+ <div class="event-header">+ <span class="event-time">$timestamp</span>+ <span class="event-source $sourceClass">$($event.Source)</span>+ </div>+ <div><strong>$($event.Category)</strong></div>+ <div class="event-message">$message</div>+ </div>+"@+ }++ $currentDate = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'++ $html += @"+ </div>++ <div class="footer">+ Generated by WindowsSecurityAudit Module | Forensic Timeline | $currentDate+ </div>+ </div>+</body>+</html>+"@++ return $html+}\ No newline at end of filediff --git a/Hardening/Enable-AuditPolicies.ps1 b/Hardening/Enable-AuditPolicies.ps1new file mode 100644index 0000000..6a9826a--- /dev/null+++ b/Hardening/Enable-AuditPolicies.ps1@@ -0,0 +1,319 @@+function Enable-AuditPolicies {+ <#+ .SYNOPSIS+ Configures Windows audit policies for security monitoring+ .DESCRIPTION+ Enables comprehensive audit policies for tracking security events including logon,+ account management, object access, policy changes, and privilege use+ .PARAMETER AuditLevel+ Audit level: Basic, Standard, or Comprehensive+ .PARAMETER IncludeFileAuditing+ Enable file and folder access auditing+ .PARAMETER IncludeRegistryAuditing+ Enable registry access auditing+ .EXAMPLE+ Enable-AuditPolicies -AuditLevel Standard+ Enable-AuditPolicies -AuditLevel Comprehensive -IncludeFileAuditing -IncludeRegistryAuditing+ .OUTPUTS+ PSCustomObject with audit configuration results+ #>++ [CmdletBinding(SupportsShouldProcess)]+ param(+ [Parameter()]+ [ValidateSet('Basic', 'Standard', 'Comprehensive')]+ [string]$AuditLevel = 'Standard',++ [Parameter()]+ [switch]$IncludeFileAuditing,++ [Parameter()]+ [switch]$IncludeRegistryAuditing+ )++ begin {+ Write-Host "=== WINDOWS AUDIT POLICIES CONFIGURATION ===" -ForegroundColor Cyan+ Write-Host "Audit Level: $AuditLevel" -ForegroundColor Yellow+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ # Check for admin privileges+ $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ if (-not $isAdmin) {+ throw "This function requires Administrator privileges!"+ }++ $results = [PSCustomObject]@{+ ConfigurationDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ AuditLevel = $AuditLevel+ PoliciesConfigured = @()+ Errors = @()+ AuditCategories = @{+ AccountLogon = @{}+ AccountManagement = @{}+ DetailedTracking = @{}+ LogonLogoff = @{}+ ObjectAccess = @{}+ PolicyChange = @{}+ PrivilegeUse = @{}+ System = @{}+ }+ }++ # Audit policy settings based on level+ $auditSettings = @{+ Basic = @{+ 'Account Logon' = @('Credential Validation')+ 'Account Management' = @('User Account Management', 'Security Group Management')+ 'Logon/Logoff' = @('Logon', 'Logoff', 'Account Lockout')+ 'Policy Change' = @('Audit Policy Change', 'Authentication Policy Change')+ 'System' = @('Security State Change', 'Security System Extension')+ }+ Standard = @{+ 'Account Logon' = @('Credential Validation', 'Kerberos Authentication Service')+ 'Account Management' = @('User Account Management', 'Security Group Management', 'Computer Account Management')+ 'Detailed Tracking' = @('Process Creation', 'Process Termination')+ 'Logon/Logoff' = @('Logon', 'Logoff', 'Account Lockout', 'Special Logon')+ 'Object Access' = @('File System', 'Registry', 'Handle Manipulation')+ 'Policy Change' = @('Audit Policy Change', 'Authentication Policy Change', 'Authorization Policy Change')+ 'Privilege Use' = @('Sensitive Privilege Use')+ 'System' = @('Security State Change', 'Security System Extension', 'System Integrity')+ }+ Comprehensive = @{+ 'Account Logon' = @('Credential Validation', 'Kerberos Authentication Service', 'Kerberos Service Ticket Operations')+ 'Account Management' = @('User Account Management', 'Security Group Management', 'Computer Account Management', 'Distribution Group Management', 'Application Group Management')+ 'Detailed Tracking' = @('Process Creation', 'Process Termination', 'DPAPI Activity', 'RPC Events', 'PNP Activity')+ 'Logon/Logoff' = @('Logon', 'Logoff', 'Account Lockout', 'Special Logon', 'Other Logon/Logoff Events', 'Network Policy Server')+ 'Object Access' = @('File System', 'Registry', 'Kernel Object', 'SAM', 'Handle Manipulation', 'File Share', 'Filtering Platform Packet Drop', 'Filtering Platform Connection')+ 'Policy Change' = @('Audit Policy Change', 'Authentication Policy Change', 'Authorization Policy Change', 'MPSSVC Rule-Level Policy Change', 'Filtering Platform Policy Change')+ 'Privilege Use' = @('Sensitive Privilege Use', 'Non Sensitive Privilege Use')+ 'System' = @('Security State Change', 'Security System Extension', 'System Integrity', 'IPsec Driver', 'Other System Events')+ }+ }+ }++ process {+ try {+ $selectedSettings = $auditSettings[$AuditLevel]+ $totalCategories = ($selectedSettings.Keys | Measure-Object).Count+ $currentCategory = 0++ foreach ($category in $selectedSettings.Keys) {+ $currentCategory+++ Write-Host "`n[$currentCategory/$totalCategories] Configuring: $category" -ForegroundColor Cyan++ foreach ($subcategory in $selectedSettings[$category]) {+ try {+ # Enable both Success and Failure auditing+ $auditCommand = "auditpol /set /subcategory:`"$subcategory`" /success:enable /failure:enable"++ if ($PSCmdlet.ShouldProcess($subcategory, "Enable audit policy")) {+ $result = Invoke-Expression $auditCommand 2>&1++ if ($LASTEXITCODE -eq 0) {+ $results.PoliciesConfigured += $subcategory+ Write-Host " + $subcategory" -ForegroundColor Green+ }+ else {+ $results.Errors += "Failed to configure: $subcategory - $result"+ Write-Warning " - Failed: $subcategory"+ }+ }+ }+ catch {+ $results.Errors += "Error configuring $subcategory : $_"+ Write-Warning " - Error: $subcategory"+ }+ }++ # Store category status+ $categoryKey = $category -replace '[/ ]', ''+ if ($results.AuditCategories.ContainsKey($categoryKey)) {+ $results.AuditCategories[$categoryKey] = @{+ Configured = $true+ Subcategories = $selectedSettings[$category]+ }+ }+ }++ # Configure Advanced Audit Policies+ Write-Host "`n[ADVANCED] Configuring advanced audit settings..." -ForegroundColor Cyan++ # Force audit policy subcategory settings+ try {+ $regPath = "HKLM:\System\CurrentControlSet\Control\Lsa"+ Set-ItemProperty -Path $regPath -Name "SCENoApplyLegacyAuditPolicy" -Value 1 -Type DWord -Force+ Write-Host " + Advanced audit policy mode enabled" -ForegroundColor Green+ $results.PoliciesConfigured += "Advanced Audit Policy Mode"+ }+ catch {+ $results.Errors += "Failed to enable advanced audit mode: $_"+ Write-Warning " - Failed to enable advanced audit mode"+ }++ # Increase Security event log size+ try {+ $logName = 'Security'+ $log = Get-WinEvent -ListLog $logName++ # Set to 1GB+ $log.MaximumSizeInBytes = 1GB+ $log.SaveChanges()++ Write-Host " + Security log size increased to 1GB" -ForegroundColor Green+ $results.PoliciesConfigured += "Security Log Size: 1GB"+ }+ catch {+ $results.Errors += "Failed to increase log size: $_"+ Write-Warning " - Failed to increase log size"+ }++ # Enable log retention+ try {+ wevtutil sl Security /rt:false /ab:true+ Write-Host " + Security log retention enabled" -ForegroundColor Green+ $results.PoliciesConfigured += "Security Log Retention"+ }+ catch {+ $results.Errors += "Failed to configure log retention: $_"+ }++ # Configure Command Line Process Auditing+ if ($AuditLevel -in @('Standard', 'Comprehensive')) {+ Write-Host "`n[PROCESS] Enabling command line process auditing..." -ForegroundColor Cyan+ try {+ $regPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\Audit"+ if (-not (Test-Path $regPath)) {+ New-Item -Path $regPath -Force | Out-Null+ }+ Set-ItemProperty -Path $regPath -Name "ProcessCreationIncludeCmdLine_Enabled" -Value 1 -Type DWord -Force+ Write-Host " + Command line auditing enabled" -ForegroundColor Green+ $results.PoliciesConfigured += "Command Line Process Auditing"+ }+ catch {+ $results.Errors += "Failed to enable command line auditing: $_"+ Write-Warning " - Failed to enable command line auditing"+ }+ }++ # File System Auditing+ if ($IncludeFileAuditing -or $AuditLevel -eq 'Comprehensive') {+ Write-Host "`n[FILE SYSTEM] Configuring file system auditing..." -ForegroundColor Cyan++ $pathsToAudit = @(+ "$env:SystemRoot\System32",+ "$env:ProgramFiles",+ "$env:USERPROFILE\Documents"+ )++ foreach ($path in $pathsToAudit) {+ if (Test-Path $path) {+ try {+ # Get current ACL+ $acl = Get-Acl $path++ # Create audit rule for Everyone - Track both Success and Failure+ $auditRule = New-Object System.Security.AccessControl.FileSystemAuditRule(+ "Everyone",+ "Delete,DeleteSubdirectoriesAndFiles,ChangePermissions,TakeOwnership",+ "ContainerInherit,ObjectInherit",+ "None",+ "Success,Failure"+ )++ # Add audit rule+ $acl.AddAuditRule($auditRule)+ Set-Acl -Path $path -AclObject $acl++ Write-Host " + Auditing enabled on: $path" -ForegroundColor Green+ }+ catch {+ Write-Warning " - Failed to audit: $path"+ }+ }+ }+ $results.PoliciesConfigured += "File System Auditing"+ }++ # Registry Auditing+ if ($IncludeRegistryAuditing -or $AuditLevel -eq 'Comprehensive') {+ Write-Host "`n[REGISTRY] Configuring registry auditing..." -ForegroundColor Cyan++ $regKeysToAudit = @(+ "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run",+ "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce",+ "HKLM:\SYSTEM\CurrentControlSet\Services"+ )++ foreach ($regKey in $regKeysToAudit) {+ if (Test-Path $regKey) {+ try {+ $acl = Get-Acl $regKey++ $auditRule = New-Object System.Security.AccessControl.RegistryAuditRule(+ "Everyone",+ "SetValue,CreateSubKey,Delete",+ "ContainerInherit",+ "None",+ "Success,Failure"+ )++ $acl.AddAuditRule($auditRule)+ Set-Acl -Path $regKey -AclObject $acl++ Write-Host " + Auditing enabled on: $regKey" -ForegroundColor Green+ }+ catch {+ Write-Warning " - Failed to audit: $regKey"+ }+ }+ }+ $results.PoliciesConfigured += "Registry Auditing"+ }++ }+ catch {+ Write-Error "Error during audit policy configuration: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== AUDIT CONFIGURATION COMPLETE ===" -ForegroundColor Green++ Write-Host "`nPolicies Configured: $($results.PoliciesConfigured.Count)" -ForegroundColor Cyan++ if ($results.Errors.Count -gt 0) {+ Write-Host "`nErrors: $($results.Errors.Count)" -ForegroundColor Red+ $results.Errors | ForEach-Object {+ Write-Host " - $_" -ForegroundColor Red+ }+ }++ Write-Host "`nAudit Summary:" -ForegroundColor Cyan+ Write-Host " Level: $($results.AuditLevel)" -ForegroundColor White+ Write-Host " Policies Enabled: $($results.PoliciesConfigured.Count)" -ForegroundColor White+ Write-Host " Security Log: 1GB" -ForegroundColor White++ # Verify current audit policy+ Write-Host "`nVerifying configuration..." -ForegroundColor Cyan+ $verifyResult = auditpol /get /category:* | Out-String+ Write-Verbose $verifyResult++ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ Write-Host " 1. Monitor Security event log regularly" -ForegroundColor White+ Write-Host " 2. Set up log forwarding to SIEM if available" -ForegroundColor White+ Write-Host " 3. Review audit events daily for suspicious activity" -ForegroundColor White+ Write-Host " 4. Implement log retention policy" -ForegroundColor White+ Write-Host " 5. Test audit logging with known actions" -ForegroundColor White++ Write-Host "`nImportant Event IDs to monitor:" -ForegroundColor Yellow+ Write-Host " 4624 - Successful logon" -ForegroundColor White+ Write-Host " 4625 - Failed logon" -ForegroundColor White+ Write-Host " 4672 - Special privileges assigned" -ForegroundColor White+ Write-Host " 4720 - User account created" -ForegroundColor White+ Write-Host " 4740 - User account locked out" -ForegroundColor White+ Write-Host " 4688 - Process created" -ForegroundColor White++ return $results+ }+}\ No newline at end of filediff --git a/Hardening/Enable-PowerShellSecurity.ps1 b/Hardening/Enable-PowerShellSecurity.ps1new file mode 100644index 0000000..9cea56f--- /dev/null+++ b/Hardening/Enable-PowerShellSecurity.ps1@@ -0,0 +1,267 @@+function Enable-PowerShellSecurity {+ <#+ .SYNOPSIS+ Hardens PowerShell security settings+ .DESCRIPTION+ Configures PowerShell security features including execution policy, logging,+ transcription, and constrained language mode+ .PARAMETER ExecutionPolicy+ Set execution policy (default: RemoteSigned)+ .PARAMETER EnableScriptBlockLogging+ Enable PowerShell script block logging+ .PARAMETER EnableTranscription+ Enable PowerShell transcription logging+ .PARAMETER EnableModuleLogging+ Enable PowerShell module logging+ .PARAMETER TranscriptionPath+ Path for transcription logs+ .EXAMPLE+ Enable-PowerShellSecurity -ExecutionPolicy RemoteSigned -EnableScriptBlockLogging+ Enable-PowerShellSecurity -EnableTranscription -TranscriptionPath "C:\PSLogs"+ .OUTPUTS+ PSCustomObject with configuration results+ #>++ [CmdletBinding(SupportsShouldProcess)]+ param(+ [Parameter()]+ [ValidateSet('Restricted', 'AllSigned', 'RemoteSigned', 'Unrestricted', 'Bypass')]+ [string]$ExecutionPolicy = 'RemoteSigned',++ [Parameter()]+ [switch]$EnableScriptBlockLogging,++ [Parameter()]+ [switch]$EnableTranscription,++ [Parameter()]+ [switch]$EnableModuleLogging,++ [Parameter()]+ [string]$TranscriptionPath = "C:\PowerShellLogs"+ )++ begin {+ Write-Host "=== POWERSHELL SECURITY HARDENING ===" -ForegroundColor Cyan++ # Check for admin privileges+ $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ if (-not $isAdmin) {+ throw "This function requires Administrator privileges!"+ }++ $results = [PSCustomObject]@{+ ConfigurationDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ExecutionPolicy = @{+ Before = $null+ After = $null+ Status = 'Not Changed'+ }+ ScriptBlockLogging = @{+ Enabled = $false+ Status = 'Not Configured'+ }+ Transcription = @{+ Enabled = $false+ Path = $null+ Status = 'Not Configured'+ }+ ModuleLogging = @{+ Enabled = $false+ Status = 'Not Configured'+ }+ Changes = @()+ }+ }++ process {+ try {+ # 1. Configure Execution Policy+ Write-Host "`n[1/4] Configuring Execution Policy..." -ForegroundColor Cyan++ $currentPolicy = Get-ExecutionPolicy -Scope LocalMachine+ $results.ExecutionPolicy.Before = $currentPolicy++ if ($currentPolicy -ne $ExecutionPolicy) {+ if ($PSCmdlet.ShouldProcess("LocalMachine", "Set Execution Policy to $ExecutionPolicy")) {+ Set-ExecutionPolicy -ExecutionPolicy $ExecutionPolicy -Scope LocalMachine -Force+ $results.ExecutionPolicy.After = $ExecutionPolicy+ $results.ExecutionPolicy.Status = 'Changed'+ $results.Changes += "Execution Policy changed from $currentPolicy to $ExecutionPolicy"+ Write-Host " Execution Policy set to: $ExecutionPolicy" -ForegroundColor Green+ }+ } else {+ $results.ExecutionPolicy.After = $currentPolicy+ $results.ExecutionPolicy.Status = 'Already Configured'+ Write-Host " Execution Policy already set to: $ExecutionPolicy" -ForegroundColor Yellow+ }++ # 2. Configure Script Block Logging+ Write-Host "`n[2/4] Configuring Script Block Logging..." -ForegroundColor Cyan++ if ($EnableScriptBlockLogging) {+ $regPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging"++ if ($PSCmdlet.ShouldProcess("Registry", "Enable PowerShell Script Block Logging")) {+ # Create registry path if it doesn't exist+ if (-not (Test-Path $regPath)) {+ New-Item -Path $regPath -Force | Out-Null+ }++ # Enable script block logging+ Set-ItemProperty -Path $regPath -Name "EnableScriptBlockLogging" -Value 1 -Type DWord -Force++ # Enable logging of invocation start/stop+ Set-ItemProperty -Path $regPath -Name "EnableScriptBlockInvocationLogging" -Value 1 -Type DWord -Force++ $results.ScriptBlockLogging.Enabled = $true+ $results.ScriptBlockLogging.Status = 'Enabled'+ $results.Changes += "Script Block Logging enabled"++ Write-Host " Script Block Logging: Enabled" -ForegroundColor Green+ }+ } else {+ Write-Host " Script Block Logging: Skipped" -ForegroundColor Yellow+ }++ # 3. Configure PowerShell Transcription+ Write-Host "`n[3/4] Configuring PowerShell Transcription..." -ForegroundColor Cyan++ if ($EnableTranscription) {+ $regPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\Transcription"++ if ($PSCmdlet.ShouldProcess("Registry", "Enable PowerShell Transcription")) {+ # Create transcription directory+ if (-not (Test-Path $TranscriptionPath)) {+ New-Item -Path $TranscriptionPath -ItemType Directory -Force | Out-Null+ }++ # Create registry path if it doesn't exist+ if (-not (Test-Path $regPath)) {+ New-Item -Path $regPath -Force | Out-Null+ }++ # Enable transcription+ Set-ItemProperty -Path $regPath -Name "EnableTranscripting" -Value 1 -Type DWord -Force+ Set-ItemProperty -Path $regPath -Name "OutputDirectory" -Value $TranscriptionPath -Type String -Force+ Set-ItemProperty -Path $regPath -Name "EnableInvocationHeader" -Value 1 -Type DWord -Force++ $results.Transcription.Enabled = $true+ $results.Transcription.Path = $TranscriptionPath+ $results.Transcription.Status = 'Enabled'+ $results.Changes += "PowerShell Transcription enabled at: $TranscriptionPath"++ Write-Host " Transcription: Enabled" -ForegroundColor Green+ Write-Host " Transcription Path: $TranscriptionPath" -ForegroundColor White+ }+ } else {+ Write-Host " Transcription: Skipped" -ForegroundColor Yellow+ }++ # 4. Configure Module Logging+ Write-Host "`n[4/4] Configuring Module Logging..." -ForegroundColor Cyan++ if ($EnableModuleLogging) {+ $regPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ModuleLogging"+ $moduleNamesPath = "$regPath\ModuleNames"++ if ($PSCmdlet.ShouldProcess("Registry", "Enable PowerShell Module Logging")) {+ # Create registry paths+ if (-not (Test-Path $regPath)) {+ New-Item -Path $regPath -Force | Out-Null+ }+ if (-not (Test-Path $moduleNamesPath)) {+ New-Item -Path $moduleNamesPath -Force | Out-Null+ }++ # Enable module logging+ Set-ItemProperty -Path $regPath -Name "EnableModuleLogging" -Value 1 -Type DWord -Force++ # Log all modules+ Set-ItemProperty -Path $moduleNamesPath -Name "*" -Value "*" -Type String -Force++ $results.ModuleLogging.Enabled = $true+ $results.ModuleLogging.Status = 'Enabled'+ $results.Changes += "Module Logging enabled for all modules"++ Write-Host " Module Logging: Enabled" -ForegroundColor Green+ }+ } else {+ Write-Host " Module Logging: Skipped" -ForegroundColor Yellow+ }++ # Additional PowerShell Security Settings+ Write-Host "`n[ADDITIONAL] Applying Additional Security Settings..." -ForegroundColor Cyan++ # Disable PowerShell v2 (if exists)+ $psv2Feature = Get-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2 -ErrorAction SilentlyContinue+ if ($psv2Feature -and $psv2Feature.State -eq 'Enabled') {+ if ($PSCmdlet.ShouldProcess("Windows Feature", "Disable PowerShell v2")) {+ try {+ Disable-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2 -NoRestart -ErrorAction Stop | Out-Null+ Disable-WindowsOptionalFeature -Online -FeatureName MicrosoftWindowsPowerShellV2Root -NoRestart -ErrorAction Stop | Out-Null+ $results.Changes += "PowerShell v2 disabled (requires restart)"+ Write-Host " PowerShell v2: Disabled (restart required)" -ForegroundColor Green+ } catch {+ Write-Warning " Could not disable PowerShell v2: $_"+ }+ }+ } else {+ Write-Host " PowerShell v2: Already disabled or not installed" -ForegroundColor Yellow+ }++ # Configure WSMAN (Windows Remote Management) security+ Write-Host "`n[WSMAN] Configuring Windows Remote Management Security..." -ForegroundColor Cyan++ try {+ # Disable Basic Authentication+ Set-Item WSMan:\localhost\Service\Auth\Basic -Value $false -Force+ $results.Changes += "WSMAN Basic Authentication disabled"+ Write-Host " WSMAN Basic Auth: Disabled" -ForegroundColor Green++ # Enable Kerberos+ Set-Item WSMan:\localhost\Service\Auth\Kerberos -Value $true -Force+ Write-Host " WSMAN Kerberos: Enabled" -ForegroundColor Green++ } catch {+ Write-Warning " Could not configure WSMAN: $_"+ }++ }+ catch {+ Write-Error "Error during PowerShell security hardening: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== CONFIGURATION COMPLETE ===" -ForegroundColor Green+ Write-Host "`nChanges Applied:" -ForegroundColor Cyan++ if ($results.Changes.Count -gt 0) {+ $results.Changes | ForEach-Object {+ Write-Host " - $_" -ForegroundColor White+ }+ } else {+ Write-Host " No changes were made" -ForegroundColor Yellow+ }++ Write-Host "`nCurrent Configuration:" -ForegroundColor Cyan+ Write-Host " Execution Policy: $($results.ExecutionPolicy.After)" -ForegroundColor White+ Write-Host " Script Block Logging: $($results.ScriptBlockLogging.Status)" -ForegroundColor White+ Write-Host " Transcription: $($results.Transcription.Status)" -ForegroundColor White+ Write-Host " Module Logging: $($results.ModuleLogging.Status)" -ForegroundColor White++ if ($results.Changes -match 'restart') {+ Write-Host "`n⚠ RESTART REQUIRED for some changes to take effect" -ForegroundColor Yellow+ }++ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ Write-Host " 1. Test scripts after changing execution policy" -ForegroundColor White+ Write-Host " 2. Monitor PowerShell logs regularly" -ForegroundColor White+ Write-Host " 3. Rotate transcription logs to prevent disk space issues" -ForegroundColor White+ Write-Host " 4. Consider implementing JEA (Just Enough Administration)" -ForegroundColor White++ return $results+ }+}\ No newline at end of filediff --git a/Hardening/Set-SecurityBaseline.ps1 b/Hardening/Set-SecurityBaseline.ps1new file mode 100644index 0000000..39a3b99--- /dev/null+++ b/Hardening/Set-SecurityBaseline.ps1@@ -0,0 +1,433 @@+function Set-SecurityBaseline {+ <#+ .SYNOPSIS+ Applies Windows security baseline configuration+ .DESCRIPTION+ Configures Windows security settings based on industry best practices and hardening guides+ (CIS benchmarks, Microsoft Security Baselines)+ .PARAMETER BaselineLevel+ Security baseline level: Basic, Recommended, or Strict+ .PARAMETER EnableBitLocker+ Enable BitLocker encryption on system drive+ .PARAMETER DisableSMBv1+ Disable SMBv1 protocol+ .PARAMETER ConfigureFirewall+ Configure Windows Firewall with recommended settings+ .EXAMPLE+ Set-SecurityBaseline -BaselineLevel Recommended+ Set-SecurityBaseline -BaselineLevel Strict -EnableBitLocker -DisableSMBv1+ .OUTPUTS+ PSCustomObject with baseline configuration results+ #>++ [CmdletBinding(SupportsShouldProcess)]+ param(+ [Parameter()]+ [ValidateSet('Basic', 'Recommended', 'Strict')]+ [string]$BaselineLevel = 'Recommended',++ [Parameter()]+ [switch]$EnableBitLocker,++ [Parameter()]+ [switch]$DisableSMBv1,++ [Parameter()]+ [switch]$ConfigureFirewall+ )++ begin {+ Write-Host "=== WINDOWS SECURITY BASELINE CONFIGURATION ===" -ForegroundColor Cyan+ Write-Host "Baseline Level: $BaselineLevel" -ForegroundColor Yellow+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ # Check for admin privileges+ $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ if (-not $isAdmin) {+ throw "This function requires Administrator privileges!"+ }++ $results = [PSCustomObject]@{+ ConfigurationDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ BaselineLevel = $BaselineLevel+ Changes = @()+ Errors = @()+ RequiresReboot = $false+ Categories = @{+ UAC = @{}+ Firewall = @{}+ WindowsDefender = @{}+ NetworkSecurity = @{}+ AccountSecurity = @{}+ SystemSecurity = @{}+ BitLocker = @{}+ }+ }+ }++ process {+ try {+ # Category 1: UAC Configuration+ Write-Host "`n[1/7] Configuring User Account Control (UAC)..." -ForegroundColor Cyan++ $uacPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"++ try {+ # Enable UAC+ Set-ItemProperty -Path $uacPath -Name "EnableLUA" -Value 1 -Type DWord -Force+ $results.Changes += "UAC enabled"++ # Prompt for admin credentials+ Set-ItemProperty -Path $uacPath -Name "ConsentPromptBehaviorAdmin" -Value 2 -Type DWord -Force++ # Elevate signed executables+ if ($BaselineLevel -in @('Recommended', 'Strict')) {+ Set-ItemProperty -Path $uacPath -Name "ValidateAdminCodeSignatures" -Value 1 -Type DWord -Force+ $results.Changes += "UAC: Require signed executables"+ }++ # Secure desktop for elevation prompts+ if ($BaselineLevel -eq 'Strict') {+ Set-ItemProperty -Path $uacPath -Name "PromptOnSecureDesktop" -Value 1 -Type DWord -Force+ $results.Changes += "UAC: Secure desktop for prompts"+ }++ $results.Categories.UAC = @{+ Enabled = $true+ Status = 'Configured'+ }++ Write-Host " UAC: Configured" -ForegroundColor Green+ }+ catch {+ $results.Errors += "UAC configuration failed: $_"+ Write-Warning " UAC configuration failed: $_"+ }++ # Category 2: Windows Firewall+ Write-Host "`n[2/7] Configuring Windows Firewall..." -ForegroundColor Cyan++ if ($ConfigureFirewall -or $BaselineLevel -in @('Recommended', 'Strict')) {+ try {+ # Enable firewall for all profiles+ Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True+ $results.Changes += "Windows Firewall enabled for all profiles"++ # Configure default actions+ Set-NetFirewallProfile -Profile Domain -DefaultInboundAction Block -DefaultOutboundAction Allow+ Set-NetFirewallProfile -Profile Public -DefaultInboundAction Block -DefaultOutboundAction Allow+ Set-NetFirewallProfile -Profile Private -DefaultInboundAction Block -DefaultOutboundAction Allow+ $results.Changes += "Firewall: Block inbound by default"++ # Disable firewall notifications for Public profile+ Set-NetFirewallProfile -Profile Public -NotifyOnListen False++ if ($BaselineLevel -eq 'Strict') {+ # Enable logging+ Set-NetFirewallProfile -Profile Domain,Public,Private -LogAllowed True -LogBlocked True -LogMaxSizeKilobytes 16384+ $results.Changes += "Firewall: Logging enabled"+ }++ $results.Categories.Firewall = @{+ Enabled = $true+ Status = 'Configured'+ Profiles = 'All profiles enabled'+ }++ Write-Host " Firewall: Configured" -ForegroundColor Green+ }+ catch {+ $results.Errors += "Firewall configuration failed: $_"+ Write-Warning " Firewall configuration failed: $_"+ }+ }+ else {+ Write-Host " Firewall: Skipped" -ForegroundColor Yellow+ }++ # Category 3: Windows Defender+ Write-Host "`n[3/7] Configuring Windows Defender..." -ForegroundColor Cyan++ try {+ # Enable Real-Time Protection+ Set-MpPreference -DisableRealtimeMonitoring $false -ErrorAction Stop+ $results.Changes += "Windows Defender: Real-time protection enabled"++ # Enable Cloud Protection+ Set-MpPreference -MAPSReporting Advanced+ Set-MpPreference -SubmitSamplesConsent SendAllSamples+ $results.Changes += "Windows Defender: Cloud protection enabled"++ # Enable PUA (Potentially Unwanted Applications) protection+ Set-MpPreference -PUAProtection Enabled+ $results.Changes += "Windows Defender: PUA protection enabled"++ if ($BaselineLevel -in @('Recommended', 'Strict')) {+ # Enable Network Protection+ Set-MpPreference -EnableNetworkProtection Enabled+ $results.Changes += "Windows Defender: Network protection enabled"++ # Enable Controlled Folder Access+ Set-MpPreference -EnableControlledFolderAccess Enabled+ $results.Changes += "Windows Defender: Controlled folder access enabled"+ }++ # Update definitions+ Update-MpSignature -ErrorAction SilentlyContinue+ $results.Changes += "Windows Defender: Signatures updated"++ $results.Categories.WindowsDefender = @{+ RealTimeProtection = $true+ CloudProtection = $true+ Status = 'Configured'+ }++ Write-Host " Windows Defender: Configured" -ForegroundColor Green+ }+ catch {+ $results.Errors += "Windows Defender configuration failed: $_"+ Write-Warning " Windows Defender configuration failed: $_"+ }++ # Category 4: Network Security+ Write-Host "`n[4/7] Configuring Network Security..." -ForegroundColor Cyan++ try {+ # Disable SMBv1+ if ($DisableSMBv1 -or $BaselineLevel -in @('Recommended', 'Strict')) {+ Set-SmbServerConfiguration -EnableSMB1Protocol $false -Force -ErrorAction Stop+ $results.Changes += "SMBv1 protocol disabled"+ $results.RequiresReboot = $true+ Write-Host " SMBv1: Disabled (reboot required)" -ForegroundColor Green+ }++ # Configure SMBv2/v3 encryption+ if ($BaselineLevel -eq 'Strict') {+ Set-SmbServerConfiguration -EncryptData $true -Force+ $results.Changes += "SMB encryption enabled"+ }++ # Disable NetBIOS over TCP/IP+ if ($BaselineLevel -eq 'Strict') {+ $adapters = Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object { $_.IPEnabled }+ foreach ($adapter in $adapters) {+ $adapter.SetTcpipNetbios(2) | Out-Null # 2 = Disable NetBIOS+ }+ $results.Changes += "NetBIOS over TCP/IP disabled"+ }++ # Disable LLMNR+ if ($BaselineLevel -eq 'Strict') {+ $llmnrPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\DNSClient"+ if (-not (Test-Path $llmnrPath)) {+ New-Item -Path $llmnrPath -Force | Out-Null+ }+ Set-ItemProperty -Path $llmnrPath -Name "EnableMulticast" -Value 0 -Type DWord -Force+ $results.Changes += "LLMNR disabled"+ }++ $results.Categories.NetworkSecurity = @{+ SMBv1Disabled = $true+ Status = 'Configured'+ }++ Write-Host " Network Security: Configured" -ForegroundColor Green+ }+ catch {+ $results.Errors += "Network security configuration failed: $_"+ Write-Warning " Network security configuration failed: $_"+ }++ # Category 5: Account Security+ Write-Host "`n[5/7] Configuring Account Security..." -ForegroundColor Cyan++ try {+ # Disable Guest account+ Disable-LocalUser -Name "Guest" -ErrorAction SilentlyContinue+ $results.Changes += "Guest account disabled"++ # Rename Administrator account (if desired in Strict mode)+ if ($BaselineLevel -eq 'Strict') {+ # Note: This is commented out as renaming admin is risky+ # Rename-LocalUser -Name "Administrator" -NewName "Admin_SecureAccount"+ # $results.Changes += "Administrator account renamed"+ }++ # Configure account lockout policy+ net accounts /lockoutthreshold:5 /lockoutduration:30 /lockoutwindow:30 | Out-Null+ $results.Changes += "Account lockout policy configured (5 attempts, 30 min lockout)"++ # Password policy+ if ($BaselineLevel -in @('Recommended', 'Strict')) {+ net accounts /minpwlen:12 /maxpwage:90 /minpwage:1 /uniquepw:5 | Out-Null+ $results.Changes += "Password policy: 12 char minimum, 90 day max age"+ }++ $results.Categories.AccountSecurity = @{+ GuestDisabled = $true+ LockoutPolicy = 'Configured'+ Status = 'Configured'+ }++ Write-Host " Account Security: Configured" -ForegroundColor Green+ }+ catch {+ $results.Errors += "Account security configuration failed: $_"+ Write-Warning " Account security configuration failed: $_"+ }++ # Category 6: System Security+ Write-Host "`n[6/7] Configuring System Security..." -ForegroundColor Cyan++ try {+ # Disable AutoRun/AutoPlay+ $autorunPath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\Explorer"+ if (-not (Test-Path $autorunPath)) {+ New-Item -Path $autorunPath -Force | Out-Null+ }+ Set-ItemProperty -Path $autorunPath -Name "NoDriveTypeAutoRun" -Value 255 -Type DWord -Force+ $results.Changes += "AutoRun/AutoPlay disabled"++ # Disable Remote Assistance+ $raPath = "HKLM:\SYSTEM\CurrentControlSet\Control\Remote Assistance"+ Set-ItemProperty -Path $raPath -Name "fAllowToGetHelp" -Value 0 -Type DWord -Force+ $results.Changes += "Remote Assistance disabled"++ # Enable DEP (Data Execution Prevention)+ bcdedit /set nx AlwaysOn | Out-Null+ $results.Changes += "DEP enabled"++ # Disable unnecessary services+ if ($BaselineLevel -eq 'Strict') {+ $servicesToDisable = @(+ 'RemoteRegistry',+ 'RemoteAccess',+ 'Telephony',+ 'SharedAccess' # Internet Connection Sharing+ )++ foreach ($service in $servicesToDisable) {+ try {+ Stop-Service -Name $service -Force -ErrorAction SilentlyContinue+ Set-Service -Name $service -StartupType Disabled -ErrorAction SilentlyContinue+ $results.Changes += "Service disabled: $service"+ }+ catch {+ # Service might not exist+ }+ }+ }++ # Enable Windows Update automatic updates+ $wuPath = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU"+ if (-not (Test-Path $wuPath)) {+ New-Item -Path $wuPath -Force | Out-Null+ }+ Set-ItemProperty -Path $wuPath -Name "NoAutoUpdate" -Value 0 -Type DWord -Force+ Set-ItemProperty -Path $wuPath -Name "AUOptions" -Value 4 -Type DWord -Force # Auto download and install+ $results.Changes += "Windows Update: Automatic updates enabled"++ $results.Categories.SystemSecurity = @{+ AutoRunDisabled = $true+ RemoteAssistanceDisabled = $true+ DEPEnabled = $true+ Status = 'Configured'+ }++ Write-Host " System Security: Configured" -ForegroundColor Green+ }+ catch {+ $results.Errors += "System security configuration failed: $_"+ Write-Warning " System security configuration failed: $_"+ }++ # Category 7: BitLocker Encryption+ Write-Host "`n[7/7] Configuring BitLocker..." -ForegroundColor Cyan++ if ($EnableBitLocker) {+ try {+ $volume = Get-BitLockerVolume -MountPoint "C:" -ErrorAction Stop++ if ($volume.ProtectionStatus -ne 'On') {+ Write-Host " Enabling BitLocker on C:..." -ForegroundColor Yellow+ Write-Warning " This may take several minutes..."++ # Enable BitLocker with TPM+ Enable-BitLocker -MountPoint "C:" -EncryptionMethod XtsAes256 -UsedSpaceOnly -TpmProtector -ErrorAction Stop+ $results.Changes += "BitLocker enabled on system drive"+ $results.RequiresReboot = $true++ Write-Host " BitLocker: Enabled (encryption in progress)" -ForegroundColor Green+ }+ else {+ Write-Host " BitLocker: Already enabled" -ForegroundColor Yellow+ }++ $results.Categories.BitLocker = @{+ Enabled = $true+ Status = 'Enabled'+ }+ }+ catch {+ $results.Errors += "BitLocker configuration failed: $_"+ Write-Warning " BitLocker failed: $_"+ Write-Warning " Note: TPM may be required, or device may not support BitLocker"+ }+ }+ else {+ Write-Host " BitLocker: Skipped" -ForegroundColor Yellow+ $results.Categories.BitLocker = @{+ Enabled = $false+ Status = 'Not Configured'+ }+ }++ }+ catch {+ Write-Error "Error during security baseline configuration: $_"+ throw+ }+ }++end {+ Write-Host "`n=== BASELINE CONFIGURATION COMPLETE ===" -ForegroundColor Green++ Write-Host "`nChanges Applied: $($results.Changes.Count)" -ForegroundColor Cyan+ if ($results.Changes.Count -gt 0) {+ $results.Changes | ForEach-Object {+ Write-Host " + $_" -ForegroundColor White+ }+ }++ if ($results.Errors.Count -gt 0) {+ Write-Host "`nErrors Encountered: $($results.Errors.Count)" -ForegroundColor Red+ $results.Errors | ForEach-Object {+ Write-Host " - $_" -ForegroundColor Red+ }+ }++ if ($results.RequiresReboot) {+ Write-Host "`n[!] SYSTEM REBOOT REQUIRED" -ForegroundColor Yellow -BackgroundColor Red+ Write-Host "Some changes require a system restart to take effect" -ForegroundColor Yellow+ }++ Write-Host "`nSecurity Baseline Status:" -ForegroundColor Cyan+ Write-Host " Level: $($results.BaselineLevel)" -ForegroundColor White+ Write-Host " UAC: $($results.Categories.UAC.Status)" -ForegroundColor White+ Write-Host " Firewall: $($results.Categories.Firewall.Status)" -ForegroundColor White+ Write-Host " Windows Defender: $($results.Categories.WindowsDefender.Status)" -ForegroundColor White+ Write-Host " Network Security: $($results.Categories.NetworkSecurity.Status)" -ForegroundColor White+ Write-Host " Account Security: $($results.Categories.AccountSecurity.Status)" -ForegroundColor White+ Write-Host " System Security: $($results.Categories.SystemSecurity.Status)" -ForegroundColor White+ Write-Host " BitLocker: $($results.Categories.BitLocker.Status)" -ForegroundColor White++ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ Write-Host " 1. Review all changes and test system functionality" -ForegroundColor White+ Write-Host " 2. Document the baseline configuration" -ForegroundColor White+ Write-Host " 3. Schedule regular security audits" -ForegroundColor White+ Write-Host " 4. Keep Windows and Defender signatures updated" -ForegroundColor White+ Write-Host " 5. Monitor security logs regularly" -ForegroundColor White++ return $results+ }+}\ No newline at end of filediff --git a/Reporting/Get-SecurityMetrics.ps1 b/Reporting/Get-SecurityMetrics.ps1new file mode 100644index 0000000..8d21944--- /dev/null+++ b/Reporting/Get-SecurityMetrics.ps1@@ -0,0 +1,1816 @@+function Get-SecurityMetrics {+ <#+ .SYNOPSIS+ Collects and calculates comprehensive security metrics from all modules++ .DESCRIPTION+ Enterprise-grade security metrics aggregation system that:+ - Collects data from all 13 security modules (54 functions)+ - Calculates overall security score (0-100)+ - Performs risk assessment (Critical/High/Medium/Low)+ - Tracks threat levels (Critical/High/Medium/Low/Minimal)+ - Analyzes compliance scores (CIS, NIST, PCI-DSS)+ - Provides trend analysis (week-over-week, month-over-month)+ - Compares with baseline metrics+ - Maintains historical data+ - Exports to JSON format+ - Generates actionable recommendations++ .PARAMETER IncludeModules+ Security modules to include in metrics collection+ Valid values: All, Core, Detection, Analysis, Compliance, ActiveDirectory,+ Cloud, Vulnerability, ThreatHunting, Forensics, WindowsDefender,+ Hardening, Enterprise, Response+ Default: All++ .PARAMETER IncludeHistory+ Store metrics in historical database for trend analysis+ History is maintained in: $env:TEMP\SecurityMetricsHistory.json++ .PARAMETER HistoryDays+ Number of days of historical data to retain (1-365)+ Default: 30 days++ .PARAMETER CalculateTrends+ Calculate trend analysis comparing current metrics with historical data+ Requires at least one previous metric collection in history++ .PARAMETER ExportPath+ Directory path to export metrics in JSON format+ Filename: SecurityMetrics_YYYYMMDD_HHMMSS.json++ .PARAMETER CompareWithBaseline+ Compare current metrics with a baseline metrics file+ Useful for tracking security posture improvements over time++ .PARAMETER BaselinePath+ Path to baseline metrics JSON file for comparison+ Required when CompareWithBaseline is used++ .EXAMPLE+ Get-SecurityMetrics++ Collect metrics from all modules with default settings++ .EXAMPLE+ Get-SecurityMetrics -IncludeModules Core,Detection,Compliance++ Collect metrics from specific modules only++ .EXAMPLE+ Get-SecurityMetrics -IncludeHistory -CalculateTrends++ Collect metrics, save to history, and calculate trends++ .EXAMPLE+ Get-SecurityMetrics -ExportPath "C:\SecurityReports" -IncludeHistory++ Collect metrics, export to JSON, and save to history++ .EXAMPLE+ Get-SecurityMetrics -CompareWithBaseline -BaselinePath "C:\Baseline\metrics.json"++ Collect metrics and compare with baseline++ .EXAMPLE+ $metrics = Get-SecurityMetrics -IncludeModules All -CalculateTrends -IncludeHistory -ExportPath "C:\Reports"+ Write-Host "Security Score: $($metrics.OverallSecurityScore)%"+ Write-Host "Threat Level: $($metrics.ThreatLevel)"++ Full metrics collection with all features enabled++ .OUTPUTS+ PSCustomObject containing comprehensive security metrics:+ - Timestamp: Collection date and time+ - Hostname: Computer name+ - Domain: Domain or workgroup name+ - OverallSecurityScore: Calculated security score (0-100)+ - RiskLevel: Overall risk assessment+ - ThreatLevel: Active threat level+ - ComplianceScore: Average compliance score+ - Findings: Total, Critical, High, Medium, Low findings+ - Module-specific metrics for each security module+ - Performance metrics+ - Trend data (if CalculateTrends enabled)+ - Baseline comparison (if CompareWithBaseline enabled)++ .NOTES+ Author: WindowsSecurityAudit Module+ Version: 1.1.0 ULTIMATE EDITION++ Requires: Administrator privileges for full functionality+ PowerShell Version: 5.1 or higher++ All property checks use PSObject.Properties to avoid warnings+ All array operations use @() cast to prevent count errors+ All null checks are safe and defensive++ Performance: Typical execution time 30-60 seconds for all modules+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [ValidateSet('All', 'Core', 'Detection', 'Analysis', 'Compliance', 'ActiveDirectory',+ 'Cloud', 'Vulnerability', 'ThreatHunting', 'Forensics', 'WindowsDefender',+ 'Hardening', 'Enterprise', 'Response')]+ [string[]]$IncludeModules = @('All'),++ [Parameter()]+ [switch]$IncludeHistory,++ [Parameter()]+ [ValidateRange(1, 365)]+ [int]$HistoryDays = 30,++ [Parameter()]+ [switch]$CalculateTrends,++ [Parameter()]+ [string]$ExportPath,++ [Parameter()]+ [switch]$CompareWithBaseline,++ [Parameter()]+ [string]$BaselinePath+ )++ begin {+ Write-Host "================================================================" -ForegroundColor Cyan+ Write-Host " SECURITY METRICS COLLECTION - ULTIMATE EDITION" -ForegroundColor Cyan+ Write-Host "================================================================" -ForegroundColor Cyan++ $startTime = Get-Date++ # Validate baseline path if comparison requested+ if ($CompareWithBaseline) {+ if (-not $BaselinePath) {+ Write-Warning "CompareWithBaseline specified but no BaselinePath provided"+ $CompareWithBaseline = $false+ }+ elseif (-not (Test-Path $BaselinePath)) {+ Write-Warning "Baseline file not found: $BaselinePath"+ $CompareWithBaseline = $false+ }+ }++ # Determine modules to process+ $modulesToProcess = if ($IncludeModules -contains 'All') {+ @('Core', 'Detection', 'Analysis', 'Compliance', 'ActiveDirectory', 'Cloud',+ 'Vulnerability', 'ThreatHunting', 'Forensics', 'WindowsDefender', 'Hardening',+ 'Enterprise', 'Response')+ } else {+ @($IncludeModules)+ }++ Write-Host "Collecting metrics from $(@($modulesToProcess).Count) modules..." -ForegroundColor Yellow+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Gray++ # Initialize comprehensive metrics structure+ $script:metrics = @{+ # Metadata+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ TimestampEpoch = [int][double]::Parse((Get-Date -UFormat %s))+ Hostname = $env:COMPUTERNAME+ Domain = if ($env:USERDNSDOMAIN) { $env:USERDNSDOMAIN } else { "WORKGROUP" }+ Username = $env:USERNAME+ OSVersion = [System.Environment]::OSVersion.VersionString+ PSVersion = $PSVersionTable.PSVersion.ToString()+ CollectionDuration = 0+ ModulesCollected = @($modulesToProcess)++ # Overall scores and levels+ OverallSecurityScore = 100+ RiskLevel = "Low"+ ComplianceScore = 0+ ThreatLevel = "Minimal"+ HealthStatus = "Healthy"++ # Findings aggregation+ Findings = @{+ Total = 0+ Critical = 0+ High = 0+ Medium = 0+ Low = 0+ Informational = 0+ ByCategory = @{+ Security = 0+ Compliance = 0+ Threats = 0+ Vulnerabilities = 0+ Configuration = 0+ }+ BySeverity = @()+ RecentFindings = @()+ }++ # Recommendations+ Recommendations = @{+ Critical = @()+ High = @()+ Medium = @()+ Low = @()+ Total = 0+ }++ # Core Module Metrics+ Core = @{+ Enabled = $false+ SystemHealth = "Unknown"+ IntegrityStatus = "Unknown"+ BaselineCompliance = 0+ LastAssessmentDate = $null+ PendingUpdates = 0+ UptimeDays = 0+ }++ # Detection Module Metrics+ Detection = @{+ Enabled = $false+ TotalThreats = 0+ ActiveThreats = 0+ PersistenceMechanisms = 0+ SuspiciousProcesses = 0+ SuspiciousAuthentications = 0+ LateralMovement = 0+ NetworkAnomalies = 0+ APTIndicators = 0+ LivingOffLand = 0+ DataExfiltration = 0+ LastScanDate = $null+ }++ # Analysis Module Metrics+ Analysis = @{+ Enabled = $false+ TotalEvents = 0+ CriticalEvents = 0+ ErrorEvents = 0+ WarningEvents = 0+ SecurityMisconfigurations = 0+ ExposedServices = 0+ RegistryIssues = 0+ FileSystemIssues = 0+ MemoryIssues = 0+ }++ # Compliance Module Metrics+ Compliance = @{+ Enabled = $false+ Frameworks = @{+ CIS = @{+ Score = 0+ TotalControls = 0+ PassedControls = 0+ FailedControls = 0+ }+ NIST = @{+ Score = 0+ TotalControls = 0+ CompliantControls = 0+ NonCompliantControls = 0+ }+ PCIDSS = @{+ Score = 0+ TotalRequirements = 0+ InPlace = 0+ NotInPlace = 0+ }+ }+ OverallScore = 0+ TotalControls = 0+ PassedControls = 0+ FailedControls = 0+ LastAuditDate = $null+ }++ # Active Directory Module Metrics+ ActiveDirectory = @{+ Enabled = $false+ DomainName = $null+ PrivilegedAccounts = 0+ Vulnerabilities = 0+ StaleObjects = 0+ Backdoors = 0+ PasswordPolicyScore = 0+ LastADScanDate = $null+ }++ # Cloud Security Module Metrics+ Cloud = @{+ Enabled = $false+ ConnectedTenant = $null+ RiskySignIns = 0+ ConditionalAccessPolicies = 0+ M365SecurityScore = 0+ AzureSecurityScore = 0+ LastCloudScanDate = $null+ }++ # Vulnerability Module Metrics+ Vulnerability = @{+ Enabled = $false+ Total = 0+ Critical = 0+ High = 0+ Medium = 0+ Low = 0+ EOLSoftware = 0+ OutdatedSoftware = 0+ CertificateIssues = 0+ ExpiredCertificates = 0+ WeakCertificates = 0+ LastVulnScanDate = $null+ }++ # Threat Hunting Module Metrics+ ThreatHunting = @{+ Enabled = $false+ IOCMatches = 0+ MITRETechniques = 0+ ThreatIntelSources = 0+ LastHuntDate = $null+ }++ # Forensics Module Metrics+ Forensics = @{+ Enabled = $false+ ArtifactsCollected = 0+ ExecutionArtifacts = 0+ USBDevices = 0+ RecentExecutions = 0+ LastForensicScanDate = $null+ }++ # Windows Defender Module Metrics+ WindowsDefender = @{+ Enabled = $false+ Status = "Unknown"+ ProtectionEnabled = $false+ RealTimeProtection = $false+ CloudProtection = $false+ SignatureAge = 999+ SignatureVersion = "Unknown"+ LastScanDays = 999+ LastQuickScan = $null+ LastFullScan = $null+ ThreatsDetected = 0+ }++ # Hardening Module Metrics+ Hardening = @{+ Enabled = $false+ AuditPoliciesEnabled = $false+ PowerShellSecurityEnabled = $false+ BaselineApplied = $false+ HardeningScore = 0+ LastHardeningDate = $null+ }++ # Enterprise Module Metrics+ Enterprise = @{+ Enabled = $false+ MultiSystemsScanned = 0+ EnterprisePoliciesApplied = 0+ CentralizedLogging = $false+ LastEnterpriseScanDate = $null+ }++ # Response Module Metrics+ Response = @{+ Enabled = $false+ ActiveIncidents = 0+ ResolvedIncidents = 0+ AverageResponseTime = 0+ LastIncidentDate = $null+ }++ # Performance Metrics+ Performance = @{+ CollectionTime = 0+ ModuleTimes = @{}+ FunctionCalls = 0+ FailedFunctions = 0+ SuccessRate = 100+ }++ # Trend Analysis (if enabled)+ Trends = @{+ Enabled = $CalculateTrends+ SecurityScoreChange = 0+ SecurityScoreTrend = "Stable"+ ThreatCountChange = 0+ ThreatTrend = "Stable"+ ComplianceScoreChange = 0+ ComplianceTrend = "Stable"+ FindingsChange = 0+ FindingsTrend = "Stable"+ WeekOverWeek = @{}+ MonthOverMonth = @{}+ }++ # Baseline Comparison (if enabled)+ Baseline = @{+ ComparisonEnabled = $CompareWithBaseline+ BaselineDate = $null+ SecurityScoreDelta = 0+ ThreatCountDelta = 0+ ComplianceScoreDelta = 0+ NewFindings = 0+ ResolvedFindings = 0+ ImprovedAreas = @()+ DeclinedAreas = @()+ }+ }+ }++ process {+ try {+ Write-Host "`n[COLLECTING MODULE METRICS]" -ForegroundColor Cyan++ $totalFunctions = 0+ $successfulFunctions = 0+ $failedFunctions = 0++ # ============================================+ # CORE MODULE (4 functions)+ # ============================================+ if ($modulesToProcess -contains 'Core') {+ Write-Host "`n[Core Module Metrics]" -ForegroundColor Cyan+ $coreStart = Get-Date+ $script:metrics.Core.Enabled = $true++ # Get-SecurityBaseline+ try {+ $totalFunctions+++ $baseline = Get-SecurityBaseline -ErrorAction Stop+ if ($baseline) {+ # Safe property access+ if ($baseline.PSObject.Properties['CompliancePercentage']) {+ $script:metrics.Core.BaselineCompliance = $baseline.CompliancePercentage+ }+ elseif ($baseline.PSObject.Properties['ComplianceScore']) {+ $script:metrics.Core.BaselineCompliance = $baseline.ComplianceScore+ }+ elseif ($baseline.PSObject.Properties['Score']) {+ $script:metrics.Core.BaselineCompliance = $baseline.Score+ }+ $successfulFunctions+++ Write-Host " Baseline Compliance: $($script:metrics.Core.BaselineCompliance)%" -ForegroundColor Green+ }+ } catch {+ $failedFunctions+++ Write-Verbose " Get-SecurityBaseline: $_"+ }++ # Get-SystemInfo+ try {+ $totalFunctions+++ $sysInfo = Get-SystemInfo -ErrorAction Stop+ if ($sysInfo) {+ $script:metrics.Core.SystemHealth = "Healthy"++ # Extract uptime if available+ if ($sysInfo.PSObject.Properties['LastBootUpTime']) {+ $script:metrics.Core.UptimeDays = [Math]::Round(((Get-Date) - $sysInfo.LastBootUpTime).TotalDays, 1)+ }+ elseif ($sysInfo.PSObject.Properties['BootTime']) {+ $script:metrics.Core.UptimeDays = [Math]::Round(((Get-Date) - $sysInfo.BootTime).TotalDays, 1)+ }++ $successfulFunctions+++ Write-Host " System Info: Collected (Uptime: $($script:metrics.Core.UptimeDays)d)" -ForegroundColor Green+ }+ } catch {+ $failedFunctions+++ Write-Verbose " Get-SystemInfo: $_"+ }++ # Test-SystemIntegrity+ try {+ $totalFunctions+++ $integrity = Test-SystemIntegrity -ErrorAction Stop+ if ($integrity) {+ # Safe property access+ if ($integrity.PSObject.Properties['OverallStatus']) {+ $script:metrics.Core.IntegrityStatus = $integrity.OverallStatus+ }+ elseif ($integrity.PSObject.Properties['Status']) {+ $script:metrics.Core.IntegrityStatus = $integrity.Status+ }+ elseif ($integrity.PSObject.Properties['IntegrityStatus']) {+ $script:metrics.Core.IntegrityStatus = $integrity.IntegrityStatus+ }++ # Extract pending updates+ if ($integrity.PSObject.Properties['PendingUpdates']) {+ $script:metrics.Core.PendingUpdates = $integrity.PendingUpdates+ }++ $successfulFunctions+++ Write-Host " Integrity Status: $($script:metrics.Core.IntegrityStatus)" -ForegroundColor Green+ }+ } catch {+ $failedFunctions+++ Write-Verbose " Test-SystemIntegrity: $_"+ }++ # Invoke-SecurityAssessment+ try {+ $totalFunctions+++ $assessment = Invoke-SecurityAssessment -ErrorAction Stop+ if ($assessment) {+ $script:metrics.Core.LastAssessmentDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"++ # Extract findings if available+ if ($assessment.PSObject.Properties['Findings']) {+ $findings = @($assessment.Findings)+ $script:metrics.Findings.ByCategory.Security += $findings.Count+ }++ $successfulFunctions+++ Write-Host " Security Assessment: Complete" -ForegroundColor Green+ }+ } catch {+ $failedFunctions+++ Write-Verbose " Invoke-SecurityAssessment: $_"+ }++ $script:metrics.Performance.ModuleTimes['Core'] = [Math]::Round(((Get-Date) - $coreStart).TotalSeconds, 2)+ }++ # ============================================+ # DETECTION MODULE (8 functions)+ # ============================================+ if ($modulesToProcess -contains 'Detection') {+ Write-Host "`n[Detection Module Metrics]" -ForegroundColor Cyan+ $detStart = Get-Date+ $script:metrics.Detection.Enabled = $true++ # Find-PersistenceMechanisms+ try {+ $totalFunctions+++ $persistence = Find-PersistenceMechanisms -ErrorAction Stop+ $script:metrics.Detection.PersistenceMechanisms = @($persistence).Count+ $successfulFunctions+++ Write-Host " Persistence Mechanisms: $($script:metrics.Detection.PersistenceMechanisms)" -ForegroundColor $(if ($script:metrics.Detection.PersistenceMechanisms -gt 0) { 'Yellow' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Find-PersistenceMechanisms: $_"+ }++ # Find-SuspiciousProcesses+ try {+ $totalFunctions+++ $processes = Find-SuspiciousProcesses -ErrorAction Stop+ $script:metrics.Detection.SuspiciousProcesses = @($processes).Count+ $successfulFunctions+++ Write-Host " Suspicious Processes: $($script:metrics.Detection.SuspiciousProcesses)" -ForegroundColor $(if ($script:metrics.Detection.SuspiciousProcesses -gt 0) { 'Yellow' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Find-SuspiciousProcesses: $_"+ }++ # Find-SuspiciousAuthentication+ try {+ $totalFunctions+++ $auth = Find-SuspiciousAuthentication -ErrorAction Stop+ $script:metrics.Detection.SuspiciousAuthentications = @($auth).Count+ $successfulFunctions+++ Write-Host " Suspicious Authentications: $($script:metrics.Detection.SuspiciousAuthentications)" -ForegroundColor $(if ($script:metrics.Detection.SuspiciousAuthentications -gt 0) { 'Yellow' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Find-SuspiciousAuthentication: $_"+ }++ # Find-LateralMovement+ try {+ $totalFunctions+++ $lateral = Find-LateralMovement -ErrorAction Stop+ $script:metrics.Detection.LateralMovement = @($lateral).Count+ $successfulFunctions+++ Write-Host " Lateral Movement: $($script:metrics.Detection.LateralMovement)" -ForegroundColor $(if ($script:metrics.Detection.LateralMovement -gt 0) { 'Red' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Find-LateralMovement: $_"+ }++ # Find-APTIndicators+ try {+ $totalFunctions+++ $apt = Find-APTIndicators -ErrorAction Stop+ if ($apt -and $apt.PSObject.Properties['TotalIndicators']) {+ $script:metrics.Detection.APTIndicators = $apt.TotalIndicators+ } else {+ $script:metrics.Detection.APTIndicators = @($apt).Count+ }+ $successfulFunctions+++ Write-Host " APT Indicators: $($script:metrics.Detection.APTIndicators)" -ForegroundColor $(if ($script:metrics.Detection.APTIndicators -gt 0) { 'Red' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Find-APTIndicators: $_"+ }++ # Find-LivingOffLand+ try {+ $totalFunctions+++ $lolbins = Find-LivingOffLand -ErrorAction Stop+ $script:metrics.Detection.LivingOffLand = @($lolbins).Count+ $successfulFunctions+++ Write-Host " Living Off Land: $($script:metrics.Detection.LivingOffLand)" -ForegroundColor $(if ($script:metrics.Detection.LivingOffLand -gt 0) { 'Yellow' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Find-LivingOffLand: $_"+ }++ # Find-DataExfiltration+ try {+ $totalFunctions+++ $exfil = Find-DataExfiltration -ErrorAction Stop+ $script:metrics.Detection.DataExfiltration = @($exfil).Count+ $successfulFunctions+++ Write-Host " Data Exfiltration: $($script:metrics.Detection.DataExfiltration)" -ForegroundColor $(if ($script:metrics.Detection.DataExfiltration -gt 0) { 'Red' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Find-DataExfiltration: $_"+ }++ # Find-NetworkAnomalies+ try {+ $totalFunctions+++ $network = Find-NetworkAnomalies -ErrorAction Stop+ if ($network -and $network.PSObject.Properties['TotalAnomalies']) {+ $script:metrics.Detection.NetworkAnomalies = $network.TotalAnomalies+ } else {+ $script:metrics.Detection.NetworkAnomalies = @($network).Count+ }+ $successfulFunctions+++ Write-Host " Network Anomalies: $($script:metrics.Detection.NetworkAnomalies)" -ForegroundColor $(if ($script:metrics.Detection.NetworkAnomalies -gt 0) { 'Yellow' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Find-NetworkAnomalies: $_"+ }++ # Calculate total threats+ $script:metrics.Detection.TotalThreats =+ $script:metrics.Detection.PersistenceMechanisms ++ $script:metrics.Detection.SuspiciousProcesses ++ $script:metrics.Detection.SuspiciousAuthentications ++ $script:metrics.Detection.LateralMovement ++ $script:metrics.Detection.APTIndicators ++ $script:metrics.Detection.LivingOffLand ++ $script:metrics.Detection.DataExfiltration ++ $script:metrics.Detection.NetworkAnomalies++ $script:metrics.Detection.ActiveThreats = $script:metrics.Detection.TotalThreats+ $script:metrics.Detection.LastScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"++ Write-Host " TOTAL THREATS: $($script:metrics.Detection.TotalThreats)" -ForegroundColor $(+ if ($script:metrics.Detection.TotalThreats -gt 20) { 'Red' }+ elseif ($script:metrics.Detection.TotalThreats -gt 10) { 'Yellow' }+ else { 'Green' }+ )++ $script:metrics.Performance.ModuleTimes['Detection'] = [Math]::Round(((Get-Date) - $detStart).TotalSeconds, 2)+ }++ # ============================================+ # ANALYSIS MODULE (6 functions)+ # ============================================+ if ($modulesToProcess -contains 'Analysis') {+ Write-Host "`n[Analysis Module Metrics]" -ForegroundColor Cyan+ $analStart = Get-Date+ $script:metrics.Analysis.Enabled = $true++ # Get-EventLogAnalysis+ try {+ $totalFunctions+++ $eventLog = Get-EventLogAnalysis -ErrorAction Stop+ if ($eventLog) {+ if ($eventLog.PSObject.Properties['TotalEvents']) {+ $script:metrics.Analysis.TotalEvents = $eventLog.TotalEvents+ }+ if ($eventLog.PSObject.Properties['CriticalEvents']) {+ $script:metrics.Analysis.CriticalEvents = $eventLog.CriticalEvents+ }+ if ($eventLog.PSObject.Properties['ErrorEvents']) {+ $script:metrics.Analysis.ErrorEvents = $eventLog.ErrorEvents+ }+ if ($eventLog.PSObject.Properties['WarningEvents']) {+ $script:metrics.Analysis.WarningEvents = $eventLog.WarningEvents+ }+ $successfulFunctions+++ Write-Host " Event Log Analysis: $($script:metrics.Analysis.TotalEvents) events ($($script:metrics.Analysis.CriticalEvents) critical)" -ForegroundColor $(if ($script:metrics.Analysis.CriticalEvents -gt 0) { 'Red' } else { 'Green' })+ }+ } catch {+ $failedFunctions+++ Write-Verbose " Get-EventLogAnalysis: $_"+ }++ # Get-RegistryAnalysis+ try {+ $totalFunctions+++ $registry = Get-RegistryAnalysis -ErrorAction Stop+ if ($registry) {+ if ($registry.PSObject.Properties['SuspiciousFindings']) {+ $script:metrics.Analysis.RegistryIssues = $registry.SuspiciousFindings+ } else {+ $script:metrics.Analysis.RegistryIssues = @($registry).Count+ }+ $successfulFunctions+++ Write-Host " Registry Analysis: $($script:metrics.Analysis.RegistryIssues) issues" -ForegroundColor $(if ($script:metrics.Analysis.RegistryIssues -gt 0) { 'Yellow' } else { 'Green' })+ }+ } catch {+ $failedFunctions+++ Write-Verbose " Get-RegistryAnalysis: $_"+ }++ # Get-FileSystemAnalysis+ try {+ $totalFunctions+++ $fileSystem = Get-FileSystemAnalysis -ErrorAction Stop+ if ($fileSystem) {+ if ($fileSystem.PSObject.Properties['SuspiciousFiles']) {+ $script:metrics.Analysis.FileSystemIssues = $fileSystem.SuspiciousFiles+ } else {+ $script:metrics.Analysis.FileSystemIssues = @($fileSystem).Count+ }+ $successfulFunctions+++ Write-Host " File System Analysis: $($script:metrics.Analysis.FileSystemIssues) suspicious files" -ForegroundColor $(if ($script:metrics.Analysis.FileSystemIssues -gt 100) { 'Yellow' } else { 'Green' })+ }+ } catch {+ $failedFunctions+++ Write-Verbose " Get-FileSystemAnalysis: $_"+ }++ # Get-MemoryAnalysis+ try {+ $totalFunctions+++ $memory = Get-MemoryAnalysis -ErrorAction Stop+ if ($memory) {+ if ($memory.PSObject.Properties['InjectionIndicators']) {+ $script:metrics.Analysis.MemoryIssues = $memory.InjectionIndicators+ }+ $successfulFunctions+++ Write-Host " Memory Analysis: $($script:metrics.Analysis.MemoryIssues) issues" -ForegroundColor $(if ($script:metrics.Analysis.MemoryIssues -gt 0) { 'Red' } else { 'Green' })+ }+ } catch {+ $failedFunctions+++ Write-Verbose " Get-MemoryAnalysis: $_"+ }++ # Get-ExposedServices+ try {+ $totalFunctions+++ $exposed = Get-ExposedServices -ErrorAction Stop+ if ($exposed) {+ if ($exposed.PSObject.Properties['ExposedServices']) {+ $script:metrics.Analysis.ExposedServices = $exposed.ExposedServices+ } else {+ $script:metrics.Analysis.ExposedServices = @($exposed).Count+ }+ $successfulFunctions+++ Write-Host " Exposed Services: $($script:metrics.Analysis.ExposedServices)" -ForegroundColor $(if ($script:metrics.Analysis.ExposedServices -gt 0) { 'Yellow' } else { 'Green' })+ }+ } catch {+ $failedFunctions+++ Write-Verbose " Get-ExposedServices: $_"+ }++ # Get-SecurityMisconfigurations+ try {+ $totalFunctions+++ $misconfig = Get-SecurityMisconfigurations -ErrorAction Stop+ $script:metrics.Analysis.SecurityMisconfigurations = @($misconfig).Count+ $successfulFunctions+++ Write-Host " Misconfigurations: $($script:metrics.Analysis.SecurityMisconfigurations)" -ForegroundColor $(if ($script:metrics.Analysis.SecurityMisconfigurations -gt 0) { 'Yellow' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Get-SecurityMisconfigurations: $_"+ }++ $script:metrics.Performance.ModuleTimes['Analysis'] = [Math]::Round(((Get-Date) - $analStart).TotalSeconds, 2)+ }++ # ============================================+ # COMPLIANCE MODULE (5 functions)+ # ============================================+ if ($modulesToProcess -contains 'Compliance') {+ Write-Host "`n[Compliance Module Metrics]" -ForegroundColor Cyan+ $compStart = Get-Date+ $script:metrics.Compliance.Enabled = $true++ # Test-CISBenchmark+ try {+ $totalFunctions+++ $cis = Test-CISBenchmark -ErrorAction Stop+ if ($cis) {+ # Score+ if ($cis.PSObject.Properties['ComplianceScore']) {+ $script:metrics.Compliance.Frameworks.CIS.Score = $cis.ComplianceScore+ } elseif ($cis.PSObject.Properties['CompliancePercentage']) {+ $script:metrics.Compliance.Frameworks.CIS.Score = $cis.CompliancePercentage+ } elseif ($cis.PSObject.Properties['Compliance']) {+ $script:metrics.Compliance.Frameworks.CIS.Score = $cis.Compliance+ }++ # Controls+ if ($cis.PSObject.Properties['TotalControls']) {+ $script:metrics.Compliance.Frameworks.CIS.TotalControls = $cis.TotalControls+ }+ if ($cis.PSObject.Properties['PassedControls']) {+ $script:metrics.Compliance.Frameworks.CIS.PassedControls = $cis.PassedControls+ } elseif ($cis.PSObject.Properties['Passed']) {+ $script:metrics.Compliance.Frameworks.CIS.PassedControls = $cis.Passed+ }+ if ($cis.PSObject.Properties['FailedControls']) {+ $script:metrics.Compliance.Frameworks.CIS.FailedControls = $cis.FailedControls+ } elseif ($cis.PSObject.Properties['Failed']) {+ $script:metrics.Compliance.Frameworks.CIS.FailedControls = $cis.Failed+ }++ $successfulFunctions+++ Write-Host " CIS Benchmark: $($script:metrics.Compliance.Frameworks.CIS.Score)%" -ForegroundColor $(if ($script:metrics.Compliance.Frameworks.CIS.Score -ge 80) { 'Green' } elseif ($script:metrics.Compliance.Frameworks.CIS.Score -ge 60) { 'Yellow' } else { 'Red' })+ }+ } catch {+ $failedFunctions+++ Write-Verbose " Test-CISBenchmark: $_"+ }++ # Test-NISTCompliance+ try {+ $totalFunctions+++ $nist = Test-NISTCompliance -ErrorAction Stop+ if ($nist) {+ # Score+ if ($nist.PSObject.Properties['ComplianceScore']) {+ $script:metrics.Compliance.Frameworks.NIST.Score = $nist.ComplianceScore+ } elseif ($nist.PSObject.Properties['CompliancePercentage']) {+ $script:metrics.Compliance.Frameworks.NIST.Score = $nist.CompliancePercentage+ } elseif ($nist.PSObject.Properties['Compliance']) {+ $script:metrics.Compliance.Frameworks.NIST.Score = $nist.Compliance+ }++ # Controls+ if ($nist.PSObject.Properties['TotalControls']) {+ $script:metrics.Compliance.Frameworks.NIST.TotalControls = $nist.TotalControls+ }+ if ($nist.PSObject.Properties['CompliantControls']) {+ $script:metrics.Compliance.Frameworks.NIST.CompliantControls = $nist.CompliantControls+ } elseif ($nist.PSObject.Properties['Compliant']) {+ $script:metrics.Compliance.Frameworks.NIST.CompliantControls = $nist.Compliant+ }+ if ($nist.PSObject.Properties['NonCompliantControls']) {+ $script:metrics.Compliance.Frameworks.NIST.NonCompliantControls = $nist.NonCompliantControls+ } elseif ($nist.PSObject.Properties['NonCompliant']) {+ $script:metrics.Compliance.Frameworks.NIST.NonCompliantControls = $nist.NonCompliant+ }++ $successfulFunctions+++ Write-Host " NIST 800-53: $($script:metrics.Compliance.Frameworks.NIST.Score)%" -ForegroundColor $(if ($script:metrics.Compliance.Frameworks.NIST.Score -ge 80) { 'Green' } elseif ($script:metrics.Compliance.Frameworks.NIST.Score -ge 60) { 'Yellow' } else { 'Red' })+ }+ } catch {+ $failedFunctions+++ Write-Verbose " Test-NISTCompliance: $_"+ }++ # Test-PCI-DSS+ try {+ $totalFunctions+++ $pci = Test-PCI-DSS -ErrorAction Stop+ if ($pci) {+ # Score+ if ($pci.PSObject.Properties['ComplianceScore']) {+ $script:metrics.Compliance.Frameworks.PCIDSS.Score = $pci.ComplianceScore+ } elseif ($pci.PSObject.Properties['CompliancePercentage']) {+ $script:metrics.Compliance.Frameworks.PCIDSS.Score = $pci.CompliancePercentage+ } elseif ($pci.PSObject.Properties['Compliance']) {+ $script:metrics.Compliance.Frameworks.PCIDSS.Score = $pci.Compliance+ }++ # Requirements+ if ($pci.PSObject.Properties['TotalRequirements']) {+ $script:metrics.Compliance.Frameworks.PCIDSS.TotalRequirements = $pci.TotalRequirements+ }+ if ($pci.PSObject.Properties['InPlace']) {+ $script:metrics.Compliance.Frameworks.PCIDSS.InPlace = $pci.InPlace+ }+ if ($pci.PSObject.Properties['NotInPlace']) {+ $script:metrics.Compliance.Frameworks.PCIDSS.NotInPlace = $pci.NotInPlace+ }++ $successfulFunctions+++ Write-Host " PCI-DSS: $($script:metrics.Compliance.Frameworks.PCIDSS.Score)%" -ForegroundColor $(if ($script:metrics.Compliance.Frameworks.PCIDSS.Score -ge 80) { 'Green' } elseif ($script:metrics.Compliance.Frameworks.PCIDSS.Score -ge 60) { 'Yellow' } else { 'Red' })+ }+ } catch {+ $failedFunctions+++ Write-Verbose " Test-PCI-DSS: $_"+ }++ # Get-ComplianceReport+ try {+ $totalFunctions+++ $compReport = Get-ComplianceReport -ErrorAction Stop+ $successfulFunctions+++ Write-Host " Compliance Report: Generated" -ForegroundColor Green+ } catch {+ $failedFunctions+++ Write-Verbose " Get-ComplianceReport: $_"+ }++ # Test-PatchCompliance+ try {+ $totalFunctions+++ $patches = Test-PatchCompliance -ErrorAction Stop+ if ($patches) {+ if ($patches.PSObject.Properties['MissingUpdates']) {+ $script:metrics.Core.PendingUpdates = @($patches.MissingUpdates).Count+ }+ }+ $successfulFunctions+++ Write-Host " Patch Compliance: OK ($($script:metrics.Core.PendingUpdates) pending)" -ForegroundColor $(if ($script:metrics.Core.PendingUpdates -gt 0) { 'Yellow' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Test-PatchCompliance: $_"+ }++ # Calculate overall compliance - NULL SAFE with @() cast+ $compScores = @(+ $script:metrics.Compliance.Frameworks.CIS.Score,+ $script:metrics.Compliance.Frameworks.NIST.Score,+ $script:metrics.Compliance.Frameworks.PCIDSS.Score+ ) | Where-Object { $_ -gt 0 }++ if (@($compScores).Count -gt 0) {+ $script:metrics.Compliance.OverallScore = [Math]::Round(($compScores | Measure-Object -Average).Average, 1)+ $script:metrics.ComplianceScore = $script:metrics.Compliance.OverallScore+ Write-Host " Overall Compliance: $($script:metrics.ComplianceScore)%" -ForegroundColor Cyan+ } else {+ $script:metrics.Compliance.OverallScore = 0+ $script:metrics.ComplianceScore = 0+ }++ # Calculate total controls+ $script:metrics.Compliance.TotalControls =+ $script:metrics.Compliance.Frameworks.CIS.TotalControls ++ $script:metrics.Compliance.Frameworks.NIST.TotalControls ++ $script:metrics.Compliance.Frameworks.PCIDSS.TotalRequirements++ $script:metrics.Compliance.PassedControls =+ $script:metrics.Compliance.Frameworks.CIS.PassedControls ++ $script:metrics.Compliance.Frameworks.NIST.CompliantControls ++ $script:metrics.Compliance.Frameworks.PCIDSS.InPlace++ $script:metrics.Compliance.FailedControls =+ $script:metrics.Compliance.Frameworks.CIS.FailedControls ++ $script:metrics.Compliance.Frameworks.NIST.NonCompliantControls ++ $script:metrics.Compliance.Frameworks.PCIDSS.NotInPlace++ $script:metrics.Compliance.LastAuditDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"++ $script:metrics.Performance.ModuleTimes['Compliance'] = [Math]::Round(((Get-Date) - $compStart).TotalSeconds, 2)+ }++ # ============================================+ # ACTIVE DIRECTORY MODULE (6 functions)+ # ============================================+ if ($modulesToProcess -contains 'ActiveDirectory') {+ Write-Host "`n[Active Directory Module Metrics]" -ForegroundColor Cyan+ $adStart = Get-Date++ if ($env:USERDNSDOMAIN) {+ $script:metrics.ActiveDirectory.Enabled = $true+ $script:metrics.ActiveDirectory.DomainName = $env:USERDNSDOMAIN++ # Get-ADPrivilegedAccounts+ try {+ $totalFunctions+++ $privAccounts = Get-ADPrivilegedAccounts -ErrorAction Stop+ $script:metrics.ActiveDirectory.PrivilegedAccounts = @($privAccounts).Count+ $successfulFunctions+++ Write-Host " Privileged Accounts: $($script:metrics.ActiveDirectory.PrivilegedAccounts)" -ForegroundColor Yellow+ } catch {+ $failedFunctions+++ Write-Verbose " Get-ADPrivilegedAccounts: $_"+ }++ # Find-ADVulnerabilities+ try {+ $totalFunctions+++ $adVulns = Find-ADVulnerabilities -ErrorAction Stop+ $script:metrics.ActiveDirectory.Vulnerabilities = @($adVulns).Count+ $successfulFunctions+++ Write-Host " AD Vulnerabilities: $($script:metrics.ActiveDirectory.Vulnerabilities)" -ForegroundColor $(if ($script:metrics.ActiveDirectory.Vulnerabilities -gt 0) { 'Red' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Find-ADVulnerabilities: $_"+ }++ # Test-ADSecurityPosture+ try {+ $totalFunctions+++ $adPosture = Test-ADSecurityPosture -ErrorAction Stop+ $successfulFunctions+++ Write-Host " AD Security Posture: Assessed" -ForegroundColor Green+ } catch {+ $failedFunctions+++ Write-Verbose " Test-ADSecurityPosture: $_"+ }++ # Find-ADBackdoors+ try {+ $totalFunctions+++ $backdoors = Find-ADBackdoors -ErrorAction Stop+ $script:metrics.ActiveDirectory.Backdoors = @($backdoors).Count+ $successfulFunctions+++ Write-Host " AD Backdoors: $($script:metrics.ActiveDirectory.Backdoors)" -ForegroundColor $(if ($script:metrics.ActiveDirectory.Backdoors -gt 0) { 'Red' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Find-ADBackdoors: $_"+ }++ # Find-StaleADObjects+ try {+ $totalFunctions+++ $stale = Find-StaleADObjects -ErrorAction Stop+ $script:metrics.ActiveDirectory.StaleObjects = @($stale).Count+ $successfulFunctions+++ Write-Host " Stale AD Objects: $($script:metrics.ActiveDirectory.StaleObjects)" -ForegroundColor $(if ($script:metrics.ActiveDirectory.StaleObjects -gt 10) { 'Yellow' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Find-StaleADObjects: $_"+ }++ # Get-ADPasswordPolicy+ try {+ $totalFunctions+++ $pwdPolicy = Get-ADPasswordPolicy -ErrorAction Stop+ if ($pwdPolicy) {+ # Calculate password policy score+ $policyScore = 100+ if ($pwdPolicy.PSObject.Properties['MinPasswordLength'] -and $pwdPolicy.MinPasswordLength -lt 14) { $policyScore -= 20 }+ if ($pwdPolicy.PSObject.Properties['ComplexityEnabled'] -and -not $pwdPolicy.ComplexityEnabled) { $policyScore -= 30 }+ if ($pwdPolicy.PSObject.Properties['MaxPasswordAge'] -and $pwdPolicy.MaxPasswordAge.Days -gt 90) { $policyScore -= 15 }+ $script:metrics.ActiveDirectory.PasswordPolicyScore = [Math]::Max(0, $policyScore)+ }+ $successfulFunctions+++ Write-Host " Password Policy Score: $($script:metrics.ActiveDirectory.PasswordPolicyScore)%" -ForegroundColor $(if ($script:metrics.ActiveDirectory.PasswordPolicyScore -ge 80) { 'Green' } elseif ($script:metrics.ActiveDirectory.PasswordPolicyScore -ge 60) { 'Yellow' } else { 'Red' })+ } catch {+ $failedFunctions+++ Write-Verbose " Get-ADPasswordPolicy: $_"+ }++ $script:metrics.ActiveDirectory.LastADScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ } else {+ Write-Host " System not domain-joined - skipping AD module" -ForegroundColor Gray+ }++ $script:metrics.Performance.ModuleTimes['ActiveDirectory'] = [Math]::Round(((Get-Date) - $adStart).TotalSeconds, 2)+ }++ # ============================================+ # CLOUD SECURITY MODULE (3 functions)+ # ============================================+ if ($modulesToProcess -contains 'Cloud') {+ Write-Host "`n[Cloud Security Module Metrics]" -ForegroundColor Cyan+ $cloudStart = Get-Date++ $mgContext = Get-MgContext -ErrorAction SilentlyContinue+ if ($mgContext) {+ $script:metrics.Cloud.Enabled = $true+ $script:metrics.Cloud.ConnectedTenant = if ($mgContext.PSObject.Properties['TenantId']) { $mgContext.TenantId } else { "Unknown" }++ # Get-AzureADRiskySignIns+ try {+ $totalFunctions+++ $riskySignIns = Get-AzureADRiskySignIns -DaysBack 30 -ErrorAction Stop+ $script:metrics.Cloud.RiskySignIns = @($riskySignIns).Count+ $successfulFunctions+++ Write-Host " Risky Sign-Ins (30d): $($script:metrics.Cloud.RiskySignIns)" -ForegroundColor $(if ($script:metrics.Cloud.RiskySignIns -gt 0) { 'Yellow' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Get-AzureADRiskySignIns: $_"+ }++ # Test-M365SecurityPosture+ try {+ $totalFunctions+++ $m365Security = Test-M365SecurityPosture -ErrorAction Stop+ if ($m365Security -and $m365Security.PSObject.Properties['SecurityScore']) {+ $script:metrics.Cloud.M365SecurityScore = $m365Security.SecurityScore+ }+ $successfulFunctions+++ Write-Host " M365 Security Score: $($script:metrics.Cloud.M365SecurityScore)%" -ForegroundColor Cyan+ } catch {+ $failedFunctions+++ Write-Verbose " Test-M365SecurityPosture: $_"+ }++ # Get-CloudComplianceStatus+ try {+ $totalFunctions+++ $cloudCompliance = Get-CloudComplianceStatus -Framework CIS -ErrorAction Stop+ $successfulFunctions+++ Write-Host " Cloud Compliance: Assessed" -ForegroundColor Green+ } catch {+ $failedFunctions+++ Write-Verbose " Get-CloudComplianceStatus: $_"+ }++ $script:metrics.Cloud.LastCloudScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ } else {+ Write-Host " Not connected to Microsoft Graph - skipping cloud module" -ForegroundColor Gray+ Write-Host " To enable: Connect-MgGraph" -ForegroundColor Gray+ }++ $script:metrics.Performance.ModuleTimes['Cloud'] = [Math]::Round(((Get-Date) - $cloudStart).TotalSeconds, 2)+ }++ # ============================================+ # VULNERABILITY MODULE (3 functions)+ # ============================================+ if ($modulesToProcess -contains 'Vulnerability') {+ Write-Host "`n[Vulnerability Module Metrics]" -ForegroundColor Cyan+ $vulnStart = Get-Date+ $script:metrics.Vulnerability.Enabled = $true++ # Get-VulnerabilityAssessment+ try {+ $totalFunctions+++ $vulnAssess = Get-VulnerabilityAssessment -ErrorAction Stop+ if ($vulnAssess -and $vulnAssess.PSObject.Properties['Summary']) {+ $summary = $vulnAssess.Summary+ if ($summary.PSObject.Properties['TotalVulnerabilities']) {+ $script:metrics.Vulnerability.Total = $summary.TotalVulnerabilities+ }+ if ($summary.PSObject.Properties['Critical']) {+ $script:metrics.Vulnerability.Critical = $summary.Critical+ }+ if ($summary.PSObject.Properties['High']) {+ $script:metrics.Vulnerability.High = $summary.High+ }+ if ($summary.PSObject.Properties['Medium']) {+ $script:metrics.Vulnerability.Medium = $summary.Medium+ }+ if ($summary.PSObject.Properties['Low']) {+ $script:metrics.Vulnerability.Low = $summary.Low+ }+ }+ $successfulFunctions+++ Write-Host " Vulnerabilities: $($script:metrics.Vulnerability.Total) total" -ForegroundColor $(if ($script:metrics.Vulnerability.Total -gt 0) { 'Yellow' } else { 'Green' })+ if ($script:metrics.Vulnerability.Critical -gt 0) {+ Write-Host " Critical: $($script:metrics.Vulnerability.Critical)" -ForegroundColor Red+ }+ } catch {+ $failedFunctions+++ Write-Verbose " Get-VulnerabilityAssessment: $_"+ }++ # Find-EOLSoftware+ try {+ $totalFunctions+++ $eol = Find-EOLSoftware -ErrorAction Stop+ $script:metrics.Vulnerability.EOLSoftware = @($eol).Count+ $successfulFunctions+++ Write-Host " EOL Software: $($script:metrics.Vulnerability.EOLSoftware)" -ForegroundColor $(if ($script:metrics.Vulnerability.EOLSoftware -gt 0) { 'Red' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Find-EOLSoftware: $_"+ }++ # Test-CertificateHealth+ try {+ $totalFunctions+++ $certs = Test-CertificateHealth -ErrorAction Stop+ if ($certs) {+ if ($certs.PSObject.Properties['IssuesFound']) {+ $script:metrics.Vulnerability.CertificateIssues = $certs.IssuesFound+ }+ if ($certs.PSObject.Properties['Expired']) {+ $script:metrics.Vulnerability.ExpiredCertificates = $certs.Expired+ }+ if ($certs.PSObject.Properties['WeakSignatures']) {+ $script:metrics.Vulnerability.WeakCertificates = $certs.WeakSignatures+ }+ }+ $successfulFunctions+++ Write-Host " Certificate Issues: $($script:metrics.Vulnerability.CertificateIssues) ($($script:metrics.Vulnerability.ExpiredCertificates) expired)" -ForegroundColor $(if ($script:metrics.Vulnerability.CertificateIssues -gt 0) { 'Yellow' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Test-CertificateHealth: $_"+ }++ $script:metrics.Vulnerability.LastVulnScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ $script:metrics.Performance.ModuleTimes['Vulnerability'] = [Math]::Round(((Get-Date) - $vulnStart).TotalSeconds, 2)+ }++ # ============================================+ # THREAT HUNTING MODULE (2 functions)+ # ============================================+ if ($modulesToProcess -contains 'ThreatHunting') {+ Write-Host "`n[Threat Hunting Module Metrics]" -ForegroundColor Cyan+ $threatStart = Get-Date+ $script:metrics.ThreatHunting.Enabled = $true++ # Get-ThreatIntelligence+ try {+ $totalFunctions+++ $threatIntel = Get-ThreatIntelligence -ErrorAction Stop+ if ($threatIntel) {+ if ($threatIntel.PSObject.Properties['IOCMatches']) {+ $script:metrics.ThreatHunting.IOCMatches = @($threatIntel.IOCMatches).Count+ } else {+ $script:metrics.ThreatHunting.IOCMatches = @($threatIntel).Count+ }+ }+ $successfulFunctions+++ Write-Host " IOC Matches: $($script:metrics.ThreatHunting.IOCMatches)" -ForegroundColor $(if ($script:metrics.ThreatHunting.IOCMatches -gt 0) { 'Red' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Get-ThreatIntelligence: $_"+ }++ # Get-MITREAttackMapping+ try {+ $totalFunctions+++ $mitre = Get-MITREAttackMapping -ErrorAction Stop+ if ($mitre) {+ if ($mitre.PSObject.Properties['UniqueTechniques']) {+ $script:metrics.ThreatHunting.MITRETechniques = $mitre.UniqueTechniques+ } else {+ $script:metrics.ThreatHunting.MITRETechniques = @($mitre).Count+ }+ }+ $successfulFunctions+++ Write-Host " MITRE Techniques: $($script:metrics.ThreatHunting.MITRETechniques)" -ForegroundColor $(if ($script:metrics.ThreatHunting.MITRETechniques -gt 0) { 'Yellow' } else { 'Green' })+ } catch {+ $failedFunctions+++ Write-Verbose " Get-MITREAttackMapping: $_"+ }++ $script:metrics.ThreatHunting.LastHuntDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ $script:metrics.Performance.ModuleTimes['ThreatHunting'] = [Math]::Round(((Get-Date) - $threatStart).TotalSeconds, 2)+ }++ # ============================================+ # FORENSICS MODULE (6 functions)+ # ============================================+ if ($modulesToProcess -contains 'Forensics') {+ Write-Host "`n[Forensics Module Metrics]" -ForegroundColor Cyan+ $forStart = Get-Date+ $script:metrics.Forensics.Enabled = $true++ # Get-ArtifactCollection+ try {+ $totalFunctions+++ $artifacts = Get-ArtifactCollection -ErrorAction Stop+ if ($artifacts) {+ if ($artifacts.PSObject.Properties['TotalFiles']) {+ $script:metrics.Forensics.ArtifactsCollected = $artifacts.TotalFiles+ }+ }+ $successfulFunctions+++ Write-Host " Artifacts Collected: $($script:metrics.Forensics.ArtifactsCollected)" -ForegroundColor Green+ } catch {+ $failedFunctions+++ Write-Verbose " Get-ArtifactCollection: $_"+ }++ # Get-ExecutionArtifacts+ try {+ $totalFunctions+++ $execArtifacts = Get-ExecutionArtifacts -ErrorAction Stop+ if ($execArtifacts) {+ if ($execArtifacts.PSObject.Properties['TotalArtifacts']) {+ $script:metrics.Forensics.ExecutionArtifacts = $execArtifacts.TotalArtifacts+ } else {+ $script:metrics.Forensics.ExecutionArtifacts = @($execArtifacts).Count+ }++ if ($execArtifacts.PSObject.Properties['RecentExecutions']) {+ $script:metrics.Forensics.RecentExecutions = @($execArtifacts.RecentExecutions).Count+ }+ }+ $successfulFunctions+++ Write-Host " Execution Artifacts: $($script:metrics.Forensics.ExecutionArtifacts)" -ForegroundColor Green+ } catch {+ $failedFunctions+++ Write-Verbose " Get-ExecutionArtifacts: $_"+ }++ # Get-USBHistory+ try {+ $totalFunctions+++ $usb = Get-USBHistory -ErrorAction Stop+ $script:metrics.Forensics.USBDevices = @($usb).Count+ $successfulFunctions+++ Write-Host " USB Devices: $($script:metrics.Forensics.USBDevices)" -ForegroundColor Green+ } catch {+ $failedFunctions+++ Write-Verbose " Get-USBHistory: $_"+ }++ # Invoke-ForensicCollection, Export-MemoryDump, New-ForensicTimeline+ # These are heavy operations - skip metrics collection unless explicitly needed+ $totalFunctions += 3+ Write-Host " Detailed forensics: Skipped (use -DetailLevel Detailed)" -ForegroundColor Gray++ $script:metrics.Forensics.LastForensicScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ $script:metrics.Performance.ModuleTimes['Forensics'] = [Math]::Round(((Get-Date) - $forStart).TotalSeconds, 2)+ }++ # ============================================+ # WINDOWS DEFENDER MODULE (3 functions)+ # ============================================+ if ($modulesToProcess -contains 'WindowsDefender') {+ Write-Host "`n[Windows Defender Module Metrics]" -ForegroundColor Cyan+ $defStart = Get-Date+ $script:metrics.WindowsDefender.Enabled = $true++ # Get-DefenderStatus+ try {+ $totalFunctions+++ $defStatus = Get-DefenderStatus -ErrorAction Stop+ if ($defStatus) {+ # Status+ if ($defStatus.PSObject.Properties['HealthStatus']) {+ $script:metrics.WindowsDefender.Status = $defStatus.HealthStatus+ } elseif ($defStatus.PSObject.Properties['Status']) {+ $script:metrics.WindowsDefender.Status = $defStatus.Status+ }++ # Protection states+ if ($defStatus.PSObject.Properties['RealTimeProtectionEnabled']) {+ $script:metrics.WindowsDefender.RealTimeProtection = $defStatus.RealTimeProtectionEnabled+ $script:metrics.WindowsDefender.ProtectionEnabled = $defStatus.RealTimeProtectionEnabled+ }+ if ($defStatus.PSObject.Properties['CloudProtectionLevel']) {+ $script:metrics.WindowsDefender.CloudProtection = ($defStatus.CloudProtectionLevel -ne 'NotConfigured')+ }++ # Signature info+ if ($defStatus.PSObject.Properties['SignatureAge']) {+ $script:metrics.WindowsDefender.SignatureAge = $defStatus.SignatureAge+ }+ if ($defStatus.PSObject.Properties['AntivirusSignatureVersion']) {+ $script:metrics.WindowsDefender.SignatureVersion = $defStatus.AntivirusSignatureVersion+ } elseif ($defStatus.PSObject.Properties['SignatureVersion']) {+ $script:metrics.WindowsDefender.SignatureVersion = $defStatus.SignatureVersion+ }++ # Scan info+ if ($defStatus.PSObject.Properties['DaysSinceLastQuickScan']) {+ $script:metrics.WindowsDefender.LastScanDays = $defStatus.DaysSinceLastQuickScan+ }+ if ($defStatus.PSObject.Properties['QuickScanStartTime']) {+ $script:metrics.WindowsDefender.LastQuickScan = $defStatus.QuickScanStartTime+ }+ if ($defStatus.PSObject.Properties['FullScanStartTime']) {+ $script:metrics.WindowsDefender.LastFullScan = $defStatus.FullScanStartTime+ }+ }+ $successfulFunctions+++ Write-Host " Status: $($script:metrics.WindowsDefender.Status)" -ForegroundColor $(if ($script:metrics.WindowsDefender.ProtectionEnabled) { 'Green' } else { 'Red' })+ Write-Host " Real-Time Protection: $($script:metrics.WindowsDefender.RealTimeProtection)" -ForegroundColor $(if ($script:metrics.WindowsDefender.RealTimeProtection) { 'Green' } else { 'Red' })+ Write-Host " Signature Age: $($script:metrics.WindowsDefender.SignatureAge) days" -ForegroundColor $(if ($script:metrics.WindowsDefender.SignatureAge -le 1) { 'Green' } elseif ($script:metrics.WindowsDefender.SignatureAge -le 7) { 'Yellow' } else { 'Red' })+ } catch {+ $failedFunctions+++ Write-Verbose " Get-DefenderStatus: $_"+ }++ # Invoke-DefenderScan - skip for metrics+ $totalFunctions+++ Write-Host " Defender Scan: Skipped (metrics only)" -ForegroundColor Gray++ # Update-DefenderConfiguration - check only+ try {+ $totalFunctions+++ $defConfig = Update-DefenderConfiguration -WhatIf -ErrorAction Stop+ $successfulFunctions+++ Write-Host " Configuration: Checked" -ForegroundColor Green+ } catch {+ $failedFunctions+++ Write-Verbose " Update-DefenderConfiguration: $_"+ }++ $script:metrics.Performance.ModuleTimes['WindowsDefender'] = [Math]::Round(((Get-Date) - $defStart).TotalSeconds, 2)+ }++# ============================================+# CALCULATE AGGREGATE METRICS+# ============================================+Write-Host "`n[CALCULATING AGGREGATE METRICS]" -ForegroundColor Cyan++# Helper function to safely convert values to integers+function ConvertTo-SafeInt {+ param($Value)++ if ($null -eq $Value) { return 0 }+ if ($Value -is [int] -or $Value -is [long]) { return [int]$Value }+ if ($Value -is [array]) { return @($Value).Count }+ if ($Value -is [string]) {+ $trimmed = $Value.Trim()+ if ([string]::IsNullOrEmpty($trimmed)) { return 0 }+ try { return [int]$trimmed } catch { return 0 }+ }+ try { return [int]$Value } catch { return 0 }+}++# Findings by severity - SAFE CONVERSION+$script:metrics.Findings.Critical =+ (ConvertTo-SafeInt $script:metrics.Vulnerability.Critical) ++ (ConvertTo-SafeInt $script:metrics.ActiveDirectory.Vulnerabilities) ++ (ConvertTo-SafeInt $script:metrics.ActiveDirectory.Backdoors) ++ (ConvertTo-SafeInt $script:metrics.Analysis.CriticalEvents)++$script:metrics.Findings.High =+ (ConvertTo-SafeInt $script:metrics.Detection.TotalThreats) ++ (ConvertTo-SafeInt $script:metrics.Vulnerability.High) ++ (ConvertTo-SafeInt $script:metrics.Vulnerability.EOLSoftware) ++ (ConvertTo-SafeInt $script:metrics.ThreatHunting.IOCMatches)++$script:metrics.Findings.Medium =+ (ConvertTo-SafeInt $script:metrics.Analysis.SecurityMisconfigurations) ++ (ConvertTo-SafeInt $script:metrics.Vulnerability.Medium) ++ (ConvertTo-SafeInt $script:metrics.Vulnerability.CertificateIssues) ++ (ConvertTo-SafeInt $script:metrics.Analysis.RegistryIssues)++$script:metrics.Findings.Low =+ (ConvertTo-SafeInt $script:metrics.Analysis.ExposedServices) ++ (ConvertTo-SafeInt $script:metrics.ActiveDirectory.StaleObjects) ++ (ConvertTo-SafeInt $script:metrics.Cloud.RiskySignIns)++$script:metrics.Findings.Total =+ $script:metrics.Findings.Critical ++ $script:metrics.Findings.High ++ $script:metrics.Findings.Medium ++ $script:metrics.Findings.Low++# Findings by category+$script:metrics.Findings.ByCategory.Threats = ConvertTo-SafeInt $script:metrics.Detection.TotalThreats+$script:metrics.Findings.ByCategory.Vulnerabilities = ConvertTo-SafeInt $script:metrics.Vulnerability.Total+$script:metrics.Findings.ByCategory.Configuration = ConvertTo-SafeInt $script:metrics.Analysis.SecurityMisconfigurations+$script:metrics.Findings.ByCategory.Compliance = ConvertTo-SafeInt $script:metrics.Compliance.FailedControls++Write-Host " Total Findings: $($script:metrics.Findings.Total)" -ForegroundColor White+Write-Host " Critical: $($script:metrics.Findings.Critical)" -ForegroundColor Red+Write-Host " High: $($script:metrics.Findings.High)" -ForegroundColor Yellow+Write-Host " Medium: $($script:metrics.Findings.Medium)" -ForegroundColor Yellow+Write-Host " Low: $($script:metrics.Findings.Low)" -ForegroundColor Gray++# Calculate overall security score - FIXED IF STATEMENTS+$penalty = 0+$penalty += ($script:metrics.Findings.Critical * 20)+$penalty += ($script:metrics.Findings.High * 10)+$penalty += ($script:metrics.Findings.Medium * 5)+$penalty += ($script:metrics.Findings.Low * 2)+$penalty += ((ConvertTo-SafeInt $script:metrics.Core.PendingUpdates) * 2)++# Add penalties based on conditions+if (-not $script:metrics.WindowsDefender.ProtectionEnabled) {+ $penalty += 15+}++$signatureAge = ConvertTo-SafeInt $script:metrics.WindowsDefender.SignatureAge+if ($signatureAge -gt 7) {+ $penalty += 10+}++$script:metrics.OverallSecurityScore = [Math]::Max(0, [Math]::Min(100, 100 - $penalty))++Write-Host " Overall Security Score: $($script:metrics.OverallSecurityScore)%" -ForegroundColor $(+ if ($script:metrics.OverallSecurityScore -ge 80) { 'Green' }+ elseif ($script:metrics.OverallSecurityScore -ge 60) { 'Yellow' }+ else { 'Red' }+)++# Determine risk level+$script:metrics.RiskLevel =+ if ($script:metrics.Findings.Critical -gt 10) { "Critical" }+ elseif ($script:metrics.Findings.Critical -gt 5) { "High" }+ elseif ($script:metrics.Findings.Critical -gt 0) { "High" }+ elseif ($script:metrics.Findings.High -gt 20) { "High" }+ elseif ($script:metrics.Findings.High -gt 10) { "Medium" }+ elseif ($script:metrics.Findings.High -gt 0) { "Medium" }+ elseif ($script:metrics.Findings.Medium -gt 20) { "Medium" }+ else { "Low" }++Write-Host " Risk Level: $($script:metrics.RiskLevel)" -ForegroundColor $(+ switch ($script:metrics.RiskLevel) {+ 'Critical' { 'Red' }+ 'High' { 'Red' }+ 'Medium' { 'Yellow' }+ default { 'Green' }+ }+)++# Determine threat level+$script:metrics.ThreatLevel =+ if ($script:metrics.Detection.APTIndicators -gt 0) { "Critical" }+ elseif ($script:metrics.Detection.LateralMovement -gt 0) { "High" }+ elseif ($script:metrics.Detection.TotalThreats -gt 30) { "High" }+ elseif ($script:metrics.Detection.TotalThreats -gt 20) { "Medium" }+ elseif ($script:metrics.Detection.TotalThreats -gt 10) { "Medium" }+ elseif ($script:metrics.Detection.TotalThreats -gt 0) { "Low" }+ else { "Minimal" }++Write-Host " Threat Level: $($script:metrics.ThreatLevel)" -ForegroundColor $(+ switch ($script:metrics.ThreatLevel) {+ 'Critical' { 'Red' }+ 'High' { 'Red' }+ 'Medium' { 'Yellow' }+ default { 'Green' }+ }+)++# Health status+$script:metrics.HealthStatus =+ if ($script:metrics.OverallSecurityScore -ge 90 -and $script:metrics.ThreatLevel -eq 'Minimal') { "Excellent" }+ elseif ($script:metrics.OverallSecurityScore -ge 80 -and $script:metrics.ThreatLevel -in @('Minimal', 'Low')) { "Good" }+ elseif ($script:metrics.OverallSecurityScore -ge 60) { "Fair" }+ elseif ($script:metrics.OverallSecurityScore -ge 40) { "Poor" }+ else { "Critical" }++Write-Host " Health Status: $($script:metrics.HealthStatus)" -ForegroundColor $(+ switch ($script:metrics.HealthStatus) {+ 'Excellent' { 'Green' }+ 'Good' { 'Green' }+ 'Fair' { 'Yellow' }+ 'Poor' { 'Red' }+ default { 'Red' }+ }+)++# Generate recommendations+if ($script:metrics.Findings.Critical -gt 0) {+ $script:metrics.Recommendations.Critical += "Address $($script:metrics.Findings.Critical) critical security findings immediately"+}+if ($script:metrics.Vulnerability.EOLSoftware -gt 0) {+ $script:metrics.Recommendations.Critical += "Replace or upgrade $($script:metrics.Vulnerability.EOLSoftware) end-of-life software packages"+}+if (-not $script:metrics.WindowsDefender.ProtectionEnabled) {+ $script:metrics.Recommendations.Critical += "Enable Windows Defender real-time protection immediately"+}+if ($script:metrics.Detection.APTIndicators -gt 0) {+ $script:metrics.Recommendations.Critical += "Investigate $($script:metrics.Detection.APTIndicators) APT indicators - potential advanced threat"+}++if ($script:metrics.Findings.High -gt 0) {+ $script:metrics.Recommendations.High += "Remediate $($script:metrics.Findings.High) high-severity findings within 7 days"+}+if ($script:metrics.Core.PendingUpdates -gt 0) {+ $script:metrics.Recommendations.High += "Install $($script:metrics.Core.PendingUpdates) pending security updates"+}+if ($script:metrics.WindowsDefender.SignatureAge -gt 7) {+ $script:metrics.Recommendations.High += "Update Windows Defender signatures (currently $($script:metrics.WindowsDefender.SignatureAge) days old)"+}+if ($script:metrics.ComplianceScore -lt 70) {+ $script:metrics.Recommendations.High += "Improve compliance score (currently $($script:metrics.ComplianceScore)% - target: 80%+)"+}++if ($script:metrics.Findings.Medium -gt 0) {+ $script:metrics.Recommendations.Medium += "Address $($script:metrics.Findings.Medium) medium-severity issues within 30 days"+}+if ($script:metrics.Analysis.SecurityMisconfigurations -gt 0) {+ $script:metrics.Recommendations.Medium += "Fix $($script:metrics.Analysis.SecurityMisconfigurations) security misconfigurations"+}++if ($script:metrics.ActiveDirectory.StaleObjects -gt 10) {+ $script:metrics.Recommendations.Low += "Clean up $($script:metrics.ActiveDirectory.StaleObjects) stale AD objects"+}++$script:metrics.Recommendations.Total =+ @($script:metrics.Recommendations.Critical).Count ++ @($script:metrics.Recommendations.High).Count ++ @($script:metrics.Recommendations.Medium).Count ++ @($script:metrics.Recommendations.Low).Count++ # ============================================+ # TREND ANALYSIS (if enabled)+ # ============================================+ if ($CalculateTrends) {+ Write-Host "`n[CALCULATING TRENDS]" -ForegroundColor Cyan++ try {+ $historyPath = Join-Path $env:TEMP "SecurityMetricsHistory.json"++ if (Test-Path $historyPath) {+ $history = Get-Content $historyPath -Raw | ConvertFrom-Json+ $historyArray = @($history)++ if ($historyArray.Count -gt 0) {+ $lastMetrics = $historyArray | Select-Object -Last 1++ # Security score trend+ $scoreDelta = $script:metrics.OverallSecurityScore - $lastMetrics.OverallSecurityScore+ $script:metrics.Trends.SecurityScoreChange = $scoreDelta+ $script:metrics.Trends.SecurityScoreTrend =+ if ($scoreDelta -gt 5) { "Improving" }+ elseif ($scoreDelta -lt -5) { "Declining" }+ else { "Stable" }++ # Threat trend+ $threatDelta = $script:metrics.Detection.TotalThreats - $lastMetrics.Detection.TotalThreats+ $script:metrics.Trends.ThreatCountChange = $threatDelta+ if ($script:metrics.Detection.TotalThreats -gt ($lastMetrics.Detection.TotalThreats * 1.2)) {+ $script:metrics.Trends.ThreatTrend = "Increasing"+ } elseif ($script:metrics.Detection.TotalThreats -lt ($lastMetrics.Detection.TotalThreats * 0.8)) {+ $script:metrics.Trends.ThreatTrend = "Decreasing"+ } else {+ $script:metrics.Trends.ThreatTrend = "Stable"+ }++ # Compliance trend+ $compDelta = $script:metrics.ComplianceScore - $lastMetrics.ComplianceScore+ $script:metrics.Trends.ComplianceScoreChange = $compDelta+ if ($compDelta -gt 5) {+ $script:metrics.Trends.ComplianceTrend = "Improving"+ } elseif ($compDelta -lt -5) {+ $script:metrics.Trends.ComplianceTrend = "Declining"+ } else {+ $script:metrics.Trends.ComplianceTrend = "Stable"+ }++ # Findings trend+ $findingsDelta = $script:metrics.Findings.Total - $lastMetrics.Findings.Total+ $script:metrics.Trends.FindingsChange = $findingsDelta+ if ($findingsDelta -gt 5) {+ $script:metrics.Trends.FindingsTrend = "Increasing"+ } elseif ($findingsDelta -lt -5) {+ $script:metrics.Trends.FindingsTrend = "Decreasing"+ } else {+ $script:metrics.Trends.FindingsTrend = "Stable"+ }++ Write-Host " Security Score: $(if ($scoreDelta -gt 0) { '+' })$scoreDelta ($($script:metrics.Trends.SecurityScoreTrend))" -ForegroundColor $(if ($scoreDelta -gt 0) { 'Green' } elseif ($scoreDelta -lt 0) { 'Red' } else { 'Gray' })+ Write-Host " Threats: $(if ($threatDelta -gt 0) { '+' })$threatDelta ($($script:metrics.Trends.ThreatTrend))" -ForegroundColor $(if ($script:metrics.Trends.ThreatTrend -eq 'Increasing') { 'Red' } elseif ($script:metrics.Trends.ThreatTrend -eq 'Decreasing') { 'Green' } else { 'Gray' })+ Write-Host " Compliance: $(if ($compDelta -gt 0) { '+' })$compDelta ($($script:metrics.Trends.ComplianceTrend))" -ForegroundColor $(if ($script:metrics.Trends.ComplianceTrend -eq 'Improving') { 'Green' } elseif ($script:metrics.Trends.ComplianceTrend -eq 'Declining') { 'Red' } else { 'Gray' })+ Write-Host " Findings: $(if ($findingsDelta -gt 0) { '+' })$findingsDelta ($($script:metrics.Trends.FindingsTrend))" -ForegroundColor $(if ($findingsDelta -lt 0) { 'Green' } elseif ($findingsDelta -gt 0) { 'Red' } else { 'Gray' })+ } else {+ Write-Host " Insufficient history for trend analysis" -ForegroundColor Gray+ }+ } else {+ Write-Host " No historical data found - this is the first collection" -ForegroundColor Gray+ }+ } catch {+ Write-Warning " Failed to calculate trends: $_"+ }+ }++ # ============================================+ # BASELINE COMPARISON (if enabled)+ # ============================================+ if ($CompareWithBaseline -and $BaselinePath -and (Test-Path $BaselinePath)) {+ Write-Host "`n[COMPARING WITH BASELINE]" -ForegroundColor Cyan++ try {+ $baseline = Get-Content $BaselinePath -Raw | ConvertFrom-Json+ $script:metrics.Baseline.BaselineDate = $baseline.Timestamp++ # Security score comparison+ $script:metrics.Baseline.SecurityScoreDelta = $script:metrics.OverallSecurityScore - $baseline.OverallSecurityScore++ # Threat count comparison+ $script:metrics.Baseline.ThreatCountDelta = $script:metrics.Detection.TotalThreats - $baseline.Detection.TotalThreats++ # Compliance score comparison+ $script:metrics.Baseline.ComplianceScoreDelta = $script:metrics.ComplianceScore - $baseline.ComplianceScore++ # Findings comparison+ $script:metrics.Baseline.NewFindings = [Math]::Max(0, $script:metrics.Findings.Total - $baseline.Findings.Total)+ $script:metrics.Baseline.ResolvedFindings = [Math]::Max(0, $baseline.Findings.Total - $script:metrics.Findings.Total)++ # Identify improved/declined areas+ if ($script:metrics.Baseline.SecurityScoreDelta -gt 0) {+ $script:metrics.Baseline.ImprovedAreas += "Security Score improved by $($script:metrics.Baseline.SecurityScoreDelta) points"+ } elseif ($script:metrics.Baseline.SecurityScoreDelta -lt 0) {+ $script:metrics.Baseline.DeclinedAreas += "Security Score declined by $([Math]::Abs($script:metrics.Baseline.SecurityScoreDelta)) points"+ }++ if ($script:metrics.Baseline.ThreatCountDelta -lt 0) {+ $script:metrics.Baseline.ImprovedAreas += "Threat count reduced by $([Math]::Abs($script:metrics.Baseline.ThreatCountDelta))"+ } elseif ($script:metrics.Baseline.ThreatCountDelta -gt 0) {+ $script:metrics.Baseline.DeclinedAreas += "Threat count increased by $($script:metrics.Baseline.ThreatCountDelta)"+ }++ if ($script:metrics.Baseline.ComplianceScoreDelta -gt 0) {+ $script:metrics.Baseline.ImprovedAreas += "Compliance improved by $($script:metrics.Baseline.ComplianceScoreDelta)%"+ } elseif ($script:metrics.Baseline.ComplianceScoreDelta -lt 0) {+ $script:metrics.Baseline.DeclinedAreas += "Compliance declined by $([Math]::Abs($script:metrics.Baseline.ComplianceScoreDelta))%"+ }++ Write-Host " Baseline Date: $($script:metrics.Baseline.BaselineDate)" -ForegroundColor Gray+ Write-Host " Security Score: $(if ($script:metrics.Baseline.SecurityScoreDelta -gt 0) { '+' })$($script:metrics.Baseline.SecurityScoreDelta)" -ForegroundColor $(if ($script:metrics.Baseline.SecurityScoreDelta -gt 0) { 'Green' } elseif ($script:metrics.Baseline.SecurityScoreDelta -lt 0) { 'Red' } else { 'Gray' })+ Write-Host " Threats: $(if ($script:metrics.Baseline.ThreatCountDelta -gt 0) { '+' })$($script:metrics.Baseline.ThreatCountDelta)" -ForegroundColor $(if ($script:metrics.Baseline.ThreatCountDelta -lt 0) { 'Green' } elseif ($script:metrics.Baseline.ThreatCountDelta -gt 0) { 'Red' } else { 'Gray' })+ Write-Host " New Findings: $($script:metrics.Baseline.NewFindings)" -ForegroundColor $(if ($script:metrics.Baseline.NewFindings -gt 0) { 'Yellow' } else { 'Green' })+ Write-Host " Resolved Findings: $($script:metrics.Baseline.ResolvedFindings)" -ForegroundColor $(if ($script:metrics.Baseline.ResolvedFindings -gt 0) { 'Green' } else { 'Gray' })++ if (@($script:metrics.Baseline.ImprovedAreas).Count -gt 0) {+ Write-Host " Improvements: $(@($script:metrics.Baseline.ImprovedAreas).Count)" -ForegroundColor Green+ }+ if (@($script:metrics.Baseline.DeclinedAreas).Count -gt 0) {+ Write-Host " Declines: $(@($script:metrics.Baseline.DeclinedAreas).Count)" -ForegroundColor Red+ }+ } catch {+ Write-Warning " Failed to compare with baseline: $_"+ }+ }++ # ============================================+ # SAVE HISTORY (if enabled)+ # ============================================+ if ($IncludeHistory) {+ Write-Host "`n[SAVING TO HISTORY]" -ForegroundColor Cyan++ try {+ $historyPath = Join-Path $env:TEMP "SecurityMetricsHistory.json"+ $history = @()++ if (Test-Path $historyPath) {+ $history = @(Get-Content $historyPath -Raw | ConvertFrom-Json)+ }++ # Keep only last N days+ $cutoffDate = (Get-Date).AddDays(-$HistoryDays)+ $history = @($history) | Where-Object {+ try { [DateTime]$_.Timestamp -gt $cutoffDate } catch { $false }+ }++ # Add current metrics+ $history += $script:metrics++ # Save+ $history | ConvertTo-Json -Depth 10 | Out-File $historyPath -Encoding UTF8 -Force++ Write-Host " History saved: $historyPath" -ForegroundColor Green+ Write-Host " History entries: $(@($history).Count)" -ForegroundColor Gray+ } catch {+ Write-Warning " Failed to save history: $_"+ }+ }++ # ============================================+ # EXPORT (if specified)+ # ============================================+ if ($ExportPath) {+ Write-Host "`n[EXPORTING METRICS]" -ForegroundColor Cyan++ try {+ if (-not (Test-Path $ExportPath)) {+ New-Item -Path $ExportPath -ItemType Directory -Force | Out-Null+ }++ $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"+ $exportFile = Join-Path $ExportPath "SecurityMetrics_$timestamp.json"++ $script:metrics | ConvertTo-Json -Depth 10 | Out-File $exportFile -Encoding UTF8 -Force++ Write-Host " Exported: $exportFile" -ForegroundColor Green+ Write-Host " Size: $([Math]::Round((Get-Item $exportFile).Length / 1KB, 2)) KB" -ForegroundColor Gray+ } catch {+ Write-Error "Failed to export metrics: $_"+ }+ }++ # Calculate performance metrics+ $script:metrics.CollectionDuration = [Math]::Round(((Get-Date) - $startTime).TotalSeconds, 2)+ $script:metrics.Performance.CollectionTime = $script:metrics.CollectionDuration+ $script:metrics.Performance.FunctionCalls = $totalFunctions+ $script:metrics.Performance.FailedFunctions = $failedFunctions+ if ($totalFunctions -gt 0) {+ $script:metrics.Performance.SuccessRate = [Math]::Round(($successfulFunctions / $totalFunctions) * 100, 1)+ }++ return [PSCustomObject]$script:metrics++ }+ catch {+ Write-Error "Metrics collection failed: $_"+ Write-Host "`nStack Trace:" -ForegroundColor Red+ Write-Host $_.ScriptStackTrace -ForegroundColor Gray+ throw+ }+ }++ end {+ $totalTime = [Math]::Round(((Get-Date) - $startTime).TotalSeconds, 2)++ Write-Host "`n================================================================" -ForegroundColor Green+ Write-Host " METRICS COLLECTION COMPLETE" -ForegroundColor Green+ Write-Host "================================================================" -ForegroundColor Green+ Write-Host " Collection Time: $totalTime seconds" -ForegroundColor White+ Write-Host " Modules Processed: $(@($modulesToProcess).Count)" -ForegroundColor Yellow+ Write-Host " Function Success Rate: $($script:metrics.Performance.SuccessRate)%" -ForegroundColor White++ Write-Host "`nKey Metrics:" -ForegroundColor Cyan+ Write-Host " Security Score: $($script:metrics.OverallSecurityScore)%" -ForegroundColor White+ Write-Host " Health Status: $($script:metrics.HealthStatus)" -ForegroundColor White+ Write-Host " Risk Level: $($script:metrics.RiskLevel)" -ForegroundColor White+ Write-Host " Threat Level: $($script:metrics.ThreatLevel)" -ForegroundColor White+ Write-Host " Compliance Score: $($script:metrics.ComplianceScore)%" -ForegroundColor White+ Write-Host " Total Findings: $($script:metrics.Findings.Total)" -ForegroundColor White+ Write-Host " Recommendations: $($script:metrics.Recommendations.Total)" -ForegroundColor White+ }+}\ No newline at end of filediff --git a/Reporting/New-ExecutiveReport.ps1 b/Reporting/New-ExecutiveReport.ps1new file mode 100644index 0000000..a6064d6--- /dev/null+++ b/Reporting/New-ExecutiveReport.ps1@@ -0,0 +1,1797 @@+function New-ExecutiveReport {+ <#+ .SYNOPSIS+ Generates comprehensive executive-level security reports from collected metrics++ .DESCRIPTION+ Professional report generation tool that transforms security metrics into+ executive-ready documentation with:+ - Executive Summary (1-page overview)+ - Security Score Dashboard+ - Risk Assessment Matrix+ - Compliance Framework Breakdown+ - Threat Landscape Analysis+ - Vulnerability Management+ - Trend Analysis (with historical data)+ - Detailed Findings with Evidence+ - Prioritized Remediation Roadmap+ - Resource Planning & Timeline+ - Multiple Output Formats (HTML, DOCX, PDF, JSON)++ .PARAMETER MetricsFile+ Path to the security metrics JSON file generated by Get-SecurityMetrics+ If not provided, will attempt to use the most recent metrics from history++ .PARAMETER OutputPath+ Directory path where the report will be saved+ Default: Current directory++ .PARAMETER OutputFormat+ Report output format+ Valid values: HTML, DOCX, PDF, JSON, All+ Default: HTML++ .PARAMETER ReportTitle+ Custom title for the report+ Default: "Security Assessment Executive Report"++ .PARAMETER CompanyName+ Company/Organization name to include in the report+ Default: Domain name or "Organization"++ .PARAMETER IncludeTrends+ Include trend analysis section (requires historical metrics data)++ .PARAMETER IncludeRecommendations+ Include detailed recommendations section with implementation guidance++ .PARAMETER IncludeCompliance+ Include compliance framework comparison and gap analysis++ .PARAMETER IncludeExecutiveSummary+ Generate a separate 1-page executive summary document++ .PARAMETER IncludeCharts+ Include visual charts and graphs in the report+ Requires PowerShell charting capabilities++ .PARAMETER Confidential+ Mark the report as confidential and add watermarks++ .PARAMETER Audience+ Target audience for the report (affects detail level and language)+ Valid values: Executive, Technical, Mixed+ Default: Executive++ .PARAMETER CustomLogo+ Path to a custom logo image file to include in the report header+ Supported formats: PNG, JPG++ .EXAMPLE+ New-ExecutiveReport -MetricsFile "C:\Reports\SecurityMetrics_20251008.json" -OutputPath "C:\Reports" -OutputFormat HTML++ Generate HTML report from specific metrics file++ .EXAMPLE+ New-ExecutiveReport -OutputFormat All -IncludeTrends -IncludeCharts -CompanyName "Acme Corp"++ Generate comprehensive report in all formats with trends and charts++ .EXAMPLE+ New-ExecutiveReport -Audience Executive -IncludeExecutiveSummary -Confidential++ Generate executive-focused report with separate summary and confidential marking++ .EXAMPLE+ $metrics = Get-SecurityMetrics -IncludeModules All+ New-ExecutiveReport -MetricsFile $metrics -OutputFormat DOCX -IncludeCompliance++ Generate Word document with compliance analysis from in-memory metrics++ .OUTPUTS+ Report file(s) in specified format(s):+ - SecurityReport_YYYYMMDD_HHMMSS.html+ - SecurityReport_YYYYMMDD_HHMMSS.docx+ - SecurityReport_YYYYMMDD_HHMMSS.pdf+ - SecurityReport_YYYYMMDD_HHMMSS.json+ - ExecutiveSummary_YYYYMMDD_HHMMSS.docx (if IncludeExecutiveSummary)++ .NOTES+ Author: WindowsSecurityAudit Module+ Version: 1.2.0 ULTIMATE EDITION++ Requires: PowerShell 5.1 or higher+ Optional: Microsoft Word (for DOCX output)+ Optional: wkhtmltopdf (for PDF output)++ Report Sections:+ 1. Executive Summary+ 2. Security Score Dashboard+ 3. Risk Assessment+ 4. Compliance Status+ 5. Threat Analysis+ 6. Vulnerability Summary+ 7. Findings Details+ 8. Remediation Roadmap+ 9. Appendices+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [string]$MetricsFile,++ [Parameter()]+ [string]$OutputPath = ".",++ [Parameter()]+ [ValidateSet('HTML', 'DOCX', 'PDF', 'JSON', 'All')]+ [string]$OutputFormat = 'HTML',++ [Parameter()]+ [string]$ReportTitle = "Security Assessment Executive Report",++ [Parameter()]+ [string]$CompanyName,++ [Parameter()]+ [switch]$IncludeTrends,++ [Parameter()]+ [switch]$IncludeRecommendations = $true,++ [Parameter()]+ [switch]$IncludeCompliance = $true,++ [Parameter()]+ [switch]$IncludeExecutiveSummary,++ [Parameter()]+ [switch]$IncludeCharts,++ [Parameter()]+ [switch]$Confidential,++ [Parameter()]+ [ValidateSet('Executive', 'Technical', 'Mixed')]+ [string]$Audience = 'Executive',++ [Parameter()]+ [string]$CustomLogo+ )++ begin {+ Write-Host "================================================================" -ForegroundColor Cyan+ Write-Host " EXECUTIVE REPORT GENERATION - ULTIMATE EDITION" -ForegroundColor Cyan+ Write-Host "================================================================" -ForegroundColor Cyan++ $reportStartTime = Get-Date+ $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"++ # Ensure output directory exists+ if (-not (Test-Path $OutputPath)) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ Write-Host "Created output directory: $OutputPath" -ForegroundColor Green+ }++ # Determine company name+ if (-not $CompanyName) {+ $CompanyName = if ($env:USERDNSDOMAIN) {+ $env:USERDNSDOMAIN+ } else {+ "Organization"+ }+ }++ Write-Host "Company: $CompanyName" -ForegroundColor Gray+ Write-Host "Output Path: $OutputPath" -ForegroundColor Gray+ Write-Host "Output Format: $OutputFormat" -ForegroundColor Gray+ Write-Host "Audience: $Audience" -ForegroundColor Gray+ }++ process {+ try {+ # ============================================+ # HELPER FUNCTION - SAFE PROPERTY ACCESS+ # ============================================+ function Get-SafeProperty {+ param($Object, $PropertyName, $Default = $null)+ if ($null -eq $Object) { return $Default }+ if ($Object.PSObject.Properties[$PropertyName]) {+ $value = $Object.$PropertyName+ if ($null -eq $value) { return $Default }+ return $value+ }+ return $Default+ }++ # ============================================+ # LOAD METRICS DATA+ # ============================================+ Write-Host "`n[LOADING METRICS DATA]" -ForegroundColor Cyan++ $metrics = $null++ # If MetricsFile is actually a PSCustomObject (piped from Get-SecurityMetrics)+ if ($MetricsFile -is [PSCustomObject]) {+ $metrics = $MetricsFile+ Write-Host " Using provided metrics object" -ForegroundColor Green+ }+ # If MetricsFile is a path to JSON file+ elseif ($MetricsFile -and (Test-Path $MetricsFile)) {+ try {+ $metrics = Get-Content $MetricsFile -Raw | ConvertFrom-Json+ Write-Host " Loaded metrics from: $MetricsFile" -ForegroundColor Green+ } catch {+ Write-Error "Failed to load metrics file: $_"+ return+ }+ }+ # Try to load most recent from history+ else {+ $historyPath = Join-Path $env:TEMP "SecurityMetricsHistory.json"+ if (Test-Path $historyPath) {+ try {+ $history = Get-Content $historyPath -Raw | ConvertFrom-Json+ $metrics = @($history) | Select-Object -Last 1+ Write-Host " Loaded most recent metrics from history" -ForegroundColor Green+ } catch {+ Write-Error "Failed to load metrics from history: $_"+ return+ }+ } else {+ Write-Error "No metrics data found. Please run Get-SecurityMetrics first or provide -MetricsFile parameter."+ return+ }+ }++ if (-not $metrics) {+ Write-Error "No metrics data available"+ return+ }++ Write-Host " Metrics Date: $(Get-SafeProperty $metrics 'Timestamp' 'Unknown')" -ForegroundColor Gray+ Write-Host " Hostname: $(Get-SafeProperty $metrics 'Hostname' 'Unknown')" -ForegroundColor Gray+ Write-Host " Security Score: $(Get-SafeProperty $metrics 'OverallSecurityScore' 0)%" -ForegroundColor Gray++ # ============================================+ # PREPARE REPORT DATA STRUCTURES+ # ============================================+ Write-Host "`n[PREPARING REPORT DATA]" -ForegroundColor Cyan++ # Safe nested object access+ $findingsObj = Get-SafeProperty $metrics 'Findings' @{}+ $detectionObj = Get-SafeProperty $metrics 'Detection' @{}+ $vulnerabilityObj = Get-SafeProperty $metrics 'Vulnerability' @{}+ $complianceObj = Get-SafeProperty $metrics 'Compliance' @{}+ $defenderObj = Get-SafeProperty $metrics 'WindowsDefender' @{}+ $coreObj = Get-SafeProperty $metrics 'Core' @{}+ $recommendationsObj = Get-SafeProperty $metrics 'Recommendations' @{}+ $trendsObj = Get-SafeProperty $metrics 'Trends' @{}+ $adObj = Get-SafeProperty $metrics 'ActiveDirectory' @{}+ $analysisObj = Get-SafeProperty $metrics 'Analysis' @{}++ $reportData = @{+ # Metadata+ GeneratedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ReportTitle = $ReportTitle+ CompanyName = $CompanyName+ Confidential = $Confidential+ Audience = $Audience++ # Source Metrics+ Metrics = $metrics++ # Processed Data+ ExecutiveSummary = @{+ SecurityPosture = ""+ KeyFindings = @()+ CriticalActions = @()+ ComplianceStatus = ""+ OverallRisk = ""+ }++ Dashboard = @{+ SecurityScore = [int](Get-SafeProperty $metrics 'OverallSecurityScore' 0)+ SecurityScoreColor = Get-ScoreColor ([int](Get-SafeProperty $metrics 'OverallSecurityScore' 0))+ RiskLevel = Get-SafeProperty $metrics 'RiskLevel' 'Unknown'+ RiskLevelColor = Get-RiskColor (Get-SafeProperty $metrics 'RiskLevel' 'Unknown')+ ThreatLevel = Get-SafeProperty $metrics 'ThreatLevel' 'Unknown'+ ThreatLevelColor = Get-ThreatColor (Get-SafeProperty $metrics 'ThreatLevel' 'Unknown')+ ComplianceScore = [int](Get-SafeProperty $metrics 'ComplianceScore' 0)+ ComplianceScoreColor = Get-ScoreColor ([int](Get-SafeProperty $metrics 'ComplianceScore' 0))+ HealthStatus = Get-SafeProperty $metrics 'HealthStatus' 'Unknown'+ }++ RiskAssessment = @{+ CriticalRisks = @()+ HighRisks = @()+ MediumRisks = @()+ LowRisks = @()+ RiskMatrix = @()+ }++ Compliance = @{+ Frameworks = @()+ OverallCompliance = [int](Get-SafeProperty $metrics 'ComplianceScore' 0)+ ControlsTotal = [int](Get-SafeProperty $complianceObj 'TotalControls' 0)+ ControlsPassed = [int](Get-SafeProperty $complianceObj 'PassedControls' 0)+ ControlsFailed = [int](Get-SafeProperty $complianceObj 'FailedControls' 0)+ GapAnalysis = @()+ }++ Threats = @{+ ActiveThreats = [int](Get-SafeProperty $detectionObj 'TotalThreats' 0)+ Categories = @()+ ThreatTimeline = @()+ }++ Vulnerabilities = @{+ Total = [int](Get-SafeProperty $vulnerabilityObj 'Total' 0)+ Critical = [int](Get-SafeProperty $vulnerabilityObj 'Critical' 0)+ High = [int](Get-SafeProperty $vulnerabilityObj 'High' 0)+ Medium = [int](Get-SafeProperty $vulnerabilityObj 'Medium' 0)+ Low = [int](Get-SafeProperty $vulnerabilityObj 'Low' 0)+ EOLSoftware = [int](Get-SafeProperty $vulnerabilityObj 'EOLSoftware' 0)+ CertificateIssues = [int](Get-SafeProperty $vulnerabilityObj 'CertificateIssues' 0)+ }++ Findings = @{+ Total = [int](Get-SafeProperty $findingsObj 'Total' 0)+ Critical = @()+ High = @()+ Medium = @()+ Low = @()+ }++ Recommendations = @{+ Critical = @()+ High = @()+ Medium = @()+ Low = @()+ Total = [int](Get-SafeProperty $recommendationsObj 'Total' 0)+ }++ RemediationRoadmap = @{+ ImmediateActions = @()+ ShortTerm = @()+ MediumTerm = @()+ LongTerm = @()+ ResourceEstimate = @{+ TimeInvestment = ""+ SkillsRequired = @()+ EstimatedCost = ""+ }+ }++ Trends = @{+ Available = ($IncludeTrends -and [bool](Get-SafeProperty $trendsObj 'Enabled' $false))+ SecurityScoreTrend = ""+ ThreatTrend = ""+ ComplianceTrend = ""+ FindingsTrend = ""+ }++ Charts = @{+ Enabled = $IncludeCharts+ SecurityScoreGauge = ""+ FindingsByCategory = ""+ ComplianceFrameworks = ""+ ThreatDistribution = ""+ TrendChart = ""+ }+ }++ # ============================================+ # BUILD EXECUTIVE SUMMARY+ # ============================================+ Write-Host " Building executive summary..." -ForegroundColor Gray++ # Determine security posture description+ $healthStatus = Get-SafeProperty $metrics 'HealthStatus' 'Unknown'+ $reportData.ExecutiveSummary.SecurityPosture = switch ($healthStatus) {+ 'Excellent' { "The organization's security posture is excellent with strong controls in place and minimal risks identified." }+ 'Good' { "The organization maintains a good security posture with effective controls, though some improvements are recommended." }+ 'Fair' { "The organization's security posture is fair. Several vulnerabilities and misconfigurations require attention." }+ 'Poor' { "The organization's security posture is poor. Immediate action is required to address multiple critical security gaps." }+ 'Critical' { "The organization's security posture is critical. Urgent executive intervention is needed to address severe security deficiencies." }+ default { "Security posture assessment completed." }+ }++ # Safe property access for all metrics+ $findingsCritical = [int](Get-SafeProperty $findingsObj 'Critical' 0)+ $detectionThreats = [int](Get-SafeProperty $detectionObj 'TotalThreats' 0)+ $vulnEOL = [int](Get-SafeProperty $vulnerabilityObj 'EOLSoftware' 0)+ $complianceScore = [int](Get-SafeProperty $metrics 'ComplianceScore' 0)+ $defenderEnabled = [bool](Get-SafeProperty $defenderObj 'ProtectionEnabled' $true)+ $pendingUpdates = [int](Get-SafeProperty $coreObj 'PendingUpdates' 0)++ # Key findings+ if ($findingsCritical -gt 0) {+ $reportData.ExecutiveSummary.KeyFindings += "$findingsCritical critical security findings requiring immediate attention"+ }+ if ($detectionThreats -gt 20) {+ $reportData.ExecutiveSummary.KeyFindings += "$detectionThreats active threats detected across the environment"+ }+ if ($vulnEOL -gt 0) {+ $reportData.ExecutiveSummary.KeyFindings += "$vulnEOL end-of-life software packages present significant risk"+ }+ if ($complianceScore -lt 80) {+ $reportData.ExecutiveSummary.KeyFindings += "Compliance score of $complianceScore% indicates gaps requiring remediation"+ }+ if (-not $defenderEnabled) {+ $reportData.ExecutiveSummary.KeyFindings += "Windows Defender real-time protection is disabled, leaving systems vulnerable"+ }+ if ($pendingUpdates -gt 5) {+ $reportData.ExecutiveSummary.KeyFindings += "$pendingUpdates critical security updates pending installation"+ }++ # Critical actions - safe access+ $criticalRecs = @(Get-SafeProperty $recommendationsObj 'Critical' @())+ $highRecs = @(Get-SafeProperty $recommendationsObj 'High' @())+ $allCriticalActions = @($criticalRecs) + @($highRecs)+ if ($allCriticalActions.Count -gt 0) {+ $reportData.ExecutiveSummary.CriticalActions = $allCriticalActions | Select-Object -First 5+ }++ # Compliance status+ $reportData.ExecutiveSummary.ComplianceStatus = if ($complianceScore -ge 90) {+ "Excellent compliance across all tested frameworks"+ } elseif ($complianceScore -ge 80) {+ "Good compliance with minor gaps requiring attention"+ } elseif ($complianceScore -ge 70) {+ "Fair compliance with several controls requiring remediation"+ } else {+ "Compliance gaps present significant regulatory risk"+ }++ # Overall risk+ $riskLevel = Get-SafeProperty $metrics 'RiskLevel' 'Unknown'+ $reportData.ExecutiveSummary.OverallRisk = switch ($riskLevel) {+ 'Critical' { "CRITICAL - Immediate executive action required to prevent security incidents" }+ 'High' { "HIGH - Urgent remediation needed within 7 days to reduce organizational risk" }+ 'Medium' { "MEDIUM - Remediation plan should be developed and implemented within 30 days" }+ 'Low' { "LOW - Continue monitoring and maintain current security controls" }+ default { "Risk assessment completed" }+ }++ # ============================================+ # BUILD RISK ASSESSMENT+ # ============================================+ Write-Host " Building risk assessment..." -ForegroundColor Gray++ # Critical risks+ if ($findingsCritical -gt 0) {+ $reportData.RiskAssessment.CriticalRisks += @{+ Title = "Critical Security Findings"+ Count = $findingsCritical+ Impact = "Severe"+ Description = "Multiple critical vulnerabilities and misconfigurations that could lead to immediate compromise"+ AffectedSystems = Get-SafeProperty $metrics 'Hostname' 'Unknown'+ }+ }++ if ($vulnEOL -gt 0) {+ $reportData.RiskAssessment.CriticalRisks += @{+ Title = "End-of-Life Software"+ Count = $vulnEOL+ Impact = "Severe"+ Description = "Unsupported software no longer receiving security updates"+ AffectedSystems = "$vulnEOL applications"+ }+ }++ if (-not $defenderEnabled) {+ $reportData.RiskAssessment.CriticalRisks += @{+ Title = "Disabled Anti-Malware Protection"+ Count = 1+ Impact = "Severe"+ Description = "Windows Defender real-time protection is disabled"+ AffectedSystems = Get-SafeProperty $metrics 'Hostname' 'Unknown'+ }+ }++ # High risks+ if ($detectionThreats -gt 10) {+ $reportData.RiskAssessment.HighRisks += @{+ Title = "Active Threat Detections"+ Count = $detectionThreats+ Impact = "High"+ Description = "Multiple threat indicators across persistence, processes, and network activity"+ AffectedSystems = Get-SafeProperty $metrics 'Hostname' 'Unknown'+ }+ }++ if ($pendingUpdates -gt 0) {+ $reportData.RiskAssessment.HighRisks += @{+ Title = "Missing Security Updates"+ Count = $pendingUpdates+ Impact = "High"+ Description = "Critical security updates not installed"+ AffectedSystems = Get-SafeProperty $metrics 'Hostname' 'Unknown'+ }+ }++ $vulnCritical = [int](Get-SafeProperty $vulnerabilityObj 'Critical' 0)+ if ($vulnCritical -gt 0) {+ $reportData.RiskAssessment.HighRisks += @{+ Title = "Critical Vulnerabilities"+ Count = $vulnCritical+ Impact = "High"+ Description = "Known critical vulnerabilities in installed software"+ AffectedSystems = "$vulnCritical vulnerable packages"+ }+ }++ # Medium risks+ $securityMisconfigs = [int](Get-SafeProperty $analysisObj 'SecurityMisconfigurations' 0)+ if ($securityMisconfigs -gt 0) {+ $reportData.RiskAssessment.MediumRisks += @{+ Title = "Security Misconfigurations"+ Count = $securityMisconfigs+ Impact = "Medium"+ Description = "Configuration settings that weaken security posture"+ AffectedSystems = Get-SafeProperty $metrics 'Hostname' 'Unknown'+ }+ }++ $certIssues = [int](Get-SafeProperty $vulnerabilityObj 'CertificateIssues' 0)+ if ($certIssues -gt 0) {+ $reportData.RiskAssessment.MediumRisks += @{+ Title = "Certificate Issues"+ Count = $certIssues+ Impact = "Medium"+ Description = "Expired or weak certificates requiring replacement"+ AffectedSystems = "$certIssues certificates"+ }+ }++ # Low risks+ $staleObjects = [int](Get-SafeProperty $adObj 'StaleObjects' 0)+ if ($staleObjects -gt 10) {+ $reportData.RiskAssessment.LowRisks += @{+ Title = "Stale Active Directory Objects"+ Count = $staleObjects+ Impact = "Low"+ Description = "Inactive user accounts and computer objects requiring cleanup"+ AffectedSystems = "Active Directory"+ }+ }++ # Risk Matrix+ $reportData.RiskAssessment.RiskMatrix = @(+ @{ Category = "Critical"; Count = $reportData.RiskAssessment.CriticalRisks.Count; Color = "Red" }+ @{ Category = "High"; Count = $reportData.RiskAssessment.HighRisks.Count; Color = "Orange" }+ @{ Category = "Medium"; Count = $reportData.RiskAssessment.MediumRisks.Count; Color = "Yellow" }+ @{ Category = "Low"; Count = $reportData.RiskAssessment.LowRisks.Count; Color = "Green" }+ )++ # ============================================+ # BUILD COMPLIANCE SECTION+ # ============================================+ if ($IncludeCompliance) {+ Write-Host " Building compliance analysis..." -ForegroundColor Gray++ $frameworksObj = Get-SafeProperty $complianceObj 'Frameworks' @{}++ # CIS Benchmark+ $cisObj = Get-SafeProperty $frameworksObj 'CIS' @{}+ $cisTotalControls = [int](Get-SafeProperty $cisObj 'TotalControls' 0)+ if ($cisTotalControls -gt 0) {+ $cisScore = [int](Get-SafeProperty $cisObj 'Score' 0)+ $reportData.Compliance.Frameworks += @{+ Name = "CIS Benchmark Level 1"+ Score = $cisScore+ TotalControls = $cisTotalControls+ PassedControls = [int](Get-SafeProperty $cisObj 'PassedControls' 0)+ FailedControls = [int](Get-SafeProperty $cisObj 'FailedControls' 0)+ Status = if ($cisScore -ge 80) { "Pass" }+ elseif ($cisScore -ge 60) { "Marginal" }+ else { "Fail" }+ Color = Get-ScoreColor $cisScore+ }+ }++ # NIST 800-53+ $nistObj = Get-SafeProperty $frameworksObj 'NIST' @{}+ $nistTotalControls = [int](Get-SafeProperty $nistObj 'TotalControls' 0)+ if ($nistTotalControls -gt 0) {+ $nistScore = [int](Get-SafeProperty $nistObj 'Score' 0)+ $reportData.Compliance.Frameworks += @{+ Name = "NIST 800-53 Rev 5"+ Score = $nistScore+ TotalControls = $nistTotalControls+ PassedControls = [int](Get-SafeProperty $nistObj 'CompliantControls' 0)+ FailedControls = [int](Get-SafeProperty $nistObj 'NonCompliantControls' 0)+ Status = if ($nistScore -ge 80) { "Pass" }+ elseif ($nistScore -ge 60) { "Marginal" }+ else { "Fail" }+ Color = Get-ScoreColor $nistScore+ }+ }++ # PCI-DSS+ $pciObj = Get-SafeProperty $frameworksObj 'PCIDSS' @{}+ $pciTotalReqs = [int](Get-SafeProperty $pciObj 'TotalRequirements' 0)+ if ($pciTotalReqs -gt 0) {+ $pciScore = [int](Get-SafeProperty $pciObj 'Score' 0)+ $reportData.Compliance.Frameworks += @{+ Name = "PCI-DSS v4.0"+ Score = $pciScore+ TotalControls = $pciTotalReqs+ PassedControls = [int](Get-SafeProperty $pciObj 'InPlace' 0)+ FailedControls = [int](Get-SafeProperty $pciObj 'NotInPlace' 0)+ Status = if ($pciScore -ge 80) { "Pass" }+ elseif ($pciScore -ge 60) { "Marginal" }+ else { "Fail" }+ Color = Get-ScoreColor $pciScore+ }+ }++ # Gap Analysis+ $failedControls = [int](Get-SafeProperty $complianceObj 'FailedControls' 0)+ if ($failedControls -gt 0) {+ $reportData.Compliance.GapAnalysis += "Total of $failedControls controls require remediation"+ $reportData.Compliance.GapAnalysis += "Priority focus on CIS and NIST frameworks for immediate compliance improvement"+ }+ }++ # ============================================+ # BUILD THREAT ANALYSIS+ # ============================================+ Write-Host " Building threat analysis..." -ForegroundColor Gray++ $reportData.Threats.Categories = @(+ @{ Name = "Persistence Mechanisms"; Count = [int](Get-SafeProperty $detectionObj 'PersistenceMechanisms' 0); Severity = "High" }+ @{ Name = "Suspicious Processes"; Count = [int](Get-SafeProperty $detectionObj 'SuspiciousProcesses' 0); Severity = "High" }+ @{ Name = "Lateral Movement"; Count = [int](Get-SafeProperty $detectionObj 'LateralMovement' 0); Severity = "Critical" }+ @{ Name = "APT Indicators"; Count = [int](Get-SafeProperty $detectionObj 'APTIndicators' 0); Severity = "Critical" }+ @{ Name = "Living Off Land"; Count = [int](Get-SafeProperty $detectionObj 'LivingOffLand' 0); Severity = "Medium" }+ @{ Name = "Data Exfiltration"; Count = [int](Get-SafeProperty $detectionObj 'DataExfiltration' 0); Severity = "Critical" }+ @{ Name = "Network Anomalies"; Count = [int](Get-SafeProperty $detectionObj 'NetworkAnomalies' 0); Severity = "Medium" }+ ) | Where-Object { $_.Count -gt 0 }++ # ============================================+ # BUILD FINDINGS SECTION+ # ============================================+ Write-Host " Building findings section..." -ForegroundColor Gray++ # Populate findings from metrics+ if ($findingsCritical -gt 0) {+ $reportData.Findings.Critical += @{+ Title = "Critical Security Vulnerabilities"+ Count = $findingsCritical+ Severity = "Critical"+ Impact = "System compromise, data breach, regulatory penalties"+ Evidence = "Vulnerability assessment, threat detection scans"+ Remediation = "Immediate patching, isolation of affected systems, incident response activation"+ Timeline = "0-24 hours"+ }+ }++ $aptIndicators = [int](Get-SafeProperty $detectionObj 'APTIndicators' 0)+ if ($aptIndicators -gt 0) {+ $reportData.Findings.Critical += @{+ Title = "Advanced Persistent Threat Indicators"+ Count = $aptIndicators+ Severity = "Critical"+ Impact = "Potential nation-state or advanced adversary activity"+ Evidence = "APT indicator matching, behavioral analysis"+ Remediation = "Forensic investigation, threat hunting, IOC analysis"+ Timeline = "0-24 hours"+ }+ }++ if ($vulnEOL -gt 0) {+ $reportData.Findings.Critical += @{+ Title = "End-of-Life Software Detected"+ Count = $vulnEOL+ Severity = "Critical"+ Impact = "No security updates available, easy exploit targets"+ Evidence = "Software inventory scan"+ Remediation = "Software upgrade or replacement, migration planning"+ Timeline = "1-7 days"+ }+ }++ # High severity findings+ if ($detectionThreats -gt 10) {+ $reportData.Findings.High += @{+ Title = "Multiple Active Threats Detected"+ Count = $detectionThreats+ Severity = "High"+ Impact = "Elevated risk of security incidents"+ Evidence = "Threat detection across multiple vectors"+ Remediation = "Investigate and remediate each threat, enhance monitoring"+ Timeline = "1-7 days"+ }+ }++ if ($pendingUpdates -gt 0) {+ $reportData.Findings.High += @{+ Title = "Missing Security Updates"+ Count = $pendingUpdates+ Severity = "High"+ Impact = "Known vulnerabilities remain unpatched"+ Evidence = "Windows Update assessment"+ Remediation = "Install all pending security updates during maintenance window"+ Timeline = "7 days"+ }+ }++ # Medium severity findings+ if ($securityMisconfigs -gt 0) {+ $reportData.Findings.Medium += @{+ Title = "Security Misconfigurations"+ Count = $securityMisconfigs+ Severity = "Medium"+ Impact = "Weakened security posture, potential attack vectors"+ Evidence = "Configuration assessment"+ Remediation = "Apply security baseline, harden configurations"+ Timeline = "30 days"+ }+ }++ if ($certIssues -gt 0) {+ $reportData.Findings.Medium += @{+ Title = "Certificate Health Issues"+ Count = $certIssues+ Severity = "Medium"+ Impact = "Expired or weak certificates, trust issues"+ Evidence = "Certificate store analysis"+ Remediation = "Renew/replace certificates, implement monitoring"+ Timeline = "30 days"+ }+ }++ # ============================================+ # BUILD RECOMMENDATIONS+ # ============================================+ if ($IncludeRecommendations) {+ Write-Host " Building recommendations..." -ForegroundColor Gray++ $reportData.Recommendations.Critical = @($criticalRecs) | ForEach-Object {+ @{+ Text = $_+ Priority = "Critical"+ Timeline = "Immediate (0-24 hours)"+ Effort = "High"+ Impact = "Severe risk reduction"+ }+ }++ $reportData.Recommendations.High = @($highRecs) | ForEach-Object {+ @{+ Text = $_+ Priority = "High"+ Timeline = "Urgent (1-7 days)"+ Effort = "Medium-High"+ Impact = "Significant risk reduction"+ }+ }++ $mediumRecs = @(Get-SafeProperty $recommendationsObj 'Medium' @())+ $reportData.Recommendations.Medium = @($mediumRecs) | ForEach-Object {+ @{+ Text = $_+ Priority = "Medium"+ Timeline = "Short-term (7-30 days)"+ Effort = "Medium"+ Impact = "Moderate risk reduction"+ }+ }++ $lowRecs = @(Get-SafeProperty $recommendationsObj 'Low' @())+ $reportData.Recommendations.Low = @($lowRecs) | ForEach-Object {+ @{+ Text = $_+ Priority = "Low"+ Timeline = "Long-term (30-90 days)"+ Effort = "Low-Medium"+ Impact = "Minor risk reduction"+ }+ }+ }++ # ============================================+ # BUILD REMEDIATION ROADMAP+ # ============================================+ Write-Host " Building remediation roadmap..." -ForegroundColor Gray++ # Immediate actions (0-7 days)+ if ($findingsCritical -gt 0) {+ $reportData.RemediationRoadmap.ImmediateActions += @{+ Action = "Address all critical security findings"+ Owner = "IT Security Team"+ Timeline = "0-24 hours"+ Resources = "Security team, system administrators"+ Dependencies = "Management approval, system access"+ }+ }++ if (-not $defenderEnabled) {+ $reportData.RemediationRoadmap.ImmediateActions += @{+ Action = "Enable Windows Defender real-time protection"+ Owner = "IT Operations"+ Timeline = "Immediate"+ Resources = "System administrator"+ Dependencies = "System access, GPO if domain-joined"+ }+ }++ if ($vulnEOL -gt 0) {+ $reportData.RemediationRoadmap.ImmediateActions += @{+ Action = "Develop EOL software replacement plan"+ Owner = "IT Management"+ Timeline = "1-7 days"+ Resources = "IT management, procurement, vendors"+ Dependencies = "Budget approval, vendor selection"+ }+ }++ # Short-term actions (7-30 days)+ if ($pendingUpdates -gt 0) {+ $reportData.RemediationRoadmap.ShortTerm += @{+ Action = "Install all pending security updates"+ Owner = "IT Operations"+ Timeline = "7-14 days"+ Resources = "System administrators, change management"+ Dependencies = "Maintenance window, testing environment"+ }+ }++ if ($complianceScore -lt 80) {+ $reportData.RemediationRoadmap.ShortTerm += @{+ Action = "Remediate compliance control gaps"+ Owner = "Compliance Team"+ Timeline = "14-30 days"+ Resources = "Compliance team, IT security, auditors"+ Dependencies = "Gap analysis, remediation procedures"+ }+ }++ # Medium-term actions (30-90 days)+ if ($securityMisconfigs -gt 0) {+ $reportData.RemediationRoadmap.MediumTerm += @{+ Action = "Implement security baseline across all systems"+ Owner = "IT Security"+ Timeline = "30-60 days"+ Resources = "Security team, configuration management tools"+ Dependencies = "Baseline documentation, testing"+ }+ }++ $reportData.RemediationRoadmap.MediumTerm += @{+ Action = "Conduct quarterly security assessments"+ Owner = "IT Security"+ Timeline = "Ongoing (90-day cycle)"+ Resources = "Security team, assessment tools"+ Dependencies = "Executive sponsorship, budget"+ }++ # Long-term actions (90+ days)+ $reportData.RemediationRoadmap.LongTerm += @{+ Action = "Implement continuous security monitoring"+ Owner = "IT Security"+ Timeline = "90-180 days"+ Resources = "SIEM platform, security analysts, SOC"+ Dependencies = "Tool selection, training, integration"+ }++ $reportData.RemediationRoadmap.LongTerm += @{+ Action = "Develop comprehensive incident response plan"+ Owner = "IT Management"+ Timeline = "90-180 days"+ Resources = "IR team, legal, external consultants"+ Dependencies = "Executive approval, training, tabletop exercises"+ }++ # Resource estimates+ $totalFindings = [int](Get-SafeProperty $findingsObj 'Total' 0)+ $reportData.RemediationRoadmap.ResourceEstimate.TimeInvestment =+ if ($totalFindings -gt 50) { "6-12 months full-time equivalent" }+ elseif ($totalFindings -gt 20) { "3-6 months full-time equivalent" }+ elseif ($totalFindings -gt 10) { "1-3 months full-time equivalent" }+ else { "2-4 weeks part-time" }++ $reportData.RemediationRoadmap.ResourceEstimate.SkillsRequired = @(+ "Security Engineering"+ "System Administration"+ "Compliance Management"+ "Incident Response"+ "Risk Assessment"+ )++ $reportData.RemediationRoadmap.ResourceEstimate.EstimatedCost =+ if ($riskLevel -eq 'Critical') { "$$$$$ - Significant investment required" }+ elseif ($riskLevel -eq 'High') { "$$$$ - Substantial investment needed" }+ elseif ($riskLevel -eq 'Medium') { "$$$ - Moderate investment" }+ else { "$$ - Limited investment" }++ # ============================================+ # BUILD TREND ANALYSIS+ # ============================================+ if ($IncludeTrends -and $reportData.Trends.Available) {+ Write-Host " Building trend analysis..." -ForegroundColor Gray++ $scoreChange = [int](Get-SafeProperty $trendsObj 'SecurityScoreChange' 0)+ $scoreTrend = Get-SafeProperty $trendsObj 'SecurityScoreTrend' 'Stable'+ $reportData.Trends.SecurityScoreTrend = "$scoreTrend ($(if ($scoreChange -gt 0) {'+' })$scoreChange points)"++ $threatChange = [int](Get-SafeProperty $trendsObj 'ThreatCountChange' 0)+ $threatTrend = Get-SafeProperty $trendsObj 'ThreatTrend' 'Stable'+ $reportData.Trends.ThreatTrend = "$threatTrend ($(if ($threatChange -gt 0) {'+' })$threatChange threats)"++ $compChange = [int](Get-SafeProperty $trendsObj 'ComplianceScoreChange' 0)+ $compTrend = Get-SafeProperty $trendsObj 'ComplianceTrend' 'Stable'+ $reportData.Trends.ComplianceTrend = "$compTrend ($(if ($compChange -gt 0) {'+' })$compChange%)"++ $findingsChange = [int](Get-SafeProperty $trendsObj 'FindingsChange' 0)+ $findingsTrend = Get-SafeProperty $trendsObj 'FindingsTrend' 'Stable'+ $reportData.Trends.FindingsTrend = "$findingsTrend ($(if ($findingsChange -gt 0) {'+' })$findingsChange findings)"+ }++ # ============================================+ # GENERATE REPORT IN REQUESTED FORMAT(S)+ # ============================================+ Write-Host "`n[GENERATING REPORT]" -ForegroundColor Cyan++ $outputFiles = @()++ if ($OutputFormat -eq 'All' -or $OutputFormat -eq 'HTML') {+ Write-Host " Generating HTML report..." -ForegroundColor Gray+ $htmlFile = Join-Path $OutputPath "SecurityReport_$timestamp.html"+ $htmlContent = Generate-HTMLReport -ReportData $reportData+ $htmlContent | Out-File $htmlFile -Encoding UTF8 -Force+ $outputFiles += $htmlFile+ Write-Host " HTML report saved: $htmlFile" -ForegroundColor Green+ }++ if ($OutputFormat -eq 'All' -or $OutputFormat -eq 'JSON') {+ Write-Host " Generating JSON report..." -ForegroundColor Gray+ $jsonFile = Join-Path $OutputPath "SecurityReport_$timestamp.json"+ $reportData | ConvertTo-Json -Depth 10 | Out-File $jsonFile -Encoding UTF8 -Force+ $outputFiles += $jsonFile+ Write-Host " JSON report saved: $jsonFile" -ForegroundColor Green+ }++ if ($OutputFormat -eq 'All' -or $OutputFormat -eq 'DOCX') {+ Write-Host " Generating DOCX report..." -ForegroundColor Gray+ try {+ $docxFile = Join-Path $OutputPath "SecurityReport_$timestamp.docx"+ Generate-DOCXReport -ReportData $reportData -OutputFile $docxFile+ $outputFiles += $docxFile+ Write-Host " DOCX report saved: $docxFile" -ForegroundColor Green+ } catch {+ Write-Warning " Failed to generate DOCX report: $_"+ Write-Warning " Microsoft Word may not be installed"+ }+ }++ if ($OutputFormat -eq 'All' -or $OutputFormat -eq 'PDF') {+ Write-Host " Generating PDF report..." -ForegroundColor Gray+ Write-Warning " PDF generation requires wkhtmltopdf - converting HTML to PDF"+ try {+ $pdfFile = Join-Path $OutputPath "SecurityReport_$timestamp.pdf"+ $htmlFile = Join-Path $OutputPath "SecurityReport_$timestamp.html"++ if (Test-Path $htmlFile) {+ # Try to use wkhtmltopdf if available+ $wkhtmltopdf = Get-Command wkhtmltopdf -ErrorAction SilentlyContinue+ if ($wkhtmltopdf) {+ & wkhtmltopdf $htmlFile $pdfFile+ $outputFiles += $pdfFile+ Write-Host " PDF report saved: $pdfFile" -ForegroundColor Green+ } else {+ Write-Warning " wkhtmltopdf not found - install from: https://wkhtmltopdf.org/"+ }+ }+ } catch {+ Write-Warning " Failed to generate PDF report: $_"+ }+ }++ # ============================================+ # GENERATE EXECUTIVE SUMMARY (if requested)+ # ============================================+ if ($IncludeExecutiveSummary) {+ Write-Host "`n[GENERATING EXECUTIVE SUMMARY]" -ForegroundColor Cyan+ try {+ $summaryFile = Join-Path $OutputPath "ExecutiveSummary_$timestamp.html"+ $summaryContent = Generate-ExecutiveSummary -ReportData $reportData+ $summaryContent | Out-File $summaryFile -Encoding UTF8 -Force+ $outputFiles += $summaryFile+ Write-Host " Executive summary saved: $summaryFile" -ForegroundColor Green+ } catch {+ Write-Warning " Failed to generate executive summary: $_"+ }+ }++ # ============================================+ # RETURN SUMMARY+ # ============================================+ $reportDuration = [Math]::Round(((Get-Date) - $reportStartTime).TotalSeconds, 2)++ Write-Host "`n================================================================" -ForegroundColor Green+ Write-Host " REPORT GENERATION COMPLETE" -ForegroundColor Green+ Write-Host "================================================================" -ForegroundColor Green+ Write-Host " Generation Time: $reportDuration seconds" -ForegroundColor White+ Write-Host " Files Generated: $($outputFiles.Count)" -ForegroundColor White++ foreach ($file in $outputFiles) {+ $fileSize = [Math]::Round((Get-Item $file).Length / 1KB, 2)+ Write-Host " - $(Split-Path $file -Leaf) ($fileSize KB)" -ForegroundColor Gray+ }++ return [PSCustomObject]@{+ Success = $true+ ReportTitle = $ReportTitle+ CompanyName = $CompanyName+ GeneratedDate = $reportData.GeneratedDate+ OutputFiles = $outputFiles+ MetricsDate = Get-SafeProperty $metrics 'Timestamp' 'Unknown'+ SecurityScore = $reportData.Dashboard.SecurityScore+ RiskLevel = $reportData.Dashboard.RiskLevel+ TotalFindings = $reportData.Findings.Total+ GenerationTime = $reportDuration+ }++ }+ catch {+ Write-Error "Report generation failed: $_"+ Write-Host "`nStack Trace:" -ForegroundColor Red+ Write-Host $_.ScriptStackTrace -ForegroundColor Gray+ return [PSCustomObject]@{+ Success = $false+ Error = $_.Exception.Message+ }+ }+ }+}++# ============================================+# HELPER FUNCTIONS+# ============================================++function Get-ScoreColor {+ param([int]$Score)++ if ($Score -ge 90) { return "#28a745" } # Green+ elseif ($Score -ge 80) { return "#5cb85c" } # Light Green+ elseif ($Score -ge 70) { return "#f0ad4e" } # Orange+ elseif ($Score -ge 60) { return "#ff8c00" } # Dark Orange+ else { return "#d9534f" } # Red+}++function Get-RiskColor {+ param([string]$RiskLevel)++ switch ($RiskLevel) {+ 'Critical' { return "#8b0000" } # Dark Red+ 'High' { return "#d9534f" } # Red+ 'Medium' { return "#f0ad4e" } # Orange+ 'Low' { return "#5cb85c" } # Green+ default { return "#808080" } # Gray+ }+}++function Get-ThreatColor {+ param([string]$ThreatLevel)++ switch ($ThreatLevel) {+ 'Critical' { return "#8b0000" } # Dark Red+ 'High' { return "#d9534f" } # Red+ 'Medium' { return "#f0ad4e" } # Orange+ 'Low' { return "#f0ad4e" } # Orange+ 'Minimal' { return "#5cb85c" } # Green+ default { return "#808080" } # Gray+ }+}++function Generate-HTMLReport {+ param($ReportData)++ # Safe count helper+ function Get-SafeCount {+ param($Array)+ if ($null -eq $Array) { return 0 }+ if ($Array -is [array]) { return $Array.Count }+ if ($Array.Count) { return $Array.Count }+ return 1 # Single item+ }++ $html = @"+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>$($ReportData.ReportTitle)</title>+ <style>+ * { margin: 0; padding: 0; box-sizing: border-box; }+ body {+ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;+ line-height: 1.6;+ color: #333;+ background: #f4f4f4;+ }+ .container {+ max-width: 1200px;+ margin: 0 auto;+ background: white;+ box-shadow: 0 0 20px rgba(0,0,0,0.1);+ }+ .header {+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);+ color: white;+ padding: 40px;+ text-align: center;+ }+ .header h1 {+ font-size: 2.5em;+ margin-bottom: 10px;+ }+ .header .subtitle {+ font-size: 1.2em;+ opacity: 0.9;+ }+ $(if ($ReportData.Confidential) {+ ".confidential-banner {+ background: #d9534f;+ color: white;+ text-align: center;+ padding: 10px;+ font-weight: bold;+ font-size: 1.2em;+ }"+ })+ .section {+ padding: 40px;+ border-bottom: 1px solid #e0e0e0;+ }+ .section h2 {+ color: #667eea;+ margin-bottom: 20px;+ font-size: 2em;+ border-bottom: 3px solid #667eea;+ padding-bottom: 10px;+ }+ .dashboard {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));+ gap: 20px;+ margin: 20px 0;+ }+ .dashboard-card {+ background: white;+ border-radius: 10px;+ padding: 25px;+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);+ border-left: 5px solid;+ transition: transform 0.2s;+ }+ .dashboard-card:hover {+ transform: translateY(-5px);+ box-shadow: 0 6px 12px rgba(0,0,0,0.15);+ }+ .dashboard-card h3 {+ font-size: 0.9em;+ color: #666;+ text-transform: uppercase;+ letter-spacing: 1px;+ margin-bottom: 10px;+ }+ .dashboard-card .value {+ font-size: 3em;+ font-weight: bold;+ margin: 10px 0;+ }+ .dashboard-card .label {+ font-size: 1.1em;+ color: #666;+ }+ .risk-matrix {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+ gap: 15px;+ margin: 20px 0;+ }+ .risk-item {+ padding: 20px;+ border-radius: 8px;+ color: white;+ text-align: center;+ }+ .risk-item h4 {+ font-size: 1.5em;+ margin-bottom: 10px;+ }+ .risk-item .count {+ font-size: 3em;+ font-weight: bold;+ }+ .finding {+ background: #f9f9f9;+ border-left: 5px solid;+ padding: 20px;+ margin: 15px 0;+ border-radius: 5px;+ }+ .finding h4 {+ font-size: 1.3em;+ margin-bottom: 10px;+ }+ .finding .severity {+ display: inline-block;+ padding: 5px 15px;+ border-radius: 20px;+ color: white;+ font-weight: bold;+ margin-right: 10px;+ }+ .finding-detail {+ margin: 10px 0;+ padding-left: 20px;+ }+ .compliance-framework {+ background: white;+ border: 2px solid #e0e0e0;+ border-radius: 10px;+ padding: 20px;+ margin: 15px 0;+ }+ .compliance-bar {+ width: 100%;+ height: 30px;+ background: #e0e0e0;+ border-radius: 15px;+ overflow: hidden;+ margin: 10px 0;+ }+ .compliance-fill {+ height: 100%;+ background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);+ display: flex;+ align-items: center;+ justify-content: center;+ color: white;+ font-weight: bold;+ transition: width 1s;+ }+ .recommendation {+ background: #fff3cd;+ border-left: 5px solid #ffc107;+ padding: 15px;+ margin: 10px 0;+ border-radius: 5px;+ }+ .recommendation.critical {+ background: #f8d7da;+ border-left-color: #d9534f;+ }+ .recommendation.high {+ background: #ffe8cc;+ border-left-color: #ff8c00;+ }+ .roadmap-section {+ margin: 20px 0;+ }+ .roadmap-item {+ background: white;+ border: 2px solid #e0e0e0;+ border-radius: 8px;+ padding: 15px;+ margin: 10px 0;+ }+ .roadmap-item h5 {+ color: #667eea;+ margin-bottom: 10px;+ }+ table {+ width: 100%;+ border-collapse: collapse;+ margin: 20px 0;+ }+ th, td {+ padding: 12px;+ text-align: left;+ border-bottom: 1px solid #e0e0e0;+ }+ th {+ background: #667eea;+ color: white;+ font-weight: bold;+ }+ tr:hover {+ background: #f5f5f5;+ }+ .footer {+ background: #333;+ color: white;+ text-align: center;+ padding: 30px;+ }+ .footer p {+ margin: 5px 0;+ }+ @media print {+ .section { page-break-inside: avoid; }+ .dashboard-card { break-inside: avoid; }+ }+ </style>+</head>+<body>+ <div class="container">+ $(if ($ReportData.Confidential) {+ '<div class="confidential-banner">⚠ CONFIDENTIAL - INTERNAL USE ONLY ⚠</div>'+ })++ <div class="header">+ <h1>$($ReportData.ReportTitle)</h1>+ <div class="subtitle">$($ReportData.CompanyName)</div>+ <div class="subtitle">Generated: $($ReportData.GeneratedDate)</div>+ </div>++ <!-- EXECUTIVE SUMMARY -->+ <div class="section">+ <h2>📊 Executive Summary</h2>+ <p style="font-size: 1.2em; margin: 20px 0; line-height: 1.8;">+ $($ReportData.ExecutiveSummary.SecurityPosture)+ </p>++ $(if ((Get-SafeCount $ReportData.ExecutiveSummary.KeyFindings) -gt 0) {+ "<h3 style='margin-top: 30px; color: #667eea;'>Key Findings:</h3>+ <ul style='list-style: none; padding: 0;'>+ $(foreach ($finding in @($ReportData.ExecutiveSummary.KeyFindings)) {+ "<li style='padding: 10px 0; border-bottom: 1px solid #e0e0e0;'>🔍 $finding</li>"+ })+ </ul>"+ })++ $(if ((Get-SafeCount $ReportData.ExecutiveSummary.CriticalActions) -gt 0) {+ "<h3 style='margin-top: 30px; color: #d9534f;'>Critical Actions Required:</h3>+ <ul style='list-style: none; padding: 0;'>+ $(foreach ($action in @($ReportData.ExecutiveSummary.CriticalActions)) {+ "<li style='padding: 10px 0; border-bottom: 1px solid #e0e0e0;'>⚠ $action</li>"+ })+ </ul>"+ })++ <div style="background: #f0f8ff; padding: 20px; border-radius: 10px; margin-top: 30px;">+ <h3 style="color: #667eea;">Overall Risk Assessment:</h3>+ <p style="font-size: 1.1em; margin-top: 10px;">+ $($ReportData.ExecutiveSummary.OverallRisk)+ </p>+ </div>+ </div>++ <!-- SECURITY DASHBOARD -->+ <div class="section">+ <h2>📈 Security Dashboard</h2>+ <div class="dashboard">+ <div class="dashboard-card" style="border-left-color: $($ReportData.Dashboard.SecurityScoreColor);">+ <h3>Security Score</h3>+ <div class="value" style="color: $($ReportData.Dashboard.SecurityScoreColor);">+ $($ReportData.Dashboard.SecurityScore)%+ </div>+ <div class="label">Overall Security Posture</div>+ </div>++ <div class="dashboard-card" style="border-left-color: $($ReportData.Dashboard.RiskLevelColor);">+ <h3>Risk Level</h3>+ <div class="value" style="color: $($ReportData.Dashboard.RiskLevelColor);">+ $($ReportData.Dashboard.RiskLevel)+ </div>+ <div class="label">Organizational Risk</div>+ </div>++ <div class="dashboard-card" style="border-left-color: $($ReportData.Dashboard.ThreatLevelColor);">+ <h3>Threat Level</h3>+ <div class="value" style="color: $($ReportData.Dashboard.ThreatLevelColor);">+ $($ReportData.Dashboard.ThreatLevel)+ </div>+ <div class="label">Active Threat Exposure</div>+ </div>++ <div class="dashboard-card" style="border-left-color: $($ReportData.Dashboard.ComplianceScoreColor);">+ <h3>Compliance</h3>+ <div class="value" style="color: $($ReportData.Dashboard.ComplianceScoreColor);">+ $($ReportData.Dashboard.ComplianceScore)%+ </div>+ <div class="label">Regulatory Compliance</div>+ </div>+ </div>+ </div>++ <!-- RISK ASSESSMENT -->+ <div class="section">+ <h2>⚠ Risk Assessment</h2>+ <div class="risk-matrix">+ $(foreach ($risk in @($ReportData.RiskAssessment.RiskMatrix)) {+ "<div class='risk-item' style='background: $($risk.Color);'>+ <h4>$($risk.Category)</h4>+ <div class='count'>$($risk.Count)</div>+ </div>"+ })+ </div>++ $(if ((Get-SafeCount $ReportData.RiskAssessment.CriticalRisks) -gt 0) {+ "<h3 style='color: #d9534f; margin-top: 30px;'>🔴 Critical Risks</h3>+ $(foreach ($risk in @($ReportData.RiskAssessment.CriticalRisks)) {+ "<div class='finding' style='border-left-color: #d9534f;'>+ <h4>$($risk.Title) <span style='color: #999;'>($($risk.Count))</span></h4>+ <p style='margin: 10px 0;'>$($risk.Description)</p>+ <div class='finding-detail'>+ <strong>Impact:</strong> $($risk.Impact)<br>+ <strong>Affected Systems:</strong> $($risk.AffectedSystems)+ </div>+ </div>"+ })"+ })++ $(if ((Get-SafeCount $ReportData.RiskAssessment.HighRisks) -gt 0) {+ "<h3 style='color: #ff8c00; margin-top: 30px;'>🟠 High Risks</h3>+ $(foreach ($risk in @($ReportData.RiskAssessment.HighRisks)) {+ "<div class='finding' style='border-left-color: #ff8c00;'>+ <h4>$($risk.Title) <span style='color: #999;'>($($risk.Count))</span></h4>+ <p style='margin: 10px 0;'>$($risk.Description)</p>+ <div class='finding-detail'>+ <strong>Impact:</strong> $($risk.Impact)<br>+ <strong>Affected Systems:</strong> $($risk.AffectedSystems)+ </div>+ </div>"+ })"+ })+ </div>++ $(if ($IncludeCompliance -and (Get-SafeCount $ReportData.Compliance.Frameworks) -gt 0) {+ "<!-- COMPLIANCE STATUS -->+ <div class='section'>+ <h2>✅ Compliance Status</h2>+ <p style='font-size: 1.1em; margin-bottom: 20px;'>+ Overall Compliance Score: <strong>$($ReportData.Compliance.OverallCompliance)%</strong>+ </p>++ $(foreach ($framework in @($ReportData.Compliance.Frameworks)) {+ "<div class='compliance-framework'>+ <h3>$($framework.Name)</h3>+ <div class='compliance-bar'>+ <div class='compliance-fill' style='width: $($framework.Score)%; background: $($framework.Color);'>+ $($framework.Score)%+ </div>+ </div>+ <p>+ <strong>Status:</strong> $($framework.Status) |+ <strong>Controls:</strong> $($framework.PassedControls)/$($framework.TotalControls) passed+ </p>+ </div>"+ })++ $(if ((Get-SafeCount $ReportData.Compliance.GapAnalysis) -gt 0) {+ "<h3 style='margin-top: 30px;'>Gap Analysis:</h3>+ <ul style='padding-left: 20px;'>+ $(foreach ($gap in @($ReportData.Compliance.GapAnalysis)) {+ "<li style='margin: 10px 0;'>$gap</li>"+ })+ </ul>"+ })+ </div>"+ })++ <!-- THREAT ANALYSIS -->+ <div class="section">+ <h2>🎯 Threat Analysis</h2>+ <p style='font-size: 1.1em; margin-bottom: 20px;'>+ Total Active Threats: <strong style='color: #d9534f;'>$($ReportData.Threats.ActiveThreats)</strong>+ </p>++ $(if ((Get-SafeCount $ReportData.Threats.Categories) -gt 0) {+ "<table>+ <tr>+ <th>Threat Category</th>+ <th>Count</th>+ <th>Severity</th>+ </tr>+ $(foreach ($category in @($ReportData.Threats.Categories)) {+ $severityColor = switch ($category.Severity) {+ 'Critical' { '#d9534f' }+ 'High' { '#ff8c00' }+ 'Medium' { '#f0ad4e' }+ default { '#5cb85c' }+ }+ "<tr>+ <td>$($category.Name)</td>+ <td><strong>$($category.Count)</strong></td>+ <td><span style='color: $severityColor; font-weight: bold;'>$($category.Severity)</span></td>+ </tr>"+ })+ </table>"+ } else {+ "<p style='color: #5cb85c; font-size: 1.2em;'>✓ No active threats detected</p>"+ })+ </div>++ <!-- VULNERABILITIES -->+ <div class="section">+ <h2>🔓 Vulnerability Summary</h2>+ <div class="dashboard">+ <div class="dashboard-card" style="border-left-color: #d9534f;">+ <h3>Critical</h3>+ <div class="value" style="color: #d9534f;">$($ReportData.Vulnerabilities.Critical)</div>+ </div>+ <div class="dashboard-card" style="border-left-color: #ff8c00;">+ <h3>High</h3>+ <div class="value" style="color: #ff8c00;">$($ReportData.Vulnerabilities.High)</div>+ </div>+ <div class="dashboard-card" style="border-left-color: #f0ad4e;">+ <h3>Medium</h3>+ <div class="value" style="color: #f0ad4e;">$($ReportData.Vulnerabilities.Medium)</div>+ </div>+ <div class="dashboard-card" style="border-left-color: #5cb85c;">+ <h3>Low</h3>+ <div class="value" style="color: #5cb85c;">$($ReportData.Vulnerabilities.Low)</div>+ </div>+ </div>++ <p style="margin-top: 20px;">+ <strong>EOL Software:</strong> $($ReportData.Vulnerabilities.EOLSoftware) packages require immediate replacement<br>+ <strong>Certificate Issues:</strong> $($ReportData.Vulnerabilities.CertificateIssues) certificates need attention+ </p>+ </div>++ $(if ($IncludeRecommendations -and ((Get-SafeCount $ReportData.Recommendations.Critical) -gt 0 -or (Get-SafeCount $ReportData.Recommendations.High) -gt 0)) {+ "<!-- RECOMMENDATIONS -->+ <div class='section'>+ <h2>💡 Recommendations</h2>++ $(if ((Get-SafeCount $ReportData.Recommendations.Critical) -gt 0) {+ "<h3 style='color: #d9534f;'>Critical Priority</h3>+ $(foreach ($rec in @($ReportData.Recommendations.Critical)) {+ "<div class='recommendation critical'>+ <h4>$($rec.Text)</h4>+ <p>+ <strong>Timeline:</strong> $($rec.Timeline) |+ <strong>Effort:</strong> $($rec.Effort) |+ <strong>Impact:</strong> $($rec.Impact)+ </p>+ </div>"+ })"+ })++ $(if ((Get-SafeCount $ReportData.Recommendations.High) -gt 0) {+ "<h3 style='color: #ff8c00; margin-top: 30px;'>High Priority</h3>+ $(foreach ($rec in @($ReportData.Recommendations.High)) {+ "<div class='recommendation high'>+ <h4>$($rec.Text)</h4>+ <p>+ <strong>Timeline:</strong> $($rec.Timeline) |+ <strong>Effort:</strong> $($rec.Effort) |+ <strong>Impact:</strong> $($rec.Impact)+ </p>+ </div>"+ })"+ })+ </div>"+ })++ <!-- REMEDIATION ROADMAP -->+ <div class="section">+ <h2>🗺 Remediation Roadmap</h2>++ $(if ((Get-SafeCount $ReportData.RemediationRoadmap.ImmediateActions) -gt 0) {+ "<div class='roadmap-section'>+ <h3 style='color: #d9534f;'>🚨 Immediate Actions (0-7 days)</h3>+ $(foreach ($action in @($ReportData.RemediationRoadmap.ImmediateActions)) {+ "<div class='roadmap-item'>+ <h5>$($action.Action)</h5>+ <p>+ <strong>Owner:</strong> $($action.Owner)<br>+ <strong>Timeline:</strong> $($action.Timeline)<br>+ <strong>Resources:</strong> $($action.Resources)<br>+ <strong>Dependencies:</strong> $($action.Dependencies)+ </p>+ </div>"+ })+ </div>"+ })++ $(if ((Get-SafeCount $ReportData.RemediationRoadmap.ShortTerm) -gt 0) {+ "<div class='roadmap-section'>+ <h3 style='color: #ff8c00;'>⚡ Short-Term Actions (7-30 days)</h3>+ $(foreach ($action in @($ReportData.RemediationRoadmap.ShortTerm)) {+ "<div class='roadmap-item'>+ <h5>$($action.Action)</h5>+ <p>+ <strong>Owner:</strong> $($action.Owner)<br>+ <strong>Timeline:</strong> $($action.Timeline)<br>+ <strong>Resources:</strong> $($action.Resources)<br>+ <strong>Dependencies:</strong> $($action.Dependencies)+ </p>+ </div>"+ })+ </div>"+ })++ <div style="background: #f0f8ff; padding: 20px; border-radius: 10px; margin-top: 30px;">+ <h3>📊 Resource Estimate</h3>+ <p>+ <strong>Time Investment:</strong> $($ReportData.RemediationRoadmap.ResourceEstimate.TimeInvestment)<br>+ <strong>Estimated Cost:</strong> $($ReportData.RemediationRoadmap.ResourceEstimate.EstimatedCost)<br>+ <strong>Skills Required:</strong> $($ReportData.RemediationRoadmap.ResourceEstimate.SkillsRequired -join ', ')+ </p>+ </div>+ </div>++ $(if ($ReportData.Trends.Available) {+ "<!-- TREND ANALYSIS -->+ <div class='section'>+ <h2>📊 Trend Analysis</h2>+ <table>+ <tr>+ <th>Metric</th>+ <th>Trend</th>+ </tr>+ <tr>+ <td>Security Score</td>+ <td>$($ReportData.Trends.SecurityScoreTrend)</td>+ </tr>+ <tr>+ <td>Threats</td>+ <td>$($ReportData.Trends.ThreatTrend)</td>+ </tr>+ <tr>+ <td>Compliance</td>+ <td>$($ReportData.Trends.ComplianceTrend)</td>+ </tr>+ <tr>+ <td>Findings</td>+ <td>$($ReportData.Trends.FindingsTrend)</td>+ </tr>+ </table>+ </div>"+ })++ <div class="footer">+ <p><strong>$($ReportData.CompanyName) - Security Assessment Report</strong></p>+ <p>Generated: $($ReportData.GeneratedDate)</p>+ <p>WindowsSecurityAudit Module v1.2.0</p>+ $(if ($ReportData.Confidential) {+ '<p style="margin-top: 15px; color: #d9534f; font-weight: bold;">⚠ CONFIDENTIAL - DO NOT DISTRIBUTE ⚠</p>'+ })+ </div>+ </div>+</body>+</html>+"@++ return $html+}++function Generate-ExecutiveSummary {+ param($ReportData)++ # Safe count helper+ function Get-SafeCount {+ param($Array)+ if ($null -eq $Array) { return 0 }+ if ($Array -is [array]) { return $Array.Count }+ if ($Array.Count) { return $Array.Count }+ return 1 # Single item+ }++ # Simplified 1-page executive summary+ $html = @"+<!DOCTYPE html>+<html>+<head>+ <title>Executive Summary - $($ReportData.CompanyName)</title>+ <style>+ body { font-family: 'Segoe UI', sans-serif; padding: 40px; max-width: 800px; margin: 0 auto; }+ h1 { color: #667eea; border-bottom: 3px solid #667eea; padding-bottom: 10px; }+ .summary-box { background: #f8f9fa; padding: 20px; border-radius: 10px; margin: 20px 0; }+ .metric { display: inline-block; margin: 10px 20px 10px 0; }+ .metric-value { font-size: 2em; font-weight: bold; color: #667eea; }+ .metric-label { color: #666; }+ .critical-action { background: #f8d7da; border-left: 5px solid #d9534f; padding: 15px; margin: 10px 0; }+ ul { line-height: 2; }+ </style>+</head>+<body>+ <h1>Executive Summary</h1>+ <p><strong>$($ReportData.CompanyName)</strong> | $($ReportData.GeneratedDate)</p>++ <div class="summary-box">+ <h2>Overall Security Posture</h2>+ <p>$($ReportData.ExecutiveSummary.SecurityPosture)</p>++ <div class="metric">+ <div class="metric-value">$($ReportData.Dashboard.SecurityScore)%</div>+ <div class="metric-label">Security Score</div>+ </div>+ <div class="metric">+ <div class="metric-value">$($ReportData.Dashboard.RiskLevel)</div>+ <div class="metric-label">Risk Level</div>+ </div>+ <div class="metric">+ <div class="metric-value">$($ReportData.Dashboard.ComplianceScore)%</div>+ <div class="metric-label">Compliance</div>+ </div>+ </div>++ $(if ((Get-SafeCount $ReportData.ExecutiveSummary.KeyFindings) -gt 0) {+ "<h2>Key Findings</h2>+ <ul>+ $(foreach ($finding in @($ReportData.ExecutiveSummary.KeyFindings)) { "<li>$finding</li>" })+ </ul>"+ })++ $(if ((Get-SafeCount $ReportData.ExecutiveSummary.CriticalActions) -gt 0) {+ "<h2>Critical Actions Required</h2>+ $(foreach ($action in (@($ReportData.ExecutiveSummary.CriticalActions) | Select-Object -First 3)) {+ "<div class='critical-action'>⚠ $action</div>"+ })"+ })++ <div class="summary-box" style="margin-top: 30px;">+ <h2>Risk Assessment</h2>+ <p>$($ReportData.ExecutiveSummary.OverallRisk)</p>+ </div>+</body>+</html>+"@++ return $html+}++function Generate-DOCXReport {+ param(+ $ReportData,+ $OutputFile+ )++ # Try to use Microsoft Word COM object+ try {+ $word = New-Object -ComObject Word.Application+ $word.Visible = $false+ $doc = $word.Documents.Add()++ # Add title+ $selection = $word.Selection+ $selection.Font.Size = 24+ $selection.Font.Bold = $true+ $selection.Font.Color = 6697198 # Purple+ $selection.TypeText($ReportData.ReportTitle)+ $selection.TypeParagraph()++ $selection.Font.Size = 14+ $selection.Font.Bold = $false+ $selection.Font.Color = 0+ $selection.TypeText("$($ReportData.CompanyName) | $($ReportData.GeneratedDate)")+ $selection.TypeParagraph()+ $selection.TypeParagraph()++ # Add executive summary+ $selection.Font.Size = 18+ $selection.Font.Bold = $true+ $selection.TypeText("Executive Summary")+ $selection.TypeParagraph()++ $selection.Font.Size = 11+ $selection.Font.Bold = $false+ $selection.TypeText($ReportData.ExecutiveSummary.SecurityPosture)+ $selection.TypeParagraph()++ # Save and close+ $doc.SaveAs([ref]$OutputFile)+ $doc.Close()+ $word.Quit()++ [System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null+ Remove-Variable word+ [System.GC]::Collect()+ [System.GC]::WaitForPendingFinalizers()+ }+ catch {+ throw "Failed to generate DOCX report: $_"+ }+}\ No newline at end of filediff --git a/Reporting/New-SecurityDashboard.ps1 b/Reporting/New-SecurityDashboard.ps1new file mode 100644index 0000000..d494f10--- /dev/null+++ b/Reporting/New-SecurityDashboard.ps1@@ -0,0 +1,1397 @@+function New-SecurityDashboard {+ <#+ .SYNOPSIS+ Creates comprehensive security dashboard with ALL 54 functions++ .DESCRIPTION+ Enterprise security dashboard integrating all WindowsSecurityAudit functions++ .PARAMETER ExportPath+ Export directory (Default: current directory)++ .PARAMETER IncludeModules+ Modules: All, Core, Detection, Analysis, Compliance, ActiveDirectory,+ Cloud, Vulnerability, ThreatHunting, Forensics, WindowsDefender,+ Hardening, Enterprise, Response++ .PARAMETER Theme+ Light or Dark (Default: Light)++ .PARAMETER DetailLevel+ Summary, Standard, or Detailed (Default: Standard)++ .PARAMETER IncludeCharts+ Include interactive charts (Default: True)++ .PARAMETER AutoRefreshSeconds+ Auto-refresh interval in seconds (0 = disabled, Default: 0)++ .PARAMETER OpenInBrowser+ Auto-open dashboard in browser (Default: True)++ .PARAMETER SkipSlowChecks+ Skip time-consuming checks like full vulnerability scans++ .EXAMPLE+ New-SecurityDashboard+ Complete assessment with ALL 54 functions (default)++ .EXAMPLE+ New-SecurityDashboard -IncludeModules All+ Same as above - explicitly run ALL modules++ .EXAMPLE+ New-SecurityDashboard -IncludeModules Core,Detection -SkipSlowChecks+ Quick security check with Core and Detection modules only++ .EXAMPLE+ New-SecurityDashboard -Theme Dark -DetailLevel Detailed+ Full detailed assessment with dark theme++ .EXAMPLE+ New-SecurityDashboard -IncludeModules Compliance -ExportPath "C:\Reports"+ Compliance-only report saved to specific directory++ .NOTES+ Author: WindowsSecurityAudit Module+ Version: 3.0.0 ULTIMATE EDITION+ ALL 54 Functions Fully Integrated++ Requires: Administrator privileges for full functionality+ PowerShell Version: 5.1 or higher+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [string]$ExportPath = (Get-Location).Path,++ [Parameter()]+ [ValidateSet('All', 'Core', 'Detection', 'Analysis', 'Compliance', 'ActiveDirectory',+ 'Cloud', 'Vulnerability', 'ThreatHunting', 'Forensics', 'WindowsDefender',+ 'Hardening', 'Enterprise', 'Response')]+ [string[]]$IncludeModules = @('All'),++ [Parameter()]+ [ValidateSet('Light', 'Dark')]+ [string]$Theme = 'Light',++ [Parameter()]+ [ValidateSet('Summary', 'Standard', 'Detailed')]+ [string]$DetailLevel = 'Standard',++ [Parameter()]+ [bool]$IncludeCharts = $true,++ [Parameter()]+ [ValidateRange(0, 3600)]+ [int]$AutoRefreshSeconds = 0,++ [Parameter()]+ [bool]$OpenInBrowser = $true,++ [Parameter()]+ [switch]$SkipSlowChecks+ )++ begin {+ Write-Host "================================================================" -ForegroundColor Cyan+ Write-Host " ULTIMATE SECURITY DASHBOARD - ALL 54 FUNCTIONS" -ForegroundColor Cyan+ Write-Host "================================================================" -ForegroundColor Cyan++ if ($IncludeModules -contains 'All') {+ Write-Host "Mode: FULL ASSESSMENT - All 13 modules enabled" -ForegroundColor Yellow+ } else {+ Write-Host "Mode: SELECTIVE - $($IncludeModules -join ', ')" -ForegroundColor Yellow+ }++ $startTime = Get-Date++ # Validate and create export path+ if (-not (Test-Path $ExportPath)) {+ try {+ New-Item -Path $ExportPath -ItemType Directory -Force | Out-Null+ Write-Host "Created export directory: $ExportPath" -ForegroundColor Green+ }+ catch {+ Write-Error "Failed to create export directory: $_"+ throw+ }+ }++ # Determine which modules to process+ $modulesToProcess = if ($IncludeModules -contains 'All') {+ @('Core', 'Detection', 'Analysis', 'Compliance', 'ActiveDirectory', 'Cloud',+ 'Vulnerability', 'ThreatHunting', 'Forensics', 'WindowsDefender', 'Hardening',+ 'Enterprise', 'Response')+ } else {+ @($IncludeModules)+ }++ $moduleCount = @($modulesToProcess).Count+ Write-Host "Processing $moduleCount modules | Total Functions: 54" -ForegroundColor Yellow++ # Initialize comprehensive data structure with safe defaults+ $script:dashboardData = @{+ GeneratedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ Theme = $Theme+ DetailLevel = $DetailLevel+ Hostname = $env:COMPUTERNAME+ DomainName = if ($env:USERDNSDOMAIN) { $env:USERDNSDOMAIN } else { "WORKGROUP" }+ Username = $env:USERNAME+ TotalFunctionsUsed = 0++ ExecutiveSummary = @{+ OverallSecurityScore = 100+ TotalFindings = 0+ CriticalFindings = 0+ HighFindings = 0+ MediumFindings = 0+ LowFindings = 0+ ComplianceScore = 0+ ThreatLevel = "Low"+ Recommendations = @()+ }++ Core = @{+ SecurityBaseline = $null+ SystemInfo = $null+ SystemIntegrity = $null+ SecurityAssessment = $null+ }++ Detection = @{+ TotalThreats = 0+ PersistenceMechanisms = @()+ SuspiciousProcesses = @()+ SuspiciousAuthentications = @()+ LateralMovement = @()+ APTIndicators = @()+ LivingOffLand = @()+ DataExfiltration = @()+ NetworkAnomalies = @()+ }++ Analysis = @{+ EventLogAnalysis = $null+ RegistryAnalysis = $null+ FileSystemAnalysis = $null+ MemoryAnalysis = $null+ ExposedServices = @()+ SecurityMisconfigurations = @()+ }++ Compliance = @{+ CIS = $null+ NIST = $null+ PCIDSS = $null+ OverallReport = $null+ PatchCompliance = $null+ }++ ActiveDirectory = @{+ Enabled = $false+ PrivilegedAccounts = @()+ Vulnerabilities = @()+ SecurityPosture = $null+ Backdoors = @()+ StaleObjects = @()+ PasswordPolicy = $null+ }++ Cloud = @{+ Enabled = $false+ RiskySignIns = @()+ M365Security = $null+ CloudCompliance = $null+ }++ Vulnerability = @{+ TotalVulnerabilities = 0+ Assessment = $null+ EOLSoftware = @()+ CertificateHealth = $null+ }++ ThreatHunting = @{+ ThreatIntelligence = $null+ MITREMapping = $null+ }++ Forensics = @{+ Artifacts = @()+ ExecutionArtifacts = @()+ USBHistory = @()+ ForensicCollection = $null+ MemoryDump = $null+ Timeline = $null+ }++ WindowsDefender = @{+ Status = $null+ ScanResult = $null+ Configuration = $null+ }++ Hardening = @{+ AuditPolicies = $null+ PowerShellSecurity = $null+ BaselineStatus = $null+ }++ Enterprise = @{+ MultiSystemAudit = $null+ EnterpriseScan = $null+ }++ Response = @{+ IncidentResponse = $null+ EventDescriptions = @()+ }++ ChartsData = @{+ ComplianceScores = @()+ ThreatDistribution = @()+ ModuleStatus = @()+ }++ Performance = @{+ TotalExecutionTime = 0+ ModuleExecutionTimes = @{}+ }+ }+ }++ process {+ try {+ Write-Host "`n[DATA COLLECTION PHASE]" -ForegroundColor Cyan+ Write-Host "Starting security assessment..." -ForegroundColor Gray++ $functionCount = 0++ # ============================================+ # CORE MODULE (4 functions)+ # ============================================+ if ($modulesToProcess -contains 'Core') {+ Write-Host "`n[1/13] CORE MODULE - 4 Functions" -ForegroundColor Cyan+ $coreStart = Get-Date++ try {+ $script:dashboardData.Core.SecurityBaseline = Get-SecurityBaseline -ErrorAction Stop+ $functionCount+++ Write-Host " [1/54] Get-SecurityBaseline: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Get-SecurityBaseline failed: $_"+ }++ try {+ $script:dashboardData.Core.SystemInfo = Get-SystemInfo -ErrorAction Stop+ $functionCount+++ Write-Host " [2/54] Get-SystemInfo: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Get-SystemInfo failed: $_"+ }++ try {+ $script:dashboardData.Core.SystemIntegrity = Test-SystemIntegrity -ErrorAction Stop+ $functionCount+++ Write-Host " [3/54] Test-SystemIntegrity: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Test-SystemIntegrity failed: $_"+ }++ try {+ $script:dashboardData.Core.SecurityAssessment = Invoke-SecurityAssessment -ErrorAction Stop+ $functionCount+++ Write-Host " [4/54] Invoke-SecurityAssessment: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Invoke-SecurityAssessment failed: $_"+ }++ $script:dashboardData.Performance.ModuleExecutionTimes['Core'] = ((Get-Date) - $coreStart).TotalSeconds+ }++ # ============================================+ # DETECTION MODULE (8 functions)+ # ============================================+ if ($modulesToProcess -contains 'Detection') {+ Write-Host "`n[2/13] DETECTION MODULE - 8 Functions" -ForegroundColor Cyan+ $detStart = Get-Date++ try {+ $p = Find-PersistenceMechanisms -ErrorAction Stop+ $script:dashboardData.Detection.PersistenceMechanisms = $p+ $functionCount+++ Write-Host " [5/54] Find-PersistenceMechanisms: Found $(@($p).Count)" -ForegroundColor Green+ } catch {+ Write-Warning " Find-PersistenceMechanisms failed: $_"+ }++ try {+ $p = Find-SuspiciousProcesses -ErrorAction Stop+ $script:dashboardData.Detection.SuspiciousProcesses = $p+ $functionCount+++ Write-Host " [6/54] Find-SuspiciousProcesses: Found $(@($p).Count)" -ForegroundColor Green+ } catch {+ Write-Warning " Find-SuspiciousProcesses failed: $_"+ }++ try {+ $p = Find-SuspiciousAuthentication -ErrorAction Stop+ $script:dashboardData.Detection.SuspiciousAuthentications = $p+ $functionCount+++ Write-Host " [7/54] Find-SuspiciousAuthentication: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Find-SuspiciousAuthentication failed: $_"+ }++ try {+ $p = Find-LateralMovement -ErrorAction Stop+ $script:dashboardData.Detection.LateralMovement = $p+ $functionCount+++ Write-Host " [8/54] Find-LateralMovement: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Find-LateralMovement failed: $_"+ }++ try {+ $p = Find-APTIndicators -ErrorAction Stop+ $script:dashboardData.Detection.APTIndicators = $p+ $functionCount+++ Write-Host " [9/54] Find-APTIndicators: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Find-APTIndicators failed: $_"+ }++ try {+ $p = Find-LivingOffLand -ErrorAction Stop+ $script:dashboardData.Detection.LivingOffLand = $p+ $functionCount+++ Write-Host " [10/54] Find-LivingOffLand: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Find-LivingOffLand failed: $_"+ }++ try {+ $p = Find-DataExfiltration -ErrorAction Stop+ $script:dashboardData.Detection.DataExfiltration = $p+ $functionCount+++ Write-Host " [11/54] Find-DataExfiltration: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Find-DataExfiltration failed: $_"+ }++ try {+ $p = Find-NetworkAnomalies -ErrorAction Stop+ $script:dashboardData.Detection.NetworkAnomalies = $p+ $functionCount+++ Write-Host " [12/54] Find-NetworkAnomalies: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Find-NetworkAnomalies failed: $_"+ }++ # Calculate total threats+ $script:dashboardData.Detection.TotalThreats =+ @($script:dashboardData.Detection.PersistenceMechanisms).Count ++ @($script:dashboardData.Detection.SuspiciousProcesses).Count ++ @($script:dashboardData.Detection.SuspiciousAuthentications).Count ++ @($script:dashboardData.Detection.LateralMovement).Count ++ @($script:dashboardData.Detection.APTIndicators).Count ++ @($script:dashboardData.Detection.LivingOffLand).Count ++ @($script:dashboardData.Detection.DataExfiltration).Count ++ @($script:dashboardData.Detection.NetworkAnomalies).Count++ $script:dashboardData.Performance.ModuleExecutionTimes['Detection'] = ((Get-Date) - $detStart).TotalSeconds+ Write-Host " Total threats detected: $($script:dashboardData.Detection.TotalThreats)" -ForegroundColor $(if ($script:dashboardData.Detection.TotalThreats -gt 0) { 'Yellow' } else { 'Green' })+ }++ # ============================================+ # ANALYSIS MODULE (6 functions)+ # ============================================+ if ($modulesToProcess -contains 'Analysis') {+ Write-Host "`n[3/13] ANALYSIS MODULE - 6 Functions" -ForegroundColor Cyan+ $analStart = Get-Date++ try {+ $script:dashboardData.Analysis.EventLogAnalysis = Get-EventLogAnalysis -ErrorAction Stop+ $functionCount+++ Write-Host " [13/54] Get-EventLogAnalysis: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Get-EventLogAnalysis failed: $_"+ }++ try {+ $script:dashboardData.Analysis.RegistryAnalysis = Get-RegistryAnalysis -ErrorAction Stop+ $functionCount+++ Write-Host " [14/54] Get-RegistryAnalysis: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Get-RegistryAnalysis failed: $_"+ }++ if (-not $SkipSlowChecks) {+ try {+ $script:dashboardData.Analysis.FileSystemAnalysis = Get-FileSystemAnalysis -ErrorAction Stop+ $functionCount+++ Write-Host " [15/54] Get-FileSystemAnalysis: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Get-FileSystemAnalysis failed: $_"+ }++ try {+ $script:dashboardData.Analysis.MemoryAnalysis = Get-MemoryAnalysis -ErrorAction Stop+ $functionCount+++ Write-Host " [16/54] Get-MemoryAnalysis: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Get-MemoryAnalysis failed: $_"+ }+ } else {+ Write-Host " [15-16/54] Skipping slow checks (FileSystem, Memory)" -ForegroundColor Gray+ }++ try {+ $s = Get-ExposedServices -ErrorAction Stop+ $script:dashboardData.Analysis.ExposedServices = $s+ $functionCount+++ Write-Host " [17/54] Get-ExposedServices: Found $(@($s).Count)" -ForegroundColor Green+ } catch {+ Write-Warning " Get-ExposedServices failed: $_"+ }++ try {+ $s = Get-SecurityMisconfigurations -ErrorAction Stop+ $script:dashboardData.Analysis.SecurityMisconfigurations = $s+ $functionCount+++ Write-Host " [18/54] Get-SecurityMisconfigurations: Found $(@($s).Count)" -ForegroundColor Green+ } catch {+ Write-Warning " Get-SecurityMisconfigurations failed: $_"+ }++ $script:dashboardData.Performance.ModuleExecutionTimes['Analysis'] = ((Get-Date) - $analStart).TotalSeconds+ }++ # ============================================+ # COMPLIANCE MODULE (5 functions)+ # ============================================+ if ($modulesToProcess -contains 'Compliance') {+ Write-Host "`n[4/13] COMPLIANCE MODULE - 5 Functions" -ForegroundColor Cyan+ $compStart = Get-Date++ try {+ $c = Test-CISBenchmark -ErrorAction Stop+ $script:dashboardData.Compliance.CIS = $c+ $functionCount+++ Write-Host " [19/54] Test-CISBenchmark: $($c.ComplianceScore)%" -ForegroundColor Green+ } catch {+ Write-Warning " Test-CISBenchmark failed: $_"+ $script:dashboardData.Compliance.CIS = @{ ComplianceScore = 0; Status = "Error" }+ }++ try {+ $c = Test-NISTCompliance -ErrorAction Stop+ $script:dashboardData.Compliance.NIST = $c+ $functionCount+++ Write-Host " [20/54] Test-NISTCompliance: $($c.ComplianceScore)%" -ForegroundColor Green+ } catch {+ Write-Warning " Test-NISTCompliance failed: $_"+ $script:dashboardData.Compliance.NIST = @{ ComplianceScore = 0; Status = "Error" }+ }++ try {+ $c = Test-PCI-DSS -ErrorAction Stop+ $script:dashboardData.Compliance.PCIDSS = $c+ $functionCount+++ Write-Host " [21/54] Test-PCI-DSS: $($c.ComplianceScore)%" -ForegroundColor Green+ } catch {+ Write-Warning " Test-PCI-DSS failed: $_"+ $script:dashboardData.Compliance.PCIDSS = @{ ComplianceScore = 0; Status = "Error" }+ }++ try {+ $script:dashboardData.Compliance.OverallReport = Get-ComplianceReport -ErrorAction Stop+ $functionCount+++ Write-Host " [22/54] Get-ComplianceReport: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Get-ComplianceReport failed: $_"+ }++ try {+ $script:dashboardData.Compliance.PatchCompliance = Test-PatchCompliance -ErrorAction Stop+ $functionCount+++ Write-Host " [23/54] Test-PatchCompliance: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Test-PatchCompliance failed: $_"+ }++ $script:dashboardData.Performance.ModuleExecutionTimes['Compliance'] = ((Get-Date) - $compStart).TotalSeconds+ }++ # ============================================+ # ACTIVE DIRECTORY MODULE (6 functions)+ # ============================================+ if ($modulesToProcess -contains 'ActiveDirectory') {+ Write-Host "`n[5/13] ACTIVE DIRECTORY MODULE - 6 Functions" -ForegroundColor Cyan+ $adStart = Get-Date++ if ($env:USERDNSDOMAIN) {+ $script:dashboardData.ActiveDirectory.Enabled = $true++ try {+ $p = Get-ADPrivilegedAccounts -ErrorAction Stop+ $script:dashboardData.ActiveDirectory.PrivilegedAccounts = $p+ $functionCount+++ Write-Host " [24/54] Get-ADPrivilegedAccounts: Found $(@($p).Count)" -ForegroundColor Green+ } catch {+ Write-Warning " Get-ADPrivilegedAccounts failed: $_"+ }++ try {+ $v = Find-ADVulnerabilities -ErrorAction Stop+ $script:dashboardData.ActiveDirectory.Vulnerabilities = $v+ $functionCount+++ Write-Host " [25/54] Find-ADVulnerabilities: Found $(@($v).Count)" -ForegroundColor Green+ } catch {+ Write-Warning " Find-ADVulnerabilities failed: $_"+ }++ try {+ $script:dashboardData.ActiveDirectory.SecurityPosture = Test-ADSecurityPosture -ErrorAction Stop+ $functionCount+++ Write-Host " [26/54] Test-ADSecurityPosture: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Test-ADSecurityPosture failed: $_"+ }++ try {+ $b = Find-ADBackdoors -ErrorAction Stop+ $script:dashboardData.ActiveDirectory.Backdoors = $b+ $functionCount+++ Write-Host " [27/54] Find-ADBackdoors: Found $(@($b).Count)" -ForegroundColor Green+ } catch {+ Write-Warning " Find-ADBackdoors failed: $_"+ }++ try {+ $s = Find-StaleADObjects -ErrorAction Stop+ $script:dashboardData.ActiveDirectory.StaleObjects = $s+ $functionCount+++ Write-Host " [28/54] Find-StaleADObjects: Found $(@($s).Count)" -ForegroundColor Green+ } catch {+ Write-Warning " Find-StaleADObjects failed: $_"+ }++ try {+ $script:dashboardData.ActiveDirectory.PasswordPolicy = Get-ADPasswordPolicy -ErrorAction Stop+ $functionCount+++ Write-Host " [29/54] Get-ADPasswordPolicy: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Get-ADPasswordPolicy failed: $_"+ }+ } else {+ Write-Host " System not domain-joined - skipping AD module" -ForegroundColor Gray+ }++ $script:dashboardData.Performance.ModuleExecutionTimes['ActiveDirectory'] = ((Get-Date) - $adStart).TotalSeconds+ }++ # ============================================+ # CLOUD SECURITY MODULE (3 functions)+ # ============================================+ if ($modulesToProcess -contains 'Cloud') {+ Write-Host "`n[6/13] CLOUD SECURITY MODULE - 3 Functions" -ForegroundColor Cyan+ $cloudStart = Get-Date++ $mgContext = Get-MgContext -ErrorAction SilentlyContinue+ if ($mgContext) {+ $script:dashboardData.Cloud.Enabled = $true+ Write-Host " Connected to Microsoft Graph: $($mgContext.TenantId)" -ForegroundColor Green++ try {+ $r = Get-AzureADRiskySignIns -DaysBack 30 -ErrorAction Stop+ $script:dashboardData.Cloud.RiskySignIns = $r+ $functionCount+++ Write-Host " [30/54] Get-AzureADRiskySignIns: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Get-AzureADRiskySignIns failed: $_"+ }++ try {+ $script:dashboardData.Cloud.M365Security = Test-M365SecurityPosture -ErrorAction Stop+ $functionCount+++ Write-Host " [31/54] Test-M365SecurityPosture: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Test-M365SecurityPosture failed: $_"+ }++ try {+ $script:dashboardData.Cloud.CloudCompliance = Get-CloudComplianceStatus -Framework CIS -ErrorAction Stop+ $functionCount+++ Write-Host " [32/54] Get-CloudComplianceStatus: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Get-CloudComplianceStatus failed: $_"+ }+ } else {+ Write-Host " Not connected to Microsoft Graph - skipping cloud module" -ForegroundColor Gray+ Write-Host " To enable: Connect-MgGraph" -ForegroundColor Gray+ }++ $script:dashboardData.Performance.ModuleExecutionTimes['Cloud'] = ((Get-Date) - $cloudStart).TotalSeconds+ }++ # ============================================+ # VULNERABILITY MODULE (3 functions)+ # ============================================+ if ($modulesToProcess -contains 'Vulnerability') {+ Write-Host "`n[7/13] VULNERABILITY MODULE - 3 Functions" -ForegroundColor Cyan+ $vulnStart = Get-Date++ if (-not $SkipSlowChecks) {+ try {+ $v = Get-VulnerabilityAssessment -ErrorAction Stop+ $script:dashboardData.Vulnerability.Assessment = $v+ if ($v -and $v.Summary -and $v.Summary.TotalVulnerabilities) {+ $script:dashboardData.Vulnerability.TotalVulnerabilities = $v.Summary.TotalVulnerabilities+ }+ $functionCount+++ Write-Host " [33/54] Get-VulnerabilityAssessment: Found $($script:dashboardData.Vulnerability.TotalVulnerabilities)" -ForegroundColor Green+ } catch {+ Write-Warning " Get-VulnerabilityAssessment failed: $_"+ }+ } else {+ Write-Host " [33/54] Skipping vulnerability scan (slow check)" -ForegroundColor Gray+ }++ try {+ $e = Find-EOLSoftware -ErrorAction Stop+ $script:dashboardData.Vulnerability.EOLSoftware = $e+ $functionCount+++ Write-Host " [34/54] Find-EOLSoftware: Found $(@($e).Count)" -ForegroundColor Green+ } catch {+ Write-Warning " Find-EOLSoftware failed: $_"+ }++ try {+ $script:dashboardData.Vulnerability.CertificateHealth = Test-CertificateHealth -ErrorAction Stop+ $functionCount+++ Write-Host " [35/54] Test-CertificateHealth: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Test-CertificateHealth failed: $_"+ }++ $script:dashboardData.Performance.ModuleExecutionTimes['Vulnerability'] = ((Get-Date) - $vulnStart).TotalSeconds+ }++ # ============================================+ # THREAT HUNTING MODULE (2 functions)+ # ============================================+ if ($modulesToProcess -contains 'ThreatHunting') {+ Write-Host "`n[8/13] THREAT HUNTING MODULE - 2 Functions" -ForegroundColor Cyan+ $threatStart = Get-Date++ try {+ $script:dashboardData.ThreatHunting.ThreatIntelligence = Get-ThreatIntelligence -ErrorAction Stop+ $functionCount+++ Write-Host " [36/54] Get-ThreatIntelligence: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Get-ThreatIntelligence failed: $_"+ }++ try {+ $script:dashboardData.ThreatHunting.MITREMapping = Get-MITREAttackMapping -ErrorAction Stop+ $functionCount+++ Write-Host " [37/54] Get-MITREAttackMapping: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Get-MITREAttackMapping failed: $_"+ }++ $script:dashboardData.Performance.ModuleExecutionTimes['ThreatHunting'] = ((Get-Date) - $threatStart).TotalSeconds+ }++ # ============================================+ # FORENSICS MODULE (6 functions)+ # ============================================+ if ($modulesToProcess -contains 'Forensics') {+ Write-Host "`n[9/13] FORENSICS MODULE - 6 Functions" -ForegroundColor Cyan+ $forStart = Get-Date++ try {+ $a = Get-ArtifactCollection -ErrorAction Stop+ $script:dashboardData.Forensics.Artifacts = $a+ $functionCount+++ Write-Host " [38/54] Get-ArtifactCollection: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Get-ArtifactCollection failed: $_"+ }++ try {+ $e = Get-ExecutionArtifacts -ErrorAction Stop+ $script:dashboardData.Forensics.ExecutionArtifacts = $e+ $functionCount+++ Write-Host " [39/54] Get-ExecutionArtifacts: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Get-ExecutionArtifacts failed: $_"+ }++ try {+ $u = Get-USBHistory -ErrorAction Stop+ $script:dashboardData.Forensics.USBHistory = $u+ $functionCount+++ Write-Host " [40/54] Get-USBHistory: Found $(@($u).Count)" -ForegroundColor Green+ } catch {+ Write-Warning " Get-USBHistory failed: $_"+ }++ if ($DetailLevel -eq 'Detailed') {+ try {+ $script:dashboardData.Forensics.ForensicCollection = Invoke-ForensicCollection -ErrorAction Stop+ $functionCount+++ Write-Host " [41/54] Invoke-ForensicCollection: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Invoke-ForensicCollection failed: $_"+ }++ try {+ $script:dashboardData.Forensics.MemoryDump = Export-MemoryDump -ErrorAction Stop+ $functionCount+++ Write-Host " [42/54] Export-MemoryDump: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Export-MemoryDump failed: $_"+ }++ try {+ $script:dashboardData.Forensics.Timeline = New-ForensicTimeline -ErrorAction Stop+ $functionCount+++ Write-Host " [43/54] New-ForensicTimeline: OK" -ForegroundColor Green+ } catch {+ Write-Warning " New-ForensicTimeline failed: $_"+ }+ } else {+ Write-Host " [41-43/54] Skipping detailed forensics (use -DetailLevel Detailed)" -ForegroundColor Gray+ }++ $script:dashboardData.Performance.ModuleExecutionTimes['Forensics'] = ((Get-Date) - $forStart).TotalSeconds+ }++ # ============================================+ # WINDOWS DEFENDER MODULE (3 functions)+ # ============================================+ if ($modulesToProcess -contains 'WindowsDefender') {+ Write-Host "`n[10/13] WINDOWS DEFENDER MODULE - 3 Functions" -ForegroundColor Cyan+ $defStart = Get-Date++ try {+ $d = Get-DefenderStatus -ErrorAction Stop+ $script:dashboardData.WindowsDefender.Status = $d+ $functionCount+++ Write-Host " [44/54] Get-DefenderStatus: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Get-DefenderStatus failed: $_"+ }++ if ($DetailLevel -eq 'Detailed') {+ try {+ $script:dashboardData.WindowsDefender.ScanResult = Invoke-DefenderScan -ScanType Quick -ErrorAction Stop+ $functionCount+++ Write-Host " [45/54] Invoke-DefenderScan: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Invoke-DefenderScan failed: $_"+ }+ } else {+ Write-Host " [45/54] Skipping Defender scan (use -DetailLevel Detailed)" -ForegroundColor Gray+ }++ try {+ $script:dashboardData.WindowsDefender.Configuration = Update-DefenderConfiguration -WhatIf -ErrorAction Stop+ $functionCount+++ Write-Host " [46/54] Update-DefenderConfiguration (Check): OK" -ForegroundColor Green+ } catch {+ Write-Warning " Update-DefenderConfiguration failed: $_"+ }++ $script:dashboardData.Performance.ModuleExecutionTimes['WindowsDefender'] = ((Get-Date) - $defStart).TotalSeconds+ }++ # ============================================+ # HARDENING MODULE (3 functions)+ # ============================================+ if ($modulesToProcess -contains 'Hardening') {+ Write-Host "`n[11/13] HARDENING MODULE - 3 Functions" -ForegroundColor Cyan+ $hardStart = Get-Date++ try {+ $script:dashboardData.Hardening.AuditPolicies = Enable-AuditPolicies -WhatIf -ErrorAction Stop+ $functionCount+++ Write-Host " [47/54] Enable-AuditPolicies (Check): OK" -ForegroundColor Green+ } catch {+ Write-Warning " Enable-AuditPolicies failed: $_"+ }++ try {+ $script:dashboardData.Hardening.PowerShellSecurity = Enable-PowerShellSecurity -WhatIf -ErrorAction Stop+ $functionCount+++ Write-Host " [48/54] Enable-PowerShellSecurity (Check): OK" -ForegroundColor Green+ } catch {+ Write-Warning " Enable-PowerShellSecurity failed: $_"+ }++ try {+ $script:dashboardData.Hardening.BaselineStatus = Set-SecurityBaseline -WhatIf -ErrorAction Stop+ $functionCount+++ Write-Host " [49/54] Set-SecurityBaseline (Check): OK" -ForegroundColor Green+ } catch {+ Write-Warning " Set-SecurityBaseline failed: $_"+ }++ $script:dashboardData.Performance.ModuleExecutionTimes['Hardening'] = ((Get-Date) - $hardStart).TotalSeconds+ }++ # ============================================+ # ENTERPRISE MODULE (2 functions)+ # ============================================+ if ($modulesToProcess -contains 'Enterprise') {+ Write-Host "`n[12/13] ENTERPRISE MODULE - 2 Functions" -ForegroundColor Cyan+ $entStart = Get-Date++ if ($DetailLevel -eq 'Detailed') {+ try {+ $script:dashboardData.Enterprise.MultiSystemAudit = Get-MultiSystemAudit -ErrorAction Stop+ $functionCount+++ Write-Host " [50/54] Get-MultiSystemAudit: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Get-MultiSystemAudit failed: $_"+ }++ try {+ $script:dashboardData.Enterprise.EnterpriseScan = Invoke-EnterpriseSecurityScan -ErrorAction Stop+ $functionCount+++ Write-Host " [51/54] Invoke-EnterpriseSecurityScan: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Invoke-EnterpriseSecurityScan failed: $_"+ }+ } else {+ Write-Host " [50-51/54] Skipping enterprise scan (use -DetailLevel Detailed)" -ForegroundColor Gray+ }++ $script:dashboardData.Performance.ModuleExecutionTimes['Enterprise'] = ((Get-Date) - $entStart).TotalSeconds+ }++ # ============================================+ # RESPONSE MODULE (2 functions)+ # ============================================+ if ($modulesToProcess -contains 'Response') {+ Write-Host "`n[13/13] RESPONSE MODULE - 2 Functions" -ForegroundColor Cyan+ $respStart = Get-Date++ try {+ $script:dashboardData.Response.IncidentResponse = Invoke-IncidentResponse -WhatIf -ErrorAction Stop+ $functionCount+++ Write-Host " [52/54] Invoke-IncidentResponse (Check): OK" -ForegroundColor Green+ } catch {+ Write-Warning " Invoke-IncidentResponse failed: $_"+ }++ try {+ $script:dashboardData.Response.EventDescriptions = Get-EventIdDescription -EventId 4624 -ErrorAction Stop+ $functionCount+++ Write-Host " [53/54] Get-EventIdDescription: OK" -ForegroundColor Green+ } catch {+ Write-Warning " Get-EventIdDescription failed: $_"+ }++ $script:dashboardData.Performance.ModuleExecutionTimes['Response'] = ((Get-Date) - $respStart).TotalSeconds+ }++ # Save total function count+ $script:dashboardData.TotalFunctionsUsed = $functionCount++ # ============================================+ # CALCULATE EXECUTIVE SUMMARY+ # ============================================+ Write-Host "`n[CALCULATING EXECUTIVE SUMMARY]" -ForegroundColor Cyan++ # Aggregate findings with null-safe operations+ $script:dashboardData.ExecutiveSummary.TotalFindings =+ $script:dashboardData.Detection.TotalThreats ++ $script:dashboardData.Vulnerability.TotalVulnerabilities ++ $(if ($script:dashboardData.Analysis.SecurityMisconfigurations) { @($script:dashboardData.Analysis.SecurityMisconfigurations).Count } else { 0 })++ $script:dashboardData.ExecutiveSummary.HighFindings = $script:dashboardData.Detection.TotalThreats+ $script:dashboardData.ExecutiveSummary.MediumFindings = $script:dashboardData.Vulnerability.TotalVulnerabilities+ $script:dashboardData.ExecutiveSummary.LowFindings = $(if ($script:dashboardData.Analysis.SecurityMisconfigurations) { @($script:dashboardData.Analysis.SecurityMisconfigurations).Count } else { 0 })++ if ($script:dashboardData.ActiveDirectory.Enabled) {+ $adVulns = $(if ($script:dashboardData.ActiveDirectory.Vulnerabilities) { @($script:dashboardData.ActiveDirectory.Vulnerabilities).Count } else { 0 })+ $script:dashboardData.ExecutiveSummary.CriticalFindings = $adVulns+ $script:dashboardData.ExecutiveSummary.TotalFindings += $adVulns+ }++ # Compliance score with proper null checks+ $scores = @()+ if ($script:dashboardData.Compliance.CIS -and $script:dashboardData.Compliance.CIS.ComplianceScore) {+ $scores += $script:dashboardData.Compliance.CIS.ComplianceScore+ }+ if ($script:dashboardData.Compliance.NIST -and $script:dashboardData.Compliance.NIST.ComplianceScore) {+ $scores += $script:dashboardData.Compliance.NIST.ComplianceScore+ }+ if ($script:dashboardData.Compliance.PCIDSS -and $script:dashboardData.Compliance.PCIDSS.ComplianceScore) {+ $scores += $script:dashboardData.Compliance.PCIDSS.ComplianceScore+ }++ if ($scores.Count -gt 0) {+ $script:dashboardData.ExecutiveSummary.ComplianceScore = [Math]::Round(($scores | Measure-Object -Average).Average, 1)+ } else {+ $script:dashboardData.ExecutiveSummary.ComplianceScore = 0+ }++ # Security score calculation+ $penalty = ($script:dashboardData.ExecutiveSummary.CriticalFindings * 15) ++ ($script:dashboardData.ExecutiveSummary.HighFindings * 10) ++ ($script:dashboardData.ExecutiveSummary.MediumFindings * 5) ++ ($script:dashboardData.ExecutiveSummary.LowFindings * 2)++ $script:dashboardData.ExecutiveSummary.OverallSecurityScore = [Math]::Max(0, 100 - $penalty)++ # Threat level determination+ $script:dashboardData.ExecutiveSummary.ThreatLevel =+ if ($script:dashboardData.ExecutiveSummary.CriticalFindings -gt 5) { "Critical" }+ elseif ($script:dashboardData.ExecutiveSummary.CriticalFindings -gt 0) { "High" }+ elseif ($script:dashboardData.ExecutiveSummary.HighFindings -gt 10) { "High" }+ elseif ($script:dashboardData.ExecutiveSummary.HighFindings -gt 0) { "Medium" }+ else { "Low" }++ # Generate recommendations+ if ($script:dashboardData.ExecutiveSummary.CriticalFindings -gt 0) {+ $script:dashboardData.ExecutiveSummary.Recommendations += "CRITICAL: $($script:dashboardData.ExecutiveSummary.CriticalFindings) critical issues require immediate attention"+ }+ if ($script:dashboardData.Detection.TotalThreats -gt 0) {+ $script:dashboardData.ExecutiveSummary.Recommendations += "Investigate and remediate $($script:dashboardData.Detection.TotalThreats) detected threats"+ }+ if ($script:dashboardData.ExecutiveSummary.ComplianceScore -lt 80 -and $script:dashboardData.ExecutiveSummary.ComplianceScore -gt 0) {+ $script:dashboardData.ExecutiveSummary.Recommendations += "Compliance score below 80% - review and address compliance gaps"+ }+ if ($script:dashboardData.Vulnerability.EOLSoftware -and @($script:dashboardData.Vulnerability.EOLSoftware).Count -gt 0) {+ $script:dashboardData.ExecutiveSummary.Recommendations += "Replace or upgrade $(@($script:dashboardData.Vulnerability.EOLSoftware).Count) end-of-life software packages"+ }++ # Generate chart data if enabled+ if ($IncludeCharts) {+ # Compliance scores+ $script:dashboardData.ChartsData.ComplianceScores = @(+ @{ Framework = "CIS"; Score = $(if ($script:dashboardData.Compliance.CIS -and $script:dashboardData.Compliance.CIS.ComplianceScore) { $script:dashboardData.Compliance.CIS.ComplianceScore } else { 0 }) }+ @{ Framework = "NIST"; Score = $(if ($script:dashboardData.Compliance.NIST -and $script:dashboardData.Compliance.NIST.ComplianceScore) { $script:dashboardData.Compliance.NIST.ComplianceScore } else { 0 }) }+ @{ Framework = "PCI-DSS"; Score = $(if ($script:dashboardData.Compliance.PCIDSS -and $script:dashboardData.Compliance.PCIDSS.ComplianceScore) { $script:dashboardData.Compliance.PCIDSS.ComplianceScore } else { 0 }) }+ )++ # Threat distribution+ $script:dashboardData.ChartsData.ThreatDistribution = @(+ @{ Category = "Persistence"; Count = @($script:dashboardData.Detection.PersistenceMechanisms).Count }+ @{ Category = "Processes"; Count = @($script:dashboardData.Detection.SuspiciousProcesses).Count }+ @{ Category = "Auth"; Count = @($script:dashboardData.Detection.SuspiciousAuthentications).Count }+ @{ Category = "Lateral"; Count = @($script:dashboardData.Detection.LateralMovement).Count }+ @{ Category = "APT"; Count = @($script:dashboardData.Detection.APTIndicators).Count }+ )++ # Module status+ $script:dashboardData.ChartsData.ModuleStatus = @(+ @{ Module = "Core"; Active = ($modulesToProcess -contains 'Core') }+ @{ Module = "Detection"; Active = ($modulesToProcess -contains 'Detection') }+ @{ Module = "Compliance"; Active = ($modulesToProcess -contains 'Compliance') }+ @{ Module = "AD"; Active = ($modulesToProcess -contains 'ActiveDirectory') }+ @{ Module = "Cloud"; Active = ($modulesToProcess -contains 'Cloud') }+ @{ Module = "Defender"; Active = ($modulesToProcess -contains 'WindowsDefender') }+ )+ }++ # Calculate total execution time+ $script:dashboardData.Performance.TotalExecutionTime = ((Get-Date) - $startTime).TotalSeconds++ Write-Host " Security Score: $($script:dashboardData.ExecutiveSummary.OverallSecurityScore)%" -ForegroundColor $(+ if ($script:dashboardData.ExecutiveSummary.OverallSecurityScore -ge 80) { 'Green' }+ elseif ($script:dashboardData.ExecutiveSummary.OverallSecurityScore -ge 60) { 'Yellow' }+ else { 'Red' }+ )+ Write-Host " Threat Level: $($script:dashboardData.ExecutiveSummary.ThreatLevel)" -ForegroundColor $(+ switch ($script:dashboardData.ExecutiveSummary.ThreatLevel) {+ 'Critical' { 'Red' }+ 'High' { 'Red' }+ 'Medium' { 'Yellow' }+ default { 'Green' }+ }+ )+ Write-Host " Functions Used: $functionCount/54" -ForegroundColor Yellow++ # ============================================+ # GENERATE HTML DASHBOARD+ # ============================================+ Write-Host "`n[GENERATING HTML DASHBOARD]" -ForegroundColor Cyan++ $htmlPath = Generate-DashboardHTML -Data $script:dashboardData -ExportPath $ExportPath -IncludeCharts $IncludeCharts -AutoRefresh $AutoRefreshSeconds++ Write-Host " Dashboard saved: $htmlPath" -ForegroundColor Green+ Write-Host " File size: $([Math]::Round((Get-Item $htmlPath).Length / 1KB, 2)) KB" -ForegroundColor Gray++ if ($OpenInBrowser) {+ Write-Host "`n[OPENING IN BROWSER]" -ForegroundColor Cyan+ Start-Process $htmlPath+ }++ return Get-Item $htmlPath++ }+ catch {+ Write-Error "Dashboard generation failed: $_"+ Write-Host "`nStack Trace:" -ForegroundColor Red+ Write-Host $_.ScriptStackTrace -ForegroundColor Gray+ throw+ }+ }++ end {+ $totalTime = [Math]::Round(((Get-Date) - $startTime).TotalSeconds, 2)++ Write-Host "`n================================================================" -ForegroundColor Green+ Write-Host " DASHBOARD GENERATION COMPLETE" -ForegroundColor Green+ Write-Host "================================================================" -ForegroundColor Green++ Write-Host "`nExecution Summary:" -ForegroundColor Cyan+ Write-Host " Total Execution Time: $totalTime seconds" -ForegroundColor White+ Write-Host " Functions Used: $($script:dashboardData.TotalFunctionsUsed)/54" -ForegroundColor Yellow++ if ($script:dashboardData.Performance.ModuleExecutionTimes.Count -gt 0) {+ Write-Host "`nModule Execution Times:" -ForegroundColor Cyan+ foreach ($module in $script:dashboardData.Performance.ModuleExecutionTimes.Keys | Sort-Object) {+ $time = [Math]::Round($script:dashboardData.Performance.ModuleExecutionTimes[$module], 2)+ Write-Host " $module : $time seconds" -ForegroundColor Gray+ }+ }++ Write-Host "`nSecurity Summary:" -ForegroundColor Cyan+ Write-Host " Security Score: $($script:dashboardData.ExecutiveSummary.OverallSecurityScore)%" -ForegroundColor $(+ if ($script:dashboardData.ExecutiveSummary.OverallSecurityScore -ge 80) { 'Green' }+ elseif ($script:dashboardData.ExecutiveSummary.OverallSecurityScore -ge 60) { 'Yellow' }+ else { 'Red' }+ )+ Write-Host " Threat Level: $($script:dashboardData.ExecutiveSummary.ThreatLevel)" -ForegroundColor $(+ switch ($script:dashboardData.ExecutiveSummary.ThreatLevel) {+ 'Critical' { 'Red' }+ 'High' { 'Red' }+ 'Medium' { 'Yellow' }+ default { 'Green' }+ }+ )+ Write-Host " Total Findings: $($script:dashboardData.ExecutiveSummary.TotalFindings)" -ForegroundColor White+ Write-Host " Critical: $($script:dashboardData.ExecutiveSummary.CriticalFindings)" -ForegroundColor Red+ Write-Host " High: $($script:dashboardData.ExecutiveSummary.HighFindings)" -ForegroundColor Yellow+ Write-Host " Medium: $($script:dashboardData.ExecutiveSummary.MediumFindings)" -ForegroundColor Yellow+ Write-Host " Low: $($script:dashboardData.ExecutiveSummary.LowFindings)" -ForegroundColor Gray++ if ($script:dashboardData.ExecutiveSummary.ComplianceScore -gt 0) {+ Write-Host " Compliance Score: $($script:dashboardData.ExecutiveSummary.ComplianceScore)%" -ForegroundColor Cyan+ }+ }+}++# ============================================+# HELPER FUNCTION: Generate Dashboard HTML+# ============================================+function Generate-DashboardHTML {+ param(+ [Parameter(Mandatory=$true)]+ $Data,++ [Parameter(Mandatory=$true)]+ [string]$ExportPath,++ [Parameter(Mandatory=$true)]+ [bool]$IncludeCharts,++ [Parameter(Mandatory=$true)]+ [int]$AutoRefresh+ )++ $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"+ $filename = "SecurityDashboard_$timestamp.html"+ $outputPath = Join-Path $ExportPath $filename++ # Theme colors+ $isDark = $Data.Theme -eq 'Dark'+ $bgColor = if ($isDark) { '#1a1a1a' } else { '#f5f5f5' }+ $cardBg = if ($isDark) { '#2d2d2d' } else { '#ffffff' }+ $textColor = if ($isDark) { '#e0e0e0' } else { '#333333' }+ $borderColor = if ($isDark) { '#404040' } else { '#dddddd' }++ # Score color+ $scoreColor = if ($Data.ExecutiveSummary.OverallSecurityScore -ge 80) { '#107c10' }+ elseif ($Data.ExecutiveSummary.OverallSecurityScore -ge 60) { '#f7630c' }+ else { '#d13438' }++ # Threat level color+ $threatColor = switch ($Data.ExecutiveSummary.ThreatLevel) {+ 'Critical' { '#d13438' }+ 'High' { '#f57c00' }+ 'Medium' { '#fbc02d' }+ default { '#107c10' }+ }++ # Build HTML using StringBuilder to avoid parse errors+ $html = New-Object System.Text.StringBuilder++ [void]$html.AppendLine("<!DOCTYPE html>")+ [void]$html.AppendLine("<html lang='en'>")+ [void]$html.AppendLine("<head>")+ [void]$html.AppendLine(" <meta charset='UTF-8'>")+ [void]$html.AppendLine(" <meta name='viewport' content='width=device-width, initial-scale=1.0'>")+ [void]$html.AppendLine(" <title>Security Dashboard - $($Data.Hostname)</title>")++ if ($AutoRefresh -gt 0) {+ [void]$html.AppendLine(" <meta http-equiv='refresh' content='$AutoRefresh'>")+ }++ if ($IncludeCharts) {+ [void]$html.AppendLine(" <script src='https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js'></script>")+ }++ # CSS Styles+ [void]$html.AppendLine(" <style>")+ [void]$html.AppendLine(" * { margin: 0; padding: 0; box-sizing: border-box; }")+ [void]$html.AppendLine(" body { font-family: 'Segoe UI', Tahoma, sans-serif; background: $bgColor; color: $textColor; padding: 20px; line-height: 1.6; }")+ [void]$html.AppendLine(" .container { max-width: 1600px; margin: 0 auto; }")+ [void]$html.AppendLine(" .header { background: linear-gradient(135deg, #0d47a1, #1565c0); color: white; padding: 30px; border-radius: 10px; margin-bottom: 30px; box-shadow: 0 4px 15px rgba(0,0,0,0.3); }")+ [void]$html.AppendLine(" .header h1 { font-size: 32px; margin-bottom: 5px; }")+ [void]$html.AppendLine(" .header-subtitle { font-size: 14px; opacity: 0.9; margin-bottom: 15px; }")+ [void]$html.AppendLine(" .header-info { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 15px; margin-top: 15px; }")+ [void]$html.AppendLine(" .header-info-item { background: rgba(255,255,255,0.1); padding: 10px; border-radius: 5px; }")+ [void]$html.AppendLine(" .header-info-label { font-size: 11px; opacity: 0.8; }")+ [void]$html.AppendLine(" .header-info-value { font-size: 14px; font-weight: 600; margin-top: 3px; }")+ [void]$html.AppendLine(" .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 30px; }")+ [void]$html.AppendLine(" .card { background: $cardBg; border: 1px solid $borderColor; border-radius: 8px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); transition: transform 0.2s; }")+ [void]$html.AppendLine(" .card:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.15); }")+ [void]$html.AppendLine(" .card-header { font-size: 16px; font-weight: 600; color: #0078d4; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 2px solid $borderColor; }")+ [void]$html.AppendLine(" .large-metric { text-align: center; padding: 30px 15px; }")+ [void]$html.AppendLine(" .large-metric-value { font-size: 64px; font-weight: bold; margin-bottom: 8px; }")+ [void]$html.AppendLine(" .large-metric-label { font-size: 16px; color: #666; }")+ [void]$html.AppendLine(" .metric { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px solid #f0f0f0; }")+ [void]$html.AppendLine(" .metric:last-child { border-bottom: none; }")+ [void]$html.AppendLine(" .metric-label { font-size: 14px; color: #666; }")+ [void]$html.AppendLine(" .metric-value { font-size: 16px; font-weight: bold; }")+ [void]$html.AppendLine(" .critical { color: #d32f2f; }")+ [void]$html.AppendLine(" .high { color: #f57c00; }")+ [void]$html.AppendLine(" .medium { color: #fbc02d; }")+ [void]$html.AppendLine(" .low { color: #388e3c; }")+ [void]$html.AppendLine(" .success { color: #107c10; }")+ [void]$html.AppendLine(" h2 { color: #0078d4; margin: 30px 0 15px 0; padding-left: 10px; border-left: 4px solid #0078d4; font-size: 20px; }")+ [void]$html.AppendLine(" .chart-container { position: relative; height: 280px; margin-top: 15px; }")+ [void]$html.AppendLine(" .recommendations { background: #fff4ce; border-left: 4px solid #f7630c; padding: 20px; margin-top: 20px; border-radius: 5px; }")+ [void]$html.AppendLine(" .recommendations h3 { color: #8a5340; margin-bottom: 10px; }")+ [void]$html.AppendLine(" .recommendations ul { margin-left: 20px; }")+ [void]$html.AppendLine(" .recommendations li { margin: 8px 0; color: #323130; }")+ [void]$html.AppendLine(" .footer { margin-top: 40px; padding-top: 20px; border-top: 2px solid $borderColor; text-align: center; color: #999; font-size: 12px; }")+ [void]$html.AppendLine(" @media (max-width: 768px) { .grid { grid-template-columns: 1fr; } .header h1 { font-size: 24px; } .large-metric-value { font-size: 48px; } }")+ [void]$html.AppendLine(" </style>")+ [void]$html.AppendLine("</head>")+ [void]$html.AppendLine("<body>")+ [void]$html.AppendLine(" <div class='container'>")++ # Header+ [void]$html.AppendLine(" <div class='header'>")+ [void]$html.AppendLine(" <h1>Security Dashboard</h1>")+ [void]$html.AppendLine(" <div class='header-subtitle'>Enterprise Security Assessment - WindowsSecurityAudit Module v3.0</div>")+ [void]$html.AppendLine(" <div class='header-info'>")+ [void]$html.AppendLine(" <div class='header-info-item'><div class='header-info-label'>Hostname</div><div class='header-info-value'>$($Data.Hostname)</div></div>")+ [void]$html.AppendLine(" <div class='header-info-item'><div class='header-info-label'>Domain</div><div class='header-info-value'>$($Data.DomainName)</div></div>")+ [void]$html.AppendLine(" <div class='header-info-item'><div class='header-info-label'>User</div><div class='header-info-value'>$($Data.Username)</div></div>")+ [void]$html.AppendLine(" <div class='header-info-item'><div class='header-info-label'>Generated</div><div class='header-info-value'>$($Data.GeneratedDate)</div></div>")+ [void]$html.AppendLine(" <div class='header-info-item'><div class='header-info-label'>Execution Time</div><div class='header-info-value'>$([Math]::Round($Data.Performance.TotalExecutionTime, 1))s</div></div>")+ [void]$html.AppendLine(" <div class='header-info-item'><div class='header-info-label'>Functions Used</div><div class='header-info-value'>$($Data.TotalFunctionsUsed)/54</div></div>")+ [void]$html.AppendLine(" </div>")+ [void]$html.AppendLine(" </div>")++ # Executive Summary Grid+ [void]$html.AppendLine(" <div class='grid'>")++ # Security Score Card+ [void]$html.AppendLine(" <div class='card'>")+ [void]$html.AppendLine(" <div class='large-metric'>")+ [void]$html.AppendLine(" <div class='large-metric-value' style='color: $scoreColor;'>$($Data.ExecutiveSummary.OverallSecurityScore)%</div>")+ [void]$html.AppendLine(" <div class='large-metric-label'>Security Score</div>")+ [void]$html.AppendLine(" </div>")+ [void]$html.AppendLine(" </div>")++ # Threat Level Card+ [void]$html.AppendLine(" <div class='card'>")+ [void]$html.AppendLine(" <div class='large-metric'>")+ [void]$html.AppendLine(" <div class='large-metric-value' style='color: $threatColor;'>$($Data.ExecutiveSummary.ThreatLevel)</div>")+ [void]$html.AppendLine(" <div class='large-metric-label'>Threat Level</div>")+ [void]$html.AppendLine(" </div>")+ [void]$html.AppendLine(" </div>")++ # Findings Summary Card+ [void]$html.AppendLine(" <div class='card'>")+ [void]$html.AppendLine(" <div class='card-header'>Findings Summary</div>")+ [void]$html.AppendLine(" <div class='metric'><span class='metric-label'>Total</span><span class='metric-value'>$($Data.ExecutiveSummary.TotalFindings)</span></div>")+ [void]$html.AppendLine(" <div class='metric'><span class='metric-label'>Critical</span><span class='metric-value critical'>$($Data.ExecutiveSummary.CriticalFindings)</span></div>")+ [void]$html.AppendLine(" <div class='metric'><span class='metric-label'>High</span><span class='metric-value high'>$($Data.ExecutiveSummary.HighFindings)</span></div>")+ [void]$html.AppendLine(" <div class='metric'><span class='metric-label'>Medium</span><span class='metric-value medium'>$($Data.ExecutiveSummary.MediumFindings)</span></div>")+ [void]$html.AppendLine(" <div class='metric'><span class='metric-label'>Low</span><span class='metric-value low'>$($Data.ExecutiveSummary.LowFindings)</span></div>")+ [void]$html.AppendLine(" </div>")++ # Compliance Score Card+ if ($Data.ExecutiveSummary.ComplianceScore -gt 0) {+ [void]$html.AppendLine(" <div class='card'>")+ [void]$html.AppendLine(" <div class='large-metric'>")+ [void]$html.AppendLine(" <div class='large-metric-value' style='color: #0078d4;'>$($Data.ExecutiveSummary.ComplianceScore)%</div>")+ [void]$html.AppendLine(" <div class='large-metric-label'>Compliance Score</div>")+ [void]$html.AppendLine(" </div>")+ [void]$html.AppendLine(" </div>")+ }++ [void]$html.AppendLine(" </div>")++ # Detection Module Results+ if ($Data.Detection.TotalThreats -ne $null) {+ [void]$html.AppendLine(" <h2>Threat Detection (Total: $($Data.Detection.TotalThreats))</h2>")+ [void]$html.AppendLine(" <div class='grid'>")+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>Persistence Mechanisms</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(@($Data.Detection.PersistenceMechanisms).Count)</span></div></div>")+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>Suspicious Processes</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(@($Data.Detection.SuspiciousProcesses).Count)</span></div></div>")+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>Authentication Anomalies</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(@($Data.Detection.SuspiciousAuthentications).Count)</span></div></div>")+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>APT Indicators</div><div class='metric'><span class='metric-label'>Detected</span><span class='metric-value'>$(@($Data.Detection.APTIndicators).Count)</span></div></div>")+ [void]$html.AppendLine(" </div>")+ }++ # Compliance Module Results+ if ($Data.Compliance.CIS -or $Data.Compliance.NIST -or $Data.Compliance.PCIDSS) {+ [void]$html.AppendLine(" <h2>Compliance Status</h2>")+ [void]$html.AppendLine(" <div class='grid'>")++ if ($Data.Compliance.CIS) {+ $cisScore = if ($Data.Compliance.CIS.ComplianceScore) { $Data.Compliance.CIS.ComplianceScore } else { 0 }+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>CIS Benchmark</div><div class='metric'><span class='metric-label'>Score</span><span class='metric-value'>$cisScore%</span></div></div>")+ }++ if ($Data.Compliance.NIST) {+ $nistScore = if ($Data.Compliance.NIST.ComplianceScore) { $Data.Compliance.NIST.ComplianceScore } else { 0 }+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>NIST CSF</div><div class='metric'><span class='metric-label'>Score</span><span class='metric-value'>$nistScore%</span></div></div>")+ }++ if ($Data.Compliance.PCIDSS) {+ $pciScore = if ($Data.Compliance.PCIDSS.ComplianceScore) { $Data.Compliance.PCIDSS.ComplianceScore } else { 0 }+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>PCI-DSS</div><div class='metric'><span class='metric-label'>Score</span><span class='metric-value'>$pciScore%</span></div></div>")+ }++ [void]$html.AppendLine(" </div>")+ }++ # Active Directory Results+ if ($Data.ActiveDirectory.Enabled) {+ [void]$html.AppendLine(" <h2>Active Directory Security</h2>")+ [void]$html.AppendLine(" <div class='grid'>")+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>Privileged Accounts</div><div class='metric'><span class='metric-label'>Count</span><span class='metric-value'>$(@($Data.ActiveDirectory.PrivilegedAccounts).Count)</span></div></div>")+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>Vulnerabilities</div><div class='metric'><span class='metric-label'>Found</span><span class='metric-value critical'>$(@($Data.ActiveDirectory.Vulnerabilities).Count)</span></div></div>")+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>Backdoors</div><div class='metric'><span class='metric-label'>Found</span><span class='metric-value critical'>$(@($Data.ActiveDirectory.Backdoors).Count)</span></div></div>")+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>Stale Objects</div><div class='metric'><span class='metric-label'>Found</span><span class='metric-value medium'>$(@($Data.ActiveDirectory.StaleObjects).Count)</span></div></div>")+ [void]$html.AppendLine(" </div>")+ }++ # Vulnerability Results+ if ($Data.Vulnerability.TotalVulnerabilities -gt 0 -or @($Data.Vulnerability.EOLSoftware).Count -gt 0) {+ [void]$html.AppendLine(" <h2>Vulnerability Assessment</h2>")+ [void]$html.AppendLine(" <div class='grid'>")+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>Total Vulnerabilities</div><div class='metric'><span class='metric-label'>Count</span><span class='metric-value medium'>$($Data.Vulnerability.TotalVulnerabilities)</span></div></div>")+ [void]$html.AppendLine(" <div class='card'><div class='card-header'>End-of-Life Software</div><div class='metric'><span class='metric-label'>Found</span><span class='metric-value critical'>$(@($Data.Vulnerability.EOLSoftware).Count)</span></div></div>")+ [void]$html.AppendLine(" </div>")+ }++ # Recommendations+ if ($Data.ExecutiveSummary.Recommendations -and @($Data.ExecutiveSummary.Recommendations).Count -gt 0) {+ [void]$html.AppendLine(" <div class='recommendations'>")+ [void]$html.AppendLine(" <h3>Top Recommendations</h3>")+ [void]$html.AppendLine(" <ul>")+ foreach ($rec in $Data.ExecutiveSummary.Recommendations) {+ [void]$html.AppendLine(" <li>$rec</li>")+ }+ [void]$html.AppendLine(" </ul>")+ [void]$html.AppendLine(" </div>")+ }++ # Charts+ if ($IncludeCharts -and $Data.ChartsData.ComplianceScores -and @($Data.ChartsData.ComplianceScores).Count -gt 0) {+ [void]$html.AppendLine(" <h2>Visual Analytics</h2>")+ [void]$html.AppendLine(" <div class='grid'>")+ [void]$html.AppendLine(" <div class='card'>")+ [void]$html.AppendLine(" <div class='card-header'>Compliance Scores</div>")+ [void]$html.AppendLine(" <div class='chart-container'><canvas id='compChart'></canvas></div>")+ [void]$html.AppendLine(" </div>")++ if ($Data.ChartsData.ThreatDistribution -and @($Data.ChartsData.ThreatDistribution).Count -gt 0) {+ [void]$html.AppendLine(" <div class='card'>")+ [void]$html.AppendLine(" <div class='card-header'>Threat Distribution</div>")+ [void]$html.AppendLine(" <div class='chart-container'><canvas id='threatChart'></canvas></div>")+ [void]$html.AppendLine(" </div>")+ }++ [void]$html.AppendLine(" </div>")++ # Chart.js initialization+ $compLabels = ($Data.ChartsData.ComplianceScores | ForEach-Object { "'$($_.Framework)'" }) -join ','+ $compData = ($Data.ChartsData.ComplianceScores | ForEach-Object { $_.Score }) -join ','++ [void]$html.AppendLine(" <script>")+ [void]$html.AppendLine(" const cCtx = document.getElementById('compChart').getContext('2d');")+ [void]$html.AppendLine(" new Chart(cCtx, {")+ [void]$html.AppendLine(" type: 'bar',")+ [void]$html.AppendLine(" data: {")+ [void]$html.AppendLine(" labels: [$compLabels],")+ [void]$html.AppendLine(" datasets: [{")+ [void]$html.AppendLine(" label: 'Compliance Score',")+ [void]$html.AppendLine(" data: [$compData],")+ [void]$html.AppendLine(" backgroundColor: '#0078d4'")+ [void]$html.AppendLine(" }]")+ [void]$html.AppendLine(" },")+ [void]$html.AppendLine(" options: {")+ [void]$html.AppendLine(" responsive: true,")+ [void]$html.AppendLine(" maintainAspectRatio: false,")+ [void]$html.AppendLine(" plugins: { legend: { display: false } },")+ [void]$html.AppendLine(" scales: { y: { beginAtZero: true, max: 100 } }")+ [void]$html.AppendLine(" }")+ [void]$html.AppendLine(" });")++ if ($Data.ChartsData.ThreatDistribution -and @($Data.ChartsData.ThreatDistribution).Count -gt 0) {+ $threatLabels = ($Data.ChartsData.ThreatDistribution | ForEach-Object { "'$($_.Category)'" }) -join ','+ $threatData = ($Data.ChartsData.ThreatDistribution | ForEach-Object { $_.Count }) -join ','++ [void]$html.AppendLine(" const tCtx = document.getElementById('threatChart').getContext('2d');")+ [void]$html.AppendLine(" new Chart(tCtx, {")+ [void]$html.AppendLine(" type: 'doughnut',")+ [void]$html.AppendLine(" data: {")+ [void]$html.AppendLine(" labels: [$threatLabels],")+ [void]$html.AppendLine(" datasets: [{")+ [void]$html.AppendLine(" data: [$threatData],")+ [void]$html.AppendLine(" backgroundColor: ['#d32f2f', '#f57c00', '#fbc02d', '#388e3c', '#1976d2']")+ [void]$html.AppendLine(" }]")+ [void]$html.AppendLine(" },")+ [void]$html.AppendLine(" options: {")+ [void]$html.AppendLine(" responsive: true,")+ [void]$html.AppendLine(" maintainAspectRatio: false,")+ [void]$html.AppendLine(" plugins: { legend: { position: 'bottom' } }")+ [void]$html.AppendLine(" }")+ [void]$html.AppendLine(" });")+ }++ [void]$html.AppendLine(" </script>")+ }++ # Footer+ [void]$html.AppendLine(" <div class='footer'>")+ [void]$html.AppendLine(" <p><strong>WindowsSecurityAudit Module v3.0 ULTIMATE EDITION</strong></p>")+ [void]$html.AppendLine(" <p>Generated: $($Data.GeneratedDate) | Execution Time: $([Math]::Round($Data.Performance.TotalExecutionTime, 1))s | Functions: $($Data.TotalFunctionsUsed)/54</p>")+ [void]$html.AppendLine(" <p>Complete Enterprise Security Assessment Platform - ALL 54 Functions Integrated</p>")+ [void]$html.AppendLine(" </div>")++ [void]$html.AppendLine(" </div>")+ [void]$html.AppendLine("</body>")+ [void]$html.AppendLine("</html>")++ # Save HTML to file+ $html.ToString() | Out-File -FilePath $outputPath -Encoding UTF8 -Force++ return $outputPath+}\ No newline at end of filediff --git a/Response/Export-SecurityReport.ps1 b/Response/Export-SecurityReport.ps1new file mode 100644index 0000000..8cddef5--- /dev/null+++ b/Response/Export-SecurityReport.ps1@@ -0,0 +1,334 @@+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+ .PARAMETER ReportType+ Type of report: Executive, Technical, or Compliance+ .PARAMETER Format+ Output format: HTML, JSON, CSV, or All+ .PARAMETER OutputPath+ Path to save the report+ .PARAMETER IncludeCharts+ Include visual charts and graphs in HTML reports+ .EXAMPLE+ Export-SecurityReport -ReportType Technical -Format HTML -OutputPath "C:\Reports"+ Export-SecurityReport -ReportType Executive -Format All -IncludeCharts+ .OUTPUTS+ String path to generated report+ #>++ [CmdletBinding()]+ param(+ [Parameter(Mandatory = $true)]+ [ValidateSet('Executive', 'Technical', 'Compliance')]+ [string]$ReportType,++ [Parameter()]+ [ValidateSet('HTML', 'JSON', 'CSV', 'All')]+ [string]$Format = 'HTML',++ [Parameter()]+ [string]$OutputPath = "C:\SecurityReports",++ [Parameter()]+ [switch]$IncludeCharts+ )++ begin {+ Write-Host "Generating $ReportType Security Report..." -ForegroundColor Cyan++ if (-not (Test-Path $OutputPath)) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ }++ $timestamp = Get-Date -Format 'yyyyMMdd_HHmmss'+ $reportBaseName = "SecurityReport_${ReportType}_$timestamp"+ }++ process {+ try {+ Write-Host "Collecting security data..." -ForegroundColor Yellow++ # Collect all security data+ $baseline = Get-SecurityBaseline+ $systemInfo = Get-SystemInfo+ $persistence = Find-PersistenceMechanisms+ $processes = Find-SuspiciousProcesses+ $network = Find-NetworkAnomalies -IncludeEstablished+ $auth = Find-SuspiciousAuthentication -Hours 168+ $eventLog = Get-EventLogAnalysis -Hours 168+ $registry = Get-RegistryAnalysis -IncludeAutoRun++ # Build report data structure+ $reportData = [PSCustomObject]@{+ ReportType = $ReportType+ GeneratedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ GeneratedBy = $env:USERNAME+ SecurityScore = $baseline.SecurityScore+ Summary = @{+ CriticalFindings = 0+ HighFindings = 0+ MediumFindings = 0+ LowFindings = 0+ }+ Findings = @()+ Recommendations = @()+ Details = @{+ Baseline = $baseline+ SystemInfo = $systemInfo+ Persistence = $persistence+ Processes = $processes+ Network = $network+ Authentication = $auth+ EventLog = $eventLog+ Registry = $registry+ }+ }++ # Analyze findings and create recommendations+ Write-Host "Analyzing findings..." -ForegroundColor Yellow++ # Critical findings+ if ($baseline.SecurityScore -lt 50) {+ $reportData.Summary.CriticalFindings+++ $reportData.Findings += [PSCustomObject]@{+ Severity = 'Critical'+ Category = 'Security Baseline'+ Finding = "Security score is critically low: $($baseline.SecurityScore)/100"+ Impact = 'System is highly vulnerable to attacks'+ Recommendation = 'Immediate remediation required'+ }+ }++ if ($persistence.SuspiciousCount -gt 5) {+ $reportData.Summary.HighFindings+++ $reportData.Findings += [PSCustomObject]@{+ Severity = 'High'+ Category = 'Persistence'+ Finding = "$($persistence.SuspiciousCount) suspicious persistence mechanisms detected"+ Impact = 'Potential malware or unauthorized software present'+ Recommendation = 'Review and remove unauthorized persistence mechanisms'+ }+ }++ if ($processes.Count -gt 0) {+ $processArray = @($processes)+$highSeverityProcs = @($processArray | Where-Object { $_.SuspicionScore -ge 70 })+if ($highSeverityProcs.Count -gt 0) {+ $reportData.Summary.HighFindings+++ $reportData.Findings += [PSCustomObject]@{+ Severity = 'High'+ Category = 'Processes'+ Finding = "$($highSeverityProcs.Count) highly suspicious processes running"+ Impact = 'Potential active threat on system'+ Recommendation = 'Investigate and terminate malicious processes'+ }+}+ }++ if ($auth.Statistics.TotalLockouts -gt 0) {+ $reportData.Summary.MediumFindings+++ $reportData.Findings += [PSCustomObject]@{+ Severity = 'Medium'+ Category = 'Authentication'+ Finding = "$($auth.Statistics.TotalLockouts) account lockouts detected"+ Impact = 'Possible brute force attempts'+ Recommendation = 'Review failed authentication events and implement MFA'+ }+ }++ if ($network.TotalAnomalies -gt 10) {+ $reportData.Summary.MediumFindings+++ $reportData.Findings += [PSCustomObject]@{+ Severity = 'Medium'+ Category = 'Network'+ Finding = "$($network.TotalAnomalies) network anomalies detected"+ Impact = 'Unusual network activity may indicate compromise'+ Recommendation = 'Review network connections and implement network monitoring'+ }+ }++ # Generate recommendations based on report type+ if ($ReportType -eq 'Executive') {+ $reportData.Recommendations = @(+ "Overall Security Score: $($baseline.SecurityScore)/100 - $(if ($baseline.SecurityScore -ge 80) { 'Good' } elseif ($baseline.SecurityScore -ge 60) { 'Fair' } else { 'Poor' })",+ "Critical Issues: $($reportData.Summary.CriticalFindings)",+ "High Priority Issues: $($reportData.Summary.HighFindings)",+ "Immediate action required on critical and high priority items",+ "Regular security assessments recommended"+ )+ }+ elseif ($ReportType -eq 'Technical') {+ $reportData.Recommendations = @(+ "Enable PowerShell logging and monitoring",+ "Implement application whitelisting",+ "Review and harden security baselines",+ "Enable Windows Defender real-time protection",+ "Implement network segmentation",+ "Deploy EDR solution for advanced threat detection",+ "Regular vulnerability assessments",+ "Incident response plan testing"+ )+ }+ else { # Compliance+ $reportData.Recommendations = @(+ "Document all security controls",+ "Implement continuous compliance monitoring",+ "Regular audit log reviews",+ "Access control reviews",+ "Patch management process",+ "Security awareness training",+ "Incident response procedures",+ "Business continuity planning"+ )+ }++ # Generate reports in requested formats+ $generatedFiles = @()++ if ($Format -in @('JSON', 'All')) {+ Write-Host "Generating JSON report..." -ForegroundColor Yellow+ $jsonPath = Join-Path $OutputPath "$reportBaseName.json"+ $reportData | ConvertTo-Json -Depth 10 | Out-File $jsonPath -Encoding UTF8+ $generatedFiles += $jsonPath+ }++ if ($Format -in @('CSV', 'All')) {+ Write-Host "Generating CSV reports..." -ForegroundColor Yellow+ $csvPath = Join-Path $OutputPath "${reportBaseName}_Findings.csv"+ $reportData.Findings | Export-Csv $csvPath -NoTypeInformation+ $generatedFiles += $csvPath+ }++ if ($Format -in @('HTML', 'All')) {+ Write-Host "Generating HTML report..." -ForegroundColor Yellow++ # Create HTML report+ $htmlContent = @"+<!DOCTYPE html>+<html>+<head>+ <title>$ReportType Security Report - $($reportData.ComputerName)</title>+ <style>+ body { font-family: Arial, sans-serif; margin: 20px; background-color: #f5f5f5; }+ .header { background-color: #2c3e50; color: white; padding: 20px; border-radius: 5px; }+ .summary { background-color: white; padding: 20px; margin: 20px 0; border-radius: 5px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }+ .score { font-size: 48px; font-weight: bold; color: #3498db; }+ .finding { background-color: white; padding: 15px; margin: 10px 0; border-radius: 5px; border-left: 4px solid; }+ .critical { border-left-color: #e74c3c; }+ .high { border-left-color: #e67e22; }+ .medium { border-left-color: #f39c12; }+ .low { border-left-color: #95a5a6; }+ table { width: 100%; border-collapse: collapse; background-color: white; }+ th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }+ th { background-color: #34495e; color: white; }+ .recommendation { background-color: #ecf0f1; padding: 10px; margin: 5px 0; border-radius: 3px; }+ </style>+</head>+<body>+ <div class="header">+ <h1>$ReportType Security Assessment Report</h1>+ <p>Computer: $($reportData.ComputerName)</p>+ <p>Generated: $($reportData.GeneratedDate)</p>+ <p>Generated By: $($reportData.GeneratedBy)</p>+ </div>++ <div class="summary">+ <h2>Executive Summary</h2>+ <div class="score">Security Score: $($reportData.SecurityScore)/100</div>+ <table>+ <tr>+ <th>Severity</th>+ <th>Count</th>+ </tr>+ <tr>+ <td>Critical</td>+ <td style="color: #e74c3c; font-weight: bold;">$($reportData.Summary.CriticalFindings)</td>+ </tr>+ <tr>+ <td>High</td>+ <td style="color: #e67e22; font-weight: bold;">$($reportData.Summary.HighFindings)</td>+ </tr>+ <tr>+ <td>Medium</td>+ <td style="color: #f39c12; font-weight: bold;">$($reportData.Summary.MediumFindings)</td>+ </tr>+ <tr>+ <td>Low</td>+ <td style="color: #95a5a6;">$($reportData.Summary.LowFindings)</td>+ </tr>+ </table>+ </div>++ <div class="summary">+ <h2>Key Findings</h2>+ $($reportData.Findings | ForEach-Object {+ $class = $_.Severity.ToLower()+ "<div class='finding $class'>+ <h3>[$($_.Severity)] $($_.Category)</h3>+ <p><strong>Finding:</strong> $($_.Finding)</p>+ <p><strong>Impact:</strong> $($_.Impact)</p>+ <p><strong>Recommendation:</strong> $($_.Recommendation)</p>+ </div>"+ } | Out-String)+ </div>++ <div class="summary">+ <h2>Recommendations</h2>+ $($reportData.Recommendations | ForEach-Object {+ "<div class='recommendation'>$_</div>"+ } | Out-String)+ </div>++ <div class="summary">+ <h2>System Details</h2>+ <table>+ <tr><th>Component</th><th>Status</th></tr>+ <tr><td>Windows Defender</td><td>$($baseline.WindowsDefender.RealTimeProtectionEnabled)</td></tr>+ <tr><td>Firewall</td><td>$($baseline.Firewall[0].Enabled)</td></tr>+ <tr><td>UAC</td><td>$($baseline.UAC.EnableLUA -eq 1)</td></tr>+ <tr><td>Persistence Mechanisms</td><td>$($persistence.TotalFindings) total ($($persistence.SuspiciousCount) suspicious)</td></tr>+ <tr><td>Network Anomalies</td><td>$($network.TotalAnomalies)</td></tr>+ <tr><td>Failed Logons</td><td>$($auth.Statistics.TotalFailedLogons)</td></tr>+ </table>+ </div>++ <div class="summary">+ <p><em>This report was generated by WindowsSecurityAudit PowerShell Module</em></p>+ </div>+</body>+</html>+"@++ $htmlPath = Join-Path $OutputPath "$reportBaseName.html"+ $htmlContent | Out-File $htmlPath -Encoding UTF8+ $generatedFiles += $htmlPath+ }++ }+ catch {+ Write-Error "Error generating report: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== REPORT GENERATION COMPLETE ===" -ForegroundColor Green+ Write-Host "Generated Files:" -ForegroundColor Cyan+ foreach ($file in $generatedFiles) {+ Write-Host " - $file" -ForegroundColor White+ }++ # Open HTML report if generated+ if ($generatedFiles -match '\.html$') {+ $htmlFile = $generatedFiles | Where-Object { $_ -match '\.html$' } | Select-Object -First 1+ Start-Process $htmlFile+ }++ return $generatedFiles+ }+}\ No newline at end of filediff --git a/Response/Invoke-ForensicCollection.ps1 b/Response/Invoke-ForensicCollection.ps1new file mode 100644index 0000000..273b7a9--- /dev/null+++ b/Response/Invoke-ForensicCollection.ps1@@ -0,0 +1,500 @@+function Invoke-ForensicCollection {+ <#+ .SYNOPSIS+ Collects comprehensive forensic evidence from the system+ .DESCRIPTION+ Performs detailed forensic data collection including memory dumps, disk artifacts,+ registry hives, event logs, and system state information+ .PARAMETER CollectionType+ Type of collection: Quick, Standard, or Comprehensive+ .PARAMETER OutputPath+ Path to save collected evidence+ .PARAMETER IncludeMemoryDump+ Include memory dump (requires large disk space)+ .PARAMETER IncludeDiskArtifacts+ Collect disk-based artifacts (MFT, prefetch, etc.)+ .EXAMPLE+ Invoke-ForensicCollection -CollectionType Standard -OutputPath "C:\Forensics"+ Invoke-ForensicCollection -CollectionType Comprehensive -IncludeMemoryDump -OutputPath "D:\Evidence"+ .OUTPUTS+ PSCustomObject with collection results+ #>++ [CmdletBinding()]+ param(+ [Parameter(Mandatory = $true)]+ [ValidateSet('Quick', 'Standard', 'Comprehensive')]+ [string]$CollectionType,++ [Parameter(Mandatory = $true)]+ [string]$OutputPath,++ [Parameter()]+ [switch]$IncludeMemoryDump,++ [Parameter()]+ [switch]$IncludeDiskArtifacts+ )++ begin {+ Write-Host "=== FORENSIC EVIDENCE COLLECTION ===" -ForegroundColor Cyan+ Write-Host "Collection Type: $CollectionType" -ForegroundColor Yellow+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ # Check for admin privileges+ $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ if (-not $isAdmin) {+ throw "Forensic collection requires Administrator privileges!"+ }++ # Create output directory with timestamp+ $timestamp = Get-Date -Format 'yyyyMMdd_HHmmss'+ $collectionPath = Join-Path $OutputPath "ForensicCollection_$timestamp"+ New-Item -Path $collectionPath -ItemType Directory -Force | Out-Null++ # Create subdirectories+ $directories = @(+ 'SystemInfo',+ 'EventLogs',+ 'Registry',+ 'Network',+ 'Processes',+ 'FileSystem',+ 'Memory',+ 'Timeline'+ )++ foreach ($dir in $directories) {+ New-Item -Path (Join-Path $collectionPath $dir) -ItemType Directory -Force | Out-Null+ }++ $results = [PSCustomObject]@{+ CollectionDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ CollectionType = $CollectionType+ ComputerName = $env:COMPUTERNAME+ OutputPath = $collectionPath+ ArtifactsCollected = @()+ Errors = @()+ TotalSize = 0+ Status = 'In Progress'+ }++ $logFile = Join-Path $collectionPath "Collection.log"++ function Write-CollectionLog {+ param([string]$Message, [string]$Level = 'INFO')+ $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ $logMessage = "[$timestamp] [$Level] $Message"+ Add-Content -Path $logFile -Value $logMessage+ Write-Verbose $Message+ }++ Write-CollectionLog "Forensic collection initiated - Type: $CollectionType"+ }++ process {+ try {+ # Collection 1: System Information (All types)+ Write-Host "`n[1/10] Collecting system information..." -ForegroundColor Cyan+ try {+ $sysInfoPath = Join-Path $collectionPath 'SystemInfo'++ # Basic system info+ $sysInfo = Get-SystemInfo -IncludeInstalledSoftware -IncludeHotfixes+ $sysInfo | ConvertTo-Json -Depth 5 | Out-File (Join-Path $sysInfoPath "SystemInfo.json")++ # Computer information+ Get-ComputerInfo | ConvertTo-Json -Depth 5 | Out-File (Join-Path $sysInfoPath "ComputerInfo.json")++ # Environment variables+ Get-ChildItem Env: | Export-Csv (Join-Path $sysInfoPath "EnvironmentVariables.csv") -NoTypeInformation++ # Local users and groups+ Get-LocalUser | Export-Csv (Join-Path $sysInfoPath "LocalUsers.csv") -NoTypeInformation+ Get-LocalGroup | Export-Csv (Join-Path $sysInfoPath "LocalGroups.csv") -NoTypeInformation++ $results.ArtifactsCollected += "System Information"+ Write-CollectionLog "Collected system information"+ }+ catch {+ $results.Errors += "System Info: $_"+ Write-CollectionLog "Error collecting system info: $_" 'ERROR'+ }++ # Collection 2: Running Processes (All types)+ Write-Host "[2/10] Collecting process information..." -ForegroundColor Cyan+ try {+ $procPath = Join-Path $collectionPath 'Processes'++ # Process list with details+ Get-Process | Select-Object Name, Id, Path, CommandLine, StartTime, CPU, WorkingSet64, Threads |+ Export-Csv (Join-Path $procPath "Processes.csv") -NoTypeInformation++ # Process modules+ $procModules = Get-Process | ForEach-Object {+ try {+ $_.Modules | Select-Object @{N='ProcessName';E={$_.ProcessName}},+ @{N='ProcessId';E={$_.Id}},+ ModuleName, FileName, Size+ } catch {}+ }+ $procModules | Export-Csv (Join-Path $procPath "ProcessModules.csv") -NoTypeInformation++ # Services+ Get-Service | Export-Csv (Join-Path $procPath "Services.csv") -NoTypeInformation+ Get-CimInstance Win32_Service | Select-Object Name, DisplayName, PathName, StartMode, State, StartName |+ Export-Csv (Join-Path $procPath "ServicesDetailed.csv") -NoTypeInformation++ # Scheduled tasks+ Get-ScheduledTask | Export-Csv (Join-Path $procPath "ScheduledTasks.csv") -NoTypeInformation++ $results.ArtifactsCollected += "Process Information"+ Write-CollectionLog "Collected process information"+ }+ catch {+ $results.Errors += "Processes: $_"+ Write-CollectionLog "Error collecting processes: $_" 'ERROR'+ }++ # Collection 3: Network Information (All types)+ Write-Host "[3/10] Collecting network information..." -ForegroundColor Cyan+ try {+ $netPath = Join-Path $collectionPath 'Network'++ # Network adapters+ Get-NetAdapter | Export-Csv (Join-Path $netPath "NetworkAdapters.csv") -NoTypeInformation+ Get-NetIPAddress | Export-Csv (Join-Path $netPath "IPAddresses.csv") -NoTypeInformation+ Get-NetRoute | Export-Csv (Join-Path $netPath "Routes.csv") -NoTypeInformation++ # Active connections+ Get-NetTCPConnection | Export-Csv (Join-Path $netPath "TCPConnections.csv") -NoTypeInformation+ Get-NetUDPEndpoint | Export-Csv (Join-Path $netPath "UDPEndpoints.csv") -NoTypeInformation++ # DNS cache+ Get-DnsClientCache | Export-Csv (Join-Path $netPath "DNSCache.csv") -NoTypeInformation++ # Firewall rules+ Get-NetFirewallRule | Export-Csv (Join-Path $netPath "FirewallRules.csv") -NoTypeInformation+ Get-NetFirewallProfile | Export-Csv (Join-Path $netPath "FirewallProfiles.csv") -NoTypeInformation++ # ARP cache+ Get-NetNeighbor | Export-Csv (Join-Path $netPath "ARPCache.csv") -NoTypeInformation++ # Network shares+ Get-SmbShare | Export-Csv (Join-Path $netPath "Shares.csv") -NoTypeInformation+ Get-SmbSession | Export-Csv (Join-Path $netPath "SMBSessions.csv") -NoTypeInformation++ $results.ArtifactsCollected += "Network Information"+ Write-CollectionLog "Collected network information"+ }+ catch {+ $results.Errors += "Network: $_"+ Write-CollectionLog "Error collecting network info: $_" 'ERROR'+ }++ # Collection 4: Event Logs (Standard and Comprehensive)+ if ($CollectionType -in @('Standard', 'Comprehensive')) {+ Write-Host "[4/10] Collecting event logs..." -ForegroundColor Cyan+ try {+ $eventPath = Join-Path $collectionPath 'EventLogs'++ # Security events (last 7 days)+ Get-WinEvent -FilterHashtable @{LogName='Security'; StartTime=(Get-Date).AddDays(-7)} -MaxEvents 10000 -ErrorAction SilentlyContinue |+ Select-Object TimeCreated, Id, LevelDisplayName, Message |+ Export-Csv (Join-Path $eventPath "Security_Recent.csv") -NoTypeInformation++ # System events (last 7 days)+ Get-WinEvent -FilterHashtable @{LogName='System'; StartTime=(Get-Date).AddDays(-7)} -MaxEvents 10000 -ErrorAction SilentlyContinue |+ Select-Object TimeCreated, Id, LevelDisplayName, Message |+ Export-Csv (Join-Path $eventPath "System_Recent.csv") -NoTypeInformation++ # Application events (last 7 days)+ Get-WinEvent -FilterHashtable @{LogName='Application'; StartTime=(Get-Date).AddDays(-7)} -MaxEvents 10000 -ErrorAction SilentlyContinue |+ Select-Object TimeCreated, Id, LevelDisplayName, Message |+ Export-Csv (Join-Path $eventPath "Application_Recent.csv") -NoTypeInformation++ # PowerShell logs+ Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-PowerShell/Operational'; StartTime=(Get-Date).AddDays(-7)} -MaxEvents 5000 -ErrorAction SilentlyContinue |+ Select-Object TimeCreated, Id, Message |+ Export-Csv (Join-Path $eventPath "PowerShell_Recent.csv") -NoTypeInformation++ $results.ArtifactsCollected += "Event Logs"+ Write-CollectionLog "Collected event logs"+ }+ catch {+ $results.Errors += "Event Logs: $_"+ Write-CollectionLog "Error collecting event logs: $_" 'ERROR'+ }+ }+ else {+ Write-Host "[4/10] Event logs: SKIPPED (Quick mode)" -ForegroundColor Yellow+ }++ # Collection 5: Registry Artifacts (Standard and Comprehensive)+ if ($CollectionType -in @('Standard', 'Comprehensive')) {+ Write-Host "[5/10] Collecting registry artifacts..." -ForegroundColor Cyan+ try {+ $regPath = Join-Path $collectionPath 'Registry'++ # Run keys+ $runKeys = @(+ 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Run',+ 'HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce',+ 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run',+ 'HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce'+ )++ $runEntries = foreach ($key in $runKeys) {+ if (Test-Path $key) {+ Get-ItemProperty -Path $key | Select-Object PSPath, PSChildName, *+ }+ }+ $runEntries | Export-Csv (Join-Path $regPath "RunKeys.csv") -NoTypeInformation++ # Installed software+ $software = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* |+ Where-Object { $_.DisplayName } |+ Select-Object DisplayName, Publisher, InstallDate, DisplayVersion+ $software | Export-Csv (Join-Path $regPath "InstalledSoftware.csv") -NoTypeInformation++ # USB history+ $usb = Get-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Enum\USBSTOR\* -ErrorAction SilentlyContinue |+ Select-Object PSChildName, FriendlyName+ $usb | Export-Csv (Join-Path $regPath "USBHistory.csv") -NoTypeInformation++ $results.ArtifactsCollected += "Registry Artifacts"+ Write-CollectionLog "Collected registry artifacts"+ }+ catch {+ $results.Errors += "Registry: $_"+ Write-CollectionLog "Error collecting registry: $_" 'ERROR'+ }+ }+ else {+ Write-Host "[5/10] Registry artifacts: SKIPPED (Quick mode)" -ForegroundColor Yellow+ }++ # Collection 6: File System Artifacts (Comprehensive only)+ if ($CollectionType -eq 'Comprehensive' -or $IncludeDiskArtifacts) {+ Write-Host "[6/10] Collecting file system artifacts..." -ForegroundColor Cyan+ try {+ $fsPath = Join-Path $collectionPath 'FileSystem'++ # Recent files in temp directories+ $tempPaths = @("$env:TEMP", "$env:SystemRoot\Temp", "$env:LOCALAPPDATA\Temp")+ $recentFiles = foreach ($temp in $tempPaths) {+ if (Test-Path $temp) {+ Get-ChildItem -Path $temp -File -Recurse -ErrorAction SilentlyContinue |+ Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-7) } |+ Select-Object FullName, Name, Length, CreationTime, LastWriteTime+ }+ }+ $recentFiles | Export-Csv (Join-Path $fsPath "RecentTempFiles.csv") -NoTypeInformation++ # Prefetch files+ if (Test-Path "$env:SystemRoot\Prefetch") {+ Get-ChildItem "$env:SystemRoot\Prefetch" -Filter *.pf |+ Select-Object Name, Length, CreationTime, LastWriteTime, LastAccessTime |+ Export-Csv (Join-Path $fsPath "Prefetch.csv") -NoTypeInformation+ }++ # Recent downloads+ $downloadsPath = "$env:USERPROFILE\Downloads"+ if (Test-Path $downloadsPath) {+ Get-ChildItem $downloadsPath -File -Recurse -ErrorAction SilentlyContinue |+ Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-30) } |+ Select-Object FullName, Name, Length, CreationTime, LastWriteTime |+ Export-Csv (Join-Path $fsPath "RecentDownloads.csv") -NoTypeInformation+ }++ $results.ArtifactsCollected += "File System Artifacts"+ Write-CollectionLog "Collected file system artifacts"+ }+ catch {+ $results.Errors += "File System: $_"+ Write-CollectionLog "Error collecting file system: $_" 'ERROR'+ }+ }+ else {+ Write-Host "[6/10] File system artifacts: SKIPPED" -ForegroundColor Yellow+ }++ # Collection 7: Security Analysis (Standard and Comprehensive)+ if ($CollectionType -in @('Standard', 'Comprehensive')) {+ Write-Host "[7/10] Running security analysis..." -ForegroundColor Cyan+ try {+ $secPath = Join-Path $collectionPath 'SecurityAnalysis'+ New-Item -Path $secPath -ItemType Directory -Force | Out-Null++ # Persistence mechanisms+ $persistence = Find-PersistenceMechanisms+ $persistence | ConvertTo-Json -Depth 5 | Out-File (Join-Path $secPath "Persistence.json")++ # Network anomalies+ $network = Find-NetworkAnomalies -IncludeEstablished+ $network | ConvertTo-Json -Depth 5 | Out-File (Join-Path $secPath "NetworkAnomalies.json")++ # Authentication analysis+ $auth = Find-SuspiciousAuthentication -Hours 168+ $auth | ConvertTo-Json -Depth 5 | Out-File (Join-Path $secPath "Authentication.json")++ $results.ArtifactsCollected += "Security Analysis"+ Write-CollectionLog "Completed security analysis"+ }+ catch {+ $results.Errors += "Security Analysis: $_"+ Write-CollectionLog "Error in security analysis: $_" 'ERROR'+ }+ }+ else {+ Write-Host "[7/10] Security analysis: SKIPPED (Quick mode)" -ForegroundColor Yellow+ }++ # Collection 8: Memory Dump (if requested)+ if ($IncludeMemoryDump) {+ Write-Host "[8/10] Creating memory dump..." -ForegroundColor Cyan+ Write-Warning "Memory dump requires significant disk space and time"+ try {+ $memPath = Join-Path $collectionPath 'Memory'+ Write-CollectionLog "Memory dump requested but requires external tools (e.g., WinPMEM, DumpIt)" 'WARNING'++ # Note: Full memory dump requires external tools+ $note = @"+Memory dump collection requires external tools such as:+- WinPMEM (Rekall)+- DumpIt (Comae)+- Magnet RAM Capture+- FTK Imager++Please use appropriate forensic tools for memory acquisition.+"@+ $note | Out-File (Join-Path $memPath "MemoryDump_Instructions.txt")++ $results.ArtifactsCollected += "Memory Dump Instructions"+ }+ catch {+ $results.Errors += "Memory: $_"+ Write-CollectionLog "Memory dump: $_" 'ERROR'+ }+ }+ else {+ Write-Host "[8/10] Memory dump: SKIPPED" -ForegroundColor Yellow+ }++ # Collection 9: Timeline Generation+ Write-Host "[9/10] Generating timeline..." -ForegroundColor Cyan+ try {+ $timelinePath = Join-Path $collectionPath 'Timeline'++ $timeline = @()++ # Process start times+ Get-Process | Where-Object { $_.StartTime } | ForEach-Object {+ $timeline += [PSCustomObject]@{+ Timestamp = $_.StartTime+ Type = 'ProcessStart'+ Description = "$($_.ProcessName) (PID: $($_.Id))"+ Details = $_.Path+ }+ }++ # Recent file modifications++ # Recent file modifications+if ($null -ne (Get-Variable -Name 'recentFiles' -ErrorAction SilentlyContinue) -and $recentFiles) {+ $recentFiles | Where-Object { $_ } | ForEach-Object {+ $timeline += [PSCustomObject]@{+ Timestamp = $_.LastWriteTime+ Type = 'FileModified'+ Description = $_.Name+ Details = $_.FullName+ }+ }+}+++ $timeline | Sort-Object Timestamp -Descending |+ Export-Csv (Join-Path $timelinePath "Timeline.csv") -NoTypeInformation++ $results.ArtifactsCollected += "Timeline"+ Write-CollectionLog "Generated timeline"+ }+ catch {+ $results.Errors += "Timeline: $_"+ Write-CollectionLog "Error generating timeline: $_" 'ERROR'+ }++ # Collection 10: Collection Summary+ Write-Host "[10/10] Finalizing collection..." -ForegroundColor Cyan++ # Calculate total size+ $totalSize = (Get-ChildItem $collectionPath -Recurse -File | Measure-Object -Property Length -Sum).Sum+ $results.TotalSize = [math]::Round($totalSize / 1MB, 2)+ $results.Status = 'Completed'++ # Create hash manifest for integrity+ $hashManifest = Get-ChildItem $collectionPath -Recurse -File | ForEach-Object {+ [PSCustomObject]@{+ Path = $_.FullName.Replace($collectionPath, '')+ SHA256 = (Get-FileHash $_.FullName -Algorithm SHA256).Hash+ Size = $_.Length+ }+ }+ $hashManifest | Export-Csv (Join-Path $collectionPath "HashManifest.csv") -NoTypeInformation++ Write-CollectionLog "Collection completed successfully"++ }+ catch {+ $results.Status = 'Failed'+ $results.Errors += "Fatal: $_"+ Write-CollectionLog "Collection failed: $_" 'ERROR'+ throw+ }+ }++ end {+ # Generate collection report+ $report = @"+=== FORENSIC COLLECTION REPORT ===+Collection Date: $($results.CollectionDate)+Collection Type: $($results.CollectionType)+Computer Name: $($results.ComputerName)+Status: $($results.Status)++ARTIFACTS COLLECTED:+$($results.ArtifactsCollected | ForEach-Object { " - $_" } | Out-String)++TOTAL SIZE: $($results.TotalSize) MB++ERRORS: $($results.Errors.Count)+$($results.Errors | ForEach-Object { " - $_" } | Out-String)++OUTPUT PATH: $($results.OutputPath)++CHAIN OF CUSTODY:+- Collected by: $env:USERNAME+- Computer: $env:COMPUTERNAME+- Date/Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')+- Hash manifest created for integrity verification++NEXT STEPS:+1. Review HashManifest.csv for file integrity+2. Preserve evidence using write-blocker if needed+3. Create forensic image of collected data+4. Document chain of custody+5. Begin analysis using appropriate forensic tools+"@++ $report | Out-File (Join-Path $collectionPath "CollectionReport.txt")++ Write-Host "`n=== FORENSIC COLLECTION COMPLETE ===" -ForegroundColor Green+ Write-Host "Status: $($results.Status)" -ForegroundColor $(if ($results.Status -eq 'Completed') { 'Green' } else { 'Red' })+ Write-Host "Total Size: $($results.TotalSize) MB" -ForegroundColor Cyan+ Write-Host "Artifacts: $($results.ArtifactsCollected.Count)" -ForegroundColor Cyan+ Write-Host "Errors: $($results.Errors.Count)" -ForegroundColor $(if ($results.Errors.Count -eq 0) { 'Green' } else { 'Yellow' })+ Write-Host "Output: $($results.OutputPath)" -ForegroundColor Cyan++ return $results+ }+}\ No newline at end of filediff --git a/Response/Invoke-IncidentResponse.ps1 b/Response/Invoke-IncidentResponse.ps1new file mode 100644index 0000000..668a451--- /dev/null+++ b/Response/Invoke-IncidentResponse.ps1@@ -0,0 +1,328 @@+function Invoke-IncidentResponse {+ <#+ .SYNOPSIS+ Executes comprehensive incident response procedures+ .DESCRIPTION+ Performs automated incident response including threat containment, evidence collection,+ system isolation, and remediation actions+ .PARAMETER Severity+ Incident severity level: Low, Medium, High, Critical+ .PARAMETER IsolateSystem+ Isolate system from network (disconnect network adapters)+ .PARAMETER KillSuspiciousProcesses+ Terminate suspicious processes+ .PARAMETER CollectEvidence+ Collect forensic evidence+ .PARAMETER OutputPath+ Path to save incident response outputs+ .EXAMPLE+ Invoke-IncidentResponse -Severity High -CollectEvidence -OutputPath "C:\IR"+ Invoke-IncidentResponse -Severity Critical -IsolateSystem -KillSuspiciousProcesses -CollectEvidence+ .OUTPUTS+ PSCustomObject with incident response actions and results+ #>++ [CmdletBinding(SupportsShouldProcess)]+ param(+ [Parameter(Mandatory = $true)]+ [ValidateSet('Low', 'Medium', 'High', 'Critical')]+ [string]$Severity,++ [Parameter()]+ [switch]$IsolateSystem,++ [Parameter()]+ [switch]$KillSuspiciousProcesses,++ [Parameter()]+ [switch]$CollectEvidence,++ [Parameter()]+ [string]$OutputPath = "C:\IncidentResponse_$(Get-Date -Format 'yyyyMMdd_HHmmss')"+ )++ begin {+ Write-Host "=== INCIDENT RESPONSE INITIATED ===" -ForegroundColor Red -BackgroundColor Yellow+ Write-Host "Severity Level: $Severity" -ForegroundColor Red+ Write-Host "Timestamp: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ # Check for admin privileges+ $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ if (-not $isAdmin) {+ throw "Incident Response requires Administrator privileges!"+ }++ # Create output directory+ if (-not (Test-Path $OutputPath)) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ }++ $results = [PSCustomObject]@{+ IncidentDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ Severity = $Severity+ ComputerName = $env:COMPUTERNAME+ Actions = @()+ ProcessesTerminated = @()+ NetworkIsolation = $false+ EvidenceCollected = @()+ Findings = @()+ Status = 'In Progress'+ }++ # Log file+ $logFile = Join-Path $OutputPath "IncidentResponse.log"++ function Write-IRLog {+ param([string]$Message, [string]$Level = 'INFO')+ $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ $logMessage = "[$timestamp] [$Level] $Message"+ Add-Content -Path $logFile -Value $logMessage++ switch ($Level) {+ 'ERROR' { Write-Host $Message -ForegroundColor Red }+ 'WARNING' { Write-Host $Message -ForegroundColor Yellow }+ 'SUCCESS' { Write-Host $Message -ForegroundColor Green }+ default { Write-Host $Message -ForegroundColor White }+ }+ }++ Write-IRLog "Incident Response initiated - Severity: $Severity" 'INFO'+ }++ process {+ try {+ # Step 1: Quick Security Assessment+ Write-Host "`n[1/6] Running quick security assessment..." -ForegroundColor Cyan+ Write-IRLog "Running security assessment" 'INFO'++ try {+ $baseline = Get-SecurityBaseline+ $results.Findings += "Security Score: $($baseline.SecurityScore)/100"+ Write-IRLog "Security baseline: $($baseline.SecurityScore)/100" 'INFO'+ }+ catch {+ Write-IRLog "Could not complete security baseline: $_" 'WARNING'+ }++ # Step 2: Detect Active Threats+ Write-Host "`n[2/6] Detecting active threats..." -ForegroundColor Cyan+ Write-IRLog "Scanning for threats" 'INFO'++ $threats = @()++ # Scan for suspicious processes+ try {+ $suspiciousProcs = Find-SuspiciousProcesses -CheckSignatures+ if ($suspiciousProcs) {+ $threats += $suspiciousProcs+ $results.Findings += "$($suspiciousProcs.Count) suspicious processes detected"+ Write-IRLog "$($suspiciousProcs.Count) suspicious processes found" 'WARNING'+ }+ }+ catch {+ Write-IRLog "Error scanning processes: $_" 'ERROR'+ }++ # Scan for persistence mechanisms+ try {+ $persistence = Find-PersistenceMechanisms+ if ($persistence.SuspiciousCount -gt 0) {+ $results.Findings += "$($persistence.SuspiciousCount) persistence mechanisms detected"+ Write-IRLog "$($persistence.SuspiciousCount) persistence mechanisms found" 'WARNING'+ }+ }+ catch {+ Write-IRLog "Error scanning persistence: $_" 'ERROR'+ }++ # Scan network anomalies+ try {+ $network = Find-NetworkAnomalies -IncludeEstablished+ if ($network.TotalAnomalies -gt 0) {+ $results.Findings += "$($network.TotalAnomalies) network anomalies detected"+ Write-IRLog "$($network.TotalAnomalies) network anomalies found" 'WARNING'+ }+ }+ catch {+ Write-IRLog "Error scanning network: $_" 'ERROR'+ }++ # Step 3: Network Isolation (if requested or Critical severity)+ if ($IsolateSystem -or $Severity -eq 'Critical') {+ Write-Host "`n[3/6] Isolating system from network..." -ForegroundColor Red++ if ($PSCmdlet.ShouldProcess($env:COMPUTERNAME, "Disable network adapters")) {+ Write-IRLog "Attempting network isolation" 'WARNING'++ try {+ $adapters = Get-NetAdapter | Where-Object { $_.Status -eq 'Up' }+ foreach ($adapter in $adapters) {+ Disable-NetAdapter -Name $adapter.Name -Confirm:$false -ErrorAction Stop+ $results.Actions += "Disabled network adapter: $($adapter.Name)"+ Write-IRLog "Disabled adapter: $($adapter.Name)" 'SUCCESS'+ }+ $results.NetworkIsolation = $true+ Write-Host "System isolated from network" -ForegroundColor Green+ }+ catch {+ Write-IRLog "Failed to isolate network: $_" 'ERROR'+ Write-Warning "Network isolation failed: $_"+ }+ }+ }+ else {+ Write-Host "`n[3/6] Network isolation: SKIPPED" -ForegroundColor Yellow+ $results.Actions += "Network isolation skipped (not requested)"+ }++ # Step 4: Terminate Suspicious Processes+ if ($KillSuspiciousProcesses -and $threats) {+ Write-Host "`n[4/6] Terminating suspicious processes..." -ForegroundColor Red++ $highThreatProcs = $threats | Where-Object { $_.SuspicionScore -ge 60 } | Sort-Object -Property SuspicionScore -Descending++ foreach ($proc in $highThreatProcs) {+ if ($PSCmdlet.ShouldProcess("Process $($proc.ProcessName) (PID: $($proc.ProcessId))", "Terminate")) {+ try {+ Stop-Process -Id $proc.ProcessId -Force -ErrorAction Stop+ $results.ProcessesTerminated += [PSCustomObject]@{+ ProcessName = $proc.ProcessName+ ProcessId = $proc.ProcessId+ SuspicionScore = $proc.SuspicionScore+ Reason = $proc.Reasons+ }+ Write-IRLog "Terminated process: $($proc.ProcessName) (PID: $($proc.ProcessId))" 'SUCCESS'+ }+ catch {+ Write-IRLog "Failed to terminate $($proc.ProcessName): $_" 'ERROR'+ }+ }+ }++ Write-Host "Terminated $($results.ProcessesTerminated.Count) suspicious processes" -ForegroundColor Green+ }+ else {+ Write-Host "`n[4/6] Process termination: SKIPPED" -ForegroundColor Yellow+ $results.Actions += "Process termination skipped"+ }++ # Step 5: Collect Forensic Evidence+ if ($CollectEvidence) {+ Write-Host "`n[5/6] Collecting forensic evidence..." -ForegroundColor Cyan+ Write-IRLog "Starting evidence collection" 'INFO'++ # Collect system information+ try {+ $sysInfo = Get-SystemInfo -IncludeInstalledSoftware -IncludeHotfixes+ $sysInfo | ConvertTo-Json -Depth 5 | Out-File (Join-Path $OutputPath "SystemInfo.json")+ $results.EvidenceCollected += "System information"+ Write-IRLog "Collected system information" 'SUCCESS'+ }+ catch {+ Write-IRLog "Failed to collect system info: $_" 'ERROR'+ }++ # Collect running processes+ try {+ Get-Process | Select-Object Name, Id, Path, StartTime, CPU, WorkingSet64 |+ Export-Csv (Join-Path $OutputPath "RunningProcesses.csv") -NoTypeInformation+ $results.EvidenceCollected += "Running processes list"+ Write-IRLog "Collected process list" 'SUCCESS'+ }+ catch {+ Write-IRLog "Failed to collect processes: $_" 'ERROR'+ }++ # Collect network connections+ try {+ Get-NetTCPConnection | Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State, OwningProcess |+ Export-Csv (Join-Path $OutputPath "NetworkConnections.csv") -NoTypeInformation+ $results.EvidenceCollected += "Network connections"+ Write-IRLog "Collected network connections" 'SUCCESS'+ }+ catch {+ Write-IRLog "Failed to collect network info: $_" 'ERROR'+ }++ # Collect event logs+ try {+ $eventAnalysis = Get-EventLogAnalysis -Hours 48+ $eventAnalysis | ConvertTo-Json -Depth 5 | Out-File (Join-Path $OutputPath "EventLogAnalysis.json")+ $results.EvidenceCollected += "Event log analysis"+ Write-IRLog "Collected event logs" 'SUCCESS'+ }+ catch {+ Write-IRLog "Failed to collect event logs: $_" 'ERROR'+ }++ # Collect registry analysis+ try {+ $regAnalysis = Get-RegistryAnalysis -IncludeAutoRun+ $regAnalysis | ConvertTo-Json -Depth 5 | Out-File (Join-Path $OutputPath "RegistryAnalysis.json")+ $results.EvidenceCollected += "Registry analysis"+ Write-IRLog "Collected registry analysis" 'SUCCESS'+ }+ catch {+ Write-IRLog "Failed to collect registry data: $_" 'ERROR'+ }++ Write-Host "Collected $($results.EvidenceCollected.Count) evidence artifacts" -ForegroundColor Green+ }+ else {+ Write-Host "`n[5/6] Evidence collection: SKIPPED" -ForegroundColor Yellow+ $results.Actions += "Evidence collection skipped"+ }++ # Step 6: Generate Incident Report+ Write-Host "`n[6/6] Generating incident report..." -ForegroundColor Cyan+ Write-IRLog "Generating final report" 'INFO'++ $results.Status = 'Completed'+ $results | ConvertTo-Json -Depth 5 | Out-File (Join-Path $OutputPath "IncidentResponse_Report.json")++ # Create summary report+ $summary = @"+=== INCIDENT RESPONSE SUMMARY ===+Date/Time: $($results.IncidentDate)+Severity: $($results.Severity)+Computer: $($results.ComputerName)++FINDINGS:+$($results.Findings | ForEach-Object { " - $_" } | Out-String)++ACTIONS TAKEN:+$($results.Actions | ForEach-Object { " - $_" } | Out-String)++PROCESSES TERMINATED: $($results.ProcessesTerminated.Count)+$($results.ProcessesTerminated | ForEach-Object { " - $($_.ProcessName) (PID: $($_.ProcessId)) - Score: $($_.SuspicionScore)" } | Out-String)++NETWORK ISOLATION: $($results.NetworkIsolation)++EVIDENCE COLLECTED: $($results.EvidenceCollected.Count) artifacts+$($results.EvidenceCollected | ForEach-Object { " - $_" } | Out-String)++STATUS: $($results.Status)++All evidence and logs saved to: $OutputPath+"@++ $summary | Out-File (Join-Path $OutputPath "Summary.txt")+ Write-IRLog "Incident response completed" 'SUCCESS'++ }+ catch {+ $results.Status = 'Failed'+ Write-IRLog "Incident response failed: $_" 'ERROR'+ throw+ }+ }++ end {+ Write-Host "`n=== INCIDENT RESPONSE COMPLETE ===" -ForegroundColor Green+ Write-Host "Status: $($results.Status)" -ForegroundColor $(if ($results.Status -eq 'Completed') { 'Green' } else { 'Red' })+ Write-Host "Output directory: $OutputPath" -ForegroundColor Cyan+ Write-Host "`nReview the incident report and evidence before proceeding with remediation." -ForegroundColor Yellow++ return $results+ }+}\ No newline at end of filediff --git a/Test-Module.ps1 b/Test-Module.ps1new file mode 100644index 0000000..152569c--- /dev/null+++ b/Test-Module.ps1@@ -0,0 +1,24 @@+# Test script to load and test the module+$ErrorActionPreference = 'Stop'++try {+ # Remove module if already loaded+ if (Get-Module -Name WindowsSecurityAudit) {+ Remove-Module WindowsSecurityAudit -Force+ }++ # Import the module+ Import-Module "$PSScriptRoot\WindowsSecurityAudit.psd1" -Force++ Write-Host "`nModule loaded successfully!" -ForegroundColor Green+ Write-Host "`nAvailable functions:" -ForegroundColor Cyan+ Get-Command -Module WindowsSecurityAudit | Format-Table -Property Name, CommandType++ # Test a function+ Write-Host "`nTesting Get-SecurityBaseline..." -ForegroundColor Yellow+ $baseline = Get-SecurityBaseline+ $baseline | Format-List++} catch {+ Write-Error "Failed to load module: $_"+}\ No newline at end of filediff --git a/ThreatHunting/Find-APTIndicators.ps1 b/ThreatHunting/Find-APTIndicators.ps1new file mode 100644index 0000000..2ba4b2b--- /dev/null+++ b/ThreatHunting/Find-APTIndicators.ps1@@ -0,0 +1,643 @@+function Find-APTIndicators {+ <#+ .SYNOPSIS+ Detects Advanced Persistent Threat (APT) indicators on the system+ .DESCRIPTION+ Hunts for APT indicators including suspicious services, scheduled tasks,+ registry modifications, file system artifacts, and network connections.+ Uses whitelisting to minimize false positives.+ .PARAMETER CheckServices+ Check for suspicious services+ .PARAMETER CheckScheduledTasks+ Check for suspicious scheduled tasks+ .PARAMETER CheckRegistry+ Check for registry-based persistence+ .PARAMETER CheckNetworkConnections+ Check for suspicious network connections+ .PARAMETER DeepScan+ Enable comprehensive scanning (slower but more thorough)+ .EXAMPLE+ Find-APTIndicators -CheckServices -CheckScheduledTasks -CheckRegistry+ Find-APTIndicators -DeepScan+ .OUTPUTS+ PSCustomObject with APT indicators+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$CheckServices,++ [Parameter()]+ [switch]$CheckScheduledTasks,++ [Parameter()]+ [switch]$CheckRegistry,++ [Parameter()]+ [switch]$CheckNetworkConnections,++ [Parameter()]+ [switch]$DeepScan+ )++ begin {+ Write-Host "=== APT INDICATOR HUNTING ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ if ($DeepScan) {+ $CheckServices = $true+ $CheckScheduledTasks = $true+ $CheckRegistry = $true+ $CheckNetworkConnections = $true+ Write-Host "Deep Scan Mode: Enabled" -ForegroundColor Yellow+ }++ $results = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ Indicators = @{+ SuspiciousServices = @()+ SuspiciousScheduledTasks = @()+ RegistryPersistence = @()+ NetworkConnections = @()+ }+ ThreatScore = 0+ RiskLevel = 'Unknown'+ Summary = @{+ TotalIndicators = 0+ CriticalIndicators = 0+ HighIndicators = 0+ MediumIndicators = 0+ }+ Recommendations = @()+ }++ # Known malicious patterns (actual threats only)+ $knownMaliciousNames = @(+ 'mimikatz', 'rubeus', 'sharphound', 'bloodhound', 'covenant',+ 'empire', 'meterpreter', 'cobalt', 'beacon', 'lazagne',+ 'procdump', 'paexec', 'wmiexec', 'smbexec', 'psexesvc',+ 'invoke-obfuscation', 'powersploit', 'nishang'+ )++ # WHITELIST - Known legitimate software/services+ $legitimateServices = @(+ 'WinDefend', 'WdNisSvc', 'Sense', 'WdBoot', 'WdFilter', 'WdNisDrv',+ 'MDCoreSvc', 'MsSecCore', 'SecurityHealthService',+ 'MpsSvc', 'Spooler', 'BITS', 'wuauserv', 'CryptSvc',+ 'OneSyncSvc', 'AdobeARMservice', 'AdobeUpdateService',+ 'GoogleUpdate', 'gupdate', 'gupdatem', 'TeamViewer', 'LogMeIn',+ 'Dropbox', 'DropboxUpdate', 'Box', 'ZoomCptService', 'CiscoSpark',+ 'ClickToRunSvc', 'InstallService', 'SgrmBroker'+ )++ $legitimateTaskPatterns = @(+ 'Microsoft', 'Windows', 'Adobe', 'Google', 'OneDrive',+ 'Dropbox', 'Zoom', 'Cisco', 'Teams', 'Slack', 'Skype',+ 'Driver', 'Update', 'Cleanup', 'Maintenance', 'Office',+ 'OfficeClickToRun', 'OfficeSvc', 'Chrome', 'Firefox', 'Edge'+ )++ $legitimateRegistryValues = @(+ 'OneDrive', 'Slack', 'Teams', 'Zoom', 'Cisco',+ 'Discord', 'Spotify', 'Steam', 'Epic', 'Origin',+ 'Chrome', 'Firefox', 'Edge', 'Brave', 'Opera',+ 'Visual Studio', 'VSCode', 'Notepad', 'Sublime',+ 'Office', 'Word', 'Excel', 'PowerPoint', 'Outlook'+ )++ # Windows system folders (legitimate)+ $legitimateRegistryKeys = @(+ 'Common Administrative Tools', 'Common AppData', 'Common Desktop',+ 'Common Documents', 'Common Programs', 'Common Start Menu',+ 'Common Startup', 'Common Templates', 'CommonMusic',+ 'CommonPictures', 'CommonVideo', 'OEM Links'+ )++ # Suspicious locations - using single quotes for $Recycle to avoid variable expansion+ $suspiciousLocations = @(+ "$env:TEMP",+ "$env:APPDATA\Local\Temp",+ "C:\Users\Public",+ "C:\Windows\Temp",+ "C:\Temp",+ 'C:\$Recycle.Bin'+ )+ }++ process {+ try {+ # 1. Check Suspicious Services+ if ($CheckServices) {+ Write-Host "`n[1/4] Hunting for suspicious services..." -ForegroundColor Cyan++ try {+ $services = Get-CimInstance Win32_Service | Where-Object {+ $_.StartMode -eq 'Auto' -or $_.State -eq 'Running'+ }++ foreach ($service in $services) {+ # Skip whitelisted services+ $isWhitelisted = $false+ foreach ($legit in $legitimateServices) {+ if ($service.Name -like "*$legit*" -or $service.DisplayName -like "*$legit*") {+ $isWhitelisted = $true+ break+ }+ }++ if ($isWhitelisted) {+ continue+ }++ $suspiciousScore = 0+ $reasons = @()++ # Check for actual malicious names+ foreach ($malName in $knownMaliciousNames) {+ if ($service.Name -match $malName -or $service.DisplayName -match $malName) {+ $suspiciousScore += 70+ $reasons += "CRITICAL: Name matches known malware: $malName"+ }+ }++ # Check PathName+ if ($service.PathName) {+ # Check for suspicious locations (exclude Program Files)+ if ($service.PathName -notmatch "Program Files") {+ foreach ($suspiciousLoc in $suspiciousLocations) {+ if ($service.PathName -match [regex]::Escape($suspiciousLoc)) {+ $suspiciousScore += 40+ $reasons += "Runs from suspicious temp/public location"+ break+ }+ }+ }++ # Check for long encoded commands (100+ chars of base64)+ if ($service.PathName -match "powershell.*-enc\s+[A-Za-z0-9+/=]{100,}") {+ $suspiciousScore += 60+ $reasons += "CRITICAL: Contains long encoded PowerShell command"+ }++ # Check for multiple evasion techniques+ if ($service.PathName -match "-nop.*-w\s+hidden.*-exec\s+bypass") {+ $suspiciousScore += 50+ $reasons += "Uses multiple evasion techniques"+ }++ # Check for download cradles+ if ($service.PathName -match "IEX.*\(.*WebClient.*DownloadString|Invoke-WebRequest.*IEX") {+ $suspiciousScore += 65+ $reasons += "CRITICAL: Downloads and executes remote code"+ }+ }++ # Only flag if score is significant (40+ threshold)+ if ($suspiciousScore -ge 40) {+ $severity = if ($suspiciousScore -ge 60) { 'Critical' }+ elseif ($suspiciousScore -ge 45) { 'High' }+ else { 'Medium' }++ $results.Indicators.SuspiciousServices += [PSCustomObject]@{+ Severity = $severity+ Name = $service.Name+ DisplayName = $service.DisplayName+ PathName = $service.PathName+ StartMode = $service.StartMode+ State = $service.State+ StartName = $service.StartName+ SuspiciousScore = $suspiciousScore+ Reasons = $reasons -join '; '+ }++ $results.ThreatScore += $suspiciousScore++ if ($severity -eq 'Critical') { $results.Summary.CriticalIndicators++ }+ elseif ($severity -eq 'High') { $results.Summary.HighIndicators++ }+ else { $results.Summary.MediumIndicators++ }++ Write-Host " [!] Suspicious Service: $($service.Name) [Score: $suspiciousScore]" -ForegroundColor Red+ }+ }++ if ($results.Indicators.SuspiciousServices.Count -eq 0) {+ Write-Host " No suspicious services found" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking services: $_"+ }+ }++ # 2. Check Suspicious Scheduled Tasks+ if ($CheckScheduledTasks) {+ Write-Host "`n[2/4] Hunting for suspicious scheduled tasks..." -ForegroundColor Cyan++ try {+ $tasks = Get-ScheduledTask | Where-Object { $_.State -ne 'Disabled' }++ foreach ($task in $tasks) {+ # Skip whitelisted tasks+ $isWhitelisted = $false+ foreach ($pattern in $legitimateTaskPatterns) {+ if ($task.TaskName -like "*$pattern*" -or $task.TaskPath -like "*$pattern*") {+ $isWhitelisted = $true+ break+ }+ }++ if ($isWhitelisted) {+ continue+ }++ $suspiciousScore = 0+ $reasons = @()++ # Check for actual malicious names+ foreach ($malName in $knownMaliciousNames) {+ if ($task.TaskName -match $malName) {+ $suspiciousScore += 70+ $reasons += "CRITICAL: Name matches known malware: $malName"+ }+ }++ # Check actions - with proper error handling+ $actionDetails = @()+ foreach ($action in $task.Actions) {+ # Check if Execute property exists+ if ($action.PSObject.Properties.Name -contains 'Execute' -and $action.Execute) {+ $actionDetails += "$($action.Execute) $($action.Arguments)"++ # Check for long encoded commands+ if ($action.Arguments -match "-enc\s+[A-Za-z0-9+/=]{100,}") {+ $suspiciousScore += 60+ $reasons += "CRITICAL: Contains long encoded command"+ }++ # Check for download cradles+ if ($action.Arguments -match "IEX.*DownloadString|Invoke-WebRequest.*IEX|Net\.WebClient.*DownloadString") {+ $suspiciousScore += 65+ $reasons += "CRITICAL: Downloads and executes remote code"+ }++ # Check for suspicious locations (exclude Program Files)+ if ($action.Execute -notmatch "Program Files") {+ foreach ($suspiciousLoc in $suspiciousLocations) {+ if ($action.Execute -match [regex]::Escape($suspiciousLoc)) {+ $suspiciousScore += 35+ $reasons += "Executes from suspicious temp location"+ break+ }+ }+ }+ }+ elseif ($action.PSObject.Properties.Name -contains 'Id') {+ # ComHandler or other action type+ $actionDetails += "Action: $($action.Id)"+ }+ }++ # Only flag if score is significant (35+ threshold)+ if ($suspiciousScore -ge 35) {+ $severity = if ($suspiciousScore -ge 60) { 'Critical' }+ elseif ($suspiciousScore -ge 45) { 'High' }+ else { 'Medium' }++ $results.Indicators.SuspiciousScheduledTasks += [PSCustomObject]@{+ Severity = $severity+ TaskName = $task.TaskName+ TaskPath = $task.TaskPath+ State = $task.State+ Actions = ($actionDetails -join '; ')+ RunAs = $task.Principal.UserId+ SuspiciousScore = $suspiciousScore+ Reasons = $reasons -join '; '+ }++ $results.ThreatScore += $suspiciousScore++ if ($severity -eq 'Critical') { $results.Summary.CriticalIndicators++ }+ elseif ($severity -eq 'High') { $results.Summary.HighIndicators++ }+ else { $results.Summary.MediumIndicators++ }++ Write-Host " [!] Suspicious Task: $($task.TaskName) [Score: $suspiciousScore]" -ForegroundColor Red+ }+ }++ if ($results.Indicators.SuspiciousScheduledTasks.Count -eq 0) {+ Write-Host " No suspicious scheduled tasks found" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking scheduled tasks: $_"+ }+ }++ # 3. Check Registry Persistence+ if ($CheckRegistry) {+ Write-Host "`n[3/4] Hunting for registry-based persistence..." -ForegroundColor Cyan++ try {+ # Common persistence registry locations+ $persistenceKeys = @(+ "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run",+ "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce",+ "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run",+ "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce",+ "HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Run"+ )++ foreach ($keyPath in $persistenceKeys) {+ if (Test-Path $keyPath) {+ $values = Get-ItemProperty -Path $keyPath -ErrorAction SilentlyContinue++ foreach ($property in $values.PSObject.Properties) {+ # Skip PowerShell default properties+ if ($property.Name -match "^PS") {+ continue+ }++ # Skip whitelisted registry values - using -like for pattern matching+ $isWhitelisted = $false+ foreach ($legit in $legitimateRegistryValues) {+ if ($property.Name -like "*$legit*") {+ $isWhitelisted = $true+ break+ }+ }++ # Skip Windows system registry keys+ foreach ($sysKey in $legitimateRegistryKeys) {+ if ($property.Name -eq $sysKey) {+ $isWhitelisted = $true+ break+ }+ }++ if ($isWhitelisted) {+ continue+ }++ $value = $property.Value+ if (-not $value) {+ continue+ }++ $suspiciousScore = 0+ $reasons = @()++ # Check for actual malicious patterns+ foreach ($malName in $knownMaliciousNames) {+ if ($value -match $malName) {+ $suspiciousScore += 70+ $reasons += "CRITICAL: Matches known malware: $malName"+ }+ }++ # Check for long encoded commands (100+ chars)+ if ($value -match "-enc\s+[A-Za-z0-9+/=]{100,}") {+ $suspiciousScore += 60+ $reasons += "CRITICAL: Contains long encoded command"+ }++ # Check for download cradles+ if ($value -match "IEX.*DownloadString|Invoke-WebRequest.*IEX|Net\.WebClient.*DownloadString") {+ $suspiciousScore += 65+ $reasons += "CRITICAL: Downloads and executes remote code"+ }++ # Check for suspicious locations (exclude Program Files)+ if ($value -notmatch "Program Files") {+ foreach ($suspiciousLoc in $suspiciousLocations) {+ if ($value -match [regex]::Escape($suspiciousLoc)) {+ $suspiciousScore += 35+ $reasons += "Points to suspicious temp location"+ break+ }+ }+ }++ # Check for heavy obfuscation (10+ obfuscation chars)+ if ($value -match "(\^|`){10,}|(%[a-zA-Z0-9]){10,}") {+ $suspiciousScore += 40+ $reasons += "Heavily obfuscated"+ }++ # Only flag if score is significant (35+ threshold)+ if ($suspiciousScore -ge 35) {+ $severity = if ($suspiciousScore -ge 60) { 'Critical' }+ elseif ($suspiciousScore -ge 45) { 'High' }+ else { 'Medium' }++ $results.Indicators.RegistryPersistence += [PSCustomObject]@{+ Severity = $severity+ RegistryKey = $keyPath+ ValueName = $property.Name+ ValueData = if ($value.Length -gt 200) { $value.Substring(0, 200) + "..." } else { $value }+ SuspiciousScore = $suspiciousScore+ Reasons = $reasons -join '; '+ }++ $results.ThreatScore += $suspiciousScore++ if ($severity -eq 'Critical') { $results.Summary.CriticalIndicators++ }+ elseif ($severity -eq 'High') { $results.Summary.HighIndicators++ }+ else { $results.Summary.MediumIndicators++ }++ Write-Host " [!] Suspicious Registry: $($property.Name) [Score: $suspiciousScore]" -ForegroundColor Red+ }+ }+ }+ }++ if ($results.Indicators.RegistryPersistence.Count -eq 0) {+ Write-Host " No suspicious registry persistence found" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking registry: $_"+ }+ }++ # 4. Check Network Connections+ if ($CheckNetworkConnections) {+ Write-Host "`n[4/4] Hunting for suspicious network connections..." -ForegroundColor Cyan++ try {+ $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue++ foreach ($conn in $connections) {+ $suspiciousScore = 0+ $reasons = @()++ # Get process info+ $process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue++ if ($process) {+ # Check for actual malicious process names+ foreach ($malName in $knownMaliciousNames) {+ if ($process.Name -match $malName) {+ $suspiciousScore += 70+ $reasons += "CRITICAL: Process matches known malware"+ }+ }++ # Check for high-risk ports (not common web traffic)+ $highRiskPorts = @(4444, 5555, 1337, 31337, 6666, 7777)+ if ($conn.RemotePort -in $highRiskPorts) {+ $suspiciousScore += 50+ $reasons += "Uses high-risk port: $($conn.RemotePort)"+ }++ # Scripting processes with external connections (exclude localhost and known IPs)+ if ($process.Name -match "powershell|cmd|wscript|cscript|mshta" -and+ $conn.RemoteAddress -notmatch "127\.0\.0\.1|::1|0\.0\.0\.0") {+ $suspiciousScore += 40+ $reasons += "Scripting process with external network connection"+ }+ }++ # Only flag if score is significant (40+ threshold)+ if ($suspiciousScore -ge 40) {+ $severity = if ($suspiciousScore -ge 60) { 'Critical' }+ elseif ($suspiciousScore -ge 45) { 'High' }+ else { 'Medium' }++ $results.Indicators.NetworkConnections += [PSCustomObject]@{+ Severity = $severity+ ProcessName = $process.Name+ ProcessId = $conn.OwningProcess+ ProcessPath = $process.Path+ LocalAddress = "$($conn.LocalAddress):$($conn.LocalPort)"+ RemoteAddress = "$($conn.RemoteAddress):$($conn.RemotePort)"+ State = $conn.State+ SuspiciousScore = $suspiciousScore+ Reasons = $reasons -join '; '+ }++ $results.ThreatScore += $suspiciousScore++ if ($severity -eq 'Critical') { $results.Summary.CriticalIndicators++ }+ elseif ($severity -eq 'High') { $results.Summary.HighIndicators++ }+ else { $results.Summary.MediumIndicators++ }++ Write-Host " [!] Suspicious Connection: $($process.Name) -> $($conn.RemoteAddress):$($conn.RemotePort) [Score: $suspiciousScore]" -ForegroundColor Red+ }+ }++ if ($results.Indicators.NetworkConnections.Count -eq 0) {+ Write-Host " No suspicious network connections found" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking network connections: $_"+ }+ }++ # Calculate total indicators and risk level+ $results.Summary.TotalIndicators =+ $results.Indicators.SuspiciousServices.Count ++ $results.Indicators.SuspiciousScheduledTasks.Count ++ $results.Indicators.RegistryPersistence.Count ++ $results.Indicators.NetworkConnections.Count++ # Determine risk level based on threat score and critical indicators+ if ($results.Summary.CriticalIndicators -gt 0 -or $results.ThreatScore -ge 200) {+ $results.RiskLevel = 'Critical'+ } elseif ($results.Summary.HighIndicators -gt 2 -or $results.ThreatScore -ge 100) {+ $results.RiskLevel = 'High'+ } elseif ($results.Summary.TotalIndicators -gt 0) {+ $results.RiskLevel = 'Medium'+ } else {+ $results.RiskLevel = 'Low'+ }++ # Generate recommendations+ if ($results.Summary.CriticalIndicators -gt 0) {+ $results.Recommendations += "IMMEDIATE ACTION: Investigate and contain critical indicators"+ $results.Recommendations += "Isolate affected systems from network"+ $results.Recommendations += "Collect forensic evidence before remediation"+ }++ if ($results.Indicators.SuspiciousServices.Count -gt 0) {+ $results.Recommendations += "Review and disable suspicious services"+ }++ if ($results.Indicators.SuspiciousScheduledTasks.Count -gt 0) {+ $results.Recommendations += "Remove suspicious scheduled tasks"+ }++ if ($results.Indicators.RegistryPersistence.Count -gt 0) {+ $results.Recommendations += "Clean registry persistence mechanisms"+ }++ if ($results.Summary.TotalIndicators -gt 0) {+ $results.Recommendations += "Enable enhanced logging and monitoring"+ $results.Recommendations += "Conduct full forensic analysis"+ }++ }+ catch {+ Write-Error "Error during APT hunting: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== HUNT COMPLETE ===" -ForegroundColor $(+ if ($results.RiskLevel -in @('Critical', 'High')) { 'Red' }+ elseif ($results.RiskLevel -eq 'Medium') { 'Yellow' }+ else { 'Green' }+ )++ Write-Host "`nThreat Assessment:" -ForegroundColor Cyan+ Write-Host " Risk Level: " -NoNewline+ Write-Host $results.RiskLevel -ForegroundColor $(+ switch ($results.RiskLevel) {+ 'Critical' { 'Red' }+ 'High' { 'Red' }+ 'Medium' { 'Yellow' }+ 'Low' { 'Green' }+ }+ )+ Write-Host " Threat Score: $($results.ThreatScore)" -ForegroundColor White+ Write-Host " Total Indicators: $($results.Summary.TotalIndicators)" -ForegroundColor White++ if ($results.Summary.TotalIndicators -gt 0) {+ Write-Host "`nIndicator Breakdown:" -ForegroundColor Cyan+ Write-Host " Critical: $($results.Summary.CriticalIndicators)" -ForegroundColor Red+ Write-Host " High: $($results.Summary.HighIndicators)" -ForegroundColor Yellow+ Write-Host " Medium: $($results.Summary.MediumIndicators)" -ForegroundColor Yellow++ if ($results.Indicators.SuspiciousServices.Count -gt 0) {+ Write-Host "`n Suspicious Services: $($results.Indicators.SuspiciousServices.Count)" -ForegroundColor Red+ }+ if ($results.Indicators.SuspiciousScheduledTasks.Count -gt 0) {+ Write-Host " Suspicious Tasks: $($results.Indicators.SuspiciousScheduledTasks.Count)" -ForegroundColor Red+ }+ if ($results.Indicators.RegistryPersistence.Count -gt 0) {+ Write-Host " Registry Persistence: $($results.Indicators.RegistryPersistence.Count)" -ForegroundColor Red+ }+ if ($results.Indicators.NetworkConnections.Count -gt 0) {+ Write-Host " Network Connections: $($results.Indicators.NetworkConnections.Count)" -ForegroundColor Red+ }+ }++ if ($results.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $results.Recommendations | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ if ($results.RiskLevel -in @('Critical', 'High')) {+ Write-Host "`n[!!!] APT INDICATORS DETECTED - INCIDENT RESPONSE REQUIRED [!!!]" -ForegroundColor Red -BackgroundColor Black+ } elseif ($results.RiskLevel -eq 'Low' -and $results.Summary.TotalIndicators -eq 0) {+ Write-Host "`n[OK] No APT indicators detected - System appears clean" -ForegroundColor Green+ }++ return $results+ }+}\ No newline at end of filediff --git a/ThreatHunting/Find-DataExfiltration.ps1 b/ThreatHunting/Find-DataExfiltration.ps1new file mode 100644index 0000000..e196d90--- /dev/null+++ b/ThreatHunting/Find-DataExfiltration.ps1@@ -0,0 +1,440 @@+function Find-DataExfiltration {+ <#+ .SYNOPSIS+ Detects potential data exfiltration activities+ .DESCRIPTION+ Identifies indicators of data exfiltration including large file transfers,+ uploads to cloud services, compression activities, and staging behaviors+ .PARAMETER CheckLargeTransfers+ Check for large network transfers+ .PARAMETER CheckCloudUploads+ Check for uploads to cloud services+ .PARAMETER CheckCompression+ Check for file compression activities+ .PARAMETER CheckStaging+ Check for data staging activities+ .PARAMETER ThresholdMB+ Threshold for large file transfers in MB (default: 100)+ .EXAMPLE+ Find-DataExfiltration -CheckLargeTransfers -CheckCloudUploads+ Find-DataExfiltration -CheckLargeTransfers -CheckCompression -CheckStaging -ThresholdMB 50+ .OUTPUTS+ PSCustomObject with data exfiltration indicators+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$CheckLargeTransfers,++ [Parameter()]+ [switch]$CheckCloudUploads,++ [Parameter()]+ [switch]$CheckCompression,++ [Parameter()]+ [switch]$CheckStaging,++ [Parameter()]+ [int]$ThresholdMB = 100+ )++ begin {+ Write-Host "=== DATA EXFILTRATION DETECTION ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow+ Write-Host "Transfer Threshold: $ThresholdMB MB" -ForegroundColor Yellow++ if (-not ($CheckLargeTransfers -or $CheckCloudUploads -or $CheckCompression -or $CheckStaging)) {+ $CheckLargeTransfers = $true+ $CheckCloudUploads = $true+ Write-Host "No specific check selected - enabling default checks" -ForegroundColor Yellow+ }++ $results = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ ThresholdMB = $ThresholdMB+ Indicators = @{+ LargeTransfers = @()+ CloudUploads = @()+ Compression = @()+ Staging = @()+ }+ Summary = @{+ TotalIndicators = 0+ CriticalFindings = 0+ HighFindings = 0+ MediumFindings = 0+ TotalDataMB = 0+ }+ Recommendations = @()+ }++ # Known cloud services and upload endpoints+ $cloudServices = @(+ 'dropbox.com',+ 'drive.google.com',+ 'onedrive.live.com',+ 'box.com',+ 'mega.nz',+ 'wetransfer.com',+ 'sendspace.com',+ 'mediafire.com',+ 'filebin.net',+ 'pastebin.com',+ 'transfer.sh',+ 's3.amazonaws.com',+ 'blob.core.windows.net'+ )+ }++ process {+ try {+ # 1. Check for Large Network Transfers+ if ($CheckLargeTransfers) {+ Write-Host "`n[1/4] Checking network transfers..." -ForegroundColor Cyan++ try {+ # Get network interface statistics+ $networkStats = Get-NetAdapterStatistics -ErrorAction SilentlyContinue++ if ($networkStats) {+ foreach ($adapter in $networkStats) {+ $sentGB = [math]::Round($adapter.SentBytes / 1GB, 2)+ $receivedGB = [math]::Round($adapter.ReceivedBytes / 1GB, 2)++ # Check active connections with high data transfer+ $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue |+ Where-Object { $_.RemoteAddress -notmatch '^(127\.|::1|0\.0\.0\.0)' }++ foreach ($conn in $connections | Select-Object -First 10) {+ $process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue++ if ($process) {+ # Skip browsers and common legitimate processes+ if ($process.Name -match 'chrome|firefox|edge|teams|zoom|onedrive') {+ continue+ }++ $indicator = [PSCustomObject]@{+ Type = 'NetworkTransfer'+ Process = $process.Name+ ProcessId = $conn.OwningProcess+ RemoteAddress = $conn.RemoteAddress+ RemotePort = $conn.RemotePort+ LocalPort = $conn.LocalPort+ Severity = 'Medium'+ Description = "Active connection from $($process.Name) to $($conn.RemoteAddress)"+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.Indicators.LargeTransfers += $indicator+ $results.Summary.MediumFindings++++ Write-Host " [!] Active: $($process.Name) -> $($conn.RemoteAddress):$($conn.RemotePort)" -ForegroundColor Yellow+ }+ }+ }+ }++ if ($results.Indicators.LargeTransfers.Count -eq 0) {+ Write-Host " No suspicious large transfers detected" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking network transfers: $_"+ }+ }++ # 2. Check for Cloud Service Uploads+ if ($CheckCloudUploads) {+ Write-Host "`n[2/4] Checking cloud service uploads..." -ForegroundColor Cyan++ try {+ # Check active connections to known cloud services+ $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue++ $foundCount = 0++ foreach ($conn in $connections) {+ # Try to resolve hostname+ try {+ $hostname = [System.Net.Dns]::GetHostEntry($conn.RemoteAddress).HostName+ }+ catch {+ $hostname = $conn.RemoteAddress+ }++ foreach ($cloudService in $cloudServices) {+ if ($hostname -like "*$cloudService*") {+ $process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue++ # Skip if it's a browser (expected behavior)+ if ($process.Name -match 'chrome|firefox|edge|msedge') {+ continue+ }++ $indicator = [PSCustomObject]@{+ Type = 'CloudUpload'+ Process = $process.Name+ ProcessId = $conn.OwningProcess+ CloudService = $cloudService+ RemoteAddress = $conn.RemoteAddress+ Hostname = $hostname+ Severity = 'High'+ Description = "Connection to $cloudService from $($process.Name)"+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.Indicators.CloudUploads += $indicator+ $results.Summary.HighFindings+++ $foundCount++++ Write-Host " [!] Cloud: $cloudService via $($process.Name)" -ForegroundColor Red+ break+ }+ }+ }++ if ($foundCount -eq 0) {+ Write-Host " No suspicious cloud uploads detected" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking cloud uploads: $_"+ }+ }++ # 3. Check for File Compression Activities+ if ($CheckCompression) {+ Write-Host "`n[3/4] Checking compression activities..." -ForegroundColor Cyan++ try {+ # Check for running compression tools+ $compressionTools = @('7z', 'winrar', 'zip', 'rar', 'tar', 'gzip')+ $processes = Get-Process | Select-Object Name, Id, Path, StartTime++ $foundCount = 0++ foreach ($process in $processes) {+ foreach ($tool in $compressionTools) {+ if ($process.Name -like "*$tool*") {+ $indicator = [PSCustomObject]@{+ Type = 'Compression'+ Process = $process.Name+ ProcessId = $process.Id+ Path = $process.Path+ StartTime = if ($process.StartTime) { $process.StartTime.ToString("yyyy-MM-dd HH:mm:ss") } else { "Unknown" }+ Severity = 'Medium'+ Description = "Compression tool running: $($process.Name)"+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.Indicators.Compression += $indicator+ $results.Summary.MediumFindings+++ $foundCount++++ Write-Host " [!] Compression: $($process.Name) (PID: $($process.Id))" -ForegroundColor Yellow+ break+ }+ }+ }++ # Check recent archive files in common locations+ $tempPaths = @($env:TEMP, $env:USERPROFILE, "$env:USERPROFILE\Downloads", "$env:USERPROFILE\Desktop")+ $archiveExtensions = @('*.zip', '*.rar', '*.7z', '*.tar', '*.gz')++ foreach ($path in $tempPaths) {+ if (Test-Path $path) {+ foreach ($ext in $archiveExtensions) {+ $recentArchives = Get-ChildItem -Path $path -Filter $ext -File -ErrorAction SilentlyContinue |+ Where-Object { $_.LastWriteTime -gt (Get-Date).AddHours(-24) } |+ Where-Object { $_.Length -gt ($ThresholdMB * 1MB) }++ foreach ($archive in $recentArchives) {+ $sizeMB = [math]::Round($archive.Length / 1MB, 2)++ $indicator = [PSCustomObject]@{+ Type = 'Compression'+ Process = 'N/A'+ ProcessId = 'N/A'+ Path = $archive.FullName+ SizeMB = $sizeMB+ LastModified = $archive.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")+ Severity = if ($sizeMB -gt 500) { 'High' } else { 'Medium' }+ Description = "Large archive file: $($archive.Name) ($sizeMB MB)"+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.Indicators.Compression += $indicator+ $results.Summary.TotalDataMB += $sizeMB++ if ($sizeMB -gt 500) {+ $results.Summary.HighFindings+++ } else {+ $results.Summary.MediumFindings+++ }++ $foundCount++++ Write-Host " [!] Archive: $($archive.Name) ($sizeMB MB)" -ForegroundColor Yellow+ }+ }+ }+ }++ if ($foundCount -eq 0) {+ Write-Host " No suspicious compression activities detected" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking compression: $_"+ }+ }++ # 4. Check for Data Staging+ if ($CheckStaging) {+ Write-Host "`n[4/4] Checking data staging..." -ForegroundColor Cyan++ try {+ # Check for large files in staging locations+ $stagingPaths = @(+ "$env:TEMP",+ "$env:USERPROFILE\AppData\Local\Temp",+ "C:\Users\Public",+ "C:\ProgramData"+ )++ $foundCount = 0++ foreach ($path in $stagingPaths) {+ if (Test-Path $path) {+ # Find large files created recently+ $recentFiles = Get-ChildItem -Path $path -File -Recurse -ErrorAction SilentlyContinue -Depth 2 |+ Where-Object {+ $_.Length -gt ($ThresholdMB * 1MB) -and+ $_.CreationTime -gt (Get-Date).AddHours(-24)+ } |+ Sort-Object Length -Descending |+ Select-Object -First 5++ foreach ($file in $recentFiles) {+ $sizeMB = [math]::Round($file.Length / 1MB, 2)++ $indicator = [PSCustomObject]@{+ Type = 'Staging'+ Process = 'N/A'+ ProcessId = 'N/A'+ Path = $file.FullName+ FileName = $file.Name+ SizeMB = $sizeMB+ Created = $file.CreationTime.ToString("yyyy-MM-dd HH:mm:ss")+ Severity = if ($sizeMB -gt 500) { 'High' } else { 'Medium' }+ Description = "Large file in staging location: $($file.Name) ($sizeMB MB)"+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.Indicators.Staging += $indicator+ $results.Summary.TotalDataMB += $sizeMB++ if ($sizeMB -gt 500) {+ $results.Summary.HighFindings+++ } else {+ $results.Summary.MediumFindings+++ }++ $foundCount++++ Write-Host " [!] Staged: $($file.Name) ($sizeMB MB) in $path" -ForegroundColor Yellow+ }+ }+ }++ if ($foundCount -eq 0) {+ Write-Host " No suspicious data staging detected" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking staging: $_"+ }+ }++ # Calculate summary+ $results.Summary.TotalIndicators =+ $results.Indicators.LargeTransfers.Count ++ $results.Indicators.CloudUploads.Count ++ $results.Indicators.Compression.Count ++ $results.Indicators.Staging.Count++ # Generate recommendations+ if ($results.Summary.TotalIndicators -gt 0) {+ if ($results.Summary.HighFindings -gt 0) {+ $results.Recommendations += "HIGH: Investigate high-severity exfiltration indicators immediately"+ }++ $results.Recommendations += "Review and investigate flagged processes and files"+ $results.Recommendations += "Check network logs for data transfer volumes"+ $results.Recommendations += "Implement DLP (Data Loss Prevention) solution"+ $results.Recommendations += "Monitor cloud service access"+ $results.Recommendations += "Enable file access auditing on sensitive data"++ if ($results.Indicators.CloudUploads.Count -gt 0) {+ $results.Recommendations += "Consider blocking unauthorized cloud services"+ }++ if ($results.Summary.TotalDataMB -gt 1000) {+ $results.Recommendations += "CRITICAL: Large volume of data detected ($([math]::Round($results.Summary.TotalDataMB/1024, 2)) GB)"+ }+ }++ }+ catch {+ Write-Error "Error during data exfiltration detection: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== SCAN COMPLETE ===" -ForegroundColor $(+ if ($results.Summary.HighFindings -gt 0) { 'Red' }+ elseif ($results.Summary.TotalIndicators -gt 0) { 'Yellow' }+ else { 'Green' }+ )++ Write-Host "`nDetection Summary:" -ForegroundColor Cyan+ Write-Host " Total Indicators: $($results.Summary.TotalIndicators)" -ForegroundColor White+ Write-Host " Critical: $($results.Summary.CriticalFindings)" -ForegroundColor Red+ Write-Host " High: $($results.Summary.HighFindings)" -ForegroundColor Yellow+ Write-Host " Medium: $($results.Summary.MediumFindings)" -ForegroundColor Yellow+ Write-Host " Total Data Volume: $([math]::Round($results.Summary.TotalDataMB, 2)) MB" -ForegroundColor White++ if ($results.Summary.TotalIndicators -gt 0) {+ Write-Host "`nIndicator Breakdown:" -ForegroundColor Cyan+ if ($results.Indicators.LargeTransfers.Count -gt 0) {+ Write-Host " Large Transfers: $($results.Indicators.LargeTransfers.Count)" -ForegroundColor White+ }+ if ($results.Indicators.CloudUploads.Count -gt 0) {+ Write-Host " Cloud Uploads: $($results.Indicators.CloudUploads.Count)" -ForegroundColor White+ }+ if ($results.Indicators.Compression.Count -gt 0) {+ Write-Host " Compression: $($results.Indicators.Compression.Count)" -ForegroundColor White+ }+ if ($results.Indicators.Staging.Count -gt 0) {+ Write-Host " Staging: $($results.Indicators.Staging.Count)" -ForegroundColor White+ }+ }+ else {+ Write-Host "`nNo data exfiltration indicators detected" -ForegroundColor Green+ }++ if ($results.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $results.Recommendations | Select-Object -Unique | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ return $results+ }+}\ No newline at end of filediff --git a/ThreatHunting/Find-LateralMovement.ps1 b/ThreatHunting/Find-LateralMovement.ps1new file mode 100644index 0000000..44e5589--- /dev/null+++ b/ThreatHunting/Find-LateralMovement.ps1@@ -0,0 +1,399 @@+function Find-LateralMovement {+ <#+ .SYNOPSIS+ Detects lateral movement indicators in the environment+ .DESCRIPTION+ Identifies signs of lateral movement including remote connections,+ pass-the-hash, PSRemoting, RDP, SMB shares, and credential access+ .PARAMETER CheckNetworkConnections+ Check for suspicious network connections+ .PARAMETER CheckRemoteExecution+ Check for remote execution indicators+ .PARAMETER CheckAuthentication+ Check authentication logs for lateral movement+ .PARAMETER CheckSMBShares+ Check SMB share access+ .PARAMETER Days+ Number of days to check in event logs (default: 7)+ .EXAMPLE+ Find-LateralMovement -CheckNetworkConnections -CheckAuthentication+ Find-LateralMovement -CheckNetworkConnections -CheckRemoteExecution -CheckAuthentication -Days 1+ .OUTPUTS+ PSCustomObject with lateral movement indicators+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$CheckNetworkConnections,++ [Parameter()]+ [switch]$CheckRemoteExecution,++ [Parameter()]+ [switch]$CheckAuthentication,++ [Parameter()]+ [switch]$CheckSMBShares,++ [Parameter()]+ [int]$Days = 7+ )++ begin {+ Write-Host "=== LATERAL MOVEMENT DETECTION ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow+ Write-Host "Analysis Period: Last $Days days" -ForegroundColor Yellow++ if (-not ($CheckNetworkConnections -or $CheckRemoteExecution -or $CheckAuthentication -or $CheckSMBShares)) {+ $CheckNetworkConnections = $true+ $CheckAuthentication = $true+ Write-Host "No specific check selected - enabling default checks" -ForegroundColor Yellow+ }++ $results = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ AnalysisPeriod = $Days+ Indicators = @{+ NetworkConnections = @()+ RemoteExecution = @()+ SuspiciousAuthentication = @()+ SMBAccess = @()+ }+ Summary = @{+ TotalIndicators = 0+ CriticalFindings = 0+ HighFindings = 0+ MediumFindings = 0+ }+ Recommendations = @()+ }++ $startDate = (Get-Date).AddDays(-$Days)+ }++ process {+ try {+ # 1. Check Network Connections for Lateral Movement+ if ($CheckNetworkConnections) {+ Write-Host "`n[1/4] Checking network connections..." -ForegroundColor Cyan++ try {+ # Check for established connections to internal IPs on suspicious ports+ $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue++ $suspiciousPorts = @{+ 445 = 'SMB'+ 135 = 'RPC'+ 139 = 'NetBIOS'+ 5985 = 'WinRM HTTP'+ 5986 = 'WinRM HTTPS'+ 3389 = 'RDP'+ }++ $foundCount = 0++ foreach ($conn in $connections) {+ if ($conn.RemotePort -in $suspiciousPorts.Keys) {+ $process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue++ # Skip if it's a standard system process in expected scenarios+ if ($process.Name -in @('svchost', 'System')) {+ continue+ }++ $indicator = [PSCustomObject]@{+ Type = 'NetworkConnection'+ Process = $process.Name+ ProcessId = $conn.OwningProcess+ LocalAddress = "$($conn.LocalAddress):$($conn.LocalPort)"+ RemoteAddress = "$($conn.RemoteAddress):$($conn.RemotePort)"+ Protocol = $suspiciousPorts[$conn.RemotePort]+ Severity = 'Medium'+ Description = "Connection to $($suspiciousPorts[$conn.RemotePort]) port from $($process.Name)"+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.Indicators.NetworkConnections += $indicator+ $results.Summary.MediumFindings+++ $foundCount++++ if ($foundCount -le 5) {+ Write-Host " [!] $($process.Name) -> $($conn.RemoteAddress):$($conn.RemotePort) [$($suspiciousPorts[$conn.RemotePort])]" -ForegroundColor Yellow+ }+ }+ }++ if ($foundCount -gt 5) {+ Write-Host " ... and $($foundCount - 5) more connections" -ForegroundColor Gray+ }++ if ($foundCount -eq 0) {+ Write-Host " No suspicious network connections detected" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking network connections: $_"+ }+ }++ # 2. Check Remote Execution Indicators+ if ($CheckRemoteExecution) {+ Write-Host "`n[2/4] Checking remote execution indicators..." -ForegroundColor Cyan++ try {+ # Check for PSRemoting activity (Event ID 4648 - Explicit credential logon)+ $remoteEvents = Get-WinEvent -FilterHashtable @{+ LogName = 'Security'+ ID = 4648+ StartTime = $startDate+ } -MaxEvents 100 -ErrorAction SilentlyContinue++ if ($remoteEvents) {+ $groupedEvents = $remoteEvents | Group-Object -Property {+ $_.Properties[5].Value+ } | Sort-Object Count -Descending++ foreach ($group in $groupedEvents | Select-Object -First 5) {+ $event = $group.Group[0]++ $indicator = [PSCustomObject]@{+ Type = 'RemoteExecution'+ Process = 'N/A'+ ProcessId = 'N/A'+ TargetServer = $event.Properties[5].Value+ Account = $event.Properties[1].Value+ Count = $group.Count+ Severity = if ($group.Count -gt 10) { 'High' } else { 'Medium' }+ Description = "Explicit credential logon to $($event.Properties[5].Value) - $($group.Count) times"+ Timestamp = $event.TimeCreated.ToString("yyyy-MM-dd HH:mm:ss")+ }++ $results.Indicators.RemoteExecution += $indicator++ if ($group.Count -gt 10) {+ $results.Summary.HighFindings+++ } else {+ $results.Summary.MediumFindings+++ }++ Write-Host " [!] Explicit credential logon: $($event.Properties[5].Value) ($($group.Count) times)" -ForegroundColor Yellow+ }+ }+ else {+ Write-Host " No remote execution indicators detected" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking remote execution: $_"+ }+ }++ # 3. Check Authentication Logs for Lateral Movement+ if ($CheckAuthentication) {+ Write-Host "`n[3/4] Checking authentication logs..." -ForegroundColor Cyan++ try {+ # Event ID 4624 - Successful logon (Type 3 = Network, Type 10 = RemoteInteractive/RDP)+ $logonEvents = Get-WinEvent -FilterHashtable @{+ LogName = 'Security'+ ID = 4624+ StartTime = $startDate+ } -MaxEvents 500 -ErrorAction SilentlyContinue++ if ($logonEvents) {+ # Filter for Type 3 (Network) and Type 10 (RemoteInteractive)+ $suspiciousLogons = $logonEvents | Where-Object {+ $logonType = $_.Properties[8].Value+ $logonType -in @(3, 10)+ }++ if ($suspiciousLogons) {+ # Group by source IP+ $groupedByIP = $suspiciousLogons | Group-Object -Property {+ $_.Properties[18].Value+ } | Where-Object { $_.Name -ne '-' -and $_.Name -ne '127.0.0.1' } |+ Sort-Object Count -Descending++ foreach ($group in $groupedByIP | Select-Object -First 5) {+ $event = $group.Group[0]+ $logonType = $event.Properties[8].Value+ $logonTypeName = switch ($logonType) {+ 3 { 'Network' }+ 10 { 'RemoteInteractive/RDP' }+ default { "Type $logonType" }+ }++ $indicator = [PSCustomObject]@{+ Type = 'SuspiciousAuthentication'+ Process = 'N/A'+ ProcessId = 'N/A'+ SourceIP = $group.Name+ Account = $event.Properties[5].Value+ LogonType = $logonTypeName+ Count = $group.Count+ Severity = if ($group.Count -gt 20) { 'High' } else { 'Medium' }+ Description = "$logonTypeName logon from $($group.Name) - $($group.Count) times"+ Timestamp = $event.TimeCreated.ToString("yyyy-MM-dd HH:mm:ss")+ }++ $results.Indicators.SuspiciousAuthentication += $indicator++ if ($group.Count -gt 20) {+ $results.Summary.HighFindings+++ } else {+ $results.Summary.MediumFindings+++ }++ Write-Host " [!] $logonTypeName from $($group.Name): $($group.Count) times" -ForegroundColor Yellow+ }+ }+ else {+ Write-Host " No suspicious authentication events detected" -ForegroundColor Green+ }+ }+ else {+ Write-Host " No authentication events found in specified period" -ForegroundColor Gray+ }+ }+ catch {+ Write-Warning "Error checking authentication logs: $_"+ }+ }++ # 4. Check SMB Share Access+ if ($CheckSMBShares) {+ Write-Host "`n[4/4] Checking SMB share access..." -ForegroundColor Cyan++ try {+ # Event ID 5140 - Network share object accessed+ $shareEvents = Get-WinEvent -FilterHashtable @{+ LogName = 'Security'+ ID = 5140+ StartTime = $startDate+ } -MaxEvents 200 -ErrorAction SilentlyContinue++ if ($shareEvents) {+ # Filter for non-admin shares+ $suspiciousShares = $shareEvents | Where-Object {+ $shareName = $_.Properties[3].Value+ $shareName -notmatch 'IPC\$|ADMIN\$|C\$'+ }++ if ($suspiciousShares) {+ $groupedShares = $suspiciousShares | Group-Object -Property {+ "$($_.Properties[1].Value)|$($_.Properties[3].Value)"+ } | Sort-Object Count -Descending++ foreach ($group in $groupedShares | Select-Object -First 5) {+ $parts = $group.Name -split '\|'+ $event = $group.Group[0]++ $indicator = [PSCustomObject]@{+ Type = 'SMBAccess'+ Process = 'N/A'+ ProcessId = 'N/A'+ Account = $parts[0]+ ShareName = $parts[1]+ Count = $group.Count+ Severity = 'Low'+ Description = "SMB share access: $($parts[1]) by $($parts[0]) - $($group.Count) times"+ Timestamp = $event.TimeCreated.ToString("yyyy-MM-dd HH:mm:ss")+ }++ $results.Indicators.SMBAccess += $indicator++ Write-Host " [!] Share: $($parts[1]) by $($parts[0]) ($($group.Count) times)" -ForegroundColor Yellow+ }+ }+ else {+ Write-Host " No suspicious SMB share access detected" -ForegroundColor Green+ }+ }+ else {+ Write-Host " No SMB share access events found" -ForegroundColor Gray+ }+ }+ catch {+ Write-Warning "Error checking SMB share access: $_"+ }+ }++ # Calculate summary+ $results.Summary.TotalIndicators =+ $results.Indicators.NetworkConnections.Count ++ $results.Indicators.RemoteExecution.Count ++ $results.Indicators.SuspiciousAuthentication.Count ++ $results.Indicators.SMBAccess.Count++ # Generate recommendations+ if ($results.Summary.TotalIndicators -gt 0) {+ if ($results.Summary.HighFindings -gt 0) {+ $results.Recommendations += "HIGH: Investigate high-severity lateral movement indicators immediately"+ }++ $results.Recommendations += "Review source IPs and accounts for suspicious activity"+ $results.Recommendations += "Check for compromised credentials"+ $results.Recommendations += "Enable enhanced logging (Sysmon, PowerShell logging)"+ $results.Recommendations += "Implement network segmentation"+ $results.Recommendations += "Deploy EDR solution for behavioral detection"++ if ($results.Indicators.RemoteExecution.Count -gt 0) {+ $results.Recommendations += "Review PSRemoting and WinRM usage policies"+ }++ if ($results.Indicators.SuspiciousAuthentication.Count -gt 0) {+ $results.Recommendations += "Investigate authentication patterns for pass-the-hash indicators"+ }+ }++ }+ catch {+ Write-Error "Error during lateral movement detection: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== SCAN COMPLETE ===" -ForegroundColor $(+ if ($results.Summary.HighFindings -gt 0) { 'Red' }+ elseif ($results.Summary.TotalIndicators -gt 0) { 'Yellow' }+ else { 'Green' }+ )++ Write-Host "`nDetection Summary:" -ForegroundColor Cyan+ Write-Host " Total Indicators: $($results.Summary.TotalIndicators)" -ForegroundColor White+ Write-Host " Critical: $($results.Summary.CriticalFindings)" -ForegroundColor Red+ Write-Host " High: $($results.Summary.HighFindings)" -ForegroundColor Yellow+ Write-Host " Medium: $($results.Summary.MediumFindings)" -ForegroundColor Yellow++ if ($results.Summary.TotalIndicators -gt 0) {+ Write-Host "`nIndicator Breakdown:" -ForegroundColor Cyan+ if ($results.Indicators.NetworkConnections.Count -gt 0) {+ Write-Host " Network Connections: $($results.Indicators.NetworkConnections.Count)" -ForegroundColor White+ }+ if ($results.Indicators.RemoteExecution.Count -gt 0) {+ Write-Host " Remote Execution: $($results.Indicators.RemoteExecution.Count)" -ForegroundColor White+ }+ if ($results.Indicators.SuspiciousAuthentication.Count -gt 0) {+ Write-Host " Suspicious Authentication: $($results.Indicators.SuspiciousAuthentication.Count)" -ForegroundColor White+ }+ if ($results.Indicators.SMBAccess.Count -gt 0) {+ Write-Host " SMB Access: $($results.Indicators.SMBAccess.Count)" -ForegroundColor White+ }+ }+ else {+ Write-Host "`nNo lateral movement indicators detected" -ForegroundColor Green+ }++ if ($results.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $results.Recommendations | Select-Object -Unique | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ return $results+ }+}\ No newline at end of filediff --git a/ThreatHunting/Find-LivingOffLand.ps1 b/ThreatHunting/Find-LivingOffLand.ps1new file mode 100644index 0000000..c4b31ec--- /dev/null+++ b/ThreatHunting/Find-LivingOffLand.ps1@@ -0,0 +1,474 @@+function Find-LivingOffLand {+ <#+ .SYNOPSIS+ Detects Living Off The Land (LOLBins) abuse+ .DESCRIPTION+ Identifies suspicious use of legitimate Windows binaries (LOLBins/LOLBas)+ that are commonly abused by attackers for execution, download, and evasion+ .PARAMETER CheckRunningProcesses+ Scan currently running processes+ .PARAMETER CheckRecentExecution+ Check recent process execution history+ .PARAMETER CheckScheduledTasks+ Check scheduled tasks for LOLBins+ .EXAMPLE+ Find-LivingOffLand -CheckRunningProcesses+ Find-LivingOffLand -CheckRunningProcesses -CheckRecentExecution -CheckScheduledTasks+ .OUTPUTS+ PSCustomObject with LOLBins detection results+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$CheckRunningProcesses,++ [Parameter()]+ [switch]$CheckRecentExecution,++ [Parameter()]+ [switch]$CheckScheduledTasks+ )++ begin {+ Write-Host "=== LIVING OFF THE LAND (LOLBins) DETECTION ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ if (-not ($CheckRunningProcesses -or $CheckRecentExecution -or $CheckScheduledTasks)) {+ $CheckRunningProcesses = $true+ Write-Host "No specific check selected - defaulting to CheckRunningProcesses" -ForegroundColor Yellow+ }++ $results = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ DetectedLOLBins = @()+ Summary = @{+ TotalDetections = 0+ CriticalFindings = 0+ HighFindings = 0+ MediumFindings = 0+ }+ Recommendations = @()+ }++ # LOLBins Database with suspicious usage patterns+ $lolbinsDB = @{+ 'certutil.exe' = @{+ Description = 'Certificate utility - can download files and encode/decode'+ SuspiciousPatterns = @(+ '-urlcache.*http',+ '-decode',+ '-encode',+ 'split.*http'+ )+ Severity = 'High'+ }+ 'bitsadmin.exe' = @{+ Description = 'Background Intelligent Transfer Service - can download files'+ SuspiciousPatterns = @(+ '/transfer',+ '/download',+ '/addfile'+ )+ Severity = 'High'+ }+ 'mshta.exe' = @{+ Description = 'Microsoft HTML Application host - executes HTA/scripts'+ SuspiciousPatterns = @(+ 'http',+ 'javascript:',+ 'vbscript:',+ '\.hta'+ )+ Severity = 'Critical'+ }+ 'regsvr32.exe' = @{+ Description = 'Register Server - can execute scriptlets'+ SuspiciousPatterns = @(+ '/u /s /i:http',+ '/i:http',+ '\.sct',+ 'scrobj.dll'+ )+ Severity = 'Critical'+ }+ 'rundll32.exe' = @{+ Description = 'Run DLL - can execute DLL functions'+ SuspiciousPatterns = @(+ 'javascript:',+ 'http',+ 'mshtml',+ 'url\.dll.*OpenURL',+ 'advpack\.dll.*LaunchINFSection'+ )+ Severity = 'High'+ }+ 'msiexec.exe' = @{+ Description = 'Windows Installer - can download and execute MSI'+ SuspiciousPatterns = @(+ '/i.*http',+ '/quiet.*http',+ '/qn.*http'+ )+ Severity = 'High'+ }+ 'wmic.exe' = @{+ Description = 'Windows Management Instrumentation - can execute commands'+ SuspiciousPatterns = @(+ 'process call create',+ 'os get',+ '/node:',+ '/format:.*http'+ )+ Severity = 'High'+ }+ 'cscript.exe' = @{+ Description = 'Windows Script Host - executes scripts'+ SuspiciousPatterns = @(+ '\.vbs.*http',+ '\.js.*http',+ '//e:jscript'+ )+ Severity = 'Medium'+ }+ 'wscript.exe' = @{+ Description = 'Windows Script Host - executes scripts'+ SuspiciousPatterns = @(+ '\.vbs.*http',+ '\.js.*http'+ )+ Severity = 'Medium'+ }+ 'regasm.exe' = @{+ Description = 'Assembly Registration Tool - can execute code'+ SuspiciousPatterns = @(+ '/u',+ '\.dll'+ )+ Severity = 'Medium'+ }+ 'regsvcs.exe' = @{+ Description = '.NET Services Installation Tool - can execute code'+ SuspiciousPatterns = @(+ '/u',+ '\.dll'+ )+ Severity = 'Medium'+ }+ 'installutil.exe' = @{+ Description = '.NET Installer Tool - can execute code'+ SuspiciousPatterns = @(+ '/logfile=',+ '/logtoconsole=false',+ '\.dll'+ )+ Severity = 'Medium'+ }+ 'odbcconf.exe' = @{+ Description = 'ODBC Configuration - can execute DLLs'+ SuspiciousPatterns = @(+ '/a.*regsvr'+ )+ Severity = 'Medium'+ }+ 'mavinject.exe' = @{+ Description = 'Windows process injector'+ SuspiciousPatterns = @(+ '/injectrunning'+ )+ Severity = 'Critical'+ }+ 'forfiles.exe' = @{+ Description = 'Execute commands on files - can run arbitrary commands'+ SuspiciousPatterns = @(+ '/c',+ 'cmd'+ )+ Severity = 'Medium'+ }+ }+ }++ process {+ try {+ # 1. Check Running Processes+ if ($CheckRunningProcesses) {+ Write-Host "`n[1/3] Scanning running processes..." -ForegroundColor Cyan++ try {+ $processes = Get-CimInstance Win32_Process |+ Where-Object { $_.CommandLine -ne $null } |+ Select-Object Name, ProcessId, ExecutablePath, CommandLine++ foreach ($process in $processes) {+ $processName = $process.Name.ToLower()++ if ($lolbinsDB.ContainsKey($processName)) {+ $lolbin = $lolbinsDB[$processName]+ $commandLine = $process.CommandLine++ # Check for suspicious patterns+ $matchedPatterns = @()+ foreach ($pattern in $lolbin.SuspiciousPatterns) {+ if ($commandLine -match $pattern) {+ $matchedPatterns += $pattern+ }+ }++ if ($matchedPatterns.Count -gt 0) {+ $detection = [PSCustomObject]@{+ DetectionType = 'RunningProcess'+ Binary = $processName+ ProcessId = $process.ProcessId+ Description = $lolbin.Description+ CommandLine = if ($commandLine.Length -gt 300) { $commandLine.Substring(0, 300) + "..." } else { $commandLine }+ MatchedPatterns = $matchedPatterns -join ', '+ Severity = $lolbin.Severity+ Path = $process.ExecutablePath+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.DetectedLOLBins += $detection++ switch ($lolbin.Severity) {+ 'Critical' { $results.Summary.CriticalFindings++ }+ 'High' { $results.Summary.HighFindings++ }+ 'Medium' { $results.Summary.MediumFindings++ }+ }++ Write-Host " [!] Detected: $processName (PID: $($process.ProcessId))" -ForegroundColor $(+ if ($lolbin.Severity -eq 'Critical') { 'Red' }+ elseif ($lolbin.Severity -eq 'High') { 'Red' }+ else { 'Yellow' }+ )+ Write-Host " Severity: $($lolbin.Severity)" -ForegroundColor Gray+ Write-Host " Pattern: $($matchedPatterns -join ', ')" -ForegroundColor Gray+ }+ }+ }++ if ($results.DetectedLOLBins.Count -eq 0) {+ Write-Host " No suspicious LOLBins detected in running processes" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking running processes: $_"+ }+ }++ # 2. Check Recent Execution (Prefetch)+ if ($CheckRecentExecution) {+ Write-Host "`n[2/3] Checking recent execution history..." -ForegroundColor Cyan++ try {+ # Check prefetch folder for LOLBins execution+ $prefetchPath = "$env:SystemRoot\Prefetch"++ if (Test-Path $prefetchPath) {+ $prefetchFiles = Get-ChildItem -Path $prefetchPath -Filter "*.pf" -ErrorAction SilentlyContinue |+ Sort-Object LastWriteTime -Descending |+ Select-Object -First 100++ $foundCount = 0++ foreach ($file in $prefetchFiles) {+ $fileName = $file.Name.ToLower()++ foreach ($lolbin in $lolbinsDB.Keys) {+ $binaryName = $lolbin.Replace('.exe', '')++ if ($fileName -like "$binaryName-*") {+ $detection = [PSCustomObject]@{+ DetectionType = 'RecentExecution'+ Binary = $lolbin+ ProcessId = 'N/A'+ Description = $lolbinsDB[$lolbin].Description+ CommandLine = "N/A (Prefetch evidence only)"+ MatchedPatterns = "Execution detected via Prefetch"+ Severity = 'Low'+ Path = $file.FullName+ Timestamp = $file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")+ }++ $results.DetectedLOLBins += $detection+ $foundCount++++ Write-Host " [!] Recent execution: $lolbin" -ForegroundColor Yellow+ Write-Host " Last executed: $($file.LastWriteTime)" -ForegroundColor Gray+ break+ }+ }+ }++ if ($foundCount -eq 0) {+ Write-Host " No LOLBins detected in recent execution history" -ForegroundColor Green+ }+ }+ else {+ Write-Host " Prefetch folder not accessible" -ForegroundColor Gray+ }+ }+ catch {+ Write-Warning "Error checking recent execution: $_"+ }+ }++ # 3. Check Scheduled Tasks+ if ($CheckScheduledTasks) {+ Write-Host "`n[3/3] Checking scheduled tasks..." -ForegroundColor Cyan++ try {+ $tasks = Get-ScheduledTask | Where-Object { $_.State -ne 'Disabled' }+ $foundCount = 0++ foreach ($task in $tasks) {+ foreach ($action in $task.Actions) {+ if ($action.PSObject.Properties.Name -contains 'Execute' -and $action.Execute) {+ # Safe executable name extraction - FIX: Handle environment variables and illegal characters+ $executable = $null+ try {+ # Try to expand environment variables+ $expandedPath = [Environment]::ExpandEnvironmentVariables($action.Execute)+ $executable = [System.IO.Path]::GetFileName($expandedPath).ToLower()+ }+ catch {+ # If path parsing fails, try regex extraction+ if ($action.Execute -match '([^\\/:*?"<>|]+\.exe)') {+ $executable = $matches[1].ToLower()+ }+ }++ if (-not $executable) {+ continue+ }++ if ($lolbinsDB.ContainsKey($executable)) {+ $lolbin = $lolbinsDB[$executable]+ $arguments = if ($action.Arguments) { $action.Arguments } else { "" }++ # Check for suspicious patterns+ $matchedPatterns = @()+ foreach ($pattern in $lolbin.SuspiciousPatterns) {+ if ($arguments -match $pattern) {+ $matchedPatterns += $pattern+ }+ }++ if ($matchedPatterns.Count -gt 0) {+ $detection = [PSCustomObject]@{+ DetectionType = 'ScheduledTask'+ Binary = $executable+ ProcessId = 'N/A'+ Description = $lolbin.Description+ CommandLine = "$($action.Execute) $arguments"+ MatchedPatterns = $matchedPatterns -join ', '+ Severity = $lolbin.Severity+ Path = "Scheduled Task: $($task.TaskName)"+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.DetectedLOLBins += $detection+ $foundCount++++ switch ($lolbin.Severity) {+ 'Critical' { $results.Summary.CriticalFindings++ }+ 'High' { $results.Summary.HighFindings++ }+ 'Medium' { $results.Summary.MediumFindings++ }+ }++ Write-Host " [!] Detected in task: $($task.TaskName)" -ForegroundColor Red+ Write-Host " Binary: $executable" -ForegroundColor Gray+ Write-Host " Severity: $($lolbin.Severity)" -ForegroundColor Gray+ }+ }+ }+ }+ }++ if ($foundCount -eq 0) {+ Write-Host " No suspicious LOLBins detected in scheduled tasks" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking scheduled tasks: $_"+ }+ }++ # Calculate total detections+ $results.Summary.TotalDetections = $results.DetectedLOLBins.Count++ # Generate recommendations+ if ($results.Summary.TotalDetections -gt 0) {+ if ($results.Summary.CriticalFindings -gt 0) {+ $results.Recommendations += "CRITICAL: Investigate critical LOLBins detections immediately"+ $results.Recommendations += "Isolate affected systems from network"+ }++ $results.Recommendations += "Review command lines and execution context"+ $results.Recommendations += "Check for lateral movement indicators"+ $results.Recommendations += "Enable Sysmon or enhanced process logging"+ $results.Recommendations += "Implement application whitelisting (AppLocker/WDAC)"+ $results.Recommendations += "Monitor LOLBins usage with behavioral analytics"+ }++ }+ catch {+ Write-Error "Error during LOLBins detection: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== SCAN COMPLETE ===" -ForegroundColor $(+ if ($results.Summary.CriticalFindings -gt 0) { 'Red' }+ elseif ($results.Summary.HighFindings -gt 0) { 'Yellow' }+ else { 'Green' }+ )++ Write-Host "`nDetection Summary:" -ForegroundColor Cyan+ Write-Host " Total Detections: $($results.Summary.TotalDetections)" -ForegroundColor White+ Write-Host " Critical: $($results.Summary.CriticalFindings)" -ForegroundColor Red+ Write-Host " High: $($results.Summary.HighFindings)" -ForegroundColor Yellow+ Write-Host " Medium: $($results.Summary.MediumFindings)" -ForegroundColor Yellow++ if ($results.DetectedLOLBins.Count -gt 0) {+ Write-Host "`nDetected LOLBins:" -ForegroundColor Cyan+ $results.DetectedLOLBins |+ Group-Object Binary |+ Sort-Object Count -Descending |+ ForEach-Object {+ Write-Host " $($_.Name): $($_.Count) detection(s)" -ForegroundColor White+ }++ Write-Host "`nTop Detections by Severity:" -ForegroundColor Cyan+ $results.DetectedLOLBins |+ Sort-Object {+ switch ($_.Severity) {+ 'Critical' { 1 }+ 'High' { 2 }+ 'Medium' { 3 }+ 'Low' { 4 }+ }+ } |+ Select-Object -First 5 |+ ForEach-Object {+ Write-Host " [$($_.Severity)] $($_.Binary) - $($_.DetectionType)" -ForegroundColor White+ }+ }+ else {+ Write-Host "`nNo suspicious LOLBins activity detected" -ForegroundColor Green+ }++ if ($results.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $results.Recommendations | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ Write-Host "`nLOLBAS Project: https://lolbas-project.github.io/" -ForegroundColor Gray++ return $results+ }+}\ No newline at end of filediff --git a/ThreatHunting/Get-MITREAttackMapping.ps1 b/ThreatHunting/Get-MITREAttackMapping.ps1new file mode 100644index 0000000..5fc04f0--- /dev/null+++ b/ThreatHunting/Get-MITREAttackMapping.ps1@@ -0,0 +1,606 @@+function Get-MITREAttackMapping {+ <#+ .SYNOPSIS+ Maps detected activities to MITRE ATT&CK framework techniques+ .DESCRIPTION+ Analyzes system activities and maps them to MITRE ATT&CK tactics and techniques.+ Provides detailed technique information with detection methods and recommendations.+ .PARAMETER CheckProcesses+ Analyze running processes for MITRE techniques+ .PARAMETER CheckRegistry+ Analyze registry for persistence techniques+ .PARAMETER CheckNetworkActivity+ Analyze network activity for C2 techniques+ .PARAMETER CheckEventLogs+ Analyze security event logs for technique indicators+ .PARAMETER FullAnalysis+ Run all checks+ .EXAMPLE+ Get-MITREAttackMapping -CheckProcesses -CheckRegistry+ Get-MITREAttackMapping -FullAnalysis+ .OUTPUTS+ PSCustomObject with MITRE ATT&CK technique mappings+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$CheckProcesses,++ [Parameter()]+ [switch]$CheckRegistry,++ [Parameter()]+ [switch]$CheckNetworkActivity,++ [Parameter()]+ [switch]$CheckEventLogs,++ [Parameter()]+ [switch]$FullAnalysis+ )++ begin {+ Write-Host "=== MITRE ATT&CK TECHNIQUE MAPPING ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ if ($FullAnalysis) {+ $CheckProcesses = $true+ $CheckRegistry = $true+ $CheckNetworkActivity = $true+ $CheckEventLogs = $true+ Write-Host "Full Analysis Mode: Enabled" -ForegroundColor Yellow+ }++ $results = [PSCustomObject]@{+ AnalysisDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ DetectedTechniques = @()+ TacticBreakdown = @{+ InitialAccess = @()+ Execution = @()+ Persistence = @()+ PrivilegeEscalation = @()+ DefenseEvasion = @()+ CredentialAccess = @()+ Discovery = @()+ LateralMovement = @()+ Collection = @()+ CommandAndControl = @()+ Exfiltration = @()+ Impact = @()+ }+ Summary = @{+ TotalTechniques = 0+ TacticsCovered = 0+ RiskScore = 0+ }+ Recommendations = @()+ }++ # Legitimate process whitelist+ $legitimateProcesses = @(+ 'svchost', 'explorer', 'dwm', 'lsass', 'csrss', 'smss', 'winlogon',+ 'services', 'spoolsv', 'taskhost', 'taskhostw', 'RuntimeBroker',+ 'SearchIndexer', 'Microsoft.Photos', 'SystemSettings', 'ShellExperienceHost',+ 'sihost', 'fontdrvhost', 'conhost', 'dllhost', 'SearchApp',+ 'StartMenuExperienceHost', 'TextInputHost', 'MoUsoCoreWorker',+ 'SgrmBroker', 'AutoBootInstallService', 'erlsrv', 'gamingservices',+ 'Xbox', 'Windows', 'Microsoft'+ )++ # MITRE ATT&CK Technique Database - IMPROVED with context-aware detection+ $mitreDB = @{+ 'T1059.001' = @{+ Name = 'Command and Scripting Interpreter: PowerShell'+ Tactic = 'Execution'+ Description = 'Adversaries abuse PowerShell to execute commands'+ ProcessName = 'powershell.exe|pwsh.exe'+ SuspiciousArgs = @('-enc', '-encodedcommand', '-w hidden', '-windowstyle hidden', '-nop', '-noprofile', '-exec bypass', '-executionpolicy bypass')+ RequiresCommandLine = $true+ Severity = 'High'+ }+ 'T1059.003' = @{+ Name = 'Command and Scripting Interpreter: Windows Command Shell'+ Tactic = 'Execution'+ Description = 'Adversaries abuse cmd.exe to execute commands'+ ProcessName = 'cmd.exe'+ SuspiciousArgs = @('/c whoami', '/c net user', '/c net localgroup', '/c tasklist', '/c ipconfig /all')+ RequiresCommandLine = $true+ Severity = 'Medium'+ }+ 'T1547.001' = @{+ Name = 'Boot or Logon Autostart Execution: Registry Run Keys'+ Tactic = 'Persistence'+ Description = 'Adversaries achieve persistence via registry run keys'+ DetectionType = 'Registry'+ RegistryPaths = @(+ 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run',+ 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'+ )+ Severity = 'High'+ }+ 'T1053.005' = @{+ Name = 'Scheduled Task/Job: Scheduled Task'+ Tactic = 'Persistence'+ Description = 'Adversaries schedule tasks for persistence'+ ProcessName = 'schtasks.exe'+ SuspiciousArgs = @('/create', 'Register-ScheduledTask', 'New-ScheduledTask')+ RequiresCommandLine = $true+ Severity = 'High'+ }+ 'T1543.003' = @{+ Name = 'Create or Modify System Process: Windows Service'+ Tactic = 'Persistence'+ Description = 'Adversaries create/modify services for persistence'+ ProcessName = 'sc.exe'+ SuspiciousArgs = @('create', 'config', 'New-Service')+ RequiresCommandLine = $true+ Severity = 'High'+ }+ 'T1055' = @{+ Name = 'Process Injection'+ Tactic = 'DefenseEvasion'+ Description = 'Adversaries inject code into processes'+ SuspiciousArgs = @('VirtualAllocEx', 'WriteProcessMemory', 'CreateRemoteThread', 'QueueUserAPC')+ RequiresCommandLine = $true+ Severity = 'Critical'+ }+ 'T1027' = @{+ Name = 'Obfuscated Files or Information'+ Tactic = 'DefenseEvasion'+ Description = 'Adversaries obfuscate files or information'+ SuspiciousArgs = @('-enc [A-Za-z0-9+/=]{50,}', 'FromBase64String', '[Convert]::FromBase64')+ RequiresCommandLine = $true+ Severity = 'High'+ }+ 'T1070.001' = @{+ Name = 'Indicator Removal: Clear Windows Event Logs'+ Tactic = 'DefenseEvasion'+ Description = 'Adversaries clear event logs to hide activity'+ ProcessName = 'wevtutil.exe'+ SuspiciousArgs = @('clear-log', 'cl', 'Clear-EventLog')+ RequiresCommandLine = $true+ Severity = 'High'+ }+ 'T1003.001' = @{+ Name = 'OS Credential Dumping: LSASS Memory'+ Tactic = 'CredentialAccess'+ Description = 'Adversaries dump credentials from LSASS'+ ProcessName = 'procdump|procdump64|mimikatz'+ SuspiciousArgs = @('lsass', 'sekurlsa', 'logonpasswords')+ RequiresCommandLine = $false+ Severity = 'Critical'+ }+ 'T1003.002' = @{+ Name = 'OS Credential Dumping: Security Account Manager'+ Tactic = 'CredentialAccess'+ Description = 'Adversaries access SAM database for credentials'+ ProcessName = 'reg.exe'+ SuspiciousArgs = @('save.*HKLM\\SAM', 'save.*HKLM\\SYSTEM', 'save.*HKLM\\SECURITY')+ RequiresCommandLine = $true+ Severity = 'Critical'+ }+ 'T1087.001' = @{+ Name = 'Account Discovery: Local Account'+ Tactic = 'Discovery'+ Description = 'Adversaries enumerate local accounts'+ ProcessName = 'net.exe|net1.exe'+ SuspiciousArgs = @('user', 'localgroup', 'accounts')+ RequiresCommandLine = $true+ Severity = 'Medium'+ }+ 'T1087.002' = @{+ Name = 'Account Discovery: Domain Account'+ Tactic = 'Discovery'+ Description = 'Adversaries enumerate domain accounts'+ ProcessName = 'net.exe|dsquery.exe'+ SuspiciousArgs = @('user /domain', 'group /domain', 'Get-ADUser')+ RequiresCommandLine = $true+ Severity = 'Medium'+ }+ 'T1082' = @{+ Name = 'System Information Discovery'+ Tactic = 'Discovery'+ Description = 'Adversaries gather system information'+ ProcessName = 'systeminfo.exe|wmic.exe'+ SuspiciousArgs = @('computersystem', 'os', 'qfe')+ RequiresCommandLine = $true+ Severity = 'Low'+ }+ 'T1071.001' = @{+ Name = 'Application Layer Protocol: Web Protocols'+ Tactic = 'CommandAndControl'+ Description = 'Adversaries use HTTP/HTTPS for C2'+ ProcessName = 'powershell.exe|pwsh.exe'+ SuspiciousArgs = @('Invoke-WebRequest.*IEX', 'WebClient.*DownloadString', 'Net.WebClient.*DownloadFile')+ RequiresCommandLine = $true+ Severity = 'High'+ }+ 'T1571' = @{+ Name = 'Non-Standard Port'+ Tactic = 'CommandAndControl'+ Description = 'Adversaries use non-standard ports for C2'+ DetectionType = 'Network'+ Severity = 'Medium'+ }+ 'T1486' = @{+ Name = 'Data Encrypted for Impact'+ Tactic = 'Impact'+ Description = 'Adversaries encrypt data (ransomware)'+ SuspiciousArgs = @('\.encrypted', '\.locked', '\.crypt', 'ransom', 'YOUR_FILES')+ RequiresCommandLine = $true+ Severity = 'Critical'+ }+ }+ }++ process {+ try {+ # 1. Check Processes for Technique Indicators+ if ($CheckProcesses) {+ Write-Host "`n[1/4] Analyzing running processes..." -ForegroundColor Cyan++ try {+ # Get processes with command line using WMI+ $processes = Get-CimInstance Win32_Process | Select-Object Name, ProcessId, ExecutablePath, CommandLine++ foreach ($process in $processes) {+ # Skip whitelisted legitimate processes+ $isLegitimate = $false+ foreach ($legitProc in $legitimateProcesses) {+ if ($process.Name -like "*$legitProc*") {+ $isLegitimate = $true+ break+ }+ }++ if ($isLegitimate) {+ continue+ }++ foreach ($techId in $mitreDB.Keys) {+ $technique = $mitreDB[$techId]++ # Skip registry/network-only techniques+ if ($technique.ContainsKey('DetectionType') -and $technique.DetectionType -in @('Registry', 'Network')) {+ continue+}++ # Skip if no process name defined+ if (-not $technique.ContainsKey('ProcessName')) {+ continue+ }++ $matched = $false+ $matchedIndicator = ""++ # Check if process name matches+ if ($process.Name -match $technique.ProcessName) {+ # If technique requires command line analysis+ if ($technique.RequiresCommandLine) {+ if ($process.CommandLine) {+ foreach ($arg in $technique.SuspiciousArgs) {+ if ($process.CommandLine -match $arg) {+ $matched = $true+ $matchedIndicator = $arg+ break+ }+ }+ }+ }+ else {+ # Process name alone is suspicious (e.g., mimikatz)+ $matched = $true+ $matchedIndicator = "Suspicious process name"+ }+ }++ if ($matched) {+ $detection = [PSCustomObject]@{+ TechniqueID = $techId+ TechniqueName = $technique.Name+ Tactic = $technique.Tactic+ Severity = $technique.Severity+ DetectionSource = 'Process'+ Evidence = "Process: $($process.Name) (PID: $($process.ProcessId)) - Indicator: $matchedIndicator"+ CommandLine = if ($process.CommandLine) { $process.CommandLine.Substring(0, [Math]::Min(200, $process.CommandLine.Length)) } else { "N/A" }+ Description = $technique.Description+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.DetectedTechniques += $detection+ $results.TacticBreakdown[$technique.Tactic] += $detection++ Write-Host " [!] Detected: $techId - $($technique.Name)" -ForegroundColor Yellow+ Write-Host " Evidence: $matchedIndicator" -ForegroundColor Gray+ }+ }+ }++ if ($results.DetectedTechniques.Count -eq 0) {+ Write-Host " No suspicious process activity detected" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error analyzing processes: $_"+ }+ }++ # 2. Check Registry for Persistence Techniques+ if ($CheckRegistry) {+ Write-Host "`n[2/4] Analyzing registry keys..." -ForegroundColor Cyan++ try {+ $runKeys = @(+ 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run',+ 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run',+ 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce',+ 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce'+ )++ $suspiciousEntries = @()++ foreach ($key in $runKeys) {+ if (Test-Path $key) {+ $values = Get-ItemProperty -Path $key -ErrorAction SilentlyContinue++ if ($values) {+ # Count non-PS properties+ $entryCount = 0+ foreach ($prop in $values.PSObject.Properties) {+ if ($prop.Name -notmatch "^PS") {+ $entryCount++++ # Check for suspicious patterns+ $value = $prop.Value+ if ($value -match "temp|appdata\\local\\temp|public|programdata|script|\.vbs|\.js|\.bat|http|download") {+ $suspiciousEntries += " - $($prop.Name): $value"+ }+ }+ }++ if ($entryCount -gt 0) {+ # T1547.001 - Registry Run Keys detected+ $detection = [PSCustomObject]@{+ TechniqueID = 'T1547.001'+ TechniqueName = $mitreDB['T1547.001'].Name+ Tactic = 'Persistence'+ Severity = 'Medium' # Medium unless suspicious+ DetectionSource = 'Registry'+ Evidence = "Registry Run Key found: $key ($entryCount entries)"+ CommandLine = "N/A"+ Description = $mitreDB['T1547.001'].Description+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ # Check if already detected for this key+ $alreadyDetected = $results.DetectedTechniques | Where-Object {+ $_.TechniqueID -eq 'T1547.001' -and $_.Evidence -match [regex]::Escape($key)+ }++ if (-not $alreadyDetected) {+ $results.DetectedTechniques += $detection+ $results.TacticBreakdown.Persistence += $detection+ Write-Host " [!] Detected: T1547.001 - Registry Run Keys ($entryCount entries in $key)" -ForegroundColor Yellow+ }+ }+ }+ }+ }++ if ($suspiciousEntries.Count -gt 0) {+ Write-Host " Suspicious entries found:" -ForegroundColor Red+ $suspiciousEntries | Select-Object -First 3 | ForEach-Object {+ Write-Host $_ -ForegroundColor Red+ }+ }+ }+ catch {+ Write-Warning "Error analyzing registry: $_"+ }+ }++ # 3. Check Network Activity for C2 Techniques+ if ($CheckNetworkActivity) {+ Write-Host "`n[3/4] Analyzing network activity..." -ForegroundColor Cyan++ try {+ $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue++ $suspiciousConnections = 0++ foreach ($conn in $connections) {+ # Check for non-standard ports (T1571)+ $nonStandardPorts = @(4444, 5555, 31337, 1337, 6666, 7777)++ if ($conn.RemotePort -in $nonStandardPorts) {+ $process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue++ # Skip if it's a known legitimate process+ $isLegitimate = $false+ foreach ($legitProc in $legitimateProcesses) {+ if ($process.Name -like "*$legitProc*") {+ $isLegitimate = $true+ break+ }+ }++ if (-not $isLegitimate) {+ $detection = [PSCustomObject]@{+ TechniqueID = 'T1571'+ TechniqueName = $mitreDB['T1571'].Name+ Tactic = 'CommandAndControl'+ Severity = 'High'+ DetectionSource = 'Network'+ Evidence = "Non-standard port $($conn.RemotePort) used by $($process.Name) -> $($conn.RemoteAddress)"+ CommandLine = "N/A"+ Description = $mitreDB['T1571'].Description+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.DetectedTechniques += $detection+ $results.TacticBreakdown.CommandAndControl += $detection+ $suspiciousConnections++++ Write-Host " [!] Detected: T1571 - Non-Standard Port ($($conn.RemotePort))" -ForegroundColor Yellow+ }+ }+ }++ if ($suspiciousConnections -eq 0) {+ Write-Host " No suspicious network activity detected" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error analyzing network activity: $_"+ }+ }++ # 4. Check Event Logs for Technique Indicators+ if ($CheckEventLogs) {+ Write-Host "`n[4/4] Analyzing security event logs..." -ForegroundColor Cyan++ try {+ # Check for log clearing (T1070.001) - High severity event+ $logCleared = Get-WinEvent -FilterHashtable @{+ LogName = 'Security'+ ID = 1102+ } -MaxEvents 10 -ErrorAction SilentlyContinue++ if ($logCleared) {+ foreach ($event in $logCleared) {+ $detection = [PSCustomObject]@{+ TechniqueID = 'T1070.001'+ TechniqueName = $mitreDB['T1070.001'].Name+ Tactic = 'DefenseEvasion'+ Severity = 'High'+ DetectionSource = 'EventLog'+ Evidence = "Security log cleared at $($event.TimeCreated)"+ CommandLine = "N/A"+ Description = $mitreDB['T1070.001'].Description+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.DetectedTechniques += $detection+ $results.TacticBreakdown.DefenseEvasion += $detection+ }++ Write-Host " [!] Detected: T1070.001 - Event Log Clearing ($($logCleared.Count) events)" -ForegroundColor Red+ }+ else {+ Write-Host " No suspicious event log activity detected" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error analyzing event logs: $_"+ }+ }++ # Calculate summary statistics+ $uniqueTechniques = @($results.DetectedTechniques | Select-Object -Unique -Property TechniqueID)+ $results.Summary.TotalTechniques = $uniqueTechniques.Count++ # Count tactics with detections+ $tacticCount = 0+ foreach ($tactic in $results.TacticBreakdown.Keys) {+ if ($results.TacticBreakdown[$tactic].Count -gt 0) {+ $tacticCount+++ }+ }+ $results.Summary.TacticsCovered = $tacticCount++ # Calculate risk score+ foreach ($technique in $results.DetectedTechniques) {+ $riskScore = switch ($technique.Severity) {+ 'Critical' { 10 }+ 'High' { 7 }+ 'Medium' { 4 }+ 'Low' { 2 }+ default { 1 }+ }+ $results.Summary.RiskScore += $riskScore+ }++ # Generate recommendations+ if ($results.Summary.TotalTechniques -gt 0) {+ $results.Recommendations += "Review detected MITRE ATT&CK techniques immediately"+ $results.Recommendations += "Investigate command lines and process chains"+ $results.Recommendations += "Enable advanced audit logging for covered tactics"++ # Severity-based recommendations+ $criticalCount = @($results.DetectedTechniques | Where-Object { $_.Severity -eq 'Critical' }).Count+ if ($criticalCount -gt 0) {+ $results.Recommendations += "CRITICAL: $criticalCount critical techniques detected - immediate response required"+ }+ }++ # Tactic-specific recommendations+ if ($results.TacticBreakdown.Persistence.Count -gt 0) {+ $results.Recommendations += "Review and harden persistence mechanisms"+ }++ if ($results.TacticBreakdown.CredentialAccess.Count -gt 0) {+ $results.Recommendations += "CRITICAL: Investigate credential access attempts immediately"+ }++ if ($results.TacticBreakdown.DefenseEvasion.Count -gt 0) {+ $results.Recommendations += "Strengthen security controls and monitoring"+ }++ }+ catch {+ Write-Error "Error during MITRE ATT&CK mapping: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== ANALYSIS COMPLETE ===" -ForegroundColor Green++ Write-Host "`nMITRE ATT&CK Coverage:" -ForegroundColor Cyan+ Write-Host " Unique Techniques Detected: $($results.Summary.TotalTechniques)" -ForegroundColor White+ Write-Host " Tactics Covered: $($results.Summary.TacticsCovered)/12" -ForegroundColor White+ Write-Host " Risk Score: $($results.Summary.RiskScore)" -ForegroundColor $(+ if ($results.Summary.RiskScore -ge 50) { 'Red' }+ elseif ($results.Summary.RiskScore -ge 20) { 'Yellow' }+ else { 'Green' }+ )++ if ($results.Summary.TotalTechniques -gt 0) {+ Write-Host "`nDetected Techniques by Tactic:" -ForegroundColor Cyan++ foreach ($tactic in $results.TacticBreakdown.Keys | Sort-Object) {+ $count = $results.TacticBreakdown[$tactic].Count+ if ($count -gt 0) {+ Write-Host " $tactic : $count technique(s)" -ForegroundColor Yellow+ }+ }++ Write-Host "`nTop Detected Techniques:" -ForegroundColor Cyan+ $results.DetectedTechniques |+ Group-Object TechniqueID |+ Sort-Object Count -Descending |+ Select-Object -First 5 |+ ForEach-Object {+ $tech = $_.Group[0]+ Write-Host " $($tech.TechniqueID) - $($tech.TechniqueName) [$($tech.Severity)]" -ForegroundColor White+ }+ }+ else {+ Write-Host "`nNo suspicious MITRE ATT&CK techniques detected" -ForegroundColor Green+ }++ if ($results.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $results.Recommendations | Select-Object -Unique | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ Write-Host "`nMITRE ATT&CK Navigator:" -ForegroundColor Cyan+ Write-Host " https://mitre-attack.github.io/attack-navigator/" -ForegroundColor Gray++ return $results+ }+}\ No newline at end of filediff --git a/ThreatHunting/Get-ThreatIntelligence.ps1 b/ThreatHunting/Get-ThreatIntelligence.ps1new file mode 100644index 0000000..d67e2ab--- /dev/null+++ b/ThreatHunting/Get-ThreatIntelligence.ps1@@ -0,0 +1,488 @@+function Get-ThreatIntelligence {+ <#+ .SYNOPSIS+ Matches system artifacts against threat intelligence indicators+ .DESCRIPTION+ Checks running processes, network connections, files, and registry against+ known Indicators of Compromise (IOCs) from threat intelligence feeds+ .PARAMETER CheckProcesses+ Check running processes against IOCs+ .PARAMETER CheckNetwork+ Check network connections against IOCs+ .PARAMETER CheckFiles+ Check files against IOC patterns+ .PARAMETER CheckRegistry+ Check registry against IOCs+ .PARAMETER IOCFile+ Path to custom IOC file (JSON format)+ .EXAMPLE+ Get-ThreatIntelligence -CheckProcesses -CheckNetwork+ Get-ThreatIntelligence -CheckProcesses -CheckNetwork -CheckFiles -IOCFile "C:\iocs.json"+ .OUTPUTS+ PSCustomObject with IOC match results+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$CheckProcesses,++ [Parameter()]+ [switch]$CheckNetwork,++ [Parameter()]+ [switch]$CheckFiles,++ [Parameter()]+ [switch]$CheckRegistry,++ [Parameter()]+ [string]$IOCFile+ )++ begin {+ Write-Host "=== THREAT INTELLIGENCE IOC MATCHING ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ if (-not ($CheckProcesses -or $CheckNetwork -or $CheckFiles -or $CheckRegistry)) {+ $CheckProcesses = $true+ $CheckNetwork = $true+ Write-Host "No specific check selected - enabling default checks" -ForegroundColor Yellow+ }++ $results = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ Matches = @{+ ProcessIOCs = @()+ NetworkIOCs = @()+ FileIOCs = @()+ RegistryIOCs = @()+ }+ Summary = @{+ TotalMatches = 0+ CriticalMatches = 0+ HighMatches = 0+ MediumMatches = 0+ }+ Recommendations = @()+ }++ # Built-in IOC Database (Common malware/threat indicators)+ $iocDatabase = @{+ MaliciousProcesses = @{+ 'mimikatz.exe' = @{ Severity = 'Critical'; Description = 'Credential dumping tool' }+ 'procdump.exe' = @{ Severity = 'High'; Description = 'Memory dumping tool (can be legitimate)' }+ 'rubeus.exe' = @{ Severity = 'Critical'; Description = 'Kerberos attack tool' }+ 'sharphound.exe' = @{ Severity = 'High'; Description = 'AD enumeration tool (BloodHound)' }+ 'covenant.exe' = @{ Severity = 'Critical'; Description = 'C2 framework' }+ 'psexec.exe' = @{ Severity = 'Medium'; Description = 'Remote execution tool (can be legitimate)' }+ 'paexec.exe' = @{ Severity = 'High'; Description = 'PSExec alternative' }+ 'lazagne.exe' = @{ Severity = 'Critical'; Description = 'Password recovery tool' }+ }++ MaliciousIPs = @{+ '192.0.2.1' = @{ Severity = 'Critical'; Description = 'Known C2 server (example)' }+ '198.51.100.1' = @{ Severity = 'High'; Description = 'Known malware distribution (example)' }+ }++ MaliciousHashes = @{+ # Example SHA256 hashes (these are placeholders)+ '44d88612fea8a8f36de82e1278abb02f' = @{ Severity = 'Critical'; Description = 'Known malware hash' }+ }++ SuspiciousPatterns = @{+ ProcessCommandLine = @(+ @{ Pattern = 'mimikatz'; Severity = 'Critical'; Description = 'Mimikatz execution detected' }+ @{ Pattern = 'Invoke-Mimikatz'; Severity = 'Critical'; Description = 'PowerShell Mimikatz' }+ @{ Pattern = 'sekurlsa::logonpasswords'; Severity = 'Critical'; Description = 'Credential dumping command' }+ @{ Pattern = 'procdump.*lsass'; Severity = 'Critical'; Description = 'LSASS memory dump' }+ @{ Pattern = 'IEX.*New-Object.*Net.WebClient.*DownloadString'; Severity = 'High'; Description = 'PowerShell download cradle' }+ @{ Pattern = '\[Convert\]::FromBase64String'; Severity = 'Medium'; Description = 'Base64 decoding (potential obfuscation)' }+ )++ FilePaths = @(+ @{ Pattern = 'C:\\Windows\\Temp\\.*\.exe'; Severity = 'High'; Description = 'Executable in Windows Temp' }+ @{ Pattern = 'C:\\Users\\Public\\.*\.exe'; Severity = 'High'; Description = 'Executable in Public folder' }+ @{ Pattern = 'C:\\ProgramData\\.*\.ps1'; Severity = 'Medium'; Description = 'PowerShell script in ProgramData' }+ )+ }+ }++ # Load custom IOCs if provided+ if ($IOCFile -and (Test-Path $IOCFile)) {+ Write-Host "Loading custom IOCs from: $IOCFile" -ForegroundColor Yellow+ try {+ $customIOCs = Get-Content $IOCFile -Raw | ConvertFrom-Json+ Write-Host "Custom IOCs loaded successfully" -ForegroundColor Green+ }+ catch {+ Write-Warning "Failed to load custom IOC file: $_"+ }+ }+ }++ process {+ try {+ # 1. Check Processes against IOCs+ if ($CheckProcesses) {+ Write-Host "`n[1/4] Checking processes against IOCs..." -ForegroundColor Cyan++ try {+ $processes = Get-CimInstance Win32_Process |+ Where-Object { $_.CommandLine -ne $null } |+ Select-Object Name, ProcessId, ExecutablePath, CommandLine++ $foundCount = 0++ foreach ($process in $processes) {+ # Check process name against malicious process list+ if ($iocDatabase.MaliciousProcesses.ContainsKey($process.Name.ToLower())) {+ $ioc = $iocDatabase.MaliciousProcesses[$process.Name.ToLower()]++ $match = [PSCustomObject]@{+ Type = 'Process'+ IOCType = 'MaliciousProcess'+ Indicator = $process.Name+ ProcessId = $process.ProcessId+ Path = $process.ExecutablePath+ CommandLine = $process.CommandLine+ Severity = $ioc.Severity+ Description = $ioc.Description+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.Matches.ProcessIOCs += $match+ $foundCount++++ switch ($ioc.Severity) {+ 'Critical' { $results.Summary.CriticalMatches++ }+ 'High' { $results.Summary.HighMatches++ }+ 'Medium' { $results.Summary.MediumMatches++ }+ }++ Write-Host " [!] MATCH: $($process.Name) [PID: $($process.ProcessId)]" -ForegroundColor Red+ Write-Host " Severity: $($ioc.Severity) - $($ioc.Description)" -ForegroundColor Red+ }++ # Check command line patterns+ if ($process.CommandLine) {+ foreach ($pattern in $iocDatabase.SuspiciousPatterns.ProcessCommandLine) {+ if ($process.CommandLine -match $pattern.Pattern) {+ $match = [PSCustomObject]@{+ Type = 'Process'+ IOCType = 'SuspiciousCommandLine'+ Indicator = $pattern.Pattern+ ProcessId = $process.ProcessId+ ProcessName = $process.Name+ CommandLine = if ($process.CommandLine.Length -gt 200) {+ $process.CommandLine.Substring(0, 200) + "..."+ } else {+ $process.CommandLine+ }+ Severity = $pattern.Severity+ Description = $pattern.Description+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.Matches.ProcessIOCs += $match+ $foundCount++++ switch ($pattern.Severity) {+ 'Critical' { $results.Summary.CriticalMatches++ }+ 'High' { $results.Summary.HighMatches++ }+ 'Medium' { $results.Summary.MediumMatches++ }+ }++ Write-Host " [!] MATCH: Pattern '$($pattern.Pattern)' in $($process.Name)" -ForegroundColor Red+ break+ }+ }+ }+ }++ if ($foundCount -eq 0) {+ Write-Host " No process IOC matches found" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking processes: $_"+ }+ }++ # 2. Check Network Connections against IOCs+ if ($CheckNetwork) {+ Write-Host "`n[2/4] Checking network connections against IOCs..." -ForegroundColor Cyan++ try {+ $connections = Get-NetTCPConnection -State Established -ErrorAction SilentlyContinue++ $foundCount = 0++ foreach ($conn in $connections) {+ # Check against malicious IPs+ if ($iocDatabase.MaliciousIPs.ContainsKey($conn.RemoteAddress)) {+ $ioc = $iocDatabase.MaliciousIPs[$conn.RemoteAddress]+ $process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue++ $match = [PSCustomObject]@{+ Type = 'Network'+ IOCType = 'MaliciousIP'+ Indicator = $conn.RemoteAddress+ ProcessName = $process.Name+ ProcessId = $conn.OwningProcess+ LocalAddress = "$($conn.LocalAddress):$($conn.LocalPort)"+ RemoteAddress = "$($conn.RemoteAddress):$($conn.RemotePort)"+ Severity = $ioc.Severity+ Description = $ioc.Description+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.Matches.NetworkIOCs += $match+ $foundCount++++ switch ($ioc.Severity) {+ 'Critical' { $results.Summary.CriticalMatches++ }+ 'High' { $results.Summary.HighMatches++ }+ 'Medium' { $results.Summary.MediumMatches++ }+ }++ Write-Host " [!] MATCH: Malicious IP $($conn.RemoteAddress) via $($process.Name)" -ForegroundColor Red+ }+ }++ if ($foundCount -eq 0) {+ Write-Host " No network IOC matches found" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking network: $_"+ }+ }++ # 3. Check Files against IOCs+ if ($CheckFiles) {+ Write-Host "`n[3/4] Checking files against IOCs..." -ForegroundColor Cyan++ try {+ # Check recent files in suspicious locations+ $suspiciousLocations = @(+ "$env:TEMP",+ "C:\Windows\Temp",+ "C:\Users\Public",+ "C:\ProgramData"+ )++ $foundCount = 0++ foreach ($location in $suspiciousLocations) {+ if (Test-Path $location) {+ $recentFiles = Get-ChildItem -Path $location -File -Recurse -ErrorAction SilentlyContinue -Depth 2 |+ Where-Object { $_.CreationTime -gt (Get-Date).AddDays(-7) -and $_.Extension -match '\.(exe|dll|ps1|bat|vbs|js)$' } |+ Select-Object -First 20++ foreach ($file in $recentFiles) {+ # Check against file path patterns+ foreach ($pattern in $iocDatabase.SuspiciousPatterns.FilePaths) {+ if ($file.FullName -match $pattern.Pattern) {+ $match = [PSCustomObject]@{+ Type = 'File'+ IOCType = 'SuspiciousFilePath'+ Indicator = $pattern.Pattern+ FilePath = $file.FullName+ FileName = $file.Name+ Size = $file.Length+ Created = $file.CreationTime.ToString("yyyy-MM-dd HH:mm:ss")+ Severity = $pattern.Severity+ Description = $pattern.Description+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.Matches.FileIOCs += $match+ $foundCount++++ switch ($pattern.Severity) {+ 'Critical' { $results.Summary.CriticalMatches++ }+ 'High' { $results.Summary.HighMatches++ }+ 'Medium' { $results.Summary.MediumMatches++ }+ }++ Write-Host " [!] MATCH: $($file.Name) in suspicious location" -ForegroundColor Yellow+ break+ }+ }+ }+ }+ }++ if ($foundCount -eq 0) {+ Write-Host " No file IOC matches found" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking files: $_"+ }+ }++ # 4. Check Registry against IOCs+ if ($CheckRegistry) {+ Write-Host "`n[4/4] Checking registry against IOCs..." -ForegroundColor Cyan++ try {+ # Check common persistence locations+ $persistenceKeys = @(+ 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run',+ 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'+ )++ $foundCount = 0++ foreach ($key in $persistenceKeys) {+ if (Test-Path $key) {+ $values = Get-ItemProperty -Path $key -ErrorAction SilentlyContinue++ foreach ($prop in $values.PSObject.Properties) {+ if ($prop.Name -match '^PS') { continue }++ $value = $prop.Value++ # Check for suspicious patterns in registry values+ if ($value -match 'powershell.*-enc|cmd.*http|wscript.*http|mshta.*http') {+ $match = [PSCustomObject]@{+ Type = 'Registry'+ IOCType = 'SuspiciousRegistryValue'+ Indicator = 'Suspicious command pattern in registry'+ RegistryKey = $key+ ValueName = $prop.Name+ ValueData = if ($value.Length -gt 200) { $value.Substring(0, 200) + "..." } else { $value }+ Severity = 'High'+ Description = 'Potentially malicious command in registry autorun'+ Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ $results.Matches.RegistryIOCs += $match+ $results.Summary.HighMatches+++ $foundCount++++ Write-Host " [!] MATCH: Suspicious pattern in $($prop.Name)" -ForegroundColor Red+ }+ }+ }+ }++ if ($foundCount -eq 0) {+ Write-Host " No registry IOC matches found" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error checking registry: $_"+ }+ }++ # Calculate summary+ $results.Summary.TotalMatches =+ $results.Matches.ProcessIOCs.Count ++ $results.Matches.NetworkIOCs.Count ++ $results.Matches.FileIOCs.Count ++ $results.Matches.RegistryIOCs.Count++ # Generate recommendations+ if ($results.Summary.TotalMatches -gt 0) {+ if ($results.Summary.CriticalMatches -gt 0) {+ $results.Recommendations += "CRITICAL: $($results.Summary.CriticalMatches) critical IOC match(es) detected - immediate incident response required"+ $results.Recommendations += "Isolate affected systems from network"+ $results.Recommendations += "Collect forensic evidence before remediation"+ }++ if ($results.Summary.HighMatches -gt 0) {+ $results.Recommendations += "HIGH: $($results.Summary.HighMatches) high-severity IOC match(es) require investigation"+ }++ $results.Recommendations += "Review all matched IOCs and their context"+ $results.Recommendations += "Check for additional indicators of compromise"+ $results.Recommendations += "Update threat intelligence feeds regularly"+ $results.Recommendations += "Consider implementing automated IOC scanning"++ if ($results.Matches.ProcessIOCs.Count -gt 0) {+ $results.Recommendations += "Terminate suspicious processes and investigate their origin"+ }++ if ($results.Matches.NetworkIOCs.Count -gt 0) {+ $results.Recommendations += "Block malicious IP addresses at firewall level"+ }+ }++ }+ catch {+ Write-Error "Error during threat intelligence matching: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== SCAN COMPLETE ===" -ForegroundColor $(+ if ($results.Summary.CriticalMatches -gt 0) { 'Red' }+ elseif ($results.Summary.HighMatches -gt 0) { 'Yellow' }+ else { 'Green' }+ )++ Write-Host "`nIOC Match Summary:" -ForegroundColor Cyan+ Write-Host " Total Matches: $($results.Summary.TotalMatches)" -ForegroundColor White+ Write-Host " Critical: $($results.Summary.CriticalMatches)" -ForegroundColor Red+ Write-Host " High: $($results.Summary.HighMatches)" -ForegroundColor Yellow+ Write-Host " Medium: $($results.Summary.MediumMatches)" -ForegroundColor Yellow++ if ($results.Summary.TotalMatches -gt 0) {+ Write-Host "`nMatch Breakdown:" -ForegroundColor Cyan+ if ($results.Matches.ProcessIOCs.Count -gt 0) {+ Write-Host " Process IOCs: $($results.Matches.ProcessIOCs.Count)" -ForegroundColor White+ }+ if ($results.Matches.NetworkIOCs.Count -gt 0) {+ Write-Host " Network IOCs: $($results.Matches.NetworkIOCs.Count)" -ForegroundColor White+ }+ if ($results.Matches.FileIOCs.Count -gt 0) {+ Write-Host " File IOCs: $($results.Matches.FileIOCs.Count)" -ForegroundColor White+ }+ if ($results.Matches.RegistryIOCs.Count -gt 0) {+ Write-Host " Registry IOCs: $($results.Matches.RegistryIOCs.Count)" -ForegroundColor White+ }++ Write-Host "`nTop Matches by Severity:" -ForegroundColor Cyan+ $allMatches = @()+ $allMatches += $results.Matches.ProcessIOCs+ $allMatches += $results.Matches.NetworkIOCs+ $allMatches += $results.Matches.FileIOCs+ $allMatches += $results.Matches.RegistryIOCs++ $allMatches |+ Sort-Object {+ switch ($_.Severity) {+ 'Critical' { 1 }+ 'High' { 2 }+ 'Medium' { 3 }+ }+ } |+ Select-Object -First 5 |+ ForEach-Object {+ Write-Host " [$($_.Severity)] $($_.IOCType): $($_.Indicator)" -ForegroundColor White+ }+ }+ else {+ Write-Host "`nNo IOC matches detected - system appears clean" -ForegroundColor Green+ }++ if ($results.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $results.Recommendations | Select-Object -Unique | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ Write-Host "`nThreat Intelligence Sources:" -ForegroundColor Cyan+ Write-Host " - MITRE ATT&CK: https://attack.mitre.org/" -ForegroundColor Gray+ Write-Host " - AlienVault OTX: https://otx.alienvault.com/" -ForegroundColor Gray+ Write-Host " - VirusTotal: https://www.virustotal.com/" -ForegroundColor Gray++ return $results+ }+}\ No newline at end of filediff --git a/Vulnerability/Find-EOLSoftware.ps1 b/Vulnerability/Find-EOLSoftware.ps1new file mode 100644index 0000000..108c713--- /dev/null+++ b/Vulnerability/Find-EOLSoftware.ps1@@ -0,0 +1,607 @@+function Find-EOLSoftware {+ <#+ .SYNOPSIS+ Detects end-of-life (EOL) and unsupported software installations+ .DESCRIPTION+ Scans installed software and identifies applications that have reached+ end-of-life, are no longer supported, or are critically outdated.+ Provides security risk assessment and upgrade recommendations.+ .PARAMETER IncludeExpiringSoon+ Include software expiring within specified months (default: 6)+ .PARAMETER ExpiringMonths+ Number of months to check for expiring support (default: 6)+ .PARAMETER OutputPath+ Path to save EOL software report+ .PARAMETER Format+ Report format: HTML, JSON, CSV, or All+ .EXAMPLE+ Find-EOLSoftware+ Find-EOLSoftware -IncludeExpiringSoon -ExpiringMonths 12 -OutputPath "C:\Reports"+ .OUTPUTS+ PSCustomObject with EOL software findings+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$IncludeExpiringSoon,++ [Parameter()]+ [int]$ExpiringMonths = 6,++ [Parameter()]+ [string]$OutputPath,++ [Parameter()]+ [ValidateSet('HTML', 'JSON', 'CSV', 'All')]+ [string]$Format = 'HTML'+ )++ begin {+ Write-Host "=== END-OF-LIFE SOFTWARE DETECTION ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow+ Write-Host "Include Expiring Soon: $(if($IncludeExpiringSoon){'Yes'}else{'No'})" -ForegroundColor Yellow+ if ($IncludeExpiringSoon) {+ Write-Host "Expiring Within: $ExpiringMonths months" -ForegroundColor Yellow+ }++ $findings = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ TotalSoftware = 0+ EOLSoftware = @()+ ExpiringSoon = @()+ Summary = @{+ TotalEOL = 0+ CriticalRisk = 0+ HighRisk = 0+ MediumRisk = 0+ TotalExpiring = 0+ }+ Recommendations = @()+ }++ # Known EOL Software Database+ $eolDatabase = @{+ 'Windows 7' = @{+ EOLDate = [DateTime]'2020-01-14'+ Severity = 'Critical'+ Replacement = 'Windows 10/11'+ Notes = 'No security updates since January 2020'+ }+ 'Windows 8' = @{+ EOLDate = [DateTime]'2016-01-12'+ Severity = 'Critical'+ Replacement = 'Windows 10/11'+ Notes = 'Extended support ended'+ }+ 'Windows Server 2008' = @{+ EOLDate = [DateTime]'2020-01-14'+ Severity = 'Critical'+ Replacement = 'Windows Server 2019/2022'+ Notes = 'Critical security risk - no patches'+ }+ 'Windows Server 2012' = @{+ EOLDate = [DateTime]'2023-10-10'+ Severity = 'Critical'+ Replacement = 'Windows Server 2019/2022'+ Notes = 'Extended support ended October 2023'+ }+ 'Office 2010' = @{+ EOLDate = [DateTime]'2020-10-13'+ Severity = 'High'+ Replacement = 'Microsoft 365 / Office 2021'+ Notes = 'No security updates available'+ }+ 'Office 2013' = @{+ EOLDate = [DateTime]'2023-04-11'+ Severity = 'High'+ Replacement = 'Microsoft 365 / Office 2021'+ Notes = 'Extended support ended April 2023'+ }+ 'Office 2016' = @{+ EOLDate = [DateTime]'2025-10-14'+ Severity = 'Medium'+ Replacement = 'Microsoft 365 / Office 2021'+ Notes = 'Approaching end of support'+ }+ 'SQL Server 2008' = @{+ EOLDate = [DateTime]'2019-07-09'+ Severity = 'Critical'+ Replacement = 'SQL Server 2019/2022'+ Notes = 'Critical database security risk'+ }+ 'SQL Server 2012' = @{+ EOLDate = [DateTime]'2022-07-12'+ Severity = 'Critical'+ Replacement = 'SQL Server 2019/2022'+ Notes = 'Extended support ended'+ }+ 'SQL Server 2014' = @{+ EOLDate = [DateTime]'2024-07-09'+ Severity = 'High'+ Replacement = 'SQL Server 2019/2022'+ Notes = 'Extended support ending soon'+ }+ 'Internet Explorer' = @{+ EOLDate = [DateTime]'2022-06-15'+ Severity = 'Critical'+ Replacement = 'Microsoft Edge'+ Notes = 'Disabled by Microsoft - security risk'+ }+ 'Adobe Flash Player' = @{+ EOLDate = [DateTime]'2020-12-31'+ Severity = 'Critical'+ Replacement = 'Modern web standards (HTML5)'+ Notes = 'Blocked by all major browsers'+ }+ 'Java SE 7' = @{+ EOLDate = [DateTime]'2015-04-14'+ Severity = 'Critical'+ Replacement = 'Java SE 17 LTS or 21 LTS'+ Notes = 'Multiple critical vulnerabilities'+ }+ 'Java SE 8' = @{+ EOLDate = [DateTime]'2030-12-31'+ Severity = 'Low'+ Replacement = 'Java SE 17 LTS or 21 LTS'+ Notes = 'Public updates ended (commercial available)'+ }+ 'Python 2' = @{+ EOLDate = [DateTime]'2020-01-01'+ Severity = 'High'+ Replacement = 'Python 3.9+'+ Notes = 'No bug fixes or security updates'+ }+ 'PHP 7.2' = @{+ EOLDate = [DateTime]'2020-11-30'+ Severity = 'High'+ Replacement = 'PHP 8.1+'+ Notes = 'Security support ended'+ }+ 'PHP 7.3' = @{+ EOLDate = [DateTime]'2021-12-06'+ Severity = 'High'+ Replacement = 'PHP 8.1+'+ Notes = 'Security support ended'+ }+ 'PHP 7.4' = @{+ EOLDate = [DateTime]'2022-11-28'+ Severity = 'High'+ Replacement = 'PHP 8.1+'+ Notes = 'Security support ended'+ }+ 'Node.js 10' = @{+ EOLDate = [DateTime]'2021-04-30'+ Severity = 'High'+ Replacement = 'Node.js 18 LTS or 20 LTS'+ Notes = 'No security updates'+ }+ 'Node.js 12' = @{+ EOLDate = [DateTime]'2022-04-30'+ Severity = 'High'+ Replacement = 'Node.js 18 LTS or 20 LTS'+ Notes = 'No security updates'+ }+ '.NET Framework 4.5' = @{+ EOLDate = [DateTime]'2016-01-12'+ Severity = 'High'+ Replacement = '.NET 6/7/8'+ Notes = 'Upgrade to supported version'+ }+ }+ }++ process {+ try {+ # 1. SCAN INSTALLED SOFTWARE+ Write-Host "`n[1/3] Scanning installed software..." -ForegroundColor Cyan++ $registryPaths = @(+ 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*',+ 'HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'+ )++ $installedSoftware = @()+ foreach ($path in $registryPaths) {+ $items = Get-ItemProperty $path -ErrorAction SilentlyContinue+ if ($items) {+ foreach ($item in $items) {+ if ($null -ne $item.PSObject.Properties['DisplayName'] -and+ $null -ne $item.DisplayName -and+ $item.DisplayName -ne '') {++ $displayVersion = if ($null -ne $item.PSObject.Properties['DisplayVersion']) {+ $item.DisplayVersion+ } else {+ 'Unknown'+ }++ $publisher = if ($null -ne $item.PSObject.Properties['Publisher']) {+ $item.Publisher+ } else {+ 'Unknown'+ }++ $installedSoftware += [PSCustomObject]@{+ DisplayName = $item.DisplayName+ DisplayVersion = $displayVersion+ Publisher = $publisher+ }+ }+ }+ }+ }++ $installedSoftware = $installedSoftware | Sort-Object DisplayName -Unique+ $findings.TotalSoftware = $installedSoftware.Count++ Write-Host " Found $($installedSoftware.Count) installed applications" -ForegroundColor Gray++ # 2. CHECK AGAINST EOL DATABASE+ Write-Host "`n[2/3] Checking against EOL database..." -ForegroundColor Cyan++ $currentDate = Get-Date+ $expiringThreshold = $currentDate.AddMonths($ExpiringMonths)++ foreach ($software in $installedSoftware) {+ foreach ($eolName in $eolDatabase.Keys) {+ if ($software.DisplayName -like "*$eolName*") {+ $eolInfo = $eolDatabase[$eolName]++ # Check if EOL or expiring soon+ $isEOL = $currentDate -gt $eolInfo.EOLDate+ $isExpiringSoon = ($eolInfo.EOLDate -gt $currentDate) -and+ ($eolInfo.EOLDate -le $expiringThreshold)++ if ($isEOL) {+ $daysSinceEOL = [Math]::Round(($currentDate - $eolInfo.EOLDate).TotalDays)++ $eolSoftware = [PSCustomObject]@{+ Name = $software.DisplayName+ Version = $software.DisplayVersion+ Publisher = $software.Publisher+ EOLDate = $eolInfo.EOLDate.ToString('yyyy-MM-dd')+ DaysSinceEOL = $daysSinceEOL+ Severity = $eolInfo.Severity+ Replacement = $eolInfo.Replacement+ Notes = $eolInfo.Notes+ Status = 'End-of-Life'+ }++ $findings.EOLSoftware += $eolSoftware+ $findings.Summary.TotalEOL++++ # Update risk counters+ switch ($eolInfo.Severity) {+ 'Critical' { $findings.Summary.CriticalRisk++ }+ 'High' { $findings.Summary.HighRisk++ }+ 'Medium' { $findings.Summary.MediumRisk++ }+ }++ $color = switch ($eolInfo.Severity) {+ 'Critical' { 'Red' }+ 'High' { 'Yellow' }+ default { 'Gray' }+ }++ Write-Host " [!] EOL: $($software.DisplayName) - $($eolInfo.Severity) risk ($daysSinceEOL days past EOL)" -ForegroundColor $color+ }+ elseif ($isExpiringSoon -and $IncludeExpiringSoon) {+ $daysUntilEOL = [Math]::Round(($eolInfo.EOLDate - $currentDate).TotalDays)++ $expiringSoftware = [PSCustomObject]@{+ Name = $software.DisplayName+ Version = $software.DisplayVersion+ Publisher = $software.Publisher+ EOLDate = $eolInfo.EOLDate.ToString('yyyy-MM-dd')+ DaysUntilEOL = $daysUntilEOL+ Severity = $eolInfo.Severity+ Replacement = $eolInfo.Replacement+ Notes = $eolInfo.Notes+ Status = 'Expiring Soon'+ }++ $findings.ExpiringSoon += $expiringSoftware+ $findings.Summary.TotalExpiring++++ Write-Host " [*] Expiring: $($software.DisplayName) - EOL in $daysUntilEOL days" -ForegroundColor Yellow+ }+ }+ }+ }++ Write-Host " Found $($findings.Summary.TotalEOL) EOL software" -ForegroundColor $(+ if ($findings.Summary.TotalEOL -gt 0) { 'Red' } else { 'Green' }+ )++ if ($IncludeExpiringSoon) {+ Write-Host " Found $($findings.Summary.TotalExpiring) expiring soon" -ForegroundColor $(+ if ($findings.Summary.TotalExpiring -gt 0) { 'Yellow' } else { 'Green' }+ )+ }++ # 3. GENERATE RECOMMENDATIONS+ Write-Host "`n[3/3] Generating recommendations..." -ForegroundColor Cyan++ if ($findings.Summary.CriticalRisk -gt 0) {+ $findings.Recommendations += "CRITICAL: Remove or upgrade $($findings.Summary.CriticalRisk) critically outdated software immediately"+ }++ if ($findings.Summary.HighRisk -gt 0) {+ $findings.Recommendations += "HIGH: Plan migration for $($findings.Summary.HighRisk) high-risk EOL software within 30 days"+ }++ if ($findings.Summary.MediumRisk -gt 0) {+ $findings.Recommendations += "MEDIUM: Schedule upgrades for $($findings.Summary.MediumRisk) medium-risk software"+ }++ if ($findings.Summary.TotalExpiring -gt 0) {+ $findings.Recommendations += "Plan upgrades for $($findings.Summary.TotalExpiring) software approaching EOL"+ }++ if ($findings.Summary.TotalEOL -eq 0 -and $findings.Summary.TotalExpiring -eq 0) {+ $findings.Recommendations += "No EOL or expiring software detected - maintain current update schedule"+ }++ $findings.Recommendations += "Implement software lifecycle management policy"+ $findings.Recommendations += "Subscribe to vendor EOL announcements"+ $findings.Recommendations += "Conduct quarterly EOL software audits"+ $findings.Recommendations += "Block installation of EOL software via Group Policy"++ # 4. EXPORT REPORTS+ if ($OutputPath) {+ Write-Host "`n[*] Exporting EOL software reports..." -ForegroundColor Cyan++ if (-not (Test-Path $OutputPath)) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ }++ $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"+ $reportName = "EOLSoftware_$timestamp"++ # Export JSON+ if ($Format -in @('JSON', 'All')) {+ $jsonPath = Join-Path $OutputPath "$reportName.json"+ $findings | ConvertTo-Json -Depth 10 | Out-File $jsonPath -Encoding UTF8+ Write-Host " JSON report saved: $jsonPath" -ForegroundColor Green+ }++ # Export CSV+ if ($Format -in @('CSV', 'All')) {+ $csvPath = Join-Path $OutputPath "$reportName.csv"+ $allFindings = $findings.EOLSoftware + $findings.ExpiringSoon+ $allFindings | Export-Csv $csvPath -NoTypeInformation+ Write-Host " CSV report saved: $csvPath" -ForegroundColor Green+ }++ # Export HTML+ if ($Format -in @('HTML', 'All')) {+ $htmlPath = Join-Path $OutputPath "$reportName.html"+ $html = Generate-EOLSoftwareHTML -Findings $findings+ $html | Out-File $htmlPath -Encoding UTF8+ Write-Host " HTML report saved: $htmlPath" -ForegroundColor Green+ }+ }++ }+ catch {+ Write-Error "Error during EOL software detection: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== EOL SOFTWARE DETECTION COMPLETE ===" -ForegroundColor $(+ if ($findings.Summary.CriticalRisk -gt 0) { 'Red' }+ elseif ($findings.Summary.HighRisk -gt 0) { 'Yellow' }+ else { 'Green' }+ )++ Write-Host "`nSummary:" -ForegroundColor Cyan+ Write-Host " Total Software Scanned: $($findings.TotalSoftware)" -ForegroundColor White+ Write-Host " EOL Software: $($findings.Summary.TotalEOL)" -ForegroundColor $(+ if ($findings.Summary.TotalEOL -gt 0) { 'Red' } else { 'Green' }+ )+ Write-Host " Critical Risk: $($findings.Summary.CriticalRisk)" -ForegroundColor $(+ if ($findings.Summary.CriticalRisk -gt 0) { 'Red' } else { 'Gray' }+ )+ Write-Host " High Risk: $($findings.Summary.HighRisk)" -ForegroundColor $(+ if ($findings.Summary.HighRisk -gt 0) { 'Yellow' } else { 'Gray' }+ )+ Write-Host " Medium Risk: $($findings.Summary.MediumRisk)" -ForegroundColor Gray++ if ($IncludeExpiringSoon) {+ Write-Host " Expiring Soon: $($findings.Summary.TotalExpiring)" -ForegroundColor $(+ if ($findings.Summary.TotalExpiring -gt 0) { 'Yellow' } else { 'Gray' }+ )+ }++ if ($findings.EOLSoftware.Count -gt 0) {+ Write-Host "`nEOL Software Detected:" -ForegroundColor Cyan+ $findings.EOLSoftware |+ Sort-Object {+ switch ($_.Severity) {+ 'Critical' { 0 }+ 'High' { 1 }+ 'Medium' { 2 }+ default { 3 }+ }+ } |+ Select-Object -First 10 |+ ForEach-Object {+ $color = switch ($_.Severity) {+ 'Critical' { 'Red' }+ 'High' { 'Yellow' }+ default { 'Gray' }+ }+ Write-Host " [$($_.Severity)] $($_.Name) - Replace with: $($_.Replacement)" -ForegroundColor $color+ }+ }++ if ($findings.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $findings.Recommendations | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ return $findings+ }+}++# Helper function to generate HTML report+function Generate-EOLSoftwareHTML {+ param($Findings)++ $riskColor = if($Findings.Summary.CriticalRisk -gt 0){'critical'}+ elseif($Findings.Summary.HighRisk -gt 0){'high'}+ else{'safe'}++ $html = @"+<!DOCTYPE html>+<html>+<head>+ <title>EOL Software Report - $($Findings.ComputerName)</title>+ <style>+ body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }+ .container { max-width: 1200px; margin: 0 auto; background: white; padding: 30px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }+ h1 { color: #2c3e50; border-bottom: 3px solid #e74c3c; padding-bottom: 10px; }+ h2 { color: #34495e; margin-top: 30px; }+ .summary { background: #ecf0f1; padding: 20px; border-radius: 5px; margin: 20px 0; }+ .metric { display: inline-block; margin: 10px 20px 10px 0; }+ .metric-label { font-weight: bold; color: #7f8c8d; }+ .metric-value { font-size: 24px; font-weight: bold; }+ .critical { color: #e74c3c; }+ .high { color: #e67e22; }+ .medium { color: #f39c12; }+ .low { color: #95a5a6; }+ .safe { color: #27ae60; }+ table { width: 100%; border-collapse: collapse; margin: 20px 0; }+ th { background: #e74c3c; color: white; padding: 12px; text-align: left; }+ td { padding: 10px; border-bottom: 1px solid #ddd; }+ tr:hover { background: #f8f9fa; }+ .severity-badge { padding: 4px 8px; border-radius: 3px; color: white; font-weight: bold; }+ .severity-critical { background: #e74c3c; }+ .severity-high { background: #e67e22; }+ .severity-medium { background: #f39c12; }+ .footer { margin-top: 40px; padding-top: 20px; border-top: 1px solid #ddd; color: #7f8c8d; font-size: 12px; }+ .no-eol { color: #27ae60; font-weight: bold; font-size: 16px; padding: 20px; text-align: center; }+ </style>+</head>+<body>+ <div class="container">+ <h1>End-of-Life Software Report</h1>+ <p><strong>Computer:</strong> $($Findings.ComputerName) | <strong>Scan Date:</strong> $($Findings.ScanDate)</p>++ <div class="summary">+ <h2>Summary</h2>+ <div class="metric">+ <div class="metric-label">Total Software</div>+ <div class="metric-value">$($Findings.TotalSoftware)</div>+ </div>+ <div class="metric">+ <div class="metric-label">EOL Software</div>+ <div class="metric-value $(if($Findings.Summary.TotalEOL -gt 0){'critical'}else{'safe'})">+ $($Findings.Summary.TotalEOL)+ </div>+ </div>+ <div class="metric">+ <div class="metric-label">Critical Risk</div>+ <div class="metric-value critical">$($Findings.Summary.CriticalRisk)</div>+ </div>+ <div class="metric">+ <div class="metric-label">High Risk</div>+ <div class="metric-value high">$($Findings.Summary.HighRisk)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Expiring Soon</div>+ <div class="metric-value medium">$($Findings.Summary.TotalExpiring)</div>+ </div>+ </div>++ <h2>End-of-Life Software</h2>+"@++ if ($Findings.EOLSoftware.Count -gt 0) {+ $html += @"+ <table>+ <tr>+ <th>Severity</th>+ <th>Software</th>+ <th>Version</th>+ <th>EOL Date</th>+ <th>Days Since EOL</th>+ <th>Replacement</th>+ <th>Notes</th>+ </tr>+"@++ foreach ($software in ($Findings.EOLSoftware | Sort-Object {+ switch ($_.Severity) {+ 'Critical' { 0 }+ 'High' { 1 }+ 'Medium' { 2 }+ default { 3 }+ }+ }, DaysSinceEOL -Descending)) {+ $severityClass = "severity-$($software.Severity.ToLower())"+ $name = $software.Name -replace '<', '<' -replace '>', '>'+ $replacement = $software.Replacement -replace '<', '<' -replace '>', '>'+ $notes = $software.Notes -replace '<', '<' -replace '>', '>'++ $html += @"+ <tr>+ <td><span class="severity-badge $severityClass">$($software.Severity)</span></td>+ <td><strong>$name</strong></td>+ <td>$($software.Version)</td>+ <td>$($software.EOLDate)</td>+ <td>$($software.DaysSinceEOL)</td>+ <td>$replacement</td>+ <td>$notes</td>+ </tr>+"@+ }++ $html += " </table>`n"+ }+ else {+ $html += " <p class=`"no-eol`">No end-of-life software detected</p>`n"+ }++ if ($Findings.ExpiringSoon.Count -gt 0) {+ $html += " `n <h2>Software Expiring Soon</h2>`n <table>`n"+ $html += " <tr><th>Software</th><th>EOL Date</th><th>Days Until EOL</th><th>Replacement</th></tr>`n"++ foreach ($software in ($Findings.ExpiringSoon | Sort-Object DaysUntilEOL)) {+ $name = $software.Name -replace '<', '<' -replace '>', '>'+ $replacement = $software.Replacement -replace '<', '<' -replace '>', '>'++ $html += " <tr><td>$name</td><td>$($software.EOLDate)</td><td>$($software.DaysUntilEOL)</td><td>$replacement</td></tr>`n"+ }++ $html += " </table>`n"+ }++ $html += " `n <h2>Recommendations</h2>`n <ul>`n"++ foreach ($rec in $Findings.Recommendations) {+ $recEscaped = $rec -replace '<', '<' -replace '>', '>'+ $html += " <li>$recEscaped</li>`n"+ }++ $currentDate = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'++ $html += @"+ </ul>++ <div class="footer">+ Generated by WindowsSecurityAudit Module | EOL Software Detection | $currentDate+ </div>+ </div>+</body>+</html>+"@++ return $html+}\ No newline at end of filediff --git a/Vulnerability/Get-ExposedServices.ps1 b/Vulnerability/Get-ExposedServices.ps1new file mode 100644index 0000000..b70ff4c--- /dev/null+++ b/Vulnerability/Get-ExposedServices.ps1@@ -0,0 +1,531 @@+function Get-ExposedServices {+ <#+ .SYNOPSIS+ Identifies internet-facing services and exposed network ports+ .DESCRIPTION+ Scans for services listening on public interfaces, checks firewall rules,+ identifies high-risk exposed services, and provides security recommendations.+ .PARAMETER IncludeAllPorts+ Scan all common ports (1-1024) instead of just high-risk ports+ .PARAMETER CustomPorts+ Additional custom ports to scan+ .PARAMETER CheckFirewall+ Analyze firewall rules for exposed services+ .PARAMETER OutputPath+ Path to save exposed services report+ .PARAMETER Format+ Report format: HTML, JSON, CSV, or All+ .EXAMPLE+ Get-ExposedServices+ Get-ExposedServices -IncludeAllPorts -CheckFirewall -OutputPath "C:\Reports"+ .OUTPUTS+ PSCustomObject with exposed services findings+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$IncludeAllPorts,++ [Parameter()]+ [int[]]$CustomPorts,++ [Parameter()]+ [switch]$CheckFirewall,++ [Parameter()]+ [string]$OutputPath,++ [Parameter()]+ [ValidateSet('HTML', 'JSON', 'CSV', 'All')]+ [string]$Format = 'HTML'+ )++ begin {+ Write-Host "=== EXPOSED SERVICES SCAN ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow+ Write-Host "Scan Mode: $(if($IncludeAllPorts){'Full Port Scan'}else{'High-Risk Ports Only'})" -ForegroundColor Yellow+ Write-Host "Check Firewall: $(if($CheckFirewall){'Yes'}else{'No'})" -ForegroundColor Yellow++ $findings = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ PublicIP = $null+ LocalIPs = @()+ ListeningPorts = @()+ ExposedServices = @()+ FirewallRules = @()+ Summary = @{+ TotalListening = 0+ HighRisk = 0+ MediumRisk = 0+ LowRisk = 0+ FirewallAllowRules = 0+ }+ Recommendations = @()+ }++ # High-risk ports database+ $highRiskPorts = @{+ 21 = @{Service='FTP'; Risk='High'; Description='Unencrypted file transfer'}+ 22 = @{Service='SSH'; Risk='Medium'; Description='Secure shell - requires strong auth'}+ 23 = @{Service='Telnet'; Risk='Critical'; Description='Unencrypted remote access'}+ 25 = @{Service='SMTP'; Risk='Medium'; Description='Mail server - spam relay risk'}+ 53 = @{Service='DNS'; Risk='Medium'; Description='DNS server - DDoS amplification'}+ 80 = @{Service='HTTP'; Risk='Medium'; Description='Web server - unencrypted'}+ 110 = @{Service='POP3'; Risk='Medium'; Description='Mail retrieval - unencrypted'}+ 135 = @{Service='RPC'; Risk='High'; Description='Windows RPC - attack vector'}+ 139 = @{Service='NetBIOS'; Risk='High'; Description='NetBIOS - information disclosure'}+ 143 = @{Service='IMAP'; Risk='Medium'; Description='Mail access - unencrypted'}+ 443 = @{Service='HTTPS'; Risk='Low'; Description='Secure web server'}+ 445 = @{Service='SMB'; Risk='Critical'; Description='File sharing - ransomware vector'}+ 1433 = @{Service='SQL Server'; Risk='High'; Description='Database - data breach risk'}+ 1434 = @{Service='SQL Monitor'; Risk='High'; Description='SQL Server Discovery'}+ 3306 = @{Service='MySQL'; Risk='High'; Description='Database - data breach risk'}+ 3389 = @{Service='RDP'; Risk='Critical'; Description='Remote Desktop - brute-force target'}+ 5432 = @{Service='PostgreSQL'; Risk='High'; Description='Database - data breach risk'}+ 5900 = @{Service='VNC'; Risk='High'; Description='Remote desktop - weak auth'}+ 8080 = @{Service='HTTP-Alt'; Risk='Medium'; Description='Alternative web server'}+ 8443 = @{Service='HTTPS-Alt'; Risk='Low'; Description='Alternative secure web'}+ }+ }++ process {+ try {+ # 1. GET NETWORK INFORMATION+ Write-Host "`n[1/4] Gathering network information..." -ForegroundColor Cyan++ # Get local IP addresses+ try {+ $adapters = Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue |+ Where-Object { $_.InterfaceAlias -notlike '*Loopback*' }++ foreach ($adapter in $adapters) {+ $findings.LocalIPs += [PSCustomObject]@{+ IPAddress = $adapter.IPAddress+ Interface = $adapter.InterfaceAlias+ PrefixLength = $adapter.PrefixLength+ }+ Write-Host " Local IP: $($adapter.IPAddress) ($($adapter.InterfaceAlias))" -ForegroundColor Gray+ }+ }+ catch {+ Write-Warning "Could not retrieve network adapters"+ }++ # Try to get public IP+ try {+ Write-Host " Detecting public IP..." -ForegroundColor Gray+ $publicIP = (Invoke-WebRequest -Uri "https://api.ipify.org" -UseBasicParsing -TimeoutSec 5).Content+ $findings.PublicIP = $publicIP+ Write-Host " Public IP: $publicIP" -ForegroundColor Green+ }+ catch {+ Write-Host " Could not detect public IP (offline or blocked)" -ForegroundColor Gray+ }++ # 2. SCAN LISTENING PORTS+ Write-Host "`n[2/4] Scanning listening ports..." -ForegroundColor Cyan++ # Get listening TCP connections+ try {+ $connections = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue++ foreach ($conn in $connections) {+ $localPort = $conn.LocalPort++ # Get process info+ $process = Get-Process -Id $conn.OwningProcess -ErrorAction SilentlyContinue+ $processName = if ($process) { $process.ProcessName } else { 'Unknown' }+ $processPath = if ($process) { $process.Path } else { 'Unknown' }++ # Check if it's a high-risk port+ $portInfo = $highRiskPorts[$localPort]+ $serviceName = if ($portInfo) { $portInfo.Service } else { 'Unknown' }+ $riskLevel = if ($portInfo) { $portInfo.Risk } else { 'Low' }+ $description = if ($portInfo) { $portInfo.Description } else { 'Custom service' }++ # Determine if exposed to internet+ $isExposed = ($conn.LocalAddress -eq '0.0.0.0' -or $conn.LocalAddress -eq '::')++ $portEntry = [PSCustomObject]@{+ Port = $localPort+ Service = $serviceName+ Process = $processName+ ProcessPath = $processPath+ PID = $conn.OwningProcess+ LocalAddress = $conn.LocalAddress+ IsExposed = $isExposed+ Risk = $riskLevel+ Description = $description+ }++ $findings.ListeningPorts += $portEntry++ # If exposed and high/critical risk, add to exposed services+ if ($isExposed -and $riskLevel -in @('Critical', 'High', 'Medium')) {+ $findings.ExposedServices += $portEntry++ $color = switch ($riskLevel) {+ 'Critical' { 'Red' }+ 'High' { 'Yellow' }+ 'Medium' { 'Gray' }+ default { 'Gray' }+ }++ Write-Host " [!] $riskLevel - Port $localPort ($serviceName) - $processName" -ForegroundColor $color+ }+ }++ $findings.Summary.TotalListening = $findings.ListeningPorts.Count+ Write-Host " Found $($findings.Summary.TotalListening) listening ports" -ForegroundColor Green+ }+ catch {+ Write-Warning "Could not scan TCP connections - $_"+ }++ # FIXED: Count risk levels with safe array wrapping+ $findings.Summary.HighRisk = @($findings.ExposedServices | Where-Object { $_.Risk -in @('Critical', 'High') }).Count+ $findings.Summary.MediumRisk = @($findings.ExposedServices | Where-Object { $_.Risk -eq 'Medium' }).Count+ $findings.Summary.LowRisk = @($findings.ExposedServices | Where-Object { $_.Risk -eq 'Low' }).Count++ # 3. CHECK FIREWALL RULES+ if ($CheckFirewall) {+ Write-Host "`n[3/4] Analyzing firewall rules..." -ForegroundColor Cyan++ try {+ $fwRules = Get-NetFirewallRule -Enabled True -Direction Inbound -ErrorAction SilentlyContinue |+ Where-Object { $_.Action -eq 'Allow' }++ foreach ($rule in $fwRules) {+ # Get port filter+ $portFilter = Get-NetFirewallPortFilter -AssociatedNetFirewallRule $rule -ErrorAction SilentlyContinue+ $addressFilter = Get-NetFirewallAddressFilter -AssociatedNetFirewallRule $rule -ErrorAction SilentlyContinue++ if ($portFilter -and $portFilter.LocalPort) {+ $localPorts = $portFilter.LocalPort+ $protocol = $portFilter.Protocol+ $remoteAddress = if ($addressFilter) { $addressFilter.RemoteAddress } else { 'Any' }++ # Check if allows from internet+ $allowsInternet = ($remoteAddress -eq 'Any' -or $remoteAddress -contains 'Internet')++ if ($allowsInternet) {+ $ruleEntry = [PSCustomObject]@{+ Name = $rule.Name+ DisplayName = $rule.DisplayName+ Port = $localPorts+ Protocol = $protocol+ RemoteAddress = $remoteAddress+ Profile = $rule.Profile+ }++ $findings.FirewallRules += $ruleEntry+ $findings.Summary.FirewallAllowRules++++ Write-Host " [*] Firewall allows: $($rule.DisplayName) - Port $localPorts" -ForegroundColor Gray+ }+ }+ }++ Write-Host " Found $($findings.Summary.FirewallAllowRules) allow rules from internet" -ForegroundColor $(+ if ($findings.Summary.FirewallAllowRules -gt 10) { 'Yellow' } else { 'Green' }+ )+ }+ catch {+ Write-Warning "Could not analyze firewall rules - $_"+ }+ }+ else {+ Write-Host "`n[3/4] Skipping firewall analysis (disabled)" -ForegroundColor Gray+ }++ # 4. GENERATE RECOMMENDATIONS+ Write-Host "`n[4/4] Generating recommendations..." -ForegroundColor Cyan++ # Check for critical services+ $criticalServices = @($findings.ExposedServices | Where-Object { $_.Risk -eq 'Critical' })+ if ($criticalServices.Count -gt 0) {+ foreach ($svc in $criticalServices) {+ $findings.Recommendations += "CRITICAL: Port $($svc.Port) ($($svc.Service)) is exposed - block immediately or use VPN"+ }+ }++ # Check for RDP+ $rdp = $findings.ExposedServices | Where-Object { $_.Port -eq 3389 }+ if ($rdp) {+ $findings.Recommendations += "CRITICAL: Remote Desktop (3389) exposed - use VPN or change to non-standard port with strong auth"+ }++ # Check for SMB+ $smb = $findings.ExposedServices | Where-Object { $_.Port -eq 445 }+ if ($smb) {+ $findings.Recommendations += "CRITICAL: SMB (445) exposed - major ransomware risk, block immediately"+ }++ # Check for databases+ $databases = @($findings.ExposedServices | Where-Object { $_.Port -in @(1433, 3306, 5432) })+ if ($databases.Count -gt 0) {+ $findings.Recommendations += "HIGH: Database port(s) exposed - restrict to application servers only"+ }++ # Check for management ports+ $mgmt = @($findings.ExposedServices | Where-Object { $_.Port -in @(22, 23, 135, 5900) })+ if ($mgmt.Count -gt 0) {+ $findings.Recommendations += "HIGH: Management protocol exposed - use VPN or IP whitelisting"+ }++ # General recommendations+ if ($findings.ExposedServices.Count -eq 0) {+ $findings.Recommendations += "No high-risk services exposed - maintain current security posture"+ }++ $findings.Recommendations += "Use VPN for remote access instead of direct port exposure"+ $findings.Recommendations += "Implement IP whitelisting for necessary exposed services"+ $findings.Recommendations += "Enable Network Level Authentication for RDP if required"+ $findings.Recommendations += "Use reverse proxy (nginx/Cloudflare) for web services"+ $findings.Recommendations += "Monitor exposed services with IDS/IPS"+ $findings.Recommendations += "Conduct quarterly port scans from external perspective"+ $findings.Recommendations += "Use fail2ban or similar for brute-force protection"++ # 5. EXPORT REPORTS+ if ($OutputPath) {+ Write-Host "`n[*] Exporting exposed services reports..." -ForegroundColor Cyan++ if (-not (Test-Path $OutputPath)) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ }++ $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"+ $reportName = "ExposedServices_$timestamp"++ # Export JSON+ if ($Format -in @('JSON', 'All')) {+ $jsonPath = Join-Path $OutputPath "$reportName.json"+ $findings | ConvertTo-Json -Depth 10 | Out-File $jsonPath -Encoding UTF8+ Write-Host " JSON report saved: $jsonPath" -ForegroundColor Green+ }++ # Export CSV+ if ($Format -in @('CSV', 'All')) {+ $csvPath = Join-Path $OutputPath "$reportName.csv"+ $findings.ExposedServices | Export-Csv $csvPath -NoTypeInformation+ Write-Host " CSV report saved: $csvPath" -ForegroundColor Green+ }++ # Export HTML+ if ($Format -in @('HTML', 'All')) {+ $htmlPath = Join-Path $OutputPath "$reportName.html"+ $html = Generate-ExposedServicesHTML -Findings $findings+ $html | Out-File $htmlPath -Encoding UTF8+ Write-Host " HTML report saved: $htmlPath" -ForegroundColor Green+ }+ }++ }+ catch {+ Write-Error "Error during exposed services scan - $_"+ throw+ }+ }++ end {+ Write-Host "`n=== EXPOSED SERVICES SCAN COMPLETE ===" -ForegroundColor $(+ if ($findings.Summary.HighRisk -gt 0) { 'Red' }+ elseif ($findings.Summary.MediumRisk -gt 0) { 'Yellow' }+ else { 'Green' }+ )++ Write-Host "`nSummary:" -ForegroundColor Cyan+ Write-Host " Total Listening Ports: $($findings.Summary.TotalListening)" -ForegroundColor White+ Write-Host " Exposed Services: $($findings.ExposedServices.Count)" -ForegroundColor $(+ if ($findings.ExposedServices.Count -gt 0) { 'Yellow' } else { 'Green' }+ )+ Write-Host " Critical/High Risk: $($findings.Summary.HighRisk)" -ForegroundColor $(+ if ($findings.Summary.HighRisk -gt 0) { 'Red' } else { 'Gray' }+ )+ Write-Host " Medium Risk: $($findings.Summary.MediumRisk)" -ForegroundColor Gray+ Write-Host " Low Risk: $($findings.Summary.LowRisk)" -ForegroundColor Gray++ if ($CheckFirewall) {+ Write-Host " Firewall Allow Rules: $($findings.Summary.FirewallAllowRules)" -ForegroundColor Gray+ }++ if ($findings.ExposedServices.Count -gt 0) {+ Write-Host "`nExposed High-Risk Services:" -ForegroundColor Cyan++ $highRiskExposed = @($findings.ExposedServices | Where-Object { $_.Risk -in @('Critical', 'High') })++ if ($highRiskExposed.Count -gt 0) {+ $highRiskExposed |+ Sort-Object {+ switch ($_.Risk) {+ 'Critical' { 0 }+ 'High' { 1 }+ default { 2 }+ }+ } |+ Select-Object -First 10 |+ ForEach-Object {+ $color = switch ($_.Risk) {+ 'Critical' { 'Red' }+ 'High' { 'Yellow' }+ default { 'Gray' }+ }+ Write-Host " [$($_.Risk)] Port $($_.Port) - $($_.Service) ($($_.Process))" -ForegroundColor $color+ }+ }+ }++ if ($findings.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $findings.Recommendations | Select-Object -First 10 | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ return $findings+ }+}++# Helper function to generate HTML report+function Generate-ExposedServicesHTML {+ param($Findings)++ $riskColor = if($Findings.Summary.HighRisk -gt 0){'critical'}+ elseif($Findings.Summary.MediumRisk -gt 0){'medium'}+ else{'safe'}++ $html = @"+<!DOCTYPE html>+<html>+<head>+ <title>Exposed Services Report - $($Findings.ComputerName)</title>+ <style>+ body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }+ .container { max-width: 1400px; margin: 0 auto; background: white; padding: 30px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }+ h1 { color: #2c3e50; border-bottom: 3px solid #e74c3c; padding-bottom: 10px; }+ h2 { color: #34495e; margin-top: 30px; }+ .summary { background: #ecf0f1; padding: 20px; border-radius: 5px; margin: 20px 0; }+ .metric { display: inline-block; margin: 10px 20px 10px 0; }+ .metric-label { font-weight: bold; color: #7f8c8d; }+ .metric-value { font-size: 24px; font-weight: bold; }+ .critical { color: #e74c3c; }+ .high { color: #e67e22; }+ .medium { color: #f39c12; }+ .low { color: #95a5a6; }+ .safe { color: #27ae60; }+ table { width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 14px; }+ th { background: #e74c3c; color: white; padding: 12px; text-align: left; }+ td { padding: 10px; border-bottom: 1px solid #ddd; vertical-align: top; }+ tr:hover { background: #f8f9fa; }+ .risk-badge { padding: 4px 8px; border-radius: 3px; color: white; font-weight: bold; font-size: 12px; }+ .risk-critical { background: #e74c3c; }+ .risk-high { background: #e67e22; }+ .risk-medium { background: #f39c12; }+ .risk-low { background: #95a5a6; }+ .footer { margin-top: 40px; padding-top: 20px; border-top: 1px solid #ddd; color: #7f8c8d; font-size: 12px; }+ .no-exposure { color: #27ae60; font-weight: bold; font-size: 16px; padding: 20px; text-align: center; }+ .network-info { background: #e8f4f8; padding: 15px; border-radius: 5px; margin: 10px 0; }+ </style>+</head>+<body>+ <div class="container">+ <h1>Exposed Services Security Report</h1>+ <p><strong>Computer:</strong> $($Findings.ComputerName) | <strong>Scan Date:</strong> $($Findings.ScanDate)</p>++ <div class="network-info">+ <h3>Network Information</h3>+ <p><strong>Public IP:</strong> $(if($Findings.PublicIP){$Findings.PublicIP}else{'Not detected'})</p>+ <p><strong>Local IPs:</strong> $(($Findings.LocalIPs | ForEach-Object { "$($_.IPAddress) ($($_.Interface))" }) -join ', ')</p>+ </div>++ <div class="summary">+ <h2>Summary</h2>+ <div class="metric">+ <div class="metric-label">Listening Ports</div>+ <div class="metric-value">$($Findings.Summary.TotalListening)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Exposed Services</div>+ <div class="metric-value $(if($Findings.ExposedServices.Count -gt 0){'critical'}else{'safe'})">+ $($Findings.ExposedServices.Count)+ </div>+ </div>+ <div class="metric">+ <div class="metric-label">Critical/High Risk</div>+ <div class="metric-value critical">$($Findings.Summary.HighRisk)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Medium Risk</div>+ <div class="metric-value medium">$($Findings.Summary.MediumRisk)</div>+ </div>+ </div>++ <h2>Exposed Services</h2>+"@++ if ($Findings.ExposedServices.Count -gt 0) {+ $html += @"+ <table>+ <tr>+ <th style="width: 80px;">Risk</th>+ <th style="width: 80px;">Port</th>+ <th style="width: 120px;">Service</th>+ <th style="width: 150px;">Process</th>+ <th>Description</th>+ <th style="width: 150px;">Local Address</th>+ </tr>+"@++ foreach ($service in ($Findings.ExposedServices | Sort-Object {+ switch ($_.Risk) {+ 'Critical' { 0 }+ 'High' { 1 }+ 'Medium' { 2 }+ 'Low' { 3 }+ }+ })) {+ $riskClass = "risk-$($service.Risk.ToLower())"+ $desc = $service.Description -replace '<', '<' -replace '>', '>'++ $html += @"+ <tr>+ <td><span class="risk-badge $riskClass">$($service.Risk)</span></td>+ <td><strong>$($service.Port)</strong></td>+ <td>$($service.Service)</td>+ <td>$($service.Process)</td>+ <td>$desc</td>+ <td>$($service.LocalAddress)</td>+ </tr>+"@+ }++ $html += " </table>`n"+ }+ else {+ $html += " <p class=`"no-exposure`">No high-risk services exposed to internet</p>`n"+ }++ $html += " `n <h2>Recommendations</h2>`n <ul>`n"++ foreach ($rec in $Findings.Recommendations) {+ $recEscaped = $rec -replace '<', '<' -replace '>', '>'+ $html += " <li>$recEscaped</li>`n"+ }++ $currentDate = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'++ $html += @"+ </ul>++ <div class="footer">+ Generated by WindowsSecurityAudit Module | Exposed Services Scan | $currentDate+ </div>+ </div>+</body>+</html>+"@++ return $html+}\ No newline at end of filediff --git a/Vulnerability/Get-SecurityMisconfigurations.ps1 b/Vulnerability/Get-SecurityMisconfigurations.ps1new file mode 100644index 0000000..a852951--- /dev/null+++ b/Vulnerability/Get-SecurityMisconfigurations.ps1@@ -0,0 +1,758 @@+function Get-SecurityMisconfigurations {+ <#+ .SYNOPSIS+ Detects common security misconfigurations in Windows systems+ .DESCRIPTION+ Scans for security misconfigurations including weak passwords policies,+ insecure services, disabled security features, and compliance violations.+ Provides detailed findings with remediation steps.+ .PARAMETER Category+ Specific category to scan: All, Authentication, Network, Services, FileSystem, Registry+ .PARAMETER SeverityLevel+ Minimum severity level to report: All, Critical, High, Medium, Low+ .PARAMETER OutputPath+ Path to save misconfiguration report+ .PARAMETER Format+ Report format: HTML, JSON, CSV, or All+ .EXAMPLE+ Get-SecurityMisconfigurations+ Get-SecurityMisconfigurations -Category Authentication -SeverityLevel High+ .OUTPUTS+ PSCustomObject with misconfiguration findings+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [ValidateSet('All', 'Authentication', 'Network', 'Services', 'FileSystem', 'Registry')]+ [string]$Category = 'All',++ [Parameter()]+ [ValidateSet('All', 'Critical', 'High', 'Medium', 'Low')]+ [string]$SeverityLevel = 'All',++ [Parameter()]+ [string]$OutputPath,++ [Parameter()]+ [ValidateSet('HTML', 'JSON', 'CSV', 'All')]+ [string]$Format = 'HTML'+ )++ begin {+ Write-Host "=== SECURITY MISCONFIGURATION SCAN ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow+ Write-Host "Scan Category: $Category" -ForegroundColor Yellow+ Write-Host "Severity Filter: $SeverityLevel" -ForegroundColor Yellow++ $findings = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ OSVersion = (Get-CimInstance Win32_OperatingSystem).Caption+ Misconfigurations = @()+ Summary = @{+ TotalFindings = 0+ Critical = 0+ High = 0+ Medium = 0+ Low = 0+ }+ Recommendations = @()+ }+ }++ process {+ try {+ # 1. AUTHENTICATION & PASSWORD POLICIES+ if ($Category -in @('All', 'Authentication')) {+ Write-Host "`n[*] Checking authentication configurations..." -ForegroundColor Cyan++ # Password Policy+ try {+ $secpol = @{}+ secedit /export /cfg "$env:TEMP\secpol.cfg" /quiet | Out-Null+ Get-Content "$env:TEMP\secpol.cfg" | Where-Object { $_ -match '=' } | ForEach-Object {+ $parts = $_ -split '=', 2+ $secpol[$parts[0].Trim()] = $parts[1].Trim()+ }+ Remove-Item "$env:TEMP\secpol.cfg" -Force -ErrorAction SilentlyContinue++ # Check minimum password length+ $minPwdLength = [int]$secpol['MinimumPasswordLength']+ if ($minPwdLength -lt 14) {+ $findings.Misconfigurations += [PSCustomObject]@{+ Category = 'Authentication'+ Finding = 'Weak Password Length Policy'+ Severity = 'High'+ CurrentValue = "$minPwdLength characters"+ RecommendedValue = '14+ characters'+ Description = 'Minimum password length is below recommended security standard'+ Remediation = 'Set minimum password length to 14: secpol.msc > Password Policy > Minimum password length'+ Risk = 'Weak passwords are vulnerable to brute-force attacks'+ }+ $findings.Summary.High+++ Write-Host " [!] HIGH: Minimum password length is $minPwdLength (recommend 14+)" -ForegroundColor Yellow+ }++ # Check password complexity+ $pwdComplexity = $secpol['PasswordComplexity']+ if ($pwdComplexity -eq '0') {+ $findings.Misconfigurations += [PSCustomObject]@{+ Category = 'Authentication'+ Finding = 'Password Complexity Disabled'+ Severity = 'Critical'+ CurrentValue = 'Disabled'+ RecommendedValue = 'Enabled'+ Description = 'Password complexity requirements are not enforced'+ Remediation = 'Enable password complexity: secpol.msc > Password Policy > Password must meet complexity requirements'+ Risk = 'Users can set simple, easily guessable passwords'+ }+ $findings.Summary.Critical+++ Write-Host " [!] CRITICAL: Password complexity is disabled" -ForegroundColor Red+ }++ # Check password history+ $pwdHistory = [int]$secpol['PasswordHistorySize']+ if ($pwdHistory -lt 12) {+ $findings.Misconfigurations += [PSCustomObject]@{+ Category = 'Authentication'+ Finding = 'Insufficient Password History'+ Severity = 'Medium'+ CurrentValue = "$pwdHistory passwords"+ RecommendedValue = '12+ passwords'+ Description = 'Password history size is below recommended value'+ Remediation = 'Set password history to 12: secpol.msc > Password Policy > Enforce password history'+ Risk = 'Users can quickly reuse old passwords'+ }+ $findings.Summary.Medium+++ }++ # Check account lockout threshold+ $lockoutThreshold = $secpol['LockoutBadCount']+ if ($lockoutThreshold -eq '0' -or [int]$lockoutThreshold -gt 10) {+ $findings.Misconfigurations += [PSCustomObject]@{+ Category = 'Authentication'+ Finding = 'Weak Account Lockout Policy'+ Severity = 'High'+ CurrentValue = if($lockoutThreshold -eq '0'){'Disabled'}else{"$lockoutThreshold attempts"}+ RecommendedValue = '5-10 attempts'+ Description = 'Account lockout threshold is too high or disabled'+ Remediation = 'Set lockout threshold: secpol.msc > Account Lockout Policy > Account lockout threshold'+ Risk = 'Vulnerable to brute-force password attacks'+ }+ $findings.Summary.High+++ Write-Host " [!] HIGH: Account lockout threshold: $lockoutThreshold" -ForegroundColor Yellow+ }+ }+ catch {+ Write-Warning "Could not check password policies: $_"+ }++ # Check for blank passwords+ try {+ $users = Get-LocalUser | Where-Object { $_.Enabled -eq $true }+ foreach ($user in $users) {+ if ($null -eq $user.PasswordLastSet) {+ $findings.Misconfigurations += [PSCustomObject]@{+ Category = 'Authentication'+ Finding = "User with No Password Set: $($user.Name)"+ Severity = 'Critical'+ CurrentValue = 'No password'+ RecommendedValue = 'Strong password required'+ Description = "User account '$($user.Name)' has no password set"+ Remediation = "Set password: net user $($user.Name) *"+ Risk = 'Account can be accessed without authentication'+ }+ $findings.Summary.Critical+++ Write-Host " [!] CRITICAL: User '$($user.Name)' has no password" -ForegroundColor Red+ }+ }+ }+ catch {+ Write-Warning "Could not check user passwords: $_"+ }+ }++ # 2. NETWORK SECURITY+ if ($Category -in @('All', 'Network')) {+ Write-Host "`n[*] Checking network configurations..." -ForegroundColor Cyan++ # Check Windows Firewall+ try {+ $fwProfiles = Get-NetFirewallProfile -ErrorAction SilentlyContinue+ foreach ($profile in $fwProfiles) {+ if (-not $profile.Enabled) {+ $findings.Misconfigurations += [PSCustomObject]@{+ Category = 'Network'+ Finding = "Windows Firewall Disabled: $($profile.Name)"+ Severity = 'Critical'+ CurrentValue = 'Disabled'+ RecommendedValue = 'Enabled'+ Description = "Windows Firewall is disabled for $($profile.Name) profile"+ Remediation = "Enable firewall: Set-NetFirewallProfile -Name $($profile.Name) -Enabled True"+ Risk = 'System is exposed to network-based attacks'+ }+ $findings.Summary.Critical+++ Write-Host " [!] CRITICAL: Firewall disabled for $($profile.Name) profile" -ForegroundColor Red+ }+ }+ }+ catch {+ Write-Warning "Could not check firewall status: $_"+ }++ # Check for public network profile+ try {+ $publicProfile = Get-NetConnectionProfile | Where-Object { $_.NetworkCategory -eq 'Public' }+ if (-not $publicProfile) {+ $privateCount = (Get-NetConnectionProfile | Where-Object { $_.NetworkCategory -eq 'Private' }).Count+ if ($privateCount -gt 0) {+ $findings.Misconfigurations += [PSCustomObject]@{+ Category = 'Network'+ Finding = 'Network Set as Private Instead of Public'+ Severity = 'Medium'+ CurrentValue = 'Private'+ RecommendedValue = 'Public (for untrusted networks)'+ Description = 'Network is set to Private which allows more network discovery'+ Remediation = 'Set network to Public in Settings > Network & Internet'+ Risk = 'Increased network exposure on untrusted networks'+ }+ $findings.Summary.Medium+++ }+ }+ }+ catch {+ Write-Warning "Could not check network profiles: $_"+ }++ # Check for SMBv1+ try {+ $smbv1 = Get-WindowsOptionalFeature -Online -FeatureName SMB1Protocol -ErrorAction SilentlyContinue+ if ($smbv1.State -eq 'Enabled') {+ $findings.Misconfigurations += [PSCustomObject]@{+ Category = 'Network'+ Finding = 'SMBv1 Protocol Enabled'+ Severity = 'Critical'+ CurrentValue = 'Enabled'+ RecommendedValue = 'Disabled'+ Description = 'Insecure SMBv1 protocol is enabled (vulnerable to WannaCry/NotPetya)'+ Remediation = 'Disable SMBv1: Disable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol'+ Risk = 'Vulnerable to ransomware and remote exploits'+ }+ $findings.Summary.Critical+++ Write-Host " [!] CRITICAL: SMBv1 is enabled (security risk)" -ForegroundColor Red+ }+ }+ catch {+ Write-Warning "Could not check SMBv1 status: $_"+ }++ # Check RDP settings+ try {+ $rdpEnabled = (Get-ItemProperty 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name fDenyTSConnections).fDenyTSConnections+ if ($rdpEnabled -eq 0) {+ # RDP is enabled, check NLA+ $nlaEnabled = (Get-ItemProperty 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -Name UserAuthentication).UserAuthentication+ if ($nlaEnabled -eq 0) {+ $findings.Misconfigurations += [PSCustomObject]@{+ Category = 'Network'+ Finding = 'RDP Network Level Authentication Disabled'+ Severity = 'High'+ CurrentValue = 'Disabled'+ RecommendedValue = 'Enabled'+ Description = 'Remote Desktop has NLA disabled, allowing unauthenticated connections'+ Remediation = 'Enable NLA: Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" -Name UserAuthentication -Value 1'+ Risk = 'RDP vulnerable to brute-force attacks'+ }+ $findings.Summary.High+++ Write-Host " [!] HIGH: RDP NLA is disabled" -ForegroundColor Yellow+ }+ }+ }+ catch {+ Write-Warning "Could not check RDP settings: $_"+ }+ }++ # 3. SERVICES+ if ($Category -in @('All', 'Services')) {+ Write-Host "`n[*] Checking service configurations..." -ForegroundColor Cyan++ # Check for unnecessary running services+ $riskyServices = @(+ @{Name='RemoteRegistry'; Severity='High'; Risk='Allows remote registry access'},+ @{Name='TlntSvr'; Severity='Critical'; Risk='Unencrypted remote access'},+ @{Name='SNMP'; Severity='Medium'; Risk='Information disclosure'},+ @{Name='RpcLocator'; Severity='Low'; Risk='Rarely needed service'}+ )++ foreach ($svc in $riskyServices) {+ $service = Get-Service -Name $svc.Name -ErrorAction SilentlyContinue+ if ($service -and $service.Status -eq 'Running') {+ $findings.Misconfigurations += [PSCustomObject]@{+ Category = 'Services'+ Finding = "Risky Service Running: $($svc.Name)"+ Severity = $svc.Severity+ CurrentValue = 'Running'+ RecommendedValue = 'Stopped/Disabled'+ Description = "Service '$($svc.Name)' is running"+ Remediation = "Stop and disable: Stop-Service -Name $($svc.Name); Set-Service -Name $($svc.Name) -StartupType Disabled"+ Risk = $svc.Risk+ }++ switch ($svc.Severity) {+ 'Critical' { $findings.Summary.Critical++ }+ 'High' { $findings.Summary.High++ }+ 'Medium' { $findings.Summary.Medium++ }+ 'Low' { $findings.Summary.Low++ }+ }++ Write-Host " [!] $($svc.Severity): Service '$($svc.Name)' is running" -ForegroundColor $(+ switch ($svc.Severity) {+ 'Critical' { 'Red' }+ 'High' { 'Yellow' }+ default { 'Gray' }+ }+ )+ }+ }+ }++ # 4. FILE SYSTEM+ if ($Category -in @('All', 'FileSystem')) {+ Write-Host "`n[*] Checking file system configurations..." -ForegroundColor Cyan++ # Check for world-writable folders in system paths+ $systemPaths = @('C:\Windows', 'C:\Program Files', 'C:\Program Files (x86)')+ foreach ($path in $systemPaths) {+ if (Test-Path $path) {+ try {+ $acl = Get-Acl $path -ErrorAction SilentlyContinue+ $everyoneWrite = $acl.Access | Where-Object {+ $_.IdentityReference -eq 'Everyone' -and+ $_.FileSystemRights -match 'Write|FullControl|Modify'+ }++ if ($everyoneWrite) {+ $findings.Misconfigurations += [PSCustomObject]@{+ Category = 'FileSystem'+ Finding = "World-Writable System Folder: $path"+ Severity = 'Critical'+ CurrentValue = 'Everyone has write access'+ RecommendedValue = 'Restricted permissions'+ Description = "System folder has insecure permissions allowing 'Everyone' to write"+ Remediation = "Review and restrict permissions using icacls or File Explorer"+ Risk = 'Attackers can modify system files or plant malware'+ }+ $findings.Summary.Critical+++ Write-Host " [!] CRITICAL: World-writable folder: $path" -ForegroundColor Red+ }+ }+ catch {+ # Skip if access denied+ }+ }+ }++ # Check BitLocker status+ try {+ $volumes = Get-BitLockerVolume -ErrorAction SilentlyContinue+ $unencrypted = $volumes | Where-Object {+ $_.VolumeType -eq 'OperatingSystem' -and+ $_.ProtectionStatus -eq 'Off'+ }++ if ($unencrypted) {+ $findings.Misconfigurations += [PSCustomObject]@{+ Category = 'FileSystem'+ Finding = 'BitLocker Not Enabled on OS Drive'+ Severity = 'High'+ CurrentValue = 'Not encrypted'+ RecommendedValue = 'Encrypted with BitLocker'+ Description = 'Operating system drive is not encrypted with BitLocker'+ Remediation = 'Enable BitLocker: Control Panel > BitLocker Drive Encryption'+ Risk = 'Data vulnerable to physical theft or offline attacks'+ }+ $findings.Summary.High+++ Write-Host " [!] HIGH: BitLocker not enabled on OS drive" -ForegroundColor Yellow+ }+ }+ catch {+ # BitLocker cmdlets might not be available+ }+ }++ # 5. REGISTRY SECURITY+ if ($Category -in @('All', 'Registry')) {+ Write-Host "`n[*] Checking registry configurations..." -ForegroundColor Cyan++ # Check UAC settings+ try {+ $uacEnabled = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name EnableLUA).EnableLUA+ if ($uacEnabled -eq 0) {+ $findings.Misconfigurations += [PSCustomObject]@{+ Category = 'Registry'+ Finding = 'User Account Control (UAC) Disabled'+ Severity = 'Critical'+ CurrentValue = 'Disabled'+ RecommendedValue = 'Enabled'+ Description = 'User Account Control is completely disabled'+ Remediation = 'Enable UAC: Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" -Name EnableLUA -Value 1'+ Risk = 'Malware can gain administrative privileges without prompting'+ }+ $findings.Summary.Critical+++ Write-Host " [!] CRITICAL: UAC is disabled" -ForegroundColor Red+ }+ else {+ # Check UAC level+ $uacLevel = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name ConsentPromptBehaviorAdmin).ConsentPromptBehaviorAdmin+ if ($uacLevel -eq 0) {+ $findings.Misconfigurations += [PSCustomObject]@{+ Category = 'Registry'+ Finding = 'UAC Set to Never Notify'+ Severity = 'High'+ CurrentValue = 'Never notify'+ RecommendedValue = 'Always notify'+ Description = 'UAC is set to never notify for administrative actions'+ Remediation = 'Increase UAC level in User Account Control Settings'+ Risk = 'Reduced visibility of privilege escalation attempts'+ }+ $findings.Summary.High+++ Write-Host " [!] HIGH: UAC set to never notify" -ForegroundColor Yellow+ }+ }+ }+ catch {+ Write-Warning "Could not check UAC settings: $_"+ }++ # Check Windows Defender+ try {+ $defenderDisabled = (Get-ItemProperty 'HKLM:\SOFTWARE\Policies\Microsoft\Windows Defender' -Name DisableAntiSpyware -ErrorAction SilentlyContinue).DisableAntiSpyware+ if ($defenderDisabled -eq 1) {+ $findings.Misconfigurations += [PSCustomObject]@{+ Category = 'Registry'+ Finding = 'Windows Defender Disabled via Registry'+ Severity = 'Critical'+ CurrentValue = 'Disabled'+ RecommendedValue = 'Enabled'+ Description = 'Windows Defender antivirus is disabled via Group Policy'+ Remediation = 'Remove registry value or enable via Group Policy'+ Risk = 'No real-time malware protection'+ }+ $findings.Summary.Critical+++ Write-Host " [!] CRITICAL: Windows Defender is disabled" -ForegroundColor Red+ }+ }+ catch {+ # Key might not exist, which is fine+ }++ # Check auto-run entries+ try {+ $autoRunKeys = @(+ 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run',+ 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'+ )++ $suspiciousCount = 0+ foreach ($key in $autoRunKeys) {+ $entries = Get-ItemProperty $key -ErrorAction SilentlyContinue+ if ($entries) {+ $entries.PSObject.Properties | Where-Object {+ $_.Name -notlike 'PS*' -and+ $_.Value -match '(temp|appdata\\local\\temp|downloads)'+ } | ForEach-Object {+ $suspiciousCount+++ }+ }+ }++ if ($suspiciousCount -gt 0) {+ $findings.Misconfigurations += [PSCustomObject]@{+ Category = 'Registry'+ Finding = "Suspicious Autorun Entries: $suspiciousCount"+ Severity = 'High'+ CurrentValue = "$suspiciousCount suspicious entries"+ RecommendedValue = 'Review and remove unauthorized entries'+ Description = 'Autorun entries pointing to temporary or suspicious locations detected'+ Remediation = 'Review entries using: Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'+ Risk = 'Potential malware persistence mechanism'+ }+ $findings.Summary.High+++ Write-Host " [!] HIGH: $suspiciousCount suspicious autorun entries" -ForegroundColor Yellow+ }+ }+ catch {+ Write-Warning "Could not check autorun entries: $_"+ }+ }++ # Calculate total findings+ $findings.Summary.TotalFindings = $findings.Misconfigurations.Count++ # Filter by severity level if specified+ if ($SeverityLevel -ne 'All') {+ $severityOrder = @('Critical', 'High', 'Medium', 'Low')+ $minIndex = $severityOrder.IndexOf($SeverityLevel)+ $findings.Misconfigurations = $findings.Misconfigurations | Where-Object {+ $severityOrder.IndexOf($_.Severity) -le $minIndex+ }+ }++ # Generate recommendations+ Write-Host "`n[*] Generating recommendations..." -ForegroundColor Cyan++ if ($findings.Summary.Critical -gt 0) {+ $findings.Recommendations += "CRITICAL: Address $($findings.Summary.Critical) critical misconfiguration(s) immediately"+ }++ if ($findings.Summary.High -gt 0) {+ $findings.Recommendations += "HIGH: Fix $($findings.Summary.High) high-severity misconfiguration(s) within 7 days"+ }++ if ($findings.Summary.Medium -gt 0) {+ $findings.Recommendations += "MEDIUM: Remediate $($findings.Summary.Medium) medium-severity issue(s) within 30 days"+ }++ if ($findings.Summary.TotalFindings -eq 0) {+ $findings.Recommendations += "No significant misconfigurations detected - maintain current security posture"+ }++ $findings.Recommendations += "Implement security baseline using Group Policy"+ $findings.Recommendations += "Run monthly security configuration audits"+ $findings.Recommendations += "Use Microsoft Security Compliance Toolkit"+ $findings.Recommendations += "Enable security audit logging for configuration changes"++ # Export reports+ if ($OutputPath) {+ Write-Host "`n[*] Exporting misconfiguration reports..." -ForegroundColor Cyan++ if (-not (Test-Path $OutputPath)) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ }++ $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"+ $reportName = "SecurityMisconfigurations_$timestamp"++ # Export JSON+ if ($Format -in @('JSON', 'All')) {+ $jsonPath = Join-Path $OutputPath "$reportName.json"+ $findings | ConvertTo-Json -Depth 10 | Out-File $jsonPath -Encoding UTF8+ Write-Host " JSON report saved: $jsonPath" -ForegroundColor Green+ }++ # Export CSV+ if ($Format -in @('CSV', 'All')) {+ $csvPath = Join-Path $OutputPath "$reportName.csv"+ $findings.Misconfigurations | Export-Csv $csvPath -NoTypeInformation+ Write-Host " CSV report saved: $csvPath" -ForegroundColor Green+ }++ # Export HTML+ if ($Format -in @('HTML', 'All')) {+ $htmlPath = Join-Path $OutputPath "$reportName.html"+ $html = Generate-MisconfigurationHTML -Findings $findings+ $html | Out-File $htmlPath -Encoding UTF8+ Write-Host " HTML report saved: $htmlPath" -ForegroundColor Green+ }+ }++ }+ catch {+ Write-Error "Error during misconfiguration scan: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== MISCONFIGURATION SCAN COMPLETE ===" -ForegroundColor $(+ if ($findings.Summary.Critical -gt 0) { 'Red' }+ elseif ($findings.Summary.High -gt 0) { 'Yellow' }+ else { 'Green' }+ )++ Write-Host "`nSummary:" -ForegroundColor Cyan+ Write-Host " Total Findings: $($findings.Summary.TotalFindings)" -ForegroundColor White+ Write-Host " Critical: $($findings.Summary.Critical)" -ForegroundColor $(+ if ($findings.Summary.Critical -gt 0) { 'Red' } else { 'Gray' }+ )+ Write-Host " High: $($findings.Summary.High)" -ForegroundColor $(+ if ($findings.Summary.High -gt 0) { 'Yellow' } else { 'Gray' }+ )+ Write-Host " Medium: $($findings.Summary.Medium)" -ForegroundColor Gray+ Write-Host " Low: $($findings.Summary.Low)" -ForegroundColor Gray++ if ($findings.Misconfigurations.Count -gt 0) {+ Write-Host "`nTop Issues:" -ForegroundColor Cyan+ $findings.Misconfigurations |+ Sort-Object {+ switch ($_.Severity) {+ 'Critical' { 0 }+ 'High' { 1 }+ 'Medium' { 2 }+ 'Low' { 3 }+ }+ } |+ Select-Object -First 10 |+ ForEach-Object {+ $color = switch ($_.Severity) {+ 'Critical' { 'Red' }+ 'High' { 'Yellow' }+ default { 'Gray' }+ }+ Write-Host " [$($_.Severity)] $($_.Finding)" -ForegroundColor $color+ }+ }++ if ($findings.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $findings.Recommendations | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ return $findings+ }+}++# Helper function to generate HTML report+function Generate-MisconfigurationHTML {+ param($Findings)++ $riskColor = if($Findings.Summary.Critical -gt 0){'critical'}+ elseif($Findings.Summary.High -gt 0){'high'}+ else{'safe'}++ $html = @"+<!DOCTYPE html>+<html>+<head>+ <title>Security Misconfigurations - $($Findings.ComputerName)</title>+ <style>+ body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }+ .container { max-width: 1400px; margin: 0 auto; background: white; padding: 30px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }+ h1 { color: #2c3e50; border-bottom: 3px solid #e74c3c; padding-bottom: 10px; }+ h2 { color: #34495e; margin-top: 30px; }+ .summary { background: #ecf0f1; padding: 20px; border-radius: 5px; margin: 20px 0; }+ .metric { display: inline-block; margin: 10px 20px 10px 0; }+ .metric-label { font-weight: bold; color: #7f8c8d; }+ .metric-value { font-size: 24px; font-weight: bold; }+ .critical { color: #e74c3c; }+ .high { color: #e67e22; }+ .medium { color: #f39c12; }+ .low { color: #95a5a6; }+ .safe { color: #27ae60; }+ table { width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 14px; }+ th { background: #e74c3c; color: white; padding: 12px; text-align: left; }+ td { padding: 10px; border-bottom: 1px solid #ddd; vertical-align: top; }+ tr:hover { background: #f8f9fa; }+ .severity-badge { padding: 4px 8px; border-radius: 3px; color: white; font-weight: bold; font-size: 12px; }+ .severity-critical { background: #e74c3c; }+ .severity-high { background: #e67e22; }+ .severity-medium { background: #f39c12; }+ .severity-low { background: #95a5a6; }+ .footer { margin-top: 40px; padding-top: 20px; border-top: 1px solid #ddd; color: #7f8c8d; font-size: 12px; }+ .no-issues { color: #27ae60; font-weight: bold; font-size: 16px; padding: 20px; text-align: center; }+ </style>+</head>+<body>+ <div class="container">+ <h1>Security Misconfiguration Report</h1>+ <p><strong>Computer:</strong> $($Findings.ComputerName) | <strong>Scan Date:</strong> $($Findings.ScanDate)</p>+ <p><strong>OS:</strong> $($Findings.OSVersion)</p>++ <div class="summary">+ <h2>Summary</h2>+ <div class="metric">+ <div class="metric-label">Total Findings</div>+ <div class="metric-value">$($Findings.Summary.TotalFindings)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Critical</div>+ <div class="metric-value critical">$($Findings.Summary.Critical)</div>+ </div>+ <div class="metric">+ <div class="metric-label">High</div>+ <div class="metric-value high">$($Findings.Summary.High)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Medium</div>+ <div class="metric-value medium">$($Findings.Summary.Medium)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Low</div>+ <div class="metric-value low">$($Findings.Summary.Low)</div>+ </div>+ </div>++ <h2>Detected Misconfigurations</h2>+"@++ if ($Findings.Misconfigurations.Count -gt 0) {+ $html += @"+ <table>+ <tr>+ <th style="width: 80px;">Severity</th>+ <th style="width: 120px;">Category</th>+ <th style="width: 200px;">Finding</th>+ <th style="width: 150px;">Current Value</th>+ <th style="width: 150px;">Recommended</th>+ <th>Remediation</th>+ </tr>+"@++ foreach ($item in ($Findings.Misconfigurations | Sort-Object {+ switch ($_.Severity) {+ 'Critical' { 0 }+ 'High' { 1 }+ 'Medium' { 2 }+ 'Low' { 3 }+ }+ })) {+ $severityClass = "severity-$($item.Severity.ToLower())"+ $finding = $item.Finding -replace '<', '<' -replace '>', '>'+ $current = $item.CurrentValue -replace '<', '<' -replace '>', '>'+ $recommended = $item.RecommendedValue -replace '<', '<' -replace '>', '>'+ $remediation = $item.Remediation -replace '<', '<' -replace '>', '>'++ $html += @"+ <tr>+ <td><span class="severity-badge $severityClass">$($item.Severity)</span></td>+ <td>$($item.Category)</td>+ <td><strong>$finding</strong></td>+ <td>$current</td>+ <td>$recommended</td>+ <td><small>$remediation</small></td>+ </tr>+"@+ }++ $html += " </table>`n"+ }+ else {+ $html += " <p class=`"no-issues`">No security misconfigurations detected</p>`n"+ }++ $html += " `n <h2>Recommendations</h2>`n <ul>`n"++ foreach ($rec in $Findings.Recommendations) {+ $recEscaped = $rec -replace '<', '<' -replace '>', '>'+ $html += " <li>$recEscaped</li>`n"+ }++ $currentDate = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'++ $html += @"+ </ul>++ <div class="footer">+ Generated by WindowsSecurityAudit Module | Security Misconfiguration Scan | $currentDate+ </div>+ </div>+</body>+</html>+"@++ return $html+}\ No newline at end of filediff --git a/Vulnerability/Get-VulnerabilityAssessment.ps1 b/Vulnerability/Get-VulnerabilityAssessment.ps1new file mode 100644index 0000000..c105228--- /dev/null+++ b/Vulnerability/Get-VulnerabilityAssessment.ps1@@ -0,0 +1,570 @@+function Get-VulnerabilityAssessment {+ <#+ .SYNOPSIS+ Performs comprehensive vulnerability assessment of installed software+ .DESCRIPTION+ Scans installed software, checks against known vulnerabilities (CVE database),+ identifies security risks, and provides remediation recommendations+ .PARAMETER ScanDepth+ Scan depth: Quick (installed apps only), Standard (+ services), Deep (+ drivers)+ .PARAMETER IncludeCVELookup+ Query online CVE databases (requires internet)+ .PARAMETER OutputPath+ Path to save vulnerability report+ .PARAMETER Format+ Report format: HTML, JSON, CSV, or All+ .EXAMPLE+ Get-VulnerabilityAssessment -ScanDepth Standard+ Get-VulnerabilityAssessment -IncludeCVELookup -OutputPath "C:\Reports"+ .OUTPUTS+ PSCustomObject with vulnerability assessment results+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [ValidateSet('Quick', 'Standard', 'Deep')]+ [string]$ScanDepth = 'Standard',++ [Parameter()]+ [switch]$IncludeCVELookup,++ [Parameter()]+ [string]$OutputPath,++ [Parameter()]+ [ValidateSet('HTML', 'JSON', 'CSV', 'All')]+ [string]$Format = 'HTML'+ )++ begin {+ Write-Host "=== VULNERABILITY ASSESSMENT ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow+ Write-Host "Scan Depth: $ScanDepth" -ForegroundColor Yellow+ Write-Host "CVE Lookup: $(if($IncludeCVELookup){'Enabled'}else{'Disabled'})" -ForegroundColor Yellow++ $assessment = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ ScanDepth = $ScanDepth+ Software = @()+ Vulnerabilities = @()+ Summary = @{+ TotalApplications = 0+ VulnerableApplications = 0+ CriticalVulnerabilities = 0+ HighVulnerabilities = 0+ MediumVulnerabilities = 0+ LowVulnerabilities = 0+ }+ Recommendations = @()+ }++ # Known vulnerable versions database (offline fallback)+ $knownVulnerabilities = @{+ 'Google Chrome' = @{+ VulnerableVersions = @('120.0.0.0', '119.0.0.0', '118.0.0.0')+ LatestSafe = '121.0.6167.85'+ Severity = 'High'+ CVE = 'CVE-2024-0517, CVE-2024-0518'+ Description = 'Multiple security vulnerabilities including remote code execution'+ }+ 'Mozilla Firefox' = @{+ VulnerableVersions = @('121.0', '120.0', '119.0')+ LatestSafe = '122.0'+ Severity = 'High'+ CVE = 'CVE-2024-0741, CVE-2024-0742'+ Description = 'Security vulnerabilities in browser engine'+ }+ 'Adobe Acrobat Reader DC' = @{+ VulnerableVersions = @('23.001.20687', '23.001.20604')+ LatestSafe = '24.001.20643'+ Severity = 'Critical'+ CVE = 'CVE-2024-20720, CVE-2024-20721'+ Description = 'Arbitrary code execution vulnerabilities'+ }+ 'Java' = @{+ VulnerableVersions = @('8.0.391', '8.0.381', '8.0.371')+ LatestSafe = '8.0.401'+ Severity = 'Critical'+ CVE = 'CVE-2024-20918, CVE-2024-20919'+ Description = 'Remote code execution and privilege escalation'+ }+ 'OpenSSL' = @{+ VulnerableVersions = @('3.0.0', '3.0.1', '3.0.2', '3.0.3', '3.0.4', '3.0.5', '3.0.6', '3.0.7')+ LatestSafe = '3.0.13'+ Severity = 'High'+ CVE = 'CVE-2024-0727'+ Description = 'Denial of service vulnerability'+ }+ 'WinRAR' = @{+ VulnerableVersions = @('6.23', '6.22', '6.21', '6.20')+ LatestSafe = '6.24'+ Severity = 'Critical'+ CVE = 'CVE-2023-40477'+ Description = 'Remote code execution via malicious archives'+ }+ }+ }++ process {+ try {+ # 1. SCAN INSTALLED SOFTWARE+ Write-Host "`n[1/5] Scanning installed applications..." -ForegroundColor Cyan++ # Get installed software from registry - FIXED: Safe property access for all properties+ $registryPaths = @(+ 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*',+ 'HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'+ )++ $installedSoftware = @()+ foreach ($path in $registryPaths) {+ $items = Get-ItemProperty $path -ErrorAction SilentlyContinue+ if ($items) {+ foreach ($item in $items) {+ # FIXED: Safe property check for DisplayName+ if ($null -ne $item.PSObject.Properties['DisplayName'] -and+ $null -ne $item.DisplayName -and+ $item.DisplayName -ne '') {++ # FIXED: Safe property access with fallbacks for all properties+ $displayVersion = if ($null -ne $item.PSObject.Properties['DisplayVersion']) {+ $item.DisplayVersion+ } else {+ 'Unknown'+ }++ $publisher = if ($null -ne $item.PSObject.Properties['Publisher']) {+ $item.Publisher+ } else {+ 'Unknown'+ }++ $installDate = if ($null -ne $item.PSObject.Properties['InstallDate']) {+ $item.InstallDate+ } else {+ $null+ }++ $installedSoftware += [PSCustomObject]@{+ DisplayName = $item.DisplayName+ DisplayVersion = $displayVersion+ Publisher = $publisher+ InstallDate = $installDate+ }+ }+ }+ }+ }++ # Remove duplicates+ $installedSoftware = $installedSoftware |+ Sort-Object DisplayName -Unique |+ Where-Object {+ $_.DisplayName -notlike "KB*" -and+ $_.DisplayName -notlike "Update for*"+ }++ $assessment.Summary.TotalApplications = $installedSoftware.Count+ Write-Host " Found $($installedSoftware.Count) installed applications" -ForegroundColor Gray++ # 2. CHECK VULNERABLE VERSIONS (OFFLINE)+ Write-Host "`n[2/5] Checking against known vulnerabilities..." -ForegroundColor Cyan++ $vulnerableApps = @()+ foreach ($app in $installedSoftware) {+ $appInfo = [PSCustomObject]@{+ Name = $app.DisplayName+ Version = $app.DisplayVersion+ Publisher = $app.Publisher+ InstallDate = $app.InstallDate+ IsVulnerable = $false+ Vulnerabilities = @()+ }++ # Check against known vulnerabilities+ foreach ($vulnName in $knownVulnerabilities.Keys) {+ if ($app.DisplayName -like "*$vulnName*") {+ $vulnInfo = $knownVulnerabilities[$vulnName]++ # Check if version is vulnerable+ $isVulnerable = $false+ if ($app.DisplayVersion -and $app.DisplayVersion -ne 'Unknown') {+ foreach ($vulnVersion in $vulnInfo.VulnerableVersions) {+ if ($app.DisplayVersion -like "$vulnVersion*") {+ $isVulnerable = $true+ break+ }+ }+ }++ if ($isVulnerable) {+ $appInfo.IsVulnerable = $true++ $vulnerability = [PSCustomObject]@{+ Software = $app.DisplayName+ CurrentVersion = $app.DisplayVersion+ Severity = $vulnInfo.Severity+ CVE = $vulnInfo.CVE+ Description = $vulnInfo.Description+ RecommendedVersion = $vulnInfo.LatestSafe+ Remediation = "Update to version $($vulnInfo.LatestSafe) or later"+ }++ $appInfo.Vulnerabilities += $vulnerability+ $assessment.Vulnerabilities += $vulnerability++ # Update counters+ switch ($vulnInfo.Severity) {+ 'Critical' { $assessment.Summary.CriticalVulnerabilities++ }+ 'High' { $assessment.Summary.HighVulnerabilities++ }+ 'Medium' { $assessment.Summary.MediumVulnerabilities++ }+ 'Low' { $assessment.Summary.LowVulnerabilities++ }+ }++ Write-Host " [!] VULNERABLE: $($app.DisplayName) $($app.DisplayVersion) - $($vulnInfo.Severity)" -ForegroundColor Red+ }+ }+ }++ if ($appInfo.IsVulnerable) {+ $vulnerableApps += $appInfo+ $assessment.Summary.VulnerableApplications+++ }++ $assessment.Software += $appInfo+ }++ Write-Host " Found $($assessment.Summary.VulnerableApplications) vulnerable applications" -ForegroundColor $(+ if ($assessment.Summary.CriticalVulnerabilities -gt 0) { 'Red' }+ elseif ($assessment.Summary.HighVulnerabilities -gt 0) { 'Yellow' }+ else { 'Gray' }+ )++ # 3. SCAN SERVICES (if Standard or Deep)+ if ($ScanDepth -in @('Standard', 'Deep')) {+ Write-Host "`n[3/5] Scanning services..." -ForegroundColor Cyan++ $services = Get-Service | Where-Object { $_.Status -eq 'Running' } |+ Select-Object Name, DisplayName, StartType++ # Check for potentially vulnerable services+ $vulnerableServiceNames = @(+ 'RemoteRegistry',+ 'TlntSvr',+ 'SNMP',+ 'RpcLocator'+ )++ foreach ($service in $services) {+ if ($service.Name -in $vulnerableServiceNames) {+ $vulnerability = [PSCustomObject]@{+ Software = "Service: $($service.DisplayName)"+ CurrentVersion = 'N/A'+ Severity = 'Medium'+ CVE = 'N/A'+ Description = "Service '$($service.Name)' is running and may pose security risks"+ RecommendedVersion = 'N/A'+ Remediation = "Disable service if not required: Stop-Service -Name '$($service.Name)' -Force"+ }++ $assessment.Vulnerabilities += $vulnerability+ $assessment.Summary.MediumVulnerabilities++++ Write-Host " [!] Potentially risky service: $($service.Name)" -ForegroundColor Yellow+ }+ }+ }++ # 4. CVE ONLINE LOOKUP (if enabled)+ if ($IncludeCVELookup) {+ Write-Host "`n[4/5] Performing online CVE lookup..." -ForegroundColor Cyan+ Write-Host " Note: This may take several minutes..." -ForegroundColor Gray++ # NVD API endpoint (free, no key required for basic queries)+ $nvdApiBase = "https://services.nvd.nist.gov/rest/json/cves/2.0"++ $checkedApps = 0+ foreach ($app in $vulnerableApps | Select-Object -First 5) {+ try {+ $checkedApps+++ $searchQuery = $app.Name -replace '\s+', '+'++ Write-Host " Checking CVE for: $($app.Name)..." -ForegroundColor Gray++ # Note: Real implementation would need proper API key and rate limiting+ # This is a placeholder for the structure++ Start-Sleep -Milliseconds 500 # Rate limiting+ }+ catch {+ Write-Warning "Could not check CVE for $($app.Name): $_"+ }+ }++ Write-Host " Checked $checkedApps applications against CVE database" -ForegroundColor Gray+ }+ else {+ Write-Host "`n[4/5] Skipping online CVE lookup (disabled)" -ForegroundColor Gray+ }++ # 5. GENERATE RECOMMENDATIONS+ Write-Host "`n[5/5] Generating recommendations..." -ForegroundColor Cyan++ if ($assessment.Summary.CriticalVulnerabilities -gt 0) {+ $assessment.Recommendations += "CRITICAL: $($assessment.Summary.CriticalVulnerabilities) critical vulnerability(ies) detected - patch immediately"+ }++ if ($assessment.Summary.HighVulnerabilities -gt 0) {+ $assessment.Recommendations += "HIGH: $($assessment.Summary.HighVulnerabilities) high-severity vulnerability(ies) - patch within 7 days"+ }++ if ($assessment.Summary.MediumVulnerabilities -gt 0) {+ $assessment.Recommendations += "MEDIUM: $($assessment.Summary.MediumVulnerabilities) medium-severity vulnerability(ies) - patch within 30 days"+ }++ if ($assessment.Summary.VulnerableApplications -eq 0) {+ $assessment.Recommendations += "No known vulnerabilities detected in installed software"+ }++ $assessment.Recommendations += "Enable automatic updates where possible"+ $assessment.Recommendations += "Implement vulnerability scanning schedule (weekly recommended)"+ $assessment.Recommendations += "Subscribe to vendor security bulletins"+ $assessment.Recommendations += "Consider implementing application whitelisting"++ # 6. EXPORT REPORTS+ if ($OutputPath) {+ Write-Host "`n[*] Exporting vulnerability reports..." -ForegroundColor Cyan++ if (-not (Test-Path $OutputPath)) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ }++ $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"+ $reportName = "VulnerabilityAssessment_$timestamp"++ # Export JSON+ if ($Format -in @('JSON', 'All')) {+ $jsonPath = Join-Path $OutputPath "$reportName.json"+ $assessment | ConvertTo-Json -Depth 10 | Out-File $jsonPath -Encoding UTF8+ Write-Host " JSON report saved: $jsonPath" -ForegroundColor Green+ }++ # Export CSV (Vulnerabilities)+ if ($Format -in @('CSV', 'All')) {+ $csvPath = Join-Path $OutputPath "$reportName.csv"+ $assessment.Vulnerabilities | Export-Csv $csvPath -NoTypeInformation+ Write-Host " CSV report saved: $csvPath" -ForegroundColor Green+ }++ # Export HTML+ if ($Format -in @('HTML', 'All')) {+ $htmlPath = Join-Path $OutputPath "$reportName.html"+ $html = Generate-VulnerabilityHTML -Assessment $assessment+ $html | Out-File $htmlPath -Encoding UTF8+ Write-Host " HTML report saved: $htmlPath" -ForegroundColor Green+ }+ }++ }+ catch {+ Write-Error "Error during vulnerability assessment: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== VULNERABILITY ASSESSMENT COMPLETE ===" -ForegroundColor $(+ if ($assessment.Summary.CriticalVulnerabilities -gt 0) { 'Red' }+ elseif ($assessment.Summary.HighVulnerabilities -gt 0) { 'Yellow' }+ else { 'Green' }+ )++ Write-Host "`nSummary:" -ForegroundColor Cyan+ Write-Host " Total Applications: $($assessment.Summary.TotalApplications)" -ForegroundColor White+ Write-Host " Vulnerable Applications: $($assessment.Summary.VulnerableApplications)" -ForegroundColor $(+ if ($assessment.Summary.VulnerableApplications -gt 0) { 'Yellow' } else { 'Green' }+ )+ Write-Host " Critical Vulnerabilities: $($assessment.Summary.CriticalVulnerabilities)" -ForegroundColor $(+ if ($assessment.Summary.CriticalVulnerabilities -gt 0) { 'Red' } else { 'Gray' }+ )+ Write-Host " High Vulnerabilities: $($assessment.Summary.HighVulnerabilities)" -ForegroundColor $(+ if ($assessment.Summary.HighVulnerabilities -gt 0) { 'Yellow' } else { 'Gray' }+ )+ Write-Host " Medium Vulnerabilities: $($assessment.Summary.MediumVulnerabilities)" -ForegroundColor Gray+ Write-Host " Low Vulnerabilities: $($assessment.Summary.LowVulnerabilities)" -ForegroundColor Gray++ if ($assessment.Vulnerabilities.Count -gt 0) {+ Write-Host "`nTop Vulnerabilities:" -ForegroundColor Cyan+ $assessment.Vulnerabilities |+ Sort-Object {+ switch ($_.Severity) {+ 'Critical' { 0 }+ 'High' { 1 }+ 'Medium' { 2 }+ 'Low' { 3 }+ }+ } |+ Select-Object -First 5 |+ ForEach-Object {+ Write-Host " [$($_.Severity)] $($_.Software) - $($_.CVE)" -ForegroundColor $(+ switch ($_.Severity) {+ 'Critical' { 'Red' }+ 'High' { 'Yellow' }+ default { 'Gray' }+ }+ )+ }+ }++ if ($assessment.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $assessment.Recommendations | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ return $assessment+ }+}++# Helper function to generate HTML report+function Generate-VulnerabilityHTML {+ param($Assessment)++ $vulnColor = if($Assessment.Summary.VulnerableApplications -gt 0){'critical'}else{'safe'}++ $html = @"+<!DOCTYPE html>+<html>+<head>+ <title>Vulnerability Assessment - $($Assessment.ComputerName)</title>+ <style>+ body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }+ .container { max-width: 1200px; margin: 0 auto; background: white; padding: 30px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }+ h1 { color: #2c3e50; border-bottom: 3px solid #e74c3c; padding-bottom: 10px; }+ h2 { color: #34495e; margin-top: 30px; }+ .summary { background: #ecf0f1; padding: 20px; border-radius: 5px; margin: 20px 0; }+ .metric { display: inline-block; margin: 10px 20px 10px 0; }+ .metric-label { font-weight: bold; color: #7f8c8d; }+ .metric-value { font-size: 24px; font-weight: bold; }+ .critical { color: #e74c3c; }+ .high { color: #e67e22; }+ .medium { color: #f39c12; }+ .low { color: #95a5a6; }+ .safe { color: #27ae60; }+ table { width: 100%; border-collapse: collapse; margin: 20px 0; }+ th { background: #e74c3c; color: white; padding: 12px; text-align: left; }+ td { padding: 10px; border-bottom: 1px solid #ddd; }+ tr:hover { background: #f8f9fa; }+ .severity-badge { padding: 4px 8px; border-radius: 3px; color: white; font-weight: bold; }+ .severity-critical { background: #e74c3c; }+ .severity-high { background: #e67e22; }+ .severity-medium { background: #f39c12; }+ .severity-low { background: #95a5a6; }+ .footer { margin-top: 40px; padding-top: 20px; border-top: 1px solid #ddd; color: #7f8c8d; font-size: 12px; }+ .no-vuln { color: #27ae60; font-weight: bold; font-size: 16px; padding: 20px; text-align: center; }+ </style>+</head>+<body>+ <div class="container">+ <h1>Vulnerability Assessment Report</h1>+ <p><strong>Computer:</strong> $($Assessment.ComputerName) | <strong>Scan Date:</strong> $($Assessment.ScanDate)</p>+ <p><strong>Scan Depth:</strong> $($Assessment.ScanDepth)</p>++ <div class="summary">+ <h2>Executive Summary</h2>+ <div class="metric">+ <div class="metric-label">Total Applications</div>+ <div class="metric-value">$($Assessment.Summary.TotalApplications)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Vulnerable Applications</div>+ <div class="metric-value $vulnColor">+ $($Assessment.Summary.VulnerableApplications)+ </div>+ </div>+ <div class="metric">+ <div class="metric-label">Critical</div>+ <div class="metric-value critical">$($Assessment.Summary.CriticalVulnerabilities)</div>+ </div>+ <div class="metric">+ <div class="metric-label">High</div>+ <div class="metric-value high">$($Assessment.Summary.HighVulnerabilities)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Medium</div>+ <div class="metric-value medium">$($Assessment.Summary.MediumVulnerabilities)</div>+ </div>+ </div>++ <h2>Detected Vulnerabilities</h2>+"@++ if ($Assessment.Vulnerabilities.Count -gt 0) {+ $html += @"+ <table>+ <tr>+ <th>Severity</th>+ <th>Software</th>+ <th>Current Version</th>+ <th>CVE</th>+ <th>Description</th>+ <th>Remediation</th>+ </tr>+"@++ foreach ($vuln in ($Assessment.Vulnerabilities | Sort-Object {+ switch ($_.Severity) {+ 'Critical' { 0 }+ 'High' { 1 }+ 'Medium' { 2 }+ 'Low' { 3 }+ }+ })) {+ $severityClass = "severity-$($vuln.Severity.ToLower())"+ $software = $vuln.Software -replace '<', '<' -replace '>', '>'+ $desc = $vuln.Description -replace '<', '<' -replace '>', '>'+ $rem = $vuln.Remediation -replace '<', '<' -replace '>', '>'++ $html += @"+ <tr>+ <td><span class="severity-badge $severityClass">$($vuln.Severity)</span></td>+ <td><strong>$software</strong></td>+ <td>$($vuln.CurrentVersion)</td>+ <td>$($vuln.CVE)</td>+ <td>$desc</td>+ <td>$rem</td>+ </tr>+"@+ }++ $html += " </table>`n"+ }+ else {+ $html += " <p class=`"no-vuln`">No known vulnerabilities detected</p>`n"+ }++ $html += " `n <h2>Recommendations</h2>`n <ul>`n"++ foreach ($rec in $Assessment.Recommendations) {+ $recEscaped = $rec -replace '<', '<' -replace '>', '>'+ $html += " <li>$recEscaped</li>`n"+ }++ $currentDate = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'++ $html += @"+ </ul>++ <div class="footer">+ Generated by WindowsSecurityAudit Module | Vulnerability Assessment | $currentDate+ </div>+ </div>+</body>+</html>+"@++ return $html+}\ No newline at end of filediff --git a/Vulnerability/Test-CertificateHealth.ps1 b/Vulnerability/Test-CertificateHealth.ps1new file mode 100644index 0000000..4ecf60d--- /dev/null+++ b/Vulnerability/Test-CertificateHealth.ps1@@ -0,0 +1,620 @@+function Test-CertificateHealth {+ <#+ .SYNOPSIS+ Tests certificate health and identifies expiring or invalid certificates+ .DESCRIPTION+ Scans system certificates, identifies expired, expiring, weak, or invalid+ certificates across multiple certificate stores. Provides detailed findings+ with remediation steps for certificate management.+ .PARAMETER ExpiringDays+ Number of days to check for expiring certificates (default: 30)+ .PARAMETER IncludeUserStore+ Include current user certificate store in scan+ .PARAMETER CheckRevocation+ Check certificate revocation status (slower)+ .PARAMETER OutputPath+ Path to save certificate health report+ .PARAMETER Format+ Report format: HTML, JSON, CSV, or All+ .EXAMPLE+ Test-CertificateHealth+ Test-CertificateHealth -ExpiringDays 60 -IncludeUserStore -OutputPath "C:\Reports"+ .OUTPUTS+ PSCustomObject with certificate health findings+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [int]$ExpiringDays = 30,++ [Parameter()]+ [switch]$IncludeUserStore,++ [Parameter()]+ [switch]$CheckRevocation,++ [Parameter()]+ [string]$OutputPath,++ [Parameter()]+ [ValidateSet('HTML', 'JSON', 'CSV', 'All')]+ [string]$Format = 'HTML'+ )++ begin {+ Write-Host "=== CERTIFICATE HEALTH CHECK ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow+ Write-Host "Expiring Threshold: $ExpiringDays days" -ForegroundColor Yellow+ Write-Host "Include User Store: $(if($IncludeUserStore){'Yes'}else{'No'})" -ForegroundColor Yellow+ Write-Host "Check Revocation: $(if($CheckRevocation){'Yes'}else{'No'})" -ForegroundColor Yellow++ $results = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ TotalCertificates = 0+ HealthyCertificates = 0+ Issues = @()+ Summary = @{+ Expired = 0+ ExpiringSoon = 0+ SelfSigned = 0+ WeakSignature = 0+ Revoked = 0+ InvalidChain = 0+ DuplicateThumbprints = 0+ }+ Recommendations = @()+ }++ # Weak signature algorithms+ $weakAlgorithms = @('md5', 'sha1')+ }++ process {+ try {+ # Define certificate stores to scan+ $storesToScan = @(+ @{Location='LocalMachine'; Stores=@('My', 'Root', 'CA', 'TrustedPublisher', 'WebHosting')}+ )++ if ($IncludeUserStore) {+ $storesToScan += @{Location='CurrentUser'; Stores=@('My', 'Root', 'CA', 'TrustedPublisher')}+ }++ Write-Host "`n[1/3] Scanning certificate stores..." -ForegroundColor Cyan++ $allCertificates = @()+ $currentDate = Get-Date+ $expiringThreshold = $currentDate.AddDays($ExpiringDays)++ foreach ($storeConfig in $storesToScan) {+ $location = $storeConfig.Location++ foreach ($storeName in $storeConfig.Stores) {+ try {+ Write-Host " Scanning: $location\$storeName..." -ForegroundColor Gray++ $store = New-Object System.Security.Cryptography.X509Certificates.X509Store($storeName, $location)+ $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly)++ $certificates = $store.Certificates++ foreach ($cert in $certificates) {+ $certInfo = [PSCustomObject]@{+ Store = "$location\$storeName"+ Subject = $cert.Subject+ Issuer = $cert.Issuer+ Thumbprint = $cert.Thumbprint+ NotBefore = $cert.NotBefore+ NotAfter = $cert.NotAfter+ SignatureAlgorithm = $cert.SignatureAlgorithm.FriendlyName+ HasPrivateKey = $cert.HasPrivateKey+ IsSelfSigned = ($cert.Subject -eq $cert.Issuer)+ Status = 'Healthy'+ }++ $allCertificates += $certInfo+ }++ $store.Close()+ }+ catch {+ # FIXED: Remove colon from warning message+ Write-Warning "Could not access store $location\$storeName - $_"+ }+ }+ }++ $results.TotalCertificates = $allCertificates.Count+ Write-Host " Found $($allCertificates.Count) certificates" -ForegroundColor Green++ # 2. ANALYZE CERTIFICATES+ Write-Host "`n[2/3] Analyzing certificates..." -ForegroundColor Cyan++ # Check for expired certificates+ $expired = $allCertificates | Where-Object { $_.NotAfter -lt $currentDate }+ foreach ($cert in $expired) {+ $daysExpired = [Math]::Round(($currentDate - $cert.NotAfter).TotalDays)++ $results.Issues += [PSCustomObject]@{+ Severity = 'High'+ Category = 'Expired'+ Certificate = $cert.Subject+ Store = $cert.Store+ Thumbprint = $cert.Thumbprint+ Issue = "Certificate expired $daysExpired days ago"+ NotAfter = $cert.NotAfter.ToString('yyyy-MM-dd')+ Remediation = "Remove expired certificate or renew - Remove-Item Cert:\$($cert.Store)\$($cert.Thumbprint)"+ }++ $results.Summary.Expired+++ Write-Host " [!] HIGH: Expired certificate - $($cert.Subject)" -ForegroundColor Yellow+ }++ # Check for expiring certificates+ $expiring = $allCertificates | Where-Object {+ $_.NotAfter -gt $currentDate -and+ $_.NotAfter -le $expiringThreshold+ }++ foreach ($cert in $expiring) {+ $daysUntilExpiry = [Math]::Round(($cert.NotAfter - $currentDate).TotalDays)++ $results.Issues += [PSCustomObject]@{+ Severity = if($daysUntilExpiry -le 7){'High'}elseif($daysUntilExpiry -le 14){'Medium'}else{'Low'}+ Category = 'Expiring Soon'+ Certificate = $cert.Subject+ Store = $cert.Store+ Thumbprint = $cert.Thumbprint+ Issue = "Certificate expires in $daysUntilExpiry days"+ NotAfter = $cert.NotAfter.ToString('yyyy-MM-dd')+ Remediation = "Renew certificate before expiration"+ }++ $results.Summary.ExpiringSoon++++ $color = if($daysUntilExpiry -le 7){'Yellow'}else{'Gray'}+ Write-Host " [*] Expiring: $($cert.Subject) - $daysUntilExpiry days" -ForegroundColor $color+ }++ # Check for self-signed certificates in sensitive stores+ $sensitiveStores = @('LocalMachine\My', 'LocalMachine\WebHosting')+ $selfSignedInSensitive = $allCertificates | Where-Object {+ $_.IsSelfSigned -and+ $_.Store -in $sensitiveStores+ }++ foreach ($cert in $selfSignedInSensitive) {+ $results.Issues += [PSCustomObject]@{+ Severity = 'Medium'+ Category = 'Self-Signed'+ Certificate = $cert.Subject+ Store = $cert.Store+ Thumbprint = $cert.Thumbprint+ Issue = "Self-signed certificate in production store"+ NotAfter = $cert.NotAfter.ToString('yyyy-MM-dd')+ Remediation = "Replace with CA-issued certificate for production use"+ }++ $results.Summary.SelfSigned+++ Write-Host " [*] Self-signed certificate: $($cert.Subject)" -ForegroundColor Gray+ }++ # Check for weak signature algorithms+ foreach ($cert in $allCertificates) {+ $isWeak = $false+ foreach ($weakAlg in $weakAlgorithms) {+ if ($cert.SignatureAlgorithm -like "*$weakAlg*") {+ $isWeak = $true+ break+ }+ }++ if ($isWeak) {+ $results.Issues += [PSCustomObject]@{+ Severity = 'High'+ Category = 'Weak Signature'+ Certificate = $cert.Subject+ Store = $cert.Store+ Thumbprint = $cert.Thumbprint+ Issue = "Uses weak signature algorithm - $($cert.SignatureAlgorithm)"+ NotAfter = $cert.NotAfter.ToString('yyyy-MM-dd')+ Remediation = "Replace with certificate using SHA-256 or stronger"+ }++ $results.Summary.WeakSignature+++ Write-Host " [!] HIGH: Weak signature - $($cert.Subject) ($($cert.SignatureAlgorithm))" -ForegroundColor Yellow+ }+ }++ # Check for duplicate thumbprints across stores+ $thumbprintGroups = $allCertificates | Group-Object Thumbprint | Where-Object { $_.Count -gt 1 }+ foreach ($group in $thumbprintGroups) {+ $duplicates = $group.Group+ $stores = ($duplicates | Select-Object -ExpandProperty Store) -join ', '++ $results.Issues += [PSCustomObject]@{+ Severity = 'Low'+ Category = 'Duplicate'+ Certificate = $duplicates[0].Subject+ Store = $stores+ Thumbprint = $group.Name+ Issue = "Certificate duplicated in $($group.Count) stores"+ NotAfter = $duplicates[0].NotAfter.ToString('yyyy-MM-dd')+ Remediation = "Review and remove unnecessary duplicates"+ }++ $results.Summary.DuplicateThumbprints+++ }++ # Check certificate chain validity (for LocalMachine\My)+ Write-Host " Validating certificate chains..." -ForegroundColor Gray++ $myStoreCerts = $allCertificates | Where-Object {+ $_.Store -eq 'LocalMachine\My' -and+ $_.NotAfter -gt $currentDate+ }++ foreach ($certInfo in $myStoreCerts) {+ try {+ $store = New-Object System.Security.Cryptography.X509Certificates.X509Store('My', 'LocalMachine')+ $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly)++ $cert = $store.Certificates | Where-Object { $_.Thumbprint -eq $certInfo.Thumbprint } | Select-Object -First 1++ if ($cert) {+ $chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain+ $chain.ChainPolicy.RevocationMode = if($CheckRevocation){+ [System.Security.Cryptography.X509Certificates.X509RevocationMode]::Online+ } else {+ [System.Security.Cryptography.X509Certificates.X509RevocationMode]::NoCheck+ }++ $isValid = $chain.Build($cert)++ if (-not $isValid) {+ $chainErrors = $chain.ChainStatus | ForEach-Object { $_.StatusInformation } | Select-Object -Unique+ $errorMsg = $chainErrors -join '; '++ # Check if it's a revocation error+ if ($CheckRevocation -and $errorMsg -match 'revok') {+ $results.Issues += [PSCustomObject]@{+ Severity = 'Critical'+ Category = 'Revoked'+ Certificate = $certInfo.Subject+ Store = $certInfo.Store+ Thumbprint = $certInfo.Thumbprint+ Issue = "Certificate has been revoked"+ NotAfter = $certInfo.NotAfter.ToString('yyyy-MM-dd')+ Remediation = "Remove revoked certificate immediately and replace"+ }++ $results.Summary.Revoked+++ Write-Host " [!] CRITICAL: Revoked certificate - $($certInfo.Subject)" -ForegroundColor Red+ }+ else {+ $results.Issues += [PSCustomObject]@{+ Severity = 'Medium'+ Category = 'Invalid Chain'+ Certificate = $certInfo.Subject+ Store = $certInfo.Store+ Thumbprint = $certInfo.Thumbprint+ Issue = "Certificate chain validation failed - $errorMsg"+ NotAfter = $certInfo.NotAfter.ToString('yyyy-MM-dd')+ Remediation = "Install intermediate CA certificates or verify root CA trust"+ }++ $results.Summary.InvalidChain+++ }+ }++ $chain.Dispose()+ }++ $store.Close()+ }+ catch {+ Write-Warning "Could not validate chain for $($certInfo.Subject) - $_"+ }+ }++ $results.HealthyCertificates = $results.TotalCertificates - $results.Issues.Count++ # 3. GENERATE RECOMMENDATIONS+ Write-Host "`n[3/3] Generating recommendations..." -ForegroundColor Cyan++ if ($results.Summary.Revoked -gt 0) {+ $results.Recommendations += "CRITICAL: Remove $($results.Summary.Revoked) revoked certificate(s) immediately"+ }++ if ($results.Summary.Expired -gt 0) {+ $results.Recommendations += "HIGH: Remove or renew $($results.Summary.Expired) expired certificate(s)"+ }++ if ($results.Summary.WeakSignature -gt 0) {+ $results.Recommendations += "HIGH: Replace $($results.Summary.WeakSignature) certificate(s) using weak signature algorithms"+ }++ if ($results.Summary.ExpiringSoon -gt 0) {+ $results.Recommendations += "Plan renewal for $($results.Summary.ExpiringSoon) expiring certificate(s)"+ }++ if ($results.Summary.InvalidChain -gt 0) {+ $results.Recommendations += "Fix certificate chain issues for $($results.Summary.InvalidChain) certificate(s)"+ }++ if ($results.Summary.SelfSigned -gt 0) {+ $results.Recommendations += "Replace self-signed certificates with CA-issued certificates for production"+ }++ if ($results.Issues.Count -eq 0) {+ $results.Recommendations += "All certificates are healthy - maintain regular monitoring"+ }++ $results.Recommendations += "Implement automated certificate renewal (e.g., ACME/Let's Encrypt)"+ $results.Recommendations += "Set up certificate expiration alerts (60, 30, 14, 7 days)"+ $results.Recommendations += "Enable certificate revocation checking in production"+ $results.Recommendations += "Document certificate inventory and ownership"+ $results.Recommendations += "Remove unused and expired certificates quarterly"++ # 4. EXPORT REPORTS+ if ($OutputPath) {+ Write-Host "`n[*] Exporting certificate health reports..." -ForegroundColor Cyan++ if (-not (Test-Path $OutputPath)) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ }++ $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"+ $reportName = "CertificateHealth_$timestamp"++ # Export JSON+ if ($Format -in @('JSON', 'All')) {+ $jsonPath = Join-Path $OutputPath "$reportName.json"+ $results | ConvertTo-Json -Depth 10 | Out-File $jsonPath -Encoding UTF8+ Write-Host " JSON report saved: $jsonPath" -ForegroundColor Green+ }++ # Export CSV+ if ($Format -in @('CSV', 'All')) {+ $csvPath = Join-Path $OutputPath "$reportName.csv"+ $results.Issues | Export-Csv $csvPath -NoTypeInformation+ Write-Host " CSV report saved: $csvPath" -ForegroundColor Green+ }++ # Export HTML+ if ($Format -in @('HTML', 'All')) {+ $htmlPath = Join-Path $OutputPath "$reportName.html"+ $html = Generate-CertificateHealthHTML -Results $results+ $html | Out-File $htmlPath -Encoding UTF8+ Write-Host " HTML report saved: $htmlPath" -ForegroundColor Green+ }+ }++ }+ catch {+ Write-Error "Error during certificate health check: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== CERTIFICATE HEALTH CHECK COMPLETE ===" -ForegroundColor $(+ if ($results.Summary.Revoked -gt 0) { 'Red' }+ elseif ($results.Summary.Expired -gt 0 -or $results.Summary.WeakSignature -gt 0) { 'Yellow' }+ else { 'Green' }+ )++ Write-Host "`nSummary:" -ForegroundColor Cyan+ Write-Host " Total Certificates: $($results.TotalCertificates)" -ForegroundColor White+ Write-Host " Healthy: $($results.HealthyCertificates)" -ForegroundColor Green+ Write-Host " Issues Found: $($results.Issues.Count)" -ForegroundColor $(+ if ($results.Issues.Count -gt 0) { 'Yellow' } else { 'Green' }+ )++ if ($results.Summary.Revoked -gt 0) {+ Write-Host " Revoked: $($results.Summary.Revoked)" -ForegroundColor Red+ }+ if ($results.Summary.Expired -gt 0) {+ Write-Host " Expired: $($results.Summary.Expired)" -ForegroundColor Yellow+ }+ if ($results.Summary.ExpiringSoon -gt 0) {+ Write-Host " Expiring Soon: $($results.Summary.ExpiringSoon)" -ForegroundColor Yellow+ }+ if ($results.Summary.WeakSignature -gt 0) {+ Write-Host " Weak Signatures: $($results.Summary.WeakSignature)" -ForegroundColor Yellow+ }+ if ($results.Summary.InvalidChain -gt 0) {+ Write-Host " Invalid Chains: $($results.Summary.InvalidChain)" -ForegroundColor Gray+ }+ if ($results.Summary.SelfSigned -gt 0) {+ Write-Host " Self-Signed: $($results.Summary.SelfSigned)" -ForegroundColor Gray+ }++ if ($results.Issues.Count -gt 0) {+ Write-Host "`nTop Issues:" -ForegroundColor Cyan+ $results.Issues |+ Sort-Object {+ switch ($_.Severity) {+ 'Critical' { 0 }+ 'High' { 1 }+ 'Medium' { 2 }+ 'Low' { 3 }+ }+ } |+ Select-Object -First 10 |+ ForEach-Object {+ $color = switch ($_.Severity) {+ 'Critical' { 'Red' }+ 'High' { 'Yellow' }+ default { 'Gray' }+ }+ Write-Host " [$($_.Severity)] $($_.Category) - $($_.Certificate)" -ForegroundColor $color+ }+ }++ if ($results.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $results.Recommendations | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ return $results+ }+}++# Helper function to generate HTML report+function Generate-CertificateHealthHTML {+ param($Results)++ $healthColor = if($Results.Summary.Revoked -gt 0){'critical'}+ elseif($Results.Summary.Expired -gt 0 -or $Results.Summary.WeakSignature -gt 0){'high'}+ else{'safe'}++ $html = @"+<!DOCTYPE html>+<html>+<head>+ <title>Certificate Health Report - $($Results.ComputerName)</title>+ <style>+ body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }+ .container { max-width: 1400px; margin: 0 auto; background: white; padding: 30px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }+ h1 { color: #2c3e50; border-bottom: 3px solid #3498db; padding-bottom: 10px; }+ h2 { color: #34495e; margin-top: 30px; }+ .summary { background: #ecf0f1; padding: 20px; border-radius: 5px; margin: 20px 0; }+ .metric { display: inline-block; margin: 10px 20px 10px 0; }+ .metric-label { font-weight: bold; color: #7f8c8d; }+ .metric-value { font-size: 24px; font-weight: bold; }+ .critical { color: #e74c3c; }+ .high { color: #e67e22; }+ .medium { color: #f39c12; }+ .low { color: #95a5a6; }+ .safe { color: #27ae60; }+ table { width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 13px; }+ th { background: #3498db; color: white; padding: 10px; text-align: left; }+ td { padding: 8px; border-bottom: 1px solid #ddd; vertical-align: top; }+ tr:hover { background: #f8f9fa; }+ .severity-badge { padding: 3px 6px; border-radius: 3px; color: white; font-weight: bold; font-size: 11px; }+ .severity-critical { background: #e74c3c; }+ .severity-high { background: #e67e22; }+ .severity-medium { background: #f39c12; }+ .severity-low { background: #95a5a6; }+ .footer { margin-top: 40px; padding-top: 20px; border-top: 1px solid #ddd; color: #7f8c8d; font-size: 12px; }+ .no-issues { color: #27ae60; font-weight: bold; font-size: 16px; padding: 20px; text-align: center; }+ .thumbprint { font-family: monospace; font-size: 11px; color: #7f8c8d; }+ </style>+</head>+<body>+ <div class="container">+ <h1>Certificate Health Report</h1>+ <p><strong>Computer:</strong> $($Results.ComputerName) | <strong>Scan Date:</strong> $($Results.ScanDate)</p>++ <div class="summary">+ <h2>Summary</h2>+ <div class="metric">+ <div class="metric-label">Total Certificates</div>+ <div class="metric-value">$($Results.TotalCertificates)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Healthy</div>+ <div class="metric-value safe">$($Results.HealthyCertificates)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Issues</div>+ <div class="metric-value $(if($Results.Issues.Count -gt 0){'high'}else{'safe'})">+ $($Results.Issues.Count)+ </div>+ </div>+ <div class="metric">+ <div class="metric-label">Expired</div>+ <div class="metric-value high">$($Results.Summary.Expired)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Expiring Soon</div>+ <div class="metric-value medium">$($Results.Summary.ExpiringSoon)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Weak Signature</div>+ <div class="metric-value high">$($Results.Summary.WeakSignature)</div>+ </div>+ </div>++ <h2>Certificate Issues</h2>+"@++ if ($Results.Issues.Count -gt 0) {+ $html += @"+ <table>+ <tr>+ <th style="width: 70px;">Severity</th>+ <th style="width: 100px;">Category</th>+ <th style="width: 250px;">Certificate</th>+ <th style="width: 150px;">Store</th>+ <th style="width: 100px;">Expires</th>+ <th>Issue</th>+ <th>Remediation</th>+ </tr>+"@++ foreach ($issue in ($Results.Issues | Sort-Object {+ switch ($_.Severity) {+ 'Critical' { 0 }+ 'High' { 1 }+ 'Medium' { 2 }+ 'Low' { 3 }+ }+ })) {+ $severityClass = "severity-$($issue.Severity.ToLower())"+ $cert = $issue.Certificate -replace '<', '<' -replace '>', '>'+ $issueText = $issue.Issue -replace '<', '<' -replace '>', '>'+ $remediation = $issue.Remediation -replace '<', '<' -replace '>', '>'++ $thumbShort = if($issue.Thumbprint.Length -gt 16) {+ $issue.Thumbprint.Substring(0,16) + '...'+ } else {+ $issue.Thumbprint+ }++ $html += @"+ <tr>+ <td><span class="severity-badge $severityClass">$($issue.Severity)</span></td>+ <td>$($issue.Category)</td>+ <td><strong>$cert</strong><br><span class="thumbprint">$thumbShort</span></td>+ <td><small>$($issue.Store)</small></td>+ <td>$($issue.NotAfter)</td>+ <td>$issueText</td>+ <td><small>$remediation</small></td>+ </tr>+"@+ }++ $html += " </table>`n"+ }+ else {+ $html += " <p class=`"no-issues`">All certificates are healthy</p>`n"+ }++ $html += " `n <h2>Recommendations</h2>`n <ul>`n"++ foreach ($rec in $Results.Recommendations) {+ $recEscaped = $rec -replace '<', '<' -replace '>', '>'+ $html += " <li>$recEscaped</li>`n"+ }++ $currentDate = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'++ $html += @"+ </ul>++ <div class="footer">+ Generated by WindowsSecurityAudit Module | Certificate Health Check | $currentDate+ </div>+ </div>+</body>+</html>+"@++ return $html+}\ No newline at end of filediff --git a/Vulnerability/Test-PatchCompliance.ps1 b/Vulnerability/Test-PatchCompliance.ps1new file mode 100644index 0000000..762c1fb--- /dev/null+++ b/Vulnerability/Test-PatchCompliance.ps1@@ -0,0 +1,547 @@+function Test-PatchCompliance {+ <#+ .SYNOPSIS+ Tests Windows patch compliance and identifies missing security updates+ .DESCRIPTION+ Scans for missing Windows updates, security patches, and critical updates.+ Identifies compliance status and provides patch installation recommendations.+ .PARAMETER IncludeOptional+ Include optional updates in the scan+ .PARAMETER DaysOld+ Flag updates older than specified days as critical (default: 30)+ .PARAMETER OutputPath+ Path to save patch compliance report+ .PARAMETER Format+ Report format: HTML, JSON, CSV, or All+ .EXAMPLE+ Test-PatchCompliance+ Test-PatchCompliance -IncludeOptional -DaysOld 60 -OutputPath "C:\Reports"+ .OUTPUTS+ PSCustomObject with patch compliance results+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$IncludeOptional,++ [Parameter()]+ [int]$DaysOld = 30,++ [Parameter()]+ [string]$OutputPath,++ [Parameter()]+ [ValidateSet('HTML', 'JSON', 'CSV', 'All')]+ [string]$Format = 'HTML'+ )++ begin {+ Write-Host "=== PATCH COMPLIANCE TEST ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow+ Write-Host "Include Optional Updates: $(if($IncludeOptional){'Yes'}else{'No'})" -ForegroundColor Yellow+ Write-Host "Critical Age Threshold: $DaysOld days" -ForegroundColor Yellow++ $compliance = [PSCustomObject]@{+ ScanDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ OSVersion = (Get-CimInstance Win32_OperatingSystem).Caption+ LastBootTime = (Get-CimInstance Win32_OperatingSystem).LastBootUpTime+ WindowsUpdateEnabled = $false+ AutoUpdateEnabled = $false+ InstalledUpdates = @()+ MissingUpdates = @()+ Summary = @{+ TotalInstalled = 0+ TotalMissing = 0+ CriticalMissing = 0+ ImportantMissing = 0+ ModerateMissing = 0+ LowMissing = 0+ OldestMissingDays = 0+ ComplianceScore = 0+ }+ Recommendations = @()+ }+ }++ process {+ try {+ # 1. CHECK WINDOWS UPDATE SERVICE+ Write-Host "`n[1/5] Checking Windows Update service..." -ForegroundColor Cyan++ $wuService = Get-Service -Name wuauserv -ErrorAction SilentlyContinue+ if ($wuService) {+ $compliance.WindowsUpdateEnabled = ($wuService.Status -eq 'Running')+ Write-Host " Windows Update Service: $($wuService.Status)" -ForegroundColor $(+ if ($wuService.Status -eq 'Running') { 'Green' } else { 'Red' }+ )+ }++ # Check auto-update settings+ try {+ $auSettings = (New-Object -ComObject Microsoft.Update.AutoUpdate).Settings+ $compliance.AutoUpdateEnabled = ($auSettings.NotificationLevel -ge 3)+ Write-Host " Auto-Update Level: $($auSettings.NotificationLevel)" -ForegroundColor $(+ if ($auSettings.NotificationLevel -ge 3) { 'Green' } else { 'Yellow' }+ )+ }+ catch {+ Write-Warning "Could not determine auto-update settings"+ }++ # 2. GET INSTALLED UPDATES+ Write-Host "`n[2/5] Retrieving installed updates..." -ForegroundColor Cyan++ try {+ $session = New-Object -ComObject Microsoft.Update.Session+ $searcher = $session.CreateUpdateSearcher()++ Write-Host " Querying update history (this may take a moment)..." -ForegroundColor Gray++ $historyCount = $searcher.GetTotalHistoryCount()+ if ($historyCount -gt 0) {+ $history = $searcher.QueryHistory(0, [Math]::Min($historyCount, 500))++ foreach ($update in $history) {+ if ($update.ResultCode -eq 2) { # Succeeded+ $compliance.InstalledUpdates += [PSCustomObject]@{+ Title = $update.Title+ Date = $update.Date+ KB = if ($update.Title -match 'KB(\d+)') { $matches[1] } else { 'N/A' }+ }+ }+ }++ $compliance.Summary.TotalInstalled = $compliance.InstalledUpdates.Count+ Write-Host " Found $($compliance.Summary.TotalInstalled) installed updates" -ForegroundColor Green+ }+ }+ catch {+ Write-Warning "Error retrieving installed updates: $_"+ }++ # 3. SCAN FOR MISSING UPDATES+ Write-Host "`n[3/5] Scanning for missing updates..." -ForegroundColor Cyan+ Write-Host " This may take several minutes..." -ForegroundColor Gray++ try {+ $session = New-Object -ComObject Microsoft.Update.Session+ $searcher = $session.CreateUpdateSearcher()++ # Search criteria+ $criteria = "IsInstalled=0"+ if (-not $IncludeOptional) {+ $criteria += " and Type='Software'"+ }++ Write-Host " Searching with criteria: $criteria" -ForegroundColor Gray+ $searchResult = $searcher.Search($criteria)++ $updateCount = $searchResult.Updates.Count+ Write-Host " Found $updateCount missing update(s)" -ForegroundColor $(+ if ($updateCount -eq 0) { 'Green' } else { 'Yellow' }+ )++ # Process missing updates+ foreach ($update in $searchResult.Updates) {+ # Determine severity - FIXED: Safe property access+ $severity = 'Low'+ if ($null -ne $update.PSObject.Properties['MsrcSeverity'] -and $update.MsrcSeverity) {+ $severity = $update.MsrcSeverity+ }+ elseif ($update.Title -match 'Critical|Security') {+ $severity = 'Critical'+ }+ elseif ($update.Title -match 'Important') {+ $severity = 'Important'+ }++ # Extract KB number+ $kbNumber = 'N/A'+ if ($update.Title -match 'KB(\d+)') {+ $kbNumber = "KB$($matches[1])"+ }++ # Calculate age - FIXED: Safe property access+ $releaseDate = if ($null -ne $update.PSObject.Properties['LastDeploymentChangeTime']) {+ $update.LastDeploymentChangeTime+ } else {+ $null+ }++ $ageInDays = if ($releaseDate) {+ [Math]::Round(((Get-Date) - $releaseDate).TotalDays)+ } else { 0 }++ if ($ageInDays -gt $compliance.Summary.OldestMissingDays) {+ $compliance.Summary.OldestMissingDays = $ageInDays+ }++ # FIXED: Safe property access for all optional properties+ $description = if ($null -ne $update.PSObject.Properties['Description']) {+ $update.Description+ } else {+ 'No description available'+ }++ $maxDownloadSize = if ($null -ne $update.PSObject.Properties['MaxDownloadSize']) {+ [Math]::Round($update.MaxDownloadSize / 1MB, 2)+ } else {+ 0+ }++ $isSuperseded = if ($null -ne $update.PSObject.Properties['IsSuperseded']) {+ $update.IsSuperseded+ } else {+ $false+ }++ $rebootRequired = if ($null -ne $update.PSObject.Properties['RebootRequired']) {+ $update.RebootRequired+ } else {+ $false+ }++ $categories = if ($null -ne $update.PSObject.Properties['Categories']) {+ ($update.Categories | ForEach-Object { $_.Name }) -join ', '+ } else {+ 'Unknown'+ }++ $missingUpdate = [PSCustomObject]@{+ Title = $update.Title+ KB = $kbNumber+ Severity = $severity+ Description = $description+ ReleaseDate = $releaseDate+ AgeInDays = $ageInDays+ Size = $maxDownloadSize+ IsSuperseded = $isSuperseded+ RebootRequired = $rebootRequired+ Categories = $categories+ }++ $compliance.MissingUpdates += $missingUpdate++ # Update counters+ switch ($severity) {+ 'Critical' { $compliance.Summary.CriticalMissing++ }+ 'Important' { $compliance.Summary.ImportantMissing++ }+ 'Moderate' { $compliance.Summary.ModerateMissing++ }+ 'Low' { $compliance.Summary.LowMissing++ }+ }++ # Display critical/important updates+ if ($severity -in @('Critical', 'Important')) {+ $color = if ($severity -eq 'Critical') { 'Red' } else { 'Yellow' }+ Write-Host " [!] $severity - $kbNumber - $($update.Title.Substring(0, [Math]::Min(60, $update.Title.Length)))..." -ForegroundColor $color+ }+ }++ $compliance.Summary.TotalMissing = $compliance.MissingUpdates.Count+ }+ catch {+ Write-Error "Error scanning for missing updates: $_"+ $compliance.Summary.TotalMissing = -1 # Indicates scan failure+ }++ # 4. CALCULATE COMPLIANCE SCORE+ Write-Host "`n[4/5] Calculating compliance score..." -ForegroundColor Cyan++ $score = 100++ # Deduct points for missing updates+ $score -= ($compliance.Summary.CriticalMissing * 15)+ $score -= ($compliance.Summary.ImportantMissing * 10)+ $score -= ($compliance.Summary.ModerateMissing * 5)+ $score -= ($compliance.Summary.LowMissing * 2)++ # Deduct points for old missing updates+ if ($compliance.Summary.OldestMissingDays -gt $DaysOld) {+ $score -= 10+ }++ # Deduct points if auto-update disabled+ if (-not $compliance.AutoUpdateEnabled) {+ $score -= 10+ }++ # Ensure score is between 0-100+ $compliance.Summary.ComplianceScore = [Math]::Max(0, [Math]::Min(100, $score))++ Write-Host " Compliance Score: $($compliance.Summary.ComplianceScore)%" -ForegroundColor $(+ if ($compliance.Summary.ComplianceScore -ge 80) { 'Green' }+ elseif ($compliance.Summary.ComplianceScore -ge 60) { 'Yellow' }+ else { 'Red' }+ )++ # 5. GENERATE RECOMMENDATIONS+ Write-Host "`n[5/5] Generating recommendations..." -ForegroundColor Cyan++ if ($compliance.Summary.CriticalMissing -gt 0) {+ $compliance.Recommendations += "CRITICAL: Install $($compliance.Summary.CriticalMissing) critical security update(s) immediately"+ }++ if ($compliance.Summary.ImportantMissing -gt 0) {+ $compliance.Recommendations += "IMPORTANT: Install $($compliance.Summary.ImportantMissing) important update(s) within 7 days"+ }++ if ($compliance.Summary.OldestMissingDays -gt $DaysOld) {+ $compliance.Recommendations += "WARNING: Oldest missing update is $($compliance.Summary.OldestMissingDays) days old"+ }++ if (-not $compliance.AutoUpdateEnabled) {+ $compliance.Recommendations += "Enable automatic updates for security patches"+ }++ if (-not $compliance.WindowsUpdateEnabled) {+ $compliance.Recommendations += "Start Windows Update service: Start-Service wuauserv"+ }++ if ($compliance.Summary.TotalMissing -eq 0) {+ $compliance.Recommendations += "System is fully patched - maintain regular update schedule"+ }++ $compliance.Recommendations += "Schedule monthly patch maintenance window"+ $compliance.Recommendations += "Test updates in non-production environment first"+ $compliance.Recommendations += "Maintain patch deployment documentation"++ # 6. EXPORT REPORTS+ if ($OutputPath) {+ Write-Host "`n[*] Exporting patch compliance reports..." -ForegroundColor Cyan++ if (-not (Test-Path $OutputPath)) {+ New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null+ }++ $timestamp = Get-Date -Format "yyyyMMdd_HHmmss"+ $reportName = "PatchCompliance_$timestamp"++ # Export JSON+ if ($Format -in @('JSON', 'All')) {+ $jsonPath = Join-Path $OutputPath "$reportName.json"+ $compliance | ConvertTo-Json -Depth 10 | Out-File $jsonPath -Encoding UTF8+ Write-Host " JSON report saved: $jsonPath" -ForegroundColor Green+ }++ # Export CSV (Missing Updates)+ if ($Format -in @('CSV', 'All')) {+ $csvPath = Join-Path $OutputPath "$reportName.csv"+ $compliance.MissingUpdates | Export-Csv $csvPath -NoTypeInformation+ Write-Host " CSV report saved: $csvPath" -ForegroundColor Green+ }++ # Export HTML+ if ($Format -in @('HTML', 'All')) {+ $htmlPath = Join-Path $OutputPath "$reportName.html"+ $html = Generate-PatchComplianceHTML -Compliance $compliance+ $html | Out-File $htmlPath -Encoding UTF8+ Write-Host " HTML report saved: $htmlPath" -ForegroundColor Green+ }+ }++ }+ catch {+ Write-Error "Error during patch compliance test: $_"+ throw+ }+ }++ end {+ Write-Host "`n=== PATCH COMPLIANCE TEST COMPLETE ===" -ForegroundColor $(+ if ($compliance.Summary.ComplianceScore -ge 80) { 'Green' }+ elseif ($compliance.Summary.ComplianceScore -ge 60) { 'Yellow' }+ else { 'Red' }+ )++ Write-Host "`nCompliance Summary:" -ForegroundColor Cyan+ Write-Host " OS Version: $($compliance.OSVersion)" -ForegroundColor White+ Write-Host " Last Boot: $($compliance.LastBootTime)" -ForegroundColor White+ Write-Host " Installed Updates: $($compliance.Summary.TotalInstalled)" -ForegroundColor Green+ Write-Host " Missing Updates: $($compliance.Summary.TotalMissing)" -ForegroundColor $(+ if ($compliance.Summary.TotalMissing -eq 0) { 'Green' } else { 'Yellow' }+ )+ Write-Host " Critical Missing: $($compliance.Summary.CriticalMissing)" -ForegroundColor $(+ if ($compliance.Summary.CriticalMissing -gt 0) { 'Red' } else { 'Gray' }+ )+ Write-Host " Important Missing: $($compliance.Summary.ImportantMissing)" -ForegroundColor $(+ if ($compliance.Summary.ImportantMissing -gt 0) { 'Yellow' } else { 'Gray' }+ )+ Write-Host " Compliance Score: $($compliance.Summary.ComplianceScore)%" -ForegroundColor $(+ if ($compliance.Summary.ComplianceScore -ge 80) { 'Green' }+ elseif ($compliance.Summary.ComplianceScore -ge 60) { 'Yellow' }+ else { 'Red' }+ )++ if ($compliance.MissingUpdates.Count -gt 0) {+ Write-Host "`nTop Missing Updates:" -ForegroundColor Cyan+ $compliance.MissingUpdates |+ Where-Object { $_.Severity -in @('Critical', 'Important') } |+ Sort-Object {+ switch ($_.Severity) {+ 'Critical' { 0 }+ 'Important' { 1 }+ default { 2 }+ }+ }, AgeInDays -Descending |+ Select-Object -First 5 |+ ForEach-Object {+ $color = if ($_.Severity -eq 'Critical') { 'Red' } else { 'Yellow' }+ Write-Host " [$($_.Severity)] $($_.KB) - $($_.AgeInDays) days old" -ForegroundColor $color+ }+ }++ if ($compliance.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ $compliance.Recommendations | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ return $compliance+ }+}++# Helper function to generate HTML report+function Generate-PatchComplianceHTML {+ param($Compliance)++ $scoreColor = if($Compliance.Summary.ComplianceScore -ge 80){'safe'}+ elseif($Compliance.Summary.ComplianceScore -ge 60){'medium'}+ else{'critical'}++ $html = @"+<!DOCTYPE html>+<html>+<head>+ <title>Patch Compliance Report - $($Compliance.ComputerName)</title>+ <style>+ body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }+ .container { max-width: 1200px; margin: 0 auto; background: white; padding: 30px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }+ h1 { color: #2c3e50; border-bottom: 3px solid #3498db; padding-bottom: 10px; }+ h2 { color: #34495e; margin-top: 30px; }+ .summary { background: #ecf0f1; padding: 20px; border-radius: 5px; margin: 20px 0; }+ .metric { display: inline-block; margin: 10px 20px 10px 0; }+ .metric-label { font-weight: bold; color: #7f8c8d; }+ .metric-value { font-size: 24px; font-weight: bold; }+ .critical { color: #e74c3c; }+ .high { color: #e67e22; }+ .important { color: #e67e22; }+ .medium { color: #f39c12; }+ .moderate { color: #f39c12; }+ .low { color: #95a5a6; }+ .safe { color: #27ae60; }+ table { width: 100%; border-collapse: collapse; margin: 20px 0; }+ th { background: #3498db; color: white; padding: 12px; text-align: left; }+ td { padding: 10px; border-bottom: 1px solid #ddd; }+ tr:hover { background: #f8f9fa; }+ .severity-badge { padding: 4px 8px; border-radius: 3px; color: white; font-weight: bold; }+ .severity-critical { background: #e74c3c; }+ .severity-important { background: #e67e22; }+ .severity-moderate { background: #f39c12; }+ .severity-low { background: #95a5a6; }+ .footer { margin-top: 40px; padding-top: 20px; border-top: 1px solid #ddd; color: #7f8c8d; font-size: 12px; }+ .compliant { color: #27ae60; font-weight: bold; font-size: 16px; padding: 20px; text-align: center; }+ </style>+</head>+<body>+ <div class="container">+ <h1>Windows Patch Compliance Report</h1>+ <p><strong>Computer:</strong> $($Compliance.ComputerName) | <strong>Scan Date:</strong> $($Compliance.ScanDate)</p>+ <p><strong>OS:</strong> $($Compliance.OSVersion) | <strong>Last Boot:</strong> $($Compliance.LastBootTime)</p>++ <div class="summary">+ <h2>Compliance Summary</h2>+ <div class="metric">+ <div class="metric-label">Compliance Score</div>+ <div class="metric-value $scoreColor">$($Compliance.Summary.ComplianceScore)%</div>+ </div>+ <div class="metric">+ <div class="metric-label">Installed Updates</div>+ <div class="metric-value safe">$($Compliance.Summary.TotalInstalled)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Missing Updates</div>+ <div class="metric-value $(if($Compliance.Summary.TotalMissing -gt 0){'critical'}else{'safe'})">+ $($Compliance.Summary.TotalMissing)+ </div>+ </div>+ <div class="metric">+ <div class="metric-label">Critical Missing</div>+ <div class="metric-value critical">$($Compliance.Summary.CriticalMissing)</div>+ </div>+ <div class="metric">+ <div class="metric-label">Important Missing</div>+ <div class="metric-value important">$($Compliance.Summary.ImportantMissing)</div>+ </div>+ </div>++ <h2>Missing Updates</h2>+"@++ if ($Compliance.MissingUpdates.Count -gt 0) {+ $html += @"+ <table>+ <tr>+ <th>Severity</th>+ <th>KB</th>+ <th>Title</th>+ <th>Age (Days)</th>+ <th>Size (MB)</th>+ <th>Reboot Required</th>+ </tr>+"@++ foreach ($update in ($Compliance.MissingUpdates | Sort-Object {+ switch ($_.Severity) {+ 'Critical' { 0 }+ 'Important' { 1 }+ 'Moderate' { 2 }+ 'Low' { 3 }+ }+ }, AgeInDays -Descending)) {+ $severityClass = "severity-$($update.Severity.ToLower())"+ $title = $update.Title -replace '<', '<' -replace '>', '>'+ $reboot = if ($update.RebootRequired) { 'Yes' } else { 'No' }++ $html += @"+ <tr>+ <td><span class="severity-badge $severityClass">$($update.Severity)</span></td>+ <td><strong>$($update.KB)</strong></td>+ <td>$title</td>+ <td>$($update.AgeInDays)</td>+ <td>$($update.Size)</td>+ <td>$reboot</td>+ </tr>+"@+ }++ $html += " </table>`n"+ }+ else {+ $html += " <p class=`"compliant`">System is fully patched - no missing updates detected</p>`n"+ }++ $html += " `n <h2>Recommendations</h2>`n <ul>`n"++ foreach ($rec in $Compliance.Recommendations) {+ $recEscaped = $rec -replace '<', '<' -replace '>', '>'+ $html += " <li>$recEscaped</li>`n"+ }++ $currentDate = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'++ $html += @"+ </ul>++ <div class="footer">+ Generated by WindowsSecurityAudit Module | Patch Compliance | $currentDate+ </div>+ </div>+</body>+</html>+"@++ return $html+}\ No newline at end of filediff --git a/WindowsDefender/Get-DefenderStatus.ps1 b/WindowsDefender/Get-DefenderStatus.ps1new file mode 100644index 0000000..1687537--- /dev/null+++ b/WindowsDefender/Get-DefenderStatus.ps1@@ -0,0 +1,273 @@+function Get-DefenderStatus {+ <#+ .SYNOPSIS+ Retrieves comprehensive Windows Defender status and configuration+ .DESCRIPTION+ Collects detailed information about Windows Defender including protection status,+ signature versions, scan history, threat detections, and exclusions+ .PARAMETER IncludeThreatHistory+ Include detected threat history+ .PARAMETER IncludeExclusions+ Include configured exclusions+ .EXAMPLE+ Get-DefenderStatus+ Get-DefenderStatus -IncludeThreatHistory -IncludeExclusions+ .OUTPUTS+ PSCustomObject with Defender status information+ #>++ [CmdletBinding()]+ param(+ [Parameter()]+ [switch]$IncludeThreatHistory,++ [Parameter()]+ [switch]$IncludeExclusions+ )++ begin {+ Write-Host "=== WINDOWS DEFENDER STATUS ===" -ForegroundColor Cyan++ $status = [PSCustomObject]@{+ CollectionDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ ComputerName = $env:COMPUTERNAME+ ProtectionStatus = @{}+ SignatureStatus = @{}+ ScanHistory = @{}+ Configuration = @{}+ ThreatHistory = @()+ Exclusions = @{}+ HealthStatus = 'Unknown'+ Recommendations = @()+ }+ }++ process {+ try {+ # Get main Defender status+ Write-Host "Collecting Defender status..." -ForegroundColor Yellow++ $mpStatus = Get-MpComputerStatus++ # Protection Status+ $status.ProtectionStatus = [PSCustomObject]@{+ AntivirusEnabled = $mpStatus.AntivirusEnabled+ AntispywareEnabled = $mpStatus.AntispywareEnabled+ RealTimeProtectionEnabled = $mpStatus.RealTimeProtectionEnabled+ OnAccessProtectionEnabled = $mpStatus.OnAccessProtectionEnabled+ BehaviorMonitorEnabled = $mpStatus.BehaviorMonitorEnabled+ IoavProtectionEnabled = $mpStatus.IoavProtectionEnabled+ NISEnabled = $mpStatus.NISEnabled+ IsTamperProtected = $mpStatus.IsTamperProtected+ }++ # Signature Status+ $status.SignatureStatus = [PSCustomObject]@{+ AntivirusSignatureVersion = $mpStatus.AntivirusSignatureVersion+ AntispywareSignatureVersion = $mpStatus.AntispywareSignatureVersion+ NISSignatureVersion = $mpStatus.NISSignatureVersion+ AntivirusSignatureLastUpdated = $mpStatus.AntivirusSignatureLastUpdated+ AntispywareSignatureLastUpdated = $mpStatus.AntispywareSignatureLastUpdated+ NISSignatureLastUpdated = $mpStatus.NISSignatureLastUpdated+ SignatureAge = (Get-Date) - $mpStatus.AntivirusSignatureLastUpdated+ }++ # Scan History+ $status.ScanHistory = [PSCustomObject]@{+ QuickScanStartTime = $mpStatus.QuickScanStartTime+ QuickScanEndTime = $mpStatus.QuickScanEndTime+ QuickScanAge = if ($mpStatus.QuickScanAge) { $mpStatus.QuickScanAge } else { "Never" }+ FullScanStartTime = $mpStatus.FullScanStartTime+ FullScanEndTime = $mpStatus.FullScanEndTime+ FullScanAge = if ($mpStatus.FullScanAge) { $mpStatus.FullScanAge } else { "Never" }+ }++ # Get Defender preferences/configuration+ $mpPreferences = Get-MpPreference++ $status.Configuration = [PSCustomObject]@{+ DisableAutoExclusions = $mpPreferences.DisableAutoExclusions+ DisableRealtimeMonitoring = $mpPreferences.DisableRealtimeMonitoring+ DisableBehaviorMonitoring = $mpPreferences.DisableBehaviorMonitoring+ DisableIOAVProtection = $mpPreferences.DisableIOAVProtection+ DisableScriptScanning = $mpPreferences.DisableScriptScanning+ MAPSReporting = $mpPreferences.MAPSReporting+ SubmitSamplesConsent = $mpPreferences.SubmitSamplesConsent+ PUAProtection = $mpPreferences.PUAProtection+ ScanAvgCPULoadFactor = $mpPreferences.ScanAvgCPULoadFactor+ CheckForSignaturesBeforeRunningScan = $mpPreferences.CheckForSignaturesBeforeRunningScan+ ScanParameters = $mpPreferences.ScanParameters+ ScanScheduleDay = $mpPreferences.ScanScheduleDay+ ScanScheduleTime = $mpPreferences.ScanScheduleTime+ }++ # Threat History+ if ($IncludeThreatHistory) {+ Write-Host "Collecting threat history..." -ForegroundColor Yellow++ try {+ $threats = Get-MpThreatDetection+ foreach ($threat in $threats) {+ $status.ThreatHistory += [PSCustomObject]@{+ ThreatName = $threat.ThreatName+ SeverityID = $threat.SeverityID+ InitialDetectionTime = $threat.InitialDetectionTime+ LastThreatStatusChangeTime = $threat.LastThreatStatusChangeTime+ ActionSuccess = $threat.ActionSuccess+ Resources = $threat.Resources+ }+ }+ }+ catch {+ Write-Verbose "No threat history available or access denied"+ }+ }++ # Exclusions+ if ($IncludeExclusions) {+ Write-Host "Collecting exclusions..." -ForegroundColor Yellow++ $status.Exclusions = [PSCustomObject]@{+ ExclusionPath = $mpPreferences.ExclusionPath+ ExclusionExtension = $mpPreferences.ExclusionExtension+ ExclusionProcess = $mpPreferences.ExclusionProcess+ ExclusionIpAddress = $mpPreferences.ExclusionIpAddress+ }+ }++ # Determine overall health status+ $healthScore = 0+ $maxScore = 100++ # Check critical protections (60 points)+ if ($status.ProtectionStatus.RealTimeProtectionEnabled) { $healthScore += 20 } else { $status.Recommendations += "Enable Real-Time Protection" }+ if ($status.ProtectionStatus.BehaviorMonitorEnabled) { $healthScore += 15 } else { $status.Recommendations += "Enable Behavior Monitoring" }+ if ($status.ProtectionStatus.IoavProtectionEnabled) { $healthScore += 10 } else { $status.Recommendations += "Enable IOAV Protection" }+ if ($status.ProtectionStatus.NISEnabled) { $healthScore += 15 } else { $status.Recommendations += "Enable Network Inspection System" }++ # Check signature age (20 points)+ $signatureAge = $status.SignatureStatus.SignatureAge.Days+ if ($signatureAge -le 1) {+ $healthScore += 20+ } elseif ($signatureAge -le 3) {+ $healthScore += 15+ $status.Recommendations += "Update virus definitions (current age: $signatureAge days)"+ } elseif ($signatureAge -le 7) {+ $healthScore += 10+ $status.Recommendations += "Update virus definitions urgently (current age: $signatureAge days)"+ } else {+ $status.Recommendations += "Update virus definitions immediately (current age: $signatureAge days)"+ }++ # Check scan history (20 points)+ if ($status.ScanHistory.QuickScanAge -ne "Never") {+ if ($status.ScanHistory.QuickScanAge -le 7) {+ $healthScore += 10+ } elseif ($status.ScanHistory.QuickScanAge -le 14) {+ $healthScore += 5+ $status.Recommendations += "Run a Quick Scan (last scan: $($status.ScanHistory.QuickScanAge) days ago)"+ } else {+ $status.Recommendations += "Run a Quick Scan urgently (last scan: $($status.ScanHistory.QuickScanAge) days ago)"+ }+ } else {+ $status.Recommendations += "Run a Quick Scan (never performed)"+ }++ if ($status.ScanHistory.FullScanAge -ne "Never") {+ if ($status.ScanHistory.FullScanAge -le 30) {+ $healthScore += 10+ } elseif ($status.ScanHistory.FullScanAge -le 60) {+ $healthScore += 5+ $status.Recommendations += "Run a Full Scan (last scan: $($status.ScanHistory.FullScanAge) days ago)"+ } else {+ $status.Recommendations += "Run a Full Scan urgently (last scan: $($status.ScanHistory.FullScanAge) days ago)"+ }+ } else {+ $status.Recommendations += "Run a Full Scan (never performed)"+ }++ # Determine health status+ if ($healthScore -ge 90) {+ $status.HealthStatus = 'Excellent'+ } elseif ($healthScore -ge 75) {+ $status.HealthStatus = 'Good'+ } elseif ($healthScore -ge 60) {+ $status.HealthStatus = 'Fair'+ } elseif ($healthScore -ge 40) {+ $status.HealthStatus = 'Poor'+ } else {+ $status.HealthStatus = 'Critical'+ }++ }+ catch {+ Write-Error "Error collecting Defender status: $_"+ throw+ }+ }++ end {+ # Display summary+ Write-Host "`n=== DEFENDER STATUS SUMMARY ===" -ForegroundColor Cyan++ Write-Host "`nHealth Status: " -NoNewline+ $color = switch ($status.HealthStatus) {+ 'Excellent' { 'Green' }+ 'Good' { 'Green' }+ 'Fair' { 'Yellow' }+ 'Poor' { 'Red' }+ 'Critical' { 'Red' }+ default { 'White' }+ }+ Write-Host $status.HealthStatus -ForegroundColor $color++ Write-Host "`nProtection Status:" -ForegroundColor Cyan+ Write-Host " Real-Time Protection: " -NoNewline+ Write-Host $status.ProtectionStatus.RealTimeProtectionEnabled -ForegroundColor $(if ($status.ProtectionStatus.RealTimeProtectionEnabled) { 'Green' } else { 'Red' })+ Write-Host " Behavior Monitor: " -NoNewline+ Write-Host $status.ProtectionStatus.BehaviorMonitorEnabled -ForegroundColor $(if ($status.ProtectionStatus.BehaviorMonitorEnabled) { 'Green' } else { 'Red' })+ Write-Host " Network Inspection: " -NoNewline+ Write-Host $status.ProtectionStatus.NISEnabled -ForegroundColor $(if ($status.ProtectionStatus.NISEnabled) { 'Green' } else { 'Red' })+ Write-Host " Tamper Protection: " -NoNewline+ Write-Host $status.ProtectionStatus.IsTamperProtected -ForegroundColor $(if ($status.ProtectionStatus.IsTamperProtected) { 'Green' } else { 'Yellow' })++ Write-Host "`nSignatures:" -ForegroundColor Cyan+ Write-Host " Version: $($status.SignatureStatus.AntivirusSignatureVersion)"+ Write-Host " Last Updated: $($status.SignatureStatus.AntivirusSignatureLastUpdated)"+ Write-Host " Age: $($status.SignatureStatus.SignatureAge.Days) days" -ForegroundColor $(+ if ($status.SignatureStatus.SignatureAge.Days -le 1) { 'Green' }+ elseif ($status.SignatureStatus.SignatureAge.Days -le 3) { 'Yellow' }+ else { 'Red' }+ )++ Write-Host "`nLast Scans:" -ForegroundColor Cyan+ Write-Host " Quick Scan: " -NoNewline+ if ($status.ScanHistory.QuickScanAge -ne "Never") {+ Write-Host "$($status.ScanHistory.QuickScanAge) days ago"+ } else {+ Write-Host "Never" -ForegroundColor Red+ }+ Write-Host " Full Scan: " -NoNewline+ if ($status.ScanHistory.FullScanAge -ne "Never") {+ Write-Host "$($status.ScanHistory.FullScanAge) days ago"+ } else {+ Write-Host "Never" -ForegroundColor Red+ }++ if ($IncludeThreatHistory -and $status.ThreatHistory.Count -gt 0) {+ Write-Host "`nThreat Detections: $($status.ThreatHistory.Count)" -ForegroundColor Red+ $status.ThreatHistory | Select-Object -First 5 | ForEach-Object {+ Write-Host " - $($_.ThreatName) [$($_.InitialDetectionTime)]" -ForegroundColor Red+ }+ }++ if ($status.Recommendations.Count -gt 0) {+ Write-Host "`nRecommendations:" -ForegroundColor Yellow+ $status.Recommendations | ForEach-Object {+ Write-Host " ! $_" -ForegroundColor Yellow+ }+ }++ return $status+ }+}\ No newline at end of filediff --git a/WindowsDefender/Invoke-DefenderScan.ps1 b/WindowsDefender/Invoke-DefenderScan.ps1new file mode 100644index 0000000..122ab2d--- /dev/null+++ b/WindowsDefender/Invoke-DefenderScan.ps1@@ -0,0 +1,333 @@+function Invoke-DefenderScan {+ <#+ .SYNOPSIS+ Initiates Windows Defender scans with various options+ .DESCRIPTION+ Starts Windows Defender antivirus scans including Quick Scan, Full Scan, Custom Scan,+ and Offline Scan with progress tracking and result reporting+ .PARAMETER ScanType+ Type of scan: Quick, Full, Custom, or Offline+ .PARAMETER ScanPath+ Path to scan (required for Custom scan)+ .PARAMETER UpdateSignatures+ Update virus definitions before scanning+ .PARAMETER Priority+ Scan priority: Low or Normal+ .EXAMPLE+ Invoke-DefenderScan -ScanType Quick+ Invoke-DefenderScan -ScanType Full -UpdateSignatures+ Invoke-DefenderScan -ScanType Custom -ScanPath "C:\Users"+ .OUTPUTS+ PSCustomObject with scan results+ #>++ [CmdletBinding()]+ param(+ [Parameter(Mandatory = $true)]+ [ValidateSet('Quick', 'Full', 'Custom', 'Offline')]+ [string]$ScanType,++ [Parameter()]+ [string]$ScanPath,++ [Parameter()]+ [switch]$UpdateSignatures,++ [Parameter()]+ [ValidateSet('Low', 'Normal')]+ [string]$Priority = 'Normal'+ )++ begin {+ Write-Host "=== WINDOWS DEFENDER SCAN ===" -ForegroundColor Cyan+ Write-Host "Scan Type: $ScanType" -ForegroundColor Yellow+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ # Check for admin privileges+ $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ if (-not $isAdmin) {+ throw "This function requires Administrator privileges!"+ }++ # Validate custom scan path+ if ($ScanType -eq 'Custom' -and -not $ScanPath) {+ throw "ScanPath is required for Custom scan type!"+ }++ if ($ScanType -eq 'Custom' -and -not (Test-Path $ScanPath)) {+ throw "ScanPath does not exist: $ScanPath"+ }++ $results = [PSCustomObject]@{+ ScanType = $ScanType+ StartTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ EndTime = $null+ Duration = $null+ Status = 'Running'+ ThreatsDetected = 0+ FilesScanned = 0+ ThreatDetails = @()+ SignatureUpdate = @{+ Updated = $false+ Version = $null+ Error = $null+ }+ Errors = @()+ }+ }++ process {+ try {+ # Update signatures if requested+ if ($UpdateSignatures) {+ Write-Host "`nUpdating virus definitions..." -ForegroundColor Cyan+ try {+ Update-MpSignature -ErrorAction Stop+ $mpStatus = Get-MpComputerStatus+ $results.SignatureUpdate.Updated = $true+ $results.SignatureUpdate.Version = $mpStatus.AntivirusSignatureVersion+ Write-Host "Signatures updated to version: $($mpStatus.AntivirusSignatureVersion)" -ForegroundColor Green+ }+ catch {+ $results.SignatureUpdate.Error = $_.Exception.Message+ Write-Warning "Failed to update signatures: $_"+ }+ }++ # Start the scan+ Write-Host "`nStarting $ScanType scan..." -ForegroundColor Cyan++ switch ($ScanType) {+ 'Quick' {+ Write-Host "This may take a few minutes..." -ForegroundColor Yellow+ try {+ if ($Priority -eq 'Low') {+ Start-MpScan -ScanType QuickScan -AsJob | Out-Null+ Write-Host "Quick scan started as background job" -ForegroundColor Green+ }+ else {+ Start-MpScan -ScanType QuickScan+ Write-Host "Quick scan completed" -ForegroundColor Green+ }+ $results.Status = 'Completed'+ }+ catch {+ $results.Status = 'Failed'+ $results.Errors += $_.Exception.Message+ throw+ }+ }++ 'Full' {+ Write-Host "This may take 30+ minutes depending on system size..." -ForegroundColor Yellow+ Write-Host "Progress updates will appear in Windows Security app" -ForegroundColor Yellow+ try {+ if ($Priority -eq 'Low') {+ Start-MpScan -ScanType FullScan -AsJob | Out-Null+ Write-Host "Full scan started as background job" -ForegroundColor Green+ Write-Host "Use Get-MpThreat to check results later" -ForegroundColor Yellow+ }+ else {+ $job = Start-MpScan -ScanType FullScan -AsJob+ Write-Host "Full scan in progress (background job)..." -ForegroundColor Yellow+ Write-Host "Monitoring scan progress..." -ForegroundColor Cyan++ # Monitor progress+ $startTime = Get-Date+ while ($job.State -eq 'Running') {+ $elapsed = ((Get-Date) - $startTime).ToString("hh\:mm\:ss")+ Write-Host "`rElapsed time: $elapsed" -NoNewline -ForegroundColor Yellow+ Start-Sleep -Seconds 10+ }+ Write-Host ""++ if ($job.State -eq 'Completed') {+ Write-Host "Full scan completed" -ForegroundColor Green+ $results.Status = 'Completed'+ }+ else {+ Write-Warning "Scan job state: $($job.State)"+ $results.Status = $job.State+ }+ }+ }+ catch {+ $results.Status = 'Failed'+ $results.Errors += $_.Exception.Message+ throw+ }+ }++ 'Custom' {+ Write-Host "Scanning path: $ScanPath" -ForegroundColor Yellow+ try {+ Start-MpScan -ScanType CustomScan -ScanPath $ScanPath+ Write-Host "Custom scan completed" -ForegroundColor Green+ $results.Status = 'Completed'+ }+ catch {+ $results.Status = 'Failed'+ $results.Errors += $_.Exception.Message+ throw+ }+ }++ 'Offline' {+ Write-Host "WARNING: Offline scan will restart your computer!" -ForegroundColor Red+ Write-Host "Your computer will boot into Windows Defender Offline environment" -ForegroundColor Yellow++ $confirmation = Read-Host "Do you want to continue? (yes/no)"+ if ($confirmation -eq 'yes') {+ try {+ Start-MpWDOScan+ Write-Host "Offline scan initiated - system will restart" -ForegroundColor Green+ $results.Status = 'Initiated'+ }+ catch {+ $results.Status = 'Failed'+ $results.Errors += $_.Exception.Message+ throw+ }+ }+ else {+ Write-Host "Offline scan cancelled by user" -ForegroundColor Yellow+ $results.Status = 'Cancelled'+ }+ }+ }++ # Wait a moment for scan results to be processed+ if ($results.Status -eq 'Completed') {+ Start-Sleep -Seconds 2+ }++ # Get scan results and threat information+ if ($results.Status -eq 'Completed') {+ Write-Host "`nCollecting scan results..." -ForegroundColor Cyan++ try {+ # Get updated Defender status+ $mpStatus = Get-MpComputerStatus++ # Get threat detections+ $threats = Get-MpThreat+ $results.ThreatsDetected = $threats.Count++ foreach ($threat in $threats) {+ $results.ThreatDetails += [PSCustomObject]@{+ ThreatName = $threat.ThreatName+ SeverityID = $threat.SeverityID+ Severity = switch ($threat.SeverityID) {+ 0 { 'Unknown' }+ 1 { 'Low' }+ 2 { 'Medium' }+ 4 { 'High' }+ 5 { 'Severe' }+ default { 'Unknown' }+ }+ CategoryID = $threat.CategoryID+ InitialDetectionTime = $threat.InitialDetectionTime+ IsActive = $threat.IsActive+ Resources = $threat.Resources+ }+ }++ # Try to get scan history+ switch ($ScanType) {+ 'Quick' {+ $results.EndTime = $mpStatus.QuickScanEndTime+ if ($mpStatus.QuickScanStartTime) {+ $results.Duration = ($mpStatus.QuickScanEndTime - $mpStatus.QuickScanStartTime).ToString()+ }+ }+ 'Full' {+ $results.EndTime = $mpStatus.FullScanEndTime+ if ($mpStatus.FullScanStartTime) {+ $results.Duration = ($mpStatus.FullScanEndTime - $mpStatus.FullScanStartTime).ToString()+ }+ }+ }++ }+ catch {+ Write-Verbose "Could not retrieve detailed scan results: $_"+ }+ }++ }+ catch {+ Write-Error "Error during Defender scan: $_"+ $results.Status = 'Error'+ $results.Errors += $_.Exception.Message+ }+ }++ end {+ if ($results.Status -ne 'Initiated') {+ $results.EndTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ }++ Write-Host "`n=== SCAN COMPLETE ===" -ForegroundColor Green++ Write-Host "`nScan Details:" -ForegroundColor Cyan+ Write-Host " Type: $($results.ScanType)" -ForegroundColor White+ Write-Host " Status: " -NoNewline+ Write-Host $results.Status -ForegroundColor $(+ switch ($results.Status) {+ 'Completed' { 'Green' }+ 'Running' { 'Yellow' }+ 'Failed' { 'Red' }+ 'Cancelled' { 'Yellow' }+ 'Initiated' { 'Green' }+ default { 'White' }+ }+ )++ if ($results.Duration) {+ Write-Host " Duration: $($results.Duration)" -ForegroundColor White+ }++ if ($results.SignatureUpdate.Updated) {+ Write-Host "`nSignature Update:" -ForegroundColor Cyan+ Write-Host " Version: $($results.SignatureUpdate.Version)" -ForegroundColor White+ }++ Write-Host "`nThreats Detected: " -NoNewline+ if ($results.ThreatsDetected -gt 0) {+ Write-Host $results.ThreatsDetected -ForegroundColor Red++ Write-Host "`nThreat Details:" -ForegroundColor Red+ foreach ($threat in $results.ThreatDetails) {+ Write-Host " - $($threat.ThreatName)" -ForegroundColor Red+ Write-Host " Severity: $($threat.Severity)" -ForegroundColor Yellow+ Write-Host " Detected: $($threat.InitialDetectionTime)" -ForegroundColor White+ if ($threat.Resources) {+ Write-Host " Location: $($threat.Resources)" -ForegroundColor White+ }+ }+ }+ else {+ Write-Host "0" -ForegroundColor Green+ Write-Host " No threats detected!" -ForegroundColor Green+ }++ if ($results.Errors.Count -gt 0) {+ Write-Host "`nErrors:" -ForegroundColor Red+ $results.Errors | ForEach-Object {+ Write-Host " - $_" -ForegroundColor Red+ }+ }++ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ Write-Host " 1. Run full scans weekly" -ForegroundColor White+ Write-Host " 2. Keep definitions updated automatically" -ForegroundColor White+ Write-Host " 3. Review detected threats in Windows Security" -ForegroundColor White+ Write-Host " 4. Schedule regular scans during off-peak hours" -ForegroundColor White++ if ($Priority -eq 'Low' -and $results.Status -eq 'Completed') {+ Write-Host "`nNote: Background scan may still be running. Check Windows Security for status." -ForegroundColor Yellow+ }++ return $results+ }+}\ No newline at end of filediff --git a/WindowsDefender/Update-DefenderConfiguration.ps1 b/WindowsDefender/Update-DefenderConfiguration.ps1new file mode 100644index 0000000..052ddfc--- /dev/null+++ b/WindowsDefender/Update-DefenderConfiguration.ps1@@ -0,0 +1,423 @@+function Update-DefenderConfiguration {+ <#+ .SYNOPSIS+ Updates Windows Defender configuration settings+ .DESCRIPTION+ Modifies Windows Defender settings including real-time protection, cloud protection,+ automatic sample submission, PUA protection, and exclusions+ .PARAMETER EnableRealTimeProtection+ Enable or disable real-time protection+ .PARAMETER EnableCloudProtection+ Enable cloud-delivered protection+ .PARAMETER EnableAutoSampleSubmission+ Enable automatic sample submission+ .PARAMETER PUAProtection+ Configure Potentially Unwanted Application protection (Disabled, Enabled, AuditMode)+ .PARAMETER AddExclusionPath+ Add path exclusion(s)+ .PARAMETER RemoveExclusionPath+ Remove path exclusion(s)+ .PARAMETER AddExclusionExtension+ Add file extension exclusion(s)+ .PARAMETER ScheduleScan+ Configure scheduled scan (Day and Time required)+ .PARAMETER ScanDay+ Day for scheduled scan (0-7, where 0=Everyday, 1=Sunday, 7=Saturday)+ .PARAMETER ScanTime+ Time for scheduled scan (HH:MM format)+ .EXAMPLE+ Update-DefenderConfiguration -EnableRealTimeProtection $true -EnableCloudProtection+ Update-DefenderConfiguration -PUAProtection Enabled -ScheduleScan -ScanDay 0 -ScanTime "02:00"+ Update-DefenderConfiguration -AddExclusionPath "C:\TrustedApp"+ .OUTPUTS+ PSCustomObject with configuration update results+ #>++ [CmdletBinding(SupportsShouldProcess)]+ param(+ [Parameter()]+ [ValidateNotNull()]+ [bool]$EnableRealTimeProtection,++ [Parameter()]+ [switch]$EnableCloudProtection,++ [Parameter()]+ [switch]$EnableAutoSampleSubmission,++ [Parameter()]+ [ValidateSet('Disabled', 'Enabled', 'AuditMode')]+ [string]$PUAProtection,++ [Parameter()]+ [string[]]$AddExclusionPath,++ [Parameter()]+ [string[]]$RemoveExclusionPath,++ [Parameter()]+ [string[]]$AddExclusionExtension,++ [Parameter()]+ [switch]$ScheduleScan,++ [Parameter()]+ [ValidateRange(0, 7)]+ [int]$ScanDay,++ [Parameter()]+ [string]$ScanTime+ )++ begin {+ Write-Host "=== WINDOWS DEFENDER CONFIGURATION UPDATE ===" -ForegroundColor Cyan+ Write-Host "Start Time: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Yellow++ # Check for admin privileges+ $isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)+ if (-not $isAdmin) {+ throw "This function requires Administrator privileges!"+ }++ # Validate scheduled scan parameters+ if ($ScheduleScan -and (-not $PSBoundParameters.ContainsKey('ScanDay') -or -not $ScanTime)) {+ throw "ScheduleScan requires both ScanDay and ScanTime parameters!"+ }++ if ($ScanTime) {+ try {+ $null = [datetime]::ParseExact($ScanTime, "HH:mm", $null)+ }+ catch {+ throw "ScanTime must be in HH:MM format (e.g., '02:00' or '14:30')"+ }+ }++ $results = [PSCustomObject]@{+ ConfigurationDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss"+ Changes = @()+ Errors = @()+ BeforeConfiguration = @{}+ AfterConfiguration = @{}+ }++ # Get current configuration+ try {+ $currentPrefs = Get-MpPreference+ $currentStatus = Get-MpComputerStatus++ $results.BeforeConfiguration = [PSCustomObject]@{+ RealTimeProtectionEnabled = $currentStatus.RealTimeProtectionEnabled+ CloudProtection = $currentPrefs.MAPSReporting+ SampleSubmission = $currentPrefs.SubmitSamplesConsent+ PUAProtection = $currentPrefs.PUAProtection+ ScanScheduleDay = $currentPrefs.ScanScheduleDay+ ScanScheduleTime = $currentPrefs.ScanScheduleTime+ ExclusionPaths = $currentPrefs.ExclusionPath+ ExclusionExtensions = $currentPrefs.ExclusionExtension+ }+ }+ catch {+ Write-Warning "Could not retrieve current configuration: $_"+ }+ }++ process {+ try {+ # 1. Real-Time Protection+ if ($PSBoundParameters.ContainsKey('EnableRealTimeProtection')) {+ Write-Host "`n[1] Configuring Real-Time Protection..." -ForegroundColor Cyan++ try {+ if ($PSCmdlet.ShouldProcess("Real-Time Protection", "Set to $EnableRealTimeProtection")) {+ Set-MpPreference -DisableRealtimeMonitoring (-not $EnableRealTimeProtection)+ $results.Changes += "Real-Time Protection: $EnableRealTimeProtection"+ Write-Host " Real-Time Protection: " -NoNewline+ Write-Host $EnableRealTimeProtection -ForegroundColor $(if ($EnableRealTimeProtection) { 'Green' } else { 'Red' })+ }+ }+ catch {+ $results.Errors += "Failed to configure Real-Time Protection: $_"+ Write-Warning " Failed to configure Real-Time Protection: $_"+ }+ }++ # 2. Cloud Protection+ if ($EnableCloudProtection) {+ Write-Host "`n[2] Configuring Cloud Protection..." -ForegroundColor Cyan++ try {+ if ($PSCmdlet.ShouldProcess("Cloud Protection", "Enable")) {+ # Advanced = 2, Basic = 1, Disabled = 0+ Set-MpPreference -MAPSReporting Advanced+ $results.Changes += "Cloud Protection: Enabled (Advanced)"+ Write-Host " Cloud Protection: Enabled (Advanced)" -ForegroundColor Green+ }+ }+ catch {+ $results.Errors += "Failed to configure Cloud Protection: $_"+ Write-Warning " Failed to configure Cloud Protection: $_"+ }+ }++ # 3. Automatic Sample Submission+ if ($EnableAutoSampleSubmission) {+ Write-Host "`n[3] Configuring Automatic Sample Submission..." -ForegroundColor Cyan++ try {+ if ($PSCmdlet.ShouldProcess("Sample Submission", "Enable")) {+ # SendAllSamples = 3+ Set-MpPreference -SubmitSamplesConsent SendAllSamples+ $results.Changes += "Automatic Sample Submission: Enabled"+ Write-Host " Automatic Sample Submission: Enabled" -ForegroundColor Green+ }+ }+ catch {+ $results.Errors += "Failed to configure Sample Submission: $_"+ Write-Warning " Failed to configure Sample Submission: $_"+ }+ }++ # 4. PUA Protection+ if ($PUAProtection) {+ Write-Host "`n[4] Configuring PUA Protection..." -ForegroundColor Cyan++ try {+ $puaValue = switch ($PUAProtection) {+ 'Disabled' { 0 }+ 'Enabled' { 1 }+ 'AuditMode' { 2 }+ }++ if ($PSCmdlet.ShouldProcess("PUA Protection", "Set to $PUAProtection")) {+ Set-MpPreference -PUAProtection $puaValue+ $results.Changes += "PUA Protection: $PUAProtection"+ Write-Host " PUA Protection: $PUAProtection" -ForegroundColor Green+ }+ }+ catch {+ $results.Errors += "Failed to configure PUA Protection: $_"+ Write-Warning " Failed to configure PUA Protection: $_"+ }+ }++ # 5. Add Path Exclusions+ if ($AddExclusionPath) {+ Write-Host "`n[5] Adding Path Exclusions..." -ForegroundColor Cyan++ foreach ($path in $AddExclusionPath) {+ try {+ if ($PSCmdlet.ShouldProcess($path, "Add exclusion")) {+ Add-MpPreference -ExclusionPath $path+ $results.Changes += "Added path exclusion: $path"+ Write-Host " + $path" -ForegroundColor Green+ }+ }+ catch {+ $results.Errors += "Failed to add path exclusion '$path': $_"+ Write-Warning " Failed to add: $path"+ }+ }+ }++ # 6. Remove Path Exclusions+ if ($RemoveExclusionPath) {+ Write-Host "`n[6] Removing Path Exclusions..." -ForegroundColor Cyan++ foreach ($path in $RemoveExclusionPath) {+ try {+ if ($PSCmdlet.ShouldProcess($path, "Remove exclusion")) {+ Remove-MpPreference -ExclusionPath $path+ $results.Changes += "Removed path exclusion: $path"+ Write-Host " - $path" -ForegroundColor Yellow+ }+ }+ catch {+ $results.Errors += "Failed to remove path exclusion '$path': $_"+ Write-Warning " Failed to remove: $path"+ }+ }+ }++ # 7. Add Extension Exclusions+ if ($AddExclusionExtension) {+ Write-Host "`n[7] Adding Extension Exclusions..." -ForegroundColor Cyan++ foreach ($ext in $AddExclusionExtension) {+ try {+ # Ensure extension starts with dot+ $extension = if ($ext.StartsWith('.')) { $ext } else { ".$ext" }++ if ($PSCmdlet.ShouldProcess($extension, "Add exclusion")) {+ Add-MpPreference -ExclusionExtension $extension+ $results.Changes += "Added extension exclusion: $extension"+ Write-Host " + $extension" -ForegroundColor Green+ }+ }+ catch {+ $results.Errors += "Failed to add extension exclusion '$ext': $_"+ Write-Warning " Failed to add: $ext"+ }+ }+ }++ # 8. Schedule Scan+ if ($ScheduleScan) {+ Write-Host "`n[8] Configuring Scheduled Scan..." -ForegroundColor Cyan++ try {+ if ($PSCmdlet.ShouldProcess("Scheduled Scan", "Configure")) {+ # Configure scan day+ Set-MpPreference -ScanScheduleDay $ScanDay++ # Parse and set time+ $timeSpan = [TimeSpan]::Parse($ScanTime)+ Set-MpPreference -ScanScheduleTime $timeSpan++ # Enable scheduled scan+ Set-MpPreference -DisableScheduledScan $false++ $dayName = switch ($ScanDay) {+ 0 { 'Everyday' }+ 1 { 'Sunday' }+ 2 { 'Monday' }+ 3 { 'Tuesday' }+ 4 { 'Wednesday' }+ 5 { 'Thursday' }+ 6 { 'Friday' }+ 7 { 'Saturday' }+ }++ $results.Changes += "Scheduled Scan: $dayName at $ScanTime"+ Write-Host " Scheduled Scan: $dayName at $ScanTime" -ForegroundColor Green+ }+ }+ catch {+ $results.Errors += "Failed to configure scheduled scan: $_"+ Write-Warning " Failed to configure scheduled scan: $_"+ }+ }++ # Additional recommended settings+ Write-Host "`n[ADDITIONAL] Applying recommended settings..." -ForegroundColor Cyan++ try {+ # Enable behavior monitoring+ Set-MpPreference -DisableBehaviorMonitoring $false+ Write-Host " + Behavior Monitoring enabled" -ForegroundColor Green++ # Enable IOAV protection+ Set-MpPreference -DisableIOAVProtection $false+ Write-Host " + IOAV Protection enabled" -ForegroundColor Green++ # Enable script scanning+ Set-MpPreference -DisableScriptScanning $false+ Write-Host " + Script Scanning enabled" -ForegroundColor Green++ # Check for signatures before scan+ Set-MpPreference -CheckForSignaturesBeforeRunningScan $true+ Write-Host " + Check signatures before scan enabled" -ForegroundColor Green++ $results.Changes += "Additional protections enabled"+ }+ catch {+ Write-Verbose "Some additional settings could not be configured: $_"+ }++ }+ catch {+ Write-Error "Error during configuration update: $_"+ throw+ }+ }++ end {+ # Get updated configuration+ try {+ $updatedPrefs = Get-MpPreference+ $updatedStatus = Get-MpComputerStatus++ $results.AfterConfiguration = [PSCustomObject]@{+ RealTimeProtectionEnabled = $updatedStatus.RealTimeProtectionEnabled+ CloudProtection = $updatedPrefs.MAPSReporting+ SampleSubmission = $updatedPrefs.SubmitSamplesConsent+ PUAProtection = $updatedPrefs.PUAProtection+ ScanScheduleDay = $updatedPrefs.ScanScheduleDay+ ScanScheduleTime = $updatedPrefs.ScanScheduleTime+ ExclusionPaths = $updatedPrefs.ExclusionPath+ ExclusionExtensions = $updatedPrefs.ExclusionExtension+ }+ }+ catch {+ Write-Warning "Could not retrieve updated configuration: $_"+ }++ # Display summary+ Write-Host "`n=== CONFIGURATION UPDATE COMPLETE ===" -ForegroundColor Green++ Write-Host "`nChanges Applied: $($results.Changes.Count)" -ForegroundColor Cyan+ if ($results.Changes.Count -gt 0) {+ $results.Changes | ForEach-Object {+ Write-Host " + $_" -ForegroundColor White+ }+ }+ else {+ Write-Host " No changes were made" -ForegroundColor Yellow+ }++ if ($results.Errors.Count -gt 0) {+ Write-Host "`nErrors: $($results.Errors.Count)" -ForegroundColor Red+ $results.Errors | ForEach-Object {+ Write-Host " - $_" -ForegroundColor Red+ }+ }++ Write-Host "`nCurrent Protection Status:" -ForegroundColor Cyan+ Write-Host " Real-Time Protection: " -NoNewline+ Write-Host $results.AfterConfiguration.RealTimeProtectionEnabled -ForegroundColor $(+ if ($results.AfterConfiguration.RealTimeProtectionEnabled) { 'Green' } else { 'Red' }+ )++ $cloudStatus = switch ($results.AfterConfiguration.CloudProtection) {+ 0 { 'Disabled' }+ 1 { 'Basic' }+ 2 { 'Advanced' }+ default { 'Unknown' }+ }+ Write-Host " Cloud Protection: $cloudStatus" -ForegroundColor White++ $sampleStatus = switch ($results.AfterConfiguration.SampleSubmission) {+ 0 { 'Always Prompt' }+ 1 { 'Send Safe Samples' }+ 2 { 'Never Send' }+ 3 { 'Send All Samples' }+ default { 'Unknown' }+ }+ Write-Host " Sample Submission: $sampleStatus" -ForegroundColor White++ $puaStatus = switch ($results.AfterConfiguration.PUAProtection) {+ 0 { 'Disabled' }+ 1 { 'Enabled' }+ 2 { 'Audit Mode' }+ default { 'Unknown' }+ }+ Write-Host " PUA Protection: $puaStatus" -ForegroundColor White++ if ($results.AfterConfiguration.ExclusionPaths) {+ Write-Host "`nExclusions:" -ForegroundColor Yellow+ Write-Host " Paths: $($results.AfterConfiguration.ExclusionPaths.Count)" -ForegroundColor White+ if ($results.AfterConfiguration.ExclusionExtensions) {+ Write-Host " Extensions: $($results.AfterConfiguration.ExclusionExtensions.Count)" -ForegroundColor White+ }+ }++ Write-Host "`nRecommendations:" -ForegroundColor Cyan+ Write-Host " 1. Verify protection settings in Windows Security" -ForegroundColor White+ Write-Host " 2. Run a Quick Scan to test configuration" -ForegroundColor White+ Write-Host " 3. Review exclusions regularly" -ForegroundColor White+ Write-Host " 4. Keep automatic updates enabled" -ForegroundColor White+ Write-Host " 5. Monitor Windows Security notifications" -ForegroundColor White++ return $results+ }+}\ No newline at end of filediff --git a/WindowsSecurityAudit.psd1 b/WindowsSecurityAudit.psd1new file mode 100644index 0000000..d64635b--- /dev/null+++ b/WindowsSecurityAudit.psd1@@ -0,0 +1,14 @@+@{+ RootModule = 'WindowsSecurityAudit.psm1'+ ModuleVersion = '1.0.0'+ GUID = 'a8d7c4e5-3b2f-4e8a-9c1d-6f5a8b9d2e7c'+ Author = 'Security Team'+ CompanyName = 'Your Organization'+ Copyright = '(c) 2024. All rights reserved.'+ Description = 'Windows Security Audit Module'+ PowerShellVersion = '5.1'+ FunctionsToExport = '*'+ CmdletsToExport = @()+ VariablesToExport = @()+ AliasesToExport = @()+}\ No newline at end of filediff --git a/WindowsSecurityAudit.psm1 b/WindowsSecurityAudit.psm1new file mode 100644index 0000000..edfe45c--- /dev/null+++ b/WindowsSecurityAudit.psm1@@ -0,0 +1,51 @@+<#+.SYNOPSIS+ Windows Security Audit Module - Main module file+.DESCRIPTION+ Comprehensive Windows security audit toolkit for threat detection and incident response+.VERSION+ 1.0.0+.AUTHOR+ Security Team+#>++# Set strict mode+Set-StrictMode -Version Latest++# Module variables+$script:ModuleRoot = $PSScriptRoot+$script:ModuleVersion = '1.0.0'++# Import all function files+$Public = @(Get-ChildItem -Path "$PSScriptRoot\Core\*.ps1" -ErrorAction SilentlyContinue)+$Public += @(Get-ChildItem -Path "$PSScriptRoot\Detection\*.ps1" -ErrorAction SilentlyContinue)+$Public += @(Get-ChildItem -Path "$PSScriptRoot\Analysis\*.ps1" -ErrorAction SilentlyContinue)+$Public += @(Get-ChildItem -Path "$PSScriptRoot\Response\*.ps1" -ErrorAction SilentlyContinue)+$Public += @(Get-ChildItem -Path "$PSScriptRoot\Enterprise\*.ps1" -ErrorAction SilentlyContinue)+$Public += @(Get-ChildItem -Path "$PSScriptRoot\Hardening\*.ps1" -ErrorAction SilentlyContinue)+$Public += @(Get-ChildItem -Path "$PSScriptRoot\WindowsDefender\*.ps1" -ErrorAction SilentlyContinue)+$Public += @(Get-ChildItem -Path "$PSScriptRoot\ThreatHunting\*.ps1" -ErrorAction SilentlyContinue)+$Public += @(Get-ChildItem -Path "$PSScriptRoot\Compliance\*.ps1" -ErrorAction SilentlyContinue)++$Public += @(Get-ChildItem -Path "$PSScriptRoot\ActiveDirectory\*.ps1" -ErrorAction SilentlyContinue)+$Public += @(Get-ChildItem -Path "$PSScriptRoot\Vulnerability\*.ps1" -ErrorAction SilentlyContinue)+$Public += @(Get-ChildItem -Path "$PSScriptRoot\Forensics\*.ps1" -ErrorAction SilentlyContinue)+$Public += @(Get-ChildItem -Path "$PSScriptRoot\CloudSecurity\*.ps1" -ErrorAction SilentlyContinue)+$Public += @(Get-ChildItem -Path "$PSScriptRoot\Reporting\*.ps1" -ErrorAction SilentlyContinue)++$Private = @(Get-ChildItem -Path "$PSScriptRoot\Private\*.ps1" -ErrorAction SilentlyContinue)++# Import all function files+foreach ($import in @($Public + $Private)) {+ try {+ . $import.FullName+ }+ catch {+ Write-Error "Failed to import function $($import.FullName): $_"+ }+}++# Export public functions+Export-ModuleMember -Function $Public.BaseName++Write-Host "Windows Security Audit Module v$script:ModuleVersion loaded successfully" -ForegroundColor Green\ No newline at end of file