OAuth Device Code Phishing: The Silent Token Heist Bypassing Your MFA + Video

Listen to this Post

Featured Image

Introduction:

Cybercriminals are constantly evolving their tactics to bypass even the most robust security measures. A recent surge in phishing campaigns, observed by ANY.RUN, highlights a dangerous shift from stealing passwords to directly hijacking authentication tokens. By exploiting Microsoft’s OAuth Device Code flow, attackers are now able to circumvent Multi-Factor Authentication (MFA) and gain persistent access to corporate environments, making traditional phishing indicators nearly useless.

Learning Objectives:

  • Understand the mechanics of the OAuth Device Code phishing attack and why it bypasses MFA.
  • Learn how to detect malicious OAuth applications and unauthorized token usage in your Entra ID (Azure AD) tenant.
  • Implement hardening techniques and conditional access policies to mitigate the risk of token theft.

You Should Know:

1. Anatomy of the Device Code Phishing Attack

This attack does not rely on stealing a user’s password. Instead, it exploits the “Device Authorization Grant” flow, designed for input-constrained devices (like smart TVs or CLI tools). The attacker initiates an authentication request on their own machine, receiving a user code. They then trick the victim into visiting a fake portal (often mimicking DocuSign or a secure document viewer) and entering that code. The victim, believing they are authorizing a legitimate action, logs into the real Microsoft login page and completes MFA. In reality, they are authorizing the attacker’s initial session. Microsoft then issues OAuth tokens (access and refresh tokens) directly to the attacker, granting them access to resources like email, Teams, and SharePoint.

2. Step-by-Step Guide: Simulating and Understanding the Flow

To fully grasp the vulnerability, security professionals can simulate the legitimate flow to understand how it feels from a victim’s perspective.

Step 1: Initiate the Flow (Attacker Side – Linux/macOS)
Using curl, you can simulate the initial request to get a device code. (Note: Replace `TENANT_ID` and CLIENT_ID—attackers often use legitimate public client IDs like those for Microsoft CLI).

curl -X POST https://login.microsoftonline.com/TENANT_ID/oauth2/v2.0/devicecode \
-d "client_id=CLIENT_ID&scope=https://graph.microsoft.com/.default"

What it does: This command requests a device code. The response includes a `user_code` (e.g., ABC123DEF) and a `verification_uri` (e.g., `https://microsoft.com/devicelogin`).

Step 2: The Lure (Victim Side)

The attacker sends a phishing email with the `user_code` and a link to the legitimate verification_uri. The victim enters the code.

Step 3: Polling for Authentication (Attacker Side)

The attacker continuously polls Microsoft’s token endpoint using the `device_code` obtained in step one. Once the victim enters the code and completes MFA, this command returns the tokens.

curl -X POST https://login.microsoftonline.com/TENANT_ID/oauth2/v2.0/token \
-d "client_id=CLIENT_ID&grant_type=urn:ietf:params:oauth:grant-type:device_code&device_code=DEVICE_CODE"

Output: The attacker receives an `access_token` and a refresh_token, granting them unauthorized access.

3. Detecting Malicious OAuth Applications with PowerShell

Once the attacker has a refresh token, they can use it to maintain access indefinitely. Blue teams must hunt for suspicious OAuth applications that were granted high privileges.

Step 1: Connect to Microsoft Graph

Run this in PowerShell (as a Global Admin or Security Admin):

Connect-MgGraph -Scopes "Application.Read.All", "AuditLog.Read.All", "Directory.Read.All"

Step 2: List OAuth Applications with High Privileges

This script identifies applications that have been granted powerful Graph permissions (like `Mail.Read` or Files.ReadWrite.All), which are common targets for attackers.

Get-MgServicePrincipal -All | Where-Object {
$<em>.AppRoles -or $</em>.Oauth2PermissionScopes
} | ForEach-Object {
$sp = $_
$sp.AppRoles | ForEach-Object {
[bash]@{
AppName = $sp.DisplayName
AppId = $sp.AppId
PermissionType = "AppRole"
Permission = $<em>.Value
}
}
$sp.Oauth2PermissionScopes | ForEach-Object {
[bash]@{
AppName = $sp.DisplayName
AppId = $sp.AppId
PermissionType = "Delegated"
Permission = $</em>.Value
}
}
} | Out-GridView

What it does: This command fetches all service principals and displays their granted permissions in a grid view for manual analysis, looking for anomalies.

4. Hunting for Device Code Authentication Events

To identify if this specific flow has been used in your tenant, you must query the Azure AD Sign-in logs.

Step 1: Use Azure Monitor or the Graph API
The following Kusto Query Language (KQL) query can be run in Azure Log Analytics to find sign-ins using the device code flow:

SigninLogs
| where TimeGenerated > ago(7d)
| where AuthenticationRequirement contains "multiFactorAuthentication"
| where AuthenticationProtocol == "deviceCode"
| project TimeGenerated, UserPrincipalName, AppDisplayName, ClientAppUsed, IPAddress, Country, IsInteractive
| order by TimeGenerated desc

What to look for: Device code flows are rarely used interactively by standard users. Any occurrence, especially from unfamiliar IP ranges or outside business hours, warrants investigation.

  1. Hardening Entra ID: Conditional Access to the Rescue
    The most effective mitigation is to block the device code flow entirely for all users except where explicitly required (e.g., for automation accounts).

Step 1: Create a Conditional Access Policy

Navigate to the Azure Portal -> Entra ID -> Security -> Conditional Access -> New Policy.

Step 2: Configure the Policy

  • Name: Block OAuth Device Code Flow
  • Assignments -> Users: All users (or exclude break-glass accounts).
  • Assignments -> Cloud apps or actions: All cloud apps.
  • Conditions -> Authentication Flows: Select “Device code flow” and set the configure toggle to “Yes”. Check the box.
  • Access Controls -> Grant: Select “Block access”.
  • Enable policy: Set to “Report-only” initially to monitor impact, then “On”.

6. Incident Response: Revoking a Compromised Refresh Token

If a compromised token is identified, it must be immediately revoked to cut off the attacker’s access.

Step 1: Revoke User Sessions (PowerShell)

This forces the user to re-authenticate and invalidates all refresh tokens issued to that user.

 Connect to Azure AD (MSOnline module - Legacy, but effective)
Connect-MsolService
 Revoke all sessions for a specific user
Revoke-MsolUserSession -UserPrincipalName "[email protected]"

Note: In Microsoft Graph PowerShell, you can use Revoke-MgUserSignInSession -UserId "[email protected]".

Step 2: Investigate and Remove Malicious Apps

If a specific malicious application was authorized, it should be removed. This requires reviewing the “Enterprise applications” blade in Entra ID and deleting the service principal associated with the attacker’s app registration.

 Remove a malicious service principal by its AppId
Remove-MgServicePrincipal -ServicePrincipalId "OBJECT_ID_OF_SP"

What Undercode Say:

  • Tokens are the new gold: This attack demonstrates that MFA is not a silver bullet. The security community must shift focus from merely securing passwords to rigorously protecting the token issuance and validation pipeline. The compromise is silent and occurs after MFA is satisfied.
  • Proactive hardening is essential: Relying on user awareness to detect this type of phishing is insufficient because the final login happens on a legitimate Microsoft domain. Technical controls, specifically Conditional Access policies to restrict authentication flows, are the only reliable defense. Organizations that treat Entra ID security as a luxury will inevitably face credential theft.
  • The HadesHunter tool mentioned serves as a stark reminder that once an attacker has a refresh token, they can automate the discovery of even more secrets within your environment (Teams, SharePoint). This creates a compounding effect, turning a single token theft into a full-blown data breach.

Prediction:

This OAuth Device Code phishing technique will rapidly become the default vector for Business Email Compromise (BEC) attacks. As detection for this method improves, we will likely see attackers pivot to abusing other less-monitored OAuth grant types and targeting third-party SaaS applications integrated with Entra ID. The future of identity-based attacks lies in token abuse, forcing a complete overhaul of how we monitor authentication logs and trust “successful” logins.

▶️ Related Video (86% Match):

🎯Let’s Practice For Free:

IT/Security Reporter URL:

Reported By: Kondah Les – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

🔐JOIN OUR CYBER WORLD [ CVE News • HackMonitor • UndercodeNews ]

💬 Whatsapp | 💬 Telegram

📢 Follow UndercodeTesting & Stay Tuned:

𝕏 formerly Twitter 🐦 | @ Threads | 🔗 Linkedin | 🦋BlueSky