xref: /optee_os/core/tee/tee_svc_cryp.c (revision 9977404eea543dc76241d8da3a29ff140759f5c0)
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_kaddr_to_user32(sess, obj, 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 	uint16_t conv_func;
1305 
1306 	for (n = 0; n < attr_count; n++) {
1307 		idx = tee_svc_cryp_obj_find_type_attr_idx(
1308 							attrs[n].attributeID,
1309 							type_props);
1310 		/* attribute not defined in current object type */
1311 		if (idx < 0)
1312 			return TEE_ERROR_ITEM_NOT_FOUND;
1313 
1314 		conv_func = type_props->type_attrs[idx].conv_func;
1315 
1316 		/* attribute bigger than maximum object size */
1317 		if (conv_func != TEE_TYPE_CONV_FUNC_VALUE &&
1318 		    o->info.maxKeySize < attrs[n].content.ref.length)
1319 			return TEE_ERROR_OUT_OF_MEMORY;
1320 
1321 		have_attrs |= 1 << idx;
1322 
1323 		res = tee_svc_cryp_obj_get_raw_data(o, type_props, idx,
1324 						    &raw_data, &raw_size);
1325 		if (res != TEE_SUCCESS)
1326 			return res;
1327 
1328 		res = tee_svc_cryp_obj_store_attr_raw(conv_func, attrs + n,
1329 						      raw_data, raw_size);
1330 		if (res != TEE_SUCCESS)
1331 			return res;
1332 
1333 		/*
1334 		 * First attr_idx signifies the attribute that gives the size
1335 		 * of the object
1336 		 */
1337 		if (type_props->type_attrs[idx].flags &
1338 		    TEE_TYPE_ATTR_SIZE_INDICATOR)
1339 			obj_size += attrs[n].content.ref.length * 8;
1340 	}
1341 
1342 	/*
1343 	 * We have to do it like this because the parity bits aren't counted
1344 	 * when telling the size of the key in bits.
1345 	 */
1346 	if (o->info.objectType == TEE_TYPE_DES ||
1347 	    o->info.objectType == TEE_TYPE_DES3)
1348 		obj_size -= obj_size / 8; /* Exclude parity in size of key */
1349 
1350 	o->have_attrs = have_attrs;
1351 	o->info.keySize = obj_size;
1352 
1353 	return TEE_SUCCESS;
1354 }
1355 
1356 TEE_Result tee_svc_cryp_obj_populate(uint32_t obj,
1357 		struct abi_user32_attribute *usr_attrs, uint32_t attr_count)
1358 {
1359 	TEE_Result res;
1360 	struct tee_ta_session *sess;
1361 	struct tee_obj *o;
1362 	const struct tee_cryp_obj_type_props *type_props;
1363 	TEE_Attribute *attrs = NULL;
1364 
1365 	res = tee_ta_get_current_session(&sess);
1366 	if (res != TEE_SUCCESS)
1367 		return res;
1368 
1369 	res = tee_obj_get(sess->ctx, obj, &o);
1370 	if (res != TEE_SUCCESS)
1371 		return res;
1372 
1373 	/* Must be a transient object */
1374 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
1375 		return TEE_ERROR_BAD_PARAMETERS;
1376 
1377 	/* Must not be initialized already */
1378 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
1379 		return TEE_ERROR_BAD_PARAMETERS;
1380 
1381 	type_props = tee_svc_find_type_props(o->info.objectType);
1382 	if (!type_props)
1383 		return TEE_ERROR_NOT_IMPLEMENTED;
1384 
1385 	attrs = malloc(sizeof(TEE_Attribute) * attr_count);
1386 	if (!attrs)
1387 		return TEE_ERROR_OUT_OF_MEMORY;
1388 	res = copy_in_attrs(sess->ctx, usr_attrs, attr_count, attrs);
1389 	if (res != TEE_SUCCESS)
1390 		goto out;
1391 
1392 	res = tee_svc_cryp_check_attr(ATTR_USAGE_POPULATE, type_props,
1393 				      attrs, attr_count);
1394 	if (res != TEE_SUCCESS)
1395 		goto out;
1396 
1397 	res = tee_svc_cryp_obj_populate_type(o, type_props, attrs, attr_count);
1398 	if (res == TEE_SUCCESS)
1399 		o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
1400 
1401 out:
1402 	free(attrs);
1403 	return res;
1404 }
1405 
1406 TEE_Result tee_svc_cryp_obj_copy(uint32_t dst, uint32_t src)
1407 {
1408 	TEE_Result res;
1409 	struct tee_ta_session *sess;
1410 	struct tee_obj *dst_o;
1411 	struct tee_obj *src_o;
1412 
1413 	res = tee_ta_get_current_session(&sess);
1414 	if (res != TEE_SUCCESS)
1415 		return res;
1416 
1417 	res = tee_obj_get(sess->ctx, dst, &dst_o);
1418 	if (res != TEE_SUCCESS)
1419 		return res;
1420 
1421 	res = tee_obj_get(sess->ctx, src, &src_o);
1422 	if (res != TEE_SUCCESS)
1423 		return res;
1424 
1425 	if ((src_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
1426 		return TEE_ERROR_BAD_PARAMETERS;
1427 	if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
1428 		return TEE_ERROR_BAD_PARAMETERS;
1429 	if ((dst_o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
1430 		return TEE_ERROR_BAD_PARAMETERS;
1431 
1432 	if (dst_o->info.objectType == src_o->info.objectType) {
1433 		/* Copy whole data */
1434 
1435 		if (dst_o->data_size != src_o->data_size)
1436 			return TEE_ERROR_BAD_STATE;
1437 		if (dst_o->cleanup != src_o->cleanup)
1438 			return TEE_ERROR_BAD_STATE;
1439 
1440 		dst_o->have_attrs = src_o->have_attrs;
1441 
1442 		switch (src_o->info.objectType) {
1443 		case TEE_TYPE_RSA_PUBLIC_KEY:
1444 			copy_rsa_public_key(dst_o->data, src_o->data);
1445 			break;
1446 		case TEE_TYPE_RSA_KEYPAIR:
1447 			copy_rsa_keypair(dst_o->data, src_o->data);
1448 			break;
1449 		case TEE_TYPE_DSA_PUBLIC_KEY:
1450 			copy_dsa_public_key(dst_o->data, src_o->data);
1451 			break;
1452 		case TEE_TYPE_DSA_KEYPAIR:
1453 			copy_dsa_keypair(dst_o->data, src_o->data);
1454 			break;
1455 		case TEE_TYPE_DH_KEYPAIR:
1456 			copy_dh_keypair(dst_o->data, src_o->data);
1457 			break;
1458 		case TEE_TYPE_ECDSA_PUBLIC_KEY:
1459 		case TEE_TYPE_ECDH_PUBLIC_KEY:
1460 			copy_ecc_public_key(dst_o->data, src_o->data);
1461 			break;
1462 		case TEE_TYPE_ECDSA_KEYPAIR:
1463 		case TEE_TYPE_ECDH_KEYPAIR:
1464 			copy_ecc_keypair(dst_o->data, src_o->data);
1465 			break;
1466 		default:
1467 			/* Generic case */
1468 			memcpy(dst_o->data, src_o->data, src_o->data_size);
1469 		}
1470 	} else if (dst_o->info.objectType == TEE_TYPE_RSA_PUBLIC_KEY &&
1471 		   src_o->info.objectType == TEE_TYPE_RSA_KEYPAIR) {
1472 		/* Extract public key from RSA key pair */
1473 		size_t n;
1474 
1475 		extract_rsa_public_key(dst_o->data, src_o->data);
1476 		dst_o->have_attrs = 0;
1477 		for (n = 0; n < TEE_ARRAY_SIZE(tee_cryp_obj_rsa_pub_key_attrs);
1478 		     n++)
1479 			dst_o->have_attrs |= 1 << n;
1480 
1481 	} else if (dst_o->info.objectType == TEE_TYPE_DSA_PUBLIC_KEY &&
1482 		   src_o->info.objectType == TEE_TYPE_DSA_KEYPAIR) {
1483 		/* Extract public key from DSA key pair */
1484 		size_t n;
1485 
1486 		extract_dsa_public_key(dst_o->data, src_o->data);
1487 		dst_o->have_attrs = 0;
1488 		for (n = 0; n < TEE_ARRAY_SIZE(tee_cryp_obj_dsa_pub_key_attrs);
1489 		     n++)
1490 			dst_o->have_attrs |= 1 << n;
1491 
1492 	} else if ((dst_o->info.objectType == TEE_TYPE_ECDSA_PUBLIC_KEY &&
1493 		    src_o->info.objectType == TEE_TYPE_ECDSA_KEYPAIR) ||
1494 		   (dst_o->info.objectType == TEE_TYPE_ECDH_PUBLIC_KEY &&
1495 		    src_o->info.objectType == TEE_TYPE_ECDH_KEYPAIR)) {
1496 		/* Extract public key from ECC key pair */
1497 		size_t n;
1498 
1499 		extract_ecc_public_key(dst_o->data, src_o->data);
1500 		dst_o->have_attrs = 0;
1501 		for (n = 0; n < TEE_ARRAY_SIZE(tee_cryp_obj_ecc_pub_key_attrs);
1502 		     n++)
1503 			dst_o->have_attrs |= 1 << n;
1504 
1505 	} else {
1506 		return TEE_ERROR_BAD_PARAMETERS;
1507 	}
1508 
1509 	dst_o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
1510 	dst_o->info.keySize = src_o->info.keySize;
1511 	dst_o->info.objectUsage = src_o->info.objectUsage;
1512 	return TEE_SUCCESS;
1513 }
1514 
1515 static TEE_Result tee_svc_obj_generate_key_rsa(
1516 	struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
1517 	uint32_t key_size,
1518 	const TEE_Attribute *params, uint32_t param_count)
1519 {
1520 	TEE_Result res;
1521 	struct rsa_keypair *key = o->data;
1522 	uint32_t e = TEE_U32_TO_BIG_ENDIAN(65537);
1523 
1524 	TEE_ASSERT(sizeof(struct rsa_keypair) == o->data_size);
1525 	if (!crypto_ops.acipher.gen_rsa_key || !crypto_ops.bignum.bin2bn)
1526 		return TEE_ERROR_NOT_IMPLEMENTED;
1527 
1528 	/* Copy the present attributes into the obj before starting */
1529 	res = tee_svc_cryp_obj_populate_type(o, type_props, params,
1530 					     param_count);
1531 	if (res != TEE_SUCCESS)
1532 		return res;
1533 	if (!GET_ATTRIBUTE(o, type_props, TEE_ATTR_RSA_PUBLIC_EXPONENT))
1534 		crypto_ops.bignum.bin2bn((const uint8_t *)&e, sizeof(e),
1535 					 key->e);
1536 	res = crypto_ops.acipher.gen_rsa_key(o->data, key_size);
1537 	if (res != TEE_SUCCESS)
1538 		return res;
1539 
1540 	/* Set bits for all known attributes for this object type */
1541 	o->have_attrs = (1 << type_props->num_type_attrs) - 1;
1542 
1543 	return TEE_SUCCESS;
1544 }
1545 
1546 static TEE_Result tee_svc_obj_generate_key_dsa(
1547 	struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
1548 	uint32_t key_size)
1549 {
1550 	TEE_Result res;
1551 
1552 	TEE_ASSERT(sizeof(struct dsa_keypair) == o->data_size);
1553 	if (!crypto_ops.acipher.gen_dsa_key)
1554 		return TEE_ERROR_NOT_IMPLEMENTED;
1555 	res = crypto_ops.acipher.gen_dsa_key(o->data, key_size);
1556 	if (res != TEE_SUCCESS)
1557 		return res;
1558 
1559 	/* Set bits for all known attributes for this object type */
1560 	o->have_attrs = (1 << type_props->num_type_attrs) - 1;
1561 
1562 	return TEE_SUCCESS;
1563 }
1564 
1565 static TEE_Result tee_svc_obj_generate_key_dh(
1566 	struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
1567 	uint32_t key_size __unused,
1568 	const TEE_Attribute *params, uint32_t param_count)
1569 {
1570 	TEE_Result res;
1571 	struct dh_keypair *tee_dh_key;
1572 	struct bignum *dh_q = NULL;
1573 	uint32_t dh_xbits = 0;
1574 
1575 	TEE_ASSERT(sizeof(struct dh_keypair) == o->data_size);
1576 
1577 	/* Copy the present attributes into the obj before starting */
1578 	res = tee_svc_cryp_obj_populate_type(o, type_props, params,
1579 					     param_count);
1580 	if (res != TEE_SUCCESS)
1581 		return res;
1582 
1583 	tee_dh_key = (struct dh_keypair *)o->data;
1584 
1585 	if (GET_ATTRIBUTE(o, type_props, TEE_ATTR_DH_SUBPRIME))
1586 		dh_q = tee_dh_key->q;
1587 	if (GET_ATTRIBUTE(o, type_props, TEE_ATTR_DH_X_BITS))
1588 		dh_xbits = tee_dh_key->xbits;
1589 	if (!crypto_ops.acipher.gen_dh_key)
1590 		return TEE_ERROR_NOT_IMPLEMENTED;
1591 	res = crypto_ops.acipher.gen_dh_key(tee_dh_key, dh_q, dh_xbits);
1592 	if (res != TEE_SUCCESS)
1593 		return res;
1594 
1595 	/* Set bits for the generated public and private key */
1596 	SET_ATTRIBUTE(o, type_props, TEE_ATTR_DH_PUBLIC_VALUE);
1597 	SET_ATTRIBUTE(o, type_props, TEE_ATTR_DH_PRIVATE_VALUE);
1598 	SET_ATTRIBUTE(o, type_props, TEE_ATTR_DH_X_BITS);
1599 	return TEE_SUCCESS;
1600 }
1601 
1602 static TEE_Result tee_svc_obj_generate_key_ecc(
1603 	struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
1604 	uint32_t key_size __unused,
1605 	const TEE_Attribute *params, uint32_t param_count)
1606 {
1607 	TEE_Result res;
1608 	struct ecc_keypair *tee_ecc_key;
1609 
1610 	TEE_ASSERT(sizeof(struct ecc_keypair) == o->data_size);
1611 
1612 	/* Copy the present attributes into the obj before starting */
1613 	res = tee_svc_cryp_obj_populate_type(o, type_props, params,
1614 					     param_count);
1615 	if (res != TEE_SUCCESS)
1616 		return res;
1617 
1618 	tee_ecc_key = (struct ecc_keypair *)o->data;
1619 
1620 	if (!crypto_ops.acipher.gen_ecc_key)
1621 		return TEE_ERROR_NOT_IMPLEMENTED;
1622 	res = crypto_ops.acipher.gen_ecc_key(tee_ecc_key);
1623 	if (res != TEE_SUCCESS)
1624 		return res;
1625 
1626 	/* Set bits for the generated public and private key */
1627 	SET_ATTRIBUTE(o, type_props, TEE_ATTR_ECC_PRIVATE_VALUE);
1628 	SET_ATTRIBUTE(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_X);
1629 	SET_ATTRIBUTE(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_Y);
1630 	SET_ATTRIBUTE(o, type_props, TEE_ATTR_ECC_CURVE);
1631 	return TEE_SUCCESS;
1632 }
1633 
1634 TEE_Result tee_svc_obj_generate_key(uint32_t obj, uint32_t key_size,
1635 			const struct abi_user32_attribute *usr_params,
1636 			uint32_t param_count)
1637 {
1638 	TEE_Result res;
1639 	struct tee_ta_session *sess;
1640 	const struct tee_cryp_obj_type_props *type_props;
1641 	struct tee_obj *o;
1642 	struct tee_cryp_obj_secret *key;
1643 	size_t byte_size;
1644 	TEE_Attribute *params = NULL;
1645 
1646 	res = tee_ta_get_current_session(&sess);
1647 	if (res != TEE_SUCCESS)
1648 		return res;
1649 
1650 	res = tee_obj_get(sess->ctx, obj, &o);
1651 	if (res != TEE_SUCCESS)
1652 		return res;
1653 
1654 	/* Must be a transient object */
1655 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
1656 		return TEE_ERROR_BAD_STATE;
1657 
1658 	/* Must not be initialized already */
1659 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
1660 		return TEE_ERROR_BAD_STATE;
1661 
1662 	/* Find description of object */
1663 	type_props = tee_svc_find_type_props(o->info.objectType);
1664 	if (!type_props)
1665 		return TEE_ERROR_NOT_SUPPORTED;
1666 
1667 	/* Check that maxKeySize follows restrictions */
1668 	if (key_size % type_props->quanta != 0)
1669 		return TEE_ERROR_NOT_SUPPORTED;
1670 	if (key_size < type_props->min_size)
1671 		return TEE_ERROR_NOT_SUPPORTED;
1672 	if (key_size > type_props->max_size)
1673 		return TEE_ERROR_NOT_SUPPORTED;
1674 
1675 	params = malloc(sizeof(TEE_Attribute) * param_count);
1676 	if (!params)
1677 		return TEE_ERROR_OUT_OF_MEMORY;
1678 	res = copy_in_attrs(sess->ctx, usr_params, param_count, params);
1679 	if (res != TEE_SUCCESS)
1680 		goto out;
1681 
1682 	res = tee_svc_cryp_check_attr(ATTR_USAGE_GENERATE_KEY, type_props,
1683 				      params, param_count);
1684 	if (res != TEE_SUCCESS)
1685 		goto out;
1686 
1687 	switch (o->info.objectType) {
1688 	case TEE_TYPE_AES:
1689 	case TEE_TYPE_DES:
1690 	case TEE_TYPE_DES3:
1691 	case TEE_TYPE_HMAC_MD5:
1692 	case TEE_TYPE_HMAC_SHA1:
1693 	case TEE_TYPE_HMAC_SHA224:
1694 	case TEE_TYPE_HMAC_SHA256:
1695 	case TEE_TYPE_HMAC_SHA384:
1696 	case TEE_TYPE_HMAC_SHA512:
1697 	case TEE_TYPE_GENERIC_SECRET:
1698 		byte_size = key_size / 8;
1699 
1700 		/*
1701 		 * We have to do it like this because the parity bits aren't
1702 		 * counted when telling the size of the key in bits.
1703 		 */
1704 		if (o->info.objectType == TEE_TYPE_DES ||
1705 		    o->info.objectType == TEE_TYPE_DES3) {
1706 			byte_size = (key_size + key_size / 7) / 8;
1707 		}
1708 
1709 		key = (struct tee_cryp_obj_secret *)o->data;
1710 		if (byte_size > (o->data_size - sizeof(*key))) {
1711 			res = TEE_ERROR_EXCESS_DATA;
1712 			goto out;
1713 		}
1714 
1715 		res = crypto_ops.prng.read((void *)(key + 1), byte_size);
1716 		if (res != TEE_SUCCESS)
1717 			goto out;
1718 
1719 		key->key_size = byte_size;
1720 
1721 		/* Set bits for all known attributes for this object type */
1722 		o->have_attrs = (1 << type_props->num_type_attrs) - 1;
1723 
1724 		break;
1725 
1726 	case TEE_TYPE_RSA_KEYPAIR:
1727 		res = tee_svc_obj_generate_key_rsa(o, type_props, key_size,
1728 						   params, param_count);
1729 		if (res != TEE_SUCCESS)
1730 			goto out;
1731 		break;
1732 
1733 	case TEE_TYPE_DSA_KEYPAIR:
1734 		res = tee_svc_obj_generate_key_dsa(o, type_props, key_size);
1735 		if (res != TEE_SUCCESS)
1736 			goto out;
1737 		break;
1738 
1739 	case TEE_TYPE_DH_KEYPAIR:
1740 		res = tee_svc_obj_generate_key_dh(o, type_props, key_size,
1741 						  params, param_count);
1742 		if (res != TEE_SUCCESS)
1743 			goto out;
1744 		break;
1745 
1746 	case TEE_TYPE_ECDSA_KEYPAIR:
1747 	case TEE_TYPE_ECDH_KEYPAIR:
1748 		res = tee_svc_obj_generate_key_ecc(o, type_props, key_size,
1749 						  params, param_count);
1750 		if (res != TEE_SUCCESS)
1751 			goto out;
1752 		break;
1753 
1754 	default:
1755 		res = TEE_ERROR_BAD_FORMAT;
1756 	}
1757 
1758 out:
1759 	free(params);
1760 	if (res == TEE_SUCCESS) {
1761 		o->info.keySize = key_size;
1762 		o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
1763 	}
1764 	return res;
1765 }
1766 
1767 static TEE_Result tee_svc_cryp_get_state(struct tee_ta_session *sess,
1768 					 uint32_t state_id,
1769 					 struct tee_cryp_state **state)
1770 {
1771 	struct tee_cryp_state *s;
1772 
1773 	TAILQ_FOREACH(s, &sess->ctx->cryp_states, link) {
1774 		if (state_id == (vaddr_t)s) {
1775 			*state = s;
1776 			return TEE_SUCCESS;
1777 		}
1778 	}
1779 	return TEE_ERROR_BAD_PARAMETERS;
1780 }
1781 
1782 static void cryp_state_free(struct tee_ta_ctx *ctx, struct tee_cryp_state *cs)
1783 {
1784 	struct tee_obj *o;
1785 
1786 	if (tee_obj_get(ctx, cs->key1, &o) == TEE_SUCCESS)
1787 		tee_obj_close(ctx, o);
1788 	if (tee_obj_get(ctx, cs->key2, &o) == TEE_SUCCESS)
1789 		tee_obj_close(ctx, o);
1790 
1791 	TAILQ_REMOVE(&ctx->cryp_states, cs, link);
1792 	if (cs->ctx_finalize != NULL)
1793 		cs->ctx_finalize(cs->ctx, cs->algo);
1794 	free(cs->ctx);
1795 	free(cs);
1796 }
1797 
1798 static TEE_Result tee_svc_cryp_check_key_type(const struct tee_obj *o,
1799 					      uint32_t algo,
1800 					      TEE_OperationMode mode)
1801 {
1802 	uint32_t req_key_type;
1803 
1804 	switch (TEE_ALG_GET_MAIN_ALG(algo)) {
1805 	case TEE_MAIN_ALGO_MD5:
1806 		req_key_type = TEE_TYPE_HMAC_MD5;
1807 		break;
1808 	case TEE_MAIN_ALGO_SHA1:
1809 		req_key_type = TEE_TYPE_HMAC_SHA1;
1810 		break;
1811 	case TEE_MAIN_ALGO_SHA224:
1812 		req_key_type = TEE_TYPE_HMAC_SHA224;
1813 		break;
1814 	case TEE_MAIN_ALGO_SHA256:
1815 		req_key_type = TEE_TYPE_HMAC_SHA256;
1816 		break;
1817 	case TEE_MAIN_ALGO_SHA384:
1818 		req_key_type = TEE_TYPE_HMAC_SHA384;
1819 		break;
1820 	case TEE_MAIN_ALGO_SHA512:
1821 		req_key_type = TEE_TYPE_HMAC_SHA512;
1822 		break;
1823 	case TEE_MAIN_ALGO_AES:
1824 		req_key_type = TEE_TYPE_AES;
1825 		break;
1826 	case TEE_MAIN_ALGO_DES:
1827 		req_key_type = TEE_TYPE_DES;
1828 		break;
1829 	case TEE_MAIN_ALGO_DES3:
1830 		req_key_type = TEE_TYPE_DES3;
1831 		break;
1832 	case TEE_MAIN_ALGO_RSA:
1833 		if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY)
1834 			req_key_type = TEE_TYPE_RSA_PUBLIC_KEY;
1835 		else
1836 			req_key_type = TEE_TYPE_RSA_KEYPAIR;
1837 		break;
1838 	case TEE_MAIN_ALGO_DSA:
1839 		if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY)
1840 			req_key_type = TEE_TYPE_DSA_PUBLIC_KEY;
1841 		else
1842 			req_key_type = TEE_TYPE_DSA_KEYPAIR;
1843 		break;
1844 	case TEE_MAIN_ALGO_DH:
1845 		req_key_type = TEE_TYPE_DH_KEYPAIR;
1846 		break;
1847 #if defined(CFG_CRYPTO_HKDF)
1848 	case TEE_MAIN_ALGO_HKDF:
1849 		req_key_type = TEE_TYPE_HKDF_IKM;
1850 		break;
1851 #endif
1852 #if defined(CFG_CRYPTO_CONCAT_KDF)
1853 	case TEE_MAIN_ALGO_CONCAT_KDF:
1854 		req_key_type = TEE_TYPE_CONCAT_KDF_Z;
1855 		break;
1856 #endif
1857 #if defined(CFG_CRYPTO_PBKDF2)
1858 	case TEE_MAIN_ALGO_PBKDF2:
1859 		req_key_type = TEE_TYPE_PBKDF2_PASSWORD;
1860 		break;
1861 #endif
1862 	default:
1863 		return TEE_ERROR_BAD_PARAMETERS;
1864 	}
1865 
1866 	if (req_key_type != o->info.objectType)
1867 		return TEE_ERROR_BAD_PARAMETERS;
1868 	return TEE_SUCCESS;
1869 }
1870 
1871 TEE_Result tee_svc_cryp_state_alloc(uint32_t algo, uint32_t mode,
1872 				    uint32_t key1, uint32_t key2,
1873 				    uint32_t *state)
1874 {
1875 	TEE_Result res;
1876 	struct tee_cryp_state *cs;
1877 	struct tee_ta_session *sess;
1878 	struct tee_obj *o1 = NULL;
1879 	struct tee_obj *o2 = NULL;
1880 
1881 	res = tee_ta_get_current_session(&sess);
1882 	if (res != TEE_SUCCESS)
1883 		return res;
1884 
1885 	if (key1 != 0) {
1886 		res = tee_obj_get(sess->ctx, key1, &o1);
1887 		if (res != TEE_SUCCESS)
1888 			return res;
1889 		if (o1->busy)
1890 			return TEE_ERROR_BAD_PARAMETERS;
1891 		res = tee_svc_cryp_check_key_type(o1, algo, mode);
1892 		if (res != TEE_SUCCESS)
1893 			return res;
1894 	}
1895 	if (key2 != 0) {
1896 		res = tee_obj_get(sess->ctx, key2, &o2);
1897 		if (res != TEE_SUCCESS)
1898 			return res;
1899 		if (o2->busy)
1900 			return TEE_ERROR_BAD_PARAMETERS;
1901 		res = tee_svc_cryp_check_key_type(o2, algo, mode);
1902 		if (res != TEE_SUCCESS)
1903 			return res;
1904 	}
1905 
1906 	cs = calloc(1, sizeof(struct tee_cryp_state));
1907 	if (!cs)
1908 		return TEE_ERROR_OUT_OF_MEMORY;
1909 	TAILQ_INSERT_TAIL(&sess->ctx->cryp_states, cs, link);
1910 	cs->algo = algo;
1911 	cs->mode = mode;
1912 
1913 	switch (TEE_ALG_GET_CLASS(algo)) {
1914 	case TEE_OPERATION_CIPHER:
1915 		if ((algo == TEE_ALG_AES_XTS && (key1 == 0 || key2 == 0)) ||
1916 		    (algo != TEE_ALG_AES_XTS && (key1 == 0 || key2 != 0))) {
1917 			res = TEE_ERROR_BAD_PARAMETERS;
1918 		} else {
1919 			if (crypto_ops.cipher.get_ctx_size)
1920 				res = crypto_ops.cipher.get_ctx_size(algo,
1921 								&cs->ctx_size);
1922 			else
1923 				res = TEE_ERROR_NOT_IMPLEMENTED;
1924 			if (res != TEE_SUCCESS)
1925 				break;
1926 			cs->ctx = calloc(1, cs->ctx_size);
1927 			if (!cs->ctx)
1928 				res = TEE_ERROR_OUT_OF_MEMORY;
1929 		}
1930 		break;
1931 	case TEE_OPERATION_AE:
1932 		if (key1 == 0 || key2 != 0) {
1933 			res = TEE_ERROR_BAD_PARAMETERS;
1934 		} else {
1935 			if (crypto_ops.authenc.get_ctx_size)
1936 				res = crypto_ops.authenc.get_ctx_size(algo,
1937 								&cs->ctx_size);
1938 			else
1939 				res = TEE_ERROR_NOT_IMPLEMENTED;
1940 			if (res != TEE_SUCCESS)
1941 				break;
1942 			cs->ctx = calloc(1, cs->ctx_size);
1943 			if (!cs->ctx)
1944 				res = TEE_ERROR_OUT_OF_MEMORY;
1945 		}
1946 		break;
1947 	case TEE_OPERATION_MAC:
1948 		if (key1 == 0 || key2 != 0) {
1949 			res = TEE_ERROR_BAD_PARAMETERS;
1950 		} else {
1951 			if (crypto_ops.mac.get_ctx_size)
1952 				res = crypto_ops.mac.get_ctx_size(algo,
1953 								&cs->ctx_size);
1954 			else
1955 				res = TEE_ERROR_NOT_IMPLEMENTED;
1956 			if (res != TEE_SUCCESS)
1957 				break;
1958 			cs->ctx = calloc(1, cs->ctx_size);
1959 			if (!cs->ctx)
1960 				res = TEE_ERROR_OUT_OF_MEMORY;
1961 		}
1962 		break;
1963 	case TEE_OPERATION_DIGEST:
1964 		if (key1 != 0 || key2 != 0) {
1965 			res = TEE_ERROR_BAD_PARAMETERS;
1966 		} else {
1967 			if (crypto_ops.hash.get_ctx_size)
1968 				res = crypto_ops.hash.get_ctx_size(algo,
1969 								&cs->ctx_size);
1970 			else
1971 				res = TEE_ERROR_NOT_IMPLEMENTED;
1972 			if (res != TEE_SUCCESS)
1973 				break;
1974 			cs->ctx = calloc(1, cs->ctx_size);
1975 			if (!cs->ctx)
1976 				res = TEE_ERROR_OUT_OF_MEMORY;
1977 		}
1978 		break;
1979 	case TEE_OPERATION_ASYMMETRIC_CIPHER:
1980 	case TEE_OPERATION_ASYMMETRIC_SIGNATURE:
1981 		if (key1 == 0 || key2 != 0)
1982 			res = TEE_ERROR_BAD_PARAMETERS;
1983 		break;
1984 	case TEE_OPERATION_KEY_DERIVATION:
1985 		if (key1 == 0 || key2 != 0)
1986 			res = TEE_ERROR_BAD_PARAMETERS;
1987 		break;
1988 	default:
1989 		res = TEE_ERROR_NOT_SUPPORTED;
1990 		break;
1991 	}
1992 	if (res != TEE_SUCCESS)
1993 		goto out;
1994 
1995 	res = tee_svc_copy_to_user(sess, state, &cs, sizeof(uint32_t));
1996 	if (res != TEE_SUCCESS)
1997 		goto out;
1998 
1999 	/* Register keys */
2000 	if (o1 != NULL) {
2001 		o1->busy = true;
2002 		cs->key1 = key1;
2003 	}
2004 	if (o2 != NULL) {
2005 		o2->busy = true;
2006 		cs->key2 = key2;
2007 	}
2008 
2009 out:
2010 	if (res != TEE_SUCCESS)
2011 		cryp_state_free(sess->ctx, cs);
2012 	return res;
2013 }
2014 
2015 TEE_Result tee_svc_cryp_state_copy(uint32_t dst, uint32_t src)
2016 {
2017 	TEE_Result res;
2018 	struct tee_cryp_state *cs_dst;
2019 	struct tee_cryp_state *cs_src;
2020 	struct tee_ta_session *sess;
2021 
2022 	res = tee_ta_get_current_session(&sess);
2023 	if (res != TEE_SUCCESS)
2024 		return res;
2025 
2026 	res = tee_svc_cryp_get_state(sess, dst, &cs_dst);
2027 	if (res != TEE_SUCCESS)
2028 		return res;
2029 	res = tee_svc_cryp_get_state(sess, src, &cs_src);
2030 	if (res != TEE_SUCCESS)
2031 		return res;
2032 	if (cs_dst->algo != cs_src->algo || cs_dst->mode != cs_src->mode)
2033 		return TEE_ERROR_BAD_PARAMETERS;
2034 	/* "Can't happen" */
2035 	if (cs_dst->ctx_size != cs_src->ctx_size)
2036 		return TEE_ERROR_BAD_STATE;
2037 
2038 	memcpy(cs_dst->ctx, cs_src->ctx, cs_src->ctx_size);
2039 	return TEE_SUCCESS;
2040 }
2041 
2042 void tee_svc_cryp_free_states(struct tee_ta_ctx *ctx)
2043 {
2044 	struct tee_cryp_state_head *states = &ctx->cryp_states;
2045 
2046 	while (!TAILQ_EMPTY(states))
2047 		cryp_state_free(ctx, TAILQ_FIRST(states));
2048 }
2049 
2050 TEE_Result tee_svc_cryp_state_free(uint32_t state)
2051 {
2052 	TEE_Result res;
2053 	struct tee_cryp_state *cs;
2054 	struct tee_ta_session *sess;
2055 
2056 	res = tee_ta_get_current_session(&sess);
2057 	if (res != TEE_SUCCESS)
2058 		return res;
2059 
2060 	res = tee_svc_cryp_get_state(sess, state, &cs);
2061 	if (res != TEE_SUCCESS)
2062 		return res;
2063 	cryp_state_free(sess->ctx, cs);
2064 	return TEE_SUCCESS;
2065 }
2066 
2067 /* iv and iv_len are ignored for some algorithms */
2068 TEE_Result tee_svc_hash_init(uint32_t state, const void *iv __unused,
2069 		size_t iv_len __unused)
2070 {
2071 	TEE_Result res;
2072 	struct tee_cryp_state *cs;
2073 	struct tee_ta_session *sess;
2074 
2075 	res = tee_ta_get_current_session(&sess);
2076 	if (res != TEE_SUCCESS)
2077 		return res;
2078 
2079 	res = tee_svc_cryp_get_state(sess, state, &cs);
2080 	if (res != TEE_SUCCESS)
2081 		return res;
2082 
2083 	switch (TEE_ALG_GET_CLASS(cs->algo)) {
2084 	case TEE_OPERATION_DIGEST:
2085 		if (!crypto_ops.hash.init)
2086 			return TEE_ERROR_NOT_IMPLEMENTED;
2087 		res = crypto_ops.hash.init(cs->ctx, cs->algo);
2088 		if (res != TEE_SUCCESS)
2089 			return res;
2090 		break;
2091 	case TEE_OPERATION_MAC:
2092 		{
2093 			struct tee_obj *o;
2094 			struct tee_cryp_obj_secret *key;
2095 
2096 			res = tee_obj_get(sess->ctx, cs->key1, &o);
2097 			if (res != TEE_SUCCESS)
2098 				return res;
2099 			if ((o->info.handleFlags &
2100 			     TEE_HANDLE_FLAG_INITIALIZED) == 0)
2101 				return TEE_ERROR_BAD_PARAMETERS;
2102 
2103 			key = (struct tee_cryp_obj_secret *)o->data;
2104 			if (!crypto_ops.mac.init)
2105 				return TEE_ERROR_NOT_IMPLEMENTED;
2106 			res = crypto_ops.mac.init(cs->ctx, cs->algo,
2107 						  (void *)(key + 1),
2108 						  key->key_size);
2109 			if (res != TEE_SUCCESS)
2110 				return res;
2111 			break;
2112 		}
2113 	default:
2114 		return TEE_ERROR_BAD_PARAMETERS;
2115 	}
2116 
2117 	return TEE_SUCCESS;
2118 }
2119 
2120 TEE_Result tee_svc_hash_update(uint32_t state, const void *chunk,
2121 			       size_t chunk_size)
2122 {
2123 	TEE_Result res;
2124 	struct tee_cryp_state *cs;
2125 	struct tee_ta_session *sess;
2126 
2127 	/* No data, but size provided isn't valid parameters. */
2128 	if (!chunk && chunk_size)
2129 		return TEE_ERROR_BAD_PARAMETERS;
2130 
2131 	/* Zero length hash is valid, but nothing we need to do. */
2132 	if (!chunk_size)
2133 		return TEE_SUCCESS;
2134 
2135 	res = tee_ta_get_current_session(&sess);
2136 	if (res != TEE_SUCCESS)
2137 		return res;
2138 
2139 	res = tee_mmu_check_access_rights(sess->ctx,
2140 					  TEE_MEMORY_ACCESS_READ |
2141 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2142 					  (tee_uaddr_t)chunk, chunk_size);
2143 	if (res != TEE_SUCCESS)
2144 		return res;
2145 
2146 	res = tee_svc_cryp_get_state(sess, state, &cs);
2147 	if (res != TEE_SUCCESS)
2148 		return res;
2149 
2150 	switch (TEE_ALG_GET_CLASS(cs->algo)) {
2151 	case TEE_OPERATION_DIGEST:
2152 		if (!crypto_ops.hash.update)
2153 			return TEE_ERROR_NOT_IMPLEMENTED;
2154 		res = crypto_ops.hash.update(cs->ctx, cs->algo, chunk,
2155 					     chunk_size);
2156 		if (res != TEE_SUCCESS)
2157 			return res;
2158 		break;
2159 	case TEE_OPERATION_MAC:
2160 		if (!crypto_ops.mac.update)
2161 			return TEE_ERROR_NOT_IMPLEMENTED;
2162 		res = crypto_ops.mac.update(cs->ctx, cs->algo, chunk,
2163 					    chunk_size);
2164 		if (res != TEE_SUCCESS)
2165 			return res;
2166 		break;
2167 	default:
2168 		return TEE_ERROR_BAD_PARAMETERS;
2169 	}
2170 
2171 	return TEE_SUCCESS;
2172 }
2173 
2174 TEE_Result tee_svc_hash_final(uint32_t state, const void *chunk,
2175 			      size_t chunk_size, void *hash, uint32_t *hash_len)
2176 {
2177 	TEE_Result res, res2;
2178 	size_t hash_size;
2179 	uint32_t hlen;
2180 	struct tee_cryp_state *cs;
2181 	struct tee_ta_session *sess;
2182 
2183 	/* No data, but size provided isn't valid parameters. */
2184 	if (!chunk && chunk_size)
2185 		return TEE_ERROR_BAD_PARAMETERS;
2186 
2187 	res = tee_ta_get_current_session(&sess);
2188 	if (res != TEE_SUCCESS)
2189 		return res;
2190 
2191 	res = tee_mmu_check_access_rights(sess->ctx,
2192 					  TEE_MEMORY_ACCESS_READ |
2193 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2194 					  (tee_uaddr_t)chunk, chunk_size);
2195 	if (res != TEE_SUCCESS)
2196 		return res;
2197 
2198 	res = tee_svc_copy_from_user(sess, &hlen, hash_len, sizeof(uint32_t));
2199 	if (res != TEE_SUCCESS)
2200 		return res;
2201 
2202 	res = tee_mmu_check_access_rights(sess->ctx,
2203 					  TEE_MEMORY_ACCESS_READ |
2204 					  TEE_MEMORY_ACCESS_WRITE |
2205 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2206 					  (tee_uaddr_t)hash, hlen);
2207 	if (res != TEE_SUCCESS)
2208 		return res;
2209 
2210 	res = tee_svc_cryp_get_state(sess, state, &cs);
2211 	if (res != TEE_SUCCESS)
2212 		return res;
2213 
2214 	switch (TEE_ALG_GET_CLASS(cs->algo)) {
2215 	case TEE_OPERATION_DIGEST:
2216 		if (!crypto_ops.hash.update || !crypto_ops.hash.final)
2217 			return TEE_ERROR_NOT_IMPLEMENTED;
2218 		res = tee_hash_get_digest_size(cs->algo, &hash_size);
2219 		if (res != TEE_SUCCESS)
2220 			return res;
2221 		if (*hash_len < hash_size) {
2222 			res = TEE_ERROR_SHORT_BUFFER;
2223 			goto out;
2224 		}
2225 
2226 		if (chunk_size) {
2227 			res = crypto_ops.hash.update(cs->ctx, cs->algo, chunk,
2228 						     chunk_size);
2229 			if (res != TEE_SUCCESS)
2230 				return res;
2231 		}
2232 
2233 		res = crypto_ops.hash.final(cs->ctx, cs->algo, hash,
2234 					    hash_size);
2235 		if (res != TEE_SUCCESS)
2236 			return res;
2237 		break;
2238 
2239 	case TEE_OPERATION_MAC:
2240 		if (!crypto_ops.mac.update || !crypto_ops.mac.final)
2241 			return TEE_ERROR_NOT_IMPLEMENTED;
2242 		res = tee_mac_get_digest_size(cs->algo, &hash_size);
2243 		if (res != TEE_SUCCESS)
2244 			return res;
2245 		if (*hash_len < hash_size) {
2246 			res = TEE_ERROR_SHORT_BUFFER;
2247 			goto out;
2248 		}
2249 
2250 		if (chunk_size) {
2251 			res = crypto_ops.mac.update(cs->ctx, cs->algo, chunk,
2252 						    chunk_size);
2253 			if (res != TEE_SUCCESS)
2254 				return res;
2255 		}
2256 
2257 		res = crypto_ops.mac.final(cs->ctx, cs->algo, hash, hash_size);
2258 		if (res != TEE_SUCCESS)
2259 			return res;
2260 		break;
2261 
2262 	default:
2263 		return TEE_ERROR_BAD_PARAMETERS;
2264 	}
2265 out:
2266 	hlen = hash_size;
2267 	res2 = tee_svc_copy_to_user(sess, hash_len, &hlen, sizeof(uint32_t));
2268 	if (res2 != TEE_SUCCESS)
2269 		return res2;
2270 	return res;
2271 }
2272 
2273 TEE_Result tee_svc_cipher_init(uint32_t state, const void *iv, size_t iv_len)
2274 {
2275 	TEE_Result res;
2276 	struct tee_cryp_state *cs;
2277 	struct tee_ta_session *sess;
2278 	struct tee_obj *o;
2279 	struct tee_cryp_obj_secret *key1;
2280 
2281 	res = tee_ta_get_current_session(&sess);
2282 	if (res != TEE_SUCCESS)
2283 		return res;
2284 
2285 	res = tee_svc_cryp_get_state(sess, state, &cs);
2286 	if (res != TEE_SUCCESS)
2287 		return res;
2288 
2289 	res = tee_mmu_check_access_rights(sess->ctx,
2290 					  TEE_MEMORY_ACCESS_READ |
2291 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2292 					  (tee_uaddr_t) iv, iv_len);
2293 	if (res != TEE_SUCCESS)
2294 		return res;
2295 
2296 	res = tee_obj_get(sess->ctx, cs->key1, &o);
2297 	if (res != TEE_SUCCESS)
2298 		return res;
2299 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
2300 		return TEE_ERROR_BAD_PARAMETERS;
2301 
2302 	key1 = (struct tee_cryp_obj_secret *)o->data;
2303 
2304 	if (!crypto_ops.cipher.init)
2305 		return TEE_ERROR_NOT_IMPLEMENTED;
2306 
2307 	if (tee_obj_get(sess->ctx, cs->key2, &o) == TEE_SUCCESS) {
2308 		struct tee_cryp_obj_secret *key2 =
2309 		    (struct tee_cryp_obj_secret *)o->data;
2310 
2311 		if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
2312 			return TEE_ERROR_BAD_PARAMETERS;
2313 
2314 		res = crypto_ops.cipher.init(cs->ctx, cs->algo, cs->mode,
2315 					     (uint8_t *)(key1 + 1),
2316 					     key1->key_size,
2317 					     (uint8_t *)(key2 + 1),
2318 					     key2->key_size,
2319 					     iv, iv_len);
2320 	} else {
2321 		res = crypto_ops.cipher.init(cs->ctx, cs->algo, cs->mode,
2322 					     (uint8_t *)(key1 + 1),
2323 					     key1->key_size,
2324 					     NULL,
2325 					     0,
2326 					     iv, iv_len);
2327 	}
2328 	if (res != TEE_SUCCESS)
2329 		return res;
2330 
2331 	cs->ctx_finalize = crypto_ops.cipher.final;
2332 	return TEE_SUCCESS;
2333 }
2334 
2335 static TEE_Result tee_svc_cipher_update_helper(uint32_t state, bool last_block,
2336 					       const void *src, size_t src_len,
2337 					       void *dst, uint32_t *dst_len)
2338 {
2339 	TEE_Result res;
2340 	struct tee_cryp_state *cs;
2341 	struct tee_ta_session *sess;
2342 	uint32_t dlen;
2343 
2344 	res = tee_ta_get_current_session(&sess);
2345 	if (res != TEE_SUCCESS)
2346 		return res;
2347 
2348 	res = tee_svc_cryp_get_state(sess, state, &cs);
2349 	if (res != TEE_SUCCESS)
2350 		return res;
2351 
2352 	res = tee_mmu_check_access_rights(sess->ctx,
2353 					  TEE_MEMORY_ACCESS_READ |
2354 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2355 					  (tee_uaddr_t)src, src_len);
2356 	if (res != TEE_SUCCESS)
2357 		return res;
2358 
2359 	if (!dst_len) {
2360 		dlen = 0;
2361 	} else {
2362 		res =
2363 		    tee_svc_copy_from_user(sess, &dlen, dst_len,
2364 					   sizeof(uint32_t));
2365 		if (res != TEE_SUCCESS)
2366 			return res;
2367 
2368 		res = tee_mmu_check_access_rights(sess->ctx,
2369 						  TEE_MEMORY_ACCESS_READ |
2370 						  TEE_MEMORY_ACCESS_WRITE |
2371 						  TEE_MEMORY_ACCESS_ANY_OWNER,
2372 						  (tee_uaddr_t)dst, dlen);
2373 		if (res != TEE_SUCCESS)
2374 			return res;
2375 	}
2376 
2377 	if (dlen < src_len) {
2378 		res = TEE_ERROR_SHORT_BUFFER;
2379 		goto out;
2380 	}
2381 
2382 	if (src_len > 0) {
2383 		/* Permit src_len == 0 to finalize the operation */
2384 		res = tee_do_cipher_update(cs->ctx, cs->algo, cs->mode,
2385 					   last_block, src, src_len, dst);
2386 	}
2387 
2388 	if (last_block && cs->ctx_finalize != NULL) {
2389 		cs->ctx_finalize(cs->ctx, cs->mode);
2390 		cs->ctx_finalize = NULL;
2391 	}
2392 
2393 out:
2394 	if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) &&
2395 	    dst_len != NULL) {
2396 		TEE_Result res2;
2397 
2398 		dlen = src_len;
2399 		res2 = tee_svc_copy_to_user(sess, dst_len, &dlen,
2400 					    sizeof(uint32_t));
2401 		if (res2 != TEE_SUCCESS)
2402 			res = res2;
2403 	}
2404 
2405 	return res;
2406 }
2407 
2408 TEE_Result tee_svc_cipher_update(uint32_t state, const void *src,
2409 				 size_t src_len, void *dst, uint32_t *dst_len)
2410 {
2411 	return tee_svc_cipher_update_helper(state, false /* last_block */,
2412 					    src, src_len, dst, dst_len);
2413 }
2414 
2415 TEE_Result tee_svc_cipher_final(uint32_t state, const void *src,
2416 				size_t src_len, void *dst, uint32_t *dst_len)
2417 {
2418 	return tee_svc_cipher_update_helper(state, true /* last_block */,
2419 					    src, src_len, dst, dst_len);
2420 }
2421 
2422 #if defined(CFG_CRYPTO_HKDF)
2423 static TEE_Result get_hkdf_params(const TEE_Attribute *params,
2424 				  uint32_t param_count,
2425 				  void **salt, size_t *salt_len, void **info,
2426 				  size_t *info_len, size_t *okm_len)
2427 {
2428 	size_t n;
2429 	enum { SALT = 0x1, LENGTH = 0x2, INFO = 0x4 };
2430 	uint8_t found = 0;
2431 
2432 	*salt = *info = NULL;
2433 	*salt_len = *info_len = *okm_len = 0;
2434 
2435 	for (n = 0; n < param_count; n++) {
2436 		switch (params[n].attributeID) {
2437 		case TEE_ATTR_HKDF_SALT:
2438 			if (!(found & SALT)) {
2439 				*salt = params[n].content.ref.buffer;
2440 				*salt_len = params[n].content.ref.length;
2441 				found |= SALT;
2442 			}
2443 			break;
2444 		case TEE_ATTR_HKDF_OKM_LENGTH:
2445 			if (!(found & LENGTH)) {
2446 				*okm_len = params[n].content.value.a;
2447 				found |= LENGTH;
2448 			}
2449 			break;
2450 		case TEE_ATTR_HKDF_INFO:
2451 			if (!(found & INFO)) {
2452 				*info = params[n].content.ref.buffer;
2453 				*info_len = params[n].content.ref.length;
2454 				found |= INFO;
2455 			}
2456 			break;
2457 		default:
2458 			/* Unexpected attribute */
2459 			return TEE_ERROR_BAD_PARAMETERS;
2460 		}
2461 
2462 	}
2463 
2464 	if (!(found & LENGTH))
2465 		return TEE_ERROR_BAD_PARAMETERS;
2466 
2467 	return TEE_SUCCESS;
2468 }
2469 #endif
2470 
2471 #if defined(CFG_CRYPTO_CONCAT_KDF)
2472 static TEE_Result get_concat_kdf_params(const TEE_Attribute *params,
2473 					uint32_t param_count,
2474 					void **other_info,
2475 					size_t *other_info_len,
2476 					size_t *derived_key_len)
2477 {
2478 	size_t n;
2479 	enum { LENGTH = 0x1, INFO = 0x2 };
2480 	uint8_t found = 0;
2481 
2482 	*other_info = NULL;
2483 	*other_info_len = *derived_key_len = 0;
2484 
2485 	for (n = 0; n < param_count; n++) {
2486 		switch (params[n].attributeID) {
2487 		case TEE_ATTR_CONCAT_KDF_OTHER_INFO:
2488 			if (!(found & INFO)) {
2489 				*other_info = params[n].content.ref.buffer;
2490 				*other_info_len = params[n].content.ref.length;
2491 				found |= INFO;
2492 			}
2493 			break;
2494 		case TEE_ATTR_CONCAT_KDF_DKM_LENGTH:
2495 			if (!(found & LENGTH)) {
2496 				*derived_key_len = params[n].content.value.a;
2497 				found |= LENGTH;
2498 			}
2499 			break;
2500 		default:
2501 			/* Unexpected attribute */
2502 			return TEE_ERROR_BAD_PARAMETERS;
2503 		}
2504 	}
2505 
2506 	if (!(found & LENGTH))
2507 		return TEE_ERROR_BAD_PARAMETERS;
2508 
2509 	return TEE_SUCCESS;
2510 }
2511 #endif
2512 
2513 #if defined(CFG_CRYPTO_PBKDF2)
2514 static TEE_Result get_pbkdf2_params(const TEE_Attribute *params,
2515 				   uint32_t param_count, void **salt,
2516 				   size_t *salt_len, size_t *derived_key_len,
2517 				   size_t *iteration_count)
2518 {
2519 	size_t n;
2520 	enum { SALT = 0x1, LENGTH = 0x2, COUNT = 0x4 };
2521 	uint8_t found = 0;
2522 
2523 	*salt = NULL;
2524 	*salt_len = *derived_key_len = *iteration_count = 0;
2525 
2526 	for (n = 0; n < param_count; n++) {
2527 		switch (params[n].attributeID) {
2528 		case TEE_ATTR_PBKDF2_SALT:
2529 			if (!(found & SALT)) {
2530 				*salt = params[n].content.ref.buffer;
2531 				*salt_len = params[n].content.ref.length;
2532 				found |= SALT;
2533 			}
2534 			break;
2535 		case TEE_ATTR_PBKDF2_DKM_LENGTH:
2536 			if (!(found & LENGTH)) {
2537 				*derived_key_len = params[n].content.value.a;
2538 				found |= LENGTH;
2539 			}
2540 			break;
2541 		case TEE_ATTR_PBKDF2_ITERATION_COUNT:
2542 			if (!(found & COUNT)) {
2543 				*iteration_count = params[n].content.value.a;
2544 				found |= COUNT;
2545 			}
2546 			break;
2547 		default:
2548 			/* Unexpected attribute */
2549 			return TEE_ERROR_BAD_PARAMETERS;
2550 		}
2551 	}
2552 
2553 	if ((found & (LENGTH|COUNT)) != (LENGTH|COUNT))
2554 		return TEE_ERROR_BAD_PARAMETERS;
2555 
2556 	return TEE_SUCCESS;
2557 }
2558 #endif
2559 
2560 TEE_Result tee_svc_cryp_derive_key(uint32_t state,
2561 			const struct abi_user32_attribute *usr_params,
2562 			uint32_t param_count, uint32_t derived_key)
2563 {
2564 	TEE_Result res = TEE_ERROR_NOT_SUPPORTED;
2565 	struct tee_ta_session *sess;
2566 	struct tee_obj *ko;
2567 	struct tee_obj *so;
2568 	struct tee_cryp_state *cs;
2569 	struct tee_cryp_obj_secret *sk;
2570 	const struct tee_cryp_obj_type_props *type_props;
2571 	TEE_Attribute *params = NULL;
2572 
2573 	res = tee_ta_get_current_session(&sess);
2574 	if (res != TEE_SUCCESS)
2575 		return res;
2576 
2577 	res = tee_svc_cryp_get_state(sess, state, &cs);
2578 	if (res != TEE_SUCCESS)
2579 		return res;
2580 
2581 	params = malloc(sizeof(TEE_Attribute) * param_count);
2582 	if (!params)
2583 		return TEE_ERROR_OUT_OF_MEMORY;
2584 	res = copy_in_attrs(sess->ctx, usr_params, param_count, params);
2585 	if (res != TEE_SUCCESS)
2586 		goto out;
2587 
2588 	/* Get key set in operation */
2589 	res = tee_obj_get(sess->ctx, cs->key1, &ko);
2590 	if (res != TEE_SUCCESS)
2591 		goto out;
2592 
2593 	res = tee_obj_get(sess->ctx, derived_key, &so);
2594 	if (res != TEE_SUCCESS)
2595 		goto out;
2596 
2597 	/* Find information needed about the object to initialize */
2598 	sk = (struct tee_cryp_obj_secret *)so->data;
2599 
2600 	/* Find description of object */
2601 	type_props = tee_svc_find_type_props(so->info.objectType);
2602 	if (!type_props) {
2603 		res = TEE_ERROR_NOT_SUPPORTED;
2604 		goto out;
2605 	}
2606 
2607 	if (cs->algo == TEE_ALG_DH_DERIVE_SHARED_SECRET) {
2608 		size_t alloc_size;
2609 		struct bignum *pub;
2610 		struct bignum *ss;
2611 
2612 		if (!crypto_ops.bignum.allocate ||
2613 		    !crypto_ops.bignum.free ||
2614 		    !crypto_ops.bignum.bin2bn ||
2615 		    !crypto_ops.bignum.bn2bin ||
2616 		    !crypto_ops.bignum.num_bytes ||
2617 		    !crypto_ops.acipher.dh_shared_secret) {
2618 			res = TEE_ERROR_NOT_IMPLEMENTED;
2619 			goto out;
2620 		}
2621 		if (param_count != 1 ||
2622 		    params[0].attributeID != TEE_ATTR_DH_PUBLIC_VALUE) {
2623 			res = TEE_ERROR_BAD_PARAMETERS;
2624 			goto out;
2625 		}
2626 
2627 		alloc_size = params[0].content.ref.length * 8;
2628 		pub = crypto_ops.bignum.allocate(alloc_size);
2629 		ss = crypto_ops.bignum.allocate(alloc_size);
2630 		if (pub && ss) {
2631 			crypto_ops.bignum.bin2bn(params[0].content.ref.buffer,
2632 					params[0].content.ref.length, pub);
2633 			res = crypto_ops.acipher.dh_shared_secret(ko->data,
2634 								  pub, ss);
2635 			if (res == TEE_SUCCESS) {
2636 				sk->key_size = crypto_ops.bignum.num_bytes(ss);
2637 				crypto_ops.bignum.bn2bin(ss,
2638 							 (uint8_t *)(sk + 1));
2639 				so->info.handleFlags |=
2640 						TEE_HANDLE_FLAG_INITIALIZED;
2641 				SET_ATTRIBUTE(so, type_props,
2642 					      TEE_ATTR_SECRET_VALUE);
2643 			}
2644 		} else {
2645 			res = TEE_ERROR_OUT_OF_MEMORY;
2646 		}
2647 		crypto_ops.bignum.free(pub);
2648 		crypto_ops.bignum.free(ss);
2649 	}
2650 #if defined(CFG_CRYPTO_HKDF)
2651 	else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_HKDF) {
2652 		void *salt, *info;
2653 		size_t salt_len, info_len, okm_len;
2654 		uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
2655 		struct tee_cryp_obj_secret *ik = ko->data;
2656 		const uint8_t *ikm = (const uint8_t *)(ik + 1);
2657 
2658 		res = get_hkdf_params(params, param_count, &salt, &salt_len,
2659 				      &info, &info_len, &okm_len);
2660 		if (res != TEE_SUCCESS)
2661 			goto out;
2662 
2663 		/* Requested size must fit into the output object's buffer */
2664 		if (okm_len >
2665 			ko->data_size - sizeof(struct tee_cryp_obj_secret)) {
2666 			res = TEE_ERROR_BAD_PARAMETERS;
2667 			goto out;
2668 		}
2669 
2670 		res = tee_cryp_hkdf(hash_id, ikm, ik->key_size, salt, salt_len,
2671 				    info, info_len, (uint8_t *)(sk + 1),
2672 				    okm_len);
2673 		if (res == TEE_SUCCESS) {
2674 			sk->key_size = okm_len;
2675 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
2676 			SET_ATTRIBUTE(so, type_props, TEE_ATTR_SECRET_VALUE);
2677 		}
2678 	}
2679 #endif
2680 #if defined(CFG_CRYPTO_CONCAT_KDF)
2681 	else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_CONCAT_KDF) {
2682 		void *info;
2683 		size_t info_len, derived_key_len;
2684 		uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
2685 		struct tee_cryp_obj_secret *ss = ko->data;
2686 		const uint8_t *shared_secret = (const uint8_t *)(ss + 1);
2687 
2688 		res = get_concat_kdf_params(params, param_count, &info,
2689 					    &info_len, &derived_key_len);
2690 		if (res != TEE_SUCCESS)
2691 			goto out;
2692 
2693 		/* Requested size must fit into the output object's buffer */
2694 		if (derived_key_len >
2695 		    ko->data_size - sizeof(struct tee_cryp_obj_secret)) {
2696 			res = TEE_ERROR_BAD_PARAMETERS;
2697 			goto out;
2698 		}
2699 
2700 		res = tee_cryp_concat_kdf(hash_id, shared_secret, ss->key_size,
2701 					  info, info_len, (uint8_t *)(sk + 1),
2702 					  derived_key_len);
2703 		if (res == TEE_SUCCESS) {
2704 			sk->key_size = derived_key_len;
2705 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
2706 			SET_ATTRIBUTE(so, type_props, TEE_ATTR_SECRET_VALUE);
2707 		}
2708 	}
2709 #endif
2710 #if defined(CFG_CRYPTO_PBKDF2)
2711 	else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_PBKDF2) {
2712 		void *salt;
2713 		size_t salt_len, iteration_count, derived_key_len;
2714 		uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
2715 		struct tee_cryp_obj_secret *ss = ko->data;
2716 		const uint8_t *password = (const uint8_t *)(ss + 1);
2717 
2718 		res = get_pbkdf2_params(params, param_count, &salt, &salt_len,
2719 					&derived_key_len, &iteration_count);
2720 		if (res != TEE_SUCCESS)
2721 			goto out;
2722 
2723 		/* Requested size must fit into the output object's buffer */
2724 		if (derived_key_len >
2725 			ko->data_size - sizeof(struct tee_cryp_obj_secret)) {
2726 			res = TEE_ERROR_BAD_PARAMETERS;
2727 			goto out;
2728 		}
2729 
2730 		res = tee_cryp_pbkdf2(hash_id, password, ss->key_size, salt,
2731 				      salt_len, iteration_count,
2732 				      (uint8_t *)(sk + 1), derived_key_len);
2733 		if (res == TEE_SUCCESS) {
2734 			sk->key_size = derived_key_len;
2735 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
2736 			SET_ATTRIBUTE(so, type_props, TEE_ATTR_SECRET_VALUE);
2737 		}
2738 	}
2739 #endif
2740 	else
2741 		res = TEE_ERROR_NOT_SUPPORTED;
2742 
2743 out:
2744 	free(params);
2745 	return res;
2746 }
2747 
2748 TEE_Result tee_svc_cryp_random_number_generate(void *buf, size_t blen)
2749 {
2750 	TEE_Result res;
2751 	struct tee_ta_session *sess;
2752 
2753 	res = tee_ta_get_current_session(&sess);
2754 	if (res != TEE_SUCCESS)
2755 		return res;
2756 
2757 	res = tee_mmu_check_access_rights(sess->ctx,
2758 					  TEE_MEMORY_ACCESS_WRITE |
2759 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2760 					  (tee_uaddr_t)buf, blen);
2761 	if (res != TEE_SUCCESS)
2762 		return res;
2763 
2764 	res = crypto_ops.prng.read(buf, blen);
2765 	if (res != TEE_SUCCESS)
2766 		return res;
2767 
2768 	return res;
2769 }
2770 
2771 TEE_Result tee_svc_authenc_init(uint32_t state, const void *nonce,
2772 				size_t nonce_len, size_t tag_len,
2773 				size_t aad_len, size_t payload_len)
2774 {
2775 	TEE_Result res;
2776 	struct tee_cryp_state *cs;
2777 	struct tee_ta_session *sess;
2778 	struct tee_obj *o;
2779 	struct tee_cryp_obj_secret *key;
2780 
2781 	res = tee_ta_get_current_session(&sess);
2782 	if (res != TEE_SUCCESS)
2783 		return res;
2784 
2785 	res = tee_svc_cryp_get_state(sess, state, &cs);
2786 	if (res != TEE_SUCCESS)
2787 		return res;
2788 
2789 	res = tee_obj_get(sess->ctx, cs->key1, &o);
2790 	if (res != TEE_SUCCESS)
2791 		return res;
2792 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
2793 		return TEE_ERROR_BAD_PARAMETERS;
2794 
2795 	if (!crypto_ops.authenc.init)
2796 		return TEE_ERROR_NOT_IMPLEMENTED;
2797 	key = (struct tee_cryp_obj_secret *)o->data;
2798 	res = crypto_ops.authenc.init(cs->ctx, cs->algo, cs->mode,
2799 				      (uint8_t *)(key + 1), key->key_size,
2800 				      nonce, nonce_len, tag_len, aad_len,
2801 				      payload_len);
2802 	if (res != TEE_SUCCESS)
2803 		return res;
2804 
2805 	cs->ctx_finalize = (tee_cryp_ctx_finalize_func_t)
2806 				crypto_ops.authenc.final;
2807 	return TEE_SUCCESS;
2808 }
2809 
2810 TEE_Result tee_svc_authenc_update_aad(uint32_t state, const void *aad_data,
2811 				      size_t aad_data_len)
2812 {
2813 	TEE_Result res;
2814 	struct tee_cryp_state *cs;
2815 	struct tee_ta_session *sess;
2816 
2817 	res = tee_ta_get_current_session(&sess);
2818 	if (res != TEE_SUCCESS)
2819 		return res;
2820 
2821 	res = tee_mmu_check_access_rights(sess->ctx,
2822 					  TEE_MEMORY_ACCESS_READ |
2823 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2824 					  (tee_uaddr_t) aad_data,
2825 					  aad_data_len);
2826 	if (res != TEE_SUCCESS)
2827 		return res;
2828 
2829 	res = tee_svc_cryp_get_state(sess, state, &cs);
2830 	if (res != TEE_SUCCESS)
2831 		return res;
2832 
2833 	if (!crypto_ops.authenc.update_aad)
2834 		return TEE_ERROR_NOT_IMPLEMENTED;
2835 	res = crypto_ops.authenc.update_aad(cs->ctx, cs->algo, cs->mode,
2836 					    aad_data, aad_data_len);
2837 	if (res != TEE_SUCCESS)
2838 		return res;
2839 
2840 	return TEE_SUCCESS;
2841 }
2842 
2843 TEE_Result tee_svc_authenc_update_payload(uint32_t state, const void *src_data,
2844 					  size_t src_len, void *dst_data,
2845 					  uint32_t *dst_len)
2846 {
2847 	TEE_Result res;
2848 	struct tee_cryp_state *cs;
2849 	struct tee_ta_session *sess;
2850 	uint32_t dlen;
2851 	size_t tmp_dlen;
2852 
2853 	res = tee_ta_get_current_session(&sess);
2854 	if (res != TEE_SUCCESS)
2855 		return res;
2856 
2857 	res = tee_svc_cryp_get_state(sess, state, &cs);
2858 	if (res != TEE_SUCCESS)
2859 		return res;
2860 
2861 	res = tee_mmu_check_access_rights(sess->ctx,
2862 					  TEE_MEMORY_ACCESS_READ |
2863 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2864 					  (tee_uaddr_t) src_data, src_len);
2865 	if (res != TEE_SUCCESS)
2866 		return res;
2867 
2868 	res = tee_svc_copy_from_user(sess, &dlen, dst_len, sizeof(uint32_t));
2869 	if (res != TEE_SUCCESS)
2870 		return res;
2871 
2872 	res = tee_mmu_check_access_rights(sess->ctx,
2873 					  TEE_MEMORY_ACCESS_READ |
2874 					  TEE_MEMORY_ACCESS_WRITE |
2875 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2876 					  (tee_uaddr_t)dst_data, dlen);
2877 	if (res != TEE_SUCCESS)
2878 		return res;
2879 
2880 	if (dlen < src_len) {
2881 		res = TEE_ERROR_SHORT_BUFFER;
2882 		goto out;
2883 	}
2884 
2885 	if (!crypto_ops.authenc.update_payload)
2886 		return TEE_ERROR_NOT_IMPLEMENTED;
2887 	tmp_dlen = dlen;
2888 	res = crypto_ops.authenc.update_payload(cs->ctx, cs->algo, cs->mode,
2889 						src_data, src_len, dst_data,
2890 						&tmp_dlen);
2891 	dlen = tmp_dlen;
2892 
2893 out:
2894 	if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
2895 		TEE_Result res2 = tee_svc_copy_to_user(sess, dst_len, &dlen,
2896 						       sizeof(uint32_t));
2897 		if (res2 != TEE_SUCCESS)
2898 			res = res2;
2899 	}
2900 
2901 	return res;
2902 }
2903 
2904 TEE_Result tee_svc_authenc_enc_final(uint32_t state, const void *src_data,
2905 				     size_t src_len, void *dst_data,
2906 				     uint32_t *dst_len, void *tag,
2907 				     uint32_t *tag_len)
2908 {
2909 	TEE_Result res;
2910 	struct tee_cryp_state *cs;
2911 	struct tee_ta_session *sess;
2912 	uint32_t dlen;
2913 	uint32_t tlen;
2914 	size_t tmp_dlen;
2915 	size_t tmp_tlen;
2916 
2917 	res = tee_ta_get_current_session(&sess);
2918 	if (res != TEE_SUCCESS)
2919 		return res;
2920 
2921 	res = tee_svc_cryp_get_state(sess, state, &cs);
2922 	if (res != TEE_SUCCESS)
2923 		return res;
2924 
2925 	if (cs->mode != TEE_MODE_ENCRYPT)
2926 		return TEE_ERROR_BAD_PARAMETERS;
2927 
2928 	res = tee_mmu_check_access_rights(sess->ctx,
2929 					  TEE_MEMORY_ACCESS_READ |
2930 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2931 					  (tee_uaddr_t)src_data, src_len);
2932 	if (res != TEE_SUCCESS)
2933 		return res;
2934 
2935 	if (!dst_len) {
2936 		dlen = 0;
2937 	} else {
2938 		res = tee_svc_copy_from_user(sess, &dlen, dst_len,
2939 					     sizeof(uint32_t));
2940 		if (res != TEE_SUCCESS)
2941 			return res;
2942 
2943 		res = tee_mmu_check_access_rights(sess->ctx,
2944 						  TEE_MEMORY_ACCESS_READ |
2945 						  TEE_MEMORY_ACCESS_WRITE |
2946 						  TEE_MEMORY_ACCESS_ANY_OWNER,
2947 						  (tee_uaddr_t)dst_data, dlen);
2948 		if (res != TEE_SUCCESS)
2949 			return res;
2950 	}
2951 
2952 	if (dlen < src_len) {
2953 		res = TEE_ERROR_SHORT_BUFFER;
2954 		goto out;
2955 	}
2956 
2957 	res = tee_svc_copy_from_user(sess, &tlen, tag_len, sizeof(uint32_t));
2958 	if (res != TEE_SUCCESS)
2959 		return res;
2960 
2961 	res = tee_mmu_check_access_rights(sess->ctx,
2962 					  TEE_MEMORY_ACCESS_READ |
2963 					  TEE_MEMORY_ACCESS_WRITE |
2964 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2965 					  (tee_uaddr_t)tag, tlen);
2966 	if (res != TEE_SUCCESS)
2967 		return res;
2968 
2969 	if (!crypto_ops.authenc.enc_final)
2970 		return TEE_ERROR_NOT_IMPLEMENTED;
2971 	tmp_dlen = dlen;
2972 	tmp_tlen = tlen;
2973 	res = crypto_ops.authenc.enc_final(cs->ctx, cs->algo, src_data,
2974 					   src_len, dst_data, &tmp_dlen, tag,
2975 					   &tmp_tlen);
2976 	dlen = tmp_dlen;
2977 	tlen = tmp_tlen;
2978 
2979 out:
2980 	if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
2981 		TEE_Result res2;
2982 
2983 		if (dst_len != NULL) {
2984 			res2 = tee_svc_copy_to_user(sess, dst_len, &dlen,
2985 						    sizeof(uint32_t));
2986 			if (res2 != TEE_SUCCESS)
2987 				return res2;
2988 		}
2989 
2990 		res2 = tee_svc_copy_to_user(sess, tag_len, &tlen,
2991 					    sizeof(uint32_t));
2992 		if (res2 != TEE_SUCCESS)
2993 			return res2;
2994 	}
2995 
2996 	return res;
2997 }
2998 
2999 TEE_Result tee_svc_authenc_dec_final(uint32_t state, const void *src_data,
3000 				     size_t src_len, void *dst_data,
3001 				     uint32_t *dst_len, const void *tag,
3002 				     size_t tag_len)
3003 {
3004 	TEE_Result res;
3005 	struct tee_cryp_state *cs;
3006 	struct tee_ta_session *sess;
3007 	uint32_t dlen;
3008 	size_t tmp_dlen;
3009 
3010 	res = tee_ta_get_current_session(&sess);
3011 	if (res != TEE_SUCCESS)
3012 		return res;
3013 
3014 	res = tee_svc_cryp_get_state(sess, state, &cs);
3015 	if (res != TEE_SUCCESS)
3016 		return res;
3017 
3018 	if (cs->mode != TEE_MODE_DECRYPT)
3019 		return TEE_ERROR_BAD_PARAMETERS;
3020 
3021 	res = tee_mmu_check_access_rights(sess->ctx,
3022 					  TEE_MEMORY_ACCESS_READ |
3023 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3024 					  (tee_uaddr_t)src_data, src_len);
3025 	if (res != TEE_SUCCESS)
3026 		return res;
3027 
3028 	if (!dst_len) {
3029 		dlen = 0;
3030 	} else {
3031 		res = tee_svc_copy_from_user(sess, &dlen, dst_len,
3032 					     sizeof(uint32_t));
3033 		if (res != TEE_SUCCESS)
3034 			return res;
3035 
3036 		res = tee_mmu_check_access_rights(sess->ctx,
3037 						  TEE_MEMORY_ACCESS_READ |
3038 						  TEE_MEMORY_ACCESS_WRITE |
3039 						  TEE_MEMORY_ACCESS_ANY_OWNER,
3040 						  (tee_uaddr_t)dst_data, dlen);
3041 		if (res != TEE_SUCCESS)
3042 			return res;
3043 	}
3044 
3045 	if (dlen < src_len) {
3046 		res = TEE_ERROR_SHORT_BUFFER;
3047 		goto out;
3048 	}
3049 
3050 	res = tee_mmu_check_access_rights(sess->ctx,
3051 					  TEE_MEMORY_ACCESS_READ |
3052 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3053 					  (tee_uaddr_t)tag, tag_len);
3054 	if (res != TEE_SUCCESS)
3055 		return res;
3056 
3057 	if (!crypto_ops.authenc.dec_final)
3058 		return TEE_ERROR_NOT_IMPLEMENTED;
3059 	tmp_dlen = dlen;
3060 	res = crypto_ops.authenc.dec_final(cs->ctx, cs->algo, src_data,
3061 					   src_len, dst_data, &tmp_dlen, tag,
3062 					   tag_len);
3063 	dlen = tmp_dlen;
3064 
3065 out:
3066 	if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) &&
3067 	    dst_len != NULL) {
3068 		TEE_Result res2;
3069 
3070 		res2 = tee_svc_copy_to_user(sess, dst_len, &dlen,
3071 					    sizeof(uint32_t));
3072 		if (res2 != TEE_SUCCESS)
3073 			return res2;
3074 	}
3075 
3076 	return res;
3077 }
3078 
3079 static void tee_svc_asymm_pkcs1_get_salt_len(const TEE_Attribute *params,
3080 					     uint32_t num_params, int *salt_len)
3081 {
3082 	size_t n;
3083 
3084 	for (n = 0; n < num_params; n++) {
3085 		if (params[n].attributeID == TEE_ATTR_RSA_PSS_SALT_LENGTH) {
3086 			*salt_len = params[n].content.value.a;
3087 			return;
3088 		}
3089 	}
3090 	*salt_len = -1;
3091 }
3092 
3093 TEE_Result tee_svc_asymm_operate(uint32_t state,
3094 			const struct abi_user32_attribute *usr_params,
3095 			uint32_t num_params, const void *src_data,
3096 			size_t src_len, void *dst_data, uint32_t *dst_len)
3097 {
3098 	TEE_Result res;
3099 	struct tee_cryp_state *cs;
3100 	struct tee_ta_session *sess;
3101 	uint32_t dlen32;
3102 	size_t dlen;
3103 	struct tee_obj *o;
3104 	void *label = NULL;
3105 	size_t label_len = 0;
3106 	size_t n;
3107 	int salt_len;
3108 	TEE_Attribute *params = NULL;
3109 
3110 	res = tee_ta_get_current_session(&sess);
3111 	if (res != TEE_SUCCESS)
3112 		return res;
3113 
3114 	res = tee_svc_cryp_get_state(sess, state, &cs);
3115 	if (res != TEE_SUCCESS)
3116 		return res;
3117 
3118 	res = tee_mmu_check_access_rights(
3119 		sess->ctx,
3120 		TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_ANY_OWNER,
3121 		(tee_uaddr_t) src_data, src_len);
3122 	if (res != TEE_SUCCESS)
3123 		return res;
3124 
3125 	res = tee_svc_copy_from_user(sess, &dlen32, dst_len, sizeof(uint32_t));
3126 	if (res != TEE_SUCCESS)
3127 		return res;
3128 	dlen = dlen32;
3129 
3130 	res = tee_mmu_check_access_rights(
3131 		sess->ctx,
3132 		TEE_MEMORY_ACCESS_READ | TEE_MEMORY_ACCESS_WRITE |
3133 			TEE_MEMORY_ACCESS_ANY_OWNER,
3134 		(tee_uaddr_t) dst_data, dlen);
3135 	if (res != TEE_SUCCESS)
3136 		return res;
3137 
3138 	params = malloc(sizeof(TEE_Attribute) * num_params);
3139 	if (!params)
3140 		return TEE_ERROR_OUT_OF_MEMORY;
3141 	res = copy_in_attrs(sess->ctx, usr_params, num_params, params);
3142 	if (res != TEE_SUCCESS)
3143 		goto out;
3144 
3145 	res = tee_obj_get(sess->ctx, cs->key1, &o);
3146 	if (res != TEE_SUCCESS)
3147 		goto out;
3148 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
3149 		res = TEE_ERROR_GENERIC;
3150 		goto out;
3151 	}
3152 
3153 	switch (cs->algo) {
3154 	case TEE_ALG_RSA_NOPAD:
3155 		if (cs->mode == TEE_MODE_ENCRYPT) {
3156 			if (crypto_ops.acipher.rsanopad_encrypt)
3157 				res = crypto_ops.acipher.rsanopad_encrypt(
3158 					o->data, src_data, src_len,
3159 					dst_data, &dlen);
3160 			else
3161 				res = TEE_ERROR_NOT_IMPLEMENTED;
3162 		} else if (cs->mode == TEE_MODE_DECRYPT) {
3163 			if (crypto_ops.acipher.rsanopad_decrypt)
3164 				res = crypto_ops.acipher.rsanopad_decrypt(
3165 					o->data, src_data, src_len, dst_data,
3166 					&dlen);
3167 			else
3168 				res = TEE_ERROR_NOT_IMPLEMENTED;
3169 		} else {
3170 			/*
3171 			 * We will panic because "the mode is not compatible
3172 			 * with the function"
3173 			 */
3174 			res = TEE_ERROR_GENERIC;
3175 		}
3176 		break;
3177 
3178 	case TEE_ALG_RSAES_PKCS1_V1_5:
3179 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
3180 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
3181 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
3182 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
3183 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
3184 		for (n = 0; n < num_params; n++) {
3185 			if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) {
3186 				label = params[n].content.ref.buffer;
3187 				label_len = params[n].content.ref.length;
3188 				break;
3189 			}
3190 		}
3191 
3192 		if (cs->mode == TEE_MODE_ENCRYPT) {
3193 			if (crypto_ops.acipher.rsaes_encrypt)
3194 				res = crypto_ops.acipher.rsaes_encrypt(
3195 					cs->algo, o->data, label, label_len,
3196 					src_data, src_len, dst_data, &dlen);
3197 			else
3198 				res = TEE_ERROR_NOT_IMPLEMENTED;
3199 		} else if (cs->mode == TEE_MODE_DECRYPT) {
3200 			if (crypto_ops.acipher.rsaes_decrypt)
3201 				res = crypto_ops.acipher.rsaes_decrypt(
3202 					cs->algo, o->data,
3203 					label, label_len,
3204 					src_data, src_len, dst_data, &dlen);
3205 			else
3206 				res = TEE_ERROR_NOT_IMPLEMENTED;
3207 		} else {
3208 			res = TEE_ERROR_BAD_PARAMETERS;
3209 		}
3210 		break;
3211 
3212 	case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
3213 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
3214 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
3215 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
3216 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
3217 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
3218 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
3219 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
3220 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
3221 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
3222 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
3223 		if (cs->mode != TEE_MODE_SIGN) {
3224 			res = TEE_ERROR_BAD_PARAMETERS;
3225 			break;
3226 		}
3227 		tee_svc_asymm_pkcs1_get_salt_len(params, num_params, &salt_len);
3228 
3229 		if (!crypto_ops.acipher.rsassa_sign) {
3230 			res = TEE_ERROR_NOT_IMPLEMENTED;
3231 			break;
3232 		}
3233 		res = crypto_ops.acipher.rsassa_sign(cs->algo, o->data,
3234 						     salt_len, src_data,
3235 						     src_len, dst_data, &dlen);
3236 		break;
3237 
3238 	case TEE_ALG_DSA_SHA1:
3239 		if (!crypto_ops.acipher.dsa_sign) {
3240 			res = TEE_ERROR_NOT_IMPLEMENTED;
3241 			break;
3242 		}
3243 		res = crypto_ops.acipher.dsa_sign(cs->algo, o->data, src_data,
3244 						  src_len, dst_data, &dlen);
3245 		break;
3246 
3247 	default:
3248 		res = TEE_ERROR_BAD_PARAMETERS;
3249 		break;
3250 	}
3251 
3252 out:
3253 	free(params);
3254 
3255 	if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
3256 		TEE_Result res2;
3257 
3258 		dlen32 = dlen;
3259 		res2 = tee_svc_copy_to_user(sess, dst_len, &dlen,
3260 					    sizeof(uint32_t));
3261 		if (res2 != TEE_SUCCESS)
3262 			return res2;
3263 	}
3264 
3265 	return res;
3266 }
3267 
3268 TEE_Result tee_svc_asymm_verify(uint32_t state,
3269 			const struct abi_user32_attribute *usr_params,
3270 			uint32_t num_params, const void *data,
3271 			size_t data_len, const void *sig, size_t sig_len)
3272 {
3273 	TEE_Result res;
3274 	struct tee_cryp_state *cs;
3275 	struct tee_ta_session *sess;
3276 	struct tee_obj *o;
3277 	size_t hash_size;
3278 	int salt_len;
3279 	TEE_Attribute *params = NULL;
3280 
3281 	res = tee_ta_get_current_session(&sess);
3282 	if (res != TEE_SUCCESS)
3283 		return res;
3284 
3285 	res = tee_svc_cryp_get_state(sess, state, &cs);
3286 	if (res != TEE_SUCCESS)
3287 		return res;
3288 
3289 	if (cs->mode != TEE_MODE_VERIFY)
3290 		return TEE_ERROR_BAD_PARAMETERS;
3291 
3292 	res = tee_mmu_check_access_rights(sess->ctx,
3293 					  TEE_MEMORY_ACCESS_READ |
3294 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3295 					  (tee_uaddr_t)data, data_len);
3296 	if (res != TEE_SUCCESS)
3297 		return res;
3298 
3299 	res = tee_mmu_check_access_rights(sess->ctx,
3300 					  TEE_MEMORY_ACCESS_READ |
3301 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3302 					  (tee_uaddr_t)sig, sig_len);
3303 	if (res != TEE_SUCCESS)
3304 		return res;
3305 
3306 	params = malloc(sizeof(TEE_Attribute) * num_params);
3307 	if (!params)
3308 		return TEE_ERROR_OUT_OF_MEMORY;
3309 	res = copy_in_attrs(sess->ctx, usr_params, num_params, params);
3310 	if (res != TEE_SUCCESS)
3311 		goto out;
3312 
3313 	res = tee_obj_get(sess->ctx, cs->key1, &o);
3314 	if (res != TEE_SUCCESS)
3315 		goto out;
3316 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
3317 		res = TEE_ERROR_BAD_PARAMETERS;
3318 		goto out;
3319 	}
3320 
3321 	res = tee_hash_get_digest_size(TEE_DIGEST_HASH_TO_ALGO(cs->algo),
3322 				       &hash_size);
3323 	if (res != TEE_SUCCESS)
3324 		goto out;
3325 
3326 	if (data_len != hash_size) {
3327 		res = TEE_ERROR_BAD_PARAMETERS;
3328 		goto out;
3329 	}
3330 
3331 	switch (TEE_ALG_GET_MAIN_ALG(cs->algo)) {
3332 	case TEE_MAIN_ALGO_RSA:
3333 		tee_svc_asymm_pkcs1_get_salt_len(params, num_params, &salt_len);
3334 		if (!crypto_ops.acipher.rsassa_verify) {
3335 			res = TEE_ERROR_NOT_IMPLEMENTED;
3336 			break;
3337 		}
3338 		res = crypto_ops.acipher.rsassa_verify(cs->algo, o->data,
3339 						       salt_len, data,
3340 						       data_len, sig, sig_len);
3341 		break;
3342 
3343 	case TEE_MAIN_ALGO_DSA:
3344 		if (!crypto_ops.acipher.dsa_verify) {
3345 			res = TEE_ERROR_NOT_IMPLEMENTED;
3346 			break;
3347 		}
3348 		res = crypto_ops.acipher.dsa_verify(cs->algo, o->data, data,
3349 						    data_len, sig, sig_len);
3350 		break;
3351 
3352 	default:
3353 		res = TEE_ERROR_NOT_SUPPORTED;
3354 	}
3355 
3356 out:
3357 	free(params);
3358 	return res;
3359 }
3360