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