TL;DR: Why a Password Reset Doesn't Evict an Attacker
When a user falls for an adversary-in-the-middle (AiTM) phishing page or clicks through a malicious OAuth consent prompt, the standard helpdesk response is to reset their password and move on.
In Microsoft 365, a password reset alone leaves four persistence layers wide open:
- Existing refresh tokens stay valid: Unless you explicitly revoke sessions (
Revoke-MgUserSignInSession), stolen refresh tokens and session cookies can keep minting new access tokens for up to 90 days—even after a password change. - OAuth apps bypass passwords and MFA completely: A malicious multi-tenant app granted
Mail.ReadWrite,Mail.Send, andoffline_accesskeeps reading and sending mail via Microsoft Graph without ever touching the user's password again. - Hidden inbox rules and forwarding survive quietly: Attackers hide rules with
PR_RULE_MSG_PROVIDERtampering (invisible to Outlook and standardGet-InboxRule), funneling replies toRSS FeedsorConversation Historywhile forwarding invoices externally. - Cloud logs alone can miss token replay: Comparing Entra sign-in
deviceIdvalues against the user's managed Windows laptop (dsregcmd /statusandMicrosoft-Windows-AAD/Operational) quickly separates real endpoint token refreshes from off-device cookie replay.
To audit all four layers in one read-only pass, I wrote Invoke-M365IdentityPersistenceAudit.ps1 using raw Microsoft Graph REST calls (Invoke-MgGraphRequest), optional Exchange Online cmdlets, and local Windows WAM/PRT telemetry.
1. Persistence Map: Where Attackers Hide After Initial Access
Once an attacker lands a valid session (via stolen credentials, AiTM reverse proxy, or device-code phishing), they usually plant persistence across identity, app consent, and mail flow before sending a single BEC email:
[ Compromised Sign-In (AiTM / Device Code / Creds) ]
|
+--> 1. Identity Layer (Entra ID)
| * Unrevoked Refresh Token (signInSessionsValidFrom < lastPasswordChange)
| * Rogue MFA Method (/authentication/methods) or Temporary Access Pass
| * Unmanaged Entra-Registered Device (/registeredDevices)
|
+--> 2. App Consent Layer (OAuth 2.0)
| * Illicit Delegated Grant (oauth2PermissionGrants + offline_access)
| * High-Risk Scopes: Mail.ReadWrite, Mail.Send, Files.ReadWrite.All
|
+--> 3. Mail Flow Layer (Exchange Online)
| * Hidden Inbox Rule (Get-InboxRule -IncludeHidden -> Delete / RSS Feeds)
| * Mailbox Forwarding (ForwardingSmtpAddress) / FullAccess Delegates
| * Tenant Transport Rule (BlindCopyTo / RedirectMessageTo)
|
+--> 4. Cloud vs. Endpoint Check
* Entra /auditLogs/signIns (deviceId, IP, clientAppUsed)
* Local Windows dsregcmd /status + Microsoft-Windows-AAD/Operational (1097/1098/1104)
2. Auditing Refresh Token Gaps, Rogue MFA, and Registered Devices
Entra ID tracks a user's session revocation boundary in two timestamps on the user object: signInSessionsValidFromDateTime and refreshTokensValidFromDateTime. Every refresh token carries an issued-at timestamp (iat); if iat is older than that boundary, Entra rejects it.
Here is the classic IR miss: someone resets the user's password in the admin portal without clicking Revoke sessions. On Graph, lastPasswordChangeDateTime jumps forward while signInSessionsValidFromDateTime stays stuck weeks or months in the past.
Get-EntraIdentityAndTokenState pulls those exact fields from /v1.0/users/{upn}, flags any reset where lastPasswordChangeDateTime is newer than signInSessionsValidFromDateTime by more than 5 minutes, and checks two other common persistence spots:
- Recently added MFA methods (
/authentication/methods): Flags any Authenticator app, phone/SMS, FIDO2 key, software OATH token, or active Temporary Access Pass created inside-LookbackDays. - Unmanaged device registrations (
/registeredDevices): Flags recently addedWorkplace(BYOD) or unmanaged devices that attackers register to satisfy loose device-state rules.
3. Catching Illicit OAuth Consent Grants (Persistence Without Passwords)
OAuth consent phishing is brutal because it looks legitimate to users and never requires stealing a password. If a user approves a third-party app requesting Mail.ReadWrite, Mail.Send, and offline_access, Entra issues the app its own refresh token.
Standard portal reviews often miss these grants because they live under per-user oauth2PermissionGrants rather than Exchange mailbox logs. Get-EntraOAuthPersistenceState pulls every user-scoped grant (plus tenant-wide AllPrincipals grants with -IncludeTenantWideGrants) and resolves each clientId via /v1.0/servicePrincipals/{id}.
Each grant is scored using three concrete signals:
- Publisher trust: Distinguishes Microsoft first-party tenant IDs (
f8cdef31-a31e-4b4a-93e4-5f571e91255aand72f988bf-86f1-41af-91ab-2d7cd011db47) and verified publishers from unverified multi-tenant apps. - High-risk scopes: Escalates
Mail.ReadWrite,Mail.Send,MailboxSettings.ReadWrite,EWS.AccessAsUser.All,Files.ReadWrite.All, andDirectory.ReadWrite.AllasCritical, and read/legacy scopes (Mail.Read,IMAP.AccessAsUser.All,SMTP.Send) asWarning. offline_accesspairing: Explicitly calls out non-Microsoft apps combining sensitive scopes withoffline_access, since those refresh tokens outlive password changes until the grant is deleted.
4. Surfacing Hidden Inbox Rules, Forwarding, and Delegates in Exchange Online
Once inside a mailbox, attackers usually create rules to hide security alerts, bounce-backs, or victim replies before launching invoice fraud. A well-known trick modifies the rule's MAPI PR_RULE_MSG_PROVIDER property so Outlook and a plain Get-InboxRule call won't display it at all.
When you run Connect-ExchangeOnline in the same session, Get-ExchangeMailboxPersistenceState compares Get-InboxRule against Get-InboxRule -IncludeHidden and checks four mailbox persistence paths:
- Hidden or evasive inbox rules: Flags any rule returned only by
-IncludeHidden, rules forwarding or redirecting mail, rules settingDeleteMessageorMarkAsRead, rules moving messages into low-visibility folders (RSS Feeds,Conversation History,Archive,Deleted Items), and rules matching BEC or security keywords (invoice,wire,bank,password,mfa,security). - Mailbox-level forwarding: Checks
Get-MailboxforForwardingSmtpAddressandForwardingAddress(which silently copy mail outside the inbox rule engine). - Non-default delegates: Filters
Get-MailboxPermissionandGet-RecipientPermissionto surface unauthorizedFullAccessandSendAstrustees. - Tenant transport rules (
-IncludeTenantTransportRules): AuditsGet-TransportRulefor org-wideBlindCopyTo,RedirectMessageTo, orDeleteMessagerules planted by a compromised admin.
5. Correlating Entra Sign-In Logs Against Windows Endpoint PRT Telemetry
When reviewing /v1.0/auditLogs/signIns during an AiTM investigation, the hardest question is often: was this token request actually from the user's laptop, or from an attacker replaying their session cookie on another machine?
Managed Windows 10/11 endpoints maintain a Primary Refresh Token (PRT) via the Web Account Manager (WAM) and log every token acquisition locally. Passing -CorrelateLocalEndpoint (or -AadEvtxPath for an offline exported .evtx) cross-checks both sides:
- Cloud side (
/v1.0/auditLogs/signIns): Flags successful legacy authentication (IMAP4,POP3,SMTP,Exchange ActiveSync), multi-country sign-ins, unmanaged device successes, and post-reset sign-ins occurring while a token revocation gap existed. (Requires Entra ID P1/P2 andAuditLog.Read.All; the script degrades gracefully if unlicensed.) - Windows endpoint side (
dsregcmd /status+Microsoft-Windows-AAD/Operational): Reads the machine's EntraDeviceId,AzureAdPrtstate, and PRT update/expiry timestamps alongside AAD Operational Event IDs1097,1098, and1104. - Mismatch flagging: Compares every successful cloud sign-in's
deviceDetail.deviceIdagainst the endpoint's localDeviceId, isolating unmatched IPs and apps that came from off-device sessions.
6. Running the Auditor & Containment Order of Operations
Connect with least-privilege read-only Graph scopes (and optionally Exchange Online), then run the auditor to get prioritized findings or JSON for your IR ticket:
# 1. Connect read-only to Microsoft Graph and Exchange Online
Connect-MgGraph -Scopes User.Read.All,UserAuthenticationMethod.Read.All,DelegatedPermissionGrant.Read.All,Application.Read.All,AuditLog.Read.All,Directory.Read.All -NoWelcome
Connect-ExchangeOnline -ShowBanner:$false
# 2. Run the full persistence audit and inspect prioritized findings
$Audit = .\Invoke-M365IdentityPersistenceAudit.ps1 -UserPrincipalName "user@contoso.com" -LookbackDays 14
$Audit.Findings | Format-Table Severity, Category, Finding, Recommendation -Wrap
# 3. Correlate cloud sign-ins with the local Windows endpoint and export JSON
.\Invoke-M365IdentityPersistenceAudit.ps1 -UserPrincipalName "user@contoso.com" -CorrelateLocalEndpoint -IncludeTenantWideGrants -Json
When you confirm a compromise, order of operations matters so the attacker can't re-enroll while you clean up:
- 1. Block sign-in and revoke sessions first: Disable the account (or block sign-in) and run
Revoke-MgUserSignInSessionso active refresh tokens and PRTs stop minting access tokens. - 2. Strip persistence before resetting the password: Remove rogue MFA methods, disable unknown Entra-registered devices, delete illicit OAuth grants (
Remove-MgOauth2PermissionGrant), and remove hidden inbox rules or forwarding. - 3. Reset the password and re-verify: Issue a strong password reset (and require MFA re-registration if needed), then re-run
Invoke-M365IdentityPersistenceAudit.ps1to verifyHealthStatusis clean before re-enabling the user.
The full script and permission reference are in the M365-EntraID-IR folder of Windows-Scripts-Tools on GitHub.