bin/dkim2-milter

filter: Statementstmt 91.9% 501 / 545 Branchbran 78.4% 196 / 250 Conditioncond 54.4% 86 / 158 MC/DCmcdc 25.5% 23 / 90 Subroutinesub 98.1% 52 / 53 Podpod n/a totaltotal 78.2% 858 / 1096 CC 168 SCAR 37.3
CC
168
Cov
82%
cb_eom
100.8
_get_sign_config
18.1
_do_sign
16.6
CRAP 41.7
« lib/Mail/DKIM2/Validate.pm ↑ Summary lib/Mail/Milter/Authentication/Handler/DKIM2Sign.pm »
1 #!/usr/bin/perl
2 64 ▶use 5.20.0;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 64 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 64 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 64 ▶use Getopt::Long;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 64 ▶use Pod::Usage;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 64 ▶use FindBin;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 64 ▶use lib -d "$FindBin::Bin/../lib/Mail/DKIM2" ? "$FindBin::Bin/../lib" : (); # running from a checkout
Subroutine BEGIN: called CC=2 SCAR=7.1
Branch: 1 branch
BranchTrueFalseTotal
-d "$FindBin::Bin/../lib/Mail/DKIM2" ? : 64 0 64
9 64 ▶use Sendmail::PMilter 1.28 ':all'; # 1.27 never answered MAIL FROM:<>
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 # Imported before _dkim2_info/_header_list_for_hash so the constants and
12 # should_skip are known at compile time. Spec version constants are the single
13 # source of truth in Mail::DKIM2::Common.
14 64 ▶use Mail::DKIM2::Common qw(
Subroutine BEGIN: called CC=1 SCAR=0.0
15 extract_mi_version
16 strip_mi_versions
17 parse_mime
18 DKIM2_DRAFT
19 DKIM2_REPO
20 DKIM2_DATE
21 64 );
22 64 ▶use Mail::DKIM2::Address qw(from_refusal_note);
Subroutine BEGIN: called CC=1 SCAR=0.0
23 64 ▶use Mail::DKIM2::Canon qw(should_skip);
Subroutine BEGIN: called CC=1 SCAR=0.0
24 64 ▶use Mail::DKIM2::Fold qw(fold_header);
Subroutine BEGIN: called CC=1 SCAR=0.0
25 64 ▶use Mail::DKIM2::Key qw(parse_dkim_pubkey load_private_key);
Subroutine BEGIN: called CC=1 SCAR=0.0
26 64 ▶use constant DKIM2_SOFTWARE => 'dkim2-milter';
Subroutine BEGIN: called CC=1 SCAR=0.0
27  
28 # X-DKIM2-Info value per draft-gondwana-dkim2-debug-header-01: a tag-list in
29 # the DKIM2 syntax, every tag (the last included) followed by ";". A ";" has
30 # no escape and ends a tag, so one inside a value becomes ",".
31 86 ▶sub _dkim2_info {
Subroutine _dkim2_info: called CC=2 SCAR=6.9
32 86 my ($action, %extra) = @_;
33 86 my @tags = ("draft=" . DKIM2_DRAFT, "repo=" . DKIM2_REPO,
34 "date=" . DKIM2_DATE, "sw=" . DKIM2_SOFTWARE, "action=$action");
35 86 push @tags, "$_=$extra{$_}" for grep { defined $extra{$_} } sort keys %extra;
36 86 my $val = join ' ', map { (my $t = $_) =~ s/;/,/g; "$t;" } @tags;
37 # Fold only after a ";" or a "," (Section 5): never inside a token, so a
38 # long hn= list breaks between names and a snaps= digest stays whole.
39 # X-DKIM2-Info is excluded from the header hash by the x-* rule, so how it
40 # is folded can never affect a signature.
41 #
42 # fold_header() budgets for the field name, so fold with it attached and
43 # then strip it -- insheader() takes the value alone, in LF form for the
44 # milter protocol.
45 86 (my $folded = fold_header("X-DKIM2-Info: $val", undef, delimiters_only => 1))
46 =~ s/^X-DKIM2-Info:\s*//;
47 86 $folded =~ s/\r\n/\n/g;
48 86 return $folded;
49 }
50  
51 # Return (count, comma-separated-names) of headers that would be included
52 # in the header hash for the given Email::MIME message object.
53 63 ▶sub _header_list_for_hash {
Subroutine _header_list_for_hash: called CC=3 SCAR=11.0
54 63 my ($msg) = @_;
55 63 my @fields;
56 63 for my $header (sort { lc($a) cmp lc($b) } $msg->header_names) {
57 611 ▶ next if should_skip($header);
Branch: 1 branch
BranchTrueFalseTotal
if should_skip($header) 160 451 611
58 451 my @vals = $msg->header_raw($header);
59 451 push @fields, (lc($header)) x scalar(@vals);
60 }
61 63 return (scalar(@fields), join(',', @fields));
62 }
63  
64 64 ▶use Mail::DKIM2::Signer;
Subroutine BEGIN: called CC=1 SCAR=0.0
65 64 ▶use Mail::DKIM2::Verifier;
Subroutine BEGIN: called CC=1 SCAR=0.0
66 64 ▶use Mail::DKIM2::Gate;
Subroutine BEGIN: called CC=1 SCAR=0.0
67 64 ▶use Mail::DKIM2::Hop;
Subroutine BEGIN: called CC=1 SCAR=0.0
68 64 ▶use Mail::DKIM2::MessageInstance;
Subroutine BEGIN: called CC=1 SCAR=0.0
69 64 ▶use Mail::DKIM2::MessageStore;
Subroutine BEGIN: called CC=1 SCAR=0.0
70 64 ▶use Mail::DKIM2::Wrap qw(wrap_single_part);
Subroutine BEGIN: called CC=1 SCAR=0.0
71 64 ▶use Crypt::PRNG qw(random_bytes);
Subroutine BEGIN: called CC=1 SCAR=0.0
72 64 ▶use Email::MIME;
Subroutine BEGIN: called CC=1 SCAR=0.0
73  
74 # --- Command-line options ---
75  
76 64 my %opts;
77 64 ▶GetOptions(\%opts,
Branch: 1 branch
BranchTrueFalseTotal
&GetOptions(\%opts, "socket|s=s", "mode|m=s", "domain|d=s", "selector=s", "keyfile|k=s", "keydir=s", "parent-from=s\@", "algorithm|a=s", "snapshot-dir=s", "dns-json=s", "allow-null-body-recipe", "max-recipe-literals=i", "wrap-single-part", "no-envelope-check", "help|h") or pod2usage(2) 62 2 64
78 'socket|s=s',
79 'mode|m=s',
80 'domain|d=s',
81 'selector=s',
82 'keyfile|k=s',
83 'keydir=s',
84 'parent-from=s@',
85 'algorithm|a=s',
86 'snapshot-dir=s',
87 'dns-json=s',
88 'allow-null-body-recipe',
89 'max-recipe-literals=i',
90 'wrap-single-part',
91 'no-envelope-check',
92 'help|h',
93 ) or pod2usage(2);
94  
95 62 ▶pod2usage(-exitval => 0, -verbose => 2, -noperldoc => 1) if $opts{help};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"help"} 0 62 62
96  
97 62 ▶if (defined $opts{'max-recipe-literals'} && $opts{'max-recipe-literals'} < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"max-recipe-literals"} and $opts{"max-recipe-literals"} < 0) 1 61 62
Condition66%2/3
defined $opts{"max-recipe-literals"} and $opts{"max-recipe-literals"} < 0
!ll&&!rl&&r
6101
MC/DC50%1/2
defined $opts{"max-recipe-literals"} and $opts{"max-recipe-literals"} < 0
defined $opts{"max-recipe-literals"} $opts{"max-recipe-literals"} < 0
Truth table66%2/3
A and B
A= defined $opts{"max-recipe-literals"}B= $opts{"max-recipe-literals"} < 0
ABresult
0X0
100
111
98 1 die "--max-recipe-literals must not be negative\n";
99 }
100 # Retired in 0.29 (-09 contract E2): this hop's own null body Recipe is
101 # always signed. Still accepted so an existing unit file starts.
102 warn "dkim2-milter: --allow-null-body-recipe is deprecated and does nothing: "
103 . "an unsigned null body Recipe is always signed (Mail::DKIM2 0.29)\n"
104 61 ▶ if $opts{'allow-null-body-recipe'};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"allow-null-body-recipe"} 1 60 61
105  
106 61 ▶$opts{socket} //= 'unix:/var/run/dkim2-milter.sock';
Condition100%2/2
$opts{"socket"} //= "unix:/var/run/dkim2-milter.sock"
l!l
592
MC/DC100%1/1
$opts{"socket"} //= "unix:/var/run/dkim2-milter.sock"
$opts{"socket"}
Truth table100%2/2
A
A= $opts{"socket"}
Aresult
11
00
107 61 ▶$opts{algorithm} //= 'rsa-sha256';
Condition50%1/2
$opts{"algorithm"} //= "rsa-sha256"
l!l
061
MC/DC0%0/1
$opts{"algorithm"} //= "rsa-sha256"
$opts{"algorithm"}
Truth table50%1/2
A
A= $opts{"algorithm"}
Aresult
11
00
108 61 ▶$opts{mode} //= 'both';
Condition50%1/2
$opts{"mode"} //= "both"
l!l
610
MC/DC0%0/1
$opts{"mode"} //= "both"
$opts{"mode"}
Truth table50%1/2
A
A= $opts{"mode"}
Aresult
11
00
109  
110 61 ▶unless ($opts{mode} =~ /^(inbound|outbound|both)$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts{"mode"} =~ /^(inbound|outbound|both)$/u) 0 61 61
111 0 die "Invalid --mode: must be inbound, outbound, or both\n";
112 }
113  
114 61 ▶if ($opts{'wrap-single-part'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"wrap-single-part"}) 11 50 61
115 11 ▶ die "--wrap-single-part needs --mode inbound\n" unless $opts{mode} eq 'inbound';
Branch: 1 branch
BranchTrueFalseTotal
unless $opts{"mode"} eq "inbound" 1 10 11
116 10 ▶ die "--wrap-single-part needs --snapshot-dir\n" unless $opts{'snapshot-dir'};
Branch: 1 branch
BranchTrueFalseTotal
unless $opts{"snapshot-dir"} 1 9 10
117 }
118  
119 59 ▶my $do_verify = $opts{mode} eq 'inbound' || $opts{mode} eq 'both';
Condition66%2/3
$opts{'mode'} eq 'inbound' || $opts{'mode'} eq 'both'
l!l&&r!l&&!r
26033
MC/DC50%1/2
$opts{'mode'} eq 'inbound' || $opts{'mode'} eq 'both'
$opts{'mode'} eq 'inbound' $opts{'mode'} eq 'both'
Truth table66%2/3
A || B
A= $opts{'mode'} eq 'inbound'B= $opts{'mode'} eq 'both'
ABresult
1X1
011
000
120 59 ▶my $do_sign = $opts{mode} eq 'outbound' || $opts{mode} eq 'both';
Condition66%2/3
$opts{'mode'} eq 'outbound' || $opts{'mode'} eq 'both'
l!l&&r!l&&!r
33026
MC/DC50%1/2
$opts{'mode'} eq 'outbound' || $opts{'mode'} eq 'both'
$opts{'mode'} eq 'outbound' $opts{'mode'} eq 'both'
Truth table66%2/3
A || B
A= $opts{'mode'} eq 'outbound'B= $opts{'mode'} eq 'both'
ABresult
1X1
011
000
121 # -09 section 14.4: the envelope must match the top signature. Only where the
122 # transaction is the one the message arrived in: in --mode both it is the
123 # outgoing one.
124 59 ▶my $check_envelope = $opts{mode} eq 'inbound' && !$opts{'no-envelope-check'};
Condition100%3/3
$opts{'mode'} eq 'inbound' && !$opts{'no-envelope-check'}
!ll&&!rl&&r
33125
MC/DC100%2/2
$opts{'mode'} eq 'inbound' && !$opts{'no-envelope-check'}
$opts{'mode'} eq 'inbound' !$opts{'no-envelope-check'}
Truth table100%3/3
A && not(B)
A= $opts{'mode'} eq 'inbound'B= !$opts{'no-envelope-check'}
ABresult
0X0
100
111
125  
126 # Determine if signing is possible
127 59 ▶my $can_sign_single = $opts{domain} && $opts{selector} && $opts{keyfile};
Condition33%2/6
$opts{'domain'} && $opts{'selector'} && $opts{'keyfile'}
!ll&&!rl&&r
5900
$opts{"domain"} and $opts{"selector"}
!ll&&!rl&&r
5900
MC/DC0%0/3
$opts{'domain'} && $opts{'selector'} && $opts{'keyfile'}
$opts{"domain"} $opts{"selector"} $opts{'keyfile'}
Truth table25%1/4
A and B && C
A= $opts{"domain"}B= $opts{"selector"}C= $opts{'keyfile'}
ABCresult
0XX0
10X0
1100
1111
128 59 ▶my $can_sign_keydir = $opts{keydir} && -d $opts{keydir};
Condition33%1/3
$opts{'keydir'} && -d $opts{'keydir'}
!ll&&!rl&&r
0059
MC/DC0%0/2
$opts{'keydir'} && -d $opts{'keydir'}
$opts{'keydir'} -d $opts{'keydir'}
Truth table33%1/3
A && B
A= $opts{'keydir'}B= -d $opts{'keydir'}
ABresult
0X0
100
111
129 59 ▶my $can_sign = $can_sign_single || $can_sign_keydir;
Condition33%1/3
$can_sign_single || $can_sign_keydir
l!l&&r!l&&!r
0590
MC/DC0%0/2
$can_sign_single || $can_sign_keydir
$can_sign_single $can_sign_keydir
Truth table33%1/3
A || B
A= $can_sign_singleB= $can_sign_keydir
ABresult
1X1
011
000
130  
131 59 ▶if ($do_sign && !$can_sign) {
Branch: 1 branch
BranchTrueFalseTotal
if ($do_sign and not $can_sign) 0 59 59
Condition66%2/3
$do_sign and not $can_sign
!ll&&!rl&&r
26330
MC/DC0%0/2
$do_sign and not $can_sign
$do_sign not $can_sign
Truth table66%2/3
A and not(B)
A= $do_signB= not $can_sign
ABresult
0X0
100
111
132 0 die "Signing (--mode $opts{mode}) requires --keydir OR (--domain, --selector, and --keyfile)\n";
133 }
134  
135 59 ▶if ($can_sign_single && $can_sign_keydir) {
Branch: 1 branch
BranchTrueFalseTotal
if ($can_sign_single and $can_sign_keydir) 0 59 59
Condition33%1/3
$can_sign_single and $can_sign_keydir
!ll&&!rl&&r
5900
MC/DC0%0/2
$can_sign_single and $can_sign_keydir
$can_sign_single $can_sign_keydir
Truth table33%1/3
A and B
A= $can_sign_singleB= $can_sign_keydir
ABresult
0X0
100
111
136 0 die "Cannot use both --keydir and --domain/--selector/--keyfile\n";
137 }
138  
139 # Preload single-domain signing key
140 59 my $sign_key;
141 59 ▶if ($can_sign_single) {
Branch: 1 branch
BranchTrueFalseTotal
if ($can_sign_single) 0 59 59
142 0 $sign_key = load_private_key($opts{keyfile});
143 0 warn "dkim2-milter: signing enabled for $opts{domain} "
144 . "(selector=$opts{selector}, algorithm=$opts{algorithm})\n";
145 }
146  
147 # Key cache for keydir mode: { domain => { selector, key, algorithm } }
148 59 my %keydir_cache;
149  
150 59 ▶if ($can_sign_keydir) {
Branch: 1 branch
BranchTrueFalseTotal
if ($can_sign_keydir) 59 0 59
151 59 warn "dkim2-milter: signing enabled via keydir $opts{keydir}\n";
152 }
153 59 warn "dkim2-milter: mode=$opts{mode}\n";
154 59 ▶warn "dkim2-milter: wrapping single-part posts\n" if $opts{'wrap-single-part'};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"wrap-single-part"} 9 50 59
155  
156 # Preload DNS overrides if specified
157 59 my $dns_data;
158 59 ▶if ($opts{'dns-json'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"dns-json"}) 59 0 59
159 59 require JSON;
160 59 ▶ open my $fh, '<', $opts{'dns-json'}
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $opts{"dns-json"} or die qq[Cannot read $opts{"dns-json"}: $!\n] 59 0 59
161 or die "Cannot read $opts{'dns-json'}: $!\n";
162 59 local $/;
163 59 $dns_data = JSON::decode_json(<$fh>);
164 59 close $fh;
165 59 warn "dkim2-milter: using DNS overrides from $opts{'dns-json'}\n";
166 }
167  
168 # Snapshot store
169 59 my $snapshot_store;
170 59 ▶if ($opts{'snapshot-dir'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"snapshot-dir"}) 59 0 59
171 $snapshot_store = Mail::DKIM2::MessageStore->new(
172 59 directory => $opts{'snapshot-dir'},
173 );
174 59 warn "dkim2-milter: snapshots in $opts{'snapshot-dir'}\n";
175 }
176  
177 # Options passed to MessageInstance->calculate() for diff-based MI
178 59 my %mi_opts;
179 59 ▶if (defined $opts{'max-recipe-literals'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opts{"max-recipe-literals"}) 0 59 59
180 0 $mi_opts{MaxRecipeLiterals} = $opts{'max-recipe-literals'};
181 0 warn "dkim2-milter: MI strategy: MaxRecipeLiterals=$opts{'max-recipe-literals'}\n";
182 }
183  
184 # --- Key directory lookup ---
185  
186 # The parent From domains a keydir domain may sign for (-09 contract E3.4):
187 # <keydir>/<domain>/parent-from, one domain per line, "#" comments. None
188 # when the file is absent.
189 31 ▶sub _read_parent_from {
Subroutine _read_parent_from: called CC=2 SCAR=11.6
190 31 my ($file) = @_;
191 31 ▶ open my $fh, '<', $file or return [];
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $file or return [] 0 31 31
192 0 my @d = map { s/#.*//r =~ s/\A\s+|\s+\z//gr } <$fh>;
193 0 close $fh;
194 0 return [ grep { length } @d ];
195 }
196  
197 # Look up signing config for a domain from the keydir.
198 # Tries exact domain first, then walks up parent domains.
199 # Returns { domain, selector, key, algorithm } or undef.
200 33 ▶sub _keydir_lookup {
Subroutine _keydir_lookup: called CC=12 SCAR=25.2
201 33 my ($domain) = @_;
202 33 $domain = lc($domain);
203  
204 # Check cache
205 33 ▶ return $keydir_cache{$domain} if exists $keydir_cache{$domain};
Branch: 1 branch
BranchTrueFalseTotal
if exists $keydir_cache{$domain} 0 33 33
206  
207 33 my $try = $domain;
208 33 ▶ while ($try) {
Branch: 1 branch
BranchTrueFalseTotal
if ($try) 36 0 36
209 36 my $dir = "$opts{keydir}/$try";
210 # A directory we cannot read is treated like one that is not there,
211 # and the walk-up below still runs: `next` here would never advance
212 # $try and the milter would spin forever on a permissions mistake.
213 36 ▶ if (-d $dir && opendir(my $dh, $dir)) {
Branch: 2 branches
BranchTrueFalseTotal
if (-d $dir and opendir my $dh, $dir) { } 31 5 36
elsif (-d $dir) { } 1 4 5
Condition100%3/3
-d $dir and opendir my $dh, $dir
!ll&&!rl&&r
4131
MC/DC100%2/2
-d $dir and opendir my $dh, $dir
-d $dir opendir my $dh, $dir
Truth table100%3/3
A and B
A= -d $dirB= opendir my $dh, $dir
ABresult
0X0
100
111
214 # Find the newest .key file (by ctime)
215 31 my @keys = map { $_->[0] }
216 0 sort { $b->[1] <=> $a->[1] }
217 31 ▶ map { [$_, (stat("$dir/$_"))[10] || 0] }
Condition50%1/2
(stat "$dir/$_")[10] || 0
l!l
310
MC/DC0%0/1
(stat "$dir/$_")[10] || 0
(stat "$dir/$_")[10]
Truth table50%1/2
A
A= (stat "$dir/$_")[10]
Aresult
11
00
218 31 grep { /\.key$/ } readdir $dh;
219 31 closedir $dh;
220  
221 31 ▶ if (@keys) {
Branch: 1 branch
BranchTrueFalseTotal
if (@keys) 31 0 31
222 31 my $file = $keys[0];
223 31 (my $selector = $file) =~ s/\.key$//;
224 31 my $key = eval { load_private_key("$dir/$file") };
225 31 ▶ if ($key) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key) 31 0 31
226 # Detect algorithm from key type
227 31 ▶ my $alg = ref($key) =~ /Ed25519/
Branch: 1 branch
BranchTrueFalseTotal
ref($key) =~ /Ed25519/u ? : 0 31 31
228 ? 'ed25519-sha256' : 'rsa-sha256';
229 31 my $config = {
230 domain => $try,
231 selector => $selector,
232 key => $key,
233 algorithm => $alg,
234 parent_from => _read_parent_from("$dir/parent-from"),
235 };
236 # Cache for both the looked-up domain and the matched domain
237 31 $keydir_cache{$domain} = $config;
238 31 ▶ $keydir_cache{$try} = $config if $try ne $domain;
Branch: 1 branch
BranchTrueFalseTotal
if $try ne $domain 1 30 31
239 31 return $config;
240 }
241 }
242 } elsif (-d $dir) {
243 1 warn "dkim2-milter: key directory $dir is not readable: $!\n";
244 }
245 # Walk up: sub.example.com -> example.com -> (stop)
246 5 ▶ $try =~ s/^[^.]+\.// or last;
Branch: 1 branch
BranchTrueFalseTotal
$try =~ s/^[^.]+\.//u or last 3 2 5
247 }
248  
249 # Cache the miss too
250 2 $keydir_cache{$domain} = undef;
251 2 return undef;
252 }
253  
254 # --- Milter setup ---
255  
256 59 my $milter = Sendmail::PMilter->new();
257 59 $milter->setconn($opts{socket});
258  
259 # Insert, change and delete headers; replace the body (--wrap-single-part).
260 59 $milter->register('dkim2-milter', {
261 envfrom => \&cb_envfrom,
262 envrcpt => \&cb_envrcpt,
263 header => \&cb_header,
264 eoh => \&cb_eoh,
265 body => \&cb_body,
266 eom => \&cb_eom,
267 close => \&cb_close,
268 }, SMFIF_ADDHDRS | SMFIF_CHGHDRS | SMFIF_CHGBODY);
269  
270 59 warn "dkim2-milter: listening on $opts{socket}\n";
271 59 $milter->main();
272  
273 # --- Milter callbacks ---
274  
275 59 ▶sub cb_envfrom {
Subroutine cb_envfrom: called CC=1 SCAR=0.0
276 59 my ($ctx, $from) = @_;
277 59 $from =~ s/^<//;
278 59 $from =~ s/>$//;
279 59 $ctx->setpriv({
280 env_from => $from,
281 env_rcpt => [],
282 headers => [],
283 raw_hdrs => [],
284 body => '',
285 });
286 59 return SMFIS_CONTINUE;
287 }
288  
289 60 ▶sub cb_envrcpt {
Subroutine cb_envrcpt: called CC=1 SCAR=0.0
290 60 my ($ctx, $rcpt) = @_;
291 60 $rcpt =~ s/^<//;
292 60 $rcpt =~ s/>$//;
293 60 push @{$ctx->getpriv->{env_rcpt}}, $rcpt;
294 60 return SMFIS_CONTINUE;
295 }
296  
297 571 ▶sub cb_header {
Subroutine cb_header: called CC=1 SCAR=0.0
298 571 my ($ctx, $field, $value) = @_;
299 571 my $priv = $ctx->getpriv;
300 571 my $EOL = "\015\012";
301 # Postfix delivers folded header values with LF continuations;
302 # normalize to CRLF so the reconstructed message is RFC 5322 compliant.
303 571 $value =~ s/\r?\n/$EOL/g;
304 # Store parsed form and raw form
305 571 push @{$priv->{headers}}, [$field, $value];
306 571 push @{$priv->{raw_hdrs}}, "$field: $value$EOL";
307 571 return SMFIS_CONTINUE;
308 }
309  
310 59 ▶sub cb_eoh {
Subroutine cb_eoh: called CC=2 SCAR=6.9
311 59 my ($ctx) = @_;
312 59 my $priv = $ctx->getpriv;
313 59 ▶ $priv->{verify} = _start_verify($priv) if $do_verify;
Branch: 1 branch
BranchTrueFalseTotal
if $do_verify 26 33 59
314 59 return SMFIS_CONTINUE;
315 }
316  
317 59 ▶sub cb_body {
Subroutine cb_body: called CC=2 SCAR=6.9
318 59 my ($ctx, $chunk) = @_;
319 59 my $priv = $ctx->getpriv;
320 59 my $EOL = "\015\012";
321 59 $chunk =~ s/\015?\012/$EOL/g;
322 59 $priv->{body} .= $chunk;
323 59 ▶ _feed_verify($priv->{verify}, $chunk) if $priv->{verify};
Branch: 1 branch
BranchTrueFalseTotal
if $priv->{"verify"} 26 33 59
324 59 return SMFIS_CONTINUE;
325 }
326  
327 59 ▶sub cb_eom {
Subroutine cb_eom: called CC=81 SCAR=46.1
328 59 my ($ctx) = @_;
329 59 my $priv = $ctx->getpriv;
330 59 my $EOL = "\015\012";
331  
332 # Reconstruct the full message
333 59 my $message = join('', @{$priv->{raw_hdrs}}) . $EOL . $priv->{body};
334  
335 # X-DKIM2-Snapshot names the snapshot an inbound milter on this host took
336 # of this message. Nothing from outside may supply one, and it never
337 # leaves: every mode removes it on sight (inbound adds a fresh one).
338 59 my @snapshot_tokens = _strip_snapshot_header($ctx, $priv, \$message);
339  
340 # X-DKIM2-Exploded: a list manager on this host (Mailman, Sympa) marks each
341 # distribution copy, asking the signer for the -08 "exploded" flag. Only
342 # a signing milter acts on it, and it never leaves: removed before signing.
343 59 ▶ $priv->{exploded} = _strip_exploded_header($ctx, $priv, \$message) if $do_sign;
Branch: 1 branch
BranchTrueFalseTotal
if $do_sign 33 26 59
344 # A List-Id says the same without being asked: a list sent this copy,
345 # and a list sends copies to more than one address. That covers a list
346 # manager that adds no hint (stock Mailman). The Signer drops the flag
347 # from a first signature (-09 section 12.5), so an unsigned post the
348 # list originates as i=1 is unaffected.
349 59 ▶ $priv->{exploded} ||= 1
Branch: 1 branch
BranchTrueFalseTotal
if $do_sign and substr($message, 0, (index($message, "\r\n\r\n") + 2)) =~ /^List-Id[ \t]*:/imu 11 48 59
Condition100%5/5
$do_sign and substr($message, 0, (index($message, "\r\n\r\n") + 2)) =~ /^List-Id[ \t]*:/imu
!ll&&!rl&&r
262211
$priv->{"exploded"} ||= 1
l!l
110
MC/DC100%2/2
$do_sign and substr($message, 0, (index($message, "\r\n\r\n") + 2)) =~ /^List-Id[ \t]*:/imu
$do_sign substr($message, 0, (index($message, "\r\n\r\n") + 2)) =~ /^List-Id[ \t]*:/imu
MC/DC100%1/1
$priv->{"exploded"} ||= 1
$priv->{"exploded"}
Truth table100%3/3
A and B
A= $do_signB= substr($message, 0, (index($message, "\r\n\r\n") + 2)) =~ /^List-Id[ \t]*:/imu
ABresult
0X0
100
111
Truth table100%2/2
A
A= $priv->{"exploded"}
Aresult
11
00
350 if $do_sign && substr($message, 0, index($message, "\r\n\r\n") + 2) =~ /^List-Id[ \t]*:/mi;
351  
352 # Extract message-id for logging
353 59 my $msgid = '';
354 59 for my $hdr (@{$priv->{headers}}) {
355 265 ▶ if (lc($hdr->[0]) eq 'message-id') {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $hdr->[0] eq "message-id") 59 206 265
356 59 $msgid = $hdr->[1];
357 59 $msgid =~ s/^\s+//;
358 59 last;
359 }
360 }
361  
362 59 warn "dkim2-milter: processing $msgid from=$priv->{env_from} mode=$opts{mode}\n";
363  
364 # Verification result, shared between the verify and sign blocks.
365 # 'none' means no DKIM2-Signature headers were present.
366 59 my $verify_result = 'none';
367  
368 # --- Inbound: verify and cache snapshot ---
369 59 ▶ if ($do_verify) {
Branch: 1 branch
BranchTrueFalseTotal
if ($do_verify) 26 33 59
370 # Started at the end of the headers; should no eoh have come, here.
371 26 ▶ $verify_result = _finish_verify($priv->{verify} // do {
Condition33%1/3
$priv->{"verify"} // do { my $state = _start_verify($priv); _feed_verify($state, $priv->{"body"}); $state }
l!l&&r!l&&!r
2600
MC/DC0%0/2
$priv->{"verify"} // do { my $state = _start_verify($priv); _feed_verify($state, $priv->{"body"}); $state }
$priv->{"verify"} do { my $state = _start_verify($priv); _feed_verify($state, $priv->{"body"}); $state }
Truth table33%1/3
A // B
A= $priv->{"verify"}B= do { my $state = _start_verify($priv); _feed_verify($state, $priv->{"body"}); $state }
ABresult
1X1
011
000
372 0 my $state = _start_verify($priv);
373 0 _feed_verify($state, $priv->{body});
374 0 $state;
375 });
376 26 my $result = $verify_result;
377 26 warn "dkim2-milter: verify $msgid result=$result\n";
378  
379 # Build the A-R and X-DKIM2-Info headers we're about to add.
380 # Authentication-Results is not in the spec exclusion list so it
381 # is included in the header hash. The MI must be computed over
382 # a synthetic message that already contains these headers.
383 26 my $ar_value = "localhost; dkim2=" . _ar_result($result);
384 26 my $info_value = _dkim2_info("verify=" . _ar_result($result));
385 26 my $ar_raw = "Authentication-Results: $ar_value$EOL";
386 # _dkim2_info() folds with bare LF (the milter wire form); the
387 # message we stamp, snapshot and may wrap is CRLF throughout.
388 26 my $info_raw = "X-DKIM2-Info: " . ($info_value =~ s/\r?\n/$EOL/gr) . $EOL;
389 26 my $message_with_ar = $info_raw . $ar_raw . $message;
390  
391 # Insert the headers into the milter output
392 26 $ctx->insheader('Authentication-Results', $ar_value, 0);
393 26 $ctx->insheader('X-DKIM2-Info', _milter_value($info_value), 0);
394  
395 # Compute MI from the message that includes A-R
396 26 my $mi_header;
397 my %mi_info;
398 26 ▶ if ($snapshot_store) {
Branch: 1 branch
BranchTrueFalseTotal
if ($snapshot_store) 26 0 26
399 # Fail closed: an exception computing the instance (a crafted
400 # message must never take the callback down with it) means no
401 # Message-Instance; the message passes with its A-R.
402 # On arrival: stamp m=1, or accept a top instance that matches
403 # the content. A top that does not match gets no snapshot.
404 26 my $ok = eval { $mi_header = _compute_mi($message_with_ar, \%mi_info); 1 };
405 26 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 1 25 26
406 1 warn "dkim2-milter: no Message-Instance for $msgid: internal error: "
407 . _error_text($@) . "\n";
408 1 $mi_header = undef;
409 }
410 26 ▶ if ($mi_header) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mi_header) 10 16 26
411 10 warn "dkim2-milter: computed MI for $msgid\n";
412 }
413 }
414  
415 # The arrival snapshot: our own m=1 over everything, or a top
416 # instance that matches the content. Nothing else is vouched for.
417 my $arrival = $mi_header ? "Message-Instance: $mi_header$EOL" . $message_with_ar
418 26 ▶ : $mi_info{matched} ? $message_with_ar
Branch: 2 branches
BranchTrueFalseTotal
$mi_header ? : 10 16 26
$mi_info{'matched'} ? : 10 6 16
419 : undef;
420 26 ▶ my $token = defined $arrival ? unpack('H*', random_bytes(16)) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $arrival ? : 20 6 26
421 26 my $snapshot = $arrival;
422  
423 26 ▶ if ($mi_header) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mi_header) 10 16 26
424 10 $ctx->insheader('Message-Instance', _milter_value($mi_header), 0);
425 10 my ($mi_ver) = $mi_header =~ /m=(\d+)/;
426 $ctx->insheader('X-DKIM2-Info', _dkim2_info("mi-m=$mi_ver",
427 hc => $mi_info{hc}, hn => $mi_info{hn},
428 10 ▶ snaps => $token && $snapshot_store->rel_path_for_mi(_snapshot_key($token))), 0);
Condition33%1/3
$token && $snapshot_store->rel_path_for_mi(_snapshot_key($token))
!ll&&!rl&&r
0010
MC/DC0%0/2
$token && $snapshot_store->rel_path_for_mi(_snapshot_key($token))
$token $snapshot_store->rel_path_for_mi(_snapshot_key($token))
Truth table33%1/3
A && B
A= $tokenB= $snapshot_store->rel_path_for_mi(_snapshot_key($token))
ABresult
0X0
100
111
429 10 warn "dkim2-milter: added MI header for $msgid\n";
430 }
431  
432 # --wrap-single-part: stock Mailman pastes a footer into a single-part
433 # body (re-encoding it); a multipart/mixed gets the footer as an extra
434 # part instead. Wrap here, record the wrap as its own unsigned
435 # instance, and snapshot the wrapped message for the outbound diff.
436 # Everything is computed before anything is sent, so any failure
437 # leaves the message unwrapped with only its arrival headers.
438 26 ▶ if ($opts{'wrap-single-part'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"wrap-single-part"}) 9 17 26
439 9 my ($wrap, $wrap_mi, %wrap_info);
440 9 ▶ if ($verify_result !~ /^(?:pass|none)\b/) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $verify_result =~ /^(?:pass|none)\b/u) { } 2 7 9
elsif (not defined $arrival) { } 0 7 7
441 2 warn "dkim2-milter: not wrapping $msgid: arrival result $verify_result\n";
442 } elsif (!defined $arrival) {
443 0 warn "dkim2-milter: not wrapping $msgid: no arrival snapshot\n";
444 } else {
445 7 my $ok = eval {
446 7 my $why;
447 7 ($wrap, $why) = wrap_single_part($arrival);
448 7 ▶ warn "dkim2-milter: not wrapping $msgid: $why\n" unless $wrap;
Branch: 1 branch
BranchTrueFalseTotal
unless $wrap 1 6 7
449 7 ▶ $wrap_mi = _compute_mi($wrap->{message}, \%wrap_info, Snapshot => $arrival) if $wrap;
Branch: 1 branch
BranchTrueFalseTotal
if $wrap 6 1 7
450 7 1;
451 };
452 7 ▶ if (!$ok) {
Branch: 3 branches
BranchTrueFalseTotal
if (not $ok) { } 0 7 7
elsif ($wrap and not $wrap_mi) { } 0 7 7
elsif ($wrap and $wrap_info{'strip_mi_versions'}) { } 0 8 8
453 0 warn "dkim2-milter: not wrapping $msgid: internal error: " . _error_text($@) . "\n";
454 0 $wrap = undef;
455 ▶ } elsif ($wrap && !$wrap_mi) {
Condition66%2/3
$wrap and not $wrap_mi
!ll&&!rl&&r
160
MC/DC0%0/2
$wrap and not $wrap_mi
$wrap not $wrap_mi
Truth table66%2/3
A and not(B)
A= $wrapB= not $wrap_mi
ABresult
0X0
100
111
456 0 warn "dkim2-milter: not wrapping $msgid: no Message-Instance for the wrap\n";
457 0 $wrap = undef;
458 ▶ } elsif ($wrap && $wrap_info{strip_mi_versions}) {
Condition66%2/3
$wrap and $wrap_info{"strip_mi_versions"}
!ll&&!rl&&r
160
MC/DC0%0/2
$wrap and $wrap_info{"strip_mi_versions"}
$wrap $wrap_info{"strip_mi_versions"}
Truth table66%2/3
A and B
A= $wrapB= $wrap_info{"strip_mi_versions"}
ABresult
0X0
100
111
459 # The inbound side never removes instances; a diff that
460 # wants to is not one to put on the wire.
461 0 warn "dkim2-milter: not wrapping $msgid: the wrap's diff would strip instances\n";
462 0 $wrap = undef;
463 }
464 }
465 9 ▶ if ($wrap) {
Branch: 1 branch
BranchTrueFalseTotal
if ($wrap) 6 3 9
466 6 for my $e (@{$wrap->{edits}}) {
467 0 ▶ if ($e->{op} eq 'delete') { $ctx->chgheader($e->{name}, $e->{index}, '') }
Branch: 2 branches
BranchTrueFalseTotal
if ($e->{'op'} eq 'delete') { } 0 6 6
elsif ($e->{'op'} eq 'change') { } 6 0 6
468 6 elsif ($e->{op} eq 'change') { $ctx->chgheader($e->{name}, $e->{index}, $e->{value}) }
469 0 else { $ctx->addheader($e->{name}, $e->{value}) }
470 }
471 6 my $body = $wrap->{body};
472 6 ▶ for (my $o = 0; $o < length $body; $o += 65535) {
Branch: 1 branch
BranchTrueFalseTotal
if ($o < length $body) 8 6 14
473 8 $ctx->replacebody(substr($body, $o, 65535));
474 }
475 6 $ctx->insheader('Message-Instance', _milter_value($wrap_mi), 0);
476 6 my ($wrap_ver) = $wrap_mi =~ /m=(\d+)/;
477 6 $ctx->insheader('X-DKIM2-Info', _milter_value(_dkim2_info("wrap-single-part")), 0);
478 $ctx->insheader('X-DKIM2-Info', _dkim2_info("mi-m=$wrap_ver",
479 hc => $wrap_info{hc}, hn => $wrap_info{hn},
480 6 snaps => $snapshot_store->rel_path_for_mi(_snapshot_key($token))), 0);
481 6 warn "dkim2-milter: wrapped $msgid as m=$wrap_ver\n";
482 6 $snapshot = "Message-Instance: $wrap_mi$EOL" . $wrap->{message};
483 }
484 }
485  
486 # Keep the snapshot (the wrapped form, if wrapped) under a fresh
487 # random token, and name it on the message for the outbound milter.
488 26 ▶ if (defined $snapshot && $snapshot_store) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $snapshot and $snapshot_store) 20 6 26
Condition66%2/3
defined $snapshot and $snapshot_store
!ll&&!rl&&r
6020
MC/DC50%1/2
defined $snapshot and $snapshot_store
defined $snapshot $snapshot_store
Truth table66%2/3
A and B
A= defined $snapshotB= $snapshot_store
ABresult
0X0
100
111
489 20 $snapshot_store->store(_snapshot_key($token), $snapshot);
490 20 $ctx->insheader('X-DKIM2-Snapshot', $token, 0);
491 }
492 }
493  
494 # --- Outbound: compute MI diff if needed, then sign ---
495 59 ▶ if ($do_sign) {
Branch: 1 branch
BranchTrueFalseTotal
if ($do_sign) 33 26 59
496 # No key for this sender: this message is not ours to sign, so it
497 # leaves exactly as it came -- no Message-Instance (unsigned, a
498 # receiver reports it as permerror), no X-DKIM2-Info, no snapshot.
499 # The From: domain is the null-sender fallback for the key lookup,
500 # and is logged for alignment below.
501 33 my $from_hdr_domain = '';
502 33 for my $hdr (@{$priv->{headers}}) {
503 246 ▶ if (lc($hdr->[0]) eq 'from') {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $hdr->[0] eq "from") 33 213 246
504 33 ($from_hdr_domain) = $hdr->[1] =~ /\@([\w.-]+)/;
505 33 ▶ $from_hdr_domain = lc($from_hdr_domain // '');
Condition50%1/2
$from_hdr_domain // ""
l!l
330
MC/DC0%0/1
$from_hdr_domain // ""
$from_hdr_domain
Truth table50%1/2
A
A= $from_hdr_domain
Aresult
11
00
506 33 last;
507 }
508 }
509 33 my $sign_config = _get_sign_config($priv->{env_from}, $from_hdr_domain);
510 33 ▶ unless ($sign_config) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($sign_config) 2 31 33
511 2 warn "dkim2-milter: no signing key for $msgid from=$priv->{env_from}\n";
512 2 _remove_unsigned_instances($ctx, $priv, $msgid);
513 2 return SMFIS_CONTINUE;
514 }
515  
516 # If there are upstream DKIM2-Signature headers we must verify the
517 # chain before extending it. In mode=both the verify block already
518 # ran; in mode=outbound we run it now on demand.
519 #
520 # allow_unsigned_mi: the message may carry a Message-Instance above the
521 # top signature that is OURS to sign. A list manager on this host
522 # (Mailman, Sympa) records its changes as a new m= and hands the
523 # message to us unsigned; the milter is the step that signs it. -08
524 # §14's "Message-Instance m=<x> is not signed" PERMERROR is a receiver's
525 # rule about mail on the wire, and applying it here refused to sign
526 # every list post whose upstream chain was signed. The opt-out does not
527 # loosen the chain gate: i=1..n still have to verify, and
528 # chain_verifies() below still requires the unsigned instance to match
529 # the content and undo cleanly.
530 # The decision itself lives in Mail::DKIM2::Gate, shared with
531 # bin/dkim2sign so the two front ends cannot drift apart: verify the
532 # upstream signatures (allowing our own unsigned instance on top), run
533 # the full undo check on the Message-Instance chain (an upstream that
534 # emitted a non-reversible Recipe would give a signature that fails at
535 # every recipient). A null body Recipe on an UNSIGNED instance (no
536 # upstream signature has its m=: a null this hop is introducing) is
537 # signed; one that arrived signed fails the upstream verification
538 # and is refused (-09 contract E2).
539 # nd= bridge: when the top signature carries nd= we may extend it only
540 # if nd= names the domain we sign as, so tell the gate which. (The
541 # gate ignores this unless the top signature has nd=.)
542 #
543 # The gate judges the message as it will be signed: with this hop's
544 # own Message-Instance (the diff against the snapshot) on top and any
545 # broken intermediate instances removed. A list manager that changed
546 # the message without recording an instance (stock Mailman: the
547 # snapshot diff is its instance) leaves a top instance that no longer
548 # matches; gating before the diff refused every such copy.
549 # DKIM2Sign has always computed first and gated second.
550 31 my $mi_header;
551 my %mi_info;
552 31 ▶ if ($snapshot_store) {
Branch: 1 branch
BranchTrueFalseTotal
if ($snapshot_store) 31 0 31
553 # Fail closed: an exception computing the instance means no
554 # Message-Instance and no signature.
555 # The snapshot is the one the inbound milter named on this very
556 # message (X-DKIM2-Snapshot, stripped above); one token or none.
557 # In --mode both the message came from outside in this same
558 # transaction, so a token on it is not one we gave it.
559 31 my $snap;
560 31 ▶ if (!$do_verify && @snapshot_tokens == 1 && $snapshot_tokens[0] =~ /^[0-9a-f]{32}\z/) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $do_verify and @snapshot_tokens == 1 and $snapshot_tokens[0] =~ /^[0-9a-f]{32}\z/u) 7 24 31
Condition66%4/6
not $do_verify and @snapshot_tokens == 1 and $snapshot_tokens[0] =~ /^[0-9a-f]{32}\z/u
!ll&&!rl&&r
2407
not $do_verify and @snapshot_tokens == 1
!ll&&!rl&&r
0247
MC/DC33%1/3
not $do_verify and @snapshot_tokens == 1 and $snapshot_tokens[0] =~ /^[0-9a-f]{32}\z/u
not $do_verify @snapshot_tokens == 1 $snapshot_tokens[0] =~ /^[0-9a-f]{32}\z/u
Truth table50%2/4
not(A) and B and C
A= not $do_verifyB= @snapshot_tokens == 1C= $snapshot_tokens[0] =~ /^[0-9a-f]{32}\z/u
ABCresult
0XX0
10X0
1100
1111
561 7 $snap = $snapshot_store->fetch(_snapshot_key($snapshot_tokens[0]));
562 7 ▶ $mi_info{snapf} = $snapshot_store->rel_path_for_mi(_snapshot_key($snapshot_tokens[0]))
Branch: 1 branch
BranchTrueFalseTotal
if defined $snap 5 2 7
563 if defined $snap;
564 }
565 31 ▶ my $ok = eval { $mi_header = _compute_mi($message, \%mi_info, Outbound => 1,
Branch: 1 branch
BranchTrueFalseTotal
defined $snap ? : 5 26 31
566 30 (defined $snap ? (Snapshot => $snap) : ())); 1 };
567 31 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 1 30 31
568 1 warn "dkim2-milter: not signing $msgid: internal error computing the "
569 . "Message-Instance: " . _error_text($@) . "\n";
570 1 _remove_unsigned_instances($ctx, $priv, $msgid);
571 1 return SMFIS_CONTINUE;
572 }
573 30 ▶ warn "dkim2-milter: computed MI for $msgid\n" if $mi_header;
Branch: 1 branch
BranchTrueFalseTotal
if $mi_header 11 19 30
574 }
575 my $sign_msg = $mi_info{strip_mi_versions}
576 30 ▶ ? strip_mi_versions($message, @{$mi_info{strip_mi_versions}})
Branch: 1 branch
BranchTrueFalseTotal
$mi_info{'strip_mi_versions'} ? : 4 26 30
577 : $message;
578 30 ▶ $sign_msg = "Message-Instance: $mi_header$EOL" . $sign_msg if $mi_header;
Branch: 1 branch
BranchTrueFalseTotal
if $mi_header 11 19 30
579  
580 30 my $gate_sd = $sign_config->{domain};
581 # Fail closed: an exception anywhere in the gate (a crafted message
582 # must never take the callback down with it) is a logged refusal.
583 # The inbound verdict (mode both) still describes the message only if
584 # this hop added and removed nothing.
585 30 my $gate = eval {
586 30 ▶ Mail::DKIM2::Gate->check($sign_msg,
Branch: 2 branches
BranchTrueFalseTotal
defined $gate_sd ? : 30 0 30
$do_verify && $sign_msg eq $message ? : 0 30 30
Condition33%1/3
$do_verify and $sign_msg eq $message
!ll&&!rl&&r
3000
MC/DC0%0/2
$do_verify and $sign_msg eq $message
$do_verify $sign_msg eq $message
Truth table33%1/3
A and B
A= $do_verifyB= $sign_msg eq $message
ABresult
0X0
100
111
587 (defined $gate_sd ? (SigningDomain => $gate_sd) : ()),
588 ($do_verify && $sign_msg eq $message ? (VerifyResult => $verify_result) : ()),
589 _gate_pubkey_cb());
590 };
591 30 ▶ unless ($gate) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($gate) 1 29 30
592 1 my $err = _error_text($@);
593 1 $gate = { reason => 'error', verify_result => $verify_result,
594 message => "internal error checking the upstream chain: $err" };
595 }
596 30 $verify_result = $gate->{verify_result};
597  
598 # -09 section 13: a message that carries DKIM2 header fields but is
599 # not one this hop can sign MUST NOT be sent on -- so a refusal of a
600 # message with an upstream DKIM2-Signature is a 550 5.7.1 with the
601 # reason (section 13.3). One with no signature (only instances this
602 # host's list manager added, which are removed) goes on unsigned.
603 30 ▶ if ($gate->{reason}
Branch: 1 branch
BranchTrueFalseTotal
if ($gate->{"reason"} and grep {lc $_->[0] eq "dkim2-signature";} @{$$priv{"headers"};}) 8 22 30
Condition100%3/3
$gate->{"reason"} and grep {lc $_->[0] eq "dkim2-signature";} @{$$priv{"headers"};}
!ll&&!rl&&r
2118
MC/DC100%2/2
$gate->{"reason"} and grep {lc $_->[0] eq "dkim2-signature";} @{$$priv{"headers"};}
$gate->{"reason"} grep {lc $_->[0] eq "dkim2-signature";} @{$$priv{"headers"};}
Truth table100%3/3
A and B
A= $gate->{"reason"}B= grep {lc $_->[0] eq "dkim2-signature";} @{$$priv{"headers"};}
ABresult
0X0
100
111
604 104 && grep { lc $_->[0] eq 'dkim2-signature' } @{$priv->{headers}}) {
605 8 warn "dkim2-milter: not signing $msgid: $gate->{message} (rejected 550 5.7.1)\n";
606 8 return _reject($ctx, "not signing: $gate->{message}");
607 }
608  
609 22 ▶ if ($gate->{reason}
Branch: 3 branches
BranchTrueFalseTotal
if ($gate->{'reason'} and $gate->{'reason'} eq 'upstream-chain' || $gate->{'reason'} eq 'error') { } 0 22 22
elsif ($gate->{'reason'} and $gate->{'reason'} eq 'broken-mi-chain') { } 1 21 22
elsif ($gate->{'reason'}) { } 0 21 21
Condition50%3/6
$gate->{"reason"} and $gate->{"reason"} eq "upstream-chain" || $gate->{"reason"} eq "error"
!ll&&!rl&&r
2110
$gate->{"reason"} eq "upstream-chain" or $gate->{"reason"} eq "error"
l!l&&r!l&&!r
001
MC/DC0%0/3
$gate->{"reason"} and $gate->{"reason"} eq "upstream-chain" || $gate->{"reason"} eq "error"
$gate->{"reason"} $gate->{"reason"} eq "upstream-chain" $gate->{"reason"} eq "error"
Truth table50%2/4
A and B or C
A= $gate->{"reason"}B= $gate->{"reason"} eq "upstream-chain"C= $gate->{"reason"} eq "error"
ABCresult
0XX0
1000
11X1
1011
610 && ($gate->{reason} eq 'upstream-chain' || $gate->{reason} eq 'error')) {
611 # Upstream chain is broken — don't extend it with a new signature.
612 0 warn "dkim2-milter: not signing $msgid: $gate->{message}\n";
613 0 _remove_unsigned_instances($ctx, $priv, $msgid);
614 ▶ } elsif ($gate->{reason} && $gate->{reason} eq 'broken-mi-chain') {
Condition66%2/3
$gate->{"reason"} and $gate->{"reason"} eq "broken-mi-chain"
!ll&&!rl&&r
2101
MC/DC50%1/2
$gate->{"reason"} and $gate->{"reason"} eq "broken-mi-chain"
$gate->{"reason"} $gate->{"reason"} eq "broken-mi-chain"
Truth table66%2/3
A and B
A= $gate->{"reason"}B= $gate->{"reason"} eq "broken-mi-chain"
ABresult
0X0
100
111
615 1 warn "dkim2-milter: not signing $msgid: $gate->{message}\n";
616 1 $ctx->insheader('X-DKIM2-Info',
617 _milter_value(_dkim2_info("not-signed=broken-mi-chain")), 0);
618 1 _remove_unsigned_instances($ctx, $priv, $msgid);
619 } elsif ($gate->{reason}) {
620 0 warn "dkim2-milter: not signing $msgid: $gate->{message}\n";
621 0 $ctx->insheader('X-DKIM2-Info',
622 _milter_value(_dkim2_info("not-signed=$gate->{reason}")), 0);
623 0 _remove_unsigned_instances($ctx, $priv, $msgid);
624 } else {
625 # Chain is valid (or there is no upstream chain) — proceed.
626 # Log domain alignment: signing domain vs envelope-from and From:
627 21 ▶ my ($env_domain) = ($priv->{env_from} || '') =~ /\@(.+)$/;
Condition50%1/2
$priv->{'env_from'} || ''
l!l
210
MC/DC0%0/1
$priv->{'env_from'} || ''
$priv->{'env_from'}
Truth table50%1/2
A
A= $priv->{'env_from'}
Aresult
11
00
628 21 ▶ $env_domain = lc($env_domain // '');
Condition50%1/2
$env_domain // ""
l!l
210
MC/DC0%0/1
$env_domain // ""
$env_domain
Truth table50%1/2
A
A= $env_domain
Aresult
11
00
629 21 ▶ my $env_aligned = ($env_domain eq lc($sign_config->{domain})) ? 'yes' : 'no';
Branch: 1 branch
BranchTrueFalseTotal
$env_domain eq lc $sign_config->{'domain'} ? : 20 1 21
630 21 ▶ my $from_aligned = ($from_hdr_domain eq lc($sign_config->{domain})) ? 'yes' : 'no';
Branch: 1 branch
BranchTrueFalseTotal
$from_hdr_domain eq lc $sign_config->{'domain'} ? : 9 12 21
631 21 warn "dkim2-milter: domain alignment $msgid"
632 . " signing=$sign_config->{domain}"
633 . " env_from=$env_domain aligned=$env_aligned"
634 . " from_hdr=$from_hdr_domain aligned=$from_aligned\n";
635  
636 # Sign before touching the headers, so a signer failure leaves no
637 # instance of ours behind.
638 21 my ($sig_header, $sign_why) = _do_sign($sign_msg, $priv, $sign_config);
639 # A list posting domain that is not the signing domain (or below
640 # it) has every rewritten post refused here: say which two.
641 warn "dkim2-milter: $msgid: "
642 . from_refusal_note($sign_config->{domain},
643 21 ▶ map { $_->[1] } grep { lc $_->[0] eq 'from' } @{$priv->{headers}}) . "\n"
Branch: 1 branch
BranchTrueFalseTotal
if not $sig_header and ($sign_why // "") =~ /From header field is not Authentic/u 2 19 21
Condition60%3/5
not $sig_header and ($sign_why // "") =~ /From header field is not Authentic/u
!ll&&!rl&&r
1902
$sign_why // ""
l!l
20
MC/DC50%1/2
not $sig_header and ($sign_why // "") =~ /From header field is not Authentic/u
not $sig_header $sign_why
Truth table66%2/3
not(A) and B
A= not $sig_headerB= $sign_why
ABresult
0X0
100
111
644 if !$sig_header && ($sign_why // '') =~ /From header field is not Authentic/;
645 # As for a gate refusal: with an upstream DKIM2-Signature on it
646 # (and this hop's change unsigned) the message is not sent on.
647 return _reject($ctx, "not signing: $sign_why")
648 if !$sig_header
649 21 ▶ && grep { lc $_->[0] eq 'dkim2-signature' } @{$priv->{headers}};
Branch: 1 branch
BranchTrueFalseTotal
if not $sig_header and grep {lc $_->[0] eq "dkim2-signature";} @{$$priv{"headers"};} 1 20 21
Condition100%3/3
not $sig_header and grep {lc $_->[0] eq "dkim2-signature";} @{$$priv{"headers"};}
!ll&&!rl&&r
1911
MC/DC100%2/2
not $sig_header and grep {lc $_->[0] eq "dkim2-signature";} @{$$priv{"headers"};}
not $sig_header grep {lc $_->[0] eq "dkim2-signature";} @{$$priv{"headers"};}
Truth table100%3/3
not(A) and B
A= not $sig_headerB= grep {lc $_->[0] eq "dkim2-signature";} @{$$priv{"headers"};}
ABresult
0X0
100
111
650 20 ▶ unless ($sig_header) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sig_header) { } 19 1 20
651 1 _remove_unsigned_instances($ctx, $priv, $msgid);
652 } else {
653 # If _compute_mi stripped broken intermediate MI headers, delete them
654 # from the wire message and log a warning. Deletes go first: their
655 # indexes count the Message-Instance fields as received, and an
656 # MTA that counts fields inserted earlier in this end-of-message
657 # would otherwise delete one place off (our own new instance).
658 # Last index first, so each index still counts the fields
659 # as received.
660 19 ▶ if ($mi_info{strip_mi_versions}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mi_info{"strip_mi_versions"}) 4 15 19
661 4 my %gone = map { $_ => 1 } @{$mi_info{strip_mi_versions}};
662 4 my ($count, @del) = (0);
663 4 for my $hdr (@{$priv->{headers}}) {
664 56 ▶ next unless lc($hdr->[0]) eq 'message-instance';
Branch: 1 branch
BranchTrueFalseTotal
unless lc $hdr->[0] eq "message-instance" 49 7 56
665 7 $count++;
666 7 ▶ my $v = extract_mi_version($hdr->[1] =~ s/^\s+//r) // 0;
Condition50%1/2
extract_mi_version($hdr->[1] =~ s/^\s+//ru) // 0
l!l
70
MC/DC0%0/1
extract_mi_version($hdr->[1] =~ s/^\s+//ru) // 0
extract_mi_version($hdr->[1] =~ s/^\s+//ru)
Truth table50%1/2
A
A= extract_mi_version($hdr->[1] =~ s/^\s+//ru)
Aresult
11
00
667 7 ▶ push @del, [$count, $v] if $gone{$v};
Branch: 1 branch
BranchTrueFalseTotal
if $gone{$v} 6 1 7
668 }
669 4 for my $d (reverse @del) {
670 6 $ctx->chgheader('Message-Instance', $d->[0], '');
671 6 ▶ warn "dkim2-milter: deleted " . ($mi_info{restart} ? 'unsigned' : 'broken')
Branch: 1 branch
BranchTrueFalseTotal
$mi_info{'restart'} ? : 5 1 6
672 . " MI m=$d->[1] from wire message\n";
673 }
674 4 my $stripped_str = join(',', map { "m=$_" } @{$mi_info{strip_mi_versions}});
675 4 my $recomp_from = $mi_info{strip_mi_versions}[0] - 1;
676 $ctx->insheader('X-DKIM2-Info', $mi_info{restart}
677 4 ▶ ? _dkim2_info("restarted-unsigned-mi=$stripped_str")
Branch: 1 branch
BranchTrueFalseTotal
$mi_info{'restart'} ? : 3 1 4
678 : _dkim2_info("stripped-broken-mi=$stripped_str,recomputed-from=m$recomp_from"), 0);
679 }
680 19 ▶ if ($mi_header) {
Branch: 1 branch
BranchTrueFalseTotal
if ($mi_header) 10 9 19
681 10 $ctx->insheader('Message-Instance', _milter_value($mi_header), 0);
682 10 my ($mi_ver) = $mi_header =~ /m=(\d+)/;
683 $ctx->insheader('X-DKIM2-Info', _dkim2_info("mi-m=$mi_ver",
684 hc => $mi_info{hc}, hn => $mi_info{hn},
685 10 snapf => $mi_info{snapf}), 0);
686 10 warn "dkim2-milter: added MI header for $msgid\n";
687 }
688  
689 19 $ctx->insheader('DKIM2-Signature', _milter_value($sig_header), 0);
690 19 $ctx->insheader('X-DKIM2-Info',
691 _dkim2_info("sign d=$sign_config->{domain} a=$sign_config->{algorithm}"), 0);
692 19 warn "dkim2-milter: signed $msgid d=$sign_config->{domain} "
693 . "a=$sign_config->{algorithm} sel=$sign_config->{selector}\n";
694 # Informational: we signed over this hop's own null body
695 # Recipe (an unsigned one, our own diff's included: the gate
696 # sees this hop's instance as unsigned too). The message
697 # will PERMERROR downstream, but our header changes are signed.
698 $ctx->insheader('X-DKIM2-Info',
699 _milter_value(_dkim2_info("null-body-recipe")), 0)
700 19 ▶ if $gate->{unsigned_null};
Branch: 1 branch
BranchTrueFalseTotal
if $gate->{"unsigned_null"} 2 17 19
701 }
702 }
703 }
704  
705 47 return SMFIS_CONTINUE;
706 }
707  
708 # Refuse the message with 550 5.7.1 and $reason as the reply text (-08
709 # section 13.3), one line, with sendmail's "%" expansion escaped.
710 9 ▶sub _reject {
Subroutine _reject: called CC=3 SCAR=11.2
711 9 my ($ctx, $reason) = @_;
712 9 ▶ (my $text = $reason // 'not signing') =~ s/[\r\n]+/ /g;
Condition50%1/2
$reason // "not signing"
l!l
90
MC/DC0%0/1
$reason // "not signing"
$reason
Truth table50%1/2
A
A= $reason
Aresult
11
00
713 9 $text =~ s/%/%%/g;
714 9 ▶ $text = substr($text, 0, 900) if length $text > 900;
Branch: 1 branch
BranchTrueFalseTotal
if length $text > 900 0 9 9
715 9 $ctx->setreply('550', '5.7.1', $text);
716 9 return SMFIS_REJECT;
717 }
718  
719 59 ▶sub cb_close {
Subroutine cb_close: called CC=1 SCAR=0.0
720 59 my ($ctx) = @_;
721 59 $ctx->setpriv(undef);
722 59 return SMFIS_CONTINUE;
723 }
724  
725 # --- Signing config lookup ---
726  
727 # Returns { domain, selector, key, algorithm } or undef.
728 33 ▶sub _get_sign_config {
Subroutine _get_sign_config: called CC=9 SCAR=29.0
729 33 my ($env_from, $from_domain_fallback) = @_;
730 33 ▶ my ($from_domain) = ($env_from || '') =~ /\@(.+)$/;
Condition50%1/2
$env_from || ''
l!l
330
MC/DC0%0/1
$env_from || ''
$env_from
Truth table50%1/2
A
A= $env_from
Aresult
11
00
731 # Null sender (bounce/DSN): no envelope domain — fall back to the From:
732 # header domain so our own Postfix-generated bounces still get signed.
733 33 ▶ $from_domain = $from_domain_fallback
Branch: 1 branch
BranchTrueFalseTotal
if not $from_domain and defined $from_domain_fallback and length $from_domain_fallback 0 33 33
Condition33%2/6
not $from_domain and defined $from_domain_fallback and length $from_domain_fallback
!ll&&!rl&&r
3300
not $from_domain and defined $from_domain_fallback
!ll&&!rl&&r
3300
MC/DC0%0/3
not $from_domain and defined $from_domain_fallback and length $from_domain_fallback
not $from_domain defined $from_domain_fallback length $from_domain_fallback
Truth table25%1/4
not(A) and B and C
A= not $from_domainB= defined $from_domain_fallbackC= length $from_domain_fallback
ABCresult
0XX0
10X0
1100
1111
734 if (!$from_domain && defined $from_domain_fallback && length $from_domain_fallback);
735 33 ▶ return unless $from_domain;
Branch: 1 branch
BranchTrueFalseTotal
unless $from_domain 0 33 33
736 33 $from_domain = lc($from_domain);
737  
738 # Single-domain mode — sign regardless of alignment; caller logs alignment.
739 33 ▶ if ($can_sign_single) {
Branch: 1 branch
BranchTrueFalseTotal
if ($can_sign_single) 0 33 33
740 return {
741 domain => $opts{domain},
742 selector => $opts{selector},
743 key => $sign_key,
744 algorithm => $opts{algorithm},
745 0 ▶ parent_from => [ @{ $opts{'parent-from'} || [] } ],
Condition0%0/2
$opts{'parent-from'} || []
l!l
00
MC/DC0%0/1
$opts{'parent-from'} || []
$opts{'parent-from'}
Truth table0%0/2
A
A= $opts{'parent-from'}
Aresult
11
00
746 };
747 }
748  
749 # Keydir mode
750 33 ▶ if ($can_sign_keydir) {
Branch: 1 branch
BranchTrueFalseTotal
if ($can_sign_keydir) 33 0 33
751 33 return _keydir_lookup($from_domain);
752 }
753  
754 0 return;
755 }
756  
757 # --- Verification ---
758  
759 # _gate_pubkey_cb(): PubkeyCallback option answering from --dns-json, else real DNS.
760 # The Domain Policy Record (-09 section 3.8) for the gate's Verifier, from
761 # --dns-json's records for the domains it lists, else DNS. Nothing without
762 # --dns-json: the Verifier then uses DNS. (The Signer never looks it up:
763 # --parent-from / the keydir parent-from file, contract E3.4.)
764 56 ▶sub _policy_cb {
Subroutine _policy_cb: called CC=2 SCAR=13.4
765 56 ▶ return unless $dns_data;
Branch: 1 branch
BranchTrueFalseTotal
unless $dns_data 0 56 56
766 0 ▶ return (PolicyCallback => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
767 0 my ($dom, $who) = @_;
768 0 ▶ return [ map { $_->[1] } @{ $dns_data->{$dom}{_domainkey} || [] } ]
Condition0%0/2
$dns_data->{$dom}{'_domainkey'} || []
l!l
00
MC/DC0%0/1
$dns_data->{$dom}{'_domainkey'} || []
$dns_data->{$dom}{'_domainkey'}
Truth table0%0/2
A
A= $dns_data->{$dom}{'_domainkey'}
Aresult
11
00
769 0 ▶ if $dns_data->{$dom};
Branch: 1 branch
BranchTrueFalseTotal
if $dns_data->{$dom} 0 0 0
770 0 return $who->fetch_domain_policy($dom);
771 56 });
772 }
773  
774 56 ▶sub _gate_pubkey_cb {
Subroutine _gate_pubkey_cb: called CC=2 SCAR=7.8
775 56 ▶ return unless $dns_data;
Branch: 1 branch
BranchTrueFalseTotal
unless $dns_data 0 56 56
776 19 ▶ return (_policy_cb(), PubkeyCallback => sub {
Subroutine __ANON__: called CC=5 SCAR=18.4
777 19 my ($sig, $idx, $v) = @_;
778 19 ▶ $idx //= 0;
Condition50%1/2
$idx //= 0
l!l
190
MC/DC0%0/1
$idx //= 0
$idx
Truth table50%1/2
A
A= $idx
Aresult
11
00
779 19 my $sel = $sig->selector($idx);
780 19 my $dom = $sig->domain;
781 my $key_txt = $dns_data->{$dom}{"$sel._domainkey"}[0][1]
782 19 ▶ if $dns_data->{$dom} && $dns_data->{$dom}{"$sel._domainkey"};
Branch: 1 branch
BranchTrueFalseTotal
if $dns_data->{$dom} and $dns_data->{$dom}{"$sel._domainkey"} 19 0 19
Condition33%1/3
$dns_data->{$dom} and $dns_data->{$dom}{"$sel._domainkey"}
!ll&&!rl&&r
0019
MC/DC0%0/2
$dns_data->{$dom} and $dns_data->{$dom}{"$sel._domainkey"}
$dns_data->{$dom} $dns_data->{$dom}{"$sel._domainkey"}
Truth table33%1/3
A and B
A= $dns_data->{$dom}B= $dns_data->{$dom}{"$sel._domainkey"}
ABresult
0X0
100
111
783 19 ▶ return parse_dkim_pubkey($key_txt) if $key_txt;
Branch: 1 branch
BranchTrueFalseTotal
if $key_txt 19 0 19
784 0 return $v->fetch_public_key($sig, $idx); # fall back to real DNS
785 56 });
786 }
787  
788 # Verification runs as the message arrives: the Verifier gets the header
789 # fields at the end of the headers -- and sends for every signature's key
790 # then, so the answers come back while the body is still arriving -- then
791 # each body chunk, and its verdict at the end of the message. The fields
792 # are the message's less any X-DKIM2-Snapshot, which cb_eom strips.
793 #
794 # Fail closed: a verifier exception, at any step, is reported as temperror
795 # (never pass) and logged at the end, rather than killing the callback.
796 # A verdict ("fail (FAIL: ...)") as Authentication-Results carries it: the
797 # result word, then the detail as an RFC 5322 comment. The detail quotes
798 # signature fields (a bad i= or m= value, as written), so it is cut to
799 # printable ASCII, its "\", "(" and ")" quoted, and kept short: a crafted
800 # i= must not close the comment and add properties of its own.
801 52 ▶sub _ar_result {
Subroutine _ar_result: called CC=6 SCAR=19.9
802 52 my ($verdict) = @_;
803 52 ▶ my ($word, $detail) = ($verdict // '') =~ /\A([a-z]+)(?: \((.*)\))?\z/s
Branch: 1 branch
BranchTrueFalseTotal
() = ($verdict // "") =~ /\A([a-z]+)(?: \((.*)\))?\z/su or return "temperror (unreadable verdict)" 52 0 52
Condition50%1/2
$verdict // ""
l!l
520
MC/DC0%0/1
$verdict // ""
$verdict
Truth table50%1/2
A
A= $verdict
Aresult
11
00
804 or return 'temperror (unreadable verdict)';
805 52 ▶ return $word unless defined $detail && length $detail;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $detail and length $detail 0 52 52
Condition33%1/3
defined $detail and length $detail
!ll&&!rl&&r
0052
MC/DC0%0/2
defined $detail and length $detail
defined $detail length $detail
Truth table33%1/3
A and B
A= defined $detailB= length $detail
ABresult
0X0
100
111
806 52 $detail =~ s/[^\x20-\x7e]//g;
807 52 ▶ $detail = substr($detail, 0, 200) . '...' if length $detail > 200;
Branch: 1 branch
BranchTrueFalseTotal
if length $detail > 200 0 52 52
808 52 $detail =~ s/([\\()])/\\$1/g;
809 52 return "$word ($detail)";
810 }
811  
812 26 ▶sub _start_verify {
Subroutine _start_verify: called CC=6 SCAR=18.0
813 26 my ($priv) = @_;
814 26 my $raw_hdrs = $priv->{raw_hdrs};
815 26 my $state = {};
816 eval {
817 my $verifier = Mail::DKIM2::Verifier->new($check_envelope ? (
818 MailFrom => '<' . ($priv->{env_from} // '') . '>',
819 26 ▶ RcptTo => [ map { "<$_>" } @{ $priv->{env_rcpt} || [] } ],
Branch: 1 branch
BranchTrueFalseTotal
$check_envelope ? : 25 1 26
Condition50%2/4
$priv->{"env_from"} // ""
l!l
250
$priv->{'env_rcpt'} || []
l!l
250
MC/DC0%0/1
$priv->{"env_from"} // ""
$priv->{"env_from"}
MC/DC0%0/1
$priv->{'env_rcpt'} || []
$priv->{'env_rcpt'}
Truth table50%1/2
A
A= $priv->{"env_from"}
Aresult
11
00
Truth table50%1/2
A
A= $priv->{'env_rcpt'}
Aresult
11
00
820 ) : ());
821 26 my %cb = _gate_pubkey_cb();
822 26 ▶ $verifier->set_pubkey_callback($cb{PubkeyCallback}) if $cb{PubkeyCallback};
Branch: 1 branch
BranchTrueFalseTotal
if $cb{"PubkeyCallback"} 26 0 26
823 26 $state->{verifier} = $verifier;
824 26 $verifier->PRINT(join('', grep { !/\AX-DKIM2-Snapshot[ \t]*:/i } @$raw_hdrs)
825 . "\015\012");
826 25 1;
827 26 ▶ } or $state->{error} = $@;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { my $verifier = "Mail::DKIM2::Verifier"->new($check_envelope ? ("MailFrom", '<' . ($priv->{"env_from"} // "") . '>', "RcptTo", [map({"<$_>";} @{$priv->{"env_rcpt"} or [];})]) : ()); my(%cb) = _gate_pubkey_cb(); $verifier->set_pubkey_callback($cb{"PubkeyCallback"}) if $cb{"PubkeyCallback"}; $state->{"verifier"} = $verifier; $verifier->PRINT(join("", grep({not /\AX-DKIM2-Snapshot[ \t]*:/iu;} @$raw_hdrs)) . "\r\n"); 1 } } or $state->{"error"} = $@ 25 1 26
828 26 return $state;
829 }
830  
831 26 ▶sub _feed_verify {
Subroutine _feed_verify: called CC=4 SCAR=13.9
832 26 my ($state, $chunk) = @_;
833 26 ▶ return if defined $state->{error} || $state->{verifier}->stopped;
Branch: 1 branch
BranchTrueFalseTotal
if defined $state->{"error"} or $state->{"verifier"}->stopped 15 11 26
Condition100%3/3
defined $state->{"error"} or $state->{"verifier"}->stopped
l!l&&r!l&&!r
11411
MC/DC100%2/2
defined $state->{"error"} or $state->{"verifier"}->stopped
defined $state->{"error"} $state->{"verifier"}->stopped
Truth table100%3/3
A or B
A= defined $state->{"error"}B= $state->{"verifier"}->stopped
ABresult
1X1
011
000
834 11 ▶ eval { $state->{verifier}->PRINT($chunk); 1 } or $state->{error} = $@;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $state->{"verifier"}->PRINT($chunk); 1 } } or $state->{"error"} = $@ 11 0 11
835 }
836  
837 26 ▶sub _finish_verify {
Subroutine _finish_verify: called CC=4 SCAR=13.9
838 26 my ($state) = @_;
839 26 ▶ unless (defined $state->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $state->{"error"}) 25 1 26
840 25 ▶ eval { $state->{verifier}->CLOSE(); 1 } or $state->{error} = $@;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $state->{"verifier"}->CLOSE; 1 } } or $state->{"error"} = $@ 24 1 25
841 }
842 26 ▶ if (defined $state->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $state->{"error"}) 2 24 26
843 warn "dkim2-milter: verify failed with an internal error: "
844 2 . _error_text($state->{error}) . "\n";
845 2 return 'temperror (internal error)';
846 }
847 24 return $state->{verifier}->result_detail();
848 }
849  
850 # One line of an exception, for the log.
851 5 ▶sub _error_text {
Subroutine _error_text: called CC=4 SCAR=15.0
852 5 my ($err) = @_;
853 5 ▶ $err = "$err" if defined $err;
Branch: 1 branch
BranchTrueFalseTotal
if defined $err 5 0 5
854 5 ▶ $err = 'unknown error' unless defined $err && length $err;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $err and length $err 0 5 5
Condition33%1/3
defined $err and length $err
!ll&&!rl&&r
005
MC/DC0%0/2
defined $err and length $err
defined $err length $err
Truth table33%1/3
A and B
A= defined $errB= length $err
ABresult
0X0
100
111
855 5 $err =~ s/\s+\z//;
856 5 $err =~ s/\s*\n\s*/ /g;
857 5 return $err;
858 }
859  
860 # --- Message-Instance ---
861  
862 # _compute_mi($message, \%info, %o): the Message-Instance this hop adds, or
863 # undef when none is needed or none can be justified.
864 # Snapshot => $previous the message as this host last vouched for it (the
865 # snapshot the X-DKIM2-Snapshot token names); a top
866 # instance that no longer matches is explained by a
867 # diff against it and nothing else.
868 # Outbound => 1 the instance the signer is about to sign. On a
869 # message with no DKIM2-Signature, every instance is
870 # this host's own and unsigned, and the copy leaves
871 # with ONE m=1 (-09 section 12.1): hashes of what is
872 # sent, Recipes back to the message as it arrived.
873 # $info->{restart} then lists the instances that
874 # go (in $info->{strip_mi_versions} too).
875 # Sets $info->{matched} when the top instance matches the content, and
876 # $info->{hc}/{hn} (the hashed header names) for X-DKIM2-Info. Stores nothing:
877 # the callers decide what becomes a snapshot.
878 63 ▶sub _compute_mi {
Subroutine _compute_mi: called CC=10 SCAR=23.0
879 63 my ($message, $info, %o) = @_;
880 63 ▶ $info //= {};
Condition50%1/2
$info //= {}
l!l
630
MC/DC0%0/1
$info //= {}
$info
Truth table50%1/2
A
A= $info
Aresult
11
00
881  
882 63 my $msg = eval { parse_mime($message) };
883 63 ▶ return unless $msg;
Branch: 1 branch
BranchTrueFalseTotal
unless $msg 0 63 63
884  
885 # Record which headers will be included in any hash we compute.
886 63 my ($hcount, $hnames) = _header_list_for_hash($msg);
887 63 $info->{hc} = $hcount;
888 63 $info->{hn} = $hnames;
889  
890 # Which instance, if any, and over what: Mail::DKIM2::Hop decides.
891 my $next = Mail::DKIM2::Hop->next_instance($message, %mi_opts,
892 63 ▶ map { defined $o{$_} ? ($_ => $o{$_}) : () } qw(Snapshot Outbound));
Branch: 1 branch
BranchTrueFalseTotal
defined $o{$_} ? : 42 84 126
893 61 ▶ $info->{matched} = 1 if $next->{matched};
Branch: 1 branch
BranchTrueFalseTotal
if $next->{"matched"} 28 33 61
894 61 ▶ if (@{ $next->{removed} }) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$next->{"removed"};}) 4 57 61
895 4 $info->{strip_mi_versions} = $next->{removed};
896 4 ▶ $info->{restart} = $next->{removed} if $next->{restart};
Branch: 1 branch
BranchTrueFalseTotal
if $next->{"restart"} 3 1 4
897 }
898 warn "dkim2-milter: $next->{detail}\n"
899 61 ▶ if $next->{reason} !~ /\A(?:unchanged|first|changed)\z/ || @{ $next->{removed} };
Branch: 1 branch
BranchTrueFalseTotal
if not $next->{"reason"} =~ /\A(?:unchanged|first|changed)\z/u or @{$next->{"removed"};} 12 49 61
Condition100%3/3
not $next->{"reason"} =~ /\A(?:unchanged|first|changed)\z/u or @{$next->{"removed"};}
l!l&&r!l&&!r
11149
MC/DC100%2/2
not $next->{"reason"} =~ /\A(?:unchanged|first|changed)\z/u or @{$next->{"removed"};}
not $next->{"reason"} =~ /\A(?:unchanged|first|changed)\z/u @{$next->{"removed"};}
Truth table100%3/3
not(A) or B
A= not $next->{"reason"} =~ /\A(?:unchanged|first|changed)\z/uB= @{$next->{"removed"};}
ABresult
1X1
011
000
900 61 ▶ return $next->{instance} ? $next->{instance}->as_header_value : undef;
Branch: 1 branch
BranchTrueFalseTotal
$next->{'instance'} ? : 27 34 61
901 }
902  
903 # Not signing: remove every Message-Instance no DKIM2-Signature on the
904 # message covers (m= above every signature's m=). Those are instances hops on
905 # this host added for a signature that is not going to be made; left in,
906 # every receiver reports "m=N is not signed". Without them an unsigned post
907 # has no DKIM2 at all, and a signed one fails honestly against the last
908 # signature (a hop changed it without signing). Deletes go last first, by
909 # index among the fields as received; nothing of ours has been inserted.
910 5 ▶sub _remove_unsigned_instances {
Subroutine _remove_unsigned_instances: called CC=9 SCAR=23.8
911 5 my ($ctx, $priv, $msgid) = @_;
912 5 my $covered = 0;
913 5 for my $h (grep { lc $_->[0] eq 'dkim2-signature' } @{$priv->{headers}}) {
914 0 my ($m) = $h->[1] =~ /(?:\A|;)\s*m\s*=\s*(\d+)/;
915 0 ▶ $covered = $m if defined $m && $m > $covered;
Branch: 1 branch
BranchTrueFalseTotal
if defined $m and $m > $covered 0 0 0
Condition0%0/3
defined $m and $m > $covered
!ll&&!rl&&r
000
MC/DC0%0/2
defined $m and $m > $covered
defined $m $m > $covered
Truth table0%0/3
A and B
A= defined $mB= $m > $covered
ABresult
0X0
100
111
916 }
917 5 my @mi = grep { lc $_->[0] eq 'message-instance' } @{$priv->{headers}};
918 5 my @gone;
919 5 for my $i (0 .. $#mi) {
920 4 ▶ my $v = extract_mi_version($mi[$i][1] =~ s/^\s+//r) // 0;
Condition50%1/2
extract_mi_version($mi[$i][1] =~ s/^\s+//ru) // 0
l!l
40
MC/DC0%0/1
extract_mi_version($mi[$i][1] =~ s/^\s+//ru) // 0
extract_mi_version($mi[$i][1] =~ s/^\s+//ru)
Truth table50%1/2
A
A= extract_mi_version($mi[$i][1] =~ s/^\s+//ru)
Aresult
11
00
921 4 ▶ push @gone, [$i + 1, $v] if $v > $covered;
Branch: 1 branch
BranchTrueFalseTotal
if $v > $covered 4 0 4
922 }
923 5 ▶ return unless @gone;
Branch: 1 branch
BranchTrueFalseTotal
unless @gone 3 2 5
924 2 $ctx->chgheader('Message-Instance', $_->[0], '') for reverse @gone;
925 2 my $list = join(',', map { "m=$_->[1]" } sort { $a->[1] <=> $b->[1] } @gone);
926 2 $ctx->insheader('X-DKIM2-Info', _milter_value(_dkim2_info("removed-unsigned-mi=$list")), 0);
927 2 warn "dkim2-milter: not signing $msgid: removed unsigned $list\n";
928 }
929  
930 # The snapshot store key for an X-DKIM2-Snapshot token.
931 48 ▶sub _snapshot_key { "X-DKIM2-Snapshot:$_[0]" }
Subroutine _snapshot_key: called CC=1 SCAR=0.0
932  
933 # Remove every X-DKIM2-Snapshot field: from the wire (deleted last first, by
934 # index among the fields as received, before anything is inserted) and from
935 # the reconstructed message. Returns the tokens that were there.
936 59 ▶sub _strip_snapshot_header {
Subroutine _strip_snapshot_header: called CC=1 SCAR=0.0
937 59 my ($ctx, $priv, $message_ref) = @_;
938 59 return _strip_header($ctx, $priv, $message_ref, 'X-DKIM2-Snapshot');
939 }
940  
941 # Remove every X-DKIM2-Exploded field, as above. True if there was one: the
942 # -07 contract makes its presence, whatever its value, the request.
943 33 ▶sub _strip_exploded_header {
Subroutine _strip_exploded_header: called CC=2 SCAR=6.9
944 33 my ($ctx, $priv, $message_ref) = @_;
945 33 my @values = _strip_header($ctx, $priv, $message_ref, 'X-DKIM2-Exploded');
946 33 ▶ return @values ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
@values ? : 1 32 33
947 }
948  
949 # Remove every $name field from the wire (deleted last first, by index among
950 # the fields as received, before anything is inserted) and from the
951 # reconstructed message. Returns the values that were there, trimmed.
952 92 ▶sub _strip_header {
Subroutine _strip_header: called CC=4 SCAR=13.9
953 92 my ($ctx, $priv, $message_ref, $name) = @_;
954 10 my @val = map { $_->[1] =~ s/^\s+|\s+$//gr }
955 92 grep { lc $_->[0] eq lc $name } @{$priv->{headers}};
956 92 ▶ return () unless @val;
Branch: 1 branch
BranchTrueFalseTotal
unless @val 82 10 92
957 10 $ctx->chgheader($name, $_, '') for reverse 1 .. @val;
958 10 my $sep = index($$message_ref, "\015\012\015\012");
959 10 ▶ if ($sep >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sep >= 0) 10 0 10
960 10 my $head = substr($$message_ref, 0, $sep + 2);
961 10 $head =~ s/^\Q$name\E[ \t]*:[^\r\n]*\r\n(?:[ \t][^\r\n]*\r\n)*//mig;
962 10 substr($$message_ref, 0, $sep + 2) = $head;
963 }
964 10 return @val;
965 }
966  
967 # Convert CRLF folding to LF for milter insheader (CRLF = end of value)
968 82 ▶sub _milter_value {
Subroutine _milter_value: called CC=1 SCAR=0.0
969 82 my ($val) = @_;
970 82 $val =~ s/\r\n/\n/g;
971 82 return $val;
972 }
973  
974 # --- Signing ---
975  
976 21 ▶sub _do_sign {
Subroutine _do_sign: called CC=12 SCAR=28.1
977 21 my ($message, $priv, $config) = @_;
978  
979 21 my $signer;
980 # Fail closed, as for the gate: an exception means no signature.
981 21 my $ok = eval {
982 $signer = Mail::DKIM2::Signer->new(
983 Domain => $config->{domain},
984 Selector => $config->{selector},
985 Key => $config->{key},
986 Algorithm => $config->{algorithm},
987 MailFrom => ( length($priv->{env_from} // '') ? $priv->{env_from} : '<>' ),
988 RcptTo => $priv->{env_rcpt},
989 ($priv->{exploded} ? (Exploded => 1) : ()),
990 # -09 contract E3.4: a d= below the From domain signs only for
991 # a parent the configuration lists; no DNS lookup.
992 ParentFromCallback => Mail::DKIM2::Address::parent_from_matcher(
993 21 ▶ @{ $config->{parent_from} || [] }),
Branch: 2 branches
BranchTrueFalseTotal
length($priv->{'env_from'} // '') ? : 21 0 21
$priv->{'exploded'} ? : 6 15 21
Condition50%2/4
$priv->{"env_from"} // ""
l!l
210
$config->{'parent_from'} || []
l!l
210
MC/DC0%0/1
$priv->{"env_from"} // ""
$priv->{"env_from"}
MC/DC0%0/1
$config->{'parent_from'} || []
$config->{'parent_from'}
Truth table50%1/2
A
A= $priv->{"env_from"}
Aresult
11
00
Truth table50%1/2
A
A= $config->{'parent_from'}
Aresult
11
00
994 );
995 21 $signer->PRINT($message);
996 21 $signer->CLOSE();
997 21 1;
998 };
999 21 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 21 21
1000 0 my $why = "internal error in the signer: " . _error_text($@);
1001 0 warn "dkim2-milter: not signing: $why\n";
1002 0 return (undef, $why);
1003 }
1004  
1005 21 ▶ unless (($signer->result // '') eq 'signed') {
Branch: 1 branch
BranchTrueFalseTotal
unless (($signer->result // "") eq "signed") 2 19 21
Condition50%1/2
$signer->result // ""
l!l
210
MC/DC0%0/1
$signer->result // ""
$signer->result
Truth table50%1/2
A
A= $signer->result
Aresult
11
00
1006 2 ▶ my $why = $signer->details // $signer->result // 'no result';
Condition40%2/5
($signer->details // $signer->result) // "no result"
l!l
20
$signer->details // $signer->result
l!l&&r!l&&!r
200
MC/DC0%0/2
($signer->details // $signer->result) // "no result"
$signer->details $signer->result
Truth table33%1/3
A // B
A= $signer->detailsB= $signer->result
ABresult
1X1
011
000
1007 2 ▶ warn "dkim2-milter: not signing: signer result="
Condition40%2/5
($signer->result_detail // $signer->result) // "none"
l!l
20
$signer->result_detail // $signer->result
l!l&&r!l&&!r
200
MC/DC0%0/2
($signer->result_detail // $signer->result) // "none"
$signer->result_detail $signer->result
Truth table33%1/3
A // B
A= $signer->result_detailB= $signer->result
ABresult
1X1
011
000
1008 . ($signer->result_detail // $signer->result // 'none') . "\n";
1009 2 return (undef, $why);
1010 }
1011  
1012 19 my $header = $signer->as_string();
1013 # Strip "DKIM2-Signature: " prefix for insheader
1014 19 $header =~ s/^DKIM2-Signature:\s*//;
1015 # Convert CRLF folding to LF folding for milter protocol
1016 19 $header =~ s/\r\n/\n/g;
1017 19 return $header;
1018 }
1019  
1020 __END__
« lib/Mail/DKIM2/Validate.pm ↑ Summary lib/Mail/Milter/Authentication/Handler/DKIM2Sign.pm »