Every Session Started the Same Way
Part 2 followed the attacker's sessions through Entra ID and into the mailbox. Every one of those sessions had the same origin: a device code sign-in. That's the front door, and this post is about how it opened.
It's worth understanding properly, because device code phishing gets past exactly the people who are careful. There's no fake domain. The certificate is valid. The sign-in page is Microsoft's, and the MFA is real. The only thing wrong is which device ends up holding the tokens.
If you're new to the series, the post-mortem, The Email Really Was From Me, has the full timeline.
About the Code in This Post
Most of the code here is read-only. One part changes your tenant: the Conditional Access policy. Run all of it from a privileged access workstation (PAW), in PowerShell 7, with the Microsoft Graph PowerShell SDK.
| Step | What it does | Needs |
|---|---|---|
| Hunt for the broker pattern | Reads sign-in logs | AuditLog.Read.All |
| Inventory device code use | Reads sign-in logs | AuditLog.Read.All |
| Create and test the block | Creates a policy (report-only), then What If | Conditional Access Administrator |
| Enforce and prove it | Turns the policy on, then reads one test sign-in | Conditional Access Administrator |
How Device Code Flow Works
Device code flow (OAuth 2.0 device authorization grant, RFC 8628) exists for things that can't show you a proper sign-in page: a conference-room display, a TV, a command-line tool on a server. It works in four steps:
- The device asks Entra ID for a code. It gets back a short user code and a secret device code.
- The device shows you the user code and tells you to go to
microsoft.com/devicelogin. - You sign in on that page, on your phone or laptop, and enter the code.
- Meanwhile, the device polls Entra ID with its secret device code. Once you've finished, the poll returns access and refresh tokens. To the device, not to you.
Step 4 is the whole problem. The person who signs in and the device that receives the tokens are deliberately separate, and nothing in the flow checks that they belong to the same person. In device code phishing, the attacker runs steps 1 and 4 from their own machine and gets the victim to do step 3. The lure is usually something that makes a code look normal: a meeting invite, a document to unlock, an RFP portal.
From the victim's side, everything checks out. Real domain, real padlock, real company sign-in. The question that protects you isn't "is this page real?" It's "did I start this sign-in?"
Why MFA Didn't Save Me
The obvious question is how this got past MFA. It didn't get past it. MFA worked; the tokens went to the wrong device.
Every successful device code sign-in in my logs carried the same authentication detail: "MFA requirement satisfied by claim in the token." Nobody answered a fresh MFA prompt. A previous, legitimate MFA result was already in the token used to sign in, and Entra ID accepted it.
The first device code sign-ins also showed an incoming token type of primary refresh token, from an Entra-joined Windows device running Edge. That means the approval happened in a browser that was already signed in. On a managed Windows machine, that's normal single sign-on. It also means the approval can be close to effortless: no password, no MFA prompt, just an account picker and a page asking whether you're trying to sign in to an app, with a Continue button.
That's worth sitting with. The better your single sign-on is, the less friction a device code approval has. Every later use of the attacker's session then inherited that MFA result. Part 2 showed the consequence: Conditional Access status success and sign-in risk none on all 22 device-code-derived sign-ins.
This is also why phishing-resistant MFA doesn't stop device code phishing. A FIDO2 key or Windows Hello binds your sign-in to the real Microsoft domain, and the device code page is the real Microsoft domain. Phishing-resistant MFA is still the right call for everything else. It just doesn't answer this attack. Blocking the flow does.
From One Code to Five Laptops
The detail that explained the rogue devices from Part 2 was the client application on those first sign-ins. It wasn't Teams or Outlook. It was Microsoft Authentication Broker (client ID 29d9ed98-a469-4536-ade2-f981bc1d605e), signing in to Microsoft Intune Enrollment. A new Windows device was registered to my account 59 seconds later.
That pairing is a known technique. In February 2025, Microsoft reported that the actor it tracks as Storm-2372 had switched its device code phishing to the Microsoft Authentication Broker client ID. The reason is what that client ID unlocks. The refresh token it returns can be exchanged for a token to the Device Registration Service, which lets the attacker register a device of their own in Entra ID. With that refresh token and the new device identity, they can then request a primary refresh token, the token Windows uses for single sign-on to everything.
That's exactly the sequence in my logs:
| Time (UTC, July 22) | What happened |
|---|---|
| 20:38 | Device code sign-in: Microsoft Authentication Broker → Intune Enrollment |
| 20:39 | First DESKTOP- device registered to my account, Entra joined |
| 20:41 | Second DESKTOP- device registered |
| 20:41 | Teams sign-in from that second device, 23 seconds after it registered, using a primary refresh token |
| 20:42 | Outlook on the web from the same device |
Under four minutes from code to mailbox. And because the attacker now had a device identity with a primary refresh token, they no longer depended on the original device code session. That's what a device registration buys an attacker, and it's why five device objects were the most important thing to find in Part 2. I'm not attributing this incident to Storm-2372; the technique has spread well beyond one actor.
Hunt for the pattern in your own tenant. This finds broker sign-ins that came from device code flow:
Connect-MgGraph -Scopes 'AuditLog.Read.All'
$broker = '29d9ed98-a469-4536-ade2-f981bc1d605e'
$since = (Get-Date).ToUniversalTime().AddDays(-30).ToString('s') + 'Z'
$types = "signInEventTypes/any(t: t eq 'interactiveUser' or " +
"t eq 'nonInteractiveUser')"
$filter = "createdDateTime ge $since and appId eq '$broker' and $types"
$uri = 'https://graph.microsoft.com/beta/auditLogs/signIns?$filter=' +
[uri]::EscapeDataString($filter)
$hits = @(while ($uri) {
$page = Invoke-MgGraphRequest -Uri $uri -OutputType PSObject
$page.value | Where-Object originalTransferMethod -eq 'deviceCodeFlow'
$uri = $page.'@odata.nextLink'
})
$hits | Select-Object createdDateTime, userPrincipalName,
resourceDisplayName, @{ n = 'Error'; e = { $_.status.errorCode } }
Any successful row deserves an explanation. Legitimate Windows setup uses the broker constantly, but it doesn't use device code flow to do it. A successful broker sign-in with device code ancestry, followed by a new device registration for the same user, is the pattern in this post.
The Flag That Outlives the First Sign-In
Part 2 noted that 22 sign-ins had device-code ancestry but only 7 showed deviceCode as their authentication protocol. Here's why.
Entra ID marks any session that started with device code flow and keeps that mark through every later token refresh. Microsoft calls this protocol tracking. In the sign-in log, the mark shows up as Original transfer method, set to deviceCodeFlow for any session that began with a device code, however many refreshes ago that was.
So a Teams token refresh three days later shows none as its protocol and deviceCodeFlow as its original transfer method. Search on the protocol and you see the door. Search on the original transfer method and you see everyone who came through it.
Protocol tracking matters for blocking, too. A block policy doesn't just stop new device code sign-ins; it also refuses refreshes from sessions that started with one. Those refusals show up as AADSTS530036, which Microsoft documents as a refresh token rejected by Conditional Access authentication flow checks.
That adds a nuance to what the post-mortem said about the October replay attempt. Of the 278 token requests the attacker sent, 14 still carried device-code ancestry, so an enforced block would have refused those as well. The other 264 didn't carry it. The block is a second line for tokens that were born from a device code. Revocation is the line for everything else, and in October, revocation is what refused all 278.
Blocking It: Inventory, Report-Only, What If, Enforce, Prove
Microsoft's guidance is blunt: it calls device code flow high risk and recommends blocking it wherever possible. Here's how we did it, in the order that keeps you from locking out something you need.
1. Inventory who uses it
Before you block anything, find out what depends on it. This groups 30 days of device-code-derived sign-ins by user and app:
$types = "signInEventTypes/any(t: t eq 'interactiveUser' or " +
"t eq 'nonInteractiveUser')"
$filter = "createdDateTime ge $since and $types"
$uri = 'https://graph.microsoft.com/beta/auditLogs/signIns?$filter=' +
[uri]::EscapeDataString($filter)
$dcf = @(while ($uri) {
$page = Invoke-MgGraphRequest -Uri $uri -OutputType PSObject
$page.value | Where-Object {
$_.originalTransferMethod -eq 'deviceCodeFlow' -or
$_.authenticationProtocol -eq 'deviceCode'
}
$uri = $page.'@odata.nextLink'
})
$dcf | Group-Object userPrincipalName, appDisplayName -NoElement |
Sort-Object Count -Descending | Format-Table Count, Name
In a large tenant, run it a week at a time. Expect three kinds of hits: Teams Rooms and Teams phones, command-line tools, and anything you can't explain. Ours turned up a surprise in the second group: me. My own Microsoft Graph PowerShell sessions had been signing in with device code. The fix was to stop using -UseDeviceCode and sign in interactively, from a PAW. Every exception you remove is one less thing an attacker can hide behind.
2. Create the policy in report-only mode
The policy targets all users and all resources, excludes one group, and blocks the device code flow. Put your two emergency-access accounts and any approved, documented exceptions in that group. Run it from a PAW, as a Conditional Access Administrator:
Connect-MgGraph -Scopes 'Policy.Read.All', 'Policy.ReadWrite.ConditionalAccess'
$exceptions = '<object ID of the device code exception group>'
$policy = @{
displayName = 'CA-BLOCK-Device-Code-Flow-All-Users'
state = 'enabledForReportingButNotEnforced'
conditions = @{
users = @{ includeUsers = @('All')
excludeGroups = @($exceptions) }
applications = @{ includeApplications = @('All') }
clientAppTypes = @('all')
authenticationFlows = @{ transferMethods = 'deviceCodeFlow' }
}
grantControls = @{ operator = 'OR'; builtInControls = @('block') }
}
$uri = 'https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies'
$created = Invoke-MgGraphRequest -Method POST -Uri $uri `
-Body ($policy | ConvertTo-Json -Depth 6) -OutputType PSObject
$created.id
enabledForReportingButNotEnforced is report-only: the policy logs what it would have blocked and blocks nothing. Leave it there for a week or two and check the report-only results in the sign-in logs for anything your inventory missed.
⚠ The Device Registration Service exclusion: Microsoft's Teams device guidance says to exclude the Device Registration Service from a policy like this, because Teams devices register through device code flow. Only add that exclusion if you have Teams devices that need it. Device registration is exactly what the attacker in this post used device code flow for.
That warning has a date attached. Since early September 2024, Microsoft has enforced authentication flows policies on the Device Registration Service, but only for policies that target all resources. A policy that targets all resources, with no exclusion, covers device registration. Ours does, on purpose.
3. Ask What If before you flip it
Conditional Access What If evaluates a hypothetical sign-in against your policies, report-only ones included. Describe a device code sign-in by a test user to Exchange Online and see what would apply:
$testUser = Get-MgUser -UserId 'ca*****@*****************re.com'
$exo = '00000002-0000-0ff1-ce00-000000000000' # Office 365 Exchange Online
$whatIf = @{
signInIdentity = @{ '@odata.type' = '#microsoft.graph.userSignIn'
userId = $testUser.Id }
signInContext = @{ '@odata.type' = '#microsoft.graph.applicationContext'
includeApplications = @($exo) }
signInConditions = @{ devicePlatform = 'windows'
clientAppType = 'mobileAppsAndDesktopClients'
authenticationFlow = @{
transferMethod = 'deviceCodeFlow' } }
appliedPoliciesOnly = $true
}
$uri = 'https://graph.microsoft.com/v1.0/identity/conditionalAccess/evaluate'
(Invoke-MgGraphRequest -Method POST -Uri $uri -OutputType PSObject `
-Body ($whatIf | ConvertTo-Json -Depth 6)).value |
Select-Object displayName, state, policyApplies,
@{ n = 'Grant'; e = { $_.grantControls.builtInControls -join ', ' } }
You're looking for your block policy with policyApplies true and a grant of block. Run it again for one emergency-access account: the block policy must not apply. That's the negative test, and it's the one that keeps you from locking yourself out.
4. Enforce it
Once report-only shows only what you expected:
$uri = 'https://graph.microsoft.com/v1.0/identity/conditionalAccess/' +
"policies/$($created.id)"
Invoke-MgGraphRequest -Method PATCH -Uri $uri `
-Body (@{ state = 'enabled' } | ConvertTo-Json)
5. Prove it with a sign-in that fails
Policy JSON proves the configuration. What If proves the expected evaluation. Only a blocked sign-in proves enforcement. Use a dedicated test account that isn't excluded and isn't an administrator, and start a device code sign-in you control yourself. If the Azure CLI is installed:
az login --use-device-code --tenant '<your tenant ID>'
Enter the code as the test user. It should stop with AADSTS53003, access blocked by Conditional Access. Then confirm the policy did it. Give the sign-in a few minutes to reach the log:
$since = (Get-Date).ToUniversalTime().AddHours(-1).ToString('s') + 'Z'
$filter = "userId eq '$($testUser.Id)' and createdDateTime ge $since"
$uri = 'https://graph.microsoft.com/beta/auditLogs/signIns?$filter=' +
[uri]::EscapeDataString($filter)
(Invoke-MgGraphRequest -Uri $uri -OutputType PSObject).value |
Where-Object authenticationProtocol -eq 'deviceCode' |
Select-Object createdDateTime, conditionalAccessStatus,
@{ n = 'Error'; e = { $_.status.errorCode } },
@{ n = 'Policy'; e = {
($_.appliedConditionalAccessPolicies |
Where-Object result -eq 'failure').displayName -join ', ' } }
The proof is one row: error 53003, Conditional Access status failure, and your block policy's name in the last column. Save that output with the date. It's the evidence that the control exists, and it's worth more than any screenshot of the policy.
Never test with a code someone sent you. Start the flow yourself, every time.
Gotcha: Report-Only Is a Measurement, Not a Control
We created our block on August 10, in report-only, exactly as above. Then it stayed report-only longer than it should have. The incident was contained, the urgent work was done, and a policy that's "in place" looks finished in the portal list.
It isn't. A report-only policy blocks nothing. It took a later review to catch it, and even then, a portal glance showing the policy as On wasn't proof. The proof was step 5: a test sign-in, blocked, with the policy named in the log. If your block has been "in place" for a while, run the check from the post-mortem's audit and the test above. It takes five minutes.
What the Block Doesn't Do
Blocking device code flow closes this door. It doesn't close every door, and it's worth being precise about the gaps:
- It doesn't revoke tokens an attacker already holds. Protocol tracking catches refreshes from device-code-born sessions, but not tokens from other sources, and not a primary refresh token on a device the attacker already registered. That's what revocation and disabling devices are for, which is Part 4.
- It doesn't stop other phishing. Adversary-in-the-middle phishing and consent phishing are different flows, with different controls.
- Exceptions are attack surface. Every account in the exception group can still be phished this way. Keep the group small, review it, and alert on its sign-ins.
What This Stage Proved
| Question | How we answered it | Result |
|---|---|---|
| How did the attacker get tokens? | Device code sign-ins, client app, and resource | Device code flow, Microsoft Authentication Broker → Intune Enrollment |
| Why no MFA prompt? | Authentication details and incoming token type | MFA satisfied by claim; approval from an already signed-in browser |
| Where did the rogue devices come from? | Sign-in and registration timing | Broker token used to register devices and get primary refresh tokens |
| Why did later sign-ins look different? | originalTransferMethod vs. protocol | Protocol tracking: 22 with ancestry, 7 with the protocol |
| Is the flow blocked now? | Report-only, What If, enforcement, test sign-in | Yes, proved with a blocked test sign-in |
Next: Containment Is More Than a Password Reset
Knowing how the attacker got in tells you what has to come out: the password, yes, but also the refresh tokens, the five devices and their primary refresh tokens, the inbox rules, and the people who got the email. Part 4 covers containment in the right order, and why we disabled the devices instead of deleting them.
Have you inventoried device code use in your tenant, or found something you couldn't explain? Leave a comment below, or get in touch.