1 /*
2 * Copyright 2017, 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 "KeymasterDevice.h"
18 #include "buffer.h"
19 #include "export_key.h"
20 #include "import_key.h"
21 #include "import_wrapped_key.h"
22 #include "proto_utils.h"
23
24 #include <Keymaster.client.h>
25 #include <nos/debug.h>
26 #include <nos/NuggetClient.h>
27
28 #include <keymasterV4_0/key_param_output.h>
29
30 #include <android-base/logging.h>
31 #include <android-base/properties.h>
32
33 #include <algorithm>
34
35 namespace android {
36 namespace hardware {
37 namespace keymaster {
38
39 namespace {
40
41 constexpr char PROPERTY_OS_VERSION[] = "ro.build.version.release";
42 constexpr char PROPERTY_OS_PATCHLEVEL[] = "ro.build.version.security_patch";
43 constexpr char PROPERTY_VENDOR_PATCHLEVEL[] = "ro.vendor.build.security_patch";
44
DigitsOnly(const std::string & code)45 std::string DigitsOnly(const std::string& code) {
46 // Keep digits only.
47 std::string filtered_code;
48 std::copy_if(code.begin(), code.end(), std::back_inserter(filtered_code),
49 isdigit);
50 return filtered_code;
51 }
52
53 /** Get one version number from a string and move loc to the point after the
54 * next version delimiter.
55 */
ExtractVersion(const std::string & version,size_t * loc)56 uint32_t ExtractVersion(const std::string& version, size_t* loc) {
57 if (*loc == std::string::npos || *loc >= version.size()) {
58 return 0;
59 }
60
61 uint32_t value = 0;
62 size_t new_loc = version.find('.', *loc);
63 if (new_loc == std::string::npos) {
64 auto sanitized = DigitsOnly(version.substr(*loc));
65 if (!sanitized.empty()) {
66 if (sanitized.size() < version.size() - *loc) {
67 LOG(ERROR) << "Unexpected version format: \"" << version
68 << "\"";
69 }
70 value = std::stoi(sanitized);
71 }
72 *loc = new_loc;
73 } else {
74 auto sanitized = DigitsOnly(version.substr(*loc, new_loc - *loc));
75 if (!sanitized.empty()) {
76 if (sanitized.size() < new_loc - *loc) {
77 LOG(ERROR) << "Unexpected version format: \"" << version
78 << "\"";
79 }
80 value = std::stoi(sanitized);
81 }
82 *loc = new_loc + 1;
83 }
84 return value;
85 }
86
VersionToUint32(const std::string & version)87 uint32_t VersionToUint32(const std::string& version) {
88 size_t loc = 0;
89 uint32_t major = ExtractVersion(version, &loc);
90 uint32_t minor = ExtractVersion(version, &loc);
91 uint32_t subminor = ExtractVersion(version, &loc);
92 return major * 10000 + minor * 100 + subminor;
93 }
94
DateCodeToUint32(const std::string & code,bool include_day)95 uint32_t DateCodeToUint32(const std::string& code, bool include_day) {
96 // Keep digits only.
97 std::string filtered_code = DigitsOnly(code);
98
99 // Return 0 if the date string has an unexpected number of digits.
100 uint32_t return_value = 0;
101 if (filtered_code.size() == 8) {
102 return_value = std::stoi(filtered_code);
103 if (!include_day) {
104 return_value /= 100;
105 }
106 } else if (filtered_code.size() == 6) {
107 return_value = std::stoi(filtered_code);
108 if (include_day) {
109 return_value *= 100;
110 }
111 } else {
112 LOG(ERROR) << "Unexpected patchset format: \"" << code << "\"";
113 }
114 return return_value;
115 }
116
117 // Helper class to call a finalizer on stack unwind.
118 class Finalize {
119 private:
120 std::function<void()> f_;
121
122 public:
Finalize(std::function<void ()> f)123 Finalize(std::function<void()> f) : f_(f) {}
~Finalize()124 ~Finalize() { if (f_) f_(); }
release()125 void release() { f_ = {}; }
126 };
127
128 } // namespace
129
130 // std
131 using std::string;
132
133 // base
134 using ::android::base::GetProperty;
135
136 // libhidl
137 using ::android::hardware::Void;
138
139 // HAL
140 using ::android::hardware::keymaster::V4_0::Algorithm;
141 using ::android::hardware::keymaster::V4_0::KeyCharacteristics;
142 using ::android::hardware::keymaster::V4_0::KeyFormat;
143 using ::android::hardware::keymaster::V4_0::HardwareAuthToken;
144 using ::android::hardware::keymaster::V4_0::HardwareAuthenticatorType;
145 using ::android::hardware::keymaster::V4_0::SecurityLevel;
146 using ::android::hardware::keymaster::V4_0::Tag;
147
148 // nos
149 using nos::NuggetClient;
150
151 // Keymaster app
152 // KM 3.0 types
153 using ::nugget::app::keymaster::AddRngEntropyRequest;
154 using ::nugget::app::keymaster::AddRngEntropyResponse;
155 using ::nugget::app::keymaster::GenerateKeyRequest;
156 using ::nugget::app::keymaster::GenerateKeyResponse;
157 using ::nugget::app::keymaster::GetKeyCharacteristicsRequest;
158 using ::nugget::app::keymaster::GetKeyCharacteristicsResponse;
159 using ::nugget::app::keymaster::ImportKeyRequest;
160 using ::nugget::app::keymaster::ImportKeyResponse;
161 using ::nugget::app::keymaster::ExportKeyRequest;
162 using ::nugget::app::keymaster::ExportKeyResponse;
163 using ::nugget::app::keymaster::StartAttestKeyRequest;
164 using ::nugget::app::keymaster::StartAttestKeyResponse;
165 using ::nugget::app::keymaster::ContinueAttestKeyRequest;
166 using ::nugget::app::keymaster::ContinueAttestKeyResponse;
167 using ::nugget::app::keymaster::FinishAttestKeyRequest;
168 using ::nugget::app::keymaster::FinishAttestKeyResponse;
169 using ::nugget::app::keymaster::UpgradeKeyRequest;
170 using ::nugget::app::keymaster::UpgradeKeyResponse;
171 using ::nugget::app::keymaster::DeleteKeyRequest;
172 using ::nugget::app::keymaster::DeleteKeyResponse;
173 using ::nugget::app::keymaster::DeleteAllKeysRequest;
174 using ::nugget::app::keymaster::DeleteAllKeysResponse;
175 using ::nugget::app::keymaster::DestroyAttestationIdsRequest;
176 using ::nugget::app::keymaster::DestroyAttestationIdsResponse;
177 using ::nugget::app::keymaster::BeginOperationRequest;
178 using ::nugget::app::keymaster::BeginOperationResponse;
179 using ::nugget::app::keymaster::UpdateOperationRequest;
180 using ::nugget::app::keymaster::UpdateOperationResponse;
181 using ::nugget::app::keymaster::FinishOperationRequest;
182 using ::nugget::app::keymaster::FinishOperationResponse;
183 using ::nugget::app::keymaster::AbortOperationRequest;
184 using ::nugget::app::keymaster::AbortOperationResponse;
185 using ::nugget::app::keymaster::ComputeSharedHmacRequest;
186 using ::nugget::app::keymaster::ComputeSharedHmacResponse;
187 using ::nugget::app::keymaster::GetHmacSharingParametersRequest;
188 using ::nugget::app::keymaster::GetHmacSharingParametersResponse;
189 using ::nugget::app::keymaster::SetSystemVersionInfoRequest;
190 using ::nugget::app::keymaster::SetSystemVersionInfoResponse;
191 using ::nugget::app::keymaster::GetBootInfoRequest;
192 using ::nugget::app::keymaster::GetBootInfoResponse;
193
194 // KM 4.0 types
195 using ::nugget::app::keymaster::ImportWrappedKeyRequest;
196 namespace nosapp = ::nugget::app::keymaster;
197
status_to_error_code(uint32_t status)198 static ErrorCode status_to_error_code(uint32_t status)
199 {
200 switch (status) {
201 case APP_SUCCESS:
202 return ErrorCode::OK;
203 break;
204 case APP_ERROR_BOGUS_ARGS:
205 return ErrorCode::INVALID_ARGUMENT;
206 break;
207 case APP_ERROR_INTERNAL:
208 return ErrorCode::UNKNOWN_ERROR;
209 break;
210 case APP_ERROR_TOO_MUCH:
211 return ErrorCode::INSUFFICIENT_BUFFER_SPACE;
212 break;
213 case APP_ERROR_RPC:
214 return ErrorCode::SECURE_HW_COMMUNICATION_FAILED;
215 break;
216 // TODO: app specific error codes go here.
217 default:
218 return ErrorCode::UNKNOWN_ERROR;
219 break;
220 }
221 }
222
223 #define KM_CALL(meth, request, response) { \
224 const uint32_t status = _keymaster. meth (request, &response); \
225 const ErrorCode error_code = translate_error_code(response.error_code()); \
226 if (status != APP_SUCCESS) { \
227 LOG(ERROR) << #meth << " : request failed with status: " \
228 << nos::StatusCodeString(status); \
229 return status_to_error_code(status); \
230 } \
231 if (error_code != ErrorCode::OK) { \
232 LOG(ERROR) << #meth << " : device response error code: " \
233 << error_code; \
234 return error_code; \
235 } \
236 }
237
238 #define KM_CALLV(meth, request, response, ...) { \
239 const uint32_t status = _keymaster. meth (request, &response); \
240 const ErrorCode error_code = translate_error_code(response.error_code()); \
241 if (status != APP_SUCCESS) { \
242 LOG(ERROR) << #meth << " : request failed with status: " \
243 << nos::StatusCodeString(status); \
244 _hidl_cb(status_to_error_code(status), __VA_ARGS__); \
245 return Void(); \
246 } \
247 if (error_code != ErrorCode::OK) { \
248 LOG(ERROR) << #meth << " : device response error code: " \
249 << error_code; \
250 _hidl_cb(error_code, __VA_ARGS__); \
251 return Void(); \
252 } \
253 }
254
255 // Methods from ::android::hardware::keymaster::V3_0::IKeymasterDevice follow.
256
KeymasterDevice(KeymasterClient & keymaster)257 KeymasterDevice::KeymasterDevice(KeymasterClient& keymaster) :
258 _keymaster{keymaster} {
259 _os_version = VersionToUint32(GetProperty(PROPERTY_OS_VERSION, ""));
260 _os_patchlevel = DateCodeToUint32(GetProperty(PROPERTY_OS_PATCHLEVEL, ""),
261 false /* include_day */);
262 _vendor_patchlevel = DateCodeToUint32(
263 GetProperty(PROPERTY_VENDOR_PATCHLEVEL, ""),
264 true /* include_day */);
265
266 SendSystemVersionInfo();
267 GetBootInfo();
268 }
269
getHardwareInfo(getHardwareInfo_cb _hidl_cb)270 Return<void> KeymasterDevice::getHardwareInfo(
271 getHardwareInfo_cb _hidl_cb)
272 {
273 LOG(VERBOSE) << "Running KeymasterDevice::getHardwareInfo";
274
275 (void)_keymaster;
276 _hidl_cb(SecurityLevel::STRONGBOX,
277 string("CitadelKeymaster"), string("Google"));
278
279 return Void();
280 }
281
getHmacSharingParameters(getHmacSharingParameters_cb _hidl_cb)282 Return<void> KeymasterDevice::getHmacSharingParameters(
283 getHmacSharingParameters_cb _hidl_cb)
284 {
285 LOG(VERBOSE) << "Running KeymasterDevice::getHmacSharingParameters";
286
287 GetHmacSharingParametersRequest request;
288 GetHmacSharingParametersResponse response;
289 HmacSharingParameters result;
290
291 KM_CALLV(GetHmacSharingParameters, request, response, result);
292
293 ErrorCode ec = translate_error_code(response.error_code());
294
295 if (ec != ErrorCode::OK) {
296 _hidl_cb(ec, HmacSharingParameters());
297 }
298
299 const std::string & nonce = response.hmac_sharing_params().nonce();
300 const std::string & seed = response.hmac_sharing_params().seed();
301
302 if (seed.size() == 32) {
303 result.seed.setToExternal(reinterpret_cast<uint8_t*>(
304 const_cast<char*>(seed.data())),
305 seed.size(), false);
306 } else if (seed.size() != 0) {
307 LOG(ERROR) << "Citadel returned unexpected seed size: "
308 << seed.size();
309 _hidl_cb(ErrorCode::UNKNOWN_ERROR, HmacSharingParameters());
310 return Void();
311 }
312
313 if (nonce.size() == result.nonce.size()) {
314 std::copy(nonce.begin(), nonce.end(), result.nonce.data());
315 } else {
316 LOG(ERROR) << "Citadel returned unexpected nonce size: "
317 << nonce.size();
318 _hidl_cb(ErrorCode::UNKNOWN_ERROR, HmacSharingParameters());
319 return Void();
320 }
321
322 _hidl_cb(ec, result);
323
324 return Void();
325 }
326
computeSharedHmac(const hidl_vec<HmacSharingParameters> & params,computeSharedHmac_cb _hidl_cb)327 Return<void> KeymasterDevice::computeSharedHmac(
328 const hidl_vec<HmacSharingParameters>& params,
329 computeSharedHmac_cb _hidl_cb)
330 {
331 LOG(VERBOSE) << "Running KeymasterDevice::computeSharedHmac";
332
333 ComputeSharedHmacRequest request;
334 ComputeSharedHmacResponse response;
335 hidl_vec<uint8_t> result;
336
337 for (const HmacSharingParameters & param : params) {
338 // TODO respect max number of parameters defined in
339 // keymaster_types.proto
340 nosapp::HmacSharingParameters* req_param =
341 request.add_hmac_sharing_params();
342 req_param->set_nonce(
343 reinterpret_cast<const int8_t*>(
344 param.nonce.data()), param.nonce.size());
345 req_param->set_seed(reinterpret_cast<const int8_t*>(param.seed.data()),
346 param.seed.size());
347 }
348
349 KM_CALLV(ComputeSharedHmac, request, response, result);
350
351 ErrorCode ec = translate_error_code(response.error_code());
352
353 if (ec != ErrorCode::OK) {
354 _hidl_cb(ec, result);
355 return Void();
356 }
357
358 const std::string & share_check = response.sharing_check();
359
360 result.setToExternal(reinterpret_cast<uint8_t*>(
361 const_cast<char*>(share_check.data())), share_check.size(), false);
362 _hidl_cb(ec, result);
363
364 return Void();
365 }
366
verifyAuthorization(uint64_t operationHandle,const hidl_vec<KeyParameter> & parametersToVerify,const HardwareAuthToken & authToken,verifyAuthorization_cb _hidl_cb)367 Return<void> KeymasterDevice::verifyAuthorization(
368 uint64_t operationHandle, const hidl_vec<KeyParameter>& parametersToVerify,
369 const HardwareAuthToken& authToken, verifyAuthorization_cb _hidl_cb)
370 {
371 LOG(VERBOSE) << "Running KeymasterDevice::verifyAuthorization";
372
373 (void)operationHandle;
374 (void)parametersToVerify;
375 (void)authToken;
376
377 (void)_keymaster;
378 _hidl_cb(ErrorCode::UNIMPLEMENTED, VerificationToken());
379
380 return Void();
381 }
382
addRngEntropy(const hidl_vec<uint8_t> & data)383 Return<ErrorCode> KeymasterDevice::addRngEntropy(const hidl_vec<uint8_t>& data)
384 {
385 LOG(VERBOSE) << "Running KeymasterDevice::addRngEntropy";
386
387 if (!data.size()) return ErrorCode::OK;
388
389 const size_t chunk_size = 1024;
390 for (size_t i = 0; i < data.size(); i += chunk_size) {
391 AddRngEntropyRequest request;
392 AddRngEntropyResponse response;
393
394 request.set_data(&data[i], std::min(chunk_size, data.size() - i));
395
396 // Call device.
397 KM_CALL(AddRngEntropy, request, response);
398 }
399
400 return ErrorCode::OK;
401 }
402
generateKey(const hidl_vec<KeyParameter> & keyParams,generateKey_cb _hidl_cb)403 Return<void> KeymasterDevice::generateKey(
404 const hidl_vec<KeyParameter>& keyParams,
405 generateKey_cb _hidl_cb)
406 {
407 LOG(VERBOSE) << "Running KeymasterDevice::generateKey";
408
409 GenerateKeyRequest request;
410 GenerateKeyResponse response;
411
412 hidl_vec<uint8_t> blob;
413 KeyCharacteristics characteristics;
414 if (hidl_params_to_pb(
415 keyParams, request.mutable_params()) != ErrorCode::OK) {
416 _hidl_cb(ErrorCode::INVALID_ARGUMENT, blob, characteristics);
417 return Void();
418 }
419
420 // Call device.
421 KM_CALLV(GenerateKey, request, response,
422 hidl_vec<uint8_t>{}, KeyCharacteristics());
423
424 blob.setToExternal(
425 reinterpret_cast<uint8_t*>(
426 const_cast<char*>(response.blob().blob().data())),
427 response.blob().blob().size(), false);
428 pb_to_hidl_params(response.characteristics().software_enforced(),
429 &characteristics.softwareEnforced);
430 pb_to_hidl_params(response.characteristics().tee_enforced(),
431 &characteristics.hardwareEnforced);
432
433 _hidl_cb(translate_error_code(response.error_code()),
434 blob, characteristics);
435 return Void();
436 }
437
getKeyCharacteristics(const hidl_vec<uint8_t> & keyBlob,const hidl_vec<uint8_t> & clientId,const hidl_vec<uint8_t> & appData,getKeyCharacteristics_cb _hidl_cb)438 Return<void> KeymasterDevice::getKeyCharacteristics(
439 const hidl_vec<uint8_t>& keyBlob,
440 const hidl_vec<uint8_t>& clientId,
441 const hidl_vec<uint8_t>& appData,
442 getKeyCharacteristics_cb _hidl_cb)
443 {
444 LOG(VERBOSE) << "Running KeymasterDevice::getKeyCharacteristics";
445
446 GetKeyCharacteristicsRequest request;
447 GetKeyCharacteristicsResponse response;
448
449 request.mutable_blob()->set_blob(&keyBlob[0], keyBlob.size());
450 request.set_client_id(&clientId[0], clientId.size());
451 request.set_app_data(&appData[0], appData.size());
452
453 // Call device.
454 KM_CALLV(GetKeyCharacteristics, request, response, KeyCharacteristics());
455
456 KeyCharacteristics characteristics;
457 pb_to_hidl_params(response.characteristics().software_enforced(),
458 &characteristics.softwareEnforced);
459 pb_to_hidl_params(response.characteristics().tee_enforced(),
460 &characteristics.hardwareEnforced);
461
462 _hidl_cb(translate_error_code(response.error_code()), characteristics);
463 return Void();
464 }
465
importKey(const hidl_vec<KeyParameter> & params,KeyFormat keyFormat,const hidl_vec<uint8_t> & keyData,importKey_cb _hidl_cb)466 Return<void> KeymasterDevice::importKey(
467 const hidl_vec<KeyParameter>& params, KeyFormat keyFormat,
468 const hidl_vec<uint8_t>& keyData, importKey_cb _hidl_cb)
469 {
470 LOG(VERBOSE) << "Running KeymasterDevice::importKey";
471
472 ErrorCode error;
473 ImportKeyRequest request;
474 ImportKeyResponse response;
475
476 error = import_key_request(params, keyFormat, keyData, &request);
477 if (error != ErrorCode::OK) {
478 LOG(ERROR) << "ImportKey request parsing failed with error "
479 << error;
480 _hidl_cb(error, hidl_vec<uint8_t>{}, KeyCharacteristics{});
481 return Void();
482 }
483
484 KM_CALLV(ImportKey, request, response,
485 hidl_vec<uint8_t>{}, KeyCharacteristics{});
486
487 hidl_vec<uint8_t> blob;
488 blob.setToExternal(
489 reinterpret_cast<uint8_t*>(
490 const_cast<char*>(response.blob().blob().data())),
491 response.blob().blob().size(), false);
492
493 KeyCharacteristics characteristics;
494 pb_to_hidl_params(response.characteristics().software_enforced(),
495 &characteristics.softwareEnforced);
496 error = pb_to_hidl_params(response.characteristics().tee_enforced(),
497 &characteristics.hardwareEnforced);
498 if (error != ErrorCode::OK) {
499 LOG(ERROR) << "KeymasterDevice::importKey: response tee_enforced :"
500 << error;
501 _hidl_cb(error, hidl_vec<uint8_t>{}, KeyCharacteristics{});
502 return Void();
503 }
504
505 _hidl_cb(ErrorCode::OK, blob, characteristics);
506 return Void();
507 }
508
exportKey(KeyFormat exportFormat,const hidl_vec<uint8_t> & keyBlob,const hidl_vec<uint8_t> & clientId,const hidl_vec<uint8_t> & appData,exportKey_cb _hidl_cb)509 Return<void> KeymasterDevice::exportKey(
510 KeyFormat exportFormat, const hidl_vec<uint8_t>& keyBlob,
511 const hidl_vec<uint8_t>& clientId,
512 const hidl_vec<uint8_t>& appData, exportKey_cb _hidl_cb)
513 {
514 LOG(VERBOSE) << "Running KeymasterDevice::exportKey";
515
516 ExportKeyRequest request;
517 ExportKeyResponse response;
518
519 request.set_format((::nugget::app::keymaster::KeyFormat)exportFormat);
520 request.mutable_blob()->set_blob(&keyBlob[0], keyBlob.size());
521 request.set_client_id(&clientId[0], clientId.size());
522 request.set_app_data(&appData[0], appData.size());
523
524 KM_CALLV(ExportKey, request, response, hidl_vec<uint8_t>{});
525
526 ErrorCode error_code = translate_error_code(response.error_code());
527 if (error_code != ErrorCode::OK) {
528 _hidl_cb(error_code, hidl_vec<uint8_t>{});
529 }
530
531 hidl_vec<uint8_t> der;
532 error_code = export_key_der(response, &der);
533
534 _hidl_cb(error_code, der);
535 return Void();
536 }
537
attestKey(const hidl_vec<uint8_t> & keyToAttest,const hidl_vec<KeyParameter> & attestParams,attestKey_cb _hidl_cb)538 Return<void> KeymasterDevice::attestKey(
539 const hidl_vec<uint8_t>& keyToAttest,
540 const hidl_vec<KeyParameter>& attestParams,
541 attestKey_cb _hidl_cb)
542 {
543 LOG(VERBOSE) << "Running KeymasterDevice::attestKey";
544
545 StartAttestKeyRequest startRequest;
546 StartAttestKeyResponse startResponse;
547
548 startRequest.mutable_blob()->set_blob(&keyToAttest[0], keyToAttest.size());
549
550 vector<hidl_vec<uint8_t> > chain;
551 if (hidl_params_to_pb(
552 attestParams, startRequest.mutable_params()) != ErrorCode::OK) {
553 _hidl_cb(ErrorCode::INVALID_ARGUMENT, chain);
554 return Void();
555 }
556
557 // TODO:
558 // startRequest.set_attestation_app_id_len(
559 // attestation_app_id_len(attestParams));
560
561 KM_CALLV(StartAttestKey, startRequest, startResponse,
562 hidl_vec<hidl_vec<uint8_t> >{});
563
564 uint64_t operationHandle = startResponse.handle().handle();
565 ContinueAttestKeyRequest continueRequest;
566 ContinueAttestKeyResponse continueResponse;
567 // Prepare to abort the pending operation in event of an error.
568 Finalize finalize([&] () { abort(operationHandle); });
569
570 continueRequest.mutable_handle()->set_handle(operationHandle);
571 // TODO
572 // continueRequest.set_attestation_app_id(
573 // attestation_app_id(attestParams));
574
575 KM_CALLV(ContinueAttestKey, continueRequest, continueResponse,
576 hidl_vec<hidl_vec<uint8_t> >{});
577
578 FinishAttestKeyRequest finishRequest;
579 FinishAttestKeyResponse finishResponse;
580
581 finishRequest.mutable_handle()->set_handle(operationHandle);
582
583 KM_CALLV(FinishAttestKey, finishRequest, finishResponse,
584 hidl_vec<hidl_vec<uint8_t> >{});
585
586 std::stringstream ss;
587 ss << startResponse.certificate_prologue();
588 ss << continueResponse.certificate_body();
589 ss << finishResponse.certificate_epilogue();
590
591 hidl_vec<uint8_t> attestation_certificate;
592 attestation_certificate.setToExternal(
593 reinterpret_cast<uint8_t*>(
594 const_cast<char*>(ss.str().data())),
595 ss.str().size(), false);
596
597 chain.push_back(attestation_certificate);
598 // TODO:
599 // chain.push_back(intermediate_certificate());
600 // chain.push_back(root_certificate());
601 // verify cert chain
602
603 _hidl_cb(ErrorCode::OK, hidl_vec<hidl_vec<uint8_t> >(chain));
604 finalize.release();
605 return Void();
606 }
607
upgradeKey(const hidl_vec<uint8_t> & keyBlobToUpgrade,const hidl_vec<KeyParameter> & upgradeParams,upgradeKey_cb _hidl_cb)608 Return<void> KeymasterDevice::upgradeKey(
609 const hidl_vec<uint8_t>& keyBlobToUpgrade,
610 const hidl_vec<KeyParameter>& upgradeParams,
611 upgradeKey_cb _hidl_cb)
612 {
613 LOG(VERBOSE) << "Running KeymasterDevice::upgradeKey";
614
615 UpgradeKeyRequest request;
616 UpgradeKeyResponse response;
617
618 request.mutable_blob()->set_blob(&keyBlobToUpgrade[0],
619 keyBlobToUpgrade.size());
620
621 hidl_vec<uint8_t> blob;
622 if (hidl_params_to_pb(
623 upgradeParams, request.mutable_params()) != ErrorCode::OK) {
624 _hidl_cb(ErrorCode::INVALID_ARGUMENT, blob);
625 return Void();
626 }
627
628 KM_CALLV(UpgradeKey, request, response, hidl_vec<uint8_t>{});
629
630 blob.setToExternal(
631 reinterpret_cast<uint8_t*>(
632 const_cast<char*>(response.blob().blob().data())),
633 response.blob().blob().size(), false);
634
635 _hidl_cb(translate_error_code(response.error_code()), blob);
636 return Void();
637 }
638
deleteKey(const hidl_vec<uint8_t> & keyBlob)639 Return<ErrorCode> KeymasterDevice::deleteKey(const hidl_vec<uint8_t>& keyBlob)
640 {
641 LOG(VERBOSE) << "Running KeymasterDevice::deleteKey";
642
643 DeleteKeyRequest request;
644 DeleteKeyResponse response;
645
646 request.mutable_blob()->set_blob(&keyBlob[0], keyBlob.size());
647
648 KM_CALL(DeleteKey, request, response);
649
650 return translate_error_code(response.error_code());
651 }
652
deleteAllKeys()653 Return<ErrorCode> KeymasterDevice::deleteAllKeys()
654 {
655 LOG(VERBOSE) << "Running KeymasterDevice::deleteAllKeys";
656
657 DeleteAllKeysRequest request;
658 DeleteAllKeysResponse response;
659
660 KM_CALL(DeleteAllKeys, request, response);
661
662 return translate_error_code(response.error_code());
663 }
664
destroyAttestationIds()665 Return<ErrorCode> KeymasterDevice::destroyAttestationIds()
666 {
667 LOG(VERBOSE) << "Running KeymasterDevice::destroyAttestationIds";
668
669 DestroyAttestationIdsRequest request;
670 DestroyAttestationIdsResponse response;
671
672 KM_CALL(DestroyAttestationIds, request, response);
673
674 return translate_error_code(response.error_code());
675 }
676
begin(KeyPurpose purpose,const hidl_vec<uint8_t> & key,const hidl_vec<KeyParameter> & inParams,const HardwareAuthToken & authToken,begin_cb _hidl_cb)677 Return<void> KeymasterDevice::begin(
678 KeyPurpose purpose, const hidl_vec<uint8_t>& key,
679 const hidl_vec<KeyParameter>& inParams,
680 const HardwareAuthToken& authToken,
681 begin_cb _hidl_cb)
682 {
683 LOG(VERBOSE) << "Running KeymasterDevice::begin";
684
685 BeginOperationRequest request;
686 BeginOperationResponse response;
687
688 request.set_purpose((::nugget::app::keymaster::KeyPurpose)purpose);
689 request.mutable_blob()->set_blob(&key[0], key.size());
690
691 hidl_vec<KeyParameter> params;
692 tag_map_t tag_map;
693 if (translate_auth_token(
694 authToken, request.mutable_auth_token()) != ErrorCode::OK) {
695 _hidl_cb(ErrorCode::INVALID_ARGUMENT, params,
696 response.handle().handle());
697 return Void();
698 }
699 if (hidl_params_to_pb(
700 inParams, request.mutable_params()) != ErrorCode::OK) {
701 _hidl_cb(ErrorCode::INVALID_ARGUMENT, params,
702 response.handle().handle());
703 return Void();
704 }
705 if (hidl_params_to_map(inParams, &tag_map) != ErrorCode::OK) {
706 _hidl_cb(ErrorCode::INVALID_ARGUMENT, params,
707 response.handle().handle());
708 return Void();
709 }
710
711 KM_CALLV(BeginOperation, request, response, hidl_vec<KeyParameter>{}, 0);
712
713 // Setup HAL buffering for this operation's data.
714 Algorithm algorithm;
715 if (translate_algorithm(response.algorithm(), &algorithm) !=
716 ErrorCode::OK) {
717 if (this->abort(response.handle().handle()) != ErrorCode::OK) {
718 LOG(ERROR) << "abort( " << response.handle().handle()
719 << ") failed";
720 }
721 _hidl_cb(ErrorCode::INVALID_ARGUMENT, params,
722 response.handle().handle());
723 return Void();
724 }
725 ErrorCode error_code = buffer_begin(response.handle().handle(), algorithm);
726 if (error_code != ErrorCode::OK) {
727 if (this->abort(response.handle().handle()) != ErrorCode::OK) {
728 LOG(ERROR) << "abort( " << response.handle().handle()
729 << ") failed";
730 }
731 _hidl_cb(ErrorCode::UNKNOWN_ERROR, params,
732 response.handle().handle());
733 return Void();
734 }
735
736 pb_to_hidl_params(response.params(), ¶ms);
737
738 _hidl_cb(translate_error_code(response.error_code()), params,
739 response.handle().handle());
740 return Void();
741 }
742
update(uint64_t operationHandle,const hidl_vec<KeyParameter> & inParams,const hidl_vec<uint8_t> & input,const HardwareAuthToken & authToken,const VerificationToken & verificationToken,update_cb _hidl_cb)743 Return<void> KeymasterDevice::update(
744 uint64_t operationHandle,
745 const hidl_vec<KeyParameter>& inParams,
746 const hidl_vec<uint8_t>& input,
747 const HardwareAuthToken& authToken,
748 const VerificationToken& verificationToken,
749 update_cb _hidl_cb)
750 {
751 LOG(VERBOSE) << "Running KeymasterDevice::update";
752
753 UpdateOperationRequest request;
754 UpdateOperationResponse response;
755
756 // TODO: does keystore chunk stream data? To what quantum?
757 if (input.size() > KM_MAX_PROTO_FIELD_SIZE) {
758 LOG(ERROR) << "Excess input length: " << input.size()
759 << "max allowed: " << KM_MAX_PROTO_FIELD_SIZE;
760 if (this->abort(operationHandle) != ErrorCode::OK) {
761 LOG(ERROR) << "abort( " << operationHandle
762 << ") failed";
763 }
764 _hidl_cb(ErrorCode::INVALID_INPUT_LENGTH, 0,
765 hidl_vec<KeyParameter>{}, hidl_vec<uint8_t>{});
766 return Void();
767 }
768
769 uint32_t consumed;
770 hidl_vec<uint8_t> output;
771 hidl_vec<KeyParameter> params;
772 ErrorCode error_code;
773 error_code = buffer_append(operationHandle, input, &consumed);
774 if (error_code != ErrorCode::OK) {
775 _hidl_cb(error_code, 0, params, output);
776 return Void();
777 }
778
779 hidl_vec<uint8_t> blocks;
780 error_code = buffer_peek(operationHandle, &blocks);
781 if (error_code != ErrorCode::OK) {
782 _hidl_cb(error_code, 0, params, output);
783 return Void();
784 }
785
786 if (blocks.size() == 0) {
787 // Insufficient data available to proceed.
788 _hidl_cb(ErrorCode::OK, consumed, params, output);
789 return Void();
790 }
791
792 request.mutable_handle()->set_handle(operationHandle);
793
794 if (hidl_params_to_pb(
795 inParams, request.mutable_params()) != ErrorCode::OK) {
796 _hidl_cb(ErrorCode::INVALID_ARGUMENT, 0, params, output);
797 return Void();
798 }
799
800 request.set_input(&blocks[0], blocks.size());
801 if (translate_auth_token(
802 authToken, request.mutable_auth_token()) != ErrorCode::OK) {
803 _hidl_cb(ErrorCode::INVALID_ARGUMENT, 0, params, output);
804 return Void();
805 }
806 translate_verification_token(verificationToken,
807 request.mutable_verification_token());
808
809 KM_CALLV(UpdateOperation, request, response,
810 0, hidl_vec<KeyParameter>{}, hidl_vec<uint8_t>{});
811
812 if (buffer_advance(operationHandle, response.consumed()) != ErrorCode::OK) {
813 _hidl_cb(ErrorCode::UNKNOWN_ERROR, 0, params, output);
814 return Void();
815 }
816
817 pb_to_hidl_params(response.params(), ¶ms);
818 output.setToExternal(
819 reinterpret_cast<uint8_t*>(const_cast<char*>(response.output().data())),
820 response.output().size(), false);
821
822 _hidl_cb(ErrorCode::OK, consumed, params, output);
823 return Void();
824 }
825
finish(uint64_t operationHandle,const hidl_vec<KeyParameter> & inParams,const hidl_vec<uint8_t> & input,const hidl_vec<uint8_t> & signature,const HardwareAuthToken & authToken,const VerificationToken & verificationToken,finish_cb _hidl_cb)826 Return<void> KeymasterDevice::finish(
827 uint64_t operationHandle,
828 const hidl_vec<KeyParameter>& inParams,
829 const hidl_vec<uint8_t>& input,
830 const hidl_vec<uint8_t>& signature,
831 const HardwareAuthToken& authToken,
832 const VerificationToken& verificationToken,
833 finish_cb _hidl_cb)
834 {
835 LOG(VERBOSE) << "Running KeymasterDevice::finish";
836
837 FinishOperationRequest request;
838 FinishOperationResponse response;
839
840 if (input.size() > KM_MAX_PROTO_FIELD_SIZE) {
841 LOG(ERROR) << "Excess input length: " << input.size()
842 << "max allowed: " << KM_MAX_PROTO_FIELD_SIZE;
843 if (this->abort(operationHandle) != ErrorCode::OK) {
844 LOG(ERROR) << "abort( " << operationHandle
845 << ") failed";
846 }
847 _hidl_cb(ErrorCode::INVALID_INPUT_LENGTH,
848 hidl_vec<KeyParameter>{}, hidl_vec<uint8_t>{});
849 return Void();
850 }
851
852 uint32_t consumed;
853 ErrorCode error_code;
854 error_code = buffer_append(operationHandle, input, &consumed);
855 if (error_code != ErrorCode::OK) {
856 _hidl_cb(error_code,
857 hidl_vec<KeyParameter>{}, hidl_vec<uint8_t>{});
858 return Void();
859 }
860
861 hidl_vec<uint8_t> data;
862 error_code = buffer_final(operationHandle, &data);
863 if (error_code != ErrorCode::OK) {
864 _hidl_cb(error_code,
865 hidl_vec<KeyParameter>{}, hidl_vec<uint8_t>{});
866 return Void();
867 }
868
869 request.mutable_handle()->set_handle(operationHandle);
870
871 hidl_vec<KeyParameter> params;
872 hidl_vec<uint8_t> output;
873 if (hidl_params_to_pb(
874 inParams, request.mutable_params()) != ErrorCode::OK) {
875 _hidl_cb(ErrorCode::INVALID_ARGUMENT, params, output);
876 return Void();
877 }
878
879 request.set_input(&data[0], data.size());
880 request.set_signature(&signature[0], signature.size());
881
882 if (translate_auth_token(
883 authToken, request.mutable_auth_token()) != ErrorCode::OK) {
884 _hidl_cb(ErrorCode::INVALID_ARGUMENT, params, output);
885 return Void();
886 }
887 translate_verification_token(verificationToken,
888 request.mutable_verification_token());
889
890 KM_CALLV(FinishOperation, request, response,
891 hidl_vec<KeyParameter>{}, hidl_vec<uint8_t>{});
892
893 pb_to_hidl_params(response.params(), ¶ms);
894 output.setToExternal(
895 reinterpret_cast<uint8_t*>(const_cast<char*>(response.output().data())),
896 response.output().size(), false);
897
898 _hidl_cb(ErrorCode::OK, params, output);
899 return Void();
900 }
901
abort(uint64_t operationHandle)902 Return<ErrorCode> KeymasterDevice::abort(uint64_t operationHandle)
903 {
904 LOG(VERBOSE) << "Running KeymasterDevice::abort";
905
906 AbortOperationRequest request;
907 AbortOperationResponse response;
908
909 request.mutable_handle()->set_handle(operationHandle);
910
911 KM_CALL(AbortOperation, request, response);
912
913 return ErrorCode::OK;
914 }
915
916 // Methods from ::android::hardware::keymaster::V4_0::IKeymasterDevice follow.
importWrappedKey(const hidl_vec<uint8_t> & wrappedKeyData,const hidl_vec<uint8_t> & wrappingKeyBlob,const hidl_vec<uint8_t> & maskingKey,const hidl_vec<KeyParameter> &,uint64_t,uint64_t,importWrappedKey_cb _hidl_cb)917 Return<void> KeymasterDevice::importWrappedKey(
918 const hidl_vec<uint8_t>& wrappedKeyData,
919 const hidl_vec<uint8_t>& wrappingKeyBlob,
920 const hidl_vec<uint8_t>& maskingKey,
921 const hidl_vec<KeyParameter>& /* unwrappingParams */,
922 uint64_t /* passwordSid */, uint64_t /* biometricSid */,
923 importWrappedKey_cb _hidl_cb)
924 {
925 LOG(VERBOSE) << "Running KeymasterDevice::importWrappedKey";
926
927 ErrorCode error;
928 ImportWrappedKeyRequest request;
929 ImportKeyResponse response;
930
931 if (maskingKey.size() != KM_WRAPPER_MASKING_KEY_SIZE) {
932 _hidl_cb(ErrorCode::INVALID_ARGUMENT, hidl_vec<uint8_t>{},
933 KeyCharacteristics{});
934 return Void();
935 }
936
937 error = import_wrapped_key_request(wrappedKeyData, wrappingKeyBlob,
938 maskingKey, &request);
939 if (error != ErrorCode::OK) {
940 LOG(ERROR) << "ImportWrappedKey request parsing failed with error "
941 << error;
942 _hidl_cb(error, hidl_vec<uint8_t>{}, KeyCharacteristics{});
943 return Void();
944 }
945
946 KM_CALLV(ImportWrappedKey, request, response,
947 hidl_vec<uint8_t>{}, KeyCharacteristics{});
948
949 hidl_vec<uint8_t> blob;
950 blob.setToExternal(
951 reinterpret_cast<uint8_t*>(
952 const_cast<char*>(response.blob().blob().data())),
953 response.blob().blob().size(), false);
954
955 KeyCharacteristics characteristics;
956 // TODO: anything to do here with softwareEnforced?
957 pb_to_hidl_params(response.characteristics().software_enforced(),
958 &characteristics.softwareEnforced);
959 error = pb_to_hidl_params(response.characteristics().tee_enforced(),
960 &characteristics.hardwareEnforced);
961 if (error != ErrorCode::OK) {
962 LOG(ERROR) <<
963 "KeymasterDevice::importWrappedKey: response tee_enforced :"
964 << error;
965 _hidl_cb(error, hidl_vec<uint8_t>{}, KeyCharacteristics{});
966 return Void();
967 }
968
969 _hidl_cb(ErrorCode::OK, blob, characteristics);
970 return Void();
971 }
972
973 // Private methods.
SendSystemVersionInfo() const974 Return<ErrorCode> KeymasterDevice::SendSystemVersionInfo() const {
975 SetSystemVersionInfoRequest request;
976 SetSystemVersionInfoResponse response;
977
978 request.set_system_version(_os_version);
979 request.set_system_security_level(_os_patchlevel);
980 request.set_vendor_security_level(_vendor_patchlevel);
981
982 KM_CALL(SetSystemVersionInfo, request, response);
983 return ErrorCode::OK;
984 }
985
GetBootInfo()986 Return<ErrorCode> KeymasterDevice::GetBootInfo() {
987 GetBootInfoRequest request;
988 GetBootInfoResponse response;
989
990 KM_CALL(GetBootInfo, request, response);
991
992 _is_unlocked = response.is_unlocked();
993 _boot_color = response.boot_color();
994 _boot_key.assign(response.boot_key().begin(), response.boot_key().end());
995 _boot_hash.assign(response.boot_hash().begin(), response.boot_hash().end());
996 return ErrorCode::OK;
997 }
998
999 } // namespace keymaster
1000 } // namespace hardware
1001 } // namespace android
1002