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