Debian Codegraph @

plugins/dkim

raw
1 #!perl -w
2
3 =head1 NAME
4
5 dkim: validate DomainKeys and (DKIM) Domain Keys Indentified Messages
6
7 =head1 SYNOPSIS
8
9 Validate the DKIM and Domainkeys signatures of a message, enforce DKIM
10 sending policies, and DKIM sign outgoing messages.
11
12 =head1 CONFIGURATION
13
14 =head2 reject [ 0 | 1 | naughty ]
15
16 dkim [ reject 0 ]
17
18 0 - do not reject
19 1 - reject messages that fail DKIM policy
20 naughty - defer rejection to the B<naughty> plugin
21
22 Default: 1
23
24 =head2 reject_type
25
26 dkim reject_type [ temp | perm ]
27
28 Default: perm
29
30 =head1 HOW TO SIGN
31
32 =head2 generate DKIM keys
33
34 =head3 the easy way
35
36 cd ~smtpd/config/dkim; ./dkim_key_gen.sh example.org
37
38 =head3 the manual way
39
40 mkdir -p ~smtpd/config/dkim/example.org
41 cd ~smtpd/config/dkim/example.org
42 echo 'may2013' > selector
43 openssl genrsa -out private 2048
44 chmod 400 private
45 openssl rsa -in private -out public -pubout
46 chown -R smtpd:smtpd ../example.org
47
48 After generating the keys, there will be three files in the example.org directory: selector, private, and public.
49
50 =head3 selector
51
52 The selector can be any value that is a valid DNS label.
53
54 =head3 key length
55
56 The minimum recommended key length for short duration keys (ones that will be replaced within a few months) is 1024. If you are unlikely to rotate your keys frequently, choose 2048, at the expense of a bit more CPU.
57
58 =head2 publish public key in DNS
59
60 If the DKIM keys were generated the easy way, there will be a fourth file named I<dns>. The contents contain the DNS formatted record of the public key, as well as suggestions for DKIM, SPF, and DMARC policy records. The records are ready to be copy/pasted into a BIND zone file, or better yet, NicTool. If you created your keys manually, look in the dkim_key_gen.sh script to see the commands used to format the DKIM public key.
61
62 The combination of the three example DKIM, SPF, and DMARC policy records in the I<dns> file tell other mail servers that if a sender claims to be from example.org, but the message is not DKIM nor SPF aligned, then the message should be rejected. Many email servers, including the largest email providers (Gmail, Yahoo, Outlook/Live/Hotmail) will refuse to accept such messages, greatly reducing the harm caused by miscreants who forge your domain(s) in the From header of their spam.
63
64 The DKIM record will look like this:
65
66 may2013._domainkey TXT "v=DKIM1;p=[public key stripped of whitespace];"
67
68 And the values in the address have the following meaning:
69
70 hash: h=[ sha1 | sha256 ]
71 test; t=[ s | s:y ]
72 granularity: g=[ ]
73 notes: n=[ ]
74 services: s=[email]
75 keytypes: [ rsa ]
76
77 =head2 testing
78
79 After confirming that the DKIM public key can be fetched with DNS (dig TXT may2013._domainkey.example.org. @ns1.example.org.), send test messages. You can testing DKIM by sending an email to:
80
81 * a Gmail address and inspect the Authentication-Results header.
82 * [email protected]
83 * [email protected]
84
85 The two DKIM relays provide a nice email report with additional debugging information.
86
87 =head2 publish DKIM policy in DNS
88
89 _domainkey TXT "o=~; t=y; [email protected]"
90
91 o=- - all are signed
92 o=~ - some are signed
93 t=y - test mode
94 r=[email] - responsible email address
95 n=[notes]
96
97 After DKIM and SPF are tested and working, update the policy, changing o=~ to o=-, so that other mail servers reject unsigned messages claiming to be from your domain.
98
99 As of this writing, most mail servers do not reject messages that fail DKIM policy, unless they also fail SPF, and no DMARC policy is published. The same holds true for SPF. There are technical reasons for this. See DMARC for more information, how you can control change that behavior, as well as receiving feedback from remote servers about messages they have accepted and rejected from senders claiming the identity of your domain(s).
100
101 =head2 Sign for others
102
103 Following the directions above will configure QP to DKIM sign messages from authenticated senders of example.org. Suppose you host client.com and would like to DKIM sign their messages too? Do that as follows:
104
105 cd ~smtpd/config/dkim
106 ln -s example.org client.com
107
108 QP will follow the symlink target and sign client.com emails with the example.org DKIM key.
109
110 This is B<not> necessary for hosts or subdomains. If the DKIM key for host.example.com does not exist, and a key for example.com does exist, the parent DKIM key will be used to sign the message. So long as your DKIM and DMARC policies are set to relaxed alignment, these signed messages for subdomains will pass.
111
112 CAUTION: just because you can sign for other domains, doesn't mean you should. Even with a relaxed DKIM policy, if the other domain doesn't have a suitable DMARC record for client.com, they may encounter deliverability problems. It is better to have keys generated and published for each domain.
113
114 =head1 SEE ALSO
115
116 http://www.dkim.org/
117
118 http://tools.ietf.org/html/rfc6376 - DKIM Signatures
119
120 http://tools.ietf.org/html/rfc5863 - DKIM Development, Deployment, & Operations
121
122 http://tools.ietf.org/html/rfc5617 - DKIM ADSP (Author Domain Signing Practices)
123
124 http://tools.ietf.org/html/rfc5585 - DKIM Service Overview
125
126 http://tools.ietf.org/html/rfc5016 - DKIM Signing Practices Protocol
127
128 http://tools.ietf.org/html/rfc4871 - DKIM Signatures
129
130 http://tools.ietf.org/html/rfc4870 - DomainKeys
131
132 http://dkimcore.org/tools/
133
134 http://www.protodave.com/tools/dkim-key-checker/
135
136 =head1 AUTHORS
137
138 2013 - Matt Simerson - added DKIM signing and key creation script
139
140 2012 - Matt Simerson - initial plugin
141
142 =head1 ACKNOWLEDGEMENTS
143
144 David Summers - http://www.nntp.perl.org/group/perl.qpsmtpd/2010/08/msg9417.html
145
146 Matthew Harrell - http://alecto.bittwiddlers.com/files/qpsmtpd/dkimcheck
147
148 I first attempted to fix the dkimcheck plugin, but soon scrapped that effort and wrote this one. Why?
149
150 =over 4
151
152 The use of $dkim->fetch_author_policy, which is deprecated by Mail::DKIM.
153
154 The paradim of a single policy, when DKIM supports 0 or many.
155
156 The OBF programming style, which is nigh impossible to test.
157
158 The nine 'if' brackets with 19 conditionals, and my inability to easily determine which of the 15 possible permutations (5 signature validation results x 3 possible policy results) were covered.
159
160 =back
161
162 =cut
163
164 use strict;
165 use warnings;
166
167 use Qpsmtpd::Constants;
168
169 # use Mail::DKIM::Verifier; # eval'ed in register()
170 # use Mail::DKIM::Signer;
171 use Socket qw(:DEFAULT :crlf);
172
173 sub init {
174 my ($self, $qp) = (shift, shift);
175 $self->{_args} = {@_};
176 $self->{_args}{reject} = 1 if !defined $self->{_args}{reject};
177 $self->{_args}{reject_type} ||= 'perm';
178 }
179
180 sub register {
181 my $self = shift;
182
183 # Mail::DKIM::TextWrap - nice idea, clients get mangled headers though
184 foreach my $mod (qw/ Mail::DKIM::Verifier Mail::DKIM::Signer /) {
185 eval "use $mod";
186 if ($@) {
187 warn "error, plugin disabled, could not load $mod\n";
188 $self->log(LOGERROR,
189 "skip, plugin disabled, is Mail::DKIM installed?");
190 return;
191 }
192 }
193
194 $self->register_hook('data_post', 'data_post_handler');
195 }
196
197 sub data_post_handler {
198 my ($self, $transaction) = @_;
199
200 if ($self->qp->connection->relay_client()) {
201
202 # this is an authenticated user sending a message.
203 return $self->sign_it($transaction);
204 }
205
206 return DECLINED if $self->is_immune();
207
208 return $self->validate_it($transaction);
209 }
210
211 sub validate_it {
212 my ($self, $transaction) = @_;
213
214 # Incoming message, perform DKIM validation
215 my $dkim = Mail::DKIM::Verifier->new() or do {
216 $self->log(LOGERROR,
217 "error, could not instantiate a new Mail::DKIM::Verifier");
218 return DECLINED;
219 };
220
221 $self->send_message_to_dkim($dkim, $transaction);
222 my $result = $dkim->result;
223 my $mess = $self->get_details($dkim);
224 $self->connection->notes('dkim_result', $result);
225 $self->connection->notes('dkim_verifier', $dkim);
226
227 my $auth_str = "dkim=" .$dkim->result_detail;
228 if ( $dkim->signature && $dkim->signature->domain ) {
229 $auth_str .= " header.i=@" . $dkim->signature->domain;
230 };
231 $self->store_auth_results( $auth_str );
232
233 foreach my $t (qw/ pass fail invalid temperror none /) {
234 next if $t ne $result;
235 my $handler = 'handle_sig_' . $t;
236 $self->log(LOGDEBUG, "dispatching $result to $handler");
237 return $self->$handler($dkim, $mess);
238 }
239
240 $self->log(LOGERROR, "error, unknown result: $result, $mess");
241 return DECLINED;
242 }
243
244 sub sign_it {
245 my ($self, $transaction) = @_;
246
247 my ($domain, $keydir) = $self->get_keydir($transaction) or return DECLINED;
248 my $selector = $self->get_selector($keydir);
249
250 my $dkim = Mail::DKIM::Signer->new(
251 Algorithm => "rsa-sha256",
252 Method => "relaxed",
253 Domain => $domain,
254 Selector => $selector,
255 KeyFile => "$keydir/private",
256 );
257
258 $self->send_message_to_dkim($dkim, $transaction);
259
260 my $signature = $dkim->signature; # what is the signature result?
261 $self->qp->transaction->header->add('DKIM-Signature',
262 $signature->as_string, 0);
263
264 $self->log(LOGINFO, "pass, we signed the message");
265 return DECLINED;
266 }
267
268 sub get_details {
269 my ($self, $dkim) = @_;
270
271 my @data;
272 my $string;
273 push @data, "domain: " . $dkim->signature->domain if $dkim->signature;
274 push @data, "selector: " . $dkim->signature->selector if $dkim->signature;
275 push @data, "result: " . $dkim->result_detail if $dkim->result_detail;
276
277 foreach my $policy ($dkim->policies) {
278 next if !$policy;
279 push @data, "policy: " . $policy->as_string;
280 push @data, "name: " . $policy->name;
281 push @data, "policy_location: " . $policy->location
282 if $policy->location;
283
284 my $policy_result;
285 $policy_result = $policy->apply($dkim);
286 $policy_result or next;
287 push @data, "policy_result: " . $policy_result if $policy_result;
288 }
289
290 return join(', ', @data);
291 }
292
293 sub handle_sig_fail {
294 my ($self, $dkim, $mess) = @_;
295
296 $self->adjust_karma(-1);
297 return $self->get_reject("signature invalid: " . $dkim->result_detail,
298 $mess);
299 }
300
301 sub handle_sig_temperror {
302 my ($self, $dkim, $mess) = @_;
303
304 $self->log(LOGINFO, "error, $mess");
305 return (DENYSOFT, "Please try again later - $dkim->result_detail");
306 }
307
308 sub handle_sig_invalid {
309 my ($self, $dkim, $mess) = @_;
310
311 my ($prs, $policies) = $self->get_policy_results($dkim);
312
313 foreach my $policy (@$policies) {
314 if ($policy->signall && !$policy->is_implied_default_policy) {
315 $self->log(LOGINFO, $mess);
316 return
317 $self->get_reject("invalid DKIM signature with sign-all policy",
318 "invalid signature, sign-all policy");
319 }
320 }
321
322 $self->adjust_karma(-1);
323 $self->log(LOGINFO, $mess);
324
325 if ($prs->{accept}) {
326 $self->log(LOGERROR, "error, invalid signature but accept policy!?");
327 return DECLINED;
328 }
329 elsif ($prs->{neutral}) {
330 $self->log(LOGERROR, "error, invalid signature but neutral policy?!");
331 return DECLINED;
332 }
333 elsif ($prs->{reject}) {
334 return
335 $self->get_reject("invalid DKIM signature: " . $dkim->result_detail,
336 "fail, invalid signature, reject policy");
337 }
338
339 # this should never happen
340 $self->log(LOGINFO, "error, invalid signature, unhandled");
341 return DECLINED;
342 }
343
344 sub handle_sig_pass {
345 my ($self, $dkim, $mess) = @_;
346
347 $self->save_signatures_to_note($dkim);
348
349 my ($prs) = $self->get_policy_results($dkim);
350
351 if ($prs->{accept}) {
352 $self->add_header($mess);
353 $self->log(LOGINFO, "pass, valid signature, accept policy");
354 $self->adjust_karma(1);
355 return DECLINED;
356 }
357 elsif ($prs->{neutral}) {
358 $self->add_header($mess);
359 $self->log(LOGINFO, "pass, valid signature, neutral policy");
360 $self->log(LOGDEBUG, $mess);
361 return DECLINED;
362 }
363 elsif ($prs->{reject}) {
364 $self->log(LOGINFO, $mess);
365 $self->adjust_karma(-1);
366 return
367 $self->get_reject("DKIM signature valid but fails policy, $mess",
368 "fail, valid sig, reject policy");
369 }
370
371 # this should never happen,
372 $self->add_header($mess);
373 $self->log(LOGERROR, "pass, valid sig, no policy results");
374 $self->log(LOGINFO, $mess);
375 return DECLINED;
376 }
377
378 sub handle_sig_none {
379 my ($self, $dkim, $mess) = @_;
380
381 my ($prs, $policies) = $self->get_policy_results($dkim);
382
383 foreach my $policy (@$policies) {
384 if ($policy->signall && !$policy->is_implied_default_policy) {
385 $self->log(LOGINFO, $mess);
386 return
387 $self->get_reject("no DKIM signature with sign-all policy",
388 "no signature, sign-all policy");
389 }
390 }
391
392 if ($prs->{accept}) {
393 $self->log(LOGINFO, "pass, no signature, accept policy");
394 return DECLINED;
395 }
396 elsif ($prs->{neutral}) {
397 $self->log(LOGINFO, "pass, no signature, neutral policy");
398 return DECLINED;
399 }
400 elsif ($prs->{reject}) {
401 $self->log(LOGINFO, $mess);
402 $self->get_reject(
403 "no DKIM signature, policy says reject: " . $dkim->result_detail,
404 "no signature, reject policy");
405 }
406
407 # should never happen
408 $self->log(LOGINFO, "error, no signature, no policy");
409 $self->log(LOGINFO, $mess);
410 return DECLINED;
411 }
412
413 sub get_keydir {
414 my ($self, $transaction) = @_;
415
416 my $domain = $transaction->sender->host;
417 my $dir = "config/dkim/$domain";
418
419 if (!-e $dir) { # the dkim key dir doesn't exist
420 my @labels = split /\./, $domain; # split the domain into labels
421 while (@labels > 1) {
422 shift @labels; # remove the first label (ie: www)
423 my $zone = join '.', @labels; # reassemble the labels
424 if (-e "config/dkim/$zone") { # if the directory exists
425 $domain = $zone; # the DKIM signing domain
426 $dir = "config/dkim/$zone"; # use the parent domain's key
427 $self->log(LOGINFO, "info, using $zone key for $domain");
428 }
429 }
430 }
431
432 if (-l $dir) {
433 $dir = readlink($dir);
434 $dir = "config/dkim/$dir" if $dir !~ /\//; # no /, relative path
435 ($domain) = (split /\//, $dir)[-1];
436 }
437
438 if (!-d $dir) {
439 $self->log(LOGINFO, "skip, DKIM not configured for $domain");
440 return;
441 }
442 if (!-r $dir) {
443 $self->log(LOGINFO, "error, unable to read key from $dir");
444 return;
445 }
446 if (!-r "$dir/private") {
447 $self->log(LOGINFO, "error, unable to read dkim key from $dir/private");
448 return;
449 }
450 return ($domain, $dir);
451 }
452
453 sub save_signatures_to_note {
454 my ($self, $dkim) = @_;
455
456 my %domains;
457 foreach my $sig ($dkim->signatures) {
458 next if $sig->result ne 'pass';
459 $domains{$sig->domain} = 1;
460 }
461 return if 0 == scalar keys %domains;
462
463 my $doms = $self->connection->notes('dkim_pass_domains') || [];
464 push @$doms, keys %domains;
465 $self->log(LOGDEBUG, "info, signed by: ". join(',', keys %domains) );
466 $self->connection->notes('dkim_pass_domains', $doms);
467 }
468
469 sub send_message_to_dkim {
470 my ($self, $dkim, $transaction) = @_;
471
472 foreach (split(/\n/s, $transaction->header->as_string)) {
473 $_ =~ s/\r?$//s;
474 eval { $dkim->PRINT($_ . CRLF); };
475 $self->log(LOGERROR, $@) if $@;
476 }
477
478 $transaction->body_resetpos;
479 while (my $line = $transaction->body_getline) {
480 chomp $line;
481 $line =~ s/\015$//;
482 eval { $dkim->PRINT($line . CRLF); };
483 $self->log(LOGERROR, $@) if $@;
484 }
485
486 eval { $dkim->CLOSE; };
487 $self->log(LOGERROR, $@) if $@;
488 }
489
490 sub get_policies {
491 my ($self, $dkim) = @_;
492
493 my @policies;
494 eval { @policies = $dkim->policies };
495 $self->log(LOGERROR, $@) if $@;
496 return @policies;
497 }
498
499 sub get_policy_results {
500 my ($self, $dkim) = @_;
501
502 my %prs;
503 my @policies = $self->get_policies($dkim);
504
505 foreach my $policy (@policies) {
506 my $policy_result;
507 eval { $policy_result = $policy->apply($dkim); }; # accept, reject, neutral
508 if ($@) {
509 $self->log(LOGERROR, $@);
510 }
511 $prs{$policy_result}++ if $policy_result;
512 }
513
514 return \%prs, \@policies;
515 }
516
517 sub get_selector {
518 my ($self, $keydir) = @_;
519
520 open my $SFH, '<', "$keydir/selector" or do {
521 $self->log(LOGINFO,
522 "error, unable to read selector from $keydir/selector");
523 return DECLINED;
524 };
525 my $selector = <$SFH>;
526 chomp $selector;
527 close $SFH;
528 $self->log(LOGDEBUG, "info, selector: $selector");
529 return $selector;
530 }
531
532 sub add_header {
533 my $self = shift;
534 my $header = shift or return;
535 $self->qp->transaction->header->add('X-DKIM-Authentication', $header, 0);
536 }
537