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