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