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 <utility>
20 #include <vector>
21 
22 #include <assert.h>
23 #include <string.h>
24 
25 #include <stddef.h>
26 
27 #include <cppbor.h>
28 #include <cppbor_parse.h>
29 
30 #include <keymaster/UniquePtr.h>
31 #include <keymaster/android_keymaster_utils.h>
32 #include <keymaster/attestation_context.h>
33 #include <keymaster/cppcose/cppcose.h>
34 #include <keymaster/key.h>
35 #include <keymaster/key_blob_utils/ae.h>
36 #include <keymaster/key_factory.h>
37 #include <keymaster/keymaster_context.h>
38 #include <keymaster/km_date.h>
39 #include <keymaster/km_openssl/openssl_err.h>
40 #include <keymaster/km_openssl/openssl_utils.h>
41 #include <keymaster/logger.h>
42 #include <keymaster/operation.h>
43 #include <keymaster/operation_table.h>
44 #include <keymaster/remote_provisioning_utils.h>
45 #include <keymaster/secure_deletion_secret_storage.h>
46 
47 namespace keymaster {
48 
49 namespace {
50 
51 using cppcose::constructCoseEncrypt;
52 using cppcose::constructCoseMac0;
53 using cppcose::CoseKey;
54 using cppcose::EC2;
55 using cppcose::ES256;
56 using cppcose::generateCoseMac0Mac;
57 using cppcose::kAesGcmNonceLength;
58 using cppcose::P256;
59 using cppcose::x25519_HKDF_DeriveKey;
60 
61 template <keymaster_tag_t T>
CheckPatchLevel(const AuthorizationSet & tee_enforced,const AuthorizationSet & sw_enforced,TypedTag<KM_UINT,T> tag,uint32_t current_patchlevel)62 keymaster_error_t CheckPatchLevel(const AuthorizationSet& tee_enforced,
63                                   const AuthorizationSet& sw_enforced, TypedTag<KM_UINT, T> tag,
64                                   uint32_t current_patchlevel) {
65     uint32_t key_patchlevel;
66     if (tee_enforced.GetTagValue(tag, &key_patchlevel) ||
67         sw_enforced.GetTagValue(tag, &key_patchlevel)) {
68         if (key_patchlevel < current_patchlevel) {
69             return KM_ERROR_KEY_REQUIRES_UPGRADE;
70         } else if (key_patchlevel > current_patchlevel) {
71             LOG_E("Key blob invalid! key patchlevel %lu is > current patchlevel %lu",
72                   (unsigned long)key_patchlevel, (unsigned long)current_patchlevel);
73             return KM_ERROR_INVALID_KEY_BLOB;
74         }
75     }
76     return KM_ERROR_OK;
77 }
78 
CheckVersionInfo(const AuthorizationSet & tee_enforced,const AuthorizationSet & sw_enforced,const KeymasterContext & context)79 keymaster_error_t CheckVersionInfo(const AuthorizationSet& tee_enforced,
80                                    const AuthorizationSet& sw_enforced,
81                                    const KeymasterContext& context) {
82     uint32_t os_version;
83     uint32_t os_patchlevel;
84     context.GetSystemVersion(&os_version, &os_patchlevel);
85 
86     keymaster_error_t err =
87         CheckPatchLevel(tee_enforced, sw_enforced, TAG_OS_PATCHLEVEL, os_patchlevel);
88     if (err != KM_ERROR_OK) return err;
89 
90     // Also check the vendor and boot patchlevels if available.
91     auto vendor_patchlevel = context.GetVendorPatchlevel();
92     if (vendor_patchlevel.has_value()) {
93         err = CheckPatchLevel(tee_enforced, sw_enforced, TAG_VENDOR_PATCHLEVEL,
94                               vendor_patchlevel.value());
95         if (err != KM_ERROR_OK) return err;
96     }
97     auto boot_patchlevel = context.GetBootPatchlevel();
98     if (boot_patchlevel.has_value()) {
99         err = CheckPatchLevel(tee_enforced, sw_enforced, TAG_BOOT_PATCHLEVEL,
100                               boot_patchlevel.value());
101         if (err != KM_ERROR_OK) return err;
102     }
103 
104     return KM_ERROR_OK;
105 }
106 
107 const keymaster_key_param_t kKeyMintEcdsaP256Params[] = {
108     Authorization(TAG_PURPOSE, KM_PURPOSE_ATTEST_KEY),
109     Authorization(TAG_ALGORITHM, KM_ALGORITHM_EC), Authorization(TAG_KEY_SIZE, 256),
110     Authorization(TAG_DIGEST, KM_DIGEST_SHA_2_256), Authorization(TAG_EC_CURVE, KM_EC_CURVE_P_256),
111     Authorization(TAG_NO_AUTH_REQUIRED),
112     // The certificate generated by KM will be discarded, these values don't matter.
113     Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0), Authorization(TAG_CERTIFICATE_NOT_AFTER, 0)};
114 
getMacFunction(bool test_mode,RemoteProvisioningContext * rem_prov_ctx)115 cppcose::HmacSha256Function getMacFunction(bool test_mode,
116                                            RemoteProvisioningContext* rem_prov_ctx) {
117     if (test_mode) {
118         return [](const cppcose::bytevec& input) {
119             const cppcose::bytevec macKey(32);
120             return cppcose::generateHmacSha256(macKey, input);
121         };
122     }
123 
124     return [rem_prov_ctx](const cppcose::bytevec& input) -> cppcose::ErrMsgOr<cppcose::HmacSha256> {
125         auto mac = rem_prov_ctx->GenerateHmacSha256(input);
126         if (!mac) {
127             return "Remote provisioning context failed to sign MAC.";
128         }
129         return *mac;
130     };
131 }
132 
blob2Pair(const keymaster_blob_t & blob)133 std::pair<const uint8_t*, size_t> blob2Pair(const keymaster_blob_t& blob) {
134     return {blob.data, blob.data_length};
135 }
136 
137 constexpr int kMaxChallengeSizeV2 = 64;
138 constexpr int kP256AffinePointSize = 32;
139 constexpr int kRoTVersion1 = 40001;
140 
141 }  // anonymous namespace
142 
AndroidKeymaster(KeymasterContext * context,size_t operation_table_size,int32_t message_version)143 AndroidKeymaster::AndroidKeymaster(KeymasterContext* context, size_t operation_table_size,
144                                    int32_t message_version)
145     : context_(context), operation_table_(new(std::nothrow) OperationTable(operation_table_size)),
146       message_version_(message_version) {}
147 
~AndroidKeymaster()148 AndroidKeymaster::~AndroidKeymaster() {}
149 
AndroidKeymaster(AndroidKeymaster && other)150 AndroidKeymaster::AndroidKeymaster(AndroidKeymaster&& other)
151     : context_(std::move(other.context_)), operation_table_(std::move(other.operation_table_)),
152       message_version_(other.message_version_) {}
153 
154 // TODO(swillden): Unify support analysis.  Right now, we have per-keytype methods that determine if
155 // specific modes, padding, etc. are supported for that key type, and AndroidKeymaster also has
156 // methods that return the same information.  They'll get out of sync.  Best to put the knowledge in
157 // the keytypes and provide some mechanism for AndroidKeymaster to query the keytypes for the
158 // information.
159 
160 template <typename T>
check_supported(const KeymasterContext & context,keymaster_algorithm_t algorithm,SupportedResponse<T> * response)161 bool check_supported(const KeymasterContext& context, keymaster_algorithm_t algorithm,
162                      SupportedResponse<T>* response) {
163     if (context.GetKeyFactory(algorithm) == nullptr) {
164         response->error = KM_ERROR_UNSUPPORTED_ALGORITHM;
165         return false;
166     }
167     return true;
168 }
169 
GetVersion(const GetVersionRequest &,GetVersionResponse * rsp)170 void AndroidKeymaster::GetVersion(const GetVersionRequest&, GetVersionResponse* rsp) {
171     if (rsp == nullptr) return;
172 
173     rsp->major_ver = 2;
174     rsp->minor_ver = 0;
175     rsp->subminor_ver = 0;
176     rsp->error = KM_ERROR_OK;
177 }
178 
GetVersion2(const GetVersion2Request & req)179 GetVersion2Response AndroidKeymaster::GetVersion2(const GetVersion2Request& req) {
180     GetVersion2Response rsp;
181     rsp.km_version = context_->GetKmVersion();
182     rsp.km_date = kKmDate;
183     rsp.max_message_version = MessageVersion(rsp.km_version, rsp.km_date);
184     rsp.error = KM_ERROR_OK;
185 
186     // Determine what message version we should use.
187     message_version_ = NegotiateMessageVersion(req, rsp);
188 
189     LOG_D("GetVersion2 results: %d, %d, %d, %d", static_cast<int>(rsp.km_version),
190           rsp.km_date, rsp.max_message_version, message_version_);
191     return rsp;
192 }
193 
SupportedAlgorithms(const SupportedAlgorithmsRequest &,SupportedAlgorithmsResponse * response)194 void AndroidKeymaster::SupportedAlgorithms(const SupportedAlgorithmsRequest& /* request */,
195                                            SupportedAlgorithmsResponse* response) {
196     if (response == nullptr) return;
197 
198     response->error = KM_ERROR_OK;
199 
200     size_t algorithm_count = 0;
201     const keymaster_algorithm_t* algorithms = context_->GetSupportedAlgorithms(&algorithm_count);
202     if (algorithm_count == 0) return;
203     response->results_length = algorithm_count;
204     response->results = dup_array(algorithms, algorithm_count);
205     if (!response->results) response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
206 }
207 
208 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)209 void GetSupported(const KeymasterContext& context, keymaster_algorithm_t algorithm,
210                   keymaster_purpose_t purpose,
211                   const T* (OperationFactory::*get_supported_method)(size_t* count) const,
212                   SupportedResponse<T>* response) {
213     if (response == nullptr || !check_supported(context, algorithm, response)) return;
214 
215     const OperationFactory* factory = context.GetOperationFactory(algorithm, purpose);
216     if (!factory) {
217         response->error = KM_ERROR_UNSUPPORTED_PURPOSE;
218         return;
219     }
220 
221     size_t count;
222     const T* supported = (factory->*get_supported_method)(&count);
223     response->SetResults(supported, count);
224 }
225 
SupportedBlockModes(const SupportedBlockModesRequest & request,SupportedBlockModesResponse * response)226 void AndroidKeymaster::SupportedBlockModes(const SupportedBlockModesRequest& request,
227                                            SupportedBlockModesResponse* response) {
228     GetSupported(*context_, request.algorithm, request.purpose,
229                  &OperationFactory::SupportedBlockModes, response);
230 }
231 
SupportedPaddingModes(const SupportedPaddingModesRequest & request,SupportedPaddingModesResponse * response)232 void AndroidKeymaster::SupportedPaddingModes(const SupportedPaddingModesRequest& request,
233                                              SupportedPaddingModesResponse* response) {
234     GetSupported(*context_, request.algorithm, request.purpose,
235                  &OperationFactory::SupportedPaddingModes, response);
236 }
237 
SupportedDigests(const SupportedDigestsRequest & request,SupportedDigestsResponse * response)238 void AndroidKeymaster::SupportedDigests(const SupportedDigestsRequest& request,
239                                         SupportedDigestsResponse* response) {
240     GetSupported(*context_, request.algorithm, request.purpose, &OperationFactory::SupportedDigests,
241                  response);
242 }
243 
SupportedImportFormats(const SupportedImportFormatsRequest & request,SupportedImportFormatsResponse * response)244 void AndroidKeymaster::SupportedImportFormats(const SupportedImportFormatsRequest& request,
245                                               SupportedImportFormatsResponse* response) {
246     if (response == nullptr || !check_supported(*context_, request.algorithm, response)) return;
247 
248     size_t count;
249     const keymaster_key_format_t* formats =
250         context_->GetKeyFactory(request.algorithm)->SupportedImportFormats(&count);
251     response->SetResults(formats, count);
252 }
253 
SupportedExportFormats(const SupportedExportFormatsRequest & request,SupportedExportFormatsResponse * response)254 void AndroidKeymaster::SupportedExportFormats(const SupportedExportFormatsRequest& request,
255                                               SupportedExportFormatsResponse* response) {
256     if (response == nullptr || !check_supported(*context_, request.algorithm, response)) return;
257 
258     size_t count;
259     const keymaster_key_format_t* formats =
260         context_->GetKeyFactory(request.algorithm)->SupportedExportFormats(&count);
261     response->SetResults(formats, count);
262 }
263 
GetHmacSharingParameters()264 GetHmacSharingParametersResponse AndroidKeymaster::GetHmacSharingParameters() {
265     GetHmacSharingParametersResponse response(message_version());
266     KeymasterEnforcement* policy = context_->enforcement_policy();
267     if (!policy) {
268         response.error = KM_ERROR_UNIMPLEMENTED;
269         return response;
270     }
271 
272     response.error = policy->GetHmacSharingParameters(&response.params);
273     return response;
274 }
275 
276 ComputeSharedHmacResponse
ComputeSharedHmac(const ComputeSharedHmacRequest & request)277 AndroidKeymaster::ComputeSharedHmac(const ComputeSharedHmacRequest& request) {
278     ComputeSharedHmacResponse response(message_version());
279     KeymasterEnforcement* policy = context_->enforcement_policy();
280     if (!policy) {
281         response.error = KM_ERROR_UNIMPLEMENTED;
282         return response;
283     }
284     response.error = policy->ComputeSharedHmac(request.params_array, &response.sharing_check);
285 
286     return response;
287 }
288 
289 VerifyAuthorizationResponse
VerifyAuthorization(const VerifyAuthorizationRequest & request)290 AndroidKeymaster::VerifyAuthorization(const VerifyAuthorizationRequest& request) {
291     KeymasterEnforcement* policy = context_->enforcement_policy();
292     if (!policy) {
293         VerifyAuthorizationResponse response(message_version());
294         response.error = KM_ERROR_UNIMPLEMENTED;
295         return response;
296     }
297 
298     return policy->VerifyAuthorization(request);
299 }
300 
GenerateTimestampToken(GenerateTimestampTokenRequest & request,GenerateTimestampTokenResponse * response)301 void AndroidKeymaster::GenerateTimestampToken(GenerateTimestampTokenRequest& request,
302                                               GenerateTimestampTokenResponse* response) {
303     KeymasterEnforcement* policy = context_->enforcement_policy();
304     if (!policy) {
305         response->error = KM_ERROR_UNIMPLEMENTED;
306     } else {
307         response->token.challenge = request.challenge;
308         response->error = policy->GenerateTimestampToken(&response->token);
309     }
310 }
311 
AddRngEntropy(const AddEntropyRequest & request,AddEntropyResponse * response)312 void AndroidKeymaster::AddRngEntropy(const AddEntropyRequest& request,
313                                      AddEntropyResponse* response) {
314     response->error = context_->AddRngEntropy(request.random_data.peek_read(),
315                                               request.random_data.available_read());
316 }
317 
get_key_factory(const AuthorizationSet & key_description,const KeymasterContext & context,keymaster_error_t * error)318 const KeyFactory* get_key_factory(const AuthorizationSet& key_description,
319                                   const KeymasterContext& context,  //
320                                   keymaster_error_t* error) {
321     keymaster_algorithm_t algorithm;
322     const KeyFactory* factory{};
323     if (!key_description.GetTagValue(TAG_ALGORITHM, &algorithm) ||
324         !(factory = context.GetKeyFactory(algorithm))) {
325         *error = KM_ERROR_UNSUPPORTED_ALGORITHM;
326     }
327     return factory;
328 }
329 
GenerateKey(const GenerateKeyRequest & request,GenerateKeyResponse * response)330 void AndroidKeymaster::GenerateKey(const GenerateKeyRequest& request,
331                                    GenerateKeyResponse* response) {
332     if (response == nullptr) return;
333 
334     const KeyFactory* factory =
335         get_key_factory(request.key_description, *context_, &response->error);
336     if (!factory) return;
337 
338     UniquePtr<Key> attest_key;
339     if (request.attestation_signing_key_blob.key_material_size) {
340         attest_key = LoadKey(request.attestation_signing_key_blob, request.attest_key_params,
341                              &response->error);
342         if (response->error != KM_ERROR_OK) return;
343     }
344 
345     if (request.key_description.Contains(TAG_PURPOSE, KM_PURPOSE_ATTEST_KEY) &&
346         request.key_description.GetTagCount(TAG_PURPOSE) > 1) {
347         // ATTEST_KEY cannot be combined with any other purpose.
348         response->error = KM_ERROR_INCOMPATIBLE_PURPOSE;
349         return;
350     }
351 
352     response->enforced.Clear();
353     response->unenforced.Clear();
354     response->error = factory->GenerateKey(request.key_description,
355                                            std::move(attest_key),  //
356                                            request.issuer_subject,
357                                            &response->key_blob,  //
358                                            &response->enforced,
359                                            &response->unenforced,  //
360                                            &response->certificate_chain);
361 }
362 
363 constexpr int kRkpVersionWithoutSuperencryption = 3;
364 
GenerateRkpKey(const GenerateRkpKeyRequest & request,GenerateRkpKeyResponse * response)365 void AndroidKeymaster::GenerateRkpKey(const GenerateRkpKeyRequest& request,
366                                       GenerateRkpKeyResponse* response) {
367     if (response == nullptr) return;
368 
369     auto rem_prov_ctx = context_->GetRemoteProvisioningContext();
370     if (!rem_prov_ctx) {
371         response->error = static_cast<keymaster_error_t>(kStatusFailed);
372         return;
373     }
374 
375     GetHwInfoResponse hwInfo(message_version());
376     rem_prov_ctx->GetHwInfo(&hwInfo);
377     if (hwInfo.version >= kRkpVersionWithoutSuperencryption && request.test_mode) {
378         response->error = static_cast<keymaster_error_t>(kStatusRemoved);
379         return;
380     }
381 
382     // Generate the keypair that will become the attestation key.
383     GenerateKeyRequest gen_key_request(message_version_);
384     gen_key_request.key_description.Reinitialize(kKeyMintEcdsaP256Params,
385                                                  array_length(kKeyMintEcdsaP256Params));
386     GenerateKeyResponse gen_key_response(message_version_);
387     GenerateKey(gen_key_request, &gen_key_response);
388     if (gen_key_response.error != KM_ERROR_OK) {
389         response->error = static_cast<keymaster_error_t>(kStatusFailed);
390         return;
391     }
392 
393     // Retrieve the certificate and parse it to build a COSE_Key
394     if (gen_key_response.certificate_chain.entry_count != 1) {
395         // Error: Need the single non-signed certificate with the public key in it.
396         response->error = static_cast<keymaster_error_t>(kStatusFailed);
397         return;
398     }
399     std::vector<uint8_t> x_coord(kP256AffinePointSize);
400     std::vector<uint8_t> y_coord(kP256AffinePointSize);
401     response->error =
402         GetEcdsa256KeyFromCert(gen_key_response.certificate_chain.begin(), x_coord.data(),
403                                x_coord.size(), y_coord.data(), y_coord.size());
404     if (response->error != KM_ERROR_OK) {
405         response->error = static_cast<keymaster_error_t>(kStatusFailed);
406         return;
407     }
408 
409     cppbor::Map cose_public_key_map = cppbor::Map()
410                                           .add(CoseKey::KEY_TYPE, EC2)
411                                           .add(CoseKey::ALGORITHM, ES256)
412                                           .add(CoseKey::CURVE, P256)
413                                           .add(CoseKey::PUBKEY_X, x_coord)
414                                           .add(CoseKey::PUBKEY_Y, y_coord);
415     if (request.test_mode) {
416         cose_public_key_map.add(CoseKey::TEST_KEY, cppbor::Null());
417     }
418 
419     std::vector<uint8_t> cosePublicKey = cose_public_key_map.canonicalize().encode();
420 
421     auto macFunction = getMacFunction(request.test_mode, rem_prov_ctx);
422     auto macedKey = constructCoseMac0(macFunction, {} /* externalAad */, cosePublicKey);
423     if (!macedKey) {
424         response->error = static_cast<keymaster_error_t>(kStatusFailed);
425         return;
426     }
427     std::vector<uint8_t> enc = macedKey->encode();
428     response->maced_public_key = KeymasterBlob(enc.data(), enc.size());
429     response->key_blob = std::move(gen_key_response.key_blob);
430     response->error = KM_ERROR_OK;
431 }
432 
GenerateCsr(const GenerateCsrRequest & request,GenerateCsrResponse * response)433 void AndroidKeymaster::GenerateCsr(const GenerateCsrRequest& request,
434                                    GenerateCsrResponse* response) {
435     if (response == nullptr) return;
436 
437     auto rem_prov_ctx = context_->GetRemoteProvisioningContext();
438     if (!rem_prov_ctx) {
439         LOG_E("Couldn't get a pointer to the remote provisioning context, returned null.");
440         response->error = static_cast<keymaster_error_t>(kStatusFailed);
441         return;
442     }
443 
444     GetHwInfoResponse hwInfo(message_version());
445     rem_prov_ctx->GetHwInfo(&hwInfo);
446     if (hwInfo.version >= kRkpVersionWithoutSuperencryption) {
447         response->error = static_cast<keymaster_error_t>(kStatusRemoved);
448         return;
449     }
450 
451     auto macFunction = getMacFunction(request.test_mode, rem_prov_ctx);
452     auto pubKeysToSign = validateAndExtractPubkeys(request.test_mode, request.num_keys,
453                                                    request.keys_to_sign_array, macFunction);
454     if (!pubKeysToSign.isOk()) {
455         LOG_E("Failed to validate and extract the public keys for the CSR");
456         response->error = static_cast<keymaster_error_t>(pubKeysToSign.moveError());
457         return;
458     }
459 
460     std::vector<uint8_t> ephemeral_mac_key(SHA256_DIGEST_LENGTH, 0 /* value */);
461     if (GenerateRandom(ephemeral_mac_key.data(), ephemeral_mac_key.size()) != KM_ERROR_OK) {
462         LOG_E("Failed to generate a random mac key.");
463         response->error = static_cast<keymaster_error_t>(kStatusFailed);
464         return;
465     }
466 
467     auto ephemeral_mac_function = [&ephemeral_mac_key](const cppcose::bytevec& input) {
468         return cppcose::generateHmacSha256(ephemeral_mac_key, input);
469     };
470 
471     auto pubKeysToSignMac = generateCoseMac0Mac(ephemeral_mac_function, std::vector<uint8_t>{},
472                                                 pubKeysToSign->encode());
473     if (!pubKeysToSignMac) {
474         LOG_E("Failed to generate COSE_Mac0 over the public keys to sign.");
475         response->error = static_cast<keymaster_error_t>(kStatusFailed);
476         return;
477     }
478     response->keys_to_sign_mac = KeymasterBlob(pubKeysToSignMac->data(), pubKeysToSignMac->size());
479 
480     std::unique_ptr<cppbor::Map> device_info_map =
481         rem_prov_ctx->CreateDeviceInfo(2 /* csrVersion */);
482     std::vector<uint8_t> device_info = device_info_map->encode();
483     response->device_info_blob = KeymasterBlob(device_info.data(), device_info.size());
484     auto protectedDataPayload = rem_prov_ctx->BuildProtectedDataPayload(
485         request.test_mode,  //
486         ephemeral_mac_key /* Payload */,
487         cppbor::Array() /* AAD */
488             .add(std::pair(request.challenge.begin(),
489                            request.challenge.end() - request.challenge.begin()))
490             .add(std::move(device_info_map))
491             .add(std::pair(pubKeysToSignMac->data(), pubKeysToSignMac->size()))
492             .encode());
493     if (!protectedDataPayload) {
494         LOG_E("Failed to construct ProtectedData: %s", protectedDataPayload.moveMessage().c_str());
495         response->error = static_cast<keymaster_error_t>(kStatusFailed);
496         return;
497     }
498 
499     std::vector<uint8_t> ephemeralPrivKey(X25519_PRIVATE_KEY_LEN);
500     std::vector<uint8_t> ephemeralPubKey(X25519_PUBLIC_VALUE_LEN);
501     X25519_keypair(ephemeralPubKey.data(), ephemeralPrivKey.data());
502 
503     auto eek = validateAndExtractEekPubAndId(request.test_mode, request.endpoint_enc_cert_chain);
504     if (!eek.isOk()) {
505         LOG_E("Failed to validate and extract the endpoint encryption key.");
506         response->error = static_cast<keymaster_error_t>(eek.moveError());
507         return;
508     }
509 
510     auto sessionKey =
511         x25519_HKDF_DeriveKey(ephemeralPubKey, ephemeralPrivKey, eek->first, true /* senderIsA */);
512     if (!sessionKey) {
513         LOG_E("Failed to derive the session key.");
514         response->error = static_cast<keymaster_error_t>(kStatusFailed);
515         return;
516     }
517 
518     std::vector<uint8_t> nonce(kAesGcmNonceLength, 0 /* value */);
519     if (GenerateRandom(nonce.data(), nonce.size()) != KM_ERROR_OK) {
520         LOG_E("Failed to generate a random nonce.");
521         response->error = static_cast<keymaster_error_t>(kStatusFailed);
522         return;
523     }
524     auto coseEncrypted = constructCoseEncrypt(*sessionKey,                       //
525                                               nonce,                             //
526                                               protectedDataPayload.moveValue(),  //
527                                               {},                                // aad
528                                               buildCertReqRecipients(ephemeralPubKey, eek->second));
529 
530     if (!coseEncrypted) {
531         LOG_E("Failed to construct a COSE_Encrypt ProtectedData structure");
532         response->error = static_cast<keymaster_error_t>(kStatusFailed);
533         return;
534     }
535     std::vector<uint8_t> payload = coseEncrypted->encode();
536     response->protected_data_blob = KeymasterBlob(payload.data(), payload.size());
537     response->error = KM_ERROR_OK;
538 }
539 
GenerateCsrV2(const GenerateCsrV2Request & request,GenerateCsrV2Response * response)540 void AndroidKeymaster::GenerateCsrV2(const GenerateCsrV2Request& request,
541                                      GenerateCsrV2Response* response) {
542 
543     if (response == nullptr) return;
544 
545     if (request.challenge.size() > kMaxChallengeSizeV2) {
546         LOG_E("Challenge is too large. %d expected. %zu actual.",
547               kMaxChallengeSizeV2,        //
548               request.challenge.size());  //
549         response->error = static_cast<keymaster_error_t>(kStatusFailed);
550         return;
551     }
552 
553     auto rem_prov_ctx = context_->GetRemoteProvisioningContext();
554     if (rem_prov_ctx == nullptr) {
555         LOG_E("Couldn't get a pointer to the remote provisioning context, returned null.");
556         response->error = static_cast<keymaster_error_t>(kStatusFailed);
557         return;
558     }
559 
560     auto macFunction = getMacFunction(false /* test_mode */, rem_prov_ctx);
561     auto pubKeys = validateAndExtractPubkeys(false /* test_mode */, request.num_keys,
562                                              request.keys_to_sign_array, macFunction);
563     if (!pubKeys.isOk()) {
564         LOG_E("Failed to validate and extract the public keys for the CSR");
565         response->error = static_cast<keymaster_error_t>(pubKeys.moveError());
566         return;
567     }
568 
569     auto csr = rem_prov_ctx->BuildCsr(
570         std::vector(request.challenge.begin(), request.challenge.end()), std::move(*pubKeys));
571     if (!csr) {
572         LOG_E("Failed to build CSR");
573         response->error = static_cast<keymaster_error_t>(kStatusFailed);
574         return;
575     }
576 
577     auto csr_blob = csr->encode();
578     response->csr = KeymasterBlob(csr_blob.data(), csr_blob.size());
579     response->error = KM_ERROR_OK;
580 }
581 
GetKeyCharacteristics(const GetKeyCharacteristicsRequest & request,GetKeyCharacteristicsResponse * response)582 void AndroidKeymaster::GetKeyCharacteristics(const GetKeyCharacteristicsRequest& request,
583                                              GetKeyCharacteristicsResponse* response) {
584     if (response == nullptr) return;
585 
586     UniquePtr<Key> key;
587     response->error =
588         context_->ParseKeyBlob(KeymasterKeyBlob(request.key_blob), request.additional_params, &key);
589     if (response->error != KM_ERROR_OK) return;
590 
591     // scavenge the key object for the auth lists
592     response->enforced = std::move(key->hw_enforced());
593     response->unenforced = std::move(key->sw_enforced());
594 
595     response->error = CheckVersionInfo(response->enforced, response->unenforced, *context_);
596 }
597 
BeginOperation(const BeginOperationRequest & request,BeginOperationResponse * response)598 void AndroidKeymaster::BeginOperation(const BeginOperationRequest& request,
599                                       BeginOperationResponse* response) {
600     if (response == nullptr) return;
601     response->op_handle = 0;
602 
603     UniquePtr<Key> key = LoadKey(request.key_blob, request.additional_params, &response->error);
604     if (!key) return;
605 
606     response->error = KM_ERROR_UNKNOWN_ERROR;
607     keymaster_algorithm_t key_algorithm;
608     if (!key->authorizations().GetTagValue(TAG_ALGORITHM, &key_algorithm)) return;
609 
610     response->error = KM_ERROR_UNSUPPORTED_PURPOSE;
611     OperationFactory* factory = key->key_factory()->GetOperationFactory(request.purpose);
612     if (!factory) return;
613 
614     uint32_t sd_slot = key->secure_deletion_slot();
615 
616     OperationPtr operation(
617         factory->CreateOperation(std::move(*key), request.additional_params, &response->error));
618     if (operation.get() == nullptr) return;
619 
620     operation->set_secure_deletion_slot(sd_slot);
621 
622     if (operation->authorizations().Contains(TAG_TRUSTED_CONFIRMATION_REQUIRED)) {
623         if (!operation->create_confirmation_verifier_buffer()) {
624             response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
625             return;
626         }
627     }
628 
629     if (context_->enforcement_policy()) {
630         km_id_t key_id;
631         response->error = KM_ERROR_UNKNOWN_ERROR;
632         if (!context_->enforcement_policy()->CreateKeyId(request.key_blob, &key_id)) return;
633         operation->set_key_id(key_id);
634         response->error = context_->enforcement_policy()->AuthorizeOperation(
635             request.purpose, key_id, operation->authorizations(), request.additional_params,
636             0 /* op_handle */, true /* is_begin_operation */);
637         if (response->error != KM_ERROR_OK) return;
638     }
639 
640     response->output_params.Clear();
641     response->error = operation->Begin(request.additional_params, &response->output_params);
642     if (response->error != KM_ERROR_OK) return;
643 
644     response->op_handle = operation->operation_handle();
645     response->error = operation_table_->Add(std::move(operation));
646 }
647 
UpdateOperation(const UpdateOperationRequest & request,UpdateOperationResponse * response)648 void AndroidKeymaster::UpdateOperation(const UpdateOperationRequest& request,
649                                        UpdateOperationResponse* response) {
650     if (response == nullptr) return;
651 
652     response->error = KM_ERROR_INVALID_OPERATION_HANDLE;
653     Operation* operation = operation_table_->Find(request.op_handle);
654     if (operation == nullptr) return;
655 
656     Buffer* confirmation_verifier_buffer = operation->get_confirmation_verifier_buffer();
657     if (confirmation_verifier_buffer != nullptr) {
658         size_t input_num_bytes = request.input.available_read();
659         if (input_num_bytes + confirmation_verifier_buffer->available_read() >
660             kConfirmationMessageMaxSize + kConfirmationTokenMessageTagSize) {
661             response->error = KM_ERROR_INVALID_ARGUMENT;
662             operation_table_->Delete(request.op_handle);
663             return;
664         }
665         if (!confirmation_verifier_buffer->reserve(input_num_bytes)) {
666             response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
667             operation_table_->Delete(request.op_handle);
668             return;
669         }
670         confirmation_verifier_buffer->write(request.input.peek_read(), input_num_bytes);
671     }
672 
673     if (context_->enforcement_policy()) {
674         response->error = context_->enforcement_policy()->AuthorizeOperation(
675             operation->purpose(), operation->key_id(), operation->authorizations(),
676             request.additional_params, request.op_handle, false /* is_begin_operation */);
677         if (response->error != KM_ERROR_OK) {
678             operation_table_->Delete(request.op_handle);
679             return;
680         }
681     }
682 
683     response->error =
684         operation->Update(request.additional_params, request.input, &response->output_params,
685                           &response->output, &response->input_consumed);
686     if (response->error != KM_ERROR_OK) {
687         // Any error invalidates the operation.
688         operation_table_->Delete(request.op_handle);
689     }
690 }
691 
FinishOperation(const FinishOperationRequest & request,FinishOperationResponse * response)692 void AndroidKeymaster::FinishOperation(const FinishOperationRequest& request,
693                                        FinishOperationResponse* response) {
694     if (response == nullptr) return;
695 
696     response->error = KM_ERROR_INVALID_OPERATION_HANDLE;
697     Operation* operation = operation_table_->Find(request.op_handle);
698     if (operation == nullptr) return;
699 
700     Buffer* confirmation_verifier_buffer = operation->get_confirmation_verifier_buffer();
701     if (confirmation_verifier_buffer != nullptr) {
702         size_t input_num_bytes = request.input.available_read();
703         if (input_num_bytes + confirmation_verifier_buffer->available_read() >
704             kConfirmationMessageMaxSize + kConfirmationTokenMessageTagSize) {
705             response->error = KM_ERROR_INVALID_ARGUMENT;
706             operation_table_->Delete(request.op_handle);
707             return;
708         }
709         if (!confirmation_verifier_buffer->reserve(input_num_bytes)) {
710             response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
711             operation_table_->Delete(request.op_handle);
712             return;
713         }
714         confirmation_verifier_buffer->write(request.input.peek_read(), input_num_bytes);
715     }
716 
717     if (context_->enforcement_policy()) {
718         response->error = context_->enforcement_policy()->AuthorizeOperation(
719             operation->purpose(), operation->key_id(), operation->authorizations(),
720             request.additional_params, request.op_handle, false /* is_begin_operation */);
721         if (response->error != KM_ERROR_OK) {
722             operation_table_->Delete(request.op_handle);
723             return;
724         }
725     }
726 
727     response->error = operation->Finish(request.additional_params, request.input, request.signature,
728                                         &response->output_params, &response->output);
729     if (response->error != KM_ERROR_OK) {
730         operation_table_->Delete(request.op_handle);
731         return;
732     }
733 
734     // Invalidate the single use key from secure storage after finish.
735     if (operation->hw_enforced().Contains(TAG_USAGE_COUNT_LIMIT, 1)) {
736         if (context_->secure_deletion_secret_storage() != nullptr) {
737             context_->secure_deletion_secret_storage()->DeleteKey(
738                 operation->secure_deletion_slot());
739         } else if (context_->secure_key_storage() != nullptr) {
740             context_->secure_key_storage()->DeleteKey(operation->key_id());
741         }
742     }
743 
744     // If the operation succeeded and TAG_TRUSTED_CONFIRMATION_REQUIRED was
745     // set, the input must be checked against the confirmation token.
746     if (response->error == KM_ERROR_OK && confirmation_verifier_buffer != nullptr) {
747         keymaster_blob_t confirmation_token_blob;
748         if (!request.additional_params.GetTagValue(TAG_CONFIRMATION_TOKEN,
749                                                    &confirmation_token_blob)) {
750             response->error = KM_ERROR_NO_USER_CONFIRMATION;
751             response->output.Clear();
752         } else {
753             if (confirmation_token_blob.data_length != kConfirmationTokenSize) {
754                 LOG_E("TAG_CONFIRMATION_TOKEN wrong size, was %zd expected %zd",
755                       confirmation_token_blob.data_length, kConfirmationTokenSize);
756                 response->error = KM_ERROR_INVALID_ARGUMENT;
757                 response->output.Clear();
758             } else {
759                 keymaster_error_t verification_result = context_->CheckConfirmationToken(
760                     confirmation_verifier_buffer->begin(),
761                     confirmation_verifier_buffer->available_read(), confirmation_token_blob.data);
762                 if (verification_result != KM_ERROR_OK) {
763                     response->error = verification_result;
764                     response->output.Clear();
765                 }
766             }
767         }
768     }
769 
770     operation_table_->Delete(request.op_handle);
771 }
772 
AbortOperation(const AbortOperationRequest & request,AbortOperationResponse * response)773 void AndroidKeymaster::AbortOperation(const AbortOperationRequest& request,
774                                       AbortOperationResponse* response) {
775     if (!response) return;
776 
777     Operation* operation = operation_table_->Find(request.op_handle);
778     if (!operation) {
779         response->error = KM_ERROR_INVALID_OPERATION_HANDLE;
780         return;
781     }
782 
783     response->error = operation->Abort();
784     operation_table_->Delete(request.op_handle);
785 }
786 
ExportKey(const ExportKeyRequest & request,ExportKeyResponse * response)787 void AndroidKeymaster::ExportKey(const ExportKeyRequest& request, ExportKeyResponse* response) {
788     if (response == nullptr) return;
789 
790     UniquePtr<Key> key;
791     response->error =
792         context_->ParseKeyBlob(KeymasterKeyBlob(request.key_blob), request.additional_params, &key);
793     if (response->error != KM_ERROR_OK) return;
794 
795     UniquePtr<uint8_t[]> out_key;
796     size_t size;
797     response->error = key->formatted_key_material(request.key_format, &out_key, &size);
798     if (response->error == KM_ERROR_OK) {
799         response->key_data = out_key.release();
800         response->key_data_length = size;
801     }
802 }
803 
AttestKey(const AttestKeyRequest & request,AttestKeyResponse * response)804 void AndroidKeymaster::AttestKey(const AttestKeyRequest& request, AttestKeyResponse* response) {
805     if (!response) return;
806 
807     UniquePtr<Key> key = LoadKey(request.key_blob, request.attest_params, &response->error);
808     if (!key) return;
809 
810     keymaster_blob_t attestation_application_id;
811     if (request.attest_params.GetTagValue(TAG_ATTESTATION_APPLICATION_ID,
812                                           &attestation_application_id)) {
813         key->sw_enforced().push_back(TAG_ATTESTATION_APPLICATION_ID, attestation_application_id);
814     }
815 
816     response->certificate_chain =
817         context_->GenerateAttestation(*key, request.attest_params, {} /* attestation_signing_key */,
818                                       {} /* issuer_subject */, &response->error);
819 }
820 
UpgradeKey(const UpgradeKeyRequest & request,UpgradeKeyResponse * response)821 void AndroidKeymaster::UpgradeKey(const UpgradeKeyRequest& request, UpgradeKeyResponse* response) {
822     if (!response) return;
823 
824     KeymasterKeyBlob upgraded_key;
825     response->error = context_->UpgradeKeyBlob(KeymasterKeyBlob(request.key_blob),
826                                                request.upgrade_params, &upgraded_key);
827     if (response->error != KM_ERROR_OK) return;
828     response->upgraded_key = upgraded_key.release();
829 }
830 
ImportKey(const ImportKeyRequest & request,ImportKeyResponse * response)831 void AndroidKeymaster::ImportKey(const ImportKeyRequest& request, ImportKeyResponse* response) {
832     if (response == nullptr) return;
833 
834     const KeyFactory* factory =
835         get_key_factory(request.key_description, *context_, &response->error);
836     if (!factory) return;
837 
838     if (context_->enforcement_policy() &&
839         request.key_description.GetTagValue(TAG_EARLY_BOOT_ONLY) &&
840         !context_->enforcement_policy()->in_early_boot()) {
841         response->error = KM_ERROR_EARLY_BOOT_ENDED;
842         return;
843     }
844 
845     UniquePtr<Key> attest_key;
846     if (request.attestation_signing_key_blob.key_material_size) {
847 
848         attest_key =
849             LoadKey(request.attestation_signing_key_blob, {} /* params */, &response->error);
850         if (response->error != KM_ERROR_OK) return;
851     }
852 
853     if (request.key_description.Contains(TAG_PURPOSE, KM_PURPOSE_ATTEST_KEY) &&
854         request.key_description.GetTagCount(TAG_PURPOSE) > 1) {
855         // ATTEST_KEY cannot be combined with any other purpose.
856         response->error = KM_ERROR_INCOMPATIBLE_PURPOSE;
857         return;
858     }
859 
860     response->error = factory->ImportKey(request.key_description,  //
861                                          request.key_format,       //
862                                          request.key_data,         //
863                                          std::move(attest_key),    //
864                                          request.issuer_subject,   //
865                                          &response->key_blob,      //
866                                          &response->enforced,      //
867                                          &response->unenforced,    //
868                                          &response->certificate_chain);
869 }
870 
DeleteKey(const DeleteKeyRequest & request,DeleteKeyResponse * response)871 void AndroidKeymaster::DeleteKey(const DeleteKeyRequest& request, DeleteKeyResponse* response) {
872     if (!response) return;
873     response->error = context_->DeleteKey(KeymasterKeyBlob(request.key_blob));
874 }
875 
DeleteAllKeys(const DeleteAllKeysRequest &,DeleteAllKeysResponse * response)876 void AndroidKeymaster::DeleteAllKeys(const DeleteAllKeysRequest&, DeleteAllKeysResponse* response) {
877     if (!response) return;
878     response->error = context_->DeleteAllKeys();
879 }
880 
Configure(const ConfigureRequest & request,ConfigureResponse * response)881 void AndroidKeymaster::Configure(const ConfigureRequest& request, ConfigureResponse* response) {
882     if (!response) return;
883     response->error = context_->SetSystemVersion(request.os_version, request.os_patchlevel);
884 }
885 
886 ConfigureVendorPatchlevelResponse
ConfigureVendorPatchlevel(const ConfigureVendorPatchlevelRequest & request)887 AndroidKeymaster::ConfigureVendorPatchlevel(const ConfigureVendorPatchlevelRequest& request) {
888     ConfigureVendorPatchlevelResponse rsp(message_version());
889     rsp.error = context_->SetVendorPatchlevel(request.vendor_patchlevel);
890     return rsp;
891 }
892 
893 ConfigureBootPatchlevelResponse
ConfigureBootPatchlevel(const ConfigureBootPatchlevelRequest & request)894 AndroidKeymaster::ConfigureBootPatchlevel(const ConfigureBootPatchlevelRequest& request) {
895     ConfigureBootPatchlevelResponse rsp(message_version());
896     rsp.error = context_->SetBootPatchlevel(request.boot_patchlevel);
897     return rsp;
898 }
899 
900 ConfigureVerifiedBootInfoResponse
ConfigureVerifiedBootInfo(const ConfigureVerifiedBootInfoRequest & request)901 AndroidKeymaster::ConfigureVerifiedBootInfo(const ConfigureVerifiedBootInfoRequest& request) {
902     ConfigureVerifiedBootInfoResponse rsp(message_version());
903     rsp.error = context_->SetVerifiedBootInfo(request.boot_state, request.bootloader_state,
904                                               request.vbmeta_digest);
905     return rsp;
906 }
907 
has_operation(keymaster_operation_handle_t op_handle) const908 bool AndroidKeymaster::has_operation(keymaster_operation_handle_t op_handle) const {
909     return operation_table_->Find(op_handle) != nullptr;
910 }
911 
LoadKey(const keymaster_key_blob_t & key_blob,const AuthorizationSet & additional_params,keymaster_error_t * error)912 UniquePtr<Key> AndroidKeymaster::LoadKey(const keymaster_key_blob_t& key_blob,
913                                          const AuthorizationSet& additional_params,
914                                          keymaster_error_t* error) {
915     if (!error) return {};
916 
917     UniquePtr<Key> key;
918     KeymasterKeyBlob key_material;
919     *error = context_->ParseKeyBlob(KeymasterKeyBlob(key_blob), additional_params, &key);
920     if (*error != KM_ERROR_OK) return {};
921 
922     *error = CheckVersionInfo(key->hw_enforced(), key->sw_enforced(), *context_);
923     if (*error != KM_ERROR_OK) return {};
924 
925     return key;
926 }
927 
ImportWrappedKey(const ImportWrappedKeyRequest & request,ImportWrappedKeyResponse * response)928 void AndroidKeymaster::ImportWrappedKey(const ImportWrappedKeyRequest& request,
929                                         ImportWrappedKeyResponse* response) {
930     if (!response) return;
931 
932     KeymasterKeyBlob secret_key;
933     AuthorizationSet key_description;
934     keymaster_key_format_t key_format;
935 
936     response->error =
937         context_->UnwrapKey(request.wrapped_key, request.wrapping_key, request.additional_params,
938                             request.masking_key, &key_description, &key_format, &secret_key);
939 
940     if (response->error != KM_ERROR_OK) {
941         return;
942     }
943 
944     int sid_idx = key_description.find(TAG_USER_SECURE_ID);
945     if (sid_idx != -1) {
946         uint8_t sids = key_description[sid_idx].long_integer;
947         if (!key_description.erase(sid_idx)) {
948             response->error = KM_ERROR_UNKNOWN_ERROR;
949             return;
950         }
951         if (sids & HW_AUTH_PASSWORD) {
952             key_description.push_back(TAG_USER_SECURE_ID, request.password_sid);
953         }
954         if (sids & HW_AUTH_FINGERPRINT) {
955             key_description.push_back(TAG_USER_SECURE_ID, request.biometric_sid);
956         }
957     }
958 
959     const KeyFactory* factory = get_key_factory(key_description, *context_, &response->error);
960     if (!factory) return;
961 
962     // There is no way for clients to pass CERTIFICATE_NOT_BEFORE and CERTIFICATE_NOT_AFTER.
963     // importWrappedKey must use validity with no well-defined expiration date.
964     if (context_->GetKmVersion() >= KmVersion::KEYMINT_1) {
965         key_description.push_back(TAG_CERTIFICATE_NOT_BEFORE, 0);
966         key_description.push_back(TAG_CERTIFICATE_NOT_AFTER, kUndefinedExpirationDateTime);
967     }
968 
969     response->error = factory->ImportKey(key_description,          //
970                                          key_format,               //
971                                          secret_key,               //
972                                          {} /* attest_key */,      //
973                                          {} /* issuer_subject */,  //
974                                          &response->key_blob,      //
975                                          &response->enforced,      //
976                                          &response->unenforced,    //
977                                          &response->certificate_chain);
978 }
979 
EarlyBootEnded()980 EarlyBootEndedResponse AndroidKeymaster::EarlyBootEnded() {
981     EarlyBootEndedResponse response(message_version());
982     response.error = KM_ERROR_UNIMPLEMENTED;
983 
984     if (context_->enforcement_policy()) {
985         context_->enforcement_policy()->early_boot_ended();
986         response.error = KM_ERROR_OK;
987     }
988 
989     return response;
990 }
991 
DeviceLocked(const DeviceLockedRequest & request)992 DeviceLockedResponse AndroidKeymaster::DeviceLocked(const DeviceLockedRequest& request) {
993     DeviceLockedResponse response(message_version());
994     response.error = KM_ERROR_UNIMPLEMENTED;
995 
996     if (context_->enforcement_policy()) {
997         context_->enforcement_policy()->device_locked(request.passwordOnly);
998         response.error = KM_ERROR_OK;
999     }
1000 
1001     return response;
1002 }
1003 
GetRootOfTrust(const GetRootOfTrustRequest & request)1004 GetRootOfTrustResponse AndroidKeymaster::GetRootOfTrust(const GetRootOfTrustRequest& request) {
1005     GetRootOfTrustResponse response(message_version());
1006 
1007     if (!context_->attestation_context()) {
1008         LOG_E("Have no attestation context, cannot get RootOfTrust");
1009         response.error = KM_ERROR_UNIMPLEMENTED;
1010         return response;
1011     }
1012 
1013     const AttestationContext::VerifiedBootParams* vbParams =
1014         context_->attestation_context()->GetVerifiedBootParams(&response.error);
1015     if (response.error != KM_ERROR_OK) {
1016         LOG_E("Error retrieving verified boot params: %d", response.error);
1017         return response;
1018     }
1019 
1020     auto boot_patch_level = context_->GetBootPatchlevel();
1021     if (!boot_patch_level) {
1022         LOG_E("Error retrieving boot patch level: %d", response.error);
1023         response.error = KM_ERROR_UNIMPLEMENTED;
1024         return response;
1025     }
1026 
1027     if (!context_->enforcement_policy()) {
1028         LOG_E("Have no enforcement policy, cannot get RootOfTrust");
1029         response.error = KM_ERROR_UNIMPLEMENTED;
1030         return response;
1031     }
1032 
1033     auto macFunction =
1034         [&](const std::vector<uint8_t>& data) -> cppcose::ErrMsgOr<cppcose::HmacSha256> {
1035         auto mac = context_->enforcement_policy()->ComputeHmac(data);
1036         if (!mac) return "Failed to compute HMAC";
1037         return *std::move(mac);
1038     };
1039 
1040     auto maced_root_of_trust = cppcose::constructCoseMac0(
1041         macFunction,  //
1042         request.challenge,
1043         cppbor::SemanticTag(kRoTVersion1, cppbor::Array(                                //
1044                                               blob2Pair(vbParams->verified_boot_key),   //
1045                                               vbParams->device_locked,                  //
1046                                               vbParams->verified_boot_state,            //
1047                                               blob2Pair(vbParams->verified_boot_hash),  //
1048                                               *boot_patch_level))
1049             .encode());
1050 
1051     if (!maced_root_of_trust) {
1052         LOG_E("Error MACing RoT: %s", maced_root_of_trust.message().c_str());
1053         response.error = KM_ERROR_UNKNOWN_ERROR;
1054     } else {
1055         response.error = KM_ERROR_OK;
1056         response.rootOfTrust =
1057             cppbor::SemanticTag(cppcose::kCoseMac0SemanticTag, *std::move(maced_root_of_trust))
1058                 .encode();
1059     }
1060 
1061     return response;
1062 }
1063 
GetHwInfo()1064 GetHwInfoResponse AndroidKeymaster::GetHwInfo() {
1065     GetHwInfoResponse response(message_version());
1066 
1067     auto rem_prov_ctx = context_->GetRemoteProvisioningContext();
1068     if (!rem_prov_ctx) {
1069         LOG_E("Couldn't get a pointer to the remote provisioning context, returned null.");
1070         response.error = static_cast<keymaster_error_t>(kStatusFailed);
1071         return response;
1072     }
1073 
1074     rem_prov_ctx->GetHwInfo(&response);
1075     response.error = KM_ERROR_OK;
1076     return response;
1077 }
1078 
1079 SetAttestationIdsResponse
SetAttestationIds(const SetAttestationIdsRequest & request)1080 AndroidKeymaster::SetAttestationIds(const SetAttestationIdsRequest& request) {
1081     SetAttestationIdsResponse response(message_version());
1082     response.error = context_->SetAttestationIds(request);
1083     return response;
1084 }
1085 
1086 SetAttestationIdsKM3Response
SetAttestationIdsKM3(const SetAttestationIdsKM3Request & request)1087 AndroidKeymaster::SetAttestationIdsKM3(const SetAttestationIdsKM3Request& request) {
1088     SetAttestationIdsKM3Response response(message_version());
1089     response.error = context_->SetAttestationIdsKM3(request);
1090     return response;
1091 }
1092 
1093 }  // namespace keymaster
1094