xref: /optee_os/ta/pkcs11/src/pkcs11_attributes.c (revision 4edd96e6d7a7228e907cf498b23e5b5fbdaf39a0)
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2017-2020, Linaro Limited
4  */
5 
6 #include <assert.h>
7 #include <inttypes.h>
8 #include <mbedtls/pk.h>
9 #include <pkcs11_ta.h>
10 #include <stdlib.h>
11 #include <string_ext.h>
12 #include <tee_internal_api_extensions.h>
13 #include <tee_internal_api.h>
14 #include <trace.h>
15 #include <util.h>
16 
17 #include "attributes.h"
18 #include "handle.h"
19 #include "pkcs11_attributes.h"
20 #include "pkcs11_helpers.h"
21 #include "pkcs11_token.h"
22 #include "sanitize_object.h"
23 #include "serializer.h"
24 #include "token_capabilities.h"
25 
26 static uint32_t pkcs11_func2ckfm(enum processing_func function)
27 {
28 	switch (function) {
29 	case PKCS11_FUNCTION_DIGEST:
30 		return PKCS11_CKFM_DIGEST;
31 	case PKCS11_FUNCTION_GENERATE:
32 		return PKCS11_CKFM_GENERATE;
33 	case PKCS11_FUNCTION_GENERATE_PAIR:
34 		return PKCS11_CKFM_GENERATE_KEY_PAIR;
35 	case PKCS11_FUNCTION_DERIVE:
36 		return PKCS11_CKFM_DERIVE;
37 	case PKCS11_FUNCTION_WRAP:
38 		return PKCS11_CKFM_WRAP;
39 	case PKCS11_FUNCTION_UNWRAP:
40 		return PKCS11_CKFM_UNWRAP;
41 	case PKCS11_FUNCTION_ENCRYPT:
42 		return PKCS11_CKFM_ENCRYPT;
43 	case PKCS11_FUNCTION_DECRYPT:
44 		return PKCS11_CKFM_DECRYPT;
45 	case PKCS11_FUNCTION_SIGN:
46 		return PKCS11_CKFM_SIGN;
47 	case PKCS11_FUNCTION_VERIFY:
48 		return PKCS11_CKFM_VERIFY;
49 	case PKCS11_FUNCTION_SIGN_RECOVER:
50 		return PKCS11_CKFM_SIGN_RECOVER;
51 	case PKCS11_FUNCTION_VERIFY_RECOVER:
52 		return PKCS11_CKFM_VERIFY_RECOVER;
53 	default:
54 		return 0;
55 	}
56 }
57 
58 enum pkcs11_rc
59 check_mechanism_against_processing(struct pkcs11_session *session,
60 				   enum pkcs11_mechanism_id mechanism_type,
61 				   enum processing_func function,
62 				   enum processing_step step)
63 {
64 	bool allowed = false;
65 
66 	switch (step) {
67 	case PKCS11_FUNC_STEP_INIT:
68 		switch (function) {
69 		case PKCS11_FUNCTION_IMPORT:
70 		case PKCS11_FUNCTION_COPY:
71 		case PKCS11_FUNCTION_MODIFY:
72 		case PKCS11_FUNCTION_DESTROY:
73 			return PKCS11_CKR_OK;
74 		default:
75 			break;
76 		}
77 		/*
78 		 * Check that the returned PKCS11_CKFM_* flag from
79 		 * pkcs11_func2ckfm() is among the ones from
80 		 * mechanism_supported_flags().
81 		 */
82 		allowed = mechanism_supported_flags(mechanism_type) &
83 			  pkcs11_func2ckfm(function);
84 		break;
85 
86 	case PKCS11_FUNC_STEP_ONESHOT:
87 		if (session->processing->always_authen &&
88 		    !session->processing->relogged)
89 			return PKCS11_CKR_USER_NOT_LOGGED_IN;
90 
91 		if (session->processing->step == PKCS11_FUNC_STEP_UPDATE ||
92 		    session->processing->step == PKCS11_FUNC_STEP_FINAL) {
93 			EMSG("Cannot perform one-shot on active processing");
94 			return PKCS11_CKR_OPERATION_ACTIVE;
95 		}
96 
97 		allowed = true;
98 		break;
99 
100 	case PKCS11_FUNC_STEP_UPDATE:
101 		if (session->processing->always_authen &&
102 		    !session->processing->relogged)
103 			return PKCS11_CKR_USER_NOT_LOGGED_IN;
104 
105 		if (session->processing->step == PKCS11_FUNC_STEP_ONESHOT ||
106 		    session->processing->step == PKCS11_FUNC_STEP_FINAL) {
107 			EMSG("Cannot perform update on finalized processing");
108 			return PKCS11_CKR_OPERATION_ACTIVE;
109 		}
110 
111 		allowed = !mechanism_is_one_shot_only(mechanism_type);
112 		break;
113 
114 	case PKCS11_FUNC_STEP_UPDATE_KEY:
115 		assert(function == PKCS11_FUNCTION_DIGEST);
116 
117 		if (session->processing->always_authen &&
118 		    !session->processing->relogged)
119 			return PKCS11_CKR_USER_NOT_LOGGED_IN;
120 
121 		allowed = true;
122 		break;
123 
124 	case PKCS11_FUNC_STEP_FINAL:
125 		if (session->processing->always_authen &&
126 		    !session->processing->relogged)
127 			return PKCS11_CKR_USER_NOT_LOGGED_IN;
128 
129 		if (session->processing->step == PKCS11_FUNC_STEP_ONESHOT) {
130 			EMSG("Cannot perform final on oneshot processing");
131 			return PKCS11_CKR_OPERATION_ACTIVE;
132 		}
133 		return PKCS11_CKR_OK;
134 
135 	default:
136 		TEE_Panic(step);
137 		break;
138 	}
139 
140 	if (!allowed) {
141 		EMSG("Processing %#x/%s not permitted (%u/%u)",
142 		     (unsigned int)mechanism_type, id2str_proc(mechanism_type),
143 		     function, step);
144 		return PKCS11_CKR_MECHANISM_INVALID;
145 	}
146 
147 	return PKCS11_CKR_OK;
148 }
149 
150 /*
151  * Object default boolean attributes as per PKCS#11
152  */
153 static uint8_t *pkcs11_object_default_boolprop(uint32_t attribute)
154 {
155 	static const uint8_t bool_true = 1;
156 	static const uint8_t bool_false;
157 
158 	switch (attribute) {
159 	/* As per PKCS#11 default value */
160 	case PKCS11_CKA_MODIFIABLE:
161 	case PKCS11_CKA_COPYABLE:
162 	case PKCS11_CKA_DESTROYABLE:
163 		return (uint8_t *)&bool_true;
164 	case PKCS11_CKA_TOKEN:
165 	case PKCS11_CKA_PRIVATE:
166 	case PKCS11_CKA_WRAP_WITH_TRUSTED:
167 	case PKCS11_CKA_ALWAYS_AUTHENTICATE:
168 	case PKCS11_CKA_SENSITIVE:
169 		return (uint8_t *)&bool_false;
170 	/* Token specific default value */
171 	case PKCS11_CKA_SIGN:
172 	case PKCS11_CKA_VERIFY:
173 	case PKCS11_CKA_DERIVE:
174 	case PKCS11_CKA_ENCRYPT:
175 	case PKCS11_CKA_DECRYPT:
176 	case PKCS11_CKA_SIGN_RECOVER:
177 	case PKCS11_CKA_VERIFY_RECOVER:
178 	case PKCS11_CKA_WRAP:
179 	case PKCS11_CKA_UNWRAP:
180 	case PKCS11_CKA_EXTRACTABLE:
181 	case PKCS11_CKA_TRUSTED:
182 		return (uint8_t *)&bool_false;
183 	default:
184 		DMSG("No default for boolprop attribute %#"PRIx32, attribute);
185 		return NULL;
186 	}
187 }
188 
189 /*
190  * Object expects several boolean attributes to be set to a default value
191  * or to a validate client configuration value. This function append the input
192  * attribute (id/size/value) in the serialized object.
193  */
194 static enum pkcs11_rc pkcs11_import_object_boolprop(struct obj_attrs **out,
195 						    struct obj_attrs *templ,
196 						    uint32_t attribute)
197 {
198 	enum pkcs11_rc rc = PKCS11_CKR_OK;
199 	uint8_t bbool = 0;
200 	uint32_t size = sizeof(uint8_t);
201 	void *attr = NULL;
202 
203 	rc = get_attribute(templ, attribute, &bbool, &size);
204 	if (rc) {
205 		if (rc != PKCS11_RV_NOT_FOUND)
206 			return rc;
207 		attr = pkcs11_object_default_boolprop(attribute);
208 		if (!attr)
209 			return PKCS11_CKR_TEMPLATE_INCOMPLETE;
210 	} else {
211 		attr = &bbool;
212 	}
213 
214 	/* Boolean attributes are 1byte in the ABI, no alignment issue */
215 	return add_attribute(out, attribute, attr, sizeof(uint8_t));
216 }
217 
218 static enum pkcs11_rc set_mandatory_boolprops(struct obj_attrs **out,
219 					      struct obj_attrs *temp,
220 					      uint32_t const *bp,
221 					      size_t bp_count)
222 {
223 	enum pkcs11_rc rc = PKCS11_CKR_OK;
224 	size_t n = 0;
225 
226 	for (n = 0; n < bp_count; n++) {
227 		rc = pkcs11_import_object_boolprop(out, temp, bp[n]);
228 		if (rc)
229 			return rc;
230 	}
231 
232 	return rc;
233 }
234 
235 static enum pkcs11_rc set_mandatory_attributes(struct obj_attrs **out,
236 					       struct obj_attrs *temp,
237 					       uint32_t const *attrs,
238 					       size_t attrs_count)
239 {
240 	enum pkcs11_rc rc = PKCS11_CKR_OK;
241 	size_t n = 0;
242 
243 	for (n = 0; n < attrs_count; n++) {
244 		uint32_t size = 0;
245 		void *value = NULL;
246 
247 		if (get_attribute_ptr(temp, attrs[n], &value, &size))
248 			return PKCS11_CKR_TEMPLATE_INCOMPLETE;
249 
250 		rc = add_attribute(out, attrs[n], value, size);
251 		if (rc)
252 			return rc;
253 	}
254 
255 	return rc;
256 }
257 
258 static enum pkcs11_rc get_default_value(enum pkcs11_attr_id id, void **value,
259 					uint32_t *size)
260 {
261 	/* should have been taken care of already */
262 	assert(!pkcs11_attr_is_boolean(id));
263 
264 	/* All other attributes have an empty default value */
265 	*value = NULL;
266 	*size = 0;
267 	return PKCS11_CKR_OK;
268 }
269 
270 static enum pkcs11_rc set_optional_attributes_with_def(struct obj_attrs **out,
271 						       struct obj_attrs *temp,
272 						       uint32_t const *attrs,
273 						       size_t attrs_count,
274 						       bool default_to_null)
275 {
276 	enum pkcs11_rc rc = PKCS11_CKR_OK;
277 	size_t n = 0;
278 
279 	for (n = 0; n < attrs_count; n++) {
280 		uint32_t size = 0;
281 		void *value = NULL;
282 
283 		rc = get_attribute_ptr(temp, attrs[n], &value, &size);
284 		if (rc == PKCS11_RV_NOT_FOUND) {
285 			if (default_to_null) {
286 				rc = get_default_value(attrs[n], &value, &size);
287 			} else {
288 				rc = PKCS11_CKR_OK;
289 				continue;
290 			}
291 		}
292 		if (rc)
293 			return rc;
294 
295 		rc = add_attribute(out, attrs[n], value, size);
296 		if (rc)
297 			return rc;
298 	}
299 
300 	return rc;
301 }
302 
303 static enum pkcs11_rc set_attributes_opt_or_null(struct obj_attrs **out,
304 						 struct obj_attrs *temp,
305 						 uint32_t const *attrs,
306 						 size_t attrs_count)
307 {
308 	return set_optional_attributes_with_def(out, temp, attrs, attrs_count,
309 						true /* defaults to empty */);
310 }
311 
312 static enum pkcs11_rc set_optional_attributes(struct obj_attrs **out,
313 					      struct obj_attrs *temp,
314 					      uint32_t const *attrs,
315 					      size_t attrs_count)
316 {
317 	return set_optional_attributes_with_def(out, temp, attrs, attrs_count,
318 						false /* no default value */);
319 }
320 
321 /*
322  * Below are listed the mandated or optional expected attributes for
323  * PKCS#11 storage objects.
324  *
325  * Note: boolprops (mandated boolean attributes) PKCS11_CKA_ALWAYS_SENSITIVE,
326  * and PKCS11_CKA_NEVER_EXTRACTABLE are set by the token, not provided
327  * in the client template.
328  */
329 
330 /* PKCS#11 specification for any object (session/token) of the storage */
331 static const uint32_t any_object_boolprops[] = {
332 	PKCS11_CKA_TOKEN, PKCS11_CKA_PRIVATE,
333 	PKCS11_CKA_MODIFIABLE, PKCS11_CKA_COPYABLE, PKCS11_CKA_DESTROYABLE,
334 };
335 
336 static const uint32_t any_object_opt_or_null[] = {
337 	PKCS11_CKA_LABEL,
338 };
339 
340 /* PKCS#11 specification for raw data object (+any_object_xxx) */
341 const uint32_t raw_data_opt_or_null[] = {
342 	PKCS11_CKA_OBJECT_ID, PKCS11_CKA_APPLICATION, PKCS11_CKA_VALUE,
343 };
344 
345 /* PKCS#11 specification for certificate object (+pkcs11_any_object_xxx) */
346 static const uint32_t pkcs11_certificate_mandated[] = {
347 	PKCS11_CKA_CERTIFICATE_TYPE,
348 };
349 
350 static const uint32_t pkcs11_certificate_boolprops[] = {
351 	PKCS11_CKA_TRUSTED,
352 };
353 
354 static const uint32_t pkcs11_certificate_optional[] = {
355 	PKCS11_CKA_CERTIFICATE_CATEGORY, PKCS11_CKA_CHECK_VALUE,
356 	PKCS11_CKA_START_DATE, PKCS11_CKA_END_DATE, PKCS11_CKA_PUBLIC_KEY_INFO,
357 };
358 
359 /*
360  * PKCS#11 specification for X.509 certificate object (+pkcs11_certificate_xxx)
361  */
362 static const uint32_t pkcs11_x509_certificate_mandated[] = {
363 	PKCS11_CKA_SUBJECT,
364 };
365 
366 static const uint32_t pkcs11_x509_certificate_optional[] = {
367 	PKCS11_CKA_ID, PKCS11_CKA_ISSUER, PKCS11_CKA_SERIAL_NUMBER,
368 	PKCS11_CKA_VALUE, PKCS11_CKA_URL,
369 	PKCS11_CKA_HASH_OF_SUBJECT_PUBLIC_KEY,
370 	PKCS11_CKA_HASH_OF_ISSUER_PUBLIC_KEY,
371 	PKCS11_CKA_JAVA_MIDP_SECURITY_DOMAIN, PKCS11_CKA_NAME_HASH_ALGORITHM,
372 };
373 
374 /* PKCS#11 specification for any key object (+any_object_xxx) */
375 static const uint32_t any_key_boolprops[] = {
376 	PKCS11_CKA_DERIVE,
377 };
378 
379 static const uint32_t any_key_opt_or_null[] = {
380 	PKCS11_CKA_ID,
381 	PKCS11_CKA_START_DATE, PKCS11_CKA_END_DATE,
382 };
383 
384 static const uint32_t any_key_optional[] = {
385 	PKCS11_CKA_ALLOWED_MECHANISMS,
386 };
387 
388 /* PKCS#11 specification for any symmetric key (+any_key_xxx) */
389 static const uint32_t symm_key_boolprops[] = {
390 	PKCS11_CKA_ENCRYPT, PKCS11_CKA_DECRYPT,
391 	PKCS11_CKA_SIGN, PKCS11_CKA_VERIFY,
392 	PKCS11_CKA_WRAP, PKCS11_CKA_UNWRAP,
393 	PKCS11_CKA_SENSITIVE, PKCS11_CKA_EXTRACTABLE,
394 	PKCS11_CKA_WRAP_WITH_TRUSTED, PKCS11_CKA_TRUSTED,
395 };
396 
397 static const uint32_t symm_key_opt_or_null[] = {
398 	PKCS11_CKA_WRAP_TEMPLATE, PKCS11_CKA_UNWRAP_TEMPLATE,
399 	PKCS11_CKA_DERIVE_TEMPLATE, PKCS11_CKA_VALUE,
400 };
401 
402 static const uint32_t symm_key_optional[] = {
403 	PKCS11_CKA_VALUE_LEN,
404 };
405 
406 /* PKCS#11 specification for any asymmetric public key (+any_key_xxx) */
407 static const uint32_t public_key_boolprops[] = {
408 	PKCS11_CKA_ENCRYPT, PKCS11_CKA_VERIFY, PKCS11_CKA_VERIFY_RECOVER,
409 	PKCS11_CKA_WRAP,
410 	PKCS11_CKA_TRUSTED,
411 };
412 
413 static const uint32_t public_key_mandated[] = {
414 };
415 
416 static const uint32_t public_key_opt_or_null[] = {
417 	PKCS11_CKA_SUBJECT, PKCS11_CKA_WRAP_TEMPLATE,
418 	PKCS11_CKA_PUBLIC_KEY_INFO,
419 };
420 
421 /* PKCS#11 specification for any asymmetric private key (+any_key_xxx) */
422 static const uint32_t private_key_boolprops[] = {
423 	PKCS11_CKA_DECRYPT, PKCS11_CKA_SIGN, PKCS11_CKA_SIGN_RECOVER,
424 	PKCS11_CKA_UNWRAP,
425 	PKCS11_CKA_SENSITIVE, PKCS11_CKA_EXTRACTABLE,
426 	PKCS11_CKA_WRAP_WITH_TRUSTED, PKCS11_CKA_ALWAYS_AUTHENTICATE,
427 };
428 
429 static const uint32_t private_key_mandated[] = {
430 };
431 
432 static const uint32_t private_key_opt_or_null[] = {
433 	PKCS11_CKA_SUBJECT, PKCS11_CKA_UNWRAP_TEMPLATE,
434 	PKCS11_CKA_PUBLIC_KEY_INFO,
435 };
436 
437 /* PKCS#11 specification for any RSA key (+public/private_key_xxx) */
438 static const uint32_t rsa_pub_key_gen_mand[] = {
439 	PKCS11_CKA_MODULUS_BITS,
440 };
441 
442 static const uint32_t rsa_pub_key_create_mand[] = {
443 	PKCS11_CKA_MODULUS, PKCS11_CKA_PUBLIC_EXPONENT,
444 };
445 
446 static const uint32_t rsa_pub_key_gen_opt_or_null[] = {
447 	PKCS11_CKA_PUBLIC_EXPONENT,
448 };
449 
450 static const uint32_t rsa_priv_key_opt_or_null[] = {
451 	PKCS11_CKA_MODULUS, PKCS11_CKA_PUBLIC_EXPONENT,
452 	PKCS11_CKA_PRIVATE_EXPONENT,
453 	PKCS11_CKA_PRIME_1, PKCS11_CKA_PRIME_2,
454 	PKCS11_CKA_EXPONENT_1, PKCS11_CKA_EXPONENT_2, PKCS11_CKA_COEFFICIENT,
455 };
456 
457 /* PKCS#11 specification for any EC key (+public/private_key_xxx) */
458 static const uint32_t ec_public_key_mandated[] = {
459 	PKCS11_CKA_EC_PARAMS,
460 };
461 
462 static const uint32_t ec_public_key_opt_or_null[] = {
463 	PKCS11_CKA_EC_POINT,
464 };
465 
466 static const uint32_t ec_private_key_mandated[] = {
467 };
468 
469 static const uint32_t ec_private_key_opt_or_null[] = {
470 	PKCS11_CKA_EC_PARAMS,
471 	PKCS11_CKA_VALUE,
472 };
473 
474 static const uint32_t eddsa_private_key_opt_or_null[] = {
475 	PKCS11_CKA_EC_PARAMS,
476 	PKCS11_CKA_VALUE,
477 	PKCS11_CKA_EC_POINT,
478 };
479 
480 static enum pkcs11_rc create_storage_attributes(struct obj_attrs **out,
481 						struct obj_attrs *temp)
482 {
483 	enum pkcs11_class_id class = PKCS11_CKO_UNDEFINED_ID;
484 	enum pkcs11_rc rc = PKCS11_CKR_OK;
485 
486 	rc = init_attributes_head(out);
487 	if (rc)
488 		return rc;
489 
490 	/* Object class is mandatory */
491 	class = get_class(temp);
492 	if (class == PKCS11_CKO_UNDEFINED_ID) {
493 		EMSG("Class attribute not found");
494 
495 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
496 	}
497 	rc = add_attribute(out, PKCS11_CKA_CLASS, &class, sizeof(uint32_t));
498 	if (rc)
499 		return rc;
500 
501 	rc = set_mandatory_boolprops(out, temp, any_object_boolprops,
502 				     ARRAY_SIZE(any_object_boolprops));
503 	if (rc)
504 		return rc;
505 
506 	return set_attributes_opt_or_null(out, temp, any_object_opt_or_null,
507 					  ARRAY_SIZE(any_object_opt_or_null));
508 }
509 
510 static enum pkcs11_rc create_genkey_attributes(struct obj_attrs **out,
511 					       struct obj_attrs *temp)
512 {
513 	uint32_t type = PKCS11_CKO_UNDEFINED_ID;
514 	enum pkcs11_rc rc = PKCS11_CKR_OK;
515 
516 	rc = create_storage_attributes(out, temp);
517 	if (rc)
518 		return rc;
519 
520 	type = get_key_type(temp);
521 	if (type == PKCS11_CKK_UNDEFINED_ID) {
522 		EMSG("Key type attribute not found");
523 
524 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
525 	}
526 	rc = add_attribute(out, PKCS11_CKA_KEY_TYPE, &type, sizeof(uint32_t));
527 	if (rc)
528 		return rc;
529 
530 	rc = set_mandatory_boolprops(out, temp, any_key_boolprops,
531 				     ARRAY_SIZE(any_key_boolprops));
532 	if (rc)
533 		return rc;
534 
535 	rc = set_attributes_opt_or_null(out, temp, any_key_opt_or_null,
536 					ARRAY_SIZE(any_key_opt_or_null));
537 	if (rc)
538 		return rc;
539 
540 	return set_optional_attributes(out, temp, any_key_optional,
541 				       ARRAY_SIZE(any_key_optional));
542 
543 }
544 
545 static enum pkcs11_rc create_symm_key_attributes(struct obj_attrs **out,
546 						 struct obj_attrs *temp)
547 {
548 	enum pkcs11_rc rc = PKCS11_CKR_OK;
549 
550 	assert(get_class(temp) == PKCS11_CKO_SECRET_KEY);
551 
552 	rc = create_genkey_attributes(out, temp);
553 	if (rc)
554 		return rc;
555 
556 	assert(get_class(*out) == PKCS11_CKO_SECRET_KEY);
557 
558 	switch (get_key_type(*out)) {
559 	case PKCS11_CKK_GENERIC_SECRET:
560 	case PKCS11_CKK_AES:
561 	case PKCS11_CKK_MD5_HMAC:
562 	case PKCS11_CKK_SHA_1_HMAC:
563 	case PKCS11_CKK_SHA256_HMAC:
564 	case PKCS11_CKK_SHA384_HMAC:
565 	case PKCS11_CKK_SHA512_HMAC:
566 	case PKCS11_CKK_SHA224_HMAC:
567 		break;
568 	default:
569 		EMSG("Invalid key type %#"PRIx32"/%s",
570 		     get_key_type(*out), id2str_key_type(get_key_type(*out)));
571 
572 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
573 	}
574 
575 	rc = set_mandatory_boolprops(out, temp, symm_key_boolprops,
576 				     ARRAY_SIZE(symm_key_boolprops));
577 	if (rc)
578 		return rc;
579 
580 	rc = set_attributes_opt_or_null(out, temp, symm_key_opt_or_null,
581 					ARRAY_SIZE(symm_key_opt_or_null));
582 	if (rc)
583 		return rc;
584 
585 	return set_optional_attributes(out, temp, symm_key_optional,
586 				       ARRAY_SIZE(symm_key_optional));
587 }
588 
589 static enum pkcs11_rc create_data_attributes(struct obj_attrs **out,
590 					     struct obj_attrs *temp)
591 {
592 	enum pkcs11_rc rc = PKCS11_CKR_OK;
593 
594 	assert(get_class(temp) == PKCS11_CKO_DATA);
595 
596 	rc = create_storage_attributes(out, temp);
597 	if (rc)
598 		return rc;
599 
600 	assert(get_class(*out) == PKCS11_CKO_DATA);
601 
602 	return set_attributes_opt_or_null(out, temp, raw_data_opt_or_null,
603 					  ARRAY_SIZE(raw_data_opt_or_null));
604 }
605 
606 static enum pkcs11_rc create_certificate_attributes(struct obj_attrs **out,
607 						    struct obj_attrs *temp)
608 {
609 	uint32_t const *mandated = NULL;
610 	uint32_t const *optional = NULL;
611 	size_t mandated_count = 0;
612 	size_t optional_count = 0;
613 	void *attr_value = NULL;
614 	uint32_t attr_size = 0;
615 	uint32_t default_cert_category =
616 		PKCS11_CK_CERTIFICATE_CATEGORY_UNSPECIFIED;
617 	uint32_t default_name_hash_alg = PKCS11_CKM_SHA_1;
618 	uint32_t cert_category = 0;
619 	enum pkcs11_rc rc = PKCS11_CKR_OK;
620 
621 	assert(get_class(temp) == PKCS11_CKO_CERTIFICATE);
622 
623 	rc = create_storage_attributes(out, temp);
624 	if (rc)
625 		return rc;
626 
627 	assert(get_class(*out) == PKCS11_CKO_CERTIFICATE);
628 
629 	rc = set_mandatory_boolprops(out, temp, pkcs11_certificate_boolprops,
630 				     ARRAY_SIZE(pkcs11_certificate_boolprops));
631 	if (rc)
632 		return rc;
633 
634 	rc = set_mandatory_attributes(out, temp, pkcs11_certificate_mandated,
635 				      ARRAY_SIZE(pkcs11_certificate_mandated));
636 	if (rc)
637 		return rc;
638 
639 	rc = set_optional_attributes(out, temp, pkcs11_certificate_optional,
640 				     ARRAY_SIZE(pkcs11_certificate_optional));
641 	if (rc)
642 		return rc;
643 
644 	switch (get_certificate_type(*out)) {
645 	case PKCS11_CKC_X_509:
646 		mandated = pkcs11_x509_certificate_mandated;
647 		optional = pkcs11_x509_certificate_optional;
648 		mandated_count = ARRAY_SIZE(pkcs11_x509_certificate_mandated);
649 		optional_count = ARRAY_SIZE(pkcs11_x509_certificate_optional);
650 		break;
651 	default:
652 		EMSG("Invalid certificate type %#"PRIx32"/%s",
653 		     get_certificate_type(*out),
654 		     id2str_certificate_type(get_certificate_type(*out)));
655 
656 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
657 	}
658 
659 	rc = set_mandatory_attributes(out, temp, mandated, mandated_count);
660 	if (rc)
661 		return rc;
662 
663 	rc = set_optional_attributes(out, temp, optional, optional_count);
664 	if (rc)
665 		return rc;
666 
667 	attr_size = 0;
668 	rc = get_attribute_ptr(*out, PKCS11_CKA_CERTIFICATE_CATEGORY,
669 			       &attr_value, &attr_size);
670 	if (rc == PKCS11_CKR_OK && attr_size == sizeof(cert_category)) {
671 		/* Sanitize certificate category */
672 		TEE_MemMove(&cert_category, attr_value, sizeof(cert_category));
673 
674 		switch (cert_category) {
675 		case PKCS11_CK_CERTIFICATE_CATEGORY_UNSPECIFIED:
676 		case PKCS11_CK_CERTIFICATE_CATEGORY_TOKEN_USER:
677 		case PKCS11_CK_CERTIFICATE_CATEGORY_AUTHORITY:
678 		case PKCS11_CK_CERTIFICATE_CATEGORY_OTHER_ENTITY:
679 			break;
680 		default:
681 			EMSG("Invalid certificate category %#"PRIx32,
682 			     cert_category);
683 
684 			return PKCS11_CKR_ATTRIBUTE_VALUE_INVALID;
685 		}
686 	} else if (rc == PKCS11_RV_NOT_FOUND) {
687 		/* Set default category when missing */
688 		rc = set_attribute(out, PKCS11_CKA_CERTIFICATE_CATEGORY,
689 				   &default_cert_category,
690 				   sizeof(default_cert_category));
691 		if (rc)
692 			return rc;
693 	} else {
694 		/* All other cases are errors */
695 		EMSG("Invalid certificate category");
696 
697 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
698 	}
699 
700 	attr_size = 0;
701 	rc = get_attribute_ptr(*out, PKCS11_CKA_NAME_HASH_ALGORITHM, NULL,
702 			       &attr_size);
703 	if (rc == PKCS11_CKR_OK && attr_size == sizeof(uint32_t)) {
704 		/* We accept any algorithm what caller wanted to specify */
705 	} else if (rc == PKCS11_RV_NOT_FOUND) {
706 		/* Set default hash algorithm when missing */
707 		rc = set_attribute(out, PKCS11_CKA_NAME_HASH_ALGORITHM,
708 				   &default_name_hash_alg,
709 				   sizeof(default_name_hash_alg));
710 		if (rc)
711 			return rc;
712 	} else {
713 		/* All other cases are errors */
714 		EMSG("Invalid name hash algorithm");
715 
716 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
717 	}
718 
719 	return rc;
720 }
721 
722 static enum pkcs11_rc create_pub_key_attributes(struct obj_attrs **out,
723 						struct obj_attrs *temp,
724 						enum processing_func function)
725 {
726 	uint32_t const *mandated = NULL;
727 	uint32_t const *oon = NULL;
728 	size_t mandated_count = 0;
729 	size_t oon_count = 0;
730 	enum pkcs11_rc rc = PKCS11_CKR_OK;
731 
732 	assert(get_class(temp) == PKCS11_CKO_PUBLIC_KEY);
733 
734 	rc = create_genkey_attributes(out, temp);
735 	if (rc)
736 		return rc;
737 
738 	assert(get_class(*out) == PKCS11_CKO_PUBLIC_KEY);
739 
740 	rc = set_mandatory_boolprops(out, temp, public_key_boolprops,
741 				     ARRAY_SIZE(public_key_boolprops));
742 	if (rc)
743 		return rc;
744 
745 	rc = set_mandatory_attributes(out, temp, public_key_mandated,
746 				      ARRAY_SIZE(public_key_mandated));
747 	if (rc)
748 		return rc;
749 
750 	rc = set_attributes_opt_or_null(out, temp,
751 					public_key_opt_or_null,
752 					ARRAY_SIZE(public_key_opt_or_null));
753 	if (rc)
754 		return rc;
755 
756 	switch (get_key_type(*out)) {
757 	case PKCS11_CKK_RSA:
758 		switch (function) {
759 		case PKCS11_FUNCTION_GENERATE_PAIR:
760 			mandated = rsa_pub_key_gen_mand;
761 			oon = rsa_pub_key_gen_opt_or_null;
762 			mandated_count = ARRAY_SIZE(rsa_pub_key_gen_mand);
763 			oon_count = ARRAY_SIZE(rsa_pub_key_gen_opt_or_null);
764 			break;
765 		case PKCS11_FUNCTION_IMPORT:
766 			mandated = rsa_pub_key_create_mand;
767 			mandated_count = ARRAY_SIZE(rsa_pub_key_create_mand);
768 			break;
769 		default:
770 			EMSG("Unsupported function %#"PRIx32"/%s", function,
771 			     id2str_function(function));
772 
773 			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
774 		}
775 		break;
776 	case PKCS11_CKK_EC:
777 	case PKCS11_CKK_EC_EDWARDS:
778 		mandated = ec_public_key_mandated;
779 		oon = ec_public_key_opt_or_null;
780 		mandated_count = ARRAY_SIZE(ec_public_key_mandated);
781 		oon_count = ARRAY_SIZE(ec_public_key_opt_or_null);
782 		break;
783 	default:
784 		EMSG("Invalid key type %#"PRIx32"/%s",
785 		     get_key_type(*out), id2str_key_type(get_key_type(*out)));
786 
787 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
788 	}
789 
790 	rc = set_mandatory_attributes(out, temp, mandated, mandated_count);
791 	if (rc)
792 		return rc;
793 
794 	return set_attributes_opt_or_null(out, temp, oon, oon_count);
795 }
796 
797 static enum pkcs11_rc create_priv_key_attributes(struct obj_attrs **out,
798 						 struct obj_attrs *temp)
799 {
800 	uint32_t const *mandated = NULL;
801 	uint32_t const *oon = NULL;
802 	size_t mandated_count = 0;
803 	size_t oon_count = 0;
804 	enum pkcs11_rc rc = PKCS11_CKR_OK;
805 
806 	assert(get_class(temp) == PKCS11_CKO_PRIVATE_KEY);
807 
808 	rc = create_genkey_attributes(out, temp);
809 	if (rc)
810 		return rc;
811 
812 	assert(get_class(*out) == PKCS11_CKO_PRIVATE_KEY);
813 
814 	rc = set_mandatory_boolprops(out, temp, private_key_boolprops,
815 				     ARRAY_SIZE(private_key_boolprops));
816 	if (rc)
817 		return rc;
818 
819 	rc = set_mandatory_attributes(out, temp, private_key_mandated,
820 				      ARRAY_SIZE(private_key_mandated));
821 	if (rc)
822 		return rc;
823 
824 	rc = set_attributes_opt_or_null(out, temp, private_key_opt_or_null,
825 					ARRAY_SIZE(private_key_opt_or_null));
826 	if (rc)
827 		return rc;
828 
829 	switch (get_key_type(*out)) {
830 	case PKCS11_CKK_RSA:
831 		oon = rsa_priv_key_opt_or_null;
832 		oon_count = ARRAY_SIZE(rsa_priv_key_opt_or_null);
833 		break;
834 	case PKCS11_CKK_EC:
835 		mandated = ec_private_key_mandated;
836 		oon = ec_private_key_opt_or_null;
837 		mandated_count = ARRAY_SIZE(ec_private_key_mandated);
838 		oon_count = ARRAY_SIZE(ec_private_key_opt_or_null);
839 		break;
840 	case PKCS11_CKK_EC_EDWARDS:
841 		mandated = ec_private_key_mandated;
842 		oon = eddsa_private_key_opt_or_null;
843 		mandated_count = ARRAY_SIZE(ec_private_key_mandated);
844 		oon_count = ARRAY_SIZE(eddsa_private_key_opt_or_null);
845 		break;
846 	default:
847 		EMSG("Invalid key type %#"PRIx32"/%s",
848 		     get_key_type(*out), id2str_key_type(get_key_type(*out)));
849 
850 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
851 	}
852 
853 	rc = set_mandatory_attributes(out, temp, mandated, mandated_count);
854 	if (rc)
855 		return rc;
856 
857 	return set_attributes_opt_or_null(out, temp, oon, oon_count);
858 }
859 
860 static enum pkcs11_rc
861 sanitize_symm_key_attributes(struct obj_attrs **temp,
862 			     enum processing_func function)
863 {
864 	enum pkcs11_rc rc = PKCS11_CKR_OK;
865 	uint32_t a_size = 0;
866 
867 	assert(get_class(*temp) == PKCS11_CKO_SECRET_KEY);
868 
869 	rc = get_attribute_ptr(*temp, PKCS11_CKA_VALUE, NULL, &a_size);
870 
871 	switch (get_key_type(*temp)) {
872 	case PKCS11_CKK_GENERIC_SECRET:
873 	case PKCS11_CKK_AES:
874 	case PKCS11_CKK_MD5_HMAC:
875 	case PKCS11_CKK_SHA_1_HMAC:
876 	case PKCS11_CKK_SHA256_HMAC:
877 	case PKCS11_CKK_SHA384_HMAC:
878 	case PKCS11_CKK_SHA512_HMAC:
879 	case PKCS11_CKK_SHA224_HMAC:
880 		switch (function) {
881 		case PKCS11_FUNCTION_IMPORT:
882 			/* CKA_VALUE is a mandatory with C_CreateObject */
883 			if (rc || a_size == 0)
884 				return PKCS11_CKR_TEMPLATE_INCONSISTENT;
885 
886 			if (get_attribute_ptr(*temp, PKCS11_CKA_VALUE_LEN, NULL,
887 					      NULL) != PKCS11_RV_NOT_FOUND)
888 				return PKCS11_CKR_TEMPLATE_INCONSISTENT;
889 
890 			return add_attribute(temp, PKCS11_CKA_VALUE_LEN,
891 					     &a_size, sizeof(uint32_t));
892 		case PKCS11_FUNCTION_GENERATE:
893 			if (rc != PKCS11_RV_NOT_FOUND)
894 				return PKCS11_CKR_TEMPLATE_INCONSISTENT;
895 			break;
896 		default:
897 			break;
898 		}
899 		break;
900 	default:
901 		EMSG("Invalid key type %#"PRIx32"/%s",
902 		     get_key_type(*temp), id2str_key_type(get_key_type(*temp)));
903 
904 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
905 	}
906 
907 	return PKCS11_CKR_OK;
908 }
909 
910 /*
911  * Create an attribute list for a new object from a template and a parent
912  * object (optional) for an object generation function (generate, copy,
913  * derive...).
914  *
915  * PKCS#11 directives on the supplied template and expected return value:
916  * - template has an invalid attribute ID: ATTRIBUTE_TYPE_INVALID
917  * - template has an invalid value for an attribute: ATTRIBUTE_VALID_INVALID
918  * - template has value for a read-only attribute: ATTRIBUTE_READ_ONLY
919  * - template+default+parent => still miss an attribute: TEMPLATE_INCONSISTENT
920  *
921  * INFO on PKCS11_CMD_COPY_OBJECT:
922  * - parent PKCS11_CKA_COPYIABLE=false => return ACTION_PROHIBITED.
923  * - template can specify PKCS11_CKA_TOKEN, PKCS11_CKA_PRIVATE,
924  *   PKCS11_CKA_MODIFIABLE, PKCS11_CKA_DESTROYABLE.
925  * - SENSITIVE can change from false to true, not from true to false.
926  * - LOCAL is the parent LOCAL
927  */
928 enum pkcs11_rc
929 create_attributes_from_template(struct obj_attrs **out, void *template,
930 				size_t template_size,
931 				struct obj_attrs *parent,
932 				enum processing_func function,
933 				enum pkcs11_mechanism_id mecha,
934 				enum pkcs11_class_id template_class)
935 {
936 	struct obj_attrs *temp = NULL;
937 	struct obj_attrs *attrs = NULL;
938 	enum pkcs11_rc rc = PKCS11_CKR_OK;
939 	uint8_t local = 0;
940 	uint8_t always_sensitive = 0;
941 	uint8_t never_extract = 0;
942 	uint8_t extractable = 0;
943 	uint32_t class = PKCS11_UNDEFINED_ID;
944 	uint32_t type = PKCS11_UNDEFINED_ID;
945 	uint32_t mechanism_id = PKCS11_CKM_UNDEFINED_ID;
946 	struct obj_attrs *req_attrs = NULL;
947 	uint32_t size = 0;
948 	uint32_t indirect_template = PKCS11_CKA_UNDEFINED_ID;
949 
950 #ifdef DEBUG	/* Sanity: check function argument */
951 	trace_attributes_from_api_head("template", template, template_size);
952 	switch (function) {
953 	case PKCS11_FUNCTION_GENERATE:
954 	case PKCS11_FUNCTION_GENERATE_PAIR:
955 	case PKCS11_FUNCTION_IMPORT:
956 	case PKCS11_FUNCTION_MODIFY:
957 	case PKCS11_FUNCTION_DERIVE:
958 	case PKCS11_FUNCTION_UNWRAP:
959 	case PKCS11_FUNCTION_COPY:
960 		break;
961 	default:
962 		TEE_Panic(TEE_ERROR_NOT_SUPPORTED);
963 	}
964 #endif
965 
966 	/*
967 	 * For PKCS11_FUNCTION_GENERATE, find the class and type
968 	 * based on the mechanism. These will be passed as hint
969 	 * sanitize_client_object() and added in temp if not
970 	 * already present
971 	 */
972 	if (function == PKCS11_FUNCTION_GENERATE) {
973 		switch (mecha) {
974 		case PKCS11_CKM_GENERIC_SECRET_KEY_GEN:
975 			class = PKCS11_CKO_SECRET_KEY;
976 			type = PKCS11_CKK_GENERIC_SECRET;
977 			break;
978 		case PKCS11_CKM_AES_KEY_GEN:
979 			class = PKCS11_CKO_SECRET_KEY;
980 			type = PKCS11_CKK_AES;
981 			break;
982 		default:
983 			TEE_Panic(TEE_ERROR_NOT_SUPPORTED);
984 		}
985 	}
986 
987 	/*
988 	 * For PKCS11_FUNCTION_GENERATE_PAIR, find the class and type
989 	 * based on the mechanism. These will be passed as hint
990 	 * sanitize_client_object() and added in temp if not
991 	 * already present
992 	 */
993 	if (function == PKCS11_FUNCTION_GENERATE_PAIR) {
994 		switch (mecha) {
995 		case PKCS11_CKM_EC_EDWARDS_KEY_PAIR_GEN:
996 			class = template_class;
997 			type = PKCS11_CKK_EDDSA;
998 			break;
999 		case PKCS11_CKM_EC_KEY_PAIR_GEN:
1000 			class = template_class;
1001 			type = PKCS11_CKK_EC;
1002 			break;
1003 		case PKCS11_CKM_RSA_PKCS_KEY_PAIR_GEN:
1004 			class = template_class;
1005 			type = PKCS11_CKK_RSA;
1006 			break;
1007 		default:
1008 			TEE_Panic(TEE_ERROR_NOT_SUPPORTED);
1009 		}
1010 	}
1011 
1012 	/*
1013 	 * Check and remove duplicates if any and create a new temporary
1014 	 * template
1015 	 */
1016 	rc = sanitize_client_object(&temp, template, template_size, class,
1017 				    type);
1018 	if (rc)
1019 		goto out;
1020 
1021 	/*
1022 	 * For function type modify and copy return the created template
1023 	 * from here. Rest of the code below is for creating objects
1024 	 * or generating keys.
1025 	 */
1026 	switch (function) {
1027 	case PKCS11_FUNCTION_MODIFY:
1028 	case PKCS11_FUNCTION_COPY:
1029 		*out = temp;
1030 		return rc;
1031 	case PKCS11_FUNCTION_DERIVE:
1032 	case PKCS11_FUNCTION_UNWRAP:
1033 		if (function == PKCS11_FUNCTION_UNWRAP)
1034 			indirect_template = PKCS11_CKA_UNWRAP_TEMPLATE;
1035 		else
1036 			indirect_template = PKCS11_CKA_DERIVE_TEMPLATE;
1037 
1038 		rc = get_attribute_ptr(parent, indirect_template,
1039 				       (void *)&req_attrs, &size);
1040 		if (rc == PKCS11_CKR_OK && size != 0) {
1041 			rc = attributes_match_add_reference(&temp, req_attrs);
1042 			if (rc)
1043 				goto out;
1044 		}
1045 		break;
1046 	default:
1047 		break;
1048 	}
1049 
1050 	/*
1051 	 * Check if class and type in temp are consistent with the mechanism
1052 	 */
1053 	switch (mecha) {
1054 	case PKCS11_CKM_GENERIC_SECRET_KEY_GEN:
1055 		if (get_class(temp) != PKCS11_CKO_SECRET_KEY ||
1056 		    get_key_type(temp) != PKCS11_CKK_GENERIC_SECRET) {
1057 			rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
1058 			goto out;
1059 		}
1060 		break;
1061 	case PKCS11_CKM_AES_KEY_GEN:
1062 		if (get_class(temp) != PKCS11_CKO_SECRET_KEY ||
1063 		    get_key_type(temp) != PKCS11_CKK_AES) {
1064 			rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
1065 			goto out;
1066 		}
1067 		break;
1068 	case PKCS11_CKM_EC_KEY_PAIR_GEN:
1069 		if ((get_class(temp) != PKCS11_CKO_PUBLIC_KEY &&
1070 		     get_class(temp) != PKCS11_CKO_PRIVATE_KEY) ||
1071 		    get_key_type(temp) != PKCS11_CKK_EC) {
1072 			rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
1073 			goto out;
1074 		}
1075 		break;
1076 	case PKCS11_CKM_EC_EDWARDS_KEY_PAIR_GEN:
1077 		if ((get_class(temp) != PKCS11_CKO_PUBLIC_KEY &&
1078 		     get_class(temp) != PKCS11_CKO_PRIVATE_KEY) ||
1079 		    get_key_type(temp) != PKCS11_CKK_EC_EDWARDS) {
1080 			rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
1081 			goto out;
1082 		}
1083 		break;
1084 	case PKCS11_CKM_RSA_PKCS_KEY_PAIR_GEN:
1085 		if ((get_class(temp) != PKCS11_CKO_PUBLIC_KEY &&
1086 		     get_class(temp) != PKCS11_CKO_PRIVATE_KEY) ||
1087 		    get_key_type(temp) != PKCS11_CKK_RSA) {
1088 			rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
1089 			goto out;
1090 		}
1091 		break;
1092 	default:
1093 		break;
1094 	}
1095 
1096 	if (!sanitize_consistent_class_and_type(temp)) {
1097 		EMSG("Inconsistent class/type");
1098 		rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
1099 		goto out;
1100 	}
1101 
1102 	/*
1103 	 * TBD - Add a check to see if temp contains any attribute which
1104 	 * is not consistent with the object class or type and return error.
1105 	 * In current implementation such attributes are ignored and not
1106 	 * added to final object while PKCS#11 specification expects a
1107 	 * failure and an error code be returned.
1108 	 */
1109 
1110 	switch (get_class(temp)) {
1111 	case PKCS11_CKO_DATA:
1112 		rc = create_data_attributes(&attrs, temp);
1113 		break;
1114 	case PKCS11_CKO_CERTIFICATE:
1115 		rc = create_certificate_attributes(&attrs, temp);
1116 		break;
1117 	case PKCS11_CKO_SECRET_KEY:
1118 		rc = sanitize_symm_key_attributes(&temp, function);
1119 		if (rc)
1120 			goto out;
1121 		rc = create_symm_key_attributes(&attrs, temp);
1122 		break;
1123 	case PKCS11_CKO_PUBLIC_KEY:
1124 		rc = create_pub_key_attributes(&attrs, temp, function);
1125 		break;
1126 	case PKCS11_CKO_PRIVATE_KEY:
1127 		rc = create_priv_key_attributes(&attrs, temp);
1128 		break;
1129 	default:
1130 		DMSG("Invalid object class %#"PRIx32"/%s",
1131 		     get_class(temp), id2str_class(get_class(temp)));
1132 
1133 		rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
1134 		break;
1135 	}
1136 	if (rc)
1137 		goto out;
1138 
1139 	if (get_attribute_ptr(temp, PKCS11_CKA_LOCAL, NULL, NULL) !=
1140 	    PKCS11_RV_NOT_FOUND) {
1141 		rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
1142 		goto out;
1143 	}
1144 
1145 	if (get_attribute_ptr(temp, PKCS11_CKA_KEY_GEN_MECHANISM, NULL, NULL) !=
1146 	    PKCS11_RV_NOT_FOUND) {
1147 		rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
1148 		goto out;
1149 	}
1150 
1151 	switch (function) {
1152 	case PKCS11_FUNCTION_GENERATE:
1153 	case PKCS11_FUNCTION_GENERATE_PAIR:
1154 		local = PKCS11_TRUE;
1155 		break;
1156 	case PKCS11_FUNCTION_IMPORT:
1157 	case PKCS11_FUNCTION_DERIVE:
1158 	case PKCS11_FUNCTION_UNWRAP:
1159 	default:
1160 		local = PKCS11_FALSE;
1161 		break;
1162 	}
1163 	rc = add_attribute(&attrs, PKCS11_CKA_LOCAL, &local, sizeof(local));
1164 	if (rc)
1165 		goto out;
1166 
1167 	switch (get_class(attrs)) {
1168 	case PKCS11_CKO_SECRET_KEY:
1169 	case PKCS11_CKO_PRIVATE_KEY:
1170 	case PKCS11_CKO_PUBLIC_KEY:
1171 		always_sensitive = PKCS11_FALSE;
1172 		never_extract = PKCS11_FALSE;
1173 
1174 		switch (function) {
1175 		case PKCS11_FUNCTION_DERIVE:
1176 			always_sensitive =
1177 				get_bool(parent, PKCS11_CKA_ALWAYS_SENSITIVE) &&
1178 				get_bool(attrs, PKCS11_CKA_SENSITIVE);
1179 			never_extract =
1180 			       get_bool(parent, PKCS11_CKA_NEVER_EXTRACTABLE) &&
1181 			       !get_bool(attrs, PKCS11_CKA_EXTRACTABLE);
1182 			break;
1183 		case PKCS11_FUNCTION_UNWRAP:
1184 			always_sensitive = PKCS11_FALSE;
1185 			never_extract = PKCS11_FALSE;
1186 			extractable = PKCS11_TRUE;
1187 
1188 			/*
1189 			 * Check if template passed by user has CKA_EXTRACTABLE.
1190 			 * If not, by default value of CKA_EXTRACTABLE is set as
1191 			 * TRUE.
1192 			 */
1193 			if (get_attribute_ptr(temp, PKCS11_CKA_EXTRACTABLE,
1194 					      NULL,
1195 					      NULL) == PKCS11_RV_NOT_FOUND) {
1196 				rc = set_attribute(&attrs,
1197 						   PKCS11_CKA_EXTRACTABLE,
1198 						   &extractable,
1199 						   sizeof(extractable));
1200 				if (rc)
1201 					goto out;
1202 			}
1203 			break;
1204 		case PKCS11_FUNCTION_GENERATE:
1205 		case PKCS11_FUNCTION_GENERATE_PAIR:
1206 			always_sensitive = get_bool(attrs,
1207 						    PKCS11_CKA_SENSITIVE);
1208 			never_extract = !get_bool(attrs,
1209 						  PKCS11_CKA_EXTRACTABLE);
1210 			break;
1211 		default:
1212 			break;
1213 		}
1214 
1215 		rc = add_attribute(&attrs, PKCS11_CKA_ALWAYS_SENSITIVE,
1216 				   &always_sensitive, sizeof(always_sensitive));
1217 		if (rc)
1218 			goto out;
1219 
1220 		rc = add_attribute(&attrs, PKCS11_CKA_NEVER_EXTRACTABLE,
1221 				   &never_extract, sizeof(never_extract));
1222 		if (rc)
1223 			goto out;
1224 
1225 		/* Keys mandate attribute PKCS11_CKA_KEY_GEN_MECHANISM */
1226 		if (local)
1227 			mechanism_id = mecha;
1228 		else
1229 			mechanism_id = PKCS11_CK_UNAVAILABLE_INFORMATION;
1230 
1231 		rc = add_attribute(&attrs, PKCS11_CKA_KEY_GEN_MECHANISM,
1232 				   &mechanism_id, sizeof(mechanism_id));
1233 		if (rc)
1234 			goto out;
1235 		break;
1236 
1237 	default:
1238 		break;
1239 	}
1240 
1241 	*out = attrs;
1242 
1243 #ifdef DEBUG
1244 	trace_attributes("object", attrs);
1245 #endif
1246 
1247 out:
1248 	TEE_Free(temp);
1249 	if (rc)
1250 		TEE_Free(attrs);
1251 
1252 	return rc;
1253 }
1254 
1255 static enum pkcs11_rc check_attrs_misc_integrity(struct obj_attrs *head)
1256 {
1257 	if (get_bool(head, PKCS11_CKA_NEVER_EXTRACTABLE) &&
1258 	    get_bool(head, PKCS11_CKA_EXTRACTABLE)) {
1259 		DMSG("Never/Extractable attributes mismatch %d/%d",
1260 		     get_bool(head, PKCS11_CKA_NEVER_EXTRACTABLE),
1261 		     get_bool(head, PKCS11_CKA_EXTRACTABLE));
1262 
1263 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1264 	}
1265 
1266 	if (get_bool(head, PKCS11_CKA_ALWAYS_SENSITIVE) &&
1267 	    !get_bool(head, PKCS11_CKA_SENSITIVE)) {
1268 		DMSG("Sensitive/always attributes mismatch %d/%d",
1269 		     get_bool(head, PKCS11_CKA_SENSITIVE),
1270 		     get_bool(head, PKCS11_CKA_ALWAYS_SENSITIVE));
1271 
1272 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1273 	}
1274 
1275 	return PKCS11_CKR_OK;
1276 }
1277 
1278 bool object_is_private(struct obj_attrs *head)
1279 {
1280 	return get_bool(head, PKCS11_CKA_PRIVATE);
1281 }
1282 
1283 bool object_is_token(struct obj_attrs *head)
1284 {
1285 	return get_bool(head, PKCS11_CKA_TOKEN);
1286 }
1287 
1288 bool object_is_modifiable(struct obj_attrs *head)
1289 {
1290 	return get_bool(head, PKCS11_CKA_MODIFIABLE);
1291 }
1292 
1293 bool object_is_copyable(struct obj_attrs *head)
1294 {
1295 	return get_bool(head, PKCS11_CKA_COPYABLE);
1296 }
1297 
1298 /*
1299  * Check access to object against authentication to token
1300  */
1301 enum pkcs11_rc check_access_attrs_against_token(struct pkcs11_session *session,
1302 						struct obj_attrs *head)
1303 {
1304 	bool private = true;
1305 
1306 	switch (get_class(head)) {
1307 	case PKCS11_CKO_SECRET_KEY:
1308 	case PKCS11_CKO_PRIVATE_KEY:
1309 	case PKCS11_CKO_PUBLIC_KEY:
1310 	case PKCS11_CKO_DATA:
1311 	case PKCS11_CKO_CERTIFICATE:
1312 		private = object_is_private(head);
1313 		break;
1314 	default:
1315 		return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1316 	}
1317 
1318 	if (private && (pkcs11_session_is_public(session) ||
1319 			pkcs11_session_is_so(session))) {
1320 		DMSG("Private object access from a public or SO session");
1321 
1322 		return PKCS11_CKR_USER_NOT_LOGGED_IN;
1323 	}
1324 
1325 	return PKCS11_CKR_OK;
1326 }
1327 
1328 /*
1329  * Check the attributes of a to-be-created object matches the token state
1330  */
1331 enum pkcs11_rc check_created_attrs_against_token(struct pkcs11_session *session,
1332 						 struct obj_attrs *head)
1333 {
1334 	enum pkcs11_rc rc = PKCS11_CKR_OK;
1335 
1336 	rc = check_attrs_misc_integrity(head);
1337 	if (rc)
1338 		return rc;
1339 
1340 	if (get_bool(head, PKCS11_CKA_TRUSTED) &&
1341 	    !pkcs11_session_is_so(session)) {
1342 		DMSG("Can't create trusted object");
1343 
1344 		return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1345 	}
1346 
1347 	if (get_bool(head, PKCS11_CKA_TOKEN) &&
1348 	    !pkcs11_session_is_read_write(session)) {
1349 		DMSG("Can't create persistent object");
1350 
1351 		return PKCS11_CKR_SESSION_READ_ONLY;
1352 	}
1353 
1354 	return PKCS11_CKR_OK;
1355 }
1356 
1357 #define DMSG_BAD_BBOOL(attr, proc, head)				\
1358 	do {								\
1359 		uint32_t __maybe_unused _attr = (attr);			\
1360 		uint8_t __maybe_unused _bvalue = 0;			\
1361 		enum pkcs11_rc __maybe_unused _rc = PKCS11_CKR_OK;	\
1362 									\
1363 		_rc = get_attribute((head), _attr, &_bvalue, NULL);	\
1364 		DMSG("%s issue for %s: %sfound, value %"PRIu8,		\
1365 		     id2str_attr(_attr), id2str_proc((proc)),		\
1366 		     _rc ? "not " : "", _bvalue);			\
1367 	} while (0)
1368 
1369 static bool __maybe_unused check_attr_bval(uint32_t proc_id __maybe_unused,
1370 					   struct obj_attrs *head,
1371 					   uint32_t attribute, bool val)
1372 {
1373 	uint8_t bbool = 0;
1374 	uint32_t sz = sizeof(bbool);
1375 
1376 	if (!get_attribute(head, attribute, &bbool, &sz) && !!bbool == val)
1377 		return true;
1378 
1379 	DMSG_BAD_BBOOL(attribute, proc_id, head);
1380 	return false;
1381 }
1382 
1383 /*
1384  * Check the attributes of a new secret match the processing/mechanism
1385  * used to create it.
1386  *
1387  * @proc_id - PKCS11_CKM_xxx
1388  * @head - head of the attributes of the to-be-created object.
1389  */
1390 enum pkcs11_rc check_created_attrs_against_processing(uint32_t proc_id,
1391 						      struct obj_attrs *head)
1392 {
1393 	/*
1394 	 * Processings that do not create secrets are not expected to call
1395 	 * this function which would panic.
1396 	 */
1397 	switch (proc_id) {
1398 	case PKCS11_PROCESSING_IMPORT:
1399 	case PKCS11_CKM_ECDH1_DERIVE:
1400 	case PKCS11_CKM_AES_ECB:
1401 	case PKCS11_CKM_AES_CBC:
1402 	case PKCS11_CKM_AES_ECB_ENCRYPT_DATA:
1403 	case PKCS11_CKM_AES_CBC_ENCRYPT_DATA:
1404 	case PKCS11_CKM_RSA_AES_KEY_WRAP:
1405 		assert(check_attr_bval(proc_id, head, PKCS11_CKA_LOCAL, false));
1406 		break;
1407 	case PKCS11_CKM_GENERIC_SECRET_KEY_GEN:
1408 	case PKCS11_CKM_AES_KEY_GEN:
1409 	case PKCS11_CKM_EC_EDWARDS_KEY_PAIR_GEN:
1410 	case PKCS11_CKM_EC_KEY_PAIR_GEN:
1411 	case PKCS11_CKM_RSA_PKCS_KEY_PAIR_GEN:
1412 		assert(check_attr_bval(proc_id, head, PKCS11_CKA_LOCAL, true));
1413 		break;
1414 	default:
1415 		TEE_Panic(proc_id);
1416 		break;
1417 	}
1418 
1419 	switch (proc_id) {
1420 	case PKCS11_CKM_GENERIC_SECRET_KEY_GEN:
1421 		assert(get_key_type(head) == PKCS11_CKK_GENERIC_SECRET);
1422 		break;
1423 	case PKCS11_CKM_AES_KEY_GEN:
1424 		assert(get_key_type(head) == PKCS11_CKK_AES);
1425 		break;
1426 	case PKCS11_CKM_EC_EDWARDS_KEY_PAIR_GEN:
1427 		assert(get_key_type(head) == PKCS11_CKK_EC_EDWARDS);
1428 		break;
1429 	case PKCS11_CKM_EC_KEY_PAIR_GEN:
1430 		assert(get_key_type(head) == PKCS11_CKK_EC);
1431 		break;
1432 	case PKCS11_CKM_RSA_PKCS_KEY_PAIR_GEN:
1433 		assert(get_key_type(head) == PKCS11_CKK_RSA);
1434 		break;
1435 	case PKCS11_PROCESSING_IMPORT:
1436 	case PKCS11_CKM_ECDH1_DERIVE:
1437 	default:
1438 		break;
1439 	}
1440 
1441 	return PKCS11_CKR_OK;
1442 }
1443 
1444 /* Return min and max key size supported for a key_type in bytes */
1445 static void get_key_min_max_sizes(enum pkcs11_key_type key_type,
1446 				  uint32_t *min_key_size,
1447 				  uint32_t *max_key_size)
1448 {
1449 	enum pkcs11_mechanism_id mechanism = PKCS11_CKM_UNDEFINED_ID;
1450 
1451 	switch (key_type) {
1452 	case PKCS11_CKK_GENERIC_SECRET:
1453 		mechanism = PKCS11_CKM_GENERIC_SECRET_KEY_GEN;
1454 		break;
1455 	case PKCS11_CKK_AES:
1456 		mechanism = PKCS11_CKM_AES_KEY_GEN;
1457 		break;
1458 	case PKCS11_CKK_MD5_HMAC:
1459 		mechanism = PKCS11_CKM_MD5_HMAC;
1460 		break;
1461 	case PKCS11_CKK_SHA_1_HMAC:
1462 		mechanism = PKCS11_CKM_SHA_1_HMAC;
1463 		break;
1464 	case PKCS11_CKK_SHA224_HMAC:
1465 		mechanism = PKCS11_CKM_SHA224_HMAC;
1466 		break;
1467 	case PKCS11_CKK_SHA256_HMAC:
1468 		mechanism = PKCS11_CKM_SHA256_HMAC;
1469 		break;
1470 	case PKCS11_CKK_SHA384_HMAC:
1471 		mechanism = PKCS11_CKM_SHA384_HMAC;
1472 		break;
1473 	case PKCS11_CKK_SHA512_HMAC:
1474 		mechanism = PKCS11_CKM_SHA512_HMAC;
1475 		break;
1476 	case PKCS11_CKK_EC:
1477 		mechanism = PKCS11_CKM_EC_KEY_PAIR_GEN;
1478 		break;
1479 	case PKCS11_CKK_EDDSA:
1480 		mechanism = PKCS11_CKM_EC_EDWARDS_KEY_PAIR_GEN;
1481 		break;
1482 	case PKCS11_CKK_RSA:
1483 		mechanism = PKCS11_CKM_RSA_PKCS_KEY_PAIR_GEN;
1484 		break;
1485 	default:
1486 		TEE_Panic(key_type);
1487 		break;
1488 	}
1489 
1490 	mechanism_supported_key_sizes_bytes(mechanism, min_key_size,
1491 					    max_key_size);
1492 }
1493 
1494 enum pkcs11_rc check_created_attrs(struct obj_attrs *key1,
1495 				   struct obj_attrs *key2)
1496 {
1497 	enum pkcs11_rc rc = PKCS11_CKR_OK;
1498 	struct obj_attrs *secret = NULL;
1499 	struct obj_attrs *private = NULL;
1500 	struct obj_attrs *public = NULL;
1501 	uint32_t max_key_size = 0;
1502 	uint32_t min_key_size = 0;
1503 	uint32_t key_length = 0;
1504 
1505 	switch (get_class(key1)) {
1506 	case PKCS11_CKO_SECRET_KEY:
1507 		secret = key1;
1508 		break;
1509 	case PKCS11_CKO_PUBLIC_KEY:
1510 		public = key1;
1511 		break;
1512 	case PKCS11_CKO_PRIVATE_KEY:
1513 		private = key1;
1514 		break;
1515 	default:
1516 		return PKCS11_CKR_ATTRIBUTE_VALUE_INVALID;
1517 	}
1518 
1519 	if (key2) {
1520 		switch (get_class(key2)) {
1521 		case PKCS11_CKO_PUBLIC_KEY:
1522 			public = key2;
1523 			if (private == key1)
1524 				break;
1525 
1526 			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1527 		case PKCS11_CKO_PRIVATE_KEY:
1528 			private = key2;
1529 			if (public == key1)
1530 				break;
1531 
1532 			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1533 		default:
1534 			return PKCS11_CKR_ATTRIBUTE_VALUE_INVALID;
1535 		}
1536 
1537 		if (get_key_type(private) != get_key_type(public))
1538 			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1539 	}
1540 
1541 	if (secret) {
1542 		switch (get_key_type(secret)) {
1543 		case PKCS11_CKK_AES:
1544 		case PKCS11_CKK_GENERIC_SECRET:
1545 		case PKCS11_CKK_MD5_HMAC:
1546 		case PKCS11_CKK_SHA_1_HMAC:
1547 		case PKCS11_CKK_SHA224_HMAC:
1548 		case PKCS11_CKK_SHA256_HMAC:
1549 		case PKCS11_CKK_SHA384_HMAC:
1550 		case PKCS11_CKK_SHA512_HMAC:
1551 			break;
1552 		default:
1553 			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1554 		}
1555 
1556 		/* Get key size */
1557 		rc = get_u32_attribute(secret, PKCS11_CKA_VALUE_LEN,
1558 				       &key_length);
1559 		if (rc)
1560 			return PKCS11_CKR_TEMPLATE_INCOMPLETE;
1561 	}
1562 	if (public) {
1563 		switch (get_key_type(public)) {
1564 		case PKCS11_CKK_RSA:
1565 			/* Get key size */
1566 			rc = get_u32_attribute(public, PKCS11_CKA_MODULUS_BITS,
1567 					       &key_length);
1568 			if (rc)
1569 				return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1570 			key_length = ROUNDUP(key_length, 8) / 8;
1571 			break;
1572 		case PKCS11_CKK_EC:
1573 		case PKCS11_CKK_EC_EDWARDS:
1574 			break;
1575 		default:
1576 			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1577 		}
1578 	}
1579 	if (private) {
1580 		switch (get_key_type(private)) {
1581 		case PKCS11_CKK_RSA:
1582 		case PKCS11_CKK_EC:
1583 		case PKCS11_CKK_EC_EDWARDS:
1584 			break;
1585 		default:
1586 			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1587 		}
1588 	}
1589 
1590 	/*
1591 	 * Check key size for symmetric keys and RSA keys
1592 	 * EC is bound to domains, no need to check here.
1593 	 */
1594 	switch (get_key_type(key1)) {
1595 	case PKCS11_CKK_EC:
1596 	case PKCS11_CKK_EC_EDWARDS:
1597 		return PKCS11_CKR_OK;
1598 	default:
1599 		break;
1600 	}
1601 
1602 	get_key_min_max_sizes(get_key_type(key1), &min_key_size, &max_key_size);
1603 	if (key_length < min_key_size || key_length > max_key_size) {
1604 		EMSG("Length %"PRIu32" vs range [%"PRIu32" %"PRIu32"]",
1605 		     key_length, min_key_size, max_key_size);
1606 
1607 		return PKCS11_CKR_KEY_SIZE_RANGE;
1608 	}
1609 
1610 	if (secret && get_key_type(secret) == PKCS11_CKK_AES) {
1611 		if (key_length != 16 && key_length != 24 && key_length != 32)
1612 			return PKCS11_CKR_KEY_SIZE_RANGE;
1613 	}
1614 
1615 	return PKCS11_CKR_OK;
1616 }
1617 
1618 /* Check processing ID against attribute ALLOWED_MECHANISMS if any */
1619 static bool parent_key_complies_allowed_processings(uint32_t proc_id,
1620 						    struct obj_attrs *head)
1621 {
1622 	char *attr = NULL;
1623 	uint32_t size = 0;
1624 	uint32_t proc = 0;
1625 	size_t count = 0;
1626 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
1627 
1628 	rc = get_attribute_ptr(head, PKCS11_CKA_ALLOWED_MECHANISMS,
1629 			       (void *)&attr, &size);
1630 	if (rc == PKCS11_RV_NOT_FOUND)
1631 		return true;
1632 	if (rc) {
1633 		EMSG("unexpected attributes state");
1634 		TEE_Panic(TEE_ERROR_BAD_STATE);
1635 	}
1636 
1637 	for (count = size / sizeof(uint32_t); count; count--) {
1638 		TEE_MemMove(&proc, attr, sizeof(uint32_t));
1639 		attr += sizeof(uint32_t);
1640 
1641 		if (proc == proc_id)
1642 			return true;
1643 	}
1644 
1645 	DMSG("can't find %s in allowed list", id2str_proc(proc_id));
1646 	return false;
1647 }
1648 
1649 static enum pkcs11_attr_id func_to_attr(enum processing_func func)
1650 {
1651 	switch (func) {
1652 	case PKCS11_FUNCTION_ENCRYPT:
1653 		return PKCS11_CKA_ENCRYPT;
1654 	case PKCS11_FUNCTION_DECRYPT:
1655 		return PKCS11_CKA_DECRYPT;
1656 	case PKCS11_FUNCTION_SIGN:
1657 		return PKCS11_CKA_SIGN;
1658 	case PKCS11_FUNCTION_VERIFY:
1659 		return PKCS11_CKA_VERIFY;
1660 	case PKCS11_FUNCTION_WRAP:
1661 		return PKCS11_CKA_WRAP;
1662 	case PKCS11_FUNCTION_UNWRAP:
1663 		return PKCS11_CKA_UNWRAP;
1664 	case PKCS11_FUNCTION_DERIVE:
1665 		return PKCS11_CKA_DERIVE;
1666 	default:
1667 		return PKCS11_CKA_UNDEFINED_ID;
1668 	}
1669 }
1670 
1671 enum pkcs11_rc
1672 check_parent_attrs_against_processing(enum pkcs11_mechanism_id proc_id,
1673 				      enum processing_func function,
1674 				      struct obj_attrs *head)
1675 {
1676 	enum pkcs11_class_id key_class = get_class(head);
1677 	enum pkcs11_key_type key_type = get_key_type(head);
1678 	enum pkcs11_attr_id attr = func_to_attr(function);
1679 
1680 	if (!get_bool(head, attr)) {
1681 		DMSG("%s not permitted", id2str_attr(attr));
1682 		return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1683 	}
1684 
1685 	/* Check processing complies with parent key family */
1686 	switch (proc_id) {
1687 	case PKCS11_CKM_AES_ECB:
1688 	case PKCS11_CKM_AES_CBC:
1689 	case PKCS11_CKM_AES_CTS:
1690 	case PKCS11_CKM_AES_CTR:
1691 	case PKCS11_CKM_AES_CMAC:
1692 	case PKCS11_CKM_AES_CMAC_GENERAL:
1693 		if (key_class == PKCS11_CKO_SECRET_KEY &&
1694 		    key_type == PKCS11_CKK_AES)
1695 			break;
1696 
1697 		DMSG("%s invalid key %s/%s", id2str_proc(proc_id),
1698 		     id2str_class(key_class), id2str_key_type(key_type));
1699 
1700 		if (function == PKCS11_FUNCTION_WRAP)
1701 			return PKCS11_CKR_WRAPPING_KEY_TYPE_INCONSISTENT;
1702 		else if (function == PKCS11_FUNCTION_UNWRAP)
1703 			return PKCS11_CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT;
1704 		else
1705 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1706 
1707 	case PKCS11_CKM_AES_ECB_ENCRYPT_DATA:
1708 	case PKCS11_CKM_AES_CBC_ENCRYPT_DATA:
1709 		if (key_class != PKCS11_CKO_SECRET_KEY &&
1710 		    key_type != PKCS11_CKK_AES)
1711 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1712 
1713 		if (get_bool(head, PKCS11_CKA_ENCRYPT)) {
1714 			/*
1715 			 * Intentionally refuse to proceed despite
1716 			 * PKCS#11 specifications v2.40 and v3.0 not expecting
1717 			 * this behavior to avoid potential security issue
1718 			 * where keys derived by these mechanisms can be
1719 			 * revealed by doing data encryption using parent key.
1720 			 */
1721 			return PKCS11_CKR_FUNCTION_FAILED;
1722 		}
1723 
1724 		break;
1725 	case PKCS11_CKM_MD5_HMAC:
1726 	case PKCS11_CKM_SHA_1_HMAC:
1727 	case PKCS11_CKM_SHA224_HMAC:
1728 	case PKCS11_CKM_SHA256_HMAC:
1729 	case PKCS11_CKM_SHA384_HMAC:
1730 	case PKCS11_CKM_SHA512_HMAC:
1731 	case PKCS11_CKM_MD5_HMAC_GENERAL:
1732 	case PKCS11_CKM_SHA_1_HMAC_GENERAL:
1733 	case PKCS11_CKM_SHA224_HMAC_GENERAL:
1734 	case PKCS11_CKM_SHA256_HMAC_GENERAL:
1735 	case PKCS11_CKM_SHA384_HMAC_GENERAL:
1736 	case PKCS11_CKM_SHA512_HMAC_GENERAL:
1737 		if (key_class != PKCS11_CKO_SECRET_KEY)
1738 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1739 
1740 		if (key_type == PKCS11_CKK_GENERIC_SECRET)
1741 			break;
1742 
1743 		switch (proc_id) {
1744 		case PKCS11_CKM_MD5_HMAC:
1745 		case PKCS11_CKM_MD5_HMAC_GENERAL:
1746 			if (key_type == PKCS11_CKK_MD5_HMAC)
1747 				break;
1748 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1749 		case PKCS11_CKM_SHA_1_HMAC:
1750 		case PKCS11_CKM_SHA_1_HMAC_GENERAL:
1751 			if (key_type == PKCS11_CKK_SHA_1_HMAC)
1752 				break;
1753 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1754 		case PKCS11_CKM_SHA224_HMAC:
1755 		case PKCS11_CKM_SHA224_HMAC_GENERAL:
1756 			if (key_type == PKCS11_CKK_SHA224_HMAC)
1757 				break;
1758 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1759 		case PKCS11_CKM_SHA256_HMAC:
1760 		case PKCS11_CKM_SHA256_HMAC_GENERAL:
1761 			if (key_type == PKCS11_CKK_SHA256_HMAC)
1762 				break;
1763 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1764 		case PKCS11_CKM_SHA384_HMAC:
1765 		case PKCS11_CKM_SHA384_HMAC_GENERAL:
1766 			if (key_type == PKCS11_CKK_SHA384_HMAC)
1767 				break;
1768 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1769 		case PKCS11_CKM_SHA512_HMAC:
1770 		case PKCS11_CKM_SHA512_HMAC_GENERAL:
1771 			if (key_type == PKCS11_CKK_SHA512_HMAC)
1772 				break;
1773 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1774 		default:
1775 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1776 		}
1777 		break;
1778 
1779 	case PKCS11_CKM_EDDSA:
1780 		if (key_type != PKCS11_CKK_EC_EDWARDS) {
1781 			EMSG("Invalid key %s for mechanism %s",
1782 			     id2str_type(key_type, key_class),
1783 			     id2str_proc(proc_id));
1784 			return PKCS11_CKR_KEY_TYPE_INCONSISTENT;
1785 		}
1786 		if (key_class != PKCS11_CKO_PUBLIC_KEY &&
1787 		    key_class != PKCS11_CKO_PRIVATE_KEY) {
1788 			EMSG("Invalid key class for mechanism %s",
1789 			     id2str_proc(proc_id));
1790 
1791 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1792 		}
1793 		break;
1794 
1795 	case PKCS11_CKM_ECDSA:
1796 	case PKCS11_CKM_ECDSA_SHA1:
1797 	case PKCS11_CKM_ECDSA_SHA224:
1798 	case PKCS11_CKM_ECDSA_SHA256:
1799 	case PKCS11_CKM_ECDSA_SHA384:
1800 	case PKCS11_CKM_ECDSA_SHA512:
1801 	case PKCS11_CKM_ECDH1_DERIVE:
1802 		if (key_type != PKCS11_CKK_EC) {
1803 			EMSG("Invalid key %s for mechanism %s",
1804 			     id2str_type(key_type, key_class),
1805 			     id2str_proc(proc_id));
1806 
1807 			return PKCS11_CKR_KEY_TYPE_INCONSISTENT;
1808 		}
1809 		if (key_class != PKCS11_CKO_PUBLIC_KEY &&
1810 		    key_class != PKCS11_CKO_PRIVATE_KEY) {
1811 			EMSG("Invalid key class for mechanism %s",
1812 			     id2str_proc(proc_id));
1813 
1814 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1815 		}
1816 		break;
1817 	case PKCS11_CKM_RSA_PKCS:
1818 	case PKCS11_CKM_MD5_RSA_PKCS:
1819 	case PKCS11_CKM_SHA1_RSA_PKCS:
1820 	case PKCS11_CKM_SHA224_RSA_PKCS:
1821 	case PKCS11_CKM_SHA256_RSA_PKCS:
1822 	case PKCS11_CKM_SHA384_RSA_PKCS:
1823 	case PKCS11_CKM_SHA512_RSA_PKCS:
1824 	case PKCS11_CKM_RSA_AES_KEY_WRAP:
1825 	case PKCS11_CKM_RSA_PKCS_OAEP:
1826 	case PKCS11_CKM_RSA_PKCS_PSS:
1827 	case PKCS11_CKM_SHA1_RSA_PKCS_PSS:
1828 	case PKCS11_CKM_SHA224_RSA_PKCS_PSS:
1829 	case PKCS11_CKM_SHA256_RSA_PKCS_PSS:
1830 	case PKCS11_CKM_SHA384_RSA_PKCS_PSS:
1831 	case PKCS11_CKM_SHA512_RSA_PKCS_PSS:
1832 		if (key_type != PKCS11_CKK_RSA) {
1833 			EMSG("Invalid key %s for mechanism %s",
1834 			     id2str_type(key_type, key_class),
1835 			     id2str_proc(proc_id));
1836 
1837 			return PKCS11_CKR_KEY_TYPE_INCONSISTENT;
1838 		}
1839 		if (key_class != PKCS11_CKO_PUBLIC_KEY &&
1840 		    key_class != PKCS11_CKO_PRIVATE_KEY) {
1841 			EMSG("Invalid key class for mechanism %s",
1842 			     id2str_proc(proc_id));
1843 
1844 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1845 		}
1846 		break;
1847 	default:
1848 		DMSG("Invalid processing %#"PRIx32"/%s", proc_id,
1849 		     id2str_proc(proc_id));
1850 
1851 		return PKCS11_CKR_MECHANISM_INVALID;
1852 	}
1853 
1854 	if (!parent_key_complies_allowed_processings(proc_id, head)) {
1855 		DMSG("Allowed mechanism failed");
1856 		return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1857 	}
1858 
1859 	return PKCS11_CKR_OK;
1860 }
1861 
1862 bool attribute_is_exportable(struct pkcs11_attribute_head *req_attr,
1863 			     struct pkcs11_object *obj)
1864 {
1865 	uint8_t boolval = 0;
1866 	uint32_t boolsize = 0;
1867 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
1868 	enum pkcs11_class_id key_class = get_class(obj->attributes);
1869 
1870 	if (key_class != PKCS11_CKO_SECRET_KEY &&
1871 	    key_class != PKCS11_CKO_PRIVATE_KEY)
1872 		return true;
1873 
1874 	switch (req_attr->id) {
1875 	case PKCS11_CKA_PRIVATE_EXPONENT:
1876 	case PKCS11_CKA_PRIME_1:
1877 	case PKCS11_CKA_PRIME_2:
1878 	case PKCS11_CKA_EXPONENT_1:
1879 	case PKCS11_CKA_EXPONENT_2:
1880 	case PKCS11_CKA_COEFFICIENT:
1881 	case PKCS11_CKA_VALUE:
1882 		boolsize = sizeof(boolval);
1883 		rc = get_attribute(obj->attributes, PKCS11_CKA_EXTRACTABLE,
1884 				   &boolval, &boolsize);
1885 		if (rc || boolval == PKCS11_FALSE)
1886 			return false;
1887 
1888 		boolsize = sizeof(boolval);
1889 		rc = get_attribute(obj->attributes, PKCS11_CKA_SENSITIVE,
1890 				   &boolval, &boolsize);
1891 		if (rc || boolval == PKCS11_TRUE)
1892 			return false;
1893 		break;
1894 	default:
1895 		break;
1896 	}
1897 
1898 	return true;
1899 }
1900 
1901 static bool attr_is_modifiable_any_key(struct pkcs11_attribute_head *attr)
1902 {
1903 	switch (attr->id) {
1904 	case PKCS11_CKA_ID:
1905 	case PKCS11_CKA_START_DATE:
1906 	case PKCS11_CKA_END_DATE:
1907 	case PKCS11_CKA_DERIVE:
1908 		return true;
1909 	default:
1910 		return false;
1911 	}
1912 }
1913 
1914 static bool attr_is_modifiable_secret_key(struct pkcs11_attribute_head *attr,
1915 					  struct pkcs11_session *session,
1916 					  struct pkcs11_object *obj)
1917 {
1918 	switch (attr->id) {
1919 	case PKCS11_CKA_ENCRYPT:
1920 	case PKCS11_CKA_DECRYPT:
1921 	case PKCS11_CKA_SIGN:
1922 	case PKCS11_CKA_VERIFY:
1923 	case PKCS11_CKA_WRAP:
1924 	case PKCS11_CKA_UNWRAP:
1925 		return true;
1926 	/* Can't be modified once set to CK_FALSE - 12 in Table 10 */
1927 	case PKCS11_CKA_EXTRACTABLE:
1928 		return get_bool(obj->attributes, attr->id);
1929 	/* Can't be modified once set to CK_TRUE - 11 in Table 10 */
1930 	case PKCS11_CKA_SENSITIVE:
1931 	case PKCS11_CKA_WRAP_WITH_TRUSTED:
1932 		return !get_bool(obj->attributes, attr->id);
1933 	/* Change in CKA_TRUSTED can only be done by SO */
1934 	case PKCS11_CKA_TRUSTED:
1935 		return pkcs11_session_is_so(session);
1936 	case PKCS11_CKA_NEVER_EXTRACTABLE:
1937 	case PKCS11_CKA_ALWAYS_SENSITIVE:
1938 		return false;
1939 	default:
1940 		return false;
1941 	}
1942 }
1943 
1944 static bool attr_is_modifiable_public_key(struct pkcs11_attribute_head *attr,
1945 					  struct pkcs11_session *session,
1946 					  struct pkcs11_object *obj __unused)
1947 {
1948 	switch (attr->id) {
1949 	case PKCS11_CKA_SUBJECT:
1950 	case PKCS11_CKA_ENCRYPT:
1951 	case PKCS11_CKA_VERIFY:
1952 	case PKCS11_CKA_VERIFY_RECOVER:
1953 	case PKCS11_CKA_WRAP:
1954 		return true;
1955 	case PKCS11_CKA_TRUSTED:
1956 		/* Change in CKA_TRUSTED can only be done by SO */
1957 		return pkcs11_session_is_so(session);
1958 	default:
1959 		return false;
1960 	}
1961 }
1962 
1963 static bool attr_is_modifiable_private_key(struct pkcs11_attribute_head *attr,
1964 					   struct pkcs11_session *sess __unused,
1965 					   struct pkcs11_object *obj)
1966 {
1967 	switch (attr->id) {
1968 	case PKCS11_CKA_SUBJECT:
1969 	case PKCS11_CKA_DECRYPT:
1970 	case PKCS11_CKA_SIGN:
1971 	case PKCS11_CKA_SIGN_RECOVER:
1972 	case PKCS11_CKA_UNWRAP:
1973 	/*
1974 	 * TBD: Revisit if we don't support PKCS11_CKA_PUBLIC_KEY_INFO
1975 	 * Specification mentions that if this attribute is
1976 	 * supplied as part of a template for C_CreateObject, C_CopyObject or
1977 	 * C_SetAttributeValue for a private key, the token MUST verify
1978 	 * correspondence between the private key data and the public key data
1979 	 * as supplied in CKA_PUBLIC_KEY_INFO. This needs to be
1980 	 * taken care of when this object type will be implemented
1981 	 */
1982 	case PKCS11_CKA_PUBLIC_KEY_INFO:
1983 		return true;
1984 	/* Can't be modified once set to CK_FALSE - 12 in Table 10 */
1985 	case PKCS11_CKA_EXTRACTABLE:
1986 		return get_bool(obj->attributes, attr->id);
1987 	/* Can't be modified once set to CK_TRUE - 11 in Table 10 */
1988 	case PKCS11_CKA_SENSITIVE:
1989 	case PKCS11_CKA_WRAP_WITH_TRUSTED:
1990 		return !get_bool(obj->attributes, attr->id);
1991 	case PKCS11_CKA_NEVER_EXTRACTABLE:
1992 	case PKCS11_CKA_ALWAYS_SENSITIVE:
1993 		return false;
1994 	default:
1995 		return false;
1996 	}
1997 }
1998 
1999 static bool attr_is_modifiable_certificate(struct pkcs11_attribute_head *attr,
2000 					   struct pkcs11_session *session,
2001 					   struct pkcs11_object *obj)
2002 {
2003 	uint8_t boolval = 0;
2004 	uint32_t boolsize = 0;
2005 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2006 
2007 	/* Trusted certificates cannot be modified. */
2008 	rc = get_attribute(obj->attributes, PKCS11_CKA_TRUSTED,
2009 			   &boolval, &boolsize);
2010 	if (rc || boolval == PKCS11_TRUE)
2011 		return false;
2012 
2013 	/* Common certificate attributes */
2014 	switch (attr->id) {
2015 	case PKCS11_CKA_TRUSTED:
2016 		/*
2017 		 * The CKA_TRUSTED attribute cannot be set to CK_TRUE by an
2018 		 * application. It MUST be set by a token initialization
2019 		 * application or by the token’s SO.
2020 		 */
2021 		return pkcs11_session_is_so(session);
2022 	case PKCS11_CKA_CERTIFICATE_TYPE:
2023 	case PKCS11_CKA_CERTIFICATE_CATEGORY:
2024 		return false;
2025 	default:
2026 		break;
2027 	}
2028 
2029 	/* Certificate type specific attributes */
2030 	switch (get_certificate_type(obj->attributes)) {
2031 	case PKCS11_CKC_X_509:
2032 		/*
2033 		 * Only the CKA_ID, CKA_ISSUER, and CKA_SERIAL_NUMBER
2034 		 * attributes may be modified after the object is created.
2035 		 */
2036 		switch (attr->id) {
2037 		case PKCS11_CKA_ID:
2038 		case PKCS11_CKA_ISSUER:
2039 		case PKCS11_CKA_SERIAL_NUMBER:
2040 			return true;
2041 		default:
2042 			break;
2043 		}
2044 		break;
2045 	default:
2046 		/* Unsupported certificate type */
2047 		break;
2048 	}
2049 
2050 	return false;
2051 }
2052 
2053 static bool attribute_is_modifiable(struct pkcs11_session *session,
2054 				    struct pkcs11_attribute_head *req_attr,
2055 				    struct pkcs11_object *obj,
2056 				    enum pkcs11_class_id class,
2057 				    enum processing_func function)
2058 {
2059 	/* Check modifiable attributes common to any object */
2060 	switch (req_attr->id) {
2061 	case PKCS11_CKA_LABEL:
2062 		return true;
2063 	case PKCS11_CKA_TOKEN:
2064 	case PKCS11_CKA_MODIFIABLE:
2065 	case PKCS11_CKA_DESTROYABLE:
2066 	case PKCS11_CKA_PRIVATE:
2067 		return function == PKCS11_FUNCTION_COPY;
2068 	case PKCS11_CKA_COPYABLE:
2069 		/*
2070 		 * Specification mentions that if the attribute value is false
2071 		 * it can't be set to true. Reading this we assume that it
2072 		 * should be possible to modify this attribute even though this
2073 		 * is not marked as modifiable in Table 10 if done in right
2074 		 * direction i.e from TRUE -> FALSE.
2075 		 */
2076 		return get_bool(obj->attributes, req_attr->id);
2077 	default:
2078 		break;
2079 	}
2080 
2081 	/* Attribute checking based on class type */
2082 	switch (class) {
2083 	case PKCS11_CKO_SECRET_KEY:
2084 	case PKCS11_CKO_PUBLIC_KEY:
2085 	case PKCS11_CKO_PRIVATE_KEY:
2086 		if (attr_is_modifiable_any_key(req_attr))
2087 			return true;
2088 		if (class == PKCS11_CKO_SECRET_KEY &&
2089 		    attr_is_modifiable_secret_key(req_attr, session, obj))
2090 			return true;
2091 		if (class == PKCS11_CKO_PUBLIC_KEY &&
2092 		    attr_is_modifiable_public_key(req_attr, session, obj))
2093 			return true;
2094 		if (class == PKCS11_CKO_PRIVATE_KEY &&
2095 		    attr_is_modifiable_private_key(req_attr, session, obj))
2096 			return true;
2097 		break;
2098 	case PKCS11_CKO_DATA:
2099 		/* None of the data object attributes are modifiable */
2100 		return false;
2101 	case PKCS11_CKO_CERTIFICATE:
2102 		return attr_is_modifiable_certificate(req_attr, session, obj);
2103 	default:
2104 		break;
2105 	}
2106 
2107 	return false;
2108 }
2109 
2110 enum pkcs11_rc check_attrs_against_modification(struct pkcs11_session *session,
2111 						struct obj_attrs *head,
2112 						struct pkcs11_object *obj,
2113 						enum processing_func function)
2114 {
2115 	enum pkcs11_class_id class = PKCS11_CKO_UNDEFINED_ID;
2116 	char *cur = NULL;
2117 	char *end = NULL;
2118 	size_t len = 0;
2119 
2120 	class = get_class(obj->attributes);
2121 
2122 	cur = (char *)head + sizeof(struct obj_attrs);
2123 	end = cur + head->attrs_size;
2124 
2125 	for (; cur < end; cur += len) {
2126 		/* Structure aligned copy of the pkcs11_ref in the object */
2127 		struct pkcs11_attribute_head cli_ref = { };
2128 
2129 		TEE_MemMove(&cli_ref, cur, sizeof(cli_ref));
2130 		len = sizeof(cli_ref) + cli_ref.size;
2131 
2132 		/*
2133 		 * Check 1 - Check if attribute belongs to the object
2134 		 * The obj->attributes has all the attributes in
2135 		 * it which are allowed for an object.
2136 		 */
2137 		if (get_attribute_ptr(obj->attributes, cli_ref.id, NULL,
2138 				      NULL) == PKCS11_RV_NOT_FOUND)
2139 			return PKCS11_CKR_ATTRIBUTE_TYPE_INVALID;
2140 
2141 		/* Check 2 - Is attribute modifiable */
2142 		if (!attribute_is_modifiable(session, &cli_ref, obj, class,
2143 					     function))
2144 			return PKCS11_CKR_ATTRIBUTE_READ_ONLY;
2145 
2146 		/*
2147 		 * Checks for modification in PKCS11_CKA_TOKEN and
2148 		 * PKCS11_CKA_PRIVATE are required for PKCS11_FUNCTION_COPY
2149 		 * only, so skip them for PKCS11_FUNCTION_MODIFY.
2150 		 */
2151 		if (function == PKCS11_FUNCTION_MODIFY)
2152 			continue;
2153 
2154 		/*
2155 		 * An attempt to copy an object to a token will fail for
2156 		 * RO session
2157 		 */
2158 		if (cli_ref.id == PKCS11_CKA_TOKEN &&
2159 		    get_bool(head, PKCS11_CKA_TOKEN)) {
2160 			if (!pkcs11_session_is_read_write(session)) {
2161 				DMSG("Can't copy to token in a RO session");
2162 				return PKCS11_CKR_SESSION_READ_ONLY;
2163 			}
2164 		}
2165 
2166 		if (cli_ref.id == PKCS11_CKA_PRIVATE) {
2167 			bool parent_priv =
2168 				get_bool(obj->attributes, cli_ref.id);
2169 			bool obj_priv = get_bool(head, cli_ref.id);
2170 
2171 			/*
2172 			 * If PKCS11_CKA_PRIVATE is being set to TRUE from
2173 			 * FALSE, user has to be logged in
2174 			 */
2175 			if (!parent_priv && obj_priv) {
2176 				if ((pkcs11_session_is_public(session) ||
2177 				     pkcs11_session_is_so(session)))
2178 					return PKCS11_CKR_USER_NOT_LOGGED_IN;
2179 			}
2180 
2181 			/*
2182 			 * Restriction added - Even for Copy, do not allow
2183 			 * modification of CKA_PRIVATE from TRUE to FALSE
2184 			 */
2185 			if (parent_priv && !obj_priv)
2186 				return PKCS11_CKR_TEMPLATE_INCONSISTENT;
2187 		}
2188 	}
2189 
2190 	return PKCS11_CKR_OK;
2191 }
2192 
2193 static enum pkcs11_rc set_secret_key_data(struct obj_attrs **head, void *data,
2194 					  size_t key_size)
2195 {
2196 	uint32_t size = sizeof(uint32_t);
2197 	uint32_t key_length = 0;
2198 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2199 
2200 	/* Get key size if present in template */
2201 	rc = get_attribute(*head, PKCS11_CKA_VALUE_LEN, &key_length, &size);
2202 	if (rc && rc != PKCS11_RV_NOT_FOUND)
2203 		return rc;
2204 
2205 	if (key_length) {
2206 		if (key_size < key_length)
2207 			return PKCS11_CKR_DATA_LEN_RANGE;
2208 	} else {
2209 		key_length = key_size;
2210 		rc = set_attribute(head, PKCS11_CKA_VALUE_LEN, &key_length,
2211 				   sizeof(uint32_t));
2212 		if (rc)
2213 			return rc;
2214 	}
2215 
2216 	/* Now we can check the VALUE_LEN field */
2217 	rc = check_created_attrs(*head, NULL);
2218 	if (rc)
2219 		return rc;
2220 
2221 	/* Remove the default empty value attribute if found */
2222 	rc = remove_empty_attribute(head, PKCS11_CKA_VALUE);
2223 	if (rc != PKCS11_CKR_OK && rc != PKCS11_RV_NOT_FOUND)
2224 		return PKCS11_CKR_GENERAL_ERROR;
2225 
2226 	return add_attribute(head, PKCS11_CKA_VALUE, data, key_length);
2227 }
2228 
2229 static enum pkcs11_rc set_private_key_data_rsa(struct obj_attrs **head,
2230 					       void *data,
2231 					       size_t key_size)
2232 {
2233 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2234 	int mbedtls_rc = 0;
2235 	uint32_t key_bits = 0;
2236 	uint32_t size = 0;
2237 	uint32_t buffer_size = 0;
2238 	void *buffer = NULL;
2239 	mbedtls_pk_context pk = { };
2240 	mbedtls_rsa_context *rsa = NULL;
2241 	mbedtls_mpi n = { };
2242 	mbedtls_mpi e = { };
2243 	mbedtls_mpi d = { };
2244 	mbedtls_mpi p = { };
2245 	mbedtls_mpi q = { };
2246 
2247 	rc = get_u32_attribute(*head, PKCS11_CKA_MODULUS_BITS, &key_bits);
2248 	if (rc && rc != PKCS11_RV_NOT_FOUND)
2249 		return rc;
2250 
2251 	if (remove_empty_attribute(head, PKCS11_CKA_MODULUS) ||
2252 	    remove_empty_attribute(head, PKCS11_CKA_PUBLIC_EXPONENT) ||
2253 	    remove_empty_attribute(head, PKCS11_CKA_PRIVATE_EXPONENT) ||
2254 	    remove_empty_attribute(head, PKCS11_CKA_PRIME_1) ||
2255 	    remove_empty_attribute(head, PKCS11_CKA_PRIME_2))
2256 		return PKCS11_CKR_GENERAL_ERROR;
2257 
2258 	mbedtls_pk_init(&pk);
2259 	mbedtls_mpi_init(&n);
2260 	mbedtls_mpi_init(&e);
2261 	mbedtls_mpi_init(&d);
2262 	mbedtls_mpi_init(&p);
2263 	mbedtls_mpi_init(&q);
2264 
2265 	mbedtls_rc = mbedtls_pk_parse_key(&pk, data, key_size, NULL, 0);
2266 	if (mbedtls_rc) {
2267 		rc = PKCS11_CKR_ARGUMENTS_BAD;
2268 		goto out;
2269 	}
2270 
2271 	rsa = mbedtls_pk_rsa(pk);
2272 	mbedtls_rc = mbedtls_rsa_export(rsa, &n, &p, &q, &d, &e);
2273 	if (mbedtls_rc) {
2274 		rc = PKCS11_CKR_ARGUMENTS_BAD;
2275 		goto out;
2276 	}
2277 
2278 	if (key_bits && mbedtls_mpi_bitlen(&n) != key_bits) {
2279 		rc = PKCS11_CKR_WRAPPED_KEY_LEN_RANGE;
2280 		goto out;
2281 	}
2282 
2283 	size = ROUNDUP_DIV(mbedtls_mpi_bitlen(&n), 8);
2284 	buffer_size = size;
2285 	buffer = TEE_Malloc(buffer_size, TEE_USER_MEM_HINT_NO_FILL_ZERO);
2286 	if (!buffer) {
2287 		rc = PKCS11_CKR_DEVICE_MEMORY;
2288 		goto out;
2289 	}
2290 
2291 	mbedtls_rc = mbedtls_mpi_write_binary(&n, buffer, size);
2292 	if (mbedtls_rc) {
2293 		rc = PKCS11_CKR_WRAPPED_KEY_INVALID;
2294 		goto out;
2295 	}
2296 
2297 	rc = add_attribute(head, PKCS11_CKA_MODULUS, buffer, size);
2298 	if (rc)
2299 		goto out;
2300 
2301 	size = ROUNDUP_DIV(mbedtls_mpi_bitlen(&e), 8);
2302 	if (buffer_size < size) {
2303 		rc = PKCS11_CKR_WRAPPED_KEY_LEN_RANGE;
2304 		goto out;
2305 	}
2306 
2307 	mbedtls_rc = mbedtls_mpi_write_binary(&e, buffer, size);
2308 	if (mbedtls_rc) {
2309 		rc = PKCS11_CKR_WRAPPED_KEY_INVALID;
2310 		goto out;
2311 	}
2312 
2313 	rc = add_attribute(head, PKCS11_CKA_PUBLIC_EXPONENT, buffer, size);
2314 	if (rc)
2315 		goto out;
2316 
2317 	size = ROUNDUP_DIV(mbedtls_mpi_bitlen(&d), 8);
2318 	if (buffer_size < size) {
2319 		rc = PKCS11_CKR_WRAPPED_KEY_LEN_RANGE;
2320 		goto out;
2321 	}
2322 
2323 	mbedtls_rc = mbedtls_mpi_write_binary(&d, buffer, size);
2324 	if (mbedtls_rc) {
2325 		rc = PKCS11_CKR_WRAPPED_KEY_INVALID;
2326 		goto out;
2327 	}
2328 
2329 	rc = add_attribute(head, PKCS11_CKA_PRIVATE_EXPONENT, buffer, size);
2330 	if (rc)
2331 		goto out;
2332 
2333 	size = ROUNDUP_DIV(mbedtls_mpi_bitlen(&p), 8);
2334 	if (buffer_size < size) {
2335 		rc = PKCS11_CKR_WRAPPED_KEY_LEN_RANGE;
2336 		goto out;
2337 	}
2338 
2339 	mbedtls_rc = mbedtls_mpi_write_binary(&p, buffer, size);
2340 	if (mbedtls_rc) {
2341 		rc = PKCS11_CKR_WRAPPED_KEY_INVALID;
2342 		goto out;
2343 	}
2344 
2345 	rc = add_attribute(head, PKCS11_CKA_PRIME_1, buffer, size);
2346 	if (rc)
2347 		goto out;
2348 
2349 	size = ROUNDUP_DIV(mbedtls_mpi_bitlen(&q), 8);
2350 	if (buffer_size < size) {
2351 		rc = PKCS11_CKR_WRAPPED_KEY_LEN_RANGE;
2352 		goto out;
2353 	}
2354 
2355 	mbedtls_rc = mbedtls_mpi_write_binary(&q, buffer, size);
2356 	if (mbedtls_rc) {
2357 		rc = PKCS11_CKR_WRAPPED_KEY_INVALID;
2358 		goto out;
2359 	}
2360 
2361 	rc = add_attribute(head, PKCS11_CKA_PRIME_2, buffer, size);
2362 
2363 out:
2364 	mbedtls_pk_free(&pk);
2365 	mbedtls_mpi_free(&n);
2366 	mbedtls_mpi_free(&e);
2367 	mbedtls_mpi_free(&d);
2368 	mbedtls_mpi_free(&p);
2369 	mbedtls_mpi_free(&q);
2370 	TEE_Free(buffer);
2371 	return rc;
2372 }
2373 
2374 enum pkcs11_rc set_key_data(struct obj_attrs **head, void *data,
2375 			    size_t key_size)
2376 {
2377 	switch (get_class(*head)) {
2378 	case PKCS11_CKO_SECRET_KEY:
2379 		return set_secret_key_data(head, data, key_size);
2380 	case PKCS11_CKO_PRIVATE_KEY:
2381 		if (get_key_type(*head) == PKCS11_CKK_RSA)
2382 			return set_private_key_data_rsa(head, data, key_size);
2383 		break;
2384 	default:
2385 		return PKCS11_CKR_GENERAL_ERROR;
2386 	}
2387 
2388 	return PKCS11_CKR_GENERAL_ERROR;
2389 }
2390 
2391 static enum pkcs11_rc alloc_copy_attribute_value(struct obj_attrs *head,
2392 						 void **data, uint32_t *sz)
2393 {
2394 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2395 	void *buffer = NULL;
2396 	void *value = NULL;
2397 
2398 	rc = get_attribute_ptr(head, PKCS11_CKA_VALUE, &value, sz);
2399 	if (rc)
2400 		return PKCS11_CKR_ARGUMENTS_BAD;
2401 
2402 	buffer = TEE_Malloc(*sz, TEE_USER_MEM_HINT_NO_FILL_ZERO);
2403 	if (!buffer)
2404 		return PKCS11_CKR_DEVICE_MEMORY;
2405 
2406 	TEE_MemMove(buffer, value, *sz);
2407 	*data = buffer;
2408 
2409 	return PKCS11_CKR_OK;
2410 }
2411 
2412 static enum pkcs11_rc
2413 encode_rsa_private_key_der(struct obj_attrs *head, void **data, uint32_t *sz)
2414 {
2415 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2416 	int i = 0;
2417 	int mbedtls_rc = 0;
2418 	int start = 0;
2419 	int der_size = 0;
2420 	void *n = NULL;
2421 	void *p = NULL;
2422 	void *q = NULL;
2423 	void *d = NULL;
2424 	void *e = NULL;
2425 	uint32_t n_len = 0;
2426 	uint32_t p_len = 0;
2427 	uint32_t q_len = 0;
2428 	uint32_t d_len = 0;
2429 	uint32_t e_len = 0;
2430 	uint8_t *buffer = NULL;
2431 	mbedtls_pk_context pk = { };
2432 	mbedtls_rsa_context *rsa = NULL;
2433 	const mbedtls_pk_info_t *pk_info = NULL;
2434 
2435 	mbedtls_pk_init(&pk);
2436 	pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA);
2437 	if (mbedtls_pk_setup(&pk, pk_info)) {
2438 		rc = PKCS11_CKR_GENERAL_ERROR;
2439 		goto out;
2440 	}
2441 
2442 	rc = get_attribute_ptr(head, PKCS11_CKA_MODULUS, &n, &n_len);
2443 	if (rc)
2444 		goto out;
2445 
2446 	rc = get_attribute_ptr(head, PKCS11_CKA_PRIME_1, &p, &p_len);
2447 	if (rc)
2448 		goto out;
2449 
2450 	rc = get_attribute_ptr(head, PKCS11_CKA_PRIME_2, &q, &q_len);
2451 	if (rc)
2452 		goto out;
2453 
2454 	rc = get_attribute_ptr(head, PKCS11_CKA_PRIVATE_EXPONENT, &d, &d_len);
2455 	if (rc)
2456 		goto out;
2457 
2458 	rc = get_attribute_ptr(head, PKCS11_CKA_PUBLIC_EXPONENT, &e, &e_len);
2459 	if (rc)
2460 		goto out;
2461 
2462 	rsa = mbedtls_pk_rsa(pk);
2463 	mbedtls_rc = mbedtls_rsa_import_raw(rsa, n, n_len, p, p_len,
2464 					    q, q_len, d, d_len, e, e_len);
2465 	if (mbedtls_rc) {
2466 		rc = PKCS11_CKR_ARGUMENTS_BAD;
2467 		goto out;
2468 	}
2469 
2470 	if (mbedtls_rsa_complete(rsa)) {
2471 		rc = PKCS11_CKR_ARGUMENTS_BAD;
2472 		goto out;
2473 	}
2474 
2475 	if (mbedtls_rsa_check_privkey(rsa)) {
2476 		rc = PKCS11_CKR_ARGUMENTS_BAD;
2477 		goto out;
2478 	}
2479 
2480 	der_size = n_len * 8;
2481 	buffer = TEE_Malloc(der_size, TEE_USER_MEM_HINT_NO_FILL_ZERO);
2482 	if (!buffer) {
2483 		rc = PKCS11_CKR_DEVICE_MEMORY;
2484 		goto out;
2485 	}
2486 
2487 	mbedtls_rc = mbedtls_pk_write_key_der(&pk, buffer, der_size);
2488 	if (mbedtls_rc < 0) {
2489 		rc = PKCS11_CKR_ARGUMENTS_BAD;
2490 		goto out;
2491 	}
2492 
2493 	start = der_size - mbedtls_rc;
2494 	for (i = 0; i < mbedtls_rc; i++) {
2495 		buffer[i] = buffer[i + start];
2496 		buffer[i + start] = 0;
2497 	}
2498 
2499 	*data = buffer;
2500 	*sz = mbedtls_rc;
2501 out:
2502 	mbedtls_pk_free(&pk);
2503 
2504 	if (rc)
2505 		TEE_Free(buffer);
2506 
2507 	return rc;
2508 }
2509 
2510 enum pkcs11_rc alloc_key_data_to_wrap(struct obj_attrs *head, void **data,
2511 				      uint32_t *sz)
2512 {
2513 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2514 
2515 	switch (get_class(head)) {
2516 	case PKCS11_CKO_SECRET_KEY:
2517 		rc = alloc_copy_attribute_value(head, data, sz);
2518 		break;
2519 	case PKCS11_CKO_PRIVATE_KEY:
2520 		if (get_key_type(head) == PKCS11_CKK_RSA)
2521 			rc = encode_rsa_private_key_der(head, data, sz);
2522 		break;
2523 	default:
2524 		break;
2525 	}
2526 
2527 	return rc;
2528 }
2529 
2530 enum pkcs11_rc add_missing_attribute_id(struct obj_attrs **pub_head,
2531 					struct obj_attrs **priv_head)
2532 {
2533 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2534 	void *id1 = NULL;
2535 	uint32_t id1_size = 0;
2536 	void *id2 = NULL;
2537 	uint32_t id2_size = 0;
2538 
2539 	assert(pub_head);
2540 	assert(priv_head);
2541 
2542 	rc = get_attribute_ptr(*pub_head, PKCS11_CKA_ID, &id1, &id1_size);
2543 	if (rc) {
2544 		if (rc != PKCS11_RV_NOT_FOUND)
2545 			return rc;
2546 		id1 = NULL;
2547 	} else if (!id1_size) {
2548 		id1 = NULL;
2549 	}
2550 
2551 	rc = get_attribute_ptr(*priv_head, PKCS11_CKA_ID, &id2, &id2_size);
2552 	if (rc) {
2553 		if (rc != PKCS11_RV_NOT_FOUND)
2554 			return rc;
2555 		id2 = NULL;
2556 	} else if (!id2_size) {
2557 		id2 = NULL;
2558 	}
2559 
2560 	/* Both have value -- let them be what caller has specified them */
2561 	if (id1 && id2)
2562 		return PKCS11_CKR_OK;
2563 
2564 	/* Both are empty -- leave empty values */
2565 	if (!id1 && !id2)
2566 		return PKCS11_CKR_OK;
2567 
2568 	/* Cross copy CKA_ID value */
2569 	if (id1)
2570 		return set_attribute(priv_head, PKCS11_CKA_ID, id1, id1_size);
2571 	else
2572 		return set_attribute(pub_head, PKCS11_CKA_ID, id2, id2_size);
2573 }
2574