Skip to content

Commit

Permalink
ta: pkcs11: write db_main and db_objs in one operation
Browse files Browse the repository at this point in the history
Problem:
There is a potential issue in persistent_token.c::init_persistent_db().
There are two steps to initialize a token DB if it doesn’t exist:
1. Call TEE_CreatePersistentObject() with db_main as the initial data.
2. Truncate the object data and then insert db_obj data.
If a power loss occurs between above two steps, only the db_main data is
present in the database. When the device restarts, it detects the existing
database and successfully reads db_main, but fails to read db_obj, leading
to a TA panic each time.
OP-TEE#6977

Solution:
Write both db_main and the initial 4 bytes of db_objs (with a count of 0)
in a single operation during TEE_CreatePersistentObject().

Tested-by: Weizhao Jiang <weizhaoj@amazon.com>
Reviewed-by: Etienne Carriere <etienne.carriere@foss.st.com>
Signed-off-by: Weizhao Jiang <weizhaoj@amazon.com>
  • Loading branch information
weizhaojiang authored and jforissier committed Aug 27, 2024
1 parent 81d5a9d commit 931c8c5
Showing 1 changed file with 18 additions and 16 deletions.
34 changes: 18 additions & 16 deletions ta/pkcs11/src/persistent_token.c
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,8 @@ struct ck_token *init_persistent_db(unsigned int token_id)
struct token_persistent_main *db_main = NULL;
struct token_persistent_objs *db_objs = NULL;
void *ptr = NULL;
void *initial_data = NULL;
uint32_t initial_data_size = 0;

if (!token)
return NULL;
Expand Down Expand Up @@ -666,34 +668,34 @@ struct ck_token *init_persistent_db(unsigned int token_id)
/*
* Object stores persistent state + persistent object
* references.
*
* Allocate the initial_data buffer to encompass the data from
* both db_main and db_objs. Since the initial data for the
* objects will be zeroed out upon creation, there’s no need
* to copy it from db_objs.
*/
initial_data_size = sizeof(*db_main) + sizeof(*db_objs);
initial_data = TEE_Malloc(initial_data_size,
TEE_MALLOC_FILL_ZERO);
if (!initial_data) {
EMSG("Failed to allocate initial_data buffer");
goto error;
}
TEE_MemMove(initial_data, db_main, sizeof(*db_main));
res = TEE_CreatePersistentObject(TEE_STORAGE_PRIVATE,
file, sizeof(file),
TEE_DATA_FLAG_ACCESS_READ |
TEE_DATA_FLAG_ACCESS_WRITE,
TEE_HANDLE_NULL,
db_main, sizeof(*db_main),
initial_data,
initial_data_size,
&db_hdl);
TEE_Free(initial_data);
if (res) {
EMSG("Failed to create db: %#"PRIx32, res);
goto error;
}

res = TEE_TruncateObjectData(db_hdl, sizeof(*db_main) +
sizeof(*db_objs));
if (res)
TEE_Panic(0);

res = TEE_SeekObjectData(db_hdl, sizeof(*db_main),
TEE_DATA_SEEK_SET);
if (res)
TEE_Panic(0);

db_objs->count = 0;
res = TEE_WriteObjectData(db_hdl, db_objs, sizeof(*db_objs));
if (res)
TEE_Panic(0);

} else {
goto error;
}
Expand Down

0 comments on commit 931c8c5

Please sign in to comment.