THREAT-BEC-OAuthDeviceCode Google Chronicle · YARA-L

Detect Business Email Compromise via OAuth Device Code Flow Phishing in Google Chronicle

OAuth Device Code Flow phishing is a prevalent Business Email Compromise (BEC) technique actively used by Scattered Spider, Storm-2372, and nation-state actors including Midnight Blizzard. The attacker sends a phishing message containing a Microsoft device code (a short alphanumeric code from https://microsoft.com/devicelogin), social-engineered to appear as an IT helpdesk request, MFA enrollment notification, or remote support session. When the victim enters the code, the attacker receives a valid OAuth access token and refresh token for the victim's Microsoft 365 account — with no password required. The attacker then has full access to email, Teams, SharePoint, OneDrive, and any M365 service the victim is licensed for. Refresh tokens may persist for 90 days, providing long-term access even after password reset. This technique bypasses MFA entirely because the device code flow is a legitimate Microsoft authentication mechanism.

MITRE ATT&CK

Tactic
Credential Access Collection

YARA-L Detection Query

Google Chronicle (YARA-L)
yaral
rule bec_oauth_device_code_phishing {
  meta:
    author = "df00tech"
    description = "Detects OAuth Device Code Flow BEC phishing in Microsoft 365: device code authentication from suspicious clients or anomalous locations, and post-compromise inbox forwarding rule creation. Threat actors: Scattered Spider, Storm-2372, Midnight Blizzard."
    severity = "CRITICAL"
    priority = "HIGH"
    reference = "https://attack.mitre.org/techniques/T1078/004/"
    mitre_attack_tactic = "Initial Access, Persistence"
    mitre_attack_technique = "T1078.004, T1114.003"

  events:
    // Event 1: Device code flow sign-in with suspicious user agent or anomalous location
    (
      $e1.metadata.event_type = "USER_LOGIN"
      AND (
        re.regex($e1.network.http.user_agent, `(?i)(python-requests|curl|wget|Go-http-client|okhttp|axios)`)
        OR (
          $e1.extensions.auth.auth_details = "deviceCode"
          AND NOT re.regex($e1.principal.location.country_or_region, `(?i)^(United Kingdom|United States)$`)
        )
      )
      AND $e1.extensions.auth.auth_details = "deviceCode"
      AND $e1.target.application = /(?i)(Microsoft|Office|Teams|SharePoint|OneDrive|Exchange)/
      AND $user = $e1.principal.user.userid
    )
    OR
    // Event 2: Inbox forwarding or deletion rule created (post-BEC follow-on)
    (
      $e2.metadata.event_type = "EMAIL_TRANSACTION"
      AND re.regex($e2.metadata.description, `(?i)(New-InboxRule|Set-InboxRule|Set-Mailbox)`)
      AND re.regex($e2.about.labels["Parameters"], `(?i)(ForwardTo|DeleteMessage|RedirectTo|ForwardAsAttachmentTo|MoveToFolder)`)
      AND NOT re.regex($e2.about.labels["Parameters"], `(?i)Junk Email`)
      AND $user = $e2.principal.user.userid
    )

  match:
    $user over 4h

  condition:
    $e1 and $e2
}
critical severity high confidence

YARA-L 2.0 rule for Google Chronicle that correlates OAuth device code flow authentication events (with suspicious automation user agents or logins from unexpected countries) with subsequent inbox rule creation containing forwarding or deletion parameters. The 4-hour match window captures the typical BEC post-compromise sequence used by Scattered Spider, Storm-2372, and Midnight Blizzard.

Data Sources

Microsoft 365 Management Activity Logs via Chronicle ingestionAzure AD Sign-In Logs via Chronicle UDM

Required Tables

UDM events with metadata.event_type USER_LOGIN and EMAIL_TRANSACTION from M365/Azure AD log sources

False Positives & Tuning

  • IT automation scripts performing legitimate device code authentication for service account provisioning
  • Users on VPN or traveling who appear to sign in from unexpected countries via device code
  • Administrators creating inbox rules programmatically as part of email migration or onboarding workflows
  • Security tools or email hygiene platforms that create inbox rules on behalf of users

Other platforms for THREAT-BEC-OAuthDeviceCode


Testing Methodology

Validate this detection against 2 adversary techniques from Atomic Red Team. Each test below lists the behaviour to exercise and the telemetry you should expect to see. Executable commands and cleanup steps are available with Pro.

  1. Test 1OAuth Device Code Flow Token Request (Simulated Phishing)

    Expected signal: Azure AD Sign-in logs record a DeviceCode flow initiation. When user enters the code, AADSignInLogs records a successful authentication with AuthenticationProtocol=deviceCode.

  2. Test 2Create BEC Inbox Forwarding Rule via Exchange Online PowerShell

    Expected signal: O365 Unified Audit Log records New-InboxRule operation with ForwardTo parameter for the authenticated user.


Response Playbook

Triage

  1. Confirm whether the device code sign-in was legitimate by contacting the affected user directly (NOT via email or Teams if account may be compromised). Ask if they recently used a code at microsoft.com/devicelogin.
  2. Check the sign-in location and IP address against the user's typical locations (Azure AD Sign-in logs, last 30 days). A sign-in from a country the user has never visited is high confidence.
  3. Review the OAuth token issued: which application (AppId) received the token? Legitimate apps include Microsoft Office, Outlook, Teams. Suspicious: generic app IDs, unknown application names, or 'first seen' apps.
  4. Check for inbox rules created within 24 hours of the device code sign-in. Look specifically for: ForwardTo (exfiltration), DeleteMessage (hiding attacker activity), MoveToFolder where the target folder is not Junk.
  5. Review email access (MailItemsAccessed, MessageRead operations in O365 audit) following the device code sign-in for signs of mail reading or forwarding.
  6. Determine if the user received a phishing email before the device code sign-in: search incoming mail for messages containing 'microsoft.com/devicelogin' or 8-character alphanumeric codes sent from external senders.

Containment

  1. Revoke all refresh tokens for the affected user immediately: Azure AD > Users > [User] > Revoke sessions (or via PowerShell: Revoke-AzureADUserAllRefreshToken -ObjectId <userID>).
  2. Delete or disable any suspicious inbox rules identified during triage.
  3. Block the attacker IP address(es) in Conditional Access or Named Locations policy.
  4. Reset the user's password and require re-enrollment of MFA devices.
  5. Enable Conditional Access policy to block Device Code flow for all users where possible (CA policy: Grant > Require compliant device, block legacy authentication).
  6. Review and revoke any OAuth application consents granted during the attacker's session (Azure AD > Enterprise Applications > review third-party apps with delegated permissions).

Evidence Collection

  1. Azure AD Sign-in logs: device code events, token issuances, subsequent application activity
  2. O365 Unified Audit Log: MailItemsAccessed, MessageRead, SendAs, SendOnBehalf operations in the incident window
  3. O365 inbox rules export: all rules for the affected user
  4. Outbound email logs: emails sent by or forwarded from the compromised account
  5. Conditional Access evaluation logs for the device code sign-in event
  6. The phishing email itself (if recoverable) for threat actor infrastructure IOCs

Escalation Criteria

  • !Evidence of financial transactions initiated from compromised email (wire transfer requests, invoice changes)
  • !Email access to finance team, HR, or executive mailboxes from compromised account (lateral BEC targeting)
  • !OAuth consent grant to third-party application with mail.read, files.read, or contacts.read permissions
  • !Evidence of email exfiltration (MailItemsAccessed showing bulk message access from attacker IP)
  • !Compromised account used to send internal phishing emails to other employees

Investigation Guide

Related Techniques

Forensic Artifacts

  • >Azure AD Sign-In logs: AppId, IPAddress, UserAgent, AuthenticationDetails fields for device code events
  • >O365 Unified Audit Log: all operations by the user in the 24 hours post-compromise
  • >O365 MailItemsAccessed events: which messages were read and by which client IP
  • >O365 message trace: all sent/forwarded messages from the compromised account
  • >Azure AD OAuth token activity: which refresh tokens were issued and when they were used
  • >Browser or email client forensics on victim device: the phishing message that contained the device code

Tuning Guidance

Device code flow is legitimately used for IoT device enrollment, smart TVs, and printer registration — these are usually one-time events. Tune by creating a baseline of users who have historically used device code authentication (e.g., IT staff enrolling conference room devices) and apply enrichment to distinguish these. The highest-fidelity signal is the sequence: device code auth + inbox rule with ForwardTo. Consider disabling device code flow entirely via Conditional Access policies for users who do not need it (most corporate users). Set up a Conditional Access policy to block the 'Azure AD Device Registration' flow or require compliant devices for this authentication method.


Hunting Queries

Hunt for users with multiple device code sign-ins across multiple locations — indicates ongoing credential theft campaign or compromised user repeatedly being targeted.

Hunting — KQL
kql
AADSignInLogs
| where TimeGenerated > ago(30d)
| where AuthenticationProtocol =~ "deviceCode"
| where Status.errorCode == 0
| summarize
    DeviceCodeLogins=count(),
    Locations=make_set(Location),
    IPs=make_set(IPAddress),
    Apps=make_set(AppDisplayName)
  by UserPrincipalName
| where DeviceCodeLogins > 3 or array_length(Locations) > 2
| sort by DeviceCodeLogins desc
Hunting — SPL
spl
index=azure sourcetype="azure:aad:signin" properties.authentication_protocol="deviceCode" properties.status.error_code=0
| stats count AS LoginCount, dc(properties.ip_address) AS UniqueIPs, values(properties.location) AS Locations
  BY properties.user_principal_name
| where LoginCount > 3 OR UniqueIPs > 2
| sort - LoginCount

Hunt for inbox forwarding rule creation within 4 hours of a device code sign-in — the high-confidence combined BEC indicator that storm-2372 and Scattered Spider are documented using.

Hunting — KQL
kql
OfficeActivity
| where TimeGenerated > ago(30d)
| where Operation in ("New-InboxRule", "Set-InboxRule")
| where Parameters has_any ("ForwardTo", "DeleteMessage", "RedirectTo", "ForwardAsAttachmentTo")
| join kind=leftouter (
    AADSignInLogs
    | where TimeGenerated > ago(30d)
    | where AuthenticationProtocol =~ "deviceCode"
    | project UserId=UserPrincipalName, DeviceCodeTime=TimeGenerated
  ) on $left.UserId == $right.UserId
| where isnotnull(DeviceCodeTime)
| extend TimeDiff=datetime_diff('minute', TimeGenerated, DeviceCodeTime)
| where TimeDiff >= 0 and TimeDiff <= 240
| project TimeGenerated, UserId, Operation, Parameters, DeviceCodeTime, TimeDiff
Hunting — SPL
spl
index=o365 sourcetype="o365:management:activity" Operation IN ("New-InboxRule", "Set-InboxRule") Parameters="*ForwardTo*"
| rename UserId AS user
| join type=inner user [
    search index=azure sourcetype="azure:aad:signin" properties.authentication_protocol="deviceCode"
    | rename properties.user_principal_name AS user
    | eval dc_time=_time
  ]
| where (_time - dc_time) >= 0 AND (_time - dc_time) <= 14400
| table _time, user, Operation, Parameters, dc_time, ClientIP

Atomic Red Team Tests

Test 1 OAuth Device Code Flow Token Request (Simulated Phishing)
linux

Simulates an OAuth device code phishing attack by initiating the device code flow against a Microsoft 365 tenant and waiting for a user to authenticate at microsoft.com/devicelogin. This tests detection of device code token acquisition in AADSignInLogs.

Command

bash
curl -s -X POST 'https://login.microsoftonline.com/<TENANT_ID>/oauth2/v2.0/devicecode' -d 'client_id=d3590ed6-52b3-4102-aeff-aad2292ab01c&scope=openid+profile+email+https://graph.microsoft.com/Mail.Read'

Expected Telemetry

Azure AD Sign-in logs record a DeviceCode flow initiation. When user enters the code, AADSignInLogs records a successful authentication with AuthenticationProtocol=deviceCode.

Expected Detection

Alert fires on device code authentication event from suspicious user agent or unexpected geographic location.

Test 2 Create BEC Inbox Forwarding Rule via Exchange Online PowerShell
windows

Simulates the post-compromise BEC inbox rule creation that attackers use to forward victim email to external addresses after OAuth token theft.

Command

powershell
Connect-ExchangeOnline; New-InboxRule -Name 'Test_Rule' -ForwardTo '[email protected]' -Enabled $true

Cleanup

powershell
Remove-InboxRule -Identity 'Test_Rule' -Force

Expected Telemetry

O365 Unified Audit Log records New-InboxRule operation with ForwardTo parameter for the authenticated user.

Expected Detection

Alert fires on New-InboxRule with ForwardTo parameter. If preceded by device code sign-in within 4 hours, high confidence BEC alert.

Related Detections