diff --git a/powershell/public/connect/Get-MtGraphScope.ps1 b/powershell/public/connect/Get-MtGraphScope.ps1 index 5d2f7fc8c1..807a3c275b 100644 --- a/powershell/public/connect/Get-MtGraphScope.ps1 +++ b/powershell/public/connect/Get-MtGraphScope.ps1 @@ -99,6 +99,7 @@ 'AgentIdentityBlueprint.Read.All' 'AgentIdentityBlueprintPrincipal.Read.All' 'Application.Read.All' + 'IdentityRiskyServicePrincipal.Read.All' 'IdentityRiskyUser.Read.All' ) diff --git a/powershell/tests/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index ae970e7cfd..0d9454d379 100644 --- a/powershell/tests/fixtures/golden/selection.json +++ b/powershell/tests/fixtures/golden/selection.json @@ -1951,7 +1951,7 @@ "AD" ] }, - "SelectedCount": 609, + "SelectedCount": 610, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -2499,6 +2499,7 @@ "MT.1252", "MT.1259", "MT.1260", + "MT.1262", "MT.1265", "ORCA.100", "ORCA.101", @@ -2581,7 +2582,7 @@ "AD" ] }, - "SelectedCount": 639, + "SelectedCount": 640, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -3161,6 +3162,7 @@ "MT.1252", "MT.1259", "MT.1260", + "MT.1262", "MT.1265", "ORCA.100", "ORCA.101", @@ -4006,7 +4008,7 @@ "AD" ] }, - "SelectedCount": 595, + "SelectedCount": 596, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -4542,6 +4544,7 @@ "MT.1252", "MT.1259", "MT.1260", + "MT.1262", "MT.1265", "ORCA.100", "ORCA.101", diff --git a/powershell/tests/functions/Get-MtGraphScope.Tests.ps1 b/powershell/tests/functions/Get-MtGraphScope.Tests.ps1 index e974fbe6ed..8c6b77c94a 100644 --- a/powershell/tests/functions/Get-MtGraphScope.Tests.ps1 +++ b/powershell/tests/functions/Get-MtGraphScope.Tests.ps1 @@ -30,6 +30,7 @@ $scopes | Should -Not -Contain 'AgentIdentityBlueprint.Read.All' $scopes | Should -Not -Contain 'AgentIdentityBlueprintPrincipal.Read.All' $scopes | Should -Not -Contain 'Application.Read.All' + $scopes | Should -Not -Contain 'IdentityRiskyServicePrincipal.Read.All' $scopes | Should -Not -Contain 'IdentityRiskyUser.Read.All' $scopes | Should -Contain 'Directory.Read.All' $scopes | Should -Not -Contain 'User.ReadBasic.All' @@ -42,6 +43,7 @@ $scopes | Should -Contain 'AgentIdentityBlueprint.Read.All' $scopes | Should -Contain 'AgentIdentityBlueprintPrincipal.Read.All' $scopes | Should -Contain 'Application.Read.All' + $scopes | Should -Contain 'IdentityRiskyServicePrincipal.Read.All' $scopes | Should -Contain 'IdentityRiskyUser.Read.All' $scopes | Should -Contain 'AuditLog.Read.All' diff --git a/powershell/tests/functions/Test-MtEntraUnremediatedHighRiskServicePrincipal.Tests.ps1 b/powershell/tests/functions/Test-MtEntraUnremediatedHighRiskServicePrincipal.Tests.ps1 new file mode 100644 index 0000000000..57ffd274eb --- /dev/null +++ b/powershell/tests/functions/Test-MtEntraUnremediatedHighRiskServicePrincipal.Tests.ps1 @@ -0,0 +1,302 @@ +Describe 'Entra ID Protection unremediated high-risk service principals (MT.1262)' { + BeforeAll { + Import-Module $PSScriptRoot/../../Maester.psd1 -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + # The native-test function is not exported; reach it the same way the agent tests do. + Use-MtModuleFunction -Name Test-MtEntraUnremediatedHighRiskServicePrincipal + } + + BeforeEach { + $script:TestResult = $null + $script:SkippedBecause = $null + $script:SkippedError = $null + $script:Severity = $null + $script:GraphObjects = $null + $script:GraphObjectType = $null + + Mock -ModuleName Maester Test-MtConnection { return $true } + Mock -ModuleName Maester Get-MtLinkServicePrincipal { return "[$($ServicePrincipal.DisplayName)](link)" } + Mock -ModuleName Maester Add-MtTestResultDetail { + param($Result, $SkippedBecause, $SkippedError, $Severity, $GraphObjects, $GraphObjectType) + + $script:TestResult = $Result + $script:SkippedBecause = $SkippedBecause + $script:SkippedError = $SkippedError + $script:Severity = $Severity + $script:GraphObjects = $GraphObjects + $script:GraphObjectType = $GraphObjectType + } + + # Role lookups default to "no roles". Tests that need roles override these. + Mock -ModuleName Maester Invoke-MtGraphRequest { return @() } -ParameterFilter { + $RelativeUri -eq 'roleManagement/directory/roleDefinitions' + } + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { + return [pscustomobject]@{ Assignments = @(); EligibleChecked = $true } + } + } + + AfterEach { + # Result text must not contain backtick-wrapped code spans (repo result-text lint). + if ($null -ne $script:TestResult) { + $script:TestResult | Should -Not -Match '`[^`]+`' + } + } + + It 'passes when there are no high-risk service principals' { + Mock -ModuleName Maester Invoke-MtGraphRequest { return @() } + + Test-MtEntraUnremediatedHighRiskServicePrincipal | Should -BeTrue + $script:TestResult | Should -Match 'Well done' + # The high-risk filter is what separates this check from MT.1263. + Should -Invoke Invoke-MtGraphRequest -ModuleName Maester -Exactly -Times 1 -ParameterFilter { + $ApiVersion -eq 'v1.0' -and + $RelativeUri -eq 'identityProtection/riskyServicePrincipals' -and + $Filter -eq "riskLevel eq 'high'" + } + # A clean tenant makes no role lookups. + Should -Invoke Get-MtDirectoryRoleAssignment -ModuleName Maester -Exactly -Times 0 + } + + It 'fails when a high-risk service principal is atRisk' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'sp-1'; appId = 'app-1'; displayName = 'Contoso Sync'; servicePrincipalType = 'Application' + riskLevel = 'high'; riskState = 'atRisk'; riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-01T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedHighRiskServicePrincipal | Should -BeFalse + $script:TestResult | Should -Match 'Contoso Sync' + $script:TestResult | Should -Match 'app-1' + $script:TestResult | Should -Match 'atRisk' + } + + It 'fails when a high-risk service principal is confirmedCompromised (must not be treated as remediated)' { + # confirmCompromised lands a service principal in confirmedCompromised, which is still unremediated. + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'sp-2'; appId = 'app-2'; displayName = 'Fabrikam Backup'; servicePrincipalType = 'Application' + riskLevel = 'high'; riskState = 'confirmedCompromised'; riskDetail = 'adminConfirmedServicePrincipalCompromised' + riskLastUpdatedDateTime = '2026-10-02T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedHighRiskServicePrincipal | Should -BeFalse + $script:TestResult | Should -Match 'Fabrikam Backup' + $script:TestResult | Should -Match 'confirmedCompromised' + } + + It 'still reports a disabled high-risk service principal (disabling does not close the risk)' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'sp-9'; appId = 'app-9'; displayName = 'Disabled App'; servicePrincipalType = 'Application' + riskLevel = 'high'; riskState = 'atRisk'; riskDetail = 'none'; isEnabled = $false + riskLastUpdatedDateTime = '2026-10-01T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedHighRiskServicePrincipal | Should -BeFalse + $script:TestResult | Should -Match 'Disabled App' + @($script:GraphObjects.id) | Should -Be @('sp-9') + } + + It 'passes when the only high-risk service principals are already remediated or dismissed' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'sp-3'; appId = 'app-3'; displayName = 'Old Reporting'; servicePrincipalType = 'Application' + riskLevel = 'high'; riskState = 'remediated'; riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-03T00:00:00Z' + }, + [pscustomobject]@{ + id = 'sp-4'; appId = 'app-4'; displayName = 'Legacy Connector'; servicePrincipalType = 'Application' + riskLevel = 'high'; riskState = 'dismissed'; riskDetail = 'adminDismissedAllRiskForServicePrincipal' + riskLastUpdatedDateTime = '2026-10-04T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedHighRiskServicePrincipal | Should -BeTrue + $script:TestResult | Should -Match 'Well done' + } + + It 'reports only the unremediated service principals in a mixed set' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'sp-1'; appId = 'app-1'; displayName = 'Contoso Sync'; servicePrincipalType = 'Application' + riskLevel = 'high'; riskState = 'atRisk'; riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-01T00:00:00Z' + }, + [pscustomobject]@{ + id = 'sp-3'; appId = 'app-3'; displayName = 'Old Reporting'; servicePrincipalType = 'Application' + riskLevel = 'high'; riskState = 'remediated'; riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-03T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedHighRiskServicePrincipal | Should -BeFalse + $script:TestResult | Should -Match 'Contoso Sync' + $script:TestResult | Should -Not -Match 'Old Reporting' + $script:TestResult | Should -Match 'Found 1 high-risk' + } + + It 'shows (unnamed) for a service principal with no display name' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'sp-5'; appId = 'app-5'; displayName = ''; servicePrincipalType = 'Application' + riskLevel = 'high'; riskState = 'atRisk'; riskDetail = 'none' + riskLastUpdatedDateTime = $null + } + ) + } + + Test-MtEntraUnremediatedHighRiskServicePrincipal | Should -BeFalse + $script:TestResult | Should -Match '\(unnamed\)' + $script:TestResult | Should -Match 'Unknown' + } + + It 'passes the unremediated service principals to the report as affected objects' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'sp-1'; appId = 'app-1'; displayName = 'Alpha App'; servicePrincipalType = 'Application' + riskLevel = 'high'; riskState = 'atRisk'; riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-01T00:00:00Z' + }, + [pscustomobject]@{ + id = 'sp-2'; appId = 'app-2'; displayName = 'Bravo App'; servicePrincipalType = 'Application' + riskLevel = 'high'; riskState = 'confirmedCompromised'; riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-02T00:00:00Z' + } + ) + } -ParameterFilter { $RelativeUri -eq 'identityProtection/riskyServicePrincipals' } + + Test-MtEntraUnremediatedHighRiskServicePrincipal | Should -BeFalse + $script:GraphObjectType | Should -BeNullOrEmpty + @($script:GraphObjects).Count | Should -Be 2 + @($script:GraphObjects.id) | Should -Be @('sp-1', 'sp-2') + @($script:GraphObjects.displayName) | Should -Be @('Alpha App', 'Bravo App') + @($script:GraphObjects | ForEach-Object { $_.'@odata.type' }) | Should -Be @('#microsoft.graph.servicePrincipal', '#microsoft.graph.servicePrincipal') + } + + It 'passes no affected objects when no service principal is left unremediated' { + Mock -ModuleName Maester Invoke-MtGraphRequest { return @() } -ParameterFilter { $RelativeUri -eq 'identityProtection/riskyServicePrincipals' } + + Test-MtEntraUnremediatedHighRiskServicePrincipal | Should -BeTrue + $script:GraphObjects | Should -BeNullOrEmpty + } + + It 'skips as NotAuthorized on a 403 from Graph' { + Mock -ModuleName Maester Invoke-MtGraphRequest { throw '403 Forbidden: Authorization_RequestDenied' } + + Test-MtEntraUnremediatedHighRiskServicePrincipal | Should -BeNullOrEmpty + $script:SkippedBecause | Should -Be 'NotAuthorized' + } + + It 'lets an unexpected failure throw so the engine records it as Error' { + Mock -ModuleName Maester Invoke-MtGraphRequest { throw 'Service unavailable' } + + { Test-MtEntraUnremediatedHighRiskServicePrincipal } | Should -Throw '*Service unavailable*' + } + + Context 'Privileged service principals at risk' { + BeforeEach { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ id = 'role-ga'; displayName = 'Global Administrator' }, + [pscustomobject]@{ id = 'role-dr'; displayName = 'Directory Readers' } + ) + } -ParameterFilter { $RelativeUri -eq 'roleManagement/directory/roleDefinitions' } + + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'sp-1'; appId = 'app-1'; displayName = 'Contoso Sync'; servicePrincipalType = 'Application' + riskLevel = 'high'; riskState = 'atRisk'; riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-01T00:00:00Z' + }, + [pscustomobject]@{ + id = 'sp-2'; appId = 'app-2'; displayName = 'Fabrikam Backup'; servicePrincipalType = 'Application' + riskLevel = 'high'; riskState = 'atRisk'; riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-02T00:00:00Z' + } + ) + } -ParameterFilter { $RelativeUri -eq 'identityProtection/riskyServicePrincipals' } + + Mock -ModuleName Maester Get-MtRoleInfo { + return [pscustomobject]@{ IsPrivileged = ($RoleName -eq 'GlobalAdministrator') } + } + } + + It 'lists the role first when an at-risk service principal holds a privileged role' { + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { + return [pscustomobject]@{ + Assignments = @([pscustomobject]@{ principalId = 'sp-2'; roleDefinitionId = 'role-ga'; AssignmentType = 'Active' }) + EligibleChecked = $true + } + } + + Test-MtEntraUnremediatedHighRiskServicePrincipal | Should -BeFalse + $script:Severity | Should -BeNullOrEmpty + $script:TestResult | Should -Match 'Global Administrator' + $script:TestResult | Should -Match '1 of them hold a privileged directory role' + # The privileged service principal is listed first. + $script:TestResult.IndexOf('Fabrikam Backup') | Should -BeLessThan $script:TestResult.IndexOf('Contoso Sync') + } + + It 'treats a PIM-eligible privileged role as privileged' { + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { + return [pscustomobject]@{ + Assignments = @([pscustomobject]@{ principalId = 'sp-1'; roleDefinitionId = 'role-ga'; AssignmentType = 'Eligible' }) + EligibleChecked = $true + } + } + + Test-MtEntraUnremediatedHighRiskServicePrincipal | Should -BeFalse + $script:Severity | Should -BeNullOrEmpty + $script:TestResult | Should -Match 'Global Administrator \\\(eligible\\\)' + } + + It 'does not list a non-privileged role' { + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { + return [pscustomobject]@{ + Assignments = @([pscustomobject]@{ principalId = 'sp-1'; roleDefinitionId = 'role-dr'; AssignmentType = 'Active' }) + EligibleChecked = $true + } + } + + Test-MtEntraUnremediatedHighRiskServicePrincipal | Should -BeFalse + $script:Severity | Should -BeNullOrEmpty + $script:TestResult | Should -Not -Match 'Directory Readers' + } + + It 'notes when PIM-eligible assignments could not be read' { + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { + return [pscustomobject]@{ Assignments = @(); EligibleChecked = $false } + } + + Test-MtEntraUnremediatedHighRiskServicePrincipal | Should -BeFalse + $script:TestResult | Should -Match 'PIM-eligible role assignments were not checked' + } + + It 'still reports the service principals when role assignments cannot be read' { + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { throw 'Forbidden' } + + Test-MtEntraUnremediatedHighRiskServicePrincipal | Should -BeFalse + $script:TestResult | Should -Match 'Contoso Sync' + $script:TestResult | Should -Match 'privileged service principals were not identified' + $script:Severity | Should -BeNullOrEmpty + } + } +} diff --git a/tests/maester/entra/Test.MT.1262.md b/tests/maester/entra/Test.MT.1262.md new file mode 100644 index 0000000000..514713695f --- /dev/null +++ b/tests/maester/entra/Test.MT.1262.md @@ -0,0 +1,40 @@ +High-risk service principals should not be left unremediated in Entra ID Protection. + +Entra ID Protection rates the risk of workload identities (service principals) and tracks a risk state for each flagged one. Signals include leaked credentials, suspicious sign-ins, suspicious API traffic and Microsoft threat intelligence. A high-risk flag only clears when an admin remediates or dismisses it. Until then the signals that triggered the flag have not been addressed, and unlike a user, a service principal can't be stopped by multifactor authentication. Dismissing a flag clears it but does not remove compromised credentials, so investigate first. + +This check reports service principals whose risk level is **high** and whose risk state is still active and unremediated (`atRisk` or `confirmedCompromised`). States that represent a handled flag (`remediated`, `dismissed`, `confirmedSafe`, `none`) are not reported. Disabled service principals are still reported, because disabling only blocks sign-ins: the risk stays open until an admin dismisses or confirms it, and the credentials behind it may still need rotating. The check reads risk only and never changes a service principal's risk state. + +If a reported service principal holds a privileged directory role, active or PIM-eligible, the result lists the role and shows that entry first, since a compromised app with admin rights puts the whole tenant at risk. + +The check needs a Microsoft Entra Workload ID Premium licence, which the risky service principals API requires. Tenants without it skip the check as not licensed. It also needs the Microsoft Graph permission `IdentityRiskyServicePrincipal.Read.All`, which Maester does not request by default. Without it the check is skipped. To identify privileged service principals, it also reads directory roles, which needs `RoleManagement.Read.Directory` or `RoleManagement.Read.All`. If those reads fail, the service principals are still reported with a note. Connect with `Connect-Maester -IncludePreview`, or grant the permission to the app registration that runs Maester. + +This is the service principal companion to MT.1260, which reports high-risk users left unremediated. A companion check, MT.1263, is planned to report on medium-risk service principals. + +#### Remediation action + +1. Open the [Microsoft Entra admin center](https://entra.microsoft.com) and navigate to **ID Protection** > **Risky workload identities**. +2. Locate each reported service principal by its name or application ID. Start with any service principal listed with a privileged role. +3. Investigate the risk detections behind the flag: look for suspicious sign-ins, unauthorized credential or configuration changes, and application roles the app should not have. +4. If the service principal is compromised: + - Inventory the credentials on the service principal and its application object. + - Add a new credential (Microsoft recommends a certificate), then remove the compromised credentials. If in doubt, remove all existing credentials. + - Rotate any Azure Key Vault secrets the service principal can access. + - Disable the service principal if it must be blocked while you investigate. +5. If the activity is confirmed safe after investigation, dismiss the risk so the flag clears. +6. Consider a risk-based Conditional Access policy for workload identities so that risky service principals are blocked automatically rather than left waiting for manual review. + +#### Known limitations + +* **Agents.** Agent identities and agent identity blueprint principals are service principals, but Entra ID Protection reports agent risk in its own list, `riskyAgents` (Microsoft Graph beta), which also covers agents' user accounts. This check reads only `riskyServicePrincipals`. In testing, an agent identity confirmed compromised appeared in `riskyAgents` and not in `riskyServicePrincipals`, and this check did not report it. +* **Privileged means directory roles.** The Privileged role column lists only built-in directory roles that Microsoft classifies as privileged, active or PIM-eligible. Custom roles and Microsoft Graph application permissions are not checked, so a service principal that holds powerful Graph permissions but no privileged built-in role shows `None`. +* **PIM-eligible roles.** Eligible role assignments are checked only when the tenant has Microsoft Entra ID P2 or Microsoft Entra ID Governance. Otherwise only active assignments are checked, and when the check reports service principals the result includes a note saying so. + +#### Related links + +* [Securing workload identities with ID Protection](https://learn.microsoft.com/entra/id-protection/concept-workload-identity-risk) +* [Conditional Access for workload identities](https://learn.microsoft.com/entra/identity/conditional-access/workload-identity) +* [riskyServicePrincipal resource type](https://learn.microsoft.com/graph/api/resources/riskyserviceprincipal) +* [ID Protection for agents](https://learn.microsoft.com/entra/id-protection/concept-risky-agents) + + +%TestResult% diff --git a/tests/maester/entra/Test.MT.1262.ps1 b/tests/maester/entra/Test.MT.1262.ps1 new file mode 100644 index 0000000000..3b423949c8 --- /dev/null +++ b/tests/maester/entra/Test.MT.1262.ps1 @@ -0,0 +1,161 @@ +function Test-MtEntraUnremediatedHighRiskServicePrincipal { + <# + .SYNOPSIS + Finds service principals that Entra ID Protection rates high risk and that nobody has remediated. + .DESCRIPTION + Entra ID Protection flags service principals (workload identities) it believes are compromised + and assigns a risk level and a risk state. A flag only clears when an admin remediates or + dismisses it. This check reports service principals whose risk level is + high and whose risk state still shows active, unremediated risk, so an admin can act on flags + that have been left sitting. If a reported service principal holds a privileged directory role, + it is listed first with its roles. It reads risk only; it never changes a service principal's risk state. + .EXAMPLE + Test-MtEntraUnremediatedHighRiskServicePrincipal + .LINK + https://maester.dev/docs/commands/Test-MtEntraUnremediatedHighRiskServicePrincipal + .LINK + https://learn.microsoft.com/graph/api/resources/riskyserviceprincipal?view=graph-rest-1.0 + #> + [MaesterTest( + Id = 'MT.1262', + Title = 'High-risk service principals should not be left unremediated in Entra ID Protection.', + Product = 'entra', + Feature = 'identity-protection', + Area = 'applications', + ResourceType = 'ServicePrincipal', + Severity = 'Medium', + UserImpact = 'Low', + ImplementationCost = 'Medium', + Mitre = 'T1078.004', + Control = ('nist-800-53-r5:AC-2(12)', 'nist-800-53-r5:IR-4'), + Cloud = ('Commercial', 'GCC', 'GCCHigh', 'DoD'), + Service = 'Graph', + License = 'AAD_WRKLDID_P1', + Permission = ('Graph:Scope:IdentityRiskyServicePrincipal.Read.All', 'Graph:Scope:RoleManagement.Read.Directory|Graph:Scope:RoleManagement.Read.All'), + Lifecycle = 'Preview', + Author = 'Dfrank77' + )] + [CmdletBinding()] + [OutputType([bool])] + param() + + # Active, unremediated risk states, same as MT.1260. 'confirmedCompromised' is still unremediated: + # confirming a service principal compromised does not clear the risk, and the confirmCompromised + # API (the documented way to simulate risk for testing) lands service principals in this state. + $UnremediatedStates = @('atRisk', 'confirmedCompromised') + + Write-Verbose 'Reading high-risk service principals from Entra ID Protection.' + # Filter riskLevel server-side only and apply the riskState set client-side, same as MT.1260. + try { + $HighRiskServicePrincipals = @( + Invoke-MtGraphRequest -ApiVersion 'v1.0' ` + -RelativeUri 'identityProtection/riskyServicePrincipals' ` + -Filter "riskLevel eq 'high'" ` + -Select @('id', 'appId', 'displayName', 'servicePrincipalType', 'riskLevel', 'riskState', 'riskDetail', 'riskLastUpdatedDateTime') + ) + } catch { + if ($_.Exception.Message -match '(?i)403|forbidden|authorization') { + Add-MtTestResultDetail -SkippedBecause NotAuthorized + return $null + } + throw + } + + # Disabled service principals are still reported. Disabling only blocks sign-ins: the risk stays open + # until an admin dismisses or confirms it, and an admin can still do that while the app is disabled. + # riskyServicePrincipal.isEnabled is not used because it can lag the service principal's real state. + $Unremediated = @( + $HighRiskServicePrincipals | Where-Object { $UnremediatedStates -contains [string]$_.riskState } + ) + Write-Verbose "Found $($HighRiskServicePrincipals.Count) high-risk service principal(s); $($Unremediated.Count) unremediated." + + if ($Unremediated.Count -eq 0) { + Add-MtTestResultDetail -Result ( + 'Well done. No high-risk service principals are left unremediated in Entra ID Protection.' + ) + return $true + } + + # Service principals at risk that hold a privileged role are listed first with their roles, as MT.1260 does + # for users. Roles are only read when there is something to report. If the lookup fails, the + # unremediated service principals are still reported, with a note. + $PrivilegedRolesBySp = @{} + $RoleNote = '' + try { + $RoleDefinitions = @( + Invoke-MtGraphRequest -ApiVersion 'v1.0' ` + -RelativeUri 'roleManagement/directory/roleDefinitions' ` + -Select @('id', 'displayName') + ) + $RoleDefLookup = @{} + foreach ($Def in $RoleDefinitions) { $RoleDefLookup[[string]$Def.id] = $Def } + + # Same properties as MT.1209, MT.1210 and MT.1260 so the active assignments come from the Graph cache. + $RoleAssignmentResult = Get-MtDirectoryRoleAssignment -Select @('id', 'principalId', 'roleDefinitionId', 'directoryScopeId') + if (!$RoleAssignmentResult.EligibleChecked) { + $RoleNote = "`n`nNote: PIM-eligible role assignments were not checked because they need " + + 'Microsoft Entra ID P2 or Governance. Only active role assignments were checked.' + } + + $UnremediatedIds = @{} + foreach ($Item in $Unremediated) { $UnremediatedIds[[string]$Item.id] = $true } + + foreach ($Assignment in @($RoleAssignmentResult.Assignments)) { + $PrincipalId = [string]$Assignment.principalId + if (!$UnremediatedIds.ContainsKey($PrincipalId)) { continue } + $RoleDef = $RoleDefLookup[[string]$Assignment.roleDefinitionId] + if ($null -eq $RoleDef) { continue } + $RoleInfo = Get-MtRoleInfo -RoleName ([string]$RoleDef.displayName -replace '\s', '') + if ($null -eq $RoleInfo -or !$RoleInfo.IsPrivileged) { continue } + $RoleName = [string]$RoleDef.displayName + if ($Assignment.AssignmentType -eq 'Eligible') { $RoleName += ' (eligible)' } + if (!$PrivilegedRolesBySp.ContainsKey($PrincipalId)) { + $PrivilegedRolesBySp[$PrincipalId] = [System.Collections.Generic.List[string]]::new() + } + $PrivilegedRolesBySp[$PrincipalId].Add($RoleName) + } + } catch { + Write-Verbose "Could not read directory role assignments: $($_.Exception.Message)" + $PrivilegedRolesBySp = @{} + $RoleNote = "`n`nNote: Directory role assignments could not be read, so privileged service principals were not identified." + } + + # Privileged service principals first, then by display name. + $Sorted = @( + $Unremediated | Sort-Object -Property @{ Expression = { -not $PrivilegedRolesBySp.ContainsKey([string]$_.id) } }, displayName + ) + $PrivilegedCount = @($Unremediated | Where-Object { $PrivilegedRolesBySp.ContainsKey([string]$_.id) }).Count + + $Result = "Found $($Unremediated.Count) high-risk service principal(s) with unremediated risk." + if ($PrivilegedCount -gt 0) { + $Result += " $PrivilegedCount of them hold a privileged directory role and are listed first." + } + $Result += "`n`n| Service principal | Application ID | Type | Risk state | Risk detail | Risk last updated | Privileged role |" + $Result += "`n| --- | --- | --- | --- | --- | --- | --- |" + foreach ($Item in $Sorted) { + $DisplayName = [string]$Item.displayName + if ([string]::IsNullOrWhiteSpace($DisplayName)) { $DisplayName = '(unnamed)' } + $Link = Get-MtLinkServicePrincipal -ServicePrincipal ([pscustomobject]@{ id = $Item.id; appId = $Item.appId; DisplayName = $DisplayName }) + $Type = Get-MtSafeMarkdown ([string]$Item.servicePrincipalType) + $State = [string]$Item.riskState + $Detail = Get-MtSafeMarkdown ([string]$Item.riskDetail) + $Updated = if ($Item.riskLastUpdatedDateTime) { + ($Item.riskLastUpdatedDateTime -as [datetime]).ToUniversalTime().ToString('yyyy-MM-dd') + } else { 'Unknown' } + $Roles = if ($PrivilegedRolesBySp.ContainsKey([string]$Item.id)) { + Get-MtSafeMarkdown ($PrivilegedRolesBySp[[string]$Item.id] -join ', ') + } else { 'None' } + $Result += "`n| $Link | $($Item.appId) | $Type | $State | $Detail | $Updated | $Roles |" + } + $Result += $RoleNote + + # Each risky service principal also appears on the report's Affected objects page; the table above stays as it is. + # There is no GraphObjectType for service principals, so the type comes from @odata.type. + $AffectedServicePrincipals = @( + $Sorted | ForEach-Object { + [pscustomobject]@{ id = [string]$_.id; displayName = [string]$_.displayName; '@odata.type' = '#microsoft.graph.servicePrincipal' } + } + ) + Add-MtTestResultDetail -Result $Result -GraphObjects $AffectedServicePrincipals + return $false +} diff --git a/website/docs/sections/permissions.md b/website/docs/sections/permissions.md index 05f1d58a0d..72852c0784 100644 --- a/website/docs/sections/permissions.md +++ b/website/docs/sections/permissions.md @@ -37,4 +37,5 @@ To run preview tests, also grant these application permissions: - **AgentIdentityBlueprint.Read.All** - **AgentIdentityBlueprintPrincipal.Read.All** - **Application.Read.All** +- **IdentityRiskyServicePrincipal.Read.All** - **IdentityRiskyUser.Read.All**