| File: | lib/Mail/Send/DKIM.pm |
| Coverage: | 87.5% |
| line | stmt | bran | cond | sub | time | code |
|---|---|---|---|---|---|---|
| 1 | package Mail::Send::DKIM; | |||||
| 2 | ||||||
| 3 | # The signing half of bin/mail-dkim: given an object configured with the | |||||
| 4 | # domains this host signs for, a message either comes back signed or comes back | |||||
| 5 | # as undef and the caller sends it as it is. Nothing here dies on a signing | |||||
| 6 | # problem, because a missing key must never stop mail being delivered. | |||||
| 7 | ||||||
| 8 | 7 7 7 | 75347 6 87 | use strict; | |||
| 9 | 7 7 7 | 12 3 119 | use warnings; | |||
| 10 | ||||||
| 11 | 7 7 7 | 1026 383278 168 | use Mail::DKIM::Signer; | |||
| 12 | 7 7 7 | 1359 107882 176 | use Params::Get; | |||
| 13 | 7 7 7 | 1907 514450 132 | use Object::Configure; | |||
| 14 | ||||||
| 15 | 7 7 7 | 31 5 28 | use version; our $VERSION = version->declare('0.001.0'); | |||
| 16 | ||||||
| 17 - 156 | =head1 NAME
Mail::Send::DKIM - sign a message with DKIM and hand it to sendmail
=head1 VERSION
0.001.0
=head1 SYNOPSIS
use Mail::Send::DKIM;
my $dkim = Mail::Send::DKIM->new(
domains => ['example.org'],
keydir => "$ENV{HOME}/dkim",
);
my $signed = $dkim->sign($message);
$message = $signed if(defined($signed));
exit($dkim->send($message, '-t', '-f', 'alerts@example.org'));
=head1 DESCRIPTION
Signs a message with DKIM when its C<From:> domain is one this host signs for,
and hands it to sendmail with whatever arguments sendmail should have. The
signed form is C<rsa-sha256> with C<relaxed> canonicalization, which is the
shape receiving sites expect.
The signature covers the message in the form DKIM defines, where every line
ends CRLF. What is handed to sendmail is the local form instead: LF line
endings, and no carriage return anywhere, whatever arrived. A CR would be data
to the MTA that keeps the message - Postfix and Exim both write the CRLF of
SMTP themselves - so a message that had travelled with CRLF in it would reach
the receiver with the CRs doubled and fail the signature it had just been given.
Nothing here dies because a key is missing: signing either produces a signed
message or produces nothing and says why on standard error, so a caller can
always fall back to sending the message as it is.
=head1 PLATFORMS
Windows is not supported. L<Mail::DKIM> needs L<Crypt::OpenSSL::RSA>, and that
module and its prerequisites, L<Crypt::OpenSSL::Random> and
L<Crypt::OpenSSL::Bignum>, do not link on Windows: Strawberry Perl's static
OpenSSL needs the C<crypt32> library, which their F<Makefile.PL> files do not
ask for. F<Makefile.PL> stops with C<OS unsupported> there, rather than failing
part-way through the install.
=head1 ENVIRONMENT
B<DKIM_DOMAINS>, B<DKIM_KEYDIR>, B<DKIM_SELECTOR>, B<DKIM_KEYFILE> and
B<SENDMAIL> are read by B<new> when the corresponding option is not given, so
the command line programs needs no configuration of its own.
=head1 PROGRAMS
The distribution is named after this module and installs four programs with
it, each with a page of its own: C<perldoc bin/mail-dkim>,
C<perldoc bin/dmarc-report.pl>, C<perldoc bin/dmarc-check-mail.pl> and
C<perldoc bin/dmarc-weekly.sh> in a checkout, and the same pages as manual
pages once installed.
=over 4
=item L<mail-dkim|https://github.com/nigelhorne/Mail-Send-DKIM/blob/master/bin/mail-dkim>
The front end to this module: a message on standard input is signed when its
C<From:> domain is one named in C<DKIM_DOMAINS>, and handed to sendmail(1) with
the arguments it was given. Put it where a script or a crontab calls sendmail
and the mail is signed without the script being changed. Its page has the
environment variables, the key layout and the exit status.
=item L<dmarc-report|https://github.com/nigelhorne/Mail-Send-DKIM/blob/master/bin/dmarc-report.pl>
Reads a directory of DMARC aggregate reports and says who sent mail for each
domain, marking every source that is not an expected one (C<DMARC_EXPECTED>),
every expected one whose mail did not authenticate, and every message that was
quarantined or rejected by policy despite passing. The exit status is non-zero
when anything needs looking at. Its page has the options.
=item L<dmarc-weekly.sh|https://github.com/nigelhorne/Mail-Send-DKIM/blob/master/bin/dmarc-weekly.sh>
The cron wrapper around it: silent when the week is clean, a mail with the full
output when it is not, and the reports moved aside to an archive afterwards.
C<DRY_RUN=1> rehearses a run and C<--crontab> prints the line to paste into a
crontab; see L</A CRONTAB ENTRY> below.
=item L<dmarc-check-mail.pl|https://github.com/nigelhorne/Mail-Send-DKIM/blob/master/bin/dmarc-check-mail.pl>
Sends one message, signed with this module, to a mailbox that can be read, so
that the C<Authentication-Results> header at the far end shows what receivers
make of this host's mail before the DMARC policy is tightened. C<--plain>
sends the same message unsigned, which is what a cron job without the module
looks like.
=back
The three DMARC programs are the reason the module exists: they report on the
mail it signs, and the weekly one sends its own report through it.
=head1 METHODS
=head2 B<new> %options
=over 4
=item C<domains>
The domains to sign for, either an array reference or a string of them
separated by commas or spaces. Defaults to C<$ENV{DKIM_DOMAINS}>. A message
from any other domain is left alone.
=item C<keydir>
Where the private keys are. Defaults to C<$ENV{DKIM_KEYDIR}>, or F<~/dkim>.
=item C<selector>
The selector the key is published under, which names the key file
F<< <keydir>/<selector>.private >>. Defaults to C<$ENV{DKIM_SELECTOR}>; with
neither set, the key file's own name is the selector when B<keyfile> is given,
and otherwise the only F<*.private> file in B<keydir> is used and its name is
the selector.
=item C<keyfile>
The private key to sign with, when it does not live at
F<< <keydir>/<selector>.private >> - a tester given one key to try, for
instance. Defaults to C<$ENV{DKIM_KEYFILE}>. It is used as it stands, and
the selector comes from its name unless one is given.
=item C<sendmail>
The program B<send> hands the message to. Defaults to C<$ENV{SENDMAIL}>, or
F</usr/sbin/sendmail>.
=back
=cut | |||||
| 157 | ||||||
| 158 | sub new | |||||
| 159 | { | |||||
| 160 | 21 | 206213 | my $class = shift; | |||
| 161 | ||||||
| 162 | # Handle hash or hashref arguments | |||||
| 163 | 21 | 103 | my $params = Params::Get::get_params(undef, \@_) // {}; | |||
| 164 | ||||||
| 165 | 21 | 422 | $params = Object::Configure::configure($class, $params); | |||
| 166 | ||||||
| 167 | 21 | 191391 | my $home = $params->{home} || $ENV{'HOME'} || (getpwuid($<))[7] || '.'; | |||
| 168 | ||||||
| 169 | 21 | 78 | my $domains = $params->{'domains'} // $ENV{'DKIM_DOMAINS'} // ''; | |||
| 170 | 21 | 80 | my @domains = ref($domains) eq 'ARRAY' ? @$domains : split(/[\s,]+/, $domains); | |||
| 171 | ||||||
| 172 | my $self = { | |||||
| 173 | 20 20 | 235 42 | 'domains' => { map { lc($_) => 1 } grep { length } @domains }, | |||
| 174 | 'keydir' => $params->{'keydir'} // $ENV{'DKIM_KEYDIR'} // "$home/dkim", | |||||
| 175 | 'selector' => $params->{'selector'} // $ENV{'DKIM_SELECTOR'}, | |||||
| 176 | 'keyfile' => $params->{'keyfile'} // $ENV{'DKIM_KEYFILE'}, | |||||
| 177 | 21 | 73 | 'sendmail' => $params->{'sendmail'} // $ENV{'SENDMAIL'} // '/usr/sbin/sendmail', | |||
| 178 | }; | |||||
| 179 | ||||||
| 180 | 21 | 98 | return bless($self, $class); | |||
| 181 | } | |||||
| 182 | ||||||
| 183 - 193 | =head2 B<sign> $message Returns the message with a C<DKIM-Signature> header added, or C<undef> when there is nothing to do or nothing that can be done: the domain is not one of B<domains>, there is no C<From:> header, no key can be found or read, or the signer failed. The reasons are warnings on standard error; the message itself is never altered in the undef case, so the caller sends it unchanged. Carriage returns are folded to LF on the way, so what comes back is in the local form. =cut | |||||
| 194 | ||||||
| 195 | sub sign | |||||
| 196 | { | |||||
| 197 | 18 | 788 | my $self = shift; | |||
| 198 | ||||||
| 199 | 18 | 50 | my $params = Params::Get::get_params('message', \@_); | |||
| 200 | 18 | 307 | my $message = $params->{message}; | |||
| 201 | ||||||
| 202 | 18 | 35 | my $domain = from_domain($message); | |||
| 203 | 18 | 26 | return unless(defined($domain)); | |||
| 204 | 17 | 42 | return unless($self->{'domains'}->{$domain}); | |||
| 205 | ||||||
| 206 | 14 | 29 | my $selector = $self->selector; | |||
| 207 | 14 | 22 | return unless(defined($selector)); | |||
| 208 | ||||||
| 209 | # A key file named outright needs neither the directory nor the naming | |||||
| 210 | # convention; otherwise the key is <keydir>/<selector>.private. | |||||
| 211 | 12 | 43 | my $keyfile = $self->{'keyfile'} // $self->{'keydir'} . "/$selector.private"; | |||
| 212 | 12 | 80 | unless(-r $keyfile) { | |||
| 213 | 0 | 0 | warn "Mail::Send::DKIM: no readable key at $keyfile; sending $domain unsigned"; | |||
| 214 | 0 | 0 | return; | |||
| 215 | } | |||||
| 216 | ||||||
| 217 | # DKIM hashes the message in the form it travels in, where every line | |||||
| 218 | # ends CRLF, so the signature is made over a CRLF copy of what arrived. | |||||
| 219 | 12 | 26 | (my $wire = _local($message)) =~ s/\n/\r\n/g; | |||
| 220 | ||||||
| 221 | 12 | 15 | my $signed; | |||
| 222 | eval { | |||||
| 223 | 12 | 132 | my $signer = Mail::DKIM::Signer->new( | |||
| 224 | Algorithm => 'rsa-sha256', | |||||
| 225 | Method => 'relaxed', | |||||
| 226 | Domain => $domain, | |||||
| 227 | Selector => $selector, | |||||
| 228 | KeyFile => $keyfile, | |||||
| 229 | ); | |||||
| 230 | 12 | 1937 | $signer->PRINT($wire); | |||
| 231 | 12 | 10373 | $signer->CLOSE; | |||
| 232 | 12 | 32112 | $signed = $signer->signature->as_string . "\n" . _local($message); | |||
| 233 | 12 | 249 | 1; | |||
| 234 | 12 | 13 | } or do { | |||
| 235 | 0 | 0 | my $error = $@ || 'unknown error'; | |||
| 236 | 0 | 0 | chomp($error); | |||
| 237 | 0 | 0 | warn "Mail::Send::DKIM: cannot sign for $domain ($error); sending unsigned"; | |||
| 238 | 0 | 0 | return; | |||
| 239 | }; | |||||
| 240 | ||||||
| 241 | 12 | 39 | return $signed; | |||
| 242 | } | |||||
| 243 | ||||||
| 244 - 253 | =head2 B<send> $message, @arguments Pipes the message to B<sendmail> with the arguments given - C<-t>, C<-f> and the rest are sendmail's own - and returns C<0> when sendmail accepted the message, sendmail's exit status when it did not, and C<1> when sendmail cannot be run at all. The message is normalised to LF first, so nothing that arrived with CRLF - signed or passed through unsigned - carries a carriage return to the MTA. =cut | |||||
| 254 | ||||||
| 255 | sub send | |||||
| 256 | { | |||||
| 257 | 9 | 3014 | my ($self, $message, @args) = @_; | |||
| 258 | ||||||
| 259 | 9 | 34032 | open(my $sendmail, '|-', $self->{'sendmail'}, @args) or do { | |||
| 260 | 1 | 82 | warn "Mail::Send::DKIM: cannot run $self->{'sendmail'}: $!"; | |||
| 261 | 1 | 30 | return 1; | |||
| 262 | }; | |||||
| 263 | 8 | 122 | print $sendmail _local($message); | |||
| 264 | ||||||
| 265 | 8 | 27200 | return 0 if(close($sendmail)); | |||
| 266 | ||||||
| 267 | 1 | 14 | my $status = $? >> 8; | |||
| 268 | ||||||
| 269 | 1 | 40 | return $status || 1; | |||
| 270 | } | |||||
| 271 | ||||||
| 272 | # | |||||
| 273 | # What is handed to sendmail is the local form of the message: LF line endings | |||||
| 274 | # and no carriage return anywhere, whatever arrived. A CR is data to the MTA | |||||
| 275 | # that keeps the message - Postfix's sendmail_fix_line_endings and Exim both | |||||
| 276 | # write the CRLF of SMTP themselves - so one that survived would reach the | |||||
| 277 | # receiver doubled, and the message would fail the signature it was just given. | |||||
| 278 | sub _local | |||||
| 279 | { | |||||
| 280 | 32 | 293 | my $message = shift; | |||
| 281 | ||||||
| 282 | 32 | 94 | $message =~ s/\r\n/\n/g; | |||
| 283 | 32 | 43 | $message =~ s/\r//g; | |||
| 284 | ||||||
| 285 | 32 | 148 | return $message; | |||
| 286 | } | |||||
| 287 | ||||||
| 288 - 294 | =head2 B<from_domain> $message The domain of the address in the first C<From:> header, in lower case, or C<undef> when there is no such header. Folded headers and display names are understood. =cut | |||||
| 295 | ||||||
| 296 | # | |||||
| 297 | # The domain an address is at, from the first From: header. A header field can | |||||
| 298 | # be folded over several lines, so the continuation lines are joined first, and | |||||
| 299 | # a display name is dropped in favour of the address in angle brackets. | |||||
| 300 | sub from_domain | |||||
| 301 | { | |||||
| 302 | 20 | 22 | my $message = shift; | |||
| 303 | ||||||
| 304 | 20 | 380 | my ($head) = $message =~ /\A(.*?)\r?\n\r?\n/s; | |||
| 305 | 20 | 27 | $head = $message unless(defined($head)); | |||
| 306 | 20 | 67 | $head =~ s/\r?\n[ \t]+/ /g; | |||
| 307 | 20 | 86 | return unless($head =~ /^From:[ \t]*(.*?)\s*$/mi); | |||
| 308 | ||||||
| 309 | 19 | 23 | my $value = $1; | |||
| 310 | 19 | 21 | my ($address) = $value =~ /<([^>]*)>/; | |||
| 311 | 19 | 25 | $address = $value unless(defined($address)); | |||
| 312 | ||||||
| 313 | # An address can be followed by a comment, so the domain is the last | |||||
| 314 | # thing that looks like one rather than the end of the string. | |||||
| 315 | 19 | 55 | my @domains = $address =~ /\@([A-Za-z0-9.-]+)/g; | |||
| 316 | 19 | 38 | return unless(@domains); | |||
| 317 | ||||||
| 318 | 19 | 44 | return lc($domains[-1]); | |||
| 319 | } | |||||
| 320 | ||||||
| 321 - 329 | =head2 B<selector> The selector the message will be signed under: the one given to B<new> or read from C<DKIM_SELECTOR>, otherwise the name of the B<keyfile> when one is given, otherwise the name of the only F<*.private> file in B<keydir>. C<undef> when it cannot be decided - no key, or several keys and no name - and the reason is a warning on standard error. B<sign> asks this before doing anything else. =cut | |||||
| 330 | ||||||
| 331 | # The key file is <keydir>/<selector>.private. With no selector named the | |||||
| 332 | # selector is the name of the only key in the directory, which is the usual | |||||
| 333 | # case: one key, published for every domain this host sends as. Anything | |||||
| 334 | # ambiguous is a warning rather than a guess. | |||||
| 335 | sub selector | |||||
| 336 | { | |||||
| 337 | 14 | 11 | my $self = shift; | |||
| 338 | ||||||
| 339 | 14 | 16 | my $selector = $self->{'selector'}; | |||
| 340 | 14 | 34 | return $selector if(defined($selector) && length($selector)); | |||
| 341 | ||||||
| 342 | # A named key file carries its selector in its name, which is the layout | |||||
| 343 | # the keys are kept in: <keydir>/<selector>.private. | |||||
| 344 | 10 | 23 | if(defined($self->{'keyfile'})) { | |||
| 345 | 1 | 4 | (my $from_name = $self->{'keyfile'}) =~ s{.*[\\/]}{}; | |||
| 346 | 1 | 4 | $from_name =~ s/\.(?:private|key|pem)\z//; | |||
| 347 | 1 | 5 | return $from_name if(length($from_name)); | |||
| 348 | } | |||||
| 349 | ||||||
| 350 | 9 | 203 | opendir(my $dh, $self->{'keydir'}) or do { | |||
| 351 | 0 | 0 | warn "Mail::Send::DKIM: cannot read $self->{'keydir'}: $!"; | |||
| 352 | 0 | 0 | return; | |||
| 353 | }; | |||||
| 354 | 9 27 | 163 53 | my @keys = sort grep { /\.private\z/ } readdir($dh); | |||
| 355 | 9 | 41 | closedir($dh); | |||
| 356 | ||||||
| 357 | 9 | 16 | unless(@keys == 1) { | |||
| 358 | warn sprintf("Mail::Send::DKIM: %s holds %d key(s); name the selector to choose one", | |||||
| 359 | 2 | 31 | $self->{'keydir'}, scalar(@keys)); | |||
| 360 | 2 | 10 | return; | |||
| 361 | } | |||||
| 362 | ||||||
| 363 | 7 | 20 | (my $found = $keys[0]) =~ s/\.private\z//; | |||
| 364 | ||||||
| 365 | 7 | 20 | return $found; | |||
| 366 | } | |||||
| 367 | ||||||
| 368 | 1; | |||||
| 369 | ||||||