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