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