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