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