From bb5316d3a0c96fc45f5692a5f2b7c8a2a08496b8 Mon Sep 17 00:00:00 2001 From: Jeremy Finney Date: Sun, 1 Nov 2026 14:00:35 +1300 Subject: [PATCH 01/15] fix(cis): align CIS M365 2.4.x and 8.x checks and guides with v7.0.0 Verify priority account coverage for the Strict preset policy, fail closed on missing data, read the Teams org-wide app settings, check the reporting destination for Teams reports, and align the guides with the CIS remediation. --- .../public/services/exchange/Get-MtExo.ps1 | 4 + ...isStrictPresetForPriorityAccount.Tests.ps1 | 115 ++++++++++++ .../functions/Test-MtCisTeamsChecks.Tests.ps1 | 174 ++++++++++++++++++ tests/cis/Test.CIS.M365.2.4.1.md | 12 +- tests/cis/Test.CIS.M365.2.4.2.md | 14 +- tests/cis/Test.CIS.M365.2.4.2.ps1 | 127 +++++++++++-- tests/cis/Test.CIS.M365.2.4.4.md | 31 ++-- tests/cis/Test.CIS.M365.2.4.4.ps1 | 47 +++-- tests/cis/Test.CIS.M365.8.1.1.md | 54 +++--- tests/cis/Test.CIS.M365.8.1.1.ps1 | 47 +++-- tests/cis/Test.CIS.M365.8.1.2.md | 7 +- tests/cis/Test.CIS.M365.8.2.1.md | 22 ++- tests/cis/Test.CIS.M365.8.2.2.md | 44 ++--- tests/cis/Test.CIS.M365.8.2.2.ps1 | 29 +-- tests/cis/Test.CIS.M365.8.2.3.md | 48 ++--- tests/cis/Test.CIS.M365.8.2.3.ps1 | 33 ++-- tests/cis/Test.CIS.M365.8.2.4.md | 11 +- tests/cis/Test.CIS.M365.8.4.1.md | 40 ++-- tests/cis/Test.CIS.M365.8.4.1.ps1 | 58 +++--- tests/cis/Test.CIS.M365.8.5.1.md | 7 +- tests/cis/Test.CIS.M365.8.5.2.md | 9 +- tests/cis/Test.CIS.M365.8.5.3.md | 36 ++-- tests/cis/Test.CIS.M365.8.5.4.md | 7 +- tests/cis/Test.CIS.M365.8.5.5.md | 7 +- tests/cis/Test.CIS.M365.8.5.6.md | 7 +- tests/cis/Test.CIS.M365.8.5.7.md | 7 +- tests/cis/Test.CIS.M365.8.5.8.md | 7 +- tests/cis/Test.CIS.M365.8.5.9.md | 7 +- tests/cis/Test.CIS.M365.8.6.1.md | 58 ++---- tests/cis/Test.CIS.M365.8.6.1.ps1 | 98 ++++------ 30 files changed, 736 insertions(+), 431 deletions(-) create mode 100644 powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 create mode 100644 powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 diff --git a/powershell/public/services/exchange/Get-MtExo.ps1 b/powershell/public/services/exchange/Get-MtExo.ps1 index f78d5f7209..1baf1534e8 100644 --- a/powershell/public/services/exchange/Get-MtExo.ps1 +++ b/powershell/public/services/exchange/Get-MtExo.ps1 @@ -59,6 +59,10 @@ "EOPProtectionPolicyRule" = "Get-EOPProtectionPolicyRule" "ATPProtectionPolicyRule" = "Get-ATPProtectionPolicyRule" "ProtectionAlert" = "Get-ProtectionAlert" + "TeamsProtectionPolicy" = "Get-TeamsProtectionPolicy" + "TeamsProtectionPolicyRule" = "Get-TeamsProtectionPolicyRule" + "ReportSubmissionPolicy" = "Get-ReportSubmissionPolicy" + "ReportSubmissionRule" = "Get-ReportSubmissionRule" "EXOMailbox" = "Get-EXOMailbox -ResultSize 'Unlimited'" "EXOSharedMailbox" = "Get-EXOMailbox -RecipientTypeDetails 'SharedMailbox' -ResultSize 'Unlimited'" "ArcConfig" = "Get-ArcConfig" diff --git a/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 b/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 new file mode 100644 index 0000000000..920bf6e5f6 --- /dev/null +++ b/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 @@ -0,0 +1,115 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force -WarningAction SilentlyContinue + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name Test-MtCisStrictPresetForPriorityAccount + + # ExchangeOnlineManagement is optional; a stub lets Get-Recipient be mocked when it is not installed. + if (-not (Get-Command Get-Recipient -ErrorAction SilentlyContinue)) { + function global:Get-Recipient { + [CmdletBinding()] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', 'Identity', Justification = 'Stub signature only; Mock binds -Identity from it.')] + param([string] $Identity) + } + $script:removeRecipientStub = $true + } + + function New-StrictRule { + param([hashtable] $Conditions = @{}) + $rule = [ordered]@{ + Identity = 'Strict Preset Security Policy' + State = 'Enabled' + SentTo = $null + SentToMemberOf = $null + RecipientDomainIs = $null + ExceptIfSentTo = $null + ExceptIfSentToMemberOf = $null + ExceptIfRecipientDomainIs = $null + } + foreach ($key in $Conditions.Keys) { $rule[$key] = $Conditions[$key] } + [pscustomobject]$rule + } +} + +AfterAll { + if ($script:removeRecipientStub) { + Remove-Item -Path Function:\Get-Recipient -ErrorAction SilentlyContinue + } +} + +Describe 'Test-MtCisStrictPresetForPriorityAccount' { + BeforeEach { + $script:Result = $null + $script:Rule = New-StrictRule -Conditions @{ SentToMemberOf = @('Priority Accounts') } + $script:VipUsers = @( + [pscustomobject]@{ + Name = 'ceo' + DisplayName = 'Chief Executive' + UserPrincipalName = 'ceo@contoso.com' + WindowsEmailAddress = 'ceo@contoso.com' + ExternalDirectoryObjectId = 'user-ceo' + } + ) + $script:Groups = @{ 'user-ceo' = @([pscustomobject]@{ id = 'group-vip'; displayName = 'Priority Accounts'; mail = 'vips@contoso.com'; mailNickname = 'vips' }) } + + Mock -ModuleName Maester Add-MtTestResultDetail { param($Result) $script:Result = $Result } + Mock -ModuleName Maester Get-MtExo -ParameterFilter { $Request -in 'EOPProtectionPolicyRule', 'ATPProtectionPolicyRule' } { $script:Rule } + Mock -ModuleName Maester Get-MtExo -ParameterFilter { $Request -eq 'VipUser' } { $script:VipUsers } + Mock -ModuleName Maester Invoke-MtGraphRequest { + $id = ($RelativeUri -split '/')[1] + $script:Groups[$id] + } + Mock -ModuleName Maester Get-Recipient { $null } + } + + It 'passes when every priority account is a member of a target group' { + Test-MtCisStrictPresetForPriorityAccount | Should -BeTrue + $script:Result | Should -Match '1 of 1' + } + + It 'resolves SentTo values to the Entra object ID of the priority account' { + $script:Rule = New-StrictRule -Conditions @{ SentTo = @('Chief Exec Mailbox') } + Mock -ModuleName Maester Get-Recipient { [pscustomobject]@{ ExternalDirectoryObjectId = 'user-ceo' } } -ParameterFilter { $Identity -eq 'Chief Exec Mailbox' } + + Test-MtCisStrictPresetForPriorityAccount | Should -BeTrue + } + + It 'includes subdomains of a RecipientDomainIs domain' { + $script:VipUsers[0].WindowsEmailAddress = 'ceo@exec.contoso.com' + $script:Rule = New-StrictRule -Conditions @{ RecipientDomainIs = @('contoso.com') } + + Test-MtCisStrictPresetForPriorityAccount | Should -BeTrue + } + + It 'fails when a priority account matches an exception' { + $script:Rule = New-StrictRule -Conditions @{ SentToMemberOf = @('Priority Accounts'); ExceptIfSentTo = @('ceo@contoso.com') } + + Test-MtCisStrictPresetForPriorityAccount | Should -BeFalse + $script:Result | Should -Match 'ceo@contoso.com' + } + + It 'requires a priority account to meet every recipient condition that is set' { + $script:Rule = New-StrictRule -Conditions @{ SentTo = @('someone.else@contoso.com'); RecipientDomainIs = @('contoso.com') } + + Test-MtCisStrictPresetForPriorityAccount | Should -BeFalse + } + + It 'fails when the rule has no recipient conditions' { + $script:Rule = New-StrictRule + + Test-MtCisStrictPresetForPriorityAccount | Should -BeFalse + $script:Result | Should -Match 'All recipients \(no conditions\)' + } + + It 'fails when no priority accounts are tagged' { + $script:VipUsers = @() + + Test-MtCisStrictPresetForPriorityAccount | Should -BeFalse + $script:Result | Should -Match 'No users are tagged as priority accounts' + } + + It 'fails when a rule is disabled' { + $script:Rule = New-StrictRule -Conditions @{ SentToMemberOf = @('Priority Accounts'); State = 'Disabled' } + + Test-MtCisStrictPresetForPriorityAccount | Should -BeFalse + } +} diff --git a/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 b/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 new file mode 100644 index 0000000000..f85655bf52 --- /dev/null +++ b/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 @@ -0,0 +1,174 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force -WarningAction SilentlyContinue + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name Test-MtCisZAP, Test-MtCisThirdPartyFileSharing, Test-MtCisThirdPartyAndCustomApps, Test-MtCisTeamsReportSecurityConcerns + + # MicrosoftTeams is optional; stubs let its cmdlets be mocked when it is not installed. + $script:stubs = @() + foreach ($name in 'Get-CsTeamsClientConfiguration', 'Get-CsTeamsMessagingPolicy', 'Get-M365UnifiedTenantSettings', 'Get-CsTeamsSettingsCustomApp') { + if (-not (Get-Command $name -ErrorAction SilentlyContinue)) { + Set-Item -Path "function:global:$name" -Value { + [CmdletBinding()] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', 'Identity', Justification = 'Stub signature only; Mock binds -Identity from it.')] + param([string] $Identity) + } + $script:stubs += $name + } + } +} + +AfterAll { + foreach ($name in $script:stubs) { + Remove-Item -Path "Function:\$name" -ErrorAction SilentlyContinue + } +} + +Describe 'Test-MtCisZAP' { + BeforeEach { + $script:Result = $null + $script:Policies = @([pscustomobject]@{ Name = 'Teams Protection Policy'; ZapEnabled = $true }) + $script:Rules = @() + Mock -ModuleName Maester Add-MtTestResultDetail { param($Result) $script:Result = $Result } + Mock -ModuleName Maester Get-MtExo -ParameterFilter { $Request -eq 'TeamsProtectionPolicy' } { $script:Policies } + Mock -ModuleName Maester Get-MtExo -ParameterFilter { $Request -eq 'TeamsProtectionPolicyRule' } { $script:Rules } + } + + It 'passes when ZAP is on' { + Test-MtCisZAP | Should -BeTrue + $script:Result | Should -Match 'No participants are excluded' + } + + It 'fails when ZAP is off' { + $script:Policies[0].ZapEnabled = $false + Test-MtCisZAP | Should -BeFalse + } + + It 'fails when no Teams protection policy is returned' { + $script:Policies = @() + Test-MtCisZAP | Should -BeFalse + $script:Result | Should -Match 'No Teams protection policy was returned' + } + + It 'lists the exclusions for review' { + $script:Rules = @([pscustomobject]@{ ExceptIfSentTo = @('research@contoso.com'); ExceptIfSentToMemberOf = $null; ExceptIfRecipientDomainIs = @('research.contoso.com') }) + Test-MtCisZAP | Should -BeTrue + $script:Result | Should -Match 'ExceptIfSentTo \| research@contoso.com' + $script:Result | Should -Match 'ExceptIfRecipientDomainIs \| research.contoso.com' + } +} + +Describe 'Test-MtCisThirdPartyFileSharing' { + BeforeEach { + $script:Result = $null + $script:Config = [pscustomobject]@{ AllowDropBox = $false; AllowBox = $false; AllowGoogleDrive = $false; AllowShareFile = $false; AllowEgnyte = $false } + Mock -ModuleName Maester Add-MtTestResultDetail { param($Result) $script:Result = $Result } + Mock -ModuleName Maester Get-CsTeamsClientConfiguration { $script:Config } + } + + It 'passes when every provider is off' { + Test-MtCisThirdPartyFileSharing | Should -BeTrue + } + + It 'fails when a provider that is not approved is on' { + $script:Config.AllowBox = $true + Test-MtCisThirdPartyFileSharing | Should -BeFalse + } + + It 'passes when only approved providers are on' { + $script:Config.AllowBox = $true + Test-MtCisThirdPartyFileSharing -ApprovedProviders Box | Should -BeTrue + } + + It 'fails when the client configuration is not returned' { + $script:Config = $null + Test-MtCisThirdPartyFileSharing | Should -BeFalse + } +} + +Describe 'Test-MtCisThirdPartyAndCustomApps' { + BeforeEach { + $script:Result = $null + $script:TenantSettings = @( + [pscustomobject]@{ SettingName = 'DefaultApp'; SettingValue = 'All' } + [pscustomobject]@{ SettingName = 'GlobalApp'; SettingValue = 'None' } + [pscustomobject]@{ SettingName = 'PrivateApp'; SettingValue = 'None' } + ) + $script:CustomApp = [pscustomobject]@{ IsSideloadedAppsInteractionEnabled = $false } + Mock -ModuleName Maester Add-MtTestResultDetail { param($Result) $script:Result = $Result } + Mock -ModuleName Maester Get-M365UnifiedTenantSettings { $script:TenantSettings } + Mock -ModuleName Maester Get-CsTeamsSettingsCustomApp { $script:CustomApp } + } + + It 'passes when third-party apps, custom apps and custom apps in preview are off' { + Test-MtCisThirdPartyAndCustomApps | Should -BeTrue + } + + It 'fails when third-party apps are available by default' { + $script:TenantSettings[1].SettingValue = 'All' + Test-MtCisThirdPartyAndCustomApps | Should -BeFalse + } + + It 'fails when users can interact with custom apps in preview' { + $script:CustomApp.IsSideloadedAppsInteractionEnabled = $true + Test-MtCisThirdPartyAndCustomApps | Should -BeFalse + } + + It 'fails when the settings are not returned' { + $script:TenantSettings = @() + $script:CustomApp = $null + Test-MtCisThirdPartyAndCustomApps | Should -BeFalse + $script:Result | Should -Match 'Not found' + } +} + +Describe 'Test-MtCisTeamsReportSecurityConcerns' { + BeforeEach { + $script:Result = $null + $script:MessagingPolicy = [pscustomobject]@{ AllowSecurityEndUserReporting = $true } + $script:Policy = [pscustomobject]@{ + EnableReportToMicrosoft = $false + ReportChatMessageEnabled = $false + ReportChatMessageToCustomizedAddressEnabled = $true + ReportJunkToCustomizedAddress = $true + ReportNotJunkToCustomizedAddress = $true + ReportPhishToCustomizedAddress = $true + ReportJunkAddresses = @('soc@contoso.com') + ReportNotJunkAddresses = @('soc@contoso.com') + ReportPhishAddresses = @('soc@contoso.com') + } + $script:Rules = @([pscustomobject]@{ Name = 'DefaultReportSubmissionRule'; State = 'Enabled'; SentTo = @('soc@contoso.com') }) + Mock -ModuleName Maester Add-MtTestResultDetail { param($Result) $script:Result = $Result } + Mock -ModuleName Maester Get-CsTeamsMessagingPolicy { $script:MessagingPolicy } + Mock -ModuleName Maester Get-MtExo -ParameterFilter { $Request -eq 'ReportSubmissionPolicy' } { $script:Policy } + Mock -ModuleName Maester Get-MtExo -ParameterFilter { $Request -eq 'ReportSubmissionRule' } { $script:Rules } + } + + It 'passes when reports go only to the reporting mailbox' { + Test-MtCisTeamsReportSecurityConcerns | Should -BeTrue + } + + It 'fails when reported messages are also sent to Microsoft' { + $script:Policy.EnableReportToMicrosoft = $true + Test-MtCisTeamsReportSecurityConcerns | Should -BeFalse + $script:Result | Should -Match 'EnableReportToMicrosoft \| True \| False \| ❌ Fail' + } + + It 'fails when the report submission rule is missing or disabled' { + $script:Rules = @([pscustomobject]@{ Name = 'DefaultReportSubmissionRule'; State = 'Disabled'; SentTo = @('soc@contoso.com') }) + Test-MtCisTeamsReportSecurityConcerns | Should -BeFalse + + $script:Rules = @() + Test-MtCisTeamsReportSecurityConcerns | Should -BeFalse + } + + It 'fails when Teams reporting is not set' { + $script:MessagingPolicy = [pscustomobject]@{ AllowSecurityEndUserReporting = $null } + Test-MtCisTeamsReportSecurityConcerns | Should -BeFalse + } + + It 'fails when no report submission policy is returned' { + $script:Policy = $null + Test-MtCisTeamsReportSecurityConcerns | Should -BeFalse + $script:Result | Should -Match 'No report submission policy was returned' + } +} diff --git a/tests/cis/Test.CIS.M365.2.4.1.md b/tests/cis/Test.CIS.M365.2.4.1.md index 2b33891c16..e1022155c2 100644 --- a/tests/cis/Test.CIS.M365.2.4.1.md +++ b/tests/cis/Test.CIS.M365.2.4.1.md @@ -7,9 +7,15 @@ The test needs the protection to be on, at least one priority account, and an en #### Remediation action 1. Sign in to the [Microsoft Defender portal](https://security.microsoft.com). -2. Go to **Settings** > **Email & collaboration** > **Priority account protection** and turn on **Priority account protection**. -3. Go to **Settings** > **Email & collaboration** > **User tags**, open **Priority account** and add the accounts to tag. -4. Go to **Email & collaboration** > **Policies & rules** > **Alert policy** and create alerts for malware and phishing that use the **Priority account** user tag, a severity of **High**, the filter for inbound mail and a notification recipient. +2. Go to **System** > **Settings** > **Email & collaboration** > [**Priority account protection**](https://security.microsoft.com/securitysettings/priorityAccountProtection) and turn on **Priority account protection**. +3. Select **User tags**, select the **Priority account** tag and select **Edit**. Add the users or groups that are your priority accounts (groups are recommended), then select **Next** and **Submit**. Repeat for any other tags you use, such as Finance or HR. +4. Go to **Email & collaboration** > **Policies & rules** > [**Alert policy**](https://security.microsoft.com/alertpoliciesv2) and select **New alert policy**. +5. Enter a name and description, set **Severity** to **High** and **Category** to **Threat management**. +6. Set **Activity is** to **Detected malware in an email message** and the mail direction to **Inbound**. +7. Select **Add condition** > **User: recipient tags are** and select **Priority account**. +8. Select **Every time an activity matches the rule**, select **Next** and add the recipients who should be notified. +9. Select **Yes, turn it on right away** and **Submit**. +10. Repeat steps 4 to 9 with **Activity is** set to **Phishing email detected at time of delivery**. #### Related links diff --git a/tests/cis/Test.CIS.M365.2.4.2.md b/tests/cis/Test.CIS.M365.2.4.2.md index 51f74daa74..e7e2c0e1ad 100644 --- a/tests/cis/Test.CIS.M365.2.4.2.md +++ b/tests/cis/Test.CIS.M365.2.4.2.md @@ -1,21 +1,25 @@ The Strict preset security policy applies its strongest protections to the recipients selected for Exchange Online Protection and Defender for Office 365. -Microsoft maintains the Standard and Strict preset security policies and updates them as threats change. Strict has the most aggressive settings for spam, phishing, malware, Safe Links and Safe Attachments, which suits the accounts that are most likely to be targeted and most valuable to compromise. +Executives, finance staff and administrators are the usual targets of spear phishing and whaling. Microsoft maintains the Standard and Strict preset security policies and updates them as threats change. Strict has the most aggressive settings for spam, phishing, malware, spoofing, impersonation, Safe Links and Safe Attachments, which suits the accounts that are most likely to be targeted and most valuable to compromise. -When enabled, a rule with no recipient conditions applies to everyone, including priority accounts. This test follows the CIS PowerShell audit procedure literally: it requires at least one explicit recipient condition on each enabled rule to pass. It does not verify that the selected recipients actually include priority accounts. To meet the audit criterion while targeting those accounts, add a group containing priority accounts to the rule's `SentToMemberOf` condition. Microsoft Defender for Office 365 licences are required. +The test reads the Strict preset rules for Exchange Online Protection and for Defender for Office 365. Each rule must be on and have at least one recipient target, following the CIS PowerShell audit procedure. The test does not verify that the selected recipients include priority accounts. To ensure those accounts are covered, add a group containing them to each rule. Microsoft Defender for Office 365 licences are required. #### Remediation action 1. Sign in to the [Microsoft Defender portal](https://security.microsoft.com). 2. Go to **Email & collaboration** > **Policies & rules** > **Threat policies** > [**Preset security policies**](https://security.microsoft.com/presetSecurityPolicies). -3. Under **Strict protection**, select **Manage protection settings**. -4. Apply the policy to **Specific recipients** and add a group containing priority accounts so each rule has a `SentToMemberOf` condition. -5. Finish the wizard and turn the policy on. +3. Turn on **Strict protection** and select **Manage protection settings**. +4. On **Apply Exchange Online Protection**, select **Specific recipients** and add the users or groups that are your priority accounts. +5. On **Apply Defender for Office 365 protection**, select **Specific recipients** and add the same users or groups. +6. On **Add email addresses to flag when impersonated by attackers**, add the internal and external senders, including your priority accounts, that attackers may impersonate. +7. On **Add domains to flag when impersonated by attackers**, add the domains of key partners. Your accepted domains are protected automatically. +8. On **Review and confirm your changes**, select **Confirm**. #### Related links * [Microsoft Defender portal - Preset security policies](https://security.microsoft.com/presetSecurityPolicies) * [Preset security policies in EOP and Microsoft Defender for Office 365](https://learn.microsoft.com/defender-office-365/preset-security-policies) +* [Security recommendations for priority accounts](https://learn.microsoft.com/defender-office-365/priority-accounts-security-recommendations) * [CIS Microsoft 365 Foundations Benchmark v7.0.0 - 2.4.2](https://www.cisecurity.org/benchmark/microsoft_365) diff --git a/tests/cis/Test.CIS.M365.2.4.2.ps1 b/tests/cis/Test.CIS.M365.2.4.2.ps1 index 7e1c7be3c3..30d3f659c8 100644 --- a/tests/cis/Test.CIS.M365.2.4.2.ps1 +++ b/tests/cis/Test.CIS.M365.2.4.2.ps1 @@ -1,16 +1,16 @@ function Test-MtCisStrictPresetForPriorityAccount { <# .SYNOPSIS - Checks that both Strict preset security policy rules are enabled and have an explicit recipient condition. + Checks that both Strict preset security policy rules are enabled and apply to every priority account. .DESCRIPTION - Checks that both the Exchange Online Protection and the Defender for Office 365 rules of the Strict preset security policy are enabled and have at least one explicit recipient condition. A rule with no recipient conditions applies to all recipients, including priority accounts, but this test follows the CIS PowerShell audit procedure literally and requires an explicit condition to pass. It does not verify that the selected recipients are priority accounts; add a priority-account group to SentToMemberOf. + Checks that both the Exchange Online Protection and the Defender for Office 365 rules of the Strict preset security policy are enabled, have at least one recipient condition (SentTo, SentToMemberOf or RecipientDomainIs), and that every user tagged as a priority account meets those conditions and is not excluded by an exception. CIS Microsoft 365 Foundations Benchmark v7.0.0 (2.4.2, L1) .EXAMPLE Test-MtCisStrictPresetForPriorityAccount - Returns true if both Strict preset security policy rules are enabled and have an explicit recipient condition. + Returns true if both Strict preset security policy rules are enabled and apply to every priority account. .LINK https://maester.dev/docs/tests/CIS.M365.2.4.2 @@ -27,7 +27,7 @@ ImplementationCost = 'Low', Mitre = 'T1566', Control = ('cis-m365:2.4.2', 'nist-800-53-r5:SI-4(5)'), - Service = 'ExchangeOnline', + Service = ('ExchangeOnline', 'Graph'), License = 'ATP_ENTERPRISE', Author = 'JeremyFinney-lgtm' )] @@ -35,41 +35,128 @@ [OutputType([bool])] param() - Write-Verbose 'Getting preset security policy rules...' + Write-Verbose 'Getting preset security policy rules and priority accounts...' $eopRule = @(Get-MtExo -Request EOPProtectionPolicyRule) | Where-Object { $_.Identity -eq 'Strict Preset Security Policy' } | Select-Object -First 1 $atpRule = @(Get-MtExo -Request ATPProtectionPolicyRule) | Where-Object { $_.Identity -eq 'Strict Preset Security Policy' } | Select-Object -First 1 + $rules = @( + [pscustomobject]@{ Name = 'Exchange Online Protection'; Rule = $eopRule } + [pscustomobject]@{ Name = 'Defender for Office 365'; Rule = $atpRule } + ) + $vipUsers = @(Get-MtExo -Request VipUser) - $report = foreach ($entry in @(@{ Name = 'Exchange Online Protection'; Rule = $eopRule }, @{ Name = 'Defender for Office 365'; Rule = $atpRule })) { + $usesGroups = @($rules.Rule | Where-Object { $_ } | Where-Object { + @($_.SentToMemberOf | Where-Object { $_ }).Count -gt 0 -or @($_.ExceptIfSentToMemberOf | Where-Object { $_ }).Count -gt 0 + }).Count -gt 0 + + # Rule values can be names, addresses or GUIDs, so each one is also resolved to its Entra object ID. + $recipientIds = @{} + $resolveIds = { + param([object[]] $Values) + foreach ($value in @($Values | Where-Object { $_ })) { + $key = "$value" + if (-not $recipientIds.ContainsKey($key)) { + $recipient = Get-Recipient -Identity $key -ErrorAction SilentlyContinue | Select-Object -First 1 + $recipientIds[$key] = "$($recipient.ExternalDirectoryObjectId)" + } + $key + if ($recipientIds[$key]) { $recipientIds[$key] } + } + } + $matchesAny = { + param([object[]] $Candidates, $Set) + @($Candidates | Where-Object { $_ -and $Set.Contains("$_") }).Count -gt 0 + } + $matchesDomain = { + param([object[]] $Domains, [string] $Domain) + @($Domains | Where-Object { $_ -and ($Domain -eq "$_" -or $Domain -like "*.$_") }).Count -gt 0 + } + + $priorityAccounts = @(foreach ($vip in $vipUsers) { + $keys = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + foreach ($value in @($vip.Name, $vip.DisplayName, $vip.UserPrincipalName, $vip.WindowsEmailAddress, $vip.Identity, $vip.DistinguishedName, $vip.ExternalDirectoryObjectId, $vip.Guid)) { + if ("$value") { $null = $keys.Add("$value") } + } + $groupKeys = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + if ($usesGroups -and $vip.ExternalDirectoryObjectId) { + $groups = @(Invoke-MtGraphRequest -ApiVersion 'v1.0' -RelativeUri "users/$($vip.ExternalDirectoryObjectId)/transitiveMemberOf/microsoft.graph.group" -Select @('id', 'displayName', 'mail', 'mailNickname')) + foreach ($group in $groups) { + foreach ($value in @($group.id, $group.displayName, $group.mail, $group.mailNickname)) { + if ("$value") { $null = $groupKeys.Add("$value") } + } + } + } + $address = if ($vip.WindowsEmailAddress) { "$($vip.WindowsEmailAddress)" } else { "$($vip.UserPrincipalName)" } + [pscustomobject]@{ + Name = if ($vip.UserPrincipalName) { "$($vip.UserPrincipalName)" } else { "$($vip.Name)" } + Keys = $keys + GroupKeys = $groupKeys + Domain = ($address -split '@')[-1] + } + }) + + # Different recipient conditions of a preset rule are combined with AND, and any exception excludes the recipient. + $isCovered = { + param($Rule, $Account) + $conditions = @() + if (@($Rule.SentTo | Where-Object { $_ }).Count -gt 0) { + $conditions += & $matchesAny (& $resolveIds $Rule.SentTo) $Account.Keys + } + if (@($Rule.SentToMemberOf | Where-Object { $_ }).Count -gt 0) { + $conditions += & $matchesAny (& $resolveIds $Rule.SentToMemberOf) $Account.GroupKeys + } + if (@($Rule.RecipientDomainIs | Where-Object { $_ }).Count -gt 0) { + $conditions += & $matchesDomain $Rule.RecipientDomainIs $Account.Domain + } + $excluded = (& $matchesAny (& $resolveIds $Rule.ExceptIfSentTo) $Account.Keys) -or + (& $matchesAny (& $resolveIds $Rule.ExceptIfSentToMemberOf) $Account.GroupKeys) -or + (& $matchesDomain $Rule.ExceptIfRecipientDomainIs $Account.Domain) + $conditions.Count -gt 0 -and $conditions -notcontains $false -and -not $excluded + } + + $report = foreach ($entry in $rules) { $rule = $entry.Rule $hasTargets = @($rule.SentTo | Where-Object { $_ }).Count -gt 0 -or @($rule.SentToMemberOf | Where-Object { $_ }).Count -gt 0 -or @($rule.RecipientDomainIs | Where-Object { $_ }).Count -gt 0 - $scope = if (-not $rule) { 'Rule not found' } elseif ($hasTargets) { 'Explicit recipient condition' } else { 'All recipients (no conditions)' } + $scope = if (-not $rule) { 'Rule not found' } elseif ($hasTargets) { 'Specific recipients' } else { 'All recipients (no conditions)' } + $uncovered = if ($rule -and $hasTargets) { @($priorityAccounts | Where-Object { -not (& $isCovered $rule $_) }) } else { $priorityAccounts } [pscustomobject]@{ Component = $entry.Name - State = if ($rule) { $rule.State } else { 'Not found' } - Scope = $scope - Pass = $null -ne $rule -and $rule.State -eq 'Enabled' -and $hasTargets + State = if ($rule) { $rule.State } else { 'Not found' } + Scope = $scope + Covered = "$($priorityAccounts.Count - $uncovered.Count) of $($priorityAccounts.Count)" + Uncovered = @($uncovered | ForEach-Object { $_.Name }) + Pass = $null -ne $rule -and $rule.State -eq 'Enabled' -and $hasTargets -and $priorityAccounts.Count -gt 0 -and $uncovered.Count -eq 0 } } $testResult = @($report | Where-Object { -not $_.Pass }).Count -eq 0 - $passText = 'The Strict preset security policy is enabled and applied to recipients.' - $failText = 'The Strict preset security policy is missing or disabled, or one or more rules lack the explicit recipient condition required by the CIS audit.' - $scopeNote = if (@($report | Where-Object { $_.Scope -eq 'All recipients (no conditions)' }).Count -gt 0) { - "`n`nNote: When enabled, a rule with no recipient conditions applies to everyone, including priority accounts. The CIS 2.4.2 PowerShell audit requires an explicit recipient condition to pass. Add a group containing priority accounts to SentToMemberOf to meet that criterion.`n`n" - } else { - '' + $passText = 'The Strict preset security policy is enabled and applies to every priority account.' + $failText = 'The Strict preset security policy is missing or disabled, has no recipient condition, or does not apply to every priority account.' + $notes = '' + if ($priorityAccounts.Count -eq 0) { + $notes += "`n`nNo users are tagged as priority accounts. Tag them with the **Priority account** user tag (CIS 2.4.1), then add them to the Strict preset security policy." + } + if (@($report | Where-Object { $_.Scope -eq 'All recipients (no conditions)' }).Count -gt 0) { + $notes += "`n`nA rule with no recipient conditions applies to everyone, but the CIS 2.4.2 audit requires the rule to name the priority accounts. Add a group that contains the priority accounts as a recipient condition." } - $resultMd = "| Component | Rule state | Scope | Result |`n" - $resultMd += "| --- | --- | --- | --- |`n" + $resultMd = "| Component | Rule state | Recipients | Priority accounts covered | Result |`n" + $resultMd += "| --- | --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Component) | $($row.State) | $($row.Scope) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultMd += "| $($row.Component) | $($row.State) | $($row.Scope) | $($row.Covered) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + } + $missing = @($report | Where-Object { $_.Uncovered.Count -gt 0 -and $_.Scope -eq 'Specific recipients' }) + if ($missing.Count -gt 0) { + $resultMd += "`n| Component | Priority accounts not covered |`n" + $resultMd += "| --- | --- |`n" + foreach ($row in $missing) { + $resultMd += "| $($row.Component) | $($row.Uncovered -join ', ') |`n" + } } if ($testResult) { $testResultMarkdown = "Well done. $passText`n`n%TestResult%" } else { - $testResultMarkdown = "$failText$scopeNote`n`n%TestResult%" + $testResultMarkdown = "$failText$notes`n`n%TestResult%" } $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $resultMd diff --git a/tests/cis/Test.CIS.M365.2.4.4.md b/tests/cis/Test.CIS.M365.2.4.4.md index 0f1e2baf85..9652ebcd44 100644 --- a/tests/cis/Test.CIS.M365.2.4.4.md +++ b/tests/cis/Test.CIS.M365.2.4.4.md @@ -1,38 +1,33 @@ -2.4.4 (L1) Ensure Zero-hour auto purge for Microsoft Teams is on +Zero-hour auto purge (ZAP) for Microsoft Teams is turned on. -Zero-hour auto purge (ZAP) is a protection feature that retroactively detects and neutralizes malware and high confidence phishing. When ZAP for Teams protection blocks a message, the message is blocked for everyone in the chat. The initial block happens right after delivery, but ZAP occurs up to 48 hours after delivery. +ZAP retroactively detects and blocks malware and high confidence phishing in Teams chats and channels. A message can be harmless when it's delivered and weaponized later, or a new signature can identify it after delivery. ZAP blocks such a message for everyone in the chat up to 48 hours after delivery. As with any anti-malware or anti-phishing protection, false positives can occur. -#### Rationale - -ZAP is intended to protect users that have received zero-day malware messages or content that is weaponized after being delivered to users. It does this by continually monitoring spam and malware signatures taking automated retroactive action on messages that have already been delivered. - -#### Impact - -As with any anti-malware or anti-phishing product, false positives may occur +The test passes when every Teams protection policy has ZAP turned on, and fails when no policy is returned. It also lists the participants excluded from Teams protection, which CIS asks you to review. The test runs on tenants with Microsoft Defender for Office 365 Plan 2. #### Remediation action -To enable Zero-hour auto purge for Microsoft Teams: - -1. Navigate to [Microsoft 365 Defender](https://security.microsoft.com) -2. Click to expand **System** select **Settings** > **Email & collaboration** > **Microsoft Teams protection** +1. Sign in to the [Microsoft Defender portal](https://security.microsoft.com). +2. Go to **System** > **Settings** > **Email & collaboration** > [**Microsoft Teams protection**](https://security.microsoft.com/securitysettings/teamsProtectionPolicy). 3. Set **Zero-hour auto purge (ZAP)** to **On (Default)**. +4. Under **Exclude these participants**, review the exclusions and remove any that are not justified. ##### PowerShell 1. Connect to Exchange Online using `Connect-ExchangeOnline`. -2. Run the following cmdlet: +2. Run the following command: ```powershell Set-TeamsProtectionPolicy -Identity "Teams Protection Policy" -ZapEnabled $true ``` +3. Review the exclusions with `Get-TeamsProtectionPolicyRule | Format-List ExceptIf*`. + #### Related links -* [Microsoft 365 Admin Center](https://admin.microsoft.com) -* [Zero-hour auto purge (ZAP) in Microsoft Teams](https://learn.microsoft.com/defender-office-365/zero-hour-auto-purge?view=o365-worldwide#zero-hour-auto-purge-zap-in-microsoft-teams) -* [Configure ZAP for Teams protection in Defender for Office 365](https://learn.microsoft.com/defender-office-365/mdo-support-teams-about?view=o365-worldwide#configure-zap-for-teams-protection-in-defender-for-office-365-plan-2) -* [CIS Microsoft 365 Foundations Benchmark v7.0.0 - Page 157](https://www.cisecurity.org/benchmark/microsoft_365) +* [Microsoft Defender portal - Microsoft Teams protection](https://security.microsoft.com/securitysettings/teamsProtectionPolicy) +* [Zero-hour auto purge (ZAP) in Microsoft Teams](https://learn.microsoft.com/defender-office-365/zero-hour-auto-purge#zero-hour-auto-purge-zap-in-microsoft-teams) +* [Configure ZAP for Teams protection in Defender for Office 365](https://learn.microsoft.com/defender-office-365/mdo-support-teams-about#configure-zap-for-teams-protection-in-defender-for-office-365-plan-2) +* [CIS Microsoft 365 Foundations Benchmark v7.0.0 - 2.4.4](https://www.cisecurity.org/benchmark/microsoft_365) %TestResult% diff --git a/tests/cis/Test.CIS.M365.2.4.4.ps1 b/tests/cis/Test.CIS.M365.2.4.4.ps1 index 2313413431..97ff6bc910 100644 --- a/tests/cis/Test.CIS.M365.2.4.4.ps1 +++ b/tests/cis/Test.CIS.M365.2.4.4.ps1 @@ -37,27 +37,48 @@ [OutputType([bool])] param() - Write-Verbose 'Get TeamsProtectionPolicy' - $teamsProtectionPolicy = Get-TeamsProtectionPolicy | Select-Object ZapEnabled + Write-Verbose 'Getting the Teams protection policy and rule' + $policies = @(Get-MtExo -Request TeamsProtectionPolicy) + $rules = @(Get-MtExo -Request TeamsProtectionPolicyRule) - Write-Verbose 'Add policy to result if ZAP is not enabled' - $result = $teamsProtectionPolicy | Where-Object { $_.ZapEnabled -ne 'True' } + $testResult = $policies.Count -gt 0 -and @($policies | Where-Object { $_.ZapEnabled -ne $true }).Count -eq 0 + + $exclusions = foreach ($rule in $rules) { + foreach ($property in 'ExceptIfSentTo', 'ExceptIfSentToMemberOf', 'ExceptIfRecipientDomainIs') { + $values = @($rule.$property | Where-Object { $_ }) + if ($values.Count -gt 0) { + [pscustomobject]@{ Exception = $property; Values = $values -join ', ' } + } + } + } - $testResult = ($result | Measure-Object).Count -eq 0 if ($testResult) { - $testResultMarkdown = "Well done. Your tenant has Zero-hour auto purge (ZAP) enabled for Microsoft Teams:`n`n%TestResult%" + $testResultMarkdown = "Well done. Your tenant has Zero-hour auto purge (ZAP) enabled for Microsoft Teams.`n`n%TestResult%" + } elseif ($policies.Count -eq 0) { + $testResultMarkdown = "No Teams protection policy was returned, so Zero-hour auto purge (ZAP) for Microsoft Teams could not be confirmed.`n`n%TestResult%" } else { - $testResultMarkdown = "Your tenant does not have Zero-hour auto purge (ZAP) enabled for Microsoft Teams:`n`n%TestResult%" + $testResultMarkdown = "Your tenant does not have Zero-hour auto purge (ZAP) enabled for Microsoft Teams.`n`n%TestResult%" } - $resultMd = "| Zero-hour auto purge (ZAP) |`n" - $resultMd += "| --- |`n" - if ($testResult) { - $itemResult = '✅ Enabled' + $resultMd = "| Policy | Zero-hour auto purge (ZAP) | Result |`n" + $resultMd += "| --- | --- | --- |`n" + foreach ($policy in $policies) { + $resultMd += "| $($policy.Name) | $($policy.ZapEnabled) | $(if ($policy.ZapEnabled -eq $true) { '✅ Pass' } else { '❌ Fail' }) |`n" + } + if ($policies.Count -eq 0) { + $resultMd += "| Not found | | ❌ Fail |`n" + } + + if (@($exclusions).Count -gt 0) { + $resultMd += "`nReview these exclusions and confirm that each one is justified. ZAP does not act on Teams messages for these participants.`n`n" + $resultMd += "| Exclusion | Participants |`n" + $resultMd += "| --- | --- |`n" + foreach ($exclusion in $exclusions) { + $resultMd += "| $($exclusion.Exception) | $($exclusion.Values) |`n" + } } else { - $itemResult = '❌ Not Enabled' + $resultMd += "`nNo participants are excluded from Teams protection.`n" } - $resultMd += "| $($itemResult) |`n" $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $resultMd diff --git a/tests/cis/Test.CIS.M365.8.1.1.md b/tests/cis/Test.CIS.M365.8.1.1.md index 25de809a8b..d5b2605613 100644 --- a/tests/cis/Test.CIS.M365.8.1.1.md +++ b/tests/cis/Test.CIS.M365.8.1.1.md @@ -1,50 +1,38 @@ -8.1.1 (L2) Ensure external file sharing in Teams is enabled for only approved cloud storage services +Teams lets users share files only through third-party cloud storage services that the organization has approved. -Microsoft Teams enables collaboration via file sharing. This file sharing is conducted within Teams, using SharePoint Online, by default; however, third-party cloud services are allowed as well. +Teams stores and shares files in SharePoint and OneDrive by default, but it can also open files from Dropbox, Box, Google Drive, Citrix ShareFile and Egnyte. Files in those services are outside the organization's data protection, retention and sharing controls, and the services may not meet the organization's security standards. Turning off the services that aren't approved keeps users on storage the organization governs. Users who rely on another provider lose access to it from Teams. ->Note: Skype for business is deprecated as of July 31, 2021 although these settings may still be valid for a period of time. See the link in the references section for more information. - -#### Rationale - -Ensuring that only authorized cloud storage providers are accessible from Teams will -help to dissuade the use of non-approved storage providers. - -#### Impact - -The impact associated with this change is highly dependent upon current practices in the tenant. If users do not use other storage providers, then minimal impact is likely. However, if users do regularly utilize providers outside of the tenant this will affect their ability to continue to do so. +The test reads the Global Teams client configuration and fails when a service is on that the organization has not approved. List approved services in the `ApprovedProviders` parameter (`Dropbox`, `Box`, `GoogleDrive`, `ShareFile`, `Egnyte`); by default none are approved. #### Remediation action -To change third-party cloud services using the UI: - -1. Navigate to **Microsoft Teams admin center** [https://admin.teams.microsoft.com](https://admin.teams.microsoft.com). -2. Select **Settings & policies > Global (Org-wide default) settings.** -3. Click **Teams** to open the **Teams settings** section. -4. Under files set storages providers to **Off** unless they have first been authorized by the organization. +1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). +2. Go to **Settings & policies** > [**Global (Org-wide default) settings**](https://admin.teams.microsoft.com/one-policy/settings) and select **Teams** to open the **Teams settings** section. +3. Under **Files**, turn off each storage provider that the organization has not authorized. +4. Select **Save**. -To change third-party cloud services using PowerShell: +##### PowerShell -1. Connect to Teams using **Connect-MicrosoftTeams**. -2. Run the following PowerShell command to disable external providers that are not authorized. (the example disables Citrix Files, DropBox, Box, Google Drive and Egnyte) +1. Connect to Teams PowerShell using `Connect-MicrosoftTeams`. +2. Run the following command, leaving out any provider that the organization has authorized: ```powershell -$Params = @{ - Identity = 'Global' - AllowGoogleDrive = $false - AllowShareFile = $false - AllowBox = $false - AllowDropBox = $false - AllowEgnyte = $false +$params = @{ + Identity = 'Global' + AllowGoogleDrive = $false + AllowShareFile = $false + AllowBox = $false + AllowDropBox = $false + AllowEgnyte = $false } -Set-CsTeamsClientConfiguration @Params +Set-CsTeamsClientConfiguration @params ``` #### Related links -* [Microsoft 365 Admin Center](https://admin.microsoft.com) -* [Microsoft Teams Admin Center](https://admin.teams.microsoft.com). -* [Manage Teams with Microsoft Teams PowerShell](https://learn.microsoft.com/microsoftteams/teams-powershell-managing-teams) -* [CIS Microsoft 365 Foundations Benchmark v7.0.0 - Page 500](https://www.cisecurity.org/benchmark/microsoft_365) +* [Microsoft Teams admin center - Settings & policies](https://admin.teams.microsoft.com/one-policy/settings) +* [Set-CsTeamsClientConfiguration](https://learn.microsoft.com/powershell/module/microsoftteams/set-csteamsclientconfiguration) +* [CIS Microsoft 365 Foundations Benchmark v7.0.0 - 8.1.1](https://www.cisecurity.org/benchmark/microsoft_365) %TestResult% diff --git a/tests/cis/Test.CIS.M365.8.1.1.ps1 b/tests/cis/Test.CIS.M365.8.1.1.ps1 index 3888bf1bb0..c65e7a8263 100644 --- a/tests/cis/Test.CIS.M365.8.1.1.ps1 +++ b/tests/cis/Test.CIS.M365.8.1.1.ps1 @@ -1,16 +1,22 @@ function Test-MtCisThirdPartyFileSharing { <# .SYNOPSIS - Ensure third-party file sharing cloud services in Teams are disabled + Ensure external file sharing in Teams is enabled for only approved cloud storage services .DESCRIPTION - Ensure third-party file sharing cloud services in Teams are disabled + Checks that the third-party cloud storage services in the Global Teams client configuration are turned off, + except those the organization has approved. CIS Microsoft 365 Foundations Benchmark v7.0.0 (8.1.1) .EXAMPLE Test-MtCisThirdPartyFileSharing - Returns true if all third-party file sharing cloud services in Teams are disabled + Returns true if every third-party cloud storage service in Teams is turned off + + .EXAMPLE + Test-MtCisThirdPartyFileSharing -ApprovedProviders Box + + Returns true if every third-party cloud storage service in Teams except Box is turned off .LINK https://maester.dev/docs/commands/Test-MtCisThirdPartyFileSharing @@ -33,32 +39,43 @@ )] [CmdletBinding()] [OutputType([bool])] - param() + param( + # Cloud storage services the organization has approved for file sharing in Teams, which may stay turned on. + [ValidateSet('Dropbox', 'Box', 'GoogleDrive', 'ShareFile', 'Egnyte')] + [string[]] $ApprovedProviders + ) - Write-Verbose 'Test-MtCisThirdPartyFileSharing: Checking if third-party file sharing cloud services in Teams are disabled' + Write-Verbose 'Test-MtCisThirdPartyFileSharing: Checking that only approved third-party cloud storage services are turned on in Teams' - $return = $true - $thirdPartyCloudServices = Get-CsTeamsClientConfiguration -Identity Global | Select-Object AllowDropbox, AllowBox, AllowGoogleDrive, AllowShareFile, AllowEgnyte + $clientConfig = Get-CsTeamsClientConfiguration -Identity Global + if ($null -eq $clientConfig) { + Add-MtTestResultDetail -Result 'The Global Teams client configuration was not returned, so the third-party cloud storage settings could not be confirmed.' + return $false + } $passResult = '✅ Pass' $failResult = '❌ Fail' - $result = "| Policy | Value | Status |`n" - $result += "| --- | --- | --- |`n" + $result = "| Setting | Value | Approved | Status |`n" + $result += "| --- | --- | --- | --- |`n" - foreach ($thirdPartyProvider in ($thirdPartyCloudServices.PSObject.Properties)) { - if ($thirdPartyProvider.Value -eq $false) { - $result += "| $($thirdPartyProvider.Name) | $($thirdPartyProvider.Value) | $passResult |`n" + $return = $true + foreach ($provider in 'Dropbox', 'Box', 'GoogleDrive', 'ShareFile', 'Egnyte') { + $setting = "Allow$provider" + $value = $clientConfig.$setting + $approved = $provider -in $ApprovedProviders + if ($value -eq $false -or ($approved -and $value -eq $true)) { + $result += "| $setting | $value | $(if ($approved) { 'Yes' } else { 'No' }) | $passResult |`n" } else { - $result += "| $($thirdPartyProvider.Name) | $($thirdPartyProvider.Value) | $failResult |`n" + $result += "| $setting | $(if ($null -eq $value) { 'Not found' } else { $value }) | $(if ($approved) { 'Yes' } else { 'No' }) | $failResult |`n" $return = $false } } if ($return) { - $testResultMarkdown = "Well done. All third-party cloud services are disabled.`n`n%TestResult%" + $testResultMarkdown = "Well done. Only approved third-party cloud storage services are turned on in Teams.`n`n%TestResult%" } else { - $testResultMarkdown = "All or specific third-party cloud services are enabled.`n`n%TestResult%" + $testResultMarkdown = "Third-party cloud storage services that are not approved are turned on in Teams. Turn them off, or add them to the ApprovedProviders parameter if the organization has approved them.`n`n%TestResult%" } $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result diff --git a/tests/cis/Test.CIS.M365.8.1.2.md b/tests/cis/Test.CIS.M365.8.1.2.md index f864b97cc8..9d04b7d5af 100644 --- a/tests/cis/Test.CIS.M365.8.1.2.md +++ b/tests/cis/Test.CIS.M365.8.1.2.md @@ -5,7 +5,7 @@ When the setting is off, channel members can still post in Teams. Only the email #### Remediation action 1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). -2. Go to **Teams** > **Teams settings**. +2. Go to **Settings & policies** > [**Global (Org-wide default) settings**](https://admin.teams.microsoft.com/one-policy/settings) and select **Teams** to open the **Teams settings** section. 3. Under **Email integration**, turn off **Users can send emails to a channel email address**. 4. Select **Save**. @@ -20,9 +20,8 @@ Set-CsTeamsClientConfiguration -Identity Global -AllowEmailIntoChannel $false #### Related links -* [Microsoft Teams admin center](https://admin.teams.microsoft.com) -* [Set-CsTeamsClientConfiguration (AllowEmailIntoChannel)](https://learn.microsoft.com/powershell/module/teams/set-csteamsclientconfiguration) -* [Set-CsTeamsClientConfiguration](https://learn.microsoft.com/powershell/module/teams/set-csteamsclientconfiguration) +* [Microsoft Teams admin center - Settings & policies](https://admin.teams.microsoft.com/one-policy/settings) +* [Set-CsTeamsClientConfiguration](https://learn.microsoft.com/powershell/module/microsoftteams/set-csteamsclientconfiguration) * [CIS Microsoft 365 Foundations Benchmark v7.0.0 - 8.1.2](https://www.cisecurity.org/benchmark/microsoft_365) diff --git a/tests/cis/Test.CIS.M365.8.2.1.md b/tests/cis/Test.CIS.M365.8.2.1.md index b91721c5c4..26604b47ea 100644 --- a/tests/cis/Test.CIS.M365.8.2.1.md +++ b/tests/cis/Test.CIS.M365.8.2.1.md @@ -1,18 +1,27 @@ Federation lets users in other Microsoft 365 and Teams organizations find and message people in your tenant. If every known external domain is allowed, anyone with a tenant in those domains can start chats with your users. That is a common route for phishing and social engineering, because the sender looks like a normal business contact. -Restricting external domains means only the partner domains you choose can communicate with your users. Turning federation off removes the path completely. +Turning off external domains in the Global (Org-wide default) external access policy removes that path for everyone the policy applies to. Users who need to work with external organizations can be given a custom external access policy, or the organization settings can allow only specific partner domains. The test passes when the Global policy turns off external domains, or when the organization settings turn external domains off, block all of them or allow only specific domains. #### Remediation action 1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). -2. Go to **Users** > **External access**. -3. Next to **Teams and Skype for Business users in external organizations**, choose **Allow only specific external domains**, select **Add external domains** and add the approved domains. To turn external access off instead, choose **Block all external domains**. -4. Select **Save**. +2. Go to **External collaboration** > **External access** and open the **Policies** tab. +3. Select the **Global (Org-wide default)** policy. +4. Set **Manage external domains for this policy** to **Off**. +5. Select **Save**. + +On the **Organization settings** tab, setting **Manage external domains for this organization** to **Off**, or to **On** with **Allow only specific external domains** or **Block all external domains**, also meets the recommendation. ##### PowerShell 1. Connect to Teams PowerShell using `Connect-MicrosoftTeams`. -2. Run the following commands to allow only specific domains, replacing the example domain with your approved domains. The list replaces the domains that are allowed now: +2. Run the following command: + +```powershell +Set-CsExternalAccessPolicy -Identity Global -EnableFederationAccess $false +``` + +To allow only specific domains for the organization instead, run the following commands, replacing the example domain with your approved domains. The list replaces the domains that are allowed now: ```powershell $domains = [System.Collections.Generic.List[string]]::new() @@ -20,12 +29,11 @@ $domains.Add('partner.example.com') Set-CsTenantFederationConfiguration -AllowFederatedUsers $true -AllowedDomainsAsAList $domains ``` ->Note: Setting AllowFederatedUsers to $false also meets the recommended state. - #### Related links * [Microsoft Teams admin center](https://admin.teams.microsoft.com) * [Manage external meetings and chat with people and organizations](https://learn.microsoft.com/microsoftteams/manage-external-access) +* [Set-CsExternalAccessPolicy](https://learn.microsoft.com/powershell/module/microsoftteams/set-csexternalaccesspolicy) * [Set-CsTenantFederationConfiguration](https://learn.microsoft.com/powershell/module/teams/set-cstenantfederationconfiguration) * [CIS Microsoft 365 Foundations Benchmark v7.0.0 - 8.2.1](https://www.cisecurity.org/benchmark/microsoft_365) diff --git a/tests/cis/Test.CIS.M365.8.2.2.md b/tests/cis/Test.CIS.M365.8.2.2.md index 654921b064..7164320256 100644 --- a/tests/cis/Test.CIS.M365.8.2.2.md +++ b/tests/cis/Test.CIS.M365.8.2.2.md @@ -1,36 +1,18 @@ -8.2.2 (L1) Ensure communication with unmanaged Teams users is disabled +Users can't chat or meet with external users who have unmanaged Microsoft accounts, such as Microsoft Teams (free). -This policy setting controls chats and meetings with external unmanaged Teams users (those not managed by an organization, such as Microsoft Teams (free)). +Little effort is needed to get a free or trial Teams account, so attackers use unmanaged accounts to reach users through external access. Attacks delivered this way include DarkGate malware, social engineering and phishing by Midnight Blizzard, GIFShell and username enumeration. Turning off communication with unmanaged accounts removes that channel. Users can no longer communicate with Teams users who aren't managed by an organization; create a separate policy for groups that need to. This setting doesn't control anonymous meeting join through a shared link, and isn't available in GCC, GCC High, DoD or private cloud environments. -The recommended state is: **People in my org can chat and have meetings with external users who have unmanaged Microsoft accounts set to Off**. - -#### Rationale - -Allowing users to communicate with unmanaged Teams users presents a potential security threat as little effort is required by threat actors to gain access to a trial or free Microsoft Teams account. Some real-world attacks and exploits delivered via Teams over external access channels include: - -* DarkGate malware -* Social engineering / Phishing attacks by "Midnight Blizzard" -* GIFShell -* Username enumeration - -#### Impact - -Users will be unable to communicate with Teams users who are not managed by an organization. Organizations may choose to create additional policies for specific groups needing to communicate with unmanaged external users. - ->Note: The settings that govern chats and meetings with external unmanaged Teams users aren't available in GCC, GCC High, or DOD deployments, or in private cloud environments +The test passes when the Global (Org-wide default) external access policy or the organization settings turn the setting off. #### Remediation action -To remediate using the UI: +1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). +2. Go to **External collaboration** > **External access** and open the **Policies** tab. +3. Select the **Global (Org-wide default)** policy. +4. Set **People in my org can chat and have meetings with external users who have unmanaged Microsoft accounts** to **Off**. +5. Select **Save**. -1. Navigate to [Microsoft 365 Teams Admin Center](https://admin.teams.microsoft.com). -2. Click to expand **External collaboration** and select **External access**. -3. Select the **Policies** tab -4. Click on the **Global (Org-wide default)** policy. -5. Set **People in my org can chat and have meetings with external users who have unmanaged Microsoft accounts** to **Off**. -6. Click **Save**. - ->Note: Configuring this setting at the organization level, in the **Organization settings** tab, to **Off** is also a compliant remediation. +Turning the same setting **Off** on the **Organization settings** tab also meets the recommendation. ##### PowerShell @@ -41,15 +23,13 @@ To remediate using the UI: Set-CsExternalAccessPolicy -Identity Global -EnableTeamsConsumerAccess $false ``` ->Note: Configuring the organization settings to block communication is also in compliance with this control. - #### Related links -* [Microsoft 365 Teams Admin Center](https://admin.teams.microsoft.com) -* [IT Admins - Manage external meetings and chat with people and organizations using Microsoft identities](https://learn.microsoft.com/microsoftteams/trusted-organizations-external-meetings-chat?tabs=organization-settings) +* [Microsoft Teams admin center](https://admin.teams.microsoft.com) +* [Manage external meetings and chat with people and organizations using Microsoft identities](https://learn.microsoft.com/microsoftteams/trusted-organizations-external-meetings-chat) * [Midnight Blizzard conducts targeted social engineering over Microsoft Teams](https://www.microsoft.com/security/blog/2023/08/02/midnight-blizzard-conducts-targeted-social-engineering-over-microsoft-teams/) * [GIFShell Attack Lets Hackers Create Reverse Shell through Microsoft Teams GIFs](https://www.bitdefender.com/en-us/blog/hotforsecurity/gifshell-attack-lets-hackers-create-reverse-shell-through-microsoft-teams-gifs) -* [CIS Microsoft 365 Foundations Benchmark v7.0.0 - Page 512](https://www.cisecurity.org/benchmark/microsoft_365) +* [CIS Microsoft 365 Foundations Benchmark v7.0.0 - 8.2.2](https://www.cisecurity.org/benchmark/microsoft_365) %TestResult% diff --git a/tests/cis/Test.CIS.M365.8.2.2.ps1 b/tests/cis/Test.CIS.M365.8.2.2.ps1 index 9b02c19a97..5cbe107be1 100644 --- a/tests/cis/Test.CIS.M365.8.2.2.ps1 +++ b/tests/cis/Test.CIS.M365.8.2.2.ps1 @@ -38,18 +38,23 @@ Write-Verbose 'Test-MtCisCommunicateWithUnmanagedTeamsUsers: Checking if communication with unmanaged Teams users is disabled' - $AllowTeamsConsumer = Get-CsTenantFederationConfiguration | Select-Object -ExpandProperty AllowTeamsConsumer - if ($AllowTeamsConsumer -eq $false) { - Add-MtTestResultDetail -Result 'Well done. Communication with unmanaged Teams users is disabled.' - return $true + $federation = Get-CsTenantFederationConfiguration + $externalAccessPolicy = Get-CsExternalAccessPolicy -Identity Global + $orgSetting = $federation.AllowTeamsConsumer + $policySetting = $externalAccessPolicy.EnableTeamsConsumerAccess + $testResult = $orgSetting -eq $false -or $policySetting -eq $false + + $resultMarkdown = if ($testResult) { + "Well done. Communication with unmanaged Teams users is disabled.`n`n" } else { - $ExternalAccessPolicy = Get-CsExternalAccessPolicy -Identity Global - if ($ExternalAccessPolicy.EnableTeamsConsumerAccess -eq $false) { - Add-MtTestResultDetail -Result 'Well done. Communication with unmanaged Teams users is disabled.' - return $true - } else { - Add-MtTestResultDetail -Result 'Communication with unmanaged Teams users is enabled.' - return $false - } + "Communication with unmanaged Teams users is enabled. Turn it off in the Global external access policy or in the organization settings.`n`n" } + $resultMarkdown += "| Setting | Value | Result |`n" + $resultMarkdown += "| --- | --- | --- |`n" + $resultMarkdown += "| AllowTeamsConsumer (organization settings) | $(if ($null -eq $orgSetting) { 'Not found' } else { $orgSetting }) | $(if ($orgSetting -eq $false) { 'Pass' } else { 'Fail' }) |`n" + $resultMarkdown += "| EnableTeamsConsumerAccess (Global external access policy) | $(if ($null -eq $policySetting) { 'Not found' } else { $policySetting }) | $(if ($policySetting -eq $false) { 'Pass' } else { 'Fail' }) |`n" + $resultMarkdown += "`nEither setting turned off meets the CIS recommendation." + + Add-MtTestResultDetail -Result $resultMarkdown + return $testResult } diff --git a/tests/cis/Test.CIS.M365.8.2.3.md b/tests/cis/Test.CIS.M365.8.2.3.md index db6818c029..28802d7dc2 100644 --- a/tests/cis/Test.CIS.M365.8.2.3.md +++ b/tests/cis/Test.CIS.M365.8.2.3.md @@ -1,40 +1,18 @@ -8.2.3 (L1) Ensure external Teams users cannot initiate conversations +External users with unmanaged Microsoft accounts, such as Microsoft Teams (free), can't start chats or meetings with users in your organization. -This setting prevents external users who are not managed by an organization from initiating contact with users in the protected organization. The recommended state is to uncheck **External users with Teams accounts not managed by an organization can contact users in my organization**. +Little effort is needed to get a free or trial Teams account, so attackers use unmanaged accounts to contact users through external access. Attacks delivered this way include DarkGate malware, social engineering and phishing by Midnight Blizzard, GIFShell and username enumeration. This setting is a stop gap for CIS 8.2.2: if some users are allowed to communicate with unmanaged accounts, they still can't be contacted first. Turning off the parent setting in 8.2.2 also blocks inbound contact. Users with an exception can still join meetings that unmanaged users set up, depending on the parent setting. This setting isn't available in GCC, GCC High, DoD or private cloud environments. ->Note: Disabling this setting is used as an additional stop gap for the previous setting which disables communication with unmanaged Teams users entirely. If an organization chooses to have an exception to (L1) Ensure communication with unmanaged Teams users is disabled they can do so while also disabling the ability for the same group of users to initiate contact. Disabling communication entirely will also disable the ability for unmanaged users to initiate contact. - -#### Rationale - -Allowing users to communicate with unmanaged Teams users presents a potential security threat as little effort is required by threat actors to gain access to a trial or free Microsoft Teams account. - -Some real-world attacks and exploits delivered via Teams over external access channels include: - -* DarkGate malware -* Social engineering / Phishing attacks by "Midnight Blizzard" -* GIFShell -* Username enumeration - -#### Impact - -The impact of disabling this is very low. -Organizations may choose to create additional policies for specific groups that need to communicate with unmanaged external users. - ->Note: Chats and meetings with external unmanaged Teams users isn't available in GCC, GCC High, or DOD deployments, or in private cloud environments. +The test passes when the Global (Org-wide default) external access policy or the organization settings turn off inbound contact from unmanaged accounts. #### Remediation action -To remediate using the UI: +1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). +2. Go to **External collaboration** > **External access** and open the **Policies** tab. +3. Select the **Global (Org-wide default)** policy. +4. Under **People in my org can chat and have meetings with external users who have unmanaged Microsoft accounts**, clear **People in my org can join external meetings and receive new chats from users who have unmanaged Microsoft accounts**. +5. Select **Save**. -1. Navigate to [Microsoft 365 Teams Admin Center](https://admin.teams.microsoft.com). -2. Click to expand **Users** select **External access**. -3. Select the **Policies** tab -4. Click on the **Global (Org-wide default)** policy. -5. Locate the parent setting **People in my organization can communicate with unmanaged Teams accounts**. -6. Uncheck **External users with Teams accounts not managed by an organization can contact users in my organization**. -7. Click **Save**. - ->Note: If People in my organization can communicate with unmanaged Teams accounts is already set to Off then this setting will not be visible and will satisfy the requirements of this recommendation. +If the parent setting is already **Off**, the option isn't shown and the recommendation is met. Clearing the same option on the **Organization settings** tab also meets the recommendation. ##### PowerShell @@ -45,15 +23,13 @@ To remediate using the UI: Set-CsExternalAccessPolicy -Identity Global -EnableTeamsConsumerInbound $false ``` ->Note: Configuring the organization settings to block inbound communication is also in compliance with this control. - #### Related links -* [Microsoft 365 Teams Admin Center](https://admin.teams.microsoft.com) -* [IT Admins - Manage external meetings and chat with people and organizations using Microsoft identities](https://learn.microsoft.com/microsoftteams/trusted-organizations-external-meetings-chat?tabs=organization-settings) +* [Microsoft Teams admin center](https://admin.teams.microsoft.com) +* [Manage external meetings and chat with people and organizations using Microsoft identities](https://learn.microsoft.com/microsoftteams/trusted-organizations-external-meetings-chat) * [Midnight Blizzard conducts targeted social engineering over Microsoft Teams](https://www.microsoft.com/security/blog/2023/08/02/midnight-blizzard-conducts-targeted-social-engineering-over-microsoft-teams/) * [GIFShell Attack Lets Hackers Create Reverse Shell through Microsoft Teams GIFs](https://www.bitdefender.com/en-us/blog/hotforsecurity/gifshell-attack-lets-hackers-create-reverse-shell-through-microsoft-teams-gifs) -* [CIS Microsoft 365 Foundations Benchmark v7.0.0 - Page 516](https://www.cisecurity.org/benchmark/microsoft_365) +* [CIS Microsoft 365 Foundations Benchmark v7.0.0 - 8.2.3](https://www.cisecurity.org/benchmark/microsoft_365) %TestResult% diff --git a/tests/cis/Test.CIS.M365.8.2.3.ps1 b/tests/cis/Test.CIS.M365.8.2.3.ps1 index f8ebdefc92..7ba68f1e61 100644 --- a/tests/cis/Test.CIS.M365.8.2.3.ps1 +++ b/tests/cis/Test.CIS.M365.8.2.3.ps1 @@ -38,20 +38,23 @@ Write-Verbose 'Test-MtCisCommunicateInitiateExternalTeamsUsers: Checking if external unmanaged Teams users cannot initiate conversations' - $AllowTeamsConsumerInbound = Get-CsTenantFederationConfiguration | Select-Object -ExpandProperty AllowTeamsConsumerInbound - if ($AllowTeamsConsumerInbound -eq $false) { - Add-MtTestResultDetail -Result 'Well done. External unmanaged Teams users cannot initiate conversations.' - return $true - } - else { - $ExternalAccessPolicy = Get-CsExternalAccessPolicy -Identity Global - if ($ExternalAccessPolicy.EnableTeamsConsumerInbound -eq $false) { - Add-MtTestResultDetail -Result 'Well done. External unmanaged Teams users cannot initiate conversations.' - return $true - } - else { - Add-MtTestResultDetail -Result 'External unmanaged Teams users can initiate conversations.' - return $false - } + $federation = Get-CsTenantFederationConfiguration + $externalAccessPolicy = Get-CsExternalAccessPolicy -Identity Global + $orgSetting = $federation.AllowTeamsConsumerInbound + $policySetting = $externalAccessPolicy.EnableTeamsConsumerInbound + $testResult = $orgSetting -eq $false -or $policySetting -eq $false + + $resultMarkdown = if ($testResult) { + "Well done. External unmanaged Teams users cannot initiate conversations.`n`n" + } else { + "External unmanaged Teams users can initiate conversations. Turn this off in the Global external access policy or in the organization settings.`n`n" } + $resultMarkdown += "| Setting | Value | Result |`n" + $resultMarkdown += "| --- | --- | --- |`n" + $resultMarkdown += "| AllowTeamsConsumerInbound (organization settings) | $(if ($null -eq $orgSetting) { 'Not found' } else { $orgSetting }) | $(if ($orgSetting -eq $false) { 'Pass' } else { 'Fail' }) |`n" + $resultMarkdown += "| EnableTeamsConsumerInbound (Global external access policy) | $(if ($null -eq $policySetting) { 'Not found' } else { $policySetting }) | $(if ($policySetting -eq $false) { 'Pass' } else { 'Fail' }) |`n" + $resultMarkdown += "`nEither setting turned off meets the CIS recommendation." + + Add-MtTestResultDetail -Result $resultMarkdown + return $testResult } diff --git a/tests/cis/Test.CIS.M365.8.2.4.md b/tests/cis/Test.CIS.M365.8.2.4.md index df834a3212..48ba9c98c7 100644 --- a/tests/cis/Test.CIS.M365.8.2.4.md +++ b/tests/cis/Test.CIS.M365.8.2.4.md @@ -1,10 +1,17 @@ Trial Teams tenants are tenants that have only trial licenses and no purchased licenses. They are short-lived, easy to create and often used for spam and phishing. If your organization can communicate with accounts in trial tenants, users can receive messages and meeting invitations from senders that have little accountability. -Blocking trial tenants keeps external communication limited to organizations that have purchased licenses. Users in your organization can still communicate with all other allowed external organizations. +Blocking trial tenants keeps external communication limited to organizations that have purchased licenses. Users in your organization can still communicate with all other allowed external organizations. Users from trial tenants are removed from existing chats, so contacts who use a trial tenant need another channel, such as email, until they move to a licensed tenant. #### Remediation action -Microsoft documents this setting for PowerShell only. Blocked is the default value, so a tenant fails this test only when the setting has been changed to Allowed. +1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). +2. Go to **External collaboration** > **External access** and open the **Organization settings** tab. +3. Set **People in my organization can communicate with accounts in trial Teams tenants** to **Off**. +4. Select **Save**. + +Off (`Blocked`) is the default value, so a tenant fails this test only when the setting has been changed. + +##### PowerShell 1. Connect to Teams PowerShell using `Connect-MicrosoftTeams`. 2. Run the following command: diff --git a/tests/cis/Test.CIS.M365.8.4.1.md b/tests/cis/Test.CIS.M365.8.4.1.md index ba6bd15e35..d4e90abc18 100644 --- a/tests/cis/Test.CIS.M365.8.4.1.md +++ b/tests/cis/Test.CIS.M365.8.4.1.md @@ -1,39 +1,37 @@ -8.4.1 (L1) Ensure app permission policies are configured +Users can't install third-party or custom Teams apps by default, and can't interact with custom apps in preview. -This policy setting controls which class of apps are available for users to install. +Third-party and custom apps can read and act on Teams data on behalf of users. An app that a user adds without review may be malicious, unverified or over-privileged, and custom apps in preview can be uploaded without admin approval. Turning these defaults off means that only apps an admin has made available can be used. Admins can still make individual apps available to everyone or to specific users and groups on the **Manage apps** page; the org-wide settings apply to apps whose availability hasn't been set. -#### Rationale - -Allowing users to install third-party or unverified apps poses a potential risk of introducing malicious software to the environment. - -#### Impact - -Users will only be able to install approved classes of apps. +The test reads the org-wide app settings with `Get-M365UnifiedTenantSettings` (`GlobalApp` for third-party apps and `PrivateApp` for custom apps must be `None`) and `Get-CsTeamsSettingsCustomApp` (`IsSideloadedAppsInteractionEnabled` must be `False`). #### Remediation action -1. Navigate to [Microsoft Teams Admin Center](https://admin.teams.microsoft.com). -2. Click to expand **Teams apps**, then select **Permission policies**. -3. Select the **Global (Org-wide default)** policy. -4. Under **Third-party apps**, set to **Block all apps** (or **Allow specific apps and block all others**). -5. Under **Custom apps**, set to **Block all apps** (or **Allow specific apps and block all others**). -6. Click **Save**. +1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). +2. Go to **Teams apps** > [**Manage apps**](https://admin.teams.microsoft.com/policies/manage-apps). +3. Select **Actions** > **Org-wide app settings**. +4. Under **Third-party apps**, turn off **Let users install and use available apps by default**. +5. Under **Custom apps**, turn off **Let users install and use available apps by default**. +6. Under **Custom apps**, turn off **Let users interact with custom apps in preview**. +7. Select **Save**. ##### PowerShell 1. Connect to Teams PowerShell using `Connect-MicrosoftTeams`. -2. Run the following command to block all third-party and custom apps: +2. Run the following commands: ```powershell -Set-CsTeamsAppPermissionPolicy -Identity Global -GlobalCatalogAppsType AllowedAppList -GlobalCatalogApps @() -PrivateCatalogAppsType AllowedAppList -PrivateCatalogApps @() +Update-M365UnifiedTenantSettings -SettingName GlobalApp -SettingValue None +Update-M365UnifiedTenantSettings -SettingName PrivateApp -SettingValue None +Set-CsTeamsSettingsCustomApp -isSideloadedAppsInteractionEnabled $false ``` #### Related links -* [Microsoft Teams Admin Center](https://admin.teams.microsoft.com). -* [Manage app permission policies in Microsoft Teams](https://learn.microsoft.com/microsoftteams/teams-app-permission-policies) -* [Set-CsTeamsAppPermissionPolicy](https://learn.microsoft.com/powershell/module/teams/set-csteamsapppermissionpolicy) -* [CIS Microsoft 365 Foundations Benchmark v7.0.0 - Page 526](https://www.cisecurity.org/benchmark/microsoft_365) +* [Microsoft Teams admin center - Manage apps](https://admin.teams.microsoft.com/policies/manage-apps) +* [App centric management to manage user access to Teams apps](https://learn.microsoft.com/microsoftteams/app-centric-management) +* [Manage custom app policies and settings](https://learn.microsoft.com/microsoftteams/teams-custom-app-policies-and-settings) +* [Update-M365UnifiedTenantSettings](https://learn.microsoft.com/powershell/module/microsoftteams/update-m365unifiedtenantsettings) +* [CIS Microsoft 365 Foundations Benchmark v7.0.0 - 8.4.1](https://www.cisecurity.org/benchmark/microsoft_365) %TestResult% diff --git a/tests/cis/Test.CIS.M365.8.4.1.ps1 b/tests/cis/Test.CIS.M365.8.4.1.ps1 index 8263757b0c..6ad8d9f7a7 100644 --- a/tests/cis/Test.CIS.M365.8.4.1.ps1 +++ b/tests/cis/Test.CIS.M365.8.4.1.ps1 @@ -4,14 +4,14 @@ Ensure app permission policies are configured .DESCRIPTION - The Global (Org-wide default) app permission policy should block third-party and custom Teams apps, - either entirely or by allowing only an approved list. + The Teams org-wide app settings should not let users install and use third-party or custom apps by default, + and should not let users interact with custom apps in preview. CIS Microsoft 365 Foundations Benchmark v7.0.0 (8.4.1, L1) .EXAMPLE Test-MtCisThirdPartyAndCustomApps - Returns true if the Global app permission policy blocks third-party and custom apps + Returns true if the org-wide app settings turn off third-party apps, custom apps and custom apps in preview by default .LINK https://maester.dev/docs/commands/Test-MtCisThirdPartyAndCustomApps @@ -37,47 +37,33 @@ [OutputType([bool])] param() - Write-Verbose 'Test-MtCisThirdPartyAndCustomApps: Checking if all or a majority of third-party and custom apps are blocked' + Write-Verbose 'Test-MtCisThirdPartyAndCustomApps: Checking the Teams org-wide app settings' - $return = $true - $appPermPolicy = Get-CsTeamsAppPermissionPolicy -Identity Global + $tenantSettings = @(Get-M365UnifiedTenantSettings) + $customAppSetting = Get-CsTeamsSettingsCustomApp - $passResult = '✅ Pass' - $failResult = '❌ Fail' + $thirdParty = ($tenantSettings | Where-Object { $_.SettingName -eq 'GlobalApp' } | Select-Object -First 1).SettingValue + $custom = ($tenantSettings | Where-Object { $_.SettingName -eq 'PrivateApp' } | Select-Object -First 1).SettingValue + $preview = $customAppSetting.IsSideloadedAppsInteractionEnabled - $result = "| Policy | Value | Status |`n" - $result += "| --- | --- | --- |`n" - - if (($appPermPolicy.GlobalCatalogAppsType -eq 'BlockedAppList') -and (-not $appPermPolicy.GlobalCatalogApps)) { - # Third-party apps - $result += "| Third-party apps | Allow all apps | $failResult |`n" - $return = $false - } elseif (($appPermPolicy.GlobalCatalogAppsType -eq 'AllowedAppList') -and ($appPermPolicy.GlobalCatalogApps)) { - $result += "| Third-party apps | Allow specific apps and block all others | $passResult |`n" - } elseif (($appPermPolicy.GlobalCatalogAppsType -eq 'BlockedAppList') -and ($appPermPolicy.GlobalCatalogApps)) { - $result += "| Third-party apps | Block specific apps and allow all others | $failResult |`n" - $return = $false - } else { - $result += "| Third-party apps | Block all apps | $passResult |`n" - } + $checks = @( + [pscustomobject]@{ Setting = 'Third-party apps: Let users install and use available apps by default'; Value = $thirdParty; Pass = $thirdParty -eq 'None' } + [pscustomobject]@{ Setting = 'Custom apps: Let users install and use available apps by default'; Value = $custom; Pass = $custom -eq 'None' } + [pscustomobject]@{ Setting = 'Custom apps: Let users interact with custom apps in preview'; Value = $preview; Pass = $preview -eq $false } + ) + $return = @($checks | Where-Object { -not $_.Pass }).Count -eq 0 - if (($appPermPolicy.PrivateCatalogAppsType -eq 'BlockedAppList') -and (-not $appPermPolicy.PrivateCatalogApps)) { - # Custom apps - $result += "| Custom apps | Allow all apps | $failResult |`n" - $return = $false - } elseif (($appPermPolicy.PrivateCatalogAppsType -eq 'AllowedAppList') -and ($appPermPolicy.PrivateCatalogApps)) { - $result += "| Custom apps | Allow specific apps and block all others | $passResult |`n" - } elseif (($appPermPolicy.PrivateCatalogAppsType -eq 'BlockedAppList') -and ($appPermPolicy.PrivateCatalogApps)) { - $result += "| Custom apps | Block specific apps and allow all others | $failResult |`n" - $return = $false - } else { - $result += "| Custom apps | Block all apps | $passResult |`n" + $result = "| Setting | Value | Status |`n" + $result += "| --- | --- | --- |`n" + foreach ($check in $checks) { + $displayValue = if ($null -eq $check.Value) { 'Not found' } else { $check.Value } + $result += "| $($check.Setting) | $displayValue | $(if ($check.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($return) { - $testResultMarkdown = "Well done. All or a majority of third-party and custom apps are blocked.`n`n%TestResult%" + $testResultMarkdown = "Well done. Users can't install third-party or custom apps by default or interact with custom apps in preview.`n`n%TestResult%" } else { - $testResultMarkdown = "All or a majority of third-party or custom apps are allowed.`n`n%TestResult%" + $testResultMarkdown = "The org-wide app settings let users install third-party or custom apps by default, or interact with custom apps in preview.`n`n%TestResult%" } $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result diff --git a/tests/cis/Test.CIS.M365.8.5.1.md b/tests/cis/Test.CIS.M365.8.5.1.md index 8380a82235..480eeb72a6 100644 --- a/tests/cis/Test.CIS.M365.8.5.1.md +++ b/tests/cis/Test.CIS.M365.8.5.1.md @@ -5,10 +5,9 @@ Turning off anonymous join keeps meetings limited to people who have signed in. #### Remediation action 1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). -2. Go to **Meetings** > **Meeting policies**. -3. Open the **Global (Org-wide default)** policy. -4. Under **Anonymous users can join a meeting**, select **Off**. -5. Select **Save**. +2. Go to **Settings & policies** > [**Global (Org-wide default) settings**](https://admin.teams.microsoft.com/one-policy/settings) and select **Meetings**. +3. Under **Meeting join & lobby**, set **Anonymous users can join a meeting unverified** to **Off**. +4. Select **Save**. ##### PowerShell diff --git a/tests/cis/Test.CIS.M365.8.5.2.md b/tests/cis/Test.CIS.M365.8.5.2.md index 7dff08bb76..76b1a9ad2b 100644 --- a/tests/cis/Test.CIS.M365.8.5.2.md +++ b/tests/cis/Test.CIS.M365.8.5.2.md @@ -1,14 +1,13 @@ Anonymous users are people who join a meeting without signing in to Microsoft Teams, and dial-in callers join by phone. If either can start a meeting, it can begin without anyone from the organization present, so nobody who is responsible for the meeting is there to control it. -When the setting is off, anonymous users and dial-in callers wait in the lobby until someone from your organization, a guest, or a user from a trusted organization starts the meeting. The setting only has an effect when anonymous users can join meetings and **Who can bypass the lobby** is set to **Everyone**. +When the setting is off, anonymous users and dial-in callers wait in the lobby until someone from your organization, a guest, or a user from a trusted organization starts the meeting. The setting only has an effect when **Who can bypass the lobby** is set to **Everyone**. If anonymous users can't join meetings, it applies only to dial-in callers. #### Remediation action 1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). -2. Go to **Meetings** > **Meeting policies**. -3. Open the **Global (Org-wide default)** policy. -4. Under **Anonymous users and dial-in callers can start a meeting**, select **Off**. -5. Select **Save**. +2. Go to **Settings & policies** > [**Global (Org-wide default) settings**](https://admin.teams.microsoft.com/one-policy/settings) and select **Meetings**. +3. Under **Meeting join & lobby**, set **Anonymous users and dial-in callers can start a meeting** to **Off**. +4. Select **Save**. ##### PowerShell diff --git a/tests/cis/Test.CIS.M365.8.5.3.md b/tests/cis/Test.CIS.M365.8.5.3.md index 37b2a3bacd..c3cb9df496 100644 --- a/tests/cis/Test.CIS.M365.8.5.3.md +++ b/tests/cis/Test.CIS.M365.8.5.3.md @@ -1,43 +1,33 @@ -8.5.3 (L1) Ensure only people in my org can bypass the lobby +Only invited people, people in your organization, or organizers and co-organizers can bypass the meeting lobby. -This policy setting controls who can join a meeting directly and who must wait in the lobby until they're admitted by an organizer, co-organizer, or presenter of the meeting. +The lobby lets an organizer, co-organizer or presenter see who is joining before admitting them. For meetings that may contain sensitive information, people who weren't invited directly should wait to be admitted, and anonymous users shouldn't be able to use a meeting link to hold meetings at unscheduled times. People outside the organization, and anyone who dials in, including internal users who are unauthenticated when dialing in, wait in the lobby until someone admits them. -The recommended state is **People who were invited** or more restrictive. - -#### Rationale - -For meetings that could contain sensitive information, it is best to allow the meeting organizer to vet anyone not directly sent an invite before admitting them to the meeting. This will also prevent the anonymous user from using the meeting link to have meetings at unscheduled times. - -#### Impact - -Individuals who are not part of the organization will have to wait in the lobby until they're admitted by an organizer, co-organizer, or presenter of the meeting. - -Any individual who dials into the meeting regardless of status will also have to wait in the lobby. This includes internal users who are considered unauthenticated when dialing in. +The test passes when **Who can bypass the lobby** in the Global (Org-wide default) meeting policy is **People who were invited** (`InvitedUsers`), **People in my org** (`EveryoneInCompanyExcludingGuests`) or **Only organizers and co-organizers** (`OrganizerOnly`). #### Remediation action -1. Navigate to [Microsoft Teams Admin Center](https://admin.teams.microsoft.com). -2. Select **Settings & policies** > **Global (Org-wide default) settings**. -3. Select **Meetings** to open the **meeting settings** section. -4. Under meeting join & lobby set **Who can bypass the lobby** to **People who were invited** or a more restrictive value: **People in my org, Only organizers and co-organizers**. +1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). +2. Go to **Settings & policies** > [**Global (Org-wide default) settings**](https://admin.teams.microsoft.com/one-policy/settings) and select **Meetings**. +3. Under **Meeting join & lobby**, set **Who can bypass the lobby** to **People who were invited**, **People in my org** or **Only organizers and co-organizers**. +4. Select **Save**. ##### PowerShell 1. Connect to Teams PowerShell using `Connect-MicrosoftTeams`. -2. Run the following command to set the recommended state: +2. Run one of the following commands: ```powershell Set-CsTeamsMeetingPolicy -Identity Global -AutoAdmittedUsers "InvitedUsers" +Set-CsTeamsMeetingPolicy -Identity Global -AutoAdmittedUsers "EveryoneInCompanyExcludingGuests" +Set-CsTeamsMeetingPolicy -Identity Global -AutoAdmittedUsers "OrganizerOnly" ``` ->Note: More restrictive values EveryoneInCompanyExcludingGuests or OrganizerOnly are also in compliance. - #### Related links -* [Microsoft Teams Admin Center](https://admin.teams.microsoft.com). +* [Microsoft Teams admin center - Settings & policies](https://admin.teams.microsoft.com/one-policy/settings) * [Overview of lobby settings and policies](https://learn.microsoft.com/microsoftteams/who-can-bypass-meeting-lobby#overview-of-lobby-settings-and-policies) -* [Set-CsTeamsMeetingPolicy](https://learn.microsoft.com/powershell/module/microsoftteams/set-csteamsmeetingpolicy?view=teams-ps&viewFallbackFrom=skype-ps) -* [CIS Microsoft 365 Foundations Benchmark v7.0.0 - Page 535](https://www.cisecurity.org/benchmark/microsoft_365) +* [Set-CsTeamsMeetingPolicy](https://learn.microsoft.com/powershell/module/microsoftteams/set-csteamsmeetingpolicy) +* [CIS Microsoft 365 Foundations Benchmark v7.0.0 - 8.5.3](https://www.cisecurity.org/benchmark/microsoft_365) %TestResult% diff --git a/tests/cis/Test.CIS.M365.8.5.4.md b/tests/cis/Test.CIS.M365.8.5.4.md index 78c8d30414..479efae570 100644 --- a/tests/cis/Test.CIS.M365.8.5.4.md +++ b/tests/cis/Test.CIS.M365.8.5.4.md @@ -5,10 +5,9 @@ Requiring dial-in callers to wait in the lobby means the organizer or a presente #### Remediation action 1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). -2. Go to **Meetings** > **Meeting policies**. -3. Open the **Global (Org-wide default)** policy. -4. Under **People dialing in can bypass the lobby**, select **Off**. -5. Select **Save**. +2. Go to **Settings & policies** > [**Global (Org-wide default) settings**](https://admin.teams.microsoft.com/one-policy/settings) and select **Meetings**. +3. Under **Meeting join & lobby**, set **People dialing in can bypass the lobby** to **Off**. +4. Select **Save**. ##### PowerShell diff --git a/tests/cis/Test.CIS.M365.8.5.5.md b/tests/cis/Test.CIS.M365.8.5.5.md index 8d3fafe270..98a2247876 100644 --- a/tests/cis/Test.CIS.M365.8.5.5.md +++ b/tests/cis/Test.CIS.M365.8.5.5.md @@ -5,10 +5,9 @@ Limiting meeting chat to signed-in participants keeps the chat to people whose i #### Remediation action 1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). -2. Go to **Meetings** > **Meeting policies**. -3. Open the **Global (Org-wide default)** policy. -4. Under **Meeting chat**, select **On for everyone but anonymous users** or **Off**. -5. Select **Save**. +2. Go to **Settings & policies** > [**Global (Org-wide default) settings**](https://admin.teams.microsoft.com/one-policy/settings) and select **Meetings**. +3. Under **Meeting engagement**, set **Meeting chat** to **On for everyone but anonymous users**, or to the more restrictive **In-meeting only except anonymous** or **Off**. +4. Select **Save**. ##### PowerShell diff --git a/tests/cis/Test.CIS.M365.8.5.6.md b/tests/cis/Test.CIS.M365.8.5.6.md index 6718e28549..f47802fc52 100644 --- a/tests/cis/Test.CIS.M365.8.5.6.md +++ b/tests/cis/Test.CIS.M365.8.5.6.md @@ -5,10 +5,9 @@ Limiting the presenter role to organizers and co-organizers keeps control of sha #### Remediation action 1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). -2. Go to **Meetings** > **Meeting policies**. -3. Open the **Global (Org-wide default)** policy. -4. Under **Who can present**, select **Only organizers and co-organizers**. -5. Select **Save**. +2. Go to **Settings & policies** > [**Global (Org-wide default) settings**](https://admin.teams.microsoft.com/one-policy/settings) and select **Meetings**. +3. Under **Content sharing**, set **Who can present** to **Only organizers and co-organizers**. +4. Select **Save**. ##### PowerShell diff --git a/tests/cis/Test.CIS.M365.8.5.7.md b/tests/cis/Test.CIS.M365.8.5.7.md index 214d702890..afb7cad3ab 100644 --- a/tests/cis/Test.CIS.M365.8.5.7.md +++ b/tests/cis/Test.CIS.M365.8.5.7.md @@ -5,10 +5,9 @@ Turning this off means external participants can't give or request control of sh #### Remediation action 1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). -2. Go to **Meetings** > **Meeting policies**. -3. Open the **Global (Org-wide default)** policy. -4. Under **External participants can give or request control**, select **Off**. -5. Select **Save**. +2. Go to **Settings & policies** > [**Global (Org-wide default) settings**](https://admin.teams.microsoft.com/one-policy/settings) and select **Meetings**. +3. Under **Content sharing**, set **External participants can give or request control** to **Off**. +4. Select **Save**. ##### PowerShell diff --git a/tests/cis/Test.CIS.M365.8.5.8.md b/tests/cis/Test.CIS.M365.8.5.8.md index 60d8f9a834..9c097a5302 100644 --- a/tests/cis/Test.CIS.M365.8.5.8.md +++ b/tests/cis/Test.CIS.M365.8.5.8.md @@ -5,10 +5,9 @@ Turning this off keeps your users out of the chat in meetings hosted by untruste #### Remediation action 1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). -2. Go to **Meetings** > **Meeting policies**. -3. Open the **Global (Org-wide default)** policy. -4. Under **External meeting chat**, select **Off**. -5. Select **Save**. +2. Go to **Settings & policies** > [**Global (Org-wide default) settings**](https://admin.teams.microsoft.com/one-policy/settings) and select **Meetings**. +3. Under **Meeting engagement**, set **External meeting chat** to **Off**. +4. Select **Save**. ##### PowerShell diff --git a/tests/cis/Test.CIS.M365.8.5.9.md b/tests/cis/Test.CIS.M365.8.5.9.md index 7cc08a2a52..fa55147930 100644 --- a/tests/cis/Test.CIS.M365.8.5.9.md +++ b/tests/cis/Test.CIS.M365.8.5.9.md @@ -5,10 +5,9 @@ Turning meeting recording off in the Global policy means nobody who has that pol #### Remediation action 1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). -2. Go to **Meetings** > **Meeting policies**. -3. Open the **Global (Org-wide default)** policy. -4. Under **Recording**, turn off **Meeting recording**. -5. Select **Save**. +2. Go to **Settings & policies** > [**Global (Org-wide default) settings**](https://admin.teams.microsoft.com/one-policy/settings) and select **Meetings**. +3. Under **Recording & transcription**, set **Meeting recording** to **Off**. +4. Select **Save**. ##### PowerShell diff --git a/tests/cis/Test.CIS.M365.8.6.1.md b/tests/cis/Test.CIS.M365.8.6.1.md index 4c23afa7bd..4a814c2580 100644 --- a/tests/cis/Test.CIS.M365.8.6.1.md +++ b/tests/cis/Test.CIS.M365.8.6.1.md @@ -1,49 +1,29 @@ -8.6.1 (L1) Ensure users can report security concerns in Teams +Users can report security concerns in Microsoft Teams, and reported items go only to the organization's reporting mailbox. -User reporting settings allow a user to report a message as malicious for further analysis. This recommendation is composed of 3 different settings and all be configured to pass: +User reporting lets people flag suspicious Teams messages quickly, so the security team can act on phishing and malicious content. Reported items can contain sensitive or personal information, and reports can include messages that are threatening or harassing, so they should stay inside the organization and be reviewed by staff who can route them to the right team, such as Human Resources. Sending reports to Microsoft should follow company policy. -* **In the Teams admin center:** On by default and controls whether users are able to report messages from Teams. When this setting is turned off, users can't report messages within Teams, so the corresponding setting in the Microsoft 365 Defender portal is irrelevant. -* **In the Microsoft 365 Defender portal:** On by default for new tenants. Existing tenants need to enable it. If user reporting of messages is turned on in the Teams admin center, it also needs to be turned on the Defender portal for user reported messages to show up correctly on the User reported tab on the Submissions page. -* **Defender - Report message destinations:** This applies to more than just Microsoft Teams and allows for an organization to keep their reports contained. Due to how the parameters are configured on the backend it is included in this assessment as a requirement. - -#### Rationale - -Users will be able to more quickly and systematically alert administrators of suspicious malicious messages within Teams. The content of these messages may be sensitive in nature and therefore should be kept within the organization and not shared with Microsoft without first consulting company policy. - ->Note -> ->* The reported message remains visible to the user in the Teams client. ->* Users can report the same message multiple times. ->* The message sender isn't notified that messages were reported. - -#### Impact - -Enabling message reporting has an impact beyond just addressing security concerns. When users of the platform report a message, the content could include messages that are threatening or harassing in nature, possibly stemming from colleagues. -Due to this the security staff responsible for reviewing and acting on these reports should be equipped with the skills to discern and appropriately direct such messages to the relevant departments, such as Human Resources (HR). +CIS requires three settings: **Report a security concern** in the Teams Global messaging policy, **Monitor reported items in Microsoft Teams** in the Microsoft Defender portal, and reported items sent to **My reporting mailbox only**. The test reads `Get-CsTeamsMessagingPolicy -Identity Global`, the report submission policy and the report submission rule. Reporting must be on, Teams and email reports must go to the reporting mailbox and not to Microsoft (`ReportChatMessageEnabled` and `EnableReportToMicrosoft` are `False`), and the reporting mailbox must be set in the policy and in an enabled report submission rule. Microsoft Defender for Office 365 Plan 1 or Plan 2, or Microsoft Defender XDR, licences are required. #### Remediation action -1. Navigate to [Microsoft Teams Admin Center](https://admin.teams.microsoft.com). -2. Select **Settings & policies** > **Global (Org-wide default) settings**. -3. Select **Messaging** to open the **messaging settings** section. -4. Set **Report a security concern** to **On**. -5. Next, navigate to [Microsoft 365 Defender](https://security.microsoft.com). -6. Click on **Settings** > **Email & collaboration** > **User reported settings**. -7. Scroll to **Microsoft Teams**. -8. Check **Monitor reported messages in Microsoft Teams** and **Save**. -9. Set **Send reported messages to:** to **My reporting mailbox only** with reports configured to be sent to authorized staff. +1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). +2. Go to **Settings & policies** > [**Global (Org-wide default) settings**](https://admin.teams.microsoft.com/one-policy/settings) and select **Messaging**. +3. Set **Report a security concern** to **On** and select **Save**. +4. Sign in to the [Microsoft Defender portal](https://security.microsoft.com). +5. Go to **System** > **Settings** > **Email & collaboration** > [**Teams user reported settings**](https://security.microsoft.com/securitysettings/teamsUserSubmission). +6. Under **Microsoft Teams**, select **Monitor reported items in Microsoft Teams**, set **Send reported items to** to **My reporting mailbox only**, add the reporting mailbox for authorized staff and select **Save**. +7. Go to [**User reported settings**](https://security.microsoft.com/securitysettings/userSubmission), set **Send reported items to** to **My reporting mailbox only** with the same reporting mailbox and select **Save**. ##### PowerShell -1. Connect to Teams PowerShell using `Connect-MicrosoftTeams`. -2. Connect to Exchange Online PowerShell using `Connect-ExchangeOnline`. -3. Run the following cmdlet: +1. Connect to Teams PowerShell using `Connect-MicrosoftTeams` and to Exchange Online PowerShell using `Connect-ExchangeOnline`. +2. Run the following command: ```powershell Set-CsTeamsMessagingPolicy -Identity Global -AllowSecurityEndUserReporting $true ``` -1. To configure the Defender reporting policies, edit and run this script: +3. Change the reporting mailbox in the following script and run it: ```powershell $usersub = "userreportedmessages@fabrikam.com" # Change this. @@ -61,15 +41,17 @@ $params = @{ } Set-ReportSubmissionPolicy @params New-ReportSubmissionRule -Name DefaultReportSubmissionRule -ReportSubmissionPolicy DefaultReportSubmissionPolicy -SentTo $usersub - ``` +If the report submission rule already exists, use `Set-ReportSubmissionRule -Identity DefaultReportSubmissionRule -SentTo $usersub` instead of `New-ReportSubmissionRule`. + #### Related links -* [Microsoft Teams Admin Center](https://admin.teams.microsoft.com) -* [Microsoft 365 Defender](https://security.microsoft.com) -* [User reported settings in Microsoft Teams](https://learn.microsoft.com/defender-office-365/submissions-teams?view=o365-worldwide) -* [CIS Microsoft 365 Foundations Benchmark v7.0.0 - Page 554](https://www.cisecurity.org/benchmark/microsoft_365) +* [Microsoft Teams admin center - Settings & policies](https://admin.teams.microsoft.com/one-policy/settings) +* [Microsoft Defender portal - Teams user reported settings](https://security.microsoft.com/securitysettings/teamsUserSubmission) +* [User reported settings in Teams](https://learn.microsoft.com/defender-office-365/submissions-teams) +* [Configure user reported message settings](https://learn.microsoft.com/defender-office-365/submissions-user-reported-messages-custom-mailbox) +* [CIS Microsoft 365 Foundations Benchmark v7.0.0 - 8.6.1](https://www.cisecurity.org/benchmark/microsoft_365) %TestResult% diff --git a/tests/cis/Test.CIS.M365.8.6.1.ps1 b/tests/cis/Test.CIS.M365.8.6.1.ps1 index b36a6b56da..07d6d261fd 100644 --- a/tests/cis/Test.CIS.M365.8.6.1.ps1 +++ b/tests/cis/Test.CIS.M365.8.6.1.ps1 @@ -4,13 +4,14 @@ Ensure users can report security concerns in Teams .DESCRIPTION - Ensures users can report security concerns in Teams, with reports directed only to an internal destination. + Checks that users can report security concerns in Teams, and that reported Teams items and email messages + go only to the organization's reporting mailbox and not to Microsoft. CIS Microsoft 365 Foundations Benchmark v7.0.0 (8.6.1, E5 L1) .EXAMPLE Test-MtCisTeamsReportSecurityConcerns - Returns true if configured properly + Returns true if users can report security concerns in Teams and reports go only to the reporting mailbox .LINK https://maester.dev/docs/commands/Test-MtCisTeamsReportSecurityConcerns @@ -27,8 +28,9 @@ UserImpact = 'Low', ImplementationCost = 'Low', Mitre = 'T1566', - Control = 'cis-m365:8.6.1', + Control = ('cis-m365:8.6.1', 'nist-800-53-r5:IR-6'), Service = ('Teams', 'ExchangeOnline'), + License = ('ATP_ENTERPRISE', 'DEFENDER_XDR'), Author = 'HenrikPiecha', Contributor = 'merill' )] @@ -39,75 +41,41 @@ Write-Verbose 'Test-MtCisTeamsReportSecurityConcerns: Checking if users can report security concerns in Teams to internal destination' - $return = $true - $MicrosoftTeamsCheck = Get-CsTeamsMessagingPolicy -Identity Global | Select-Object AllowSecurityEndUserReporting - $MicrosoftReportPolicy = Get-ReportSubmissionPolicy | Select-Object ReportJunkToCustomizedAddress, ReportNotJunkToCustomizedAddress, ReportPhishToCustomizedAddress, ReportJunkAddresses, ReportNotJunkAddresses, ReportPhishAddresses, ReportChatMessageEnabled, ReportChatMessageToCustomizedAddressEnabled + $messagingPolicy = Get-CsTeamsMessagingPolicy -Identity Global + $reportPolicy = @(Get-MtExo -Request ReportSubmissionPolicy) | Select-Object -First 1 + $reportRules = @(Get-MtExo -Request ReportSubmissionRule) | Where-Object { $_ } - $passResult = '✅ Pass' - $failResult = '❌ Fail' + $hasAddress = { param([object[]] $Values) @($Values | Where-Object { "$_" }).Count -gt 0 } + $ruleAddresses = @($reportRules | Where-Object { $_.State -ne 'Disabled' } | ForEach-Object { $_.SentTo } | Where-Object { "$_" }) - $result = "| Policy | Value | Status |`n" - $result += "| --- | --- | --- |`n" + $checks = @( + [pscustomobject]@{ Setting = 'AllowSecurityEndUserReporting (Teams Global messaging policy)'; Value = $messagingPolicy.AllowSecurityEndUserReporting; Expected = 'True'; Pass = $messagingPolicy.AllowSecurityEndUserReporting -eq $true } + [pscustomobject]@{ Setting = 'ReportChatMessageEnabled'; Value = $reportPolicy.ReportChatMessageEnabled; Expected = 'False'; Pass = $reportPolicy.ReportChatMessageEnabled -eq $false } + [pscustomobject]@{ Setting = 'ReportChatMessageToCustomizedAddressEnabled'; Value = $reportPolicy.ReportChatMessageToCustomizedAddressEnabled; Expected = 'True'; Pass = $reportPolicy.ReportChatMessageToCustomizedAddressEnabled -eq $true } + [pscustomobject]@{ Setting = 'EnableReportToMicrosoft'; Value = $reportPolicy.EnableReportToMicrosoft; Expected = 'False'; Pass = $reportPolicy.EnableReportToMicrosoft -eq $false } + [pscustomobject]@{ Setting = 'ReportJunkToCustomizedAddress'; Value = $reportPolicy.ReportJunkToCustomizedAddress; Expected = 'True'; Pass = $reportPolicy.ReportJunkToCustomizedAddress -eq $true } + [pscustomobject]@{ Setting = 'ReportNotJunkToCustomizedAddress'; Value = $reportPolicy.ReportNotJunkToCustomizedAddress; Expected = 'True'; Pass = $reportPolicy.ReportNotJunkToCustomizedAddress -eq $true } + [pscustomobject]@{ Setting = 'ReportPhishToCustomizedAddress'; Value = $reportPolicy.ReportPhishToCustomizedAddress; Expected = 'True'; Pass = $reportPolicy.ReportPhishToCustomizedAddress -eq $true } + [pscustomobject]@{ Setting = 'ReportJunkAddresses'; Value = @($reportPolicy.ReportJunkAddresses) -join ', '; Expected = 'Reporting mailbox'; Pass = & $hasAddress $reportPolicy.ReportJunkAddresses } + [pscustomobject]@{ Setting = 'ReportNotJunkAddresses'; Value = @($reportPolicy.ReportNotJunkAddresses) -join ', '; Expected = 'Reporting mailbox'; Pass = & $hasAddress $reportPolicy.ReportNotJunkAddresses } + [pscustomobject]@{ Setting = 'ReportPhishAddresses'; Value = @($reportPolicy.ReportPhishAddresses) -join ', '; Expected = 'Reporting mailbox'; Pass = & $hasAddress $reportPolicy.ReportPhishAddresses } + [pscustomobject]@{ Setting = 'Report submission rule (SentTo)'; Value = $ruleAddresses -join ', '; Expected = 'Enabled rule with the reporting mailbox'; Pass = $ruleAddresses.Count -gt 0 } + ) + $return = $null -ne $messagingPolicy -and $null -ne $reportPolicy -and @($checks | Where-Object { -not $_.Pass }).Count -eq 0 - if ($MicrosoftTeamsCheck.AllowSecurityEndUserReporting -eq $false) { - $result += "| AllowSecurityEndUserReporting | $($MicrosoftTeamsCheck.AllowSecurityEndUserReporting) | $failResult |`n" - $return = $false - } else { - $result += "| AllowSecurityEndUserReporting | $($MicrosoftTeamsCheck.AllowSecurityEndUserReporting) | $passResult |`n" - } - if ($MicrosoftReportPolicy.ReportJunkToCustomizedAddress -eq $false) { - $result += "| ReportJunkToCustomizedAddress | $($MicrosoftReportPolicy.ReportJunkToCustomizedAddress) | $failResult |`n" - $return = $false - } else { - $result += "| ReportJunkToCustomizedAddress | $($MicrosoftReportPolicy.ReportJunkToCustomizedAddress) | $passResult |`n" + $result = "| Setting | Value | Expected | Status |`n" + $result += "| --- | --- | --- | --- |`n" + foreach ($check in $checks) { + $displayValue = if ($null -eq $check.Value -or "$($check.Value)" -eq '') { 'Not set' } else { $check.Value } + $result += "| $($check.Setting) | $displayValue | $($check.Expected) | $(if ($check.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } - if ($MicrosoftReportPolicy.ReportNotJunkToCustomizedAddress -eq $false) { - $result += "| ReportNotJunkToCustomizedAddress | $($MicrosoftReportPolicy.ReportNotJunkToCustomizedAddress) | $failResult |`n" - $return = $false - } else { - $result += "| ReportNotJunkToCustomizedAddress | $($MicrosoftReportPolicy.ReportNotJunkToCustomizedAddress) | $passResult |`n" - } - if ($MicrosoftReportPolicy.ReportPhishToCustomizedAddress -eq $false) { - $result += "| ReportPhishToCustomizedAddress | $($MicrosoftReportPolicy.ReportPhishToCustomizedAddress) | $failResult |`n" - $return = $false - } else { - $result += "| ReportPhishToCustomizedAddress | $($MicrosoftReportPolicy.ReportPhishToCustomizedAddress) | $passResult |`n" - } - if ([string]::IsNullOrEmpty($MicrosoftReportPolicy.ReportJunkAddresses)) { - $result += "| ReportJunkAddresses | NULL | $failResult |`n" - $return = $false - } else { - $result += "| ReportJunkAddresses | $($MicrosoftReportPolicy.ReportJunkAddresses) | $passResult |`n" - } - if ([string]::IsNullOrEmpty($MicrosoftReportPolicy.ReportNotJunkAddresses)) { - $result += "| ReportNotJunkAddresses | NULL | $failResult |`n" - $return = $false - } else { - $result += "| ReportNotJunkAddresses | $($MicrosoftReportPolicy.ReportNotJunkAddresses) | $passResult |`n" - } - if ([string]::IsNullOrEmpty($MicrosoftReportPolicy.ReportPhishAddresses)) { - $result += "| ReportPhishAddresses | NULL | $failResult |`n" - $return = $false - } else { - $result += "| ReportPhishAddresses | $($MicrosoftReportPolicy.ReportPhishAddresses) | $passResult |`n" - } - if ($MicrosoftReportPolicy.ReportChatMessageEnabled -eq $true) { - $result += "| ReportChatMessageEnabled | $($MicrosoftReportPolicy.ReportChatMessageEnabled) | $failResult |`n" - $return = $false - } else { - $result += "| ReportChatMessageEnabled | $($MicrosoftReportPolicy.ReportChatMessageEnabled) | $passResult |`n" - } - if ($MicrosoftReportPolicy.ReportChatMessageToCustomizedAddressEnabled -eq $false) { - $result += "| ReportChatMessageToCustomizedAddressEnabled | $($MicrosoftReportPolicy.ReportChatMessageToCustomizedAddressEnabled) | $failResult |`n" - $return = $false - } else { - $result += "| ReportChatMessageToCustomizedAddressEnabled | $($MicrosoftReportPolicy.ReportChatMessageToCustomizedAddressEnabled) | $passResult |`n" - } if ($return) { - $testResultMarkdown = "Well done. All report submission policies are configured properly.`n`n%TestResult%" + $testResultMarkdown = "Well done. Users can report security concerns in Teams, and reports go only to your reporting mailbox.`n`n%TestResult%" + } elseif ($null -eq $reportPolicy) { + $testResultMarkdown = "No report submission policy was returned, so the reporting destination could not be confirmed. Configure the user reported settings in the Microsoft Defender portal.`n`n%TestResult%" } else { - $testResultMarkdown = "All or specific report submission policies are missing proper configuration.`n`n%TestResult%" + $testResultMarkdown = "Users can't report security concerns in Teams, or reports are not sent only to your reporting mailbox.`n`n%TestResult%" } $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result From 32559f0e80ce9299de6b995c2ca276641d0ca580 Mon Sep 17 00:00:00 2001 From: Jeremy Finney Date: Sun, 1 Nov 2026 14:34:10 +1300 Subject: [PATCH 02/15] fix(cis): address review feedback for v7.0.0 checks --- ...isStrictPresetForPriorityAccount.Tests.ps1 | 1 + .../functions/Test-MtCisTeamsChecks.Tests.ps1 | 37 +++++++++++++- tests/cis/Test.CIS.M365.2.4.4.ps1 | 11 ++-- tests/cis/Test.CIS.M365.8.2.2.ps1 | 2 +- tests/cis/Test.CIS.M365.8.2.3.ps1 | 2 +- tests/cis/Test.CIS.M365.8.2.4.md | 2 +- tests/cis/Test.CIS.M365.8.4.1.md | 2 +- tests/cis/Test.CIS.M365.8.4.1.ps1 | 16 +++++- tests/cis/Test.CIS.M365.8.6.1.md | 3 +- tests/cis/Test.CIS.M365.8.6.1.ps1 | 51 ++++++++++++++++--- 10 files changed, 107 insertions(+), 20 deletions(-) diff --git a/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 b/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 index 920bf6e5f6..725ed9c877 100644 --- a/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 @@ -14,6 +14,7 @@ } function New-StrictRule { + [CmdletBinding(SupportsShouldProcess = $true)] param([hashtable] $Conditions = @{}) $rule = [ordered]@{ Identity = 'Strict Preset Security Policy' diff --git a/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 b/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 index f85655bf52..0d5a921872 100644 --- a/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 @@ -9,8 +9,8 @@ if (-not (Get-Command $name -ErrorAction SilentlyContinue)) { Set-Item -Path "function:global:$name" -Value { [CmdletBinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', 'Identity', Justification = 'Stub signature only; Mock binds -Identity from it.')] param([string] $Identity) + $null = $Identity } $script:stubs += $name } @@ -88,13 +88,15 @@ Describe 'Test-MtCisThirdPartyFileSharing' { Describe 'Test-MtCisThirdPartyAndCustomApps' { BeforeEach { $script:Result = $null + $script:SkippedBecause = $null $script:TenantSettings = @( [pscustomobject]@{ SettingName = 'DefaultApp'; SettingValue = 'All' } [pscustomobject]@{ SettingName = 'GlobalApp'; SettingValue = 'None' } [pscustomobject]@{ SettingName = 'PrivateApp'; SettingValue = 'None' } ) $script:CustomApp = [pscustomobject]@{ IsSideloadedAppsInteractionEnabled = $false } - Mock -ModuleName Maester Add-MtTestResultDetail { param($Result) $script:Result = $Result } + Mock -ModuleName Maester Add-MtTestResultDetail { param($Result, $SkippedBecause) $script:Result = $Result; $script:SkippedBecause = $SkippedBecause } + Mock -ModuleName Maester Get-MgContext { [pscustomobject]@{ AuthType = 'Delegated' } } Mock -ModuleName Maester Get-M365UnifiedTenantSettings { $script:TenantSettings } Mock -ModuleName Maester Get-CsTeamsSettingsCustomApp { $script:CustomApp } } @@ -119,6 +121,22 @@ Describe 'Test-MtCisThirdPartyAndCustomApps' { Test-MtCisThirdPartyAndCustomApps | Should -BeFalse $script:Result | Should -Match 'Not found' } + + It 'skips before reading unified tenant settings with app-only authentication' { + Mock -ModuleName Maester Get-MgContext { [pscustomobject]@{ AuthType = 'AppOnly' } } + + Test-MtCisThirdPartyAndCustomApps | Should -BeNullOrEmpty + $script:SkippedBecause | Should -Be 'NotSupportedAppPermission' + Should -Invoke Get-M365UnifiedTenantSettings -ModuleName Maester -Times 0 -Exactly + } + + It 'skips when unified tenant settings reports unsupported app-only authentication' { + Mock -ModuleName Maester Get-MgContext { $null } + Mock -ModuleName Maester Get-M365UnifiedTenantSettings { throw 'Application-based authentication is not supported for this cmdlet.' } + + Test-MtCisThirdPartyAndCustomApps | Should -BeNullOrEmpty + $script:SkippedBecause | Should -Be 'NotSupportedAppPermission' + } } Describe 'Test-MtCisTeamsReportSecurityConcerns' { @@ -129,6 +147,7 @@ Describe 'Test-MtCisTeamsReportSecurityConcerns' { EnableReportToMicrosoft = $false ReportChatMessageEnabled = $false ReportChatMessageToCustomizedAddressEnabled = $true + ReportChatMessageAddresses = @('soc@contoso.com') ReportJunkToCustomizedAddress = $true ReportNotJunkToCustomizedAddress = $true ReportPhishToCustomizedAddress = $true @@ -166,6 +185,20 @@ Describe 'Test-MtCisTeamsReportSecurityConcerns' { Test-MtCisTeamsReportSecurityConcerns | Should -BeFalse } + It 'fails when the Teams reporting mailbox is not configured' { + $script:Policy.ReportChatMessageAddresses = @() + + Test-MtCisTeamsReportSecurityConcerns | Should -BeFalse + $script:Result | Should -Match 'ReportChatMessageAddresses \| Not set \| soc@contoso.com \| ❌ Fail' + } + + It 'fails when a reporting destination differs from the single mailbox' { + $script:Rules[0].SentTo = @('triage@contoso.com') + + Test-MtCisTeamsReportSecurityConcerns | Should -BeFalse + $script:Result | Should -Match 'Report submission rule \(SentTo\) \| triage@contoso.com \| soc@contoso.com \| ❌ Fail' + } + It 'fails when no report submission policy is returned' { $script:Policy = $null Test-MtCisTeamsReportSecurityConcerns | Should -BeFalse diff --git a/tests/cis/Test.CIS.M365.2.4.4.ps1 b/tests/cis/Test.CIS.M365.2.4.4.ps1 index 97ff6bc910..39548d339e 100644 --- a/tests/cis/Test.CIS.M365.2.4.4.ps1 +++ b/tests/cis/Test.CIS.M365.2.4.4.ps1 @@ -54,9 +54,11 @@ if ($testResult) { $testResultMarkdown = "Well done. Your tenant has Zero-hour auto purge (ZAP) enabled for Microsoft Teams.`n`n%TestResult%" - } elseif ($policies.Count -eq 0) { + } + elseif ($policies.Count -eq 0) { $testResultMarkdown = "No Teams protection policy was returned, so Zero-hour auto purge (ZAP) for Microsoft Teams could not be confirmed.`n`n%TestResult%" - } else { + } + else { $testResultMarkdown = "Your tenant does not have Zero-hour auto purge (ZAP) enabled for Microsoft Teams.`n`n%TestResult%" } @@ -70,13 +72,14 @@ } if (@($exclusions).Count -gt 0) { - $resultMd += "`nReview these exclusions and confirm that each one is justified. ZAP does not act on Teams messages for these participants.`n`n" + $resultMd += "`nReview these exclusions and confirm that each one is justified. These exceptions match recipient conditions: if any recipient in a chat is not excluded, ZAP can still block the message for everyone. ZAP takes no action only when all recipients are excluded.`n`n" $resultMd += "| Exclusion | Participants |`n" $resultMd += "| --- | --- |`n" foreach ($exclusion in $exclusions) { $resultMd += "| $($exclusion.Exception) | $($exclusion.Values) |`n" } - } else { + } + else { $resultMd += "`nNo participants are excluded from Teams protection.`n" } diff --git a/tests/cis/Test.CIS.M365.8.2.2.ps1 b/tests/cis/Test.CIS.M365.8.2.2.ps1 index 5cbe107be1..63069dca19 100644 --- a/tests/cis/Test.CIS.M365.8.2.2.ps1 +++ b/tests/cis/Test.CIS.M365.8.2.2.ps1 @@ -45,7 +45,7 @@ $testResult = $orgSetting -eq $false -or $policySetting -eq $false $resultMarkdown = if ($testResult) { - "Well done. Communication with unmanaged Teams users is disabled.`n`n" + "Well done. Communication with unmanaged Teams users is turned off by the audited Global external access policy or organization setting. Custom external access policies assigned to users are not checked.`n`n" } else { "Communication with unmanaged Teams users is enabled. Turn it off in the Global external access policy or in the organization settings.`n`n" } diff --git a/tests/cis/Test.CIS.M365.8.2.3.ps1 b/tests/cis/Test.CIS.M365.8.2.3.ps1 index 7ba68f1e61..649fecb193 100644 --- a/tests/cis/Test.CIS.M365.8.2.3.ps1 +++ b/tests/cis/Test.CIS.M365.8.2.3.ps1 @@ -45,7 +45,7 @@ $testResult = $orgSetting -eq $false -or $policySetting -eq $false $resultMarkdown = if ($testResult) { - "Well done. External unmanaged Teams users cannot initiate conversations.`n`n" + "Well done. The audited Global external access policy or organization setting prevents external unmanaged Teams users from initiating conversations. Custom external access policies assigned to users are not checked.`n`n" } else { "External unmanaged Teams users can initiate conversations. Turn this off in the Global external access policy or in the organization settings.`n`n" } diff --git a/tests/cis/Test.CIS.M365.8.2.4.md b/tests/cis/Test.CIS.M365.8.2.4.md index 48ba9c98c7..f6e40afd9c 100644 --- a/tests/cis/Test.CIS.M365.8.2.4.md +++ b/tests/cis/Test.CIS.M365.8.2.4.md @@ -1,6 +1,6 @@ Trial Teams tenants are tenants that have only trial licenses and no purchased licenses. They are short-lived, easy to create and often used for spam and phishing. If your organization can communicate with accounts in trial tenants, users can receive messages and meeting invitations from senders that have little accountability. -Blocking trial tenants keeps external communication limited to organizations that have purchased licenses. Users in your organization can still communicate with all other allowed external organizations. Users from trial tenants are removed from existing chats, so contacts who use a trial tenant need another channel, such as email, until they move to a licensed tenant. +Setting `ExternalAccessWithTrialTenants` to `Blocked` blocks communication with trial-only tenants and removes their users from existing chats, except for domains explicitly allowed by `AllowedTrialTenantDomains`. This test reads only `ExternalAccessWithTrialTenants`, so a passing result doesn't rule out those allowlisted exceptions. Users in your organization can still communicate with other allowed external organizations. #### Remediation action diff --git a/tests/cis/Test.CIS.M365.8.4.1.md b/tests/cis/Test.CIS.M365.8.4.1.md index d4e90abc18..ea65550cc7 100644 --- a/tests/cis/Test.CIS.M365.8.4.1.md +++ b/tests/cis/Test.CIS.M365.8.4.1.md @@ -2,7 +2,7 @@ Users can't install third-party or custom Teams apps by default, and can't inter Third-party and custom apps can read and act on Teams data on behalf of users. An app that a user adds without review may be malicious, unverified or over-privileged, and custom apps in preview can be uploaded without admin approval. Turning these defaults off means that only apps an admin has made available can be used. Admins can still make individual apps available to everyone or to specific users and groups on the **Manage apps** page; the org-wide settings apply to apps whose availability hasn't been set. -The test reads the org-wide app settings with `Get-M365UnifiedTenantSettings` (`GlobalApp` for third-party apps and `PrivateApp` for custom apps must be `None`) and `Get-CsTeamsSettingsCustomApp` (`IsSideloadedAppsInteractionEnabled` must be `False`). +The test reads the org-wide app settings with `Get-M365UnifiedTenantSettings` (`GlobalApp` for third-party apps and `PrivateApp` for custom apps must be `None`) and `Get-CsTeamsSettingsCustomApp` (`IsSideloadedAppsInteractionEnabled` must be `False`). Microsoft doesn't support `Get-M365UnifiedTenantSettings` with application-based Teams authentication, and the documented Graph teams-app-settings endpoint doesn't support application permissions for these settings. The test skips app-only contexts; run it with delegated authentication. #### Remediation action diff --git a/tests/cis/Test.CIS.M365.8.4.1.ps1 b/tests/cis/Test.CIS.M365.8.4.1.ps1 index 6ad8d9f7a7..5d2972e0d9 100644 --- a/tests/cis/Test.CIS.M365.8.4.1.ps1 +++ b/tests/cis/Test.CIS.M365.8.4.1.ps1 @@ -39,7 +39,21 @@ Write-Verbose 'Test-MtCisThirdPartyAndCustomApps: Checking the Teams org-wide app settings' - $tenantSettings = @(Get-M365UnifiedTenantSettings) + $graphContext = if (Get-Command Get-MgContext -ErrorAction SilentlyContinue) { Get-MgContext } else { $null } + if ($graphContext -and $graphContext.AuthType -ne 'Delegated') { + Add-MtTestResultDetail -SkippedBecause NotSupportedAppPermission + return $null + } + + try { + $tenantSettings = @(Get-M365UnifiedTenantSettings -SettingNames GlobalApp, PrivateApp -ErrorAction Stop) + } catch { + if ($_.Exception.Message -match '(?i)(application[- ]based|app[- ]only|application authentication).{0,100}(not supported|unsupported)|(not supported|unsupported).{0,100}(application[- ]based|app[- ]only|application authentication)') { + Add-MtTestResultDetail -SkippedBecause NotSupportedAppPermission + return $null + } + throw + } $customAppSetting = Get-CsTeamsSettingsCustomApp $thirdParty = ($tenantSettings | Where-Object { $_.SettingName -eq 'GlobalApp' } | Select-Object -First 1).SettingValue diff --git a/tests/cis/Test.CIS.M365.8.6.1.md b/tests/cis/Test.CIS.M365.8.6.1.md index 4a814c2580..6001d293a7 100644 --- a/tests/cis/Test.CIS.M365.8.6.1.md +++ b/tests/cis/Test.CIS.M365.8.6.1.md @@ -32,6 +32,7 @@ $params = @{ EnableReportToMicrosoft = $false ReportChatMessageEnabled = $false ReportChatMessageToCustomizedAddressEnabled = $true + ReportChatMessageAddresses = $usersub ReportJunkToCustomizedAddress = $true ReportNotJunkToCustomizedAddress = $true ReportPhishToCustomizedAddress = $true @@ -43,7 +44,7 @@ Set-ReportSubmissionPolicy @params New-ReportSubmissionRule -Name DefaultReportSubmissionRule -ReportSubmissionPolicy DefaultReportSubmissionPolicy -SentTo $usersub ``` -If the report submission rule already exists, use `Set-ReportSubmissionRule -Identity DefaultReportSubmissionRule -SentTo $usersub` instead of `New-ReportSubmissionRule`. +If the report submission rule already exists, use `Set-ReportSubmissionRule -Identity DefaultReportSubmissionRule -SentTo $usersub` to configure its recipient. If the rule is disabled, enable it with `Enable-ReportSubmissionRule -Identity DefaultReportSubmissionRule`. #### Related links diff --git a/tests/cis/Test.CIS.M365.8.6.1.ps1 b/tests/cis/Test.CIS.M365.8.6.1.ps1 index 07d6d261fd..78231a2673 100644 --- a/tests/cis/Test.CIS.M365.8.6.1.ps1 +++ b/tests/cis/Test.CIS.M365.8.6.1.ps1 @@ -45,22 +45,57 @@ $reportPolicy = @(Get-MtExo -Request ReportSubmissionPolicy) | Select-Object -First 1 $reportRules = @(Get-MtExo -Request ReportSubmissionRule) | Where-Object { $_ } - $hasAddress = { param([object[]] $Values) @($Values | Where-Object { "$_" }).Count -gt 0 } - $ruleAddresses = @($reportRules | Where-Object { $_.State -ne 'Disabled' } | ForEach-Object { $_.SentTo } | Where-Object { "$_" }) + $ruleAddresses = @( + $reportRules | + Where-Object { $_.State -eq 'Enabled' } | + ForEach-Object { $_.SentTo } | + Where-Object { -not [string]::IsNullOrWhiteSpace("$($_)") } + ) + $destinationValues = [ordered]@{ + ReportJunkAddresses = @($reportPolicy.ReportJunkAddresses) + ReportNotJunkAddresses = @($reportPolicy.ReportNotJunkAddresses) + ReportPhishAddresses = @($reportPolicy.ReportPhishAddresses) + 'Report submission rule (SentTo)' = $ruleAddresses + ReportChatMessageAddresses = @($reportPolicy.ReportChatMessageAddresses) + } + $reportingMailbox = @( + $destinationValues.Values | + ForEach-Object { $_ } | + Where-Object { -not [string]::IsNullOrWhiteSpace("$($_)") } | + Select-Object -First 1 + )[0] + $normalizedMailbox = if ($reportingMailbox) { "$reportingMailbox".Trim().ToLowerInvariant() } else { $null } + $destinationChecks = foreach ($destination in $destinationValues.GetEnumerator()) { + $addresses = @( + $destination.Value | + Where-Object { -not [string]::IsNullOrWhiteSpace("$($_)") } | + ForEach-Object { "$_".Trim().ToLowerInvariant() } | + Sort-Object -Unique + ) + $displayAddresses = @( + $destination.Value | + Where-Object { -not [string]::IsNullOrWhiteSpace("$($_)") } | + ForEach-Object { "$_".Trim() } | + Sort-Object -Unique + ) + [pscustomobject]@{ + Setting = $destination.Key + Value = $displayAddresses -join ', ' + Expected = if ($reportingMailbox) { $reportingMailbox } else { 'One reporting mailbox' } + Pass = $null -ne $normalizedMailbox -and $addresses.Count -eq 1 -and $addresses[0] -eq $normalizedMailbox + } + } + $teamsAddressCheck = $destinationChecks | Where-Object { $_.Setting -eq 'ReportChatMessageAddresses' } $checks = @( [pscustomobject]@{ Setting = 'AllowSecurityEndUserReporting (Teams Global messaging policy)'; Value = $messagingPolicy.AllowSecurityEndUserReporting; Expected = 'True'; Pass = $messagingPolicy.AllowSecurityEndUserReporting -eq $true } [pscustomobject]@{ Setting = 'ReportChatMessageEnabled'; Value = $reportPolicy.ReportChatMessageEnabled; Expected = 'False'; Pass = $reportPolicy.ReportChatMessageEnabled -eq $false } - [pscustomobject]@{ Setting = 'ReportChatMessageToCustomizedAddressEnabled'; Value = $reportPolicy.ReportChatMessageToCustomizedAddressEnabled; Expected = 'True'; Pass = $reportPolicy.ReportChatMessageToCustomizedAddressEnabled -eq $true } + [pscustomobject]@{ Setting = 'ReportChatMessageToCustomizedAddressEnabled'; Value = $reportPolicy.ReportChatMessageToCustomizedAddressEnabled; Expected = 'True'; Pass = $reportPolicy.ReportChatMessageToCustomizedAddressEnabled -eq $true -and $teamsAddressCheck.Pass } [pscustomobject]@{ Setting = 'EnableReportToMicrosoft'; Value = $reportPolicy.EnableReportToMicrosoft; Expected = 'False'; Pass = $reportPolicy.EnableReportToMicrosoft -eq $false } [pscustomobject]@{ Setting = 'ReportJunkToCustomizedAddress'; Value = $reportPolicy.ReportJunkToCustomizedAddress; Expected = 'True'; Pass = $reportPolicy.ReportJunkToCustomizedAddress -eq $true } [pscustomobject]@{ Setting = 'ReportNotJunkToCustomizedAddress'; Value = $reportPolicy.ReportNotJunkToCustomizedAddress; Expected = 'True'; Pass = $reportPolicy.ReportNotJunkToCustomizedAddress -eq $true } [pscustomobject]@{ Setting = 'ReportPhishToCustomizedAddress'; Value = $reportPolicy.ReportPhishToCustomizedAddress; Expected = 'True'; Pass = $reportPolicy.ReportPhishToCustomizedAddress -eq $true } - [pscustomobject]@{ Setting = 'ReportJunkAddresses'; Value = @($reportPolicy.ReportJunkAddresses) -join ', '; Expected = 'Reporting mailbox'; Pass = & $hasAddress $reportPolicy.ReportJunkAddresses } - [pscustomobject]@{ Setting = 'ReportNotJunkAddresses'; Value = @($reportPolicy.ReportNotJunkAddresses) -join ', '; Expected = 'Reporting mailbox'; Pass = & $hasAddress $reportPolicy.ReportNotJunkAddresses } - [pscustomobject]@{ Setting = 'ReportPhishAddresses'; Value = @($reportPolicy.ReportPhishAddresses) -join ', '; Expected = 'Reporting mailbox'; Pass = & $hasAddress $reportPolicy.ReportPhishAddresses } - [pscustomobject]@{ Setting = 'Report submission rule (SentTo)'; Value = $ruleAddresses -join ', '; Expected = 'Enabled rule with the reporting mailbox'; Pass = $ruleAddresses.Count -gt 0 } - ) + ) + @($destinationChecks) $return = $null -ne $messagingPolicy -and $null -ne $reportPolicy -and @($checks | Where-Object { -not $_.Pass }).Count -eq 0 $result = "| Setting | Value | Expected | Status |`n" From ec4fe6b5355004f031dd822ffaecf22226a65729 Mon Sep 17 00:00:00 2001 From: Jeremy Finney Date: Sun, 1 Nov 2026 14:40:37 +1300 Subject: [PATCH 03/15] test: rename strict rule fixture helper --- ...tCisStrictPresetForPriorityAccount.Tests.ps1 | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 b/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 index 725ed9c877..c80ac3ab42 100644 --- a/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 @@ -13,8 +13,7 @@ $script:removeRecipientStub = $true } - function New-StrictRule { - [CmdletBinding(SupportsShouldProcess = $true)] + function Get-StrictRuleFixture { param([hashtable] $Conditions = @{}) $rule = [ordered]@{ Identity = 'Strict Preset Security Policy' @@ -40,7 +39,7 @@ AfterAll { Describe 'Test-MtCisStrictPresetForPriorityAccount' { BeforeEach { $script:Result = $null - $script:Rule = New-StrictRule -Conditions @{ SentToMemberOf = @('Priority Accounts') } + $script:Rule = Get-StrictRuleFixture -Conditions @{ SentToMemberOf = @('Priority Accounts') } $script:VipUsers = @( [pscustomobject]@{ Name = 'ceo' @@ -68,7 +67,7 @@ Describe 'Test-MtCisStrictPresetForPriorityAccount' { } It 'resolves SentTo values to the Entra object ID of the priority account' { - $script:Rule = New-StrictRule -Conditions @{ SentTo = @('Chief Exec Mailbox') } + $script:Rule = Get-StrictRuleFixture -Conditions @{ SentTo = @('Chief Exec Mailbox') } Mock -ModuleName Maester Get-Recipient { [pscustomobject]@{ ExternalDirectoryObjectId = 'user-ceo' } } -ParameterFilter { $Identity -eq 'Chief Exec Mailbox' } Test-MtCisStrictPresetForPriorityAccount | Should -BeTrue @@ -76,26 +75,26 @@ Describe 'Test-MtCisStrictPresetForPriorityAccount' { It 'includes subdomains of a RecipientDomainIs domain' { $script:VipUsers[0].WindowsEmailAddress = 'ceo@exec.contoso.com' - $script:Rule = New-StrictRule -Conditions @{ RecipientDomainIs = @('contoso.com') } + $script:Rule = Get-StrictRuleFixture -Conditions @{ RecipientDomainIs = @('contoso.com') } Test-MtCisStrictPresetForPriorityAccount | Should -BeTrue } It 'fails when a priority account matches an exception' { - $script:Rule = New-StrictRule -Conditions @{ SentToMemberOf = @('Priority Accounts'); ExceptIfSentTo = @('ceo@contoso.com') } + $script:Rule = Get-StrictRuleFixture -Conditions @{ SentToMemberOf = @('Priority Accounts'); ExceptIfSentTo = @('ceo@contoso.com') } Test-MtCisStrictPresetForPriorityAccount | Should -BeFalse $script:Result | Should -Match 'ceo@contoso.com' } It 'requires a priority account to meet every recipient condition that is set' { - $script:Rule = New-StrictRule -Conditions @{ SentTo = @('someone.else@contoso.com'); RecipientDomainIs = @('contoso.com') } + $script:Rule = Get-StrictRuleFixture -Conditions @{ SentTo = @('someone.else@contoso.com'); RecipientDomainIs = @('contoso.com') } Test-MtCisStrictPresetForPriorityAccount | Should -BeFalse } It 'fails when the rule has no recipient conditions' { - $script:Rule = New-StrictRule + $script:Rule = Get-StrictRuleFixture Test-MtCisStrictPresetForPriorityAccount | Should -BeFalse $script:Result | Should -Match 'All recipients \(no conditions\)' @@ -109,7 +108,7 @@ Describe 'Test-MtCisStrictPresetForPriorityAccount' { } It 'fails when a rule is disabled' { - $script:Rule = New-StrictRule -Conditions @{ SentToMemberOf = @('Priority Accounts'); State = 'Disabled' } + $script:Rule = Get-StrictRuleFixture -Conditions @{ SentToMemberOf = @('Priority Accounts'); State = 'Disabled' } Test-MtCisStrictPresetForPriorityAccount | Should -BeFalse } From 56688eebf56db221a0ce0c48bca7c0afe1e70860 Mon Sep 17 00:00:00 2001 From: Jeremy Finney Date: Sun, 1 Nov 2026 14:47:24 +1300 Subject: [PATCH 04/15] fix(cis): base app-only skip on Teams auth --- .../tests/functions/Test-MtCisTeamsChecks.Tests.ps1 | 9 +++------ tests/cis/Test.CIS.M365.8.4.1.md | 2 +- tests/cis/Test.CIS.M365.8.4.1.ps1 | 6 ------ 3 files changed, 4 insertions(+), 13 deletions(-) diff --git a/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 b/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 index 0d5a921872..f04ffb63dd 100644 --- a/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 @@ -96,7 +96,6 @@ Describe 'Test-MtCisThirdPartyAndCustomApps' { ) $script:CustomApp = [pscustomobject]@{ IsSideloadedAppsInteractionEnabled = $false } Mock -ModuleName Maester Add-MtTestResultDetail { param($Result, $SkippedBecause) $script:Result = $Result; $script:SkippedBecause = $SkippedBecause } - Mock -ModuleName Maester Get-MgContext { [pscustomobject]@{ AuthType = 'Delegated' } } Mock -ModuleName Maester Get-M365UnifiedTenantSettings { $script:TenantSettings } Mock -ModuleName Maester Get-CsTeamsSettingsCustomApp { $script:CustomApp } } @@ -122,16 +121,14 @@ Describe 'Test-MtCisThirdPartyAndCustomApps' { $script:Result | Should -Match 'Not found' } - It 'skips before reading unified tenant settings with app-only authentication' { + It 'uses Teams settings when the Graph context is app-only' { Mock -ModuleName Maester Get-MgContext { [pscustomobject]@{ AuthType = 'AppOnly' } } - Test-MtCisThirdPartyAndCustomApps | Should -BeNullOrEmpty - $script:SkippedBecause | Should -Be 'NotSupportedAppPermission' - Should -Invoke Get-M365UnifiedTenantSettings -ModuleName Maester -Times 0 -Exactly + Test-MtCisThirdPartyAndCustomApps | Should -BeTrue + Should -Invoke Get-M365UnifiedTenantSettings -ModuleName Maester -Times 1 -Exactly } It 'skips when unified tenant settings reports unsupported app-only authentication' { - Mock -ModuleName Maester Get-MgContext { $null } Mock -ModuleName Maester Get-M365UnifiedTenantSettings { throw 'Application-based authentication is not supported for this cmdlet.' } Test-MtCisThirdPartyAndCustomApps | Should -BeNullOrEmpty diff --git a/tests/cis/Test.CIS.M365.8.4.1.md b/tests/cis/Test.CIS.M365.8.4.1.md index ea65550cc7..5a2fa34994 100644 --- a/tests/cis/Test.CIS.M365.8.4.1.md +++ b/tests/cis/Test.CIS.M365.8.4.1.md @@ -2,7 +2,7 @@ Users can't install third-party or custom Teams apps by default, and can't inter Third-party and custom apps can read and act on Teams data on behalf of users. An app that a user adds without review may be malicious, unverified or over-privileged, and custom apps in preview can be uploaded without admin approval. Turning these defaults off means that only apps an admin has made available can be used. Admins can still make individual apps available to everyone or to specific users and groups on the **Manage apps** page; the org-wide settings apply to apps whose availability hasn't been set. -The test reads the org-wide app settings with `Get-M365UnifiedTenantSettings` (`GlobalApp` for third-party apps and `PrivateApp` for custom apps must be `None`) and `Get-CsTeamsSettingsCustomApp` (`IsSideloadedAppsInteractionEnabled` must be `False`). Microsoft doesn't support `Get-M365UnifiedTenantSettings` with application-based Teams authentication, and the documented Graph teams-app-settings endpoint doesn't support application permissions for these settings. The test skips app-only contexts; run it with delegated authentication. +The test reads the org-wide app settings with `Get-M365UnifiedTenantSettings` (`GlobalApp` for third-party apps and `PrivateApp` for custom apps must be `None`) and `Get-CsTeamsSettingsCustomApp` (`IsSideloadedAppsInteractionEnabled` must be `False`). Microsoft doesn't support `Get-M365UnifiedTenantSettings` with application-based Teams authentication, and the documented Graph teams-app-settings endpoint doesn't support application permissions for these settings. The test skips when the Teams settings cmdlet reports unsupported application authentication; it does not use `Get-MgContext`, which describes the separate Graph session. Run 8.4.1 with delegated Teams authentication. #### Remediation action diff --git a/tests/cis/Test.CIS.M365.8.4.1.ps1 b/tests/cis/Test.CIS.M365.8.4.1.ps1 index 5d2972e0d9..b71467aea6 100644 --- a/tests/cis/Test.CIS.M365.8.4.1.ps1 +++ b/tests/cis/Test.CIS.M365.8.4.1.ps1 @@ -39,12 +39,6 @@ Write-Verbose 'Test-MtCisThirdPartyAndCustomApps: Checking the Teams org-wide app settings' - $graphContext = if (Get-Command Get-MgContext -ErrorAction SilentlyContinue) { Get-MgContext } else { $null } - if ($graphContext -and $graphContext.AuthType -ne 'Delegated') { - Add-MtTestResultDetail -SkippedBecause NotSupportedAppPermission - return $null - } - try { $tenantSettings = @(Get-M365UnifiedTenantSettings -SettingNames GlobalApp, PrivateApp -ErrorAction Stop) } catch { From cb728f4634df269e9f90b803d041efe64b1001f1 Mon Sep 17 00:00:00 2001 From: Jeremy Finney Date: Sun, 1 Nov 2026 15:09:30 +1300 Subject: [PATCH 05/15] fix(cis): short-circuit Teams unmanaged user checks --- .../functions/Test-MtCisTeamsChecks.Tests.ps1 | 46 ++++++++++++++++++- tests/cis/Test.CIS.M365.8.2.2.ps1 | 11 +++-- tests/cis/Test.CIS.M365.8.2.3.ps1 | 11 +++-- 3 files changed, 61 insertions(+), 7 deletions(-) diff --git a/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 b/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 index f04ffb63dd..20091bc405 100644 --- a/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 @@ -5,7 +5,7 @@ # MicrosoftTeams is optional; stubs let its cmdlets be mocked when it is not installed. $script:stubs = @() - foreach ($name in 'Get-CsTeamsClientConfiguration', 'Get-CsTeamsMessagingPolicy', 'Get-M365UnifiedTenantSettings', 'Get-CsTeamsSettingsCustomApp') { + foreach ($name in 'Get-CsTeamsClientConfiguration', 'Get-CsTeamsMessagingPolicy', 'Get-M365UnifiedTenantSettings', 'Get-CsTeamsSettingsCustomApp', 'Get-CsTenantFederationConfiguration', 'Get-CsExternalAccessPolicy') { if (-not (Get-Command $name -ErrorAction SilentlyContinue)) { Set-Item -Path "function:global:$name" -Value { [CmdletBinding()] @@ -15,6 +15,9 @@ $script:stubs += $name } } + + . "$PSScriptRoot/../../../tests/cis/Test.CIS.M365.8.2.2.ps1" + . "$PSScriptRoot/../../../tests/cis/Test.CIS.M365.8.2.3.ps1" } AfterAll { @@ -57,6 +60,47 @@ Describe 'Test-MtCisZAP' { } } +Describe 'CIS unmanaged Teams user settings' { + BeforeEach { + $script:Federation = [pscustomobject]@{ + AllowTeamsConsumer = $false + AllowTeamsConsumerInbound = $false + } + $script:GlobalPolicy = $null + Mock Get-CsTenantFederationConfiguration { $script:Federation } + Mock Get-CsExternalAccessPolicy { + if ($null -eq $script:GlobalPolicy) { throw 'The Global policy lookup should not run.' } + $script:GlobalPolicy + } + } + + It 'passes 8.2.2 without looking up the Global policy when the organization setting is false' { + Test-MtCisCommunicateWithUnmanagedTeamsUsers | Should -BeTrue + Should -Invoke Get-CsExternalAccessPolicy -Times 0 -Exactly + } + + It 'passes 8.2.3 without looking up the Global policy when the organization setting is false' { + Test-MtCisCommunicateInitiateExternalTeamsUsers | Should -BeTrue + Should -Invoke Get-CsExternalAccessPolicy -Times 0 -Exactly + } + + It 'uses the Global policy fallback for 8.2.2 when the organization setting is enabled' { + $script:Federation.AllowTeamsConsumer = $true + $script:GlobalPolicy = [pscustomobject]@{ EnableTeamsConsumerAccess = $false } + + Test-MtCisCommunicateWithUnmanagedTeamsUsers | Should -BeTrue + Should -Invoke Get-CsExternalAccessPolicy -Times 1 -Exactly + } + + It 'uses the Global policy fallback for 8.2.3 when the organization setting is enabled' { + $script:Federation.AllowTeamsConsumerInbound = $true + $script:GlobalPolicy = [pscustomobject]@{ EnableTeamsConsumerInbound = $false } + + Test-MtCisCommunicateInitiateExternalTeamsUsers | Should -BeTrue + Should -Invoke Get-CsExternalAccessPolicy -Times 1 -Exactly + } +} + Describe 'Test-MtCisThirdPartyFileSharing' { BeforeEach { $script:Result = $null diff --git a/tests/cis/Test.CIS.M365.8.2.2.ps1 b/tests/cis/Test.CIS.M365.8.2.2.ps1 index 63069dca19..76cce31e12 100644 --- a/tests/cis/Test.CIS.M365.8.2.2.ps1 +++ b/tests/cis/Test.CIS.M365.8.2.2.ps1 @@ -39,9 +39,12 @@ Write-Verbose 'Test-MtCisCommunicateWithUnmanagedTeamsUsers: Checking if communication with unmanaged Teams users is disabled' $federation = Get-CsTenantFederationConfiguration - $externalAccessPolicy = Get-CsExternalAccessPolicy -Identity Global $orgSetting = $federation.AllowTeamsConsumer - $policySetting = $externalAccessPolicy.EnableTeamsConsumerAccess + $policySetting = $null + if ($orgSetting -ne $false) { + $externalAccessPolicy = Get-CsExternalAccessPolicy -Identity Global + $policySetting = $externalAccessPolicy.EnableTeamsConsumerAccess + } $testResult = $orgSetting -eq $false -or $policySetting -eq $false $resultMarkdown = if ($testResult) { @@ -52,7 +55,9 @@ $resultMarkdown += "| Setting | Value | Result |`n" $resultMarkdown += "| --- | --- | --- |`n" $resultMarkdown += "| AllowTeamsConsumer (organization settings) | $(if ($null -eq $orgSetting) { 'Not found' } else { $orgSetting }) | $(if ($orgSetting -eq $false) { 'Pass' } else { 'Fail' }) |`n" - $resultMarkdown += "| EnableTeamsConsumerAccess (Global external access policy) | $(if ($null -eq $policySetting) { 'Not found' } else { $policySetting }) | $(if ($policySetting -eq $false) { 'Pass' } else { 'Fail' }) |`n" + $policyValue = if ($orgSetting -eq $false) { 'Not checked' } elseif ($null -eq $policySetting) { 'Not found' } else { $policySetting } + $policyResult = if ($orgSetting -eq $false) { 'Not checked' } elseif ($policySetting -eq $false) { 'Pass' } else { 'Fail' } + $resultMarkdown += "| EnableTeamsConsumerAccess (Global external access policy) | $policyValue | $policyResult |`n" $resultMarkdown += "`nEither setting turned off meets the CIS recommendation." Add-MtTestResultDetail -Result $resultMarkdown diff --git a/tests/cis/Test.CIS.M365.8.2.3.ps1 b/tests/cis/Test.CIS.M365.8.2.3.ps1 index 649fecb193..b1f9427590 100644 --- a/tests/cis/Test.CIS.M365.8.2.3.ps1 +++ b/tests/cis/Test.CIS.M365.8.2.3.ps1 @@ -39,9 +39,12 @@ Write-Verbose 'Test-MtCisCommunicateInitiateExternalTeamsUsers: Checking if external unmanaged Teams users cannot initiate conversations' $federation = Get-CsTenantFederationConfiguration - $externalAccessPolicy = Get-CsExternalAccessPolicy -Identity Global $orgSetting = $federation.AllowTeamsConsumerInbound - $policySetting = $externalAccessPolicy.EnableTeamsConsumerInbound + $policySetting = $null + if ($orgSetting -ne $false) { + $externalAccessPolicy = Get-CsExternalAccessPolicy -Identity Global + $policySetting = $externalAccessPolicy.EnableTeamsConsumerInbound + } $testResult = $orgSetting -eq $false -or $policySetting -eq $false $resultMarkdown = if ($testResult) { @@ -52,7 +55,9 @@ $resultMarkdown += "| Setting | Value | Result |`n" $resultMarkdown += "| --- | --- | --- |`n" $resultMarkdown += "| AllowTeamsConsumerInbound (organization settings) | $(if ($null -eq $orgSetting) { 'Not found' } else { $orgSetting }) | $(if ($orgSetting -eq $false) { 'Pass' } else { 'Fail' }) |`n" - $resultMarkdown += "| EnableTeamsConsumerInbound (Global external access policy) | $(if ($null -eq $policySetting) { 'Not found' } else { $policySetting }) | $(if ($policySetting -eq $false) { 'Pass' } else { 'Fail' }) |`n" + $policyValue = if ($orgSetting -eq $false) { 'Not checked' } elseif ($null -eq $policySetting) { 'Not found' } else { $policySetting } + $policyResult = if ($orgSetting -eq $false) { 'Not checked' } elseif ($policySetting -eq $false) { 'Pass' } else { 'Fail' } + $resultMarkdown += "| EnableTeamsConsumerInbound (Global external access policy) | $policyValue | $policyResult |`n" $resultMarkdown += "`nEither setting turned off meets the CIS recommendation." Add-MtTestResultDetail -Result $resultMarkdown From 21d70d574eebf587ce5421840856e8b2bde5c36d Mon Sep 17 00:00:00 2001 From: Jeremy Finney Date: Wed, 4 Nov 2026 11:30:46 +1300 Subject: [PATCH 06/15] Add CIS parked-domain audit handling --- .../Get-MtCisParkedDomainClassification.ps1 | 137 ++++++++++++++ .../services/exchange/Resolve-MtDnsRecord.ps1 | 132 ++++++++++++++ .../exchange/Resolve-MtDnsTxtRecord.ps1 | 56 +----- ...-MtCisParkedDomainClassification.Tests.ps1 | 160 +++++++++++++++++ .../functions/Resolve-MtDnsRecord.Tests.ps1 | 170 ++++++++++++++++++ .../Test-MtCisDmarcRecordsPublished.Tests.ps1 | 114 +++++++++++- .../Test-MtCisSpfRecordsPublished.Tests.ps1 | 107 +++++++++++ .../tests/functions/Test-MtDkim.Tests.ps1 | 58 +++++- tests/cis/Test.CIS.M365.2.1.10.md | 12 +- tests/cis/Test.CIS.M365.2.1.10.ps1 | 77 ++++++-- tests/cis/Test.CIS.M365.2.1.8.md | 12 +- tests/cis/Test.CIS.M365.2.1.8.ps1 | 64 +++++-- tests/cis/Test.CIS.M365.2.1.9.md | 10 +- tests/cis/Test.CIS.M365.2.1.9.ps1 | 84 ++++++--- 14 files changed, 1073 insertions(+), 120 deletions(-) create mode 100644 powershell/internal/checks/cis/exchange/Get-MtCisParkedDomainClassification.ps1 create mode 100644 powershell/internal/services/exchange/Resolve-MtDnsRecord.ps1 create mode 100644 powershell/tests/functions/Get-MtCisParkedDomainClassification.Tests.ps1 create mode 100644 powershell/tests/functions/Resolve-MtDnsRecord.Tests.ps1 create mode 100644 powershell/tests/functions/Test-MtCisSpfRecordsPublished.Tests.ps1 diff --git a/powershell/internal/checks/cis/exchange/Get-MtCisParkedDomainClassification.ps1 b/powershell/internal/checks/cis/exchange/Get-MtCisParkedDomainClassification.ps1 new file mode 100644 index 0000000000..90634ac61c --- /dev/null +++ b/powershell/internal/checks/cis/exchange/Get-MtCisParkedDomainClassification.ps1 @@ -0,0 +1,137 @@ +function Get-MtCisParkedDomainClassification { + <# + .SYNOPSIS + Classifies an accepted domain using DNS evidence for the CIS email-authentication checks. + + .DESCRIPTION + Sending requires a positive SPF mechanism, a DKIM selector record, or an Exchange DKIM signing + configuration. NotSending requires a single SPF record with only a non-authorizing all + mechanism and no known DKIM selector records or Exchange signing configuration. Parked + additionally requires no MX record (or a null MX) and no address or CNAME record at the domain + apex. Incomplete or conflicting evidence is Unknown and must not receive the parked-domain + audit exception. + + .PARAMETER DomainName + The accepted domain to classify. + + .PARAMETER DkimSigningConfigs + Exchange DKIM signing configurations already retrieved by the calling test. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] + [string]$DomainName, + + [object[]]$DkimSigningConfigs = @(), + + [string[]]$ParkedDomains = @() + ) + + $lookups = [ordered]@{ + SPF = Resolve-MtDnsRecord -Name $DomainName -Type TXT + MX = Resolve-MtDnsRecord -Name $DomainName -Type MX + A = Resolve-MtDnsRecord -Name $DomainName -Type A + AAAA = Resolve-MtDnsRecord -Name $DomainName -Type AAAA + CNAME = Resolve-MtDnsRecord -Name $DomainName -Type CNAME + } + foreach ($selector in 'selector1', 'selector2') { + foreach ($type in 'CNAME', 'TXT') { + $lookupName = "$selector._domainkey.$DomainName" + $lookups["DKIM:$selector`:$type"] = Resolve-MtDnsRecord -Name $lookupName -Type $type + } + } + + $spfAnswers = @($lookups.SPF.Answers | ForEach-Object { $_.Value } | Where-Object { $_ -match '^\s*v=spf1(?:\s|$)' }) + $spfRecord = if ($spfAnswers.Count -eq 1) { [string]$spfAnswers[0] } else { $null } + $spfTerms = if ($spfRecord) { @($spfRecord.Trim() -split '\s+' | Select-Object -Skip 1) } else { @() } + $spfAllTerms = @($spfTerms | Where-Object { $_ -match '^(?i)[+?~-]?all$' }) + $spfRedirectTerms = @($spfTerms | Where-Object { $_ -match '^(?i)redirect=' }) + $spfOtherTerms = @($spfTerms | Where-Object { $_ -notmatch '^(?i)[+?~-]?all$' -and $_ -notmatch '^(?i)exp=' -and $_ -notmatch '^(?i)redirect=' }) + $spfAllQualifier = if ($spfAllTerms.Count -eq 1) { + $qualifier = [regex]::Match($spfAllTerms[0], '^(?[+?~-]?)all$', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase).Groups['qualifier'].Value + if ($qualifier) { $qualifier } else { '+' } + } else { + $null + } + $spfDoesNotAuthorizeSenders = $spfAllTerms.Count -eq 1 -and $spfAllQualifier -in @('-', '~', '?') -and $spfOtherTerms.Count -eq 0 + $spfHasSenderMechanisms = $spfRecord -and -not $spfDoesNotAuthorizeSenders -and ($spfOtherTerms.Count -gt 0 -or $spfAllQualifier -eq '+') + + $domainConfigs = @($DkimSigningConfigs | Where-Object { + $configDomain = $null + if ($_.PSObject.Properties['Domain']) { + $configDomain = $_.Domain + } elseif ($_.PSObject.Properties['Name']) { + $configDomain = $_.Name + } + $configDomain -and [string]::Equals([string]$configDomain, $DomainName, [System.StringComparison]::OrdinalIgnoreCase) + }) + $dkimLookups = @($lookups.GetEnumerator() | Where-Object { $_.Key -like 'DKIM:*' }) + $hasDkimEvidence = $domainConfigs.Count -gt 0 -or @($dkimLookups | Where-Object { @($_.Value.Answers).Count -gt 0 }).Count -gt 0 + $unknownDkimLookups = @($dkimLookups | Where-Object { $_.Value.Status -notin @('Success', 'NXDomain') }) + + $classification = 'Unknown' + $reason = 'The DNS evidence does not establish whether the domain sends email.' + if ($hasDkimEvidence -or $spfHasSenderMechanisms) { + $classification = 'Sending' + $reason = 'An Exchange DKIM configuration, a known DKIM selector record, or an SPF mechanism other than -all indicates email-sending use.' + } elseif ($spfDoesNotAuthorizeSenders -and $unknownDkimLookups.Count -eq 0) { + $classification = 'NotSending' + $reason = 'SPF has only a non-authorizing all mechanism and no Exchange DKIM configuration or selector1/selector2 records were found.' + + $mxRecords = @($lookups.MX.Answers) + $nullMx = $mxRecords.Count -eq 1 -and [string]$mxRecords[0].Value -eq '.' -and [string]$mxRecords[0].Preference -eq '0' + $hasMx = @($mxRecords | Where-Object { [string]$_.Value -and [string]$_.Value -ne '.' }).Count -gt 0 + $hasAddress = @($lookups.A.Answers).Count -gt 0 -or @($lookups.AAAA.Answers).Count -gt 0 + $hasCname = @($lookups.CNAME.Answers).Count -gt 0 + $receivingLookupsKnown = @($lookups.MX, $lookups.A, $lookups.AAAA, $lookups.CNAME | Where-Object { $_.Status -notin @('Success', 'NXDomain') }).Count -eq 0 + $hasNoMx = $mxRecords.Count -eq 0 + + if ($receivingLookupsKnown -and -not $hasMx -and -not $hasAddress -and -not $hasCname -and ($hasNoMx -or $nullMx)) { + $classification = 'Parked' + $reason = if ($nullMx) { + 'SPF has only a non-authorizing all mechanism, no DKIM configuration or known selector records exist, and null MX plus no apex address or CNAME records indicates no email or other DNS use.' + } else { + 'SPF has only a non-authorizing all mechanism, no DKIM configuration or known selector records exist, and no MX, fallback address, or apex CNAME records were found.' + } + } + } + + if ($classification -eq 'Unknown') { + $failedLookups = @($lookups.GetEnumerator() | Where-Object { $_.Value.Status -notin @('Success', 'NXDomain') }) + if ($failedLookups.Count -gt 0) { + $reason = "DNS lookup results are incomplete for $($failedLookups.Key -join ', '); the domain is not classified as parked." + } elseif (-not $spfRecord) { + $reason = 'A single SPF v1 record was not found; the domain is not classified as parked.' + } else { + $reason = 'The SPF and DKIM evidence is conflicting or inconclusive; the domain is not classified as parked.' + } + } elseif ($classification -eq 'NotSending') { + $failedReceivingLookups = @($lookups.MX, $lookups.A, $lookups.AAAA, $lookups.CNAME | Where-Object { $_.Status -notin @('Success', 'NXDomain') }) + if ($failedReceivingLookups.Count -gt 0) { + $reason += ' Receiving or other domain use could not be ruled out because some DNS lookups failed.' + } elseif ($hasMx -or $hasAddress -or $hasCname) { + $reason += ' Receiving or other domain use is present, so the domain is not classified as parked.' + } + } + + $isOverride = @($ParkedDomains | Where-Object { + [string]::Equals($_.TrimEnd('.'), $DomainName.TrimEnd('.'), [System.StringComparison]::OrdinalIgnoreCase) + }).Count -gt 0 + if ($isOverride) { + $automaticClassification = $classification + $classification = 'Parked' + $reason = "The domain was explicitly listed in ParkedDomains. Automatic DNS classification was '$automaticClassification'." + } + + return [pscustomobject]@{ + DomainName = $DomainName + Classification = $classification + IsParked = $classification -eq 'Parked' + IsOverride = $isOverride + SpfRecord = $spfRecord + SpfDeniesAll = $spfDoesNotAuthorizeSenders -and $spfAllQualifier -eq '-' -and $spfRedirectTerms.Count -eq 0 + DkimEvidence = $hasDkimEvidence + Reason = $reason + } +} \ No newline at end of file diff --git a/powershell/internal/services/exchange/Resolve-MtDnsRecord.ps1 b/powershell/internal/services/exchange/Resolve-MtDnsRecord.ps1 new file mode 100644 index 0000000000..7430139d01 --- /dev/null +++ b/powershell/internal/services/exchange/Resolve-MtDnsRecord.ps1 @@ -0,0 +1,132 @@ +function Resolve-MtDnsRecord { + <# + .SYNOPSIS + Resolves DNS records with consistent results across supported platforms. + + .DESCRIPTION + Uses Resolve-DnsName on Windows and Resolve-Dns from DnsClient-PS on other platforms. + A successful query with no answers has Status Success and an empty Answers array. + + .PARAMETER Name + The DNS name to query. + + .PARAMETER Type + The DNS record type to query. + #> + [CmdletBinding()] + [OutputType([pscustomobject])] + param( + [Parameter(Mandatory)] + [string]$Name, + + [Parameter(Mandatory)] + [ValidateSet('A', 'AAAA', 'CNAME', 'MX', 'TXT')] + [string]$Type + ) + + $result = [pscustomobject]@{ + Name = $Name + Type = $Type + Status = 'Success' + Answers = [object[]]@() + Error = $null + } + $answers = @() + + if ($IsWindows) { + try { + $response = Resolve-DnsName -Name $Name -Type $Type -ErrorAction Stop + $answers = @($response | Where-Object { $_.Section -eq 'Answer' -and $_.Type -eq $Type }) + } catch [System.Management.Automation.CommandNotFoundException] { + $result.Status = 'NotAvailable' + $result.Error = 'Unsupported platform, Resolve-DnsName not available' + return $result + } catch { + if ($_.FullyQualifiedErrorId -like 'DNS_ERROR_RCODE_NAME_ERROR*') { + $result.Status = 'NXDomain' + } elseif ($_.FullyQualifiedErrorId -notlike 'DNS_INFO_NO_RECORDS*') { + $result.Status = 'Error' + $result.Error = "$_" + } + return $result + } + } else { + if (-not (Get-Command -Name 'Resolve-Dns' -ErrorAction SilentlyContinue)) { + $result.Status = 'NotAvailable' + $result.Error = 'Missing dependency, Resolve-Dns not available' + return $result + } + + try { + $response = Resolve-Dns -Query $Name -QueryType $Type -ErrorAction Stop + if ($response.HasError) { + if ("$($response.Header.ResponseCode)" -eq 'NotExistentDomain') { + $result.Status = 'NXDomain' + } else { + $result.Status = 'Error' + $result.Error = $response.ErrorMessage + } + return $result + } + $answers = @($response.Answers | Where-Object { "$($_.RecordType)" -eq $Type }) + } catch { + $result.Status = 'Error' + $result.Error = "$_" + return $result + } + } + + foreach ($answer in $answers) { + $value = $null + $preference = $null + switch ($Type) { + 'TXT' { + if ($answer.PSObject.Properties['Strings']) { + $value = @($answer.Strings) -join '' + } elseif ($answer.PSObject.Properties['Text']) { + $value = @($answer.Text) -join '' + } + } + 'MX' { + if ($answer.PSObject.Properties['NameExchange']) { + $value = $answer.NameExchange + } elseif ($answer.PSObject.Properties['Exchange']) { + $value = $answer.Exchange + } + if ($answer.PSObject.Properties['Preference']) { + $preference = $answer.Preference + } + } + 'CNAME' { + foreach ($propertyName in 'NameHost', 'CanonicalName', 'CName', 'HostName') { + if ($answer.PSObject.Properties[$propertyName]) { + $value = $answer.PSObject.Properties[$propertyName].Value + break + } + } + } + { $_ -in 'A', 'AAAA' } { + foreach ($propertyName in 'IPAddress', 'IPv4Address', 'IPv6Address', 'Address') { + if ($answer.PSObject.Properties[$propertyName]) { + $value = $answer.PSObject.Properties[$propertyName].Value + break + } + } + } + } + + if ($null -eq $value -or [string]::IsNullOrWhiteSpace([string]$value)) { + $result.Status = 'Error' + $result.Error = "The DNS resolver returned an unusable $Type answer for $Name." + $result.Answers = [object[]]@() + return $result + } + + $result.Answers += [pscustomobject]@{ + Value = [string]$value + Preference = $preference + } + } + + return $result +} \ No newline at end of file diff --git a/powershell/internal/services/exchange/Resolve-MtDnsTxtRecord.ps1 b/powershell/internal/services/exchange/Resolve-MtDnsTxtRecord.ps1 index 2cd1adfa34..1bc6b4aeb0 100644 --- a/powershell/internal/services/exchange/Resolve-MtDnsTxtRecord.ps1 +++ b/powershell/internal/services/exchange/Resolve-MtDnsTxtRecord.ps1 @@ -29,55 +29,11 @@ [string]$Name ) - $result = [pscustomobject]@{ - Name = $Name - Status = 'Success' - Answers = [string[]]@() - Error = $null + $dnsResult = Resolve-MtDnsRecord -Name $Name -Type TXT + return [pscustomobject]@{ + Name = $dnsResult.Name + Status = $dnsResult.Status + Answers = [string[]]@($dnsResult.Answers | ForEach-Object { $_.Value }) + Error = $dnsResult.Error } - - if ($IsWindows) { - try { - $response = Resolve-DnsName -Name $Name -Type TXT -ErrorAction Stop - $result.Answers = [string[]]@($response | Where-Object { $_.Section -eq 'Answer' -and $_.Type -eq 'TXT' } | ForEach-Object { $_.Strings -join '' }) - } catch [System.Management.Automation.CommandNotFoundException] { - $result.Status = 'NotAvailable' - $result.Error = 'Unsupported platform, Resolve-DnsName not available' - } catch { - Write-Verbose "TXT lookup for $($Name) failed: $_" - if ($_.FullyQualifiedErrorId -like 'DNS_ERROR_RCODE_NAME_ERROR*') { - $result.Status = 'NXDomain' - } elseif ($_.FullyQualifiedErrorId -notlike 'DNS_INFO_NO_RECORDS*') { - $result.Status = 'Error' - $result.Error = "$_" - } - } - return $result - } - - if (-not (Get-Command -Name 'Resolve-Dns' -ErrorAction SilentlyContinue)) { - Write-Verbose 'For non-Windows platforms, please install the DnsClient-PS module: Install-Module DnsClient-PS -Scope CurrentUser' - $result.Status = 'NotAvailable' - $result.Error = 'Missing dependency, Resolve-Dns not available' - return $result - } - - try { - $response = Resolve-Dns -Query $Name -QueryType TXT -ErrorAction Stop - if ($response.HasError) { - if ("$($response.Header.ResponseCode)" -eq 'NotExistentDomain') { - $result.Status = 'NXDomain' - } else { - $result.Status = 'Error' - $result.Error = $response.ErrorMessage - } - } else { - $result.Answers = [string[]]@($response.Answers | Where-Object { "$($_.RecordType)" -eq 'TXT' } | ForEach-Object { $_.Text -join '' }) - } - } catch { - Write-Verbose "TXT lookup for $($Name) failed: $_" - $result.Status = 'Error' - $result.Error = "$_" - } - return $result } diff --git a/powershell/tests/functions/Get-MtCisParkedDomainClassification.Tests.ps1 b/powershell/tests/functions/Get-MtCisParkedDomainClassification.Tests.ps1 new file mode 100644 index 0000000000..7230a8c7a5 --- /dev/null +++ b/powershell/tests/functions/Get-MtCisParkedDomainClassification.Tests.ps1 @@ -0,0 +1,160 @@ +Describe 'Get-MtCisParkedDomainClassification' { + BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force -WarningAction SilentlyContinue + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name Get-MtCisParkedDomainClassification + + function New-TestDnsResult { + param( + [string]$Name, + [string]$Type, + [object[]]$Answers = @(), + [string]$Status = 'Success' + ) + [pscustomobject]@{ Name = $Name; Type = $Type; Status = $Status; Answers = $Answers; Error = $null } + } + } + + BeforeEach { + $script:dnsResults = @{} + Mock Resolve-MtDnsRecord -ModuleName Maester { + $key = "$Type|$Name" + if ($script:dnsResults.ContainsKey($key)) { + return $script:dnsResults[$key] + } + return New-TestDnsResult -Name $Name -Type $Type + } + } + + It 'classifies a deny-all domain with null MX and no other DNS use as parked' { + $script:dnsResults['TXT|parked.example'] = New-TestDnsResult -Name 'parked.example' -Type TXT -Answers @( + [pscustomobject]@{ Value = 'v=spf1 -all'; Preference = $null } + ) + $script:dnsResults['MX|parked.example'] = New-TestDnsResult -Name 'parked.example' -Type MX -Answers @( + [pscustomobject]@{ Value = '.'; Preference = 0 } + ) + + $result = Get-MtCisParkedDomainClassification -DomainName 'parked.example' + + $result.Classification | Should -Be 'Parked' + $result.IsParked | Should -BeTrue + } + + It 'classifies a deny-all domain without MX or fallback addresses as parked' { + $script:dnsResults['TXT|parked.example'] = New-TestDnsResult -Name 'parked.example' -Type TXT -Answers @( + [pscustomobject]@{ Value = 'v=spf1 -all'; Preference = $null } + ) + + $result = Get-MtCisParkedDomainClassification -DomainName 'parked.example' + + $result.Classification | Should -Be 'Parked' + } + + It 'classifies a softfail-only domain as parked so the audit can enforce hard fail' { + $script:dnsResults['TXT|parked.example'] = New-TestDnsResult -Name 'parked.example' -Type TXT -Answers @( + [pscustomobject]@{ Value = 'v=spf1 ~all'; Preference = $null } + ) + + $result = Get-MtCisParkedDomainClassification -DomainName 'parked.example' + + $result.Classification | Should -Be 'Parked' + $result.SpfDeniesAll | Should -BeFalse + } + + It 'does not classify a domain with fallback address records as parked' { + $script:dnsResults['TXT|mail.example'] = New-TestDnsResult -Name 'mail.example' -Type TXT -Answers @( + [pscustomobject]@{ Value = 'v=spf1 -all'; Preference = $null } + ) + $script:dnsResults['A|mail.example'] = New-TestDnsResult -Name 'mail.example' -Type A -Answers @( + [pscustomobject]@{ Value = '192.0.2.10'; Preference = $null } + ) + + $result = Get-MtCisParkedDomainClassification -DomainName 'mail.example' + + $result.Classification | Should -Be 'NotSending' + $result.IsParked | Should -BeFalse + } + + It 'classifies a configured DKIM domain as sending' { + $config = [pscustomobject]@{ Domain = 'sender.example'; Enabled = $false } + + $result = Get-MtCisParkedDomainClassification -DomainName 'sender.example' -DkimSigningConfigs @($config) + + $result.Classification | Should -Be 'Sending' + } + + It 'classifies a domain with a published standard DKIM selector as sending' { + $script:dnsResults['TXT|sender.example'] = New-TestDnsResult -Name 'sender.example' -Type TXT -Answers @( + [pscustomobject]@{ Value = 'v=spf1 -all'; Preference = $null } + ) + $script:dnsResults['CNAME|selector1._domainkey.sender.example'] = New-TestDnsResult -Name 'selector1._domainkey.sender.example' -Type CNAME -Answers @( + [pscustomobject]@{ Value = 'selector1-sender._domainkey.example.onmicrosoft.com'; Preference = $null } + ) + + $result = Get-MtCisParkedDomainClassification -DomainName 'sender.example' + + $result.Classification | Should -Be 'Sending' + $result.DkimEvidence | Should -BeTrue + } + + It 'applies an explicit parked override while retaining conflicting DKIM evidence' { + $script:dnsResults['CNAME|selector1._domainkey.sender.example'] = New-TestDnsResult -Name 'selector1._domainkey.sender.example' -Type CNAME -Answers @( + [pscustomobject]@{ Value = 'selector1-sender._domainkey.example.onmicrosoft.com'; Preference = $null } + ) + + $result = Get-MtCisParkedDomainClassification -DomainName 'sender.example' -ParkedDomains 'SENDER.EXAMPLE.' + + $result.Classification | Should -Be 'Parked' + $result.IsOverride | Should -BeTrue + $result.DkimEvidence | Should -BeTrue + } + + It 'classifies a domain with SPF mechanisms as sending' { + $script:dnsResults['TXT|sender.example'] = New-TestDnsResult -Name 'sender.example' -Type TXT -Answers @( + [pscustomobject]@{ Value = 'v=spf1 include:spf.example.net -all'; Preference = $null } + ) + + $result = Get-MtCisParkedDomainClassification -DomainName 'sender.example' + + $result.Classification | Should -Be 'Sending' + } + + It 'treats an unqualified all mechanism as a sending signal' { + $script:dnsResults['TXT|sender.example'] = New-TestDnsResult -Name 'sender.example' -Type TXT -Answers @( + [pscustomobject]@{ Value = 'v=spf1 all'; Preference = $null } + ) + + $result = Get-MtCisParkedDomainClassification -DomainName 'sender.example' + + $result.Classification | Should -Be 'Sending' + } + + It 'leaves a domain unknown when SPF is missing' { + $result = Get-MtCisParkedDomainClassification -DomainName 'unknown.example' + + $result.Classification | Should -Be 'Unknown' + $result.IsParked | Should -BeFalse + } + + It 'leaves redirect-only SPF unknown until the redirect target is evaluated' { + $script:dnsResults['TXT|unknown.example'] = New-TestDnsResult -Name 'unknown.example' -Type TXT -Answers @( + [pscustomobject]@{ Value = 'v=spf1 redirect=_spf.example.net'; Preference = $null } + ) + + $result = Get-MtCisParkedDomainClassification -DomainName 'unknown.example' + + $result.Classification | Should -Be 'Unknown' + $result.SpfDeniesAll | Should -BeFalse + } + + It 'leaves a domain unknown when a DKIM DNS lookup fails' { + $script:dnsResults['TXT|unknown.example'] = New-TestDnsResult -Name 'unknown.example' -Type TXT -Answers @( + [pscustomobject]@{ Value = 'v=spf1 -all'; Preference = $null } + ) + $script:dnsResults['CNAME|selector1._domainkey.unknown.example'] = New-TestDnsResult -Name 'selector1._domainkey.unknown.example' -Type CNAME -Status Error + + $result = Get-MtCisParkedDomainClassification -DomainName 'unknown.example' + + $result.Classification | Should -Be 'Unknown' + } +} \ No newline at end of file diff --git a/powershell/tests/functions/Resolve-MtDnsRecord.Tests.ps1 b/powershell/tests/functions/Resolve-MtDnsRecord.Tests.ps1 new file mode 100644 index 0000000000..f4f32a3528 --- /dev/null +++ b/powershell/tests/functions/Resolve-MtDnsRecord.Tests.ps1 @@ -0,0 +1,170 @@ +Describe 'Resolve-MtDnsRecord with Resolve-DnsName' -Skip:(-not $IsWindows) { + BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force -WarningAction SilentlyContinue + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name Resolve-MtDnsRecord + } + + BeforeEach { + Mock Resolve-DnsName -ModuleName Maester {} + } + + It 'normalizes MX answers and their preference' { + Mock Resolve-DnsName -ModuleName Maester { + [pscustomobject]@{ + Section = 'Answer' + Type = 'MX' + NameExchange = 'mail.example.com' + Preference = 10 + } + } + + $result = Resolve-MtDnsRecord -Name 'example.com' -Type MX + + $result.Status | Should -Be 'Success' + $result.Answers.Count | Should -Be 1 + $result.Answers[0].Value | Should -Be 'mail.example.com' + $result.Answers[0].Preference | Should -Be 10 + } + + It 'joins TXT character strings into one record' { + Mock Resolve-DnsName -ModuleName Maester { + [pscustomobject]@{ + Section = 'Answer' + Type = 'TXT' + Strings = @('v=spf1 ', '-all') + } + } + + $result = Resolve-MtDnsRecord -Name 'example.com' -Type TXT + + $result.Answers[0].Value | Should -Be 'v=spf1 -all' + } + + It 'returns success with no answers when the record type is absent' { + $result = Resolve-MtDnsRecord -Name 'example.com' -Type MX + + $result.Status | Should -Be 'Success' + $result.Answers.Count | Should -Be 0 + } + + It 'distinguishes a missing DNS name from a resolver failure' { + Mock Resolve-DnsName -ModuleName Maester { + throw [System.Management.Automation.ErrorRecord]::new( + [System.Exception]::new('The DNS name does not exist.'), + 'DNS_ERROR_RCODE_NAME_ERROR', + [System.Management.Automation.ErrorCategory]::ObjectNotFound, + $null + ) + } + + $missing = Resolve-MtDnsRecord -Name 'missing.example' -Type MX + + Mock Resolve-DnsName -ModuleName Maester { + throw [System.Management.Automation.ErrorRecord]::new( + [System.Exception]::new('The DNS server is unavailable.'), + 'DNS_ERROR_RCODE_SERVER_FAILURE', + [System.Management.Automation.ErrorCategory]::ResourceUnavailable, + $null + ) + } + + $unavailable = Resolve-MtDnsRecord -Name 'example.com' -Type MX + + $missing.Status | Should -Be 'NXDomain' + $unavailable.Status | Should -Be 'Error' + } +} + +Describe 'Resolve-MtDnsRecord with Resolve-Dns' -Skip:$IsWindows { + BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force -WarningAction SilentlyContinue + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name Resolve-MtDnsRecord + + $script:createdDnsStub = & (Get-Module Maester) { + if (-not (Get-Command -Name 'Resolve-Dns' -ErrorAction SilentlyContinue)) { + Set-Item -Path 'Function:script:Resolve-Dns' -Value { + [CmdletBinding()] + param($Query, $QueryType, $NameServer) + throw 'The DNS resolver must be mocked in this test.' + } + $true + } else { + $false + } + } + } + + AfterAll { + if ($script:createdDnsStub) { + & (Get-Module Maester) { Remove-Item -Path 'Function:script:Resolve-Dns' } + } + } + + BeforeEach { + Mock Resolve-Dns -ModuleName Maester {} + } + + It 'normalizes MX answers and their preference' { + Mock Resolve-Dns -ModuleName Maester { + [pscustomobject]@{ + HasError = $false + Header = [pscustomobject]@{ ResponseCode = 'NoError' } + Answers = @([pscustomobject]@{ RecordType = 'MX'; Exchange = 'mail.example.com'; Preference = 10 }) + } + } + + $result = Resolve-MtDnsRecord -Name 'example.com' -Type MX + + $result.Status | Should -Be 'Success' + $result.Answers.Count | Should -Be 1 + $result.Answers[0].Value | Should -Be 'mail.example.com' + $result.Answers[0].Preference | Should -Be 10 + Should -Invoke -ModuleName Maester Resolve-Dns -Exactly 1 -ParameterFilter { + $Query -eq 'example.com' -and $QueryType -eq 'MX' + } + } + + It 'joins TXT character strings into one record' { + Mock Resolve-Dns -ModuleName Maester { + [pscustomobject]@{ + HasError = $false + Header = [pscustomobject]@{ ResponseCode = 'NoError' } + Answers = @([pscustomobject]@{ RecordType = 'TXT'; Text = @('v=spf1 ', '-all') }) + } + } + + $result = Resolve-MtDnsRecord -Name 'example.com' -Type TXT + + $result.Answers[0].Value | Should -Be 'v=spf1 -all' + } + + It 'distinguishes a missing DNS name from a resolver failure' { + Mock Resolve-Dns -ModuleName Maester { + [pscustomobject]@{ + HasError = $true + Header = [pscustomobject]@{ ResponseCode = 'NotExistentDomain' } + ErrorMessage = 'Non-Existent Domain' + Answers = @() + } + } + + $missing = Resolve-MtDnsRecord -Name 'missing.example' -Type MX + + Mock Resolve-Dns -ModuleName Maester { + [pscustomobject]@{ + HasError = $true + Header = [pscustomobject]@{ ResponseCode = 'ServerFailure' } + ErrorMessage = 'Server Failure' + Answers = @() + } + } + + $unavailable = Resolve-MtDnsRecord -Name 'example.com' -Type MX + + $missing.Status | Should -Be 'NXDomain' + $unavailable.Status | Should -Be 'Error' + $unavailable.Error | Should -Be 'Server Failure' + } +} \ No newline at end of file diff --git a/powershell/tests/functions/Test-MtCisDmarcRecordsPublished.Tests.ps1 b/powershell/tests/functions/Test-MtCisDmarcRecordsPublished.Tests.ps1 index 75200ec0e9..cffee9fbbf 100644 --- a/powershell/tests/functions/Test-MtCisDmarcRecordsPublished.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisDmarcRecordsPublished.Tests.ps1 @@ -4,20 +4,82 @@ . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" Use-MtModuleFunction -Name Test-MtCisDmarcRecordsPublished + $script:dmarcRecordText = 'v=DMARC1; p=reject' + $script:dnsResolverCommand = if ($IsWindows) { 'Resolve-DnsName' } else { 'Resolve-Dns' } + $script:createdDnsResolverStub = & (Get-Module Maester) { + param($CommandName) + if (-not (Get-Command -Name $CommandName -ErrorAction SilentlyContinue)) { + Set-Item -Path "Function:script:$CommandName" -Value { + [CmdletBinding()] + param($Name, $Type, $Query, $QueryType, $NameServer) + throw 'The DNS resolver must be mocked in this test.' + } + $true + } else { + $false + } + } $script:dnsResolverCommand + Mock -CommandName $script:dnsResolverCommand -ModuleName Maester { + if ($script:dnsResolverCommand -eq 'Resolve-DnsName') { + [pscustomobject]@{ Section = 'Answer'; Type = 'TXT'; Strings = @($script:dmarcRecordText) } + } else { + [pscustomobject]@{ + HasError = $false + Header = [pscustomobject]@{ ResponseCode = 'NoError' } + Answers = @([pscustomobject]@{ RecordType = 'TXT'; Text = @($script:dmarcRecordText) }) + } + } + } + $script:parkedDmarcRecord = ConvertFrom-MailAuthenticationRecordDmarc -DomainName 'parked.example' + $script:dmarcRecordText = 'v=DMARC1; p=quarantine' + $script:quarantineDmarcRecord = ConvertFrom-MailAuthenticationRecordDmarc -DomainName 'quarantine.example' + $script:dmarcRecordText = 'v=DMARC1; p=reject; pct=100; rua=mailto:reports@example.com; ruf=mailto:forensic@example.com' + $script:fullyCompliantDmarcRecord = ConvertFrom-MailAuthenticationRecordDmarc -DomainName 'sending.example' + $script:domains = @() $script:registrableDomains = @{} $script:dmarcResults = @{} + $script:classifications = @{} + $script:dkimSigningConfigs = @() - Mock Get-MtExo -ModuleName Maester { $script:domains } + Mock Get-MtExo -ModuleName Maester { + if ($Request -eq 'AcceptedDomain') { return $script:domains } + return $script:dkimSigningConfigs + } Mock Get-MtRegistrableDomain -ModuleName Maester { $script:registrableDomains[$DomainName] } Mock ConvertFrom-MailAuthenticationRecordDmarc -ModuleName Maester { $script:dmarcResults[$DomainName] } - Mock Add-MtTestResultDetail -ModuleName Maester {} + Mock Get-MtCisParkedDomainClassification -ModuleName Maester { + $classification = if ($script:classifications.ContainsKey($DomainName)) { + $script:classifications[$DomainName] + } else { + [pscustomobject]@{ Classification = 'Sending'; Reason = 'Sending-domain test default.' } + } + if ($ParkedDomains -contains $DomainName) { + $classification.Classification = 'Parked' + } + return $classification + } + Mock Add-MtTestResultDetail -ModuleName Maester { + $script:resultDetail = [pscustomobject]@{ Result = $Result; Investigate = [bool]$Investigate; SkippedBecause = $SkippedBecause } + } + } + + AfterAll { + if ($script:createdDnsResolverStub) { + & (Get-Module Maester) { + param($CommandName) + Remove-Item -Path "Function:script:$CommandName" + } $script:dnsResolverCommand + } } BeforeEach { $script:domains = @() $script:registrableDomains = @{} $script:dmarcResults = @{} + $script:classifications = @{} + $script:dkimSigningConfigs = @() + $script:resultDetail = $null } It 'fails a known noncompliant domain before skipping an unavailable lookup' { @@ -59,4 +121,52 @@ $Result -match 'Invalid DMARC record' -and $Result -match 'mail.example.com' } } + + It 'requires p=reject but not reporting tags for parked domains' { + $script:domains = @([pscustomobject]@{ DomainName = 'parked.example'; IsCoExistenceDomain = $false }) + $script:registrableDomains = @{ 'parked.example' = 'parked.example' } + $script:dmarcResults = @{ 'parked.example' = $script:parkedDmarcRecord } + $script:classifications = @{ 'parked.example' = [pscustomobject]@{ Classification = 'Parked'; Reason = 'No mail-use signals were found.' } } + + Test-MtCisDmarcRecordsPublished | Should -BeTrue + $script:resultDetail.Investigate | Should -BeFalse + } + + It 'fails a parked domain whose DMARC policy is quarantine' { + $script:domains = @([pscustomobject]@{ DomainName = 'parked.example'; IsCoExistenceDomain = $false }) + $script:registrableDomains = @{ 'parked.example' = 'parked.example' } + $script:dmarcResults = @{ 'parked.example' = $script:quarantineDmarcRecord } + $script:classifications = @{ 'parked.example' = [pscustomobject]@{ Classification = 'Parked'; Reason = 'No mail-use signals were found.' } } + + Test-MtCisDmarcRecordsPublished | Should -BeFalse + } + + It 'investigates an unknown domain when only the parked-domain policy passes' { + $script:domains = @([pscustomobject]@{ DomainName = 'unknown.example'; IsCoExistenceDomain = $false }) + $script:registrableDomains = @{ 'unknown.example' = 'unknown.example' } + $script:dmarcResults = @{ 'unknown.example' = $script:parkedDmarcRecord } + $script:classifications = @{ 'unknown.example' = [pscustomobject]@{ Classification = 'Unknown'; Reason = 'DNS evidence is incomplete.' } } + + Test-MtCisDmarcRecordsPublished | Should -BeTrue + $script:resultDetail.Investigate | Should -BeTrue + } + + It 'applies an explicit parked override and requires reject policy' { + $script:domains = @([pscustomobject]@{ DomainName = 'unknown.example'; IsCoExistenceDomain = $false }) + $script:registrableDomains = @{ 'unknown.example' = 'unknown.example' } + $script:dmarcResults = @{ 'unknown.example' = $script:quarantineDmarcRecord } + $script:classifications = @{ 'unknown.example' = [pscustomobject]@{ Classification = 'Unknown'; Reason = 'DNS evidence is incomplete.' } } + + Test-MtCisDmarcRecordsPublished -ParkedDomains 'unknown.example' | Should -BeFalse + } + + It 'accepts a fully compliant DMARC record when both procedures pass' { + $script:domains = @([pscustomobject]@{ DomainName = 'unknown.example'; IsCoExistenceDomain = $false }) + $script:registrableDomains = @{ 'unknown.example' = 'unknown.example' } + $script:dmarcResults = @{ 'unknown.example' = $script:fullyCompliantDmarcRecord } + $script:classifications = @{ 'unknown.example' = [pscustomobject]@{ Classification = 'Unknown'; Reason = 'DNS evidence is incomplete.' } } + + Test-MtCisDmarcRecordsPublished | Should -BeTrue + $script:resultDetail.Investigate | Should -BeFalse + } } diff --git a/powershell/tests/functions/Test-MtCisSpfRecordsPublished.Tests.ps1 b/powershell/tests/functions/Test-MtCisSpfRecordsPublished.Tests.ps1 new file mode 100644 index 0000000000..fbaf964ec3 --- /dev/null +++ b/powershell/tests/functions/Test-MtCisSpfRecordsPublished.Tests.ps1 @@ -0,0 +1,107 @@ +Describe 'CIS M365 SPF check' { + BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force -WarningAction SilentlyContinue + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name Test-MtCisSpfRecordsPublished + + Mock Get-MtExo -ModuleName Maester { + if ($Request -eq 'AcceptedDomain') { return $script:domains } + return $script:dkimSigningConfigs + } + Mock ConvertFrom-MailAuthenticationRecordSpf -ModuleName Maester { $script:spfResults[$DomainName] } + Mock Get-MtCisParkedDomainClassification -ModuleName Maester { + $classification = $script:classifications[$DomainName] + if ($ParkedDomains -contains $DomainName) { + $classification.Classification = 'Parked' + } + return $classification + } + Mock Add-MtTestResultDetail -ModuleName Maester { + $script:resultDetail = [pscustomobject]@{ + Result = $Result + Investigate = [bool]$Investigate + SkippedBecause = $SkippedBecause + } + } + } + + BeforeEach { + $script:domains = @([pscustomobject]@{ DomainName = 'example.com'; InitialDomain = $false; IsCoExistenceDomain = $false }) + $script:dkimSigningConfigs = @() + $script:spfResults = @{} + $script:classifications = @{} + $script:resultDetail = $null + } + + It 'requires a hard-fail SPF record for a parked domain' { + $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 ~all' } + $script:classifications['example.com'] = [pscustomobject]@{ + Classification = 'Parked' + SpfDeniesAll = $false + Reason = 'No sending or receiving signals were found.' + } + + Test-MtCisSpfRecordsPublished | Should -BeFalse + $script:resultDetail.Result | Should -Match 'parked/non-sending audit requires an SPF record' + } + + It 'accepts a hard-fail SPF record for a parked domain' { + $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 -all' } + $script:classifications['example.com'] = [pscustomobject]@{ + Classification = 'Parked' + SpfDeniesAll = $true + Reason = 'No sending or receiving signals were found.' + } + + Test-MtCisSpfRecordsPublished | Should -BeTrue + $script:resultDetail.Investigate | Should -BeFalse + } + + It 'keeps the soft-fail rule for sending domains' { + $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 include:spf.example.net ~all' } + $script:classifications['example.com'] = [pscustomobject]@{ + Classification = 'Sending' + SpfDeniesAll = $false + Reason = 'An SPF sending mechanism was found.' + } + + Test-MtCisSpfRecordsPublished | Should -BeTrue + $script:resultDetail.Investigate | Should -BeFalse + } + + It 'investigates when a soft-fail record passes only the sending-domain rule' { + $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 ~all' } + $script:classifications['example.com'] = [pscustomobject]@{ + Classification = 'Unknown' + SpfDeniesAll = $false + Reason = 'Mail use is inconclusive.' + } + + Test-MtCisSpfRecordsPublished | Should -BeTrue + $script:resultDetail.Investigate | Should -BeTrue + } + + It 'investigates an indirect all policy when parked status is unknown' { + $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 redirect=_spf.example.net' } + $script:spfResults['_spf.example.net'] = [pscustomobject]@{ record = 'v=spf1 -all' } + $script:classifications['example.com'] = [pscustomobject]@{ + Classification = 'Unknown' + SpfDeniesAll = $false + Reason = 'The SPF redirect target is inconclusive.' + } + + Test-MtCisSpfRecordsPublished | Should -BeTrue + $script:resultDetail.Investigate | Should -BeTrue + } + + It 'applies a parked override but still requires hard fail' { + $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 ~all' } + $script:classifications['example.com'] = [pscustomobject]@{ + Classification = 'Unknown' + SpfDeniesAll = $false + Reason = 'Mail use is inconclusive.' + } + + Test-MtCisSpfRecordsPublished -ParkedDomains 'example.com' | Should -BeFalse + } +} \ No newline at end of file diff --git a/powershell/tests/functions/Test-MtDkim.Tests.ps1 b/powershell/tests/functions/Test-MtDkim.Tests.ps1 index af59d2de3f..4b7d8c76e9 100644 --- a/powershell/tests/functions/Test-MtDkim.Tests.ps1 +++ b/powershell/tests/functions/Test-MtDkim.Tests.ps1 @@ -12,6 +12,18 @@ Describe 'DKIM checks with no signing configuration' -ForEach @( BeforeEach { Mock -ModuleName Maester Test-MtConnection { return $true } Mock -ModuleName Maester Add-MtTestResultDetail { } + Mock -ModuleName Maester Get-MtCisParkedDomainClassification { + $classification = if ($DomainName -eq 'parked.example') { 'Parked' } else { 'Sending' } + [PSCustomObject]@{ + DomainName = $DomainName + Classification = $classification + IsParked = $classification -eq 'Parked' + SpfRecord = $null + SpfDeniesAll = $false + DkimEvidence = $false + Reason = 'Mock domain classification' + } + } Mock -ModuleName Maester Get-MailAuthenticationRecord { throw 'DNS lookup should not be attempted without a DKIM signing configuration' } @@ -45,8 +57,8 @@ Describe 'DKIM checks with no signing configuration' -ForEach @( InitialDomain = $false IsCoexistenceDomain = $false SendingFromDomainDisabled = $true - ExpectedResultByCommand = @{ - 'Test-MtCisDkim' = $null + ExpectedResultByCommand = @{ + 'Test-MtCisDkim' = $true 'Test-MtCisaDkim' = $null } } @@ -107,6 +119,48 @@ Describe 'DKIM checks with no signing configuration' -ForEach @( } } +Describe 'CIS DKIM domain classification outcomes' { + BeforeEach { + Mock -ModuleName Maester Add-MtTestResultDetail { + $script:detail = [PSCustomObject]@{ Result = $Result; Investigate = [bool]$Investigate; SkippedBecause = $SkippedBecause } + } + Mock -ModuleName Maester Get-MtExo { + if ($Request -eq 'AcceptedDomain') { + return @([PSCustomObject]@{ DomainName = 'unknown.example'; InitialDomain = $false; IsCoexistenceDomain = $false }) + } + return @() + } + Mock -ModuleName Maester Get-MailAuthenticationRecord { throw 'No DKIM lookup should be needed for this classification.' } + } + + It 'investigates domains whose sending use cannot be established' { + Mock -ModuleName Maester Get-MtCisParkedDomainClassification { + [PSCustomObject]@{ Classification = 'Unknown'; IsParked = $false; Reason = 'DNS evidence is incomplete.' } + } + + Test-MtCisDkim | Should -BeTrue + $script:detail.Investigate | Should -BeTrue + } + + It 'fails a parked override when DKIM evidence remains' { + Mock -ModuleName Maester Get-MtCisParkedDomainClassification { + $classification = if ($ParkedDomains -contains $DomainName) { 'Parked' } else { 'Sending' } + [PSCustomObject]@{ Classification = $classification; DkimEvidence = $true; Reason = 'Explicit parked override.' } + } + + Test-MtCisDkim -ParkedDomains 'unknown.example' | Should -BeFalse + } + + It 'marks a non-sending receive domain out of scope for DKIM' { + Mock -ModuleName Maester Get-MtCisParkedDomainClassification { + [PSCustomObject]@{ Classification = 'NotSending'; IsParked = $false; Reason = 'The domain has receive-only DNS records.' } + } + + Test-MtCisDkim | Should -BeNullOrEmpty + $script:detail.SkippedBecause | Should -Be 'NotApplicable' + } +} + Describe 'DKIM checks for coexistence domains with a signing configuration' -ForEach @( @{ CommandName = 'Test-MtCisDkim' } @{ CommandName = 'Test-MtCisaDkim' } diff --git a/tests/cis/Test.CIS.M365.2.1.10.md b/tests/cis/Test.CIS.M365.2.1.10.md index fdc8ee3cd1..cb9b5c8c01 100644 --- a/tests/cis/Test.CIS.M365.2.1.10.md +++ b/tests/cis/Test.CIS.M365.2.1.10.md @@ -1,13 +1,19 @@ -Every accepted domain, including the initial onmicrosoft.com domain, has a DMARC policy of quarantine or reject that covers all mail and names addresses for aggregate and forensic reports. +Every accepted domain, including the initial onmicrosoft.com domain, must meet the applicable DMARC audit. Sending domains require a quarantine or reject policy that covers all mail and names addresses for aggregate and forensic reports. Parked or otherwise non-sending domains require a valid DMARC record with `p=reject`. DMARC tells receiving servers what to do with mail that fails SPF and DKIM alignment, and sends you reports about who is sending mail in your name. With a policy of none, spoofed mail is still delivered. Quarantine or reject stops it, and the reports show abuse and legitimate senders that you forgot. -The test uses the record at the domain, or at its organisational domain (for example contoso.com for mail.contoso.com) when the domain has no valid record, including a malformed record, applying the subdomain policy where one exists. The policy must apply to 100 percent of mail (no pct tag, or pct=100). Both rua and ruf addresses must be mailto addresses. Move to enforcement in steps and review the aggregate reports first. +The test uses the record at the domain, or at its organisational domain (for example contoso.com for mail.contoso.com) when the domain has no valid record, including a malformed record, applying the subdomain policy where one exists. For sending domains, the policy must apply to 100 percent of mail (no pct tag, or pct=100), and both rua and ruf addresses must be mailto addresses. + +Maester identifies a likely non-sending domain when it finds one SPF v1 record with only a non-authorizing `-all`, `~all`, or `?all` mechanism, no Exchange DKIM signing configuration, and no selector1 or selector2 DKIM CNAME/TXT record. It classifies the domain as parked only when those signals are also accompanied by no usable MX route (or a null MX) and no A, AAAA, or CNAME record at the domain apex. This conservative DNS assessment does not use `AcceptedDomain.SendingFromDomainDisabled`. + +Parked or non-sending domains use the CIS parked-domain requirement: a valid DMARC record with `p=reject`; rua, ruf, and pct are not required for this branch. Missing SPF, conflicting signals, DNS errors, and unresolved redirect-only SPF policies do not receive the parked exception. When only one of the sending and non-sending audit procedures passes, the result requires investigation. Selector discovery is limited to the standard Exchange Online selectors, so nonstandard DKIM selector names cannot be ruled out automatically. + +When DNS evidence is inconclusive but a domain is known to be parked, add its name to this test's `ParkedDomains` parameter in `TestSettings[].Parameters`. This selects the parked audit branch; it does not waive the requirement for a valid DMARC record with `p=reject`. #### Remediation action 1. Open the DNS zone of each custom domain at your DNS host. For the initial `*.onmicrosoft.com` domain, use the Microsoft 365 admin center instead: go to **Settings** > **Domains**, select the `*.onmicrosoft.com` domain, open the **DNS records** tab and select **Add record**. -2. Create or edit the TXT record `_dmarc.` (in the admin center, the host name is `_dmarc`) with a value such as `v=DMARC1; p=reject; pct=100; rua=mailto:dmarc-reports@; ruf=mailto:dmarc-forensic@`. +2. Create or edit the TXT record `_dmarc.` (in the admin center, the host name is `_dmarc`). For a sending domain, use a value such as `v=DMARC1; p=reject; pct=100; rua=mailto:dmarc-reports@; ruf=mailto:dmarc-forensic@`. For a parked or non-sending domain, `v=DMARC1; p=reject` meets the parked-domain requirement. 3. Start with `p=none` or `p=quarantine` if you are not sure that all your senders are aligned, review the reports and then move to `p=reject`. 4. Check the record with `Resolve-DnsName -Name _dmarc. -Type TXT`. diff --git a/tests/cis/Test.CIS.M365.2.1.10.ps1 b/tests/cis/Test.CIS.M365.2.1.10.ps1 index 73944087cd..4eadd65900 100644 --- a/tests/cis/Test.CIS.M365.2.1.10.ps1 +++ b/tests/cis/Test.CIS.M365.2.1.10.ps1 @@ -1,16 +1,16 @@ function Test-MtCisDmarcRecordsPublished { <# .SYNOPSIS - Checks that every accepted domain has a DMARC policy of quarantine or reject with aggregate and forensic reporting. + Checks the applicable CIS DMARC requirement for each accepted domain. .DESCRIPTION - Looks up the DMARC record that applies to each accepted domain, falling back to the organisational domain when the domain has no valid record, including a malformed record. Passes when the applied policy is quarantine or reject, covers 100 percent of mail and defines mailto addresses for aggregate (rua) and forensic (ruf) reports. + Looks up the DMARC record that applies to each accepted domain, falling back to the organisational domain when the domain has no valid record, including a malformed record. Sending domains require quarantine or reject, 100 percent coverage, and mailto aggregate (rua) and forensic (ruf) report addresses. Parked or otherwise non-sending domains require a valid record with p=reject. Ambiguous domain-use evidence is reported for investigation when the two procedures produce different results. CIS Microsoft 365 Foundations Benchmark v7.0.0 (2.1.10, L1) .EXAMPLE Test-MtCisDmarcRecordsPublished - Returns true if all accepted domains have an enforcing DMARC policy with reporting addresses. + Returns true if all accepted domains meet the applicable CIS DMARC requirement. .LINK https://maester.dev/docs/tests/CIS.M365.2.1.10 @@ -32,13 +32,18 @@ )] [CmdletBinding()] [OutputType([bool])] - param() + param( + # Domains explicitly confirmed as parked; the parked DMARC audit still applies. + [string[]]$ParkedDomains = @() + ) Write-Verbose 'Getting accepted domains...' $domains = @(Get-MtExo -Request AcceptedDomain | Where-Object { $_.IsCoExistenceDomain -eq $false }) + $dkimSigningConfigs = @(Get-MtExo -Request DkimSigningConfig) $report = foreach ($domain in $domains) { $name = $domain.DomainName + $classification = Get-MtCisParkedDomainClassification -DomainName $name -DkimSigningConfigs $dkimSigningConfigs -ParkedDomains $ParkedDomains $dmarc = $null $source = $null $unavailable = $false @@ -59,45 +64,81 @@ } } if ($unavailable) { - [pscustomobject]@{ Domain = $name; Policy = 'Not checked'; Source = 'None'; Failed = 'DNS lookup not available'; Pass = $null } + [pscustomobject]@{ Domain = $name; Classification = $classification.Classification; Policy = 'Not checked'; Source = 'None'; Failed = 'DNS lookup not available'; Pass = $null; Investigate = $false } continue } $policy = $null if ($dmarc) { $policy = if ($source -ne $name -and $dmarc.policySubdomain) { $dmarc.policySubdomain } else { $dmarc.policy } } - $checks = [ordered]@{ + $sendingChecks = [ordered]@{ 'Record is valid' = $null -ne $dmarc -and $dmarc.valid 'Policy is quarantine or reject' = $policy -in @('quarantine', 'reject') 'Applies to 100 percent' = $null -eq $dmarc -or $dmarc.percentage -eq 100 -or $null -eq $dmarc.percentage 'Aggregate reports (rua)' = @($dmarc.reportAggregate | Where-Object { $_.mailAddress }).Count -gt 0 'Forensic reports (ruf)' = @($dmarc.reportForensic | Where-Object { $_.mailAddress }).Count -gt 0 } - $failedChecks = @($checks.GetEnumerator() | Where-Object { -not $_.Value } | ForEach-Object { $_.Key }) + $nonSendingChecks = [ordered]@{ + 'Record is valid' = $null -ne $dmarc -and $dmarc.valid + 'Parked-domain policy is reject' = $policy -eq 'reject' + } + $sendingFailures = @($sendingChecks.GetEnumerator() | Where-Object { -not $_.Value } | ForEach-Object { $_.Key }) + $nonSendingFailures = @($nonSendingChecks.GetEnumerator() | Where-Object { -not $_.Value } | ForEach-Object { $_.Key }) + $failedChecks = @() + $investigate = $false + if ($classification.Classification -in @('Parked', 'NotSending')) { + $failedChecks = $nonSendingFailures + $pass = $failedChecks.Count -eq 0 + } elseif ($classification.Classification -eq 'Unknown') { + if ($sendingFailures.Count -eq 0 -and $nonSendingFailures.Count -eq 0) { + $pass = $true + } elseif ($sendingFailures.Count -eq 0 -or $nonSendingFailures.Count -eq 0) { + $pass = $true + $investigate = $true + $failedChecks = if ($sendingFailures.Count -eq 0) { + @("If parked or non-sending: $($nonSendingFailures -join ', ')") + } else { + @("If sending: $($sendingFailures -join ', ')") + } + } else { + $pass = $false + $failedChecks = @( + @($sendingFailures | ForEach-Object { "If sending: $_" }) + + @($nonSendingFailures | ForEach-Object { "If parked or non-sending: $_" }) + ) + } + } else { + $failedChecks = $sendingFailures + $pass = $failedChecks.Count -eq 0 + } [pscustomobject]@{ - Domain = $name - Policy = if ($policy) { $policy } elseif ($invalidCandidate) { 'Invalid DMARC record' } else { 'No valid record' } - Source = if ($source) { $source } elseif ($invalidCandidate) { $invalidCandidate } else { 'None' } - Failed = $failedChecks -join ', ' - Pass = $failedChecks.Count -eq 0 + Domain = $name + Classification = $classification.Classification + Policy = if ($policy) { $policy } elseif ($invalidCandidate) { 'Invalid DMARC record' } else { 'No valid record' } + Source = if ($source) { $source } elseif ($invalidCandidate) { $invalidCandidate } else { 'None' } + Failed = $failedChecks -join ', ' + Pass = $pass + Investigate = $investigate } } $checked = @($report | Where-Object { $null -ne $_.Pass }) - $unchecked = @($report | Where-Object { $null -eq $_.Pass }) + $unchecked = @($report | Where-Object { $null -eq $_.Pass -and -not $_.Investigate }) $failed = @($checked | Where-Object { -not $_.Pass }) + $investigated = @($report | Where-Object { $_.Investigate }) if ($failed.Count -eq 0 -and $unchecked.Count -gt 0) { Add-MtTestResultDetail -SkippedBecause NotSupported return $null } $testResult = $failed.Count -eq 0 - $passText = 'All accepted domains have an enforcing DMARC policy with reporting addresses.' + $passText = 'All accepted domains meet the applicable CIS DMARC requirement.' $failText = "$($failed.Count) domain(s) do not have a compliant DMARC policy." - $resultMd = "| Domain | Applied policy | Record found at | Failed checks | Result |`n" - $resultMd += "| --- | --- | --- | --- | --- |`n" + $resultMd = "| Domain | Classification | Applied policy | Record found at | Failed checks | Result |`n" + $resultMd += "| --- | --- | --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Domain) | $($row.Policy) | $($row.Source) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($null -eq $row.Pass) { 'Not checked' } elseif ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultText = if ($null -eq $row.Pass -and $row.Investigate) { 'Investigate' } elseif ($null -eq $row.Pass) { 'Not checked' } elseif ($row.Pass) { '✅ Pass' } else { '❌ Fail' } + $resultMd += "| $($row.Domain) | $($row.Classification) | $($row.Policy) | $($row.Source) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $resultText |`n" } if ($testResult) { @@ -107,6 +148,6 @@ } $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $resultMd - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate:($investigated.Count -gt 0 -and $failed.Count -eq 0) return $testResult } diff --git a/tests/cis/Test.CIS.M365.2.1.8.md b/tests/cis/Test.CIS.M365.2.1.8.md index 75444fa9fd..938c762be1 100644 --- a/tests/cis/Test.CIS.M365.2.1.8.md +++ b/tests/cis/Test.CIS.M365.2.1.8.md @@ -1,13 +1,19 @@ -Every custom domain that is accepted by Exchange Online publishes an SPF record that ends in a hard fail (-all) or soft fail (~all). +Sending domains must publish an SPF record that ends in a hard fail (-all) or soft fail (~all). Parked or otherwise non-sending domains must publish an SPF policy that denies all senders with -all. SPF lists the servers that may send mail for a domain. Receiving servers use it to reject, or to mark as suspicious, mail that pretends to come from your domain. Without an SPF record, or with one that ends in a neutral or permissive qualifier, anyone can send mail that looks like it comes from you without raising a flag. -The test follows a redirect modifier only when the record has no all mechanism, since receivers ignore the redirect in that case. Domains in the onmicrosoft.com namespace are skipped. Parked domains that never send mail should publish a record of "v=spf1 -all". +Maester identifies a likely non-sending domain when it finds one SPF v1 record with no sender-authorizing mechanism, no Exchange DKIM signing configuration, and no selector1 or selector2 DKIM CNAME/TXT record. It classifies the domain as parked only when those signals are also accompanied by no usable MX route (or a null MX) and no A, AAAA, or CNAME record at the domain apex. This conservative DNS assessment does not use `AcceptedDomain.SendingFromDomainDisabled`. + +For a parked or non-sending domain, the SPF record must explicitly use `-all`; a `~all` policy does not meet the parked-domain audit. For sending domains, the test follows a redirect modifier only when the record has no all mechanism, since receivers ignore the redirect in that case. Domains in the onmicrosoft.com namespace are skipped. + +Missing SPF, conflicting signals, DNS errors, and unresolved redirect-only policies do not receive the parked exception. When the record passes the sending-domain rule but could fail the parked-domain rule, the result requires investigation. Selector discovery is limited to the standard Exchange Online selectors, so nonstandard DKIM selector names cannot be ruled out automatically. + +When DNS evidence is inconclusive but a domain is known to be parked, add its name to this test's `ParkedDomains` parameter in `TestSettings[].Parameters`. This selects the parked audit branch; it does not waive the requirement to publish `v=spf1 -all`. #### Remediation action 1. Open the DNS zone of each custom domain at your DNS host. -2. Create or edit the TXT record at the domain root so that it lists your sending services and ends with `-all` (or `~all`). For Exchange Online only, use `v=spf1 include:spf.protection.outlook.com -all`. +2. Create or edit the TXT record at the domain root. For a sending domain, list its sending services and end with `-all` or `~all`; for a parked or non-sending domain, publish `v=spf1 -all`. For Exchange Online only, use `v=spf1 include:spf.protection.outlook.com -all`. 3. Wait for the change to propagate and check the record with `Resolve-DnsName -Name -Type TXT`. #### Related links diff --git a/tests/cis/Test.CIS.M365.2.1.8.ps1 b/tests/cis/Test.CIS.M365.2.1.8.ps1 index 4909a0d6f2..3980d6d9b1 100644 --- a/tests/cis/Test.CIS.M365.2.1.8.ps1 +++ b/tests/cis/Test.CIS.M365.2.1.8.ps1 @@ -1,16 +1,16 @@ function Test-MtCisSpfRecordsPublished { <# .SYNOPSIS - Checks that every custom accepted domain publishes an SPF record that ends in -all or ~all. + Checks the applicable CIS SPF requirement for each custom accepted domain. .DESCRIPTION - Looks up the SPF record of each custom accepted domain and passes when a record exists and ends with a hard fail or soft fail, either directly or through a redirect. Domains in the onmicrosoft.com namespace are excluded because Microsoft manages their SPF. + Sending domains must publish an SPF record that ends with -all or ~all, directly or through a redirect. Parked or otherwise non-sending domains must publish an SPF policy that denies all senders with -all. Domains in the onmicrosoft.com namespace are excluded because Microsoft manages their SPF. Ambiguous domain-use evidence is reported for investigation rather than receiving the parked-domain exception. CIS Microsoft 365 Foundations Benchmark v7.0.0 (2.1.8, L1) .EXAMPLE Test-MtCisSpfRecordsPublished - Returns true if all custom domains publish an SPF record that ends in -all or ~all. + Returns true if all custom domains meet the applicable CIS SPF requirement. .LINK https://maester.dev/docs/tests/CIS.M365.2.1.8 @@ -32,20 +32,25 @@ )] [CmdletBinding()] [OutputType([bool])] - param() + param( + # Domains explicitly confirmed as parked; the parked SPF audit still applies. + [string[]]$ParkedDomains = @() + ) Write-Verbose 'Getting accepted domains...' $domains = @(Get-MtExo -Request AcceptedDomain | Where-Object { $_.InitialDomain -eq $false -and $_.IsCoExistenceDomain -eq $false }) + $dkimSigningConfigs = @(Get-MtExo -Request DkimSigningConfig) $report = foreach ($domain in $domains) { $name = $domain.DomainName + $classification = Get-MtCisParkedDomainClassification -DomainName $name -DkimSigningConfigs $dkimSigningConfigs -ParkedDomains $ParkedDomains $detail = '' $spf = ConvertFrom-MailAuthenticationRecordSpf -DomainName $name if ($spf -is [string] -and ($spf -like '*not available' -or $spf -eq 'DNS lookup unavailable')) { - [pscustomobject]@{ Domain = $name; Record = $null; Pass = $null; Detail = 'DNS lookup not available' } + [pscustomobject]@{ Domain = $name; Record = $null; Classification = $classification.Classification; Pass = $null; Investigate = $false; Detail = 'DNS lookup not available' } continue } - $record = if ($spf.GetType().Name -eq 'SPFRecord') { $spf.record } else { $null } + $record = if ($spf -and $spf.PSObject.Properties['record']) { $spf.record } else { $null } $effective = $record $redirectTargets = @() $redirectError = $null @@ -77,8 +82,7 @@ $redirectUnavailable = $true break } - $redirectedType = if ($null -ne $redirected) { $redirected.GetType().Name } else { $null } - $effective = if ($redirectedType -eq 'SPFRecord') { $redirected.record } else { $null } + $effective = if ($null -ne $redirected -and $redirected.PSObject.Properties['record']) { $redirected.record } else { $null } if (-not $effective) { $redirectError = "No SPF record was found at redirect target $target." break @@ -86,11 +90,13 @@ } if ($redirectUnavailable) { - [pscustomobject]@{ Domain = $name; Record = $record; Pass = $null; Detail = "DNS lookup not available for $($redirectTargets[-1])" } + [pscustomobject]@{ Domain = $name; Record = $record; Classification = $classification.Classification; Pass = $null; Investigate = $false; Detail = "DNS lookup not available for $($redirectTargets[-1])" } continue } $effectiveAll = [regex]::Match([string]$effective, '(?i)(^|\s)(?[+?~-]?)all(\s|$)') - $pass = $effectiveAll.Success -and $effectiveAll.Groups['q'].Value -in '-', '~' + $sendingDomainPass = $effectiveAll.Success -and $effectiveAll.Groups['q'].Value -in '-', '~' + $pass = $sendingDomainPass + $investigate = $false if (-not $record) { $detail = 'No SPF record found' } elseif ($redirectError) { @@ -103,27 +109,49 @@ elseif (-not $pass) { $detail = 'The record does not end with -all or ~all' } - [pscustomobject]@{ Domain = $name; Record = $record; Pass = $pass; Detail = $detail } + + if ($classification.Classification -in @('Parked', 'NotSending')) { + $pass = $classification.SpfDeniesAll + $detail = if ($pass) { + 'The parked/non-sending audit requires an SPF record that explicitly denies all senders; this record uses -all.' + } else { + 'The parked/non-sending audit requires an SPF record that explicitly denies all senders with -all.' + } + } elseif ($classification.Classification -eq 'Unknown' -and $sendingDomainPass -and -not $classification.SpfDeniesAll) { + $pass = $null + $investigate = $true + $detail = 'The sending-domain SPF audit passes, but the available evidence cannot rule out the parked-domain requirement for -all.' + } elseif ($classification.Classification -eq 'Unknown' -and $sendingDomainPass) { + $pass = $true + $detail = 'The record meets both the sending-domain and parked-domain SPF requirements.' + } + + $detail = "$($classification.Reason) $detail" + [pscustomobject]@{ Domain = $name; Record = $record; Classification = $classification.Classification; Pass = $pass; Investigate = $investigate; Detail = $detail } } - $unchecked = @($report | Where-Object { $null -eq $_.Pass }) + $unchecked = @($report | Where-Object { $null -eq $_.Pass -and -not $_.Investigate }) $failed = @($report | Where-Object { $_.Pass -eq $false }) + $investigated = @($report | Where-Object { $_.Investigate }) if ($failed.Count -gt 0) { $testResult = $false } elseif ($unchecked.Count -gt 0) { Add-MtTestResultDetail -SkippedBecause NotSupported return $null + } elseif ($investigated.Count -gt 0) { + $testResult = $true } else { $testResult = $true } - $passText = if ($domains.Count -eq 0) { 'There are no custom domains, so no SPF records are required.' } else { 'All custom domains publish an SPF record that ends in -all or ~all.' } - $failText = "$($failed.Count) custom domain(s) do not publish a compliant SPF record." + $passText = if ($domains.Count -eq 0) { 'There are no custom domains, so no SPF records are required.' } else { 'All custom domains meet the applicable CIS SPF requirement.' } + $failText = "$($failed.Count) custom domain(s) do not meet the applicable CIS SPF requirement." - $resultMd = "| Domain | SPF record | Detail | Result |`n" - $resultMd += "| --- | --- | --- | --- |`n" + $resultMd = "| Domain | Classification | SPF record | Detail | Result |`n" + $resultMd += "| --- | --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Domain) | $($row.Record) | $($row.Detail) | $(if ($null -eq $row.Pass) { 'Not checked' } elseif ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $resultText = if ($null -eq $row.Pass -and $row.Investigate) { 'Investigate' } elseif ($null -eq $row.Pass) { 'Not checked' } elseif ($row.Pass) { '✅ Pass' } else { '❌ Fail' } + $resultMd += "| $($row.Domain) | $($row.Classification) | $($row.Record) | $($row.Detail) | $resultText |`n" } if ($testResult) { @@ -134,6 +162,6 @@ } $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $resultMd - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate:($investigated.Count -gt 0 -and $failed.Count -eq 0) return $testResult } diff --git a/tests/cis/Test.CIS.M365.2.1.9.md b/tests/cis/Test.CIS.M365.2.1.9.md index e7434e811a..d91c1ee688 100644 --- a/tests/cis/Test.CIS.M365.2.1.9.md +++ b/tests/cis/Test.CIS.M365.2.1.9.md @@ -12,7 +12,13 @@ There should be no impact of setting up DKIM however, organizations should ensur >Note: Initial (MOERA, e.g. `contoso.onmicrosoft.com`) and coexistence (`*.mail.onmicrosoft.com`) domains are excluded from this check, as Microsoft automatically signs outbound mail for those domains. -For each sending domain, the check requires Exchange DKIM to be enabled and its status to be **Valid**. +For domains classified as sending, the check requires Exchange DKIM to be enabled and its status to be **Valid**. A likely sending domain has an SPF sender-authorizing mechanism, an Exchange DKIM signing configuration, or a selector1/selector2 DKIM CNAME/TXT record. + +Maester classifies a domain as not sending when its single SPF v1 record has only a non-authorizing `-all`, `~all`, or `?all` mechanism and no Exchange DKIM signing configuration or selector1/selector2 records are found. It is classified as parked only when it also has no usable MX route (or a null MX) and no A, AAAA, or CNAME record at the domain apex. This classification does not use `AcceptedDomain.SendingFromDomainDisabled`. + +For a confirmed parked domain, CIS requires that DKIM records are not published; the check passes only when no Exchange DKIM configuration or standard selector1/selector2 records are found. A domain with no sending signals but with receiving or other apex DNS records is outside the sending-domain audit scope. Domains with missing or conflicting evidence, or failed DNS lookups, are marked for investigation rather than automatically treated as parked. Selector discovery is limited to the standard Exchange Online selectors, so nonstandard DKIM selector names cannot be ruled out automatically. + +When DNS evidence is inconclusive but a domain is known to be parked, add its name to this test's `ParkedDomains` parameter in `TestSettings[].Parameters`. This selects the parked audit branch; any detected Exchange DKIM configuration or standard selector record still fails the check. #### Remediation action @@ -46,6 +52,8 @@ The initial domain is the domain that you used when you signed up for Office 365 5. Select **DKIM** 6. Click on each domain and click **Enable** next to **Sign messages for this domain with DKIM signature**. +For a confirmed parked domain, do not create an Exchange DKIM signing configuration or publish selector records. Before removing existing records, confirm the domain is not used to send email through Exchange Online or another service. + Final remediation step using the Exchange Online PowerShell Module: 1. Connect to Exchange Online service using `Connect-ExchangeOnline`. diff --git a/tests/cis/Test.CIS.M365.2.1.9.ps1 b/tests/cis/Test.CIS.M365.2.1.9.ps1 index 9a427ac2a3..d645d0bd3b 100644 --- a/tests/cis/Test.CIS.M365.2.1.9.ps1 +++ b/tests/cis/Test.CIS.M365.2.1.9.ps1 @@ -1,17 +1,16 @@ function Test-MtCisDkim { <# .SYNOPSIS - Checks state of DKIM for all EXO domains + Checks DKIM for domains that send email and verifies parked domains have no DKIM records. .DESCRIPTION - DKIM should be enabled with a valid Exchange status for all sending domains. Initial (MOERA) and coexistence domains are excluded, as Microsoft automatically signs outbound mail for those domains. + Sending domains require DKIM to be enabled with a valid Exchange status. Parked domains must not publish DKIM records. Initial (MOERA) and coexistence domains are excluded, as Microsoft automatically signs outbound mail for those domains. Ambiguous domain-use evidence is reported for investigation. CIS Microsoft 365 Foundations Benchmark v7.0.0 (2.1.9, L1) .EXAMPLE Test-MtCisDkim - Returns true if every evaluated domain has a DKIM record, DKIM enabled in Exchange, and Exchange status Valid. - Initial, coexistence, and Exchange sending-disabled domains are excluded; if no domains remain, the test is skipped. + Returns true if every sending domain has DKIM enabled with Exchange status Valid and every parked domain has no known Exchange selector records. Initial and coexistence domains are excluded. Domains classified as not sending are out of scope; ambiguous domains require investigation. .LINK https://maester.dev/docs/commands/Test-MtCisDkim @@ -37,22 +36,21 @@ [OutputType([bool])] param( # Selector-name for the DKIM record to test.. - [string]$Selector = 'selector1' + [string]$Selector = 'selector1', + + # Domains explicitly confirmed as parked; any detected DKIM configuration or selector still fails the audit. + [string[]]$ParkedDomains = @() ) $dkimSigningConfigs = Get-MtExo -Request DkimSigningConfig $acceptedDomains = Get-MtExo -Request AcceptedDomain - <# DKIM record without key for parked domains - $sendingDomains = $acceptedDomains | Where-Object { - -not $_.SendingFromDomainDisabled - } - #> $dkimRecords = @() foreach ($domain in $acceptedDomains) { if ($domain.InitialDomain -eq $true -or $domain.IsCoExistenceDomain -eq $true) { $dkimRecord = [PSCustomObject]@{ domain = $domain.DomainName + classification = 'Excluded' pass = 'Skipped' reason = 'Initial or coexistence domain excluded from DKIM audit (Microsoft auto-signs outbound mail for this domain)' exchangeStatus = 'Excluded' @@ -62,6 +60,44 @@ continue } + $classification = Get-MtCisParkedDomainClassification -DomainName $domain.DomainName -DkimSigningConfigs $dkimSigningConfigs -ParkedDomains $ParkedDomains + if ($classification.Classification -eq 'Parked') { + $hasDkimEvidence = $classification.DkimEvidence + $dkimRecords += [PSCustomObject]@{ + domain = $domain.DomainName + classification = $classification.Classification + pass = if ($hasDkimEvidence) { 'Failed' } else { 'Passed' } + reason = if ($hasDkimEvidence) { "Parked domain has a DKIM configuration or known selector record that must be removed. $($classification.Reason)" } else { "Parked domain has no known DKIM selector records. $($classification.Reason)" } + exchangeStatus = 'Not applicable' + dkimRecord = $null + } + continue + } + + if ($classification.Classification -eq 'NotSending') { + $dkimRecords += [PSCustomObject]@{ + domain = $domain.DomainName + classification = $classification.Classification + pass = 'Skipped' + reason = "The CIS DKIM audit applies to domains configured to send email. $($classification.Reason)" + exchangeStatus = 'Not applicable' + dkimRecord = $null + } + continue + } + + if ($classification.Classification -eq 'Unknown') { + $dkimRecords += [PSCustomObject]@{ + domain = $domain.DomainName + classification = $classification.Classification + pass = 'Investigate' + reason = "Sending use could not be established; the domain was not classified as parked. $($classification.Reason)" + exchangeStatus = 'Not determined' + dkimRecord = $null + } + continue + } + $dkimSigningConfig = $dkimSigningConfigs | Where-Object { $_.domain -eq $domain.domainname } @@ -69,8 +105,9 @@ if (-not $dkimSigningConfig) { $dkimRecord = [PSCustomObject]@{ domain = $domain.DomainName - pass = if ($domain.SendingFromDomainDisabled) { 'Skipped' } else { 'Failed' } - reason = if ($domain.SendingFromDomainDisabled) { 'Parked domain' } else { 'No DkimSigningConfig found for domain' } + classification = $classification.Classification + pass = 'Failed' + reason = 'No DkimSigningConfig found for a domain classified as sending' exchangeStatus = 'Not configured' dkimRecord = $null } @@ -103,11 +140,9 @@ $dkimRecord | Add-Member -MemberType NoteProperty -Name 'pass' -Value 'Failed' $dkimRecord | Add-Member -MemberType NoteProperty -Name 'reason' -Value '' $dkimRecord | Add-Member -MemberType NoteProperty -Name 'exchangeStatus' -Value $dkimSigningConfig.Status + $dkimRecord | Add-Member -MemberType NoteProperty -Name 'classification' -Value $classification.Classification - if ($domain.SendingFromDomainDisabled) { - $dkimRecord.pass = 'Skipped' - $dkimRecord.reason = 'Parked domain' - } elseif (-not $dkimSigningConfig.enabled) { + if (-not $dkimSigningConfig.enabled) { $dkimRecord.pass = 'Failed' $dkimRecord.reason = 'DKIM is disabled' } elseif ($dkimSigningConfig.Status -ne 'Valid') { @@ -133,8 +168,10 @@ if ('Failed' -in $dkimRecords.pass) { $testResult = $false - } elseif ('Failed' -notin $dkimRecords.pass -and 'Passed' -notin $dkimRecords.pass) { - Add-MtTestResultDetail -SkippedBecause NotSupported + } elseif ('Investigate' -in $dkimRecords.pass) { + $testResult = $true + } elseif ('Passed' -notin $dkimRecords.pass) { + Add-MtTestResultDetail -SkippedBecause NotApplicable return $null } else { $testResult = $true @@ -143,7 +180,7 @@ if ('Failed' -in $dkimRecords.pass) { $portalLink = 'https://security.microsoft.com/authentication?viewid=DKIM' if ($testResult) { - $testResultMarkdown = "Well done. Your tenant's domains have DKIM configured and valid records exist.`n`n%TestResult%" + $testResultMarkdown = "Well done. Sending domains have DKIM configured and valid records exist, and parked domains have no known Exchange selector records.`n`n%TestResult%" } else { $testResultMarkdown = "Your tenant's domains do not have DKIM fully deployed. Review [EXO configuration]($portalLink) and DNS records.`n`n%TestResult%" } @@ -151,19 +188,20 @@ if ('Failed' -in $dkimRecords.pass) { $passResult = '✅ Pass' $failResult = '❌ Fail' $skipResult = '🗄️ Skip' - $result = "| Domain | Result | Exchange status | Reason |`n" - $result += "| --- | --- | --- | --- |`n" + $result = "| Domain | Classification | Result | Exchange status | Reason |`n" + $result += "| --- | --- | --- | --- | --- |`n" foreach ($item in $dkimRecords | Sort-Object -Property domain) { switch ($item.pass) { 'Passed' { $itemResult = $passResult } 'Skipped' { $itemResult = $skipResult } 'Failed' { $itemResult = $failResult } + 'Investigate' { $itemResult = '🔎 Investigate' } } - $result += "| $($item.domain) | $($itemResult) | $($item.exchangeStatus) | $($item.reason) |`n" + $result += "| $($item.domain) | $($item.classification) | $($itemResult) | $($item.exchangeStatus) | $($item.reason) |`n" } $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result - Add-MtTestResultDetail -Result $testResultMarkdown + Add-MtTestResultDetail -Result $testResultMarkdown -Investigate:('Investigate' -in $dkimRecords.pass -and 'Failed' -notin $dkimRecords.pass) return $testResult } From 42a5d025268b9ae056b9fc29b12e334ee567a85f Mon Sep 17 00:00:00 2001 From: Jeremy Finney Date: Thu, 5 Nov 2026 08:39:15 +1300 Subject: [PATCH 07/15] docs: list manual CIS assessment IDs --- website/scripts/generate-test-docs.mjs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/website/scripts/generate-test-docs.mjs b/website/scripts/generate-test-docs.mjs index 37f8a514f7..3c52b7daa3 100644 --- a/website/scripts/generate-test-docs.mjs +++ b/website/scripts/generate-test-docs.mjs @@ -67,8 +67,11 @@ const suiteConfig = { title: "CIS Benchmark Tests", sidebarLabel: "🌀 CIS", description: "CIS Benchmark controls implemented as Maester tests.", - overview: - "These tests verify tenant and organization configuration against CIS Benchmark recommendations.", + overview: `These tests verify tenant and organization configuration against CIS Benchmark recommendations. + +The CIS Microsoft 365 Foundations Benchmark v7.0.0 designates the following recommendations for manual assessment. Complete these assessments in addition to running Maester's automated checks. Although CIS marks 8.4.1 manual, Maester includes an automated check for it. + +**Manual assessment recommendation IDs:** 1.1.2, 1.3.8, 2.2.1, 2.4.3, 2.4.5, 5.1.2.1, 5.1.2.4, 5.1.2.5, 5.1.2.6, 5.1.3.2, 5.1.3.3, 5.2.4.1, 5.2.4.2, 5.2.4.3, 5.2.4.4, 5.2.4.5, 8.4.1.`, }, orca: { label: "ORCA", From ffdc08ffc1c18686fb4497a29f52febf3fdbda0d Mon Sep 17 00:00:00 2001 From: Jeremy Finney Date: Thu, 5 Nov 2026 09:42:10 +1300 Subject: [PATCH 08/15] Revert "Add CIS parked-domain audit handling" This reverts commit 48f164dcc8e4f6aed81d3cfdc17c3166d0cd9ad6. --- .../Get-MtCisParkedDomainClassification.ps1 | 137 -------------- .../services/exchange/Resolve-MtDnsRecord.ps1 | 132 -------------- .../exchange/Resolve-MtDnsTxtRecord.ps1 | 58 +++++- ...-MtCisParkedDomainClassification.Tests.ps1 | 160 ----------------- .../functions/Resolve-MtDnsRecord.Tests.ps1 | 170 ------------------ .../Test-MtCisDmarcRecordsPublished.Tests.ps1 | 114 +----------- .../Test-MtCisSpfRecordsPublished.Tests.ps1 | 107 ----------- .../tests/functions/Test-MtDkim.Tests.ps1 | 60 +------ tests/cis/Test.CIS.M365.2.1.10.md | 12 +- tests/cis/Test.CIS.M365.2.1.10.ps1 | 77 ++------ tests/cis/Test.CIS.M365.2.1.8.md | 12 +- tests/cis/Test.CIS.M365.2.1.8.ps1 | 64 ++----- tests/cis/Test.CIS.M365.2.1.9.md | 10 +- tests/cis/Test.CIS.M365.2.1.9.ps1 | 84 +++------ 14 files changed, 122 insertions(+), 1075 deletions(-) delete mode 100644 powershell/internal/checks/cis/exchange/Get-MtCisParkedDomainClassification.ps1 delete mode 100644 powershell/internal/services/exchange/Resolve-MtDnsRecord.ps1 delete mode 100644 powershell/tests/functions/Get-MtCisParkedDomainClassification.Tests.ps1 delete mode 100644 powershell/tests/functions/Resolve-MtDnsRecord.Tests.ps1 delete mode 100644 powershell/tests/functions/Test-MtCisSpfRecordsPublished.Tests.ps1 diff --git a/powershell/internal/checks/cis/exchange/Get-MtCisParkedDomainClassification.ps1 b/powershell/internal/checks/cis/exchange/Get-MtCisParkedDomainClassification.ps1 deleted file mode 100644 index 90634ac61c..0000000000 --- a/powershell/internal/checks/cis/exchange/Get-MtCisParkedDomainClassification.ps1 +++ /dev/null @@ -1,137 +0,0 @@ -function Get-MtCisParkedDomainClassification { - <# - .SYNOPSIS - Classifies an accepted domain using DNS evidence for the CIS email-authentication checks. - - .DESCRIPTION - Sending requires a positive SPF mechanism, a DKIM selector record, or an Exchange DKIM signing - configuration. NotSending requires a single SPF record with only a non-authorizing all - mechanism and no known DKIM selector records or Exchange signing configuration. Parked - additionally requires no MX record (or a null MX) and no address or CNAME record at the domain - apex. Incomplete or conflicting evidence is Unknown and must not receive the parked-domain - audit exception. - - .PARAMETER DomainName - The accepted domain to classify. - - .PARAMETER DkimSigningConfigs - Exchange DKIM signing configurations already retrieved by the calling test. - #> - [CmdletBinding()] - [OutputType([pscustomobject])] - param( - [Parameter(Mandatory)] - [string]$DomainName, - - [object[]]$DkimSigningConfigs = @(), - - [string[]]$ParkedDomains = @() - ) - - $lookups = [ordered]@{ - SPF = Resolve-MtDnsRecord -Name $DomainName -Type TXT - MX = Resolve-MtDnsRecord -Name $DomainName -Type MX - A = Resolve-MtDnsRecord -Name $DomainName -Type A - AAAA = Resolve-MtDnsRecord -Name $DomainName -Type AAAA - CNAME = Resolve-MtDnsRecord -Name $DomainName -Type CNAME - } - foreach ($selector in 'selector1', 'selector2') { - foreach ($type in 'CNAME', 'TXT') { - $lookupName = "$selector._domainkey.$DomainName" - $lookups["DKIM:$selector`:$type"] = Resolve-MtDnsRecord -Name $lookupName -Type $type - } - } - - $spfAnswers = @($lookups.SPF.Answers | ForEach-Object { $_.Value } | Where-Object { $_ -match '^\s*v=spf1(?:\s|$)' }) - $spfRecord = if ($spfAnswers.Count -eq 1) { [string]$spfAnswers[0] } else { $null } - $spfTerms = if ($spfRecord) { @($spfRecord.Trim() -split '\s+' | Select-Object -Skip 1) } else { @() } - $spfAllTerms = @($spfTerms | Where-Object { $_ -match '^(?i)[+?~-]?all$' }) - $spfRedirectTerms = @($spfTerms | Where-Object { $_ -match '^(?i)redirect=' }) - $spfOtherTerms = @($spfTerms | Where-Object { $_ -notmatch '^(?i)[+?~-]?all$' -and $_ -notmatch '^(?i)exp=' -and $_ -notmatch '^(?i)redirect=' }) - $spfAllQualifier = if ($spfAllTerms.Count -eq 1) { - $qualifier = [regex]::Match($spfAllTerms[0], '^(?[+?~-]?)all$', [System.Text.RegularExpressions.RegexOptions]::IgnoreCase).Groups['qualifier'].Value - if ($qualifier) { $qualifier } else { '+' } - } else { - $null - } - $spfDoesNotAuthorizeSenders = $spfAllTerms.Count -eq 1 -and $spfAllQualifier -in @('-', '~', '?') -and $spfOtherTerms.Count -eq 0 - $spfHasSenderMechanisms = $spfRecord -and -not $spfDoesNotAuthorizeSenders -and ($spfOtherTerms.Count -gt 0 -or $spfAllQualifier -eq '+') - - $domainConfigs = @($DkimSigningConfigs | Where-Object { - $configDomain = $null - if ($_.PSObject.Properties['Domain']) { - $configDomain = $_.Domain - } elseif ($_.PSObject.Properties['Name']) { - $configDomain = $_.Name - } - $configDomain -and [string]::Equals([string]$configDomain, $DomainName, [System.StringComparison]::OrdinalIgnoreCase) - }) - $dkimLookups = @($lookups.GetEnumerator() | Where-Object { $_.Key -like 'DKIM:*' }) - $hasDkimEvidence = $domainConfigs.Count -gt 0 -or @($dkimLookups | Where-Object { @($_.Value.Answers).Count -gt 0 }).Count -gt 0 - $unknownDkimLookups = @($dkimLookups | Where-Object { $_.Value.Status -notin @('Success', 'NXDomain') }) - - $classification = 'Unknown' - $reason = 'The DNS evidence does not establish whether the domain sends email.' - if ($hasDkimEvidence -or $spfHasSenderMechanisms) { - $classification = 'Sending' - $reason = 'An Exchange DKIM configuration, a known DKIM selector record, or an SPF mechanism other than -all indicates email-sending use.' - } elseif ($spfDoesNotAuthorizeSenders -and $unknownDkimLookups.Count -eq 0) { - $classification = 'NotSending' - $reason = 'SPF has only a non-authorizing all mechanism and no Exchange DKIM configuration or selector1/selector2 records were found.' - - $mxRecords = @($lookups.MX.Answers) - $nullMx = $mxRecords.Count -eq 1 -and [string]$mxRecords[0].Value -eq '.' -and [string]$mxRecords[0].Preference -eq '0' - $hasMx = @($mxRecords | Where-Object { [string]$_.Value -and [string]$_.Value -ne '.' }).Count -gt 0 - $hasAddress = @($lookups.A.Answers).Count -gt 0 -or @($lookups.AAAA.Answers).Count -gt 0 - $hasCname = @($lookups.CNAME.Answers).Count -gt 0 - $receivingLookupsKnown = @($lookups.MX, $lookups.A, $lookups.AAAA, $lookups.CNAME | Where-Object { $_.Status -notin @('Success', 'NXDomain') }).Count -eq 0 - $hasNoMx = $mxRecords.Count -eq 0 - - if ($receivingLookupsKnown -and -not $hasMx -and -not $hasAddress -and -not $hasCname -and ($hasNoMx -or $nullMx)) { - $classification = 'Parked' - $reason = if ($nullMx) { - 'SPF has only a non-authorizing all mechanism, no DKIM configuration or known selector records exist, and null MX plus no apex address or CNAME records indicates no email or other DNS use.' - } else { - 'SPF has only a non-authorizing all mechanism, no DKIM configuration or known selector records exist, and no MX, fallback address, or apex CNAME records were found.' - } - } - } - - if ($classification -eq 'Unknown') { - $failedLookups = @($lookups.GetEnumerator() | Where-Object { $_.Value.Status -notin @('Success', 'NXDomain') }) - if ($failedLookups.Count -gt 0) { - $reason = "DNS lookup results are incomplete for $($failedLookups.Key -join ', '); the domain is not classified as parked." - } elseif (-not $spfRecord) { - $reason = 'A single SPF v1 record was not found; the domain is not classified as parked.' - } else { - $reason = 'The SPF and DKIM evidence is conflicting or inconclusive; the domain is not classified as parked.' - } - } elseif ($classification -eq 'NotSending') { - $failedReceivingLookups = @($lookups.MX, $lookups.A, $lookups.AAAA, $lookups.CNAME | Where-Object { $_.Status -notin @('Success', 'NXDomain') }) - if ($failedReceivingLookups.Count -gt 0) { - $reason += ' Receiving or other domain use could not be ruled out because some DNS lookups failed.' - } elseif ($hasMx -or $hasAddress -or $hasCname) { - $reason += ' Receiving or other domain use is present, so the domain is not classified as parked.' - } - } - - $isOverride = @($ParkedDomains | Where-Object { - [string]::Equals($_.TrimEnd('.'), $DomainName.TrimEnd('.'), [System.StringComparison]::OrdinalIgnoreCase) - }).Count -gt 0 - if ($isOverride) { - $automaticClassification = $classification - $classification = 'Parked' - $reason = "The domain was explicitly listed in ParkedDomains. Automatic DNS classification was '$automaticClassification'." - } - - return [pscustomobject]@{ - DomainName = $DomainName - Classification = $classification - IsParked = $classification -eq 'Parked' - IsOverride = $isOverride - SpfRecord = $spfRecord - SpfDeniesAll = $spfDoesNotAuthorizeSenders -and $spfAllQualifier -eq '-' -and $spfRedirectTerms.Count -eq 0 - DkimEvidence = $hasDkimEvidence - Reason = $reason - } -} \ No newline at end of file diff --git a/powershell/internal/services/exchange/Resolve-MtDnsRecord.ps1 b/powershell/internal/services/exchange/Resolve-MtDnsRecord.ps1 deleted file mode 100644 index 7430139d01..0000000000 --- a/powershell/internal/services/exchange/Resolve-MtDnsRecord.ps1 +++ /dev/null @@ -1,132 +0,0 @@ -function Resolve-MtDnsRecord { - <# - .SYNOPSIS - Resolves DNS records with consistent results across supported platforms. - - .DESCRIPTION - Uses Resolve-DnsName on Windows and Resolve-Dns from DnsClient-PS on other platforms. - A successful query with no answers has Status Success and an empty Answers array. - - .PARAMETER Name - The DNS name to query. - - .PARAMETER Type - The DNS record type to query. - #> - [CmdletBinding()] - [OutputType([pscustomobject])] - param( - [Parameter(Mandatory)] - [string]$Name, - - [Parameter(Mandatory)] - [ValidateSet('A', 'AAAA', 'CNAME', 'MX', 'TXT')] - [string]$Type - ) - - $result = [pscustomobject]@{ - Name = $Name - Type = $Type - Status = 'Success' - Answers = [object[]]@() - Error = $null - } - $answers = @() - - if ($IsWindows) { - try { - $response = Resolve-DnsName -Name $Name -Type $Type -ErrorAction Stop - $answers = @($response | Where-Object { $_.Section -eq 'Answer' -and $_.Type -eq $Type }) - } catch [System.Management.Automation.CommandNotFoundException] { - $result.Status = 'NotAvailable' - $result.Error = 'Unsupported platform, Resolve-DnsName not available' - return $result - } catch { - if ($_.FullyQualifiedErrorId -like 'DNS_ERROR_RCODE_NAME_ERROR*') { - $result.Status = 'NXDomain' - } elseif ($_.FullyQualifiedErrorId -notlike 'DNS_INFO_NO_RECORDS*') { - $result.Status = 'Error' - $result.Error = "$_" - } - return $result - } - } else { - if (-not (Get-Command -Name 'Resolve-Dns' -ErrorAction SilentlyContinue)) { - $result.Status = 'NotAvailable' - $result.Error = 'Missing dependency, Resolve-Dns not available' - return $result - } - - try { - $response = Resolve-Dns -Query $Name -QueryType $Type -ErrorAction Stop - if ($response.HasError) { - if ("$($response.Header.ResponseCode)" -eq 'NotExistentDomain') { - $result.Status = 'NXDomain' - } else { - $result.Status = 'Error' - $result.Error = $response.ErrorMessage - } - return $result - } - $answers = @($response.Answers | Where-Object { "$($_.RecordType)" -eq $Type }) - } catch { - $result.Status = 'Error' - $result.Error = "$_" - return $result - } - } - - foreach ($answer in $answers) { - $value = $null - $preference = $null - switch ($Type) { - 'TXT' { - if ($answer.PSObject.Properties['Strings']) { - $value = @($answer.Strings) -join '' - } elseif ($answer.PSObject.Properties['Text']) { - $value = @($answer.Text) -join '' - } - } - 'MX' { - if ($answer.PSObject.Properties['NameExchange']) { - $value = $answer.NameExchange - } elseif ($answer.PSObject.Properties['Exchange']) { - $value = $answer.Exchange - } - if ($answer.PSObject.Properties['Preference']) { - $preference = $answer.Preference - } - } - 'CNAME' { - foreach ($propertyName in 'NameHost', 'CanonicalName', 'CName', 'HostName') { - if ($answer.PSObject.Properties[$propertyName]) { - $value = $answer.PSObject.Properties[$propertyName].Value - break - } - } - } - { $_ -in 'A', 'AAAA' } { - foreach ($propertyName in 'IPAddress', 'IPv4Address', 'IPv6Address', 'Address') { - if ($answer.PSObject.Properties[$propertyName]) { - $value = $answer.PSObject.Properties[$propertyName].Value - break - } - } - } - } - - if ($null -eq $value -or [string]::IsNullOrWhiteSpace([string]$value)) { - $result.Status = 'Error' - $result.Error = "The DNS resolver returned an unusable $Type answer for $Name." - $result.Answers = [object[]]@() - return $result - } - - $result.Answers += [pscustomobject]@{ - Value = [string]$value - Preference = $preference - } - } - - return $result -} \ No newline at end of file diff --git a/powershell/internal/services/exchange/Resolve-MtDnsTxtRecord.ps1 b/powershell/internal/services/exchange/Resolve-MtDnsTxtRecord.ps1 index 1bc6b4aeb0..e40b7698d4 100644 --- a/powershell/internal/services/exchange/Resolve-MtDnsTxtRecord.ps1 +++ b/powershell/internal/services/exchange/Resolve-MtDnsTxtRecord.ps1 @@ -1,4 +1,4 @@ -function Resolve-MtDnsTxtRecord { +function Resolve-MtDnsTxtRecord { <# .SYNOPSIS Returns the TXT records published at a DNS name, without filtering them. @@ -29,11 +29,55 @@ [string]$Name ) - $dnsResult = Resolve-MtDnsRecord -Name $Name -Type TXT - return [pscustomobject]@{ - Name = $dnsResult.Name - Status = $dnsResult.Status - Answers = [string[]]@($dnsResult.Answers | ForEach-Object { $_.Value }) - Error = $dnsResult.Error + $result = [pscustomobject]@{ + Name = $Name + Status = 'Success' + Answers = [string[]]@() + Error = $null } + + if ($IsWindows) { + try { + $response = Resolve-DnsName -Name $Name -Type TXT -ErrorAction Stop + $result.Answers = [string[]]@($response | Where-Object { $_.Section -eq 'Answer' -and $_.Type -eq 'TXT' } | ForEach-Object { $_.Strings -join '' }) + } catch [System.Management.Automation.CommandNotFoundException] { + $result.Status = 'NotAvailable' + $result.Error = 'Unsupported platform, Resolve-DnsName not available' + } catch { + Write-Verbose "TXT lookup for $($Name) failed: $_" + if ($_.FullyQualifiedErrorId -like 'DNS_ERROR_RCODE_NAME_ERROR*') { + $result.Status = 'NXDomain' + } elseif ($_.FullyQualifiedErrorId -notlike 'DNS_INFO_NO_RECORDS*') { + $result.Status = 'Error' + $result.Error = "$_" + } + } + return $result + } + + if (-not (Get-Command -Name 'Resolve-Dns' -ErrorAction SilentlyContinue)) { + Write-Verbose 'For non-Windows platforms, please install the DnsClient-PS module: Install-Module DnsClient-PS -Scope CurrentUser' + $result.Status = 'NotAvailable' + $result.Error = 'Missing dependency, Resolve-Dns not available' + return $result + } + + try { + $response = Resolve-Dns -Query $Name -QueryType TXT -ErrorAction Stop + if ($response.HasError) { + if ("$($response.Header.ResponseCode)" -eq 'NotExistentDomain') { + $result.Status = 'NXDomain' + } else { + $result.Status = 'Error' + $result.Error = $response.ErrorMessage + } + } else { + $result.Answers = [string[]]@($response.Answers | Where-Object { "$($_.RecordType)" -eq 'TXT' } | ForEach-Object { $_.Text -join '' }) + } + } catch { + Write-Verbose "TXT lookup for $($Name) failed: $_" + $result.Status = 'Error' + $result.Error = "$_" + } + return $result } diff --git a/powershell/tests/functions/Get-MtCisParkedDomainClassification.Tests.ps1 b/powershell/tests/functions/Get-MtCisParkedDomainClassification.Tests.ps1 deleted file mode 100644 index 7230a8c7a5..0000000000 --- a/powershell/tests/functions/Get-MtCisParkedDomainClassification.Tests.ps1 +++ /dev/null @@ -1,160 +0,0 @@ -Describe 'Get-MtCisParkedDomainClassification' { - BeforeAll { - Import-Module "$PSScriptRoot/../../Maester.psd1" -Force -WarningAction SilentlyContinue - . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" - Use-MtModuleFunction -Name Get-MtCisParkedDomainClassification - - function New-TestDnsResult { - param( - [string]$Name, - [string]$Type, - [object[]]$Answers = @(), - [string]$Status = 'Success' - ) - [pscustomobject]@{ Name = $Name; Type = $Type; Status = $Status; Answers = $Answers; Error = $null } - } - } - - BeforeEach { - $script:dnsResults = @{} - Mock Resolve-MtDnsRecord -ModuleName Maester { - $key = "$Type|$Name" - if ($script:dnsResults.ContainsKey($key)) { - return $script:dnsResults[$key] - } - return New-TestDnsResult -Name $Name -Type $Type - } - } - - It 'classifies a deny-all domain with null MX and no other DNS use as parked' { - $script:dnsResults['TXT|parked.example'] = New-TestDnsResult -Name 'parked.example' -Type TXT -Answers @( - [pscustomobject]@{ Value = 'v=spf1 -all'; Preference = $null } - ) - $script:dnsResults['MX|parked.example'] = New-TestDnsResult -Name 'parked.example' -Type MX -Answers @( - [pscustomobject]@{ Value = '.'; Preference = 0 } - ) - - $result = Get-MtCisParkedDomainClassification -DomainName 'parked.example' - - $result.Classification | Should -Be 'Parked' - $result.IsParked | Should -BeTrue - } - - It 'classifies a deny-all domain without MX or fallback addresses as parked' { - $script:dnsResults['TXT|parked.example'] = New-TestDnsResult -Name 'parked.example' -Type TXT -Answers @( - [pscustomobject]@{ Value = 'v=spf1 -all'; Preference = $null } - ) - - $result = Get-MtCisParkedDomainClassification -DomainName 'parked.example' - - $result.Classification | Should -Be 'Parked' - } - - It 'classifies a softfail-only domain as parked so the audit can enforce hard fail' { - $script:dnsResults['TXT|parked.example'] = New-TestDnsResult -Name 'parked.example' -Type TXT -Answers @( - [pscustomobject]@{ Value = 'v=spf1 ~all'; Preference = $null } - ) - - $result = Get-MtCisParkedDomainClassification -DomainName 'parked.example' - - $result.Classification | Should -Be 'Parked' - $result.SpfDeniesAll | Should -BeFalse - } - - It 'does not classify a domain with fallback address records as parked' { - $script:dnsResults['TXT|mail.example'] = New-TestDnsResult -Name 'mail.example' -Type TXT -Answers @( - [pscustomobject]@{ Value = 'v=spf1 -all'; Preference = $null } - ) - $script:dnsResults['A|mail.example'] = New-TestDnsResult -Name 'mail.example' -Type A -Answers @( - [pscustomobject]@{ Value = '192.0.2.10'; Preference = $null } - ) - - $result = Get-MtCisParkedDomainClassification -DomainName 'mail.example' - - $result.Classification | Should -Be 'NotSending' - $result.IsParked | Should -BeFalse - } - - It 'classifies a configured DKIM domain as sending' { - $config = [pscustomobject]@{ Domain = 'sender.example'; Enabled = $false } - - $result = Get-MtCisParkedDomainClassification -DomainName 'sender.example' -DkimSigningConfigs @($config) - - $result.Classification | Should -Be 'Sending' - } - - It 'classifies a domain with a published standard DKIM selector as sending' { - $script:dnsResults['TXT|sender.example'] = New-TestDnsResult -Name 'sender.example' -Type TXT -Answers @( - [pscustomobject]@{ Value = 'v=spf1 -all'; Preference = $null } - ) - $script:dnsResults['CNAME|selector1._domainkey.sender.example'] = New-TestDnsResult -Name 'selector1._domainkey.sender.example' -Type CNAME -Answers @( - [pscustomobject]@{ Value = 'selector1-sender._domainkey.example.onmicrosoft.com'; Preference = $null } - ) - - $result = Get-MtCisParkedDomainClassification -DomainName 'sender.example' - - $result.Classification | Should -Be 'Sending' - $result.DkimEvidence | Should -BeTrue - } - - It 'applies an explicit parked override while retaining conflicting DKIM evidence' { - $script:dnsResults['CNAME|selector1._domainkey.sender.example'] = New-TestDnsResult -Name 'selector1._domainkey.sender.example' -Type CNAME -Answers @( - [pscustomobject]@{ Value = 'selector1-sender._domainkey.example.onmicrosoft.com'; Preference = $null } - ) - - $result = Get-MtCisParkedDomainClassification -DomainName 'sender.example' -ParkedDomains 'SENDER.EXAMPLE.' - - $result.Classification | Should -Be 'Parked' - $result.IsOverride | Should -BeTrue - $result.DkimEvidence | Should -BeTrue - } - - It 'classifies a domain with SPF mechanisms as sending' { - $script:dnsResults['TXT|sender.example'] = New-TestDnsResult -Name 'sender.example' -Type TXT -Answers @( - [pscustomobject]@{ Value = 'v=spf1 include:spf.example.net -all'; Preference = $null } - ) - - $result = Get-MtCisParkedDomainClassification -DomainName 'sender.example' - - $result.Classification | Should -Be 'Sending' - } - - It 'treats an unqualified all mechanism as a sending signal' { - $script:dnsResults['TXT|sender.example'] = New-TestDnsResult -Name 'sender.example' -Type TXT -Answers @( - [pscustomobject]@{ Value = 'v=spf1 all'; Preference = $null } - ) - - $result = Get-MtCisParkedDomainClassification -DomainName 'sender.example' - - $result.Classification | Should -Be 'Sending' - } - - It 'leaves a domain unknown when SPF is missing' { - $result = Get-MtCisParkedDomainClassification -DomainName 'unknown.example' - - $result.Classification | Should -Be 'Unknown' - $result.IsParked | Should -BeFalse - } - - It 'leaves redirect-only SPF unknown until the redirect target is evaluated' { - $script:dnsResults['TXT|unknown.example'] = New-TestDnsResult -Name 'unknown.example' -Type TXT -Answers @( - [pscustomobject]@{ Value = 'v=spf1 redirect=_spf.example.net'; Preference = $null } - ) - - $result = Get-MtCisParkedDomainClassification -DomainName 'unknown.example' - - $result.Classification | Should -Be 'Unknown' - $result.SpfDeniesAll | Should -BeFalse - } - - It 'leaves a domain unknown when a DKIM DNS lookup fails' { - $script:dnsResults['TXT|unknown.example'] = New-TestDnsResult -Name 'unknown.example' -Type TXT -Answers @( - [pscustomobject]@{ Value = 'v=spf1 -all'; Preference = $null } - ) - $script:dnsResults['CNAME|selector1._domainkey.unknown.example'] = New-TestDnsResult -Name 'selector1._domainkey.unknown.example' -Type CNAME -Status Error - - $result = Get-MtCisParkedDomainClassification -DomainName 'unknown.example' - - $result.Classification | Should -Be 'Unknown' - } -} \ No newline at end of file diff --git a/powershell/tests/functions/Resolve-MtDnsRecord.Tests.ps1 b/powershell/tests/functions/Resolve-MtDnsRecord.Tests.ps1 deleted file mode 100644 index f4f32a3528..0000000000 --- a/powershell/tests/functions/Resolve-MtDnsRecord.Tests.ps1 +++ /dev/null @@ -1,170 +0,0 @@ -Describe 'Resolve-MtDnsRecord with Resolve-DnsName' -Skip:(-not $IsWindows) { - BeforeAll { - Import-Module "$PSScriptRoot/../../Maester.psd1" -Force -WarningAction SilentlyContinue - . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" - Use-MtModuleFunction -Name Resolve-MtDnsRecord - } - - BeforeEach { - Mock Resolve-DnsName -ModuleName Maester {} - } - - It 'normalizes MX answers and their preference' { - Mock Resolve-DnsName -ModuleName Maester { - [pscustomobject]@{ - Section = 'Answer' - Type = 'MX' - NameExchange = 'mail.example.com' - Preference = 10 - } - } - - $result = Resolve-MtDnsRecord -Name 'example.com' -Type MX - - $result.Status | Should -Be 'Success' - $result.Answers.Count | Should -Be 1 - $result.Answers[0].Value | Should -Be 'mail.example.com' - $result.Answers[0].Preference | Should -Be 10 - } - - It 'joins TXT character strings into one record' { - Mock Resolve-DnsName -ModuleName Maester { - [pscustomobject]@{ - Section = 'Answer' - Type = 'TXT' - Strings = @('v=spf1 ', '-all') - } - } - - $result = Resolve-MtDnsRecord -Name 'example.com' -Type TXT - - $result.Answers[0].Value | Should -Be 'v=spf1 -all' - } - - It 'returns success with no answers when the record type is absent' { - $result = Resolve-MtDnsRecord -Name 'example.com' -Type MX - - $result.Status | Should -Be 'Success' - $result.Answers.Count | Should -Be 0 - } - - It 'distinguishes a missing DNS name from a resolver failure' { - Mock Resolve-DnsName -ModuleName Maester { - throw [System.Management.Automation.ErrorRecord]::new( - [System.Exception]::new('The DNS name does not exist.'), - 'DNS_ERROR_RCODE_NAME_ERROR', - [System.Management.Automation.ErrorCategory]::ObjectNotFound, - $null - ) - } - - $missing = Resolve-MtDnsRecord -Name 'missing.example' -Type MX - - Mock Resolve-DnsName -ModuleName Maester { - throw [System.Management.Automation.ErrorRecord]::new( - [System.Exception]::new('The DNS server is unavailable.'), - 'DNS_ERROR_RCODE_SERVER_FAILURE', - [System.Management.Automation.ErrorCategory]::ResourceUnavailable, - $null - ) - } - - $unavailable = Resolve-MtDnsRecord -Name 'example.com' -Type MX - - $missing.Status | Should -Be 'NXDomain' - $unavailable.Status | Should -Be 'Error' - } -} - -Describe 'Resolve-MtDnsRecord with Resolve-Dns' -Skip:$IsWindows { - BeforeAll { - Import-Module "$PSScriptRoot/../../Maester.psd1" -Force -WarningAction SilentlyContinue - . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" - Use-MtModuleFunction -Name Resolve-MtDnsRecord - - $script:createdDnsStub = & (Get-Module Maester) { - if (-not (Get-Command -Name 'Resolve-Dns' -ErrorAction SilentlyContinue)) { - Set-Item -Path 'Function:script:Resolve-Dns' -Value { - [CmdletBinding()] - param($Query, $QueryType, $NameServer) - throw 'The DNS resolver must be mocked in this test.' - } - $true - } else { - $false - } - } - } - - AfterAll { - if ($script:createdDnsStub) { - & (Get-Module Maester) { Remove-Item -Path 'Function:script:Resolve-Dns' } - } - } - - BeforeEach { - Mock Resolve-Dns -ModuleName Maester {} - } - - It 'normalizes MX answers and their preference' { - Mock Resolve-Dns -ModuleName Maester { - [pscustomobject]@{ - HasError = $false - Header = [pscustomobject]@{ ResponseCode = 'NoError' } - Answers = @([pscustomobject]@{ RecordType = 'MX'; Exchange = 'mail.example.com'; Preference = 10 }) - } - } - - $result = Resolve-MtDnsRecord -Name 'example.com' -Type MX - - $result.Status | Should -Be 'Success' - $result.Answers.Count | Should -Be 1 - $result.Answers[0].Value | Should -Be 'mail.example.com' - $result.Answers[0].Preference | Should -Be 10 - Should -Invoke -ModuleName Maester Resolve-Dns -Exactly 1 -ParameterFilter { - $Query -eq 'example.com' -and $QueryType -eq 'MX' - } - } - - It 'joins TXT character strings into one record' { - Mock Resolve-Dns -ModuleName Maester { - [pscustomobject]@{ - HasError = $false - Header = [pscustomobject]@{ ResponseCode = 'NoError' } - Answers = @([pscustomobject]@{ RecordType = 'TXT'; Text = @('v=spf1 ', '-all') }) - } - } - - $result = Resolve-MtDnsRecord -Name 'example.com' -Type TXT - - $result.Answers[0].Value | Should -Be 'v=spf1 -all' - } - - It 'distinguishes a missing DNS name from a resolver failure' { - Mock Resolve-Dns -ModuleName Maester { - [pscustomobject]@{ - HasError = $true - Header = [pscustomobject]@{ ResponseCode = 'NotExistentDomain' } - ErrorMessage = 'Non-Existent Domain' - Answers = @() - } - } - - $missing = Resolve-MtDnsRecord -Name 'missing.example' -Type MX - - Mock Resolve-Dns -ModuleName Maester { - [pscustomobject]@{ - HasError = $true - Header = [pscustomobject]@{ ResponseCode = 'ServerFailure' } - ErrorMessage = 'Server Failure' - Answers = @() - } - } - - $unavailable = Resolve-MtDnsRecord -Name 'example.com' -Type MX - - $missing.Status | Should -Be 'NXDomain' - $unavailable.Status | Should -Be 'Error' - $unavailable.Error | Should -Be 'Server Failure' - } -} \ No newline at end of file diff --git a/powershell/tests/functions/Test-MtCisDmarcRecordsPublished.Tests.ps1 b/powershell/tests/functions/Test-MtCisDmarcRecordsPublished.Tests.ps1 index cffee9fbbf..75200ec0e9 100644 --- a/powershell/tests/functions/Test-MtCisDmarcRecordsPublished.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisDmarcRecordsPublished.Tests.ps1 @@ -4,82 +4,20 @@ . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" Use-MtModuleFunction -Name Test-MtCisDmarcRecordsPublished - $script:dmarcRecordText = 'v=DMARC1; p=reject' - $script:dnsResolverCommand = if ($IsWindows) { 'Resolve-DnsName' } else { 'Resolve-Dns' } - $script:createdDnsResolverStub = & (Get-Module Maester) { - param($CommandName) - if (-not (Get-Command -Name $CommandName -ErrorAction SilentlyContinue)) { - Set-Item -Path "Function:script:$CommandName" -Value { - [CmdletBinding()] - param($Name, $Type, $Query, $QueryType, $NameServer) - throw 'The DNS resolver must be mocked in this test.' - } - $true - } else { - $false - } - } $script:dnsResolverCommand - Mock -CommandName $script:dnsResolverCommand -ModuleName Maester { - if ($script:dnsResolverCommand -eq 'Resolve-DnsName') { - [pscustomobject]@{ Section = 'Answer'; Type = 'TXT'; Strings = @($script:dmarcRecordText) } - } else { - [pscustomobject]@{ - HasError = $false - Header = [pscustomobject]@{ ResponseCode = 'NoError' } - Answers = @([pscustomobject]@{ RecordType = 'TXT'; Text = @($script:dmarcRecordText) }) - } - } - } - $script:parkedDmarcRecord = ConvertFrom-MailAuthenticationRecordDmarc -DomainName 'parked.example' - $script:dmarcRecordText = 'v=DMARC1; p=quarantine' - $script:quarantineDmarcRecord = ConvertFrom-MailAuthenticationRecordDmarc -DomainName 'quarantine.example' - $script:dmarcRecordText = 'v=DMARC1; p=reject; pct=100; rua=mailto:reports@example.com; ruf=mailto:forensic@example.com' - $script:fullyCompliantDmarcRecord = ConvertFrom-MailAuthenticationRecordDmarc -DomainName 'sending.example' - $script:domains = @() $script:registrableDomains = @{} $script:dmarcResults = @{} - $script:classifications = @{} - $script:dkimSigningConfigs = @() - Mock Get-MtExo -ModuleName Maester { - if ($Request -eq 'AcceptedDomain') { return $script:domains } - return $script:dkimSigningConfigs - } + Mock Get-MtExo -ModuleName Maester { $script:domains } Mock Get-MtRegistrableDomain -ModuleName Maester { $script:registrableDomains[$DomainName] } Mock ConvertFrom-MailAuthenticationRecordDmarc -ModuleName Maester { $script:dmarcResults[$DomainName] } - Mock Get-MtCisParkedDomainClassification -ModuleName Maester { - $classification = if ($script:classifications.ContainsKey($DomainName)) { - $script:classifications[$DomainName] - } else { - [pscustomobject]@{ Classification = 'Sending'; Reason = 'Sending-domain test default.' } - } - if ($ParkedDomains -contains $DomainName) { - $classification.Classification = 'Parked' - } - return $classification - } - Mock Add-MtTestResultDetail -ModuleName Maester { - $script:resultDetail = [pscustomobject]@{ Result = $Result; Investigate = [bool]$Investigate; SkippedBecause = $SkippedBecause } - } - } - - AfterAll { - if ($script:createdDnsResolverStub) { - & (Get-Module Maester) { - param($CommandName) - Remove-Item -Path "Function:script:$CommandName" - } $script:dnsResolverCommand - } + Mock Add-MtTestResultDetail -ModuleName Maester {} } BeforeEach { $script:domains = @() $script:registrableDomains = @{} $script:dmarcResults = @{} - $script:classifications = @{} - $script:dkimSigningConfigs = @() - $script:resultDetail = $null } It 'fails a known noncompliant domain before skipping an unavailable lookup' { @@ -121,52 +59,4 @@ $Result -match 'Invalid DMARC record' -and $Result -match 'mail.example.com' } } - - It 'requires p=reject but not reporting tags for parked domains' { - $script:domains = @([pscustomobject]@{ DomainName = 'parked.example'; IsCoExistenceDomain = $false }) - $script:registrableDomains = @{ 'parked.example' = 'parked.example' } - $script:dmarcResults = @{ 'parked.example' = $script:parkedDmarcRecord } - $script:classifications = @{ 'parked.example' = [pscustomobject]@{ Classification = 'Parked'; Reason = 'No mail-use signals were found.' } } - - Test-MtCisDmarcRecordsPublished | Should -BeTrue - $script:resultDetail.Investigate | Should -BeFalse - } - - It 'fails a parked domain whose DMARC policy is quarantine' { - $script:domains = @([pscustomobject]@{ DomainName = 'parked.example'; IsCoExistenceDomain = $false }) - $script:registrableDomains = @{ 'parked.example' = 'parked.example' } - $script:dmarcResults = @{ 'parked.example' = $script:quarantineDmarcRecord } - $script:classifications = @{ 'parked.example' = [pscustomobject]@{ Classification = 'Parked'; Reason = 'No mail-use signals were found.' } } - - Test-MtCisDmarcRecordsPublished | Should -BeFalse - } - - It 'investigates an unknown domain when only the parked-domain policy passes' { - $script:domains = @([pscustomobject]@{ DomainName = 'unknown.example'; IsCoExistenceDomain = $false }) - $script:registrableDomains = @{ 'unknown.example' = 'unknown.example' } - $script:dmarcResults = @{ 'unknown.example' = $script:parkedDmarcRecord } - $script:classifications = @{ 'unknown.example' = [pscustomobject]@{ Classification = 'Unknown'; Reason = 'DNS evidence is incomplete.' } } - - Test-MtCisDmarcRecordsPublished | Should -BeTrue - $script:resultDetail.Investigate | Should -BeTrue - } - - It 'applies an explicit parked override and requires reject policy' { - $script:domains = @([pscustomobject]@{ DomainName = 'unknown.example'; IsCoExistenceDomain = $false }) - $script:registrableDomains = @{ 'unknown.example' = 'unknown.example' } - $script:dmarcResults = @{ 'unknown.example' = $script:quarantineDmarcRecord } - $script:classifications = @{ 'unknown.example' = [pscustomobject]@{ Classification = 'Unknown'; Reason = 'DNS evidence is incomplete.' } } - - Test-MtCisDmarcRecordsPublished -ParkedDomains 'unknown.example' | Should -BeFalse - } - - It 'accepts a fully compliant DMARC record when both procedures pass' { - $script:domains = @([pscustomobject]@{ DomainName = 'unknown.example'; IsCoExistenceDomain = $false }) - $script:registrableDomains = @{ 'unknown.example' = 'unknown.example' } - $script:dmarcResults = @{ 'unknown.example' = $script:fullyCompliantDmarcRecord } - $script:classifications = @{ 'unknown.example' = [pscustomobject]@{ Classification = 'Unknown'; Reason = 'DNS evidence is incomplete.' } } - - Test-MtCisDmarcRecordsPublished | Should -BeTrue - $script:resultDetail.Investigate | Should -BeFalse - } } diff --git a/powershell/tests/functions/Test-MtCisSpfRecordsPublished.Tests.ps1 b/powershell/tests/functions/Test-MtCisSpfRecordsPublished.Tests.ps1 deleted file mode 100644 index fbaf964ec3..0000000000 --- a/powershell/tests/functions/Test-MtCisSpfRecordsPublished.Tests.ps1 +++ /dev/null @@ -1,107 +0,0 @@ -Describe 'CIS M365 SPF check' { - BeforeAll { - Import-Module "$PSScriptRoot/../../Maester.psd1" -Force -WarningAction SilentlyContinue - . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" - Use-MtModuleFunction -Name Test-MtCisSpfRecordsPublished - - Mock Get-MtExo -ModuleName Maester { - if ($Request -eq 'AcceptedDomain') { return $script:domains } - return $script:dkimSigningConfigs - } - Mock ConvertFrom-MailAuthenticationRecordSpf -ModuleName Maester { $script:spfResults[$DomainName] } - Mock Get-MtCisParkedDomainClassification -ModuleName Maester { - $classification = $script:classifications[$DomainName] - if ($ParkedDomains -contains $DomainName) { - $classification.Classification = 'Parked' - } - return $classification - } - Mock Add-MtTestResultDetail -ModuleName Maester { - $script:resultDetail = [pscustomobject]@{ - Result = $Result - Investigate = [bool]$Investigate - SkippedBecause = $SkippedBecause - } - } - } - - BeforeEach { - $script:domains = @([pscustomobject]@{ DomainName = 'example.com'; InitialDomain = $false; IsCoExistenceDomain = $false }) - $script:dkimSigningConfigs = @() - $script:spfResults = @{} - $script:classifications = @{} - $script:resultDetail = $null - } - - It 'requires a hard-fail SPF record for a parked domain' { - $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 ~all' } - $script:classifications['example.com'] = [pscustomobject]@{ - Classification = 'Parked' - SpfDeniesAll = $false - Reason = 'No sending or receiving signals were found.' - } - - Test-MtCisSpfRecordsPublished | Should -BeFalse - $script:resultDetail.Result | Should -Match 'parked/non-sending audit requires an SPF record' - } - - It 'accepts a hard-fail SPF record for a parked domain' { - $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 -all' } - $script:classifications['example.com'] = [pscustomobject]@{ - Classification = 'Parked' - SpfDeniesAll = $true - Reason = 'No sending or receiving signals were found.' - } - - Test-MtCisSpfRecordsPublished | Should -BeTrue - $script:resultDetail.Investigate | Should -BeFalse - } - - It 'keeps the soft-fail rule for sending domains' { - $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 include:spf.example.net ~all' } - $script:classifications['example.com'] = [pscustomobject]@{ - Classification = 'Sending' - SpfDeniesAll = $false - Reason = 'An SPF sending mechanism was found.' - } - - Test-MtCisSpfRecordsPublished | Should -BeTrue - $script:resultDetail.Investigate | Should -BeFalse - } - - It 'investigates when a soft-fail record passes only the sending-domain rule' { - $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 ~all' } - $script:classifications['example.com'] = [pscustomobject]@{ - Classification = 'Unknown' - SpfDeniesAll = $false - Reason = 'Mail use is inconclusive.' - } - - Test-MtCisSpfRecordsPublished | Should -BeTrue - $script:resultDetail.Investigate | Should -BeTrue - } - - It 'investigates an indirect all policy when parked status is unknown' { - $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 redirect=_spf.example.net' } - $script:spfResults['_spf.example.net'] = [pscustomobject]@{ record = 'v=spf1 -all' } - $script:classifications['example.com'] = [pscustomobject]@{ - Classification = 'Unknown' - SpfDeniesAll = $false - Reason = 'The SPF redirect target is inconclusive.' - } - - Test-MtCisSpfRecordsPublished | Should -BeTrue - $script:resultDetail.Investigate | Should -BeTrue - } - - It 'applies a parked override but still requires hard fail' { - $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 ~all' } - $script:classifications['example.com'] = [pscustomobject]@{ - Classification = 'Unknown' - SpfDeniesAll = $false - Reason = 'Mail use is inconclusive.' - } - - Test-MtCisSpfRecordsPublished -ParkedDomains 'example.com' | Should -BeFalse - } -} \ No newline at end of file diff --git a/powershell/tests/functions/Test-MtDkim.Tests.ps1 b/powershell/tests/functions/Test-MtDkim.Tests.ps1 index 4b7d8c76e9..53616a393d 100644 --- a/powershell/tests/functions/Test-MtDkim.Tests.ps1 +++ b/powershell/tests/functions/Test-MtDkim.Tests.ps1 @@ -1,4 +1,4 @@ -BeforeAll { +BeforeAll { . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" # Check functions that became native tests are not exported. Use-MtModuleFunction -Name Test-MtCisaDkim, Test-MtCisDkim @@ -12,18 +12,6 @@ Describe 'DKIM checks with no signing configuration' -ForEach @( BeforeEach { Mock -ModuleName Maester Test-MtConnection { return $true } Mock -ModuleName Maester Add-MtTestResultDetail { } - Mock -ModuleName Maester Get-MtCisParkedDomainClassification { - $classification = if ($DomainName -eq 'parked.example') { 'Parked' } else { 'Sending' } - [PSCustomObject]@{ - DomainName = $DomainName - Classification = $classification - IsParked = $classification -eq 'Parked' - SpfRecord = $null - SpfDeniesAll = $false - DkimEvidence = $false - Reason = 'Mock domain classification' - } - } Mock -ModuleName Maester Get-MailAuthenticationRecord { throw 'DNS lookup should not be attempted without a DKIM signing configuration' } @@ -57,8 +45,8 @@ Describe 'DKIM checks with no signing configuration' -ForEach @( InitialDomain = $false IsCoexistenceDomain = $false SendingFromDomainDisabled = $true - ExpectedResultByCommand = @{ - 'Test-MtCisDkim' = $true + ExpectedResultByCommand = @{ + 'Test-MtCisDkim' = $null 'Test-MtCisaDkim' = $null } } @@ -119,48 +107,6 @@ Describe 'DKIM checks with no signing configuration' -ForEach @( } } -Describe 'CIS DKIM domain classification outcomes' { - BeforeEach { - Mock -ModuleName Maester Add-MtTestResultDetail { - $script:detail = [PSCustomObject]@{ Result = $Result; Investigate = [bool]$Investigate; SkippedBecause = $SkippedBecause } - } - Mock -ModuleName Maester Get-MtExo { - if ($Request -eq 'AcceptedDomain') { - return @([PSCustomObject]@{ DomainName = 'unknown.example'; InitialDomain = $false; IsCoexistenceDomain = $false }) - } - return @() - } - Mock -ModuleName Maester Get-MailAuthenticationRecord { throw 'No DKIM lookup should be needed for this classification.' } - } - - It 'investigates domains whose sending use cannot be established' { - Mock -ModuleName Maester Get-MtCisParkedDomainClassification { - [PSCustomObject]@{ Classification = 'Unknown'; IsParked = $false; Reason = 'DNS evidence is incomplete.' } - } - - Test-MtCisDkim | Should -BeTrue - $script:detail.Investigate | Should -BeTrue - } - - It 'fails a parked override when DKIM evidence remains' { - Mock -ModuleName Maester Get-MtCisParkedDomainClassification { - $classification = if ($ParkedDomains -contains $DomainName) { 'Parked' } else { 'Sending' } - [PSCustomObject]@{ Classification = $classification; DkimEvidence = $true; Reason = 'Explicit parked override.' } - } - - Test-MtCisDkim -ParkedDomains 'unknown.example' | Should -BeFalse - } - - It 'marks a non-sending receive domain out of scope for DKIM' { - Mock -ModuleName Maester Get-MtCisParkedDomainClassification { - [PSCustomObject]@{ Classification = 'NotSending'; IsParked = $false; Reason = 'The domain has receive-only DNS records.' } - } - - Test-MtCisDkim | Should -BeNullOrEmpty - $script:detail.SkippedBecause | Should -Be 'NotApplicable' - } -} - Describe 'DKIM checks for coexistence domains with a signing configuration' -ForEach @( @{ CommandName = 'Test-MtCisDkim' } @{ CommandName = 'Test-MtCisaDkim' } diff --git a/tests/cis/Test.CIS.M365.2.1.10.md b/tests/cis/Test.CIS.M365.2.1.10.md index cb9b5c8c01..fdc8ee3cd1 100644 --- a/tests/cis/Test.CIS.M365.2.1.10.md +++ b/tests/cis/Test.CIS.M365.2.1.10.md @@ -1,19 +1,13 @@ -Every accepted domain, including the initial onmicrosoft.com domain, must meet the applicable DMARC audit. Sending domains require a quarantine or reject policy that covers all mail and names addresses for aggregate and forensic reports. Parked or otherwise non-sending domains require a valid DMARC record with `p=reject`. +Every accepted domain, including the initial onmicrosoft.com domain, has a DMARC policy of quarantine or reject that covers all mail and names addresses for aggregate and forensic reports. DMARC tells receiving servers what to do with mail that fails SPF and DKIM alignment, and sends you reports about who is sending mail in your name. With a policy of none, spoofed mail is still delivered. Quarantine or reject stops it, and the reports show abuse and legitimate senders that you forgot. -The test uses the record at the domain, or at its organisational domain (for example contoso.com for mail.contoso.com) when the domain has no valid record, including a malformed record, applying the subdomain policy where one exists. For sending domains, the policy must apply to 100 percent of mail (no pct tag, or pct=100), and both rua and ruf addresses must be mailto addresses. - -Maester identifies a likely non-sending domain when it finds one SPF v1 record with only a non-authorizing `-all`, `~all`, or `?all` mechanism, no Exchange DKIM signing configuration, and no selector1 or selector2 DKIM CNAME/TXT record. It classifies the domain as parked only when those signals are also accompanied by no usable MX route (or a null MX) and no A, AAAA, or CNAME record at the domain apex. This conservative DNS assessment does not use `AcceptedDomain.SendingFromDomainDisabled`. - -Parked or non-sending domains use the CIS parked-domain requirement: a valid DMARC record with `p=reject`; rua, ruf, and pct are not required for this branch. Missing SPF, conflicting signals, DNS errors, and unresolved redirect-only SPF policies do not receive the parked exception. When only one of the sending and non-sending audit procedures passes, the result requires investigation. Selector discovery is limited to the standard Exchange Online selectors, so nonstandard DKIM selector names cannot be ruled out automatically. - -When DNS evidence is inconclusive but a domain is known to be parked, add its name to this test's `ParkedDomains` parameter in `TestSettings[].Parameters`. This selects the parked audit branch; it does not waive the requirement for a valid DMARC record with `p=reject`. +The test uses the record at the domain, or at its organisational domain (for example contoso.com for mail.contoso.com) when the domain has no valid record, including a malformed record, applying the subdomain policy where one exists. The policy must apply to 100 percent of mail (no pct tag, or pct=100). Both rua and ruf addresses must be mailto addresses. Move to enforcement in steps and review the aggregate reports first. #### Remediation action 1. Open the DNS zone of each custom domain at your DNS host. For the initial `*.onmicrosoft.com` domain, use the Microsoft 365 admin center instead: go to **Settings** > **Domains**, select the `*.onmicrosoft.com` domain, open the **DNS records** tab and select **Add record**. -2. Create or edit the TXT record `_dmarc.` (in the admin center, the host name is `_dmarc`). For a sending domain, use a value such as `v=DMARC1; p=reject; pct=100; rua=mailto:dmarc-reports@; ruf=mailto:dmarc-forensic@`. For a parked or non-sending domain, `v=DMARC1; p=reject` meets the parked-domain requirement. +2. Create or edit the TXT record `_dmarc.` (in the admin center, the host name is `_dmarc`) with a value such as `v=DMARC1; p=reject; pct=100; rua=mailto:dmarc-reports@; ruf=mailto:dmarc-forensic@`. 3. Start with `p=none` or `p=quarantine` if you are not sure that all your senders are aligned, review the reports and then move to `p=reject`. 4. Check the record with `Resolve-DnsName -Name _dmarc. -Type TXT`. diff --git a/tests/cis/Test.CIS.M365.2.1.10.ps1 b/tests/cis/Test.CIS.M365.2.1.10.ps1 index 4eadd65900..73944087cd 100644 --- a/tests/cis/Test.CIS.M365.2.1.10.ps1 +++ b/tests/cis/Test.CIS.M365.2.1.10.ps1 @@ -1,16 +1,16 @@ function Test-MtCisDmarcRecordsPublished { <# .SYNOPSIS - Checks the applicable CIS DMARC requirement for each accepted domain. + Checks that every accepted domain has a DMARC policy of quarantine or reject with aggregate and forensic reporting. .DESCRIPTION - Looks up the DMARC record that applies to each accepted domain, falling back to the organisational domain when the domain has no valid record, including a malformed record. Sending domains require quarantine or reject, 100 percent coverage, and mailto aggregate (rua) and forensic (ruf) report addresses. Parked or otherwise non-sending domains require a valid record with p=reject. Ambiguous domain-use evidence is reported for investigation when the two procedures produce different results. + Looks up the DMARC record that applies to each accepted domain, falling back to the organisational domain when the domain has no valid record, including a malformed record. Passes when the applied policy is quarantine or reject, covers 100 percent of mail and defines mailto addresses for aggregate (rua) and forensic (ruf) reports. CIS Microsoft 365 Foundations Benchmark v7.0.0 (2.1.10, L1) .EXAMPLE Test-MtCisDmarcRecordsPublished - Returns true if all accepted domains meet the applicable CIS DMARC requirement. + Returns true if all accepted domains have an enforcing DMARC policy with reporting addresses. .LINK https://maester.dev/docs/tests/CIS.M365.2.1.10 @@ -32,18 +32,13 @@ )] [CmdletBinding()] [OutputType([bool])] - param( - # Domains explicitly confirmed as parked; the parked DMARC audit still applies. - [string[]]$ParkedDomains = @() - ) + param() Write-Verbose 'Getting accepted domains...' $domains = @(Get-MtExo -Request AcceptedDomain | Where-Object { $_.IsCoExistenceDomain -eq $false }) - $dkimSigningConfigs = @(Get-MtExo -Request DkimSigningConfig) $report = foreach ($domain in $domains) { $name = $domain.DomainName - $classification = Get-MtCisParkedDomainClassification -DomainName $name -DkimSigningConfigs $dkimSigningConfigs -ParkedDomains $ParkedDomains $dmarc = $null $source = $null $unavailable = $false @@ -64,81 +59,45 @@ } } if ($unavailable) { - [pscustomobject]@{ Domain = $name; Classification = $classification.Classification; Policy = 'Not checked'; Source = 'None'; Failed = 'DNS lookup not available'; Pass = $null; Investigate = $false } + [pscustomobject]@{ Domain = $name; Policy = 'Not checked'; Source = 'None'; Failed = 'DNS lookup not available'; Pass = $null } continue } $policy = $null if ($dmarc) { $policy = if ($source -ne $name -and $dmarc.policySubdomain) { $dmarc.policySubdomain } else { $dmarc.policy } } - $sendingChecks = [ordered]@{ + $checks = [ordered]@{ 'Record is valid' = $null -ne $dmarc -and $dmarc.valid 'Policy is quarantine or reject' = $policy -in @('quarantine', 'reject') 'Applies to 100 percent' = $null -eq $dmarc -or $dmarc.percentage -eq 100 -or $null -eq $dmarc.percentage 'Aggregate reports (rua)' = @($dmarc.reportAggregate | Where-Object { $_.mailAddress }).Count -gt 0 'Forensic reports (ruf)' = @($dmarc.reportForensic | Where-Object { $_.mailAddress }).Count -gt 0 } - $nonSendingChecks = [ordered]@{ - 'Record is valid' = $null -ne $dmarc -and $dmarc.valid - 'Parked-domain policy is reject' = $policy -eq 'reject' - } - $sendingFailures = @($sendingChecks.GetEnumerator() | Where-Object { -not $_.Value } | ForEach-Object { $_.Key }) - $nonSendingFailures = @($nonSendingChecks.GetEnumerator() | Where-Object { -not $_.Value } | ForEach-Object { $_.Key }) - $failedChecks = @() - $investigate = $false - if ($classification.Classification -in @('Parked', 'NotSending')) { - $failedChecks = $nonSendingFailures - $pass = $failedChecks.Count -eq 0 - } elseif ($classification.Classification -eq 'Unknown') { - if ($sendingFailures.Count -eq 0 -and $nonSendingFailures.Count -eq 0) { - $pass = $true - } elseif ($sendingFailures.Count -eq 0 -or $nonSendingFailures.Count -eq 0) { - $pass = $true - $investigate = $true - $failedChecks = if ($sendingFailures.Count -eq 0) { - @("If parked or non-sending: $($nonSendingFailures -join ', ')") - } else { - @("If sending: $($sendingFailures -join ', ')") - } - } else { - $pass = $false - $failedChecks = @( - @($sendingFailures | ForEach-Object { "If sending: $_" }) + - @($nonSendingFailures | ForEach-Object { "If parked or non-sending: $_" }) - ) - } - } else { - $failedChecks = $sendingFailures - $pass = $failedChecks.Count -eq 0 - } + $failedChecks = @($checks.GetEnumerator() | Where-Object { -not $_.Value } | ForEach-Object { $_.Key }) [pscustomobject]@{ - Domain = $name - Classification = $classification.Classification - Policy = if ($policy) { $policy } elseif ($invalidCandidate) { 'Invalid DMARC record' } else { 'No valid record' } - Source = if ($source) { $source } elseif ($invalidCandidate) { $invalidCandidate } else { 'None' } - Failed = $failedChecks -join ', ' - Pass = $pass - Investigate = $investigate + Domain = $name + Policy = if ($policy) { $policy } elseif ($invalidCandidate) { 'Invalid DMARC record' } else { 'No valid record' } + Source = if ($source) { $source } elseif ($invalidCandidate) { $invalidCandidate } else { 'None' } + Failed = $failedChecks -join ', ' + Pass = $failedChecks.Count -eq 0 } } $checked = @($report | Where-Object { $null -ne $_.Pass }) - $unchecked = @($report | Where-Object { $null -eq $_.Pass -and -not $_.Investigate }) + $unchecked = @($report | Where-Object { $null -eq $_.Pass }) $failed = @($checked | Where-Object { -not $_.Pass }) - $investigated = @($report | Where-Object { $_.Investigate }) if ($failed.Count -eq 0 -and $unchecked.Count -gt 0) { Add-MtTestResultDetail -SkippedBecause NotSupported return $null } $testResult = $failed.Count -eq 0 - $passText = 'All accepted domains meet the applicable CIS DMARC requirement.' + $passText = 'All accepted domains have an enforcing DMARC policy with reporting addresses.' $failText = "$($failed.Count) domain(s) do not have a compliant DMARC policy." - $resultMd = "| Domain | Classification | Applied policy | Record found at | Failed checks | Result |`n" - $resultMd += "| --- | --- | --- | --- | --- | --- |`n" + $resultMd = "| Domain | Applied policy | Record found at | Failed checks | Result |`n" + $resultMd += "| --- | --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultText = if ($null -eq $row.Pass -and $row.Investigate) { 'Investigate' } elseif ($null -eq $row.Pass) { 'Not checked' } elseif ($row.Pass) { '✅ Pass' } else { '❌ Fail' } - $resultMd += "| $($row.Domain) | $($row.Classification) | $($row.Policy) | $($row.Source) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $resultText |`n" + $resultMd += "| $($row.Domain) | $($row.Policy) | $($row.Source) | $(if ($row.Failed) { $row.Failed } else { 'None' }) | $(if ($null -eq $row.Pass) { 'Not checked' } elseif ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { @@ -148,6 +107,6 @@ } $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $resultMd - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate:($investigated.Count -gt 0 -and $failed.Count -eq 0) + Add-MtTestResultDetail -Result $testResultMarkdown return $testResult } diff --git a/tests/cis/Test.CIS.M365.2.1.8.md b/tests/cis/Test.CIS.M365.2.1.8.md index 938c762be1..75444fa9fd 100644 --- a/tests/cis/Test.CIS.M365.2.1.8.md +++ b/tests/cis/Test.CIS.M365.2.1.8.md @@ -1,19 +1,13 @@ -Sending domains must publish an SPF record that ends in a hard fail (-all) or soft fail (~all). Parked or otherwise non-sending domains must publish an SPF policy that denies all senders with -all. +Every custom domain that is accepted by Exchange Online publishes an SPF record that ends in a hard fail (-all) or soft fail (~all). SPF lists the servers that may send mail for a domain. Receiving servers use it to reject, or to mark as suspicious, mail that pretends to come from your domain. Without an SPF record, or with one that ends in a neutral or permissive qualifier, anyone can send mail that looks like it comes from you without raising a flag. -Maester identifies a likely non-sending domain when it finds one SPF v1 record with no sender-authorizing mechanism, no Exchange DKIM signing configuration, and no selector1 or selector2 DKIM CNAME/TXT record. It classifies the domain as parked only when those signals are also accompanied by no usable MX route (or a null MX) and no A, AAAA, or CNAME record at the domain apex. This conservative DNS assessment does not use `AcceptedDomain.SendingFromDomainDisabled`. - -For a parked or non-sending domain, the SPF record must explicitly use `-all`; a `~all` policy does not meet the parked-domain audit. For sending domains, the test follows a redirect modifier only when the record has no all mechanism, since receivers ignore the redirect in that case. Domains in the onmicrosoft.com namespace are skipped. - -Missing SPF, conflicting signals, DNS errors, and unresolved redirect-only policies do not receive the parked exception. When the record passes the sending-domain rule but could fail the parked-domain rule, the result requires investigation. Selector discovery is limited to the standard Exchange Online selectors, so nonstandard DKIM selector names cannot be ruled out automatically. - -When DNS evidence is inconclusive but a domain is known to be parked, add its name to this test's `ParkedDomains` parameter in `TestSettings[].Parameters`. This selects the parked audit branch; it does not waive the requirement to publish `v=spf1 -all`. +The test follows a redirect modifier only when the record has no all mechanism, since receivers ignore the redirect in that case. Domains in the onmicrosoft.com namespace are skipped. Parked domains that never send mail should publish a record of "v=spf1 -all". #### Remediation action 1. Open the DNS zone of each custom domain at your DNS host. -2. Create or edit the TXT record at the domain root. For a sending domain, list its sending services and end with `-all` or `~all`; for a parked or non-sending domain, publish `v=spf1 -all`. For Exchange Online only, use `v=spf1 include:spf.protection.outlook.com -all`. +2. Create or edit the TXT record at the domain root so that it lists your sending services and ends with `-all` (or `~all`). For Exchange Online only, use `v=spf1 include:spf.protection.outlook.com -all`. 3. Wait for the change to propagate and check the record with `Resolve-DnsName -Name -Type TXT`. #### Related links diff --git a/tests/cis/Test.CIS.M365.2.1.8.ps1 b/tests/cis/Test.CIS.M365.2.1.8.ps1 index 3980d6d9b1..4909a0d6f2 100644 --- a/tests/cis/Test.CIS.M365.2.1.8.ps1 +++ b/tests/cis/Test.CIS.M365.2.1.8.ps1 @@ -1,16 +1,16 @@ function Test-MtCisSpfRecordsPublished { <# .SYNOPSIS - Checks the applicable CIS SPF requirement for each custom accepted domain. + Checks that every custom accepted domain publishes an SPF record that ends in -all or ~all. .DESCRIPTION - Sending domains must publish an SPF record that ends with -all or ~all, directly or through a redirect. Parked or otherwise non-sending domains must publish an SPF policy that denies all senders with -all. Domains in the onmicrosoft.com namespace are excluded because Microsoft manages their SPF. Ambiguous domain-use evidence is reported for investigation rather than receiving the parked-domain exception. + Looks up the SPF record of each custom accepted domain and passes when a record exists and ends with a hard fail or soft fail, either directly or through a redirect. Domains in the onmicrosoft.com namespace are excluded because Microsoft manages their SPF. CIS Microsoft 365 Foundations Benchmark v7.0.0 (2.1.8, L1) .EXAMPLE Test-MtCisSpfRecordsPublished - Returns true if all custom domains meet the applicable CIS SPF requirement. + Returns true if all custom domains publish an SPF record that ends in -all or ~all. .LINK https://maester.dev/docs/tests/CIS.M365.2.1.8 @@ -32,25 +32,20 @@ )] [CmdletBinding()] [OutputType([bool])] - param( - # Domains explicitly confirmed as parked; the parked SPF audit still applies. - [string[]]$ParkedDomains = @() - ) + param() Write-Verbose 'Getting accepted domains...' $domains = @(Get-MtExo -Request AcceptedDomain | Where-Object { $_.InitialDomain -eq $false -and $_.IsCoExistenceDomain -eq $false }) - $dkimSigningConfigs = @(Get-MtExo -Request DkimSigningConfig) $report = foreach ($domain in $domains) { $name = $domain.DomainName - $classification = Get-MtCisParkedDomainClassification -DomainName $name -DkimSigningConfigs $dkimSigningConfigs -ParkedDomains $ParkedDomains $detail = '' $spf = ConvertFrom-MailAuthenticationRecordSpf -DomainName $name if ($spf -is [string] -and ($spf -like '*not available' -or $spf -eq 'DNS lookup unavailable')) { - [pscustomobject]@{ Domain = $name; Record = $null; Classification = $classification.Classification; Pass = $null; Investigate = $false; Detail = 'DNS lookup not available' } + [pscustomobject]@{ Domain = $name; Record = $null; Pass = $null; Detail = 'DNS lookup not available' } continue } - $record = if ($spf -and $spf.PSObject.Properties['record']) { $spf.record } else { $null } + $record = if ($spf.GetType().Name -eq 'SPFRecord') { $spf.record } else { $null } $effective = $record $redirectTargets = @() $redirectError = $null @@ -82,7 +77,8 @@ $redirectUnavailable = $true break } - $effective = if ($null -ne $redirected -and $redirected.PSObject.Properties['record']) { $redirected.record } else { $null } + $redirectedType = if ($null -ne $redirected) { $redirected.GetType().Name } else { $null } + $effective = if ($redirectedType -eq 'SPFRecord') { $redirected.record } else { $null } if (-not $effective) { $redirectError = "No SPF record was found at redirect target $target." break @@ -90,13 +86,11 @@ } if ($redirectUnavailable) { - [pscustomobject]@{ Domain = $name; Record = $record; Classification = $classification.Classification; Pass = $null; Investigate = $false; Detail = "DNS lookup not available for $($redirectTargets[-1])" } + [pscustomobject]@{ Domain = $name; Record = $record; Pass = $null; Detail = "DNS lookup not available for $($redirectTargets[-1])" } continue } $effectiveAll = [regex]::Match([string]$effective, '(?i)(^|\s)(?[+?~-]?)all(\s|$)') - $sendingDomainPass = $effectiveAll.Success -and $effectiveAll.Groups['q'].Value -in '-', '~' - $pass = $sendingDomainPass - $investigate = $false + $pass = $effectiveAll.Success -and $effectiveAll.Groups['q'].Value -in '-', '~' if (-not $record) { $detail = 'No SPF record found' } elseif ($redirectError) { @@ -109,49 +103,27 @@ elseif (-not $pass) { $detail = 'The record does not end with -all or ~all' } - - if ($classification.Classification -in @('Parked', 'NotSending')) { - $pass = $classification.SpfDeniesAll - $detail = if ($pass) { - 'The parked/non-sending audit requires an SPF record that explicitly denies all senders; this record uses -all.' - } else { - 'The parked/non-sending audit requires an SPF record that explicitly denies all senders with -all.' - } - } elseif ($classification.Classification -eq 'Unknown' -and $sendingDomainPass -and -not $classification.SpfDeniesAll) { - $pass = $null - $investigate = $true - $detail = 'The sending-domain SPF audit passes, but the available evidence cannot rule out the parked-domain requirement for -all.' - } elseif ($classification.Classification -eq 'Unknown' -and $sendingDomainPass) { - $pass = $true - $detail = 'The record meets both the sending-domain and parked-domain SPF requirements.' - } - - $detail = "$($classification.Reason) $detail" - [pscustomobject]@{ Domain = $name; Record = $record; Classification = $classification.Classification; Pass = $pass; Investigate = $investigate; Detail = $detail } + [pscustomobject]@{ Domain = $name; Record = $record; Pass = $pass; Detail = $detail } } - $unchecked = @($report | Where-Object { $null -eq $_.Pass -and -not $_.Investigate }) + $unchecked = @($report | Where-Object { $null -eq $_.Pass }) $failed = @($report | Where-Object { $_.Pass -eq $false }) - $investigated = @($report | Where-Object { $_.Investigate }) if ($failed.Count -gt 0) { $testResult = $false } elseif ($unchecked.Count -gt 0) { Add-MtTestResultDetail -SkippedBecause NotSupported return $null - } elseif ($investigated.Count -gt 0) { - $testResult = $true } else { $testResult = $true } - $passText = if ($domains.Count -eq 0) { 'There are no custom domains, so no SPF records are required.' } else { 'All custom domains meet the applicable CIS SPF requirement.' } - $failText = "$($failed.Count) custom domain(s) do not meet the applicable CIS SPF requirement." + $passText = if ($domains.Count -eq 0) { 'There are no custom domains, so no SPF records are required.' } else { 'All custom domains publish an SPF record that ends in -all or ~all.' } + $failText = "$($failed.Count) custom domain(s) do not publish a compliant SPF record." - $resultMd = "| Domain | Classification | SPF record | Detail | Result |`n" - $resultMd += "| --- | --- | --- | --- | --- |`n" + $resultMd = "| Domain | SPF record | Detail | Result |`n" + $resultMd += "| --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultText = if ($null -eq $row.Pass -and $row.Investigate) { 'Investigate' } elseif ($null -eq $row.Pass) { 'Not checked' } elseif ($row.Pass) { '✅ Pass' } else { '❌ Fail' } - $resultMd += "| $($row.Domain) | $($row.Classification) | $($row.Record) | $($row.Detail) | $resultText |`n" + $resultMd += "| $($row.Domain) | $($row.Record) | $($row.Detail) | $(if ($null -eq $row.Pass) { 'Not checked' } elseif ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { @@ -162,6 +134,6 @@ } $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $resultMd - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate:($investigated.Count -gt 0 -and $failed.Count -eq 0) + Add-MtTestResultDetail -Result $testResultMarkdown return $testResult } diff --git a/tests/cis/Test.CIS.M365.2.1.9.md b/tests/cis/Test.CIS.M365.2.1.9.md index d91c1ee688..e7434e811a 100644 --- a/tests/cis/Test.CIS.M365.2.1.9.md +++ b/tests/cis/Test.CIS.M365.2.1.9.md @@ -12,13 +12,7 @@ There should be no impact of setting up DKIM however, organizations should ensur >Note: Initial (MOERA, e.g. `contoso.onmicrosoft.com`) and coexistence (`*.mail.onmicrosoft.com`) domains are excluded from this check, as Microsoft automatically signs outbound mail for those domains. -For domains classified as sending, the check requires Exchange DKIM to be enabled and its status to be **Valid**. A likely sending domain has an SPF sender-authorizing mechanism, an Exchange DKIM signing configuration, or a selector1/selector2 DKIM CNAME/TXT record. - -Maester classifies a domain as not sending when its single SPF v1 record has only a non-authorizing `-all`, `~all`, or `?all` mechanism and no Exchange DKIM signing configuration or selector1/selector2 records are found. It is classified as parked only when it also has no usable MX route (or a null MX) and no A, AAAA, or CNAME record at the domain apex. This classification does not use `AcceptedDomain.SendingFromDomainDisabled`. - -For a confirmed parked domain, CIS requires that DKIM records are not published; the check passes only when no Exchange DKIM configuration or standard selector1/selector2 records are found. A domain with no sending signals but with receiving or other apex DNS records is outside the sending-domain audit scope. Domains with missing or conflicting evidence, or failed DNS lookups, are marked for investigation rather than automatically treated as parked. Selector discovery is limited to the standard Exchange Online selectors, so nonstandard DKIM selector names cannot be ruled out automatically. - -When DNS evidence is inconclusive but a domain is known to be parked, add its name to this test's `ParkedDomains` parameter in `TestSettings[].Parameters`. This selects the parked audit branch; any detected Exchange DKIM configuration or standard selector record still fails the check. +For each sending domain, the check requires Exchange DKIM to be enabled and its status to be **Valid**. #### Remediation action @@ -52,8 +46,6 @@ The initial domain is the domain that you used when you signed up for Office 365 5. Select **DKIM** 6. Click on each domain and click **Enable** next to **Sign messages for this domain with DKIM signature**. -For a confirmed parked domain, do not create an Exchange DKIM signing configuration or publish selector records. Before removing existing records, confirm the domain is not used to send email through Exchange Online or another service. - Final remediation step using the Exchange Online PowerShell Module: 1. Connect to Exchange Online service using `Connect-ExchangeOnline`. diff --git a/tests/cis/Test.CIS.M365.2.1.9.ps1 b/tests/cis/Test.CIS.M365.2.1.9.ps1 index d645d0bd3b..9a427ac2a3 100644 --- a/tests/cis/Test.CIS.M365.2.1.9.ps1 +++ b/tests/cis/Test.CIS.M365.2.1.9.ps1 @@ -1,16 +1,17 @@ function Test-MtCisDkim { <# .SYNOPSIS - Checks DKIM for domains that send email and verifies parked domains have no DKIM records. + Checks state of DKIM for all EXO domains .DESCRIPTION - Sending domains require DKIM to be enabled with a valid Exchange status. Parked domains must not publish DKIM records. Initial (MOERA) and coexistence domains are excluded, as Microsoft automatically signs outbound mail for those domains. Ambiguous domain-use evidence is reported for investigation. + DKIM should be enabled with a valid Exchange status for all sending domains. Initial (MOERA) and coexistence domains are excluded, as Microsoft automatically signs outbound mail for those domains. CIS Microsoft 365 Foundations Benchmark v7.0.0 (2.1.9, L1) .EXAMPLE Test-MtCisDkim - Returns true if every sending domain has DKIM enabled with Exchange status Valid and every parked domain has no known Exchange selector records. Initial and coexistence domains are excluded. Domains classified as not sending are out of scope; ambiguous domains require investigation. + Returns true if every evaluated domain has a DKIM record, DKIM enabled in Exchange, and Exchange status Valid. + Initial, coexistence, and Exchange sending-disabled domains are excluded; if no domains remain, the test is skipped. .LINK https://maester.dev/docs/commands/Test-MtCisDkim @@ -36,21 +37,22 @@ [OutputType([bool])] param( # Selector-name for the DKIM record to test.. - [string]$Selector = 'selector1', - - # Domains explicitly confirmed as parked; any detected DKIM configuration or selector still fails the audit. - [string[]]$ParkedDomains = @() + [string]$Selector = 'selector1' ) $dkimSigningConfigs = Get-MtExo -Request DkimSigningConfig $acceptedDomains = Get-MtExo -Request AcceptedDomain + <# DKIM record without key for parked domains + $sendingDomains = $acceptedDomains | Where-Object { + -not $_.SendingFromDomainDisabled + } + #> $dkimRecords = @() foreach ($domain in $acceptedDomains) { if ($domain.InitialDomain -eq $true -or $domain.IsCoExistenceDomain -eq $true) { $dkimRecord = [PSCustomObject]@{ domain = $domain.DomainName - classification = 'Excluded' pass = 'Skipped' reason = 'Initial or coexistence domain excluded from DKIM audit (Microsoft auto-signs outbound mail for this domain)' exchangeStatus = 'Excluded' @@ -60,44 +62,6 @@ continue } - $classification = Get-MtCisParkedDomainClassification -DomainName $domain.DomainName -DkimSigningConfigs $dkimSigningConfigs -ParkedDomains $ParkedDomains - if ($classification.Classification -eq 'Parked') { - $hasDkimEvidence = $classification.DkimEvidence - $dkimRecords += [PSCustomObject]@{ - domain = $domain.DomainName - classification = $classification.Classification - pass = if ($hasDkimEvidence) { 'Failed' } else { 'Passed' } - reason = if ($hasDkimEvidence) { "Parked domain has a DKIM configuration or known selector record that must be removed. $($classification.Reason)" } else { "Parked domain has no known DKIM selector records. $($classification.Reason)" } - exchangeStatus = 'Not applicable' - dkimRecord = $null - } - continue - } - - if ($classification.Classification -eq 'NotSending') { - $dkimRecords += [PSCustomObject]@{ - domain = $domain.DomainName - classification = $classification.Classification - pass = 'Skipped' - reason = "The CIS DKIM audit applies to domains configured to send email. $($classification.Reason)" - exchangeStatus = 'Not applicable' - dkimRecord = $null - } - continue - } - - if ($classification.Classification -eq 'Unknown') { - $dkimRecords += [PSCustomObject]@{ - domain = $domain.DomainName - classification = $classification.Classification - pass = 'Investigate' - reason = "Sending use could not be established; the domain was not classified as parked. $($classification.Reason)" - exchangeStatus = 'Not determined' - dkimRecord = $null - } - continue - } - $dkimSigningConfig = $dkimSigningConfigs | Where-Object { $_.domain -eq $domain.domainname } @@ -105,9 +69,8 @@ if (-not $dkimSigningConfig) { $dkimRecord = [PSCustomObject]@{ domain = $domain.DomainName - classification = $classification.Classification - pass = 'Failed' - reason = 'No DkimSigningConfig found for a domain classified as sending' + pass = if ($domain.SendingFromDomainDisabled) { 'Skipped' } else { 'Failed' } + reason = if ($domain.SendingFromDomainDisabled) { 'Parked domain' } else { 'No DkimSigningConfig found for domain' } exchangeStatus = 'Not configured' dkimRecord = $null } @@ -140,9 +103,11 @@ $dkimRecord | Add-Member -MemberType NoteProperty -Name 'pass' -Value 'Failed' $dkimRecord | Add-Member -MemberType NoteProperty -Name 'reason' -Value '' $dkimRecord | Add-Member -MemberType NoteProperty -Name 'exchangeStatus' -Value $dkimSigningConfig.Status - $dkimRecord | Add-Member -MemberType NoteProperty -Name 'classification' -Value $classification.Classification - if (-not $dkimSigningConfig.enabled) { + if ($domain.SendingFromDomainDisabled) { + $dkimRecord.pass = 'Skipped' + $dkimRecord.reason = 'Parked domain' + } elseif (-not $dkimSigningConfig.enabled) { $dkimRecord.pass = 'Failed' $dkimRecord.reason = 'DKIM is disabled' } elseif ($dkimSigningConfig.Status -ne 'Valid') { @@ -168,10 +133,8 @@ if ('Failed' -in $dkimRecords.pass) { $testResult = $false - } elseif ('Investigate' -in $dkimRecords.pass) { - $testResult = $true - } elseif ('Passed' -notin $dkimRecords.pass) { - Add-MtTestResultDetail -SkippedBecause NotApplicable + } elseif ('Failed' -notin $dkimRecords.pass -and 'Passed' -notin $dkimRecords.pass) { + Add-MtTestResultDetail -SkippedBecause NotSupported return $null } else { $testResult = $true @@ -180,7 +143,7 @@ if ('Failed' -in $dkimRecords.pass) { $portalLink = 'https://security.microsoft.com/authentication?viewid=DKIM' if ($testResult) { - $testResultMarkdown = "Well done. Sending domains have DKIM configured and valid records exist, and parked domains have no known Exchange selector records.`n`n%TestResult%" + $testResultMarkdown = "Well done. Your tenant's domains have DKIM configured and valid records exist.`n`n%TestResult%" } else { $testResultMarkdown = "Your tenant's domains do not have DKIM fully deployed. Review [EXO configuration]($portalLink) and DNS records.`n`n%TestResult%" } @@ -188,20 +151,19 @@ if ('Failed' -in $dkimRecords.pass) { $passResult = '✅ Pass' $failResult = '❌ Fail' $skipResult = '🗄️ Skip' - $result = "| Domain | Classification | Result | Exchange status | Reason |`n" - $result += "| --- | --- | --- | --- | --- |`n" + $result = "| Domain | Result | Exchange status | Reason |`n" + $result += "| --- | --- | --- | --- |`n" foreach ($item in $dkimRecords | Sort-Object -Property domain) { switch ($item.pass) { 'Passed' { $itemResult = $passResult } 'Skipped' { $itemResult = $skipResult } 'Failed' { $itemResult = $failResult } - 'Investigate' { $itemResult = '🔎 Investigate' } } - $result += "| $($item.domain) | $($item.classification) | $($itemResult) | $($item.exchangeStatus) | $($item.reason) |`n" + $result += "| $($item.domain) | $($itemResult) | $($item.exchangeStatus) | $($item.reason) |`n" } $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result - Add-MtTestResultDetail -Result $testResultMarkdown -Investigate:('Investigate' -in $dkimRecords.pass -and 'Failed' -notin $dkimRecords.pass) + Add-MtTestResultDetail -Result $testResultMarkdown return $testResult } From 5945ac5d42e76751105c331113752d8c2e59fc5a Mon Sep 17 00:00:00 2001 From: Jeremy Finney Date: Thu, 5 Nov 2026 09:44:36 +1300 Subject: [PATCH 09/15] test: cover CIS third-party storage edge cases --- .../functions/Test-MtCisTeamsChecks.Tests.ps1 | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 b/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 index 20091bc405..fca73b4fe9 100644 --- a/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 @@ -123,10 +123,28 @@ Describe 'Test-MtCisThirdPartyFileSharing' { Test-MtCisThirdPartyFileSharing -ApprovedProviders Box | Should -BeTrue } + It 'fails when approved and unapproved providers are both on' { + $script:Config.AllowDropBox = $true + $script:Config.AllowBox = $true + Test-MtCisThirdPartyFileSharing -ApprovedProviders Box | Should -BeFalse + } + It 'fails when the client configuration is not returned' { $script:Config = $null Test-MtCisThirdPartyFileSharing | Should -BeFalse } + + It 'fails when a provider setting is missing' { + $script:Config = [pscustomobject]@{ + AllowDropBox = $false + AllowBox = $false + AllowGoogleDrive = $false + AllowShareFile = $false + } + + Test-MtCisThirdPartyFileSharing | Should -BeFalse + $script:Result | Should -Match 'AllowEgnyte \| Not found \| No \| .*Fail' + } } Describe 'Test-MtCisThirdPartyAndCustomApps' { From afb258f635b8925d4511e5ef6bd475f9af8b7ae5 Mon Sep 17 00:00:00 2001 From: Jeremy Finney Date: Mon, 9 Nov 2026 06:34:17 +1300 Subject: [PATCH 10/15] fix(cis): align checks with audit procedures Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../public/services/exchange/Get-MtExo.ps1 | 1 - ...isStrictPresetForPriorityAccount.Tests.ps1 | 86 ++++-------- .../functions/Test-MtCisTeamsChecks.Tests.ps1 | 22 ++- tests/cis/Test.CIS.M365.2.4.2.md | 2 +- tests/cis/Test.CIS.M365.2.4.2.ps1 | 129 +++--------------- tests/cis/Test.CIS.M365.8.6.1.md | 5 +- tests/cis/Test.CIS.M365.8.6.1.ps1 | 21 +-- 7 files changed, 63 insertions(+), 203 deletions(-) diff --git a/powershell/public/services/exchange/Get-MtExo.ps1 b/powershell/public/services/exchange/Get-MtExo.ps1 index 1baf1534e8..6ec1f01677 100644 --- a/powershell/public/services/exchange/Get-MtExo.ps1 +++ b/powershell/public/services/exchange/Get-MtExo.ps1 @@ -62,7 +62,6 @@ "TeamsProtectionPolicy" = "Get-TeamsProtectionPolicy" "TeamsProtectionPolicyRule" = "Get-TeamsProtectionPolicyRule" "ReportSubmissionPolicy" = "Get-ReportSubmissionPolicy" - "ReportSubmissionRule" = "Get-ReportSubmissionRule" "EXOMailbox" = "Get-EXOMailbox -ResultSize 'Unlimited'" "EXOSharedMailbox" = "Get-EXOMailbox -RecipientTypeDetails 'SharedMailbox' -ResultSize 'Unlimited'" "ArcConfig" = "Get-ArcConfig" diff --git a/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 b/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 index c80ac3ab42..545e40d000 100644 --- a/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 @@ -3,16 +3,6 @@ . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" Use-MtModuleFunction -Name Test-MtCisStrictPresetForPriorityAccount - # ExchangeOnlineManagement is optional; a stub lets Get-Recipient be mocked when it is not installed. - if (-not (Get-Command Get-Recipient -ErrorAction SilentlyContinue)) { - function global:Get-Recipient { - [CmdletBinding()] - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', 'Identity', Justification = 'Stub signature only; Mock binds -Identity from it.')] - param([string] $Identity) - } - $script:removeRecipientStub = $true - } - function Get-StrictRuleFixture { param([hashtable] $Conditions = @{}) $rule = [ordered]@{ @@ -21,94 +11,66 @@ SentTo = $null SentToMemberOf = $null RecipientDomainIs = $null - ExceptIfSentTo = $null - ExceptIfSentToMemberOf = $null - ExceptIfRecipientDomainIs = $null } foreach ($key in $Conditions.Keys) { $rule[$key] = $Conditions[$key] } [pscustomobject]$rule } } -AfterAll { - if ($script:removeRecipientStub) { - Remove-Item -Path Function:\Get-Recipient -ErrorAction SilentlyContinue - } -} - Describe 'Test-MtCisStrictPresetForPriorityAccount' { BeforeEach { $script:Result = $null - $script:Rule = Get-StrictRuleFixture -Conditions @{ SentToMemberOf = @('Priority Accounts') } - $script:VipUsers = @( - [pscustomobject]@{ - Name = 'ceo' - DisplayName = 'Chief Executive' - UserPrincipalName = 'ceo@contoso.com' - WindowsEmailAddress = 'ceo@contoso.com' - ExternalDirectoryObjectId = 'user-ceo' - } - ) - $script:Groups = @{ 'user-ceo' = @([pscustomobject]@{ id = 'group-vip'; displayName = 'Priority Accounts'; mail = 'vips@contoso.com'; mailNickname = 'vips' }) } - + $script:EopRule = Get-StrictRuleFixture -Conditions @{ SentToMemberOf = @('Priority Accounts') } + $script:AtpRule = Get-StrictRuleFixture -Conditions @{ SentToMemberOf = @('Priority Accounts') } Mock -ModuleName Maester Add-MtTestResultDetail { param($Result) $script:Result = $Result } - Mock -ModuleName Maester Get-MtExo -ParameterFilter { $Request -in 'EOPProtectionPolicyRule', 'ATPProtectionPolicyRule' } { $script:Rule } - Mock -ModuleName Maester Get-MtExo -ParameterFilter { $Request -eq 'VipUser' } { $script:VipUsers } - Mock -ModuleName Maester Invoke-MtGraphRequest { - $id = ($RelativeUri -split '/')[1] - $script:Groups[$id] + Mock -ModuleName Maester Get-MtExo -ParameterFilter { $Request -in 'EOPProtectionPolicyRule', 'ATPProtectionPolicyRule' } { + if ($Request -eq 'EOPProtectionPolicyRule') { $script:EopRule } else { $script:AtpRule } } - Mock -ModuleName Maester Get-Recipient { $null } + Mock -ModuleName Maester Invoke-MtGraphRequest { throw 'CIS 2.4.2 does not use Graph.' } } - It 'passes when every priority account is a member of a target group' { + It 'passes when both enabled rules have recipient conditions' { Test-MtCisStrictPresetForPriorityAccount | Should -BeTrue - $script:Result | Should -Match '1 of 1' + $script:Result | Should -Match 'SentToMemberOf' + Should -Invoke Get-MtExo -ModuleName Maester -ParameterFilter { $Request -eq 'EOPProtectionPolicyRule' } -Times 1 -Exactly + Should -Invoke Get-MtExo -ModuleName Maester -ParameterFilter { $Request -eq 'ATPProtectionPolicyRule' } -Times 1 -Exactly } - It 'resolves SentTo values to the Entra object ID of the priority account' { - $script:Rule = Get-StrictRuleFixture -Conditions @{ SentTo = @('Chief Exec Mailbox') } - Mock -ModuleName Maester Get-Recipient { [pscustomobject]@{ ExternalDirectoryObjectId = 'user-ceo' } } -ParameterFilter { $Identity -eq 'Chief Exec Mailbox' } + It 'accepts a SentTo target' { + $script:EopRule = Get-StrictRuleFixture -Conditions @{ SentTo = @('user@contoso.com') } Test-MtCisStrictPresetForPriorityAccount | Should -BeTrue } - It 'includes subdomains of a RecipientDomainIs domain' { - $script:VipUsers[0].WindowsEmailAddress = 'ceo@exec.contoso.com' - $script:Rule = Get-StrictRuleFixture -Conditions @{ RecipientDomainIs = @('contoso.com') } + It 'accepts a RecipientDomainIs target' { + $script:EopRule = Get-StrictRuleFixture -Conditions @{ RecipientDomainIs = @('contoso.com') } Test-MtCisStrictPresetForPriorityAccount | Should -BeTrue } - It 'fails when a priority account matches an exception' { - $script:Rule = Get-StrictRuleFixture -Conditions @{ SentToMemberOf = @('Priority Accounts'); ExceptIfSentTo = @('ceo@contoso.com') } - - Test-MtCisStrictPresetForPriorityAccount | Should -BeFalse - $script:Result | Should -Match 'ceo@contoso.com' - } - - It 'requires a priority account to meet every recipient condition that is set' { - $script:Rule = Get-StrictRuleFixture -Conditions @{ SentTo = @('someone.else@contoso.com'); RecipientDomainIs = @('contoso.com') } - - Test-MtCisStrictPresetForPriorityAccount | Should -BeFalse + It 'does not check account coverage with Graph' { + Test-MtCisStrictPresetForPriorityAccount | Should -BeTrue + Should -Invoke Invoke-MtGraphRequest -ModuleName Maester -Times 0 -Exactly } It 'fails when the rule has no recipient conditions' { - $script:Rule = Get-StrictRuleFixture + $script:EopRule = Get-StrictRuleFixture + $script:EopRule.SentToMemberOf = $null + $script:AtpRule = Get-StrictRuleFixture Test-MtCisStrictPresetForPriorityAccount | Should -BeFalse - $script:Result | Should -Match 'All recipients \(no conditions\)' + $script:Result | Should -Match 'no recipient conditions' } - It 'fails when no priority accounts are tagged' { - $script:VipUsers = @() + It 'fails when a rule is not returned' { + $script:EopRule = $null Test-MtCisStrictPresetForPriorityAccount | Should -BeFalse - $script:Result | Should -Match 'No users are tagged as priority accounts' + $script:Result | Should -Match 'Not found' } It 'fails when a rule is disabled' { - $script:Rule = Get-StrictRuleFixture -Conditions @{ SentToMemberOf = @('Priority Accounts'); State = 'Disabled' } + $script:AtpRule = Get-StrictRuleFixture -Conditions @{ SentToMemberOf = @('Priority Accounts'); State = 'Disabled' } Test-MtCisStrictPresetForPriorityAccount | Should -BeFalse } diff --git a/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 b/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 index fca73b4fe9..73e93eaca7 100644 --- a/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 @@ -9,8 +9,12 @@ if (-not (Get-Command $name -ErrorAction SilentlyContinue)) { Set-Item -Path "function:global:$name" -Value { [CmdletBinding()] - param([string] $Identity) + param( + [string] $Identity, + [string[]] $SettingNames + ) $null = $Identity + $null = $SettingNames } $script:stubs += $name } @@ -214,15 +218,15 @@ Describe 'Test-MtCisTeamsReportSecurityConcerns' { ReportNotJunkAddresses = @('soc@contoso.com') ReportPhishAddresses = @('soc@contoso.com') } - $script:Rules = @([pscustomobject]@{ Name = 'DefaultReportSubmissionRule'; State = 'Enabled'; SentTo = @('soc@contoso.com') }) Mock -ModuleName Maester Add-MtTestResultDetail { param($Result) $script:Result = $Result } Mock -ModuleName Maester Get-CsTeamsMessagingPolicy { $script:MessagingPolicy } Mock -ModuleName Maester Get-MtExo -ParameterFilter { $Request -eq 'ReportSubmissionPolicy' } { $script:Policy } - Mock -ModuleName Maester Get-MtExo -ParameterFilter { $Request -eq 'ReportSubmissionRule' } { $script:Rules } + Mock -ModuleName Maester Get-MtExo -ParameterFilter { $Request -eq 'ReportSubmissionRule' } {} } It 'passes when reports go only to the reporting mailbox' { Test-MtCisTeamsReportSecurityConcerns | Should -BeTrue + Should -Invoke Get-MtExo -ModuleName Maester -ParameterFilter { $Request -eq 'ReportSubmissionRule' } -Times 0 -Exactly } It 'fails when reported messages are also sent to Microsoft' { @@ -231,14 +235,6 @@ Describe 'Test-MtCisTeamsReportSecurityConcerns' { $script:Result | Should -Match 'EnableReportToMicrosoft \| True \| False \| ❌ Fail' } - It 'fails when the report submission rule is missing or disabled' { - $script:Rules = @([pscustomobject]@{ Name = 'DefaultReportSubmissionRule'; State = 'Disabled'; SentTo = @('soc@contoso.com') }) - Test-MtCisTeamsReportSecurityConcerns | Should -BeFalse - - $script:Rules = @() - Test-MtCisTeamsReportSecurityConcerns | Should -BeFalse - } - It 'fails when Teams reporting is not set' { $script:MessagingPolicy = [pscustomobject]@{ AllowSecurityEndUserReporting = $null } Test-MtCisTeamsReportSecurityConcerns | Should -BeFalse @@ -252,10 +248,10 @@ Describe 'Test-MtCisTeamsReportSecurityConcerns' { } It 'fails when a reporting destination differs from the single mailbox' { - $script:Rules[0].SentTo = @('triage@contoso.com') + $script:Policy.ReportChatMessageAddresses = @('triage@contoso.com') Test-MtCisTeamsReportSecurityConcerns | Should -BeFalse - $script:Result | Should -Match 'Report submission rule \(SentTo\) \| triage@contoso.com \| soc@contoso.com \| ❌ Fail' + $script:Result | Should -Match 'ReportChatMessageAddresses \| triage@contoso.com \| soc@contoso.com \| ❌ Fail' } It 'fails when no report submission policy is returned' { diff --git a/tests/cis/Test.CIS.M365.2.4.2.md b/tests/cis/Test.CIS.M365.2.4.2.md index e7e2c0e1ad..d1d687201d 100644 --- a/tests/cis/Test.CIS.M365.2.4.2.md +++ b/tests/cis/Test.CIS.M365.2.4.2.md @@ -2,7 +2,7 @@ The Strict preset security policy applies its strongest protections to the recip Executives, finance staff and administrators are the usual targets of spear phishing and whaling. Microsoft maintains the Standard and Strict preset security policies and updates them as threats change. Strict has the most aggressive settings for spam, phishing, malware, spoofing, impersonation, Safe Links and Safe Attachments, which suits the accounts that are most likely to be targeted and most valuable to compromise. -The test reads the Strict preset rules for Exchange Online Protection and for Defender for Office 365. Each rule must be on and have at least one recipient target, following the CIS PowerShell audit procedure. The test does not verify that the selected recipients include priority accounts. To ensure those accounts are covered, add a group containing them to each rule. Microsoft Defender for Office 365 licences are required. +The test reads the Strict preset rules for Exchange Online Protection and Defender for Office 365. Each rule must be enabled and have at least one recipient condition: `SentTo`, `SentToMemberOf` or `RecipientDomainIs`. This follows the CIS PowerShell audit procedure; it does not verify whether those targets include every priority account or evaluate rule exceptions, so review the target values and membership separately. Preset security policies can't target user tags, so use a group that contains the priority accounts. Microsoft Defender for Office 365 licences are required. #### Remediation action diff --git a/tests/cis/Test.CIS.M365.2.4.2.ps1 b/tests/cis/Test.CIS.M365.2.4.2.ps1 index 30d3f659c8..678f0dc08a 100644 --- a/tests/cis/Test.CIS.M365.2.4.2.ps1 +++ b/tests/cis/Test.CIS.M365.2.4.2.ps1 @@ -1,16 +1,16 @@ function Test-MtCisStrictPresetForPriorityAccount { <# .SYNOPSIS - Checks that both Strict preset security policy rules are enabled and apply to every priority account. + Checks that both Strict preset security policy rules are enabled and have recipient conditions. .DESCRIPTION - Checks that both the Exchange Online Protection and the Defender for Office 365 rules of the Strict preset security policy are enabled, have at least one recipient condition (SentTo, SentToMemberOf or RecipientDomainIs), and that every user tagged as a priority account meets those conditions and is not excluded by an exception. + Checks that the Exchange Online Protection and Defender for Office 365 rules of the Strict preset security policy are enabled and have at least one recipient condition (SentTo, SentToMemberOf or RecipientDomainIs), as required by the CIS PowerShell audit procedure. CIS Microsoft 365 Foundations Benchmark v7.0.0 (2.4.2, L1) .EXAMPLE Test-MtCisStrictPresetForPriorityAccount - Returns true if both Strict preset security policy rules are enabled and apply to every priority account. + Returns true if both Strict preset security policy rules are enabled and have recipient conditions. .LINK https://maester.dev/docs/tests/CIS.M365.2.4.2 @@ -27,7 +27,7 @@ ImplementationCost = 'Low', Mitre = 'T1566', Control = ('cis-m365:2.4.2', 'nist-800-53-r5:SI-4(5)'), - Service = ('ExchangeOnline', 'Graph'), + Service = 'ExchangeOnline', License = 'ATP_ENTERPRISE', Author = 'JeremyFinney-lgtm' )] @@ -35,128 +35,43 @@ [OutputType([bool])] param() - Write-Verbose 'Getting preset security policy rules and priority accounts...' + Write-Verbose 'Getting Strict preset security policy rules...' $eopRule = @(Get-MtExo -Request EOPProtectionPolicyRule) | Where-Object { $_.Identity -eq 'Strict Preset Security Policy' } | Select-Object -First 1 $atpRule = @(Get-MtExo -Request ATPProtectionPolicyRule) | Where-Object { $_.Identity -eq 'Strict Preset Security Policy' } | Select-Object -First 1 $rules = @( [pscustomobject]@{ Name = 'Exchange Online Protection'; Rule = $eopRule } [pscustomobject]@{ Name = 'Defender for Office 365'; Rule = $atpRule } ) - $vipUsers = @(Get-MtExo -Request VipUser) - - $usesGroups = @($rules.Rule | Where-Object { $_ } | Where-Object { - @($_.SentToMemberOf | Where-Object { $_ }).Count -gt 0 -or @($_.ExceptIfSentToMemberOf | Where-Object { $_ }).Count -gt 0 - }).Count -gt 0 - - # Rule values can be names, addresses or GUIDs, so each one is also resolved to its Entra object ID. - $recipientIds = @{} - $resolveIds = { - param([object[]] $Values) - foreach ($value in @($Values | Where-Object { $_ })) { - $key = "$value" - if (-not $recipientIds.ContainsKey($key)) { - $recipient = Get-Recipient -Identity $key -ErrorAction SilentlyContinue | Select-Object -First 1 - $recipientIds[$key] = "$($recipient.ExternalDirectoryObjectId)" - } - $key - if ($recipientIds[$key]) { $recipientIds[$key] } - } - } - $matchesAny = { - param([object[]] $Candidates, $Set) - @($Candidates | Where-Object { $_ -and $Set.Contains("$_") }).Count -gt 0 - } - $matchesDomain = { - param([object[]] $Domains, [string] $Domain) - @($Domains | Where-Object { $_ -and ($Domain -eq "$_" -or $Domain -like "*.$_") }).Count -gt 0 - } - - $priorityAccounts = @(foreach ($vip in $vipUsers) { - $keys = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) - foreach ($value in @($vip.Name, $vip.DisplayName, $vip.UserPrincipalName, $vip.WindowsEmailAddress, $vip.Identity, $vip.DistinguishedName, $vip.ExternalDirectoryObjectId, $vip.Guid)) { - if ("$value") { $null = $keys.Add("$value") } - } - $groupKeys = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) - if ($usesGroups -and $vip.ExternalDirectoryObjectId) { - $groups = @(Invoke-MtGraphRequest -ApiVersion 'v1.0' -RelativeUri "users/$($vip.ExternalDirectoryObjectId)/transitiveMemberOf/microsoft.graph.group" -Select @('id', 'displayName', 'mail', 'mailNickname')) - foreach ($group in $groups) { - foreach ($value in @($group.id, $group.displayName, $group.mail, $group.mailNickname)) { - if ("$value") { $null = $groupKeys.Add("$value") } - } + $report = foreach ($entry in $rules) { + $rule = $entry.Rule + $recipientConditions = @() + if ($rule) { + foreach ($condition in @('SentTo', 'SentToMemberOf', 'RecipientDomainIs')) { + if (@($rule.$condition | Where-Object { $_ }).Count -gt 0) { + $recipientConditions += $condition } } - $address = if ($vip.WindowsEmailAddress) { "$($vip.WindowsEmailAddress)" } else { "$($vip.UserPrincipalName)" } - [pscustomobject]@{ - Name = if ($vip.UserPrincipalName) { "$($vip.UserPrincipalName)" } else { "$($vip.Name)" } - Keys = $keys - GroupKeys = $groupKeys - Domain = ($address -split '@')[-1] - } - }) - - # Different recipient conditions of a preset rule are combined with AND, and any exception excludes the recipient. - $isCovered = { - param($Rule, $Account) - $conditions = @() - if (@($Rule.SentTo | Where-Object { $_ }).Count -gt 0) { - $conditions += & $matchesAny (& $resolveIds $Rule.SentTo) $Account.Keys - } - if (@($Rule.SentToMemberOf | Where-Object { $_ }).Count -gt 0) { - $conditions += & $matchesAny (& $resolveIds $Rule.SentToMemberOf) $Account.GroupKeys - } - if (@($Rule.RecipientDomainIs | Where-Object { $_ }).Count -gt 0) { - $conditions += & $matchesDomain $Rule.RecipientDomainIs $Account.Domain } - $excluded = (& $matchesAny (& $resolveIds $Rule.ExceptIfSentTo) $Account.Keys) -or - (& $matchesAny (& $resolveIds $Rule.ExceptIfSentToMemberOf) $Account.GroupKeys) -or - (& $matchesDomain $Rule.ExceptIfRecipientDomainIs $Account.Domain) - $conditions.Count -gt 0 -and $conditions -notcontains $false -and -not $excluded - } - - $report = foreach ($entry in $rules) { - $rule = $entry.Rule - $hasTargets = @($rule.SentTo | Where-Object { $_ }).Count -gt 0 -or @($rule.SentToMemberOf | Where-Object { $_ }).Count -gt 0 -or @($rule.RecipientDomainIs | Where-Object { $_ }).Count -gt 0 - $scope = if (-not $rule) { 'Rule not found' } elseif ($hasTargets) { 'Specific recipients' } else { 'All recipients (no conditions)' } - $uncovered = if ($rule -and $hasTargets) { @($priorityAccounts | Where-Object { -not (& $isCovered $rule $_) }) } else { $priorityAccounts } + $state = if ($rule) { $rule.State } else { 'Not found' } [pscustomobject]@{ - Component = $entry.Name - State = if ($rule) { $rule.State } else { 'Not found' } - Scope = $scope - Covered = "$($priorityAccounts.Count - $uncovered.Count) of $($priorityAccounts.Count)" - Uncovered = @($uncovered | ForEach-Object { $_.Name }) - Pass = $null -ne $rule -and $rule.State -eq 'Enabled' -and $hasTargets -and $priorityAccounts.Count -gt 0 -and $uncovered.Count -eq 0 + Component = $entry.Name + State = $state + RecipientConditions = if ($recipientConditions.Count -gt 0) { $recipientConditions -join ', ' } else { 'None' } + Pass = $null -ne $rule -and $state -eq 'Enabled' -and $recipientConditions.Count -gt 0 } } $testResult = @($report | Where-Object { -not $_.Pass }).Count -eq 0 - $passText = 'The Strict preset security policy is enabled and applies to every priority account.' - $failText = 'The Strict preset security policy is missing or disabled, has no recipient condition, or does not apply to every priority account.' - $notes = '' - if ($priorityAccounts.Count -eq 0) { - $notes += "`n`nNo users are tagged as priority accounts. Tag them with the **Priority account** user tag (CIS 2.4.1), then add them to the Strict preset security policy." - } - if (@($report | Where-Object { $_.Scope -eq 'All recipients (no conditions)' }).Count -gt 0) { - $notes += "`n`nA rule with no recipient conditions applies to everyone, but the CIS 2.4.2 audit requires the rule to name the priority accounts. Add a group that contains the priority accounts as a recipient condition." - } - - $resultMd = "| Component | Rule state | Recipients | Priority accounts covered | Result |`n" - $resultMd += "| --- | --- | --- | --- | --- |`n" + $resultMd = "| Component | Rule state | Recipient conditions | Result |`n" + $resultMd += "| --- | --- | --- | --- |`n" foreach ($row in $report) { - $resultMd += "| $($row.Component) | $($row.State) | $($row.Scope) | $($row.Covered) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" - } - $missing = @($report | Where-Object { $_.Uncovered.Count -gt 0 -and $_.Scope -eq 'Specific recipients' }) - if ($missing.Count -gt 0) { - $resultMd += "`n| Component | Priority accounts not covered |`n" - $resultMd += "| --- | --- |`n" - foreach ($row in $missing) { - $resultMd += "| $($row.Component) | $($row.Uncovered -join ', ') |`n" - } + $resultMd += "| $($row.Component) | $($row.State) | $($row.RecipientConditions) | $(if ($row.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($testResult) { - $testResultMarkdown = "Well done. $passText`n`n%TestResult%" + $testResultMarkdown = "Well done. Both Strict preset security policy rules are enabled and have recipient conditions.`n`n%TestResult%" } else { - $testResultMarkdown = "$failText$notes`n`n%TestResult%" + $testResultMarkdown = "One or both Strict preset security policy rules are missing, disabled, or have no recipient conditions. Configure both rules with a recipient target using SentTo, SentToMemberOf or RecipientDomainIs.`n`n%TestResult%" } $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $resultMd diff --git a/tests/cis/Test.CIS.M365.8.6.1.md b/tests/cis/Test.CIS.M365.8.6.1.md index 6001d293a7..91c9ce26df 100644 --- a/tests/cis/Test.CIS.M365.8.6.1.md +++ b/tests/cis/Test.CIS.M365.8.6.1.md @@ -2,7 +2,7 @@ Users can report security concerns in Microsoft Teams, and reported items go onl User reporting lets people flag suspicious Teams messages quickly, so the security team can act on phishing and malicious content. Reported items can contain sensitive or personal information, and reports can include messages that are threatening or harassing, so they should stay inside the organization and be reviewed by staff who can route them to the right team, such as Human Resources. Sending reports to Microsoft should follow company policy. -CIS requires three settings: **Report a security concern** in the Teams Global messaging policy, **Monitor reported items in Microsoft Teams** in the Microsoft Defender portal, and reported items sent to **My reporting mailbox only**. The test reads `Get-CsTeamsMessagingPolicy -Identity Global`, the report submission policy and the report submission rule. Reporting must be on, Teams and email reports must go to the reporting mailbox and not to Microsoft (`ReportChatMessageEnabled` and `EnableReportToMicrosoft` are `False`), and the reporting mailbox must be set in the policy and in an enabled report submission rule. Microsoft Defender for Office 365 Plan 1 or Plan 2, or Microsoft Defender XDR, licences are required. +CIS requires **Report a security concern** in the Teams Global messaging policy, **Monitor reported items in Microsoft Teams** in the Microsoft Defender portal, and reported items sent to **My reporting mailbox only**. The test reads `Get-CsTeamsMessagingPolicy -Identity Global` and the report submission policy. Reporting must be on, Teams and email reports must go to the same reporting mailbox and not to Microsoft (`ReportChatMessageEnabled` and `EnableReportToMicrosoft` are `False`). Microsoft Defender for Office 365 Plan 1 or Plan 2, or Microsoft Defender XDR, licences are required. #### Remediation action @@ -41,11 +41,8 @@ $params = @{ ReportPhishAddresses = $usersub } Set-ReportSubmissionPolicy @params -New-ReportSubmissionRule -Name DefaultReportSubmissionRule -ReportSubmissionPolicy DefaultReportSubmissionPolicy -SentTo $usersub ``` -If the report submission rule already exists, use `Set-ReportSubmissionRule -Identity DefaultReportSubmissionRule -SentTo $usersub` to configure its recipient. If the rule is disabled, enable it with `Enable-ReportSubmissionRule -Identity DefaultReportSubmissionRule`. - #### Related links * [Microsoft Teams admin center - Settings & policies](https://admin.teams.microsoft.com/one-policy/settings) diff --git a/tests/cis/Test.CIS.M365.8.6.1.ps1 b/tests/cis/Test.CIS.M365.8.6.1.ps1 index 78231a2673..bf41c6b0c9 100644 --- a/tests/cis/Test.CIS.M365.8.6.1.ps1 +++ b/tests/cis/Test.CIS.M365.8.6.1.ps1 @@ -4,8 +4,8 @@ Ensure users can report security concerns in Teams .DESCRIPTION - Checks that users can report security concerns in Teams, and that reported Teams items and email messages - go only to the organization's reporting mailbox and not to Microsoft. + Checks that users can report security concerns in Teams and that configured report destinations use + the organization's reporting mailbox. CIS Microsoft 365 Foundations Benchmark v7.0.0 (8.6.1, E5 L1) .EXAMPLE @@ -43,20 +43,11 @@ $messagingPolicy = Get-CsTeamsMessagingPolicy -Identity Global $reportPolicy = @(Get-MtExo -Request ReportSubmissionPolicy) | Select-Object -First 1 - $reportRules = @(Get-MtExo -Request ReportSubmissionRule) | Where-Object { $_ } - - $ruleAddresses = @( - $reportRules | - Where-Object { $_.State -eq 'Enabled' } | - ForEach-Object { $_.SentTo } | - Where-Object { -not [string]::IsNullOrWhiteSpace("$($_)") } - ) $destinationValues = [ordered]@{ - ReportJunkAddresses = @($reportPolicy.ReportJunkAddresses) - ReportNotJunkAddresses = @($reportPolicy.ReportNotJunkAddresses) - ReportPhishAddresses = @($reportPolicy.ReportPhishAddresses) - 'Report submission rule (SentTo)' = $ruleAddresses - ReportChatMessageAddresses = @($reportPolicy.ReportChatMessageAddresses) + ReportJunkAddresses = @($reportPolicy.ReportJunkAddresses) + ReportNotJunkAddresses = @($reportPolicy.ReportNotJunkAddresses) + ReportPhishAddresses = @($reportPolicy.ReportPhishAddresses) + ReportChatMessageAddresses = @($reportPolicy.ReportChatMessageAddresses) } $reportingMailbox = @( $destinationValues.Values | From 6ee715f7b339bbabfca01880578a98e55786dfbb Mon Sep 17 00:00:00 2001 From: Jeremy Finney Date: Tue, 10 Nov 2026 07:42:45 +1300 Subject: [PATCH 11/15] fix(cis): escape tenant data in result markdown Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../functions/Test-MtCisTeamsChecks.Tests.ps1 | 27 ++++++++++++++++--- tests/cis/Test.CIS.M365.2.4.4.ps1 | 6 +++-- tests/cis/Test.CIS.M365.8.6.1.ps1 | 4 ++- 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 b/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 index 73e93eaca7..c800b95a8b 100644 --- a/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 @@ -59,9 +59,21 @@ Describe 'Test-MtCisZAP' { It 'lists the exclusions for review' { $script:Rules = @([pscustomobject]@{ ExceptIfSentTo = @('research@contoso.com'); ExceptIfSentToMemberOf = $null; ExceptIfRecipientDomainIs = @('research.contoso.com') }) Test-MtCisZAP | Should -BeTrue - $script:Result | Should -Match 'ExceptIfSentTo \| research@contoso.com' + $script:Result | Should -Match 'ExceptIfSentTo \| research\\?@contoso\.com' $script:Result | Should -Match 'ExceptIfRecipientDomainIs \| research.contoso.com' } + + It 'escapes tenant-controlled Markdown in policy names and exclusions' { + $script:Policies = @([pscustomobject]@{ Name = '![x](https://example.com)'; ZapEnabled = $true }) + $participant = 'research@contoso.com|[link](https://example.com)' + $script:Rules = @([pscustomobject]@{ ExceptIfSentTo = @($participant); ExceptIfSentToMemberOf = $null; ExceptIfRecipientDomainIs = $null }) + + Test-MtCisZAP | Should -BeTrue + $safeName = Get-MtSafeMarkdown -Text '![x](https://example.com)' + $safeParticipant = Get-MtSafeMarkdown -Text $participant + $script:Result | Should -Match ([regex]::Escape("| $safeName | True | ✅ Pass |")) + $script:Result | Should -Match ([regex]::Escape("| ExceptIfSentTo | $safeParticipant |")) + } } Describe 'CIS unmanaged Teams user settings' { @@ -244,14 +256,23 @@ Describe 'Test-MtCisTeamsReportSecurityConcerns' { $script:Policy.ReportChatMessageAddresses = @() Test-MtCisTeamsReportSecurityConcerns | Should -BeFalse - $script:Result | Should -Match 'ReportChatMessageAddresses \| Not set \| soc@contoso.com \| ❌ Fail' + $script:Result | Should -Match 'ReportChatMessageAddresses \| Not set \| soc\\?@contoso\.com \| ❌ Fail' } It 'fails when a reporting destination differs from the single mailbox' { $script:Policy.ReportChatMessageAddresses = @('triage@contoso.com') Test-MtCisTeamsReportSecurityConcerns | Should -BeFalse - $script:Result | Should -Match 'ReportChatMessageAddresses \| triage@contoso.com \| soc@contoso.com \| ❌ Fail' + $script:Result | Should -Match 'ReportChatMessageAddresses \| triage\\?@contoso\.com \| soc\\?@contoso\.com \| ❌ Fail' + } + + It 'escapes tenant-controlled Markdown in reporting destinations' { + $destination = 'triage@contoso.com|[link](https://example.com)' + $script:Policy.ReportChatMessageAddresses = @($destination) + + Test-MtCisTeamsReportSecurityConcerns | Should -BeFalse + $safeDestination = Get-MtSafeMarkdown -Text $destination + $script:Result | Should -Match ([regex]::Escape("| ReportChatMessageAddresses | $safeDestination |")) } It 'fails when no report submission policy is returned' { diff --git a/tests/cis/Test.CIS.M365.2.4.4.ps1 b/tests/cis/Test.CIS.M365.2.4.4.ps1 index 39548d339e..e82736a0fa 100644 --- a/tests/cis/Test.CIS.M365.2.4.4.ps1 +++ b/tests/cis/Test.CIS.M365.2.4.4.ps1 @@ -65,7 +65,8 @@ $resultMd = "| Policy | Zero-hour auto purge (ZAP) | Result |`n" $resultMd += "| --- | --- | --- |`n" foreach ($policy in $policies) { - $resultMd += "| $($policy.Name) | $($policy.ZapEnabled) | $(if ($policy.ZapEnabled -eq $true) { '✅ Pass' } else { '❌ Fail' }) |`n" + $safeName = Get-MtSafeMarkdown -Text "$($policy.Name)" + $resultMd += "| $safeName | $($policy.ZapEnabled) | $(if ($policy.ZapEnabled -eq $true) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($policies.Count -eq 0) { $resultMd += "| Not found | | ❌ Fail |`n" @@ -76,7 +77,8 @@ $resultMd += "| Exclusion | Participants |`n" $resultMd += "| --- | --- |`n" foreach ($exclusion in $exclusions) { - $resultMd += "| $($exclusion.Exception) | $($exclusion.Values) |`n" + $safeValues = Get-MtSafeMarkdown -Text "$($exclusion.Values)" + $resultMd += "| $($exclusion.Exception) | $safeValues |`n" } } else { diff --git a/tests/cis/Test.CIS.M365.8.6.1.ps1 b/tests/cis/Test.CIS.M365.8.6.1.ps1 index bf41c6b0c9..880a39232b 100644 --- a/tests/cis/Test.CIS.M365.8.6.1.ps1 +++ b/tests/cis/Test.CIS.M365.8.6.1.ps1 @@ -93,7 +93,9 @@ $result += "| --- | --- | --- | --- |`n" foreach ($check in $checks) { $displayValue = if ($null -eq $check.Value -or "$($check.Value)" -eq '') { 'Not set' } else { $check.Value } - $result += "| $($check.Setting) | $displayValue | $($check.Expected) | $(if ($check.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" + $safeValue = Get-MtSafeMarkdown -Text "$displayValue" + $safeExpected = Get-MtSafeMarkdown -Text "$($check.Expected)" + $result += "| $($check.Setting) | $safeValue | $safeExpected | $(if ($check.Pass) { '✅ Pass' } else { '❌ Fail' }) |`n" } if ($return) { From a9d682a2f66bb9312203eb30f818de2da9d1a4ae Mon Sep 17 00:00:00 2001 From: Jeremy Finney Date: Thu, 12 Nov 2026 09:00:16 +1300 Subject: [PATCH 12/15] Address CIS review feedback --- .../services/exchange/Resolve-MtDnsTxtRecord.ps1 | 2 +- .../functions/Invoke-MtPackGitHubRequest.Tests.ps1 | 2 +- powershell/tests/functions/Test-MtDkim.Tests.ps1 | 2 +- tests/cis/Test.CIS.M365.2.4.2.md | 6 +++--- tests/cis/Test.CIS.M365.2.4.4.md | 11 ++++++++--- tests/cis/Test.CIS.M365.8.1.1.md | 7 ++++--- tests/cis/Test.CIS.M365.8.1.1.ps1 | 4 ++-- tests/cis/Test.CIS.M365.8.2.1.md | 5 +++-- tests/cis/Test.CIS.M365.8.2.2.md | 4 ++-- tests/cis/Test.CIS.M365.8.5.3.md | 4 +++- tests/cis/Test.CIS.M365.8.6.1.md | 4 ++++ 11 files changed, 32 insertions(+), 19 deletions(-) diff --git a/powershell/internal/services/exchange/Resolve-MtDnsTxtRecord.ps1 b/powershell/internal/services/exchange/Resolve-MtDnsTxtRecord.ps1 index e40b7698d4..2cd1adfa34 100644 --- a/powershell/internal/services/exchange/Resolve-MtDnsTxtRecord.ps1 +++ b/powershell/internal/services/exchange/Resolve-MtDnsTxtRecord.ps1 @@ -1,4 +1,4 @@ -function Resolve-MtDnsTxtRecord { +function Resolve-MtDnsTxtRecord { <# .SYNOPSIS Returns the TXT records published at a DNS name, without filtering them. diff --git a/powershell/tests/functions/Invoke-MtPackGitHubRequest.Tests.ps1 b/powershell/tests/functions/Invoke-MtPackGitHubRequest.Tests.ps1 index edba6469da..fc0f702b60 100644 --- a/powershell/tests/functions/Invoke-MtPackGitHubRequest.Tests.ps1 +++ b/powershell/tests/functions/Invoke-MtPackGitHubRequest.Tests.ps1 @@ -1,4 +1,4 @@ -BeforeAll { +BeforeAll { Import-Module "$PSScriptRoot/../../Maester.psd1" -Force $script:savedGhToken = $env:GH_TOKEN diff --git a/powershell/tests/functions/Test-MtDkim.Tests.ps1 b/powershell/tests/functions/Test-MtDkim.Tests.ps1 index d1ff031e5c..fc8387f904 100644 --- a/powershell/tests/functions/Test-MtDkim.Tests.ps1 +++ b/powershell/tests/functions/Test-MtDkim.Tests.ps1 @@ -1,4 +1,4 @@ -BeforeAll { +BeforeAll { . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" # Check functions that became native tests are not exported. Use-MtModuleFunction -Name Test-MtCisaDkim, Test-MtCisDkim diff --git a/tests/cis/Test.CIS.M365.2.4.2.md b/tests/cis/Test.CIS.M365.2.4.2.md index d1d687201d..5d6e325dca 100644 --- a/tests/cis/Test.CIS.M365.2.4.2.md +++ b/tests/cis/Test.CIS.M365.2.4.2.md @@ -2,15 +2,15 @@ The Strict preset security policy applies its strongest protections to the recip Executives, finance staff and administrators are the usual targets of spear phishing and whaling. Microsoft maintains the Standard and Strict preset security policies and updates them as threats change. Strict has the most aggressive settings for spam, phishing, malware, spoofing, impersonation, Safe Links and Safe Attachments, which suits the accounts that are most likely to be targeted and most valuable to compromise. -The test reads the Strict preset rules for Exchange Online Protection and Defender for Office 365. Each rule must be enabled and have at least one recipient condition: `SentTo`, `SentToMemberOf` or `RecipientDomainIs`. This follows the CIS PowerShell audit procedure; it does not verify whether those targets include every priority account or evaluate rule exceptions, so review the target values and membership separately. Preset security policies can't target user tags, so use a group that contains the priority accounts. Microsoft Defender for Office 365 licences are required. +The test reads the Strict preset rules for Exchange Online Protection and Defender for Office 365. Each rule must be enabled and have at least one recipient condition: `SentTo`, `SentToMemberOf` or `RecipientDomainIs`. This follows the CIS PowerShell audit procedure, but it does not verify that those targets include every priority account or evaluate rule exceptions. Review the recipient conditions, target membership and exceptions on both rules: different condition types combine with AND, while any matching exception excludes the recipient. Adjust or remove conditions and exceptions that keep a priority account from receiving either protection. Preset security policies can't target user tags, so use a group that contains the priority accounts. Microsoft Defender for Office 365 licences are required. #### Remediation action 1. Sign in to the [Microsoft Defender portal](https://security.microsoft.com). 2. Go to **Email & collaboration** > **Policies & rules** > **Threat policies** > [**Preset security policies**](https://security.microsoft.com/presetSecurityPolicies). 3. Turn on **Strict protection** and select **Manage protection settings**. -4. On **Apply Exchange Online Protection**, select **Specific recipients** and add the users or groups that are your priority accounts. -5. On **Apply Defender for Office 365 protection**, select **Specific recipients** and add the same users or groups. +4. On **Apply Exchange Online Protection**, select **Specific recipients** and add the users or groups that are your priority accounts. Review existing recipient conditions and exceptions on this page, and adjust or remove any that keep a priority account from receiving protection. +5. On **Apply Defender for Office 365 protection**, select **Specific recipients** and add the same users or groups. Review existing recipient conditions and exceptions here as well, and adjust or remove any that keep a priority account from receiving protection. 6. On **Add email addresses to flag when impersonated by attackers**, add the internal and external senders, including your priority accounts, that attackers may impersonate. 7. On **Add domains to flag when impersonated by attackers**, add the domains of key partners. Your accepted domains are protected automatically. 8. On **Review and confirm your changes**, select **Confirm**. diff --git a/tests/cis/Test.CIS.M365.2.4.4.md b/tests/cis/Test.CIS.M365.2.4.4.md index 9652ebcd44..e1a72665c8 100644 --- a/tests/cis/Test.CIS.M365.2.4.4.md +++ b/tests/cis/Test.CIS.M365.2.4.4.md @@ -14,10 +14,15 @@ The test passes when every Teams protection policy has ZAP turned on, and fails ##### PowerShell 1. Connect to Exchange Online using `Connect-ExchangeOnline`. -2. Run the following command: +2. Check whether a Teams protection policy exists, then create or update it with ZAP enabled: ```powershell -Set-TeamsProtectionPolicy -Identity "Teams Protection Policy" -ZapEnabled $true +if (Get-TeamsProtectionPolicy) { + Set-TeamsProtectionPolicy -Identity "Teams Protection Policy" -ZapEnabled $true +} +else { + New-TeamsProtectionPolicy -Name "Teams Protection Policy" -ZapEnabled $true +} ``` 3. Review the exclusions with `Get-TeamsProtectionPolicyRule | Format-List ExceptIf*`. @@ -26,7 +31,7 @@ Set-TeamsProtectionPolicy -Identity "Teams Protection Policy" -ZapEnabled $true * [Microsoft Defender portal - Microsoft Teams protection](https://security.microsoft.com/securitysettings/teamsProtectionPolicy) * [Zero-hour auto purge (ZAP) in Microsoft Teams](https://learn.microsoft.com/defender-office-365/zero-hour-auto-purge#zero-hour-auto-purge-zap-in-microsoft-teams) -* [Configure ZAP for Teams protection in Defender for Office 365](https://learn.microsoft.com/defender-office-365/mdo-support-teams-about#configure-zap-for-teams-protection-in-defender-for-office-365-plan-2) +* [Configure ZAP for Teams protection in Defender for Office 365](https://learn.microsoft.com/defender-office-365/mdo-support-teams-about#configure-zap-for-teams-protection-in-defender-for-office-365) * [CIS Microsoft 365 Foundations Benchmark v7.0.0 - 2.4.4](https://www.cisecurity.org/benchmark/microsoft_365) diff --git a/tests/cis/Test.CIS.M365.8.1.1.md b/tests/cis/Test.CIS.M365.8.1.1.md index d5b2605613..7f89f37dca 100644 --- a/tests/cis/Test.CIS.M365.8.1.1.md +++ b/tests/cis/Test.CIS.M365.8.1.1.md @@ -1,13 +1,13 @@ -Teams lets users share files only through third-party cloud storage services that the organization has approved. +The check evaluates only five third-party storage settings in the Global Teams client configuration: Dropbox, Box, Google Drive, Citrix ShareFile and Egnyte. A pass means each setting is present and disabled, or enabled only when its provider is listed in `ApprovedProviders`. It does not evaluate Teams storage apps, the Teams Files policy or the default upload-app setting, so a pass does not prove that all file sharing is limited to approved services. Review enabled cloud-storage apps separately under **Teams apps** > **Manage apps**, and review the Files settings. Teams stores and shares files in SharePoint and OneDrive by default, but it can also open files from Dropbox, Box, Google Drive, Citrix ShareFile and Egnyte. Files in those services are outside the organization's data protection, retention and sharing controls, and the services may not meet the organization's security standards. Turning off the services that aren't approved keeps users on storage the organization governs. Users who rely on another provider lose access to it from Teams. -The test reads the Global Teams client configuration and fails when a service is on that the organization has not approved. List approved services in the `ApprovedProviders` parameter (`Dropbox`, `Box`, `GoogleDrive`, `ShareFile`, `Egnyte`); by default none are approved. +The `ApprovedProviders` parameter accepts `Dropbox`, `Box`, `GoogleDrive`, `ShareFile` and `Egnyte`; by default none are approved. #### Remediation action 1. Sign in to the [Microsoft Teams admin center](https://admin.teams.microsoft.com). -2. Go to **Settings & policies** > [**Global (Org-wide default) settings**](https://admin.teams.microsoft.com/one-policy/settings) and select **Teams** to open the **Teams settings** section. +2. If the **Settings & policies** experience is not enabled, select the opt-in card or banner in the Teams admin center to switch to it. Then go to **Settings & policies** > [**Global (Org-wide default) settings**](https://admin.teams.microsoft.com/one-policy/settings) and select **Teams** to open the **Teams settings** section. In the existing interface, go to **Teams** > **Teams settings**. 3. Under **Files**, turn off each storage provider that the organization has not authorized. 4. Select **Save**. @@ -31,6 +31,7 @@ Set-CsTeamsClientConfiguration @params #### Related links * [Microsoft Teams admin center - Settings & policies](https://admin.teams.microsoft.com/one-policy/settings) +* [Manage apps in the Teams admin center](https://learn.microsoft.com/microsoftteams/manage-apps) * [Set-CsTeamsClientConfiguration](https://learn.microsoft.com/powershell/module/microsoftteams/set-csteamsclientconfiguration) * [CIS Microsoft 365 Foundations Benchmark v7.0.0 - 8.1.1](https://www.cisecurity.org/benchmark/microsoft_365) diff --git a/tests/cis/Test.CIS.M365.8.1.1.ps1 b/tests/cis/Test.CIS.M365.8.1.1.ps1 index c65e7a8263..0c11c460d7 100644 --- a/tests/cis/Test.CIS.M365.8.1.1.ps1 +++ b/tests/cis/Test.CIS.M365.8.1.1.ps1 @@ -73,9 +73,9 @@ } if ($return) { - $testResultMarkdown = "Well done. Only approved third-party cloud storage services are turned on in Teams.`n`n%TestResult%" + $testResultMarkdown = "Well done. The five checked third-party storage settings in the Global Teams client configuration are disabled or enabled only for approved providers.`n`n%TestResult%" } else { - $testResultMarkdown = "Third-party cloud storage services that are not approved are turned on in Teams. Turn them off, or add them to the ApprovedProviders parameter if the organization has approved them.`n`n%TestResult%" + $testResultMarkdown = "One or more of the five checked third-party storage settings are missing or enabled without approval. Turn them off, or add approved providers to the ApprovedProviders parameter.`n`n%TestResult%" } $testResultMarkdown = $testResultMarkdown -replace '%TestResult%', $result diff --git a/tests/cis/Test.CIS.M365.8.2.1.md b/tests/cis/Test.CIS.M365.8.2.1.md index 26604b47ea..2d28a530a8 100644 --- a/tests/cis/Test.CIS.M365.8.2.1.md +++ b/tests/cis/Test.CIS.M365.8.2.1.md @@ -1,6 +1,6 @@ Federation lets users in other Microsoft 365 and Teams organizations find and message people in your tenant. If every known external domain is allowed, anyone with a tenant in those domains can start chats with your users. That is a common route for phishing and social engineering, because the sender looks like a normal business contact. -Turning off external domains in the Global (Org-wide default) external access policy removes that path for everyone the policy applies to. Users who need to work with external organizations can be given a custom external access policy, or the organization settings can allow only specific partner domains. The test passes when the Global policy turns off external domains, or when the organization settings turn external domains off, block all of them or allow only specific domains. +Turning off external domains in the Global (Org-wide default) external access policy removes that path for everyone the policy applies to. Users who need to work with external organizations can be assigned a custom external access policy, or the organization settings can allow only specific partner domains. Both the organization setting and the policy assigned to a user must allow federation. An organization allowlist alone does not enable federation if the applicable policy still turns it off. The test passes when the Global policy turns off external domains, or when the organization settings turn external domains off, block all of them or allow only specific domains. #### Remediation action @@ -21,11 +21,12 @@ On the **Organization settings** tab, setting **Manage external domains for this Set-CsExternalAccessPolicy -Identity Global -EnableFederationAccess $false ``` -To allow only specific domains for the organization instead, run the following commands, replacing the example domain with your approved domains. The list replaces the domains that are allowed now: +To use an organization allowlist instead of disabling federation in the Global policy, turn federation on in the Global policy and configure the tenant-level allowlist. Replace the example domain with your approved domains; the list replaces the domains that are allowed now: ```powershell $domains = [System.Collections.Generic.List[string]]::new() $domains.Add('partner.example.com') +Set-CsExternalAccessPolicy -Identity Global -EnableFederationAccess $true Set-CsTenantFederationConfiguration -AllowFederatedUsers $true -AllowedDomainsAsAList $domains ``` diff --git a/tests/cis/Test.CIS.M365.8.2.2.md b/tests/cis/Test.CIS.M365.8.2.2.md index 7164320256..b1955d1de3 100644 --- a/tests/cis/Test.CIS.M365.8.2.2.md +++ b/tests/cis/Test.CIS.M365.8.2.2.md @@ -1,6 +1,6 @@ Users can't chat or meet with external users who have unmanaged Microsoft accounts, such as Microsoft Teams (free). -Little effort is needed to get a free or trial Teams account, so attackers use unmanaged accounts to reach users through external access. Attacks delivered this way include DarkGate malware, social engineering and phishing by Midnight Blizzard, GIFShell and username enumeration. Turning off communication with unmanaged accounts removes that channel. Users can no longer communicate with Teams users who aren't managed by an organization; create a separate policy for groups that need to. This setting doesn't control anonymous meeting join through a shared link, and isn't available in GCC, GCC High, DoD or private cloud environments. +Little effort is needed to get a free or trial Teams account, so attackers use unmanaged accounts to reach users through external access. Attacks delivered this way include DarkGate malware, social engineering and phishing by Midnight Blizzard, GIFShell and username enumeration. Turning off communication with unmanaged accounts removes that channel. Users can no longer communicate with Teams users who aren't managed by an organization. To make exceptions with a custom policy, keep the organization-level setting on and assign an allowing policy to the users who need access; turning the organization setting off cannot be overridden by a custom policy. This setting doesn't control anonymous meeting join through a shared link, and isn't available in GCC, GCC High, DoD or private cloud environments. The test passes when the Global (Org-wide default) external access policy or the organization settings turn the setting off. @@ -12,7 +12,7 @@ The test passes when the Global (Org-wide default) external access policy or the 4. Set **People in my org can chat and have meetings with external users who have unmanaged Microsoft accounts** to **Off**. 5. Select **Save**. -Turning the same setting **Off** on the **Organization settings** tab also meets the recommendation. +Turning the same setting **Off** on the **Organization settings** tab also meets the recommendation, but blocks unmanaged-account access for everyone and cannot be overridden by a custom policy. ##### PowerShell diff --git a/tests/cis/Test.CIS.M365.8.5.3.md b/tests/cis/Test.CIS.M365.8.5.3.md index c3cb9df496..b7954b69e7 100644 --- a/tests/cis/Test.CIS.M365.8.5.3.md +++ b/tests/cis/Test.CIS.M365.8.5.3.md @@ -1,6 +1,8 @@ Only invited people, people in your organization, or organizers and co-organizers can bypass the meeting lobby. -The lobby lets an organizer, co-organizer or presenter see who is joining before admitting them. For meetings that may contain sensitive information, people who weren't invited directly should wait to be admitted, and anonymous users shouldn't be able to use a meeting link to hold meetings at unscheduled times. People outside the organization, and anyone who dials in, including internal users who are unauthenticated when dialing in, wait in the lobby until someone admits them. +The lobby lets an organizer, co-organizer or presenter see who is joining before admitting them. With **People who were invited** (`InvitedUsers`), invited external participants can bypass the lobby, including people who receive a forwarded invitation and invitees on a distribution list. People who have only the meeting link, but no invitation, and participants who are not signed in must wait in the lobby. Choose **People in my org** or **Only organizers and co-organizers** if invited external participants should also wait. + +This test checks only the Global meeting policy default; organizers can change **Who can bypass the lobby** in Meeting options. Phone dial-in callers use the separate **People dialing in can bypass the lobby** setting, which organizers can also change in Meeting options. When that setting is on, callers may bypass the lobby after the meeting starts even when this test passes. Review the dial-in setting separately. The test passes when **Who can bypass the lobby** in the Global (Org-wide default) meeting policy is **People who were invited** (`InvitedUsers`), **People in my org** (`EveryoneInCompanyExcludingGuests`) or **Only organizers and co-organizers** (`OrganizerOnly`). diff --git a/tests/cis/Test.CIS.M365.8.6.1.md b/tests/cis/Test.CIS.M365.8.6.1.md index 91c9ce26df..9796ea9d0a 100644 --- a/tests/cis/Test.CIS.M365.8.6.1.md +++ b/tests/cis/Test.CIS.M365.8.6.1.md @@ -41,6 +41,10 @@ $params = @{ ReportPhishAddresses = $usersub } Set-ReportSubmissionPolicy @params + +if (-not (Get-ReportSubmissionRule)) { + New-ReportSubmissionRule -Name DefaultReportSubmissionRule -ReportSubmissionPolicy DefaultReportSubmissionPolicy -SentTo $usersub +} ``` #### Related links From a474fc54d43f37d229819680b5e13aedfb83c559 Mon Sep 17 00:00:00 2001 From: Jeremy Finney Date: Fri, 13 Nov 2026 08:10:17 +1300 Subject: [PATCH 13/15] chore: credit reviewer for strict preset finding Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/cis/Test.CIS.M365.2.4.2.ps1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/cis/Test.CIS.M365.2.4.2.ps1 b/tests/cis/Test.CIS.M365.2.4.2.ps1 index 678f0dc08a..cf4823632f 100644 --- a/tests/cis/Test.CIS.M365.2.4.2.ps1 +++ b/tests/cis/Test.CIS.M365.2.4.2.ps1 @@ -29,7 +29,8 @@ Control = ('cis-m365:2.4.2', 'nist-800-53-r5:SI-4(5)'), Service = 'ExchangeOnline', License = 'ATP_ENTERPRISE', - Author = 'JeremyFinney-lgtm' + Author = 'JeremyFinney-lgtm', + Contributor = 'merill' )] [CmdletBinding()] [OutputType([bool])] From 477b5ac8cb419ada60963345d748e1fd997836f1 Mon Sep 17 00:00:00 2001 From: Jeremy Finney Date: Sat, 14 Nov 2026 07:31:24 +1300 Subject: [PATCH 14/15] Add isolated strict preset failure cases Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- ...est-MtCisStrictPresetForPriorityAccount.Tests.ps1 | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 b/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 index 545e40d000..74ddfa64e5 100644 --- a/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisStrictPresetForPriorityAccount.Tests.ps1 @@ -62,6 +62,18 @@ Describe 'Test-MtCisStrictPresetForPriorityAccount' { $script:Result | Should -Match 'no recipient conditions' } + It 'fails when the EOP rule has no recipient conditions and the ATP rule is targeted' { + $script:EopRule = Get-StrictRuleFixture + + Test-MtCisStrictPresetForPriorityAccount | Should -BeFalse + } + + It 'fails when the ATP rule has no recipient conditions and the EOP rule is targeted' { + $script:AtpRule = Get-StrictRuleFixture + + Test-MtCisStrictPresetForPriorityAccount | Should -BeFalse + } + It 'fails when a rule is not returned' { $script:EopRule = $null From 1f1adcee2242722ff2d6def6b5555f803de92955 Mon Sep 17 00:00:00 2001 From: Jeremy Finney Date: Mon, 16 Nov 2026 17:13:19 +1300 Subject: [PATCH 15/15] fix(cis): align Teams check result details Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../functions/Test-MtCisTeamsChecks.Tests.ps1 | 23 +++++++++++++++---- tests/cis/Test.CIS.M365.8.1.1.ps1 | 5 +++- tests/cis/Test.CIS.M365.8.2.2.ps1 | 8 ++++--- tests/cis/Test.CIS.M365.8.2.3.ps1 | 8 ++++--- 4 files changed, 33 insertions(+), 11 deletions(-) diff --git a/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 b/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 index c800b95a8b..26ea23d941 100644 --- a/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisTeamsChecks.Tests.ps1 @@ -78,11 +78,13 @@ Describe 'Test-MtCisZAP' { Describe 'CIS unmanaged Teams user settings' { BeforeEach { + $script:Result = $null $script:Federation = [pscustomobject]@{ AllowTeamsConsumer = $false AllowTeamsConsumerInbound = $false } $script:GlobalPolicy = $null + Mock Add-MtTestResultDetail { param($Result) $script:Result = $Result } Mock Get-CsTenantFederationConfiguration { $script:Federation } Mock Get-CsExternalAccessPolicy { if ($null -eq $script:GlobalPolicy) { throw 'The Global policy lookup should not run.' } @@ -92,28 +94,40 @@ Describe 'CIS unmanaged Teams user settings' { It 'passes 8.2.2 without looking up the Global policy when the organization setting is false' { Test-MtCisCommunicateWithUnmanagedTeamsUsers | Should -BeTrue + $script:Result | Should -Match ([regex]::Escape('| AllowTeamsConsumer (organization settings) | False | ✅ Pass |')) Should -Invoke Get-CsExternalAccessPolicy -Times 0 -Exactly } It 'passes 8.2.3 without looking up the Global policy when the organization setting is false' { Test-MtCisCommunicateInitiateExternalTeamsUsers | Should -BeTrue + $script:Result | Should -Match ([regex]::Escape('| AllowTeamsConsumerInbound (organization settings) | False | ✅ Pass |')) Should -Invoke Get-CsExternalAccessPolicy -Times 0 -Exactly } - It 'uses the Global policy fallback for 8.2.2 when the organization setting is enabled' { + It 'uses the Global policy fallback and reports pass/fail for 8.2.2 when the organization setting is enabled' { $script:Federation.AllowTeamsConsumer = $true $script:GlobalPolicy = [pscustomobject]@{ EnableTeamsConsumerAccess = $false } Test-MtCisCommunicateWithUnmanagedTeamsUsers | Should -BeTrue - Should -Invoke Get-CsExternalAccessPolicy -Times 1 -Exactly + $script:Result | Should -Match ([regex]::Escape('| EnableTeamsConsumerAccess (Global external access policy) | False | ✅ Pass |')) + + $script:GlobalPolicy.EnableTeamsConsumerAccess = $true + Test-MtCisCommunicateWithUnmanagedTeamsUsers | Should -BeFalse + $script:Result | Should -Match ([regex]::Escape('| EnableTeamsConsumerAccess (Global external access policy) | True | ❌ Fail |')) + Should -Invoke Get-CsExternalAccessPolicy -Times 2 -Exactly } - It 'uses the Global policy fallback for 8.2.3 when the organization setting is enabled' { + It 'uses the Global policy fallback and reports pass/fail for 8.2.3 when the organization setting is enabled' { $script:Federation.AllowTeamsConsumerInbound = $true $script:GlobalPolicy = [pscustomobject]@{ EnableTeamsConsumerInbound = $false } Test-MtCisCommunicateInitiateExternalTeamsUsers | Should -BeTrue - Should -Invoke Get-CsExternalAccessPolicy -Times 1 -Exactly + $script:Result | Should -Match ([regex]::Escape('| EnableTeamsConsumerInbound (Global external access policy) | False | ✅ Pass |')) + + $script:GlobalPolicy.EnableTeamsConsumerInbound = $true + Test-MtCisCommunicateInitiateExternalTeamsUsers | Should -BeFalse + $script:Result | Should -Match ([regex]::Escape('| EnableTeamsConsumerInbound (Global external access policy) | True | ❌ Fail |')) + Should -Invoke Get-CsExternalAccessPolicy -Times 2 -Exactly } } @@ -127,6 +141,7 @@ Describe 'Test-MtCisThirdPartyFileSharing' { It 'passes when every provider is off' { Test-MtCisThirdPartyFileSharing | Should -BeTrue + $script:Result | Should -Match ([regex]::Escape('| AllowDropBox | False | No | ✅ Pass |')) } It 'fails when a provider that is not approved is on' { diff --git a/tests/cis/Test.CIS.M365.8.1.1.ps1 b/tests/cis/Test.CIS.M365.8.1.1.ps1 index 0c11c460d7..467a9e64dc 100644 --- a/tests/cis/Test.CIS.M365.8.1.1.ps1 +++ b/tests/cis/Test.CIS.M365.8.1.1.ps1 @@ -35,7 +35,7 @@ Control = ('cis-m365:8.1.1', 'nist-800-53-r5:AC-20', 'nist-800-53-r5:CM-7'), Service = 'Teams', Author = 'HenrikPiecha', - Contributor = ('merill', 'Mynster9361') + Contributor = ('merill', 'Mynster9361', 'julien-ly') )] [CmdletBinding()] [OutputType([bool])] @@ -62,6 +62,9 @@ $return = $true foreach ($provider in 'Dropbox', 'Box', 'GoogleDrive', 'ShareFile', 'Egnyte') { $setting = "Allow$provider" + if ($provider -eq 'Dropbox') { + $setting = 'AllowDropBox' + } $value = $clientConfig.$setting $approved = $provider -in $ApprovedProviders if ($value -eq $false -or ($approved -and $value -eq $true)) { diff --git a/tests/cis/Test.CIS.M365.8.2.2.ps1 b/tests/cis/Test.CIS.M365.8.2.2.ps1 index 76cce31e12..8652dd8ef9 100644 --- a/tests/cis/Test.CIS.M365.8.2.2.ps1 +++ b/tests/cis/Test.CIS.M365.8.2.2.ps1 @@ -29,7 +29,7 @@ Control = ('cis-m365:8.2.2', 'nist-800-53-r5:AC-20'), Service = 'Teams', Author = 'HenrikPiecha', - Contributor = ('merill', 'Mynster9361') + Contributor = ('merill', 'Mynster9361', 'julien-ly') )] [CmdletBinding()] [OutputType([bool])] @@ -46,6 +46,8 @@ $policySetting = $externalAccessPolicy.EnableTeamsConsumerAccess } $testResult = $orgSetting -eq $false -or $policySetting -eq $false + $passResult = '✅ Pass' + $failResult = '❌ Fail' $resultMarkdown = if ($testResult) { "Well done. Communication with unmanaged Teams users is turned off by the audited Global external access policy or organization setting. Custom external access policies assigned to users are not checked.`n`n" @@ -54,9 +56,9 @@ } $resultMarkdown += "| Setting | Value | Result |`n" $resultMarkdown += "| --- | --- | --- |`n" - $resultMarkdown += "| AllowTeamsConsumer (organization settings) | $(if ($null -eq $orgSetting) { 'Not found' } else { $orgSetting }) | $(if ($orgSetting -eq $false) { 'Pass' } else { 'Fail' }) |`n" + $resultMarkdown += "| AllowTeamsConsumer (organization settings) | $(if ($null -eq $orgSetting) { 'Not found' } else { $orgSetting }) | $(if ($orgSetting -eq $false) { $passResult } else { $failResult }) |`n" $policyValue = if ($orgSetting -eq $false) { 'Not checked' } elseif ($null -eq $policySetting) { 'Not found' } else { $policySetting } - $policyResult = if ($orgSetting -eq $false) { 'Not checked' } elseif ($policySetting -eq $false) { 'Pass' } else { 'Fail' } + $policyResult = if ($orgSetting -eq $false) { 'Not checked' } elseif ($policySetting -eq $false) { $passResult } else { $failResult } $resultMarkdown += "| EnableTeamsConsumerAccess (Global external access policy) | $policyValue | $policyResult |`n" $resultMarkdown += "`nEither setting turned off meets the CIS recommendation." diff --git a/tests/cis/Test.CIS.M365.8.2.3.ps1 b/tests/cis/Test.CIS.M365.8.2.3.ps1 index b1f9427590..42852e79e2 100644 --- a/tests/cis/Test.CIS.M365.8.2.3.ps1 +++ b/tests/cis/Test.CIS.M365.8.2.3.ps1 @@ -29,7 +29,7 @@ Control = ('cis-m365:8.2.3', 'nist-800-53-r5:AC-20'), Service = 'Teams', Author = 'Mynster9361', - Contributor = 'merill' + Contributor = ('merill', 'julien-ly') )] [CmdletBinding()] [OutputType([bool])] @@ -46,6 +46,8 @@ $policySetting = $externalAccessPolicy.EnableTeamsConsumerInbound } $testResult = $orgSetting -eq $false -or $policySetting -eq $false + $passResult = '✅ Pass' + $failResult = '❌ Fail' $resultMarkdown = if ($testResult) { "Well done. The audited Global external access policy or organization setting prevents external unmanaged Teams users from initiating conversations. Custom external access policies assigned to users are not checked.`n`n" @@ -54,9 +56,9 @@ } $resultMarkdown += "| Setting | Value | Result |`n" $resultMarkdown += "| --- | --- | --- |`n" - $resultMarkdown += "| AllowTeamsConsumerInbound (organization settings) | $(if ($null -eq $orgSetting) { 'Not found' } else { $orgSetting }) | $(if ($orgSetting -eq $false) { 'Pass' } else { 'Fail' }) |`n" + $resultMarkdown += "| AllowTeamsConsumerInbound (organization settings) | $(if ($null -eq $orgSetting) { 'Not found' } else { $orgSetting }) | $(if ($orgSetting -eq $false) { $passResult } else { $failResult }) |`n" $policyValue = if ($orgSetting -eq $false) { 'Not checked' } elseif ($null -eq $policySetting) { 'Not found' } else { $policySetting } - $policyResult = if ($orgSetting -eq $false) { 'Not checked' } elseif ($policySetting -eq $false) { 'Pass' } else { 'Fail' } + $policyResult = if ($orgSetting -eq $false) { 'Not checked' } elseif ($policySetting -eq $false) { $passResult } else { $failResult } $resultMarkdown += "| EnableTeamsConsumerInbound (Global external access policy) | $policyValue | $policyResult |`n" $resultMarkdown += "`nEither setting turned off meets the CIS recommendation."