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