diff --git a/powershell/internal/services/entra/Get-MtServicePrincipalRiskDetection.ps1 b/powershell/internal/services/entra/Get-MtServicePrincipalRiskDetection.ps1 new file mode 100644 index 0000000000..bc24ffe3e1 --- /dev/null +++ b/powershell/internal/services/entra/Get-MtServicePrincipalRiskDetection.ps1 @@ -0,0 +1,40 @@ +function Get-MtServicePrincipalRiskDetection { + <# + .SYNOPSIS + Returns the Entra ID Protection workload identity risk detections that are still open. + + .DESCRIPTION + Reads identityProtection/servicePrincipalRiskDetections (Microsoft Graph v1.0) and returns the + detections whose risk state is atRisk or confirmedCompromised: the detections nobody has remediated + or dismissed. Each state is read with its own single-property filter, because Graph rejects some + compound filters on the Identity Protection endpoints, and each read goes through the Graph cache so + the checks that call this in one run share the same two requests. + + Graph keeps risk detections for 90 days, so older detections are not returned. The API needs a + Microsoft Entra Workload ID Premium licence and the IdentityRiskEvent.Read.All permission. + + .EXAMPLE + Get-MtServicePrincipalRiskDetection | Group-Object riskEventType + + Counts the open workload identity risk detections by detection type. + + .LINK + https://learn.microsoft.com/graph/api/identityprotectionroot-list-serviceprincipalriskdetections?view=graph-rest-1.0 + #> + [CmdletBinding()] + [OutputType([object[]])] + param() + + $select = @( + 'id', 'riskEventType', 'riskLevel', 'riskState', 'riskDetail', 'activity', 'detectionTimingType', + 'ipAddress', 'location', 'activityDateTime', 'detectedDateTime', 'lastUpdatedDateTime', + 'servicePrincipalId', 'servicePrincipalDisplayName', 'appId', 'keyIds' + ) + + foreach ($state in @('atRisk', 'confirmedCompromised')) { + Invoke-MtGraphRequest -ApiVersion 'v1.0' ` + -RelativeUri 'identityProtection/servicePrincipalRiskDetections' ` + -Filter "riskState eq '$state'" ` + -Select $select + } +} diff --git a/powershell/tests/fixtures/golden/config-layouts/root-custom-tenant/expected.json b/powershell/tests/fixtures/golden/config-layouts/root-custom-tenant/expected.json index e805f75524..d26dcad98b 100644 --- a/powershell/tests/fixtures/golden/config-layouts/root-custom-tenant/expected.json +++ b/powershell/tests/fixtures/golden/config-layouts/root-custom-tenant/expected.json @@ -15,7 +15,7 @@ "TenantId": null, "ConfigFile": "powershell/tests/fixtures/golden/config-layouts/root-custom-tenant/maester-config.json", "ConfigSource": "maester-config.json", - "CustomOverlay": "powershell/tests/fixtures/golden/config-layouts/root-custom-tenant/Custom/maester-config.json", + "CustomOverlay": "powershell/tests/fixtures/golden/config-layouts/root-custom-tenant/custom/maester-config.json", "UsedShippedFile": false, "GlobalSettings": { "EmergencyAccessAccounts": [ @@ -37,7 +37,7 @@ "TenantId": "11111111-2222-3333-4444-555555555555", "ConfigFile": "powershell/tests/fixtures/golden/config-layouts/root-custom-tenant/maester-config.11111111-2222-3333-4444-555555555555.json", "ConfigSource": "maester-config.11111111-2222-3333-4444-555555555555.json", - "CustomOverlay": "powershell/tests/fixtures/golden/config-layouts/root-custom-tenant/Custom/maester-config.json", + "CustomOverlay": "powershell/tests/fixtures/golden/config-layouts/root-custom-tenant/custom/maester-config.json", "UsedShippedFile": false, "GlobalSettings": { "EmergencyAccessAccounts": [ diff --git a/powershell/tests/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index ce3cdde573..cc80a46915 100644 --- a/powershell/tests/fixtures/golden/selection.json +++ b/powershell/tests/fixtures/golden/selection.json @@ -1921,7 +1921,7 @@ "AD" ] }, - "SelectedCount": 590, + "SelectedCount": 591, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -2451,6 +2451,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1274", "ORCA.100", "ORCA.101", "ORCA.102", @@ -2532,7 +2533,7 @@ "AD" ] }, - "SelectedCount": 620, + "SelectedCount": 621, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -3094,6 +3095,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1274", "ORCA.100", "ORCA.101", "ORCA.102", @@ -3928,7 +3930,7 @@ "AD" ] }, - "SelectedCount": 576, + "SelectedCount": 577, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -4446,6 +4448,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1274", "ORCA.100", "ORCA.101", "ORCA.102", diff --git a/powershell/tests/functions/Test-MtEntraServicePrincipalRiskDetection.Tests.ps1 b/powershell/tests/functions/Test-MtEntraServicePrincipalRiskDetection.Tests.ps1 new file mode 100644 index 0000000000..8dcdc7e904 --- /dev/null +++ b/powershell/tests/functions/Test-MtEntraServicePrincipalRiskDetection.Tests.ps1 @@ -0,0 +1,176 @@ +Describe 'Entra ID Protection open workload identity risk detections (MT.1274)' { + BeforeAll { + Import-Module $PSScriptRoot/../../Maester.psd1 -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + # The native-test functions are not exported; reach them the same way the other check tests do. + Use-MtModuleFunction -Name Test-MtEntraServicePrincipalRiskDetection, Get-MtServicePrincipalRiskDetectionInstance + + function script:New-TestDetection { + param( + [string] $Type = 'leakedCredentials', + [string] $Level = 'high', + [string] $State = 'atRisk', + [string] $Upn = 'alice@contoso.com', + [string] $Detected = '2026-10-01T00:00:00Z' + ) + [pscustomobject]@{ + id = [guid]::NewGuid().ToString() + riskEventType = $Type + riskLevel = $Level + riskState = $State + activity = 'signin' + ipAddress = '203.0.113.10' + location = [pscustomobject]@{ city = 'Seattle'; countryOrRegion = 'US' } + detectedDateTime = $Detected + servicePrincipalId = 'sp-1' + servicePrincipalDisplayName = 'Alice' + appId = $Upn + } + } + + # The documented instances, read once so the per-test mocks of Get-MtServicePrincipalRiskDetection stay in charge. + $script:DocumentedInstances = InModuleScope Maester { + # Capture the script block first: Set-Item updates the FunctionInfo object in place. + $realBody = (Get-Command Get-MtServicePrincipalRiskDetection).ScriptBlock + Set-Item -Path function:Get-MtServicePrincipalRiskDetection -Value { @() } + try { Get-MtServicePrincipalRiskDetectionInstance } finally { Set-Item -Path function:Get-MtServicePrincipalRiskDetection -Value $realBody } + } + + function script:Get-TestInstance { + param([string] $Id) + $script:DocumentedInstances | Where-Object { $_.Id -eq $Id } + } + } + + BeforeEach { + $script:TestResult = $null + $script:SkippedBecause = $null + $script:Severity = $null + + Mock -ModuleName Maester Add-MtTestResultDetail { + param($Result, $SkippedBecause, $SkippedError, $Severity) + $script:TestResult = $Result + $script:SkippedBecause = $SkippedBecause + $script:Severity = $Severity + } + } + + AfterEach { + # Result text must not contain backtick-wrapped code spans (repo result-text lint). + if ($null -ne $script:TestResult) { + $script:TestResult | Should -Not -Match '`[^`]+`' + } + } + + Context 'Instance source' { + It 'returns one instance per documented detection type' { + $instances = InModuleScope Maester { + Mock Get-MtServicePrincipalRiskDetection { return @() } + Get-MtServicePrincipalRiskDetectionInstance + } + $instances.Count | Should -Be 8 + ($instances.Id | Sort-Object -Unique).Count | Should -Be 8 + $instances.Id | Should -Contain 'maliciousApplication' + $instances.Id | Should -Contain 'anomalousServicePrincipalActivity' + foreach ($instance in $instances) { + $instance.Id | Should -Match '^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$' + $instance.Severity | Should -BeIn @('High', 'Medium', 'Low') + $instance.Data.About | Should -Not -BeNullOrEmpty + $instance.Data.Tips | Should -Match '^https://learn\.microsoft\.com/' + } + } + + It 'adds a row for an undocumented detection type that has open detections' { + $instances = InModuleScope Maester { + Mock Get-MtServicePrincipalRiskDetection { + return @( + [pscustomobject]@{ riskEventType = 'leakedCredentials' } + [pscustomobject]@{ riskEventType = 'brandNewDetection' } + ) + } + Get-MtServicePrincipalRiskDetectionInstance + } + $instances.Count | Should -Be 9 + $instances.Id | Should -Contain 'brandNewDetection' + } + + It 'returns the documented types when the detections cannot be read' { + $instances = InModuleScope Maester { + Mock Get-MtServicePrincipalRiskDetection { throw '403 Forbidden' } + Get-MtServicePrincipalRiskDetectionInstance + } + $instances.Count | Should -Be 8 + } + } + + Context 'Check' { + It 'passes when no detection of the type is open' { + Mock -ModuleName Maester Get-MtServicePrincipalRiskDetection { return @(New-TestDetection -Type 'suspiciousSignins') } + + Test-MtEntraServicePrincipalRiskDetection -Instance (Get-TestInstance 'leakedCredentials') | Should -BeTrue + $script:TestResult | Should -Match 'Well done' + $script:Severity | Should -Be 'High' + } + + It 'fails and lists the open detections of the type, high risk first' { + Mock -ModuleName Maester Get-MtServicePrincipalRiskDetection { + return @( + New-TestDetection -Level 'low' -Upn 'low@contoso.com' + New-TestDetection -Level 'high' -Upn 'high@contoso.com' + New-TestDetection -Level 'medium' -Upn 'medium@contoso.com' -State 'confirmedCompromised' + New-TestDetection -Type 'suspiciousSignins' -Upn 'other@contoso.com' + ) + } + + Test-MtEntraServicePrincipalRiskDetection -Instance (Get-TestInstance 'leakedCredentials') | Should -BeFalse + $script:TestResult | Should -Match 'Found 3 open' + $script:TestResult | Should -Match '1 high, 1 medium, 1 low' + $script:TestResult | Should -Not -Match 'other@contoso\.com' + $script:TestResult.IndexOf('high@contoso.com') | Should -BeLessThan $script:TestResult.IndexOf('medium@contoso.com') + $script:TestResult.IndexOf('medium@contoso.com') | Should -BeLessThan $script:TestResult.IndexOf('low@contoso.com') + } + + It 'skips as not authorized when Graph returns 403' { + Mock -ModuleName Maester Get-MtServicePrincipalRiskDetection { throw 'Response status code does not indicate success: 403 (Forbidden).' } + + Test-MtEntraServicePrincipalRiskDetection -Instance (Get-TestInstance 'leakedCredentials') | Should -BeNullOrEmpty + $script:SkippedBecause | Should -Be 'NotAuthorized' + } + + It 'limits the table and says how many more there are' { + Mock -ModuleName Maester Get-MtServicePrincipalRiskDetection { + return @(1..105 | ForEach-Object { New-TestDetection -Type 'suspiciousAPITraffic' -Level 'low' -Upn "user$_@contoso.com" }) + } + + Test-MtEntraServicePrincipalRiskDetection -Instance (Get-TestInstance 'suspiciousAPITraffic') | Should -BeFalse + $script:TestResult | Should -Match 'Showing the first 100 of 105' + } + + It 'escapes a tenant-controlled display name' { + Mock -ModuleName Maester Get-MtServicePrincipalRiskDetection { + $d = New-TestDetection + $d.servicePrincipalDisplayName = '[Sign in again](https://phish.example)' + return @($d) + } + + Test-MtEntraServicePrincipalRiskDetection -Instance (Get-TestInstance 'leakedCredentials') | Should -BeFalse + $script:TestResult | Should -Not -Match '(? **Risk detections** > **Workload identity detections**. Start with high-risk detections and with service principals that hold privileged app roles or directory roles. +2. Investigate each service principal: its sign-ins, recent changes to its credentials, owners and app roles, and its configuration changes in the audit log. +3. If the activity is legitimate, go to **ID Protection** > **Risky workload identities** and select **Dismiss risk**. +4. If the service principal is compromised, select **Confirm compromised**, then: + - inventory the credentials of the service principal and its application object, add a new credential (preferably a certificate) and remove all the old ones; + - rotate any Azure Key Vault secrets the service principal can read; + - remove app roles, owners or permissions an attacker added, or disable the service principal until it is clean. +5. To block risky workload identities automatically, use a Conditional Access policy for workload identities with the service principal risk condition. + +#### Related links + +* [Securing workload identities with Microsoft Entra 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) +* [Microsoft Entra security operations guide for applications](https://learn.microsoft.com/entra/architecture/security-operations-applications) + + +%TestResult% diff --git a/tests/maester/entra/Test.MT.1274.ps1 b/tests/maester/entra/Test.MT.1274.ps1 new file mode 100644 index 0000000000..76ee6461b8 --- /dev/null +++ b/tests/maester/entra/Test.MT.1274.ps1 @@ -0,0 +1,190 @@ +function Get-MtServicePrincipalRiskDetectionInstance { + <# + .SYNOPSIS + Returns one MT.1274 instance per Entra ID Protection workload identity risk detection type. + + .DESCRIPTION + Instance source of the MT.1274 family. Returns one instance for each workload identity risk + detection type that Microsoft documents (MT.1274.), so every type has a row in the + report whether or not it has open detections. Any riskEventType that Graph returns for an open + detection and that is not in the list gets a row of its own, so a detection Microsoft adds later is + reported rather than dropped. If the open detections cannot be read here, only the documented + types are returned and each row reports the error itself. + + Source: https://learn.microsoft.com/entra/id-protection/concept-workload-identity-risk + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param() + + $investigate = 'https://learn.microsoft.com/entra/id-protection/concept-workload-identity-risk#investigate-risky-workload-identities' + + # Name, severity of an open detection and a short summary of each documented detection type. + $catalog = @( + @{ Id = 'investigationsThreatIntelligence'; Name = 'Microsoft Entra threat intelligence'; Severity = 'High' + About = "The service principal's activity matches attack patterns known to Microsoft threat intelligence." } + @{ Id = 'suspiciousSignins'; Name = 'Suspicious sign-ins'; Severity = 'Medium' + About = 'The service principal signed in with properties unusual for it, such as a new IP address, ASN, country, target resource, user agent or credential type.' } + @{ Id = 'adminConfirmedServicePrincipalCompromised'; Name = 'Admin confirmed service principal compromised'; Severity = 'High' + About = 'An administrator confirmed this service principal compromised. Its credentials still need to be replaced.' } + @{ Id = 'leakedCredentials'; Name = 'Leaked credentials'; Severity = 'High' + About = "A valid credential of the service principal was found in public code or a leak, so anyone who found it can sign in as the app." } + @{ Id = 'maliciousApplication'; Name = 'Malicious application'; Severity = 'High' + About = 'Microsoft disabled the application for violating its terms of service.' } + @{ Id = 'suspiciousApplication'; Name = 'Suspicious application'; Severity = 'Medium' + About = 'Microsoft found that the application might violate its terms of service but has not disabled it.' } + @{ Id = 'anomalousServicePrincipalActivity'; Name = 'Anomalous service principal activity'; Severity = 'Medium' + About = 'The service principal made directory changes that differ from its usual administrative behaviour.' } + @{ Id = 'suspiciousAPITraffic'; Name = 'Suspicious API traffic'; Severity = 'Medium' + About = 'The service principal made unusual Microsoft Graph calls or enumerated the directory, which can be reconnaissance or data exfiltration.' } + ) + + $known = @{} + foreach ($entry in $catalog) { + $known[$entry.Id] = $true + $entry.Tips = $investigate + [pscustomobject]@{ + Id = $entry.Id + Title = "Open '$($entry.Name)' workload identity risk detections should be reviewed in Entra ID Protection." + Severity = $entry.Severity + Data = [pscustomobject]$entry + } + } + + # Detection types Microsoft has added since this list was written. + try { + $openTypes = @(Get-MtServicePrincipalRiskDetection | ForEach-Object { [string]$_.riskEventType } | Where-Object { $_ } | Sort-Object -Unique) + } catch { + Write-Verbose "MT.1274: could not read open risk detections for undocumented types. $($_.Exception.Message)" + $openTypes = @() + } + foreach ($type in $openTypes) { + if ($known.ContainsKey($type) -or $type -notmatch '^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$') { continue } + [pscustomobject]@{ + Id = $type + Title = "Open '$type' workload identity risk detections should be reviewed in Entra ID Protection." + Severity = 'Medium' + Data = [pscustomobject]@{ + Id = $type + Name = $type + Severity = 'Medium' + About = 'Microsoft Graph returned this detection type, but it is not in the list Maester knows. Check the Microsoft documentation for what it means.' + Tips = $investigate + } + } + } +} + +function Test-MtEntraServicePrincipalRiskDetection { + <# + .SYNOPSIS + Checks that no Entra ID Protection workload identity risk detection of a given type is left open. + + .DESCRIPTION + Runs once per workload identity risk detection type (identityProtection/servicePrincipalRiskDetections). + Fails when at least one detection of the type still has the risk state atRisk or + confirmedCompromised, and lists those detections with the high-risk ones first. Detections that have + been remediated or dismissed pass. The check reads risk only and never changes it. + + .EXAMPLE + Invoke-MtTest -Id MT.1274 + + .LINK + https://maester.dev/docs/tests/MT.1274 + + .LINK + https://learn.microsoft.com/entra/id-protection/concept-workload-identity-risk + #> + [MaesterTest( + Id = 'MT.1274', + Title = 'Open Entra ID Protection workload identity risk detections should be reviewed.', + Product = 'entra', + Feature = 'identity-protection', + Area = 'applications', + ResourceType = 'ServicePrincipal', + Severity = 'Medium', + UserImpact = 'Low', + ImplementationCost = 'Medium', + Mitre = ('T1078.004', 'T1098.001', 'T1552'), + Control = ('nist-800-53-r5:IR-4', 'nist-800-53-r5:AC-2(12)'), + Service = 'Graph', + License = ('AAD_WRKLDID_P1', 'AAD_WRKLDID_P2'), + Permission = 'Graph:Scope:IdentityRiskEvent.Read.All', + InstanceSource = 'Get-MtServicePrincipalRiskDetectionInstance', + Lifecycle = 'Preview', + Author = 'merill' + )] + [CmdletBinding()] + [OutputType([bool])] + param( + # The detection type to check, supplied by the engine. + $Instance + ) + + # Rows shown in the result table. + $MaxRows = 100 + + $type = $Instance.Data + $severity = $Instance.Severity + $name = Get-MtSafeMarkdown ([string]$type.Name) + $about = "**$name** ($([string]$type.Id)): $($type.About) [Investigation guidance]($($type.Tips))" + + try { + $detections = @(Get-MtServicePrincipalRiskDetection) + } catch { + if ($_.Exception.Message -match '(?i)403|forbidden|authorization') { + Add-MtTestResultDetail -Severity $severity -SkippedBecause NotAuthorized + return $null + } + throw + } + + $open = @($detections | Where-Object { [string]$_.riskEventType -eq [string]$type.Id }) + Write-Verbose "MT.1274: $($open.Count) open '$($type.Id)' detection(s) out of $($detections.Count) open detection(s)." + + if ($open.Count -eq 0) { + Add-MtTestResultDetail -Severity $severity -Result "Well done. No '$name' workload identity risk detections are open.`n`n$about" + return $true + } + + $levelOrder = @{ high = 0; medium = 1; low = 2 } + $sorted = @( + $open | Sort-Object -Property @( + @{ Expression = { $order = $levelOrder[[string]$_.riskLevel]; if ($null -eq $order) { 3 } else { $order } } } + @{ Expression = { $_.detectedDateTime -as [datetime] }; Descending = $true } + ) + ) + + $counts = foreach ($level in @('high', 'medium', 'low')) { + $count = @($open | Where-Object { [string]$_.riskLevel -eq $level }).Count + if ($count -gt 0) { "$count $level" } + } + $other = $open.Count - @($open | Where-Object { [string]$_.riskLevel -in @('high', 'medium', 'low') }).Count + if ($other -gt 0) { $counts = @($counts) + "$other with no level shown" } + + $result = "Found $($open.Count) open '$name' workload identity risk detection(s): $(@($counts) -join ', ').`n`n$about" + $result += "`n`n| Service principal | App ID | Risk level | Risk state | Detected (UTC) | IP address |" + $result += "`n| --- | --- | --- | --- | --- | --- |" + foreach ($item in @($sorted | Select-Object -First $MaxRows)) { + $displayName = [string]$item.servicePrincipalDisplayName + if ([string]::IsNullOrWhiteSpace($displayName)) { $displayName = '(unnamed)' } + $detected = if ($item.detectedDateTime) { + ($item.detectedDateTime -as [datetime]).ToUniversalTime().ToString('yyyy-MM-dd HH:mm') + } else { 'Unknown' } + $cells = @( + $displayName + [string]$item.appId + [string]$item.riskLevel + [string]$item.riskState + $detected + [string]$item.ipAddress + ) | ForEach-Object { Get-MtSafeMarkdown ([string]$_) } + $result += "`n| $($cells -join ' | ') |" + } + if ($sorted.Count -gt $MaxRows) { + $result += "`n`nShowing the first $MaxRows of $($sorted.Count). See **ID Protection** > **Risk detections** > **Workload identity detections** in the Microsoft Entra admin center for the rest." + } + + Add-MtTestResultDetail -Severity $severity -Result $result + return $false +}