SHELL/8.2.1.ps1

$CheckId = "8.2.1"
$Title = "Ensure external domains are restricted in the Teams admin center"
$Level = "L2"
$BenchmarkType = "Automated"

function Convert-ToDomainText {
    param([AllowNull()]$Value)

    if ($null -eq $Value) { return $null }

    if ($Value -is [string]) { return $Value }

    if ($Value.PSObject.Properties.Match("Domain").Count -gt 0 -and $Value.Domain) {
        return [string]$Value.Domain
    }

    if ($Value.PSObject.Properties.Match("Name").Count -gt 0 -and $Value.Name) {
        return [string]$Value.Name
    }

    return [string]$Value
}

try {
    $GlobalPolicy = Get-CsExternalAccessPolicy -Identity Global -ErrorAction Stop
    $TenantFederation = Get-CsTenantFederationConfiguration -ErrorAction Stop

    $EnableFederationAccess = [bool]$GlobalPolicy.EnableFederationAccess
    $AllowFederatedUsers = [bool]$TenantFederation.AllowFederatedUsers
    $AllowedDomains = @($TenantFederation.AllowedDomains | ForEach-Object { Convert-ToDomainText $_ } | Where-Object { $_ })
    $AllowedDomainsNormalized = @($AllowedDomains | ForEach-Object { $_.Trim() } | Where-Object { $_ })

    $ContainsAllowAllKnownDomains = @($AllowedDomainsNormalized | Where-Object { $_ -match '(?i)^AllowAllKnownDomains$' }).Count -gt 0

    if (-not $AllowFederatedUsers) {
        $Pass = $true
        $Status = "PASS"
        $Reason = $null
    }
    else {
        $Pass = (-not $ContainsAllowAllKnownDomains) -and ($AllowedDomainsNormalized.Count -gt 0)
        $Status = if ($Pass) { "PASS" } else { "FAIL" }
        $Reason = if ($Pass) { $null } else { "AllowFederatedUsers is True but AllowedDomains is empty or includes AllowAllKnownDomains." }
    }

    [pscustomobject]@{
        CheckId = $CheckId
        Title = $Title
        Level = $Level
        BenchmarkType = $BenchmarkType
        Status = $Status
        Pass = $Pass
        Evidence = [pscustomobject]@{
            GlobalPolicy_EnableFederationAccess = $EnableFederationAccess
            TenantFederation_AllowFederatedUsers = $AllowFederatedUsers
            TenantFederation_AllowedDomains = $AllowedDomainsNormalized
            ContainsAllowAllKnownDomains = $ContainsAllowAllKnownDomains
            SourceDocument = "CIS_Microsoft_365_Foundations_Benchmark_v6.0.1"
        }
        Error = $Reason
        Timestamp = Get-Date
    }
}
catch {
    [pscustomobject]@{
        CheckId = $CheckId
        Title = $Title
        Level = $Level
        BenchmarkType = $BenchmarkType
        Status = "ERROR"
        Pass = $null
        Evidence = [pscustomobject]@{
            SourceDocument = "CIS_Microsoft_365_Foundations_Benchmark_v6.0.1"
        }
        Error = $_.Exception.Message
        Timestamp = Get-Date
    }
}