Contained isn’t clean, Part 1: why containment is only half the job

Contained isn't clean - Part 1 - The problem

Part 1 of 4 - The problem

Disclaimer and scope. The goal of this series is to demonstrate Microsoft Defender automatic attack disruption: how malicious activity in a Microsoft 365 tenant is detected and defended against automatically, and why containment must be followed by removing the footholds an attacker leaves behind. Everything shown was carried out in an isolated lab tenant built for the purpose. The techniques are well-documented adversary behaviours catalogued in MITRE ATT&CK, reproduced here only to show how a defender detects, disrupts and eradicates them. This process and the associated scripts are for simulation and defensive testing in a tenant you own and control. Do not use them against any environment you are not authorised to test. Planting these footholds requires privileged access in the first place - the controls described in this series are what stop a real attacker reaching that point, and what clean up if one does.

Introduction

Microsoft Defender can lock down a compromised account within minutes of an attack starting, with no analyst in the loop. That is a genuine step change. But stopping an attack and cleaning up after it are two different jobs, and the gap between them is where a lot of organisations get caught out.

Incident response has always separated the two: containment stops the attacker spreading, eradication removes everything they left behind, and recovery brings the business back online. Skip the middle step and the first person to re-enable the account quietly reopens the door.

This series builds that scenario end to end in a lab. The noisy endpoint route is blocked by Defender straight away, so the attacker does what a real adversary-in-the-middle attacker does - works entirely in the identity plane from a stolen session, leaves four footholds in Entra ID and Exchange Online, and gets contained. Then we prove the footholds survive containment, hunt them down, and remove them without touching anything the real user still needs. This first part sets up the problem and shows Defender’s automatic response doing its job.

How Defender responds on its own

Automatic attack disruption

Automatic attack disruption correlates signals across endpoints, identities, email and SaaS apps, identifies the assets the attacker controls, and contains them by disabling users, revoking sessions or containing devices. Microsoft states that containment actions run at a confidence level of 99% or higher, and every automatic action can be undone by the SOC.

Predictive shielding

Predictive shielding extends attack disruption by acting before the attacker uses stolen credentials. When Defender sees high-confidence signs of credential theft on a device, it can restrict the accounts likely exposed there. It is available to Defender for Endpoint P2 customers who meet the prerequisites, and Microsoft recommends the Defender for Identity sensor to enrich its data.

Gotcha: in the incident Activities tab, the Performed by column shows Attack Disruption for both attack disruption and predictive shielding actions. Filter incidents by the Predictive Shielding tag to tell them apart.

The gap: what containment leaves behind

Attackers who get in through a phished or stolen session move quickly to make sure they can get back in. These are the footholds the lab recreates, and none of them is removed by disabling the user or revoking their sessions:

Foothold MITRE ATT&CK Why containment does not remove it
Attacker-registered MFA methodT1098.005 Device RegistrationDisabling the account and revoking sessions leaves registered methods in place. Re-enable the user and the attacker can pass MFA again.
Directory role added to the userT1098.003 Additional Cloud RolesThe role assignment stays on the account and comes back into use the moment the account is enabled.
Client secret added to an appT1098.001 Additional Cloud CredentialsThe secret belongs to the app, not the user. Disabling the user does nothing to it, so the attacker keeps signing in as the app.
Hidden inbox ruleT1564.008 Email Hiding RulesThe rule lives in the mailbox and keeps running whether the user can sign in or not.

Stage 1 - The loud route is blocked

The lab first tried the obvious way in: endpoint tooling on the lab VM to dump credentials from memory. Microsoft Defender Antivirus quarantined it on sight. A Meterpreter variant, a hack-tool, a credential-injection trojan and a PowerShell offensive-tooling detection were all flagged Severe or High the moment they landed, before anything could touch LSASS.

Defender Antivirus - multiple threat families found and quarantined on the endpoint.
Defender Antivirus - multiple threat families found and quarantined on the endpoint.

That is defence in depth doing its job, and it is the point worth making: the malware-heavy route is the one your controls are best at catching. Defender correlated the detections into a single incident and drew the attack graph automatically.

The incident attack graph: the device linked to the quarantined tooling, with the threat families named.
The incident attack graph: the device linked to the quarantined tooling, with the threat families named.

It is not how a capable identity attacker operates today.

Impair Defenses (T1562)

Before the credential dump even ran, Controlled Folder Access blocked the tooling from writing to protected folders. That is the control doing its job: against unprivileged ransomware, the common case it is built for, it holds.

Getting past it is not free. Adding an allowed application or changing the mode needs local admin, and weakening or turning off a security control is itself an attack technique - T1562 Impair Defenses - and one of the behaviours Defender treats as high value. The action is loud: it writes to DeviceEvents, and tampering like this can feed attack disruption. So the first thing the attacker meets is a control that blocks them, and the only way past hands the defender more signal.

Gotcha: if you do allow an application through Controlled Folder Access, never allow an interpreter such as powershell.exe - anything that can invoke it inherits the pass. Allow specific signed binaries only.

Hunt Controlled Folder Access violations and Defender tampering:

DeviceEvents
| where Timestamp > ago(1d)
| where ActionType in ("ControlledFolderAccessViolationBlocked",
    "ControlledFolderAccessViolationAudited", "TamperingAttempt")
| project Timestamp, DeviceName, ActionType, InitiatingProcessFileName,
    FolderPath, AdditionalFields

Next in the series: Part 2 stages the attack in the lab and plants the four footholds in the identity plane.

Contained isn’t clean, Part 2: staging the attack

Contained isn't clean - Part 2 - Staging the attack

Part 2 of 4 - The lab and the footholds

In the previous part: Defender’s automatic attack disruption and predictive shielding contain a compromised account, but the footholds an attacker leaves behind are a separate problem. The obvious endpoint route was blocked by antivirus, so the attack moves to the identity plane.

The lab

Everything runs in a dedicated Contoso test tenant:

  • Victim user: a licensed Microsoft 365 E5 account (the compromised user) with its own Authenticator registered
  • Second compromised account: an over-privileged helpdesk account holding Privileged Role Administrator and Application Administrator - more privilege than a helpdesk needs, which is exactly what attackers look for
  • Victim device: an Entra joined Windows 11 VM onboarded to Defender for Endpoint, signed in as the victim user
  • Attacker: a separate browser on a different public IP, using the stolen session

Prerequisites

  • Microsoft 365 E5 or A5, or Defender for Office 365 Plan 2 plus Defender for Endpoint P2
  • Defender for Endpoint device discovery set to Standard
  • The VM’s device group set to an automation level that lets disruption act without approval
  • Mailbox auditing on, including UpdateInboxRules
  • The test user not excluded from automated response (Settings > Microsoft Defender XDR > Identity automated response)
  • Microsoft 365 app connector in Defender for Cloud Apps, with Entra ID management events, Entra ID sign-in events, Entra ID apps and Microsoft 365 activities all ticked

Gotcha: the Microsoft 365 connector can show as Connected while only Entra users and groups is ticked. In that state CloudAppEvents stays empty and the hunting queries in Part 4 return nothing. Open the connector’s Edit settings and tick the event sources before you need them - it takes a few hours for data to start flowing.

The attacker changes tack: the identity plane

An adversary-in-the-middle attack needs no endpoint malware at all. The attacker phishes the user through a proxy, captures the session token once the user has completed MFA, and replays it. From that point they are the user, in a browser, with nothing on the device for antivirus to see. Everything that follows happens in Entra ID and Exchange Online.

Where predictive shielding fits: predictive shielding acts when Defender sees high-confidence credential theft on a device, restricting the accounts likely exposed there. In this run the endpoint tooling never executed, so that signal is never raised. That is precisely why the identity-plane footholds matter - there was no noisy on-device event to trip it.

The four footholds

With the stolen session, the attacker plants persistence. Two are done as the victim, two through the compromised helpdesk account. The planting steps are described here so the lab can be reproduced; the public companion repository ships only the detection and removal tooling.

As the victim user

  • Register a second Microsoft Authenticator (or software OATH) method, so the attacker holds a valid MFA method of their own (T1098.005). In the lab this is done through the My Sign-ins page; it registers as a new method with its own id.
  • Create an inbox rule that moves mail containing “invoice” or “payment” to RSS Feeds and marks it read (T1564.008).

Gotcha: registering the method is not finished until the verification step completes. A half-finished enrolment - scanning the QR but not approving the test notification - leaves nothing recorded in Entra, even though the authenticator app shows the account.

Through the compromised helpdesk account

  • Add a directory role to the victim (T1098.003) - a role the helpdesk account can assign because it holds Privileged Role Administrator.
  • Add a client secret to an app registration (T1098.001), using its Application Administrator rights. The secret belongs to the app, so it survives anything done to the user.

Note: the privileged footholds can only be planted from the helpdesk account, not the victim. That split - a phished user plus an over-privileged second account - is what turns a single compromised mailbox into tenant-wide persistence.

Next in the series: Part 3 contains both accounts and proves the footholds survive.

Contained isn’t clean, Part 3: containment and the gap

Contained isn't clean - Part 3 - Containment and the gap

Part 3 of 4 - Containment, and what it leaves behind

In the previous part: The attacker has planted four footholds - a rogue MFA method and an inbox rule on the victim, and a directory role and an app secret through an over-privileged helpdesk account.

Stage 3 - Containment

Attack disruption may fire on the identity activity on its own; in a lab it often will not, because it needs a high-confidence correlated pattern. Either way the response is the same. If disruption fired, the user is already disabled with sessions revoked. If not, take the same actions by hand from the user page in the Defender or Entra portal: revoke sessions, then block sign-in. Do the same for the helpdesk account.

In this lab run, attack disruption did not fire on the identity activity and the DisruptionAndResponseEvents table stayed empty, which is the common lab outcome. The point stands either way, because the manual containment takes exactly the actions disruption would.

Both accounts showing Account status: Disabled after revoke-sessions and block-sign-in.
Both accounts showing Account status: Disabled after revoke-sessions and block-sign-in.

Stage 4 - The door left open

Here is the heart of it. With the accounts contained, look at the victim’s registered authentication methods. The account is disabled and its sessions are revoked, yet both methods are still there: the legitimate Microsoft Authenticator and the attacker’s own method, untouched.

The victim's authentication methods while the account is disabled - the attacker's method is still registered alongside the legitimate one.
The victim’s authentication methods while the account is disabled - the attacker’s method is still registered alongside the legitimate one.

Containment did exactly what it is meant to - it killed the sessions and blocked sign-in. And it did nothing to the footholds. The attacker’s MFA method is intact, the added role is still assigned, the app secret still works, and the inbox rule is still running. The moment the service desk re-enables the account to close the incident, the attacker walks straight back in.

Reinforcing the hunting approach: the Entra authentication methods page itself warns that hidden and temporary methods are not shown, and to use the Graph API to see them all. That is exactly why the hunt in Part 4 reads methods through Graph rather than trusting the portal view.

The lesson so far

  • Containment buys time. It does not make the account safe.
  • Every account in the incident matters, not just the first one. The helpdesk account did more damage than the phished user.
  • Re-enabling a contained account before removing the footholds hands the attacker their access back.

Next in the series: Part 4 hunts the footholds and eradicates them precisely, then restores the account safely.

Contained isn’t clean, Part 4: hunt and eradicate

Contained isn't clean - Part 4 - Hunt and eradicate

Part 4 of 4 - Finding and removing the footholds

In the previous part: The accounts are contained, but the four footholds survived. Now we find them and remove them - the eradication step that makes re-enabling safe.

Stage 5 - Hunting the footholds

Three of the four footholds are visible in the CloudAppEvents table in Advanced hunting, each under a specific ActionType confirmed in the lab. Set the time window to match the incident.

Roles added (T1098.003)

CloudAppEvents
| where Timestamp > ago(1d)
| where ActionType == "Add member to role."
| project Timestamp, ActionType, AccountDisplayName, IPAddress, CountryCode, RawEventData
| order by Timestamp desc

App secrets added (T1098.001)

The ActionType Microsoft writes for this contains a dash, so match on the distinctive text rather than the whole string:

CloudAppEvents
| where Timestamp > ago(1d)
| where ActionType has "Certificates and secrets management"
| project Timestamp, ActionType, AccountDisplayName, IPAddress, RawEventData
| order by Timestamp desc

Inbox rules created (T1564.008)

CloudAppEvents
| where Timestamp > ago(1d)
| where ActionType in ("New-InboxRule", "Set-InboxRule", "UpdateInboxRules")
| project Timestamp, ActionType, AccountDisplayName, IPAddress, CountryCode, RawEventData
| order by Timestamp desc

All three in one query

CloudAppEvents
| where Timestamp > ago(1d)
| where ActionType in ("Add member to role.", "New-InboxRule")
    or ActionType has "Certificates and secrets management"
| project Timestamp, ActionType, AccountDisplayName, IPAddress, CountryCode
| order by Timestamp desc
The combined query returning the role, secret and inbox-rule events, with the attacker IP against the inbox rule.
The combined query returning the role, secret and inbox-rule events, with the attacker IP against the inbox rule.

Gotcha 1 - the MFA method is not here. The attacker-registered authentication method does not appear in CloudAppEvents at all; self-service registration through the My Sign-ins page is not written to that table. This is why the companion hunt reads authentication methods directly through Microsoft Graph - KQL alone would miss the MFA foothold.

Gotcha 2 - the IP is not always populated. In the lab the mailbox action (New-InboxRule) carried the attacker IP and country, but the Entra directory actions (the role and the secret) came through with an empty IPAddress. Do not rely on IP alone to scope these; correlate on the acting account and the timestamps instead.

The Graph hunt

Because the MFA method is invisible to KQL, the companion hunt script reads authentication methods, directory roles, app secrets and inbox rules straight from Microsoft Graph and Exchange Online. It surfaces the hidden and temporary methods the portal omits, and it is read-only - run it to find the footholds, then again after removal to confirm the account is clean.

Stage 6 - Removing the footholds

The aim is precision: remove what the attacker added and nothing else. Each foothold is removed by its own identifier - the authentication method id, the role assignment id, the secret key id, the inbox-rule name - so the user’s legitimate methods and settings are left untouched.

  • MFA method: delete only the method the attacker registered. Removing it by id leaves the user’s own Authenticator in place; a blanket “require re-register MFA” would wipe the legitimate method too.
  • Role: remove the added assignment, then review why the helpdesk account could assign it in the first place.
  • App secret: delete the secret by its key id, then review the app’s sign-in logs for anything it was used for.
  • Inbox rule: remove the rule, and check for forwarding set on the mailbox.

Gotcha - verify, do not trust the message. Some Graph removal cmdlets return an error that does not stop the script, so a naive script can report success when nothing was removed. The companion removal script checks the method’s real type, uses explicit error handling, and reports success only when the call actually succeeds. Always re-run the hunt afterwards.

After removal: only the user's own Authenticator remains, the attacker's method gone.
After removal: only the user’s own Authenticator remains, the attacker’s method gone.

Stage 7 - Verify and recover

  1. Re-run the hunt and confirm nothing remains - one legitimate method, no roles, no secrets, no inbox rules.
  2. Reset the password and revoke sessions once more, for the victim and the helpdesk account.
  3. Re-enable the accounts - now safe, because the footholds are gone.
  4. Confirm the attacker can no longer sign in.

Takeaways

  • Containment buys time; eradication makes the account safe. Build a post-containment checklist for MFA methods, role assignments, app credentials and mailbox rules, and run it before anyone re-enables an account.
  • Remove what the attacker added, not everything. Wiping a user’s own MFA creates a support call and a fresh social-engineering window.
  • Not every foothold is in one table. The role, secret and inbox rule are in CloudAppEvents; the MFA method is only visible through Graph.
  • Keep the hunt and removal ready as scripts, so the checklist takes minutes rather than hours.

Companion scripts

The read-only hunt and the precise removal script are on GitHub at cloud-secure-ai/attack-disruption-footholds-lab, with a README and the MITRE ATT&CK mapping. The repository is deliberately defensive: the script that plants the footholds is not included, because planting requires privileged access in any case and the published tooling is limited to detection and removal.

References

Where do we start with data classification? Part 1: Let the data tell you

Part 1 - Let the data tell you

“Where do we start?” It is the question I get asked in nearly every Microsoft Purview engagement. Purview has a huge toolset - sensitivity labels, data loss prevention, insider risk, retention, Data Security Posture Management - but none of it works until the organisation has told Purview what it needs to protect. Purview does not know that a design specification is Contoso’s crown jewels. Contoso has to tell it.

That is classification, and it is where most projects stall. Workshops ask the business to list its sensitive data, the business lists what it can remember, and the result is a handful of sensitive information types (SITs) that miss most of what matters.

This series takes a different route. Instead of asking people what they think is sensitive, we ask the data. I use a Microsoft CDX demo tenant, Microsoft Security Copilot and the Data Security Posture Agent (preview) to discover what Contoso actually holds, and then turn those findings into classifiers. The series runs in five short parts:

All data in this series is fictional and lives in a Microsoft CDX demo tenant. Every script and template is published on GitHub at https://github.com/cloud-secure-ai/Purview-data-classification

A word you will see a lot in this series: gotcha, short for “got you”. A gotcha is something to watch out for that is not documented on learn.microsoft.com or anywhere else, and that you usually only find by hitting it.

Start with what Purview already sees

Before building anything, look at what Purview has already found. Out of the box, Purview scans Microsoft 365 content against hundreds of built-in SITs and Microsoft’s pre-trained classifiers. In the Contoso tenant the Purview home page reported 1,866 items containing sensitive information. The top three types were All Full Names (301 items), a custom SIT called Proseware Merger (152 items) and EU Tax Identification Number (130 items).

The second most common sensitive type in this tenant is not a regulatory identifier. It is a custom type someone built to find a confidential merger. That is intellectual property, and built-in rules will never find it on their own.

The unified Classifiers page

Microsoft is rolling out a unified Classifiers page (preview) under Information Protection > Classifiers. It brings SITs, exact data match, trainable classifiers and document fingerprinting into one list, and runs alongside the classic pages.

The unified Classifiers page in Microsoft Purview (preview)
The unified Classifiers page in Microsoft Purview (preview)

The most useful change is two columns side by side: Classified items and Affected policies. Filter to trainable classifiers and custom SITs and the gap is obvious. Finance matched 134 items, HR 52. The custom Proseware Merger and Mark 8 Project types matched 152 and 101 items. Every one shows 0 affected policies.

Sensitive content found, no policy using it
Sensitive content found, no policy using it

That single view is a ready-made gap analysis: Purview has found the data and nothing is protecting it. It is also the limit of what you get for free. These columns only count what an existing classifier already recognises. Anything Contoso has never defined does not appear at all.

Why starting from SITs is backwards

Most guidance on the Posture Agent shows it searching for a SIT you already have: “find files containing credit card numbers that are shared externally”. That is useful for remediation, but it does not answer “where do we start?”. If you already knew your SITs, you would not be asking.

I learned this the hard way in the lab. My first prompt asked the agent to find unlabelled Mark 8 confidential data. It ran successfully and found 0 items. The prompt was turned into a literal keyword query, limited to the default 30-day window, over content that did not use those words. Searching for what you think exists finds nothing new.

The real value is the other way round. Describe the kind of content that would hurt the organisation if it leaked, let the agent find it by meaning, and then look for the patterns that repeat. Those patterns are your candidate SITs.

The Data Security Posture Agent (preview)

The Posture Agent is a Security Copilot agent in Microsoft Purview. It has two capabilities in two places:

  • Data discovery, in DSPM > Discover > Asset explorer > Posture Agent tab. You describe what you are looking for in natural language, choose the people, groups or sites to search, and the agent analyses files, emails and messages for that content.
  • Credential scanning, in Data Security Investigations > Posture agent. It scans selected locations for exposed passwords, keys and tokens and tracks each scan on a task board.
Data discovery lives in the new unified DSPM, under Asset explorer
Data discovery lives in the new unified DSPM, under Asset explorer

Note the banner: DSPM (classic) and DSPM for AI (classic) retire on 30 November 2026, and the agent only lives in the new unified DSPM. If you have been waiting to move, this is the push.

Things worth knowing before you plan around it:

  • It finds and reports. It does not act on its own. You can label selected files from the results, export a report or schedule the prompt to run daily, weekly or monthly.
  • Only two prompts can run at once, and a run may be capped at 5 GB or 10,000 items, returning the top 1,000 matches. It is a fast, targeted discovery tool, not a full-tenant inventory.
  • The default time range is the last 30 days. Ask for a wider range in the prompt if your content is older.
  • It needs Security Copilot capacity, and every run consumes it. Part 2 covers what that took and cost.

The agent is a non-human identity

Expand Permissions and roles in the setup dialogue and you will see that starting the agent creates its own identity, with permission to access, read and see metadata for documents and content.

The Posture Agent runs under its own identity with read access to content
The Posture Agent runs under its own identity with read access to content

That is a non-human identity with broad read access to your most sensitive data. Treat it like one: know who deployed it, review it with your other agent identities and make sure its activity is in your audit process. In the lab, the credential scanning task card even reads “Started by Data security posture agent” - the agent, not the admin, is the actor.

Role design matters too. Compliance Administrator and Security Reader can run the agent and see summaries. Viewing matched snippets or opening matched files needs content-level roles such as Data Classification Content Viewer or Purview Content Analyst. Our audit log showed exactly that split: the admin was granted the compliance roles and blocked on the content roles.

What we found

Once the prerequisites were in place (Part 2), one discovery-style prompt over a single user’s mailbox and OneDrive returned 20 items, none of them labelled:

  • A document named CR-227 Product Overview - a reference number format that no SIT covered.
  • Project Tailspin and Customer Purchasing Data for Project 9 - internal codenames that no SIT covered.
  • Contoso Patent Template and an R&D expense report - content defined by what it is rather than a pattern, which is a job for a trainable classifier.
  • An annual financial report draft, already covered by the built-in Finance classifier.
  • Noise: Power BI visual definitions, Outlook task reminders and meeting titles.

None of the useful findings were on anyone’s list. That is the point. Part 3 shows how each one becomes a classifier, and how to deal with the noise.

So where do we start?

  1. Look at what Purview already sees. The unified Classifiers page shows classified items against affected policies. That is your first gap list.
  2. Do not start by asking the agent about the SITs you already have. Ask it about the kind of content that would hurt you if it leaked.
  3. Treat the agent as a non-human identity from day one.
  4. Get the prerequisites right before you pay for capacity. That is Part 2.

References