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