• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <keymaster/android_keymaster.h>
18 
19 #include <vector>
20 
21 #include <assert.h>
22 #include <string.h>
23 
24 #include <stddef.h>
25 
26 #include <cppbor.h>
27 #include <cppbor_parse.h>
28 
29 #include <keymaster/UniquePtr.h>
30 #include <keymaster/android_keymaster_utils.h>
31 #include <keymaster/cppcose/cppcose.h>
32 #include <keymaster/key.h>
33 #include <keymaster/key_blob_utils/ae.h>
34 #include <keymaster/key_factory.h>
35 #include <keymaster/keymaster_context.h>
36 #include <keymaster/km_date.h>
37 #include <keymaster/km_openssl/openssl_err.h>
38 #include <keymaster/km_openssl/openssl_utils.h>
39 #include <keymaster/logger.h>
40 #include <keymaster/operation.h>
41 #include <keymaster/operation_table.h>
42 #include <keymaster/remote_provisioning_utils.h>
43 
44 namespace keymaster {
45 
46 namespace {
47 
48 using cppcose::constructCoseEncrypt;
49 using cppcose::constructCoseMac0;
50 using cppcose::constructCoseSign1;
51 using cppcose::CoseKey;
52 using cppcose::EC2;
53 using cppcose::ES256;
54 using cppcose::generateCoseMac0Mac;
55 using cppcose::kAesGcmNonceLength;
56 using cppcose::P256;
57 using cppcose::x25519_HKDF_DeriveKey;
58 
59 template <keymaster_tag_t T>
CheckPatchLevel(const AuthorizationSet & tee_enforced,const AuthorizationSet & sw_enforced,TypedTag<KM_UINT,T> tag,uint32_t current_patchlevel)60 keymaster_error_t CheckPatchLevel(const AuthorizationSet& tee_enforced,
61                                   const AuthorizationSet& sw_enforced, TypedTag<KM_UINT, T> tag,
62                                   uint32_t current_patchlevel) {
63     uint32_t key_patchlevel;
64     if (tee_enforced.GetTagValue(tag, &key_patchlevel) ||
65         sw_enforced.GetTagValue(tag, &key_patchlevel)) {
66         if (key_patchlevel < current_patchlevel) {
67             return KM_ERROR_KEY_REQUIRES_UPGRADE;
68         } else if (key_patchlevel > current_patchlevel) {
69             return KM_ERROR_INVALID_KEY_BLOB;
70         }
71     }
72     return KM_ERROR_OK;
73 }
74 
CheckVersionInfo(const AuthorizationSet & tee_enforced,const AuthorizationSet & sw_enforced,const KeymasterContext & context)75 keymaster_error_t CheckVersionInfo(const AuthorizationSet& tee_enforced,
76                                    const AuthorizationSet& sw_enforced,
77                                    const KeymasterContext& context) {
78     uint32_t os_version;
79     uint32_t os_patchlevel;
80     context.GetSystemVersion(&os_version, &os_patchlevel);
81 
82     keymaster_error_t err =
83         CheckPatchLevel(tee_enforced, sw_enforced, TAG_OS_PATCHLEVEL, os_patchlevel);
84     if (err != KM_ERROR_OK) return err;
85 
86     // Also check the vendor and boot patchlevels if available.
87     auto vendor_patchlevel = context.GetVendorPatchlevel();
88     if (vendor_patchlevel.has_value()) {
89         err = CheckPatchLevel(tee_enforced, sw_enforced, TAG_VENDOR_PATCHLEVEL,
90                               vendor_patchlevel.value());
91         if (err != KM_ERROR_OK) return err;
92     }
93     auto boot_patchlevel = context.GetBootPatchlevel();
94     if (boot_patchlevel.has_value()) {
95         err = CheckPatchLevel(tee_enforced, sw_enforced, TAG_BOOT_PATCHLEVEL,
96                               boot_patchlevel.value());
97         if (err != KM_ERROR_OK) return err;
98     }
99 
100     return KM_ERROR_OK;
101 }
102 
103 const keymaster_key_param_t kKeyMintEcdsaP256Params[] = {
104     Authorization(TAG_PURPOSE, KM_PURPOSE_ATTEST_KEY),
105     Authorization(TAG_ALGORITHM, KM_ALGORITHM_EC), Authorization(TAG_KEY_SIZE, 256),
106     Authorization(TAG_DIGEST, KM_DIGEST_SHA_2_256), Authorization(TAG_EC_CURVE, KM_EC_CURVE_P_256),
107     Authorization(TAG_NO_AUTH_REQUIRED),
108     // The certificate generated by KM will be discarded, these values don't matter.
109     Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0), Authorization(TAG_CERTIFICATE_NOT_AFTER, 0)};
110 
getMacFunction(bool test_mode,RemoteProvisioningContext * rem_prov_ctx)111 cppcose::HmacSha256Function getMacFunction(bool test_mode,
112                                            RemoteProvisioningContext* rem_prov_ctx) {
113     if (test_mode) {
114         return [](const cppcose::bytevec& input) {
115             const cppcose::bytevec macKey(32);
116             return cppcose::generateHmacSha256(macKey, input);
117         };
118     }
119 
120     return [rem_prov_ctx](const cppcose::bytevec& input) -> cppcose::ErrMsgOr<cppcose::HmacSha256> {
121         auto mac = rem_prov_ctx->GenerateHmacSha256(input);
122         if (!mac) {
123             return "Remote provisioning context failed to sign MAC.";
124         }
125         return *mac;
126     };
127 }
128 
129 constexpr int kP256AffinePointSize = 32;
130 
131 }  // anonymous namespace
132 
AndroidKeymaster(KeymasterContext * context,size_t operation_table_size,uint32_t message_version)133 AndroidKeymaster::AndroidKeymaster(KeymasterContext* context, size_t operation_table_size,
134                                    uint32_t message_version)
135     : context_(context), operation_table_(new (std::nothrow) OperationTable(operation_table_size)),
136       message_version_(message_version) {}
137 
~AndroidKeymaster()138 AndroidKeymaster::~AndroidKeymaster() {}
139 
AndroidKeymaster(AndroidKeymaster && other)140 AndroidKeymaster::AndroidKeymaster(AndroidKeymaster&& other)
141     : context_(move(other.context_)), operation_table_(move(other.operation_table_)) {}
142 
143 // TODO(swillden): Unify support analysis.  Right now, we have per-keytype methods that determine if
144 // specific modes, padding, etc. are supported for that key type, and AndroidKeymaster also has
145 // methods that return the same information.  They'll get out of sync.  Best to put the knowledge in
146 // the keytypes and provide some mechanism for AndroidKeymaster to query the keytypes for the
147 // information.
148 
149 template <typename T>
check_supported(const KeymasterContext & context,keymaster_algorithm_t algorithm,SupportedResponse<T> * response)150 bool check_supported(const KeymasterContext& context, keymaster_algorithm_t algorithm,
151                      SupportedResponse<T>* response) {
152     if (context.GetKeyFactory(algorithm) == nullptr) {
153         response->error = KM_ERROR_UNSUPPORTED_ALGORITHM;
154         return false;
155     }
156     return true;
157 }
158 
GetVersion(const GetVersionRequest &,GetVersionResponse * rsp)159 void AndroidKeymaster::GetVersion(const GetVersionRequest&, GetVersionResponse* rsp) {
160     if (rsp == nullptr) return;
161 
162     rsp->major_ver = 2;
163     rsp->minor_ver = 0;
164     rsp->subminor_ver = 0;
165     rsp->error = KM_ERROR_OK;
166 }
167 
GetVersion2(const GetVersion2Request & req)168 GetVersion2Response AndroidKeymaster::GetVersion2(const GetVersion2Request& req) {
169     GetVersion2Response rsp;
170     rsp.km_version = context_->GetKmVersion();
171     rsp.km_date = kKmDate;
172     rsp.max_message_version = MessageVersion(rsp.km_version, rsp.km_date);
173     rsp.error = KM_ERROR_OK;
174 
175     // Determine what message version we should use.
176     message_version_ = NegotiateMessageVersion(req, rsp);
177 
178     LOG_D("GetVersion2 results: %d, %d, %d, %d", rsp.km_version, rsp.km_date,
179           rsp.max_message_version, message_version_);
180     return rsp;
181 }
182 
SupportedAlgorithms(const SupportedAlgorithmsRequest &,SupportedAlgorithmsResponse * response)183 void AndroidKeymaster::SupportedAlgorithms(const SupportedAlgorithmsRequest& /* request */,
184                                            SupportedAlgorithmsResponse* response) {
185     if (response == nullptr) return;
186 
187     response->error = KM_ERROR_OK;
188 
189     size_t algorithm_count = 0;
190     const keymaster_algorithm_t* algorithms = context_->GetSupportedAlgorithms(&algorithm_count);
191     if (algorithm_count == 0) return;
192     response->results_length = algorithm_count;
193     response->results = dup_array(algorithms, algorithm_count);
194     if (!response->results) response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
195 }
196 
197 template <typename T>
GetSupported(const KeymasterContext & context,keymaster_algorithm_t algorithm,keymaster_purpose_t purpose,const T * (OperationFactory::* get_supported_method)(size_t * count)const,SupportedResponse<T> * response)198 void GetSupported(const KeymasterContext& context, keymaster_algorithm_t algorithm,
199                   keymaster_purpose_t purpose,
200                   const T* (OperationFactory::*get_supported_method)(size_t* count) const,
201                   SupportedResponse<T>* response) {
202     if (response == nullptr || !check_supported(context, algorithm, response)) return;
203 
204     const OperationFactory* factory = context.GetOperationFactory(algorithm, purpose);
205     if (!factory) {
206         response->error = KM_ERROR_UNSUPPORTED_PURPOSE;
207         return;
208     }
209 
210     size_t count;
211     const T* supported = (factory->*get_supported_method)(&count);
212     response->SetResults(supported, count);
213 }
214 
SupportedBlockModes(const SupportedBlockModesRequest & request,SupportedBlockModesResponse * response)215 void AndroidKeymaster::SupportedBlockModes(const SupportedBlockModesRequest& request,
216                                            SupportedBlockModesResponse* response) {
217     GetSupported(*context_, request.algorithm, request.purpose,
218                  &OperationFactory::SupportedBlockModes, response);
219 }
220 
SupportedPaddingModes(const SupportedPaddingModesRequest & request,SupportedPaddingModesResponse * response)221 void AndroidKeymaster::SupportedPaddingModes(const SupportedPaddingModesRequest& request,
222                                              SupportedPaddingModesResponse* response) {
223     GetSupported(*context_, request.algorithm, request.purpose,
224                  &OperationFactory::SupportedPaddingModes, response);
225 }
226 
SupportedDigests(const SupportedDigestsRequest & request,SupportedDigestsResponse * response)227 void AndroidKeymaster::SupportedDigests(const SupportedDigestsRequest& request,
228                                         SupportedDigestsResponse* response) {
229     GetSupported(*context_, request.algorithm, request.purpose, &OperationFactory::SupportedDigests,
230                  response);
231 }
232 
SupportedImportFormats(const SupportedImportFormatsRequest & request,SupportedImportFormatsResponse * response)233 void AndroidKeymaster::SupportedImportFormats(const SupportedImportFormatsRequest& request,
234                                               SupportedImportFormatsResponse* response) {
235     if (response == nullptr || !check_supported(*context_, request.algorithm, response)) return;
236 
237     size_t count;
238     const keymaster_key_format_t* formats =
239         context_->GetKeyFactory(request.algorithm)->SupportedImportFormats(&count);
240     response->SetResults(formats, count);
241 }
242 
SupportedExportFormats(const SupportedExportFormatsRequest & request,SupportedExportFormatsResponse * response)243 void AndroidKeymaster::SupportedExportFormats(const SupportedExportFormatsRequest& request,
244                                               SupportedExportFormatsResponse* response) {
245     if (response == nullptr || !check_supported(*context_, request.algorithm, response)) return;
246 
247     size_t count;
248     const keymaster_key_format_t* formats =
249         context_->GetKeyFactory(request.algorithm)->SupportedExportFormats(&count);
250     response->SetResults(formats, count);
251 }
252 
GetHmacSharingParameters()253 GetHmacSharingParametersResponse AndroidKeymaster::GetHmacSharingParameters() {
254     GetHmacSharingParametersResponse response(message_version());
255     KeymasterEnforcement* policy = context_->enforcement_policy();
256     if (!policy) {
257         response.error = KM_ERROR_UNIMPLEMENTED;
258         return response;
259     }
260 
261     response.error = policy->GetHmacSharingParameters(&response.params);
262     return response;
263 }
264 
265 ComputeSharedHmacResponse
ComputeSharedHmac(const ComputeSharedHmacRequest & request)266 AndroidKeymaster::ComputeSharedHmac(const ComputeSharedHmacRequest& request) {
267     ComputeSharedHmacResponse response(message_version());
268     KeymasterEnforcement* policy = context_->enforcement_policy();
269     if (!policy) {
270         response.error = KM_ERROR_UNIMPLEMENTED;
271         return response;
272     }
273     response.error = policy->ComputeSharedHmac(request.params_array, &response.sharing_check);
274 
275     return response;
276 }
277 
278 VerifyAuthorizationResponse
VerifyAuthorization(const VerifyAuthorizationRequest & request)279 AndroidKeymaster::VerifyAuthorization(const VerifyAuthorizationRequest& request) {
280     KeymasterEnforcement* policy = context_->enforcement_policy();
281     if (!policy) {
282         VerifyAuthorizationResponse response(message_version());
283         response.error = KM_ERROR_UNIMPLEMENTED;
284         return response;
285     }
286 
287     return policy->VerifyAuthorization(request);
288 }
289 
GenerateTimestampToken(GenerateTimestampTokenRequest & request,GenerateTimestampTokenResponse * response)290 void AndroidKeymaster::GenerateTimestampToken(GenerateTimestampTokenRequest& request,
291                                               GenerateTimestampTokenResponse* response) {
292     KeymasterEnforcement* policy = context_->enforcement_policy();
293     if (!policy) {
294         response->error = KM_ERROR_UNIMPLEMENTED;
295     } else {
296         response->token.challenge = request.challenge;
297         response->error = policy->GenerateTimestampToken(&response->token);
298     }
299 }
300 
AddRngEntropy(const AddEntropyRequest & request,AddEntropyResponse * response)301 void AndroidKeymaster::AddRngEntropy(const AddEntropyRequest& request,
302                                      AddEntropyResponse* response) {
303     response->error = context_->AddRngEntropy(request.random_data.peek_read(),
304                                               request.random_data.available_read());
305 }
306 
get_key_factory(const AuthorizationSet & key_description,const KeymasterContext & context,keymaster_error_t * error)307 const KeyFactory* get_key_factory(const AuthorizationSet& key_description,
308                                   const KeymasterContext& context,  //
309                                   keymaster_error_t* error) {
310     keymaster_algorithm_t algorithm;
311     const KeyFactory* factory{};
312     if (!key_description.GetTagValue(TAG_ALGORITHM, &algorithm) ||
313         !(factory = context.GetKeyFactory(algorithm))) {
314         *error = KM_ERROR_UNSUPPORTED_ALGORITHM;
315     }
316     return factory;
317 }
318 
GenerateKey(const GenerateKeyRequest & request,GenerateKeyResponse * response)319 void AndroidKeymaster::GenerateKey(const GenerateKeyRequest& request,
320                                    GenerateKeyResponse* response) {
321     if (response == nullptr) return;
322 
323     const KeyFactory* factory =
324         get_key_factory(request.key_description, *context_, &response->error);
325     if (!factory) return;
326 
327     UniquePtr<Key> attest_key;
328     if (request.attestation_signing_key_blob.key_material_size) {
329         attest_key = LoadKey(request.attestation_signing_key_blob, request.attest_key_params,
330                              &response->error);
331         if (response->error != KM_ERROR_OK) return;
332     }
333 
334     response->enforced.Clear();
335     response->unenforced.Clear();
336     response->error = factory->GenerateKey(request.key_description,
337                                            move(attest_key),  //
338                                            request.issuer_subject,
339                                            &response->key_blob,  //
340                                            &response->enforced,
341                                            &response->unenforced,  //
342                                            &response->certificate_chain);
343 }
344 
GenerateRkpKey(const GenerateRkpKeyRequest & request,GenerateRkpKeyResponse * response)345 void AndroidKeymaster::GenerateRkpKey(const GenerateRkpKeyRequest& request,
346                                       GenerateRkpKeyResponse* response) {
347     if (response == nullptr) return;
348 
349     auto rem_prov_ctx = context_->GetRemoteProvisioningContext();
350     if (rem_prov_ctx == nullptr) {
351         response->error = static_cast<keymaster_error_t>(kStatusFailed);
352         return;
353     }
354 
355     // Generate the keypair that will become the attestation key.
356     GenerateKeyRequest gen_key_request(message_version_);
357     gen_key_request.key_description.Reinitialize(kKeyMintEcdsaP256Params,
358                                                  array_length(kKeyMintEcdsaP256Params));
359     GenerateKeyResponse gen_key_response(message_version_);
360     GenerateKey(gen_key_request, &gen_key_response);
361     if (gen_key_response.error != KM_ERROR_OK) {
362         response->error = static_cast<keymaster_error_t>(kStatusFailed);
363         return;
364     }
365 
366     // Retrieve the certificate and parse it to build a COSE_Key
367     if (gen_key_response.certificate_chain.entry_count != 1) {
368         // Error: Need the single non-signed certificate with the public key in it.
369         response->error = static_cast<keymaster_error_t>(kStatusFailed);
370         return;
371     }
372     std::vector<uint8_t> x_coord(kP256AffinePointSize);
373     std::vector<uint8_t> y_coord(kP256AffinePointSize);
374     response->error =
375         GetEcdsa256KeyFromCert(gen_key_response.certificate_chain.begin(), x_coord.data(),
376                                x_coord.size(), y_coord.data(), y_coord.size());
377     if (response->error != KM_ERROR_OK) {
378         response->error = static_cast<keymaster_error_t>(kStatusFailed);
379         return;
380     }
381 
382     cppbor::Map cose_public_key_map = cppbor::Map()
383                                           .add(CoseKey::KEY_TYPE, EC2)
384                                           .add(CoseKey::ALGORITHM, ES256)
385                                           .add(CoseKey::CURVE, P256)
386                                           .add(CoseKey::PUBKEY_X, x_coord)
387                                           .add(CoseKey::PUBKEY_Y, y_coord);
388     if (request.test_mode) {
389         cose_public_key_map.add(CoseKey::TEST_KEY, cppbor::Null());
390     }
391 
392     std::vector<uint8_t> cosePublicKey = cose_public_key_map.canonicalize().encode();
393 
394     auto macFunction = getMacFunction(request.test_mode, rem_prov_ctx);
395     auto macedKey = constructCoseMac0(macFunction, {} /* externalAad */, cosePublicKey);
396     if (!macedKey) {
397         response->error = static_cast<keymaster_error_t>(kStatusFailed);
398         return;
399     }
400     std::vector<uint8_t> enc = macedKey->encode();
401     response->maced_public_key = KeymasterBlob(enc.data(), enc.size());
402     response->key_blob = std::move(gen_key_response.key_blob);
403     response->error = KM_ERROR_OK;
404 }
405 
GenerateCsr(const GenerateCsrRequest & request,GenerateCsrResponse * response)406 void AndroidKeymaster::GenerateCsr(const GenerateCsrRequest& request,
407                                    GenerateCsrResponse* response) {
408     if (response == nullptr) return;
409 
410     auto rem_prov_ctx = context_->GetRemoteProvisioningContext();
411     if (rem_prov_ctx == nullptr) {
412         LOG_E("Couldn't get a pointer to the remote provisioning context, returned null.", 0);
413         response->error = static_cast<keymaster_error_t>(kStatusFailed);
414         return;
415     }
416 
417     auto macFunction = getMacFunction(request.test_mode, rem_prov_ctx);
418     auto pubKeysToSign = validateAndExtractPubkeys(request.test_mode, request.num_keys,
419                                                    request.keys_to_sign_array, macFunction);
420     if (!pubKeysToSign.isOk()) {
421         LOG_E("Failed to validate and extract the public keys for the CSR", 0);
422         response->error = static_cast<keymaster_error_t>(pubKeysToSign.moveError());
423         return;
424     }
425 
426     std::vector<uint8_t> ephemeral_mac_key(SHA256_DIGEST_LENGTH, 0 /* value */);
427     if (GenerateRandom(ephemeral_mac_key.data(), ephemeral_mac_key.size()) != KM_ERROR_OK) {
428         LOG_E("Failed to generate a random mac key.", 0);
429         response->error = static_cast<keymaster_error_t>(kStatusFailed);
430         return;
431     }
432 
433     auto ephemeral_mac_function = [&ephemeral_mac_key](const cppcose::bytevec& input) {
434         return cppcose::generateHmacSha256(ephemeral_mac_key, input);
435     };
436 
437     auto pubKeysToSignMac =
438         generateCoseMac0Mac(ephemeral_mac_function, std::vector<uint8_t>{}, *pubKeysToSign);
439     if (!pubKeysToSignMac) {
440         LOG_E("Failed to generate COSE_Mac0 over the public keys to sign.", 0);
441         response->error = static_cast<keymaster_error_t>(kStatusFailed);
442         return;
443     }
444     response->keys_to_sign_mac = KeymasterBlob(pubKeysToSignMac->data(), pubKeysToSignMac->size());
445 
446     std::vector<uint8_t> devicePrivKey;
447     cppbor::Array bcc;
448     if (request.test_mode) {
449         std::tie(devicePrivKey, bcc) = rem_prov_ctx->GenerateBcc(/*testMode=*/true);
450     } else {
451         devicePrivKey = rem_prov_ctx->devicePrivKey_;
452         auto clone = rem_prov_ctx->bcc_.clone();
453         if (!clone->asArray()) {
454             LOG_E("The BCC is not an array.", 0);
455             response->error = static_cast<keymaster_error_t>(kStatusFailed);
456             return;
457         }
458         bcc = std::move(*clone->asArray());
459     }
460     std::unique_ptr<cppbor::Map> device_info_map = rem_prov_ctx->CreateDeviceInfo();
461     std::vector<uint8_t> device_info = device_info_map->encode();
462     response->device_info_blob = KeymasterBlob(device_info.data(), device_info.size());
463     auto signedMac =
464         constructCoseSign1(devicePrivKey /* Signing key */,  //
465                            ephemeral_mac_key /* Payload */,
466                            cppbor::Array() /* AAD */
467                                .add(std::pair(request.challenge.begin(),
468                                               request.challenge.end() - request.challenge.begin()))
469                                .add(std::move(device_info_map))
470                                .add(std::pair(pubKeysToSignMac->data(), pubKeysToSignMac->size()))
471                                .encode());
472     if (!signedMac) {
473         LOG_E("Failed to construct COSE_Sign1 over the ephemeral mac key.", 0);
474         response->error = static_cast<keymaster_error_t>(kStatusFailed);
475         return;
476     }
477 
478     std::vector<uint8_t> ephemeralPrivKey(X25519_PRIVATE_KEY_LEN);
479     std::vector<uint8_t> ephemeralPubKey(X25519_PUBLIC_VALUE_LEN);
480     X25519_keypair(ephemeralPubKey.data(), ephemeralPrivKey.data());
481 
482     auto eek = validateAndExtractEekPubAndId(request.test_mode, request.endpoint_enc_cert_chain);
483     if (!eek.isOk()) {
484         LOG_E("Failed to validate and extract the endpoint encryption key.", 0);
485         response->error = static_cast<keymaster_error_t>(eek.moveError());
486         return;
487     }
488 
489     auto sessionKey =
490         x25519_HKDF_DeriveKey(ephemeralPubKey, ephemeralPrivKey, eek->first, true /* senderIsA */);
491     if (!sessionKey) {
492         LOG_E("Failed to derive the session key.", 0);
493         response->error = static_cast<keymaster_error_t>(kStatusFailed);
494         return;
495     }
496 
497     std::vector<uint8_t> nonce(kAesGcmNonceLength, 0 /* value */);
498     if (GenerateRandom(nonce.data(), nonce.size()) != KM_ERROR_OK) {
499         LOG_E("Failed to generate a random nonce.", 0);
500         response->error = static_cast<keymaster_error_t>(kStatusFailed);
501         return;
502     }
503     auto coseEncrypted = constructCoseEncrypt(*sessionKey, nonce,
504                                               cppbor::Array()  // payload
505                                                   .add(signedMac.moveValue())
506                                                   .add(std::move(bcc))
507                                                   .encode(),
508                                               {},  // aad
509                                               buildCertReqRecipients(ephemeralPubKey, eek->second));
510 
511     if (!coseEncrypted) {
512         LOG_E("Failed to construct a COSE_Encrypt ProtectedData structure", 0);
513         response->error = static_cast<keymaster_error_t>(kStatusFailed);
514         return;
515     }
516     std::vector<uint8_t> payload = coseEncrypted->encode();
517     response->protected_data_blob = KeymasterBlob(payload.data(), payload.size());
518     response->error = KM_ERROR_OK;
519 }
520 
GetKeyCharacteristics(const GetKeyCharacteristicsRequest & request,GetKeyCharacteristicsResponse * response)521 void AndroidKeymaster::GetKeyCharacteristics(const GetKeyCharacteristicsRequest& request,
522                                              GetKeyCharacteristicsResponse* response) {
523     if (response == nullptr) return;
524 
525     UniquePtr<Key> key;
526     response->error =
527         context_->ParseKeyBlob(KeymasterKeyBlob(request.key_blob), request.additional_params, &key);
528     if (response->error != KM_ERROR_OK) return;
529 
530     // scavenge the key object for the auth lists
531     response->enforced = move(key->hw_enforced());
532     response->unenforced = move(key->sw_enforced());
533 
534     response->error = CheckVersionInfo(response->enforced, response->unenforced, *context_);
535 }
536 
BeginOperation(const BeginOperationRequest & request,BeginOperationResponse * response)537 void AndroidKeymaster::BeginOperation(const BeginOperationRequest& request,
538                                       BeginOperationResponse* response) {
539     if (response == nullptr) return;
540     response->op_handle = 0;
541 
542     UniquePtr<Key> key = LoadKey(request.key_blob, request.additional_params, &response->error);
543     if (!key) return;
544 
545     response->error = KM_ERROR_UNKNOWN_ERROR;
546     keymaster_algorithm_t key_algorithm;
547     if (!key->authorizations().GetTagValue(TAG_ALGORITHM, &key_algorithm)) return;
548 
549     response->error = KM_ERROR_UNSUPPORTED_PURPOSE;
550     OperationFactory* factory = key->key_factory()->GetOperationFactory(request.purpose);
551     if (!factory) return;
552 
553     OperationPtr operation(
554         factory->CreateOperation(move(*key), request.additional_params, &response->error));
555     if (operation.get() == nullptr) return;
556 
557     if (operation->authorizations().Contains(TAG_TRUSTED_CONFIRMATION_REQUIRED)) {
558         if (!operation->create_confirmation_verifier_buffer()) {
559             response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
560             return;
561         }
562     }
563 
564     if (context_->enforcement_policy()) {
565         km_id_t key_id;
566         response->error = KM_ERROR_UNKNOWN_ERROR;
567         if (!context_->enforcement_policy()->CreateKeyId(request.key_blob, &key_id)) return;
568         operation->set_key_id(key_id);
569         response->error = context_->enforcement_policy()->AuthorizeOperation(
570             request.purpose, key_id, operation->authorizations(), request.additional_params,
571             0 /* op_handle */, true /* is_begin_operation */);
572         if (response->error != KM_ERROR_OK) return;
573     }
574 
575     response->output_params.Clear();
576     response->error = operation->Begin(request.additional_params, &response->output_params);
577     if (response->error != KM_ERROR_OK) return;
578 
579     response->op_handle = operation->operation_handle();
580     response->error = operation_table_->Add(move(operation));
581 }
582 
UpdateOperation(const UpdateOperationRequest & request,UpdateOperationResponse * response)583 void AndroidKeymaster::UpdateOperation(const UpdateOperationRequest& request,
584                                        UpdateOperationResponse* response) {
585     if (response == nullptr) return;
586 
587     response->error = KM_ERROR_INVALID_OPERATION_HANDLE;
588     Operation* operation = operation_table_->Find(request.op_handle);
589     if (operation == nullptr) return;
590 
591     Buffer* confirmation_verifier_buffer = operation->get_confirmation_verifier_buffer();
592     if (confirmation_verifier_buffer != nullptr) {
593         size_t input_num_bytes = request.input.available_read();
594         if (input_num_bytes + confirmation_verifier_buffer->available_read() >
595             kConfirmationMessageMaxSize + kConfirmationTokenMessageTagSize) {
596             response->error = KM_ERROR_INVALID_ARGUMENT;
597             operation_table_->Delete(request.op_handle);
598             return;
599         }
600         if (!confirmation_verifier_buffer->reserve(input_num_bytes)) {
601             response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
602             operation_table_->Delete(request.op_handle);
603             return;
604         }
605         confirmation_verifier_buffer->write(request.input.peek_read(), input_num_bytes);
606     }
607 
608     if (context_->enforcement_policy()) {
609         response->error = context_->enforcement_policy()->AuthorizeOperation(
610             operation->purpose(), operation->key_id(), operation->authorizations(),
611             request.additional_params, request.op_handle, false /* is_begin_operation */);
612         if (response->error != KM_ERROR_OK) {
613             operation_table_->Delete(request.op_handle);
614             return;
615         }
616     }
617 
618     response->error =
619         operation->Update(request.additional_params, request.input, &response->output_params,
620                           &response->output, &response->input_consumed);
621     if (response->error != KM_ERROR_OK) {
622         // Any error invalidates the operation.
623         operation_table_->Delete(request.op_handle);
624     }
625 }
626 
FinishOperation(const FinishOperationRequest & request,FinishOperationResponse * response)627 void AndroidKeymaster::FinishOperation(const FinishOperationRequest& request,
628                                        FinishOperationResponse* response) {
629     if (response == nullptr) return;
630 
631     response->error = KM_ERROR_INVALID_OPERATION_HANDLE;
632     Operation* operation = operation_table_->Find(request.op_handle);
633     if (operation == nullptr) return;
634 
635     Buffer* confirmation_verifier_buffer = operation->get_confirmation_verifier_buffer();
636     if (confirmation_verifier_buffer != nullptr) {
637         size_t input_num_bytes = request.input.available_read();
638         if (input_num_bytes + confirmation_verifier_buffer->available_read() >
639             kConfirmationMessageMaxSize + kConfirmationTokenMessageTagSize) {
640             response->error = KM_ERROR_INVALID_ARGUMENT;
641             operation_table_->Delete(request.op_handle);
642             return;
643         }
644         if (!confirmation_verifier_buffer->reserve(input_num_bytes)) {
645             response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
646             operation_table_->Delete(request.op_handle);
647             return;
648         }
649         confirmation_verifier_buffer->write(request.input.peek_read(), input_num_bytes);
650     }
651 
652     if (context_->enforcement_policy()) {
653         response->error = context_->enforcement_policy()->AuthorizeOperation(
654             operation->purpose(), operation->key_id(), operation->authorizations(),
655             request.additional_params, request.op_handle, false /* is_begin_operation */);
656         if (response->error != KM_ERROR_OK) {
657             operation_table_->Delete(request.op_handle);
658             return;
659         }
660     }
661 
662     response->error = operation->Finish(request.additional_params, request.input, request.signature,
663                                         &response->output_params, &response->output);
664     if (response->error != KM_ERROR_OK) {
665         operation_table_->Delete(request.op_handle);
666         return;
667     }
668 
669     // Invalidate the single use key from secure storage after finish.
670     if (operation->hw_enforced().Contains(TAG_USAGE_COUNT_LIMIT, 1) &&
671         context_->secure_key_storage() != nullptr) {
672         response->error = context_->secure_key_storage()->DeleteKey(operation->key_id());
673     }
674 
675     // If the operation succeeded and TAG_TRUSTED_CONFIRMATION_REQUIRED was
676     // set, the input must be checked against the confirmation token.
677     if (response->error == KM_ERROR_OK && confirmation_verifier_buffer != nullptr) {
678         keymaster_blob_t confirmation_token_blob;
679         if (!request.additional_params.GetTagValue(TAG_CONFIRMATION_TOKEN,
680                                                    &confirmation_token_blob)) {
681             response->error = KM_ERROR_NO_USER_CONFIRMATION;
682             response->output.Clear();
683         } else {
684             if (confirmation_token_blob.data_length != kConfirmationTokenSize) {
685                 LOG_E("TAG_CONFIRMATION_TOKEN wrong size, was %zd expected %zd",
686                       confirmation_token_blob.data_length, kConfirmationTokenSize);
687                 response->error = KM_ERROR_INVALID_ARGUMENT;
688                 response->output.Clear();
689             } else {
690                 keymaster_error_t verification_result = context_->CheckConfirmationToken(
691                     confirmation_verifier_buffer->begin(),
692                     confirmation_verifier_buffer->available_read(), confirmation_token_blob.data);
693                 if (verification_result != KM_ERROR_OK) {
694                     response->error = verification_result;
695                     response->output.Clear();
696                 }
697             }
698         }
699     }
700 
701     operation_table_->Delete(request.op_handle);
702 }
703 
AbortOperation(const AbortOperationRequest & request,AbortOperationResponse * response)704 void AndroidKeymaster::AbortOperation(const AbortOperationRequest& request,
705                                       AbortOperationResponse* response) {
706     if (!response) return;
707 
708     Operation* operation = operation_table_->Find(request.op_handle);
709     if (!operation) {
710         response->error = KM_ERROR_INVALID_OPERATION_HANDLE;
711         return;
712     }
713 
714     response->error = operation->Abort();
715     operation_table_->Delete(request.op_handle);
716 }
717 
ExportKey(const ExportKeyRequest & request,ExportKeyResponse * response)718 void AndroidKeymaster::ExportKey(const ExportKeyRequest& request, ExportKeyResponse* response) {
719     if (response == nullptr) return;
720 
721     UniquePtr<Key> key;
722     response->error =
723         context_->ParseKeyBlob(KeymasterKeyBlob(request.key_blob), request.additional_params, &key);
724     if (response->error != KM_ERROR_OK) return;
725 
726     UniquePtr<uint8_t[]> out_key;
727     size_t size;
728     response->error = key->formatted_key_material(request.key_format, &out_key, &size);
729     if (response->error == KM_ERROR_OK) {
730         response->key_data = out_key.release();
731         response->key_data_length = size;
732     }
733 }
734 
AttestKey(const AttestKeyRequest & request,AttestKeyResponse * response)735 void AndroidKeymaster::AttestKey(const AttestKeyRequest& request, AttestKeyResponse* response) {
736     if (!response) return;
737 
738     UniquePtr<Key> key = LoadKey(request.key_blob, request.attest_params, &response->error);
739     if (!key) return;
740 
741     keymaster_blob_t attestation_application_id;
742     if (request.attest_params.GetTagValue(TAG_ATTESTATION_APPLICATION_ID,
743                                           &attestation_application_id)) {
744         key->sw_enforced().push_back(TAG_ATTESTATION_APPLICATION_ID, attestation_application_id);
745     }
746 
747     response->certificate_chain =
748         context_->GenerateAttestation(*key, request.attest_params, {} /* attestation_signing_key */,
749                                       {} /* issuer_subject */, &response->error);
750 }
751 
UpgradeKey(const UpgradeKeyRequest & request,UpgradeKeyResponse * response)752 void AndroidKeymaster::UpgradeKey(const UpgradeKeyRequest& request, UpgradeKeyResponse* response) {
753     if (!response) return;
754 
755     KeymasterKeyBlob upgraded_key;
756     response->error = context_->UpgradeKeyBlob(KeymasterKeyBlob(request.key_blob),
757                                                request.upgrade_params, &upgraded_key);
758     if (response->error != KM_ERROR_OK) return;
759     response->upgraded_key = upgraded_key.release();
760 }
761 
ImportKey(const ImportKeyRequest & request,ImportKeyResponse * response)762 void AndroidKeymaster::ImportKey(const ImportKeyRequest& request, ImportKeyResponse* response) {
763     if (response == nullptr) return;
764 
765     const KeyFactory* factory =
766         get_key_factory(request.key_description, *context_, &response->error);
767     if (!factory) return;
768 
769     if (context_->enforcement_policy() &&
770         request.key_description.GetTagValue(TAG_EARLY_BOOT_ONLY) &&
771         !context_->enforcement_policy()->in_early_boot()) {
772         response->error = KM_ERROR_EARLY_BOOT_ENDED;
773         return;
774     }
775 
776     UniquePtr<Key> attest_key;
777     if (request.attestation_signing_key_blob.key_material_size) {
778 
779         attest_key =
780             LoadKey(request.attestation_signing_key_blob, {} /* params */, &response->error);
781         if (response->error != KM_ERROR_OK) return;
782     }
783 
784     response->error = factory->ImportKey(request.key_description,  //
785                                          request.key_format,       //
786                                          request.key_data,         //
787                                          move(attest_key),         //
788                                          request.issuer_subject,   //
789                                          &response->key_blob,      //
790                                          &response->enforced,      //
791                                          &response->unenforced,    //
792                                          &response->certificate_chain);
793 }
794 
DeleteKey(const DeleteKeyRequest & request,DeleteKeyResponse * response)795 void AndroidKeymaster::DeleteKey(const DeleteKeyRequest& request, DeleteKeyResponse* response) {
796     if (!response) return;
797     response->error = context_->DeleteKey(KeymasterKeyBlob(request.key_blob));
798 }
799 
DeleteAllKeys(const DeleteAllKeysRequest &,DeleteAllKeysResponse * response)800 void AndroidKeymaster::DeleteAllKeys(const DeleteAllKeysRequest&, DeleteAllKeysResponse* response) {
801     if (!response) return;
802     response->error = context_->DeleteAllKeys();
803 }
804 
Configure(const ConfigureRequest & request,ConfigureResponse * response)805 void AndroidKeymaster::Configure(const ConfigureRequest& request, ConfigureResponse* response) {
806     if (!response) return;
807     response->error = context_->SetSystemVersion(request.os_version, request.os_patchlevel);
808 }
809 
810 ConfigureVendorPatchlevelResponse
ConfigureVendorPatchlevel(const ConfigureVendorPatchlevelRequest & request)811 AndroidKeymaster::ConfigureVendorPatchlevel(const ConfigureVendorPatchlevelRequest& request) {
812     ConfigureVendorPatchlevelResponse rsp(message_version());
813     rsp.error = context_->SetVendorPatchlevel(request.vendor_patchlevel);
814     return rsp;
815 }
816 
817 ConfigureBootPatchlevelResponse
ConfigureBootPatchlevel(const ConfigureBootPatchlevelRequest & request)818 AndroidKeymaster::ConfigureBootPatchlevel(const ConfigureBootPatchlevelRequest& request) {
819     ConfigureBootPatchlevelResponse rsp(message_version());
820     rsp.error = context_->SetBootPatchlevel(request.boot_patchlevel);
821     return rsp;
822 }
823 
has_operation(keymaster_operation_handle_t op_handle) const824 bool AndroidKeymaster::has_operation(keymaster_operation_handle_t op_handle) const {
825     return operation_table_->Find(op_handle) != nullptr;
826 }
827 
LoadKey(const keymaster_key_blob_t & key_blob,const AuthorizationSet & additional_params,keymaster_error_t * error)828 UniquePtr<Key> AndroidKeymaster::LoadKey(const keymaster_key_blob_t& key_blob,
829                                          const AuthorizationSet& additional_params,
830                                          keymaster_error_t* error) {
831     if (!error) return {};
832 
833     UniquePtr<Key> key;
834     KeymasterKeyBlob key_material;
835     *error = context_->ParseKeyBlob(KeymasterKeyBlob(key_blob), additional_params, &key);
836     if (*error != KM_ERROR_OK) return {};
837 
838     *error = CheckVersionInfo(key->hw_enforced(), key->sw_enforced(), *context_);
839     if (*error != KM_ERROR_OK) return {};
840 
841     return key;
842 }
843 
ImportWrappedKey(const ImportWrappedKeyRequest & request,ImportWrappedKeyResponse * response)844 void AndroidKeymaster::ImportWrappedKey(const ImportWrappedKeyRequest& request,
845                                         ImportWrappedKeyResponse* response) {
846     if (!response) return;
847 
848     KeymasterKeyBlob secret_key;
849     AuthorizationSet key_description;
850     keymaster_key_format_t key_format;
851 
852     response->error =
853         context_->UnwrapKey(request.wrapped_key, request.wrapping_key, request.additional_params,
854                             request.masking_key, &key_description, &key_format, &secret_key);
855 
856     if (response->error != KM_ERROR_OK) {
857         return;
858     }
859 
860     int sid_idx = key_description.find(TAG_USER_SECURE_ID);
861     if (sid_idx != -1) {
862         uint8_t sids = key_description[sid_idx].long_integer;
863         if (!key_description.erase(sid_idx)) {
864             response->error = KM_ERROR_UNKNOWN_ERROR;
865             return;
866         }
867         if (sids & HW_AUTH_PASSWORD) {
868             key_description.push_back(TAG_USER_SECURE_ID, request.password_sid);
869         }
870         if (sids & HW_AUTH_FINGERPRINT) {
871             key_description.push_back(TAG_USER_SECURE_ID, request.biometric_sid);
872         }
873 
874         if (context_->GetKmVersion() >= KmVersion::KEYMINT_1) {
875             key_description.push_back(TAG_CERTIFICATE_NOT_BEFORE, 0);
876             key_description.push_back(TAG_CERTIFICATE_NOT_AFTER, kUndefinedExpirationDateTime);
877         }
878     }
879 
880     const KeyFactory* factory = get_key_factory(key_description, *context_, &response->error);
881     if (!factory) return;
882 
883     response->error = factory->ImportKey(key_description,          //
884                                          key_format,               //
885                                          secret_key,               //
886                                          {} /* attest_key */,      //
887                                          {} /* issuer_subject */,  //
888                                          &response->key_blob,      //
889                                          &response->enforced,      //
890                                          &response->unenforced,    //
891                                          &response->certificate_chain);
892 }
893 
EarlyBootEnded()894 EarlyBootEndedResponse AndroidKeymaster::EarlyBootEnded() {
895     if (context_->enforcement_policy()) {
896         context_->enforcement_policy()->early_boot_ended();
897     }
898     return EarlyBootEndedResponse(message_version());
899 }
900 
DeviceLocked(const DeviceLockedRequest & request)901 DeviceLockedResponse AndroidKeymaster::DeviceLocked(const DeviceLockedRequest& request) {
902     if (context_->enforcement_policy()) {
903         context_->enforcement_policy()->device_locked(request.passwordOnly);
904     }
905     return DeviceLockedResponse(message_version());
906 }
907 
908 }  // namespace keymaster
909