Home | History | Annotate | Download | only in keymaster
      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 "certs.h"
     21 #include "import_key.h"
     22 #include "import_wrapped_key.h"
     23 #include "proto_utils.h"
     24 
     25 #include <Keymaster.client.h>
     26 #include <nos/debug.h>
     27 #include <nos/NuggetClient.h>
     28 
     29 #include <keymasterV4_0/key_param_output.h>
     30 
     31 #include <openssl/sha.h>
     32 
     33 #include <android-base/logging.h>
     34 #include <android-base/properties.h>
     35 
     36 #include <algorithm>
     37 
     38 #include <time.h>
     39 
     40 namespace android {
     41 namespace hardware {
     42 namespace keymaster {
     43 
     44 namespace {
     45 
     46 constexpr char PROPERTY_OS_VERSION[] = "ro.build.version.release";
     47 constexpr char PROPERTY_OS_PATCHLEVEL[] = "ro.build.version.security_patch";
     48 constexpr char PROPERTY_VENDOR_PATCHLEVEL[] = "ro.vendor.build.security_patch";
     49 
     50 std::string DigitsOnly(const std::string& code) {
     51     // Keep digits only.
     52     std::string filtered_code;
     53     std::copy_if(code.begin(), code.end(), std::back_inserter(filtered_code),
     54                  isdigit);
     55     return filtered_code;
     56 }
     57 
     58 /** Get one version number from a string and move loc to the point after the
     59  * next version delimiter.
     60  */
     61 uint32_t ExtractVersion(const std::string& version, size_t* loc) {
     62     if (*loc == std::string::npos || *loc >= version.size()) {
     63         return 0;
     64     }
     65 
     66     uint32_t value = 0;
     67     size_t new_loc = version.find('.', *loc);
     68     if (new_loc == std::string::npos) {
     69         auto sanitized = DigitsOnly(version.substr(*loc));
     70         if (!sanitized.empty()) {
     71             if (sanitized.size() < version.size() - *loc) {
     72                 LOG(ERROR) << "Unexpected version format: \"" << version
     73                            << "\"";
     74             }
     75             value = std::stoi(sanitized);
     76         }
     77         *loc = new_loc;
     78     } else {
     79         auto sanitized = DigitsOnly(version.substr(*loc, new_loc - *loc));
     80         if (!sanitized.empty()) {
     81             if (sanitized.size() < new_loc - *loc) {
     82                 LOG(ERROR) << "Unexpected version format: \"" << version
     83                            << "\"";
     84             }
     85             value = std::stoi(sanitized);
     86         }
     87         *loc = new_loc + 1;
     88     }
     89     return value;
     90 }
     91 
     92 uint32_t VersionToUint32(const std::string& version) {
     93     size_t loc = 0;
     94     uint32_t major = ExtractVersion(version, &loc);
     95     uint32_t minor = ExtractVersion(version, &loc);
     96     uint32_t subminor = ExtractVersion(version, &loc);
     97     return major * 10000 + minor * 100 + subminor;
     98 }
     99 
    100 uint32_t DateCodeToUint32(const std::string& code, bool include_day) {
    101     // Keep digits only.
    102     std::string filtered_code = DigitsOnly(code);
    103 
    104     // Return 0 if the date string has an unexpected number of digits.
    105     uint32_t return_value = 0;
    106     if (filtered_code.size() == 8) {
    107         return_value = std::stoi(filtered_code);
    108         if (!include_day) {
    109             return_value /= 100;
    110         }
    111     } else if (filtered_code.size() == 6) {
    112         return_value = std::stoi(filtered_code);
    113         if (include_day) {
    114             return_value *= 100;
    115         }
    116     } else {
    117         LOG(ERROR) << "Unexpected patchset format: \"" << code << "\"";
    118     }
    119     return return_value;
    120 }
    121 
    122 // Helper class to call a finalizer on stack unwind.
    123 class Finalize {
    124  private:
    125     std::function<void()> f_;
    126 
    127  public:
    128     Finalize(std::function<void()> f) : f_(f) {}
    129     ~Finalize() { if (f_) f_(); }
    130     void release() { f_ = {}; }
    131 };
    132 
    133 inline std::string hidlVec2String(const hidl_vec<uint8_t>& value) {
    134     return std::string(
    135         reinterpret_cast<const std::string::value_type*>(
    136             &value[0]), value.size());
    137 }
    138 
    139 }  // namespace
    140 
    141 // std
    142 using std::string;
    143 
    144 // base
    145 using ::android::base::GetProperty;
    146 using ::android::base::WaitForPropertyCreation;
    147 
    148 // libhidl
    149 using ::android::hardware::Void;
    150 
    151 // HAL
    152 using ::android::hardware::keymaster::V4_0::Algorithm;
    153 using ::android::hardware::keymaster::V4_0::KeyCharacteristics;
    154 using ::android::hardware::keymaster::V4_0::KeyFormat;
    155 using ::android::hardware::keymaster::V4_0::HardwareAuthToken;
    156 using ::android::hardware::keymaster::V4_0::HardwareAuthenticatorType;
    157 using ::android::hardware::keymaster::V4_0::SecurityLevel;
    158 using ::android::hardware::keymaster::V4_0::Tag;
    159 
    160 // nos
    161 using nos::NuggetClient;
    162 
    163 // Keymaster app
    164 // KM 3.0 types
    165 using ::nugget::app::keymaster::AddRngEntropyRequest;
    166 using ::nugget::app::keymaster::AddRngEntropyResponse;
    167 using ::nugget::app::keymaster::GenerateKeyRequest;
    168 using ::nugget::app::keymaster::GenerateKeyResponse;
    169 using ::nugget::app::keymaster::GetKeyCharacteristicsRequest;
    170 using ::nugget::app::keymaster::GetKeyCharacteristicsResponse;
    171 using ::nugget::app::keymaster::ImportKeyRequest;
    172 using ::nugget::app::keymaster::ImportKeyResponse;
    173 using ::nugget::app::keymaster::ExportKeyRequest;
    174 using ::nugget::app::keymaster::ExportKeyResponse;
    175 using ::nugget::app::keymaster::StartAttestKeyRequest;
    176 using ::nugget::app::keymaster::StartAttestKeyResponse;
    177 using ::nugget::app::keymaster::ContinueAttestKeyRequest;
    178 using ::nugget::app::keymaster::ContinueAttestKeyResponse;
    179 using ::nugget::app::keymaster::FinishAttestKeyRequest;
    180 using ::nugget::app::keymaster::FinishAttestKeyResponse;
    181 using ::nugget::app::keymaster::UpgradeKeyRequest;
    182 using ::nugget::app::keymaster::UpgradeKeyResponse;
    183 using ::nugget::app::keymaster::DeleteKeyRequest;
    184 using ::nugget::app::keymaster::DeleteKeyResponse;
    185 using ::nugget::app::keymaster::DeleteAllKeysRequest;
    186 using ::nugget::app::keymaster::DeleteAllKeysResponse;
    187 using ::nugget::app::keymaster::DestroyAttestationIdsRequest;
    188 using ::nugget::app::keymaster::DestroyAttestationIdsResponse;
    189 using ::nugget::app::keymaster::BeginOperationRequest;
    190 using ::nugget::app::keymaster::BeginOperationResponse;
    191 using ::nugget::app::keymaster::UpdateOperationRequest;
    192 using ::nugget::app::keymaster::UpdateOperationResponse;
    193 using ::nugget::app::keymaster::FinishOperationRequest;
    194 using ::nugget::app::keymaster::FinishOperationResponse;
    195 using ::nugget::app::keymaster::AbortOperationRequest;
    196 using ::nugget::app::keymaster::AbortOperationResponse;
    197 using ::nugget::app::keymaster::ComputeSharedHmacRequest;
    198 using ::nugget::app::keymaster::ComputeSharedHmacResponse;
    199 using ::nugget::app::keymaster::GetHmacSharingParametersRequest;
    200 using ::nugget::app::keymaster::GetHmacSharingParametersResponse;
    201 using ::nugget::app::keymaster::SetSystemVersionInfoRequest;
    202 using ::nugget::app::keymaster::SetSystemVersionInfoResponse;
    203 using ::nugget::app::keymaster::GetBootInfoRequest;
    204 using ::nugget::app::keymaster::GetBootInfoResponse;
    205 
    206 // KM 4.0 types
    207 using ::nugget::app::keymaster::ImportWrappedKeyRequest;
    208 namespace nosapp = ::nugget::app::keymaster;
    209 
    210 // KM internal types
    211 using ::nugget::app::keymaster::AttestationSelector;
    212 
    213 static ErrorCode status_to_error_code(uint32_t status)
    214 {
    215     switch (status) {
    216     case APP_SUCCESS:
    217         return ErrorCode::OK;
    218         break;
    219     case APP_ERROR_BOGUS_ARGS:
    220         return ErrorCode::INVALID_ARGUMENT;
    221         break;
    222     case APP_ERROR_INTERNAL:
    223         return ErrorCode::UNKNOWN_ERROR;
    224         break;
    225     case APP_ERROR_TOO_MUCH:
    226         return ErrorCode::INSUFFICIENT_BUFFER_SPACE;
    227         break;
    228     case APP_ERROR_RPC:
    229         return ErrorCode::SECURE_HW_COMMUNICATION_FAILED;
    230         break;
    231     // TODO: app specific error codes go here.
    232     default:
    233         return ErrorCode::UNKNOWN_ERROR;
    234         break;
    235     }
    236 }
    237 
    238 static uint64_t ms_since_epoch(void)
    239 {
    240     uint64_t seconds;
    241     uint64_t milli_seconds;
    242     struct timespec spec;
    243 
    244     ::clock_gettime(CLOCK_REALTIME, &spec);
    245 
    246     seconds = spec.tv_sec;
    247     milli_seconds = spec.tv_nsec / (1000 * 1000);
    248 
    249     return (seconds * 1000) + milli_seconds;
    250 }
    251 
    252 #define KM_CALL(meth, request, response) {                                    \
    253     const uint32_t status = _keymaster. meth (request, &response);            \
    254     const ErrorCode error_code = translate_error_code(response.error_code()); \
    255     if (status != APP_SUCCESS) {                                              \
    256         LOG(ERROR) << #meth << " : request failed with status: "              \
    257                    << nos::StatusCodeString(status);                          \
    258         return status_to_error_code(status);                                  \
    259     }                                                                         \
    260     if (error_code != ErrorCode::OK) {                                        \
    261         LOG(ERROR) << #meth << " : device response error code: "              \
    262                    << error_code;                                             \
    263         return error_code;                                                    \
    264     }                                                                         \
    265 }
    266 
    267 #define KM_CALLV(meth, request, response, ...) {                              \
    268     const uint32_t status = _keymaster. meth (request, &response);            \
    269     const ErrorCode error_code = translate_error_code(response.error_code()); \
    270     if (status != APP_SUCCESS) {                                              \
    271         LOG(ERROR) << #meth << " : request failed with status: "              \
    272                    << nos::StatusCodeString(status);                          \
    273         _hidl_cb(status_to_error_code(status), __VA_ARGS__);                  \
    274         return Void();                                                        \
    275     }                                                                         \
    276     if (error_code != ErrorCode::OK) {                                        \
    277         LOG(ERROR) << #meth << " : device response error code: "              \
    278                    << error_code;                                             \
    279         _hidl_cb(error_code, __VA_ARGS__);                                    \
    280         return Void();                                                        \
    281     }                                                                         \
    282 }
    283 
    284 #define KM_CALLV_ABORT(meth, request, response, ...) {                        \
    285     const uint32_t status = _keymaster. meth (request, &response);            \
    286     const ErrorCode error_code = translate_error_code(response.error_code()); \
    287     if (status != APP_SUCCESS) {                                              \
    288         LOG(ERROR) << #meth << " : request failed with status: "              \
    289                    << nos::StatusCodeString(status) << " aborting operation"; \
    290         _hidl_cb(status_to_error_code(status), __VA_ARGS__);                  \
    291         abort(request.handle().handle());                                     \
    292         return Void();                                                        \
    293     }                                                                         \
    294     if (error_code != ErrorCode::OK) {                                        \
    295         LOG(ERROR) << #meth << " : device response error code: "              \
    296                    << error_code;                                             \
    297         _hidl_cb(error_code, __VA_ARGS__);                                    \
    298         return Void();                                                        \
    299     }                                                                         \
    300 }
    301 
    302 // Methods from ::android::hardware::keymaster::V3_0::IKeymasterDevice follow.
    303 
    304 KeymasterDevice::KeymasterDevice(KeymasterClient& keymaster) :
    305         _keymaster{keymaster} {
    306     // Block until all of the properties have been created
    307     while (!(WaitForPropertyCreation(PROPERTY_OS_VERSION) &&
    308              WaitForPropertyCreation(PROPERTY_OS_PATCHLEVEL) &&
    309              WaitForPropertyCreation(PROPERTY_VENDOR_PATCHLEVEL))) {}
    310 
    311     _os_version = VersionToUint32(GetProperty(PROPERTY_OS_VERSION, ""));
    312     _os_patchlevel = DateCodeToUint32(GetProperty(PROPERTY_OS_PATCHLEVEL, ""),
    313                                      false /* include_day */);
    314     _vendor_patchlevel = DateCodeToUint32(
    315             GetProperty(PROPERTY_VENDOR_PATCHLEVEL, ""),
    316             true /* include_day */);
    317 
    318     SendSystemVersionInfo();
    319     GetBootInfo();
    320 }
    321 
    322 Return<void> KeymasterDevice::getHardwareInfo(
    323         getHardwareInfo_cb _hidl_cb)
    324 {
    325     LOG(VERBOSE) << "Running KeymasterDevice::getHardwareInfo";
    326 
    327     (void)_keymaster;
    328     _hidl_cb(SecurityLevel::STRONGBOX,
    329              string("CitadelKeymaster"), string("Google"));
    330 
    331     return Void();
    332 }
    333 
    334 Return<void> KeymasterDevice::getHmacSharingParameters(
    335     getHmacSharingParameters_cb _hidl_cb)
    336 {
    337     LOG(VERBOSE) << "Running KeymasterDevice::getHmacSharingParameters";
    338 
    339     GetHmacSharingParametersRequest request;
    340     GetHmacSharingParametersResponse response;
    341     HmacSharingParameters result;
    342 
    343     KM_CALLV(GetHmacSharingParameters, request, response, result);
    344 
    345     ErrorCode ec = translate_error_code(response.error_code());
    346 
    347     if (ec != ErrorCode::OK) {
    348         _hidl_cb(ec, HmacSharingParameters());
    349     }
    350 
    351     const std::string & nonce = response.hmac_sharing_params().nonce();
    352     const std::string & seed = response.hmac_sharing_params().seed();
    353 
    354     if (seed.size() == 32) {
    355         result.seed.setToExternal(reinterpret_cast<uint8_t*>(
    356                 const_cast<char*>(seed.data())),
    357                 seed.size(), false);
    358     } else if (seed.size() != 0) {
    359         LOG(ERROR) << "Citadel returned unexpected seed size: "
    360                 << seed.size();
    361         _hidl_cb(ErrorCode::UNKNOWN_ERROR, HmacSharingParameters());
    362         return Void();
    363     }
    364 
    365     if (nonce.size() == result.nonce.size()) {
    366         std::copy(nonce.begin(), nonce.end(), result.nonce.data());
    367     } else {
    368         LOG(ERROR) << "Citadel returned unexpected nonce size: "
    369                 << nonce.size();
    370         _hidl_cb(ErrorCode::UNKNOWN_ERROR, HmacSharingParameters());
    371         return Void();
    372     }
    373 
    374     _hidl_cb(ec, result);
    375 
    376     return Void();
    377 }
    378 
    379 Return<void> KeymasterDevice::computeSharedHmac(
    380     const hidl_vec<HmacSharingParameters>& params,
    381     computeSharedHmac_cb _hidl_cb)
    382 {
    383     LOG(VERBOSE) << "Running KeymasterDevice::computeSharedHmac";
    384 
    385     ComputeSharedHmacRequest request;
    386     ComputeSharedHmacResponse response;
    387     hidl_vec<uint8_t> result;
    388 
    389     for (const HmacSharingParameters & param : params) {
    390         // TODO respect max number of parameters defined in
    391         // keymaster_types.proto
    392         nosapp::HmacSharingParameters* req_param =
    393                 request.add_hmac_sharing_params();
    394         req_param->set_nonce(
    395                 reinterpret_cast<const int8_t*>(
    396                 param.nonce.data()), param.nonce.size());
    397         req_param->set_seed(reinterpret_cast<const int8_t*>(param.seed.data()),
    398                 param.seed.size());
    399     }
    400 
    401     KM_CALLV(ComputeSharedHmac, request, response, result);
    402 
    403     ErrorCode ec = translate_error_code(response.error_code());
    404 
    405     if (ec != ErrorCode::OK) {
    406         _hidl_cb(ec, result);
    407         return Void();
    408     }
    409 
    410     const std::string & share_check = response.sharing_check();
    411 
    412     result.setToExternal(reinterpret_cast<uint8_t*>(
    413             const_cast<char*>(share_check.data())), share_check.size(), false);
    414     _hidl_cb(ec, result);
    415 
    416     return Void();
    417 }
    418 
    419 Return<void> KeymasterDevice::verifyAuthorization(
    420     uint64_t operationHandle, const hidl_vec<KeyParameter>& parametersToVerify,
    421     const HardwareAuthToken& authToken, verifyAuthorization_cb _hidl_cb)
    422 {
    423     LOG(VERBOSE) << "Running KeymasterDevice::verifyAuthorization";
    424 
    425     (void)operationHandle;
    426     (void)parametersToVerify;
    427     (void)authToken;
    428 
    429     (void)_keymaster;
    430     _hidl_cb(ErrorCode::UNIMPLEMENTED, VerificationToken());
    431 
    432     return Void();
    433 }
    434 
    435 Return<ErrorCode> KeymasterDevice::addRngEntropy(const hidl_vec<uint8_t>& data)
    436 {
    437     LOG(VERBOSE) << "Running KeymasterDevice::addRngEntropy";
    438 
    439     if (!data.size()) return ErrorCode::OK;
    440 
    441     const size_t chunk_size = 1024;
    442     for (size_t i = 0; i < data.size(); i += chunk_size) {
    443         AddRngEntropyRequest request;
    444         AddRngEntropyResponse response;
    445 
    446         request.set_data(&data[i], std::min(chunk_size, data.size() - i));
    447 
    448         // Call device.
    449         KM_CALL(AddRngEntropy, request, response);
    450     }
    451 
    452     return ErrorCode::OK;
    453 }
    454 
    455 Return<void> KeymasterDevice::generateKey(
    456         const hidl_vec<KeyParameter>& keyParams,
    457         generateKey_cb _hidl_cb)
    458 {
    459     LOG(VERBOSE) << "Running KeymasterDevice::generateKey";
    460 
    461     GenerateKeyRequest request;
    462     GenerateKeyResponse response;
    463 
    464     hidl_vec<uint8_t> blob;
    465     KeyCharacteristics characteristics;
    466     if (hidl_params_to_pb(
    467             keyParams, request.mutable_params()) != ErrorCode::OK) {
    468       _hidl_cb(ErrorCode::INVALID_ARGUMENT, blob, characteristics);
    469       return Void();
    470     }
    471     request.set_creation_time_ms(ms_since_epoch());
    472 
    473     // Call device.
    474     KM_CALLV(GenerateKey, request, response,
    475              hidl_vec<uint8_t>{}, KeyCharacteristics());
    476 
    477     blob.setToExternal(
    478         reinterpret_cast<uint8_t*>(
    479             const_cast<char*>(response.blob().blob().data())),
    480         response.blob().blob().size(), false);
    481     pb_to_hidl_params(response.characteristics().software_enforced(),
    482                       &characteristics.softwareEnforced);
    483     pb_to_hidl_params(response.characteristics().tee_enforced(),
    484                       &characteristics.hardwareEnforced);
    485 
    486     _hidl_cb(translate_error_code(response.error_code()),
    487              blob, characteristics);
    488     return Void();
    489 }
    490 
    491 Return<void> KeymasterDevice::getKeyCharacteristics(
    492         const hidl_vec<uint8_t>& keyBlob,
    493         const hidl_vec<uint8_t>& clientId,
    494         const hidl_vec<uint8_t>& appData,
    495         getKeyCharacteristics_cb _hidl_cb)
    496 {
    497     LOG(VERBOSE) << "Running KeymasterDevice::getKeyCharacteristics";
    498 
    499     GetKeyCharacteristicsRequest request;
    500     GetKeyCharacteristicsResponse response;
    501 
    502     request.mutable_blob()->set_blob(&keyBlob[0], keyBlob.size());
    503     request.set_client_id(&clientId[0], clientId.size());
    504     request.set_app_data(&appData[0], appData.size());
    505 
    506     // Call device.
    507     KM_CALLV(GetKeyCharacteristics, request, response, KeyCharacteristics());
    508 
    509     KeyCharacteristics characteristics;
    510     pb_to_hidl_params(response.characteristics().software_enforced(),
    511                       &characteristics.softwareEnforced);
    512     pb_to_hidl_params(response.characteristics().tee_enforced(),
    513                       &characteristics.hardwareEnforced);
    514 
    515     _hidl_cb(translate_error_code(response.error_code()), characteristics);
    516     return Void();
    517 }
    518 
    519 Return<void> KeymasterDevice::importKey(
    520         const hidl_vec<KeyParameter>& params, KeyFormat keyFormat,
    521         const hidl_vec<uint8_t>& keyData, importKey_cb _hidl_cb)
    522 {
    523     LOG(VERBOSE) << "Running KeymasterDevice::importKey";
    524 
    525     ErrorCode error;
    526     ImportKeyRequest request;
    527     ImportKeyResponse response;
    528 
    529     error = import_key_request(params, keyFormat, keyData, &request);
    530     if (error != ErrorCode::OK) {
    531         LOG(ERROR) << "ImportKey request parsing failed with error "
    532                    << error;
    533         _hidl_cb(error, hidl_vec<uint8_t>{}, KeyCharacteristics{});
    534         return Void();
    535     }
    536     request.set_creation_time_ms(ms_since_epoch());
    537 
    538     KM_CALLV(ImportKey, request, response,
    539              hidl_vec<uint8_t>{}, KeyCharacteristics{});
    540 
    541     hidl_vec<uint8_t> blob;
    542     blob.setToExternal(
    543         reinterpret_cast<uint8_t*>(
    544             const_cast<char*>(response.blob().blob().data())),
    545         response.blob().blob().size(), false);
    546 
    547     KeyCharacteristics characteristics;
    548     pb_to_hidl_params(response.characteristics().software_enforced(),
    549                       &characteristics.softwareEnforced);
    550     error = pb_to_hidl_params(response.characteristics().tee_enforced(),
    551                               &characteristics.hardwareEnforced);
    552     if (error != ErrorCode::OK) {
    553         LOG(ERROR) << "KeymasterDevice::importKey: response tee_enforced :"
    554                    << error;
    555         _hidl_cb(error, hidl_vec<uint8_t>{}, KeyCharacteristics{});
    556         return Void();
    557     }
    558 
    559     _hidl_cb(ErrorCode::OK, blob, characteristics);
    560     return Void();
    561 }
    562 
    563 Return<void> KeymasterDevice::exportKey(
    564         KeyFormat exportFormat, const hidl_vec<uint8_t>& keyBlob,
    565         const hidl_vec<uint8_t>& clientId,
    566         const hidl_vec<uint8_t>& appData, exportKey_cb _hidl_cb)
    567 {
    568     LOG(VERBOSE) << "Running KeymasterDevice::exportKey";
    569 
    570     ExportKeyRequest request;
    571     ExportKeyResponse response;
    572 
    573     request.set_format((::nugget::app::keymaster::KeyFormat)exportFormat);
    574     request.mutable_blob()->set_blob(&keyBlob[0], keyBlob.size());
    575     request.set_client_id(&clientId[0], clientId.size());
    576     request.set_app_data(&appData[0], appData.size());
    577 
    578     KM_CALLV(ExportKey, request, response, hidl_vec<uint8_t>{});
    579 
    580     hidl_vec<uint8_t> der;
    581     ErrorCode error_code = export_key_der(response, &der);
    582     if (error_code != ErrorCode::OK) {
    583         LOG(ERROR) << "KeymasterDevice::exportKey: DER conversion failed: "
    584                    << error_code;
    585         _hidl_cb(error_code, hidl_vec<uint8_t>{});
    586         return Void();
    587     }
    588 
    589     _hidl_cb(error_code, der);
    590     return Void();
    591 }
    592 
    593 #define ATTESTATION_APPLICATION_ID_MAX_SIZE 1024
    594 #define UTCTIME_STR_WITH_NUL_SIZE           14
    595 static size_t integer_size(uint64_t value)
    596 {
    597         size_t octet_count = 1;
    598         for (value >>= 8; value; value >>= 8) {
    599                 octet_count++;
    600         }
    601         return octet_count;
    602 }
    603 static size_t encoded_length_size(size_t length)
    604 {
    605         if (length < 0x80) {
    606                 return 1;
    607         }
    608         return integer_size(length) + 1;
    609 }
    610 
    611 static uint8_t *asn1_encode_length(size_t length, const uint8_t *head, uint8_t *tail)
    612 {
    613         if (!tail || tail < head + encoded_length_size(length)) {
    614                 return NULL;
    615         }
    616 
    617         if (length < 0x80) {
    618                 // Short length case
    619                 *(--tail) = length;
    620         } else {
    621                 // Encode length
    622                 uint8_t length_len;
    623                 uint8_t *orig_tail = tail;
    624                 do {
    625                         *(--tail) = length & 0xFF;
    626                         length >>= 8;
    627                 } while (length);
    628 
    629                 // Encode length of length.  Assumes length < pow(128, 127).
    630                 // Should be good.
    631                 length_len = (orig_tail - tail);
    632                 *(--tail) = 0x80 | length_len;
    633         }
    634         return tail;
    635 }
    636 
    637 Return<void> KeymasterDevice::attestKey(
    638         const hidl_vec<uint8_t>& keyToAttest,
    639         const hidl_vec<KeyParameter>& attestParams,
    640         attestKey_cb _hidl_cb)
    641 {
    642     LOG(VERBOSE) << "Running KeymasterDevice::attestKey";
    643 
    644     StartAttestKeyRequest startRequest;
    645     StartAttestKeyResponse startResponse;
    646 
    647     // Ensure that required parameters are present.
    648     tag_map_t attest_tag_map;
    649     if (hidl_params_to_map(attestParams, &attest_tag_map) != ErrorCode::OK) {
    650         _hidl_cb(ErrorCode::INVALID_ARGUMENT, hidl_vec<hidl_vec<uint8_t> >{});
    651       return Void();
    652     }
    653     if (attest_tag_map.find(Tag::ATTESTATION_APPLICATION_ID) ==
    654         attest_tag_map.end()) {
    655         _hidl_cb(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
    656                  hidl_vec<hidl_vec<uint8_t> >{});
    657       return Void();
    658     }
    659 
    660     hidl_vec<uint8_t> client_id;
    661     if (attest_tag_map.find(Tag::APPLICATION_ID) != attest_tag_map.end()) {
    662         client_id = attest_tag_map.find(Tag::APPLICATION_ID)->second[0].blob;
    663     }
    664     hidl_vec<uint8_t> app_data;
    665     if (attest_tag_map.find(Tag::APPLICATION_DATA) != attest_tag_map.end()) {
    666         app_data = attest_tag_map.find(
    667             Tag::APPLICATION_DATA)->second[0].blob;
    668     }
    669 
    670     GetKeyCharacteristicsRequest charRequest;
    671     GetKeyCharacteristicsResponse charResponse;
    672 
    673     charRequest.mutable_blob()->set_blob(&keyToAttest[0], keyToAttest.size());
    674     charRequest.set_client_id(&client_id[0], client_id.size());
    675     charRequest.set_app_data(&app_data[0], app_data.size());
    676 
    677     // Call device.
    678     KM_CALLV(GetKeyCharacteristics, charRequest,
    679              charResponse, hidl_vec<hidl_vec<uint8_t> >{});
    680 
    681     KeyCharacteristics characteristics;
    682     pb_to_hidl_params(charResponse.characteristics().software_enforced(),
    683                       &characteristics.softwareEnforced);
    684     pb_to_hidl_params(charResponse.characteristics().tee_enforced(),
    685                       &characteristics.hardwareEnforced);
    686 
    687     tag_map_t char_tag_map;
    688     if (hidl_params_to_map(characteristics.softwareEnforced,
    689                            &attest_tag_map) != ErrorCode::OK) {
    690         _hidl_cb(ErrorCode::INVALID_ARGUMENT, hidl_vec<hidl_vec<uint8_t> >{});
    691       return Void();
    692     }
    693 
    694     time_t not_before = 0;
    695     if (char_tag_map.find(Tag::ACTIVE_DATETIME) != char_tag_map.end()) {
    696         not_before = char_tag_map.find(
    697             Tag::ACTIVE_DATETIME)->second[0].f.dateTime;
    698     } else if (char_tag_map.find(Tag::CREATION_DATETIME) !=
    699                char_tag_map.end()) {
    700         not_before = char_tag_map.find(
    701             Tag::CREATION_DATETIME)->second[0].f.dateTime;
    702     }
    703     // TODO: else: both ACTIVE and CREATION datetime are absent, is
    704     // this an error?
    705     time_t not_after = 0;
    706     if (char_tag_map.find(Tag::USAGE_EXPIRE_DATETIME) != char_tag_map.end()) {
    707         not_after = char_tag_map.find(
    708             Tag::USAGE_EXPIRE_DATETIME)->second[0].f.dateTime;
    709     } else {
    710         not_after = 1842739199; // Batch cert expiry date: 2028-05-23:23:59:59.
    711     }
    712 
    713     char not_before_str[UTCTIME_STR_WITH_NUL_SIZE] = {};
    714     char not_after_str[UTCTIME_STR_WITH_NUL_SIZE] = {};
    715     if (::strftime(not_before_str, sizeof(not_before_str),
    716                    "%y%m%d%H%M%SZ", gmtime(&not_before)) == 0 ||
    717         ::strftime(not_after_str, sizeof(not_after_str),
    718                    "%y%m%d%H%M%SZ", gmtime(&not_after)) == 0) {
    719         _hidl_cb(ErrorCode::UNKNOWN_ERROR, hidl_vec<hidl_vec<uint8_t> >{});
    720     }
    721 
    722     startRequest.mutable_blob()->set_blob(&keyToAttest[0], keyToAttest.size());
    723     if (hidl_params_to_pb(
    724             attestParams, startRequest.mutable_params()) != ErrorCode::OK) {
    725       _hidl_cb(ErrorCode::INVALID_ARGUMENT, hidl_vec<hidl_vec<uint8_t> >{});
    726       return Void();
    727     }
    728 
    729     // Developer configs (i.e. nodelocked-RO), and PROTO devices will
    730     // fall back to TEST certs here, since BATCH certs will be
    731     // unavailable.  The selected certificate may be determined via
    732     // info included in the response to FinishAttestKeyRequest().
    733     startRequest.set_selector(AttestationSelector::ATTEST_BATCH);
    734 
    735     startRequest.set_not_before(not_before_str,
    736                                 sizeof(not_before_str) - 1);
    737     startRequest.set_not_after(not_after_str,
    738                                 sizeof(not_after_str) - 1);
    739 
    740     // TODO: as an optimization, avoid sending the
    741     // ATTESTATION_APPLICATION_ID to Start, since only the length of
    742     // this field is needed at this stage.
    743     // NOTE: citadel adds the AAID to the hash in the prologue for now. So if this
    744     // is ever changes the HASH_update call needs to move in the citadel firmware.
    745 
    746     KM_CALLV(StartAttestKey, startRequest, startResponse,
    747              hidl_vec<hidl_vec<uint8_t> >{});
    748 
    749     uint64_t operationHandle = startResponse.handle().handle();
    750     ContinueAttestKeyRequest continueRequest;
    751     ContinueAttestKeyResponse continueResponse;
    752     // Prepare to abort the pending operation in event of an error.
    753     Finalize finalize([&] () { abort(operationHandle); });
    754 
    755     continueRequest.mutable_handle()->set_handle(operationHandle);
    756     if (hidl_params_to_pb(
    757             attestParams, continueRequest.mutable_params()) != ErrorCode::OK) {
    758         LOG(ERROR) << "Failed to parse attest params";
    759         _hidl_cb(ErrorCode::INVALID_ARGUMENT, hidl_vec<hidl_vec<uint8_t> >{});
    760         return Void();
    761     }
    762 
    763     KM_CALLV(ContinueAttestKey, continueRequest, continueResponse,
    764              hidl_vec<hidl_vec<uint8_t> >{});
    765 
    766     FinishAttestKeyRequest finishRequest;
    767     FinishAttestKeyResponse finishResponse;
    768 
    769     finishRequest.mutable_handle()->set_handle(operationHandle);
    770 
    771     KM_CALLV(FinishAttestKey, finishRequest, finishResponse,
    772              hidl_vec<hidl_vec<uint8_t> >{});
    773 
    774     hidl_vec<uint8_t>& attestation_application_id =
    775             attest_tag_map[Tag::ATTESTATION_APPLICATION_ID].begin()->blob;
    776     size_t cert_len = startResponse.certificate_prologue().size()
    777                     + attestation_application_id.size()
    778                     + continueResponse.certificate_body().size()
    779                     + finishResponse.certificate_epilogue().size();
    780 
    781     std::stringstream ss;
    782     {
    783         char c = 0x30;
    784         ss.write(&c, 1); // DER_SEQUENCE | DER_CONSTRUCTED
    785 
    786         uint8_t buffer[10];
    787         auto * cert_header = asn1_encode_length(cert_len, buffer, buffer + sizeof(buffer));
    788 
    789         if (cert_header == nullptr) {
    790             LOG(ERROR) << "Failed to generate attestation certificate sequence header";
    791             _hidl_cb(ErrorCode::UNKNOWN_ERROR, hidl_vec<hidl_vec<uint8_t> >{});
    792             return Void();
    793         }
    794         ss.write(reinterpret_cast<char*>(cert_header), buffer + sizeof(buffer) - cert_header);
    795     }
    796 
    797     ss << startResponse.certificate_prologue();
    798     ss.write(reinterpret_cast<const std::stringstream::char_type*>(
    799             attestation_application_id.data()), attestation_application_id.size());
    800     ss << continueResponse.certificate_body();
    801     ss << finishResponse.certificate_epilogue();
    802 
    803     if (!ss) {
    804         LOG(ERROR) << "Failed to generate attestation certificate";
    805         _hidl_cb(ErrorCode::UNKNOWN_ERROR, hidl_vec<hidl_vec<uint8_t> >{});
    806         return Void();
    807     }
    808 
    809     vector<hidl_vec<uint8_t> > chain;
    810     string attestation_str = ss.str();
    811     {
    812         hidl_vec<uint8_t> attestation_certificate;
    813         attestation_certificate.setToExternal(
    814                 reinterpret_cast<uint8_t*>(
    815                         const_cast<char*>(attestation_str.data())),
    816                 attestation_str.size(), false);
    817 
    818         chain.push_back(std::move(attestation_certificate));
    819 
    820         hidl_vec<uint8_t> batch_cert;
    821         hidl_vec<uint8_t> intermediate_cert;
    822         hidl_vec<uint8_t> root;
    823 
    824         for (const KeyParameter &param : characteristics.hardwareEnforced) {
    825             if (param.tag != Tag::ALGORITHM) {
    826                 continue;
    827             }
    828 
    829             // Node-locked RO implies that factory provisioned certs
    830             // (if any), are inaccessible, so fallback to the TEST
    831             // certs.  Similarly, PROTO chips were not provisioned
    832             // with certs, and hence will fallback to TEST certs.
    833             if (finishResponse.nodelocked_ro() ||
    834                 finishResponse.chip_fusing() == nosapp::FUSING_PROTO) {
    835                 if (param.f.algorithm == Algorithm::RSA) {
    836                     batch_cert.setToExternal(
    837                         const_cast<uint8_t*>(
    838                             TEST_BATCH_RSA_CERT),
    839                                       sizeof(TEST_BATCH_RSA_CERT));
    840                     intermediate_cert.setToExternal(
    841                         const_cast<uint8_t*>(
    842                             TEST_BATCH_RSA_INT_CERT),
    843                         sizeof(TEST_BATCH_RSA_INT_CERT));
    844                     root.setToExternal(
    845                         const_cast<uint8_t*>(
    846                             TEST_BATCH_ROOT_CERT),
    847                         sizeof(TEST_BATCH_ROOT_CERT));
    848                 } else {
    849                     batch_cert.setToExternal(
    850                         const_cast<uint8_t*>(
    851                             TEST_BATCH_EC_CERT),
    852                         sizeof(TEST_BATCH_EC_CERT));
    853                     intermediate_cert.setToExternal(
    854                         const_cast<uint8_t*>(
    855                             TEST_BATCH_EC_INT_CERT),
    856                         sizeof(TEST_BATCH_EC_INT_CERT));
    857                     root.setToExternal(
    858                         const_cast<uint8_t*>(
    859                             TEST_BATCH_ROOT_CERT),
    860                         sizeof(TEST_BATCH_ROOT_CERT));
    861                 }
    862             } else if (finishResponse.chip_fusing() == nosapp::FUSING_DVT) {
    863                 if (param.f.algorithm == Algorithm::RSA) {
    864                     batch_cert.setToExternal(
    865                         const_cast<uint8_t*>(DEV_BATCH_RSA_CERT),
    866                         sizeof(DEV_BATCH_RSA_CERT));
    867                     intermediate_cert.setToExternal(
    868                         const_cast<uint8_t*>(DEV_BATCH_RSA_INT_CERT),
    869                         sizeof(DEV_BATCH_RSA_INT_CERT));
    870                 } else {
    871                     batch_cert.setToExternal(
    872                         const_cast<uint8_t*>(DEV_BATCH_EC_CERT),
    873                         sizeof(DEV_BATCH_EC_CERT));
    874                     intermediate_cert.setToExternal(
    875                         const_cast<uint8_t*>(DEV_BATCH_EC_INT_CERT),
    876                         sizeof(DEV_BATCH_EC_INT_CERT));
    877                 }
    878                 root.setToExternal(
    879                     const_cast<uint8_t*>(DEV_BATCH_ROOT_CERT),
    880                     sizeof(DEV_BATCH_ROOT_CERT));
    881             } else {  // PVT!
    882                 if (param.f.algorithm == Algorithm::RSA) {
    883                     batch_cert.setToExternal(
    884                         const_cast<uint8_t*>(PROD_BATCH_RSA_CERT),
    885                         sizeof(PROD_BATCH_RSA_CERT));
    886                     intermediate_cert.setToExternal(
    887                         const_cast<uint8_t*>(PROD_BATCH_RSA_INT_CERT),
    888                         sizeof(PROD_BATCH_RSA_INT_CERT));
    889                 } else {
    890                     batch_cert.setToExternal(
    891                         const_cast<uint8_t*>(PROD_BATCH_EC_CERT),
    892                         sizeof(PROD_BATCH_EC_CERT));
    893                     intermediate_cert.setToExternal(
    894                         const_cast<uint8_t*>(PROD_BATCH_EC_INT_CERT),
    895                         sizeof(PROD_BATCH_EC_INT_CERT));
    896                 }
    897                 root.setToExternal(
    898                     const_cast<uint8_t*>(PROD_BATCH_ROOT_CERT),
    899                     sizeof(PROD_BATCH_ROOT_CERT));
    900             }
    901             break; // we found the ALGORITM tag so we can break the loop
    902         }
    903 
    904         chain.push_back(std::move(batch_cert));
    905         chain.push_back(std::move(intermediate_cert));
    906         chain.push_back(std::move(root));
    907     }
    908 
    909     _hidl_cb(ErrorCode::OK, chain);
    910     finalize.release();
    911     return Void();
    912 }
    913 
    914 Return<void> KeymasterDevice::upgradeKey(
    915         const hidl_vec<uint8_t>& keyBlobToUpgrade,
    916         const hidl_vec<KeyParameter>& upgradeParams,
    917         upgradeKey_cb _hidl_cb)
    918 {
    919     LOG(VERBOSE) << "Running KeymasterDevice::upgradeKey";
    920 
    921     UpgradeKeyRequest request;
    922     UpgradeKeyResponse response;
    923 
    924     request.mutable_blob()->set_blob(&keyBlobToUpgrade[0],
    925                                      keyBlobToUpgrade.size());
    926 
    927     hidl_vec<uint8_t> blob;
    928     if (hidl_params_to_pb(
    929             upgradeParams, request.mutable_params()) != ErrorCode::OK) {
    930       _hidl_cb(ErrorCode::INVALID_ARGUMENT, blob);
    931       return Void();
    932     }
    933 
    934     KM_CALLV(UpgradeKey, request, response, hidl_vec<uint8_t>{});
    935 
    936     blob.setToExternal(
    937         reinterpret_cast<uint8_t*>(
    938             const_cast<char*>(response.blob().blob().data())),
    939         response.blob().blob().size(), false);
    940 
    941     _hidl_cb(translate_error_code(response.error_code()), blob);
    942     return Void();
    943 }
    944 
    945 Return<ErrorCode> KeymasterDevice::deleteKey(const hidl_vec<uint8_t>& keyBlob)
    946 {
    947     LOG(VERBOSE) << "Running KeymasterDevice::deleteKey";
    948 
    949     DeleteKeyRequest request;
    950     DeleteKeyResponse response;
    951 
    952     request.mutable_blob()->set_blob(&keyBlob[0], keyBlob.size());
    953 
    954     KM_CALL(DeleteKey, request, response);
    955 
    956     return translate_error_code(response.error_code());
    957 }
    958 
    959 Return<ErrorCode> KeymasterDevice::deleteAllKeys()
    960 {
    961     LOG(VERBOSE) << "Running KeymasterDevice::deleteAllKeys";
    962 
    963     DeleteAllKeysRequest request;
    964     DeleteAllKeysResponse response;
    965 
    966     KM_CALL(DeleteAllKeys, request, response);
    967 
    968     return translate_error_code(response.error_code());
    969 }
    970 
    971 Return<ErrorCode> KeymasterDevice::destroyAttestationIds()
    972 {
    973     LOG(VERBOSE) << "Running KeymasterDevice::destroyAttestationIds";
    974 
    975     DestroyAttestationIdsRequest request;
    976     DestroyAttestationIdsResponse response;
    977 
    978     KM_CALL(DestroyAttestationIds, request, response);
    979 
    980     return translate_error_code(response.error_code());
    981 }
    982 
    983 Return<void> KeymasterDevice::begin(
    984         KeyPurpose purpose, const hidl_vec<uint8_t>& key,
    985         const hidl_vec<KeyParameter>& inParams,
    986         const HardwareAuthToken& authToken,
    987         begin_cb _hidl_cb)
    988 {
    989     LOG(VERBOSE) << "Running KeymasterDevice::begin";
    990 
    991     BeginOperationRequest request;
    992     BeginOperationResponse response;
    993 
    994     request.set_purpose((::nugget::app::keymaster::KeyPurpose)purpose);
    995     request.mutable_blob()->set_blob(&key[0], key.size());
    996 
    997     hidl_vec<KeyParameter> params;
    998     if (translate_auth_token(
    999             authToken, request.mutable_auth_token()) != ErrorCode::OK) {
   1000         _hidl_cb(ErrorCode::INVALID_ARGUMENT, params,
   1001                  response.handle().handle());
   1002         return Void();
   1003     }
   1004     if (hidl_params_to_pb(
   1005             inParams, request.mutable_params()) != ErrorCode::OK) {
   1006       _hidl_cb(ErrorCode::INVALID_ARGUMENT, params,
   1007                response.handle().handle());
   1008       return Void();
   1009     }
   1010     tag_map_t tag_map;
   1011     if (hidl_params_to_map(inParams, &tag_map) != ErrorCode::OK) {
   1012         _hidl_cb(ErrorCode::INVALID_ARGUMENT, params,
   1013                  response.handle().handle());
   1014       return Void();
   1015     }
   1016 
   1017     KM_CALLV(BeginOperation, request, response, hidl_vec<KeyParameter>{}, 0);
   1018 
   1019     // Setup HAL buffering for this operation's data.
   1020     Algorithm algorithm;
   1021     if (translate_algorithm(response.algorithm(), &algorithm) !=
   1022         ErrorCode::OK) {
   1023         if (this->abort(response.handle().handle()) != ErrorCode::OK) {
   1024             LOG(ERROR) << "abort( " << response.handle().handle()
   1025                        << ") failed";
   1026         }
   1027         _hidl_cb(ErrorCode::INVALID_ARGUMENT, params,
   1028                  response.handle().handle());
   1029         return Void();
   1030     }
   1031     ErrorCode error_code = buffer_begin(response.handle().handle(), algorithm);
   1032     if (error_code != ErrorCode::OK) {
   1033         if (this->abort(response.handle().handle()) != ErrorCode::OK) {
   1034             LOG(ERROR) << "abort( " << response.handle().handle()
   1035                        << ") failed";
   1036         }
   1037         _hidl_cb(ErrorCode::UNKNOWN_ERROR, params,
   1038                  response.handle().handle());
   1039         return Void();
   1040     }
   1041 
   1042     pb_to_hidl_params(response.params(), &params);
   1043 
   1044     _hidl_cb(translate_error_code(response.error_code()), params,
   1045              response.handle().handle());
   1046     return Void();
   1047 }
   1048 
   1049 Return<void> KeymasterDevice::update(
   1050         uint64_t operationHandle,
   1051         const hidl_vec<KeyParameter>& inParams,
   1052         const hidl_vec<uint8_t>& input,
   1053         const HardwareAuthToken& authToken,
   1054         const VerificationToken& verificationToken,
   1055         update_cb _hidl_cb)
   1056 {
   1057     LOG(VERBOSE) << "Running KeymasterDevice::update";
   1058 
   1059     UpdateOperationRequest request;
   1060     UpdateOperationResponse response;
   1061 
   1062     uint32_t consumed;
   1063     hidl_vec<uint8_t> output;
   1064     hidl_vec<KeyParameter> params;
   1065     ErrorCode error_code;
   1066     error_code = buffer_append(operationHandle, input, &consumed);
   1067     if (error_code != ErrorCode::OK) {
   1068         _hidl_cb(error_code, 0, params, output);
   1069         return Void();
   1070     }
   1071 
   1072     hidl_vec<uint8_t> blocks;
   1073     error_code = buffer_peek(operationHandle, &blocks);
   1074     if (error_code != ErrorCode::OK) {
   1075         _hidl_cb(error_code, 0, params, output);
   1076         return Void();
   1077     }
   1078 
   1079     // blocks.size() may be zero, but do a round-trip none-the-less
   1080     // since this may be GCM, there may be AAD data in params.
   1081     // TODO: as an optimization, do some inspection apriori.
   1082 
   1083     request.mutable_handle()->set_handle(operationHandle);
   1084 
   1085     if (hidl_params_to_pb(
   1086             inParams, request.mutable_params()) != ErrorCode::OK) {
   1087       _hidl_cb(ErrorCode::INVALID_ARGUMENT, 0, params, output);
   1088       return Void();
   1089     }
   1090 
   1091     request.set_input(&blocks[0], blocks.size());
   1092     if (translate_auth_token(
   1093             authToken, request.mutable_auth_token()) != ErrorCode::OK) {
   1094         _hidl_cb(ErrorCode::INVALID_ARGUMENT, 0, params, output);
   1095         return Void();
   1096     }
   1097     translate_verification_token(verificationToken,
   1098                                  request.mutable_verification_token());
   1099 
   1100     KM_CALLV_ABORT(UpdateOperation, request, response,
   1101                    0, hidl_vec<KeyParameter>{}, hidl_vec<uint8_t>{});
   1102 
   1103     if (buffer_advance(operationHandle, response.consumed()) != ErrorCode::OK) {
   1104         _hidl_cb(ErrorCode::UNKNOWN_ERROR, 0, params, output);
   1105         return Void();
   1106     }
   1107 
   1108     pb_to_hidl_params(response.params(), &params);
   1109     output.setToExternal(
   1110         reinterpret_cast<uint8_t*>(const_cast<char*>(response.output().data())),
   1111         response.output().size(), false);
   1112 
   1113     // Special case ECDSA sign + Digest::NONE, which discards all but
   1114     // the left-most len(SHA256) bytes.
   1115     Algorithm algorithm;
   1116     buffer_algorithm(operationHandle, &algorithm);
   1117     if (algorithm == Algorithm::EC) {
   1118         if (response.consumed() == 0 && // Implies Digest::NONE.
   1119             buffer_remaining(operationHandle) >= SHA256_DIGEST_LENGTH) {
   1120             consumed = input.size();    // Discard remaining input.
   1121         }
   1122     }
   1123     _hidl_cb(ErrorCode::OK, consumed, params, output);
   1124     return Void();
   1125 }
   1126 
   1127 Return<void> KeymasterDevice::finish(
   1128         uint64_t operationHandle,
   1129         const hidl_vec<KeyParameter>& inParams,
   1130         const hidl_vec<uint8_t>& input,
   1131         const hidl_vec<uint8_t>& signature,
   1132         const HardwareAuthToken& authToken,
   1133         const VerificationToken& verificationToken,
   1134         finish_cb _hidl_cb)
   1135 {
   1136     LOG(VERBOSE) << "Running KeymasterDevice::finish";
   1137 
   1138     FinishOperationRequest request;
   1139     FinishOperationResponse response;
   1140 
   1141     ErrorCode error_code;
   1142     hidl_vec<uint8_t> output;
   1143 
   1144     // Consume any input data via update calls.
   1145     size_t consumed = 0;
   1146     hidl_vec<KeyParameter> input_params = inParams;
   1147     string update_output_str;
   1148     while (consumed < input.size()) {
   1149         hidl_vec<KeyParameter> out_params;
   1150         update_cb _update_hidl_cb =
   1151             [&] (
   1152                 ErrorCode error, uint32_t input_consumed,
   1153                 const hidl_vec<KeyParameter>& params,
   1154                 const hidl_vec<uint8_t>& update_output) {
   1155                     error_code = error;
   1156                     if (error == ErrorCode::OK) {
   1157                         consumed += input_consumed;
   1158                         input_params = params;  // Update the params.
   1159                         update_output_str += hidlVec2String(update_output);
   1160                     }
   1161             };
   1162 
   1163         hidl_vec<uint8_t> input_data;
   1164         input_data.setToExternal(const_cast<uint8_t*>(&input.data()[consumed]),
   1165                                  input.size() - consumed);
   1166         update(operationHandle, input_params, input_data, authToken,
   1167                verificationToken, _update_hidl_cb);
   1168         if (error_code != ErrorCode::OK) {
   1169             _hidl_cb(error_code,
   1170                      hidl_vec<KeyParameter>{}, hidl_vec<uint8_t>{});
   1171             return Void();
   1172         }
   1173     }
   1174 
   1175     hidl_vec<uint8_t> data;
   1176     error_code = buffer_final(operationHandle, &data);
   1177     if (error_code != ErrorCode::OK) {
   1178         _hidl_cb(error_code,
   1179                  hidl_vec<KeyParameter>{}, hidl_vec<uint8_t>{});
   1180         return Void();
   1181     }
   1182 
   1183     request.mutable_handle()->set_handle(operationHandle);
   1184 
   1185     hidl_vec<KeyParameter> params;
   1186     if (hidl_params_to_pb(
   1187             input_params, request.mutable_params()) != ErrorCode::OK) {
   1188       _hidl_cb(ErrorCode::INVALID_ARGUMENT, params, output);
   1189       return Void();
   1190     }
   1191 
   1192     request.set_input(&data[0], data.size());
   1193     request.set_signature(&signature[0], signature.size());
   1194 
   1195     if (translate_auth_token(
   1196             authToken, request.mutable_auth_token()) != ErrorCode::OK) {
   1197         _hidl_cb(ErrorCode::INVALID_ARGUMENT, params, output);
   1198         return Void();
   1199     }
   1200     translate_verification_token(verificationToken,
   1201                                  request.mutable_verification_token());
   1202 
   1203     KM_CALLV_ABORT(FinishOperation, request, response,
   1204                    hidl_vec<KeyParameter>{}, hidl_vec<uint8_t>{});
   1205 
   1206     pb_to_hidl_params(response.params(), &params);
   1207     // Concatenate accumulated output from Update().
   1208     update_output_str += string(
   1209         response.output().data(), response.output().size());
   1210     output.setToExternal(
   1211         reinterpret_cast<uint8_t*>(const_cast<char*>(
   1212                                        update_output_str.data())),
   1213         update_output_str.size(), false);
   1214 
   1215     _hidl_cb(ErrorCode::OK, params, output);
   1216     return Void();
   1217 }
   1218 
   1219 Return<ErrorCode> KeymasterDevice::abort(uint64_t operationHandle)
   1220 {
   1221     LOG(VERBOSE) << "Running KeymasterDevice::abort";
   1222 
   1223     AbortOperationRequest request;
   1224     AbortOperationResponse response;
   1225 
   1226     request.mutable_handle()->set_handle(operationHandle);
   1227 
   1228     KM_CALL(AbortOperation, request, response);
   1229 
   1230     return ErrorCode::OK;
   1231 }
   1232 
   1233 // Methods from ::android::hardware::keymaster::V4_0::IKeymasterDevice follow.
   1234 Return<void> KeymasterDevice::importWrappedKey(
   1235     const hidl_vec<uint8_t>& wrappedKeyData,
   1236     const hidl_vec<uint8_t>& wrappingKeyBlob,
   1237     const hidl_vec<uint8_t>& maskingKey,
   1238     const hidl_vec<KeyParameter>& /* unwrappingParams */,
   1239     uint64_t /* passwordSid */, uint64_t /* biometricSid */,
   1240     importWrappedKey_cb _hidl_cb)
   1241 {
   1242     LOG(VERBOSE) << "Running KeymasterDevice::importWrappedKey";
   1243 
   1244     ErrorCode error;
   1245     ImportWrappedKeyRequest request;
   1246     ImportKeyResponse response;
   1247 
   1248     if (maskingKey.size() != KM_WRAPPER_MASKING_KEY_SIZE) {
   1249         _hidl_cb(ErrorCode::INVALID_ARGUMENT, hidl_vec<uint8_t>{},
   1250                  KeyCharacteristics{});
   1251         return Void();
   1252     }
   1253 
   1254     error = import_wrapped_key_request(wrappedKeyData, wrappingKeyBlob,
   1255                                        maskingKey, &request);
   1256     if (error != ErrorCode::OK) {
   1257         LOG(ERROR) << "ImportWrappedKey request parsing failed with error "
   1258                    << error;
   1259         _hidl_cb(error, hidl_vec<uint8_t>{}, KeyCharacteristics{});
   1260         return Void();
   1261     }
   1262     request.set_creation_time_ms(ms_since_epoch());
   1263 
   1264     KM_CALLV(ImportWrappedKey, request, response,
   1265              hidl_vec<uint8_t>{}, KeyCharacteristics{});
   1266 
   1267     hidl_vec<uint8_t> blob;
   1268     blob.setToExternal(
   1269         reinterpret_cast<uint8_t*>(
   1270             const_cast<char*>(response.blob().blob().data())),
   1271         response.blob().blob().size(), false);
   1272 
   1273     KeyCharacteristics characteristics;
   1274     // TODO: anything to do here with softwareEnforced?
   1275     pb_to_hidl_params(response.characteristics().software_enforced(),
   1276                       &characteristics.softwareEnforced);
   1277     error = pb_to_hidl_params(response.characteristics().tee_enforced(),
   1278                               &characteristics.hardwareEnforced);
   1279     if (error != ErrorCode::OK) {
   1280         LOG(ERROR) <<
   1281             "KeymasterDevice::importWrappedKey: response tee_enforced :"
   1282                    << error;
   1283         _hidl_cb(error, hidl_vec<uint8_t>{}, KeyCharacteristics{});
   1284         return Void();
   1285     }
   1286 
   1287     _hidl_cb(ErrorCode::OK, blob, characteristics);
   1288     return Void();
   1289 }
   1290 
   1291 // Private methods.
   1292 Return<ErrorCode> KeymasterDevice::SendSystemVersionInfo() const {
   1293     SetSystemVersionInfoRequest request;
   1294     SetSystemVersionInfoResponse response;
   1295 
   1296     request.set_system_version(_os_version);
   1297     request.set_system_security_level(_os_patchlevel);
   1298     request.set_vendor_security_level(_vendor_patchlevel);
   1299 
   1300     KM_CALL(SetSystemVersionInfo, request, response);
   1301     return ErrorCode::OK;
   1302 }
   1303 
   1304 Return<ErrorCode> KeymasterDevice::GetBootInfo() {
   1305     GetBootInfoRequest request;
   1306     GetBootInfoResponse response;
   1307 
   1308     KM_CALL(GetBootInfo, request, response);
   1309 
   1310     _is_unlocked = response.is_unlocked();
   1311     _boot_color = response.boot_color();
   1312     _boot_key.assign(response.boot_key().begin(), response.boot_key().end());
   1313     _boot_hash.assign(response.boot_hash().begin(), response.boot_hash().end());
   1314     return ErrorCode::OK;
   1315 }
   1316 
   1317 }  // namespace keymaster
   1318 }  // namespace hardware
   1319 }  // namespace android
   1320