diff --git a/powershell/public/connect/Get-MtGraphScope.ps1 b/powershell/public/connect/Get-MtGraphScope.ps1 index 5d2f7fc8c1..ec441c56f3 100644 --- a/powershell/public/connect/Get-MtGraphScope.ps1 +++ b/powershell/public/connect/Get-MtGraphScope.ps1 @@ -99,6 +99,7 @@ 'AgentIdentityBlueprint.Read.All' 'AgentIdentityBlueprintPrincipal.Read.All' 'Application.Read.All' + 'IdentityRiskyAgent.Read.All' 'IdentityRiskyUser.Read.All' ) diff --git a/powershell/tests/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index ae970e7cfd..bad126b078 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", @@ -2500,6 +2500,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1285", "ORCA.100", "ORCA.101", "ORCA.102", @@ -2581,7 +2582,7 @@ "AD" ] }, - "SelectedCount": 639, + "SelectedCount": 640, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -3162,6 +3163,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1285", "ORCA.100", "ORCA.101", "ORCA.102", @@ -4006,7 +4008,7 @@ "AD" ] }, - "SelectedCount": 595, + "SelectedCount": 596, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -4543,6 +4545,7 @@ "MT.1259", "MT.1260", "MT.1265", + "MT.1285", "ORCA.100", "ORCA.101", "ORCA.102", diff --git a/powershell/tests/functions/Get-MtGraphScope.Tests.ps1 b/powershell/tests/functions/Get-MtGraphScope.Tests.ps1 index e974fbe6ed..d8f23c32e3 100644 --- a/powershell/tests/functions/Get-MtGraphScope.Tests.ps1 +++ b/powershell/tests/functions/Get-MtGraphScope.Tests.ps1 @@ -30,6 +30,7 @@ $scopes | Should -Not -Contain 'AgentIdentityBlueprint.Read.All' $scopes | Should -Not -Contain 'AgentIdentityBlueprintPrincipal.Read.All' $scopes | Should -Not -Contain 'Application.Read.All' + $scopes | Should -Not -Contain 'IdentityRiskyAgent.Read.All' $scopes | Should -Not -Contain 'IdentityRiskyUser.Read.All' $scopes | Should -Contain 'Directory.Read.All' $scopes | Should -Not -Contain 'User.ReadBasic.All' @@ -42,6 +43,7 @@ $scopes | Should -Contain 'AgentIdentityBlueprint.Read.All' $scopes | Should -Contain 'AgentIdentityBlueprintPrincipal.Read.All' $scopes | Should -Contain 'Application.Read.All' + $scopes | Should -Contain 'IdentityRiskyAgent.Read.All' $scopes | Should -Contain 'IdentityRiskyUser.Read.All' $scopes | Should -Contain 'AuditLog.Read.All' diff --git a/powershell/tests/functions/Test-MtEntraUnremediatedMediumRiskAgent.Tests.ps1 b/powershell/tests/functions/Test-MtEntraUnremediatedMediumRiskAgent.Tests.ps1 new file mode 100644 index 0000000000..c826c3db80 --- /dev/null +++ b/powershell/tests/functions/Test-MtEntraUnremediatedMediumRiskAgent.Tests.ps1 @@ -0,0 +1,465 @@ +Describe 'Entra ID Protection unremediated medium-risk agents (MT.1285)' { + BeforeAll { + Import-Module $PSScriptRoot/../../Maester.psd1 -Force + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + # The native-test function is not exported; reach it the same way the agent tests do. + Use-MtModuleFunction -Name Test-MtEntraUnremediatedMediumRiskAgent + } + + 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 + } + + # Role lookups default to "no roles". Tests that need roles override these. + Mock -ModuleName Maester Invoke-MtGraphRequest { return @() } -ParameterFilter { + $RelativeUri -eq 'roleManagement/directory/roleDefinitions' + } + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { + return [pscustomobject]@{ Assignments = @(); EligibleChecked = $true } + } + } + + AfterEach { + # Result text must not contain backtick-wrapped code spans (repo result-text lint). + if ($null -ne $script:TestResult) { + $script:TestResult | Should -Not -Match '`[^`]+`' + } + } + + It 'passes when there are no medium-risk agents' { + Mock -ModuleName Maester Invoke-MtGraphRequest { return @() } + + Test-MtEntraUnremediatedMediumRiskAgent | Should -BeTrue + $script:TestResult | Should -Match 'Well done' + # The medium-risk filter is what separates this check from MT.1284, and agent risk is in beta only. + Should -Invoke Invoke-MtGraphRequest -ModuleName Maester -Exactly -Times 1 -ParameterFilter { + $ApiVersion -eq 'beta' -and + $RelativeUri -eq 'identityProtection/riskyAgents' -and + $Filter -eq "riskLevel eq 'medium'" + } + # A clean tenant makes no role lookups. + Should -Invoke Get-MtDirectoryRoleAssignment -ModuleName Maester -Exactly -Times 0 + } + + It 'fails when a medium-risk agent identity is atRisk' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'ag-1'; agentDisplayName = 'Contoso Helper'; identityType = 'agentIdentity'; blueprintId = 'bp-1' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-01T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedMediumRiskAgent | Should -BeFalse + $script:TestResult | Should -Match 'Contoso Helper' + $script:TestResult | Should -Match 'ag-1' + $script:TestResult | Should -Match 'Agent identity' + $script:TestResult | Should -Match 'atRisk' + $script:TestResult | Should -Match '2026-10-01' + } + + It 'fails when a medium-risk agent is confirmedCompromised (must not be treated as remediated)' { + # confirmCompromised lands an agent in confirmedCompromised, which is still unremediated. + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'ag-2'; agentDisplayName = 'Fabrikam Assistant'; identityType = 'agentIdentity' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'confirmedCompromised' + riskDetail = 'adminConfirmedAgentCompromised'; riskLastModifiedDateTime = '2026-10-02T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedMediumRiskAgent | Should -BeFalse + $script:TestResult | Should -Match 'Fabrikam Assistant' + $script:TestResult | Should -Match 'confirmedCompromised' + } + + It 'still reports a disabled medium-risk agent (disabling does not close the risk)' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'ag-9'; agentDisplayName = 'Disabled Agent'; identityType = 'agentIdentity' + isEnabled = $false; isDeleted = $false; riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-01T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedMediumRiskAgent | Should -BeFalse + $script:TestResult | Should -Match 'Disabled Agent \| Agent identity \| ag-9 \| No \|' + @($script:GraphObjects.id) | Should -Be @('ag-9') + } + + It 'does not report a deleted medium-risk agent' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'ag-8'; agentDisplayName = 'Deleted Agent'; identityType = 'agentIdentity' + isEnabled = $false; isDeleted = $true; riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-01T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedMediumRiskAgent | Should -BeTrue + $script:TestResult | Should -Match 'Well done' + $script:GraphObjects | Should -BeNullOrEmpty + } + + It 'passes when the only medium-risk agents are already remediated, dismissed or confirmed safe' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'ag-3'; agentDisplayName = 'Old Reporter'; identityType = 'agentIdentity' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'remediated'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-03T00:00:00Z' + }, + [pscustomobject]@{ + id = 'ag-4'; agentDisplayName = 'Legacy Bot'; identityType = 'agentIdentity' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'dismissed'; riskDetail = 'adminDismissedRiskForAgent' + riskLastModifiedDateTime = '2026-10-04T00:00:00Z' + }, + [pscustomobject]@{ + id = 'ag-6'; agentDisplayName = 'Checked Bot'; identityType = 'agentIdentity' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'confirmedSafe'; riskDetail = 'adminConfirmedAgentSafe' + riskLastModifiedDateTime = '2026-10-05T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedMediumRiskAgent | Should -BeTrue + $script:TestResult | Should -Match 'Well done' + } + + It 'reports only the unremediated agents in a mixed set' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'ag-1'; agentDisplayName = 'Contoso Helper'; identityType = 'agentIdentity' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-01T00:00:00Z' + }, + [pscustomobject]@{ + id = 'ag-3'; agentDisplayName = 'Old Reporter'; identityType = 'agentIdentity' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'remediated'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-03T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedMediumRiskAgent | Should -BeFalse + $script:TestResult | Should -Match 'Contoso Helper' + $script:TestResult | Should -Not -Match 'Old Reporter' + $script:TestResult | Should -Match 'Found 1 medium-risk' + } + + It 'names each agent type from @odata.type, falling back to identityType, and shows a type it does not know as Other agent' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + '@odata.type' = '#microsoft.graph.riskyAgentIdentity' + id = 'ag-1'; agentDisplayName = 'Alpha Agent'; identityType = 'agentIdentity' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-01T00:00:00Z' + }, + [pscustomobject]@{ + '@odata.type' = '#microsoft.graph.riskyAgentUser' + id = 'au-1'; agentDisplayName = 'Bravo Agent'; identityType = 'agentUser' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-01T00:00:00Z' + }, + # Without the Prefer header Graph returns a blueprint principal's identityType as unknownFutureValue. + [pscustomobject]@{ + '@odata.type' = '#microsoft.graph.riskyAgentIdentityBlueprintPrincipal' + id = 'bp-1'; agentDisplayName = 'Charlie Agent'; identityType = 'unknownFutureValue' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-01T00:00:00Z' + }, + # No @odata.type: identityType is used. + [pscustomobject]@{ + id = 'us-1'; agentDisplayName = 'Delta Agent'; identityType = 'user' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-01T00:00:00Z' + }, + [pscustomobject]@{ + id = 'xx-1'; agentDisplayName = 'Echo Agent'; identityType = 'unknownFutureValue' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-01T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedMediumRiskAgent | Should -BeFalse + $script:TestResult | Should -Match 'Alpha Agent \| Agent identity \|' + $script:TestResult | Should -Match 'Bravo Agent \| Agent user \|' + $script:TestResult | Should -Match 'Charlie Agent \| Blueprint principal \|' + $script:TestResult | Should -Match 'Delta Agent \| User \|' + $script:TestResult | Should -Match 'Echo Agent \| Other agent \|' + # Every agent is in the table, but one of an unknown kind is not linked as an object of a guessed type. + $script:TestResult | Should -Match 'Found 5 medium-risk' + @($script:GraphObjects.id) | Should -Be @('ag-1', 'au-1', 'bp-1', 'us-1') + @($script:GraphObjects | ForEach-Object { $_.'@odata.type' }) | Should -Be @( + '#microsoft.graph.servicePrincipal', '#microsoft.graph.user', '#microsoft.graph.servicePrincipal', '#microsoft.graph.user' + ) + } + + It 'points to the portal when Graph withholds the risk detail, and shows Unknown for an unreadable date' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'ag-2'; agentDisplayName = 'Fabrikam Assistant'; identityType = 'agentIdentity' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'confirmedCompromised' + riskDetail = 'unknownFutureValue'; riskLastModifiedDateTime = 'not a date' + } + ) + } + + Test-MtEntraUnremediatedMediumRiskAgent | Should -BeFalse + $script:TestResult | Should -Match '\| confirmedCompromised \| Not returned by Graph, see the Risky agents report \| Unknown \|' + $script:TestResult | Should -Not -Match 'unknownFutureValue' + } + + It 'does not report risk states that are not active' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'ag-3'; agentDisplayName = 'No State'; identityType = 'agentIdentity' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'none'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-01T00:00:00Z' + }, + [pscustomobject]@{ + id = 'ag-4'; agentDisplayName = 'Future State'; identityType = 'agentIdentity' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'unknownFutureValue'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-01T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedMediumRiskAgent | Should -BeTrue + $script:TestResult | Should -Match 'Well done' + } + + It 'sorts agents without a privileged role by name' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'ag-z'; agentDisplayName = 'Zulu Agent'; identityType = 'agentIdentity' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-01T00:00:00Z' + }, + [pscustomobject]@{ + id = 'ag-a'; agentDisplayName = 'Alpha Agent'; identityType = 'agentIdentity' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-01T00:00:00Z' + } + ) + } -ParameterFilter { $RelativeUri -eq 'identityProtection/riskyAgents' } + + Test-MtEntraUnremediatedMediumRiskAgent | Should -BeFalse + $script:TestResult.IndexOf('Alpha Agent') | Should -BeLessThan $script:TestResult.IndexOf('Zulu Agent') + @($script:GraphObjects.id) | Should -Be @('ag-a', 'ag-z') + } + + It 'only reads from Graph (never changes an agent''s risk state)' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'ag-1'; agentDisplayName = 'Contoso Helper'; identityType = 'agentIdentity' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-01T00:00:00Z' + } + ) + } -ParameterFilter { $RelativeUri -eq 'identityProtection/riskyAgents' } + + Test-MtEntraUnremediatedMediumRiskAgent | Should -BeFalse + Should -Invoke Invoke-MtGraphRequest -ModuleName Maester -Times 2 -Exactly + Should -Invoke Invoke-MtGraphRequest -ModuleName Maester -Times 0 -Exactly -ParameterFilter { + $Method -and $Method -ne 'GET' + } + } + + It 'shows (unnamed) for an agent with no display name, and Unknown for a missing date or enabled flag' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'ag-5'; agentDisplayName = ''; identityType = 'agentIdentity' + isDeleted = $false; riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastModifiedDateTime = $null + } + ) + } + + Test-MtEntraUnremediatedMediumRiskAgent | Should -BeFalse + $script:TestResult | Should -Match '\| \(unnamed\) \| Agent identity \| ag-5 \| Unknown \| atRisk \| none \| Unknown \|' + } + + It 'escapes markdown in an agent name that comes from the tenant' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'ag-7'; agentDisplayName = 'Evil | [Sign in](https://phish.example)'; identityType = 'agentIdentity' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-01T00:00:00Z' + } + ) + } + + Test-MtEntraUnremediatedMediumRiskAgent | Should -BeFalse + $script:TestResult | Should -Not -Match '\[Sign in\]\(https://phish' + $script:TestResult | Should -Match 'Evil \\\|' + } + + It 'passes the unremediated agents to the report as affected objects with the right object type' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + return @( + [pscustomobject]@{ + id = 'ag-1'; agentDisplayName = 'Alpha Agent'; identityType = 'agentIdentity' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-01T00:00:00Z' + }, + [pscustomobject]@{ + id = 'au-1'; agentDisplayName = 'Bravo Agent'; identityType = 'agentUser' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'confirmedCompromised'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-02T00:00:00Z' + } + ) + } -ParameterFilter { $RelativeUri -eq 'identityProtection/riskyAgents' } + + Test-MtEntraUnremediatedMediumRiskAgent | Should -BeFalse + $script:GraphObjectType | Should -BeNullOrEmpty + @($script:GraphObjects).Count | Should -Be 2 + @($script:GraphObjects.id) | Should -Be @('ag-1', 'au-1') + @($script:GraphObjects.displayName) | Should -Be @('Alpha Agent', 'Bravo Agent') + # Agents' user accounts are users; agent identities are service principals. + @($script:GraphObjects | ForEach-Object { $_.'@odata.type' }) | Should -Be @('#microsoft.graph.servicePrincipal', '#microsoft.graph.user') + } + + It 'passes no affected objects when no agent is left unremediated' { + Mock -ModuleName Maester Invoke-MtGraphRequest { return @() } -ParameterFilter { $RelativeUri -eq 'identityProtection/riskyAgents' } + + Test-MtEntraUnremediatedMediumRiskAgent | 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-MtEntraUnremediatedMediumRiskAgent | 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-MtEntraUnremediatedMediumRiskAgent } | Should -Throw '*Service unavailable*' + } + + Context 'Privileged agents 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 = 'ag-1'; agentDisplayName = 'Contoso Helper'; identityType = 'agentIdentity' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-01T00:00:00Z' + }, + [pscustomobject]@{ + id = 'ag-2'; agentDisplayName = 'Fabrikam Assistant'; identityType = 'agentIdentity' + isEnabled = $true; isDeleted = $false; riskLevel = 'medium'; riskState = 'atRisk'; riskDetail = 'none' + riskLastModifiedDateTime = '2026-10-02T00:00:00Z' + } + ) + } -ParameterFilter { $RelativeUri -eq 'identityProtection/riskyAgents' } + + Mock -ModuleName Maester Get-MtRoleInfo { + return [pscustomobject]@{ IsPrivileged = ($RoleName -eq 'GlobalAdministrator') } + } + } + + It 'lists the role first when an at-risk agent holds a privileged role' { + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { + return [pscustomobject]@{ + Assignments = @([pscustomobject]@{ principalId = 'ag-2'; roleDefinitionId = 'role-ga'; AssignmentType = 'Active' }) + EligibleChecked = $true + } + } + + Test-MtEntraUnremediatedMediumRiskAgent | Should -BeFalse + $script:Severity | Should -BeNullOrEmpty + $script:TestResult | Should -Match 'Global Administrator' + $script:TestResult | Should -Match '1 of them hold a privileged directory role' + # The privileged agent is listed first. + $script:TestResult.IndexOf('Fabrikam Assistant') | Should -BeLessThan $script:TestResult.IndexOf('Contoso Helper') + } + + It 'treats a PIM-eligible privileged role as privileged' { + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { + return [pscustomobject]@{ + Assignments = @([pscustomobject]@{ principalId = 'ag-1'; roleDefinitionId = 'role-ga'; AssignmentType = 'Eligible' }) + EligibleChecked = $true + } + } + + Test-MtEntraUnremediatedMediumRiskAgent | 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 = 'ag-1'; roleDefinitionId = 'role-dr'; AssignmentType = 'Active' }) + EligibleChecked = $true + } + } + + Test-MtEntraUnremediatedMediumRiskAgent | 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-MtEntraUnremediatedMediumRiskAgent | Should -BeFalse + $script:TestResult | Should -Match 'PIM-eligible role assignments were not checked' + } + + It 'still reports the agents when role assignments cannot be read' { + Mock -ModuleName Maester Get-MtDirectoryRoleAssignment { throw 'Forbidden' } + + Test-MtEntraUnremediatedMediumRiskAgent | Should -BeFalse + $script:TestResult | Should -Match 'Contoso Helper' + $script:TestResult | Should -Match 'privileged agents were not identified' + $script:Severity | Should -BeNullOrEmpty + } + } +} diff --git a/tests/maester/entra/Test.MT.1285.md b/tests/maester/entra/Test.MT.1285.md new file mode 100644 index 0000000000..47872a89c8 --- /dev/null +++ b/tests/maester/entra/Test.MT.1285.md @@ -0,0 +1,36 @@ +Medium-risk agents should not be left unremediated in Entra ID Protection. + +Entra ID Protection rates the risk of agents (Microsoft Entra Agent ID) and tracks a risk state for each flagged one. This covers agent identities, agent identity blueprint principals and agents' user accounts. Signals include anomalous sign-ins, reconnaissance of the directory, failed attempts to reach resources the agent isn't authorized for, new credentials added to a blueprint and then used, and Microsoft threat intelligence. Microsoft documents admin actions, **Confirm safe** and **Dismiss risk**, as the way to clear an agent's risk, and until then the signals that triggered the flag have not been addressed. An agent can't be sent through multifactor authentication the way a risky user can: for agent risk, Conditional Access can only block, so the flag is left for an admin to handle. Dismissing a flag clears it but does not remove compromised credentials, so investigate before you clear it. + +This check reports agents whose risk level is **medium** and whose risk state is still active and unremediated (`atRisk` or `confirmedCompromised`). States that represent a handled flag (`dismissed`, `confirmedSafe`, `remediated`, `none`) are not reported. Deleted agents are not reported, because a deleted agent cannot sign in and leaves nothing to act on. Disabled agents are still reported, because disabling only blocks sign-ins: the risk stays open until an admin dismisses it or confirms the agent safe. The check reads risk only and never changes an agent's risk state. + +If a reported agent holds a privileged directory role, active or PIM-eligible, the result lists the role and shows that entry first, since a compromised agent with admin rights puts the whole tenant at risk. + +The check needs Microsoft Entra ID P2 and Microsoft Agent 365: ID Protection for agents needs P2 during the preview, and Microsoft says it will require Agent 365. Tenants without both skip the check as not licensed. It also needs the Microsoft Graph permission `IdentityRiskyAgent.Read.All`, which Maester does not request by default. Without it the check is skipped. To identify privileged agents, it also reads directory roles, which needs `RoleManagement.Read.Directory` or `RoleManagement.Read.All`. If those reads fail, the agents are still reported with a note. Connect with `Connect-Maester -IncludePreview`, or grant the permission to the app registration that runs Maester. + +This is the agent companion to MT.1263, which reports medium-risk service principals. Entra ID Protection reports agent risk in its own list, `riskyAgents`, which MT.1263 does not read. + +#### Remediation action + +1. Open the [Microsoft Entra admin center](https://entra.microsoft.com) and navigate to **ID Protection** > **Risky agents**. Locate each reported agent by its name or object ID, starting with any agent this check's result lists with a privileged role. +2. Contain the agent before you investigate: select **Disable** to block its sign-ins. **Confirm compromise** blocks the agent only if a Conditional Access policy blocks high agent risk. It raises the risk level to high, so this check stops listing it, and the agent stays in the Risky agents report as high risk until you clear the flag. If its risk detections point to its blueprint's credentials, for example **Suspicious credential usage**, also disable the blueprint (**Entra ID** > **Agents** > **Agent blueprints**, then **Disable** on its overview page) and rotate its credentials right away. Disabling a blueprint blocks every agent identity created from it in your tenant, not only this one. A single-instance agent has no blueprint principal or other agent identities in your tenant, so disabling the agent contains it; still rotate the blueprint's credentials if it has any. If another tenant publishes the blueprint, its credentials are managed in that tenant, so you can't rotate them: keep the blueprint disabled in your tenant, or for a single-instance agent keep the agent disabled, and contact the publisher to rotate them. +3. Investigate and recover by following Microsoft's [steps for responding to agent security incidents](https://learn.microsoft.com/entra/agent-id/manage-agent-identities-admin#respond-to-agent-security-incidents). After a false positive, re-enable the agent if you disabled it. Before you re-enable a shared blueprint, confirm that no other agent identity created from it has an unremediated compromise; if one does, re-enable the blueprint only after that compromise is remediated, including the credential rotation or publisher confirmation below. After a compromise, rotate the blueprint's credentials, if it has any, before you re-enable the agent or its blueprint, or retire the agent identity. If the blueprint's credentials were compromised, rotate them even if you retire the agent. If another tenant publishes the blueprint and its credentials were compromised, you can't rotate them, since they're managed in that tenant: disable the blueprint in your tenant, or for a single-instance agent keep the agent disabled, report the compromise to the publisher, and re-enable only after the publisher confirms it rotated them. This isn't needed after a false positive unless another agent identity created from the blueprint has an unremediated compromise. Credentials are configured on the blueprint, not on the agent identity. +4. Clear the flag from the Risky agents report, as described in [ID Protection for agents](https://learn.microsoft.com/entra/id-protection/concept-risky-agents): **Confirm safe** for a false positive, or **Dismiss risk** when the risk is no longer relevant after investigation or is a benign true positive. +5. Consider risk-based Conditional Access policies for agents, which block agents at the risk levels you choose (see [Conditional Access for agents](https://learn.microsoft.com/entra/identity/conditional-access/agent-id)), so that risky agent identities and agents' user accounts are blocked automatically rather than left waiting for manual review. + +#### Known limitations + +* **Beta API.** Microsoft publishes the risky agents list (`riskyAgents`) in Microsoft Graph beta only, so its shape can change. +* **Agent type.** The type comes from each item's `@odata.type`, with `identityType` as the fallback. Some of these values are new enum members that Graph returns as `unknownFutureValue` unless the request asks for them, and Maester's Graph requests don't. An agent whose type can't be read is still reported, with the type **Other agent**, but isn't listed on the report's affected objects page. +* **Risk detail.** Microsoft documents the agent values of Risk detail (`adminConfirmedAgentCompromised`, `adminConfirmedAgentSafe`, `adminDismissedRiskForAgent`) as new enum members that Graph returns only when the request asks for them. In testing, Graph returned `adminConfirmedAgentCompromised` without being asked. If Graph does withhold one, the column says so and points to the Risky agents report. +* **Privileged means directory roles.** The Privileged role column lists only built-in directory roles that Microsoft classifies as privileged, active or PIM-eligible. Custom roles and Microsoft Graph application permissions are not checked, so an agent that holds powerful Graph permissions but no privileged built-in role shows `None`. Only roles assigned directly to the agent are matched: a role held through membership of a role-assignable group isn't detected. +* **PIM-eligible roles.** Eligible role assignments are checked only when the tenant has Microsoft Entra ID P2 or Microsoft Entra ID Governance. Otherwise only active assignments are checked, and when the check reports agents the result includes a note saying so. + +#### Related links + +* [ID Protection for agents](https://learn.microsoft.com/entra/id-protection/concept-risky-agents) +* [Conditional Access for agents](https://learn.microsoft.com/entra/identity/conditional-access/agent-id) +* [riskyAgent resource type](https://learn.microsoft.com/graph/api/resources/riskyagent?view=graph-rest-beta) + + +%TestResult% diff --git a/tests/maester/entra/Test.MT.1285.ps1 b/tests/maester/entra/Test.MT.1285.ps1 new file mode 100644 index 0000000000..fe1b9e40d5 --- /dev/null +++ b/tests/maester/entra/Test.MT.1285.ps1 @@ -0,0 +1,192 @@ +function Test-MtEntraUnremediatedMediumRiskAgent { + <# + .SYNOPSIS + Finds agents that Entra ID Protection rates medium risk and that nobody has remediated. + .DESCRIPTION + Entra ID Protection flags agents (agent identities, agent identity blueprint principals and agents' + user accounts) it believes are compromised and assigns a risk level and a risk state. Microsoft documents + admin actions (confirm safe, dismiss risk) as the way to clear an agent's risk. This check reports agents 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 agent holds a privileged directory role, it is + listed first with its roles. It reads risk only; it never changes an agent's risk state. + .EXAMPLE + Test-MtEntraUnremediatedMediumRiskAgent + .LINK + https://maester.dev/docs/commands/Test-MtEntraUnremediatedMediumRiskAgent + .LINK + https://learn.microsoft.com/graph/api/resources/riskyagent?view=graph-rest-beta + #> + [MaesterTest( + Id = 'MT.1285', + Title = 'Medium-risk agents should not be left unremediated in Entra ID Protection.', + Product = 'entra', + Feature = 'identity-protection', + Area = 'ai', + ResourceType = 'Agent', + Severity = 'Low', + UserImpact = 'Low', + ImplementationCost = 'Medium', + Mitre = 'T1078.004', + Control = ('nist-800-53-r5:AC-2(12)', 'nist-800-53-r5:IR-4'), + Cloud = ('Commercial', 'GCC', 'GCCHigh', 'DoD'), + Service = 'Graph', + License = 'AAD_PREMIUM_P2&AGENT_365', + Permission = ('Graph:Scope:IdentityRiskyAgent.Read.All', 'Graph:Scope:RoleManagement.Read.Directory|Graph:Scope:RoleManagement.Read.All'), + Lifecycle = 'Preview', + Author = 'Dfrank77' + )] + [CmdletBinding()] + [OutputType([bool])] + param() + + # Active, unremediated risk states, same as MT.1262. 'confirmedCompromised' is still unremediated: + # an admin confirming an agent compromised raises its risk to high and does not clear it. + $UnremediatedStates = @('atRisk', 'confirmedCompromised') + + # Each item's @odata.type says which kind of agent it is (riskyAgentIdentity, riskyAgentUser or + # riskyAgentIdentityBlueprintPrincipal). It is read first because identityType is an evolvable enum: + # without the Prefer: include-unknown-enum-members header, which Invoke-MtGraphRequest can't send, Graph + # returns blueprint principals as unknownFutureValue. identityType is the fallback. + # Name shown in the table, and the object type used on the report's Affected objects page. Agents' user + # accounts and regular user accounts are users; agent identities and blueprint principals are service principals. + $AgentTypes = @{ + '#microsoft.graph.riskyAgentIdentity' = @{ Name = 'Agent identity'; ObjectType = '#microsoft.graph.servicePrincipal' } + '#microsoft.graph.riskyAgentUser' = @{ Name = 'Agent user'; ObjectType = '#microsoft.graph.user' } + '#microsoft.graph.riskyAgentIdentityBlueprintPrincipal' = @{ Name = 'Blueprint principal'; ObjectType = '#microsoft.graph.servicePrincipal' } + 'agentIdentity' = @{ Name = 'Agent identity'; ObjectType = '#microsoft.graph.servicePrincipal' } + 'agentUser' = @{ Name = 'Agent user'; ObjectType = '#microsoft.graph.user' } + 'agentIdentityBlueprintPrincipal' = @{ Name = 'Blueprint principal'; ObjectType = '#microsoft.graph.servicePrincipal' } + 'user' = @{ Name = 'User'; ObjectType = '#microsoft.graph.user' } + } + $GetAgentType = { + param($Item) + foreach ($Key in @([string]$Item.'@odata.type', [string]$Item.identityType)) { + if ($Key -and $AgentTypes.ContainsKey($Key)) { return $AgentTypes[$Key] } + } + # An agent of a kind Maester doesn't know yet is still reported, but not linked as an object of a guessed type. + return @{ Name = 'Other agent'; ObjectType = $null } + } + + # Microsoft documents the agent values of riskDetail as evolvable too (unknownFutureValue without the + # Prefer header; in testing Graph returned them anyway), so that value points the admin to the portal + # instead of showing the sentinel. + $RiskDetailUnknown = 'Not returned by Graph, see the Risky agents report' + + Write-Verbose 'Reading medium-risk agents from Entra ID Protection.' + # Agent risk is a separate list from riskyServicePrincipals and is available in Microsoft Graph beta only. + # Filter riskLevel server-side and apply the riskState set client-side, same as MT.1262. + try { + $MediumRiskAgents = @( + Invoke-MtGraphRequest -ApiVersion 'beta' ` + -RelativeUri 'identityProtection/riskyAgents' ` + -Filter "riskLevel eq 'medium'" + ) + } catch { + if ($_.Exception.Message -match '(?i)403|forbidden|authorization') { + Add-MtTestResultDetail -SkippedBecause NotAuthorized + return $null + } + throw + } + + # Deleted agents stay in the risk list, but a deleted agent cannot sign in and leaves nothing to act on. + # Disabled agents are still reported: disabling only blocks sign-ins, and the risk stays open until an + # admin dismisses it or confirms the agent safe. + $Unremediated = @( + $MediumRiskAgents | Where-Object { + ($UnremediatedStates -contains [string]$_.riskState) -and ($_.isDeleted -ne $true) + } + ) + Write-Verbose "Found $($MediumRiskAgents.Count) medium-risk agent(s); $($Unremediated.Count) unremediated and not deleted." + + if ($Unremediated.Count -eq 0) { + Add-MtTestResultDetail -Result ( + 'Well done. No medium-risk agents are left unremediated in Entra ID Protection.' + ) + return $true + } + + # Agents at risk that hold a privileged role are listed first with their roles, as MT.1262 does for + # service principals. Roles are only read when there is something to report. If the lookup fails, the + # unremediated agents are still reported, with a note. + $PrivilegedRolesByAgent = @{} + $RoleNote = '' + try { + $RoleDefinitions = @( + Invoke-MtGraphRequest -ApiVersion 'v1.0' ` + -RelativeUri 'roleManagement/directory/roleDefinitions' ` + -Select @('id', 'displayName') + ) + $RoleDefLookup = @{} + foreach ($Def in $RoleDefinitions) { $RoleDefLookup[[string]$Def.id] = $Def } + + # Same properties as MT.1209, MT.1210 and MT.1262 so the active assignments come from the Graph cache. + $RoleAssignmentResult = Get-MtDirectoryRoleAssignment -Select @('id', 'principalId', 'roleDefinitionId', 'directoryScopeId') + if (!$RoleAssignmentResult.EligibleChecked) { + $RoleNote = "`n`nNote: PIM-eligible role assignments were not checked because they need " + + 'Microsoft Entra ID P2 or Governance. Only active role assignments were checked.' + } + + $UnremediatedIds = @{} + foreach ($Item in $Unremediated) { $UnremediatedIds[[string]$Item.id] = $true } + + foreach ($Assignment in @($RoleAssignmentResult.Assignments)) { + $PrincipalId = [string]$Assignment.principalId + if (!$UnremediatedIds.ContainsKey($PrincipalId)) { continue } + $RoleDef = $RoleDefLookup[[string]$Assignment.roleDefinitionId] + if ($null -eq $RoleDef) { continue } + $RoleInfo = Get-MtRoleInfo -RoleName ([string]$RoleDef.displayName -replace '\s', '') + if ($null -eq $RoleInfo -or !$RoleInfo.IsPrivileged) { continue } + $RoleName = [string]$RoleDef.displayName + if ($Assignment.AssignmentType -eq 'Eligible') { $RoleName += ' (eligible)' } + if (!$PrivilegedRolesByAgent.ContainsKey($PrincipalId)) { + $PrivilegedRolesByAgent[$PrincipalId] = [System.Collections.Generic.List[string]]::new() + } + $PrivilegedRolesByAgent[$PrincipalId].Add($RoleName) + } + } catch { + Write-Verbose "Could not read directory role assignments: $($_.Exception.Message)" + $PrivilegedRolesByAgent = @{} + $RoleNote = "`n`nNote: Directory role assignments could not be read, so privileged agents were not identified." + } + + # Privileged agents first, then by display name. + $Sorted = @( + $Unremediated | Sort-Object -Property @{ Expression = { -not $PrivilegedRolesByAgent.ContainsKey([string]$_.id) } }, agentDisplayName + ) + $PrivilegedCount = @($Unremediated | Where-Object { $PrivilegedRolesByAgent.ContainsKey([string]$_.id) }).Count + + $Result = "Found $($Unremediated.Count) medium-risk agent(s) with unremediated risk." + if ($PrivilegedCount -gt 0) { + $Result += " $PrivilegedCount of them hold a privileged directory role and are listed first." + } + $Result += "`n`n| Agent | Type | Object ID | Enabled | Risk state | Risk detail | Risk last updated | Privileged role |" + $Result += "`n| --- | --- | --- | --- | --- | --- | --- | --- |" + foreach ($Item in $Sorted) { + # The agent's name comes from the tenant, so it is escaped. The (unnamed) placeholder is ours and is not. + $DisplayName = if ([string]::IsNullOrWhiteSpace([string]$Item.agentDisplayName)) { '(unnamed)' } else { Get-MtSafeMarkdown ([string]$Item.agentDisplayName) } + $Type = (& $GetAgentType $Item).Name + $Enabled = if ($Item.isEnabled -eq $false) { 'No' } elseif ($Item.isEnabled -eq $true) { 'Yes' } else { 'Unknown' } + $State = [string]$Item.riskState + $Detail = if ([string]$Item.riskDetail -eq 'unknownFutureValue') { $RiskDetailUnknown } else { Get-MtSafeMarkdown ([string]$Item.riskDetail) } + $UpdatedDate = $Item.riskLastModifiedDateTime -as [datetime] + $Updated = if ($UpdatedDate) { $UpdatedDate.ToUniversalTime().ToString('yyyy-MM-dd') } else { 'Unknown' } + $Roles = if ($PrivilegedRolesByAgent.ContainsKey([string]$Item.id)) { + Get-MtSafeMarkdown ($PrivilegedRolesByAgent[[string]$Item.id] -join ', ') + } else { 'None' } + $Result += "`n| $DisplayName | $Type | $($Item.id) | $Enabled | $State | $Detail | $Updated | $Roles |" + } + $Result += $RoleNote + + # Each risky agent of a known kind also appears on the report's Affected objects page; the table above stays as it is. + $AffectedAgents = @( + $Sorted | ForEach-Object { + $ObjectType = (& $GetAgentType $_).ObjectType + if ($ObjectType) { + [pscustomobject]@{ id = [string]$_.id; displayName = [string]$_.agentDisplayName; '@odata.type' = $ObjectType } + } + } + ) + Add-MtTestResultDetail -Result $Result -GraphObjects $AffectedAgents + return $false +} diff --git a/website/docs/sections/permissions.md b/website/docs/sections/permissions.md index 05f1d58a0d..b898765f0d 100644 --- a/website/docs/sections/permissions.md +++ b/website/docs/sections/permissions.md @@ -37,4 +37,5 @@ To run preview tests, also grant these application permissions: - **AgentIdentityBlueprint.Read.All** - **AgentIdentityBlueprintPrincipal.Read.All** - **Application.Read.All** +- **IdentityRiskyAgent.Read.All** - **IdentityRiskyUser.Read.All**