xref: /optee_os/core/tee/tee_svc_cryp.c (revision 21282bae8ad769f51b273d4d4a652a57c9198538)
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, const TEE_Attribute *params, uint32_t param_count)
1751 {
1752 	TEE_Result res;
1753 	struct dh_keypair *tee_dh_key;
1754 	struct bignum *dh_q = NULL;
1755 	uint32_t dh_xbits = 0;
1756 
1757 	/* Copy the present attributes into the obj before starting */
1758 	res = tee_svc_cryp_obj_populate_type(o, type_props, params,
1759 					     param_count);
1760 	if (res != TEE_SUCCESS)
1761 		return res;
1762 
1763 	tee_dh_key = (struct dh_keypair *)o->attr;
1764 
1765 	if (get_attribute(o, type_props, TEE_ATTR_DH_SUBPRIME))
1766 		dh_q = tee_dh_key->q;
1767 	if (get_attribute(o, type_props, TEE_ATTR_DH_X_BITS))
1768 		dh_xbits = tee_dh_key->xbits;
1769 	res = crypto_acipher_gen_dh_key(tee_dh_key, dh_q, dh_xbits, key_size);
1770 	if (res != TEE_SUCCESS)
1771 		return res;
1772 
1773 	/* Set bits for the generated public and private key */
1774 	set_attribute(o, type_props, TEE_ATTR_DH_PUBLIC_VALUE);
1775 	set_attribute(o, type_props, TEE_ATTR_DH_PRIVATE_VALUE);
1776 	set_attribute(o, type_props, TEE_ATTR_DH_X_BITS);
1777 	return TEE_SUCCESS;
1778 }
1779 
1780 static TEE_Result tee_svc_obj_generate_key_ecc(
1781 	struct tee_obj *o, const struct tee_cryp_obj_type_props *type_props,
1782 	uint32_t key_size, const TEE_Attribute *params, uint32_t param_count)
1783 {
1784 	TEE_Result res;
1785 	struct ecc_keypair *tee_ecc_key;
1786 
1787 	/* Copy the present attributes into the obj before starting */
1788 	res = tee_svc_cryp_obj_populate_type(o, type_props, params,
1789 					     param_count);
1790 	if (res != TEE_SUCCESS)
1791 		return res;
1792 
1793 	tee_ecc_key = (struct ecc_keypair *)o->attr;
1794 
1795 	res = crypto_acipher_gen_ecc_key(tee_ecc_key, key_size);
1796 	if (res != TEE_SUCCESS)
1797 		return res;
1798 
1799 	/* Set bits for the generated public and private key */
1800 	set_attribute(o, type_props, TEE_ATTR_ECC_PRIVATE_VALUE);
1801 	set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_X);
1802 	set_attribute(o, type_props, TEE_ATTR_ECC_PUBLIC_VALUE_Y);
1803 	set_attribute(o, type_props, TEE_ATTR_ECC_CURVE);
1804 	return TEE_SUCCESS;
1805 }
1806 
1807 TEE_Result syscall_obj_generate_key(unsigned long obj, unsigned long key_size,
1808 			const struct utee_attribute *usr_params,
1809 			unsigned long param_count)
1810 {
1811 	TEE_Result res;
1812 	struct tee_ta_session *sess;
1813 	const struct tee_cryp_obj_type_props *type_props;
1814 	struct tee_obj *o;
1815 	struct tee_cryp_obj_secret *key;
1816 	size_t byte_size;
1817 	TEE_Attribute *params = NULL;
1818 
1819 	res = tee_ta_get_current_session(&sess);
1820 	if (res != TEE_SUCCESS)
1821 		return res;
1822 
1823 	res = tee_obj_get(to_user_ta_ctx(sess->ctx),
1824 			  tee_svc_uref_to_vaddr(obj), &o);
1825 	if (res != TEE_SUCCESS)
1826 		return res;
1827 
1828 	/* Must be a transient object */
1829 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_PERSISTENT) != 0)
1830 		return TEE_ERROR_BAD_STATE;
1831 
1832 	/* Must not be initialized already */
1833 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
1834 		return TEE_ERROR_BAD_STATE;
1835 
1836 	/* Find description of object */
1837 	type_props = tee_svc_find_type_props(o->info.objectType);
1838 	if (!type_props)
1839 		return TEE_ERROR_NOT_SUPPORTED;
1840 
1841 	/* Check that maxKeySize follows restrictions */
1842 	if (key_size % type_props->quanta != 0)
1843 		return TEE_ERROR_NOT_SUPPORTED;
1844 	if (key_size < type_props->min_size)
1845 		return TEE_ERROR_NOT_SUPPORTED;
1846 	if (key_size > type_props->max_size)
1847 		return TEE_ERROR_NOT_SUPPORTED;
1848 
1849 	size_t alloc_size = 0;
1850 
1851 	if (MUL_OVERFLOW(sizeof(TEE_Attribute), param_count, &alloc_size))
1852 		return TEE_ERROR_OVERFLOW;
1853 
1854 	params = malloc(alloc_size);
1855 	if (!params)
1856 		return TEE_ERROR_OUT_OF_MEMORY;
1857 	res = copy_in_attrs(to_user_ta_ctx(sess->ctx), usr_params, param_count,
1858 			    params);
1859 	if (res != TEE_SUCCESS)
1860 		goto out;
1861 
1862 	res = tee_svc_cryp_check_attr(ATTR_USAGE_GENERATE_KEY, type_props,
1863 				      params, param_count);
1864 	if (res != TEE_SUCCESS)
1865 		goto out;
1866 
1867 	switch (o->info.objectType) {
1868 	case TEE_TYPE_AES:
1869 	case TEE_TYPE_DES:
1870 	case TEE_TYPE_DES3:
1871 	case TEE_TYPE_SM4:
1872 	case TEE_TYPE_HMAC_MD5:
1873 	case TEE_TYPE_HMAC_SHA1:
1874 	case TEE_TYPE_HMAC_SHA224:
1875 	case TEE_TYPE_HMAC_SHA256:
1876 	case TEE_TYPE_HMAC_SHA384:
1877 	case TEE_TYPE_HMAC_SHA512:
1878 	case TEE_TYPE_HMAC_SM3:
1879 	case TEE_TYPE_GENERIC_SECRET:
1880 		byte_size = key_size / 8;
1881 
1882 		/*
1883 		 * We have to do it like this because the parity bits aren't
1884 		 * counted when telling the size of the key in bits.
1885 		 */
1886 		if (o->info.objectType == TEE_TYPE_DES ||
1887 		    o->info.objectType == TEE_TYPE_DES3) {
1888 			byte_size = (key_size + key_size / 7) / 8;
1889 		}
1890 
1891 		key = (struct tee_cryp_obj_secret *)o->attr;
1892 		if (byte_size > key->alloc_size) {
1893 			res = TEE_ERROR_EXCESS_DATA;
1894 			goto out;
1895 		}
1896 
1897 		res = crypto_rng_read((void *)(key + 1), byte_size);
1898 		if (res != TEE_SUCCESS)
1899 			goto out;
1900 
1901 		key->key_size = byte_size;
1902 
1903 		/* Set bits for all known attributes for this object type */
1904 		o->have_attrs = (1 << type_props->num_type_attrs) - 1;
1905 
1906 		break;
1907 
1908 	case TEE_TYPE_RSA_KEYPAIR:
1909 		res = tee_svc_obj_generate_key_rsa(o, type_props, key_size,
1910 						   params, param_count);
1911 		if (res != TEE_SUCCESS)
1912 			goto out;
1913 		break;
1914 
1915 	case TEE_TYPE_DSA_KEYPAIR:
1916 		res = tee_svc_obj_generate_key_dsa(o, type_props, key_size,
1917 						   params, param_count);
1918 		if (res != TEE_SUCCESS)
1919 			goto out;
1920 		break;
1921 
1922 	case TEE_TYPE_DH_KEYPAIR:
1923 		res = tee_svc_obj_generate_key_dh(o, type_props, key_size,
1924 						  params, param_count);
1925 		if (res != TEE_SUCCESS)
1926 			goto out;
1927 		break;
1928 
1929 	case TEE_TYPE_ECDSA_KEYPAIR:
1930 	case TEE_TYPE_ECDH_KEYPAIR:
1931 	case TEE_TYPE_SM2_PKE_KEYPAIR:
1932 		res = tee_svc_obj_generate_key_ecc(o, type_props, key_size,
1933 						  params, param_count);
1934 		if (res != TEE_SUCCESS)
1935 			goto out;
1936 		break;
1937 
1938 	default:
1939 		res = TEE_ERROR_BAD_FORMAT;
1940 	}
1941 
1942 out:
1943 	free_wipe(params);
1944 	if (res == TEE_SUCCESS) {
1945 		o->info.keySize = key_size;
1946 		o->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
1947 	}
1948 	return res;
1949 }
1950 
1951 static TEE_Result tee_svc_cryp_get_state(struct tee_ta_session *sess,
1952 					 uint32_t state_id,
1953 					 struct tee_cryp_state **state)
1954 {
1955 	struct tee_cryp_state *s;
1956 	struct user_ta_ctx *utc = to_user_ta_ctx(sess->ctx);
1957 
1958 	TAILQ_FOREACH(s, &utc->cryp_states, link) {
1959 		if (state_id == (vaddr_t)s) {
1960 			*state = s;
1961 			return TEE_SUCCESS;
1962 		}
1963 	}
1964 	return TEE_ERROR_BAD_PARAMETERS;
1965 }
1966 
1967 static void cryp_state_free(struct user_ta_ctx *utc, struct tee_cryp_state *cs)
1968 {
1969 	struct tee_obj *o;
1970 
1971 	if (tee_obj_get(utc, cs->key1, &o) == TEE_SUCCESS)
1972 		tee_obj_close(utc, o);
1973 	if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS)
1974 		tee_obj_close(utc, o);
1975 
1976 	TAILQ_REMOVE(&utc->cryp_states, cs, link);
1977 	if (cs->ctx_finalize != NULL)
1978 		cs->ctx_finalize(cs->ctx);
1979 
1980 	switch (TEE_ALG_GET_CLASS(cs->algo)) {
1981 	case TEE_OPERATION_CIPHER:
1982 		crypto_cipher_free_ctx(cs->ctx);
1983 		break;
1984 	case TEE_OPERATION_AE:
1985 		crypto_authenc_free_ctx(cs->ctx);
1986 		break;
1987 	case TEE_OPERATION_DIGEST:
1988 		crypto_hash_free_ctx(cs->ctx);
1989 		break;
1990 	case TEE_OPERATION_MAC:
1991 		crypto_mac_free_ctx(cs->ctx);
1992 		break;
1993 	default:
1994 		assert(!cs->ctx);
1995 	}
1996 
1997 	free(cs);
1998 }
1999 
2000 static TEE_Result tee_svc_cryp_check_key_type(const struct tee_obj *o,
2001 					      uint32_t algo,
2002 					      TEE_OperationMode mode)
2003 {
2004 	uint32_t req_key_type;
2005 	uint32_t req_key_type2 = 0;
2006 
2007 	switch (TEE_ALG_GET_MAIN_ALG(algo)) {
2008 	case TEE_MAIN_ALGO_MD5:
2009 		req_key_type = TEE_TYPE_HMAC_MD5;
2010 		break;
2011 	case TEE_MAIN_ALGO_SHA1:
2012 		req_key_type = TEE_TYPE_HMAC_SHA1;
2013 		break;
2014 	case TEE_MAIN_ALGO_SHA224:
2015 		req_key_type = TEE_TYPE_HMAC_SHA224;
2016 		break;
2017 	case TEE_MAIN_ALGO_SHA256:
2018 		req_key_type = TEE_TYPE_HMAC_SHA256;
2019 		break;
2020 	case TEE_MAIN_ALGO_SHA384:
2021 		req_key_type = TEE_TYPE_HMAC_SHA384;
2022 		break;
2023 	case TEE_MAIN_ALGO_SHA512:
2024 		req_key_type = TEE_TYPE_HMAC_SHA512;
2025 		break;
2026 	case TEE_MAIN_ALGO_SM3:
2027 		req_key_type = TEE_TYPE_HMAC_SM3;
2028 		break;
2029 	case TEE_MAIN_ALGO_AES:
2030 		req_key_type = TEE_TYPE_AES;
2031 		break;
2032 	case TEE_MAIN_ALGO_DES:
2033 		req_key_type = TEE_TYPE_DES;
2034 		break;
2035 	case TEE_MAIN_ALGO_DES3:
2036 		req_key_type = TEE_TYPE_DES3;
2037 		break;
2038 	case TEE_MAIN_ALGO_SM4:
2039 		req_key_type = TEE_TYPE_SM4;
2040 		break;
2041 	case TEE_MAIN_ALGO_RSA:
2042 		req_key_type = TEE_TYPE_RSA_KEYPAIR;
2043 		if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY)
2044 			req_key_type2 = TEE_TYPE_RSA_PUBLIC_KEY;
2045 		break;
2046 	case TEE_MAIN_ALGO_DSA:
2047 		req_key_type = TEE_TYPE_DSA_KEYPAIR;
2048 		if (mode == TEE_MODE_ENCRYPT || mode == TEE_MODE_VERIFY)
2049 			req_key_type2 = TEE_TYPE_DSA_PUBLIC_KEY;
2050 		break;
2051 	case TEE_MAIN_ALGO_DH:
2052 		req_key_type = TEE_TYPE_DH_KEYPAIR;
2053 		break;
2054 	case TEE_MAIN_ALGO_ECDSA:
2055 		req_key_type = TEE_TYPE_ECDSA_KEYPAIR;
2056 		if (mode == TEE_MODE_VERIFY)
2057 			req_key_type2 = TEE_TYPE_ECDSA_PUBLIC_KEY;
2058 		break;
2059 	case TEE_MAIN_ALGO_ECDH:
2060 		req_key_type = TEE_TYPE_ECDH_KEYPAIR;
2061 		break;
2062 	case TEE_MAIN_ALGO_SM2_PKE:
2063 		if (mode == TEE_MODE_ENCRYPT)
2064 			req_key_type = TEE_TYPE_SM2_PKE_PUBLIC_KEY;
2065 		else
2066 			req_key_type = TEE_TYPE_SM2_PKE_KEYPAIR;
2067 		break;
2068 	case TEE_MAIN_ALGO_SM2_DSA_SM3:
2069 		if (mode == TEE_MODE_VERIFY)
2070 			req_key_type = TEE_TYPE_SM2_DSA_PUBLIC_KEY;
2071 		else
2072 			req_key_type = TEE_TYPE_SM2_DSA_KEYPAIR;
2073 		break;
2074 #if defined(CFG_CRYPTO_SM2_KEP)
2075 	case TEE_MAIN_ALGO_SM2_KEP:
2076 		req_key_type = TEE_TYPE_SM2_KEP_KEYPAIR;
2077 		req_key_type2 = TEE_TYPE_SM2_KEP_PUBLIC_KEY;
2078 		break;
2079 #endif
2080 #if defined(CFG_CRYPTO_HKDF)
2081 	case TEE_MAIN_ALGO_HKDF:
2082 		req_key_type = TEE_TYPE_HKDF_IKM;
2083 		break;
2084 #endif
2085 #if defined(CFG_CRYPTO_CONCAT_KDF)
2086 	case TEE_MAIN_ALGO_CONCAT_KDF:
2087 		req_key_type = TEE_TYPE_CONCAT_KDF_Z;
2088 		break;
2089 #endif
2090 #if defined(CFG_CRYPTO_PBKDF2)
2091 	case TEE_MAIN_ALGO_PBKDF2:
2092 		req_key_type = TEE_TYPE_PBKDF2_PASSWORD;
2093 		break;
2094 #endif
2095 	default:
2096 		return TEE_ERROR_BAD_PARAMETERS;
2097 	}
2098 
2099 	if (req_key_type != o->info.objectType &&
2100 	    req_key_type2 != o->info.objectType)
2101 		return TEE_ERROR_BAD_PARAMETERS;
2102 	return TEE_SUCCESS;
2103 }
2104 
2105 TEE_Result syscall_cryp_state_alloc(unsigned long algo, unsigned long mode,
2106 			unsigned long key1, unsigned long key2,
2107 			uint32_t *state)
2108 {
2109 	TEE_Result res;
2110 	struct tee_cryp_state *cs;
2111 	struct tee_ta_session *sess;
2112 	struct tee_obj *o1 = NULL;
2113 	struct tee_obj *o2 = NULL;
2114 	struct user_ta_ctx *utc;
2115 
2116 	res = tee_ta_get_current_session(&sess);
2117 	if (res != TEE_SUCCESS)
2118 		return res;
2119 	utc = to_user_ta_ctx(sess->ctx);
2120 
2121 	if (key1 != 0) {
2122 		res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key1), &o1);
2123 		if (res != TEE_SUCCESS)
2124 			return res;
2125 		if (o1->busy)
2126 			return TEE_ERROR_BAD_PARAMETERS;
2127 		res = tee_svc_cryp_check_key_type(o1, algo, mode);
2128 		if (res != TEE_SUCCESS)
2129 			return res;
2130 	}
2131 	if (key2 != 0) {
2132 		res = tee_obj_get(utc, tee_svc_uref_to_vaddr(key2), &o2);
2133 		if (res != TEE_SUCCESS)
2134 			return res;
2135 		if (o2->busy)
2136 			return TEE_ERROR_BAD_PARAMETERS;
2137 		res = tee_svc_cryp_check_key_type(o2, algo, mode);
2138 		if (res != TEE_SUCCESS)
2139 			return res;
2140 	}
2141 
2142 	cs = calloc(1, sizeof(struct tee_cryp_state));
2143 	if (!cs)
2144 		return TEE_ERROR_OUT_OF_MEMORY;
2145 	TAILQ_INSERT_TAIL(&utc->cryp_states, cs, link);
2146 	cs->algo = algo;
2147 	cs->mode = mode;
2148 	cs->state = CRYP_STATE_UNINITIALIZED;
2149 
2150 	switch (TEE_ALG_GET_CLASS(algo)) {
2151 	case TEE_OPERATION_CIPHER:
2152 		if ((algo == TEE_ALG_AES_XTS && (key1 == 0 || key2 == 0)) ||
2153 		    (algo != TEE_ALG_AES_XTS && (key1 == 0 || key2 != 0))) {
2154 			res = TEE_ERROR_BAD_PARAMETERS;
2155 		} else {
2156 			res = crypto_cipher_alloc_ctx(&cs->ctx, algo);
2157 			if (res != TEE_SUCCESS)
2158 				break;
2159 		}
2160 		break;
2161 	case TEE_OPERATION_AE:
2162 		if (key1 == 0 || key2 != 0) {
2163 			res = TEE_ERROR_BAD_PARAMETERS;
2164 		} else {
2165 			res = crypto_authenc_alloc_ctx(&cs->ctx, algo);
2166 			if (res != TEE_SUCCESS)
2167 				break;
2168 		}
2169 		break;
2170 	case TEE_OPERATION_MAC:
2171 		if (key1 == 0 || key2 != 0) {
2172 			res = TEE_ERROR_BAD_PARAMETERS;
2173 		} else {
2174 			res = crypto_mac_alloc_ctx(&cs->ctx, algo);
2175 			if (res != TEE_SUCCESS)
2176 				break;
2177 		}
2178 		break;
2179 	case TEE_OPERATION_DIGEST:
2180 		if (key1 != 0 || key2 != 0) {
2181 			res = TEE_ERROR_BAD_PARAMETERS;
2182 		} else {
2183 			res = crypto_hash_alloc_ctx(&cs->ctx, algo);
2184 			if (res != TEE_SUCCESS)
2185 				break;
2186 		}
2187 		break;
2188 	case TEE_OPERATION_ASYMMETRIC_CIPHER:
2189 	case TEE_OPERATION_ASYMMETRIC_SIGNATURE:
2190 		if (algo == TEE_ALG_RSASSA_PKCS1_V1_5 &&
2191 		    !IS_ENABLED(CFG_CRYPTO_RSASSA_NA1)) {
2192 			res = TEE_ERROR_NOT_SUPPORTED;
2193 			break;
2194 		}
2195 		if (key1 == 0 || key2 != 0)
2196 			res = TEE_ERROR_BAD_PARAMETERS;
2197 		break;
2198 	case TEE_OPERATION_KEY_DERIVATION:
2199 		if (algo == TEE_ALG_SM2_KEP) {
2200 			if (key1 == 0 || key2 == 0)
2201 				res = TEE_ERROR_BAD_PARAMETERS;
2202 		} else {
2203 			if (key1 == 0 || key2 != 0)
2204 				res = TEE_ERROR_BAD_PARAMETERS;
2205 		}
2206 		break;
2207 	default:
2208 		res = TEE_ERROR_NOT_SUPPORTED;
2209 		break;
2210 	}
2211 	if (res != TEE_SUCCESS)
2212 		goto out;
2213 
2214 	res = tee_svc_copy_kaddr_to_uref(state, cs);
2215 	if (res != TEE_SUCCESS)
2216 		goto out;
2217 
2218 	/* Register keys */
2219 	if (o1 != NULL) {
2220 		o1->busy = true;
2221 		cs->key1 = (vaddr_t)o1;
2222 	}
2223 	if (o2 != NULL) {
2224 		o2->busy = true;
2225 		cs->key2 = (vaddr_t)o2;
2226 	}
2227 
2228 out:
2229 	if (res != TEE_SUCCESS)
2230 		cryp_state_free(utc, cs);
2231 	return res;
2232 }
2233 
2234 TEE_Result syscall_cryp_state_copy(unsigned long dst, unsigned long src)
2235 {
2236 	TEE_Result res;
2237 	struct tee_cryp_state *cs_dst;
2238 	struct tee_cryp_state *cs_src;
2239 	struct tee_ta_session *sess;
2240 
2241 	res = tee_ta_get_current_session(&sess);
2242 	if (res != TEE_SUCCESS)
2243 		return res;
2244 
2245 	res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(dst), &cs_dst);
2246 	if (res != TEE_SUCCESS)
2247 		return res;
2248 
2249 	res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(src), &cs_src);
2250 	if (res != TEE_SUCCESS)
2251 		return res;
2252 	if (cs_dst->algo != cs_src->algo || cs_dst->mode != cs_src->mode)
2253 		return TEE_ERROR_BAD_PARAMETERS;
2254 
2255 	switch (TEE_ALG_GET_CLASS(cs_src->algo)) {
2256 	case TEE_OPERATION_CIPHER:
2257 		crypto_cipher_copy_state(cs_dst->ctx, cs_src->ctx);
2258 		break;
2259 	case TEE_OPERATION_AE:
2260 		crypto_authenc_copy_state(cs_dst->ctx, cs_src->ctx);
2261 		break;
2262 	case TEE_OPERATION_DIGEST:
2263 		crypto_hash_copy_state(cs_dst->ctx, cs_src->ctx);
2264 		break;
2265 	case TEE_OPERATION_MAC:
2266 		crypto_mac_copy_state(cs_dst->ctx, cs_src->ctx);
2267 		break;
2268 	default:
2269 		return TEE_ERROR_BAD_STATE;
2270 	}
2271 
2272 	cs_dst->state = cs_src->state;
2273 
2274 	return TEE_SUCCESS;
2275 }
2276 
2277 void tee_svc_cryp_free_states(struct user_ta_ctx *utc)
2278 {
2279 	struct tee_cryp_state_head *states = &utc->cryp_states;
2280 
2281 	while (!TAILQ_EMPTY(states))
2282 		cryp_state_free(utc, TAILQ_FIRST(states));
2283 }
2284 
2285 TEE_Result syscall_cryp_state_free(unsigned long state)
2286 {
2287 	TEE_Result res;
2288 	struct tee_cryp_state *cs;
2289 	struct tee_ta_session *sess;
2290 
2291 	res = tee_ta_get_current_session(&sess);
2292 	if (res != TEE_SUCCESS)
2293 		return res;
2294 
2295 	res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
2296 	if (res != TEE_SUCCESS)
2297 		return res;
2298 	cryp_state_free(to_user_ta_ctx(sess->ctx), cs);
2299 	return TEE_SUCCESS;
2300 }
2301 
2302 TEE_Result syscall_hash_init(unsigned long state,
2303 			     const void *iv __maybe_unused,
2304 			     size_t iv_len __maybe_unused)
2305 {
2306 	TEE_Result res;
2307 	struct tee_cryp_state *cs;
2308 	struct tee_ta_session *sess;
2309 
2310 	res = tee_ta_get_current_session(&sess);
2311 	if (res != TEE_SUCCESS)
2312 		return res;
2313 
2314 	res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
2315 	if (res != TEE_SUCCESS)
2316 		return res;
2317 
2318 	switch (TEE_ALG_GET_CLASS(cs->algo)) {
2319 	case TEE_OPERATION_DIGEST:
2320 		res = crypto_hash_init(cs->ctx);
2321 		if (res != TEE_SUCCESS)
2322 			return res;
2323 		break;
2324 	case TEE_OPERATION_MAC:
2325 		{
2326 			struct tee_obj *o;
2327 			struct tee_cryp_obj_secret *key;
2328 
2329 			res = tee_obj_get(to_user_ta_ctx(sess->ctx),
2330 					  cs->key1, &o);
2331 			if (res != TEE_SUCCESS)
2332 				return res;
2333 			if ((o->info.handleFlags &
2334 			     TEE_HANDLE_FLAG_INITIALIZED) == 0)
2335 				return TEE_ERROR_BAD_PARAMETERS;
2336 
2337 			key = (struct tee_cryp_obj_secret *)o->attr;
2338 			res = crypto_mac_init(cs->ctx, (void *)(key + 1),
2339 					      key->key_size);
2340 			if (res != TEE_SUCCESS)
2341 				return res;
2342 			break;
2343 		}
2344 	default:
2345 		return TEE_ERROR_BAD_PARAMETERS;
2346 	}
2347 
2348 	cs->state = CRYP_STATE_INITIALIZED;
2349 
2350 	return TEE_SUCCESS;
2351 }
2352 
2353 TEE_Result syscall_hash_update(unsigned long state, const void *chunk,
2354 			size_t chunk_size)
2355 {
2356 	struct tee_ta_session *sess = NULL;
2357 	struct tee_cryp_state *cs = NULL;
2358 	TEE_Result res = TEE_SUCCESS;
2359 
2360 	/* No data, but size provided isn't valid parameters. */
2361 	if (!chunk && chunk_size)
2362 		return TEE_ERROR_BAD_PARAMETERS;
2363 
2364 	/* Zero length hash is valid, but nothing we need to do. */
2365 	if (!chunk_size)
2366 		return TEE_SUCCESS;
2367 
2368 	res = tee_ta_get_current_session(&sess);
2369 	if (res != TEE_SUCCESS)
2370 		return res;
2371 
2372 	res = tee_mmu_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
2373 					  TEE_MEMORY_ACCESS_READ |
2374 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2375 					  (uaddr_t)chunk, chunk_size);
2376 	if (res != TEE_SUCCESS)
2377 		return res;
2378 
2379 	res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
2380 	if (res != TEE_SUCCESS)
2381 		return res;
2382 
2383 	if (cs->state != CRYP_STATE_INITIALIZED)
2384 		return TEE_ERROR_BAD_STATE;
2385 
2386 	switch (TEE_ALG_GET_CLASS(cs->algo)) {
2387 	case TEE_OPERATION_DIGEST:
2388 		res = crypto_hash_update(cs->ctx, chunk, chunk_size);
2389 		if (res != TEE_SUCCESS)
2390 			return res;
2391 		break;
2392 	case TEE_OPERATION_MAC:
2393 		res = crypto_mac_update(cs->ctx, chunk, chunk_size);
2394 		if (res != TEE_SUCCESS)
2395 			return res;
2396 		break;
2397 	default:
2398 		return TEE_ERROR_BAD_PARAMETERS;
2399 	}
2400 
2401 	return TEE_SUCCESS;
2402 }
2403 
2404 TEE_Result syscall_hash_final(unsigned long state, const void *chunk,
2405 			size_t chunk_size, void *hash, uint64_t *hash_len)
2406 {
2407 	struct tee_ta_session *sess = NULL;
2408 	struct tee_cryp_state *cs = NULL;
2409 	TEE_Result res2 = TEE_SUCCESS;
2410 	TEE_Result res = TEE_SUCCESS;
2411 	size_t hash_size = 0;
2412 	size_t hlen = 0;
2413 
2414 	/* No data, but size provided isn't valid parameters. */
2415 	if (!chunk && chunk_size)
2416 		return TEE_ERROR_BAD_PARAMETERS;
2417 
2418 	res = tee_ta_get_current_session(&sess);
2419 	if (res != TEE_SUCCESS)
2420 		return res;
2421 
2422 	res = tee_mmu_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
2423 					  TEE_MEMORY_ACCESS_READ |
2424 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2425 					  (uaddr_t)chunk, chunk_size);
2426 	if (res != TEE_SUCCESS)
2427 		return res;
2428 
2429 	res = get_user_u64_as_size_t(&hlen, hash_len);
2430 	if (res != TEE_SUCCESS)
2431 		return res;
2432 
2433 	res = tee_mmu_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
2434 					  TEE_MEMORY_ACCESS_READ |
2435 					  TEE_MEMORY_ACCESS_WRITE |
2436 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2437 					  (uaddr_t)hash, hlen);
2438 	if (res != TEE_SUCCESS)
2439 		return res;
2440 
2441 	res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
2442 	if (res != TEE_SUCCESS)
2443 		return res;
2444 
2445 	if (cs->state != CRYP_STATE_INITIALIZED)
2446 		return TEE_ERROR_BAD_STATE;
2447 
2448 	switch (TEE_ALG_GET_CLASS(cs->algo)) {
2449 	case TEE_OPERATION_DIGEST:
2450 		res = tee_alg_get_digest_size(cs->algo, &hash_size);
2451 		if (res != TEE_SUCCESS)
2452 			return res;
2453 		if (hlen < hash_size) {
2454 			res = TEE_ERROR_SHORT_BUFFER;
2455 			goto out;
2456 		}
2457 
2458 		if (chunk_size) {
2459 			res = crypto_hash_update(cs->ctx, chunk, chunk_size);
2460 			if (res != TEE_SUCCESS)
2461 				return res;
2462 		}
2463 
2464 		res = crypto_hash_final(cs->ctx, hash, hash_size);
2465 		if (res != TEE_SUCCESS)
2466 			return res;
2467 		break;
2468 
2469 	case TEE_OPERATION_MAC:
2470 		res = tee_alg_get_digest_size(cs->algo, &hash_size);
2471 		if (res != TEE_SUCCESS)
2472 			return res;
2473 		if (hlen < hash_size) {
2474 			res = TEE_ERROR_SHORT_BUFFER;
2475 			goto out;
2476 		}
2477 
2478 		if (chunk_size) {
2479 			res = crypto_mac_update(cs->ctx, chunk, chunk_size);
2480 			if (res != TEE_SUCCESS)
2481 				return res;
2482 		}
2483 
2484 		res = crypto_mac_final(cs->ctx, hash, hash_size);
2485 		if (res != TEE_SUCCESS)
2486 			return res;
2487 		break;
2488 
2489 	default:
2490 		return TEE_ERROR_BAD_PARAMETERS;
2491 	}
2492 out:
2493 	res2 = put_user_u64(hash_len, hash_size);
2494 	if (res2 != TEE_SUCCESS)
2495 		return res2;
2496 	return res;
2497 }
2498 
2499 TEE_Result syscall_cipher_init(unsigned long state, const void *iv,
2500 			size_t iv_len)
2501 {
2502 	struct tee_cryp_obj_secret *key1 = NULL;
2503 	struct tee_ta_session *sess = NULL;
2504 	struct tee_cryp_state *cs = NULL;
2505 	struct user_ta_ctx *utc = NULL;
2506 	TEE_Result res = TEE_SUCCESS;
2507 	struct tee_obj *o = NULL;
2508 
2509 	res = tee_ta_get_current_session(&sess);
2510 	if (res != TEE_SUCCESS)
2511 		return res;
2512 	utc = to_user_ta_ctx(sess->ctx);
2513 
2514 	res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
2515 	if (res != TEE_SUCCESS)
2516 		return res;
2517 
2518 	if (TEE_ALG_GET_CLASS(cs->algo) != TEE_OPERATION_CIPHER)
2519 		return TEE_ERROR_BAD_STATE;
2520 
2521 	res = tee_mmu_check_access_rights(&utc->uctx,
2522 					  TEE_MEMORY_ACCESS_READ |
2523 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2524 					  (uaddr_t)iv, iv_len);
2525 	if (res != TEE_SUCCESS)
2526 		return res;
2527 
2528 	res = tee_obj_get(utc, cs->key1, &o);
2529 	if (res != TEE_SUCCESS)
2530 		return res;
2531 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
2532 		return TEE_ERROR_BAD_PARAMETERS;
2533 
2534 	key1 = o->attr;
2535 
2536 	if (tee_obj_get(utc, cs->key2, &o) == TEE_SUCCESS) {
2537 		struct tee_cryp_obj_secret *key2 = o->attr;
2538 
2539 		if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
2540 			return TEE_ERROR_BAD_PARAMETERS;
2541 
2542 		res = crypto_cipher_init(cs->ctx, cs->mode,
2543 					 (uint8_t *)(key1 + 1), key1->key_size,
2544 					 (uint8_t *)(key2 + 1), key2->key_size,
2545 					 iv, iv_len);
2546 	} else {
2547 		res = crypto_cipher_init(cs->ctx, cs->mode,
2548 					 (uint8_t *)(key1 + 1), key1->key_size,
2549 					 NULL, 0, iv, iv_len);
2550 	}
2551 	if (res != TEE_SUCCESS)
2552 		return res;
2553 
2554 	cs->ctx_finalize = crypto_cipher_final;
2555 	cs->state = CRYP_STATE_INITIALIZED;
2556 
2557 	return TEE_SUCCESS;
2558 }
2559 
2560 static TEE_Result tee_svc_cipher_update_helper(unsigned long state,
2561 			bool last_block, const void *src, size_t src_len,
2562 			void *dst, uint64_t *dst_len)
2563 {
2564 	struct tee_ta_session *sess = NULL;
2565 	struct tee_cryp_state *cs = NULL;
2566 	TEE_Result res = TEE_SUCCESS;
2567 	size_t dlen = 0;
2568 
2569 	res = tee_ta_get_current_session(&sess);
2570 	if (res != TEE_SUCCESS)
2571 		return res;
2572 
2573 	res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
2574 	if (res != TEE_SUCCESS)
2575 		return res;
2576 
2577 	if (cs->state != CRYP_STATE_INITIALIZED)
2578 		return TEE_ERROR_BAD_STATE;
2579 
2580 	res = tee_mmu_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
2581 					  TEE_MEMORY_ACCESS_READ |
2582 					  TEE_MEMORY_ACCESS_ANY_OWNER,
2583 					  (uaddr_t)src, src_len);
2584 	if (res != TEE_SUCCESS)
2585 		return res;
2586 
2587 	if (!dst_len) {
2588 		dlen = 0;
2589 	} else {
2590 		struct user_mode_ctx *uctx = &to_user_ta_ctx(sess->ctx)->uctx;
2591 		uint32_t flags = TEE_MEMORY_ACCESS_READ |
2592 				 TEE_MEMORY_ACCESS_WRITE |
2593 				 TEE_MEMORY_ACCESS_ANY_OWNER;
2594 
2595 		res = get_user_u64_as_size_t(&dlen, dst_len);
2596 		if (res != TEE_SUCCESS)
2597 			return res;
2598 
2599 		res = tee_mmu_check_access_rights(uctx, flags, (uaddr_t)dst,
2600 						  dlen);
2601 		if (res != TEE_SUCCESS)
2602 			return res;
2603 	}
2604 
2605 	if (dlen < src_len) {
2606 		res = TEE_ERROR_SHORT_BUFFER;
2607 		goto out;
2608 	}
2609 
2610 	if (src_len > 0) {
2611 		/* Permit src_len == 0 to finalize the operation */
2612 		res = tee_do_cipher_update(cs->ctx, cs->algo, cs->mode,
2613 					   last_block, src, src_len, dst);
2614 	}
2615 
2616 	if (last_block && cs->ctx_finalize != NULL) {
2617 		cs->ctx_finalize(cs->ctx);
2618 		cs->ctx_finalize = NULL;
2619 	}
2620 
2621 out:
2622 	if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) &&
2623 	    dst_len != NULL) {
2624 		TEE_Result res2;
2625 
2626 		res2 = put_user_u64(dst_len, src_len);
2627 		if (res2 != TEE_SUCCESS)
2628 			res = res2;
2629 	}
2630 
2631 	return res;
2632 }
2633 
2634 TEE_Result syscall_cipher_update(unsigned long state, const void *src,
2635 			size_t src_len, void *dst, uint64_t *dst_len)
2636 {
2637 	return tee_svc_cipher_update_helper(state, false /* last_block */,
2638 					    src, src_len, dst, dst_len);
2639 }
2640 
2641 TEE_Result syscall_cipher_final(unsigned long state, const void *src,
2642 			size_t src_len, void *dst, uint64_t *dst_len)
2643 {
2644 	return tee_svc_cipher_update_helper(state, true /* last_block */,
2645 					    src, src_len, dst, dst_len);
2646 }
2647 
2648 #if defined(CFG_CRYPTO_HKDF)
2649 static TEE_Result get_hkdf_params(const TEE_Attribute *params,
2650 				  uint32_t param_count,
2651 				  void **salt, size_t *salt_len, void **info,
2652 				  size_t *info_len, size_t *okm_len)
2653 {
2654 	size_t n;
2655 	enum { SALT = 0x1, LENGTH = 0x2, INFO = 0x4 };
2656 	uint8_t found = 0;
2657 
2658 	*salt = *info = NULL;
2659 	*salt_len = *info_len = *okm_len = 0;
2660 
2661 	for (n = 0; n < param_count; n++) {
2662 		switch (params[n].attributeID) {
2663 		case TEE_ATTR_HKDF_SALT:
2664 			if (!(found & SALT)) {
2665 				*salt = params[n].content.ref.buffer;
2666 				*salt_len = params[n].content.ref.length;
2667 				found |= SALT;
2668 			}
2669 			break;
2670 		case TEE_ATTR_HKDF_OKM_LENGTH:
2671 			if (!(found & LENGTH)) {
2672 				*okm_len = params[n].content.value.a;
2673 				found |= LENGTH;
2674 			}
2675 			break;
2676 		case TEE_ATTR_HKDF_INFO:
2677 			if (!(found & INFO)) {
2678 				*info = params[n].content.ref.buffer;
2679 				*info_len = params[n].content.ref.length;
2680 				found |= INFO;
2681 			}
2682 			break;
2683 		default:
2684 			/* Unexpected attribute */
2685 			return TEE_ERROR_BAD_PARAMETERS;
2686 		}
2687 
2688 	}
2689 
2690 	if (!(found & LENGTH))
2691 		return TEE_ERROR_BAD_PARAMETERS;
2692 
2693 	return TEE_SUCCESS;
2694 }
2695 #endif
2696 
2697 #if defined(CFG_CRYPTO_CONCAT_KDF)
2698 static TEE_Result get_concat_kdf_params(const TEE_Attribute *params,
2699 					uint32_t param_count,
2700 					void **other_info,
2701 					size_t *other_info_len,
2702 					size_t *derived_key_len)
2703 {
2704 	size_t n;
2705 	enum { LENGTH = 0x1, INFO = 0x2 };
2706 	uint8_t found = 0;
2707 
2708 	*other_info = NULL;
2709 	*other_info_len = *derived_key_len = 0;
2710 
2711 	for (n = 0; n < param_count; n++) {
2712 		switch (params[n].attributeID) {
2713 		case TEE_ATTR_CONCAT_KDF_OTHER_INFO:
2714 			if (!(found & INFO)) {
2715 				*other_info = params[n].content.ref.buffer;
2716 				*other_info_len = params[n].content.ref.length;
2717 				found |= INFO;
2718 			}
2719 			break;
2720 		case TEE_ATTR_CONCAT_KDF_DKM_LENGTH:
2721 			if (!(found & LENGTH)) {
2722 				*derived_key_len = params[n].content.value.a;
2723 				found |= LENGTH;
2724 			}
2725 			break;
2726 		default:
2727 			/* Unexpected attribute */
2728 			return TEE_ERROR_BAD_PARAMETERS;
2729 		}
2730 	}
2731 
2732 	if (!(found & LENGTH))
2733 		return TEE_ERROR_BAD_PARAMETERS;
2734 
2735 	return TEE_SUCCESS;
2736 }
2737 #endif
2738 
2739 #if defined(CFG_CRYPTO_PBKDF2)
2740 static TEE_Result get_pbkdf2_params(const TEE_Attribute *params,
2741 				   uint32_t param_count, void **salt,
2742 				   size_t *salt_len, size_t *derived_key_len,
2743 				   size_t *iteration_count)
2744 {
2745 	size_t n;
2746 	enum { SALT = 0x1, LENGTH = 0x2, COUNT = 0x4 };
2747 	uint8_t found = 0;
2748 
2749 	*salt = NULL;
2750 	*salt_len = *derived_key_len = *iteration_count = 0;
2751 
2752 	for (n = 0; n < param_count; n++) {
2753 		switch (params[n].attributeID) {
2754 		case TEE_ATTR_PBKDF2_SALT:
2755 			if (!(found & SALT)) {
2756 				*salt = params[n].content.ref.buffer;
2757 				*salt_len = params[n].content.ref.length;
2758 				found |= SALT;
2759 			}
2760 			break;
2761 		case TEE_ATTR_PBKDF2_DKM_LENGTH:
2762 			if (!(found & LENGTH)) {
2763 				*derived_key_len = params[n].content.value.a;
2764 				found |= LENGTH;
2765 			}
2766 			break;
2767 		case TEE_ATTR_PBKDF2_ITERATION_COUNT:
2768 			if (!(found & COUNT)) {
2769 				*iteration_count = params[n].content.value.a;
2770 				found |= COUNT;
2771 			}
2772 			break;
2773 		default:
2774 			/* Unexpected attribute */
2775 			return TEE_ERROR_BAD_PARAMETERS;
2776 		}
2777 	}
2778 
2779 	if ((found & (LENGTH|COUNT)) != (LENGTH|COUNT))
2780 		return TEE_ERROR_BAD_PARAMETERS;
2781 
2782 	return TEE_SUCCESS;
2783 }
2784 #endif
2785 
2786 #if defined(CFG_CRYPTO_SM2_KEP)
2787 static TEE_Result get_sm2_kep_params(const TEE_Attribute *params,
2788 				     uint32_t param_count,
2789 				     struct ecc_public_key *peer_key,
2790 				     struct ecc_public_key *peer_eph_key,
2791 				     struct sm2_kep_parms *kep_parms)
2792 {
2793 	TEE_Result res = TEE_ERROR_GENERIC;
2794 	size_t n;
2795 	enum {
2796 		IS_INITIATOR,
2797 		PEER_KEY_X,
2798 		PEER_KEY_Y,
2799 		PEER_EPH_KEY_X,
2800 		PEER_EPH_KEY_Y,
2801 		INITIATOR_ID,
2802 		RESPONDER_ID,
2803 	};
2804 	uint8_t mandatory = BIT(IS_INITIATOR) | BIT(PEER_KEY_X) |
2805 		BIT(PEER_KEY_Y) | BIT(PEER_EPH_KEY_X) | BIT(PEER_EPH_KEY_Y) |
2806 		BIT(INITIATOR_ID) | BIT(RESPONDER_ID);
2807 	uint8_t found = 0;
2808 
2809 	res = crypto_acipher_alloc_ecc_public_key(peer_key, 256);
2810 	if (res)
2811 		goto out;
2812 
2813 	res = crypto_acipher_alloc_ecc_public_key(peer_eph_key, 256);
2814 	if (res)
2815 		goto out;
2816 
2817 	peer_key->curve = TEE_ECC_CURVE_SM2;
2818 	peer_eph_key->curve = TEE_ECC_CURVE_SM2;
2819 
2820 	for (n = 0; n < param_count; n++) {
2821 		const TEE_Attribute *p = &params[n];
2822 
2823 		switch (p->attributeID) {
2824 		case TEE_ATTR_SM2_KEP_USER:
2825 			kep_parms->is_initiator = !p->content.value.a;
2826 			found |= BIT(IS_INITIATOR);
2827 			break;
2828 		case TEE_ATTR_ECC_PUBLIC_VALUE_X:
2829 			crypto_bignum_bin2bn(p->content.ref.buffer,
2830 					     p->content.ref.length,
2831 					     peer_key->x);
2832 			found |= BIT(PEER_KEY_X);
2833 			break;
2834 		case TEE_ATTR_ECC_PUBLIC_VALUE_Y:
2835 			crypto_bignum_bin2bn(p->content.ref.buffer,
2836 					     p->content.ref.length,
2837 					     peer_key->y);
2838 			found |= BIT(PEER_KEY_Y);
2839 			break;
2840 		case TEE_ATTR_ECC_EPHEMERAL_PUBLIC_VALUE_X:
2841 			crypto_bignum_bin2bn(p->content.ref.buffer,
2842 					     p->content.ref.length,
2843 					     peer_eph_key->x);
2844 			found |= BIT(PEER_EPH_KEY_X);
2845 			break;
2846 		case TEE_ATTR_ECC_EPHEMERAL_PUBLIC_VALUE_Y:
2847 			crypto_bignum_bin2bn(p->content.ref.buffer,
2848 					     p->content.ref.length,
2849 					     peer_eph_key->y);
2850 			found |= BIT(PEER_EPH_KEY_Y);
2851 			break;
2852 		case TEE_ATTR_SM2_ID_INITIATOR:
2853 			kep_parms->initiator_id = p->content.ref.buffer;
2854 			kep_parms->initiator_id_len = p->content.ref.length;
2855 			found |= BIT(INITIATOR_ID);
2856 			break;
2857 		case TEE_ATTR_SM2_ID_RESPONDER:
2858 			kep_parms->responder_id = p->content.ref.buffer;
2859 			kep_parms->responder_id_len = p->content.ref.length;
2860 			found |= BIT(RESPONDER_ID);
2861 			break;
2862 		case TEE_ATTR_SM2_KEP_CONFIRMATION_IN:
2863 			kep_parms->conf_in = p->content.ref.buffer;
2864 			kep_parms->conf_in_len = p->content.ref.length;
2865 			break;
2866 		case TEE_ATTR_SM2_KEP_CONFIRMATION_OUT:
2867 			kep_parms->conf_out = p->content.ref.buffer;
2868 			kep_parms->conf_out_len = p->content.ref.length;
2869 			break;
2870 		default:
2871 			/* Unexpected attribute */
2872 			res = TEE_ERROR_BAD_PARAMETERS;
2873 			goto out;
2874 		}
2875 	}
2876 
2877 	if ((found & mandatory) != mandatory) {
2878 		res = TEE_ERROR_BAD_PARAMETERS;
2879 		goto out;
2880 	}
2881 
2882 	return TEE_SUCCESS;
2883 out:
2884 	crypto_acipher_free_ecc_public_key(peer_key);
2885 	crypto_acipher_free_ecc_public_key(peer_eph_key);
2886 	return res;
2887 }
2888 #endif
2889 
2890 TEE_Result syscall_cryp_derive_key(unsigned long state,
2891 			const struct utee_attribute *usr_params,
2892 			unsigned long param_count, unsigned long derived_key)
2893 {
2894 	TEE_Result res = TEE_ERROR_NOT_SUPPORTED;
2895 	struct tee_ta_session *sess;
2896 	struct tee_obj *ko;
2897 	struct tee_obj *so;
2898 	struct tee_cryp_state *cs;
2899 	struct tee_cryp_obj_secret *sk;
2900 	const struct tee_cryp_obj_type_props *type_props;
2901 	TEE_Attribute *params = NULL;
2902 	struct user_ta_ctx *utc;
2903 
2904 	res = tee_ta_get_current_session(&sess);
2905 	if (res != TEE_SUCCESS)
2906 		return res;
2907 	utc = to_user_ta_ctx(sess->ctx);
2908 
2909 	res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
2910 	if (res != TEE_SUCCESS)
2911 		return res;
2912 
2913 	size_t alloc_size = 0;
2914 
2915 	if (MUL_OVERFLOW(sizeof(TEE_Attribute), param_count, &alloc_size))
2916 		return TEE_ERROR_OVERFLOW;
2917 
2918 	params = malloc(alloc_size);
2919 	if (!params)
2920 		return TEE_ERROR_OUT_OF_MEMORY;
2921 	res = copy_in_attrs(utc, usr_params, param_count, params);
2922 	if (res != TEE_SUCCESS)
2923 		goto out;
2924 
2925 	/* Get key set in operation */
2926 	res = tee_obj_get(utc, cs->key1, &ko);
2927 	if (res != TEE_SUCCESS)
2928 		goto out;
2929 
2930 	res = tee_obj_get(utc, tee_svc_uref_to_vaddr(derived_key), &so);
2931 	if (res != TEE_SUCCESS)
2932 		goto out;
2933 
2934 	/* Find information needed about the object to initialize */
2935 	sk = so->attr;
2936 
2937 	/* Find description of object */
2938 	type_props = tee_svc_find_type_props(so->info.objectType);
2939 	if (!type_props) {
2940 		res = TEE_ERROR_NOT_SUPPORTED;
2941 		goto out;
2942 	}
2943 
2944 	if (cs->algo == TEE_ALG_DH_DERIVE_SHARED_SECRET) {
2945 		struct bignum *pub;
2946 		struct bignum *ss;
2947 
2948 		if (param_count != 1 ||
2949 		    params[0].attributeID != TEE_ATTR_DH_PUBLIC_VALUE) {
2950 			res = TEE_ERROR_BAD_PARAMETERS;
2951 			goto out;
2952 		}
2953 
2954 		size_t bin_size = params[0].content.ref.length;
2955 
2956 		if (MUL_OVERFLOW(bin_size, 8, &alloc_size)) {
2957 			res = TEE_ERROR_OVERFLOW;
2958 			goto out;
2959 		}
2960 
2961 		pub = crypto_bignum_allocate(alloc_size);
2962 		ss = crypto_bignum_allocate(alloc_size);
2963 		if (pub && ss) {
2964 			crypto_bignum_bin2bn(params[0].content.ref.buffer,
2965 					     bin_size, pub);
2966 			res = crypto_acipher_dh_shared_secret(ko->attr,
2967 							      pub, ss);
2968 			if (res == TEE_SUCCESS) {
2969 				sk->key_size = crypto_bignum_num_bytes(ss);
2970 				crypto_bignum_bn2bin(ss, (uint8_t *)(sk + 1));
2971 				so->info.handleFlags |=
2972 						TEE_HANDLE_FLAG_INITIALIZED;
2973 				set_attribute(so, type_props,
2974 					      TEE_ATTR_SECRET_VALUE);
2975 			}
2976 		} else {
2977 			res = TEE_ERROR_OUT_OF_MEMORY;
2978 		}
2979 		crypto_bignum_free(pub);
2980 		crypto_bignum_free(ss);
2981 	} else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_ECDH) {
2982 		struct ecc_public_key key_public;
2983 		uint8_t *pt_secret;
2984 		unsigned long pt_secret_len;
2985 
2986 		if (param_count != 2 ||
2987 		    params[0].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_X ||
2988 		    params[1].attributeID != TEE_ATTR_ECC_PUBLIC_VALUE_Y) {
2989 			res = TEE_ERROR_BAD_PARAMETERS;
2990 			goto out;
2991 		}
2992 
2993 		switch (cs->algo) {
2994 		case TEE_ALG_ECDH_P192:
2995 			alloc_size = 192;
2996 			break;
2997 		case TEE_ALG_ECDH_P224:
2998 			alloc_size = 224;
2999 			break;
3000 		case TEE_ALG_ECDH_P256:
3001 			alloc_size = 256;
3002 			break;
3003 		case TEE_ALG_ECDH_P384:
3004 			alloc_size = 384;
3005 			break;
3006 		case TEE_ALG_ECDH_P521:
3007 			alloc_size = 521;
3008 			break;
3009 		default:
3010 			res = TEE_ERROR_NOT_IMPLEMENTED;
3011 			goto out;
3012 		}
3013 
3014 		/* Create the public key */
3015 		res = crypto_acipher_alloc_ecc_public_key(&key_public,
3016 							  alloc_size);
3017 		if (res != TEE_SUCCESS)
3018 			goto out;
3019 		key_public.curve = ((struct ecc_keypair *)ko->attr)->curve;
3020 		crypto_bignum_bin2bn(params[0].content.ref.buffer,
3021 				     params[0].content.ref.length,
3022 				     key_public.x);
3023 		crypto_bignum_bin2bn(params[1].content.ref.buffer,
3024 				     params[1].content.ref.length,
3025 				     key_public.y);
3026 
3027 		pt_secret = (uint8_t *)(sk + 1);
3028 		pt_secret_len = sk->alloc_size;
3029 		res = crypto_acipher_ecc_shared_secret(ko->attr, &key_public,
3030 						       pt_secret,
3031 						       &pt_secret_len);
3032 
3033 		if (res == TEE_SUCCESS) {
3034 			sk->key_size = pt_secret_len;
3035 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
3036 			set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
3037 		}
3038 
3039 		/* free the public key */
3040 		crypto_acipher_free_ecc_public_key(&key_public);
3041 	}
3042 #if defined(CFG_CRYPTO_HKDF)
3043 	else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_HKDF) {
3044 		void *salt, *info;
3045 		size_t salt_len, info_len, okm_len;
3046 		uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
3047 		struct tee_cryp_obj_secret *ik = ko->attr;
3048 		const uint8_t *ikm = (const uint8_t *)(ik + 1);
3049 
3050 		res = get_hkdf_params(params, param_count, &salt, &salt_len,
3051 				      &info, &info_len, &okm_len);
3052 		if (res != TEE_SUCCESS)
3053 			goto out;
3054 
3055 		/* Requested size must fit into the output object's buffer */
3056 		if (okm_len > ik->alloc_size) {
3057 			res = TEE_ERROR_BAD_PARAMETERS;
3058 			goto out;
3059 		}
3060 
3061 		res = tee_cryp_hkdf(hash_id, ikm, ik->key_size, salt, salt_len,
3062 				    info, info_len, (uint8_t *)(sk + 1),
3063 				    okm_len);
3064 		if (res == TEE_SUCCESS) {
3065 			sk->key_size = okm_len;
3066 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
3067 			set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
3068 		}
3069 	}
3070 #endif
3071 #if defined(CFG_CRYPTO_CONCAT_KDF)
3072 	else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_CONCAT_KDF) {
3073 		void *info;
3074 		size_t info_len, derived_key_len;
3075 		uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
3076 		struct tee_cryp_obj_secret *ss = ko->attr;
3077 		const uint8_t *shared_secret = (const uint8_t *)(ss + 1);
3078 
3079 		res = get_concat_kdf_params(params, param_count, &info,
3080 					    &info_len, &derived_key_len);
3081 		if (res != TEE_SUCCESS)
3082 			goto out;
3083 
3084 		/* Requested size must fit into the output object's buffer */
3085 		if (derived_key_len > ss->alloc_size) {
3086 			res = TEE_ERROR_BAD_PARAMETERS;
3087 			goto out;
3088 		}
3089 
3090 		res = tee_cryp_concat_kdf(hash_id, shared_secret, ss->key_size,
3091 					  info, info_len, (uint8_t *)(sk + 1),
3092 					  derived_key_len);
3093 		if (res == TEE_SUCCESS) {
3094 			sk->key_size = derived_key_len;
3095 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
3096 			set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
3097 		}
3098 	}
3099 #endif
3100 #if defined(CFG_CRYPTO_PBKDF2)
3101 	else if (TEE_ALG_GET_MAIN_ALG(cs->algo) == TEE_MAIN_ALGO_PBKDF2) {
3102 		void *salt;
3103 		size_t salt_len, iteration_count, derived_key_len;
3104 		uint32_t hash_id = TEE_ALG_GET_DIGEST_HASH(cs->algo);
3105 		struct tee_cryp_obj_secret *ss = ko->attr;
3106 		const uint8_t *password = (const uint8_t *)(ss + 1);
3107 
3108 		res = get_pbkdf2_params(params, param_count, &salt, &salt_len,
3109 					&derived_key_len, &iteration_count);
3110 		if (res != TEE_SUCCESS)
3111 			goto out;
3112 
3113 		/* Requested size must fit into the output object's buffer */
3114 		if (derived_key_len > ss->alloc_size) {
3115 			res = TEE_ERROR_BAD_PARAMETERS;
3116 			goto out;
3117 		}
3118 
3119 		res = tee_cryp_pbkdf2(hash_id, password, ss->key_size, salt,
3120 				      salt_len, iteration_count,
3121 				      (uint8_t *)(sk + 1), derived_key_len);
3122 		if (res == TEE_SUCCESS) {
3123 			sk->key_size = derived_key_len;
3124 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
3125 			set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
3126 		}
3127 	}
3128 #endif
3129 #if defined(CFG_CRYPTO_SM2_KEP)
3130 	else if (cs->algo == TEE_ALG_SM2_KEP) {
3131 		struct ecc_public_key peer_eph_key = { };
3132 		struct ecc_public_key peer_key = { };
3133 		struct sm2_kep_parms kep_parms = {
3134 			.out = (uint8_t *)(sk + 1),
3135 			.out_len = so->info.maxKeySize,
3136 		};
3137 		struct tee_obj *ko2 = NULL;
3138 
3139 		res = tee_obj_get(utc, cs->key2, &ko2);
3140 		if (res != TEE_SUCCESS)
3141 			goto out;
3142 
3143 		res = get_sm2_kep_params(params, param_count, &peer_key,
3144 					 &peer_eph_key, &kep_parms);
3145 		if (res != TEE_SUCCESS)
3146 			goto out;
3147 
3148 		/*
3149 		 * key1 is our private keypair, key2 is our ephemeral public key
3150 		 */
3151 		res = crypto_acipher_sm2_kep_derive(ko->attr, /* key1 */
3152 						    ko2->attr, /* key2 */
3153 						    &peer_key, &peer_eph_key,
3154 						    &kep_parms);
3155 
3156 		if (res == TEE_SUCCESS) {
3157 			sk->key_size = kep_parms.out_len;
3158 			so->info.handleFlags |= TEE_HANDLE_FLAG_INITIALIZED;
3159 			set_attribute(so, type_props, TEE_ATTR_SECRET_VALUE);
3160 		}
3161 		crypto_acipher_free_ecc_public_key(&peer_key);
3162 		crypto_acipher_free_ecc_public_key(&peer_eph_key);
3163 	}
3164 #endif
3165 	else
3166 		res = TEE_ERROR_NOT_SUPPORTED;
3167 
3168 out:
3169 	free_wipe(params);
3170 	return res;
3171 }
3172 
3173 TEE_Result syscall_cryp_random_number_generate(void *buf, size_t blen)
3174 {
3175 	struct tee_ta_session *sess = NULL;
3176 	TEE_Result res = TEE_SUCCESS;
3177 
3178 	res = tee_ta_get_current_session(&sess);
3179 	if (res != TEE_SUCCESS)
3180 		return res;
3181 
3182 	res = tee_mmu_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
3183 					  TEE_MEMORY_ACCESS_WRITE |
3184 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3185 					  (uaddr_t)buf, blen);
3186 	if (res != TEE_SUCCESS)
3187 		return res;
3188 
3189 	res = crypto_rng_read(buf, blen);
3190 	if (res != TEE_SUCCESS)
3191 		return res;
3192 
3193 	return res;
3194 }
3195 
3196 TEE_Result syscall_authenc_init(unsigned long state, const void *nonce,
3197 				size_t nonce_len, size_t tag_len,
3198 				size_t aad_len, size_t payload_len)
3199 {
3200 	struct tee_cryp_obj_secret *key = NULL;
3201 	struct tee_ta_session *sess = NULL;
3202 	struct tee_cryp_state *cs = NULL;
3203 	TEE_Result res = TEE_SUCCESS;
3204 	struct tee_obj *o = NULL;
3205 
3206 	res = tee_ta_get_current_session(&sess);
3207 	if (res != TEE_SUCCESS)
3208 		return res;
3209 
3210 	res = tee_mmu_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
3211 					  TEE_MEMORY_ACCESS_READ |
3212 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3213 					  (uaddr_t)nonce, nonce_len);
3214 	if (res != TEE_SUCCESS)
3215 		return res;
3216 
3217 	res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
3218 	if (res != TEE_SUCCESS)
3219 		return res;
3220 
3221 	res = tee_obj_get(to_user_ta_ctx(sess->ctx), cs->key1, &o);
3222 	if (res != TEE_SUCCESS)
3223 		return res;
3224 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0)
3225 		return TEE_ERROR_BAD_PARAMETERS;
3226 
3227 	key = o->attr;
3228 	res = crypto_authenc_init(cs->ctx, cs->mode, (uint8_t *)(key + 1),
3229 				  key->key_size, nonce, nonce_len, tag_len,
3230 				  aad_len, payload_len);
3231 	if (res != TEE_SUCCESS)
3232 		return res;
3233 
3234 	cs->ctx_finalize = crypto_authenc_final;
3235 	cs->state = CRYP_STATE_INITIALIZED;
3236 
3237 	return TEE_SUCCESS;
3238 }
3239 
3240 TEE_Result syscall_authenc_update_aad(unsigned long state,
3241 				      const void *aad_data, size_t aad_data_len)
3242 {
3243 	TEE_Result res = TEE_SUCCESS;
3244 	struct tee_cryp_state *cs;
3245 	struct tee_ta_session *sess;
3246 
3247 	res = tee_ta_get_current_session(&sess);
3248 	if (res != TEE_SUCCESS)
3249 		return res;
3250 
3251 	res = tee_mmu_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
3252 					  TEE_MEMORY_ACCESS_READ |
3253 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3254 					  (uaddr_t) aad_data,
3255 					  aad_data_len);
3256 	if (res != TEE_SUCCESS)
3257 		return res;
3258 
3259 	res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
3260 	if (res != TEE_SUCCESS)
3261 		return res;
3262 
3263 	if (cs->state != CRYP_STATE_INITIALIZED)
3264 		return TEE_ERROR_BAD_STATE;
3265 
3266 	if (TEE_ALG_GET_CLASS(cs->algo) != TEE_OPERATION_AE)
3267 		return TEE_ERROR_BAD_STATE;
3268 
3269 	res = crypto_authenc_update_aad(cs->ctx, cs->mode, aad_data,
3270 					aad_data_len);
3271 	if (res != TEE_SUCCESS)
3272 		return res;
3273 
3274 	return TEE_SUCCESS;
3275 }
3276 
3277 TEE_Result syscall_authenc_update_payload(unsigned long state,
3278 					  const void *src_data,
3279 					  size_t src_len, void *dst_data,
3280 					  uint64_t *dst_len)
3281 {
3282 	struct tee_ta_session *sess = NULL;
3283 	struct tee_cryp_state *cs = NULL;
3284 	TEE_Result res = TEE_SUCCESS;
3285 	size_t dlen = 0;
3286 
3287 	res = tee_ta_get_current_session(&sess);
3288 	if (res != TEE_SUCCESS)
3289 		return res;
3290 
3291 	res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
3292 	if (res != TEE_SUCCESS)
3293 		return res;
3294 
3295 	if (cs->state != CRYP_STATE_INITIALIZED)
3296 		return TEE_ERROR_BAD_STATE;
3297 
3298 	if (TEE_ALG_GET_CLASS(cs->algo) != TEE_OPERATION_AE)
3299 		return TEE_ERROR_BAD_STATE;
3300 
3301 	res = tee_mmu_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
3302 					  TEE_MEMORY_ACCESS_READ |
3303 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3304 					  (uaddr_t)src_data, src_len);
3305 	if (res != TEE_SUCCESS)
3306 		return res;
3307 
3308 	res = get_user_u64_as_size_t(&dlen, dst_len);
3309 	if (res != TEE_SUCCESS)
3310 		return res;
3311 
3312 	res = tee_mmu_check_access_rights(&to_user_ta_ctx(sess->ctx)->uctx,
3313 					  TEE_MEMORY_ACCESS_READ |
3314 					  TEE_MEMORY_ACCESS_WRITE |
3315 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3316 					  (uaddr_t)dst_data, dlen);
3317 	if (res != TEE_SUCCESS)
3318 		return res;
3319 
3320 	if (dlen < src_len) {
3321 		res = TEE_ERROR_SHORT_BUFFER;
3322 		goto out;
3323 	}
3324 
3325 	res = crypto_authenc_update_payload(cs->ctx, cs->mode, src_data,
3326 					    src_len, dst_data, &dlen);
3327 out:
3328 	if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
3329 		TEE_Result res2 = put_user_u64(dst_len, dlen);
3330 
3331 		if (res2 != TEE_SUCCESS)
3332 			res = res2;
3333 	}
3334 
3335 	return res;
3336 }
3337 
3338 TEE_Result syscall_authenc_enc_final(unsigned long state, const void *src_data,
3339 				     size_t src_len, void *dst_data,
3340 				     uint64_t *dst_len, void *tag,
3341 				     uint64_t *tag_len)
3342 {
3343 	struct tee_ta_session *sess = NULL;
3344 	struct user_mode_ctx *uctx = NULL;
3345 	struct tee_cryp_state *cs = NULL;
3346 	TEE_Result res = TEE_SUCCESS;
3347 	size_t dlen = 0;
3348 	size_t tlen = 0;
3349 
3350 	res = tee_ta_get_current_session(&sess);
3351 	if (res != TEE_SUCCESS)
3352 		return res;
3353 
3354 	uctx = &to_user_ta_ctx(sess->ctx)->uctx;
3355 
3356 	res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
3357 	if (res != TEE_SUCCESS)
3358 		return res;
3359 
3360 	if (cs->state != CRYP_STATE_INITIALIZED)
3361 		return TEE_ERROR_BAD_STATE;
3362 
3363 	if (cs->mode != TEE_MODE_ENCRYPT)
3364 		return TEE_ERROR_BAD_PARAMETERS;
3365 
3366 	if (TEE_ALG_GET_CLASS(cs->algo) != TEE_OPERATION_AE)
3367 		return TEE_ERROR_BAD_STATE;
3368 
3369 	res = tee_mmu_check_access_rights(uctx,
3370 					  TEE_MEMORY_ACCESS_READ |
3371 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3372 					  (uaddr_t)src_data, src_len);
3373 	if (res != TEE_SUCCESS)
3374 		return res;
3375 
3376 	if (!dst_len) {
3377 		dlen = 0;
3378 	} else {
3379 		res = get_user_u64_as_size_t(&dlen, dst_len);
3380 		if (res != TEE_SUCCESS)
3381 			return res;
3382 
3383 		res = tee_mmu_check_access_rights(uctx,
3384 						  TEE_MEMORY_ACCESS_READ |
3385 						  TEE_MEMORY_ACCESS_WRITE |
3386 						  TEE_MEMORY_ACCESS_ANY_OWNER,
3387 						  (uaddr_t)dst_data, dlen);
3388 		if (res != TEE_SUCCESS)
3389 			return res;
3390 	}
3391 
3392 	if (dlen < src_len) {
3393 		res = TEE_ERROR_SHORT_BUFFER;
3394 		goto out;
3395 	}
3396 
3397 	res = get_user_u64_as_size_t(&tlen, tag_len);
3398 	if (res != TEE_SUCCESS)
3399 		return res;
3400 
3401 	res = tee_mmu_check_access_rights(uctx,
3402 					  TEE_MEMORY_ACCESS_READ |
3403 					  TEE_MEMORY_ACCESS_WRITE |
3404 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3405 					  (uaddr_t)tag, tlen);
3406 	if (res != TEE_SUCCESS)
3407 		return res;
3408 
3409 	res = crypto_authenc_enc_final(cs->ctx, src_data, src_len, dst_data,
3410 				       &dlen, tag, &tlen);
3411 
3412 out:
3413 	if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
3414 		TEE_Result res2 = TEE_SUCCESS;
3415 
3416 		if (dst_len != NULL) {
3417 			res2 = put_user_u64(dst_len, dlen);
3418 			if (res2 != TEE_SUCCESS)
3419 				return res2;
3420 		}
3421 
3422 		res2 = put_user_u64(tag_len, tlen);
3423 		if (res2 != TEE_SUCCESS)
3424 			return res2;
3425 	}
3426 
3427 	return res;
3428 }
3429 
3430 TEE_Result syscall_authenc_dec_final(unsigned long state,
3431 			const void *src_data, size_t src_len, void *dst_data,
3432 			uint64_t *dst_len, const void *tag, size_t tag_len)
3433 {
3434 	struct tee_ta_session *sess = NULL;
3435 	struct user_mode_ctx *uctx = NULL;
3436 	struct tee_cryp_state *cs = NULL;
3437 	TEE_Result res = TEE_SUCCESS;
3438 	size_t dlen = 0;
3439 
3440 	res = tee_ta_get_current_session(&sess);
3441 	if (res != TEE_SUCCESS)
3442 		return res;
3443 
3444 	uctx = &to_user_ta_ctx(sess->ctx)->uctx;
3445 
3446 	res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
3447 	if (res != TEE_SUCCESS)
3448 		return res;
3449 
3450 	if (cs->state != CRYP_STATE_INITIALIZED)
3451 		return TEE_ERROR_BAD_STATE;
3452 
3453 	if (cs->mode != TEE_MODE_DECRYPT)
3454 		return TEE_ERROR_BAD_PARAMETERS;
3455 
3456 	if (TEE_ALG_GET_CLASS(cs->algo) != TEE_OPERATION_AE)
3457 		return TEE_ERROR_BAD_STATE;
3458 
3459 	res = tee_mmu_check_access_rights(uctx,
3460 					  TEE_MEMORY_ACCESS_READ |
3461 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3462 					  (uaddr_t)src_data, src_len);
3463 	if (res != TEE_SUCCESS)
3464 		return res;
3465 
3466 	if (!dst_len) {
3467 		dlen = 0;
3468 	} else {
3469 		res = get_user_u64_as_size_t(&dlen, dst_len);
3470 		if (res != TEE_SUCCESS)
3471 			return res;
3472 
3473 		res = tee_mmu_check_access_rights(uctx,
3474 						  TEE_MEMORY_ACCESS_READ |
3475 						  TEE_MEMORY_ACCESS_WRITE |
3476 						  TEE_MEMORY_ACCESS_ANY_OWNER,
3477 						  (uaddr_t)dst_data, dlen);
3478 		if (res != TEE_SUCCESS)
3479 			return res;
3480 	}
3481 
3482 	if (dlen < src_len) {
3483 		res = TEE_ERROR_SHORT_BUFFER;
3484 		goto out;
3485 	}
3486 
3487 	res = tee_mmu_check_access_rights(uctx,
3488 					  TEE_MEMORY_ACCESS_READ |
3489 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3490 					  (uaddr_t)tag, tag_len);
3491 	if (res != TEE_SUCCESS)
3492 		return res;
3493 
3494 	res = crypto_authenc_dec_final(cs->ctx, src_data, src_len, dst_data,
3495 				       &dlen, tag, tag_len);
3496 
3497 out:
3498 	if ((res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) &&
3499 	    dst_len != NULL) {
3500 		TEE_Result res2 = put_user_u64(dst_len, dlen);
3501 
3502 		if (res2 != TEE_SUCCESS)
3503 			return res2;
3504 	}
3505 
3506 	return res;
3507 }
3508 
3509 static int pkcs1_get_salt_len(const TEE_Attribute *params, uint32_t num_params,
3510 			      size_t default_len)
3511 {
3512 	size_t n;
3513 
3514 	assert(default_len < INT_MAX);
3515 
3516 	for (n = 0; n < num_params; n++) {
3517 		if (params[n].attributeID == TEE_ATTR_RSA_PSS_SALT_LENGTH) {
3518 			if (params[n].content.value.a < INT_MAX)
3519 				return params[n].content.value.a;
3520 			break;
3521 		}
3522 	}
3523 	/*
3524 	 * If salt length isn't provided use the default value which is
3525 	 * the length of the digest.
3526 	 */
3527 	return default_len;
3528 }
3529 
3530 TEE_Result syscall_asymm_operate(unsigned long state,
3531 			const struct utee_attribute *usr_params,
3532 			size_t num_params, const void *src_data, size_t src_len,
3533 			void *dst_data, uint64_t *dst_len)
3534 {
3535 	TEE_Result res;
3536 	struct tee_cryp_state *cs;
3537 	struct tee_ta_session *sess;
3538 	size_t dlen;
3539 	struct tee_obj *o;
3540 	void *label = NULL;
3541 	size_t label_len = 0;
3542 	size_t n;
3543 	int salt_len;
3544 	TEE_Attribute *params = NULL;
3545 	struct user_ta_ctx *utc;
3546 
3547 	res = tee_ta_get_current_session(&sess);
3548 	if (res != TEE_SUCCESS)
3549 		return res;
3550 	utc = to_user_ta_ctx(sess->ctx);
3551 
3552 	res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
3553 	if (res != TEE_SUCCESS)
3554 		return res;
3555 
3556 	res = tee_mmu_check_access_rights(&utc->uctx,
3557 					  TEE_MEMORY_ACCESS_READ |
3558 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3559 					  (uaddr_t)src_data, src_len);
3560 	if (res != TEE_SUCCESS)
3561 		return res;
3562 
3563 	res = get_user_u64_as_size_t(&dlen, dst_len);
3564 	if (res != TEE_SUCCESS)
3565 		return res;
3566 
3567 	res = tee_mmu_check_access_rights(&utc->uctx,
3568 					  TEE_MEMORY_ACCESS_READ |
3569 					  TEE_MEMORY_ACCESS_WRITE |
3570 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3571 					  (uaddr_t)dst_data, dlen);
3572 	if (res != TEE_SUCCESS)
3573 		return res;
3574 
3575 	size_t alloc_size = 0;
3576 
3577 	if (MUL_OVERFLOW(sizeof(TEE_Attribute), num_params, &alloc_size))
3578 		return TEE_ERROR_OVERFLOW;
3579 
3580 	params = malloc(alloc_size);
3581 	if (!params)
3582 		return TEE_ERROR_OUT_OF_MEMORY;
3583 	res = copy_in_attrs(utc, usr_params, num_params, params);
3584 	if (res != TEE_SUCCESS)
3585 		goto out;
3586 
3587 	res = tee_obj_get(utc, cs->key1, &o);
3588 	if (res != TEE_SUCCESS)
3589 		goto out;
3590 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
3591 		res = TEE_ERROR_GENERIC;
3592 		goto out;
3593 	}
3594 
3595 	switch (cs->algo) {
3596 	case TEE_ALG_RSA_NOPAD:
3597 		if (cs->mode == TEE_MODE_ENCRYPT) {
3598 			res = crypto_acipher_rsanopad_encrypt(o->attr, src_data,
3599 							      src_len, dst_data,
3600 							      &dlen);
3601 		} else if (cs->mode == TEE_MODE_DECRYPT) {
3602 			res = crypto_acipher_rsanopad_decrypt(o->attr, src_data,
3603 							      src_len, dst_data,
3604 							      &dlen);
3605 		} else {
3606 			/*
3607 			 * We will panic because "the mode is not compatible
3608 			 * with the function"
3609 			 */
3610 			res = TEE_ERROR_GENERIC;
3611 		}
3612 		break;
3613 
3614 	case TEE_ALG_SM2_PKE:
3615 		if (cs->mode == TEE_MODE_ENCRYPT) {
3616 			res = crypto_acipher_sm2_pke_encrypt(o->attr, src_data,
3617 							     src_len, dst_data,
3618 							     &dlen);
3619 		} else if (cs->mode == TEE_MODE_DECRYPT) {
3620 			res = crypto_acipher_sm2_pke_decrypt(o->attr, src_data,
3621 							     src_len, dst_data,
3622 							     &dlen);
3623 		} else {
3624 			res = TEE_ERROR_GENERIC;
3625 		}
3626 		break;
3627 
3628 	case TEE_ALG_RSAES_PKCS1_V1_5:
3629 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
3630 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
3631 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
3632 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
3633 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
3634 		for (n = 0; n < num_params; n++) {
3635 			if (params[n].attributeID == TEE_ATTR_RSA_OAEP_LABEL) {
3636 				label = params[n].content.ref.buffer;
3637 				label_len = params[n].content.ref.length;
3638 				break;
3639 			}
3640 		}
3641 
3642 		if (cs->mode == TEE_MODE_ENCRYPT) {
3643 			res = crypto_acipher_rsaes_encrypt(cs->algo, o->attr,
3644 							   label, label_len,
3645 							   src_data, src_len,
3646 							   dst_data, &dlen);
3647 		} else if (cs->mode == TEE_MODE_DECRYPT) {
3648 			res = crypto_acipher_rsaes_decrypt(
3649 					cs->algo, o->attr, label, label_len,
3650 					src_data, src_len, dst_data, &dlen);
3651 		} else {
3652 			res = TEE_ERROR_BAD_PARAMETERS;
3653 		}
3654 		break;
3655 
3656 #if defined(CFG_CRYPTO_RSASSA_NA1)
3657 	case TEE_ALG_RSASSA_PKCS1_V1_5:
3658 #endif
3659 	case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
3660 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
3661 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
3662 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
3663 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
3664 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
3665 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
3666 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
3667 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
3668 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
3669 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
3670 		if (cs->mode != TEE_MODE_SIGN) {
3671 			res = TEE_ERROR_BAD_PARAMETERS;
3672 			break;
3673 		}
3674 		salt_len = pkcs1_get_salt_len(params, num_params, src_len);
3675 		res = crypto_acipher_rsassa_sign(cs->algo, o->attr, salt_len,
3676 						 src_data, src_len, dst_data,
3677 						 &dlen);
3678 		break;
3679 
3680 	case TEE_ALG_DSA_SHA1:
3681 	case TEE_ALG_DSA_SHA224:
3682 	case TEE_ALG_DSA_SHA256:
3683 		res = crypto_acipher_dsa_sign(cs->algo, o->attr, src_data,
3684 					      src_len, dst_data, &dlen);
3685 		break;
3686 	case TEE_ALG_ECDSA_P192:
3687 	case TEE_ALG_ECDSA_P224:
3688 	case TEE_ALG_ECDSA_P256:
3689 	case TEE_ALG_ECDSA_P384:
3690 	case TEE_ALG_ECDSA_P521:
3691 		res = crypto_acipher_ecc_sign(cs->algo, o->attr, src_data,
3692 					      src_len, dst_data, &dlen);
3693 		break;
3694 	case TEE_ALG_SM2_DSA_SM3:
3695 		res = crypto_acipher_sm2_dsa_sign(cs->algo, o->attr, src_data,
3696 						  src_len, dst_data, &dlen);
3697 		break;
3698 
3699 	default:
3700 		res = TEE_ERROR_BAD_PARAMETERS;
3701 		break;
3702 	}
3703 
3704 out:
3705 	free_wipe(params);
3706 
3707 	if (res == TEE_SUCCESS || res == TEE_ERROR_SHORT_BUFFER) {
3708 		TEE_Result res2 = put_user_u64(dst_len, dlen);
3709 
3710 		if (res2 != TEE_SUCCESS)
3711 			return res2;
3712 	}
3713 
3714 	return res;
3715 }
3716 
3717 TEE_Result syscall_asymm_verify(unsigned long state,
3718 			const struct utee_attribute *usr_params,
3719 			size_t num_params, const void *data, size_t data_len,
3720 			const void *sig, size_t sig_len)
3721 {
3722 	struct tee_ta_session *sess = NULL;
3723 	struct tee_cryp_state *cs = NULL;
3724 	struct user_ta_ctx *utc = NULL;
3725 	TEE_Result res = TEE_SUCCESS;
3726 	TEE_Attribute *params = NULL;
3727 	struct tee_obj *o = NULL;
3728 	size_t hash_size = 0;
3729 	uint32_t hash_algo = 0;
3730 	int salt_len = 0;
3731 
3732 	res = tee_ta_get_current_session(&sess);
3733 	if (res != TEE_SUCCESS)
3734 		return res;
3735 	utc = to_user_ta_ctx(sess->ctx);
3736 
3737 	res = tee_svc_cryp_get_state(sess, tee_svc_uref_to_vaddr(state), &cs);
3738 	if (res != TEE_SUCCESS)
3739 		return res;
3740 
3741 	if (cs->mode != TEE_MODE_VERIFY)
3742 		return TEE_ERROR_BAD_PARAMETERS;
3743 
3744 	res = tee_mmu_check_access_rights(&utc->uctx,
3745 					  TEE_MEMORY_ACCESS_READ |
3746 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3747 					  (uaddr_t)data, data_len);
3748 	if (res != TEE_SUCCESS)
3749 		return res;
3750 
3751 	res = tee_mmu_check_access_rights(&utc->uctx,
3752 					  TEE_MEMORY_ACCESS_READ |
3753 					  TEE_MEMORY_ACCESS_ANY_OWNER,
3754 					  (uaddr_t)sig, sig_len);
3755 	if (res != TEE_SUCCESS)
3756 		return res;
3757 
3758 	size_t alloc_size = 0;
3759 
3760 	if (MUL_OVERFLOW(sizeof(TEE_Attribute), num_params, &alloc_size))
3761 		return TEE_ERROR_OVERFLOW;
3762 
3763 	params = malloc(alloc_size);
3764 	if (!params)
3765 		return TEE_ERROR_OUT_OF_MEMORY;
3766 	res = copy_in_attrs(utc, usr_params, num_params, params);
3767 	if (res != TEE_SUCCESS)
3768 		goto out;
3769 
3770 	res = tee_obj_get(utc, cs->key1, &o);
3771 	if (res != TEE_SUCCESS)
3772 		goto out;
3773 	if ((o->info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
3774 		res = TEE_ERROR_BAD_PARAMETERS;
3775 		goto out;
3776 	}
3777 
3778 	switch (TEE_ALG_GET_MAIN_ALG(cs->algo)) {
3779 	case TEE_MAIN_ALGO_RSA:
3780 		if (cs->algo != TEE_ALG_RSASSA_PKCS1_V1_5) {
3781 			hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo);
3782 			res = tee_alg_get_digest_size(hash_algo, &hash_size);
3783 			if (res != TEE_SUCCESS)
3784 				break;
3785 			if (data_len != hash_size) {
3786 				res = TEE_ERROR_BAD_PARAMETERS;
3787 				break;
3788 			}
3789 			salt_len = pkcs1_get_salt_len(params, num_params,
3790 						      hash_size);
3791 		}
3792 		res = crypto_acipher_rsassa_verify(cs->algo, o->attr, salt_len,
3793 						   data, data_len, sig,
3794 						   sig_len);
3795 		break;
3796 
3797 	case TEE_MAIN_ALGO_DSA:
3798 		hash_algo = TEE_DIGEST_HASH_TO_ALGO(cs->algo);
3799 		res = tee_alg_get_digest_size(hash_algo, &hash_size);
3800 		if (res != TEE_SUCCESS)
3801 			break;
3802 		/*
3803 		 * Depending on the DSA algorithm (NIST), the digital signature
3804 		 * output size may be truncated to the size of a key pair
3805 		 * (Q prime size). Q prime size must be less or equal than the
3806 		 * hash output length of the hash algorithm involved.
3807 		 */
3808 		if (data_len > hash_size) {
3809 			res = TEE_ERROR_BAD_PARAMETERS;
3810 			break;
3811 		}
3812 		res = crypto_acipher_dsa_verify(cs->algo, o->attr, data,
3813 						data_len, sig, sig_len);
3814 		break;
3815 
3816 	case TEE_MAIN_ALGO_ECDSA:
3817 		res = crypto_acipher_ecc_verify(cs->algo, o->attr, data,
3818 						data_len, sig, sig_len);
3819 		break;
3820 
3821 	case TEE_MAIN_ALGO_SM2_DSA_SM3:
3822 		res = crypto_acipher_sm2_dsa_verify(cs->algo, o->attr, data,
3823 						    data_len, sig, sig_len);
3824 		break;
3825 
3826 	default:
3827 		res = TEE_ERROR_NOT_SUPPORTED;
3828 	}
3829 
3830 out:
3831 	free_wipe(params);
3832 	return res;
3833 }
3834