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