Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 103 additions & 0 deletions Compare-SecurityReports.ps1
Original file line number Diff line number Diff line change
@@ -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
69 changes: 69 additions & 0 deletions Get-ADPrivilegedGroupMembers.ps1
Original file line number Diff line number Diff line change
@@ -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
66 changes: 66 additions & 0 deletions Get-ADStaleAccounts.ps1
Original file line number Diff line number Diff line change
@@ -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
74 changes: 74 additions & 0 deletions Get-AzurePublicExposure.ps1
Original file line number Diff line number Diff line change
@@ -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
Loading