1 // SPDX-License-Identifier: BSD-2-Clause 2 /* 3 * Copyright (c) 2014, STMicroelectronics International N.V. 4 */ 5 6 #include <assert.h> 7 #include <crypto/crypto.h> 8 #include <kernel/huk_subkey.h> 9 #include <kernel/misc.h> 10 #include <kernel/msg_param.h> 11 #include <kernel/mutex.h> 12 #include <kernel/panic.h> 13 #include <kernel/tee_common.h> 14 #include <kernel/tee_common_otp.h> 15 #include <kernel/tee_misc.h> 16 #include <kernel/thread.h> 17 #include <mempool.h> 18 #include <mm/core_memprot.h> 19 #include <mm/mobj.h> 20 #include <mm/tee_mm.h> 21 #include <optee_rpc_cmd.h> 22 #include <stdlib.h> 23 #include <string_ext.h> 24 #include <string.h> 25 #include <sys/queue.h> 26 #include <tee/tee_fs.h> 27 #include <tee/tee_fs_key_manager.h> 28 #include <tee/tee_pobj.h> 29 #include <tee/tee_svc_storage.h> 30 #include <trace.h> 31 #include <util.h> 32 33 #define RPMB_STORAGE_START_ADDRESS 0 34 #define RPMB_FS_FAT_START_ADDRESS 512 35 #define RPMB_BLOCK_SIZE_SHIFT 8 36 #define RPMB_CID_PRV_OFFSET 9 37 #define RPMB_CID_CRC_OFFSET 15 38 39 #define RPMB_FS_MAGIC 0x52504D42 40 #define FS_VERSION 2 41 42 #define FILE_IS_ACTIVE (1u << 0) 43 #define FILE_IS_LAST_ENTRY (1u << 1) 44 45 #define TEE_RPMB_FS_FILENAME_LENGTH 224 46 47 #define TMP_BLOCK_SIZE 4096U 48 49 #define RPMB_MAX_RETRIES 10 50 51 /** 52 * Utilized when caching is enabled, i.e., when CFG_RPMB_FS_CACHE_ENTRIES > 0. 53 * Cache size + the number of entries that are repeatedly read in and buffered 54 * once the cache is full. 55 */ 56 #define RPMB_BUF_MAX_ENTRIES (CFG_RPMB_FS_CACHE_ENTRIES + \ 57 CFG_RPMB_FS_RD_ENTRIES) 58 59 /** 60 * FS parameters: Information often used by internal functions. 61 * fat_start_address will be set by rpmb_fs_setup(). 62 * rpmb_fs_parameters can be read by any other function. 63 */ 64 struct rpmb_fs_parameters { 65 uint32_t fat_start_address; 66 uint32_t max_rpmb_address; 67 }; 68 69 /** 70 * File entry for a single file in a RPMB_FS partition. 71 */ 72 struct rpmb_fat_entry { 73 uint32_t start_address; 74 uint32_t data_size; 75 uint32_t flags; 76 uint32_t write_counter; 77 uint8_t fek[TEE_FS_KM_FEK_SIZE]; 78 char filename[TEE_RPMB_FS_FILENAME_LENGTH]; 79 }; 80 81 /** 82 * Structure that describes buffered/cached FAT FS entries in RPMB storage. 83 * This structure is used in functions traversing the FAT FS. 84 */ 85 struct rpmb_fat_entry_dir { 86 /* 87 * Buffer storing the FAT FS entries read in from RPMB storage. It 88 * includes the optional cache entries (CFG_RPMB_FS_CACHE_ENTRIES) 89 * and entries temporary read for current FAT FS traversal 90 * (CFG_RPMB_FS_RD_ENTRIES) when not found from cached entries. 91 */ 92 struct rpmb_fat_entry *rpmb_fat_entry_buf; 93 /* Current index of FAT FS entry to read from buffer. */ 94 uint32_t idx_curr; 95 /* Total number of FAT FS entries in buffer. */ 96 uint32_t num_buffered; 97 /* Total number of FAT FS entries read during traversal. */ 98 uint32_t num_total_read; 99 /* Indicates that last FAT FS entry was read. */ 100 bool last_reached; 101 }; 102 103 /** 104 * FAT entry context with reference to a FAT entry and its 105 * location in RPMB. 106 */ 107 struct rpmb_file_handle { 108 struct rpmb_fat_entry fat_entry; 109 const TEE_UUID *uuid; 110 char filename[TEE_RPMB_FS_FILENAME_LENGTH]; 111 /* Address for current entry in RPMB */ 112 uint32_t rpmb_fat_address; 113 }; 114 115 /** 116 * RPMB_FS partition data 117 */ 118 struct rpmb_fs_partition { 119 uint32_t rpmb_fs_magic; 120 uint32_t fs_version; 121 uint32_t write_counter; 122 uint32_t fat_start_address; 123 /* Do not use reserved[] for other purpose than partition data. */ 124 uint8_t reserved[112]; 125 }; 126 127 /** 128 * A node in a list of directory entries. 129 */ 130 struct tee_rpmb_fs_dirent { 131 struct tee_fs_dirent entry; 132 SIMPLEQ_ENTRY(tee_rpmb_fs_dirent) link; 133 }; 134 135 /** 136 * The RPMB directory representation. It contains a queue of 137 * RPMB directory entries: 'next'. 138 * The current pointer points to the last directory entry 139 * returned by readdir(). 140 */ 141 struct tee_fs_dir { 142 struct tee_rpmb_fs_dirent *current; 143 /* */ 144 SIMPLEQ_HEAD(next_head, tee_rpmb_fs_dirent) next; 145 }; 146 147 static struct rpmb_fs_parameters *fs_par; 148 static struct rpmb_fat_entry_dir *fat_entry_dir; 149 150 /* 151 * Lower interface to RPMB device 152 */ 153 154 #define RPMB_DATA_OFFSET (RPMB_STUFF_DATA_SIZE + RPMB_KEY_MAC_SIZE) 155 #define RPMB_MAC_PROTECT_DATA_SIZE (RPMB_DATA_FRAME_SIZE - RPMB_DATA_OFFSET) 156 157 #define RPMB_MSG_TYPE_REQ_AUTH_KEY_PROGRAM 0x0001 158 #define RPMB_MSG_TYPE_REQ_WRITE_COUNTER_VAL_READ 0x0002 159 #define RPMB_MSG_TYPE_REQ_AUTH_DATA_WRITE 0x0003 160 #define RPMB_MSG_TYPE_REQ_AUTH_DATA_READ 0x0004 161 #define RPMB_MSG_TYPE_REQ_RESULT_READ 0x0005 162 #define RPMB_MSG_TYPE_RESP_AUTH_KEY_PROGRAM 0x0100 163 #define RPMB_MSG_TYPE_RESP_WRITE_COUNTER_VAL_READ 0x0200 164 #define RPMB_MSG_TYPE_RESP_AUTH_DATA_WRITE 0x0300 165 #define RPMB_MSG_TYPE_RESP_AUTH_DATA_READ 0x0400 166 167 #define RPMB_STUFF_DATA_SIZE 196 168 #define RPMB_KEY_MAC_SIZE 32 169 #define RPMB_DATA_SIZE 256 170 #define RPMB_NONCE_SIZE 16 171 #define RPMB_DATA_FRAME_SIZE 512 172 173 #define RPMB_RESULT_OK 0x00 174 #define RPMB_RESULT_GENERAL_FAILURE 0x01 175 #define RPMB_RESULT_AUTH_FAILURE 0x02 176 #define RPMB_RESULT_COUNTER_FAILURE 0x03 177 #define RPMB_RESULT_ADDRESS_FAILURE 0x04 178 #define RPMB_RESULT_WRITE_FAILURE 0x05 179 #define RPMB_RESULT_READ_FAILURE 0x06 180 #define RPMB_RESULT_AUTH_KEY_NOT_PROGRAMMED 0x07 181 #define RPMB_RESULT_MASK 0x3F 182 #define RPMB_RESULT_WR_CNT_EXPIRED 0x80 183 184 /* RPMB internal commands */ 185 #define RPMB_CMD_DATA_REQ 0x00 186 #define RPMB_CMD_GET_DEV_INFO 0x01 187 188 #define RPMB_SIZE_SINGLE (128 * 1024) 189 190 /* Error codes for get_dev_info request/response. */ 191 #define RPMB_CMD_GET_DEV_INFO_RET_OK 0x00 192 #define RPMB_CMD_GET_DEV_INFO_RET_ERROR 0x01 193 194 struct rpmb_data_frame { 195 uint8_t stuff_bytes[RPMB_STUFF_DATA_SIZE]; 196 uint8_t key_mac[RPMB_KEY_MAC_SIZE]; 197 uint8_t data[RPMB_DATA_SIZE]; 198 uint8_t nonce[RPMB_NONCE_SIZE]; 199 uint8_t write_counter[4]; 200 uint8_t address[2]; 201 uint8_t block_count[2]; 202 uint8_t op_result[2]; 203 uint8_t msg_type[2]; 204 }; 205 206 struct rpmb_req { 207 uint16_t cmd; 208 uint16_t dev_id; 209 uint16_t block_count; 210 /* variable length of data */ 211 /* uint8_t data[]; REMOVED! */ 212 }; 213 214 #define TEE_RPMB_REQ_DATA(req) \ 215 ((void *)((struct rpmb_req *)(req) + 1)) 216 217 struct rpmb_raw_data { 218 uint16_t msg_type; 219 uint16_t *op_result; 220 uint16_t *block_count; 221 uint16_t *blk_idx; 222 uint32_t *write_counter; 223 uint8_t *nonce; 224 uint8_t *key_mac; 225 uint8_t *data; 226 /* data length to read or write */ 227 uint32_t len; 228 /* Byte address offset in the first block involved */ 229 uint8_t byte_offset; 230 }; 231 232 #define RPMB_EMMC_CID_SIZE 16 233 struct rpmb_dev_info { 234 uint8_t cid[RPMB_EMMC_CID_SIZE]; 235 /* EXT CSD-slice 168 "RPMB Size" */ 236 uint8_t rpmb_size_mult; 237 /* EXT CSD-slice 222 "Reliable Write Sector Count" */ 238 uint8_t rel_wr_sec_c; 239 /* Check the ret code and accept the data only if it is OK. */ 240 uint8_t ret_code; 241 }; 242 243 /* 244 * Struct for rpmb context data. 245 * 246 * @key RPMB key. 247 * @cid eMMC card ID. 248 * @wr_cnt Current write counter. 249 * @max_blk_idx The highest block index supported by current device. 250 * @rel_wr_blkcnt Max number of data blocks for each reliable write. 251 * @dev_id Device ID of the eMMC device. 252 * @wr_cnt_synced Flag indicating if write counter is synced to RPMB. 253 * @key_derived Flag indicating if key has been generated. 254 * @key_verified Flag indicating the key generated is verified ok. 255 * @dev_info_synced Flag indicating if dev info has been retrieved from RPMB. 256 */ 257 struct tee_rpmb_ctx { 258 uint8_t key[RPMB_KEY_MAC_SIZE]; 259 uint8_t cid[RPMB_EMMC_CID_SIZE]; 260 uint32_t wr_cnt; 261 uint16_t max_blk_idx; 262 uint16_t rel_wr_blkcnt; 263 uint16_t dev_id; 264 bool wr_cnt_synced; 265 bool key_derived; 266 bool key_verified; 267 bool dev_info_synced; 268 }; 269 270 static struct tee_rpmb_ctx *rpmb_ctx; 271 272 /* If set to true, don't try to access RPMB until rebooted */ 273 static bool rpmb_dead; 274 275 /* 276 * Mutex to serialize the operations exported by this file. 277 * It protects rpmb_ctx and prevents overlapping operations on eMMC devices with 278 * different IDs. 279 */ 280 static struct mutex rpmb_mutex = MUTEX_INITIALIZER; 281 282 #ifdef CFG_RPMB_TESTKEY 283 284 static const uint8_t rpmb_test_key[RPMB_KEY_MAC_SIZE] = { 285 0xD3, 0xEB, 0x3E, 0xC3, 0x6E, 0x33, 0x4C, 0x9F, 286 0x98, 0x8C, 0xE2, 0xC0, 0xB8, 0x59, 0x54, 0x61, 287 0x0D, 0x2B, 0xCF, 0x86, 0x64, 0x84, 0x4D, 0xF2, 288 0xAB, 0x56, 0xE6, 0xC6, 0x1B, 0xB7, 0x01, 0xE4 289 }; 290 291 static TEE_Result tee_rpmb_key_gen(uint16_t dev_id __unused, 292 uint8_t *key, uint32_t len) 293 { 294 TEE_Result res = TEE_SUCCESS; 295 296 if (!key || RPMB_KEY_MAC_SIZE != len) { 297 res = TEE_ERROR_BAD_PARAMETERS; 298 goto out; 299 } 300 301 DMSG("RPMB: Using test key"); 302 memcpy(key, rpmb_test_key, RPMB_KEY_MAC_SIZE); 303 304 out: 305 return res; 306 } 307 308 #else /* !CFG_RPMB_TESTKEY */ 309 310 static TEE_Result tee_rpmb_key_gen(uint16_t dev_id __unused, 311 uint8_t *key, uint32_t len) 312 { 313 uint8_t message[RPMB_EMMC_CID_SIZE]; 314 315 if (!key || RPMB_KEY_MAC_SIZE != len) 316 return TEE_ERROR_BAD_PARAMETERS; 317 318 IMSG("RPMB: Using generated key"); 319 320 /* 321 * PRV/CRC would be changed when doing eMMC FFU 322 * The following fields should be masked off when deriving RPMB key 323 * 324 * CID [55: 48]: PRV (Product revision) 325 * CID [07: 01]: CRC (CRC7 checksum) 326 * CID [00]: not used 327 */ 328 memcpy(message, rpmb_ctx->cid, RPMB_EMMC_CID_SIZE); 329 memset(message + RPMB_CID_PRV_OFFSET, 0, 1); 330 memset(message + RPMB_CID_CRC_OFFSET, 0, 1); 331 return huk_subkey_derive(HUK_SUBKEY_RPMB, message, sizeof(message), 332 key, len); 333 } 334 335 #endif /* !CFG_RPMB_TESTKEY */ 336 337 static void u32_to_bytes(uint32_t u32, uint8_t *bytes) 338 { 339 *bytes = (uint8_t) (u32 >> 24); 340 *(bytes + 1) = (uint8_t) (u32 >> 16); 341 *(bytes + 2) = (uint8_t) (u32 >> 8); 342 *(bytes + 3) = (uint8_t) u32; 343 } 344 345 static void bytes_to_u32(uint8_t *bytes, uint32_t *u32) 346 { 347 *u32 = (uint32_t) ((*(bytes) << 24) + 348 (*(bytes + 1) << 16) + 349 (*(bytes + 2) << 8) + (*(bytes + 3))); 350 } 351 352 static void u16_to_bytes(uint16_t u16, uint8_t *bytes) 353 { 354 *bytes = (uint8_t) (u16 >> 8); 355 *(bytes + 1) = (uint8_t) u16; 356 } 357 358 static void bytes_to_u16(uint8_t *bytes, uint16_t *u16) 359 { 360 *u16 = (uint16_t) ((*bytes << 8) + *(bytes + 1)); 361 } 362 363 static void get_op_result_bits(uint8_t *bytes, uint8_t *res) 364 { 365 *res = *(bytes + 1) & RPMB_RESULT_MASK; 366 } 367 368 static TEE_Result tee_rpmb_mac_calc(uint8_t *mac, uint32_t macsize, 369 uint8_t *key, uint32_t keysize, 370 struct rpmb_data_frame *datafrms, 371 uint16_t blkcnt) 372 { 373 TEE_Result res = TEE_ERROR_GENERIC; 374 int i; 375 void *ctx = NULL; 376 377 if (!mac || !key || !datafrms) 378 return TEE_ERROR_BAD_PARAMETERS; 379 380 res = crypto_mac_alloc_ctx(&ctx, TEE_ALG_HMAC_SHA256); 381 if (res) 382 return res; 383 384 res = crypto_mac_init(ctx, key, keysize); 385 if (res != TEE_SUCCESS) 386 goto func_exit; 387 388 for (i = 0; i < blkcnt; i++) { 389 res = crypto_mac_update(ctx, datafrms[i].data, 390 RPMB_MAC_PROTECT_DATA_SIZE); 391 if (res != TEE_SUCCESS) 392 goto func_exit; 393 } 394 395 res = crypto_mac_final(ctx, mac, macsize); 396 if (res != TEE_SUCCESS) 397 goto func_exit; 398 399 res = TEE_SUCCESS; 400 401 func_exit: 402 crypto_mac_free_ctx(ctx); 403 return res; 404 } 405 406 struct tee_rpmb_mem { 407 struct mobj *phreq_mobj; 408 struct mobj *phresp_mobj; 409 size_t req_size; 410 size_t resp_size; 411 }; 412 413 static void tee_rpmb_free(struct tee_rpmb_mem *mem) 414 { 415 if (!mem) 416 return; 417 418 if (mem->phreq_mobj) { 419 thread_rpc_free_payload(mem->phreq_mobj); 420 mem->phreq_mobj = NULL; 421 } 422 if (mem->phresp_mobj) { 423 thread_rpc_free_payload(mem->phresp_mobj); 424 mem->phresp_mobj = NULL; 425 } 426 } 427 428 429 static TEE_Result tee_rpmb_alloc(size_t req_size, size_t resp_size, 430 struct tee_rpmb_mem *mem, void **req, void **resp) 431 { 432 TEE_Result res = TEE_SUCCESS; 433 size_t req_s = ROUNDUP(req_size, sizeof(uint32_t)); 434 size_t resp_s = ROUNDUP(resp_size, sizeof(uint32_t)); 435 436 if (!mem) 437 return TEE_ERROR_BAD_PARAMETERS; 438 439 memset(mem, 0, sizeof(*mem)); 440 441 mem->phreq_mobj = thread_rpc_alloc_payload(req_s); 442 mem->phresp_mobj = thread_rpc_alloc_payload(resp_s); 443 444 if (!mem->phreq_mobj || !mem->phresp_mobj) { 445 res = TEE_ERROR_OUT_OF_MEMORY; 446 goto out; 447 } 448 449 *req = mobj_get_va(mem->phreq_mobj, 0); 450 *resp = mobj_get_va(mem->phresp_mobj, 0); 451 if (!*req || !*resp) { 452 res = TEE_ERROR_GENERIC; 453 goto out; 454 } 455 456 mem->req_size = req_size; 457 mem->resp_size = resp_size; 458 459 out: 460 if (res != TEE_SUCCESS) 461 tee_rpmb_free(mem); 462 return res; 463 } 464 465 static TEE_Result tee_rpmb_invoke(struct tee_rpmb_mem *mem) 466 { 467 struct thread_param params[2] = { 468 [0] = THREAD_PARAM_MEMREF(IN, mem->phreq_mobj, 0, 469 mem->req_size), 470 [1] = THREAD_PARAM_MEMREF(OUT, mem->phresp_mobj, 0, 471 mem->resp_size), 472 }; 473 474 return thread_rpc_cmd(OPTEE_RPC_CMD_RPMB, 2, params); 475 } 476 477 static bool is_zero(const uint8_t *buf, size_t size) 478 { 479 size_t i; 480 481 for (i = 0; i < size; i++) 482 if (buf[i]) 483 return false; 484 return true; 485 } 486 487 static TEE_Result encrypt_block(uint8_t *out, const uint8_t *in, 488 uint16_t blk_idx, const uint8_t *fek, 489 const TEE_UUID *uuid) 490 { 491 return tee_fs_crypt_block(uuid, out, in, RPMB_DATA_SIZE, 492 blk_idx, fek, TEE_MODE_ENCRYPT); 493 } 494 495 static TEE_Result decrypt_block(uint8_t *out, const uint8_t *in, 496 uint16_t blk_idx, const uint8_t *fek, 497 const TEE_UUID *uuid) 498 { 499 return tee_fs_crypt_block(uuid, out, in, RPMB_DATA_SIZE, 500 blk_idx, fek, TEE_MODE_DECRYPT); 501 } 502 503 /* Decrypt/copy at most one block of data */ 504 static TEE_Result decrypt(uint8_t *out, const struct rpmb_data_frame *frm, 505 size_t size, size_t offset, 506 uint16_t blk_idx __maybe_unused, const uint8_t *fek, 507 const TEE_UUID *uuid) 508 { 509 uint8_t *tmp __maybe_unused; 510 TEE_Result res = TEE_SUCCESS; 511 512 513 if ((size + offset < size) || (size + offset > RPMB_DATA_SIZE)) 514 panic("invalid size or offset"); 515 516 if (!fek) { 517 /* Block is not encrypted (not a file data block) */ 518 memcpy(out, frm->data + offset, size); 519 } else if (is_zero(fek, TEE_FS_KM_FEK_SIZE)) { 520 /* The file was created with encryption disabled */ 521 return TEE_ERROR_SECURITY; 522 } else { 523 /* Block is encrypted */ 524 if (size < RPMB_DATA_SIZE) { 525 /* 526 * Since output buffer is not large enough to hold one 527 * block we must allocate a temporary buffer. 528 */ 529 tmp = malloc(RPMB_DATA_SIZE); 530 if (!tmp) 531 return TEE_ERROR_OUT_OF_MEMORY; 532 res = decrypt_block(tmp, frm->data, blk_idx, fek, uuid); 533 if (res == TEE_SUCCESS) 534 memcpy(out, tmp + offset, size); 535 free(tmp); 536 } else { 537 res = decrypt_block(out, frm->data, blk_idx, fek, uuid); 538 } 539 } 540 541 return res; 542 } 543 544 static TEE_Result tee_rpmb_req_pack(struct rpmb_req *req, 545 struct rpmb_raw_data *rawdata, 546 uint16_t nbr_frms, uint16_t dev_id, 547 const uint8_t *fek, const TEE_UUID *uuid) 548 { 549 TEE_Result res = TEE_ERROR_GENERIC; 550 int i; 551 struct rpmb_data_frame *datafrm; 552 553 if (!req || !rawdata || !nbr_frms) 554 return TEE_ERROR_BAD_PARAMETERS; 555 556 /* 557 * Check write blockcount is not bigger than reliable write 558 * blockcount. 559 */ 560 if ((rawdata->msg_type == RPMB_MSG_TYPE_REQ_AUTH_DATA_WRITE) && 561 (nbr_frms > rpmb_ctx->rel_wr_blkcnt)) { 562 DMSG("wr_blkcnt(%d) > rel_wr_blkcnt(%d)", nbr_frms, 563 rpmb_ctx->rel_wr_blkcnt); 564 return TEE_ERROR_GENERIC; 565 } 566 567 req->cmd = RPMB_CMD_DATA_REQ; 568 req->dev_id = dev_id; 569 570 /* Allocate memory for construct all data packets and calculate MAC. */ 571 datafrm = calloc(nbr_frms, RPMB_DATA_FRAME_SIZE); 572 if (!datafrm) 573 return TEE_ERROR_OUT_OF_MEMORY; 574 575 for (i = 0; i < nbr_frms; i++) { 576 u16_to_bytes(rawdata->msg_type, datafrm[i].msg_type); 577 578 if (rawdata->block_count) 579 u16_to_bytes(*rawdata->block_count, 580 datafrm[i].block_count); 581 582 if (rawdata->blk_idx) { 583 /* Check the block index is within range. */ 584 if ((*rawdata->blk_idx + nbr_frms - 1) > 585 rpmb_ctx->max_blk_idx) { 586 res = TEE_ERROR_GENERIC; 587 goto func_exit; 588 } 589 u16_to_bytes(*rawdata->blk_idx, datafrm[i].address); 590 } 591 592 if (rawdata->write_counter) 593 u32_to_bytes(*rawdata->write_counter, 594 datafrm[i].write_counter); 595 596 if (rawdata->nonce) 597 memcpy(datafrm[i].nonce, rawdata->nonce, 598 RPMB_NONCE_SIZE); 599 600 if (rawdata->data) { 601 if (fek) { 602 res = encrypt_block(datafrm[i].data, 603 rawdata->data + 604 (i * RPMB_DATA_SIZE), 605 *rawdata->blk_idx + i, 606 fek, uuid); 607 if (res != TEE_SUCCESS) 608 goto func_exit; 609 } else { 610 memcpy(datafrm[i].data, 611 rawdata->data + (i * RPMB_DATA_SIZE), 612 RPMB_DATA_SIZE); 613 } 614 } 615 } 616 617 if (rawdata->key_mac) { 618 if (rawdata->msg_type == RPMB_MSG_TYPE_REQ_AUTH_DATA_WRITE) { 619 res = 620 tee_rpmb_mac_calc(rawdata->key_mac, 621 RPMB_KEY_MAC_SIZE, rpmb_ctx->key, 622 RPMB_KEY_MAC_SIZE, datafrm, 623 nbr_frms); 624 if (res != TEE_SUCCESS) 625 goto func_exit; 626 } 627 memcpy(datafrm[nbr_frms - 1].key_mac, 628 rawdata->key_mac, RPMB_KEY_MAC_SIZE); 629 } 630 631 memcpy(TEE_RPMB_REQ_DATA(req), datafrm, 632 nbr_frms * RPMB_DATA_FRAME_SIZE); 633 634 #ifdef CFG_RPMB_FS_DEBUG_DATA 635 for (i = 0; i < nbr_frms; i++) { 636 DMSG("Dumping data frame %d:", i); 637 DHEXDUMP((uint8_t *)&datafrm[i] + RPMB_STUFF_DATA_SIZE, 638 512 - RPMB_STUFF_DATA_SIZE); 639 } 640 #endif 641 642 res = TEE_SUCCESS; 643 func_exit: 644 free(datafrm); 645 return res; 646 } 647 648 static TEE_Result data_cpy_mac_calc_1b(struct rpmb_raw_data *rawdata, 649 struct rpmb_data_frame *frm, 650 const uint8_t *fek, const TEE_UUID *uuid) 651 { 652 TEE_Result res; 653 uint8_t *data; 654 uint16_t idx; 655 656 if (rawdata->len + rawdata->byte_offset > RPMB_DATA_SIZE) 657 return TEE_ERROR_BAD_PARAMETERS; 658 659 res = tee_rpmb_mac_calc(rawdata->key_mac, RPMB_KEY_MAC_SIZE, 660 rpmb_ctx->key, RPMB_KEY_MAC_SIZE, frm, 1); 661 if (res != TEE_SUCCESS) 662 return res; 663 664 data = rawdata->data; 665 bytes_to_u16(frm->address, &idx); 666 667 res = decrypt(data, frm, rawdata->len, rawdata->byte_offset, idx, fek, 668 uuid); 669 return res; 670 } 671 672 static TEE_Result tee_rpmb_data_cpy_mac_calc(struct rpmb_data_frame *datafrm, 673 struct rpmb_raw_data *rawdata, 674 uint16_t nbr_frms, 675 struct rpmb_data_frame *lastfrm, 676 const uint8_t *fek, 677 const TEE_UUID *uuid) 678 { 679 TEE_Result res = TEE_ERROR_GENERIC; 680 int i; 681 void *ctx = NULL; 682 uint16_t offset; 683 uint32_t size; 684 uint8_t *data; 685 uint16_t start_idx; 686 struct rpmb_data_frame localfrm; 687 688 if (!datafrm || !rawdata || !nbr_frms || !lastfrm) 689 return TEE_ERROR_BAD_PARAMETERS; 690 691 if (nbr_frms == 1) 692 return data_cpy_mac_calc_1b(rawdata, lastfrm, fek, uuid); 693 694 /* nbr_frms > 1 */ 695 696 data = rawdata->data; 697 698 res = crypto_mac_alloc_ctx(&ctx, TEE_ALG_HMAC_SHA256); 699 if (res) 700 goto func_exit; 701 702 res = crypto_mac_init(ctx, rpmb_ctx->key, RPMB_KEY_MAC_SIZE); 703 if (res != TEE_SUCCESS) 704 goto func_exit; 705 706 /* 707 * Note: JEDEC JESD84-B51: "In every packet the address is the start 708 * address of the full access (not address of the individual half a 709 * sector)" 710 */ 711 bytes_to_u16(lastfrm->address, &start_idx); 712 713 for (i = 0; i < (nbr_frms - 1); i++) { 714 715 /* 716 * By working on a local copy of the RPMB frame, we ensure that 717 * the data can not be modified after the MAC is computed but 718 * before the payload is decrypted/copied to the output buffer. 719 */ 720 memcpy(&localfrm, &datafrm[i], RPMB_DATA_FRAME_SIZE); 721 722 res = crypto_mac_update(ctx, localfrm.data, 723 RPMB_MAC_PROTECT_DATA_SIZE); 724 if (res != TEE_SUCCESS) 725 goto func_exit; 726 727 if (i == 0) { 728 /* First block */ 729 offset = rawdata->byte_offset; 730 size = RPMB_DATA_SIZE - offset; 731 } else { 732 /* Middle blocks */ 733 size = RPMB_DATA_SIZE; 734 offset = 0; 735 } 736 737 res = decrypt(data, &localfrm, size, offset, start_idx + i, 738 fek, uuid); 739 if (res != TEE_SUCCESS) 740 goto func_exit; 741 742 data += size; 743 } 744 745 /* Last block */ 746 size = (rawdata->len + rawdata->byte_offset) % RPMB_DATA_SIZE; 747 if (size == 0) 748 size = RPMB_DATA_SIZE; 749 res = decrypt(data, lastfrm, size, 0, start_idx + nbr_frms - 1, fek, 750 uuid); 751 if (res != TEE_SUCCESS) 752 goto func_exit; 753 754 /* Update MAC against the last block */ 755 res = crypto_mac_update(ctx, lastfrm->data, RPMB_MAC_PROTECT_DATA_SIZE); 756 if (res != TEE_SUCCESS) 757 goto func_exit; 758 759 res = crypto_mac_final(ctx, rawdata->key_mac, RPMB_KEY_MAC_SIZE); 760 if (res != TEE_SUCCESS) 761 goto func_exit; 762 763 res = TEE_SUCCESS; 764 765 func_exit: 766 crypto_mac_free_ctx(ctx); 767 return res; 768 } 769 770 static TEE_Result tee_rpmb_resp_unpack_verify(struct rpmb_data_frame *datafrm, 771 struct rpmb_raw_data *rawdata, 772 uint16_t nbr_frms, 773 const uint8_t *fek, 774 const TEE_UUID *uuid) 775 { 776 TEE_Result res = TEE_ERROR_GENERIC; 777 uint16_t msg_type; 778 uint32_t wr_cnt; 779 uint16_t blk_idx; 780 uint8_t op_result; 781 struct rpmb_data_frame lastfrm; 782 783 if (!datafrm || !rawdata || !nbr_frms) 784 return TEE_ERROR_BAD_PARAMETERS; 785 786 #ifdef CFG_RPMB_FS_DEBUG_DATA 787 for (uint32_t i = 0; i < nbr_frms; i++) { 788 DMSG("Dumping data frame %d:", i); 789 DHEXDUMP((uint8_t *)&datafrm[i] + RPMB_STUFF_DATA_SIZE, 790 512 - RPMB_STUFF_DATA_SIZE); 791 } 792 #endif 793 794 /* Make sure the last data packet can't be modified once verified */ 795 memcpy(&lastfrm, &datafrm[nbr_frms - 1], RPMB_DATA_FRAME_SIZE); 796 797 /* Handle operation result and translate to TEEC error code. */ 798 get_op_result_bits(lastfrm.op_result, &op_result); 799 if (op_result == RPMB_RESULT_AUTH_KEY_NOT_PROGRAMMED) 800 return TEE_ERROR_ITEM_NOT_FOUND; 801 if (op_result != RPMB_RESULT_OK) 802 return TEE_ERROR_GENERIC; 803 804 /* Check the response msg_type. */ 805 bytes_to_u16(lastfrm.msg_type, &msg_type); 806 if (msg_type != rawdata->msg_type) { 807 DMSG("Unexpected msg_type (0x%04x != 0x%04x)", msg_type, 808 rawdata->msg_type); 809 return TEE_ERROR_GENERIC; 810 } 811 812 if (rawdata->blk_idx) { 813 bytes_to_u16(lastfrm.address, &blk_idx); 814 if (blk_idx != *rawdata->blk_idx) { 815 DMSG("Unexpected block index"); 816 return TEE_ERROR_GENERIC; 817 } 818 } 819 820 if (rawdata->write_counter) { 821 wr_cnt = *rawdata->write_counter; 822 bytes_to_u32(lastfrm.write_counter, rawdata->write_counter); 823 if (msg_type == RPMB_MSG_TYPE_RESP_AUTH_DATA_WRITE) { 824 /* Verify the write counter is incremented by 1 */ 825 if (*rawdata->write_counter != wr_cnt + 1) { 826 DMSG("Counter mismatched (0x%04x/0x%04x)", 827 *rawdata->write_counter, wr_cnt + 1); 828 return TEE_ERROR_SECURITY; 829 } 830 rpmb_ctx->wr_cnt++; 831 } 832 } 833 834 if (rawdata->nonce) { 835 if (buf_compare_ct(rawdata->nonce, lastfrm.nonce, 836 RPMB_NONCE_SIZE) != 0) { 837 DMSG("Nonce mismatched"); 838 return TEE_ERROR_SECURITY; 839 } 840 } 841 842 if (rawdata->key_mac) { 843 if (msg_type == RPMB_MSG_TYPE_RESP_AUTH_DATA_READ) { 844 if (!rawdata->data) 845 return TEE_ERROR_GENERIC; 846 847 res = tee_rpmb_data_cpy_mac_calc(datafrm, rawdata, 848 nbr_frms, &lastfrm, 849 fek, uuid); 850 851 if (res != TEE_SUCCESS) 852 return res; 853 } else { 854 /* 855 * There should be only one data frame for 856 * other msg types. 857 */ 858 if (nbr_frms != 1) 859 return TEE_ERROR_GENERIC; 860 861 res = tee_rpmb_mac_calc(rawdata->key_mac, 862 RPMB_KEY_MAC_SIZE, 863 rpmb_ctx->key, 864 RPMB_KEY_MAC_SIZE, 865 &lastfrm, 1); 866 867 if (res != TEE_SUCCESS) 868 return res; 869 } 870 871 if (consttime_memcmp(rawdata->key_mac, 872 (datafrm + nbr_frms - 1)->key_mac, 873 RPMB_KEY_MAC_SIZE) != 0) { 874 DMSG("MAC mismatched:"); 875 #ifdef CFG_RPMB_FS_DEBUG_DATA 876 DHEXDUMP((uint8_t *)rawdata->key_mac, 32); 877 #endif 878 return TEE_ERROR_SECURITY; 879 } 880 } 881 882 return TEE_SUCCESS; 883 } 884 885 static TEE_Result tee_rpmb_get_dev_info(uint16_t dev_id, 886 struct rpmb_dev_info *dev_info) 887 { 888 TEE_Result res = TEE_ERROR_GENERIC; 889 struct tee_rpmb_mem mem; 890 struct rpmb_dev_info *di; 891 struct rpmb_req *req = NULL; 892 uint8_t *resp = NULL; 893 uint32_t req_size; 894 uint32_t resp_size; 895 896 if (!dev_info) 897 return TEE_ERROR_BAD_PARAMETERS; 898 899 req_size = sizeof(struct rpmb_req); 900 resp_size = sizeof(struct rpmb_dev_info); 901 res = tee_rpmb_alloc(req_size, resp_size, &mem, 902 (void *)&req, (void *)&resp); 903 if (res != TEE_SUCCESS) 904 goto func_exit; 905 906 req->cmd = RPMB_CMD_GET_DEV_INFO; 907 req->dev_id = dev_id; 908 909 di = (struct rpmb_dev_info *)resp; 910 di->ret_code = RPMB_CMD_GET_DEV_INFO_RET_ERROR; 911 912 res = tee_rpmb_invoke(&mem); 913 if (res != TEE_SUCCESS) 914 goto func_exit; 915 916 if (di->ret_code != RPMB_CMD_GET_DEV_INFO_RET_OK) { 917 res = TEE_ERROR_GENERIC; 918 goto func_exit; 919 } 920 921 memcpy((uint8_t *)dev_info, resp, sizeof(struct rpmb_dev_info)); 922 923 #ifdef CFG_RPMB_FS_DEBUG_DATA 924 DMSG("Dumping dev_info:"); 925 DHEXDUMP((uint8_t *)dev_info, sizeof(struct rpmb_dev_info)); 926 #endif 927 928 res = TEE_SUCCESS; 929 930 func_exit: 931 tee_rpmb_free(&mem); 932 return res; 933 } 934 935 static TEE_Result tee_rpmb_init_read_wr_cnt(uint16_t dev_id, 936 uint32_t *wr_cnt, 937 uint16_t *op_result) 938 { 939 TEE_Result res = TEE_ERROR_GENERIC; 940 struct tee_rpmb_mem mem; 941 uint16_t msg_type; 942 uint8_t nonce[RPMB_NONCE_SIZE]; 943 uint8_t hmac[RPMB_KEY_MAC_SIZE]; 944 struct rpmb_req *req = NULL; 945 struct rpmb_data_frame *resp = NULL; 946 struct rpmb_raw_data rawdata; 947 uint32_t req_size; 948 uint32_t resp_size; 949 950 if (!wr_cnt) 951 return TEE_ERROR_BAD_PARAMETERS; 952 953 req_size = sizeof(struct rpmb_req) + RPMB_DATA_FRAME_SIZE; 954 resp_size = RPMB_DATA_FRAME_SIZE; 955 res = tee_rpmb_alloc(req_size, resp_size, &mem, 956 (void *)&req, (void *)&resp); 957 if (res != TEE_SUCCESS) 958 goto func_exit; 959 960 res = crypto_rng_read(nonce, RPMB_NONCE_SIZE); 961 if (res != TEE_SUCCESS) 962 goto func_exit; 963 964 msg_type = RPMB_MSG_TYPE_REQ_WRITE_COUNTER_VAL_READ; 965 966 memset(&rawdata, 0x00, sizeof(struct rpmb_raw_data)); 967 rawdata.msg_type = msg_type; 968 rawdata.nonce = nonce; 969 970 res = tee_rpmb_req_pack(req, &rawdata, 1, dev_id, NULL, NULL); 971 if (res != TEE_SUCCESS) 972 goto func_exit; 973 974 res = tee_rpmb_invoke(&mem); 975 if (res != TEE_SUCCESS) 976 goto func_exit; 977 978 msg_type = RPMB_MSG_TYPE_RESP_WRITE_COUNTER_VAL_READ; 979 980 memset(&rawdata, 0x00, sizeof(struct rpmb_raw_data)); 981 rawdata.msg_type = msg_type; 982 rawdata.op_result = op_result; 983 rawdata.write_counter = wr_cnt; 984 rawdata.nonce = nonce; 985 rawdata.key_mac = hmac; 986 987 res = tee_rpmb_resp_unpack_verify(resp, &rawdata, 1, NULL, NULL); 988 if (res != TEE_SUCCESS) 989 goto func_exit; 990 991 res = TEE_SUCCESS; 992 993 func_exit: 994 tee_rpmb_free(&mem); 995 return res; 996 } 997 998 static TEE_Result tee_rpmb_verify_key_sync_counter(uint16_t dev_id) 999 { 1000 uint16_t op_result = 0; 1001 TEE_Result res = TEE_ERROR_GENERIC; 1002 1003 res = tee_rpmb_init_read_wr_cnt(dev_id, &rpmb_ctx->wr_cnt, 1004 &op_result); 1005 1006 if (res == TEE_SUCCESS) { 1007 rpmb_ctx->key_verified = true; 1008 rpmb_ctx->wr_cnt_synced = true; 1009 } else 1010 EMSG("Verify key returning 0x%x", res); 1011 return res; 1012 } 1013 1014 #ifdef CFG_RPMB_WRITE_KEY 1015 static TEE_Result tee_rpmb_write_key(uint16_t dev_id) 1016 { 1017 TEE_Result res = TEE_ERROR_GENERIC; 1018 struct tee_rpmb_mem mem = { 0 }; 1019 uint16_t msg_type; 1020 struct rpmb_req *req = NULL; 1021 struct rpmb_data_frame *resp = NULL; 1022 struct rpmb_raw_data rawdata; 1023 uint32_t req_size; 1024 uint32_t resp_size; 1025 1026 req_size = sizeof(struct rpmb_req) + RPMB_DATA_FRAME_SIZE; 1027 resp_size = RPMB_DATA_FRAME_SIZE; 1028 res = tee_rpmb_alloc(req_size, resp_size, &mem, 1029 (void *)&req, (void *)&resp); 1030 if (res != TEE_SUCCESS) 1031 goto func_exit; 1032 1033 msg_type = RPMB_MSG_TYPE_REQ_AUTH_KEY_PROGRAM; 1034 1035 memset(&rawdata, 0x00, sizeof(struct rpmb_raw_data)); 1036 rawdata.msg_type = msg_type; 1037 rawdata.key_mac = rpmb_ctx->key; 1038 1039 res = tee_rpmb_req_pack(req, &rawdata, 1, dev_id, NULL, NULL); 1040 if (res != TEE_SUCCESS) 1041 goto func_exit; 1042 1043 res = tee_rpmb_invoke(&mem); 1044 if (res != TEE_SUCCESS) 1045 goto func_exit; 1046 1047 msg_type = RPMB_MSG_TYPE_RESP_AUTH_KEY_PROGRAM; 1048 1049 memset(&rawdata, 0x00, sizeof(struct rpmb_raw_data)); 1050 rawdata.msg_type = msg_type; 1051 1052 res = tee_rpmb_resp_unpack_verify(resp, &rawdata, 1, NULL, NULL); 1053 if (res != TEE_SUCCESS) 1054 goto func_exit; 1055 1056 res = TEE_SUCCESS; 1057 1058 func_exit: 1059 tee_rpmb_free(&mem); 1060 return res; 1061 } 1062 1063 static TEE_Result tee_rpmb_write_and_verify_key(uint16_t dev_id) 1064 { 1065 TEE_Result res; 1066 1067 if (!plat_rpmb_key_is_ready()) { 1068 DMSG("RPMB INIT: platform indicates RPMB key is not ready"); 1069 return TEE_ERROR_BAD_STATE; 1070 } 1071 1072 DMSG("RPMB INIT: Writing Key value:"); 1073 DHEXDUMP(rpmb_ctx->key, RPMB_KEY_MAC_SIZE); 1074 1075 res = tee_rpmb_write_key(dev_id); 1076 if (res == TEE_SUCCESS) { 1077 DMSG("RPMB INIT: Verifying Key"); 1078 res = tee_rpmb_verify_key_sync_counter(dev_id); 1079 } 1080 return res; 1081 } 1082 #else 1083 static TEE_Result tee_rpmb_write_and_verify_key(uint16_t dev_id __unused) 1084 { 1085 DMSG("RPMB INIT: CFG_RPMB_WRITE_KEY is not set"); 1086 return TEE_ERROR_BAD_STATE; 1087 } 1088 #endif 1089 1090 /* This function must never return TEE_SUCCESS if rpmb_ctx == NULL */ 1091 static TEE_Result tee_rpmb_init(uint16_t dev_id) 1092 { 1093 TEE_Result res = TEE_SUCCESS; 1094 struct rpmb_dev_info dev_info; 1095 uint32_t nblocks = 0; 1096 1097 if (rpmb_dead) 1098 return TEE_ERROR_COMMUNICATION; 1099 1100 if (!rpmb_ctx) { 1101 rpmb_ctx = calloc(1, sizeof(struct tee_rpmb_ctx)); 1102 if (!rpmb_ctx) 1103 return TEE_ERROR_OUT_OF_MEMORY; 1104 } else if (rpmb_ctx->dev_id != dev_id) { 1105 memset(rpmb_ctx, 0x00, sizeof(struct tee_rpmb_ctx)); 1106 } 1107 1108 rpmb_ctx->dev_id = dev_id; 1109 1110 if (!rpmb_ctx->dev_info_synced) { 1111 DMSG("RPMB: Syncing device information"); 1112 1113 dev_info.rpmb_size_mult = 0; 1114 dev_info.rel_wr_sec_c = 0; 1115 res = tee_rpmb_get_dev_info(dev_id, &dev_info); 1116 if (res != TEE_SUCCESS) 1117 goto func_exit; 1118 1119 DMSG("RPMB: RPMB size is %d*128 KB", dev_info.rpmb_size_mult); 1120 DMSG("RPMB: Reliable Write Sector Count is %d", 1121 dev_info.rel_wr_sec_c); 1122 1123 if (dev_info.rpmb_size_mult == 0) { 1124 res = TEE_ERROR_GENERIC; 1125 goto func_exit; 1126 } 1127 1128 if (MUL_OVERFLOW(dev_info.rpmb_size_mult, 1129 RPMB_SIZE_SINGLE / RPMB_DATA_SIZE, &nblocks) || 1130 SUB_OVERFLOW(nblocks, 1, &rpmb_ctx->max_blk_idx)) { 1131 res = TEE_ERROR_BAD_PARAMETERS; 1132 goto func_exit; 1133 } 1134 1135 memcpy(rpmb_ctx->cid, dev_info.cid, RPMB_EMMC_CID_SIZE); 1136 1137 #ifdef RPMB_DRIVER_MULTIPLE_WRITE_FIXED 1138 rpmb_ctx->rel_wr_blkcnt = dev_info.rel_wr_sec_c * 2; 1139 #else 1140 rpmb_ctx->rel_wr_blkcnt = 1; 1141 #endif 1142 1143 rpmb_ctx->dev_info_synced = true; 1144 } 1145 1146 if (!rpmb_ctx->key_derived) { 1147 DMSG("RPMB INIT: Deriving key"); 1148 1149 res = tee_rpmb_key_gen(dev_id, rpmb_ctx->key, 1150 RPMB_KEY_MAC_SIZE); 1151 if (res != TEE_SUCCESS) { 1152 EMSG("RPMB INIT: Deriving key failed with error 0x%x", 1153 res); 1154 goto func_exit; 1155 } 1156 1157 rpmb_ctx->key_derived = true; 1158 } 1159 1160 /* Perform a write counter read to verify if the key is ok. */ 1161 if (!rpmb_ctx->wr_cnt_synced || !rpmb_ctx->key_verified) { 1162 DMSG("RPMB INIT: Verifying Key"); 1163 1164 res = tee_rpmb_verify_key_sync_counter(dev_id); 1165 if (res == TEE_ERROR_ITEM_NOT_FOUND && 1166 !rpmb_ctx->key_verified) { 1167 /* 1168 * Need to write the key here and verify it. 1169 */ 1170 DMSG("RPMB INIT: Auth key not yet written"); 1171 res = tee_rpmb_write_and_verify_key(dev_id); 1172 } else if (res != TEE_SUCCESS) { 1173 EMSG("Verify key failed!"); 1174 EMSG("Make sure key here matches device key"); 1175 } 1176 } 1177 1178 func_exit: 1179 return res; 1180 } 1181 1182 /* 1183 * Read RPMB data in bytes. 1184 * 1185 * @dev_id Device ID of the eMMC device. 1186 * @addr Byte address of data. 1187 * @data Pointer to the data. 1188 * @len Size of data in bytes. 1189 * @fek Encrypted File Encryption Key or NULL. 1190 */ 1191 static TEE_Result tee_rpmb_read(uint16_t dev_id, uint32_t addr, uint8_t *data, 1192 uint32_t len, const uint8_t *fek, 1193 const TEE_UUID *uuid) 1194 { 1195 TEE_Result res = TEE_ERROR_GENERIC; 1196 struct tee_rpmb_mem mem = { 0 }; 1197 uint16_t msg_type; 1198 uint8_t nonce[RPMB_NONCE_SIZE]; 1199 uint8_t hmac[RPMB_KEY_MAC_SIZE]; 1200 struct rpmb_req *req = NULL; 1201 struct rpmb_data_frame *resp = NULL; 1202 struct rpmb_raw_data rawdata; 1203 uint32_t req_size; 1204 uint32_t resp_size; 1205 uint16_t blk_idx; 1206 uint16_t blkcnt; 1207 uint8_t byte_offset; 1208 1209 if (!data || !len) 1210 return TEE_ERROR_BAD_PARAMETERS; 1211 1212 blk_idx = addr / RPMB_DATA_SIZE; 1213 byte_offset = addr % RPMB_DATA_SIZE; 1214 1215 if (len + byte_offset + RPMB_DATA_SIZE < RPMB_DATA_SIZE) { 1216 /* Overflow */ 1217 return TEE_ERROR_BAD_PARAMETERS; 1218 } 1219 blkcnt = 1220 ROUNDUP(len + byte_offset, RPMB_DATA_SIZE) / RPMB_DATA_SIZE; 1221 res = tee_rpmb_init(dev_id); 1222 if (res != TEE_SUCCESS) 1223 goto func_exit; 1224 1225 req_size = sizeof(struct rpmb_req) + RPMB_DATA_FRAME_SIZE; 1226 resp_size = RPMB_DATA_FRAME_SIZE * blkcnt; 1227 res = tee_rpmb_alloc(req_size, resp_size, &mem, 1228 (void *)&req, (void *)&resp); 1229 if (res != TEE_SUCCESS) 1230 goto func_exit; 1231 1232 msg_type = RPMB_MSG_TYPE_REQ_AUTH_DATA_READ; 1233 res = crypto_rng_read(nonce, RPMB_NONCE_SIZE); 1234 if (res != TEE_SUCCESS) 1235 goto func_exit; 1236 1237 memset(&rawdata, 0x00, sizeof(struct rpmb_raw_data)); 1238 rawdata.msg_type = msg_type; 1239 rawdata.nonce = nonce; 1240 rawdata.blk_idx = &blk_idx; 1241 res = tee_rpmb_req_pack(req, &rawdata, 1, dev_id, NULL, NULL); 1242 if (res != TEE_SUCCESS) 1243 goto func_exit; 1244 1245 req->block_count = blkcnt; 1246 1247 DMSG("Read %u block%s at index %u", blkcnt, ((blkcnt > 1) ? "s" : ""), 1248 blk_idx); 1249 1250 res = tee_rpmb_invoke(&mem); 1251 if (res != TEE_SUCCESS) 1252 goto func_exit; 1253 1254 msg_type = RPMB_MSG_TYPE_RESP_AUTH_DATA_READ; 1255 1256 memset(&rawdata, 0x00, sizeof(struct rpmb_raw_data)); 1257 rawdata.msg_type = msg_type; 1258 rawdata.block_count = &blkcnt; 1259 rawdata.blk_idx = &blk_idx; 1260 rawdata.nonce = nonce; 1261 rawdata.key_mac = hmac; 1262 rawdata.data = data; 1263 1264 rawdata.len = len; 1265 rawdata.byte_offset = byte_offset; 1266 1267 res = tee_rpmb_resp_unpack_verify(resp, &rawdata, blkcnt, fek, uuid); 1268 if (res != TEE_SUCCESS) 1269 goto func_exit; 1270 1271 res = TEE_SUCCESS; 1272 1273 func_exit: 1274 tee_rpmb_free(&mem); 1275 return res; 1276 } 1277 1278 static TEE_Result write_req(uint16_t dev_id, uint16_t blk_idx, 1279 const void *data_blks, uint16_t blkcnt, 1280 const uint8_t *fek, const TEE_UUID *uuid, 1281 struct tee_rpmb_mem *mem, void *req, void *resp) 1282 { 1283 TEE_Result res = TEE_SUCCESS; 1284 uint8_t hmac[RPMB_KEY_MAC_SIZE] = { }; 1285 uint32_t wr_cnt = rpmb_ctx->wr_cnt; 1286 struct rpmb_raw_data rawdata = { }; 1287 size_t retry_count = 0; 1288 1289 assert(mem->req_size <= 1290 sizeof(struct rpmb_req) + blkcnt * RPMB_DATA_FRAME_SIZE); 1291 assert(mem->resp_size <= RPMB_DATA_FRAME_SIZE); 1292 1293 while (true) { 1294 memset(req, 0, mem->req_size); 1295 memset(resp, 0, mem->resp_size); 1296 1297 memset(&rawdata, 0, sizeof(struct rpmb_raw_data)); 1298 rawdata.msg_type = RPMB_MSG_TYPE_REQ_AUTH_DATA_WRITE; 1299 rawdata.block_count = &blkcnt; 1300 rawdata.blk_idx = &blk_idx; 1301 rawdata.write_counter = &wr_cnt; 1302 rawdata.key_mac = hmac; 1303 rawdata.data = (uint8_t *)data_blks; 1304 1305 res = tee_rpmb_req_pack(req, &rawdata, blkcnt, dev_id, fek, 1306 uuid); 1307 if (res) { 1308 /* 1309 * If we haven't tried to send a request yet we can 1310 * allow a failure here since there's no chance of 1311 * an intercepted request with a valid write 1312 * counter. 1313 */ 1314 if (!retry_count) 1315 return res; 1316 1317 retry_count++; 1318 if (retry_count >= RPMB_MAX_RETRIES) 1319 goto out_of_retries; 1320 1321 DMSG("Request pack failed, retrying %zu", retry_count); 1322 continue; 1323 } 1324 1325 res = tee_rpmb_invoke(mem); 1326 if (res != TEE_SUCCESS) { 1327 retry_count++; 1328 if (retry_count >= RPMB_MAX_RETRIES) 1329 goto out_of_retries; 1330 /* 1331 * To force wr_cnt sync next time, as it might get 1332 * out of sync due to inconsistent operation result! 1333 */ 1334 rpmb_ctx->wr_cnt_synced = false; 1335 DMSG("Write invoke failed, retrying %zu", retry_count); 1336 continue; 1337 } 1338 1339 memset(&rawdata, 0, sizeof(struct rpmb_raw_data)); 1340 rawdata.msg_type = RPMB_MSG_TYPE_RESP_AUTH_DATA_WRITE; 1341 rawdata.block_count = &blkcnt; 1342 rawdata.blk_idx = &blk_idx; 1343 rawdata.write_counter = &wr_cnt; 1344 rawdata.key_mac = hmac; 1345 1346 res = tee_rpmb_resp_unpack_verify(resp, &rawdata, 1, NULL, 1347 NULL); 1348 if (res != TEE_SUCCESS) { 1349 retry_count++; 1350 if (retry_count >= RPMB_MAX_RETRIES) 1351 goto out_of_retries; 1352 /* 1353 * To force wr_cnt sync next time, as it might get 1354 * out of sync due to inconsistent operation result! 1355 */ 1356 rpmb_ctx->wr_cnt_synced = false; 1357 DMSG("Write resp unpack verify failed, retrying %zu", 1358 retry_count); 1359 continue; 1360 } 1361 1362 return TEE_SUCCESS; 1363 } 1364 1365 out_of_retries: 1366 rpmb_dead = true; 1367 /* 1368 * We're using this error code to cause an eventuall calling TA to 1369 * panic since we don't know if the data to be written has been 1370 * committed to storage or not. 1371 */ 1372 return TEE_ERROR_COMMUNICATION; 1373 } 1374 1375 static TEE_Result tee_rpmb_write_blk(uint16_t dev_id, uint16_t blk_idx, 1376 const uint8_t *data_blks, uint16_t blkcnt, 1377 const uint8_t *fek, const TEE_UUID *uuid) 1378 { 1379 TEE_Result res; 1380 struct tee_rpmb_mem mem; 1381 struct rpmb_req *req = NULL; 1382 struct rpmb_data_frame *resp = NULL; 1383 uint32_t req_size; 1384 uint32_t resp_size; 1385 uint32_t nbr_writes; 1386 uint16_t tmp_blkcnt; 1387 uint16_t tmp_blk_idx; 1388 uint16_t i; 1389 1390 DMSG("Write %u block%s at index %u", blkcnt, ((blkcnt > 1) ? "s" : ""), 1391 blk_idx); 1392 1393 if (!data_blks || !blkcnt) 1394 return TEE_ERROR_BAD_PARAMETERS; 1395 1396 res = tee_rpmb_init(dev_id); 1397 if (res != TEE_SUCCESS) 1398 return res; 1399 1400 /* 1401 * We need to split data when block count 1402 * is bigger than reliable block write count. 1403 */ 1404 if (blkcnt < rpmb_ctx->rel_wr_blkcnt) 1405 req_size = sizeof(struct rpmb_req) + 1406 RPMB_DATA_FRAME_SIZE * blkcnt; 1407 else 1408 req_size = sizeof(struct rpmb_req) + 1409 RPMB_DATA_FRAME_SIZE * rpmb_ctx->rel_wr_blkcnt; 1410 1411 resp_size = RPMB_DATA_FRAME_SIZE; 1412 res = tee_rpmb_alloc(req_size, resp_size, &mem, 1413 (void *)&req, (void *)&resp); 1414 if (res != TEE_SUCCESS) 1415 return res; 1416 1417 nbr_writes = blkcnt / rpmb_ctx->rel_wr_blkcnt; 1418 if (blkcnt % rpmb_ctx->rel_wr_blkcnt > 0) 1419 nbr_writes += 1; 1420 1421 tmp_blkcnt = rpmb_ctx->rel_wr_blkcnt; 1422 tmp_blk_idx = blk_idx; 1423 for (i = 0; i < nbr_writes; i++) { 1424 size_t offs = i * rpmb_ctx->rel_wr_blkcnt * RPMB_DATA_SIZE; 1425 1426 /* 1427 * To handle the last write of block count which is 1428 * equal or smaller than reliable write block count. 1429 */ 1430 if (i == nbr_writes - 1) 1431 tmp_blkcnt = blkcnt - rpmb_ctx->rel_wr_blkcnt * 1432 (nbr_writes - 1); 1433 1434 res = write_req(dev_id, tmp_blk_idx, data_blks + offs, 1435 tmp_blkcnt, fek, uuid, &mem, req, resp); 1436 if (res) 1437 goto out; 1438 1439 1440 tmp_blk_idx += tmp_blkcnt; 1441 } 1442 1443 out: 1444 tee_rpmb_free(&mem); 1445 return res; 1446 } 1447 1448 static bool tee_rpmb_write_is_atomic(uint16_t dev_id __unused, uint32_t addr, 1449 uint32_t len) 1450 { 1451 uint8_t byte_offset = addr % RPMB_DATA_SIZE; 1452 uint16_t blkcnt = ROUNDUP(len + byte_offset, 1453 RPMB_DATA_SIZE) / RPMB_DATA_SIZE; 1454 1455 return (blkcnt <= rpmb_ctx->rel_wr_blkcnt); 1456 } 1457 1458 /* 1459 * Write RPMB data in bytes. 1460 * 1461 * @dev_id Device ID of the eMMC device. 1462 * @addr Byte address of data. 1463 * @data Pointer to the data. 1464 * @len Size of data in bytes. 1465 * @fek Encrypted File Encryption Key or NULL. 1466 */ 1467 static TEE_Result tee_rpmb_write(uint16_t dev_id, uint32_t addr, 1468 const uint8_t *data, uint32_t len, 1469 const uint8_t *fek, const TEE_UUID *uuid) 1470 { 1471 TEE_Result res = TEE_ERROR_GENERIC; 1472 uint8_t *data_tmp = NULL; 1473 uint16_t blk_idx; 1474 uint16_t blkcnt; 1475 uint8_t byte_offset; 1476 1477 blk_idx = addr / RPMB_DATA_SIZE; 1478 byte_offset = addr % RPMB_DATA_SIZE; 1479 1480 blkcnt = 1481 ROUNDUP(len + byte_offset, RPMB_DATA_SIZE) / RPMB_DATA_SIZE; 1482 1483 if (byte_offset == 0 && (len % RPMB_DATA_SIZE) == 0) { 1484 res = tee_rpmb_write_blk(dev_id, blk_idx, data, blkcnt, fek, 1485 uuid); 1486 if (res != TEE_SUCCESS) 1487 goto func_exit; 1488 } else { 1489 data_tmp = calloc(blkcnt, RPMB_DATA_SIZE); 1490 if (!data_tmp) { 1491 res = TEE_ERROR_OUT_OF_MEMORY; 1492 goto func_exit; 1493 } 1494 1495 /* Read the complete blocks */ 1496 res = tee_rpmb_read(dev_id, blk_idx * RPMB_DATA_SIZE, data_tmp, 1497 blkcnt * RPMB_DATA_SIZE, fek, uuid); 1498 if (res != TEE_SUCCESS) 1499 goto func_exit; 1500 1501 /* Partial update of the data blocks */ 1502 memcpy(data_tmp + byte_offset, data, len); 1503 1504 res = tee_rpmb_write_blk(dev_id, blk_idx, data_tmp, blkcnt, 1505 fek, uuid); 1506 if (res != TEE_SUCCESS) 1507 goto func_exit; 1508 } 1509 1510 res = TEE_SUCCESS; 1511 1512 func_exit: 1513 free(data_tmp); 1514 return res; 1515 } 1516 1517 /* 1518 * Read the RPMB write counter. 1519 * 1520 * @dev_id Device ID of the eMMC device. 1521 * @counter Pointer to the counter. 1522 */ 1523 static TEE_Result tee_rpmb_get_write_counter(uint16_t dev_id, 1524 uint32_t *counter) 1525 { 1526 TEE_Result res = TEE_SUCCESS; 1527 1528 if (!counter) 1529 return TEE_ERROR_BAD_PARAMETERS; 1530 1531 if (rpmb_dead) 1532 return TEE_ERROR_COMMUNICATION; 1533 1534 if (!rpmb_ctx || !rpmb_ctx->wr_cnt_synced) { 1535 res = tee_rpmb_init(dev_id); 1536 if (res != TEE_SUCCESS) 1537 goto func_exit; 1538 } 1539 1540 *counter = rpmb_ctx->wr_cnt; 1541 1542 func_exit: 1543 return res; 1544 } 1545 1546 /* 1547 * Read the RPMB max block. 1548 * 1549 * @dev_id Device ID of the eMMC device. 1550 * @counter Pointer to receive the max block. 1551 */ 1552 static TEE_Result tee_rpmb_get_max_block(uint16_t dev_id, uint32_t *max_block) 1553 { 1554 TEE_Result res = TEE_SUCCESS; 1555 1556 if (!max_block) 1557 return TEE_ERROR_BAD_PARAMETERS; 1558 1559 if (rpmb_dead) 1560 return TEE_ERROR_COMMUNICATION; 1561 1562 if (!rpmb_ctx || !rpmb_ctx->dev_info_synced) { 1563 res = tee_rpmb_init(dev_id); 1564 if (res != TEE_SUCCESS) 1565 goto func_exit; 1566 } 1567 1568 *max_block = rpmb_ctx->max_blk_idx; 1569 1570 func_exit: 1571 return res; 1572 } 1573 1574 /* 1575 * End of lower interface to RPMB device 1576 */ 1577 1578 static TEE_Result get_fat_start_address(uint32_t *addr); 1579 static TEE_Result rpmb_fs_setup(void); 1580 1581 /** 1582 * fat_entry_dir_free: Free the FAT entry dir. 1583 */ 1584 static void fat_entry_dir_free(void) 1585 { 1586 if (fat_entry_dir) { 1587 free(fat_entry_dir->rpmb_fat_entry_buf); 1588 free(fat_entry_dir); 1589 fat_entry_dir = NULL; 1590 } 1591 } 1592 1593 /** 1594 * fat_entry_dir_init: Initialize the FAT FS entry buffer/cache 1595 * This function must be called before reading FAT FS entries using the 1596 * function fat_entry_dir_get_next. This initializes the buffer/cache with the 1597 * first FAT FS entries. 1598 */ 1599 static TEE_Result fat_entry_dir_init(void) 1600 { 1601 TEE_Result res = TEE_ERROR_GENERIC; 1602 struct rpmb_fat_entry *fe = NULL; 1603 uint32_t fat_address = 0; 1604 uint32_t num_elems_read = 0; 1605 1606 if (fat_entry_dir) 1607 return TEE_SUCCESS; 1608 1609 res = rpmb_fs_setup(); 1610 if (res) 1611 return res; 1612 1613 res = get_fat_start_address(&fat_address); 1614 if (res) 1615 return res; 1616 1617 fat_entry_dir = calloc(1, sizeof(struct rpmb_fat_entry_dir)); 1618 if (!fat_entry_dir) 1619 return TEE_ERROR_OUT_OF_MEMORY; 1620 1621 /* 1622 * If caching is enabled, read in up to the maximum cache size, but 1623 * never more than the single read in size. Otherwise, read in as many 1624 * entries fit into the temporary buffer. 1625 */ 1626 if (CFG_RPMB_FS_CACHE_ENTRIES) 1627 num_elems_read = MIN(CFG_RPMB_FS_CACHE_ENTRIES, 1628 CFG_RPMB_FS_RD_ENTRIES); 1629 else 1630 num_elems_read = CFG_RPMB_FS_RD_ENTRIES; 1631 1632 /* 1633 * Allocate memory for the FAT FS entries to read in. 1634 */ 1635 fe = calloc(num_elems_read, sizeof(struct rpmb_fat_entry)); 1636 if (!fe) { 1637 res = TEE_ERROR_OUT_OF_MEMORY; 1638 goto out; 1639 } 1640 1641 res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID, fat_address, (uint8_t *)fe, 1642 num_elems_read * sizeof(*fe), NULL, NULL); 1643 if (res) 1644 goto out; 1645 1646 fat_entry_dir->rpmb_fat_entry_buf = fe; 1647 1648 /* 1649 * We use this variable when getting next entries from the buffer/cache 1650 * to see whether we have to read in more entries from storage. 1651 */ 1652 fat_entry_dir->num_buffered = num_elems_read; 1653 1654 return TEE_SUCCESS; 1655 out: 1656 fat_entry_dir_free(); 1657 free(fe); 1658 return res; 1659 } 1660 1661 /** 1662 * fat_entry_dir_deinit: If caching is enabled, free the temporary buffer for 1663 * FAT FS entries in case the cache was too small. Keep the elements in the 1664 * cache. Reset the counter variables to start the next traversal from fresh 1665 * from the first cached entry. If caching is disabled, just free the 1666 * temporary buffer by calling fat_entry_dir_free and return. 1667 */ 1668 static void fat_entry_dir_deinit(void) 1669 { 1670 struct rpmb_fat_entry *fe = NULL; 1671 1672 if (!fat_entry_dir) 1673 return; 1674 1675 if (!CFG_RPMB_FS_CACHE_ENTRIES) { 1676 fat_entry_dir_free(); 1677 return; 1678 } 1679 1680 fe = fat_entry_dir->rpmb_fat_entry_buf; 1681 fat_entry_dir->idx_curr = 0; 1682 fat_entry_dir->num_total_read = 0; 1683 fat_entry_dir->last_reached = false; 1684 1685 if (fat_entry_dir->num_buffered > CFG_RPMB_FS_CACHE_ENTRIES) { 1686 fat_entry_dir->num_buffered = CFG_RPMB_FS_CACHE_ENTRIES; 1687 1688 fe = realloc(fe, fat_entry_dir->num_buffered * sizeof(*fe)); 1689 1690 /* 1691 * In case realloc fails, we are on the safe side if we destroy 1692 * the whole structure. Upon the next init, the cache has to be 1693 * re-established, but this case should not happen in practice. 1694 */ 1695 if (!fe) 1696 fat_entry_dir_free(); 1697 else 1698 fat_entry_dir->rpmb_fat_entry_buf = fe; 1699 } 1700 } 1701 1702 /** 1703 * fat_entry_dir_update: Updates a persisted FAT FS entry in the cache. 1704 * This function updates the FAT entry fat_entry that was written to address 1705 * fat_address onto RPMB storage in the cache. 1706 */ 1707 static TEE_Result __maybe_unused fat_entry_dir_update 1708 (struct rpmb_fat_entry *fat_entry, 1709 uint32_t fat_address) 1710 { 1711 uint32_t fat_entry_buf_idx = 0; 1712 /* Use a temp var to avoid compiler warning if caching disabled. */ 1713 uint32_t max_cache_entries = CFG_RPMB_FS_CACHE_ENTRIES; 1714 1715 assert(!((fat_address - RPMB_FS_FAT_START_ADDRESS) % 1716 sizeof(struct rpmb_fat_entry))); 1717 1718 /* Nothing to update if the cache is not initialized. */ 1719 if (!fat_entry_dir) 1720 return TEE_SUCCESS; 1721 1722 fat_entry_buf_idx = (fat_address - RPMB_FS_FAT_START_ADDRESS) / 1723 sizeof(struct rpmb_fat_entry); 1724 1725 /* Only need to write if index points to an entry in cache. */ 1726 if (fat_entry_buf_idx < fat_entry_dir->num_buffered && 1727 fat_entry_buf_idx < max_cache_entries) { 1728 memcpy(fat_entry_dir->rpmb_fat_entry_buf + fat_entry_buf_idx, 1729 fat_entry, sizeof(struct rpmb_fat_entry)); 1730 } 1731 1732 return TEE_SUCCESS; 1733 } 1734 1735 /** 1736 * fat_entry_dir_get_next: Get next FAT FS entry. 1737 * Read either from cache/buffer, or by reading from RPMB storage if the 1738 * elements in the buffer/cache are fully read. When reading in from RPMB 1739 * storage, the buffer is overwritten in case caching is disabled. 1740 * In case caching is enabled, the cache is either further filled, or a 1741 * temporary buffer populated if the cache is already full. 1742 * The FAT FS entry is written to fat_entry. The respective address in RPMB 1743 * storage is written to fat_address, if not NULL. When the last FAT FS entry 1744 * was previously read, the function indicates this case by writing a NULL 1745 * pointer to fat_entry. 1746 * Returns a value different TEE_SUCCESS if the next FAT FS entry could not be 1747 * retrieved. 1748 */ 1749 static TEE_Result fat_entry_dir_get_next(struct rpmb_fat_entry **fat_entry, 1750 uint32_t *fat_address) 1751 { 1752 TEE_Result res = TEE_ERROR_GENERIC; 1753 struct rpmb_fat_entry *fe = NULL; 1754 uint32_t num_elems_read = 0; 1755 uint32_t fat_address_local = 0; 1756 1757 assert(fat_entry_dir && fat_entry); 1758 1759 /* Don't read further if we previously read the last FAT FS entry. */ 1760 if (fat_entry_dir->last_reached) { 1761 *fat_entry = NULL; 1762 return TEE_SUCCESS; 1763 } 1764 1765 fe = fat_entry_dir->rpmb_fat_entry_buf; 1766 1767 /* Determine address of FAT FS entry in RPMB storage. */ 1768 fat_address_local = RPMB_FS_FAT_START_ADDRESS + 1769 (fat_entry_dir->num_total_read * 1770 sizeof(struct rpmb_fat_entry)); 1771 1772 /* 1773 * We've read all so-far buffered elements, so we need to 1774 * read in more entries from RPMB storage. 1775 */ 1776 if (fat_entry_dir->idx_curr >= fat_entry_dir->num_buffered) { 1777 /* 1778 * This is the case where we do not cache entries, so just read 1779 * in next set of FAT FS entries into the buffer. 1780 * Goto the end of the when statement if that is done. 1781 */ 1782 if (!CFG_RPMB_FS_CACHE_ENTRIES) { 1783 num_elems_read = CFG_RPMB_FS_RD_ENTRIES; 1784 fat_entry_dir->idx_curr = 0; 1785 1786 res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID, 1787 fat_address_local, (uint8_t *)fe, 1788 num_elems_read * sizeof(*fe), NULL, 1789 NULL); 1790 if (res) 1791 return res; 1792 goto post_read_in; 1793 } 1794 1795 /* 1796 * We cache FAT FS entries, and the buffer is not completely 1797 * filled. Further keep on extending the buffer up to its max 1798 * size by reading in from RPMB. 1799 */ 1800 if (fat_entry_dir->num_total_read < RPMB_BUF_MAX_ENTRIES) { 1801 /* 1802 * Read at most as many elements as fit in the buffer 1803 * and no more than the defined number of entries to 1804 * read in at once. 1805 */ 1806 num_elems_read = MIN(RPMB_BUF_MAX_ENTRIES - 1807 fat_entry_dir->num_total_read, 1808 (uint32_t)CFG_RPMB_FS_RD_ENTRIES); 1809 1810 /* 1811 * Expand the buffer to fit in the additional entries. 1812 */ 1813 fe = realloc(fe, 1814 (fat_entry_dir->num_buffered + 1815 num_elems_read) * sizeof(*fe)); 1816 if (!fe) 1817 return TEE_ERROR_OUT_OF_MEMORY; 1818 1819 fat_entry_dir->rpmb_fat_entry_buf = fe; 1820 1821 /* Read in to the next free slot in the buffer/cache. */ 1822 res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID, 1823 fat_address_local, 1824 (uint8_t *)(fe + 1825 fat_entry_dir->num_total_read), 1826 num_elems_read * sizeof(*fe), 1827 NULL, NULL); 1828 if (res) 1829 return res; 1830 1831 fat_entry_dir->num_buffered += num_elems_read; 1832 } else { 1833 /* 1834 * This happens when we have read as many elements as 1835 * can possibly fit into the buffer. 1836 * As the first part of the buffer serves as our cache, 1837 * we only overwrite the last part that serves as our 1838 * temporary buffer used to iteratively read in entries 1839 * when the cache is full. Read in the temporary buffer 1840 * maximum size. 1841 */ 1842 num_elems_read = CFG_RPMB_FS_RD_ENTRIES; 1843 /* Reset index to beginning of the temporary buffer. */ 1844 fat_entry_dir->idx_curr = CFG_RPMB_FS_CACHE_ENTRIES; 1845 1846 /* Read in elements after the end of the cache. */ 1847 res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID, 1848 fat_address_local, 1849 (uint8_t *)(fe + 1850 fat_entry_dir->idx_curr), 1851 num_elems_read * sizeof(*fe), 1852 NULL, NULL); 1853 if (res) 1854 return res; 1855 } 1856 } 1857 1858 post_read_in: 1859 if (fat_address) 1860 *fat_address = fat_address_local; 1861 1862 *fat_entry = fe + fat_entry_dir->idx_curr; 1863 1864 fat_entry_dir->idx_curr++; 1865 fat_entry_dir->num_total_read++; 1866 1867 /* 1868 * Indicate last entry was read. 1869 * Ensures we return a zero value for fat_entry on next invocation. 1870 */ 1871 if ((*fat_entry)->flags & FILE_IS_LAST_ENTRY) 1872 fat_entry_dir->last_reached = true; 1873 1874 return TEE_SUCCESS; 1875 } 1876 1877 #if (TRACE_LEVEL >= TRACE_FLOW) 1878 static void dump_fat(void) 1879 { 1880 TEE_Result res = TEE_ERROR_SECURITY; 1881 struct rpmb_fat_entry *fe = NULL; 1882 1883 if (!fs_par) 1884 return; 1885 1886 if (fat_entry_dir_init()) 1887 return; 1888 1889 while (true) { 1890 res = fat_entry_dir_get_next(&fe, NULL); 1891 if (res || !fe) 1892 break; 1893 1894 FMSG("flags %#"PRIx32", size %"PRIu32", address %#"PRIx32 1895 ", filename '%s'", 1896 fe->flags, fe->data_size, fe->start_address, fe->filename); 1897 } 1898 1899 fat_entry_dir_deinit(); 1900 } 1901 #else 1902 static void dump_fat(void) 1903 { 1904 } 1905 #endif 1906 1907 #if (TRACE_LEVEL >= TRACE_DEBUG) 1908 static void dump_fh(struct rpmb_file_handle *fh) 1909 { 1910 DMSG("fh->filename=%s", fh->filename); 1911 DMSG("fh->rpmb_fat_address=%u", fh->rpmb_fat_address); 1912 DMSG("fh->fat_entry.start_address=%u", fh->fat_entry.start_address); 1913 DMSG("fh->fat_entry.data_size=%u", fh->fat_entry.data_size); 1914 } 1915 #else 1916 static void dump_fh(struct rpmb_file_handle *fh __unused) 1917 { 1918 } 1919 #endif 1920 1921 static struct rpmb_file_handle *alloc_file_handle(struct tee_pobj *po, 1922 bool temporary) 1923 { 1924 struct rpmb_file_handle *fh = NULL; 1925 1926 fh = calloc(1, sizeof(struct rpmb_file_handle)); 1927 if (!fh) 1928 return NULL; 1929 1930 if (po) 1931 tee_svc_storage_create_filename(fh->filename, 1932 sizeof(fh->filename), po, 1933 temporary); 1934 1935 return fh; 1936 } 1937 1938 /** 1939 * write_fat_entry: Store info in a fat_entry to RPMB. 1940 */ 1941 static TEE_Result write_fat_entry(struct rpmb_file_handle *fh, 1942 bool update_write_counter) 1943 { 1944 TEE_Result res = TEE_ERROR_GENERIC; 1945 1946 /* Protect partition data. */ 1947 if (fh->rpmb_fat_address < sizeof(struct rpmb_fs_partition)) { 1948 res = TEE_ERROR_ACCESS_CONFLICT; 1949 goto out; 1950 } 1951 1952 if (fh->rpmb_fat_address % sizeof(struct rpmb_fat_entry) != 0) { 1953 res = TEE_ERROR_BAD_PARAMETERS; 1954 goto out; 1955 } 1956 1957 if (update_write_counter) { 1958 res = tee_rpmb_get_write_counter(CFG_RPMB_FS_DEV_ID, 1959 &fh->fat_entry.write_counter); 1960 if (res) 1961 goto out; 1962 } 1963 1964 res = tee_rpmb_write(CFG_RPMB_FS_DEV_ID, fh->rpmb_fat_address, 1965 (uint8_t *)&fh->fat_entry, 1966 sizeof(struct rpmb_fat_entry), NULL, NULL); 1967 1968 dump_fat(); 1969 1970 /* If caching enabled, update a successfully written entry in cache. */ 1971 if (CFG_RPMB_FS_CACHE_ENTRIES && !res) 1972 res = fat_entry_dir_update(&fh->fat_entry, 1973 fh->rpmb_fat_address); 1974 1975 out: 1976 return res; 1977 } 1978 1979 /** 1980 * rpmb_fs_setup: Setup RPMB FS. 1981 * Set initial partition and FS values and write to RPMB. 1982 * Store frequently used data in RAM. 1983 */ 1984 static TEE_Result rpmb_fs_setup(void) 1985 { 1986 TEE_Result res = TEE_ERROR_GENERIC; 1987 struct rpmb_fs_partition *partition_data = NULL; 1988 struct rpmb_file_handle *fh = NULL; 1989 uint32_t max_rpmb_block = 0; 1990 1991 if (fs_par) { 1992 res = TEE_SUCCESS; 1993 goto out; 1994 } 1995 1996 res = tee_rpmb_get_max_block(CFG_RPMB_FS_DEV_ID, &max_rpmb_block); 1997 if (res != TEE_SUCCESS) 1998 goto out; 1999 2000 /* 2001 * We're going to read a full block in order to have a full block 2002 * for the dummy write below. 2003 */ 2004 COMPILE_TIME_ASSERT(sizeof(struct rpmb_fs_partition) <= 2005 RPMB_DATA_SIZE); 2006 partition_data = calloc(1, RPMB_DATA_SIZE); 2007 if (!partition_data) { 2008 res = TEE_ERROR_OUT_OF_MEMORY; 2009 goto out; 2010 } 2011 2012 res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID, RPMB_STORAGE_START_ADDRESS, 2013 (uint8_t *)partition_data, RPMB_DATA_SIZE, 2014 NULL, NULL); 2015 if (res != TEE_SUCCESS) 2016 goto out; 2017 /* 2018 * Perform a write in order to increase the write counter. This 2019 * prevents late usage (replay attack) of a previously blocked 2020 * request with a valid write counter value. 2021 */ 2022 res = tee_rpmb_write(CFG_RPMB_FS_DEV_ID, RPMB_STORAGE_START_ADDRESS, 2023 (uint8_t *)partition_data, RPMB_DATA_SIZE, 2024 NULL, NULL); 2025 if (res != TEE_SUCCESS) 2026 goto out; 2027 /* 2028 * We're reading again in case a stale request was committed 2029 * instead of the one issued above. If this succeeds we're in sync 2030 * with the RPMB block since there are no other possible stale 2031 * blocks with valid write counters available. 2032 */ 2033 res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID, RPMB_STORAGE_START_ADDRESS, 2034 (uint8_t *)partition_data, 2035 sizeof(struct rpmb_fs_partition), NULL, NULL); 2036 if (res != TEE_SUCCESS) 2037 goto out; 2038 2039 #ifndef CFG_RPMB_RESET_FAT 2040 if (partition_data->rpmb_fs_magic == RPMB_FS_MAGIC) { 2041 if (partition_data->fs_version == FS_VERSION) { 2042 res = TEE_SUCCESS; 2043 goto store_fs_par; 2044 } else { 2045 EMSG("Wrong software is in use."); 2046 res = TEE_ERROR_ACCESS_DENIED; 2047 goto out; 2048 } 2049 } 2050 #else 2051 EMSG("**** Clearing Storage ****"); 2052 #endif 2053 2054 /* Setup new partition data. */ 2055 partition_data->rpmb_fs_magic = RPMB_FS_MAGIC; 2056 partition_data->fs_version = FS_VERSION; 2057 partition_data->fat_start_address = RPMB_FS_FAT_START_ADDRESS; 2058 2059 /* Initial FAT entry with FILE_IS_LAST_ENTRY flag set. */ 2060 fh = alloc_file_handle(NULL, false); 2061 if (!fh) { 2062 res = TEE_ERROR_OUT_OF_MEMORY; 2063 goto out; 2064 } 2065 fh->fat_entry.flags = FILE_IS_LAST_ENTRY; 2066 fh->rpmb_fat_address = partition_data->fat_start_address; 2067 2068 /* Write init FAT entry and partition data to RPMB. */ 2069 res = write_fat_entry(fh, true); 2070 if (res != TEE_SUCCESS) 2071 goto out; 2072 2073 res = 2074 tee_rpmb_get_write_counter(CFG_RPMB_FS_DEV_ID, 2075 &partition_data->write_counter); 2076 if (res != TEE_SUCCESS) 2077 goto out; 2078 res = tee_rpmb_write(CFG_RPMB_FS_DEV_ID, RPMB_STORAGE_START_ADDRESS, 2079 (uint8_t *)partition_data, 2080 sizeof(struct rpmb_fs_partition), NULL, NULL); 2081 2082 #ifndef CFG_RPMB_RESET_FAT 2083 store_fs_par: 2084 #endif 2085 2086 /* Store FAT start address. */ 2087 fs_par = calloc(1, sizeof(struct rpmb_fs_parameters)); 2088 if (!fs_par) { 2089 res = TEE_ERROR_OUT_OF_MEMORY; 2090 goto out; 2091 } 2092 2093 fs_par->fat_start_address = partition_data->fat_start_address; 2094 fs_par->max_rpmb_address = max_rpmb_block << RPMB_BLOCK_SIZE_SHIFT; 2095 2096 dump_fat(); 2097 2098 out: 2099 free(fh); 2100 free(partition_data); 2101 return res; 2102 } 2103 2104 /** 2105 * get_fat_start_address: 2106 * FAT start_address from fs_par. 2107 */ 2108 static TEE_Result get_fat_start_address(uint32_t *addr) 2109 { 2110 if (!fs_par) 2111 return TEE_ERROR_NO_DATA; 2112 2113 *addr = fs_par->fat_start_address; 2114 2115 return TEE_SUCCESS; 2116 } 2117 2118 /** 2119 * read_fat: Read FAT entries 2120 * Return matching FAT entry for read, rm rename and stat. 2121 * Build up memory pool and return matching entry for write operation. 2122 * "Last FAT entry" can be returned during write. 2123 */ 2124 static TEE_Result read_fat(struct rpmb_file_handle *fh, tee_mm_pool_t *p) 2125 { 2126 TEE_Result res = TEE_ERROR_GENERIC; 2127 tee_mm_entry_t *mm = NULL; 2128 struct rpmb_fat_entry *fe = NULL; 2129 uint32_t fat_address; 2130 bool entry_found = false; 2131 bool expand_fat = false; 2132 struct rpmb_file_handle last_fh; 2133 2134 DMSG("fat_address %d", fh->rpmb_fat_address); 2135 2136 res = fat_entry_dir_init(); 2137 if (res) 2138 goto out; 2139 2140 /* 2141 * The pool is used to represent the current RPMB layout. To find 2142 * a slot for the file tee_mm_alloc is called on the pool. Thus 2143 * if it is not NULL the entire FAT must be traversed to fill in 2144 * the pool. 2145 */ 2146 while (true) { 2147 res = fat_entry_dir_get_next(&fe, &fat_address); 2148 if (res || !fe) 2149 break; 2150 2151 /* 2152 * Look for an entry, matching filenames. (read, rm, 2153 * rename and stat.). Only store first filename match. 2154 */ 2155 if ((!strcmp(fh->filename, fe->filename)) && 2156 (fe->flags & FILE_IS_ACTIVE) && !entry_found) { 2157 entry_found = true; 2158 fh->rpmb_fat_address = fat_address; 2159 memcpy(&fh->fat_entry, fe, sizeof(*fe)); 2160 if (!p) 2161 break; 2162 } 2163 2164 /* Add existing files to memory pool. (write) */ 2165 if (p) { 2166 if ((fe->flags & FILE_IS_ACTIVE) && fe->data_size > 0) { 2167 2168 mm = tee_mm_alloc2(p, fe->start_address, 2169 fe->data_size); 2170 if (!mm) { 2171 res = TEE_ERROR_OUT_OF_MEMORY; 2172 goto out; 2173 } 2174 } 2175 2176 /* Unused FAT entries can be reused (write) */ 2177 if (((fe->flags & FILE_IS_ACTIVE) == 0) && 2178 fh->rpmb_fat_address == 0) { 2179 fh->rpmb_fat_address = fat_address; 2180 memcpy(&fh->fat_entry, fe, 2181 sizeof(struct rpmb_fat_entry)); 2182 } 2183 2184 if (((fe->flags & FILE_IS_LAST_ENTRY) != 0) && 2185 fh->rpmb_fat_address == fat_address) { 2186 2187 /* 2188 * If the last entry was reached and was chosen 2189 * by the previous check, then the FAT needs to 2190 * be expanded. 2191 * fh->rpmb_fat_address is the address chosen 2192 * to store the files FAT entry and fat_address 2193 * is the current FAT entry address being 2194 * compared. 2195 */ 2196 expand_fat = true; 2197 } 2198 } 2199 } 2200 2201 if (res) 2202 goto out; 2203 /* 2204 * Represent the FAT table in the pool. 2205 */ 2206 if (p) { 2207 /* 2208 * Since fat_address is the start of the last entry it needs to 2209 * be moved up by an entry. 2210 */ 2211 fat_address += sizeof(struct rpmb_fat_entry); 2212 2213 /* Make room for yet a FAT entry and add to memory pool. */ 2214 if (expand_fat) 2215 fat_address += sizeof(struct rpmb_fat_entry); 2216 2217 mm = tee_mm_alloc2(p, RPMB_STORAGE_START_ADDRESS, fat_address); 2218 if (!mm) { 2219 res = TEE_ERROR_OUT_OF_MEMORY; 2220 goto out; 2221 } 2222 2223 if (expand_fat) { 2224 /* 2225 * Point fat_address to the beginning of the new 2226 * entry. 2227 */ 2228 fat_address -= sizeof(struct rpmb_fat_entry); 2229 memset(&last_fh, 0, sizeof(last_fh)); 2230 last_fh.fat_entry.flags = FILE_IS_LAST_ENTRY; 2231 last_fh.rpmb_fat_address = fat_address; 2232 res = write_fat_entry(&last_fh, true); 2233 if (res != TEE_SUCCESS) 2234 goto out; 2235 } 2236 } 2237 2238 if (!fh->rpmb_fat_address) 2239 res = TEE_ERROR_ITEM_NOT_FOUND; 2240 2241 out: 2242 fat_entry_dir_deinit(); 2243 return res; 2244 } 2245 2246 static TEE_Result generate_fek(struct rpmb_fat_entry *fe, const TEE_UUID *uuid) 2247 { 2248 TEE_Result res; 2249 2250 again: 2251 res = tee_fs_generate_fek(uuid, fe->fek, sizeof(fe->fek)); 2252 if (res != TEE_SUCCESS) 2253 return res; 2254 2255 if (is_zero(fe->fek, sizeof(fe->fek))) 2256 goto again; 2257 2258 return res; 2259 } 2260 2261 static TEE_Result rpmb_fs_open_internal(struct rpmb_file_handle *fh, 2262 const TEE_UUID *uuid, bool create) 2263 { 2264 tee_mm_pool_t p; 2265 bool pool_result; 2266 TEE_Result res = TEE_ERROR_GENERIC; 2267 2268 /* We need to do setup in order to make sure fs_par is filled in */ 2269 res = rpmb_fs_setup(); 2270 if (res != TEE_SUCCESS) 2271 goto out; 2272 2273 fh->uuid = uuid; 2274 if (create) { 2275 /* Upper memory allocation must be used for RPMB_FS. */ 2276 pool_result = tee_mm_init(&p, 2277 RPMB_STORAGE_START_ADDRESS, 2278 fs_par->max_rpmb_address, 2279 RPMB_BLOCK_SIZE_SHIFT, 2280 TEE_MM_POOL_HI_ALLOC); 2281 2282 if (!pool_result) { 2283 res = TEE_ERROR_OUT_OF_MEMORY; 2284 goto out; 2285 } 2286 2287 res = read_fat(fh, &p); 2288 tee_mm_final(&p); 2289 if (res != TEE_SUCCESS) 2290 goto out; 2291 } else { 2292 res = read_fat(fh, NULL); 2293 if (res != TEE_SUCCESS) 2294 goto out; 2295 } 2296 2297 /* 2298 * If this is opened with create and the entry found was not active 2299 * then this is a new file and the FAT entry must be written 2300 */ 2301 if (create) { 2302 if ((fh->fat_entry.flags & FILE_IS_ACTIVE) == 0) { 2303 memset(&fh->fat_entry, 0, 2304 sizeof(struct rpmb_fat_entry)); 2305 memcpy(fh->fat_entry.filename, fh->filename, 2306 strlen(fh->filename)); 2307 /* Start address and size are 0 */ 2308 fh->fat_entry.flags = FILE_IS_ACTIVE; 2309 2310 res = generate_fek(&fh->fat_entry, uuid); 2311 if (res != TEE_SUCCESS) 2312 goto out; 2313 DMSG("GENERATE FEK key: %p", 2314 (void *)fh->fat_entry.fek); 2315 DHEXDUMP(fh->fat_entry.fek, sizeof(fh->fat_entry.fek)); 2316 2317 res = write_fat_entry(fh, true); 2318 if (res != TEE_SUCCESS) 2319 goto out; 2320 } 2321 } 2322 2323 res = TEE_SUCCESS; 2324 2325 out: 2326 return res; 2327 } 2328 2329 static void rpmb_fs_close(struct tee_file_handle **tfh) 2330 { 2331 struct rpmb_file_handle *fh = (struct rpmb_file_handle *)*tfh; 2332 2333 free(fh); 2334 *tfh = NULL; 2335 } 2336 2337 static TEE_Result rpmb_fs_read(struct tee_file_handle *tfh, size_t pos, 2338 void *buf, size_t *len) 2339 { 2340 TEE_Result res; 2341 struct rpmb_file_handle *fh = (struct rpmb_file_handle *)tfh; 2342 size_t size = *len; 2343 2344 if (!size) 2345 return TEE_SUCCESS; 2346 2347 mutex_lock(&rpmb_mutex); 2348 2349 dump_fh(fh); 2350 2351 res = read_fat(fh, NULL); 2352 if (res != TEE_SUCCESS) 2353 goto out; 2354 2355 if (pos >= fh->fat_entry.data_size) { 2356 *len = 0; 2357 goto out; 2358 } 2359 2360 size = MIN(size, fh->fat_entry.data_size - pos); 2361 if (size) { 2362 res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID, 2363 fh->fat_entry.start_address + pos, buf, 2364 size, fh->fat_entry.fek, fh->uuid); 2365 if (res != TEE_SUCCESS) 2366 goto out; 2367 } 2368 *len = size; 2369 2370 out: 2371 mutex_unlock(&rpmb_mutex); 2372 return res; 2373 } 2374 2375 static TEE_Result update_write_helper(struct rpmb_file_handle *fh, 2376 size_t pos, const void *buf, 2377 size_t size, uintptr_t new_fat, 2378 size_t new_size) 2379 { 2380 uintptr_t old_fat = fh->fat_entry.start_address; 2381 size_t old_size = fh->fat_entry.data_size; 2382 const uint8_t *rem_buf = buf; 2383 size_t rem_size = size; 2384 uint8_t *blk_buf = NULL; 2385 size_t blk_offset = 0; 2386 size_t blk_size = 0; 2387 TEE_Result res = TEE_SUCCESS; 2388 2389 blk_buf = mempool_alloc(mempool_default, TMP_BLOCK_SIZE); 2390 if (!blk_buf) 2391 return TEE_ERROR_OUT_OF_MEMORY; 2392 2393 while (blk_offset < new_size) { 2394 uint8_t *copy_dst = blk_buf; 2395 size_t copy_size = 0; 2396 size_t rd_size = 0; 2397 2398 blk_size = MIN(TMP_BLOCK_SIZE, new_size - blk_offset); 2399 memset(blk_buf, 0, blk_size); 2400 2401 /* Possibly read old RPMB data in temporary buffer */ 2402 if (blk_offset < pos && blk_offset < old_size) { 2403 rd_size = MIN(blk_size, old_size - blk_offset); 2404 2405 res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID, 2406 old_fat + blk_offset, blk_buf, 2407 rd_size, fh->fat_entry.fek, 2408 fh->uuid); 2409 if (res != TEE_SUCCESS) 2410 break; 2411 } 2412 2413 /* Possibly update data in temporary buffer */ 2414 if ((blk_offset + TMP_BLOCK_SIZE > pos) && 2415 (blk_offset < pos + size)) { 2416 size_t offset = 0; 2417 2418 copy_dst = blk_buf; 2419 copy_size = TMP_BLOCK_SIZE; 2420 2421 if (blk_offset < pos) { 2422 offset = pos - blk_offset; 2423 2424 copy_dst += offset; 2425 copy_size -= offset; 2426 } 2427 copy_size = MIN(copy_size, rem_size); 2428 2429 memcpy(copy_dst, rem_buf, copy_size); 2430 rem_buf += copy_size; 2431 rem_size -= copy_size; 2432 } 2433 2434 /* Write temporary buffer to new RPMB destination */ 2435 res = tee_rpmb_write(CFG_RPMB_FS_DEV_ID, new_fat + blk_offset, 2436 blk_buf, blk_size, 2437 fh->fat_entry.fek, fh->uuid); 2438 if (res != TEE_SUCCESS) 2439 break; 2440 2441 blk_offset += blk_size; 2442 } 2443 2444 mempool_free(mempool_default, blk_buf); 2445 2446 return res; 2447 } 2448 2449 static TEE_Result rpmb_fs_write_primitive(struct rpmb_file_handle *fh, 2450 size_t pos, const void *buf, 2451 size_t size) 2452 { 2453 TEE_Result res = TEE_ERROR_GENERIC; 2454 tee_mm_pool_t p = { }; 2455 bool pool_result = false; 2456 size_t end = 0; 2457 uint32_t start_addr = 0; 2458 2459 if (!size) 2460 return TEE_SUCCESS; 2461 2462 if (!fs_par) { 2463 res = TEE_ERROR_GENERIC; 2464 goto out; 2465 } 2466 2467 dump_fh(fh); 2468 2469 /* Upper memory allocation must be used for RPMB_FS. */ 2470 pool_result = tee_mm_init(&p, 2471 RPMB_STORAGE_START_ADDRESS, 2472 fs_par->max_rpmb_address, 2473 RPMB_BLOCK_SIZE_SHIFT, 2474 TEE_MM_POOL_HI_ALLOC); 2475 if (!pool_result) { 2476 res = TEE_ERROR_OUT_OF_MEMORY; 2477 goto out; 2478 } 2479 2480 res = read_fat(fh, &p); 2481 if (res != TEE_SUCCESS) 2482 goto out; 2483 2484 if (fh->fat_entry.flags & FILE_IS_LAST_ENTRY) 2485 panic("invalid last entry flag"); 2486 2487 if (ADD_OVERFLOW(pos, size, &end)) { 2488 res = TEE_ERROR_BAD_PARAMETERS; 2489 goto out; 2490 } 2491 if (ADD_OVERFLOW(fh->fat_entry.start_address, pos, &start_addr)) { 2492 res = TEE_ERROR_BAD_PARAMETERS; 2493 goto out; 2494 } 2495 2496 if (end <= fh->fat_entry.data_size && 2497 tee_rpmb_write_is_atomic(CFG_RPMB_FS_DEV_ID, start_addr, size)) { 2498 2499 DMSG("Updating data in-place"); 2500 res = tee_rpmb_write(CFG_RPMB_FS_DEV_ID, start_addr, buf, 2501 size, fh->fat_entry.fek, fh->uuid); 2502 } else { 2503 /* 2504 * File must be extended, or update cannot be atomic: allocate, 2505 * read, update, write. 2506 */ 2507 size_t new_size = MAX(end, fh->fat_entry.data_size); 2508 tee_mm_entry_t *mm = tee_mm_alloc(&p, new_size); 2509 uintptr_t new_fat_entry = 0; 2510 2511 DMSG("Need to re-allocate"); 2512 if (!mm) { 2513 DMSG("RPMB: No space left"); 2514 res = TEE_ERROR_STORAGE_NO_SPACE; 2515 goto out; 2516 } 2517 2518 new_fat_entry = tee_mm_get_smem(mm); 2519 2520 res = update_write_helper(fh, pos, buf, size, 2521 new_fat_entry, new_size); 2522 if (res == TEE_SUCCESS) { 2523 fh->fat_entry.data_size = new_size; 2524 fh->fat_entry.start_address = new_fat_entry; 2525 2526 res = write_fat_entry(fh, true); 2527 } 2528 } 2529 2530 out: 2531 if (pool_result) 2532 tee_mm_final(&p); 2533 2534 return res; 2535 } 2536 2537 static TEE_Result rpmb_fs_write(struct tee_file_handle *tfh, size_t pos, 2538 const void *buf, size_t size) 2539 { 2540 TEE_Result res; 2541 2542 mutex_lock(&rpmb_mutex); 2543 res = rpmb_fs_write_primitive((struct rpmb_file_handle *)tfh, pos, 2544 buf, size); 2545 mutex_unlock(&rpmb_mutex); 2546 2547 return res; 2548 } 2549 2550 static TEE_Result rpmb_fs_remove_internal(struct rpmb_file_handle *fh) 2551 { 2552 TEE_Result res; 2553 2554 res = read_fat(fh, NULL); 2555 if (res) 2556 return res; 2557 2558 /* Clear this file entry. */ 2559 memset(&fh->fat_entry, 0, sizeof(struct rpmb_fat_entry)); 2560 return write_fat_entry(fh, false); 2561 } 2562 2563 static TEE_Result rpmb_fs_remove(struct tee_pobj *po) 2564 { 2565 TEE_Result res; 2566 struct rpmb_file_handle *fh = alloc_file_handle(po, po->temporary); 2567 2568 if (!fh) 2569 return TEE_ERROR_OUT_OF_MEMORY; 2570 2571 mutex_lock(&rpmb_mutex); 2572 2573 res = rpmb_fs_remove_internal(fh); 2574 2575 mutex_unlock(&rpmb_mutex); 2576 2577 free(fh); 2578 return res; 2579 } 2580 2581 static TEE_Result rpmb_fs_rename_internal(struct tee_pobj *old, 2582 struct tee_pobj *new, 2583 bool overwrite) 2584 { 2585 TEE_Result res = TEE_ERROR_GENERIC; 2586 struct rpmb_file_handle *fh_old = NULL; 2587 struct rpmb_file_handle *fh_new = NULL; 2588 2589 if (!old) { 2590 res = TEE_ERROR_BAD_PARAMETERS; 2591 goto out; 2592 } 2593 2594 if (new) 2595 fh_old = alloc_file_handle(old, old->temporary); 2596 else 2597 fh_old = alloc_file_handle(old, true); 2598 if (!fh_old) { 2599 res = TEE_ERROR_OUT_OF_MEMORY; 2600 goto out; 2601 } 2602 2603 if (new) 2604 fh_new = alloc_file_handle(new, new->temporary); 2605 else 2606 fh_new = alloc_file_handle(old, false); 2607 if (!fh_new) { 2608 res = TEE_ERROR_OUT_OF_MEMORY; 2609 goto out; 2610 } 2611 2612 res = read_fat(fh_old, NULL); 2613 if (res != TEE_SUCCESS) 2614 goto out; 2615 2616 res = read_fat(fh_new, NULL); 2617 if (res == TEE_SUCCESS) { 2618 if (!overwrite) { 2619 res = TEE_ERROR_ACCESS_CONFLICT; 2620 goto out; 2621 } 2622 2623 /* Clear this file entry. */ 2624 memset(&fh_new->fat_entry, 0, sizeof(struct rpmb_fat_entry)); 2625 res = write_fat_entry(fh_new, false); 2626 if (res != TEE_SUCCESS) 2627 goto out; 2628 } 2629 2630 memset(fh_old->fat_entry.filename, 0, TEE_RPMB_FS_FILENAME_LENGTH); 2631 memcpy(fh_old->fat_entry.filename, fh_new->filename, 2632 strlen(fh_new->filename)); 2633 2634 res = write_fat_entry(fh_old, false); 2635 2636 out: 2637 free(fh_old); 2638 free(fh_new); 2639 2640 return res; 2641 } 2642 2643 static TEE_Result rpmb_fs_rename(struct tee_pobj *old, struct tee_pobj *new, 2644 bool overwrite) 2645 { 2646 TEE_Result res; 2647 2648 mutex_lock(&rpmb_mutex); 2649 res = rpmb_fs_rename_internal(old, new, overwrite); 2650 mutex_unlock(&rpmb_mutex); 2651 2652 return res; 2653 } 2654 2655 static TEE_Result rpmb_fs_truncate(struct tee_file_handle *tfh, size_t length) 2656 { 2657 struct rpmb_file_handle *fh = (struct rpmb_file_handle *)tfh; 2658 tee_mm_pool_t p; 2659 bool pool_result = false; 2660 tee_mm_entry_t *mm; 2661 uint32_t newsize; 2662 uint8_t *newbuf = NULL; 2663 uintptr_t newaddr; 2664 TEE_Result res = TEE_ERROR_GENERIC; 2665 2666 mutex_lock(&rpmb_mutex); 2667 2668 if (length > INT32_MAX) { 2669 res = TEE_ERROR_BAD_PARAMETERS; 2670 goto out; 2671 } 2672 newsize = length; 2673 2674 res = read_fat(fh, NULL); 2675 if (res != TEE_SUCCESS) 2676 goto out; 2677 2678 if (newsize > fh->fat_entry.data_size) { 2679 /* Extend file */ 2680 2681 pool_result = tee_mm_init(&p, 2682 RPMB_STORAGE_START_ADDRESS, 2683 fs_par->max_rpmb_address, 2684 RPMB_BLOCK_SIZE_SHIFT, 2685 TEE_MM_POOL_HI_ALLOC); 2686 if (!pool_result) { 2687 res = TEE_ERROR_OUT_OF_MEMORY; 2688 goto out; 2689 } 2690 res = read_fat(fh, &p); 2691 if (res != TEE_SUCCESS) 2692 goto out; 2693 2694 mm = tee_mm_alloc(&p, newsize); 2695 newbuf = calloc(1, newsize); 2696 if (!mm || !newbuf) { 2697 res = TEE_ERROR_OUT_OF_MEMORY; 2698 goto out; 2699 } 2700 2701 if (fh->fat_entry.data_size) { 2702 res = tee_rpmb_read(CFG_RPMB_FS_DEV_ID, 2703 fh->fat_entry.start_address, 2704 newbuf, fh->fat_entry.data_size, 2705 fh->fat_entry.fek, fh->uuid); 2706 if (res != TEE_SUCCESS) 2707 goto out; 2708 } 2709 2710 newaddr = tee_mm_get_smem(mm); 2711 res = tee_rpmb_write(CFG_RPMB_FS_DEV_ID, newaddr, newbuf, 2712 newsize, fh->fat_entry.fek, fh->uuid); 2713 if (res != TEE_SUCCESS) 2714 goto out; 2715 2716 } else { 2717 /* Don't change file location */ 2718 newaddr = fh->fat_entry.start_address; 2719 } 2720 2721 /* fh->pos is unchanged */ 2722 fh->fat_entry.data_size = newsize; 2723 fh->fat_entry.start_address = newaddr; 2724 res = write_fat_entry(fh, true); 2725 2726 out: 2727 mutex_unlock(&rpmb_mutex); 2728 if (pool_result) 2729 tee_mm_final(&p); 2730 if (newbuf) 2731 free(newbuf); 2732 2733 return res; 2734 } 2735 2736 static void rpmb_fs_dir_free(struct tee_fs_dir *dir) 2737 { 2738 struct tee_rpmb_fs_dirent *e; 2739 2740 if (!dir) 2741 return; 2742 2743 free(dir->current); 2744 2745 while ((e = SIMPLEQ_FIRST(&dir->next))) { 2746 SIMPLEQ_REMOVE_HEAD(&dir->next, link); 2747 free(e); 2748 } 2749 } 2750 2751 static TEE_Result rpmb_fs_dir_populate(const char *path, 2752 struct tee_fs_dir *dir) 2753 { 2754 struct tee_rpmb_fs_dirent *current = NULL; 2755 struct rpmb_fat_entry *fe = NULL; 2756 uint32_t fat_address; 2757 uint32_t filelen; 2758 char *filename; 2759 bool matched; 2760 struct tee_rpmb_fs_dirent *next = NULL; 2761 uint32_t pathlen; 2762 TEE_Result res = TEE_ERROR_GENERIC; 2763 char temp; 2764 2765 mutex_lock(&rpmb_mutex); 2766 2767 res = fat_entry_dir_init(); 2768 if (res) 2769 goto out; 2770 2771 pathlen = strlen(path); 2772 2773 while (true) { 2774 res = fat_entry_dir_get_next(&fe, &fat_address); 2775 if (res || !fe) 2776 break; 2777 2778 filename = fe->filename; 2779 if (fe->flags & FILE_IS_ACTIVE) { 2780 matched = false; 2781 filelen = strlen(filename); 2782 if (filelen > pathlen) { 2783 temp = filename[pathlen]; 2784 filename[pathlen] = '\0'; 2785 if (strcmp(filename, path) == 0) 2786 matched = true; 2787 2788 filename[pathlen] = temp; 2789 } 2790 2791 if (matched) { 2792 next = malloc(sizeof(*next)); 2793 if (!next) { 2794 res = TEE_ERROR_OUT_OF_MEMORY; 2795 goto out; 2796 } 2797 2798 next->entry.oidlen = tee_hs2b((uint8_t *) 2799 &filename[pathlen], 2800 next->entry.oid, 2801 filelen - pathlen, 2802 sizeof(next->entry.oid)); 2803 if (next->entry.oidlen) { 2804 SIMPLEQ_INSERT_TAIL(&dir->next, 2805 next, link); 2806 current = next; 2807 } else { 2808 free(next); 2809 next = NULL; 2810 } 2811 } 2812 } 2813 } 2814 2815 if (res) 2816 goto out; 2817 2818 if (current) 2819 res = TEE_SUCCESS; 2820 else 2821 res = TEE_ERROR_ITEM_NOT_FOUND; /* No directories were found. */ 2822 2823 out: 2824 mutex_unlock(&rpmb_mutex); 2825 fat_entry_dir_deinit(); 2826 if (res) 2827 rpmb_fs_dir_free(dir); 2828 2829 return res; 2830 } 2831 2832 static TEE_Result rpmb_fs_opendir(const TEE_UUID *uuid, struct tee_fs_dir **dir) 2833 { 2834 uint32_t len; 2835 char path_local[TEE_RPMB_FS_FILENAME_LENGTH]; 2836 TEE_Result res = TEE_ERROR_GENERIC; 2837 struct tee_fs_dir *rpmb_dir = NULL; 2838 2839 if (!uuid || !dir) { 2840 res = TEE_ERROR_BAD_PARAMETERS; 2841 goto out; 2842 } 2843 2844 memset(path_local, 0, sizeof(path_local)); 2845 if (tee_svc_storage_create_dirname(path_local, sizeof(path_local) - 1, 2846 uuid) != TEE_SUCCESS) { 2847 res = TEE_ERROR_BAD_PARAMETERS; 2848 goto out; 2849 } 2850 len = strlen(path_local); 2851 2852 /* Add a slash to correctly match the full directory name. */ 2853 if (path_local[len - 1] != '/') 2854 path_local[len] = '/'; 2855 2856 rpmb_dir = calloc(1, sizeof(*rpmb_dir)); 2857 if (!rpmb_dir) { 2858 res = TEE_ERROR_OUT_OF_MEMORY; 2859 goto out; 2860 } 2861 SIMPLEQ_INIT(&rpmb_dir->next); 2862 2863 res = rpmb_fs_dir_populate(path_local, rpmb_dir); 2864 if (res != TEE_SUCCESS) { 2865 free(rpmb_dir); 2866 rpmb_dir = NULL; 2867 goto out; 2868 } 2869 2870 *dir = rpmb_dir; 2871 2872 out: 2873 return res; 2874 } 2875 2876 static TEE_Result rpmb_fs_readdir(struct tee_fs_dir *dir, 2877 struct tee_fs_dirent **ent) 2878 { 2879 if (!dir) 2880 return TEE_ERROR_GENERIC; 2881 2882 free(dir->current); 2883 2884 dir->current = SIMPLEQ_FIRST(&dir->next); 2885 if (!dir->current) 2886 return TEE_ERROR_ITEM_NOT_FOUND; 2887 2888 SIMPLEQ_REMOVE_HEAD(&dir->next, link); 2889 2890 *ent = &dir->current->entry; 2891 return TEE_SUCCESS; 2892 } 2893 2894 static void rpmb_fs_closedir(struct tee_fs_dir *dir) 2895 { 2896 if (dir) { 2897 rpmb_fs_dir_free(dir); 2898 free(dir); 2899 } 2900 } 2901 2902 static TEE_Result rpmb_fs_open(struct tee_pobj *po, size_t *size, 2903 struct tee_file_handle **ret_fh) 2904 { 2905 TEE_Result res; 2906 struct rpmb_file_handle *fh = alloc_file_handle(po, po->temporary); 2907 2908 if (!fh) 2909 return TEE_ERROR_OUT_OF_MEMORY; 2910 2911 mutex_lock(&rpmb_mutex); 2912 2913 res = rpmb_fs_open_internal(fh, &po->uuid, false); 2914 if (!res && size) 2915 *size = fh->fat_entry.data_size; 2916 2917 mutex_unlock(&rpmb_mutex); 2918 2919 if (res) 2920 free(fh); 2921 else 2922 *ret_fh = (struct tee_file_handle *)fh; 2923 2924 return res; 2925 } 2926 2927 static TEE_Result rpmb_fs_create(struct tee_pobj *po, bool overwrite, 2928 const void *head, size_t head_size, 2929 const void *attr, size_t attr_size, 2930 const void *data, size_t data_size, 2931 struct tee_file_handle **ret_fh) 2932 { 2933 TEE_Result res; 2934 size_t pos = 0; 2935 struct rpmb_file_handle *fh = alloc_file_handle(po, po->temporary); 2936 2937 if (!fh) 2938 return TEE_ERROR_OUT_OF_MEMORY; 2939 2940 mutex_lock(&rpmb_mutex); 2941 res = rpmb_fs_open_internal(fh, &po->uuid, true); 2942 if (res) 2943 goto out; 2944 2945 if (head && head_size) { 2946 res = rpmb_fs_write_primitive(fh, pos, head, head_size); 2947 if (res) 2948 goto out; 2949 pos += head_size; 2950 } 2951 2952 if (attr && attr_size) { 2953 res = rpmb_fs_write_primitive(fh, pos, attr, attr_size); 2954 if (res) 2955 goto out; 2956 pos += attr_size; 2957 } 2958 2959 if (data && data_size) { 2960 res = rpmb_fs_write_primitive(fh, pos, data, data_size); 2961 if (res) 2962 goto out; 2963 } 2964 2965 if (po->temporary) { 2966 /* 2967 * If it's a temporary filename (which it normally is) 2968 * rename into the final filename now that the file is 2969 * fully initialized. 2970 */ 2971 po->temporary = false; 2972 res = rpmb_fs_rename_internal(po, NULL, overwrite); 2973 if (res) { 2974 po->temporary = true; 2975 goto out; 2976 } 2977 /* Update file handle after rename. */ 2978 tee_svc_storage_create_filename(fh->filename, 2979 sizeof(fh->filename), 2980 po, false); 2981 } 2982 2983 out: 2984 if (res) { 2985 rpmb_fs_remove_internal(fh); 2986 free(fh); 2987 } else { 2988 *ret_fh = (struct tee_file_handle *)fh; 2989 } 2990 mutex_unlock(&rpmb_mutex); 2991 2992 return res; 2993 } 2994 2995 const struct tee_file_operations rpmb_fs_ops = { 2996 .open = rpmb_fs_open, 2997 .create = rpmb_fs_create, 2998 .close = rpmb_fs_close, 2999 .read = rpmb_fs_read, 3000 .write = rpmb_fs_write, 3001 .truncate = rpmb_fs_truncate, 3002 .rename = rpmb_fs_rename, 3003 .remove = rpmb_fs_remove, 3004 .opendir = rpmb_fs_opendir, 3005 .closedir = rpmb_fs_closedir, 3006 .readdir = rpmb_fs_readdir, 3007 }; 3008 3009 TEE_Result tee_rpmb_fs_raw_open(const char *fname, bool create, 3010 struct tee_file_handle **ret_fh) 3011 { 3012 TEE_Result res; 3013 struct rpmb_file_handle *fh = calloc(1, sizeof(*fh)); 3014 static const TEE_UUID uuid = { 0 }; 3015 3016 if (!fh) 3017 return TEE_ERROR_OUT_OF_MEMORY; 3018 3019 snprintf(fh->filename, sizeof(fh->filename), "/%s", fname); 3020 3021 mutex_lock(&rpmb_mutex); 3022 3023 res = rpmb_fs_open_internal(fh, &uuid, create); 3024 3025 mutex_unlock(&rpmb_mutex); 3026 3027 if (res) { 3028 if (create) 3029 rpmb_fs_remove_internal(fh); 3030 free(fh); 3031 } else { 3032 *ret_fh = (struct tee_file_handle *)fh; 3033 } 3034 3035 return res; 3036 } 3037 3038 bool __weak plat_rpmb_key_is_ready(void) 3039 { 3040 return true; 3041 } 3042