blib/lib/Web/VWF/Mail.pm

filter: Statementstmt 93.9% 62 / 66 Branchbran 85.0% 17 / 20 Conditioncond 58.8% 10 / 17 MC/DCmcdc 30.0% 3 / 10 Subroutinesub 100% 10 / 10 Podpod 100% 3 / 3 totaltotal 83.3% 105 / 126 CC 17 SCAR 16.9
CC
17
Cov
86%
_sign
9.1
new
6.0
close
5.1
CRAP 5.4
« blib/lib/Web/VWF/Throttle.pm ↑ Summary blib/lib/Web/VWF/Blacklist.pm »
1 package Web::VWF::Mail;
2  
3 # A message on its way to sendmail(1), signed with DKIM when the site has a
4 # key configured.
5 #
6 # The signature is made here, in the web process, rather than by a milter:
7 # the web user normally has no root access to install one, and a message
8 # handed to sendmail(1) never passes smtpd, so smtpd_milters - which only
9 # sees SMTP submissions - would not sign it in any case.
10 #
11 # Mail::DKIM is loaded at run time for the same reason it is only a
12 # recommendation: a site that does not sign, or one whose Mail::DKIM has gone
13 # missing, must still be able to send its contact form. An unsigned message
14 # is a worse outcome than a signed one and a much better one than a lost
15 # enquiry, so every failure here falls back to sending unsigned.
16  
17 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 1 ▶use version; our $VERSION = version->declare('0.003.0');
Subroutine BEGIN: called CC=1 SCAR=0.0
24  
25 1 Readonly::Scalar my $DEFAULT_SENDMAIL => '/usr/sbin/sendmail';
26  
27 # DKIM is defined over CRLF line endings. Both hashes - the body hash and the
28 # header hash - are taken over the message as it would appear on the wire, so
29 # a bare LF anywhere in the message changes them and the signature fails at
30 # the receiver.
31 1 Readonly::Scalar my $CRLF => "\r\n";
32  
33 =head1 NAME
34  
35 Web::VWF::Mail - send mail through sendmail(1), DKIM signed when configured
36  
37 =head1 SYNOPSIS
38  
39 my $mail = Web::VWF::Mail->new(
40 from => 'no-reply@example.com',
41 domain => 'example.com',
42 selector => '202611',
43 keyfile => '/home/site/dkim/202611.private',
44 );
45  
46 $mail->print("To: someone\@example.com\n",
47 "From: \"Example\" <no-reply\@example.com>\n",
48 "Subject: hello\n\n",
49 "Body\n");
50  
51 $mail->close or warn 'the message was not delivered';
52  
53 =head1 DESCRIPTION
54  
55 Buffers a message and, at L</close>, signs it with DKIM if the site has a
56 key and then pipes it to sendmail(1) with C<-t>.
57  
58 Signing is skipped, and the message is sent unsigned, when C<domain>,
59 C<selector> or C<keyfile> is unset, when the key cannot be read, and when
60 Mail::DKIM is not installed or cannot produce a signature. Each of those
61 cases warns, because an unsigned message from a site that expects to sign is
62 worth looking at - but it is still sent.
63  
64 =head1 METHODS
65  
66 =head2 new
67  
68 Takes a hash or a hash reference of:
69  
70 from - envelope sender, also given to sendmail -f (required)
71 domain - the domain to sign for; signing is skipped if unset
72 selector - the DKIM selector, e.g. 202611; signing is skipped if unset
73 keyfile - path to the PEM private key; signing is skipped if unset
74 sendmail - the program to run, defaulting to /usr/sbin/sendmail
75  
76 The envelope sender matters as much as the header: sendmail fills in the web
77 user and this host when it is given nothing, and a receiving site is entitled
78 to reject that.
79  
80 C<new> croaks, with C<from is required>, when C<from> is missing, and with
81 C<from is not a valid envelope sender> when it holds a control character, a
82 space or a leading C<->. The address is passed to sendmail(1) as an
83 argument, and a value such as C<-X/etc/passwd> or one with a line break in it
84 would otherwise be read as an option or as an extra header.
85  
86 =head3 API SPECIFICATION
87  
88 =head4 INPUT
89  
90 {
91 from => { type => 'string', min => 1 },
92 domain => { type => 'string', optional => 1 },
93 selector => { type => 'string', optional => 1 },
94 keyfile => { type => 'string', optional => 1 },
95 sendmail => { type => 'string', optional => 1 },
96 }
97  
98 =head4 OUTPUT
99  
100 { type => 'object', isa => 'Web::VWF::Mail' }
101  
102 =head2 print
103  
104 Appends text to the message. The arguments are joined exactly as C<print>
105 would join them, so a caller can keep writing one C<print> statement per
106 header. It always returns true.
107  
108 =head3 API SPECIFICATION
109  
110 =head4 INPUT
111  
112 { text => { type => 'string', optional => 1 } } # any number of strings
113  
114 =head4 OUTPUT
115  
116 { type => 'integer', value => 1 }
117  
118 =head2 close
119  
120 Signs the message, pipes it to sendmail(1), and returns true if sendmail
121 exited cleanly. Calling it a second time returns the first result without
122 sending the message again, so it is safe in an END block.
123  
124 It returns false, after a C<carp> naming the program and the reason, when
125 sendmail(1) cannot be run, and false when it can be run but exits with a
126 failure status or the message cannot be written to it. Problems with signing
127 are never failures: they warn, and the message goes out unsigned.
128  
129 =head3 API SPECIFICATION
130  
131 =head4 INPUT
132  
133 {}
134  
135 =head4 OUTPUT
136  
137 { type => 'integer', min => 0, max => 1 } # 1 if sendmail exited cleanly
138  
139 =head1 AUTHOR
140  
141 Nigel Horne, C<< <njh at nigelhorne.com> >>
142  
143 =head1 LICENCE AND COPYRIGHT
144  
145 Copyright 2026 Nigel Horne.
146  
147 Usage is subject to the GPL2 licence terms.
148 If you use it,
149 please let me know.
150  
151 =cut
152  
153 12 ▶sub new {
Subroutine new: called CC=6 SCAR=17.9
Pod documented
154 12 my $class = shift;
155 12 ▶ my %args = (ref($_[0]) eq 'HASH') ? %{$_[0]} : @_;
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 1 11 12
156  
157 12 ▶ croak('from is required') unless($args{'from'});
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"from"} 2 10 12
158  
159 # The sender is an argument to sendmail -f, and goes there without a shell,
160 # so the risk is not shell injection but option injection (a leading '-')
161 # and a line break that sendmail -t could treat as the start of a header.
162 10 ▶ croak('from is not a valid envelope sender') if($args{'from'} =~ /[\x00-\x20\x7f]/ || $args{'from'} =~ /\A-/);
Branch: 1 branch
BranchTrueFalseTotal
if $args{"from"} =~ /[\x00-\x20\x7f]/ or $args{"from"} =~ /\A-/ 4 6 10
Condition100%3/3
$args{"from"} =~ /[\x00-\x20\x7f]/ or $args{"from"} =~ /\A-/
l!l&&r!l&&!r
316
MC/DC100%2/2
$args{"from"} =~ /[\x00-\x20\x7f]/ or $args{"from"} =~ /\A-/
$args{"from"} =~ /[\x00-\x20\x7f]/ $args{"from"} =~ /\A-/
Truth table100%3/3
A or B
A= $args{"from"} =~ /[\x00-\x20\x7f]/B= $args{"from"} =~ /\A-/
ABresult
1X1
011
000
163  
164 my $self = {
165 'from' => $args{'from'},
166 'sendmail' => $args{'sendmail'} || $DEFAULT_SENDMAIL,
167 'domain' => $args{'domain'},
168 'selector' => $args{'selector'},
169 6 ▶ 'keyfile' => $args{'keyfile'},
Condition66%2/3
$args{'sendmail'} || $DEFAULT_SENDMAIL
l!l&&r!l&&!r
420
MC/DC0%0/2
$args{'sendmail'} || $DEFAULT_SENDMAIL
$args{'sendmail'} $DEFAULT_SENDMAIL
Truth table66%2/3
A || B
A= $args{'sendmail'}B= $DEFAULT_SENDMAIL
ABresult
1X1
011
000
170 'buffer' => '',
171 'status' => undef,
172 };
173  
174 6 return bless $self, $class;
175 }
176  
177 5 ▶sub print {
Subroutine print: called CC=1 SCAR=0.0
Pod documented
178 5 my $self = shift;
179  
180 5 $self->{'buffer'} .= join('', @_);
181  
182 5 return 1;
183 }
184  
185 5 ▶sub close {
Subroutine close: called CC=5 SCAR=16.3
Pod documented
186 5 my $self = shift;
187  
188 # Undefined, not false, is the marker for "not sent yet": a failed send
189 # has to be remembered as a failure rather than looked at again.
190 5 ▶ return $self->{'status'} if(defined($self->{'status'}));
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"status"} 1 4 5
191  
192 4 my $message = $self->_sign($self->{'buffer'});
193  
194 4 ▶ open(my $fh, '|-', $self->{'sendmail'}, '-t', '-f', $self->{'from'}) or do {
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "|-", $self->{"sendmail"}, "-t", "-f", $self->{"from"} or do { Carp::carp("Cannot run ", $self->{"sendmail"}, ": ", $!); return $self->{"status"} = 0 } 3 1 4
195 1 Carp::carp('Cannot run ', $self->{'sendmail'}, ': ', $!);
196 1 return $self->{'status'} = 0;
197 };
198  
199 # A failed write is not enough to report on its own, because sendmail may
200 # have exited before reading; close() on a pipe reports the exit status
201 # either way, so both are combined.
202 3 my $written = CORE::print($fh $message);
203 3 my $closed = CORE::close($fh);
204  
205 3 ▶ $self->{'status'} = ($written && $closed) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$written && $closed ? : 3 0 3
Condition33%1/3
$written and $closed
!ll&&!rl&&r
003
MC/DC0%0/2
$written and $closed
$written $closed
Truth table33%1/3
A and B
A= $writtenB= $closed
ABresult
0X0
100
111
206  
207 3 return $self->{'status'};
208 }
209  
210 # Return the message, with a DKIM-Signature line in front of it if it can be
211 # signed. Private because a caller that signs part of a message and then
212 # sends it some other way would produce a signature over the wrong bytes.
213 4 ▶sub _sign {
Subroutine _sign: called CC=8 SCAR=22.1
214 4 my ($self, $message) = @_;
215  
216 4 my $domain = $self->{'domain'};
217 4 my $selector = $self->{'selector'};
218 4 my $keyfile = $self->{'keyfile'};
219  
220 4 my $signed = _crlf($message);
221  
222 4 ▶ return $signed unless($domain && $selector && $keyfile);
Branch: 1 branch
BranchTrueFalseTotal
unless $domain and $selector and $keyfile 2 2 4
Condition66%4/6
$domain and $selector and $keyfile
!ll&&!rl&&r
202
$domain and $selector
!ll&&!rl&&r
202
MC/DC33%1/3
$domain and $selector and $keyfile
$domain $selector $keyfile
Truth table50%2/4
A and B and C
A= $domainB= $selectorC= $keyfile
ABCresult
0XX0
10X0
1100
1111
223  
224 2 ▶ unless(-r $keyfile) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-r $keyfile) 1 1 2
225 1 warn "DKIM key $keyfile is not readable; sending unsigned\n";
226 1 return $signed;
227 }
228  
229 1 my $signer = eval {
230 1 require Mail::DKIM::Signer;
231  
232 1 Mail::DKIM::Signer->new(
233 Domain => $domain,
234 Selector => $selector,
235 KeyFile => $keyfile,
236 Algorithm => 'rsa-sha256',
237 # Both header and body relaxed: 'relaxed' alone would sign the
238 # body with simple canonicalisation, so a message that picks up
239 # a trailing newline on the way out would fail.
240 Method => 'relaxed/relaxed',
241 );
242 };
243 1 ▶ if(!$signer) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($signer) 0 1 1
244 0 ▶ warn 'Cannot create DKIM signer: ', $@ || 'unknown error', "; sending unsigned\n";
Condition0%0/2
$@ || 'unknown error'
l!l
00
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
245 0 return $signed;
246 }
247  
248 1 $signer->PRINT($signed);
249 1 $signer->CLOSE;
250  
251 1 my @signatures = $signer->signatures();
252 1 ▶ if(!@signatures) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@signatures) 0 1 1
253 0 warn "DKIM signing produced no signature; sending unsigned\n";
254 0 return $signed;
255 }
256  
257 1 return join('', map { $_->as_string() . $CRLF } @signatures) . $signed;
258 }
259  
260 # sendmail(1) -t accepts CRLF, and DKIM requires it
261 4 ▶sub _crlf {
Subroutine _crlf: called CC=1 SCAR=0.0
262 4 my $message = shift;
263  
264 4 $message =~ s/\r\n/\n/g;
265 4 $message =~ s/\n/$CRLF/g;
266  
267 4 return $message;
268 }
269  
270 1 1;
« blib/lib/Web/VWF/Throttle.pm ↑ Summary blib/lib/Web/VWF/Blacklist.pm »