xref: /optee_os/core/tee/tee_svc_cryp.c (revision 31908aeac446be4859fe9dc98dc4e1e0c13b528c)
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 	return TEE_SUCCESS;
974 }
975 
976 static TEE_Result tee_svc_cryp_obj_store_attr_raw(uint16_t conv_func,
977 						  const TEE_Attribute *attr,
978 						  void *data, size_t data_size)
979 {
980 	TEE_Result res;
981 	struct tee_cryp_obj_secret *obj;
982 	struct bignum *bn;
983 
984 	if (!attr)
985 		return TEE_ERROR_BAD_STATE;
986 
987 	if (conv_func != TEE_TYPE_CONV_FUNC_VALUE && !attr->content.ref.buffer)
988 		return TEE_ERROR_BAD_PARAMETERS;
989 
990 	switch (conv_func) {
991 	case TEE_TYPE_CONV_FUNC_NONE:
992 		/* No conversion data size has to match exactly */
993 		if (attr->content.ref.length != data_size)
994 			return TEE_ERROR_BAD_PARAMETERS;
995 		memcpy(data, attr->content.ref.buffer, data_size);
996 		return TEE_SUCCESS;
997 
998 	case TEE_TYPE_CONV_FUNC_SECRET:
999 		if (!TEE_ALIGNMENT_IS_OK(data, struct tee_cryp_obj_secret))
1000 			return TEE_ERROR_BAD_STATE;
1001 		obj = (struct tee_cryp_obj_secret *)(void *)data;
1002 
1003 		/* Data size has to fit in allocated buffer */
1004 		if (attr->content.ref.length >
1005 		    (data_size - sizeof(struct tee_cryp_obj_secret)))
1006 			return TEE_ERROR_BAD_PARAMETERS;
1007 
1008 		memcpy(obj + 1, attr->content.ref.buffer,
1009 		       attr->content.ref.length);
1010 		obj->key_size = attr->content.ref.length;
1011 		return TEE_SUCCESS;
1012 
1013 	case TEE_TYPE_CONV_FUNC_BIGNUM:
1014 		/*
1015 		 * Read the array of bytes (stored in attr->content.ref.buffer)
1016 		 * and convert it to a bignum (pointed to by data)
1017 		 */
1018 		bn = *(struct bignum **)data;
1019 		if (!crypto_ops.bignum.bin2bn)
1020 			return TEE_ERROR_NOT_IMPLEMENTED;
1021 		res = crypto_ops.bignum.bin2bn(attr->content.ref.buffer,
1022 					       attr->content.ref.length,
1023 					       bn);
1024 		return res;
1025 
1026 	case TEE_TYPE_CONV_FUNC_VALUE:
1027 		/*
1028 		 * a value attribute consists of two uint32 but have not
1029 		 * seen anything that actaully would need that so this fills
1030 		 * the data from the first value and discards the second value
1031 		 */
1032 		*(uint32_t *)data = attr->content.value.a;
1033 
1034 		return TEE_SUCCESS;
1035 
1036 	default:
1037 		return TEE_ERROR_BAD_STATE;
1038 	}
1039 }
1040 
1041 
1042 static TEE_Result copy_in_attrs(struct tee_ta_ctx *ctx,
1043 			const struct abi_user32_attribute *usr_attrs,
1044 			uint32_t attr_count, TEE_Attribute *attrs)
1045 {
1046 	TEE_Result res;
1047 	uint32_t n;
1048 
1049 	res = tee_mmu_check_access_rights(ctx,
1050 			TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER,
1051 			(tee_uaddr_t)usr_attrs,
1052 			attr_count * sizeof(struct abi_user32_attribute));
1053 	if (res != TEE_SUCCESS)
1054 		return res;
1055 
1056 	abi_user_attr32_to_attr(attrs, usr_attrs, attr_count);
1057 
1058 	for (n = 0; n < attr_count; n++) {
1059 		if (attrs[n].attributeID & TEE_ATTR_BIT_VALUE)
1060 			continue;
1061 		res = tee_mmu_check_access_rights(ctx, TEE_MEMORY_ACCESS_READ |
1062 						  TEE_MEMORY_ACCESS_ANY_OWNER,
1063 						  (tee_uaddr_t)
1064 						  attrs[n].content.ref.buffer,
1065 						  attrs[n].content.ref.length);
1066 		if (res != TEE_SUCCESS)
1067 			return res;
1068 	}
1069 
1070 	return TEE_SUCCESS;
1071 }
1072 
1073 enum attr_usage {
1074 	ATTR_USAGE_POPULATE,
1075 	ATTR_USAGE_GENERATE_KEY
1076 };
1077 
1078 static TEE_Result tee_svc_cryp_check_attr(enum attr_usage usage,
1079 					  const struct tee_cryp_obj_type_props
1080 						*type_props,
1081 					  const TEE_Attribute *attrs,
1082 					  uint32_t attr_count)
1083 {
1084 	uint32_t required_flag;
1085 	uint32_t opt_flag;
1086 	bool all_opt_needed;
1087 	uint32_t req_attrs = 0;
1088 	uint32_t opt_grp_attrs = 0;
1089 	uint32_t attrs_found = 0;
1090 	size_t n;
1091 
1092 	if (usage == ATTR_USAGE_POPULATE) {
1093 		required_flag = TEE_TYPE_ATTR_REQUIRED;
1094 		opt_flag = TEE_TYPE_ATTR_OPTIONAL_GROUP;
1095 		all_opt_needed = true;
1096 	} else {
1097 		required_flag = TEE_TYPE_ATTR_GEN_KEY_REQ;
1098 		opt_flag = TEE_TYPE_ATTR_GEN_KEY_OPT;
1099 		all_opt_needed = false;
1100 	}
1101 
1102 	/*
1103 	 * First find out which attributes are required and which belong to
1104 	 * the optional group
1105 	 */
1106 	for (n = 0; n < type_props->num_type_attrs; n++) {
1107 		uint32_t bit = 1 << n;
1108 		uint32_t flags = type_props->type_attrs[n].flags;
1109 
1110 		if (flags & required_flag)
1111 			req_attrs |= bit;
1112 		else if (flags & opt_flag)
1113 			opt_grp_attrs |= bit;
1114 	}
1115 
1116 	/*
1117 	 * Verify that all required attributes are in place and
1118 	 * that the same attribute isn't repeated.
1119 	 */
1120 	for (n = 0; n < attr_count; n++) {
1121 		int idx =
1122 		    tee_svc_cryp_obj_find_type_attr_idx(attrs[n].attributeID,
1123 							type_props);
1124 		if (idx >= 0) {
1125 			uint32_t bit = 1 << idx;
1126 
1127 			if ((attrs_found & bit) != 0)
1128 				return TEE_ERROR_ITEM_NOT_FOUND;
1129 
1130 			attrs_found |= bit;
1131 		}
1132 	}
1133 	/* Required attribute missing */
1134 	if ((attrs_found & req_attrs) != req_attrs)
1135 		return TEE_ERROR_ITEM_NOT_FOUND;
1136 
1137 	/*
1138 	 * If the flag says that "if one of the optional attributes are included
1139 	 * all of them has to be included" this must be checked.
1140 	 */
1141 	if (all_opt_needed && (attrs_found & opt_grp_attrs) != 0 &&
1142 	    (attrs_found & opt_grp_attrs) != opt_grp_attrs)
1143 		return TEE_ERROR_ITEM_NOT_FOUND;
1144 
1145 	return TEE_SUCCESS;
1146 }
1147 
1148 static TEE_Result tee_svc_cryp_obj_populate_type(
1149 		struct tee_obj *o,
1150 		const struct tee_cryp_obj_type_props *type_props,
1151 		const TEE_Attribute *attrs,
1152 		uint32_t attr_count)
1153 {
1154 	TEE_Result res;
1155 	uint32_t have_attrs = 0;
1156 	size_t obj_size = 0;
1157 	size_t n;
1158 
1159 	for (n = 0; n < attr_count; n++) {
1160 		size_t raw_size;
1161 		void *raw_data;
1162 		int idx =
1163 		    tee_svc_cryp_obj_find_type_attr_idx(attrs[n].attributeID,
1164 							type_props);
1165 		if (idx < 0)
1166 			continue;
1167 
1168 		have_attrs |= 1 << idx;
1169 
1170 		res = tee_svc_cryp_obj_get_raw_data(o, type_props, idx,
1171 						    &raw_data, &raw_size);
1172 		if (res != TEE_SUCCESS)
1173 			return res;
1174 
1175 		res =
1176 		    tee_svc_cryp_obj_store_attr_raw(
1177 			    type_props->type_attrs[idx].conv_func,
1178 			    attrs + n, raw_data, raw_size);
1179 		if (res != TEE_SUCCESS)
1180 			return res;
1181 
1182 		/*
1183 		 * First attr_idx signifies the attribute that gives the size
1184 		 * of the object
1185 		 */
1186 		if (type_props->type_attrs[idx].flags &
1187 		    TEE_TYPE_ATTR_SIZE_INDICATOR) {
1188 			obj_size += attrs[n].content.ref.length * 8;
1189 		}
1190 	}
1191 
1192 	/*
1193 	 * We have to do it like this because the parity bits aren't counted
1194 	 * when telling the size of the key in bits.
1195 	 */
1196 	if (o->info.objectType == TEE_TYPE_DES ||
1197 	    o->info.objectType == TEE_TYPE_DES3)
1198 		obj_size -= obj_size / 8; /* Exclude parity in size of key */
1199 
1200 	o->have_attrs = have_attrs;
1201 	o->info.keySize = obj_size;
1202 	return TEE_SUCCESS;
1203 }
1204 
1205 TEE_Result tee_svc_cryp_obj_populate(uint32_t obj,
1206 		struct abi_user32_attribute *usr_attrs, uint32_t attr_count)
1207 {
1208 	TEE_Result res;
1209 	struct tee_ta_session *sess;
1210 	struct tee_obj *o;
1211 	const struct tee_cryp_obj_type_props *type_props;
1212 	TEE_Attribute *attrs = NULL;
1213 
1214 	res = tee_ta_get_current_session(&sess);
1215 	if (res != TEE_SUCCESS)
1216 		return res;
1217 
1218 	res = tee_obj_get(sess->ctx, obj, &o);
1219 	if (res != TEE_SUCCESS)
1220 		return res;
1221 
1222 	/* Must be a transient object */
1223 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
1224 		return TEE_ERROR_BAD_PARAMETERS;
1225 
1226 	/* Must not be initialized already */
1227 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
1228 		return TEE_ERROR_BAD_PARAMETERS;
1229 
1230 	type_props = tee_svc_find_type_props(o->info.objectType);
1231 	if (!type_props)
1232 		return TEE_ERROR_NOT_IMPLEMENTED;
1233 
1234 	attrs = malloc(sizeof(TEE_Attribute) * attr_count);
1235 	if (!attrs)
1236 		return TEE_ERROR_OUT_OF_MEMORY;
1237 	res = copy_in_attrs(sess->ctx, usr_attrs, attr_count, attrs);
1238 	if (res != TEE_SUCCESS)
1239 		goto out;
1240 
1241 	res = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props,
1242 				      attrs, attr_count);
1243 	if (res != TEE_SUCCESS)
1244 		goto out;
1245 
1246 	res = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count);
1247 	if (res == TEE_SUCCESS)
1248 		o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
1249 
1250 out:
1251 	free(attrs);
1252 	return res;
1253 }
1254 
1255 TEE_Result tee_svc_cryp_obj_copy(uint32_t dst, uint32_t src)
1256 {
1257 	TEE_Result res;
1258 	struct tee_ta_session *sess;
1259 	struct tee_obj *dst_o;
1260 	struct tee_obj *src_o;
1261 
1262 	res = tee_ta_get_current_session(&sess);
1263 	if (res != TEE_SUCCESS)
1264 		return res;
1265 
1266 	res = tee_obj_get(sess->ctx, dst, &dst_o);
1267 	if (res != TEE_SUCCESS)
1268 		return res;
1269 
1270 	res = tee_obj_get(sess->ctx, src, &src_o);
1271 	if (res != TEE_SUCCESS)
1272 		return res;
1273 
1274 	if ((src_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
1275 		return TEE_ERROR_BAD_PARAMETERS;
1276 	if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
1277 		return TEE_ERROR_BAD_PARAMETERS;
1278 	if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
1279 		return TEE_ERROR_BAD_PARAMETERS;
1280 
1281 	if (dst_o->info.objectType == src_o->info.objectType) {
1282 		/* Copy whole data */
1283 
1284 		if (dst_o->data_size != src_o->data_size)
1285 			return TEE_ERROR_BAD_STATE;
1286 		if (dst_o->cleanup != src_o->cleanup)
1287 			return TEE_ERROR_BAD_STATE;
1288 
1289 		dst_o->have_attrs = src_o->have_attrs;
1290 
1291 		switch (src_o->info.objectType) {
1292 		case TEE_TYPE_RSA_PUBLIC_KEY:
1293 			copy_rsa_public_key(dst_o->data, src_o->data);
1294 			break;
1295 		case TEE_TYPE_RSA_KEYPAIR:
1296 			copy_rsa_keypair(dst_o->data, src_o->data);
1297 			break;
1298 		case TEE_TYPE_DSA_PUBLIC_KEY:
1299 			copy_dsa_public_key(dst_o->data, src_o->data);
1300 			break;
1301 		case TEE_TYPE_DSA_KEYPAIR:
1302 			copy_dsa_keypair(dst_o->data, src_o->data);
1303 			break;
1304 		case TEE_TYPE_DH_KEYPAIR:
1305 			copy_dh_keypair(dst_o->data, src_o->data);
1306 			break;
1307 		default:
1308 			/* Generic case */
1309 			memcpy(dst_o->data, src_o->data, src_o->data_size);
1310 		}
1311 	} else if (dst_o->info.objectType == TEE_TYPE_RSA_PUBLIC_KEY &&
1312 		   src_o->info.objectType == TEE_TYPE_RSA_KEYPAIR) {
1313 		/* Extract public key from RSA key pair */
1314 		size_t n;
1315 
1316 		extract_rsa_public_key(dst_o->data, src_o->data);
1317 		dst_o->have_attrs = 0;
1318 		for (n = 0; n < TEE_ARRAY_SIZE(tee_cryp_obj_rsa_pub_key_attrs);
1319 		     n++)
1320 			dst_o->have_attrs |= 1 << n;
1321 
1322 	} else if (dst_o->info.objectType == TEE_TYPE_DSA_PUBLIC_KEY &&
1323 		   src_o->info.objectType == TEE_TYPE_DSA_KEYPAIR) {
1324 		/* Extract public key from DSA key pair */
1325 		size_t n;
1326 
1327 		extract_dsa_public_key(dst_o->data, src_o->data);
1328 		dst_o->have_attrs = 0;
1329 		for (n = 0; n < TEE_ARRAY_SIZE(tee_cryp_obj_dsa_pub_key_attrs);
1330 		     n++)
1331 			dst_o->have_attrs |= 1 << n;
1332 
1333 	} else {
1334 		return TEE_ERROR_BAD_PARAMETERS;
1335 	}
1336 
1337 	dst_o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
1338 	dst_o->info.keySize = src_o->info.keySize;
1339 	dst_o->info.objectUsage = src_o->info.objectUsage;
1340 	return TEE_SUCCESS;
1341 }
1342 
1343 static TEE_Result tee_svc_obj_generate_key_rsa(
1344 	struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
1345 	uint32_t key_size,
1346 	const TEE_Attribute *params, uint32_t param_count)
1347 {
1348 	TEE_Result res;
1349 	struct rsa_keypair *key = o->data;
1350 	uint32_t e = TEE_U32_TO_BIG_ENDIAN(65537);
1351 
1352 	TEE_ASSERT(sizeof(struct rsa_keypair) == o->data_size);
1353 	if (!crypto_ops.acipher.gen_rsa_key || !crypto_ops.bignum.bin2bn)
1354 		return TEE_ERROR_NOT_IMPLEMENTED;
1355 
1356 	/* Copy the present attributes into the obj before starting */
1357 	res = tee_svc_cryp_obj_populate_type(o, type_props, params,
1358 					     param_count);
1359 	if (res != TEE_SUCCESS)
1360 		return res;
1361 	if (!GET_ATTRIBUTE(o, type_props, TEE_ATTR_RSA_PUBLIC_EXPONENT))
1362 		crypto_ops.bignum.bin2bn((const uint8_t *)&e, sizeof(e),
1363 					 key->e);
1364 	res = crypto_ops.acipher.gen_rsa_key(o->data, key_size);
1365 	if (res != TEE_SUCCESS)
1366 		return res;
1367 
1368 	/* Set bits for all known attributes for this object type */
1369 	o->have_attrs = (1 << type_props->num_type_attrs) - 1;
1370 
1371 	return TEE_SUCCESS;
1372 }
1373 
1374 static TEE_Result tee_svc_obj_generate_key_dsa(
1375 	struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
1376 	uint32_t key_size)
1377 {
1378 	TEE_Result res;
1379 
1380 	TEE_ASSERT(sizeof(struct dsa_keypair) == o->data_size);
1381 	if (!crypto_ops.acipher.gen_dsa_key)
1382 		return TEE_ERROR_NOT_IMPLEMENTED;
1383 	res = crypto_ops.acipher.gen_dsa_key(o->data, key_size);
1384 	if (res != TEE_SUCCESS)
1385 		return res;
1386 
1387 	/* Set bits for all known attributes for this object type */
1388 	o->have_attrs = (1 << type_props->num_type_attrs) - 1;
1389 
1390 	return TEE_SUCCESS;
1391 }
1392 
1393 static TEE_Result tee_svc_obj_generate_key_dh(
1394 	struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
1395 	uint32_t key_size __unused,
1396 	const TEE_Attribute *params, uint32_t param_count)
1397 {
1398 	TEE_Result res;
1399 	struct dh_keypair *tee_dh_key;
1400 	struct bignum *dh_q = NULL;
1401 	uint32_t dh_xbits = 0;
1402 
1403 	TEE_ASSERT(sizeof(struct dh_keypair) == o->data_size);
1404 
1405 	/* Copy the present attributes into the obj before starting */
1406 	res = tee_svc_cryp_obj_populate_type(o, type_props, params,
1407 					     param_count);
1408 	if (res != TEE_SUCCESS)
1409 		return res;
1410 
1411 	tee_dh_key = (struct dh_keypair *)o->data;
1412 
1413 	if (GET_ATTRIBUTE(o, type_props, TEE_ATTR_DH_SUBPRIME))
1414 		dh_q = tee_dh_key->q;
1415 	if (GET_ATTRIBUTE(o, type_props, TEE_ATTR_DH_X_BITS))
1416 		dh_xbits = tee_dh_key->xbits;
1417 	if (!crypto_ops.acipher.gen_dh_key)
1418 		return TEE_ERROR_NOT_IMPLEMENTED;
1419 	res = crypto_ops.acipher.gen_dh_key(tee_dh_key, dh_q, dh_xbits);
1420 	if (res != TEE_SUCCESS)
1421 		return res;
1422 
1423 	/* Set bits for the generated public and private key */
1424 	SET_ATTRIBUTE(o, type_props, TEE_ATTR_DH_PUBLIC_VALUE);
1425 	SET_ATTRIBUTE(o, type_props, TEE_ATTR_DH_PRIVATE_VALUE);
1426 	SET_ATTRIBUTE(o, type_props, TEE_ATTR_DH_X_BITS);
1427 	return TEE_SUCCESS;
1428 }
1429 
1430 TEE_Result tee_svc_obj_generate_key(uint32_t obj, uint32_t key_size,
1431 			const struct abi_user32_attribute *usr_params,
1432 			uint32_t param_count)
1433 {
1434 	TEE_Result res;
1435 	struct tee_ta_session *sess;
1436 	const struct tee_cryp_obj_type_props *type_props;
1437 	struct tee_obj *o;
1438 	struct tee_cryp_obj_secret *key;
1439 	size_t byte_size;
1440 	TEE_Attribute *params = NULL;
1441 
1442 	res = tee_ta_get_current_session(&sess);
1443 	if (res != TEE_SUCCESS)
1444 		return res;
1445 
1446 	res = tee_obj_get(sess->ctx, obj, &o);
1447 	if (res != TEE_SUCCESS)
1448 		return res;
1449 
1450 	/* Must be a transient object */
1451 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
1452 		return TEE_ERROR_BAD_STATE;
1453 
1454 	/* Must not be initialized already */
1455 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
1456 		return TEE_ERROR_BAD_STATE;
1457 
1458 	/* Find description of object */
1459 	type_props = tee_svc_find_type_props(o->info.objectType);
1460 	if (!type_props)
1461 		return TEE_ERROR_NOT_SUPPORTED;
1462 
1463 	/* Check that maxKeySize follows restrictions */
1464 	if (key_size % type_props->quanta != 0)
1465 		return TEE_ERROR_NOT_SUPPORTED;
1466 	if (key_size < type_props->min_size)
1467 		return TEE_ERROR_NOT_SUPPORTED;
1468 	if (key_size > type_props->max_size)
1469 		return TEE_ERROR_NOT_SUPPORTED;
1470 
1471 	params = malloc(sizeof(TEE_Attribute) * param_count);
1472 	if (!params)
1473 		return TEE_ERROR_OUT_OF_MEMORY;
1474 	res = copy_in_attrs(sess->ctx, usr_params, param_count, params);
1475 	if (res != TEE_SUCCESS)
1476 		goto out;
1477 
1478 	res = tee_svc_cryp_check_attr(ATTR_USAGE_GENERATE_KEY, type_props,
1479 				      params, param_count);
1480 	if (res != TEE_SUCCESS)
1481 		goto out;
1482 
1483 	switch (o->info.objectType) {
1484 	case TEE_TYPE_AES:
1485 	case TEE_TYPE_DES:
1486 	case TEE_TYPE_DES3:
1487 	case TEE_TYPE_HMAC_MD5:
1488 	case TEE_TYPE_HMAC_SHA1:
1489 	case TEE_TYPE_HMAC_SHA224:
1490 	case TEE_TYPE_HMAC_SHA256:
1491 	case TEE_TYPE_HMAC_SHA384:
1492 	case TEE_TYPE_HMAC_SHA512:
1493 	case TEE_TYPE_GENERIC_SECRET:
1494 		byte_size = key_size / 8;
1495 
1496 		/*
1497 		 * We have to do it like this because the parity bits aren't
1498 		 * counted when telling the size of the key in bits.
1499 		 */
1500 		if (o->info.objectType == TEE_TYPE_DES ||
1501 		    o->info.objectType == TEE_TYPE_DES3) {
1502 			byte_size = (key_size + key_size / 7) / 8;
1503 		}
1504 
1505 		key = (struct tee_cryp_obj_secret *)o->data;
1506 		if (byte_size > (o->data_size - sizeof(*key))) {
1507 			res = TEE_ERROR_EXCESS_DATA;
1508 			goto out;
1509 		}
1510 
1511 		res = crypto_ops.prng.read((void *)(key + 1), byte_size);
1512 		if (res != TEE_SUCCESS)
1513 			goto out;
1514 
1515 		key->key_size = byte_size;
1516 
1517 		/* Set bits for all known attributes for this object type */
1518 		o->have_attrs = (1 << type_props->num_type_attrs) - 1;
1519 
1520 		break;
1521 
1522 	case TEE_TYPE_RSA_KEYPAIR:
1523 		res = tee_svc_obj_generate_key_rsa(o, type_props, key_size,
1524 						   params, param_count);
1525 		if (res != TEE_SUCCESS)
1526 			goto out;
1527 		break;
1528 
1529 	case TEE_TYPE_DSA_KEYPAIR:
1530 		res = tee_svc_obj_generate_key_dsa(o, type_props, key_size);
1531 		if (res != TEE_SUCCESS)
1532 			goto out;
1533 		break;
1534 
1535 	case TEE_TYPE_DH_KEYPAIR:
1536 		res = tee_svc_obj_generate_key_dh(o, type_props, key_size,
1537 						  params, param_count);
1538 		if (res != TEE_SUCCESS)
1539 			goto out;
1540 		break;
1541 
1542 	default:
1543 		res = TEE_ERROR_BAD_FORMAT;
1544 	}
1545 
1546 out:
1547 	free(params);
1548 	if (res == TEE_SUCCESS) {
1549 		o->info.keySize = key_size;
1550 		o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
1551 	}
1552 	return res;
1553 }
1554 
1555 static TEE_Result tee_svc_cryp_get_state(struct tee_ta_session *sess,
1556 					 uint32_t state_id,
1557 					 struct tee_cryp_state **state)
1558 {
1559 	struct tee_cryp_state *s;
1560 
1561 	TAILQ_FOREACH(s, &sess->ctx->cryp_states, link) {
1562 		if (state_id == (vaddr_t)s) {
1563 			*state = s;
1564 			return TEE_SUCCESS;
1565 		}
1566 	}
1567 	return TEE_ERROR_BAD_PARAMETERS;
1568 }
1569 
1570 static void cryp_state_free(struct tee_ta_ctx *ctx, struct tee_cryp_state *cs)
1571 {
1572 	struct tee_obj *o;
1573 
1574 	if (tee_obj_get(ctx, cs->key1, &o) == TEE_SUCCESS)
1575 		tee_obj_close(ctx, o);
1576 	if (tee_obj_get(ctx, cs->key2, &o) == TEE_SUCCESS)
1577 		tee_obj_close(ctx, o);
1578 
1579 	TAILQ_REMOVE(&ctx->cryp_states, cs, link);
1580 	if (cs->ctx_finalize != NULL)
1581 		cs->ctx_finalize(cs->ctx, cs->algo);
1582 	free(cs->ctx);
1583 	free(cs);
1584 }
1585 
1586 static TEE_Result tee_svc_cryp_check_key_type(const struct tee_obj *o,
1587 					      uint32_t algo,
1588 					      TEE_OperationMode mode)
1589 {
1590 	uint32_t req_key_type;
1591 
1592 	switch (TEE_ALG_GET_MAIN_ALG(algo)) {
1593 	case TEE_MAIN_ALGO_MD5:
1594 		req_key_type = TEE_TYPE_HMAC_MD5;
1595 		break;
1596 	case TEE_MAIN_ALGO_SHA1:
1597 		req_key_type = TEE_TYPE_HMAC_SHA1;
1598 		break;
1599 	case TEE_MAIN_ALGO_SHA224:
1600 		req_key_type = TEE_TYPE_HMAC_SHA224;
1601 		break;
1602 	case TEE_MAIN_ALGO_SHA256:
1603 		req_key_type = TEE_TYPE_HMAC_SHA256;
1604 		break;
1605 	case TEE_MAIN_ALGO_SHA384:
1606 		req_key_type = TEE_TYPE_HMAC_SHA384;
1607 		break;
1608 	case TEE_MAIN_ALGO_SHA512:
1609 		req_key_type = TEE_TYPE_HMAC_SHA512;
1610 		break;
1611 	case TEE_MAIN_ALGO_AES:
1612 		req_key_type = TEE_TYPE_AES;
1613 		break;
1614 	case TEE_MAIN_ALGO_DES:
1615 		req_key_type = TEE_TYPE_DES;
1616 		break;
1617 	case TEE_MAIN_ALGO_DES3:
1618 		req_key_type = TEE_TYPE_DES3;
1619 		break;
1620 	case TEE_MAIN_ALGO_RSA:
1621 		if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY)
1622 			req_key_type = TEE_TYPE_RSA_PUBLIC_KEY;
1623 		else
1624 			req_key_type = TEE_TYPE_RSA_KEYPAIR;
1625 		break;
1626 	case TEE_MAIN_ALGO_DSA:
1627 		if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY)
1628 			req_key_type = TEE_TYPE_DSA_PUBLIC_KEY;
1629 		else
1630 			req_key_type = TEE_TYPE_DSA_KEYPAIR;
1631 		break;
1632 	case TEE_MAIN_ALGO_DH:
1633 		req_key_type = TEE_TYPE_DH_KEYPAIR;
1634 		break;
1635 #if defined(CFG_CRYPTO_HKDF)
1636 	case TEE_MAIN_ALGO_HKDF:
1637 		req_key_type = TEE_TYPE_HKDF_IKM;
1638 		break;
1639 #endif
1640 #if defined(CFG_CRYPTO_CONCAT_KDF)
1641 	case TEE_MAIN_ALGO_CONCAT_KDF:
1642 		req_key_type = TEE_TYPE_CONCAT_KDF_Z;
1643 		break;
1644 #endif
1645 #if defined(CFG_CRYPTO_PBKDF2)
1646 	case TEE_MAIN_ALGO_PBKDF2:
1647 		req_key_type = TEE_TYPE_PBKDF2_PASSWORD;
1648 		break;
1649 #endif
1650 	default:
1651 		return TEE_ERROR_BAD_PARAMETERS;
1652 	}
1653 
1654 	if (req_key_type != o->info.objectType)
1655 		return TEE_ERROR_BAD_PARAMETERS;
1656 	return TEE_SUCCESS;
1657 }
1658 
1659 TEE_Result tee_svc_cryp_state_alloc(uint32_t algo, uint32_t mode,
1660 				    uint32_t key1, uint32_t key2,
1661 				    uint32_t *state)
1662 {
1663 	TEE_Result res;
1664 	struct tee_cryp_state *cs;
1665 	struct tee_ta_session *sess;
1666 	struct tee_obj *o1 = NULL;
1667 	struct tee_obj *o2 = NULL;
1668 
1669 	res = tee_ta_get_current_session(&sess);
1670 	if (res != TEE_SUCCESS)
1671 		return res;
1672 
1673 	if (key1 != 0) {
1674 		res = tee_obj_get(sess->ctx, key1, &o1);
1675 		if (res != TEE_SUCCESS)
1676 			return res;
1677 		if (o1->busy)
1678 			return TEE_ERROR_BAD_PARAMETERS;
1679 		res = tee_svc_cryp_check_key_type(o1, algo, mode);
1680 		if (res != TEE_SUCCESS)
1681 			return res;
1682 	}
1683 	if (key2 != 0) {
1684 		res = tee_obj_get(sess->ctx, key2, &o2);
1685 		if (res != TEE_SUCCESS)
1686 			return res;
1687 		if (o2->busy)
1688 			return TEE_ERROR_BAD_PARAMETERS;
1689 		res = tee_svc_cryp_check_key_type(o2, algo, mode);
1690 		if (res != TEE_SUCCESS)
1691 			return res;
1692 	}
1693 
1694 	cs = calloc(1, sizeof(struct tee_cryp_state));
1695 	if (!cs)
1696 		return TEE_ERROR_OUT_OF_MEMORY;
1697 	TAILQ_INSERT_TAIL(&sess->ctx->cryp_states, cs, link);
1698 	cs->algo = algo;
1699 	cs->mode = mode;
1700 
1701 	switch (TEE_ALG_GET_CLASS(algo)) {
1702 	case TEE_OPERATION_CIPHER:
1703 		if ((algo == TEE_ALG_AES_XTS && (key1 == 0 || key2 == 0)) ||
1704 		    (algo != TEE_ALG_AES_XTS && (key1 == 0 || key2 != 0))) {
1705 			res = TEE_ERROR_BAD_PARAMETERS;
1706 		} else {
1707 			if (crypto_ops.cipher.get_ctx_size)
1708 				res = crypto_ops.cipher.get_ctx_size(algo,
1709 								&cs->ctx_size);
1710 			else
1711 				res = TEE_ERROR_NOT_IMPLEMENTED;
1712 			if (res != TEE_SUCCESS)
1713 				break;
1714 			cs->ctx = calloc(1, cs->ctx_size);
1715 			if (!cs->ctx)
1716 				res = TEE_ERROR_OUT_OF_MEMORY;
1717 		}
1718 		break;
1719 	case TEE_OPERATION_AE:
1720 		if (key1 == 0 || key2 != 0) {
1721 			res = TEE_ERROR_BAD_PARAMETERS;
1722 		} else {
1723 			if (crypto_ops.authenc.get_ctx_size)
1724 				res = crypto_ops.authenc.get_ctx_size(algo,
1725 								&cs->ctx_size);
1726 			else
1727 				res = TEE_ERROR_NOT_IMPLEMENTED;
1728 			if (res != TEE_SUCCESS)
1729 				break;
1730 			cs->ctx = calloc(1, cs->ctx_size);
1731 			if (!cs->ctx)
1732 				res = TEE_ERROR_OUT_OF_MEMORY;
1733 		}
1734 		break;
1735 	case TEE_OPERATION_MAC:
1736 		if (key1 == 0 || key2 != 0) {
1737 			res = TEE_ERROR_BAD_PARAMETERS;
1738 		} else {
1739 			if (crypto_ops.mac.get_ctx_size)
1740 				res = crypto_ops.mac.get_ctx_size(algo,
1741 								&cs->ctx_size);
1742 			else
1743 				res = TEE_ERROR_NOT_IMPLEMENTED;
1744 			if (res != TEE_SUCCESS)
1745 				break;
1746 			cs->ctx = calloc(1, cs->ctx_size);
1747 			if (!cs->ctx)
1748 				res = TEE_ERROR_OUT_OF_MEMORY;
1749 		}
1750 		break;
1751 	case TEE_OPERATION_DIGEST:
1752 		if (key1 != 0 || key2 != 0) {
1753 			res = TEE_ERROR_BAD_PARAMETERS;
1754 		} else {
1755 			if (crypto_ops.hash.get_ctx_size)
1756 				res = crypto_ops.hash.get_ctx_size(algo,
1757 								&cs->ctx_size);
1758 			else
1759 				res = TEE_ERROR_NOT_IMPLEMENTED;
1760 			if (res != TEE_SUCCESS)
1761 				break;
1762 			cs->ctx = calloc(1, cs->ctx_size);
1763 			if (!cs->ctx)
1764 				res = TEE_ERROR_OUT_OF_MEMORY;
1765 		}
1766 		break;
1767 	case TEE_OPERATION_ASYMMETRIC_CIPHER:
1768 	case TEE_OPERATION_ASYMMETRIC_SIGNATURE:
1769 		if (key1 == 0 || key2 != 0)
1770 			res = TEE_ERROR_BAD_PARAMETERS;
1771 		break;
1772 	case TEE_OPERATION_KEY_DERIVATION:
1773 		if (key1 == 0 || key2 != 0)
1774 			res = TEE_ERROR_BAD_PARAMETERS;
1775 		break;
1776 	default:
1777 		res = TEE_ERROR_NOT_SUPPORTED;
1778 		break;
1779 	}
1780 	if (res != TEE_SUCCESS)
1781 		goto out;
1782 
1783 	res = tee_svc_copy_to_user(sess, state, &cs, sizeof(uint32_t));
1784 	if (res != TEE_SUCCESS)
1785 		goto out;
1786 
1787 	/* Register keys */
1788 	if (o1 != NULL) {
1789 		o1->busy = true;
1790 		cs->key1 = key1;
1791 	}
1792 	if (o2 != NULL) {
1793 		o2->busy = true;
1794 		cs->key2 = key2;
1795 	}
1796 
1797 out:
1798 	if (res != TEE_SUCCESS)
1799 		cryp_state_free(sess->ctx, cs);
1800 	return res;
1801 }
1802 
1803 TEE_Result tee_svc_cryp_state_copy(uint32_t dst, uint32_t src)
1804 {
1805 	TEE_Result res;
1806 	struct tee_cryp_state *cs_dst;
1807 	struct tee_cryp_state *cs_src;
1808 	struct tee_ta_session *sess;
1809 
1810 	res = tee_ta_get_current_session(&sess);
1811 	if (res != TEE_SUCCESS)
1812 		return res;
1813 
1814 	res = tee_svc_cryp_get_state(sess, dst, &cs_dst);
1815 	if (res != TEE_SUCCESS)
1816 		return res;
1817 	res = tee_svc_cryp_get_state(sess, src, &cs_src);
1818 	if (res != TEE_SUCCESS)
1819 		return res;
1820 	if (cs_dst->algo != cs_src->algo || cs_dst->mode != cs_src->mode)
1821 		return TEE_ERROR_BAD_PARAMETERS;
1822 	/* "Can't happen" */
1823 	if (cs_dst->ctx_size != cs_src->ctx_size)
1824 		return TEE_ERROR_BAD_STATE;
1825 
1826 	memcpy(cs_dst->ctx, cs_src->ctx, cs_src->ctx_size);
1827 	return TEE_SUCCESS;
1828 }
1829 
1830 void tee_svc_cryp_free_states(struct tee_ta_ctx *ctx)
1831 {
1832 	struct tee_cryp_state_head *states = &ctx->cryp_states;
1833 
1834 	while (!TAILQ_EMPTY(states))
1835 		cryp_state_free(ctx, TAILQ_FIRST(states));
1836 }
1837 
1838 TEE_Result tee_svc_cryp_state_free(uint32_t state)
1839 {
1840 	TEE_Result res;
1841 	struct tee_cryp_state *cs;
1842 	struct tee_ta_session *sess;
1843 
1844 	res = tee_ta_get_current_session(&sess);
1845 	if (res != TEE_SUCCESS)
1846 		return res;
1847 
1848 	res = tee_svc_cryp_get_state(sess, state, &cs);
1849 	if (res != TEE_SUCCESS)
1850 		return res;
1851 	cryp_state_free(sess->ctx, cs);
1852 	return TEE_SUCCESS;
1853 }
1854 
1855 /* iv and iv_len are ignored for some algorithms */
1856 TEE_Result tee_svc_hash_init(uint32_t state, const void *iv __unused,
1857 		size_t iv_len __unused)
1858 {
1859 	TEE_Result res;
1860 	struct tee_cryp_state *cs;
1861 	struct tee_ta_session *sess;
1862 
1863 	res = tee_ta_get_current_session(&sess);
1864 	if (res != TEE_SUCCESS)
1865 		return res;
1866 
1867 	res = tee_svc_cryp_get_state(sess, state, &cs);
1868 	if (res != TEE_SUCCESS)
1869 		return res;
1870 
1871 	switch (TEE_ALG_GET_CLASS(cs->algo)) {
1872 	case TEE_OPERATION_DIGEST:
1873 		if (!crypto_ops.hash.init)
1874 			return TEE_ERROR_NOT_IMPLEMENTED;
1875 		res = crypto_ops.hash.init(cs->ctx, cs->algo);
1876 		if (res != TEE_SUCCESS)
1877 			return res;
1878 		break;
1879 	case TEE_OPERATION_MAC:
1880 		{
1881 			struct tee_obj *o;
1882 			struct tee_cryp_obj_secret *key;
1883 
1884 			res = tee_obj_get(sess->ctx, cs->key1, &o);
1885 			if (res != TEE_SUCCESS)
1886 				return res;
1887 			if ((o->info.handleFlags &
1888 			     TEE_HANDLE_FLAG_INITIALIZED) == 0)
1889 				return TEE_ERROR_BAD_PARAMETERS;
1890 
1891 			key = (struct tee_cryp_obj_secret *)o->data;
1892 			if (!crypto_ops.mac.init)
1893 				return TEE_ERROR_NOT_IMPLEMENTED;
1894 			res = crypto_ops.mac.init(cs->ctx, cs->algo,
1895 						  (void *)(key + 1),
1896 						  key->key_size);
1897 			if (res != TEE_SUCCESS)
1898 				return res;
1899 			break;
1900 		}
1901 	default:
1902 		return TEE_ERROR_BAD_PARAMETERS;
1903 	}
1904 
1905 	return TEE_SUCCESS;
1906 }
1907 
1908 TEE_Result tee_svc_hash_update(uint32_t state, const void *chunk,
1909 			       size_t chunk_size)
1910 {
1911 	TEE_Result res;
1912 	struct tee_cryp_state *cs;
1913 	struct tee_ta_session *sess;
1914 
1915 	/* No data, but size provided isn't valid parameters. */
1916 	if (!chunk && chunk_size)
1917 		return TEE_ERROR_BAD_PARAMETERS;
1918 
1919 	/* Zero length hash is valid, but nothing we need to do. */
1920 	if (!chunk_size)
1921 		return TEE_SUCCESS;
1922 
1923 	res = tee_ta_get_current_session(&sess);
1924 	if (res != TEE_SUCCESS)
1925 		return res;
1926 
1927 	res = tee_mmu_check_access_rights(sess->ctx,
1928 					  TEE_MEMORY_ACCESS_READ |
1929 					  TEE_MEMORY_ACCESS_ANY_OWNER,
1930 					  (tee_uaddr_t)chunk, chunk_size);
1931 	if (res != TEE_SUCCESS)
1932 		return res;
1933 
1934 	res = tee_svc_cryp_get_state(sess, state, &cs);
1935 	if (res != TEE_SUCCESS)
1936 		return res;
1937 
1938 	switch (TEE_ALG_GET_CLASS(cs->algo)) {
1939 	case TEE_OPERATION_DIGEST:
1940 		if (!crypto_ops.hash.update)
1941 			return TEE_ERROR_NOT_IMPLEMENTED;
1942 		res = crypto_ops.hash.update(cs->ctx, cs->algo, chunk,
1943 					     chunk_size);
1944 		if (res != TEE_SUCCESS)
1945 			return res;
1946 		break;
1947 	case TEE_OPERATION_MAC:
1948 		if (!crypto_ops.mac.update)
1949 			return TEE_ERROR_NOT_IMPLEMENTED;
1950 		res = crypto_ops.mac.update(cs->ctx, cs->algo, chunk,
1951 					    chunk_size);
1952 		if (res != TEE_SUCCESS)
1953 			return res;
1954 		break;
1955 	default:
1956 		return TEE_ERROR_BAD_PARAMETERS;
1957 	}
1958 
1959 	return TEE_SUCCESS;
1960 }
1961 
1962 TEE_Result tee_svc_hash_final(uint32_t state, const void *chunk,
1963 			      size_t chunk_size, void *hash, uint32_t *hash_len)
1964 {
1965 	TEE_Result res, res2;
1966 	size_t hash_size;
1967 	uint32_t hlen;
1968 	struct tee_cryp_state *cs;
1969 	struct tee_ta_session *sess;
1970 
1971 	/* No data, but size provided isn't valid parameters. */
1972 	if (!chunk && chunk_size)
1973 		return TEE_ERROR_BAD_PARAMETERS;
1974 
1975 	res = tee_ta_get_current_session(&sess);
1976 	if (res != TEE_SUCCESS)
1977 		return res;
1978 
1979 	res = tee_mmu_check_access_rights(sess->ctx,
1980 					  TEE_MEMORY_ACCESS_READ |
1981 					  TEE_MEMORY_ACCESS_ANY_OWNER,
1982 					  (tee_uaddr_t)chunk, chunk_size);
1983 	if (res != TEE_SUCCESS)
1984 		return res;
1985 
1986 	res = tee_svc_copy_from_user(sess, &hlen, hash_len, sizeof(uint32_t));
1987 	if (res != TEE_SUCCESS)
1988 		return res;
1989 
1990 	res = tee_mmu_check_access_rights(sess->ctx,
1991 					  TEE_MEMORY_ACCESS_READ |
1992 					  TEE_MEMORY_ACCESS_WRITE |
1993 					  TEE_MEMORY_ACCESS_ANY_OWNER,
1994 					  (tee_uaddr_t)hash, hlen);
1995 	if (res != TEE_SUCCESS)
1996 		return res;
1997 
1998 	res = tee_svc_cryp_get_state(sess, state, &cs);
1999 	if (res != TEE_SUCCESS)
2000 		return res;
2001 
2002 	switch (TEE_ALG_GET_CLASS(cs->algo)) {
2003 	case TEE_OPERATION_DIGEST:
2004 		if (!crypto_ops.hash.update || !crypto_ops.hash.final)
2005 			return TEE_ERROR_NOT_IMPLEMENTED;
2006 		res = tee_hash_get_digest_size(cs->algo, &hash_size);
2007 		if (res != TEE_SUCCESS)
2008 			return res;
2009 		if (*hash_len < hash_size) {
2010 			res = TEE_ERROR_SHORT_BUFFER;
2011 			goto out;
2012 		}
2013 
2014 		if (chunk_size) {
2015 			res = crypto_ops.hash.update(cs->ctx, cs->algo, chunk,
2016 						     chunk_size);
2017 			if (res != TEE_SUCCESS)
2018 				return res;
2019 		}
2020 
2021 		res = crypto_ops.hash.final(cs->ctx, cs->algo, hash,
2022 					    hash_size);
2023 		if (res != TEE_SUCCESS)
2024 			return res;
2025 		break;
2026 
2027 	case TEE_OPERATION_MAC:
2028 		if (!crypto_ops.mac.update || !crypto_ops.mac.final)
2029 			return TEE_ERROR_NOT_IMPLEMENTED;
2030 		res = tee_mac_get_digest_size(cs->algo, &hash_size);
2031 		if (res != TEE_SUCCESS)
2032 			return res;
2033 		if (*hash_len < hash_size) {
2034 			res = TEE_ERROR_SHORT_BUFFER;
2035 			goto out;
2036 		}
2037 
2038 		if (chunk_size) {
2039 			res = crypto_ops.mac.update(cs->ctx, cs->algo, chunk,
2040 						    chunk_size);
2041 			if (res != TEE_SUCCESS)
2042 				return res;
2043 		}
2044 
2045 		res = crypto_ops.mac.final(cs->ctx, cs->algo, hash, hash_size);
2046 		if (res != TEE_SUCCESS)
2047 			return res;
2048 		break;
2049 
2050 	default:
2051 		return TEE_ERROR_BAD_PARAMETERS;
2052 	}
2053 out:
2054 	hlen = hash_size;
2055 	res2 = tee_svc_copy_to_user(sess, hash_len, &hlen, sizeof(uint32_t));
2056 	if (res2 != TEE_SUCCESS)
2057 		return res2;
2058 	return res;
2059 }
2060 
2061 TEE_Result tee_svc_cipher_init(uint32_t state, const void *iv, size_t iv_len)
2062 {
2063 	TEE_Result res;
2064 	struct tee_cryp_state *cs;
2065 	struct tee_ta_session *sess;
2066 	struct tee_obj *o;
2067 	struct tee_cryp_obj_secret *key1;
2068 
2069 	res = tee_ta_get_current_session(&sess);
2070 	if (res != TEE_SUCCESS)
2071 		return res;
2072 
2073 	res = tee_svc_cryp_get_state(sess, state, &cs);
2074 	if (res != TEE_SUCCESS)
2075 		return res;
2076 
2077 	res = tee_mmu_check_access_rights(sess->ctx,
2078 					  TEE_MEMORY_ACCESS_READ |
2079 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2080 					  (tee_uaddr_t) iv, iv_len);
2081 	if (res != TEE_SUCCESS)
2082 		return res;
2083 
2084 	res = tee_obj_get(sess->ctx, cs->key1, &o);
2085 	if (res != TEE_SUCCESS)
2086 		return res;
2087 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
2088 		return TEE_ERROR_BAD_PARAMETERS;
2089 
2090 	key1 = (struct tee_cryp_obj_secret *)o->data;
2091 
2092 	if (!crypto_ops.cipher.init)
2093 		return TEE_ERROR_NOT_IMPLEMENTED;
2094 
2095 	if (tee_obj_get(sess->ctx, cs->key2, &o) == TEE_SUCCESS) {
2096 		struct tee_cryp_obj_secret *key2 =
2097 		    (struct tee_cryp_obj_secret *)o->data;
2098 
2099 		if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
2100 			return TEE_ERROR_BAD_PARAMETERS;
2101 
2102 		res = crypto_ops.cipher.init(cs->ctx, cs->algo, cs->mode,
2103 					     (uint8_t *)(key1 + 1),
2104 					     key1->key_size,
2105 					     (uint8_t *)(key2 + 1),
2106 					     key2->key_size,
2107 					     iv, iv_len);
2108 	} else {
2109 		res = crypto_ops.cipher.init(cs->ctx, cs->algo, cs->mode,
2110 					     (uint8_t *)(key1 + 1),
2111 					     key1->key_size,
2112 					     NULL,
2113 					     0,
2114 					     iv, iv_len);
2115 	}
2116 	if (res != TEE_SUCCESS)
2117 		return res;
2118 
2119 	cs->ctx_finalize = crypto_ops.cipher.final;
2120 	return TEE_SUCCESS;
2121 }
2122 
2123 static TEE_Result tee_svc_cipher_update_helper(uint32_t state, bool last_block,
2124 					       const void *src, size_t src_len,
2125 					       void *dst, uint32_t *dst_len)
2126 {
2127 	TEE_Result res;
2128 	struct tee_cryp_state *cs;
2129 	struct tee_ta_session *sess;
2130 	uint32_t dlen;
2131 
2132 	res = tee_ta_get_current_session(&sess);
2133 	if (res != TEE_SUCCESS)
2134 		return res;
2135 
2136 	res = tee_svc_cryp_get_state(sess, state, &cs);
2137 	if (res != TEE_SUCCESS)
2138 		return res;
2139 
2140 	res = tee_mmu_check_access_rights(sess->ctx,
2141 					  TEE_MEMORY_ACCESS_READ |
2142 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2143 					  (tee_uaddr_t)src, src_len);
2144 	if (res != TEE_SUCCESS)
2145 		return res;
2146 
2147 	if (!dst_len) {
2148 		dlen = 0;
2149 	} else {
2150 		res =
2151 		    tee_svc_copy_from_user(sess, &dlen, dst_len,
2152 					   sizeof(uint32_t));
2153 		if (res != TEE_SUCCESS)
2154 			return res;
2155 
2156 		res = tee_mmu_check_access_rights(sess->ctx,
2157 						  TEE_MEMORY_ACCESS_READ |
2158 						  TEE_MEMORY_ACCESS_WRITE |
2159 						  TEE_MEMORY_ACCESS_ANY_OWNER,
2160 						  (tee_uaddr_t)dst, dlen);
2161 		if (res != TEE_SUCCESS)
2162 			return res;
2163 	}
2164 
2165 	if (dlen < src_len) {
2166 		res = TEE_ERROR_SHORT_BUFFER;
2167 		goto out;
2168 	}
2169 
2170 	if (src_len > 0) {
2171 		/* Permit src_len == 0 to finalize the operation */
2172 		res = tee_do_cipher_update(cs->ctx, cs->algo, cs->mode,
2173 					   last_block, src, src_len, dst);
2174 	}
2175 
2176 	if (last_block && cs->ctx_finalize != NULL) {
2177 		cs->ctx_finalize(cs->ctx, cs->mode);
2178 		cs->ctx_finalize = NULL;
2179 	}
2180 
2181 out:
2182 	if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) &&
2183 	    dst_len != NULL) {
2184 		TEE_Result res2;
2185 
2186 		dlen = src_len;
2187 		res2 = tee_svc_copy_to_user(sess, dst_len, &dlen,
2188 					    sizeof(uint32_t));
2189 		if (res2 != TEE_SUCCESS)
2190 			res = res2;
2191 	}
2192 
2193 	return res;
2194 }
2195 
2196 TEE_Result tee_svc_cipher_update(uint32_t state, const void *src,
2197 				 size_t src_len, void *dst, uint32_t *dst_len)
2198 {
2199 	return tee_svc_cipher_update_helper(state, false /* last_block */,
2200 					    src, src_len, dst, dst_len);
2201 }
2202 
2203 TEE_Result tee_svc_cipher_final(uint32_t state, const void *src,
2204 				size_t src_len, void *dst, uint32_t *dst_len)
2205 {
2206 	return tee_svc_cipher_update_helper(state, true /* last_block */,
2207 					    src, src_len, dst, dst_len);
2208 }
2209 
2210 #if defined(CFG_CRYPTO_HKDF)
2211 static TEE_Result get_hkdf_params(const TEE_Attribute *params,
2212 				  uint32_t param_count,
2213 				  void **salt, size_t *salt_len, void **info,
2214 				  size_t *info_len, size_t *okm_len)
2215 {
2216 	size_t n;
2217 	enum { SALT = 0x1, LENGTH = 0x2, INFO = 0x4 };
2218 	uint8_t found = 0;
2219 
2220 	*salt = *info = NULL;
2221 	*salt_len = *info_len = *okm_len = 0;
2222 
2223 	for (n = 0; n < param_count; n++) {
2224 		switch (params[n].attributeID) {
2225 		case TEE_ATTR_HKDF_SALT:
2226 			if (!(found & SALT)) {
2227 				*salt = params[n].content.ref.buffer;
2228 				*salt_len = params[n].content.ref.length;
2229 				found |= SALT;
2230 			}
2231 			break;
2232 		case TEE_ATTR_HKDF_OKM_LENGTH:
2233 			if (!(found & LENGTH)) {
2234 				*okm_len = params[n].content.value.a;
2235 				found |= LENGTH;
2236 			}
2237 			break;
2238 		case TEE_ATTR_HKDF_INFO:
2239 			if (!(found & INFO)) {
2240 				*info = params[n].content.ref.buffer;
2241 				*info_len = params[n].content.ref.length;
2242 				found |= INFO;
2243 			}
2244 			break;
2245 		default:
2246 			/* Unexpected attribute */
2247 			return TEE_ERROR_BAD_PARAMETERS;
2248 		}
2249 
2250 	}
2251 
2252 	if (!(found & LENGTH))
2253 		return TEE_ERROR_BAD_PARAMETERS;
2254 
2255 	return TEE_SUCCESS;
2256 }
2257 #endif
2258 
2259 #if defined(CFG_CRYPTO_CONCAT_KDF)
2260 static TEE_Result get_concat_kdf_params(const TEE_Attribute *params,
2261 					uint32_t param_count,
2262 					void **other_info,
2263 					size_t *other_info_len,
2264 					size_t *derived_key_len)
2265 {
2266 	size_t n;
2267 	enum { LENGTH = 0x1, INFO = 0x2 };
2268 	uint8_t found = 0;
2269 
2270 	*other_info = NULL;
2271 	*other_info_len = *derived_key_len = 0;
2272 
2273 	for (n = 0; n < param_count; n++) {
2274 		switch (params[n].attributeID) {
2275 		case TEE_ATTR_CONCAT_KDF_OTHER_INFO:
2276 			if (!(found & INFO)) {
2277 				*other_info = params[n].content.ref.buffer;
2278 				*other_info_len = params[n].content.ref.length;
2279 				found |= INFO;
2280 			}
2281 			break;
2282 		case TEE_ATTR_CONCAT_KDF_DKM_LENGTH:
2283 			if (!(found & LENGTH)) {
2284 				*derived_key_len = params[n].content.value.a;
2285 				found |= LENGTH;
2286 			}
2287 			break;
2288 		default:
2289 			/* Unexpected attribute */
2290 			return TEE_ERROR_BAD_PARAMETERS;
2291 		}
2292 	}
2293 
2294 	if (!(found & LENGTH))
2295 		return TEE_ERROR_BAD_PARAMETERS;
2296 
2297 	return TEE_SUCCESS;
2298 }
2299 #endif
2300 
2301 #if defined(CFG_CRYPTO_PBKDF2)
2302 static TEE_Result get_pbkdf2_params(const TEE_Attribute *params,
2303 				   uint32_t param_count, void **salt,
2304 				   size_t *salt_len, size_t *derived_key_len,
2305 				   size_t *iteration_count)
2306 {
2307 	size_t n;
2308 	enum { SALT = 0x1, LENGTH = 0x2, COUNT = 0x4 };
2309 	uint8_t found = 0;
2310 
2311 	*salt = NULL;
2312 	*salt_len = *derived_key_len = *iteration_count = 0;
2313 
2314 	for (n = 0; n < param_count; n++) {
2315 		switch (params[n].attributeID) {
2316 		case TEE_ATTR_PBKDF2_SALT:
2317 			if (!(found & SALT)) {
2318 				*salt = params[n].content.ref.buffer;
2319 				*salt_len = params[n].content.ref.length;
2320 				found |= SALT;
2321 			}
2322 			break;
2323 		case TEE_ATTR_PBKDF2_DKM_LENGTH:
2324 			if (!(found & LENGTH)) {
2325 				*derived_key_len = params[n].content.value.a;
2326 				found |= LENGTH;
2327 			}
2328 			break;
2329 		case TEE_ATTR_PBKDF2_ITERATION_COUNT:
2330 			if (!(found & COUNT)) {
2331 				*iteration_count = params[n].content.value.a;
2332 				found |= COUNT;
2333 			}
2334 			break;
2335 		default:
2336 			/* Unexpected attribute */
2337 			return TEE_ERROR_BAD_PARAMETERS;
2338 		}
2339 	}
2340 
2341 	if ((found & (LENGTH|COUNT)) != (LENGTH|COUNT))
2342 		return TEE_ERROR_BAD_PARAMETERS;
2343 
2344 	return TEE_SUCCESS;
2345 }
2346 #endif
2347 
2348 TEE_Result tee_svc_cryp_derive_key(uint32_t state,
2349 			const struct abi_user32_attribute *usr_params,
2350 			uint32_t param_count, uint32_t derived_key)
2351 {
2352 	TEE_Result res = TEE_ERROR_NOT_SUPPORTED;
2353 	struct tee_ta_session *sess;
2354 	struct tee_obj *ko;
2355 	struct tee_obj *so;
2356 	struct tee_cryp_state *cs;
2357 	struct tee_cryp_obj_secret *sk;
2358 	const struct tee_cryp_obj_type_props *type_props;
2359 	TEE_Attribute *params = NULL;
2360 
2361 	res = tee_ta_get_current_session(&sess);
2362 	if (res != TEE_SUCCESS)
2363 		return res;
2364 
2365 	res = tee_svc_cryp_get_state(sess, state, &cs);
2366 	if (res != TEE_SUCCESS)
2367 		return res;
2368 
2369 	params = malloc(sizeof(TEE_Attribute) * param_count);
2370 	if (!params)
2371 		return TEE_ERROR_OUT_OF_MEMORY;
2372 	res = copy_in_attrs(sess->ctx, usr_params, param_count, params);
2373 	if (res != TEE_SUCCESS)
2374 		goto out;
2375 
2376 	/* Get key set in operation */
2377 	res = tee_obj_get(sess->ctx, cs->key1, &ko);
2378 	if (res != TEE_SUCCESS)
2379 		goto out;
2380 
2381 	res = tee_obj_get(sess->ctx, derived_key, &so);
2382 	if (res != TEE_SUCCESS)
2383 		goto out;
2384 
2385 	/* Find information needed about the object to initialize */
2386 	sk = (struct tee_cryp_obj_secret *)so->data;
2387 
2388 	/* Find description of object */
2389 	type_props = tee_svc_find_type_props(so->info.objectType);
2390 	if (!type_props) {
2391 		res = TEE_ERROR_NOT_SUPPORTED;
2392 		goto out;
2393 	}
2394 
2395 	if (cs->algo == TEE_ALG_DH_DERIVE_SHARED_SECRET) {
2396 		size_t alloc_size;
2397 		struct bignum *pub;
2398 		struct bignum *ss;
2399 
2400 		if (!crypto_ops.bignum.allocate ||
2401 		    !crypto_ops.bignum.free ||
2402 		    !crypto_ops.bignum.bin2bn ||
2403 		    !crypto_ops.bignum.bn2bin ||
2404 		    !crypto_ops.bignum.num_bytes ||
2405 		    !crypto_ops.acipher.dh_shared_secret) {
2406 			res = TEE_ERROR_NOT_IMPLEMENTED;
2407 			goto out;
2408 		}
2409 		if (param_count != 1 ||
2410 		    params[0].attributeID != TEE_ATTR_DH_PUBLIC_VALUE) {
2411 			res = TEE_ERROR_BAD_PARAMETERS;
2412 			goto out;
2413 		}
2414 
2415 		alloc_size = params[0].content.ref.length * 8;
2416 		pub = crypto_ops.bignum.allocate(alloc_size);
2417 		ss = crypto_ops.bignum.allocate(alloc_size);
2418 		if (pub && ss) {
2419 			crypto_ops.bignum.bin2bn(params[0].content.ref.buffer,
2420 					params[0].content.ref.length, pub);
2421 			res = crypto_ops.acipher.dh_shared_secret(ko->data,
2422 								  pub, ss);
2423 			if (res == TEE_SUCCESS) {
2424 				sk->key_size = crypto_ops.bignum.num_bytes(ss);
2425 				crypto_ops.bignum.bn2bin(ss,
2426 							 (uint8_t *)(sk + 1));
2427 				so->info.handleFlags |=
2428 						TEE_HANDLE_FLAG_INITIALIZED;
2429 				SET_ATTRIBUTE(so, type_props,
2430 					      TEE_ATTR_SECRET_VALUE);
2431 			}
2432 		} else {
2433 			res = TEE_ERROR_OUT_OF_MEMORY;
2434 		}
2435 		crypto_ops.bignum.free(pub);
2436 		crypto_ops.bignum.free(ss);
2437 	}
2438 #if defined(CFG_CRYPTO_HKDF)
2439 	else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_HKDF) {
2440 		void *salt, *info;
2441 		size_t salt_len, info_len, okm_len;
2442 		uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
2443 		struct tee_cryp_obj_secret *ik = ko->data;
2444 		const uint8_t *ikm = (const uint8_t *)(ik + 1);
2445 
2446 		res = get_hkdf_params(params, param_count, &salt, &salt_len,
2447 				      &info, &info_len, &okm_len);
2448 		if (res != TEE_SUCCESS)
2449 			goto out;
2450 
2451 		/* Requested size must fit into the output object's buffer */
2452 		if (okm_len >
2453 			ko->data_size - sizeof(struct tee_cryp_obj_secret)) {
2454 			res = TEE_ERROR_BAD_PARAMETERS;
2455 			goto out;
2456 		}
2457 
2458 		res = tee_cryp_hkdf(hash_id, ikm, ik->key_size, salt, salt_len,
2459 				    info, info_len, (uint8_t *)(sk + 1),
2460 				    okm_len);
2461 		if (res == TEE_SUCCESS) {
2462 			sk->key_size = okm_len;
2463 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
2464 			SET_ATTRIBUTE(so, type_props, TEE_ATTR_SECRET_VALUE);
2465 		}
2466 	}
2467 #endif
2468 #if defined(CFG_CRYPTO_CONCAT_KDF)
2469 	else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_CONCAT_KDF) {
2470 		void *info;
2471 		size_t info_len, derived_key_len;
2472 		uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
2473 		struct tee_cryp_obj_secret *ss = ko->data;
2474 		const uint8_t *shared_secret = (const uint8_t *)(ss + 1);
2475 
2476 		res = get_concat_kdf_params(params, param_count, &info,
2477 					    &info_len, &derived_key_len);
2478 		if (res != TEE_SUCCESS)
2479 			goto out;
2480 
2481 		/* Requested size must fit into the output object's buffer */
2482 		if (derived_key_len >
2483 		    ko->data_size - sizeof(struct tee_cryp_obj_secret)) {
2484 			res = TEE_ERROR_BAD_PARAMETERS;
2485 			goto out;
2486 		}
2487 
2488 		res = tee_cryp_concat_kdf(hash_id, shared_secret, ss->key_size,
2489 					  info, info_len, (uint8_t *)(sk + 1),
2490 					  derived_key_len);
2491 		if (res == TEE_SUCCESS) {
2492 			sk->key_size = derived_key_len;
2493 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
2494 			SET_ATTRIBUTE(so, type_props, TEE_ATTR_SECRET_VALUE);
2495 		}
2496 	}
2497 #endif
2498 #if defined(CFG_CRYPTO_PBKDF2)
2499 	else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_PBKDF2) {
2500 		void *salt;
2501 		size_t salt_len, iteration_count, derived_key_len;
2502 		uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
2503 		struct tee_cryp_obj_secret *ss = ko->data;
2504 		const uint8_t *password = (const uint8_t *)(ss + 1);
2505 
2506 		res = get_pbkdf2_params(params, param_count, &salt, &salt_len,
2507 					&derived_key_len, &iteration_count);
2508 		if (res != TEE_SUCCESS)
2509 			goto out;
2510 
2511 		/* Requested size must fit into the output object's buffer */
2512 		if (derived_key_len >
2513 			ko->data_size - sizeof(struct tee_cryp_obj_secret)) {
2514 			res = TEE_ERROR_BAD_PARAMETERS;
2515 			goto out;
2516 		}
2517 
2518 		res = tee_cryp_pbkdf2(hash_id, password, ss->key_size, salt,
2519 				      salt_len, iteration_count,
2520 				      (uint8_t *)(sk + 1), derived_key_len);
2521 		if (res == TEE_SUCCESS) {
2522 			sk->key_size = derived_key_len;
2523 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
2524 			SET_ATTRIBUTE(so, type_props, TEE_ATTR_SECRET_VALUE);
2525 		}
2526 	}
2527 #endif
2528 	else
2529 		res = TEE_ERROR_NOT_SUPPORTED;
2530 
2531 out:
2532 	free(params);
2533 	return res;
2534 }
2535 
2536 TEE_Result tee_svc_cryp_random_number_generate(void *buf, size_t blen)
2537 {
2538 	TEE_Result res;
2539 	struct tee_ta_session *sess;
2540 
2541 	res = tee_ta_get_current_session(&sess);
2542 	if (res != TEE_SUCCESS)
2543 		return res;
2544 
2545 	res = tee_mmu_check_access_rights(sess->ctx,
2546 					  TEE_MEMORY_ACCESS_WRITE |
2547 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2548 					  (tee_uaddr_t)buf, blen);
2549 	if (res != TEE_SUCCESS)
2550 		return res;
2551 
2552 	res = crypto_ops.prng.read(buf, blen);
2553 	if (res != TEE_SUCCESS)
2554 		return res;
2555 
2556 	return res;
2557 }
2558 
2559 TEE_Result tee_svc_authenc_init(uint32_t state, const void *nonce,
2560 				size_t nonce_len, size_t tag_len,
2561 				size_t aad_len, size_t payload_len)
2562 {
2563 	TEE_Result res;
2564 	struct tee_cryp_state *cs;
2565 	struct tee_ta_session *sess;
2566 	struct tee_obj *o;
2567 	struct tee_cryp_obj_secret *key;
2568 
2569 	res = tee_ta_get_current_session(&sess);
2570 	if (res != TEE_SUCCESS)
2571 		return res;
2572 
2573 	res = tee_svc_cryp_get_state(sess, state, &cs);
2574 	if (res != TEE_SUCCESS)
2575 		return res;
2576 
2577 	res = tee_obj_get(sess->ctx, cs->key1, &o);
2578 	if (res != TEE_SUCCESS)
2579 		return res;
2580 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
2581 		return TEE_ERROR_BAD_PARAMETERS;
2582 
2583 	if (!crypto_ops.authenc.init)
2584 		return TEE_ERROR_NOT_IMPLEMENTED;
2585 	key = (struct tee_cryp_obj_secret *)o->data;
2586 	res = crypto_ops.authenc.init(cs->ctx, cs->algo, cs->mode,
2587 				      (uint8_t *)(key + 1), key->key_size,
2588 				      nonce, nonce_len, tag_len, aad_len,
2589 				      payload_len);
2590 	if (res != TEE_SUCCESS)
2591 		return res;
2592 
2593 	cs->ctx_finalize = (tee_cryp_ctx_finalize_func_t)
2594 				crypto_ops.authenc.final;
2595 	return TEE_SUCCESS;
2596 }
2597 
2598 TEE_Result tee_svc_authenc_update_aad(uint32_t state, const void *aad_data,
2599 				      size_t aad_data_len)
2600 {
2601 	TEE_Result res;
2602 	struct tee_cryp_state *cs;
2603 	struct tee_ta_session *sess;
2604 
2605 	res = tee_ta_get_current_session(&sess);
2606 	if (res != TEE_SUCCESS)
2607 		return res;
2608 
2609 	res = tee_mmu_check_access_rights(sess->ctx,
2610 					  TEE_MEMORY_ACCESS_READ |
2611 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2612 					  (tee_uaddr_t) aad_data,
2613 					  aad_data_len);
2614 	if (res != TEE_SUCCESS)
2615 		return res;
2616 
2617 	res = tee_svc_cryp_get_state(sess, state, &cs);
2618 	if (res != TEE_SUCCESS)
2619 		return res;
2620 
2621 	if (!crypto_ops.authenc.update_aad)
2622 		return TEE_ERROR_NOT_IMPLEMENTED;
2623 	res = crypto_ops.authenc.update_aad(cs->ctx, cs->algo, cs->mode,
2624 					    aad_data, aad_data_len);
2625 	if (res != TEE_SUCCESS)
2626 		return res;
2627 
2628 	return TEE_SUCCESS;
2629 }
2630 
2631 TEE_Result tee_svc_authenc_update_payload(uint32_t state, const void *src_data,
2632 					  size_t src_len, void *dst_data,
2633 					  uint32_t *dst_len)
2634 {
2635 	TEE_Result res;
2636 	struct tee_cryp_state *cs;
2637 	struct tee_ta_session *sess;
2638 	uint32_t dlen;
2639 	size_t tmp_dlen;
2640 
2641 	res = tee_ta_get_current_session(&sess);
2642 	if (res != TEE_SUCCESS)
2643 		return res;
2644 
2645 	res = tee_svc_cryp_get_state(sess, state, &cs);
2646 	if (res != TEE_SUCCESS)
2647 		return res;
2648 
2649 	res = tee_mmu_check_access_rights(sess->ctx,
2650 					  TEE_MEMORY_ACCESS_READ |
2651 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2652 					  (tee_uaddr_t) src_data, src_len);
2653 	if (res != TEE_SUCCESS)
2654 		return res;
2655 
2656 	res = tee_svc_copy_from_user(sess, &dlen, dst_len, sizeof(uint32_t));
2657 	if (res != TEE_SUCCESS)
2658 		return res;
2659 
2660 	res = tee_mmu_check_access_rights(sess->ctx,
2661 					  TEE_MEMORY_ACCESS_READ |
2662 					  TEE_MEMORY_ACCESS_WRITE |
2663 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2664 					  (tee_uaddr_t)dst_data, dlen);
2665 	if (res != TEE_SUCCESS)
2666 		return res;
2667 
2668 	if (dlen < src_len) {
2669 		res = TEE_ERROR_SHORT_BUFFER;
2670 		goto out;
2671 	}
2672 
2673 	if (!crypto_ops.authenc.update_payload)
2674 		return TEE_ERROR_NOT_IMPLEMENTED;
2675 	tmp_dlen = dlen;
2676 	res = crypto_ops.authenc.update_payload(cs->ctx, cs->algo, cs->mode,
2677 						src_data, src_len, dst_data,
2678 						&tmp_dlen);
2679 	dlen = tmp_dlen;
2680 
2681 out:
2682 	if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
2683 		TEE_Result res2 = tee_svc_copy_to_user(sess, dst_len, &dlen,
2684 						       sizeof(uint32_t));
2685 		if (res2 != TEE_SUCCESS)
2686 			res = res2;
2687 	}
2688 
2689 	return res;
2690 }
2691 
2692 TEE_Result tee_svc_authenc_enc_final(uint32_t state, const void *src_data,
2693 				     size_t src_len, void *dst_data,
2694 				     uint32_t *dst_len, void *tag,
2695 				     uint32_t *tag_len)
2696 {
2697 	TEE_Result res;
2698 	struct tee_cryp_state *cs;
2699 	struct tee_ta_session *sess;
2700 	uint32_t dlen;
2701 	uint32_t tlen;
2702 	size_t tmp_dlen;
2703 	size_t tmp_tlen;
2704 
2705 	res = tee_ta_get_current_session(&sess);
2706 	if (res != TEE_SUCCESS)
2707 		return res;
2708 
2709 	res = tee_svc_cryp_get_state(sess, state, &cs);
2710 	if (res != TEE_SUCCESS)
2711 		return res;
2712 
2713 	if (cs->mode != TEE_MODE_ENCRYPT)
2714 		return TEE_ERROR_BAD_PARAMETERS;
2715 
2716 	res = tee_mmu_check_access_rights(sess->ctx,
2717 					  TEE_MEMORY_ACCESS_READ |
2718 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2719 					  (tee_uaddr_t)src_data, src_len);
2720 	if (res != TEE_SUCCESS)
2721 		return res;
2722 
2723 	if (!dst_len) {
2724 		dlen = 0;
2725 	} else {
2726 		res = tee_svc_copy_from_user(sess, &dlen, dst_len,
2727 					     sizeof(uint32_t));
2728 		if (res != TEE_SUCCESS)
2729 			return res;
2730 
2731 		res = tee_mmu_check_access_rights(sess->ctx,
2732 						  TEE_MEMORY_ACCESS_READ |
2733 						  TEE_MEMORY_ACCESS_WRITE |
2734 						  TEE_MEMORY_ACCESS_ANY_OWNER,
2735 						  (tee_uaddr_t)dst_data, dlen);
2736 		if (res != TEE_SUCCESS)
2737 			return res;
2738 	}
2739 
2740 	if (dlen < src_len) {
2741 		res = TEE_ERROR_SHORT_BUFFER;
2742 		goto out;
2743 	}
2744 
2745 	res = tee_svc_copy_from_user(sess, &tlen, tag_len, sizeof(uint32_t));
2746 	if (res != TEE_SUCCESS)
2747 		return res;
2748 
2749 	res = tee_mmu_check_access_rights(sess->ctx,
2750 					  TEE_MEMORY_ACCESS_READ |
2751 					  TEE_MEMORY_ACCESS_WRITE |
2752 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2753 					  (tee_uaddr_t)tag, tlen);
2754 	if (res != TEE_SUCCESS)
2755 		return res;
2756 
2757 	if (!crypto_ops.authenc.enc_final)
2758 		return TEE_ERROR_NOT_IMPLEMENTED;
2759 	tmp_dlen = dlen;
2760 	tmp_tlen = tlen;
2761 	res = crypto_ops.authenc.enc_final(cs->ctx, cs->algo, src_data,
2762 					   src_len, dst_data, &tmp_dlen, tag,
2763 					   &tmp_tlen);
2764 	dlen = tmp_dlen;
2765 	tlen = tmp_tlen;
2766 
2767 out:
2768 	if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
2769 		TEE_Result res2;
2770 
2771 		if (dst_len != NULL) {
2772 			res2 = tee_svc_copy_to_user(sess, dst_len, &dlen,
2773 						    sizeof(uint32_t));
2774 			if (res2 != TEE_SUCCESS)
2775 				return res2;
2776 		}
2777 
2778 		res2 = tee_svc_copy_to_user(sess, tag_len, &tlen,
2779 					    sizeof(uint32_t));
2780 		if (res2 != TEE_SUCCESS)
2781 			return res2;
2782 	}
2783 
2784 	return res;
2785 }
2786 
2787 TEE_Result tee_svc_authenc_dec_final(uint32_t state, const void *src_data,
2788 				     size_t src_len, void *dst_data,
2789 				     uint32_t *dst_len, const void *tag,
2790 				     size_t tag_len)
2791 {
2792 	TEE_Result res;
2793 	struct tee_cryp_state *cs;
2794 	struct tee_ta_session *sess;
2795 	uint32_t dlen;
2796 	size_t tmp_dlen;
2797 
2798 	res = tee_ta_get_current_session(&sess);
2799 	if (res != TEE_SUCCESS)
2800 		return res;
2801 
2802 	res = tee_svc_cryp_get_state(sess, state, &cs);
2803 	if (res != TEE_SUCCESS)
2804 		return res;
2805 
2806 	if (cs->mode != TEE_MODE_DECRYPT)
2807 		return TEE_ERROR_BAD_PARAMETERS;
2808 
2809 	res = tee_mmu_check_access_rights(sess->ctx,
2810 					  TEE_MEMORY_ACCESS_READ |
2811 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2812 					  (tee_uaddr_t)src_data, src_len);
2813 	if (res != TEE_SUCCESS)
2814 		return res;
2815 
2816 	if (!dst_len) {
2817 		dlen = 0;
2818 	} else {
2819 		res = tee_svc_copy_from_user(sess, &dlen, dst_len,
2820 					     sizeof(uint32_t));
2821 		if (res != TEE_SUCCESS)
2822 			return res;
2823 
2824 		res = tee_mmu_check_access_rights(sess->ctx,
2825 						  TEE_MEMORY_ACCESS_READ |
2826 						  TEE_MEMORY_ACCESS_WRITE |
2827 						  TEE_MEMORY_ACCESS_ANY_OWNER,
2828 						  (tee_uaddr_t)dst_data, dlen);
2829 		if (res != TEE_SUCCESS)
2830 			return res;
2831 	}
2832 
2833 	if (dlen < src_len) {
2834 		res = TEE_ERROR_SHORT_BUFFER;
2835 		goto out;
2836 	}
2837 
2838 	res = tee_mmu_check_access_rights(sess->ctx,
2839 					  TEE_MEMORY_ACCESS_READ |
2840 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2841 					  (tee_uaddr_t)tag, tag_len);
2842 	if (res != TEE_SUCCESS)
2843 		return res;
2844 
2845 	if (!crypto_ops.authenc.dec_final)
2846 		return TEE_ERROR_NOT_IMPLEMENTED;
2847 	tmp_dlen = dlen;
2848 	res = crypto_ops.authenc.dec_final(cs->ctx, cs->algo, src_data,
2849 					   src_len, dst_data, &tmp_dlen, tag,
2850 					   tag_len);
2851 	dlen = tmp_dlen;
2852 
2853 out:
2854 	if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) &&
2855 	    dst_len != NULL) {
2856 		TEE_Result res2;
2857 
2858 		res2 = tee_svc_copy_to_user(sess, dst_len, &dlen,
2859 					    sizeof(uint32_t));
2860 		if (res2 != TEE_SUCCESS)
2861 			return res2;
2862 	}
2863 
2864 	return res;
2865 }
2866 
2867 static void tee_svc_asymm_pkcs1_get_salt_len(const TEE_Attribute *params,
2868 					     uint32_t num_params, int *salt_len)
2869 {
2870 	size_t n;
2871 
2872 	for (n = 0; n < num_params; n++) {
2873 		if (params[n].attributeID == TEE_ATTR_RSA_PSS_SALT_LENGTH) {
2874 			*salt_len = params[n].content.value.a;
2875 			return;
2876 		}
2877 	}
2878 	*salt_len = -1;
2879 }
2880 
2881 TEE_Result tee_svc_asymm_operate(uint32_t state,
2882 			const struct abi_user32_attribute *usr_params,
2883 			uint32_t num_params, const void *src_data,
2884 			size_t src_len, void *dst_data, uint32_t *dst_len)
2885 {
2886 	TEE_Result res;
2887 	struct tee_cryp_state *cs;
2888 	struct tee_ta_session *sess;
2889 	uint32_t dlen32;
2890 	size_t dlen;
2891 	struct tee_obj *o;
2892 	void *label = NULL;
2893 	size_t label_len = 0;
2894 	size_t n;
2895 	int salt_len;
2896 	TEE_Attribute *params = NULL;
2897 
2898 	res = tee_ta_get_current_session(&sess);
2899 	if (res != TEE_SUCCESS)
2900 		return res;
2901 
2902 	res = tee_svc_cryp_get_state(sess, state, &cs);
2903 	if (res != TEE_SUCCESS)
2904 		return res;
2905 
2906 	res = tee_mmu_check_access_rights(
2907 		sess->ctx,
2908 		TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER,
2909 		(tee_uaddr_t) src_data, src_len);
2910 	if (res != TEE_SUCCESS)
2911 		return res;
2912 
2913 	res = tee_svc_copy_from_user(sess, &dlen32, dst_len, sizeof(uint32_t));
2914 	if (res != TEE_SUCCESS)
2915 		return res;
2916 	dlen = dlen32;
2917 
2918 	res = tee_mmu_check_access_rights(
2919 		sess->ctx,
2920 		TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE |
2921 			TEE_MEMORY_ACCESS_ANY_OWNER,
2922 		(tee_uaddr_t) dst_data, dlen);
2923 	if (res != TEE_SUCCESS)
2924 		return res;
2925 
2926 	params = malloc(sizeof(TEE_Attribute) * num_params);
2927 	if (!params)
2928 		return TEE_ERROR_OUT_OF_MEMORY;
2929 	res = copy_in_attrs(sess->ctx, usr_params, num_params, params);
2930 	if (res != TEE_SUCCESS)
2931 		goto out;
2932 
2933 	res = tee_obj_get(sess->ctx, cs->key1, &o);
2934 	if (res != TEE_SUCCESS)
2935 		goto out;
2936 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
2937 		res = TEE_ERROR_GENERIC;
2938 		goto out;
2939 	}
2940 
2941 	switch (cs->algo) {
2942 	case TEE_ALG_RSA_NOPAD:
2943 		if (cs->mode == TEE_MODE_ENCRYPT) {
2944 			if (crypto_ops.acipher.rsanopad_encrypt)
2945 				res = crypto_ops.acipher.rsanopad_encrypt(
2946 					o->data, src_data, src_len,
2947 					dst_data, &dlen);
2948 			else
2949 				res = TEE_ERROR_NOT_IMPLEMENTED;
2950 		} else if (cs->mode == TEE_MODE_DECRYPT) {
2951 			if (crypto_ops.acipher.rsanopad_decrypt)
2952 				res = crypto_ops.acipher.rsanopad_decrypt(
2953 					o->data, src_data, src_len, dst_data,
2954 					&dlen);
2955 			else
2956 				res = TEE_ERROR_NOT_IMPLEMENTED;
2957 		} else {
2958 			/*
2959 			 * We will panic because "the mode is not compatible
2960 			 * with the function"
2961 			 */
2962 			res = TEE_ERROR_GENERIC;
2963 		}
2964 		break;
2965 
2966 	case TEE_ALG_RSAES_PKCS1_V1_5:
2967 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
2968 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
2969 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
2970 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
2971 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
2972 		for (n = 0; n < num_params; n++) {
2973 			if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) {
2974 				label = params[n].content.ref.buffer;
2975 				label_len = params[n].content.ref.length;
2976 				break;
2977 			}
2978 		}
2979 
2980 		if (cs->mode == TEE_MODE_ENCRYPT) {
2981 			if (crypto_ops.acipher.rsaes_encrypt)
2982 				res = crypto_ops.acipher.rsaes_encrypt(
2983 					cs->algo, o->data, label, label_len,
2984 					src_data, src_len, dst_data, &dlen);
2985 			else
2986 				res = TEE_ERROR_NOT_IMPLEMENTED;
2987 		} else if (cs->mode == TEE_MODE_DECRYPT) {
2988 			if (crypto_ops.acipher.rsaes_decrypt)
2989 				res = crypto_ops.acipher.rsaes_decrypt(
2990 					cs->algo, o->data,
2991 					label, label_len,
2992 					src_data, src_len, dst_data, &dlen);
2993 			else
2994 				res = TEE_ERROR_NOT_IMPLEMENTED;
2995 		} else {
2996 			res = TEE_ERROR_BAD_PARAMETERS;
2997 		}
2998 		break;
2999 
3000 	case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
3001 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
3002 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
3003 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
3004 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
3005 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
3006 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
3007 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
3008 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
3009 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
3010 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
3011 		if (cs->mode != TEE_MODE_SIGN) {
3012 			res = TEE_ERROR_BAD_PARAMETERS;
3013 			break;
3014 		}
3015 		tee_svc_asymm_pkcs1_get_salt_len(params, num_params, &salt_len);
3016 
3017 		if (!crypto_ops.acipher.rsassa_sign) {
3018 			res = TEE_ERROR_NOT_IMPLEMENTED;
3019 			break;
3020 		}
3021 		res = crypto_ops.acipher.rsassa_sign(cs->algo, o->data,
3022 						     salt_len, src_data,
3023 						     src_len, dst_data, &dlen);
3024 		break;
3025 
3026 	case TEE_ALG_DSA_SHA1:
3027 		if (!crypto_ops.acipher.dsa_sign) {
3028 			res = TEE_ERROR_NOT_IMPLEMENTED;
3029 			break;
3030 		}
3031 		res = crypto_ops.acipher.dsa_sign(cs->algo, o->data, src_data,
3032 						  src_len, dst_data, &dlen);
3033 		break;
3034 
3035 	default:
3036 		res = TEE_ERROR_BAD_PARAMETERS;
3037 		break;
3038 	}
3039 
3040 out:
3041 	free(params);
3042 
3043 	if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
3044 		TEE_Result res2;
3045 
3046 		dlen32 = dlen;
3047 		res2 = tee_svc_copy_to_user(sess, dst_len, &dlen,
3048 					    sizeof(uint32_t));
3049 		if (res2 != TEE_SUCCESS)
3050 			return res2;
3051 	}
3052 
3053 	return res;
3054 }
3055 
3056 TEE_Result tee_svc_asymm_verify(uint32_t state,
3057 			const struct abi_user32_attribute *usr_params,
3058 			uint32_t num_params, const void *data,
3059 			size_t data_len, const void *sig, size_t sig_len)
3060 {
3061 	TEE_Result res;
3062 	struct tee_cryp_state *cs;
3063 	struct tee_ta_session *sess;
3064 	struct tee_obj *o;
3065 	size_t hash_size;
3066 	int salt_len;
3067 	TEE_Attribute *params = NULL;
3068 
3069 	res = tee_ta_get_current_session(&sess);
3070 	if (res != TEE_SUCCESS)
3071 		return res;
3072 
3073 	res = tee_svc_cryp_get_state(sess, state, &cs);
3074 	if (res != TEE_SUCCESS)
3075 		return res;
3076 
3077 	if (cs->mode != TEE_MODE_VERIFY)
3078 		return TEE_ERROR_BAD_PARAMETERS;
3079 
3080 	res = tee_mmu_check_access_rights(sess->ctx,
3081 					  TEE_MEMORY_ACCESS_READ |
3082 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3083 					  (tee_uaddr_t)data, data_len);
3084 	if (res != TEE_SUCCESS)
3085 		return res;
3086 
3087 	res = tee_mmu_check_access_rights(sess->ctx,
3088 					  TEE_MEMORY_ACCESS_READ |
3089 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3090 					  (tee_uaddr_t)sig, sig_len);
3091 	if (res != TEE_SUCCESS)
3092 		return res;
3093 
3094 	params = malloc(sizeof(TEE_Attribute) * num_params);
3095 	if (!params)
3096 		return TEE_ERROR_OUT_OF_MEMORY;
3097 	res = copy_in_attrs(sess->ctx, usr_params, num_params, params);
3098 	if (res != TEE_SUCCESS)
3099 		goto out;
3100 
3101 	res = tee_obj_get(sess->ctx, cs->key1, &o);
3102 	if (res != TEE_SUCCESS)
3103 		goto out;
3104 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
3105 		res = TEE_ERROR_BAD_PARAMETERS;
3106 		goto out;
3107 	}
3108 
3109 	res = tee_hash_get_digest_size(TEE_DIGEST_HASH_TO_ALGO(cs->algo),
3110 				       &hash_size);
3111 	if (res != TEE_SUCCESS)
3112 		goto out;
3113 
3114 	if (data_len != hash_size) {
3115 		res = TEE_ERROR_BAD_PARAMETERS;
3116 		goto out;
3117 	}
3118 
3119 	switch (TEE_ALG_GET_MAIN_ALG(cs->algo)) {
3120 	case TEE_MAIN_ALGO_RSA:
3121 		tee_svc_asymm_pkcs1_get_salt_len(params, num_params, &salt_len);
3122 		if (!crypto_ops.acipher.rsassa_verify) {
3123 			res = TEE_ERROR_NOT_IMPLEMENTED;
3124 			break;
3125 		}
3126 		res = crypto_ops.acipher.rsassa_verify(cs->algo, o->data,
3127 						       salt_len, data,
3128 						       data_len, sig, sig_len);
3129 		break;
3130 
3131 	case TEE_MAIN_ALGO_DSA:
3132 		if (!crypto_ops.acipher.dsa_verify) {
3133 			res = TEE_ERROR_NOT_IMPLEMENTED;
3134 			break;
3135 		}
3136 		res = crypto_ops.acipher.dsa_verify(cs->algo, o->data, data,
3137 						    data_len, sig, sig_len);
3138 		break;
3139 
3140 	default:
3141 		res = TEE_ERROR_NOT_SUPPORTED;
3142 	}
3143 
3144 out:
3145 	free(params);
3146 	return res;
3147 }
3148