xref: /optee_os/core/tee/fs_htree.c (revision f28e506057504d325272c7848ed062b36444b7cf)
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. In the case of SQL FS the version of the node/block is ignored
96  * as the atomic update is finalized with a call to
97  * tee_fs_rpc_end_transaction().
98  */
99 
100 #define HTREE_NODE_COMMITTED_BLOCK	BIT32(0)
101 /* n is 0 or 1 */
102 #define HTREE_NODE_COMMITTED_CHILD(n)	BIT32(1 + (n))
103 
104 struct htree_node {
105 	size_t id;
106 	bool dirty;
107 	bool block_updated;
108 	struct tee_fs_htree_node_image node;
109 	struct htree_node *parent;
110 	struct htree_node *child[2];
111 };
112 
113 struct tee_fs_htree {
114 	struct htree_node root;
115 	struct tee_fs_htree_image head;
116 	uint8_t fek[TEE_FS_HTREE_FEK_SIZE];
117 	struct tee_fs_htree_imeta imeta;
118 	bool dirty;
119 	const struct tee_fs_htree_storage *stor;
120 	void *stor_aux;
121 };
122 
123 struct traverse_arg;
124 typedef TEE_Result (*traverse_cb_t)(struct traverse_arg *targ,
125 				    struct htree_node *node);
126 struct traverse_arg {
127 	struct tee_fs_htree *ht;
128 	traverse_cb_t cb;
129 	void *arg;
130 };
131 
132 static TEE_Result rpc_read(struct tee_fs_htree *ht, enum tee_fs_htree_type type,
133 			   size_t idx, size_t vers, void *data, size_t dlen)
134 {
135 	TEE_Result res;
136 	struct tee_fs_rpc_operation op;
137 	size_t bytes;
138 	void *p;
139 
140 	res = ht->stor->rpc_read_init(ht->stor_aux, &op, type, idx, vers, &p);
141 	if (res != TEE_SUCCESS)
142 		return res;
143 
144 	res = ht->stor->rpc_read_final(&op, &bytes);
145 	if (res != TEE_SUCCESS)
146 		return res;
147 
148 	if (bytes != dlen)
149 		return TEE_ERROR_CORRUPT_OBJECT;
150 
151 	memcpy(data, p, dlen);
152 	return TEE_SUCCESS;
153 }
154 
155 static TEE_Result rpc_read_head(struct tee_fs_htree *ht, size_t vers,
156 				struct tee_fs_htree_image *head)
157 {
158 	return rpc_read(ht, TEE_FS_HTREE_TYPE_HEAD, 0, vers,
159 			head, sizeof(*head));
160 }
161 
162 static TEE_Result rpc_read_node(struct tee_fs_htree *ht, size_t node_id,
163 				size_t vers,
164 				struct tee_fs_htree_node_image *node)
165 {
166 	return rpc_read(ht, TEE_FS_HTREE_TYPE_NODE, node_id - 1, vers,
167 			node, sizeof(*node));
168 }
169 
170 static TEE_Result rpc_write(struct tee_fs_htree *ht,
171 			    enum tee_fs_htree_type type, size_t idx,
172 			    size_t vers, const void *data, size_t dlen)
173 {
174 	TEE_Result res;
175 	struct tee_fs_rpc_operation op;
176 	void *p;
177 
178 	res = ht->stor->rpc_write_init(ht->stor_aux, &op, type, idx, vers, &p);
179 	if (res != TEE_SUCCESS)
180 		return res;
181 
182 	memcpy(p, data, dlen);
183 	return ht->stor->rpc_write_final(&op);
184 }
185 
186 static TEE_Result rpc_write_head(struct tee_fs_htree *ht, size_t vers,
187 				 const struct tee_fs_htree_image *head)
188 {
189 	return rpc_write(ht, TEE_FS_HTREE_TYPE_HEAD, 0, vers,
190 			 head, sizeof(*head));
191 }
192 
193 static TEE_Result rpc_write_node(struct tee_fs_htree *ht, size_t node_id,
194 				 size_t vers,
195 				 const struct tee_fs_htree_node_image *node)
196 {
197 	return rpc_write(ht, TEE_FS_HTREE_TYPE_NODE, node_id - 1, vers,
198 			 node, sizeof(*node));
199 }
200 
201 static TEE_Result traverse_post_order(struct traverse_arg *targ,
202 				      struct htree_node *node)
203 {
204 	TEE_Result res;
205 
206 	/*
207 	 * This function is recursing but not very deep, only with Log(N)
208 	 * maximum depth.
209 	 */
210 
211 	if (!node)
212 		return TEE_SUCCESS;
213 
214 	res = traverse_post_order(targ, node->child[0]);
215 	if (res != TEE_SUCCESS)
216 		return res;
217 
218 	res = traverse_post_order(targ, node->child[1]);
219 	if (res != TEE_SUCCESS)
220 		return res;
221 
222 	return targ->cb(targ, node);
223 }
224 
225 static TEE_Result htree_traverse_post_order(struct tee_fs_htree *ht,
226 					    traverse_cb_t cb, void *arg)
227 {
228 	struct traverse_arg targ = { ht, cb, arg };
229 
230 	return traverse_post_order(&targ, &ht->root);
231 }
232 
233 static size_t node_id_to_level(size_t node_id)
234 {
235 	assert(node_id && node_id < UINT_MAX);
236 	/* Calculate level of the node, root node (1) has level 1 */
237 	return sizeof(unsigned int) * 8 - __builtin_clz(node_id);
238 }
239 
240 static struct htree_node *find_closest_node(struct tee_fs_htree *ht,
241 					    size_t node_id)
242 {
243 	struct htree_node *node = &ht->root;
244 	size_t level = node_id_to_level(node_id);
245 	size_t n;
246 
247 	/* n = 1 because root node is level 1 */
248 	for (n = 1; n < level; n++) {
249 		struct htree_node *child;
250 		size_t bit_idx;
251 
252 		/*
253 		 * The difference between levels of the current node and
254 		 * the node we're looking for tells which bit decides
255 		 * direction in the tree.
256 		 *
257 		 * As the first bit has index 0 we'll subtract 1
258 		 */
259 		bit_idx = level - n - 1;
260 		child = node->child[((node_id >> bit_idx) & 1)];
261 		if (!child)
262 			return node;
263 		node = child;
264 	}
265 
266 	return node;
267 }
268 
269 static struct htree_node *find_node(struct tee_fs_htree *ht, size_t node_id)
270 {
271 	struct htree_node *node = find_closest_node(ht, node_id);
272 
273 	if (node && node->id == node_id)
274 		return node;
275 	return NULL;
276 }
277 
278 static TEE_Result get_node(struct tee_fs_htree *ht, bool create,
279 			   size_t node_id, struct htree_node **node_ret)
280 {
281 	struct htree_node *node;
282 	struct htree_node *nc;
283 	size_t n;
284 
285 	node = find_closest_node(ht, node_id);
286 	if (!node)
287 		return TEE_ERROR_GENERIC;
288 	if (node->id == node_id)
289 		goto ret_node;
290 
291 	/*
292 	 * Trying to read beyond end of file should be caught earlier than
293 	 * here.
294 	 */
295 	if (!create)
296 		return TEE_ERROR_GENERIC;
297 
298 	/*
299 	 * Add missing nodes, some nodes may already be there. When we've
300 	 * processed the range all nodes up to node_id will be in the tree.
301 	 */
302 	for (n = node->id + 1; n <= node_id; n++) {
303 		node = find_closest_node(ht, n);
304 		if (node->id == n)
305 			continue;
306 		/* Node id n should be a child of node */
307 		assert((n >> 1) == node->id);
308 		assert(!node->child[n & 1]);
309 
310 		nc = calloc(1, sizeof(*nc));
311 		if (!nc)
312 			return TEE_ERROR_OUT_OF_MEMORY;
313 		nc->id = n;
314 		nc->parent = node;
315 		node->child[n & 1] = nc;
316 		node = nc;
317 	}
318 
319 	if (node->id > ht->imeta.max_node_id)
320 		ht->imeta.max_node_id = node->id;
321 
322 ret_node:
323 	*node_ret = node;
324 	return TEE_SUCCESS;
325 }
326 
327 static int get_idx_from_counter(uint32_t counter0, uint32_t counter1)
328 {
329 	if (!(counter0 & 1)) {
330 		if (!(counter1 & 1))
331 			return 0;
332 		if (counter0 > counter1)
333 			return 0;
334 		else
335 			return 1;
336 	}
337 
338 	if (counter1 & 1)
339 		return 1;
340 	else
341 		return -1;
342 }
343 
344 static TEE_Result init_head_from_data(struct tee_fs_htree *ht,
345 				      const uint8_t *hash)
346 {
347 	TEE_Result res;
348 	int idx;
349 
350 	if (hash) {
351 		for (idx = 0;; idx++) {
352 			res = rpc_read_node(ht, 1, idx, &ht->root.node);
353 			if (res != TEE_SUCCESS)
354 				return res;
355 
356 			if (!memcmp(ht->root.node.hash, hash,
357 				    sizeof(ht->root.node.hash))) {
358 				res = rpc_read_head(ht, idx, &ht->head);
359 				if (res != TEE_SUCCESS)
360 					return res;
361 				break;
362 			}
363 
364 			if (idx)
365 				return TEE_ERROR_SECURITY;
366 		}
367 	} else {
368 		struct tee_fs_htree_image head[2];
369 
370 		for (idx = 0; idx < 2; idx++) {
371 			res = rpc_read_head(ht, idx, head + idx);
372 			if (res != TEE_SUCCESS)
373 				return res;
374 		}
375 
376 		idx = get_idx_from_counter(head[0].counter, head[1].counter);
377 		if (idx < 0)
378 			return TEE_ERROR_SECURITY;
379 
380 		res = rpc_read_node(ht, 1, idx, &ht->root.node);
381 		if (res != TEE_SUCCESS)
382 			return res;
383 
384 		ht->head = head[idx];
385 	}
386 
387 	ht->root.id = 1;
388 
389 	return TEE_SUCCESS;
390 }
391 
392 static TEE_Result init_tree_from_data(struct tee_fs_htree *ht)
393 {
394 	TEE_Result res;
395 	struct tee_fs_htree_node_image node_image;
396 	struct htree_node *node;
397 	struct htree_node *nc;
398 	size_t committed_version;
399 	size_t node_id = 2;
400 
401 	while (node_id <= ht->imeta.max_node_id) {
402 		node = find_node(ht, node_id >> 1);
403 		if (!node)
404 			return TEE_ERROR_GENERIC;
405 		committed_version = !!(node->node.flags &
406 				    HTREE_NODE_COMMITTED_CHILD(node_id & 1));
407 
408 		res = rpc_read_node(ht, node_id, committed_version,
409 				    &node_image);
410 		if (res != TEE_SUCCESS)
411 			return res;
412 
413 		res = get_node(ht, true, node_id, &nc);
414 		if (res != TEE_SUCCESS)
415 			return res;
416 		nc->node = node_image;
417 		node_id++;
418 	}
419 
420 	return TEE_SUCCESS;
421 }
422 
423 static TEE_Result calc_node_hash(struct htree_node *node, void *ctx,
424 				 uint8_t *digest)
425 {
426 	TEE_Result res;
427 	uint32_t alg = TEE_FS_HTREE_HASH_ALG;
428 	uint8_t *ndata = (uint8_t *)&node->node + sizeof(node->node.hash);
429 	size_t nsize = sizeof(node->node) - sizeof(node->node.hash);
430 
431 	res = crypto_ops.hash.init(ctx, alg);
432 	if (res != TEE_SUCCESS)
433 		return res;
434 
435 	res = crypto_ops.hash.update(ctx, alg, ndata, nsize);
436 	if (res != TEE_SUCCESS)
437 		return res;
438 
439 	if (node->child[0]) {
440 		res = crypto_ops.hash.update(ctx, alg,
441 					     node->child[0]->node.hash,
442 					     sizeof(node->child[0]->node.hash));
443 		if (res != TEE_SUCCESS)
444 			return res;
445 	}
446 
447 	if (node->child[1]) {
448 		res = crypto_ops.hash.update(ctx, alg,
449 					     node->child[1]->node.hash,
450 					     sizeof(node->child[1]->node.hash));
451 		if (res != TEE_SUCCESS)
452 			return res;
453 	}
454 
455 	return crypto_ops.hash.final(ctx, alg, digest, TEE_FS_HTREE_HASH_SIZE);
456 }
457 
458 static TEE_Result authenc_init(void **ctx_ret, TEE_OperationMode mode,
459 			       struct tee_fs_htree *ht,
460 			       struct tee_fs_htree_node_image *ni,
461 			       size_t payload_len)
462 {
463 	TEE_Result res = TEE_SUCCESS;
464 	const uint32_t alg = TEE_FS_HTREE_AUTH_ENC_ALG;
465 	uint8_t *ctx;
466 	size_t ctx_size;
467 	size_t aad_len = TEE_FS_HTREE_FEK_SIZE + TEE_FS_HTREE_IV_SIZE;
468 	uint8_t *iv;
469 
470 	if (ni) {
471 		iv = ni->iv;
472 	} else {
473 		iv = ht->head.iv;
474 		aad_len += TEE_FS_HTREE_HASH_SIZE + sizeof(ht->head.counter);
475 	}
476 
477 	if (mode == TEE_MODE_ENCRYPT) {
478 		res = crypto_ops.prng.read(iv, TEE_FS_HTREE_IV_SIZE);
479 		if (res != TEE_SUCCESS)
480 			return res;
481 	}
482 
483 	res = crypto_ops.authenc.get_ctx_size(alg, &ctx_size);
484 	if (res != TEE_SUCCESS)
485 		return res;
486 
487 	ctx = malloc(ctx_size);
488 	if (!ctx) {
489 		EMSG("request memory size %zu failed", ctx_size);
490 		return TEE_ERROR_OUT_OF_MEMORY;
491 	}
492 
493 	res = crypto_ops.authenc.init(ctx, alg, mode,
494 				      ht->fek, TEE_FS_HTREE_FEK_SIZE,
495 				      iv, TEE_FS_HTREE_IV_SIZE,
496 				      TEE_FS_HTREE_TAG_SIZE, aad_len,
497 				      payload_len);
498 	if (res != TEE_SUCCESS)
499 		goto exit;
500 
501 	if (!ni) {
502 		res = crypto_ops.authenc.update_aad(ctx, alg, mode,
503 						    ht->root.node.hash,
504 						    TEE_FS_HTREE_FEK_SIZE);
505 		if (res != TEE_SUCCESS)
506 			goto exit;
507 
508 		res = crypto_ops.authenc.update_aad(ctx, alg, mode,
509 						    (void *)&ht->head.counter,
510 						    sizeof(ht->head.counter));
511 		if (res != TEE_SUCCESS)
512 			goto exit;
513 	}
514 
515 	res = crypto_ops.authenc.update_aad(ctx, alg, mode, ht->head.enc_fek,
516 					    TEE_FS_HTREE_FEK_SIZE);
517 	if (res != TEE_SUCCESS)
518 		goto exit;
519 
520 	res = crypto_ops.authenc.update_aad(ctx, alg, mode, iv,
521 					    TEE_FS_HTREE_IV_SIZE);
522 
523 exit:
524 	if (res == TEE_SUCCESS)
525 		*ctx_ret = ctx;
526 	else
527 		free(ctx);
528 
529 	return res;
530 }
531 
532 static TEE_Result authenc_decrypt_final(void *ctx, const uint8_t *tag,
533 					const void *crypt, size_t len,
534 					void *plain)
535 {
536 	TEE_Result res;
537 	size_t out_size = len;
538 
539 	res = crypto_ops.authenc.dec_final(ctx, TEE_FS_HTREE_AUTH_ENC_ALG,
540 					   crypt, len, plain, &out_size,
541 					   tag, TEE_FS_HTREE_TAG_SIZE);
542 	crypto_ops.authenc.final(ctx, TEE_FS_HTREE_AUTH_ENC_ALG);
543 	free(ctx);
544 
545 	if (res == TEE_SUCCESS && out_size != len)
546 		return TEE_ERROR_GENERIC;
547 	if (res == TEE_ERROR_MAC_INVALID)
548 		return TEE_ERROR_CORRUPT_OBJECT;
549 
550 	return res;
551 }
552 
553 static TEE_Result authenc_encrypt_final(void *ctx, uint8_t *tag,
554 					const void *plain, size_t len,
555 					void *crypt)
556 {
557 	TEE_Result res;
558 	size_t out_size = len;
559 	size_t out_tag_size = TEE_FS_HTREE_TAG_SIZE;
560 
561 	res = crypto_ops.authenc.enc_final(ctx, TEE_FS_HTREE_AUTH_ENC_ALG,
562 					   plain, len, crypt, &out_size,
563 					   tag, &out_tag_size);
564 	crypto_ops.authenc.final(ctx, TEE_FS_HTREE_AUTH_ENC_ALG);
565 	free(ctx);
566 
567 	if (res == TEE_SUCCESS &&
568 	    (out_size != len || out_tag_size != TEE_FS_HTREE_TAG_SIZE))
569 		return TEE_ERROR_GENERIC;
570 
571 	return res;
572 }
573 
574 static TEE_Result verify_root(struct tee_fs_htree *ht)
575 {
576 	TEE_Result res;
577 	void *ctx;
578 
579 	res = tee_fs_fek_crypt(TEE_MODE_DECRYPT, ht->head.enc_fek,
580 			       sizeof(ht->fek), ht->fek);
581 	if (res != TEE_SUCCESS)
582 		return res;
583 
584 	res = authenc_init(&ctx, TEE_MODE_DECRYPT, ht, NULL, sizeof(ht->imeta));
585 	if (res != TEE_SUCCESS)
586 		return res;
587 
588 	return authenc_decrypt_final(ctx, ht->head.tag, ht->head.imeta,
589 				     sizeof(ht->imeta), &ht->imeta);
590 }
591 
592 static TEE_Result verify_node(struct traverse_arg *targ,
593 			      struct htree_node *node)
594 {
595 	void *ctx = targ->arg;
596 	TEE_Result res;
597 	uint8_t digest[TEE_FS_HTREE_HASH_SIZE];
598 
599 	res = calc_node_hash(node, ctx, digest);
600 	if (res == TEE_SUCCESS &&
601 	    buf_compare_ct(digest, node->node.hash, sizeof(digest)))
602 		return TEE_ERROR_CORRUPT_OBJECT;
603 
604 	return res;
605 }
606 
607 static TEE_Result verify_tree(struct tee_fs_htree *ht)
608 {
609 	TEE_Result res;
610 	size_t size;
611 	void *ctx;
612 
613 	if (!crypto_ops.hash.get_ctx_size || !crypto_ops.hash.init ||
614 	    !crypto_ops.hash.update || !crypto_ops.hash.final)
615 		return TEE_ERROR_NOT_SUPPORTED;
616 
617 	res = crypto_ops.hash.get_ctx_size(TEE_FS_HTREE_HASH_ALG, &size);
618 	if (res != TEE_SUCCESS)
619 		return res;
620 
621 	ctx = malloc(size);
622 	if (!ctx)
623 		return TEE_ERROR_OUT_OF_MEMORY;
624 
625 	res = htree_traverse_post_order(ht, verify_node, ctx);
626 	free(ctx);
627 
628 	return res;
629 }
630 
631 static TEE_Result init_root_node(struct tee_fs_htree *ht)
632 {
633 	TEE_Result res;
634 	size_t size;
635 	void *ctx;
636 
637 	res = crypto_ops.hash.get_ctx_size(TEE_FS_HTREE_HASH_ALG, &size);
638 	if (res != TEE_SUCCESS)
639 		return res;
640 	ctx = malloc(size);
641 	if (!ctx)
642 		return TEE_ERROR_OUT_OF_MEMORY;
643 
644 	ht->root.id = 1;
645 
646 	res = calc_node_hash(&ht->root, ctx, ht->root.node.hash);
647 	free(ctx);
648 
649 	return res;
650 }
651 
652 TEE_Result tee_fs_htree_open(bool create, uint8_t *hash,
653 			     const struct tee_fs_htree_storage *stor,
654 			     void *stor_aux, struct tee_fs_htree **ht_ret)
655 {
656 	TEE_Result res;
657 	struct tee_fs_htree *ht = calloc(1, sizeof(*ht));
658 
659 	if (!ht)
660 		return TEE_ERROR_OUT_OF_MEMORY;
661 
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_ops.prng.read(ht->fek, sizeof(ht->fek));
669 		if (res != TEE_SUCCESS)
670 			goto out;
671 
672 		res = tee_fs_fek_crypt(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