Listen to this Post

Introduction:
A recent widespread phishing campaign has successfully bypassed Multi-Factor Authentication (MFA) for over 340 organizations globally, not by exploiting a technical vulnerability in Microsoft 365, but by abusing a legitimate authentication mechanism. Attackers are leveraging OAuth token theft through device code phishing, allowing them to maintain persistent access to Exchange, SharePoint, and Teams for up to 90 days—even after victims reset their passwords. This attack highlights a critical gap in identity security: MFA alone is no longer sufficient to prevent modern token-based compromises.
Learning Objectives:
- Understand how attackers use device code authentication to steal OAuth tokens without requiring user credentials.
- Learn to detect and mitigate token theft using Conditional Access policies, Microsoft Sentinel, and identity hardening techniques.
- Implement step-by-step incident response procedures to revoke compromised tokens and prevent lateral movement.
You Should Know:
- The Anatomy of OAuth Token Theft via Device Code Phishing
This attack begins with the adversary initiating a device code authentication flow against a legitimate Microsoft 365 application. Unlike traditional phishing that steals passwords, this method targets the OAuth 2.0 device authorization grant. The attacker generates a device code and URL, then tricks the victim into entering the code on a legitimate Microsoft login page. Once the victim authenticates and approves MFA, the attacker receives a valid refresh token, which can be used to generate access tokens for up to 90 days.
Step-by-step guide explaining what this does and how to use it (from a defensive perspective):
1. Simulate the Attack (For Testing):
- Use a tool like `token-tester` or `Evilginx2` to act as a proxy. The attacker configures a phishing page mimicking the Microsoft device code entry screen.
- Command (Linux): `evilginx2 -p phishlet_name` to start a phishing proxy that captures tokens.
- The attacker sends the victim a link: `https://microsoft.com/devicelogin` (legitimate) with a pre-generated code or directs them to a fake page that captures the code.
- Once the victim enters the code and completes MFA, the proxy captures the
refresh_token.
2. Extract and Use the Token (Defender Awareness):
- The attacker uses the captured token via PowerShell or Azure CLI.
- PowerShell (Windows):
$Response = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/common/oauth2/v2.0/token" -Body @{ client_id = "your_client_id" grant_type = "refresh_token" refresh_token = "captured_token" scope = "https://graph.microsoft.com/.default" } $Response.access_token - This generates a new access token, allowing access to mail, SharePoint, and Teams without a password.
3. Detection:
- Monitor Azure AD Sign-In Logs for `Client app` = “Device Code Flow” with unusual locations or user agents.
- Use KQL (Kusto Query Language) in Microsoft Sentinel:
AADSignInEventsBeta | where ClientAppUsed == "Device Code Flow" | where ResultType == 0 // Success | where Country != "ExpectedCountry" | summarize by AccountUpn, IPAddress, Country, Timestamp
- Why MFA Alone Fails: Token Replay and Conditional Access Gaps
Traditional MFA assumes that if a user passes a push notification or TOTP, the session is secure. However, device code phishing captures the token after MFA is satisfied. The attacker then replays this token from their own infrastructure, effectively impersonating the user. Even if the victim changes their password, the refresh token remains valid until it expires or is explicitly revoked. This is because OAuth tokens are tied to the application session, not the user’s password.
Step-by-step guide explaining what this does and how to use it (mitigation):
1. Enforce Conditional Access Policies:
- Navigate to Azure AD > Security > Conditional Access.
- Create a policy targeting “All cloud apps” with conditions for “Device Code Flow.”
- Set “Grant” to “Require compliant device” or “Require hybrid joined device.” This blocks token requests from non-managed devices.
- PowerShell (AzureAD module) to check policy application:
Get-AzureADMSConditionalAccessPolicy | Where-Object {$_.Conditions.Applications.IncludeUserActions -eq "None"} | Select-Object DisplayName, State
2. Restrict Token Lifetimes:
- While Microsoft recommends using default settings, you can use Conditional Access Authentication Context to reduce token validity for sensitive apps.
- Configure token lifetime via PowerShell (though Microsoft recommends moving to Conditional Access):
New-AzureADPolicy -Definition @('{"TokenLifetimePolicy":{"Version":1,"AccessTokenLifetime":"0.02:00:00","MaxAgeSingleFactor":"0.08:00:00"}}') -DisplayName "ShortLivedTokens" -Type "TokenLifetimePolicy"
3. Block Legacy Authentication:
- Ensure legacy protocols (POP3, IMAP, SMTP) are disabled, but note that device code flow is considered modern authentication. It must be explicitly blocked via Conditional Access if not required.
3. Detection Engineering in Microsoft Sentinel and SIEM
Detecting token theft requires moving beyond simple logins to understanding authentication context and anomalous behavior. The key is identifying the use of a refresh token from an unrecognized location or device immediately after a legitimate login.
Step-by-step guide explaining what this does and how to use it:
1. Create a Detection Rule for Token Anomalies:
- In Microsoft Sentinel, use the following KQL to detect a login from a new country within 10 minutes of a device code flow:
let DeviceCodeLogins = AADSignInEventsBeta | where ClientAppUsed == "Device Code Flow" | where ErrorCode == 0 | project AccountUpn, DeviceCodeTimestamp=Timestamp, DeviceCodeIP=IPAddress; let SubsequentLogins = AADSignInEventsBeta | where ClientAppUsed != "Device Code Flow" | project AccountUpn, LoginTimestamp=Timestamp, LoginIP=IPAddress; DeviceCodeLogins | join SubsequentLogins on AccountUpn | where LoginTimestamp > DeviceCodeTimestamp | where LoginIP != DeviceCodeIP | extend TimeDifference = datetime_diff('minute', LoginTimestamp, DeviceCodeTimestamp) | where TimeDifference < 10 - This rule identifies a refresh token being used from a different IP shortly after the device code was authorized.
2. Hunt for Service Principal Consent Grants:
- Attackers often use malicious apps. Hunt for high-risk OAuth consent grants:
AADAdminConsent | where ConsentType == "AllPrincipals" | where InitiatingUser != "" | extend AppId = tostring(AdditionalDetails[bash].Key) | project Timestamp, AppId, AppDisplayName, InitiatingUser, ConsentType
4. Incident Response: Revoking Tokens and Remediation
Once a token theft is confirmed, password resets are ineffective. The incident response team must revoke all refresh tokens for the compromised user and investigate any created service principals or mailbox rules.
Step-by-step guide explaining what this does and how to use it:
1. Revoke Sessions and Tokens:
- Azure Portal: Go to Azure AD > Users > select user > “Revoke sessions.” This invalidates all tokens.
- PowerShell (Microsoft Graph):
Connect-MgGraph -Scopes "User.ReadWrite.All" Revoke-MgUserSignInSession -UserId "[email protected]"
2. Check for Mailbox Forwarding Rules (Exchange Online):
- Attackers often set up stealthy rules to exfiltrate data.
- PowerShell (Exchange Online Module):
Get-InboxRule -Mailbox [email protected] | Format-List Name, Description, ForwardTo, DeleteMessage Remove-InboxRule -Mailbox [email protected] -Identity "RuleName" -Confirm:$false
3. Audit OAuth Applications:
- Use Microsoft Graph API to list and revoke unauthorized apps:
Get-MgUserOAuth2PermissionGrant -UserId "[email protected]" | Where-Object {$<em>.Scope -like "Mail.Read"} | Remove-MgUserOAuth2PermissionGrant -OAuth2PermissionGrantId $</em>.Id
- Hardening Azure AD and Conditional Access for Token Security
To prevent future occurrences, organizations must implement a Zero Trust model that treats tokens as primary attack vectors. This involves geographic restrictions, risk-based policies, and device compliance.
Step-by-step guide explaining what this does and how to use it:
1. Implement Risk-Based Conditional Access:
- Use Azure AD Identity Protection to automate responses to risky sign-ins.
- Create a policy: “Require password change” for medium/high risk users and “Block access” for token replay anomalies.
2. Disable Device Code Flow If Unused:
- If your organization does not require device code authentication (common in CI/CD or embedded systems), block it via Conditional Access.
- Configuration: Create a Conditional Access policy targeting “All users” > Cloud apps > “All apps” > Conditions > Client apps > Select “Device Code Flow” > Grant > “Block access.”
3. Continuous Monitoring with Workbooks:
- Deploy the Microsoft 365 “Authentication methods usage & insights” workbook to track token issuance trends.
- Monitor for spikes in “Device Code Flow” sign-ins, which may indicate a phishing campaign.
What Undercode Say:
- Token is the new perimeter. Attackers are shifting focus from stealing passwords to stealing tokens, rendering traditional MFA obsolete if not paired with device compliance and risk-based policies.
- Detection requires context. Without analyzing authentication chains (device code flow followed by anomalous logins), token theft remains invisible in standard logs. Proactive hunting using KQL is essential.
- Mitigation is policy-driven. Conditional Access remains the strongest control. Blocking device code flow entirely, or enforcing it only from compliant devices, eliminates the attack vector for most organizations.
Prediction:
As identity providers increasingly enforce passwordless authentication, token-based attacks will become the dominant vector for enterprise breaches. We predict a rise in adversary-in-the-middle (AiTM) phishing kits specifically targeting OAuth flows, alongside regulatory shifts mandating short token lifetimes and real-time revocation capabilities. Organizations that fail to implement Conditional Access policies to govern token issuance will face inevitable compromise, as the sophistication of token replay attacks outpaces traditional incident response timelines.
▶️ Related Video (78% Match):
🎯Let’s Practice For Free:
IT/Security Reporter URL:
Reported By: Kondah Cette – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


