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