blib/lib/Mail/DMARC/Policy.pm untested

filter: Statementstmt 0.0% 0 / 143 Branchbran 0.0% 0 / 118 Conditioncond 0.0% 0 / 30 MC/DCmcdc 0.0% 0 / 19 Subroutinesub 0.0% 0 / 29 Podpod 0.0% 0 / 23 totaltotal 0.0% 0 / 362 CC 60 SCAR 34.0
CC
60
Cov
0%
is_valid
110.0
parse
56.0
new
42.0
CRAP 29.9
1 package Mail::DMARC::Policy;
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  
11 use Mail::DMARC::Report::URI;
12  
13 sub new( $class, @args ) {
14 my $package = ref $class ? ref $class : $class;
15 my $self = bless {}, $package;
16  
17 return $self if !@args; # no args, empty pol
18 if ( 1 == @args ) { # a string
19 my $policy = $self->parse( $args[0] );
20 $self->is_valid($policy);
21 return $policy;
22 }
23  
24 croak "invalid arguments" if @args % 2 != 0;
25 my $policy = {@args};
26 bless $policy, $package;
27 croak "invalid policy" if !$self->is_valid($policy);
28 return bless $policy, $package;
29 }
30  
31 sub parse( $self, $str, @junk ) {
32 croak "invalid parse request" if @junk;
33 my $cleaned = $str;
34 $cleaned =~ s/\s//g; # remove whitespace
35 $cleaned =~ s/\\;/;/g; # replace \; with ;
36 $cleaned =~ s/;;/;/g; # replace ;; with ;
37 $cleaned =~ s/;0;/;/g; # replace ;0; with ;
38 chop $cleaned if ';' eq substr $cleaned, -1, 1; # remove a trailing ;
39 my @tag_vals = split /;/, $cleaned;
40 my %policy;
41 my $warned = 0;
42  
43 foreach my $tv (@tag_vals) {
44 my ( $tag, $value ) = split /=|:|-/, $tv, 2;
45 if ( !defined $tag || !defined $value || $value eq '' ) {
46 if ( !$warned ) {
47  
48 #warn "tv: $tv\n";
49 warn "invalid DMARC record, please post this message to\n"
50 . "\thttps://github.com/msimerson/mail-dmarc/issues/39\n"
51 . "\t$str\n";
52 }
53 $warned++;
54 next;
55 }
56 $policy{ lc $tag } = $value;
57 }
58  
59 # RFC 9989: an unrecognized value for an optional tag is ignored (the tag
60 # reverts to its default); it MUST NOT invalidate the whole record. The
61 # setters croak, so normalize here on the parse-from-DNS path instead.
62 if ( defined $policy{psd} && $policy{psd} !~ /^[ynu]$/i ) {
63 warn "ignoring invalid psd ($policy{psd})\n";
64 delete $policy{psd};
65 }
66 if ( defined $policy{t} && $policy{t} !~ /^[yn]$/i ) {
67 warn "ignoring invalid t ($policy{t})\n";
68 delete $policy{t};
69 }
70  
71 return bless \%policy, ref $self; # inherited defaults + overrides
72 }
73  
74 sub stringify($self) {
75 my %dmarc_record = %{$self};
76 delete $dmarc_record{domain};
77  
78 my $dmarc_txt = 'v=' . ( delete $dmarc_record{v} ); # "v" tag must be first
79 foreach my $key ( keys %dmarc_record ) {
80 $dmarc_txt .= "; $key=$dmarc_record{$key}";
81 }
82 return $dmarc_txt;
83 }
84  
85 sub apply_defaults($self) {
86 $self->adkim('r') if !defined $self->adkim;
87 $self->aspf('r') if !defined $self->aspf;
88 $self->fo(0) if !defined $self->fo;
89  
90 # rf, ri, pct are deprecated in DMARCbis (RFC 9989) and MUST be ignored
91 return 1;
92 }
93  
94 sub v( $self, $val = undef ) {
95 return $self->{v} if @_ == 1;
96 croak "unsupported DMARC version" if 'DMARC1' ne uc $val;
97 return $self->{v} = $val;
98 }
99  
100 sub p( $self, $val = undef ) {
101 return $self->{p} if @_ == 1;
102 croak "invalid p" if !$self->is_valid_p($val);
103 return $self->{p} = $val;
104 }
105  
106 sub sp( $self, $val = undef ) {
107 return $self->{sp} if @_ == 1;
108 croak "invalid sp ($val)" if !$self->is_valid_p($val);
109 return $self->{sp} = $val;
110 }
111  
112 sub np( $self, $val = undef ) {
113 return $self->{np} if @_ == 1;
114 croak "invalid np ($val)" if !$self->is_valid_p($val);
115 return $self->{np} = $val;
116 }
117  
118 sub psd( $self, $val = undef ) {
119 return $self->{psd} if @_ == 1;
120 croak "invalid psd ($val)" if 0 == grep {/^\Q$val\E$/i} qw/ y n u /;
121 return $self->{psd} = lc $val;
122 }
123  
124 sub t( $self, $val = undef ) {
125 return $self->{t} if @_ == 1;
126 croak "invalid t ($val)" if 0 == grep {/^\Q$val\E$/i} qw/ y n /;
127 return $self->{t} = lc $val;
128 }
129  
130 sub adkim( $self, $val = undef ) {
131 return $self->{adkim} if @_ == 1;
132 croak "invalid adkim" if 0 == grep {/^\Q$val\E$/ix} qw/ r s /;
133 return $self->{adkim} = $val;
134 }
135  
136 sub aspf( $self, $val = undef ) {
137 return $self->{aspf} if @_ == 1;
138 croak "invalid aspf" if 0 == grep {/^\Q$val\E$/ix} qw/ r s /;
139 return $self->{aspf} = $val;
140 }
141  
142 sub fo( $self, $val = undef ) {
143 return $self->{fo} if @_ == 1;
144 croak "invalid fo: $val" if $val !~ /^[01ds](:[01ds])*$/ix;
145 return $self->{fo} = $val;
146 }
147  
148 sub rua( $self, $val = undef ) {
149 return $self->{rua} if @_ == 1;
150 croak "invalid rua" if !$self->is_valid_uri_list($val);
151 return $self->{rua} = $val;
152 }
153  
154 sub ruf( $self, $val = undef ) {
155 return $self->{ruf} if @_ == 1;
156 croak "invalid rua" if !$self->is_valid_uri_list($val);
157 return $self->{ruf} = $val;
158 }
159  
160 sub rf( $self, $val = undef ) {
161 return $self->{rf} if @_ == 1;
162 foreach my $f ( split /,/, $val ) {
163 croak "invalid format: $f" if !$self->is_valid_rf($f);
164 }
165 return $self->{rf} = $val;
166 }
167  
168 sub ri( $self, $val = undef ) {
169 return $self->{ri} if @_ == 1;
170 croak "not numeric ($val)!" if $val =~ /\D/;
171 croak "not an integer!" if $val != int $val;
172 croak "out of range" if ( $val < 0 || $val > 4294967295 );
173 return $self->{ri} = $val;
174 }
175  
176 sub pct( $self, $val = undef ) {
177 return $self->{pct} if @_ == 1;
178 croak "not numeric ($val)!" if $val =~ /\D/;
179 croak "not an integer!" if $val != int $val;
180 croak "out of range" if $val < 0 || $val > 100;
181 return $self->{pct} = $val;
182 }
183  
184 sub domain( $self, $val = undef ) {
185 return $self->{domain} if @_ == 1;
186 return $self->{domain} = $val;
187 }
188  
189 sub is_valid_rf( $self, $f ) {
190 return ( grep {/^\Q$f\E$/i} qw/ iodef afrf / ) ? 1 : 0;
191 }
192  
193 sub is_valid_p( $self, $p ) {
194 croak "unspecified p" if !defined $p;
195 return ( grep {/^\Q$p\E$/i} qw/ none reject quarantine / ) ? 1 : 0;
196 }
197  
198 sub is_valid_uri_list( $self, $str ) {
199 $self->{uri} ||= Mail::DMARC::Report::URI->new;
200 my $uris = $self->{uri}->parse($str);
201 return scalar @$uris;
202 }
203  
204 sub is_valid( $self, $obj = undef ) {
205 $obj = $self if !$obj;
206 croak "missing version specifier" if !$obj->{v};
207 croak "invalid version" if 'DMARC1' ne uc $obj->{v};
208  
209 # psd=y domains (PSDs) are not required to have a p= tag
210 my $is_psd = defined $obj->{psd} && lc $obj->{psd} eq 'y';
211  
212 if ( !$obj->{p} && !$is_psd ) {
213 if ( $obj->{rua} && $self->is_valid_uri_list( $obj->{rua} ) ) {
214 $obj->{p} = 'none';
215 }
216 else {
217 croak "missing policy action (p=)";
218 }
219 }
220 if ( $obj->{p} ) {
221 croak "invalid policy action" if !$self->is_valid_p( $obj->{p} );
222 }
223 if ( defined $obj->{np} ) {
224 croak "invalid np" if !$self->is_valid_p( $obj->{np} );
225 }
226  
227 # everything else is optional
228 return 1;
229 }
230  
231 1;
232  
233 __END__
234  
235 =pod
236  
237 =head1 NAME
238  
239 Mail::DMARC::Policy - a DMARC policy in object format
240  
241 =head1 VERSION
242  
243 version 2.20260827
244  
245 =head1 SYNOPSIS
246  
247 my $pol = Mail::DMARC::Policy->new(
248 'v=DMARC1; p=none; rua=mailto:dmarc@example.com'
249 );
250  
251 print "not a valid DMARC version!" if $pol->v ne 'DMARC1';
252 print "take no action" if $pol->p eq 'none';
253 print "reject that unaligned message" if $pol->p eq 'reject';
254 print "do not send aggregate reports" if ! $pol->rua;
255 print "do not send forensic reports" if ! $pol->ruf;
256  
257 =head1 EXAMPLES
258  
259 A DMARC record in DNS format looks like this:
260  
261 v=DMARC1; p=reject; adkim=s; aspf=s; rua=mailto:dmarc@example.com;
262  
263 DMARC records are stored in TXT resource records in the DNS, at _dmarc.example.com. To retrieve a DMARC record for a domain:
264  
265 =head2 dig
266  
267 dig +short _dmarc.example.com TXT
268  
269 =head2 perlishly
270  
271 print $_->txtdata."\n"
272 for Net::DNS::Resolver->new(dnsrch=>0)->send('_dmarc.example.com','TXT')->answer;
273  
274 =head2 dmarc_lookup
275  
276 dmarc_lookup example.com
277  
278 =head1 METHODS
279  
280 All methods validate their input against the DMARC specification (RFC 7489 / DMARCbis RFC 9989). Attempts to set invalid values will throw exceptions.
281  
282 =head2 new
283  
284 Create a new empty policy:
285  
286 my $pol = Mail::DMARC::Policy->new;
287  
288 Create a new policy from named arguments:
289  
290 my $pol = Mail::DMARC::Policy->new(
291 v => 'DMARC1',
292 p => 'none',
293 );
294  
295 Create a new policy from a DMARC DNS resource record:
296  
297 my $pol = Mail::DMARC::Policy->new(
298 'v=DMARC1; p=reject; rua=mailto:dmarc@example.com;'
299 );
300  
301 If a policy is passed in (the latter two examples), the resulting policy object will be an exact representation of the record as returned from DNS.
302  
303 =head2 apply_defaults
304  
305 The DMARC tags C<adkim>, C<aspf>, and C<fo> have default values when not specified in the published DNS record. Calling I<apply_defaults> will apply those defaults to tags not present in the DNS record.
306  
307 C<rf>, C<ri>, and C<pct> are deprecated in DMARCbis (RFC 9989) and MUST be ignored; C<apply_defaults> no longer sets them.
308  
309 =head2 parse
310  
311 Accepts a string containing a DMARC Resource Record, as it would be retrieved
312 via DNS.
313  
314 my $pol = Mail::DMARC::Policy->new;
315 $pol->parse( 'v=DMARC1; p=none; rua=mailto:dmarc@example.com' );
316 $pol->parse( 'v=DMARC1' ); # external reporting record
317  
318 =head2 stringify
319  
320 Returns the textual representation of the DMARC record.
321  
322 my $pol = Mail::DMARC::Policy->new('v=DMARC1; p=none;');
323 print $pol->stringify;
324  
325 =head1 Record Tags
326  
327 =head2 Tag Overview
328  
329 v=DMARC1; (version)
330 p=none; (disposition policy : reject, quarantine, none (monitor))
331 sp=reject; (subdomain policy: same as p)
332 adkim=s; (dkim alignment: s=strict, r=relaxed)
333 aspf=r; (spf alignment: s=strict, r=relaxed)
334 rua=mailto:dmarc-feedback@example.com; (aggregate reports)
335 ruf=mailto:dmarc-feedback@example.com; (forensic reports)
336 rf=afrf; (DEPRECATED in DMARCbis: report format)
337 ri=8400; (DEPRECATED in DMARCbis: report interval)
338 pct=50; (DEPRECATED in DMARCbis: percent of messages to filter)
339  
340 =head2 Tags in Detail
341  
342 The descriptions of each DMARC record tag and its corresponding values is from the March 31, 2013 draft of the DMARC spec:
343  
344 https://datatracker.ietf.org/doc/draft-kucherawy-dmarc-base/?include_text=1
345  
346 Each tag has a mutator that's a setter and getter. To set any of the tag values, pass in the new value. Examples:
347  
348 $pol->p('none'); set policy action to none
349 print "do nothing" if $pol->p eq 'none'; get policy action
350  
351 =head2 v
352  
353 Version (plain-text; REQUIRED). Identifies the record retrieved
354 as a DMARC record. It MUST have the value of "DMARC1". The value
355 of this tag MUST match precisely; if it does not or it is absent,
356 the entire retrieved record MUST be ignored. It MUST be the first
357 tag in the list.
358  
359 =head2 p
360  
361 Requested Mail Receiver policy (plain-text; REQUIRED for policy
362 records). Indicates the policy to be enacted by the Receiver at
363 the request of the Domain Owner. Policy applies to the domain
364 queried and to sub-domains unless sub-domain policy is explicitly
365 described using the "sp" tag. This tag is mandatory for policy
366 records only, but not for third-party reporting records (see
367 Section 8.2).
368  
369 =head2 sp
370  
371 {R6} Requested Mail Receiver policy for subdomains (plain-text;
372 OPTIONAL). Indicates the policy to be enacted by the Receiver at
373 the request of the Domain Owner. It applies only to subdomains of
374 the domain queried and not to the domain itself. Its syntax is
375 identical to that of the "p" tag defined above. If absent, the
376 policy specified by the "p" tag MUST be applied for subdomains.
377  
378 =head2 adkim
379  
380 (plain-text; OPTIONAL, default is "r".) Indicates whether or
381 not strict DKIM identifier alignment is required by the Domain
382 Owner. If and only if the value of the string is "s", strict mode
383 is in use. See Section 4.3.1 for details.
384  
385 =head2 aspf
386  
387 (plain-text; OPTIONAL, default is "r".) Indicates whether or
388 not strict SPF identifier alignment is required by the Domain
389 Owner. If and only if the value of the string is "s", strict mode
390 is in use. See Section 4.3.2 for details.
391  
392 =head2 fo
393  
394 Failure reporting options (plain-text; OPTIONAL, default "0"))
395 Provides requested options for generation of failure reports.
396 Report generators MAY choose to adhere to the requested options.
397 This tag's content MUST be ignored if a "ruf" tag (below) is not
398 also specified. The value of this tag is a colon-separated list
399 of characters that indicate failure reporting options as follows:
400  
401 0: Generate a DMARC failure report if all underlying
402 authentication mechanisms failed to produce an aligned "pass"
403 result.
404  
405 1: Generate a DMARC failure report if any underlying
406 authentication mechanism failed to produce an aligned "pass"
407 result.
408  
409 d: Generate a DKIM failure report if the message had a signature
410 that failed evaluation, regardless of its alignment. DKIM-
411 specific reporting is described in [AFRF-DKIM].
412  
413 s: Generate an SPF failure report if the message failed SPF
414 evaluation, regardless of its alignment. SPF-specific
415 reporting is described in [AFRF-SPF].
416  
417 =head2 rua
418  
419 Addresses to which aggregate feedback is to be sent (comma-
420 separated plain-text list of DMARC URIs; OPTIONAL). {R11} A comma
421 or exclamation point that is part of such a DMARC URI MUST be
422 encoded per Section 2.1 of [URI] so as to distinguish it from the
423 list delimiter or an OPTIONAL size limit. Section 8.2 discusses
424 considerations that apply when the domain name of a URI differs
425 from that of the domain advertising the policy. See Section 15.6
426 for additional considerations. Any valid URI can be specified. A
427 Mail Receiver MUST implement support for a "mailto:" URI, i.e. the
428 ability to send a DMARC report via electronic mail. If not
429 provided, Mail Receivers MUST NOT generate aggregate feedback
430 reports. URIs not supported by Mail Receivers MUST be ignored.
431 The aggregate feedback report format is described in Section 8.3.
432  
433 =head2 ruf
434  
435 Addresses to which message-specific failure information is to
436 be reported (comma-separated plain-text list of DMARC URIs;
437 OPTIONAL). {R11} If present, the Domain Owner is requesting Mail
438 Receivers to send detailed failure reports about messages that
439 fail the DMARC evaluation in specific ways (see the "fo" tag
440 above). The format of the message to be generated MUST follow
441 that specified in the "rf" tag. Section 8.2 discusses
442 considerations that apply when the domain name of a URI differs
443 from that of the domain advertising the policy. A Mail Receiver
444 MUST implement support for a "mailto:" URI, i.e. the ability to
445 send a DMARC report via electronic mail. If not provided, Mail
446 Receivers MUST NOT generate failure reports. See Section 15.6 for
447 additional considerations.
448  
449 =head2 rf
450  
451 B<Deprecated in DMARCbis (RFC 9989).> This tag MUST be ignored; it is documented here for historical reference only.
452  
453 Format to be used for message-specific failure reports (comma-
454 separated plain-text list of values; OPTIONAL; default "afrf").
455 The value of this tag is a list of one or more report formats as
456 requested by the Domain Owner to be used when a message fails both
457 [SPF] and [DKIM] tests to report details of the individual
458 failure. The values MUST be present in the registry of reporting
459 formats defined in Section 14; a Mail Receiver observing a
460 different value SHOULD ignore it, or MAY ignore the entire DMARC
461 record. Initial default values are "afrf" (defined in [AFRF]) and
462 "iodef" (defined in [IODEF]). See Section 8.4 for details.
463  
464 =head2 ri
465  
466 B<Deprecated in DMARCbis (RFC 9989).> This tag MUST be ignored; it is documented here for historical reference only.
467  
468 Interval requested between aggregate reports (plain-text, 32-bit
469 unsigned integer; OPTIONAL; default 86400). {R14} Indicates a
470 request to Receivers to generate aggregate reports separated by no
471 more than the requested number of seconds. DMARC implementations
472 MUST be able to provide daily reports and SHOULD be able to
473 provide hourly reports when requested. However, anything other
474 than a daily report is understood to be accommodated on a best-
475 effort basis.
476  
477 =head2 pct
478  
479 B<Deprecated in DMARCbis (RFC 9989).> This tag MUST be ignored; it is documented here for historical reference only.
480  
481 (plain-text integer between 0 and 100, inclusive; OPTIONAL;
482 default is 100). {R8} Percentage of messages from the DNS domain's
483 mail stream to which the DMARC mechanism is to be applied.
484 However, this MUST NOT be applied to the DMARC-generated reports,
485 all of which must be sent and received unhindered. The purpose of
486 the "pct" tag is to allow Domain Owners to enact a slow rollout
487 enforcement of the DMARC mechanism. The prospect of "all or
488 nothing" is recognized as preventing many organizations from
489 experimenting with strong authentication-based mechanisms. See
490 Section 7.1 for details.
491  
492 =head1 AUTHORS
493  
494 =over 4
495  
496 =item *
497  
498 Matt Simerson <msimerson@cpan.org>
499  
500 =item *
501  
502 Davide Migliavacca <shari@cpan.org>
503  
504 =item *
505  
506 Marc Bradshaw <marc@marcbradshaw.net>
507  
508 =back
509  
510 =head1 COPYRIGHT AND LICENSE
511  
512 This software is copyright (c) 2026 by Matt Simerson.
513  
514 This is free software; you can redistribute it and/or modify it under
515 the same terms as the Perl 5 programming language system itself.
516  
517 =cut