xref: /optee_os/core/tee/fs_htree.c (revision b1d7375c01ec8bcbf3561d27425d320afed23bce)
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2017, Linaro Limited
4  */
5 
6 #include <assert.h>
7 #include <crypto/crypto.h>
8 #include <initcall.h>
9 #include <kernel/tee_common_otp.h>
10 #include <optee_msg_supplicant.h>
11 #include <stdlib.h>
12 #include <string_ext.h>
13 #include <string.h>
14 #include <tee/fs_htree.h>
15 #include <tee/tee_fs_key_manager.h>
16 #include <tee/tee_fs_rpc.h>
17 #include <utee_defines.h>
18 #include <util.h>
19 
20 #define TEE_FS_HTREE_CHIP_ID_SIZE	32
21 #define TEE_FS_HTREE_HASH_ALG		TEE_ALG_SHA256
22 #define TEE_FS_HTREE_TSK_SIZE		TEE_FS_HTREE_HASH_SIZE
23 #define TEE_FS_HTREE_ENC_ALG		TEE_ALG_AES_ECB_NOPAD
24 #define TEE_FS_HTREE_ENC_SIZE		TEE_AES_BLOCK_SIZE
25 #define TEE_FS_HTREE_SSK_SIZE		TEE_FS_HTREE_HASH_SIZE
26 
27 #define TEE_FS_HTREE_AUTH_ENC_ALG	TEE_ALG_AES_GCM
28 #define TEE_FS_HTREE_HMAC_ALG		TEE_ALG_HMAC_SHA256
29 
30 #define BLOCK_NUM_TO_NODE_ID(num)	((num) + 1)
31 
32 #define NODE_ID_TO_BLOCK_NUM(id)	((id) - 1)
33 
34 /*
35  * The hash tree is implemented as a binary tree with the purpose to ensure
36  * integrity of the data in the nodes. The data in the nodes their turn
37  * provides both integrity and confidentiality of the data blocks.
38  *
39  * The hash tree is saved in a file as:
40  * +----------------------------+
41  * | htree_image.0		|
42  * | htree_image.1		|
43  * +----------------------------+
44  * | htree_node_image.1.0	|
45  * | htree_node_image.1.1	|
46  * +----------------------------+
47  * | htree_node_image.2.0	|
48  * | htree_node_image.2.1	|
49  * +----------------------------+
50  * | htree_node_image.3.0	|
51  * | htree_node_image.3.1	|
52  * +----------------------------+
53  * | htree_node_image.4.0	|
54  * | htree_node_image.4.1	|
55  * +----------------------------+
56  * ...
57  *
58  * htree_image is the header of the file, there's two instances of it. One
59  * which is committed and the other is used when updating the file. Which
60  * is committed is indicated by the "counter" field, the one with the
61  * largest value is selected.
62  *
63  * htree_node_image is a node in the hash tree, each node has two instances
64  * which is committed is decided by the parent node .flag bit
65  * HTREE_NODE_COMMITTED_CHILD. Which version is the committed version of
66  * node 1 is determined by the by the lowest bit of the counter field in
67  * the header.
68  *
69  * Note that nodes start counting at 1 while blocks at 0, this means that
70  * block 0 is represented by node 1.
71  *
72  * Where different elements are stored in the file is managed by the file
73  * system.
74  */
75 
76 #define HTREE_NODE_COMMITTED_BLOCK	BIT32(0)
77 /* n is 0 or 1 */
78 #define HTREE_NODE_COMMITTED_CHILD(n)	BIT32(1 + (n))
79 
80 struct htree_node {
81 	size_t id;
82 	bool dirty;
83 	bool block_updated;
84 	struct tee_fs_htree_node_image node;
85 	struct htree_node *parent;
86 	struct htree_node *child[2];
87 };
88 
89 struct tee_fs_htree {
90 	struct htree_node root;
91 	struct tee_fs_htree_image head;
92 	uint8_t fek[TEE_FS_HTREE_FEK_SIZE];
93 	struct tee_fs_htree_imeta imeta;
94 	bool dirty;
95 	const TEE_UUID *uuid;
96 	const struct tee_fs_htree_storage *stor;
97 	void *stor_aux;
98 };
99 
100 struct traverse_arg;
101 typedef TEE_Result (*traverse_cb_t)(struct traverse_arg *targ,
102 				    struct htree_node *node);
103 struct traverse_arg {
104 	struct tee_fs_htree *ht;
105 	traverse_cb_t cb;
106 	void *arg;
107 };
108 
109 static TEE_Result rpc_read(struct tee_fs_htree *ht, enum tee_fs_htree_type type,
110 			   size_t idx, size_t vers, void *data, size_t dlen)
111 {
112 	TEE_Result res;
113 	struct tee_fs_rpc_operation op;
114 	size_t bytes;
115 	void *p;
116 
117 	res = ht->stor->rpc_read_init(ht->stor_aux, &op, type, idx, vers, &p);
118 	if (res != TEE_SUCCESS)
119 		return res;
120 
121 	res = ht->stor->rpc_read_final(&op, &bytes);
122 	if (res != TEE_SUCCESS)
123 		return res;
124 
125 	if (bytes != dlen)
126 		return TEE_ERROR_CORRUPT_OBJECT;
127 
128 	memcpy(data, p, dlen);
129 	return TEE_SUCCESS;
130 }
131 
132 static TEE_Result rpc_read_head(struct tee_fs_htree *ht, size_t vers,
133 				struct tee_fs_htree_image *head)
134 {
135 	return rpc_read(ht, TEE_FS_HTREE_TYPE_HEAD, 0, vers,
136 			head, sizeof(*head));
137 }
138 
139 static TEE_Result rpc_read_node(struct tee_fs_htree *ht, size_t node_id,
140 				size_t vers,
141 				struct tee_fs_htree_node_image *node)
142 {
143 	return rpc_read(ht, TEE_FS_HTREE_TYPE_NODE, node_id - 1, vers,
144 			node, sizeof(*node));
145 }
146 
147 static TEE_Result rpc_write(struct tee_fs_htree *ht,
148 			    enum tee_fs_htree_type type, size_t idx,
149 			    size_t vers, const void *data, size_t dlen)
150 {
151 	TEE_Result res;
152 	struct tee_fs_rpc_operation op;
153 	void *p;
154 
155 	res = ht->stor->rpc_write_init(ht->stor_aux, &op, type, idx, vers, &p);
156 	if (res != TEE_SUCCESS)
157 		return res;
158 
159 	memcpy(p, data, dlen);
160 	return ht->stor->rpc_write_final(&op);
161 }
162 
163 static TEE_Result rpc_write_head(struct tee_fs_htree *ht, size_t vers,
164 				 const struct tee_fs_htree_image *head)
165 {
166 	return rpc_write(ht, TEE_FS_HTREE_TYPE_HEAD, 0, vers,
167 			 head, sizeof(*head));
168 }
169 
170 static TEE_Result rpc_write_node(struct tee_fs_htree *ht, size_t node_id,
171 				 size_t vers,
172 				 const struct tee_fs_htree_node_image *node)
173 {
174 	return rpc_write(ht, TEE_FS_HTREE_TYPE_NODE, node_id - 1, vers,
175 			 node, sizeof(*node));
176 }
177 
178 static TEE_Result traverse_post_order(struct traverse_arg *targ,
179 				      struct htree_node *node)
180 {
181 	TEE_Result res;
182 
183 	/*
184 	 * This function is recursing but not very deep, only with Log(N)
185 	 * maximum depth.
186 	 */
187 
188 	if (!node)
189 		return TEE_SUCCESS;
190 
191 	res = traverse_post_order(targ, node->child[0]);
192 	if (res != TEE_SUCCESS)
193 		return res;
194 
195 	res = traverse_post_order(targ, node->child[1]);
196 	if (res != TEE_SUCCESS)
197 		return res;
198 
199 	return targ->cb(targ, node);
200 }
201 
202 static TEE_Result htree_traverse_post_order(struct tee_fs_htree *ht,
203 					    traverse_cb_t cb, void *arg)
204 {
205 	struct traverse_arg targ = { ht, cb, arg };
206 
207 	return traverse_post_order(&targ, &ht->root);
208 }
209 
210 static size_t node_id_to_level(size_t node_id)
211 {
212 	assert(node_id && node_id < UINT_MAX);
213 	/* Calculate level of the node, root node (1) has level 1 */
214 	return sizeof(unsigned int) * 8 - __builtin_clz(node_id);
215 }
216 
217 static struct htree_node *find_closest_node(struct tee_fs_htree *ht,
218 					    size_t node_id)
219 {
220 	struct htree_node *node = &ht->root;
221 	size_t level = node_id_to_level(node_id);
222 	size_t n;
223 
224 	/* n = 1 because root node is level 1 */
225 	for (n = 1; n < level; n++) {
226 		struct htree_node *child;
227 		size_t bit_idx;
228 
229 		/*
230 		 * The difference between levels of the current node and
231 		 * the node we're looking for tells which bit decides
232 		 * direction in the tree.
233 		 *
234 		 * As the first bit has index 0 we'll subtract 1
235 		 */
236 		bit_idx = level - n - 1;
237 		child = node->child[((node_id >> bit_idx) & 1)];
238 		if (!child)
239 			return node;
240 		node = child;
241 	}
242 
243 	return node;
244 }
245 
246 static struct htree_node *find_node(struct tee_fs_htree *ht, size_t node_id)
247 {
248 	struct htree_node *node = find_closest_node(ht, node_id);
249 
250 	if (node && node->id == node_id)
251 		return node;
252 	return NULL;
253 }
254 
255 static TEE_Result get_node(struct tee_fs_htree *ht, bool create,
256 			   size_t node_id, struct htree_node **node_ret)
257 {
258 	struct htree_node *node;
259 	struct htree_node *nc;
260 	size_t n;
261 
262 	node = find_closest_node(ht, node_id);
263 	if (!node)
264 		return TEE_ERROR_GENERIC;
265 	if (node->id == node_id)
266 		goto ret_node;
267 
268 	/*
269 	 * Trying to read beyond end of file should be caught earlier than
270 	 * here.
271 	 */
272 	if (!create)
273 		return TEE_ERROR_GENERIC;
274 
275 	/*
276 	 * Add missing nodes, some nodes may already be there. When we've
277 	 * processed the range all nodes up to node_id will be in the tree.
278 	 */
279 	for (n = node->id + 1; n <= node_id; n++) {
280 		node = find_closest_node(ht, n);
281 		if (node->id == n)
282 			continue;
283 		/* Node id n should be a child of node */
284 		assert((n >> 1) == node->id);
285 		assert(!node->child[n & 1]);
286 
287 		nc = calloc(1, sizeof(*nc));
288 		if (!nc)
289 			return TEE_ERROR_OUT_OF_MEMORY;
290 		nc->id = n;
291 		nc->parent = node;
292 		node->child[n & 1] = nc;
293 		node = nc;
294 	}
295 
296 	if (node->id > ht->imeta.max_node_id)
297 		ht->imeta.max_node_id = node->id;
298 
299 ret_node:
300 	*node_ret = node;
301 	return TEE_SUCCESS;
302 }
303 
304 static int get_idx_from_counter(uint32_t counter0, uint32_t counter1)
305 {
306 	if (!(counter0 & 1)) {
307 		if (!(counter1 & 1))
308 			return 0;
309 		if (counter0 > counter1)
310 			return 0;
311 		else
312 			return 1;
313 	}
314 
315 	if (counter1 & 1)
316 		return 1;
317 	else
318 		return -1;
319 }
320 
321 static TEE_Result init_head_from_data(struct tee_fs_htree *ht,
322 				      const uint8_t *hash)
323 {
324 	TEE_Result res;
325 	int idx;
326 
327 	if (hash) {
328 		for (idx = 0;; idx++) {
329 			res = rpc_read_node(ht, 1, idx, &ht->root.node);
330 			if (res != TEE_SUCCESS)
331 				return res;
332 
333 			if (!memcmp(ht->root.node.hash, hash,
334 				    sizeof(ht->root.node.hash))) {
335 				res = rpc_read_head(ht, idx, &ht->head);
336 				if (res != TEE_SUCCESS)
337 					return res;
338 				break;
339 			}
340 
341 			if (idx)
342 				return TEE_ERROR_SECURITY;
343 		}
344 	} else {
345 		struct tee_fs_htree_image head[2];
346 
347 		for (idx = 0; idx < 2; idx++) {
348 			res = rpc_read_head(ht, idx, head + idx);
349 			if (res != TEE_SUCCESS)
350 				return res;
351 		}
352 
353 		idx = get_idx_from_counter(head[0].counter, head[1].counter);
354 		if (idx < 0)
355 			return TEE_ERROR_SECURITY;
356 
357 		res = rpc_read_node(ht, 1, idx, &ht->root.node);
358 		if (res != TEE_SUCCESS)
359 			return res;
360 
361 		ht->head = head[idx];
362 	}
363 
364 	ht->root.id = 1;
365 
366 	return TEE_SUCCESS;
367 }
368 
369 static TEE_Result init_tree_from_data(struct tee_fs_htree *ht)
370 {
371 	TEE_Result res;
372 	struct tee_fs_htree_node_image node_image;
373 	struct htree_node *node;
374 	struct htree_node *nc;
375 	size_t committed_version;
376 	size_t node_id = 2;
377 
378 	while (node_id <= ht->imeta.max_node_id) {
379 		node = find_node(ht, node_id >> 1);
380 		if (!node)
381 			return TEE_ERROR_GENERIC;
382 		committed_version = !!(node->node.flags &
383 				    HTREE_NODE_COMMITTED_CHILD(node_id & 1));
384 
385 		res = rpc_read_node(ht, node_id, committed_version,
386 				    &node_image);
387 		if (res != TEE_SUCCESS)
388 			return res;
389 
390 		res = get_node(ht, true, node_id, &nc);
391 		if (res != TEE_SUCCESS)
392 			return res;
393 		nc->node = node_image;
394 		node_id++;
395 	}
396 
397 	return TEE_SUCCESS;
398 }
399 
400 static TEE_Result calc_node_hash(struct htree_node *node, void *ctx,
401 				 uint8_t *digest)
402 {
403 	TEE_Result res;
404 	uint32_t alg = TEE_FS_HTREE_HASH_ALG;
405 	uint8_t *ndata = (uint8_t *)&node->node + sizeof(node->node.hash);
406 	size_t nsize = sizeof(node->node) - sizeof(node->node.hash);
407 
408 	res = crypto_hash_init(ctx, alg);
409 	if (res != TEE_SUCCESS)
410 		return res;
411 
412 	res = crypto_hash_update(ctx, alg, ndata, nsize);
413 	if (res != TEE_SUCCESS)
414 		return res;
415 
416 	if (node->child[0]) {
417 		res = crypto_hash_update(ctx, alg, node->child[0]->node.hash,
418 					 sizeof(node->child[0]->node.hash));
419 		if (res != TEE_SUCCESS)
420 			return res;
421 	}
422 
423 	if (node->child[1]) {
424 		res = crypto_hash_update(ctx, alg, node->child[1]->node.hash,
425 					 sizeof(node->child[1]->node.hash));
426 		if (res != TEE_SUCCESS)
427 			return res;
428 	}
429 
430 	return crypto_hash_final(ctx, alg, digest, TEE_FS_HTREE_HASH_SIZE);
431 }
432 
433 static TEE_Result authenc_init(void **ctx_ret, TEE_OperationMode mode,
434 			       struct tee_fs_htree *ht,
435 			       struct tee_fs_htree_node_image *ni,
436 			       size_t payload_len)
437 {
438 	TEE_Result res = TEE_SUCCESS;
439 	const uint32_t alg = TEE_FS_HTREE_AUTH_ENC_ALG;
440 	uint8_t *ctx;
441 	size_t ctx_size;
442 	size_t aad_len = TEE_FS_HTREE_FEK_SIZE + TEE_FS_HTREE_IV_SIZE;
443 	uint8_t *iv;
444 
445 	if (ni) {
446 		iv = ni->iv;
447 	} else {
448 		iv = ht->head.iv;
449 		aad_len += TEE_FS_HTREE_HASH_SIZE + sizeof(ht->head.counter);
450 	}
451 
452 	if (mode == TEE_MODE_ENCRYPT) {
453 		res = crypto_rng_read(iv, TEE_FS_HTREE_IV_SIZE);
454 		if (res != TEE_SUCCESS)
455 			return res;
456 	}
457 
458 	res = crypto_authenc_get_ctx_size(alg, &ctx_size);
459 	if (res != TEE_SUCCESS)
460 		return res;
461 
462 	ctx = malloc(ctx_size);
463 	if (!ctx) {
464 		EMSG("request memory size %zu failed", ctx_size);
465 		return TEE_ERROR_OUT_OF_MEMORY;
466 	}
467 
468 	res = crypto_authenc_init(ctx, alg, mode, ht->fek,
469 				  TEE_FS_HTREE_FEK_SIZE, iv,
470 				  TEE_FS_HTREE_IV_SIZE, TEE_FS_HTREE_TAG_SIZE,
471 				  aad_len, payload_len);
472 	if (res != TEE_SUCCESS)
473 		goto exit;
474 
475 	if (!ni) {
476 		res = crypto_authenc_update_aad(ctx, alg, mode,
477 						ht->root.node.hash,
478 						TEE_FS_HTREE_FEK_SIZE);
479 		if (res != TEE_SUCCESS)
480 			goto exit;
481 
482 		res = crypto_authenc_update_aad(ctx, alg, mode,
483 						(void *)&ht->head.counter,
484 						sizeof(ht->head.counter));
485 		if (res != TEE_SUCCESS)
486 			goto exit;
487 	}
488 
489 	res = crypto_authenc_update_aad(ctx, alg, mode, ht->head.enc_fek,
490 					TEE_FS_HTREE_FEK_SIZE);
491 	if (res != TEE_SUCCESS)
492 		goto exit;
493 
494 	res = crypto_authenc_update_aad(ctx, alg, mode, iv,
495 					TEE_FS_HTREE_IV_SIZE);
496 
497 exit:
498 	if (res == TEE_SUCCESS)
499 		*ctx_ret = ctx;
500 	else
501 		free(ctx);
502 
503 	return res;
504 }
505 
506 static TEE_Result authenc_decrypt_final(void *ctx, const uint8_t *tag,
507 					const void *crypt, size_t len,
508 					void *plain)
509 {
510 	TEE_Result res;
511 	size_t out_size = len;
512 
513 	res = crypto_authenc_dec_final(ctx, TEE_FS_HTREE_AUTH_ENC_ALG, crypt,
514 				       len, plain, &out_size, tag,
515 				       TEE_FS_HTREE_TAG_SIZE);
516 	crypto_authenc_final(ctx, TEE_FS_HTREE_AUTH_ENC_ALG);
517 	free(ctx);
518 
519 	if (res == TEE_SUCCESS && out_size != len)
520 		return TEE_ERROR_GENERIC;
521 	if (res == TEE_ERROR_MAC_INVALID)
522 		return TEE_ERROR_CORRUPT_OBJECT;
523 
524 	return res;
525 }
526 
527 static TEE_Result authenc_encrypt_final(void *ctx, uint8_t *tag,
528 					const void *plain, size_t len,
529 					void *crypt)
530 {
531 	TEE_Result res;
532 	size_t out_size = len;
533 	size_t out_tag_size = TEE_FS_HTREE_TAG_SIZE;
534 
535 	res = crypto_authenc_enc_final(ctx, TEE_FS_HTREE_AUTH_ENC_ALG, plain,
536 				       len, crypt, &out_size, tag,
537 				       &out_tag_size);
538 	crypto_authenc_final(ctx, TEE_FS_HTREE_AUTH_ENC_ALG);
539 	free(ctx);
540 
541 	if (res == TEE_SUCCESS &&
542 	    (out_size != len || out_tag_size != TEE_FS_HTREE_TAG_SIZE))
543 		return TEE_ERROR_GENERIC;
544 
545 	return res;
546 }
547 
548 static TEE_Result verify_root(struct tee_fs_htree *ht)
549 {
550 	TEE_Result res;
551 	void *ctx;
552 
553 	res = tee_fs_fek_crypt(ht->uuid, TEE_MODE_DECRYPT, ht->head.enc_fek,
554 			       sizeof(ht->fek), ht->fek);
555 	if (res != TEE_SUCCESS)
556 		return res;
557 
558 	res = authenc_init(&ctx, TEE_MODE_DECRYPT, ht, NULL, sizeof(ht->imeta));
559 	if (res != TEE_SUCCESS)
560 		return res;
561 
562 	return authenc_decrypt_final(ctx, ht->head.tag, ht->head.imeta,
563 				     sizeof(ht->imeta), &ht->imeta);
564 }
565 
566 static TEE_Result verify_node(struct traverse_arg *targ,
567 			      struct htree_node *node)
568 {
569 	void *ctx = targ->arg;
570 	TEE_Result res;
571 	uint8_t digest[TEE_FS_HTREE_HASH_SIZE];
572 
573 	res = calc_node_hash(node, ctx, digest);
574 	if (res == TEE_SUCCESS &&
575 	    buf_compare_ct(digest, node->node.hash, sizeof(digest)))
576 		return TEE_ERROR_CORRUPT_OBJECT;
577 
578 	return res;
579 }
580 
581 static TEE_Result verify_tree(struct tee_fs_htree *ht)
582 {
583 	TEE_Result res;
584 	size_t size;
585 	void *ctx;
586 
587 	res = crypto_hash_get_ctx_size(TEE_FS_HTREE_HASH_ALG, &size);
588 	if (res != TEE_SUCCESS)
589 		return res;
590 
591 	ctx = malloc(size);
592 	if (!ctx)
593 		return TEE_ERROR_OUT_OF_MEMORY;
594 
595 	res = htree_traverse_post_order(ht, verify_node, ctx);
596 	free(ctx);
597 
598 	return res;
599 }
600 
601 static TEE_Result init_root_node(struct tee_fs_htree *ht)
602 {
603 	TEE_Result res;
604 	size_t size;
605 	void *ctx;
606 
607 	res = crypto_hash_get_ctx_size(TEE_FS_HTREE_HASH_ALG, &size);
608 	if (res != TEE_SUCCESS)
609 		return res;
610 	ctx = malloc(size);
611 	if (!ctx)
612 		return TEE_ERROR_OUT_OF_MEMORY;
613 
614 	ht->root.id = 1;
615 	ht->root.dirty = true;
616 
617 	res = calc_node_hash(&ht->root, ctx, ht->root.node.hash);
618 	free(ctx);
619 
620 	return res;
621 }
622 
623 TEE_Result tee_fs_htree_open(bool create, uint8_t *hash, const TEE_UUID *uuid,
624 			     const struct tee_fs_htree_storage *stor,
625 			     void *stor_aux, struct tee_fs_htree **ht_ret)
626 {
627 	TEE_Result res;
628 	struct tee_fs_htree *ht = calloc(1, sizeof(*ht));
629 
630 	if (!ht)
631 		return TEE_ERROR_OUT_OF_MEMORY;
632 
633 	ht->uuid = uuid;
634 	ht->stor = stor;
635 	ht->stor_aux = stor_aux;
636 
637 	if (create) {
638 		const struct tee_fs_htree_image dummy_head = { .counter = 0 };
639 
640 		res = crypto_rng_read(ht->fek, sizeof(ht->fek));
641 		if (res != TEE_SUCCESS)
642 			goto out;
643 
644 		res = tee_fs_fek_crypt(ht->uuid, TEE_MODE_ENCRYPT, ht->fek,
645 				       sizeof(ht->fek), ht->head.enc_fek);
646 		if (res != TEE_SUCCESS)
647 			goto out;
648 
649 		res = init_root_node(ht);
650 		if (res != TEE_SUCCESS)
651 			goto out;
652 
653 		ht->dirty = true;
654 		res = tee_fs_htree_sync_to_storage(&ht, hash);
655 		if (res != TEE_SUCCESS)
656 			goto out;
657 		res = rpc_write_head(ht, 0, &dummy_head);
658 	} else {
659 		res = init_head_from_data(ht, hash);
660 		if (res != TEE_SUCCESS)
661 			goto out;
662 
663 		res = verify_root(ht);
664 		if (res != TEE_SUCCESS)
665 			goto out;
666 
667 		res = init_tree_from_data(ht);
668 		if (res != TEE_SUCCESS)
669 			goto out;
670 
671 		res = verify_tree(ht);
672 	}
673 out:
674 	if (res == TEE_SUCCESS)
675 		*ht_ret = ht;
676 	else
677 		tee_fs_htree_close(&ht);
678 	return res;
679 }
680 
681 struct tee_fs_htree_meta *tee_fs_htree_get_meta(struct tee_fs_htree *ht)
682 {
683 	return &ht->imeta.meta;
684 }
685 
686 static TEE_Result free_node(struct traverse_arg *targ __unused,
687 			    struct htree_node *node)
688 {
689 	if (node->parent)
690 		free(node);
691 	return TEE_SUCCESS;
692 }
693 
694 void tee_fs_htree_close(struct tee_fs_htree **ht)
695 {
696 	if (!*ht)
697 		return;
698 	htree_traverse_post_order(*ht, free_node, NULL);
699 	free(*ht);
700 	*ht = NULL;
701 }
702 
703 static TEE_Result htree_sync_node_to_storage(struct traverse_arg *targ,
704 					     struct htree_node *node)
705 {
706 	TEE_Result res;
707 	uint8_t vers;
708 
709 	/*
710 	 * The node can be dirty while the block isn't updated due to
711 	 * updated children, but if block is updated the node has to be
712 	 * dirty.
713 	 */
714 	assert(node->dirty >= node->block_updated);
715 
716 	if (!node->dirty)
717 		return TEE_SUCCESS;
718 
719 	if (node->parent) {
720 		uint32_t f = HTREE_NODE_COMMITTED_CHILD(node->id & 1);
721 
722 		node->parent->dirty = true;
723 		node->parent->node.flags ^= f;
724 		vers = !!(node->parent->node.flags & f);
725 	} else {
726 		/*
727 		 * Counter isn't updated yet, it's increased just before
728 		 * writing the header.
729 		 */
730 		vers = !(targ->ht->head.counter & 1);
731 	}
732 
733 	res = calc_node_hash(node, targ->arg, node->node.hash);
734 	if (res != TEE_SUCCESS)
735 		return res;
736 
737 	node->dirty = false;
738 	node->block_updated = false;
739 
740 	return rpc_write_node(targ->ht, node->id, vers, &node->node);
741 }
742 
743 static TEE_Result update_root(struct tee_fs_htree *ht)
744 {
745 	TEE_Result res;
746 	void *ctx;
747 
748 	ht->head.counter++;
749 
750 	res = authenc_init(&ctx, TEE_MODE_ENCRYPT, ht, NULL, sizeof(ht->imeta));
751 	if (res != TEE_SUCCESS)
752 		return res;
753 
754 	return authenc_encrypt_final(ctx, ht->head.tag, &ht->imeta,
755 				     sizeof(ht->imeta), &ht->head.imeta);
756 }
757 
758 TEE_Result tee_fs_htree_sync_to_storage(struct tee_fs_htree **ht_arg,
759 					uint8_t *hash)
760 {
761 	TEE_Result res;
762 	struct tee_fs_htree *ht = *ht_arg;
763 	size_t size;
764 	void *ctx;
765 
766 	if (!ht)
767 		return TEE_ERROR_CORRUPT_OBJECT;
768 
769 	if (!ht->dirty)
770 		return TEE_SUCCESS;
771 
772 	res = crypto_hash_get_ctx_size(TEE_FS_HTREE_HASH_ALG, &size);
773 	if (res != TEE_SUCCESS)
774 		return res;
775 	ctx = malloc(size);
776 	if (!ctx)
777 		return TEE_ERROR_OUT_OF_MEMORY;
778 
779 	res = htree_traverse_post_order(ht, htree_sync_node_to_storage, ctx);
780 	if (res != TEE_SUCCESS)
781 		goto out;
782 
783 	/* All the nodes are written to storage now. Time to update root. */
784 	res = update_root(ht);
785 	if (res != TEE_SUCCESS)
786 		goto out;
787 
788 	res = rpc_write_head(ht, ht->head.counter & 1, &ht->head);
789 	if (res != TEE_SUCCESS)
790 		goto out;
791 
792 	ht->dirty = false;
793 	if (hash)
794 		memcpy(hash, ht->root.node.hash, sizeof(ht->root.node.hash));
795 out:
796 	free(ctx);
797 	if (res != TEE_SUCCESS)
798 		tee_fs_htree_close(ht_arg);
799 	return res;
800 }
801 
802 static TEE_Result get_block_node(struct tee_fs_htree *ht, bool create,
803 				 size_t block_num, struct htree_node **node)
804 {
805 	TEE_Result res;
806 	struct htree_node *nd;
807 
808 	res = get_node(ht, create, BLOCK_NUM_TO_NODE_ID(block_num), &nd);
809 	if (res == TEE_SUCCESS)
810 		*node = nd;
811 
812 	return res;
813 }
814 
815 TEE_Result tee_fs_htree_write_block(struct tee_fs_htree **ht_arg,
816 				    size_t block_num, const void *block)
817 {
818 	struct tee_fs_htree *ht = *ht_arg;
819 	TEE_Result res;
820 	struct tee_fs_rpc_operation op;
821 	struct htree_node *node = NULL;
822 	uint8_t block_vers;
823 	void *ctx;
824 	void *enc_block;
825 
826 	if (!ht)
827 		return TEE_ERROR_CORRUPT_OBJECT;
828 
829 	res = get_block_node(ht, true, block_num, &node);
830 	if (res != TEE_SUCCESS)
831 		goto out;
832 
833 	if (!node->block_updated)
834 		node->node.flags ^= HTREE_NODE_COMMITTED_BLOCK;
835 
836 	block_vers = !!(node->node.flags & HTREE_NODE_COMMITTED_BLOCK);
837 	res = ht->stor->rpc_write_init(ht->stor_aux, &op,
838 				       TEE_FS_HTREE_TYPE_BLOCK, block_num,
839 				       block_vers, &enc_block);
840 	if (res != TEE_SUCCESS)
841 		goto out;
842 
843 	res = authenc_init(&ctx, TEE_MODE_ENCRYPT, ht, &node->node,
844 			   ht->stor->block_size);
845 	if (res != TEE_SUCCESS)
846 		goto out;
847 	res = authenc_encrypt_final(ctx, node->node.tag, block,
848 				    ht->stor->block_size, enc_block);
849 	if (res != TEE_SUCCESS)
850 		goto out;
851 
852 	res = ht->stor->rpc_write_final(&op);
853 	if (res != TEE_SUCCESS)
854 		goto out;
855 
856 	node->block_updated = true;
857 	node->dirty = true;
858 	ht->dirty = true;
859 out:
860 	if (res != TEE_SUCCESS)
861 		tee_fs_htree_close(ht_arg);
862 	return res;
863 }
864 
865 TEE_Result tee_fs_htree_read_block(struct tee_fs_htree **ht_arg,
866 				   size_t block_num, void *block)
867 {
868 	struct tee_fs_htree *ht = *ht_arg;
869 	TEE_Result res;
870 	struct tee_fs_rpc_operation op;
871 	struct htree_node *node;
872 	uint8_t block_vers;
873 	size_t len;
874 	void *ctx;
875 	void *enc_block;
876 
877 	if (!ht)
878 		return TEE_ERROR_CORRUPT_OBJECT;
879 
880 	res = get_block_node(ht, false, block_num, &node);
881 	if (res != TEE_SUCCESS)
882 		goto out;
883 
884 	block_vers = !!(node->node.flags & HTREE_NODE_COMMITTED_BLOCK);
885 	res = ht->stor->rpc_read_init(ht->stor_aux, &op,
886 				      TEE_FS_HTREE_TYPE_BLOCK, block_num,
887 				      block_vers, &enc_block);
888 	if (res != TEE_SUCCESS)
889 		goto out;
890 
891 	res = ht->stor->rpc_read_final(&op, &len);
892 	if (res != TEE_SUCCESS)
893 		goto out;
894 	if (len != ht->stor->block_size) {
895 		res = TEE_ERROR_CORRUPT_OBJECT;
896 		goto out;
897 	}
898 
899 	res = authenc_init(&ctx, TEE_MODE_DECRYPT, ht, &node->node,
900 			   ht->stor->block_size);
901 	if (res != TEE_SUCCESS)
902 		goto out;
903 
904 	res = authenc_decrypt_final(ctx, node->node.tag, enc_block,
905 				    ht->stor->block_size, block);
906 out:
907 	if (res != TEE_SUCCESS)
908 		tee_fs_htree_close(ht_arg);
909 	return res;
910 }
911 
912 TEE_Result tee_fs_htree_truncate(struct tee_fs_htree **ht_arg, size_t block_num)
913 {
914 	struct tee_fs_htree *ht = *ht_arg;
915 	size_t node_id = BLOCK_NUM_TO_NODE_ID(block_num);
916 	struct htree_node *node;
917 
918 	if (!ht)
919 		return TEE_ERROR_CORRUPT_OBJECT;
920 
921 	while (node_id < ht->imeta.max_node_id) {
922 		node = find_closest_node(ht, ht->imeta.max_node_id);
923 		assert(node && node->id == ht->imeta.max_node_id);
924 		assert(!node->child[0] && !node->child[1]);
925 		assert(node->parent);
926 		assert(node->parent->child[node->id & 1] == node);
927 		node->parent->child[node->id & 1] = NULL;
928 		free(node);
929 		ht->imeta.max_node_id--;
930 		ht->dirty = true;
931 	}
932 
933 	return TEE_SUCCESS;
934 }
935