xref: /optee_os/ta/pkcs11/src/pkcs11_attributes.c (revision 19a31ec40245ae01a9adcd206eec2a4bb4479fc9)
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 __maybe_unused,
262 					void **value, 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
1647 check_created_attrs_against_processing(uint32_t proc_id,
1648 				       struct obj_attrs *head __maybe_unused)
1649 {
1650 	/*
1651 	 * Processings that do not create secrets are not expected to call
1652 	 * this function which would panic.
1653 	 */
1654 	switch (proc_id) {
1655 	case PKCS11_PROCESSING_IMPORT:
1656 	case PKCS11_CKM_ECDH1_DERIVE:
1657 	case PKCS11_CKM_AES_ECB:
1658 	case PKCS11_CKM_AES_CBC:
1659 	case PKCS11_CKM_AES_ECB_ENCRYPT_DATA:
1660 	case PKCS11_CKM_AES_CBC_ENCRYPT_DATA:
1661 	case PKCS11_CKM_RSA_AES_KEY_WRAP:
1662 		assert(check_attr_bval(proc_id, head, PKCS11_CKA_LOCAL, false));
1663 		break;
1664 	case PKCS11_CKM_GENERIC_SECRET_KEY_GEN:
1665 	case PKCS11_CKM_AES_KEY_GEN:
1666 	case PKCS11_CKM_EC_EDWARDS_KEY_PAIR_GEN:
1667 	case PKCS11_CKM_EC_KEY_PAIR_GEN:
1668 	case PKCS11_CKM_RSA_PKCS_KEY_PAIR_GEN:
1669 		assert(check_attr_bval(proc_id, head, PKCS11_CKA_LOCAL, true));
1670 		break;
1671 	default:
1672 		TEE_Panic(proc_id);
1673 		break;
1674 	}
1675 
1676 	switch (proc_id) {
1677 	case PKCS11_CKM_GENERIC_SECRET_KEY_GEN:
1678 		assert(get_key_type(head) == PKCS11_CKK_GENERIC_SECRET);
1679 		break;
1680 	case PKCS11_CKM_AES_KEY_GEN:
1681 		assert(get_key_type(head) == PKCS11_CKK_AES);
1682 		break;
1683 	case PKCS11_CKM_EC_EDWARDS_KEY_PAIR_GEN:
1684 		assert(get_key_type(head) == PKCS11_CKK_EC_EDWARDS);
1685 		break;
1686 	case PKCS11_CKM_EC_KEY_PAIR_GEN:
1687 		assert(get_key_type(head) == PKCS11_CKK_EC);
1688 		break;
1689 	case PKCS11_CKM_RSA_PKCS_KEY_PAIR_GEN:
1690 		assert(get_key_type(head) == PKCS11_CKK_RSA);
1691 		break;
1692 	case PKCS11_PROCESSING_IMPORT:
1693 	case PKCS11_CKM_ECDH1_DERIVE:
1694 	default:
1695 		break;
1696 	}
1697 
1698 	return PKCS11_CKR_OK;
1699 }
1700 
1701 /* Return min and max key size supported for a key_type in bytes */
1702 static void get_key_min_max_sizes(enum pkcs11_key_type key_type,
1703 				  uint32_t *min_key_size,
1704 				  uint32_t *max_key_size)
1705 {
1706 	enum pkcs11_mechanism_id mechanism = PKCS11_CKM_UNDEFINED_ID;
1707 
1708 	switch (key_type) {
1709 	case PKCS11_CKK_GENERIC_SECRET:
1710 		mechanism = PKCS11_CKM_GENERIC_SECRET_KEY_GEN;
1711 		break;
1712 	case PKCS11_CKK_AES:
1713 		mechanism = PKCS11_CKM_AES_KEY_GEN;
1714 		break;
1715 	case PKCS11_CKK_MD5_HMAC:
1716 		mechanism = PKCS11_CKM_MD5_HMAC;
1717 		break;
1718 	case PKCS11_CKK_SHA_1_HMAC:
1719 		mechanism = PKCS11_CKM_SHA_1_HMAC;
1720 		break;
1721 	case PKCS11_CKK_SHA224_HMAC:
1722 		mechanism = PKCS11_CKM_SHA224_HMAC;
1723 		break;
1724 	case PKCS11_CKK_SHA256_HMAC:
1725 		mechanism = PKCS11_CKM_SHA256_HMAC;
1726 		break;
1727 	case PKCS11_CKK_SHA384_HMAC:
1728 		mechanism = PKCS11_CKM_SHA384_HMAC;
1729 		break;
1730 	case PKCS11_CKK_SHA512_HMAC:
1731 		mechanism = PKCS11_CKM_SHA512_HMAC;
1732 		break;
1733 	case PKCS11_CKK_EC:
1734 		mechanism = PKCS11_CKM_EC_KEY_PAIR_GEN;
1735 		break;
1736 	case PKCS11_CKK_EDDSA:
1737 		mechanism = PKCS11_CKM_EC_EDWARDS_KEY_PAIR_GEN;
1738 		break;
1739 	case PKCS11_CKK_RSA:
1740 		mechanism = PKCS11_CKM_RSA_PKCS_KEY_PAIR_GEN;
1741 		break;
1742 	default:
1743 		TEE_Panic(key_type);
1744 		break;
1745 	}
1746 
1747 	mechanism_supported_key_sizes_bytes(mechanism, min_key_size,
1748 					    max_key_size);
1749 }
1750 
1751 enum pkcs11_rc check_created_attrs(struct obj_attrs *key1,
1752 				   struct obj_attrs *key2)
1753 {
1754 	enum pkcs11_rc rc = PKCS11_CKR_OK;
1755 	struct obj_attrs *secret = NULL;
1756 	struct obj_attrs *private = NULL;
1757 	struct obj_attrs *public = NULL;
1758 	uint32_t max_key_size = 0;
1759 	uint32_t min_key_size = 0;
1760 	uint32_t key_length = 0;
1761 
1762 	switch (get_class(key1)) {
1763 	case PKCS11_CKO_SECRET_KEY:
1764 		secret = key1;
1765 		break;
1766 	case PKCS11_CKO_PUBLIC_KEY:
1767 		public = key1;
1768 		break;
1769 	case PKCS11_CKO_PRIVATE_KEY:
1770 		private = key1;
1771 		break;
1772 	default:
1773 		return PKCS11_CKR_ATTRIBUTE_VALUE_INVALID;
1774 	}
1775 
1776 	if (key2) {
1777 		switch (get_class(key2)) {
1778 		case PKCS11_CKO_PUBLIC_KEY:
1779 			public = key2;
1780 			if (private == key1)
1781 				break;
1782 
1783 			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1784 		case PKCS11_CKO_PRIVATE_KEY:
1785 			private = key2;
1786 			if (public == key1)
1787 				break;
1788 
1789 			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1790 		default:
1791 			return PKCS11_CKR_ATTRIBUTE_VALUE_INVALID;
1792 		}
1793 
1794 		if (get_key_type(private) != get_key_type(public))
1795 			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1796 	}
1797 
1798 	if (secret) {
1799 		switch (get_key_type(secret)) {
1800 		case PKCS11_CKK_AES:
1801 		case PKCS11_CKK_GENERIC_SECRET:
1802 		case PKCS11_CKK_MD5_HMAC:
1803 		case PKCS11_CKK_SHA_1_HMAC:
1804 		case PKCS11_CKK_SHA224_HMAC:
1805 		case PKCS11_CKK_SHA256_HMAC:
1806 		case PKCS11_CKK_SHA384_HMAC:
1807 		case PKCS11_CKK_SHA512_HMAC:
1808 			break;
1809 		default:
1810 			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1811 		}
1812 
1813 		/* Get key size */
1814 		rc = get_u32_attribute(secret, PKCS11_CKA_VALUE_LEN,
1815 				       &key_length);
1816 		if (rc)
1817 			return PKCS11_CKR_TEMPLATE_INCOMPLETE;
1818 	}
1819 	if (public) {
1820 		switch (get_key_type(public)) {
1821 		case PKCS11_CKK_RSA:
1822 			/* Get key size */
1823 			rc = get_u32_attribute(public, PKCS11_CKA_MODULUS_BITS,
1824 					       &key_length);
1825 			if (rc)
1826 				return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1827 			key_length = ROUNDUP(key_length, 8) / 8;
1828 			break;
1829 		case PKCS11_CKK_EC:
1830 		case PKCS11_CKK_EC_EDWARDS:
1831 			break;
1832 		default:
1833 			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1834 		}
1835 	}
1836 	if (private) {
1837 		switch (get_key_type(private)) {
1838 		case PKCS11_CKK_RSA:
1839 		case PKCS11_CKK_EC:
1840 		case PKCS11_CKK_EC_EDWARDS:
1841 			break;
1842 		default:
1843 			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1844 		}
1845 	}
1846 
1847 	/*
1848 	 * Check key size for symmetric keys and RSA keys
1849 	 * EC is bound to domains, no need to check here.
1850 	 */
1851 	switch (get_key_type(key1)) {
1852 	case PKCS11_CKK_EC:
1853 	case PKCS11_CKK_EC_EDWARDS:
1854 		return PKCS11_CKR_OK;
1855 	default:
1856 		break;
1857 	}
1858 
1859 	get_key_min_max_sizes(get_key_type(key1), &min_key_size, &max_key_size);
1860 	if (key_length < min_key_size || key_length > max_key_size) {
1861 		EMSG("Length %"PRIu32" vs range [%"PRIu32" %"PRIu32"]",
1862 		     key_length, min_key_size, max_key_size);
1863 
1864 		return PKCS11_CKR_KEY_SIZE_RANGE;
1865 	}
1866 
1867 	if (secret && get_key_type(secret) == PKCS11_CKK_AES) {
1868 		if (key_length != 16 && key_length != 24 && key_length != 32)
1869 			return PKCS11_CKR_KEY_SIZE_RANGE;
1870 	}
1871 
1872 	return PKCS11_CKR_OK;
1873 }
1874 
1875 /* Check processing ID against attribute ALLOWED_MECHANISMS if any */
1876 static bool parent_key_complies_allowed_processings(uint32_t proc_id,
1877 						    struct obj_attrs *head)
1878 {
1879 	char *attr = NULL;
1880 	uint32_t size = 0;
1881 	uint32_t proc = 0;
1882 	size_t count = 0;
1883 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
1884 
1885 	rc = get_attribute_ptr(head, PKCS11_CKA_ALLOWED_MECHANISMS,
1886 			       (void *)&attr, &size);
1887 	if (rc == PKCS11_RV_NOT_FOUND)
1888 		return true;
1889 	if (rc) {
1890 		EMSG("unexpected attributes state");
1891 		TEE_Panic(TEE_ERROR_BAD_STATE);
1892 	}
1893 
1894 	for (count = size / sizeof(uint32_t); count; count--) {
1895 		TEE_MemMove(&proc, attr, sizeof(uint32_t));
1896 		attr += sizeof(uint32_t);
1897 
1898 		if (proc == proc_id)
1899 			return true;
1900 	}
1901 
1902 	DMSG("can't find %s in allowed list", id2str_proc(proc_id));
1903 	return false;
1904 }
1905 
1906 static enum pkcs11_attr_id func_to_attr(enum processing_func func)
1907 {
1908 	switch (func) {
1909 	case PKCS11_FUNCTION_ENCRYPT:
1910 		return PKCS11_CKA_ENCRYPT;
1911 	case PKCS11_FUNCTION_DECRYPT:
1912 		return PKCS11_CKA_DECRYPT;
1913 	case PKCS11_FUNCTION_SIGN:
1914 		return PKCS11_CKA_SIGN;
1915 	case PKCS11_FUNCTION_VERIFY:
1916 		return PKCS11_CKA_VERIFY;
1917 	case PKCS11_FUNCTION_WRAP:
1918 		return PKCS11_CKA_WRAP;
1919 	case PKCS11_FUNCTION_UNWRAP:
1920 		return PKCS11_CKA_UNWRAP;
1921 	case PKCS11_FUNCTION_DERIVE:
1922 		return PKCS11_CKA_DERIVE;
1923 	default:
1924 		return PKCS11_CKA_UNDEFINED_ID;
1925 	}
1926 }
1927 
1928 enum pkcs11_rc
1929 check_parent_attrs_against_processing(enum pkcs11_mechanism_id proc_id,
1930 				      enum processing_func function,
1931 				      struct obj_attrs *head)
1932 {
1933 	enum pkcs11_class_id key_class = get_class(head);
1934 	enum pkcs11_key_type key_type = get_key_type(head);
1935 	enum pkcs11_attr_id attr = func_to_attr(function);
1936 
1937 	if (!get_bool(head, attr)) {
1938 		DMSG("%s not permitted", id2str_attr(attr));
1939 		return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1940 	}
1941 
1942 	/* Check processing complies with parent key family */
1943 	switch (proc_id) {
1944 	case PKCS11_CKM_AES_ECB:
1945 	case PKCS11_CKM_AES_CBC:
1946 	case PKCS11_CKM_AES_CTS:
1947 	case PKCS11_CKM_AES_CTR:
1948 	case PKCS11_CKM_AES_GCM:
1949 	case PKCS11_CKM_AES_CMAC:
1950 	case PKCS11_CKM_AES_CMAC_GENERAL:
1951 		if (key_class == PKCS11_CKO_SECRET_KEY &&
1952 		    key_type == PKCS11_CKK_AES)
1953 			break;
1954 
1955 		DMSG("%s invalid key %s/%s", id2str_proc(proc_id),
1956 		     id2str_class(key_class), id2str_key_type(key_type));
1957 
1958 		if (function == PKCS11_FUNCTION_WRAP)
1959 			return PKCS11_CKR_WRAPPING_KEY_TYPE_INCONSISTENT;
1960 		else if (function == PKCS11_FUNCTION_UNWRAP)
1961 			return PKCS11_CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT;
1962 		else
1963 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1964 
1965 	case PKCS11_CKM_AES_ECB_ENCRYPT_DATA:
1966 	case PKCS11_CKM_AES_CBC_ENCRYPT_DATA:
1967 		if (key_class != PKCS11_CKO_SECRET_KEY &&
1968 		    key_type != PKCS11_CKK_AES)
1969 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1970 
1971 		if (get_bool(head, PKCS11_CKA_ENCRYPT)) {
1972 			/*
1973 			 * Intentionally refuse to proceed despite
1974 			 * PKCS#11 specifications v2.40 and v3.0 not expecting
1975 			 * this behavior to avoid potential security issue
1976 			 * where keys derived by these mechanisms can be
1977 			 * revealed by doing data encryption using parent key.
1978 			 */
1979 			return PKCS11_CKR_FUNCTION_FAILED;
1980 		}
1981 
1982 		break;
1983 	case PKCS11_CKM_MD5_HMAC:
1984 	case PKCS11_CKM_SHA_1_HMAC:
1985 	case PKCS11_CKM_SHA224_HMAC:
1986 	case PKCS11_CKM_SHA256_HMAC:
1987 	case PKCS11_CKM_SHA384_HMAC:
1988 	case PKCS11_CKM_SHA512_HMAC:
1989 	case PKCS11_CKM_MD5_HMAC_GENERAL:
1990 	case PKCS11_CKM_SHA_1_HMAC_GENERAL:
1991 	case PKCS11_CKM_SHA224_HMAC_GENERAL:
1992 	case PKCS11_CKM_SHA256_HMAC_GENERAL:
1993 	case PKCS11_CKM_SHA384_HMAC_GENERAL:
1994 	case PKCS11_CKM_SHA512_HMAC_GENERAL:
1995 		if (key_class != PKCS11_CKO_SECRET_KEY)
1996 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1997 
1998 		if (key_type == PKCS11_CKK_GENERIC_SECRET)
1999 			break;
2000 
2001 		switch (proc_id) {
2002 		case PKCS11_CKM_MD5_HMAC:
2003 		case PKCS11_CKM_MD5_HMAC_GENERAL:
2004 			if (key_type == PKCS11_CKK_MD5_HMAC)
2005 				break;
2006 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
2007 		case PKCS11_CKM_SHA_1_HMAC:
2008 		case PKCS11_CKM_SHA_1_HMAC_GENERAL:
2009 			if (key_type == PKCS11_CKK_SHA_1_HMAC)
2010 				break;
2011 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
2012 		case PKCS11_CKM_SHA224_HMAC:
2013 		case PKCS11_CKM_SHA224_HMAC_GENERAL:
2014 			if (key_type == PKCS11_CKK_SHA224_HMAC)
2015 				break;
2016 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
2017 		case PKCS11_CKM_SHA256_HMAC:
2018 		case PKCS11_CKM_SHA256_HMAC_GENERAL:
2019 			if (key_type == PKCS11_CKK_SHA256_HMAC)
2020 				break;
2021 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
2022 		case PKCS11_CKM_SHA384_HMAC:
2023 		case PKCS11_CKM_SHA384_HMAC_GENERAL:
2024 			if (key_type == PKCS11_CKK_SHA384_HMAC)
2025 				break;
2026 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
2027 		case PKCS11_CKM_SHA512_HMAC:
2028 		case PKCS11_CKM_SHA512_HMAC_GENERAL:
2029 			if (key_type == PKCS11_CKK_SHA512_HMAC)
2030 				break;
2031 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
2032 		default:
2033 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
2034 		}
2035 		break;
2036 
2037 	case PKCS11_CKM_EDDSA:
2038 		if (key_type != PKCS11_CKK_EC_EDWARDS) {
2039 			EMSG("Invalid key %s for mechanism %s",
2040 			     id2str_type(key_type, key_class),
2041 			     id2str_proc(proc_id));
2042 			return PKCS11_CKR_KEY_TYPE_INCONSISTENT;
2043 		}
2044 		if (key_class != PKCS11_CKO_PUBLIC_KEY &&
2045 		    key_class != PKCS11_CKO_PRIVATE_KEY) {
2046 			EMSG("Invalid key class for mechanism %s",
2047 			     id2str_proc(proc_id));
2048 
2049 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
2050 		}
2051 		break;
2052 
2053 	case PKCS11_CKM_ECDSA:
2054 	case PKCS11_CKM_ECDSA_SHA1:
2055 	case PKCS11_CKM_ECDSA_SHA224:
2056 	case PKCS11_CKM_ECDSA_SHA256:
2057 	case PKCS11_CKM_ECDSA_SHA384:
2058 	case PKCS11_CKM_ECDSA_SHA512:
2059 	case PKCS11_CKM_ECDH1_DERIVE:
2060 		if (key_type != PKCS11_CKK_EC) {
2061 			EMSG("Invalid key %s for mechanism %s",
2062 			     id2str_type(key_type, key_class),
2063 			     id2str_proc(proc_id));
2064 
2065 			return PKCS11_CKR_KEY_TYPE_INCONSISTENT;
2066 		}
2067 		if (key_class != PKCS11_CKO_PUBLIC_KEY &&
2068 		    key_class != PKCS11_CKO_PRIVATE_KEY) {
2069 			EMSG("Invalid key class for mechanism %s",
2070 			     id2str_proc(proc_id));
2071 
2072 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
2073 		}
2074 		break;
2075 	case PKCS11_CKM_RSA_PKCS:
2076 	case PKCS11_CKM_MD5_RSA_PKCS:
2077 	case PKCS11_CKM_SHA1_RSA_PKCS:
2078 	case PKCS11_CKM_SHA224_RSA_PKCS:
2079 	case PKCS11_CKM_SHA256_RSA_PKCS:
2080 	case PKCS11_CKM_SHA384_RSA_PKCS:
2081 	case PKCS11_CKM_SHA512_RSA_PKCS:
2082 	case PKCS11_CKM_RSA_AES_KEY_WRAP:
2083 	case PKCS11_CKM_RSA_PKCS_OAEP:
2084 	case PKCS11_CKM_RSA_PKCS_PSS:
2085 	case PKCS11_CKM_SHA1_RSA_PKCS_PSS:
2086 	case PKCS11_CKM_SHA224_RSA_PKCS_PSS:
2087 	case PKCS11_CKM_SHA256_RSA_PKCS_PSS:
2088 	case PKCS11_CKM_SHA384_RSA_PKCS_PSS:
2089 	case PKCS11_CKM_SHA512_RSA_PKCS_PSS:
2090 		if (key_type != PKCS11_CKK_RSA) {
2091 			EMSG("Invalid key %s for mechanism %s",
2092 			     id2str_type(key_type, key_class),
2093 			     id2str_proc(proc_id));
2094 
2095 			return PKCS11_CKR_KEY_TYPE_INCONSISTENT;
2096 		}
2097 		if (key_class != PKCS11_CKO_PUBLIC_KEY &&
2098 		    key_class != PKCS11_CKO_PRIVATE_KEY) {
2099 			EMSG("Invalid key class for mechanism %s",
2100 			     id2str_proc(proc_id));
2101 
2102 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
2103 		}
2104 		break;
2105 	default:
2106 		DMSG("Invalid processing %#"PRIx32"/%s", proc_id,
2107 		     id2str_proc(proc_id));
2108 
2109 		return PKCS11_CKR_MECHANISM_INVALID;
2110 	}
2111 
2112 	if (!parent_key_complies_allowed_processings(proc_id, head)) {
2113 		DMSG("Allowed mechanism failed");
2114 		return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
2115 	}
2116 
2117 	return PKCS11_CKR_OK;
2118 }
2119 
2120 bool attribute_is_exportable(struct pkcs11_attribute_head *req_attr,
2121 			     struct pkcs11_object *obj)
2122 {
2123 	uint8_t boolval = 0;
2124 	uint32_t boolsize = 0;
2125 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2126 	enum pkcs11_class_id key_class = get_class(obj->attributes);
2127 
2128 	if (attribute_is_hidden(req_attr))
2129 		return false;
2130 
2131 	if (key_class != PKCS11_CKO_SECRET_KEY &&
2132 	    key_class != PKCS11_CKO_PRIVATE_KEY)
2133 		return true;
2134 
2135 	switch (req_attr->id) {
2136 	case PKCS11_CKA_PRIVATE_EXPONENT:
2137 	case PKCS11_CKA_PRIME_1:
2138 	case PKCS11_CKA_PRIME_2:
2139 	case PKCS11_CKA_EXPONENT_1:
2140 	case PKCS11_CKA_EXPONENT_2:
2141 	case PKCS11_CKA_COEFFICIENT:
2142 	case PKCS11_CKA_VALUE:
2143 		boolsize = sizeof(boolval);
2144 		rc = get_attribute(obj->attributes, PKCS11_CKA_EXTRACTABLE,
2145 				   &boolval, &boolsize);
2146 		if (rc || boolval == PKCS11_FALSE)
2147 			return false;
2148 
2149 		boolsize = sizeof(boolval);
2150 		rc = get_attribute(obj->attributes, PKCS11_CKA_SENSITIVE,
2151 				   &boolval, &boolsize);
2152 		if (rc || boolval == PKCS11_TRUE)
2153 			return false;
2154 		break;
2155 	default:
2156 		break;
2157 	}
2158 
2159 	return true;
2160 }
2161 
2162 static bool attr_is_modifiable_any_key(struct pkcs11_attribute_head *attr)
2163 {
2164 	switch (attr->id) {
2165 	case PKCS11_CKA_ID:
2166 	case PKCS11_CKA_START_DATE:
2167 	case PKCS11_CKA_END_DATE:
2168 	case PKCS11_CKA_DERIVE:
2169 		return true;
2170 	default:
2171 		return false;
2172 	}
2173 }
2174 
2175 static bool attr_is_modifiable_secret_key(struct pkcs11_attribute_head *attr,
2176 					  struct pkcs11_session *session,
2177 					  struct pkcs11_object *obj)
2178 {
2179 	switch (attr->id) {
2180 	case PKCS11_CKA_ENCRYPT:
2181 	case PKCS11_CKA_DECRYPT:
2182 	case PKCS11_CKA_SIGN:
2183 	case PKCS11_CKA_VERIFY:
2184 	case PKCS11_CKA_WRAP:
2185 	case PKCS11_CKA_UNWRAP:
2186 	case PKCS11_CKA_CHECK_VALUE:
2187 		return true;
2188 	/* Can't be modified once set to CK_FALSE - 12 in Table 10 */
2189 	case PKCS11_CKA_EXTRACTABLE:
2190 		return get_bool(obj->attributes, attr->id);
2191 	/* Can't be modified once set to CK_TRUE - 11 in Table 10 */
2192 	case PKCS11_CKA_SENSITIVE:
2193 	case PKCS11_CKA_WRAP_WITH_TRUSTED:
2194 		return !get_bool(obj->attributes, attr->id);
2195 	/* Change in CKA_TRUSTED can only be done by SO */
2196 	case PKCS11_CKA_TRUSTED:
2197 		return pkcs11_session_is_so(session);
2198 	case PKCS11_CKA_NEVER_EXTRACTABLE:
2199 	case PKCS11_CKA_ALWAYS_SENSITIVE:
2200 		return false;
2201 	default:
2202 		return false;
2203 	}
2204 }
2205 
2206 static bool attr_is_modifiable_public_key(struct pkcs11_attribute_head *attr,
2207 					  struct pkcs11_session *session,
2208 					  struct pkcs11_object *obj __unused)
2209 {
2210 	switch (attr->id) {
2211 	case PKCS11_CKA_SUBJECT:
2212 	case PKCS11_CKA_ENCRYPT:
2213 	case PKCS11_CKA_VERIFY:
2214 	case PKCS11_CKA_VERIFY_RECOVER:
2215 	case PKCS11_CKA_WRAP:
2216 		return true;
2217 	case PKCS11_CKA_TRUSTED:
2218 		/* Change in CKA_TRUSTED can only be done by SO */
2219 		return pkcs11_session_is_so(session);
2220 	default:
2221 		return false;
2222 	}
2223 }
2224 
2225 static bool attr_is_modifiable_private_key(struct pkcs11_attribute_head *attr,
2226 					   struct pkcs11_session *sess __unused,
2227 					   struct pkcs11_object *obj)
2228 {
2229 	switch (attr->id) {
2230 	case PKCS11_CKA_SUBJECT:
2231 	case PKCS11_CKA_DECRYPT:
2232 	case PKCS11_CKA_SIGN:
2233 	case PKCS11_CKA_SIGN_RECOVER:
2234 	case PKCS11_CKA_UNWRAP:
2235 	/*
2236 	 * TBD: Revisit if we don't support PKCS11_CKA_PUBLIC_KEY_INFO
2237 	 * Specification mentions that if this attribute is
2238 	 * supplied as part of a template for C_CreateObject, C_CopyObject or
2239 	 * C_SetAttributeValue for a private key, the token MUST verify
2240 	 * correspondence between the private key data and the public key data
2241 	 * as supplied in CKA_PUBLIC_KEY_INFO. This needs to be
2242 	 * taken care of when this object type will be implemented
2243 	 */
2244 	case PKCS11_CKA_PUBLIC_KEY_INFO:
2245 		return true;
2246 	/* Can't be modified once set to CK_FALSE - 12 in Table 10 */
2247 	case PKCS11_CKA_EXTRACTABLE:
2248 		return get_bool(obj->attributes, attr->id);
2249 	/* Can't be modified once set to CK_TRUE - 11 in Table 10 */
2250 	case PKCS11_CKA_SENSITIVE:
2251 	case PKCS11_CKA_WRAP_WITH_TRUSTED:
2252 		return !get_bool(obj->attributes, attr->id);
2253 	case PKCS11_CKA_NEVER_EXTRACTABLE:
2254 	case PKCS11_CKA_ALWAYS_SENSITIVE:
2255 		return false;
2256 	default:
2257 		return false;
2258 	}
2259 }
2260 
2261 static bool attr_is_modifiable_certificate(struct pkcs11_attribute_head *attr,
2262 					   struct pkcs11_session *session,
2263 					   struct pkcs11_object *obj)
2264 {
2265 	uint8_t boolval = 0;
2266 	uint32_t boolsize = 0;
2267 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2268 
2269 	/* Trusted certificates cannot be modified. */
2270 	rc = get_attribute(obj->attributes, PKCS11_CKA_TRUSTED,
2271 			   &boolval, &boolsize);
2272 	if (rc || boolval == PKCS11_TRUE)
2273 		return false;
2274 
2275 	/* Common certificate attributes */
2276 	switch (attr->id) {
2277 	case PKCS11_CKA_TRUSTED:
2278 		/*
2279 		 * The CKA_TRUSTED attribute cannot be set to CK_TRUE by an
2280 		 * application. It MUST be set by a token initialization
2281 		 * application or by the token’s SO.
2282 		 */
2283 		return pkcs11_session_is_so(session);
2284 	case PKCS11_CKA_CERTIFICATE_TYPE:
2285 	case PKCS11_CKA_CERTIFICATE_CATEGORY:
2286 		return false;
2287 	default:
2288 		break;
2289 	}
2290 
2291 	/* Certificate type specific attributes */
2292 	switch (get_certificate_type(obj->attributes)) {
2293 	case PKCS11_CKC_X_509:
2294 		/*
2295 		 * Only the CKA_ID, CKA_ISSUER, and CKA_SERIAL_NUMBER
2296 		 * attributes may be modified after the object is created.
2297 		 */
2298 		switch (attr->id) {
2299 		case PKCS11_CKA_ID:
2300 		case PKCS11_CKA_ISSUER:
2301 		case PKCS11_CKA_SERIAL_NUMBER:
2302 			return true;
2303 		default:
2304 			break;
2305 		}
2306 		break;
2307 	default:
2308 		/* Unsupported certificate type */
2309 		break;
2310 	}
2311 
2312 	return false;
2313 }
2314 
2315 static bool attribute_is_modifiable(struct pkcs11_session *session,
2316 				    struct pkcs11_attribute_head *req_attr,
2317 				    struct pkcs11_object *obj,
2318 				    enum pkcs11_class_id class,
2319 				    enum processing_func function)
2320 {
2321 	/* Check modifiable attributes common to any object */
2322 	switch (req_attr->id) {
2323 	case PKCS11_CKA_LABEL:
2324 		return true;
2325 	case PKCS11_CKA_TOKEN:
2326 	case PKCS11_CKA_MODIFIABLE:
2327 	case PKCS11_CKA_DESTROYABLE:
2328 	case PKCS11_CKA_PRIVATE:
2329 		return function == PKCS11_FUNCTION_COPY;
2330 	case PKCS11_CKA_COPYABLE:
2331 		/*
2332 		 * Specification mentions that if the attribute value is false
2333 		 * it can't be set to true. Reading this we assume that it
2334 		 * should be possible to modify this attribute even though this
2335 		 * is not marked as modifiable in Table 10 if done in right
2336 		 * direction i.e from TRUE -> FALSE.
2337 		 */
2338 		return get_bool(obj->attributes, req_attr->id);
2339 	default:
2340 		break;
2341 	}
2342 
2343 	/* Attribute checking based on class type */
2344 	switch (class) {
2345 	case PKCS11_CKO_SECRET_KEY:
2346 	case PKCS11_CKO_PUBLIC_KEY:
2347 	case PKCS11_CKO_PRIVATE_KEY:
2348 		if (attr_is_modifiable_any_key(req_attr))
2349 			return true;
2350 		if (class == PKCS11_CKO_SECRET_KEY &&
2351 		    attr_is_modifiable_secret_key(req_attr, session, obj))
2352 			return true;
2353 		if (class == PKCS11_CKO_PUBLIC_KEY &&
2354 		    attr_is_modifiable_public_key(req_attr, session, obj))
2355 			return true;
2356 		if (class == PKCS11_CKO_PRIVATE_KEY &&
2357 		    attr_is_modifiable_private_key(req_attr, session, obj))
2358 			return true;
2359 		break;
2360 	case PKCS11_CKO_DATA:
2361 		/* None of the data object attributes are modifiable */
2362 		return false;
2363 	case PKCS11_CKO_CERTIFICATE:
2364 		return attr_is_modifiable_certificate(req_attr, session, obj);
2365 	default:
2366 		break;
2367 	}
2368 
2369 	return false;
2370 }
2371 
2372 enum pkcs11_rc check_attrs_against_modification(struct pkcs11_session *session,
2373 						struct obj_attrs *head,
2374 						struct pkcs11_object *obj,
2375 						enum processing_func function)
2376 {
2377 	enum pkcs11_class_id class = PKCS11_CKO_UNDEFINED_ID;
2378 	char *cur = NULL;
2379 	char *end = NULL;
2380 	size_t len = 0;
2381 
2382 	class = get_class(obj->attributes);
2383 
2384 	cur = (char *)head + sizeof(struct obj_attrs);
2385 	end = cur + head->attrs_size;
2386 
2387 	for (; cur < end; cur += len) {
2388 		/* Structure aligned copy of the pkcs11_ref in the object */
2389 		struct pkcs11_attribute_head cli_ref = { };
2390 
2391 		TEE_MemMove(&cli_ref, cur, sizeof(cli_ref));
2392 		len = sizeof(cli_ref) + cli_ref.size;
2393 
2394 		/* Protect hidden attributes */
2395 		if (attribute_is_hidden(&cli_ref))
2396 			return PKCS11_CKR_ATTRIBUTE_TYPE_INVALID;
2397 
2398 		/*
2399 		 * Check 1 - Check if attribute belongs to the object
2400 		 * The obj->attributes has all the attributes in
2401 		 * it which are allowed for an object.
2402 		 */
2403 		if (get_attribute_ptr(obj->attributes, cli_ref.id, NULL,
2404 				      NULL) == PKCS11_RV_NOT_FOUND)
2405 			return PKCS11_CKR_ATTRIBUTE_TYPE_INVALID;
2406 
2407 		/* Check 2 - Is attribute modifiable */
2408 		if (!attribute_is_modifiable(session, &cli_ref, obj, class,
2409 					     function))
2410 			return PKCS11_CKR_ATTRIBUTE_READ_ONLY;
2411 
2412 		/*
2413 		 * Checks for modification in PKCS11_CKA_TOKEN and
2414 		 * PKCS11_CKA_PRIVATE are required for PKCS11_FUNCTION_COPY
2415 		 * only, so skip them for PKCS11_FUNCTION_MODIFY.
2416 		 */
2417 		if (function == PKCS11_FUNCTION_MODIFY)
2418 			continue;
2419 
2420 		/*
2421 		 * An attempt to copy an object to a token will fail for
2422 		 * RO session
2423 		 */
2424 		if (cli_ref.id == PKCS11_CKA_TOKEN &&
2425 		    get_bool(head, PKCS11_CKA_TOKEN)) {
2426 			if (!pkcs11_session_is_read_write(session)) {
2427 				DMSG("Can't copy to token in a RO session");
2428 				return PKCS11_CKR_SESSION_READ_ONLY;
2429 			}
2430 		}
2431 
2432 		if (cli_ref.id == PKCS11_CKA_PRIVATE) {
2433 			bool parent_priv =
2434 				get_bool(obj->attributes, cli_ref.id);
2435 			bool obj_priv = get_bool(head, cli_ref.id);
2436 
2437 			/*
2438 			 * If PKCS11_CKA_PRIVATE is being set to TRUE from
2439 			 * FALSE, user has to be logged in
2440 			 */
2441 			if (!parent_priv && obj_priv) {
2442 				if ((pkcs11_session_is_public(session) ||
2443 				     pkcs11_session_is_so(session)))
2444 					return PKCS11_CKR_USER_NOT_LOGGED_IN;
2445 			}
2446 
2447 			/*
2448 			 * Restriction added - Even for Copy, do not allow
2449 			 * modification of CKA_PRIVATE from TRUE to FALSE
2450 			 */
2451 			if (parent_priv && !obj_priv)
2452 				return PKCS11_CKR_TEMPLATE_INCONSISTENT;
2453 		}
2454 	}
2455 
2456 	return PKCS11_CKR_OK;
2457 }
2458 
2459 static enum pkcs11_rc set_secret_key_data(struct obj_attrs **head, void *data,
2460 					  size_t key_size)
2461 {
2462 	uint32_t size = sizeof(uint32_t);
2463 	uint32_t key_length = 0;
2464 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2465 
2466 	/* Get key size if present in template */
2467 	rc = get_attribute(*head, PKCS11_CKA_VALUE_LEN, &key_length, &size);
2468 	if (rc && rc != PKCS11_RV_NOT_FOUND)
2469 		return rc;
2470 
2471 	if (key_length) {
2472 		if (key_size < key_length)
2473 			return PKCS11_CKR_DATA_LEN_RANGE;
2474 	} else {
2475 		key_length = key_size;
2476 		rc = set_attribute(head, PKCS11_CKA_VALUE_LEN, &key_length,
2477 				   sizeof(uint32_t));
2478 		if (rc)
2479 			return rc;
2480 	}
2481 
2482 	/* Now we can check the VALUE_LEN field */
2483 	rc = check_created_attrs(*head, NULL);
2484 	if (rc)
2485 		return rc;
2486 
2487 	/* Remove the default empty value attribute if found */
2488 	rc = remove_empty_attribute(head, PKCS11_CKA_VALUE);
2489 	if (rc != PKCS11_CKR_OK && rc != PKCS11_RV_NOT_FOUND)
2490 		return PKCS11_CKR_GENERAL_ERROR;
2491 
2492 	rc = add_attribute(head, PKCS11_CKA_VALUE, data, key_length);
2493 	if (rc)
2494 		return rc;
2495 
2496 	return set_check_value_attr(head);
2497 }
2498 
2499 static enum pkcs11_rc set_private_key_data_rsa(struct obj_attrs **head,
2500 					       void *data,
2501 					       size_t key_size)
2502 {
2503 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2504 	int mbedtls_rc = 0;
2505 	uint32_t key_bits = 0;
2506 	uint32_t size = 0;
2507 	uint32_t buffer_size = 0;
2508 	void *buffer = NULL;
2509 	mbedtls_pk_context pk = { };
2510 	mbedtls_rsa_context *rsa = NULL;
2511 	mbedtls_mpi n = { };
2512 	mbedtls_mpi e = { };
2513 	mbedtls_mpi d = { };
2514 	mbedtls_mpi p = { };
2515 	mbedtls_mpi q = { };
2516 
2517 	rc = get_u32_attribute(*head, PKCS11_CKA_MODULUS_BITS, &key_bits);
2518 	if (rc && rc != PKCS11_RV_NOT_FOUND)
2519 		return rc;
2520 
2521 	if (remove_empty_attribute(head, PKCS11_CKA_MODULUS) ||
2522 	    remove_empty_attribute(head, PKCS11_CKA_PUBLIC_EXPONENT) ||
2523 	    remove_empty_attribute(head, PKCS11_CKA_PRIVATE_EXPONENT) ||
2524 	    remove_empty_attribute(head, PKCS11_CKA_PRIME_1) ||
2525 	    remove_empty_attribute(head, PKCS11_CKA_PRIME_2))
2526 		return PKCS11_CKR_GENERAL_ERROR;
2527 
2528 	mbedtls_pk_init(&pk);
2529 	mbedtls_mpi_init(&n);
2530 	mbedtls_mpi_init(&e);
2531 	mbedtls_mpi_init(&d);
2532 	mbedtls_mpi_init(&p);
2533 	mbedtls_mpi_init(&q);
2534 
2535 	mbedtls_rc = mbedtls_pk_parse_key(&pk, data, key_size,
2536 					  NULL, 0, mbd_rand, NULL);
2537 	if (mbedtls_rc) {
2538 		rc = PKCS11_CKR_ARGUMENTS_BAD;
2539 		goto out;
2540 	}
2541 
2542 	rsa = mbedtls_pk_rsa(pk);
2543 	if (!rsa) {
2544 		rc = PKCS11_CKR_GENERAL_ERROR;
2545 		goto out;
2546 	}
2547 
2548 	mbedtls_rc = mbedtls_rsa_export(rsa, &n, &p, &q, &d, &e);
2549 	if (mbedtls_rc) {
2550 		rc = PKCS11_CKR_ARGUMENTS_BAD;
2551 		goto out;
2552 	}
2553 
2554 	if (key_bits && mbedtls_mpi_bitlen(&n) != key_bits) {
2555 		rc = PKCS11_CKR_WRAPPED_KEY_LEN_RANGE;
2556 		goto out;
2557 	}
2558 
2559 	size = ROUNDUP_DIV(mbedtls_mpi_bitlen(&n), 8);
2560 	buffer_size = size;
2561 	buffer = TEE_Malloc(buffer_size, TEE_USER_MEM_HINT_NO_FILL_ZERO);
2562 	if (!buffer) {
2563 		rc = PKCS11_CKR_DEVICE_MEMORY;
2564 		goto out;
2565 	}
2566 
2567 	mbedtls_rc = mbedtls_mpi_write_binary(&n, buffer, size);
2568 	if (mbedtls_rc) {
2569 		rc = PKCS11_CKR_WRAPPED_KEY_INVALID;
2570 		goto out;
2571 	}
2572 
2573 	rc = add_attribute(head, PKCS11_CKA_MODULUS, buffer, size);
2574 	if (rc)
2575 		goto out;
2576 
2577 	size = ROUNDUP_DIV(mbedtls_mpi_bitlen(&e), 8);
2578 	if (buffer_size < size) {
2579 		rc = PKCS11_CKR_WRAPPED_KEY_LEN_RANGE;
2580 		goto out;
2581 	}
2582 
2583 	mbedtls_rc = mbedtls_mpi_write_binary(&e, buffer, size);
2584 	if (mbedtls_rc) {
2585 		rc = PKCS11_CKR_WRAPPED_KEY_INVALID;
2586 		goto out;
2587 	}
2588 
2589 	rc = add_attribute(head, PKCS11_CKA_PUBLIC_EXPONENT, buffer, size);
2590 	if (rc)
2591 		goto out;
2592 
2593 	size = ROUNDUP_DIV(mbedtls_mpi_bitlen(&d), 8);
2594 	if (buffer_size < size) {
2595 		rc = PKCS11_CKR_WRAPPED_KEY_LEN_RANGE;
2596 		goto out;
2597 	}
2598 
2599 	mbedtls_rc = mbedtls_mpi_write_binary(&d, buffer, size);
2600 	if (mbedtls_rc) {
2601 		rc = PKCS11_CKR_WRAPPED_KEY_INVALID;
2602 		goto out;
2603 	}
2604 
2605 	rc = add_attribute(head, PKCS11_CKA_PRIVATE_EXPONENT, buffer, size);
2606 	if (rc)
2607 		goto out;
2608 
2609 	size = ROUNDUP_DIV(mbedtls_mpi_bitlen(&p), 8);
2610 	if (buffer_size < size) {
2611 		rc = PKCS11_CKR_WRAPPED_KEY_LEN_RANGE;
2612 		goto out;
2613 	}
2614 
2615 	mbedtls_rc = mbedtls_mpi_write_binary(&p, buffer, size);
2616 	if (mbedtls_rc) {
2617 		rc = PKCS11_CKR_WRAPPED_KEY_INVALID;
2618 		goto out;
2619 	}
2620 
2621 	rc = add_attribute(head, PKCS11_CKA_PRIME_1, buffer, size);
2622 	if (rc)
2623 		goto out;
2624 
2625 	size = ROUNDUP_DIV(mbedtls_mpi_bitlen(&q), 8);
2626 	if (buffer_size < size) {
2627 		rc = PKCS11_CKR_WRAPPED_KEY_LEN_RANGE;
2628 		goto out;
2629 	}
2630 
2631 	mbedtls_rc = mbedtls_mpi_write_binary(&q, buffer, size);
2632 	if (mbedtls_rc) {
2633 		rc = PKCS11_CKR_WRAPPED_KEY_INVALID;
2634 		goto out;
2635 	}
2636 
2637 	rc = add_attribute(head, PKCS11_CKA_PRIME_2, buffer, size);
2638 
2639 out:
2640 	mbedtls_pk_free(&pk);
2641 	mbedtls_mpi_free(&n);
2642 	mbedtls_mpi_free(&e);
2643 	mbedtls_mpi_free(&d);
2644 	mbedtls_mpi_free(&p);
2645 	mbedtls_mpi_free(&q);
2646 	TEE_Free(buffer);
2647 	return rc;
2648 }
2649 
2650 enum pkcs11_rc set_key_data(struct obj_attrs **head, void *data,
2651 			    size_t key_size)
2652 {
2653 	switch (get_class(*head)) {
2654 	case PKCS11_CKO_SECRET_KEY:
2655 		return set_secret_key_data(head, data, key_size);
2656 	case PKCS11_CKO_PRIVATE_KEY:
2657 		if (get_key_type(*head) == PKCS11_CKK_RSA)
2658 			return set_private_key_data_rsa(head, data, key_size);
2659 		break;
2660 	default:
2661 		return PKCS11_CKR_GENERAL_ERROR;
2662 	}
2663 
2664 	return PKCS11_CKR_GENERAL_ERROR;
2665 }
2666 
2667 static enum pkcs11_rc alloc_copy_attribute_value(struct obj_attrs *head,
2668 						 void **data, uint32_t *sz)
2669 {
2670 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2671 	void *buffer = NULL;
2672 	void *value = NULL;
2673 
2674 	rc = get_attribute_ptr(head, PKCS11_CKA_VALUE, &value, sz);
2675 	if (rc)
2676 		return PKCS11_CKR_ARGUMENTS_BAD;
2677 
2678 	buffer = TEE_Malloc(*sz, TEE_USER_MEM_HINT_NO_FILL_ZERO);
2679 	if (!buffer)
2680 		return PKCS11_CKR_DEVICE_MEMORY;
2681 
2682 	TEE_MemMove(buffer, value, *sz);
2683 	*data = buffer;
2684 
2685 	return PKCS11_CKR_OK;
2686 }
2687 
2688 static enum pkcs11_rc
2689 encode_rsa_private_key_der(struct obj_attrs *head, void **data, uint32_t *sz)
2690 {
2691 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2692 	int i = 0;
2693 	int mbedtls_rc = 0;
2694 	int start = 0;
2695 	int der_size = 0;
2696 	void *n = NULL;
2697 	void *p = NULL;
2698 	void *q = NULL;
2699 	void *d = NULL;
2700 	void *e = NULL;
2701 	uint32_t n_len = 0;
2702 	uint32_t p_len = 0;
2703 	uint32_t q_len = 0;
2704 	uint32_t d_len = 0;
2705 	uint32_t e_len = 0;
2706 	uint8_t *buffer = NULL;
2707 	mbedtls_pk_context pk = { };
2708 	mbedtls_rsa_context *rsa = NULL;
2709 	const mbedtls_pk_info_t *pk_info = NULL;
2710 
2711 	mbedtls_pk_init(&pk);
2712 	pk_info = mbedtls_pk_info_from_type(MBEDTLS_PK_RSA);
2713 	if (mbedtls_pk_setup(&pk, pk_info)) {
2714 		rc = PKCS11_CKR_GENERAL_ERROR;
2715 		goto out;
2716 	}
2717 
2718 	rc = get_attribute_ptr(head, PKCS11_CKA_MODULUS, &n, &n_len);
2719 	if (rc)
2720 		goto out;
2721 
2722 	rc = get_attribute_ptr(head, PKCS11_CKA_PRIME_1, &p, &p_len);
2723 	if (rc)
2724 		goto out;
2725 
2726 	rc = get_attribute_ptr(head, PKCS11_CKA_PRIME_2, &q, &q_len);
2727 	if (rc)
2728 		goto out;
2729 
2730 	rc = get_attribute_ptr(head, PKCS11_CKA_PRIVATE_EXPONENT, &d, &d_len);
2731 	if (rc)
2732 		goto out;
2733 
2734 	rc = get_attribute_ptr(head, PKCS11_CKA_PUBLIC_EXPONENT, &e, &e_len);
2735 	if (rc)
2736 		goto out;
2737 
2738 	rsa = mbedtls_pk_rsa(pk);
2739 	if (!rsa) {
2740 		rc = PKCS11_CKR_GENERAL_ERROR;
2741 		goto out;
2742 	}
2743 
2744 	mbedtls_rc = mbedtls_rsa_import_raw(rsa, n, n_len, p, p_len,
2745 					    q, q_len, d, d_len, e, e_len);
2746 	if (mbedtls_rc) {
2747 		rc = PKCS11_CKR_ARGUMENTS_BAD;
2748 		goto out;
2749 	}
2750 
2751 	if (mbedtls_rsa_complete(rsa)) {
2752 		rc = PKCS11_CKR_ARGUMENTS_BAD;
2753 		goto out;
2754 	}
2755 
2756 	if (mbedtls_rsa_check_privkey(rsa)) {
2757 		rc = PKCS11_CKR_ARGUMENTS_BAD;
2758 		goto out;
2759 	}
2760 
2761 	der_size = n_len * 8;
2762 	buffer = TEE_Malloc(der_size, TEE_USER_MEM_HINT_NO_FILL_ZERO);
2763 	if (!buffer) {
2764 		rc = PKCS11_CKR_DEVICE_MEMORY;
2765 		goto out;
2766 	}
2767 
2768 	mbedtls_rc = mbedtls_pk_write_key_der(&pk, buffer, der_size);
2769 	if (mbedtls_rc < 0) {
2770 		rc = PKCS11_CKR_ARGUMENTS_BAD;
2771 		goto out;
2772 	}
2773 
2774 	start = der_size - mbedtls_rc;
2775 	for (i = 0; i < mbedtls_rc; i++) {
2776 		buffer[i] = buffer[i + start];
2777 		buffer[i + start] = 0;
2778 	}
2779 
2780 	*data = buffer;
2781 	*sz = mbedtls_rc;
2782 out:
2783 	mbedtls_pk_free(&pk);
2784 
2785 	if (rc)
2786 		TEE_Free(buffer);
2787 
2788 	return rc;
2789 }
2790 
2791 enum pkcs11_rc alloc_key_data_to_wrap(struct obj_attrs *head, void **data,
2792 				      uint32_t *sz)
2793 {
2794 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2795 
2796 	switch (get_class(head)) {
2797 	case PKCS11_CKO_SECRET_KEY:
2798 		rc = alloc_copy_attribute_value(head, data, sz);
2799 		break;
2800 	case PKCS11_CKO_PRIVATE_KEY:
2801 		if (get_key_type(head) == PKCS11_CKK_RSA)
2802 			rc = encode_rsa_private_key_der(head, data, sz);
2803 		break;
2804 	default:
2805 		break;
2806 	}
2807 
2808 	return rc;
2809 }
2810 
2811 enum pkcs11_rc add_missing_attribute_id(struct obj_attrs **pub_head,
2812 					struct obj_attrs **priv_head)
2813 {
2814 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2815 	void *id1 = NULL;
2816 	uint32_t id1_size = 0;
2817 	void *id2 = NULL;
2818 	uint32_t id2_size = 0;
2819 
2820 	assert(pub_head);
2821 	assert(priv_head);
2822 
2823 	rc = get_attribute_ptr(*pub_head, PKCS11_CKA_ID, &id1, &id1_size);
2824 	if (rc) {
2825 		if (rc != PKCS11_RV_NOT_FOUND)
2826 			return rc;
2827 		id1 = NULL;
2828 	} else if (!id1_size) {
2829 		id1 = NULL;
2830 	}
2831 
2832 	rc = get_attribute_ptr(*priv_head, PKCS11_CKA_ID, &id2, &id2_size);
2833 	if (rc) {
2834 		if (rc != PKCS11_RV_NOT_FOUND)
2835 			return rc;
2836 		id2 = NULL;
2837 	} else if (!id2_size) {
2838 		id2 = NULL;
2839 	}
2840 
2841 	/* Both have value -- let them be what caller has specified them */
2842 	if (id1 && id2)
2843 		return PKCS11_CKR_OK;
2844 
2845 	/* Both are empty -- leave empty values */
2846 	if (!id1 && !id2)
2847 		return PKCS11_CKR_OK;
2848 
2849 	/* Cross copy CKA_ID value */
2850 	if (id1)
2851 		return set_attribute(priv_head, PKCS11_CKA_ID, id1, id1_size);
2852 	else
2853 		return set_attribute(pub_head, PKCS11_CKA_ID, id2, id2_size);
2854 }
2855 
2856 /*
2857  * The key check value is derived from the object by taking the first
2858  * three bytes of the SHA-1 hash of the object's CKA_VALUE attribute.
2859  */
2860 static enum pkcs11_rc compute_check_value_with_sha1(void *key,
2861 						    uint32_t key_size,
2862 						    void *kcv)
2863 {
2864 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2865 	TEE_Result res = TEE_ERROR_GENERIC;
2866 	TEE_OperationHandle op = TEE_HANDLE_NULL;
2867 	size_t buf_size = TEE_MAX_HASH_SIZE;
2868 	uint8_t *buf = NULL;
2869 
2870 	assert(key && kcv);
2871 
2872 	res = TEE_AllocateOperation(&op, TEE_ALG_SHA1, TEE_MODE_DIGEST, 0);
2873 	rc = tee2pkcs_error(res);
2874 	if (rc != PKCS11_CKR_OK)
2875 		goto out;
2876 
2877 	buf = TEE_Malloc(buf_size, TEE_MALLOC_FILL_ZERO);
2878 	if (!buf) {
2879 		rc = PKCS11_CKR_DEVICE_MEMORY;
2880 		goto out;
2881 	}
2882 
2883 	res = TEE_DigestDoFinal(op, key, key_size, buf, &buf_size);
2884 	rc = tee2pkcs_error(res);
2885 	if (rc != PKCS11_CKR_OK)
2886 		goto out;
2887 
2888 	TEE_MemMove(kcv, buf, PKCS11_CKA_CHECK_VALUE_SIZE);
2889 
2890 out:
2891 	TEE_Free(buf);
2892 	TEE_FreeOperation(op);
2893 
2894 	return rc;
2895 }
2896 
2897 /*
2898  * The key check value that is calculated as follows:
2899  * 1) Take a buffer of the cipher block size of binary zeros (0x00).
2900  * 2) Encrypt this block in ECB mode.
2901  * 3) Take the first three bytes of cipher text as the check value.
2902  */
2903 static enum pkcs11_rc compute_check_value_with_ecb(void *key, uint32_t key_size,
2904 						   void *kcv)
2905 {
2906 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2907 	TEE_Result res = TEE_ERROR_GENERIC;
2908 	TEE_OperationHandle op = TEE_HANDLE_NULL;
2909 	TEE_ObjectHandle hkey = TEE_HANDLE_NULL;
2910 	TEE_Attribute attr = { };
2911 	uint8_t buf[TEE_AES_BLOCK_SIZE] = { };
2912 	size_t buf_size = sizeof(buf);
2913 
2914 	assert(key && kcv);
2915 
2916 	res = TEE_AllocateOperation(&op, TEE_ALG_AES_ECB_NOPAD,
2917 				    TEE_MODE_ENCRYPT, key_size * 8);
2918 	rc = tee2pkcs_error(res);
2919 	if (rc != PKCS11_CKR_OK)
2920 		goto out;
2921 
2922 	res = TEE_AllocateTransientObject(TEE_TYPE_AES, key_size * 8, &hkey);
2923 	rc = tee2pkcs_error(res);
2924 	if (rc != PKCS11_CKR_OK)
2925 		goto out;
2926 
2927 	TEE_InitRefAttribute(&attr, TEE_ATTR_SECRET_VALUE, key, key_size);
2928 
2929 	res = TEE_PopulateTransientObject(hkey, &attr, 1);
2930 	rc = tee2pkcs_error(res);
2931 	if (rc != PKCS11_CKR_OK)
2932 		goto out;
2933 
2934 	res = TEE_SetOperationKey(op, hkey);
2935 	rc = tee2pkcs_error(res);
2936 	if (rc != PKCS11_CKR_OK)
2937 		goto out;
2938 
2939 	TEE_CipherInit(op, NULL, 0);
2940 
2941 	res = TEE_CipherDoFinal(op, buf, buf_size, buf, &buf_size);
2942 	rc = tee2pkcs_error(res);
2943 	if (rc != PKCS11_CKR_OK)
2944 		goto out;
2945 
2946 	TEE_MemMove(kcv, buf, PKCS11_CKA_CHECK_VALUE_SIZE);
2947 
2948 out:
2949 	TEE_FreeTransientObject(hkey);
2950 	TEE_FreeOperation(op);
2951 
2952 	return rc;
2953 }
2954 
2955 enum pkcs11_rc set_check_value_attr(struct obj_attrs **head)
2956 {
2957 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
2958 	uint32_t val_len = 0;
2959 	uint32_t kcv2_len = 0;
2960 	void *val = NULL;
2961 	uint8_t kcv[PKCS11_CKA_CHECK_VALUE_SIZE] = { };
2962 	void *kcv2 = NULL;
2963 
2964 	assert(head && *head);
2965 
2966 	if (!IS_ENABLED(CFG_PKCS11_TA_CHECK_VALUE_ATTRIBUTE))
2967 		return PKCS11_CKR_OK;
2968 
2969 	switch (get_class(*head)) {
2970 	case PKCS11_CKO_SECRET_KEY:
2971 	case PKCS11_CKO_CERTIFICATE:
2972 		break;
2973 	default:
2974 		/* Nothing to do */
2975 		return PKCS11_CKR_OK;
2976 	}
2977 
2978 	/* Check whether CKA_CHECK_VALUE has been provided in the template */
2979 	rc = get_attribute_ptr(*head, PKCS11_CKA_CHECK_VALUE, &kcv2, &kcv2_len);
2980 
2981 	if (rc != PKCS11_CKR_OK && rc != PKCS11_RV_NOT_FOUND)
2982 		return PKCS11_CKR_GENERAL_ERROR;
2983 
2984 	/*
2985 	 * The generation of the KCV may be prevented by the application
2986 	 * supplying the attribute in the template as a no-value (0 length)
2987 	 * entry.
2988 	 */
2989 	if (rc == PKCS11_CKR_OK && !kcv2_len)
2990 		return PKCS11_CKR_OK;
2991 
2992 	if (rc == PKCS11_CKR_OK && kcv2_len != PKCS11_CKA_CHECK_VALUE_SIZE)
2993 		return PKCS11_CKR_ATTRIBUTE_VALUE_INVALID;
2994 
2995 	/* Get key CKA_VALUE */
2996 	rc = get_attribute_ptr(*head, PKCS11_CKA_VALUE, &val, &val_len);
2997 	if (rc)
2998 		return rc;
2999 
3000 	if (get_class(*head) == PKCS11_CKO_SECRET_KEY) {
3001 		switch (get_key_type(*head)) {
3002 		case PKCS11_CKK_AES:
3003 			rc = compute_check_value_with_ecb(val, val_len, kcv);
3004 			break;
3005 		case PKCS11_CKK_GENERIC_SECRET:
3006 		case PKCS11_CKK_MD5_HMAC:
3007 		case PKCS11_CKK_SHA_1_HMAC:
3008 		case PKCS11_CKK_SHA256_HMAC:
3009 		case PKCS11_CKK_SHA384_HMAC:
3010 		case PKCS11_CKK_SHA512_HMAC:
3011 		case PKCS11_CKK_SHA224_HMAC:
3012 			rc = compute_check_value_with_sha1(val, val_len, kcv);
3013 			break;
3014 		default:
3015 			rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
3016 			break;
3017 		}
3018 	} else {
3019 		rc = compute_check_value_with_sha1(val, val_len, kcv);
3020 	}
3021 
3022 	if (rc)
3023 		return rc;
3024 
3025 	/*
3026 	 * If the computed KCV does not match the provided one
3027 	 * then return CKR_ATTRIBUTE_VALUE_INVALID
3028 	 */
3029 	if (kcv2_len) {
3030 		/* Provided KCV value shall match the computed one */
3031 		if (TEE_MemCompare(kcv2, kcv, PKCS11_CKA_CHECK_VALUE_SIZE))
3032 			rc = PKCS11_CKR_ATTRIBUTE_VALUE_INVALID;
3033 	} else {
3034 		rc = add_attribute(head, PKCS11_CKA_CHECK_VALUE, kcv,
3035 				   PKCS11_CKA_CHECK_VALUE_SIZE);
3036 	}
3037 
3038 	return rc;
3039 }
3040