在 Microsoft Perception 中設定並管理 Recon 代理程式

管理員可以使用本指南在 Microsoft Perception 中設定 Recon 代理程式、設定存取權限,以及啟動與檢視工作階段。 在入口網站建立代理程式身分,然後執行 PowerShell 指令碼以指派其唯讀權限。

開始之前,請確認已在你的租戶中設定好 Perception。 檢視先決條件以了解訂閱與存取需求。

Prerequisites

建議使用下列產品以協助改善 Recon Agent 的發現結果,但並非使用 Agent 的必要條件:

  • Microsoft Defender 雲端安全性態勢管理(Defender CSPM)
  • Microsoft Defender for Servers 方案 2

所需的權限

對於特權設定任務,如有提供,請使用透過 Microsoft Entra Privileged Identity Management(PIM) 的即時存取。 只啟用執行任務所需的角色。

代理程式的存取由 Microsoft Defender 中現有的安全角色所控制:

Role 您可以執行的作業
安全管理員 設定並設定 Recon 代理程式,包括其身份與權限,並移除代理程式。 您組織中至少有一位使用者需要此角色。
Security Reader 啟動工作階段、檢視及互動代理程式工作階段,以及查看工作階段詳細資訊。

若要委派代理程式設定,請請您的 Microsoft Entra 管理員指派安全性管理員。授予代理程式 Microsoft Graph 與 Azure 權限時,需要代理程式權限中列出的額外角色。

代理程式權限

人類角色控制誰能設定或使用偵察代理程式。 代理程式權限授權代理程式讀取 Microsoft Entra ID 目錄資訊及 Azure 資源資訊。

權限指派腳本授予 Microsoft Graph 應用程式權限及 Azure 基於角色的存取控制(RBAC)角色。 授予每個權限集的管理員需要具備相應的角色:

權限設定 授予權限所需的角色 授予代理程式的權限
Microsoft Graph 應用程式權限 Microsoft Entra ID 中的特權角色管理員。 User.Read.All、Organization.Read.All、GroupMember.Read.All、Application.Read.All、DelegatedPermissionGrant.Read.All、Policy.Read.All、RoleManagement.Read.Directory和AuditLog.Read.All。
Azure 訂用帳戶範圍的 RBAC 角色 每個目標訂閱的角色型 存取控制 管理員。 Reader、金鑰保存庫 Reader、Log Analytics Reader 以及 Security Reader。

使用 PowerShell 設定 Recon 代理程式

在 Perception 中建立代理程式身分,然後使用權限指派指令碼授予 代理程式權限中列出的權限。

準備存取權與工具

在執行腳本之前,請先準備好 PowerShell 和 Azure CLI。 使用具有 Security Admin 的帳號來設定代理程式。 指派權限還需要 Microsoft Graph 的Privileged Role Administrator,以及每個目標訂閱上的Role Based 存取控制 Administrator。

建立識別並指派權限

若要啟用 Recon 代理程式,請建立其身份並指派唯讀權限:

Note

Recon Agent 使用的是代理身份,而非代理使用者身份。 代理程式使用者身份不支援 Recon 代理程式的唯讀操作。

  1. 作為具有安全性管理員角色的使用者,請登入 Microsoft Defender 入口網站,並前往感知>代理程式。

  2. 在「準備設定」中,找到 Recon Agent,然後選擇「設定」。 建立一個新的代理身份。 有關一般設定資訊,請參閱「設定代理程式」。

  3. 在 Microsoft Defender 入口網站中,前往 感知>代理程式,並開啟 Recon Agent。

  4. 從 「身分識別」 區段複製代理程式的物件 ID。 使用此值作為腳本的 AgentId 參數。

  5. 將 權限指派指令碼 複製到名為 ReconAgent-Permissions.ps1的檔案中。

  6. 確認 Azure CLI 已以有權授與所選權限集的帳戶登入。 請在 PowerShell 中執行包含租戶 ID、代理物件 ID 及目標訂閱 ID 的腳本。 若要授予兩個權限集,請使用「準備存取與工具」中列出的 Microsoft Entra 與 Azure 角色的帳戶:

    .\ReconAgent-Permissions.ps1 -TenantId "<tenant-id>" -AgentId "<agent-object-id>" -Permissions All -SubscriptionId "<subscription-id>"
    

    如果不同管理員授予這兩個權限集,請讓每位管理員只用其授權帳戶執行相應指令:

    .\ReconAgent-Permissions.ps1 -TenantId "<tenant-id>" -AgentId "<agent-object-id>" -Permissions Graph
    .\ReconAgent-Permissions.ps1 -TenantId "<tenant-id>" -AgentId "<agent-object-id>" -Permissions Azure -SubscriptionId "<subscription-id>"
    

    SubscriptionId 接受一個或多個訂閱,且為 All 或 Azure 所必需。 腳本會在需要時提示 Azure CLI 登入。

  7. 在啟動工作階段前,請檢視權限指派結果並解決所報告的失敗。

  8. 在入口網站完成代理程式設定。

權限指派指令碼

將下列指令碼另存為ReconAgent-Permissions.ps1,以授予 Recon Agent 的 Microsoft Graph 應用程式權限及 Azure RBAC 角色。

<#
.SYNOPSIS
    Assigns the Graph API permissions and Azure RBAC roles required by Recon.

.DESCRIPTION
    Assigns the following Graph API application permissions:
      - User.Read.All
      - Organization.Read.All
      - GroupMember.Read.All
      - Application.Read.All
      - DelegatedPermissionGrant.Read.All
      - Policy.Read.All
      - RoleManagement.Read.Directory
      - AuditLog.Read.All

        Assigns the following Azure RBAC roles at subscription scope:
            - Reader
            - Key Vault Reader
            - Log Analytics Reader
            - Security Reader

.PARAMETER TenantId
    The Tenant Id.

.PARAMETER AgentId
    The Entra ID Object ID (principal ID) of the Agent Identity to assign roles to. To get this value,
    1. Go to the Microsoft Defender portal at https://security.microsoft.com/ -> Perception -> Agents
    2. Search for the Recon Agent and click on it to open the agent details page
    3. Copy the value under the "Identity" section

.PARAMETER Permissions
    Permission sets to assign: All, Azure, or Graph. Defaults to All.

.PARAMETER SubscriptionId
    One or more Azure subscriptions to receive the Recon RBAC assignments.
    Values can be comma-delimited, space-delimited, or supplied as an array.
    Required when Permissions is All or Azure.

Example: .\ReconAgent-Permissions.ps1 -TenantId <TenandId> -AgentId <AgentId> -Permissions All -SubscriptionId <SubscriptionId>
Example: .\ReconAgent-Permissions.ps1 -TenantId <TenandId> -AgentId <AgentId> -Permissions Azure -SubscriptionId <SubscriptionId1>, <SubscriptionId2>

#>

[CmdletBinding()]
param(
    [Parameter(Mandatory = $true)]
    [ValidatePattern('^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$')]
    [string]$TenantId,

    [Parameter(Mandatory = $true)]
    [ValidatePattern('^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$')]
    [string]$AgentId,

    [ValidateSet('All', 'Azure', 'Graph')]
    [string]$Permissions = 'All',

    [string[]]$SubscriptionId,

    [Parameter(ValueFromRemainingArguments = $true, DontShow = $true)]
    [string[]]$AdditionalSubscriptionId
)

$ErrorActionPreference = 'Stop'

$subscriptionIds = @(@($SubscriptionId) + @($AdditionalSubscriptionId) |
    ForEach-Object { $_ -split '[,\s]+' } |
    Where-Object { -not [string]::IsNullOrWhiteSpace($_) } |
    ForEach-Object { $_.Trim() } |
    Sort-Object -Unique)

if ($Permissions -in @('All', 'Azure') -and $subscriptionIds.Count -eq 0) {
    throw '-SubscriptionId requires at least one subscription GUID when -Permissions is All or Azure.'
}

foreach ($id in $subscriptionIds) {
    if ($id -notmatch '^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$') {
        throw "Invalid subscription ID '$id'. Supply one or more GUIDs separated by commas or spaces."
    }
}

function Invoke-AzJson {
    param(
        [Parameter(Mandatory)]
        [string[]]$Arguments
    )

    $output = & az @Arguments 2>&1
    if ($LASTEXITCODE -ne 0) {
        throw "az $($Arguments -join ' ') failed: $($output -join [Environment]::NewLine)"
    }

    if (-not $output) {
        return $null
    }

    return ($output -join [Environment]::NewLine) | ConvertFrom-Json | Write-Output
}

function Test-AzureActionAllowed {
    param(
        [Parameter(Mandatory)]
        [string]$Scope,

        [Parameter(Mandatory)]
        [string]$Action
    )

    $permissionsResponse = Invoke-AzJson -Arguments @(
        'rest', '--method', 'GET',
        '--url', "https://management.azure.com$Scope/providers/Microsoft.Authorization/permissions?api-version=2022-04-01",
        '--output', 'json'
    )

    foreach ($permission in @($permissionsResponse.value)) {
        $isAllowed = @($permission.actions | Where-Object {
            $Action -like [string]$_
        }).Count -gt 0
        $isExcluded = @($permission.notActions | Where-Object {
            $Action -like [string]$_
        }).Count -gt 0

        if ($isAllowed -and -not $isExcluded) {
            return $true
        }
    }

    return $false
}

function Write-Section {
    param([string]$Title)

    Write-Host ''
    Write-Host $Title -ForegroundColor Cyan
    Write-Host ('-' * $Title.Length) -ForegroundColor DarkGray
}

function Write-Step {
    param(
        [string]$Message,
        [ValidateSet('Info', 'OK', 'Warn', 'Err', 'Step')]
        [string]$Level = 'Info'
    )

    $color = switch ($Level) {
        'OK' { 'Green' }
        'Warn' { 'Yellow' }
        'Err' { 'Red' }
        'Step' { 'Cyan' }
        default { 'Gray' }
    }
    $prefix = switch ($Level) {
        'OK' { '[ OK ]' }
        'Warn' { '[WARN]' }
        'Err' { '[FAIL]' }
        'Step' { '[STEP]' }
        default { '[ -- ]' }
    }

    if ($Level -eq 'Step') {
        Write-Host ''
    }

    Write-Host (
        '{0} {1} {2}' -f
        (Get-Date -Format 'HH:mm:ss'), $prefix, $Message
    ) -ForegroundColor $color
}

function Write-ConsoleResults {
    param([object[]]$Results)

    Write-Section 'Granular Recon permission assignment'
    Write-Step `
        -Message "Agent: Recon, EntraObjectId: $AgentId" `
        -Level Step

    foreach ($result in @($Results |
        Sort-Object PermissionSet, SubscriptionId, Role)) {
        $category = if ($result.PermissionSet -eq 'Graph') {
            'Microsoft Graph permission'
        }
        else {
            'Azure RBAC'
        }
        $value = if ($result.PermissionSet -eq 'Azure') {
            "{0} ({1})" -f $result.Role, $result.Scope
        }
        else {
            "Graph $($result.Role)"
        }
        $assignmentResult = switch ($result.Status) {
            'Already assigned' { 'Already existed' }
            'Assigned' { 'Added' }
            default { $result.Status }
        }
        $level = if ($result.Status -eq 'Failed') { 'Err' } else { 'OK' }

        Write-Step `
            -Message "$category`: $value - $assignmentResult" `
            -Level $level
        if ($result.Status -eq 'Failed' -and
            -not [string]::IsNullOrWhiteSpace([string]$result.Details)) {
            Write-Host ("       Details:  {0}" -f $result.Details) `
                -ForegroundColor DarkGray
        }
    }
}

if (-not (Get-Command az -ErrorAction SilentlyContinue)) {
    throw 'Azure CLI is required but the az command was not found.'
}

Write-Host ''
Write-Host 'Recon Agent Permission Assignment' -ForegroundColor Cyan
Write-Host 'Assigns required Microsoft Graph and Azure RBAC permissions' `
    -ForegroundColor DarkGray
Write-Host "Permission set: $Permissions"
Write-Host "Tenant: $TenantId"

# Ensure Azure CLI is signed in to the requested tenant.
$account = $null
try {
    $account = Invoke-AzJson -Arguments @('account', 'show', '--output', 'json')
}
catch {
    # No usable cached Azure CLI session.
}

if (-not $account -or [string]$account.tenantId -ne $TenantId) {
    & az login --tenant $TenantId --allow-no-subscriptions | Out-Null
    if ($LASTEXITCODE -ne 0) {
        throw "Azure CLI sign-in to tenant $TenantId failed."
    }
}

$agentServicePrincipal = Invoke-AzJson -Arguments @(
    'rest', '--method', 'GET',
    '--url', "https://graph.microsoft.com/v1.0/servicePrincipals/$AgentId",
    '--output', 'json'
)
if ([string]$agentServicePrincipal.id -ne $AgentId) {
    throw "Agent service principal $AgentId could not be resolved in tenant $TenantId."
}

$results = @()

if ($Permissions -in @('All', 'Graph')) {
    $graphToken = & az account get-access-token `
        --tenant $TenantId `
        --resource-type ms-graph `
        --query accessToken `
        --output tsv 2>&1
    if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace([string]$graphToken)) {
        throw "Unable to acquire a Microsoft Graph token: $($graphToken -join [Environment]::NewLine)"
    }
    $graphHeaders = @{
        Authorization = "Bearer $([string]$graphToken)"
        Accept = 'application/json'
    }

    # Graph API roles (AppRoleId -> Role Name)
    $graphRoleIds = @{
        'df021288-bdef-4463-88db-98f22de89214' = 'User.Read.All'
        '498476ce-e0fe-48b0-b801-37ba7e2685c6' = 'Organization.Read.All'
        '98830695-27a2-44f7-8c18-0c3ebc9698f6' = 'GroupMember.Read.All'
        '9a5d68dd-52b0-4cc2-bd40-abcf44ac3a30' = 'Application.Read.All'
        '81b4724a-58aa-41c1-8a55-84ef97466587' = 'DelegatedPermissionGrant.Read.All'
        '246dd0d5-5bd0-4def-940b-0421030a5b68' = 'Policy.Read.All'
        '483bed4a-2ad3-4361-a73b-c83ccdbdc53c' = 'RoleManagement.Read.Directory'
        'b0afded3-3588-46d8-8b3d-9842eff778da' = 'AuditLog.Read.All'
    }

    $graphServicePrincipal = Invoke-AzJson -Arguments @(
        'ad', 'sp', 'show',
        '--id', '00000003-0000-0000-c000-000000000000',
        '--output', 'json'
    )
    $GraphObjectId = [string]$graphServicePrincipal.id
    if ([string]::IsNullOrWhiteSpace($GraphObjectId)) {
        throw "Microsoft Graph service principal could not be resolved in tenant $TenantId."
    }

    $existingAssignmentsResponse = Invoke-AzJson -Arguments @(
        'rest', '--method', 'GET',
        '--url', "https://graph.microsoft.com/v1.0/servicePrincipals/$AgentId/appRoleAssignments",
        '--output', 'json'
    )
    $existingAssignments = @($existingAssignmentsResponse.value)

    foreach ($rid in $graphRoleIds.Keys) {
        $roleName = $graphRoleIds[$rid]
        $existingAssignment = $existingAssignments |
            Where-Object {
                [string]$_.resourceId -eq $GraphObjectId -and
                [string]$_.appRoleId -eq $rid
            } |
            Select-Object -First 1

        if ($existingAssignment) {
            $results += [pscustomobject]@{
                PermissionSet = 'Graph'
                Role = $roleName
                Status = 'Already assigned'
                Details = ''
            }
            continue
        }

        $body = @{
            principalId = $AgentId
            resourceId = $GraphObjectId
            appRoleId = $rid
        } | ConvertTo-Json -Compress

        try {
            Invoke-RestMethod `
                -Method Post `
                -Uri "https://graph.microsoft.com/v1.0/servicePrincipals/$AgentId/appRoleAssignments" `
                -Headers $graphHeaders `
                -ContentType 'application/json' `
                -Body $body | Out-Null
            $results += [pscustomobject]@{
                PermissionSet = 'Graph'
                Role = $roleName
                Status = 'Assigned'
                Details = ''
            }
        }
        catch {
            $details = if ($_.ErrorDetails.Message) {
                $_.ErrorDetails.Message
            }
            else {
                $_.Exception.Message
            }
            $results += [pscustomobject]@{
                PermissionSet = 'Graph'
                Role = $roleName
                Status = 'Failed'
                Details = $details
            }
        }
    }
}

if ($Permissions -in @('All', 'Azure')) {
    $azureRoles = @(
        'Reader'
        'Key Vault Reader'
        'Log Analytics Reader'
        'Security Reader'
    )

    foreach ($currentSubscriptionId in $subscriptionIds) {
        $subscription = Invoke-AzJson -Arguments @(
            'account', 'show',
            '--subscription', $currentSubscriptionId,
            '--output', 'json'
        )
        if ([string]$subscription.tenantId -ne $TenantId) {
            throw "Subscription $currentSubscriptionId belongs to tenant $($subscription.tenantId), not requested tenant $TenantId."
        }

        & az account set --subscription $currentSubscriptionId
        if ($LASTEXITCODE -ne 0) {
            throw "Unable to select Azure subscription $currentSubscriptionId."
        }

        $scope = "/subscriptions/$currentSubscriptionId"
        try {
            $canWriteRoleAssignments = Test-AzureActionAllowed `
                -Scope $scope `
                -Action 'Microsoft.Authorization/roleAssignments/write'
            if (-not $canWriteRoleAssignments) {
                throw "The signed-in account does not have Microsoft.Authorization/roleAssignments/write at $scope. Assign Owner, User Access Administrator, or Role Based Access Control Administrator at this scope or a parent scope."
            }
        }
        catch {
            $results += [pscustomobject]@{
                PermissionSet = 'Azure'
                SubscriptionId = $currentSubscriptionId
                Scope = $scope
                Role = 'Role assignment preflight'
                Status = 'Failed'
                Details = $_.Exception.Message
            }
            continue
        }

        foreach ($roleName in $azureRoles) {
            try {
                $existingRoleAssignments = @(Invoke-AzJson -Arguments @(
                    'role', 'assignment', 'list',
                    '--assignee-object-id', $AgentId,
                    '--role', $roleName,
                    '--scope', $scope,
                    '--output', 'json'
                ))

                if ($existingRoleAssignments.Count -gt 0) {
                    $results += [pscustomobject]@{
                        PermissionSet = 'Azure'
                        SubscriptionId = $currentSubscriptionId
                        Scope = $scope
                        Role = $roleName
                        Status = 'Already assigned'
                        Details = ''
                    }
                    continue
                }

                Invoke-AzJson -Arguments @(
                    'role', 'assignment', 'create',
                    '--assignee-object-id', $AgentId,
                    '--assignee-principal-type', 'ServicePrincipal',
                    '--role', $roleName,
                    '--scope', $scope,
                    '--output', 'json'
                ) | Out-Null

                $results += [pscustomobject]@{
                    PermissionSet = 'Azure'
                    SubscriptionId = $currentSubscriptionId
                    Scope = $scope
                    Role = $roleName
                    Status = 'Assigned'
                    Details = ''
                }
            }
            catch {
                $results += [pscustomobject]@{
                    PermissionSet = 'Azure'
                    SubscriptionId = $currentSubscriptionId
                    Scope = $scope
                    Role = $roleName
                    Status = 'Failed'
                    Details = $_.Exception.Message
                }
            }
        }
    }
}

Write-ConsoleResults -Results $results
Write-Host

if ($results.Status -contains 'Failed') {
    exit 1
}

exit 0

允許其他使用者存取

請請您的 Microsoft Entra 管理員將 Security Reader 或 Security Admin 指派給需要使用代理程式的人。 這些角色讓他們可以在設定完成後查看並互動工作階段。

啟動偵察特工會議

如需有關可用工作階段入口點的資訊,請參閱 開始新的工作階段。

從 「選擇 Recon 使用案例」中選擇劇本。 以下步驟示範如何啟動 「評估身份風險 」工作階段:

  1. 在導覽窗格中,選取 感知>工作階段。

  2. 選取 新工作階段。

  3. 選擇 「評估身份風險 」操作手冊。

    Microsoft Perception 劇本中啟動新工作階段的選項截圖。

    「需要額外輸入」窗格會開啟。 需要輸入兩項資料:

    Field Description
    Azure 訂閱 Azure 訂閱 ID 或名稱,以設定會話範圍。 每次課程限額訂閱一次。 管理員會在設定 Recon Agent 時預先設定這個清單,你只能使用預先設定的訂閱。
    受控識別 選取受控識別。

    評估身份風險手冊的螢幕截圖,其中包含虛構的訂閱與受管理身份名稱。

    Note

    當您啟動 「識別攻擊路徑」 會話時,訂閱選擇器會列出已登入使用者可用的訂閱,而非 Recon Agent 應用程式。 該使用者需要對整個所選訂閱的讀取權限。 工作階段開始後,Recon 會使用自己的身分進行偵察。

  4. 填寫兩個欄位並選擇 開始會話。

遊戲以 運行 狀態開始。 代理程式在擬定任務清單並開始執行工作時,會顯示其進度。

監控會話進度

當工作階段執行時,右側窗格會顯示:

  • 概覽:顯示會話摘要及當前狀態。
  • 進度:追蹤已完成的步驟。 例如,任務完成時,值會從 0/1 變為 1/1 。
  • Recon Agent:識別本次工作階段的活動代理。
  • 輸入:顯示您提供的目標環境與使用情境。
  • 輸出:列出目前產生的檔案,並隨工作階段進行更新。

如果工作階段回報收集失敗或權限不足,請先處理這些限制,再對受影響範圍下結論。

了解報告

根據你設定要回答的問題,檢視報告:

  1. 檢查範圍與限制。 檢視任何所述假設、缺失資料或失敗的收集步驟。 不要把一次工作階段當成對你環境的全面評估。
  2. 檢查證據。 檢視發現中引用的資源、身份、權限與關係。 在使用重大主張做出安全決策前,請先驗證其內容。
  3. 將觀察與假設分開。 潛在的攻擊路徑並不代表攻擊者已經利用該路徑,或不代表利用會成功。
  4. 決定哪些事需要追蹤。 辨識哪些發現需要進一步調查、由資源或身分擁有者審查,或是個別授權的測試。

Important

Recon Agent 的輸出內容由 AI 產生,並以可透過唯讀 API 存取取得的資料為基礎。 在使用調查結果規劃修復或風險溝通前,務必檢查其準確性。 報告中附有橫幅:「 AI 生成內容可能不正確。請檢查準確性。」

下一步