Mail-DKIM2

 view release on metacpan or  search on metacpan

lib/Mail/DKIM2/Signer.pm  view on Meta::CPAN

package Mail::DKIM2::Signer;
use strict;
use warnings;

our $VERSION = '0.36';

use base 'Mail::DKIM2::HeaderParser';
use MIME::Base64 qw(encode_base64);
use Carp;
use Scalar::Util ();

use Mail::DKIM2::Address ();
use Mail::DKIM2::Common qw(chain_length_error);
use Mail::DKIM2::Canon qw(build_signing_input);
use Mail::DKIM2::Key qw(load_private_key signature_algorithm signature_algorithm_for_key);
use Mail::DKIM2::Chain;
use Mail::DKIM2::Signature;
use Mail::DKIM2::MessageInstance;
use Mail::DKIM2::HeaderPlan;

sub known_options {
    return qw(Domain Selector KeyFile Key Algorithm MailFrom RcptTo
              Nonce Flags Exploded Timestamp NextDomain ParentFromCallback
              PolicyCallback Resolver);
}

sub init {
    my $self = shift;
    $self->SUPER::init;
    croak "Domain required" unless $self->{Domain};
    croak "Selector required" unless $self->{Selector};
    croak "KeyFile or Key required" unless $self->{KeyFile} || $self->{Key};

    if ($self->{KeyFile} && !$self->{Key}) {
        $self->{Key} = load_private_key($self->{KeyFile});
    }

    # The algorithm is the key's unless the caller names one; a name this
    # library does not implement, or one the key cannot sign with, is a
    # mistake in the call -- never a signature labelled as something it is
    # not, or an exception from inside CLOSE.
    $self->{Algorithm} ||= signature_algorithm_for_key($self->{Key}) || 'rsa-sha256';
    my $alg = signature_algorithm($self->{Algorithm})
        or croak "unsupported Algorithm $self->{Algorithm}";
    croak "Algorithm $self->{Algorithm} needs a $alg->{key_class} key"
        unless Scalar::Util::blessed($self->{Key}) && $self->{Key}->isa($alg->{key_class});
    $self->{_alg} = $alg;
    $self->{_chain} = Mail::DKIM2::Chain->new;
}

sub handle_header {
    my ($self, $field_name, $contents, $line) = @_;
    $self->{_chain}->add_field($field_name, $contents, $line);
}

# The message's Message-Instance and DKIM2-Signature fields, numbered
# (Mail::DKIM2::Chain). Complete once the header block has been read.
sub chain { return $_[0]->{_chain} }

sub finish_header {
    my $self = shift;

    my $chain  = $self->{_chain};
    my $next_i = ($chain->top_signature_number // 0) + 1;

    # A chain no verifier can number is a PERMERROR to all of them, and so
    # is one a signature would take past the limit: do not sign over it.
    # Whether the chain is otherwise worth extending -- its signatures, its
    # instances against the content -- is Mail::DKIM2::Gate's to decide.
    # A line that is not a field is in no header hash (HeaderParser).
    my $error = ($self->malformed_header ? 'malformed header field' : undef)
        // $chain->numbering_error
        // chain_length_error({ 'dkim2-signature' => $next_i });
    # A signature names the Message-Instance it covers in m=, and a verifier
    # rejects one that names none (tag=m missing), so a message with no
    # instance cannot be signed: compute one first (dkim2sign does).
    $error //= 'no Message-Instance field to sign over' unless $chain->instance_numbers;
    # -09 section 3.2: a Signer MUST use an RSA key of at least 1024 bits,
    # and every verifier calls a shorter one "too short".
    if (my $min = $self->{_alg}{min_bits}) {
        $error //= "signing key is shorter than $min bits"
            if $self->{Key}->size * 8 < $min;
    }
    # -09 sections 11 and 12.4: a hop that originates the message, or whose
    # instances changed From, signs with a d= the From is Authentic for.
    # -09 contract E3.4: d= may also be below the From domain when the
    # caller says this d= may sign for it (ParentFromCallback), or, as an
    # explicit opt-in, when that domain's Domain Policy Record allows it.
    # Without either the upward case is refused: no live DNS by default.
    if (!$error && $self->_from_must_match) {
        my $e = Mail::DKIM2::Address::from_pair_error($self->{Domain},
            sub { $self->_parent_policy(@_) },
            map { $_->[1] } grep { lc $_->[0] eq 'from' }
            @{ Mail::DKIM2::HeaderPlan::fields($self->{headers}) });
        $error = "From header field is not Authentic for d=$self->{Domain}" if $e;

lib/Mail/DKIM2/Signer.pm  view on Meta::CPAN

        RcptTo   => ['<recipient@example.net>'],
    );

    # One shot ...
    $signer->load($message);
    # ... or streaming, with CRLF line endings
    $signer->PRINT($chunk) for @chunks;
    $signer->CLOSE;

    die $signer->result_detail unless $signer->result eq 'signed';
    my $header = $signer->as_string;    # "DKIM2-Signature: i=1; ..." (folded)

    # The same message to several envelope recipients: one pass, one cheap
    # signature per recipient.
    for my $rcpt (@rcpts) {
        my $header = $signer->sign_for_recipient($rcpt);
    }

=head1 DESCRIPTION

Adds a DKIM2-Signature header for this hop. The message must already carry
the Message-Instance header this hop wants to sign over (see
L<Mail::DKIM2::MessageInstance>; a message with none is a C<fail>); the
Signer reads the existing
Message-Instance and DKIM2-Signature headers, chooses the next C<i=>, builds
the signing input of -09 section 12.8, and signs it. It does not alter
the message: the caller prepends the header C<as_string> returns.

Nothing it signs is in the body (section 12.8), so the body is discarded as
it arrives, and a caller holding the message in a file may feed it the
header block alone.

Extends L<Mail::DKIM2::HeaderParser>, which provides C<PRINT>, C<CLOSE>,
C<load> and the tie interface.

This module implements draft-ietf-dkim-dkim2-spec-09; see L<Mail::DKIM2/STATUS>
for what that means for the wire format and the API, and
L<Mail::DKIM2/CONVENTIONS> for the option, input and error conventions every
module here follows.

=head1 CONSTRUCTOR

=head2 new(%options)

Required:

=over 4

=item Domain

The signing domain, the C<d=> tag.

=item Selector

The selector of the key, published at C<< <Selector>._domainkey.<Domain> >>.

=item Key or KeyFile

The private key as a L<Crypt::PK::RSA> or L<Crypt::PK::Ed25519> object, or
the path of a PEM file holding one (loaded with
L<Mail::DKIM2::Key/load_private_key>).

=back

Optional:

=over 4

=item Algorithm

C<rsa-sha256> or C<ed25519-sha256>. Defaults to the one the key signs with
(since 0.31; before, to C<rsa-sha256> whatever the key). Any other name, or
one that is not the key's, croaks.

=item MailFrom

The envelope sender of this hop, recorded in C<mf=>. Bare addresses are
bracketed; C<< '<>' >> or undef records the null sender.

=item RcptTo

An arrayref of this hop's envelope recipients, recorded in C<rt=>.

=item NextDomain

The C<d=> of the hop that will sign next, recorded in C<nd=> for an
imaginary forwarding hop (-09 section 12.3). Excludes C<MailFrom> and
C<RcptTo>.

=item Timestamp

The C<t=> value; defaults to now. Fix it for reproducible test output.

=item Nonce

The C<n=> value, at most 64 characters.

=item Flags

An arrayref of C<f=> flags, such as C<feedback>. An C<exploded> among
them is a request for the flag, as C<Exploded> is.

=item Exploded

True when this hop sends the message to more than one address, as a list
manager does (-09 section 12.5). The signature then carries the
C<exploded> flag, which it also gets whenever C<rt=> holds more than one
address. Never at C<i=1>: there the flag, requested this way or in
C<Flags>, is dropped.

=item ParentFromCallback

Whether this C<Domain> may make a From in a parent domain Authentic (-09
sections 7.1 item 4 and 11.1, contract E3.4; new in 0.29). Called as
C<< ($from_domain, $signer) >>, with the From domain as a lowercased
A-label, only when a hop that must make From Authentic signs with a C<d=>
below the From domain; true signs, false refuses. Answer it from
configuration or a database: the operator knows its own domains' policy, so
the Signer makes no DNS lookup for this unless asked to (below). Without
this option, C<PolicyCallback> or C<Resolver>, such a message is refused.



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