Debian Codegraph @

bin/amavisd-signer

raw ◀ ▶
1 Debian patch touch this file
1 #!/usr/bin/perl -T
2 # SPDX-License-Identifier: BSD-2-Clause
3
4 #------------------------------------------------------------------------------
5 # This is amavisd-signer, a DKIM signing service daemon for amavisd.
6 # It uses an AM.PDP protocol lookalike to receive a request from amavisd
7 # and provides two services: choosing a signing key, and signing a
8 # message digest with a chosen DKIM private key.
9 #
10 # Author: Mark Martinec <[email protected]>
11 #
12 # Copyright (c) 2010-2014, Mark Martinec
13 # All rights reserved.
14 #
15 # Redistribution and use in source and binary forms, with or without
16 # modification, are permitted provided that the following conditions
17 # are met:
18 # 1. Redistributions of source code must retain the above copyright notice,
19 # this list of conditions and the following disclaimer.
20 # 2. Redistributions in binary form must reproduce the above copyright notice,
21 # this list of conditions and the following disclaimer in the documentation
22 # and/or other materials provided with the distribution.
23 #
24 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
25 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
28 # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 # POSSIBILITY OF SUCH DAMAGE.
35 #
36 # The views and conclusions contained in the software and documentation are
37 # those of the authors and should not be interpreted as representing official
38 # policies, either expressed or implied, of the Jozef Stefan Institute.
39
40 # (the above license is the 2-clause BSD license, also known as
41 # a "Simplified BSD License", and pertains to this program only)
42 #
43 # Patches and problem reports are welcome.
44 # The latest version of this program is available at:
45 # http://www.ijs.si/software/amavisd/
46 #------------------------------------------------------------------------------
47
48 # Using a separate signing service (which may run under a dedicated UID or
49 # GID or as root, having exclusive access to private keys) releaves amavisd
50 # process from needing to have access to private keys. Separating roles can
51 # provide improved protection for DKIM private keys, and/or can provide more
52 # flexibility in choosing a signing key.
53 #
54 # Usage:
55 # amavisd-signer &
56
57 package AmavisSigner;
58
59 use strict;
60 use re 'taint';
61 use warnings FATAL => 'utf8';
62 no warnings 'uninitialized';
63
64 use Sys::Syslog; # used by Net::Server for logging
65 use MIME::Base64;
66 use Mail::DKIM;
67 use Mail::DKIM::PrivateKey;
68
69 use Net::Server 0.91;
70 use Net::Server::Multiplex;
71 use Amavis::Util;
72 use vars qw(@ISA);
73 @ISA = qw(Net::Server::Multiplex);
74
75 use vars qw(
76 $VERSION $log_level
77 %dkim_signing_keys_by_domain
78 @dkim_signing_keys_list @dkim_signing_keys_storage
79 @dkim_signature_options_bysender_maps
80 $daemon_chroot_dir $daemon_user @daemon_groups $pid_file $daemonize
81 $inet_socket_bind @listen_sockets $listen_queue_size
82 $syslog_ident $syslog_facility
83 );
84
85 $VERSION = 1.001; # 20100730
86
87 #
88 # Please adjust the following settings as necessary:
89 #
90
•91 $daemon_user = 'amavis';
92 @daemon_groups = 'amavis';
93 # $daemon_chroot_dir = '/var/lib/amavis'; # chroot directory or undef
94
95 # $daemonize = 1;
96
97 $log_level = 2; # 0..5
98 $syslog_facility = 'mail';
99 $syslog_ident = 'amavisd-signer';
100
101 # the $inet_socket_bind and @listen_sockets should correspond to a
102 # setting $dkim_signing_service in amavisd.conf :
103 $inet_socket_bind = '127.0.0.1';
104 @listen_sockets = ( 20203 );
105 $listen_queue_size = undef; # uses a default
106
107 # Load all available private keys and supply their public key RR constraints.
108 # Arguments are a domain, a selector, a key (a file name of a private key in
109 # PEM format), followed by optional attributes/constraints (tags, represented
110 # here as Perl hash key/value pairs) which are allowed by RFC 4871 in a public
111 # key resource record (v, g, h, k, n, s, t), of which only g, h, k, s and t
112 # are considered to be constraints limiting the choice of a signing key.
113 #
114 # signing domain selector private key options
115 # ------------- -------- ---------------------- ----------
116 # dkim_key('example.org', 'abc', '/var/db/dkim/a.key.pem');
117 # dkim_key('example.org', 'yyy', '/var/db/dkim/b.key.pem', t=>'s');
118 # dkim_key('example.org', 'zzz', '/var/db/dkim/b.key.pem', h=>'sha256');
119 # dkim_key('example.com', 'sel-2008', '/var/db/dkim/sel-example-com.key.pem',
120 # t=>'s:y', g=>'*', k=>'rsa', h=>'sha256:sha1', s=>'email',
121 # n=>'testing; 1, 2');
122 # dkim_key('guest.example.com', 'g', '/var/db/dkim/g-guest-ex-com.key.pem');
123 # dkim_key('mail.example.com', 'notif', '/var/db/dkim/notif-mail.key.pem');
124
125 # @dkim_signature_options_bysender_maps maps author/sender addresses or
126 # domains to signature tags/requirements; possible signature tags according
127 # to RFC 4871 are: (v), a, (b), (bh), c, d, (h), i, l, q, s, (t), x, z;
128 # of which the following are determined implicitly: v, b, bh, h, t
129 # (tag h is controlled by %signed_header_fields); currently ignored tags
130 # are l and z; instead of an absolute expiration time (tag x) one may use
131 # a pseudo tag 'ttl' to specify a relative expiration time in seconds, which
132 # is converted to an absolute expiration time prior to signing: x = t + ttl;
133 # a built-in default is provided for each tag if no better match is found
134 #
135 # @dkim_signature_options_bysender_maps = ( {
136 # '[email protected]' => { a => 'rsa-sha1', ttl => 7*24*3600 },
137 # '[email protected]' => { a => 'rsa-sha1', ttl => 7*24*3600 },
138 # 'mail.example.com' => { a => 'rsa-sha1', ttl => 10*24*3600 },
139 # # explicit 'd' forces a third-party signature on foreign (hosted) domains
140 # 'guest.example' => { d => 'guest.example.com' },
141 # '.example.com' => { d => 'example.com' },
142 # # catchall defaults
143 # '.' => { a => 'rsa-sha256', c => 'relaxed/simple', ttl => 30*24*3600 },
144 # # 'd' defaults to a domain of an author/sender address,
145 # # 's' defaults to whatever selector is offered by a matching key
146 # } );
147
148
149 #
150 # No further user-configurable settings below (but feel free
151 # to customize code in choose_key_request() or replace it altogether.
152 #
153
154 sub ll($) {
155 my($level) = @_;
156 $level <= $log_level;
157 }
158
159 my($server); # a Net::Server object
160 sub do_log($$;@) {
161 my($level, $errmsg, @args) = @_;
162 $errmsg = sprintf($errmsg,@args) if @args;
163 if ($level <= $log_level) {
164 my($prio); # Net::Server logging priority
165 # 0=err, 1=warning, 2=notice, 3=info, 4=debug
166 if ($level >= 3) { $prio = 4 }
167 elsif ($level >= 0) { $prio = 2 }
168 elsif ($level >= -1) { $prio = 1 }
169 else { $prio = 0 }
170 $server->log($prio, sanitize_str($errmsg));
171 # Net::Server directs STDERR to the log_file
172 # print STDERR sanitize_str($errmsg)."\n";
173 }
174 }
175
176 sub sanitize_str {
177 my($str, $keep_eol) = @_;
178 my(%map) = ("\r" => '\\r', "\n" => '\\n', "\f" => '\\f', "\t" => '\\t',
179 "\b" => '\\b', "\e" => '\\e', "\\" => '\\\\');
180 if ($keep_eol) {
181 $str =~ s/([^\012\040-\133\135-\176])/ # and \240-\376 ?
182 exists($map{$1}) ? $map{$1} :
183 sprintf(ord($1)>255 ? '\\x{%04x}' : '\\%03o', ord($1))/eg;
184 } else {
185 $str =~ s/([^\040-\133\135-\176])/ # and \240-\376 ?
186 exists($map{$1}) ? $map{$1} :
187 sprintf(ord($1)>255 ? '\\x{%04x}' : '\\%03o', ord($1))/eg;
188 }
189 $str;
190 }
191
192 sub split_address($) {
193 my($mailbox) = @_; local($1,$2);
194 $mailbox =~ /^ (.*?) ( \@ (?: \[ (?: \\. | [^\]\\] ){0,999} (?: \] | \z)
195 | [^\[\@] )*
196 ) \z/xs ? ($1, $2) : ($mailbox, '');
197 }
198
199 # THE dkim_key IS A DIRECT COPY OF THE SAME ROUTINE FROM amavisd
200 #
201 # Store a private DKIM signing key for a given domain and selector.
202 # The argument $key can be a Mail::DKIM::PrivateKey object or a file
203 # name containing a key in a PEM format (e.g. as generated by openssl).
204 # For compatibility with dkim_milter the signing domain can include a '*'
205 # as a wildcard - this is not recommended as this way amavisd could produce
206 # signatures which have no corresponding public key published in DNS.
207 # The proper way is to have one dkim_key entry for each published DNS RR.
208 # Optional arguments can provide additional information about the resource
209 # record (RR) of a public key, i.e. its options according to RFC 4871.
210 # The subroutine is typically called from a configuration file, once for
211 # each signing key available.
212 #
213 sub dkim_key($$$;@) {
214 my($domain,$selector,$key) = @_; shift; shift; shift;
215 @_%2 == 0 or die "dkim_key: a list of key/value pairs expected as options\n";
216 my(%key_options) = @_; # remaining args are options from a public key RR
217 defined $domain && $domain ne ''
218 or die "dkim_key: domain must not be empty: ($domain,$selector,$key)";
219 defined $selector && $selector ne ''
220 or die "dkim_key: selector must not be empty: ($domain,$selector,$key)";
221 my($key_storage_ind);
222 if (ref $key) { # key already preprocessed and provided as an object
223 push(@dkim_signing_keys_storage, [$key]);
224 $key_storage_ind = $#dkim_signing_keys_storage;
225 } else { # assume a name of a file containing a private key in PEM format
226 my($fname) = $key;
227 my($pem_fh) = IO::File->new; # open a file with a private key
228 $pem_fh->open($fname,'<') or die "Can't open PEM file $fname: $!";
229 my(@stat_list) = stat($pem_fh); # soft-link friendly
230 @stat_list or warn "Error on accessing $fname: $!";
231 my($dev,$inode) = @stat_list;
232 if ($dev && $inode) {
233 for my $j (0..$#dkim_signing_keys_storage) { # same file reused?
234 my($k,$dv,$in,$fn) = @{$dkim_signing_keys_storage[$j]};
235 if ($dv == $dev && $in == $inode) { $key_storage_ind = $j; last }
236 }
237 }
238 if (!defined($key_storage_ind)) {
239 # read file and store its contents as a new entry
240 my($nbytes,$buff); $key = '';
241 while (($nbytes=$pem_fh->read($buff,16384)) > 0) { $key .= $buff }
242 defined $nbytes or die "Error reading key from file $fname: $!";
243 push(@dkim_signing_keys_storage, [$key,$dev,$inode,$fname]);
244 $key_storage_ind = $#dkim_signing_keys_storage;
245 }
246 $pem_fh->close or die "Error closing file $fname: $!";
247 $key_options{k} = 'rsa' if defined $key_options{k}; # force RSA
248 }
249 $domain = lc($domain) if !ref($domain); # possibly a regexp
250 $selector = lc($selector);
251 $key_options{domain} = $domain; $key_options{selector} = $selector;
252 $key_options{key_storage_ind} = $key_storage_ind;
253 if (@dkim_signing_keys_list > 100) {
254 # sorry, skip the test to avoid slow O(n^2) searches
255 } else {
256 !(grep { $_->{domain} eq $domain && $_->{selector} eq $selector }
257 @dkim_signing_keys_list)
258 or die "dkim_key: selector $selector for domain $domain already in use\n";
259 }
260 $key_options{key_ind} = $#dkim_signing_keys_list + 1;
261 push(@dkim_signing_keys_list, \%key_options); # using a list preserves order
262 }
263
264 # THE dkim_key_postprocess IS A DIRECT COPY OF THE SAME ROUTINE FROM amavisd
265 #
266 # Convert private keys (as strings in PEM format) into RSA objects
267 # and do some pre-processing on @dkim_signing_keys_list entries
268 # (may run unprivileged)
269 #
270 sub dkim_key_postprocess() {
271 # convert private keys (as strings in PEM format) into RSA objects
272 for my $ks (@dkim_signing_keys_storage) {
273 my($pkcs1,$dev,$inode,$fname) = @$ks;
274 if (ref($pkcs1) && UNIVERSAL::isa($pkcs1,'Crypt::OpenSSL::RSA')) {
275 # it is already a Crypt::OpenSSL::RSA object
276 } else {
277 # assume a string is a private key in PEM format, convert it to RSA obj
278 $ks->[0] = Crypt::OpenSSL::RSA->new_private_key($pkcs1);
279 }
280 }
281 for my $ent (@dkim_signing_keys_list) {
282 my($domain) = $ent->{domain};
283 $dkim_signing_keys_by_domain{$domain} = []
284 if !$dkim_signing_keys_by_domain{$domain};
285 }
286 my($any_wild); my($j) = 0;
287 for my $ent (@dkim_signing_keys_list) {
288 $ent->{v} = 'DKIM1' if !defined $ent->{v}; # provide a default
289 if (defined $ent->{n}) { # encode n as qp-section (rfc4871, rfc2047)
290 $ent->{n} =~ s{([\000-\037\177=;"])}{sprintf('=%02X',ord($1))}egs;
291 }
292 my($domain) = $ent->{domain};
293 if (ref($domain) eq 'Regexp') {
294 $ent->{domain_re} = $domain;
295 $any_wild = sprintf("key#%d, %s", $j+1, $domain) if !defined $any_wild;
296 } elsif ($domain =~ /\*/) {
297 # wildcarded signing domain in a key declaration, evil, asks for trouble!
298 # support wildcards in signing domain for compatibility with dkim_milter
299 my($regexp) = $domain;
300 $regexp =~ s/\*{2,}/*/gs; # collapse successive wildcards
301 # '*' is a wildcard, quote the rest
302 $regexp =~ s{ ([@#/.^$|*+?(){}\[\]\\]) }{$1 eq '*' ? '.*' : '\\'.$1}gex;
303 $regexp = '^' . $regexp . '\\z'; # implicit anchors
304 $regexp =~ s/^\^\.\*//s; # remove leading anchor if redundant
305 $regexp =~ s/\.\*\\z\z//s; # remove trailing anchor if redundant
306 $regexp = '(?:)' if $regexp eq ''; # just in case, non-empty regexp
307 # presence of {'domain_re'} entry lets get_dkim_key use this regexp
308 # instead of a direct string comparision with {'domain'}
309 $ent->{domain_re} = qr{$regexp}; # compiled regexp object
310 $any_wild = sprintf("key#%d, %s", $j+1, $domain) if !defined $any_wild;
311 }
312 # %dkim_signing_keys_by_domain entries contain lists of indices into
313 # the @dkim_signing_keys_list of all potentially applicable signing keys.
314 # This hash (keyed by domain name) avoids linear searching for signing
315 # keys for all fully-specified domains in @dkim_signing_keys_list.
316 # Wildcarded entries must still be looked up sequentially at run-time
317 # to preserve the declared order and the 'first match wins' paradigm.
318 # Such entries are only supported for compatibility with dkim_milter
319 # and are evil because amavisd has no quick way of verifying that DNS RR
320 # really exists, so signatures generated by amavisd can fail when not all
321 # possible DNS resource records exist for wildcarded signing domains.
322 #
323 if (!defined($ent->{domain_re})) { # no regexp, just plain match on domain
324 push(@{$dkim_signing_keys_by_domain{$domain}}, $j);
325 } else { # a wildcard in a signing domain, compatibility with dkim_milter
326 # wildcarded signing domain potentially matches any _by_domain entry
327 for my $d (keys %dkim_signing_keys_by_domain) {
328 push(@{$dkim_signing_keys_by_domain{$d}}, $j);
329 }
330 # the '*' entry collects only wildcarded signing keys
331 $dkim_signing_keys_by_domain{'*'} = []
332 if !$dkim_signing_keys_by_domain{'*'};
333 push(@{$dkim_signing_keys_by_domain{'*'}}, $j);
334 }
335 $j++;
336 }
337 do_log(0,"dkim: wildcard in signing domain (%s), may produce unverifiable ".
338 "signatures with no published public key, avoid!", $any_wild)
339 if $any_wild;
340 }
341
342 # THE get_dkim_key IS A DIRECT COPY OF THE SAME ROUTINE FROM amavisd
343 #
344 # Fetch a private DKIM signing key for a given signing domain, with its
345 # resource-record (RR) constraints compatible with proposed signature options.
346 # The first such key is returned as a hash; if no key is found an empty hash
347 # is returned. When a selector (s) is given it must match the selector of
348 # a key; when algorithm (a) is given, the key type and a hash algorithm must
349 # match the desired use too; the service type (s) must be 'email' or '*';
350 # when identity (i) is given it must match the granularity (g) of a key;
351 #
352 # sign.opts. key options
353 # ---------- -----------
354 # d => domain
355 # s => selector
356 # a => k, h(list)
357 # i => g, t=s
358 #
359 sub get_dkim_key(@) {
360 @_ % 2 == 0 or die "get_dkim_key: a list of pairs is expected as query opts";
361 my(%options) = @_; # signature options (v, a, c, d, h, i, l, q, s, t, x, z),
362 # of which d is required, while s, a and t are optional but taken into
363 # account in searching for a compatible key - the rest are ignored
364 my(%key_options);
365 my($domain) = $options{d};
366 defined $domain && $domain ne ''
367 or die "get_dkim_key: domain is required, but tag 'd' is missing";
368 $domain = lc($domain);
369 my(@indices) = $dkim_signing_keys_by_domain{$domain} ?
370 @{$dkim_signing_keys_by_domain{$domain}} :
371 $dkim_signing_keys_by_domain{'*'} ?
372 @{$dkim_signing_keys_by_domain{'*'}} : ();
373 if (@indices) {
374 my($selector) = $options{s};
375 $selector = $selector eq '' ? undef : lc($selector) if defined $selector;
376 local($1,$2);
377 my($keytype,$hashalg) =
378 defined $options{a} && $options{a} =~ /^([a-z0-9]+)-(.*)\z/is ? ($1,$2)
379 : ('rsa',undef);
380 my($identity_localpart,$identity_domain) =
381 !defined($options{i}) ? () : split_address($options{i});
382 $identity_localpart = '' if !defined $identity_localpart;
383 $identity_domain = '' if !defined $identity_domain;
384 # find the first key (associated with a domain) with compatible options
385 for my $j (@indices) {
386 my($ent) = $dkim_signing_keys_list[$j];
387 next unless defined $ent->{domain_re} ? $domain =~ $ent->{domain_re}
388 : $domain eq $ent->{domain};
389 next if defined $selector && $ent->{selector} ne $selector;
390 next if $keytype ne (exists $ent->{k} ? $ent->{k} : 'rsa');
391 next if exists $ent->{s} &&
392 !(grep { $_ eq '*' || $_ eq 'email' } split(/:/, $ent->{s}) );
393 next if defined $hashalg && exists $ent->{'h'} &&
394 !(grep { $_ eq $hashalg } split(/:/, $ent->{'h'}) );
395 if (defined($options{i})) {
396 if (lc($identity_domain) eq $domain) {
397 # ok
398 } elsif (exists $ent->{t} && (grep {$_ eq 's'} split(/:/,$ent->{t}))) {
399 next; # no subdomains allowed
400 }
401 if (!exists($ent->{g}) || $ent->{g} eq '*') {
402 # ok
403 } elsif ($ent->{g} =~ /^ ([^*]*) \* (.*) \z/xs) {
404 next if $identity_localpart !~ /^ \Q$1\E .* \Q$2\E \z/xs;
405 } else {
406 next if $identity_localpart ne $ent->{g};
407 }
408 }
409 %key_options = %$ent; last; # found a suitable match
410 }
411 }
412 if (defined $key_options{key_storage_ind}) {
413 # obtain actual key from @dkim_signing_keys_storage
414 ($key_options{key}) =
415 @{$dkim_signing_keys_storage[$key_options{key_storage_ind}]};
416 }
417 %key_options;
418 }
419
420 sub proto_encode($@) {
421 my($attribute_name,@strings) = @_; local($1);
422 for ($attribute_name,@strings) {
423 # just in case, handle non-octet characters:
424 s/([^\000-\377])/sprintf('\\x{%04x}',ord($1))/eg and
425 do_log(-1,"proto_encode: non-octet character encountered: %s", $_);
426 }
427 $attribute_name =~ # encode all but alfanumerics, . _ + -
428 s/([^0-9a-zA-Z._+-])/sprintf("%%%02x",ord($1))/eg;
429 for (@strings) { # encode % and nonprintables
430 s/([^\041-\044\046-\176])/sprintf("%%%02x",ord($1))/eg;
431 }
432 $attribute_name . '=' . join(' ',@strings);
433 }
434
435 sub proto_decode($) {
436 my($str) = @_; local($1);
437 $str =~ s/%([0-9a-fA-F]{2})/pack("C",hex($1))/egs;
438 $str;
439 }
440
441 sub split_localpart($$) {
442 my($localpart, $delimiter) = @_;
443 my($owner_request_special) = 1; # configurable ???
444 my($extension); local($1,$2);
445 if ($localpart =~ /^(postmaster|mailer-daemon|double-bounce)\z/i) {
446 # do not split these, regardless of what the delimiter is
447 } elsif ($delimiter eq '-' && $owner_request_special &&
448 $localpart =~ /^owner-.|.-request\z/si) {
449 # don't split owner-foo or foo-request
450 } elsif ($localpart =~ /^(.+?)(\Q$delimiter\E.*)\z/s) {
451 ($localpart, $extension) = ($1, $2); # extension includes a delimiter
452 # do not split the address if the result would have a null localpart
453 }
454 ($localpart, $extension);
455 }
456
457 sub unique_ref(@) {
458 my($r) = @_ == 1 && ref($_[0]) ? $_[0] : \@_; # accept list, or a list ref
459 my(%seen); my(@result) = grep { defined($_) && !$seen{$_}++ } @$r;
460 \@result;
461 }
462
463 sub make_query_keys($$$;$) {
464 my($addr,$at_with_user,$include_bare_user,$append_string) = @_;
465 my($localpart,$domain) = split_address($addr); $domain = lc($domain);
466 my($saved_full_localpart) = $localpart;
467 $localpart = lc($localpart); ### if !c('localpart_is_case_sensitive');
468 # chop off leading @, and trailing dots
469 local($1);
470 $domain = $1 if $domain =~ /^\@?(.*?)\.*\z/s;
471 my($extension); my($delim) = '+'; ### c('recipient_delimiter');
472 if ($delim ne '') {
473 ($localpart,$extension) = split_localpart($localpart,$delim);
474 # extension includes a delimiter since amavisd-new-2.5.0!
475 }
476 $extension = '' if !defined $extension; # mute warnings
477 my($append_to_user,$prepend_to_domain) = $at_with_user ? ('@','') : ('','@');
478 my(@keys); # a list of query keys
479 push(@keys, $addr); # as is
480 push(@keys, $localpart.$extension.'@'.$domain)
481 if $extension ne ''; # [email protected]
482 push(@keys, $localpart.'@'.$domain); # [email protected]
483 if ($include_bare_user) { # typically enabled for local users only
484 push(@keys, $localpart.$extension.$append_to_user)
485 if $extension ne ''; # user+foo(@)
486 push(@keys, $localpart.$append_to_user); # user(@)
487 }
488 push(@keys, $prepend_to_domain.$domain); # (@)sub.example.com
489 if ($domain =~ /\[/) { # don't split address literals
490 push(@keys, $prepend_to_domain.'.'); # (@).
491 } else {
492 my(@dkeys); my($d) = $domain;
493 for (;;) { # (@).sub.example.com (@).example.com (@).com (@).
494 push(@dkeys, $prepend_to_domain.'.'.$d);
495 last if $d eq '';
496 $d = ($d =~ /^([^.]*)\.(.*)\z/s) ? $2 : '';
497 }
498 if (@dkeys > 10) { @dkeys = @dkeys[$#dkeys-9 .. $#dkeys] } # sanity limit
499 push(@keys,@dkeys);
500 }
501 if (defined $append_string && $append_string ne '') {
502 $_ .= $append_string for @keys;
503 }
504 my($keys_ref) = unique_ref(\@keys); # remove duplicates
505 ll(5) && do_log(5,"query_keys: %s", join(', ',@$keys_ref));
506 # the rhs replacement strings are similar to what would be obtained
507 # by lookup_re() given the following regular expression:
508 # /^( ( ( [^\@]*? ) ( \Q$delim\E [^\@]* )? ) (?: \@ (.*) ) )$/xs
509 my($rhs) = [ # a list of right-hand side replacement strings
510 $addr, # $1 = [email protected]
511 $saved_full_localpart, # $2 = User+Foo
512 $localpart, # $3 = user
513 $extension, # $4 = +foo
514 $domain, # $5 = sub.example.com
515 ];
516 ($keys_ref, $rhs);
517 }
518
519 sub lookup_hash($$;$%) {
520 my($addr, $hash_ref,$get_all,%options) = @_;
521 ref($hash_ref) eq 'HASH'
522 or die "lookup_hash: arg2 must be a hash ref: $hash_ref";
523 local($1,$2,$3,$4); my(@matchingkey,@result); my($append_string);
524 $append_string = $options{AppendStr} if defined $options{AppendStr};
525 my($keys_ref,$rhs_ref) = make_query_keys($addr,1,1,$append_string);
526 for my $key (@$keys_ref) { # do the search
527 if (exists $$hash_ref{$key}) { # got it
528 push(@result,$$hash_ref{$key}); push(@matchingkey,$key);
529 last if !$get_all;
530 }
531 }
532 # do the right-hand side replacements if any $n, ${n} or $(n) is specified
533 for my $r (@result) { # remember that $r is just an alias to array elements
534 if (defined($r) && !ref($r) && index($r,'$') >= 0) { # plain string with $
535 my($any) = $r =~ s{ \$ ( (\d+) | \{ (\d+) \} | \( (\d+) \) ) }
536 { my($j)=$2+$3+$4; $j<1 ? '' : $rhs_ref->[$j-1] }gxse;
537 # bring taintedness of input to the result
538 $r .= substr($addr,0,0) if $any;
539 }
540 }
541 if (!$get_all) { ($result[0], $matchingkey[0]) }
542 else { (\@result, \@matchingkey) }
543 }
544
545 sub lookup2($$$%) {
546 my($get_all, $addr, $tables_ref, %options) = @_;
547 (@_ - 3) % 2 == 0 or die "lookup2: options argument not in pairs (not hash)";
548 my($label, @result,@matchingkey);
549 for my $tb (!$tables_ref ? () : @$tables_ref) {
550 my($t) = ref($tb) eq 'REF' ? $$tb : $tb; # allow one level of indirection
551 if (!ref($t) || ref($t) eq 'SCALAR') { # a scalar always matches
552 my($r) = ref($t) ? $$t : $t; # allow direct or indirect reference
553 if (defined $r) {
554 do_log(5,'lookup: (scalar) matches, result="%s"', $r);
555 push(@result,$r); push(@matchingkey,"(constant:$r)");
556 }
557 } elsif (ref($t) eq 'HASH') {
558 my($r,$mk);
559 ($r,$mk) = lookup_hash($addr,$t,$get_all,%options) if %$t;
560 if (!defined $r) {}
561 elsif (!$get_all) { push(@result,$r); push(@matchingkey,$mk) }
562 elsif (@$r) { push(@result,@$r); push(@matchingkey,@$mk) }
563 } else {
564 die "TROUBLE: lookup table not implemented for object: " . ref($t);
565 }
566 last if @result && !$get_all;
567 }
568 if (!$get_all) { ($result[0], $matchingkey[0]) }
569 else { (\@result, \@matchingkey) }
570 }
571
572 sub parse_quoted_rfc2821($$) {
573 my($addr,$unquote) = @_;
574 # the angle-bracket stripping is not really a duty of this subroutine,
575 # as it should have been already done elsewhere, but we allow it here anyway:
576 $addr =~ s/^\s*<//s; $addr =~ s/>\s*\z//s; # tolerate unmatched angle brkts
577 local($1,$2); my($source_route,$localpart,$domain) = ('','','');
578 # RFC 2821: so-called "source route" MUST BE accepted,
579 # SHOULD NOT be generated, and SHOULD be ignored.
580 # Path = "<" [ A-d-l ":" ] Mailbox ">"
581 # A-d-l = At-domain *( "," A-d-l )
582 # At-domain = "@" domain
583 if (index($addr,':') >= 0 && # triage before more testing for source route
584 $addr =~ m{^ ( [ \t]* \@ (?: [0-9A-Za-z.!\#\$%&*/^{}=_+-]* |
585 \[ (?: \\. | [^\]\\] ){0,999} \] ) [ \t]*
586 (?: , [ \t]* \@ (?: [0-9A-Za-z.!\#\$%&*/^{}=_+-]* |
587 \[ (?: \\. | [^\]\\] ){0,999} \] ) [ \t]* )*
588 : [ \t]* ) (.*) \z }xs)
589 { # NOTE: we are quite liberal on allowing whitespace around , and : here,
590 # and liberal in allowed character set and syntax of domain names,
591 # we mainly avoid stop-characters in the domain names of source route
592 $source_route = $1; $addr = $2;
593 }
594 if ($addr =~ m{^ ( .*? )
595 ( \@ (?: [^\@\[\]]+ | \[ (?: \\. | [^\]\\] ){0,999} \]
596 | [^\@] )* )
597 \z}xs) {
598 ($localpart,$domain) = ($1,$2);
599 } else {
600 ($localpart,$domain) = ($addr,'');
601 }
602 $localpart =~ s/ " | \\ (.) | \\ \z /$1/xsg if $unquote; # undo quoted-pairs
603 ($source_route, $localpart, $domain);
604 }
605
606 sub unquote_rfc2821_local($) {
607 my($mailbox) = @_;
608 my($source_route,$localpart,$domain) = parse_quoted_rfc2821($mailbox,1);
609 # make address with '@' in the localpart but no domain (like <"[email protected]"> )
610 # distinguishable from <[email protected]> by representing it as [email protected]@ in
611 # unquoted form; (it still obeys all regular rules, it is not a dirty trick)
612 $domain = '@' if $domain eq '' && $localpart ne '' && $localpart =~ /\@/;
613 $localpart . $domain;
614 }
615
616 #
617 # ======================================================================
618 # Code above is copied from amavisd; some day it should be factored out.
619 # Code from here on is specific to amavisd-signer.
620 # ======================================================================
621 #
622
623 # process a request to choose a signing key;
624 #
625 sub choose_key_request($) {
626 my($attr) = @_;
627 my(@results);
628 my(%sig_options); # signature options, and constraints for choosing a key
629 my(%key_options); # options associated with a signing key
630 my(@tried_domains); # used for logging a failure
631 my($chosen_addr,$chosen_addr_src);
632 my($cand) = $attr->{candidate};
633 my(@candidates) = !defined $cand ? () : !ref $cand ? $cand : @$cand;
634 my($sobm) = \@dkim_signature_options_bysender_maps;
635 for my $pair (@candidates) {
636 my($addr_src,$addr) = split(' ',$pair,2);
637 $addr = unquote_rfc2821_local($addr);
638 my($addr_localpart,$addr_domain) = split_address($addr);
639 $addr_domain = lc($addr_domain);
640 my($dkim_options_ref,$mk_ref) = lookup2(1,$addr,$sobm);
641 $dkim_options_ref = [] if !defined $dkim_options_ref; #***?
642 # place catchall default(s) at the end of the list of options;
643 push(@$dkim_options_ref, { c => 'relaxed/simple', a => 'rsa-sha256' });
644 %sig_options = (); # signature options:
645 # (v), a, (b), (bh), c, d, (h), i, (l), q, s, (t), x, (z)
646 # traverse from specific to general, first match wins
647 for my $opts_hash_ref (@$dkim_options_ref) {
648 while (my($k,$v) = each(%$opts_hash_ref))
649 { $sig_options{$k} = $v if !exists($sig_options{$k}) }
650 }
651 # a default for a signing domain is a domain of each tried address
652 if (!exists($sig_options{d}))
653 { my($d) = $addr_domain; $d =~ s/^\@//; $sig_options{d} = $d }
654 push(@tried_domains, $sig_options{d});
655 ll(5) && do_log(5, "signature options for %s(%s): %s", $addr,$addr_src,
656 join('; ', map { $_.'='.$sig_options{$_} } keys %sig_options));
657 # find a private key associated with a signing domain and selector,
658 # and meeting constraints
659 %key_options = get_dkim_key(%sig_options)
660 if defined $sig_options{d} && $sig_options{d} ne '';
661 my($key) = $key_options{key};
662 if (defined $key && $key ne '') { # found; copy the key and its options
663 $sig_options{key} = $key; $sig_options{s} = $key_options{selector};
664 $chosen_addr = $addr; $chosen_addr_src = $addr_src;
665 last;
666 }
667 }
668 # if any signature options were specified in the request and not overruled
669 # by more specific ones here, copy them to the resulting set of sig options
670 for my $opt (keys %$attr) {
671 if ($opt =~ /^sig\.(.+)\z/) {
672 $sig_options{$1} = $attr->{$opt} if !exists($sig_options{$1});
673 }
674 }
675 ll(5) && do_log(5, "sig options: %s",
676 join('; ', map { $_.'='.$sig_options{$_} } keys %sig_options));
677 my(%key_options);
678 if (defined $sig_options{d} && $sig_options{d} ne '') {
679 %key_options = get_dkim_key(%sig_options);
680 }
681 do_log(5, "key options: %s is %s",
682 $_, $key_options{$_}) for keys %key_options;
683 my($s) = $key_options{'selector'};
684 my($d) = $key_options{'domain'};
685 $sig_options{'s'} = $s;
686 $sig_options{'d'} = $d;
687 delete $sig_options{'key'}; # no use of key ref in the protocol
688 for my $opt (sort keys %sig_options) {
689 if (defined $sig_options{$opt}) {
690 push(@results, proto_encode('sig.'.$opt, $sig_options{$opt}));
691 }
692 }
693 # optional information if available: client may log it, or use for debugging
694 if (defined $chosen_addr_src && defined $chosen_addr) {
695 push(@results, proto_encode('chosen_candidate',
696 $chosen_addr_src, $chosen_addr));
697 }
698 \@results;
699 }
700
701 # sign a digest code using the specified algorithm and a private signing key
702 #
703 sub dkim_rsa_sign($$$) {
704 my($digest,$alg_name,$key) = @_;
705 my($result);
706 $digest = '' if !defined $digest;
707 $alg_name = '' if !defined $alg_name;
708 if (defined $key && $key ne '') {
709 my($key) = Mail::DKIM::PrivateKey->load(Cork => $key);
710 $key or die "no key available\n";
711 $result = $key->sign_digest($alg_name,$digest);
712 }
713 $result;
714 }
715
716 # process a request to sign the supplied digest with a selected key
717 #
718 # presence of the 'b' attribute in the result indicates success,
719 # otherwise the result is treated as signature unavailable
720 #
721 sub sign_request($) {
722 my($attr) = @_;
723 my(@results, $reason, $sig);
724 my($digest, $digest_alg, $selector, $domain) =
725 @$attr{qw(digest digest_alg s d)};
726 if (!defined $digest || $digest eq '') {
727 $reason = 'cannot sign, digest not provided, nothing to sign';
728 } elsif (!defined $digest_alg || $digest_alg eq '') {
729 $reason = 'cannot sign, digest algorithm name not provided';
730 } elsif (!defined $domain || $domain eq '') {
731 $reason = 'cannot sign, signing domain not provided';
732 } elsif (!defined $selector || $selector eq '') {
733 $reason = 'cannot sign, selector not provided';
734 } else {
735 my(%sig_options); # signature options: v, a, c, d, h, i, l, q, s, t, x, z
736 $sig_options{s} = $selector;
737 $sig_options{d} = $domain;
738 my(%key_options) = get_dkim_key(%sig_options);
739 if (!defined $key_options{key}) {
740 $reason = 'cannot sign, signing key not available';
741 } else {
742 do_log(5, "key options: %s is %s",
743 $_, $key_options{$_}) for keys %key_options;
744 eval {
745 $sig = dkim_rsa_sign(decode_base64($digest),
746 $digest_alg, $key_options{key}); 1;
747 } or do {
748 my($eval_stat) = $@ ne '' ? $@ : "errno=$!"; chomp $eval_stat;
749 do_log(0, "signing failed: %s", $eval_stat);
750 $reason = 'cannot sign: ' . $eval_stat;
751 };
752 push(@results, proto_encode('d', $key_options{'domain'}));
753 push(@results, proto_encode('s', $key_options{'selector'}));
754 }
755 }
756 if (defined $sig && $sig ne '') {
757 push(@results, proto_encode('b', encode_base64($sig,'')));
758 } else {
759 $reason = 'cannot sign: signing failed' if !defined $reason;
760 push(@results, proto_encode('reason', $reason));
761 }
762 \@results;
763 }
764
765 # process the request received from amavisd
766 #
767 sub do_the_request($) {
768 my($attr) = @_;
769 ll(2) && do_log(2, "got: %s", join('; ', map {
770 my($k) = $_; my($v) = $attr->{$k};
771 map { $k.'='.$_ } (!ref $v ? $v : @$v) } keys %$attr));
772 my(@results);
773 my($req_id) = $attr->{request_id};
774 my($log_id) = $attr->{log_id};
775 push(@results, proto_encode('request_id', $req_id)) if defined $req_id;
776 push(@results, proto_encode('log_id', $log_id)) if defined $log_id;
777 my($request_type) = $attr->{request};
778 $request_type = '' if !defined $request_type;
779 if ($request_type eq 'choose_key') {
780 push(@results, @{choose_key_request($attr)});
781 } elsif ($request_type eq 'sign') {
782 push(@results, @{sign_request($attr)});
783 } else {
784 push(@results, proto_encode('reason', 'unknown request type'));
785 do_log(2, "got: ignoring request: %s", $request_type);
786 }
787 ll(1) && do_log(1, "response: %s", join('; ', @results));
788 do_log(5, "");
789 \@results;
790 }
791
792 # IO::Multiplex -style callback hook
793 #
794 sub mux_connection {
795 my($self,$mux,$fh) = @_;
796 do_log(3, "client %s just connected", $self->{peeraddr});
797 $self->{attr} = {};
798 }
799
800 # the mux_connection callback is guaranteed to have already been run once
801 #
802 sub mux_input {
803 my($self,$mux,$fh,$in_ref) = @_;
804 my $attr = $self->{attr};
805 do_log(5, "input from %s ready", $self->{peeraddr});
806
807 # process each line in the input, leaving partial lines in the input buffer
808 local($1,$2); my($quit) = 0;
809 while ($$in_ref =~ s/^(.*?)\015?\012//) {
810 my($ln) = $1;
811 if ($ln eq '') { # empty line indicates end of a request
812 my($results_ref) = do_the_request($attr);
813 print(join('', map { $_."\015\012" } (@$results_ref,'')))
814 or do_log(0,"mux_input: error writing a response to socket" );
815 %$attr = (); # reset, awaiting next request in the same session
816 } elsif ($ln =~ /^ ([^=\000\012]*?) (?: = | : [ \t]* ) (.*) \z/xsi) {
817 my($attr_name) = proto_decode($1);
818 my($attr_val) = proto_decode($2);
819 if (!exists $attr->{$attr_name}) {
820 $attr->{$attr_name} = $attr_val; # simple scalar for one-time attrs
821 } elsif (!ref($attr->{$attr_name})) { # multiple, convert to a list
822 $attr->{$attr_name} = [ $attr->{$attr_name}, $attr_val ];
823 } else { # append to a list of same-name attributes
824 push(@{$attr->{$attr_name}}, $attr_val);
825 }
826 } else {
827 do_log(0, "mux_input: ignored line: %s", $ln);
828 }
829 }
830 close(STDOUT) if $quit;
831 }
832
833
834 #
835 # Main program starts here (after initializations near the top of this file)
836 #
837
838 @daemon_groups = Amavis::Util::get_user_groups($daemon_user) if not @daemon_groups;
839
840 dkim_key_postprocess();
841
842 # set up a Net::Server configuration
843 $server = AmavisSigner->new({
844 # limit socket bind (e.g. to the loopback interface)
845 host => (!defined $inet_socket_bind || $inet_socket_bind eq '' ? '*'
846 : $inet_socket_bind),
847 port => \@listen_sockets, # listen on these sockets (Unix or inet)
848 listen => $listen_queue_size, # undef for a default
849 user => ($> == 0 || $< == 0) ? $daemon_user : undef,
850 group => (($> == 0 || $< == 0) && @daemon_groups) ? "@daemon_groups" : undef,
851 background => $daemonize ? 1 : undef,
852 setsid => $daemonize ? 1 : undef,
853 chroot => $daemon_chroot_dir ne '' ? $daemon_chroot_dir : undef,
854 pid_file => $pid_file,
855 log_file => $daemonize ? 'Sys::Syslog' : undef,
856 syslog_ident => $syslog_ident,
857 syslog_facility => $syslog_facility,
858 syslog_logsock => 'native',
859 # 0=err, 1=warning, 2=notice, 3=info, 4=debug
860 log_level => $log_level >= 5 ? 4 : 2,
861 });
862
863 $server->run; # transferring control to Net::Server
864 exit 1; # shouldn't get here
865
866 # TODO: pkcs11 URI
867 # In order to use a key an application needs the path to the PKCS11 lib,
868 # the key ID, username, pin and the slot number
869 #
870 # http://blogs.sun.com/janp/entry/pkcs_11_engine_patch_including
871 # pkcs11:[object=<label>] # object (key) label, eg. "mykey"
872 # [;token=<label>] # token label
873 # [;manuf=<label>] # manufacturer ID
874 # [;serial=<label>] # serial number of the token
875 # [;model=<label>] # token model
876 # [;objecttype=(public|private|cert|data)]
877 # [;passphrasedialog=(builtin|exec:<file>)]
878 #
879 # alternative:
880 # pkcs11:///path/to/pkcs11/lib?slot=0&id=123
881 # file:///path/to/pem/file
882 #
883 # SEE: http://blog.nominet.org.uk/tech/category/crypto/