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