Security teams are actively contending with a sophisticated social engineering campaign codenamed "DEBULL" that is hijacking Microsoft 365 accounts by abusing the legitimate Microsoft device code authentication flow. Observed by ZeroBEC between the last week of June 2026 and continuing into early July, this campaign represents a significant evolution in phishing techniques — one that bypasses traditional credential theft detection by leveraging Microsoft's own authentication infrastructure.
Unlike conventional phishing attacks that employ fraudulent login pages designed to harvest credentials directly, DEBULL instead manipulates users into initiating a legitimate device code authentication on Microsoft's official servers. Once the user completes the authentication flow on a legitimate Microsoft endpoint, the attackers (who initiated the device code request) obtain valid refresh tokens and gain persistent access to the victim's account. This technique is particularly dangerous because it bypasses many email security filters, credential protection mechanisms, and may even satisfy conditional access policies depending on configuration.
Defenders must act now to detect this activity and implement compensating controls, as the attack leverages a legitimate authentication mechanism rather than exploiting a vulnerability that can be simply patched.
Technical Analysis
Attack Mechanics
The DEBULL campaign abuses the OAuth 2.0 Device Authorization Grant flow (RFC 8628), a legitimate mechanism designed for devices with limited input capabilities (such as smart TVs, IoT devices, or command-line interfaces) to authenticate users. The attack chain unfolds as follows:
-
Initial Compromise/Lure: Attackers send collaboration-themed social engineering lures to targets (e.g., "Review this document shared via Teams" or "Project plan requires your approval"). These messages contain instructions to visit a specific Microsoft device login URL (e.g.,
microsoft.com/devicelogin) and enter a provided code. -
Device Code Generation: The attacker's infrastructure initiates a device code request to the Microsoft identity platform (
https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/devicecode), receiving a user code, device code, and verification URI. -
User Interaction: The victim, believing they are accessing a legitimate collaboration resource, visits the verification URI and enters the user code. This is a genuine Microsoft login page — not a phishing site.
-
Authentication Completion: The victim completes multi-factor authentication (if required) and consents to the requested permissions. Microsoft issues tokens to the device code endpoint.
-
Token Harvesting: The attacker's system polls the token endpoint (
https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token) with the device code until authentication is complete, then captures the access token, refresh token, and ID token. -
Session Establishment: Attackers use the obtained tokens to authenticate as the victim, establishing persistent access that may remain valid for extended periods depending on refresh token lifetime policies.
Affected Components
- Microsoft Entra ID (formerly Azure AD): All tenants allowing device code flow authentication
- Microsoft 365 Services: Exchange Online, SharePoint Online, Teams, OneDrive
- OAuth 2.0 Device Authorization Grant Endpoint:
login.microsoftonline.com
Exploitation Status
- Confirmed Active Exploitation: ZeroBEC has confirmed active campaigns in late June 2026 through early July 2026
- Technique, Not Vulnerability: This abuse of a legitimate protocol feature, not a software vulnerability requiring a CVE
- No Patch Available: Remediation requires configuration changes, not software updates
Detection & Response
SIGMA Rules
---
title: Potential Microsoft Device Code Flow Phishing - User Initiated from Unusual Context
id: 3a8f7d2e-1b9c-4f5e-9c3d-2e1b5a6c7d8f
status: experimental
description: Detects potential device code flow attack when user initiates device login following suspicious email activity or from unexpected location context. This correlates email reception with subsequent device code authentication attempts.
references:
- https://attack.mitre.org/techniques/T1078/
- https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-device-code
author: Security Arsenal
date: 2026/07/02
tags:
- attack.valid_accounts
- attack.t1078.004
logsource:
product: azure
service: signinlogs
detection:
selection:
AppDisplayName|contains: 'Microsoft Device Code'
AuthenticationRequirement: 'singleFactorAuthentication' or 'multiFactorAuthentication'
filter_legitimate:
DeviceDetail|contains:
- 'Windows'
- 'macOS'
- 'iOS'
- 'Android'
condition: selection and not filter_legitimate
falsepositives:
- Legitimate device code authentication from IoT devices or CLI tools
- Developers testing device code flow applications
level: medium
---
title: Microsoft 365 Device Code Authentication from Impossible Travel Location
id: 7b4e9f3a-2c1d-4e8f-a3b5-6c7d8e9f0a1b
status: experimental
description: Detects device code flow authentications exhibiting impossible travel patterns — rapid successful logins from geographically distant locations, which may indicate an attacker-triggered device code flow authenticated by a victim elsewhere.
references:
- https://attack.mitre.org/techniques/T1078/
author: Security Arsenal
date: 2026/07/02
tags:
- attack.valid_accounts
- attack.t1078.004
logsource:
product: azure
service: signinlogs
detection:
selection:
AppDisplayName|contains: 'Device Code'
Status: 'Success'
timeframe: 2h
timeframe: true
condition: selection | count() by UserPrincipalName > 1
correlation:
type: value_count
rules:
- selection
group-by:
- UserPrincipalName
timeframe: 2h
condition:
gte: 2
falsepositives:
- Users traveling legitimately while using device code authentication
- Shared accounts accessed from multiple global offices
level: high
---
title: Suspicious OAuth Application Permissions Granted via Device Code Flow
id: 9c2f4e8b-5d3e-4f9a-b1c6-7d8e9f0a1b2c
status: experimental
description: Detects when high-risk OAuth permissions are consented during device code flow authentication, which may indicate an attacker harvesting tokens with elevated privileges.
references:
- https://attack.mpire.org/techniques/T1136/
author: Security Arsenal
date: 2026/07/02
tags:
- attack.persistence
- attack.t1136.003
logsource:
product: azure
service: auditlogs
detection:
selection:
OperationName:
- 'Consent to application'
- 'Add app role assignment to service principal'
Category: 'ApplicationManagement'
filter_device_code:
InitiatedBy|contains: 'Device Code'
filter_high_privilege:
Permissions|contains:
- 'Mail.ReadWrite'
- 'Files.ReadWrite.All'
- 'User.ReadWrite.All'
- 'Directory.ReadWrite.All'
condition: selection and filter_device_code and filter_high_privilege
falsepositives:
- Legitimate admin consent for required applications
- User self-consent for approved productivity apps
level: high
KQL (Microsoft Sentinel / Defender)
// Hunt for suspicious device code authentication patterns
// Identify users with device code logins from unusual locations or correlating with phishing
let DeviceCodeSignins = SigninLogs
| where AppDisplayName contains "Device Code"
| where ResultType == 0
| project TimeGenerated, UserPrincipalName, AppDisplayName, IPAddress,
Location, DeviceDetail, ConditionalAccessStatus, RiskDetail;
// Correlate with recent suspicious email activity (if available)
let SuspiciousEmails = EmailEvents
| where Timestamp > ago(7d)
| where ThreatTypes has_any ("Phish", "Malware")
| where RecipientEmailAddress has_any (DeviceCodeSignins | project UserPrincipalName)
| project RecipientEmailAddress, Timestamp, Subject, SenderFromAddress;
// Join to find users who received phishing emails and then used device code auth
DeviceCodeSignins
| join kind=inner SuspiciousEmails on $left.UserPrincipalName == $right.RecipientEmailAddress
| where TimeGenerated between (Timestamp - 1h .. Timestamp + 24h)
| project TimeGenerated, UserPrincipalName, IPAddress, Location, Subject,
SenderFromAddress, ConditionalAccessStatus
| order by TimeGenerated desc
---
// Detect impossible travel patterns with device code authentication
SigninLogs
| where AppDisplayName contains "Device Code"
| where ResultType == 0
| summarize FirstSeen=min(TimeGenerated), LastSeen=max(TimeGenerated),
Count=count(),
IPAddresses=make_set(IPAddress),
Locations=make_set(Location),
Countries=make_set(LocationDetails.CountryOrRegion)
by UserPrincipalName
| where Count > 1
| extend TimeDiff = datetime_diff('hour', LastSeen, FirstSeen)
| where TimeDiff < 4 // Multiple device code logins within 4 hours
| where array_length(Countries) > 1
| project UserPrincipalName, FirstSeen, LastSeen, TimeDiff,
IPAddresses, Locations, Countries
---
// Identify OAuth token issuances via device code flow with sensitive scopes
AuditLogs
| where OperationName in ("Consent to application", "Add OAuth2PermissionGrant",
"Add service principal")
| where Timestamp > ago(7d)
| extend InitiatedByActor = tostring(InitiatedBy.user.userPrincipalName)
| extend InitiatedByApp = tostring(InitiatedBy.app.displayName)
| where InitiatedByApp contains "Device" or InitiatedByActor contains "Device"
| parse TargetResources[*].modifiedProperties with *
'"Scope":"' Scope '"' *
'"ConsentType":"' ConsentType '"' *
'"ClientId":"' ClientId '"' *
| where Scope has_any ("ReadWrite.All", "FullControl", "Application.ReadWrite.All",
"Directory.ReadWrite.All", "RoleManagement")
| project Timestamp, OperationName, InitiatedByActor, InitiatedByApp,
Scope, ConsentType, ClientId, ActorIpAddress = InitiatedBy.user.ipAddress
| order by Timestamp desc
Velociraptor VQL
-- Hunt for browser artifacts related to Microsoft device code flow phishing
-- This searches for recent visits to device login pages in common browser history
SELECT
timestamp(string=LastVisitedTime) AS EventTime,
Username,
URL,
Title,
VisitCount,
TypedCount
FROM glob(globs="*/History", root=expand(path=%"%LocalAppData%\Google\Chrome\User Data\*"))
WHERE URL =~ "microsoft.com/devicelogin"
OR URL =~ "login.microsoftonline.com.*devicecode"
OR URL =~ "microsoft.com/link"
OR Title =~ "sign in"
ORDER BY EventTime DESC
LIMIT 100
---
-- Check for recent OAuth token usage patterns that may indicate device code abuse
-- This examines cached credentials and tokens in Microsoft authentication caches
SELECT
Mtime AS LastModified,
Size,
FullPath,
Mode
FROM glob(globs="**/MicrosoftIdentityCache*", root=expand(path=%"%LocalAppData%"))
WHERE Mtime > now() - 24h
OR FullPath =~ "TokenCache"
ORDER BY LastModified DESC
LIMIT 50
---
-- Identify PowerShell or command-line activity that may be polling OAuth token endpoints
-- Attackers using DEBULL-style tooling may use scripts to poll for tokens
SELECT
Pid,
Name,
CommandLine,
Exe,
Username,
CreateTime
FROM pslist()
WHERE CommandLine =~ "devicecode"
OR CommandLine =~ "oauth2/token"
OR CommandLine =~ "login.microsoftonline.com.*token"
OR Exe =~ "powershell"
AND CommandLine =~ "Invoke-WebRequest"
AND CommandLine =~ "login.microsoftonline"
ORDER BY CreateTime DESC
Remediation Script (PowerShell)
# Microsoft 365 Device Code Flow Hardening Script
# Use this to assess current configuration and apply security controls
# Connect to Microsoft Graph - required for all operations
# Ensure proper permissions: Policy.Read.All, Policy.ReadWrite.ConditionalAccess, RoleManagement.Read.Directory
Write-Host "Connecting to Microsoft Graph..."
Connect-MgGraph -Scopes "Policy.Read.All","Policy.ReadWrite.ConditionalAccess","RoleManagement.Read.Directory" -NoWelcome
# Function to check if device code flow is disabled via authentication method policy
function Get-DeviceCodeFlowPolicy {
param(
[string]$PolicyId = "DeviceCodeFlowPolicy"
)
try {
$policy = Get-MgPolicyAuthenticationMethodPolicy -AuthenticationMethodPolicyId $PolicyId -ErrorAction SilentlyContinue
return $policy
} catch {
Write-Warning "Could not retrieve device code flow policy."
return $null
}
}
# Function to audit conditional access policies for device code flow coverage
function Test-DeviceCodeConditionalAccess {
Write-Host "`n[+] Auditing Conditional Access Policies for Device Code Flow Coverage..." -ForegroundColor Cyan
$policies = Get-MgIdentityConditionalAccessPolicy -All
$deviceCodePolicies = @()
$excludedUsers = @()
foreach ($policy in $policies) {
$state = $policy.State
if ($state -eq "disabled" -or $state -eq "enabledForReportingButNotEnforced") {
continue
}
# Check if policy applies to device code authentication
$clientAppTypes = $policy.Conditions.ClientAppTypes
$filterPlatforms = $policy.Conditions.Platforms.Filter
# Check for device code specific configurations
$policyJson = $policy | ConvertTo-Json -Depth 10
if ($policyJson -match "deviceCode" -or
$clientAppTypes -contains "all" -or
$clientAppTypes -contains "mobileAppsAndDesktopClients") {
$deviceCodePolicies += [PSCustomObject]@{
Name = $policy.DisplayName
Id = $policy.Id
State = $state
ClientAppTypes = $clientAppTypes -join ", "
GrantControls = ($policy.GrantControls.BuiltInControls -join ", ")
}
}
}
if ($deviceCodePolicies.Count -eq 0) {
Write-Host " [!] WARNING: No Conditional Access policies explicitly covering device code flow found." -ForegroundColor Red
Write-Host " [!] Device code authentication bypasses all CA policies unless explicitly configured." -ForegroundColor Red
} else {
Write-Host " [*] Found $($deviceCodePolicies.Count) policies that may affect device code flow:" -ForegroundColor Green
$deviceCodePolicies | Format-Table Name, State, GrantControls -AutoSize
}
return $deviceCodePolicies
}
# Function to review recent device code authentication attempts
function Get-RecentDeviceCodeAuthEvents {
Write-Host "`n[+] Reviewing Recent Device Code Authentication Events (last 7 days)..." -ForegroundColor Cyan
$startDate = (Get-Date).AddDays(-7)
# This requires Microsoft Graph beta endpoint for signinLogs with detailed filtering
try {
$filter = "createdDateTime ge $([DateTimeOffset]::Now.AddDays(-7).ToString('o'))"
# Note: In production, use proper Graph query with detailed filtering
Write-Host " [*] Query requires Microsoft Graph Sign-in Logs audit permissions." -ForegroundColor Yellow
Write-Host " [*] Recommended: Review Sign-in logs in Entra ID portal filtering by 'Device Code' application." -ForegroundColor Yellow
Write-Host " Portal URL: https://entra.microsoft.com/#view/Microsoft_AAD_IAM/SignInsBlade" -ForegroundColor White
} catch {
Write-Warning "Could not retrieve sign-in logs. Check permissions."
}
}
# Function to check for risky OAuth app grants
function Get-RiskOAuthGrants {
Write-Host "`n[+] Checking for High-Risk OAuth Permissions Granted..." -ForegroundColor Cyan
try {
$servicePrincipals = Get-MgServicePrincipal -All
$highRiskApps = @()
foreach ($sp in $servicePrincipals) {
$appRoles = $sp.AppRoles
$oauth2Permissions = $sp.OAuth2PermissionScopes
# Check for high-risk permissions
$riskyRoles = $appRoles | Where-Object { $_.Value -match "ReadWrite\.All|FullControl|RoleManagement|Directory" }
$riskyScopes = $oauth2Permissions | Where-Object { $_.Value -match "ReadWrite\.All|FullControl|RoleManagement|Directory" }
if ($riskyRoles -or $riskyScopes) {
# Get consent grants
$grants = Get-MgOauth2PermissionGrant -Filter "clientId eq '$($sp.Id)'" -All -ErrorAction SilentlyContinue
if ($grants) {
$highRiskApps += [PSCustomObject]@{
AppName = $sp.DisplayName
AppId = $sp.AppId
RiskyPermissions = "$(($riskyRoles.Value -join ', ')) $(($riskyScopes.Value -join ', '))"
ConsentType = ($grants.ConsentType -join ', ')
PrincipalId = ($grants.PrincipalId -join ', ')
}
}
}
}
if ($highRiskApps.Count -gt 0) {
Write-Host " [!] Found $($highRiskApps.Count) applications with high-risk permissions granted:" -ForegroundColor Yellow
$highRiskApps | Format-Table AppName, RiskyPermissions, ConsentType -AutoSize
} else {
Write-Host " [*] No high-risk OAuth grants detected." -ForegroundColor Green
}
return $highRiskApps
} catch {
Write-Warning "Could not audit OAuth grants: $_"
}
}
# Function to disable device code flow (if supported in tenant)
function Disable-DeviceCodeFlow {
Write-Host "`n[+] Device Code Flow Restriction Options:" -ForegroundColor Cyan
Write-Host " Option 1: Disable via Conditional Access (Recommended)" -ForegroundColor White
Write-Host " Option 2: Configure Authentication Methods Policy (Preview)" -ForegroundColor White
Write-Host " Option 3: Block device code via Client App Type restrictions" -ForegroundColor White
Write-Host "`n NOTE: Device code flow cannot be completely disabled in all tenants." -ForegroundColor Yellow
Write-Host " The most effective control is Conditional Access policy blocking it." -ForegroundColor Yellow
}
# Main execution
Write-Host "="*60
Write-Host "Microsoft 365 Device Code Flow Security Assessment" -ForegroundColor Magenta
Write-Host "Date: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Gray
Write-Host "="*60
# Run assessments
$policy = Get-DeviceCodeFlowPolicy
$caPolicies = Test-DeviceCodeConditionalAccess
Get-RecentDeviceCodeAuthEvents
$riskyApps = Get-RiskOAuthGrants
Disable-DeviceCodeFlow
Write-Host "`n"*60
Write-Host "Assessment Complete." -ForegroundColor Green
Write-Host "Next Steps:" -ForegroundColor Cyan
Write-Host " 1. Review and create Conditional Access policies to block device code flow for sensitive users." -ForegroundColor White
Write-Host " 2. Implement stricter OAuth app consent workflows." -ForegroundColor White
Write-Host " 3. Enable continuous access evaluation (CAE) where possible." -ForegroundColor White
Write-Host " 4. Educate users about device code phishing techniques." -ForegroundColor White
Write-Host "="*60
Remediation
Defending against the DEBULL campaign requires a layered defense strategy, as there is no single patch to apply. The following remediation steps should be implemented immediately:
1. Implement Conditional Access Controls
Create or modify Conditional Access policies to block or require additional verification for device code flow authentication:
- Navigate to Microsoft Entra admin center > Protection > Conditional Access
- Create a new policy targeting:
- Users/Groups: All users (or begin with high-privilege accounts)
- Cloud apps: All Microsoft 365 services or specific sensitive apps
- Conditions > Client app types: Select "Other clients" and specifically exclude "Device code" or block it entirely
- Configure Grant controls:
- "Require multi-factor authentication" (if not already enforced)
- "Require device to be marked as compliant" or "Hybrid Azure AD joined"
- Set policy to Report-only mode first to validate, then enable after 24-48 hours of monitoring
Note: The client app type filter for device code authentication may not be exposed in all tenants. In such cases, create policies based on:
- Sign-in risk levels
- Impossible travel conditions
- Location-based restrictions
2. Configure Authentication Method Policy
Where available, disable or restrict device code flow via authentication method policy:
- Navigate to Microsoft Entra admin center > Authentication methods > Authentication methods policy
- Review Device code flow settings
- If available, disable for all users or specific groups
- Note: This capability may not be available in all license tiers
3. Strengthen OAuth Application Governance
Implement stricter controls over application consents:
- Navigate to Microsoft Entra admin center > Enterprise applications > Consent and permissions
- Set User consent for applications to "Do not allow user consent"
- Configure Admin consent workflow to require approval for new applications
- Review existing OAuth grants and revoke unnecessary permissions
- Implement app governance policies to alert on suspicious permission grants
4. Enable Continuous Access Evaluation (CAE)
Reduce the window of opportunity for token abuse:
- CAE enables revocation of access tokens in near real-time
- Configure session lifetimes to appropriate limits
- Ensure "Refresh token max inactive time" is configured (default: 90 days, recommended: 14-30 days for sensitive accounts)
5. Deploy User Awareness Training
Educate users about this specific attack technique:
- Red flag indicators:
- Unexpected instructions to visit
microsoft.com/devicelogin - Unexpected requests to enter a "device code" or "user code"
- Collaboration-themed lures prompting unusual authentication steps
- Unexpected instructions to visit
- Safe practices:
- Never enter codes received from unexpected sources
- Verify collaboration requests through secondary channels
- Report suspicious authentication requests to security team
6. Implement Detection Rules
Deploy the SIGMA rules and KQL queries provided in the Detection & Response section above to:
- Monitor for device code authentication events
- Detect impossible travel patterns
- Alert on high-risk OAuth consent grants
7. Review and Investigate Compromised Accounts
For the period of active threat (June 24 - July 10, 2026):
- Export sign-in logs filtering for "Device Code" application
- Cross-reference with suspicious email activity during the same period
- Investigate any accounts showing device code authentication from unusual locations
- Force password reset and revoke all sessions for potentially compromised accounts
- Conduct forensic review of mailbox activity for compromised accounts
8. Microsoft Official Resources
- Microsoft Entra Device Code Flow Documentation: https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-device-code
- Conditional Access Planning Guide: https://learn.microsoft.com/en-us/entra/identity/conditional-access/how-to-conditional-access-plan
- Managing OAuth Consent: https://learn.microsoft.com/en-us/entra/identity-platform/howto-restrict-user-consent
Timeline for Implementation
| Priority | Action | Timeframe |
|---|---|---|
| Critical | Deploy detection rules (SIGMA/KQL) | Immediate (within 24 hours) |
| High | Configure Conditional Access for device code blocking | 48-72 hours (report-only first) |
| High | Review recent authentication logs for compromise | 72 hours |
| Medium | Implement OAuth consent governance | 1 week |
| Medium | Deploy user awareness training | 1-2 weeks |
Related Resources
Security Arsenal Managed SOC Services AlertMonitor Platform Book a SOC Assessment soc-mdr Intel Hub
Is your security operations ready?
Get a free SOC assessment or see how AlertMonitor cuts through alert noise with automated triage.