Mail-DKIM2

 view release on metacpan or  search on metacpan

lib/Mail/Milter/Authentication/Handler/DKIM2Sign.pm  view on Meta::CPAN

package Mail::Milter::Authentication::Handler::DKIM2Sign;
use 5.20.0;
use strict;
use warnings;
use Mail::Milter::Authentication::Pragmas;
# ABSTRACT: Handler class for DKIM2 signing
our $VERSION = '0.36';
use base 'Mail::Milter::Authentication::Handler';

use Mail::DKIM2::Common qw(extract_mi_version parse_mime DKIM2_DRAFT DKIM2_REPO DKIM2_DATE);
use Mail::DKIM2::Address qw(from_refusal_note);
use Mail::DKIM2::Fold qw(fold_header);
use Mail::DKIM2::Key qw(load_private_key parse_dkim_pubkey);
use Mail::DKIM2::Gate;
use Mail::DKIM2::Hop;
use Mail::DKIM2::MessageInstance;
use Mail::DKIM2::MessageStore;
use Mail::DKIM2::Signer;
use Email::MIME;
use MIME::Base64 qw(decode_base64);
use constant DKIM2_SOFTWARE => 'authentication_milter-DKIM2Sign';

sub default_config {
    return {
        # Static domain config: domain => { selector, keyfile,
        # parent_from_domains (optional, -09 contract E3.4) }
        'domains'              => {},
        # HTTP endpoint for dynamic key lookup: GET {url}?domain=X
        # Expected response: {"selector":"sel1","key":"base64_pem_data"}
        # or: {"selector":"sel1","keyfile":"/path/to/key.pem"}
        'key_endpoint'         => undef,
        'key_endpoint_timeout' => 5,
        # Only sign for authenticated/local senders
        'sign_authenticated'   => 1,
        'sign_local'           => 1,
        # Add Message-Instance headers
        'add_message_instance' => 1,
        # SMTP params to record in the signature
        'record_smtp_params'   => 1,
        # Directory for message snapshots (shared with DKIM2Verify)
        'snapshot_directory'   => undef,
        # Body Recipe literal-line cap for a snapshot diff; over it the
        # body Recipe is null (MessageInstance MaxRecipeLiterals)
        'max_recipe_literals'  => 1000,
        'ignore_header_prefixes' => [],   # our own fields, hashed by neither end (IgnorePrefixes)
        # Deprecated (0.29): this hop's own null body Recipe is always
        # signed; accepted, warned about, ignored
        'allow_null_body_recipe' => undef,
        # Testing only: verify the upstream chain with keys from this dns.json
        # instead of DNS, and without the t=/expiry check
        'dns_overrides'        => undef,
        'skip_timestamp_check' => 0,
    };
}

# The handler's configuration with default_config() filled in for every
# option the operator left out (or set to null). authentication_milter does
# not merge default_config() at runtime -- it only uses it to generate a
# sample config -- so without this a left-out option is undef: sign_local,
# sign_authenticated, add_message_instance and record_smtp_params would all
# silently be off.
sub _config {
    my ($self) = @_;
    my $given    = $self->handler_config() || {};
    my $defaults = default_config();
    return { %$given, map { $_ => $given->{$_} // $defaults->{$_} } keys %$defaults };
}

sub register_metrics {
    return {
        'dkim2_sign_total' => 'The number of emails signed with DKIM2',
    };
}

lib/Mail/Milter/Authentication/Handler/DKIM2Sign.pm  view on Meta::CPAN

    $self->change_header( 'X-DKIM2-Snapshot', $_, q{} ) for reverse 1 .. @tokens;
    $self->{'_snapshot_token'} = ( @tokens == 1 && $tokens[0] =~ /\A[0-9a-f]{32}\z/ ) ? $tokens[0] : undef;

    # X-DKIM2-Exploded: a list manager on this host (Mailman, Sympa) marks
    # each distribution copy, asking for the -08 "exploded" flag (section
    # 12.5). Its presence, whatever the value, is the request. It never
    # leaves either.
    my $exploded = grep { /\AX-DKIM2-Exploded[ \t]*:/i } @{ $self->{'headers'} || [] };
    $self->change_header( 'X-DKIM2-Exploded', $_, q{} ) for reverse 1 .. $exploded;
    # A List-Id says the same without being asked (a list manager that adds
    # no hint, such as stock Mailman): a list sent this copy, to more than
    # one address. The Signer drops the flag from a first signature.
    $exploded ||= grep { /\AList-Id[ \t]*:/i } @{ $self->{'headers'} || [] };

    # Determine if we should sign this message
    my $should_sign = 0;
    if ( $config->{'sign_authenticated'} && $self->is_authenticated() ) {
        $should_sign = 1;
    }
    if ( $config->{'sign_local'} && $self->is_local_ip_address() ) {
        $should_sign = 1;
    }
    return unless $should_sign;

    # Determine the signing domain from the envelope sender.
    my $env_from = $self->{'env_from'} || '';
    $env_from =~ s/^<//;
    $env_from =~ s/>$//;
    my $sign_domain;
    if ( $env_from =~ /\@(.+)$/ ) {
        $sign_domain = lc $1;
    }
    # Null sender (MAIL FROM <>) — e.g. a Postfix-generated bounce/DSN. There is
    # no envelope domain to sign for, so fall back to the From: header domain
    # (typically MAILER-DAEMON@<host>). We only sign if it resolves to a key,
    # i.e. it is genuinely one of our own bounces.
    if ( !$sign_domain && $env_from eq '' ) {
        $sign_domain = $self->_from_header_domain();
    }
    return unless $sign_domain;

    # Look up signing config for this domain
    my $sign_config = $self->_get_sign_config($sign_domain);
    unless ($sign_config) {
        $self->dbgout( 'DKIM2Sign', "No signing config for $sign_domain", LOG_DEBUG );
        $self->_remove_unsigned_instances($handler);
        return;
    }

    eval {
        my $selector = $sign_config->{selector};
        my $key;
        if ( $sign_config->{key} ) {
            # Inline PEM key data (may be base64-encoded)
            my $pem = $sign_config->{key};
            $pem = decode_base64($pem) unless $pem =~ /^-----/;
            require Crypt::PK::RSA;
            $key = Crypt::PK::RSA->new(\$pem);
        }
        elsif ( $sign_config->{keyfile} ) {
            $key = load_private_key($sign_config->{keyfile});
        }
        else {
            die "No key or keyfile in signing config for $sign_domain";
        }

        # Build the full message (pre_headers + original headers + add_headers + body)
        my $EOL = "\015\012";
        my $message_data = '';

        # pre_headers from handler (reversed as they prepend in reverse)
        foreach my $h (reverse @{$handler->{pre_headers} || []}) {
            $message_data .= _fmtheader($h);
        }

        # Original headers (less X-DKIM2-Snapshot and X-DKIM2-Exploded,
        # removed above)
        foreach my $chunk (grep { !/\AX-DKIM2-(?:Snapshot|Exploded)[ \t]*:/i } @{$self->{'headers'} || []}) {
            $message_data .= $chunk;
        }

        # post-headers from handler
        foreach my $h (@{$handler->{add_headers} || []}) {
            $message_data .= _fmtheader($h);
        }

        # End of headers + body
        $message_data .= $EOL;
        foreach my $chunk (@{$self->{'body'}}) {
            $message_data .= $chunk;
        }

        # Compute Message-Instance if configured.  Nothing reaches the wire
        # until the gate below has passed and the signer has signed: a
        # refused message goes out as it came in (apart from X-DKIM2-Info),
        # as with bin/dkim2-milter.
        my @mi_removals;
        my $mi_value;
        if ( $config->{'add_message_instance'} ) {
            delete $self->{'_stripped_mi_versions'};
            delete $self->{'_clean_message_data'};
            delete $self->{'_restarted_mi'};
            my $mi = $self->_compute_message_instance($message_data, $config);
            if ( $self->{'_stripped_mi_versions'} ) {
                # Broken intermediate MIs were stripped; use the cleaned message data
                $message_data = $self->{'_clean_message_data'} // $message_data;
                # Record the stripped versions so the wire message can be
                # cleaned up once we have signed
                @mi_removals = @{$self->{'_stripped_mi_versions'}};
                delete $self->{'_stripped_mi_versions'};
                delete $self->{'_clean_message_data'};
            }
            if ($mi) {
                $mi_value = $mi->as_header_value;
                # Prepend MI header (will be included when we re-feed the signer)
                $message_data = "Message-Instance: $mi_value$EOL" . $message_data;
            }
        }

        # Build SMTP params
        my %signer_args = (



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