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