xref: /optee_os/ta/pkcs11/src/processing_asymm.c (revision ea36ae9b4a2f188d4d2ebf2be3e40262a6e98d05)
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2018-2020, Linaro Limited
4  */
5 
6 #include <assert.h>
7 #include <compiler.h>
8 #include <mbedtls/nist_kw.h>
9 #include <string_ext.h>
10 #include <tee_api_defines.h>
11 #include <tee_internal_api.h>
12 #include <tee_internal_api_extensions.h>
13 
14 #include "attributes.h"
15 #include "pkcs11_helpers.h"
16 #include "pkcs11_token.h"
17 #include "processing.h"
18 #include "serializer.h"
19 
20 bool processing_is_tee_asymm(uint32_t proc_id)
21 {
22 	switch (proc_id) {
23 	/* RSA flavors */
24 	case PKCS11_CKM_RSA_AES_KEY_WRAP:
25 	case PKCS11_CKM_RSA_PKCS:
26 	case PKCS11_CKM_RSA_X_509:
27 	case PKCS11_CKM_RSA_PKCS_OAEP:
28 	case PKCS11_CKM_RSA_PKCS_PSS:
29 	case PKCS11_CKM_MD5_RSA_PKCS:
30 	case PKCS11_CKM_SHA1_RSA_PKCS:
31 	case PKCS11_CKM_SHA224_RSA_PKCS:
32 	case PKCS11_CKM_SHA256_RSA_PKCS:
33 	case PKCS11_CKM_SHA384_RSA_PKCS:
34 	case PKCS11_CKM_SHA512_RSA_PKCS:
35 	case PKCS11_CKM_SHA1_RSA_PKCS_PSS:
36 	case PKCS11_CKM_SHA224_RSA_PKCS_PSS:
37 	case PKCS11_CKM_SHA256_RSA_PKCS_PSS:
38 	case PKCS11_CKM_SHA384_RSA_PKCS_PSS:
39 	case PKCS11_CKM_SHA512_RSA_PKCS_PSS:
40 	/* EC flavors */
41 	case PKCS11_CKM_EDDSA:
42 	case PKCS11_CKM_ECDSA:
43 	case PKCS11_CKM_ECDH1_DERIVE:
44 	case PKCS11_CKM_ECDSA_SHA1:
45 	case PKCS11_CKM_ECDSA_SHA224:
46 	case PKCS11_CKM_ECDSA_SHA256:
47 	case PKCS11_CKM_ECDSA_SHA384:
48 	case PKCS11_CKM_ECDSA_SHA512:
49 		return true;
50 	default:
51 		return false;
52 	}
53 }
54 
55 static enum pkcs11_rc
56 pkcs2tee_algorithm(uint32_t *tee_id, uint32_t *tee_hash_id,
57 		   enum processing_func function __unused,
58 		   struct pkcs11_attribute_head *proc_params,
59 		   struct pkcs11_object *obj)
60 {
61 	static const struct {
62 		enum pkcs11_mechanism_id mech_id;
63 		uint32_t tee_id;
64 		uint32_t tee_hash_id;
65 	} pkcs2tee_algo[] = {
66 		/* RSA flavors */
67 		{ PKCS11_CKM_RSA_AES_KEY_WRAP, 1, 0 },
68 		{ PKCS11_CKM_RSA_PKCS, TEE_ALG_RSAES_PKCS1_V1_5, 0 },
69 		{ PKCS11_CKM_RSA_PKCS_OAEP, 1, 0 },
70 		{ PKCS11_CKM_RSA_PKCS_PSS, 1, 0 },
71 		{ PKCS11_CKM_RSA_X_509, TEE_ALG_RSA_NOPAD, 0 },
72 		{ PKCS11_CKM_MD5_RSA_PKCS, TEE_ALG_RSASSA_PKCS1_V1_5_MD5,
73 		  TEE_ALG_MD5 },
74 		{ PKCS11_CKM_SHA1_RSA_PKCS, TEE_ALG_RSASSA_PKCS1_V1_5_SHA1,
75 		  TEE_ALG_SHA1 },
76 		{ PKCS11_CKM_SHA224_RSA_PKCS, TEE_ALG_RSASSA_PKCS1_V1_5_SHA224,
77 		  TEE_ALG_SHA224 },
78 		{ PKCS11_CKM_SHA256_RSA_PKCS, TEE_ALG_RSASSA_PKCS1_V1_5_SHA256,
79 		  TEE_ALG_SHA256 },
80 		{ PKCS11_CKM_SHA384_RSA_PKCS, TEE_ALG_RSASSA_PKCS1_V1_5_SHA384,
81 		  TEE_ALG_SHA384 },
82 		{ PKCS11_CKM_SHA512_RSA_PKCS, TEE_ALG_RSASSA_PKCS1_V1_5_SHA512,
83 		  TEE_ALG_SHA512 },
84 		{ PKCS11_CKM_SHA1_RSA_PKCS_PSS,
85 		  TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1, TEE_ALG_SHA1 },
86 		{ PKCS11_CKM_SHA224_RSA_PKCS_PSS,
87 		  TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224, TEE_ALG_SHA224 },
88 		{ PKCS11_CKM_SHA256_RSA_PKCS_PSS,
89 		  TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256, TEE_ALG_SHA256 },
90 		{ PKCS11_CKM_SHA384_RSA_PKCS_PSS,
91 		  TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384, TEE_ALG_SHA384 },
92 		{ PKCS11_CKM_SHA512_RSA_PKCS_PSS,
93 		  TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512, TEE_ALG_SHA512 },
94 		/* EC flavors (Must find key size from the object) */
95 		{ PKCS11_CKM_ECDSA, 1, 0 },
96 		{ PKCS11_CKM_ECDSA_SHA1, 1, TEE_ALG_SHA1 },
97 		{ PKCS11_CKM_ECDSA_SHA224, 1, TEE_ALG_SHA224 },
98 		{ PKCS11_CKM_ECDSA_SHA256, 1, TEE_ALG_SHA256 },
99 		{ PKCS11_CKM_ECDSA_SHA384, 1, TEE_ALG_SHA384 },
100 		{ PKCS11_CKM_ECDSA_SHA512, 1, TEE_ALG_SHA512 },
101 		{ PKCS11_CKM_ECDH1_DERIVE, 1, 0 },
102 		{ PKCS11_CKM_EDDSA, TEE_ALG_ED25519, 0 },
103 	};
104 	size_t n = 0;
105 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
106 
107 	for (n = 0; n < ARRAY_SIZE(pkcs2tee_algo); n++) {
108 		if (pkcs2tee_algo[n].mech_id == proc_params->id) {
109 			*tee_id = pkcs2tee_algo[n].tee_id;
110 			*tee_hash_id = pkcs2tee_algo[n].tee_hash_id;
111 			break;
112 		}
113 	}
114 
115 	if (n == ARRAY_SIZE(pkcs2tee_algo))
116 		return PKCS11_RV_NOT_IMPLEMENTED;
117 
118 	switch (proc_params->id) {
119 	case PKCS11_CKM_RSA_PKCS_PSS:
120 	case PKCS11_CKM_SHA1_RSA_PKCS_PSS:
121 	case PKCS11_CKM_SHA224_RSA_PKCS_PSS:
122 	case PKCS11_CKM_SHA256_RSA_PKCS_PSS:
123 	case PKCS11_CKM_SHA384_RSA_PKCS_PSS:
124 	case PKCS11_CKM_SHA512_RSA_PKCS_PSS:
125 		rc = pkcs2tee_algo_rsa_pss(tee_id, proc_params);
126 		break;
127 	case PKCS11_CKM_RSA_PKCS_OAEP:
128 		rc = pkcs2tee_algo_rsa_oaep(tee_id, tee_hash_id, proc_params);
129 		break;
130 	case PKCS11_CKM_RSA_AES_KEY_WRAP:
131 		rc = pkcs2tee_algo_rsa_aes_wrap(tee_id, tee_hash_id,
132 						proc_params);
133 		break;
134 	case PKCS11_CKM_ECDSA:
135 	case PKCS11_CKM_ECDSA_SHA1:
136 	case PKCS11_CKM_ECDSA_SHA224:
137 	case PKCS11_CKM_ECDSA_SHA256:
138 	case PKCS11_CKM_ECDSA_SHA384:
139 	case PKCS11_CKM_ECDSA_SHA512:
140 		rc = pkcs2tee_algo_ecdsa(tee_id, proc_params, obj);
141 		break;
142 	case PKCS11_CKM_ECDH1_DERIVE:
143 		rc = pkcs2tee_algo_ecdh(tee_id, proc_params, obj);
144 		break;
145 	default:
146 		rc = PKCS11_CKR_OK;
147 		break;
148 	}
149 
150 	/*
151 	 * PKCS#11 uses single mechanism CKM_RSA_PKCS for both ciphering and
152 	 * authentication whereas GPD TEE expects TEE_ALG_RSAES_PKCS1_V1_5 for
153 	 * ciphering and TEE_ALG_RSASSA_PKCS1_V1_5 for authentication.
154 	 */
155 	if (*tee_id == TEE_ALG_RSAES_PKCS1_V1_5 &&
156 	    (function == PKCS11_FUNCTION_SIGN ||
157 	     function == PKCS11_FUNCTION_VERIFY))
158 		*tee_id = TEE_ALG_RSASSA_PKCS1_V1_5;
159 
160 	return rc;
161 }
162 
163 static enum pkcs11_rc pkcs2tee_key_type(uint32_t *tee_type,
164 					struct pkcs11_object *obj,
165 					enum processing_func function)
166 {
167 	enum pkcs11_class_id class = get_class(obj->attributes);
168 	enum pkcs11_key_type type = get_key_type(obj->attributes);
169 
170 	switch (class) {
171 	case PKCS11_CKO_PUBLIC_KEY:
172 	case PKCS11_CKO_PRIVATE_KEY:
173 		break;
174 	default:
175 		TEE_Panic(class);
176 		break;
177 	}
178 
179 	switch (type) {
180 	case PKCS11_CKK_EC:
181 		if (class == PKCS11_CKO_PRIVATE_KEY) {
182 			if (function == PKCS11_FUNCTION_DERIVE)
183 				*tee_type = TEE_TYPE_ECDH_KEYPAIR;
184 			else
185 				*tee_type = TEE_TYPE_ECDSA_KEYPAIR;
186 		} else {
187 			if (function == PKCS11_FUNCTION_DERIVE)
188 				*tee_type = TEE_TYPE_ECDH_PUBLIC_KEY;
189 			else
190 				*tee_type = TEE_TYPE_ECDSA_PUBLIC_KEY;
191 		}
192 		break;
193 	case PKCS11_CKK_RSA:
194 		if (class == PKCS11_CKO_PRIVATE_KEY)
195 			*tee_type = TEE_TYPE_RSA_KEYPAIR;
196 		else
197 			*tee_type = TEE_TYPE_RSA_PUBLIC_KEY;
198 		break;
199 	case PKCS11_CKK_EC_EDWARDS:
200 		if (class == PKCS11_CKO_PRIVATE_KEY)
201 			*tee_type = TEE_TYPE_ED25519_KEYPAIR;
202 		else
203 			*tee_type = TEE_TYPE_ED25519_PUBLIC_KEY;
204 		break;
205 	default:
206 		TEE_Panic(type);
207 		break;
208 	}
209 
210 	return PKCS11_CKR_OK;
211 }
212 
213 static enum pkcs11_rc
214 allocate_tee_operation(struct pkcs11_session *session,
215 		       enum processing_func function,
216 		       struct pkcs11_attribute_head *params,
217 		       struct pkcs11_object *obj)
218 {
219 	uint32_t size = (uint32_t)get_object_key_bit_size(obj);
220 	uint32_t algo = 0;
221 	uint32_t hash_algo = 0;
222 	uint32_t mode = 0;
223 	uint32_t hash_mode = 0;
224 	TEE_Result res = TEE_ERROR_GENERIC;
225 	struct active_processing *processing = session->processing;
226 
227 	assert(processing->tee_op_handle == TEE_HANDLE_NULL);
228 	assert(processing->tee_op_handle2 == TEE_HANDLE_NULL);
229 
230 	if (pkcs2tee_algorithm(&algo, &hash_algo, function, params, obj))
231 		return PKCS11_CKR_FUNCTION_FAILED;
232 
233 	/*
234 	 * PKCS#11 allows Sign/Verify with CKM_RSA_X_509 while GP TEE API
235 	 * only permits Encrypt/Decrypt with TEE_ALG_RSA_NOPAD.
236 	 * For other algorithm, use simple 1-to-1 ID conversion pkcs2tee_mode().
237 	 */
238 	if (params->id == PKCS11_CKM_RSA_X_509) {
239 		assert(!hash_algo);
240 		switch (function) {
241 		case PKCS11_FUNCTION_ENCRYPT:
242 		case PKCS11_FUNCTION_VERIFY:
243 			mode = TEE_MODE_ENCRYPT;
244 			break;
245 		case PKCS11_FUNCTION_DECRYPT:
246 		case PKCS11_FUNCTION_SIGN:
247 			mode = TEE_MODE_DECRYPT;
248 			break;
249 		default:
250 			TEE_Panic(0);
251 		}
252 	} else {
253 		pkcs2tee_mode(&mode, function);
254 	}
255 
256 	if (hash_algo) {
257 		pkcs2tee_mode(&hash_mode, PKCS11_FUNCTION_DIGEST);
258 
259 		res = TEE_AllocateOperation(&processing->tee_op_handle2,
260 					    hash_algo, hash_mode, 0);
261 		if (res) {
262 			EMSG("TEE_AllocateOp. failed %#"PRIx32" %#"PRIx32,
263 			     hash_algo, hash_mode);
264 
265 			if (res == TEE_ERROR_NOT_SUPPORTED)
266 				return PKCS11_CKR_MECHANISM_INVALID;
267 			return tee2pkcs_error(res);
268 		}
269 		processing->tee_hash_algo = hash_algo;
270 	}
271 
272 	res = TEE_AllocateOperation(&processing->tee_op_handle,
273 				    algo, mode, size);
274 	if (res)
275 		EMSG("TEE_AllocateOp. failed %#"PRIx32" %#"PRIx32" %#"PRIx32,
276 		     algo, mode, size);
277 
278 	if (res == TEE_ERROR_NOT_SUPPORTED)
279 		return PKCS11_CKR_MECHANISM_INVALID;
280 
281 	if (res != TEE_SUCCESS &&
282 	    processing->tee_op_handle2 != TEE_HANDLE_NULL) {
283 		TEE_FreeOperation(session->processing->tee_op_handle2);
284 		processing->tee_op_handle2 = TEE_HANDLE_NULL;
285 		processing->tee_hash_algo = 0;
286 	}
287 
288 	return tee2pkcs_error(res);
289 }
290 
291 static enum pkcs11_rc load_tee_key(struct pkcs11_session *session,
292 				   struct pkcs11_object *obj,
293 				   enum processing_func function)
294 {
295 	TEE_Attribute *tee_attrs = NULL;
296 	size_t tee_attrs_count = 0;
297 	size_t object_size = 0;
298 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
299 	TEE_Result res = TEE_ERROR_GENERIC;
300 	enum pkcs11_class_id __maybe_unused class = get_class(obj->attributes);
301 	enum pkcs11_key_type type = get_key_type(obj->attributes);
302 
303 	assert(class == PKCS11_CKO_PUBLIC_KEY ||
304 	       class == PKCS11_CKO_PRIVATE_KEY);
305 
306 	if (obj->key_handle != TEE_HANDLE_NULL) {
307 		switch (type) {
308 		case PKCS11_CKK_RSA:
309 			/* RSA loaded keys can be reused */
310 			assert((obj->key_type == TEE_TYPE_RSA_PUBLIC_KEY &&
311 				class == PKCS11_CKO_PUBLIC_KEY) ||
312 			       (obj->key_type == TEE_TYPE_RSA_KEYPAIR &&
313 				class == PKCS11_CKO_PRIVATE_KEY));
314 			goto key_ready;
315 		case PKCS11_CKK_EC:
316 			/* Reuse EC TEE key only if already DSA or DH */
317 			switch (obj->key_type) {
318 			case TEE_TYPE_ECDSA_PUBLIC_KEY:
319 			case TEE_TYPE_ECDSA_KEYPAIR:
320 				if (function != PKCS11_FUNCTION_DERIVE)
321 					goto key_ready;
322 				break;
323 			case TEE_TYPE_ECDH_PUBLIC_KEY:
324 			case TEE_TYPE_ECDH_KEYPAIR:
325 				if (function == PKCS11_FUNCTION_DERIVE)
326 					goto key_ready;
327 				break;
328 			default:
329 				assert(0);
330 				break;
331 			}
332 			break;
333 		case PKCS11_CKK_EC_EDWARDS:
334 			assert((obj->key_type == TEE_TYPE_ED25519_PUBLIC_KEY &&
335 				class == PKCS11_CKO_PUBLIC_KEY) ||
336 			       (obj->key_type == TEE_TYPE_ED25519_KEYPAIR &&
337 				class == PKCS11_CKO_PRIVATE_KEY));
338 			goto key_ready;
339 		default:
340 			assert(0);
341 			break;
342 		}
343 
344 		TEE_CloseObject(obj->key_handle);
345 		obj->key_handle = TEE_HANDLE_NULL;
346 	}
347 
348 	rc = pkcs2tee_key_type(&obj->key_type, obj, function);
349 	if (rc)
350 		return rc;
351 
352 	object_size = get_object_key_bit_size(obj);
353 	if (!object_size)
354 		return PKCS11_CKR_GENERAL_ERROR;
355 
356 	switch (type) {
357 	case PKCS11_CKK_RSA:
358 		rc = load_tee_rsa_key_attrs(&tee_attrs, &tee_attrs_count, obj);
359 		break;
360 	case PKCS11_CKK_EC:
361 		rc = load_tee_ec_key_attrs(&tee_attrs, &tee_attrs_count, obj);
362 		break;
363 	case PKCS11_CKK_EC_EDWARDS:
364 		rc = load_tee_eddsa_key_attrs(&tee_attrs, &tee_attrs_count,
365 					      obj);
366 		break;
367 	default:
368 		break;
369 	}
370 	if (rc)
371 		return rc;
372 
373 	res = TEE_AllocateTransientObject(obj->key_type, object_size,
374 					  &obj->key_handle);
375 	if (res) {
376 		DMSG("TEE_AllocateTransientObject failed, %#"PRIx32, res);
377 
378 		return tee2pkcs_error(res);
379 	}
380 
381 	res = TEE_PopulateTransientObject(obj->key_handle,
382 					  tee_attrs, tee_attrs_count);
383 
384 	TEE_Free(tee_attrs);
385 
386 	if (res) {
387 		DMSG("TEE_PopulateTransientObject failed, %#"PRIx32, res);
388 
389 		goto error;
390 	}
391 
392 key_ready:
393 	res = TEE_SetOperationKey(session->processing->tee_op_handle,
394 				  obj->key_handle);
395 	if (res) {
396 		DMSG("TEE_SetOperationKey failed, %#"PRIx32, res);
397 
398 		goto error;
399 	}
400 
401 	return PKCS11_CKR_OK;
402 
403 error:
404 	TEE_FreeTransientObject(obj->key_handle);
405 	obj->key_handle = TEE_HANDLE_NULL;
406 	return tee2pkcs_error(res);
407 }
408 
409 static enum pkcs11_rc
410 init_tee_operation(struct pkcs11_session *session,
411 		   struct pkcs11_attribute_head *proc_params,
412 		   struct pkcs11_object *obj)
413 {
414 	enum pkcs11_rc rc = PKCS11_CKR_OK;
415 	struct active_processing *proc = session->processing;
416 
417 	switch (proc_params->id) {
418 	case PKCS11_CKM_RSA_X_509:
419 		rc = pkcs2tee_rsa_nopad_context(proc);
420 		break;
421 	case PKCS11_CKM_RSA_PKCS_PSS:
422 	case PKCS11_CKM_SHA1_RSA_PKCS_PSS:
423 	case PKCS11_CKM_SHA224_RSA_PKCS_PSS:
424 	case PKCS11_CKM_SHA256_RSA_PKCS_PSS:
425 	case PKCS11_CKM_SHA384_RSA_PKCS_PSS:
426 	case PKCS11_CKM_SHA512_RSA_PKCS_PSS:
427 		rc = pkcs2tee_proc_params_rsa_pss(proc, proc_params);
428 		if (rc)
429 			break;
430 
431 		rc = pkcs2tee_validate_rsa_pss(proc, obj);
432 		break;
433 	case PKCS11_CKM_RSA_PKCS_OAEP:
434 		rc = pkcs2tee_proc_params_rsa_oaep(proc, proc_params);
435 		break;
436 	case PKCS11_CKM_EDDSA:
437 		rc = pkcs2tee_proc_params_eddsa(proc, proc_params);
438 		break;
439 	case PKCS11_CKM_RSA_AES_KEY_WRAP:
440 		rc = pkcs2tee_proc_params_rsa_aes_wrap(proc, proc_params);
441 		break;
442 	default:
443 		break;
444 	}
445 
446 	return rc;
447 }
448 
449 enum pkcs11_rc init_asymm_operation(struct pkcs11_session *session,
450 				    enum processing_func function,
451 				    struct pkcs11_attribute_head *proc_params,
452 				    struct pkcs11_object *obj)
453 {
454 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
455 
456 	assert(processing_is_tee_asymm(proc_params->id));
457 
458 	rc = allocate_tee_operation(session, function, proc_params, obj);
459 	if (rc)
460 		return rc;
461 
462 	rc = load_tee_key(session, obj, function);
463 	if (rc)
464 		return rc;
465 
466 	rc = init_tee_operation(session, proc_params, obj);
467 	if (!rc)
468 		session->processing->mecha_type = proc_params->id;
469 
470 	return rc;
471 }
472 
473 /*
474  * step_sym_step - step (update/oneshot/final) on a symmetric crypto operation
475  *
476  * @session - current session
477  * @function - processing function (encrypt, decrypt, sign, ...)
478  * @step - step ID in the processing (oneshot, update, final)
479  * @ptypes - invocation parameter types
480  * @params - invocation parameter references
481  */
482 enum pkcs11_rc step_asymm_operation(struct pkcs11_session *session,
483 				    enum processing_func function,
484 				    enum processing_step step,
485 				    uint32_t ptypes, TEE_Param *params)
486 {
487 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
488 	TEE_Result res = TEE_ERROR_GENERIC;
489 	void *in_buf = NULL;
490 	void *in2_buf = NULL;
491 	void *out_buf = NULL;
492 	void *hash_buf = NULL;
493 	void *temp_buf = NULL;
494 	uint32_t in_size = 0;
495 	uint32_t in2_size = 0;
496 	size_t out_size = 0;
497 	size_t hash_size = 0;
498 	size_t temp_size = 0;
499 	TEE_Attribute *tee_attrs = NULL;
500 	size_t tee_attrs_count = 0;
501 	bool output_data = false;
502 	struct active_processing *proc = session->processing;
503 	struct rsa_aes_key_wrap_processing_ctx *rsa_aes_ctx = NULL;
504 	struct rsa_oaep_processing_ctx *rsa_oaep_ctx = NULL;
505 	struct rsa_pss_processing_ctx *rsa_pss_ctx = NULL;
506 	struct eddsa_processing_ctx *eddsa_ctx = NULL;
507 	size_t sz = 0;
508 
509 	if (TEE_PARAM_TYPE_GET(ptypes, 1) == TEE_PARAM_TYPE_MEMREF_INPUT) {
510 		in_buf = params[1].memref.buffer;
511 		in_size = params[1].memref.size;
512 		if (in_size && !in_buf)
513 			return PKCS11_CKR_ARGUMENTS_BAD;
514 	}
515 	if (TEE_PARAM_TYPE_GET(ptypes, 2) == TEE_PARAM_TYPE_MEMREF_INPUT) {
516 		in2_buf = params[2].memref.buffer;
517 		in2_size = params[2].memref.size;
518 		if (in2_size && !in2_buf)
519 			return PKCS11_CKR_ARGUMENTS_BAD;
520 	}
521 	if (TEE_PARAM_TYPE_GET(ptypes, 2) == TEE_PARAM_TYPE_MEMREF_OUTPUT) {
522 		out_buf = params[2].memref.buffer;
523 		out_size = params[2].memref.size;
524 		if (out_size && !out_buf)
525 			return PKCS11_CKR_ARGUMENTS_BAD;
526 	}
527 	if (TEE_PARAM_TYPE_GET(ptypes, 3) != TEE_PARAM_TYPE_NONE)
528 		return PKCS11_CKR_ARGUMENTS_BAD;
529 
530 	switch (step) {
531 	case PKCS11_FUNC_STEP_ONESHOT:
532 	case PKCS11_FUNC_STEP_UPDATE:
533 	case PKCS11_FUNC_STEP_FINAL:
534 		break;
535 	default:
536 		return PKCS11_CKR_GENERAL_ERROR;
537 	}
538 
539 	/* TEE attribute(s) required by the operation */
540 	switch (proc->mecha_type) {
541 	case PKCS11_CKM_RSA_PKCS_PSS:
542 	case PKCS11_CKM_SHA1_RSA_PKCS_PSS:
543 	case PKCS11_CKM_SHA224_RSA_PKCS_PSS:
544 	case PKCS11_CKM_SHA256_RSA_PKCS_PSS:
545 	case PKCS11_CKM_SHA384_RSA_PKCS_PSS:
546 	case PKCS11_CKM_SHA512_RSA_PKCS_PSS:
547 		tee_attrs = TEE_Malloc(sizeof(TEE_Attribute),
548 				       TEE_USER_MEM_HINT_NO_FILL_ZERO);
549 		if (!tee_attrs) {
550 			rc = PKCS11_CKR_DEVICE_MEMORY;
551 			goto out;
552 		}
553 
554 		rsa_pss_ctx = proc->extra_ctx;
555 
556 		TEE_InitValueAttribute(&tee_attrs[tee_attrs_count],
557 				       TEE_ATTR_RSA_PSS_SALT_LENGTH,
558 				       rsa_pss_ctx->salt_len, 0);
559 		tee_attrs_count++;
560 		break;
561 	case PKCS11_CKM_EDDSA:
562 		eddsa_ctx = proc->extra_ctx;
563 
564 		tee_attrs = TEE_Malloc(2 * sizeof(TEE_Attribute),
565 				       TEE_USER_MEM_HINT_NO_FILL_ZERO);
566 		if (!tee_attrs) {
567 			rc = PKCS11_CKR_DEVICE_MEMORY;
568 			goto out;
569 		}
570 
571 		if (eddsa_ctx->flag) {
572 			TEE_InitValueAttribute(&tee_attrs[tee_attrs_count],
573 					       TEE_ATTR_EDDSA_PREHASH, 0, 0);
574 			tee_attrs_count++;
575 		}
576 
577 		if (eddsa_ctx->ctx_len > 0) {
578 			TEE_InitRefAttribute(&tee_attrs[tee_attrs_count],
579 					     TEE_ATTR_EDDSA_CTX, eddsa_ctx->ctx,
580 					     eddsa_ctx->ctx_len);
581 			tee_attrs_count++;
582 		}
583 		break;
584 	case PKCS11_CKM_RSA_PKCS_OAEP:
585 		rsa_oaep_ctx = proc->extra_ctx;
586 
587 		if (!rsa_oaep_ctx->source_data_len)
588 			break;
589 
590 		tee_attrs = TEE_Malloc(sizeof(TEE_Attribute),
591 				       TEE_USER_MEM_HINT_NO_FILL_ZERO);
592 		if (!tee_attrs) {
593 			rc = PKCS11_CKR_DEVICE_MEMORY;
594 			goto out;
595 		}
596 
597 		TEE_InitRefAttribute(&tee_attrs[tee_attrs_count],
598 				     TEE_ATTR_RSA_OAEP_LABEL,
599 				     rsa_oaep_ctx->source_data,
600 				     rsa_oaep_ctx->source_data_len);
601 		tee_attrs_count++;
602 		break;
603 	case PKCS11_CKM_RSA_AES_KEY_WRAP:
604 		rsa_aes_ctx = proc->extra_ctx;
605 
606 		if (!rsa_aes_ctx->source_data_len)
607 			break;
608 
609 		tee_attrs = TEE_Malloc(sizeof(TEE_Attribute),
610 				       TEE_USER_MEM_HINT_NO_FILL_ZERO);
611 		if (!tee_attrs) {
612 			rc = PKCS11_CKR_DEVICE_MEMORY;
613 			goto out;
614 		}
615 
616 		TEE_InitRefAttribute(&tee_attrs[tee_attrs_count],
617 				     TEE_ATTR_RSA_OAEP_LABEL,
618 				     rsa_aes_ctx->source_data,
619 				     rsa_aes_ctx->source_data_len);
620 		tee_attrs_count++;
621 		break;
622 	default:
623 		break;
624 	}
625 
626 	/*
627 	 * Handle multi stage update step for mechas needing hash
628 	 * calculation
629 	 */
630 	if (step == PKCS11_FUNC_STEP_UPDATE) {
631 		switch (proc->mecha_type) {
632 		case PKCS11_CKM_ECDSA_SHA1:
633 		case PKCS11_CKM_ECDSA_SHA224:
634 		case PKCS11_CKM_ECDSA_SHA256:
635 		case PKCS11_CKM_ECDSA_SHA384:
636 		case PKCS11_CKM_ECDSA_SHA512:
637 		case PKCS11_CKM_MD5_RSA_PKCS:
638 		case PKCS11_CKM_SHA1_RSA_PKCS:
639 		case PKCS11_CKM_SHA224_RSA_PKCS:
640 		case PKCS11_CKM_SHA256_RSA_PKCS:
641 		case PKCS11_CKM_SHA384_RSA_PKCS:
642 		case PKCS11_CKM_SHA512_RSA_PKCS:
643 		case PKCS11_CKM_SHA1_RSA_PKCS_PSS:
644 		case PKCS11_CKM_SHA224_RSA_PKCS_PSS:
645 		case PKCS11_CKM_SHA256_RSA_PKCS_PSS:
646 		case PKCS11_CKM_SHA384_RSA_PKCS_PSS:
647 		case PKCS11_CKM_SHA512_RSA_PKCS_PSS:
648 			assert(proc->tee_op_handle2 != TEE_HANDLE_NULL);
649 
650 			TEE_DigestUpdate(proc->tee_op_handle2, in_buf, in_size);
651 			rc = PKCS11_CKR_OK;
652 			break;
653 		default:
654 			/*
655 			 * Other mechanism do not expect multi stage
656 			 * operation
657 			 */
658 			rc = PKCS11_CKR_GENERAL_ERROR;
659 			break;
660 		}
661 
662 		goto out;
663 	}
664 
665 	/*
666 	 * Handle multi stage one shot and final steps for mechas needing hash
667 	 * calculation
668 	 */
669 	switch (proc->mecha_type) {
670 	case PKCS11_CKM_ECDSA_SHA1:
671 	case PKCS11_CKM_ECDSA_SHA224:
672 	case PKCS11_CKM_ECDSA_SHA256:
673 	case PKCS11_CKM_ECDSA_SHA384:
674 	case PKCS11_CKM_ECDSA_SHA512:
675 	case PKCS11_CKM_MD5_RSA_PKCS:
676 	case PKCS11_CKM_SHA1_RSA_PKCS:
677 	case PKCS11_CKM_SHA224_RSA_PKCS:
678 	case PKCS11_CKM_SHA256_RSA_PKCS:
679 	case PKCS11_CKM_SHA384_RSA_PKCS:
680 	case PKCS11_CKM_SHA512_RSA_PKCS:
681 	case PKCS11_CKM_SHA1_RSA_PKCS_PSS:
682 	case PKCS11_CKM_SHA224_RSA_PKCS_PSS:
683 	case PKCS11_CKM_SHA256_RSA_PKCS_PSS:
684 	case PKCS11_CKM_SHA384_RSA_PKCS_PSS:
685 	case PKCS11_CKM_SHA512_RSA_PKCS_PSS:
686 		assert(proc->tee_op_handle2 != TEE_HANDLE_NULL);
687 
688 		hash_size = TEE_ALG_GET_DIGEST_SIZE(proc->tee_hash_algo);
689 		hash_buf = TEE_Malloc(hash_size, 0);
690 		if (!hash_buf)
691 			return PKCS11_CKR_DEVICE_MEMORY;
692 
693 		res = TEE_DigestDoFinal(proc->tee_op_handle2, in_buf, in_size,
694 					hash_buf, &hash_size);
695 
696 		rc = tee2pkcs_error(res);
697 		if (rc != PKCS11_CKR_OK)
698 			goto out;
699 
700 		break;
701 	default:
702 		break;
703 	}
704 
705 	/*
706 	 * Finalize either provided hash or calculated hash with signing
707 	 * operation
708 	 */
709 
710 	/* First determine amount of bytes for signing operation */
711 	switch (proc->mecha_type) {
712 	case PKCS11_CKM_ECDSA:
713 		sz = ecdsa_get_input_max_byte_size(proc->tee_op_handle);
714 		if (!in_size || !sz) {
715 			rc = PKCS11_CKR_FUNCTION_FAILED;
716 			goto out;
717 		}
718 
719 		/*
720 		 * Note 3) Input the entire raw digest. Internally, this will
721 		 * be truncated to the appropriate number of bits.
722 		 */
723 		if (in_size > sz)
724 			in_size = sz;
725 
726 		if (function == PKCS11_FUNCTION_VERIFY && in2_size != 2 * sz) {
727 			rc = PKCS11_CKR_SIGNATURE_LEN_RANGE;
728 			goto out;
729 		}
730 		break;
731 	case PKCS11_CKM_ECDSA_SHA1:
732 	case PKCS11_CKM_ECDSA_SHA224:
733 	case PKCS11_CKM_ECDSA_SHA256:
734 	case PKCS11_CKM_ECDSA_SHA384:
735 	case PKCS11_CKM_ECDSA_SHA512:
736 		/* Get key size in bytes */
737 		sz = ecdsa_get_input_max_byte_size(proc->tee_op_handle);
738 		if (!sz) {
739 			rc = PKCS11_CKR_FUNCTION_FAILED;
740 			goto out;
741 		}
742 
743 		if (function == PKCS11_FUNCTION_VERIFY &&
744 		    in2_size != 2 * sz) {
745 			rc = PKCS11_CKR_SIGNATURE_LEN_RANGE;
746 			goto out;
747 		}
748 		break;
749 	case PKCS11_CKM_RSA_PKCS:
750 	case PKCS11_CKM_RSA_X_509:
751 	case PKCS11_CKM_MD5_RSA_PKCS:
752 	case PKCS11_CKM_SHA1_RSA_PKCS:
753 	case PKCS11_CKM_SHA224_RSA_PKCS:
754 	case PKCS11_CKM_SHA256_RSA_PKCS:
755 	case PKCS11_CKM_SHA384_RSA_PKCS:
756 	case PKCS11_CKM_SHA512_RSA_PKCS:
757 	case PKCS11_CKM_RSA_PKCS_PSS:
758 	case PKCS11_CKM_SHA1_RSA_PKCS_PSS:
759 	case PKCS11_CKM_SHA224_RSA_PKCS_PSS:
760 	case PKCS11_CKM_SHA256_RSA_PKCS_PSS:
761 	case PKCS11_CKM_SHA384_RSA_PKCS_PSS:
762 	case PKCS11_CKM_SHA512_RSA_PKCS_PSS:
763 		/* Get key size in bytes */
764 		sz = rsa_get_input_max_byte_size(proc->tee_op_handle);
765 		if (!sz) {
766 			rc = PKCS11_CKR_FUNCTION_FAILED;
767 			goto out;
768 		}
769 
770 		if (function == PKCS11_FUNCTION_VERIFY && in2_size != sz) {
771 			rc = PKCS11_CKR_SIGNATURE_LEN_RANGE;
772 			goto out;
773 		}
774 		break;
775 	default:
776 		break;
777 	}
778 
779 	/* Next perform actual signing operation */
780 	switch (proc->mecha_type) {
781 	case PKCS11_CKM_ECDSA:
782 	case PKCS11_CKM_EDDSA:
783 	case PKCS11_CKM_RSA_PKCS:
784 	case PKCS11_CKM_RSA_PKCS_OAEP:
785 	case PKCS11_CKM_RSA_PKCS_PSS:
786 		/* For operations using provided input data */
787 		switch (function) {
788 		case PKCS11_FUNCTION_ENCRYPT:
789 			res = TEE_AsymmetricEncrypt(proc->tee_op_handle,
790 						    tee_attrs, tee_attrs_count,
791 						    in_buf, in_size,
792 						    out_buf, &out_size);
793 			output_data = true;
794 			rc = tee2pkcs_error(res);
795 			if (rc == PKCS11_CKR_ARGUMENTS_BAD)
796 				rc = PKCS11_CKR_DATA_LEN_RANGE;
797 			break;
798 
799 		case PKCS11_FUNCTION_DECRYPT:
800 			res = TEE_AsymmetricDecrypt(proc->tee_op_handle,
801 						    tee_attrs, tee_attrs_count,
802 						    in_buf, in_size,
803 						    out_buf, &out_size);
804 			output_data = true;
805 			rc = tee2pkcs_error(res);
806 			if (rc == PKCS11_CKR_ARGUMENTS_BAD)
807 				rc = PKCS11_CKR_ENCRYPTED_DATA_LEN_RANGE;
808 			break;
809 
810 		case PKCS11_FUNCTION_SIGN:
811 			res = TEE_AsymmetricSignDigest(proc->tee_op_handle,
812 						       tee_attrs,
813 						       tee_attrs_count,
814 						       in_buf, in_size,
815 						       out_buf, &out_size);
816 			output_data = true;
817 			rc = tee2pkcs_error(res);
818 			break;
819 
820 		case PKCS11_FUNCTION_VERIFY:
821 			res = TEE_AsymmetricVerifyDigest(proc->tee_op_handle,
822 							 tee_attrs,
823 							 tee_attrs_count,
824 							 in_buf, in_size,
825 							 in2_buf, in2_size);
826 			rc = tee2pkcs_error(res);
827 			break;
828 
829 		default:
830 			TEE_Panic(function);
831 			break;
832 		}
833 		break;
834 
835 	case PKCS11_CKM_RSA_X_509:
836 		switch (function) {
837 		case PKCS11_FUNCTION_ENCRYPT:
838 			/*
839 			 * Input message size shall be at most the key size
840 			 * As encrypting with raw RSA can be unsafe, it
841 			 * remains the responsibility of the client to
842 			 * prolerly pad the message for safe usage.
843 			 */
844 			if (in_size > sz) {
845 				rc = PKCS11_CKR_DATA_LEN_RANGE;
846 				break;
847 			}
848 			res = TEE_AsymmetricEncrypt(proc->tee_op_handle,
849 						    tee_attrs, tee_attrs_count,
850 						    in_buf, in_size,
851 						    out_buf, &out_size);
852 			output_data = true;
853 			rc = tee2pkcs_error(res);
854 			if (rc == PKCS11_CKR_ARGUMENTS_BAD)
855 				rc = PKCS11_CKR_DATA_LEN_RANGE;
856 			break;
857 		case PKCS11_FUNCTION_DECRYPT:
858 			/*
859 			 * Input message size shall be at most the key size
860 			 * As decrypting with raw RSA can be unsafe, it
861 			 * remains the responsibility of the encryption
862 			 * instance to have prolerly padded its message.
863 			 */
864 			if (in_size > sz) {
865 				rc = PKCS11_CKR_ENCRYPTED_DATA_LEN_RANGE;
866 				break;
867 			}
868 
869 			res = TEE_AsymmetricDecrypt(proc->tee_op_handle,
870 						    tee_attrs, tee_attrs_count,
871 						    in_buf, in_size,
872 						    out_buf, &out_size);
873 			output_data = true;
874 			rc = tee2pkcs_error(res);
875 			if (rc == PKCS11_CKR_ARGUMENTS_BAD)
876 				rc = PKCS11_CKR_ENCRYPTED_DATA_LEN_RANGE;
877 			break;
878 		case PKCS11_FUNCTION_SIGN:
879 			/*
880 			 * GP TEE API only allows Decrypt, not Verify operation,
881 			 * on TEE_ALG_RSA_NOPAD. Be a bit strict on the size and
882 			 * content of the message and ensure the generate
883 			 * signature as the size of the modulus (@sz here).
884 			 *
885 			 * It remains the responsibility of the client to have
886 			 * a safe padding scheme for the provided message data.
887 			 */
888 			if (in_size != sz) {
889 				EMSG("Invalid data size %"PRIu32" != %zu",
890 				     in_size, sz);
891 				rc = PKCS11_CKR_DATA_LEN_RANGE;
892 				break;
893 			}
894 
895 			if (out_size < sz) {
896 				rc = PKCS11_CKR_BUFFER_TOO_SMALL;
897 				out_size = sz;
898 				output_data = true;
899 				break;
900 			}
901 
902 			temp_size = sz;
903 			temp_buf = proc->extra_ctx;
904 			res = TEE_AsymmetricDecrypt(proc->tee_op_handle,
905 						    tee_attrs, tee_attrs_count,
906 						    in_buf, in_size,
907 						    temp_buf, &temp_size);
908 			if (!res && temp_size != sz) {
909 				EMSG("CMK_RSA_X509: signature size %zu != %zu",
910 				     temp_size, sz);
911 				rc = PKCS11_CKR_DATA_INVALID;
912 				break;
913 			}
914 			if (!res) {
915 				TEE_MemMove(out_buf, temp_buf, sz);
916 				TEE_MemFill(temp_buf, 0xa5, sz);
917 			}
918 			output_data = true;
919 			rc = tee2pkcs_error(res);
920 			out_size = sz;
921 			break;
922 		case PKCS11_FUNCTION_VERIFY:
923 			/*
924 			 * GP TEE API only allows Encrypt, not Verify operation,
925 			 * on TEE_ALG_RSA_NOPAD. Encrypt signature in
926 			 * temporary buffer preallocated to the size of the key.
927 			 */
928 			temp_size = sz;
929 			temp_buf = proc->extra_ctx;
930 			res = TEE_AsymmetricEncrypt(proc->tee_op_handle,
931 						    tee_attrs, tee_attrs_count,
932 						    in2_buf, in2_size,
933 						    temp_buf, &temp_size);
934 			rc = tee2pkcs_error(res);
935 			if (rc == PKCS11_CKR_OK) {
936 				/*
937 				 * Skip nul bytes heading message before
938 				 * comparing encrypted signature.
939 				 */
940 				char *ptr = in_buf;
941 				size_t n = 0;
942 
943 				for (n = 0; n < in_size; n++)
944 					if (ptr[n])
945 						break;
946 				in_size -= n;
947 				ptr += n;
948 				if (n > 1)
949 					IMSG("Unsafe signature: skip %zu bytes",
950 					     n);
951 
952 				if (temp_size != in_size ||
953 				    consttime_memcmp(temp_buf, ptr, in_size))
954 					rc = PKCS11_CKR_SIGNATURE_INVALID;
955 			}
956 			break;
957 		default:
958 			TEE_Panic(function);
959 			break;
960 		}
961 		break;
962 
963 	case PKCS11_CKM_ECDSA_SHA1:
964 	case PKCS11_CKM_ECDSA_SHA224:
965 	case PKCS11_CKM_ECDSA_SHA256:
966 	case PKCS11_CKM_ECDSA_SHA384:
967 	case PKCS11_CKM_ECDSA_SHA512:
968 	case PKCS11_CKM_MD5_RSA_PKCS:
969 	case PKCS11_CKM_SHA1_RSA_PKCS:
970 	case PKCS11_CKM_SHA224_RSA_PKCS:
971 	case PKCS11_CKM_SHA256_RSA_PKCS:
972 	case PKCS11_CKM_SHA384_RSA_PKCS:
973 	case PKCS11_CKM_SHA512_RSA_PKCS:
974 	case PKCS11_CKM_SHA1_RSA_PKCS_PSS:
975 	case PKCS11_CKM_SHA224_RSA_PKCS_PSS:
976 	case PKCS11_CKM_SHA256_RSA_PKCS_PSS:
977 	case PKCS11_CKM_SHA384_RSA_PKCS_PSS:
978 	case PKCS11_CKM_SHA512_RSA_PKCS_PSS:
979 		/* For operations having hash operation use calculated hash */
980 		switch (function) {
981 		case PKCS11_FUNCTION_SIGN:
982 			res = TEE_AsymmetricSignDigest(proc->tee_op_handle,
983 						       tee_attrs,
984 						       tee_attrs_count,
985 						       hash_buf, hash_size,
986 						       out_buf, &out_size);
987 			output_data = true;
988 			rc = tee2pkcs_error(res);
989 			break;
990 
991 		case PKCS11_FUNCTION_VERIFY:
992 			res = TEE_AsymmetricVerifyDigest(proc->tee_op_handle,
993 							 tee_attrs,
994 							 tee_attrs_count,
995 							 hash_buf, hash_size,
996 							 in2_buf, in2_size);
997 			rc = tee2pkcs_error(res);
998 			break;
999 
1000 		default:
1001 			TEE_Panic(function);
1002 			break;
1003 		}
1004 		break;
1005 	default:
1006 		TEE_Panic(proc->mecha_type);
1007 		break;
1008 	}
1009 
1010 out:
1011 	if (output_data &&
1012 	    (rc == PKCS11_CKR_OK || rc == PKCS11_CKR_BUFFER_TOO_SMALL)) {
1013 		switch (TEE_PARAM_TYPE_GET(ptypes, 2)) {
1014 		case TEE_PARAM_TYPE_MEMREF_OUTPUT:
1015 		case TEE_PARAM_TYPE_MEMREF_INOUT:
1016 			params[2].memref.size = out_size;
1017 			break;
1018 		default:
1019 			rc = PKCS11_CKR_GENERAL_ERROR;
1020 			break;
1021 		}
1022 	}
1023 
1024 	TEE_Free(hash_buf);
1025 	TEE_Free(tee_attrs);
1026 
1027 	return rc;
1028 }
1029 
1030 enum pkcs11_rc do_asymm_derivation(struct pkcs11_session *session,
1031 				   struct pkcs11_attribute_head *proc_params,
1032 				   struct obj_attrs **head)
1033 {
1034 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
1035 	TEE_ObjectHandle out_handle = TEE_HANDLE_NULL;
1036 	TEE_Result res = TEE_ERROR_GENERIC;
1037 	TEE_Attribute tee_attrs[2] = { };
1038 	size_t tee_attrs_count = 0;
1039 	uint32_t key_byte_size = 0;
1040 	uint32_t key_bit_size = 0;
1041 	void *a_ptr = NULL;
1042 	size_t a_size = 0;
1043 
1044 	/* Remove default attribute set at template sanitization */
1045 	if (remove_empty_attribute(head, PKCS11_CKA_VALUE))
1046 		return PKCS11_CKR_FUNCTION_FAILED;
1047 
1048 	rc = get_u32_attribute(*head, PKCS11_CKA_VALUE_LEN, &key_bit_size);
1049 	if (rc)
1050 		return rc;
1051 
1052 	key_bit_size *= 8;
1053 	key_byte_size = (key_bit_size + 7) / 8;
1054 
1055 	res = TEE_AllocateTransientObject(TEE_TYPE_GENERIC_SECRET,
1056 					  key_byte_size * 8, &out_handle);
1057 	if (res) {
1058 		DMSG("TEE_AllocateTransientObject failed, %#"PRIx32, res);
1059 		return tee2pkcs_error(res);
1060 	}
1061 
1062 	switch (proc_params->id) {
1063 	case PKCS11_CKM_ECDH1_DERIVE:
1064 		rc = pkcs2tee_param_ecdh(proc_params, &a_ptr, &a_size);
1065 		if (rc)
1066 			goto out;
1067 
1068 		TEE_InitRefAttribute(&tee_attrs[tee_attrs_count],
1069 				     TEE_ATTR_ECC_PUBLIC_VALUE_X,
1070 				     a_ptr, a_size / 2);
1071 		tee_attrs_count++;
1072 		TEE_InitRefAttribute(&tee_attrs[tee_attrs_count],
1073 				     TEE_ATTR_ECC_PUBLIC_VALUE_Y,
1074 				     (char *)a_ptr + a_size / 2,
1075 				     a_size / 2);
1076 		tee_attrs_count++;
1077 		break;
1078 	default:
1079 		TEE_Panic(proc_params->id);
1080 		break;
1081 	}
1082 
1083 	TEE_DeriveKey(session->processing->tee_op_handle, &tee_attrs[0],
1084 		      tee_attrs_count, out_handle);
1085 
1086 	rc = alloc_get_tee_attribute_data(out_handle, TEE_ATTR_SECRET_VALUE,
1087 					  &a_ptr, &a_size);
1088 	if (rc)
1089 		goto out;
1090 
1091 	if (a_size * 8 < key_bit_size)
1092 		rc = PKCS11_CKR_KEY_SIZE_RANGE;
1093 	else
1094 		rc = add_attribute(head, PKCS11_CKA_VALUE, a_ptr,
1095 				   key_byte_size);
1096 	TEE_Free(a_ptr);
1097 out:
1098 	release_active_processing(session);
1099 	TEE_FreeTransientObject(out_handle);
1100 
1101 	return rc;
1102 }
1103 
1104 static enum pkcs11_rc wrap_rsa_aes_key(struct active_processing *proc,
1105 				       void *data, uint32_t data_sz,
1106 				       void *out_buf, uint32_t *out_sz)
1107 {
1108 	enum pkcs11_rc rc = PKCS11_CKR_OK;
1109 	TEE_Result res = TEE_ERROR_GENERIC;
1110 	int mbedtls_rc = 0;
1111 	struct rsa_aes_key_wrap_processing_ctx *ctx = proc->extra_ctx;
1112 	mbedtls_nist_kw_context kw_ctx = { };
1113 	uint8_t aes_key_value[32] = { };
1114 	uint32_t aes_key_size = ctx->aes_key_bits / 8;
1115 	size_t aes_wrapped_size = *out_sz;
1116 	uint32_t expected_size = 0;
1117 	size_t target_key_size = 0;
1118 	const size_t kw_semiblock_len = 8;
1119 
1120 	if (ctx->aes_key_bits != 128 &&
1121 	    ctx->aes_key_bits != 192 &&
1122 	    ctx->aes_key_bits != 256)
1123 		return PKCS11_CKR_ARGUMENTS_BAD;
1124 
1125 	mbedtls_nist_kw_init(&kw_ctx);
1126 	TEE_GenerateRandom(aes_key_value, aes_key_size);
1127 	res = TEE_AsymmetricEncrypt(proc->tee_op_handle,
1128 				    NULL, 0,
1129 				    aes_key_value, aes_key_size,
1130 				    out_buf, &aes_wrapped_size);
1131 	expected_size = aes_wrapped_size + data_sz + kw_semiblock_len;
1132 	if (res) {
1133 		if (res == TEE_ERROR_SHORT_BUFFER)
1134 			*out_sz = expected_size;
1135 
1136 		rc = tee2pkcs_error(res);
1137 		goto out;
1138 	}
1139 
1140 	if (*out_sz < expected_size) {
1141 		rc = PKCS11_CKR_BUFFER_TOO_SMALL;
1142 		*out_sz = expected_size;
1143 		goto out;
1144 	}
1145 
1146 	mbedtls_rc = mbedtls_nist_kw_setkey(&kw_ctx, MBEDTLS_CIPHER_ID_AES,
1147 					    aes_key_value, ctx->aes_key_bits,
1148 					    true);
1149 	if (mbedtls_rc) {
1150 		if (mbedtls_rc == MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA)
1151 			rc = PKCS11_CKR_KEY_SIZE_RANGE;
1152 		else
1153 			rc = PKCS11_CKR_FUNCTION_FAILED;
1154 
1155 		goto out;
1156 	}
1157 
1158 	mbedtls_rc = mbedtls_nist_kw_wrap(&kw_ctx, MBEDTLS_KW_MODE_KWP,
1159 					  data, data_sz,
1160 					  (uint8_t *)out_buf + aes_wrapped_size,
1161 					  &target_key_size,
1162 					  *out_sz - aes_wrapped_size);
1163 	if (mbedtls_rc) {
1164 		rc = PKCS11_CKR_ARGUMENTS_BAD;
1165 		goto out;
1166 	}
1167 
1168 	assert(*out_sz >= target_key_size + aes_wrapped_size);
1169 	*out_sz = target_key_size + aes_wrapped_size;
1170 
1171 out:
1172 	mbedtls_nist_kw_free(&kw_ctx);
1173 	TEE_MemFill(aes_key_value, 0, aes_key_size);
1174 	return rc;
1175 }
1176 
1177 static enum pkcs11_rc unwrap_rsa_aes_key(struct active_processing *proc,
1178 					 void *data, uint32_t data_sz,
1179 					 void **out_buf, uint32_t *out_sz)
1180 {
1181 	enum pkcs11_rc rc = PKCS11_CKR_OK;
1182 	int mbedtls_rc = 0;
1183 	TEE_Result res = TEE_ERROR_GENERIC;
1184 	TEE_OperationInfo info = { };
1185 	struct rsa_aes_key_wrap_processing_ctx *ctx = proc->extra_ctx;
1186 	mbedtls_nist_kw_context kw_ctx = { };
1187 	uint8_t aes_key_value[32] = { };
1188 	size_t aes_key_size = ctx->aes_key_bits / 8;
1189 	uint32_t wrapped_key_size = 0;
1190 	uint32_t rsa_key_size = 0;
1191 	size_t target_key_size = 0;
1192 
1193 	if (ctx->aes_key_bits != 128 &&
1194 	    ctx->aes_key_bits != 192 &&
1195 	    ctx->aes_key_bits != 256)
1196 		return PKCS11_CKR_ARGUMENTS_BAD;
1197 
1198 	TEE_GetOperationInfo(proc->tee_op_handle, &info);
1199 	rsa_key_size = info.keySize / 8;
1200 	wrapped_key_size = data_sz - rsa_key_size;
1201 	target_key_size = wrapped_key_size - 8;
1202 
1203 	*out_buf = TEE_Malloc(target_key_size, TEE_MALLOC_FILL_ZERO);
1204 	if (!*out_buf)
1205 		return PKCS11_CKR_DEVICE_MEMORY;
1206 
1207 	mbedtls_nist_kw_init(&kw_ctx);
1208 	res = TEE_AsymmetricDecrypt(proc->tee_op_handle,
1209 				    NULL, 0,
1210 				    data, rsa_key_size,
1211 				    aes_key_value, &aes_key_size);
1212 	if (res) {
1213 		rc = tee2pkcs_error(res);
1214 		goto out;
1215 	}
1216 
1217 	mbedtls_rc = mbedtls_nist_kw_setkey(&kw_ctx, MBEDTLS_CIPHER_ID_AES,
1218 					    aes_key_value, ctx->aes_key_bits,
1219 					    false);
1220 	if (mbedtls_rc) {
1221 		rc = PKCS11_CKR_WRAPPED_KEY_INVALID;
1222 		goto out;
1223 	}
1224 
1225 	mbedtls_rc = mbedtls_nist_kw_unwrap(&kw_ctx, MBEDTLS_KW_MODE_KWP,
1226 					    (uint8_t *)data + rsa_key_size,
1227 					    wrapped_key_size, *out_buf,
1228 					    &target_key_size, target_key_size);
1229 	if (mbedtls_rc) {
1230 		rc = PKCS11_CKR_WRAPPED_KEY_INVALID;
1231 		goto out;
1232 	}
1233 
1234 	*out_sz = target_key_size;
1235 out:
1236 	TEE_MemFill(aes_key_value, 0, aes_key_size);
1237 	mbedtls_nist_kw_free(&kw_ctx);
1238 	return rc;
1239 }
1240 
1241 enum pkcs11_rc wrap_data_by_asymm_enc(struct pkcs11_session *session,
1242 				      void *data, uint32_t data_sz,
1243 				      void *out_buf, uint32_t *out_sz)
1244 {
1245 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
1246 	struct active_processing *proc = session->processing;
1247 
1248 	switch (proc->mecha_type) {
1249 	case PKCS11_CKM_RSA_AES_KEY_WRAP:
1250 		rc = wrap_rsa_aes_key(proc, data, data_sz, out_buf, out_sz);
1251 		break;
1252 	default:
1253 		return PKCS11_CKR_MECHANISM_INVALID;
1254 	}
1255 
1256 	return rc;
1257 }
1258 
1259 enum pkcs11_rc unwrap_key_by_asymm(struct pkcs11_session *session,
1260 				   void *data, uint32_t data_sz,
1261 				   void **out_buf, uint32_t *out_sz)
1262 {
1263 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
1264 	struct active_processing *proc = session->processing;
1265 
1266 	switch (proc->mecha_type) {
1267 	case PKCS11_CKM_RSA_AES_KEY_WRAP:
1268 		rc = unwrap_rsa_aes_key(proc, data, data_sz, out_buf, out_sz);
1269 		break;
1270 	default:
1271 		return PKCS11_CKR_MECHANISM_INVALID;
1272 	}
1273 
1274 	return rc;
1275 }
1276