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