diff --git a/.github/workflows/update-agent-blocked-permissions.yaml b/.github/workflows/update-agent-blocked-permissions.yaml new file mode 100644 index 0000000000..878061a613 --- /dev/null +++ b/.github/workflows/update-agent-blocked-permissions.yaml @@ -0,0 +1,196 @@ +--- +name: update-agent-blocked-permissions + +on: + schedule: + - cron: "0 8 10 * *" # Monthly on the 10th at 08:00 UTC + workflow_dispatch: + inputs: + allow_large_removal: + description: Accept more removed permissions than the script allows. Tick only after checking Microsoft's table. + type: boolean + default: false + +permissions: {} + +concurrency: + group: update-agent-blocked-permissions + cancel-in-progress: false + +env: + SNAPSHOT_PATH: powershell/internal/generated/AgentBlockedPermissions.json + FAILURE_LABEL: agent-blocked-permissions + FAILURE_TITLE: The agent blocked permissions snapshot could not be updated + +jobs: + update-agent-blocked-permissions: + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Update agent blocked permissions snapshot + shell: pwsh + env: + ALLOW_LARGE_REMOVAL: ${{ inputs.allow_large_removal == true }} + run: | + $parameters = @{ Verbose = $true } + if ($env:ALLOW_LARGE_REMOVAL -eq 'true') { $parameters.AllowLargeRemoval = $true } + ./build/Update-MtAgentBlockedPermissions.ps1 @parameters + + - name: Summarize snapshot changes + id: diff + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + + $diff = @(git diff --unified=0 -- $env:SNAPSHOT_PATH) + if ($diff.Count -eq 0) { + Write-Host 'No changes to the blocked permissions snapshot.' + 'changed=false' | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8 + exit 0 + } + + $newSnapshot = Get-Content -LiteralPath $env:SNAPSHOT_PATH -Raw | ConvertFrom-Json + + $addedPattern = '^\+\s*"Permission":\s*"(.+)"' + $removedPattern = '^-\s*"Permission":\s*"(.+)"' + + $addedNames = @($diff | Select-String -Pattern $addedPattern | ForEach-Object { $_.Matches[0].Groups[1].Value }) + $removedNames = @($diff | Select-String -Pattern $removedPattern | ForEach-Object { $_.Matches[0].Groups[1].Value }) + + $trulyAdded = @($addedNames | Where-Object { $_ -notin $removedNames } | Sort-Object) + $trulyRemoved = @($removedNames | Where-Object { $_ -notin $addedNames } | Sort-Object) + + $lines = [System.Collections.Generic.List[string]]::new() + $lines.Add("| Change | Permissions |") + $lines.Add("| --- | --- |") + $lines.Add("| Added | $($trulyAdded.Count) |") + $lines.Add("| Removed | $($trulyRemoved.Count) |") + $lines.Add("| New total | $($newSnapshot.Count) |") + $lines.Add('') + + if ($trulyAdded.Count -gt 0) { + $lines.Add('### Newly blocked permissions') + $lines.Add('') + $lines.Add('Microsoft now blocks these for agents. If any appear in MT.1223''s curated list, the check is watching a permission that can no longer fire.') + $lines.Add('') + foreach ($name in $trulyAdded) { + $lines.Add("- ``$name``") + } + $lines.Add('') + } + + if ($trulyRemoved.Count -gt 0) { + $lines.Add('### Unblocked permissions') + $lines.Add('') + $lines.Add('Microsoft removed the block on these. Agents can now hold them. Evaluate whether any are dangerous enough to add to MT.1223.') + $lines.Add('') + foreach ($name in $trulyRemoved) { + $lines.Add("- ``$name``") + } + $lines.Add('') + } + + $summary = $lines -join "`n" + Write-Host $summary + $summary | Out-File -FilePath $env:GITHUB_STEP_SUMMARY -Append -Encoding utf8 + + $delimiter = "DIFF_$(New-Guid)" + "changed=true" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8 + "diff_summary<<$delimiter`n$summary`n$delimiter" | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8 + + - name: Generate maester-bot app token + id: app-token + if: steps.diff.outputs.changed == 'true' + uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + app-id: ${{ secrets.MAESTER_BOT_APP_ID }} + private-key: ${{ secrets.MAESTER_BOT_PRIVATE_KEY }} + permission-contents: write + permission-pull-requests: write + + - name: Create Pull Request + if: steps.diff.outputs.changed == 'true' + uses: peter-evans/create-pull-request@3ffccacd46053766916f087ce41d627c0b8cf2d1 # v8.1.3 + with: + token: ${{ steps.app-token.outputs.token }} + commit-message: "chore: update agent blocked permissions snapshot" + branch: "automation/update-agent-blocked-permissions" + delete-branch: true + title: "chore: update agent blocked permissions snapshot" + body: | + Refreshes `powershell/internal/generated/AgentBlockedPermissions.json` from + Microsoft's [agent identity platform overview](https://learn.microsoft.com/graph/api/resources/agentid-platform-overview) + documentation. + + **Review the diff as data, not as a routine bump.** The source is `main` of + [microsoftgraph/microsoft-graph-docs-contrib](https://github.com/microsoftgraph/microsoft-graph-docs-contrib), + a public docs repository that takes community pull requests. `SourceSha256` shows the snapshot + matches the table that was downloaded; it does not show that the edit upstream was correct. + Check each added or removed permission against Microsoft's documentation before merging. + + Why this matters in Maester: + - `AgentBlockedPermissionDrift.Tests.ps1` compares MT.1223's curated list of high-risk + agent permissions against this snapshot. If Microsoft blocks a permission that MT.1223 + watches for, the test fails so someone can remove the dead entry. + - Newly unblocked permissions may be dangerous enough to add to MT.1223. + + ## Diff summary + + ${{ steps.diff.outputs.diff_summary }} + + Reviewer note: + - **Newly blocked** permissions that overlap with MT.1223 need to be removed from + `Get-MtEntraAgentHighRiskGraphPermission` because agents can no longer hold them. + - **Unblocked** permissions need a judgment call on whether they belong in MT.1223. + labels: automation + + # The update runs on a schedule and stops on purpose when Microsoft's table changes shape, so a failed run would + # otherwise go unnoticed while the drift test keeps passing against the old snapshot. Like eidsca-sync, one issue + # (labelled agent-blocked-permissions) stays open while runs fail and closes when a run succeeds. The snapshot keeps + # no timestamp, so an unchanged table still raises no pull request. + report-update-status: + needs: update-agent-blocked-permissions + if: always() + runs-on: ubuntu-latest + permissions: + issues: write + + steps: + - name: Open, update or close the failure issue + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + RESULT: ${{ needs.update-agent-blocked-permissions.result }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + issue=$(gh issue list --label "$FAILURE_LABEL" --state open --limit 1 --json number --jq '.[0].number // empty') + if [ "$RESULT" = "failure" ]; then + body=$(printf '%s\n' \ + "The \`update-agent-blocked-permissions\` workflow failed, so \`$SNAPSHOT_PATH\` was not refreshed: $RUN_URL" \ + "" \ + "The drift test keeps passing against the old snapshot, so this issue is the signal that the snapshot is going stale." \ + "" \ + "The script stops on purpose when Microsoft's table no longer looks the way it expects: a renamed section, changed columns or symbols, a duplicate name, or more removed permissions than it allows in one update. Read the error in the run log and check the [source table](https://learn.microsoft.com/graph/api/resources/agentid-platform-overview). Then fix the script, or, if a large removal is real, run the workflow manually with **allow_large_removal** ticked." \ + "" \ + "This issue closes when a run succeeds.") + if [ -n "$issue" ]; then + gh issue comment "$issue" --body "$body" + echo "Commented on issue #$issue." + else + gh label create "$FAILURE_LABEL" --color d93f0b --description "The agent blocked permissions snapshot could not be updated" --force + url=$(gh issue create --title "$FAILURE_TITLE" --body "$body" --label "$FAILURE_LABEL") + echo "Opened issue ${url##*/}." + fi + elif [ "$RESULT" = "success" ] && [ -n "$issue" ]; then + gh issue close "$issue" --reason completed --comment "The snapshot update ran successfully again: $RUN_URL" + echo "Closed issue #$issue." + else + echo "Update job result: $RESULT. Nothing to report." + fi + diff --git a/build/Update-MtAgentBlockedPermissions.ps1 b/build/Update-MtAgentBlockedPermissions.ps1 new file mode 100644 index 0000000000..16396772b2 --- /dev/null +++ b/build/Update-MtAgentBlockedPermissions.ps1 @@ -0,0 +1,236 @@ +<# + .SYNOPSIS + Updates the checked-in snapshot of Microsoft Graph permissions blocked for agent identities. + + .DESCRIPTION + Downloads Microsoft's agentid-platform-overview.md from the public docs repo, + parses the "Microsoft Graph permissions blocked for agents" table, validates the + result, and writes a JSON snapshot into the module's internal generated folder. + The update-agent-blocked-permissions workflow runs this monthly and raises a pull + request when the table changes. + For reproducibility, pass a commit-pinned raw URL with -SourceUrl. + + .EXAMPLE + ./build/Update-MtAgentBlockedPermissions.ps1 +#> + +[CmdletBinding()] +param ( + # Path to the generated JSON snapshot. + [string] $SnapshotPath = "$PSScriptRoot/../powershell/internal/generated/AgentBlockedPermissions.json", + + # Raw URL of Microsoft's agent ID platform overview page. + [string] $SourceUrl = 'https://raw.githubusercontent.com/microsoftgraph/microsoft-graph-docs-contrib/main/api-reference/v1.0/resources/agentid-platform-overview.md', + + # Fewest rows accepted when there is no earlier snapshot to compare with. The table has 59 rows today. + [int] $MinimumRowCount = 50, + + # Most permissions that may drop out of the table in one update, as a percentage of the earlier snapshot. + # A larger drop is more likely a broken parse or a bad edit upstream than a real change, so the script + # stops. After checking Microsoft's table, run it again with -AllowLargeRemoval. + [ValidateRange(0, 100)] + [int] $MaximumRemovedPercent = 20, + + # Accept more removals than -MaximumRemovedPercent allows. Use it only after checking Microsoft's table. + [switch] $AllowLargeRemoval +) + +$ErrorActionPreference = 'Stop' + +# --- Download --- + +Write-Verbose "Downloading agent blocked permissions from $SourceUrl..." +try { + $response = Invoke-WebRequest -Uri $SourceUrl -UseBasicParsing -ErrorAction Stop +} catch { + throw "Failed to download agent permissions doc from $SourceUrl. Error: $_" +} + +if ($response.StatusCode -ne 200) { + throw "Unexpected HTTP status code $($response.StatusCode) from $SourceUrl" +} + +$content = $response.Content +if ([string]::IsNullOrWhiteSpace($content) -or $content.Length -lt 1000) { + throw "Downloaded content appears empty or too short ($($content.Length) chars). Aborting." +} + +# --- Find the table --- + +$lines = $content -split "`n" +$headerIndexes = @(for ($i = 0; $i -lt $lines.Count; $i++) { + if ($lines[$i] -match '^\|\s*Permission name\s*\|') { $i } +}) + +if ($headerIndexes.Count -eq 0) { + throw "Could not find the 'Permission name' table header in the downloaded markdown. Microsoft may have renamed or moved the section." +} +if ($headerIndexes.Count -gt 1) { + throw "Found $($headerIndexes.Count) tables with a 'Permission name' header (lines $(($headerIndexes | ForEach-Object { $_ + 1 }) -join ', ')); expected one. Check which table lists the blocked permissions." +} +$tableStartIndex = $headerIndexes[0] + +# Rows are read by column position, so check the column names and their order first. +# A swapped or added column would otherwise put the wrong values in the snapshot. +$expectedHeader = @('Permission name', 'Delegated', 'Application') +$headerCells = @($lines[$tableStartIndex].Trim() -split '\|' | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' }) +if (-not [string]::Equals(($headerCells -join ' | '), ($expectedHeader -join ' | '), [StringComparison]::OrdinalIgnoreCase)) { + throw "Unexpected table columns '$($headerCells -join ' | ')'; expected '$($expectedHeader -join ' | ')'. Microsoft may have added, removed or reordered a column." +} +if ($tableStartIndex + 1 -ge $lines.Count -or $lines[$tableStartIndex + 1].Trim() -notmatch '^\|(\s*:?-+:?\s*\|){3}$') { + throw "Expected a three-column separator row (|---|---|---|) after the table header." +} + +# --- Parse rows --- + +$permissions = [System.Collections.Generic.List[hashtable]]::new() + +# Skip the header row and the separator row (the |---|---|---| line) +for ($i = $tableStartIndex + 2; $i -lt $lines.Count; $i++) { + $line = $lines[$i].Trim() + + # Stop at the first non-table line + if (-not $line.StartsWith('|')) { break } + + # Split on | and trim. The split gives us empty strings at the start and end. + $cells = $line -split '\|' | ForEach-Object { $_.Trim() } | Where-Object { $_ -ne '' } + + if ($cells.Count -ne 3) { + throw "Malformed row (expected 3 columns, found $($cells.Count)): $line" + } + + # Column 0: permission name (may be a markdown link like [Name](url)) + $permName = $cells[0] + if ($permName -match '^\[([^\]]+)\]') { + $permName = $Matches[1] + } + $permName = $permName.Trim() + + if ([string]::IsNullOrWhiteSpace($permName)) { + throw "Empty permission name in row: $line" + } + + # Graph permission names use only letters, digits, '.', '_' and '-', as in Microsoft's Graph + # permissions reference. Anything else (a space, a backtick, an invisible character) would put a + # name in the snapshot that is not the real permission name. A space breaks the drift test's + # match; an invisible character does not even show, because PowerShell's -eq ignores it. The + # check is case-sensitive (-cnotmatch) because a case-insensitive [A-Za-z] also accepts the + # Kelvin sign. + if ($permName -cnotmatch '^[A-Za-z0-9][A-Za-z0-9._-]*\z') { + throw "Unexpected characters in permission name '$permName' in row: $line" + } + + # Column 1: Delegated, column 2: Application. Each cell must hold exactly one symbol: + # U+274C (cross mark) means blocked, U+2796 (heavy minus sign) means not blocked. A trailing + # U+FE0F (emoji presentation selector) does not change the meaning, so it is removed first. + # Compared ordinally: -ceq ignores U+FE0F and zero-width characters on some machines and not on + # others (not when .NET runs in invariant globalization mode). + $delegated, $application = foreach ($column in 1, 2) { + $value = $cells[$column].Replace([string][char]0xFE0F, '').Trim() + if ([string]::Equals($value, [string][char]0x274C, [StringComparison]::Ordinal)) { $true } + elseif ([string]::Equals($value, [string][char]0x2796, [StringComparison]::Ordinal)) { $false } + else { throw "Unexpected $($expectedHeader[$column]) value '$($cells[$column])' for $permName" } + } + + $permissions.Add(@{ + Permission = $permName + Delegated = $delegated + Application = $application + }) +} + +# --- Validate --- + +# Compare with the snapshot already checked in. A fixed minimum stops a real shrink by Microsoft just as it +# stops a broken parse, so the guard is relative to the earlier snapshot: too many permissions dropping out at +# once stops the update. With no earlier snapshot (the first run), the fixed minimum still applies. +$previousNames = @() +if (Test-Path -LiteralPath $SnapshotPath) { + try { + $previousSnapshot = Get-Content -LiteralPath $SnapshotPath -Raw | ConvertFrom-Json + } catch { + throw "Could not read the existing snapshot at $SnapshotPath to compare with. $($_.Exception.Message)" + } + $previousNames = @($previousSnapshot.Permissions | ForEach-Object { [string]$_.Permission }) +} + +if ($previousNames.Count -eq 0) { + if ($permissions.Count -lt $MinimumRowCount) { + throw "Only $($permissions.Count) permissions parsed; expected at least $MinimumRowCount. The table format may have changed." + } +} else { + $currentNames = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + foreach ($p in $permissions) { [void]$currentNames.Add($p.Permission) } + $removedNames = @($previousNames | Where-Object { -not $currentNames.Contains($_) }) + $allowedRemovals = [math]::Floor($previousNames.Count * $MaximumRemovedPercent / 100) + if ($removedNames.Count -gt $allowedRemovals -and -not $AllowLargeRemoval) { + throw ("$($removedNames.Count) of the $($previousNames.Count) permissions in the current snapshot are no longer in the table, " + + "more than the $allowedRemovals ($MaximumRemovedPercent%) allowed in one update. That is more likely a broken parse or a bad edit " + + "upstream than a real change. Check the source; if the removals are real, run again with -AllowLargeRemoval. " + + "No longer listed: $($removedNames -join ', ')") + } + Write-Verbose "$($removedNames.Count) permission(s) dropped out of the table since the last snapshot (at most $allowedRemovals allowed)." +} + +# A name listed twice makes the snapshot ambiguous (which row's values apply?), and the ordinal +# sort below does not keep equal names in a fixed order. Stop instead of writing either. +$seen = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) +foreach ($p in $permissions) { + if (-not $seen.Add($p.Permission)) { + throw "Permission '$($p.Permission)' appears more than once in the table. Check the source before updating the snapshot." + } +} + +Write-Verbose "Parsed $($permissions.Count) blocked permissions." + +# --- Hash the source for traceability --- + +$sourceBytes = [System.Text.Encoding]::UTF8.GetBytes(($lines[$tableStartIndex..($i - 1)] -join "`n")) +$sha256 = [System.Security.Cryptography.SHA256]::Create() +try { + $sourceHash = (-join ($sha256.ComputeHash($sourceBytes) | ForEach-Object { $_.ToString('x2') })) +} finally { + $sha256.Dispose() +} + +# --- Build output --- +# The snapshot holds no timestamp, so the workflow's git diff is non-empty only when +# Microsoft's table or SourceUrl changes. + +# Sort by ordinal (character code) comparison. Sort-Object compares by the machine's culture, +# which orders some names differently from one machine to another and would make the +# snapshot change without any change in Microsoft's table. +$sorted = [System.Collections.Generic.List[hashtable]]::new($permissions) +$sorted.Sort([System.Comparison[hashtable]] { param($a, $b) [string]::CompareOrdinal($a.Permission, $b.Permission) }) + +$output = [ordered]@{ + SourceUrl = $SourceUrl + SourceSha256 = $sourceHash + Count = $permissions.Count + Permissions = @($sorted | ForEach-Object { + [ordered]@{ + Permission = $_.Permission + Delegated = $_.Delegated + Application = $_.Application + } + }) +} + +# --- Write --- + +$resolvedPath = $SnapshotPath +if (Test-Path -LiteralPath $SnapshotPath) { + $resolvedPath = (Resolve-Path -LiteralPath $SnapshotPath).ProviderPath +} else { + $parent = Split-Path -Parent $SnapshotPath + if (-not (Test-Path -LiteralPath $parent)) { + New-Item -ItemType Directory -Path $parent -Force | Out-Null + } + $resolvedPath = [System.IO.Path]::GetFullPath($SnapshotPath) +} + +$json = $output | ConvertTo-Json -Depth 5 +$utf8NoBom = [System.Text.UTF8Encoding]::new($false) +[System.IO.File]::WriteAllText($resolvedPath, $json + "`n", $utf8NoBom) + +Write-Verbose "Updated $resolvedPath with $($permissions.Count) permissions; source SHA-256: $sourceHash" diff --git a/powershell/internal/generated/AgentBlockedPermissions.json b/powershell/internal/generated/AgentBlockedPermissions.json new file mode 100644 index 0000000000..63d0c9b374 --- /dev/null +++ b/powershell/internal/generated/AgentBlockedPermissions.json @@ -0,0 +1,302 @@ +{ + "SourceUrl": "https://raw.githubusercontent.com/microsoftgraph/microsoft-graph-docs-contrib/main/api-reference/v1.0/resources/agentid-platform-overview.md", + "SourceSha256": "f526e4be67d44498c78a91f52eca42920dcfea4329e78951395e83479647fe56", + "Count": 59, + "Permissions": [ + { + "Permission": "AgentIdentity.Create", + "Delegated": false, + "Application": true + }, + { + "Permission": "AgentIdentity.Create.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "AgentIdentity.CreateAsManager", + "Delegated": false, + "Application": true + }, + { + "Permission": "AgentIdentityBlueprint.Create", + "Delegated": false, + "Application": true + }, + { + "Permission": "AgentIdentityBlueprint.CreateAsManager", + "Delegated": false, + "Application": true + }, + { + "Permission": "AgentIdentityBlueprint.ReadWrite.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "AgentIdentityBlueprintPrincipal.Create", + "Delegated": false, + "Application": true + }, + { + "Permission": "AppRoleAssignment.ReadWrite.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "Application.ReadWrite.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "Application.ReadWrite.OwnedBy", + "Delegated": false, + "Application": true + }, + { + "Permission": "BitlockerKey.Read.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "Calendars.Read", + "Delegated": false, + "Application": true + }, + { + "Permission": "ChannelMessage.Read.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "ChannelMessage.Read.Group", + "Delegated": false, + "Application": true + }, + { + "Permission": "Chat.Read.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "Chat.ReadWrite.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "ConsentRequest.ReadWrite.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "CustomSecAttributeAssignment.ReadWrite.All", + "Delegated": true, + "Application": true + }, + { + "Permission": "CustomSecAttributeDefinition.ReadWrite.All", + "Delegated": true, + "Application": true + }, + { + "Permission": "DelegatedPermissionGrant.ReadWrite.All", + "Delegated": true, + "Application": true + }, + { + "Permission": "Device.ReadWrite.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "Device.Write.Restricted", + "Delegated": true, + "Application": true + }, + { + "Permission": "DeviceManagementConfiguration.Read.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "Directory.AccessAsUser.All", + "Delegated": true, + "Application": false + }, + { + "Permission": "Directory.ReadWrite.All", + "Delegated": true, + "Application": true + }, + { + "Permission": "Directory.Write.Restricted", + "Delegated": true, + "Application": true + }, + { + "Permission": "Domain.ReadWrite.All", + "Delegated": true, + "Application": true + }, + { + "Permission": "EduRoster.ReadWrite.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "EntitlementManagement.ReadWrite.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "Files.Read.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "Files.ReadWrite.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "Group.Create", + "Delegated": false, + "Application": true + }, + { + "Permission": "Group.ReadWrite.All", + "Delegated": true, + "Application": true + }, + { + "Permission": "Group.Write.Restricted", + "Delegated": true, + "Application": false + }, + { + "Permission": "GroupMember.ReadWrite.All", + "Delegated": true, + "Application": true + }, + { + "Permission": "IdentityProvider.ReadWrite.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "LifecycleManagement.ReadWrite.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "Organization.ReadWrite.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "Policy.ReadWrite.AuthenticationMethod", + "Delegated": false, + "Application": true + }, + { + "Permission": "Policy.ReadWrite.CrossTenantAccess", + "Delegated": false, + "Application": true + }, + { + "Permission": "Policy.ReadWrite.PermissionGrant", + "Delegated": false, + "Application": true + }, + { + "Permission": "Policy.ReadWrite.SecurityDefaults", + "Delegated": false, + "Application": true + }, + { + "Permission": "PrintJob.ReadWrite.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "PrivilegedAccess.ReadWrite.AzureAD", + "Delegated": false, + "Application": true + }, + { + "Permission": "PrivilegedAccess.ReadWrite.AzureResources", + "Delegated": false, + "Application": true + }, + { + "Permission": "RoleManagement.ReadWrite.All", + "Delegated": true, + "Application": false + }, + { + "Permission": "RoleManagement.ReadWrite.Directory", + "Delegated": true, + "Application": true + }, + { + "Permission": "Sites.FullControl.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "Sites.Manage.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "Sites.Read.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "Sites.ReadWrite.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "Tasks.ReadWrite.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "User-PasswordProfile.ReadWrite.All", + "Delegated": true, + "Application": true + }, + { + "Permission": "User.DeleteRestore.All", + "Delegated": true, + "Application": true + }, + { + "Permission": "User.EnableDisableAccount.All", + "Delegated": true, + "Application": true + }, + { + "Permission": "User.Invite.All", + "Delegated": false, + "Application": true + }, + { + "Permission": "User.ReadWrite.All", + "Delegated": true, + "Application": true + }, + { + "Permission": "UserAuthenticationMethod.Read.All", + "Delegated": true, + "Application": false + }, + { + "Permission": "UserAuthenticationMethod.ReadWrite.All", + "Delegated": true, + "Application": true + } + ] +} diff --git a/powershell/internal/services/entra/Get-MtEntraAgentHighRiskGraphPermission.ps1 b/powershell/internal/services/entra/Get-MtEntraAgentHighRiskGraphPermission.ps1 new file mode 100644 index 0000000000..e89cde8617 --- /dev/null +++ b/powershell/internal/services/entra/Get-MtEntraAgentHighRiskGraphPermission.ps1 @@ -0,0 +1,30 @@ +function Get-MtEntraAgentHighRiskGraphPermission { + <# + .SYNOPSIS + Returns the Microsoft Graph application permissions MT.1223 treats as high risk on agent identities. + + .DESCRIPTION + The single source of the MT.1223 permission list. Each key is a permission name and each value is + its attack path: Direct when the permission can grant privilege on its own, Indirect when it opens + a path to privilege. Get-MtEntraAgentHighRiskGraphPermissionFinding uses it to find the + permissions, and the agent blocked permissions drift test reads it so the two cannot drift apart. + #> + [CmdletBinding()] + [OutputType([hashtable])] + param() + + @{ + 'AdministrativeUnit.ReadWrite.All' = 'Indirect' + 'Application.ReadUpdate.All' = 'Indirect' + 'DeviceManagementConfiguration.ReadWrite.All' = 'Indirect' + 'DeviceManagementRBAC.ReadWrite.All' = 'Indirect' + 'Policy.ReadWrite.ConditionalAccess' = 'Direct' + 'PrivilegedAccess.ReadWrite.AzureADGroup' = 'Direct' + 'PrivilegedAssignmentSchedule.ReadWrite.AzureADGroup' = 'Direct' + 'PrivilegedEligibilitySchedule.ReadWrite.AzureADGroup' = 'Indirect' + 'RoleAssignmentSchedule.ReadWrite.Directory' = 'Direct' + 'RoleEligibilitySchedule.ReadWrite.Directory' = 'Indirect' + 'RoleManagementPolicy.ReadWrite.AzureADGroup' = 'Indirect' + 'RoleManagementPolicy.ReadWrite.Directory' = 'Indirect' + } +} diff --git a/powershell/internal/services/entra/Get-MtEntraAgentHighRiskGraphPermissionFinding.ps1 b/powershell/internal/services/entra/Get-MtEntraAgentHighRiskGraphPermissionFinding.ps1 index 464470a655..53c30dc759 100644 --- a/powershell/internal/services/entra/Get-MtEntraAgentHighRiskGraphPermissionFinding.ps1 +++ b/powershell/internal/services/entra/Get-MtEntraAgentHighRiskGraphPermissionFinding.ps1 @@ -3,20 +3,7 @@ [OutputType([pscustomobject])] param() - $RiskPaths = @{ - 'AdministrativeUnit.ReadWrite.All' = 'Indirect' - 'Application.ReadUpdate.All' = 'Indirect' - 'DeviceManagementConfiguration.ReadWrite.All' = 'Indirect' - 'DeviceManagementRBAC.ReadWrite.All' = 'Indirect' - 'Policy.ReadWrite.ConditionalAccess' = 'Direct' - 'PrivilegedAccess.ReadWrite.AzureADGroup' = 'Direct' - 'PrivilegedAssignmentSchedule.ReadWrite.AzureADGroup' = 'Direct' - 'PrivilegedEligibilitySchedule.ReadWrite.AzureADGroup' = 'Indirect' - 'RoleAssignmentSchedule.ReadWrite.Directory' = 'Direct' - 'RoleEligibilitySchedule.ReadWrite.Directory' = 'Indirect' - 'RoleManagementPolicy.ReadWrite.AzureADGroup' = 'Indirect' - 'RoleManagementPolicy.ReadWrite.Directory' = 'Indirect' - } + $RiskPaths = Get-MtEntraAgentHighRiskGraphPermission $AgentIdentities = @( Invoke-MtGraphRequest -ApiVersion 'v1.0' ` -RelativeUri 'servicePrincipals/microsoft.graph.agentIdentity' ` diff --git a/powershell/tests/general/AgentBlockedPermissionDrift.Tests.ps1 b/powershell/tests/general/AgentBlockedPermissionDrift.Tests.ps1 new file mode 100644 index 0000000000..f0a7f1c138 --- /dev/null +++ b/powershell/tests/general/AgentBlockedPermissionDrift.Tests.ps1 @@ -0,0 +1,81 @@ +BeforeDiscovery { + # MT.1223's list comes from the same function the check uses, so a change to the check's list + # is picked up here automatically. If Microsoft blocks any of these for agents, the permission + # is dead weight in the check. + Import-Module (Join-Path $PSScriptRoot '../../Maester.psd1') -Force + $script:Mt1223Permissions = @( + (& (Get-Module Maester) { Get-MtEntraAgentHighRiskGraphPermission }).Keys | Sort-Object + ) + + $snapshotPath = Join-Path $PSScriptRoot '../../internal/generated/AgentBlockedPermissions.json' + + # The snapshot is generated by build/Update-MtAgentBlockedPermissions.ps1 and + # checked in. If it is missing, the "Snapshot file should exist" test fails. + if (-not (Test-Path -LiteralPath $snapshotPath)) { + $script:SnapshotMissing = $true + $script:BlockedPermissions = @() + return + } + + $script:SnapshotMissing = $false + $snapshot = Get-Content -LiteralPath $snapshotPath -Raw | ConvertFrom-Json + $script:BlockedPermissions = $snapshot.Permissions +} + +Describe 'MT.1223 permission list vs. agent blocked permissions snapshot' { + + BeforeAll { + $snapshotPath = Join-Path $PSScriptRoot '../../internal/generated/AgentBlockedPermissions.json' + + if (-not (Test-Path -LiteralPath $snapshotPath)) { + return + } + + $snapshot = Get-Content -LiteralPath $snapshotPath -Raw | ConvertFrom-Json + $script:BlockedPermissions = $snapshot.Permissions + $script:SnapshotCount = $snapshot.Count + } + + It 'Snapshot file should exist' { + Test-Path -LiteralPath (Join-Path $PSScriptRoot '../../internal/generated/AgentBlockedPermissions.json') | Should -BeTrue -Because ` + 'AgentBlockedPermissions.json must be checked in. Run build/Update-MtAgentBlockedPermissions.ps1 to generate it.' + } + + It 'MT.1223 permission list should not be empty' -ForEach @(@{ PermissionCount = $script:Mt1223Permissions.Count }) { + $PermissionCount | Should -BeGreaterThan 0 -Because ` + 'Get-MtEntraAgentHighRiskGraphPermission returned no permissions, so the drift check below would run nothing.' + } + + # The generator stops on a broken table, so these check that the committed file is whole rather than its + # size: a fixed minimum here would fail CI on a real shrink by Microsoft that a reviewer had accepted. + It 'Snapshot should not be empty' -Skip:($script:SnapshotMissing) { + @($script:BlockedPermissions).Count | Should -BeGreaterThan 0 -Because ` + 'an empty snapshot would make every per-permission check below pass without checking anything.' + } + + It 'Snapshot Count should match the number of permissions it lists' -Skip:($script:SnapshotMissing) { + $script:SnapshotCount | Should -Be @($script:BlockedPermissions).Count -Because ` + 'a mismatch means the file was edited by hand or written incompletely. Regenerate it with build/Update-MtAgentBlockedPermissions.ps1.' + } + + It 'Snapshot should not list a permission twice' -Skip:($script:SnapshotMissing) { + $seen = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + $duplicates = @($script:BlockedPermissions | Where-Object { -not $seen.Add([string]$_.Permission) } | ForEach-Object { $_.Permission }) + $duplicates | Should -BeNullOrEmpty -Because 'the generator stops on a duplicate name, so one here means the file was edited by hand.' + } + + It ' should not be blocked for both Application and Delegated in the snapshot' -Skip:($script:SnapshotMissing) -ForEach @( + $script:Mt1223Permissions | ForEach-Object { @{ Permission = $_ } } + ) { + $entry = $script:BlockedPermissions | Where-Object { $_.Permission -eq $permission } + if ($null -eq $entry) { + # Permission isn't in the blocked list at all, which means it's grantable. Pass. + $true | Should -BeTrue + } else { + # MT.1223 reports a permission held as an application permission or as a delegated grant, so it can + # still fire while either one is allowed. Only a permission blocked for both can never fire. + ($entry.Application -and $entry.Delegated) | Should -BeFalse -Because ` + "'$permission' is now blocked for both Application and Delegated by Microsoft (per AgentBlockedPermissions.json). It should be removed from MT.1223's curated list because agents can no longer hold it either way." + } + } +}