xref: /optee_os/lib/libutee/tee_api_operations.c (revision ade6f848e084d7c63f1e3866d7c059b8a9f9e834)
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2014, STMicroelectronics International N.V.
4  */
5 #include <stdlib.h>
6 #include <string.h>
7 #include <string_ext.h>
8 
9 #include <tee_api.h>
10 #include <tee_api_defines_extensions.h>
11 #include <tee_internal_api_extensions.h>
12 #include <utee_syscalls.h>
13 #include <utee_defines.h>
14 #include <util.h>
15 #include "tee_api_private.h"
16 
17 struct __TEE_OperationHandle {
18 	TEE_OperationInfo info;
19 	TEE_ObjectHandle key1;
20 	TEE_ObjectHandle key2;
21 	uint32_t operationState;/* Operation state : INITIAL or ACTIVE */
22 	uint8_t *buffer;	/* buffer to collect complete blocks */
23 	bool buffer_two_blocks;	/* True if two blocks need to be buffered */
24 	size_t block_size;	/* Block size of cipher */
25 	size_t buffer_offs;	/* Offset in buffer */
26 	uint32_t state;		/* Handle to state in TEE Core */
27 	uint32_t ae_tag_len;	/*
28 				 * tag_len in bytes for AE operation else unused
29 				 */
30 };
31 
32 /* Cryptographic Operations API - Generic Operation Functions */
33 
34 TEE_Result TEE_AllocateOperation(TEE_OperationHandle *operation,
35 				 uint32_t algorithm, uint32_t mode,
36 				 uint32_t maxKeySize)
37 {
38 	TEE_Result res;
39 	TEE_OperationHandle op = TEE_HANDLE_NULL;
40 	uint32_t handle_state = 0;
41 	size_t block_size = 1;
42 	uint32_t req_key_usage;
43 	bool with_private_key = false;
44 	bool buffer_two_blocks = false;
45 
46 	if (!operation)
47 		TEE_Panic(0);
48 
49 	if (algorithm == TEE_ALG_AES_XTS)
50 		handle_state = TEE_HANDLE_FLAG_EXPECT_TWO_KEYS;
51 
52 	/* Check algorithm max key size */
53 	switch (algorithm) {
54 	case TEE_ALG_DSA_SHA1:
55 		if (maxKeySize < 512)
56 			return TEE_ERROR_NOT_SUPPORTED;
57 		if (maxKeySize > 1024)
58 			return TEE_ERROR_NOT_SUPPORTED;
59 		if (maxKeySize % 64 != 0)
60 			return TEE_ERROR_NOT_SUPPORTED;
61 		break;
62 
63 	case TEE_ALG_DSA_SHA224:
64 		if (maxKeySize != 2048)
65 			return TEE_ERROR_NOT_SUPPORTED;
66 		break;
67 
68 	case TEE_ALG_DSA_SHA256:
69 		if (maxKeySize != 2048 && maxKeySize != 3072)
70 			return TEE_ERROR_NOT_SUPPORTED;
71 		break;
72 
73 	case TEE_ALG_ECDSA_P192:
74 	case TEE_ALG_ECDH_P192:
75 		if (maxKeySize != 192)
76 			return TEE_ERROR_NOT_SUPPORTED;
77 		break;
78 
79 	case TEE_ALG_ECDSA_P224:
80 	case TEE_ALG_ECDH_P224:
81 		if (maxKeySize != 224)
82 			return TEE_ERROR_NOT_SUPPORTED;
83 		break;
84 
85 	case TEE_ALG_ECDSA_P256:
86 	case TEE_ALG_ECDH_P256:
87 		if (maxKeySize != 256)
88 			return TEE_ERROR_NOT_SUPPORTED;
89 		break;
90 
91 	case TEE_ALG_ECDSA_P384:
92 	case TEE_ALG_ECDH_P384:
93 		if (maxKeySize != 384)
94 			return TEE_ERROR_NOT_SUPPORTED;
95 		break;
96 
97 	case TEE_ALG_ECDSA_P521:
98 	case TEE_ALG_ECDH_P521:
99 		if (maxKeySize != 521)
100 			return TEE_ERROR_NOT_SUPPORTED;
101 		break;
102 
103 	default:
104 		break;
105 	}
106 
107 	/* Check algorithm mode */
108 	switch (algorithm) {
109 	case TEE_ALG_AES_CTS:
110 	case TEE_ALG_AES_XTS:
111 		buffer_two_blocks = true;
112 		/* FALLTHROUGH */
113 	case TEE_ALG_AES_ECB_NOPAD:
114 	case TEE_ALG_AES_CBC_NOPAD:
115 	case TEE_ALG_AES_CCM:
116 	case TEE_ALG_DES_ECB_NOPAD:
117 	case TEE_ALG_DES_CBC_NOPAD:
118 	case TEE_ALG_DES3_ECB_NOPAD:
119 	case TEE_ALG_DES3_CBC_NOPAD:
120 	case TEE_ALG_SM4_ECB_NOPAD:
121 	case TEE_ALG_SM4_CBC_NOPAD:
122 	case TEE_ALG_SM4_CTR:
123 		if (TEE_ALG_GET_MAIN_ALG(algorithm) == TEE_MAIN_ALGO_AES)
124 			block_size = TEE_AES_BLOCK_SIZE;
125 		else if (TEE_ALG_GET_MAIN_ALG(algorithm) == TEE_MAIN_ALGO_SM4)
126 			block_size = TEE_SM4_BLOCK_SIZE;
127 		else
128 			block_size = TEE_DES_BLOCK_SIZE;
129 		/* FALLTHROUGH */
130 	case TEE_ALG_AES_CTR:
131 	case TEE_ALG_AES_GCM:
132 		if (mode == TEE_MODE_ENCRYPT)
133 			req_key_usage = TEE_USAGE_ENCRYPT;
134 		else if (mode == TEE_MODE_DECRYPT)
135 			req_key_usage = TEE_USAGE_DECRYPT;
136 		else
137 			return TEE_ERROR_NOT_SUPPORTED;
138 		break;
139 
140 #if defined(CFG_CRYPTO_RSASSA_NA1)
141 	case TEE_ALG_RSASSA_PKCS1_V1_5:
142 #endif
143 	case TEE_ALG_RSASSA_PKCS1_V1_5_MD5:
144 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA1:
145 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA224:
146 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA256:
147 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA384:
148 	case TEE_ALG_RSASSA_PKCS1_V1_5_SHA512:
149 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA1:
150 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA224:
151 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256:
152 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA384:
153 	case TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA512:
154 	case TEE_ALG_DSA_SHA1:
155 	case TEE_ALG_DSA_SHA224:
156 	case TEE_ALG_DSA_SHA256:
157 	case TEE_ALG_ECDSA_P192:
158 	case TEE_ALG_ECDSA_P224:
159 	case TEE_ALG_ECDSA_P256:
160 	case TEE_ALG_ECDSA_P384:
161 	case TEE_ALG_ECDSA_P521:
162 		if (mode == TEE_MODE_SIGN) {
163 			with_private_key = true;
164 			req_key_usage = TEE_USAGE_SIGN;
165 		} else if (mode == TEE_MODE_VERIFY) {
166 			req_key_usage = TEE_USAGE_VERIFY;
167 		} else {
168 			return TEE_ERROR_NOT_SUPPORTED;
169 		}
170 		break;
171 
172 	case TEE_ALG_RSAES_PKCS1_V1_5:
173 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA1:
174 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA224:
175 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA256:
176 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA384:
177 	case TEE_ALG_RSAES_PKCS1_OAEP_MGF1_SHA512:
178 		if (mode == TEE_MODE_ENCRYPT) {
179 			req_key_usage = TEE_USAGE_ENCRYPT;
180 		} else if (mode == TEE_MODE_DECRYPT) {
181 			with_private_key = true;
182 			req_key_usage = TEE_USAGE_DECRYPT;
183 		} else {
184 			return TEE_ERROR_NOT_SUPPORTED;
185 		}
186 		break;
187 
188 	case TEE_ALG_RSA_NOPAD:
189 		if (mode == TEE_MODE_ENCRYPT) {
190 			req_key_usage = TEE_USAGE_ENCRYPT | TEE_USAGE_VERIFY;
191 		} else if (mode == TEE_MODE_DECRYPT) {
192 			with_private_key = true;
193 			req_key_usage = TEE_USAGE_DECRYPT | TEE_USAGE_SIGN;
194 		} else {
195 			return TEE_ERROR_NOT_SUPPORTED;
196 		}
197 		break;
198 
199 	case TEE_ALG_DH_DERIVE_SHARED_SECRET:
200 	case TEE_ALG_ECDH_P192:
201 	case TEE_ALG_ECDH_P224:
202 	case TEE_ALG_ECDH_P256:
203 	case TEE_ALG_ECDH_P384:
204 	case TEE_ALG_ECDH_P521:
205 	case TEE_ALG_HKDF_MD5_DERIVE_KEY:
206 	case TEE_ALG_HKDF_SHA1_DERIVE_KEY:
207 	case TEE_ALG_HKDF_SHA224_DERIVE_KEY:
208 	case TEE_ALG_HKDF_SHA256_DERIVE_KEY:
209 	case TEE_ALG_HKDF_SHA384_DERIVE_KEY:
210 	case TEE_ALG_HKDF_SHA512_DERIVE_KEY:
211 	case TEE_ALG_CONCAT_KDF_SHA1_DERIVE_KEY:
212 	case TEE_ALG_CONCAT_KDF_SHA224_DERIVE_KEY:
213 	case TEE_ALG_CONCAT_KDF_SHA256_DERIVE_KEY:
214 	case TEE_ALG_CONCAT_KDF_SHA384_DERIVE_KEY:
215 	case TEE_ALG_CONCAT_KDF_SHA512_DERIVE_KEY:
216 	case TEE_ALG_PBKDF2_HMAC_SHA1_DERIVE_KEY:
217 		if (mode != TEE_MODE_DERIVE)
218 			return TEE_ERROR_NOT_SUPPORTED;
219 		with_private_key = true;
220 		req_key_usage = TEE_USAGE_DERIVE;
221 		break;
222 
223 	case TEE_ALG_MD5:
224 	case TEE_ALG_SHA1:
225 	case TEE_ALG_SHA224:
226 	case TEE_ALG_SHA256:
227 	case TEE_ALG_SHA384:
228 	case TEE_ALG_SHA512:
229 		if (mode != TEE_MODE_DIGEST)
230 			return TEE_ERROR_NOT_SUPPORTED;
231 		/* v1.1: flags always set for digest operations */
232 		handle_state |= TEE_HANDLE_FLAG_KEY_SET;
233 		req_key_usage = 0;
234 		break;
235 
236 	case TEE_ALG_DES_CBC_MAC_NOPAD:
237 	case TEE_ALG_AES_CBC_MAC_NOPAD:
238 	case TEE_ALG_AES_CBC_MAC_PKCS5:
239 	case TEE_ALG_AES_CMAC:
240 	case TEE_ALG_DES_CBC_MAC_PKCS5:
241 	case TEE_ALG_DES3_CBC_MAC_NOPAD:
242 	case TEE_ALG_DES3_CBC_MAC_PKCS5:
243 	case TEE_ALG_HMAC_MD5:
244 	case TEE_ALG_HMAC_SHA1:
245 	case TEE_ALG_HMAC_SHA224:
246 	case TEE_ALG_HMAC_SHA256:
247 	case TEE_ALG_HMAC_SHA384:
248 	case TEE_ALG_HMAC_SHA512:
249 		if (mode != TEE_MODE_MAC)
250 			return TEE_ERROR_NOT_SUPPORTED;
251 		req_key_usage = TEE_USAGE_MAC;
252 		break;
253 
254 	default:
255 		return TEE_ERROR_NOT_SUPPORTED;
256 	}
257 
258 	op = TEE_Malloc(sizeof(*op), TEE_MALLOC_FILL_ZERO);
259 	if (!op)
260 		return TEE_ERROR_OUT_OF_MEMORY;
261 
262 	op->info.algorithm = algorithm;
263 	op->info.operationClass = TEE_ALG_GET_CLASS(algorithm);
264 #ifdef CFG_CRYPTO_RSASSA_NA1
265 	if (algorithm == TEE_ALG_RSASSA_PKCS1_V1_5)
266 		op->info.operationClass = TEE_OPERATION_ASYMMETRIC_SIGNATURE;
267 #endif
268 	op->info.mode = mode;
269 	op->info.maxKeySize = maxKeySize;
270 	op->info.requiredKeyUsage = req_key_usage;
271 	op->info.handleState = handle_state;
272 
273 	if (block_size > 1) {
274 		size_t buffer_size = block_size;
275 
276 		if (buffer_two_blocks)
277 			buffer_size *= 2;
278 
279 		op->buffer = TEE_Malloc(buffer_size,
280 					TEE_USER_MEM_HINT_NO_FILL_ZERO);
281 		if (op->buffer == NULL) {
282 			res = TEE_ERROR_OUT_OF_MEMORY;
283 			goto out;
284 		}
285 	}
286 	op->block_size = block_size;
287 	op->buffer_two_blocks = buffer_two_blocks;
288 
289 	if (TEE_ALG_GET_CLASS(algorithm) != TEE_OPERATION_DIGEST) {
290 		uint32_t mks = maxKeySize;
291 		TEE_ObjectType key_type = TEE_ALG_GET_KEY_TYPE(algorithm,
292 						       with_private_key);
293 
294 		/*
295 		 * If two keys are expected the max key size is the sum of
296 		 * the size of both keys.
297 		 */
298 		if (op->info.handleState & TEE_HANDLE_FLAG_EXPECT_TWO_KEYS)
299 			mks /= 2;
300 
301 		res = TEE_AllocateTransientObject(key_type, mks, &op->key1);
302 		if (res != TEE_SUCCESS)
303 			goto out;
304 
305 		if (op->info.handleState & TEE_HANDLE_FLAG_EXPECT_TWO_KEYS) {
306 			res = TEE_AllocateTransientObject(key_type, mks,
307 							  &op->key2);
308 			if (res != TEE_SUCCESS)
309 				goto out;
310 		}
311 	}
312 
313 	res = utee_cryp_state_alloc(algorithm, mode, (unsigned long)op->key1,
314 				    (unsigned long)op->key2, &op->state);
315 	if (res != TEE_SUCCESS)
316 		goto out;
317 
318 	/*
319 	 * Initialize digest operations
320 	 * Other multi-stage operations initialized w/ TEE_xxxInit functions
321 	 * Non-applicable on asymmetric operations
322 	 */
323 	if (TEE_ALG_GET_CLASS(algorithm) == TEE_OPERATION_DIGEST) {
324 		res = utee_hash_init(op->state, NULL, 0);
325 		if (res != TEE_SUCCESS)
326 			goto out;
327 		/* v1.1: flags always set for digest operations */
328 		op->info.handleState |= TEE_HANDLE_FLAG_INITIALIZED;
329 	}
330 
331 	op->operationState = TEE_OPERATION_STATE_INITIAL;
332 
333 	*operation = op;
334 
335 out:
336 	if (res != TEE_SUCCESS) {
337 		if (res != TEE_ERROR_OUT_OF_MEMORY &&
338 		    res != TEE_ERROR_NOT_SUPPORTED)
339 			TEE_Panic(res);
340 		if (op) {
341 			if (op->state) {
342 				TEE_FreeOperation(op);
343 			} else {
344 				TEE_Free(op->buffer);
345 				TEE_FreeTransientObject(op->key1);
346 				TEE_FreeTransientObject(op->key2);
347 				TEE_Free(op);
348 			}
349 		}
350 	}
351 
352 	return res;
353 }
354 
355 void TEE_FreeOperation(TEE_OperationHandle operation)
356 {
357 	TEE_Result res;
358 
359 	if (operation == TEE_HANDLE_NULL)
360 		TEE_Panic(0);
361 
362 	/*
363 	 * Note that keys should not be freed here, since they are
364 	 * claimed by the operation they will be freed by
365 	 * utee_cryp_state_free().
366 	 */
367 	res = utee_cryp_state_free(operation->state);
368 	if (res != TEE_SUCCESS)
369 		TEE_Panic(res);
370 
371 	TEE_Free(operation->buffer);
372 	TEE_Free(operation);
373 }
374 
375 void TEE_GetOperationInfo(TEE_OperationHandle operation,
376 			  TEE_OperationInfo *operationInfo)
377 {
378 	if (operation == TEE_HANDLE_NULL)
379 		TEE_Panic(0);
380 
381 	if (!operationInfo)
382 		TEE_Panic(0);
383 
384 	*operationInfo = operation->info;
385 }
386 
387 TEE_Result TEE_GetOperationInfoMultiple(TEE_OperationHandle operation,
388 			  TEE_OperationInfoMultiple *operationInfoMultiple,
389 			  uint32_t *operationSize)
390 {
391 	TEE_Result res = TEE_SUCCESS;
392 	TEE_ObjectInfo key_info1;
393 	TEE_ObjectInfo key_info2;
394 	uint32_t num_of_keys;
395 	size_t n;
396 
397 	if (operation == TEE_HANDLE_NULL) {
398 		res = TEE_ERROR_BAD_PARAMETERS;
399 		goto out;
400 	}
401 
402 	if (!operationInfoMultiple) {
403 		res = TEE_ERROR_BAD_PARAMETERS;
404 		goto out;
405 	}
406 
407 	if (!operationSize) {
408 		res = TEE_ERROR_BAD_PARAMETERS;
409 		goto out;
410 	}
411 
412 	num_of_keys = (*operationSize-sizeof(TEE_OperationInfoMultiple))/
413 			sizeof(TEE_OperationInfoKey);
414 
415 	if (num_of_keys > 2) {
416 		res = TEE_ERROR_BAD_PARAMETERS;
417 		goto out;
418 	}
419 
420 	/* Two keys flag (TEE_ALG_AES_XTS only) */
421 	if ((operation->info.handleState & TEE_HANDLE_FLAG_EXPECT_TWO_KEYS) !=
422 	    0 &&
423 	    (num_of_keys != 2)) {
424 		res = TEE_ERROR_SHORT_BUFFER;
425 		goto out;
426 	}
427 
428 	/* Clear */
429 	for (n = 0; n < num_of_keys; n++) {
430 		operationInfoMultiple->keyInformation[n].keySize = 0;
431 		operationInfoMultiple->keyInformation[n].requiredKeyUsage = 0;
432 	}
433 
434 	if (num_of_keys == 2) {
435 		res = TEE_GetObjectInfo1(operation->key2, &key_info2);
436 		/* Key2 is not a valid handle */
437 		if (res != TEE_SUCCESS)
438 			goto out;
439 
440 		operationInfoMultiple->keyInformation[1].keySize =
441 			key_info2.keySize;
442 		operationInfoMultiple->keyInformation[1].requiredKeyUsage =
443 			operation->info.requiredKeyUsage;
444 	}
445 
446 	if (num_of_keys >= 1) {
447 		res = TEE_GetObjectInfo1(operation->key1, &key_info1);
448 		/* Key1 is not a valid handle */
449 		if (res != TEE_SUCCESS) {
450 			if (num_of_keys == 2) {
451 				operationInfoMultiple->keyInformation[1].
452 							keySize = 0;
453 				operationInfoMultiple->keyInformation[1].
454 							requiredKeyUsage = 0;
455 			}
456 			goto out;
457 		}
458 
459 		operationInfoMultiple->keyInformation[0].keySize =
460 			key_info1.keySize;
461 		operationInfoMultiple->keyInformation[0].requiredKeyUsage =
462 			operation->info.requiredKeyUsage;
463 	}
464 
465 	/* No key */
466 	operationInfoMultiple->algorithm = operation->info.algorithm;
467 	operationInfoMultiple->operationClass = operation->info.operationClass;
468 	operationInfoMultiple->mode = operation->info.mode;
469 	operationInfoMultiple->digestLength = operation->info.digestLength;
470 	operationInfoMultiple->maxKeySize = operation->info.maxKeySize;
471 	operationInfoMultiple->handleState = operation->info.handleState;
472 	operationInfoMultiple->operationState = operation->operationState;
473 	operationInfoMultiple->numberOfKeys = num_of_keys;
474 
475 out:
476 	if (res != TEE_SUCCESS &&
477 	    res != TEE_ERROR_SHORT_BUFFER)
478 		TEE_Panic(res);
479 
480 	return res;
481 }
482 
483 void TEE_ResetOperation(TEE_OperationHandle operation)
484 {
485 	TEE_Result res;
486 
487 	if (operation == TEE_HANDLE_NULL)
488 		TEE_Panic(0);
489 
490 	if (!(operation->info.handleState & TEE_HANDLE_FLAG_KEY_SET))
491 			TEE_Panic(0);
492 
493 	operation->operationState = TEE_OPERATION_STATE_INITIAL;
494 
495 	if (operation->info.operationClass == TEE_OPERATION_DIGEST) {
496 		res = utee_hash_init(operation->state, NULL, 0);
497 		if (res != TEE_SUCCESS)
498 			TEE_Panic(res);
499 		operation->info.handleState |= TEE_HANDLE_FLAG_INITIALIZED;
500 	} else {
501 		operation->info.handleState &= ~TEE_HANDLE_FLAG_INITIALIZED;
502 	}
503 }
504 
505 TEE_Result TEE_SetOperationKey(TEE_OperationHandle operation,
506 			       TEE_ObjectHandle key)
507 {
508 	TEE_Result res;
509 	uint32_t key_size = 0;
510 	TEE_ObjectInfo key_info;
511 
512 	if (operation == TEE_HANDLE_NULL) {
513 		res = TEE_ERROR_BAD_PARAMETERS;
514 		goto out;
515 	}
516 
517 	if (operation->operationState != TEE_OPERATION_STATE_INITIAL) {
518 		res = TEE_ERROR_BAD_PARAMETERS;
519 		goto out;
520 	}
521 
522 	if (key == TEE_HANDLE_NULL) {
523 		/* Operation key cleared */
524 		TEE_ResetTransientObject(operation->key1);
525 		res = TEE_ERROR_BAD_PARAMETERS;
526 		goto out;
527 	}
528 
529 	/* No key for digest operation */
530 	if (operation->info.operationClass == TEE_OPERATION_DIGEST) {
531 		res = TEE_ERROR_BAD_PARAMETERS;
532 		goto out;
533 	}
534 
535 	/* Two keys flag not expected (TEE_ALG_AES_XTS excluded) */
536 	if ((operation->info.handleState & TEE_HANDLE_FLAG_EXPECT_TWO_KEYS) !=
537 	    0) {
538 		res = TEE_ERROR_BAD_PARAMETERS;
539 		goto out;
540 	}
541 
542 	res = TEE_GetObjectInfo1(key, &key_info);
543 	/* Key is not a valid handle */
544 	if (res != TEE_SUCCESS)
545 		goto out;
546 
547 	/* Supplied key has to meet required usage */
548 	if ((key_info.objectUsage & operation->info.requiredKeyUsage) !=
549 	    operation->info.requiredKeyUsage) {
550 		res = TEE_ERROR_BAD_PARAMETERS;
551 		goto out;
552 	}
553 
554 	if (operation->info.maxKeySize < key_info.keySize) {
555 		res = TEE_ERROR_BAD_PARAMETERS;
556 		goto out;
557 	}
558 
559 	key_size = key_info.keySize;
560 
561 	TEE_ResetTransientObject(operation->key1);
562 	operation->info.handleState &= ~TEE_HANDLE_FLAG_KEY_SET;
563 
564 	res = TEE_CopyObjectAttributes1(operation->key1, key);
565 	if (res != TEE_SUCCESS)
566 		goto out;
567 
568 	operation->info.handleState |= TEE_HANDLE_FLAG_KEY_SET;
569 
570 	operation->info.keySize = key_size;
571 
572 out:
573 	if (res != TEE_SUCCESS  &&
574 	    res != TEE_ERROR_CORRUPT_OBJECT &&
575 	    res != TEE_ERROR_STORAGE_NOT_AVAILABLE)
576 		TEE_Panic(res);
577 
578 	return res;
579 }
580 
581 TEE_Result TEE_SetOperationKey2(TEE_OperationHandle operation,
582 				TEE_ObjectHandle key1, TEE_ObjectHandle key2)
583 {
584 	TEE_Result res;
585 	uint32_t key_size = 0;
586 	TEE_ObjectInfo key_info1;
587 	TEE_ObjectInfo key_info2;
588 
589 	if (operation == TEE_HANDLE_NULL) {
590 		res = TEE_ERROR_BAD_PARAMETERS;
591 		goto out;
592 	}
593 
594 	if (operation->operationState != TEE_OPERATION_STATE_INITIAL) {
595 		res = TEE_ERROR_BAD_PARAMETERS;
596 		goto out;
597 	}
598 
599 	/*
600 	 * Key1/Key2 and/or are not initialized and
601 	 * Either both keys are NULL or both are not NULL
602 	 */
603 	if (key1 == TEE_HANDLE_NULL || key2 == TEE_HANDLE_NULL) {
604 		/* Clear operation key1 (if needed) */
605 		if (key1 == TEE_HANDLE_NULL)
606 			TEE_ResetTransientObject(operation->key1);
607 		/* Clear operation key2 (if needed) */
608 		if (key2 == TEE_HANDLE_NULL)
609 			TEE_ResetTransientObject(operation->key2);
610 		res = TEE_ERROR_BAD_PARAMETERS;
611 		goto out;
612 	}
613 
614 	/* No key for digest operation */
615 	if (operation->info.operationClass == TEE_OPERATION_DIGEST) {
616 		res = TEE_ERROR_BAD_PARAMETERS;
617 		goto out;
618 	}
619 
620 	/* Two keys flag expected (TEE_ALG_AES_XTS only) */
621 	if ((operation->info.handleState & TEE_HANDLE_FLAG_EXPECT_TWO_KEYS) ==
622 	    0) {
623 		res = TEE_ERROR_BAD_PARAMETERS;
624 		goto out;
625 	}
626 
627 	res = TEE_GetObjectInfo1(key1, &key_info1);
628 	/* Key1 is not a valid handle */
629 	if (res != TEE_SUCCESS)
630 		goto out;
631 
632 	/* Supplied key has to meet required usage */
633 	if ((key_info1.objectUsage & operation->info.
634 	     requiredKeyUsage) != operation->info.requiredKeyUsage) {
635 		res = TEE_ERROR_BAD_PARAMETERS;
636 		goto out;
637 	}
638 
639 	res = TEE_GetObjectInfo1(key2, &key_info2);
640 	/* Key2 is not a valid handle */
641 	if (res != TEE_SUCCESS) {
642 		if (res == TEE_ERROR_CORRUPT_OBJECT)
643 			res = TEE_ERROR_CORRUPT_OBJECT_2;
644 		goto out;
645 	}
646 
647 	/* Supplied key has to meet required usage */
648 	if ((key_info2.objectUsage & operation->info.
649 	     requiredKeyUsage) != operation->info.requiredKeyUsage) {
650 		res = TEE_ERROR_BAD_PARAMETERS;
651 		goto out;
652 	}
653 
654 	/*
655 	 * AES-XTS (the only multi key algorithm supported, requires the
656 	 * keys to be of equal size.
657 	 */
658 	if (operation->info.algorithm == TEE_ALG_AES_XTS &&
659 	    key_info1.keySize != key_info2.keySize) {
660 		res = TEE_ERROR_BAD_PARAMETERS;
661 		goto out;
662 
663 	}
664 
665 	if (operation->info.maxKeySize < key_info1.keySize) {
666 		res = TEE_ERROR_BAD_PARAMETERS;
667 		goto out;
668 	}
669 
670 	/*
671 	 * Odd that only the size of one key should be reported while
672 	 * size of two key are used when allocating the operation.
673 	 */
674 	key_size = key_info1.keySize;
675 
676 	TEE_ResetTransientObject(operation->key1);
677 	TEE_ResetTransientObject(operation->key2);
678 	operation->info.handleState &= ~TEE_HANDLE_FLAG_KEY_SET;
679 
680 	res = TEE_CopyObjectAttributes1(operation->key1, key1);
681 	if (res != TEE_SUCCESS)
682 		goto out;
683 
684 	res = TEE_CopyObjectAttributes1(operation->key2, key2);
685 	if (res != TEE_SUCCESS) {
686 		if (res == TEE_ERROR_CORRUPT_OBJECT)
687 			res = TEE_ERROR_CORRUPT_OBJECT_2;
688 		goto out;
689 	}
690 
691 	operation->info.handleState |= TEE_HANDLE_FLAG_KEY_SET;
692 
693 	operation->info.keySize = key_size;
694 
695 out:
696 	if (res != TEE_SUCCESS  &&
697 	    res != TEE_ERROR_CORRUPT_OBJECT &&
698 	    res != TEE_ERROR_CORRUPT_OBJECT_2 &&
699 	    res != TEE_ERROR_STORAGE_NOT_AVAILABLE &&
700 	    res != TEE_ERROR_STORAGE_NOT_AVAILABLE_2)
701 		TEE_Panic(res);
702 
703 	return res;
704 }
705 
706 void TEE_CopyOperation(TEE_OperationHandle dst_op, TEE_OperationHandle src_op)
707 {
708 	TEE_Result res;
709 
710 	if (dst_op == TEE_HANDLE_NULL || src_op == TEE_HANDLE_NULL)
711 		TEE_Panic(0);
712 	if (dst_op->info.algorithm != src_op->info.algorithm)
713 		TEE_Panic(0);
714 	if (src_op->info.operationClass != TEE_OPERATION_DIGEST) {
715 		TEE_ObjectHandle key1 = TEE_HANDLE_NULL;
716 		TEE_ObjectHandle key2 = TEE_HANDLE_NULL;
717 
718 		if (src_op->info.handleState & TEE_HANDLE_FLAG_KEY_SET) {
719 			key1 = src_op->key1;
720 			key2 = src_op->key2;
721 		}
722 
723 		if ((src_op->info.handleState &
724 		     TEE_HANDLE_FLAG_EXPECT_TWO_KEYS) == 0) {
725 			TEE_SetOperationKey(dst_op, key1);
726 		} else {
727 			TEE_SetOperationKey2(dst_op, key1, key2);
728 		}
729 	}
730 	dst_op->info.handleState = src_op->info.handleState;
731 	dst_op->info.keySize = src_op->info.keySize;
732 	dst_op->operationState = src_op->operationState;
733 
734 	if (dst_op->buffer_two_blocks != src_op->buffer_two_blocks ||
735 	    dst_op->block_size != src_op->block_size)
736 		TEE_Panic(0);
737 
738 	if (dst_op->buffer != NULL) {
739 		if (src_op->buffer == NULL)
740 			TEE_Panic(0);
741 
742 		memcpy(dst_op->buffer, src_op->buffer, src_op->buffer_offs);
743 		dst_op->buffer_offs = src_op->buffer_offs;
744 	} else if (src_op->buffer != NULL) {
745 		TEE_Panic(0);
746 	}
747 
748 	res = utee_cryp_state_copy(dst_op->state, src_op->state);
749 	if (res != TEE_SUCCESS)
750 		TEE_Panic(res);
751 }
752 
753 /* Cryptographic Operations API - Message Digest Functions */
754 
755 static void init_hash_operation(TEE_OperationHandle operation, const void *IV,
756 				uint32_t IVLen)
757 {
758 	TEE_Result res;
759 
760 	/*
761 	 * Note : IV and IVLen are never used in current implementation
762 	 * This is why coherent values of IV and IVLen are not checked
763 	 */
764 	res = utee_hash_init(operation->state, IV, IVLen);
765 	if (res != TEE_SUCCESS)
766 		TEE_Panic(res);
767 	operation->buffer_offs = 0;
768 	operation->info.handleState |= TEE_HANDLE_FLAG_INITIALIZED;
769 }
770 
771 void TEE_DigestUpdate(TEE_OperationHandle operation,
772 		      const void *chunk, uint32_t chunkSize)
773 {
774 	TEE_Result res = TEE_ERROR_GENERIC;
775 
776 	if (operation == TEE_HANDLE_NULL ||
777 	    operation->info.operationClass != TEE_OPERATION_DIGEST)
778 		TEE_Panic(0);
779 
780 	operation->operationState = TEE_OPERATION_STATE_ACTIVE;
781 
782 	res = utee_hash_update(operation->state, chunk, chunkSize);
783 	if (res != TEE_SUCCESS)
784 		TEE_Panic(res);
785 }
786 
787 TEE_Result TEE_DigestDoFinal(TEE_OperationHandle operation, const void *chunk,
788 			     uint32_t chunkLen, void *hash, uint32_t *hashLen)
789 {
790 	TEE_Result res;
791 	uint64_t hl;
792 
793 	if ((operation == TEE_HANDLE_NULL) ||
794 	    (!chunk && chunkLen) ||
795 	    !hash ||
796 	    !hashLen ||
797 	    (operation->info.operationClass != TEE_OPERATION_DIGEST)) {
798 		res = TEE_ERROR_BAD_PARAMETERS;
799 		goto out;
800 	}
801 
802 	hl = *hashLen;
803 	res = utee_hash_final(operation->state, chunk, chunkLen, hash, &hl);
804 	*hashLen = hl;
805 	if (res != TEE_SUCCESS)
806 		goto out;
807 
808 	/* Reset operation state */
809 	init_hash_operation(operation, NULL, 0);
810 
811 	operation->operationState = TEE_OPERATION_STATE_INITIAL;
812 
813 out:
814 	if (res != TEE_SUCCESS &&
815 	    res != TEE_ERROR_SHORT_BUFFER)
816 		TEE_Panic(res);
817 
818 	return res;
819 }
820 
821 /* Cryptographic Operations API - Symmetric Cipher Functions */
822 
823 void TEE_CipherInit(TEE_OperationHandle operation, const void *IV,
824 		    uint32_t IVLen)
825 {
826 	TEE_Result res;
827 
828 	if (operation == TEE_HANDLE_NULL)
829 		TEE_Panic(0);
830 
831 	if (operation->info.operationClass != TEE_OPERATION_CIPHER)
832 		TEE_Panic(0);
833 
834 	if (!(operation->info.handleState & TEE_HANDLE_FLAG_KEY_SET) ||
835 	    !(operation->key1))
836 		TEE_Panic(0);
837 
838 	if (operation->operationState != TEE_OPERATION_STATE_INITIAL)
839 		TEE_ResetOperation(operation);
840 
841 	operation->operationState = TEE_OPERATION_STATE_ACTIVE;
842 
843 	res = utee_cipher_init(operation->state, IV, IVLen);
844 	if (res != TEE_SUCCESS)
845 		TEE_Panic(res);
846 
847 	operation->buffer_offs = 0;
848 	operation->info.handleState |= TEE_HANDLE_FLAG_INITIALIZED;
849 }
850 
851 static TEE_Result tee_buffer_update(
852 		TEE_OperationHandle op,
853 		TEE_Result(*update_func)(unsigned long state, const void *src,
854 				size_t slen, void *dst, uint64_t *dlen),
855 		const void *src_data, size_t src_len,
856 		void *dest_data, uint64_t *dest_len)
857 {
858 	TEE_Result res;
859 	const uint8_t *src = src_data;
860 	size_t slen = src_len;
861 	uint8_t *dst = dest_data;
862 	size_t dlen = *dest_len;
863 	size_t acc_dlen = 0;
864 	uint64_t tmp_dlen;
865 	size_t l;
866 	size_t buffer_size;
867 	size_t buffer_left;
868 
869 	if (!src) {
870 		if (slen)
871 			TEE_Panic(0);
872 		goto out;
873 	}
874 
875 	if (op->buffer_two_blocks) {
876 		buffer_size = op->block_size * 2;
877 		buffer_left = 1;
878 	} else {
879 		buffer_size = op->block_size;
880 		buffer_left = 0;
881 	}
882 
883 	if (op->buffer_offs > 0) {
884 		/* Fill up complete block */
885 		if (op->buffer_offs < op->block_size)
886 			l = MIN(slen, op->block_size - op->buffer_offs);
887 		else
888 			l = MIN(slen, buffer_size - op->buffer_offs);
889 		memcpy(op->buffer + op->buffer_offs, src, l);
890 		op->buffer_offs += l;
891 		src += l;
892 		slen -= l;
893 		if ((op->buffer_offs % op->block_size) != 0)
894 			goto out;	/* Nothing left to do */
895 	}
896 
897 	/* If we can feed from buffer */
898 	if ((op->buffer_offs > 0) &&
899 	    ((op->buffer_offs + slen) >= (buffer_size + buffer_left))) {
900 		l = ROUNDUP(op->buffer_offs + slen - buffer_size,
901 				op->block_size);
902 		l = MIN(op->buffer_offs, l);
903 		tmp_dlen = dlen;
904 		res = update_func(op->state, op->buffer, l, dst, &tmp_dlen);
905 		if (res != TEE_SUCCESS)
906 			TEE_Panic(res);
907 		dst += tmp_dlen;
908 		dlen -= tmp_dlen;
909 		acc_dlen += tmp_dlen;
910 		op->buffer_offs -= l;
911 		if (op->buffer_offs > 0) {
912 			/*
913 			 * Slen is small enough to be contained in rest buffer.
914 			 */
915 			memcpy(op->buffer, op->buffer + l, buffer_size - l);
916 			memcpy(op->buffer + op->buffer_offs, src, slen);
917 			op->buffer_offs += slen;
918 			goto out;	/* Nothing left to do */
919 		}
920 	}
921 
922 	if (slen >= (buffer_size + buffer_left)) {
923 		/* Buffer is empty, feed as much as possible from src */
924 		if (op->info.algorithm == TEE_ALG_AES_CTS)
925 			l = ROUNDUP(slen - buffer_size, op->block_size);
926 		else
927 			l = ROUNDUP(slen - buffer_size + 1, op->block_size);
928 
929 		tmp_dlen = dlen;
930 		res = update_func(op->state, src, l, dst, &tmp_dlen);
931 		if (res != TEE_SUCCESS)
932 			TEE_Panic(res);
933 		src += l;
934 		slen -= l;
935 		dst += tmp_dlen;
936 		dlen -= tmp_dlen;
937 		acc_dlen += tmp_dlen;
938 	}
939 
940 	/* Slen is small enough to be contained in buffer. */
941 	memcpy(op->buffer + op->buffer_offs, src, slen);
942 	op->buffer_offs += slen;
943 
944 out:
945 	*dest_len = acc_dlen;
946 	return TEE_SUCCESS;
947 }
948 
949 TEE_Result TEE_CipherUpdate(TEE_OperationHandle operation, const void *srcData,
950 			    uint32_t srcLen, void *destData, uint32_t *destLen)
951 {
952 	TEE_Result res;
953 	size_t req_dlen;
954 	uint64_t dl;
955 
956 	if (operation == TEE_HANDLE_NULL ||
957 	    (srcData == NULL && srcLen != 0) ||
958 	    destLen == NULL ||
959 	    (destData == NULL && *destLen != 0)) {
960 		res = TEE_ERROR_BAD_PARAMETERS;
961 		goto out;
962 	}
963 
964 	if (operation->info.operationClass != TEE_OPERATION_CIPHER) {
965 		res = TEE_ERROR_BAD_PARAMETERS;
966 		goto out;
967 	}
968 
969 	if ((operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
970 		res = TEE_ERROR_BAD_PARAMETERS;
971 		goto out;
972 	}
973 
974 	if (operation->operationState != TEE_OPERATION_STATE_ACTIVE) {
975 		res = TEE_ERROR_BAD_PARAMETERS;
976 		goto out;
977 	}
978 
979 	if (!srcData && !srcLen) {
980 		*destLen = 0;
981 		res = TEE_SUCCESS;
982 		goto out;
983 	}
984 
985 	/* Calculate required dlen */
986 	if (operation->block_size > 1) {
987 		req_dlen = ((operation->buffer_offs + srcLen) /
988 			    operation->block_size) * operation->block_size;
989 	} else {
990 		req_dlen = srcLen;
991 	}
992 	if (operation->buffer_two_blocks) {
993 		if (req_dlen > operation->block_size * 2)
994 			req_dlen -= operation->block_size * 2;
995 		else
996 			req_dlen = 0;
997 	}
998 	/*
999 	 * Check that required destLen is big enough before starting to feed
1000 	 * data to the algorithm. Errors during feeding of data are fatal as we
1001 	 * can't restore sync with this API.
1002 	 */
1003 	if (*destLen < req_dlen) {
1004 		*destLen = req_dlen;
1005 		res = TEE_ERROR_SHORT_BUFFER;
1006 		goto out;
1007 	}
1008 
1009 	dl = *destLen;
1010 	if (operation->block_size > 1) {
1011 		res = tee_buffer_update(operation, utee_cipher_update, srcData,
1012 					srcLen, destData, &dl);
1013 	} else {
1014 		if (srcLen > 0) {
1015 			res = utee_cipher_update(operation->state, srcData,
1016 						 srcLen, destData, &dl);
1017 		} else {
1018 			res = TEE_SUCCESS;
1019 			dl = 0;
1020 		}
1021 	}
1022 	*destLen = dl;
1023 
1024 out:
1025 	if (res != TEE_SUCCESS &&
1026 	    res != TEE_ERROR_SHORT_BUFFER)
1027 		TEE_Panic(res);
1028 
1029 	return res;
1030 }
1031 
1032 TEE_Result TEE_CipherDoFinal(TEE_OperationHandle operation,
1033 			     const void *srcData, uint32_t srcLen,
1034 			     void *destData, uint32_t *destLen)
1035 {
1036 	TEE_Result res;
1037 	uint8_t *dst = destData;
1038 	size_t acc_dlen = 0;
1039 	uint64_t tmp_dlen;
1040 	size_t req_dlen;
1041 
1042 	if (operation == TEE_HANDLE_NULL ||
1043 	    (srcData == NULL && srcLen != 0) ||
1044 	    destLen == NULL ||
1045 	    (destData == NULL && *destLen != 0)) {
1046 		res = TEE_ERROR_BAD_PARAMETERS;
1047 		goto out;
1048 	}
1049 
1050 	if (operation->info.operationClass != TEE_OPERATION_CIPHER) {
1051 		res = TEE_ERROR_BAD_PARAMETERS;
1052 		goto out;
1053 	}
1054 
1055 	if ((operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
1056 		res = TEE_ERROR_BAD_PARAMETERS;
1057 		goto out;
1058 	}
1059 
1060 	if (operation->operationState != TEE_OPERATION_STATE_ACTIVE) {
1061 		res = TEE_ERROR_BAD_PARAMETERS;
1062 		goto out;
1063 	}
1064 
1065 	/*
1066 	 * Check that the final block doesn't require padding for those
1067 	 * algorithms that requires client to supply padding.
1068 	 */
1069 	if (operation->info.algorithm == TEE_ALG_AES_ECB_NOPAD ||
1070 	    operation->info.algorithm == TEE_ALG_AES_CBC_NOPAD ||
1071 	    operation->info.algorithm == TEE_ALG_DES_ECB_NOPAD ||
1072 	    operation->info.algorithm == TEE_ALG_DES_CBC_NOPAD ||
1073 	    operation->info.algorithm == TEE_ALG_DES3_ECB_NOPAD ||
1074 	    operation->info.algorithm == TEE_ALG_DES3_CBC_NOPAD ||
1075 	    operation->info.algorithm == TEE_ALG_SM4_ECB_NOPAD ||
1076 	    operation->info.algorithm == TEE_ALG_SM4_CBC_NOPAD) {
1077 		if (((operation->buffer_offs + srcLen) % operation->block_size)
1078 		    != 0) {
1079 			res = TEE_ERROR_BAD_PARAMETERS;
1080 			goto out;
1081 		}
1082 	}
1083 
1084 	/*
1085 	 * Check that required destLen is big enough before starting to feed
1086 	 * data to the algorithm. Errors during feeding of data are fatal as we
1087 	 * can't restore sync with this API.
1088 	 */
1089 	if (operation->block_size > 1) {
1090 		req_dlen = operation->buffer_offs + srcLen;
1091 	} else {
1092 		req_dlen = srcLen;
1093 	}
1094 	if (*destLen < req_dlen) {
1095 		*destLen = req_dlen;
1096 		res = TEE_ERROR_SHORT_BUFFER;
1097 		goto out;
1098 	}
1099 
1100 	tmp_dlen = *destLen - acc_dlen;
1101 	if (operation->block_size > 1) {
1102 		res = tee_buffer_update(operation, utee_cipher_update,
1103 					srcData, srcLen, dst, &tmp_dlen);
1104 		if (res != TEE_SUCCESS)
1105 			goto out;
1106 
1107 		dst += tmp_dlen;
1108 		acc_dlen += tmp_dlen;
1109 
1110 		tmp_dlen = *destLen - acc_dlen;
1111 		res = utee_cipher_final(operation->state, operation->buffer,
1112 					operation->buffer_offs, dst, &tmp_dlen);
1113 	} else {
1114 		res = utee_cipher_final(operation->state, srcData,
1115 					srcLen, dst, &tmp_dlen);
1116 	}
1117 	if (res != TEE_SUCCESS)
1118 		goto out;
1119 
1120 	acc_dlen += tmp_dlen;
1121 	*destLen = acc_dlen;
1122 
1123 	operation->info.handleState &= ~TEE_HANDLE_FLAG_INITIALIZED;
1124 
1125 	operation->operationState = TEE_OPERATION_STATE_INITIAL;
1126 
1127 out:
1128 	if (res != TEE_SUCCESS &&
1129 	    res != TEE_ERROR_SHORT_BUFFER)
1130 		TEE_Panic(res);
1131 
1132 	return res;
1133 }
1134 
1135 /* Cryptographic Operations API - MAC Functions */
1136 
1137 void TEE_MACInit(TEE_OperationHandle operation, const void *IV, uint32_t IVLen)
1138 {
1139 	if (operation == TEE_HANDLE_NULL)
1140 		TEE_Panic(0);
1141 
1142 	if (operation->info.operationClass != TEE_OPERATION_MAC)
1143 		TEE_Panic(0);
1144 
1145 	if (!(operation->info.handleState & TEE_HANDLE_FLAG_KEY_SET) ||
1146 	    !(operation->key1))
1147 		TEE_Panic(0);
1148 
1149 	if (operation->operationState != TEE_OPERATION_STATE_INITIAL)
1150 		TEE_ResetOperation(operation);
1151 
1152 	operation->operationState = TEE_OPERATION_STATE_ACTIVE;
1153 
1154 	init_hash_operation(operation, IV, IVLen);
1155 }
1156 
1157 void TEE_MACUpdate(TEE_OperationHandle operation, const void *chunk,
1158 		   uint32_t chunkSize)
1159 {
1160 	TEE_Result res;
1161 
1162 	if (operation == TEE_HANDLE_NULL || (chunk == NULL && chunkSize != 0))
1163 		TEE_Panic(0);
1164 
1165 	if (operation->info.operationClass != TEE_OPERATION_MAC)
1166 		TEE_Panic(0);
1167 
1168 	if ((operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED) == 0)
1169 		TEE_Panic(0);
1170 
1171 	if (operation->operationState != TEE_OPERATION_STATE_ACTIVE)
1172 		TEE_Panic(0);
1173 
1174 	res = utee_hash_update(operation->state, chunk, chunkSize);
1175 	if (res != TEE_SUCCESS)
1176 		TEE_Panic(res);
1177 }
1178 
1179 TEE_Result TEE_MACComputeFinal(TEE_OperationHandle operation,
1180 			       const void *message, uint32_t messageLen,
1181 			       void *mac, uint32_t *macLen)
1182 {
1183 	TEE_Result res;
1184 	uint64_t ml;
1185 
1186 	if (operation == TEE_HANDLE_NULL ||
1187 	    (message == NULL && messageLen != 0) ||
1188 	    mac == NULL ||
1189 	    macLen == NULL) {
1190 		res = TEE_ERROR_BAD_PARAMETERS;
1191 		goto out;
1192 	}
1193 
1194 	if (operation->info.operationClass != TEE_OPERATION_MAC) {
1195 		res = TEE_ERROR_BAD_PARAMETERS;
1196 		goto out;
1197 	}
1198 
1199 	if ((operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
1200 		res = TEE_ERROR_BAD_PARAMETERS;
1201 		goto out;
1202 	}
1203 
1204 	if (operation->operationState != TEE_OPERATION_STATE_ACTIVE) {
1205 		res = TEE_ERROR_BAD_PARAMETERS;
1206 		goto out;
1207 	}
1208 
1209 	ml = *macLen;
1210 	res = utee_hash_final(operation->state, message, messageLen, mac, &ml);
1211 	*macLen = ml;
1212 	if (res != TEE_SUCCESS)
1213 		goto out;
1214 
1215 	operation->info.handleState &= ~TEE_HANDLE_FLAG_INITIALIZED;
1216 
1217 	operation->operationState = TEE_OPERATION_STATE_INITIAL;
1218 
1219 out:
1220 	if (res != TEE_SUCCESS &&
1221 	    res != TEE_ERROR_SHORT_BUFFER)
1222 		TEE_Panic(res);
1223 
1224 	return res;
1225 }
1226 
1227 TEE_Result TEE_MACCompareFinal(TEE_OperationHandle operation,
1228 			       const void *message, uint32_t messageLen,
1229 			       const void *mac, uint32_t macLen)
1230 {
1231 	TEE_Result res;
1232 	uint8_t computed_mac[TEE_MAX_HASH_SIZE];
1233 	uint32_t computed_mac_size = TEE_MAX_HASH_SIZE;
1234 
1235 	if (operation->info.operationClass != TEE_OPERATION_MAC) {
1236 		res = TEE_ERROR_BAD_PARAMETERS;
1237 		goto out;
1238 	}
1239 
1240 	if ((operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
1241 		res = TEE_ERROR_BAD_PARAMETERS;
1242 		goto out;
1243 	}
1244 
1245 	if (operation->operationState != TEE_OPERATION_STATE_ACTIVE) {
1246 		res = TEE_ERROR_BAD_PARAMETERS;
1247 		goto out;
1248 	}
1249 
1250 	res = TEE_MACComputeFinal(operation, message, messageLen, computed_mac,
1251 				  &computed_mac_size);
1252 	if (res != TEE_SUCCESS)
1253 		goto out;
1254 
1255 	if (computed_mac_size != macLen) {
1256 		res = TEE_ERROR_MAC_INVALID;
1257 		goto out;
1258 	}
1259 
1260 	if (consttime_memcmp(mac, computed_mac, computed_mac_size) != 0) {
1261 		res = TEE_ERROR_MAC_INVALID;
1262 		goto out;
1263 	}
1264 
1265 	operation->operationState = TEE_OPERATION_STATE_INITIAL;
1266 
1267 out:
1268 	if (res != TEE_SUCCESS &&
1269 	    res != TEE_ERROR_MAC_INVALID)
1270 		TEE_Panic(res);
1271 
1272 	return res;
1273 }
1274 
1275 /* Cryptographic Operations API - Authenticated Encryption Functions */
1276 
1277 TEE_Result TEE_AEInit(TEE_OperationHandle operation, const void *nonce,
1278 		      uint32_t nonceLen, uint32_t tagLen, uint32_t AADLen,
1279 		      uint32_t payloadLen)
1280 {
1281 	TEE_Result res;
1282 
1283 	if (operation == TEE_HANDLE_NULL || nonce == NULL) {
1284 		res = TEE_ERROR_BAD_PARAMETERS;
1285 		goto out;
1286 	}
1287 
1288 	if (operation->info.operationClass != TEE_OPERATION_AE) {
1289 		res = TEE_ERROR_BAD_PARAMETERS;
1290 		goto out;
1291 	}
1292 
1293 	if (operation->operationState != TEE_OPERATION_STATE_INITIAL) {
1294 		res = TEE_ERROR_BAD_PARAMETERS;
1295 		goto out;
1296 	}
1297 
1298 	/*
1299 	 * AES-CCM tag len is specified by AES-CCM spec and handled in TEE Core
1300 	 * in the implementation. But AES-GCM spec doesn't specify the tag len
1301 	 * according to the same principle so we have to check here instead to
1302 	 * be GP compliant.
1303 	 */
1304 	if (operation->info.algorithm == TEE_ALG_AES_GCM) {
1305 		/*
1306 		 * From GP spec: For AES-GCM, can be 128, 120, 112, 104, or 96
1307 		 */
1308 		if (tagLen < 96 || tagLen > 128 || (tagLen % 8 != 0)) {
1309 			res = TEE_ERROR_NOT_SUPPORTED;
1310 			goto out;
1311 		}
1312 	}
1313 
1314 	res = utee_authenc_init(operation->state, nonce, nonceLen,
1315 				tagLen / 8, AADLen, payloadLen);
1316 	if (res != TEE_SUCCESS)
1317 		goto out;
1318 
1319 	operation->ae_tag_len = tagLen / 8;
1320 	operation->info.handleState |= TEE_HANDLE_FLAG_INITIALIZED;
1321 
1322 out:
1323 	if (res != TEE_SUCCESS &&
1324 	    res != TEE_ERROR_NOT_SUPPORTED)
1325 			TEE_Panic(res);
1326 
1327 	return res;
1328 }
1329 
1330 void TEE_AEUpdateAAD(TEE_OperationHandle operation, const void *AADdata,
1331 		     uint32_t AADdataLen)
1332 {
1333 	TEE_Result res;
1334 
1335 	if (operation == TEE_HANDLE_NULL ||
1336 	    (AADdata == NULL && AADdataLen != 0))
1337 		TEE_Panic(0);
1338 
1339 	if (operation->info.operationClass != TEE_OPERATION_AE)
1340 		TEE_Panic(0);
1341 
1342 	if ((operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED) == 0)
1343 		TEE_Panic(0);
1344 
1345 	res = utee_authenc_update_aad(operation->state, AADdata, AADdataLen);
1346 
1347 	operation->operationState = TEE_OPERATION_STATE_ACTIVE;
1348 
1349 	if (res != TEE_SUCCESS)
1350 		TEE_Panic(res);
1351 }
1352 
1353 TEE_Result TEE_AEUpdate(TEE_OperationHandle operation, const void *srcData,
1354 			uint32_t srcLen, void *destData, uint32_t *destLen)
1355 {
1356 	TEE_Result res;
1357 	size_t req_dlen;
1358 	uint64_t dl;
1359 
1360 	if (operation == TEE_HANDLE_NULL ||
1361 	    (srcData == NULL && srcLen != 0) ||
1362 	    destLen == NULL ||
1363 	    (destData == NULL && *destLen != 0)) {
1364 		res = TEE_ERROR_BAD_PARAMETERS;
1365 		goto out;
1366 	}
1367 
1368 	if (operation->info.operationClass != TEE_OPERATION_AE) {
1369 		res = TEE_ERROR_BAD_PARAMETERS;
1370 		goto out;
1371 	}
1372 
1373 	if ((operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
1374 		res = TEE_ERROR_BAD_PARAMETERS;
1375 		goto out;
1376 	}
1377 
1378 	if (!srcData && !srcLen) {
1379 		*destLen = 0;
1380 		res = TEE_SUCCESS;
1381 		goto out;
1382 	}
1383 
1384 	/*
1385 	 * Check that required destLen is big enough before starting to feed
1386 	 * data to the algorithm. Errors during feeding of data are fatal as we
1387 	 * can't restore sync with this API.
1388 	 */
1389 	if (operation->block_size > 1) {
1390 		req_dlen = ROUNDDOWN(operation->buffer_offs + srcLen,
1391 				     operation->block_size);
1392 	} else {
1393 		req_dlen = srcLen;
1394 	}
1395 
1396 	if (*destLen < req_dlen) {
1397 		*destLen = req_dlen;
1398 		res = TEE_ERROR_SHORT_BUFFER;
1399 		goto out;
1400 	}
1401 
1402 	dl = *destLen;
1403 	if (operation->block_size > 1) {
1404 		res = tee_buffer_update(operation, utee_authenc_update_payload,
1405 					srcData, srcLen, destData, &dl);
1406 	} else {
1407 		if (srcLen > 0) {
1408 			res = utee_authenc_update_payload(operation->state,
1409 							  srcData, srcLen,
1410 							  destData, &dl);
1411 		} else {
1412 			dl = 0;
1413 			res = TEE_SUCCESS;
1414 		}
1415 	}
1416 	if (res != TEE_SUCCESS)
1417 		goto out;
1418 
1419 	*destLen = dl;
1420 
1421 	operation->operationState = TEE_OPERATION_STATE_ACTIVE;
1422 
1423 out:
1424 	if (res != TEE_SUCCESS &&
1425 	    res != TEE_ERROR_SHORT_BUFFER)
1426 			TEE_Panic(res);
1427 
1428 	return res;
1429 }
1430 
1431 TEE_Result TEE_AEEncryptFinal(TEE_OperationHandle operation,
1432 			      const void *srcData, uint32_t srcLen,
1433 			      void *destData, uint32_t *destLen, void *tag,
1434 			      uint32_t *tagLen)
1435 {
1436 	TEE_Result res;
1437 	uint8_t *dst = destData;
1438 	size_t acc_dlen = 0;
1439 	uint64_t tmp_dlen;
1440 	size_t req_dlen;
1441 	uint64_t tl;
1442 
1443 	if (operation == TEE_HANDLE_NULL ||
1444 	    (srcData == NULL && srcLen != 0) ||
1445 	    destLen == NULL ||
1446 	    (destData == NULL && *destLen != 0) ||
1447 	    tag == NULL || tagLen == NULL) {
1448 		res = TEE_ERROR_BAD_PARAMETERS;
1449 		goto out;
1450 	}
1451 
1452 	if (operation->info.operationClass != TEE_OPERATION_AE) {
1453 		res = TEE_ERROR_BAD_PARAMETERS;
1454 		goto out;
1455 	}
1456 
1457 	if ((operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
1458 		res = TEE_ERROR_BAD_PARAMETERS;
1459 		goto out;
1460 	}
1461 
1462 	/*
1463 	 * Check that required destLen is big enough before starting to feed
1464 	 * data to the algorithm. Errors during feeding of data are fatal as we
1465 	 * can't restore sync with this API.
1466 	 *
1467 	 * Need to check this before update_payload since sync would be lost if
1468 	 * we return short buffer after that.
1469 	 */
1470 	res = TEE_ERROR_GENERIC;
1471 
1472 	req_dlen = operation->buffer_offs + srcLen;
1473 	if (*destLen < req_dlen) {
1474 		*destLen = req_dlen;
1475 		res = TEE_ERROR_SHORT_BUFFER;
1476 	}
1477 
1478 	if (*tagLen < operation->ae_tag_len) {
1479 		*tagLen = operation->ae_tag_len;
1480 		res = TEE_ERROR_SHORT_BUFFER;
1481 	}
1482 
1483 	if (res == TEE_ERROR_SHORT_BUFFER)
1484 		goto out;
1485 
1486 	tl = *tagLen;
1487 	tmp_dlen = *destLen - acc_dlen;
1488 	if (operation->block_size > 1) {
1489 		res = tee_buffer_update(operation, utee_authenc_update_payload,
1490 					srcData, srcLen, dst, &tmp_dlen);
1491 		if (res != TEE_SUCCESS)
1492 			goto out;
1493 
1494 		dst += tmp_dlen;
1495 		acc_dlen += tmp_dlen;
1496 
1497 		tmp_dlen = *destLen - acc_dlen;
1498 		res = utee_authenc_enc_final(operation->state,
1499 					     operation->buffer,
1500 					     operation->buffer_offs, dst,
1501 					     &tmp_dlen, tag, &tl);
1502 	} else {
1503 		res = utee_authenc_enc_final(operation->state, srcData,
1504 					     srcLen, dst, &tmp_dlen,
1505 					     tag, &tl);
1506 	}
1507 	*tagLen = tl;
1508 	if (res != TEE_SUCCESS)
1509 		goto out;
1510 
1511 	acc_dlen += tmp_dlen;
1512 	*destLen = acc_dlen;
1513 
1514 	operation->info.handleState &= ~TEE_HANDLE_FLAG_INITIALIZED;
1515 
1516 	operation->operationState = TEE_OPERATION_STATE_INITIAL;
1517 
1518 out:
1519 	if (res != TEE_SUCCESS &&
1520 	    res != TEE_ERROR_SHORT_BUFFER)
1521 			TEE_Panic(res);
1522 
1523 	return res;
1524 }
1525 
1526 TEE_Result TEE_AEDecryptFinal(TEE_OperationHandle operation,
1527 			      const void *srcData, uint32_t srcLen,
1528 			      void *destData, uint32_t *destLen, void *tag,
1529 			      uint32_t tagLen)
1530 {
1531 	TEE_Result res;
1532 	uint8_t *dst = destData;
1533 	size_t acc_dlen = 0;
1534 	uint64_t tmp_dlen;
1535 	size_t req_dlen;
1536 
1537 	if (operation == TEE_HANDLE_NULL ||
1538 	    (srcData == NULL && srcLen != 0) ||
1539 	    destLen == NULL ||
1540 	    (destData == NULL && *destLen != 0) ||
1541 	    (tag == NULL && tagLen != 0)) {
1542 		res = TEE_ERROR_BAD_PARAMETERS;
1543 		goto out;
1544 	}
1545 
1546 	if (operation->info.operationClass != TEE_OPERATION_AE) {
1547 		res = TEE_ERROR_BAD_PARAMETERS;
1548 		goto out;
1549 	}
1550 
1551 	if ((operation->info.handleState & TEE_HANDLE_FLAG_INITIALIZED) == 0) {
1552 		res = TEE_ERROR_BAD_PARAMETERS;
1553 		goto out;
1554 	}
1555 
1556 	/*
1557 	 * Check that required destLen is big enough before starting to feed
1558 	 * data to the algorithm. Errors during feeding of data are fatal as we
1559 	 * can't restore sync with this API.
1560 	 */
1561 	req_dlen = operation->buffer_offs + srcLen;
1562 	if (*destLen < req_dlen) {
1563 		*destLen = req_dlen;
1564 		res = TEE_ERROR_SHORT_BUFFER;
1565 		goto out;
1566 	}
1567 
1568 	tmp_dlen = *destLen - acc_dlen;
1569 	if (operation->block_size > 1) {
1570 		res = tee_buffer_update(operation, utee_authenc_update_payload,
1571 					srcData, srcLen, dst, &tmp_dlen);
1572 		if (res != TEE_SUCCESS)
1573 			goto out;
1574 
1575 		dst += tmp_dlen;
1576 		acc_dlen += tmp_dlen;
1577 
1578 		tmp_dlen = *destLen - acc_dlen;
1579 		res = utee_authenc_dec_final(operation->state,
1580 					     operation->buffer,
1581 					     operation->buffer_offs, dst,
1582 					     &tmp_dlen, tag, tagLen);
1583 	} else {
1584 		res = utee_authenc_dec_final(operation->state, srcData,
1585 					     srcLen, dst, &tmp_dlen,
1586 					     tag, tagLen);
1587 	}
1588 	if (res != TEE_SUCCESS)
1589 		goto out;
1590 
1591 	/* Supplied tagLen should match what we initiated with */
1592 	if (tagLen != operation->ae_tag_len)
1593 		res = TEE_ERROR_MAC_INVALID;
1594 
1595 	acc_dlen += tmp_dlen;
1596 	*destLen = acc_dlen;
1597 
1598 	operation->info.handleState &= ~TEE_HANDLE_FLAG_INITIALIZED;
1599 
1600 	operation->operationState = TEE_OPERATION_STATE_INITIAL;
1601 
1602 out:
1603 	if (res != TEE_SUCCESS &&
1604 	    res != TEE_ERROR_SHORT_BUFFER &&
1605 	    res != TEE_ERROR_MAC_INVALID)
1606 			TEE_Panic(res);
1607 
1608 	return res;
1609 }
1610 
1611 /* Cryptographic Operations API - Asymmetric Functions */
1612 
1613 TEE_Result TEE_AsymmetricEncrypt(TEE_OperationHandle operation,
1614 				 const TEE_Attribute *params,
1615 				 uint32_t paramCount, const void *srcData,
1616 				 uint32_t srcLen, void *destData,
1617 				 uint32_t *destLen)
1618 {
1619 	TEE_Result res;
1620 	struct utee_attribute ua[paramCount];
1621 	uint64_t dl;
1622 
1623 	if (operation == TEE_HANDLE_NULL || (srcData == NULL && srcLen != 0) ||
1624 	    destLen == NULL || (destData == NULL && *destLen != 0))
1625 		TEE_Panic(0);
1626 	if (params == NULL && paramCount != 0)
1627 		TEE_Panic(0);
1628 	if (!operation->key1)
1629 		TEE_Panic(0);
1630 	if (operation->info.operationClass != TEE_OPERATION_ASYMMETRIC_CIPHER)
1631 		TEE_Panic(0);
1632 	if (operation->info.mode != TEE_MODE_ENCRYPT)
1633 		TEE_Panic(0);
1634 
1635 	__utee_from_attr(ua, params, paramCount);
1636 	dl = *destLen;
1637 	res = utee_asymm_operate(operation->state, ua, paramCount, srcData,
1638 				 srcLen, destData, &dl);
1639 	*destLen = dl;
1640 
1641 	if (res != TEE_SUCCESS &&
1642 	    res != TEE_ERROR_SHORT_BUFFER &&
1643 	    res != TEE_ERROR_BAD_PARAMETERS)
1644 		TEE_Panic(res);
1645 
1646 	return res;
1647 }
1648 
1649 TEE_Result TEE_AsymmetricDecrypt(TEE_OperationHandle operation,
1650 				 const TEE_Attribute *params,
1651 				 uint32_t paramCount, const void *srcData,
1652 				 uint32_t srcLen, void *destData,
1653 				 uint32_t *destLen)
1654 {
1655 	TEE_Result res;
1656 	struct utee_attribute ua[paramCount];
1657 	uint64_t dl;
1658 
1659 	if (operation == TEE_HANDLE_NULL || (srcData == NULL && srcLen != 0) ||
1660 	    destLen == NULL || (destData == NULL && *destLen != 0))
1661 		TEE_Panic(0);
1662 	if (params == NULL && paramCount != 0)
1663 		TEE_Panic(0);
1664 	if (!operation->key1)
1665 		TEE_Panic(0);
1666 	if (operation->info.operationClass != TEE_OPERATION_ASYMMETRIC_CIPHER)
1667 		TEE_Panic(0);
1668 	if (operation->info.mode != TEE_MODE_DECRYPT)
1669 		TEE_Panic(0);
1670 
1671 	__utee_from_attr(ua, params, paramCount);
1672 	dl = *destLen;
1673 	res = utee_asymm_operate(operation->state, ua, paramCount, srcData,
1674 				 srcLen, destData, &dl);
1675 	*destLen = dl;
1676 
1677 	if (res != TEE_SUCCESS &&
1678 	    res != TEE_ERROR_SHORT_BUFFER &&
1679 	    res != TEE_ERROR_BAD_PARAMETERS)
1680 		TEE_Panic(res);
1681 
1682 	return res;
1683 }
1684 
1685 TEE_Result TEE_AsymmetricSignDigest(TEE_OperationHandle operation,
1686 				    const TEE_Attribute *params,
1687 				    uint32_t paramCount, const void *digest,
1688 				    uint32_t digestLen, void *signature,
1689 				    uint32_t *signatureLen)
1690 {
1691 	TEE_Result res;
1692 	struct utee_attribute ua[paramCount];
1693 	uint64_t sl;
1694 
1695 	if (operation == TEE_HANDLE_NULL ||
1696 	    (digest == NULL && digestLen != 0) ||
1697 	    signature == NULL || signatureLen == NULL)
1698 		TEE_Panic(0);
1699 	if (params == NULL && paramCount != 0)
1700 		TEE_Panic(0);
1701 	if (!operation->key1)
1702 		TEE_Panic(0);
1703 	if (operation->info.operationClass !=
1704 	    TEE_OPERATION_ASYMMETRIC_SIGNATURE)
1705 		TEE_Panic(0);
1706 	if (operation->info.mode != TEE_MODE_SIGN)
1707 		TEE_Panic(0);
1708 
1709 	__utee_from_attr(ua, params, paramCount);
1710 	sl = *signatureLen;
1711 	res = utee_asymm_operate(operation->state, ua, paramCount, digest,
1712 				 digestLen, signature, &sl);
1713 	*signatureLen = sl;
1714 
1715 	if (res != TEE_SUCCESS && res != TEE_ERROR_SHORT_BUFFER)
1716 		TEE_Panic(res);
1717 
1718 	return res;
1719 }
1720 
1721 TEE_Result TEE_AsymmetricVerifyDigest(TEE_OperationHandle operation,
1722 				      const TEE_Attribute *params,
1723 				      uint32_t paramCount, const void *digest,
1724 				      uint32_t digestLen,
1725 				      const void *signature,
1726 				      uint32_t signatureLen)
1727 {
1728 	TEE_Result res;
1729 	struct utee_attribute ua[paramCount];
1730 
1731 	if (operation == TEE_HANDLE_NULL ||
1732 	    (digest == NULL && digestLen != 0) ||
1733 	    (signature == NULL && signatureLen != 0))
1734 		TEE_Panic(0);
1735 	if (params == NULL && paramCount != 0)
1736 		TEE_Panic(0);
1737 	if (!operation->key1)
1738 		TEE_Panic(0);
1739 	if (operation->info.operationClass !=
1740 	    TEE_OPERATION_ASYMMETRIC_SIGNATURE)
1741 		TEE_Panic(0);
1742 	if (operation->info.mode != TEE_MODE_VERIFY)
1743 		TEE_Panic(0);
1744 
1745 	__utee_from_attr(ua, params, paramCount);
1746 	res = utee_asymm_verify(operation->state, ua, paramCount, digest,
1747 				digestLen, signature, signatureLen);
1748 
1749 	if (res != TEE_SUCCESS && res != TEE_ERROR_SIGNATURE_INVALID)
1750 		TEE_Panic(res);
1751 
1752 	return res;
1753 }
1754 
1755 /* Cryptographic Operations API - Key Derivation Functions */
1756 
1757 void TEE_DeriveKey(TEE_OperationHandle operation,
1758 		   const TEE_Attribute *params, uint32_t paramCount,
1759 		   TEE_ObjectHandle derivedKey)
1760 {
1761 	TEE_Result res;
1762 	TEE_ObjectInfo key_info;
1763 	struct utee_attribute ua[paramCount];
1764 
1765 	if (operation == TEE_HANDLE_NULL || derivedKey == 0)
1766 		TEE_Panic(0);
1767 	if (params == NULL && paramCount != 0)
1768 		TEE_Panic(0);
1769 	if (TEE_ALG_GET_CLASS(operation->info.algorithm) !=
1770 	    TEE_OPERATION_KEY_DERIVATION)
1771 		TEE_Panic(0);
1772 
1773 	if (operation->info.operationClass != TEE_OPERATION_KEY_DERIVATION)
1774 		TEE_Panic(0);
1775 	if (!operation->key1)
1776 		TEE_Panic(0);
1777 	if (operation->info.mode != TEE_MODE_DERIVE)
1778 		TEE_Panic(0);
1779 	if ((operation->info.handleState & TEE_HANDLE_FLAG_KEY_SET) == 0)
1780 		TEE_Panic(0);
1781 
1782 	res = utee_cryp_obj_get_info((unsigned long)derivedKey, &key_info);
1783 	if (res != TEE_SUCCESS)
1784 		TEE_Panic(res);
1785 
1786 	if (key_info.objectType != TEE_TYPE_GENERIC_SECRET)
1787 		TEE_Panic(0);
1788 	if ((key_info.handleFlags & TEE_HANDLE_FLAG_INITIALIZED) != 0)
1789 		TEE_Panic(0);
1790 
1791 	__utee_from_attr(ua, params, paramCount);
1792 	res = utee_cryp_derive_key(operation->state, ua, paramCount,
1793 				   (unsigned long)derivedKey);
1794 	if (res != TEE_SUCCESS)
1795 		TEE_Panic(res);
1796 }
1797 
1798 /* Cryptographic Operations API - Random Number Generation Functions */
1799 
1800 void TEE_GenerateRandom(void *randomBuffer, uint32_t randomBufferLen)
1801 {
1802 	TEE_Result res;
1803 
1804 	res = utee_cryp_random_number_generate(randomBuffer, randomBufferLen);
1805 	if (res != TEE_SUCCESS)
1806 		TEE_Panic(res);
1807 }
1808 
1809 int rand(void)
1810 {
1811 	int rc;
1812 
1813 	TEE_GenerateRandom(&rc, sizeof(rc));
1814 
1815 	/*
1816 	 * RAND_MAX is the larges int, INT_MAX which is all bits but the
1817 	 * highest bit set.
1818 	 */
1819 	return rc & RAND_MAX;
1820 }
1821