diff --git a/powershell/Maester.psm1 b/powershell/Maester.psm1 index ff65045908..fecc38fc89 100644 --- a/powershell/Maester.psm1 +++ b/powershell/Maester.psm1 @@ -23,6 +23,7 @@ $__MtSession = @{ Connections = @() ConnectionConfig = $null # Reference to config discovered by a connector, not an explicit run config. DnsCache = @() + DnsRecordCache = @{} ExoCache = @{} OrcaCache = @{} AIAgentInfo = $null # Get-MtAIAgentInfo cache: @{ Agents; Error }, Error is why no agent data is available diff --git a/powershell/internal/checks/cis/exchange/Test-MtCisParkedDomain.ps1 b/powershell/internal/checks/cis/exchange/Test-MtCisParkedDomain.ps1 new file mode 100644 index 0000000000..b61d56c513 --- /dev/null +++ b/powershell/internal/checks/cis/exchange/Test-MtCisParkedDomain.ps1 @@ -0,0 +1,31 @@ +function Test-MtCisParkedDomain { + <# + .SYNOPSIS + Returns true when a domain is in the list of parked domains an admin gave a CIS email-authentication check. + + .DESCRIPTION + CIS Microsoft 365 Foundations Benchmark v7.0.0 (2.1.8 to 2.1.10) sets different requirements for domains that + are not used to send email, but leaves it to the auditor to say which domains those are. Maester does not + guess from DNS: a domain is parked only when it is listed in the check's ParkedDomains parameter. The + comparison ignores case and a trailing dot. + + .PARAMETER DomainName + The accepted domain to look up. + + .PARAMETER ParkedDomains + The domains the admin listed as parked. + #> + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [string]$DomainName, + + [string[]]$ParkedDomains = @() + ) + + $name = $DomainName.TrimEnd('.') + return @($ParkedDomains | Where-Object { + $_ -and [string]::Equals($_.Trim().TrimEnd('.'), $name, [System.StringComparison]::OrdinalIgnoreCase) + }).Count -gt 0 +} diff --git a/powershell/internal/services/exchange/Resolve-MtDnsRecord.ps1 b/powershell/internal/services/exchange/Resolve-MtDnsRecord.ps1 new file mode 100644 index 0000000000..7cb1914d83 --- /dev/null +++ b/powershell/internal/services/exchange/Resolve-MtDnsRecord.ps1 @@ -0,0 +1,153 @@ +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. + All lookup outcomes are cached until Clear-MtDnsCache resets the session snapshot. + Queries use absolute DNS names so suffix search policies cannot change the cached identity. + Cached results are shared read-only objects and retain the first caller's Name spelling. + + .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 + ) + + if ($null -eq $__MtSession.DnsRecordCache) { + $__MtSession.DnsRecordCache = @{} + } + + $queryName = "$($Name.TrimEnd('.'))." + $cacheKey = "$($Type.ToUpperInvariant())|$($queryName.ToLowerInvariant())" + if ($__MtSession.DnsRecordCache.ContainsKey($cacheKey)) { + Write-Verbose "DNS record exists in cache for $Type $Name - Use Clear-MtDnsCache to reset" + return $__MtSession.DnsRecordCache[$cacheKey] + } + + $result = [pscustomobject]@{ + Name = $Name + Type = $Type + Status = 'Success' + Answers = [object[]]@() + Error = $null + } + $answers = @() + + if ($IsWindows) { + try { + $response = Resolve-DnsName -Name $queryName -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' + $__MtSession.DnsRecordCache[$cacheKey] = $result + 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 = "$_" + } + $__MtSession.DnsRecordCache[$cacheKey] = $result + return $result + } + } else { + if (-not (Get-Command -Name 'Resolve-Dns' -ErrorAction SilentlyContinue)) { + $result.Status = 'NotAvailable' + $result.Error = 'Missing dependency, Resolve-Dns not available' + $__MtSession.DnsRecordCache[$cacheKey] = $result + return $result + } + + try { + $response = Resolve-Dns -Query $queryName -QueryType $Type -ErrorAction Stop + if ($response.HasError) { + if ("$($response.Header.ResponseCode)" -eq 'NotExistentDomain') { + $result.Status = 'NXDomain' + } else { + $result.Status = 'Error' + $result.Error = $response.ErrorMessage + } + $__MtSession.DnsRecordCache[$cacheKey] = $result + return $result + } + $answers = @($response.Answers | Where-Object { "$($_.RecordType)" -eq $Type }) + } catch { + $result.Status = 'Error' + $result.Error = "$_" + $__MtSession.DnsRecordCache[$cacheKey] = $result + 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 ($Type -ne 'TXT' -and [string]::IsNullOrWhiteSpace([string]$value))) { + $result.Status = 'Error' + $result.Error = "The DNS resolver returned an unusable $Type answer for $Name." + $result.Answers = [object[]]@() + $__MtSession.DnsRecordCache[$cacheKey] = $result + return $result + } + + $result.Answers += [pscustomobject]@{ + Value = [string]$value + Preference = $preference + } + } + + $__MtSession.DnsRecordCache[$cacheKey] = $result + return $result +} 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/public/connect/Clear-MtDnsCache.ps1 b/powershell/public/connect/Clear-MtDnsCache.ps1 index 26076559f5..3d4eec04ea 100644 --- a/powershell/public/connect/Clear-MtDnsCache.ps1 +++ b/powershell/public/connect/Clear-MtDnsCache.ps1 @@ -23,4 +23,5 @@ Write-Verbose -Message "Clearing the results cached from DNS lookups in this session" $__MtSession.DnsCache = @() + $__MtSession.DnsRecordCache = @{} } diff --git a/powershell/tests/functions/Resolve-MtDnsRecord.Tests.ps1 b/powershell/tests/functions/Resolve-MtDnsRecord.Tests.ps1 new file mode 100644 index 0000000000..f367d9bb4e --- /dev/null +++ b/powershell/tests/functions/Resolve-MtDnsRecord.Tests.ps1 @@ -0,0 +1,338 @@ +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 { + Clear-MtDnsCache + 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 'keeps an empty TXT record without discarding other answers' { + Mock Resolve-DnsName -ModuleName Maester { + @( + [pscustomobject]@{ Section = 'Answer'; Type = 'TXT'; Strings = @('') } + [pscustomobject]@{ Section = 'Answer'; Type = 'TXT'; Strings = @('v=spf1 -all') } + ) + } + + $result = Resolve-MtDnsRecord -Name 'example.com' -Type TXT + + $result.Status | Should -Be 'Success' + $result.Answers.Count | Should -Be 2 + $result.Answers.Value | Should -Contain '' + $result.Answers.Value | Should -Contain 'v=spf1 -all' + } + + It 'caches results by case-insensitive DNS name and record type' { + Mock Resolve-DnsName -ModuleName Maester { + [pscustomobject]@{ Section = 'Answer'; Type = 'TXT'; Strings = @('v=spf1 -all') } + } + + $first = Resolve-MtDnsRecord -Name 'Example.com' -Type TXT + $second = Resolve-MtDnsRecord -Name 'example.COM.' -Type TXT + + $second.Answers[0].Value | Should -Be $first.Answers[0].Value + [object]::ReferenceEquals($first, $second) | Should -BeTrue + $second.Name | Should -Be 'Example.com' + Should -Invoke Resolve-DnsName -ModuleName Maester -Exactly 1 -ParameterFilter { + $Name -eq 'Example.com.' -and $Type -eq 'TXT' + } + + Clear-MtDnsCache + $null = Resolve-MtDnsRecord -Name 'example.com' -Type TXT + + Should -Invoke Resolve-DnsName -ModuleName Maester -Exactly 2 -ParameterFilter { + $Type -eq 'TXT' + } + } + + It 'caches outcomes until explicitly cleared' -ForEach @( + @{ Status = 'Success'; ErrorId = 'DNS_INFO_NO_RECORDS' } + @{ Status = 'NXDomain'; ErrorId = 'DNS_ERROR_RCODE_NAME_ERROR' } + @{ Status = 'Error'; ErrorId = 'DNS_ERROR_RCODE_SERVER_FAILURE' } + @{ Status = 'NotAvailable'; ErrorId = 'MissingResolver' } + ) { + Mock Resolve-DnsName -ModuleName Maester { + if ($Status -eq 'NotAvailable') { + throw [System.Management.Automation.CommandNotFoundException]::new('Resolver unavailable.') + } + throw [System.Management.Automation.ErrorRecord]::new( + [System.Exception]::new('Negative DNS test result.'), + $ErrorId, + [System.Management.Automation.ErrorCategory]::ResourceUnavailable, + $null + ) + } + + $first = Resolve-MtDnsRecord -Name 'negative.example' -Type MX + Mock Resolve-DnsName -ModuleName Maester { + [pscustomobject]@{ Section = 'Answer'; Type = 'MX'; NameExchange = 'mail.example.com'; Preference = 10 } + } + $cached = Resolve-MtDnsRecord -Name 'negative.example' -Type MX + + $first.Status | Should -Be $Status + $cached.Status | Should -Be $Status + $cached.Error | Should -Be $first.Error + $cached.Answers.Count | Should -Be 0 + Should -Invoke Resolve-DnsName -ModuleName Maester -Exactly 1 + + Clear-MtDnsCache + $refreshed = Resolve-MtDnsRecord -Name 'negative.example' -Type MX + + $refreshed.Status | Should -Be 'Success' + $refreshed.Answers[0].Value | Should -Be 'mail.example.com' + Should -Invoke Resolve-DnsName -ModuleName Maester -Exactly 2 + } + + 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 + + Clear-MtDnsCache + 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 'missing.example' -Type MX + + $missing.Status | Should -Be 'NXDomain' + $unavailable.Status | Should -Be 'Error' + Should -Invoke Resolve-DnsName -ModuleName Maester -Exactly 2 + } +} + +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 "Resolve-Dns was called without a mock (query '$Query', type '$QueryType', server '$NameServer')." + } + $true + } else { + $false + } + } + } + + AfterAll { + if ($script:createdDnsStub) { + & (Get-Module Maester) { Remove-Item -Path 'Function:script:Resolve-Dns' } + } + } + + BeforeEach { + Clear-MtDnsCache + 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 'keeps an empty TXT record without discarding other answers' { + Mock Resolve-Dns -ModuleName Maester { + [pscustomobject]@{ + HasError = $false + Header = [pscustomobject]@{ ResponseCode = 'NoError' } + Answers = @( + [pscustomobject]@{ RecordType = 'TXT'; Text = @('') } + [pscustomobject]@{ RecordType = 'TXT'; Text = @('v=spf1 -all') } + ) + } + } + + $result = Resolve-MtDnsRecord -Name 'example.com' -Type TXT + + $result.Status | Should -Be 'Success' + $result.Answers.Count | Should -Be 2 + $result.Answers.Value | Should -Contain '' + $result.Answers.Value | Should -Contain 'v=spf1 -all' + } + + It 'caches results by case-insensitive DNS name and record type' { + Mock Resolve-Dns -ModuleName Maester { + [pscustomobject]@{ + HasError = $false + Header = [pscustomobject]@{ ResponseCode = 'NoError' } + Answers = @([pscustomobject]@{ RecordType = 'TXT'; Text = @('v=spf1 -all') }) + } + } + + $first = Resolve-MtDnsRecord -Name 'Example.com' -Type TXT + $second = Resolve-MtDnsRecord -Name 'example.COM.' -Type TXT + + $second.Answers[0].Value | Should -Be $first.Answers[0].Value + [object]::ReferenceEquals($first, $second) | Should -BeTrue + $second.Name | Should -Be 'Example.com' + Should -Invoke Resolve-Dns -ModuleName Maester -Exactly 1 -ParameterFilter { + $Query -eq 'Example.com.' -and $QueryType -eq 'TXT' + } + + Clear-MtDnsCache + $null = Resolve-MtDnsRecord -Name 'example.com' -Type TXT + + Should -Invoke Resolve-Dns -ModuleName Maester -Exactly 2 -ParameterFilter { + $QueryType -eq 'TXT' + } + } + + It 'caches outcomes until explicitly cleared' -ForEach @( + @{ Status = 'Success'; ResponseCode = 'NoError'; HasError = $false } + @{ Status = 'NXDomain'; ResponseCode = 'NotExistentDomain'; HasError = $true } + @{ Status = 'Error'; ResponseCode = 'ServerFailure'; HasError = $true } + ) { + Mock Resolve-Dns -ModuleName Maester { + [pscustomobject]@{ + HasError = $HasError + Header = [pscustomobject]@{ ResponseCode = $ResponseCode } + ErrorMessage = 'Negative DNS test result.' + Answers = @() + } + } + + $first = Resolve-MtDnsRecord -Name 'negative.example' -Type MX + Mock Resolve-Dns -ModuleName Maester { + [pscustomobject]@{ + HasError = $false + Header = [pscustomobject]@{ ResponseCode = 'NoError' } + Answers = @([pscustomobject]@{ RecordType = 'MX'; Exchange = 'mail.example.com'; Preference = 10 }) + } + } + $cached = Resolve-MtDnsRecord -Name 'negative.example' -Type MX + + $first.Status | Should -Be $Status + $cached.Status | Should -Be $Status + $cached.Error | Should -Be $first.Error + $cached.Answers.Count | Should -Be 0 + Should -Invoke Resolve-Dns -ModuleName Maester -Exactly 1 + + Clear-MtDnsCache + $refreshed = Resolve-MtDnsRecord -Name 'negative.example' -Type MX + + $refreshed.Status | Should -Be 'Success' + $refreshed.Answers[0].Value | Should -Be 'mail.example.com' + Should -Invoke Resolve-Dns -ModuleName Maester -Exactly 2 + } + + 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 + + Clear-MtDnsCache + Mock Resolve-Dns -ModuleName Maester { + [pscustomobject]@{ + HasError = $true + Header = [pscustomobject]@{ ResponseCode = 'ServerFailure' } + ErrorMessage = 'Server Failure' + Answers = @() + } + } + + $unavailable = Resolve-MtDnsRecord -Name 'missing.example' -Type MX + + $missing.Status | Should -Be 'NXDomain' + $unavailable.Status | Should -Be 'Error' + $unavailable.Error | Should -Be 'Server Failure' + Should -Invoke Resolve-Dns -ModuleName Maester -Exactly 2 + } +} diff --git a/powershell/tests/functions/Test-MtCisDmarcRecordsPublished.Tests.ps1 b/powershell/tests/functions/Test-MtCisDmarcRecordsPublished.Tests.ps1 index 75200ec0e9..018e76f144 100644 --- a/powershell/tests/functions/Test-MtCisDmarcRecordsPublished.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisDmarcRecordsPublished.Tests.ps1 @@ -4,20 +4,53 @@ . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" Use-MtModuleFunction -Name Test-MtCisDmarcRecordsPublished + $script:parkedDmarcRecord = [pscustomobject]@{ + valid = $true + policy = 'reject' + policySubdomain = $null + percentage = 100 + reportAggregate = @() + reportForensic = @() + } + $script:quarantineDmarcRecord = [pscustomobject]@{ + valid = $true + policy = 'quarantine' + policySubdomain = $null + percentage = 100 + reportAggregate = @() + reportForensic = @() + } + $script:fullyCompliantDmarcRecord = [pscustomobject]@{ + valid = $true + policy = 'reject' + policySubdomain = $null + percentage = 100 + reportAggregate = @([pscustomobject]@{ mailAddress = 'reports@example.com' }) + reportForensic = @([pscustomobject]@{ mailAddress = 'forensic@example.com' }) + } + $script:domains = @() $script:registrableDomains = @{} $script:dmarcResults = @{} + $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 Add-MtTestResultDetail -ModuleName Maester { + $script:resultDetail = [pscustomobject]@{ Result = $Result; Investigate = [bool]$Investigate; SkippedBecause = $SkippedBecause } + } } BeforeEach { $script:domains = @() $script:registrableDomains = @{} $script:dmarcResults = @{} + $script:dkimSigningConfigs = @() + $script:resultDetail = $null } It 'fails a known noncompliant domain before skipping an unavailable lookup' { @@ -43,6 +76,30 @@ } } + It 'returns when another DMARC lookup is unavailable' -ForEach @( + @{ Outcome = 'a failure'; Parked = @(); ExpectedResult = $false; ExpectedSkip = $null } + @{ Outcome = 'NotSupported'; Parked = @('example.com'); ExpectedResult = $null; ExpectedSkip = 'NotSupported' } + ) { + $script:domains = @( + [pscustomobject]@{ DomainName = 'example.com'; IsCoExistenceDomain = $false } + [pscustomobject]@{ DomainName = 'unavailable.example'; IsCoExistenceDomain = $false } + ) + $script:registrableDomains = @{ + 'example.com' = 'example.com' + 'unavailable.example' = 'unavailable.example' + } + $script:dmarcResults = @{ + 'example.com' = $script:parkedDmarcRecord + 'unavailable.example' = 'DNS lookup unavailable' + } + + Test-MtCisDmarcRecordsPublished -ParkedDomains $Parked | Should -Be $ExpectedResult + $script:resultDetail.SkippedBecause | Should -Be $ExpectedSkip + if ($null -eq $ExpectedSkip) { + $script:resultDetail.Result | Should -Match '\| unavailable\.example .* \| Not checked \|' + } + } + It 'looks up the organizational domain after an invalid subdomain record and reports an invalid effective record' { $script:domains = @([pscustomobject]@{ DomainName = 'mail.example.com'; IsCoExistenceDomain = $false }) $script:registrableDomains = @{ 'mail.example.com' = 'example.com' } @@ -59,4 +116,61 @@ $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 } + + Test-MtCisDmarcRecordsPublished -ParkedDomains 'parked.example' | Should -BeTrue + $script:resultDetail.Investigate | Should -BeFalse + $script:resultDetail.Result | Should -Match '\| parked\.example \| Parked \|' + } + + It 'binds ParkedDomains from ' -ForEach @( + @{ Source = 'Setting'; Config = @{}; Classification = 'Parked'; ExpectedResult = $true } + @{ Source = 'Config'; Config = @{ ParkedDomains = @() }; Classification = 'Sending'; ExpectedResult = $false } + ) { + $script:domains = @([pscustomobject]@{ DomainName = 'parked.example'; IsCoExistenceDomain = $false }) + $script:registrableDomains = @{ 'parked.example' = 'parked.example' } + $script:dmarcResults = @{ 'parked.example' = $script:parkedDmarcRecord } + $binding = InModuleScope Maester -Parameters @{ Config = $Config } { + ConvertTo-MtTestParameter -Test (Get-MtTest 'CIS.M365.2.1.10') -ConfigValue $Config -GlobalSetting @{ ParkedDomains = @('parked.example') } + } + $binding.Error | Should -BeNullOrEmpty + ($binding.Effective | Where-Object Name -EQ 'ParkedDomains').Source | Should -Be $Source + $parameters = $binding.Bound + + Test-MtCisDmarcRecordsPublished @parameters | Should -Be $ExpectedResult + $script:resultDetail.Result | Should -Match "\| parked\.example \| $Classification \|" + } + + 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 } + + Test-MtCisDmarcRecordsPublished -ParkedDomains 'parked.example' | Should -BeFalse + $script:resultDetail.Result | Should -Match 'Parked-domain policy is reject' + } + + It 'applies the sending-domain audit to a domain that is not listed' { + $script:domains = @([pscustomobject]@{ DomainName = 'parked.example'; IsCoExistenceDomain = $false }) + $script:registrableDomains = @{ 'parked.example' = 'parked.example' } + $script:dmarcResults = @{ 'parked.example' = $script:parkedDmarcRecord } + + Test-MtCisDmarcRecordsPublished | Should -BeFalse + $script:resultDetail.Result | Should -Match '\| parked\.example \| Sending \|' + $script:resultDetail.Result | Should -Match 'Aggregate reports \(rua\)' + } + + It 'accepts a fully compliant DMARC record for a sending domain' { + $script:domains = @([pscustomobject]@{ DomainName = 'sending.example'; IsCoExistenceDomain = $false }) + $script:registrableDomains = @{ 'sending.example' = 'sending.example' } + $script:dmarcResults = @{ 'sending.example' = $script:fullyCompliantDmarcRecord } + + Test-MtCisDmarcRecordsPublished | Should -BeTrue + $script:resultDetail.Investigate | Should -BeFalse + $script:resultDetail.Result | Should -Match 'Well done\. All accepted domains meet' + } } diff --git a/powershell/tests/functions/Test-MtCisSpfRecordsPublished.Tests.ps1 b/powershell/tests/functions/Test-MtCisSpfRecordsPublished.Tests.ps1 new file mode 100644 index 0000000000..a5cf7a5d35 --- /dev/null +++ b/powershell/tests/functions/Test-MtCisSpfRecordsPublished.Tests.ps1 @@ -0,0 +1,147 @@ +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 @() + } + Mock ConvertFrom-MailAuthenticationRecordSpf -ModuleName Maester { $script:spfResults[$DomainName] } + 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:spfResults = @{} + $script:resultDetail = $null + } + + It 'requires a hard-fail SPF record for a parked domain' { + $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 ~all' } + + Test-MtCisSpfRecordsPublished -ParkedDomains 'example.com' | Should -BeFalse + $script:resultDetail.Result | Should -Match 'CIS requires v=spf1 -all' + $script:resultDetail.Result | Should -Match '\| example\.com \| Parked \|' + } + + It 'accepts for a parked domain' -ForEach @( + @{ Record = 'v=spf1 -all' } + @{ Record = 'V=SPF1 -ALL ' } + @{ Record = 'v=spf1 exp=why.example.com -all' } + @{ Record = 'v=spf1 exp=explain._spf.%{d} -all' } + @{ Record = 'v=spf1 exp=%{ir}.%{v}.%{d2r-}.example.com -all' } + @{ Record = 'V=SPF1 EXP=%{S}.%{L1R+}.example.com. -ALL' } + @{ Record = 'v=spf1 exp=why%%.%_.%-.example.com -all' } + @{ Record = 'v=spf1 exp=why.example.xn--p1ai -all' } + ) { + $script:spfResults['example.com'] = [pscustomobject]@{ record = $Record } + + Test-MtCisSpfRecordsPublished -ParkedDomains 'Example.com.' | Should -BeTrue + $script:resultDetail.Investigate | Should -BeFalse + } + + It 'rejects for a parked domain' -ForEach @( + @{ Record = 'v=spf1 include:spf.protection.outlook.com -all' } + @{ Record = 'v=spf1 redirect=_spf.example.net' } + @{ Record = 'v=spf1 -all exp=why.example.com' } + @{ Record = 'v=spf1 exp=a.example exp=b.example -all' } + @{ Record = 'v=spf1 exp=%(d).example.com -all' } + @{ Record = 'v=spf1 exp=%{d.example.com -all' } + @{ Record = 'v=spf1 exp=%{x}.example.com -all' } + @{ Record = 'v=spf1 exp=%{d2rr}.example.com -all' } + @{ Record = 'v=spf1 exp=%{d:}.example.com -all' } + @{ Record = 'v=spf1 exp=why%.example.com -all' } + @{ Record = 'v=spf1 exp=%{c}.example.com -all' } + @{ Record = 'v=spf1 exp=why.example.123 -all' } + @{ Record = 'v=spf1 exp=why.example.com- -all' } + @{ Record = 'v=spf1 exp= -all' } + @{ Record = 'v=spf10 exp=%{d} -all' } + @{ Record = 'v=spf1 exp=%{d} ~all' } + ) { + $script:spfResults['example.com'] = [pscustomobject]@{ record = $Record } + $script:spfResults['_spf.example.net'] = [pscustomobject]@{ record = 'v=spf1 -all' } + + Test-MtCisSpfRecordsPublished -ParkedDomains 'example.com' | Should -BeFalse + } + + It 'fails a parked redirect without resolving an unavailable target' { + $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 redirect=_spf.example.net' } + $script:spfResults['_spf.example.net'] = 'DNS lookup unavailable' + + Test-MtCisSpfRecordsPublished -ParkedDomains 'example.com' | Should -BeFalse + Should -Invoke ConvertFrom-MailAuthenticationRecordSpf -ModuleName Maester -Times 1 -Exactly + } + + It 'applies the sending-domain rule to a domain that is not listed' { + $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 ~all' } + + Test-MtCisSpfRecordsPublished | Should -BeTrue + $script:resultDetail.Investigate | Should -BeFalse + $script:resultDetail.Result | Should -Match '\| example\.com \| Sending \|' + } + + It 'binds ParkedDomains from ' -ForEach @( + @{ Source = 'Setting'; Config = @{}; Classification = 'Parked'; ExpectedResult = $false } + @{ Source = 'Config'; Config = @{ ParkedDomains = @() }; Classification = 'Sending'; ExpectedResult = $true } + ) { + $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 ~all' } + $binding = InModuleScope Maester -Parameters @{ Config = $Config } { + ConvertTo-MtTestParameter -Test (Get-MtTest 'CIS.M365.2.1.8') -ConfigValue $Config -GlobalSetting @{ ParkedDomains = @('example.com') } + } + $binding.Error | Should -BeNullOrEmpty + ($binding.Effective | Where-Object Name -EQ 'ParkedDomains').Source | Should -Be $Source + $parameters = $binding.Bound + + Test-MtCisSpfRecordsPublished @parameters | Should -Be $ExpectedResult + $script:resultDetail.Result | Should -Match "\| example\.com \| $Classification \|" + } + + It 'keeps the soft-fail rule for sending domains' { + $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 include:spf.example.net ~all' } + + Test-MtCisSpfRecordsPublished | Should -BeTrue + $script:resultDetail.Result | Should -Match 'Well done\. All custom domains meet' + } + + It 'requires the all qualifier to be the final sending-domain term' { + $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 include:spf.example.net -all include:vendor.example' } + + Test-MtCisSpfRecordsPublished | Should -BeFalse + } + + It 'rejects a sending-domain record with an earlier all mechanism' { + $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 all include:vendor.example -all' } + + Test-MtCisSpfRecordsPublished | Should -BeFalse + } + + It 'follows a redirect for a sending domain' { + $script:spfResults['example.com'] = [pscustomobject]@{ record = 'v=spf1 redirect=_spf.example.net' } + $script:spfResults['_spf.example.net'] = [pscustomobject]@{ record = 'v=spf1 include:spf.protection.outlook.com -all' } + + Test-MtCisSpfRecordsPublished | Should -BeTrue + } + + It 'returns when another SPF lookup is unavailable' -ForEach @( + @{ Outcome = 'a failure'; Record = 'v=spf1 ?all'; ExpectedResult = $false; ExpectedSkip = $null } + @{ Outcome = 'NotSupported'; Record = 'v=spf1 ~all'; ExpectedResult = $null; ExpectedSkip = 'NotSupported' } + ) { + $script:domains += [pscustomobject]@{ DomainName = 'unavailable.example'; InitialDomain = $false; IsCoExistenceDomain = $false } + $script:spfResults['example.com'] = [pscustomobject]@{ record = $Record } + $script:spfResults['unavailable.example'] = 'DNS lookup unavailable' + + Test-MtCisSpfRecordsPublished | Should -Be $ExpectedResult + $script:resultDetail.SkippedBecause | Should -Be $ExpectedSkip + if ($null -eq $ExpectedSkip) { + $script:resultDetail.Result | Should -Match '\| unavailable\.example .* \| Not checked \|' + } + } +} diff --git a/powershell/tests/functions/Test-MtCisaDmarcRecordExist.Tests.ps1 b/powershell/tests/functions/Test-MtCisaDmarcRecordExist.Tests.ps1 index efcb91bab4..d8930e079e 100644 --- a/powershell/tests/functions/Test-MtCisaDmarcRecordExist.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisaDmarcRecordExist.Tests.ps1 @@ -347,6 +347,10 @@ Describe 'CISA.MS.EXO.4.1 with DNS mocked' { } Describe 'Resolve-MtDnsTxtRecord' { + BeforeEach { + Clear-MtDnsCache + } + Context 'with Resolve-Dns from DnsClient-PS' -Skip:$IsWindows { BeforeAll { $script:createdStub = $false @@ -384,7 +388,7 @@ Describe 'Resolve-MtDnsTxtRecord' { $result.Status | Should -Be 'Success' $result.Answers | Should -Be @('v=DMARC1; p=reject; rua=mailto:reports@contoso.com', 'some unrelated TXT record') - Should -Invoke -ModuleName Maester Resolve-Dns -Exactly 1 -ParameterFilter { $Query -eq '_dmarc.contoso.com' -and $QueryType -eq 'TXT' } + Should -Invoke -ModuleName Maester Resolve-Dns -Exactly 1 -ParameterFilter { $Query -eq '_dmarc.contoso.com.' -and $QueryType -eq 'TXT' } } It 'returns no answers when the name has no TXT records' { @@ -464,7 +468,7 @@ Describe 'Resolve-MtDnsTxtRecord' { $result.Status | Should -Be 'Success' $result.Answers | Should -Be @('v=DMARC1; p=reject; rua=mailto:reports@contoso.com', 'some unrelated TXT record') - Should -Invoke -ModuleName Maester Resolve-DnsName -Exactly 1 -ParameterFilter { $Name -eq '_dmarc.contoso.com' -and $Type -eq 'TXT' } + Should -Invoke -ModuleName Maester Resolve-DnsName -Exactly 1 -ParameterFilter { $Name -eq '_dmarc.contoso.com.' -and $Type -eq 'TXT' } } It 'reports NXDomain when the name does not exist' { diff --git a/powershell/tests/functions/Test-MtDkim.Tests.ps1 b/powershell/tests/functions/Test-MtDkim.Tests.ps1 index fc8387f904..b7ffc66ad8 100644 --- a/powershell/tests/functions/Test-MtDkim.Tests.ps1 +++ b/powershell/tests/functions/Test-MtDkim.Tests.ps1 @@ -12,6 +12,9 @@ Describe 'DKIM checks with no signing configuration' -ForEach @( BeforeEach { Mock -ModuleName Maester Test-MtConnection { return $true } Mock -ModuleName Maester Add-MtTestResultDetail { } + Mock -ModuleName Maester Resolve-MtDnsRecord { + [PSCustomObject]@{ Name = $Name; Type = $Type; Status = 'NXDomain'; Answers = [object[]]@() } + } Mock -ModuleName Maester Get-MailAuthenticationRecord { throw 'DNS lookup should not be attempted without a DKIM signing configuration' } @@ -48,7 +51,7 @@ Describe 'DKIM checks with no signing configuration' -ForEach @( # Test-MtCisaDkim does not read SendingFromDomainDisabled: MS.EXO.3.1v1 asks for DKIM on every # domain, so a domain that cannot send is checked like any other. ExpectedResultByCommand = @{ - 'Test-MtCisDkim' = $null + 'Test-MtCisDkim' = $true 'Test-MtCisaDkim' = $false } } @@ -99,7 +102,8 @@ Describe 'DKIM checks with no signing configuration' -ForEach @( $expectedResult = $ExpectedResultByCommand[$CommandName] - $result = & $CommandName + $parameters = if ($CommandName -eq 'Test-MtCisDkim' -and $DomainName -eq 'parked.example') { @{ ParkedDomains = 'parked.example' } } else { @{} } + $result = & $CommandName @parameters if ($null -eq $expectedResult) { $result | Should -BeNullOrEmpty } else { @@ -109,6 +113,113 @@ Describe 'DKIM checks with no signing configuration' -ForEach @( } } +Describe 'CIS DKIM with ParkedDomains' { + BeforeEach { + $script:acceptedDomains = @([PSCustomObject]@{ DomainName = 'parked.example'; InitialDomain = $false; IsCoexistenceDomain = $false }) + # Name -> status for the selector lookups; anything not listed is NXDomain. + $script:selectorStatus = @{} + $script:selectorRecords = @{} + 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 $script:acceptedDomains } + return @() + } + Mock -ModuleName Maester Get-MailAuthenticationRecord { throw 'No Exchange DKIM lookup should be needed for a parked domain.' } + Mock -ModuleName Maester Resolve-MtDnsRecord { + $key = "$Type|$Name" + $status = if ($script:selectorStatus.ContainsKey($key)) { $script:selectorStatus[$key] } elseif ($script:selectorRecords.ContainsKey($key)) { 'Success' } else { 'NXDomain' } + $answers = if ($script:selectorRecords.ContainsKey($key)) { [object[]]@([PSCustomObject]@{ Value = $script:selectorRecords[$key] }) } else { [object[]]@() } + [PSCustomObject]@{ Name = $Name; Type = $Type; Status = $status; Answers = $answers } + } + } + + It 'checks a domain against the sending-domain audit unless it is listed' { + Test-MtCisDkim | Should -BeFalse + $script:detail.Result | Should -Match '\| parked\.example \| Sending \|' + Should -Invoke Resolve-MtDnsRecord -ModuleName Maester -Exactly 0 + } + + It 'binds ParkedDomains from ' -ForEach @( + @{ Source = 'Setting'; Config = @{}; Classification = 'Parked'; ExpectedResult = $true } + @{ Source = 'Config'; Config = @{ ParkedDomains = @() }; Classification = 'Sending'; ExpectedResult = $false } + ) { + $binding = InModuleScope Maester -Parameters @{ Config = $Config } { + ConvertTo-MtTestParameter -Test (Get-MtTest 'CIS.M365.2.1.9') -ConfigValue $Config -GlobalSetting @{ ParkedDomains = @('parked.example') } + } + $binding.Error | Should -BeNullOrEmpty + ($binding.Effective | Where-Object Name -EQ 'ParkedDomains').Source | Should -Be $Source + $parameters = $binding.Bound + + Test-MtCisDkim @parameters | Should -Be $ExpectedResult + $script:detail.Result | Should -Match "\| parked\.example \| $Classification \|" + } + + It 'passes a listed domain with no selector records' { + Test-MtCisDkim -ParkedDomains 'PARKED.example.' | Should -BeTrue + $script:detail.Result | Should -Match '\| parked\.example \| Parked \|' + $script:detail.Result | Should -Match 'Well done' + Should -Invoke Resolve-MtDnsRecord -ModuleName Maester -Exactly 4 + } + + It 'fails a listed domain that publishes a selector record' { + $script:selectorRecords['CNAME|selector1._domainkey.parked.example'] = 'selector1-parked-example._domainkey.contoso.onmicrosoft.com' + + Test-MtCisDkim -ParkedDomains 'parked.example' | Should -BeFalse + $script:detail.Result | Should -Match 'a selector1 or selector2 DKIM record is published' + } + + It 'fails a listed domain with a selector record even when another lookup failed' { + $script:selectorRecords['TXT|selector2._domainkey.parked.example'] = 'v=DKIM1; p=abc' + $script:selectorStatus['CNAME|selector1._domainkey.parked.example'] = 'Error' + + Test-MtCisDkim -ParkedDomains 'parked.example' | Should -BeFalse + $script:detail.Investigate | Should -BeFalse + } + + It 'investigates a listed domain when a selector lookup fails' { + $script:selectorStatus['CNAME|selector1._domainkey.parked.example'] = 'Error' + + Test-MtCisDkim -ParkedDomains 'parked.example' | Should -BeTrue + $script:detail.Investigate | Should -BeTrue + $script:detail.Result | Should -Match 'Compliance .* remains unconfirmed' + } + + It 'skips with NotSupported when DNS lookups are not available' { + foreach ($selector in 'selector1', 'selector2') { + foreach ($type in 'CNAME', 'TXT') { $script:selectorStatus["$type|$selector._domainkey.parked.example"] = 'NotAvailable' } + } + + Test-MtCisDkim -ParkedDomains 'parked.example' | Should -BeNullOrEmpty + $script:detail.SkippedBecause | Should -Be 'NotSupported' + } + + It 'reports a compliant parked domain alongside one that ' -ForEach @( + @{ OtherOutcome = 'needs investigation'; Status = 'Error'; ExpectedResult = $true; ExpectedInvestigation = $true; ExpectedUnconfirmed = $true } + @{ OtherOutcome = 'cannot be checked'; Status = 'NotAvailable'; ExpectedResult = $true; ExpectedInvestigation = $true; ExpectedUnconfirmed = $true } + @{ OtherOutcome = 'passes'; Status = $null; ExpectedResult = $true; ExpectedInvestigation = $false; ExpectedUnconfirmed = $false } + ) { + $script:acceptedDomains += [PSCustomObject]@{ DomainName = 'other.example'; InitialDomain = $false; IsCoexistenceDomain = $false } + if ($Status) { + foreach ($selector in 'selector1', 'selector2') { + foreach ($type in 'CNAME', 'TXT') { $script:selectorStatus["$type|$selector._domainkey.other.example"] = $Status } + } + } + + Test-MtCisDkim -ParkedDomains 'parked.example', 'other.example' | Should -Be $ExpectedResult + $script:detail.Investigate | Should -Be $ExpectedInvestigation + $script:detail.SkippedBecause | Should -BeNullOrEmpty + $script:detail.Result | Should -Match '\| parked\.example .*Pass' + if ($ExpectedUnconfirmed) { + $script:detail.Result | Should -Match 'Compliance .* remains unconfirmed' + $script:detail.Result | Should -Not -Match 'Well done' + } else { + $script:detail.Result | Should -Match 'Well done' + } + } +} + 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..7e461eb7c1 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 domains, which don't send email, 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 does not guess which domains are parked. CIS leaves that to the person running the audit, so set the shared `GlobalSettings.ParkedDomains` list in the Maester config for all three checks. A per-test `ParkedDomains` value in `TestSettings[].Parameters` overrides the shared list for that check. Every other domain gets the sending-domain audit. + +The engine binds this setting to the test parameter and validates entries as domain names. An explicit empty per-test list overrides the shared list, so every domain in that check receives the sending-domain audit. + +Parked domains use the CIS parked-domain requirement: a valid DMARC record with `p=reject`; rua, ruf and pct are not required. When the DNS lookup is not available for a domain, it is listed as Not checked. #### 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 domain, `v=DMARC1; p=reject` meets the parked-domain requirement; add the domain to `ParkedDomains`. 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..ea80235bc6 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. Domains listed in the ParkedDomains parameter require a valid record with p=reject. Every other domain gets the sending-domain audit. 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 @@ -28,17 +28,24 @@ Mitre = ('T1566', 'T1684.002'), Control = ('cis-m365:2.1.10', 'nist-800-53-r5:SI-8'), Service = 'ExchangeOnline', - Author = 'JeremyFinney-lgtm' + Author = 'JeremyFinney-lgtm', + Contributor = ('earbona23', 'merill') )] [CmdletBinding()] [OutputType([bool])] - param() + param( + # Domains that are not used to send email. They need a valid DMARC record with p=reject. + [MaesterParameter(Setting = 'ParkedDomains')] + [string[]]$ParkedDomains = @() + ) Write-Verbose 'Getting accepted domains...' $domains = @(Get-MtExo -Request AcceptedDomain | Where-Object { $_.IsCoExistenceDomain -eq $false }) $report = foreach ($domain in $domains) { $name = $domain.DomainName + $isParked = Test-MtCisParkedDomain -DomainName $name -ParkedDomains $ParkedDomains + $classification = if ($isParked) { 'Parked' } else { 'Sending' } $dmarc = $null $source = $null $unavailable = $false @@ -52,34 +59,42 @@ if ($found -eq 'Invalid DMARC record') { $invalidCandidate = $candidate } continue } - if ($null -ne $found -and $found.GetType().Name -eq 'DMARCRecord') { + if ($null -ne $found -and $found -isnot [string]) { $dmarc = $found $source = $candidate break } } if ($unavailable) { - [pscustomobject]@{ Domain = $name; Policy = 'Not checked'; Source = 'None'; Failed = 'DNS lookup not available'; Pass = $null } + [pscustomobject]@{ Domain = $name; Classification = $classification; 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 } } - $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 + $checks = if ($isParked) { + [ordered]@{ + 'Record is valid' = $null -ne $dmarc -and $dmarc.valid + 'Parked-domain policy is reject' = $policy -eq 'reject' + } + } else { + [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 }) [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 + 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 }) @@ -91,13 +106,14 @@ } $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) { '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) { diff --git a/tests/cis/Test.CIS.M365.2.1.8.md b/tests/cis/Test.CIS.M365.2.1.8.md index 75444fa9fd..8177c061c1 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 domains, which don't send email, must publish `v=spf1 -all`, which denies all senders. 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 does not guess which domains are parked. CIS leaves that to the person running the audit, so set the shared `GlobalSettings.ParkedDomains` list in the Maester config for all three checks. A per-test `ParkedDomains` value in `TestSettings[].Parameters` overrides the shared list for that check. Every other domain gets the sending-domain audit. + +The engine binds this setting to the test parameter and validates entries as domain names. An explicit empty per-test list overrides the shared list, so every domain in that check receives the sending-domain audit. + +For a parked domain the record must be `v=spf1 -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. + +An `exp=` modifier does not authorize senders. A parked-domain record may include one before `-all`, but its domain-spec must have valid RFC 7208 syntax: `exp=explain._spf.%{d}` is valid, while `exp=%(d).example.com` is not. The check validates syntax without expanding macros or looking up the explanation text. The audit still requires the compliant all mechanism to be the final term: `v=spf1 -all exp=why.example.com` does not meet that termination requirement. An earlier `all` mechanism ends SPF evaluation before a later qualifier, so a record such as `v=spf1 all include:vendor.example -all` does not meet the audit. #### 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 domain, publish `v=spf1 -all` and add the domain to `ParkedDomains`. 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 @@ -15,6 +21,7 @@ The test follows a redirect modifier only when the record has no all mechanism, * [Set up SPF to help prevent spoofing](https://learn.microsoft.com/defender-office-365/email-authentication-spf-configure) * [Email authentication in Microsoft 365](https://learn.microsoft.com/defender-office-365/email-authentication-about) * [CIS Microsoft 365 Foundations Benchmark v7.0.0 - 2.1.8](https://www.cisecurity.org/benchmark/microsoft_365) +* [RFC 7208 - SPF macro syntax](https://www.rfc-editor.org/rfc/rfc7208.html#section-7) %TestResult% diff --git a/tests/cis/Test.CIS.M365.2.1.8.ps1 b/tests/cis/Test.CIS.M365.2.1.8.ps1 index 4909a0d6f2..3da1f04bdb 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. Domains listed in the ParkedDomains parameter must publish v=spf1 -all, which denies all senders. Every other domain gets the sending-domain audit. 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 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 @@ -28,24 +28,46 @@ Mitre = ('T1566', 'T1684.002'), Control = ('cis-m365:2.1.8', 'nist-800-53-r5:SI-8'), Service = 'ExchangeOnline', - Author = 'JeremyFinney-lgtm' + Author = 'JeremyFinney-lgtm', + Contributor = ('earbona23', 'merill') )] [CmdletBinding()] [OutputType([bool])] - param() + param( + # Domains that are not used to send email. They must publish v=spf1 -all. + [MaesterParameter(Setting = 'ParkedDomains')] + [string[]]$ParkedDomains = @() + ) Write-Verbose 'Getting accepted domains...' $domains = @(Get-MtExo -Request AcceptedDomain | Where-Object { $_.InitialDomain -eq $false -and $_.IsCoExistenceDomain -eq $false }) $report = foreach ($domain in $domains) { $name = $domain.DomainName + $isParked = Test-MtCisParkedDomain -DomainName $name -ParkedDomains $ParkedDomains + $classification = if ($isParked) { 'Parked' } else { 'Sending' } $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; Pass = $null; Detail = 'DNS lookup not available' } + continue + } + $record = if ($spf -and $spf.PSObject.Properties['record']) { $spf.record } else { $null } + if ($isParked) { + # CIS asks parked domains for v=spf1 -all: no sender mechanisms, no redirect, hard fail last. + # RFC 7208 sections 7.1-7.2: validate exp's domain-spec, not the fetched explanation text. + $macroExpand = '%(?:\{[slodiphv][0-9]*r?[.\-+,/_=]*\}|[%_-])' + $macroString = "(?:$macroExpand|[\x21-\x24\x26-\x7E])*" + $domainEnd = "(?:\.(?:[a-z0-9]*[a-z][a-z0-9]*|[a-z0-9]+-[a-z0-9-]*[a-z0-9])\.?|$macroExpand)" + $pass = [string]$record -match "(?i)^\s*v=spf1(?:\s+exp=$macroString$domainEnd)?\s+-all\s*$" + $detail = if ($pass) { + 'Listed as parked; the record denies all senders with -all.' + } else { + 'Listed as parked; CIS requires v=spf1 -all, which denies all senders.' + } + [pscustomobject]@{ Domain = $name; Record = $record; Classification = $classification; Pass = $pass; Detail = $detail } continue } - $record = if ($spf.GetType().Name -eq 'SPFRecord') { $spf.record } else { $null } $effective = $record $redirectTargets = @() $redirectError = $null @@ -77,8 +99,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 +107,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; Pass = $null; 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 '-', '~' + $effectiveTerms = [string]$effective -split '\s+' + $allMechanisms = @($effectiveTerms | Where-Object { $_ -match '(?i)^[+?~-]?all$' }) + $effectiveAll = [regex]::Match([string]$effective, '(?i)(^|\s)(?[+?~-]?)all\s*$') + $pass = $effectiveAll.Success -and $effectiveAll.Groups['q'].Value -in '-', '~' -and $allMechanisms.Count -eq 1 if (-not $record) { $detail = 'No SPF record found' } elseif ($redirectError) { @@ -103,7 +126,8 @@ elseif (-not $pass) { $detail = 'The record does not end with -all or ~all' } - [pscustomobject]@{ Domain = $name; Record = $record; Pass = $pass; Detail = $detail } + + [pscustomobject]@{ Domain = $name; Record = $record; Classification = $classification; Pass = $pass; Detail = $detail } } $unchecked = @($report | Where-Object { $null -eq $_.Pass }) @@ -117,13 +141,14 @@ $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) { 'Not checked' } elseif ($row.Pass) { '✅ Pass' } else { '❌ Fail' } + $resultMd += "| $($row.Domain) | $($row.Classification) | $($row.Record) | $($row.Detail) | $resultText |`n" } if ($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..55a54832f5 100644 --- a/tests/cis/Test.CIS.M365.2.1.9.md +++ b/tests/cis/Test.CIS.M365.2.1.9.md @@ -12,7 +12,15 @@ 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**. +The check requires Exchange DKIM to be enabled and its status to be **Valid** for every domain except the parked domains you list. + +Maester does not guess which domains are parked. CIS leaves that to the person running the audit, so set the shared `GlobalSettings.ParkedDomains` list in the Maester config for all three checks. A per-test `ParkedDomains` value in `TestSettings[].Parameters` overrides the shared list for that check. Every other domain gets the sending-domain audit. + +The engine binds this setting to the test parameter and validates entries as domain names. An explicit empty per-test list overrides the shared list, so every domain in that check receives the sending-domain audit. + +For a parked domain, CIS asks that DKIM records are not published. The check passes when none of the selector1/selector2 CNAME or TXT records exist, and fails when one does. If some of those lookups fail, the domain is marked for investigation; if DNS lookups are not available at all, it is skipped. Only the standard Exchange Online selectors are checked. + +When a parked domain needs investigation or was skipped because DNS lookups are unavailable, the result says compliance is unconfirmed instead of showing a full-compliance banner. Known failures still take precedence. #### Remediation action @@ -46,6 +54,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 publish standard DKIM selector records. An unused Exchange signing configuration alone does not fail this audit; remove it if the domain no longer needs it. 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..5b53f381d5 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. + Domains require DKIM to be enabled with a valid Exchange status. Domains listed in the ParkedDomains parameter must not publish DKIM records instead. 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 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 domain has DKIM enabled with Exchange status Valid, and every domain listed in ParkedDomains has no selector1 or selector2 DKIM record. Initial and coexistence domains are excluded. .LINK https://maester.dev/docs/commands/Test-MtCisDkim @@ -31,28 +30,28 @@ Control = ('cis-m365:2.1.9', 'nist-800-53-r5:SC-8'), Service = 'ExchangeOnline', Author = 'NZLostboy', - Contributor = ('JeanPhilippeGeorge', 'brianreidc7', 'amlhive-tech') + Contributor = ('JeanPhilippeGeorge', 'brianreidc7', 'amlhive-tech', 'JeremyFinney-lgtm', 'earbona23', 'merill') )] [CmdletBinding()] [OutputType([bool])] param( # Selector-name for the DKIM record to test.. - [string]$Selector = 'selector1' + [string]$Selector = 'selector1', + + # Domains that are not used to send email. They must not publish DKIM records. + [MaesterParameter(Setting = 'ParkedDomains')] + [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 +61,37 @@ continue } + if (Test-MtCisParkedDomain -DomainName $domain.DomainName -ParkedDomains $ParkedDomains) { + # CIS: don't publish DKIM records for a parked domain. Exchange Online uses selector1 and selector2. + $selectorLookups = foreach ($selectorName in 'selector1', 'selector2') { + foreach ($recordType in 'CNAME', 'TXT') { + Resolve-MtDnsRecord -Name "$selectorName._domainkey.$($domain.DomainName)" -Type $recordType + } + } + $hasSelectorRecord = @($selectorLookups | Where-Object { @($_.Answers).Count -gt 0 }).Count -gt 0 + $incompleteLookups = @($selectorLookups | Where-Object { $_.Status -notin @('Success', 'NXDomain') }) + $resolverUnavailable = @($selectorLookups | Where-Object { $_.Status -ne 'NotAvailable' }).Count -eq 0 + + $pass, $reason = if ($hasSelectorRecord) { + 'Failed', 'Listed as parked, but a selector1 or selector2 DKIM record is published. Remove it.' + } elseif ($resolverUnavailable) { + 'NotSupported', 'Listed as parked, but DNS lookups are not available here, so the DKIM records could not be checked.' + } elseif ($incompleteLookups.Count -gt 0) { + 'Investigate', 'Listed as parked, but some DKIM selector lookups failed, so it could not be confirmed that no record is published.' + } else { + 'Passed', 'Listed as parked, and no selector1 or selector2 DKIM record is published.' + } + $dkimRecords += [PSCustomObject]@{ + domain = $domain.DomainName + classification = 'Parked' + pass = $pass + reason = $reason + exchangeStatus = 'Not applicable' + dkimRecord = $null + } + continue + } + $dkimSigningConfig = $dkimSigningConfigs | Where-Object { $_.domain -eq $domain.domainname } @@ -69,8 +99,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 = 'Sending' + pass = 'Failed' + reason = 'No DkimSigningConfig found. Add the domain to ParkedDomains if it does not send email.' exchangeStatus = 'Not configured' dkimRecord = $null } @@ -103,11 +134,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 'Sending' - 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') { @@ -122,7 +151,7 @@ } elseif ($domain.DomainName -like '*.onmicrosoft.com') { $dkimRecord.reason = "Recommendation: Disable sending from domain" } elseif ($dkimRecord.dkimRecord -like '*not available') { - $dkimRecord.pass = 'Skipped' + $dkimRecord.pass = 'NotSupported' $dkimRecord.reason = $dkimRecord.dkimRecord } else { $dkimRecord.reason = $dkimRecord.dkimRecord @@ -131,19 +160,31 @@ $dkimRecords += $dkimRecord } -if ('Failed' -in $dkimRecords.pass) { + if ('Failed' -in $dkimRecords.pass) { $testResult = $false - } elseif ('Failed' -notin $dkimRecords.pass -and 'Passed' -notin $dkimRecords.pass) { + } + elseif ('Investigate' -in $dkimRecords.pass) { + $testResult = $true + } + elseif ('NotSupported' -in $dkimRecords.pass -and 'Passed' -notin $dkimRecords.pass) { Add-MtTestResultDetail -SkippedBecause NotSupported return $null - } else { + } + elseif ('Passed' -notin $dkimRecords.pass) { + Add-MtTestResultDetail -SkippedBecause NotApplicable + return $null + } + else { $testResult = $true } $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%" + if ($testResult -and ('Investigate' -in $dkimRecords.pass -or 'NotSupported' -in $dkimRecords.pass)) { + $testResultMarkdown = "Compliance with the applicable CIS DKIM requirement remains unconfirmed. Review the domains marked Investigate or skipped because DNS lookups are unavailable.`n`n%TestResult%" + } + elseif ($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 +192,21 @@ 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 } + 'NotSupported' { $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 -or 'NotSupported' -in $dkimRecords.pass) -and 'Failed' -notin $dkimRecords.pass) return $testResult }