1 // SPDX-License-Identifier: BSD-2-Clause 2 /* 3 * Copyright (c) 2014-2019, Linaro Limited 4 * Copyright (c) 2021, SumUp Services GmbH 5 */ 6 7 #include <assert.h> 8 #include <crypto/crypto.h> 9 #include <crypto/crypto_impl.h> 10 #include <stdlib.h> 11 #include <string.h> 12 #include <tee_api_types.h> 13 #include <tomcrypt_private.h> 14 #include <utee_defines.h> 15 #include <util.h> 16 17 struct ltc_omac_ctx { 18 struct crypto_mac_ctx ctx; 19 int cipher_idx; 20 omac_state state; 21 }; 22 23 static const struct crypto_mac_ops ltc_omac_ops; 24 25 static struct ltc_omac_ctx *to_omac_ctx(struct crypto_mac_ctx *ctx) 26 { 27 assert(ctx && ctx->ops == <c_omac_ops); 28 29 return container_of(ctx, struct ltc_omac_ctx, ctx); 30 } 31 32 static TEE_Result ltc_omac_init(struct crypto_mac_ctx *ctx, const uint8_t *key, 33 size_t len) 34 { 35 struct ltc_omac_ctx *hc = to_omac_ctx(ctx); 36 37 if (omac_init(&hc->state, hc->cipher_idx, key, len) == CRYPT_OK) 38 return TEE_SUCCESS; 39 else 40 return TEE_ERROR_BAD_STATE; 41 } 42 43 static TEE_Result ltc_omac_update(struct crypto_mac_ctx *ctx, 44 const uint8_t *data, size_t len) 45 { 46 if (omac_process(&to_omac_ctx(ctx)->state, data, len) == CRYPT_OK) 47 return TEE_SUCCESS; 48 else 49 return TEE_ERROR_BAD_STATE; 50 } 51 52 static TEE_Result ltc_omac_final(struct crypto_mac_ctx *ctx, uint8_t *digest, 53 size_t len) 54 { 55 unsigned long l = len; 56 57 if (omac_done(&to_omac_ctx(ctx)->state, digest, &l) == CRYPT_OK) 58 return TEE_SUCCESS; 59 else 60 return TEE_ERROR_BAD_STATE; 61 } 62 63 static void ltc_omac_free_ctx(struct crypto_mac_ctx *ctx) 64 { 65 free(to_omac_ctx(ctx)); 66 } 67 68 static void ltc_omac_copy_state(struct crypto_mac_ctx *dst_ctx, 69 struct crypto_mac_ctx *src_ctx) 70 { 71 struct ltc_omac_ctx *src = to_omac_ctx(src_ctx); 72 struct ltc_omac_ctx *dst = to_omac_ctx(dst_ctx); 73 74 assert(src->cipher_idx == dst->cipher_idx); 75 dst->state = src->state; 76 } 77 78 static const struct crypto_mac_ops ltc_omac_ops = { 79 .init = ltc_omac_init, 80 .update = ltc_omac_update, 81 .final = ltc_omac_final, 82 .free_ctx = ltc_omac_free_ctx, 83 .copy_state = ltc_omac_copy_state, 84 }; 85 86 static TEE_Result crypto_common_cmac_alloc_ctx(struct crypto_mac_ctx **ctx_ret, 87 const char *cipher) 88 { 89 struct ltc_omac_ctx *ctx = NULL; 90 int cipher_idx = find_cipher(cipher); 91 92 if (!ctx_ret) 93 return TEE_ERROR_BAD_PARAMETERS; 94 95 if (cipher_idx < 0) 96 return TEE_ERROR_NOT_SUPPORTED; 97 98 ctx = calloc(1, sizeof(*ctx)); 99 if (!ctx) 100 return TEE_ERROR_OUT_OF_MEMORY; 101 102 ctx->ctx.ops = <c_omac_ops; 103 ctx->cipher_idx = cipher_idx; 104 *ctx_ret = &ctx->ctx; 105 106 return TEE_SUCCESS; 107 } 108 109 TEE_Result crypto_aes_cmac_alloc_ctx(struct crypto_mac_ctx **ctx_ret) 110 { 111 return crypto_common_cmac_alloc_ctx(ctx_ret, "aes"); 112 } 113 114 TEE_Result crypto_des3_cmac_alloc_ctx(struct crypto_mac_ctx **ctx_ret) 115 { 116 return crypto_common_cmac_alloc_ctx(ctx_ret, "3des"); 117 } 118