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