Mail-DKIM2

 view release on metacpan or  search on metacpan

bin/dkim2-milter  view on Meta::CPAN

#!/usr/bin/perl
use 5.20.0;
use strict;
use warnings;
use Getopt::Long;
use Socket qw(AF_INET AF_INET6 AF_UNIX inet_pton inet_ntop sockaddr_family
              unpack_sockaddr_in unpack_sockaddr_in6);
use Pod::Usage;
use FindBin;
use lib -d "$FindBin::Bin/../lib/Mail/DKIM2" ? "$FindBin::Bin/../lib" : ();   # running from a checkout
use Sendmail::PMilter 1.28 ':all';   # 1.27 never answered MAIL FROM:<>

# Imported before _dkim2_info/_header_list_for_hash so the constants and
# should_skip are known at compile time. Spec version constants are the single
# source of truth in Mail::DKIM2::Common.
use Mail::DKIM2::Common qw(
    extract_mi_version
    strip_mi_versions
    parse_mime
    DKIM2_DRAFT
    DKIM2_REPO
    DKIM2_DATE
);
use Mail::DKIM2::Address qw(from_refusal_note);
use Mail::DKIM2::Canon qw(should_skip);
use Mail::DKIM2::Fold qw(fold_header);
use Mail::DKIM2::Key qw(parse_dkim_pubkey load_private_key);
use constant DKIM2_SOFTWARE => 'dkim2-milter';

# X-DKIM2-Info value per draft-gondwana-dkim2-debug-header-01: a tag-list in
# the DKIM2 syntax, every tag (the last included) followed by ";". A ";" has
# no escape and ends a tag, so one inside a value becomes ",".
sub _dkim2_info {
    my ($action, %extra) = @_;
    my @tags = ("draft=" . DKIM2_DRAFT, "repo=" . DKIM2_REPO,
                "date=" . DKIM2_DATE, "sw=" . DKIM2_SOFTWARE, "action=$action");
    push @tags, "$_=$extra{$_}" for grep { defined $extra{$_} } sort keys %extra;
    my $val = join ' ', map { (my $t = $_) =~ s/;/,/g; "$t;" } @tags;
    # Fold only after a ";" or a ","  (Section 5): never inside a token, so a
    # long hn= list breaks between names and a snaps= digest stays whole.
    # X-DKIM2-Info is excluded from the header hash by the x-* rule, so how it
    # is folded can never affect a signature.
    #
    # fold_header() budgets for the field name, so fold with it attached and
    # then strip it -- insheader() takes the value alone, in LF form for the
    # milter protocol.
    (my $folded = fold_header("X-DKIM2-Info: $val", undef, delimiters_only => 1))
        =~ s/^X-DKIM2-Info:\s*//;
    $folded =~ s/\r\n/\n/g;
    return $folded;
}

# Return (count, comma-separated-names) of headers that would be included
# in the header hash for the given Email::MIME message object.
sub _header_list_for_hash {
    my ($msg) = @_;
    my @fields;
    for my $header (sort { lc($a) cmp lc($b) } $msg->header_names) {
        next if should_skip($header);
        my @vals = $msg->header_raw($header);
        push @fields, (lc($header)) x scalar(@vals);
    }
    return (scalar(@fields), join(',', @fields));
}

use Mail::DKIM2::Signer;
use Mail::DKIM2::Verifier;
use Mail::DKIM2::Gate;
use Mail::DKIM2::Hop;
use Mail::DKIM2::MessageInstance;
use Mail::DKIM2::MessageStore;
use Mail::DKIM2::Wrap qw(wrap_single_part);
use Crypt::PRNG qw(random_bytes);
use Email::MIME;

# --- Command-line options ---

my %opts;
GetOptions(\%opts,
    'socket|s=s',
    'mode|m=s',
    'domain|d=s',
    'selector=s',
    'keyfile|k=s',
    'keydir=s',
    'parent-from=s@',
    'algorithm|a=s',

bin/dkim2-milter  view on Meta::CPAN

    'help|h',
) or pod2usage(2);

pod2usage(-exitval => 0, -verbose => 2, -noperldoc => 1) if $opts{help};

if (defined $opts{'max-recipe-literals'} && $opts{'max-recipe-literals'} < 0) {
    die "--max-recipe-literals must not be negative\n";
}
# Retired in 0.29 (-09 contract E2): this hop's own null body Recipe is
# always signed. Still accepted so an existing unit file starts.
warn "dkim2-milter: --allow-null-body-recipe is deprecated and does nothing: "
   . "an unsigned null body Recipe is always signed (Mail::DKIM2 0.29)\n"
    if $opts{'allow-null-body-recipe'};

$opts{socket}    //= 'unix:/var/run/dkim2-milter.sock';
$opts{algorithm} //= 'rsa-sha256';
$opts{mode}      //= 'both';
$opts{'authserv-id'} //= 'localhost';
die "--authserv-id must be a hostname-like token\n"
    unless $opts{'authserv-id'} =~ /\A[A-Za-z0-9][A-Za-z0-9.\-]*\z/;

unless ($opts{mode} =~ /^(inbound|outbound|both)$/) {
    die "Invalid --mode: must be inbound, outbound, or both\n";
}

die "--internal-hosts needs --mode both\n"
    if $opts{'internal-hosts'} && $opts{mode} ne 'both';

if ($opts{'wrap-single-part'}) {
    die "--wrap-single-part needs --mode inbound\n" unless $opts{mode} eq 'inbound';
    die "--wrap-single-part needs --snapshot-dir\n" unless $opts{'snapshot-dir'};
}

my $do_sign   = $opts{mode} eq 'outbound' || $opts{mode} eq 'both';
# -09 section 14.4: the envelope must match the top signature. Only in an
# inbound transaction: that is the one the message arrived in.
my $check_envelope = !$opts{'no-envelope-check'};

# --mode both: which clients send mail out through this host. Loopback (and
# a unix-socket client) always; --internal-hosts adds networks. A client
# that authenticated (SMTP AUTH) is outbound wherever it is.
my @internal_nets = map { _parse_cidr($_) } '127.0.0.0/8', '::1/128',
    map { split /[\s,]+/ } @{ $opts{'internal-hosts'} || [] };

# Determine if signing is possible
my $can_sign_single = $opts{domain} && $opts{selector} && $opts{keyfile};
my $can_sign_keydir = $opts{keydir} && -d $opts{keydir};
my $can_sign = $can_sign_single || $can_sign_keydir;

if ($do_sign && !$can_sign) {
    die "Signing (--mode $opts{mode}) requires --keydir OR (--domain, --selector, and --keyfile)\n";
}

if ($can_sign_single && $can_sign_keydir) {
    die "Cannot use both --keydir and --domain/--selector/--keyfile\n";
}

# Preload single-domain signing key
my $sign_key;
if ($can_sign_single) {
    $sign_key = load_private_key($opts{keyfile});
    warn "dkim2-milter: signing enabled for $opts{domain} "
       . "(selector=$opts{selector}, algorithm=$opts{algorithm})\n";
}

# Key cache for keydir mode: { domain => { selector, key, algorithm } }
my %keydir_cache;

if ($can_sign_keydir) {
    warn "dkim2-milter: signing enabled via keydir $opts{keydir}\n";
}
warn "dkim2-milter: mode=$opts{mode}\n";
warn "dkim2-milter: wrapping single-part posts\n" if $opts{'wrap-single-part'};

# Preload DNS overrides if specified
my $dns_data;
if ($opts{'dns-json'}) {
    require JSON;
    open my $fh, '<', $opts{'dns-json'}
        or die "Cannot read $opts{'dns-json'}: $!\n";
    local $/;
    $dns_data = JSON::decode_json(<$fh>);
    close $fh;
    warn "dkim2-milter: using DNS overrides from $opts{'dns-json'}\n";
}

# Snapshot store
my $snapshot_store;
if ($opts{'snapshot-dir'}) {
    $snapshot_store = Mail::DKIM2::MessageStore->new(
        directory => $opts{'snapshot-dir'},
    );
    warn "dkim2-milter: snapshots in $opts{'snapshot-dir'}\n";
}

# Options passed to MessageInstance->calculate() for diff-based MI
my %mi_opts;
if (defined $opts{'max-recipe-literals'}) {
    $mi_opts{MaxRecipeLiterals} = $opts{'max-recipe-literals'};
    warn "dkim2-milter: MI strategy: MaxRecipeLiterals=$opts{'max-recipe-literals'}\n";
}

# --- Key directory lookup ---

# The parent From domains a keydir domain may sign for (-09 contract E3.4):
# <keydir>/<domain>/parent-from, one domain per line, "#" comments. None
# when the file is absent.
sub _read_parent_from {
    my ($file) = @_;
    open my $fh, '<', $file or return [];
    my @d = map { s/#.*//r =~ s/\A\s+|\s+\z//gr } <$fh>;
    close $fh;
    return [ grep { length } @d ];
}

# Look up signing config for a domain from the keydir.
# Tries exact domain first, then walks up parent domains.
# Returns { domain, selector, key, algorithm } or undef.
sub _keydir_lookup {
    my ($domain) = @_;
    $domain = lc($domain);

    # Check cache
    return $keydir_cache{$domain} if exists $keydir_cache{$domain};

    my $try = $domain;
    while ($try) {
        my $dir = "$opts{keydir}/$try";
        # A directory we cannot read is treated like one that is not there,
        # and the walk-up below still runs: `next` here would never advance
        # $try and the milter would spin forever on a permissions mistake.
        if (-d $dir && opendir(my $dh, $dir)) {
            # Find the newest .key file (by ctime)
            my @keys = map { $_->[0] }
                       sort { $b->[1] <=> $a->[1] }
                       map { [$_, (stat("$dir/$_"))[10] || 0] }
                       grep { /\.key$/ } readdir $dh;
            closedir $dh;

            if (@keys) {
                my $file = $keys[0];
                (my $selector = $file) =~ s/\.key$//;
                my $key = eval { load_private_key("$dir/$file") };
                if ($key) {
                    # Detect algorithm from key type
                    my $alg = ref($key) =~ /Ed25519/
                        ? 'ed25519-sha256' : 'rsa-sha256';
                    my $config = {
                        domain    => $try,
                        selector  => $selector,
                        key       => $key,
                        algorithm => $alg,
                        parent_from => _read_parent_from("$dir/parent-from"),
                    };
                    # Cache for both the looked-up domain and the matched domain
                    $keydir_cache{$domain} = $config;
                    $keydir_cache{$try} = $config if $try ne $domain;
                    return $config;
                }
            }
        } elsif (-d $dir) {
            warn "dkim2-milter: key directory $dir is not readable: $!\n";
        }
        # Walk up: sub.example.com -> example.com -> (stop)
        $try =~ s/^[^.]+\.// or last;
    }

    # Cache the miss too
    $keydir_cache{$domain} = undef;
    return undef;
}

# --- Milter setup ---

my $milter = Sendmail::PMilter->new();
$milter->setconn($opts{socket});

# Insert, change and delete headers; replace the body (--wrap-single-part).
$milter->register('dkim2-milter', {
    connect => \&cb_connect,
    envfrom => \&cb_envfrom,
    envrcpt => \&cb_envrcpt,
    header  => \&cb_header,
    eoh     => \&cb_eoh,
    body    => \&cb_body,
    eom     => \&cb_eom,
    close   => \&cb_close,
}, SMFIF_ADDHDRS | SMFIF_CHGHDRS | SMFIF_CHGBODY);

warn "dkim2-milter: listening on $opts{socket}\n";
$milter->main();

# --- Milter callbacks ---

# The client's address, kept for the whole connection: see cb_envfrom.
sub cb_connect {
    my ($ctx, $host, $sockaddr) = @_;
    $ctx->setpriv({ client => _client_addr($sockaddr) });
    return SMFIS_CONTINUE;
}

sub cb_envfrom {
    my ($ctx, $from) = @_;



( run in 1.156 second using v1.01-cache-2.11-cpan-8379b9b8ec2 )