blib/lib/Net/Amazon/AlexaValidator.pm untested

filter: Statementstmt 0.0% 0 / 150 Branchbran 0.0% 0 / 32 Conditioncond 0.0% 0 / 23 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 18 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 225 CC 17 SCAR 43.2
CC
17
Cov
0%
validate_request
182.0
_invalid_keychain_uri
30.0
BEGIN
2.0
CRAP 74.9
1 package Net::Amazon::AlexaValidator;
2  
3 our $VERSION = "0.01";
4 $VERSION = eval $VERSION;
5  
6 use Crypt::OpenSSL::RSA;
7 use Crypt::OpenSSL::VerifyX509;
8 use Crypt::OpenSSL::X509;
9 use DateTime::Format::ISO8601;
10 use DateTime::Format::x509;
11 use Digest::MD5 qw(md5_hex);
12 use Digest::SHA1 qw(sha1);
13 use Encode;
14 use JSON;
15 use LWP::Simple;
16 use MIME::Base64 qw(decode_base64);
17 use Moo;
18 use Try::Tiny;
19 use Types::Standard -types;
20 use URI;
21 use URI::Normalize qw( normalize_uri );
22  
23 # ABSTRACT: Implements all security-related checks required for Amazon Alexa Skills
24  
25 =head1 NAME
26  
27 Net::Amazon::AlexaValidator - implements all security-related checks required for
28 Amazon Alexa Skills.
29  
30 =head1 SYNOPSIS
31  
32 my $alexa_validator = Net::Amazon::AlexaValidator->new({
33 application_id => 'my_application_id_from_amazon_dev_site',
34 echo_domain => 'DNS:echo-api.amazon.com',
35 cert_dir => '/tmp/',
36 });
37 my $request = $c->req; # Requires a L<Catalyst::Request> object
38 my $ret = $alexa_validator->validate_request($request);
39  
40 =head1 DESCRIPTION
41  
42 Highlights of the validation include:
43  
44 =over
45  
46 =item *
47  
48 Verifies the Signature Certificate URL. Amazon's requirements are listed here: L<https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/developing-an-alexa-skill-as-a-web-service#h2_verify_sig_cert>
49  
50 =item *
51  
52 Downloads the PEM-encoded X.509 certificate chain that Alexa used to sign the message as specified by the SignatureCertChainUrl header value on the request.
53  
54 =item *
55  
56 Validates that the signing certificate has not expired (examine both the Not Before and Not After dates).
57  
58 =item *
59  
60 Validates that the domain echo-api.amazon.com is present in the Subject Alternative Names (SANs) section of the signing certificate.
61  
62 =item *
63  
64 Validates that all certificates in the chain combine to create a chain of trust to a trusted root CA certificate.
65  
66 =item *
67  
68 Base64-decodes the Signature header value on the request to obtain the encrypted signature.
69  
70 =item *
71  
72 Uses the public key extracted from the signing certificate to decrypt the encrypted signature to produce the asserted hash value. Generates a SHA-1 hash value from the full HTTPS request body to produce the derived hash value, and compares the asserted hash value and derived hash values to ensure that they match.
73  
74 =item *
75  
76 Checks the request timestamp to ensure that the request is not an old request being sent as part of a "replay" attack.
77  
78 =over
79  
80 =back
81  
82 =back
83  
84 =head1 Configuration options
85  
86 =over
87  
88 =back
89  
90 =head2 echo_domain
91  
92 The echo domain that must be present in the Subject Alternative Names (SANs) section of the signing certificate
93  
94 =cut
95  
96 has 'echo_domain' => (
97 is => 'rw',
98 isa => Str,
99 );
100  
101 =head2 application_id
102  
103 Application ID from your app's Amazon Alexa App settings
104  
105 =cut
106  
107 has 'application_id' => (
108 is => 'rw',
109 isa => Maybe[Str],
110 );
111  
112  
113 =head2 cert_dir
114  
115 Directory in which to store your Alexa certificate, once validated
116  
117 =cut
118  
119 has 'cert_dir' => (
120 is => 'rw',
121 isa => Maybe[Str],
122 );
123  
124 =head1 Subroutines
125  
126 =over
127  
128 =back
129  
130 =head2 validate_request
131  
132 Verifies this is a valid Amazon Alexa request. Checks things like application_id, certificates, timestamp.
133  
134 returns { success, error_msg }
135  
136 =cut
137  
138 sub validate_request {
139 my ($self, $request) = @_;
140  
141  
142 my $raw_request;
143  
144 my $body_fh = $request->body;
145 # Read in the raw request exactly as Amazon sent it (Catalyst will sometimes reorder the request fields)
146 # request->body is an IO::Handle that can be read exactly like any filehandle. Grab all the data from that file.
147 unless(seek $body_fh, 0, 0) {
148 return { success => 0, error_msg => "Could not read catalyst request FH. Seek failed: $!" };
149 }
150 $raw_request = do { local $/; <$body_fh> }; # slurp the raw request
151  
152 # Validate application ID: must match the one we specified in the Alexa App settings
153 my $alexa_msg = $request->body_data;
154 unless($alexa_msg->{session}->{application}->{applicationId} eq $self->application_id) {
155 return { success => 0, error_msg => "Invalid Application ID" };
156 }
157  
158 # Validate timestamp: must be in the last 150 seconds.
159 my $ts = $alexa_msg->{request}->{timestamp};
160 my $msg_time = DateTime::Format::ISO8601->parse_datetime($ts);
161 my $diff = DateTime->now() - $msg_time;
162 unless($diff->seconds < 150) {
163 return { success => 0, error_msg => "Invalid Amazon Alexa timestamp: $ts" };
164 }
165  
166 # It's possible we've already downloaded and validated Amazon's request signature. If that's the case, we'll have
167 # a file with the same md5-hashed name.
168 my $cert_chain_url = $request->headers->header('signaturecertchainurl');
169 my $primary_cert_filename = $self->cert_dir . md5_hex($cert_chain_url) . "_primary.pem";
170 my $secondary_cert_filename = $self->cert_dir . md5_hex($cert_chain_url) . "_secondary.pem";
171  
172 my $decoded_cert;
173 if (-f $primary_cert_filename && -f $secondary_cert_filename) {
174 # If the file already exists, we've validated it during a previous Alexa interaction. Unless the $cert_chain_url
175 # has changed (in which case, the file name changes), we can go ahead and consider it validated.
176 # Primary certificate is already validated...just read it from file.
177 $decoded_cert = Crypt::OpenSSL::X509->new_from_file( $primary_cert_filename );
178 }
179 else {
180 # Validate the URI of the certificate chain
181 my $keychain_invalid = $self->_invalid_keychain_uri($cert_chain_url);
182 if($keychain_invalid) {
183 return { success => 0, error_msg => sprintf("Invalid Amazon Alexa keychain URI (%s): %s", $cert_chain_url, $keychain_invalid) };
184 }
185 # URI of the certificate appears valid, so go ahead and download it
186 my $cert = get($cert_chain_url);
187  
188 # $cert actually contains TWO certificates. Use the first one.
189 my @two_certs = split(/(-----BEGIN CERTIFICATE-----)/, $cert);
190  
191 unless((scalar @two_certs) > 2) {
192 return { success => 0, error_msg => "Invalid Amazon Certificate file" };
193 }
194  
195 # Split the certificate up into two parts and save both to file.
196 my $primary_cert = $two_certs[1] . $two_certs[2]; # grab and use the primary certificate
197 my $secondary_cert = $two_certs[3] . $two_certs[4]; # grab the secondary certificate
198 open(my $primary_cert_fh, '>', $primary_cert_filename ) or
199 return { success => 0, error_msg => "Could not open file $primary_cert_filename" };
200 print $primary_cert_fh $primary_cert;
201 close $primary_cert_fh;
202 open(my $secondary_cert_fh, '>', $secondary_cert_filename ) or
203 return { success => 0, error_msg => "Could not open file $secondary_cert_filename" };
204 print $secondary_cert_fh $secondary_cert;
205 close $secondary_cert_fh;
206  
207 $decoded_cert = Crypt::OpenSSL::X509->new_from_string( $primary_cert );
208  
209 # Ensure that the echo domain is present in the Subject Alternative Names (SANs) section of the signing certificate
210 my $exts = $decoded_cert->extensions_by_name();
211 my $san_ext = $exts->{subjectAltName};
212 unless ($san_ext->to_string() eq $self->echo_domain) {
213 unlink $primary_cert_filename;
214 unlink $secondary_cert_filename;
215 return { success => 0, error_msg => sprintf("Amazon Alexa certificate failed SANs validation: %s", $san_ext) };
216 }
217  
218 # Ensure that all certificates in the chain combine to create a chain of trust to a trusted root CA certificate
219 # Compare the asserted hash value and derived hash values to ensure that they match.
220 my $openssl_verify = "openssl verify -CAfile /etc/ssl/certs/ca-certificates.crt -untrusted $secondary_cert_filename $primary_cert_filename";
221 my $valid;
222  
223 open my $check, "-|", $openssl_verify or ( log_error({user => 'ssiegal', message => "Cannot run OpenSSL"}) && return 0 );
224 if (do { local $/; <$check> } =~ /\bOK\b/) {
225 $valid = 1;
226 }
227 close $check or ( log_error({user => 'ssiegal', message => "Cannot run OpenSSL"}) && return 0 );
228  
229 unless($valid) {
230 unlink $primary_cert_filename;
231 unlink $secondary_cert_filename;
232 return { success => 0, error_msg => "Amazon Alexa cert failed openssl verification" };
233 }
234 }
235  
236 # At this point we should have a decoded certificate.
237 unless($decoded_cert) {
238 unlink $primary_cert_filename;
239 unlink $secondary_cert_filename;
240 return { success => 0, error_msg => "Could not read primary certificate from file $primary_cert_filename" };
241 }
242  
243 # Ensure that the signing certificate has not expired (examine both the Not Before and Not After dates)
244 my $not_before = DateTime::Format::x509->parse_datetime($decoded_cert->notBefore);
245 my $not_after = DateTime::Format::x509->parse_datetime($decoded_cert->notAfter);
246 my $now = DateTime->now();
247 unless($now >= $not_before && $now <= $not_after) {
248 unlink $primary_cert_filename;
249 unlink $secondary_cert_filename;
250 return { success => 0, error_msg => sprintf("Amazon Alexa certificate failed before/after timestamp validation (%s/%s)", $not_before, $not_after) };
251 }
252  
253 # Once you have determined that the signing certificate is valid, extract the public key from it.
254 my $pub_key = Crypt::OpenSSL::RSA->new_public_key($decoded_cert->pubkey());
255  
256 # Base64-decode the Signature header value on the request to obtain the encrypted signature.
257 my $signature = decode_base64($request->headers->header('signature'));
258  
259 my $valid;
260 try {
261 $valid = $pub_key->verify($raw_request, $signature);
262 } catch {
263 return { success => 0, error_msg => "Amazon Alexa certificate failed public key validation: $_" };
264 };
265  
266 unless($valid) {
267 unlink $primary_cert_filename;
268 unlink $secondary_cert_filename;
269 return { success => 0, error_msg => "Amazon Alexa cert failed public key verification" };
270 }
271  
272 # If we're here, we've passed all the checks. FULL SPEED AHEAD!
273 return { success => 1, error_msg => "" };
274 }
275  
276 # Validate keychain uri from Amazon is proper. undef indicates no errors found.
277 # Example URI: https://s3.amazonaws.com/echo.api/echo-api-cert-3.pem
278 sub _invalid_keychain_uri {
279 my ($self, $keychain_uri) = @_;
280  
281 # Normalize the URI first
282 my $uri = normalize_uri( $keychain_uri );
283  
284 my $error_msg = undef;
285  
286 unless(lc($uri->host) eq 's3.amazonaws.com') {
287 $error_msg = 'The host for the Certificate provided in the header is invalid';
288 }
289  
290 unless($uri->path =~ m{^/echo.api/}) {
291 $error_msg = 'The URL path for the Certificate provided in the header is invalid';
292 }
293  
294 unless(lc($uri->scheme) eq 'https') {
295 $error_msg = 'The URL is using an unsupported scheme. Should be https';
296 }
297  
298 if ($uri->port && $uri->port != 443) {
299 $error_msg = 'The URL is using an unsupported https port';
300 }
301  
302 return $error_msg;
303 }
304  
305 1;