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 "secure_storage_manager.h"
18 #include "keymaster_attributes.pb.h"
19
20 #include <errno.h>
21 #include <stdio.h>
22 #include <uapi/err.h>
23
24 #include <lib/storage/storage.h>
25
26 #include <keymaster/UniquePtr.h>
27 #include <keymaster/android_keymaster_utils.h>
28 #include "pb_decode.h"
29 #include "pb_encode.h"
30 #include "trusty_logger.h"
31
32 namespace keymaster {
33
34 // Name of the attestation key file is kAttestKeyCertPrefix.%algorithm. This key
35 // file stores key and certificate chain in a protobuf format.
36 const char* kAttestKeyCertPrefix = "AttestKeyCert";
37 // Name of the legacy attestation key file prefix.
38 const char* kLegacyAttestKeyPrefix = "AttestKey.";
39 // Name of the legacy certificate file prefix.
40 const char* kLegacyAttestCertPrefix = "AttestCert.";
41
42 // Name of the file to store keymaster attributes in a protobuf format.
43 const char* kAttributeFileName = "Attribute";
44 // Name of the legacy keymaster attribute files.
45 const char* kLegacyAttestUuidFileName = "AttestUuid";
46 const char* kLegacyProductIdFileName = "ProductId";
47
48 // Name of the file to store attestation IDs in a protobuf format.
49 const char* kAttestationIdsFileName = "AttestationIds";
50
51 // Maximum file name size.
52 static const int kStorageIdLengthMax = 64;
53
54 // Maximum length for an individual attestation ID field.
55 static const int kAttestationIdLengthMax = 64;
56
57 // These values should match keymaster_attributes.proto descriptions.
58 static const int kKeySizeMax = 2048;
59 static const int kCertSizeMax = 2048;
60
GetKeySlotStr(AttestationKeySlot key_slot)61 const char* GetKeySlotStr(AttestationKeySlot key_slot) {
62 switch (key_slot) {
63 case AttestationKeySlot::kRsa:
64 return "rsa";
65 case AttestationKeySlot::kEcdsa:
66 return "ec";
67 case AttestationKeySlot::kEddsa:
68 return "ed";
69 case AttestationKeySlot::kEpid:
70 return "epid";
71 case AttestationKeySlot::kClaimable0:
72 return "c0";
73 case AttestationKeySlot::kSomRsa:
74 return "s_rsa";
75 case AttestationKeySlot::kSomEcdsa:
76 return "s_ec";
77 case AttestationKeySlot::kSomEddsa:
78 return "s_ed";
79 case AttestationKeySlot::kSomEpid:
80 return "s_epid";
81 default:
82 return "";
83 }
84 }
85
86 class FileCloser {
87 public:
get_file_handle()88 file_handle_t get_file_handle() { return file_handle; }
open_file(storage_session_t session,const char * name,uint32_t flags,uint32_t opflags)89 int open_file(storage_session_t session,
90 const char* name,
91 uint32_t flags,
92 uint32_t opflags) {
93 return storage_open_file(session, &file_handle, name, flags, opflags);
94 }
~FileCloser()95 ~FileCloser() {
96 if (file_handle) {
97 storage_close_file(file_handle);
98 }
99 }
100
101 private:
102 file_handle_t file_handle = 0;
103 };
104
get_instance(bool translate_format)105 SecureStorageManager* SecureStorageManager::get_instance(
106 bool translate_format) {
107 static SecureStorageManager instance;
108 if (instance.session_handle_ != STORAGE_INVALID_SESSION) {
109 int rc = storage_end_transaction(instance.session_handle_, false);
110 if (rc < 0) {
111 LOG_E("Error: existing session is stale.");
112 storage_close_session(instance.session_handle_);
113 instance.session_handle_ = STORAGE_INVALID_SESSION;
114 }
115 }
116 if (instance.session_handle_ == STORAGE_INVALID_SESSION) {
117 storage_open_session(&instance.session_handle_, STORAGE_CLIENT_TP_PORT);
118 if (instance.session_handle_ == STORAGE_INVALID_SESSION) {
119 return nullptr;
120 }
121 }
122 #ifdef KEYMASTER_LEGACY_FORMAT
123 if (translate_format && instance.legacy_format) {
124 keymaster_error_t err = instance.TranslateLegacyFormat();
125 if (err != KM_ERROR_OK) {
126 LOG_E("Failed to translate legacy file format!");
127 instance.CloseSession();
128 return nullptr;
129 } else {
130 instance.legacy_format = false;
131 }
132 }
133 #endif // #ifdef KEYMASTER_LEGACY_FORMAT
134 return &instance;
135 }
136
WriteKeyToStorage(AttestationKeySlot key_slot,const uint8_t * key,uint32_t key_size)137 keymaster_error_t SecureStorageManager::WriteKeyToStorage(
138 AttestationKeySlot key_slot,
139 const uint8_t* key,
140 uint32_t key_size) {
141 if (key_size > kKeySizeMax) {
142 return KM_ERROR_INVALID_ARGUMENT;
143 }
144 AttestationKey* attestation_key_p;
145 keymaster_error_t err = ReadAttestationKey(key_slot, &attestation_key_p);
146 if (err != KM_ERROR_OK) {
147 CloseSession();
148 return err;
149 }
150 UniquePtr<AttestationKey> attestation_key(attestation_key_p);
151 attestation_key->has_key = true;
152 memcpy(attestation_key->key.bytes, key, key_size);
153 attestation_key->key.size = key_size;
154
155 err = WriteAttestationKey(key_slot, attestation_key.get(), true);
156 if (err != KM_ERROR_OK) {
157 CloseSession();
158 }
159 return err;
160 }
161
ReadKeyFromStorage(AttestationKeySlot key_slot,keymaster_error_t * error)162 KeymasterKeyBlob SecureStorageManager::ReadKeyFromStorage(
163 AttestationKeySlot key_slot,
164 keymaster_error_t* error) {
165 AttestationKey* attestation_key_p;
166 keymaster_error_t err = ReadAttestationKey(key_slot, &attestation_key_p);
167 if (err != KM_ERROR_OK) {
168 CloseSession();
169 if (error) {
170 *error = err;
171 }
172 return {};
173 }
174 UniquePtr<AttestationKey> attestation_key(attestation_key_p);
175 if (!attestation_key->has_key) {
176 if (error) {
177 *error = KM_ERROR_INVALID_ARGUMENT;
178 }
179 return {};
180 }
181 KeymasterKeyBlob result(attestation_key->key.size);
182 if (result.key_material == nullptr) {
183 if (error) {
184 *error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
185 }
186 return {};
187 }
188 memcpy(result.writable_data(), attestation_key->key.bytes,
189 result.key_material_size);
190 return result;
191 }
192
AttestationKeyExists(AttestationKeySlot key_slot,bool * exists)193 keymaster_error_t SecureStorageManager::AttestationKeyExists(
194 AttestationKeySlot key_slot,
195 bool* exists) {
196 AttestationKey* attestation_key_p;
197 keymaster_error_t err = ReadAttestationKey(key_slot, &attestation_key_p);
198 if (err != KM_ERROR_OK) {
199 CloseSession();
200 return err;
201 }
202 UniquePtr<AttestationKey> attestation_key(attestation_key_p);
203 *exists = attestation_key->has_key;
204 return KM_ERROR_OK;
205 }
206
WriteCertToStorage(AttestationKeySlot key_slot,const uint8_t * cert,uint32_t cert_size,uint32_t index)207 keymaster_error_t SecureStorageManager::WriteCertToStorage(
208 AttestationKeySlot key_slot,
209 const uint8_t* cert,
210 uint32_t cert_size,
211 uint32_t index) {
212 if (cert_size > kCertSizeMax || index >= kMaxCertChainLength) {
213 return KM_ERROR_INVALID_ARGUMENT;
214 }
215 AttestationKey* attestation_key_p;
216 keymaster_error_t err = ReadAttestationKey(key_slot, &attestation_key_p);
217 if (err != KM_ERROR_OK) {
218 CloseSession();
219 return err;
220 }
221 UniquePtr<AttestationKey> attestation_key(attestation_key_p);
222 if (attestation_key->certs_count < index) {
223 /* Skip a layer in cert chain. */
224 return KM_ERROR_INVALID_ARGUMENT;
225 } else if (attestation_key->certs_count == index) {
226 attestation_key->certs_count++;
227 }
228 attestation_key->certs[index].content.size = cert_size;
229 memcpy(attestation_key->certs[index].content.bytes, cert, cert_size);
230
231 err = WriteAttestationKey(key_slot, attestation_key.get(), true);
232 if (err != KM_ERROR_OK) {
233 CloseSession();
234 }
235 return err;
236 }
237
ReadCertChainFromStorage(AttestationKeySlot key_slot,keymaster_cert_chain_t * cert_chain)238 keymaster_error_t SecureStorageManager::ReadCertChainFromStorage(
239 AttestationKeySlot key_slot,
240 keymaster_cert_chain_t* cert_chain) {
241 AttestationKey* attestation_key_p;
242 // Clear entry count in case of early return.
243 cert_chain->entry_count = 0;
244 cert_chain->entries = nullptr;
245 keymaster_error_t err = ReadAttestationKey(key_slot, &attestation_key_p);
246 if (err != KM_ERROR_OK) {
247 CloseSession();
248 return err;
249 }
250 UniquePtr<AttestationKey> attestation_key(attestation_key_p);
251 uint32_t cert_chain_length = attestation_key->certs_count;
252 cert_chain->entry_count = cert_chain_length;
253 if (cert_chain_length == 0) {
254 return KM_ERROR_OK;
255 }
256
257 cert_chain->entries =
258 new (std::nothrow) keymaster_blob_t[cert_chain_length];
259 if (cert_chain->entries == nullptr) {
260 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
261 }
262 memset(cert_chain->entries, 0,
263 sizeof(keymaster_blob_t) * cert_chain_length);
264
265 for (size_t i = 0; i < cert_chain_length; i++) {
266 uint32_t content_size = attestation_key->certs[i].content.size;
267 cert_chain->entries[i].data_length = content_size;
268 uint8_t* buffer = new (std::nothrow) uint8_t[content_size];
269 if (buffer == nullptr) {
270 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
271 }
272 memcpy(buffer, attestation_key->certs[i].content.bytes, content_size);
273 cert_chain->entries[i].data = buffer;
274 }
275
276 return KM_ERROR_OK;
277 }
278
DeleteCertChainFromStorage(AttestationKeySlot key_slot)279 keymaster_error_t SecureStorageManager::DeleteCertChainFromStorage(
280 AttestationKeySlot key_slot) {
281 AttestationKey* attestation_key_p;
282 keymaster_error_t err = ReadAttestationKey(key_slot, &attestation_key_p);
283 if (err != KM_ERROR_OK) {
284 CloseSession();
285 return err;
286 }
287 UniquePtr<AttestationKey> attestation_key(attestation_key_p);
288 attestation_key->certs_count = 0;
289
290 err = WriteAttestationKey(key_slot, attestation_key.get(), true);
291 if (err != KM_ERROR_OK) {
292 CloseSession();
293 }
294 return err;
295 }
296
ReadCertChainLength(AttestationKeySlot key_slot,uint32_t * cert_chain_length)297 keymaster_error_t SecureStorageManager::ReadCertChainLength(
298 AttestationKeySlot key_slot,
299 uint32_t* cert_chain_length) {
300 AttestationKey* attestation_key_p;
301 keymaster_error_t err = ReadAttestationKey(key_slot, &attestation_key_p);
302 if (err != KM_ERROR_OK) {
303 CloseSession();
304 return err;
305 }
306 UniquePtr<AttestationKey> attestation_key(attestation_key_p);
307 *cert_chain_length = attestation_key->certs_count;
308 return KM_ERROR_OK;
309 }
310
DeleteKey(AttestationKeySlot key_slot,bool commit)311 keymaster_error_t SecureStorageManager::DeleteKey(AttestationKeySlot key_slot,
312 bool commit) {
313 char key_file[kStorageIdLengthMax];
314 snprintf(key_file, kStorageIdLengthMax, "%s.%s", kAttestKeyCertPrefix,
315 GetKeySlotStr(key_slot));
316 int rc = storage_delete_file(session_handle_, key_file,
317 commit ? STORAGE_OP_COMPLETE : 0);
318 if (rc < 0 && rc != ERR_NOT_FOUND) {
319 LOG_E("Error: [%d] deleting storage object '%s'", rc, key_file);
320 if (commit) {
321 // If DeleteKey is part of a larger operations, then do not close
322 // the session.
323 CloseSession();
324 }
325 return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
326 }
327 return KM_ERROR_OK;
328 }
329
ReadKeymasterAttributes(KeymasterAttributes ** km_attributes_p)330 keymaster_error_t SecureStorageManager::ReadKeymasterAttributes(
331 KeymasterAttributes** km_attributes_p) {
332 UniquePtr<KeymasterAttributes> km_attributes(new (
333 std::nothrow) KeymasterAttributes(KeymasterAttributes_init_zero));
334 if (!km_attributes.get()) {
335 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
336 }
337 keymaster_error_t err =
338 DecodeFromFile(KeymasterAttributes_fields, km_attributes.get(),
339 kAttributeFileName);
340 if (err < 0) {
341 LOG_E("Error: [%d] decoding from file '%s'", err, kAttributeFileName);
342 return err;
343 }
344 *km_attributes_p = km_attributes.release();
345 return KM_ERROR_OK;
346 }
347
WriteKeymasterAttributes(const KeymasterAttributes * km_attributes,bool commit)348 keymaster_error_t SecureStorageManager::WriteKeymasterAttributes(
349 const KeymasterAttributes* km_attributes,
350 bool commit) {
351 return EncodeToFile(KeymasterAttributes_fields, km_attributes,
352 kAttributeFileName, commit);
353 }
354
WriteAttestationIds(const AttestationIds * attestation_ids,bool commit)355 keymaster_error_t SecureStorageManager::WriteAttestationIds(
356 const AttestationIds* attestation_ids,
357 bool commit) {
358 return EncodeToFile(AttestationIds_fields, attestation_ids,
359 kAttestationIdsFileName, commit);
360 }
361
ReadAttestationUuid(uint8_t attestation_uuid[kAttestationUuidSize])362 keymaster_error_t SecureStorageManager::ReadAttestationUuid(
363 uint8_t attestation_uuid[kAttestationUuidSize]) {
364 KeymasterAttributes* km_attributes_p;
365 keymaster_error_t err = ReadKeymasterAttributes(&km_attributes_p);
366 if (err != KM_ERROR_OK) {
367 CloseSession();
368 return err;
369 }
370 UniquePtr<KeymasterAttributes> km_attributes(km_attributes_p);
371 if (!(km_attributes->has_uuid)) {
372 return KM_ERROR_INVALID_ARGUMENT;
373 }
374 if (km_attributes->uuid.size != kAttestationUuidSize) {
375 return KM_ERROR_UNKNOWN_ERROR;
376 }
377 memcpy(attestation_uuid, km_attributes->uuid.bytes, kAttestationUuidSize);
378 return KM_ERROR_OK;
379 }
380
WriteAttestationUuid(const uint8_t attestation_uuid[kAttestationUuidSize])381 keymaster_error_t SecureStorageManager::WriteAttestationUuid(
382 const uint8_t attestation_uuid[kAttestationUuidSize]) {
383 KeymasterAttributes* km_attributes_p;
384 keymaster_error_t err = ReadKeymasterAttributes(&km_attributes_p);
385 if (err != KM_ERROR_OK) {
386 CloseSession();
387 return err;
388 }
389 UniquePtr<KeymasterAttributes> km_attributes(km_attributes_p);
390 km_attributes->has_uuid = true;
391 km_attributes->uuid.size = kAttestationUuidSize;
392 memcpy(km_attributes->uuid.bytes, attestation_uuid, kAttestationUuidSize);
393 err = WriteKeymasterAttributes(km_attributes.get(), true);
394 if (err != KM_ERROR_OK) {
395 CloseSession();
396 }
397 return err;
398 }
399
DeleteAttestationUuid()400 keymaster_error_t SecureStorageManager::DeleteAttestationUuid() {
401 KeymasterAttributes* km_attributes_p;
402 keymaster_error_t err = ReadKeymasterAttributes(&km_attributes_p);
403 if (err != KM_ERROR_OK) {
404 CloseSession();
405 return err;
406 }
407 UniquePtr<KeymasterAttributes> km_attributes(km_attributes_p);
408 km_attributes->has_uuid = false;
409 err = WriteKeymasterAttributes(km_attributes.get(), true);
410 if (err != KM_ERROR_OK) {
411 CloseSession();
412 }
413 return err;
414 }
415
SetProductId(const uint8_t product_id[kProductIdSize])416 keymaster_error_t SecureStorageManager::SetProductId(
417 const uint8_t product_id[kProductIdSize]) {
418 KeymasterAttributes* km_attributes_p;
419 keymaster_error_t err = ReadKeymasterAttributes(&km_attributes_p);
420 if (err != KM_ERROR_OK) {
421 CloseSession();
422 return err;
423 }
424 UniquePtr<KeymasterAttributes> km_attributes(km_attributes_p);
425 #ifndef KEYMASTER_DEBUG
426 if (km_attributes->has_product_id) {
427 LOG_E("Error: Product ID already set!\n");
428 return KM_ERROR_INVALID_ARGUMENT;
429 }
430 #endif /* KEYMASTER_DEBUG */
431 km_attributes->has_product_id = true;
432 km_attributes->product_id.size = kProductIdSize;
433 memcpy(km_attributes->product_id.bytes, product_id, kProductIdSize);
434 err = WriteKeymasterAttributes(km_attributes.get(), true);
435 if (err != KM_ERROR_OK) {
436 CloseSession();
437 }
438 return err;
439 }
440
ReadProductId(uint8_t product_id[kProductIdSize])441 keymaster_error_t SecureStorageManager::ReadProductId(
442 uint8_t product_id[kProductIdSize]) {
443 KeymasterAttributes* km_attributes_p;
444 keymaster_error_t err = ReadKeymasterAttributes(&km_attributes_p);
445 if (err != KM_ERROR_OK) {
446 CloseSession();
447 return err;
448 }
449 UniquePtr<KeymasterAttributes> km_attributes(km_attributes_p);
450 if (!km_attributes->has_product_id) {
451 return KM_ERROR_INVALID_ARGUMENT;
452 }
453 if (km_attributes->product_id.size != kProductIdSize) {
454 return KM_ERROR_UNKNOWN_ERROR;
455 }
456 memcpy(product_id, km_attributes->product_id.bytes, kProductIdSize);
457 return KM_ERROR_OK;
458 }
459
460 struct AttestationIdResult {
461 keymaster_error_t error;
462 UniquePtr<AttestationIds> ids;
463 };
464
ValidateAndSetBaseAttestationIds(const SetAttestationIdsRequest & request)465 static struct AttestationIdResult ValidateAndSetBaseAttestationIds(
466 const SetAttestationIdsRequest& request) {
467 AttestationIds* attestation_ids_p =
468 new (std::nothrow) AttestationIds(AttestationIds_init_zero);
469 if (attestation_ids_p == nullptr) {
470 return {KM_ERROR_MEMORY_ALLOCATION_FAILED, nullptr};
471 }
472 UniquePtr<AttestationIds> attestation_ids(attestation_ids_p);
473 if (request.brand.buffer_size() > kAttestationIdLengthMax) {
474 LOG_E("Error: Brand ID too large: %zu", request.brand.buffer_size());
475 return {KM_ERROR_INVALID_ARGUMENT, nullptr};
476 } else if (request.brand.buffer_size() > 0) {
477 attestation_ids->has_brand = true;
478 attestation_ids->brand.size = request.brand.buffer_size();
479 memcpy(attestation_ids->brand.bytes, request.brand.begin(),
480 request.brand.buffer_size());
481 }
482
483 if (request.device.buffer_size() > kAttestationIdLengthMax) {
484 LOG_E("Error: Device ID too large: %zu", request.device.buffer_size());
485 return {KM_ERROR_INVALID_ARGUMENT, nullptr};
486 } else if (request.device.buffer_size() > 0) {
487 attestation_ids->has_device = true;
488 attestation_ids->device.size = request.device.buffer_size();
489 memcpy(attestation_ids->device.bytes, request.device.begin(),
490 request.device.buffer_size());
491 }
492
493 if (request.product.buffer_size() > kAttestationIdLengthMax) {
494 LOG_E("Error: Product ID too large: %zu",
495 request.product.buffer_size());
496 return {KM_ERROR_INVALID_ARGUMENT, nullptr};
497 } else if (request.product.buffer_size() > 0) {
498 attestation_ids->has_product = true;
499 attestation_ids->product.size = request.product.buffer_size();
500 memcpy(attestation_ids->product.bytes, request.product.begin(),
501 request.product.buffer_size());
502 }
503
504 if (request.serial.buffer_size() > kAttestationIdLengthMax) {
505 LOG_E("Error: Serial number too large: %zu",
506 request.serial.buffer_size());
507 return {KM_ERROR_INVALID_ARGUMENT, nullptr};
508 } else if (request.serial.buffer_size() > 0) {
509 attestation_ids->has_serial = true;
510 attestation_ids->serial.size = request.serial.buffer_size();
511 memcpy(attestation_ids->serial.bytes, request.serial.begin(),
512 request.serial.buffer_size());
513 }
514
515 if (request.imei.buffer_size() > kAttestationIdLengthMax) {
516 LOG_E("Error: IMEI ID too large: %zu", request.imei.buffer_size());
517 return {KM_ERROR_INVALID_ARGUMENT, nullptr};
518 } else if (request.imei.buffer_size() > 0) {
519 attestation_ids->has_imei = true;
520 attestation_ids->imei.size = request.imei.buffer_size();
521 memcpy(attestation_ids->imei.bytes, request.imei.begin(),
522 request.imei.buffer_size());
523 }
524
525 if (request.meid.buffer_size() > kAttestationIdLengthMax) {
526 LOG_E("Error: MEID ID too large: %zu", request.meid.buffer_size());
527 return {KM_ERROR_INVALID_ARGUMENT, nullptr};
528 } else if (request.meid.buffer_size() > 0) {
529 attestation_ids->has_meid = true;
530 attestation_ids->meid.size = request.meid.buffer_size();
531 memcpy(attestation_ids->meid.bytes, request.meid.begin(),
532 request.meid.buffer_size());
533 }
534
535 if (request.manufacturer.buffer_size() > kAttestationIdLengthMax) {
536 LOG_E("Error: Manufacturer ID too large: %zu",
537 request.manufacturer.buffer_size());
538 return {KM_ERROR_INVALID_ARGUMENT, nullptr};
539 } else if (request.manufacturer.buffer_size() > 0) {
540 attestation_ids->has_manufacturer = true;
541 attestation_ids->manufacturer.size = request.manufacturer.buffer_size();
542 memcpy(attestation_ids->manufacturer.bytes,
543 request.manufacturer.begin(),
544 request.manufacturer.buffer_size());
545 }
546
547 if (request.model.buffer_size() > kAttestationIdLengthMax) {
548 LOG_E("Error: Model ID too large: %zu", request.model.buffer_size());
549 return {KM_ERROR_INVALID_ARGUMENT, nullptr};
550 } else if (request.model.buffer_size() > 0) {
551 attestation_ids->has_model = true;
552 attestation_ids->model.size = request.model.buffer_size();
553 memcpy(attestation_ids->model.bytes, request.model.begin(),
554 request.model.buffer_size());
555 }
556 return {KM_ERROR_OK, std::move(attestation_ids)};
557 }
558
SetAttestationIdsKM3(const SetAttestationIdsKM3Request & request)559 keymaster_error_t SecureStorageManager::SetAttestationIdsKM3(
560 const SetAttestationIdsKM3Request& request) {
561 auto result = ValidateAndSetBaseAttestationIds(request.base);
562 if (result.error != KM_ERROR_OK) {
563 return result.error;
564 }
565 if (request.second_imei.buffer_size() > kAttestationIdLengthMax) {
566 LOG_E("Error: Second IMEI ID too large: %zu",
567 request.second_imei.buffer_size());
568 return KM_ERROR_INVALID_ARGUMENT;
569 } else if (request.second_imei.buffer_size() > 0) {
570 result.ids->has_second_imei = true;
571 result.ids->second_imei.size = request.second_imei.buffer_size();
572 memcpy(result.ids->second_imei.bytes, request.second_imei.begin(),
573 request.second_imei.buffer_size());
574 }
575
576 keymaster_error_t err = WriteAttestationIds(result.ids.get(), true);
577 if (err != KM_ERROR_OK) {
578 CloseSession();
579 }
580 return err;
581 }
582
ClearAttestationIds()583 keymaster_error_t SecureStorageManager::ClearAttestationIds() {
584 int rc = storage_delete_file(session_handle_, kAttestationIdsFileName,
585 STORAGE_OP_COMPLETE);
586 if (rc < 0 && rc != ERR_NOT_FOUND) {
587 LOG_E("Error: [%d] deleting attestation IDs file", rc);
588 CloseSession();
589 return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
590 }
591 return KM_ERROR_UNIMPLEMENTED;
592 }
593
SetAttestationIds(const SetAttestationIdsRequest & request)594 keymaster_error_t SecureStorageManager::SetAttestationIds(
595 const SetAttestationIdsRequest& request) {
596 auto result = ValidateAndSetBaseAttestationIds(request);
597 if (result.error != KM_ERROR_OK) {
598 return result.error;
599 }
600 keymaster_error_t err = WriteAttestationIds(result.ids.get(), true);
601 if (err != KM_ERROR_OK) {
602 CloseSession();
603 }
604 return err;
605 }
606
ReadAttestationIds(AttestationIds * attestation_ids_p)607 keymaster_error_t SecureStorageManager::ReadAttestationIds(
608 AttestationIds* attestation_ids_p) {
609 *attestation_ids_p = AttestationIds_init_zero;
610 keymaster_error_t err = DecodeFromFile(
611 AttestationIds_fields, attestation_ids_p, kAttestationIdsFileName);
612 if (err < 0) {
613 LOG_E("Error: [%d] decoding from file '%s'", err,
614 kAttestationIdsFileName);
615 CloseSession();
616 return err;
617 }
618 return KM_ERROR_OK;
619 }
620
DeleteProductId()621 keymaster_error_t SecureStorageManager::DeleteProductId() {
622 KeymasterAttributes* km_attributes_p;
623 keymaster_error_t err = ReadKeymasterAttributes(&km_attributes_p);
624 if (err != KM_ERROR_OK) {
625 CloseSession();
626 return err;
627 }
628 UniquePtr<KeymasterAttributes> km_attributes(km_attributes_p);
629 km_attributes_p->has_product_id = false;
630 err = WriteKeymasterAttributes(km_attributes.get(), true);
631 if (err != KM_ERROR_OK) {
632 CloseSession();
633 }
634 return err;
635 }
636
DeleteAllAttestationData()637 keymaster_error_t SecureStorageManager::DeleteAllAttestationData() {
638 if (DeleteKey(AttestationKeySlot::kRsa, false) != KM_ERROR_OK ||
639 DeleteKey(AttestationKeySlot::kEcdsa, false) != KM_ERROR_OK ||
640 DeleteKey(AttestationKeySlot::kEddsa, false) != KM_ERROR_OK ||
641 DeleteKey(AttestationKeySlot::kEpid, false) != KM_ERROR_OK ||
642 DeleteKey(AttestationKeySlot::kClaimable0, false) != KM_ERROR_OK ||
643 DeleteKey(AttestationKeySlot::kSomRsa, false) != KM_ERROR_OK ||
644 DeleteKey(AttestationKeySlot::kSomEcdsa, false) != KM_ERROR_OK ||
645 DeleteKey(AttestationKeySlot::kSomEddsa, false) != KM_ERROR_OK ||
646 DeleteKey(AttestationKeySlot::kSomEpid, false) != KM_ERROR_OK) {
647 // Something wrong, abort the transaction.
648 storage_end_transaction(session_handle_, false);
649 CloseSession();
650 return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
651 }
652 int rc = storage_end_transaction(session_handle_, true);
653 if (rc < 0) {
654 LOG_E("Error: failed to commit transaction while deleting keys.");
655 CloseSession();
656 return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
657 }
658 return KM_ERROR_OK;
659 }
660
ReadAttestationKey(AttestationKeySlot key_slot,AttestationKey ** attestation_key_p)661 keymaster_error_t SecureStorageManager::ReadAttestationKey(
662 AttestationKeySlot key_slot,
663 AttestationKey** attestation_key_p) {
664 char key_file[kStorageIdLengthMax];
665 snprintf(key_file, kStorageIdLengthMax, "%s.%s", kAttestKeyCertPrefix,
666 GetKeySlotStr(key_slot));
667
668 UniquePtr<AttestationKey> attestation_key(
669 new (std::nothrow) AttestationKey(AttestationKey_init_zero));
670 if (!attestation_key.get()) {
671 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
672 }
673 keymaster_error_t err = DecodeFromFile(AttestationKey_fields,
674 attestation_key.get(), key_file);
675 if (err < 0) {
676 LOG_E("Error: [%d] decoding from file '%s'", err, key_file);
677 return err;
678 }
679 *attestation_key_p = attestation_key.release();
680 return KM_ERROR_OK;
681 }
682
WriteAttestationKey(AttestationKeySlot key_slot,const AttestationKey * attestation_key,bool commit)683 keymaster_error_t SecureStorageManager::WriteAttestationKey(
684 AttestationKeySlot key_slot,
685 const AttestationKey* attestation_key,
686 bool commit) {
687 char key_file[kStorageIdLengthMax];
688 snprintf(key_file, kStorageIdLengthMax, "%s.%s", kAttestKeyCertPrefix,
689 GetKeySlotStr(key_slot));
690
691 return EncodeToFile(AttestationKey_fields, attestation_key, key_file,
692 commit);
693 }
694
CloseSession()695 void SecureStorageManager::CloseSession() {
696 if (session_handle_ != STORAGE_INVALID_SESSION) {
697 storage_close_session(session_handle_);
698 session_handle_ = STORAGE_INVALID_SESSION;
699 }
700 }
701
702 struct FileStatus {
703 /* How many bytes handled in the file. */
704 uint64_t bytes_handled;
705 file_handle_t file_handle;
FileStatuskeymaster::FileStatus706 FileStatus() : bytes_handled(0), file_handle(0) {}
707 };
708
write_to_file_callback(pb_ostream_t * stream,const uint8_t * buf,size_t count)709 bool write_to_file_callback(pb_ostream_t* stream,
710 const uint8_t* buf,
711 size_t count) {
712 FileStatus* file_status = reinterpret_cast<FileStatus*>(stream->state);
713 /* Do not commit the write. */
714 int rc = storage_write(file_status->file_handle, file_status->bytes_handled,
715 buf, count, 0);
716 if (rc < 0 || static_cast<size_t>(rc) < count) {
717 LOG_E("Error: failed to write to file: %d\n", rc);
718 return false;
719 }
720 file_status->bytes_handled += rc;
721 return true;
722 }
723
read_from_file_callback(pb_istream_t * stream,uint8_t * buf,size_t count)724 bool read_from_file_callback(pb_istream_t* stream, uint8_t* buf, size_t count) {
725 if (buf == NULL) {
726 return false;
727 }
728 FileStatus* file_status = reinterpret_cast<FileStatus*>(stream->state);
729 int rc = storage_read(file_status->file_handle, file_status->bytes_handled,
730 buf, count);
731 if (rc < 0 || static_cast<size_t>(rc) < count) {
732 LOG_E("Error: failed to read from file: %d\n", rc);
733 return false;
734 }
735 file_status->bytes_handled += rc;
736 return true;
737 }
738
EncodeToFile(const pb_field_t fields[],const void * dest_struct,const char filename[],bool commit)739 keymaster_error_t SecureStorageManager::EncodeToFile(const pb_field_t fields[],
740 const void* dest_struct,
741 const char filename[],
742 bool commit) {
743 FileCloser file;
744 int rc = file.open_file(
745 session_handle_, filename,
746 STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE, 0);
747 if (rc < 0) {
748 LOG_E("Error: failed to open file '%s': %d\n", filename, rc);
749 return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
750 }
751 FileStatus new_file_status;
752 new_file_status.file_handle = file.get_file_handle();
753 pb_ostream_t stream = {&write_to_file_callback, &new_file_status, SIZE_MAX,
754 0, 0};
755 if (!pb_encode(&stream, fields, dest_struct)) {
756 LOG_E("Error: encoding fields to file '%s'", filename);
757 /* Abort the transaction. */
758 storage_end_transaction(session_handle_, false);
759 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
760 }
761 if (commit) {
762 /* Commit the write. */
763 rc = storage_end_transaction(session_handle_, true);
764 if (rc < 0) {
765 LOG_E("Error: failed to commit write transaction for file '%s': %d"
766 "\n",
767 filename, rc);
768 return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
769 }
770 }
771 return KM_ERROR_OK;
772 }
773
DecodeFromFile(const pb_field_t fields[],void * dest_struct,const char filename[])774 keymaster_error_t SecureStorageManager::DecodeFromFile(
775 const pb_field_t fields[],
776 void* dest_struct,
777 const char filename[]) {
778 uint64_t file_size;
779 FileCloser file;
780 int rc = file.open_file(session_handle_, filename, 0, 0);
781 if (rc == ERR_NOT_FOUND) {
782 // File not exists
783 return KM_ERROR_OK;
784 }
785 if (rc < 0) {
786 LOG_E("Error: failed to open file '%s': %d\n", filename, rc);
787 return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
788 }
789 rc = storage_get_file_size(file.get_file_handle(), &file_size);
790 if (rc < 0) {
791 LOG_E("Error: failed to get size of attributes file '%s': %d\n",
792 filename, rc);
793 return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
794 }
795 FileStatus new_file_status;
796 new_file_status.file_handle = file.get_file_handle();
797 pb_istream_t stream = {&read_from_file_callback, &new_file_status,
798 static_cast<size_t>(file_size), 0};
799 if (!pb_decode(&stream, fields, dest_struct)) {
800 LOG_E("Error: decoding fields from file '%s'", filename);
801 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
802 }
803 return KM_ERROR_OK;
804 }
805
806 #ifdef KEYMASTER_LEGACY_FORMAT
807
TranslateLegacyFormat()808 keymaster_error_t SecureStorageManager::TranslateLegacyFormat() {
809 FileCloser file;
810 int rc = file.open_file(session_handle_, kAttributeFileName, 0, 0);
811 if (rc == NO_ERROR) {
812 // New attribute file exists, nothing to do.
813 return KM_ERROR_OK;
814 }
815
816 UniquePtr<KeymasterAttributes> km_attributes(new (
817 std::nothrow) KeymasterAttributes(KeymasterAttributes_init_zero));
818 if (km_attributes.get() == nullptr) {
819 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
820 }
821
822 AttestationKeySlot key_slots[] = {
823 AttestationKeySlot::kRsa, AttestationKeySlot::kEcdsa,
824 AttestationKeySlot::kEddsa, AttestationKeySlot::kEpid,
825 AttestationKeySlot::kClaimable0, AttestationKeySlot::kSomRsa,
826 AttestationKeySlot::kSomEcdsa, AttestationKeySlot::kSomEddsa,
827 AttestationKeySlot::kSomEpid};
828 char key_file[kStorageIdLengthMax];
829 char cert_file[kStorageIdLengthMax];
830 uint32_t key_size;
831 uint32_t cert_size;
832 keymaster_error_t err;
833 for (size_t i = 0; i < sizeof(key_slots) / sizeof(int); i++) {
834 AttestationKeySlot key_slot = key_slots[i];
835 UniquePtr<AttestationKey> attestation_key(
836 new (std::nothrow) AttestationKey(AttestationKey_init_zero));
837 if (attestation_key.get() == nullptr) {
838 return KM_ERROR_MEMORY_ALLOCATION_FAILED;
839 }
840 snprintf(key_file, kStorageIdLengthMax, "%s.%s", kLegacyAttestKeyPrefix,
841 GetKeySlotStr(key_slot));
842 err = LegacySecureStorageRead(key_file, attestation_key->key.bytes,
843 &key_size, kKeySizeMax);
844 if (err != KM_ERROR_OK) {
845 return err;
846 }
847 if (key_size == 0) {
848 // Legacy key file for this key slot is not found.
849 continue;
850 }
851 attestation_key->key.size = key_size;
852 attestation_key->has_key = true;
853 // Do not commit the delete.
854 rc = storage_delete_file(session_handle_, key_file, 0);
855 if (rc < 0) {
856 return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
857 }
858 for (int index = 0; index < kMaxCertChainLength; index++) {
859 snprintf(cert_file, kStorageIdLengthMax, "%s.%s.%d",
860 kLegacyAttestCertPrefix, GetKeySlotStr(key_slot), index);
861 err = LegacySecureStorageRead(
862 cert_file, attestation_key->certs[index].content.bytes,
863 &cert_size, kCertSizeMax);
864 if (err != KM_ERROR_OK) {
865 return err;
866 }
867 if (cert_size == 0) {
868 // One cert does not exist, no need to continue reading.
869 break;
870 }
871 attestation_key->certs[index].content.size = cert_size;
872 attestation_key->certs_count = index + 1;
873 // Do not commit the delete.
874 rc = storage_delete_file(session_handle_, cert_file, 0);
875 if (rc < 0) {
876 return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
877 }
878 }
879 // Do not commit the write.
880 keymaster_error_t err =
881 WriteAttestationKey(key_slot, attestation_key.get(), false);
882 if (err != KM_ERROR_OK) {
883 LOG_E("Failed to write attestation key for slot: %d: %d\n",
884 key_slot, err);
885 return err;
886 }
887 }
888
889 uint32_t product_id_size;
890 err = LegacySecureStorageRead(kLegacyProductIdFileName,
891 km_attributes->product_id.bytes,
892 &product_id_size, kProductIdSize);
893 if (err != KM_ERROR_OK) {
894 return err;
895 }
896 if (product_id_size != 0) {
897 km_attributes->has_product_id = true;
898 km_attributes->product_id.size = product_id_size;
899 rc = storage_delete_file(session_handle_, kLegacyProductIdFileName, 0);
900 if (rc < 0) {
901 return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
902 }
903 }
904 uint32_t uuid_size;
905 err = LegacySecureStorageRead(kLegacyAttestUuidFileName,
906 km_attributes->uuid.bytes, &uuid_size,
907 kAttestationUuidSize);
908 if (err != KM_ERROR_OK) {
909 return err;
910 }
911 if (uuid_size != 0) {
912 km_attributes->has_uuid = true;
913 km_attributes->uuid.size = uuid_size;
914 rc = storage_delete_file(session_handle_, kLegacyAttestUuidFileName, 0);
915 if (rc < 0) {
916 return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
917 }
918 }
919 err = WriteKeymasterAttributes(km_attributes.get(), false);
920 if (err != KM_ERROR_OK) {
921 return err;
922 }
923
924 // Commit the pending transactions.
925 rc = storage_end_transaction(session_handle_, STORAGE_OP_COMPLETE);
926 if (rc < 0) {
927 LOG_E("Error: failed to commit write transaction to translate file"
928 " format.\n");
929 return KM_ERROR_SECURE_HW_COMMUNICATION_FAILED;
930 }
931 return KM_ERROR_OK;
932 }
933
LegacySecureStorageRead(const char * filename,void * data,uint32_t * size,uint32_t max_size)934 keymaster_error_t SecureStorageManager::LegacySecureStorageRead(
935 const char* filename,
936 void* data,
937 uint32_t* size,
938 uint32_t max_size) {
939 FileCloser file;
940 uint64_t file_size;
941 int rc = file.open_file(session_handle_, filename, 0, 0);
942 if (rc == ERR_NOT_FOUND) {
943 *size = 0;
944 return KM_ERROR_OK;
945 }
946 rc = storage_get_file_size(file.get_file_handle(), &file_size);
947 if (rc < 0) {
948 return KM_ERROR_UNKNOWN_ERROR;
949 }
950 if (file_size > static_cast<uint64_t>(max_size)) {
951 return KM_ERROR_UNKNOWN_ERROR;
952 }
953 *size = static_cast<uint32_t>(file_size);
954 rc = storage_read(file.get_file_handle(), 0, data, file_size);
955 if (rc < 0) {
956 return KM_ERROR_UNKNOWN_ERROR;
957 }
958 if (static_cast<uint32_t>(rc) < *size) {
959 return KM_ERROR_UNKNOWN_ERROR;
960 }
961 return KM_ERROR_OK;
962 }
963
LegacySecureStorageWrite(const char * filename,const uint8_t * data,uint32_t data_size)964 keymaster_error_t SecureStorageManager::LegacySecureStorageWrite(
965 const char* filename,
966 const uint8_t* data,
967 uint32_t data_size) {
968 FileCloser file;
969 int rc = file.open_file(
970 session_handle_, filename,
971 STORAGE_FILE_OPEN_CREATE | STORAGE_FILE_OPEN_TRUNCATE, 0);
972 if (rc < 0) {
973 return KM_ERROR_UNKNOWN_ERROR;
974 }
975 rc = storage_write(file.get_file_handle(), 0, data, data_size,
976 STORAGE_OP_COMPLETE);
977 if (rc < 0) {
978 LOG_E("Error: [%d] writing storage object '%s'", rc, filename);
979 return KM_ERROR_UNKNOWN_ERROR;
980 }
981 if (static_cast<uint32_t>(rc) < data_size) {
982 LOG_E("Error: invalid object size [%d] from '%s'", rc, filename);
983 return KM_ERROR_UNKNOWN_ERROR;
984 }
985
986 return KM_ERROR_OK;
987 }
988
989 // Deprecated implementation for writing key to storage, for backward
990 // compatibility tests only.
LegacyWriteKeyToStorage(AttestationKeySlot key_slot,const uint8_t * key,uint32_t key_size)991 keymaster_error_t SecureStorageManager::LegacyWriteKeyToStorage(
992 AttestationKeySlot key_slot,
993 const uint8_t* key,
994 uint32_t key_size) {
995 char key_file[kStorageIdLengthMax];
996 snprintf(key_file, kStorageIdLengthMax, "%s.%s", kLegacyAttestKeyPrefix,
997 GetKeySlotStr(key_slot));
998 return LegacySecureStorageWrite(key_file, key, key_size);
999 }
1000
1001 // Deprecated implementation for writing cert to storage, for backward
1002 // compatibility tests only.
LegacyWriteCertToStorage(AttestationKeySlot key_slot,const uint8_t * cert,uint32_t cert_size,uint32_t index)1003 keymaster_error_t SecureStorageManager::LegacyWriteCertToStorage(
1004 AttestationKeySlot key_slot,
1005 const uint8_t* cert,
1006 uint32_t cert_size,
1007 uint32_t index) {
1008 char cert_file[kStorageIdLengthMax];
1009 snprintf(cert_file, kStorageIdLengthMax, "%s.%s.%d",
1010 kLegacyAttestCertPrefix, GetKeySlotStr(key_slot), index);
1011 return LegacySecureStorageWrite(cert_file, cert, cert_size);
1012 }
1013
1014 // Deprecated, for unit tests only.
LegacyWriteAttestationUuid(const uint8_t attestation_uuid[kAttestationUuidSize])1015 keymaster_error_t SecureStorageManager::LegacyWriteAttestationUuid(
1016 const uint8_t attestation_uuid[kAttestationUuidSize]) {
1017 return LegacySecureStorageWrite(kLegacyAttestUuidFileName, attestation_uuid,
1018 kAttestationUuidSize);
1019 }
1020
1021 // Deprecated, for unit tests only.
LegacySetProductId(const uint8_t product_id[kProductIdSize])1022 keymaster_error_t SecureStorageManager::LegacySetProductId(
1023 const uint8_t product_id[kProductIdSize]) {
1024 return LegacySecureStorageWrite(kLegacyProductIdFileName, product_id,
1025 kProductIdSize);
1026 }
1027 #endif // #ifdef KEYMASTER_LEGACY_FORMAT
1028
SecureStorageManager()1029 SecureStorageManager::SecureStorageManager() {
1030 session_handle_ = STORAGE_INVALID_SESSION;
1031 }
1032
~SecureStorageManager()1033 SecureStorageManager::~SecureStorageManager() {
1034 CloseSession();
1035 }
1036
1037 } // namespace keymaster
1038