Device Code Phishing: How Attackers Bypass MFA by Abusing OAuth 20 Device Flow + Video

Listen to this Post

Featured Image

Introduction:

The OAuth 2.0 device authorization grant flow, designed for input-constrained devices like smart TVs and printers, is being weaponized in a sophisticated phishing campaign. Instead of stealing credentials, attackers trick users into entering a legitimate verification code on a real Microsoft login page, allowing them to hijack the OAuth token and gain persistent, MFA-bypassing access to corporate email and cloud files.

Learning Objectives:

  • Understand the mechanics of the device code phishing attack and how it differs from traditional credential harvesting.
  • Learn how to detect this threat using Microsoft 365 audit logs, PowerShell, and Kusto Query Language (KQL).
  • Implement effective mitigations including Conditional Access policies and user education to block token theft.

You Should Know:

1. Anatomy of the Device Code Phishing Attack

The attack leverages the OAuth 2.0 device code flow, a standard protocol intended for devices that cannot directly access a web browser. In this flow, the device displays a code and a URL (e.g., microsoft.com/devicelogin). The user signs in on their browser and enters the code, and the device polls Microsoft for an access token.

Attackers automate this process. They generate their own device code request to a legitimate OAuth endpoint (like Microsoft’s login.microsoftonline.com). The attacker then sends the code and URL to the victim via a phishing email (e.g., a fake “February Asset Report Statement” on Dropbox DocSend). The victim, believing they are authorizing access to a shared file, visits the legitimate Microsoft page and enters the code. The attacker’s script immediately receives the access and refresh tokens, granting them long-term access without ever needing the victim’s password or a multi-factor authentication (MFA) code.

Step‑by‑step guide explaining the flow:

  1. Attacker Setup: The attacker registers a malicious application with Microsoft Entra ID (or uses a pre-existing one). They initiate the device code flow against the Microsoft OAuth 2.0 endpoint (/devicecode).
  2. Phishing Lure: The victim receives an email impersonating a legitimate service (e.g., “The Dropbox DocSend Team”) with a “View Content” button.
  3. Redirection: Clicking the link leads to a fake OneDrive or SharePoint page that displays a “verification code” (the one generated by the attacker) and instructs the user to “Continue to Microsoft.”
  4. User Interaction: The victim is redirected to the legitimate `microsoft.com/devicelogin` page and enters the provided code. The user believes they are authenticating to access a file.
  5. Token Harvesting: Once the user enters the code, the attacker’s script, which has been polling the token endpoint, receives the access token and refresh token. The attacker now has a valid session.
  6. Post-Exploitation: The attacker uses the stolen tokens to access the victim’s email via Microsoft Graph API, SharePoint, and OneDrive, bypassing password policies and MFA.

2. Detection and Hunting with Logs and Commands

Detecting this attack requires analyzing authentication logs for anomalies in the device code flow. Security teams should focus on the `AuthenticationDetails` in Microsoft Entra ID sign-in logs.

Using PowerShell to Identify Device Code Logins:

The following command uses the `Microsoft Graph` module to retrieve sign-in logs where the authentication protocol was “deviceCode”.

 Install and import Microsoft Graph module if not already done
 Install-Module Microsoft.Graph -Scope CurrentUser

Connect-MgGraph -Scopes "AuditLog.Read.All"

Retrieve sign-in logs for device code flow in the last 7 days
Get-MgAuditLogSignIn -Filter "clientAppUsed eq 'Device Code Flow'" -All | 
Select-Object UserPrincipalName, AppDisplayName, CreatedDateTime, IPAddress, 
Status, AuthenticationRequirement | 
Export-Csv -Path "DeviceCodeLogins.csv" -NoTypeInformation

Using Kusto Query Language (KQL) in Microsoft Sentinel:

To hunt for these activities, analysts can use the following query against the `SigninLogs` table:

SigninLogs
| where ClientAppUsed == "Device Code Flow"
| where ResultType == 0 // Successful sign-in
| where TimeGenerated > ago(7d)
| project TimeGenerated, UserPrincipalName, AppDisplayName, IPAddress, 
AuthenticationRequirement, Location = tostring(LocationDetails.city)
| sort by TimeGenerated desc

Linux/Unix Command Line:

While the attack targets Microsoft environments, defenders can use `curl` to simulate the device code flow for testing purposes. This helps security teams understand how an attacker sees the token response.

 Step 1: Request device code and user code
curl -X POST https://login.microsoftonline.com/common/oauth2/v2.0/devicecode \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "client_id=YOUR_CLIENT_ID&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2F.default"

Step 2: After user enters code, poll for token (simulating attacker)
curl -X POST https://login.microsoftonline.com/common/oauth2/v2.0/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code&client_id=YOUR_CLIENT_ID&device_code=DEVICE_CODE_FROM_STEP1"

3. Mitigation: Conditional Access and Policy Hardening

Preventing device code flow abuse requires configuration changes within Microsoft Entra ID, as the flow is enabled by default for all users.

Step‑by‑step guide to block device code flow:

1. Create a Conditional Access Policy:

  • Navigate to Microsoft Entra Admin Center > Protection > Conditional Access.
  • Create a new policy targeting All users (or exclude a break-glass account).
  • Under Cloud apps or actions, include All cloud apps.
  • Under Conditions, go to Client apps.
  • Select Configure Yes, and under Other clients, check Device code flow.
  • Set Access controls to Block.
  • Enable the policy and test with a pilot group first.

2. Disable Device Code Flow for Specific Applications:

If blocking globally is too restrictive, identify and block the malicious applications used in the attack.
– Use PowerShell to find apps using device code flow and disable it via application manifest.
– Microsoft Graph API Command:

PATCH https://graph.microsoft.com/v1.0/applications/{object-id}
{
"web": {
"implicitGrantSettings": {
"enableDeviceCode": false
}
}
}

3. Enforce Token Protection:

Configure Conditional Access policies to enforce session lifetime and token protection to limit the validity of stolen refresh tokens. Set sign-in frequency to “Every time” for high-risk users.

4. User Awareness and Triage

The phishing email in the attack uses a legitimate “Copy Code” button and a fake OneDrive interface. Users should be trained to recognize that legitimate services will not ask them to enter a code received via email on a third-party page unless they initiated the process themselves.

Step‑by‑step guide for user triage:

  1. Identify Suspicious Communications: Look for emails requesting immediate action to access a shared document, especially those with “Verify your identity” instructions.
  2. Verify the URL: The Microsoft device login page is legitimate (`https://microsoft.com/devicelogin`). However, users should check the context. If they were not prompted to sign in on a new device, they should never enter a code.
  3. Revoke Sessions: If a user suspects they have been phished, they must immediately:

– Go to `https://mysignins.microsoft.com/security-info`.
– Select “Sign out everywhere” to revoke all active sessions and refresh tokens.
– Change their password and register for a new MFA method.

5. Incident Response: Revoking Stolen Tokens

When a compromised token is identified, simply resetting the password is insufficient. Refresh tokens can persist for up to 90 days. The following steps must be taken to invalidate the attacker’s access.

Step‑by‑step guide to revoke tokens:

1. Revoke All Sessions via PowerShell:

 Connect to Microsoft Graph
Connect-MgGraph -Scopes "User.Read.All", "UserAuthenticationMethod.ReadWrite.All"

Revoke all refresh tokens for the compromised user
Revoke-MgUserAllRefreshToken -UserId "[email protected]"

2. Reset Password and Require Re-registration:

  • Reset the user’s password.
  • Use the Azure AD portal or PowerShell to require the user to re-register for MFA.
  • Command to require MFA re-registration:
    Get-MgUserAuthenticationMethod -UserId "[email protected]" | Remove-MgUserAuthenticationMethod
    

3. Investigate Attacker Activity:

  • Use `Search-UnifiedAuditLog` in PowerShell to check for mailbox rules created by the attacker.
  • Review SharePoint and OneDrive access logs for unusual data exfiltration patterns.

What Undercode Say:

  • Token Theft is the New Credential Theft: Modern phishing attacks are moving beyond password capture to focus on session hijacking and token theft, rendering traditional MFA ineffective against adversary-in-the-middle (AiTM) techniques.
  • Configuration is Key: The device code flow, while useful for legitimate scenarios, is a massive security gap if left enabled for all users. A simple Conditional Access policy blocking “Other clients” can neutralize this entire attack vector.
  • Detection Requires Granular Logging: Without examining `clientAppUsed` or `authenticationProtocol` fields in sign-in logs, security teams remain blind to these attacks. Integrating Microsoft 365 logs into a SIEM is critical for hunting such non-interactive sign-ins.

Prediction:

As Microsoft and other cloud providers continue to push for passwordless authentication, attackers will increasingly focus on abusing legitimate OAuth 2.0 flows and API permissions. The device code phishing technique will likely evolve into automated attacks targeting service accounts and headless systems, making the implementation of Conditional Access policies and continuous token hygiene mandatory for every organization. The future of identity security will hinge not on preventing initial compromise, but on rapidly detecting and invalidating post-authentication token misuse.

▶️ Related Video (82% Match):

🎯Let’s Practice For Free:

IT/Security Reporter URL:

Reported By: A Phishing – 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