blib/lib/Mail/DMARC.pm untested

filter: Statementstmt 0.0% 0 / 163 Branchbran 0.0% 0 / 78 Conditioncond 0.0% 0 / 12 MC/DCmcdc 0.0% 0 / 8 Subroutinesub 0.0% 0 / 32 Podpod 0.0% 0 / 20 totaltotal 0.0% 0 / 313 CC 40 SCAR 28.9
CC
40
Cov
0%
get_report_window
56.0
dkim
42.0
new
30.0
CRAP 17.9
1 package Mail::DMARC;
2 use strict;
3 use warnings;
4 use feature 'signatures';
5 no warnings 'experimental::args_array_with_signatures'; ## no critic (ProhibitNoWarnings)
6  
7 our $VERSION = '2.20260827';
8  
9 use Carp;
10 our $psl_loads = 0;
11  
12 use parent 'Mail::DMARC::Base';
13 require Mail::DMARC::Policy;
14 require Mail::DMARC::Result;
15 require Mail::DMARC::Report::Aggregate::Record;
16 require Mail::DMARC::Report::Aggregate::Record::Auth_Results::SPF;
17 require Mail::DMARC::Report::Aggregate::Record::Auth_Results::DKIM;
18  
19 sub new( $class, @args ) {
20 croak "invalid args" if @args % 2;
21 my %args = @args;
22 my $self = bless { config_file => 'mail-dmarc.ini', }, $class;
23  
24 my @keys = sort {
25 $a eq 'config_file' ? -1
26 : $b eq 'config_file' ? 1
27 : ( $a cmp $b )
28 } keys %args;
29  
30 foreach my $key (@keys) {
31 if ( $self->can($key) ) {
32 $self->$key( $args{$key} );
33 }
34 else {
35 $self->{$key} = $args{$key};
36 }
37 }
38 return $self;
39 }
40  
41 sub source_ip( $self, $val = undef ) {
42 return $self->{source_ip} if @_ == 1;
43 croak "invalid source_ip" if !$self->is_valid_ip($val);
44 return $self->{source_ip} = $val;
45 }
46  
47 sub envelope_to( $self, $val = undef ) {
48 return $self->{envelope_to} if @_ == 1;
49 croak "invalid envelope_to" if !$self->is_valid_domain( lc $val );
50 return $self->{envelope_to} = $val;
51 }
52  
53 sub envelope_from( $self, $val = undef ) {
54 return $self->{envelope_from} if @_ == 1;
55 croak "invalid envelope_from" if !$self->is_valid_domain( lc $val );
56 return $self->{envelope_from} = $val;
57 }
58  
59 sub header_from( $self, $val = undef ) {
60 return $self->{header_from} if @_ == 1;
61 croak "invalid header_from" if !$self->is_valid_domain( lc $val );
62 return $self->{header_from} = lc $val;
63 }
64  
65 sub header_from_raw( $self, $val = undef ) {
66 return $self->{header_from_raw} if @_ == 1;
67  
68 #croak "invalid header_from_raw: $val" if 'from:' ne lc substr($val, 0, 5);
69 return $self->{header_from_raw} = lc $val;
70 }
71  
72 sub sender( $self, $val = undef ) {
73 return $self->{sender} if @_ == 1;
74 croak "invalid sender" if !$self->is_valid_domain( lc $val );
75 return $self->{sender} = lc $val;
76 }
77  
78 sub local_policy( $self, $val = undef ) {
79 return $self->{local_policy} if @_ == 1;
80  
81 # TODO: document this, when and why it would be used
82 return $self->{local_policy} = $val;
83 }
84  
85 sub dkim( $self, @args ) {
86 if ( !@args ) {
87 $self->_unwrap('dkim');
88 return $self->{dkim};
89 }
90  
91 # one shot
92 if ( @args == 1 ) {
93  
94 # warn "one argument\n";
95 if ( ref $args[0] eq 'CODE' ) {
96 return $self->{dkim} = $args[0];
97 }
98  
99 if ( ref $args[0] eq 'ARRAY' ) {
100 foreach my $d ( @{ $args[0] } ) {
101 push @{ $self->{dkim} },
102 Mail::DMARC::Report::Aggregate::Record::Auth_Results::DKIM
103 ->new($d);
104 }
105 return $self->{dkim};
106 }
107  
108 if ( ref $args[0] eq 'Mail::DKIM::Verifier' ) {
109 $self->_from_mail_dkim( $args[0] );
110 return $self->{dkim};
111 }
112 }
113  
114 #warn "iterative\n";
115 push @{ $self->{dkim} },
116 Mail::DMARC::Report::Aggregate::Record::Auth_Results::DKIM->new(@args);
117  
118 return $self->{dkim};
119 }
120  
121 sub _from_mail_dkim( $self, $dkim ) {
122 my $signatures = 0;
123  
124 # A DKIM verifier will have result and signature methods.
125 foreach my $s ( $dkim->signatures ) {
126 next if ref $s eq 'Mail::DKIM::DkSignature';
127 $signatures++;
128  
129 my $result = $s->result;
130  
131 if ( $result eq 'invalid' ) { # See GH Issue #21
132 $result = 'temperror';
133 }
134  
135 push @{ $self->{dkim} },
136 Mail::DMARC::Report::Aggregate::Record::Auth_Results::DKIM->new(
137 domain => $s->domain,
138 selector => $s->selector,
139 result => $result,
140 human_result => $s->result_detail,
141 );
142 }
143  
144 if ( $signatures < 1 ) {
145 push @{ $self->{dkim} },
146 Mail::DMARC::Report::Aggregate::Record::Auth_Results::DKIM->new(
147 domain => '',
148 result => 'none',
149 );
150 }
151  
152 return;
153 }
154  
155 sub _unwrap( $self, $key ) {
156 if ( $self->{$key} and ref $self->{$key} eq 'CODE' ) {
157 my $code = delete $self->{$key};
158 $self->$key( $self->$code );
159 }
160 return;
161 }
162  
163 sub spf( $self, @args ) {
164 if ( !@args ) {
165 $self->_unwrap('spf');
166 return $self->{spf};
167 }
168  
169 if ( @args == 1 && ref $args[0] eq 'CODE' ) {
170 return $self->{spf} = $args[0];
171 }
172  
173 if ( @args == 1 && ref $args[0] eq 'ARRAY' ) {
174  
175 # warn "SPF one shot";
176 foreach my $d ( @{ $args[0] } ) {
177 push @{ $self->{spf} },
178 Mail::DMARC::Report::Aggregate::Record::Auth_Results::SPF->new($d);
179 }
180 return $self->{spf};
181 }
182  
183 #warn "SPF iterative";
184 push @{ $self->{spf} },
185 Mail::DMARC::Report::Aggregate::Record::Auth_Results::SPF->new(@args);
186  
187 return $self->{spf};
188 }
189  
190 sub policy( $self, @args ) {
191 return $self->{policy} if ref $self->{policy} && !@args;
192 return $self->{policy} = Mail::DMARC::Policy->new(@args);
193 }
194  
195 sub report($self) {
196 return $self->{report} if ref $self->{report};
197 require Mail::DMARC::Report;
198 return $self->{report} = Mail::DMARC::Report->new();
199 }
200  
201 sub result($self) {
202 return $self->{result} if ref $self->{result};
203 return $self->{result} = Mail::DMARC::Result->new();
204 }
205  
206 sub is_subdomain( $self, $val = undef ) {
207 return $self->{is_subdomain} if @_ == 1;
208 croak "invalid boolean" if 0 == grep {/^$val$/ix} qw/ 0 1/;
209 return $self->{is_subdomain} = $val;
210 }
211  
212 sub get_report_window( $self, $interval = undef, $now = undef ) {
213 my $min_interval = $self->config->{'report_sending'}{'min_interval'};
214 my $max_interval = $self->config->{'report_sending'}{'max_interval'};
215  
216 $interval = 86400 if !$interval; # Default to 1 day
217 if ($min_interval) {
218 $interval = $min_interval if $interval < $min_interval;
219 }
220 if ($max_interval) {
221 $interval = $max_interval if $interval > $max_interval;
222 }
223  
224 if ( ( 86400 % $interval ) != 0 ) {
225  
226 # Interval does not fit into a day nicely,
227 # So don't work out a window, just run with it.
228 return ( $now, $now + $interval - 1 );
229 }
230  
231 my $begin = $self->get_start_of_zulu_day($now);
232 my $end = $begin + $interval - 1;
233  
234 while ( $end < $now ) {
235 $begin = $begin + $interval;
236 $end = $begin + $interval - 1;
237 }
238  
239 return ( $begin, $end );
240 }
241  
242 sub get_start_of_zulu_day( $self, $t ) {
243 my $start_of_zulu_day = $t - ( $t % 86400 );
244 return $start_of_zulu_day;
245 }
246  
247 sub save_aggregate($self) {
248 my $agg = $self->report->aggregate;
249  
250 # put config information in report metadata
251 foreach my $f (qw/ org_name email extra_contact_info report_id /) {
252 $agg->metadata->$f( $self->config->{organization}{$f} );
253 }
254  
255 my ( $begin, $end )
256 = $self->get_report_window( $self->result->published->ri, $self->time );
257  
258 $agg->metadata->begin($begin);
259 $agg->metadata->end($end);
260  
261 $agg->policy_published( $self->result->published );
262  
263 my $rec = Mail::DMARC::Report::Aggregate::Record->new();
264 $rec->row->source_ip( $self->source_ip );
265  
266 $rec->identifiers(
267 envelope_to => $self->envelope_to,
268 envelope_from => $self->envelope_from,
269 header_from => $self->header_from,
270 );
271  
272 $rec->auth_results->dkim( $self->dkim );
273 $rec->auth_results->spf( $self->spf );
274  
275 $rec->row->policy_evaluated(
276 disposition => $self->result->disposition,
277 dkim => $self->result->dkim,
278 spf => $self->result->spf,
279 reason => $self->result->reason,
280 );
281  
282 $agg->record($rec);
283 return $self->report->save_aggregate;
284 }
285  
286 sub init($self) {
287  
288 # used for testing
289 map { delete $self->{$_} } qw/ spf spf_ar dkim dkim_ar /;
290 return;
291 }
292  
293 1;
294  
295 __END__
296  
297 =pod
298  
299 =head1 Status Badges
300  
301 =for markdown [![Build Status](https://github.com/msimerson/mail-dmarc/actions/workflows/ci.yml/badge.svg)](https://github.com/msimerson/mail-dmarc/actions/workflows/ci.yml)
302  
303 =for markdown [![Coverage Status](https://coveralls.io/repos/msimerson/mail-dmarc/badge.svg)](https://coveralls.io/r/msimerson/mail-dmarc)
304  
305 =head1 NAME
306  
307 Mail::DMARC - Perl implementation of DMARC
308  
309 =head1 VERSION
310  
311 version 2.20260827
312  
313 =head1 SYNOPSIS
314  
315 DMARC: Domain-based Message Authentication, Reporting and Conformance
316  
317 my $dmarc = Mail::DMARC::PurePerl->new(
318 ... # see the documentation for the "new" method for required args
319 );
320  
321 my $result = $dmarc->validate();
322  
323 if ( $result->result eq 'pass' ) {
324 ...continue normal processing...
325 return;
326 };
327  
328 # any result that did not pass is a fail. Now for disposition
329  
330 if ( $result->disposition eq 'reject' ) {
331 ...treat the sender to a 550 ...
332 };
333 if ( $result->disposition eq 'quarantine' ) {
334 ...assign a bunch of spam points...
335 };
336 if ( $result->disposition eq 'none' ) {
337 ...continue normal processing...
338 };
339  
340 =head1 DESCRIPTION
341  
342 This module is a suite of tools for implementing DMARC. It implements DMARCbis (L<RFC 9989|https://www.rfc-editor.org/rfc/rfc9989>) - including the DNS tree walk for Organizational Domain discovery and the C<np>, C<psd>, and C<t> policy tags - while remaining compatible with the original L<RFC 7489|https://www.rfc-editor.org/rfc/rfc7489>. It intends to implement every MUST and every SHOULD.
343  
344 This module can be used by...
345  
346 =over 4
347  
348 =item *
349  
350 MTAs and filtering tools like SpamAssassin to validate that incoming messages are aligned with the purported sender's policy.
351  
352 =item *
353  
354 email senders, to receive DMARC reports from other mail servers and display them via CLI and web interfaces.
355  
356 =item *
357  
358 MTA operators to send DMARC reports to DMARC author domains.
359  
360 =back
361  
362 When a message arrives via SMTP, the MTA or filtering application can pass in a small amount of metadata about the connection (envelope details, SPF and DKIM results) to Mail::DMARC. When the B<validate> method is called, Mail::DMARC will determine if:
363  
364 a. the header_from domain exists
365 b. the header_from domain publishes a DMARC policy
366 c. if a policy is published...
367 d. does the message conform to the published policy?
368 e. did the policy request reporting? If so, save details.
369  
370 The validation results are returned as a L<Mail::DMARC::Result> object. If the author domain requested a report, it was saved to the L<Report Store|Mail::DMARC::Report::Store>. The Store class includes a SQL implementation that is tested with SQLite, MySQL and PostgreSQL.
371  
372 There is more information available in the $result object. See L<Mail::DMARC::Result> for complete details.
373  
374 Reports are viewed with the L<dmarc_view_reports> program or with a web browser and the L<dmarc_httpd> program.
375  
376 Aggregate reports are sent to their requestors with the L<dmarc_send_reports> program.
377  
378 For aggregate reports that you have been sent, the L<dmarc_receive> program will parse the email messages (from IMAP, Mbox, or files) and save the report results into the L<Report Store|Mail::DMARC::Report::Store>.
379  
380 The report store can use the same database to store reports you have received as well as reports you will send. There are several ways to identify the difference, including:
381  
382 =over 4
383  
384 =item *
385  
386 received reports will have a null value for report_policy_published.rua
387  
388 =item *
389  
390 outgoing reports will have null values for report.uuid and report_record.count
391  
392 =back
393  
394 =head1 CLASSES
395  
396 L<Mail::DMARC> - the perl interface for DMARC
397  
398 L<Mail::DMARC::Policy> - a DMARC policy
399  
400 L<Mail::DMARC::PurePerl> - Pure Perl implementation of DMARC
401  
402 L<Mail::DMARC::Result> - the results of applying policy
403  
404 L<Mail::DMARC::Report> - Reporting: the R in DMARC
405  
406 =over 2
407  
408 L<Mail::DMARC::Report::Send> - send reports via SMTP & HTTP
409  
410 L<Mail::DMARC::Report::Receive> - receive and store reports from email, HTTP
411  
412 L<Mail::DMARC::Report::Store> - a persistent data store for aggregate reports
413  
414 L<Mail::DMARC::Report::View> - CLI and CGI methods for viewing reports
415  
416 =back
417  
418 L<Mail::DMARC::libopendmarc|https://metacpan.org/pod/Mail::DMARC::libopendmarc> - an XS implementation using libopendmarc
419  
420 =head1 METHODS
421  
422 =head2 new
423  
424 Create a DMARC object.
425  
426 my $dmarc = Mail::DMARC::PurePerl->new;
427  
428 Populate it.
429  
430 $dmarc->source_ip('192.0.1.1');
431 $dmarc->envelope_to('recipient.example.com');
432 $dmarc->envelope_from('sender.example.com');
433 $dmarc->header_from('sender.example.com');
434 $dmarc->dkim( $dkim_verifier );
435 $dmarc->spf([
436 { domain => 'example.com',
437 scope => 'mfrom',
438 result => 'pass',
439 },
440 {
441 scope => 'helo',
442 domain => 'mta.example.com',
443 result => 'fail',
444 },
445 ]);
446  
447 Run the request:
448  
449 my $result = $dmarc->validate();
450  
451 Alternatively, pass in all the required parameters in one shot:
452  
453 my $dmarc = Mail::DMARC::PurePerl->new(
454 source_ip => '192.0.1.1',
455 envelope_to => 'example.com',
456 envelope_from => 'cars4you.info',
457 header_from => 'yahoo.com',
458 dkim => $dkim_results, # same format
459 spf => $spf_results, # as previous example
460 );
461 my $result = $dmarc->validate();
462  
463 =head2 source_ip
464  
465 The remote IP that attempted sending the message. DMARC only uses this data for reporting to domains that request DMARC reports.
466  
467 =head2 envelope_to
468  
469 The domain portion of the RFC5321.RcptTo, (aka, the envelope recipient), and the bold portion in the following example:
470  
471 =over 8
472  
473 RCPT TO:&lt;user@B<example.com>>
474  
475 =back
476  
477 =head2 envelope_from
478  
479 The domain portion of the RFC5321.MailFrom, (aka, the envelope sender). That is the the bold portion in the following example:
480  
481 =over 8
482  
483 MAIL FROM:&lt;user@B<example.com>>
484  
485 =back
486  
487 =head2 header_from
488  
489 The domain portion of the RFC5322.From, aka, the From message header.
490  
491 =over 8
492  
493 From: Ultimate Vacation &lt;sweepstakes@B<example.com>>
494  
495 =back
496  
497 You can instead pass in the entire From: header with header_from_raw.
498  
499 =head2 header_from_raw
500  
501 Retrieve the header_from domain by parsing it from a raw From field/header. The domain portion is extracted by L<get_dom_from_header|Mail::DMARC::PurePerl#get_dom_from_header>, which is fast, generally effective, but also rather crude. It has limits, so read the description.
502  
503 =head2 dkim
504  
505 If Mail::DKIM::Verifier was used to validate the message, just pass in the Mail::DKIM::Verifier object that processed the message:
506  
507 $dmarc->dkim( $dkim_verifier );
508  
509 Otherwise, pass in an array reference. Each member of the DKIM array results represents a DKIM signature in the message and consists of the 4 keys shown in this example:
510  
511 $dmarc->dkim( [
512 {
513 domain => 'example.com',
514 selector => 'apr2013',
515 result => 'fail',
516 human_result=> 'fail (body has been altered)',
517 },
518 {
519 # 2nd signature, if present
520 },
521 ] );
522  
523 The dkim results can also be build iteratively by passing in key value pairs or hash references for each signature in the message:
524  
525 $dmarc->dkim( domain => 'sig1.com', result => 'fail' );
526 $dmarc->dkim( domain => 'sig2.com', result => 'pass' );
527 $dmarc->dkim( { domain => 'example.com', result => 'neutral' } );
528  
529 Each hash or hashref is appended to the dkim array.
530  
531 Finally, you can pass a coderef which won't be called until the dkim method is used to read the dkim results. It must return an array reference as described above.
532  
533 The dkim result is an array reference.
534  
535 =head3 domain
536  
537 The d= parameter in the DKIM signature
538  
539 =head3 selector
540  
541 The s= parameter in the DKIM signature
542  
543 =head3 result
544  
545 The validation results of this signature. One of: none, pass, fail, policy, neutral, temperror, or permerror
546  
547 =head3 human result
548  
549 Additional information about the DKIM result. This is comparable to Mail::DKIM::Verifier->result_detail.
550  
551 =head2 spf
552  
553 The spf method works exactly the same as dkim. It accepts named arguments, a hashref, an arrayref, or a coderef:
554  
555 $dmarc->spf(
556 domain => 'example.com',
557 scope => 'mfrom',
558 result => 'pass',
559 );
560  
561 The SPF domain and result are required for DMARC validation and the scope is used for reporting.
562  
563 =head3 domain
564  
565 The SPF checked domain
566  
567 =head3 scope
568  
569 The scope of the checked domain: mfrom, helo
570  
571 =head3 result
572  
573 The SPF result code: none, neutral, pass, fail, softfail, temperror, or permerror.
574  
575 =head1 DESIGN & GOALS
576  
577 =head2 Correct
578  
579 The DMARC spec is lengthy and evolving, making correctness a moving target. In cases where correctness is ambiguous, options are generally provided.
580  
581 =head2 Easy to use
582  
583 Providing an implementation of DMARC that SMTP utilities can utilize will aid DMARC adoption.
584  
585 The list of dependencies appears long because of reporting. If this module is used without reporting, the number of dependencies not included with perl is about 5.
586  
587 =head2 Maintainable
588  
589 Since DMARC is evolving, this implementation aims to be straight forward and easy to alter and extend. The programming style is primarily OO, which carries a small performance penalty but dividends in maintainability.
590  
591 When multiple options are available, such as when sending reports via SMTP or HTTP, calls should be made to the parent Send class to broker the request. When storing reports, calls are made to the Store class which dispatches to the SQL class. The idea is that if someone desired a data store other than those provided by perl's DBI class, they could easily implement their own. If you do, please fork it on GitHub and share.
592  
593 =head2 Fast
594  
595 If you deploy this in an environment where performance is insufficient, please profile the app and submit a report and preferably, patches.
596  
597 =head1 SEE ALSO
598  
599 L<Mail::DMARC on GitHub|https://github.com/msimerson/mail-dmarc>
600  
601 L<RFC 9989|https://www.rfc-editor.org/rfc/rfc9989> - DMARCbis, the current DMARC standard
602  
603 L<RFC 7489|https://www.rfc-editor.org/rfc/rfc7489> - the original (2015) DMARC specification
604  
605 =head1 HISTORY
606  
607 The daddy of this perl module was a L<DMARC module for the qpsmtpd MTA|https://github.com/smtpd/qpsmtpd/blob/master/plugins/dmarc>.
608  
609 =head1 AUTHORS
610  
611 =over 4
612  
613 =item *
614  
615 Matt Simerson <msimerson@cpan.org>
616  
617 =item *
618  
619 Davide Migliavacca <shari@cpan.org>
620  
621 =item *
622  
623 Marc Bradshaw <marc@marcbradshaw.net>
624  
625 =back
626  
627 =head1 CONTRIBUTORS
628  
629 =for stopwords Benny Pedersen Jean Paul Galea Marisa Clardy Priyadi Iman Nurcahyo Ricardo Signes
630  
631 =over 4
632  
633 =item *
634  
635 Benny Pedersen <me@junc.eu>
636  
637 =item *
638  
639 Jean Paul Galea <jeanpaul@yubico.com>
640  
641 =item *
642  
643 Marisa Clardy <marisa@clardy.eu>
644  
645 =item *
646  
647 Priyadi Iman Nurcahyo <priyadi@priyadi.net>
648  
649 =item *
650  
651 Ricardo Signes <rjbs@cpan.org>
652  
653 =back
654  
655 =head1 COPYRIGHT AND LICENSE
656  
657 This software is copyright (c) 2026 by Matt Simerson.
658  
659 This is free software; you can redistribute it and/or modify it under
660 the same terms as the Perl 5 programming language system itself.
661  
662 =cut