xref: /optee_os/ta/pkcs11/src/pkcs11_attributes.c (revision 0ac5c69596fcd74e295f79770b3eb4109b362bd2)
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 <pkcs11_ta.h>
9 #include <stdlib.h>
10 #include <string_ext.h>
11 #include <tee_internal_api_extensions.h>
12 #include <tee_internal_api.h>
13 #include <trace.h>
14 #include <util.h>
15 
16 #include "attributes.h"
17 #include "handle.h"
18 #include "pkcs11_attributes.h"
19 #include "pkcs11_helpers.h"
20 #include "pkcs11_token.h"
21 #include "sanitize_object.h"
22 #include "serializer.h"
23 #include "token_capabilities.h"
24 
25 /* Byte size of CKA_ID attribute when generated locally */
26 #define PKCS11_CKA_DEFAULT_SIZE		16
27 
28 static uint32_t pkcs11_func2ckfm(enum processing_func function)
29 {
30 	switch (function) {
31 	case PKCS11_FUNCTION_DIGEST:
32 		return PKCS11_CKFM_DIGEST;
33 	case PKCS11_FUNCTION_GENERATE:
34 		return PKCS11_CKFM_GENERATE;
35 	case PKCS11_FUNCTION_GENERATE_PAIR:
36 		return PKCS11_CKFM_GENERATE_KEY_PAIR;
37 	case PKCS11_FUNCTION_DERIVE:
38 		return PKCS11_CKFM_DERIVE;
39 	case PKCS11_FUNCTION_WRAP:
40 		return PKCS11_CKFM_WRAP;
41 	case PKCS11_FUNCTION_UNWRAP:
42 		return PKCS11_CKFM_UNWRAP;
43 	case PKCS11_FUNCTION_ENCRYPT:
44 		return PKCS11_CKFM_ENCRYPT;
45 	case PKCS11_FUNCTION_DECRYPT:
46 		return PKCS11_CKFM_DECRYPT;
47 	case PKCS11_FUNCTION_SIGN:
48 		return PKCS11_CKFM_SIGN;
49 	case PKCS11_FUNCTION_VERIFY:
50 		return PKCS11_CKFM_VERIFY;
51 	case PKCS11_FUNCTION_SIGN_RECOVER:
52 		return PKCS11_CKFM_SIGN_RECOVER;
53 	case PKCS11_FUNCTION_VERIFY_RECOVER:
54 		return PKCS11_CKFM_VERIFY_RECOVER;
55 	default:
56 		return 0;
57 	}
58 }
59 
60 enum pkcs11_rc
61 check_mechanism_against_processing(struct pkcs11_session *session,
62 				   enum pkcs11_mechanism_id mechanism_type,
63 				   enum processing_func function,
64 				   enum processing_step step)
65 {
66 	bool allowed = false;
67 
68 	switch (step) {
69 	case PKCS11_FUNC_STEP_INIT:
70 		switch (function) {
71 		case PKCS11_FUNCTION_IMPORT:
72 		case PKCS11_FUNCTION_COPY:
73 		case PKCS11_FUNCTION_MODIFY:
74 		case PKCS11_FUNCTION_DESTROY:
75 			return PKCS11_CKR_OK;
76 		default:
77 			break;
78 		}
79 		/*
80 		 * Check that the returned PKCS11_CKFM_* flag from
81 		 * pkcs11_func2ckfm() is among the ones from
82 		 * mechanism_supported_flags().
83 		 */
84 		allowed = mechanism_supported_flags(mechanism_type) &
85 			  pkcs11_func2ckfm(function);
86 		break;
87 
88 	case PKCS11_FUNC_STEP_ONESHOT:
89 		if (session->processing->always_authen &&
90 		    !session->processing->relogged)
91 			return PKCS11_CKR_USER_NOT_LOGGED_IN;
92 
93 		if (session->processing->updated) {
94 			EMSG("Cannot perform one-shot on updated processing");
95 			return PKCS11_CKR_OPERATION_ACTIVE;
96 		}
97 
98 		allowed = true;
99 		break;
100 
101 	case PKCS11_FUNC_STEP_UPDATE:
102 		if (session->processing->always_authen &&
103 		    !session->processing->relogged)
104 			return PKCS11_CKR_USER_NOT_LOGGED_IN;
105 
106 		allowed = !mechanism_is_one_shot_only(mechanism_type);
107 		break;
108 
109 	case PKCS11_FUNC_STEP_UPDATE_KEY:
110 		assert(function == PKCS11_FUNCTION_DIGEST);
111 
112 		if (session->processing->always_authen &&
113 		    !session->processing->relogged)
114 			return PKCS11_CKR_USER_NOT_LOGGED_IN;
115 
116 		allowed = true;
117 		break;
118 
119 	case PKCS11_FUNC_STEP_FINAL:
120 		if (session->processing->always_authen &&
121 		    !session->processing->relogged)
122 			return PKCS11_CKR_USER_NOT_LOGGED_IN;
123 
124 		return PKCS11_CKR_OK;
125 
126 	default:
127 		TEE_Panic(step);
128 		break;
129 	}
130 
131 	if (!allowed) {
132 		EMSG("Processing %#x/%s not permitted (%u/%u)",
133 		     (unsigned int)mechanism_type, id2str_proc(mechanism_type),
134 		     function, step);
135 		return PKCS11_CKR_MECHANISM_INVALID;
136 	}
137 
138 	return PKCS11_CKR_OK;
139 }
140 
141 /*
142  * Object default boolean attributes as per PKCS#11
143  */
144 static uint8_t *pkcs11_object_default_boolprop(uint32_t attribute)
145 {
146 	static const uint8_t bool_true = 1;
147 	static const uint8_t bool_false;
148 
149 	switch (attribute) {
150 	/* As per PKCS#11 default value */
151 	case PKCS11_CKA_MODIFIABLE:
152 	case PKCS11_CKA_COPYABLE:
153 	case PKCS11_CKA_DESTROYABLE:
154 		return (uint8_t *)&bool_true;
155 	case PKCS11_CKA_TOKEN:
156 	case PKCS11_CKA_PRIVATE:
157 	case PKCS11_CKA_WRAP_WITH_TRUSTED:
158 	case PKCS11_CKA_ALWAYS_AUTHENTICATE:
159 	case PKCS11_CKA_SENSITIVE:
160 		return (uint8_t *)&bool_false;
161 	/* Token specific default value */
162 	case PKCS11_CKA_SIGN:
163 	case PKCS11_CKA_VERIFY:
164 	case PKCS11_CKA_DERIVE:
165 	case PKCS11_CKA_ENCRYPT:
166 	case PKCS11_CKA_DECRYPT:
167 	case PKCS11_CKA_SIGN_RECOVER:
168 	case PKCS11_CKA_VERIFY_RECOVER:
169 	case PKCS11_CKA_WRAP:
170 	case PKCS11_CKA_UNWRAP:
171 	case PKCS11_CKA_EXTRACTABLE:
172 	case PKCS11_CKA_TRUSTED:
173 		return (uint8_t *)&bool_false;
174 	default:
175 		DMSG("No default for boolprop attribute %#"PRIx32, attribute);
176 		return NULL;
177 	}
178 }
179 
180 /*
181  * Object expects several boolean attributes to be set to a default value
182  * or to a validate client configuration value. This function append the input
183  * attribute (id/size/value) in the serialized object.
184  */
185 static enum pkcs11_rc pkcs11_import_object_boolprop(struct obj_attrs **out,
186 						    struct obj_attrs *templ,
187 						    uint32_t attribute)
188 {
189 	enum pkcs11_rc rc = PKCS11_CKR_OK;
190 	uint8_t bbool = 0;
191 	uint32_t size = sizeof(uint8_t);
192 	void *attr = NULL;
193 
194 	rc = get_attribute(templ, attribute, &bbool, &size);
195 	if (rc) {
196 		if (rc != PKCS11_RV_NOT_FOUND)
197 			return rc;
198 		attr = pkcs11_object_default_boolprop(attribute);
199 		if (!attr)
200 			return PKCS11_CKR_TEMPLATE_INCOMPLETE;
201 	} else {
202 		attr = &bbool;
203 	}
204 
205 	/* Boolean attributes are 1byte in the ABI, no alignment issue */
206 	return add_attribute(out, attribute, attr, sizeof(uint8_t));
207 }
208 
209 static enum pkcs11_rc set_mandatory_boolprops(struct obj_attrs **out,
210 					      struct obj_attrs *temp,
211 					      uint32_t const *bp,
212 					      size_t bp_count)
213 {
214 	enum pkcs11_rc rc = PKCS11_CKR_OK;
215 	size_t n = 0;
216 
217 	for (n = 0; n < bp_count; n++) {
218 		rc = pkcs11_import_object_boolprop(out, temp, bp[n]);
219 		if (rc)
220 			return rc;
221 	}
222 
223 	return rc;
224 }
225 
226 static enum pkcs11_rc set_mandatory_attributes(struct obj_attrs **out,
227 					       struct obj_attrs *temp,
228 					       uint32_t const *attrs,
229 					       size_t attrs_count)
230 {
231 	enum pkcs11_rc rc = PKCS11_CKR_OK;
232 	size_t n = 0;
233 
234 	for (n = 0; n < attrs_count; n++) {
235 		uint32_t size = 0;
236 		void *value = NULL;
237 
238 		if (get_attribute_ptr(temp, attrs[n], &value, &size))
239 			return PKCS11_CKR_TEMPLATE_INCOMPLETE;
240 
241 		rc = add_attribute(out, attrs[n], value, size);
242 		if (rc)
243 			return rc;
244 	}
245 
246 	return rc;
247 }
248 
249 static enum pkcs11_rc get_default_value(enum pkcs11_attr_id id, void **value,
250 					uint32_t *size)
251 {
252 	/* should have been taken care of already */
253 	assert(!pkcs11_attr_is_boolean(id));
254 
255 	if (id == PKCS11_CKA_PUBLIC_KEY_INFO) {
256 		EMSG("Cannot provide default PUBLIC_KEY_INFO");
257 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
258 	}
259 
260 	/* All other attributes have an empty default value */
261 	*value = NULL;
262 	*size = 0;
263 	return PKCS11_CKR_OK;
264 }
265 
266 static enum pkcs11_rc set_optional_attributes_with_def(struct obj_attrs **out,
267 						       struct obj_attrs *temp,
268 						       uint32_t const *attrs,
269 						       size_t attrs_count,
270 						       bool default_to_null)
271 {
272 	enum pkcs11_rc rc = PKCS11_CKR_OK;
273 	size_t n = 0;
274 
275 	for (n = 0; n < attrs_count; n++) {
276 		uint32_t size = 0;
277 		void *value = NULL;
278 
279 		rc = get_attribute_ptr(temp, attrs[n], &value, &size);
280 		if (rc == PKCS11_RV_NOT_FOUND) {
281 			if (default_to_null) {
282 				rc = get_default_value(attrs[n], &value, &size);
283 			} else {
284 				rc = PKCS11_CKR_OK;
285 				continue;
286 			}
287 		}
288 		if (rc)
289 			return rc;
290 
291 		rc = add_attribute(out, attrs[n], value, size);
292 		if (rc)
293 			return rc;
294 	}
295 
296 	return rc;
297 }
298 
299 static enum pkcs11_rc set_attributes_opt_or_null(struct obj_attrs **out,
300 						 struct obj_attrs *temp,
301 						 uint32_t const *attrs,
302 						 size_t attrs_count)
303 {
304 	return set_optional_attributes_with_def(out, temp, attrs, attrs_count,
305 						true /* defaults to empty */);
306 }
307 
308 static enum pkcs11_rc set_optional_attributes(struct obj_attrs **out,
309 					      struct obj_attrs *temp,
310 					      uint32_t const *attrs,
311 					      size_t attrs_count)
312 {
313 	return set_optional_attributes_with_def(out, temp, attrs, attrs_count,
314 						false /* no default value */);
315 }
316 
317 /*
318  * Below are listed the mandated or optional expected attributes for
319  * PKCS#11 storage objects.
320  *
321  * Note: boolprops (mandated boolean attributes) PKCS11_CKA_ALWAYS_SENSITIVE,
322  * and PKCS11_CKA_NEVER_EXTRACTABLE are set by the token, not provided
323  * in the client template.
324  */
325 
326 /* PKCS#11 specification for any object (session/token) of the storage */
327 static const uint32_t any_object_boolprops[] = {
328 	PKCS11_CKA_TOKEN, PKCS11_CKA_PRIVATE,
329 	PKCS11_CKA_MODIFIABLE, PKCS11_CKA_COPYABLE, PKCS11_CKA_DESTROYABLE,
330 };
331 
332 static const uint32_t any_object_opt_or_null[] = {
333 	PKCS11_CKA_LABEL,
334 };
335 
336 /* PKCS#11 specification for raw data object (+any_object_xxx) */
337 const uint32_t raw_data_opt_or_null[] = {
338 	PKCS11_CKA_OBJECT_ID, PKCS11_CKA_APPLICATION, PKCS11_CKA_VALUE,
339 };
340 
341 /* PKCS#11 specification for any key object (+any_object_xxx) */
342 static const uint32_t any_key_boolprops[] = {
343 	PKCS11_CKA_DERIVE,
344 };
345 
346 static const uint32_t any_key_opt_or_null[] = {
347 	PKCS11_CKA_ID,
348 	PKCS11_CKA_START_DATE, PKCS11_CKA_END_DATE,
349 };
350 
351 static const uint32_t any_key_optional[] = {
352 	PKCS11_CKA_ALLOWED_MECHANISMS,
353 };
354 
355 /* PKCS#11 specification for any symmetric key (+any_key_xxx) */
356 static const uint32_t symm_key_boolprops[] = {
357 	PKCS11_CKA_ENCRYPT, PKCS11_CKA_DECRYPT,
358 	PKCS11_CKA_SIGN, PKCS11_CKA_VERIFY,
359 	PKCS11_CKA_WRAP, PKCS11_CKA_UNWRAP,
360 	PKCS11_CKA_SENSITIVE, PKCS11_CKA_EXTRACTABLE,
361 	PKCS11_CKA_WRAP_WITH_TRUSTED, PKCS11_CKA_TRUSTED,
362 };
363 
364 static const uint32_t symm_key_opt_or_null[] = {
365 	PKCS11_CKA_WRAP_TEMPLATE, PKCS11_CKA_UNWRAP_TEMPLATE,
366 	PKCS11_CKA_DERIVE_TEMPLATE, PKCS11_CKA_VALUE,
367 };
368 
369 static const uint32_t symm_key_optional[] = {
370 	PKCS11_CKA_VALUE_LEN,
371 };
372 
373 /* PKCS#11 specification for any asymmetric public key (+any_key_xxx) */
374 static const uint32_t public_key_boolprops[] = {
375 	PKCS11_CKA_ENCRYPT, PKCS11_CKA_VERIFY, PKCS11_CKA_VERIFY_RECOVER,
376 	PKCS11_CKA_WRAP,
377 	PKCS11_CKA_TRUSTED,
378 };
379 
380 static const uint32_t public_key_mandated[] = {
381 	PKCS11_CKA_SUBJECT
382 };
383 
384 static const uint32_t public_key_opt_or_null[] = {
385 	PKCS11_CKA_WRAP_TEMPLATE, PKCS11_CKA_PUBLIC_KEY_INFO,
386 };
387 
388 /* PKCS#11 specification for any asymmetric private key (+any_key_xxx) */
389 static const uint32_t private_key_boolprops[] = {
390 	PKCS11_CKA_DECRYPT, PKCS11_CKA_SIGN, PKCS11_CKA_SIGN_RECOVER,
391 	PKCS11_CKA_UNWRAP,
392 	PKCS11_CKA_SENSITIVE, PKCS11_CKA_EXTRACTABLE,
393 	PKCS11_CKA_WRAP_WITH_TRUSTED, PKCS11_CKA_ALWAYS_AUTHENTICATE,
394 };
395 
396 static const uint32_t private_key_mandated[] = {
397 	PKCS11_CKA_SUBJECT
398 };
399 
400 static const uint32_t private_key_opt_or_null[] = {
401 	PKCS11_CKA_UNWRAP_TEMPLATE, PKCS11_CKA_PUBLIC_KEY_INFO,
402 };
403 
404 /* PKCS#11 specification for any RSA key (+public/private_key_xxx) */
405 static const uint32_t rsa_public_key_mandated[] = {
406 	PKCS11_CKA_MODULUS_BITS,
407 };
408 
409 static const uint32_t rsa_public_key_opt_or_null[] = {
410 	PKCS11_CKA_MODULUS, PKCS11_CKA_PUBLIC_EXPONENT,
411 };
412 
413 static const uint32_t rsa_private_key_opt_or_null[] = {
414 	PKCS11_CKA_MODULUS, PKCS11_CKA_PUBLIC_EXPONENT,
415 	PKCS11_CKA_PRIVATE_EXPONENT,
416 	PKCS11_CKA_PRIME_1, PKCS11_CKA_PRIME_2,
417 	PKCS11_CKA_EXPONENT_1, PKCS11_CKA_EXPONENT_2, PKCS11_CKA_COEFFICIENT,
418 };
419 
420 /* PKCS#11 specification for any EC key (+public/private_key_xxx) */
421 static const uint32_t ec_public_key_mandated[] = {
422 	PKCS11_CKA_EC_PARAMS,
423 };
424 
425 static const uint32_t ec_public_key_opt_or_null[] = {
426 	PKCS11_CKA_EC_POINT,
427 };
428 
429 static const uint32_t ec_private_key_mandated[] = {
430 	PKCS11_CKA_EC_PARAMS,
431 };
432 
433 static const uint32_t ec_private_key_opt_or_null[] = {
434 	PKCS11_CKA_VALUE,
435 };
436 
437 static enum pkcs11_rc create_storage_attributes(struct obj_attrs **out,
438 						struct obj_attrs *temp)
439 {
440 	enum pkcs11_class_id class = PKCS11_CKO_UNDEFINED_ID;
441 	enum pkcs11_rc rc = PKCS11_CKR_OK;
442 
443 	rc = init_attributes_head(out);
444 	if (rc)
445 		return rc;
446 
447 	/* Object class is mandatory */
448 	class = get_class(temp);
449 	if (class == PKCS11_CKO_UNDEFINED_ID) {
450 		EMSG("Class attribute not found");
451 
452 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
453 	}
454 	rc = add_attribute(out, PKCS11_CKA_CLASS, &class, sizeof(uint32_t));
455 	if (rc)
456 		return rc;
457 
458 	rc = set_mandatory_boolprops(out, temp, any_object_boolprops,
459 				     ARRAY_SIZE(any_object_boolprops));
460 	if (rc)
461 		return rc;
462 
463 	return set_attributes_opt_or_null(out, temp, any_object_opt_or_null,
464 					  ARRAY_SIZE(any_object_opt_or_null));
465 }
466 
467 static enum pkcs11_rc create_genkey_attributes(struct obj_attrs **out,
468 					       struct obj_attrs *temp)
469 {
470 	uint32_t type = PKCS11_CKO_UNDEFINED_ID;
471 	enum pkcs11_rc rc = PKCS11_CKR_OK;
472 
473 	rc = create_storage_attributes(out, temp);
474 	if (rc)
475 		return rc;
476 
477 	type = get_key_type(temp);
478 	if (type == PKCS11_CKK_UNDEFINED_ID) {
479 		EMSG("Key type attribute not found");
480 
481 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
482 	}
483 	rc = add_attribute(out, PKCS11_CKA_KEY_TYPE, &type, sizeof(uint32_t));
484 	if (rc)
485 		return rc;
486 
487 	rc = set_mandatory_boolprops(out, temp, any_key_boolprops,
488 				     ARRAY_SIZE(any_key_boolprops));
489 	if (rc)
490 		return rc;
491 
492 	rc = set_attributes_opt_or_null(out, temp, any_key_opt_or_null,
493 					ARRAY_SIZE(any_key_opt_or_null));
494 	if (rc)
495 		return rc;
496 
497 	return set_optional_attributes(out, temp, any_key_optional,
498 				       ARRAY_SIZE(any_key_optional));
499 
500 }
501 
502 static enum pkcs11_rc create_symm_key_attributes(struct obj_attrs **out,
503 						 struct obj_attrs *temp)
504 {
505 	enum pkcs11_rc rc = PKCS11_CKR_OK;
506 
507 	assert(get_class(temp) == PKCS11_CKO_SECRET_KEY);
508 
509 	rc = create_genkey_attributes(out, temp);
510 	if (rc)
511 		return rc;
512 
513 	assert(get_class(*out) == PKCS11_CKO_SECRET_KEY);
514 
515 	switch (get_key_type(*out)) {
516 	case PKCS11_CKK_GENERIC_SECRET:
517 	case PKCS11_CKK_AES:
518 	case PKCS11_CKK_MD5_HMAC:
519 	case PKCS11_CKK_SHA_1_HMAC:
520 	case PKCS11_CKK_SHA256_HMAC:
521 	case PKCS11_CKK_SHA384_HMAC:
522 	case PKCS11_CKK_SHA512_HMAC:
523 	case PKCS11_CKK_SHA224_HMAC:
524 		break;
525 	default:
526 		EMSG("Invalid key type %#"PRIx32"/%s",
527 		     get_key_type(*out), id2str_key_type(get_key_type(*out)));
528 
529 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
530 	}
531 
532 	rc = set_mandatory_boolprops(out, temp, symm_key_boolprops,
533 				     ARRAY_SIZE(symm_key_boolprops));
534 	if (rc)
535 		return rc;
536 
537 	rc = set_attributes_opt_or_null(out, temp, symm_key_opt_or_null,
538 					ARRAY_SIZE(symm_key_opt_or_null));
539 	if (rc)
540 		return rc;
541 
542 	return set_optional_attributes(out, temp, symm_key_optional,
543 				       ARRAY_SIZE(symm_key_optional));
544 }
545 
546 static enum pkcs11_rc create_data_attributes(struct obj_attrs **out,
547 					     struct obj_attrs *temp)
548 {
549 	enum pkcs11_rc rc = PKCS11_CKR_OK;
550 
551 	assert(get_class(temp) == PKCS11_CKO_DATA);
552 
553 	rc = create_storage_attributes(out, temp);
554 	if (rc)
555 		return rc;
556 
557 	assert(get_class(*out) == PKCS11_CKO_DATA);
558 
559 	return set_attributes_opt_or_null(out, temp, raw_data_opt_or_null,
560 					  ARRAY_SIZE(raw_data_opt_or_null));
561 }
562 
563 static enum pkcs11_rc create_pub_key_attributes(struct obj_attrs **out,
564 						struct obj_attrs *temp)
565 {
566 	uint32_t const *mandated = NULL;
567 	uint32_t const *opt_or_null = NULL;
568 	size_t mandated_count = 0;
569 	size_t opt_or_null_count = 0;
570 	enum pkcs11_rc rc = PKCS11_CKR_OK;
571 
572 	assert(get_class(temp) == PKCS11_CKO_PUBLIC_KEY);
573 
574 	rc = create_genkey_attributes(out, temp);
575 	if (rc)
576 		return rc;
577 
578 	assert(get_class(*out) == PKCS11_CKO_PUBLIC_KEY);
579 
580 	rc = set_mandatory_boolprops(out, temp, public_key_boolprops,
581 				     ARRAY_SIZE(public_key_boolprops));
582 	if (rc)
583 		return rc;
584 
585 	rc = set_mandatory_attributes(out, temp, public_key_mandated,
586 				      ARRAY_SIZE(public_key_mandated));
587 	if (rc)
588 		return rc;
589 
590 	rc = set_attributes_opt_or_null(out, temp,
591 					public_key_opt_or_null,
592 					ARRAY_SIZE(public_key_opt_or_null));
593 	if (rc)
594 		return rc;
595 
596 	switch (get_key_type(*out)) {
597 	case PKCS11_CKK_RSA:
598 		mandated = rsa_public_key_mandated;
599 		opt_or_null = rsa_public_key_opt_or_null;
600 		mandated_count = ARRAY_SIZE(rsa_public_key_mandated);
601 		opt_or_null_count = ARRAY_SIZE(rsa_public_key_opt_or_null);
602 		break;
603 	case PKCS11_CKK_EC:
604 		mandated = ec_public_key_mandated;
605 		opt_or_null = ec_public_key_opt_or_null;
606 		mandated_count = ARRAY_SIZE(ec_public_key_mandated);
607 		opt_or_null_count = ARRAY_SIZE(ec_public_key_opt_or_null);
608 		break;
609 	default:
610 		EMSG("Invalid key type %#"PRIx32"/%s",
611 		     get_key_type(*out), id2str_key_type(get_key_type(*out)));
612 
613 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
614 	}
615 
616 	rc = set_mandatory_attributes(out, temp, mandated, mandated_count);
617 	if (rc)
618 		return rc;
619 
620 	return set_attributes_opt_or_null(out, temp, opt_or_null,
621 					  opt_or_null_count);
622 }
623 
624 static enum pkcs11_rc create_priv_key_attributes(struct obj_attrs **out,
625 						 struct obj_attrs *temp)
626 {
627 	uint32_t const *mandated = NULL;
628 	uint32_t const *opt_or_null = NULL;
629 	size_t mandated_count = 0;
630 	size_t opt_or_null_count = 0;
631 	enum pkcs11_rc rc = PKCS11_CKR_OK;
632 
633 	assert(get_class(temp) == PKCS11_CKO_PRIVATE_KEY);
634 
635 	rc = create_genkey_attributes(out, temp);
636 	if (rc)
637 		return rc;
638 
639 	assert(get_class(*out) == PKCS11_CKO_PRIVATE_KEY);
640 
641 	rc = set_mandatory_boolprops(out, temp, private_key_boolprops,
642 				     ARRAY_SIZE(private_key_boolprops));
643 	if (rc)
644 		return rc;
645 
646 	rc = set_mandatory_attributes(out, temp, private_key_mandated,
647 				      ARRAY_SIZE(private_key_mandated));
648 	if (rc)
649 		return rc;
650 
651 	rc = set_attributes_opt_or_null(out, temp, private_key_opt_or_null,
652 					ARRAY_SIZE(private_key_opt_or_null));
653 	if (rc)
654 		return rc;
655 
656 	switch (get_key_type(*out)) {
657 	case PKCS11_CKK_RSA:
658 		opt_or_null = rsa_private_key_opt_or_null;
659 		opt_or_null_count = ARRAY_SIZE(rsa_private_key_opt_or_null);
660 		break;
661 	case PKCS11_CKK_EC:
662 		mandated = ec_private_key_mandated;
663 		opt_or_null = ec_private_key_opt_or_null;
664 		mandated_count = ARRAY_SIZE(ec_private_key_mandated);
665 		opt_or_null_count = ARRAY_SIZE(ec_private_key_opt_or_null);
666 		break;
667 	default:
668 		EMSG("Invalid key type %#"PRIx32"/%s",
669 		     get_key_type(*out), id2str_key_type(get_key_type(*out)));
670 
671 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
672 	}
673 
674 	rc = set_mandatory_attributes(out, temp, mandated, mandated_count);
675 	if (rc)
676 		return rc;
677 
678 	return set_attributes_opt_or_null(out, temp, opt_or_null,
679 					  opt_or_null_count);
680 }
681 
682 /*
683  * Create an attribute list for a new object from a template and a parent
684  * object (optional) for an object generation function (generate, copy,
685  * derive...).
686  *
687  * PKCS#11 directives on the supplied template and expected return value:
688  * - template has an invalid attribute ID: ATTRIBUTE_TYPE_INVALID
689  * - template has an invalid value for an attribute: ATTRIBUTE_VALID_INVALID
690  * - template has value for a read-only attribute: ATTRIBUTE_READ_ONLY
691  * - template+default+parent => still miss an attribute: TEMPLATE_INCONSISTENT
692  *
693  * INFO on PKCS11_CMD_COPY_OBJECT:
694  * - parent PKCS11_CKA_COPYIABLE=false => return ACTION_PROHIBITED.
695  * - template can specify PKCS11_CKA_TOKEN, PKCS11_CKA_PRIVATE,
696  *   PKCS11_CKA_MODIFIABLE, PKCS11_CKA_DESTROYABLE.
697  * - SENSITIVE can change from false to true, not from true to false.
698  * - LOCAL is the parent LOCAL
699  */
700 enum pkcs11_rc
701 create_attributes_from_template(struct obj_attrs **out, void *template,
702 				size_t template_size,
703 				struct obj_attrs *parent,
704 				enum processing_func function,
705 				enum pkcs11_mechanism_id mecha,
706 				enum pkcs11_class_id template_class __unused)
707 {
708 	struct obj_attrs *temp = NULL;
709 	struct obj_attrs *attrs = NULL;
710 	enum pkcs11_rc rc = PKCS11_CKR_OK;
711 	uint8_t local = 0;
712 	uint8_t always_sensitive = 0;
713 	uint8_t never_extract = 0;
714 	uint32_t class = PKCS11_UNDEFINED_ID;
715 	uint32_t type = PKCS11_UNDEFINED_ID;
716 	uint32_t mechanism_id = PKCS11_CKM_UNDEFINED_ID;
717 
718 #ifdef DEBUG	/* Sanity: check function argument */
719 	trace_attributes_from_api_head("template", template, template_size);
720 	switch (function) {
721 	case PKCS11_FUNCTION_GENERATE:
722 	case PKCS11_FUNCTION_IMPORT:
723 	case PKCS11_FUNCTION_MODIFY:
724 	case PKCS11_FUNCTION_DERIVE:
725 	case PKCS11_FUNCTION_COPY:
726 		break;
727 	default:
728 		TEE_Panic(TEE_ERROR_NOT_SUPPORTED);
729 	}
730 #endif
731 
732 	/*
733 	 * For PKCS11_FUNCTION_GENERATE, find the class and type
734 	 * based on the mechanism. These will be passed as hint
735 	 * sanitize_client_object() and added in temp if not
736 	 * already present
737 	 */
738 	if (function == PKCS11_FUNCTION_GENERATE) {
739 		switch (mecha) {
740 		case PKCS11_CKM_GENERIC_SECRET_KEY_GEN:
741 			class = PKCS11_CKO_SECRET_KEY;
742 			type = PKCS11_CKK_GENERIC_SECRET;
743 			break;
744 		case PKCS11_CKM_AES_KEY_GEN:
745 			class = PKCS11_CKO_SECRET_KEY;
746 			type = PKCS11_CKK_AES;
747 			break;
748 		default:
749 			TEE_Panic(TEE_ERROR_NOT_SUPPORTED);
750 		}
751 	}
752 
753 	/*
754 	 * Check and remove duplicates if any and create a new temporary
755 	 * template
756 	 */
757 	rc = sanitize_client_object(&temp, template, template_size, class,
758 				    type);
759 	if (rc)
760 		goto out;
761 
762 	/*
763 	 * For function type modify and copy return the created template
764 	 * from here. Rest of the code below is for creating objects
765 	 * or generating keys.
766 	 */
767 	switch (function) {
768 	case PKCS11_FUNCTION_MODIFY:
769 	case PKCS11_FUNCTION_COPY:
770 		*out = temp;
771 		return rc;
772 	default:
773 		break;
774 	}
775 
776 	/*
777 	 * Check if class and type in temp are consistent with the mechanism
778 	 */
779 	switch (mecha) {
780 	case PKCS11_CKM_GENERIC_SECRET_KEY_GEN:
781 		if (get_class(temp) != PKCS11_CKO_SECRET_KEY ||
782 		    get_key_type(temp) != PKCS11_CKK_GENERIC_SECRET) {
783 			rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
784 			goto out;
785 		}
786 		break;
787 	case PKCS11_CKM_AES_KEY_GEN:
788 		if (get_class(temp) != PKCS11_CKO_SECRET_KEY ||
789 		    get_key_type(temp) != PKCS11_CKK_AES) {
790 			rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
791 			goto out;
792 		}
793 		break;
794 	default:
795 		break;
796 	}
797 
798 	if (!sanitize_consistent_class_and_type(temp)) {
799 		EMSG("Inconsistent class/type");
800 		rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
801 		goto out;
802 	}
803 
804 	switch (get_class(temp)) {
805 	case PKCS11_CKO_DATA:
806 		rc = create_data_attributes(&attrs, temp);
807 		break;
808 	case PKCS11_CKO_SECRET_KEY:
809 		rc = create_symm_key_attributes(&attrs, temp);
810 		break;
811 	case PKCS11_CKO_PUBLIC_KEY:
812 		rc = create_pub_key_attributes(&attrs, temp);
813 		break;
814 	case PKCS11_CKO_PRIVATE_KEY:
815 		rc = create_priv_key_attributes(&attrs, temp);
816 		break;
817 	default:
818 		DMSG("Invalid object class %#"PRIx32"/%s",
819 		     get_class(temp), id2str_class(get_class(temp)));
820 
821 		rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
822 		break;
823 	}
824 	if (rc)
825 		goto out;
826 
827 	if (get_attribute_ptr(temp, PKCS11_CKA_LOCAL, NULL, NULL) !=
828 	    PKCS11_RV_NOT_FOUND) {
829 		rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
830 		goto out;
831 	}
832 
833 	if (get_attribute_ptr(temp, PKCS11_CKA_KEY_GEN_MECHANISM, NULL, NULL) !=
834 	    PKCS11_RV_NOT_FOUND) {
835 		rc = PKCS11_CKR_TEMPLATE_INCONSISTENT;
836 		goto out;
837 	}
838 
839 	switch (function) {
840 	case PKCS11_FUNCTION_GENERATE:
841 		local = PKCS11_TRUE;
842 		break;
843 	case PKCS11_FUNCTION_IMPORT:
844 	case PKCS11_FUNCTION_DERIVE:
845 	default:
846 		local = PKCS11_FALSE;
847 		break;
848 	}
849 	rc = add_attribute(&attrs, PKCS11_CKA_LOCAL, &local, sizeof(local));
850 	if (rc)
851 		goto out;
852 
853 	switch (get_class(attrs)) {
854 	case PKCS11_CKO_SECRET_KEY:
855 	case PKCS11_CKO_PRIVATE_KEY:
856 	case PKCS11_CKO_PUBLIC_KEY:
857 		always_sensitive = PKCS11_FALSE;
858 		never_extract = PKCS11_FALSE;
859 
860 		switch (function) {
861 		case PKCS11_FUNCTION_DERIVE:
862 			always_sensitive =
863 				get_bool(parent, PKCS11_CKA_ALWAYS_SENSITIVE) &&
864 				get_bool(attrs, PKCS11_CKA_SENSITIVE);
865 			never_extract =
866 			       get_bool(parent, PKCS11_CKA_NEVER_EXTRACTABLE) &&
867 			       !get_bool(attrs, PKCS11_CKA_EXTRACTABLE);
868 			break;
869 		case PKCS11_FUNCTION_GENERATE:
870 			always_sensitive = get_bool(attrs,
871 						    PKCS11_CKA_SENSITIVE);
872 			never_extract = !get_bool(attrs,
873 						  PKCS11_CKA_EXTRACTABLE);
874 			break;
875 		default:
876 			break;
877 		}
878 
879 		rc = add_attribute(&attrs, PKCS11_CKA_ALWAYS_SENSITIVE,
880 				   &always_sensitive, sizeof(always_sensitive));
881 		if (rc)
882 			goto out;
883 
884 		rc = add_attribute(&attrs, PKCS11_CKA_NEVER_EXTRACTABLE,
885 				   &never_extract, sizeof(never_extract));
886 		if (rc)
887 			goto out;
888 
889 		/* Keys mandate attribute PKCS11_CKA_KEY_GEN_MECHANISM */
890 		if (local)
891 			mechanism_id = mecha;
892 		else
893 			mechanism_id = PKCS11_CK_UNAVAILABLE_INFORMATION;
894 
895 		rc = add_attribute(&attrs, PKCS11_CKA_KEY_GEN_MECHANISM,
896 				   &mechanism_id, sizeof(mechanism_id));
897 		if (rc)
898 			goto out;
899 		break;
900 
901 	default:
902 		break;
903 	}
904 
905 	*out = attrs;
906 
907 #ifdef DEBUG
908 	trace_attributes("object", attrs);
909 #endif
910 
911 out:
912 	TEE_Free(temp);
913 	if (rc)
914 		TEE_Free(attrs);
915 
916 	return rc;
917 }
918 
919 static enum pkcs11_rc check_attrs_misc_integrity(struct obj_attrs *head)
920 {
921 	if (get_bool(head, PKCS11_CKA_NEVER_EXTRACTABLE) &&
922 	    get_bool(head, PKCS11_CKA_EXTRACTABLE)) {
923 		DMSG("Never/Extractable attributes mismatch %d/%d",
924 		     get_bool(head, PKCS11_CKA_NEVER_EXTRACTABLE),
925 		     get_bool(head, PKCS11_CKA_EXTRACTABLE));
926 
927 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
928 	}
929 
930 	if (get_bool(head, PKCS11_CKA_ALWAYS_SENSITIVE) &&
931 	    !get_bool(head, PKCS11_CKA_SENSITIVE)) {
932 		DMSG("Sensitive/always attributes mismatch %d/%d",
933 		     get_bool(head, PKCS11_CKA_SENSITIVE),
934 		     get_bool(head, PKCS11_CKA_ALWAYS_SENSITIVE));
935 
936 		return PKCS11_CKR_TEMPLATE_INCONSISTENT;
937 	}
938 
939 	return PKCS11_CKR_OK;
940 }
941 
942 bool object_is_private(struct obj_attrs *head)
943 {
944 	return get_bool(head, PKCS11_CKA_PRIVATE);
945 }
946 
947 bool object_is_token(struct obj_attrs *head)
948 {
949 	return get_bool(head, PKCS11_CKA_TOKEN);
950 }
951 
952 bool object_is_modifiable(struct obj_attrs *head)
953 {
954 	return get_bool(head, PKCS11_CKA_MODIFIABLE);
955 }
956 
957 bool object_is_copyable(struct obj_attrs *head)
958 {
959 	return get_bool(head, PKCS11_CKA_COPYABLE);
960 }
961 
962 /*
963  * Check access to object against authentication to token
964  */
965 enum pkcs11_rc check_access_attrs_against_token(struct pkcs11_session *session,
966 						struct obj_attrs *head)
967 {
968 	bool private = true;
969 
970 	switch (get_class(head)) {
971 	case PKCS11_CKO_SECRET_KEY:
972 	case PKCS11_CKO_PRIVATE_KEY:
973 	case PKCS11_CKO_PUBLIC_KEY:
974 	case PKCS11_CKO_DATA:
975 		private = object_is_private(head);
976 		break;
977 	default:
978 		return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
979 	}
980 
981 	if (private && (pkcs11_session_is_public(session) ||
982 			pkcs11_session_is_so(session))) {
983 		DMSG("Private object access from a public or SO session");
984 
985 		return PKCS11_CKR_USER_NOT_LOGGED_IN;
986 	}
987 
988 	return PKCS11_CKR_OK;
989 }
990 
991 /*
992  * Check the attributes of a to-be-created object matches the token state
993  */
994 enum pkcs11_rc check_created_attrs_against_token(struct pkcs11_session *session,
995 						 struct obj_attrs *head)
996 {
997 	enum pkcs11_rc rc = PKCS11_CKR_OK;
998 
999 	rc = check_attrs_misc_integrity(head);
1000 	if (rc)
1001 		return rc;
1002 
1003 	if (get_bool(head, PKCS11_CKA_TRUSTED) &&
1004 	    !pkcs11_session_is_so(session)) {
1005 		DMSG("Can't create trusted object");
1006 
1007 		return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1008 	}
1009 
1010 	if (get_bool(head, PKCS11_CKA_TOKEN) &&
1011 	    !pkcs11_session_is_read_write(session)) {
1012 		DMSG("Can't create persistent object");
1013 
1014 		return PKCS11_CKR_SESSION_READ_ONLY;
1015 	}
1016 
1017 	/*
1018 	 * TODO: START_DATE and END_DATE: complies with current time?
1019 	 */
1020 	return PKCS11_CKR_OK;
1021 }
1022 
1023 #define DMSG_BAD_BBOOL(attr, proc, head)				\
1024 	do {								\
1025 		uint32_t __maybe_unused _attr = (attr);			\
1026 		uint8_t __maybe_unused _bvalue = 0;			\
1027 		enum pkcs11_rc __maybe_unused _rc = PKCS11_CKR_OK;	\
1028 									\
1029 		_rc = get_attribute((head), _attr, &_bvalue, NULL);	\
1030 		DMSG("%s issue for %s: %sfound, value %"PRIu8,		\
1031 		     id2str_attr(_attr), id2str_proc((proc)),		\
1032 		     _rc ? "not " : "", _bvalue);			\
1033 	} while (0)
1034 
1035 static bool __maybe_unused check_attr_bval(uint32_t proc_id __maybe_unused,
1036 					   struct obj_attrs *head,
1037 					   uint32_t attribute, bool val)
1038 {
1039 	uint8_t bbool = 0;
1040 	uint32_t sz = sizeof(bbool);
1041 
1042 	if (!get_attribute(head, attribute, &bbool, &sz) && !!bbool == val)
1043 		return true;
1044 
1045 	DMSG_BAD_BBOOL(attribute, proc_id, head);
1046 	return false;
1047 }
1048 
1049 /*
1050  * Check the attributes of a new secret match the processing/mechanism
1051  * used to create it.
1052  *
1053  * @proc_id - PKCS11_CKM_xxx
1054  * @head - head of the attributes of the to-be-created object.
1055  */
1056 enum pkcs11_rc check_created_attrs_against_processing(uint32_t proc_id,
1057 						      struct obj_attrs *head)
1058 {
1059 	/*
1060 	 * Processings that do not create secrets are not expected to call
1061 	 * this function which would panic.
1062 	 */
1063 	switch (proc_id) {
1064 	case PKCS11_PROCESSING_IMPORT:
1065 	case PKCS11_CKM_AES_ECB_ENCRYPT_DATA:
1066 	case PKCS11_CKM_AES_CBC_ENCRYPT_DATA:
1067 		assert(check_attr_bval(proc_id, head, PKCS11_CKA_LOCAL, false));
1068 		break;
1069 	case PKCS11_CKM_GENERIC_SECRET_KEY_GEN:
1070 	case PKCS11_CKM_AES_KEY_GEN:
1071 		assert(check_attr_bval(proc_id, head, PKCS11_CKA_LOCAL, true));
1072 		break;
1073 	default:
1074 		TEE_Panic(proc_id);
1075 		break;
1076 	}
1077 
1078 	switch (proc_id) {
1079 	case PKCS11_CKM_GENERIC_SECRET_KEY_GEN:
1080 		assert(get_key_type(head) == PKCS11_CKK_GENERIC_SECRET);
1081 		break;
1082 	case PKCS11_CKM_AES_KEY_GEN:
1083 		assert(get_key_type(head) == PKCS11_CKK_AES);
1084 		break;
1085 	case PKCS11_PROCESSING_IMPORT:
1086 	default:
1087 		break;
1088 	}
1089 
1090 	return PKCS11_CKR_OK;
1091 }
1092 
1093 /* Return min and max key size supported for a key_type in bytes */
1094 static void get_key_min_max_sizes(enum pkcs11_key_type key_type,
1095 				  uint32_t *min_key_size,
1096 				  uint32_t *max_key_size)
1097 {
1098 	enum pkcs11_mechanism_id mechanism = PKCS11_CKM_UNDEFINED_ID;
1099 
1100 	switch (key_type) {
1101 	case PKCS11_CKK_GENERIC_SECRET:
1102 		mechanism = PKCS11_CKM_GENERIC_SECRET_KEY_GEN;
1103 		break;
1104 	case PKCS11_CKK_AES:
1105 		mechanism = PKCS11_CKM_AES_KEY_GEN;
1106 		break;
1107 	case PKCS11_CKK_MD5_HMAC:
1108 		mechanism = PKCS11_CKM_MD5_HMAC;
1109 		break;
1110 	case PKCS11_CKK_SHA_1_HMAC:
1111 		mechanism = PKCS11_CKM_SHA_1_HMAC;
1112 		break;
1113 	case PKCS11_CKK_SHA224_HMAC:
1114 		mechanism = PKCS11_CKM_SHA224_HMAC;
1115 		break;
1116 	case PKCS11_CKK_SHA256_HMAC:
1117 		mechanism = PKCS11_CKM_SHA256_HMAC;
1118 		break;
1119 	case PKCS11_CKK_SHA384_HMAC:
1120 		mechanism = PKCS11_CKM_SHA384_HMAC;
1121 		break;
1122 	case PKCS11_CKK_SHA512_HMAC:
1123 		mechanism = PKCS11_CKM_SHA512_HMAC;
1124 		break;
1125 	default:
1126 		TEE_Panic(key_type);
1127 		break;
1128 	}
1129 
1130 	mechanism_supported_key_sizes_bytes(mechanism, min_key_size,
1131 					    max_key_size);
1132 }
1133 
1134 enum pkcs11_rc check_created_attrs(struct obj_attrs *key1,
1135 				   struct obj_attrs *key2)
1136 {
1137 	enum pkcs11_rc rc = PKCS11_CKR_OK;
1138 	struct obj_attrs *secret = NULL;
1139 	uint32_t max_key_size = 0;
1140 	uint32_t min_key_size = 0;
1141 	uint32_t key_length = 0;
1142 
1143 	switch (get_class(key1)) {
1144 	case PKCS11_CKO_SECRET_KEY:
1145 		secret = key1;
1146 		break;
1147 	default:
1148 		return PKCS11_CKR_ATTRIBUTE_VALUE_INVALID;
1149 	}
1150 
1151 	if (key2)
1152 		return PKCS11_CKR_ATTRIBUTE_VALUE_INVALID;
1153 
1154 	if (secret) {
1155 		switch (get_key_type(secret)) {
1156 		case PKCS11_CKK_AES:
1157 		case PKCS11_CKK_GENERIC_SECRET:
1158 		case PKCS11_CKK_MD5_HMAC:
1159 		case PKCS11_CKK_SHA_1_HMAC:
1160 		case PKCS11_CKK_SHA224_HMAC:
1161 		case PKCS11_CKK_SHA256_HMAC:
1162 		case PKCS11_CKK_SHA384_HMAC:
1163 		case PKCS11_CKK_SHA512_HMAC:
1164 			break;
1165 		default:
1166 			return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1167 		}
1168 
1169 		/* Get key size */
1170 		rc = get_u32_attribute(secret, PKCS11_CKA_VALUE_LEN,
1171 				       &key_length);
1172 		if (rc)
1173 			return PKCS11_CKR_TEMPLATE_INCOMPLETE;
1174 	}
1175 
1176 	get_key_min_max_sizes(get_key_type(key1), &min_key_size, &max_key_size);
1177 	if (key_length < min_key_size || key_length > max_key_size) {
1178 		EMSG("Length %"PRIu32" vs range [%"PRIu32" %"PRIu32"]",
1179 		     key_length, min_key_size, max_key_size);
1180 
1181 		return PKCS11_CKR_KEY_SIZE_RANGE;
1182 	}
1183 
1184 	if (secret && get_key_type(secret) == PKCS11_CKK_AES) {
1185 		if (key_length != 16 && key_length != 24 && key_length != 32)
1186 			return PKCS11_CKR_KEY_SIZE_RANGE;
1187 	}
1188 
1189 	return PKCS11_CKR_OK;
1190 }
1191 
1192 /* Check processing ID against attribute ALLOWED_MECHANISMS if any */
1193 static bool parent_key_complies_allowed_processings(uint32_t proc_id,
1194 						    struct obj_attrs *head)
1195 {
1196 	char *attr = NULL;
1197 	uint32_t size = 0;
1198 	uint32_t proc = 0;
1199 	size_t count = 0;
1200 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
1201 
1202 	rc = get_attribute_ptr(head, PKCS11_CKA_ALLOWED_MECHANISMS,
1203 			       (void *)&attr, &size);
1204 	if (rc == PKCS11_RV_NOT_FOUND)
1205 		return true;
1206 	if (rc) {
1207 		EMSG("unexpected attributes state");
1208 		TEE_Panic(TEE_ERROR_BAD_STATE);
1209 	}
1210 
1211 	for (count = size / sizeof(uint32_t); count; count--) {
1212 		TEE_MemMove(&proc, attr, sizeof(uint32_t));
1213 		attr += sizeof(uint32_t);
1214 
1215 		if (proc == proc_id)
1216 			return true;
1217 	}
1218 
1219 	DMSG("can't find %s in allowed list", id2str_proc(proc_id));
1220 	return false;
1221 }
1222 
1223 static enum pkcs11_attr_id func_to_attr(enum processing_func func)
1224 {
1225 	switch (func) {
1226 	case PKCS11_FUNCTION_ENCRYPT:
1227 		return PKCS11_CKA_ENCRYPT;
1228 	case PKCS11_FUNCTION_DECRYPT:
1229 		return PKCS11_CKA_DECRYPT;
1230 	case PKCS11_FUNCTION_SIGN:
1231 		return PKCS11_CKA_SIGN;
1232 	case PKCS11_FUNCTION_VERIFY:
1233 		return PKCS11_CKA_VERIFY;
1234 	case PKCS11_FUNCTION_WRAP:
1235 		return PKCS11_CKA_WRAP;
1236 	case PKCS11_FUNCTION_UNWRAP:
1237 		return PKCS11_CKA_UNWRAP;
1238 	case PKCS11_FUNCTION_DERIVE:
1239 		return PKCS11_CKA_DERIVE;
1240 	default:
1241 		return PKCS11_CKA_UNDEFINED_ID;
1242 	}
1243 }
1244 
1245 enum pkcs11_rc
1246 check_parent_attrs_against_processing(enum pkcs11_mechanism_id proc_id,
1247 				      enum processing_func function,
1248 				      struct obj_attrs *head)
1249 {
1250 	enum pkcs11_class_id key_class = get_class(head);
1251 	enum pkcs11_key_type key_type = get_key_type(head);
1252 	enum pkcs11_attr_id attr = func_to_attr(function);
1253 
1254 	if (!get_bool(head, attr)) {
1255 		DMSG("%s not permitted", id2str_attr(attr));
1256 		return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1257 	}
1258 
1259 	/* Check processing complies with parent key family */
1260 	switch (proc_id) {
1261 	case PKCS11_CKM_AES_ECB:
1262 	case PKCS11_CKM_AES_CBC:
1263 	case PKCS11_CKM_AES_CBC_PAD:
1264 	case PKCS11_CKM_AES_CTS:
1265 	case PKCS11_CKM_AES_CTR:
1266 		if (key_class == PKCS11_CKO_SECRET_KEY &&
1267 		    key_type == PKCS11_CKK_AES)
1268 			break;
1269 
1270 		DMSG("%s invalid key %s/%s", id2str_proc(proc_id),
1271 		     id2str_class(key_class), id2str_key_type(key_type));
1272 
1273 		return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1274 
1275 	case PKCS11_CKM_AES_ECB_ENCRYPT_DATA:
1276 	case PKCS11_CKM_AES_CBC_ENCRYPT_DATA:
1277 		if (key_class != PKCS11_CKO_SECRET_KEY &&
1278 		    key_type != PKCS11_CKK_AES)
1279 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1280 
1281 		if (get_bool(head, PKCS11_CKA_ENCRYPT)) {
1282 			/*
1283 			 * Intentionally refuse to proceed despite
1284 			 * PKCS#11 specifications v2.40 and v3.0 not expecting
1285 			 * this behavior to avoid potential security issue
1286 			 * where keys derived by these mechanisms can be
1287 			 * revealed by doing data encryption using parent key.
1288 			 */
1289 			return PKCS11_CKR_FUNCTION_FAILED;
1290 		}
1291 
1292 		break;
1293 	case PKCS11_CKM_MD5_HMAC:
1294 	case PKCS11_CKM_SHA_1_HMAC:
1295 	case PKCS11_CKM_SHA224_HMAC:
1296 	case PKCS11_CKM_SHA256_HMAC:
1297 	case PKCS11_CKM_SHA384_HMAC:
1298 	case PKCS11_CKM_SHA512_HMAC:
1299 		if (key_class != PKCS11_CKO_SECRET_KEY)
1300 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1301 
1302 		if (key_type == PKCS11_CKK_GENERIC_SECRET)
1303 			break;
1304 
1305 		switch (proc_id) {
1306 		case PKCS11_CKM_MD5_HMAC:
1307 			if (key_type == PKCS11_CKK_MD5_HMAC)
1308 				break;
1309 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1310 		case PKCS11_CKM_SHA_1_HMAC:
1311 			if (key_type == PKCS11_CKK_SHA_1_HMAC)
1312 				break;
1313 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1314 		case PKCS11_CKM_SHA224_HMAC:
1315 			if (key_type == PKCS11_CKK_SHA224_HMAC)
1316 				break;
1317 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1318 		case PKCS11_CKM_SHA256_HMAC:
1319 			if (key_type == PKCS11_CKK_SHA256_HMAC)
1320 				break;
1321 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1322 		case PKCS11_CKM_SHA384_HMAC:
1323 			if (key_type == PKCS11_CKK_SHA384_HMAC)
1324 				break;
1325 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1326 		case PKCS11_CKM_SHA512_HMAC:
1327 			if (key_type == PKCS11_CKK_SHA512_HMAC)
1328 				break;
1329 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1330 		default:
1331 			return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1332 		}
1333 		break;
1334 
1335 	default:
1336 		DMSG("Invalid processing %#"PRIx32"/%s", proc_id,
1337 		     id2str_proc(proc_id));
1338 
1339 		return PKCS11_CKR_MECHANISM_INVALID;
1340 	}
1341 
1342 	if (!parent_key_complies_allowed_processings(proc_id, head)) {
1343 		DMSG("Allowed mechanism failed");
1344 		return PKCS11_CKR_KEY_FUNCTION_NOT_PERMITTED;
1345 	}
1346 
1347 	return PKCS11_CKR_OK;
1348 }
1349 
1350 bool attribute_is_exportable(struct pkcs11_attribute_head *req_attr,
1351 			     struct pkcs11_object *obj)
1352 {
1353 	uint8_t boolval = 0;
1354 	uint32_t boolsize = 0;
1355 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
1356 	enum pkcs11_class_id key_class = get_class(obj->attributes);
1357 
1358 	if (key_class != PKCS11_CKO_SECRET_KEY &&
1359 	    key_class != PKCS11_CKO_PRIVATE_KEY)
1360 		return true;
1361 
1362 	switch (req_attr->id) {
1363 	case PKCS11_CKA_PRIVATE_EXPONENT:
1364 	case PKCS11_CKA_PRIME_1:
1365 	case PKCS11_CKA_PRIME_2:
1366 	case PKCS11_CKA_EXPONENT_1:
1367 	case PKCS11_CKA_EXPONENT_2:
1368 	case PKCS11_CKA_COEFFICIENT:
1369 	case PKCS11_CKA_VALUE:
1370 		boolsize = sizeof(boolval);
1371 		rc = get_attribute(obj->attributes, PKCS11_CKA_EXTRACTABLE,
1372 				   &boolval, &boolsize);
1373 		if (rc || boolval == PKCS11_FALSE)
1374 			return false;
1375 
1376 		boolsize = sizeof(boolval);
1377 		rc = get_attribute(obj->attributes, PKCS11_CKA_SENSITIVE,
1378 				   &boolval, &boolsize);
1379 		if (rc || boolval == PKCS11_TRUE)
1380 			return false;
1381 		break;
1382 	default:
1383 		break;
1384 	}
1385 
1386 	return true;
1387 }
1388 
1389 static bool attr_is_modifiable_any_key(struct pkcs11_attribute_head *attr)
1390 {
1391 	switch (attr->id) {
1392 	case PKCS11_CKA_ID:
1393 	case PKCS11_CKA_START_DATE:
1394 	case PKCS11_CKA_END_DATE:
1395 	case PKCS11_CKA_DERIVE:
1396 		return true;
1397 	default:
1398 		return false;
1399 	}
1400 }
1401 
1402 static bool attr_is_modifiable_secret_key(struct pkcs11_attribute_head *attr,
1403 					  struct pkcs11_session *session,
1404 					  struct pkcs11_object *obj)
1405 {
1406 	switch (attr->id) {
1407 	case PKCS11_CKA_ENCRYPT:
1408 	case PKCS11_CKA_DECRYPT:
1409 	case PKCS11_CKA_SIGN:
1410 	case PKCS11_CKA_VERIFY:
1411 	case PKCS11_CKA_WRAP:
1412 	case PKCS11_CKA_UNWRAP:
1413 		return true;
1414 	/* Can't be modified once set to CK_FALSE - 12 in Table 10 */
1415 	case PKCS11_CKA_EXTRACTABLE:
1416 		return get_bool(obj->attributes, attr->id);
1417 	/* Can't be modified once set to CK_TRUE - 11 in Table 10 */
1418 	case PKCS11_CKA_SENSITIVE:
1419 	case PKCS11_CKA_WRAP_WITH_TRUSTED:
1420 		return !get_bool(obj->attributes, attr->id);
1421 	/* Change in CKA_TRUSTED can only be done by SO */
1422 	case PKCS11_CKA_TRUSTED:
1423 		return pkcs11_session_is_so(session);
1424 	case PKCS11_CKA_NEVER_EXTRACTABLE:
1425 	case PKCS11_CKA_ALWAYS_SENSITIVE:
1426 		return false;
1427 	default:
1428 		return false;
1429 	}
1430 }
1431 
1432 static bool attr_is_modifiable_public_key(struct pkcs11_attribute_head *attr,
1433 					  struct pkcs11_session *session,
1434 					  struct pkcs11_object *obj __unused)
1435 {
1436 	switch (attr->id) {
1437 	case PKCS11_CKA_SUBJECT:
1438 	case PKCS11_CKA_ENCRYPT:
1439 	case PKCS11_CKA_VERIFY:
1440 	case PKCS11_CKA_VERIFY_RECOVER:
1441 	case PKCS11_CKA_WRAP:
1442 		return true;
1443 	case PKCS11_CKA_TRUSTED:
1444 		/* Change in CKA_TRUSTED can only be done by SO */
1445 		return pkcs11_session_is_so(session);
1446 	default:
1447 		return false;
1448 	}
1449 }
1450 
1451 static bool attr_is_modifiable_private_key(struct pkcs11_attribute_head *attr,
1452 					   struct pkcs11_session *sess __unused,
1453 					   struct pkcs11_object *obj)
1454 {
1455 	switch (attr->id) {
1456 	case PKCS11_CKA_SUBJECT:
1457 	case PKCS11_CKA_DECRYPT:
1458 	case PKCS11_CKA_SIGN:
1459 	case PKCS11_CKA_SIGN_RECOVER:
1460 	case PKCS11_CKA_UNWRAP:
1461 	/*
1462 	 * TBD: Revisit if we don't support PKCS11_CKA_PUBLIC_KEY_INFO
1463 	 * Specification mentions that if this attribute is
1464 	 * supplied as part of a template for C_CreateObject, C_CopyObject or
1465 	 * C_SetAttributeValue for a private key, the token MUST verify
1466 	 * correspondence between the private key data and the public key data
1467 	 * as supplied in CKA_PUBLIC_KEY_INFO. This needs to be
1468 	 * taken care of when this object type will be implemented
1469 	 */
1470 	case PKCS11_CKA_PUBLIC_KEY_INFO:
1471 		return true;
1472 	/* Can't be modified once set to CK_FALSE - 12 in Table 10 */
1473 	case PKCS11_CKA_EXTRACTABLE:
1474 		return get_bool(obj->attributes, attr->id);
1475 	/* Can't be modified once set to CK_TRUE - 11 in Table 10 */
1476 	case PKCS11_CKA_SENSITIVE:
1477 	case PKCS11_CKA_WRAP_WITH_TRUSTED:
1478 		return !get_bool(obj->attributes, attr->id);
1479 	case PKCS11_CKA_NEVER_EXTRACTABLE:
1480 	case PKCS11_CKA_ALWAYS_SENSITIVE:
1481 		return false;
1482 	default:
1483 		return false;
1484 	}
1485 }
1486 
1487 static bool attribute_is_modifiable(struct pkcs11_session *session,
1488 				    struct pkcs11_attribute_head *req_attr,
1489 				    struct pkcs11_object *obj,
1490 				    enum pkcs11_class_id class,
1491 				    enum processing_func function)
1492 {
1493 	/* Check modifiable attributes common to any object */
1494 	switch (req_attr->id) {
1495 	case PKCS11_CKA_LABEL:
1496 		return true;
1497 	case PKCS11_CKA_TOKEN:
1498 	case PKCS11_CKA_MODIFIABLE:
1499 	case PKCS11_CKA_DESTROYABLE:
1500 	case PKCS11_CKA_PRIVATE:
1501 		return function == PKCS11_FUNCTION_COPY;
1502 	case PKCS11_CKA_COPYABLE:
1503 		/*
1504 		 * Specification mentions that if the attribute value is false
1505 		 * it can't be set to true. Reading this we assume that it
1506 		 * should be possible to modify this attribute even though this
1507 		 * is not marked as modifiable in Table 10 if done in right
1508 		 * direction i.e from TRUE -> FALSE.
1509 		 */
1510 		return get_bool(obj->attributes, req_attr->id);
1511 	default:
1512 		break;
1513 	}
1514 
1515 	/* Attribute checking based on class type */
1516 	switch (class) {
1517 	case PKCS11_CKO_SECRET_KEY:
1518 	case PKCS11_CKO_PUBLIC_KEY:
1519 	case PKCS11_CKO_PRIVATE_KEY:
1520 		if (attr_is_modifiable_any_key(req_attr))
1521 			return true;
1522 		if (class == PKCS11_CKO_SECRET_KEY &&
1523 		    attr_is_modifiable_secret_key(req_attr, session, obj))
1524 			return true;
1525 		if (class == PKCS11_CKO_PUBLIC_KEY &&
1526 		    attr_is_modifiable_public_key(req_attr, session, obj))
1527 			return true;
1528 		if (class == PKCS11_CKO_PRIVATE_KEY &&
1529 		    attr_is_modifiable_private_key(req_attr, session, obj))
1530 			return true;
1531 		break;
1532 	case PKCS11_CKO_DATA:
1533 		/* None of the data object attributes are modifiable */
1534 		return false;
1535 	default:
1536 		break;
1537 	}
1538 
1539 	return false;
1540 }
1541 
1542 enum pkcs11_rc check_attrs_against_modification(struct pkcs11_session *session,
1543 						struct obj_attrs *head,
1544 						struct pkcs11_object *obj,
1545 						enum processing_func function)
1546 {
1547 	enum pkcs11_class_id class = PKCS11_CKO_UNDEFINED_ID;
1548 	char *cur = NULL;
1549 	char *end = NULL;
1550 	size_t len = 0;
1551 
1552 	class = get_class(obj->attributes);
1553 
1554 	cur = (char *)head + sizeof(struct obj_attrs);
1555 	end = cur + head->attrs_size;
1556 
1557 	for (; cur < end; cur += len) {
1558 		/* Structure aligned copy of the pkcs11_ref in the object */
1559 		struct pkcs11_attribute_head cli_ref = { };
1560 
1561 		TEE_MemMove(&cli_ref, cur, sizeof(cli_ref));
1562 		len = sizeof(cli_ref) + cli_ref.size;
1563 
1564 		/*
1565 		 * Check 1 - Check if attribute belongs to the object
1566 		 * The obj->attributes has all the attributes in
1567 		 * it which are allowed for an object.
1568 		 */
1569 		if (get_attribute_ptr(obj->attributes, cli_ref.id, NULL,
1570 				      NULL) == PKCS11_RV_NOT_FOUND)
1571 			return PKCS11_CKR_ATTRIBUTE_TYPE_INVALID;
1572 
1573 		/* Check 2 - Is attribute modifiable */
1574 		if (!attribute_is_modifiable(session, &cli_ref, obj, class,
1575 					     function))
1576 			return PKCS11_CKR_ATTRIBUTE_READ_ONLY;
1577 
1578 		/*
1579 		 * Checks for modification in PKCS11_CKA_TOKEN and
1580 		 * PKCS11_CKA_PRIVATE are required for PKCS11_FUNCTION_COPY
1581 		 * only, so skip them for PKCS11_FUNCTION_MODIFY.
1582 		 */
1583 		if (function == PKCS11_FUNCTION_MODIFY)
1584 			continue;
1585 
1586 		/*
1587 		 * An attempt to copy an object to a token will fail for
1588 		 * RO session
1589 		 */
1590 		if (cli_ref.id == PKCS11_CKA_TOKEN &&
1591 		    get_bool(head, PKCS11_CKA_TOKEN)) {
1592 			if (!pkcs11_session_is_read_write(session)) {
1593 				DMSG("Can't copy to token in a RO session");
1594 				return PKCS11_CKR_SESSION_READ_ONLY;
1595 			}
1596 		}
1597 
1598 		if (cli_ref.id == PKCS11_CKA_PRIVATE) {
1599 			bool parent_priv =
1600 				get_bool(obj->attributes, cli_ref.id);
1601 			bool obj_priv = get_bool(head, cli_ref.id);
1602 
1603 			/*
1604 			 * If PKCS11_CKA_PRIVATE is being set to TRUE from
1605 			 * FALSE, user has to be logged in
1606 			 */
1607 			if (!parent_priv && obj_priv) {
1608 				if ((pkcs11_session_is_public(session) ||
1609 				     pkcs11_session_is_so(session)))
1610 					return PKCS11_CKR_USER_NOT_LOGGED_IN;
1611 			}
1612 
1613 			/*
1614 			 * Restriction added - Even for Copy, do not allow
1615 			 * modification of CKA_PRIVATE from TRUE to FALSE
1616 			 */
1617 			if (parent_priv && !obj_priv)
1618 				return PKCS11_CKR_TEMPLATE_INCONSISTENT;
1619 		}
1620 	}
1621 
1622 	return PKCS11_CKR_OK;
1623 }
1624 
1625 static enum pkcs11_rc set_secret_key_data(struct obj_attrs **head, void *data,
1626 					  size_t key_size)
1627 {
1628 	uint32_t size = sizeof(uint32_t);
1629 	uint32_t key_length = 0;
1630 	enum pkcs11_rc rc = PKCS11_CKR_GENERAL_ERROR;
1631 
1632 	/* Get key size if present in template */
1633 	rc = get_attribute(*head, PKCS11_CKA_VALUE_LEN, &key_length, &size);
1634 	if (rc && rc != PKCS11_RV_NOT_FOUND)
1635 		return rc;
1636 
1637 	if (key_length) {
1638 		if (key_size < key_length)
1639 			return PKCS11_CKR_DATA_LEN_RANGE;
1640 	} else {
1641 		key_length = key_size;
1642 		rc = set_attribute(head, PKCS11_CKA_VALUE_LEN, &key_length,
1643 				   sizeof(uint32_t));
1644 		if (rc)
1645 			return rc;
1646 	}
1647 
1648 	/* Now we can check the VALUE_LEN field */
1649 	rc = check_created_attrs(*head, NULL);
1650 	if (rc)
1651 		return rc;
1652 
1653 	/* Remove the default empty value attribute if found */
1654 	rc = remove_empty_attribute(head, PKCS11_CKA_VALUE);
1655 	if (rc != PKCS11_CKR_OK && rc != PKCS11_RV_NOT_FOUND)
1656 		return PKCS11_CKR_GENERAL_ERROR;
1657 
1658 	return add_attribute(head, PKCS11_CKA_VALUE, data, key_length);
1659 }
1660 
1661 enum pkcs11_rc set_key_data(struct obj_attrs **head, void *data,
1662 			    size_t key_size)
1663 {
1664 	switch (get_class(*head)) {
1665 	case PKCS11_CKO_SECRET_KEY:
1666 		return set_secret_key_data(head, data, key_size);
1667 	default:
1668 		return PKCS11_CKR_GENERAL_ERROR;
1669 	}
1670 }
1671