view release on metacpan or search on metacpan
you want to pass a false value in an input that accepts a boolean
value, use 0 for false.
The constructor checks the options, including that certificates and
keys can be read and loaded, and that signer is a code reference, so
problems are reported by it and not by the first signature; it does not
check that a certificate is otherwise valid, nor that a key matches it.
credentials and x509 are copied (shallowly), so changing your own hash
afterwards has no effect, but the accessors give back the copies held
by the object: leave them alone. Mind that ->credentials includes the
secret access key. private_key and private_key_password are dropped
from the copy of x509 as soon as the key is loaded, so ->x509 does not
have them. Subclasses and roles work as usual.
The two variants are implemented by two internal classes, one per
option, that this class uses on your behalf:
AWS::Signature::V4::Credentials and AWS::Signature::V4::X509. They are
documented for the record, but you do not need to know about them.
credentials
the serial number of the certificate, in decimal. It is taken from
the certificate if not provided;
private_key_file, private_key
the private key, either as the path of a file or as its content, in
PEM or DER format (as understood by CryptX). private_key wins if
both are given;
private_key_password
only for encrypted keys. Like private_key, it is not kept once the
key is loaded;
signer
alternative to the keys: a function that gets the bytes to sign and
returns the signature of their SHA-256, as raw bytes: PKCS#1 v1.5
for RSA and DER for ECDSA (e.g. to delegate to an HSM or a KMS).
Decode it first if your HSM or KMS gives it in base64 or hex: the
ERRORS
Errors are reported by throwing Ouch exceptions (see $@->code,
$@->message). The code is 400 when the problem is in what the caller
provided, e.g. a missing option, an invalid URL, a certificate that
cannot be read, a chunk that goes past the declared size; it is 500
when the fault is in the module itself, i.e. something that should not
happen whatever the input. The exception is reported at the line of the
caller, and its trace does not include the arguments of the calls, as
they may hold secrets like passwords. Moo's own complaints, e.g. about
the arguments of the constructors that are not meant to be called
directly, are not Ouch exceptions.
SECURITY CONSIDERATIONS
* URLs. A URL must be ASCII, without control characters and without
user information (user@host): AWS endpoints never have it, and user
agents do not all agree on which host such a URL points to. For the
same reason the host can only be a name made of letters, digits, .,
_, ~ and -, or an IP address, with an optional numeric port.
ordinary characters of the key and /public/%2e%2e/admin is signed as
it is.
* Do not log the results. headers and authorization can be used to
replay the request for up to 15 minutes; a presigned URL is a bearer
token until it expires; headers, canonical_request and presigned URLs
include the session token, if there is one. Treat them as secrets.
* Secrets in memory. The signer keeps the credentials (the secret
access key included) as long as it lives, and ->credentials gives
them back. The text of an X.509 private key and its password are
dropped once the key is loaded. The key derived for signed chunks,
which could sign any request for the same service, region and day, is
kept by the chunker in a closure: no accessor gives back its bytes
and dumping the chunker does not show them, but whoever holds the
chunker can still sign with it through its internals. Do not hand the
chunker, let alone the signer, to code that you would not trust with
the credentials.
* Error messages may include values that the caller provided, with
non-printable characters escaped (e.g. \x{A}), so that they cannot
eg/07-rolesanywhere-x509.pl view on Meta::CPAN
unless $region =~ m{\A[a-z0-9-]+\z};
my $signer = AWS::Signature::V4->new(
service => 'rolesanywhere',
region => $region,
x509 => {
key_type => $ENV{KEY_TYPE} // 'RSA',
certificate_file => $ENV{CERT_FILE} // die("CERT_FILE?\n"),
private_key_file => $ENV{KEY_FILE} // die("KEY_FILE?\n"),
(defined $ENV{CHAIN_FILE} ? (chain_files => $ENV{CHAIN_FILE}) : ()),
(defined $ENV{KEY_PASSWORD} ? (private_key_password => $ENV{KEY_PASSWORD}) : ()),
},
);
say {*STDERR} 'algorithm: ', $signer->algorithm;
# the ARNs are required; only a dry run, which sends nothing, makes do
# with a placeholder just to show the shape of the request
sub arn {
my ($name, $placeholder) = @_;
return $ENV{$name} if defined $ENV{$name} && length $ENV{$name};
die "$name?\n" unless $ENV{DRY_RUN};
lib/AWS/Signature/V4.pm view on Meta::CPAN
# Certificate-based variant, as used by IAM Roles Anywhere.
# certificate / certificate_file: PEM or DER text, or path of a file with it
# chain / chain_files: optional arrayref of PEM/DER intermediate certificates,
# or of paths of files with them; a PEM item can be a bundle.
# chain can also be a plain string: a PEM-encoded bundle, and
# chain_files a plain string: the path of one file
# key_type: 'RSA' or 'ECDSA'
# signer: sub ($bytes_to_sign) -> signature (DER for ECDSA, PKCS#1 v1.5
# for RSA), computed with SHA-256; or, alternatively,
# private_key_file / private_key: PEM or DER key (path or content), signed
# with CryptX; private_key_password if it is encrypted
has x509 => (is => 'ro', coerce => \&_copy, isa => sub { _hash_or_undef(x509 => @_) });
# S3 is the odd one out: this is the only place that knows how to tell. S3
# Object Lambda, S3 on Outposts and S3 Express sign with names of their own,
# under the same rules.
has _is_s3 => (is => 'lazy', init_arg => undef);
sub _build__is_s3 ($self) { $self->service =~ m{\As3(?:-object-lambda|-outposts|express)?\z} }
has double_encode => (is => 'ro', lazy => 1, default => sub ($self) { !$self->_is_s3 });
has normalize_path => (is => 'ro', lazy => 1, default => sub ($self) { !$self->_is_s3 });
lib/AWS/Signature/V4.pm view on Meta::CPAN
my $credentials_params = $self->credentials;
fail 400, 'provide either "credentials" or "x509", not both'
if $credentials_params && $x509_params;
fail 400, 'provide (exactly) one of "credentials" or "x509"'
unless $credentials_params || $x509_params;
$self->_auth; # force building and fail fast
# after using the parameters, we get rid of sensitive data in the input
# hash for X509
delete($x509_params->{$_}) for qw< private_key private_key_password >;
return;
}
sub _build__auth ($self) {
return $self->credentials
? AWS::Signature::V4::Credentials->new($self->credentials->%*)
: AWS::Signature::V4::X509->new($self->x509->%*);
}
lib/AWS/Signature/V4.pod view on Meta::CPAN
use C<0> for I<false>.
The constructor checks the options, including that certificates and keys
can be read and loaded, and that C<signer> is a code reference, so
problems are reported by it and not by the first signature; it does not
check that a certificate is otherwise valid, nor that a key matches it.
C<credentials> and C<x509> are copied (shallowly), so changing your own
hash afterwards has no effect, but the accessors give back the copies
held by the object: leave them alone. Mind that C<< ->credentials >>
includes the secret access key. C<private_key> and
C<private_key_password> are dropped from the copy of C<x509> as soon as
the key is loaded, so C<< ->x509 >> does not have them. Subclasses and
roles work as usual.
The two variants are implemented by two internal classes, one per
option, that this class uses on your behalf:
L<AWS::Signature::V4::Credentials> and L<AWS::Signature::V4::X509>. They
are documented for the record, but you do not need to know about them.
=over
lib/AWS/Signature/V4.pod view on Meta::CPAN
the serial number of the certificate, in decimal. It is taken from the
certificate if not provided;
=item C<private_key_file>, C<private_key>
the private key, either as the path of a file or as its content, in PEM
or DER format (as understood by L<CryptX>). C<private_key> wins if both
are given;
=item C<private_key_password>
only for encrypted keys. Like C<private_key>, it is not kept once the key
is loaded;
=item C<signer>
alternative to the keys: a function that gets the bytes to sign and
returns the signature of their SHA-256, as raw bytes: PKCS#1 v1.5 for
RSA and DER for ECDSA (e.g. to delegate to an HSM or a KMS). Decode it
first if your HSM or KMS gives it in base64 or hex: the returned bytes are
lib/AWS/Signature/V4.pod view on Meta::CPAN
=head1 ERRORS
Errors are reported by throwing L<Ouch> exceptions (see C<< $@->code >>,
C<< $@->message >>). The code is C<400> when the problem is in what the
caller provided, e.g. a missing option, an invalid URL, a certificate that
cannot be read, a chunk that goes past the declared size; it is C<500>
when the fault is in the module itself, i.e. something that should not
happen whatever the input. The exception is reported at the line of the
caller, and its C<trace> does not include the arguments of the calls, as
they may hold secrets like passwords. Moo's own complaints, e.g. about the
arguments of the constructors that are not meant to be called directly,
are not Ouch exceptions.
=head1 SECURITY CONSIDERATIONS
=over
=item *
lib/AWS/Signature/V4.pod view on Meta::CPAN
B<Do not log the results.> C<headers> and C<authorization> can be used to
replay the request for up to 15 minutes; a presigned URL is a bearer token
until it expires; C<headers>, C<canonical_request> and presigned URLs
include the session token, if there is one. Treat them as secrets.
=item *
B<Secrets in memory.> The signer keeps the credentials (the secret access
key included) as long as it lives, and C<< ->credentials >> gives them
back. The text of an X.509 private key and its password are dropped once
the key is loaded. The key derived for signed chunks, which could sign
any request for the same service, region and day, is kept by the chunker
in a closure: no accessor gives back its bytes and dumping the chunker
does not show them, but whoever holds the chunker can still sign with it
through its internals. Do not hand the chunker, let alone the signer, to
code that you would not trust with the credentials.
=item *
B<Error messages> may include values that the caller provided, with
lib/AWS/Signature/V4/Error.pod view on Meta::CPAN
=head1 DESCRIPTION
B<This module is internal: you are not supposed to use it.> It is what the
modules of the distribution use to throw L<Ouch> exceptions, see
L<AWS::Signature::V4/ERRORS> for what the callers can expect.
It exists to do two things that a bare C<ouch> would not do: report the
error at the line of the caller, like C<croak>, and keep the arguments of
the calls out of the backtrace kept by the exception, because they can
include secrets like passwords and tokens.
=head1 INTERFACE
=head2 fail
fail $code, $message;
fail $code, $message, $data;
Throw an L<Ouch> exception. All arguments go to C<ouch> as they are.
lib/AWS/Signature/V4/X509.pm view on Meta::CPAN
my (undef, $cs) = _tlv($der, 0);
my (undef, $ts) = _tlv($der, $cs);
my ($tag, $s, $e) = _tlv($der, $ts);
($tag, $s, $e) = _tlv($der, $e) if $tag == 0xA0; # skip explicit version
fail 400, 'cannot find certificate serial number' unless $tag == 0x02;
return Math::BigInt->from_hex(unpack 'H*', substr $der, $s, $e - $s)
->bstr; # DER integers here are positive; leading 0x00 is harmless
}
# The error of CryptX, without the location and the backtrace that Carp adds
# when verbose (the arguments in it may hold the password), escaped as caller
# input because it can hold the file name.
sub _clean_error ($e) {
$e =~ s{\n\t.*}{}s; # the backtrace lines start with a tab
$e =~ s{\s+at \S+ line \d+\.?\s*\z}{};
return shown($e =~ s{\A\s+|\s+\z}{}gr);
}
# $key is a file name or a scalar reference to the PEM text
sub _cryptx_signer ($algo, $key, $password = undef) {
my $class = $algo eq 'RSA' ? 'Crypt::PK::RSA' : 'Crypt::PK::ECC';
eval "require $class; 1" or fail 500, "cannot load $class";
my @args = ($key, defined $password ? ($password) : ());
my $pk = eval {
# no backtrace, e.g. from -MCarp=verbose or Carp::Always, with the password
local $Carp::Verbose = 0;
local $Carp::MaxArgNums = -1;
local $SIG{__DIE__};
$class->new(@args);
} // fail 400, "cannot load the private key: " . _clean_error($@);
fail 400, 'the key is not a private key' unless $pk->is_private;
return $algo eq 'RSA'
? sub ($bytes) { $pk->sign_message($bytes, 'SHA256', 'v1.5') }
: sub ($bytes) { $pk->sign_message($bytes, 'SHA256') };
}
lib/AWS/Signature/V4/X509.pm view on Meta::CPAN
# only the first certificate of a PEM bundle is used
# chain / chain_files: optional arrayref of PEM/DER intermediate certificates,
# or of paths of files with them; a PEM item can be a bundle.
# chain can also be a plain string: a PEM-encoded bundle, and
# chain_files a plain string: the path of one file
# key_type: 'RSA' or 'ECDSA'
# serial: the serial number of the certificate, if it cannot be found
# signer: sub ($bytes_to_sign) -> raw signature bytes (DER for ECDSA,
# PKCS#1 v1.5 for RSA), computed with SHA-256; or, alternatively,
# private_key_file / private_key: PEM or DER key (path or content, the
# content wins), signed with CryptX; private_key_password if it
# is encrypted
has [qw<
key_type certificate certificate_file chain chain_files serial signer
private_key_file
>] => (is => 'ro');
# the key text and its password are secrets, only needed to load the key:
# no public accessor, and they are dropped as soon as the key is loaded
has $_ => (is => 'ro', reader => "_$_", clearer => "_clear_$_")
for qw< private_key private_key_password >;
# Derived from the options above. Lazy, so that each builder can use the
# others without depending on the order in which the constructor sets things
# up; BUILD forces them all, so that a bad certificate, chain or key is
# reported by new() and not by the first signature.
#
# **NOTE**: to add one, add its name here and write its builder.
my @DERIVED = qw< algorithm credential_id _chain _der _signer _type >;
has $_ => (is => 'lazy', init_arg => undef) for @DERIVED;
sub BUILD ($self, $args) {
my %known = map { $_ => 1 } qw<
key_type certificate certificate_file chain chain_files serial signer
private_key_file private_key private_key_password
>;
if (my ($name) = sort(grep { !$known{$_} } keys $args->%*)) {
fail 400, 'unknown option "' . shown($name) . '" in x509';
}
for my $name (@DERIVED) { # not "for (...)": builders may use $_
$self->$name;
}
# we don't need private key material past this point, so we get rid
# of it immediately. Of course it may still linger in memory depending
# on garbage collection.
$self->_clear_private_key;
$self->_clear_private_key_password;
return;
}
sub _build__type ($self) {
my $type = uc($self->key_type // fail 400, 'missing x509/key_type');
fail 400, 'x509/key_type must be RSA or ECDSA, got ' . shown($type)
unless $type eq 'RSA' || $type eq 'ECDSA';
return $type;
}
lib/AWS/Signature/V4/X509.pm view on Meta::CPAN
return $self->serial // _certificate_serial($self->_der);
}
sub _build__signer ($self) {
my $type = $self->_type;
my $signer = $self->signer;
fail 400, '"signer" must be a code reference'
if defined $signer && ref $signer ne 'CODE';
if (!$signer && defined $self->_private_key) { # the content wins, as for certificate
my $key = $self->_private_key; # CryptX wants a reference for a PEM/DER text
$signer = _cryptx_signer($type, \$key, $self->_private_key_password);
}
elsif (!$signer && defined $self->private_key_file) {
$signer = _cryptx_signer($type, $self->private_key_file, $self->_private_key_password);
}
return $signer
// fail 400, 'x509 needs one of "signer", "private_key_file", "private_key"';
}
# ---- what AWS::Signature::V4 wants from a variant --------------------------
# hex signature of the string to sign; the scope is not used here
sub signature ($self, $scope, $string_to_sign) {
my $sig = $self->_signer->($string_to_sign);
lib/AWS/Signature/V4/X509.pod view on Meta::CPAN
certificate, as required by IAM Roles Anywhere
(C<AWS4-X509-RSA-SHA256> or C<AWS4-X509-ECDSA-SHA256>): the signature is
made with the private key of the certificate, and the certificate, and
its chain, travel with the request.
B<You are not supposed to use this module directly.>
L<AWS::Signature::V4> creates an object when it is given the C<x509>
option, using the same keys, and calls the methods below. All the options
(C<key_type>, C<certificate>, C<certificate_file>, C<chain>,
C<chain_files>, C<serial>, C<signer>, C<private_key_file>, C<private_key>
and C<private_key_password>) are described in L<AWS::Signature::V4/new>;
each one but C<private_key> and C<private_key_password> (see below) is
available as a read-only accessor. C<key_type> is the type of
the key, C<RSA> or C<ECDSA>, and it is what makes the L</algorithm> the
name AWS knows. The class is documented for those who work on the
distribution, not as a public interface.
The constructor loads and checks everything: it reads the files, decodes
the certificates (PEM or DER) and finds the serial number, and loads the
key with L<CryptX> unless a C<signer> is provided. Any problem is reported
by an L<Ouch> exception with code C<400>, so it is seen when the signer is
created and not when the first request is signed. It does not check that
the certificate is valid otherwise, or that the key matches it: only
that each certificate is a DER SEQUENCE (definite, minimal lengths) that
fills its data exactly. The error of L<CryptX> about the key goes in the
message without its location or backtrace, which may hold the password,
and escaped, as it may hold the file name.
C<private_key> and C<private_key_password> have no public accessor and are
dropped as soon as the key is loaded, so that the object does not keep
them around.
=head1 THE INTERFACE OF A VARIANT
L<AWS::Signature::V4> talks to the variant in use, this class or its
sibling, through the same few methods, so that it does not need to know
which one it is dealing with. The scope is what appears in the
C<Credential> and in the string to sign, like
ok $verifies->($tk->{string_to_sign}, $tk->{signature}),
"$alg private_key wins over private_key_file";
system("openssl pkey -in $dir/$alg.key -aes256 -passout pass:s3cret -out $dir/$alg.enc 2>/dev/null") == 0
or die "pkey enc";
for my $variant ([private_key_file => "$dir/$alg.enc"],
[private_key => do { open my $k, '<', "$dir/$alg.enc" or die; local $/; <$k> }]) {
my ($opt, $val) = @$variant;
my $xe = AWS::Signature::V4->new(
service => 'rolesanywhere', region => 'eu-west-1',
x509 => {key_type => $alg, certificate_file => "$dir/$alg.pem",
$opt => $val, private_key_password => 's3cret'},
);
my $te = $xe->sign(method => 'GET',
url => 'https://rolesanywhere.eu-west-1.amazonaws.com/sessions',
time => 1440938160);
ok $verifies->($te->{string_to_sign}, $te->{signature}),
"$alg encrypted $opt signature verifies";
}
is dies { AWS::Signature::V4->new(service => 'x', region => 'y', x509 => {
key_type => $alg, certificate_file => "$dir/$alg.pem",
private_key_file => "$dir/$alg.enc", private_key_password => 'wrong'}) },
object { prop blessed => 'Ouch'; call code => 400 },
"$alg wrong password is rejected";
like $t->{authorization},
qr{^AWS4-X509-$alg-SHA256 Credential=\d+/20150830/eu-west-1/rolesanywhere/aws4_request, SignedHeaders=content-type;host;x-amz-date;x-amz-x509, Signature=[0-9a-f]+$},
"$alg authorization shape";
my $serial = qx{openssl x509 -in $dir/$alg.pem -noout -serial};
my ($hex) = $serial =~ /serial=(\w+)/;
my ($got) = $t->{authorization} =~ /Credential=(\d+)\//;
is $got, Math::BigInt->from_hex($hex)->bstr, "$alg serial decimal";
ok $verifies->($t->{string_to_sign}, $t->{signature}), "$alg signature verifies";
}
}
unlike $e->message, qr{\Q$secret\E}, 'nor in the message';
my $d = [1, 2, 3];
is thrown(400, 'array', $d)->data, [1, 2, 3], 'not only hashes';
is thrown(400, 'scalar', 'plain')->data, 'plain', 'nor references';
};
subtest 'data and arguments stay out of the trace' => sub {
my $e = do {
package Some::Caller;
sub run ($password) { main::thrown(400, 'oops', {got => $secret}) }
run('Hunter2');
};
is $e->data, {got => $secret}, 'data kept';
unlike $e->trace, qr{\Q$secret\E|Hunter2|HASH\(}, 'no arguments in the trace';
};
subtest 'reported where the caller is' => sub {
my $line = __LINE__ + 1;
my $e = dies { fail 400, 'here', {some => 'data'} };
like "$e", qr{ at \S*error\.t line $line\b}, 'file and line of the caller';
}
# internal problems are 500
ouch_like sub { AWS::Signature::V4::Chunker->new(signed => 1, expected => 0) }, 500,
'chunker without key';
# the error is reported where the caller is, and holds no secrets
my $e = dies {
AWS::Signature::V4->new(%x509, x509 => {
key_type => 'RSA', certificate => $der, serial => 1,
private_key => 'garbage', private_key_password => $secret,
});
};
like "$e", qr{ at \S*errors\.t line \d+}, 'error reported at the line of the caller';
unlike $e->trace, qr{\Q$secret\E}, 'the trace does not include the password';
unlike "$e", qr{\Q$secret\E}, 'the message does not include the password';
for my $how ('verbose', 'die handler') {
my $e = dies {
local $Carp::Verbose = $how eq 'verbose';
local $SIG{__DIE__} = sub { die Carp::longmess($_[0]) } if $how eq 'die handler';
AWS::Signature::V4->new(%x509, x509 => {
key_type => 'RSA', certificate => $der, serial => 1,
private_key => 'garbage', private_key_password => $secret,
});
};
like $e->message, qr{\Acannot load the private key: [^\n]+\z},
"$how: the message is one line";
unlike "$e", qr{\Q$secret\E}, "$how: the message does not include the password";
}
like dies { $s->sign(url => 'http://h/') }, qr{ at \S*errors\.t line \d+},
'same for the errors of sign';
# options: undefined is like missing, derived values cannot be set
my $t = AWS::Signature::V4->new(
service => 's3', region => 'r', %cred,
payload_header => undef, double_encode => undef, normalize_path => undef,
);
ok $t->payload_header, 'undefined payload_header: default for s3';
t/security.t view on Meta::CPAN
my $dir = File::Temp::tempdir(CLEANUP => 1);
system(qq{openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 }
. qq{-aes256 -pass pass:TopSecretPass -out $dir/k.pem 2>/dev/null}) == 0
or skip_all 'openssl needed';
system(qq{openssl req -new -x509 -key $dir/k.pem -passin pass:TopSecretPass }
. qq{-subj /CN=t -days 1 -out $dir/c.pem 2>/dev/null}) == 0
or skip_all 'openssl needed';
my $pem = do { local (@ARGV, $/) = "$dir/k.pem"; <> };
my $s = AWS::Signature::V4->new(service => 'rolesanywhere', region => 'r',
x509 => {key_type => 'ECDSA', certificate_file => "$dir/c.pem",
private_key => $pem, private_key_password => 'TopSecretPass'});
ok !exists $s->x509->{private_key}, 'no key text in ->x509';
ok !exists $s->x509->{private_key_password}, 'no password in ->x509';
my $dump = dump_of($s);
unlike $dump, qr/TopSecretPass/, 'no password in a dump';
unlike $dump, qr/ENCRYPTED PRIVATE KEY/, 'no key text in a dump';
like $s->sign(method => 'GET', url => 'https://h/', time => 0)->{signature},
qr/\A[0-9a-f]+\z/, 'signing still works';
};
subtest 'userinfo in the url is refused' => sub {
for my $u ('http://a@evil.example@good.example/', 'http://user@good.example/') {
is dies { $s3->sign(method => 'GET', url => $u) }, bad_request(qr/user/), $u;
}
};