bin/dkim2-milter

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