Hunting the APIM Classic compromise with the logs you actually have

Microsoft's advisory for the Azure API Management issue says an unauthorised party could run administrative operations on Classic tier instances, including reading secrets. The obvious next question from anyone running those instances is whether someone read theirs. In most tenants your logs cannot answer it, because the route the attackers most likely used writes nothing to them.

The break-in left no trace, but the stolen credentials still have to be used somewhere, and that part does show up. Sign-ins, token requests, Key Vault access changes and new app credentials all land in tables most of us already collect.

I put together a set of hunts for a workspace that only has the basics: AzureActivity, SigninLogs, AADServicePrincipalSignInLogs, AADManagedIdentitySignInLogs and AuditLogs, plus CloudAuditEvents in Defender XDR if you can see it. There are no gateway logs or Key Vault audit logs in that list. If you have those as well, good for you, and Anders Kristiansen's post covers them.


What happened

The affected tiers are Developer, Basic, Standard and Premium. Consumption and the v2 tiers were not affected. Microsoft's advisory says an instance on one of those tiers may have been accessed when both of these are true:

  • its secrets were stored in APIM, or stored in Azure Key Vault and referenced from APIM
  • it was reachable from the internet without the network controls in Microsoft's APIM security guidance fully in place, which Microsoft describes as internal VNET mode

Keeping a secret in Key Vault does not take an instance out of scope. A Key Vault reference from a named value is enough to bring it in. If your named values point at Key Vault, treat the secrets in that vault as exposed and rotate them there.

The data that could have been read is named values, identity provider client secrets, OpenID Connect provider client secrets, subscription keys, and the tokens used to call the direct management APIs.

Microsoft has not said which path was used. Independent researchers point at the legacy direct management API, <instance>.management.azure-api.net, which authenticates with SAS tokens signed by the instance's tenant access key. It does not use Entra ID, does not check Azure RBAC and does not write to the Azure Activity log.

The timeline is short. Equinor reported the attack on 17 November, Microsoft identified the flaw on 18 November and closed the path on 19 November, rotating the keys Microsoft controls. Keys and secrets that customers control were not rotated for them, so anything read before 19 November still works until you rotate it. No indicators of compromise and no CVE have been published.


What your logs can and cannot see

Activity Logged in the basic tables Hunts
The break-in and secret reads through the legacy API No None
Microsoft's fix and key rotation on 19 November Yes, as platform events in AzureActivity H1
Secret reads and configuration changes through Azure Resource Manager Yes H2, H3, H4, H13
Sign-ins with stolen app secrets Yes H5, H6, H7, H14
Key Vault tokens issued to unusual identities or IPs Token issuance only, not which secrets were read H8
Key Vault access widened Yes H9
APIM-linked apps acting in Azure Yes H10
New credentials, owners or consent in Entra ID Yes H11
The APIM managed identity asking for new things Partly H12
Stolen subscription keys used against your APIs No, needs gateway logs None
Individual Key Vault secret reads No, needs Key Vault audit logs None

Finding the apps first

Most of the useful hunts follow app registrations: the Entra apps whose client secrets sat in APIM as identity providers, OAuth and OpenID Connect servers, named values or backend credentials. Nobody keeps that list up to date. I certainly did not have one.

Find-ApimAppIds.ps1 builds it. It reads each in-scope APIM instance through Azure Resource Manager and collects client IDs from identity providers, authorisation servers, OpenID Connect providers, credential manager providers, plain named values and the client_id values in global and API policies. With -IncludeEntra it also lists Entra apps whose redirect URIs point at your APIM hostnames. At the end it writes a CSV and prints a let ApimAppIds = dynamic([...]); line ready to paste.

The script needed to be safe to run against instances that may already have lost their secrets, so the design is fussy:

  • every request goes through one function, Invoke-ArmRead, that only sends GET
  • that function refuses any path containing a secret-returning action such as listSecrets, listValue or listKeys, and it checks this before anything is sent
  • it never calls Set-AzContext, and it only follows paging links that point back to Azure Resource Manager
  • secret named values and backend credentials are reported by name only; their values are never requested
  • the CSV holds client IDs, object names, backend URLs and Key Vault secret identifiers (the address, not the secret), so treat it as internal

Reader on the APIM instances is enough. By default it only scans the affected tiers, and you can narrow it further to the affected subscriptions and instances:

$subs  = @("<sub-id-1>", "<sub-id-2>")
$names = @("<apim-name-1>", "<apim-name-2>")
./Find-ApimAppIds.ps1 -TenantId "<tenant-id>" -SubscriptionId $subs -ApimName $names -IncludeEntra

The script signs in to the tenant and the first subscription you passed, then reads all of them by path.

Here is the whole script. It runs against instances that may already be compromised, so read it before you run it.

#Requires -Version 5.1
#Requires -Modules Az.Accounts, Az.Resources
<#
.SYNOPSIS
    Finds the Entra app registrations (client IDs) whose credentials are held in
    Azure API Management, so you can fill ApimAppIds in the hunting queries.

.DESCRIPTION
    READ-ONLY. Every request goes through one function that only ever sends GET,
    and refuses any path that would return or change a secret (listSecrets,
    listValue, listKeys, regenerate, and similar). Secret values are never
    requested, never held and never written out.

    It does not change your Azure context (no Set-AzContext), stores no tokens,
    and only follows pagination links that point back to Azure Resource Manager.

    Checks every APIM instance you can see for:
      - Developer portal identity providers (Entra ID and Entra B2C apps)
      - OAuth 2.0 authorization servers and OpenID Connect providers
      - Credential manager (authorization) providers
      - Plain named values that contain a GUID
      - Secret named values and backends with stored credentials (names only)
      - client_id values in the global policy and every API policy
    With -IncludeEntra it also lists Entra app registrations whose redirect URIs
    point at your APIM hostnames.

    What it writes: client IDs, object names, backend URLs and Key Vault secret
    identifiers (the address, not the secret). Treat the CSV as internal.

.PARAMETER SubscriptionId
    Only scan APIM instances in these subscriptions (the affected subscription
    list). Each value must be a subscription GUID.

.PARAMETER ApimName
    Only scan these APIM instances, by name (the affected instance list).
    APIM names are unique across Azure.

.PARAMETER TenantId
    Your Entra tenant ID. If you are not signed in to that tenant, the script runs
    Connect-AzAccount for you, straight to that tenant and the first subscription
    in -SubscriptionId, so you are not asked to pick a subscription. All the
    subscriptions you pass are still scanned.

.PARAMETER IncludeAllTiers
    Also scan Consumption and v2 instances. By default only the tiers affected
    by the November 2026 issue are scanned: Developer, Basic, Standard, Premium.

.PARAMETER IncludeEntra
    Also search Entra app registrations by redirect URI, matching only the
    hostnames of the instances in scope. Needs permission to read applications
    in Entra ID.

.PARAMETER OutFile
    CSV file for all findings. Default: apim-app-ids.csv in the current folder.

.NOTES
    Permissions: Reader on the APIM instances is enough. Do not run as Owner or
    Global Administrator; activate a Reader role through PIM if you use it.
    API version: 2024-05-01 (latest stable Microsoft.ApiManagement version).
    Tested logic only; review before running and follow your execution policy.

.EXAMPLE
    Connect-AzAccount
    .\Find-ApimAppIds.ps1 -IncludeEntra

.EXAMPLE
    # Only the affected subscriptions and instances, signing in as part of the run
    $subs = @("<sub-id-1>", "<sub-id-2>")
    $names = @("<apim-name-1>", "<apim-name-2>")
    .\Find-ApimAppIds.ps1 -TenantId "<tenant-id>" -SubscriptionId $subs -ApimName $names -IncludeEntra
#>
[CmdletBinding()]
param(
    [ValidatePattern('^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$')]
    [string[]]$SubscriptionId,
    [ValidatePattern('^[a-zA-Z][a-zA-Z0-9-]{0,49}$')]
    [string[]]$ApimName,
    [ValidatePattern('^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$')]
    [string]$TenantId,
    [switch]$IncludeAllTiers,
    [switch]$IncludeEntra,
    [ValidateNotNullOrEmpty()]
    [string]$OutFile = "apim-app-ids.csv"
)

$ApiVersion    = "2024-05-01"
$AffectedTiers = @("Developer", "Basic", "Standard", "Premium")
$GuidPattern   = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}'
$GuidOnly      = '^' + $GuidPattern + '$'
$ClientIdRegex = 'client[_-]?id["''\s:=]*["'']?(\{\{[^}]+\}\}|' + $GuidPattern + ')'
$SecretishName = 'client|secret|app|spn|sp-|password|pwd|key|token|cred'

# Actions that return or change secrets. A path that calls one is refused before
# any request is sent. Checked by segment, so an API that happens to be named
# "token" is still allowed.
$BlockedActions = @(
    'listsecrets', 'listvalue', 'listkeys', 'listdebugcredentials', 'listtrace',
    'regenerateprimarykey', 'regeneratesecondarykey', 'regeneratekey',
    'generatetoken', 'token', 'getssotoken'
)
$CollectionNames = @(
    'subscriptions', 'resourcegroups', 'providers', 'service', 'apis', 'backends',
    'namedvalues', 'identityproviders', 'authorizationservers',
    'openidconnectproviders', 'authorizationproviders', 'policies', 'users'
)

function Test-BlockedPath {
    param([string]$Path)
    $segments = @(($Path -split '\?')[0].Trim('/').Split('/') | ForEach-Object { $_.ToLower() })
    for ($i = 1; $i -lt $segments.Count; $i++) {
        # An action follows a resource name; a resource name follows a collection.
        if ($segments[$i] -in $BlockedActions -and $segments[$i - 1] -notin $CollectionNames) {
            return $true
        }
    }
    return $false
}

# ---------------------------------------------------------------- prerequisites
$context = Get-AzContext
$signedIn = ($null -ne $context -and $null -ne $context.Account -and $null -ne $context.Tenant -and $context.Tenant.Id)
if ($TenantId -and (-not $signedIn -or $context.Tenant.Id -ne $TenantId)) {
    # Sign in straight to the tenant. Naming one subscription skips the picker; the
    # script reads every subscription in -SubscriptionId by path, so which one is
    # "current" makes no difference.
    $connectArgs = @{ TenantId = $TenantId; ErrorAction = 'Stop' }
    if ($SubscriptionId) { $connectArgs.Subscription = $SubscriptionId[0] }
    $null = Connect-AzAccount @connectArgs
    $context = Get-AzContext
}
elseif (-not $signedIn) {
    throw "Not signed in. Run Connect-AzAccount, or pass -TenantId and the script will sign you in."
}
$ArmBase = ([string]$context.Environment.ResourceManagerUrl).TrimEnd('/')
$ArmHost = ([uri]$ArmBase).Host
$SupportsPaginate = (Get-Command Invoke-AzRestMethod).Parameters.ContainsKey('Paginate')
Write-Host "Signed in as $($context.Account.Id) to $ArmHost"
if (-not $SupportsPaginate) {
    Write-Warning "Your Az.Accounts module has no -Paginate. Update with: Update-Module Az.Accounts. Falling back to validated manual paging."
}

$Rows = New-Object System.Collections.Generic.List[object]

function Add-Finding {
    param([string]$Instance, [string]$Source, [string]$Name, [string]$ClientId, [string]$Detail)
    $Rows.Add([pscustomobject]@{
        Instance = $Instance
        Source   = $Source
        Name     = $Name
        ClientId = $ClientId
        Detail   = $Detail
    })
}

# ------------------------------------------------------------ the only HTTP call
function Invoke-ArmRead {
    <#
      Sends a GET to Azure Resource Manager and returns the parsed JSON, or $null.
      Refuses secret-returning paths, retries throttling, and never sends anything
      but GET.
    #>
    param(
        [Parameter(Mandatory)] [string]$Path,
        [string]$Query = "",
        [switch]$List,
        # For reads where "not there" is a normal answer, such as an API with no policy.
        [switch]$AllowNotFound
    )
    if ($Path -notmatch '^/subscriptions/') { throw "Refusing non-ARM path: $Path" }
    if (Test-BlockedPath $Path) { throw "Refusing secret-returning path: $Path" }

    $fullPath = "${Path}?api-version=${ApiVersion}${Query}"
    for ($attempt = 1; $attempt -le 4; $attempt++) {
        try {
            if ($List -and $SupportsPaginate) {
                $resp = Invoke-AzRestMethod -Method GET -Path $fullPath -Paginate -ErrorAction Stop
            }
            else {
                $resp = Invoke-AzRestMethod -Method GET -Path $fullPath -ErrorAction Stop
            }
        }
        catch {
            Write-Warning "GET $Path failed: $($_.Exception.Message)"
            return $null
        }
        if ($resp.StatusCode -eq 200) { break }
        if ($resp.StatusCode -in @(429, 500, 502, 503, 504) -and $attempt -lt 4) {
            $wait = [math]::Min(30, [math]::Pow(2, $attempt))
            $retryAfter = 0
            if ($resp.Headers -and [int]::TryParse(("$($resp.Headers['Retry-After'])").Trim('{', '}', ' '), [ref]$retryAfter) -and $retryAfter -gt 0) {
                $wait = [math]::Min(60, $retryAfter)
            }
            Start-Sleep -Seconds $wait
            continue
        }
        if ($resp.StatusCode -eq 404 -and $AllowNotFound) { return $null }
        # Report Azure's own error code and message so a failure can be explained.
        $errCode = ""; $errMsg = ""
        try {
            $errBody = $resp.Content | ConvertFrom-Json -ErrorAction Stop
            $errCode = [string]$errBody.error.code
            $errMsg  = [string]$errBody.error.message
        }
        catch { }
        Write-Warning "GET $Path returned $($resp.StatusCode) $errCode $errMsg"
        return $null
    }
    if ($resp.StatusCode -ne 200) { return $null }
    $body = $resp.Content | ConvertFrom-Json

    # Fallback paging for older Az.Accounts: only follow links back to ARM.
    if ($List -and -not $SupportsPaginate) {
        $items = @($body.value)
        $next = [string]$body.nextLink
        while ($next) {
            $nextUri = [uri]$next
            if ($nextUri.Scheme -ne 'https' -or $nextUri.Host -ne $ArmHost) {
                Write-Warning "Ignoring nextLink to unexpected host: $($nextUri.Host)"
                break
            }
            if (Test-BlockedPath $nextUri.AbsolutePath) { break }
            $pageResp = Invoke-AzRestMethod -Method GET -Path $nextUri.PathAndQuery
            if ($pageResp.StatusCode -ne 200) { break }
            $page = $pageResp.Content | ConvertFrom-Json
            $items += @($page.value)
            $next = [string]$page.nextLink
        }
        return [pscustomobject]@{ value = $items }
    }
    return $body
}

function Get-ArmItems {
    param([Parameter(Mandatory)] [string]$Path)
    $body = Invoke-ArmRead -Path $Path -List
    if ($null -eq $body) { return }
    foreach ($item in @($body.value)) { if ($null -ne $item) { $item } }
}

# ------------------------------------------------------------------- discovery
function Get-ApimInstances {
    $found = @()
    # With -SubscriptionId the instances are listed straight from each subscription,
    # so Resource Graph is only used for a tenant-wide scan.
    if (-not $SubscriptionId -and (Get-Command Search-AzGraph -ErrorAction SilentlyContinue)) {
        try {
            # Fixed query text: nothing from the command line is built into it.
            $query = "resources | where type =~ 'microsoft.apimanagement/service' | project id, name, sku = tostring(sku.name) | order by id asc"
            $graphArgs = @{ Query = $query; First = 1000; ErrorAction = 'Stop' }
            $skip = $null
            do {
                if ($skip) { $graphArgs.SkipToken = $skip }
                $page = Search-AzGraph @graphArgs
                $records = if ($null -ne $page.Data) { $page.Data } else { $page }
                foreach ($r in $records) { $found += [pscustomobject]@{ Id = $r.id; Name = $r.name; Sku = $r.sku } }
                $skip = $page.SkipToken
            } while ($skip)
            return $found
        }
        catch {
            Write-Warning "Resource Graph search failed ($($_.Exception.Message)). Listing each subscription instead."
            $found = @()
        }
    }
    Write-Host "Listing APIM instances per subscription, without changing your context."
    $subIds = if ($SubscriptionId) { $SubscriptionId } else { @(Get-AzSubscription -TenantId $context.Tenant.Id | ForEach-Object { $_.Id }) }
    foreach ($subId in $subIds) {
        foreach ($svc in Get-ArmItems "/subscriptions/$subId/providers/Microsoft.ApiManagement/service") {
            $found += [pscustomobject]@{ Id = $svc.id; Name = $svc.name; Sku = $svc.sku.name }
        }
    }
    return $found
}

function Get-ClientIdsFromGrants {
    param($Grants)
    $ids = @()
    if ($null -eq $Grants) { return $ids }
    foreach ($grant in $Grants.PSObject.Properties) {
        $value = $grant.Value
        if ($null -ne $value -and $value.PSObject.Properties.Name -contains "clientId" -and $value.clientId) {
            $ids += [string]$value.clientId
        }
    }
    return $ids
}

function Search-Instance {
    param($Instance)
    $rid  = $Instance.Id
    $name = $Instance.Name
    Write-Host "Scanning $name ($($Instance.Sku))"

    # The Consumption tier has no developer portal, so it has no identity providers
    # (asking returns 400). Consumption was also not affected by this incident.
    $isConsumption = ([string]$Instance.Sku -eq "Consumption")
    if ($isConsumption) {
        Write-Host "  Consumption tier: skipping developer portal identity providers (not available on this tier)"
    }
    $identityProviders = if ($isConsumption) { @() } else { @(Get-ArmItems "$rid/identityProviders") }
    foreach ($idp in $identityProviders) {
        $p = $idp.properties
        $kind = if ($p.type) { [string]$p.type } else { [string]$idp.name }
        $detail = if ($kind -in @("aad", "aadB2C")) { "Entra app" } else { "Non-Entra provider: rotate the secret at that provider" }
        Add-Finding $name "Identity provider" $kind ([string]$p.clientId) $detail
    }

    foreach ($srv in Get-ArmItems "$rid/authorizationServers") {
        $p = $srv.properties
        $endpoint = [string]$p.tokenEndpoint
        $detail = if ($endpoint -match "microsoftonline") { "Entra app" } else { "Token endpoint: $endpoint" }
        Add-Finding $name "OAuth 2.0 server" ([string]$p.displayName) ([string]$p.clientId) $detail
    }

    foreach ($oidc in Get-ArmItems "$rid/openidConnectProviders") {
        $p = $oidc.properties
        $meta = [string]$p.metadataEndpoint
        $detail = if ($meta -match "microsoftonline") { "Entra app" } else { "Metadata: $meta" }
        Add-Finding $name "OpenID Connect provider" ([string]$p.displayName) ([string]$p.clientId) $detail
    }

    foreach ($prov in Get-ArmItems "$rid/authorizationProviders") {
        $p = $prov.properties
        $ids = Get-ClientIdsFromGrants $p.oauth2.grantTypes
        Add-Finding $name "Credential manager provider" ([string]$p.displayName) ($ids -join ";") "Identity provider: $($p.identityProvider)"
    }

    foreach ($nv in Get-ArmItems "$rid/namedValues") {
        $p = $nv.properties
        $display = [string]$p.displayName
        $kv = [string]$p.keyVault.secretIdentifier
        if ($p.secret -or $kv) {
            if ($display -match $SecretishName) {
                $kvText = if ($kv) { "; Key Vault: $kv" } else { "" }
                Add-Finding $name "Named value (secret)" $display "" "Secret value not read$kvText. Find which app this secret belongs to."
            }
        }
        else {
            # Plain values are returned by GET anyway; only GUIDs are kept, nothing else is written.
            foreach ($m in [regex]::Matches([string]$p.value, $GuidPattern)) {
                Add-Finding $name "Named value (plain GUID)" $display $m.Value.ToLower() "GUID in a plain named value. Could be a client ID or a tenant ID: check in Entra."
            }
        }
    }

    foreach ($be in Get-ArmItems "$rid/backends") {
        $creds = $be.properties.credentials
        if ($null -ne $creds) {
            $kinds = @($creds.PSObject.Properties | Where-Object { $null -ne $_.Value } | ForEach-Object { $_.Name })
            if ($kinds.Count -gt 0) {
                Add-Finding $name "Backend with credentials" ([string]$be.name) "" "URL: $($be.properties.url); credential types: $($kinds -join ', ')"
            }
        }
    }

    # Policy text is scanned in memory for client_id only; it is never written out.
    $policies = @()
    # A 404 here just means no policy is set at that level.
    $global = Invoke-ArmRead -Path "$rid/policies/policy" -Query "&format=rawxml" -AllowNotFound
    if ($global) { $policies += [pscustomobject]@{ Where = "Global policy"; Text = [string]$global.properties.value } }
    foreach ($api in Get-ArmItems "$rid/apis") {
        $apiName = [uri]::EscapeDataString([string]$api.name)
        $apiPolicy = Invoke-ArmRead -Path "$rid/apis/$apiName/policies/policy" -Query "&format=rawxml" -AllowNotFound
        if ($apiPolicy) { $policies += [pscustomobject]@{ Where = "API policy: $($api.name)"; Text = [string]$apiPolicy.properties.value } }
    }
    foreach ($pol in $policies) {
        foreach ($m in [regex]::Matches($pol.Text, $ClientIdRegex, [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)) {
            $value = $m.Groups[1].Value
            if ($value -match $GuidOnly) {
                Add-Finding $name "Policy client_id" $pol.Where $value.ToLower() "Literal client ID in policy"
            }
            else {
                Add-Finding $name "Policy client_id" $pol.Where "" "client_id comes from named value $value"
            }
        }
    }
}

function Search-Entra {
    param($Instances)
    Write-Host "Scanning Entra app registrations for APIM redirect URIs"
    $hosts = New-Object System.Collections.Generic.HashSet[string]
    foreach ($inst in $Instances) {
        $svc = Invoke-ArmRead -Path $inst.Id
        if ($null -eq $svc) { continue }
        foreach ($url in @($svc.properties.gatewayUrl, $svc.properties.developerPortalUrl)) {
            if ($url) { $null = $hosts.Add((([string]$url) -replace '^https?://', '').Split('/')[0].ToLower()) }
        }
        foreach ($hc in @($svc.properties.hostnameConfigurations)) {
            if ($hc.hostName) { $null = $hosts.Add(([string]$hc.hostName).ToLower()) }
        }
    }
    $apps = Get-AzADApplication -Select AppId, DisplayName, Web, Spa, PublicClient
    foreach ($app in $apps) {
        $uris = @()
        $uris += @($app.Web.RedirectUri)
        $uris += @($app.Spa.RedirectUri)
        $uris += @($app.PublicClient.RedirectUri)
        $hits = @($uris | Where-Object {
            $u = ([string]$_).ToLower()
            $u -and ($u -like "*azure-api.net*" -or ($hosts | Where-Object { $u -like "*$_*" }))
        })
        if ($hits.Count -gt 0) {
            Add-Finding "(Entra)" "App redirect URI points at APIM" ([string]$app.DisplayName) ([string]$app.AppId) (($hits | Select-Object -First 3) -join "; ")
        }
    }
}

# ------------------------------------------------------------------------ main
$allInstances = @(Get-ApimInstances)
$instances = $allInstances
if (-not $IncludeAllTiers) {
    $skippedTier = @($instances | Where-Object { [string]$_.Sku -notin $AffectedTiers })
    $instances = @($instances | Where-Object { [string]$_.Sku -in $AffectedTiers })
    foreach ($s in $skippedTier) { Write-Host "  Skipping $($s.Name) ($($s.Sku)): not an affected tier. Use -IncludeAllTiers to scan it." }
}
if ($ApimName) {
    $wanted = @($ApimName | ForEach-Object { $_.ToLower() })
    $instances = @($instances | Where-Object { ([string]$_.Name).ToLower() -in $wanted })
    $foundNames = @($allInstances | ForEach-Object { ([string]$_.Name).ToLower() })
    foreach ($n in $wanted) {
        if ($n -notin $foundNames) { Write-Warning "APIM instance '$n' was not found in the subscriptions you can see." }
    }
}
$scope = @()
if ($SubscriptionId) { $scope += "$($SubscriptionId.Count) subscription(s)" }
if ($ApimName) { $scope += "$($ApimName.Count) named instance(s)" }
$scope += if ($IncludeAllTiers) { "all tiers" } else { "affected tiers only" }
Write-Host "Scope: $($scope -join ', ')"
Write-Host "Scanning $($instances.Count) of $($allInstances.Count) APIM instance(s) found"
foreach ($inst in $instances) {
    try { Search-Instance $inst }
    catch { Write-Warning "Skipped $($inst.Name): $($_.Exception.Message)" }
}
if ($IncludeEntra) {
    try { Search-Entra $instances }
    catch { Write-Warning "Entra search failed: $($_.Exception.Message)" }
}

$Rows | Export-Csv -Path $OutFile -NoTypeInformation -Encoding UTF8

$ids = @($Rows | Where-Object { $_.ClientId -match $GuidOnly } | ForEach-Object { $_.ClientId.ToLower() } | Sort-Object -Unique)
Write-Host ""
Write-Host "Wrote $($Rows.Count) findings to $OutFile (internal: contains app IDs and backend URLs, no secrets)"
Write-Host "$($ids.Count) candidate client IDs. Check each in Entra before using it:"
Write-Host ""
$quoted = $ids | ForEach-Object { '"' + $_ + '"' }
Write-Host ("let ApimAppIds = dynamic([" + ($quoted -join ", ") + "]);")

$noId = @($Rows | Where-Object { -not $_.ClientId })
if ($noId.Count -gt 0) {
    Write-Host ""
    Write-Host "$($noId.Count) findings hold a secret but no client ID (secret named values, backends)."
    Write-Host "Open the CSV and trace each to its app by name or owner."
}

Treat the output as a list of candidates. The script grabs any GUID in a plain named value, and some of those will be tenant IDs. H5b, further down, checks each ID against the sign-in and audit tables.


Getting set up

The settings block

Every hunt reads the same variables, so you set them once at the top of your query editor and stop copying them about. H4 runs in Defender XDR advanced hunting, so AffectedSubs and KnownEgressRanges need declaring there too.

let HuntStart = datetime(2026-10-01);
let HuntEnd = datetime(2026-11-24 23:59:59.9999999);
let BaselineStart = ago(90d);
let ApimAppIds = dynamic(["<app-id-of-each-app-whose-secret-is-in-apim>"]);
let ApimIdentities = dynamic(["<apim-managed-identity-object-id>"]);
let AffectedSubs = dynamic(["<affected-subscription-id>"]);
let AffectedApim = dynamic(["<affected-apim-instance-name>"]);
let KnownEgressRanges = dynamic(["<first-two-octets>"]);

HuntStart goes as far back as you can justify. Microsoft has not said when exploitation started, so starting on 1 November would be a guess and an optimistic one. With 90 days of retention, starting the window on 1 October leaves roughly five weeks of baseline from ago(90d).

HuntEnd is set to the last tick of the day, 23:59:59.9999999. between includes both ends, so this covers the whole of 24 November. Stopping at 23:59:59 would miss any event logged in the final second.

ApimAppIds comes from the script above. ApimIdentities holds the principalId of each affected instance's managed identity. AffectedSubs and AffectedApim are your affected subscriptions and instance names; APIM names are unique across Azure, so a name is enough.

KnownEgressRanges takes the first two octets of addresses you trust, such as your corporate proxy ranges. Every hunt drops those before it builds the baseline. Be careful with this one. Some proxies share its egress addresses between all its customers, so an attacker using the same proxy from another tenant would be filtered out along with your staff. Keep the list to ranges you actually own or contract.

Is the list complete?

Before trusting AffectedSubs, check it. These list every APIM instance on an affected tier and set InList to false for anything your list misses.

Resource Graph Explorer does not support let, which you find out when a query that worked in Sentinel fails in the portal. So the IDs go in as literals:

resources
| where type =~ "microsoft.apimanagement/service"
| where tostring(sku.name) in~ ("Developer", "Basic", "Standard", "Premium")
| extend InList = subscriptionId in~ ("<sub-id-1>", "<sub-id-2>")
| project name, subscriptionId, resourceGroup, Sku = tostring(sku.name), InList
| order by InList asc, name asc

In Sentinel, arg("") reads Resource Graph and the variables work:

arg("").Resources
| where type =~ "microsoft.apimanagement/service"
| where tostring(sku.name) in~ ("Developer", "Basic", "Standard", "Premium")
| extend InList = subscriptionId in~ (AffectedSubs)
| project name, subscriptionId, resourceGroup, Sku = tostring(sku.name), InList
| order by InList asc, name asc

And the same check for instance names:

arg("").Resources
| where type =~ "microsoft.apimanagement/service"
| where tostring(sku.name) in~ ("Developer", "Basic", "Standard", "Premium")
| extend InList = name in~ (AffectedApim)
| project name, subscriptionId, resourceGroup, Sku = tostring(sku.name), InList
| order by InList asc, name asc

H1. Microsoft's fix

The Notice part finds the Service Health notice in each affected subscription. The main part counts APIM events with no caller and no IP, per day, for the affected instances only, and joins the notice time on.

A cluster of caller-less events on 19 November in a subscription that got the notice is Microsoft applying its fix and rotating its own keys. Caller-less events on other dates, particularly secret reads, are not explained by anything Microsoft has published. H13a and H13b, further down, are for working through those.

let Notice = AzureActivity
    | where TimeGenerated between (HuntStart .. HuntEnd)
    | where SubscriptionId in~ (AffectedSubs)
    | where CategoryValue == "ServiceHealth"
    | where tostring(Properties_d.trackingId) == "MZK9-GH0"
    | summarize NoticeTime = min(TimeGenerated) by SubscriptionId;
AzureActivity
| where TimeGenerated between (HuntStart .. HuntEnd)
| where OperationNameValue startswith "Microsoft.ApiManagement/"
| extend ApimService = tolower(extract(@"(?i)/service/([^/]+)", 1, _ResourceId))
| where ApimService in~ (AffectedApim)
| where isempty(Caller) and isempty(CallerIpAddress)
| summarize Events = count()
    , Operations = make_set(OperationNameValue, 20)
    , Instances = make_set(ApimService, 20)
    by Day = bin(TimeGenerated, 1d), SubscriptionId
| lookup kind=leftouter Notice on SubscriptionId
| sort by Day asc

Secret reads and changes through Resource Manager

If an attacker had an administrator's token rather than the legacy route, their reads and changes went through Azure Resource Manager and were logged like everyone else's.

H2. APIM secret reads by a new caller or IP

Takes successful APIM secret reads (listSecrets, listValue, listKeys, generateToken, listDebugCredentials and user token generation) on the affected instances. Callers and IPs from before HuntStart form the baseline, and a read in the window is kept if either is new. SecretsRead lists the named values, providers and subscriptions each caller read, which is what they could have walked off with.

A known administrator from a new country deserves more attention than a new pipeline on a familiar range. A read you cannot match to a named person and an approved change should be treated as hostile until someone proves otherwise.

let SecretReads = AzureActivity
    | where TimeGenerated between (BaselineStart .. HuntEnd)
    | extend Op = tolower(OperationNameValue)
    | where Op startswith "microsoft.apimanagement/"
    | extend ApimService = tolower(extract(@"(?i)/service/([^/]+)", 1, _ResourceId))
    | where ApimService in~ (AffectedApim)
    | where Op has_any ("listsecrets", "listvalue", "listkeys", "generatetoken", "listdebugcredentials")
        or Op endswith "/users/token/action"
    | where ActivityStatusValue in~ ("Success", "Succeeded")
    | where extract(@"^(\d{1,3}\.\d{1,3})\.", 1, CallerIpAddress) !in (KnownEgressRanges);
let Baseline = SecretReads | where TimeGenerated < HuntStart;
let KnownCallers = Baseline | distinct Caller;
let KnownIps = Baseline | distinct CallerIpAddress;
SecretReads
| where TimeGenerated between (HuntStart .. HuntEnd)
| extend IsNewCaller = Caller !in (KnownCallers)
    , IsNewIp = CallerIpAddress !in (KnownIps)
| where IsNewCaller or IsNewIp
| extend ResourcePath = tolower(_ResourceId)
| extend ApimService = extract(@"/service/([^/]+)", 1, ResourcePath)
    , SecretObject = extract(@"/service/[^/]+/(.+)$", 1, ResourcePath)
    , Country = tostring(geo_info_from_ip_address(CallerIpAddress).country)
| summarize FirstRead = min(TimeGenerated)
    , LastRead = max(TimeGenerated)
    , Reads = count()
    , SecretsRead = make_set(SecretObject, 100)
    by Caller, CallerIpAddress, Country, ApimService, IsNewCaller, IsNewIp
| sort by FirstRead asc

H3. Credential reads across every provider

A stolen token rarely stops at APIM. H3 applies the same idea to every resource provider: storage account keys and SAS, Cosmos DB keys, Service Bus and Event Hubs connection strings, AKS cluster credentials, App Service publishing credentials and the rest. The baseline is per caller. CredReadsByCaller builds a caller-and-operation value and a caller-and-IP value for each read, and a read in the window is kept if either is new for that caller.

Rows from affected subscriptions sort first. Look at the others too, because a credential taken from APIM works wherever its identity has access.

let CredReads = AzureActivity
    | where TimeGenerated between (BaselineStart .. HuntEnd)
    | extend Op = tolower(OperationNameValue)
    | where Op has_any ("listkeys", "listsecrets", "listvalue", "listcredential", "listcredentials", "listconnectionstrings", "listaccountsas", "listservicesas", "listadmincredential", "listclusteradmincredential", "listclusterusercredential", "listpublishingcredentials", "generatetoken", "getaccesstoken")
    | where ActivityStatusValue in~ ("Success", "Succeeded")
    | where extract(@"^(\d{1,3}\.\d{1,3})\.", 1, CallerIpAddress) !in (KnownEgressRanges);
let CredReadsByCaller = CredReads
    | extend CallerOperation = strcat(Caller, "|", Op)
        , CallerIp = strcat(Caller, "|", CallerIpAddress);
let KnownCallerOperations = CredReadsByCaller
    | where TimeGenerated < HuntStart
    | distinct CallerOperation;
let KnownCallerIps = CredReadsByCaller
    | where TimeGenerated < HuntStart
    | distinct CallerIp;
CredReadsByCaller
| where TimeGenerated between (HuntStart .. HuntEnd)
| extend IsNewOperationForCaller = CallerOperation !in (KnownCallerOperations)
    , IsNewIpForCaller = CallerIp !in (KnownCallerIps)
| where IsNewOperationForCaller or IsNewIpForCaller
| extend Provider = tostring(split(OperationNameValue, "/")[0])
    , Country = tostring(geo_info_from_ip_address(CallerIpAddress).country)
    , InAffectedSub = SubscriptionId in~ (AffectedSubs)
| summarize FirstRead = min(TimeGenerated)
    , LastRead = max(TimeGenerated)
    , Reads = count()
    , NewOperationReads = countif(IsNewOperationForCaller)
    , NewIpReads = countif(IsNewIpForCaller)
    , AffectedSubReads = countif(InAffectedSub)
    , Subscriptions = make_set(SubscriptionId, 20)
    , Providers = make_set(Provider, 20)
    , Operations = make_set(OperationNameValue, 30)
    , Resources = make_set(_ResourceId, 50)
    by Caller, CallerIpAddress, Country
| sort by AffectedSubReads desc, FirstRead asc

H4. Credential reads from anonymous proxies or new countries (Defender XDR)

CloudAuditEvents adds country, ISP and anonymous-proxy flags to Azure control-plane events, which is the only IP reputation you get in this set of tables. H4 keeps credential reads from anonymous proxies or from countries not seen before HuntStart.

Two warnings. Defender XDR keeps 30 days, so with an October start there is no baseline and every country is new; only the proxy flag means anything. And if your account cannot see Defender for Cloud data in Defender XDR, the table returns nothing and no error, which looks clean and is not. The column set also varies between tenants, hence all the column_ifexists.

// Runs in Defender XDR advanced hunting, so it declares its own variables.
// The CloudAuditEvents schema differs between tenants (DataSource or AuditSource,
// with or without the IP enrichment columns), so every column that varies is read
// with column_ifexists and given a safe default.
let AffectedSubs = dynamic(["<affected-subscription-id>"]);
let KnownEgressRanges = dynamic(["<first-two-octets>"]);
let Window = 7d;
let CredReads = CloudAuditEvents
    | extend EventTime = coalesce(column_ifexists("Timestamp", datetime(null)), column_ifexists("TimeGenerated", datetime(null)))
    | where EventTime > ago(30d)
    | extend Source = coalesce(column_ifexists("AuditSource", ""), column_ifexists("DataSource", ""))
    | where Source startswith "Azure"
    | where OperationName has_any ("listKeys", "listSecrets", "listValue", "listCredential", "listConnectionStrings", "listAccountSas", "listServiceSas", "listAdminCredential", "listClusterAdminCredential", "listPublishingCredentials", "generateToken")
    | extend ClientIp = coalesce(column_ifexists("IPAddress", ""), tostring(RawEventData.callerIpAddress))
    | where extract(@"^(\d{1,3}\.\d{1,3})\.", 1, ClientIp) !in (KnownEgressRanges)
    | extend ResId = coalesce(column_ifexists("ResourceId", ""), column_ifexists("AzureResourceId", ""), column_ifexists("CloudResourceId", ""), tostring(RawEventData.resourceId))
        , Country = column_ifexists("CountryCode", "")
        , Provider = column_ifexists("Isp", "")
        , AnonProxy = tobool(column_ifexists("IsAnonymousProxy", false))
        , Caller = coalesce(tostring(RawEventData.caller), tostring(RawEventData.identity.claims.appid));
let KnownCountries = CredReads
    | where EventTime < ago(Window)
    | where isnotempty(Country)
    | distinct Country;
CredReads
| where EventTime >= ago(Window)
| where AnonProxy == true or (isnotempty(Country) and Country !in (KnownCountries))
| extend SubscriptionId = extract(@"(?i)/subscriptions/([^/]+)", 1, ResId)
| extend InAffectedSub = SubscriptionId in~ (AffectedSubs)
| summarize FirstSeen = min(EventTime)
    , Events = count()
    , AffectedSubEvents = countif(InAffectedSub)
    , Operations = make_set(OperationName, 30)
    , Resources = make_set(ResId, 30)
    by Caller, ClientIp, Country, Provider, AnonProxy, Source
| sort by AnonProxy desc, AffectedSubEvents desc, FirstSeen asc

H5. APIM secret reads and configuration changes by caller

A changed policy can send request data to an outside endpoint, and a changed identity provider can point portal sign-ins at someone else's app, so each of these writes can give someone a way back in. Each event gets an Activity label, and IsNewCaller compares each caller and instance pair with the baseline.

let ApimActivity = AzureActivity
    | where TimeGenerated between (BaselineStart .. HuntEnd)
    | where ResourceProviderValue =~ "Microsoft.ApiManagement"
    | extend ApimService = tolower(extract(@"(?i)/service/([^/]+)", 1, _ResourceId))
    | where ApimService in~ (AffectedApim)
    | where extract(@"^(\d{1,3}\.\d{1,3})\.", 1, CallerIpAddress) !in (KnownEgressRanges)
    | extend Op = tolower(OperationNameValue)
    | extend Activity = case(
        Op contains "/namedvalues/listvalue/action"
            or Op contains "/subscriptions/listsecrets/action"
            or Op contains "/tenant/listsecrets/action"
            or Op contains "/identityproviders/listsecrets/action", "Secret read"
        , Op contains "/policies/write", "Policy change"
        , Op contains "/namedvalues/write", "Named value change"
        , Op contains "/identityproviders/write", "Identity provider change"
        , Op contains "/users/write", "User change"
        , Op contains "/portalsettings/write" or Op contains "/portalrevisions/write", "Developer portal change"
        , "")
    | where isnotempty(Activity)
    | extend Caller = iif(isempty(Caller), "(no caller recorded)", Caller)
    | extend CallerService = strcat(Caller, "|", ApimService);
let KnownCallerServices = ApimActivity
    | where TimeGenerated < HuntStart
    | distinct CallerService;
ApimActivity
| where TimeGenerated between (HuntStart .. HuntEnd)
| extend IsNewCaller = CallerService !in (KnownCallerServices)
    , NoCaller = Caller == "(no caller recorded)"
    , ApimObject = extract(@"(?i)/service/[^/]+/(.+)$", 1, _ResourceId)
| summarize FirstSeen = min(TimeGenerated)
    , LastSeen = max(TimeGenerated)
    , Events = count()
    , Succeeded = countif(ActivityStatusValue in~ ("Success", "Succeeded"))
    , Failed = countif(ActivityStatusValue in~ ("Failure", "Failed"))
    , Activities = make_set(Activity, 10)
    , Operations = make_set(Op, 20)
    , Objects = make_set(ApimObject, 50)
    , SourceIps = make_set(CallerIpAddress, 20)
    by Caller, ApimService, IsNewCaller, NoCaller
| sort by NoCaller desc, IsNewCaller desc, FirstSeen asc

Why some events have no caller

Caller comes from the token on the request. When no customer token was involved it is empty, and there are three reasons that happens:

  1. The platform did something on its own: maintenance, certificate rotation, scaling, and Microsoft's own fix on 19 November.
  2. Microsoft wrote a Service Health notice, which has no caller either.
  3. The resource provider reported a change after the fact that did not come through Resource Manager at all.

The first two are expected. The third is the interesting one, because the legacy direct management API is that kind of route, and Microsoft has not said whether changes made through it surface later as caller-less events.

H5a. Caller-less events on one day

Caller-less APIM events tend to arrive in their thousands, so reading them one by one is not ideal. Set Day to the date you are looking at. H5a gives each operation that ran with no caller that day a verdict:

VerdictRule
EscalateA secret read or configuration change that has run with no caller on two days or fewer
ReviewA secret read or configuration change that often runs with no caller, or any other operation that rarely does
RoutineAnything else that runs with no caller on more than two days

HasCallerEvidence is true if any event carried an evidence section in Authorization, which a platform operation would not have. If that is true, treat the row as Escalate whatever the verdict says.

let Day = datetime(2026-11-19);
let CallerLess = AzureActivity
    | where TimeGenerated between (BaselineStart .. HuntEnd)
    | where ResourceProviderValue =~ "Microsoft.ApiManagement"
    | where isempty(Caller)
    | extend Op = tolower(OperationNameValue);
let History = CallerLess
    | summarize DaysSeenCallerLess = dcount(bin(TimeGenerated, 1d))
        , FirstSeenCallerLess = min(TimeGenerated)
        , LastSeenCallerLess = max(TimeGenerated)
        by Op;
CallerLess
| where TimeGenerated between (Day .. (Day + 1d - 1tick))
| extend ApimService = tolower(extract(@"(?i)/service/([^/]+)", 1, _ResourceId))
    , HasEvidence = isnotempty(parse_json(Authorization).evidence)
| summarize EventsOnDay = count()
    , Instances = make_set(ApimService, 10)
    , Statuses = make_set(ActivityStatusValue, 5)
    , HasCallerEvidence = max(toint(HasEvidence)) == 1
    , CorrelationIds = make_set(CorrelationId, 5)
    by Op
| lookup kind=leftouter History on Op
| extend IsSecretOrConfig = Op contains "/listvalue/action"
    or Op contains "/listsecrets/action"
    or Op contains "/policies/write"
    or Op contains "/namedvalues/write"
    or Op contains "/identityproviders/write"
    or Op contains "/users/write"
    or Op contains "/portalsettings/write"
    or Op contains "/portalrevisions/write"
| extend Assessment = case(
    IsSecretOrConfig and DaysSeenCallerLess <= 2, "Escalate"
    , IsSecretOrConfig or DaysSeenCallerLess <= 2, "Review"
    , "Routine")
| extend Priority = case(Assessment == "Escalate", 1, Assessment == "Review", 2, 3)
    , Operation = replace_string(Op, "microsoft.apimanagement/service/", "")
| project Assessment
    , Operation
    , EventsOnDay
    , DaysSeenCallerLess
    , FirstSeenCallerLess
    , LastSeenCallerLess
    , Instances
    , Statuses
    , HasCallerEvidence
    , CorrelationIds
    , Priority
| sort by Priority asc, DaysSeenCallerLess asc
| project-away Priority

H5b. Working through the Review rows

One request often writes several Activity log entries and only some of them carry the caller. H5b checks whether each caller-less event behind a Review row shares a CorrelationId with an event that did record one, and groups the results by operation and caller. DatesSeen lists every date the operation ran without a caller.

Work through it in order. Where Explained is true, CallerList names the person or app, and you confirm the change was expected. Where it is false and the operation is not a secret read or configuration change, note it and move on. Where it is false and it is a secret read or configuration change, look at DatesSeen: a regular pattern is the provider syncing; dates clustered around the incident with no matching change are where the support case starts.

let Day = datetime(2026-11-19);
let CallerLess = AzureActivity
    | where TimeGenerated between (BaselineStart .. HuntEnd)
    | where ResourceProviderValue =~ "Microsoft.ApiManagement"
    | where isempty(Caller)
    | extend Op = tolower(OperationNameValue);
let History = CallerLess
    | summarize DaysSeenCallerLess = dcount(bin(TimeGenerated, 1d))
        , DatesSeen = make_set(format_datetime(bin(TimeGenerated, 1d), "yyyy-MM-dd"), 50)
        by Op;
let ReviewOps = CallerLess
    | where TimeGenerated between (Day .. (Day + 1d - 1tick))
    | distinct Op
    | lookup kind=leftouter History on Op
    | extend IsSecretOrConfig = Op contains "/listvalue/action"
        or Op contains "/listsecrets/action"
        or Op contains "/policies/write"
        or Op contains "/namedvalues/write"
        or Op contains "/identityproviders/write"
        or Op contains "/users/write"
        or Op contains "/portalsettings/write"
        or Op contains "/portalrevisions/write"
    | where (IsSecretOrConfig and DaysSeenCallerLess > 2) or (not(IsSecretOrConfig) and DaysSeenCallerLess <= 2);
let WithCaller = AzureActivity
    | where TimeGenerated between ((Day - 1d) .. (Day + 2d))
    | where isnotempty(Caller)
    | summarize Callers = make_set(Caller, 5)
        , CallerIps = make_set(CallerIpAddress, 5)
        , CallerOperations = make_set(OperationNameValue, 10)
        by CorrelationId;
CallerLess
| where TimeGenerated between (Day .. (Day + 1d - 1tick))
| join kind=inner ReviewOps on Op
| lookup kind=leftouter WithCaller on CorrelationId
| extend Explained = isnotempty(Callers)
    , WhyReview = iif(IsSecretOrConfig, "Secret read or config change that often has no caller", "Operation that rarely has no caller")
    , Operation = replace_string(Op, "microsoft.apimanagement/service/", "")
    , CallerList = strcat_array(Callers, ", ")
    , ApimService = tolower(extract(@"(?i)/service/([^/]+)", 1, _ResourceId))
| summarize Events = count()
    , FirstEvent = min(TimeGenerated)
    , LastEvent = max(TimeGenerated)
    , Statuses = make_set(ActivityStatusValue, 5)
    , Instances = make_set(ApimService, 10)
    , SampleCorrelationIds = make_set(CorrelationId, 5)
    , DaysSeenCallerLess = take_any(DaysSeenCallerLess)
    , DatesSeen = take_any(DatesSeen)
    by Operation, WhyReview, Explained, CallerList
| sort by Explained asc, Events desc

Stolen app secrets in use

The identity provider and OpenID Connect secrets in the advisory belong to Entra apps. Anyone holding one can request an app-only token, and that sign-in lands in AADServicePrincipalSignInLogs.

H6. APIM-linked apps signing in from new IPs

For the apps in ApimAppIds, each app and IP pair from before HuntStart forms the baseline, and sign-ins in the window from new pairs come back with attempts, successes, target resources and the credential key ID. Developer portal identity provider apps normally authenticate from APIM's own addresses, so a new IP is worth a look. If CredentialKeyIds contains the key ID of a secret you already replaced, that secret still works. Delete it from the app registration as well as adding the new one.

let SignIns = AADServicePrincipalSignInLogs
    | where TimeGenerated between (BaselineStart .. HuntEnd)
    | where AppId in~ (ApimAppIds)
    | where extract(@"^(\d{1,3}\.\d{1,3})\.", 1, IPAddress) !in (KnownEgressRanges);
let Known = SignIns
    | where TimeGenerated < HuntStart
    | distinct AppId, IPAddress;
SignIns
| where TimeGenerated between (HuntStart .. HuntEnd)
| join kind=leftanti Known on AppId, IPAddress
| summarize FirstSeen = min(TimeGenerated)
    , LastSeen = max(TimeGenerated)
    , Attempts = count()
    , Successes = countif(ResultType in ("0", "Success"))
    , Results = make_set(ResultType, 10)
    , Resources = make_set(ResourceDisplayName, 20)
    , CredentialTypes = make_set(ClientCredentialType, 5)
    , CredentialKeyIds = make_set(ServicePrincipalCredentialKeyId, 10)
    , Locations = make_set(Location, 10)
    by AppId, ServicePrincipalName, IPAddress, AutonomousSystemNumber
| sort by FirstSeen asc

H6a. Why H6 came back empty

A developer portal identity provider app is normally used when a person signs in to the portal, and that sign-in goes to SigninLogs, not the service principal table. An attacker with the secret would show up in the service principal table, which is why H6 looks there. H6a counts both, per app, so you can see which kind of empty you have.

ResultMeaning
SpWindow is 0No app-only tokens in the window. An empty H6 is clean for that app.
SpWindow equals SpWindowExcludedAsEgressEvery sign-in came through your egress ranges. Check those ranges are yours.
SpWindow above 0, H6 emptyEvery IP in the window was already in the baseline.
Everything 0The app is unused, or the ID is wrong. H6b checks.
let Apps = print AppId = ApimAppIds
    | mv-expand AppId to typeof(string)
    | extend AppId = tolower(AppId);
let SpSignIns = AADServicePrincipalSignInLogs
    | where TimeGenerated between (BaselineStart .. HuntEnd)
    | where AppId in~ (ApimAppIds)
    | extend IsEgress = extract(@"^(\d{1,3}\.\d{1,3})\.", 1, IPAddress) in (KnownEgressRanges)
    | summarize SpBaseline = countif(TimeGenerated < HuntStart)
        , SpWindow = countif(TimeGenerated >= HuntStart)
        , SpWindowExcludedAsEgress = countif(TimeGenerated >= HuntStart and IsEgress)
        , SpWindowIps = dcountif(IPAddress, TimeGenerated >= HuntStart)
        by AppId = tolower(AppId);
let UserSignIns = SigninLogs
    | where TimeGenerated between (BaselineStart .. HuntEnd)
    | where AppId in~ (ApimAppIds)
    | summarize UserBaseline = countif(TimeGenerated < HuntStart)
        , UserWindow = countif(TimeGenerated >= HuntStart)
        by AppId = tolower(AppId);
Apps
| lookup kind=leftouter SpSignIns on AppId
| lookup kind=leftouter UserSignIns on AppId
| extend SpBaseline = coalesce(SpBaseline, 0)
    , SpWindow = coalesce(SpWindow, 0)
    , SpWindowExcludedAsEgress = coalesce(SpWindowExcludedAsEgress, 0)
    , SpWindowIps = coalesce(SpWindowIps, 0)
    , UserBaseline = coalesce(UserBaseline, 0)
    , UserWindow = coalesce(UserWindow, 0)
| sort by SpWindow desc

H6b. Checking the IDs in ApimAppIds

The script picks up any GUID in a plain named value, so some IDs will be tenant IDs or something else entirely. H6b looks each one up across the sign-in and audit tables and gives a verdict: tenant ID, app with sign-ins, API app that other apps call but which never signs in itself, unused app registration, or not seen anywhere. The last one can mean the app lives in another tenant, such as an Entra B2C tenant for a developer portal aadB2C identity provider, where its sign-ins are logged instead.

let Ids = print Id = ApimAppIds
    | mv-expand Id to typeof(string)
    | extend Id = tolower(trim(" ", Id));
let KnownTenants = union
    (SigninLogs | where TimeGenerated between (BaselineStart .. HuntEnd) | distinct T = tolower(AADTenantId))
    , (SigninLogs | where TimeGenerated between (BaselineStart .. HuntEnd) | distinct T = tolower(HomeTenantId))
    , (SigninLogs | where TimeGenerated between (BaselineStart .. HuntEnd) | distinct T = tolower(ResourceTenantId))
    | where isnotempty(T)
    | distinct T;
let AsSpApp = AADServicePrincipalSignInLogs
    | where TimeGenerated between (BaselineStart .. HuntEnd)
    | where AppId in~ (ApimAppIds)
    | summarize AppOnlySignIns = count()
        , SpName = take_any(ServicePrincipalName)
        , OwnerTenant = take_any(AppOwnerTenantId)
        by Id = tolower(AppId);
let AsUserApp = SigninLogs
    | where TimeGenerated between (BaselineStart .. HuntEnd)
    | where AppId in~ (ApimAppIds)
    | summarize UserSignIns = count()
        , UserAppName = take_any(AppDisplayName)
        by Id = tolower(AppId);
let AsResource = union
    (SigninLogs | where TimeGenerated between (BaselineStart .. HuntEnd) | where ResourceIdentity in~ (ApimAppIds) | project ResourceIdentity, ResourceDisplayName)
    , (AADServicePrincipalSignInLogs | where TimeGenerated between (BaselineStart .. HuntEnd) | where ResourceIdentity in~ (ApimAppIds) | project ResourceIdentity, ResourceDisplayName)
    | summarize TokensIssuedForIt = count()
        , ResourceName = take_any(ResourceDisplayName)
        by Id = tolower(ResourceIdentity);
let InAudit = AuditLogs
    | where TimeGenerated between (BaselineStart .. HuntEnd)
    | mv-expand Detail = AdditionalDetails
    | where tostring(Detail.key) =~ "AppId"
    | extend Id = tolower(tostring(Detail.value))
    | where Id in~ (ApimAppIds)
    | summarize AuditEvents = count()
        , AuditName = take_any(tostring(TargetResources[0].displayName))
        by Id;
Ids
| lookup kind=leftouter AsSpApp on Id
| lookup kind=leftouter AsUserApp on Id
| lookup kind=leftouter AsResource on Id
| lookup kind=leftouter InAudit on Id
| extend IsTenantId = Id in (KnownTenants)
    , Name = coalesce(SpName, UserAppName, ResourceName, AuditName)
    , AppOnlySignIns = coalesce(AppOnlySignIns, 0)
    , UserSignIns = coalesce(UserSignIns, 0)
    , TokensIssuedForIt = coalesce(TokensIssuedForIt, 0)
    , AuditEvents = coalesce(AuditEvents, 0)
| extend Verdict = case(
    IsTenantId, "Tenant ID, not an app: remove from ApimAppIds"
    , AppOnlySignIns > 0 or UserSignIns > 0, "App with sign-ins: H5 covers it"
    , TokensIssuedForIt > 0, "API app: tokens issued for it, but it does not sign in itself"
    , AuditEvents > 0, "App registration with no sign-ins in 90 days: unused"
    , "Not seen in any table: check in Entra ID, may be another tenant or not an app ID")
| project Id
    , Name
    , Verdict
    , AppOnlySignIns
    , UserSignIns
    , TokensIssuedForIt
    , AuditEvents
    , OwnerTenant
| sort by Verdict asc

H7. Rotated secrets still being tried

AADSTS7000215 is an invalid client secret and AADSTS7000222 is an expired one. Your own pipelines will throw a few straight after a rotation and then stop once someone updates them. Failures that keep coming, from IPs your pipelines don't use, could mean someone outside still has the old secret. It is the closest thing to proof of theft these logs will give you, and it only appears once the stolen secret stops working. Keep running it after rotation.

AADServicePrincipalSignInLogs
| where TimeGenerated between (HuntStart .. HuntEnd)
| where ResultType in ("7000215", "7000222")
| where extract(@"^(\d{1,3}\.\d{1,3})\.", 1, IPAddress) !in (KnownEgressRanges)
| summarize FirstFailure = min(TimeGenerated)
    , LastFailure = max(TimeGenerated)
    , Failures = count()
    , Ips = make_set(IPAddress, 20)
    , Asns = make_set(AutonomousSystemNumber, 10)
    , Resources = make_set(ResourceDisplayName, 10)
    , Errors = make_set(ResultDescription, 5)
    by AppId, ServicePrincipalName
| sort by LastFailure desc

H8. Any app using a client secret from a new IP

The safety catch for apps the script missed. It looks at every service principal sign-in that used a client secret to get a token for Key Vault, Azure Resource Manager or Microsoft Graph, and keeps app and IP pairs the baseline never saw. New deployments add noise. Start with apps nobody owns, IPs in hosting provider ranges (check AutonomousSystemNumber) and apps whose first new sign-in went straight to Key Vault.

let SignIns = AADServicePrincipalSignInLogs
    | where TimeGenerated between (BaselineStart .. HuntEnd)
    | where ClientCredentialType =~ "clientSecret"
    | where ResourceDisplayName in~ ("Azure Key Vault", "Windows Azure Service Management API", "Microsoft Graph")
    | where extract(@"^(\d{1,3}\.\d{1,3})\.", 1, IPAddress) !in (KnownEgressRanges);
let Known = SignIns
    | where TimeGenerated < HuntStart
    | distinct AppId, IPAddress;
SignIns
| where TimeGenerated between (HuntStart .. HuntEnd)
| where ResultType == "0"
| join kind=leftanti Known on AppId, IPAddress
| summarize FirstSeen = min(TimeGenerated)
    , SignIns = count()
    , Resources = make_set(ResourceDisplayName, 5)
    , CredentialKeyIds = make_set(ServicePrincipalCredentialKeyId, 5)
    , Locations = make_set(Location, 5)
    by AppId, ServicePrincipalName, IPAddress, AutonomousSystemNumber
| sort by FirstSeen asc

H9. An app suddenly reaching for more resources

Someone testing a stolen secret tends to request tokens for several resources in a short time, while the app's real workload touches the same few every day. H9 counts the distinct resources each APIM-linked app got tokens for per hour and keeps hours in the window above that app's busiest baseline hour. An app with no baseline sign-ins has a peak of 0, so any hour with a sign-in comes back. If the IPs here also show up as new in H6, look at that first.

let HourlyResources = AADServicePrincipalSignInLogs
    | where TimeGenerated between (BaselineStart .. HuntEnd)
    | where AppId in~ (ApimAppIds)
    | where extract(@"^(\d{1,3}\.\d{1,3})\.", 1, IPAddress) !in (KnownEgressRanges)
    | where ResultType in ("0", "Success")
    | summarize Resources = dcount(ResourceIdentity)
        , ResourceNames = make_set(ResourceDisplayName, 20)
        , Ips = make_set(IPAddress, 10)
        by AppId, ServicePrincipalName, Hour = bin(TimeGenerated, 1h);
let BaselinePeak = HourlyResources
    | where Hour < HuntStart
    | summarize BaselineMaxResources = max(Resources) by AppId;
HourlyResources
| where Hour between (HuntStart .. HuntEnd)
| lookup kind=leftouter BaselinePeak on AppId
| extend BaselineMaxResources = coalesce(BaselineMaxResources, 0)
| where Resources > BaselineMaxResources
| project Hour
    , AppId
    , ServicePrincipalName
    , Resources
    , BaselineMaxResources
    , ResourceNames
    , Ips
| sort by Hour asc

Key Vault

Key Vault is in scope in two ways. Secrets referenced from APIM named values count as exposed even though they live in Key Vault, so they need rotating at source; these logs cannot show whether anyone read them through APIM. And an attacker with a stolen administrator token can go to the vault directly, which H10 and H11 look for.

H10. Key Vault tokens to new identity and IP pairs

Unions successful sign-ins to Key Vault from all three sign-in tables, matched on Key Vault's resource app ID, which is the same in every tenant. Identity and IP pairs the baseline never saw come back. It cannot tell you which secrets were read, only who was given a token that allows reading them and from where. The one detailed victim report describes that kind of token.

Most rows will have no meaningful risk level, and the query labels them so a blank does not get read as clean:

RiskLevelMeaning
n/a (workload identity)Service principal or managed identity. Those tables have no risk column.
not recordedA user sign-in Entra ID Protection did not score. Without Entra ID P2, none are scored.
noneScored, nothing found.
hiddenThe account running the query cannot see risk data.
low, medium, highScored as risky. These sort first.
let KvTokens = union
    (SigninLogs
        | where TimeGenerated between (BaselineStart .. HuntEnd)
        | project TimeGenerated, IdentityType = "User", Identity = UserPrincipalName, IdentityId = UserId, AppId, AppName = AppDisplayName, IPAddress, ResultType, ResourceIdentity, ResourceDisplayName, Location, RiskLevel = iif(isempty(RiskLevelDuringSignIn), "not recorded", RiskLevelDuringSignIn))
    , (AADServicePrincipalSignInLogs
        | where TimeGenerated between (BaselineStart .. HuntEnd)
        | project TimeGenerated, IdentityType = "Service principal", Identity = ServicePrincipalName, IdentityId = ServicePrincipalId, AppId, AppName = ServicePrincipalName, IPAddress, ResultType, ResourceIdentity, ResourceDisplayName, Location, RiskLevel = "n/a (workload identity)")
    , (AADManagedIdentitySignInLogs
        | where TimeGenerated between (BaselineStart .. HuntEnd)
        | project TimeGenerated, IdentityType = "Managed identity", Identity = ServicePrincipalName, IdentityId = ServicePrincipalId, AppId, AppName = ServicePrincipalName, IPAddress, ResultType, ResourceIdentity, ResourceDisplayName, Location, RiskLevel = "n/a (workload identity)")
    // cfa8b339-... is the fixed app ID of Azure Key Vault in every Entra tenant
    | where ResourceIdentity == "cfa8b339-82a2-471a-a3c9-0fc0be7a4093" or ResourceDisplayName =~ "Azure Key Vault"
    | where ResultType == "0"
    | where extract(@"^(\d{1,3}\.\d{1,3})\.", 1, IPAddress) !in (KnownEgressRanges);
let Known = KvTokens
    | where TimeGenerated < HuntStart
    | distinct IdentityId, IPAddress;
KvTokens
| where TimeGenerated between (HuntStart .. HuntEnd)
| join kind=leftanti Known on IdentityId, IPAddress
| summarize FirstToken = min(TimeGenerated)
    , LastToken = max(TimeGenerated)
    , Tokens = count()
    , Apps = make_set(AppName, 10)
    , Locations = make_set(Location, 5)
    , RiskLevels = make_set(RiskLevel, 5)
    by IdentityType, Identity, IdentityId, IPAddress
| extend IsRisky = set_has_element(RiskLevels, "high") or set_has_element(RiskLevels, "medium") or set_has_element(RiskLevels, "low")
| sort by IsRisky desc, FirstToken asc

H11. Key Vault access widened

With an administrator's token, the quickest route to more secrets is to grant yourself access or open the vault firewall. H11 lists access policy writes, vault writes (which include network rules), secret writes, vault deletions and role assignments scoped to a vault, with the principal and role pulled out of the request body. Every row changes who can read secrets, so every row should match a change ticket. Compare GrantedPrincipal with the identities in H10.

AzureActivity
| where TimeGenerated between (HuntStart .. HuntEnd)
| where ActivityStatusValue in~ ("Success", "Succeeded")
| where extract(@"^(\d{1,3}\.\d{1,3})\.", 1, CallerIpAddress) !in (KnownEgressRanges)
| extend Op = tolower(OperationNameValue)
| where Op in (
        "microsoft.keyvault/vaults/accesspolicies/write"
        , "microsoft.keyvault/vaults/write"
        , "microsoft.keyvault/vaults/secrets/write"
        , "microsoft.keyvault/vaults/delete"
        )
    or (Op == "microsoft.authorization/roleassignments/write" and _ResourceId has "microsoft.keyvault/vaults")
| extend Request = parse_json(tostring(parse_json(Properties).requestbody))
| extend GrantedPrincipal = tostring(Request.Properties.PrincipalId)
    , GrantedRole = tostring(Request.Properties.RoleDefinitionId)
    , Vault = extract(@"(?i)/vaults/([^/]+)", 1, _ResourceId)
    , InAffectedSub = SubscriptionId in~ (AffectedSubs)
| project TimeGenerated
    , InAffectedSub
    , Caller
    , CallerIpAddress
    , OperationNameValue
    , Vault
    , GrantedPrincipal
    , GrantedRole
    , _ResourceId
    , CorrelationId
| sort by InAffectedSub desc, TimeGenerated asc

Apps and identities acting in Azure

H12. APIM-linked apps calling Resource Manager

A developer portal identity provider app should have no reason to manage Azure resources. H12 reads the appid claim from each AzureActivity event and keeps the ones in ApimAppIds. Claims_d is empty in some workspaces, so it falls back to the raw Claims text. For identity provider apps, any row is worth a look. An empty result is the normal answer.

AzureActivity
| where TimeGenerated between (HuntStart .. HuntEnd)
// Claims_d is empty in some workspaces, so fall back to the raw Claims text
| extend AppId = tolower(coalesce(tostring(Claims_d.appid), extract(@'"appid"\s*:\s*"([0-9a-fA-F-]{36})"', 1, Claims)))
| where AppId in~ (ApimAppIds)
| where extract(@"^(\d{1,3}\.\d{1,3})\.", 1, CallerIpAddress) !in (KnownEgressRanges)
| extend InAffectedSub = SubscriptionId in~ (AffectedSubs)
| summarize FirstSeen = min(TimeGenerated)
    , LastSeen = max(TimeGenerated)
    , Events = count()
    , AffectedSubEvents = countif(InAffectedSub)
    , Subscriptions = make_set(SubscriptionId, 20)
    , Operations = make_set(OperationNameValue, 50)
    , Resources = make_set(_ResourceId, 50)
    , Ips = make_set(CallerIpAddress, 20)
    by AppId, Caller
| sort by AffectedSubEvents desc, FirstSeen asc

H12a. Can H12 see app IDs at all?

The first row says how many AzureActivity events carry an appid claim. If that is 0, H12 cannot work in your workspace. The other rows show, per app, how many tokens it got for Resource Manager. Zero across the board backs up an empty H12.

let ClaimsCoverage = AzureActivity
    | where TimeGenerated between (HuntStart .. HuntEnd)
    | summarize Rows = count()
        , WithAppId = countif(isnotempty(tostring(Claims_d.appid)) or Claims has "appid");
let ArmTokens = AADServicePrincipalSignInLogs
    | where TimeGenerated between (HuntStart .. HuntEnd)
    | where AppId in~ (ApimAppIds)
    | summarize SignIns = count()
        , ArmSignIns = countif(ResourceDisplayName in~ ("Windows Azure Service Management API", "Azure Resource Manager"))
        , Resources = make_set(ResourceDisplayName, 20)
        by AppId, ServicePrincipalName;
ClaimsCoverage
| extend Check = "AzureActivity claims"
| project Check, Rows, WithAppId
| union (ArmTokens | extend Check = strcat("Sign-ins: ", ServicePrincipalName, " (", AppId, ")"))

H13. The APIM managed identity asking for new things

Administrative access to APIM lets someone change policies so the instance's own identity fetches tokens for other resources. H13 compares the resources each APIM identity requested tokens for in the window with the baseline. A first request for Microsoft Graph, Resource Manager or a storage account suggests a policy changed, possibly through the route that leaves no log. Compare the policies with source control, and check H5 for any policy write that did go through Resource Manager.

let MiSignIns = AADManagedIdentitySignInLogs
    | where TimeGenerated between (BaselineStart .. HuntEnd)
    | where ServicePrincipalId in (ApimIdentities)
    | where extract(@"^(\d{1,3}\.\d{1,3})\.", 1, IPAddress) !in (KnownEgressRanges);
let KnownResources = MiSignIns
    | where TimeGenerated < HuntStart
    | distinct ServicePrincipalId, ResourceIdentity;
MiSignIns
| where TimeGenerated between (HuntStart .. HuntEnd)
| join kind=leftanti KnownResources on ServicePrincipalId, ResourceIdentity
| summarize FirstSeen = min(TimeGenerated)
    , LastSeen = max(TimeGenerated)
    , SignIns = count()
    , Results = make_set(ResultType, 10)
    , Ips = make_set(IPAddress, 20)
    by ServicePrincipalId, ServicePrincipalName, ResourceDisplayName, ResourceIdentity
| sort by FirstSeen asc

H14. Persistence in Entra ID

The sensible attacker adds their own way back in before you rotate. H14 lists successful audit events that add secrets, certificates, federated credentials, owners, consent, app role assignments, delegated permission grants and new service principals, one row per target, with who did it and from where. Your own rotation will show up here too, so look at who made each change. Changes to ApimAppIds apps before 19 November, or one unfamiliar initiator touching several apps, are the ones to chase.

AuditLogs
| where TimeGenerated between (HuntStart .. HuntEnd)
| where OperationName has_any (
    "Certificates and secrets management"
    , "Add service principal credentials"
    , "Update application"
    , "Add owner to application"
    , "Add owner to service principal"
    , "Consent to application"
    , "Add app role assignment to service principal"
    , "Add service principal"
    , "Add delegated permission grant"
    )
| where Result =~ "success"
| mv-expand Target = TargetResources
| extend TargetName = tostring(Target.displayName)
    , TargetId = tostring(Target.id)
    , TargetType = tostring(Target.type)
    , InitiatorUser = tostring(InitiatedBy.user.userPrincipalName)
    , InitiatorApp = tostring(InitiatedBy.app.displayName)
    , InitiatorIp = tostring(InitiatedBy.user.ipAddress)
| where extract(@"^(\d{1,3}\.\d{1,3})\.", 1, InitiatorIp) !in (KnownEgressRanges)
| summarize Changes = count()
    , Operations = make_set(OperationName, 10)
    , FirstChange = min(TimeGenerated)
    , LastChange = max(TimeGenerated)
    by TargetName, TargetId, TargetType, InitiatorUser, InitiatorApp, InitiatorIp
| sort by FirstChange asc

Reading an empty result

Steps one and two of this attack left nothing in customer logs. An empty result across every hunt tells you nobody used the stolen material in a way these tables record, in the window you chose, through addresses you did not exclude. It does not tell you nothing was taken.

Rotate everything NSM lists regardless: named values, identity provider and OpenID Connect secrets, subscription keys, backend credentials, the Key Vault secrets your named values reference (in Key Vault, at source), and the tenant access keys. Then switch off the direct management API on every instance (Management API, Enable Management REST API, set to No) so the route is closed whatever else happens.


What this is not

  • It does not detect the theft. That needed gateway logs, Key Vault audit logs or something Microsoft has not given us.
  • It does not cover stolen subscription keys used against your APIs. That needs ApiManagementGatewayLogs.
  • It does not read Graph activity. If you collect MicrosoftGraphActivityLogs, Anders' post has a hunt for it.
  • The queries have been checked with Microsoft's Kusto.Language parser against the published schemas, and some have been run against live tenants, but not all of them against every tenant shape. Column names drift. Check them against yours.
  • It is not a replacement for rotating credentials.

So: rotate everything, close the direct management API, and keep H7 running. If the old secrets are still out there, that is where they will turn up.

Sources