← All articles
Best PracticesNov 29, 202620 min read

Turn On Microsoft 365 Audit Logging and Restrict Teams External Access: A Step-by-Step Guide

Serdal Tarkan AltunSecurity Research EngineerLinkedIn

Summary

To turn on Microsoft 365 audit logging, confirm in Exchange Online PowerShell that unified audit log ingestion (UnifiedAuditLogIngestionEnabled) is True, turn it on if it isn't and remove mailbox audit bypasses. To restrict Teams external access, replace "allow all external domains" with a trusted-domain allow list and limit chat with unmanaged Teams accounts. Both are Microsoft 365 security best practices.

Quick steps

  1. Run the two read-only scripts: one for audit logging and mailbox auditing, one for Teams external access.
  2. Turn on unified audit log ingestion and mailbox auditing on by default if either is off, and remove audit bypasses nobody can justify.
  3. Check how long your licenses keep audit records, pick a search method and alert on audit setting changes.
  4. Restrict Teams external access to an allow list of partner domains.
  5. Turn off, or make outbound only, chat with Teams accounts not managed by an organization.
  6. Verify both changes, keep the JSON backups for rollback and monitor Teams admin changes.

Applies to: Microsoft 365 tenants in the global (commercial) cloud with Exchange Online and Microsoft Teams, as of November 2026. The scripts run in Windows PowerShell 5.1 with the ExchangeOnlineManagement and MicrosoftTeams modules. The Graph audit query API isn't available in US government or 21Vianet clouds, and chat with unmanaged Teams accounts isn't available in GCC, GCC High or DoD.

What is the unified audit log, and why does it matter?

The unified audit log is the Microsoft 365 record of user and admin activity across Exchange Online, SharePoint, OneDrive, Microsoft Entra ID, Microsoft Teams and other services, which Microsoft Purview Audit keeps and lets you search. Investigations of a compromised Microsoft 365 account depend on it, so the first question is whether your tenant is recording at all.

Microsoft's auditing article says audit logging is on by default for Microsoft 365 organizations, with two exceptions: Small and Medium Business licenses (Microsoft 365 Business Basic, Business Standard and Business Premium) and unmanaged tenants on free trials of enterprise licenses. In those tenants an admin must turn it on. When auditing is off, audit searches in Purview and Search-UnifiedAuditLog return nothing, and neither the Office 365 Management Activity API nor Microsoft Sentinel can reach the data.

MITRE ATT&CK lists turning off cloud logging as T1685.002, Disable or Modify Cloud Log, and its description names Set-MailboxAuditBypassAssociation as one way to stop mailbox auditing for chosen users in Office 365. The rules for disabled or bypassed Exchange audit logging watch for both changes.

What is Teams external access?

Teams external access, also called federation, lets users chat and meet with people outside the organization who sign in with a Microsoft identity: users of other Microsoft 365 organizations and people using Teams with an account not managed by an organization. Microsoft's external access article says all external domains are allowed by default, and both the organization settings and the user policies start turned on.

External access isn't guest access. A guest is invited into your tenant as a Microsoft Entra B2B collaboration user and can join teams and open files; an external access user stays in their own Microsoft Entra tenant and can only chat, call and meet.

External access (federation) Guest access
Identity Stays in the other organization or an unmanaged Teams account A B2B collaboration guest account in your directory
What they can do Chat, call, meet, be added to group chats Join teams and channels, chat, call, meet, open shared files
Access to your teams, sites and files No Yes, where shared
Where you control it Teams admin center, Users > External access; Set-CsTenantFederationConfiguration Teams guest access settings and Microsoft Entra ID guest invitations
Related detection Teams admin changes (Monitor and detect) Guest invitation rules, cross-tenant access setting rules

How do attackers use Teams external chat?

Attackers use external chat, which the default setting allows from every domain, to reach staff directly while posing as IT support. Microsoft Threat Intelligence has reported this pattern several times:

  • August 2, 2023: Midnight Blizzard sent credential theft lures as Teams chats. The actor renamed small business tenants it had already compromised, added new onmicrosoft.com subdomains with security themed names and sent message requests posing as technical support. The goal was to get users to enter a code and approve an MFA prompt, which the MFA fatigue rules look at from the sign-in side. Microsoft counted fewer than 40 organizations affected, and in some cases the actor then tried to register a device in Microsoft Entra ID.
  • May 15, 2024, updated June 2024: at the end of May 2024, Storm-1811 started calling and messaging users over Teams from tenants it created, with display names such as "Help Desk" and "IT Support". The chats led to Quick Assist sessions and credential theft through an adversary-in-the-middle phishing kit, which the token theft and AiTM rules address; Microsoft describes Storm-1811 as a group known to deploy Black Basta ransomware.
  • September 2, 2026: a Microsoft Security blog post on IT support impersonation describes an actor in a separate tenant who talks users into granting a remote session, then moves toward domain controllers. Its recommendations include restricting Teams external access to trusted domains only.

The 2026 post maps the first contact to T1566.003, Phishing: Spearphishing via Service. Teams shows external labels and an Accept or Block prompt, but these campaigns work by persuading the user to ignore them, which is an identity-based attack more than a software flaw.

Why do both belong in Microsoft 365 security best practices?

Among Microsoft 365 security best practices, these two work as a pair. Restricting external chat closes one of the paths in, and the unified audit log is how you'll know whether someone used it or changed the setting back. Our checklist of Microsoft Entra ID basics lists exporting audit logs to a SIEM, and the common Microsoft Entra ID misconfigurations include guest sprawl and logs kept only for the default retention.

Before you start

Read the settings first, agree on the allow list with the business, then change them in a maintenance window. Test in a lab tenant first, because an allow list blocks chat and meetings with every domain you leave out.

Roles and modules you need

Task Role or permission Microsoft names
Turn auditing on or off (Set-AdminAuditLogConfig) Audit Logs role in Exchange Online; the Compliance Management and Organization Management role groups have it by default
Search the audit log in the Purview portal Audit Logs or View-Only Audit Logs role; the Audit Manager and Audit Reader role groups have them
Run Search-UnifiedAuditLog Audit Logs or View-Only Audit Logs role in the Exchange admin center
Create audit log retention policies Organization Configuration role in the Purview portal
Query the audit log through Microsoft Graph AuditLogsQuery.Read.All, or a service-scoped AuditLogsQuery-*.Read.All permission
Change Teams external access and federation Teams Administrator
Create alert policies in the Microsoft Defender portal Manage Alerts role

For the other Exchange cmdlets in this guide, such as Set-MailboxAuditBypassAssociation, find the role that grants them in your tenant with Get-ManagementRole -Cmdlet <cmdlet>, as Microsoft's Exchange permissions article describes.

Both modules support Windows PowerShell 5.1. Connect in separate blocks before you run any script:

Connect-ExchangeOnline -UserPrincipalName admin@corp.example.com
Connect-MicrosoftTeams

Run the Exchange commands in Exchange Online PowerShell, not Security & Compliance PowerShell, where UnifiedAuditLogIngestionEnabled always reads False.

Plan the change

  • List the partner domains your users chat and meet with, from the business owners of those relationships. That list becomes the Teams allow list.
  • Decide which mailbox audit bypasses are justified. Microsoft presents the bypass as a noise reduction for trusted service accounts and warns that the account can then reach any mailbox it has permissions on with no audit record.
  • Tell the security operations team, since both steps write admin audit records that your own alerts should catch.

Step 1: Audit the current state

Start with two read-only scripts, one per service. Neither reads audit records, mail, chat content or credentials.

Check audit logging and mailbox auditing (read-only)

This script reads the unified audit log setting, the organization's mailbox auditing switch and every account that bypasses mailbox audit logging. With -IncludeMailboxes it also lists user and shared mailboxes whose audited actions were customized. Microsoft's mailbox auditing article explains why that matters: a customized mailbox no longer gets the new default actions Microsoft adds. Run it on an admin workstation after Connect-ExchangeOnline:

#Requires -Version 5.1
#Requires -Modules ExchangeOnlineManagement

<#
.SYNOPSIS
    Read-only check of Microsoft 365 audit logging and mailbox auditing in Exchange Online.

.DESCRIPTION
    Reads, in an existing Exchange Online PowerShell session:

      - UnifiedAuditLogIngestionEnabled from Get-AdminAuditLogConfig: is the organization
        recording user and admin activity in the Microsoft 365 audit log?
      - AuditDisabled from Get-OrganizationConfig: is mailbox auditing on by default turned off?
      - every account whose AuditBypassEnabled value is True in Get-MailboxAuditBypassAssociation
      - with IncludeMailboxes, the user and shared mailboxes whose DefaultAuditSet doesn't list
        Admin, Delegate and Owner, which means their audited actions were customized and new
        default actions aren't added to them

    Returns one row per finding with Status OK or Review and writes the rows to a CSV file.
    It reads configuration only. It reads no audit records, no mail and no credentials.

.PARAMETER OutputPath
    Path of the CSV report, for example 'C:\Reports\M365\audit-readiness.csv'.

.PARAMETER IncludeMailboxes
    Also read every user and shared mailbox. This can take a long time in a large organization.

.EXAMPLE
    .\Get-M365AuditReadiness.ps1 -OutputPath 'C:\Reports\M365\audit-readiness.csv' -IncludeMailboxes

.NOTES
    Read-only. Makes no change in Exchange Online. Writes only the CSV report.
    Run it in Exchange Online PowerShell after Connect-ExchangeOnline, not in Security & Compliance
    PowerShell, where UnifiedAuditLogIngestionEnabled always reads False.
#>
[CmdletBinding()]
param(
    [Parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [string]$OutputPath,

    [switch]$IncludeMailboxes
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

if (-not (Get-Command -Name Get-AdminAuditLogConfig -ErrorAction SilentlyContinue)) {
    throw 'Exchange Online cmdlets not found. Run Connect-ExchangeOnline first.'
}

$reportFolder = Split-Path -Path $OutputPath -Parent
if ($reportFolder -and -not (Test-Path -Path $reportFolder -PathType Container)) {
    throw "Report folder not found: $reportFolder"
}

$rows = New-Object System.Collections.Generic.List[object]
function Add-Finding {
    param([string]$Check, [string]$Status, [string]$Detail)
    $rows.Add([pscustomobject]@{ Check = $Check; Status = $Status; Detail = $Detail })
}

# 1. Unified audit log ingestion for the organization
$ingestion = (Get-AdminAuditLogConfig).UnifiedAuditLogIngestionEnabled
if ($ingestion -eq $true) {
    Add-Finding -Check 'Unified audit log ingestion' -Status 'OK' -Detail 'UnifiedAuditLogIngestionEnabled is True'
}
else {
    Add-Finding -Check 'Unified audit log ingestion' -Status 'Review' -Detail 'UnifiedAuditLogIngestionEnabled is False: user and admin activity is not recorded'
}

# 2. Mailbox auditing on by default
$auditDisabled = (Get-OrganizationConfig).AuditDisabled
if ($auditDisabled -eq $true) {
    Add-Finding -Check 'Mailbox auditing on by default' -Status 'Review' -Detail 'AuditDisabled is True: no mailbox actions are audited'
}
else {
    Add-Finding -Check 'Mailbox auditing on by default' -Status 'OK' -Detail 'AuditDisabled is False'
}

# 3. Accounts that bypass mailbox audit logging
$bypassed = @(Get-MailboxAuditBypassAssociation -ResultSize Unlimited | Where-Object { $_.AuditBypassEnabled -eq $true })
if ($bypassed.Count -eq 0) {
    Add-Finding -Check 'Mailbox audit bypass' -Status 'OK' -Detail 'No account bypasses mailbox audit logging'
}
foreach ($account in $bypassed) {
    Add-Finding -Check 'Mailbox audit bypass' -Status 'Review' -Detail "$($account.Name): mailbox actions by this account are not logged in any mailbox"
}

# 4. Optional: mailboxes whose audited actions were customized
if ($IncludeMailboxes) {
    $mailboxes = @(Get-Mailbox -ResultSize Unlimited -RecipientTypeDetails UserMailbox, SharedMailbox)
    $customized = @($mailboxes | Where-Object {
        $set = @($_.DefaultAuditSet | ForEach-Object { [string]$_ })
        -not (($set -contains 'Admin') -and ($set -contains 'Delegate') -and ($set -contains 'Owner'))
    })
    if ($customized.Count -eq 0) {
        Add-Finding -Check 'Default audited actions' -Status 'OK' -Detail "All $($mailboxes.Count) user and shared mailboxes use the Microsoft-managed actions"
    }
    foreach ($mailbox in $customized) {
        Add-Finding -Check 'Default audited actions' -Status 'Review' -Detail "$($mailbox.UserPrincipalName): DefaultAuditSet is '$(@($mailbox.DefaultAuditSet) -join ',')'"
    }
}

$rows | Export-Csv -Path $OutputPath -NoTypeInformation -Encoding UTF8
$rows
.\Get-M365AuditReadiness.ps1 -OutputPath 'C:\Reports\M365\audit-readiness.csv' -IncludeMailboxes | Format-Table -AutoSize

Example output (the values are illustrative):

Check                          Status Detail
-----                          ------ ------
Unified audit log ingestion    Review UnifiedAuditLogIngestionEnabled is False: user and admin activity is not recorded
Mailbox auditing on by default OK     AuditDisabled is False
Mailbox audit bypass           Review svc-archive: mailbox actions by this account are not logged in any mailbox
Default audited actions        Review finance-shared@corp.example.com: DefaultAuditSet is 'Owner'

How to read the results:

  • Unified audit log ingestion is False: nothing is recorded, so no record exists of what happened before you turn it on. Step 2 fixes this.
  • Mailbox audit bypass: Microsoft says you can't turn off mailbox auditing for one mailbox while auditing on by default is on, but a bypass keeps all mailbox actions of one account out of the log. Each one needs an owner and a reason.
  • Default audited actions: DefaultAuditSet lists the sign-in types (Admin, Delegate, Owner) for which Microsoft still manages the audited actions. A missing type was customized with Set-Mailbox.

Summarize Teams external access (read-only)

This script reads the tenant federation configuration and every external access policy, and marks the settings that leave external chat open. Run it after Connect-MicrosoftTeams as a Teams Administrator:

#Requires -Version 5.1
#Requires -Modules MicrosoftTeams

<#
.SYNOPSIS
    Read-only summary of Microsoft Teams external access (federation) settings and policies.

.DESCRIPTION
    Reads the tenant federation configuration with Get-CsTenantFederationConfiguration and the
    external access policies with Get-CsExternalAccessPolicy, then returns one row per setting:

      - AllowFederatedUsers, the domain mode (all known domains or an allow list), the allowed
        and blocked domains and BlockAllSubdomains
      - AllowTeamsConsumer and AllowTeamsConsumerInbound (Teams accounts not managed by an
        organization) and ExternalAccessWithTrialTenants
      - for each external access policy: EnableFederationAccess, EnableTeamsConsumerAccess,
        EnableTeamsConsumerInbound and CommunicationWithExternalOrgs

    Settings that leave external chat open to every domain or to unmanaged accounts are marked
    Review. Writes the rows to a CSV file. It changes nothing.

.PARAMETER OutputPath
    Path of the CSV report, for example 'C:\Reports\M365\teams-external-access.csv'.

.EXAMPLE
    .\Get-TeamsExternalAccessSummary.ps1 -OutputPath 'C:\Reports\M365\teams-external-access.csv'

.NOTES
    Read-only. Makes no change in Microsoft Teams. Writes only the CSV report.
    Run it after Connect-MicrosoftTeams with a Teams Administrator account.
    A property that the installed module version doesn't return is reported as 'Not returned'.
#>
[CmdletBinding()]
param(
    [Parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [string]$OutputPath
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

if (-not (Get-Command -Name Get-CsTenantFederationConfiguration -ErrorAction SilentlyContinue)) {
    throw 'Microsoft Teams cmdlets not found. Run Connect-MicrosoftTeams first.'
}

$reportFolder = Split-Path -Path $OutputPath -Parent
if ($reportFolder -and -not (Test-Path -Path $reportFolder -PathType Container)) {
    throw "Report folder not found: $reportFolder"
}

function Get-OptionalValue {
    param($InputObject, [string]$Name)
    $property = $InputObject.PSObject.Properties[$Name]
    if ($null -eq $property) { return 'Not returned' }
    return $property.Value
}

function ConvertTo-DomainText {
    param($Value)
    $domains = foreach ($item in @($Value)) {
        if ($null -eq $item) { continue }
        $domainProperty = $item.PSObject.Properties['Domain']
        if ($null -ne $domainProperty) { [string]$domainProperty.Value }
        else { ([string]$item) -replace '^Domain=', '' }
    }
    return (@($domains | Where-Object { $_ }) -join '; ')
}

$rows = New-Object System.Collections.Generic.List[object]
function Add-Setting {
    param([string]$Scope, [string]$Setting, $Value, [string]$Assessment)
    $rows.Add([pscustomobject]@{ Scope = $Scope; Setting = $Setting; Value = [string]$Value; Assessment = $Assessment })
}

# 1. Organization settings
$fed = Get-CsTenantFederationConfiguration
$allowed = $fed.AllowedDomains
$allowAll = ($null -ne $allowed) -and ((($allowed.PSObject.TypeNames -join ' ') -match 'AllowAllKnownDomains') -or ([string]$allowed -match '^AllowAllKnownDomains'))
if ($allowAll) {
    $domainMode = 'AllowAllKnownDomains'
    $allowedText = ''
}
else {
    $domainMode = 'AllowList'
    $listProperty = if ($null -ne $allowed) { $allowed.PSObject.Properties['AllowedDomain'] } else { $null }
    $allowedText = if ($null -ne $listProperty) { ConvertTo-DomainText -Value $listProperty.Value } else { ConvertTo-DomainText -Value $allowed }
}
$blockedText = ConvertTo-DomainText -Value $fed.BlockedDomains

$fedAssessment = 'OK'
if ($fed.AllowFederatedUsers -eq $true -and $allowAll -and -not $blockedText) { $fedAssessment = 'Review: every external domain is allowed' }
elseif ($fed.AllowFederatedUsers -eq $true -and $allowAll) { $fedAssessment = 'Review: every domain except the blocked list is allowed' }
Add-Setting -Scope 'Organization' -Setting 'AllowFederatedUsers' -Value $fed.AllowFederatedUsers -Assessment $fedAssessment
Add-Setting -Scope 'Organization' -Setting 'DomainMode' -Value $domainMode -Assessment ''
Add-Setting -Scope 'Organization' -Setting 'AllowedDomains' -Value $allowedText -Assessment ''
Add-Setting -Scope 'Organization' -Setting 'BlockedDomains' -Value $blockedText -Assessment ''
Add-Setting -Scope 'Organization' -Setting 'BlockAllSubdomains' -Value (Get-OptionalValue -InputObject $fed -Name 'BlockAllSubdomains') -Assessment ''

$consumer = Get-OptionalValue -InputObject $fed -Name 'AllowTeamsConsumer'
$consumerInbound = Get-OptionalValue -InputObject $fed -Name 'AllowTeamsConsumerInbound'
$trial = Get-OptionalValue -InputObject $fed -Name 'ExternalAccessWithTrialTenants'
Add-Setting -Scope 'Organization' -Setting 'AllowTeamsConsumer' -Value $consumer -Assessment $(if ($consumer -eq $true) { 'Review: chat with unmanaged Teams accounts is on' } else { 'OK' })
Add-Setting -Scope 'Organization' -Setting 'AllowTeamsConsumerInbound' -Value $consumerInbound -Assessment $(if ($consumer -eq $true -and $consumerInbound -eq $true) { 'Review: unmanaged Teams accounts can start chats' } else { 'OK' })
Add-Setting -Scope 'Organization' -Setting 'ExternalAccessWithTrialTenants' -Value $trial -Assessment $(if ([string]$trial -eq 'Allowed') { 'Review: trial-only tenants can reach users' } else { '' })

# 2. External access policies (user level)
foreach ($policy in @(Get-CsExternalAccessPolicy)) {
    $scope = "Policy $($policy.Identity)"
    foreach ($name in 'EnableFederationAccess', 'EnableTeamsConsumerAccess', 'EnableTeamsConsumerInbound', 'CommunicationWithExternalOrgs') {
        Add-Setting -Scope $scope -Setting $name -Value (Get-OptionalValue -InputObject $policy -Name $name) -Assessment ''
    }
}

$rows | Export-Csv -Path $OutputPath -NoTypeInformation -Encoding UTF8
$rows
.\Get-TeamsExternalAccessSummary.ps1 -OutputPath 'C:\Reports\M365\teams-external-access.csv' | Format-Table -AutoSize

Example output (the values are illustrative):

Scope         Setting                        Value                Assessment
-----         -------                        -----                ----------
Organization  AllowFederatedUsers            True                 Review: every external domain is allowed
Organization  DomainMode                     AllowAllKnownDomains
Organization  AllowedDomains
Organization  BlockedDomains
Organization  BlockAllSubdomains             False
Organization  AllowTeamsConsumer             True                 Review: chat with unmanaged Teams accounts is on
Organization  AllowTeamsConsumerInbound      True                 Review: unmanaged Teams accounts can start chats
Organization  ExternalAccessWithTrialTenants Blocked
Policy Global EnableFederationAccess         True
Policy Global EnableTeamsConsumerAccess      True
Policy Global EnableTeamsConsumerInbound     True
Policy Global CommunicationWithExternalOrgs  OrganizationDefault

A user can use external access only when both the organization setting and their policy allow it, and AllowFederatedUsers set to False blocks every external domain whatever the lists and policies say. The output above shows the defaults: any external organization that also allows yours can reach every user, and so can unmanaged Teams accounts.

Step 2: Turn on the unified audit log and remove audit bypasses

Turn auditing on first, because every later step depends on its records.

Turn on unified audit log ingestion

In the portal, sign in to the Microsoft Purview portal, open the Audit solution card and select the Start recording user and admin activity banner, which appears only when auditing is off. In Exchange Online PowerShell, the cmdlet supports -WhatIf:

Set-AdminAuditLogConfig -UnifiedAuditLogIngestionEnabled $true -WhatIf

Drop -WhatIf to apply it. Microsoft says the change can take up to 60 minutes to take effect, and new events can take several hours to become searchable. Turning auditing on or off is itself recorded as a Set-AdminAuditLogConfig admin record.

Turn on auditing and remove bypasses with one script (changes configuration)

When the Step 1 report shows more than one gap, this script fixes them in order. It writes the previous values to a JSON backup, turns on ingestion and mailbox auditing on by default if either is off, and removes the bypass only for the accounts you name. It never turns auditing off or adds a bypass. Run it as an Exchange admin who holds the Audit Logs role and the roles that Get-ManagementRole -Cmdlet reports for the other two cmdlets, with -WhatIf first:

#Requires -Version 5.1
#Requires -Modules ExchangeOnlineManagement

<#
.SYNOPSIS
    Turns on Microsoft 365 audit logging and mailbox auditing, and removes named audit bypasses.

.DESCRIPTION
    Reads the current audit settings and writes them to a JSON backup first, even under -WhatIf:
    UnifiedAuditLogIngestionEnabled, AuditDisabled and the accounts that bypass mailbox audit
    logging. Then, one change at a time with -WhatIf and -Confirm support:

      1. If UnifiedAuditLogIngestionEnabled is False, runs
         Set-AdminAuditLogConfig -UnifiedAuditLogIngestionEnabled $true.
      2. If AuditDisabled is True, runs Set-OrganizationConfig -AuditDisabled $false.
      3. For each account in RemoveBypassFor that currently bypasses mailbox audit logging, runs
         Set-MailboxAuditBypassAssociation -AuditBypassEnabled $false.

    The script only turns auditing on. It never turns auditing off and never adds a bypass.

.PARAMETER BackupPath
    Path of the JSON backup, for example 'C:\Reports\M365\audit-baseline-backup.json'.

.PARAMETER RemoveBypassFor
    Optional. Accounts (name, alias, email address or user principal name) whose mailbox audit
    bypass you decided to remove, for example 'svc-archive@corp.example.com'.

.EXAMPLE
    .\Set-M365AuditBaseline.ps1 -BackupPath 'C:\Reports\M365\audit-baseline-backup.json' -RemoveBypassFor 'svc-archive@corp.example.com' -WhatIf

.NOTES
    Changes configuration. Changes the Exchange Online audit settings of the organization.
    Run it in Exchange Online PowerShell after Connect-ExchangeOnline, with an account that holds
    the Audit Logs role and the roles that Get-ManagementRole -Cmdlet reports for
    Set-OrganizationConfig and Set-MailboxAuditBypassAssociation.
    Turning on auditing can take up to 60 minutes to take effect.
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
param(
    [Parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [string]$BackupPath,

    [ValidateNotNullOrEmpty()]
    [string[]]$RemoveBypassFor = @()
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

if (-not (Get-Command -Name Set-AdminAuditLogConfig -ErrorAction SilentlyContinue)) {
    throw 'Exchange Online cmdlets not found. Run Connect-ExchangeOnline first.'
}

$backupFolder = Split-Path -Path $BackupPath -Parent
if ($backupFolder -and -not (Test-Path -Path $backupFolder -PathType Container)) {
    throw "Backup folder not found: $backupFolder"
}

# 1. Current state, written to the backup before any change
$ingestion = (Get-AdminAuditLogConfig).UnifiedAuditLogIngestionEnabled
$auditDisabled = (Get-OrganizationConfig).AuditDisabled
$bypassed = @(Get-MailboxAuditBypassAssociation -ResultSize Unlimited |
    Where-Object { $_.AuditBypassEnabled -eq $true } | ForEach-Object { [string]$_.Name })

$backup = [pscustomobject]@{
    CapturedUtc                     = (Get-Date).ToUniversalTime().ToString('o')
    UnifiedAuditLogIngestionEnabled = $ingestion
    AuditDisabled                   = $auditDisabled
    AuditBypassEnabledAccounts      = $bypassed
}
ConvertTo-Json -InputObject $backup -Depth 3 | Set-Content -Path $BackupPath -Encoding UTF8 -WhatIf:$false

# 2. Unified audit log ingestion
if ($ingestion -ne $true) {
    if ($PSCmdlet.ShouldProcess('Microsoft 365 organization', 'Turn on unified audit log ingestion')) {
        Set-AdminAuditLogConfig -UnifiedAuditLogIngestionEnabled $true
        [pscustomobject]@{ Change = 'UnifiedAuditLogIngestionEnabled'; Target = 'Organization'; Status = 'Set to True' }
    }
}

# 3. Mailbox auditing on by default
if ($auditDisabled -eq $true) {
    if ($PSCmdlet.ShouldProcess('Microsoft 365 organization', 'Turn mailbox auditing on by default back on')) {
        Set-OrganizationConfig -AuditDisabled $false
        [pscustomobject]@{ Change = 'AuditDisabled'; Target = 'Organization'; Status = 'Set to False' }
    }
}

# 4. Named mailbox audit bypasses
foreach ($identity in $RemoveBypassFor) {
    # Require exactly one matching account before any change
    $association = @(Get-MailboxAuditBypassAssociation -Identity $identity)
    if ($association.Count -ne 1) {
        Write-Warning "$identity matched $($association.Count) accounts; skipped."
        continue
    }
    if ($association[0].AuditBypassEnabled -ne $true) {
        Write-Warning "$identity doesn't bypass mailbox audit logging; skipped."
        continue
    }
    if ($PSCmdlet.ShouldProcess($identity, 'Stop bypassing mailbox audit logging')) {
        Set-MailboxAuditBypassAssociation -Identity $identity -AuditBypassEnabled $false
        [pscustomobject]@{ Change = 'AuditBypassEnabled'; Target = $identity; Status = 'Set to False' }
    }
}
.\Set-M365AuditBaseline.ps1 -BackupPath 'C:\Reports\M365\audit-baseline-backup.json' -RemoveBypassFor 'svc-archive@corp.example.com' -WhatIf
What if: Performing the operation "Turn on unified audit log ingestion" on target "Microsoft 365 organization".
What if: Performing the operation "Stop bypassing mailbox audit logging" on target "svc-archive@corp.example.com".

Run it again without -WhatIf to apply. The changes appear as Set-OrganizationConfig records and Set-MailboxAuditBypassAssociation records. To restore Microsoft-managed actions on a customized mailbox, run Set-Mailbox -Identity <MailboxIdentity> -DefaultAuditSet Admin,Delegate,Owner.

Step 3: Set audit retention, search and alerting

Recording is half the job; you also need the records to last long enough and someone to look at them.

How long does Microsoft 365 keep audit logs?

Retention depends on the license of the user who performed the activity. As of November 2026, Microsoft's retention policy article gives these defaults:

License of the user who acted Default retention Longer retention
Audit (Standard): Office 365 or Microsoft 365 licenses without E5 180 days for records created on or after October 17, 2023 (90 days before that date) Not available
Audit (Premium): Office 365 E5, Microsoft 365 E5, Microsoft Purview Suite or the E5 eDiscovery and Audit add-on 1 year for Microsoft Entra ID, Exchange, OneDrive and SharePoint records; 180 days for other services Retention policies up to 1 year, up to 50 policies per organization
Audit (Premium) plus the 10-Year Audit Log Retention add-on As above Retention policies up to 10 years, from the time the policy exists

Guest users and users without E5 keep the 180 days, even in an E5 tenant. Teams records fall under "other services", so an E5 tenant that wants a year of Teams admin and chat records needs a retention policy for them. Create one in the Purview portal: open Audit, select Create audit retention policy, set Record type to the Microsoft Teams record type and choose a Duration. Changing a license or a policy changes the expiry of records added after the change, not those already stored.

For anything longer, or for correlation with other logs, stream the audit log to your SIEM through the Office 365 Management Activity API or the Microsoft Sentinel connector.

How do you search the unified audit log?

Method Where Limits Microsoft documents Best for
Audit search Purview portal, Audit > Search Date range up to 180 days; up to 10 search jobs at a time per account; export up to 50,000 rows (Standard) or 1,000,000 rows (Premium) Investigations
Search-UnifiedAuditLog Exchange Online PowerShell 100 records by default; -ResultSize up to 5,000; -SessionCommand ReturnLargeSet pages through up to 50,000 Quick scripted checks
Audit Search Graph API POST /security/auditLog/queries, Microsoft Graph v1.0 Global service only; tenant-level daily and concurrent query limits Automation
Office 365 Management Activity API REST service Microsoft's recommended way to download audit data programmatically SIEM export

For core services such as Exchange, SharePoint, OneDrive and Teams, Microsoft says a record is typically available 60 to 90 minutes after the event, with no guaranteed time. A Search-UnifiedAuditLog check for the changes in this guide, read-only:

Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-90) -EndDate (Get-Date) -Operations Set-AdminAuditLogConfig, Set-MailboxAuditBypassAssociation, TeamsAdminAction -ResultSize 5000 |
    Select-Object CreationDate, UserIds, RecordType, AuditData

The same search through Microsoft Graph's audit log query API runs as a job. Creating the query only reads data; it needs AuditLogsQuery.Read.All:

POST https://graph.microsoft.com/v1.0/security/auditLog/queries
Content-Type: application/json

{
  "displayName": "Audit and Teams admin changes",
  "filterStartDateTime": "2026-11-01T00:00:00Z",
  "filterEndDateTime": "2026-11-29T00:00:00Z",
  "operationFilters": ["Set-AdminAuditLogConfig", "Set-MailboxAuditBypassAssociation", "TeamsAdminAction"]
}

Poll GET /security/auditLog/queries/{auditLogQueryId} until status reads succeeded, then read the results from GET /security/auditLog/queries/{auditLogQueryId}/records.

How do you alert on audit and external access changes?

Create alerts for the changes an attacker would make next: auditing turned off, a bypass added and Teams external access opened again. The Microsoft Defender portal keeps alert policies under Email & collaboration > Policies & rules > Alert policy, and the activities it can track depend on your plan. In a SIEM, use the queries in Monitor and detect.

Step 4: Restrict Teams external access to trusted domains

Replace "allow all external domains" with an allow list. Microsoft offers four models:

Model Effect When to use it
Allow all external domains The default: any federated organization can find, chat and meet with your users Not recommended
Block only specific external domains Every domain except the blocked list is allowed; subdomains aren't blocked unless BlockAllSubdomains is True Short-term, while you build an allow list
Allow only specific external domains Only listed domains are allowed; every other domain is blocked Recommended for most organizations
Block all external domains No external chat or meetings through federation Organizations that use guest access only

A block list can't keep up with the campaigns above: Midnight Blizzard added new onmicrosoft.com subdomains to compromised tenants, and Storm-1811 used tenants it created. An allow list blocks domains like these, because a new domain isn't on it. Federation is also mutual: a partner can chat with your users only if their organization allows yours too.

Set the allow list in the Teams admin center

  1. In the Teams admin center, go to Users > External access.
  2. Next to Teams and Skype for Business users in external organizations, choose Allow only specific external domains.
  3. Select Add external domains, type a domain in the Domain box and select Done. Repeat for each partner domain.

Set it with PowerShell (changes configuration)

The script below makes the same change with Set-CsTenantFederationConfiguration. Strings can't be passed to -AllowedDomains, so it builds the allow list with New-CsEdgeDomainPattern and New-CsEdgeAllowList, as Microsoft's reference shows; the list can hold up to 4,000 domains. It backs up the current settings to JSON, refuses to turn on federation that's off, and supports -WhatIf and -Confirm. Run it as a Teams Administrator:

#Requires -Version 5.1
#Requires -Modules MicrosoftTeams

<#
.SYNOPSIS
    Restricts Microsoft Teams external access to named domains and limits unmanaged Teams accounts.

.DESCRIPTION
    Writes the current tenant federation settings to a JSON backup first, even under -WhatIf:
    AllowFederatedUsers, the domain mode, the allowed and blocked domains, BlockAllSubdomains,
    AllowTeamsConsumer and AllowTeamsConsumerInbound. Then it sends one
    Set-CsTenantFederationConfiguration call with the changes you asked for:

      AllowedDomain     replaces the domain list with an allow list: only these domains are
                        allowed and every other domain is blocked
      BlockedDomain     adds domains to the blocked list while all other domains stay allowed;
                        BlockAllSubdomains also blocks their subdomains
      DisableUnmanagedTeams       sets AllowTeamsConsumer to False
      BlockUnmanagedTeamsInbound  sets AllowTeamsConsumerInbound to False

    The script only narrows external access. It stops when AllowFederatedUsers is already False
    (external access is off for every domain) and when you add blocked domains while an allow
    list is in effect (Teams ignores the blocked list then).

.PARAMETER BackupPath
    Path of the JSON backup, for example 'C:\Reports\M365\teams-federation-backup.json'.

.PARAMETER AllowedDomain
    Domains of the organizations your users may chat and meet with, for example 'partner.example.com'.

.PARAMETER BlockedDomain
    Domains to add to the blocked list, for example 'blocked.example.net'.

.PARAMETER BlockAllSubdomains
    With BlockedDomain, also block every subdomain of the blocked domains.

.PARAMETER DisableUnmanagedTeams
    Turn off chat with Teams accounts that aren't managed by an organization.

.PARAMETER BlockUnmanagedTeamsInbound
    Keep chat with unmanaged Teams accounts, but only users in your organization can start it.

.EXAMPLE
    .\Set-TeamsExternalAccessRestriction.ps1 -BackupPath 'C:\Reports\M365\teams-federation-backup.json' -AllowedDomain 'partner.example.com', 'supplier.example.org' -DisableUnmanagedTeams -WhatIf

.NOTES
    Changes configuration. Changes the Microsoft Teams external access settings of the tenant.
    Run it after Connect-MicrosoftTeams with a Teams Administrator account.
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High', DefaultParameterSetName = 'Consumer')]
param(
    [Parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [string]$BackupPath,

    [Parameter(Mandatory = $true, ParameterSetName = 'AllowList')]
    [ValidatePattern('^(?=.{4,253}$)([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$')]
    [string[]]$AllowedDomain,

    [Parameter(Mandatory = $true, ParameterSetName = 'BlockList')]
    [ValidatePattern('^(?=.{4,253}$)([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$')]
    [string[]]$BlockedDomain,

    [Parameter(ParameterSetName = 'BlockList')]
    [switch]$BlockAllSubdomains,

    [switch]$DisableUnmanagedTeams,

    [switch]$BlockUnmanagedTeamsInbound
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

if (-not (Get-Command -Name Set-CsTenantFederationConfiguration -ErrorAction SilentlyContinue)) {
    throw 'Microsoft Teams cmdlets not found. Run Connect-MicrosoftTeams first.'
}

$backupFolder = Split-Path -Path $BackupPath -Parent
if ($backupFolder -and -not (Test-Path -Path $backupFolder -PathType Container)) {
    throw "Backup folder not found: $backupFolder"
}

function ConvertTo-DomainArray {
    param($Value)
    $domains = foreach ($item in @($Value)) {
        if ($null -eq $item) { continue }
        $domainProperty = $item.PSObject.Properties['Domain']
        if ($null -ne $domainProperty) { [string]$domainProperty.Value }
        else { ([string]$item) -replace '^Domain=', '' }
    }
    return @($domains | Where-Object { $_ } | ForEach-Object { $_.ToLowerInvariant() } | Sort-Object -Unique)
}

# 1. Current settings, written to the backup before any change
$fed = Get-CsTenantFederationConfiguration
$allowed = $fed.AllowedDomains
$allowAll = ($null -ne $allowed) -and ((($allowed.PSObject.TypeNames -join ' ') -match 'AllowAllKnownDomains') -or ([string]$allowed -match '^AllowAllKnownDomains'))
$currentAllowed = @()
if (-not $allowAll -and $null -ne $allowed) {
    $listProperty = $allowed.PSObject.Properties['AllowedDomain']
    $source = if ($null -ne $listProperty) { $listProperty.Value } else { $allowed }
    $currentAllowed = @(ConvertTo-DomainArray -Value $source)
}
$currentBlocked = @(ConvertTo-DomainArray -Value $fed.BlockedDomains)

$backup = [pscustomobject]@{
    CapturedUtc               = (Get-Date).ToUniversalTime().ToString('o')
    AllowFederatedUsers       = $fed.AllowFederatedUsers
    AllowedDomainsMode        = $(if ($allowAll) { 'AllowAllKnownDomains' } else { 'AllowList' })
    AllowedDomains            = @($currentAllowed)
    BlockedDomains            = @($currentBlocked)
    BlockAllSubdomains        = $fed.BlockAllSubdomains
    AllowTeamsConsumer        = $fed.AllowTeamsConsumer
    AllowTeamsConsumerInbound = $fed.AllowTeamsConsumerInbound
}
ConvertTo-Json -InputObject $backup -Depth 3 | Set-Content -Path $BackupPath -Encoding UTF8 -WhatIf:$false

if ($fed.AllowFederatedUsers -ne $true) {
    throw 'AllowFederatedUsers is False, so external access is already off for every domain. This script does not turn it on.'
}

# 2. Build the change
$change = @{}
$description = New-Object System.Collections.Generic.List[string]

if ($PSCmdlet.ParameterSetName -eq 'AllowList') {
    $patterns = @($AllowedDomain | ForEach-Object { New-CsEdgeDomainPattern -Domain $_.ToLowerInvariant() })
    $change['AllowedDomains'] = New-CsEdgeAllowList -AllowedDomain $patterns
    $description.Add("allow only $($AllowedDomain -join ', ')")
}

if ($PSCmdlet.ParameterSetName -eq 'BlockList') {
    if (-not $allowAll) {
        throw 'An allow list is in effect, so Teams ignores the blocked list. Add the domains to the allow list instead.'
    }
    $blockedList = New-Object 'System.Collections.Generic.List[string]'
    foreach ($domain in @($currentBlocked) + @($BlockedDomain | ForEach-Object { $_.ToLowerInvariant() }) | Sort-Object -Unique) {
        $blockedList.Add($domain)
    }
    $change['BlockedDomains'] = $blockedList
    $description.Add("block $($BlockedDomain -join ', ')")
    if ($BlockAllSubdomains) {
        $change['BlockAllSubdomains'] = $true
        $description.Add('block their subdomains')
    }
}

if ($DisableUnmanagedTeams) {
    $change['AllowTeamsConsumer'] = $false
    $description.Add('turn off chat with unmanaged Teams accounts')
}
elseif ($BlockUnmanagedTeamsInbound) {
    $change['AllowTeamsConsumerInbound'] = $false
    $description.Add('stop unmanaged Teams accounts from starting chats')
}

if ($change.Count -eq 0) {
    Write-Output 'Nothing to change. Pass AllowedDomain, BlockedDomain, DisableUnmanagedTeams or BlockUnmanagedTeamsInbound.'
    return
}

# 3. Apply it in one call
if ($PSCmdlet.ShouldProcess('Tenant federation configuration', ($description -join '; '))) {
    Set-CsTenantFederationConfiguration @change -Confirm:$false
    [pscustomobject]@{ Change = ($description -join '; '); Backup = $BackupPath; Status = 'Applied' }
}
.\Set-TeamsExternalAccessRestriction.ps1 -BackupPath 'C:\Reports\M365\teams-federation-backup.json' -AllowedDomain 'partner.example.com', 'supplier.example.org' -WhatIf
What if: Performing the operation "allow only partner.example.com, supplier.example.org" on target "Tenant federation configuration".

If you stay on a block list for now, pass -BlockedDomain with -BlockAllSubdomains instead. Teams ignores the blocked list while an allow list is in effect, and the script stops in that case. People from blocked domains can still join meetings anonymously if anonymous access is allowed, so review your meeting settings separately.

Microsoft also lists two related organization settings. ExternalAccessWithTrialTenants controls tenants that hold only trial licenses; its default is Blocked, and the Step 1 script flags Allowed. Block specific users from communicating with people in my organization blocks up to 200 individual external users when you can't block their whole domain.

Step 5: Limit unmanaged Teams accounts and per-user external access

Chat with Teams accounts not managed by an organization, such as Microsoft Teams (free), is a separate switch from federation, and it's on by default.

Setting Where Recommended value Effect
People in my organization can communicate with unmanaged Teams accounts Teams admin center, Users > External access; AllowTeamsConsumer Off, unless a business need exists Off blocks chat and meetings with unmanaged accounts
External users with Teams accounts not managed by an organization can contact users in my organization Same page; AllowTeamsConsumerInbound Off when the setting above stays on Off means only your users can start the conversation, and unmanaged users can't search for your users by email address
External access policies Users > External access > Policies; Set-CsExternalAccessPolicy Keep the org-wide default narrow and assign a custom policy to the users who need more EnableFederationAccess, EnableTeamsConsumerAccess and EnableTeamsConsumerInbound per user or group

With the change script, -DisableUnmanagedTeams sets AllowTeamsConsumer to False, or -BlockUnmanagedTeamsInbound keeps outbound chat and turns off inbound:

.\Set-TeamsExternalAccessRestriction.ps1 -BackupPath 'C:\Reports\M365\teams-consumer-backup.json' -DisableUnmanagedTeams -WhatIf

External access policies can also carry their own domain lists through CommunicationWithExternalOrgs, AllowedExternalDomains and BlockedExternalDomains, up to 100 domains per list. A custom policy assigned to a user takes precedence over the organization's domain setting, so a policy that allows all external domains undoes the allow list for its users. The Step 1 script lists every policy so you can spot one. Skype consumer interoperability ended on May 5, 2025, and AllowPublicUsers can no longer be used.

Verify

Run both read-only scripts again and compare them with the first run.

Check Expected result
Get-M365AuditReadiness.ps1 Unified audit log ingestion OK, mailbox auditing OK, only justified bypasses left
Purview portal, Audit No Start recording user and admin activity banner
Search-UnifiedAuditLog -Operations Set-AdminAuditLogConfig A record of your change, with your account, time and IP address
Get-TeamsExternalAccessSummary.ps1 DomainMode is AllowList with your partner domains, AllowTeamsConsumer or AllowTeamsConsumerInbound is False
A chat from a test account in a non-listed tenant The chat doesn't reach your user

For a single user, the Run Tests diagnostic that Microsoft's external access article links to opens in the Microsoft 365 admin center. It takes the user's SIP address and the federated tenant's domain name, checks whether that user can reach a user in a trusted organization and suggests what to change.

Roll back

Keep the JSON backups; they hold the previous values and no secrets.

Change How to roll back Notes
Unified audit log ingestion turned on Set-AdminAuditLogConfig -UnifiedAuditLogIngestionEnabled $false Not recommended. Nothing is recorded while it's off, and those events can't be recovered later
Mailbox auditing on by default turned on Set-OrganizationConfig -AuditDisabled $true Not recommended. No mailbox actions are audited and bypass associations are ignored
Mailbox audit bypass removed Set-MailboxAuditBypassAssociation -Identity <account> -AuditBypassEnabled $true for each account in the backup Only for a service account whose noise you've reviewed
Teams allow list or block list Restore the domain mode and lists from the JSON backup (below) or in Users > External access Chat with removed domains resumes only if their organization still allows yours
Unmanaged Teams accounts Set-CsTenantFederationConfiguration -AllowTeamsConsumer $true -AllowTeamsConsumerInbound $true Restores the default
Audit retention policy Delete it in Purview or with Remove-UnifiedAuditLogRetentionPolicy in Security & Compliance PowerShell Removal can take up to 30 minutes

To restore the Teams federation settings from the backup, preview first:

$backup = Get-Content -Path 'C:\Reports\M365\teams-federation-backup.json' -Raw | ConvertFrom-Json
$restore = @{
    AllowTeamsConsumer        = [bool]$backup.AllowTeamsConsumer
    AllowTeamsConsumerInbound = [bool]$backup.AllowTeamsConsumerInbound
    BlockAllSubdomains        = [bool]$backup.BlockAllSubdomains
}
if ($backup.AllowedDomainsMode -eq 'AllowAllKnownDomains') {
    $restore['AllowedDomains'] = New-CsEdgeAllowAllKnownDomains
}
else {
    $restore['AllowedDomains'] = New-CsEdgeAllowList -AllowedDomain @($backup.AllowedDomains | ForEach-Object { New-CsEdgeDomainPattern -Domain $_ })
}
$blocked = New-Object 'System.Collections.Generic.List[string]'
@($backup.BlockedDomains) | Where-Object { $_ } | ForEach-Object { $blocked.Add($_) }
if ($blocked.Count -gt 0) { $restore['BlockedDomains'] = $blocked } else { $restore['BlockedDomains'] = $null }
Set-CsTenantFederationConfiguration @restore -WhatIf

Monitor and detect

Watch three things: the audit settings, the Teams external access settings and external first contact.

Operation Recorded when Related pages
Set-AdminAuditLogConfig The unified audit log setting changes, also from the Purview banner Audit log setting source page, Exchange audit logging rules
Set-MailboxAuditBypassAssociation A bypass is added or removed Audit bypass source page
Set-OrganizationConfig, Set-Mailbox Mailbox auditing is changed for the organization or one mailbox Organization setting source page, mailbox setting source page
TeamsAdminAction A Teams admin changes a setting in the Teams admin center, PowerShell or the API Teams app and organization setting rules, whose detection logic baselines this operation
TeamsTenantSettingChanged A global admin changes an org-wide Teams setting in the Microsoft 365 admin center TeamsTenantSettingChanged source page
ChatCreated, CreateThreadProbe A Teams chat is created; a user probes whether they can create a chat with users in your organization Query 4 below

Query 1 reads the Exchange admin records in the OfficeActivity table that the Microsoft Sentinel Microsoft 365 connector fills, and flags values that weaken auditing:

// Changes to Microsoft 365 audit logging and mailbox auditing, from the Exchange admin records in OfficeActivity.
// Needs the Microsoft 365 data connector with Exchange selected. Parameters holds the cmdlet parameters
// as JSON text (Name and Value pairs); WeakensAuditing flags the values that turn auditing off or add a bypass.
OfficeActivity
| where TimeGenerated > ago(30d)
| where Operation in~ ("Set-AdminAuditLogConfig", "Set-MailboxAuditBypassAssociation", "Set-OrganizationConfig", "Set-Mailbox")
| where Operation in~ ("Set-AdminAuditLogConfig", "Set-MailboxAuditBypassAssociation")
    or Parameters has_any ("AuditDisabled", "AuditEnabled", "AuditOwner", "AuditDelegate", "AuditAdmin", "DefaultAuditSet")
| mv-apply Parameter = todynamic(Parameters) on (
    summarize Values = make_bag(bag_pack(tostring(Parameter.Name), tostring(Parameter.Value))))
| extend Ingestion = tostring(Values.UnifiedAuditLogIngestionEnabled),
         Bypass = tostring(Values.AuditBypassEnabled),
         OrgAuditDisabled = tostring(Values.AuditDisabled)
| extend WeakensAuditing = Ingestion =~ "False" or Bypass =~ "True" or OrgAuditDisabled =~ "True"
| project TimeGenerated, Operation, UserId, ClientIP, Ingestion, Bypass, OrgAuditDisabled, WeakensAuditing, Parameters, ResultStatus
| order by WeakensAuditing desc, TimeGenerated desc

If auditing is turned off, Microsoft says Sentinel can't reach audit data, so the record of that change may be the last one you get. Query 2 catches the silence that follows:

// Workloads whose records stopped arriving in OfficeActivity: auditing turned off, a broken connector or no activity.
// The 6-hour threshold leaves room for the 60 to 90 minutes Microsoft says a record typically takes, with no guaranteed time.
OfficeActivity
| where TimeGenerated > ago(7d)
| summarize LastRecord = max(TimeGenerated), Records = count() by OfficeWorkload
| extend HoursSinceLastRecord = datetime_diff('hour', now(), LastRecord)
| where HoursSinceLastRecord > 6
| order by HoursSinceLastRecord desc

Query 3 runs in Microsoft Defender XDR advanced hunting against CloudAppEvents and lists every Teams admin change, external access changes among them. Microsoft's audit activity list describes TeamsAdminAction without naming its fields, so the query filters on the operation only and returns the raw record for review. In Sentinel, where the connector delivers Teams records, filter OfficeActivity on Operation == "TeamsAdminAction" instead:

// Teams admin changes. TeamsAdminAction is logged when a Teams admin updates, adds or deletes Teams settings or
// configurations with PowerShell, the admin center or the API; TeamsTenantSettingChanged covers org-wide settings
// changed in the Microsoft 365 admin center. Read RawEventData for the setting that changed.
CloudAppEvents
| where Timestamp > ago(30d)
| where Application == "Microsoft Teams"
| where ActionType in ("TeamsAdminAction", "TeamsTenantSettingChanged")
| project Timestamp, ActionType, AccountDisplayName, AccountObjectId, IPAddress, RawEventData
| order by Timestamp desc

Query 4 lists chats started from outside the organization, using the ChatCreated fields that Microsoft Threat Intelligence reads in its hunting queries, and puts help desk or security display names first:

// Teams chats started by someone outside the organization, with the creator's tenant ID.
// Uses the ChatCreated fields that Microsoft Threat Intelligence reads in its Teams help desk hunting queries.
CloudAppEvents
| where Timestamp > ago(7d)
| where Application == "Microsoft Teams"
| where ActionType == "ChatCreated"
| where IsExternalUser == true
| extend CreatorName = tostring(RawEventData.Members[0].DisplayName),
         CreatorUpn = tostring(RawEventData.Members[0].UPN),
         CreatorTenantId = tostring(RawEventData.Members[0].OrganizationId),
         RecipientUpn = tostring(RawEventData.Members[1].UPN),
         ThreadId = tostring(RawEventData.ChatThreadId)
| extend LooksLikeSupport = CreatorName matches regex @"(?i)(help ?desk|service ?desk|support|security)"
| project Timestamp, CreatorName, CreatorUpn, CreatorTenantId, RecipientUpn, LooksLikeSupport, ThreadId
| order by LooksLikeSupport desc, Timestamp desc

Microsoft's activity table says a ChatCreated record is logged only when the chat is created through a Microsoft Graph API call, and that federated chats write it in every participating tenant; Microsoft Threat Intelligence hunts external chats with the same record. An empty result is therefore not proof that no external chat took place. A chat from an unknown tenant followed by an MFA approval, a new device or a remote support session for the same user is the sequence the reports above describe.

Troubleshooting

Most problems come from the wrong PowerShell session, licensing or a list that Teams ignores.

Symptom Cause Fix
UnifiedAuditLogIngestionEnabled is False although auditing is on The command ran in Security & Compliance PowerShell Run it in Exchange Online PowerShell
Audit search returns nothing right after turning auditing on The change can take up to 60 minutes, and events several hours to become searchable Wait, then search again
Search-UnifiedAuditLog returns only 100 records 100 is the default Use -ResultSize (up to 5,000) or -SessionCommand ReturnLargeSet with a -SessionId
E5 tenant keeps only 180 days of some records The acting user has no E5 or Audit (Premium) license, is a guest, or the service isn't covered by the default one-year policy Assign the license or create an audit retention policy
A mailbox still shows AuditEnabled True after setting it to False Mailbox auditing on by default overrides the mailbox setting Expected; use a bypass association only where justified
Set-CsTenantFederationConfiguration -AllowedDomains "partner.example.com" fails The parameter takes domain objects, not strings Use New-CsEdgeDomainPattern and New-CsEdgeAllowList, or -AllowedDomainsAsAList
Blocked domains have no effect An allow list is in effect, or AllowFederatedUsers is False Use one model; keep AllowFederatedUsers True for either list to apply
A partner can't chat although their domain is allowed Their organization doesn't allow yours, or the user's external access policy turns federation off Ask the partner to allow your domain; check EnableFederationAccess on the user's policy
Users on one policy still reach every domain Their custom external access policy allows all external domains Set CommunicationWithExternalOrgs to OrganizationDefault

How Forestall helps

Forestall collects the tenant's Teams External Access Settings, including chat with unmanaged Teams accounts, blocked users and security team managed blocked domains, and shows each object with its risk, exposure point and issues. The Teams Settings object covers org-wide options such as channel email. Both sit in Unified Identities next to Active Directory, Entra ID and Azure objects, and you can open them in the graph. Identity Attack Surface Management gives an agentless map of identities and trust relationships across Active Directory, Entra ID, Azure and Microsoft 365, including services such as Exchange and Teams.

Frequently Asked Questions

Is the Microsoft 365 unified audit log enabled by default?

For most Microsoft 365 enterprise organizations, yes: Microsoft says the unified audit log is on by default, but not for Small and Medium Business licenses such as Microsoft 365 Business Basic, Business Standard and Business Premium, or for unmanaged tenants on free trials of enterprise licenses. Check it with Get-AdminAuditLogConfig | Format-List UnifiedAuditLogIngestionEnabled in Exchange Online PowerShell; True means auditing is on.

Is the unified audit log available in Microsoft 365 Business Standard?

Yes, Microsoft 365 Business Standard has the unified audit log, but it isn't turned on by default. Microsoft lists Business Basic, Business Standard and Business Premium as licenses where an admin must turn on auditing, either from the banner on the Audit page of the Microsoft Purview portal or with Set-AdminAuditLogConfig -UnifiedAuditLogIngestionEnabled $true. Records for users without an E5 or Audit (Premium) license are kept for 180 days.

How long are Microsoft 365 audit logs kept?

As of November 2026, Microsoft 365 Audit (Standard) keeps audit log records for 180 days. For users with an E5 or Audit (Premium) license, Microsoft Entra ID, Exchange, OneDrive and SharePoint records are kept for one year by default, and retention policies can keep other services for up to a year. The 10-Year Audit Log Retention add-on allows up to 10 years.

What is the difference between Teams external access and guest access?

Teams external access, or federation, lets your users chat, call and meet with people who stay in their own Microsoft 365 organization or use an unmanaged Teams account; they can't open your teams or files. Guest access adds the person to your directory as a Microsoft Entra B2B guest, who can join teams and channels and work on shared files. Each has its own settings.

How do I block external users in Microsoft Teams?

To block external users in Microsoft Teams, go to Users > External access in the Teams admin center and choose Allow only specific external domains or Block only specific external domains, or turn on Block specific users from communicating with people in my organization for up to 200 individual users. In PowerShell, set the domain lists with Set-CsTenantFederationConfiguration. An allow list is safer, because the campaigns Microsoft reported used new domains and tenants.

Can attackers still reach users after I restrict external access?

Yes, through channels other than Teams external access. Domain restrictions stop federated chat from tenants you didn't list, but people from blocked domains can still join meetings anonymously if anonymous access is allowed, guests in your tenant can still chat, and email and phone calls are untouched. Keep monitoring Teams admin changes, so nobody quietly reopens external access.

References

Share This Article, Secure Your Friends!

See your identity exposure clearly.

Start with a 1-day Proof of Value in your own environment.