File Coverage

File:bin/dmarc-check-mail.pl
Coverage:80.5%

linestmtbrancondsubtimecode
1#!/usr/bin/env perl
2#
3# The POD at the end of this file is this programme's description: perldoc
4# dmarc-check-mail.pl.
5
6
17
17
17
35053
15
312
use strict;
7
17
17
17
30
15
403
use warnings;
8
9
17
17
17
5113
78439
37
use Getopt::Long qw(GetOptions);
10
17
17
17
1554
19
195
use File::Spec;
11
17
17
17
3610
46144
58
use POSIX qw(strftime);
12
17
17
17
14135
8293
469
use Sys::Hostname qw(hostname);
13
14
17
17
17
2995
8382
1332
use FindBin qw($Bin);
15# Beside the module in a checkout, and under lib/perl5 when installed with
16# INSTALL_BASE into a prefix that @INC does not reach on its own.
17
17
17
17
34
34
3005
4818
19
174
51
use lib grep { -d } map { "$Bin/../$_" } qw(lib lib/perl5);
18
19# Kept apart from what the options become, so that the usage text goes on
20# offering these however the programme was called.
21my %default = (
22        'to' => $ENV{'DMARC_TEST_TO'} || 'nigel@example.org',
23        'from' => $ENV{'DMARC_TEST_FROM'} || 'alerts@example.org',
24        'domain' => $ENV{'DMARC_TEST_DOMAIN'} || 'example.org',
25        'selector' => $ENV{'DMARC_TEST_SELECTOR'} || 'selector1',
26        'sendmail' => $ENV{'SENDMAIL'} || '/usr/sbin/sendmail',
27
17
1062861
        'keyfile' => $ENV{'DKIM_KEYFILE'},
28);
29
30
17
62
my %opt = (
31        %default,
32        'plain' => 0,
33        'dry-run' => 0,
34        'save' => undef,
35);
36
37# Nothing that goes wrong once the options have been read is a usage error, and
38# die() decides a status of its own - whatever errno was left over (2 for a
39# directory that is not there, 13 for one that is not writable) or sendmail's
40# own - which would hand out the 2 that means "the options were not usable".
41# 1 is the status for having sent nothing, whichever failure it was.
42sub fail
43{
44
6
159
        print STDERR @_;
45
46
6
0
        exit(1);
47}
48
49GetOptions(
50        'to|t=s' => \$opt{'to'},
51        'from|f=s' => \$opt{'from'},
52        'domain=s' => \$opt{'domain'},
53        'selector=s' => \$opt{'selector'},
54        'keyfile|k=s' => \$opt{'keyfile'},
55        'sendmail=s' => \$opt{'sendmail'},
56        'plain' => \$opt{'plain'},
57        'dry-run|n' => \$opt{'dry-run'},
58        'save=s' => \$opt{'save'},
59
0
0
        'help|h' => sub { usage(0) },
60
17
132
) or usage(2);
61
62
16
10569
usage(2) unless($opt{'to'} && $opt{'from'});
63# Both addresses become headers, and --from is sendmail's envelope sender as
64# well, so neither may hold a space or a control character - the shape of a
65# header injection - or begin with a - that sendmail would read as an option.
66
14
56
usage(2) if(unusable_address($opt{'to'}) || unusable_address($opt{'from'}));
67
68
9
34
my $host = hostname();
69
9
116
my $token = sprintf('%s-%d', $host, time());
70
9
548
my $now = strftime('%Y-%m-%d %H:%M:%S %z', localtime());
71
72# Sending unsigned from the signing path is a mistake worth stopping: the
73# whole point is to see a signature arrive.  --plain asks for it deliberately.
74
9
16
my ($keyfile, $mailer);
75
9
18
if($opt{'plain'}) {
76
5
7
        $mailer = 'sendmail(1), unsigned';
77} else {
78
4
11
        $keyfile = $opt{'keyfile'} || find_keyfile();
79
4
7
        if(!$keyfile) {
80
1
1
                my @candidates = candidate_keys();
81
1
3
                fail "No DKIM key found: name one with --keyfile or set DKIM_KEYFILE.\n"
82                        . (@candidates ? 'Looked at: ' . join(', ', @candidates) . "\n" : '')
83                        . "Use --plain to send unsigned on purpose.\n";
84        }
85
3
28
        fail "Cannot read $keyfile\n" unless(-r $keyfile);
86        # Loaded here rather than with use, so that --plain still works on a host
87        # without Mail::DKIM: sending unsigned is exactly what it is for there.
88        fail "Mail::DKIM is not installed for $^X, so nothing can be signed.\n"
89                . "Install it, or use --plain to send unsigned on purpose.\n"
90
2
2
2
2
2
515
129297
9
                unless(eval { require Mail::DKIM::Signer; require Mail::Send::DKIM; 1 });
91
2
5
        $mailer = "Mail::Send::DKIM, signed with d=$opt{'domain'} s=$opt{'selector'}";
92}
93
94
7
13
my $subject = "DKIM check from $host at $now";
95
7
21
my $body = <<"BODY";
96This is a test message from $host at $now.
97
98It was sent by $mailer.
99
100Its only purpose is to show, in the headers at the far end, whether mail from
101this host authenticates.  The token below is unique to this run, so the message
102can be found again among others:
103
104  $token
105
106Nothing replies to it and nothing depends on it.
107BODY
108
109
7
32
my $message = join('',
110        "From: $opt{'from'}\n",
111        "To: $opt{'to'}\n",
112        "Subject: $subject\n",
113        "Date: $now\n",
114        "Message-ID: <$token\@$host>\n",
115        "MIME-Version: 1.0\n",
116        "Content-Type: text/plain; charset=utf-8\n",
117        "Content-Transfer-Encoding: 8bit\n",
118        "\n",
119        $body,
120);
121
122# Sign first, then decide what to do with the result, so that what is printed,
123# saved and sent are the same bytes - and so that a rehearsal exercises the
124# signing rather than pretending to.
125
7
30
my $wire = $opt{'plain'} ? $message : sign($message);
126
127
7
16
if($opt{'save'}) {
128
1
39
        open(my $fh, '>', $opt{'save'}) or fail "Cannot write $opt{'save'}: $!\n";
129
0
0
        print $fh $wire;
130
0
0
        close($fh) or fail "Cannot close $opt{'save'}: $!\n";
131
0
0
        print "Message as sent is in $opt{'save'}\n\n";
132}
133
134
6
22
if($opt{'dry-run'}) {
135
3
15
        print $wire;
136
3
4
        print "\n--- nothing was sent; run again without --dry-run ---\n";
137
3
69
        exit(0);
138}
139
140
3
6137
open(my $sendmail, '|-', $opt{'sendmail'}, '-t', '-f', $opt{'from'})
141        or fail "Cannot run $opt{'sendmail'}: $!\n";
142
2
24
print $sendmail $wire;
143
2
6583
unless(close($sendmail)) {
144
2
29
        fail "sendmail reported a failure; the message was not delivered.\n";
145}
146
147
0
0
print "Sent to $opt{'to'} as $opt{'from'}\n";
148
0
0
print "  via       : $mailer\n";
149
0
0
print "  token     : $token\n\n";
150
0
0
print "In the mailbox, open that message and choose \"Show original\".  You want:\n";
151
0
0
print "  SPF:   pass  (ip= the sending host)\n";
152
0
0
print "  DKIM:  pass  (domain=$opt{'domain'}, selector=$opt{'selector'})\n";
153
0
0
print "  DMARC: pass\n\n";
154
0
0
print "If DKIM is missing, nothing downstream can pass: check that the key is\n";
155
0
0
print "the one published at $opt{'selector'}._domainkey.$opt{'domain'}, and that\n";
156
0
0
print "Mail::DKIM is installed for $^X.\n";
157
158
0
0
exit(0);
159
160# One signing implementation for the repository: Mail::Send::DKIM, which is
161# what bin/mail-dkim uses, so what this sends is what the site's mail looks
162# like.  The message's own From: domain is allowed as well as --domain, so a
163# test sent as a different address than the one being signed for still signs.
164sub sign
165{
166
2
2
        my $message = shift;
167
168
2
6
        require Mail::Send::DKIM;
169
170        my $dkim = Mail::Send::DKIM->new(
171                'domains' => [$opt{'domain'}, Mail::Send::DKIM::from_domain($message)],
172                'keyfile' => $keyfile,
173
2
4
                'selector' => $opt{'selector'},
174        );
175
176
2
35
        my $signed = $dkim->sign($message);
177
2
9
        return $signed if(defined($signed));
178
179        # The module has already said what went wrong on standard error; this adds
180        # what the tester knows and it does not: which key was meant.
181
0
0
        fail "Cannot sign with $keyfile.\n"
182                . "Check that it is the key published at $opt{'selector'}._domainkey.$opt{'domain'}.\n";
183}
184
185# The site's key is wherever the site keeps it; these are the places it has
186# lived, so the common case needs no argument.
187sub candidate_keys
188{
189
9
10
        my @dirs = grep { defined } (
190                $ENV{'HOME'} ? File::Spec->catdir($ENV{'HOME'}, 'dkim') : undef,
191                $ENV{'HOME'} ? File::Spec->catdir($ENV{'HOME'}, '.dkim') : undef,
192
3
41
                $ENV{'HOME'} ? File::Spec->catdir($ENV{'HOME'}, 'lib', 'dkim') : undef,
193        );
194
195
3
6
        my @keys;
196
3
7
        foreach my $dir (@dirs) {
197
9
48
                next unless(-d $dir);
198
1
50
                foreach my $name (glob(File::Spec->catfile($dir, '*'))) {
199
1
4
                        next unless($name =~ /\.(?:private|key|pem)\z/);
200
1
2
                        push @keys, $name;
201                }
202        }
203
204
3
5
        return @keys;
205}
206
207sub find_keyfile
208{
209
2
4
        foreach my $key (candidate_keys()) {
210                # A directory can hold keys for several domains; the selector names
211                # the one this message must be signed with.
212
1
9
                return $key if($key =~ /\Q$opt{'selector'}\E/ || $key =~ /\Q$opt{'domain'}\E/);
213        }
214
215
1
2
        return undef;
216}
217
218# An address that cannot be written into a header as it stands, and that would
219# be read as an option by sendmail if it began with a dash.
220sub unusable_address
221{
222
25
21
        my $address = shift;
223
224
25
55
        return 1 if($address =~ /[\x00-\x20\x7f]/);
225
22
34
        return 1 if($address =~ /\A-/);
226
227
20
42
        return 0;
228}
229
230sub usage
231{
232
8
623
        my $status = shift // 0;
233
234
8
61
        print <<"USAGE";
235$0 - send one test message from this host, so its authentication can be read
236
237Usage:
238  $0 [options]
239
240  --to ADDR         where to send it          (default $default{'to'})
241  --from ADDR       envelope and header From  (default $default{'from'})
242  --domain DOMAIN   the domain to sign for    (default $default{'domain'})
243  --selector SEL    the DKIM selector         (default $default{'selector'})
244  --keyfile FILE    the DKIM private key      (default: found under ~/dkim)
245  --plain           send unsigned via sendmail(1), the way cron does
246  --dry-run         sign the message, print it, send nothing
247  --save FILE       also write the message, as it is sent, to FILE
248  --sendmail PATH   sendmail to use           (default $default{'sendmail'})
249  --help            this text
250
251Sent through Mail::Send::DKIM, the signer bin/mail-dkim uses, so that what
252arrives is what the site's mail actually looks like.
253USAGE
254
255
8
        exit($status);
256}
257
258 - 399
=pod

=head1 NAME

dmarc-check-mail.pl - send one test message from this host, so its authentication can be read

=head1 SYNOPSIS

        dmarc-check-mail.pl

        dmarc-check-mail.pl --plain

        dmarc-check-mail.pl --keyfile ~/dkim/selector1.private --domain example.org

=head1 DESCRIPTION

Sends one message through sendmail(1) to a mailbox that can be read, and says
what the C<Authentication-Results> header at the far end should contain.  The
message is signed with L<Mail::Send::DKIM>, the signer C<mail-dkim> uses, so
that what arrives is what this site's mail really looks like, rather than a test
of a signing path nothing else uses.  C<--plain> sends the same message
unsigned, which is what a cron job without the module looks like, so that both
can be compared in the same mailbox.

The subject and body carry a token made of the host name and the time, so that
the message can be found again among others.

=head1 OPTIONS

=over 4

=item B<--to> ADDR (C<-t>)

Where to send it.  Default C<DMARC_TEST_TO>, or C<nigel@example.org>.  It is
written into the message's C<To:> header, so an address holding a space or a
control character, or beginning with a C<->, is refused, as C<--from> is.

=item B<--from> ADDR (C<-f>)

The envelope sender and the header C<From:>.  Default C<DMARC_TEST_FROM>, or
C<alerts@example.org>.  An address holding a space or a control character, or
beginning with a C<->, is refused.

=item B<--domain> DOMAIN

The domain to sign for.  Default C<DMARC_TEST_DOMAIN>, or C<example.org>.  The
domain in the message's own C<From:> is signed for as well, so that a test sent
as an address from the domain being signed for still signs.

=item B<--selector> SEL

The selector to sign with.  Default C<DMARC_TEST_SELECTOR>, or C<selector1>.  It
also chooses the key when C<--keyfile> is not given.

=item B<--keyfile> FILE (C<-k>)

The private key.  Default C<DKIM_KEYFILE>, or the first file under C<~/dkim>,
C<~/.dkim> or C<~/lib/dkim> named C<*.private>, C<*.key> or C<*.pem> whose name
holds the selector or the domain.

=item B<--plain>

Send the message unsigned, through sendmail(1) alone, which is what cron does.
No key is looked for and Mail::DKIM need not be installed, so this still works
on a host that cannot sign at all.

=item B<--dry-run> (C<-n>)

Sign the message, print it, and send nothing.

=item B<--save> FILE

Also write the message, as it is sent, to FILE.

=item B<--sendmail> PATH

The sendmail the message is handed to.  Default C<SENDMAIL>, or
C</usr/sbin/sendmail>.

=item B<--help> (C<-h>)

Print the usage summary and exit 0.

=back

Each default above is set by the variable named with it, and nothing else is
read.

=head1 ENVIRONMENT

=over 4

=item C<DMARC_TEST_TO>

The default for C<--to>.

=item C<DMARC_TEST_FROM>

The default for C<--from>.

=item C<DMARC_TEST_DOMAIN>

The default for C<--domain>.

=item C<DMARC_TEST_SELECTOR>

The default for C<--selector>, which also chooses the key.

=item C<SENDMAIL>

The default for C<--sendmail>.

=item C<DKIM_KEYFILE>

The key, when C<--keyfile> is not given.

=item C<HOME>

Where the key is looked for when neither is given: C<~/dkim>, C<~/.dkim> and
C<~/lib/dkim>.

=back

=head1 EXIT STATUS

C<0> when the message was handed to sendmail, printed by C<--dry-run>, or
C<--help> was asked for - and the first two do not mean it arrived, or that it
authenticated: that is what the headers at the far end say.  C<1> when nothing
was sent: no key was found, the key could not be read, Mail::DKIM is not
installed for this perl, C<--save> could not be written, or sendmail could not
be run or reported a failure.  Standard error says which.  C<2> when the
options were not usable - an unknown option, no C<--to> or C<--from>, or a
C<--to> or C<--from> that cannot be an address - so nothing was signed or sent,
and no transport was asked to do anything.  C<2> never means that a message was
attempted and failed.

=head1 SEE ALSO

L<Mail::Send::DKIM>, the signer, and C<mail-dkim>, the sendmail front end that
C<dmarc-weekly.sh> sends its alerts through.

=cut