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