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