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