lib/Mail/DKIM2/DSN.pm

filter: Statementstmt 99.5% 231 / 232 Branchbran 78.3% 94 / 120 Conditioncond 58.2% 46 / 79 MC/DCmcdc 26.8% 11 / 41 Subroutinesub 100% 25 / 25 Podpod 100% 4 / 4 totaltotal 82.0% 411 / 501 CC 96 SCAR 26.2
CC
96
Cov
86%
propagate
28.1
_parse_report
14.1
_check_alignment
14.1
CRAP 13.8
« lib/Mail/DKIM2/Hop.pm ↑ Summary lib/Mail/DKIM2/Wrap.pm »
1 package Mail::DKIM2::DSN;
2 8 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 8 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 8 our $VERSION = '0.35';
6  
7 8 ▶use Email::MIME;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 8 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 8 ▶use List::Util qw(max);
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 8 ▶use Mail::DKIM2::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 8 ▶use Mail::DKIM2::Common qw(parse_mime extract_mi_version);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 8 ▶use Mail::DKIM2::Address qw(domain_of relaxed_domain_match);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 8 ▶use Mail::DKIM2::MessageInstance;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 8 ▶use Mail::DKIM2::Signature;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 8 ▶use Mail::DKIM2::Signer;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 8 ▶use Mail::DKIM2::Verifier;
Subroutine BEGIN: called CC=1 SCAR=0.0
18  
19 # Mail::DKIM2::DSN - propagate a DKIM2-signed DSN upstream (RFC 6522 DSN
20 # structure; DKIM2 -09 §16.3 propagation procedure).
21 #
22 # When a Forwarder receives a Delivery Status Notification for a message it
23 # forwarded, it may propagate that DSN back towards the original sender. The
24 # propagated DSN is a *new* message: the Forwarder rebuilds the enclosed
25 # original to the state it was in when forwarded outward (undoing its own
26 # Message-Instance modification and removing the DKIM2-Signature and
27 # Message-Instance it added), then re-signs the whole DSN with MAIL FROM <>
28 # so that it carries exactly one Message-Instance and one DKIM2-Signature.
29  
30 # Return the highest-sequence DKIM2-Signature (parsed) of an Email::MIME msg.
31 52 ▶sub _top_sig {
Subroutine _top_sig: called CC=2 SCAR=6.9
32 52 my ($msg) = @_;
33 52 my @sigs = map { Mail::DKIM2::Signature->parse($_) } $msg->header_raw('DKIM2-Signature');
34 52 ▶ return unless @sigs;
Branch: 1 branch
BranchTrueFalseTotal
unless @sigs 4 48 52
35 48 my ($top) = sort { $b->sequence <=> $a->sequence } @sigs;
36 48 return $top;
37 }
38  
39 # Remove the Forwarder's hop from an Email::MIME: the highest-sequence
40 # DKIM2-Signature, and then any nd= signature left on top, since a §12.3
41 # bridge belongs to the hop it was made for and an nd= signature is never
42 # valid as the top of a chain. (header_filter mishandles long folded values,
43 # so filter on header_raw and re-set the survivors.)
44 7 ▶sub _strip_top_sig {
Subroutine _strip_top_sig: called CC=5 SCAR=16.2
45 7 my ($msg) = @_;
46 7 my @sigs = $msg->header_raw('DKIM2-Signature');
47 7 ▶ return unless @sigs;
Branch: 1 branch
BranchTrueFalseTotal
unless @sigs 0 7 7
48 9 my @parsed = sort { $a->[1]->sequence <=> $b->[1]->sequence }
49 7 map { [ $_, Mail::DKIM2::Signature->parse($_) ] } @sigs;
50 7 my $maxi = $parsed[-1][1]->sequence;
51 7 pop @parsed;
52 7 ▶ while (@parsed) {
Branch: 1 branch
BranchTrueFalseTotal
if (@parsed) 9 0 9
53 9 my $nd = $parsed[-1][1]->next_domain;
54 9 ▶ last unless defined $nd && length $nd;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $nd and length $nd 7 2 9
Condition66%2/3
defined $nd and length $nd
!ll&&!rl&&r
702
MC/DC50%1/2
defined $nd and length $nd
defined $nd length $nd
Truth table66%2/3
A and B
A= defined $ndB= length $nd
ABresult
0X0
100
111
55 2 pop @parsed;
56 }
57 7 $msg->header_raw_set('DKIM2-Signature', map { $_->[0] } @parsed);
58 7 return $maxi;
59 }
60  
61 # Extract the Email::MIME of the embedded original from a message/rfc822 (or
62 # text/rfc822-headers) part.
63 27 ▶sub _embedded {
Subroutine _embedded: called CC=2 SCAR=7.0
64 27 my ($part) = @_;
65 27 my @sub = $part->subparts;
66 27 ▶ return $sub[0] if @sub;
Branch: 1 branch
BranchTrueFalseTotal
if @sub 0 27 27
67 27 return parse_mime($part->body);
68 }
69  
70 # Re-sign a rebuilt/created DSN as a NEW message: prepend one Message-Instance
71 # (v=1) and one DKIM2-Signature (the supplied signer is configured with
72 # MailFrom => '<>'). Returns the final raw message.
73 10 ▶sub _sign_as_new {
Subroutine _sign_as_new: called CC=4 SCAR=14.4
74 10 my ($signer, $dsn) = @_;
75 10 my $dsn_text = $dsn->as_string;
76 10 $dsn_text =~ s/\r?\n/\r\n/g;
77 10 my $mi = Mail::DKIM2::MessageInstance->calculate(parse_mime($dsn_text));
78 10 my $with_mi = "Message-Instance: " . $mi->as_string . "\r\n" . $dsn_text;
79 10 $signer->PRINT($with_mi);
80 10 $signer->CLOSE;
81 10 ▶ croak "DSN not signed: " . ($signer->result_detail // 'no result')
Branch: 1 branch
BranchTrueFalseTotal
unless ($signer->result // "") eq "signed" 0 10 10
Condition25%1/4
$signer->result // ""
l!l
100
$signer->result_detail // "no result"
l!l
00
MC/DC0%0/1
$signer->result // ""
$signer->result
MC/DC0%0/1
$signer->result_detail // "no result"
$signer->result_detail
Truth table50%1/2
A
A= $signer->result
Aresult
11
00
Truth table0%0/2
A
A= $signer->result_detail
Aresult
11
00
82 unless ($signer->result // '') eq 'signed';
83 10 my $sig_hdr = $signer->as_string;
84 10 $sig_hdr =~ s/\r?\n$//;
85 10 return $sig_hdr . "\r\n" . $with_mi;
86 }
87  
88 # Build a text/rfc822-headers embedded-original part: the headers only (no
89 # body) of $orig, an Email::MIME. Used by propagate() when the original body
90 # is unrecoverable (a "null Recipe" upstream) and so must not be carried.
91 2 ▶sub _headers_only_part {
Subroutine _headers_only_part: called CC=1 SCAR=0.0
92 2 my ($orig) = @_;
93 2 return Email::MIME->create(
94 attributes => { content_type => 'text/rfc822-headers', encoding => '7bit' },
95 body => $orig->header_obj->as_string,
96 );
97 }
98  
99 # Build the multipart/report Content-Type (with report-type) by reading the
100 # boundary Email::MIME chose for a freshly-created multipart object.
101 4 ▶sub _set_report_type {
Subroutine _set_report_type: called CC=3 SCAR=11.3
102 4 my ($msg) = @_;
103 4 ▶ my $ct = $msg->header('Content-Type') // '';
Condition50%1/2
$msg->header("Content-Type") // ""
l!l
40
MC/DC0%0/1
$msg->header("Content-Type") // ""
$msg->header("Content-Type")
Truth table50%1/2
A
A= $msg->header("Content-Type")
Aresult
11
00
104 4 ▶ return if $ct =~ /report-type=/i;
Branch: 1 branch
BranchTrueFalseTotal
if $ct =~ /report-type=/i 0 4 4
105 4 $ct =~ s{^(multipart/report)}{$1; report-type=delivery-status}i;
106 4 $msg->header_str_set('Content-Type', $ct);
107 }
108  
109 # may_generate(Message => $raw, PubkeyCallback|Resolver, SkipTimestampCheck):
110 # whether a DSN may be sent for this message at all (-09 section 16): its
111 # top DKIM2-Signature's mf= is not <>, and it is Provisionally Verified
112 # (section 13.2: the top signature is correct and the top Message-Instance
113 # matches). Returns ($ok, $why); $why says what is missing.
114 16 ▶sub may_generate {
Subroutine may_generate: called CC=12 SCAR=25.0
Pod documented
115 16 my ($class, %args) = @_;
116 16 Mail::DKIM2::Util::check_options("$class->may_generate", \%args,
117 qw(Domain Message PubkeyCallback Resolver SkipTimestampCheck));
118 16 ▶ my $raw = $args{Message} // croak "may_generate: need Message";
Condition50%1/2
$args{"Message"} // croak("may_generate: need Message")
l!l
160
MC/DC0%0/1
$args{"Message"} // croak("may_generate: need Message")
$args{"Message"}
Truth table50%1/2
A
A= $args{"Message"}
Aresult
11
00
119 16 (my $text = $raw) =~ s/\r?\n/\r\n/g;
120 16 my $top = eval { _top_sig(parse_mime($text)) };
121 16 ▶ die $@ if ref $@;
Branch: 1 branch
BranchTrueFalseTotal
if ref $@ 0 16 16
122 16 ▶ return (0, 'the message has no DKIM2-Signature, so it is not Provisionally Verified')
Branch: 1 branch
BranchTrueFalseTotal
unless $top 3 13 16
123 unless $top;
124 13 my $mf = $top->mail_from;
125 13 ▶ return (0, 'the top DKIM2-Signature mf= is <>, so no DSN may be sent')
Branch: 1 branch
BranchTrueFalseTotal
if not defined $mf or $mf =~ /\A<\s*>\z/ 3 10 13
Condition66%2/3
not defined $mf or $mf =~ /\A<\s*>\z/
l!l&&r!l&&!r
0310
MC/DC50%1/2
not defined $mf or $mf =~ /\A<\s*>\z/
not defined $mf $mf =~ /\A<\s*>\z/
Truth table66%2/3
not(A) or B
A= not defined $mfB= $mf =~ /\A<\s*>\z/
ABresult
1X1
011
000
126 if !defined $mf || $mf =~ /\A<\s*>\z/;
127 my $v = Mail::DKIM2::Verifier->new(
128 10 ▶ map { exists $args{$_} ? ($_ => $args{$_}) : () } qw(PubkeyCallback Resolver));
Branch: 1 branch
BranchTrueFalseTotal
exists $args{$_} ? : 10 10 20
129 10 ▶ $v->skip_timestamp_check(1) if $args{SkipTimestampCheck};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"SkipTimestampCheck"} 6 4 10
130 10 $v->load($text);
131 10 ▶ return (0, 'the message is not Provisionally Verified ('
Branch: 1 branch
BranchTrueFalseTotal
unless $v->provisionally_verified 1 9 10
Condition33%1/3
$v->details // $v->result
l!l&&r!l&&!r
100
MC/DC0%0/2
$v->details // $v->result
$v->details $v->result
Truth table33%1/3
A // B
A= $v->detailsB= $v->result
ABresult
1X1
011
000
132 . ($v->details // $v->result) . ')')
133 unless $v->provisionally_verified;
134 # -09 sections 7.1 item 4, 16.2: the DSN's d= MUST relaxed-match a
135 # recipient in the reported message's top rt= -- the same test a
136 # receiver makes of it (_check_alignment) -- or it is a forgery to them.
137 9 ▶ if (defined $args{Domain}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"Domain"}) 7 2 9
138 my ($aligned, $detail) = _check_alignment(
139 7 Mail::DKIM2::Signature->new(Domain => $args{Domain}), $top);
140 7 ▶ return (0, $detail) unless $aligned eq 'pass';
Branch: 1 branch
BranchTrueFalseTotal
unless $aligned eq "pass" 1 6 7
141 }
142 8 return (1, undef);
143 }
144  
145 # Generate a fresh DKIM2-signed DSN for an inbound message, sent back to the
146 # original sender (RFC 6522 three-part multipart/report structure; DKIM2
147 # -09 §16.1). Used by the reflector-dsn address, which
148 # bounces every message regardless of whether it arrived DKIM2-signed.
149 #
150 # Args: Message (inbound message), Signer (MailFrom => '<>'), To (envelope
151 # sender to bounce to; if omitted, the top DKIM2-Signature's mf=, never the
152 # From: header field), ReportingMTA, Status, Reason.
153 9 ▶sub generate {
Subroutine generate: called CC=13 SCAR=26.3
Pod documented
154 9 my ($class, %args) = @_;
155 9 Mail::DKIM2::Util::check_options("$class->generate", \%args,
156 qw(Message Signer To ReportingMTA Status Reason FinalRecipient
157 PubkeyCallback Resolver SkipTimestampCheck));
158 8 ▶ my $raw = $args{Message} or croak "generate: need Message";
Branch: 1 branch
BranchTrueFalseTotal
my $raw = $args{"Message"} or croak("generate: need Message") 8 0 8
159 8 ▶ my $signer = $args{Signer} or croak "generate: need Signer";
Branch: 1 branch
BranchTrueFalseTotal
my $signer = $args{"Signer"} or croak("generate: need Signer") 8 0 8
160 8 ▶ my $mta = $args{ReportingMTA} // 'dkim2.com';
Condition100%2/2
$args{"ReportingMTA"} // "dkim2.com"
l!l
62
MC/DC100%1/1
$args{"ReportingMTA"} // "dkim2.com"
$args{"ReportingMTA"}
Truth table100%2/2
A
A= $args{"ReportingMTA"}
Aresult
11
00
161 8 ▶ my $status = $args{Status} // '5.7.1';
Condition50%1/2
$args{"Status"} // "5.7.1"
l!l
08
MC/DC0%0/1
$args{"Status"} // "5.7.1"
$args{"Status"}
Truth table50%1/2
A
A= $args{"Status"}
Aresult
11
00
162 8 ▶ my $reason = $args{Reason} // 'message rejected by reflector-dsn (demo bounce)';
Condition100%2/2
$args{"Reason"} // "message rejected by reflector-dsn (demo bounce)"
l!l
26
MC/DC100%1/1
$args{"Reason"} // "message rejected by reflector-dsn (demo bounce)"
$args{"Reason"}
Truth table100%2/2
A
A= $args{"Reason"}
Aresult
11
00
163  
164 # -09 section 16: never for a message with a null top mf=, nor for one
165 # that is not Provisionally Verified.
166 my ($may, $why) = $class->may_generate(Message => $raw, Domain => $signer->{Domain},
167 8 ▶ map { exists $args{$_} ? ($_ => $args{$_}) : () }
Branch: 1 branch
BranchTrueFalseTotal
exists $args{$_} ? : 13 11 24
168 qw(PubkeyCallback Resolver SkipTimestampCheck));
169 8 ▶ croak "generate: not sending a DSN: $why" unless $may;
Branch: 1 branch
BranchTrueFalseTotal
unless $may 4 4 8
170  
171 4 my $orig = parse_mime($raw);
172  
173 # Where to send the bounce: the explicit envelope sender, else the top
174 # signature's mf= (section 16). Never the From: header field.
175 4 my $to = $args{To};
176 4 ▶ if (!defined $to || !length $to || $to eq '<>') {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $to && length $to or $to eq "<>") 2 2 4
Condition66%4/6
not defined $to && length $to or $to eq "<>"
l!l&&r!l&&!r
202
defined $to && length $to
!ll&&!rl&&r
202
MC/DC33%1/3
not defined $to && length $to or $to eq "<>"
defined $to length $to $to eq "<>"
Truth table50%2/4
not(A && B) or C
A= defined $toB= length $toC= $to eq "<>"
ABCresult
0XX1
10X1
1111
1100
177 2 $to = _top_sig($orig)->mail_from;
178 }
179  
180 4 ▶ my $final_rcpt = $args{FinalRecipient} // $orig->header('To') // $to;
Condition33%2/6
($args{"FinalRecipient"} // $orig->header("To")) // $to
l!l&&r!l&&!r
400
$args{"FinalRecipient"} // $orig->header("To")
l!l&&r!l&&!r
040
MC/DC0%0/3
($args{"FinalRecipient"} // $orig->header("To")) // $to
$args{"FinalRecipient"} $orig->header("To") $to
Truth table25%1/4
A // B // C
A= $args{"FinalRecipient"}B= $orig->header("To")C= $to
ABCresult
1XX1
01X1
0011
0000
181  
182 # Part 1: human-readable explanation.
183 4 my $human = Email::MIME->create(
184 attributes => { content_type => 'text/plain', charset => 'UTF-8', encoding => '7bit' },
185 body_str => "This is a DKIM2 demonstration Delivery Status Notification.\n\n"
186 . "Your message was received by the reflector-dsn address and a\n"
187 . "DKIM2-signed DSN has been returned to you.\n\n"
188 . "Reason: $reason\n",
189 );
190  
191 # Part 2: machine-readable delivery status.
192 4 my $ds = Email::MIME->create(
193 attributes => { content_type => 'message/delivery-status', encoding => '7bit' },
194 body => "Reporting-MTA: dns; $mta\r\n"
195 . "\r\n"
196 . "Final-Recipient: rfc822; $final_rcpt\r\n"
197 . "Action: failed\r\n"
198 . "Status: $status\r\n"
199 . "Diagnostic-Code: smtp; $status $reason\r\n",
200 );
201  
202 # Part 3: the original message.
203 4 my $orig_part = Email::MIME->create(
204 attributes => { content_type => 'message/rfc822', encoding => '7bit' },
205 body => $orig->as_string,
206 );
207  
208 # Use verbatim `header` (not `header_str`) for these plain-ASCII fields:
209 # header_str runs the address encoder, which warns "empty host portion" on
210 # a bare addr-spec in some Email::MIME versions. The values are already
211 # well-formed, so emit them as-is.
212 4 my $dsn = Email::MIME->create(
213 attributes => { content_type => 'multipart/report', encoding => '7bit' },
214 header => [
215 # The signer's own address: -09 section 11 requires a From
216 # Authentic for this, the DSN's i=1 signature.
217 From => "Mail Delivery System <postmaster\@$signer->{Domain}>",
218 To => $to,
219 Subject => 'Delivery Status Notification (Failure)',
220 ],
221 parts => [ $human, $ds, $orig_part ],
222 );
223 4 _set_report_type($dsn);
224  
225 # The new DSN's envelope is MAIL FROM <> RCPT TO <bounce destination>.
226 4 $signer->{MailFrom} = '<>';
227 4 $signer->{RcptTo} = [$to];
228 4 return { raw => _sign_as_new($signer, $dsn), send_to => $to };
229 }
230  
231 # Parse a raw DSN and validate the RFC 6522 three-part multipart/report
232 # structure: part[0] is human-readable text, one part is machine-readable
233 # delivery-status, and one part is the returned original (message/rfc822 or,
234 # when the body is unrecoverable, text/rfc822-headers). A bare part count is
235 # not enough -- e.g. a report with two text/plain parts and an embedded
236 # original would pass a ">=3" check without being a valid DSN.
237 # Returns ($dsn, $orig_idx, $orig_part); croaks with $who as the prefix.
238 28 ▶sub _parse_report {
Subroutine _parse_report: called CC=13 SCAR=26.5
239 28 my ($raw, $who) = @_;
240 28 my $dsn = parse_mime($raw);
241 28 ▶ my $ct = $dsn->content_type // '';
Condition50%1/2
$dsn->content_type // ""
l!l
280
MC/DC0%0/1
$dsn->content_type // ""
$dsn->content_type
Truth table50%1/2
A
A= $dsn->content_type
Aresult
11
00
242 28 ▶ croak "$who: not a multipart/report DSN" unless $ct =~ m{multipart/report}i;
Branch: 1 branch
BranchTrueFalseTotal
unless $ct =~ m[multipart/report]i 0 28 28
243  
244 28 my @parts = $dsn->subparts;
245 28 ▶ croak "$who: DSN must have at least three parts" unless @parts >= 3;
Branch: 1 branch
BranchTrueFalseTotal
unless @parts >= 3 0 28 28
246  
247 28 ▶ my $part0_ct = $parts[0]->content_type // '';
Condition50%1/2
$parts[0]->content_type // ""
l!l
280
MC/DC0%0/1
$parts[0]->content_type // ""
$parts[0]->content_type
Truth table50%1/2
A
A= $parts[0]->content_type
Aresult
11
00
248 28 ▶ croak "$who: DSN part 1 is not human-readable text (text/plain)"
Branch: 1 branch
BranchTrueFalseTotal
unless $part0_ct =~ m[^text/plain]i 0 28 28
249 unless $part0_ct =~ m{^text/plain}i;
250  
251 28 ▶ my $has_delivery_status = grep { ($_->content_type // '') =~ m{^message/delivery-status}i } @parts;
Condition50%1/2
$_->content_type // ""
l!l
840
MC/DC0%0/1
$_->content_type // ""
$_->content_type
Truth table50%1/2
A
A= $_->content_type
Aresult
11
00
252 28 ▶ croak "$who: DSN has no message/delivery-status part"
Branch: 1 branch
BranchTrueFalseTotal
unless $has_delivery_status 1 27 28
253 unless $has_delivery_status;
254  
255 27 my ($orig_idx, $orig_part);
256 27 for my $i (0 .. $#parts) {
257 81 ▶ my $pct = $parts[$i]->content_type // '';
Condition50%1/2
$parts[$i]->content_type // ""
l!l
810
MC/DC0%0/1
$parts[$i]->content_type // ""
$parts[$i]->content_type
Truth table50%1/2
A
A= $parts[$i]->content_type
Aresult
11
00
258 81 ▶ if ($pct =~ m{^message/rfc822}i || $pct =~ m{^text/rfc822-headers}i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pct =~ m[^message/rfc822]i or $pct =~ m[^text/rfc822-headers]i) 27 54 81
Condition100%3/3
$pct =~ m[^message/rfc822]i or $pct =~ m[^text/rfc822-headers]i
l!l&&r!l&&!r
24354
MC/DC100%2/2
$pct =~ m[^message/rfc822]i or $pct =~ m[^text/rfc822-headers]i
$pct =~ m[^message/rfc822]i $pct =~ m[^text/rfc822-headers]i
Truth table100%3/3
A or B
A= $pct =~ m[^message/rfc822]iB= $pct =~ m[^text/rfc822-headers]i
ABresult
1X1
011
000
259 27 $orig_idx = $i; $orig_part = $parts[$i]; last;
260 }
261 }
262 27 ▶ croak "$who: no embedded original message part" unless defined $orig_idx;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $orig_idx 0 27 27
263 27 return ($dsn, $orig_idx, $orig_part);
264 }
265  
266 # Return the LOWEST-sequence DKIM2-Signature (parsed) of an Email::MIME msg.
267 # For a DSN that is the signature of the system that generated it: §16.3
268 # makes a DSN a new message with exactly one signature, and if that DSN is
269 # itself forwarded onwards, i=1 is still its originator.
270 19 ▶sub _origin_sig {
Subroutine _origin_sig: called CC=2 SCAR=7.0
271 19 my ($msg) = @_;
272 19 my @sigs = map { Mail::DKIM2::Signature->parse($_) } $msg->header_raw('DKIM2-Signature');
273 19 ▶ return unless @sigs;
Branch: 1 branch
BranchTrueFalseTotal
unless @sigs 9 10 19
274 0 my ($bottom) = sort { $a->sequence <=> $b->sequence } @sigs;
275 10 return $bottom;
276 }
277  
278 # -09 §16.4 point 1: "The DSN's DKIM2-Signature will have a signing
279 # domain that is aligned with the recipient of the message that is being
280 # returned. The recipient's address is located in the rt= tag of the last
281 # (highest i= tag) DKIM2-Signature in the returned message."
282 #
283 # This is the check that says the bounce came from the place we handed the
284 # message to, and it is worth nothing unless the DSN's own signature has been
285 # verified -- anyone can write d=. authenticate() therefore verifies the DSN
286 # as well, and only compares the d= it has proved.
287 #
288 # The direction is §7.2's: labels come off the left of the ADDRESS domain, so
289 # d= may be equal to or a parent of the rt= domain, never a child of it. A
290 # system with a dedicated bounce domain signs as its organizational domain
291 # (d=example.com) and puts the bounce address on the subdomain
292 # (<...@bounces.example.com>) -- the subdomain belongs in the address, not in
293 # the signing domain -- so nothing legitimate needs the other direction.
294 #
295 # Returns ('pass'|'fail'|'none', $detail).
296 23 ▶sub _check_alignment {
Subroutine _check_alignment: called CC=12 SCAR=26.4
297 23 my ($dsn_sig, $orig_top) = @_;
298 23 ▶ return ('none', 'DSN carries no DKIM2-Signature of its own') unless $dsn_sig;
Branch: 1 branch
BranchTrueFalseTotal
unless $dsn_sig 0 23 23
299  
300 23 ▶ my $d = $dsn_sig->domain // '';
Condition50%1/2
$dsn_sig->domain // ""
l!l
230
MC/DC0%0/1
$dsn_sig->domain // ""
$dsn_sig->domain
Truth table50%1/2
A
A= $dsn_sig->domain
Aresult
11
00
301 23 ▶ return ('none', 'DSN signature has no d=') unless length $d;
Branch: 1 branch
BranchTrueFalseTotal
unless length $d 0 23 23
302  
303 23 ▶ my $rt = $orig_top ? $orig_top->rcpt_to : undef;
Branch: 1 branch
BranchTrueFalseTotal
$orig_top ? : 23 0 23
304 23 ▶ my @rts = ref($rt) eq 'ARRAY' ? @$rt : (defined $rt ? ($rt) : ());
Branch: 2 branches
BranchTrueFalseTotal
ref $rt eq 'ARRAY' ? : 22 1 23
defined $rt ? : 0 1 1
305 23 ▶ return ('none', "returned message's top signature has no rt= to align with")
Branch: 1 branch
BranchTrueFalseTotal
unless @rts 1 22 23
306 unless @rts;
307  
308 22 for my $r (@rts) {
309 22 my ($rd, $literal) = domain_of($r);
310 22 ▶ next unless $rd && !$literal;
Branch: 1 branch
BranchTrueFalseTotal
unless $rd and not $literal 0 22 22
Condition33%1/3
$rd and not $literal
!ll&&!rl&&r
0022
MC/DC0%0/2
$rd and not $literal
$rd not $literal
Truth table33%1/3
A and not(B)
A= $rdB= not $literal
ABresult
0X0
100
111
311 22 ▶ return ('pass', "DSN d=$d is aligned with rt= $r")
Branch: 1 branch
BranchTrueFalseTotal
if relaxed_domain_match($rd, $d) 15 7 22
312 if relaxed_domain_match($rd, $d);
313 }
314 7 return ('fail', "DSN d=$d is not aligned with the returned message's rt= ("
315 . join(', ', @rts) . ')');
316 }
317  
318 # Authenticate an inbound DSN before propagating it (-09 §16.4):
319 #
320 # * the returned original's DKIM2 chain must verify, from its headers alone
321 # when the DSN carries only headers (point 3);
322 # * the DSN's own signature must verify, and its d= must be aligned with the
323 # rt= of the returned original's top signature -- i.e. the bounce came
324 # from the system the message was handed to (point 1);
325 # * deciding whether that top signature is one the CALLER made (d= and mf=)
326 # is left to the caller (point 2), since only it knows its own domains.
327 #
328 # A DSN that carries no DKIM2-Signature at all is not what §16.4 is about
329 # ("When a system receives a DKIM2 signed DSN"), so it is reported as
330 # dsn_result 'none' with alignment 'none' rather than failed: a caller that
331 # wants to insist on a signed DSN can require them, and one still handling
332 # legacy bounces can see that this was one.
333 #
334 # Args: raw (the DSN), pubkey_callback (as for Verifier), and optionally
335 # skip_timestamp_check. Returns a hashref:
336 # ok 1 iff every check above that could run did pass
337 # result, details the returned original's Verifier verdict
338 # top the returned original's highest DKIM2-Signature, if any
339 # dsn_result,
340 # dsn_details the DSN's own Verifier verdict ('none' if unsigned)
341 # dsn_sig the DSN's originating (i=1) DKIM2-Signature, if any
342 # alignment,
343 # alignment_detail point 1: 'pass', 'fail' or 'none' (not checkable)
344 # headers_only the DSN carried header fields only
345 # embedded the returned original as an Email::MIME
346 # Croaks, as propagate does, when the message is not an RFC 6522 DSN.
347 21 ▶sub authenticate {
Subroutine authenticate: called CC=14 SCAR=26.4
Pod documented
348 21 my ($class, %args) = @_;
349 21 Mail::DKIM2::Util::check_options("$class->authenticate", \%args,
350 qw(Message PubkeyCallback Resolver SkipTimestampCheck));
351 19 ▶ my $raw = $args{Message} or croak "authenticate: need Message";
Branch: 1 branch
BranchTrueFalseTotal
my $raw = $args{"Message"} or croak("authenticate: need Message") 19 0 19
352 # The keys: PubkeyCallback, else the verifier's own DNS fetch through
353 # Resolver (one is made if none is given).
354 19 ▶ my %key_source = map { exists $args{$_} ? ($_ => $args{$_}) : () }
Branch: 1 branch
BranchTrueFalseTotal
exists $args{$_} ? : 19 19 38
355 qw(PubkeyCallback Resolver);
356  
357 19 my (undef, undef, $orig_part) = _parse_report($raw, 'authenticate');
358 19 ▶ my $headers_only = ($orig_part->content_type // '') =~ m{text/rfc822-headers}i;
Condition50%1/2
$orig_part->content_type // ""
l!l
190
MC/DC0%0/1
$orig_part->content_type // ""
$orig_part->content_type
Truth table50%1/2
A
A= $orig_part->content_type
Aresult
11
00
359 19 my $embedded = _embedded($orig_part);
360 19 my $top = _top_sig($embedded);
361  
362 19 my $v = Mail::DKIM2::Verifier->new(%key_source);
363 19 ▶ $v->headers_only(1) if $headers_only;
Branch: 1 branch
BranchTrueFalseTotal
if $headers_only 2 17 19
364 19 ▶ $v->skip_timestamp_check(1) if $args{SkipTimestampCheck};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"SkipTimestampCheck"} 17 2 19
365 19 (my $text = $embedded->as_string) =~ s/\r?\n/\r\n/g;
366 19 $v->PRINT($text);
367 19 $v->CLOSE;
368  
369 # The DSN itself, from the bytes as they arrived: re-serializing the
370 # Email::MIME we parsed could move a byte the body hash covers.
371 19 my $dv = Mail::DKIM2::Verifier->new(%key_source);
372 19 ▶ $dv->skip_timestamp_check(1) if $args{SkipTimestampCheck};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"SkipTimestampCheck"} 17 2 19
373 19 (my $dsn_text = $raw) =~ s/\r?\n/\r\n/g;
374 19 $dv->PRINT($dsn_text);
375 19 $dv->CLOSE;
376 19 my $dsn_result = $dv->result;
377  
378 19 my $dsn_sig = _origin_sig(parse_mime($dsn_text));
379 19 ▶ my ($alignment, $alignment_detail) =
Branch: 2 branches
BranchTrueFalseTotal
$dsn_result eq 'pass' ? : 9 10 19
$dsn_result eq 'none' ? : 9 1 10
380 ($dsn_result eq 'pass') ? _check_alignment($dsn_sig, $top)
381 : ($dsn_result eq 'none') ? ('none', 'DSN carries no DKIM2-Signature of its own')
382 : ('none', "DSN's own signature did not verify");
383  
384 # A DSN with no signature of its own (dsn_result none) is reported as
385 # such, so a caller can relay it as the legacy bounce it is, but it is not
386 # ok: anyone holding a copy of the returned message could have written
387 # it, and point 1 has no d= to align.
388 19 ▶ my $ok = (($v->result // '') eq 'pass')
Condition87%7/8
($v->result // '') eq 'pass' && $dsn_result eq 'pass' && $alignment ne 'fail'
!ll&&!rl&&r
1027
($v->result // "") eq "pass" and $dsn_result eq "pass"
!ll&&!rl&&r
559
$v->result // ""
l!l
190
MC/DC66%2/3
($v->result // '') eq 'pass' && $dsn_result eq 'pass' && $alignment ne 'fail'
$v->result $dsn_result eq "pass" $alignment ne 'fail'
Truth table75%3/4
A and B && C
A= $v->resultB= $dsn_result eq "pass"C= $alignment ne 'fail'
ABCresult
0XX0
10X0
1100
1111
389 && $dsn_result eq 'pass'
390 && ($alignment ne 'fail');
391  
392 return {
393 19 ▶ ok => $ok ? 1 : 0,
Branch: 2 branches
BranchTrueFalseTotal
$ok ? : 7 12 19
$headers_only ? : 2 17 19
394 result => $v->result,
395 details => $v->result_detail,
396 top => $top,
397 dsn_result => $dsn_result,
398 dsn_details => $dv->result_detail,
399 dsn_sig => $dsn_sig,
400 alignment => $alignment,
401 alignment_detail => $alignment_detail,
402 headers_only => $headers_only ? 1 : 0,
403 embedded => $embedded,
404 };
405 }
406  
407 # Propagate a received DSN upstream (-09 §16.3).
408 #
409 # §16.4 is not optional here: "If the verification fails then the DSN MUST
410 # NOT be propagated any further", so propagate authenticates first and croaks
411 # rather than re-signing a DSN it could not authenticate as ours. That needs a
412 # PubkeyCallback; a caller that has authenticated already (or is exercising
413 # the rebuild machinery on a fixture, as t/dsn.t does) passes
414 # SkipAuthentication => 1 to say so.
415 14 ▶sub propagate {
Subroutine propagate: called CC=25 SCAR=33.4
Pod documented
416 14 my ($class, %args) = @_;
417 14 Mail::DKIM2::Util::check_options("$class->propagate", \%args,
418 qw(Message ForwarderDomain Signer PubkeyCallback Resolver
419 SkipAuthentication SkipTimestampCheck));
420 13 ▶ my $raw = $args{Message} or croak "propagate: need Message";
Branch: 1 branch
BranchTrueFalseTotal
my $raw = $args{"Message"} or croak("propagate: need Message") 13 0 13
421 13 ▶ my $fwd = $args{ForwarderDomain} or croak "propagate: need ForwarderDomain";
Branch: 1 branch
BranchTrueFalseTotal
my $fwd = $args{"ForwarderDomain"} or croak("propagate: need ForwarderDomain") 13 0 13
422 13 ▶ my $signer = $args{Signer} or croak "propagate: need Signer";
Branch: 1 branch
BranchTrueFalseTotal
my $signer = $args{"Signer"} or croak("propagate: need Signer") 13 0 13
423  
424 13 ▶ unless ($args{SkipAuthentication}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($args{"SkipAuthentication"}) 8 5 13
425 my $auth = $class->authenticate(
426 Message => $raw,
427 SkipTimestampCheck => $args{SkipTimestampCheck},
428 8 ▶ map { exists $args{$_} ? ($_ => $args{$_}) : () }
Branch: 1 branch
BranchTrueFalseTotal
exists $args{$_} ? : 8 8 16
429 qw(PubkeyCallback Resolver),
430 );
431 8 ▶ unless ($auth->{ok}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($auth->{"ok"}) 4 4 8
432 croak "propagate: DSN did not authenticate (§16.4), not propagating: "
433 . (($auth->{result} // '') ne 'pass'
434 ? ($auth->{details} // $auth->{result} // 'unknown')
435 4 ▶ : $auth->{alignment_detail});
Branch: 1 branch
BranchTrueFalseTotal
($auth->{'result'} // '') ne 'pass' ? : 2 2 4
Condition42%3/7
$auth->{"result"} // ""
l!l
40
($auth->{"details"} // $auth->{"result"}) // "unknown"
l!l
20
$auth->{"details"} // $auth->{"result"}
l!l&&r!l&&!r
200
MC/DC0%0/1
$auth->{"result"} // ""
$auth->{"result"}
MC/DC0%0/2
($auth->{"details"} // $auth->{"result"}) // "unknown"
$auth->{"details"} $auth->{"result"}
Truth table50%1/2
A
A= $auth->{"result"}
Aresult
11
00
Truth table33%1/3
A // B
A= $auth->{"details"}B= $auth->{"result"}
ABresult
1X1
011
000
436 }
437 }
438  
439 9 my ($dsn, $orig_idx, $orig_part) = _parse_report($raw, 'propagate');
440 8 my @parts = $dsn->subparts;
441  
442 8 ▶ my $headers_only = ($orig_part->content_type // '') =~ m{text/rfc822-headers}i;
Condition50%1/2
$orig_part->content_type // ""
l!l
80
MC/DC0%0/1
$orig_part->content_type // ""
$orig_part->content_type
Truth table50%1/2
A
A= $orig_part->content_type
Aresult
11
00
443 8 my $embedded = _embedded($orig_part);
444  
445 # 0. The hop to strip is ForwarderDomain's own: the returned original's
446 # top signature must be its. Authentication shows the chain is
447 # genuine, not that this caller added the top hop.
448 8 my $own = _top_sig($embedded);
449 8 ▶ my $own_d = $own ? ($own->domain // '') : '';
Branch: 1 branch
BranchTrueFalseTotal
$own ? : 8 0 8
Condition50%1/2
$own->domain // ""
l!l
80
MC/DC0%0/1
$own->domain // ""
$own->domain
Truth table50%1/2
A
A= $own->domain
Aresult
11
00
450 8 ▶ croak "propagate: ForwarderDomain $fwd is not the d= ($own_d) of the "
Branch: 1 branch
BranchTrueFalseTotal
unless lc $own_d eq lc $fwd 1 7 8
451 . "returned message's top DKIM2-Signature, so that hop is not ours to strip"
452 unless lc $own_d eq lc $fwd;
453  
454 # 1. Undo the Forwarder's outward modification (reverses the highest MI and
455 # removes that Message-Instance header). If the body cannot be
456 # regenerated, fall back to headers-only.
457 7 my $body_recoverable = 1;
458 {
459 # Determine whether the top MI declares an unrecoverable body.
460 7 my @mis = $embedded->header_raw('Message-Instance');
461 7 ▶ if (@mis) {
Branch: 1 branch
BranchTrueFalseTotal
if (@mis) 7 0 7
462 7 ▶ my ($high) = sort { (extract_mi_version($b) // 0) <=> (extract_mi_version($a) // 0) } @mis;
Condition50%2/4
extract_mi_version($b) // 0
l!l
20
extract_mi_version($a) // 0
l!l
20
MC/DC0%0/1
extract_mi_version($b) // 0
extract_mi_version($b)
MC/DC0%0/1
extract_mi_version($a) // 0
extract_mi_version($a)
Truth table50%1/2
A
A= extract_mi_version($b)
Aresult
11
00
Truth table50%1/2
A
A= extract_mi_version($a)
Aresult
11
00
463 7 my $mi_obj = Mail::DKIM2::MessageInstance->parse($high);
464 7 ▶ $body_recoverable = 0 if $mi_obj->unrecoverable;
Branch: 1 branch
BranchTrueFalseTotal
if $mi_obj->unrecoverable 1 6 7
465 }
466 7 my $undone = Mail::DKIM2::MessageInstance->undo($embedded);
467 7 ▶ $embedded = $undone if $undone; # undo() returns undef if no MI present
Branch: 1 branch
BranchTrueFalseTotal
if $undone 7 0 7
468 }
469  
470 # 2. Remove the DKIM2-Signature the Forwarder added on the outward journey.
471 7 _strip_top_sig($embedded);
472  
473 # 3. The propagated DSN is addressed to the MAIL FROM of the now-highest
474 # DKIM2-Signature of the rebuilt original.
475 7 my $top = _top_sig($embedded);
476 7 ▶ my $upstream = $top ? $top->mail_from : undef;
Branch: 1 branch
BranchTrueFalseTotal
$top ? : 7 0 7
477 7 ▶ croak "propagate: no remaining DKIM2-Signature to derive upstream MAIL FROM"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $upstream 0 7 7
478 unless defined $upstream;
479 # -09 section 16: no DSN goes to a null MAIL FROM.
480 7 ▶ croak "propagate: the now-top DKIM2-Signature mf= is <>, so no DSN may be sent"
Branch: 1 branch
BranchTrueFalseTotal
if $upstream =~ /\A<\s*>\z/ 1 6 7
481 if $upstream =~ /\A<\s*>\z/;
482  
483 # 4. Rebuild the embedded part. If the body is unrecoverable, emit
484 # text/rfc822-headers (headers only); otherwise message/rfc822.
485 6 my $rebuilt_original;
486 6 ▶ if ($headers_only || !$body_recoverable) {
Branch: 1 branch
BranchTrueFalseTotal
if ($headers_only or not $body_recoverable) { } 2 4 6
Condition100%3/3
$headers_only or not $body_recoverable
l!l&&r!l&&!r
114
MC/DC100%2/2
$headers_only or not $body_recoverable
$headers_only not $body_recoverable
Truth table100%3/3
A or not(B)
A= $headers_onlyB= not $body_recoverable
ABresult
1X1
011
000
487 # headers only — strip the body
488 2 $rebuilt_original = _headers_only_part($embedded);
489 } else {
490 4 $rebuilt_original = Email::MIME->create(
491 attributes => { content_type => 'message/rfc822', encoding => '7bit' },
492 body => $embedded->as_string,
493 );
494 }
495  
496 # 5. Replace the original part; leave the human-readable and
497 # delivery-status parts in place (a fuller implementation would rewrite
498 # the human-readable text to remove destination-specific detail).
499 6 $parts[$orig_idx] = $rebuilt_original;
500 6 $dsn->parts_set(\@parts);
501  
502 # 6. The propagated DSN is a NEW message: one Message-Instance (v=1) and one
503 # DKIM2-Signature, signed by the Forwarder with MAIL FROM <>. So the
504 # inbound DSN's OWN instance and signature go: they belong to the DSN we
505 # received, which we have already authenticated (§16.4) and are not
506 # continuing. Leaving them makes the new instance m=2 on a chain whose
507 # i=1 is somebody else's, which is not a chain at all.
508 6 $dsn->header_raw_set('Message-Instance');
509 6 $dsn->header_raw_set('DKIM2-Signature');
510 # 7. A new message from the Forwarder, so its From is the Forwarder's:
511 # -09 section 11 requires a From Authentic for the i=1 signature,
512 # and the reporting MTA's From would name the destination the
513 # message went to, which section 16.3 says to remove.
514 6 $dsn->header_raw_set('From', "Mail Delivery System <postmaster\@$signer->{Domain}>");
515  
516 6 $signer->{MailFrom} = '<>';
517 6 $signer->{RcptTo} = [$upstream];
518 6 return { raw => _sign_as_new($signer, $dsn), upstream_mailfrom => $upstream };
519 }
520  
521 8 1;
522  
523 __END__
« lib/Mail/DKIM2/Hop.pm ↑ Summary lib/Mail/DKIM2/Wrap.pm »