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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions powershell/internal/services/entra/Get-MtUserRiskDetection.ps1
Original file line number Diff line number Diff line change
@@ -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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand All @@ -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": [
Expand Down
9 changes: 6 additions & 3 deletions powershell/tests/fixtures/golden/selection.json
Original file line number Diff line number Diff line change
Expand Up @@ -1921,7 +1921,7 @@
"AD"
]
},
"SelectedCount": 590,
"SelectedCount": 591,
"SelectedFamilies": [
"MT.1024",
"MT.1059",
Expand Down Expand Up @@ -2451,6 +2451,7 @@
"MT.1259",
"MT.1260",
"MT.1265",
"MT.1273",
"ORCA.100",
"ORCA.101",
"ORCA.102",
Expand Down Expand Up @@ -2532,7 +2533,7 @@
"AD"
]
},
"SelectedCount": 620,
"SelectedCount": 621,
"SelectedFamilies": [
"MT.1024",
"MT.1033",
Expand Down Expand Up @@ -3094,6 +3095,7 @@
"MT.1259",
"MT.1260",
"MT.1265",
"MT.1273",
"ORCA.100",
"ORCA.101",
"ORCA.102",
Expand Down Expand Up @@ -3928,7 +3930,7 @@
"AD"
]
},
"SelectedCount": 576,
"SelectedCount": 577,
"SelectedFamilies": [
"MT.1024",
"MT.1033",
Expand Down Expand Up @@ -4446,6 +4448,7 @@
"MT.1259",
"MT.1260",
"MT.1265",
"MT.1273",
"ORCA.100",
"ORCA.101",
"ORCA.102",
Expand Down
193 changes: 193 additions & 0 deletions powershell/tests/functions/Test-MtEntraUserRiskDetection.Tests.ps1
Original file line number Diff line number Diff line change
@@ -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 '(?<!\\)\[Sign in again\]\('
}
}

Context 'Data access' {
It 'reads the two open risk states from the v1.0 endpoint' {
InModuleScope Maester {
Mock Invoke-MtGraphRequest { return @() }
Get-MtUserRiskDetection | Should -BeNullOrEmpty
Should -Invoke Invoke-MtGraphRequest -Exactly -Times 2
Should -Invoke Invoke-MtGraphRequest -Exactly -Times 1 -ParameterFilter {
$ApiVersion -eq 'v1.0' -and $RelativeUri -eq 'identityProtection/riskDetections' -and $Filter -eq "riskState eq 'atRisk'"
}
Should -Invoke Invoke-MtGraphRequest -Exactly -Times 1 -ParameterFilter {
$Filter -eq "riskState eq 'confirmedCompromised'"
}
}
}
}
}
1 change: 1 addition & 0 deletions powershell/tests/general/NativeTestLint.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ Describe 'Native built-in tests' {
# instances need a premium licence) keep their own check.
$allowed = @(
'MT.1024' # Entra recommendations: only the premium recommendation instances need Entra ID P2.
'MT.1273' # User risk detections: only the premium detection types need Entra ID P2.
)
$problems = foreach ($f in $script:files | Where-Object Function) {
if ($f.Test.Id -in $allowed) { continue }
Expand Down
34 changes: 34 additions & 0 deletions tests/maester/entra/Test.MT.1273.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
Open Entra ID Protection user risk detections should be reviewed.

Entra ID Protection raises a risk detection for each suspicious sign-in or account event it sees: a password guessed in a password spray, a sign-in through an attacker-in-the-middle proxy, a password found in a leak, an authentication method registered by someone who is not the user, a mailbox rule that forwards mail outside the organization, and more. Each detection stays open (**atRisk**) until someone remediates it, dismisses it or confirms it safe. Open detections that nobody reviews are signs of compromise that nobody is acting on, and Graph only keeps them for 90 days.

Maester creates one result per detection type (MT.1273.&lt;riskEventType&gt;), so the report shows which kinds of signal are waiting. A result fails when at least one detection of its type 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. Each result starts with a short explanation of its detection type and a link to Microsoft's investigation tips. The severity of each result reflects how strong a sign of compromise that detection type is.

Detection types that need Microsoft Entra ID P2 are skipped in tenants without it; those tenants see such detections as **Additional risk detected** (generic). Detection types that come from Microsoft Defender for Cloud Apps, Defender for Endpoint or Defender for Office 365 only fire when the tenant uses those products, and otherwise pass. A detection type that Microsoft adds later, and that Maester does not know yet, gets a result of its own when it has open detections.

This check reads the detections behind the risk. MT.1260 reports the users that are high risk and unremediated; the two complement each other.

The check reads identityProtection/riskDetections with the Microsoft Graph permission IdentityRiskEvent.Read.All, which Maester requests by default. It never changes a user's risk.

#### Remediation action

The security operations team should review every open detection and close it one way or the other.

1. Open the [Microsoft Entra admin center](https://entra.microsoft.com) and go to **ID Protection** > **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)

<!--- Results --->
%TestResult%
Loading
Loading