diff --git a/powershell/internal/services/entra/Get-MtPrincipalPrivilegedRole.ps1 b/powershell/internal/services/entra/Get-MtPrincipalPrivilegedRole.ps1 new file mode 100644 index 0000000000..321321543b --- /dev/null +++ b/powershell/internal/services/entra/Get-MtPrincipalPrivilegedRole.ps1 @@ -0,0 +1,78 @@ +function Get-MtPrincipalPrivilegedRole { + <# + .SYNOPSIS + Returns the privileged directory roles held by the given principals. + + .DESCRIPTION + Shared by the Entra ID Protection risk checks (MT.1260 to MT.1263) so the privileged-role lookup lives in one place. + + For each principal ID passed in, returns the display names of the privileged directory roles assigned to it, + active or PIM-eligible. Eligible roles get ' (eligible)' after the name. A role counts as privileged when + Maester's role catalog (Get-MtRoleInfo) marks it IsPrivileged, as MT.1210 does. + + Only direct assignments are matched. A role held through a role-assignable group is not returned yet. + + The scope of an assignment (directoryScopeId) is not checked, so a role scoped to an administrative unit counts + the same as a tenant-wide one. MT.1210 treats scope the same way. + + The result has two properties: RolesByPrincipal, a hashtable from principal ID to a list of role names (only + principals that hold a privileged role are present), and EligibleChecked, which is true when PIM-eligible + assignments were read (they need Microsoft Entra ID P2 or Governance). + + Errors reading role definitions or assignments are not caught, so the caller can report that privileged + principals could not be identified. + + .EXAMPLE + $privileged = Get-MtPrincipalPrivilegedRole -PrincipalId $riskyUsers.id + $privileged.RolesByPrincipal[$user.id] + + Returns the privileged roles held by each risky user. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + # Object IDs of the users or service principals to look up. + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [string[]] $PrincipalId + ) + + $wanted = @{} + foreach ($id in $PrincipalId) { + if (-not [string]::IsNullOrWhiteSpace($id)) { $wanted[[string]$id] = $true } + } + + $roleDefinitions = @( + Invoke-MtGraphRequest -ApiVersion 'v1.0' ` + -RelativeUri 'roleManagement/directory/roleDefinitions' ` + -Select @('id', 'displayName') + ) + $roleDefinitionById = @{} + foreach ($definition in $roleDefinitions) { $roleDefinitionById[[string]$definition.id] = $definition } + + # Same properties as MT.1209 and MT.1210 so the active assignments come from the Graph cache. + $assignmentResult = Get-MtDirectoryRoleAssignment -Select @('id', 'principalId', 'roleDefinitionId', 'directoryScopeId') + + $rolesByPrincipal = @{} + foreach ($assignment in @($assignmentResult.Assignments)) { + $principal = [string]$assignment.principalId + if (-not $wanted.ContainsKey($principal)) { continue } + # directoryScopeId is not checked: an administrative-unit-scoped role counts as tenant-wide, as in MT.1210. + $definition = $roleDefinitionById[[string]$assignment.roleDefinitionId] + if ($null -eq $definition) { continue } + # isPrivileged is not queryable on roleDefinitions; use Maester's role catalog, as MT.1210 does. + $roleInfo = Get-MtRoleInfo -RoleName ([string]$definition.displayName -replace '\s', '') + if ($null -eq $roleInfo -or -not $roleInfo.IsPrivileged) { continue } + $roleName = [string]$definition.displayName + if ($assignment.AssignmentType -eq 'Eligible') { $roleName += ' (eligible)' } + if (-not $rolesByPrincipal.ContainsKey($principal)) { + $rolesByPrincipal[$principal] = [System.Collections.Generic.List[string]]::new() + } + $rolesByPrincipal[$principal].Add($roleName) + } + + [pscustomobject]@{ + RolesByPrincipal = $rolesByPrincipal + EligibleChecked = [bool]$assignmentResult.EligibleChecked + } +} diff --git a/powershell/tests/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index ae970e7cfd..734d897092 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.1261", "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.1261", "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.1261", "MT.1265", "ORCA.100", "ORCA.101", diff --git a/powershell/tests/functions/Get-MtPrincipalPrivilegedRole.Tests.ps1 b/powershell/tests/functions/Get-MtPrincipalPrivilegedRole.Tests.ps1 new file mode 100644 index 0000000000..3c12cb3def --- /dev/null +++ b/powershell/tests/functions/Get-MtPrincipalPrivilegedRole.Tests.ps1 @@ -0,0 +1,92 @@ +BeforeAll { + Import-Module $PSScriptRoot/../../Maester.psd1 -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name Get-MtPrincipalPrivilegedRole +} + +Describe 'Get-MtPrincipalPrivilegedRole' -Tag 'Unit' { + 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 Get-MtRoleInfo { + return [pscustomobject]@{ IsPrivileged = ($RoleName -eq 'GlobalAdministrator') } + } + } + + It 'returns an active privileged role held by a requested principal' { + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { + return [pscustomobject]@{ + Assignments = @([pscustomobject]@{ principalId = 'p-1'; roleDefinitionId = 'role-ga'; AssignmentType = 'Active' }) + EligibleChecked = $true + } + } + + $result = Get-MtPrincipalPrivilegedRole -PrincipalId 'p-1' + + @($result.RolesByPrincipal['p-1']) | Should -Be @('Global Administrator') + $result.EligibleChecked | Should -BeTrue + } + + It 'marks a PIM-eligible privileged role as eligible' { + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { + return [pscustomobject]@{ + Assignments = @([pscustomobject]@{ principalId = 'p-1'; roleDefinitionId = 'role-ga'; AssignmentType = 'Eligible' }) + EligibleChecked = $true + } + } + + $result = Get-MtPrincipalPrivilegedRole -PrincipalId 'p-1' + + @($result.RolesByPrincipal['p-1']) | Should -Be @('Global Administrator (eligible)') + } + + It 'ignores principals that were not requested, even when they hold a privileged role' { + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { + return [pscustomobject]@{ + Assignments = @( + [pscustomobject]@{ principalId = 'p-1'; roleDefinitionId = 'role-ga'; AssignmentType = 'Active' }, + [pscustomobject]@{ principalId = 'someone-else'; roleDefinitionId = 'role-ga'; AssignmentType = 'Active' } + ) + EligibleChecked = $true + } + } + + $result = Get-MtPrincipalPrivilegedRole -PrincipalId 'p-1' + + @($result.RolesByPrincipal.Keys) | Should -Be @('p-1') + } + + It 'ignores a role that is not privileged' { + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { + return [pscustomobject]@{ + Assignments = @([pscustomobject]@{ principalId = 'p-1'; roleDefinitionId = 'role-dr'; AssignmentType = 'Active' }) + EligibleChecked = $true + } + } + + $result = Get-MtPrincipalPrivilegedRole -PrincipalId 'p-1' + + $result.RolesByPrincipal.Count | Should -Be 0 + } + + It 'reports when PIM-eligible assignments were not checked' { + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { + return [pscustomobject]@{ Assignments = @(); EligibleChecked = $false } + } + + $result = Get-MtPrincipalPrivilegedRole -PrincipalId 'p-1' + + $result.EligibleChecked | Should -BeFalse + } + + It 'lets a failure to read role assignments throw, so the caller can report it' { + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { throw '403 Forbidden' } + + { Get-MtPrincipalPrivilegedRole -PrincipalId 'p-1' } | Should -Throw '*403*' + } +} diff --git a/powershell/tests/functions/Test-MtEntraUnremediatedHighRiskUser.Tests.ps1 b/powershell/tests/functions/Test-MtEntraUnremediatedHighRiskUser.Tests.ps1 index f98f9d470c..2d819b766f 100644 --- a/powershell/tests/functions/Test-MtEntraUnremediatedHighRiskUser.Tests.ps1 +++ b/powershell/tests/functions/Test-MtEntraUnremediatedHighRiskUser.Tests.ps1 @@ -11,15 +11,19 @@ $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 Add-MtTestResultDetail { - param($Result, $SkippedBecause, $SkippedError, $Severity) + 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. @@ -157,6 +161,52 @@ $script:TestResult | Should -Match 'Found 1 high-risk' } + It 'does not report a deleted user, who cannot sign in and leaves nothing to act on' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'user-5'; isDeleted = $true; userPrincipalName = 'erin@contoso.com'; userDisplayName = 'Erin' + riskLevel = 'high'; riskState = 'atRisk'; riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-05T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedHighRiskUser | Should -BeTrue + $script:TestResult | Should -Match 'Well done' + } + + It 'passes the unremediated users to the report as affected objects' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'user-1'; userPrincipalName = 'alice@contoso.com'; userDisplayName = 'Alice' + riskLevel = 'high'; riskState = 'atRisk'; riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-01T00:00:00Z' + }, + [pscustomobject]@{ + id = 'user-2'; userPrincipalName = 'bob@contoso.com'; userDisplayName = 'Bob' + riskLevel = 'high'; riskState = 'confirmedCompromised'; riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-02T00:00:00Z' + } + ) + } -ParameterFilter { $RelativeUri -eq 'identityProtection/riskyUsers' } + + Test-MtEntraUnremediatedHighRiskUser | Should -BeFalse + $script:GraphObjectType | Should -Be 'IdentityProtection' + @($script:GraphObjects).Count | Should -Be 2 + @($script:GraphObjects.id) | Should -Be @('user-1', 'user-2') + @($script:GraphObjects.displayName) | Should -Be @('Alice', 'Bob') + @($script:GraphObjects.userPrincipalName) | Should -Be @('alice@contoso.com', 'bob@contoso.com') + } + + It 'passes no affected objects when no user is left unremediated' { + Mock -ModuleName Maester Invoke-MtGraphRequest { return @() } -ParameterFilter { $RelativeUri -eq 'identityProtection/riskyUsers' } + + Test-MtEntraUnremediatedHighRiskUser | 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' } @@ -215,6 +265,9 @@ # The privileged user is listed first. # Matched as a regex rather than IndexOf, so the position is found whether or not the # escaping helper put a backslash before the @. + # Both users must be present first; a missing match returns Index 0 and would pass the order check. + $script:TestResult | Should -Match 'bob\\?@contoso\.com' + $script:TestResult | Should -Match 'alice\\?@contoso\.com' [regex]::Match($script:TestResult, 'bob\\?@contoso\.com').Index | Should -BeLessThan ([regex]::Match($script:TestResult, 'alice\\?@contoso\.com').Index) } diff --git a/powershell/tests/functions/Test-MtEntraUnremediatedMediumRiskUser.Tests.ps1 b/powershell/tests/functions/Test-MtEntraUnremediatedMediumRiskUser.Tests.ps1 new file mode 100644 index 0000000000..fc860d599e --- /dev/null +++ b/powershell/tests/functions/Test-MtEntraUnremediatedMediumRiskUser.Tests.ps1 @@ -0,0 +1,311 @@ +Describe 'Entra ID Protection unremediated medium-risk users (MT.1261)' { + BeforeAll { + Import-Module $PSScriptRoot/../../Maester.psd1 -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name Test-MtEntraUnremediatedMediumRiskUser + } + + 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 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 + } + + Mock -ModuleName Maester Invoke-MtGraphRequest { return @() } -ParameterFilter { + $RelativeUri -eq 'roleManagement/directory/roleDefinitions' + } + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { + return [pscustomobject]@{ Assignments = @(); EligibleChecked = $true } + } + } + + AfterEach { + if ($null -ne $script:TestResult) { + $script:TestResult | Should -Not -Match '`[^`]+`' + } + } + + It 'passes when there are no medium-risk users' { + Mock -ModuleName Maester Invoke-MtGraphRequest { return @() } + + Test-MtEntraUnremediatedMediumRiskUser | Should -BeTrue + $script:TestResult | Should -Match 'Well done' + # The medium-risk filter is what separates this check from MT.1260. + Should -Invoke Invoke-MtGraphRequest -ModuleName Maester -Exactly -Times 1 -ParameterFilter { + $ApiVersion -eq 'v1.0' -and + $RelativeUri -eq 'identityProtection/riskyUsers' -and + $Filter -eq "riskLevel eq 'medium'" + } + Should -Invoke Get-MtDirectoryRoleAssignment -ModuleName Maester -Exactly -Times 0 + } + + It 'fails when a medium-risk user is atRisk' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'user-1' + userPrincipalName = 'alice@contoso.com' + userDisplayName = 'Alice' + riskLevel = 'medium' + riskState = 'atRisk' + riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-01T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedMediumRiskUser | Should -BeFalse + $script:TestResult | Should -Match 'alice\\?@contoso\.com' + $script:TestResult | Should -Match 'atRisk' + } + + It 'escapes a tenant-controlled display name so it cannot render as a link' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'user-1' + userPrincipalName = 'alice@contoso.com' + userDisplayName = '[Sign in again](https://phish.example)' + riskLevel = 'medium' + riskState = 'atRisk' + riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-01T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedMediumRiskUser | Should -BeFalse + $script:TestResult | Should -Not -Match '\| \[Sign in again\]\(' + $script:TestResult | Should -Match ([regex]::Escape('\[Sign in again\]\(https\://phish.example\)')) + } + + It 'fails when a medium-risk user is confirmedCompromised (must not be treated as remediated)' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'user-2' + userPrincipalName = 'bob@contoso.com' + userDisplayName = 'Bob' + riskLevel = 'medium' + riskState = 'confirmedCompromised' + riskDetail = 'adminConfirmedUserCompromised' + riskLastUpdatedDateTime = '2026-10-02T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedMediumRiskUser | Should -BeFalse + $script:TestResult | Should -Match 'bob\\?@contoso\.com' + $script:TestResult | Should -Match 'confirmedCompromised' + } + + It 'passes when the only medium-risk users are already remediated or dismissed' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'user-3'; userPrincipalName = 'carol@contoso.com'; userDisplayName = 'Carol' + riskLevel = 'medium'; riskState = 'remediated'; riskDetail = 'userPerformedSecuredPasswordReset' + riskLastUpdatedDateTime = '2026-10-03T00:00:00Z' + }, + [pscustomobject]@{ + id = 'user-4'; userPrincipalName = 'dave@contoso.com'; userDisplayName = 'Dave' + riskLevel = 'medium'; riskState = 'dismissed'; riskDetail = 'adminDismissedAllRiskForUser' + riskLastUpdatedDateTime = '2026-10-04T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedMediumRiskUser | Should -BeTrue + $script:TestResult | Should -Match 'Well done' + } + + It 'reports only the unremediated users in a mixed set' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'user-1'; userPrincipalName = 'alice@contoso.com'; userDisplayName = 'Alice' + riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-01T00:00:00Z' + }, + [pscustomobject]@{ + id = 'user-3'; userPrincipalName = 'carol@contoso.com'; userDisplayName = 'Carol' + riskLevel = 'medium'; riskState = 'remediated'; riskDetail = 'userPerformedSecuredPasswordReset' + riskLastUpdatedDateTime = '2026-10-03T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedMediumRiskUser | Should -BeFalse + $script:TestResult | Should -Match 'alice\\?@contoso\.com' + $script:TestResult | Should -Not -Match 'carol\\?@contoso\.com' + $script:TestResult | Should -Match 'Found 1 medium-risk' + } + + It 'does not report a deleted user, who cannot sign in and leaves nothing to act on' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'user-5'; isDeleted = $true; userPrincipalName = 'erin@contoso.com'; userDisplayName = 'Erin' + riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-05T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedMediumRiskUser | Should -BeTrue + $script:TestResult | Should -Match 'Well done' + } + + It 'passes the unremediated users to the report as affected objects' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'user-1'; userPrincipalName = 'alice@contoso.com'; userDisplayName = 'Alice' + riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-01T00:00:00Z' + }, + [pscustomobject]@{ + id = 'user-2'; userPrincipalName = 'bob@contoso.com'; userDisplayName = 'Bob' + riskLevel = 'medium'; riskState = 'confirmedCompromised'; riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-02T00:00:00Z' + } + ) + } -ParameterFilter { $RelativeUri -eq 'identityProtection/riskyUsers' } + + Test-MtEntraUnremediatedMediumRiskUser | Should -BeFalse + $script:GraphObjectType | Should -Be 'IdentityProtection' + @($script:GraphObjects).Count | Should -Be 2 + @($script:GraphObjects.id) | Should -Be @('user-1', 'user-2') + @($script:GraphObjects.displayName) | Should -Be @('Alice', 'Bob') + @($script:GraphObjects.userPrincipalName) | Should -Be @('alice@contoso.com', 'bob@contoso.com') + } + + It 'passes no affected objects when no user is left unremediated' { + Mock -ModuleName Maester Invoke-MtGraphRequest { return @() } -ParameterFilter { $RelativeUri -eq 'identityProtection/riskyUsers' } + + Test-MtEntraUnremediatedMediumRiskUser | 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-MtEntraUnremediatedMediumRiskUser | 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-MtEntraUnremediatedMediumRiskUser } | Should -Throw '*Service unavailable*' + } + + Context 'Privileged users 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 = 'user-1'; userPrincipalName = 'alice@contoso.com'; userDisplayName = 'Alice' + riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-01T00:00:00Z' + }, + [pscustomobject]@{ + id = 'user-2'; userPrincipalName = 'bob@contoso.com'; userDisplayName = 'Bob' + riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastUpdatedDateTime = '2026-10-02T00:00:00Z' + } + ) + } -ParameterFilter { $RelativeUri -eq 'identityProtection/riskyUsers' } + + Mock -ModuleName Maester Get-MtRoleInfo { + return [pscustomobject]@{ IsPrivileged = ($RoleName -eq 'GlobalAdministrator') } + } + } + + It 'lists the role first when an at-risk user holds a privileged role' { + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { + return [pscustomobject]@{ + Assignments = @([pscustomobject]@{ principalId = 'user-2'; roleDefinitionId = 'role-ga'; AssignmentType = 'Active' }) + EligibleChecked = $true + } + } + + Test-MtEntraUnremediatedMediumRiskUser | Should -BeFalse + $script:Severity | Should -BeNullOrEmpty + $script:TestResult | Should -Match 'Global Administrator' + $script:TestResult | Should -Match '1 of them hold a privileged directory role' + # Matched as a regex rather than IndexOf, so the position is found whether or not the + # escaping helper put a backslash before the @. + # Both users must be present first; a missing match returns Index 0 and would pass the order check. + $script:TestResult | Should -Match 'bob\\?@contoso\.com' + $script:TestResult | Should -Match 'alice\\?@contoso\.com' + [regex]::Match($script:TestResult, 'bob\\?@contoso\.com').Index | + Should -BeLessThan ([regex]::Match($script:TestResult, 'alice\\?@contoso\.com').Index) + } + + It 'treats a PIM-eligible privileged role as privileged' { + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { + return [pscustomobject]@{ + Assignments = @([pscustomobject]@{ principalId = 'user-1'; roleDefinitionId = 'role-ga'; AssignmentType = 'Eligible' }) + EligibleChecked = $true + } + } + + Test-MtEntraUnremediatedMediumRiskUser | 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 = 'user-1'; roleDefinitionId = 'role-dr'; AssignmentType = 'Active' }) + EligibleChecked = $true + } + } + + Test-MtEntraUnremediatedMediumRiskUser | 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-MtEntraUnremediatedMediumRiskUser | Should -BeFalse + $script:TestResult | Should -Match 'PIM-eligible role assignments were not checked' + } + + It 'still reports the users when role assignments cannot be read' { + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { throw 'Forbidden' } + + Test-MtEntraUnremediatedMediumRiskUser | Should -BeFalse + $script:TestResult | Should -Match 'alice\\?@contoso\.com' + $script:TestResult | Should -Match 'privileged users were not identified' + $script:Severity | Should -BeNullOrEmpty + } + } +} diff --git a/tests/maester/entra/Test.MT.1260.md b/tests/maester/entra/Test.MT.1260.md index 3d94ff2ab7..c8ea1e83f8 100644 --- a/tests/maester/entra/Test.MT.1260.md +++ b/tests/maester/entra/Test.MT.1260.md @@ -8,7 +8,7 @@ If a reported user holds a privileged directory role, active or PIM-eligible, th The check needs the Microsoft Graph permission `IdentityRiskyUser.Read.All`, which Maester does not request by default. Without it the check is skipped. Connect with `Connect-Maester -IncludePreview`, or grant the permission to the app registration that runs Maester. -A companion check, MT.1261, is planned to report on medium-risk users. This check is about the outcome (users actually left unremediated). It is complementary to MT.1253, which checks that a Conditional Access policy requiring risk remediation is in place; one checks the control, this one checks the result. +A companion check, MT.1261, reports on medium-risk users. This check is about the outcome (users actually left unremediated). It is complementary to MT.1253, which checks that a Conditional Access policy requiring risk remediation is in place; one checks the control, this one checks the result. #### Remediation action diff --git a/tests/maester/entra/Test.MT.1260.ps1 b/tests/maester/entra/Test.MT.1260.ps1 index 51c863322a..21d20ae116 100644 --- a/tests/maester/entra/Test.MT.1260.ps1 +++ b/tests/maester/entra/Test.MT.1260.ps1 @@ -28,9 +28,10 @@ ImplementationCost = 'Low', 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_PREMIUM_P2', - Permission = 'Graph:Scope:IdentityRiskyUser.Read.All', + Permission = ('Graph:Scope:IdentityRiskyUser.Read.All', 'Graph:Scope:RoleManagement.Read.Directory|Graph:Scope:RoleManagement.Read.All'), Lifecycle = 'Preview', Author = 'Dfrank77' )] @@ -38,6 +39,7 @@ [OutputType([bool])] param() + # Deleted users can stay in the risk report, but a deleted account cannot sign in and leaves nothing to act on, so it is not reported. # Active, unremediated risk states. A flag an admin has handled moves to 'remediated', # 'dismissed', 'confirmedSafe' or 'none'; those are intentionally excluded. # 'confirmedCompromised' MUST be treated as unremediated alongside 'atRisk' -- confirming a @@ -54,7 +56,7 @@ Invoke-MtGraphRequest -ApiVersion 'v1.0' ` -RelativeUri 'identityProtection/riskyUsers' ` -Filter "riskLevel eq 'high'" ` - -Select @('id', 'userPrincipalName', 'userDisplayName', 'riskLevel', 'riskState', 'riskDetail', 'riskLastUpdatedDateTime') + -Select @('id', 'isDeleted', 'userPrincipalName', 'userDisplayName', 'riskLevel', 'riskState', 'riskDetail', 'riskLastUpdatedDateTime') ) } catch { if ($_.Exception.Message -match '(?i)403|forbidden|authorization') { @@ -65,7 +67,7 @@ } $Unremediated = @( - $HighRiskUsers | Where-Object { $UnremediatedStates -contains [string]$_.riskState } + $HighRiskUsers | Where-Object { $UnremediatedStates -contains [string]$_.riskState -and $_.isDeleted -ne $true } ) Write-Verbose "Found $($HighRiskUsers.Count) high-risk user(s); $($Unremediated.Count) unremediated." @@ -82,39 +84,12 @@ $PrivilegedRolesByUser = @{} $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 and MT.1210 so the active assignments come from the Graph cache. - $RoleAssignmentResult = Get-MtDirectoryRoleAssignment -Select @('id', 'principalId', 'roleDefinitionId', 'directoryScopeId') - if (!$RoleAssignmentResult.EligibleChecked) { + $PrivilegedResult = Get-MtPrincipalPrivilegedRole -PrincipalId @($Unremediated | ForEach-Object { [string]$_.id }) + $PrivilegedRolesByUser = $PrivilegedResult.RolesByPrincipal + if (!$PrivilegedResult.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 } - # isPrivileged is not queryable on roleDefinitions; use Maester's role catalog, as MT.1210 does. - $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 (!$PrivilegedRolesByUser.ContainsKey($PrincipalId)) { - $PrivilegedRolesByUser[$PrincipalId] = [System.Collections.Generic.List[string]]::new() - } - $PrivilegedRolesByUser[$PrincipalId].Add($RoleName) - } } catch { Write-Verbose "Could not read directory role assignments: $($_.Exception.Message)" $PrivilegedRolesByUser = @{} @@ -150,6 +125,12 @@ } $Result += $RoleNote - Add-MtTestResultDetail -Result $Result + # Each risky user also appears on the report's Affected objects page; the table above stays as it is. + $AffectedUsers = @( + $Sorted | ForEach-Object { + [pscustomobject]@{ id = [string]$_.id; displayName = [string]$_.userDisplayName; userPrincipalName = [string]$_.userPrincipalName } + } + ) + Add-MtTestResultDetail -Result $Result -GraphObjects $AffectedUsers -GraphObjectType IdentityProtection return $false } diff --git a/tests/maester/entra/Test.MT.1261.md b/tests/maester/entra/Test.MT.1261.md new file mode 100644 index 0000000000..3ddfd5aa48 --- /dev/null +++ b/tests/maester/entra/Test.MT.1261.md @@ -0,0 +1,30 @@ +Medium-risk users should not be left unremediated in Entra ID Protection. + +Entra ID Protection rates a user's risk and tracks a risk state for each flagged user. A medium-risk flag only clears when the risk is remediated, for example by a password reset, or when an admin dismisses it or confirms the user safe. Until then the signals that triggered the flag have not been addressed. Dismissing a flag clears it but does not change the user's password, so investigate first. + +This check reports users whose risk level is **medium** 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. Deleted users are not reported either: they can stay in the risk report, but a deleted account cannot sign in and leaves nothing to remediate. The check reads risk only and never changes a user's risk state. + +If a reported user holds a privileged directory role, active or PIM-eligible, the result lists the role and shows that entry first, since even a medium-risk flag on an admin account warrants prompt investigation. + +The check needs the Microsoft Graph permission `IdentityRiskyUser.Read.All`, which Maester does not request by default. Without it the check is skipped. To identify privileged users, it also reads directory roles, which needs `RoleManagement.Read.Directory` or `RoleManagement.Read.All`. If those reads fail, the users are still reported with a note. Connect with `Connect-Maester -IncludePreview`, or grant the permission to the app registration that runs Maester. + +A companion check, MT.1260, reports on high-risk users. This check is about the outcome (users actually left unremediated). It is complementary to MT.1253, which checks that a Conditional Access policy requiring risk remediation is in place; one checks the control, this one checks the result. + +#### Remediation action + +1. Open the [Microsoft Entra admin center](https://entra.microsoft.com) and navigate to **Protection** > **Identity Protection** > **Risky users**. +2. Locate each reported user by their user principal name. Start with any user listed with a privileged role. +3. Investigate the risk detections behind the flag and decide whether the account is compromised. +4. Remediate the risk by the appropriate path: + - If compromised, require a password reset, revoke the user's refresh tokens, and review recent sign-ins and activity. + - If the activity is confirmed safe after investigation, dismiss the user's risk or confirm the user safe so the flag clears. +5. Consider a risk-based Conditional Access policy so that future medium-risk users are remediated automatically rather than left waiting for manual review. + +#### Related links + +* [Remediate risks and unblock users](https://learn.microsoft.com/entra/id-protection/howto-identity-protection-remediate-unblock) +* [Investigate risk with Microsoft Entra ID Protection](https://learn.microsoft.com/entra/id-protection/howto-identity-protection-investigate-risk) +* [What is risk in Microsoft Entra ID Protection](https://learn.microsoft.com/entra/id-protection/concept-identity-protection-risks) + + +%TestResult% diff --git a/tests/maester/entra/Test.MT.1261.ps1 b/tests/maester/entra/Test.MT.1261.ps1 new file mode 100644 index 0000000000..ecfc09593d --- /dev/null +++ b/tests/maester/entra/Test.MT.1261.ps1 @@ -0,0 +1,139 @@ +function Test-MtEntraUnremediatedMediumRiskUser { + <# + .SYNOPSIS + Finds users that Entra ID Protection rates medium risk and that nobody has remediated. + + .DESCRIPTION + Entra ID Protection flags users it believes may be compromised and assigns a risk level and a + risk state. A flag only clears when someone remediates it (password reset) or an admin + dismisses or confirms-safe it. This check reports users whose risk level is medium and whose + risk state still shows active, unremediated risk, so an admin can act on flags that have been + left sitting. If a reported user holds a privileged directory role, it is listed first + with its roles. It reads risk only; it never changes a user's risk state. + + .EXAMPLE + Test-MtEntraUnremediatedMediumRiskUser + + .LINK + https://maester.dev/docs/commands/Test-MtEntraUnremediatedMediumRiskUser + + .LINK + https://learn.microsoft.com/graph/api/resources/riskyuser?view=graph-rest-1.0 + #> + [MaesterTest( + Id = 'MT.1261', + Title = 'Medium-risk users should not be left unremediated in Entra ID Protection.', + Product = 'entra', + Feature = 'identity-protection', + Area = 'logging-and-detection', + ResourceType = 'User', + Severity = 'Low', + UserImpact = 'Low', + ImplementationCost = 'Low', + 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_PREMIUM_P2', + Permission = ('Graph:Scope:IdentityRiskyUser.Read.All', 'Graph:Scope:RoleManagement.Read.Directory|Graph:Scope:RoleManagement.Read.All'), + Lifecycle = 'Preview', + Author = 'Dfrank77' + )] + [CmdletBinding()] + [OutputType([bool])] + param() + + # Deleted users can stay in the risk report, but a deleted account cannot sign in and leaves nothing to act on, so it is not reported. + # Active, unremediated risk states. A flag an admin has handled moves to 'remediated', + # 'dismissed', 'confirmedSafe' or 'none'; those are intentionally excluded. + # 'confirmedCompromised' MUST be treated as unremediated alongside 'atRisk' -- confirming a + # user compromised does not clear the risk. + $UnremediatedStates = @('atRisk', 'confirmedCompromised') + + Write-Verbose 'Reading medium-risk users from Entra ID Protection.' + # Filter riskLevel server-side only. The riskState set is applied client-side on purpose: + # Graph rejects some compound / 'or' / 'in' filter shapes on this endpoint, so a single-property + # filter is the reliable shape, and the state list is tiny to post-filter. + try { + $MediumRiskUsers = @( + Invoke-MtGraphRequest -ApiVersion 'v1.0' ` + -RelativeUri 'identityProtection/riskyUsers' ` + -Filter "riskLevel eq 'medium'" ` + -Select @('id', 'isDeleted', 'userPrincipalName', 'userDisplayName', 'riskLevel', 'riskState', 'riskDetail', 'riskLastUpdatedDateTime') + ) + } catch { + if ($_.Exception.Message -match '(?i)403|forbidden|authorization') { + Add-MtTestResultDetail -SkippedBecause NotAuthorized + return $null + } + throw + } + + $Unremediated = @( + $MediumRiskUsers | Where-Object { $UnremediatedStates -contains [string]$_.riskState -and $_.isDeleted -ne $true } + ) + Write-Verbose "Found $($MediumRiskUsers.Count) medium-risk user(s); $($Unremediated.Count) unremediated." + + if ($Unremediated.Count -eq 0) { + Add-MtTestResultDetail -Result ( + 'Well done. No medium-risk users are left unremediated in Entra ID Protection.' + ) + return $true + } + + # Privileged users at risk are listed first with their roles (#2518). Roles are only read when + # there is something to report, so a clean tenant makes no extra Graph calls. The role lookup is extra + # detail: if it fails, the unremediated users are still reported, with a note. + $PrivilegedRolesByUser = @{} + $RoleNote = '' + try { + $PrivilegedResult = Get-MtPrincipalPrivilegedRole -PrincipalId @($Unremediated | ForEach-Object { [string]$_.id }) + $PrivilegedRolesByUser = $PrivilegedResult.RolesByPrincipal + if (!$PrivilegedResult.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.' + } + } catch { + Write-Verbose "Could not read directory role assignments: $($_.Exception.Message)" + $PrivilegedRolesByUser = @{} + $RoleNote = "`n`nNote: Directory role assignments could not be read, so privileged users were not identified." + } + + # Privileged users first, then by user principal name. + $Sorted = @( + $Unremediated | Sort-Object -Property @{ Expression = { -not $PrivilegedRolesByUser.ContainsKey([string]$_.id) } }, userPrincipalName + ) + $PrivilegedCount = @($Unremediated | Where-Object { $PrivilegedRolesByUser.ContainsKey([string]$_.id) }).Count + + $Result = "Found $($Unremediated.Count) medium-risk user(s) with unremediated risk." + if ($PrivilegedCount -gt 0) { + $Result += " $PrivilegedCount of them hold a privileged directory role and are listed first." + } + $Result += "`n`n| User | User principal name | Risk state | Risk detail | Risk last updated | Privileged role |" + $Result += "`n| --- | --- | --- | --- | --- | --- |" + foreach ($Item in $Sorted) { + $DisplayName = [string]$Item.userDisplayName + if ([string]::IsNullOrWhiteSpace($DisplayName)) { $DisplayName = '(unnamed)' } + $DisplayName = Get-MtSafeMarkdown $DisplayName + $Upn = Get-MtSafeMarkdown ([string]$Item.userPrincipalName) + $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 ($PrivilegedRolesByUser.ContainsKey([string]$Item.id)) { + Get-MtSafeMarkdown ($PrivilegedRolesByUser[[string]$Item.id] -join ', ') + } else { 'None' } + $Result += "`n| $DisplayName | $Upn | $State | $Detail | $Updated | $Roles |" + } + $Result += $RoleNote + + # Each risky user also appears on the report's Affected objects page; the table above stays as it is. + $AffectedUsers = @( + $Sorted | ForEach-Object { + [pscustomobject]@{ id = [string]$_.id; displayName = [string]$_.userDisplayName; userPrincipalName = [string]$_.userPrincipalName } + } + ) + Add-MtTestResultDetail -Result $Result -GraphObjects $AffectedUsers -GraphObjectType IdentityProtection + return $false +}