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