From 08df3b7511dafd9b0604c2e6cbf83ed5d511d4ef Mon Sep 17 00:00:00 2001 From: Merill Fernando Date: Sun, 8 Nov 2026 20:38:47 +1100 Subject: [PATCH] feat(entra): add MT.1273 - open Entra ID Protection user risk detections, one result per detection type A family check with one row per documented sign-in and user riskEventType (plus any undocumented type with open detections). A row fails when a detection of its type is still atRisk or confirmedCompromised and lists them high risk first, so SecOps can review and dismiss or remediate them. Part of #2730. Co-Authored-By: Claude Opus 5.5 Entire-Checkpoint: 01M6X8CMR457WNSZ1TZGV4DGSM --- .../entra/Get-MtUserRiskDetection.ps1 | 40 +++ .../root-custom-tenant/expected.json | 4 +- .../tests/fixtures/golden/selection.json | 9 +- .../Test-MtEntraUserRiskDetection.Tests.ps1 | 193 ++++++++++++++ .../tests/general/NativeTestLint.Tests.ps1 | 1 + tests/maester/entra/Test.MT.1273.md | 34 +++ tests/maester/entra/Test.MT.1273.ps1 | 249 ++++++++++++++++++ 7 files changed, 525 insertions(+), 5 deletions(-) create mode 100644 powershell/internal/services/entra/Get-MtUserRiskDetection.ps1 create mode 100644 powershell/tests/functions/Test-MtEntraUserRiskDetection.Tests.ps1 create mode 100644 tests/maester/entra/Test.MT.1273.md create mode 100644 tests/maester/entra/Test.MT.1273.ps1 diff --git a/powershell/internal/services/entra/Get-MtUserRiskDetection.ps1 b/powershell/internal/services/entra/Get-MtUserRiskDetection.ps1 new file mode 100644 index 0000000000..d5e1e015f8 --- /dev/null +++ b/powershell/internal/services/entra/Get-MtUserRiskDetection.ps1 @@ -0,0 +1,40 @@ +function Get-MtUserRiskDetection { + <# + .SYNOPSIS + Returns the Entra ID Protection user risk detections that are still open. + + .DESCRIPTION + Reads identityProtection/riskDetections (Microsoft Graph v1.0) and returns the detections whose risk + state is atRisk or confirmedCompromised: the detections nobody has remediated, dismissed or confirmed + safe. 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 + Microsoft Entra ID P1 or P2 and the IdentityRiskEvent.Read.All permission. + + .EXAMPLE + Get-MtUserRiskDetection | Group-Object riskEventType + + Counts the open user risk detections by detection type. + + .LINK + https://learn.microsoft.com/graph/api/riskdetection-list?view=graph-rest-1.0 + #> + [CmdletBinding()] + [OutputType([object[]])] + param() + + $select = @( + 'id', 'riskEventType', 'riskLevel', 'riskState', 'riskDetail', 'activity', 'detectionTimingType', + 'ipAddress', 'location', 'activityDateTime', 'detectedDateTime', 'lastUpdatedDateTime', + 'userId', 'userDisplayName', 'userPrincipalName' + ) + + foreach ($state in @('atRisk', 'confirmedCompromised')) { + Invoke-MtGraphRequest -ApiVersion 'v1.0' ` + -RelativeUri 'identityProtection/riskDetections' ` + -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..96732034b4 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.1273", "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.1273", "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.1273", "ORCA.100", "ORCA.101", "ORCA.102", diff --git a/powershell/tests/functions/Test-MtEntraUserRiskDetection.Tests.ps1 b/powershell/tests/functions/Test-MtEntraUserRiskDetection.Tests.ps1 new file mode 100644 index 0000000000..6ef4902716 --- /dev/null +++ b/powershell/tests/functions/Test-MtEntraUserRiskDetection.Tests.ps1 @@ -0,0 +1,193 @@ +Describe 'Entra ID Protection open user risk detections (MT.1273)' { + 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-MtEntraUserRiskDetection, Get-MtUserRiskDetectionInstance + + function script:New-TestDetection { + param( + [string] $Type = 'passwordSpray', + [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 + userId = 'user-1' + userDisplayName = 'Alice' + userPrincipalName = $Upn + } + } + + # The documented instances, read once so the per-test mocks of Get-MtUserRiskDetection stay in charge. + $script:DocumentedInstances = InModuleScope Maester { + # Capture the script block first: Set-Item updates the FunctionInfo object in place. + $realBody = (Get-Command Get-MtUserRiskDetection).ScriptBlock + Set-Item -Path function:Get-MtUserRiskDetection -Value { @() } + try { Get-MtUserRiskDetectionInstance } finally { Set-Item -Path function:Get-MtUserRiskDetection -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 + } + Mock -ModuleName Maester Get-MtLicenseInformation { return 'P2' } + } + + 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-MtUserRiskDetection { return @() } + Get-MtUserRiskDetectionInstance + } + $instances.Count | Should -Be 27 + ($instances.Id | Sort-Object -Unique).Count | Should -Be 27 + $instances.Id | Should -Contain 'suspiciousCredentialAddition' + $instances.Id | Should -Contain 'generic' + 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-MtUserRiskDetection { + return @( + [pscustomobject]@{ riskEventType = 'passwordSpray' } + [pscustomobject]@{ riskEventType = 'brandNewDetection' } + ) + } + Get-MtUserRiskDetectionInstance + } + $instances.Count | Should -Be 28 + $instances.Id | Should -Contain 'brandNewDetection' + } + + It 'returns the documented types when the detections cannot be read' { + $instances = InModuleScope Maester { + Mock Get-MtUserRiskDetection { throw '403 Forbidden' } + Get-MtUserRiskDetectionInstance + } + $instances.Count | Should -Be 27 + } + } + + Context 'Check' { + It 'passes when no detection of the type is open' { + Mock -ModuleName Maester Get-MtUserRiskDetection { return @(New-TestDetection -Type 'leakedCredentials') } + + Test-MtEntraUserRiskDetection -Instance (Get-TestInstance 'passwordSpray') | 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-MtUserRiskDetection { + 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 'leakedCredentials' -Upn 'other@contoso.com' + ) + } + + Test-MtEntraUserRiskDetection -Instance (Get-TestInstance 'passwordSpray') | 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 a premium detection type without Entra ID P2' { + Mock -ModuleName Maester Get-MtLicenseInformation { return 'P1' } + Mock -ModuleName Maester Get-MtUserRiskDetection { return @() } + + Test-MtEntraUserRiskDetection -Instance (Get-TestInstance 'passwordSpray') | Should -BeNullOrEmpty + $script:SkippedBecause | Should -Be 'NotLicensedEntraIDP2' + Should -Invoke Get-MtUserRiskDetection -ModuleName Maester -Exactly -Times 0 + } + + It 'checks a non-premium detection type without Entra ID P2' { + Mock -ModuleName Maester Get-MtLicenseInformation { return 'P1' } + Mock -ModuleName Maester Get-MtUserRiskDetection { return @(New-TestDetection -Type 'leakedCredentials') } + + Test-MtEntraUserRiskDetection -Instance (Get-TestInstance 'leakedCredentials') | Should -BeFalse + } + + It 'skips as not authorized when Graph returns 403' { + Mock -ModuleName Maester Get-MtUserRiskDetection { throw 'Response status code does not indicate success: 403 (Forbidden).' } + + Test-MtEntraUserRiskDetection -Instance (Get-TestInstance 'passwordSpray') | Should -BeNullOrEmpty + $script:SkippedBecause | Should -Be 'NotAuthorized' + } + + It 'limits the table and says how many more there are' { + Mock -ModuleName Maester Get-MtUserRiskDetection { + return @(1..105 | ForEach-Object { New-TestDetection -Type 'anonymizedIPAddress' -Level 'low' -Upn "user$_@contoso.com" }) + } + + Test-MtEntraUserRiskDetection -Instance (Get-TestInstance 'anonymizedIPAddress') | Should -BeFalse + $script:TestResult | Should -Match 'Showing the first 100 of 105' + } + + It 'escapes a tenant-controlled display name' { + Mock -ModuleName Maester Get-MtUserRiskDetection { + $d = New-TestDetection + $d.userDisplayName = '[Sign in again](https://phish.example)' + return @($d) + } + + Test-MtEntraUserRiskDetection -Instance (Get-TestInstance 'passwordSpray') | Should -BeFalse + $script:TestResult | Should -Not -Match '(? **Risk detections**. Filter by **Detection type** and by **Risk state** = **At risk**. Start with high-risk detections and with users who hold an admin role. +2. Investigate each detection: the user's sign-ins around the detection time, the IP address and location, recent changes to the user's authentication methods, mailbox rules and app consents. Confirm with the user through a channel the attacker cannot control. +3. If the activity is legitimate, close it: in **Risky sign-ins** select **Confirm sign-in safe**, or in **Risky users** select **Dismiss user risk**. +4. If the account is compromised, select **Confirm user compromised** and remediate: + - require a secure password reset and revoke the user's sessions; + - remove any authentication method, device, inbox rule or app consent the attacker added. A password reset alone does not remove an attacker's MFA method; + - check what the account accessed while it was compromised. +5. To keep the queue short, use risk-based Conditional Access policies that require risk remediation, so users clear most user and sign-in risk themselves. + +#### Related links + +* [What are risk detections?](https://learn.microsoft.com/entra/id-protection/concept-identity-protection-risks) +* [Investigate risk with Microsoft Entra ID Protection](https://learn.microsoft.com/entra/id-protection/howto-identity-protection-investigate-risk) +* [Remediate risks and unblock users](https://learn.microsoft.com/entra/id-protection/howto-identity-protection-remediate-unblock) +* [Provide feedback on risk detections](https://learn.microsoft.com/entra/id-protection/howto-identity-protection-risk-feedback) + + +%TestResult% diff --git a/tests/maester/entra/Test.MT.1273.ps1 b/tests/maester/entra/Test.MT.1273.ps1 new file mode 100644 index 0000000000..f259291084 --- /dev/null +++ b/tests/maester/entra/Test.MT.1273.ps1 @@ -0,0 +1,249 @@ +function Get-MtUserRiskDetectionInstance { + <# + .SYNOPSIS + Returns one MT.1273 instance per Entra ID Protection user risk detection type. + + .DESCRIPTION + Instance source of the MT.1273 family. Returns one instance for each sign-in and user risk + detection type that Microsoft documents (MT.1273.), 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-identity-protection-risks + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param() + + $investigate = 'https://learn.microsoft.com/entra/id-protection/howto-identity-protection-investigate-risk' + + # Name, whether Entra ID P2 is needed to see it, severity of an open detection, a short summary, + # and Microsoft's investigation tips where they publish a section for the type. + $catalog = @( + @{ Id = 'riskyIPAddress'; Name = 'Activity from anonymous IP address'; Premium = $true; Severity = 'Medium' + About = 'Microsoft Defender for Cloud Apps saw the user active from an IP address known as an anonymous proxy.' } + @{ Id = 'authenticatorPhishing'; Name = 'Suspicious MFA authentication approval'; Premium = $true; Severity = 'High' + About = 'An MFA approval in Microsoft Authenticator came from a device and location that do not match the sign-in it approved, a sign of a phishing or social engineering attack.' } + @{ Id = 'generic'; Name = 'Additional risk detected'; Premium = $false; Severity = 'Medium' + About = 'A premium detection fired. Its details are only shown to tenants with Microsoft Entra ID P2.' } + @{ Id = 'adminConfirmedUserCompromised'; Name = 'Admin confirmed user compromised'; Premium = $false; Severity = 'High' + About = 'An administrator confirmed this user compromised. The account still needs to be remediated.' } + @{ Id = 'anomalousToken'; Name = 'Anomalous token'; Premium = $true; Severity = 'Medium' + About = 'A session or refresh token has unusual characteristics, such as an unusual lifetime or use from an unfamiliar location, which can indicate token replay.' + Tips = "$investigate#anomalous-token-and-token-issuer-anomaly-detections" } + @{ Id = 'anonymizedIPAddress'; Name = 'Anonymous IP address'; Premium = $false; Severity = 'Low' + About = 'The user signed in from an anonymous IP address, such as Tor or an anonymizing VPN.' } + @{ Id = 'unlikelyTravel'; Name = 'Atypical travel'; Premium = $true; Severity = 'Medium' + About = 'Two sign-ins came from locations too far apart for the user to travel between, and at least one location is unusual for the user.' + Tips = "$investigate#atypical-travel-detections" } + @{ Id = 'mcasImpossibleTravel'; Name = 'Impossible travel'; Premium = $true; Severity = 'Medium' + About = 'Microsoft Defender for Cloud Apps saw activity from distant locations within a time shorter than the travel time between them.' } + @{ Id = 'maliciousIPAddress'; Name = 'Malicious IP address'; Premium = $true; Severity = 'Medium' + About = 'The user signed in from an IP address with a high rate of failed sign-ins or a bad reputation.' + Tips = "$investigate#malicious-ip-address-detections" } + @{ Id = 'mcasFinSuspiciousFileAccess'; Name = 'Mass access to sensitive files'; Premium = $true; Severity = 'Medium' + About = 'Microsoft Defender for Cloud Apps saw the user access an unusual number of possibly sensitive files in SharePoint or OneDrive.' } + @{ Id = 'investigationsThreatIntelligence'; Name = 'Microsoft Entra threat intelligence'; Premium = $false; Severity = 'High' + About = "The user's activity matches attack patterns known to Microsoft threat intelligence." + Tips = "$investigate#microsoft-entra-threat-intelligence" } + @{ Id = 'newCountry'; Name = 'New country'; Premium = $true; Severity = 'Low' + About = 'Microsoft Defender for Cloud Apps saw activity from a country new or infrequent for the organization.' } + @{ Id = 'passwordSpray'; Name = 'Password spray'; Premium = $true; Severity = 'High' + About = "A password spray attack correctly guessed the user's password." + Tips = "$investigate#password-spray-detections" } + @{ Id = 'suspiciousBrowser'; Name = 'Suspicious browser'; Premium = $true; Severity = 'Medium' + About = 'The same browser was used for suspicious sign-ins across several tenants from different countries.' + Tips = "$investigate#suspicious-browser-detections" } + @{ Id = 'suspiciousInboxForwarding'; Name = 'Suspicious inbox forwarding'; Premium = $true; Severity = 'Medium' + About = "Microsoft Defender for Cloud Apps found a suspicious forwarding rule on the user's mailbox, such as one that copies all mail to an external address." } + @{ Id = 'mcasSuspiciousInboxManipulationRules'; Name = 'Suspicious inbox manipulation rules'; Premium = $true; Severity = 'Medium' + About = "Microsoft Defender for Cloud Apps found suspicious rules that delete or move messages in the user's mailbox." } + @{ Id = 'tokenIssuerAnomaly'; Name = 'Token issuer anomaly'; Premium = $true; Severity = 'High' + About = 'A SAML token has unusual claims or claims that match known attacker patterns, which suggests the token issuer may be compromised.' + Tips = "$investigate#anomalous-token-and-token-issuer-anomaly-detections" } + @{ Id = 'unfamiliarFeatures'; Name = 'Unfamiliar sign-in properties'; Premium = $true; Severity = 'Medium' + About = 'A sign-in had properties, such as IP address, ASN, location, device or browser, that are unfamiliar for the user.' } + @{ Id = 'nationStateIP'; Name = 'Verified threat actor IP'; Premium = $true; Severity = 'High' + About = 'The user signed in from an IP address that Microsoft threat intelligence ties to a nation-state actor or cybercrime group.' } + @{ Id = 'anomalousUserActivity'; Name = 'Anomalous user activity'; Premium = $true; Severity = 'Medium' + About = 'The user made directory changes that differ from their usual administrative behaviour.' } + @{ Id = 'attackerinTheMiddle'; Name = 'Attacker in the middle'; Premium = $true; Severity = 'High' + About = "The user's sign-in session went through a malicious reverse proxy, which can capture the password and the session token." + } + @{ Id = 'leakedCredentials'; Name = 'Leaked credentials'; Premium = $false; Severity = 'High' + About = "The user's current, valid password was found in a known credential leak." + Tips = "$investigate#leaked-credentials-detections" } + @{ Id = 'attemptedPrtAccess'; Name = 'Possible attempt to access Primary Refresh Token (PRT)'; Premium = $true; Severity = 'High' + About = "Microsoft Defender for Endpoint saw an attempt to read the user's Primary Refresh Token on a device." } + @{ Id = 'suspiciousAPITraffic'; Name = 'Suspicious API traffic'; Premium = $true; Severity = 'Medium' + About = 'The user made unusual Microsoft Graph calls or enumerated the directory, which can be reconnaissance by an attacker.' } + @{ Id = 'suspiciousCredentialAddition'; Name = 'Suspicious credential addition'; Premium = $true; Severity = 'High' + About = 'A new authentication method was registered on the account in suspicious circumstances. An attacker who registers a method keeps access after a password reset.' } + @{ Id = 'suspiciousSendingPatterns'; Name = 'Suspicious sending patterns'; Premium = $true; Severity = 'Medium' + About = 'Microsoft Defender for Office 365 saw the user send suspicious email, and the user is at risk of being, or has been, restricted from sending.' } + @{ Id = 'userReportedSuspiciousActivity'; Name = 'User reported suspicious activity'; Premium = $true; Severity = 'Medium' + About = 'The user denied an MFA prompt they did not start and reported it as suspicious, which means someone else may have their password.' } + ) + + $known = @{} + foreach ($entry in $catalog) { + $known[$entry.Id] = $true + if (-not $entry.ContainsKey('Tips')) { $entry.Tips = $investigate } + [pscustomobject]@{ + Id = $entry.Id + Title = "Open '$($entry.Name)' 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-MtUserRiskDetection | ForEach-Object { [string]$_.riskEventType } | Where-Object { $_ } | Sort-Object -Unique) + } catch { + Write-Verbose "MT.1273: 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' risk detections should be reviewed in Entra ID Protection." + Severity = 'Medium' + Data = [pscustomobject]@{ + Id = $type + Name = $type + Premium = $false + 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-MtEntraUserRiskDetection { + <# + .SYNOPSIS + Checks that no Entra ID Protection user risk detection of a given type is left open. + + .DESCRIPTION + Runs once per sign-in and user risk detection type (identityProtection/riskDetections). 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, + dismissed or confirmed safe pass. Rows for detection types that need Microsoft Entra ID P2 are + skipped in tenants without it, because such tenants see those detections only as Additional risk + detected. The check reads risk only and never changes it. + + .EXAMPLE + Invoke-MtTest -Id MT.1273 + + .LINK + https://maester.dev/docs/tests/MT.1273 + + .LINK + https://learn.microsoft.com/entra/id-protection/concept-identity-protection-risks + #> + [MaesterTest( + Id = 'MT.1273', + Title = 'Open Entra ID Protection user risk detections should be reviewed.', + Product = 'entra', + Feature = 'identity-protection', + Area = 'logging-and-detection', + ResourceType = 'User', + Severity = 'Medium', + UserImpact = 'Low', + ImplementationCost = 'Low', + Mitre = ('T1078.004', 'T1110.003', 'T1557', 'T1098.005', 'T1114.003'), + Control = ('nist-800-53-r5:IR-4', 'nist-800-53-r5:AC-2(12)'), + Service = 'Graph', + License = 'AAD_PREMIUM', + Permission = 'Graph:Scope:IdentityRiskEvent.Read.All', + InstanceSource = 'Get-MtUserRiskDetectionInstance', + Lifecycle = 'Preview', + Author = 'merill' + )] + [CmdletBinding()] + [OutputType([bool])] + param( + # The detection type to check, supplied by the engine. + $Instance + ) + + # Rows shown in the result table. A tenant can have thousands of detections of a noisy type. + $MaxRows = 100 + + $type = $Instance.Data + $severity = $Instance.Severity + $name = Get-MtSafeMarkdown ([string]$type.Name) + $about = "**$name** ($([string]$type.Id)): $($type.About) [Investigation tips]($($type.Tips))" + + if ($type.Premium -and (Get-MtLicenseInformation -Product 'EntraID') -ne 'P2') { + Add-MtTestResultDetail -Severity $severity -SkippedBecause NotLicensedEntraIDP2 + return $null + } + + try { + $detections = @(Get-MtUserRiskDetection) + } 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.1273: $($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' 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' risk detection(s): $(@($counts) -join ', ').`n`n$about" + $result += "`n`n| User | User principal name | Risk level | Risk state | Detected (UTC) | Activity | IP address | Location |" + $result += "`n| --- | --- | --- | --- | --- | --- | --- | --- |" + foreach ($item in @($sorted | Select-Object -First $MaxRows)) { + $displayName = [string]$item.userDisplayName + if ([string]::IsNullOrWhiteSpace($displayName)) { $displayName = '(unnamed)' } + $detected = if ($item.detectedDateTime) { + ($item.detectedDateTime -as [datetime]).ToUniversalTime().ToString('yyyy-MM-dd HH:mm') + } else { 'Unknown' } + $location = @($item.location.city, $item.location.countryOrRegion | Where-Object { $_ }) -join ', ' + $cells = @( + $displayName + [string]$item.userPrincipalName + [string]$item.riskLevel + [string]$item.riskState + $detected + [string]$item.activity + [string]$item.ipAddress + $location + ) | 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** in the Microsoft Entra admin center for the rest." + } + + Add-MtTestResultDetail -Severity $severity -Result $result + return $false +}