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