Rules/MAIL-002.dkim-enabled.psd1

@{
    Id          = 'MAIL-002'
    Title       = 'DKIM selectors are published for every custom mail domain'
    Area        = 'EmailAuthDns'
    Severity    = 'Medium'
    References  = @(
        'CIS Microsoft 365 Foundations Benchmark (DKIM signing)'
        'https://learn.microsoft.com/defender-office-365/email-authentication-dkim-configure'
    )
    Rationale   = 'DKIM cryptographically ties outgoing mail to the domain; DMARC alignment depends on it. Microsoft 365 uses the selector1/selector2 CNAME pair.'
    Remediation = 'Enable DKIM signing per mail domain in Microsoft Defender and publish both selector CNAME records.'
    Test        = {
        param($Snapshot)
        $customDomains = @($Snapshot.EmailAuthDns | Where-Object { -not $_.isOnMicrosoft })
        # Older snapshots have no isMailDomain field - treat those as mail domains.
        $mailDomains = @($customDomains | Where-Object {
                -not $_.PSObject.Properties['isMailDomain'] -or [bool]$_.isMailDomain
            })
        $nonMailDomains = @($customDomains | Where-Object {
                $_.PSObject.Properties['isMailDomain'] -and -not [bool]$_.isMailDomain
            })
        $notes = @()
        if ($nonMailDomains.Count -gt 0) {
            $notes = @('Not evaluated (no Email service): ' + (@($nonMailDomains | ForEach-Object { $_.domain }) -join ', ') + '.')
        }
        if ($mailDomains.Count -eq 0) {
            return New-TLRuleResult -Status Pass -Evidence (@('No custom mail domains to check.') + $notes)
        }
        $bad = @($mailDomains | Where-Object { -not ($_.dkim.selector1 -and $_.dkim.selector2) })
        if ($bad.Count -gt 0) {
            New-TLRuleResult -Status Fail -Evidence (@($bad | ForEach-Object { "$($_.domain): selector CNAMEs missing" }) + $notes)
        }
        else {
            New-TLRuleResult -Status Pass -Evidence (@($mailDomains | ForEach-Object { "$($_.domain): both selectors published" }) + $notes)
        }
    }
}