lib/Mail/Send/DKIM.pm

Structural Coverage (Approximate)

TER1 (Statement): 91.49%
TER2 (Branch): 82.35%
TER3 (LCSAJ): 100.0% (3/3)
Approximate LCSAJ segments: 35

LCSAJ Legend

● Covered — this LCSAJ path was executed during testing.

● Not covered — this LCSAJ path was never executed. These are the paths to focus on.

Multiple dots on a line indicate that multiple control-flow paths begin at that line. Hovering over any dot shows:

        start → end → jump
        

Uncovered paths show [NOT COVERED] in the tooltip.

Mutant Testing Legend

Survived (tests missed this) Killed (tests detected this) No mutation
    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: use strict;
    9: use warnings;
   10: 
   11: use Mail::DKIM::Signer;
   12: use Params::Get;
   13: use Object::Configure;
   14: 
   15: use version; our $VERSION = version->declare('0.001.0');
   16: 
   17: =head1 NAME
   18: 
   19: Mail::Send::DKIM - sign a message with DKIM and hand it to sendmail
   20: 
   21: =head1 VERSION
   22: 
   23: 0.001.0
   24: 
   25: =head1 SYNOPSIS
   26: 
   27: 	use Mail::Send::DKIM;
   28: 
   29: 	my $dkim = Mail::Send::DKIM->new(
   30: 		domains => ['example.org'],
   31: 		keydir => "$ENV{HOME}/dkim",
   32: 	);
   33: 
   34: 	my $signed = $dkim->sign($message);
   35: 	$message = $signed if(defined($signed));
   36: 
   37: 	exit($dkim->send($message, '-t', '-f', 'alerts@example.org'));
   38: 
   39: =head1 DESCRIPTION
   40: 
   41: Signs a message with DKIM when its C<From:> domain is one this host signs for,
   42: and hands it to sendmail with whatever arguments sendmail should have.  The
   43: signed form is C<rsa-sha256> with C<relaxed> canonicalization, which is the
   44: shape receiving sites expect.
   45: 
   46: The signature covers the message in the form DKIM defines, where every line
   47: ends CRLF.  What is handed to sendmail is the local form instead: LF line
   48: endings, and no carriage return anywhere, whatever arrived.  A CR would be data
   49: to the MTA that keeps the message - Postfix and Exim both write the CRLF of
   50: SMTP themselves - so a message that had travelled with CRLF in it would reach
   51: the receiver with the CRs doubled and fail the signature it had just been given.
   52: 
   53: Nothing here dies because a key is missing: signing either produces a signed
   54: message or produces nothing and says why on standard error, so a caller can
   55: always fall back to sending the message as it is.
   56: 
   57: =head1 PLATFORMS
   58: 
   59: Windows is not supported.  L<Mail::DKIM> needs L<Crypt::OpenSSL::RSA>, and that
   60: module and its prerequisites, L<Crypt::OpenSSL::Random> and
   61: L<Crypt::OpenSSL::Bignum>, do not link on Windows: Strawberry Perl's static
   62: OpenSSL needs the C<crypt32> library, which their F<Makefile.PL> files do not
   63: ask for.  F<Makefile.PL> stops with C<OS unsupported> there, rather than failing
   64: part-way through the install.
   65: 
   66: =head1 ENVIRONMENT
   67: 
   68: B<DKIM_DOMAINS>, B<DKIM_KEYDIR>, B<DKIM_SELECTOR>, B<DKIM_KEYFILE> and
   69: B<SENDMAIL> are read by B<new> when the corresponding option is not given, so
   70: the command line programs needs no configuration of its own.
   71: 
   72: =head1 PROGRAMS
   73: 
   74: The distribution is named after this module and installs four programs with
   75: it, each with a page of its own: C<perldoc bin/mail-dkim>,
   76: C<perldoc bin/dmarc-report.pl>, C<perldoc bin/dmarc-check-mail.pl> and
   77: C<perldoc bin/dmarc-weekly.sh> in a checkout, and the same pages as manual
   78: pages once installed.
   79: 
   80: =over 4
   81: 
   82: =item L<mail-dkim|https://github.com/nigelhorne/Mail-Send-DKIM/blob/master/bin/mail-dkim>
   83: 
   84: The front end to this module: a message on standard input is signed when its
   85: C<From:> domain is one named in C<DKIM_DOMAINS>, and handed to sendmail(1) with
   86: the arguments it was given.  Put it where a script or a crontab calls sendmail
   87: and the mail is signed without the script being changed.  Its page has the
   88: environment variables, the key layout and the exit status.
   89: 
   90: =item L<dmarc-report|https://github.com/nigelhorne/Mail-Send-DKIM/blob/master/bin/dmarc-report.pl>
   91: 
   92: Reads a directory of DMARC aggregate reports and says who sent mail for each
   93: domain, marking every source that is not an expected one (C<DMARC_EXPECTED>),
   94: every expected one whose mail did not authenticate, and every message that was
   95: quarantined or rejected by policy despite passing.  The exit status is non-zero
   96: when anything needs looking at.  Its page has the options.
   97: 
   98: =item L<dmarc-weekly.sh|https://github.com/nigelhorne/Mail-Send-DKIM/blob/master/bin/dmarc-weekly.sh>
   99: 
  100: The cron wrapper around it: silent when the week is clean, a mail with the full
  101: output when it is not, and the reports moved aside to an archive afterwards.
  102: C<DRY_RUN=1> rehearses a run and C<--crontab> prints the line to paste into a
  103: crontab; see L</A CRONTAB ENTRY> below.
  104: 
  105: =item L<dmarc-check-mail.pl|https://github.com/nigelhorne/Mail-Send-DKIM/blob/master/bin/dmarc-check-mail.pl>
  106: 
  107: Sends one message, signed with this module, to a mailbox that can be read, so
  108: that the C<Authentication-Results> header at the far end shows what receivers
  109: make of this host's mail before the DMARC policy is tightened.  C<--plain>
  110: sends the same message unsigned, which is what a cron job without the module
  111: looks like.
  112: 
  113: =back
  114: 
  115: The three DMARC programs are the reason the module exists: they report on the
  116: mail it signs, and the weekly one sends its own report through it.
  117: 
  118: =head1 METHODS
  119: 
  120: =head2 B<new> %options
  121: 
  122: =over 4
  123: 
  124: =item C<domains>
  125: 
  126: The domains to sign for, either an array reference or a string of them
  127: separated by commas or spaces.  Defaults to C<$ENV{DKIM_DOMAINS}>.  A message
  128: from any other domain is left alone.
  129: 
  130: =item C<keydir>
  131: 
  132: Where the private keys are.  Defaults to C<$ENV{DKIM_KEYDIR}>, or F<~/dkim>.
  133: 
  134: =item C<selector>
  135: 
  136: The selector the key is published under, which names the key file
  137: F<< <keydir>/<selector>.private >>.  Defaults to C<$ENV{DKIM_SELECTOR}>; with
  138: neither set, the key file's own name is the selector when B<keyfile> is given,
  139: and otherwise the only F<*.private> file in B<keydir> is used and its name is
  140: the selector.
  141: 
  142: =item C<keyfile>
  143: 
  144: The private key to sign with, when it does not live at
  145: F<< <keydir>/<selector>.private >> - a tester given one key to try, for
  146: instance.  Defaults to C<$ENV{DKIM_KEYFILE}>.  It is used as it stands, and
  147: the selector comes from its name unless one is given.
  148: 
  149: =item C<sendmail>
  150: 
  151: The program B<send> hands the message to.  Defaults to C<$ENV{SENDMAIL}>, or
  152: F</usr/sbin/sendmail>.
  153: 
  154: =back
  155: 
  156: =cut
  157: 
  158: sub new
  159: {
  160: 	my $class = shift;
  161: 
  162: 	# Handle hash or hashref arguments
  163: 	my $params = Params::Get::get_params(undef, \@_) // {};
  164: 
  165: 	$params = Object::Configure::configure($class, $params);
  166: 
  167: 	my $home = $params->{home} || $ENV{'HOME'} || (getpwuid($<))[7] || '.';
  168: 
  169: 	my $domains = $params->{'domains'} // $ENV{'DKIM_DOMAINS'} // '';
  170: 	my @domains = ref($domains) eq 'ARRAY' ? @$domains : split(/[\s,]+/, $domains);
  171: 

Mutants (Total: 2, Killed: 2, Survived: 0)

172: my $self = { 173: '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: 'sendmail' => $params->{'sendmail'} // $ENV{'SENDMAIL'} // '/usr/sbin/sendmail', 178: }; 179: 180: return bless($self, $class); 181: } 182: 183: =head2 B<sign> $message 184: 185: Returns the message with a C<DKIM-Signature> header added, or C<undef> when 186: there is nothing to do or nothing that can be done: the domain is not one of 187: B<domains>, there is no C<From:> header, no key can be found or read, or the 188: signer failed. The reasons are warnings on standard error; the message itself 189: is never altered in the undef case, so the caller sends it unchanged. 190: Carriage returns are folded to LF on the way, so what comes back is in the 191: local form. 192: 193: =cut 194: 195: sub sign 196: { ●197 → 212 → 215 197: my $self = shift; 198: 199: my $params = Params::Get::get_params('message', \@_); 200: my $message = $params->{message}; 201: 202: my $domain = from_domain($message); 203: return unless(defined($domain));

Mutants (Total: 1, Killed: 1, Survived: 0)

204: return unless($self->{'domains'}->{$domain}); 205: 206: my $selector = $self->selector; 207: 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: my $keyfile = $self->{'keyfile'} // $self->{'keydir'} . "/$selector.private"; 212: unless(-r $keyfile) { 213: warn "Mail::Send::DKIM: no readable key at $keyfile; sending $domain unsigned"; 214: 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: (my $wire = _local($message)) =~ s/\n/\r\n/g; 220: 221: my $signed; 222: eval { 223: my $signer = Mail::DKIM::Signer->new( 224: Algorithm => 'rsa-sha256', 225: Method => 'relaxed', 226: Domain => $domain, 227: Selector => $selector, 228: KeyFile => $keyfile, 229: ); 230: $signer->PRINT($wire); 231: $signer->CLOSE; 232: $signed = $signer->signature->as_string . "\n" . _local($message);

Mutants (Total: 2, Killed: 2, Survived: 0)

233: 1; 234: } or do { 235: my $error = $@ || 'unknown error'; 236: chomp($error); 237: warn "Mail::Send::DKIM: cannot sign for $domain ($error); sending unsigned"; 238: return; 239: }; 240: 241: return $signed; 242: } 243: 244: =head2 B<send> $message, @arguments 245: 246: Pipes the message to B<sendmail> with the arguments given - C<-t>, C<-f> and 247: the rest are sendmail's own - and returns C<0> when sendmail accepted the 248: message, sendmail's exit status when it did not, and C<1> when sendmail cannot 249: be run at all. The message is normalised to LF first, so nothing that arrived 250: with CRLF - signed or passed through unsigned - carries a carriage return to 251: the MTA. 252:

Mutants (Total: 2, Killed: 2, Survived: 0)

253: =cut 254: 255: sub send 256: {

Mutants (Total: 2, Killed: 2, Survived: 0)

257: my ($self, $message, @args) = @_; 258: 259: open(my $sendmail, '|-', $self->{'sendmail'}, @args) or do { 260: warn "Mail::Send::DKIM: cannot run $self->{'sendmail'}: $!";

Mutants (Total: 2, Killed: 2, Survived: 0)

261: return 1; 262: }; 263: print $sendmail _local($message); 264: 265: return 0 if(close($sendmail)); 266: 267: my $status = $? >> 8; 268: 269: 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

Mutants (Total: 2, Killed: 2, Survived: 0)

277: # receiver doubled, and the message would fail the signature it was just given. 278: sub _local 279: { 280: my $message = shift; 281: 282: $message =~ s/\r\n/\n/g; 283: $message =~ s/\r//g; 284: 285: return $message; 286: } 287: 288: =head2 B<from_domain> $message 289: 290: The domain of the address in the first C<From:> header, in lower case, or 291: C<undef> when there is no such header. Folded headers and display names are 292: understood. 293: 294: =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: my $message = shift; 303: 304: my ($head) = $message =~ /\A(.*?)\r?\n\r?\n/s; 305: $head = $message unless(defined($head)); 306: $head =~ s/\r?\n[ \t]+/ /g; 307: return unless($head =~ /^From:[ \t]*(.*?)\s*$/mi); 308: 309: my $value = $1;

Mutants (Total: 2, Killed: 2, Survived: 0)

310: my ($address) = $value =~ /<([^>]*)>/; 311: $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: my @domains = $address =~ /\@([A-Za-z0-9.-]+)/g; 316: return unless(@domains); 317: 318: return lc($domains[-1]); 319: } 320: 321: =head2 B<selector> 322: 323: The selector the message will be signed under: the one given to B<new> or read 324: from C<DKIM_SELECTOR>, otherwise the name of the B<keyfile> when one is given, 325: otherwise the name of the only F<*.private> file in B<keydir>. C<undef> when it 326: cannot be decided - no key, or several keys and no name - and the reason is a 327: warning on standard error. B<sign> asks this before doing anything else. 328: 329: =cut 330: 331: # The key file is <keydir>/<selector>.private. With no selector named the

Mutants (Total: 2, Killed: 2, Survived: 0)

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

Mutants (Total: 1, Killed: 1, Survived: 0)

336: { ●337 → 344 → 350 337: my $self = shift; 338:

Mutants (Total: 2, Killed: 2, Survived: 0)

339: my $selector = $self->{'selector'}; 340: 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: if(defined($self->{'keyfile'})) { 345: (my $from_name = $self->{'keyfile'}) =~ s{.*[\\/]}{}; 346: $from_name =~ s/\.(?:private|key|pem)\z//; 347: return $from_name if(length($from_name)); 348: }

Mutants (Total: 2, Killed: 2, Survived: 0)

349: ●350 → 357 → 361 350: opendir(my $dh, $self->{'keydir'}) or do { 351: warn "Mail::Send::DKIM: cannot read $self->{'keydir'}: $!"; 352: return; 353: }; 354: my @keys = sort grep { /\.private\z/ } readdir($dh); 355: closedir($dh); 356:

Mutants (Total: 2, Killed: 2, Survived: 0)

357: unless(@keys == 1) { 358: warn sprintf("Mail::Send::DKIM: %s holds %d key(s); name the selector to choose one", 359: $self->{'keydir'}, scalar(@keys)); 360: return; 361: } 362: 363: (my $found = $keys[0]) =~ s/\.private\z//; 364: 365: return $found; 366: } 367: 368: 1; 369: 370: __END__ 371: 372: =head1 A CRONTAB ENTRY 373: 374: A job that sends mail from cron is where an unsigned message is least likely to 375: be noticed, so that is usually where this module earns its keep: the program 376: that ships with it, F<mail-dkim>, is put where the job would have called 377: sendmail(1), and the job itself is not changed. 378: 379: The weekly summary in this distribution is such a job, and its mail goes out 380: through F<mail-dkim>. A crontab line for it looks like this, with the values of 381: the machine it runs on: 382: 383: 0 6 * * 1 DMARC_EXPECTED=192.0.2.10 MAIL_TO=alerts@example.org \ 384: PERL=/usr/bin/perl /usr/local/bin/dmarc-weekly.sh 385: 386: The three settings are not optional, because cron starts a job with almost no 387: environment. C<DMARC_EXPECTED> is what makes a sender nobody expected a 388: finding, and the run stops with a usage error without it, since guessing would 389: excuse every sender. C<MAIL_TO> is where a week that needs looking at is 390: mailed, and is also the address the alert is sent as unless C<MAIL_FROM> says 391: otherwise. C<PERL> has to be an absolute path to a perl that has 392: C<XML::PP>, as cron's C<PATH> usually holds only the system one; F<--crontab> 393: fills it in with the first perl on the machine that can load the module. 394: C<DMARC_DIR> and C<DMARC_ARCHIVE_DIR> are left out of the line because they 395: default to C<~/Downloads> and C<~/dmarc-archive>. 396: 397: F<dmarc-weekly.sh --crontab> prints that line with the path and the perl filled 398: in for the machine it runs on, which is more use than an example carrying 399: somebody else's values; for that reason no example crontab file is shipped or 400: installed. A job of your own takes the same shape with F<mail-dkim> in place of 401: the wrapper: C<DKIM_DOMAINS> and C<DKIM_KEYDIR> say what to sign for, and the 402: arguments given to it are passed to sendmail(1) as they are. 403: 404: =head1 SEE ALSO 405: 406: =over 4 407: 408: =item * L<Configure an Object at Runtime|Object::Configure> 409: 410: =item * L<Test Dashboard|https://nigelhorne.github.io/Mail-Send-DKIM/coverage/> 411: 412: =back 413: 414: L<Mail::DKIM::Signer>, which does the signing underneath, and L</PROGRAMS> 415: above for the programs this distribution installs beside the module. 416: 417: =head1 AUTHOR 418: 419: Nigel Horne, C<< <njh at nigelhorne.com> >> 420: 421: =head1 LICENCE AND COPYRIGHT 422: 423: Copyright 2026 Nigel Horne. 424: 425: Usage is subject to the GPL2 licence terms. 426: If you use it, 427: please let me know. 428: 429: =cut 430: 431: 1;