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