xref: /optee_os/core/tee/tee_svc_cryp.c (revision a82246113d60ed9872031e70e9a64f186a62cf21)
1 /*
2  * Copyright (c) 2014, STMicroelectronics International N.V.
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 #include <tee_api_types.h>
28 #include <kernel/tee_ta_manager.h>
29 #include <utee_defines.h>
30 #include <mm/tee_mmu.h>
31 #include <tee/tee_svc.h>
32 #include <tee/tee_svc_cryp.h>
33 #include <tee/tee_cryp_utl.h>
34 #include <sys/queue.h>
35 #include <tee/tee_obj.h>
36 #include <tee/tee_cryp_provider.h>
37 #include <trace.h>
38 #include <string_ext.h>
39 #if defined(CFG_CRYPTO_HKDF) || defined(CFG_CRYPTO_CONCAT_KDF) || \
40 	defined(CFG_CRYPTO_PBKDF2)
41 #include <tee_api_defines_extensions.h>
42 #endif
43 #if defined(CFG_CRYPTO_HKDF)
44 #include <tee/tee_cryp_hkdf.h>
45 #endif
46 #if defined(CFG_CRYPTO_CONCAT_KDF)
47 #include <tee/tee_cryp_concat_kdf.h>
48 #endif
49 #if defined(CFG_CRYPTO_PBKDF2)
50 #include <tee/tee_cryp_pbkdf2.h>
51 #endif
52 
53 /* Set an attribute on an object */
54 #define SET_ATTRIBUTE(_object, _props, _attr)	\
55 	((_object)->have_attrs |= \
56 		(1 << (tee_svc_cryp_obj_find_type_attr_idx((_attr), (_props)))))
57 
58 /* Get an attribute on an object */
59 #define GET_ATTRIBUTE(_object, _props, _attr)	\
60 	((_object)->have_attrs & \
61 		(1 << (tee_svc_cryp_obj_find_type_attr_idx((_attr), (_props)))))
62 
63 #define TEE_USAGE_DEFAULT   0xffffffff
64 
65 typedef void (*tee_cryp_ctx_finalize_func_t) (void *ctx, uint32_t algo);
66 struct tee_cryp_state {
67 	TAILQ_ENTRY(tee_cryp_state) link;
68 	uint32_t algo;
69 	uint32_t mode;
70 	uint32_t key1;
71 	uint32_t key2;
72 	size_t ctx_size;
73 	void *ctx;
74 	tee_cryp_ctx_finalize_func_t ctx_finalize;
75 };
76 
77 struct tee_cryp_obj_secret {
78 	uint32_t key_size;
79 
80 	/*
81 	 * Pseudo code visualize layout of structure
82 	 * Next follows data, such as:
83 	 *	uint8_t data[key_size]
84 	 * key_size must never exceed
85 	 * (obj->data_size - sizeof(struct tee_cryp_obj_secret)).
86 	 */
87 };
88 
89 #define TEE_TYPE_ATTR_OPTIONAL       0x0
90 #define TEE_TYPE_ATTR_REQUIRED       0x1
91 #define TEE_TYPE_ATTR_OPTIONAL_GROUP 0x2
92 #define TEE_TYPE_ATTR_SIZE_INDICATOR 0x4
93 #define TEE_TYPE_ATTR_GEN_KEY_OPT    0x8
94 #define TEE_TYPE_ATTR_GEN_KEY_REQ    0x10
95 
96 #define TEE_TYPE_CONV_FUNC_NONE       0
97     /* Handle storing of generic secret keys of varying lengths */
98 #define TEE_TYPE_CONV_FUNC_SECRET     1
99     /* Convert to/from big-endian byte array and provider-specific bignum */
100 #define TEE_TYPE_CONV_FUNC_BIGNUM     2
101     /* Convert to/from value attribute depending on direction */
102 #define TEE_TYPE_CONV_FUNC_VALUE      4
103 
104 struct tee_cryp_obj_type_attrs {
105 	uint32_t attr_id;
106 	uint16_t flags;
107 	uint16_t conv_func;
108 	uint16_t raw_offs;
109 	uint16_t raw_size;
110 };
111 
112 #define RAW_DATA(_x, _y)	\
113 	.raw_offs = offsetof(_x, _y), .raw_size = TEE_MEMBER_SIZE(_x, _y)
114 
115 static const struct tee_cryp_obj_type_attrs
116 	tee_cryp_obj_secret_value_attrs[] = {
117 	{
118 	.attr_id = TEE_ATTR_SECRET_VALUE,
119 	.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
120 	.conv_func = TEE_TYPE_CONV_FUNC_SECRET,
121 	.raw_offs = 0,
122 	.raw_size = 0
123 	},
124 };
125 
126 static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_pub_key_attrs[] = {
127 	{
128 	.attr_id = TEE_ATTR_RSA_MODULUS,
129 	.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
130 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
131 	RAW_DATA(struct rsa_public_key, n)
132 	},
133 
134 	{
135 	.attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT,
136 	.flags = TEE_TYPE_ATTR_REQUIRED,
137 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
138 	RAW_DATA(struct rsa_public_key, e)
139 	},
140 };
141 
142 static const struct tee_cryp_obj_type_attrs tee_cryp_obj_rsa_keypair_attrs[] = {
143 	{
144 	.attr_id = TEE_ATTR_RSA_MODULUS,
145 	.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
146 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
147 	RAW_DATA(struct rsa_keypair, n)
148 	},
149 
150 	{
151 	.attr_id = TEE_ATTR_RSA_PUBLIC_EXPONENT,
152 	.flags = TEE_TYPE_ATTR_REQUIRED,
153 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
154 	RAW_DATA(struct rsa_keypair, e)
155 	},
156 
157 	{
158 	.attr_id = TEE_ATTR_RSA_PRIVATE_EXPONENT,
159 	.flags = TEE_TYPE_ATTR_REQUIRED,
160 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
161 	RAW_DATA(struct rsa_keypair, d)
162 	},
163 
164 	{
165 	.attr_id = TEE_ATTR_RSA_PRIME1,
166 	.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP,
167 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
168 	RAW_DATA(struct rsa_keypair, p)
169 	},
170 
171 	{
172 	.attr_id = TEE_ATTR_RSA_PRIME2,
173 	.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP,
174 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
175 	RAW_DATA(struct rsa_keypair, q)
176 	},
177 
178 	{
179 	.attr_id = TEE_ATTR_RSA_EXPONENT1,
180 	.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP,
181 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
182 	RAW_DATA(struct rsa_keypair, dp)
183 	},
184 
185 	{
186 	.attr_id = TEE_ATTR_RSA_EXPONENT2,
187 	.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP,
188 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
189 	RAW_DATA(struct rsa_keypair, dq)
190 	},
191 
192 	{
193 	.attr_id = TEE_ATTR_RSA_COEFFICIENT,
194 	.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP,
195 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
196 	RAW_DATA(struct rsa_keypair, qp)
197 	},
198 };
199 
200 static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_pub_key_attrs[] = {
201 	{
202 	.attr_id = TEE_ATTR_DSA_PRIME,
203 	.flags = TEE_TYPE_ATTR_REQUIRED,
204 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
205 	RAW_DATA(struct dsa_public_key, p)
206 	},
207 
208 	{
209 	.attr_id = TEE_ATTR_DSA_SUBPRIME,
210 	.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
211 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
212 	RAW_DATA(struct dsa_public_key, q)
213 	},
214 
215 	{
216 	.attr_id = TEE_ATTR_DSA_BASE,
217 	.flags = TEE_TYPE_ATTR_REQUIRED,
218 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
219 	RAW_DATA(struct dsa_public_key, g)
220 	},
221 
222 	{
223 	.attr_id = TEE_ATTR_DSA_PUBLIC_VALUE,
224 	.flags = TEE_TYPE_ATTR_REQUIRED,
225 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
226 	RAW_DATA(struct dsa_public_key, y)
227 	},
228 };
229 
230 static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dsa_keypair_attrs[] = {
231 	{
232 	.attr_id = TEE_ATTR_DSA_PRIME,
233 	.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ,
234 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
235 	RAW_DATA(struct dsa_keypair, p)
236 	},
237 
238 	{
239 	.attr_id = TEE_ATTR_DSA_SUBPRIME,
240 	.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR |
241 		 TEE_TYPE_ATTR_GEN_KEY_REQ,
242 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
243 	RAW_DATA(struct dsa_keypair, q)
244 	},
245 
246 	{
247 	.attr_id = TEE_ATTR_DSA_BASE,
248 	.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ,
249 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
250 	RAW_DATA(struct dsa_keypair, g)
251 	},
252 
253 	{
254 	.attr_id = TEE_ATTR_DSA_PRIVATE_VALUE,
255 	.flags = TEE_TYPE_ATTR_REQUIRED,
256 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
257 	RAW_DATA(struct dsa_keypair, x)
258 	},
259 
260 	{
261 	.attr_id = TEE_ATTR_DSA_PUBLIC_VALUE,
262 	.flags = TEE_TYPE_ATTR_REQUIRED,
263 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
264 	RAW_DATA(struct dsa_keypair, y)
265 	},
266 };
267 
268 static const struct tee_cryp_obj_type_attrs tee_cryp_obj_dh_keypair_attrs[] = {
269 	{
270 	.attr_id = TEE_ATTR_DH_PRIME,
271 	.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR |
272 		 TEE_TYPE_ATTR_GEN_KEY_REQ,
273 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
274 	RAW_DATA(struct dh_keypair, p)
275 	},
276 
277 	{
278 	.attr_id = TEE_ATTR_DH_BASE,
279 	.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_GEN_KEY_REQ,
280 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
281 	RAW_DATA(struct dh_keypair, g)
282 	},
283 
284 	{
285 	.attr_id = TEE_ATTR_DH_PUBLIC_VALUE,
286 	.flags = TEE_TYPE_ATTR_REQUIRED,
287 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
288 	RAW_DATA(struct dh_keypair, y)
289 	},
290 
291 	{
292 	.attr_id = TEE_ATTR_DH_PRIVATE_VALUE,
293 	.flags = TEE_TYPE_ATTR_REQUIRED,
294 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
295 	RAW_DATA(struct dh_keypair, x)
296 	},
297 
298 	{
299 	.attr_id = TEE_ATTR_DH_SUBPRIME,
300 	.flags = TEE_TYPE_ATTR_OPTIONAL_GROUP |	 TEE_TYPE_ATTR_GEN_KEY_OPT,
301 	.conv_func = TEE_TYPE_CONV_FUNC_BIGNUM,
302 	RAW_DATA(struct dh_keypair, q)
303 	},
304 
305 	{
306 	.attr_id = TEE_ATTR_DH_X_BITS,
307 	.flags = TEE_TYPE_ATTR_GEN_KEY_OPT,
308 	.conv_func = TEE_TYPE_CONV_FUNC_VALUE,
309 	RAW_DATA(struct dh_keypair, xbits)
310 	},
311 };
312 
313 #if defined(CFG_CRYPTO_HKDF)
314 static const struct tee_cryp_obj_type_attrs
315 	tee_cryp_obj_hkdf_ikm_attrs[] = {
316 	{
317 	.attr_id = TEE_ATTR_HKDF_IKM,
318 	.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
319 	.conv_func = TEE_TYPE_CONV_FUNC_SECRET,
320 	.raw_offs = 0,
321 	.raw_size = 0
322 	},
323 };
324 #endif
325 
326 #if defined(CFG_CRYPTO_CONCAT_KDF)
327 static const struct tee_cryp_obj_type_attrs
328 	tee_cryp_obj_concat_kdf_z_attrs[] = {
329 	{
330 	.attr_id = TEE_ATTR_CONCAT_KDF_Z,
331 	.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
332 	.conv_func = TEE_TYPE_CONV_FUNC_SECRET,
333 	.raw_offs = 0,
334 	.raw_size = 0
335 	},
336 };
337 #endif
338 
339 #if defined(CFG_CRYPTO_PBKDF2)
340 static const struct tee_cryp_obj_type_attrs
341 	tee_cryp_obj_pbkdf2_passwd_attrs[] = {
342 	{
343 	.attr_id = TEE_ATTR_PBKDF2_PASSWORD,
344 	.flags = TEE_TYPE_ATTR_REQUIRED | TEE_TYPE_ATTR_SIZE_INDICATOR,
345 	.conv_func = TEE_TYPE_CONV_FUNC_SECRET,
346 	.raw_offs = 0,
347 	.raw_size = 0
348 	},
349 };
350 #endif
351 
352 struct tee_cryp_obj_type_props {
353 	TEE_ObjectType obj_type;
354 	uint16_t min_size;	/* may not be smaller than this */
355 	uint16_t max_size;	/* may not be larger than this */
356 	uint16_t alloc_size;	/* this many bytes are allocated to hold data */
357 	uint8_t quanta;		/* may only be an multiple of this */
358 
359 	uint8_t num_type_attrs;
360 	const struct tee_cryp_obj_type_attrs *type_attrs;
361 };
362 
363 #define PROP(obj_type, quanta, min_size, max_size, alloc_size, type_attrs) \
364 		{ (obj_type), (min_size), (max_size), (alloc_size), (quanta), \
365 		  TEE_ARRAY_SIZE(type_attrs), (type_attrs) }
366 
367 static const struct tee_cryp_obj_type_props tee_cryp_obj_props[] = {
368 	PROP(TEE_TYPE_AES, 64, 128, 256,	/* valid sizes 128, 192, 256 */
369 		256 / 8 + sizeof(struct tee_cryp_obj_secret),
370 		tee_cryp_obj_secret_value_attrs),
371 	PROP(TEE_TYPE_DES, 56, 56, 56,
372 		/*
373 		* Valid size 56 without parity, note that we still allocate
374 		* for 64 bits since the key is supplied with parity.
375 		*/
376 		64 / 8 + sizeof(struct tee_cryp_obj_secret),
377 		tee_cryp_obj_secret_value_attrs),
378 	PROP(TEE_TYPE_DES3, 56, 112, 168,
379 		/*
380 		* Valid sizes 112, 168 without parity, note that we still
381 		* allocate for with space for the parity since the key is
382 		* supplied with parity.
383 		*/
384 		192 / 8 + sizeof(struct tee_cryp_obj_secret),
385 		tee_cryp_obj_secret_value_attrs),
386 	PROP(TEE_TYPE_HMAC_MD5, 8, 64, 512,
387 		512 / 8 + sizeof(struct tee_cryp_obj_secret),
388 		tee_cryp_obj_secret_value_attrs),
389 	PROP(TEE_TYPE_HMAC_SHA1, 8, 80, 512,
390 		512 / 8 + sizeof(struct tee_cryp_obj_secret),
391 		tee_cryp_obj_secret_value_attrs),
392 	PROP(TEE_TYPE_HMAC_SHA224, 8, 112, 512,
393 		512 / 8 + sizeof(struct tee_cryp_obj_secret),
394 		tee_cryp_obj_secret_value_attrs),
395 	PROP(TEE_TYPE_HMAC_SHA256, 8, 192, 1024,
396 		1024 / 8 + sizeof(struct tee_cryp_obj_secret),
397 		tee_cryp_obj_secret_value_attrs),
398 	PROP(TEE_TYPE_HMAC_SHA384, 8, 256, 1024,
399 		1024 / 8 + sizeof(struct tee_cryp_obj_secret),
400 		tee_cryp_obj_secret_value_attrs),
401 	PROP(TEE_TYPE_HMAC_SHA512, 8, 256, 1024,
402 		1024 / 8 + sizeof(struct tee_cryp_obj_secret),
403 		tee_cryp_obj_secret_value_attrs),
404 	PROP(TEE_TYPE_GENERIC_SECRET, 8, 0, 4096,
405 		4096 / 8 + sizeof(struct tee_cryp_obj_secret),
406 		tee_cryp_obj_secret_value_attrs),
407 #if defined(CFG_CRYPTO_HKDF)
408 	PROP(TEE_TYPE_HKDF_IKM, 8, 0, 4096,
409 		4096 / 8 + sizeof(struct tee_cryp_obj_secret),
410 		tee_cryp_obj_hkdf_ikm_attrs),
411 #endif
412 #if defined(CFG_CRYPTO_CONCAT_KDF)
413 	PROP(TEE_TYPE_CONCAT_KDF_Z, 8, 0, 4096,
414 		4096 / 8 + sizeof(struct tee_cryp_obj_secret),
415 		tee_cryp_obj_concat_kdf_z_attrs),
416 #endif
417 #if defined(CFG_CRYPTO_PBKDF2)
418 	PROP(TEE_TYPE_PBKDF2_PASSWORD, 8, 0, 4096,
419 		4096 / 8 + sizeof(struct tee_cryp_obj_secret),
420 		tee_cryp_obj_pbkdf2_passwd_attrs),
421 #endif
422 	PROP(TEE_TYPE_RSA_PUBLIC_KEY, 1, 256, 2048,
423 		sizeof(struct rsa_public_key),
424 		tee_cryp_obj_rsa_pub_key_attrs),
425 
426 	PROP(TEE_TYPE_RSA_KEYPAIR, 1, 256, 2048,
427 		sizeof(struct rsa_keypair),
428 		tee_cryp_obj_rsa_keypair_attrs),
429 
430 	PROP(TEE_TYPE_DSA_PUBLIC_KEY, 64, 512, 1024,
431 		sizeof(struct dsa_public_key),
432 		tee_cryp_obj_dsa_pub_key_attrs),
433 
434 	PROP(TEE_TYPE_DSA_KEYPAIR, 64, 512, 1024,
435 		sizeof(struct dsa_keypair),
436 		tee_cryp_obj_dsa_keypair_attrs),
437 
438 	PROP(TEE_TYPE_DH_KEYPAIR, 1, 256, 2048,
439 		sizeof(struct dh_keypair),
440 		tee_cryp_obj_dh_keypair_attrs),
441 };
442 
443 TEE_Result tee_svc_cryp_obj_get_info(uint32_t obj, TEE_ObjectInfo *info)
444 {
445 	TEE_Result res;
446 	struct tee_ta_session *sess;
447 	struct tee_obj *o;
448 
449 	res = tee_ta_get_current_session(&sess);
450 	if (res != TEE_SUCCESS)
451 		return res;
452 
453 	res = tee_obj_get(sess->ctx, obj, &o);
454 	if (res != TEE_SUCCESS)
455 		return res;
456 
457 	/* TODO add TEE_ERROR_STORAGE_NOT_AVAILABLE implementation */
458 
459 	return tee_svc_copy_to_user(sess, info, &o->info, sizeof(o->info));
460 }
461 
462 TEE_Result tee_svc_cryp_obj_restrict_usage(uint32_t obj, uint32_t usage)
463 {
464 	TEE_Result res;
465 	struct tee_ta_session *sess;
466 	struct tee_obj *o;
467 
468 	res = tee_ta_get_current_session(&sess);
469 	if (res != TEE_SUCCESS)
470 		return res;
471 
472 	res = tee_obj_get(sess->ctx, obj, &o);
473 	if (res != TEE_SUCCESS)
474 		return res;
475 
476 	/* TODO add TEE_ERROR_STORAGE_NOT_AVAILABLE implementation */
477 
478 	o->info.objectUsage &= usage;
479 
480 	return TEE_SUCCESS;
481 }
482 
483 static TEE_Result tee_svc_cryp_obj_get_raw_data(
484 		struct tee_obj *o,
485 		const struct tee_cryp_obj_type_props *type_props,
486 		size_t idx, void **data, size_t *size)
487 {
488 	const struct tee_cryp_obj_type_attrs *type_attr =
489 	    type_props->type_attrs + idx;
490 	if (type_attr->raw_size == 0) {
491 		struct tee_cryp_obj_secret *key =
492 		    (struct tee_cryp_obj_secret *)o->data;
493 
494 		/* Handle generic secret */
495 		if (type_attr->raw_offs != 0)
496 			return TEE_ERROR_BAD_STATE;
497 		*size = key->key_size;
498 	} else {
499 		*size = type_attr->raw_size;
500 	}
501 	*data = (uint8_t *)o->data + type_attr->raw_offs;
502 	return TEE_SUCCESS;
503 }
504 
505 static int tee_svc_cryp_obj_find_type_attr_idx(
506 		uint32_t attr_id,
507 		const struct tee_cryp_obj_type_props *type_props)
508 {
509 	size_t n;
510 
511 	for (n = 0; n < type_props->num_type_attrs; n++) {
512 		if (attr_id == type_props->type_attrs[n].attr_id)
513 			return n;
514 	}
515 	return -1;
516 }
517 
518 static const struct tee_cryp_obj_type_props *tee_svc_find_type_props(
519 		TEE_ObjectType obj_type)
520 {
521 	size_t n;
522 
523 	for (n = 0; n < TEE_ARRAY_SIZE(tee_cryp_obj_props); n++) {
524 		if (tee_cryp_obj_props[n].obj_type == obj_type)
525 			return tee_cryp_obj_props + n;
526 	}
527 
528 	return NULL;
529 }
530 
531 static TEE_Result tee_svc_cryp_obj_copy_out(struct tee_ta_session *sess,
532 					    void *buffer, uint32_t *size,
533 					    uint16_t conv_func,
534 					    void *raw_data,
535 					    uint32_t raw_data_size)
536 {
537 	TEE_Result res;
538 	uint32_t s;
539 	uint32_t n;
540 	uint32_t req_size;
541 	uint32_t key_size;
542 	struct tee_cryp_obj_secret *obj;
543 	struct bignum *bn;
544 	uint32_t value[2] = { 0, 0 };
545 
546 	res = tee_svc_copy_from_user(sess, &s, size, sizeof(uint32_t));
547 	if (res != TEE_SUCCESS)
548 		return res;
549 
550 	switch (conv_func) {
551 	case TEE_TYPE_CONV_FUNC_NONE:
552 
553 		res = tee_svc_copy_to_user(sess, size, &raw_data_size,
554 					   sizeof(uint32_t));
555 		if (res != TEE_SUCCESS)
556 			return res;
557 		if (s < raw_data_size)
558 			return TEE_ERROR_SHORT_BUFFER;
559 		return tee_svc_copy_to_user(sess, buffer, raw_data,
560 					    raw_data_size);
561 	case TEE_TYPE_CONV_FUNC_SECRET:
562 
563 		if (!TEE_ALIGNMENT_IS_OK(raw_data, struct tee_cryp_obj_secret))
564 			return TEE_ERROR_BAD_STATE;
565 		obj = (struct tee_cryp_obj_secret *)(void *)raw_data;
566 		key_size = obj->key_size;
567 		res = tee_svc_copy_to_user(sess, size, &key_size,
568 					   sizeof(uint32_t));
569 		if (res != TEE_SUCCESS)
570 			return res;
571 		if (s < key_size)
572 			return TEE_ERROR_SHORT_BUFFER;
573 		return tee_svc_copy_to_user(sess, buffer, obj + 1,
574 					    key_size);
575 
576 	case TEE_TYPE_CONV_FUNC_BIGNUM:
577 
578 		bn = *(struct bignum **)raw_data;
579 		req_size = crypto_ops.bignum.num_bytes(bn);
580 		if (req_size == 0)
581 			return TEE_SUCCESS;
582 		res = tee_svc_copy_to_user(sess, size, &req_size,
583 					   sizeof(uint32_t));
584 		if (res != TEE_SUCCESS)
585 			return res;
586 		/* Check that the converted result fits the user buffer. */
587 		if (s < req_size)
588 			return TEE_ERROR_SHORT_BUFFER;
589 		/* Check we can access data using supplied user mode pointer */
590 		res = tee_mmu_check_access_rights(sess->ctx,
591 						  TEE_MEMORY_ACCESS_READ |
592 						  TEE_MEMORY_ACCESS_WRITE |
593 						  TEE_MEMORY_ACCESS_ANY_OWNER,
594 						  (tee_uaddr_t)buffer,
595 						  req_size);
596 		if (res != TEE_SUCCESS)
597 			return res;
598 		/*
599 		 * Write the bignum (wich raw data points to) into an array of
600 		 * bytes (stored in buffer)
601 		 */
602 		crypto_ops.bignum.bn2bin(bn, buffer);
603 		return TEE_SUCCESS;
604 
605 	case TEE_TYPE_CONV_FUNC_VALUE:
606 		n = sizeof(value);
607 		/*
608 		 * a value attribute consists of two uint32 but have not
609 		 * seen anything that actaully would need that so this
610 		 * fills in one with data and the other with zero
611 		 */
612 		TEE_ASSERT(raw_data_size == sizeof(uint32_t));
613 		value[0] = *(uint32_t *)raw_data;
614 		res = tee_svc_copy_to_user(sess, size, &n, sizeof(uint32_t));
615 		if (res != TEE_SUCCESS)
616 			return res;
617 		/* Check that the converted result fits the user buf */
618 		if (s < n)
619 			return TEE_ERROR_SHORT_BUFFER;
620 		return tee_svc_copy_to_user(sess, buffer, &value, n);
621 
622 	default:
623 		return TEE_ERROR_BAD_STATE;
624 	}
625 }
626 
627 TEE_Result tee_svc_cryp_obj_get_attr(uint32_t obj, uint32_t attr_id,
628 				     void *buffer, uint32_t *size)
629 {
630 	TEE_Result res;
631 	struct tee_ta_session *sess;
632 	struct tee_obj *o;
633 	const struct tee_cryp_obj_type_props *type_props;
634 	int idx;
635 	size_t raw_size;
636 	void *raw_data;
637 
638 	res = tee_ta_get_current_session(&sess);
639 	if (res != TEE_SUCCESS)
640 		return res;
641 
642 	res = tee_obj_get(sess->ctx, obj, &o);
643 	if (res != TEE_SUCCESS)
644 		return TEE_ERROR_ITEM_NOT_FOUND;
645 
646 	/* Check that the object is initialized */
647 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
648 		return TEE_ERROR_ITEM_NOT_FOUND;
649 
650 	/* Check that getting the attribute is allowed */
651 	if ((attr_id & TEE_ATTR_BIT_PROTECTED) == 0 &&
652 	    (o->info.objectUsage & TEE_USAGE_EXTRACTABLE) == 0)
653 		return TEE_ERROR_ACCESS_DENIED;
654 
655 	type_props = tee_svc_find_type_props(o->info.objectType);
656 	if (!type_props) {
657 		/* Unknown object type, "can't happen" */
658 		return TEE_ERROR_BAD_STATE;
659 	}
660 
661 	idx = tee_svc_cryp_obj_find_type_attr_idx(attr_id, type_props);
662 	if ((idx < 0) || ((o->have_attrs & (1 << idx)) == 0))
663 		return TEE_ERROR_ITEM_NOT_FOUND;
664 
665 	res = tee_svc_cryp_obj_get_raw_data(o, type_props, idx,
666 					    &raw_data, &raw_size);
667 	if (res != TEE_SUCCESS)
668 		return res;
669 
670 	return tee_svc_cryp_obj_copy_out(sess, buffer, size,
671 					 type_props->type_attrs[idx].conv_func,
672 					 raw_data, raw_size);
673 }
674 
675 static void bn_cleanup(struct bignum *bn, bool del)
676 {
677 	if (del)
678 		crypto_ops.bignum.free(bn);
679 	else
680 		crypto_ops.bignum.clear(bn);
681 }
682 
683 static void cleanup_rsa_keypair(void *p, bool del)
684 {
685 	struct rsa_keypair *s = (struct rsa_keypair *)p;
686 
687 	bn_cleanup(s->e, del);
688 	bn_cleanup(s->d, del);
689 	bn_cleanup(s->n, del);
690 	bn_cleanup(s->p, del);
691 	bn_cleanup(s->q, del);
692 	bn_cleanup(s->qp, del);
693 	bn_cleanup(s->dp, del);
694 	bn_cleanup(s->dq, del);
695 }
696 
697 static void cleanup_dsa_keypair(void *p, bool del)
698 {
699 	struct dsa_keypair *s = (struct dsa_keypair *)p;
700 
701 	bn_cleanup(s->g, del);
702 	bn_cleanup(s->p, del);
703 	bn_cleanup(s->q, del);
704 	bn_cleanup(s->y, del);
705 	bn_cleanup(s->x, del);
706 }
707 
708 static void cleanup_rsa_public_key(void *p, bool del)
709 {
710 	struct rsa_public_key *s = (struct rsa_public_key *)p;
711 
712 	bn_cleanup(s->e, del);
713 	bn_cleanup(s->n, del);
714 }
715 
716 static void cleanup_dsa_public_key(void *p, bool del)
717 {
718 	struct dsa_public_key *s = (struct dsa_public_key *)p;
719 
720 	bn_cleanup(s->g, del);
721 	bn_cleanup(s->p, del);
722 	bn_cleanup(s->q, del);
723 	bn_cleanup(s->y, del);
724 }
725 
726 static void cleanup_dh_keypair(void *p, bool del)
727 {
728 	struct dh_keypair *s = (struct dh_keypair *)p;
729 
730 	bn_cleanup(s->g, del);
731 	bn_cleanup(s->p, del);
732 	bn_cleanup(s->x, del);
733 	bn_cleanup(s->y, del);
734 	bn_cleanup(s->q, del);
735 	s->xbits = 0;
736 }
737 
738 static void copy_rsa_public_key(struct rsa_public_key *to,
739 				const struct rsa_public_key *from)
740 {
741 	crypto_ops.bignum.copy(to->e, from->e);
742 	crypto_ops.bignum.copy(to->n, from->n);
743 }
744 
745 static void copy_rsa_keypair(struct rsa_keypair *to,
746 			     const struct rsa_keypair *from)
747 {
748 	crypto_ops.bignum.copy(to->e, from->e);
749 	crypto_ops.bignum.copy(to->d, from->d);
750 	crypto_ops.bignum.copy(to->n, from->n);
751 	crypto_ops.bignum.copy(to->p, from->p);
752 	crypto_ops.bignum.copy(to->q, from->q);
753 	crypto_ops.bignum.copy(to->qp, from->qp);
754 	crypto_ops.bignum.copy(to->dp, from->dp);
755 	crypto_ops.bignum.copy(to->dq, from->dq);
756 }
757 
758 static void copy_dsa_public_key(struct dsa_public_key *to,
759 				const struct dsa_public_key *from)
760 {
761 	crypto_ops.bignum.copy(to->g, from->g);
762 	crypto_ops.bignum.copy(to->p, from->p);
763 	crypto_ops.bignum.copy(to->q, from->q);
764 	crypto_ops.bignum.copy(to->y, from->y);
765 }
766 
767 
768 static void copy_dsa_keypair(struct dsa_keypair *to,
769 			     const struct dsa_keypair *from)
770 {
771 	crypto_ops.bignum.copy(to->g, from->g);
772 	crypto_ops.bignum.copy(to->p, from->p);
773 	crypto_ops.bignum.copy(to->q, from->q);
774 	crypto_ops.bignum.copy(to->y, from->y);
775 	crypto_ops.bignum.copy(to->x, from->x);
776 }
777 
778 static void copy_dh_keypair(struct dh_keypair *to,
779 			    const struct dh_keypair *from)
780 {
781 	crypto_ops.bignum.copy(to->g, from->g);
782 	crypto_ops.bignum.copy(to->p, from->p);
783 	crypto_ops.bignum.copy(to->y, from->y);
784 	crypto_ops.bignum.copy(to->x, from->x);
785 	crypto_ops.bignum.copy(to->q, from->q);
786 	to->xbits = from->xbits;
787 }
788 
789 static void extract_rsa_public_key(struct rsa_public_key *to,
790 				   const struct rsa_keypair *from)
791 {
792 	crypto_ops.bignum.copy(to->e, from->e);
793 	crypto_ops.bignum.copy(to->n, from->n);
794 }
795 
796 static void extract_dsa_public_key(struct dsa_public_key *to,
797 				   const struct dsa_keypair *from)
798 {
799 	crypto_ops.bignum.copy(to->g, from->g);
800 	crypto_ops.bignum.copy(to->p, from->p);
801 	crypto_ops.bignum.copy(to->q, from->q);
802 	crypto_ops.bignum.copy(to->y, from->y);
803 }
804 
805 TEE_Result tee_svc_cryp_obj_alloc(TEE_ObjectType obj_type,
806 				  uint32_t max_key_size, uint32_t *obj)
807 {
808 	TEE_Result res;
809 	struct tee_ta_session *sess;
810 	const struct tee_cryp_obj_type_props *type_props;
811 	struct tee_obj *o;
812 
813 	res = tee_ta_get_current_session(&sess);
814 	if (res != TEE_SUCCESS)
815 		return res;
816 
817 	/*
818 	 * Verify that maxKeySize is supported and find out how
819 	 * much should be allocated.
820 	 */
821 
822 	/* Find description of object */
823 	type_props = tee_svc_find_type_props(obj_type);
824 	if (!type_props)
825 		return TEE_ERROR_NOT_SUPPORTED;
826 
827 	/* Check that maxKeySize follows restrictions */
828 	if (max_key_size % type_props->quanta != 0)
829 		return TEE_ERROR_NOT_SUPPORTED;
830 	if (max_key_size < type_props->min_size)
831 		return TEE_ERROR_NOT_SUPPORTED;
832 	if (max_key_size > type_props->max_size)
833 		return TEE_ERROR_NOT_SUPPORTED;
834 
835 	o = calloc(1, sizeof(*o));
836 	if (!o)
837 		return TEE_ERROR_OUT_OF_MEMORY;
838 	o->data = calloc(1, type_props->alloc_size);
839 	if (!o->data) {
840 		free(o);
841 		return TEE_ERROR_OUT_OF_MEMORY;
842 	}
843 	o->data_size = type_props->alloc_size;
844 
845 	/* If we have a key structure, pre-allocate the bignums inside */
846 	switch (obj_type) {
847 	case TEE_TYPE_RSA_PUBLIC_KEY:
848 		if (!crypto_ops.acipher.alloc_rsa_public_key)
849 			goto notimpl;
850 		if (crypto_ops.acipher.alloc_rsa_public_key(o->data,
851 							    max_key_size)
852 				!= TEE_SUCCESS)
853 			goto alloc_err;
854 		o->cleanup = cleanup_rsa_public_key;
855 		break;
856 	case TEE_TYPE_RSA_KEYPAIR:
857 		if (!crypto_ops.acipher.alloc_rsa_keypair)
858 			goto notimpl;
859 		if (crypto_ops.acipher.alloc_rsa_keypair(o->data,
860 							 max_key_size)
861 				!= TEE_SUCCESS)
862 			goto alloc_err;
863 		o->cleanup = cleanup_rsa_keypair;
864 		break;
865 	case TEE_TYPE_DSA_PUBLIC_KEY:
866 		if (!crypto_ops.acipher.alloc_dsa_public_key)
867 			goto notimpl;
868 		if (crypto_ops.acipher.alloc_dsa_public_key(o->data,
869 							    max_key_size)
870 				!= TEE_SUCCESS)
871 			goto alloc_err;
872 		o->cleanup = cleanup_dsa_public_key;
873 		break;
874 	case TEE_TYPE_DSA_KEYPAIR:
875 		if (!crypto_ops.acipher.alloc_dsa_keypair)
876 			goto notimpl;
877 		if (crypto_ops.acipher.alloc_dsa_keypair(o->data, max_key_size)
878 				!= TEE_SUCCESS)
879 			goto alloc_err;
880 		o->cleanup = cleanup_dsa_keypair;
881 		break;
882 	case TEE_TYPE_DH_KEYPAIR:
883 		if (!crypto_ops.acipher.alloc_dh_keypair)
884 			goto notimpl;
885 		if (crypto_ops.acipher.alloc_dh_keypair(o->data, max_key_size)
886 				!= TEE_SUCCESS)
887 			goto alloc_err;
888 		o->cleanup = cleanup_dh_keypair;
889 		break;
890 	default:
891 		break;
892 	}
893 
894 	o->info.objectType = obj_type;
895 	o->info.maxKeySize = max_key_size;
896 	o->info.objectUsage = TEE_USAGE_DEFAULT;
897 	o->info.handleFlags = 0;
898 
899 	o->fd = -1;
900 
901 	tee_obj_add(sess->ctx, o);
902 
903 	res = tee_svc_copy_to_user(sess, obj, &o, sizeof(o));
904 	if (res != TEE_SUCCESS)
905 		tee_obj_close(sess->ctx, o);
906 	return res;
907 
908 alloc_err:
909 	free(o->data);
910 	free(o);
911 	return TEE_ERROR_OUT_OF_MEMORY;
912 notimpl:
913 	free(o->data);
914 	free(o);
915 	return TEE_ERROR_NOT_IMPLEMENTED;
916 }
917 
918 TEE_Result tee_svc_cryp_obj_close(uint32_t obj)
919 {
920 	TEE_Result res;
921 	struct tee_ta_session *sess;
922 	struct tee_obj *o;
923 
924 	res = tee_ta_get_current_session(&sess);
925 	if (res != TEE_SUCCESS)
926 		return res;
927 
928 	res = tee_obj_get(sess->ctx, obj, &o);
929 	if (res != TEE_SUCCESS)
930 		return res;
931 
932 	/*
933 	 * If it's busy it's used by an operation, a client should never have
934 	 * this handle.
935 	 */
936 	if (o->busy)
937 		return TEE_ERROR_ITEM_NOT_FOUND;
938 
939 	tee_obj_close(sess->ctx, o);
940 	return TEE_SUCCESS;
941 }
942 
943 TEE_Result tee_svc_cryp_obj_reset(uint32_t obj)
944 {
945 	TEE_Result res;
946 	struct tee_ta_session *sess;
947 	struct tee_obj *o;
948 
949 	res = tee_ta_get_current_session(&sess);
950 	if (res != TEE_SUCCESS)
951 		return res;
952 
953 	res = tee_obj_get(sess->ctx, obj, &o);
954 	if (res != TEE_SUCCESS)
955 		return res;
956 
957 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) == 0) {
958 		if (o->cleanup) {
959 			/*
960 			 * o->data contains pointers to key data.
961 			 * Clear key data, but keep the pointers.
962 			 */
963 			o->cleanup(o->data, false);
964 		} else {
965 			memset(o->data, 0, o->data_size);
966 		}
967 		o->info.keySize = 0;
968 		o->info.objectUsage = TEE_USAGE_DEFAULT;
969 	} else {
970 		return TEE_ERROR_BAD_PARAMETERS;
971 	}
972 
973 	/* the object is no more initialized */
974 	o->info.handleFlags &= ~TEE_HANDLE_FLAG_INITIALIZED;
975 
976 	return TEE_SUCCESS;
977 }
978 
979 static TEE_Result tee_svc_cryp_obj_store_attr_raw(uint16_t conv_func,
980 						  const TEE_Attribute *attr,
981 						  void *data, size_t data_size)
982 {
983 	TEE_Result res;
984 	struct tee_cryp_obj_secret *obj;
985 	struct bignum *bn;
986 
987 	if (!attr)
988 		return TEE_ERROR_BAD_STATE;
989 
990 	if (conv_func != TEE_TYPE_CONV_FUNC_VALUE && !attr->content.ref.buffer)
991 		return TEE_ERROR_BAD_PARAMETERS;
992 
993 	switch (conv_func) {
994 	case TEE_TYPE_CONV_FUNC_NONE:
995 		/* No conversion data size has to match exactly */
996 		if (attr->content.ref.length != data_size)
997 			return TEE_ERROR_BAD_PARAMETERS;
998 		memcpy(data, attr->content.ref.buffer, data_size);
999 		return TEE_SUCCESS;
1000 
1001 	case TEE_TYPE_CONV_FUNC_SECRET:
1002 		if (!TEE_ALIGNMENT_IS_OK(data, struct tee_cryp_obj_secret))
1003 			return TEE_ERROR_BAD_STATE;
1004 		obj = (struct tee_cryp_obj_secret *)(void *)data;
1005 
1006 		/* Data size has to fit in allocated buffer */
1007 		if (attr->content.ref.length >
1008 		    (data_size - sizeof(struct tee_cryp_obj_secret)))
1009 			return TEE_ERROR_BAD_PARAMETERS;
1010 
1011 		memcpy(obj + 1, attr->content.ref.buffer,
1012 		       attr->content.ref.length);
1013 		obj->key_size = attr->content.ref.length;
1014 		return TEE_SUCCESS;
1015 
1016 	case TEE_TYPE_CONV_FUNC_BIGNUM:
1017 		/*
1018 		 * Read the array of bytes (stored in attr->content.ref.buffer)
1019 		 * and convert it to a bignum (pointed to by data)
1020 		 */
1021 		bn = *(struct bignum **)data;
1022 		if (!crypto_ops.bignum.bin2bn)
1023 			return TEE_ERROR_NOT_IMPLEMENTED;
1024 		res = crypto_ops.bignum.bin2bn(attr->content.ref.buffer,
1025 					       attr->content.ref.length,
1026 					       bn);
1027 		return res;
1028 
1029 	case TEE_TYPE_CONV_FUNC_VALUE:
1030 		/*
1031 		 * a value attribute consists of two uint32 but have not
1032 		 * seen anything that actaully would need that so this fills
1033 		 * the data from the first value and discards the second value
1034 		 */
1035 		*(uint32_t *)data = attr->content.value.a;
1036 
1037 		return TEE_SUCCESS;
1038 
1039 	default:
1040 		return TEE_ERROR_BAD_STATE;
1041 	}
1042 }
1043 
1044 
1045 static TEE_Result copy_in_attrs(struct tee_ta_ctx *ctx,
1046 			const struct abi_user32_attribute *usr_attrs,
1047 			uint32_t attr_count, TEE_Attribute *attrs)
1048 {
1049 	TEE_Result res;
1050 	uint32_t n;
1051 
1052 	res = tee_mmu_check_access_rights(ctx,
1053 			TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER,
1054 			(tee_uaddr_t)usr_attrs,
1055 			attr_count * sizeof(struct abi_user32_attribute));
1056 	if (res != TEE_SUCCESS)
1057 		return res;
1058 
1059 	abi_user_attr32_to_attr(attrs, usr_attrs, attr_count);
1060 
1061 	for (n = 0; n < attr_count; n++) {
1062 		if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE)
1063 			continue;
1064 		res = tee_mmu_check_access_rights(ctx, TEE_MEMORY_ACCESS_READ |
1065 						  TEE_MEMORY_ACCESS_ANY_OWNER,
1066 						  (tee_uaddr_t)
1067 						  attrs[n].content.ref.buffer,
1068 						  attrs[n].content.ref.length);
1069 		if (res != TEE_SUCCESS)
1070 			return res;
1071 	}
1072 
1073 	return TEE_SUCCESS;
1074 }
1075 
1076 enum attr_usage {
1077 	ATTR_USAGE_POPULATE,
1078 	ATTR_USAGE_GENERATE_KEY
1079 };
1080 
1081 static TEE_Result tee_svc_cryp_check_attr(enum attr_usage usage,
1082 					  const struct tee_cryp_obj_type_props
1083 						*type_props,
1084 					  const TEE_Attribute *attrs,
1085 					  uint32_t attr_count)
1086 {
1087 	uint32_t required_flag;
1088 	uint32_t opt_flag;
1089 	bool all_opt_needed;
1090 	uint32_t req_attrs = 0;
1091 	uint32_t opt_grp_attrs = 0;
1092 	uint32_t attrs_found = 0;
1093 	size_t n;
1094 
1095 	if (usage == ATTR_USAGE_POPULATE) {
1096 		required_flag = TEE_TYPE_ATTR_REQUIRED;
1097 		opt_flag = TEE_TYPE_ATTR_OPTIONAL_GROUP;
1098 		all_opt_needed = true;
1099 	} else {
1100 		required_flag = TEE_TYPE_ATTR_GEN_KEY_REQ;
1101 		opt_flag = TEE_TYPE_ATTR_GEN_KEY_OPT;
1102 		all_opt_needed = false;
1103 	}
1104 
1105 	/*
1106 	 * First find out which attributes are required and which belong to
1107 	 * the optional group
1108 	 */
1109 	for (n = 0; n < type_props->num_type_attrs; n++) {
1110 		uint32_t bit = 1 << n;
1111 		uint32_t flags = type_props->type_attrs[n].flags;
1112 
1113 		if (flags & required_flag)
1114 			req_attrs |= bit;
1115 		else if (flags & opt_flag)
1116 			opt_grp_attrs |= bit;
1117 	}
1118 
1119 	/*
1120 	 * Verify that all required attributes are in place and
1121 	 * that the same attribute isn't repeated.
1122 	 */
1123 	for (n = 0; n < attr_count; n++) {
1124 		int idx =
1125 		    tee_svc_cryp_obj_find_type_attr_idx(attrs[n].attributeID,
1126 							type_props);
1127 		if (idx >= 0) {
1128 			uint32_t bit = 1 << idx;
1129 
1130 			if ((attrs_found & bit) != 0)
1131 				return TEE_ERROR_ITEM_NOT_FOUND;
1132 
1133 			attrs_found |= bit;
1134 		}
1135 	}
1136 	/* Required attribute missing */
1137 	if ((attrs_found & req_attrs) != req_attrs)
1138 		return TEE_ERROR_ITEM_NOT_FOUND;
1139 
1140 	/*
1141 	 * If the flag says that "if one of the optional attributes are included
1142 	 * all of them has to be included" this must be checked.
1143 	 */
1144 	if (all_opt_needed && (attrs_found & opt_grp_attrs) != 0 &&
1145 	    (attrs_found & opt_grp_attrs) != opt_grp_attrs)
1146 		return TEE_ERROR_ITEM_NOT_FOUND;
1147 
1148 	return TEE_SUCCESS;
1149 }
1150 
1151 static TEE_Result tee_svc_cryp_obj_populate_type(
1152 		struct tee_obj *o,
1153 		const struct tee_cryp_obj_type_props *type_props,
1154 		const TEE_Attribute *attrs,
1155 		uint32_t attr_count)
1156 {
1157 	TEE_Result res;
1158 	uint32_t have_attrs = 0;
1159 	size_t obj_size = 0;
1160 	size_t n;
1161 
1162 	for (n = 0; n < attr_count; n++) {
1163 		size_t raw_size;
1164 		void *raw_data;
1165 		int idx =
1166 		    tee_svc_cryp_obj_find_type_attr_idx(attrs[n].attributeID,
1167 							type_props);
1168 		if (idx < 0)
1169 			continue;
1170 
1171 		have_attrs |= 1 << idx;
1172 
1173 		res = tee_svc_cryp_obj_get_raw_data(o, type_props, idx,
1174 						    &raw_data, &raw_size);
1175 		if (res != TEE_SUCCESS)
1176 			return res;
1177 
1178 		res =
1179 		    tee_svc_cryp_obj_store_attr_raw(
1180 			    type_props->type_attrs[idx].conv_func,
1181 			    attrs + n, raw_data, raw_size);
1182 		if (res != TEE_SUCCESS)
1183 			return res;
1184 
1185 		/*
1186 		 * First attr_idx signifies the attribute that gives the size
1187 		 * of the object
1188 		 */
1189 		if (type_props->type_attrs[idx].flags &
1190 		    TEE_TYPE_ATTR_SIZE_INDICATOR) {
1191 			obj_size += attrs[n].content.ref.length * 8;
1192 		}
1193 	}
1194 
1195 	/*
1196 	 * We have to do it like this because the parity bits aren't counted
1197 	 * when telling the size of the key in bits.
1198 	 */
1199 	if (o->info.objectType == TEE_TYPE_DES ||
1200 	    o->info.objectType == TEE_TYPE_DES3)
1201 		obj_size -= obj_size / 8; /* Exclude parity in size of key */
1202 
1203 	o->have_attrs = have_attrs;
1204 	o->info.keySize = obj_size;
1205 	return TEE_SUCCESS;
1206 }
1207 
1208 TEE_Result tee_svc_cryp_obj_populate(uint32_t obj,
1209 		struct abi_user32_attribute *usr_attrs, uint32_t attr_count)
1210 {
1211 	TEE_Result res;
1212 	struct tee_ta_session *sess;
1213 	struct tee_obj *o;
1214 	const struct tee_cryp_obj_type_props *type_props;
1215 	TEE_Attribute *attrs = NULL;
1216 
1217 	res = tee_ta_get_current_session(&sess);
1218 	if (res != TEE_SUCCESS)
1219 		return res;
1220 
1221 	res = tee_obj_get(sess->ctx, obj, &o);
1222 	if (res != TEE_SUCCESS)
1223 		return res;
1224 
1225 	/* Must be a transient object */
1226 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
1227 		return TEE_ERROR_BAD_PARAMETERS;
1228 
1229 	/* Must not be initialized already */
1230 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
1231 		return TEE_ERROR_BAD_PARAMETERS;
1232 
1233 	type_props = tee_svc_find_type_props(o->info.objectType);
1234 	if (!type_props)
1235 		return TEE_ERROR_NOT_IMPLEMENTED;
1236 
1237 	attrs = malloc(sizeof(TEE_Attribute) * attr_count);
1238 	if (!attrs)
1239 		return TEE_ERROR_OUT_OF_MEMORY;
1240 	res = copy_in_attrs(sess->ctx, usr_attrs, attr_count, attrs);
1241 	if (res != TEE_SUCCESS)
1242 		goto out;
1243 
1244 	res = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props,
1245 				      attrs, attr_count);
1246 	if (res != TEE_SUCCESS)
1247 		goto out;
1248 
1249 	res = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count);
1250 	if (res == TEE_SUCCESS)
1251 		o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
1252 
1253 out:
1254 	free(attrs);
1255 	return res;
1256 }
1257 
1258 TEE_Result tee_svc_cryp_obj_copy(uint32_t dst, uint32_t src)
1259 {
1260 	TEE_Result res;
1261 	struct tee_ta_session *sess;
1262 	struct tee_obj *dst_o;
1263 	struct tee_obj *src_o;
1264 
1265 	res = tee_ta_get_current_session(&sess);
1266 	if (res != TEE_SUCCESS)
1267 		return res;
1268 
1269 	res = tee_obj_get(sess->ctx, dst, &dst_o);
1270 	if (res != TEE_SUCCESS)
1271 		return res;
1272 
1273 	res = tee_obj_get(sess->ctx, src, &src_o);
1274 	if (res != TEE_SUCCESS)
1275 		return res;
1276 
1277 	if ((src_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
1278 		return TEE_ERROR_BAD_PARAMETERS;
1279 	if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
1280 		return TEE_ERROR_BAD_PARAMETERS;
1281 	if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
1282 		return TEE_ERROR_BAD_PARAMETERS;
1283 
1284 	if (dst_o->info.objectType == src_o->info.objectType) {
1285 		/* Copy whole data */
1286 
1287 		if (dst_o->data_size != src_o->data_size)
1288 			return TEE_ERROR_BAD_STATE;
1289 		if (dst_o->cleanup != src_o->cleanup)
1290 			return TEE_ERROR_BAD_STATE;
1291 
1292 		dst_o->have_attrs = src_o->have_attrs;
1293 
1294 		switch (src_o->info.objectType) {
1295 		case TEE_TYPE_RSA_PUBLIC_KEY:
1296 			copy_rsa_public_key(dst_o->data, src_o->data);
1297 			break;
1298 		case TEE_TYPE_RSA_KEYPAIR:
1299 			copy_rsa_keypair(dst_o->data, src_o->data);
1300 			break;
1301 		case TEE_TYPE_DSA_PUBLIC_KEY:
1302 			copy_dsa_public_key(dst_o->data, src_o->data);
1303 			break;
1304 		case TEE_TYPE_DSA_KEYPAIR:
1305 			copy_dsa_keypair(dst_o->data, src_o->data);
1306 			break;
1307 		case TEE_TYPE_DH_KEYPAIR:
1308 			copy_dh_keypair(dst_o->data, src_o->data);
1309 			break;
1310 		default:
1311 			/* Generic case */
1312 			memcpy(dst_o->data, src_o->data, src_o->data_size);
1313 		}
1314 	} else if (dst_o->info.objectType == TEE_TYPE_RSA_PUBLIC_KEY &&
1315 		   src_o->info.objectType == TEE_TYPE_RSA_KEYPAIR) {
1316 		/* Extract public key from RSA key pair */
1317 		size_t n;
1318 
1319 		extract_rsa_public_key(dst_o->data, src_o->data);
1320 		dst_o->have_attrs = 0;
1321 		for (n = 0; n < TEE_ARRAY_SIZE(tee_cryp_obj_rsa_pub_key_attrs);
1322 		     n++)
1323 			dst_o->have_attrs |= 1 << n;
1324 
1325 	} else if (dst_o->info.objectType == TEE_TYPE_DSA_PUBLIC_KEY &&
1326 		   src_o->info.objectType == TEE_TYPE_DSA_KEYPAIR) {
1327 		/* Extract public key from DSA key pair */
1328 		size_t n;
1329 
1330 		extract_dsa_public_key(dst_o->data, src_o->data);
1331 		dst_o->have_attrs = 0;
1332 		for (n = 0; n < TEE_ARRAY_SIZE(tee_cryp_obj_dsa_pub_key_attrs);
1333 		     n++)
1334 			dst_o->have_attrs |= 1 << n;
1335 
1336 	} else {
1337 		return TEE_ERROR_BAD_PARAMETERS;
1338 	}
1339 
1340 	dst_o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
1341 	dst_o->info.keySize = src_o->info.keySize;
1342 	dst_o->info.objectUsage = src_o->info.objectUsage;
1343 	return TEE_SUCCESS;
1344 }
1345 
1346 static TEE_Result tee_svc_obj_generate_key_rsa(
1347 	struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
1348 	uint32_t key_size,
1349 	const TEE_Attribute *params, uint32_t param_count)
1350 {
1351 	TEE_Result res;
1352 	struct rsa_keypair *key = o->data;
1353 	uint32_t e = TEE_U32_TO_BIG_ENDIAN(65537);
1354 
1355 	TEE_ASSERT(sizeof(struct rsa_keypair) == o->data_size);
1356 	if (!crypto_ops.acipher.gen_rsa_key || !crypto_ops.bignum.bin2bn)
1357 		return TEE_ERROR_NOT_IMPLEMENTED;
1358 
1359 	/* Copy the present attributes into the obj before starting */
1360 	res = tee_svc_cryp_obj_populate_type(o, type_props, params,
1361 					     param_count);
1362 	if (res != TEE_SUCCESS)
1363 		return res;
1364 	if (!GET_ATTRIBUTE(o, type_props, TEE_ATTR_RSA_PUBLIC_EXPONENT))
1365 		crypto_ops.bignum.bin2bn((const uint8_t *)&e, sizeof(e),
1366 					 key->e);
1367 	res = crypto_ops.acipher.gen_rsa_key(o->data, key_size);
1368 	if (res != TEE_SUCCESS)
1369 		return res;
1370 
1371 	/* Set bits for all known attributes for this object type */
1372 	o->have_attrs = (1 << type_props->num_type_attrs) - 1;
1373 
1374 	return TEE_SUCCESS;
1375 }
1376 
1377 static TEE_Result tee_svc_obj_generate_key_dsa(
1378 	struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
1379 	uint32_t key_size)
1380 {
1381 	TEE_Result res;
1382 
1383 	TEE_ASSERT(sizeof(struct dsa_keypair) == o->data_size);
1384 	if (!crypto_ops.acipher.gen_dsa_key)
1385 		return TEE_ERROR_NOT_IMPLEMENTED;
1386 	res = crypto_ops.acipher.gen_dsa_key(o->data, key_size);
1387 	if (res != TEE_SUCCESS)
1388 		return res;
1389 
1390 	/* Set bits for all known attributes for this object type */
1391 	o->have_attrs = (1 << type_props->num_type_attrs) - 1;
1392 
1393 	return TEE_SUCCESS;
1394 }
1395 
1396 static TEE_Result tee_svc_obj_generate_key_dh(
1397 	struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
1398 	uint32_t key_size __unused,
1399 	const TEE_Attribute *params, uint32_t param_count)
1400 {
1401 	TEE_Result res;
1402 	struct dh_keypair *tee_dh_key;
1403 	struct bignum *dh_q = NULL;
1404 	uint32_t dh_xbits = 0;
1405 
1406 	TEE_ASSERT(sizeof(struct dh_keypair) == o->data_size);
1407 
1408 	/* Copy the present attributes into the obj before starting */
1409 	res = tee_svc_cryp_obj_populate_type(o, type_props, params,
1410 					     param_count);
1411 	if (res != TEE_SUCCESS)
1412 		return res;
1413 
1414 	tee_dh_key = (struct dh_keypair *)o->data;
1415 
1416 	if (GET_ATTRIBUTE(o, type_props, TEE_ATTR_DH_SUBPRIME))
1417 		dh_q = tee_dh_key->q;
1418 	if (GET_ATTRIBUTE(o, type_props, TEE_ATTR_DH_X_BITS))
1419 		dh_xbits = tee_dh_key->xbits;
1420 	if (!crypto_ops.acipher.gen_dh_key)
1421 		return TEE_ERROR_NOT_IMPLEMENTED;
1422 	res = crypto_ops.acipher.gen_dh_key(tee_dh_key, dh_q, dh_xbits);
1423 	if (res != TEE_SUCCESS)
1424 		return res;
1425 
1426 	/* Set bits for the generated public and private key */
1427 	SET_ATTRIBUTE(o, type_props, TEE_ATTR_DH_PUBLIC_VALUE);
1428 	SET_ATTRIBUTE(o, type_props, TEE_ATTR_DH_PRIVATE_VALUE);
1429 	SET_ATTRIBUTE(o, type_props, TEE_ATTR_DH_X_BITS);
1430 	return TEE_SUCCESS;
1431 }
1432 
1433 TEE_Result tee_svc_obj_generate_key(uint32_t obj, uint32_t key_size,
1434 			const struct abi_user32_attribute *usr_params,
1435 			uint32_t param_count)
1436 {
1437 	TEE_Result res;
1438 	struct tee_ta_session *sess;
1439 	const struct tee_cryp_obj_type_props *type_props;
1440 	struct tee_obj *o;
1441 	struct tee_cryp_obj_secret *key;
1442 	size_t byte_size;
1443 	TEE_Attribute *params = NULL;
1444 
1445 	res = tee_ta_get_current_session(&sess);
1446 	if (res != TEE_SUCCESS)
1447 		return res;
1448 
1449 	res = tee_obj_get(sess->ctx, obj, &o);
1450 	if (res != TEE_SUCCESS)
1451 		return res;
1452 
1453 	/* Must be a transient object */
1454 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
1455 		return TEE_ERROR_BAD_STATE;
1456 
1457 	/* Must not be initialized already */
1458 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
1459 		return TEE_ERROR_BAD_STATE;
1460 
1461 	/* Find description of object */
1462 	type_props = tee_svc_find_type_props(o->info.objectType);
1463 	if (!type_props)
1464 		return TEE_ERROR_NOT_SUPPORTED;
1465 
1466 	/* Check that maxKeySize follows restrictions */
1467 	if (key_size % type_props->quanta != 0)
1468 		return TEE_ERROR_NOT_SUPPORTED;
1469 	if (key_size < type_props->min_size)
1470 		return TEE_ERROR_NOT_SUPPORTED;
1471 	if (key_size > type_props->max_size)
1472 		return TEE_ERROR_NOT_SUPPORTED;
1473 
1474 	params = malloc(sizeof(TEE_Attribute) * param_count);
1475 	if (!params)
1476 		return TEE_ERROR_OUT_OF_MEMORY;
1477 	res = copy_in_attrs(sess->ctx, usr_params, param_count, params);
1478 	if (res != TEE_SUCCESS)
1479 		goto out;
1480 
1481 	res = tee_svc_cryp_check_attr(ATTR_USAGE_GENERATE_KEY, type_props,
1482 				      params, param_count);
1483 	if (res != TEE_SUCCESS)
1484 		goto out;
1485 
1486 	switch (o->info.objectType) {
1487 	case TEE_TYPE_AES:
1488 	case TEE_TYPE_DES:
1489 	case TEE_TYPE_DES3:
1490 	case TEE_TYPE_HMAC_MD5:
1491 	case TEE_TYPE_HMAC_SHA1:
1492 	case TEE_TYPE_HMAC_SHA224:
1493 	case TEE_TYPE_HMAC_SHA256:
1494 	case TEE_TYPE_HMAC_SHA384:
1495 	case TEE_TYPE_HMAC_SHA512:
1496 	case TEE_TYPE_GENERIC_SECRET:
1497 		byte_size = key_size / 8;
1498 
1499 		/*
1500 		 * We have to do it like this because the parity bits aren't
1501 		 * counted when telling the size of the key in bits.
1502 		 */
1503 		if (o->info.objectType == TEE_TYPE_DES ||
1504 		    o->info.objectType == TEE_TYPE_DES3) {
1505 			byte_size = (key_size + key_size / 7) / 8;
1506 		}
1507 
1508 		key = (struct tee_cryp_obj_secret *)o->data;
1509 		if (byte_size > (o->data_size - sizeof(*key))) {
1510 			res = TEE_ERROR_EXCESS_DATA;
1511 			goto out;
1512 		}
1513 
1514 		res = crypto_ops.prng.read((void *)(key + 1), byte_size);
1515 		if (res != TEE_SUCCESS)
1516 			goto out;
1517 
1518 		key->key_size = byte_size;
1519 
1520 		/* Set bits for all known attributes for this object type */
1521 		o->have_attrs = (1 << type_props->num_type_attrs) - 1;
1522 
1523 		break;
1524 
1525 	case TEE_TYPE_RSA_KEYPAIR:
1526 		res = tee_svc_obj_generate_key_rsa(o, type_props, key_size,
1527 						   params, param_count);
1528 		if (res != TEE_SUCCESS)
1529 			goto out;
1530 		break;
1531 
1532 	case TEE_TYPE_DSA_KEYPAIR:
1533 		res = tee_svc_obj_generate_key_dsa(o, type_props, key_size);
1534 		if (res != TEE_SUCCESS)
1535 			goto out;
1536 		break;
1537 
1538 	case TEE_TYPE_DH_KEYPAIR:
1539 		res = tee_svc_obj_generate_key_dh(o, type_props, key_size,
1540 						  params, param_count);
1541 		if (res != TEE_SUCCESS)
1542 			goto out;
1543 		break;
1544 
1545 	default:
1546 		res = TEE_ERROR_BAD_FORMAT;
1547 	}
1548 
1549 out:
1550 	free(params);
1551 	if (res == TEE_SUCCESS) {
1552 		o->info.keySize = key_size;
1553 		o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
1554 	}
1555 	return res;
1556 }
1557 
1558 static TEE_Result tee_svc_cryp_get_state(struct tee_ta_session *sess,
1559 					 uint32_t state_id,
1560 					 struct tee_cryp_state **state)
1561 {
1562 	struct tee_cryp_state *s;
1563 
1564 	TAILQ_FOREACH(s, &sess->ctx->cryp_states, link) {
1565 		if (state_id == (vaddr_t)s) {
1566 			*state = s;
1567 			return TEE_SUCCESS;
1568 		}
1569 	}
1570 	return TEE_ERROR_BAD_PARAMETERS;
1571 }
1572 
1573 static void cryp_state_free(struct tee_ta_ctx *ctx, struct tee_cryp_state *cs)
1574 {
1575 	struct tee_obj *o;
1576 
1577 	if (tee_obj_get(ctx, cs->key1, &o) == TEE_SUCCESS)
1578 		tee_obj_close(ctx, o);
1579 	if (tee_obj_get(ctx, cs->key2, &o) == TEE_SUCCESS)
1580 		tee_obj_close(ctx, o);
1581 
1582 	TAILQ_REMOVE(&ctx->cryp_states, cs, link);
1583 	if (cs->ctx_finalize != NULL)
1584 		cs->ctx_finalize(cs->ctx, cs->algo);
1585 	free(cs->ctx);
1586 	free(cs);
1587 }
1588 
1589 static TEE_Result tee_svc_cryp_check_key_type(const struct tee_obj *o,
1590 					      uint32_t algo,
1591 					      TEE_OperationMode mode)
1592 {
1593 	uint32_t req_key_type;
1594 
1595 	switch (TEE_ALG_GET_MAIN_ALG(algo)) {
1596 	case TEE_MAIN_ALGO_MD5:
1597 		req_key_type = TEE_TYPE_HMAC_MD5;
1598 		break;
1599 	case TEE_MAIN_ALGO_SHA1:
1600 		req_key_type = TEE_TYPE_HMAC_SHA1;
1601 		break;
1602 	case TEE_MAIN_ALGO_SHA224:
1603 		req_key_type = TEE_TYPE_HMAC_SHA224;
1604 		break;
1605 	case TEE_MAIN_ALGO_SHA256:
1606 		req_key_type = TEE_TYPE_HMAC_SHA256;
1607 		break;
1608 	case TEE_MAIN_ALGO_SHA384:
1609 		req_key_type = TEE_TYPE_HMAC_SHA384;
1610 		break;
1611 	case TEE_MAIN_ALGO_SHA512:
1612 		req_key_type = TEE_TYPE_HMAC_SHA512;
1613 		break;
1614 	case TEE_MAIN_ALGO_AES:
1615 		req_key_type = TEE_TYPE_AES;
1616 		break;
1617 	case TEE_MAIN_ALGO_DES:
1618 		req_key_type = TEE_TYPE_DES;
1619 		break;
1620 	case TEE_MAIN_ALGO_DES3:
1621 		req_key_type = TEE_TYPE_DES3;
1622 		break;
1623 	case TEE_MAIN_ALGO_RSA:
1624 		if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY)
1625 			req_key_type = TEE_TYPE_RSA_PUBLIC_KEY;
1626 		else
1627 			req_key_type = TEE_TYPE_RSA_KEYPAIR;
1628 		break;
1629 	case TEE_MAIN_ALGO_DSA:
1630 		if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY)
1631 			req_key_type = TEE_TYPE_DSA_PUBLIC_KEY;
1632 		else
1633 			req_key_type = TEE_TYPE_DSA_KEYPAIR;
1634 		break;
1635 	case TEE_MAIN_ALGO_DH:
1636 		req_key_type = TEE_TYPE_DH_KEYPAIR;
1637 		break;
1638 #if defined(CFG_CRYPTO_HKDF)
1639 	case TEE_MAIN_ALGO_HKDF:
1640 		req_key_type = TEE_TYPE_HKDF_IKM;
1641 		break;
1642 #endif
1643 #if defined(CFG_CRYPTO_CONCAT_KDF)
1644 	case TEE_MAIN_ALGO_CONCAT_KDF:
1645 		req_key_type = TEE_TYPE_CONCAT_KDF_Z;
1646 		break;
1647 #endif
1648 #if defined(CFG_CRYPTO_PBKDF2)
1649 	case TEE_MAIN_ALGO_PBKDF2:
1650 		req_key_type = TEE_TYPE_PBKDF2_PASSWORD;
1651 		break;
1652 #endif
1653 	default:
1654 		return TEE_ERROR_BAD_PARAMETERS;
1655 	}
1656 
1657 	if (req_key_type != o->info.objectType)
1658 		return TEE_ERROR_BAD_PARAMETERS;
1659 	return TEE_SUCCESS;
1660 }
1661 
1662 TEE_Result tee_svc_cryp_state_alloc(uint32_t algo, uint32_t mode,
1663 				    uint32_t key1, uint32_t key2,
1664 				    uint32_t *state)
1665 {
1666 	TEE_Result res;
1667 	struct tee_cryp_state *cs;
1668 	struct tee_ta_session *sess;
1669 	struct tee_obj *o1 = NULL;
1670 	struct tee_obj *o2 = NULL;
1671 
1672 	res = tee_ta_get_current_session(&sess);
1673 	if (res != TEE_SUCCESS)
1674 		return res;
1675 
1676 	if (key1 != 0) {
1677 		res = tee_obj_get(sess->ctx, key1, &o1);
1678 		if (res != TEE_SUCCESS)
1679 			return res;
1680 		if (o1->busy)
1681 			return TEE_ERROR_BAD_PARAMETERS;
1682 		res = tee_svc_cryp_check_key_type(o1, algo, mode);
1683 		if (res != TEE_SUCCESS)
1684 			return res;
1685 	}
1686 	if (key2 != 0) {
1687 		res = tee_obj_get(sess->ctx, key2, &o2);
1688 		if (res != TEE_SUCCESS)
1689 			return res;
1690 		if (o2->busy)
1691 			return TEE_ERROR_BAD_PARAMETERS;
1692 		res = tee_svc_cryp_check_key_type(o2, algo, mode);
1693 		if (res != TEE_SUCCESS)
1694 			return res;
1695 	}
1696 
1697 	cs = calloc(1, sizeof(struct tee_cryp_state));
1698 	if (!cs)
1699 		return TEE_ERROR_OUT_OF_MEMORY;
1700 	TAILQ_INSERT_TAIL(&sess->ctx->cryp_states, cs, link);
1701 	cs->algo = algo;
1702 	cs->mode = mode;
1703 
1704 	switch (TEE_ALG_GET_CLASS(algo)) {
1705 	case TEE_OPERATION_CIPHER:
1706 		if ((algo == TEE_ALG_AES_XTS && (key1 == 0 || key2 == 0)) ||
1707 		    (algo != TEE_ALG_AES_XTS && (key1 == 0 || key2 != 0))) {
1708 			res = TEE_ERROR_BAD_PARAMETERS;
1709 		} else {
1710 			if (crypto_ops.cipher.get_ctx_size)
1711 				res = crypto_ops.cipher.get_ctx_size(algo,
1712 								&cs->ctx_size);
1713 			else
1714 				res = TEE_ERROR_NOT_IMPLEMENTED;
1715 			if (res != TEE_SUCCESS)
1716 				break;
1717 			cs->ctx = calloc(1, cs->ctx_size);
1718 			if (!cs->ctx)
1719 				res = TEE_ERROR_OUT_OF_MEMORY;
1720 		}
1721 		break;
1722 	case TEE_OPERATION_AE:
1723 		if (key1 == 0 || key2 != 0) {
1724 			res = TEE_ERROR_BAD_PARAMETERS;
1725 		} else {
1726 			if (crypto_ops.authenc.get_ctx_size)
1727 				res = crypto_ops.authenc.get_ctx_size(algo,
1728 								&cs->ctx_size);
1729 			else
1730 				res = TEE_ERROR_NOT_IMPLEMENTED;
1731 			if (res != TEE_SUCCESS)
1732 				break;
1733 			cs->ctx = calloc(1, cs->ctx_size);
1734 			if (!cs->ctx)
1735 				res = TEE_ERROR_OUT_OF_MEMORY;
1736 		}
1737 		break;
1738 	case TEE_OPERATION_MAC:
1739 		if (key1 == 0 || key2 != 0) {
1740 			res = TEE_ERROR_BAD_PARAMETERS;
1741 		} else {
1742 			if (crypto_ops.mac.get_ctx_size)
1743 				res = crypto_ops.mac.get_ctx_size(algo,
1744 								&cs->ctx_size);
1745 			else
1746 				res = TEE_ERROR_NOT_IMPLEMENTED;
1747 			if (res != TEE_SUCCESS)
1748 				break;
1749 			cs->ctx = calloc(1, cs->ctx_size);
1750 			if (!cs->ctx)
1751 				res = TEE_ERROR_OUT_OF_MEMORY;
1752 		}
1753 		break;
1754 	case TEE_OPERATION_DIGEST:
1755 		if (key1 != 0 || key2 != 0) {
1756 			res = TEE_ERROR_BAD_PARAMETERS;
1757 		} else {
1758 			if (crypto_ops.hash.get_ctx_size)
1759 				res = crypto_ops.hash.get_ctx_size(algo,
1760 								&cs->ctx_size);
1761 			else
1762 				res = TEE_ERROR_NOT_IMPLEMENTED;
1763 			if (res != TEE_SUCCESS)
1764 				break;
1765 			cs->ctx = calloc(1, cs->ctx_size);
1766 			if (!cs->ctx)
1767 				res = TEE_ERROR_OUT_OF_MEMORY;
1768 		}
1769 		break;
1770 	case TEE_OPERATION_ASYMMETRIC_CIPHER:
1771 	case TEE_OPERATION_ASYMMETRIC_SIGNATURE:
1772 		if (key1 == 0 || key2 != 0)
1773 			res = TEE_ERROR_BAD_PARAMETERS;
1774 		break;
1775 	case TEE_OPERATION_KEY_DERIVATION:
1776 		if (key1 == 0 || key2 != 0)
1777 			res = TEE_ERROR_BAD_PARAMETERS;
1778 		break;
1779 	default:
1780 		res = TEE_ERROR_NOT_SUPPORTED;
1781 		break;
1782 	}
1783 	if (res != TEE_SUCCESS)
1784 		goto out;
1785 
1786 	res = tee_svc_copy_to_user(sess, state, &cs, sizeof(uint32_t));
1787 	if (res != TEE_SUCCESS)
1788 		goto out;
1789 
1790 	/* Register keys */
1791 	if (o1 != NULL) {
1792 		o1->busy = true;
1793 		cs->key1 = key1;
1794 	}
1795 	if (o2 != NULL) {
1796 		o2->busy = true;
1797 		cs->key2 = key2;
1798 	}
1799 
1800 out:
1801 	if (res != TEE_SUCCESS)
1802 		cryp_state_free(sess->ctx, cs);
1803 	return res;
1804 }
1805 
1806 TEE_Result tee_svc_cryp_state_copy(uint32_t dst, uint32_t src)
1807 {
1808 	TEE_Result res;
1809 	struct tee_cryp_state *cs_dst;
1810 	struct tee_cryp_state *cs_src;
1811 	struct tee_ta_session *sess;
1812 
1813 	res = tee_ta_get_current_session(&sess);
1814 	if (res != TEE_SUCCESS)
1815 		return res;
1816 
1817 	res = tee_svc_cryp_get_state(sess, dst, &cs_dst);
1818 	if (res != TEE_SUCCESS)
1819 		return res;
1820 	res = tee_svc_cryp_get_state(sess, src, &cs_src);
1821 	if (res != TEE_SUCCESS)
1822 		return res;
1823 	if (cs_dst->algo != cs_src->algo || cs_dst->mode != cs_src->mode)
1824 		return TEE_ERROR_BAD_PARAMETERS;
1825 	/* "Can't happen" */
1826 	if (cs_dst->ctx_size != cs_src->ctx_size)
1827 		return TEE_ERROR_BAD_STATE;
1828 
1829 	memcpy(cs_dst->ctx, cs_src->ctx, cs_src->ctx_size);
1830 	return TEE_SUCCESS;
1831 }
1832 
1833 void tee_svc_cryp_free_states(struct tee_ta_ctx *ctx)
1834 {
1835 	struct tee_cryp_state_head *states = &ctx->cryp_states;
1836 
1837 	while (!TAILQ_EMPTY(states))
1838 		cryp_state_free(ctx, TAILQ_FIRST(states));
1839 }
1840 
1841 TEE_Result tee_svc_cryp_state_free(uint32_t state)
1842 {
1843 	TEE_Result res;
1844 	struct tee_cryp_state *cs;
1845 	struct tee_ta_session *sess;
1846 
1847 	res = tee_ta_get_current_session(&sess);
1848 	if (res != TEE_SUCCESS)
1849 		return res;
1850 
1851 	res = tee_svc_cryp_get_state(sess, state, &cs);
1852 	if (res != TEE_SUCCESS)
1853 		return res;
1854 	cryp_state_free(sess->ctx, cs);
1855 	return TEE_SUCCESS;
1856 }
1857 
1858 /* iv and iv_len are ignored for some algorithms */
1859 TEE_Result tee_svc_hash_init(uint32_t state, const void *iv __unused,
1860 		size_t iv_len __unused)
1861 {
1862 	TEE_Result res;
1863 	struct tee_cryp_state *cs;
1864 	struct tee_ta_session *sess;
1865 
1866 	res = tee_ta_get_current_session(&sess);
1867 	if (res != TEE_SUCCESS)
1868 		return res;
1869 
1870 	res = tee_svc_cryp_get_state(sess, state, &cs);
1871 	if (res != TEE_SUCCESS)
1872 		return res;
1873 
1874 	switch (TEE_ALG_GET_CLASS(cs->algo)) {
1875 	case TEE_OPERATION_DIGEST:
1876 		if (!crypto_ops.hash.init)
1877 			return TEE_ERROR_NOT_IMPLEMENTED;
1878 		res = crypto_ops.hash.init(cs->ctx, cs->algo);
1879 		if (res != TEE_SUCCESS)
1880 			return res;
1881 		break;
1882 	case TEE_OPERATION_MAC:
1883 		{
1884 			struct tee_obj *o;
1885 			struct tee_cryp_obj_secret *key;
1886 
1887 			res = tee_obj_get(sess->ctx, cs->key1, &o);
1888 			if (res != TEE_SUCCESS)
1889 				return res;
1890 			if ((o->info.handleFlags &
1891 			     TEE_HANDLE_FLAG_INITIALIZED) == 0)
1892 				return TEE_ERROR_BAD_PARAMETERS;
1893 
1894 			key = (struct tee_cryp_obj_secret *)o->data;
1895 			if (!crypto_ops.mac.init)
1896 				return TEE_ERROR_NOT_IMPLEMENTED;
1897 			res = crypto_ops.mac.init(cs->ctx, cs->algo,
1898 						  (void *)(key + 1),
1899 						  key->key_size);
1900 			if (res != TEE_SUCCESS)
1901 				return res;
1902 			break;
1903 		}
1904 	default:
1905 		return TEE_ERROR_BAD_PARAMETERS;
1906 	}
1907 
1908 	return TEE_SUCCESS;
1909 }
1910 
1911 TEE_Result tee_svc_hash_update(uint32_t state, const void *chunk,
1912 			       size_t chunk_size)
1913 {
1914 	TEE_Result res;
1915 	struct tee_cryp_state *cs;
1916 	struct tee_ta_session *sess;
1917 
1918 	/* No data, but size provided isn't valid parameters. */
1919 	if (!chunk && chunk_size)
1920 		return TEE_ERROR_BAD_PARAMETERS;
1921 
1922 	/* Zero length hash is valid, but nothing we need to do. */
1923 	if (!chunk_size)
1924 		return TEE_SUCCESS;
1925 
1926 	res = tee_ta_get_current_session(&sess);
1927 	if (res != TEE_SUCCESS)
1928 		return res;
1929 
1930 	res = tee_mmu_check_access_rights(sess->ctx,
1931 					  TEE_MEMORY_ACCESS_READ |
1932 					  TEE_MEMORY_ACCESS_ANY_OWNER,
1933 					  (tee_uaddr_t)chunk, chunk_size);
1934 	if (res != TEE_SUCCESS)
1935 		return res;
1936 
1937 	res = tee_svc_cryp_get_state(sess, state, &cs);
1938 	if (res != TEE_SUCCESS)
1939 		return res;
1940 
1941 	switch (TEE_ALG_GET_CLASS(cs->algo)) {
1942 	case TEE_OPERATION_DIGEST:
1943 		if (!crypto_ops.hash.update)
1944 			return TEE_ERROR_NOT_IMPLEMENTED;
1945 		res = crypto_ops.hash.update(cs->ctx, cs->algo, chunk,
1946 					     chunk_size);
1947 		if (res != TEE_SUCCESS)
1948 			return res;
1949 		break;
1950 	case TEE_OPERATION_MAC:
1951 		if (!crypto_ops.mac.update)
1952 			return TEE_ERROR_NOT_IMPLEMENTED;
1953 		res = crypto_ops.mac.update(cs->ctx, cs->algo, chunk,
1954 					    chunk_size);
1955 		if (res != TEE_SUCCESS)
1956 			return res;
1957 		break;
1958 	default:
1959 		return TEE_ERROR_BAD_PARAMETERS;
1960 	}
1961 
1962 	return TEE_SUCCESS;
1963 }
1964 
1965 TEE_Result tee_svc_hash_final(uint32_t state, const void *chunk,
1966 			      size_t chunk_size, void *hash, uint32_t *hash_len)
1967 {
1968 	TEE_Result res, res2;
1969 	size_t hash_size;
1970 	uint32_t hlen;
1971 	struct tee_cryp_state *cs;
1972 	struct tee_ta_session *sess;
1973 
1974 	/* No data, but size provided isn't valid parameters. */
1975 	if (!chunk && chunk_size)
1976 		return TEE_ERROR_BAD_PARAMETERS;
1977 
1978 	res = tee_ta_get_current_session(&sess);
1979 	if (res != TEE_SUCCESS)
1980 		return res;
1981 
1982 	res = tee_mmu_check_access_rights(sess->ctx,
1983 					  TEE_MEMORY_ACCESS_READ |
1984 					  TEE_MEMORY_ACCESS_ANY_OWNER,
1985 					  (tee_uaddr_t)chunk, chunk_size);
1986 	if (res != TEE_SUCCESS)
1987 		return res;
1988 
1989 	res = tee_svc_copy_from_user(sess, &hlen, hash_len, sizeof(uint32_t));
1990 	if (res != TEE_SUCCESS)
1991 		return res;
1992 
1993 	res = tee_mmu_check_access_rights(sess->ctx,
1994 					  TEE_MEMORY_ACCESS_READ |
1995 					  TEE_MEMORY_ACCESS_WRITE |
1996 					  TEE_MEMORY_ACCESS_ANY_OWNER,
1997 					  (tee_uaddr_t)hash, hlen);
1998 	if (res != TEE_SUCCESS)
1999 		return res;
2000 
2001 	res = tee_svc_cryp_get_state(sess, state, &cs);
2002 	if (res != TEE_SUCCESS)
2003 		return res;
2004 
2005 	switch (TEE_ALG_GET_CLASS(cs->algo)) {
2006 	case TEE_OPERATION_DIGEST:
2007 		if (!crypto_ops.hash.update || !crypto_ops.hash.final)
2008 			return TEE_ERROR_NOT_IMPLEMENTED;
2009 		res = tee_hash_get_digest_size(cs->algo, &hash_size);
2010 		if (res != TEE_SUCCESS)
2011 			return res;
2012 		if (*hash_len < hash_size) {
2013 			res = TEE_ERROR_SHORT_BUFFER;
2014 			goto out;
2015 		}
2016 
2017 		if (chunk_size) {
2018 			res = crypto_ops.hash.update(cs->ctx, cs->algo, chunk,
2019 						     chunk_size);
2020 			if (res != TEE_SUCCESS)
2021 				return res;
2022 		}
2023 
2024 		res = crypto_ops.hash.final(cs->ctx, cs->algo, hash,
2025 					    hash_size);
2026 		if (res != TEE_SUCCESS)
2027 			return res;
2028 		break;
2029 
2030 	case TEE_OPERATION_MAC:
2031 		if (!crypto_ops.mac.update || !crypto_ops.mac.final)
2032 			return TEE_ERROR_NOT_IMPLEMENTED;
2033 		res = tee_mac_get_digest_size(cs->algo, &hash_size);
2034 		if (res != TEE_SUCCESS)
2035 			return res;
2036 		if (*hash_len < hash_size) {
2037 			res = TEE_ERROR_SHORT_BUFFER;
2038 			goto out;
2039 		}
2040 
2041 		if (chunk_size) {
2042 			res = crypto_ops.mac.update(cs->ctx, cs->algo, chunk,
2043 						    chunk_size);
2044 			if (res != TEE_SUCCESS)
2045 				return res;
2046 		}
2047 
2048 		res = crypto_ops.mac.final(cs->ctx, cs->algo, hash, hash_size);
2049 		if (res != TEE_SUCCESS)
2050 			return res;
2051 		break;
2052 
2053 	default:
2054 		return TEE_ERROR_BAD_PARAMETERS;
2055 	}
2056 out:
2057 	hlen = hash_size;
2058 	res2 = tee_svc_copy_to_user(sess, hash_len, &hlen, sizeof(uint32_t));
2059 	if (res2 != TEE_SUCCESS)
2060 		return res2;
2061 	return res;
2062 }
2063 
2064 TEE_Result tee_svc_cipher_init(uint32_t state, const void *iv, size_t iv_len)
2065 {
2066 	TEE_Result res;
2067 	struct tee_cryp_state *cs;
2068 	struct tee_ta_session *sess;
2069 	struct tee_obj *o;
2070 	struct tee_cryp_obj_secret *key1;
2071 
2072 	res = tee_ta_get_current_session(&sess);
2073 	if (res != TEE_SUCCESS)
2074 		return res;
2075 
2076 	res = tee_svc_cryp_get_state(sess, state, &cs);
2077 	if (res != TEE_SUCCESS)
2078 		return res;
2079 
2080 	res = tee_mmu_check_access_rights(sess->ctx,
2081 					  TEE_MEMORY_ACCESS_READ |
2082 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2083 					  (tee_uaddr_t) iv, iv_len);
2084 	if (res != TEE_SUCCESS)
2085 		return res;
2086 
2087 	res = tee_obj_get(sess->ctx, cs->key1, &o);
2088 	if (res != TEE_SUCCESS)
2089 		return res;
2090 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
2091 		return TEE_ERROR_BAD_PARAMETERS;
2092 
2093 	key1 = (struct tee_cryp_obj_secret *)o->data;
2094 
2095 	if (!crypto_ops.cipher.init)
2096 		return TEE_ERROR_NOT_IMPLEMENTED;
2097 
2098 	if (tee_obj_get(sess->ctx, cs->key2, &o) == TEE_SUCCESS) {
2099 		struct tee_cryp_obj_secret *key2 =
2100 		    (struct tee_cryp_obj_secret *)o->data;
2101 
2102 		if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
2103 			return TEE_ERROR_BAD_PARAMETERS;
2104 
2105 		res = crypto_ops.cipher.init(cs->ctx, cs->algo, cs->mode,
2106 					     (uint8_t *)(key1 + 1),
2107 					     key1->key_size,
2108 					     (uint8_t *)(key2 + 1),
2109 					     key2->key_size,
2110 					     iv, iv_len);
2111 	} else {
2112 		res = crypto_ops.cipher.init(cs->ctx, cs->algo, cs->mode,
2113 					     (uint8_t *)(key1 + 1),
2114 					     key1->key_size,
2115 					     NULL,
2116 					     0,
2117 					     iv, iv_len);
2118 	}
2119 	if (res != TEE_SUCCESS)
2120 		return res;
2121 
2122 	cs->ctx_finalize = crypto_ops.cipher.final;
2123 	return TEE_SUCCESS;
2124 }
2125 
2126 static TEE_Result tee_svc_cipher_update_helper(uint32_t state, bool last_block,
2127 					       const void *src, size_t src_len,
2128 					       void *dst, uint32_t *dst_len)
2129 {
2130 	TEE_Result res;
2131 	struct tee_cryp_state *cs;
2132 	struct tee_ta_session *sess;
2133 	uint32_t dlen;
2134 
2135 	res = tee_ta_get_current_session(&sess);
2136 	if (res != TEE_SUCCESS)
2137 		return res;
2138 
2139 	res = tee_svc_cryp_get_state(sess, state, &cs);
2140 	if (res != TEE_SUCCESS)
2141 		return res;
2142 
2143 	res = tee_mmu_check_access_rights(sess->ctx,
2144 					  TEE_MEMORY_ACCESS_READ |
2145 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2146 					  (tee_uaddr_t)src, src_len);
2147 	if (res != TEE_SUCCESS)
2148 		return res;
2149 
2150 	if (!dst_len) {
2151 		dlen = 0;
2152 	} else {
2153 		res =
2154 		    tee_svc_copy_from_user(sess, &dlen, dst_len,
2155 					   sizeof(uint32_t));
2156 		if (res != TEE_SUCCESS)
2157 			return res;
2158 
2159 		res = tee_mmu_check_access_rights(sess->ctx,
2160 						  TEE_MEMORY_ACCESS_READ |
2161 						  TEE_MEMORY_ACCESS_WRITE |
2162 						  TEE_MEMORY_ACCESS_ANY_OWNER,
2163 						  (tee_uaddr_t)dst, dlen);
2164 		if (res != TEE_SUCCESS)
2165 			return res;
2166 	}
2167 
2168 	if (dlen < src_len) {
2169 		res = TEE_ERROR_SHORT_BUFFER;
2170 		goto out;
2171 	}
2172 
2173 	if (src_len > 0) {
2174 		/* Permit src_len == 0 to finalize the operation */
2175 		res = tee_do_cipher_update(cs->ctx, cs->algo, cs->mode,
2176 					   last_block, src, src_len, dst);
2177 	}
2178 
2179 	if (last_block && cs->ctx_finalize != NULL) {
2180 		cs->ctx_finalize(cs->ctx, cs->mode);
2181 		cs->ctx_finalize = NULL;
2182 	}
2183 
2184 out:
2185 	if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) &&
2186 	    dst_len != NULL) {
2187 		TEE_Result res2;
2188 
2189 		dlen = src_len;
2190 		res2 = tee_svc_copy_to_user(sess, dst_len, &dlen,
2191 					    sizeof(uint32_t));
2192 		if (res2 != TEE_SUCCESS)
2193 			res = res2;
2194 	}
2195 
2196 	return res;
2197 }
2198 
2199 TEE_Result tee_svc_cipher_update(uint32_t state, const void *src,
2200 				 size_t src_len, void *dst, uint32_t *dst_len)
2201 {
2202 	return tee_svc_cipher_update_helper(state, false /* last_block */,
2203 					    src, src_len, dst, dst_len);
2204 }
2205 
2206 TEE_Result tee_svc_cipher_final(uint32_t state, const void *src,
2207 				size_t src_len, void *dst, uint32_t *dst_len)
2208 {
2209 	return tee_svc_cipher_update_helper(state, true /* last_block */,
2210 					    src, src_len, dst, dst_len);
2211 }
2212 
2213 #if defined(CFG_CRYPTO_HKDF)
2214 static TEE_Result get_hkdf_params(const TEE_Attribute *params,
2215 				  uint32_t param_count,
2216 				  void **salt, size_t *salt_len, void **info,
2217 				  size_t *info_len, size_t *okm_len)
2218 {
2219 	size_t n;
2220 	enum { SALT = 0x1, LENGTH = 0x2, INFO = 0x4 };
2221 	uint8_t found = 0;
2222 
2223 	*salt = *info = NULL;
2224 	*salt_len = *info_len = *okm_len = 0;
2225 
2226 	for (n = 0; n < param_count; n++) {
2227 		switch (params[n].attributeID) {
2228 		case TEE_ATTR_HKDF_SALT:
2229 			if (!(found & SALT)) {
2230 				*salt = params[n].content.ref.buffer;
2231 				*salt_len = params[n].content.ref.length;
2232 				found |= SALT;
2233 			}
2234 			break;
2235 		case TEE_ATTR_HKDF_OKM_LENGTH:
2236 			if (!(found & LENGTH)) {
2237 				*okm_len = params[n].content.value.a;
2238 				found |= LENGTH;
2239 			}
2240 			break;
2241 		case TEE_ATTR_HKDF_INFO:
2242 			if (!(found & INFO)) {
2243 				*info = params[n].content.ref.buffer;
2244 				*info_len = params[n].content.ref.length;
2245 				found |= INFO;
2246 			}
2247 			break;
2248 		default:
2249 			/* Unexpected attribute */
2250 			return TEE_ERROR_BAD_PARAMETERS;
2251 		}
2252 
2253 	}
2254 
2255 	if (!(found & LENGTH))
2256 		return TEE_ERROR_BAD_PARAMETERS;
2257 
2258 	return TEE_SUCCESS;
2259 }
2260 #endif
2261 
2262 #if defined(CFG_CRYPTO_CONCAT_KDF)
2263 static TEE_Result get_concat_kdf_params(const TEE_Attribute *params,
2264 					uint32_t param_count,
2265 					void **other_info,
2266 					size_t *other_info_len,
2267 					size_t *derived_key_len)
2268 {
2269 	size_t n;
2270 	enum { LENGTH = 0x1, INFO = 0x2 };
2271 	uint8_t found = 0;
2272 
2273 	*other_info = NULL;
2274 	*other_info_len = *derived_key_len = 0;
2275 
2276 	for (n = 0; n < param_count; n++) {
2277 		switch (params[n].attributeID) {
2278 		case TEE_ATTR_CONCAT_KDF_OTHER_INFO:
2279 			if (!(found & INFO)) {
2280 				*other_info = params[n].content.ref.buffer;
2281 				*other_info_len = params[n].content.ref.length;
2282 				found |= INFO;
2283 			}
2284 			break;
2285 		case TEE_ATTR_CONCAT_KDF_DKM_LENGTH:
2286 			if (!(found & LENGTH)) {
2287 				*derived_key_len = params[n].content.value.a;
2288 				found |= LENGTH;
2289 			}
2290 			break;
2291 		default:
2292 			/* Unexpected attribute */
2293 			return TEE_ERROR_BAD_PARAMETERS;
2294 		}
2295 	}
2296 
2297 	if (!(found & LENGTH))
2298 		return TEE_ERROR_BAD_PARAMETERS;
2299 
2300 	return TEE_SUCCESS;
2301 }
2302 #endif
2303 
2304 #if defined(CFG_CRYPTO_PBKDF2)
2305 static TEE_Result get_pbkdf2_params(const TEE_Attribute *params,
2306 				   uint32_t param_count, void **salt,
2307 				   size_t *salt_len, size_t *derived_key_len,
2308 				   size_t *iteration_count)
2309 {
2310 	size_t n;
2311 	enum { SALT = 0x1, LENGTH = 0x2, COUNT = 0x4 };
2312 	uint8_t found = 0;
2313 
2314 	*salt = NULL;
2315 	*salt_len = *derived_key_len = *iteration_count = 0;
2316 
2317 	for (n = 0; n < param_count; n++) {
2318 		switch (params[n].attributeID) {
2319 		case TEE_ATTR_PBKDF2_SALT:
2320 			if (!(found & SALT)) {
2321 				*salt = params[n].content.ref.buffer;
2322 				*salt_len = params[n].content.ref.length;
2323 				found |= SALT;
2324 			}
2325 			break;
2326 		case TEE_ATTR_PBKDF2_DKM_LENGTH:
2327 			if (!(found & LENGTH)) {
2328 				*derived_key_len = params[n].content.value.a;
2329 				found |= LENGTH;
2330 			}
2331 			break;
2332 		case TEE_ATTR_PBKDF2_ITERATION_COUNT:
2333 			if (!(found & COUNT)) {
2334 				*iteration_count = params[n].content.value.a;
2335 				found |= COUNT;
2336 			}
2337 			break;
2338 		default:
2339 			/* Unexpected attribute */
2340 			return TEE_ERROR_BAD_PARAMETERS;
2341 		}
2342 	}
2343 
2344 	if ((found & (LENGTH|COUNT)) != (LENGTH|COUNT))
2345 		return TEE_ERROR_BAD_PARAMETERS;
2346 
2347 	return TEE_SUCCESS;
2348 }
2349 #endif
2350 
2351 TEE_Result tee_svc_cryp_derive_key(uint32_t state,
2352 			const struct abi_user32_attribute *usr_params,
2353 			uint32_t param_count, uint32_t derived_key)
2354 {
2355 	TEE_Result res = TEE_ERROR_NOT_SUPPORTED;
2356 	struct tee_ta_session *sess;
2357 	struct tee_obj *ko;
2358 	struct tee_obj *so;
2359 	struct tee_cryp_state *cs;
2360 	struct tee_cryp_obj_secret *sk;
2361 	const struct tee_cryp_obj_type_props *type_props;
2362 	TEE_Attribute *params = NULL;
2363 
2364 	res = tee_ta_get_current_session(&sess);
2365 	if (res != TEE_SUCCESS)
2366 		return res;
2367 
2368 	res = tee_svc_cryp_get_state(sess, state, &cs);
2369 	if (res != TEE_SUCCESS)
2370 		return res;
2371 
2372 	params = malloc(sizeof(TEE_Attribute) * param_count);
2373 	if (!params)
2374 		return TEE_ERROR_OUT_OF_MEMORY;
2375 	res = copy_in_attrs(sess->ctx, usr_params, param_count, params);
2376 	if (res != TEE_SUCCESS)
2377 		goto out;
2378 
2379 	/* Get key set in operation */
2380 	res = tee_obj_get(sess->ctx, cs->key1, &ko);
2381 	if (res != TEE_SUCCESS)
2382 		goto out;
2383 
2384 	res = tee_obj_get(sess->ctx, derived_key, &so);
2385 	if (res != TEE_SUCCESS)
2386 		goto out;
2387 
2388 	/* Find information needed about the object to initialize */
2389 	sk = (struct tee_cryp_obj_secret *)so->data;
2390 
2391 	/* Find description of object */
2392 	type_props = tee_svc_find_type_props(so->info.objectType);
2393 	if (!type_props) {
2394 		res = TEE_ERROR_NOT_SUPPORTED;
2395 		goto out;
2396 	}
2397 
2398 	if (cs->algo == TEE_ALG_DH_DERIVE_SHARED_SECRET) {
2399 		size_t alloc_size;
2400 		struct bignum *pub;
2401 		struct bignum *ss;
2402 
2403 		if (!crypto_ops.bignum.allocate ||
2404 		    !crypto_ops.bignum.free ||
2405 		    !crypto_ops.bignum.bin2bn ||
2406 		    !crypto_ops.bignum.bn2bin ||
2407 		    !crypto_ops.bignum.num_bytes ||
2408 		    !crypto_ops.acipher.dh_shared_secret) {
2409 			res = TEE_ERROR_NOT_IMPLEMENTED;
2410 			goto out;
2411 		}
2412 		if (param_count != 1 ||
2413 		    params[0].attributeID != TEE_ATTR_DH_PUBLIC_VALUE) {
2414 			res = TEE_ERROR_BAD_PARAMETERS;
2415 			goto out;
2416 		}
2417 
2418 		alloc_size = params[0].content.ref.length * 8;
2419 		pub = crypto_ops.bignum.allocate(alloc_size);
2420 		ss = crypto_ops.bignum.allocate(alloc_size);
2421 		if (pub && ss) {
2422 			crypto_ops.bignum.bin2bn(params[0].content.ref.buffer,
2423 					params[0].content.ref.length, pub);
2424 			res = crypto_ops.acipher.dh_shared_secret(ko->data,
2425 								  pub, ss);
2426 			if (res == TEE_SUCCESS) {
2427 				sk->key_size = crypto_ops.bignum.num_bytes(ss);
2428 				crypto_ops.bignum.bn2bin(ss,
2429 							 (uint8_t *)(sk + 1));
2430 				so->info.handleFlags |=
2431 						TEE_HANDLE_FLAG_INITIALIZED;
2432 				SET_ATTRIBUTE(so, type_props,
2433 					      TEE_ATTR_SECRET_VALUE);
2434 			}
2435 		} else {
2436 			res = TEE_ERROR_OUT_OF_MEMORY;
2437 		}
2438 		crypto_ops.bignum.free(pub);
2439 		crypto_ops.bignum.free(ss);
2440 	}
2441 #if defined(CFG_CRYPTO_HKDF)
2442 	else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_HKDF) {
2443 		void *salt, *info;
2444 		size_t salt_len, info_len, okm_len;
2445 		uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
2446 		struct tee_cryp_obj_secret *ik = ko->data;
2447 		const uint8_t *ikm = (const uint8_t *)(ik + 1);
2448 
2449 		res = get_hkdf_params(params, param_count, &salt, &salt_len,
2450 				      &info, &info_len, &okm_len);
2451 		if (res != TEE_SUCCESS)
2452 			goto out;
2453 
2454 		/* Requested size must fit into the output object's buffer */
2455 		if (okm_len >
2456 			ko->data_size - sizeof(struct tee_cryp_obj_secret)) {
2457 			res = TEE_ERROR_BAD_PARAMETERS;
2458 			goto out;
2459 		}
2460 
2461 		res = tee_cryp_hkdf(hash_id, ikm, ik->key_size, salt, salt_len,
2462 				    info, info_len, (uint8_t *)(sk + 1),
2463 				    okm_len);
2464 		if (res == TEE_SUCCESS) {
2465 			sk->key_size = okm_len;
2466 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
2467 			SET_ATTRIBUTE(so, type_props, TEE_ATTR_SECRET_VALUE);
2468 		}
2469 	}
2470 #endif
2471 #if defined(CFG_CRYPTO_CONCAT_KDF)
2472 	else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_CONCAT_KDF) {
2473 		void *info;
2474 		size_t info_len, derived_key_len;
2475 		uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
2476 		struct tee_cryp_obj_secret *ss = ko->data;
2477 		const uint8_t *shared_secret = (const uint8_t *)(ss + 1);
2478 
2479 		res = get_concat_kdf_params(params, param_count, &info,
2480 					    &info_len, &derived_key_len);
2481 		if (res != TEE_SUCCESS)
2482 			goto out;
2483 
2484 		/* Requested size must fit into the output object's buffer */
2485 		if (derived_key_len >
2486 		    ko->data_size - sizeof(struct tee_cryp_obj_secret)) {
2487 			res = TEE_ERROR_BAD_PARAMETERS;
2488 			goto out;
2489 		}
2490 
2491 		res = tee_cryp_concat_kdf(hash_id, shared_secret, ss->key_size,
2492 					  info, info_len, (uint8_t *)(sk + 1),
2493 					  derived_key_len);
2494 		if (res == TEE_SUCCESS) {
2495 			sk->key_size = derived_key_len;
2496 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
2497 			SET_ATTRIBUTE(so, type_props, TEE_ATTR_SECRET_VALUE);
2498 		}
2499 	}
2500 #endif
2501 #if defined(CFG_CRYPTO_PBKDF2)
2502 	else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_PBKDF2) {
2503 		void *salt;
2504 		size_t salt_len, iteration_count, derived_key_len;
2505 		uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
2506 		struct tee_cryp_obj_secret *ss = ko->data;
2507 		const uint8_t *password = (const uint8_t *)(ss + 1);
2508 
2509 		res = get_pbkdf2_params(params, param_count, &salt, &salt_len,
2510 					&derived_key_len, &iteration_count);
2511 		if (res != TEE_SUCCESS)
2512 			goto out;
2513 
2514 		/* Requested size must fit into the output object's buffer */
2515 		if (derived_key_len >
2516 			ko->data_size - sizeof(struct tee_cryp_obj_secret)) {
2517 			res = TEE_ERROR_BAD_PARAMETERS;
2518 			goto out;
2519 		}
2520 
2521 		res = tee_cryp_pbkdf2(hash_id, password, ss->key_size, salt,
2522 				      salt_len, iteration_count,
2523 				      (uint8_t *)(sk + 1), derived_key_len);
2524 		if (res == TEE_SUCCESS) {
2525 			sk->key_size = derived_key_len;
2526 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
2527 			SET_ATTRIBUTE(so, type_props, TEE_ATTR_SECRET_VALUE);
2528 		}
2529 	}
2530 #endif
2531 	else
2532 		res = TEE_ERROR_NOT_SUPPORTED;
2533 
2534 out:
2535 	free(params);
2536 	return res;
2537 }
2538 
2539 TEE_Result tee_svc_cryp_random_number_generate(void *buf, size_t blen)
2540 {
2541 	TEE_Result res;
2542 	struct tee_ta_session *sess;
2543 
2544 	res = tee_ta_get_current_session(&sess);
2545 	if (res != TEE_SUCCESS)
2546 		return res;
2547 
2548 	res = tee_mmu_check_access_rights(sess->ctx,
2549 					  TEE_MEMORY_ACCESS_WRITE |
2550 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2551 					  (tee_uaddr_t)buf, blen);
2552 	if (res != TEE_SUCCESS)
2553 		return res;
2554 
2555 	res = crypto_ops.prng.read(buf, blen);
2556 	if (res != TEE_SUCCESS)
2557 		return res;
2558 
2559 	return res;
2560 }
2561 
2562 TEE_Result tee_svc_authenc_init(uint32_t state, const void *nonce,
2563 				size_t nonce_len, size_t tag_len,
2564 				size_t aad_len, size_t payload_len)
2565 {
2566 	TEE_Result res;
2567 	struct tee_cryp_state *cs;
2568 	struct tee_ta_session *sess;
2569 	struct tee_obj *o;
2570 	struct tee_cryp_obj_secret *key;
2571 
2572 	res = tee_ta_get_current_session(&sess);
2573 	if (res != TEE_SUCCESS)
2574 		return res;
2575 
2576 	res = tee_svc_cryp_get_state(sess, state, &cs);
2577 	if (res != TEE_SUCCESS)
2578 		return res;
2579 
2580 	res = tee_obj_get(sess->ctx, cs->key1, &o);
2581 	if (res != TEE_SUCCESS)
2582 		return res;
2583 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
2584 		return TEE_ERROR_BAD_PARAMETERS;
2585 
2586 	if (!crypto_ops.authenc.init)
2587 		return TEE_ERROR_NOT_IMPLEMENTED;
2588 	key = (struct tee_cryp_obj_secret *)o->data;
2589 	res = crypto_ops.authenc.init(cs->ctx, cs->algo, cs->mode,
2590 				      (uint8_t *)(key + 1), key->key_size,
2591 				      nonce, nonce_len, tag_len, aad_len,
2592 				      payload_len);
2593 	if (res != TEE_SUCCESS)
2594 		return res;
2595 
2596 	cs->ctx_finalize = (tee_cryp_ctx_finalize_func_t)
2597 				crypto_ops.authenc.final;
2598 	return TEE_SUCCESS;
2599 }
2600 
2601 TEE_Result tee_svc_authenc_update_aad(uint32_t state, const void *aad_data,
2602 				      size_t aad_data_len)
2603 {
2604 	TEE_Result res;
2605 	struct tee_cryp_state *cs;
2606 	struct tee_ta_session *sess;
2607 
2608 	res = tee_ta_get_current_session(&sess);
2609 	if (res != TEE_SUCCESS)
2610 		return res;
2611 
2612 	res = tee_mmu_check_access_rights(sess->ctx,
2613 					  TEE_MEMORY_ACCESS_READ |
2614 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2615 					  (tee_uaddr_t) aad_data,
2616 					  aad_data_len);
2617 	if (res != TEE_SUCCESS)
2618 		return res;
2619 
2620 	res = tee_svc_cryp_get_state(sess, state, &cs);
2621 	if (res != TEE_SUCCESS)
2622 		return res;
2623 
2624 	if (!crypto_ops.authenc.update_aad)
2625 		return TEE_ERROR_NOT_IMPLEMENTED;
2626 	res = crypto_ops.authenc.update_aad(cs->ctx, cs->algo, cs->mode,
2627 					    aad_data, aad_data_len);
2628 	if (res != TEE_SUCCESS)
2629 		return res;
2630 
2631 	return TEE_SUCCESS;
2632 }
2633 
2634 TEE_Result tee_svc_authenc_update_payload(uint32_t state, const void *src_data,
2635 					  size_t src_len, void *dst_data,
2636 					  uint32_t *dst_len)
2637 {
2638 	TEE_Result res;
2639 	struct tee_cryp_state *cs;
2640 	struct tee_ta_session *sess;
2641 	uint32_t dlen;
2642 	size_t tmp_dlen;
2643 
2644 	res = tee_ta_get_current_session(&sess);
2645 	if (res != TEE_SUCCESS)
2646 		return res;
2647 
2648 	res = tee_svc_cryp_get_state(sess, state, &cs);
2649 	if (res != TEE_SUCCESS)
2650 		return res;
2651 
2652 	res = tee_mmu_check_access_rights(sess->ctx,
2653 					  TEE_MEMORY_ACCESS_READ |
2654 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2655 					  (tee_uaddr_t) src_data, src_len);
2656 	if (res != TEE_SUCCESS)
2657 		return res;
2658 
2659 	res = tee_svc_copy_from_user(sess, &dlen, dst_len, sizeof(uint32_t));
2660 	if (res != TEE_SUCCESS)
2661 		return res;
2662 
2663 	res = tee_mmu_check_access_rights(sess->ctx,
2664 					  TEE_MEMORY_ACCESS_READ |
2665 					  TEE_MEMORY_ACCESS_WRITE |
2666 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2667 					  (tee_uaddr_t)dst_data, dlen);
2668 	if (res != TEE_SUCCESS)
2669 		return res;
2670 
2671 	if (dlen < src_len) {
2672 		res = TEE_ERROR_SHORT_BUFFER;
2673 		goto out;
2674 	}
2675 
2676 	if (!crypto_ops.authenc.update_payload)
2677 		return TEE_ERROR_NOT_IMPLEMENTED;
2678 	tmp_dlen = dlen;
2679 	res = crypto_ops.authenc.update_payload(cs->ctx, cs->algo, cs->mode,
2680 						src_data, src_len, dst_data,
2681 						&tmp_dlen);
2682 	dlen = tmp_dlen;
2683 
2684 out:
2685 	if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
2686 		TEE_Result res2 = tee_svc_copy_to_user(sess, dst_len, &dlen,
2687 						       sizeof(uint32_t));
2688 		if (res2 != TEE_SUCCESS)
2689 			res = res2;
2690 	}
2691 
2692 	return res;
2693 }
2694 
2695 TEE_Result tee_svc_authenc_enc_final(uint32_t state, const void *src_data,
2696 				     size_t src_len, void *dst_data,
2697 				     uint32_t *dst_len, void *tag,
2698 				     uint32_t *tag_len)
2699 {
2700 	TEE_Result res;
2701 	struct tee_cryp_state *cs;
2702 	struct tee_ta_session *sess;
2703 	uint32_t dlen;
2704 	uint32_t tlen;
2705 	size_t tmp_dlen;
2706 	size_t tmp_tlen;
2707 
2708 	res = tee_ta_get_current_session(&sess);
2709 	if (res != TEE_SUCCESS)
2710 		return res;
2711 
2712 	res = tee_svc_cryp_get_state(sess, state, &cs);
2713 	if (res != TEE_SUCCESS)
2714 		return res;
2715 
2716 	if (cs->mode != TEE_MODE_ENCRYPT)
2717 		return TEE_ERROR_BAD_PARAMETERS;
2718 
2719 	res = tee_mmu_check_access_rights(sess->ctx,
2720 					  TEE_MEMORY_ACCESS_READ |
2721 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2722 					  (tee_uaddr_t)src_data, src_len);
2723 	if (res != TEE_SUCCESS)
2724 		return res;
2725 
2726 	if (!dst_len) {
2727 		dlen = 0;
2728 	} else {
2729 		res = tee_svc_copy_from_user(sess, &dlen, dst_len,
2730 					     sizeof(uint32_t));
2731 		if (res != TEE_SUCCESS)
2732 			return res;
2733 
2734 		res = tee_mmu_check_access_rights(sess->ctx,
2735 						  TEE_MEMORY_ACCESS_READ |
2736 						  TEE_MEMORY_ACCESS_WRITE |
2737 						  TEE_MEMORY_ACCESS_ANY_OWNER,
2738 						  (tee_uaddr_t)dst_data, dlen);
2739 		if (res != TEE_SUCCESS)
2740 			return res;
2741 	}
2742 
2743 	if (dlen < src_len) {
2744 		res = TEE_ERROR_SHORT_BUFFER;
2745 		goto out;
2746 	}
2747 
2748 	res = tee_svc_copy_from_user(sess, &tlen, tag_len, sizeof(uint32_t));
2749 	if (res != TEE_SUCCESS)
2750 		return res;
2751 
2752 	res = tee_mmu_check_access_rights(sess->ctx,
2753 					  TEE_MEMORY_ACCESS_READ |
2754 					  TEE_MEMORY_ACCESS_WRITE |
2755 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2756 					  (tee_uaddr_t)tag, tlen);
2757 	if (res != TEE_SUCCESS)
2758 		return res;
2759 
2760 	if (!crypto_ops.authenc.enc_final)
2761 		return TEE_ERROR_NOT_IMPLEMENTED;
2762 	tmp_dlen = dlen;
2763 	tmp_tlen = tlen;
2764 	res = crypto_ops.authenc.enc_final(cs->ctx, cs->algo, src_data,
2765 					   src_len, dst_data, &tmp_dlen, tag,
2766 					   &tmp_tlen);
2767 	dlen = tmp_dlen;
2768 	tlen = tmp_tlen;
2769 
2770 out:
2771 	if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
2772 		TEE_Result res2;
2773 
2774 		if (dst_len != NULL) {
2775 			res2 = tee_svc_copy_to_user(sess, dst_len, &dlen,
2776 						    sizeof(uint32_t));
2777 			if (res2 != TEE_SUCCESS)
2778 				return res2;
2779 		}
2780 
2781 		res2 = tee_svc_copy_to_user(sess, tag_len, &tlen,
2782 					    sizeof(uint32_t));
2783 		if (res2 != TEE_SUCCESS)
2784 			return res2;
2785 	}
2786 
2787 	return res;
2788 }
2789 
2790 TEE_Result tee_svc_authenc_dec_final(uint32_t state, const void *src_data,
2791 				     size_t src_len, void *dst_data,
2792 				     uint32_t *dst_len, const void *tag,
2793 				     size_t tag_len)
2794 {
2795 	TEE_Result res;
2796 	struct tee_cryp_state *cs;
2797 	struct tee_ta_session *sess;
2798 	uint32_t dlen;
2799 	size_t tmp_dlen;
2800 
2801 	res = tee_ta_get_current_session(&sess);
2802 	if (res != TEE_SUCCESS)
2803 		return res;
2804 
2805 	res = tee_svc_cryp_get_state(sess, state, &cs);
2806 	if (res != TEE_SUCCESS)
2807 		return res;
2808 
2809 	if (cs->mode != TEE_MODE_DECRYPT)
2810 		return TEE_ERROR_BAD_PARAMETERS;
2811 
2812 	res = tee_mmu_check_access_rights(sess->ctx,
2813 					  TEE_MEMORY_ACCESS_READ |
2814 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2815 					  (tee_uaddr_t)src_data, src_len);
2816 	if (res != TEE_SUCCESS)
2817 		return res;
2818 
2819 	if (!dst_len) {
2820 		dlen = 0;
2821 	} else {
2822 		res = tee_svc_copy_from_user(sess, &dlen, dst_len,
2823 					     sizeof(uint32_t));
2824 		if (res != TEE_SUCCESS)
2825 			return res;
2826 
2827 		res = tee_mmu_check_access_rights(sess->ctx,
2828 						  TEE_MEMORY_ACCESS_READ |
2829 						  TEE_MEMORY_ACCESS_WRITE |
2830 						  TEE_MEMORY_ACCESS_ANY_OWNER,
2831 						  (tee_uaddr_t)dst_data, dlen);
2832 		if (res != TEE_SUCCESS)
2833 			return res;
2834 	}
2835 
2836 	if (dlen < src_len) {
2837 		res = TEE_ERROR_SHORT_BUFFER;
2838 		goto out;
2839 	}
2840 
2841 	res = tee_mmu_check_access_rights(sess->ctx,
2842 					  TEE_MEMORY_ACCESS_READ |
2843 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2844 					  (tee_uaddr_t)tag, tag_len);
2845 	if (res != TEE_SUCCESS)
2846 		return res;
2847 
2848 	if (!crypto_ops.authenc.dec_final)
2849 		return TEE_ERROR_NOT_IMPLEMENTED;
2850 	tmp_dlen = dlen;
2851 	res = crypto_ops.authenc.dec_final(cs->ctx, cs->algo, src_data,
2852 					   src_len, dst_data, &tmp_dlen, tag,
2853 					   tag_len);
2854 	dlen = tmp_dlen;
2855 
2856 out:
2857 	if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) &&
2858 	    dst_len != NULL) {
2859 		TEE_Result res2;
2860 
2861 		res2 = tee_svc_copy_to_user(sess, dst_len, &dlen,
2862 					    sizeof(uint32_t));
2863 		if (res2 != TEE_SUCCESS)
2864 			return res2;
2865 	}
2866 
2867 	return res;
2868 }
2869 
2870 static void tee_svc_asymm_pkcs1_get_salt_len(const TEE_Attribute *params,
2871 					     uint32_t num_params, int *salt_len)
2872 {
2873 	size_t n;
2874 
2875 	for (n = 0; n < num_params; n++) {
2876 		if (params[n].attributeID == TEE_ATTR_RSA_PSS_SALT_LENGTH) {
2877 			*salt_len = params[n].content.value.a;
2878 			return;
2879 		}
2880 	}
2881 	*salt_len = -1;
2882 }
2883 
2884 TEE_Result tee_svc_asymm_operate(uint32_t state,
2885 			const struct abi_user32_attribute *usr_params,
2886 			uint32_t num_params, const void *src_data,
2887 			size_t src_len, void *dst_data, uint32_t *dst_len)
2888 {
2889 	TEE_Result res;
2890 	struct tee_cryp_state *cs;
2891 	struct tee_ta_session *sess;
2892 	uint32_t dlen32;
2893 	size_t dlen;
2894 	struct tee_obj *o;
2895 	void *label = NULL;
2896 	size_t label_len = 0;
2897 	size_t n;
2898 	int salt_len;
2899 	TEE_Attribute *params = NULL;
2900 
2901 	res = tee_ta_get_current_session(&sess);
2902 	if (res != TEE_SUCCESS)
2903 		return res;
2904 
2905 	res = tee_svc_cryp_get_state(sess, state, &cs);
2906 	if (res != TEE_SUCCESS)
2907 		return res;
2908 
2909 	res = tee_mmu_check_access_rights(
2910 		sess->ctx,
2911 		TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER,
2912 		(tee_uaddr_t) src_data, src_len);
2913 	if (res != TEE_SUCCESS)
2914 		return res;
2915 
2916 	res = tee_svc_copy_from_user(sess, &dlen32, dst_len, sizeof(uint32_t));
2917 	if (res != TEE_SUCCESS)
2918 		return res;
2919 	dlen = dlen32;
2920 
2921 	res = tee_mmu_check_access_rights(
2922 		sess->ctx,
2923 		TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE |
2924 			TEE_MEMORY_ACCESS_ANY_OWNER,
2925 		(tee_uaddr_t) dst_data, dlen);
2926 	if (res != TEE_SUCCESS)
2927 		return res;
2928 
2929 	params = malloc(sizeof(TEE_Attribute) * num_params);
2930 	if (!params)
2931 		return TEE_ERROR_OUT_OF_MEMORY;
2932 	res = copy_in_attrs(sess->ctx, usr_params, num_params, params);
2933 	if (res != TEE_SUCCESS)
2934 		goto out;
2935 
2936 	res = tee_obj_get(sess->ctx, cs->key1, &o);
2937 	if (res != TEE_SUCCESS)
2938 		goto out;
2939 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
2940 		res = TEE_ERROR_GENERIC;
2941 		goto out;
2942 	}
2943 
2944 	switch (cs->algo) {
2945 	case TEE_ALG_RSA_NOPAD:
2946 		if (cs->mode == TEE_MODE_ENCRYPT) {
2947 			if (crypto_ops.acipher.rsanopad_encrypt)
2948 				res = crypto_ops.acipher.rsanopad_encrypt(
2949 					o->data, src_data, src_len,
2950 					dst_data, &dlen);
2951 			else
2952 				res = TEE_ERROR_NOT_IMPLEMENTED;
2953 		} else if (cs->mode == TEE_MODE_DECRYPT) {
2954 			if (crypto_ops.acipher.rsanopad_decrypt)
2955 				res = crypto_ops.acipher.rsanopad_decrypt(
2956 					o->data, src_data, src_len, dst_data,
2957 					&dlen);
2958 			else
2959 				res = TEE_ERROR_NOT_IMPLEMENTED;
2960 		} else {
2961 			/*
2962 			 * We will panic because "the mode is not compatible
2963 			 * with the function"
2964 			 */
2965 			res = TEE_ERROR_GENERIC;
2966 		}
2967 		break;
2968 
2969 	case TEE_ALG_RSAES_PKCS1_V1_5:
2970 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
2971 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
2972 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
2973 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
2974 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
2975 		for (n = 0; n < num_params; n++) {
2976 			if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) {
2977 				label = params[n].content.ref.buffer;
2978 				label_len = params[n].content.ref.length;
2979 				break;
2980 			}
2981 		}
2982 
2983 		if (cs->mode == TEE_MODE_ENCRYPT) {
2984 			if (crypto_ops.acipher.rsaes_encrypt)
2985 				res = crypto_ops.acipher.rsaes_encrypt(
2986 					cs->algo, o->data, label, label_len,
2987 					src_data, src_len, dst_data, &dlen);
2988 			else
2989 				res = TEE_ERROR_NOT_IMPLEMENTED;
2990 		} else if (cs->mode == TEE_MODE_DECRYPT) {
2991 			if (crypto_ops.acipher.rsaes_decrypt)
2992 				res = crypto_ops.acipher.rsaes_decrypt(
2993 					cs->algo, o->data,
2994 					label, label_len,
2995 					src_data, src_len, dst_data, &dlen);
2996 			else
2997 				res = TEE_ERROR_NOT_IMPLEMENTED;
2998 		} else {
2999 			res = TEE_ERROR_BAD_PARAMETERS;
3000 		}
3001 		break;
3002 
3003 	case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
3004 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
3005 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
3006 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
3007 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
3008 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
3009 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
3010 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
3011 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
3012 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
3013 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
3014 		if (cs->mode != TEE_MODE_SIGN) {
3015 			res = TEE_ERROR_BAD_PARAMETERS;
3016 			break;
3017 		}
3018 		tee_svc_asymm_pkcs1_get_salt_len(params, num_params, &salt_len);
3019 
3020 		if (!crypto_ops.acipher.rsassa_sign) {
3021 			res = TEE_ERROR_NOT_IMPLEMENTED;
3022 			break;
3023 		}
3024 		res = crypto_ops.acipher.rsassa_sign(cs->algo, o->data,
3025 						     salt_len, src_data,
3026 						     src_len, dst_data, &dlen);
3027 		break;
3028 
3029 	case TEE_ALG_DSA_SHA1:
3030 		if (!crypto_ops.acipher.dsa_sign) {
3031 			res = TEE_ERROR_NOT_IMPLEMENTED;
3032 			break;
3033 		}
3034 		res = crypto_ops.acipher.dsa_sign(cs->algo, o->data, src_data,
3035 						  src_len, dst_data, &dlen);
3036 		break;
3037 
3038 	default:
3039 		res = TEE_ERROR_BAD_PARAMETERS;
3040 		break;
3041 	}
3042 
3043 out:
3044 	free(params);
3045 
3046 	if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
3047 		TEE_Result res2;
3048 
3049 		dlen32 = dlen;
3050 		res2 = tee_svc_copy_to_user(sess, dst_len, &dlen,
3051 					    sizeof(uint32_t));
3052 		if (res2 != TEE_SUCCESS)
3053 			return res2;
3054 	}
3055 
3056 	return res;
3057 }
3058 
3059 TEE_Result tee_svc_asymm_verify(uint32_t state,
3060 			const struct abi_user32_attribute *usr_params,
3061 			uint32_t num_params, const void *data,
3062 			size_t data_len, const void *sig, size_t sig_len)
3063 {
3064 	TEE_Result res;
3065 	struct tee_cryp_state *cs;
3066 	struct tee_ta_session *sess;
3067 	struct tee_obj *o;
3068 	size_t hash_size;
3069 	int salt_len;
3070 	TEE_Attribute *params = NULL;
3071 
3072 	res = tee_ta_get_current_session(&sess);
3073 	if (res != TEE_SUCCESS)
3074 		return res;
3075 
3076 	res = tee_svc_cryp_get_state(sess, state, &cs);
3077 	if (res != TEE_SUCCESS)
3078 		return res;
3079 
3080 	if (cs->mode != TEE_MODE_VERIFY)
3081 		return TEE_ERROR_BAD_PARAMETERS;
3082 
3083 	res = tee_mmu_check_access_rights(sess->ctx,
3084 					  TEE_MEMORY_ACCESS_READ |
3085 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3086 					  (tee_uaddr_t)data, data_len);
3087 	if (res != TEE_SUCCESS)
3088 		return res;
3089 
3090 	res = tee_mmu_check_access_rights(sess->ctx,
3091 					  TEE_MEMORY_ACCESS_READ |
3092 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3093 					  (tee_uaddr_t)sig, sig_len);
3094 	if (res != TEE_SUCCESS)
3095 		return res;
3096 
3097 	params = malloc(sizeof(TEE_Attribute) * num_params);
3098 	if (!params)
3099 		return TEE_ERROR_OUT_OF_MEMORY;
3100 	res = copy_in_attrs(sess->ctx, usr_params, num_params, params);
3101 	if (res != TEE_SUCCESS)
3102 		goto out;
3103 
3104 	res = tee_obj_get(sess->ctx, cs->key1, &o);
3105 	if (res != TEE_SUCCESS)
3106 		goto out;
3107 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
3108 		res = TEE_ERROR_BAD_PARAMETERS;
3109 		goto out;
3110 	}
3111 
3112 	res = tee_hash_get_digest_size(TEE_DIGEST_HASH_TO_ALGO(cs->algo),
3113 				       &hash_size);
3114 	if (res != TEE_SUCCESS)
3115 		goto out;
3116 
3117 	if (data_len != hash_size) {
3118 		res = TEE_ERROR_BAD_PARAMETERS;
3119 		goto out;
3120 	}
3121 
3122 	switch (TEE_ALG_GET_MAIN_ALG(cs->algo)) {
3123 	case TEE_MAIN_ALGO_RSA:
3124 		tee_svc_asymm_pkcs1_get_salt_len(params, num_params, &salt_len);
3125 		if (!crypto_ops.acipher.rsassa_verify) {
3126 			res = TEE_ERROR_NOT_IMPLEMENTED;
3127 			break;
3128 		}
3129 		res = crypto_ops.acipher.rsassa_verify(cs->algo, o->data,
3130 						       salt_len, data,
3131 						       data_len, sig, sig_len);
3132 		break;
3133 
3134 	case TEE_MAIN_ALGO_DSA:
3135 		if (!crypto_ops.acipher.dsa_verify) {
3136 			res = TEE_ERROR_NOT_IMPLEMENTED;
3137 			break;
3138 		}
3139 		res = crypto_ops.acipher.dsa_verify(cs->algo, o->data, data,
3140 						    data_len, sig, sig_len);
3141 		break;
3142 
3143 	default:
3144 		res = TEE_ERROR_NOT_SUPPORTED;
3145 	}
3146 
3147 out:
3148 	free(params);
3149 	return res;
3150 }
3151