From 4727b282f68c1bfa813ee6ae79b87fbc38096a06 Mon Sep 17 00:00:00 2001 From: Merill Fernando Date: Thu, 5 Nov 2026 07:56:51 +1100 Subject: [PATCH 1/5] feat: add Zero Trust Assessment export facts to affected objects The Zero Trust Assessment exports the tenant's apps, service principals, users, devices, directory roles, agent identities and Intune configuration policies into zt-export. The ZTA pack now reads those Graph JSON pages and adds what they say about each object to the Affected objects page: an app's Tier 0 permissions, consent, credentials and last sign-in; a user's roles, MFA and last sign-in; a device's management state; an agent's sponsors. - Add-MtAffectedObjectFact (exported): records facts about an object while the run collects affected objects; Get-MtAffectedObject merges them onto the record with the same System|Type|Id. Facts never add a record. - The HTML report embeds the facts of objects that have any; the CSV joins them into a Facts column. The Affected objects page shows a risk / to review badge and lists the facts when a row is expanded; search matches fact values. - New object types from result links: AgentIdentity, AgentIdentityBlueprint, AgentIdentityBlueprintPrincipal and Intune ConfigurationPolicy. - The ZT step lives in packs/zero-trust-assessment/helpers and is removed by deleting that folder, the Helpers entry and one call in Get-MtZtaInstance. ZeroTrustAssessment.ObjectFacts turns it off. - Fix the pack test that assumed the ZeroTrustAssessment module is not installed: on a machine that has it, the test ran a real assessment. Co-Authored-By: Claude Opus 5.5 Entire-Checkpoint: 01M6M5KAPW2CHZZHM71YWP4QXK --- .../helpers/Add-MtZtaObjectFact.ps1 | 499 ++++++++++++++++++ .../maester-pack.guide.json | 1 + packs/zero-trust-assessment/maester-pack.json | 1 + .../zero-trust-assessment/tests/Test.ZTA.ps1 | 2 + powershell/Maester.psd1 | 1 + powershell/Maester.psm1 | 1 + .../affected-objects/Get-MtAffectedObject.ps1 | 6 + .../Get-MtAffectedObjectFromMarkdown.ps1 | 5 + .../Get-MtAffectedObjectTypeDefinition.ps1 | 6 + .../report/affected-objects/README.md | 29 +- .../internal/session/Clear-ModuleVariable.ps1 | 1 + powershell/public/report/Get-MtHtmlReport.ps1 | 10 +- .../public/run/Add-MtAffectedObjectFact.ps1 | 121 +++++ powershell/public/run/Invoke-Maester.ps1 | 3 +- .../functions/Get-MtAffectedObject.Tests.ps1 | 107 ++++ .../functions/Get-MtHtmlReport.Tests.ps1 | 16 + .../ZeroTrustAssessmentPack.Tests.ps1 | 109 +++- report/src/lib/affectedObjectTypes.ts | 5 + report/src/pages/AffectedObjectsPage.tsx | 124 ++++- website/docs/packs/zero-trust-assessment.md | 24 + 20 files changed, 1054 insertions(+), 17 deletions(-) create mode 100644 packs/zero-trust-assessment/helpers/Add-MtZtaObjectFact.ps1 create mode 100644 powershell/public/run/Add-MtAffectedObjectFact.ps1 diff --git a/packs/zero-trust-assessment/helpers/Add-MtZtaObjectFact.ps1 b/packs/zero-trust-assessment/helpers/Add-MtZtaObjectFact.ps1 new file mode 100644 index 0000000000..b316c7ce96 --- /dev/null +++ b/packs/zero-trust-assessment/helpers/Add-MtZtaObjectFact.ps1 @@ -0,0 +1,499 @@ +function Add-MtZtaObjectFact { + <# + .SYNOPSIS + Adds facts from the Zero Trust Assessment's tenant export to the objects on Maester's Affected objects page. + + .DESCRIPTION + The assessment exports the tenant's applications, service principals, users, devices, directory roles, agent + identities and Intune configuration policies into zt-export, next to its report, as pages of Graph JSON. This + reads those pages and records what they say about each object with Add-MtAffectedObjectFact: an app's + permissions, credentials and last sign-in, a user's roles, MFA registration and last sign-in, and so on. + The facts appear on the objects that the run lists, whichever check named them. + + It runs in the pack's instance source, after the assessment and before a temporary output folder is deleted. + Nothing is added when the export is not there (a report file copied on its own), when the + ZeroTrustAssessment.ObjectFacts setting is false, or on a Maester version without Add-MtAffectedObjectFact. + A problem reading the export is a warning, never a failed run. + + This is the only code in Maester that reads the export. When the assessment's tests become native Maester + tests, delete this file, the Helpers entry in maester-pack.json and its call in Get-MtZtaInstance. + #> + [CmdletBinding()] + [OutputType([void])] + param( + # The report file, the assessment's output folder, or its zt-export folder. + [Parameter(Mandatory)] [string] $ReportPath, + + # The assessment's report, read by Read-MtZtaReport, for its tenant id and when it ran. + [Parameter(Mandatory)] $Report + ) + + if (-not (Get-Command -Name Add-MtAffectedObjectFact -ErrorAction Ignore)) { return } + if (-not [bool](Get-MtSetting -Name 'ZeroTrustAssessment.ObjectFacts' -Default $true)) { return } + + $folder = if (Test-Path -LiteralPath $ReportPath -PathType Container) { $ReportPath } else { Split-Path -Path $ReportPath -Parent } + $root = $null + if ($folder) { + $root = @($folder, (Join-Path $folder 'zt-export')) | Where-Object { + (Test-Path -LiteralPath (Join-Path $_ 'ServicePrincipal') -PathType Container) -or + (Test-Path -LiteralPath (Join-Path $_ 'User') -PathType Container) + } | Select-Object -First 1 + } + if (-not $root) { + Write-Verbose "No zt-export folder next to $ReportPath, so the Zero Trust Assessment adds no facts to the affected objects." + return + } + + try { + $records = @(ConvertTo-MtZtaObjectFactRecord -ExportPath $root -Report $Report) + if ($records.Count -eq 0) { return } + $asOf = ConvertTo-MtZtaDate $Report.ExecutedAt + $parameters = @{ Source = 'Zero Trust Assessment' } + if ($asOf) { $parameters.AsOf = $asOf } + $records | Add-MtAffectedObjectFact @parameters + Write-Verbose "The Zero Trust Assessment export added facts about $($records.Count) object(s)." + } catch { + Write-Warning "The Zero Trust Assessment export could not be read, so its facts are not on the Affected objects page: $($_.Exception.Message)" + } +} + +function ConvertTo-MtZtaDate { + <# + .SYNOPSIS + Returns a value of the export as a UTC date, or $null. + #> + [CmdletBinding()] + [OutputType([Nullable[datetime]])] + param([Parameter(Position = 0)] $Value) + + if ($null -eq $Value) { return $null } + if ($Value -is [datetime]) { + # ConvertFrom-Json reads ISO dates already; an unspecified kind is UTC, as the export writes it. + if ($Value.Kind -eq [System.DateTimeKind]::Unspecified) { return [datetime]::SpecifyKind($Value, [System.DateTimeKind]::Utc) } + return $Value.ToUniversalTime() + } + if ($Value -is [datetimeoffset]) { return $Value.UtcDateTime } + $parsed = [datetime]::MinValue + $styles = [System.Globalization.DateTimeStyles]::AdjustToUniversal -bor [System.Globalization.DateTimeStyles]::AssumeUniversal + if ([datetime]::TryParse([string]$Value, [cultureinfo]::InvariantCulture, $styles, [ref]$parsed)) { return $parsed } + $null +} + +function Read-MtZtaExportEntity { + <# + .SYNOPSIS + Returns the objects of one entity of the assessment's export, read page by page. + #> + [CmdletBinding()] + [OutputType([object[]])] + param( + [Parameter(Mandatory)] [string] $ExportPath, + [Parameter(Mandatory)] [string] $Name + ) + + $entityPath = Join-Path $ExportPath $Name + if (-not (Test-Path -LiteralPath $entityPath -PathType Container)) { return } + # Pages are -0.json, -1.json...; -model.json describes the table, not the data. + foreach ($file in @(Get-ChildItem -LiteralPath $entityPath -File -Filter "$Name-*.json" | Where-Object { $_.BaseName -match '-\d+$' } | Sort-Object { [int]($_.BaseName -replace '^.*-', '') })) { + $page = Get-Content -LiteralPath $file.FullName -Raw -Encoding utf8 | ConvertFrom-Json -Depth 30 + if ($null -eq $page) { continue } + if ($page.PSObject.Properties['value']) { foreach ($item in @($page.value)) { if ($null -ne $item) { $item } } } + else { $page } + } +} + +function ConvertTo-MtZtaObjectFactRecord { + <# + .SYNOPSIS + Builds one record of facts per object in the assessment's export: System, Type, Id and Fact. + + .DESCRIPTION + Tones follow Add-MtAffectedObjectFact: Risk for a path to tenant takeover or a privileged account without MFA, + Warning for something to review (unused for 90 days, no owner or sponsor, a client secret, an unassigned + policy), Good for a reassuring sign, Info for the rest. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] [string] $ExportPath, + [Parameter(Mandatory)] $Report + ) + + $asOf = ConvertTo-MtZtaDate $Report.ExecutedAt + if (-not $asOf) { $asOf = [datetime]::UtcNow } + $tenantId = [string]$Report.TenantId + $staleDays = 90 + $comparer = [System.StringComparer]::OrdinalIgnoreCase + + # The first-party Microsoft tenants that publish Microsoft's own apps. + $microsoftTenants = [System.Collections.Generic.HashSet[string]]::new([string[]]@( + 'f8cdef31-a31e-4b4a-93e4-5f571e91255a', '72f988bf-86f1-41af-91ab-2d7cd011db47', '33e01921-4d64-4f8c-a055-5bdaffd5e33d' + ), $comparer) + # Graph permissions with a direct or indirect path to Global Administrator: the Tier 0 list that MT.1050 and + # MT.1051 use (https://github.com/emiliensocchi/azure-tiering). + $tierZero = [System.Collections.Generic.HashSet[string]]::new([string[]]@( + 'AdministrativeUnit.ReadWrite.All', 'AppRoleAssignment.ReadWrite.All', 'Application.ReadWrite.All', + 'Application.ReadWrite.OwnedBy', 'DeviceManagementConfiguration.ReadWrite.All', 'DeviceManagementRBAC.ReadWrite.All', + 'Directory.ReadWrite.All', 'Domain.ReadWrite.All', 'EntitlementManagement.ReadWrite.All', 'Group.ReadWrite.All', + 'GroupMember.ReadWrite.All', 'Organization.ReadWrite.All', 'Policy.ReadWrite.AuthenticationMethod', + 'Policy.ReadWrite.ConditionalAccess', 'Policy.ReadWrite.PermissionGrant', 'PrivilegedAccess.ReadWrite.AzureADGroup', + 'PrivilegedAssignmentSchedule.ReadWrite.AzureADGroup', 'PrivilegedEligibilitySchedule.ReadWrite.AzureADGroup', + 'RoleAssignmentSchedule.ReadWrite.Directory', 'RoleEligibilitySchedule.ReadWrite.Directory', + 'RoleManagement.ReadWrite.Directory', 'RoleManagementPolicy.ReadWrite.AzureADGroup', + 'RoleManagementPolicy.ReadWrite.Directory', 'User-PasswordProfile.ReadWrite.All', 'User.DeleteRestore.All', + 'User.EnableDisableAccount.All', 'User.ReadWrite.All', 'UserAuthenticationMethod.ReadWrite.All' + ), $comparer) + $graphAppId = '00000003-0000-0000-c000-000000000000' + + $formatDate = { param([datetime]$Date) $Date.ToString('yyyy-MM-dd', [cultureinfo]::InvariantCulture) } + $daysBefore = { param([datetime]$Date) [int][math]::Floor(($asOf - $Date).TotalDays) } + $describeWhen = { + param([datetime]$Date) + $days = & $daysBefore $Date + if ($days -le 0) { return "$(& $formatDate $Date) (the day of the assessment)" } + if ($days -eq 1) { return "$(& $formatDate $Date) (1 day before the assessment)" } + "$(& $formatDate $Date) ($days days before the assessment)" + } + $join = { + param([string[]]$Items, [int]$Max = 6) + $all = @($Items | Where-Object { $_ }) + if ($all.Count -le $Max) { return $all -join ', ' } + (($all | Select-Object -First $Max) -join ', ') + ", and $($all.Count - $Max) more" + } + $newFact = { param($Name, $Value, $Tone = 'Info') [pscustomobject]@{ Name = $Name; Value = $Value; Tone = $Tone } } + $credentialFacts = { + param($Passwords, $Keys) + foreach ($kind in @(@{ Name = 'Client secrets'; Items = @($Passwords | Where-Object { $_ }) }, @{ Name = 'Certificates'; Items = @($Keys | Where-Object { $_ }) })) { + if ($kind.Items.Count -eq 0) { continue } + $ends = @($kind.Items | ForEach-Object { ConvertTo-MtZtaDate $_.endDateTime }) + $active = @($ends | Where-Object { $_ -and $_ -ge $asOf } | Sort-Object) + $expired = @($ends | Where-Object { $_ -and $_ -lt $asOf }).Count + $parts = [System.Collections.Generic.List[string]]::new() + if ($active.Count -gt 0) { $parts.Add("$($active.Count) active, the next expires on $(& $formatDate $active[0])") } + if ($expired -gt 0) { $parts.Add("$expired expired") } + $tone = if ($kind.Name -eq 'Client secrets' -and $active.Count -gt 0) { 'Warning' } + elseif ($active.Count -gt 0 -and ($active[0] - $asOf).TotalDays -le 30) { 'Warning' } + else { 'Info' } + & $newFact $kind.Name ($parts -join '; ') $tone + } + } + + # --- Directory roles: principal id -> 'Role (how)' --------------------------------------------------------- + $roleDefinitions = [System.Collections.Generic.Dictionary[string, object]]::new($comparer) + foreach ($definition in @(Read-MtZtaExportEntity -ExportPath $ExportPath -Name 'RoleDefinition')) { + $roleDefinitions[[string]$definition.id] = $definition + if ($definition.templateId) { $roleDefinitions[[string]$definition.templateId] = $definition } + } + $rolesByPrincipal = [System.Collections.Generic.Dictionary[string, System.Collections.Generic.List[object]]]::new($comparer) + $addRole = { + param($PrincipalId, $RoleDefinitionId, [string]$How, $Scope) + if (-not $PrincipalId -or -not $RoleDefinitionId) { return } + $definition = $null + $null = $roleDefinitions.TryGetValue([string]$RoleDefinitionId, [ref]$definition) + $name = if ($definition) { [string]$definition.displayName } else { [string]$RoleDefinitionId } + if ($Scope -and [string]$Scope -ne '/') { $How = "$How, scoped" } + $list = $null + if (-not $rolesByPrincipal.TryGetValue([string]$PrincipalId, [ref]$list)) { + $list = [System.Collections.Generic.List[object]]::new() + $rolesByPrincipal[[string]$PrincipalId] = $list + } + $label = "$name ($How)" + if (-not ($list | Where-Object Label -EQ $label)) { + $list.Add([pscustomobject]@{ Label = $label; Privileged = [bool]($definition -and $definition.isPrivileged); Permanent = $How -like 'permanent*' }) + } + } + # With PIM the schedule instances say how a role is held; without it only the assignments are exported. + $activeInstances = @(Read-MtZtaExportEntity -ExportPath $ExportPath -Name 'RoleAssignmentScheduleInstance') + if ($activeInstances.Count -gt 0) { + foreach ($instance in $activeInstances) { + $how = if ([string]$instance.assignmentType -eq 'Activated') { 'activated' } else { 'permanent' } + & $addRole $instance.principalId $instance.roleDefinitionId $how $instance.directoryScopeId + } + foreach ($member in @(Read-MtZtaExportEntity -ExportPath $ExportPath -Name 'RoleAssignmentScheduleInstanceGroup')) { + & $addRole $member.id $member.roleDefinitionId 'permanent, through a group' $null + } + } else { + foreach ($assignment in @(Read-MtZtaExportEntity -ExportPath $ExportPath -Name 'RoleAssignment')) { + & $addRole $assignment.principalId $assignment.roleDefinitionId 'permanent' $assignment.directoryScopeId + } + foreach ($member in @(Read-MtZtaExportEntity -ExportPath $ExportPath -Name 'RoleAssignmentGroup')) { + & $addRole $member.id $member.roleDefinitionId 'permanent, through a group' $null + } + } + foreach ($instance in @(Read-MtZtaExportEntity -ExportPath $ExportPath -Name 'RoleEligibilityScheduleInstance')) { + & $addRole $instance.principalId $instance.roleDefinitionId 'eligible' $instance.directoryScopeId + } + foreach ($member in @(Read-MtZtaExportEntity -ExportPath $ExportPath -Name 'RoleEligibilityScheduleInstanceGroup')) { + & $addRole $member.id $member.roleDefinitionId 'eligible, through a group' $null + } + $roleFact = { + param($PrincipalId) + $roles = $null + if (-not $rolesByPrincipal.TryGetValue([string]$PrincipalId, [ref]$roles)) { return } + $tone = if (@($roles | Where-Object { $_.Privileged -and $_.Permanent }).Count -gt 0) { 'Risk' } else { 'Info' } + & $newFact 'Entra roles' (& $join @($roles | Sort-Object { -not $_.Privileged }, Label | ForEach-Object Label)) $tone + } + + # --- Service principals: names of the resources and permissions they grant ------------------------------- + $servicePrincipals = @(Read-MtZtaExportEntity -ExportPath $ExportPath -Name 'ServicePrincipal') + $resourceName = [System.Collections.Generic.Dictionary[string, string]]::new($comparer) + $appRoleName = [System.Collections.Generic.Dictionary[string, string]]::new($comparer) + $servicePrincipalById = [System.Collections.Generic.Dictionary[string, object]]::new($comparer) + $graphResourceIds = [System.Collections.Generic.HashSet[string]]::new($comparer) + foreach ($sp in $servicePrincipals) { + $resourceName[[string]$sp.id] = [string]$sp.displayName + $servicePrincipalById[[string]$sp.id] = $sp + if ([string]$sp.appId -eq $graphAppId) { $null = $graphResourceIds.Add([string]$sp.id) } + foreach ($role in @($sp.appRoles)) { + if ($role -and $role.id) { $appRoleName["$($sp.id)|$($role.id)"] = [string]$role.value } + } + } + $lastSignIn = [System.Collections.Generic.Dictionary[string, object]]::new($comparer) + $hasSignInActivity = $false + foreach ($activity in @(Read-MtZtaExportEntity -ExportPath $ExportPath -Name 'ServicePrincipalSignIn')) { + $hasSignInActivity = $true + if ($activity.appId) { $lastSignIn[[string]$activity.appId] = ConvertTo-MtZtaDate $activity.lastSignInActivity.lastSignInDateTime } + } + + # Facts about what an app can do, shared by its enterprise application and its app registration. + $appFacts = { + param($Sp) + $isMicrosoft = $Sp.appOwnerOrganizationId -and $microsoftTenants.Contains([string]$Sp.appOwnerOrganizationId) + + $byResource = [ordered]@{} + $risky = [System.Collections.Generic.List[string]]::new() + foreach ($assignment in @($Sp.appRoleAssignments)) { + if (-not $assignment) { continue } + $name = $null + if (-not $appRoleName.TryGetValue("$($assignment.resourceId)|$($assignment.appRoleId)", [ref]$name) -or -not $name) { continue } + $resource = $null + $null = $resourceName.TryGetValue([string]$assignment.resourceId, [ref]$resource) + if (-not $resource) { $resource = 'Another app' } + if (-not $byResource.Contains($resource)) { $byResource[$resource] = [System.Collections.Generic.List[string]]::new() } + if (-not $byResource[$resource].Contains($name)) { $byResource[$resource].Add($name) } + if ($graphResourceIds.Contains([string]$assignment.resourceId) -and $tierZero.Contains($name)) { $risky.Add($name) } + } + if ($byResource.Count -gt 0) { + $text = (@($byResource.Keys | ForEach-Object { "$($_): $(& $join @($byResource[$_]) 8)" }) -join '; ') + if ($risky.Count -gt 0) { + $lead = if ($risky.Count -eq 1) { "$($risky[0]) has a path to Global Administrator" } else { "$(& $join @($risky) 4) have a path to Global Administrator" } + & $newFact 'Application permissions' "$lead. $text" 'Risk' + } else { + & $newFact 'Application permissions' $text + } + } + + # Microsoft's own apps are consented for everyone when the tenant is created, so only other apps are listed. + $tenantWide = @(if (-not $isMicrosoft) { $Sp.oauth2PermissionGrants | Where-Object { $_ -and [string]$_.consentType -eq 'AllPrincipals' } }) + if ($tenantWide.Count -gt 0) { + $scopes = [System.Collections.Generic.List[string]]::new() + $write = $false + foreach ($grant in $tenantWide) { + $resource = $null + $null = $resourceName.TryGetValue([string]$grant.resourceId, [ref]$resource) + $names = @(([string]$grant.scope) -split '\s+' | Where-Object { $_ -and $_ -notin 'openid', 'profile', 'offline_access', 'email' }) + if ($names | Where-Object { $_ -match '\.ReadWrite|\.Send$|FullControl|\.Manage' }) { $write = $true } + if ($names.Count -gt 0) { $scopes.Add("$(if ($resource) { $resource } else { 'Another app' }): $(& $join $names 8)") } + } + if ($scopes.Count -gt 0) { + & $newFact 'Consented for all users' ($scopes -join '; ') $(if ($write) { 'Warning' } else { 'Info' }) + } + } + $userGrants = @($Sp.oauth2PermissionGrants | Where-Object { $_ -and [string]$_.consentType -eq 'Principal' } | ForEach-Object principalId | Select-Object -Unique).Count + if ($userGrants -gt 0) { & $newFact 'Consented by users' $(if ($userGrants -eq 1) { '1 user' } else { "$userGrants users" }) } + + if ($hasSignInActivity -and $Sp.appId) { + $last = $null + $null = $lastSignIn.TryGetValue([string]$Sp.appId, [ref]$last) + if ($last) { + $stale = (& $daysBefore $last) -gt $staleDays + & $newFact 'Last sign-in' (& $describeWhen $last) $(if ($stale -and -not $isMicrosoft) { 'Warning' } else { 'Info' }) + } elseif (-not $isMicrosoft) { + & $newFact 'Last sign-in' 'None recorded' 'Warning' + } + } + } + + $records = [System.Collections.Generic.List[object]]::new() + $add = { + param([string]$System, [string]$Type, $Id, $Facts) + $list = @($Facts | Where-Object { $_ }) + if ($Id -and $list.Count -gt 0) { $records.Add([pscustomobject]@{ System = $System; Type = $Type; Id = [string]$Id; Fact = $list }) } + } + + # --- Enterprise applications (and agent identities, which are service principals) ------------------------- + $appFactsByAppId = [System.Collections.Generic.Dictionary[string, object[]]]::new($comparer) + foreach ($sp in $servicePrincipals) { + $facts = [System.Collections.Generic.List[object]]::new() + $owner = [string]$sp.appOwnerOrganizationId + $publisher = if ([string]$sp.servicePrincipalType -eq 'ManagedIdentity') { 'Managed identity' } + elseif ($owner -and $owner -eq $tenantId) { 'This tenant' } + elseif ($owner -and $microsoftTenants.Contains($owner)) { 'Microsoft' } + elseif ($sp.publisherName) { "Another organization ($($sp.publisherName))" } + elseif ($owner) { 'Another organization' } + if ($publisher) { $facts.Add((& $newFact 'Publisher' $publisher)) } + if ($sp.accountEnabled -eq $false) { $facts.Add((& $newFact 'Sign-in' 'Disabled')) } + $shared = @(& $appFacts $sp) + foreach ($fact in $shared) { $facts.Add($fact) } + if ($sp.appId) { $appFactsByAppId[[string]$sp.appId] = $shared } + $sso = [string]$sp.preferredSingleSignOnMode + if ($sso -and $sso -ne 'notSupported') { $facts.Add((& $newFact 'Single sign-on' $sso.ToUpperInvariant().Replace('PASSWORD', 'Password-based'))) } + foreach ($fact in @(& $credentialFacts $sp.passwordCredentials $sp.keyCredentials)) { $facts.Add($fact) } + $role = & $roleFact $sp.id + if ($role) { $facts.Add($role) } + & $add 'EntraID' 'ServicePrincipal' $sp.id $facts + } + + # --- App registrations: keyed by appId, as their portal link is ------------------------------------------ + $audience = @{ + AzureADMyOrg = 'This organization only' + AzureADMultipleOrgs = 'Any Microsoft Entra organization' + AzureADandPersonalMicrosoftAccount = 'Any Microsoft Entra organization and personal Microsoft accounts' + PersonalMicrosoftAccount = 'Personal Microsoft accounts only' + } + foreach ($app in @(Read-MtZtaExportEntity -ExportPath $ExportPath -Name 'Application')) { + $facts = [System.Collections.Generic.List[object]]::new() + $who = [string]$app.signInAudience + if ($who) { $facts.Add((& $newFact 'Who can sign in' $(if ($audience.ContainsKey($who)) { $audience[$who] } else { $who }))) } + $owners = @($app.owners | Where-Object { $_ }) + $facts.Add((& $newFact 'Owners' $(if ($owners.Count -eq 0) { 'None' } else { [string]$owners.Count }) $(if ($owners.Count -eq 0) { 'Warning' } else { 'Info' }))) + foreach ($fact in @(& $credentialFacts $app.passwordCredentials $app.keyCredentials)) { $facts.Add($fact) } + $shared = $null + if ($app.appId -and $appFactsByAppId.TryGetValue([string]$app.appId, [ref]$shared)) { foreach ($fact in $shared) { $facts.Add($fact) } } + & $add 'EntraID' 'AppRegistration' $app.appId $facts + } + + # --- Users ---------------------------------------------------------------------------------------------- + $registration = [System.Collections.Generic.Dictionary[string, object]]::new($comparer) + foreach ($detail in @(Read-MtZtaExportEntity -ExportPath $ExportPath -Name 'UserRegistrationDetails')) { + if ($detail.id) { $registration[[string]$detail.id] = $detail } + } + foreach ($user in @(Read-MtZtaExportEntity -ExportPath $ExportPath -Name 'User')) { + $facts = [System.Collections.Generic.List[object]]::new() + $account = @( + if ([string]$user.userType -eq 'Guest') { 'Guest' } else { 'Member' } + if ($user.onPremisesSyncEnabled -eq $true) { 'synced from on-premises' } + if ($user.accountEnabled -eq $false) { 'disabled' } + ) -join ', ' + $facts.Add((& $newFact 'Account' $account)) + $role = & $roleFact $user.id + if ($role) { $facts.Add($role) } + + $detail = $null + if ($registration.TryGetValue([string]$user.id, [ref]$detail)) { + $privileged = [bool]$detail.isAdmin -or ($role -and $role.Tone -eq 'Risk') + if ($detail.isMfaRegistered -eq $true) { + $methods = @($detail.methodsRegistered | Where-Object { $_ }) + $facts.Add((& $newFact 'MFA' $(if ($methods.Count -gt 0) { "Registered: $(& $join $methods)" } else { 'Registered' }) 'Good')) + } elseif ($user.accountEnabled -ne $false) { + $facts.Add((& $newFact 'MFA' 'Not registered' $(if ($privileged) { 'Risk' } else { 'Warning' }))) + } + if ($detail.isPasswordlessCapable -eq $true) { $facts.Add((& $newFact 'Passwordless' 'Can sign in without a password' 'Good')) } + } + + $activity = $user.signInActivity + if ($activity) { + $dates = @( + ConvertTo-MtZtaDate $activity.lastSuccessfulSignInDateTime + ConvertTo-MtZtaDate $activity.lastSignInDateTime + ConvertTo-MtZtaDate $activity.lastNonInteractiveSignInDateTime + ) | Where-Object { $_ } | Sort-Object -Descending + if ($dates.Count -gt 0) { + $stale = (& $daysBefore $dates[0]) -gt $staleDays -and $user.accountEnabled -ne $false + $facts.Add((& $newFact 'Last sign-in' (& $describeWhen $dates[0]) $(if ($stale) { 'Warning' } else { 'Info' }))) + } elseif ($user.accountEnabled -ne $false) { + $facts.Add((& $newFact 'Last sign-in' 'None recorded' 'Warning')) + } + } + & $add 'EntraID' 'User' $user.id $facts + # A check that names a user only by UPN ([upn]() links) gets a record keyed by the UPN when the run never read that user. + if ($user.userPrincipalName) { & $add 'EntraID' 'User' $user.userPrincipalName $facts } + } + + # --- Devices -------------------------------------------------------------------------------------------- + $joinType = @{ AzureAd = 'Microsoft Entra joined'; ServerAd = 'Microsoft Entra hybrid joined'; Workplace = 'Microsoft Entra registered' } + foreach ($device in @(Read-MtZtaExportEntity -ExportPath $ExportPath -Name 'Device')) { + $facts = [System.Collections.Generic.List[object]]::new() + $os = (@($device.operatingSystem, $device.operatingSystemVersion) | Where-Object { $_ }) -join ' ' + if ($os) { $facts.Add((& $newFact 'Operating system' $os)) } + $trust = [string]$device.trustType + if ($trust) { $facts.Add((& $newFact 'Join type' $(if ($joinType.ContainsKey($trust)) { $joinType[$trust] } else { $trust }))) } + if ($device.isManaged -eq $true) { + if ($device.isCompliant -eq $true) { $facts.Add((& $newFact 'Management' 'Managed and compliant' 'Good')) } + else { $facts.Add((& $newFact 'Management' 'Managed, not compliant' 'Warning')) } + } elseif ($trust -in 'AzureAd', 'ServerAd') { + $facts.Add((& $newFact 'Management' 'Not managed' 'Warning')) + } + if ($device.accountEnabled -eq $false) { $facts.Add((& $newFact 'Status' 'Disabled')) } + $last = ConvertTo-MtZtaDate $device.approximateLastSignInDateTime + if ($last) { + $stale = (& $daysBefore $last) -gt $staleDays -and $device.accountEnabled -ne $false + $facts.Add((& $newFact 'Last sign-in' (& $describeWhen $last) $(if ($stale) { 'Warning' } else { 'Info' }))) + } + & $add 'EntraID' 'Device' $device.id $facts + } + + # --- Agent identities and their blueprints ----------------------------------------------------------------- + $blueprints = @(Read-MtZtaExportEntity -ExportPath $ExportPath -Name 'AgentIdentityBlueprint') + $blueprintName = [System.Collections.Generic.Dictionary[string, string]]::new($comparer) + foreach ($blueprint in $blueprints) { + if ($blueprint.appId) { $blueprintName[[string]$blueprint.appId] = [string]$blueprint.displayName } + if ($blueprint.id) { $blueprintName[[string]$blueprint.id] = [string]$blueprint.displayName } + } + $agentsPerBlueprint = @{} + foreach ($agent in @(Read-MtZtaExportEntity -ExportPath $ExportPath -Name 'AgentIdentity')) { + $facts = [System.Collections.Generic.List[object]]::new() + $name = $null + if ($agent.agentIdentityBlueprintId) { + $key = [string]$agent.agentIdentityBlueprintId + $agentsPerBlueprint[$key] = 1 + [int]$agentsPerBlueprint[$key] + if ($blueprintName.TryGetValue($key, [ref]$name) -and $name) { $facts.Add((& $newFact 'Blueprint' $name)) } + } + $sponsors = @($agent.sponsors | Where-Object { $_ }).Count + $facts.Add((& $newFact 'Sponsors' $(if ($sponsors -eq 0) { 'None' } else { [string]$sponsors }) $(if ($sponsors -eq 0) { 'Warning' } else { 'Info' }))) + if ($agent.accountEnabled -eq $false) { $facts.Add((& $newFact 'Sign-in' 'Disabled')) } + $sp = $null + if ($servicePrincipalById.TryGetValue([string]$agent.id, [ref]$sp)) { foreach ($fact in @(& $appFacts $sp)) { $facts.Add($fact) } } + $role = & $roleFact $agent.id + if ($role) { $facts.Add($role) } + & $add 'EntraID' 'AgentIdentity' $agent.id $facts + } + foreach ($blueprint in $blueprints) { + $facts = [System.Collections.Generic.List[object]]::new() + $owners = @($blueprint.owners | Where-Object { $_ }).Count + $facts.Add((& $newFact 'Owners' $(if ($owners -eq 0) { 'None' } else { [string]$owners }) $(if ($owners -eq 0) { 'Warning' } else { 'Info' }))) + $sponsors = @($blueprint.sponsors | Where-Object { $_ }).Count + $facts.Add((& $newFact 'Sponsors' $(if ($sponsors -eq 0) { 'None' } else { [string]$sponsors }) $(if ($sponsors -eq 0) { 'Warning' } else { 'Info' }))) + $count = [int]$agentsPerBlueprint[[string]$blueprint.appId] + $facts.Add((& $newFact 'Agent identities' $(if ($count -eq 1) { '1' } else { [string]$count }))) + foreach ($fact in @(& $credentialFacts $blueprint.passwordCredentials $blueprint.keyCredentials)) { $facts.Add($fact) } + & $add 'EntraID' 'AgentIdentityBlueprint' $blueprint.appId $facts + } + + foreach ($principal in @(Read-MtZtaExportEntity -ExportPath $ExportPath -Name 'AgentIdentityBlueprintPrincipal')) { + $facts = [System.Collections.Generic.List[object]]::new() + $name = $null + if ($principal.appId -and $blueprintName.TryGetValue([string]$principal.appId, [ref]$name) -and $name) { $facts.Add((& $newFact 'Blueprint' $name)) } + if ($principal.accountEnabled -eq $false) { $facts.Add((& $newFact 'Sign-in' 'Disabled')) } + $sp = $null + if ($servicePrincipalById.TryGetValue([string]$principal.id, [ref]$sp)) { foreach ($fact in @(& $appFacts $sp)) { $facts.Add($fact) } } + $role = & $roleFact $principal.id + if ($role) { $facts.Add($role) } + & $add 'EntraID' 'AgentIdentityBlueprintPrincipal' $principal.id $facts + } + + # --- Intune configuration policies --------------------------------------------------------------------------- + foreach ($policy in @(Read-MtZtaExportEntity -ExportPath $ExportPath -Name 'ConfigurationPolicy')) { + $facts = [System.Collections.Generic.List[object]]::new() + $assignments = @($policy.assignments | Where-Object { $_ }).Count + $facts.Add((& $newFact 'Assignments' $(if ($assignments -eq 0) { 'Not assigned' } else { [string]$assignments }) $(if ($assignments -eq 0) { 'Warning' } else { 'Info' }))) + $platform = (@($policy.platforms, $(if ($policy.technologies) { "($($policy.technologies -replace ',', ', '))" })) | Where-Object { $_ }) -join ' ' + if ($platform) { $facts.Add((& $newFact 'Platform' $platform)) } + if ($null -ne $policy.settingCount) { $facts.Add((& $newFact 'Settings' ([string]$policy.settingCount))) } + $modified = ConvertTo-MtZtaDate $policy.lastModifiedDateTime + if ($modified) { $facts.Add((& $newFact 'Last changed' (& $describeWhen $modified))) } + & $add 'Intune' 'ConfigurationPolicy' $policy.id $facts + } + + $records.ToArray() +} diff --git a/packs/zero-trust-assessment/maester-pack.guide.json b/packs/zero-trust-assessment/maester-pack.guide.json index e53e19ba05..7b0c79c7db 100644 --- a/packs/zero-trust-assessment/maester-pack.guide.json +++ b/packs/zero-trust-assessment/maester-pack.guide.json @@ -30,6 +30,7 @@ { "Name": "ZeroTrustAssessment.Connect", "Default": "none", "Text": "Further Connect-ZtAssessment parameters, for example { \"Service\": [\"Graph\", \"Azure\"], \"UseDeviceCode\": true }." }, { "Name": "ZeroTrustAssessment.ShowLog", "Default": "true", "Text": "List the tests the assessment runs in its live output." }, { "Name": "ZeroTrustAssessment.EmbedReport", "Default": "true", "Text": "Embed the assessment's own HTML report in the Maester report." }, + { "Name": "ZeroTrustAssessment.ObjectFacts", "Default": "true", "Text": "Add what the assessment's export says about each app, user, device and policy to the Affected objects page." }, { "Name": "ZeroTrustAssessment.OutputPath", "Default": "temporary", "Text": "Where the assessment writes its report and export. Kept when set." }, { "Name": "ZeroTrustAssessment.ReportPath", "Default": "empty", "Text": "Read a report you already have instead of running the assessment." }, { "Name": "ZeroTrustAssessment.DisableTelemetry", "Default": "true", "Text": "The assessment sends the tenant ID to Microsoft unless this is true." } diff --git a/packs/zero-trust-assessment/maester-pack.json b/packs/zero-trust-assessment/maester-pack.json index 59822fa2e8..a933f2f11e 100644 --- a/packs/zero-trust-assessment/maester-pack.json +++ b/packs/zero-trust-assessment/maester-pack.json @@ -15,6 +15,7 @@ "RequiresMaester": ">=3.0", "Code": "ZTA", "Suites": ["tests"], + "Helpers": ["helpers"], "Catalog": "catalog.json", "Uses": { "Services": ["Graph"], diff --git a/packs/zero-trust-assessment/tests/Test.ZTA.ps1 b/packs/zero-trust-assessment/tests/Test.ZTA.ps1 index 3232104946..9bc8cf5262 100644 --- a/packs/zero-trust-assessment/tests/Test.ZTA.ps1 +++ b/packs/zero-trust-assessment/tests/Test.ZTA.ps1 @@ -41,6 +41,8 @@ function Get-MtZtaInstance { } Add-MtZtaReportAttachment -ReportPath $reportPath + # Facts from the assessment's tenant export for the Affected objects page (helpers/Add-MtZtaObjectFact.ps1). + Add-MtZtaObjectFact -ReportPath $reportPath -Report $report ConvertTo-MtZtaInstance -Report $report } finally { # A collection into a temporary folder leaves nothing behind: the export holds raw tenant data. diff --git a/powershell/Maester.psd1 b/powershell/Maester.psd1 index 61b5856f33..bdc0f70835 100644 --- a/powershell/Maester.psd1 +++ b/powershell/Maester.psd1 @@ -57,6 +57,7 @@ # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = @( + 'Add-MtAffectedObjectFact', 'Add-MtMaesterAppFederatedCredential', 'Add-MtReportAttachment', 'Add-MtTestResultDetail', diff --git a/powershell/Maester.psm1 b/powershell/Maester.psm1 index 0bd9625818..bbf77bea80 100644 --- a/powershell/Maester.psm1 +++ b/powershell/Maester.psm1 @@ -36,6 +36,7 @@ $__MtSession = @{ ADCredential = $null # Active Directory credential retained only for the connected session ADCollectionTime = $null # Timestamp of last AD data collection IncludeAffectedObjects = $false # Set by Invoke-Maester -IncludeAffectedObjects; gates per-test object capture + AffectedObjectFacts = $null # Add-MtAffectedObjectFact: System|Type|Id -> facts about an object, merged into the AffectedObjects Console = $null # Get-MtConsoleMode result for the current Invoke-Maester run PackConnections = @{} # Maester Packs: service -> connection state a pack connector set with Set-MtConnectionState ReportAttachments = $null # Add-MtReportAttachment: reports of other tools embedded in the HTML report diff --git a/powershell/internal/report/affected-objects/Get-MtAffectedObject.ps1 b/powershell/internal/report/affected-objects/Get-MtAffectedObject.ps1 index 388b9d9ef3..98712bfc16 100644 --- a/powershell/internal/report/affected-objects/Get-MtAffectedObject.ps1 +++ b/powershell/internal/report/affected-objects/Get-MtAffectedObject.ps1 @@ -117,12 +117,17 @@ function Get-MtAffectedObject { if ($record.DisplayName) { return "name:$($record.DisplayName)" } return '' } + # Facts that Add-MtAffectedObjectFact recorded during the run, keyed System|Type|Id. They describe + # objects the run lists: facts about an object that no source found add no record. + $factsByKey = $__MtSession.AffectedObjectFacts $inventory = $records | Group-Object -Property { "$($_.System)|$($_.Type)|$(& $identityOf $_)" } | ForEach-Object { $best = $_.Group | Sort-Object { $rank = $sourceRank[[string]$_.Source] if ($null -eq $rank) { [int]::MaxValue } else { $rank } } | Select-Object -First 1 $uniqueId = Get-MtAffectedObjectUniqueId -System $best.System -Type $best.Type -Id (& $identityOf $best) + $facts = $null + if ($factsByKey -and $best.Id) { $null = $factsByKey.TryGetValue("$($best.System)|$($best.Type)|$($best.Id)", [ref]$facts) } [PSCustomObject]@{ System = $best.System AnchorKind = $best.AnchorKind @@ -135,6 +140,7 @@ function Get-MtAffectedObject { PortalLink = ($_.Group.PortalLink | Where-Object { $_ } | Select-Object -First 1) Tests = @($_.Group.TestId | Where-Object { $_ } | Select-Object -Unique) Sources = @($_.Group.Source | Select-Object -Unique) + Facts = @($facts | Where-Object { $_ }) } } diff --git a/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromMarkdown.ps1 b/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromMarkdown.ps1 index 488571bb49..b3178f99dc 100644 --- a/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromMarkdown.ps1 +++ b/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromMarkdown.ps1 @@ -41,6 +41,11 @@ function Get-MtAffectedObjectFromMarkdown { @{ System = 'EntraID'; Type = 'User'; Regex = "UserProfileMenuBlade/~/\w+/userId/($guid)" } @{ System = 'EntraID'; Type = 'Group'; Regex = "GroupDetailsMenuBlade/~/\w+/groupId/($guid)" } @{ System = 'EntraID'; Type = 'Device'; Regex = "DeviceDetailsMenuBlade/~/\w+/objectId/($guid)" } + @{ System = 'EntraID'; Type = 'AgentIdentity'; Regex = "AgentIdentity\.MenuView/~/\w+/objectId/($guid)" } + # By appId the link opens the blueprint (an application); by objectId, its service principal. + @{ System = 'EntraID'; Type = 'AgentIdentityBlueprint'; Regex = "AgentBlueprintDetails\.MenuView/~/\w+/appId/($guid)" } + @{ System = 'EntraID'; Type = 'AgentIdentityBlueprintPrincipal'; Regex = "AgentBlueprintDetails\.MenuView/~/\w+/objectId/($guid)" } + @{ System = 'Intune'; Type = 'ConfigurationPolicy'; Regex = "Microsoft_Intune_Workflows/PolicySummaryBlade/policyId/($guid)" } @{ System = 'EntraID'; Type = 'AccessPackageCatalog'; Regex = "Microsoft_Azure_ELMAdmin/CatalogBlade/catalogId/($guid)" } @{ System = 'EntraID'; Type = 'AccessPackage'; Regex = "EntitlementMenuBlade/~/overview/entitlementId/($guid)" } @{ System = 'EntraID'; Type = 'PimAlert'; Regex = "Microsoft_Azure_PIMCommon/AlertDetail/providerId/aadroles/alertId/([^/)\s]+)" } diff --git a/powershell/internal/report/affected-objects/Get-MtAffectedObjectTypeDefinition.ps1 b/powershell/internal/report/affected-objects/Get-MtAffectedObjectTypeDefinition.ps1 index 551ea3e36f..3d21ee002d 100644 --- a/powershell/internal/report/affected-objects/Get-MtAffectedObjectTypeDefinition.ps1 +++ b/powershell/internal/report/affected-objects/Get-MtAffectedObjectTypeDefinition.ps1 @@ -31,6 +31,9 @@ EntraID = @( 'AccessPackage' 'AccessPackageCatalog' + 'AgentIdentity' + 'AgentIdentityBlueprint' + 'AgentIdentityBlueprintPrincipal' 'AppRegistration' 'AuthenticationMethod' 'AuthorizationPolicy' @@ -50,6 +53,9 @@ 'SharingPolicy' 'TransportRule' ) + Intune = @( + 'ConfigurationPolicy' + ) GitHub = @( 'GitHubOrganization' 'GitHubRepository' diff --git a/powershell/internal/report/affected-objects/README.md b/powershell/internal/report/affected-objects/README.md index 5f903d322c..976cf1d62d 100644 --- a/powershell/internal/report/affected-objects/README.md +++ b/powershell/internal/report/affected-objects/README.md @@ -46,6 +46,7 @@ Every source normalizes into the same record shape so results can be merged and | `PortalLink` | Admin-portal deep link when a template exists for the type | | `Tests` | Test ids (`MT.xxxx`, ...) that referenced the object (aggregated) | | `Sources` | Which of the three detection sources found it (aggregated) | +| `Facts` | What a pack or test added about the object with `Add-MtAffectedObjectFact` (see [Facts](#facts)); empty if none | ## Anchor kinds @@ -105,6 +106,10 @@ pattern acts as a type system: | `UserProfileMenuBlade/~/*/userId/{guid}` | User | | `GroupDetailsMenuBlade/~/*/groupId/{guid}` | Group | | `DeviceDetailsMenuBlade/~/*/objectId/{guid}` | Device | +| `AgentIdentity.MenuView/~/*/objectId/{guid}` | AgentIdentity | +| `AgentBlueprintDetails.MenuView/~/*/appId/{guid}` | AgentIdentityBlueprint | +| `AgentBlueprintDetails.MenuView/~/*/objectId/{guid}` | AgentIdentityBlueprintPrincipal | +| `Microsoft_Intune_Workflows/PolicySummaryBlade/policyId/{guid}` | ConfigurationPolicy (Intune) | | `Microsoft_Azure_ELMAdmin/CatalogBlade/catalogId/{guid}` | AccessPackageCatalog | | `EntitlementMenuBlade/~/overview/entitlementId/{guid}` | AccessPackage | | `Microsoft_Azure_PIMCommon/AlertDetail/.../alertId/{id}` | PimAlert | @@ -197,11 +202,11 @@ After the merge, `Select-MtAffectedObjectByType` filters the inventory against t | `ExcludedTypes` | Recognised types that are deliberately not affected objects. Dropped silently. | | Everything else | Systems absent from `KnownTypes` (`MicrosoftGraph`) pass through unchanged — their `Type` is a Graph resource path and cannot be enumerated. | -Currently inventoried: `EntraID` — AccessPackage, AccessPackageCatalog, AppRegistration, -AuthenticationMethod, AuthorizationPolicy, ConditionalAccessPolicy, ConsentPolicy, Device, -DirectoryRole, Domains, Group, ServicePrincipal, User; `DefenderXDR` — Device; -`ExchangeOnline` — SharingPolicy, TransportRule; `GitHub` — GitHubOrganization, -GitHubRepository, GitHubResource. +Currently inventoried: `EntraID` — AccessPackage, AccessPackageCatalog, AgentIdentity, +AgentIdentityBlueprint, AgentIdentityBlueprintPrincipal, AppRegistration, AuthenticationMethod, AuthorizationPolicy, +ConditionalAccessPolicy, ConsentPolicy, Device, DirectoryRole, Domains, Group, ServicePrincipal, User; +`DefenderXDR` — Device; `ExchangeOnline` — SharingPolicy, TransportRule; `Intune` — +ConfigurationPolicy; `GitHub` — GitHubOrganization, GitHubRepository, GitHubResource. Excluded: `EntraID` — `EntraRecommendation`, `PimAlert`. Both describe a condition of the tenant (a recommendation, an alert), not an addressable object, so they are findings that @@ -216,6 +221,20 @@ up as an explicit maintenance item instead of silently reaching the report. Add `IdentityProtection` objects are the users at risk, so they are recorded as `User` (`Instance` with a user profile deep link) rather than as the Identity Protection blade. +## Facts + +`Add-MtAffectedObjectFact` (exported, so packs and custom tests can call it) records facts about an +object while the run collects affected objects: `Name`, `Value`, `Tone` (`Risk`, `Warning`, `Good` or +`Info`), `Source` and `AsOf`. They are kept in `$__MtSession.AffectedObjectFacts`, keyed `System|Type|Id`, +and `Get-MtAffectedObject` copies them onto the record with that key. Facts never add a record: an object +no source found is not listed, however much is known about it. The html report embeds the facts of the +objects that have any; the CSV joins them into one `Facts` column. + +The Zero Trust Assessment pack is the first source (`packs/zero-trust-assessment/helpers/Add-MtZtaObjectFact.ps1`): +it reads the assessment's tenant export. Keys must match the records: an app registration is keyed by its +appId, as its portal link is, and so is an agent identity blueprint; a blueprint principal is keyed by its +service principal's object id. + ## Extending detection - **New portal deep-link pattern** → add a row to the regex table in diff --git a/powershell/internal/session/Clear-ModuleVariable.ps1 b/powershell/internal/session/Clear-ModuleVariable.ps1 index c01ab8e3f0..14c7b1dd9b 100644 --- a/powershell/internal/session/Clear-ModuleVariable.ps1 +++ b/powershell/internal/session/Clear-ModuleVariable.ps1 @@ -24,6 +24,7 @@ function Clear-ModuleVariable { Clear-MtADCache $__MtSession.AIAgentInfo = $null $__MtSession.IncludeAffectedObjects = $false + $__MtSession.AffectedObjectFacts = $null $__MtSession.AzureDevOpsConnectionCache = $null # Invoke-Maester resets the per-run cache but preserves the existing GitHub session. # Disconnect-MtGitHub, including through Disconnect-Maester, owns clearing GitHubConnection and GitHubAuthHeader. diff --git a/powershell/public/report/Get-MtHtmlReport.ps1 b/powershell/public/report/Get-MtHtmlReport.ps1 index 67d2ee200c..f6cb6a85ba 100644 --- a/powershell/public/report/Get-MtHtmlReport.ps1 +++ b/powershell/public/report/Get-MtHtmlReport.ps1 @@ -100,7 +100,7 @@ # objects files keep the full records. if ($null -ne $copy.AffectedObjects) { $copy.AffectedObjects = @($copy.AffectedObjects | ForEach-Object { - [PSCustomObject]@{ + $slim = [ordered]@{ System = $_.System Type = $_.Type Id = $_.Id @@ -109,6 +109,14 @@ Tests = @($_.Tests) Referenced = [bool](@($_.Sources) | Where-Object { $_ -in 'GraphObjects', 'Markdown' }) } + # Only objects that have facts carry the property, so a report without any stays as small as before. + $facts = @(Get-ObjectProperty $_ 'Facts' | Where-Object { $_ }) + if ($facts.Count -gt 0) { + $slim.Facts = @($facts | ForEach-Object { + [PSCustomObject]@{ Name = $_.Name; Value = $_.Value; Tone = $_.Tone; Source = $_.Source; AsOf = $_.AsOf } + }) + } + [PSCustomObject]$slim }) } # The report data lists each attachment without its content, which is written into its own element. diff --git a/powershell/public/run/Add-MtAffectedObjectFact.ps1 b/powershell/public/run/Add-MtAffectedObjectFact.ps1 new file mode 100644 index 0000000000..baaa1cc40d --- /dev/null +++ b/powershell/public/run/Add-MtAffectedObjectFact.ps1 @@ -0,0 +1,121 @@ +function Add-MtAffectedObjectFact { + <# + .SYNOPSIS + Adds facts about an object, such as its last sign-in or its expired secrets, to the Affected objects page. + + .DESCRIPTION + Call this from a test, an instance source or a pack that knows more about an object than the checks that name + it: when the object was last used, which permissions it holds, whether its credentials have expired. The facts + are shown with the object on the Affected objects page of the HTML report and kept in the AffectedObjects of the + results, the JSON output and the objects files. + + Facts only describe an object that the run already lists. They are merged into the record with the same System, + Type and Id when the results are built, so adding facts about an object that no check names adds nothing to the + report. Facts are collected only while Invoke-Maester collects affected objects; otherwise the call does nothing. + + Each fact has a Name, a Value and a Tone: Risk for something to fix, Warning for something to review, Good for a + sign that the object is in order, and Info (the default) for anything else. Adding a fact with the same Name from + the same Source again replaces the earlier one. + + The value is shown as text. Name counts rather than other people where you can: the page shows facts to everyone + who reads the report, and -RedactUserIdentity replaces only the names of users the run knows. + + .EXAMPLE + Add-MtAffectedObjectFact -Type ServicePrincipal -Id $sp.id -Source 'Contoso inventory' -Fact @( + @{ Name = 'Last sign-in'; Value = '2026-06-15 (143 days ago)'; Tone = 'Risk' } + @{ Name = 'Publisher'; Value = 'Third party (Contoso Ltd)' } + ) + + Adds two facts to an enterprise application. + + .EXAMPLE + $records | Add-MtAffectedObjectFact -Source 'Zero Trust Assessment' -AsOf $report.ExecutedAt + + Adds facts to many objects at once. Each record has Type, Id and Fact properties, and optionally System. + + .LINK + https://maester.dev/docs/commands/Add-MtAffectedObjectFact + #> + [CmdletBinding()] + [OutputType([void])] + param( + # The object type, as the Affected objects page records it: User, Group, ServicePrincipal, AppRegistration + # (keyed by its appId), Device, ConditionalAccessPolicy, AgentIdentity, AgentIdentityBlueprint, ConfigurationPolicy... + [Parameter(Mandatory, ValueFromPipelineByPropertyName)] + [ValidateNotNullOrEmpty()] + [string] $Type, + + # The object's id, the same id the record uses (for an app registration, its appId). + [Parameter(Mandatory, ValueFromPipelineByPropertyName)] + [ValidateNotNullOrEmpty()] + [string] $Id, + + # The facts: hashtables or objects with Name, Value and an optional Tone (Risk, Warning, Good or Info). + [Parameter(Mandatory, ValueFromPipelineByPropertyName)] + [AllowEmptyCollection()] + [object[]] $Fact, + + # Where the object lives: EntraID (the default), Intune, ExchangeOnline, GitHub... + [Parameter(ValueFromPipelineByPropertyName)] + [ValidateNotNullOrEmpty()] + [string] $System = 'EntraID', + + # What the facts come from, shown with them, for example 'Zero Trust Assessment'. + [Parameter(Mandatory)] + [ValidateNotNullOrEmpty()] + [string] $Source, + + # When the data behind the facts was read, when that is not now (a report written earlier). + [Parameter()] + [Nullable[datetime]] $AsOf + ) + + begin { + $collecting = [bool]$__MtSession.IncludeAffectedObjects + if (-not $collecting) { + Write-Verbose 'Add-MtAffectedObjectFact: this run does not collect affected objects, so the facts are not kept.' + return + } + if ($null -eq $__MtSession.AffectedObjectFacts) { + $__MtSession.AffectedObjectFacts = [System.Collections.Generic.Dictionary[string, System.Collections.Generic.List[object]]]::new([System.StringComparer]::OrdinalIgnoreCase) + } + $asOfText = if ($null -ne $AsOf) { $AsOf.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ', [cultureinfo]::InvariantCulture) } else { $null } + $tones = @('Risk', 'Warning', 'Good', 'Info') + } + + process { + if (-not $collecting) { return } + + $key = '{0}|{1}|{2}' -f $System, $Type, $Id + $list = $null + if (-not $__MtSession.AffectedObjectFacts.TryGetValue($key, [ref]$list)) { + $list = [System.Collections.Generic.List[object]]::new() + $__MtSession.AffectedObjectFacts[$key] = $list + } + + foreach ($item in @($Fact)) { + if ($null -eq $item) { continue } + $name = [string](Get-ObjectProperty $item 'Name') + $value = Get-ObjectProperty $item 'Value' + if ([string]::IsNullOrWhiteSpace($name) -or $null -eq $value -or [string]::IsNullOrWhiteSpace([string]$value)) { continue } + $tone = [string](Get-ObjectProperty $item 'Tone') + $tone = if ($tone) { $tones | Where-Object { $_ -eq $tone } | Select-Object -First 1 } else { 'Info' } + if (-not $tone) { + Write-Warning "Add-MtAffectedObjectFact: '$name' has the tone '$(Get-ObjectProperty $item 'Tone')', which is not Risk, Warning, Good or Info, so it is shown as Info." + $tone = 'Info' + } + $text = ([string]$value).Trim() + if ($text.Length -gt 300) { $text = $text.Substring(0, 297) + '...' } + + $index = $list.FindIndex({ param($existing) $existing.Name -eq $name -and $existing.Source -eq $Source }) + $record = [PSCustomObject]@{ + Name = $name + Value = $text + Tone = $tone + Source = $Source + AsOf = $asOfText + } + if ($index -ge 0) { $list[$index] = $record } else { $list.Add($record) } + } + } +} diff --git a/powershell/public/run/Invoke-Maester.ps1 b/powershell/public/run/Invoke-Maester.ps1 index 57a491cb52..d66115c165 100644 --- a/powershell/public/run/Invoke-Maester.ps1 +++ b/powershell/public/run/Invoke-Maester.ps1 @@ -1085,7 +1085,8 @@ if (![string]::IsNullOrEmpty($out.OutputAffectedObjectsCsvFile) -and $maesterResults.AffectedObjects) { $output = $maesterResults.AffectedObjects | Select-Object System, AnchorKind, Type, Id, UniqueId, DisplayName, UserPrincipalName, PortalLink, @{ Name = 'Tests'; Expression = { $_.Tests -join '; ' } }, - @{ Name = 'Sources'; Expression = { $_.Sources -join '; ' } } | + @{ Name = 'Sources'; Expression = { $_.Sources -join '; ' } }, + @{ Name = 'Facts'; Expression = { @($_.Facts | Where-Object { $_ } | ForEach-Object { "$($_.Name): $($_.Value)" }) -join '; ' } } | ConvertTo-Csv -NoTypeInformation if ($redactNonHtml) { # Piped so the replacement regex is built once, not once per row. diff --git a/powershell/tests/functions/Get-MtAffectedObject.Tests.ps1 b/powershell/tests/functions/Get-MtAffectedObject.Tests.ps1 index ae5774d14b..a1a862a544 100644 --- a/powershell/tests/functions/Get-MtAffectedObject.Tests.ps1 +++ b/powershell/tests/functions/Get-MtAffectedObject.Tests.ps1 @@ -619,6 +619,113 @@ Describe 'Affected objects' { } } + Context 'Facts' { + BeforeAll { + # One result that links a user, an agent identity, a blueprint, its principal and an Intune policy. + $script:factResults = [PSCustomObject]@{ + Tests = @( + [PSCustomObject]@{ + Id = 'ZTA.1' + ResultDetail = [PSCustomObject]@{ + TestResult = @( + '[Adele](https://entra.microsoft.com/#view/Microsoft_AAD_UsersAndTenants/UserProfileMenuBlade/~/overview/userId/aaaaaaaa-0000-0000-0000-000000000001)' + '[Agent](https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/AgentIdentity.MenuView/~/overview/objectId/aaaaaaaa-0000-0000-0000-000000000002/menuId/overview)' + '[Blueprint](https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/AgentBlueprintDetails.MenuView/~/overview/appId/aaaaaaaa-0000-0000-0000-000000000003)' + '[Blueprint](https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/AgentBlueprintDetails.MenuView/~/overview/objectId/aaaaaaaa-0000-0000-0000-000000000005)' + '[Policy](https://intune.microsoft.com/#view/Microsoft_Intune_Workflows/PolicySummaryBlade/policyId/aaaaaaaa-0000-0000-0000-000000000004/technology/mdm)' + ) -join "`n" + } + } + ) + } + + # Runs the block with the session collecting affected objects and an empty fact store. + function Invoke-WithFactCollection { + param([scriptblock] $ScriptBlock) + InModuleScope Maester -Parameters @{ Block = $ScriptBlock; Results = $script:factResults } { + param($Block, $Results) + $previous = $__MtSession.IncludeAffectedObjects + try { + $__MtSession.IncludeAffectedObjects = $true + $__MtSession.AffectedObjectFacts = $null + # Recreated here so the block runs in module scope, where the internal functions are. + & ([scriptblock]::Create($Block.ToString())) $Results + } finally { + $__MtSession.IncludeAffectedObjects = $previous + $__MtSession.AffectedObjectFacts = $null + } + } + } + } + + It 'Should recognise agent identities, blueprints and Intune configuration policies in result links' { + $inventory = Invoke-WithFactCollection { param($Results) Get-MtAffectedObject -MaesterResults $Results -ExcludeSessionCache } + + ($inventory | Where-Object Type -EQ 'AgentIdentity').Id | Should -Be 'aaaaaaaa-0000-0000-0000-000000000002' + # By appId the link names the blueprint; by objectId, the blueprint's service principal. + ($inventory | Where-Object Type -EQ 'AgentIdentityBlueprint').Id | Should -Be 'aaaaaaaa-0000-0000-0000-000000000003' + ($inventory | Where-Object Type -EQ 'AgentIdentityBlueprintPrincipal').Id | Should -Be 'aaaaaaaa-0000-0000-0000-000000000005' + $policy = $inventory | Where-Object Type -EQ 'ConfigurationPolicy' + $policy.System | Should -Be 'Intune' + $policy.Id | Should -Be 'aaaaaaaa-0000-0000-0000-000000000004' + } + + It 'Should add facts to the object with the same System, Type and Id, and add no object of its own' { + $inventory = Invoke-WithFactCollection { + param($Results) + Add-MtAffectedObjectFact -Type User -Id 'AAAAAAAA-0000-0000-0000-000000000001' -Source 'Test' -AsOf ([datetime]'2026-10-23T12:30:00Z') -Fact @( + @{ Name = 'MFA'; Value = 'Not registered'; Tone = 'Risk' } + @{ Name = 'Account'; Value = 'Member' } + ) + Add-MtAffectedObjectFact -Type User -Id 'bbbbbbbb-0000-0000-0000-000000000009' -Source 'Test' -Fact @{ Name = 'Account'; Value = 'Guest' } + Get-MtAffectedObject -MaesterResults $Results -ExcludeSessionCache + } + + $user = $inventory | Where-Object Type -EQ 'User' + $user.Facts.Name | Should -Be @('MFA', 'Account') + $user.Facts[0].Tone | Should -Be 'Risk' + $user.Facts[1].Tone | Should -Be 'Info' + $user.Facts[0].Source | Should -Be 'Test' + $user.Facts[0].AsOf | Should -Be '2026-10-23T12:30:00Z' + $inventory.Id | Should -Not -Contain 'bbbbbbbb-0000-0000-0000-000000000009' + ($inventory | Where-Object Type -EQ 'ConfigurationPolicy').Facts | Should -BeNullOrEmpty + } + + It 'Should take facts from the pipeline, replace a fact with the same name and source, and treat an unknown tone as Info' { + $inventory = Invoke-WithFactCollection { + param($Results) + @( + [PSCustomObject]@{ System = 'Intune'; Type = 'ConfigurationPolicy'; Id = 'aaaaaaaa-0000-0000-0000-000000000004'; Fact = @(@{ Name = 'Assignments'; Value = 'Not assigned'; Tone = 'Warning' }) } + ) | Add-MtAffectedObjectFact -Source 'Test' + Add-MtAffectedObjectFact -System Intune -Type ConfigurationPolicy -Id 'aaaaaaaa-0000-0000-0000-000000000004' -Source 'Test' -Fact @{ Name = 'Assignments'; Value = '2'; Tone = 'Loud' } -WarningAction SilentlyContinue + Add-MtAffectedObjectFact -System Intune -Type ConfigurationPolicy -Id 'aaaaaaaa-0000-0000-0000-000000000004' -Source 'Other' -Fact @{ Name = 'Assignments'; Value = '3' } + Get-MtAffectedObject -MaesterResults $Results -ExcludeSessionCache + } + + $facts = ($inventory | Where-Object Type -EQ 'ConfigurationPolicy').Facts + $facts.Count | Should -Be 2 + $facts[0].Value | Should -Be '2' + $facts[0].Tone | Should -Be 'Info' + $facts[1].Source | Should -Be 'Other' + } + + It 'Should keep no facts when the run does not collect affected objects' { + $kept = InModuleScope Maester { + $previous = $__MtSession.IncludeAffectedObjects + try { + $__MtSession.IncludeAffectedObjects = $false + $__MtSession.AffectedObjectFacts = $null + Add-MtAffectedObjectFact -Type User -Id 'aaaaaaaa-0000-0000-0000-000000000001' -Source 'Test' -Fact @{ Name = 'Account'; Value = 'Member' } + $__MtSession.AffectedObjectFacts + } finally { + $__MtSession.IncludeAffectedObjects = $previous + } + } + + $kept | Should -BeNullOrEmpty + } + } + Context 'IncludeAffectedObjects gating' { BeforeAll { $script:pesterResults = InModuleScope Maester { diff --git a/powershell/tests/functions/Get-MtHtmlReport.Tests.ps1 b/powershell/tests/functions/Get-MtHtmlReport.Tests.ps1 index 88302bad52..340a68c986 100644 --- a/powershell/tests/functions/Get-MtHtmlReport.Tests.ps1 +++ b/powershell/tests/functions/Get-MtHtmlReport.Tests.ps1 @@ -137,6 +137,22 @@ Describe 'Get-MtHtmlReport' { $html | Should -BeLike '*MT.1033.0*' } + It 'Should embed the facts of an object, and no Facts property for objects without any' { + $html = Get-MtHtmlReport -MaesterResults $singleTenant + $html | Should -Not -BeLike '*"Facts"*' + + $record = $singleTenant.AffectedObjects[0] | Select-Object -Property * + $record | Add-Member -NotePropertyName Facts -NotePropertyValue @( + [PSCustomObject]@{ Name = 'MFA'; Value = 'Not registered'; Tone = 'Risk'; Source = 'Zero Trust Assessment'; AsOf = '2026-10-23T12:30:00Z' } + ) + $withFacts = $singleTenant | Select-Object -Property * -ExcludeProperty AffectedObjects + $withFacts | Add-Member -NotePropertyName AffectedObjects -NotePropertyValue @($record) + $html = Get-MtHtmlReport -MaesterResults $withFacts + + $html | Should -BeLike '*"Facts"*' + $html | Should -BeLike '*Not registered*' + } + It 'Should contain emergency access account config data' { $html = Get-MtHtmlReport -MaesterResults $singleTenant diff --git a/powershell/tests/functions/ZeroTrustAssessmentPack.Tests.ps1 b/powershell/tests/functions/ZeroTrustAssessmentPack.Tests.ps1 index c76a247c61..3de8a4aa00 100644 --- a/powershell/tests/functions/ZeroTrustAssessmentPack.Tests.ps1 +++ b/powershell/tests/functions/ZeroTrustAssessmentPack.Tests.ps1 @@ -168,6 +168,109 @@ Describe 'Zero Trust Assessment pack' { } } + Context 'facts from the export' { + BeforeAll { + . (Join-Path $script:PackRoot 'helpers/Add-MtZtaObjectFact.ps1') + + # A small export in the assessment's layout: zt-export//-.json pages of Graph JSON. + $script:Export = Join-Path $TestDrive 'facts/zt-export' + function Write-ZtaExportPage { + param([string] $Name, [object[]] $Value) + $folder = New-Item -ItemType Directory -Path (Join-Path $script:Export $Name) -Force + @{ value = @($Value) } | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath (Join-Path $folder "$Name-0.json") + # The model file describes the table and must not be read as data. + '{ "value": [ { "id": "model" } ] }' | Set-Content -LiteralPath (Join-Path $folder "$Name-model.json") + } + $tenant = '11111111-1111-1111-1111-111111111111' + $graph = '22222222-0000-0000-0000-000000000001' + Copy-Item -LiteralPath (Join-Path $script:Fixture 'ZeroTrustAssessmentReport.json') -Destination (New-Item -ItemType Directory -Path $script:Export -Force) + Write-ZtaExportPage ServicePrincipal @( + @{ id = $graph; appId = '00000003-0000-0000-c000-000000000000'; displayName = 'Microsoft Graph'; appOwnerOrganizationId = 'f8cdef31-a31e-4b4a-93e4-5f571e91255a' + appRoles = @(@{ id = 'r1'; value = 'Directory.ReadWrite.All' }, @{ id = 'r2'; value = 'User.Read.All' }); appRoleAssignments = @() } + @{ id = 'sp-1'; appId = 'app-1'; displayName = 'Contoso sync'; appOwnerOrganizationId = $tenant; accountEnabled = $true + appRoleAssignments = @(@{ resourceId = $graph; appRoleId = 'r1' }, @{ resourceId = $graph; appRoleId = 'r2' }) + oauth2PermissionGrants = @(@{ consentType = 'AllPrincipals'; resourceId = $graph; scope = 'openid User.ReadWrite.All' }) + passwordCredentials = @(@{ endDateTime = '2027-01-01T00:00:00Z' }, @{ endDateTime = '2025-01-01T00:00:00Z' }) } + ) + Write-ZtaExportPage ServicePrincipalSignIn @(@{ appId = 'app-1'; lastSignInActivity = @{ lastSignInDateTime = '2026-01-01T00:00:00Z' } }) + Write-ZtaExportPage Application @(@{ id = 'obj-1'; appId = 'app-1'; signInAudience = 'AzureADMultipleOrgs'; owners = @() }) + Write-ZtaExportPage RoleDefinition @(@{ id = 'ga'; templateId = 'ga'; displayName = 'Global Administrator'; isPrivileged = $true }) + Write-ZtaExportPage RoleAssignment @(@{ principalId = 'user-1'; roleDefinitionId = 'ga'; directoryScopeId = '/' }) + Write-ZtaExportPage User @(@{ id = 'user-1'; userType = 'Member'; accountEnabled = $true; signInActivity = @{ lastSignInDateTime = '2026-10-20T00:00:00Z' } }) + Write-ZtaExportPage UserRegistrationDetails @(@{ id = 'user-1'; isMfaRegistered = $false; isAdmin = $true }) + Write-ZtaExportPage ConfigurationPolicy @(@{ id = 'pol-1'; platforms = 'windows10'; technologies = 'mdm'; settingCount = 3; assignments = @() }) + + $script:Report = [pscustomobject]@{ TenantId = $tenant; ExecutedAt = '2026-10-23T12:00:00Z' } + $script:Facts = @(ConvertTo-MtZtaObjectFactRecord -ExportPath $script:Export -Report $script:Report) + function Get-ZtaFact { + param([string] $Type, [string] $Id, [string] $Name) + ($script:Facts | Where-Object { $_.Type -eq $Type -and $_.Id -eq $Id }).Fact | Where-Object Name -EQ $Name + } + } + + It 'names an app''s Tier 0 Graph permissions as a risk' { + $fact = Get-ZtaFact ServicePrincipal sp-1 'Application permissions' + $fact.Tone | Should -Be 'Risk' + $fact.Value | Should -Be 'Directory.ReadWrite.All has a path to Global Administrator. Microsoft Graph: Directory.ReadWrite.All, User.Read.All' + } + + It 'lists write permissions consented for all users, without openid' { + $fact = Get-ZtaFact ServicePrincipal sp-1 'Consented for all users' + $fact.Value | Should -Be 'Microsoft Graph: User.ReadWrite.All' + $fact.Tone | Should -Be 'Warning' + } + + It 'counts active and expired client secrets and dates sign-ins from the assessment' { + (Get-ZtaFact ServicePrincipal sp-1 'Client secrets').Value | Should -Be '1 active, the next expires on 2027-01-01; 1 expired' + $signIn = Get-ZtaFact ServicePrincipal sp-1 'Last sign-in' + $signIn.Value | Should -Be '2026-01-01 (295 days before the assessment)' + $signIn.Tone | Should -Be 'Warning' + } + + It 'keys an app registration by its appId and gives it the app''s permissions' { + (Get-ZtaFact AppRegistration app-1 'Owners').Tone | Should -Be 'Warning' + (Get-ZtaFact AppRegistration app-1 'Who can sign in').Value | Should -Be 'Any Microsoft Entra organization' + (Get-ZtaFact AppRegistration app-1 'Application permissions').Tone | Should -Be 'Risk' + } + + It 'names a permanent Global Administrator without MFA as a risk' { + (Get-ZtaFact User user-1 'Entra roles').Value | Should -Be 'Global Administrator (permanent)' + (Get-ZtaFact User user-1 'Entra roles').Tone | Should -Be 'Risk' + (Get-ZtaFact User user-1 'MFA').Tone | Should -Be 'Risk' + (Get-ZtaFact User user-1 'Last sign-in').Tone | Should -Be 'Info' + } + + It 'names an unassigned Intune policy for review' { + $record = $script:Facts | Where-Object Type -EQ 'ConfigurationPolicy' + $record.System | Should -Be 'Intune' + (Get-ZtaFact ConfigurationPolicy pol-1 'Assignments').Value | Should -Be 'Not assigned' + } + + It 'reads no model file as data' { + $script:Facts.Id | Should -Not -Contain 'model' + } + + It 'adds the facts to the run when it collects affected objects, and nothing when ObjectFacts is false' { + $collect = { + param([hashtable] $Setting) + InModuleScope Maester { $__MtSession.IncludeAffectedObjects = $true; $__MtSession.AffectedObjectFacts = $null } + try { + $null = Invoke-ZtaPack -Setting $Setting + InModuleScope Maester { if ($__MtSession.AffectedObjectFacts) { @($__MtSession.AffectedObjectFacts.Keys) } } + } finally { + InModuleScope Maester { $__MtSession.IncludeAffectedObjects = $false; $__MtSession.AffectedObjectFacts = $null } + } + } + $report = Join-Path $script:Export 'ZeroTrustAssessmentReport.json' + + $keys = @(& $collect @{ 'ZeroTrustAssessment.ReportPath' = $report }) + $keys | Should -Contain 'EntraID|User|user-1' + $keys | Should -Contain 'Intune|ConfigurationPolicy|pol-1' + + @(& $collect @{ 'ZeroTrustAssessment.ReportPath' = $report; 'ZeroTrustAssessment.ObjectFacts' = $false }) | Should -BeNullOrEmpty + } + } + Context 'running the assessment' { BeforeAll { # A stand-in for the ZeroTrustAssessment module: it records what it was called with and writes the @@ -314,7 +417,11 @@ function Invoke-ZtAssessment { } It 'skips the family when the module is not installed' { - $env:PSModulePath = $script:OriginalModulePath + # Leave out every module folder that has the assessment, so a copy installed on this machine never + # runs a real assessment against the tenant it last signed in to. + $env:PSModulePath = @($script:OriginalModulePath -split [System.IO.Path]::PathSeparator | Where-Object { + $_ -and -not (Test-Path -LiteralPath (Join-Path $_ 'ZeroTrustAssessment')) + }) -join [System.IO.Path]::PathSeparator try { $rows = Invoke-ZtaPack -Setting @{ 'ZeroTrustAssessment.ReportPath' = '' } } finally { diff --git a/report/src/lib/affectedObjectTypes.ts b/report/src/lib/affectedObjectTypes.ts index de9e3989e3..56182d74f3 100644 --- a/report/src/lib/affectedObjectTypes.ts +++ b/report/src/lib/affectedObjectTypes.ts @@ -14,6 +14,10 @@ const knownTypes: Record = { Group: ["Group", "group"], ServicePrincipal: ["Enterprise application", "enterprise-app"], AppRegistration: ["App registration", "app-registration"], + AgentIdentity: ["Agent identity", "enterprise-app"], + AgentIdentityBlueprint: ["Agent identity blueprint", "app-registration"], + AgentIdentityBlueprintPrincipal: ["Agent blueprint principal", "enterprise-app"], + ConfigurationPolicy: ["Configuration policy", "intune"], DirectoryRole: ["Directory role", "directory-role"], AccessPackage: ["Access package", "identity-governance"], AccessPackageCatalog: ["Access package catalog", "identity-governance"], @@ -24,6 +28,7 @@ const knownTypes: Record = { const systemNames: Record = { EntraID: "Entra ID", ExchangeOnline: "Exchange Online", + Intune: "Intune", MicrosoftGraph: "Microsoft Graph", } diff --git a/report/src/pages/AffectedObjectsPage.tsx b/report/src/pages/AffectedObjectsPage.tsx index d78270ff91..af7f474acf 100644 --- a/report/src/pages/AffectedObjectsPage.tsx +++ b/report/src/pages/AffectedObjectsPage.tsx @@ -8,6 +8,17 @@ import { affectedObjectTypePriority, getAffectedObjectTypeInfo, type AffectedObj import { cn } from "@/lib/utils" +// What a pack or test knows about the object (Add-MtAffectedObjectFact), shown when the row is expanded. +interface AffectedObjectFact { + Name: string + Value: string + Tone?: string | null + Source?: string | null + AsOf?: string | null +} + +type Tone = "Risk" | "Warning" | "Good" | "Info" + // The html report embeds a slim record (Referenced flag); older reports and the json output carry // the full record with its Sources list. interface AffectedObjectRecord { @@ -19,6 +30,7 @@ interface AffectedObjectRecord { Tests?: string[] | null Referenced?: boolean Sources?: string[] | null + Facts?: AffectedObjectFact[] | null } // eslint-disable-next-line @typescript-eslint/no-explicit-any @@ -47,6 +59,9 @@ interface AffectedObject { failed: number failSeverity: number maxSeverity: number + facts: AffectedObjectFact[] + risks: number + warnings: number } const severities = ["Critical", "High", "Medium", "Low", "Info"] as const @@ -76,6 +91,44 @@ const statusBadge: Record = { } const statusMark: Record = { Failed: "✕", Passed: "✓", Other: "•" } +const toneOrder: Tone[] = ["Risk", "Warning", "Good", "Info"] +const toTone = (tone?: string | null): Tone => (toneOrder.includes(tone as Tone) ? (tone as Tone) : "Info") +const toneDot: Record = { + Risk: "bg-red-600", + Warning: "bg-amber-500", + Good: "bg-green-600", + Info: "bg-gray-300 dark:bg-zinc-600", +} +const toneValue: Record = { + Risk: "text-red-700 dark:text-red-300", + Warning: "text-amber-800 dark:text-amber-300", + Good: "text-green-700 dark:text-green-300", + Info: "text-gray-800 dark:text-zinc-200", +} + +// The facts behind a "2 risks" badge, for its tooltip. +function factTitle(o: AffectedObject, tone: Tone) { + return o.facts + .filter((fact) => toTone(fact.Tone) === tone) + .map((fact) => `${fact.Name}: ${fact.Value}`) + .join("\n") +} + +// "Zero Trust Assessment, 23 Oct 2026": where the facts come from and when that data was read. +function factSources(facts: AffectedObjectFact[]) { + const seen = new Map() + for (const fact of facts) { + const source = fact.Source || "Unknown source" + if (!seen.has(source)) seen.set(source, fact.AsOf ?? null) + } + return [...seen.entries()].map(([source, asOf]) => { + const date = asOf ? new Date(asOf) : null + return date && !Number.isNaN(date.getTime()) + ? `${source}, ${date.toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" })}` + : source + }) +} + const referencedSources = ["GraphObjects", "Markdown"] @@ -219,6 +272,12 @@ export default function AffectedObjectsPage() { a.id.localeCompare(b.id) ) const failedChecks = checks.filter((check) => check.status === "Failed") + const facts = (Array.isArray(record.Facts) ? record.Facts : []) + .filter((fact) => fact && fact.Name && fact.Value) + .map((fact, order) => ({ fact, order })) + // Risks first, then warnings, keeping the order the source gave within a tone. + .sort((a, b) => toneOrder.indexOf(toTone(a.fact.Tone)) - toneOrder.indexOf(toTone(b.fact.Tone)) || a.order - b.order) + .map(({ fact }) => fact) return { key: `${record.System}|${record.Type}|${record.Id ?? ""}|${index}`, record, @@ -233,6 +292,9 @@ export default function AffectedObjectsPage() { failed: failedChecks.length, failSeverity: Math.max(0, ...failedChecks.map((check) => severityRank(check.severity))), maxSeverity: Math.max(0, ...checks.map((check) => severityRank(check.severity))), + facts, + risks: facts.filter((fact) => toTone(fact.Tone) === "Risk").length, + warnings: facts.filter((fact) => toTone(fact.Tone) === "Warning").length, } }), [records, checksById] @@ -320,7 +382,14 @@ export default function AffectedObjectsPage() { if (activeType !== null && groupKey(o) !== activeType) return false if ( term && - ![o.info.name, o.label, o.record.Id, o.record.Type, ...o.checks.flatMap((c) => [c.id, c.title])] + ![ + o.info.name, + o.label, + o.record.Id, + o.record.Type, + ...o.checks.flatMap((c) => [c.id, c.title]), + ...o.facts.flatMap((f) => [f.Name, f.Value]), + ] .filter(Boolean) .some((value) => String(value).toLowerCase().includes(term)) ) @@ -369,7 +438,9 @@ export default function AffectedObjectsPage() { setSort(null) } - const rowKeys = isReferencedTab ? rows.map((o) => o.key) : [] + // Referenced objects open to their checks; any object opens to its facts. + const canOpen = (o: AffectedObject) => isReferencedTab || o.facts.length > 0 + const rowKeys = rows.filter(canOpen).map((o) => o.key) const allOpen = rowKeys.length > 0 && rowKeys.every((key) => open.has(key)) const hasFilters = activeType !== null || severityFilter.size > 0 || resultFilter !== "All" || search !== "" || sort !== null const columnCount = isReferencedTab ? 5 : 4 @@ -406,23 +477,24 @@ export default function AffectedObjectsPage() { const renderRow = (o: AffectedObject) => { const isOpen = open.has(o.key) - const checks = visibleChecks(o) + const expandable = canOpen(o) + const checks = isReferencedTab ? visibleChecks(o) : [] const top = severities.find((s) => severityRank(s) === (o.failSeverity || o.maxSeverity)) return [ { - if (!isReferencedTab || (event.target as HTMLElement).closest("a")) return + if (!expandable || (event.target as HTMLElement).closest("a")) return setOpen(toggleIn(open, o.key)) }} - aria-expanded={isReferencedTab ? isOpen : undefined} + aria-expanded={expandable ? isOpen : undefined} > - {isReferencedTab && ( + {expandable && ( )} @@ -455,6 +527,20 @@ export default function AffectedObjectsPage() { {o.record.DisplayName && o.record.Id ? o.record.Id : o.record.Type} ) : null} + {o.risks + o.warnings > 0 && ( +
+ {o.risks > 0 && ( + + {o.risks === 1 ? "1 risk" : `${o.risks} risks`} + + )} + {o.warnings > 0 && ( + + {o.warnings} to review + + )} +
+ )} {isReferencedTab ? ( <> @@ -475,15 +561,35 @@ export default function AffectedObjectsPage() { Run-level read )} , - isReferencedTab && isOpen ? ( + expandable && isOpen ? ( c.id.length))) * 0.46}rem` } as CSSProperties} + style={{ "--id-col": `${Math.min(26, Math.max(0, ...checks.map((c) => c.id.length))) * 0.46}rem` } as CSSProperties} > + {o.facts.length > 0 && ( +
0 && "border-b border-gray-200 dark:border-zinc-800")}> +
+ {o.facts.map((fact, index) => { + const tone = toTone(fact.Tone) + return ( +
+
+ + {fact.Name} + {tone !== "Info" && ({tone})} +
+
{fact.Value}
+
+ ) + })} +
+

From {factSources(o.facts).join("; ")}

+
+ )} {checks.map((c) => (