| 1 | package Mail::DMARC::PurePerl; | ||
| 2 | our $VERSION = '2.20260827'; | ||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use feature 'signatures'; | ||
| 6 | use feature 'try'; | ||
| 7 | no warnings 'experimental::try'; ## no critic (ProhibitNoWarnings) | ||
| 8 | |||
| 9 | use Carp; | ||
| 10 | |||
| 11 | use parent 'Mail::DMARC'; | ||
| 12 | |||
| 13 | sub init($self) { | ||
| 14 | $self->is_subdomain(0); | ||
| 15 | $self->{header_from} = undef; | ||
| 16 | $self->{header_from_raw} = undef; | ||
| 17 | $self->{envelope_to} = undef; | ||
| 18 | $self->{envelope_from} = undef; | ||
| 19 | $self->{source_ip} = undef; | ||
| 20 | $self->{sender} = undef; | ||
| 21 | $self->{policy} = undef; | ||
| 22 | $self->{result} = undef; | ||
| 23 | $self->{report} = undef; | ||
| 24 | $self->{spf} = undef; | ||
| 25 | $self->{dkim} = undef; | ||
| 26 | $self->{_tw_cache} = {}; | ||
| 27 | return; | ||
| 28 | } | ||
| 29 | |||
| 30 | sub validate( $self, $policy = undef ) { | ||
| 31 | $self->result->result('fail'); # set a couple | ||
| 32 | $self->result->disposition('none'); # defaults | ||
| 33 | |||
| 34 | # 11.2.1 Extract RFC5322.From domain | ||
| 35 | my $from_dom = $self->get_from_dom() or return $self->result; | ||
| 36 | |||
| 37 | # 9.6. reject email if the domain appears to not exist | ||
| 38 | $self->exists_in_dns() or return $self->result; | ||
| 39 | |||
| 40 | $policy ||= $self->discover_policy(); # 11.2.2 Query DNS for DMARC policy | ||
| 41 | if ( !$policy ) { | ||
| 42 | |||
| 43 | # RFC7489 section 4.3 step 8: | ||
| 44 | # If a policy is found, it is combined with the Author's domain | ||
| 45 | # and the SPF and DKIM results to produce a DMARC policy result (a | ||
| 46 | # "pass" or "fail") | ||
| 47 | # Hence, if no (valid) policy has been found, produce "none" instead. | ||
| 48 | $self->result->result('none'); | ||
| 49 | return $self->result; | ||
| 50 | } | ||
| 51 | |||
| 52 | # 3.5 Out of Scope DMARC has no "short-circuit" provision, such as | ||
| 53 | # specifying that a pass from one authentication test allows one | ||
| 54 | # to skip the other(s). All are required for reporting. | ||
| 55 | |||
| 56 | try { $self->is_dkim_aligned; } catch ($e) { }; # 11.2.3. DKIM signature verification checks | ||
| 57 | try { $self->is_spf_aligned; } catch ($e) { }; # 11.2.4. SPF validation checks | ||
| 58 | my $aligned = $self->is_aligned(); # 11.2.5. identifier alignment checks | ||
| 59 | |||
| 60 | if ( $self->config->{report_store}{auto_save} ) { | ||
| 61 | try { $self->save_aggregate(); } catch ($e) { }; | ||
| 62 | } | ||
| 63 | |||
| 64 | return $self->result if $aligned; | ||
| 65 | |||
| 66 | # Determine if the from domain is a non-existent subdomain (for np tag) | ||
| 67 | my $is_sub = $self->is_subdomain; | ||
| 68 | my $sub_exists | ||
| 69 | = !$is_sub | ||
| 70 | || !defined $policy->np | ||
| 71 | || $self->_author_domain_exists($from_dom); | ||
| 72 | |||
| 73 | my $effective_p; | ||
| 74 | if ( $is_sub && !$sub_exists && defined $policy->np ) { | ||
| 75 | |||
| 76 | # RFC 9989 §4.7 np tag: policy for non-existent subdomains | ||
| 77 | $effective_p = $policy->np; | ||
| 78 | } | ||
| 79 | elsif ( defined $policy->sp | ||
| 80 | && $self->result->published | ||
| 81 | && $self->result->published->domain ne $from_dom ) | ||
| 82 | { | ||
| 83 | $effective_p = $policy->sp; | ||
| 84 | } | ||
| 85 | else { | ||
| 86 | $effective_p = $policy->p; | ||
| 87 | } | ||
| 88 | $effective_p //= 'none'; | ||
| 89 | |||
| 90 | # RFC 9989 4.7 t tag: testing mode, apply one severity level lower | ||
| 91 | if ( defined $policy->t && lc( $policy->t ) eq 'y' ) { | ||
| 92 | my $tested | ||
| 93 | = ( lc($effective_p) eq 'reject' ) ? 'quarantine' | ||
| 94 | : ( lc($effective_p) eq 'quarantine' ) ? 'none' | ||
| 95 | : $effective_p; | ||
| 96 | if ( $tested ne $effective_p ) { | ||
| 97 | $effective_p = $tested; | ||
| 98 | $self->result->reason( | ||
| 99 | type => 'other', | ||
| 100 | comment => 'policy testing mode (t=y)' | ||
| 101 | ); | ||
| 102 | } | ||
| 103 | } | ||
| 104 | |||
| 105 | # RFC 9989: pct tag is deprecated and MUST be ignored | ||
| 106 | |||
| 107 | # Apply policy. Emails that fail the DMARC mechanism check are | ||
| 108 | # disposed of in accordance with the discovered DMARC policy. | ||
| 109 | if ( lc $effective_p eq 'none' ) { | ||
| 110 | return $self->result; | ||
| 111 | } | ||
| 112 | |||
| 113 | return $self->result if $self->is_whitelisted; | ||
| 114 | |||
| 115 | $self->result->disposition($effective_p); | ||
| 116 | return $self->result; | ||
| 117 | } | ||
| 118 | |||
| 119 | sub save_aggregate($self) { | ||
| 120 | my $pol; | ||
| 121 | try { | ||
| 122 | $pol = $self->result->published; | ||
| 123 | } catch ($e) { }; | ||
| 124 | if ( $pol && $self->has_valid_reporting_uri( $pol->rua ) ) { | ||
| 125 | my @valid_report_uris = $self->get_valid_reporting_uri( $pol->rua ); | ||
| 126 | |||
| 127 | my $filtered_report_uris = join( | ||
| 128 | ',', | ||
| 129 | map { | ||
| 130 | $_->{'uri'} | ||
| 131 | . ( | ||
| 132 | ( $_->{'max_bytes'} > 0 ) ? ( '!' . $_->{'max_bytes'} ) : q{} ) | ||
| 133 | } @valid_report_uris | ||
| 134 | ); | ||
| 135 | |||
| 136 | $self->result->published->rua($filtered_report_uris); | ||
| 137 | |||
| 138 | return $self->SUPER::save_aggregate(); | ||
| 139 | } | ||
| 140 | return; | ||
| 141 | } | ||
| 142 | |||
| 143 | sub discover_policy( $self, $from_dom = undef ) { | ||
| 144 | $from_dom ||= $self->header_from; | ||
| 145 | croak if !$from_dom; | ||
| 146 | print "Header From: $from_dom\n" if $self->verbose; | ||
| 147 | |||
| 148 | # RFC 9989 4.10: DNS Tree Walk replaces PSL-based org domain lookup | ||
| 149 | my ( $record_str, $org_dom, $at_dom ) = $self->tree_walk($from_dom); | ||
| 150 | |||
| 151 | # Fall back to PSL when no DMARC records exist for org domain determination | ||
| 152 | $org_dom //= $self->_psl_organizational_domain($from_dom); | ||
| 153 | $self->is_subdomain( $org_dom eq $from_dom ? 0 : 1 ); | ||
| 154 | |||
| 155 | if ( !$record_str ) { | ||
| 156 | $self->result->result('none'); | ||
| 157 | $self->result->reason( type => 'other', comment => 'no policy' ) | ||
| 158 | if !@{ $self->result->reason }; | ||
| 159 | return; | ||
| 160 | } | ||
| 161 | |||
| 162 | my $policy; | ||
| 163 | my $policy_str = "domain=$at_dom;" . $record_str; | ||
| 164 | try { | ||
| 165 | $policy = $self->policy($policy_str); | ||
| 166 | } | ||
| 167 | catch ($error) { | ||
| 168 | $self->result->reason( | ||
| 169 | type => 'other', | ||
| 170 | comment => "policy parse error: $error" | ||
| 171 | ); | ||
| 172 | return; | ||
| 173 | } | ||
| 174 | return unless $policy; | ||
| 175 | $self->result->published($policy); | ||
| 176 | |||
| 177 | # If a retrieved policy record does not contain a valid "p" tag, or | ||
| 178 | # contains an "sp"/"np" tag that is not valid, then: | ||
| 179 | my $p_invalid = $policy->p && !$policy->is_valid_p( $policy->p ); | ||
| 180 | my $sp_invalid = defined $policy->sp && !$policy->is_valid_p( $policy->sp ); | ||
| 181 | my $np_invalid = defined $policy->np && !$policy->is_valid_p( $policy->np ); | ||
| 182 | |||
| 183 | # psd=y records are not required to have p= | ||
| 184 | my $is_psd = defined $policy->psd && lc( $policy->psd ) eq 'y'; | ||
| 185 | |||
| 186 | if ( ( !$policy->p && !$is_psd ) || $p_invalid || $sp_invalid || $np_invalid ) { | ||
| 187 | if ( !$policy->rua | ||
| 188 | || !$self->has_valid_reporting_uri( $policy->rua ) ) | ||
| 189 | { | ||
| 190 | $self->result->reason( type => 'other', comment => "no valid rua" ); | ||
| 191 | return; | ||
| 192 | } | ||
| 193 | $policy->v('DMARC1'); | ||
| 194 | $policy->p('none'); | ||
| 195 | } | ||
| 196 | |||
| 197 | # psd=y records reach here without p= value, default to 'none' so all | ||
| 198 | # downstream consumers see a concrete value. | ||
| 199 | $policy->p('none') if !$policy->p; | ||
| 200 | |||
| 201 | return $policy; | ||
| 202 | } | ||
| 203 | |||
| 204 | sub is_aligned($self) { | ||
| 205 | |||
| 206 | # 11.2.5 Conduct identifier alignment checks. With authentication checks | ||
| 207 | # and policy discovery performed, the Mail Receiver checks if | ||
| 208 | # Authenticated Identifiers fall into alignment as decribed in | ||
| 209 | # Section 4. If one or more of the Authenticated Identifiers align | ||
| 210 | # with the RFC5322.From domain, the message is considered to pass | ||
| 211 | # the DMARC mechanism check. All other conditions (authentication | ||
| 212 | # failures, identifier mismatches) are considered to be DMARC | ||
| 213 | # mechanism check failures. | ||
| 214 | |||
| 215 | if ( 'pass' eq $self->result->spf | ||
| 216 | || 'pass' eq $self->result->dkim ) | ||
| 217 | { | ||
| 218 | $self->result->result('pass'); | ||
| 219 | $self->result->disposition('none'); | ||
| 220 | return 1; | ||
| 221 | } | ||
| 222 | return 0; | ||
| 223 | } | ||
| 224 | |||
| 225 | sub is_dkim_aligned($self) { | ||
| 226 | $self->result->dkim('fail'); # our 'default' result | ||
| 227 | $self->get_dkim_pass_sigs() or return; | ||
| 228 | |||
| 229 | # 11.2.3 Perform DKIM signature verification checks. A single email may | ||
| 230 | # contain multiple DKIM signatures. The results MUST include the | ||
| 231 | # value of the "d=" tag from all DKIM signatures that validated. | ||
| 232 | |||
| 233 | my $from_dom = $self->header_from or croak "header_from not set!"; | ||
| 234 | my $policy = $self->policy or croak "no policy!?"; | ||
| 235 | my $from_org = $self->get_organizational_domain(); | ||
| 236 | |||
| 237 | # Required in report: DKIM-Domain, DKIM-Identity, DKIM-Selector | ||
| 238 | foreach my $dkim_ref ( $self->get_dkim_pass_sigs() ) { | ||
| 239 | my $dkim_dom = lc $dkim_ref->{domain}; | ||
| 240 | |||
| 241 | my $dkmeta = { | ||
| 242 | domain => $dkim_ref->{domain}, | ||
| 243 | selector => $dkim_ref->{selector}, | ||
| 244 | identity => '', # TODO, what is this? | ||
| 245 | }; | ||
| 246 | |||
| 247 | if ( $dkim_dom eq $from_dom ) { # strict alignment requires exact match | ||
| 248 | $self->result->dkim('pass'); | ||
| 249 | $self->result->dkim_align('strict'); | ||
| 250 | $self->result->dkim_meta($dkmeta); | ||
| 251 | last; | ||
| 252 | } | ||
| 253 | |||
| 254 | # don't try relaxed if policy specifies strict | ||
| 255 | next if $policy->adkim && 's' eq lc $policy->adkim; | ||
| 256 | |||
| 257 | # don't try relaxed if we already got a strict match | ||
| 258 | next if 'pass' eq $self->result->dkim; | ||
| 259 | |||
| 260 | # relaxed policy (default): Org. Dom must match a DKIM sig | ||
| 261 | my $dkim_org = $self->get_organizational_domain($dkim_dom); | ||
| 262 | if ( $dkim_org eq $from_org ) { | ||
| 263 | $self->result->dkim('pass'); | ||
| 264 | $self->result->dkim_align('relaxed'); | ||
| 265 | $self->result->dkim_meta($dkmeta); | ||
| 266 | } | ||
| 267 | } | ||
| 268 | return 1 if 'pass' eq lc $self->result->dkim; | ||
| 269 | return; | ||
| 270 | } | ||
| 271 | |||
| 272 | sub is_spf_aligned( $self, $spf_dom = undef ) { | ||
| 273 | |||
| 274 | if ( !$spf_dom && !$self->spf ) { croak "missing SPF!"; } | ||
| 275 | |||
| 276 | my $from_dom = lc $self->header_from or croak "header_from not set!"; | ||
| 277 | my $from_org = $self->get_organizational_domain($from_dom); | ||
| 278 | |||
| 279 | $self->result->spf('fail'); | ||
| 280 | |||
| 281 | my @spf_results; | ||
| 282 | if ($spf_dom) { | ||
| 283 | push @spf_results, | ||
| 284 | { domain => lc $spf_dom, result => 'pass', scope => 'mfrom' }; | ||
| 285 | } | ||
| 286 | else { | ||
| 287 | my @all_results = @{ $self->spf }; | ||
| 288 | |||
| 289 | # RFC 7489 §4.3.2: only RFC5321.MailFrom (mfrom) is used for DMARC SPF | ||
| 290 | # alignment. EHLO/HELO is not used. Results with no scope specified are | ||
| 291 | # treated as mfrom for backward compatibility. | ||
| 292 | @spf_results = grep { !defined $_->{scope} || lc $_->{scope} ne 'helo' } | ||
| 293 | @all_results; | ||
| 294 | } | ||
| 295 | |||
| 296 | foreach my $res (@spf_results) { | ||
| 297 | next if lc $res->{result} ne 'pass'; | ||
| 298 | my $s_dom = lc $res->{domain}; | ||
| 299 | |||
| 300 | if ( $s_dom eq $from_dom ) { | ||
| 301 | $self->result->spf('pass'); | ||
| 302 | $self->result->spf_align('strict'); | ||
| 303 | return 1; | ||
| 304 | } | ||
| 305 | |||
| 306 | # don't try relaxed match if strict policy requested | ||
| 307 | next if $self->policy->aspf && 's' eq lc $self->policy->aspf; | ||
| 308 | |||
| 309 | if ( $self->get_organizational_domain($s_dom) eq $from_org ) { | ||
| 310 | $self->result->spf('pass'); | ||
| 311 | $self->result->spf_align('relaxed'); | ||
| 312 | |||
| 313 | # Don't return, we might find a strict match later. DMARC just | ||
| 314 | # needs one, for reporting it's nice to have the best match | ||
| 315 | } | ||
| 316 | } | ||
| 317 | |||
| 318 | return 1 if $self->result->spf eq 'pass'; | ||
| 319 | return 0; | ||
| 320 | } | ||
| 321 | |||
| 322 | sub is_whitelisted( $self, $s_ip = undef ) { | ||
| 323 | $s_ip ||= $self->source_ip; | ||
| 324 | return if !defined $s_ip; | ||
| 325 | if ( !$self->{_whitelist} ) { | ||
| 326 | my $white_file = $self->config->{smtp}{whitelist} or return; | ||
| 327 | return if !-f $white_file || !-r $white_file; | ||
| 328 | foreach my $line ( split /\n/, $self->slurp($white_file) ) { | ||
| 329 | next if $line =~ /^#/; # ignore comments | ||
| 330 | my ( $lip, $reason ) = split /\s+/, $line, 2; | ||
| 331 | next if not defined $lip; | ||
| 332 | $self->{_whitelist}{$lip} = $reason; | ||
| 333 | } | ||
| 334 | } | ||
| 335 | return if !$self->{_whitelist}{$s_ip}; | ||
| 336 | |||
| 337 | my ( $type, $comment ) = split /\s+/, $self->{_whitelist}{$s_ip}, 2; | ||
| 338 | |||
| 339 | # Validate type against RFC 7489 PolicyOverrideType enum | ||
| 340 | my @valid_reason_types | ||
| 341 | = qw/ forwarded sampled_out trusted_forwarder mailing_list local_policy other /; | ||
| 342 | if ( !$type || !grep { $_ eq lc $type } @valid_reason_types ) { | ||
| 343 | $type = 'other'; | ||
| 344 | } | ||
| 345 | $self->result->disposition('none'); | ||
| 346 | $self->result->reason( | ||
| 347 | type => $type, | ||
| 348 | ( $comment && $comment =~ /\S/ ? ( 'comment' => $comment ) : () ), | ||
| 349 | ); | ||
| 350 | return $type; | ||
| 351 | } | ||
| 352 | |||
| 353 | sub has_valid_reporting_uri( $self, $rua ) { | ||
| 354 | my @valid_reporting_uris = $self->get_valid_reporting_uri($rua); | ||
| 355 | return scalar @valid_reporting_uris; | ||
| 356 | } | ||
| 357 | |||
| 358 | sub get_valid_reporting_uri( $self, $rua ) { | ||
| 359 | return unless $rua; | ||
| 360 | my $recips_ref = $self->report->uri->parse($rua); | ||
| 361 | my @has_permission; | ||
| 362 | foreach my $uri_ref (@$recips_ref) { | ||
| 363 | if ( !$self->external_report( $uri_ref->{uri} ) ) { | ||
| 364 | push @has_permission, $uri_ref; | ||
| 365 | next; | ||
| 366 | } | ||
| 367 | my $ext = $self->verify_external_reporting($uri_ref); | ||
| 368 | push @has_permission, $uri_ref if $ext; | ||
| 369 | } | ||
| 370 | return @has_permission; | ||
| 371 | } | ||
| 372 | |||
| 373 | sub get_dkim_pass_sigs($self) { | ||
| 374 | my $dkim_sigs = $self->dkim or return (); # message not signed | ||
| 375 | |||
| 376 | if ( 'ARRAY' ne ref $dkim_sigs ) { | ||
| 377 | croak "dkim needs to be an array reference!"; | ||
| 378 | } | ||
| 379 | |||
| 380 | return grep { 'pass' eq lc $_->{result} } @$dkim_sigs; | ||
| 381 | } | ||
| 382 | |||
| 383 | sub tree_walk( $self, $from_dom ) { | ||
| 384 | $from_dom = lc $from_dom; | ||
| 385 | |||
| 386 | return @{ $self->{_tw_cache}{$from_dom} } | ||
| 387 | if $self->{_tw_cache}{$from_dom}; | ||
| 388 | |||
| 389 | # RFC 9989 4.10 DNS Tree Walk: walk up the DNS hierarchy from | ||
| 390 | # the author domain, querying _dmarc.<target> at each level. | ||
| 391 | # Stop when a record with psd=n (org domain anchor) or psd=y (PSD) | ||
| 392 | # is found, or after 8 queries, or when no labels remain. | ||
| 393 | |||
| 394 | my @labels = split /\./, $from_dom; | ||
| 395 | my $target = $from_dom; | ||
| 396 | my $query_count = 0; | ||
| 397 | |||
| 398 | # policy_record / at_dom: FIRST record found (most specific, author domain wins) | ||
| 399 | # org_dom: domain of the last record found, or the psd=n anchor | ||
| 400 | # prev_target: target queried one step before the current one (one label | ||
| 401 | # longer); when a psd=y PSD is found, that child is the Organizational Domain | ||
| 402 | my ( $policy_record, $at_dom, $org_dom, $prev_target ); | ||
| 403 | |||
| 404 | while ( $query_count < 8 && @labels > 0 ) { | ||
| 405 | $query_count++; | ||
| 406 | my $query = $self->get_resolver->send( "_dmarc.$target", 'TXT' ); | ||
| 407 | if ($query) { | ||
| 408 | my @matches; | ||
| 409 | for my $rr ( $query->answer ) { | ||
| 410 | next if $rr->type ne 'TXT'; | ||
| 411 | next if 'v=dmarc1' ne lc substr( $rr->txtdata, 0, 8 ); | ||
| 412 | push @matches, join( '', $rr->txtdata ); | ||
| 413 | } | ||
| 414 | if ( @matches == 1 ) { | ||
| 415 | my $rec = $matches[0]; | ||
| 416 | my $pol; | ||
| 417 | try { | ||
| 418 | $pol = $self->policy->parse("domain=$target;$rec"); | ||
| 419 | } | ||
| 420 | catch ($e) { }; | ||
| 421 | if ($pol) { | ||
| 422 | |||
| 423 | # Author domain takes precedence: save only the first record found | ||
| 424 | if ( !defined $policy_record ) { | ||
| 425 | $policy_record = $rec; | ||
| 426 | $at_dom = $target; | ||
| 427 | } | ||
| 428 | my $psd_val = defined $pol->psd ? lc $pol->psd : 'u'; | ||
| 429 | if ( $psd_val eq 'n' ) { | ||
| 430 | |||
| 431 | # Lucky anchor: this domain is the Organizational Domain | ||
| 432 | print "Tree Walk anchor (psd=n): $target\n" | ||
| 433 | if $self->verbose; | ||
| 434 | my @result = ( $policy_record, $target, $at_dom ); | ||
| 435 | $self->{_tw_cache}{$from_dom} = \@result; | ||
| 436 | return @result; | ||
| 437 | } | ||
| 438 | if ( $psd_val eq 'y' ) { | ||
| 439 | |||
| 440 | # PSD found; org domain is the child one label below it | ||
| 441 | my $below = $prev_target // $from_dom; | ||
| 442 | print "Tree Walk PSD (psd=y): $target, org=$below\n" | ||
| 443 | if $self->verbose; | ||
| 444 | my @result = ( $policy_record, $below, $at_dom ); | ||
| 445 | $self->{_tw_cache}{$from_dom} = \@result; | ||
| 446 | return @result; | ||
| 447 | } | ||
| 448 | |||
| 449 | # psd=u (default): update org_dom candidate, keep walking | ||
| 450 | $org_dom = $target; | ||
| 451 | } | ||
| 452 | } | ||
| 453 | elsif ( @matches > 1 ) { | ||
| 454 | |||
| 455 | # 9.5. If the remaining set contains multiple records, processing | ||
| 456 | # terminates and the Mail Receiver takes no action. | ||
| 457 | $self->result->reason( | ||
| 458 | type => 'other', | ||
| 459 | comment => "too many policies" | ||
| 460 | ); | ||
| 461 | print "Too many DMARC records\n" if $self->verbose; | ||
| 462 | return; | ||
| 463 | } | ||
| 464 | } | ||
| 465 | |||
| 466 | # Remove leftmost label; apply >=8-label reduction rule (RFC 9989 4.10) | ||
| 467 | $prev_target = $target; | ||
| 468 | my $n = @labels; | ||
| 469 | if ( $n >= 8 ) { | ||
| 470 | my $trim = $n - 7; | ||
| 471 | splice @labels, 0, $trim; | ||
| 472 | } | ||
| 473 | else { | ||
| 474 | shift @labels; | ||
| 475 | } | ||
| 476 | $target = join( '.', @labels ); | ||
| 477 | } | ||
| 478 | |||
| 479 | # Walked to top without a psd=n/y anchor; use last record found as org domain | ||
| 480 | my @result = ( $policy_record, $org_dom, $at_dom ); | ||
| 481 | $self->{_tw_cache}{$from_dom} = \@result; | ||
| 482 | return @result; | ||
| 483 | } | ||
| 484 | |||
| 485 | sub get_organizational_domain( $self, $from_dom = undef ) { | ||
| 486 | $from_dom ||= $self->header_from; | ||
| 487 | croak "missing header_from!" if !$from_dom; | ||
| 488 | $from_dom = lc $from_dom; | ||
| 489 | |||
| 490 | my ( undef, $org_dom ) = $self->tree_walk($from_dom); | ||
| 491 | |||
| 492 | # Fallback: when no DMARC records exist in DNS for this tree, use the PSL | ||
| 493 | # to determine the org domain | ||
| 494 | if ( !defined $org_dom ) { | ||
| 495 | $org_dom = $self->_psl_organizational_domain($from_dom); | ||
| 496 | } | ||
| 497 | |||
| 498 | print "Organizational Domain: $org_dom\n" if $self->verbose; | ||
| 499 | return $org_dom; | ||
| 500 | } | ||
| 501 | |||
| 502 | sub _psl_organizational_domain( $self, $from_dom ) { | ||
| 503 | my @labels = reverse split /\./, lc $from_dom; | ||
| 504 | my $greatest = 0; | ||
| 505 | for ( my $i = 0; $i <= $#labels; $i++ ) { | ||
| 506 | next if !$labels[$i]; | ||
| 507 | my $tld = join '.', reverse( @labels[ 0 .. $i ] ); | ||
| 508 | $greatest = $i + 1 if $self->is_public_suffix($tld); | ||
| 509 | } | ||
| 510 | return $from_dom if $greatest == @labels; | ||
| 511 | return join '.', reverse( @labels[ 0 .. $greatest ] ); | ||
| 512 | } | ||
| 513 | |||
| 514 | sub _dns_name_exists( $self, $dom ) { | ||
| 515 | |||
| 516 | # RFC 9989 3.2.13: a name is non-existent only when DNS consistently | ||
| 517 | # returns NXDOMAIN. NOERROR/NODATA means the name exists but lacks that | ||
| 518 | # record type. Timeouts and other errors are treated conservatively as | ||
| 519 | # existing. | ||
| 520 | my $got_response = 0; | ||
| 521 | for my $type (qw/ A AAAA MX NS /) { | ||
| 522 | my $q = $self->get_resolver->send( $dom, $type ); | ||
| 523 | next unless $q; | ||
| 524 | return 1 | ||
| 525 | if $q->header->rcode ne 'NXDOMAIN'; # NOERROR/NODATA or error → exists | ||
| 526 | $got_response = 1; | ||
| 527 | } | ||
| 528 | return $got_response ? 0 : 1; | ||
| 529 | } | ||
| 530 | |||
| 531 | sub _author_domain_exists( $self, $dom ) { | ||
| 532 | return $self->_dns_name_exists($dom); | ||
| 533 | } | ||
| 534 | |||
| 535 | sub exists_in_dns( $self, $from_dom = undef ) { | ||
| 536 | $from_dom ||= $self->header_from; | ||
| 537 | croak "no header_from!" if !$from_dom; | ||
| 538 | |||
| 539 | # rfc7489 6.6.3 | ||
| 540 | # If the set produced by the mechanism above contains no DMARC policy | ||
| 541 | # record (i.e., any indication that there is no such record as opposed | ||
| 542 | # to a transient DNS error), Mail Receivers SHOULD NOT apply the DMARC | ||
| 543 | # mechanism to the message. | ||
| 544 | |||
| 545 | my $org_dom = $self->get_organizational_domain($from_dom); | ||
| 546 | my @todo = $from_dom; | ||
| 547 | if ( $from_dom ne $org_dom ) { | ||
| 548 | push @todo, $org_dom; | ||
| 549 | $self->is_subdomain(1); | ||
| 550 | } | ||
| 551 | my $matched = 0; | ||
| 552 | foreach (@todo) { | ||
| 553 | last if $matched; | ||
| 554 | $matched = 1 if $self->_dns_name_exists($_); | ||
| 555 | } | ||
| 556 | if ( !$matched ) { | ||
| 557 | $self->result->result('none'); | ||
| 558 | $self->result->disposition('none'); | ||
| 559 | $self->result->reason( | ||
| 560 | type => 'other', | ||
| 561 | comment => "$from_dom not in DNS" | ||
| 562 | ); | ||
| 563 | } | ||
| 564 | return $matched; | ||
| 565 | } | ||
| 566 | |||
| 567 | sub fetch_dmarc_record( $self, $zone, $org_dom = undef ) { | ||
| 568 | |||
| 569 | # 1. Mail Receivers MUST query the DNS for a DMARC TXT record at the | ||
| 570 | # DNS domain matching the one found in the RFC5322.From domain in | ||
| 571 | # the message. A possibly empty set of records is returned. | ||
| 572 | my @matches = (); | ||
| 573 | my $query = $self->get_resolver->send( "_dmarc.$zone", 'TXT' ) | ||
| 574 | or return ( \@matches, $zone ); | ||
| 575 | |||
| 576 | for my $rr ( $query->answer ) { | ||
| 577 | next if $rr->type ne 'TXT'; | ||
| 578 | |||
| 579 | # 2. Records that do not start with a "v=" tag that identifies the | ||
| 580 | # current version of DMARC are discarded. | ||
| 581 | next if 'v=dmarc1' ne lc substr( $rr->txtdata, 0, 8 ); | ||
| 582 | print "\n" . $rr->txtdata . "\n\n" if $self->verbose; | ||
| 583 | push @matches, join( '', $rr->txtdata ); # join long records | ||
| 584 | } | ||
| 585 | if (@matches) { | ||
| 586 | return \@matches, $zone; # found one! (at least) | ||
| 587 | } | ||
| 588 | |||
| 589 | # 3. If the set is now empty, the Mail Receiver MUST query the DNS for | ||
| 590 | # a DMARC TXT record at the DNS domain matching the Organizational | ||
| 591 | # Domain in place of the RFC5322.From domain in the message (if | ||
| 592 | # different). This record can contain policy to be asserted for | ||
| 593 | # subdomains of the Organizational Domain. | ||
| 594 | if ( defined $org_dom ) { # <- recursion break | ||
| 595 | if ( $org_dom ne $zone ) { | ||
| 596 | return $self->fetch_dmarc_record($org_dom); # <- recursion | ||
| 597 | } | ||
| 598 | } | ||
| 599 | |||
| 600 | return \@matches, $zone; | ||
| 601 | } | ||
| 602 | |||
| 603 | sub get_from_dom($self) { | ||
| 604 | return $self->header_from if $self->header_from; | ||
| 605 | |||
| 606 | my $header = $self->header_from_raw or do { | ||
| 607 | $self->result->reason( type => 'other', comment => "no header_from" ); | ||
| 608 | return; | ||
| 609 | }; | ||
| 610 | |||
| 611 | # RFC 7489 §5.6.1: if From contains multiple addresses with different | ||
| 612 | # domains, use the Sender header domain. Caller should set $dmarc->sender. | ||
| 613 | my @domains; | ||
| 614 | while ( $header =~ /\@([\w][\w.-]*)/g ) { | ||
| 615 | my $dom = lc $1; | ||
| 616 | $dom =~ s/[>;\s,].*$//; | ||
| 617 | push @domains, $dom if $dom; | ||
| 618 | } | ||
| 619 | my %unique_doms = map { $_ => 1 } @domains; | ||
| 620 | if ( keys %unique_doms > 1 ) { | ||
| 621 | if ( $self->sender ) { | ||
| 622 | my $sender_dom = $self->to_ascii_domain( $self->sender ); | ||
| 623 | return $self->header_from($sender_dom); | ||
| 624 | } | ||
| 625 | $self->result->result('none'); | ||
| 626 | $self->result->reason( | ||
| 627 | type => 'other', | ||
| 628 | comment => | ||
| 629 | 'multiple RFC5322.From domains; provide Sender header via $dmarc->sender', | ||
| 630 | ); | ||
| 631 | return; | ||
| 632 | } | ||
| 633 | |||
| 634 | # Caller can pass in pre-parsed from_dom if this doesn't suit them. | ||
| 635 | my ($from_dom) = ( split /@/, $header )[-1]; # grab everything after the @ | ||
| 636 | ($from_dom) = split /(\s+|>)/, lc $from_dom; # remove trailing cruft | ||
| 637 | if ( !$from_dom ) { | ||
| 638 | $self->result->reason( | ||
| 639 | type => 'other', | ||
| 640 | comment => "invalid header_from: ($header)" | ||
| 641 | ); | ||
| 642 | return; | ||
| 643 | } | ||
| 644 | |||
| 645 | # RFC 8616 §6: convert U-labels to A-labels before DNS lookups | ||
| 646 | $from_dom = $self->to_ascii_domain($from_dom); | ||
| 647 | |||
| 648 | return $self->header_from($from_dom); | ||
| 649 | } | ||
| 650 | |||
| 651 | sub external_report( $self, $uri ) { | ||
| 652 | my $dmarc_dom = $self->result->published->domain | ||
| 653 | or croak "published policy not tagged!"; | ||
| 654 | |||
| 655 | if ( 'mailto' eq $uri->scheme ) { | ||
| 656 | my $dest_email = lc $uri->path; | ||
| 657 | my ($dest_host) = ( split /@/, $dest_email )[-1]; | ||
| 658 | if ( $self->get_organizational_domain($dest_host) eq | ||
| 659 | $self->get_organizational_domain($dmarc_dom) ) | ||
| 660 | { | ||
| 661 | print "$dest_host not external for $dmarc_dom\n" if $self->verbose; | ||
| 662 | return 0; | ||
| 663 | } | ||
| 664 | print "$dest_host is external for $dmarc_dom\n" if $self->verbose; | ||
| 665 | return 1; | ||
| 666 | } | ||
| 667 | |||
| 668 | if ( $uri->scheme =~ /^https?$/ ) { | ||
| 669 | if ( $uri->host eq $dmarc_dom ) { | ||
| 670 | print $uri->host . " not external for $dmarc_dom\n" if $self->verbose; | ||
| 671 | return 0; | ||
| 672 | } | ||
| 673 | print $uri->host . " is external for $dmarc_dom\n" if $self->verbose; | ||
| 674 | return 1; | ||
| 675 | } | ||
| 676 | |||
| 677 | return 1; | ||
| 678 | } | ||
| 679 | |||
| 680 | sub _uri_authority_host($uri) { | ||
| 681 | my $scheme = $uri->scheme // ''; | ||
| 682 | if ( $scheme eq 'mailto' ) { | ||
| 683 | my $path = $uri->path or return; | ||
| 684 | return ( split /@/, $path )[-1]; | ||
| 685 | } | ||
| 686 | elsif ( $scheme =~ /^https?$/ ) { | ||
| 687 | return $uri->host; | ||
| 688 | } | ||
| 689 | return; | ||
| 690 | } | ||
| 691 | |||
| 692 | sub verify_external_reporting( $self, $uri_ref = undef ) { | ||
| 693 | $uri_ref or croak "missing URI"; | ||
| 694 | |||
| 695 | # 1. Extract the host portion of the authority component of the URI. | ||
| 696 | # Call this the "destination host". | ||
| 697 | my $dmarc_dom = $self->result->published->domain | ||
| 698 | or croak "published policy not tagged!"; | ||
| 699 | |||
| 700 | # 1. Extract the host portion of the authority component of the URI. | ||
| 701 | my $dest_host; | ||
| 702 | my $scheme = $uri_ref->{uri}->scheme // ''; | ||
| 703 | if ( $scheme eq 'mailto' ) { | ||
| 704 | my $path = $uri_ref->{uri}->path or croak "invalid mailto URI"; | ||
| 705 | ($dest_host) = ( split /@/, $path )[-1]; | ||
| 706 | } | ||
| 707 | elsif ( $scheme =~ /^https?$/ ) { | ||
| 708 | $dest_host = $uri_ref->{uri}->host or croak "invalid $scheme URI"; | ||
| 709 | } | ||
| 710 | else { | ||
| 711 | print "\tunsupported URI scheme '$scheme' for external verification\n" | ||
| 712 | if $self->verbose; | ||
| 713 | return; | ||
| 714 | } | ||
| 715 | |||
| 716 | # 2. Prepend the string "_report._dmarc". | ||
| 717 | # 3. Prepend the domain name from which the policy was retrieved, | ||
| 718 | # after conversion to an A-label if needed. | ||
| 719 | my $dest = join '.', $dmarc_dom, '_report._dmarc', $dest_host; | ||
| 720 | |||
| 721 | # 4. Query the DNS for a TXT record at the constructed name. | ||
| 722 | my $query = $self->get_resolver->send( $dest, 'TXT' ) or do { | ||
| 723 | print "\tquery for $dest failed\n" if $self->verbose; | ||
| 724 | return; | ||
| 725 | }; | ||
| 726 | |||
| 727 | # 5. For each record, parse the result...same overall format: | ||
| 728 | # "v=DMARC1" tag is mandatory and MUST appear first in the list. | ||
| 729 | my @matches; | ||
| 730 | for my $rr ( $query->answer ) { | ||
| 731 | next if $rr->type ne 'TXT'; | ||
| 732 | |||
| 733 | next if 'v=dmarc1' ne lc substr( $rr->txtdata, 0, 8 ); | ||
| 734 | my $policy = undef; | ||
| 735 | my $dmarc_str = join( '', $rr->txtdata ); # join parts | ||
| 736 | try { $policy = $self->policy->parse($dmarc_str) } catch ($e) { }; | ||
| 737 | push @matches, $policy ? $policy : $dmarc_str; | ||
| 738 | } | ||
| 739 | |||
| 740 | # 6. If the result includes no TXT resource records...stop | ||
| 741 | if ( !@matches ) { | ||
| 742 | print "\tno TXT match for $dest\n" if $self->verbose; | ||
| 743 | return; | ||
| 744 | } | ||
| 745 | |||
| 746 | # 7. If > 1 TXT resource record remains, external reporting authorized | ||
| 747 | # 8. If a "rua" or "ruf" tag is discovered, replace the | ||
| 748 | # corresponding value with the one found in this record. | ||
| 749 | my @overrides = grep { ref $_ && $_->{rua} } @matches; | ||
| 750 | foreach my $or (@overrides) { | ||
| 751 | my $recips_ref = $self->report->uri->parse( $or->{rua} ) or next; | ||
| 752 | |||
| 753 | # the overriding URI MUST use the same destination host from step 1. | ||
| 754 | my $override_host = _uri_authority_host( $recips_ref->[0]{uri} ); | ||
| 755 | next unless defined $override_host && $override_host eq $dest_host; | ||
| 756 | print "found override RUA: $or->{rua}\n" if $self->verbose; | ||
| 757 | $self->result->published->rua( $or->{rua} ); | ||
| 758 | } | ||
| 759 | |||
| 760 | return @matches; | ||
| 761 | } | ||
| 762 | |||
| 763 | 1; | ||
| 764 | |||
| 765 | __END__ | ||
| 766 | |||
| 767 | =pod | ||
| 768 | |||
| 769 | =head1 NAME | ||
| 770 | |||
| 771 | Mail::DMARC::PurePerl - Pure Perl implementation of DMARC | ||
| 772 | |||
| 773 | =head1 VERSION | ||
| 774 | |||
| 775 | version 2.20260827 | ||
| 776 | |||
| 777 | =head1 METHODS | ||
| 778 | |||
| 779 | =head2 init | ||
| 780 | |||
| 781 | Reset the Mail::DMARC object, preparing it for a fresh request. | ||
| 782 | |||
| 783 | =head2 validate | ||
| 784 | |||
| 785 | This method does the following: | ||
| 786 | |||
| 787 | =over 4 | ||
| 788 | |||
| 789 | * check if the RFC5322.From domain exists (exists_in_dns) | ||
| 790 | |||
| 791 | * query DNS for a DMARC policy (discover_policy) | ||
| 792 | |||
| 793 | * check DKIM alignment (is_dkim_aligned) | ||
| 794 | |||
| 795 | * check SPF alignment (is_spf_aligned) | ||
| 796 | |||
| 797 | * determine DMARC alignment (is_aligned) | ||
| 798 | |||
| 799 | * calculate the I<effective> DMARC policy | ||
| 800 | |||
| 801 | * apply the DMARC policy (see L<Mail::DMARC::Result>) | ||
| 802 | |||
| 803 | =back | ||
| 804 | |||
| 805 | =head2 discover_policy | ||
| 806 | |||
| 807 | Query the DNS to determine if a DMARC policy exists. When the domain name in the email From header (header_from) is not an Organizational Domain (ex: www.example.com), an attempt is made to determine the O.D. using the Mozilla Public Suffix List. When the O.D. differs from the header_from, a second DNS query is sent to _dmarc.[O.D.]. | ||
| 808 | |||
| 809 | If a DMARC DNS record is found, it is parsed as a L<Mail::DMARC::Policy> object and returned. | ||
| 810 | |||
| 811 | =head2 is_aligned | ||
| 812 | |||
| 813 | Determine if this message is DMARC aligned. To pass this test, the message must pass at least one of the alignment test (DKIM or SPF). | ||
| 814 | |||
| 815 | =head2 is_dkim_aligned | ||
| 816 | |||
| 817 | Determine if a valid DKIM signature in the message is aligned with the message's From header domain. This match can be in strict (exact match) or relaxed (subdomains match) alignment. | ||
| 818 | |||
| 819 | =head2 is_spf_aligned | ||
| 820 | |||
| 821 | Same as DKIM, but for SPF. | ||
| 822 | |||
| 823 | =head2 has_valid_reporting_uri | ||
| 824 | |||
| 825 | Check for the presence of a valid reporting URI in the rua or ruf DMARC policy tags. | ||
| 826 | |||
| 827 | =head2 get_organizational_domain | ||
| 828 | |||
| 829 | From the 2013 DMARC spec, section 4: | ||
| 830 | |||
| 831 | Organizational Domain: ..is the domain that was registered with a domain | ||
| 832 | name registrar. Heuristics are used to determine this... | ||
| 833 | |||
| 834 | =head2 exists_in_dns | ||
| 835 | |||
| 836 | Determine if a domain exists, reliably. The DMARC draft says: | ||
| 837 | |||
| 838 | 9.6 If the RFC5322.From domain does not exist in the DNS, Mail Receivers | ||
| 839 | SHOULD direct the receiving SMTP server to reject the message {R9}. | ||
| 840 | |||
| 841 | And in Appendix A.4: | ||
| 842 | |||
| 843 | A common practice among MTA operators, and indeed one documented in | ||
| 844 | [ADSP], is a test to determine domain existence prior to any more | ||
| 845 | expensive processing. This is typically done by querying the DNS for | ||
| 846 | MX, A or AAAA resource records for the name being evaluated, and | ||
| 847 | assuming the domain is non-existent if it could be determined that no | ||
| 848 | such records were published for that domain name. | ||
| 849 | |||
| 850 | The original pre-standardization version of this protocol included a | ||
| 851 | mandatory check of this nature. It was ultimately removed, as the | ||
| 852 | method's error rate was too high without substantial manual tuning | ||
| 853 | and heuristic work. There are indeed use cases this work needs to | ||
| 854 | address where such a method would return a negative result about a | ||
| 855 | domain for which reporting is desired, such as a registered domain | ||
| 856 | name that never sends legitimate mail and thus has none of these | ||
| 857 | records present in the DNS. | ||
| 858 | |||
| 859 | I went back to the ADSP (which led me to the ietf-dkim email list where | ||
| 860 | some 'experts' failed to agree on The Right Way to test domain validity. They | ||
| 861 | pointed out: MX records aren't mandatory, and A or AAAA aren't reliable. | ||
| 862 | |||
| 863 | Some experimentation proved both arguments in real world usage. This module | ||
| 864 | tests for existence by searching for a MX, NS, A, or AAAA record. Since this | ||
| 865 | search may be repeated for the Organizational Name, if the NS query fails, | ||
| 866 | there is no delegation from the TLD. That has proven very reliable. | ||
| 867 | |||
| 868 | =head2 fetch_dmarc_record | ||
| 869 | |||
| 870 | Query the DNS for the presence of a DMARC record at the header from domain name and the Organizational Domain name. Returns the discovered DNS record answers. | ||
| 871 | |||
| 872 | =head2 get_from_dom | ||
| 873 | |||
| 874 | Returns the header_from attribute, if defined. | ||
| 875 | |||
| 876 | When header_from is not defined, crudely, and very quickly parse a From header and return the domain name (aka, the header_from domain). | ||
| 877 | |||
| 878 | The From header format is defined in RFC 822 and is very complex. The From header can contain multiple email addresses, each with different domains. This method returns the last one. If you want to handle this differently, parse the From header yourself and set header_from. | ||
| 879 | |||
| 880 | =head2 external_report | ||
| 881 | |||
| 882 | Determine if a report URL is external. If the domain name portion of the URI is not the same as the domain where the DMARC record was discovered, the report address is considered external. | ||
| 883 | |||
| 884 | =head2 verify_external_reporting | ||
| 885 | |||
| 886 | =head3 8.2. Verifying External Destinations | ||
| 887 | |||
| 888 | It is possible to specify destinations for the different reports that | ||
| 889 | are outside the domain making the request. This is enabled to allow | ||
| 890 | domains that do not have mail servers to request reports and have | ||
| 891 | them go someplace that is able to receive and process them. | ||
| 892 | |||
| 893 | Without checks, this would allow a bad actor to publish a DMARC | ||
| 894 | policy record that requests reports be sent to a victim address, and | ||
| 895 | then send a large volume of mail that will fail both DKIM and SPF | ||
| 896 | checks to a wide variety of destinations, which will in turn flood | ||
| 897 | the victim with unwanted reports. Therefore, a verification | ||
| 898 | mechanism is included. | ||
| 899 | |||
| 900 | When a Mail Receiver discovers a DMARC policy in the DNS, and the | ||
| 901 | domain at which that record was discovered is not identical to the | ||
| 902 | host part of the authority component of a [URI] specified in the | ||
| 903 | "rua" or "ruf" tag, the following verification steps SHOULD be taken: | ||
| 904 | |||
| 905 | 1. Extract the host portion of the authority component of the URI. | ||
| 906 | Call this the "destination host". | ||
| 907 | 2. Prepend the string "_report._dmarc". | ||
| 908 | 3. Prepend the domain name from which the policy was retrieved, | ||
| 909 | after conversion to an A-label if needed. | ||
| 910 | 4. Query the DNS for a TXT record at the constructed name. | ||
| 911 | 5. For each record, parse the result...same overall format: | ||
| 912 | "v=DMARC1" tag is mandatory and MUST appear first in the list. | ||
| 913 | 6. If the result includes no TXT resource records...stop | ||
| 914 | 7. If > 1 TXT resource record remains, external reporting authorized | ||
| 915 | 8. If a "rua" or "ruf" tag is discovered, replace the | ||
| 916 | corresponding value with the one found in this record. | ||
| 917 | |||
| 918 | The overriding URI MUST use the same destination host from the first step. | ||
| 919 | |||
| 920 | =head1 NOT IMPLEMENTED | ||
| 921 | |||
| 922 | =head2 RFC 9991 - DMARC Failure Reporting | ||
| 923 | |||
| 924 | RFC 9991 defines the format and delivery of per-message DMARC failure reports | ||
| 925 | (forensic reports, sent via the C<ruf> tag). This module does B<not> implement | ||
| 926 | RFC 9991. Sending failure reports is not supported. The C<ruf> tag in a DMARC | ||
| 927 | policy record is parsed and stored but no failure reports are generated or | ||
| 928 | delivered. | ||
| 929 | |||
| 930 | =head1 AUTHORS | ||
| 931 | |||
| 932 | =over 4 | ||
| 933 | |||
| 934 | =item * | ||
| 935 | |||
| 936 | Matt Simerson <msimerson@cpan.org> | ||
| 937 | |||
| 938 | =item * | ||
| 939 | |||
| 940 | Davide Migliavacca <shari@cpan.org> | ||
| 941 | |||
| 942 | =item * | ||
| 943 | |||
| 944 | Marc Bradshaw <marc@marcbradshaw.net> | ||
| 945 | |||
| 946 | =back | ||
| 947 | |||
| 948 | =head1 COPYRIGHT AND LICENSE | ||
| 949 | |||
| 950 | This software is copyright (c) 2026 by Matt Simerson. | ||
| 951 | |||
| 952 | This is free software; you can redistribute it and/or modify it under | ||
| 953 | the same terms as the Perl 5 programming language system itself. | ||
| 954 | |||
| 955 | =cut |