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