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