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