blib/lib/AWS/Signature/V4/X509.pm untested

filter: Statementstmt 0.0% 0 / 132 Branchbran 0.0% 0 / 48 Conditioncond 0.0% 0 / 86 MC/DCmcdc 0.0% 0 / 56 Subroutinesub 0.0% 0 / 28 Podpod 0.0% 0 / 21 totaltotal 0.0% 0 / 371 CC 25 SCAR 23.4
CC
25
Cov
0%
_cryptx_signer
30.0
_tlv
20.0
_build__signer
20.0
CRAP 10.4
1 package AWS::Signature::V4::X509;
2 use v5.24;
3 use experimental qw< signatures >;
4 use Moo;
5 use MIME::Base64 qw< encode_base64 decode_base64 >;
6 use Math::BigInt;
7  
8 use AWS::Signature::V4::Error qw< fail shown >;
9  
10 # a plain string or an arrayref of plain strings => arrayref
11 sub _items ($value, $name) {
12 $value = [$value] unless ref $value;
13 ref $value eq 'ARRAY'
14 or fail 400, "x509/$name must be a string or an array reference";
15 for my $item ($value->@*) {
16 fail 400, "x509/$name must hold strings" if !defined $item || ref $item;
17 }
18 return $value;
19 }
20  
21 sub _b64 ($der) { encode_base64($der, '') }
22  
23 # ---- X.509 helpers (no external dependencies) ------------------------------
24  
25 sub _slurp ($file) {
26 open my $fh, '<:raw', $file or fail 400, 'open(' . shown($file) . "): $!";
27 local $/;
28 my $data = <$fh>;
29 close $fh;
30 return $data;
31 }
32  
33 sub _to_ders ($cert) { # PEM bundles hold many certificates
34 return _check_der($cert) unless $cert =~ m{-----BEGIN};
35 my @ders = map { decode_base64($_) }
36 $cert =~ m{-----BEGIN CERTIFICATE-----(.*?)-----END CERTIFICATE-----}sg;
37 @ders or fail 400, 'no CERTIFICATE block in PEM';
38 return map { _check_der($_) } @ders;
39 }
40  
41 sub _to_der ($cert) {
42 return _check_der($cert) unless $cert =~ m{-----BEGIN};
43 $cert =~ m{-----BEGIN CERTIFICATE-----(.*?)-----END CERTIFICATE-----}s
44 or fail 400, 'no CERTIFICATE block in PEM';
45 return _check_der(decode_base64($1));
46 }
47  
48 # a certificate is a DER SEQUENCE that fits exactly in the data
49 sub _check_der ($der) {
50 my ($tag, undef, $end) = _tlv($der, 0);
51 fail 400, 'not a DER-encoded certificate'
52 unless $tag == 0x30 && $end == length $der;
53 return $der;
54 }
55  
56 # read one DER TLV at $off => (tag, content_start, content_end)
57 sub _tlv ($der, $off) {
58 my $max = length $der;
59 $off + 2 <= $max or fail 400, 'truncated certificate';
60 my $tag = ord substr $der, $off++, 1;
61 my $len = ord substr $der, $off++, 1;
62 if ($len & 0x80) { # long form, DER wants it minimal and definite
63 my $n = $len & 0x7F;
64 fail 400, 'not a DER-encoded certificate' if $n == 0 || $n > 4;
65 $off + $n <= $max or fail 400, 'truncated certificate';
66 $len = 0;
67 $len = ($len << 8) | ord substr($der, $off++, 1) for 1 .. $n;
68 fail 400, 'not a DER-encoded certificate'
69 if $len < 0x80 || $len < 1 << 8 * ($n - 1);
70 }
71 $off + $len <= $max or fail 400, 'truncated certificate';
72 return ($tag, $off, $off + $len);
73 }
74  
75 # Certificate ::= SEQ { tbs SEQ { [0] version?, INTEGER serial, ... }, ... }
76 sub _certificate_serial ($der) {
77 my (undef, $cs) = _tlv($der, 0);
78 my (undef, $ts) = _tlv($der, $cs);
79 my ($tag, $s, $e) = _tlv($der, $ts);
80 ($tag, $s, $e) = _tlv($der, $e) if $tag == 0xA0; # skip explicit version
81 fail 400, 'cannot find certificate serial number' unless $tag == 0x02;
82 return Math::BigInt->from_hex(unpack 'H*', substr $der, $s, $e - $s)
83 ->bstr; # DER integers here are positive; leading 0x00 is harmless
84 }
85  
86 # The error of CryptX, without the location and the backtrace that Carp adds
87 # when verbose (the arguments in it may hold the password), escaped as caller
88 # input because it can hold the file name.
89 sub _clean_error ($e) {
90 $e =~ s{\n\t.*}{}s; # the backtrace lines start with a tab
91 $e =~ s{\s+at \S+ line \d+\.?\s*\z}{};
92 return shown($e =~ s{\A\s+|\s+\z}{}gr);
93 }
94  
95 # $key is a file name or a scalar reference to the PEM text
96 sub _cryptx_signer ($algo, $key, $password = undef) {
97 my $class = $algo eq 'RSA' ? 'Crypt::PK::RSA' : 'Crypt::PK::ECC';
98 eval "require $class; 1" or fail 500, "cannot load $class";
99 my @args = ($key, defined $password ? ($password) : ());
100 my $pk = eval {
101 # no backtrace, e.g. from -MCarp=verbose or Carp::Always, with the password
102 local $Carp::Verbose = 0;
103 local $Carp::MaxArgNums = -1;
104 local $SIG{__DIE__};
105 $class->new(@args);
106 } // fail 400, "cannot load the private key: " . _clean_error($@);
107 fail 400, 'the key is not a private key' unless $pk->is_private;
108 return $algo eq 'RSA'
109 ? sub ($bytes) { $pk->sign_message($bytes, 'SHA256', 'v1.5') }
110 : sub ($bytes) { $pk->sign_message($bytes, 'SHA256') };
111 }
112  
113 use namespace::clean;
114  
115 # The certificate-based variant, as used by IAM Roles Anywhere. The options
116 # are the ones of the "x509" option of AWS::Signature::V4:
117 # certificate / certificate_file: PEM or DER text, or path of a file with it;
118 # only the first certificate of a PEM bundle is used
119 # chain / chain_files: optional arrayref of PEM/DER intermediate certificates,
120 # or of paths of files with them; a PEM item can be a bundle.
121 # chain can also be a plain string: a PEM-encoded bundle, and
122 # chain_files a plain string: the path of one file
123 # key_type: 'RSA' or 'ECDSA'
124 # serial: the serial number of the certificate, if it cannot be found
125 # signer: sub ($bytes_to_sign) -> raw signature bytes (DER for ECDSA,
126 # PKCS#1 v1.5 for RSA), computed with SHA-256; or, alternatively,
127 # private_key_file / private_key: PEM or DER key (path or content, the
128 # content wins), signed with CryptX; private_key_password if it
129 # is encrypted
130 has [qw<
131 key_type certificate certificate_file chain chain_files serial signer
132 private_key_file
133 >] => (is => 'ro');
134  
135 # the key text and its password are secrets, only needed to load the key:
136 # no public accessor, and they are dropped as soon as the key is loaded
137 has $_ => (is => 'ro', reader => "_$_", clearer => "_clear_$_")
138 for qw< private_key private_key_password >;
139  
140 # Derived from the options above. Lazy, so that each builder can use the
141 # others without depending on the order in which the constructor sets things
142 # up; BUILD forces them all, so that a bad certificate, chain or key is
143 # reported by new() and not by the first signature.
144 #
145 # **NOTE**: to add one, add its name here and write its builder.
146 my @DERIVED = qw< algorithm credential_id _chain _der _signer _type >;
147 has $_ => (is => 'lazy', init_arg => undef) for @DERIVED;
148  
149 sub BUILD ($self, $args) {
150 my %known = map { $_ => 1 } qw<
151 key_type certificate certificate_file chain chain_files serial signer
152 private_key_file private_key private_key_password
153 >;
154 if (my ($name) = sort(grep { !$known{$_} } keys $args->%*)) {
155 fail 400, 'unknown option "' . shown($name) . '" in x509';
156 }
157 for my $name (@DERIVED) { # not "for (...)": builders may use $_
158 $self->$name;
159 }
160  
161 # we don't need private key material past this point, so we get rid
162 # of it immediately. Of course it may still linger in memory depending
163 # on garbage collection.
164 $self->_clear_private_key;
165 $self->_clear_private_key_password;
166 return;
167 }
168  
169 sub _build__type ($self) {
170 my $type = uc($self->key_type // fail 400, 'missing x509/key_type');
171 fail 400, 'x509/key_type must be RSA or ECDSA, got ' . shown($type)
172 unless $type eq 'RSA' || $type eq 'ECDSA';
173 return $type;
174 }
175  
176 sub _build_algorithm ($self) { 'AWS4-X509-' . $self->_type . '-SHA256' }
177  
178 sub _build__der ($self) {
179 my $cert = $self->certificate;
180 if (!defined $cert && defined $self->certificate_file) {
181 $cert = _slurp($self->certificate_file);
182 }
183 defined $cert or fail 400, 'x509 needs "certificate" or "certificate_file"';
184 return _to_der($cert);
185 }
186  
187 sub _build__chain ($self) {
188 my $chain = $self->chain;
189 if (!defined $chain && defined $self->chain_files) {
190 my $files = _items($self->chain_files, 'chain_files'); # a single path or an arrayref
191 $chain = [map { _slurp($_) } $files->@*];
192 }
193 if (defined $chain && !ref $chain) { # a plain string is a PEM bundle
194 $chain =~ m{-----BEGIN CERTIFICATE-----}
195 or fail 400, 'x509/chain as a string must be PEM-encoded';
196 }
197 return [map { _to_ders($_) } _items($chain // [], 'chain')->@*];
198 }
199  
200 sub _build_credential_id ($self) {
201 return $self->serial // _certificate_serial($self->_der);
202 }
203  
204 sub _build__signer ($self) {
205 my $type = $self->_type;
206 my $signer = $self->signer;
207 fail 400, '"signer" must be a code reference'
208 if defined $signer && ref $signer ne 'CODE';
209 if (!$signer && defined $self->_private_key) { # the content wins, as for certificate
210 my $key = $self->_private_key; # CryptX wants a reference for a PEM/DER text
211 $signer = _cryptx_signer($type, \$key, $self->_private_key_password);
212 }
213 elsif (!$signer && defined $self->private_key_file) {
214 $signer = _cryptx_signer($type, $self->private_key_file, $self->_private_key_password);
215 }
216 return $signer
217 // fail 400, 'x509 needs one of "signer", "private_key_file", "private_key"';
218 }
219  
220 # ---- what AWS::Signature::V4 wants from a variant --------------------------
221  
222 # hex signature of the string to sign; the scope is not used here
223 sub signature ($self, $scope, $string_to_sign) {
224 my $sig = $self->_signer->($string_to_sign);
225 fail 400, 'the x509 signer returned no signature'
226 unless defined $sig && !ref $sig && length $sig;
227 utf8::downgrade($sig, 1)
228 or fail 400, 'the x509 signer returned a string with wide characters';
229 return unpack 'H*', $sig;
230 }
231  
232 # what goes with the request besides the signature, as (name => value) pairs
233 sub extra_fields ($self) {
234 my $chain = $self->_chain;
235 return (
236 'X-Amz-X509' => _b64($self->_der),
237 ($chain->@* ? ('X-Amz-X509-Chain' => join ',', map { _b64($_) } $chain->@*) : ()),
238 );
239 }
240  
241 # No derived key, so no signed chunks. This is stated twice, on purpose:
242 # AWS::Signature::V4 asks can_sign_chunks() up front, to refuse the request
243 # before doing anything else, and signing_key() is what fails if somebody
244 # asks for the key anyway. If this ever changes, change BOTH, and the
245 # corresponding tests in t/variants.t.
246 sub can_sign_chunks ($self) { 0 }
247 sub signing_key ($self, $scope) {
248 fail 400, 'signed streaming needs the credentials variant, not x509';
249 }
250  
251 1;