{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "workspace": {
            "type": "String"
        }
    },
    "resources": [
        {
            "id": "[concat(resourceId('Microsoft.OperationalInsights/workspaces/providers', parameters('workspace'), 'Microsoft.SecurityInsights'),'/alertRules/microsoft-entra-id-powershell-accessing-non-entra-id-resources')]",
            "name": "[concat(parameters('workspace'),'/Microsoft.SecurityInsights/microsoft-entra-id-powershell-accessing-non-entra-id-resources')]",
            "type": "Microsoft.OperationalInsights/workspaces/providers/alertRules",
            "kind": "Scheduled",
            "apiVersion": "2023-12-01-preview",
            "properties": {
                "displayName": "Entra ID PowerShell Client - Non-Directory Access Risk",
                "description": "Scores every successful token issuance to the retired Entra ID (Azure AD) PowerShell public client for any audience outside the directory APIs. The module was deprecated on 30 March 2024, lost support on 30 March 2025 and was switched off during the second half of 2025, so remaining use of this client id is either a legacy script or an attacker borrowing a pre-consented public client for token abuse. Weighted signals rank each event by audience sensitivity, first use, Identity Protection risk, guest status and directory roles, so known relics stay silent while resurrections and token phishing fire.\n\nTABLES: SigninLogs, AADNonInteractiveUserSignInLogs, IdentityInfo\nCONNECTORS: Microsoft Entra ID (both the interactive and non-interactive sign in streams must be enabled); UEBA (Behavior Analytics) populates IdentityInfo\nLICENSE: Entra ID P1 for sign in log export. P2 adds the Identity Protection risk signals, which degrade to silence without it. UEBA is required for IdentityInfo; role and department enrichment degrades to silence without it.\n\nTUNING:\n1. Query period must be P14D - the 14d client usage baseline only resolves if the rule looks back that far.\n2. Run the query for 14 days without the score gate and summarise by UserPrincipalName; migrate what you find and add only reviewed identities to TrustedIdentities.\n3. FireThreshold defaults to 5; a first use of the client fires on its own merit, established identities need risk, guest or role evidence stacked on a sensitive audience.\n4. Extend SensitiveResources with audiences you guard, for example Azure DevOps 499b84ac-1321-427f-aa17-267ca6975798.\n5. ClientAppId can be repointed at another legacy public client, but every client needs its own DirectoryResources equivalent and its own expected audience review.\n\nKNOWN FALSE POSITIVES:\n1. Legacy scripts that hardcode this pre-consented client id to mint ARM or Key Vault tokens - established identities score 4 and stay silent; review and migrate rather than trusting them.\n2. First run of an old runbook by a new engineer - fires once as a first use; that alert is correct, investigate and migrate the script.\n3. Identity Protection medium risk on an established member - scores 4 and stays silent; risk stacks, it never carries the alert alone.\n\nINVESTIGATION STEPS:\n1. Confirm with the identity owner whether they ran a script or tool at StartTime.\n2. Review the session context: IP address, user agent and RiskState against the identity's normal activity.\n3. Follow the token audience: for Azure Service Management review AzureActivity by this identity since StartTime, for Key Vault review vault data plane access.\n4. Hunt the same identity across other legacy public client ids for token pivoting.\n5. If malicious, revoke sessions and refresh tokens, reset credentials and review registered MFA methods before restoring access.\n\nBLIND SPOTS:\nAttackers can switch to sibling public clients such as the Azure CLI or Microsoft Office ids; Microsoft Graph access through this client is out of scope by design; a compromised identity already in the baseline hitting non sensitive audiences scores 4 unless Identity Protection flags it; service principal token abuse lives in AADServicePrincipalSignInLogs; identities quiet for more than 14 days refire as first use.\n\nAuthor: Bartosz Wysocki | https://www.itprofessor.cloud\nVersion: 1.0 | 2026-07-11",
                "severity": "Medium",
                "enabled": true,
                "query": "// =====================================================================\n// Entra ID PowerShell Client - Non-Directory Access Risk\n// =====================================================================\n// Tables  : SigninLogs, AADNonInteractiveUserSignInLogs, IdentityInfo\n// License : Entra ID P1; P2 adds Identity Protection risk signals; UEBA required for IdentityInfo (both degrade to silence without them)\n// Tuning  : see rule description for full tuning notes\n// Author  : Bartosz Wysocki | itprofessor.cloud\n// Version : 1.0 | 2026-07-11\n// =====================================================================\nlet DetectionWindow = 1h;          // rule runs hourly; only events inside the last run interval are scored\nlet BaselineWindow = 14d;          // client usage history depth; must equal the rule query period\nlet IdentityLookback = 14d;        // how far back IdentityInfo snapshots are read\nlet FireThreshold = 5;             // minimum RiskScore for a row to alert\nlet ClientAppId = \"1b730954-1685-4b74-9bfd-dac224a7b894\"; // retired Entra ID (Azure AD) PowerShell public client\nlet TrustedIdentities = dynamic([]); // UPNs of reviewed legacy identities still permitted to use this client\nlet DirectoryResources = dynamic([\"00000002-0000-0000-c000-000000000000\", \"00000003-0000-0000-c000-000000000000\"]); // AAD Graph and Microsoft Graph, the designed targets of this client\n// Scoring weights - no signal fires alone, pairs clear the threshold, soft signals only stack\nlet W_NonDirectoryAccess = 2;      // floor: the retired directory client reached a non-directory API\nlet W_NewUserForClient = 3;        // identity has no history with this client before the detection window\nlet W_SensitiveResource = 2;       // token audience is a control or data plane API worth guarding\nlet W_HighRiskSignIn = 3;          // Identity Protection scored the sign in high risk\nlet W_MediumRiskSignIn = 2;        // Identity Protection scored the sign in medium risk\nlet W_GuestUser = 2;               // token belongs to a B2B guest identity\nlet W_PrivilegedUser = 2;          // identity holds Entra directory roles per IdentityInfo\n// Sensitive first party audiences - extend with the APIs you guard\nlet SensitiveResources = datatable(ResourceIdentity: string, ResourceCategory: string) [\n    \"797f4846-ba00-4fd7-ba43-dac1f8f63013\", \"Azure Service Management\",\n    \"cfa8b339-82a2-471a-a3c9-0fc0be7a4093\", \"Azure Key Vault\",\n    \"e406a681-f3d4-42a8-90b6-c2b029497af1\", \"Azure Storage\",\n    \"00000002-0000-0ff1-ce00-000000000000\", \"Exchange Online\",\n    \"00000003-0000-0ff1-ce00-000000000000\", \"SharePoint Online\"\n];\n// Helper - normalise both sign in tables to one schema\nlet ClientTokenEvents = (tableName: string) {\n    table(tableName)\n    | where TimeGenerated > ago(BaselineWindow)\n    | where AppId =~ ClientAppId\n    | where ResultType == \"0\"\n    | project TimeGenerated, UserId = tolower(UserId), UserPrincipalName,\n        UserDisplayName = column_ifexists(\"UserDisplayName\", \"\"),\n        UserType = column_ifexists(\"UserType\", \"\"),\n        IPAddress, UserAgent, ResourceIdentity = tolower(ResourceIdentity),\n        ResourceDisplayName, RiskLevelDuringSignIn, RiskState, SourceTable = tableName\n};\n// Fourteen days of successful token issuance to the client, read twice, so materialise it once\nlet ClientSignIns = materialize(union isfuzzy=true\n    (ClientTokenEvents(\"SigninLogs\")),\n    (ClientTokenEvents(\"AADNonInteractiveUserSignInLogs\")));\n// Lookup - identities that used the client before the detection window, so events cannot baseline themselves\nlet BaselineUsers = ClientSignIns\n    | where TimeGenerated between (ago(BaselineWindow) .. ago(DetectionWindow))\n    | distinct UserId\n    | extend SeenBefore = true;\n// Guard - the first use signal only fires when the baseline actually holds data\nlet HasHistory = toscalar(BaselineUsers | summarize count());\n// Lookup - latest identity snapshot per object id, for role and department enrichment\nlet IdentitySnapshot = IdentityInfo\n    | where TimeGenerated > ago(IdentityLookback)\n    | extend AccountObjectId = tolower(AccountObjectId)\n    | summarize arg_max(TimeGenerated, AssignedRoles, Department, JobTitle) by AccountObjectId\n    | project AccountObjectId, AssignedRoles, Department, JobTitle;\n// Main pipeline - one row per identity, audience and source address, scored on positive evidence only\nClientSignIns\n| where TimeGenerated > ago(DetectionWindow)\n| where ResourceIdentity !in (DirectoryResources)\n| where UserPrincipalName !in~ (TrustedIdentities)\n| summarize StartTime = min(TimeGenerated), EndTime = max(TimeGenerated), Events = count(),\n    arg_max(TimeGenerated, UserDisplayName, UserType, UserAgent, ResourceDisplayName, RiskLevelDuringSignIn, RiskState, SourceTable)\n    by UserId, UserPrincipalName, ResourceIdentity, IPAddress\n| join kind=leftouter (BaselineUsers) on UserId\n| join kind=leftouter (IdentitySnapshot) on $left.UserId == $right.AccountObjectId\n| lookup kind=leftouter (SensitiveResources) on ResourceIdentity\n| extend IsGuest = UserType =~ \"Guest\" or UserPrincipalName contains \"#EXT#\"\n| extend S_NonDirectory = W_NonDirectoryAccess\n| extend S_NewUser = iff(HasHistory > 0 and isnull(SeenBefore), W_NewUserForClient, 0)\n| extend S_Sensitive = iff(isnotempty(ResourceCategory), W_SensitiveResource, 0)\n| extend S_HighRisk = iff(RiskLevelDuringSignIn =~ \"high\", W_HighRiskSignIn, 0)\n| extend S_MediumRisk = iff(RiskLevelDuringSignIn =~ \"medium\", W_MediumRiskSignIn, 0)\n| extend S_Guest = iff(IsGuest, W_GuestUser, 0)\n| extend S_Privileged = iff(array_length(set_difference(todynamic(AssignedRoles), dynamic([\"\"]))) > 0, W_PrivilegedUser, 0)\n| extend RiskScore = S_NonDirectory + S_NewUser + S_Sensitive + S_HighRisk + S_MediumRisk + S_Guest + S_Privileged\n| where RiskScore >= FireThreshold\n| extend Risk_1 = \"Retired directory client reached a non-directory API\"\n| extend Risk_2 = iff(S_NewUser > 0, \"First use of this client by this identity in the baseline window\", \"\")\n| extend Risk_3 = iff(S_Sensitive > 0, strcat(\"Sensitive resource: \", ResourceCategory), \"\")\n| extend Risk_4 = iff(S_HighRisk > 0, \"Identity Protection high risk sign in\", \"\")\n| extend Risk_5 = iff(S_MediumRisk > 0, \"Identity Protection medium risk sign in\", \"\")\n| extend Risk_6 = iff(S_Guest > 0, \"Guest identity\", \"\")\n| extend Risk_7 = iff(S_Privileged > 0, strcat(\"Identity holds directory roles: \", tostring(AssignedRoles)), \"\")\n| extend RiskIndicators = trim(@\"\\s\\|\\s*$\", strcat(\n    iff(isnotempty(Risk_1), strcat(Risk_1, \" | \"), \"\"),\n    iff(isnotempty(Risk_2), strcat(Risk_2, \" | \"), \"\"),\n    iff(isnotempty(Risk_3), strcat(Risk_3, \" | \"), \"\"),\n    iff(isnotempty(Risk_4), strcat(Risk_4, \" | \"), \"\"),\n    iff(isnotempty(Risk_5), strcat(Risk_5, \" | \"), \"\"),\n    iff(isnotempty(Risk_6), strcat(Risk_6, \" | \"), \"\"),\n    iff(isnotempty(Risk_7), strcat(Risk_7, \" | \"), \"\")))\n| extend GuestHomeDomain = iff(IsGuest, extract(@\"_([^_]+)#EXT#\", 1, UserPrincipalName), \"\")\n| extend ResourceName = iff(isnotempty(ResourceDisplayName), ResourceDisplayName, ResourceIdentity)\n| extend Name = tostring(split(UserPrincipalName, \"@\", 0)[0])\n| extend UPNSuffix = tostring(split(UserPrincipalName, \"@\", 1)[0])\n| project StartTime, EndTime, Events, UserPrincipalName, UserDisplayName, UserId, Name, UPNSuffix,\n    IPAddress, UserAgent, ResourceName, ResourceIdentity, ResourceCategory,\n    RiskLevel = RiskLevelDuringSignIn, RiskState, GuestHomeDomain, Department, JobTitle,\n    DirectoryRoles = tostring(AssignedRoles), SourceTable, RiskScore, RiskIndicators\n| sort by RiskScore desc, EndTime desc",
                "queryFrequency": "PT1H",
                "queryPeriod": "P14D",
                "triggerOperator": "GreaterThan",
                "triggerThreshold": 0,
                "suppressionDuration": "PT1H",
                "suppressionEnabled": false,
                "startTimeUtc": null,
                "tactics": [
                    "InitialAccess",
                    "LateralMovement"
                ],
                "techniques": [
                    "T1078",
                    "T1550"
                ],
                "subTechniques": [
                    "T1078.004",
                    "T1550.001"
                ],
                "alertRuleTemplateName": null,
                "incidentConfiguration": {
                    "createIncident": true,
                    "groupingConfiguration": {
                        "enabled": true,
                        "reopenClosedIncident": false,
                        "lookbackDuration": "PT6H",
                        "matchingMethod": "Selected",
                        "groupByEntities": [
                            "Account"
                        ],
                        "groupByAlertDetails": null,
                        "groupByCustomDetails": null
                    }
                },
                "eventGroupingSettings": {
                    "aggregationKind": "AlertPerResult"
                },
                "alertDetailsOverride": {
                    "alertDisplayNameFormat": "Retired Entra PowerShell client: {{UserPrincipalName}} accessed {{ResourceName}}",
                    "alertDescriptionFormat": "{{UserPrincipalName}} obtained tokens for {{ResourceName}} using the retired Entra ID PowerShell public client across {{Events}} sign in events. RiskIndicators in the custom details lists the signals."
                },
                "customDetails": {
                    "Resource": "ResourceName",
                    "ResourceId": "ResourceIdentity",
                    "ResourceTier": "ResourceCategory",
                    "Events": "Events",
                    "RiskLevel": "RiskLevel",
                    "RiskState": "RiskState",
                    "UserAgent": "UserAgent",
                    "SourceTable": "SourceTable",
                    "GuestHomeDomain": "GuestHomeDomain",
                    "Department": "Department",
                    "JobTitle": "JobTitle",
                    "DirectoryRoles": "DirectoryRoles",
                    "RiskScore": "RiskScore",
                    "RiskIndicators": "RiskIndicators"
                },
                "entityMappings": [
                    {
                        "entityType": "Account",
                        "fieldMappings": [
                            {
                                "identifier": "Name",
                                "columnName": "Name"
                            },
                            {
                                "identifier": "UPNSuffix",
                                "columnName": "UPNSuffix"
                            },
                            {
                                "identifier": "AadUserId",
                                "columnName": "UserId"
                            }
                        ]
                    },
                    {
                        "entityType": "IP",
                        "fieldMappings": [
                            {
                                "identifier": "Address",
                                "columnName": "IPAddress"
                            }
                        ]
                    }
                ],
                "sentinelEntitiesMappings": null,
                "templateVersion": null
            }
        }
    ]
}
