Device Code Phishing Registered a Rogue Device in Entra ID


What this means for your clients: A fake document email can get an employee to approve a code that adds a stranger's computer to the company's Microsoft account, and a password change leaves it there, so someone has to find and delete it.
An employee gets an email about an Adobe-protected NDA, types a short code on Microsoft's real sign-in page, and a minute later a Windows PC that nobody owns is registered in their company's Microsoft Entra ID. Huntress documented the campaign on December 3. The page was genuine. The code belonged to the attacker.
As of 12:18 PM MST, Friday, December 4, 2026, Huntress reports a device code phishing campaign that registered 468 attacker-controlled Windows devices across 326 identities in 305 organizations' Microsoft Entra ID tenants in November 2026.
What happened
Huntress says the lure, a fake Adobe-protected non-disclosure agreement, walks the victim through Microsoft's device code sign-in. Approving the code hands the attacker access and refresh tokens tied to the Microsoft Authentication Broker app. That is token theft through a real Microsoft page.
A Python script then redeems the tokens from a different IP as python-requests/2.32.5 and registers a new Windows device as joined to Entra ID, which receives a Primary Refresh Token. Huntress explains that a PRT survives a password reset and can satisfy Conditional Access policies that require a registered device: "A password reset alone doesn't remove the access; the device has to be deleted." The attacker then usually signed in to Azure Active Directory and Microsoft Office, often reaching OneDrive, SharePoint or Exchange.
Most device names are MH- plus 16 uppercase hex characters, such as MH-51FB898341CEA47A, and every registration Huntress found reported build 10.0.19041.928 with no hardware identifiers. That build is hardcoded in ROADtools, a public Entra ID toolkit, and belongs to Windows 10 version 2004, out of servicing since 2021. Huntress counted 46 MH- names in more than one organization. The actor appears to work weekdays.
First sign-ins came mostly through residential proxies such as DataImpulse, Oxylabs, NodeMaven, IPRoyal and Shifter, and no residential IP served more than two victims. Scripted sign-ins rotated through five datacenter IPs that together touched 361 accounts in 337 organizations, with 1,186 failed and 197 successful sign-ins. Huntress cannot tell whether their hosting customer is the actor or a reseller.
Huntress groups the activity into three operations: A, the MH- and some DESKTOP- devices (high confidence for MH-, moderate for DESKTOP-); B, a device named for the user and domain, then DESKTOP- plus six characters (high); and C, Device- plus eight hex and GraphSpy-Device, the GraphSpy default, on build 10.0.26100 (low). None is tied to a named actor.
Where Microsoft Defender was connected, it caught part of it: the 36 organizations with Defender connected to Huntress held 47 victims, and Defender raised an incident on 25, titled "User session compromised by device code phishing (attack disruption)," with the alert "Suspicious Entra device join or registration." Microsoft was not breached, Entra ID has no flaw, and there is nothing to patch.
Why this matters for your company
Most small companies reset the password, force a new sign-in and move on. That ends the session and leaves the registered device. The device is the foothold. It is trusted, it can satisfy a Conditional Access rule that asks for a registered device, and it is on nobody's asset list because nobody bought it. The attacker needs no malware on any PC.
That makes this identity threat detection and Microsoft 365 security work. Mail and file access that outlives the reset feeds business email compromise. For MSP security, the device list belongs in every account takeover response. For small business security, the test is simple: can you list every device registered in your Entra ID, and who registered it, before lunch? With so few victims per residential address, blocklists will not carry the load.
What to do today
Block the device code flow with Conditional Access wherever nobody needs it; that takes Entra ID P1 or above, and below P1, turn on Security Defaults. Limit who can register or join devices and how many each user can register, and require MFA to register one. Require managed, compliant devices, so trust comes from device compliance in Intune rather than registration alone. Review the device list on a schedule.
If you find a rogue device, start incident response: delete the device in Entra ID, revoke the user's sessions, reset credentials, review MFA methods and inbox rules, and check mail and file access since the registration time.
Indicator (defanged) | Type | Huntress context |
^MH-[0-9A-F]{16}$ | Device name pattern | Operation A rogue devices |
MH-51FB898341CEA47A | Device name | 24 organizations, 10 days |
MH-AD72DAD766A59028 | Device name | 18 organizations, 3 days |
MH-4AE06D5094ABCAD7 | Device name | 17 organizations, 7 days |
MH-F80EA97CA5FB3E90 | Device name | 14 organizations, 2 days |
10.0.19041.928 | Reported build | ROADtools default, Windows 10 version 2004 |
10.0.19045.2006, 10.0.19045.0, 10.0.26100 | Reported builds | Other builds Huntress says to hunt with no hardware identifiers |
181[.]214[.]147[.]42 | IPv4 | Scripted sign-ins, BK Customers |
92[.]62[.]251[.]249 | IPv4 | Scripted sign-ins, FREAKHOSTING LTD |
37[.]252[.]11[.]196 | IPv4 | Scripted sign-ins, Artnet Sp. z o.o. |
146[.]103[.]38[.]149 | IPv4 | Scripted sign-ins, BK Customers |
193[.]109[.]193[.]166 | IPv4 | Scripted sign-ins, Datacamp Limited, still in use at publication |
python-requests/2.32.5, python-httpx, node, node-fetch, undici, axios | User agents | Programmatic clients Huntress lists as IOCs; python-requests/2.32.5 on scripted sign-ins |
Dsreg/10.0 (Windows 10.0.19041.928) | User agent | ROADtools device registration |
AADSTS50199 | Sign-in error | CMSI interrupt on the first Microsoft Authentication Broker sign-ins |
How to hunt
Test 1 covers 30 days of Entra audit logs and the hunts look back 90 days. This threat hunting runs in Splunk, Elastic, CrowdStrike and Microsoft KQL for Microsoft Sentinel or Log Analytics. Hunt 2 follows the suspicious session ID, which Huntress calls the easiest hunt.
Test 1: which devices are registered in your Entra ID, who owns each one and what does each claim to be
Purpose: each recent registration with owner, app, build, join type and hardware identifier, counted by build.
Splunk
`comment("OS version, join type and hardware ID are read from the raw target resource text because the modified property names vary; verify in your environment. YOUR_APPROVED_DEVICE_NAMES is optional, as a | separated list.")`
index=YOUR_INDEX sourcetype="azure:monitor:aad" earliest=-30d@d operationName IN ("Add device", "Register device", "Add registered owner to device")
| eval device=coalesce(mvindex('properties.targetResources{}.displayName', mvfind('properties.targetResources{}.type', "^Device$")), "(no device name in record)")
| eval who=coalesce('properties.initiatedBy.user.userPrincipalName', mvindex('properties.targetResources{}.userPrincipalName', 0)), init_app='properties.initiatedBy.app.displayName'
| rex field=_raw "(?<os_version>10\.0\.\d{5}(\.\d+)?)"
| rex field=_raw "(?i)(?<join_type>AzureAd|Workplace|ServerAd)"
| stats min(_time) as first_seen values(operationName) as operations values(who) as owner_or_user values(init_app) as initiating_app values(os_version) as os_version values(join_type) as join_type values(_raw) as record_text by device
| eval os_version=mvindex(os_version, 0)
| eval status=case(isnull(os_version), "2 OS version not in the record: read it by hand",
NOT match(device, "^(YOUR_APPROVED_DEVICE_NAMES)$"), "3 not on your approved list: name an owner",
true(), "4 on your approved list")
| eventstats count as devices_on_build by os_version
| appendpipe [| stats count as devices | where devices=0 | eval status="0 no device registrations in 30 days: confirm audit logs arrive before calling this clean"]
| convert ctime(first_seen)
| table status device owner_or_user initiating_app os_version devices_on_build join_type operations first_seen record_text
| sort status -devices_on_build deviceElastic
// Last 30 days of the Azure integration's audit logs. OS version, join type and hardware ID are read from event.original,
// which the integration keeps when Preserve original event is on; verify in your environment.
// YOUR_APPROVED_DEVICE_NAMES is optional. For the count by OS version, end with: | STATS devices = COUNT(*) BY os_version
FROM logs-azure.auditlogs-*
| WHERE @timestamp >= NOW() - 30 days
AND azure.auditlogs.operation_name IN ("Add device", "Register device", "Add registered owner to device")
| EVAL raw = COALESCE(event.original, ""),
device = COALESCE(`azure.auditlogs.properties.target_resources.0.display_name`, "(no device name in record)"),
who = COALESCE(azure.auditlogs.properties.initiated_by.user.userPrincipalName, `azure.auditlogs.properties.target_resources.0.user_principal_name`)
| GROK raw """(?<os_version>10\.0\.[0-9]{5}(\.[0-9]+)?)"""
| GROK raw """(?<join_type>(?i:AzureAd|Workplace|ServerAd))"""
| EVAL kept = CASE(raw == "", 0, 1)
| STATS first_seen = MIN(@timestamp), operations = VALUES(azure.auditlogs.operation_name), owner_or_user = VALUES(who),
initiating_app = VALUES(azure.auditlogs.properties.initiated_by.app.displayName),
os_versions = VALUES(os_version), join_types = VALUES(join_type), kept = MAX(kept), record_text = VALUES(raw) BY device
| EVAL os_version = MV_FIRST(os_versions)
| EVAL status = CASE(kept == 0, "0 record text not kept: turn on Preserve original event before calling this clean",
os_version IS NULL, "2 OS version not in the record: read it by hand",
device NOT IN ("YOUR_APPROVED_DEVICE_NAMES"), "3 not on your approved list: name an owner",
"4 on your approved list")
| SORT status, os_version, deviceCrowdStrike
// Time picker: last 30 days. Repo from CrowdStrike's Entra ID connector.
// Vendor.operationName, Vendor.initiatedBy.* and the Vendor.properties audit paths come from a community field reference; verify in your environment.
// OS version, join type and hardware ID are read from @rawstring because the modified property names vary.
// An empty result is not a clean result: confirm AuditLogs events reach this repo.
// For the count by OS version, end with: | groupBy([os_version], function=count(as=devices))
#repo = "3pi_microsoft_entra_id"
| Vendor.operationName = /^(Add device|Register device|Add registered owner to device)$/
| rename(field="Vendor.properties.targetResources[0].displayName", as=device)
| rename(field="Vendor.properties.targetResources[0].userPrincipalName", as=target_upn)
| rename(field="Vendor.properties.initiatedBy.user.userPrincipalName", as=init_upn)
| rename(field="Vendor.initiatedBy.app.displayName", as=init_app)
| coalesce([init_upn, target_upn], as=who)
| default(field=device, value="(no device name in record)")
| regex("(?<os_version>10\.0\.\d{5}(\.\d+)?)", field=@rawstring, strict=false)
| regex("(?<join_type>AzureAd|Workplace|ServerAd)", field=@rawstring, flags="i", strict=false)
| groupBy([device], function=[min(@timestamp, as=first_seen), collect([Vendor.operationName, who, init_app, os_version, join_type, @rawstring])], limit=max)
| default(field=os_version, value="")
| case {
os_version = "" | status := "2 OS version not in the record: read it by hand" ;
in(field="device", values=["YOUR_APPROVED_DEVICE_NAMES"]) | status := "4 on your approved list" ;
* | status := "3 not on your approved list: name an owner" }
| sort([status, device], order=asc, limit=10000)Microsoft KQL
// Last 30 days of AuditLogs in Microsoft Sentinel or Log Analytics.
// OS version, join type and hardware ID are read from the whole TargetResources text because the modified property names vary; verify in your environment.
// YOUR_APPROVED_DEVICE_NAMES is optional.
let lookback = 30d;
let approved = dynamic(["YOUR_APPROVED_DEVICE_NAMES"]);
let inv = materialize(
AuditLogs
| where TimeGenerated > ago(lookback)
| where OperationName in ("Add device", "Register device", "Add registered owner to device")
| mv-apply t = TargetResources on (
summarize Device = take_anyif(tostring(t.displayName), tostring(t.type) == "Device"),
TargetUser = take_anyif(tostring(t.userPrincipalName), tostring(t.type) == "User"))
| extend Raw = tostring(TargetResources)
| extend Device = iff(isempty(Device), "(no device name in record)", Device),
Who = coalesce(tostring(InitiatedBy.user.userPrincipalName), TargetUser),
InitiatingApp = tostring(InitiatedBy.app.displayName),
OsVersion = extract(@"(10\.0\.\d{5}(\.\d+)?)", 1, Raw),
JoinType = extract(@"(?i)(AzureAd|Workplace|ServerAd)", 1, Raw)
| summarize FirstSeen = min(TimeGenerated), Operations = make_set(OperationName),
OwnerOrUser = make_set_if(Who, isnotempty(Who)), InitiatingApps = make_set_if(InitiatingApp, isnotempty(InitiatingApp)),
OsVersion = take_anyif(OsVersion, isnotempty(OsVersion)), JoinType = take_anyif(JoinType, isnotempty(JoinType)),
RecordText = make_set(Raw) by Device
| extend Status = case(isempty(OsVersion), "2 OS version not in the record: read it by hand",
not(Device in (approved)), "3 not on your approved list: name an owner",
"4 on your approved list"));
let builds = inv | summarize DevicesOnBuild = count() by OsVersion;
let health = print Status = "0 no device registrations in 30 days: confirm AuditLogs arrive before calling this clean"
| where toscalar(inv | count) == 0;
inv
| join kind=leftouter builds on OsVersion
| project-away OsVersion1
| union health
| order by Status asc, DevicesOnBuild descField mapping: the three device audit operations, with name and owner from the target resources and build, join type and hardware identifier from the record text. Missing detail is flagged, never cleared.
Hunt 1: device registrations that carry a toolkit's defaults
Purpose: Huntress's names and builds for all three operations, plus the Dsreg/10.0 user agent.
Splunk
`comment("Builds, hardware ID and Dsreg are matched in the raw record text; verify in your environment.")`
index=YOUR_INDEX sourcetype="azure:monitor:aad" earliest=-90d@d (operationName IN ("Add device", "Register device", "Add registered owner to device") OR "Dsreg/10.0")
| eval is_reg=if(in(operationName, "Add device", "Register device", "Add registered owner to device"), 1, 0)
| eval who=coalesce('properties.initiatedBy.user.userPrincipalName', 'properties.userPrincipalName', mvindex('properties.targetResources{}.userPrincipalName', 0))
| eval device=if(is_reg=1, coalesce(mvindex('properties.targetResources{}.displayName', mvfind('properties.targetResources{}.type', "^Device$")), "(no device name in record)"), "sign-in by ".coalesce(who, "unknown user"))
| rex field=_raw "(?<build>10\.0\.\d{5}(\.\d+)?)"
| eval mh=if(match(device, "^MH-[0-9A-F]{16}$"), 1, 0)
| eval toolkit_build=if(match(_raw, "(^|[^0-9.])10\.0\.(19041\.928|19045\.2006|19045\.0|26100)([^0-9.]|$)"), 1, 0)
| eval tool_name=if(match(device, "^(DESKTOP-[A-Z0-9]{6}|DESKTOP-[A-Z0-9]{8}|Device-[0-9A-Fa-f]{8}|GraphSpy-Device)$"), 1, 0)
| eval dsreg=if(match('properties.userAgent', "^Dsreg/10\.0") OR match(_raw, "Dsreg/10\.0"), 1, 0)
| stats min(_time) as first_seen values(who) as owner values(build) as build max(mh) as mh max(toolkit_build) as toolkit_build max(tool_name) as tool_name max(dsreg) as dsreg values(_raw) as record_text by device
| eval status=case(mh=1, "1 MH- name with 16 hex characters",
toolkit_build=1, "1 toolkit default build: read the record for a hardware identifier",
tool_name=1, "2 toolkit-style name: read the record for a hardware identifier",
dsreg=1, "2 Dsreg/10.0 user agent")
| where isnotnull(status)
| convert ctime(first_seen)
| table status device owner build first_seen record_text
| sort status first_seenElastic
// Last 90 days. Builds, hardware ID and Dsreg are read from event.original, kept when Preserve original event is on; verify in your environment.
FROM logs-azure.auditlogs-*, logs-azure.signinlogs-*
| WHERE @timestamp >= NOW() - 90 days
| EVAL raw = COALESCE(event.original, ""),
is_reg = COALESCE(azure.auditlogs.operation_name IN ("Add device", "Register device", "Add registered owner to device"), false),
agent = COALESCE(user_agent.original, azure.auditlogs.properties.additional_details.user_agent, ""),
dsreg = agent LIKE "Dsreg/10.0*" OR raw LIKE "*Dsreg/10.0*"
| WHERE is_reg OR dsreg
| EVAL owner = COALESCE(azure.auditlogs.properties.initiated_by.user.userPrincipalName, azure.signinlogs.properties.user_principal_name),
device = CASE(is_reg, COALESCE(`azure.auditlogs.properties.target_resources.0.display_name`, "(no device name in record)"), CONCAT("sign-in by ", COALESCE(owner, "unknown user")))
| GROK raw """(?<build>10\.0\.[0-9]{5}(\.[0-9]+)?)"""
| EVAL mh = CASE(device RLIKE "MH-[0-9A-F]{16}", 1, 0),
tb = CASE(raw RLIKE """.*[^0-9.]10\.0\.(19041\.928|19045\.2006|19045\.0|26100)[^0-9.].*""", 1, 0),
tn = CASE(device RLIKE "DESKTOP-[A-Z0-9]{6}|DESKTOP-[A-Z0-9]{8}|Device-[0-9A-Fa-f]{8}|GraphSpy-Device", 1, 0),
ds = CASE(dsreg, 1, 0)
| STATS first_seen = MIN(@timestamp), owners = VALUES(owner), builds = VALUES(build),
mh = MAX(mh), tb = MAX(tb), tn = MAX(tn), ds = MAX(ds), record_text = VALUES(raw) BY device
| EVAL status = CASE(mh == 1, "1 MH- name with 16 hex characters",
tb == 1, "1 toolkit default build: read the record for a hardware identifier",
tn == 1, "2 toolkit-style name: read the record for a hardware identifier",
ds == 1, "2 Dsreg/10.0 user agent",
null)
| WHERE status IS NOT NULL
| SORT status, first_seenCrowdStrike
// Time picker: last 90 days. Fields after the repo come from a community field reference; verify in your environment.
// Builds, hardware ID and Dsreg are matched in @rawstring.
#repo = "3pi_microsoft_entra_id"
| Vendor.operationName = /^(Add device|Register device|Add registered owner to device)$/ or "Dsreg/10.0"
| case { Vendor.operationName = /^(Add device|Register device|Add registered owner to device)$/ | is_reg := 1 ; * | is_reg := 0 }
| rename(field="Vendor.properties.targetResources[0].displayName", as=device)
| rename(field="Vendor.properties.initiatedBy.user.userPrincipalName", as=init_upn)
| coalesce([init_upn, user.email, user.full_name], as=owner)
| case { is_reg = 0 | device := format("sign-in by %s", field=[owner]) ; * | default(field=device, value="(no device name in record)") }
| regex("(?<build>10\.0\.\d{5}(\.\d+)?)", field=@rawstring, strict=false)
| case { device = /^MH-[0-9A-F]{16}$/ | mh := 1 ; * | mh := 0 }
| case { @rawstring = /(^|[^0-9.])10\.0\.(19041\.928|19045\.2006|19045\.0|26100)([^0-9.]|$)/ | tb := 1 ; * | tb := 0 }
| case { device = /^(DESKTOP-[A-Z0-9]{6}|DESKTOP-[A-Z0-9]{8}|Device-[0-9A-Fa-f]{8}|GraphSpy-Device)$/ | tn := 1 ; * | tn := 0 }
| case { @rawstring = /Dsreg\/10\.0/ | ds := 1 ; * | ds := 0 }
| groupBy([device], function=[min(@timestamp, as=first_seen), max(mh, as=mh), max(tb, as=tb), max(tn, as=tn), max(ds, as=ds), collect([owner, build, @rawstring])], limit=max)
| case {
mh = 1 | status := "1 MH- name with 16 hex characters" ;
tb = 1 | status := "1 toolkit default build: read the record for a hardware identifier" ;
tn = 1 | status := "2 toolkit-style name: read the record for a hardware identifier" ;
ds = 1 | status := "2 Dsreg/10.0 user agent" ;
* | status := "" }
| status != ""
| sort([status, first_seen], order=asc, limit=10000)Microsoft KQL
// Last 90 days. Builds, hardware ID and Dsreg are matched in the TargetResources and AdditionalDetails text; verify in your environment.
let lookback = 90d;
let toolkitBuild = @"(^|[^0-9.])10\.0\.(19041\.928|19045\.2006|19045\.0|26100)([^0-9.]|$)";
let toolkitName = @"^(DESKTOP-[A-Z0-9]{6}|DESKTOP-[A-Z0-9]{8}|Device-[0-9A-Fa-f]{8}|GraphSpy-Device)$";
let regs = AuditLogs
| where TimeGenerated > ago(lookback)
| where OperationName in ("Add device", "Register device", "Add registered owner to device")
| mv-apply t = TargetResources on (
summarize Device = take_anyif(tostring(t.displayName), tostring(t.type) == "Device"),
TargetUser = take_anyif(tostring(t.userPrincipalName), tostring(t.type) == "User"))
| extend Raw = strcat(tostring(TargetResources), " ", tostring(AdditionalDetails)),
Owner = coalesce(tostring(InitiatedBy.user.userPrincipalName), TargetUser)
| extend Build = extract(@"(10\.0\.\d{5}(\.\d+)?)", 1, Raw),
Mh = iff(Device matches regex @"^MH-[0-9A-F]{16}$", 1, 0),
Tb = iff(Raw matches regex toolkitBuild, 1, 0),
Tn = iff(Device matches regex toolkitName, 1, 0),
Ds = iff(Raw contains "Dsreg/10.0", 1, 0)
| summarize FirstSeen = min(TimeGenerated), Owners = make_set_if(Owner, isnotempty(Owner)), Build = take_anyif(Build, isnotempty(Build)),
Mh = max(Mh), Tb = max(Tb), Tn = max(Tn), Ds = max(Ds), RecordText = make_set(Raw) by Device;
let dsregSignins = union SigninLogs, AADNonInteractiveUserSignInLogs
| where TimeGenerated > ago(lookback) and UserAgent startswith "Dsreg/10.0"
| summarize FirstSeen = min(TimeGenerated), Owners = make_set(UserPrincipalName), Build = take_any(UserAgent), RecordText = make_set(UserAgent) by Device = strcat("sign-in from ", IPAddress)
| extend Mh = 0, Tb = 0, Tn = 0, Ds = 1;
union regs, dsregSignins
| extend Status = case(Mh == 1, "1 MH- name with 16 hex characters",
Tb == 1, "1 toolkit default build: read the record for a hardware identifier",
Tn == 1, "2 toolkit-style name: read the record for a hardware identifier",
Ds == 1, "2 Dsreg/10.0 user agent",
"")
| where isnotempty(Status)
| project Status, Device, Owners, Build, FirstSeen, RecordText
| order by Status asc, FirstSeen ascField mapping: the same records, names from the device display name and builds from the record text, plus Dsreg/10.0 sign-ins. False positives: Autopilot, Intune enrollment and lab machines on old images; confirm the hardware identifier and the person before deleting.
Hunt 2: a device code sign-in that turns into a scripted sign-in and a new device
Purpose: the chain Huntress walks through, device code to script to new device.
Splunk
`comment("properties.status.errorCode, properties.authenticationProtocol, properties.appId, properties.sessionId and properties.correlationId follow the Entra sign-in schema; verify in your environment. The app ID is the one CrowdStrike gives for device code PRT phishing.")`
index=YOUR_INDEX sourcetype="azure:monitor:aad" earliest=-90d@d (operationName="Sign-in activity" OR operationName IN ("Add device", "Register device", "Add registered owner to device"))
| eval user=lower(coalesce('properties.userPrincipalName', 'properties.initiatedBy.user.userPrincipalName', mvindex('properties.targetResources{}.userPrincipalName', 0)))
| eval session=coalesce('properties.sessionId', 'properties.correlationId'), ip=coalesce('properties.ipAddress', callerIpAddress), ua='properties.userAgent'
| eval step=case(in(operationName, "Add device", "Register device", "Add registered owner to device"), "register",
'properties.isInteractive'="true" AND ('properties.appDisplayName'="Microsoft Authentication Broker" OR 'properties.appId'="29d9ed98-a469-4536-ade2-f981bc1d605e") AND ('properties.status.errorCode'=50199 OR 'properties.authenticationProtocol'="deviceCode"), "code",
'properties.isInteractive'!="true" AND match(ua, "(?i)^(python-requests|python-httpx|node|node-fetch|undici|axios)"), "script")
| where isnotnull(step)
| sort 0 user _time
| eval code_time=if(step="code", _time, null()), code_ip=if(step="code", ip, null()), code_session=if(step="code", session, null())
| streamstats last(code_time) as last_code_time last(code_ip) as last_code_ip last(code_session) as last_code_session by user
| eval pivot=if(step="script" AND _time-last_code_time<=1800 AND ip!=last_code_ip AND session=last_code_session, 1, 0)
| eval pivot_time=if(pivot=1, _time, null()), pivot_ip=if(pivot=1, ip, null()), pivot_ua=if(pivot=1, ua, null())
| streamstats last(pivot_time) as last_pivot_time by user
| eval device=if(step="register", mvindex('properties.targetResources{}.displayName', mvfind('properties.targetResources{}.type', "^Device$")), null())
| eval chain=case(step="register" AND _time-last_pivot_time<=86400, "1 device code, scripted sign-in, then a device registration",
pivot=1, "2 device code, then a scripted sign-in from a new IP in the same session")
| where isnotnull(chain)
| stats min(_time) as first_seen values(chain) as chain values(last_code_ip) as device_code_ip values(pivot_ip) as scripted_ip values(pivot_ua) as scripted_ua values(device) as device by user
| eval status=mvindex(mvsort(chain), 0)
| convert ctime(first_seen)
| table status user first_seen device_code_ip scripted_ip scripted_ua device
| sort status first_seenElastic
// Last 90 days. This integration exposes correlation_id but no session ID, so the chain is grouped by user and UTC day;
// compare the IPs and correlation IDs in the output. user_agent.original: verify in your environment.
// app_id 29d9ed98-a469-4536-ade2-f981bc1d605e is the client ID CrowdStrike gives for device code PRT phishing.
FROM logs-azure.signinlogs-*, logs-azure.auditlogs-*
| WHERE @timestamp >= NOW() - 90 days
| EVAL user = TO_LOWER(COALESCE(azure.signinlogs.properties.user_principal_name, azure.auditlogs.properties.initiated_by.user.userPrincipalName, `azure.auditlogs.properties.target_resources.0.user_principal_name`)),
ua = TO_LOWER(COALESCE(user_agent.original, "")),
is_code = azure.signinlogs.properties.is_interactive == true
AND (azure.signinlogs.properties.app_display_name == "Microsoft Authentication Broker" OR azure.signinlogs.properties.app_id == "29d9ed98-a469-4536-ade2-f981bc1d605e")
AND (azure.signinlogs.properties.status.error_code == 50199 OR azure.signinlogs.properties.authentication_protocol == "deviceCode"),
is_script = azure.signinlogs.properties.is_interactive == false
AND (ua LIKE "python-requests*" OR ua LIKE "python-httpx*" OR ua LIKE "node*" OR ua LIKE "undici*" OR ua LIKE "axios*"),
is_reg = azure.auditlogs.operation_name IN ("Add device", "Register device", "Add registered owner to device"),
day = DATE_TRUNC(1 day, @timestamp)
| WHERE is_code OR is_script OR is_reg
| STATS code_time = MIN(@timestamp) WHERE is_code, code_ips = VALUES(source.ip) WHERE is_code,
code_corr = VALUES(azure.signinlogs.properties.correlation_id) WHERE is_code,
script_time = MIN(@timestamp) WHERE is_script, script_ips = VALUES(source.ip) WHERE is_script,
script_uas = VALUES(user_agent.original) WHERE is_script, script_corr = VALUES(azure.signinlogs.properties.correlation_id) WHERE is_script,
reg_time = MAX(@timestamp) WHERE is_reg, devices = VALUES(`azure.auditlogs.properties.target_resources.0.display_name`) WHERE is_reg
BY user, day
| EVAL gap_min = DATE_DIFF("minute", code_time, script_time)
| WHERE gap_min >= 0 AND gap_min <= 30
AND MV_CONCAT(TO_STRING(script_ips), ",") != MV_CONCAT(TO_STRING(code_ips), ",")
| EVAL status = CASE(reg_time IS NOT NULL AND reg_time >= code_time, "1 device code, scripted sign-in, then a device registration",
"2 device code, then a scripted sign-in from a new IP")
| KEEP status, user, code_time, code_ips, script_time, script_ips, script_uas, code_corr, script_corr, reg_time, devices
| SORT status, code_time DESCCrowdStrike
#repo = "3pi_microsoft_entra_id" | Vendor.properties.authenticationProtocol = deviceCode | Vendor.properties.appId = "29d9ed98-a469-4536-ade2-f981bc1d605e"
// Line 1 is CrowdStrike's published device code query; the app ID is CrowdStrike's. Huntress names the app Microsoft Authentication Broker.
// Time picker: last 90 days. Fields after line 1 come from a community field reference, and Vendor.properties.sessionId and Vendor.properties.isInteractive are assumed from the Entra schema; verify in your environment.
| coalesce([user.email, user.full_name], as=upn) | upn := lower(upn)
| coalesce([Vendor.properties.sessionId, Vendor.properties.correlationId, Vendor.correlationId], as=sid)
| rename(field="source.ip", as=code_ip) | code_time := @timestamp
| join(query={
#repo = "3pi_microsoft_entra_id" event.provider = /SignInLogs/i
| user_agent.original = /^(python-requests|python-httpx|node|node-fetch|undici|axios)/i | Vendor.properties.isInteractive = false
| coalesce([user.email, user.full_name], as=upn) | upn := lower(upn)
| coalesce([Vendor.properties.sessionId, Vendor.properties.correlationId, Vendor.correlationId], as=sid)
| rename(field="source.ip", as=script_ip) | rename(field="user_agent.original", as=script_ua) | script_time := @timestamp
}, field=[upn, sid], include=[script_ip, script_ua, script_time], mode=inner)
| test(script_time >= code_time) | test(script_time - code_time <= 1800000) | test(script_ip != code_ip)
| join(query={
#repo = "3pi_microsoft_entra_id" Vendor.operationName = /^(Add device|Register device|Add registered owner to device)$/
| rename(field="Vendor.properties.initiatedBy.user.userPrincipalName", as=init_upn) | rename(field="Vendor.properties.targetResources[0].userPrincipalName", as=target_upn) | coalesce([init_upn, target_upn], as=upn) | upn := lower(upn)
| rename(field="Vendor.properties.targetResources[0].displayName", as=device) | reg_time := @timestamp
}, field=upn, include=[device, reg_time], mode=left)
| case {
test(reg_time >= code_time) | test(reg_time - code_time <= 86400000) | status := "1 device code, scripted sign-in, then a device registration" ;
* | status := "2 device code, then a scripted sign-in from a new IP in the same session" }
| select([status, upn, code_time, code_ip, script_time, script_ip, script_ua, device, reg_time])
| sort([status, code_time], order=asc, limit=10000)Microsoft KQL
// Last 90 days. AppId 29d9ed98-a469-4536-ade2-f981bc1d605e is the client ID CrowdStrike gives for device code PRT phishing;
// Huntress names the app Microsoft Authentication Broker. In Defender XDR advanced hunting, EntraIdSignInEvents carries the same sign-ins.
let lookback = 90d;
let pivotWindow = 30m;
let programmatic = @"(?i)^(python-requests|python-httpx|node|node-fetch|undici|axios)";
let deviceCode = SigninLogs
| where TimeGenerated > ago(lookback)
| where AppDisplayName == "Microsoft Authentication Broker" or AppId == "29d9ed98-a469-4536-ade2-f981bc1d605e"
| where ResultType == "50199" or AuthenticationProtocol == "deviceCode"
| project CodeTime = TimeGenerated, User = tolower(UserPrincipalName), CodeSession = SessionId, CodeCorrelation = CorrelationId, CodeIP = IPAddress;
let scripted = AADNonInteractiveUserSignInLogs
| where TimeGenerated > ago(lookback)
| where UserAgent matches regex programmatic
| project ScriptTime = TimeGenerated, User = tolower(UserPrincipalName), ScriptSession = SessionId, ScriptCorrelation = CorrelationId,
ScriptIP = IPAddress, ScriptUA = UserAgent, ScriptApp = AppDisplayName;
let registrations = AuditLogs
| where TimeGenerated > ago(lookback)
| where OperationName in ("Add device", "Register device", "Add registered owner to device")
| mv-apply t = TargetResources on (
summarize Device = take_anyif(tostring(t.displayName), tostring(t.type) == "Device"),
TargetUser = take_anyif(tostring(t.userPrincipalName), tostring(t.type) == "User"))
| project RegTime = TimeGenerated, User = tolower(coalesce(tostring(InitiatedBy.user.userPrincipalName), TargetUser)), Device;
deviceCode
| join kind=inner scripted on User
| where ScriptTime between (CodeTime .. (CodeTime + pivotWindow))
| where ScriptIP != CodeIP
| where (isnotempty(CodeSession) and CodeSession == ScriptSession) or (isnotempty(CodeCorrelation) and CodeCorrelation == ScriptCorrelation)
| join kind=leftouter registrations on User
| extend Registered = isnotempty(Device) and RegTime between (CodeTime .. (CodeTime + 1d))
| summarize CodeIP = take_any(CodeIP), ScriptIP = take_any(ScriptIP), ScriptUA = take_any(ScriptUA), ScriptApp = take_any(ScriptApp),
Devices = make_set_if(Device, Registered), Registered = max(toint(Registered)) by User, CodeTime
| extend Status = iff(Registered == 1, "1 device code, scripted sign-in, then a device registration",
"2 device code, then a scripted sign-in from a new IP in the same session")
| order by Status asc, CodeTime descField mapping: Authentication Broker sign-ins, then programmatic non-interactive sign-ins, then registrations, by user. Splunk, CrowdStrike and Microsoft KQL match session or correlation ID; Elastic groups by user and day. CrowdStrike opens with CrowdStrike's device code query. False positives: developers testing device code sign-ins from scripts; check whether a device followed.
Hunt 3: sign-ins from the campaign's addresses, scripted clients and brand-new devices
Purpose: Huntress's five IPs, scripted clients on ordinary accounts, and sign-ins from new Hunt 1 devices.
Splunk
`comment("properties.deviceDetail.displayName, properties.deviceDetail.deviceId and properties.status.errorCode follow the Entra sign-in schema; verify in your environment. YOUR_NAMED_APPROVED_REGISTRARS is a | separated list of lowercase accounts.")`
index=YOUR_INDEX sourcetype="azure:monitor:aad" earliest=-90d@d (operationName="Sign-in activity" OR operationName IN ("Add device", "Register device"))
| eval user=lower(coalesce('properties.userPrincipalName', 'properties.initiatedBy.user.userPrincipalName', mvindex('properties.targetResources{}.userPrincipalName', 0)))
| eval ip=coalesce('properties.ipAddress', callerIpAddress), ua='properties.userAgent'
| eval reg_device=if(in(operationName, "Add device", "Register device"), mvindex('properties.targetResources{}.displayName', mvfind('properties.targetResources{}.type', "^Device$")), null())
| eval hunt1_name=if(match(reg_device, "^(MH-[0-9A-F]{16}|DESKTOP-[A-Z0-9]{6}|DESKTOP-[A-Z0-9]{8}|Device-[0-9A-Fa-f]{8}|GraphSpy-Device)$"), reg_device, null())
| eval reg_time=if(isnotnull(hunt1_name), _time, null())
| eval signin_device=coalesce('properties.deviceDetail.displayName', 'properties.deviceDetail.deviceId')
| eval match_device=coalesce(hunt1_name, signin_device)
| sort 0 match_device _time
| streamstats last(reg_time) as last_reg_time last(hunt1_name) as last_reg_name by match_device
| eval status=case(
in(ip, "181.214.147.42", "92.62.251.249", "37.252.11.196", "146.103.38.149", "193.109.193.166"), "1 sign-in from an IP Huntress lists",
operationName="Sign-in activity" AND isnotnull(last_reg_time) AND _time-last_reg_time<=86400 AND signin_device=last_reg_name, "1 sign-in from a device registered within 24 hours with a Hunt 1 name",
operationName="Sign-in activity" AND 'properties.isInteractive'!="true" AND match(ua, "(?i)^(python-requests|python-httpx|node|node-fetch|undici|axios)") AND NOT match(user, "^(YOUR_NAMED_APPROVED_REGISTRARS)$"), "2 scripted client on an account not on your automation list")
| where isnotnull(status)
| eval result=if('properties.status.errorCode'=0, "success", "failure")
| stats count as events count(eval(result="success")) as successful count(eval(result="failure")) as failed min(_time) as first_seen max(_time) as last_seen values(ip) as ips values(ua) as user_agents values(last_reg_name) as new_device by status user
| convert ctime(first_seen) ctime(last_seen)
| sort status -eventsElastic
// Last 90 days. device_detail.display_name ties a sign-in to a newly registered device; user_agent.original: verify in your environment.
// YOUR_NAMED_APPROVED_REGISTRARS lists lowercase accounts allowed to run scripts.
FROM logs-azure.signinlogs-*, logs-azure.auditlogs-*
| WHERE @timestamp >= NOW() - 90 days
| EVAL user = TO_LOWER(COALESCE(azure.signinlogs.properties.user_principal_name, azure.auditlogs.properties.initiated_by.user.userPrincipalName, `azure.auditlogs.properties.target_resources.0.user_principal_name`)),
ua = TO_LOWER(COALESCE(user_agent.original, "")),
is_signin = event.dataset == "azure.signinlogs",
reg_device = CASE(azure.auditlogs.operation_name IN ("Add device", "Register device"), `azure.auditlogs.properties.target_resources.0.display_name`, null),
signin_device = azure.signinlogs.properties.device_detail.display_name,
name = COALESCE(reg_device, signin_device),
hunt1 = COALESCE(name RLIKE "MH-[0-9A-F]{16}|DESKTOP-[A-Z0-9]{6}|DESKTOP-[A-Z0-9]{8}|Device-[0-9A-Fa-f]{8}|GraphSpy-Device", false),
huntress_ip = COALESCE(TO_STRING(source.ip) IN ("181.214.147.42", "92.62.251.249", "37.252.11.196", "146.103.38.149", "193.109.193.166"), false),
scripted = COALESCE(is_signin AND azure.signinlogs.properties.is_interactive == false
AND (ua LIKE "python-requests*" OR ua LIKE "python-httpx*" OR ua LIKE "node*" OR ua LIKE "undici*" OR ua LIKE "axios*")
AND user NOT IN ("YOUR_NAMED_APPROVED_REGISTRARS"), false),
device_key = CASE(hunt1, name, null),
user_key = CASE(hunt1, null, user)
| WHERE huntress_ip OR scripted OR hunt1
| STATS users = VALUES(user), ip_hits = COUNT(*) WHERE huntress_ip, ip_success = COUNT(*) WHERE huntress_ip AND azure.signinlogs.properties.status.error_code == 0,
scripted_hits = COUNT(*) WHERE scripted, reg_time = MIN(@timestamp) WHERE hunt1 AND reg_device IS NOT NULL,
device_signin = MIN(@timestamp) WHERE hunt1 AND is_signin,
ips = VALUES(source.ip) WHERE huntress_ip OR scripted, user_agents = VALUES(user_agent.original) WHERE scripted
BY user_key, device_key
| EVAL hours = DATE_DIFF("hour", reg_time, device_signin)
| EVAL status = CASE(ip_hits > 0, "1 sign-in from an IP Huntress lists",
hours >= 0 AND hours <= 24, "1 sign-in from a device registered within 24 hours with a Hunt 1 name",
scripted_hits > 0, "2 scripted client on an account not on your automation list",
null)
| WHERE status IS NOT NULL
| SORT status, ip_hits DESC, user_keyCrowdStrike
// Time picker: last 90 days. Fields after the repo come from a community field reference; verify in your environment.
// YOUR_NAMED_APPROVED_REGISTRARS lists lowercase accounts allowed to run scripts.
#repo = "3pi_microsoft_entra_id" event.provider = /SignInLogs/i
| coalesce([user.email, user.full_name], as=upn) | upn := lower(upn)
| coalesce([Vendor.deviceDetail.displayName, Vendor.properties.deviceDetail.displayName], as=signin_device)
| join(query={
#repo = "3pi_microsoft_entra_id" Vendor.operationName = /^(Add device|Register device)$/
| rename(field="Vendor.properties.targetResources[0].displayName", as=signin_device)
| signin_device = /^(MH-[0-9A-F]{16}|DESKTOP-[A-Z0-9]{6}|DESKTOP-[A-Z0-9]{8}|Device-[0-9A-Fa-f]{8}|GraphSpy-Device)$/
| reg_time := @timestamp
}, field=signin_device, include=[reg_time], mode=left)
| case {
in(field="source.ip", values=["181.214.147.42", "92.62.251.249", "37.252.11.196", "146.103.38.149", "193.109.193.166"]) | status := "1 sign-in from an IP Huntress lists" ;
test(@timestamp >= reg_time) | test(@timestamp - reg_time <= 86400000) | status := "1 sign-in from a device registered within 24 hours with a Hunt 1 name" ;
user_agent.original = /^(python-requests|python-httpx|node|node-fetch|undici|axios)/i Vendor.properties.isInteractive = false | !in(field="upn", values=["YOUR_NAMED_APPROVED_REGISTRARS"]) | status := "2 scripted client on an account not on your automation list" ;
* | status := "" }
| status != ""
| groupBy([status, upn], function=[count(as=events), min(@timestamp, as=first_seen), max(@timestamp, as=last_seen), collect([source.ip, user_agent.original, #event.outcome, signin_device])], limit=max)
| sort([status, events], order=asc, limit=10000)Microsoft KQL
// Last 90 days. DeviceDetail.displayName and deviceId come from the sign-in DeviceDetail column; verify in your environment.
// YOUR_NAMED_APPROVED_REGISTRARS lists lowercase accounts allowed to run scripts.
let lookback = 90d;
let huntressIPs = dynamic(["181.214.147.42", "92.62.251.249", "37.252.11.196", "146.103.38.149", "193.109.193.166"]);
let programmatic = @"(?i)^(python-requests|python-httpx|node|node-fetch|undici|axios)";
let approvedAutomation = dynamic(["YOUR_NAMED_APPROVED_REGISTRARS"]);
let hunt1Name = @"^(MH-[0-9A-F]{16}|DESKTOP-[A-Z0-9]{6}|DESKTOP-[A-Z0-9]{8}|Device-[0-9A-Fa-f]{8}|GraphSpy-Device)$";
let signins = union
(SigninLogs | where TimeGenerated > ago(lookback) | extend Dev = DeviceDetail),
(AADNonInteractiveUserSignInLogs | where TimeGenerated > ago(lookback) | extend Dev = todynamic(DeviceDetail))
| project TimeGenerated, User = tolower(UserPrincipalName), IPAddress, UserAgent, AppDisplayName, ResultType, IsInteractive,
DevName = tostring(Dev.displayName), DevId = tostring(Dev.deviceId);
let newDevices = AuditLogs
| where TimeGenerated > ago(lookback)
| where OperationName in ("Add device", "Register device")
| mv-apply t = TargetResources on (
summarize Device = take_anyif(tostring(t.displayName), tostring(t.type) == "Device"),
DeviceObjectId = take_anyif(tostring(t.id), tostring(t.type) == "Device"))
| where Device matches regex hunt1Name
| project RegTime = TimeGenerated, Device, DeviceObjectId;
let ipHits = signins
| where IPAddress in (huntressIPs)
| extend Status = "1 sign-in from an IP Huntress lists";
let deviceHits = union
(signins | join kind=inner newDevices on $left.DevName == $right.Device),
(signins | join kind=inner newDevices on $left.DevId == $right.DeviceObjectId)
| where TimeGenerated between (RegTime .. (RegTime + 24h))
| extend Status = "1 sign-in from a device registered within 24 hours with a Hunt 1 name";
let scriptHits = signins
| where IsInteractive == false and UserAgent matches regex programmatic and not(User in (approvedAutomation))
| extend Status = "2 scripted client on an account not on your automation list";
union ipHits, deviceHits, scriptHits
| summarize Events = count(), Successful = countif(ResultType in~ ("0", "Success")), Failed = countif(ResultType !in~ ("0", "Success")),
FirstSeen = min(TimeGenerated), LastSeen = max(TimeGenerated),
IPs = make_set(IPAddress, 20), UserAgents = make_set(UserAgent, 10), Devices = make_set_if(DevName, isnotempty(DevName), 10) by Status, User
| order by Status asc, Events descField mapping: sign-in IP, user agent and device detail, joined to new registrations. YOUR_NAMED_APPROVED_REGISTRARS lists service accounts that run scripts. False positives: reused hosting addresses and undocumented automation.
Reading the results before you escalate
For a Test 1 device nobody can explain, or several devices on one build with no hardware identifier, treat the owning account as compromised, even after a password change. A row flagged for missing detail is not clean until a person reads the raw event.
A Hunt 1 hit on an MH- name, or a toolkit build with no hardware identifier, is a rogue device registration: run the response steps above. A DESKTOP- name alone is a lead until the build and hardware identifier agree. A Hunt 2 row with the registration is the whole chain. Start at the session, then work out what the attacker opened in Exchange, SharePoint and OneDrive.
A Hunt 3 hit on a Huntress IP, a Hunt 1 device, or a scripted client on someone who runs no scripts sends you to that user's device list, then to other accounts the same IP touched; Huntress saw one IP reach 60 accounts. If everything is clean, keep Test 1 and Hunt 1 as scheduled reports. That is detection engineering for an attack that installs nothing.
One next step
Today, open your Conditional Access policies and check whether the device code flow is blocked; if you have Entra ID P1 or above and nobody needs it, block it. The attacker brought a device, and the password reset did not remove it. For a wider look at the same Microsoft 365 risks, start with a free Inception Foresight M365 Assessment at inceptionsecurity.com/m365assessment.
Follow us on LinkedIn (Inception Security) and X (@inceptionsec).



