1 /*
2  * Copyright 2018-2024 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 /*
11  * See SP800-185 "Appendix A - KMAC, .... in Terms of Keccak[c]"
12  *
13  * Inputs are:
14  *    K = Key                  (len(K) < 2^2040 bits)
15  *    X = Input
16  *    L = Output length        (0 <= L < 2^2040 bits)
17  *    S = Customization String Default="" (len(S) < 2^2040 bits)
18  *
19  * KMAC128(K, X, L, S)
20  * {
21  *     newX = bytepad(encode_string(K), 168) ||  X || right_encode(L).
22  *     T = bytepad(encode_string("KMAC") || encode_string(S), 168).
23  *     return KECCAK[256](T || newX || 00, L).
24  * }
25  *
26  * KMAC256(K, X, L, S)
27  * {
28  *     newX = bytepad(encode_string(K), 136) ||  X || right_encode(L).
29  *     T = bytepad(encode_string("KMAC") || encode_string(S), 136).
30  *     return KECCAK[512](T || newX || 00, L).
31  * }
32  *
33  * KMAC128XOF(K, X, L, S)
34  * {
35  *     newX = bytepad(encode_string(K), 168) ||  X || right_encode(0).
36  *     T = bytepad(encode_string("KMAC") || encode_string(S), 168).
37  *     return KECCAK[256](T || newX || 00, L).
38  * }
39  *
40  * KMAC256XOF(K, X, L, S)
41  * {
42  *     newX = bytepad(encode_string(K), 136) ||  X || right_encode(0).
43  *     T = bytepad(encode_string("KMAC") || encode_string(S), 136).
44  *     return KECCAK[512](T || newX || 00, L).
45  * }
46  *
47  */
48 
49 #include <stdlib.h>
50 #include <string.h>
51 #include <openssl/core_dispatch.h>
52 #include <openssl/core_names.h>
53 #include <openssl/params.h>
54 #include <openssl/evp.h>
55 #include <openssl/err.h>
56 #include <openssl/proverr.h>
57 #include <openssl/fips_names.h>
58 #include "prov/securitycheck.h"
59 #include "prov/implementations.h"
60 #include "prov/provider_ctx.h"
61 #include "prov/provider_util.h"
62 #include "prov/providercommon.h"
63 #include "internal/cryptlib.h" /* ossl_assert */
64 
65 /*
66  * Forward declaration of everything implemented here.  This is not strictly
67  * necessary for the compiler, but provides an assurance that the signatures
68  * of the functions in the dispatch table are correct.
69  */
70 static OSSL_FUNC_mac_newctx_fn kmac128_new;
71 static OSSL_FUNC_mac_newctx_fn kmac256_new;
72 static OSSL_FUNC_mac_dupctx_fn kmac_dup;
73 static OSSL_FUNC_mac_freectx_fn kmac_free;
74 static OSSL_FUNC_mac_gettable_ctx_params_fn kmac_gettable_ctx_params;
75 static OSSL_FUNC_mac_get_ctx_params_fn kmac_get_ctx_params;
76 static OSSL_FUNC_mac_settable_ctx_params_fn kmac_settable_ctx_params;
77 static OSSL_FUNC_mac_set_ctx_params_fn kmac_set_ctx_params;
78 static OSSL_FUNC_mac_init_fn kmac_init;
79 static OSSL_FUNC_mac_update_fn kmac_update;
80 static OSSL_FUNC_mac_final_fn kmac_final;
81 
82 #define KMAC_MAX_BLOCKSIZE ((1600 - 128 * 2) / 8) /* 168 */
83 
84 /*
85  * Length encoding will be  a 1 byte size + length in bits (3 bytes max)
86  * This gives a range of 0..0XFFFFFF bits = 2097151 bytes).
87  */
88 #define KMAC_MAX_OUTPUT_LEN (0xFFFFFF / 8)
89 #define KMAC_MAX_ENCODED_HEADER_LEN (1 + 3)
90 
91 /*
92  * Restrict the maximum length of the customisation string.  This must not
93  * exceed 64 bits = 8k bytes.
94  */
95 #define KMAC_MAX_CUSTOM 512
96 
97 /* Maximum size of encoded custom string */
98 #define KMAC_MAX_CUSTOM_ENCODED (KMAC_MAX_CUSTOM + KMAC_MAX_ENCODED_HEADER_LEN)
99 
100 /* Maximum key size in bytes = 512 (4096 bits) */
101 #define KMAC_MAX_KEY 512
102 #define KMAC_MIN_KEY 4
103 
104 /*
105  * Maximum Encoded Key size will be padded to a multiple of the blocksize
106  * i.e KMAC_MAX_KEY + KMAC_MAX_ENCODED_HEADER_LEN = 512 + 4
107  * Padded to a multiple of KMAC_MAX_BLOCKSIZE
108  */
109 #define KMAC_MAX_KEY_ENCODED (KMAC_MAX_BLOCKSIZE * 4)
110 
111 /* Fixed value of encode_string("KMAC") */
112 static const unsigned char kmac_string[] = {
113     0x01, 0x20, 0x4B, 0x4D, 0x41, 0x43
114 };
115 
116 #define KMAC_FLAG_XOF_MODE          1
117 
118 struct kmac_data_st {
119     void  *provctx;
120     EVP_MD_CTX *ctx;
121     PROV_DIGEST digest;
122     size_t out_len;
123     size_t key_len;
124     size_t custom_len;
125     /* If xof_mode = 1 then we use right_encode(0) */
126     int xof_mode;
127     /* key and custom are stored in encoded form */
128     unsigned char key[KMAC_MAX_KEY_ENCODED];
129     unsigned char custom[KMAC_MAX_CUSTOM_ENCODED];
130 #ifdef FIPS_MODULE
131     /*
132      * 'internal' is set to 1 if KMAC is used inside another algorithm such as a
133      * KDF. In this case it is the parent algorithm that is responsible for
134      * performing any conditional FIPS indicator related checks for KMAC.
135      */
136     int internal;
137 #endif
138     OSSL_FIPS_IND_DECLARE
139 };
140 
141 static int encode_string(unsigned char *out, size_t out_max_len, size_t *out_len,
142                          const unsigned char *in, size_t in_len);
143 static int right_encode(unsigned char *out, size_t out_max_len, size_t *out_len,
144                         size_t bits);
145 static int bytepad(unsigned char *out, size_t *out_len,
146                    const unsigned char *in1, size_t in1_len,
147                    const unsigned char *in2, size_t in2_len,
148                    size_t w);
149 static int kmac_bytepad_encode_key(unsigned char *out, size_t out_max_len,
150                                    size_t *out_len,
151                                    const unsigned char *in, size_t in_len,
152                                    size_t w);
153 
kmac_free(void * vmacctx)154 static void kmac_free(void *vmacctx)
155 {
156     struct kmac_data_st *kctx = vmacctx;
157 
158     if (kctx != NULL) {
159         EVP_MD_CTX_free(kctx->ctx);
160         ossl_prov_digest_reset(&kctx->digest);
161         OPENSSL_cleanse(kctx->key, kctx->key_len);
162         OPENSSL_cleanse(kctx->custom, kctx->custom_len);
163         OPENSSL_free(kctx);
164     }
165 }
166 
167 /*
168  * We have KMAC implemented as a hash, which we can use instead of
169  * reimplementing the EVP functionality with direct use of
170  * keccak_mac_init() and friends.
171  */
kmac_new(void * provctx)172 static struct kmac_data_st *kmac_new(void *provctx)
173 {
174     struct kmac_data_st *kctx;
175 
176     if (!ossl_prov_is_running())
177         return NULL;
178 
179     if ((kctx = OPENSSL_zalloc(sizeof(*kctx))) == NULL
180             || (kctx->ctx = EVP_MD_CTX_new()) == NULL) {
181         kmac_free(kctx);
182         return NULL;
183     }
184     kctx->provctx = provctx;
185     OSSL_FIPS_IND_INIT(kctx)
186     return kctx;
187 }
188 
kmac_fetch_new(void * provctx,const OSSL_PARAM * params)189 static void *kmac_fetch_new(void *provctx, const OSSL_PARAM *params)
190 {
191     struct kmac_data_st *kctx = kmac_new(provctx);
192     int md_size;
193 
194     if (kctx == NULL)
195         return 0;
196     if (!ossl_prov_digest_load_from_params(&kctx->digest, params,
197                                       PROV_LIBCTX_OF(provctx))) {
198         kmac_free(kctx);
199         return 0;
200     }
201 
202     md_size = EVP_MD_get_size(ossl_prov_digest_md(&kctx->digest));
203     if (md_size <= 0) {
204         kmac_free(kctx);
205         return 0;
206     }
207     kctx->out_len = (size_t)md_size;
208     return kctx;
209 }
210 
kmac128_new(void * provctx)211 static void *kmac128_new(void *provctx)
212 {
213     static const OSSL_PARAM kmac128_params[] = {
214         OSSL_PARAM_utf8_string("digest", OSSL_DIGEST_NAME_KECCAK_KMAC128,
215                                sizeof(OSSL_DIGEST_NAME_KECCAK_KMAC128)),
216         OSSL_PARAM_END
217     };
218     return kmac_fetch_new(provctx, kmac128_params);
219 }
220 
kmac256_new(void * provctx)221 static void *kmac256_new(void *provctx)
222 {
223     static const OSSL_PARAM kmac256_params[] = {
224         OSSL_PARAM_utf8_string("digest", OSSL_DIGEST_NAME_KECCAK_KMAC256,
225                                sizeof(OSSL_DIGEST_NAME_KECCAK_KMAC256)),
226         OSSL_PARAM_END
227     };
228     return kmac_fetch_new(provctx, kmac256_params);
229 }
230 
kmac_dup(void * vsrc)231 static void *kmac_dup(void *vsrc)
232 {
233     struct kmac_data_st *src = vsrc;
234     struct kmac_data_st *dst;
235 
236     if (!ossl_prov_is_running())
237         return NULL;
238 
239     dst = kmac_new(src->provctx);
240     if (dst == NULL)
241         return NULL;
242 
243     if (!EVP_MD_CTX_copy(dst->ctx, src->ctx)
244         || !ossl_prov_digest_copy(&dst->digest, &src->digest)) {
245         kmac_free(dst);
246         return NULL;
247     }
248 #ifdef FIPS_MODULE
249     dst->internal = src->internal;
250 #endif
251     dst->out_len = src->out_len;
252     dst->key_len = src->key_len;
253     dst->custom_len = src->custom_len;
254     dst->xof_mode = src->xof_mode;
255     memcpy(dst->key, src->key, src->key_len);
256     memcpy(dst->custom, src->custom, dst->custom_len);
257     OSSL_FIPS_IND_COPY(dst, src)
258 
259     return dst;
260 }
261 
kmac_setkey(struct kmac_data_st * kctx,const unsigned char * key,size_t keylen)262 static int kmac_setkey(struct kmac_data_st *kctx, const unsigned char *key,
263                        size_t keylen)
264 {
265     const EVP_MD *digest = ossl_prov_digest_md(&kctx->digest);
266     int w = EVP_MD_get_block_size(digest);
267 
268     if (keylen < KMAC_MIN_KEY || keylen > KMAC_MAX_KEY) {
269         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
270         return 0;
271     }
272 #ifdef FIPS_MODULE
273     /*
274      * Only do the key check if KMAC is fetched directly.
275      * Other algorithms that embed KMAC such as SSKDF will ignore this check.
276      */
277     if (!kctx->internal) {
278         int approved = ossl_mac_check_key_size(keylen);
279 
280         if (!approved) {
281             if (!OSSL_FIPS_IND_ON_UNAPPROVED(kctx, OSSL_FIPS_IND_SETTABLE1,
282                                              PROV_LIBCTX_OF(kctx->provctx),
283                                              "KMAC", "Key size",
284                                              ossl_fips_config_kmac_key_check)) {
285                 ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
286                 return 0;
287             }
288         }
289     }
290 #endif
291     if (w <= 0) {
292         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_DIGEST_LENGTH);
293         return 0;
294     }
295     if (!kmac_bytepad_encode_key(kctx->key, sizeof(kctx->key), &kctx->key_len,
296                                  key, keylen, (size_t)w))
297         return 0;
298     return 1;
299 }
300 
301 /*
302  * The init() assumes that any ctrl methods are set beforehand for
303  * md, key and custom. Setting the fields afterwards will have no
304  * effect on the output mac.
305  */
kmac_init(void * vmacctx,const unsigned char * key,size_t keylen,const OSSL_PARAM params[])306 static int kmac_init(void *vmacctx, const unsigned char *key,
307                      size_t keylen, const OSSL_PARAM params[])
308 {
309     struct kmac_data_st *kctx = vmacctx;
310     EVP_MD_CTX *ctx = kctx->ctx;
311     unsigned char *out;
312     size_t out_len, block_len;
313     int res, t;
314 
315     if (!ossl_prov_is_running() || !kmac_set_ctx_params(kctx, params))
316         return 0;
317 
318     if (key != NULL) {
319         if (!kmac_setkey(kctx, key, keylen))
320             return 0;
321     } else if (kctx->key_len == 0) {
322         /* Check key has been set */
323         ERR_raise(ERR_LIB_PROV, PROV_R_NO_KEY_SET);
324         return 0;
325     }
326     if (!EVP_DigestInit_ex(kctx->ctx, ossl_prov_digest_md(&kctx->digest),
327                            NULL))
328         return 0;
329 
330     t = EVP_MD_get_block_size(ossl_prov_digest_md(&kctx->digest));
331     if (t <= 0) {
332         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_DIGEST_LENGTH);
333         return 0;
334     }
335     block_len = t;
336 
337     /* Set default custom string if it is not already set */
338     if (kctx->custom_len == 0) {
339         const OSSL_PARAM cparams[] = {
340             OSSL_PARAM_octet_string(OSSL_MAC_PARAM_CUSTOM, "", 0),
341             OSSL_PARAM_END
342         };
343         (void)kmac_set_ctx_params(kctx, cparams);
344     }
345 
346     if (!bytepad(NULL, &out_len, kmac_string, sizeof(kmac_string),
347                  kctx->custom, kctx->custom_len, block_len)) {
348         ERR_raise(ERR_LIB_PROV, ERR_R_INTERNAL_ERROR);
349         return 0;
350     }
351     out = OPENSSL_malloc(out_len);
352     if (out == NULL)
353         return 0;
354     res = bytepad(out, NULL, kmac_string, sizeof(kmac_string),
355                   kctx->custom, kctx->custom_len, block_len)
356           && EVP_DigestUpdate(ctx, out, out_len)
357           && EVP_DigestUpdate(ctx, kctx->key, kctx->key_len);
358     OPENSSL_free(out);
359     return res;
360 }
361 
kmac_update(void * vmacctx,const unsigned char * data,size_t datalen)362 static int kmac_update(void *vmacctx, const unsigned char *data,
363                        size_t datalen)
364 {
365     struct kmac_data_st *kctx = vmacctx;
366 
367     return EVP_DigestUpdate(kctx->ctx, data, datalen);
368 }
369 
kmac_final(void * vmacctx,unsigned char * out,size_t * outl,size_t outsize)370 static int kmac_final(void *vmacctx, unsigned char *out, size_t *outl,
371                       size_t outsize)
372 {
373     struct kmac_data_st *kctx = vmacctx;
374     EVP_MD_CTX *ctx = kctx->ctx;
375     size_t lbits, len;
376     unsigned char encoded_outlen[KMAC_MAX_ENCODED_HEADER_LEN];
377     int ok;
378 
379     if (!ossl_prov_is_running())
380         return 0;
381 
382     /* KMAC XOF mode sets the encoded length to 0 */
383     lbits = (kctx->xof_mode ? 0 : (kctx->out_len * 8));
384 
385     ok = right_encode(encoded_outlen, sizeof(encoded_outlen), &len, lbits)
386         && EVP_DigestUpdate(ctx, encoded_outlen, len)
387         && EVP_DigestFinalXOF(ctx, out, kctx->out_len);
388     *outl = kctx->out_len;
389     return ok;
390 }
391 
392 static const OSSL_PARAM known_gettable_ctx_params[] = {
393     OSSL_PARAM_size_t(OSSL_MAC_PARAM_SIZE, NULL),
394     OSSL_PARAM_size_t(OSSL_MAC_PARAM_BLOCK_SIZE, NULL),
395     OSSL_FIPS_IND_GETTABLE_CTX_PARAM()
396     OSSL_PARAM_END
397 };
kmac_gettable_ctx_params(ossl_unused void * ctx,ossl_unused void * provctx)398 static const OSSL_PARAM *kmac_gettable_ctx_params(ossl_unused void *ctx,
399                                                   ossl_unused void *provctx)
400 {
401     return known_gettable_ctx_params;
402 }
403 
kmac_get_ctx_params(void * vmacctx,OSSL_PARAM params[])404 static int kmac_get_ctx_params(void *vmacctx, OSSL_PARAM params[])
405 {
406     struct kmac_data_st *kctx = vmacctx;
407     OSSL_PARAM *p;
408     int sz;
409 
410     if ((p = OSSL_PARAM_locate(params, OSSL_MAC_PARAM_SIZE)) != NULL
411             && !OSSL_PARAM_set_size_t(p, kctx->out_len))
412         return 0;
413 
414     if ((p = OSSL_PARAM_locate(params, OSSL_MAC_PARAM_BLOCK_SIZE)) != NULL) {
415         sz = EVP_MD_block_size(ossl_prov_digest_md(&kctx->digest));
416         if (!OSSL_PARAM_set_int(p, sz))
417             return 0;
418     }
419 
420     if (!OSSL_FIPS_IND_GET_CTX_PARAM(kctx, params))
421         return 0;
422 
423     return 1;
424 }
425 
426 static const OSSL_PARAM known_settable_ctx_params[] = {
427     OSSL_PARAM_int(OSSL_MAC_PARAM_XOF, NULL),
428     OSSL_PARAM_size_t(OSSL_MAC_PARAM_SIZE, NULL),
429     OSSL_PARAM_octet_string(OSSL_MAC_PARAM_KEY, NULL, 0),
430     OSSL_PARAM_octet_string(OSSL_MAC_PARAM_CUSTOM, NULL, 0),
431     OSSL_FIPS_IND_SETTABLE_CTX_PARAM(OSSL_MAC_PARAM_FIPS_NO_SHORT_MAC)
432     OSSL_FIPS_IND_SETTABLE_CTX_PARAM(OSSL_MAC_PARAM_FIPS_KEY_CHECK)
433     OSSL_PARAM_END
434 };
kmac_settable_ctx_params(ossl_unused void * ctx,ossl_unused void * provctx)435 static const OSSL_PARAM *kmac_settable_ctx_params(ossl_unused void *ctx,
436                                                   ossl_unused void *provctx)
437 {
438     return known_settable_ctx_params;
439 }
440 
441 /*
442  * The following params can be set any time before final():
443  *     - "outlen" or "size":    The requested output length.
444  *     - "xof":                 If set, this indicates that right_encoded(0)
445  *                              is part of the digested data, otherwise it
446  *                              uses right_encoded(requested output length).
447  *
448  * All other params should be set before init().
449  */
kmac_set_ctx_params(void * vmacctx,const OSSL_PARAM * params)450 static int kmac_set_ctx_params(void *vmacctx, const OSSL_PARAM *params)
451 {
452     struct kmac_data_st *kctx = vmacctx;
453     const OSSL_PARAM *p;
454 
455     if (ossl_param_is_empty(params))
456         return 1;
457 
458     if (!OSSL_FIPS_IND_SET_CTX_PARAM(kctx, OSSL_FIPS_IND_SETTABLE0, params,
459                                      OSSL_MAC_PARAM_FIPS_NO_SHORT_MAC))
460         return 0;
461     if (!OSSL_FIPS_IND_SET_CTX_PARAM(kctx, OSSL_FIPS_IND_SETTABLE1, params,
462                                      OSSL_MAC_PARAM_FIPS_KEY_CHECK))
463         return 0;
464 
465     if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_XOF)) != NULL
466         && !OSSL_PARAM_get_int(p, &kctx->xof_mode))
467         return 0;
468     if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_SIZE)) != NULL) {
469         size_t sz = 0;
470 
471         if (!OSSL_PARAM_get_size_t(p, &sz))
472             return 0;
473         if (sz > KMAC_MAX_OUTPUT_LEN) {
474             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_OUTPUT_LENGTH);
475             return 0;
476         }
477 #ifdef FIPS_MODULE
478         /* SP 800-185 8.4.2 mandates a minimum of 32 bits of output */
479         if (sz < 32 / 8) {
480             if (!OSSL_FIPS_IND_ON_UNAPPROVED(kctx, OSSL_FIPS_IND_SETTABLE0,
481                                              PROV_LIBCTX_OF(kctx->provctx),
482                                              "KMAC", "length",
483                                              ossl_fips_config_no_short_mac)) {
484                 ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_OUTPUT_LENGTH);
485                 return 0;
486             }
487         }
488 #endif
489         kctx->out_len = sz;
490     }
491     if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_KEY)) != NULL
492             && !kmac_setkey(kctx, p->data, p->data_size))
493         return 0;
494     if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_CUSTOM))
495         != NULL) {
496         if (p->data_size > KMAC_MAX_CUSTOM) {
497             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CUSTOM_LENGTH);
498             return 0;
499         }
500         if (!encode_string(kctx->custom, sizeof(kctx->custom), &kctx->custom_len,
501                            p->data, p->data_size))
502             return 0;
503     }
504     return 1;
505 }
506 
507 /* Encoding/Padding Methods. */
508 
509 /* Returns the number of bytes required to store 'bits' into a byte array */
get_encode_size(size_t bits)510 static unsigned int get_encode_size(size_t bits)
511 {
512     unsigned int cnt = 0, sz = sizeof(size_t);
513 
514     while (bits && (cnt < sz)) {
515         ++cnt;
516         bits >>= 8;
517     }
518     /* If bits is zero 1 byte is required */
519     if (cnt == 0)
520         cnt = 1;
521     return cnt;
522 }
523 
524 /*
525  * Convert an integer into bytes . The number of bytes is appended
526  * to the end of the buffer. Returns an array of bytes 'out' of size
527  * *out_len.
528  *
529  * e.g if bits = 32, out[2] = { 0x20, 0x01 }
530  */
right_encode(unsigned char * out,size_t out_max_len,size_t * out_len,size_t bits)531 static int right_encode(unsigned char *out, size_t out_max_len, size_t *out_len,
532                         size_t bits)
533 {
534     unsigned int len = get_encode_size(bits);
535     int i;
536 
537     if (len >= out_max_len) {
538         ERR_raise(ERR_LIB_PROV, PROV_R_LENGTH_TOO_LARGE);
539         return 0;
540     }
541 
542     /* MSB's are at the start of the bytes array */
543     for (i = len - 1; i >= 0; --i) {
544         out[i] = (unsigned char)(bits & 0xFF);
545         bits >>= 8;
546     }
547     /* Tack the length onto the end */
548     out[len] = (unsigned char)len;
549 
550     /* The Returned length includes the tacked on byte */
551     *out_len = len + 1;
552     return 1;
553 }
554 
555 /*
556  * Encodes a string with a left encoded length added. Note that the
557  * in_len is converted to bits (*8).
558  *
559  * e.g- in="KMAC" gives out[6] = { 0x01, 0x20, 0x4B, 0x4D, 0x41, 0x43 }
560  *                                 len   bits    K     M     A     C
561  */
encode_string(unsigned char * out,size_t out_max_len,size_t * out_len,const unsigned char * in,size_t in_len)562 static int encode_string(unsigned char *out, size_t out_max_len, size_t *out_len,
563                          const unsigned char *in, size_t in_len)
564 {
565     if (in == NULL) {
566         *out_len = 0;
567     } else {
568         size_t i, bits, len, sz;
569 
570         bits = 8 * in_len;
571         len = get_encode_size(bits);
572         sz = 1 + len + in_len;
573 
574         if (sz > out_max_len) {
575             ERR_raise(ERR_LIB_PROV, PROV_R_LENGTH_TOO_LARGE);
576             return 0;
577         }
578 
579         out[0] = (unsigned char)len;
580         for (i = len; i > 0; --i) {
581             out[i] = (bits & 0xFF);
582             bits >>= 8;
583         }
584         memcpy(out + len + 1, in, in_len);
585         *out_len = sz;
586     }
587     return 1;
588 }
589 
590 /*
591  * Returns a zero padded encoding of the inputs in1 and an optional
592  * in2 (can be NULL). The padded output must be a multiple of the blocksize 'w'.
593  * The value of w is in bytes (< 256).
594  *
595  * The returned output is:
596  *    zero_padded(multiple of w, (left_encode(w) || in1 [|| in2])
597  */
bytepad(unsigned char * out,size_t * out_len,const unsigned char * in1,size_t in1_len,const unsigned char * in2,size_t in2_len,size_t w)598 static int bytepad(unsigned char *out, size_t *out_len,
599                    const unsigned char *in1, size_t in1_len,
600                    const unsigned char *in2, size_t in2_len, size_t w)
601 {
602     int len;
603     unsigned char *p = out;
604     int sz = w;
605 
606     if (out == NULL) {
607         if (out_len == NULL) {
608             ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_NULL_PARAMETER);
609             return 0;
610         }
611         sz = 2 + in1_len + (in2 != NULL ? in2_len : 0);
612         *out_len = (sz + w - 1) / w * w;
613         return 1;
614     }
615 
616     if (!ossl_assert(w <= 255))
617         return 0;
618 
619     /* Left encoded w */
620     *p++ = 1;
621     *p++ = (unsigned char)w;
622     /* || in1 */
623     memcpy(p, in1, in1_len);
624     p += in1_len;
625     /* [ || in2 ] */
626     if (in2 != NULL && in2_len > 0) {
627         memcpy(p, in2, in2_len);
628         p += in2_len;
629     }
630     /* Figure out the pad size (divisible by w) */
631     len = p - out;
632     sz = (len + w - 1) / w * w;
633     /* zero pad the end of the buffer */
634     if (sz != len)
635         memset(p, 0, sz - len);
636     if (out_len != NULL)
637         *out_len = sz;
638     return 1;
639 }
640 
641 /* Returns out = bytepad(encode_string(in), w) */
kmac_bytepad_encode_key(unsigned char * out,size_t out_max_len,size_t * out_len,const unsigned char * in,size_t in_len,size_t w)642 static int kmac_bytepad_encode_key(unsigned char *out, size_t out_max_len,
643                                    size_t *out_len,
644                                    const unsigned char *in, size_t in_len,
645                                    size_t w)
646 {
647     unsigned char tmp[KMAC_MAX_KEY + KMAC_MAX_ENCODED_HEADER_LEN];
648     size_t tmp_len;
649 
650     if (!encode_string(tmp, sizeof(tmp), &tmp_len, in, in_len))
651         return 0;
652     if (!bytepad(NULL, out_len, tmp, tmp_len, NULL, 0, w))
653         return 0;
654     if (!ossl_assert(*out_len <= out_max_len))
655         return 0;
656     return bytepad(out, NULL, tmp, tmp_len, NULL, 0, w);
657 }
658 
659 #define IMPLEMENT_KMAC_TABLE(size, funcname, newname)                          \
660 const OSSL_DISPATCH ossl_kmac##size##_##funcname[] =                           \
661 {                                                                              \
662     { OSSL_FUNC_MAC_NEWCTX, (void (*)(void))kmac##size##_##newname },          \
663     { OSSL_FUNC_MAC_DUPCTX, (void (*)(void))kmac_dup },                        \
664     { OSSL_FUNC_MAC_FREECTX, (void (*)(void))kmac_free },                      \
665     { OSSL_FUNC_MAC_INIT, (void (*)(void))kmac_init },                         \
666     { OSSL_FUNC_MAC_UPDATE, (void (*)(void))kmac_update },                     \
667     { OSSL_FUNC_MAC_FINAL, (void (*)(void))kmac_final },                       \
668     { OSSL_FUNC_MAC_GETTABLE_CTX_PARAMS,                                       \
669       (void (*)(void))kmac_gettable_ctx_params },                              \
670     { OSSL_FUNC_MAC_GET_CTX_PARAMS, (void (*)(void))kmac_get_ctx_params },     \
671     { OSSL_FUNC_MAC_SETTABLE_CTX_PARAMS,                                       \
672       (void (*)(void))kmac_settable_ctx_params },                              \
673     { OSSL_FUNC_MAC_SET_CTX_PARAMS, (void (*)(void))kmac_set_ctx_params },     \
674     OSSL_DISPATCH_END                                                          \
675 }
676 
677 #define KMAC_TABLE(size) IMPLEMENT_KMAC_TABLE(size, functions, new)
678 
679 KMAC_TABLE(128);
680 KMAC_TABLE(256);
681 
682 #ifdef FIPS_MODULE
683 # define KMAC_INTERNAL_TABLE(size)                                             \
684 static OSSL_FUNC_mac_newctx_fn kmac##size##_internal_new;                      \
685 static void *kmac##size##_internal_new(void *provctx)                          \
686 {                                                                              \
687     struct kmac_data_st *macctx = kmac##size##_new(provctx);                   \
688                                                                                \
689     if (macctx != NULL)                                                        \
690         macctx->internal = 1;                                                  \
691     return macctx;                                                             \
692 }                                                                              \
693 IMPLEMENT_KMAC_TABLE(size, internal_functions, internal_new)
694 
695 KMAC_INTERNAL_TABLE(128);
696 KMAC_INTERNAL_TABLE(256);
697 #endif /* FIPS_MODULE */
698