After a business email compromise, attackers commonly leave two kinds of persistence in the mailbox: inbox rules that forward, redirect or hide messages, and mailbox (SMTP) forwarding to an external address. Find both in Exchange Online PowerShell with Get-InboxRule -Mailbox <user> -IncludeHidden and Get-Mailbox -Identity <user> | Format-List Forwarding*Address,DeliverTo*, remove them with Remove-InboxRule and Set-Mailbox, and then set Automatic forwarding rules to Off - Forwarding is disabled in the outbound spam policy so any rule you missed can't send mail outside the organization. Do this after the account is disabled or its password is reset and its sessions are revoked, or the attacker can simply recreate the rules.
Who this is for and what you will have
This guide is for Exchange Online and security administrators cleaning up after a phishing or password-spray compromise of one or more mailboxes. It follows Microsoft's compromised-account response order and adds the inspection detail you need for rules. At the end you will have:
- The attacker's access cut off: account disabled or password reset, sessions revoked.
- Every inbox rule, hidden or not, reviewed and the malicious ones removed.
- Mailbox forwarding, delegate access and Send As permissions checked.
- A tenant-wide sweep for the same rules in other mailboxes.
- External automatic forwarding blocked by policy, with alerts watching for new attempts.
How attackers use rules and forwarding
Common signs
Microsoft lists these symptoms of a compromised mailbox:
- Rules that automatically forward email to unknown addresses.
- Rules that move messages to Notes, Junk Email or RSS Subscriptions, where the user won't look.
- Suspicious messages in Sent Items or Deleted Items.
- Recently added external email forwarding.
- The mailbox blocked from sending email.
- Unexpected changes to the user's contact details in the global address list, or to their signature.
In a payment-fraud scenario, for example, a rule that matches words such as "invoice" or "payment", or one correspondent, and moves those messages out of the inbox means the user never sees the replies while the attacker continues the conversation from their mailbox.
Where forwarding can be configured
| Mechanism | Who can set it | Where to look |
|---|---|---|
| Inbox rule with Forward, Redirect or Forward as attachment | The user, or anyone signed in as the user | Get-InboxRule -IncludeHidden |
| Mailbox forwarding (SMTP forwarding) | An admin | Get-Mailbox properties ForwardingAddress, ForwardingSmtpAddress, DeliverToMailboxAndForward |
| Mail flow rule (transport rule) | An Exchange admin | Get-TransportRule; the Auto forwarded messages report shows the rule ID |
If both ForwardingAddress and ForwardingSmtpAddress are set, mail is forwarded only to ForwardingAddress. A nonblank ForwardingSmtpAddress usually means forwarding to an external address.
Prerequisites
- Roles. Organization Management or Security Administrator in Exchange Online for policy changes; recipient management permissions for mailbox changes.
Get-InboxRuledoesn't work for the View-Only Organization Management role group or the Global Reader role, so a read-only account can't do this review. - Modules. The Exchange Online PowerShell module and the Microsoft Graph PowerShell SDK (
Install-Module -Name Microsoft.Graph -Scope CurrentUser). - The audit trail first. Before you delete anything, export the evidence. Rule creation is logged as
New-InboxRuleandSet-InboxRule(Outlook on the web and PowerShell) orUpdateInboxRules(Outlook desktop). See searching the Microsoft 365 audit log for the queries.
Step 1: Contain the account
Rules keep working after a password reset, and existing tokens keep working until you revoke them. Contain the account before you clean the mailbox.
Connect-MgGraph -Scopes "User.ReadWrite.All","User.RevokeSessions.All"
$user = Get-MgUser -Search UserPrincipalName:'jason@contoso.com' -ConsistencyLevel Eventual
# Disable sign-in for the duration of the investigation
Update-MgUser -UserId $user.Id -AccountEnabled $false
# Invalidate refresh tokens and active sessions
Revoke-MgUserSignInSession -UserId jason@contoso.comIf you can't disable the account, reset the password instead. Don't send the new password by email, because the attacker may still be reading the mailbox. For accounts synchronised from Active Directory, reset the password in Active Directory twice. App passwords aren't revoked by a password reset, so have the user delete and recreate them.
While the account is disabled, also review:
- MFA methods: remove any method the user didn't register.
- Application consents: review the applications the user consented to and remove and revoke any that shouldn't be allowed.
- Admin roles: remove any role assignment that shouldn't be there.
Step 2: Inspect the mailbox's inbox rules
Connect to Exchange Online and list every rule, including hidden ones:
Connect-ExchangeOnline -UserPrincipalName admin@contoso.com
Get-InboxRule -Mailbox jason@contoso.com -IncludeHidden |
Format-List Name,Enabled,Priority,RedirectTo,ForwardTo,ForwardAsAttachmentTo,IdentityWhat each property means:
RedirectTo: a nonblank value redirects messages; they aren't delivered to the mailbox.ForwardTo: messages are forwarded to the listed recipients.ForwardAsAttachmentTo: messages are forwarded as attachments.Identity: the unique rule identity, in the formalias\16752869479666417665. Use this rather than the name, because a malicious rule can have a blank, duplicate or meaningless name.
To see every condition and action of a single rule, including the folder it moves mail to and the words it matches, use the identity:
Get-InboxRule -Identity "jason\10210541742734704641" -IncludeHidden | Format-ListTreat a rule as suspicious when any of these apply:
- It forwards or redirects to an address the user doesn't recognise, especially an external one.
- It moves mail to RSS Subscriptions, Notes or Junk Email, or deletes it.
- It matches financial words, a specific supplier, or the user's own manager.
- It marks messages as read and moves them, so nothing appears unread.
- Its name is blank, a punctuation mark or meaningless.
- It starts an application or references an
.exe,.zipor URL. That is the older Outlook rules injection attack, which current Outlook clients block by default.
Before you change anything, save the full rule list as evidence:
Get-InboxRule -Mailbox jason@contoso.com -IncludeHidden |
Select-Object * | Export-Csv C:\IR\jason-inboxrules.csv -NoTypeInformationStep 3: Remove the malicious rules
Disable a rule if you want to keep it for analysis, or remove it outright:
# Stop it from processing mail but keep it
Disable-InboxRule -Mailbox jason@contoso.com -Identity "jason\10210541742734704641"
# Remove it
Remove-InboxRule -Mailbox jason@contoso.com -Identity "jason\10210541742734704641"Be aware of one side effect: when you create, modify, remove, enable or disable an inbox rule in Exchange PowerShell, any client-side rules created by Outlook in that mailbox are removed. Remove-InboxRule shows a confirmation prompt when the mailbox has Outlook-created rules; -Force hides it. Record the user's legitimate rules in Step 2 so they can be recreated.
If the user has no legitimate rules, or you can't tell which are legitimate, removing every rule is the faster and safer option:
Get-InboxRule -Mailbox jason@contoso.com | Remove-InboxRuleStep 4: Check mailbox forwarding, delegates and Send As
Mailbox forwarding is separate from inbox rules:
Get-Mailbox -Identity jason@contoso.com | Format-List Forwarding*Address,DeliverTo*DeliverToMailboxAndForward set to True keeps a copy in the mailbox and forwards one; False forwards only. Both forwarding properties default to blank ($null), which means no forwarding. To clear them:
Set-Mailbox -Identity jason@contoso.com -ForwardingSmtpAddress $null -ForwardingAddress $null -DeliverToMailboxAndForward $falseIn the Exchange admin center the same setting is under Recipients > Mailboxes > select the mailbox > Mailbox > Email forwarding > Manage email forwarding, where you turn off Forward all emails sent to this mailbox.
An attacker with admin rights, or one who added themselves as a delegate, may also have granted access to another account. Review permissions on the mailbox:
# Full Access (the NT AUTHORITY\SELF entry is the owner and is expected)
Get-MailboxPermission -Identity jason@contoso.com | Where-Object { $_.IsInherited -eq $false }
# Send As
Get-RecipientPermission -Identity jason@contoso.comRemove any entry you can't account for. Then check that the user isn't listed on the Restricted entities page, which happens when a compromised account sends spam.
Step 5: Sweep the rest of the tenant
A phishing campaign can compromise more than one mailbox. Run the same checks across every user and shared mailbox and review the output, rather than relying on reports from users:
$mailboxes = Get-Mailbox -ResultSize Unlimited -RecipientTypeDetails UserMailbox,SharedMailbox
$rules = foreach ($mbx in $mailboxes) {
Get-InboxRule -Mailbox $mbx.UserPrincipalName -IncludeHidden -ErrorAction SilentlyContinue |
Where-Object { $_.ForwardTo -or $_.ForwardAsAttachmentTo -or $_.RedirectTo } |
Select-Object @{n='Mailbox';e={$mbx.UserPrincipalName}},Name,Enabled,ForwardTo,ForwardAsAttachmentTo,RedirectTo,Identity
}
$rules | Export-Csv C:\IR\forwarding-rules-all.csv -NoTypeInformation
$mailboxes | Where-Object { $_.ForwardingSmtpAddress -or $_.ForwardingAddress } |
Select-Object UserPrincipalName,ForwardingAddress,ForwardingSmtpAddress,DeliverToMailboxAndForward |
Export-Csv C:\IR\mailbox-forwarding-all.csv -NoTypeInformationThe loop above only flags forwarding; rules that only move or delete mail need a second pass, filtered on the target folder or the action you found in Step 2.
Two more places to look:
- Auto forwarded messages report. In the Exchange admin center at
https://admin.exchange.microsoft.com, expand Reports and select Mail flow, then open Auto forwarded messages. It shows who forwarded to external domains, the forwarding type (Mail flow rules, Inbox rules or SMTP forwarding), the recipient domain and the first forward date. The summary covers up to the last 90 days. - Mail flow rules. If the report shows a rule ID, run
Get-TransportRule -Identity <RuleID>and check who created or changed it in the audit log.
Microsoft's older Get-AllTenantRulesAndForms.ps1 script dumps rules and custom forms for every mailbox, but the repository is archived and lines 154 to 158 use a connection method that no longer works. Remove those lines and connect first if you use it.
Step 6: Block external automatic forwarding
The outbound spam policy controls automatic forwarding to external recipients for both inbox rules and mailbox forwarding. The Automatic forwarding rules setting has three values:
| Portal value | PowerShell AutoForwardingMode | Effect |
|---|---|---|
| Automatic - System-controlled | Automatic | Default. Since 2021 equivalent to Off for new organizations and for existing ones that weren't actively using it; can remain equivalent to On in organizations that were already using it |
| On - Forwarding is enabled | On | External auto-forwarding isn't restricted by the policy |
| Off - Forwarding is disabled | Off | External auto-forwarding is blocked and the sender gets an NDR |
Because Automatic behaves differently between organizations, Microsoft recommends setting On or Off explicitly. To turn it off for everyone:
Set-HostedOutboundSpamFilterPolicy -Identity Default -AutoForwardingMode OffIn the Defender portal, go to Email & collaboration > Policies & rules > Threat policies > Anti-spam, open Anti-spam outbound policy (Default), edit Protection settings and set Automatic forwarding rules. If a few mailboxes have a business need to forward externally, create a custom outbound policy for just those users with forwarding On:
New-HostedOutboundSpamFilterPolicy -Name "Allow external forwarding"
Set-HostedOutboundSpamFilterPolicy -Identity "Allow external forwarding" -AutoForwardingMode On
New-HostedOutboundSpamFilterRule -Name "Allow external forwarding" -HostedOutboundSpamFilterPolicy "Allow external forwarding" -FromMemberOf "External Forwarding Allowed"When one control allows forwarding and another blocks it, the block typically wins. Remote domains and mail flow rules can still block forwarding that the outbound policy allows, which is useful for allowing only specific partner domains. Forwarding between internal users isn't affected by this setting.
Step 7: Confirm the alerts are on
These default alert policies cover the attacker behaviour in this guide. Check them in the Defender portal under Email & collaboration > Policies & rules > Alert policy:
| Alert policy | Fires when | Severity |
|---|---|---|
| Creation of forwarding/redirect rule | Someone creates an inbox rule that forwards or redirects; only rules created in Outlook on the web or Exchange Online PowerShell | Informational |
| Suspicious email forwarding activity | Someone autoforwarded email to a suspicious external account | High |
| Suspicious email sending patterns detected | A user sent suspicious email and is at risk of being restricted | Medium |
| User restricted from sending email | A user was blocked from sending, usually after a compromise | High |
Make sure the email recipients include the people who respond to incidents, not only the default TenantAdmins group. Alerts depend on audit logging, which is on by default.
Verify the clean-up
Get-InboxRule -Mailbox <user> -IncludeHiddenreturns only rules the user confirms are theirs.Get-Mailboxshows blankForwardingAddressandForwardingSmtpAddress.Get-MailboxPermissionandGet-RecipientPermissionshow no unexplained entries.Get-HostedOutboundSpamFilterPolicy | Format-List Name,AutoForwardingModeshowsOffon the default policy.- On a test mailbox with a rule that forwards to an external address, send a test message and confirm the forwarded copy is blocked with the 5.7.520 NDR shown in the troubleshooting section.
- The Auto forwarded messages report shows no new forwarders over the following days.
- Re-enable the account only after the password is reset, MFA is enforced and the steps above pass.
Troubleshooting
5.7.520 Access denied, Your organization does not allow external forwarding. Please contact your administrator for further assistance. AS(7555). This is the expected NDR once forwarding is blocked. If a user with a legitimate need receives it, add them to a custom outbound policy with forwarding On.
Get-InboxRule returns access denied for a read-only admin. The cmdlet doesn't work for View-Only Organization Management or Global Reader. Use an account with recipient management permissions.
A rule reappears after you remove it. The attacker still has access: a session that wasn't revoked, an app password, a consented application or an unremoved delegate. Repeat Step 1 and Step 4, then remove the rule again.
The user lost their own Outlook rules. Changing rules in PowerShell removes client-side Outlook rules. Recreate them from the export you made in Step 2.
The forwarding alert didn't fire. Creation of forwarding/redirect rule only tracks rules created in Outlook on the web or Exchange Online PowerShell, not rules created in the Outlook desktop client. Search for UpdateInboxRules in the audit log to cover that gap.
The user is still blocked from sending. Remove them from Restricted entities in the Defender portal or with Remove-BlockedSenderAddress -SenderAddress jason@contoso.com. Restrictions are usually removed within an hour, and should be removed within 24 hours.
Checklist
- Account disabled or password reset; sessions revoked; app passwords replaced.
- MFA methods, application consents and admin roles reviewed.
- Inbox rules exported, then malicious ones removed by identity, hidden rules included.
- Mailbox forwarding cleared; Full Access and Send As reviewed.
- Tenant-wide sweep of rules and forwarding exported and reviewed.
- Auto forwarded messages report and mail flow rules checked.
AutoForwardingModeset toOffon the default outbound policy; exceptions in a scoped custom policy.- Forwarding and restricted-sender alert policies on, with the right recipients.
- User removed from Restricted entities if needed; account re-enabled with MFA enforced.
References
- Respond to a compromised email account
- Detect and remediate Outlook rules and custom forms injection attacks
- Control external email forwarding and fix 5.7.520 errors
- Configure outbound spam policies
- Get-InboxRule
- Remove-InboxRule
- Set-HostedOutboundSpamFilterPolicy
- Auto forwarded messages report
- Alert policies in the Microsoft Defender portal
- Remove blocked users from the Restricted entities page