SpfLookupCount.psm1
|
function Get-SpfLookupCount { <# .SYNOPSIS Count the DNS lookups an SPF record needs (the limit is 10, RFC 7208 section 4.6.4). .DESCRIPTION Offline. Counts the terms that cost a lookup (include, a, mx, ptr, exists, redirect) in the record you pass. To count nested includes, pass the text of each included record in -Included (domain to record); an include that is not in that table is counted as one lookup and flagged as not expanded. .EXAMPLE Get-SpfLookupCount -Record 'v=spf1 include:_spf.google.com a mx -all' -Included @{ '_spf.google.com' = 'v=spf1 include:_netblocks.google.com -all' } #> [CmdletBinding()] param( [Parameter(Mandatory, ValueFromPipeline)][string]$Record, [hashtable]$Included = @{}, [int]$Limit = 10 ) process { $script:SpfSeen = @{} $notes = New-Object System.Collections.Generic.List[string] $count = 0 function Walk([string]$text, [int]$depth) { if ($depth -gt 10) { $notes.Add('stopped at depth 10 (possible include loop)'); return } $terms = ($text.Trim() -split '\s+') | Where-Object { $_ } if ($terms.Count -eq 0 -or $terms[0].ToLowerInvariant() -ne 'v=spf1') { $notes.Add("not an SPF record: '$($text.Substring(0, [Math]::Min(30, $text.Length)))'"); return } foreach ($t in $terms[1..($terms.Count - 1)]) { $m = $t -replace '^[+\-~?]', '' $name = ($m -split '[:=/]')[0].ToLowerInvariant() if ($name -in 'include', 'redirect') { $script:count++ $dom = ($m -split '[:=]', 2)[1] if ($Included.ContainsKey($dom)) { if ($script:SpfSeen.ContainsKey($dom)) { $notes.Add("include loop on $dom") } else { $script:SpfSeen[$dom] = 1; Walk $Included[$dom] ($depth + 1) } } else { $notes.Add("$dom not expanded (counted as 1; its own lookups are extra)") } } elseif ($name -in 'a', 'mx', 'ptr', 'exists') { $script:count++ } } } $script:count = 0 Walk $Record 0 $n = $script:count [pscustomobject]@{ Lookups = $n; Limit = $Limit; Over = ($n -gt $Limit); Notes = $notes.ToArray() } } } Export-ModuleMember -Function Get-SpfLookupCount |