xref: /optee_os/core/tee/tee_svc_cryp.c (revision 6e909320d48bde26016da1086bc3d89b2df6a6bb)
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 ((TEE_ALG_GET_CHAIN_MODE(algo) == TEE_CHAIN_MODE_XTS &&
2627 		     (key1 == 0 || key2 == 0)) ||
2628 		    (TEE_ALG_GET_CHAIN_MODE(algo) != TEE_CHAIN_MODE_XTS &&
2629 		    (key1 == 0 || key2 != 0))) {
2630 			res = TEE_ERROR_BAD_PARAMETERS;
2631 		} else {
2632 			res = crypto_cipher_alloc_ctx(&cs->ctx, algo);
2633 			if (res != TEE_SUCCESS)
2634 				break;
2635 		}
2636 		break;
2637 	case TEE_OPERATION_AE:
2638 		if (key1 == 0 || key2 != 0) {
2639 			res = TEE_ERROR_BAD_PARAMETERS;
2640 		} else {
2641 			res = crypto_authenc_alloc_ctx(&cs->ctx, algo);
2642 			if (res != TEE_SUCCESS)
2643 				break;
2644 		}
2645 		break;
2646 	case TEE_OPERATION_MAC:
2647 		if (key1 == 0 || key2 != 0) {
2648 			res = TEE_ERROR_BAD_PARAMETERS;
2649 		} else {
2650 			res = crypto_mac_alloc_ctx(&cs->ctx, algo);
2651 			if (res != TEE_SUCCESS)
2652 				break;
2653 		}
2654 		break;
2655 	case TEE_OPERATION_DIGEST:
2656 		if (key1 != 0 || key2 != 0) {
2657 			res = TEE_ERROR_BAD_PARAMETERS;
2658 		} else {
2659 			res = crypto_hash_alloc_ctx(&cs->ctx, algo);
2660 			if (res != TEE_SUCCESS)
2661 				break;
2662 		}
2663 		break;
2664 	case TEE_OPERATION_ASYMMETRIC_CIPHER:
2665 	case TEE_OPERATION_ASYMMETRIC_SIGNATURE:
2666 		if (algo == TEE_ALG_RSASSA_PKCS1_V1_5 &&
2667 		    !IS_ENABLED(CFG_CRYPTO_RSASSA_NA1)) {
2668 			res = TEE_ERROR_NOT_SUPPORTED;
2669 			break;
2670 		}
2671 		if (key1 == 0 || key2 != 0)
2672 			res = TEE_ERROR_BAD_PARAMETERS;
2673 		break;
2674 	case TEE_OPERATION_KEY_DERIVATION:
2675 		if (algo == TEE_ALG_SM2_KEP) {
2676 			if (key1 == 0 || key2 == 0)
2677 				res = TEE_ERROR_BAD_PARAMETERS;
2678 		} else {
2679 			if (key1 == 0 || key2 != 0)
2680 				res = TEE_ERROR_BAD_PARAMETERS;
2681 		}
2682 		break;
2683 	default:
2684 		res = TEE_ERROR_NOT_SUPPORTED;
2685 		break;
2686 	}
2687 	if (res != TEE_SUCCESS)
2688 		goto out;
2689 
2690 	res = copy_kaddr_to_uref(state, cs);
2691 	if (res != TEE_SUCCESS)
2692 		goto out;
2693 
2694 	/* Register keys */
2695 	if (o1 != NULL) {
2696 		o1->busy = true;
2697 		cs->key1 = (vaddr_t)o1;
2698 	}
2699 	if (o2 != NULL) {
2700 		o2->busy = true;
2701 		cs->key2 = (vaddr_t)o2;
2702 	}
2703 
2704 out:
2705 	if (res != TEE_SUCCESS)
2706 		cryp_state_free(utc, cs);
2707 	return res;
2708 }
2709 
2710 TEE_Result syscall_cryp_state_copy(unsigned long dst, unsigned long src)
2711 {
2712 	struct ts_session *sess = ts_get_current_session();
2713 	TEE_Result res = TEE_SUCCESS;
2714 	struct tee_cryp_state *cs_dst = NULL;
2715 	struct tee_cryp_state *cs_src = NULL;
2716 
2717 	res = tee_svc_cryp_get_state(sess, uref_to_vaddr(dst), &cs_dst);
2718 	if (res != TEE_SUCCESS)
2719 		return res;
2720 
2721 	res = tee_svc_cryp_get_state(sess, uref_to_vaddr(src), &cs_src);
2722 	if (res != TEE_SUCCESS)
2723 		return res;
2724 	if (cs_dst->algo != cs_src->algo || cs_dst->mode != cs_src->mode)
2725 		return TEE_ERROR_BAD_PARAMETERS;
2726 
2727 	switch (TEE_ALG_GET_CLASS(cs_src->algo)) {
2728 	case TEE_OPERATION_CIPHER:
2729 		crypto_cipher_copy_state(cs_dst->ctx, cs_src->ctx);
2730 		break;
2731 	case TEE_OPERATION_AE:
2732 		crypto_authenc_copy_state(cs_dst->ctx, cs_src->ctx);
2733 		break;
2734 	case TEE_OPERATION_DIGEST:
2735 		crypto_hash_copy_state(cs_dst->ctx, cs_src->ctx);
2736 		break;
2737 	case TEE_OPERATION_MAC:
2738 		crypto_mac_copy_state(cs_dst->ctx, cs_src->ctx);
2739 		break;
2740 	default:
2741 		return TEE_ERROR_BAD_STATE;
2742 	}
2743 
2744 	cs_dst->state = cs_src->state;
2745 	cs_dst->ctx_finalize = cs_src->ctx_finalize;
2746 
2747 	return TEE_SUCCESS;
2748 }
2749 
2750 void tee_svc_cryp_free_states(struct user_ta_ctx *utc)
2751 {
2752 	struct tee_cryp_state_head *states = &utc->cryp_states;
2753 
2754 	while (!TAILQ_EMPTY(states))
2755 		cryp_state_free(utc, TAILQ_FIRST(states));
2756 }
2757 
2758 TEE_Result syscall_cryp_state_free(unsigned long state)
2759 {
2760 	struct ts_session *sess = ts_get_current_session();
2761 	TEE_Result res = TEE_SUCCESS;
2762 	struct tee_cryp_state *cs = NULL;
2763 
2764 	res = tee_svc_cryp_get_state(sess, uref_to_vaddr(state), &cs);
2765 	if (res != TEE_SUCCESS)
2766 		return res;
2767 	cryp_state_free(to_user_ta_ctx(sess->ctx), cs);
2768 	return TEE_SUCCESS;
2769 }
2770 
2771 TEE_Result syscall_hash_init(unsigned long state,
2772 			     const void *iv __maybe_unused,
2773 			     size_t iv_len __maybe_unused)
2774 {
2775 	struct ts_session *sess = ts_get_current_session();
2776 	TEE_Result res = TEE_SUCCESS;
2777 	struct tee_cryp_state *cs = NULL;
2778 
2779 	res = tee_svc_cryp_get_state(sess, uref_to_vaddr(state), &cs);
2780 	if (res != TEE_SUCCESS)
2781 		return res;
2782 
2783 	switch (TEE_ALG_GET_CLASS(cs->algo)) {
2784 	case TEE_OPERATION_DIGEST:
2785 		res = crypto_hash_init(cs->ctx);
2786 		if (res != TEE_SUCCESS)
2787 			return res;
2788 		break;
2789 	case TEE_OPERATION_MAC:
2790 		{
2791 			struct tee_obj *o;
2792 			struct tee_cryp_obj_secret *key;
2793 
2794 			res = tee_obj_get(to_user_ta_ctx(sess->ctx),
2795 					  cs->key1, &o);
2796 			if (res != TEE_SUCCESS)
2797 				return res;
2798 			if ((o->info.handleFlags &
2799 			     TEE_HANDLE_FLAG_INITIALIZED) == 0)
2800 				return TEE_ERROR_BAD_PARAMETERS;
2801 
2802 			key = (struct tee_cryp_obj_secret *)o->attr;
2803 			res = crypto_mac_init(cs->ctx, (void *)(key + 1),
2804 					      key->key_size);
2805 			if (res != TEE_SUCCESS)
2806 				return res;
2807 			break;
2808 		}
2809 	default:
2810 		return TEE_ERROR_BAD_PARAMETERS;
2811 	}
2812 
2813 	cs->state = CRYP_STATE_INITIALIZED;
2814 
2815 	return TEE_SUCCESS;
2816 }
2817 
2818 TEE_Result syscall_hash_update(unsigned long state, const void *chunk,
2819 			size_t chunk_size)
2820 {
2821 	struct ts_session *sess = ts_get_current_session();
2822 	struct tee_cryp_state *cs = NULL;
2823 	TEE_Result res = TEE_SUCCESS;
2824 
2825 	/* No data, but size provided isn't valid parameters. */
2826 	if (!chunk && chunk_size)
2827 		return TEE_ERROR_BAD_PARAMETERS;
2828 
2829 	/* Zero length hash is valid, but nothing we need to do. */
2830 	if (!chunk_size)
2831 		return TEE_SUCCESS;
2832 
2833 	chunk = memtag_strip_tag_const(chunk);
2834 
2835 	res = vm_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
2836 				     TEE_MEMORY_ACCESS_READ |
2837 				     TEE_MEMORY_ACCESS_ANY_OWNER,
2838 				     (uaddr_t)chunk, chunk_size);
2839 	if (res != TEE_SUCCESS)
2840 		return res;
2841 
2842 	res = tee_svc_cryp_get_state(sess, uref_to_vaddr(state), &cs);
2843 	if (res != TEE_SUCCESS)
2844 		return res;
2845 
2846 	if (cs->state != CRYP_STATE_INITIALIZED)
2847 		return TEE_ERROR_BAD_STATE;
2848 
2849 	switch (TEE_ALG_GET_CLASS(cs->algo)) {
2850 	case TEE_OPERATION_DIGEST:
2851 		res = crypto_hash_update(cs->ctx, chunk, chunk_size);
2852 		if (res != TEE_SUCCESS)
2853 			return res;
2854 		break;
2855 	case TEE_OPERATION_MAC:
2856 		res = crypto_mac_update(cs->ctx, chunk, chunk_size);
2857 		if (res != TEE_SUCCESS)
2858 			return res;
2859 		break;
2860 	default:
2861 		return TEE_ERROR_BAD_PARAMETERS;
2862 	}
2863 
2864 	return TEE_SUCCESS;
2865 }
2866 
2867 TEE_Result syscall_hash_final(unsigned long state, const void *chunk,
2868 			size_t chunk_size, void *hash, uint64_t *hash_len)
2869 {
2870 	struct ts_session *sess = ts_get_current_session();
2871 	struct tee_cryp_state *cs = NULL;
2872 	TEE_Result res2 = TEE_SUCCESS;
2873 	TEE_Result res = TEE_SUCCESS;
2874 	size_t hash_size = 0;
2875 	size_t hlen = 0;
2876 
2877 	/* No data, but size provided isn't valid parameters. */
2878 	if (!chunk && chunk_size)
2879 		return TEE_ERROR_BAD_PARAMETERS;
2880 
2881 	chunk = memtag_strip_tag_const(chunk);
2882 	hash = memtag_strip_tag(hash);
2883 
2884 	res = vm_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
2885 				     TEE_MEMORY_ACCESS_READ |
2886 				     TEE_MEMORY_ACCESS_ANY_OWNER,
2887 				     (uaddr_t)chunk, chunk_size);
2888 	if (res != TEE_SUCCESS)
2889 		return res;
2890 
2891 	res = get_user_u64_as_size_t(&hlen, hash_len);
2892 	if (res != TEE_SUCCESS)
2893 		return res;
2894 
2895 	res = vm_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
2896 				     TEE_MEMORY_ACCESS_READ |
2897 				     TEE_MEMORY_ACCESS_WRITE |
2898 				     TEE_MEMORY_ACCESS_ANY_OWNER,
2899 				     (uaddr_t)hash, hlen);
2900 	if (res != TEE_SUCCESS)
2901 		return res;
2902 
2903 	res = tee_svc_cryp_get_state(sess, uref_to_vaddr(state), &cs);
2904 	if (res != TEE_SUCCESS)
2905 		return res;
2906 
2907 	if (cs->state != CRYP_STATE_INITIALIZED)
2908 		return TEE_ERROR_BAD_STATE;
2909 
2910 	switch (TEE_ALG_GET_CLASS(cs->algo)) {
2911 	case TEE_OPERATION_DIGEST:
2912 		res = tee_alg_get_digest_size(cs->algo, &hash_size);
2913 		if (res != TEE_SUCCESS)
2914 			return res;
2915 		if (hlen < hash_size) {
2916 			res = TEE_ERROR_SHORT_BUFFER;
2917 			goto out;
2918 		}
2919 
2920 		if (chunk_size) {
2921 			res = crypto_hash_update(cs->ctx, chunk, chunk_size);
2922 			if (res != TEE_SUCCESS)
2923 				return res;
2924 		}
2925 
2926 		res = crypto_hash_final(cs->ctx, hash, hash_size);
2927 		if (res != TEE_SUCCESS)
2928 			return res;
2929 		break;
2930 
2931 	case TEE_OPERATION_MAC:
2932 		res = tee_alg_get_digest_size(cs->algo, &hash_size);
2933 		if (res != TEE_SUCCESS)
2934 			return res;
2935 		if (hlen < hash_size) {
2936 			res = TEE_ERROR_SHORT_BUFFER;
2937 			goto out;
2938 		}
2939 
2940 		if (chunk_size) {
2941 			res = crypto_mac_update(cs->ctx, chunk, chunk_size);
2942 			if (res != TEE_SUCCESS)
2943 				return res;
2944 		}
2945 
2946 		res = crypto_mac_final(cs->ctx, hash, hash_size);
2947 		if (res != TEE_SUCCESS)
2948 			return res;
2949 		break;
2950 
2951 	default:
2952 		return TEE_ERROR_BAD_PARAMETERS;
2953 	}
2954 out:
2955 	res2 = put_user_u64(hash_len, hash_size);
2956 	if (res2 != TEE_SUCCESS)
2957 		return res2;
2958 	return res;
2959 }
2960 
2961 TEE_Result syscall_cipher_init(unsigned long state, const void *iv,
2962 			size_t iv_len)
2963 {
2964 	struct ts_session *sess = ts_get_current_session();
2965 	struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx);
2966 	struct tee_cryp_obj_secret *key1 = NULL;
2967 	struct tee_cryp_state *cs = NULL;
2968 	TEE_Result res = TEE_SUCCESS;
2969 	struct tee_obj *o = NULL;
2970 
2971 	res = tee_svc_cryp_get_state(sess, uref_to_vaddr(state), &cs);
2972 	if (res != TEE_SUCCESS)
2973 		return res;
2974 
2975 	if (TEE_ALG_GET_CLASS(cs->algo) != TEE_OPERATION_CIPHER)
2976 		return TEE_ERROR_BAD_STATE;
2977 
2978 	iv = memtag_strip_tag_const(iv);
2979 
2980 	res = vm_check_access_rights(&utc->uctx,
2981 				     TEE_MEMORY_ACCESS_READ |
2982 				     TEE_MEMORY_ACCESS_ANY_OWNER,
2983 				     (uaddr_t)iv, iv_len);
2984 	if (res != TEE_SUCCESS)
2985 		return res;
2986 
2987 	res = tee_obj_get(utc, cs->key1, &o);
2988 	if (res != TEE_SUCCESS)
2989 		return res;
2990 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
2991 		return TEE_ERROR_BAD_PARAMETERS;
2992 
2993 	key1 = o->attr;
2994 
2995 	if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) {
2996 		struct tee_cryp_obj_secret *key2 = o->attr;
2997 
2998 		if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
2999 			return TEE_ERROR_BAD_PARAMETERS;
3000 
3001 		res = crypto_cipher_init(cs->ctx, cs->mode,
3002 					 (uint8_t *)(key1 + 1), key1->key_size,
3003 					 (uint8_t *)(key2 + 1), key2->key_size,
3004 					 iv, iv_len);
3005 	} else {
3006 		res = crypto_cipher_init(cs->ctx, cs->mode,
3007 					 (uint8_t *)(key1 + 1), key1->key_size,
3008 					 NULL, 0, iv, iv_len);
3009 	}
3010 	if (res != TEE_SUCCESS)
3011 		return res;
3012 
3013 	cs->ctx_finalize = crypto_cipher_final;
3014 	cs->state = CRYP_STATE_INITIALIZED;
3015 
3016 	return TEE_SUCCESS;
3017 }
3018 
3019 static TEE_Result tee_svc_cipher_update_helper(unsigned long state,
3020 			bool last_block, const void *src, size_t src_len,
3021 			void *dst, uint64_t *dst_len)
3022 {
3023 	struct ts_session *sess = ts_get_current_session();
3024 	struct tee_cryp_state *cs = NULL;
3025 	TEE_Result res = TEE_SUCCESS;
3026 	size_t dlen = 0;
3027 
3028 	res = tee_svc_cryp_get_state(sess, uref_to_vaddr(state), &cs);
3029 	if (res != TEE_SUCCESS)
3030 		return res;
3031 
3032 	if (cs->state != CRYP_STATE_INITIALIZED)
3033 		return TEE_ERROR_BAD_STATE;
3034 
3035 	src = memtag_strip_tag_const(src);
3036 	dst = memtag_strip_tag(dst);
3037 
3038 	res = vm_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
3039 				     TEE_MEMORY_ACCESS_READ |
3040 				     TEE_MEMORY_ACCESS_ANY_OWNER,
3041 				     (uaddr_t)src, src_len);
3042 	if (res != TEE_SUCCESS)
3043 		return res;
3044 
3045 	if (!dst_len) {
3046 		dlen = 0;
3047 	} else {
3048 		struct user_mode_ctx *uctx = &to_user_ta_ctx(sess->ctx)->uctx;
3049 		uint32_t flags = TEE_MEMORY_ACCESS_READ |
3050 				 TEE_MEMORY_ACCESS_WRITE |
3051 				 TEE_MEMORY_ACCESS_ANY_OWNER;
3052 
3053 		res = get_user_u64_as_size_t(&dlen, dst_len);
3054 		if (res != TEE_SUCCESS)
3055 			return res;
3056 
3057 		res = vm_check_access_rights(uctx, flags, (uaddr_t)dst, dlen);
3058 		if (res != TEE_SUCCESS)
3059 			return res;
3060 	}
3061 
3062 	if (dlen < src_len) {
3063 		res = TEE_ERROR_SHORT_BUFFER;
3064 		goto out;
3065 	}
3066 
3067 	if (src_len > 0) {
3068 		/* Permit src_len == 0 to finalize the operation */
3069 		res = tee_do_cipher_update(cs->ctx, cs->algo, cs->mode,
3070 					   last_block, src, src_len, dst);
3071 	}
3072 
3073 	if (last_block && cs->ctx_finalize != NULL) {
3074 		cs->ctx_finalize(cs->ctx);
3075 		cs->ctx_finalize = NULL;
3076 	}
3077 
3078 out:
3079 	if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) &&
3080 	    dst_len != NULL) {
3081 		TEE_Result res2;
3082 
3083 		res2 = put_user_u64(dst_len, src_len);
3084 		if (res2 != TEE_SUCCESS)
3085 			res = res2;
3086 	}
3087 
3088 	return res;
3089 }
3090 
3091 TEE_Result syscall_cipher_update(unsigned long state, const void *src,
3092 			size_t src_len, void *dst, uint64_t *dst_len)
3093 {
3094 	return tee_svc_cipher_update_helper(state, false /* last_block */,
3095 					    src, src_len, dst, dst_len);
3096 }
3097 
3098 TEE_Result syscall_cipher_final(unsigned long state, const void *src,
3099 			size_t src_len, void *dst, uint64_t *dst_len)
3100 {
3101 	return tee_svc_cipher_update_helper(state, true /* last_block */,
3102 					    src, src_len, dst, dst_len);
3103 }
3104 
3105 #if defined(CFG_CRYPTO_HKDF)
3106 static TEE_Result get_hkdf_params(const TEE_Attribute *params,
3107 				  uint32_t param_count,
3108 				  void **salt, size_t *salt_len, void **info,
3109 				  size_t *info_len, size_t *okm_len)
3110 {
3111 	size_t n;
3112 	enum { SALT = 0x1, LENGTH = 0x2, INFO = 0x4 };
3113 	uint8_t found = 0;
3114 
3115 	*salt = *info = NULL;
3116 	*salt_len = *info_len = *okm_len = 0;
3117 
3118 	for (n = 0; n < param_count; n++) {
3119 		switch (params[n].attributeID) {
3120 		case TEE_ATTR_HKDF_SALT:
3121 			if (!(found & SALT)) {
3122 				*salt = params[n].content.ref.buffer;
3123 				*salt_len = params[n].content.ref.length;
3124 				found |= SALT;
3125 			}
3126 			break;
3127 		case TEE_ATTR_HKDF_OKM_LENGTH:
3128 			if (!(found & LENGTH)) {
3129 				*okm_len = params[n].content.value.a;
3130 				found |= LENGTH;
3131 			}
3132 			break;
3133 		case TEE_ATTR_HKDF_INFO:
3134 			if (!(found & INFO)) {
3135 				*info = params[n].content.ref.buffer;
3136 				*info_len = params[n].content.ref.length;
3137 				found |= INFO;
3138 			}
3139 			break;
3140 		default:
3141 			/* Unexpected attribute */
3142 			return TEE_ERROR_BAD_PARAMETERS;
3143 		}
3144 
3145 	}
3146 
3147 	if (!(found & LENGTH))
3148 		return TEE_ERROR_BAD_PARAMETERS;
3149 
3150 	return TEE_SUCCESS;
3151 }
3152 #endif
3153 
3154 #if defined(CFG_CRYPTO_CONCAT_KDF)
3155 static TEE_Result get_concat_kdf_params(const TEE_Attribute *params,
3156 					uint32_t param_count,
3157 					void **other_info,
3158 					size_t *other_info_len,
3159 					size_t *derived_key_len)
3160 {
3161 	size_t n;
3162 	enum { LENGTH = 0x1, INFO = 0x2 };
3163 	uint8_t found = 0;
3164 
3165 	*other_info = NULL;
3166 	*other_info_len = *derived_key_len = 0;
3167 
3168 	for (n = 0; n < param_count; n++) {
3169 		switch (params[n].attributeID) {
3170 		case TEE_ATTR_CONCAT_KDF_OTHER_INFO:
3171 			if (!(found & INFO)) {
3172 				*other_info = params[n].content.ref.buffer;
3173 				*other_info_len = params[n].content.ref.length;
3174 				found |= INFO;
3175 			}
3176 			break;
3177 		case TEE_ATTR_CONCAT_KDF_DKM_LENGTH:
3178 			if (!(found & LENGTH)) {
3179 				*derived_key_len = params[n].content.value.a;
3180 				found |= LENGTH;
3181 			}
3182 			break;
3183 		default:
3184 			/* Unexpected attribute */
3185 			return TEE_ERROR_BAD_PARAMETERS;
3186 		}
3187 	}
3188 
3189 	if (!(found & LENGTH))
3190 		return TEE_ERROR_BAD_PARAMETERS;
3191 
3192 	return TEE_SUCCESS;
3193 }
3194 #endif
3195 
3196 #if defined(CFG_CRYPTO_PBKDF2)
3197 static TEE_Result get_pbkdf2_params(const TEE_Attribute *params,
3198 				   uint32_t param_count, void **salt,
3199 				   size_t *salt_len, size_t *derived_key_len,
3200 				   size_t *iteration_count)
3201 {
3202 	size_t n;
3203 	enum { SALT = 0x1, LENGTH = 0x2, COUNT = 0x4 };
3204 	uint8_t found = 0;
3205 
3206 	*salt = NULL;
3207 	*salt_len = *derived_key_len = *iteration_count = 0;
3208 
3209 	for (n = 0; n < param_count; n++) {
3210 		switch (params[n].attributeID) {
3211 		case TEE_ATTR_PBKDF2_SALT:
3212 			if (!(found & SALT)) {
3213 				*salt = params[n].content.ref.buffer;
3214 				*salt_len = params[n].content.ref.length;
3215 				found |= SALT;
3216 			}
3217 			break;
3218 		case TEE_ATTR_PBKDF2_DKM_LENGTH:
3219 			if (!(found & LENGTH)) {
3220 				*derived_key_len = params[n].content.value.a;
3221 				found |= LENGTH;
3222 			}
3223 			break;
3224 		case TEE_ATTR_PBKDF2_ITERATION_COUNT:
3225 			if (!(found & COUNT)) {
3226 				*iteration_count = params[n].content.value.a;
3227 				found |= COUNT;
3228 			}
3229 			break;
3230 		default:
3231 			/* Unexpected attribute */
3232 			return TEE_ERROR_BAD_PARAMETERS;
3233 		}
3234 	}
3235 
3236 	if ((found & (LENGTH|COUNT)) != (LENGTH|COUNT))
3237 		return TEE_ERROR_BAD_PARAMETERS;
3238 
3239 	return TEE_SUCCESS;
3240 }
3241 #endif
3242 
3243 #if defined(CFG_CRYPTO_SM2_KEP)
3244 static TEE_Result get_sm2_kep_params(const TEE_Attribute *params,
3245 				     uint32_t param_count,
3246 				     struct ecc_public_key *peer_key,
3247 				     struct ecc_public_key *peer_eph_key,
3248 				     struct sm2_kep_parms *kep_parms)
3249 {
3250 	TEE_Result res = TEE_ERROR_GENERIC;
3251 	size_t n;
3252 	enum {
3253 		IS_INITIATOR,
3254 		PEER_KEY_X,
3255 		PEER_KEY_Y,
3256 		PEER_EPH_KEY_X,
3257 		PEER_EPH_KEY_Y,
3258 		INITIATOR_ID,
3259 		RESPONDER_ID,
3260 	};
3261 	uint8_t mandatory = BIT(IS_INITIATOR) | BIT(PEER_KEY_X) |
3262 		BIT(PEER_KEY_Y) | BIT(PEER_EPH_KEY_X) | BIT(PEER_EPH_KEY_Y) |
3263 		BIT(INITIATOR_ID) | BIT(RESPONDER_ID);
3264 	uint8_t found = 0;
3265 
3266 	res = crypto_acipher_alloc_ecc_public_key(peer_key,
3267 						  TEE_TYPE_SM2_KEP_PUBLIC_KEY,
3268 						  256);
3269 	if (res)
3270 		return res;
3271 
3272 	res = crypto_acipher_alloc_ecc_public_key(peer_eph_key,
3273 						  TEE_TYPE_SM2_KEP_PUBLIC_KEY,
3274 						  256);
3275 	if (res)
3276 		goto out_p;
3277 
3278 	peer_key->curve = TEE_ECC_CURVE_SM2;
3279 	peer_eph_key->curve = TEE_ECC_CURVE_SM2;
3280 
3281 	for (n = 0; n < param_count; n++) {
3282 		const TEE_Attribute *p = &params[n];
3283 
3284 		switch (p->attributeID) {
3285 		case TEE_ATTR_SM2_KEP_USER:
3286 			kep_parms->is_initiator = !p->content.value.a;
3287 			found |= BIT(IS_INITIATOR);
3288 			break;
3289 		case TEE_ATTR_ECC_PUBLIC_VALUE_X:
3290 			crypto_bignum_bin2bn(p->content.ref.buffer,
3291 					     p->content.ref.length,
3292 					     peer_key->x);
3293 			found |= BIT(PEER_KEY_X);
3294 			break;
3295 		case TEE_ATTR_ECC_PUBLIC_VALUE_Y:
3296 			crypto_bignum_bin2bn(p->content.ref.buffer,
3297 					     p->content.ref.length,
3298 					     peer_key->y);
3299 			found |= BIT(PEER_KEY_Y);
3300 			break;
3301 		case __OPTEE_SM2_KEP_ATTR_ECC_EPHEMERAL_PUBLIC_VALUE_X:
3302 		case TEE_ATTR_ECC_EPHEMERAL_PUBLIC_VALUE_X:
3303 			crypto_bignum_bin2bn(p->content.ref.buffer,
3304 					     p->content.ref.length,
3305 					     peer_eph_key->x);
3306 			found |= BIT(PEER_EPH_KEY_X);
3307 			break;
3308 		case __OPTEE_SM2_KEP_ATTR_ECC_EPHEMERAL_PUBLIC_VALUE_Y:
3309 		case TEE_ATTR_ECC_EPHEMERAL_PUBLIC_VALUE_Y:
3310 			crypto_bignum_bin2bn(p->content.ref.buffer,
3311 					     p->content.ref.length,
3312 					     peer_eph_key->y);
3313 			found |= BIT(PEER_EPH_KEY_Y);
3314 			break;
3315 		case TEE_ATTR_SM2_ID_INITIATOR:
3316 			kep_parms->initiator_id = p->content.ref.buffer;
3317 			kep_parms->initiator_id_len = p->content.ref.length;
3318 			found |= BIT(INITIATOR_ID);
3319 			break;
3320 		case TEE_ATTR_SM2_ID_RESPONDER:
3321 			kep_parms->responder_id = p->content.ref.buffer;
3322 			kep_parms->responder_id_len = p->content.ref.length;
3323 			found |= BIT(RESPONDER_ID);
3324 			break;
3325 		case TEE_ATTR_SM2_KEP_CONFIRMATION_IN:
3326 			kep_parms->conf_in = p->content.ref.buffer;
3327 			kep_parms->conf_in_len = p->content.ref.length;
3328 			break;
3329 		case TEE_ATTR_SM2_KEP_CONFIRMATION_OUT:
3330 			kep_parms->conf_out = p->content.ref.buffer;
3331 			kep_parms->conf_out_len = p->content.ref.length;
3332 			break;
3333 		default:
3334 			/* Unexpected attribute */
3335 			res = TEE_ERROR_BAD_PARAMETERS;
3336 			goto out;
3337 		}
3338 	}
3339 
3340 	if ((found & mandatory) != mandatory) {
3341 		res = TEE_ERROR_BAD_PARAMETERS;
3342 		goto out;
3343 	}
3344 
3345 	return TEE_SUCCESS;
3346 out:
3347 	crypto_acipher_free_ecc_public_key(peer_eph_key);
3348 out_p:
3349 	crypto_acipher_free_ecc_public_key(peer_key);
3350 	return res;
3351 }
3352 #endif
3353 
3354 TEE_Result syscall_cryp_derive_key(unsigned long state,
3355 			const struct utee_attribute *usr_params,
3356 			unsigned long param_count, unsigned long derived_key)
3357 {
3358 	struct ts_session *sess = ts_get_current_session();
3359 	struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx);
3360 	TEE_Result res = TEE_ERROR_NOT_SUPPORTED;
3361 	struct tee_obj *ko = NULL;
3362 	struct tee_obj *so = NULL;
3363 	struct tee_cryp_state *cs = NULL;
3364 	struct tee_cryp_obj_secret *sk = NULL;
3365 	const struct tee_cryp_obj_type_props *type_props = NULL;
3366 	TEE_Attribute *params = NULL;
3367 	size_t alloc_size = 0;
3368 
3369 	res = tee_svc_cryp_get_state(sess, uref_to_vaddr(state), &cs);
3370 	if (res != TEE_SUCCESS)
3371 		return res;
3372 
3373 	if (MUL_OVERFLOW(sizeof(TEE_Attribute), param_count, &alloc_size))
3374 		return TEE_ERROR_OVERFLOW;
3375 
3376 	params = malloc(alloc_size);
3377 	if (!params)
3378 		return TEE_ERROR_OUT_OF_MEMORY;
3379 	res = copy_in_attrs(utc, usr_params, param_count, params);
3380 	if (res != TEE_SUCCESS)
3381 		goto out;
3382 
3383 	/* Get key set in operation */
3384 	res = tee_obj_get(utc, cs->key1, &ko);
3385 	if (res != TEE_SUCCESS)
3386 		goto out;
3387 
3388 	res = tee_obj_get(utc, uref_to_vaddr(derived_key), &so);
3389 	if (res != TEE_SUCCESS)
3390 		goto out;
3391 
3392 	/* Find information needed about the object to initialize */
3393 	sk = so->attr;
3394 
3395 	/* Find description of object */
3396 	type_props = tee_svc_find_type_props(so->info.objectType);
3397 	if (!type_props) {
3398 		res = TEE_ERROR_NOT_SUPPORTED;
3399 		goto out;
3400 	}
3401 
3402 	if (cs->algo == TEE_ALG_DH_DERIVE_SHARED_SECRET) {
3403 		struct bignum *pub = NULL;
3404 		struct bignum *ss = NULL;
3405 		size_t bin_size = 0;
3406 
3407 		if (param_count != 1 ||
3408 		    params[0].attributeID != TEE_ATTR_DH_PUBLIC_VALUE) {
3409 			res = TEE_ERROR_BAD_PARAMETERS;
3410 			goto out;
3411 		}
3412 
3413 		bin_size = params[0].content.ref.length;
3414 
3415 		if (MUL_OVERFLOW(bin_size, 8, &alloc_size)) {
3416 			res = TEE_ERROR_OVERFLOW;
3417 			goto out;
3418 		}
3419 
3420 		pub = crypto_bignum_allocate(alloc_size);
3421 		ss = crypto_bignum_allocate(alloc_size);
3422 		if (pub && ss) {
3423 			crypto_bignum_bin2bn(params[0].content.ref.buffer,
3424 					     bin_size, pub);
3425 			res = crypto_acipher_dh_shared_secret(ko->attr,
3426 							      pub, ss);
3427 			if (res == TEE_SUCCESS) {
3428 				sk->key_size = crypto_bignum_num_bytes(ss);
3429 				crypto_bignum_bn2bin(ss, (uint8_t *)(sk + 1));
3430 				so->info.handleFlags |=
3431 						TEE_HANDLE_FLAG_INITIALIZED;
3432 				set_attribute(so, type_props,
3433 					      TEE_ATTR_SECRET_VALUE);
3434 			}
3435 		} else {
3436 			res = TEE_ERROR_OUT_OF_MEMORY;
3437 		}
3438 		crypto_bignum_free(pub);
3439 		crypto_bignum_free(ss);
3440 	} else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_ECDH) {
3441 		struct ecc_public_key key_public;
3442 		uint8_t *pt_secret;
3443 		unsigned long pt_secret_len;
3444 		uint32_t key_type = TEE_TYPE_ECDH_PUBLIC_KEY;
3445 
3446 		if (param_count != 2 ||
3447 		    params[0].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_X ||
3448 		    params[1].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_Y) {
3449 			res = TEE_ERROR_BAD_PARAMETERS;
3450 			goto out;
3451 		}
3452 
3453 		switch (cs->algo) {
3454 		case TEE_ALG_ECDH_P192:
3455 			alloc_size = 192;
3456 			break;
3457 		case TEE_ALG_ECDH_P224:
3458 			alloc_size = 224;
3459 			break;
3460 		case TEE_ALG_ECDH_P256:
3461 			alloc_size = 256;
3462 			break;
3463 		case TEE_ALG_ECDH_P384:
3464 			alloc_size = 384;
3465 			break;
3466 		case TEE_ALG_ECDH_P521:
3467 			alloc_size = 521;
3468 			break;
3469 		default:
3470 			res = TEE_ERROR_NOT_IMPLEMENTED;
3471 			goto out;
3472 		}
3473 
3474 		/* Create the public key */
3475 		res = crypto_acipher_alloc_ecc_public_key(&key_public, key_type,
3476 							  alloc_size);
3477 		if (res != TEE_SUCCESS)
3478 			goto out;
3479 		key_public.curve = ((struct ecc_keypair *)ko->attr)->curve;
3480 		crypto_bignum_bin2bn(params[0].content.ref.buffer,
3481 				     params[0].content.ref.length,
3482 				     key_public.x);
3483 		crypto_bignum_bin2bn(params[1].content.ref.buffer,
3484 				     params[1].content.ref.length,
3485 				     key_public.y);
3486 
3487 		pt_secret = (uint8_t *)(sk + 1);
3488 		pt_secret_len = sk->alloc_size;
3489 		res = crypto_acipher_ecc_shared_secret(ko->attr, &key_public,
3490 						       pt_secret,
3491 						       &pt_secret_len);
3492 
3493 		if (res == TEE_SUCCESS) {
3494 			sk->key_size = pt_secret_len;
3495 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
3496 			set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
3497 		}
3498 
3499 		/* free the public key */
3500 		crypto_acipher_free_ecc_public_key(&key_public);
3501 	}
3502 #if defined(CFG_CRYPTO_HKDF)
3503 	else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_HKDF) {
3504 		void *salt, *info;
3505 		size_t salt_len, info_len, okm_len;
3506 		uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
3507 		struct tee_cryp_obj_secret *ik = ko->attr;
3508 		const uint8_t *ikm = (const uint8_t *)(ik + 1);
3509 
3510 		res = get_hkdf_params(params, param_count, &salt, &salt_len,
3511 				      &info, &info_len, &okm_len);
3512 		if (res != TEE_SUCCESS)
3513 			goto out;
3514 
3515 		/* Requested size must fit into the output object's buffer */
3516 		if (okm_len > ik->alloc_size) {
3517 			res = TEE_ERROR_BAD_PARAMETERS;
3518 			goto out;
3519 		}
3520 
3521 		res = tee_cryp_hkdf(hash_id, ikm, ik->key_size, salt, salt_len,
3522 				    info, info_len, (uint8_t *)(sk + 1),
3523 				    okm_len);
3524 		if (res == TEE_SUCCESS) {
3525 			sk->key_size = okm_len;
3526 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
3527 			set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
3528 		}
3529 	}
3530 #endif
3531 #if defined(CFG_CRYPTO_CONCAT_KDF)
3532 	else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_CONCAT_KDF) {
3533 		void *info;
3534 		size_t info_len, derived_key_len;
3535 		uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
3536 		struct tee_cryp_obj_secret *ss = ko->attr;
3537 		const uint8_t *shared_secret = (const uint8_t *)(ss + 1);
3538 
3539 		res = get_concat_kdf_params(params, param_count, &info,
3540 					    &info_len, &derived_key_len);
3541 		if (res != TEE_SUCCESS)
3542 			goto out;
3543 
3544 		/* Requested size must fit into the output object's buffer */
3545 		if (derived_key_len > ss->alloc_size) {
3546 			res = TEE_ERROR_BAD_PARAMETERS;
3547 			goto out;
3548 		}
3549 
3550 		res = tee_cryp_concat_kdf(hash_id, shared_secret, ss->key_size,
3551 					  info, info_len, (uint8_t *)(sk + 1),
3552 					  derived_key_len);
3553 		if (res == TEE_SUCCESS) {
3554 			sk->key_size = derived_key_len;
3555 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
3556 			set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
3557 		}
3558 	}
3559 #endif
3560 #if defined(CFG_CRYPTO_PBKDF2)
3561 	else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_PBKDF2) {
3562 		void *salt;
3563 		size_t salt_len, iteration_count, derived_key_len;
3564 		uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
3565 		struct tee_cryp_obj_secret *ss = ko->attr;
3566 		const uint8_t *password = (const uint8_t *)(ss + 1);
3567 
3568 		res = get_pbkdf2_params(params, param_count, &salt, &salt_len,
3569 					&derived_key_len, &iteration_count);
3570 		if (res != TEE_SUCCESS)
3571 			goto out;
3572 
3573 		/* Requested size must fit into the output object's buffer */
3574 		if (derived_key_len > ss->alloc_size) {
3575 			res = TEE_ERROR_BAD_PARAMETERS;
3576 			goto out;
3577 		}
3578 
3579 		res = tee_cryp_pbkdf2(hash_id, password, ss->key_size, salt,
3580 				      salt_len, iteration_count,
3581 				      (uint8_t *)(sk + 1), derived_key_len);
3582 		if (res == TEE_SUCCESS) {
3583 			sk->key_size = derived_key_len;
3584 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
3585 			set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
3586 		}
3587 	}
3588 #endif
3589 #if defined(CFG_CRYPTO_SM2_KEP)
3590 	else if (cs->algo == TEE_ALG_SM2_KEP) {
3591 		struct ecc_public_key peer_eph_key = { };
3592 		struct ecc_public_key peer_key = { };
3593 		struct sm2_kep_parms kep_parms = {
3594 			.out = (uint8_t *)(sk + 1),
3595 			.out_len = so->info.maxObjectSize,
3596 		};
3597 		struct tee_obj *ko2 = NULL;
3598 
3599 		res = tee_obj_get(utc, cs->key2, &ko2);
3600 		if (res != TEE_SUCCESS)
3601 			goto out;
3602 
3603 		res = get_sm2_kep_params(params, param_count, &peer_key,
3604 					 &peer_eph_key, &kep_parms);
3605 		if (res != TEE_SUCCESS)
3606 			goto out;
3607 
3608 		/*
3609 		 * key1 is our private keypair, key2 is our ephemeral public key
3610 		 */
3611 		res = crypto_acipher_sm2_kep_derive(ko->attr, /* key1 */
3612 						    ko2->attr, /* key2 */
3613 						    &peer_key, &peer_eph_key,
3614 						    &kep_parms);
3615 
3616 		if (res == TEE_SUCCESS) {
3617 			sk->key_size = kep_parms.out_len;
3618 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
3619 			set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
3620 		}
3621 		crypto_acipher_free_ecc_public_key(&peer_key);
3622 		crypto_acipher_free_ecc_public_key(&peer_eph_key);
3623 	}
3624 #endif
3625 #if defined(CFG_CRYPTO_X25519)
3626 	else if (cs->algo == TEE_ALG_X25519) {
3627 		uint8_t *x25519_pub_key = NULL;
3628 		uint8_t *pt_secret = NULL;
3629 		unsigned long pt_secret_len = 0;
3630 
3631 		if (param_count != 1 ||
3632 		    params[0].attributeID != TEE_ATTR_X25519_PUBLIC_VALUE) {
3633 			res = TEE_ERROR_BAD_PARAMETERS;
3634 			goto out;
3635 		}
3636 
3637 		/* X25519 public key size is 32 bytes */
3638 		if (params[0].content.ref.length != KEY_SIZE_BYTES_25519) {
3639 			res = TEE_ERROR_BAD_PARAMETERS;
3640 			goto out;
3641 		}
3642 
3643 		/* Set the public key */
3644 		x25519_pub_key = params[0].content.ref.buffer;
3645 
3646 		pt_secret = (uint8_t *)(sk + 1);
3647 		pt_secret_len = sk->alloc_size;
3648 		res = crypto_acipher_x25519_shared_secret(ko->attr,
3649 							  x25519_pub_key,
3650 							  pt_secret,
3651 							  &pt_secret_len);
3652 
3653 		if (res == TEE_SUCCESS) {
3654 			sk->key_size = pt_secret_len;
3655 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
3656 			set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
3657 		}
3658 	}
3659 #endif
3660 	else
3661 		res = TEE_ERROR_NOT_SUPPORTED;
3662 
3663 out:
3664 	free_wipe(params);
3665 	return res;
3666 }
3667 
3668 TEE_Result syscall_cryp_random_number_generate(void *buf, size_t blen)
3669 {
3670 	struct ts_session *sess = ts_get_current_session();
3671 	TEE_Result res = TEE_SUCCESS;
3672 
3673 	buf = memtag_strip_tag(buf);
3674 
3675 	res = vm_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
3676 				     TEE_MEMORY_ACCESS_WRITE,
3677 				     (uaddr_t)buf, blen);
3678 	if (res != TEE_SUCCESS)
3679 		return res;
3680 
3681 	res = crypto_rng_read(buf, blen);
3682 	if (res != TEE_SUCCESS)
3683 		return res;
3684 
3685 	return res;
3686 }
3687 
3688 TEE_Result syscall_authenc_init(unsigned long state, const void *nonce,
3689 				size_t nonce_len, size_t tag_len,
3690 				size_t aad_len, size_t payload_len)
3691 {
3692 	struct ts_session *sess = ts_get_current_session();
3693 	struct tee_cryp_obj_secret *key = NULL;
3694 	struct tee_cryp_state *cs = NULL;
3695 	TEE_Result res = TEE_SUCCESS;
3696 	struct tee_obj *o = NULL;
3697 
3698 	nonce = memtag_strip_tag_const(nonce);
3699 
3700 	res = vm_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
3701 				     TEE_MEMORY_ACCESS_READ |
3702 				     TEE_MEMORY_ACCESS_ANY_OWNER,
3703 				     (uaddr_t)nonce, nonce_len);
3704 	if (res != TEE_SUCCESS)
3705 		return res;
3706 
3707 	res = tee_svc_cryp_get_state(sess, uref_to_vaddr(state), &cs);
3708 	if (res != TEE_SUCCESS)
3709 		return res;
3710 
3711 	res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o);
3712 	if (res != TEE_SUCCESS)
3713 		return res;
3714 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
3715 		return TEE_ERROR_BAD_PARAMETERS;
3716 
3717 	key = o->attr;
3718 	res = crypto_authenc_init(cs->ctx, cs->mode, (uint8_t *)(key + 1),
3719 				  key->key_size, nonce, nonce_len, tag_len,
3720 				  aad_len, payload_len);
3721 	if (res != TEE_SUCCESS)
3722 		return res;
3723 
3724 	cs->ctx_finalize = crypto_authenc_final;
3725 	cs->state = CRYP_STATE_INITIALIZED;
3726 
3727 	return TEE_SUCCESS;
3728 }
3729 
3730 TEE_Result syscall_authenc_update_aad(unsigned long state,
3731 				      const void *aad_data, size_t aad_data_len)
3732 {
3733 	struct ts_session *sess = ts_get_current_session();
3734 	TEE_Result res = TEE_SUCCESS;
3735 	struct tee_cryp_state *cs = NULL;
3736 
3737 	aad_data = memtag_strip_tag_const(aad_data);
3738 
3739 	res = vm_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
3740 				     TEE_MEMORY_ACCESS_READ |
3741 				     TEE_MEMORY_ACCESS_ANY_OWNER,
3742 				     (uaddr_t)aad_data, aad_data_len);
3743 	if (res != TEE_SUCCESS)
3744 		return res;
3745 
3746 	res = tee_svc_cryp_get_state(sess, uref_to_vaddr(state), &cs);
3747 	if (res != TEE_SUCCESS)
3748 		return res;
3749 
3750 	if (cs->state != CRYP_STATE_INITIALIZED)
3751 		return TEE_ERROR_BAD_STATE;
3752 
3753 	if (TEE_ALG_GET_CLASS(cs->algo) != TEE_OPERATION_AE)
3754 		return TEE_ERROR_BAD_STATE;
3755 
3756 	res = crypto_authenc_update_aad(cs->ctx, cs->mode, aad_data,
3757 					aad_data_len);
3758 	if (res != TEE_SUCCESS)
3759 		return res;
3760 
3761 	return TEE_SUCCESS;
3762 }
3763 
3764 TEE_Result syscall_authenc_update_payload(unsigned long state,
3765 					  const void *src_data,
3766 					  size_t src_len, void *dst_data,
3767 					  uint64_t *dst_len)
3768 {
3769 	struct ts_session *sess = ts_get_current_session();
3770 	struct tee_cryp_state *cs = NULL;
3771 	TEE_Result res = TEE_SUCCESS;
3772 	size_t dlen = 0;
3773 
3774 	res = tee_svc_cryp_get_state(sess, uref_to_vaddr(state), &cs);
3775 	if (res != TEE_SUCCESS)
3776 		return res;
3777 
3778 	if (cs->state != CRYP_STATE_INITIALIZED)
3779 		return TEE_ERROR_BAD_STATE;
3780 
3781 	if (TEE_ALG_GET_CLASS(cs->algo) != TEE_OPERATION_AE)
3782 		return TEE_ERROR_BAD_STATE;
3783 
3784 	src_data = memtag_strip_tag_const(src_data);
3785 	dst_data = memtag_strip_tag(dst_data);
3786 
3787 	res = vm_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
3788 				     TEE_MEMORY_ACCESS_READ |
3789 				     TEE_MEMORY_ACCESS_ANY_OWNER,
3790 				     (uaddr_t)src_data, src_len);
3791 	if (res != TEE_SUCCESS)
3792 		return res;
3793 
3794 	res = get_user_u64_as_size_t(&dlen, dst_len);
3795 	if (res != TEE_SUCCESS)
3796 		return res;
3797 
3798 	res = vm_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
3799 				     TEE_MEMORY_ACCESS_READ |
3800 				     TEE_MEMORY_ACCESS_WRITE |
3801 				     TEE_MEMORY_ACCESS_ANY_OWNER,
3802 				     (uaddr_t)dst_data, dlen);
3803 	if (res != TEE_SUCCESS)
3804 		return res;
3805 
3806 	if (dlen < src_len) {
3807 		res = TEE_ERROR_SHORT_BUFFER;
3808 		goto out;
3809 	}
3810 
3811 	res = crypto_authenc_update_payload(cs->ctx, cs->mode, src_data,
3812 					    src_len, dst_data, &dlen);
3813 out:
3814 	if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
3815 		TEE_Result res2 = put_user_u64(dst_len, dlen);
3816 
3817 		if (res2 != TEE_SUCCESS)
3818 			res = res2;
3819 	}
3820 
3821 	return res;
3822 }
3823 
3824 TEE_Result syscall_authenc_enc_final(unsigned long state, const void *src_data,
3825 				     size_t src_len, void *dst_data,
3826 				     uint64_t *dst_len, void *tag,
3827 				     uint64_t *tag_len)
3828 {
3829 	struct ts_session *sess = ts_get_current_session();
3830 	struct user_mode_ctx *uctx = &to_user_ta_ctx(sess->ctx)->uctx;
3831 	struct tee_cryp_state *cs = NULL;
3832 	TEE_Result res = TEE_SUCCESS;
3833 	size_t dlen = 0;
3834 	size_t tlen = 0;
3835 
3836 	res = tee_svc_cryp_get_state(sess, uref_to_vaddr(state), &cs);
3837 	if (res != TEE_SUCCESS)
3838 		return res;
3839 
3840 	if (cs->state != CRYP_STATE_INITIALIZED)
3841 		return TEE_ERROR_BAD_STATE;
3842 
3843 	if (cs->mode != TEE_MODE_ENCRYPT)
3844 		return TEE_ERROR_BAD_PARAMETERS;
3845 
3846 	if (TEE_ALG_GET_CLASS(cs->algo) != TEE_OPERATION_AE)
3847 		return TEE_ERROR_BAD_STATE;
3848 
3849 	src_data = memtag_strip_tag_const(src_data);
3850 	dst_data = memtag_strip_tag(dst_data);
3851 	tag = memtag_strip_tag(tag);
3852 
3853 	res = vm_check_access_rights(uctx,
3854 				     TEE_MEMORY_ACCESS_READ |
3855 				     TEE_MEMORY_ACCESS_ANY_OWNER,
3856 				     (uaddr_t)src_data, src_len);
3857 	if (res != TEE_SUCCESS)
3858 		return res;
3859 
3860 	if (!dst_len) {
3861 		dlen = 0;
3862 	} else {
3863 		res = get_user_u64_as_size_t(&dlen, dst_len);
3864 		if (res != TEE_SUCCESS)
3865 			return res;
3866 
3867 		res = vm_check_access_rights(uctx,
3868 					     TEE_MEMORY_ACCESS_READ |
3869 					     TEE_MEMORY_ACCESS_WRITE |
3870 					     TEE_MEMORY_ACCESS_ANY_OWNER,
3871 					     (uaddr_t)dst_data, dlen);
3872 		if (res != TEE_SUCCESS)
3873 			return res;
3874 	}
3875 
3876 	if (dlen < src_len) {
3877 		res = TEE_ERROR_SHORT_BUFFER;
3878 		goto out;
3879 	}
3880 
3881 	res = get_user_u64_as_size_t(&tlen, tag_len);
3882 	if (res != TEE_SUCCESS)
3883 		return res;
3884 
3885 	res = vm_check_access_rights(uctx,
3886 				     TEE_MEMORY_ACCESS_READ |
3887 				     TEE_MEMORY_ACCESS_WRITE |
3888 				     TEE_MEMORY_ACCESS_ANY_OWNER,
3889 				     (uaddr_t)tag, tlen);
3890 	if (res != TEE_SUCCESS)
3891 		return res;
3892 
3893 	res = crypto_authenc_enc_final(cs->ctx, src_data, src_len, dst_data,
3894 				       &dlen, tag, &tlen);
3895 
3896 out:
3897 	if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
3898 		TEE_Result res2 = TEE_SUCCESS;
3899 
3900 		if (dst_len != NULL) {
3901 			res2 = put_user_u64(dst_len, dlen);
3902 			if (res2 != TEE_SUCCESS)
3903 				return res2;
3904 		}
3905 
3906 		res2 = put_user_u64(tag_len, tlen);
3907 		if (res2 != TEE_SUCCESS)
3908 			return res2;
3909 	}
3910 
3911 	return res;
3912 }
3913 
3914 TEE_Result syscall_authenc_dec_final(unsigned long state,
3915 			const void *src_data, size_t src_len, void *dst_data,
3916 			uint64_t *dst_len, const void *tag, size_t tag_len)
3917 {
3918 	struct ts_session *sess = ts_get_current_session();
3919 	struct user_mode_ctx *uctx = &to_user_ta_ctx(sess->ctx)->uctx;
3920 	struct tee_cryp_state *cs = NULL;
3921 	TEE_Result res = TEE_SUCCESS;
3922 	size_t dlen = 0;
3923 
3924 	res = tee_svc_cryp_get_state(sess, uref_to_vaddr(state), &cs);
3925 	if (res != TEE_SUCCESS)
3926 		return res;
3927 
3928 	if (cs->state != CRYP_STATE_INITIALIZED)
3929 		return TEE_ERROR_BAD_STATE;
3930 
3931 	if (cs->mode != TEE_MODE_DECRYPT)
3932 		return TEE_ERROR_BAD_PARAMETERS;
3933 
3934 	if (TEE_ALG_GET_CLASS(cs->algo) != TEE_OPERATION_AE)
3935 		return TEE_ERROR_BAD_STATE;
3936 
3937 	src_data = memtag_strip_tag_const(src_data);
3938 	dst_data = memtag_strip_tag(dst_data);
3939 	tag = memtag_strip_tag_const(tag);
3940 
3941 	res = vm_check_access_rights(uctx,
3942 				     TEE_MEMORY_ACCESS_READ |
3943 				     TEE_MEMORY_ACCESS_ANY_OWNER,
3944 				     (uaddr_t)src_data, src_len);
3945 	if (res != TEE_SUCCESS)
3946 		return res;
3947 
3948 	if (!dst_len) {
3949 		dlen = 0;
3950 	} else {
3951 		res = get_user_u64_as_size_t(&dlen, dst_len);
3952 		if (res != TEE_SUCCESS)
3953 			return res;
3954 
3955 		res = vm_check_access_rights(uctx,
3956 					     TEE_MEMORY_ACCESS_READ |
3957 					     TEE_MEMORY_ACCESS_WRITE |
3958 					     TEE_MEMORY_ACCESS_ANY_OWNER,
3959 					     (uaddr_t)dst_data, dlen);
3960 		if (res != TEE_SUCCESS)
3961 			return res;
3962 	}
3963 
3964 	if (dlen < src_len) {
3965 		res = TEE_ERROR_SHORT_BUFFER;
3966 		goto out;
3967 	}
3968 
3969 	res = vm_check_access_rights(uctx, TEE_MEMORY_ACCESS_READ,
3970 				     (uaddr_t)tag, tag_len);
3971 	if (res != TEE_SUCCESS)
3972 		return res;
3973 
3974 	res = crypto_authenc_dec_final(cs->ctx, src_data, src_len, dst_data,
3975 				       &dlen, tag, tag_len);
3976 
3977 out:
3978 	if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) &&
3979 	    dst_len != NULL) {
3980 		TEE_Result res2 = put_user_u64(dst_len, dlen);
3981 
3982 		if (res2 != TEE_SUCCESS)
3983 			return res2;
3984 	}
3985 
3986 	return res;
3987 }
3988 
3989 static int pkcs1_get_salt_len(const TEE_Attribute *params, uint32_t num_params,
3990 			      size_t default_len)
3991 {
3992 	size_t n;
3993 
3994 	assert(default_len < INT_MAX);
3995 
3996 	for (n = 0; n < num_params; n++) {
3997 		if (params[n].attributeID == TEE_ATTR_RSA_PSS_SALT_LENGTH) {
3998 			if (params[n].content.value.a < INT_MAX)
3999 				return params[n].content.value.a;
4000 			break;
4001 		}
4002 	}
4003 	/*
4004 	 * If salt length isn't provided use the default value which is
4005 	 * the length of the digest.
4006 	 */
4007 	return default_len;
4008 }
4009 
4010 TEE_Result syscall_asymm_operate(unsigned long state,
4011 			const struct utee_attribute *usr_params,
4012 			size_t num_params, const void *src_data, size_t src_len,
4013 			void *dst_data, uint64_t *dst_len)
4014 {
4015 	struct ts_session *sess = ts_get_current_session();
4016 	struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx);
4017 	TEE_Result res = TEE_SUCCESS;
4018 	struct tee_cryp_state *cs = NULL;
4019 	size_t dlen = 0;
4020 	struct tee_obj *o = NULL;
4021 	void *label = NULL;
4022 	size_t label_len = 0;
4023 	size_t n = 0;
4024 	int salt_len = 0;
4025 	TEE_Attribute *params = NULL;
4026 	size_t alloc_size = 0;
4027 
4028 	res = tee_svc_cryp_get_state(sess, uref_to_vaddr(state), &cs);
4029 	if (res != TEE_SUCCESS)
4030 		return res;
4031 
4032 	src_data = memtag_strip_tag_const(src_data);
4033 	dst_data = memtag_strip_tag(dst_data);
4034 
4035 	res = vm_check_access_rights(&utc->uctx,
4036 				     TEE_MEMORY_ACCESS_READ |
4037 				     TEE_MEMORY_ACCESS_ANY_OWNER,
4038 				     (uaddr_t)src_data, src_len);
4039 	if (res != TEE_SUCCESS)
4040 		return res;
4041 
4042 	res = get_user_u64_as_size_t(&dlen, dst_len);
4043 	if (res != TEE_SUCCESS)
4044 		return res;
4045 
4046 	res = vm_check_access_rights(&utc->uctx,
4047 				     TEE_MEMORY_ACCESS_READ |
4048 				     TEE_MEMORY_ACCESS_WRITE |
4049 				     TEE_MEMORY_ACCESS_ANY_OWNER,
4050 				     (uaddr_t)dst_data, dlen);
4051 	if (res != TEE_SUCCESS)
4052 		return res;
4053 
4054 	if (MUL_OVERFLOW(sizeof(TEE_Attribute), num_params, &alloc_size))
4055 		return TEE_ERROR_OVERFLOW;
4056 
4057 	params = malloc(alloc_size);
4058 	if (!params)
4059 		return TEE_ERROR_OUT_OF_MEMORY;
4060 	res = copy_in_attrs(utc, usr_params, num_params, params);
4061 	if (res != TEE_SUCCESS)
4062 		goto out;
4063 
4064 	res = tee_obj_get(utc, cs->key1, &o);
4065 	if (res != TEE_SUCCESS)
4066 		goto out;
4067 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
4068 		res = TEE_ERROR_GENERIC;
4069 		goto out;
4070 	}
4071 
4072 	switch (cs->algo) {
4073 	case TEE_ALG_RSA_NOPAD:
4074 		if (cs->mode == TEE_MODE_ENCRYPT) {
4075 			res = crypto_acipher_rsanopad_encrypt(o->attr, src_data,
4076 							      src_len, dst_data,
4077 							      &dlen);
4078 		} else if (cs->mode == TEE_MODE_DECRYPT) {
4079 			res = crypto_acipher_rsanopad_decrypt(o->attr, src_data,
4080 							      src_len, dst_data,
4081 							      &dlen);
4082 		} else {
4083 			/*
4084 			 * We will panic because "the mode is not compatible
4085 			 * with the function"
4086 			 */
4087 			res = TEE_ERROR_GENERIC;
4088 		}
4089 		break;
4090 
4091 	case TEE_ALG_SM2_PKE:
4092 		if (cs->mode == TEE_MODE_ENCRYPT) {
4093 			res = crypto_acipher_sm2_pke_encrypt(o->attr, src_data,
4094 							     src_len, dst_data,
4095 							     &dlen);
4096 		} else if (cs->mode == TEE_MODE_DECRYPT) {
4097 			res = crypto_acipher_sm2_pke_decrypt(o->attr, src_data,
4098 							     src_len, dst_data,
4099 							     &dlen);
4100 		} else {
4101 			res = TEE_ERROR_GENERIC;
4102 		}
4103 		break;
4104 
4105 	case TEE_ALG_RSAES_PKCS1_V1_5:
4106 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
4107 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
4108 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
4109 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
4110 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
4111 		for (n = 0; n < num_params; n++) {
4112 			if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) {
4113 				label = params[n].content.ref.buffer;
4114 				label_len = params[n].content.ref.length;
4115 				break;
4116 			}
4117 		}
4118 
4119 		if (cs->mode == TEE_MODE_ENCRYPT) {
4120 			res = crypto_acipher_rsaes_encrypt(cs->algo, o->attr,
4121 							   label, label_len,
4122 							   src_data, src_len,
4123 							   dst_data, &dlen);
4124 		} else if (cs->mode == TEE_MODE_DECRYPT) {
4125 			res = crypto_acipher_rsaes_decrypt(
4126 					cs->algo, o->attr, label, label_len,
4127 					src_data, src_len, dst_data, &dlen);
4128 		} else {
4129 			res = TEE_ERROR_BAD_PARAMETERS;
4130 		}
4131 		break;
4132 
4133 #if defined(CFG_CRYPTO_RSASSA_NA1)
4134 	case TEE_ALG_RSASSA_PKCS1_V1_5:
4135 #endif
4136 	case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
4137 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
4138 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
4139 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
4140 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
4141 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
4142 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
4143 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
4144 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
4145 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
4146 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
4147 		if (cs->mode != TEE_MODE_SIGN) {
4148 			res = TEE_ERROR_BAD_PARAMETERS;
4149 			break;
4150 		}
4151 		salt_len = pkcs1_get_salt_len(params, num_params, src_len);
4152 		res = crypto_acipher_rsassa_sign(cs->algo, o->attr, salt_len,
4153 						 src_data, src_len, dst_data,
4154 						 &dlen);
4155 		break;
4156 
4157 	case TEE_ALG_DSA_SHA1:
4158 	case TEE_ALG_DSA_SHA224:
4159 	case TEE_ALG_DSA_SHA256:
4160 		res = crypto_acipher_dsa_sign(cs->algo, o->attr, src_data,
4161 					      src_len, dst_data, &dlen);
4162 		break;
4163 
4164 	case TEE_ALG_ED25519:
4165 		res = tee_svc_obj_ed25519_sign(o->attr, src_data, src_len,
4166 					       dst_data, &dlen, params,
4167 					       num_params);
4168 		break;
4169 
4170 	case TEE_ALG_ECDSA_P192:
4171 	case TEE_ALG_ECDSA_P224:
4172 	case TEE_ALG_ECDSA_P256:
4173 	case TEE_ALG_ECDSA_P384:
4174 	case TEE_ALG_ECDSA_P521:
4175 	case TEE_ALG_SM2_DSA_SM3:
4176 		res = crypto_acipher_ecc_sign(cs->algo, o->attr, src_data,
4177 					      src_len, dst_data, &dlen);
4178 		break;
4179 	default:
4180 		res = TEE_ERROR_BAD_PARAMETERS;
4181 		break;
4182 	}
4183 
4184 out:
4185 	free_wipe(params);
4186 
4187 	if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
4188 		TEE_Result res2 = put_user_u64(dst_len, dlen);
4189 
4190 		if (res2 != TEE_SUCCESS)
4191 			return res2;
4192 	}
4193 
4194 	return res;
4195 }
4196 
4197 TEE_Result syscall_asymm_verify(unsigned long state,
4198 			const struct utee_attribute *usr_params,
4199 			size_t num_params, const void *data, size_t data_len,
4200 			const void *sig, size_t sig_len)
4201 {
4202 	struct ts_session *sess = ts_get_current_session();
4203 	struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx);
4204 	struct tee_cryp_state *cs = NULL;
4205 	TEE_Result res = TEE_SUCCESS;
4206 	TEE_Attribute *params = NULL;
4207 	struct tee_obj *o = NULL;
4208 	size_t hash_size = 0;
4209 	uint32_t hash_algo = 0;
4210 	int salt_len = 0;
4211 	size_t alloc_size = 0;
4212 
4213 	res = tee_svc_cryp_get_state(sess, uref_to_vaddr(state), &cs);
4214 	if (res != TEE_SUCCESS)
4215 		return res;
4216 
4217 	if (cs->mode != TEE_MODE_VERIFY)
4218 		return TEE_ERROR_BAD_PARAMETERS;
4219 
4220 	data = memtag_strip_tag_const(data);
4221 	sig = memtag_strip_tag_const(sig);
4222 
4223 	res = vm_check_access_rights(&utc->uctx,
4224 				     TEE_MEMORY_ACCESS_READ |
4225 				     TEE_MEMORY_ACCESS_ANY_OWNER,
4226 				     (uaddr_t)data, data_len);
4227 	if (res != TEE_SUCCESS)
4228 		return res;
4229 
4230 	res = vm_check_access_rights(&utc->uctx,
4231 				     TEE_MEMORY_ACCESS_READ |
4232 				     TEE_MEMORY_ACCESS_ANY_OWNER,
4233 				     (uaddr_t)sig, sig_len);
4234 	if (res != TEE_SUCCESS)
4235 		return res;
4236 
4237 	if (MUL_OVERFLOW(sizeof(TEE_Attribute), num_params, &alloc_size))
4238 		return TEE_ERROR_OVERFLOW;
4239 
4240 	params = malloc(alloc_size);
4241 	if (!params)
4242 		return TEE_ERROR_OUT_OF_MEMORY;
4243 	res = copy_in_attrs(utc, usr_params, num_params, params);
4244 	if (res != TEE_SUCCESS)
4245 		goto out;
4246 
4247 	res = tee_obj_get(utc, cs->key1, &o);
4248 	if (res != TEE_SUCCESS)
4249 		goto out;
4250 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
4251 		res = TEE_ERROR_BAD_PARAMETERS;
4252 		goto out;
4253 	}
4254 
4255 	switch (TEE_ALG_GET_MAIN_ALG(cs->algo)) {
4256 	case TEE_MAIN_ALGO_RSA:
4257 		if (cs->algo != TEE_ALG_RSASSA_PKCS1_V1_5) {
4258 			hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo);
4259 			res = tee_alg_get_digest_size(hash_algo, &hash_size);
4260 			if (res != TEE_SUCCESS)
4261 				break;
4262 			if (data_len != hash_size) {
4263 				res = TEE_ERROR_BAD_PARAMETERS;
4264 				break;
4265 			}
4266 			salt_len = pkcs1_get_salt_len(params, num_params,
4267 						      hash_size);
4268 		}
4269 		res = crypto_acipher_rsassa_verify(cs->algo, o->attr, salt_len,
4270 						   data, data_len, sig,
4271 						   sig_len);
4272 		break;
4273 
4274 	case TEE_MAIN_ALGO_DSA:
4275 		hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo);
4276 		res = tee_alg_get_digest_size(hash_algo, &hash_size);
4277 		if (res != TEE_SUCCESS)
4278 			break;
4279 
4280 		if (data_len != hash_size) {
4281 			struct dsa_public_key *key = o->attr;
4282 
4283 			/*
4284 			 * Depending on the DSA algorithm (NIST), the
4285 			 * digital signature output size may be truncated
4286 			 * to the size of a key pair (Q prime size). Q
4287 			 * prime size must be less or equal than the hash
4288 			 * output length of the hash algorithm involved.
4289 			 *
4290 			 * We're checking here in order to be able to
4291 			 * return this particular error code, which will
4292 			 * cause TEE_AsymmetricVerifyDigest() to panic as
4293 			 * required by GP. crypto_acipher_dsa_verify() is
4294 			 * implemented in the glue layer of the crypto
4295 			 * library and it might be a bit harder to catch
4296 			 * this particular case there or lead to duplicated
4297 			 * code in different crypto glue layers.
4298 			 *
4299 			 * The GP spec says that we SHOULD panic if
4300 			 * data_len != hash_size, but that would break a
4301 			 * few of the DSA tests in xtest where the
4302 			 * hash_size is larger than possible data_len. So
4303 			 * the compromise is in case data_len != hash_size
4304 			 * check that it's not smaller than what makes
4305 			 * sense.
4306 			 */
4307 			if (data_len != crypto_bignum_num_bytes(key->q)) {
4308 				res = TEE_ERROR_BAD_PARAMETERS;
4309 				break;
4310 			}
4311 		}
4312 		res = crypto_acipher_dsa_verify(cs->algo, o->attr, data,
4313 						data_len, sig, sig_len);
4314 		break;
4315 
4316 	case TEE_MAIN_ALGO_ED25519:
4317 		res = tee_svc_obj_ed25519_verify(o->attr, data,
4318 						 data_len, sig, sig_len,
4319 						 params, num_params);
4320 		break;
4321 
4322 	case TEE_MAIN_ALGO_ECDSA:
4323 	case TEE_MAIN_ALGO_SM2_DSA_SM3:
4324 		res = crypto_acipher_ecc_verify(cs->algo, o->attr, data,
4325 						data_len, sig, sig_len);
4326 		break;
4327 
4328 	default:
4329 		res = TEE_ERROR_NOT_SUPPORTED;
4330 	}
4331 
4332 out:
4333 	free_wipe(params);
4334 	return res;
4335 }
4336