Block Device-Code Phishing & Audit Rogue PRTs in Microsoft Entra ID (PowerShell & Conditional Access Runbook)

🛡️ Security Runbook Brief — Stopping Entra ID Device-Code Phishing (Dec 2026)
  • Active Threat (Dec 2026): Attackers are abusing legitimate Microsoft Entra ID OAuth 2.0 Device Authorization Grant (deviceCodeTransfer) flows to trick users into entering a 9-character code on microsoft.com/devicelogin, registering rogue devices and harvesting Primary Refresh Tokens (PRTs).
  • Immediate Defense: Create a Conditional Access policy targeting Authentication Flows → Device code flow and set Grant to Block access (excluding only scoped kiosk/IoT service groups).
  • Forensic Audit: Query Microsoft Graph /v1.0/devices and /v1.0/auditLogs/signIns to detect unrecognized registered devices, unusual Linux/Python user-agents, and anomalous PRT issuance.

In early December 2026, security advisories flagged widespread enterprise campaigns abusing Microsoft Entra ID's OAuth 2.0 device-code authentication flow (https://login.microsoftonline.com/common/oauth2/deviceauth) to bypass MFA prompts, register attacker-controlled devices, and access Exchange Online and SharePoint Online via stolen Primary Refresh Tokens (PRTs).

Because device-code authentication happens on a separate browser session initiated by the victim on their own trusted workstation, traditional network location checks or phishing-resistant MFA prompts on the victim's browser will not stop the attacker's remote CLI or script from receiving the resulting access and refresh tokens—unless you explicitly block the flow in Conditional Access.


Architecture: How Device-Code Phishing Works & Where Conditional Access Blocks It

1. Attacker Requests Code POST /devicecode Client: Edge / PowerShell / Microsoft Auth Broker Receives 9-Char User Code 2. Victim Enters Code microsoft.com/devicelogin Completes MFA on Own PC Approves Remote Session Without CA: Attacker Gets PRT 3. Conditional Access Defense (Zero Trust) Condition: Authentication Flows → Device code flow Grant: Block Access (Tenant-Wide Default) + Restrict Device Registration (Require MFA + Max Devices) Result: Token Exchange Fails Immediately Companion Guardrail: Block Non-Compliant Device Registrations & Audit Existing Devices Review Entra ID > Devices > Device settings and run the Graph PowerShell audit below for newly registered WorkplaceJoined devices.

Step 1: Audit Registered Devices via Microsoft Graph PowerShell

Attackers using device-code phishing against Microsoft Auth Broker or Intune Company Portal often register a rogue Microsoft Entra registered (Workplace) device so they can mint a PRT and satisfy weak "Require hybrid/registered device" checks.

Run this live-tested Microsoft Graph script (using unattended Certificate-Based Authentication) to list recently registered devices—flagging unknown Linux, macOS, or anomalous Windows registrations:

POWERSHELL
#Requires -Version 7.0
# Connect with Directory.Read.All or Device.Read.All
Connect-MgGraph `
    -ClientId "<AppId>" `
    -TenantId "<TenantId>" `
    -CertificateThumbprint "<Thumbprint>" `
    -NoWelcome

$LookbackDate = (Get-Date).AddDays(-14).ToString("yyyy-MM-ddTHH:mm:ssZ")

# Query devices registered or active in the last 14 days
$Devices = Invoke-MgGraphRequest -Method GET `
    -Uri "https://graph.microsoft.com/v1.0/devices?`$select=id,displayName,operatingSystem,operatingSystemVersion,trustType,createdDateTime,approximateLastSignInDateTime,isCompliant,isManaged&`$top=200"

$RecentDevices = $Devices.value | Where-Object {
    $_.createdDateTime -ge $LookbackDate
} | Sort-Object createdDateTime -Descending

$RecentDevices | Select-Object displayName, operatingSystem, trustType, isManaged, isCompliant, createdDateTime |
    Format-Table -AutoSize
What to investigate immediately: Any trustType = Workplace device with isManaged = False registered to an executive, IT admin, or remote user who did not intentionally enroll a new personal device.

Step 2: Hunt Device-Code Sign-Ins in Entra ID Audit Logs (Entra ID P1/P2)

If your tenant has Entra ID P1 or P2 and AuditLog.Read.All consented, query signIns specifically for authenticationProtocol eq 'deviceCode' (note: tenants without P1/P2 licensing will return 400 Bad Request on /auditLogs/signIns):

POWERSHELL
$StartUtc = (Get-Date).AddDays(-7).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")

$Uri = "https://graph.microsoft.com/v1.0/auditLogs/signIns?" +
       "`$filter=createdDateTime ge $StartUtc and authenticationProtocol eq 'deviceCode'&" +
       "`$select=createdDateTime,userPrincipalName,appDisplayName,ipAddress,clientAppUsed,status,location"

$DeviceCodeSignIns = (Invoke-MgGraphRequest -Method GET -Uri $Uri).value

if ($DeviceCodeSignIns.Count -eq 0) {
    Write-Host "[+] No deviceCode sign-ins detected in the last 7 days." -ForegroundColor Green
} else {
    $DeviceCodeSignIns | Select-Object createdDateTime, userPrincipalName, appDisplayName, ipAddress,
        @{N='Country';E={$_.location.countryOrRegion}},
        @{N='ErrorCode';E={$_.status.errorCode}} |
        Format-Table -AutoSize
}

Step 3: Block Device-Code Flow via Conditional Access (Graph API / Portal)

In the Microsoft Entra Admin Center:

  1. Navigate to Protection → Conditional Access → Policies → New policy.
  2. Name: CA-Block-Device-Code-Authentication-Flow
  3. Users: All users (exclude your Break-Glass Emergency Access accounts).
  4. Target resources: All resources (formerly 'All cloud apps').
  5. Conditions → Authentication Flows: Set Configure = Yes and select Device code flow (deviceCodeTransfer).
  6. Access controls → Grant: Block access.
  7. Enable in Report-only for 48 hours to verify zero legitimate IoT/conference-room devices rely on it, then switch to On.

To deploy or verify this policy via Microsoft Graph PowerShell (Policy.ReadWrite.ConditionalAccess):

POWERSHELL
$PolicyBody = @{
    displayName = "CA-Block-Device-Code-Authentication-Flow"
    state       = "enabledForReportingButNotEnforced" # Switch to "enabled" after 48h verification
    conditions  = @{
        users = @{
            includeUsers = @("All")
            excludeUsers = @("<BreakGlassUserObjectId-1>", "<BreakGlassUserObjectId-2>")
        }
        applications = @{
            includeApplications = @("All")
        }
        authenticationFlows = @{
            transferMethods = "deviceCodeFlow"
        }
    }
    grantControls = @{
        operator        = "OR"
        builtInControls = @("block")
    }
} | ConvertTo-Json -Depth 6

Invoke-MgGraphRequest -Method POST `
    -Uri "https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies" `
    -Body $PolicyBody `
    -ContentType "application/json"

Step 4: Harden Device Registration & Revoke Compromised Sessions

If you confirm a user fell victim to a device-code phish:

  1. Revoke Refresh Tokens immediately: Revoke-MgUserSignInSession -UserId "<UserObjectId>"
  2. Delete the rogue device object from Entra ID (Remove-MgDevice -DeviceId "<DeviceObjectId>").
  3. Require MFA to register or join devices: In Entra Admin Center → Devices → Device settings, set Require Multifactor Authentication to register or join devices with Microsoft Entra to Yes and cap Maximum number of devices per user (e.g., 5).

For deeper Conditional Access & phishing-resistant MFA hardening, see Book Series 2 Ch 3: Zero Trust Conditional Access, Passkeys & PIM and Entra ID Conditional Access Policy Plans.


References & Official Microsoft Documentation

đź’¬ Reader Comments & Feedback

Did this runbook help, or did Microsoft change a cmdlet or UI menu? Share your feedback below.