diff --git a/Compare-SecurityReports.ps1 b/Compare-SecurityReports.ps1 new file mode 100644 index 0000000..f937816 --- /dev/null +++ b/Compare-SecurityReports.ps1 @@ -0,0 +1,103 @@ +<# +.SYNOPSIS +Compare two CSV reports by explicit unique keys, showing added/removed/changed entries. +.DESCRIPTION +No external modules or service connections required. Keys and values are compared +case-sensitively as CSV strings; null versus empty cannot be distinguished in CSV. +Composite keys are JSON-encoded to avoid delimiter collisions. Duplicate/blank keys +are rejected. By default schemas must match; use -CompareProperty for an explicit +shared subset. Header-only CSVs are supported; empty files without headers are not. +Added/Removed rows contain complete row JSON; Changed rows contain per-property +values. Output cannot overwrite either input, even with -Force. +.EXAMPLE +.\Compare-SecurityReports.ps1 -BeforePath .\before.csv -AfterPath .\after.csv -Key ComputerName,Id -OutputPath .\changes.csv +.EXAMPLE +.\Compare-SecurityReports.ps1 -BeforePath .\old.csv -AfterPath .\new.csv -Key Id -CompareProperty Enabled,Name +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)][string]$BeforePath, + [Parameter(Mandatory)][string]$AfterPath, + [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string[]]$Key, + [string[]]$CompareProperty, + [string]$OutputPath, + [switch]$Force +) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +function Read-SecurityReport { + param([string]$Path) + $records = @(Import-Csv -LiteralPath $Path -ErrorAction Stop -WarningAction Stop) + $schema = if ($records.Count) { @($records[0].PSObject.Properties.Name) } else { + # Duplicate a header-only CSV into a synthetic data row to parse its schema, + # including quoted commas/newlines, without hand-splitting the CSV format. + $text = Get-Content -LiteralPath $Path -Raw -ErrorAction Stop + if ([string]::IsNullOrWhiteSpace($text)) { throw "CSV has no header: $Path" } + $headerRow = @(ConvertFrom-Csv -InputObject ($text.TrimEnd() + "`n" + $text) -ErrorAction Stop -WarningAction Stop) + if (-not $headerRow.Count) { throw "CSV has no readable header: $Path" } + @($headerRow[0].PSObject.Properties.Name) + } + [pscustomobject]@{ Records = $records; Schema = $schema } +} +function ConvertTo-ReportIndex { + param([object[]]$Records, [string]$Label) + $index = [Collections.Generic.Dictionary[string,object]]::new([StringComparer]::Ordinal) + foreach ($record in $Records) { + $parts = [ordered]@{} + foreach ($column in $Key) { + $value = [string]$record.$column + if ([string]::IsNullOrWhiteSpace($value)) { throw "Blank key '$column' in $Label." } + $parts[$column] = $value + } + $encoded = ConvertTo-Json -InputObject $parts -Compress + if ($index.ContainsKey($encoded)) { throw "Duplicate key in ${Label}: $encoded" } + $index.Add($encoded, $record) + } + # Preserve an empty dictionary as one return value. + ,$index +} +$before = Read-SecurityReport $BeforePath +$after = Read-SecurityReport $AfterPath +if (@($Key | Sort-Object -Unique).Count -ne $Key.Count) { throw 'Key columns must be unique.' } +foreach ($column in $Key) { + if ($column -notin $before.Schema -or $column -notin $after.Schema) { throw "Key column not present in both reports: $column" } +} +if ($CompareProperty) { + foreach ($column in $CompareProperty) { + if ($column -notin $before.Schema -or $column -notin $after.Schema) { throw "Comparison column not present in both reports: $column" } + } + $columns = @($CompareProperty | Sort-Object -Unique | Where-Object { $_ -notin $Key }) +} else { + if (@($before.Schema | Where-Object { $_ -notin $after.Schema }).Count -or @($after.Schema | Where-Object { $_ -notin $before.Schema }).Count) { + throw 'Report schemas differ. Use -CompareProperty to select a shared subset explicitly.' + } + $columns = @($before.Schema | Where-Object { $_ -notin $Key }) +} +if ($OutputPath) { + $destination = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutputPath) + foreach ($inputPath in $BeforePath,$AfterPath) { + if ($destination -eq (Resolve-Path -LiteralPath $inputPath).ProviderPath) { throw 'OutputPath cannot overwrite an input report.' } + } +} +$old = ConvertTo-ReportIndex -Records $before.Records -Label Before +$new = ConvertTo-ReportIndex -Records $after.Records -Label After +$allKeys = [Collections.Generic.SortedSet[string]]::new([StringComparer]::Ordinal) +foreach ($entryKey in $old.Keys) { $null = $allKeys.Add($entryKey) } +foreach ($entryKey in $new.Keys) { $null = $allKeys.Add($entryKey) } +$rows = @(foreach ($entryKey in $allKeys) { + if (-not $old.ContainsKey($entryKey)) { + [pscustomobject]@{ ChangeType = 'Added'; Key = $entryKey; Property = '*'; Before = $null; After = (ConvertTo-Json -InputObject $new[$entryKey] -Compress) } + } elseif (-not $new.ContainsKey($entryKey)) { + [pscustomobject]@{ ChangeType = 'Removed'; Key = $entryKey; Property = '*'; Before = (ConvertTo-Json -InputObject $old[$entryKey] -Compress); After = $null } + } else { + foreach ($column in $columns) { + $previous = [string]$old[$entryKey].$column + $current = [string]$new[$entryKey].$column + if (-not [string]::Equals($previous, $current, [StringComparison]::Ordinal)) { + [pscustomobject]@{ ChangeType = 'Changed'; Key = $entryKey; Property = $column; Before = $previous; After = $current } + } + } + } +}) +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/Get-ADPrivilegedGroupMembers.ps1 b/Get-ADPrivilegedGroupMembers.ps1 new file mode 100644 index 0000000..74c43fa --- /dev/null +++ b/Get-ADPrivilegedGroupMembers.ps1 @@ -0,0 +1,69 @@ +<# +.SYNOPSIS +Report direct and nested membership paths in selected privileged AD groups. +.DESCRIPTION +Requires ActiveDirectory and directory-read access. Defaults to groups marked +adminCount=1 in the selected domain; this is a review set, not a complete privilege +model. Specify -GroupIdentity for custom groups. Does not include primary-group +membership, ACL delegation, unresolvable foreign principals, or other domains' +groups automatically. Group cycles and depth limits are emitted explicitly. +.EXAMPLE +.\Get-ADPrivilegedGroupMembers.ps1 -Server dc.example.com -OutputPath .\privileged.csv +.EXAMPLE +.\Get-ADPrivilegedGroupMembers.ps1 -Server dc.example.com -GroupIdentity 'Domain Admins','Helpdesk Tier 1' +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Server, + [string[]]$GroupIdentity, + [ValidateRange(1,100)][int]$MaxDepth = 32, + [string]$OutputPath, + [switch]$Force +) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +$roots = if ($GroupIdentity) { + @($GroupIdentity | Sort-Object -Unique | ForEach-Object { Get-ADGroup -Identity $_ -Server $Server -ErrorAction Stop }) +} else { + @(Get-ADGroup -Filter 'adminCount -eq 1' -Server $Server -ErrorAction Stop) +} +$cache = @{} +$rows = @(foreach ($rootGroup in $roots) { + $stack = [Collections.Generic.Stack[object]]::new() + $stack.Push(@{ Group = $rootGroup; Names = @($rootGroup.Name); DNs = @($rootGroup.DistinguishedName); Depth = 0 }) + while ($stack.Count) { + $current = $stack.Pop() + $dn = $current.Group.DistinguishedName + if (-not $cache.ContainsKey($dn)) { + $cache[$dn] = @(Get-ADGroupMember -Identity $dn -Server $Server -ErrorAction Stop) + } + foreach ($member in $cache[$dn]) { + $depth = $current.Depth + 1 + $status = 'Member' + if ($member.ObjectClass -eq 'group') { + if ($member.DistinguishedName -in $current.DNs) { $status = 'Cycle' } + elseif ($depth -ge $MaxDepth) { $status = 'DepthLimit' } + else { $status = 'NestedGroup' } + } elseif ($member.ObjectClass -eq 'foreignSecurityPrincipal') { $status = 'ForeignPrincipalNotExpanded' } + [pscustomobject]@{ + Server = $Server + RootGroup = $rootGroup.Name + RootGroupDN = $rootGroup.DistinguishedName + MemberName = $member.Name + SamAccountName = $member.SamAccountName + ObjectClass = $member.ObjectClass + MemberDN = $member.DistinguishedName + SID = [string]$member.SID + Depth = $depth + MembershipPath = (@($current.Names) + @($member.Name)) -join ' -> ' + DistinguishedNamePath = (@($current.DNs) + @($member.DistinguishedName)) -join ' -> ' + Status = $status + } + if ($status -eq 'NestedGroup') { + $stack.Push(@{ Group = $member; Names = @($current.Names) + @($member.Name); DNs = @($current.DNs) + @($member.DistinguishedName); Depth = $depth }) + } + } + } +}) +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/Get-ADStaleAccounts.ps1 b/Get-ADStaleAccounts.ps1 new file mode 100644 index 0000000..1691249 --- /dev/null +++ b/Get-ADStaleAccounts.ps1 @@ -0,0 +1,66 @@ +<# +.SYNOPSIS +Report user and computer inactivity candidates without disabling or deleting them. +.DESCRIPTION +Requires ActiveDirectory and directory-read access. LastLogonDate is replicated +and approximate (commonly delayed up to 14 days); this is not exact last-logon +evidence. Accounts without that value use creation date and are labelled separately. +Unknown timestamps are included as insufficient evidence, never labelled stale. +Enabled accounts only by default. Review service accounts and other activity before +any remediation. PasswordLastSet is included as an additional review signal. +.EXAMPLE +.\Get-ADStaleAccounts.ps1 -Server dc.example.com -InactiveDays 90 -OutputPath .\stale.csv +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$Server, + [ValidateSet('All','User','Computer')][string]$AccountType = 'All', + [ValidateRange(1,36500)][int]$InactiveDays = 90, + [string]$SearchBase, + [pscredential]$Credential, + [switch]$IncludeDisabled, + [datetimeoffset]$AsOf = [datetimeoffset]::UtcNow, + [string]$OutputPath, + [switch]$Force +) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +if ($InactiveDays -lt 15) { Write-Warning 'Short thresholds can misclassify activity because LastLogonDate is replicated with delay.' } +$query = @{ Server = $Server; Filter = 'Enabled -eq $true'; Properties = 'LastLogonDate','whenCreated','PasswordLastSet','Enabled'; ErrorAction = 'Stop' } +if ($IncludeDisabled) { $query.Filter = '*' } +if ($SearchBase) { $query.SearchBase = $SearchBase } +if ($Credential) { $query.Credential = $Credential } +$cutoff = $AsOf.UtcDateTime.AddDays(-$InactiveDays) +$rows = @(foreach ($type in @('User','Computer')) { + if ($AccountType -ne 'All' -and $AccountType -ne $type) { continue } + $accounts = if ($type -eq 'User') { @(Get-ADUser @query) } else { @(Get-ADComputer @query) } + foreach ($account in $accounts) { + $reference = $null + $reason = 'InsufficientTimestamps' + if ($null -ne $account.LastLogonDate) { + $reference = ([datetime]$account.LastLogonDate).ToUniversalTime() + $reason = 'ApproximateLastLogon' + } elseif ($null -ne $account.whenCreated) { + $reference = ([datetime]$account.whenCreated).ToUniversalTime() + $reason = 'NoReplicatedLogonCreationFallback' + } + if ($null -ne $reference -and $reference -gt $cutoff) { continue } + [pscustomobject]@{ + Server = $Server + AccountType = $type + Name = $account.Name + SamAccountName = $account.SamAccountName + DistinguishedName = $account.DistinguishedName + Enabled = $account.Enabled + LastLogonDate = $account.LastLogonDate + Created = $account.whenCreated + PasswordLastSet = $account.PasswordLastSet + DaysSinceReference = if ($null -ne $reference) { [math]::Floor(($AsOf.UtcDateTime - $reference).TotalDays) } else { $null } + IsInactivityCandidate = if ($null -ne $reference) { $true } else { $null } + Evidence = $reason + CutoffUtc = $cutoff.ToString('o') + } + } +}) +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/Get-AzurePublicExposure.ps1 b/Get-AzurePublicExposure.ps1 new file mode 100644 index 0000000..019d271 --- /dev/null +++ b/Get-AzurePublicExposure.ps1 @@ -0,0 +1,74 @@ +<# +.SYNOPSIS +Inventory Azure public IPs and NSG rules potentially allowing management access. +.DESCRIPTION +Connect-AzAccount first. Requires Az.Accounts, Az.Network and Reader access in each +requested subscription. Includes assigned/unassigned public IPs and standalone NSG +candidate rules (including plural fields, Internet/IPv4/IPv6 any-source and ranges). +These are configured-rule findings, NOT proof of reachability. Does not evaluate +deny precedence, effective NIC/subnet policy, routes, firewalls, JIT, load-balancer +NAT, application gateways or guest listeners, and does not correlate IPs to rules. +The caller's Azure context is restored even on errors. No network probing occurs. +.EXAMPLE +.\Get-AzurePublicExposure.ps1 -TenantId TENANT-GUID -SubscriptionId SUB-GUID -OutputPath .\exposure.csv +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)][string]$TenantId, + [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string[]]$SubscriptionId, + [ValidateRange(1,65535)][int[]]$ManagementPort = @(22,3389,5985,5986), + [string]$OutputPath, + [switch]$Force +) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +function Test-ManagementPortRange { + param([string[]]$Ranges, [int]$Port) + foreach ($range in $Ranges) { + if ($range -eq '*') { return $true } + if ($range -match '^\d+$' -and [int]$range -eq $Port) { return $true } + if ($range -match '^(\d+)-(\d+)$' -and $Port -ge [int]$Matches[1] -and $Port -le [int]$Matches[2]) { return $true } + } + $false +} +$original = Get-AzContext -ErrorAction Stop +if (-not $original -or $original.Tenant.Id -ne $TenantId) { throw 'Connect-AzAccount to the requested tenant first.' } +$subscriptions = @(Get-AzSubscription -TenantId $TenantId -ErrorAction Stop | Where-Object { $_.Id -in $SubscriptionId }) +foreach ($id in $SubscriptionId) { if ($id -notin $subscriptions.Id) { throw "Subscription not accessible in requested tenant: $id" } } +$rows = @(foreach ($subscription in $subscriptions) { + try { + $context = Set-AzContext -Tenant $TenantId -SubscriptionId $subscription.Id -Scope Process -ErrorAction Stop + foreach ($ip in @(Get-AzPublicIpAddress -DefaultProfile $context -ErrorAction Stop)) { + [pscustomobject]@{ + FindingType = 'PublicIpInventory'; TenantId = $TenantId; SubscriptionId = $subscription.Id + ResourceId = $ip.Id; ResourceName = $ip.Name; ResourceGroup = $ip.ResourceGroupName; Location = $ip.Location + PublicIpAddress = $ip.IpAddress; AssociatedResourceIds = (@($ip.IpConfiguration.Id) + @($ip.NatGateway.Id) | Where-Object { $_ }) -join ';' + RuleName = $null; Priority = $null; Protocol = $null; SourceAddresses = $null + DestinationAddresses = $null; DestinationPorts = $null; MatchedManagementPorts = $null + DestinationASGs = $null; Assessment = 'InventoryOnlyNotReachabilityProof' + } + } + foreach ($nsg in @(Get-AzNetworkSecurityGroup -DefaultProfile $context -ErrorAction Stop)) { + foreach ($rule in @($nsg.SecurityRules) + @($nsg.DefaultSecurityRules)) { + if (-not $rule -or $rule.Direction -ne 'Inbound' -or $rule.Access -ne 'Allow' -or $rule.Protocol -notin 'Tcp','Udp','*') { continue } + $sources = @(@($rule.SourceAddressPrefix) + @($rule.SourceAddressPrefixes) | Where-Object { $_ }) + if (-not @($sources | Where-Object { $_ -in '*','Internet','0.0.0.0/0','::/0' }).Count) { continue } + $ports = @(@($rule.DestinationPortRange) + @($rule.DestinationPortRanges) | Where-Object { $_ }) + $matched = @($ManagementPort | Sort-Object -Unique | Where-Object { Test-ManagementPortRange -Ranges $ports -Port $_ }) + if (-not $matched.Count) { continue } + [pscustomobject]@{ + FindingType = 'PotentialManagementExposure'; TenantId = $TenantId; SubscriptionId = $subscription.Id + ResourceId = $nsg.Id; ResourceName = $nsg.Name; ResourceGroup = $nsg.ResourceGroupName; Location = $nsg.Location + PublicIpAddress = $null; AssociatedResourceIds = (@($nsg.NetworkInterfaces.Id) + @($nsg.Subnets.Id) | Where-Object { $_ }) -join ';' + RuleName = $rule.Name; Priority = $rule.Priority; Protocol = $rule.Protocol; SourceAddresses = $sources -join ';' + DestinationAddresses = (@($rule.DestinationAddressPrefix) + @($rule.DestinationAddressPrefixes) | Where-Object { $_ }) -join ';' + DestinationPorts = $ports -join ';'; MatchedManagementPorts = $matched -join ';' + DestinationASGs = @($rule.DestinationApplicationSecurityGroups | ForEach-Object { $_.Id }) -join ';' + Assessment = 'CandidateRuleNotEffectiveAccess' + } + } + } + } finally { $null = Set-AzContext -Context $original -Scope Process -ErrorAction Stop } +}) +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/Get-EntraAppCredentialExpiry.ps1 b/Get-EntraAppCredentialExpiry.ps1 new file mode 100644 index 0000000..2818d98 --- /dev/null +++ b/Get-EntraAppCredentialExpiry.ps1 @@ -0,0 +1,57 @@ +<# +.SYNOPSIS +Report expiring application secrets and certificates without emitting secret values. +.DESCRIPTION +Connect-MgGraph to the requested tenant first. Requires Microsoft.Graph.Applications, +Application.Read.All and a supported directory role for delegated access. Reads +application registrations, not service-principal credentials. Explicit output +projection excludes SecretText, Hint, certificate bytes and other credential data. +Default output includes expired, expiring, missing-expiry and not-yet-valid metadata. +Use -IncludeAll for credentials outside the threshold too. +.EXAMPLE +.\Get-EntraAppCredentialExpiry.ps1 -TenantId TENANT-GUID -WithinDays 30 -OutputPath .\expiry.csv +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$TenantId, + [ValidateRange(0,36500)][int]$WithinDays = 30, + [datetimeoffset]$AsOf = [datetimeoffset]::UtcNow, + [switch]$IncludeAll, + [string]$OutputPath, + [switch]$Force +) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +Assert-ToolkitGraphContext -TenantId $TenantId +$applications = @(Get-MgApplication -All -Property id,appId,displayName,passwordCredentials,keyCredentials -ErrorAction Stop) +$rows = @(foreach ($application in $applications) { + foreach ($kind in 'Secret','Certificate') { + $credentials = if ($kind -eq 'Secret') { @($application.PasswordCredentials) } else { @($application.KeyCredentials) } + foreach ($metadata in $credentials) { + if ($null -eq $metadata) { continue } + $start = if ($metadata.StartDateTime) { [datetimeoffset]$metadata.StartDateTime } else { $null } + $end = if ($metadata.EndDateTime) { [datetimeoffset]$metadata.EndDateTime } else { $null } + $status = if ($null -eq $end) { 'MissingExpiry' } + elseif ($end -le $AsOf) { 'Expired' } + elseif ($null -ne $start -and $start -gt $AsOf) { 'NotYetValid' } + elseif ($end -le $AsOf.AddDays($WithinDays)) { 'Expiring' } + else { 'Valid' } + if ($status -eq 'Valid' -and -not $IncludeAll) { continue } + [pscustomobject]@{ + TenantId = $TenantId + ApplicationObjectId = $application.Id + AppId = $application.AppId + ApplicationName = $application.DisplayName + CredentialType = $kind + CredentialId = $metadata.KeyId + CredentialName = $metadata.DisplayName + StartUtc = if ($null -ne $start) { $start.UtcDateTime.ToString('o') } else { $null } + EndUtc = if ($null -ne $end) { $end.UtcDateTime.ToString('o') } else { $null } + DaysRemaining = if ($null -ne $end) { [math]::Floor(($end - $AsOf).TotalDays) } else { $null } + Status = $status + } + } + } +}) +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/Get-O365MailboxForwarding.ps1 b/Get-O365MailboxForwarding.ps1 new file mode 100644 index 0000000..ee64b64 --- /dev/null +++ b/Get-O365MailboxForwarding.ps1 @@ -0,0 +1,128 @@ +<# +.SYNOPSIS +Report mailbox forwarding and hidden/visible inbox forwarding rules. +.DESCRIPTION +Connect exactly one Exchange Online session first. Requires ExchangeOnlineManagement +and RBAC permitting Get-Mailbox, Get-InboxRule, Get-Recipient and Get-AcceptedDomain. +Get-InboxRule is not supported for View-Only Organization Management/Global Reader. +All configured destinations are returned by default, including disabled rules. +-ExternalOnly retains external and unresolved targets for review. Mail contacts are +resolved to ExternalEmailAddress; groups are labelled Unknown, not expanded. Does +not follow forwarding chains or determine whether outbound policies allow delivery. +Resolution/permission/service failures are not silently treated as safe destinations. +.EXAMPLE +.\Get-O365MailboxForwarding.ps1 -ExternalOnly -OutputPath .\forwarding.csv +.EXAMPLE +.\Get-O365MailboxForwarding.ps1 -MailboxIdentity alice@example.com +#> +[CmdletBinding()] +param([string[]]$MailboxIdentity, [switch]$ExternalOnly, [string]$OutputPath, [switch]$Force) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +if (@(Get-ConnectionInformation -ErrorAction Stop | Where-Object { $_.State -eq 'Connected' }).Count -ne 1) { + throw 'Connect exactly one Exchange Online session before running.' +} +$acceptedDomains = @(Get-AcceptedDomain -ErrorAction Stop) +if (-not $acceptedDomains.Count) { throw 'No accepted domains returned; cannot classify forwarding destinations.' } +function Get-ForwardingScope { + param([string]$Address) + if (-not $Address) { return 'Unknown' } + $domain = ($Address -split '@')[-1] + foreach ($accepted in $acceptedDomains) { + $name = [string]$accepted.DomainName + if ($name.StartsWith('*.') -and $domain.EndsWith($name.Substring(1), [StringComparison]::OrdinalIgnoreCase)) { return 'InternalDomain' } + if ($domain -eq $name -or ($accepted.MatchSubDomains -and $domain.EndsWith('.' + $name, [StringComparison]::OrdinalIgnoreCase))) { return 'InternalDomain' } + } + 'External' +} +function ConvertTo-ForwardingSmtpAddress { + param([object]$Value) + $text = ([string]$Value).Trim() + if (-not $text) { return $null } + if ($text -match '(?i)\[SMTP:([^\]]+)\]') { $text = $Matches[1] } + $text = $text -replace '(?i)^smtp:', '' + try { + $address = [System.Net.Mail.MailAddress]::new($text).Address + if ($address -notmatch '@') { return $null } + $address + } catch [FormatException] { return $null } +} +$cache = @{} +function Resolve-ForwardingDestination { + param([object]$Destination) + $raw = [string]$Destination + if ($cache.ContainsKey($raw)) { return $cache[$raw] } + $smtp = $null + foreach ($value in @($Destination.ExternalEmailAddress, $Destination.PrimarySmtpAddress, $Destination.Address, $Destination.SmtpAddress, $raw)) { + $smtp = ConvertTo-ForwardingSmtpAddress $value + if ($smtp) { break } + } + $scope = Get-ForwardingScope $smtp + $resolution = 'SmtpAddress' + if ($scope -ne 'External') { + $identity = if ($smtp) { $smtp } elseif ($Destination.DistinguishedName) { [string]$Destination.DistinguishedName } else { $raw } + try { + $recipient = Get-Recipient -Identity $identity -ErrorAction Stop + if ($recipient.ExternalEmailAddress) { + $smtp = ConvertTo-ForwardingSmtpAddress $recipient.ExternalEmailAddress + $scope = Get-ForwardingScope $smtp + $resolution = 'ExternalRecipientAddress' + } elseif ([string]$recipient.RecipientType -match 'Group') { + $smtp = ConvertTo-ForwardingSmtpAddress $recipient.PrimarySmtpAddress + $scope = 'Unknown' + $resolution = 'GroupNotExpanded' + } else { + $smtp = ConvertTo-ForwardingSmtpAddress $recipient.PrimarySmtpAddress + $scope = Get-ForwardingScope $smtp + $resolution = 'RecipientResolved' + } + } catch { + if ($_.FullyQualifiedErrorId -notmatch 'ManagementObjectNotFound|ManagementObjectAmbiguous') { throw } + $scope = 'Unknown' + $resolution = 'UnresolvedRecipient' + Write-Warning "Unable to resolve forwarding recipient: $raw" + } + } + $result = [pscustomobject]@{ RawTarget = $raw; TargetAddress = $smtp; Scope = $scope; Resolution = $resolution } + $cache[$raw] = $result + $result +} +$mailboxes = if ($MailboxIdentity) { + @($MailboxIdentity | Sort-Object -Unique | ForEach-Object { Get-Mailbox -Identity $_ -ErrorAction Stop }) +} else { + @(Get-Mailbox -RecipientTypeDetails UserMailbox,SharedMailbox -ResultSize Unlimited -ErrorAction Stop) +} +$rows = @(foreach ($mailbox in $mailboxes) { + $identity = [string]$mailbox.PrimarySmtpAddress + if (-not $identity) { throw 'A mailbox has no primary SMTP address; cannot query its inbox rules.' } + $settings = [Collections.Generic.List[object]]::new() + foreach ($field in 'ForwardingAddress','ForwardingSmtpAddress') { + if ($mailbox.$field) { $settings.Add(@{ Type = 'Mailbox'; Name = $null; Id = $null; Enabled = $null; Action = $field; Target = $mailbox.$field }) } + } + foreach ($rule in @(Get-InboxRule -Mailbox $identity -IncludeHidden -ResultSize Unlimited -ErrorAction Stop)) { + foreach ($action in 'ForwardTo','RedirectTo','ForwardAsAttachmentTo') { + foreach ($target in @($rule.$action)) { + if ($null -ne $target) { $settings.Add(@{ Type = 'InboxRule'; Name = $rule.Name; Id = $rule.Identity; Enabled = $rule.Enabled; Action = $action; Target = $target }) } + } + } + } + foreach ($setting in $settings) { + $destination = Resolve-ForwardingDestination $setting.Target + if ($ExternalOnly -and $destination.Scope -eq 'InternalDomain') { continue } + [pscustomobject]@{ + Mailbox = $identity + SourceType = $setting.Type + RuleName = $setting.Name + RuleIdentity = [string]$setting.Id + RuleEnabled = $setting.Enabled + Action = $setting.Action + RawTarget = $destination.RawTarget + TargetAddress = $destination.TargetAddress + TargetScope = $destination.Scope + Resolution = $destination.Resolution + DeliverToMailboxAndForward = $mailbox.DeliverToMailboxAndForward + } + } +}) +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/Get-WindowsPersistence.ps1 b/Get-WindowsPersistence.ps1 new file mode 100644 index 0000000..d938fa5 --- /dev/null +++ b/Get-WindowsPersistence.ps1 @@ -0,0 +1,93 @@ +<# +.SYNOPSIS +Collect common Windows persistence configuration without executing target commands. +.DESCRIPTION +Requires Windows, CIM, ScheduledTasks, registry and filesystem read access. Use +WinRM and appropriate credentials for remote hosts. Collects all services, task +actions (including disabled tasks), machine Run/RunOnce values, loaded user hives' +Run/RunOnce values and common/per-profile Startup files. Does not load user hives, +resolve shortcuts, start tasks, inspect WMI subscriptions, or declare entries +malicious. Registry and startup coverage is limited to readable/loaded profiles. +Failure to read a selected source terminates the report. Command lines may contain +sensitive information; protect exports. ComputerName + Id is a comparison key. +.EXAMPLE +.\Get-WindowsPersistence.ps1 -OutputPath .\persistence.csv +.EXAMPLE +.\Get-WindowsPersistence.ps1 -ComputerName server.example.com -Credential (Get-Credential) +#> +[CmdletBinding()] +param([string]$ComputerName = $env:COMPUTERNAME, [pscredential]$Credential, [string]$OutputPath, [switch]$Force) +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/Private/Common.ps1" +$collector = { + $ErrorActionPreference = 'Stop' + if ($env:OS -ne 'Windows_NT') { throw 'Persistence collection requires Windows.' } + foreach ($service in @(Get-CimInstance -ClassName Win32_Service -ErrorAction Stop)) { + [pscustomobject]@{ + ComputerName = $env:COMPUTERNAME; Id = 'Service:' + $service.Name; Type = 'Service'; Name = $service.Name + Location = 'Win32_Service'; Command = $service.PathName; Arguments = $null + User = $service.StartName; State = $service.State; StartMode = $service.StartMode + } + } + foreach ($task in @(Get-ScheduledTask -ErrorAction Stop)) { + $index = 0 + foreach ($action in @($task.Actions)) { + $index++ + $command = if ($action.Execute) { $action.Execute } else { 'NonExecAction:' + [string]$action.ClassId } + [pscustomobject]@{ + ComputerName = $env:COMPUTERNAME; Id = "Task:$($task.TaskPath)$($task.TaskName):$index"; Type = 'ScheduledTask'; Name = $task.TaskName + Location = $task.TaskPath; Command = $command; Arguments = $action.Arguments + User = $task.Principal.UserId; State = [string]$task.State; StartMode = $null + } + } + } + $keys = [Collections.Generic.List[string]]::new() + foreach ($suffix in 'Run','RunOnce') { + $keys.Add("Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\$suffix") + $keys.Add("Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\$suffix") + } + foreach ($hive in @(Get-ChildItem -LiteralPath 'Registry::HKEY_USERS' -ErrorAction Stop)) { + if ($hive.PSChildName -notmatch '^S-1-(5-21|12-1)-[\d-]+$') { continue } + foreach ($suffix in 'Run','RunOnce') { + $keys.Add("Registry::HKEY_USERS\$($hive.PSChildName)\SOFTWARE\Microsoft\Windows\CurrentVersion\$suffix") + $keys.Add("Registry::HKEY_USERS\$($hive.PSChildName)\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\$suffix") + } + } + foreach ($key in $keys) { + if (-not (Test-Path -LiteralPath $key -ErrorAction Stop)) { continue } + $values = Get-ItemProperty -LiteralPath $key -ErrorAction Stop + foreach ($property in $values.PSObject.Properties) { + if ($property.Name -in 'PSPath','PSParentPath','PSChildName','PSDrive','PSProvider') { continue } + [pscustomobject]@{ + ComputerName = $env:COMPUTERNAME; Id = "Registry:${key}:$($property.Name)"; Type = 'RegistryAutorun'; Name = $property.Name + Location = $key; Command = [string]$property.Value; Arguments = $null + User = if ($key -like 'Registry::HKEY_USERS*') { ($key -split '\\')[1] } else { 'Machine' } + State = 'Configured'; StartMode = $null + } + } + } + $startupPaths = [Collections.Generic.List[string]]::new() + $common = [Environment]::GetFolderPath('CommonStartup') + if ($common) { $startupPaths.Add($common) } + foreach ($userFolder in @(Get-ChildItem -LiteralPath (Join-Path $env:SystemDrive Users) -Directory -Force -ErrorAction Stop)) { + $startupPaths.Add((Join-Path $userFolder.FullName 'AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup')) + } + foreach ($startupPath in $startupPaths) { + if (-not (Test-Path -LiteralPath $startupPath -PathType Container -ErrorAction Stop)) { continue } + foreach ($file in @(Get-ChildItem -LiteralPath $startupPath -File -Force -ErrorAction Stop)) { + [pscustomobject]@{ + ComputerName = $env:COMPUTERNAME; Id = 'Startup:' + $file.FullName; Type = 'StartupFile'; Name = $file.Name + Location = $startupPath; Command = $file.FullName; Arguments = $null + User = 'SeeProfilePath'; State = 'PresentTargetNotExecuted'; StartMode = $null + } + } + } +} +$local = $ComputerName -in '.', 'localhost', $env:COMPUTERNAME +$rows = if ($local -and -not $Credential) { @(& $collector) } else { + $query = @{ ComputerName = $ComputerName; ScriptBlock = $collector; ErrorAction = 'Stop' } + if ($Credential) { $query.Credential = $Credential } + @(Invoke-Command @query | Select-Object ComputerName,Id,Type,Name,Location,Command,Arguments,User,State,StartMode) +} +if ($OutputPath) { Export-ToolkitReport -InputObject $rows -Path $OutputPath -Force:$Force } +$rows diff --git a/README.md b/README.md index 0301e1e..0ca9189 100644 --- a/README.md +++ b/README.md @@ -33,42 +33,63 @@ For unattended jobs use the service's supported certificate or managed-identity flow with the documented permissions and roles. Do not embed passwords or tokens. Scripts reuse the caller's session and do not disconnect it. -## Script catalog +## Full script catalog + +All 35 runnable scripts are listed below. See [security audit examples](docs/SecurityAudits.md) for the seven new reports and their limits. | Area / script | Purpose | Prerequisites / access | Changes systems? | |---|---|---|---| -| `Export-ADGroupMembers.ps1` | Direct/recursive members, including object type | ActiveDirectory; directory read | No | -| `Export-ADGroupMemberCreationDates.ps1` | Creation dates of user members | ActiveDirectory; directory read | No | -| `GrabAD-GroupMembers.ps1` | Compatibility entry point for group report | Same as group report | No | -| `Get-ADUserEnabledStatus.ps1` | Enabled/disabled status from an identity list | ActiveDirectory; directory read | No | -| `Get-ADPasswordNeverExpires.ps1` | Non-expiring password configuration | ActiveDirectory; directory read | No | -| `Get-ADExpiredAccounts.ps1` | Enabled expired accounts; optional no-expiration report | ActiveDirectory; directory read | No | -| `Get-ADMissingPhoneNumbers.ps1` | Enabled users missing all phone fields | ActiveDirectory; directory read | No | -| `Get-ADRecentlyCreatedUsers.ps1` | Recently created users | ActiveDirectory; directory read | No | -| `Get-ADUserCreationAudit.ps1` | Match creator evidence in DC event 4720 by target SID | AD read; DC Security-log read; retained account-management auditing | No | -| `Get-ADUserLoginData.ps1` | Password/logon metadata | ActiveDirectory; directory read | No | -| `Copy_AD_UserGroups.ps1` | Copy reviewed direct memberships | ActiveDirectory; delegated group management | **Yes** | -| `verify-credentials.ps1` | Validate one credential against a domain | DirectoryServices; domain connectivity | Authentication attempt; can affect lockout counters | -| `ExportNSG_All_BySubscription.ps1` | NSG rule audit with subscription identity and plural fields | Az.Accounts, Az.Network; Reader in selected subscriptions | Session context temporarily switched and restored | -| `Export-GraphDevices.ps1` | Directory-device report with optional filters | Graph Authentication + Identity.DirectoryManagement; Device.Read.All | No | -| `Get-GraphDeviceCompliance.ps1` | Directory compliance flags | Same as device report | No | -| `Find-GraphDevice.ps1` | Device display-name prefix search | Same as device report | No | -| `Get-GraphWindowsDevices.ps1` | Windows directory devices | Same as device report | No | -| `GraphAPI-GuestUserStatus.ps1` | Latest available interactive guest sign-in | Graph Users + Reports; User.Read.All, AuditLog.Read.All; supported role/license | No | -| `Set-GraphDeviceExtensionAttribute.ps1` | Set one selected attribute, then read it back | Graph device update/read; see permission notes below | **Yes** | -| `Export-O365MailboxHolds.ps1` | Mailbox hold flags and retention-processing pauses | ExchangeOnlineManagement; mailbox-read RBAC | No | -| `Export-O365BlockedSendersAndDomains.ps1` | Selected anti-spam policy's blocked entries | ExchangeOnlineManagement; policy-read RBAC | No | -| `BlockLegacyAuthentication.ps1` | Apply a blocking policy or restore saved assignments | ExchangeOnlineManagement; policy/user-management RBAC | **Yes** | -| `DefenderToolkit.ps1` | Explicit Defender status, scans and configuration actions | Defender module; elevation for changes | **Yes**, except Status/Preferences/Detections | -| `Get-BrowserHistory.ps1` | Chrome/Edge/Firefox SQLite history with UTC timestamps | Windows; sqlite3 >= 3.33 on targets; profile-read rights; WinRM for remote collection | Temporary snapshot/job files only | -| `Get-ComputerInfo.ps1` | OS, logged-on user and hotfix inventory | CIM/WinRM; target permissions | Temporary CIM session only | -| `Get-RemoteSerialNumber.ps1` | BIOS/serial inventory | CIM/WinRM; target permissions | Temporary CIM session only | -| `Get-WindowsEvents.ps1` | Selected log and time range | Windows Event Log remote access; log-read rights | No | -| `Date_Selector.ps1` | Return selected date or no value on cancel | Interactive Windows desktop; STA | No | +| [Export-ADGroupMembers.ps1](Export-ADGroupMembers.ps1) | Direct/recursive members, including object type | ActiveDirectory; directory read | No | +| [Export-ADGroupMemberCreationDates.ps1](Export-ADGroupMemberCreationDates.ps1) | Creation dates of user members | ActiveDirectory; directory read | No | +| [GrabAD-GroupMembers.ps1](GrabAD-GroupMembers.ps1) | Compatibility entry point for group report | Same as group report | No | +| [Get-ADUserEnabledStatus.ps1](Get-ADUserEnabledStatus.ps1) | Enabled/disabled status from an identity list | ActiveDirectory; directory read | No | +| [Get-ADPasswordNeverExpires.ps1](Get-ADPasswordNeverExpires.ps1) | Non-expiring password configuration | ActiveDirectory; directory read | No | +| [Get-ADExpiredAccounts.ps1](Get-ADExpiredAccounts.ps1) | Enabled expired accounts; optional no-expiration report | ActiveDirectory; directory read | No | +| [Get-ADMissingPhoneNumbers.ps1](Get-ADMissingPhoneNumbers.ps1) | Enabled users missing all phone fields | ActiveDirectory; directory read | No | +| [Get-ADRecentlyCreatedUsers.ps1](Get-ADRecentlyCreatedUsers.ps1) | Recently created users | ActiveDirectory; directory read | No | +| [Get-ADUserCreationAudit.ps1](Get-ADUserCreationAudit.ps1) | Match creator evidence in DC event 4720 by target SID | AD read; DC Security-log read; retained account-management auditing | No | +| [Get-ADUserLoginData.ps1](Get-ADUserLoginData.ps1) | Password/logon metadata | ActiveDirectory; directory read | No | +| [Copy_AD_UserGroups.ps1](Copy_AD_UserGroups.ps1) | Copy reviewed direct memberships | ActiveDirectory; delegated group management | **Yes** | +| [verify-credentials.ps1](verify-credentials.ps1) | Validate one credential against a domain | DirectoryServices; domain connectivity | Authentication attempt; can affect lockout counters | +| [ExportNSG_All_BySubscription.ps1](ExportNSG_All_BySubscription.ps1) | NSG rule audit with subscription identity and plural fields | Az.Accounts, Az.Network; Reader in selected subscriptions | Session context temporarily switched and restored | +| [Export-GraphDevices.ps1](Export-GraphDevices.ps1) | Directory-device report with optional filters | Graph Authentication + Identity.DirectoryManagement; Device.Read.All | No | +| [Get-GraphDeviceCompliance.ps1](Get-GraphDeviceCompliance.ps1) | Directory compliance flags | Same as device report | No | +| [Find-GraphDevice.ps1](Find-GraphDevice.ps1) | Device display-name prefix search | Same as device report | No | +| [Get-GraphWindowsDevices.ps1](Get-GraphWindowsDevices.ps1) | Windows directory devices | Same as device report | No | +| [GraphAPI-GuestUserStatus.ps1](GraphAPI-GuestUserStatus.ps1) | Latest available interactive guest sign-in | Graph Users + Reports; User.Read.All, AuditLog.Read.All; supported role/license | No | +| [Set-GraphDeviceExtensionAttribute.ps1](Set-GraphDeviceExtensionAttribute.ps1) | Set one selected attribute, then read it back | Graph device update/read; see permission notes below | **Yes** | +| [Export-O365MailboxHolds.ps1](Export-O365MailboxHolds.ps1) | Mailbox hold flags and retention-processing pauses | ExchangeOnlineManagement; mailbox-read RBAC | No | +| [Export-O365BlockedSendersAndDomains.ps1](Export-O365BlockedSendersAndDomains.ps1) | Selected anti-spam policy's blocked entries | ExchangeOnlineManagement; policy-read RBAC | No | +| [BlockLegacyAuthentication.ps1](BlockLegacyAuthentication.ps1) | Apply a blocking policy or restore saved assignments | ExchangeOnlineManagement; policy/user-management RBAC | **Yes** | +| [DefenderToolkit.ps1](DefenderToolkit.ps1) | Explicit Defender status, scans and configuration actions | Defender module; elevation for changes | **Yes**, except Status/Preferences/Detections | +| [Get-BrowserHistory.ps1](Get-BrowserHistory.ps1) | Chrome/Edge/Firefox SQLite history with UTC timestamps | Windows; sqlite3 >= 3.33 on targets; profile-read rights; WinRM for remote collection | Temporary snapshot/job files only | +| [Get-ComputerInfo.ps1](Get-ComputerInfo.ps1) | OS, logged-on user and hotfix inventory | CIM/WinRM; target permissions | Temporary CIM session only | +| [Get-RemoteSerialNumber.ps1](Get-RemoteSerialNumber.ps1) | BIOS/serial inventory | CIM/WinRM; target permissions | Temporary CIM session only | +| [Get-WindowsEvents.ps1](Get-WindowsEvents.ps1) | Selected log and time range | Windows Event Log remote access; log-read rights | No | +| [Date_Selector.ps1](Date_Selector.ps1) | Return selected date or no value on cancel | Interactive Windows desktop; STA | No | +| [Get-ADPrivilegedGroupMembers.ps1](Get-ADPrivilegedGroupMembers.ps1) | Privileged-group membership paths with cycle/depth reporting | ActiveDirectory; directory read in selected domain | No | +| [Get-ADStaleAccounts.ps1](Get-ADStaleAccounts.ps1) | User/computer inactivity candidates with explicit evidence | ActiveDirectory; directory read; optional credentials/OU scope | No | +| [Get-EntraAppCredentialExpiry.ps1](Get-EntraAppCredentialExpiry.ps1) | Secret/certificate expiry metadata, without credential values | Graph Applications; Application.Read.All and supported role | No | +| [Get-O365MailboxForwarding.ps1](Get-O365MailboxForwarding.ps1) | Mailbox and hidden inbox-rule forwarding destinations | ExchangeOnlineManagement; mailbox/inbox-rule/recipient/accepted-domain RBAC | No | +| [Get-AzurePublicExposure.ps1](Get-AzurePublicExposure.ps1) | Public-IP inventory and broad management-port NSG candidates | Az.Accounts, Az.Network; Reader in selected subscriptions | Session context temporarily switched and restored | +| [Get-WindowsPersistence.ps1](Get-WindowsPersistence.ps1) | Services, task actions, Run/RunOnce values and Startup files | Windows CIM/ScheduledTasks/registry/filesystem read; WinRM for remote | No | +| [Compare-SecurityReports.ps1](Compare-SecurityReports.ps1) | Added, removed and changed CSV entries using explicit unique keys | Local CSV files; no service modules | No | Azure Firewall commands are now [reference examples](docs/AzureFirewallExamples.md), not an executable sequence of placeholder changes. +### Supporting scripts + +These support the runnable scripts and validation; do not run the test files as administration tools. + +| File | Purpose | +|---|---| +| [Private/Common.ps1](Private/Common.ps1) | Shared CSV export, identity-list and Graph context helpers | +| [tools/Test-Repository.ps1](tools/Test-Repository.ps1) | Parse, analyze and run the complete regression suite | +| [tests/Toolkit.Tests.ps1](tests/Toolkit.Tests.ps1) | Existing administrative safety and reporting regressions | +| [tests/BrowserHistory.Tests.ps1](tests/BrowserHistory.Tests.ps1) | Synthetic SQLite/browser collection tests | +| [tests/SecurityAudits.Tests.ps1](tests/SecurityAudits.Tests.ps1) | New audit reports, report comparisons and catalog coverage | + ## Change safety and recovery Mutating scripts support `-WhatIf` and high-impact confirmation. Preview first. @@ -122,7 +143,23 @@ reported as an error rather than silently treated as "no users" or "no activity" and retention. Do not commit them; common report/database formats are ignored. - No retained sign-in or event record does not prove an account was never used or has no creator. Specify all relevant DCs/collectors for creation audits. -- AD `LastLogonDate` is replicated and approximate. +- AD `LastLogonDate` is replicated and approximate. Stale-account results are + candidates for investigation; absence of a replicated timestamp is not proof + that an account has never been used. +- Privileged-group reports default to `adminCount=1` groups in the selected domain. + Include custom groups explicitly; primary groups, ACL delegation and unresolved + foreign group expansion are outside this report's coverage. +- Application expiry reports cover app registrations, not enterprise application + service-principal credentials. Output contains credential metadata only. +- Forwarding reports describe configuration, including disabled rules. Accepted + domains classify addresses; groups/unresolved targets remain `Unknown`. Delivery + policies, transitive forwarding and group expansion are not evaluated. +- Azure public-exposure findings are potential configured-rule exposure, not proof + that a host is reachable. IP inventory and NSG findings are independent. +- Windows persistence snapshots are evidence, not malware verdicts. Unloaded user + registry hives, WMI subscriptions and shortcut targets are not inspected. +- CSV comparisons require explicit unique, nonblank keys. Values are compared as + case-sensitive strings; use `-CompareProperty` to omit volatile timestamps. - Graph `IsCompliant` is nullable directory metadata, not full Intune compliance. - Mailbox `RetentionHoldEnabled` pauses MRM; it is not a preservation hold. The mailbox report does not resolve organization-wide retention/eDiscovery coverage. diff --git a/docs/SecurityAudits.md b/docs/SecurityAudits.md new file mode 100644 index 0000000..482f593 --- /dev/null +++ b/docs/SecurityAudits.md @@ -0,0 +1,145 @@ +# Security audit reports + +All seven additions are read-only. They return structured objects and accept +`-OutputPath` and `-Force` under the repository's existing CSV handling rules. +Authenticate explicitly before running cloud reports. No script requests new +permissions, installs software, disables accounts or changes service configuration. +Read `Get-Help .\SCRIPT.ps1 -Full` for parameters and limits. + +## Privileged AD group members + +```powershell +.\Get-ADPrivilegedGroupMembers.ps1 -Server dc.example.com -OutputPath .\privileged.csv +.\Get-ADPrivilegedGroupMembers.ps1 -Server dc.example.com -GroupIdentity 'Domain Admins','Custom Helpdesk' -MaxDepth 20 +``` + +Defaults to groups marked `adminCount=1` in the selected domain. That attribute +can include previously protected groups and does not identify all custom privilege +paths. Select additional groups explicitly. Each membership path is preserved; +`Cycle`, `DepthLimit` and `ForeignPrincipalNotExpanded` identify incomplete paths. +Primary-group membership and ACL-based rights are not included. Repeat the query +for relevant domains with a suitable server. Requires directory-read access. +Both friendly-name and distinguished-name paths are included so groups with the +same display name in different OUs remain distinguishable. + +## Stale AD accounts + +```powershell +.\Get-ADStaleAccounts.ps1 -Server dc.example.com -InactiveDays 90 -OutputPath .\stale.csv +.\Get-ADStaleAccounts.ps1 -Server dc.example.com -AccountType Computer -IncludeDisabled -SearchBase 'OU=Servers,DC=example,DC=com' +``` + +Reports enabled users and computers by default. Replicated `LastLogonDate` can lag +activity; the report is not evidence for automatic deletion. Missing logon dates +use creation age and a separate evidence label. Newly created accounts without +logon data are excluded until old enough. Missing both timestamps yields an +`InsufficientTimestamps` row with a null inactivity flag. `PasswordLastSet` provides +an extra signal for review; service accounts may have other activity sources. +`-AsOf` allows a repeatable comparison cutoff. Optional credentials are passed to +all selected AD queries. + +## Entra application credential expiry + +```powershell +Connect-MgGraph -TenantId 'YOUR-TENANT-ID' -Scopes 'Application.Read.All' +.\Get-EntraAppCredentialExpiry.ps1 -TenantId 'YOUR-TENANT-ID' -WithinDays 30 -OutputPath .\expiry.csv +``` + +Requires `Microsoft.Graph.Applications`, `Application.Read.All` and a supported +role for delegated access. Explicitly selects application registration credential +metadata and follows all pages. Statuses are `Expired`, `Expiring`, `MissingExpiry`, +`NotYetValid` and (with `-IncludeAll`) `Valid`. Applications with no credentials +produce no credential rows. Does not output secret text, hints, key bytes, or full +credential objects, and does not inspect service-principal credentials. Credential +IDs, app names and expiration dates still warrant appropriate report access. + +## Microsoft 365 mailbox forwarding + +```powershell +Connect-ExchangeOnline +.\Get-O365MailboxForwarding.ps1 -ExternalOnly -OutputPath .\forwarding.csv +.\Get-O365MailboxForwarding.ps1 -MailboxIdentity alice@example.com +``` + +Requires exactly one connected Exchange Online session with RBAC for mailbox, +inbox-rule, recipient and accepted-domain reads. `Get-InboxRule` does not support +View-Only Organization Management or Entra Global Reader; assign a role that +actually permits these reads rather than assuming that any read role suffices. +Default mailbox scope is user/shared mailboxes; explicit identities can select +others. Includes hidden and disabled rules and reports their configured state. + +Resolves internal mail contacts to external routing addresses. Accepted domains +classify addresses only: they do not establish delivery safety. Distribution +groups and missing/ambiguous recipients are `Unknown`; `-ExternalOnly` retains them +for investigation. Unexpected permission/service failures stop collection. Does +not expand distribution groups, follow chained forwarding, or determine whether +outbound spam policies, transport rules or competing forwarding settings permit +actual delivery. No mailbox rules are modified. + +## Azure public exposure + +```powershell +Connect-AzAccount -Tenant 'YOUR-TENANT-ID' +.\Get-AzurePublicExposure.ps1 -TenantId 'YOUR-TENANT-ID' -SubscriptionId 'YOUR-SUBSCRIPTION-ID' -OutputPath .\exposure.csv +``` + +Requires Az.Accounts/Az.Network and Reader access. `PublicIpInventory` includes +assigned and unassigned public IP resources. `PotentialManagementExposure` flags +inbound allow rules with broad sources (`*`, `Internet`, `0.0.0.0/0`, `::/0`) and +TCP/UDP/wildcard rules matching default management ports 22, 3389, 5985 or 5986. +Customize with `-ManagementPort`. Handles plural ranges and IPv6 any-source rules. +Associated resource IDs and destination ASGs are included when available. + +Public IPs and NSG candidates are separate observations, not a correlation or +reachability test. Deny precedence, effective NIC/subnet rules, guest firewalls, +routes, listeners, JIT and NAT are not evaluated. A candidate can be unattached or +blocked elsewhere; a service can also be exposed through mechanisms this report +does not inventory. Collection temporarily switches the process Azure context and +restores it in `finally`, including failures. No network probes are sent. + +## Windows persistence inventory + +```powershell +.\Get-WindowsPersistence.ps1 -OutputPath .\persistence-before.csv +.\Get-WindowsPersistence.ps1 -ComputerName server.example.com -Credential (Get-Credential) -OutputPath .\persistence-remote.csv +``` + +Requires Windows and read access to CIM services, ScheduledTasks, the registry and +Startup directories; remote runs need WinRM. Enumerates services, every task action, +machine 64/32-bit Run/RunOnce values, equivalent values in loaded user hives, and +common/per-profile Startup files. Captures disabled tasks too. Does not execute +configured command lines, resolve shortcuts, load hives, enable tasks, or modify +services. WMI subscriptions, browser extensions and other persistence mechanisms +are outside scope. Any unreadable selected source produces an error; do not treat +an error as a clean host. Command lines can contain sensitive data. + +## Compare report snapshots + +```powershell +.\Compare-SecurityReports.ps1 -BeforePath .\persistence-before.csv -AfterPath .\persistence-after.csv -Key ComputerName,Id -OutputPath .\changes.csv +.\Compare-SecurityReports.ps1 -BeforePath .\old-devices.csv -AfterPath .\new-devices.csv -Key id -CompareProperty displayName,accountEnabled +``` + +Choose stable keys unique within each report. Composite keys are encoded so values +containing punctuation cannot collide. Duplicate or blank keys cause an error. +Default comparison requires matching schemas and compares every non-key column. +With `-CompareProperty`, explicitly select shared fields to tolerate schema changes +or omit volatile timestamps. Values and keys are case-sensitive CSV strings, not +locale-dependent date/number interpretations; null and empty CSV fields are +indistinguishable. Header-only files support empty snapshots; files without headers +do not. Reports with no findings normally write no CSV under the shared export +rules, so provide a header-only snapshot if you need to compare an empty result. + +`Changed` rows identify individual properties and their previous/current values. +`Added` and `Removed` rows store the entire respective CSV record as JSON. Identical +reports return no rows. Neither input can be overwritten through `-OutputPath`, +even when `-Force` is supplied. File content changes to a Startup shortcut are not +visible in persistence comparisons unless its reported metadata changes. + +## Source references + +- [Graph: list applications and permissions](https://learn.microsoft.com/en-us/graph/api/application-list?view=graph-rest-1.0) +- [Exchange: Get-InboxRule, hidden rules and role limitations](https://learn.microsoft.com/en-us/powershell/module/exchangepowershell/get-inboxrule?view=exchange-ps) +- [Exchange: Get-Recipient](https://learn.microsoft.com/en-us/powershell/module/exchangepowershell/get-recipient?view=exchange-ps) +- [Azure: NSG priority, address, protocol and port semantics](https://learn.microsoft.com/en-us/azure/virtual-network/network-security-groups-overview) +- [Microsoft: replicated logon timestamp limitations](https://devblogs.microsoft.com/scripting/dandelions-vcr-clocks-and-last-logon-times-these-are-a-few-of-our-least-favorite-things/) diff --git a/tests/SecurityAudits.Tests.ps1 b/tests/SecurityAudits.Tests.ps1 new file mode 100644 index 0000000..fe78903 --- /dev/null +++ b/tests/SecurityAudits.Tests.ps1 @@ -0,0 +1,324 @@ +BeforeAll { + $repo = Split-Path $PSScriptRoot -Parent + $asOf = [datetimeoffset]'2026-10-27T12:00:00Z' + $testComputer = 'fixture-host.example.test' + function Get-ADGroup { [CmdletBinding()] param($Identity,$Filter,$Server) throw 'Unmocked AD query' } + function Get-ADGroupMember { [CmdletBinding()] param($Identity,$Server) throw 'Unmocked AD query' } + function Get-ADUser { [CmdletBinding()] param($Filter,$Server,$Properties,$SearchBase,[pscredential]$Credential) throw 'Unmocked AD query' } + function Get-ADComputer { [CmdletBinding()] param($Filter,$Server,$Properties,$SearchBase,[pscredential]$Credential) throw 'Unmocked AD query' } + function Get-MgContext { [CmdletBinding()] param() throw 'Unmocked Graph query' } + function Get-MgApplication { [CmdletBinding()] param([switch]$All,$Property) throw 'Unmocked Graph query' } + function Get-ConnectionInformation { [CmdletBinding()] param() throw 'Unmocked Exchange query' } + function Get-AcceptedDomain { [CmdletBinding()] param() throw 'Unmocked Exchange query' } + function Get-Mailbox { [CmdletBinding()] param($Identity,$ResultSize,$RecipientTypeDetails) throw 'Unmocked Exchange query' } + function Get-InboxRule { [CmdletBinding()] param($Mailbox,[switch]$IncludeHidden,$ResultSize) throw 'Unmocked Exchange query' } + function Get-Recipient { [CmdletBinding()] param($Identity) throw 'Unmocked Exchange query' } + function Get-AzContext { [CmdletBinding()] param() throw 'Unmocked Azure query' } + function Get-AzSubscription { [CmdletBinding()] param($TenantId) throw 'Unmocked Azure query' } + function Set-AzContext { [CmdletBinding()] param($Context,$Tenant,$SubscriptionId,$Scope) throw 'Unmocked Azure context change' } + function Get-AzPublicIpAddress { [CmdletBinding()] param($DefaultProfile) throw 'Unmocked Azure query' } + function Get-AzNetworkSecurityGroup { [CmdletBinding()] param($DefaultProfile) throw 'Unmocked Azure query' } + function Get-ScheduledTask { [CmdletBinding()] param() throw 'Unmocked scheduled-task query' } +} + +Describe 'Privileged AD group paths' { + BeforeEach { + Mock Get-ADGroup { [pscustomobject]@{Name='Root';DistinguishedName='CN=Root';ObjectClass='group'} } + Mock Get-ADGroupMember { + if ($Identity -eq 'CN=Root') { [pscustomobject]@{Name='Nested';DistinguishedName='CN=Nested';ObjectClass='group'} } + else { [pscustomobject]@{Name='Alice';SamAccountName='alice';DistinguishedName='CN=Alice';ObjectClass='user';SID='S-1-5-21-1-1000'} } + } + } + It 'uses the requested server and preserves indirect membership paths' { + $rows = @(& "$repo/Get-ADPrivilegedGroupMembers.ps1" -Server selected.dc) + $rows.Count | Should -Be 2 + ($rows | Where-Object MemberName -eq Alice).MembershipPath | Should -Be 'Root -> Nested -> Alice' + ($rows | Where-Object MemberName -eq Alice).Depth | Should -Be 2 + ($rows | Where-Object MemberName -eq Alice).DistinguishedNamePath | Should -Be 'CN=Root -> CN=Nested -> CN=Alice' + Should -Invoke Get-ADGroup -Times 1 -ParameterFilter { $Server -eq 'selected.dc' -and $Filter -eq 'adminCount -eq 1' } + Should -Invoke Get-ADGroupMember -Times 2 -ParameterFilter { $Server -eq 'selected.dc' } + } + It 'emits a group cycle rather than recursing forever' { + Mock Get-ADGroupMember { + if ($Identity -eq 'CN=Root') { [pscustomobject]@{Name='Nested';DistinguishedName='CN=Nested';ObjectClass='group'} } + else { [pscustomobject]@{Name='Root';DistinguishedName='CN=Root';ObjectClass='group'} } + } + $rows = @(& "$repo/Get-ADPrivilegedGroupMembers.ps1" -Server dc) + ($rows | Where-Object Status -eq Cycle).MembershipPath | Should -Be 'Root -> Nested -> Root' + Should -Invoke Get-ADGroupMember -Times 2 + } + It 'reports a depth limit instead of silently truncating the path' { + $rows = @(& "$repo/Get-ADPrivilegedGroupMembers.ps1" -Server dc -MaxDepth 1) + $rows[0].Status | Should -Be DepthLimit + Should -Invoke Get-ADGroupMember -Times 1 + } + It 'accepts custom group identities without relying on localized group names' { + & "$repo/Get-ADPrivilegedGroupMembers.ps1" -Server dc -GroupIdentity custom-review-group + Should -Invoke Get-ADGroup -Times 1 -ParameterFilter { $Identity -eq 'custom-review-group' } + } + It 'propagates access failures rather than returning a clean empty membership report' { + Mock Get-ADGroupMember { throw 'Access denied' } + { & "$repo/Get-ADPrivilegedGroupMembers.ps1" -Server dc } | Should -Throw '*Access denied*' + } +} + +Describe 'Stale AD accounts' { + BeforeEach { + Mock Get-ADUser { + [pscustomobject]@{Name='Old';Enabled=$true;LastLogonDate=[datetime]'2026-01-01T00:00:00Z';whenCreated=[datetime]'2025-01-01T00:00:00Z'} + [pscustomobject]@{Name='Recent';Enabled=$true;LastLogonDate=[datetime]'2026-10-25T00:00:00Z';whenCreated=[datetime]'2025-01-01T00:00:00Z'} + [pscustomobject]@{Name='NewNoLogon';Enabled=$true;LastLogonDate=$null;whenCreated=[datetime]'2026-10-26T00:00:00Z'} + [pscustomobject]@{Name='OldNoLogon';Enabled=$true;LastLogonDate=$null;whenCreated=[datetime]'2025-01-01T00:00:00Z'} + [pscustomobject]@{Name='Unknown';Enabled=$true;LastLogonDate=$null;whenCreated=$null} + } + Mock Get-ADComputer { [pscustomobject]@{Name='OldComputer';Enabled=$true;LastLogonDate=[datetime]'2026-01-01T00:00:00Z';whenCreated=[datetime]'2025-01-01T00:00:00Z'} } + } + It 'excludes recent accounts and separates missing-logon and missing-timestamp evidence' { + $rows = @(& "$repo/Get-ADStaleAccounts.ps1" -Server dc -AsOf $asOf) + $rows.Count | Should -Be 4 + $rows.Name | Should -Not -Contain Recent + $rows.Name | Should -Not -Contain NewNoLogon + ($rows | Where-Object Name -eq OldNoLogon).Evidence | Should -Be NoReplicatedLogonCreationFallback + ($rows | Where-Object Name -eq Unknown).IsInactivityCandidate | Should -BeNullOrEmpty + Should -Invoke Get-ADComputer -Times 1 + } + It 'honors account type, OU, credentials and explicit disabled-account inclusion' { + $credential = [pscredential]::new('fixture-reader', [Security.SecureString]::new()) + & "$repo/Get-ADStaleAccounts.ps1" -Server selected.dc -AccountType Computer -IncludeDisabled -SearchBase 'OU=Test,DC=example,DC=test' -Credential $credential -AsOf $asOf + Should -Invoke Get-ADUser -Times 0 + Should -Invoke Get-ADComputer -Times 1 -ParameterFilter { $Server -eq 'selected.dc' -and $Filter -eq '*' -and $SearchBase -eq 'OU=Test,DC=example,DC=test' -and $null -ne $Credential } + } +} + +Describe 'Application credential metadata' { + BeforeEach { + Mock Get-MgContext { [pscustomobject]@{TenantId='tenant'} } + Mock Get-MgApplication { + [pscustomobject]@{ + Id='object';AppId='app';DisplayName='Example' + PasswordCredentials=@( + [pscustomobject]@{KeyId='expired';EndDateTime=$asOf.AddDays(-1);SecretText='DO-NOT-EMIT';Hint='DO-NOT-EMIT'}, + [pscustomobject]@{KeyId='soon';EndDateTime=$asOf.AddDays(5)}, + [pscustomobject]@{KeyId='valid';EndDateTime=$asOf.AddDays(100)}, + [pscustomobject]@{KeyId='missing';EndDateTime=$null} + ) + KeyCredentials=@([pscustomobject]@{KeyId='future';StartDateTime=$asOf.AddDays(2);EndDateTime=$asOf.AddDays(100);Key='DO-NOT-EMIT'}) + } + } + } + It 'includes expired, expiring, missing and not-yet-valid metadata, excluding healthy credentials by default' { + $rows = @(& "$repo/Get-EntraAppCredentialExpiry.ps1" -TenantId tenant -AsOf $asOf) + $rows.Count | Should -Be 4 + $rows.Status | Should -Contain Expired + $rows.Status | Should -Contain Expiring + $rows.Status | Should -Contain MissingExpiry + $rows.Status | Should -Contain NotYetValid + Should -Invoke Get-MgApplication -Times 1 -ParameterFilter { $All -and 'passwordCredentials' -in $Property -and 'keyCredentials' -in $Property } + } + It 'never emits secret, hint or certificate-byte properties' { + $rows = @(& "$repo/Get-EntraAppCredentialExpiry.ps1" -TenantId tenant -AsOf $asOf -IncludeAll) + $rows.Count | Should -Be 5 + ($rows | ConvertTo-Json -Depth 5) | Should -Not -Match 'DO-NOT-EMIT|SecretText|Hint' + $rows[0].PSObject.Properties.Name | Should -Not -Contain 'Key' + } + It 'rejects a wrong tenant before listing applications' { + { & "$repo/Get-EntraAppCredentialExpiry.ps1" -TenantId wrong } | Should -Throw '*Connect-MgGraph*' + Should -Invoke Get-MgApplication -Times 0 + } +} + +Describe 'Mailbox forwarding' { + BeforeEach { + Mock Get-ConnectionInformation { [pscustomobject]@{State='Connected'} } + Mock Get-AcceptedDomain { [pscustomobject]@{DomainName='example.test';MatchSubDomains=$false} } + Mock Get-Mailbox { [pscustomobject]@{PrimarySmtpAddress='alice@example.test';ForwardingSmtpAddress='smtp:archive@outside.test';ForwardingAddress=$null;DeliverToMailboxAndForward=$true} } + Mock Get-InboxRule { + [pscustomobject]@{Name='Hidden redirect';Identity='rule1';Enabled=$false;RedirectTo=@('"External" [SMTP:redirect@outside.test]');ForwardTo=@();ForwardAsAttachmentTo=@()} + [pscustomobject]@{Name='Internal';Identity='rule2';Enabled=$true;ForwardTo=@('bob@example.test')} + } + Mock Get-Recipient { [pscustomobject]@{PrimarySmtpAddress='bob@example.test';RecipientType='UserMailbox';ExternalEmailAddress=$null} } + } + It 'includes mailbox forwarding and disabled hidden rules, preserving their enabled state' { + $rows = @(& "$repo/Get-O365MailboxForwarding.ps1") + $rows.Count | Should -Be 3 + ($rows | Where-Object RuleName -eq 'Hidden redirect').RuleEnabled | Should -BeFalse + ($rows | Where-Object RuleName -eq 'Hidden redirect').TargetAddress | Should -Be 'redirect@outside.test' + Should -Invoke Get-InboxRule -Times 1 -ParameterFilter { $IncludeHidden -and $ResultSize -eq 'Unlimited' } + } + It 'filters internal destinations but keeps external ones' { + $rows = @(& "$repo/Get-O365MailboxForwarding.ps1" -ExternalOnly) + $rows.Count | Should -Be 2 + $rows.TargetScope | Should -Not -Contain InternalDomain + } + It 'resolves internal mail contacts to their external routing addresses' { + Mock Get-Recipient { [pscustomobject]@{PrimarySmtpAddress='contact@example.test';RecipientType='MailContact';ExternalEmailAddress='SMTP:contact@outside.test'} } + $rows = @(& "$repo/Get-O365MailboxForwarding.ps1" -ExternalOnly) + $rows.Count | Should -Be 3 + ($rows | Where-Object RuleName -eq Internal).TargetAddress | Should -Be 'contact@outside.test' + } + It 'keeps groups as unresolved review targets rather than calling them safe' { + Mock Get-Recipient { [pscustomobject]@{PrimarySmtpAddress='group@example.test';RecipientType='MailUniversalDistributionGroup'} } + $rows = @(& "$repo/Get-O365MailboxForwarding.ps1" -ExternalOnly) + ($rows | Where-Object RuleName -eq Internal).Resolution | Should -Be GroupNotExpanded + ($rows | Where-Object RuleName -eq Internal).TargetScope | Should -Be Unknown + } + It 'stops on permission failures instead of silently dropping destinations' { + Mock Get-Recipient { throw 'Access denied' } + { & "$repo/Get-O365MailboxForwarding.ps1" } | Should -Throw '*Access denied*' + } +} + +Describe 'Azure exposure candidates' { + BeforeEach { + Mock Get-AzContext { [pscustomobject]@{Tenant=[pscustomobject]@{Id='tenant'};Name='original'} } + Mock Get-AzSubscription { [pscustomobject]@{Id='sub';Name='Subscription'} } + Mock Set-AzContext { [pscustomobject]@{Name='isolated'} } + Mock Get-AzPublicIpAddress { [pscustomobject]@{Id='/public/ip';Name='public';IpAddress='203.0.113.10';IpConfiguration=[pscustomobject]@{Id='/nic/ipconfig'}} } + Mock Get-AzNetworkSecurityGroup { + [pscustomobject]@{ + Id='/nsg';Name='nsg';NetworkInterfaces=@();Subnets=@();DefaultSecurityRules=@() + SecurityRules=@( + [pscustomobject]@{Name='BroadRange';Direction='Inbound';Access='Allow';Protocol='Tcp';Priority=100;SourceAddressPrefixes=@('::/0');DestinationPortRanges=@('3300-3400','5986');DestinationAddressPrefix='*'}, + [pscustomobject]@{Name='PrivateSsh';Direction='Inbound';Access='Allow';Protocol='Tcp';Priority=110;SourceAddressPrefix='10.0.0.0/8';DestinationPortRange='22'}, + [pscustomobject]@{Name='Deny';Direction='Inbound';Access='Deny';Protocol='Tcp';Priority=90;SourceAddressPrefix='*';DestinationPortRange='22'}, + [pscustomobject]@{Name='Web';Direction='Inbound';Access='Allow';Protocol='Tcp';Priority=120;SourceAddressPrefix='Internet';DestinationPortRange='443'} + ) + } + } + } + It 'reports public IP inventory separately from broad IPv6/ranged management-rule candidates' { + $rows = @(& "$repo/Get-AzurePublicExposure.ps1" -TenantId tenant -SubscriptionId sub) + $rows.Count | Should -Be 2 + ($rows | Where-Object FindingType -eq PublicIpInventory).PublicIpAddress | Should -Be '203.0.113.10' + $finding = $rows | Where-Object FindingType -eq PotentialManagementExposure + $finding.MatchedManagementPorts | Should -Be '3389;5986' + $finding.Assessment | Should -Be CandidateRuleNotEffectiveAccess + Should -Invoke Set-AzContext -Times 1 -ParameterFilter { $Context.Name -eq 'original' } + } + It 'handles Internet source tags and wildcard protocols/ports' { + Mock Get-AzNetworkSecurityGroup { [pscustomobject]@{Name='nsg';SecurityRules=@([pscustomobject]@{Name='All';Direction='Inbound';Access='Allow';Protocol='*';SourceAddressPrefix='Internet';DestinationPortRange='*'});DefaultSecurityRules=@()} } + $rows = @(& "$repo/Get-AzurePublicExposure.ps1" -TenantId tenant -SubscriptionId sub) + ($rows | Where-Object FindingType -eq PotentialManagementExposure).MatchedManagementPorts | Should -Be '22;3389;5985;5986' + } + It 'restores context when an Azure query fails' { + Mock Get-AzPublicIpAddress { throw 'Subscription access failed' } + { & "$repo/Get-AzurePublicExposure.ps1" -TenantId tenant -SubscriptionId sub } | Should -Throw '*Subscription access failed*' + Should -Invoke Set-AzContext -Times 1 -ParameterFilter { $Context.Name -eq 'original' } + } + It 'refuses inaccessible subscriptions before changing context' { + { & "$repo/Get-AzurePublicExposure.ps1" -TenantId tenant -SubscriptionId wrong } | Should -Throw '*not accessible*' + Should -Invoke Set-AzContext -Times 0 + } +} + +Describe 'Windows persistence snapshots' { + BeforeEach { + Mock Get-CimInstance { [pscustomobject]@{Name='FixtureSvc';PathName='C:\fixture.exe --service';StartName='SYSTEM';State='Running';StartMode='Auto'} } + Mock Get-ScheduledTask { [pscustomobject]@{TaskName='FixtureTask';TaskPath='\';State='Disabled';Principal=[pscustomobject]@{UserId='SYSTEM'};Actions=@([pscustomobject]@{Execute='C:\task.exe';Arguments='--fixture'})} } + Mock Get-ChildItem { @() } + Mock Test-Path { $false } + Mock Invoke-Command { & $ScriptBlock } + } + It 'collects service command lines and disabled task actions without executing them' { + $rows = @(& "$repo/Get-WindowsPersistence.ps1" -ComputerName localhost) + $rows.Count | Should -Be 2 + ($rows | Where-Object Type -eq Service).Command | Should -Be 'C:\fixture.exe --service' + ($rows | Where-Object Type -eq ScheduledTask).State | Should -Be Disabled + ($rows | Where-Object Type -eq ScheduledTask).Id | Should -Be 'Task:\FixtureTask:1' + Should -Invoke Invoke-Command -Times 0 + } + It 'sends a self-contained collector and credentials to the requested remote host' { + $credential = [pscredential]::new('fixture-reader', [Security.SecureString]::new()) + $rows = @(& "$repo/Get-WindowsPersistence.ps1" -ComputerName $testComputer -Credential $credential) + $rows.Count | Should -Be 2 + Should -Invoke Invoke-Command -Times 1 -ParameterFilter { $ComputerName -eq $testComputer -and $null -ne $Credential -and $ScriptBlock.ToString() -match 'Get-ScheduledTask' } + } + It 'includes loaded-user Run values and Startup files while excluding registry provider metadata' { + $sid = 'S-1-5-21-1-2-3-1000' + $runKey = "Registry::HKEY_USERS\$sid\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" + $startup = 'C:\Users\fixture\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup' + Mock Get-ChildItem { + if ($LiteralPath -eq 'Registry::HKEY_USERS') { [pscustomobject]@{PSChildName=$sid} } + elseif ($LiteralPath -eq (Join-Path $env:SystemDrive Users)) { [pscustomobject]@{FullName='C:\Users\fixture'} } + elseif ($LiteralPath -eq $startup) { [pscustomobject]@{Name='fixture.lnk';FullName="$startup\fixture.lnk"} } + } + Mock Test-Path { $LiteralPath -eq $runKey -or $LiteralPath -eq $startup } + Mock Get-ItemProperty { [pscustomobject]@{PSPath='provider-metadata';FixtureRun='C:\autorun.exe --fixture'} } + $rows = @(& "$repo/Get-WindowsPersistence.ps1" -ComputerName localhost) + ($rows | Where-Object Type -eq RegistryAutorun).User | Should -Be $sid + ($rows | Where-Object Type -eq RegistryAutorun).Command | Should -Be 'C:\autorun.exe --fixture' + $rows.Name | Should -Not -Contain PSPath + ($rows | Where-Object Type -eq StartupFile).Name | Should -Be fixture.lnk + } + It 'fails visibly if scheduled-task collection is denied' { + Mock Get-ScheduledTask { throw 'Scheduled task access denied' } + { & "$repo/Get-WindowsPersistence.ps1" -ComputerName localhost } | Should -Throw '*access denied*' + } +} + +Describe 'CSV security report comparisons' { + BeforeEach { + $beforePath = Join-Path $TestDrive 'before.csv' + $afterPath = Join-Path $TestDrive 'after.csv' + } + It 'reports additions, removals and case-sensitive property changes' { + @([pscustomobject]@{Id='a';Value='Enabled'},[pscustomobject]@{Id='removed';Value='X'}) | Export-Csv $beforePath -NoTypeInformation + @([pscustomobject]@{Id='a';Value='enabled'},[pscustomobject]@{Id='added';Value='Y'}) | Export-Csv $afterPath -NoTypeInformation + $rows = @(& "$repo/Compare-SecurityReports.ps1" -BeforePath $beforePath -AfterPath $afterPath -Key Id) + $rows.Count | Should -Be 3 + $rows.ChangeType | Should -Contain Added + $rows.ChangeType | Should -Contain Removed + ($rows | Where-Object ChangeType -eq Changed).Before | Should -Be 'Enabled' + ($rows | Where-Object ChangeType -eq Changed).After | Should -Be 'enabled' + } + It 'supports header-only input reports' { + '"Id","Value"' | Set-Content $beforePath + [pscustomobject]@{Id='a';Value='new'} | Export-Csv $afterPath -NoTypeInformation + $rows = @(& "$repo/Compare-SecurityReports.ps1" -BeforePath $beforePath -AfterPath $afterPath -Key Id) + $rows.Count | Should -Be 1 + $rows[0].ChangeType | Should -Be Added + } + It 'does not collide composite keys containing delimiter characters' { + @([pscustomobject]@{A='a|b';B='c';Value='1'},[pscustomobject]@{A='a';B='b|c';Value='2'}) | Export-Csv $beforePath -NoTypeInformation + Copy-Item $beforePath $afterPath + @(& "$repo/Compare-SecurityReports.ps1" -BeforePath $beforePath -AfterPath $afterPath -Key A,B).Count | Should -Be 0 + } + It 'rejects duplicate keys rather than overwriting earlier rows' { + @([pscustomobject]@{Id='a';Value='1'},[pscustomobject]@{Id='a';Value='2'}) | Export-Csv $beforePath -NoTypeInformation + Copy-Item $beforePath $afterPath + { & "$repo/Compare-SecurityReports.ps1" -BeforePath $beforePath -AfterPath $afterPath -Key Id } | Should -Throw '*Duplicate key*' + } + It 'rejects blank keys' { + [pscustomobject]@{Id='';Value='1'} | Export-Csv $beforePath -NoTypeInformation + Copy-Item $beforePath $afterPath + { & "$repo/Compare-SecurityReports.ps1" -BeforePath $beforePath -AfterPath $afterPath -Key Id } | Should -Throw '*Blank key*' + } + It 'rejects schema drift unless comparison properties are explicit' { + [pscustomobject]@{Id='a';Value='1'} | Export-Csv $beforePath -NoTypeInformation + [pscustomobject]@{Id='a';Value='1';Extra='x'} | Export-Csv $afterPath -NoTypeInformation + { & "$repo/Compare-SecurityReports.ps1" -BeforePath $beforePath -AfterPath $afterPath -Key Id } | Should -Throw '*schemas differ*' + @(& "$repo/Compare-SecurityReports.ps1" -BeforePath $beforePath -AfterPath $afterPath -Key Id -CompareProperty Value).Count | Should -Be 0 + } + It 'prevents overwriting an input even with Force' { + [pscustomobject]@{Id='a';Value='1'} | Export-Csv $beforePath -NoTypeInformation + Copy-Item $beforePath $afterPath + { & "$repo/Compare-SecurityReports.ps1" -BeforePath $beforePath -AfterPath $afterPath -Key Id -OutputPath $beforePath -Force } | Should -Throw '*cannot overwrite*' + } +} + +Describe 'Complete README catalog' { + It 'links every runnable root script and every new audit script' { + $readme = Get-Content "$repo/README.md" -Raw + foreach ($scriptFile in Get-ChildItem $repo -Filter *.ps1 -File) { + $readme | Should -Match ([regex]::Escape('](' + $scriptFile.Name + ')')) + } + } + It 'keeps the catalog count and supporting-file links current' { + $readme = Get-Content "$repo/README.md" -Raw + $count = @(Get-ChildItem $repo -Filter *.ps1 -File).Count + $readme | Should -Match "All $count runnable scripts" + foreach ($support in @('Private/Common.ps1','tools/Test-Repository.ps1') + @(Get-ChildItem "$repo/tests" -Filter *.ps1 -File | ForEach-Object { 'tests/' + $_.Name })) { + $readme | Should -Match ([regex]::Escape('](' + $support + ')')) + } + } +}