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