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

Building a Defender Security Dashboard with Workbooks: the series

Building a Defender Security Dashboard with Workbooks: the series

One page that answers: how healthy is our security posture?

Ask the Contoso security team how healthy its security posture is, and the answer takes a tour of the portal. The device inventory, filtered by hand. The onboarding page. The security recommendations. The incidents queue. The attack surface reduction report. Every page answers part of the question, none of them answers all of it, and a manager asking for a weekly view gets a set of screenshots.

This series builds the alternative: a single page in the Microsoft Defender portal that answers the whole question, keeps itself up to date, and needs nothing extra installed to make it work.

The finished dashboard - sensor health from the lab tenant
The finished dashboard - sensor health from the lab tenant

Who this series is for

The series is written for two kinds of reader, and each part works for both.

  • If you lead or manage security, read this guide and the In plain terms box and Key takeaways in each part. They explain what each section of the dashboard tells you and what good looks like - no code required.
  • If you run Defender day to day, each part gives you the queries, the settings and real screenshots to build the dashboard yourself - or import the finished version from GitHub in a few minutes.

What the dashboard shows

PartSectionQuestion it answers
1Device healthAre all our devices reporting in, and are the servers that control our identities covered?
2Protection controlsAre antivirus, tamper protection, attack surface reduction rules, BitLocker and the firewall actually switched on?
3Alerts and attack surface reductionWhat is raising alerts, and which attack-blocking rules are ready to move from test mode to blocking?

Each part adds one section to the same dashboard. Together they answer the question a manager actually asks: are we watching every device, are the protections on, and what is happening right now?

The control compliance grid from Part 2 - antivirus green, attack surface reduction rules red
The control compliance grid from Part 2 - antivirus green, attack surface reduction rules red

The jargon, in one line each

TermWhat it means
Microsoft Defender portalMicrosoft’s security console (security.microsoft.com), where alerts, devices and investigations live
WorkbookA dashboard page inside the portal, built from charts and tables that update themselves
Advanced huntingThe portal’s search engine over the last 30 days of security data
KQLKusto Query Language - the language advanced hunting uses to ask questions of that data
SensorThe part of Defender for Endpoint on each device that reports what happens on it
Tier 0 serversThe few servers that control identity - domain controllers, AD CS, AD FS and Entra Connect. Compromise one and an attacker can reach everything
Tamper protectionA setting that stops anyone, including an attacker, switching Defender off
EDREndpoint detection and response - Defender’s ability to spot an attack in progress and act on it
ASR rulesAttack surface reduction rules - switches that block common attack techniques, such as an Office document launching a program
Defender Vulnerability ManagementThe part of Defender that checks every device’s settings against Microsoft’s recommended configuration

Why a workbook in the Defender portal

  • It reads advanced hunting directly. Every table Contoso already uses for hunting - device, vulnerability management, alert and event data - can drive a section. There is no data export, no Log Analytics workspace and no Azure resource to build first.
  • It is live. Each section runs its query whenever the workbook opens or refreshes, and auto refresh can rerun everything on a schedule, from every five minutes to once a day.
  • It respects each viewer’s access. A viewer sees only the data their own permissions allow, so the same workbook works for the central security team and for a regional team limited to its own devices.
  • It is shareable and portable. Workbooks are saved for the whole organisation, and the dashboard exports as one file that imports into another tenant in seconds.

Live data and history

Device, alert and event data is current to within minutes. The protection control sections read Defender Vulnerability Management assessments, which Defender updates on its own schedule rather than continuously. Advanced hunting keeps 30 days of data, so the dashboard shows the current state and the last month - which is exactly what a weekly review needs.

An example, not the limit

The three sections in this series are an example of what a Defender workbook can do, not a boundary. Any table in the advanced hunting schema can become a section, so the same approach extends well beyond device health and alerts. A few directions Contoso could take next:

Use caseAdvanced hunting tableWhat it could show
Sensitive file activity on devicesDeviceFileEventsFiles with a sensitivity label that were created, modified, renamed or copied, by label and by device
Purview data security signalsDataSecurityEvents (preview)Activity matched to sensitive information types and DLP policies, shared from Insider Risk Management
Generative AI app usageCloudAppEvents, DeviceNetworkEventsWhich users and devices use generative AI apps and services, and how often
Local AI agentsAgentsInfoAI agents discovered on onboarded devices, with their versions
Sign-in and email riskIdentityLogonEvents, EmailEventsFailed sign-ins on Tier 0 accounts, and phishing delivered or blocked

Each use case follows the same pattern as the sections in this series: write the query in advanced hunting, check the results, then add it to the workbook as a new section. Some tables depend on other products or settings - DataSecurityEvents, for example, is populated only when Insider Risk Management shares its alerts with Defender - so confirm a table returns data in your own tenant first.

Where the dashboard lives

The finished dashboard sits in the Defender portal under Workbooks (security.microsoft.com/sentinel/workbooks), alongside Microsoft’s example workbooks. Part 1 shows how to create it, save it and open it again.

What you need

  • Workbooks in the Defender portal. Available to tenants using Microsoft Sentinel in the Defender portal, and to tenants on the Integrated Security Operations Center (ISOC) preview - Microsoft Defender Suite, Microsoft 365 E5 or E7 without an active Sentinel workspace.
  • To build it: the Workbooks Unified RBAC permission with Manage access, or the Security Administrator role.
  • To view it: the Workbooks permission with Reader access, or the Security Reader role.
  • Data: devices onboarded to Defender for Endpoint, and Defender Vulnerability Management for the Part 2 controls.

How the series works

Every query is shown in full and explained in the post that uses it. Every screenshot comes from a real lab tenant, so you will see what the dashboard looks like with real gaps in it - including a device that has stopped reporting and a set of attack surface reduction rules that were never switched on.

If you would rather start with the finished product, the companion repository has the complete workbook as a single file, ready to import, together with every query as a .kql file.

GitHub: github.com/cloud-secure-ai/Building-a-Defender-Security-Dashboard

The series


References

Seรกn O’Farrell | cloud-secure.ai