1 /*
2  * Copyright 2020, 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 #define LOG_TAG "android.hardware.security.keymint-impl.remote"
18 #include <android-base/logging.h>
19 
20 #include "guest/hals/keymint/remote/remote_keymint_device.h"
21 
22 #include <aidl/android/hardware/security/keymint/ErrorCode.h>
23 
24 #include <keymaster/android_keymaster.h>
25 #include <keymaster/contexts/pure_soft_keymaster_context.h>
26 #include <keymaster/keymaster_configuration.h>
27 
28 #include "KeyMintUtils.h"
29 #include "guest/hals/keymint/remote/remote_keymint_operation.h"
30 
31 namespace aidl::android::hardware::security::keymint {
32 
33 using namespace ::keymaster;
34 using namespace km_utils;
35 using secureclock::TimeStampToken;
36 
37 namespace {
38 
convertKeyCharacteristics(const vector<KeyParameter> & keyParams,SecurityLevel keyMintSecurityLevel,const AuthorizationSet & sw_enforced,const AuthorizationSet & hw_enforced,bool include_keystore_enforced=true)39 vector<KeyCharacteristics> convertKeyCharacteristics(
40     const vector<KeyParameter>& keyParams, SecurityLevel keyMintSecurityLevel,
41     const AuthorizationSet& sw_enforced, const AuthorizationSet& hw_enforced,
42     bool include_keystore_enforced = true) {
43   KeyCharacteristics keyMintEnforced{keyMintSecurityLevel, {}};
44 
45   if (keyMintSecurityLevel != SecurityLevel::SOFTWARE) {
46     // We're pretending to be TRUSTED_ENVIRONMENT or STRONGBOX.
47     keyMintEnforced.authorizations = kmParamSet2Aidl(hw_enforced);
48     if (include_keystore_enforced && !sw_enforced.empty()) {
49       return {std::move(keyMintEnforced),
50               {SecurityLevel::KEYSTORE, kmParamSet2Aidl(sw_enforced)}};
51     }
52     return {std::move(keyMintEnforced)};
53   }
54 
55   KeyCharacteristics keystoreEnforced{SecurityLevel::KEYSTORE, {}};
56   CHECK(hw_enforced.empty())
57       << "Hardware-enforced list is non-empty for pure SW KeyMint";
58 
59   // This is a pure software implementation, so all tags are in sw_enforced.
60   // We need to walk through the SW-enforced list and figure out which tags to
61   // return in the software list and which in the keystore list.
62 
63   for (auto& entry : sw_enforced) {
64     switch (entry.tag) {
65       /* Invalid and unused */
66       case KM_TAG_ECIES_SINGLE_HASH_MODE:
67       case KM_TAG_INVALID:
68       case KM_TAG_KDF:
69       case KM_TAG_ROLLBACK_RESISTANCE:
70         CHECK(false) << "We shouldn't see tag " << entry.tag;
71         break;
72 
73       /* Unimplemented */
74       case KM_TAG_ALLOW_WHILE_ON_BODY:
75       case KM_TAG_BOOTLOADER_ONLY:
76       case KM_TAG_ROLLBACK_RESISTANT:
77       case KM_TAG_STORAGE_KEY:
78         break;
79 
80       /* Unenforceable */
81       case KM_TAG_CREATION_DATETIME:
82         for (const auto& p : keyParams) {
83           if (p.tag == Tag::CREATION_DATETIME) {
84             keystoreEnforced.authorizations.push_back(kmParam2Aidl(entry));
85           }
86         }
87         break;
88 
89       /* Disallowed in KeyCharacteristics */
90       case KM_TAG_APPLICATION_DATA:
91       case KM_TAG_ATTESTATION_APPLICATION_ID:
92         break;
93 
94       /* Not key characteristics */
95       case KM_TAG_ASSOCIATED_DATA:
96       case KM_TAG_ATTESTATION_CHALLENGE:
97       case KM_TAG_ATTESTATION_ID_BRAND:
98       case KM_TAG_ATTESTATION_ID_DEVICE:
99       case KM_TAG_ATTESTATION_ID_IMEI:
100       case KM_TAG_ATTESTATION_ID_SECOND_IMEI:
101       case KM_TAG_ATTESTATION_ID_MANUFACTURER:
102       case KM_TAG_ATTESTATION_ID_MEID:
103       case KM_TAG_ATTESTATION_ID_MODEL:
104       case KM_TAG_ATTESTATION_ID_PRODUCT:
105       case KM_TAG_ATTESTATION_ID_SERIAL:
106       case KM_TAG_AUTH_TOKEN:
107       case KM_TAG_CERTIFICATE_SERIAL:
108       case KM_TAG_CERTIFICATE_SUBJECT:
109       case KM_TAG_CERTIFICATE_NOT_AFTER:
110       case KM_TAG_CERTIFICATE_NOT_BEFORE:
111       case KM_TAG_CONFIRMATION_TOKEN:
112       case KM_TAG_DEVICE_UNIQUE_ATTESTATION:
113       case KM_TAG_IDENTITY_CREDENTIAL_KEY:
114       case KM_TAG_MAC_LENGTH:
115       case KM_TAG_NONCE:
116       case KM_TAG_RESET_SINCE_ID_ROTATION:
117       case KM_TAG_ROOT_OF_TRUST:
118       case KM_TAG_UNIQUE_ID:
119       case KM_TAG_MODULE_HASH:
120         break;
121 
122       /* KeyMint-enforced */
123       case KM_TAG_ALGORITHM:
124       case KM_TAG_APPLICATION_ID:
125       case KM_TAG_AUTH_TIMEOUT:
126       case KM_TAG_BLOB_USAGE_REQUIREMENTS:
127       case KM_TAG_BLOCK_MODE:
128       case KM_TAG_BOOT_PATCHLEVEL:
129       case KM_TAG_CALLER_NONCE:
130       case KM_TAG_DIGEST:
131       case KM_TAG_EARLY_BOOT_ONLY:
132       case KM_TAG_EC_CURVE:
133       case KM_TAG_EXPORTABLE:
134       case KM_TAG_INCLUDE_UNIQUE_ID:
135       case KM_TAG_KEY_SIZE:
136       case KM_TAG_MAX_USES_PER_BOOT:
137       case KM_TAG_MIN_MAC_LENGTH:
138       case KM_TAG_MIN_SECONDS_BETWEEN_OPS:
139       case KM_TAG_NO_AUTH_REQUIRED:
140       case KM_TAG_ORIGIN:
141       case KM_TAG_OS_PATCHLEVEL:
142       case KM_TAG_OS_VERSION:
143       case KM_TAG_PADDING:
144       case KM_TAG_PURPOSE:
145       case KM_TAG_RSA_OAEP_MGF_DIGEST:
146       case KM_TAG_RSA_PUBLIC_EXPONENT:
147       case KM_TAG_UNLOCKED_DEVICE_REQUIRED:
148       case KM_TAG_USER_AUTH_TYPE:
149       case KM_TAG_USER_SECURE_ID:
150       case KM_TAG_TRUSTED_CONFIRMATION_REQUIRED:
151       case KM_TAG_TRUSTED_USER_PRESENCE_REQUIRED:
152       case KM_TAG_VENDOR_PATCHLEVEL:
153         keyMintEnforced.authorizations.push_back(kmParam2Aidl(entry));
154         break;
155 
156       /* Keystore-enforced */
157       case KM_TAG_ACTIVE_DATETIME:
158       case KM_TAG_ALL_APPLICATIONS:
159       case KM_TAG_ALL_USERS:
160       case KM_TAG_MAX_BOOT_LEVEL:
161       case KM_TAG_ORIGINATION_EXPIRE_DATETIME:
162       case KM_TAG_USAGE_EXPIRE_DATETIME:
163       case KM_TAG_USER_ID:
164       case KM_TAG_USAGE_COUNT_LIMIT:
165         keystoreEnforced.authorizations.push_back(kmParam2Aidl(entry));
166         break;
167     }
168   }
169 
170   vector<KeyCharacteristics> retval;
171   retval.reserve(2);
172   if (!keyMintEnforced.authorizations.empty()) {
173     retval.push_back(std::move(keyMintEnforced));
174   }
175   if (include_keystore_enforced && !keystoreEnforced.authorizations.empty()) {
176     retval.push_back(std::move(keystoreEnforced));
177   }
178 
179   return retval;
180 }
181 
convertCertificate(const keymaster_blob_t & cert)182 Certificate convertCertificate(const keymaster_blob_t& cert) {
183   return {std::vector<uint8_t>(cert.data, cert.data + cert.data_length)};
184 }
185 
convertCertificateChain(const CertificateChain & chain)186 vector<Certificate> convertCertificateChain(const CertificateChain& chain) {
187   vector<Certificate> retval;
188   retval.reserve(chain.entry_count);
189   std::transform(chain.begin(), chain.end(), std::back_inserter(retval),
190                  convertCertificate);
191   return retval;
192 }
193 
194 }  // namespace
195 
RemoteKeyMintDevice(::keymaster::RemoteKeymaster & impl,SecurityLevel securityLevel)196 RemoteKeyMintDevice::RemoteKeyMintDevice(::keymaster::RemoteKeymaster& impl,
197                                          SecurityLevel securityLevel)
198     : impl_(impl), securityLevel_(securityLevel) {}
199 
~RemoteKeyMintDevice()200 RemoteKeyMintDevice::~RemoteKeyMintDevice() {}
201 
getHardwareInfo(KeyMintHardwareInfo * info)202 ScopedAStatus RemoteKeyMintDevice::getHardwareInfo(KeyMintHardwareInfo* info) {
203   info->versionNumber = 1;
204   info->securityLevel = securityLevel_;
205   info->keyMintName = "RemoteKeyMintDevice";
206   info->keyMintAuthorName = "Google";
207   info->timestampTokenRequired = false;
208   return ScopedAStatus::ok();
209 }
210 
addRngEntropy(const vector<uint8_t> & data)211 ScopedAStatus RemoteKeyMintDevice::addRngEntropy(const vector<uint8_t>& data) {
212   if (data.size() == 0) {
213     return ScopedAStatus::ok();
214   }
215 
216   AddEntropyRequest request(impl_.message_version());
217   request.random_data.Reinitialize(data.data(), data.size());
218 
219   AddEntropyResponse response(impl_.message_version());
220   impl_.AddRngEntropy(request, &response);
221 
222   return kmError2ScopedAStatus(response.error);
223 }
224 
generateKey(const vector<KeyParameter> & keyParams,const optional<AttestationKey> & attestationKey,KeyCreationResult * creationResult)225 ScopedAStatus RemoteKeyMintDevice::generateKey(
226     const vector<KeyParameter>& keyParams,
227     const optional<AttestationKey>& attestationKey,
228     KeyCreationResult* creationResult) {
229   GenerateKeyRequest request(impl_.message_version());
230   request.key_description.Reinitialize(KmParamSet(keyParams));
231   if (attestationKey) {
232     request.attestation_signing_key_blob = KeymasterKeyBlob(
233         attestationKey->keyBlob.data(), attestationKey->keyBlob.size());
234     request.attest_key_params.Reinitialize(
235         KmParamSet(attestationKey->attestKeyParams));
236     request.issuer_subject =
237         KeymasterBlob(attestationKey->issuerSubjectName.data(),
238                       attestationKey->issuerSubjectName.size());
239   }
240 
241   GenerateKeyResponse response(impl_.message_version());
242   impl_.GenerateKey(request, &response);
243 
244   if (response.error != KM_ERROR_OK) {
245     // Note a key difference between this current aidl and previous hal, is
246     // that hal returns void where as aidl returns the error status.  If
247     // aidl returns error, then aidl will not return any change you may make
248     // to the out parameters.  This is quite different from hal where all
249     // output variable can be modified due to hal returning void.
250     //
251     // So the caller need to be aware not to expect aidl functions to clear
252     // the output variables for you in case of error.  If you left some
253     // wrong data set in the out parameters, they will stay there.
254     return kmError2ScopedAStatus(response.error);
255   }
256 
257   creationResult->keyBlob = kmBlob2vector(response.key_blob);
258   creationResult->keyCharacteristics = convertKeyCharacteristics(
259       keyParams, securityLevel_, response.unenforced, response.enforced);
260   creationResult->certificateChain =
261       convertCertificateChain(response.certificate_chain);
262   return ScopedAStatus::ok();
263 }
264 
importKey(const vector<KeyParameter> & keyParams,KeyFormat keyFormat,const vector<uint8_t> & keyData,const optional<AttestationKey> & attestationKey,KeyCreationResult * creationResult)265 ScopedAStatus RemoteKeyMintDevice::importKey(
266     const vector<KeyParameter>& keyParams, KeyFormat keyFormat,
267     const vector<uint8_t>& keyData,
268     const optional<AttestationKey>& attestationKey,
269     KeyCreationResult* creationResult) {
270   ImportKeyRequest request(impl_.message_version());
271   request.key_description.Reinitialize(KmParamSet(keyParams));
272   request.key_format = legacy_enum_conversion(keyFormat);
273   request.key_data = KeymasterKeyBlob(keyData.data(), keyData.size());
274   if (attestationKey) {
275     request.attestation_signing_key_blob = KeymasterKeyBlob(
276         attestationKey->keyBlob.data(), attestationKey->keyBlob.size());
277     request.attest_key_params.Reinitialize(
278         KmParamSet(attestationKey->attestKeyParams));
279     request.issuer_subject =
280         KeymasterBlob(attestationKey->issuerSubjectName.data(),
281                       attestationKey->issuerSubjectName.size());
282   }
283 
284   ImportKeyResponse response(impl_.message_version());
285   impl_.ImportKey(request, &response);
286 
287   if (response.error != KM_ERROR_OK) {
288     return kmError2ScopedAStatus(response.error);
289   }
290 
291   creationResult->keyBlob = kmBlob2vector(response.key_blob);
292   creationResult->keyCharacteristics = convertKeyCharacteristics(
293       keyParams, securityLevel_, response.unenforced, response.enforced);
294   creationResult->certificateChain =
295       convertCertificateChain(response.certificate_chain);
296 
297   return ScopedAStatus::ok();
298 }
299 
importWrappedKey(const vector<uint8_t> & wrappedKeyData,const vector<uint8_t> & wrappingKeyBlob,const vector<uint8_t> & maskingKey,const vector<KeyParameter> & unwrappingParams,int64_t passwordSid,int64_t biometricSid,KeyCreationResult * creationResult)300 ScopedAStatus RemoteKeyMintDevice::importWrappedKey(
301     const vector<uint8_t>& wrappedKeyData,         //
302     const vector<uint8_t>& wrappingKeyBlob,        //
303     const vector<uint8_t>& maskingKey,             //
304     const vector<KeyParameter>& unwrappingParams,  //
305     int64_t passwordSid, int64_t biometricSid,     //
306     KeyCreationResult* creationResult) {
307   ImportWrappedKeyRequest request(impl_.message_version());
308   request.SetWrappedMaterial(wrappedKeyData.data(), wrappedKeyData.size());
309   request.SetWrappingMaterial(wrappingKeyBlob.data(), wrappingKeyBlob.size());
310   request.SetMaskingKeyMaterial(maskingKey.data(), maskingKey.size());
311   request.additional_params.Reinitialize(KmParamSet(unwrappingParams));
312   request.password_sid = static_cast<uint64_t>(passwordSid);
313   request.biometric_sid = static_cast<uint64_t>(biometricSid);
314 
315   ImportWrappedKeyResponse response(impl_.message_version());
316   impl_.ImportWrappedKey(request, &response);
317 
318   if (response.error != KM_ERROR_OK) {
319     return kmError2ScopedAStatus(response.error);
320   }
321 
322   creationResult->keyBlob = kmBlob2vector(response.key_blob);
323   creationResult->keyCharacteristics = convertKeyCharacteristics(
324       unwrappingParams, securityLevel_, response.unenforced, response.enforced);
325   creationResult->certificateChain =
326       convertCertificateChain(response.certificate_chain);
327 
328   return ScopedAStatus::ok();
329 }
330 
upgradeKey(const vector<uint8_t> & keyBlobToUpgrade,const vector<KeyParameter> & upgradeParams,vector<uint8_t> * keyBlob)331 ScopedAStatus RemoteKeyMintDevice::upgradeKey(
332     const vector<uint8_t>& keyBlobToUpgrade,
333     const vector<KeyParameter>& upgradeParams, vector<uint8_t>* keyBlob) {
334   UpgradeKeyRequest request(impl_.message_version());
335   request.SetKeyMaterial(keyBlobToUpgrade.data(), keyBlobToUpgrade.size());
336   request.upgrade_params.Reinitialize(KmParamSet(upgradeParams));
337 
338   UpgradeKeyResponse response(impl_.message_version());
339   impl_.UpgradeKey(request, &response);
340 
341   if (response.error != KM_ERROR_OK) {
342     return kmError2ScopedAStatus(response.error);
343   }
344 
345   *keyBlob = kmBlob2vector(response.upgraded_key);
346   return ScopedAStatus::ok();
347 }
348 
deleteKey(const vector<uint8_t> & keyBlob)349 ScopedAStatus RemoteKeyMintDevice::deleteKey(const vector<uint8_t>& keyBlob) {
350   DeleteKeyRequest request(impl_.message_version());
351   request.SetKeyMaterial(keyBlob.data(), keyBlob.size());
352 
353   DeleteKeyResponse response(impl_.message_version());
354   impl_.DeleteKey(request, &response);
355 
356   return kmError2ScopedAStatus(response.error);
357 }
358 
deleteAllKeys()359 ScopedAStatus RemoteKeyMintDevice::deleteAllKeys() {
360   // There's nothing to be done to delete software key blobs.
361   DeleteAllKeysRequest request(impl_.message_version());
362   DeleteAllKeysResponse response(impl_.message_version());
363   impl_.DeleteAllKeys(request, &response);
364 
365   return kmError2ScopedAStatus(response.error);
366 }
367 
destroyAttestationIds()368 ScopedAStatus RemoteKeyMintDevice::destroyAttestationIds() {
369   return kmError2ScopedAStatus(KM_ERROR_UNIMPLEMENTED);
370 }
371 
begin(KeyPurpose purpose,const vector<uint8_t> & keyBlob,const vector<KeyParameter> & params,const optional<HardwareAuthToken> & authToken,BeginResult * result)372 ScopedAStatus RemoteKeyMintDevice::begin(
373     KeyPurpose purpose, const vector<uint8_t>& keyBlob,
374     const vector<KeyParameter>& params,
375     const optional<HardwareAuthToken>& authToken, BeginResult* result) {
376   BeginOperationRequest request(impl_.message_version());
377   request.purpose = legacy_enum_conversion(purpose);
378   request.SetKeyMaterial(keyBlob.data(), keyBlob.size());
379   request.additional_params.Reinitialize(KmParamSet(params));
380 
381   vector<uint8_t> vector_token = authToken2AidlVec(authToken);
382   request.additional_params.push_back(
383       TAG_AUTH_TOKEN, reinterpret_cast<uint8_t*>(vector_token.data()),
384       vector_token.size());
385 
386   BeginOperationResponse response(impl_.message_version());
387   impl_.BeginOperation(request, &response);
388 
389   if (response.error != KM_ERROR_OK) {
390     return kmError2ScopedAStatus(response.error);
391   }
392 
393   result->params = kmParamSet2Aidl(response.output_params);
394   result->challenge = response.op_handle;
395   result->operation = ndk::SharedRefBase::make<RemoteKeyMintOperation>(
396       impl_, response.op_handle);
397   return ScopedAStatus::ok();
398 }
399 
deviceLocked(bool passwordOnly,const std::optional<secureclock::TimeStampToken> & timestampToken)400 ScopedAStatus RemoteKeyMintDevice::deviceLocked(
401     bool passwordOnly,
402     const std::optional<secureclock::TimeStampToken>& timestampToken) {
403   DeviceLockedRequest request(impl_.message_version());
404   request.passwordOnly = passwordOnly;
405   if (timestampToken.has_value()) {
406     request.token.challenge = timestampToken->challenge;
407     request.token.mac = {timestampToken->mac.data(),
408                          timestampToken->mac.size()};
409     request.token.timestamp = timestampToken->timestamp.milliSeconds;
410   }
411   DeviceLockedResponse response = impl_.DeviceLocked(request);
412   return kmError2ScopedAStatus(response.error);
413 }
414 
earlyBootEnded()415 ScopedAStatus RemoteKeyMintDevice::earlyBootEnded() {
416   EarlyBootEndedResponse response = impl_.EarlyBootEnded();
417   return kmError2ScopedAStatus(response.error);
418 }
419 
convertStorageKeyToEphemeral(const std::vector<uint8_t> &,std::vector<uint8_t> *)420 ScopedAStatus RemoteKeyMintDevice::convertStorageKeyToEphemeral(
421     const std::vector<uint8_t>& /* storageKeyBlob */,
422     std::vector<uint8_t>* /* ephemeralKeyBlob */) {
423   return kmError2ScopedAStatus(KM_ERROR_UNIMPLEMENTED);
424 }
425 
getKeyCharacteristics(const std::vector<uint8_t> & storageKeyBlob,const std::vector<uint8_t> & appId,const std::vector<uint8_t> & appData,std::vector<KeyCharacteristics> * keyCharacteristics)426 ScopedAStatus RemoteKeyMintDevice::getKeyCharacteristics(
427     const std::vector<uint8_t>& storageKeyBlob,
428     const std::vector<uint8_t>& appId, const std::vector<uint8_t>& appData,
429     std::vector<KeyCharacteristics>* keyCharacteristics) {
430   GetKeyCharacteristicsRequest request(impl_.message_version());
431   request.SetKeyMaterial(storageKeyBlob.data(), storageKeyBlob.size());
432   addClientAndAppData(appId, appData, &request.additional_params);
433 
434   GetKeyCharacteristicsResponse response(impl_.message_version());
435   impl_.GetKeyCharacteristics(request, &response);
436 
437   if (response.error != KM_ERROR_OK) {
438     return kmError2ScopedAStatus(response.error);
439   }
440 
441   *keyCharacteristics = convertKeyCharacteristics(
442       {} /*keyParams*/, securityLevel_, response.unenforced, response.enforced,
443       false /*include_keystore_enforced*/);
444 
445   return ScopedAStatus::ok();
446 }
447 
getRootOfTrustChallenge(std::array<uint8_t,16> *)448 ScopedAStatus RemoteKeyMintDevice::getRootOfTrustChallenge(
449     std::array<uint8_t, 16>* /* challenge */) {
450   return kmError2ScopedAStatus(KM_ERROR_UNIMPLEMENTED);
451 }
452 
getRootOfTrust(const std::array<uint8_t,16> & challenge,std::vector<uint8_t> * rootOfTrust)453 ScopedAStatus RemoteKeyMintDevice::getRootOfTrust(
454     const std::array<uint8_t, 16>& challenge,
455     std::vector<uint8_t>* rootOfTrust) {
456   if (!rootOfTrust) {
457     return kmError2ScopedAStatus(KM_ERROR_UNEXPECTED_NULL_POINTER);
458   }
459   GetRootOfTrustRequest request(impl_.message_version(),
460                                 {challenge.begin(), challenge.end()});
461   GetRootOfTrustResponse response = impl_.GetRootOfTrust(request);
462   if (response.error != KM_ERROR_OK) {
463     return kmError2ScopedAStatus(response.error);
464   }
465 
466   *rootOfTrust = std::move(response.rootOfTrust);
467   return ScopedAStatus::ok();
468 }
469 
sendRootOfTrust(const std::vector<uint8_t> &)470 ScopedAStatus RemoteKeyMintDevice::sendRootOfTrust(
471     const std::vector<uint8_t>& /* rootOfTrust */) {
472   return kmError2ScopedAStatus(KM_ERROR_UNIMPLEMENTED);
473 }
474 
475 }  // namespace aidl::android::hardware::security::keymint
476