kmac: fix customistation string overflow bug
[openssl.git] / providers / implementations / macs / kmac_prov.c
1 /*
2  * Copyright 2018-2021 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
58 #include "prov/implementations.h"
59 #include "prov/provider_ctx.h"
60 #include "prov/provider_util.h"
61 #include "prov/providercommon.h"
62
63 /*
64  * Forward declaration of everything implemented here.  This is not strictly
65  * necessary for the compiler, but provides an assurance that the signatures
66  * of the functions in the dispatch table are correct.
67  */
68 static OSSL_FUNC_mac_newctx_fn kmac128_new;
69 static OSSL_FUNC_mac_newctx_fn kmac256_new;
70 static OSSL_FUNC_mac_dupctx_fn kmac_dup;
71 static OSSL_FUNC_mac_freectx_fn kmac_free;
72 static OSSL_FUNC_mac_gettable_ctx_params_fn kmac_gettable_ctx_params;
73 static OSSL_FUNC_mac_get_ctx_params_fn kmac_get_ctx_params;
74 static OSSL_FUNC_mac_settable_ctx_params_fn kmac_settable_ctx_params;
75 static OSSL_FUNC_mac_set_ctx_params_fn kmac_set_ctx_params;
76 static OSSL_FUNC_mac_init_fn kmac_init;
77 static OSSL_FUNC_mac_update_fn kmac_update;
78 static OSSL_FUNC_mac_final_fn kmac_final;
79
80 #define KMAC_MAX_BLOCKSIZE ((1600 - 128*2) / 8) /* 168 */
81
82 /* Length encoding will be  a 1 byte size + length in bits (2 bytes max) */
83 #define KMAC_MAX_ENCODED_HEADER_LEN 3
84
85 /*
86  * Restrict the maximum length of the customisation string.  This must not
87  * exceed 64 bits = 8k bytes.
88  */
89 #define KMAC_MAX_CUSTOM 256
90
91 /* Maximum size of encoded custom string */
92 #define KMAC_MAX_CUSTOM_ENCODED (KMAC_MAX_CUSTOM + KMAC_MAX_ENCODED_HEADER_LEN)
93
94 /* Maximum key size in bytes = 2040 / 8 */
95 #define KMAC_MAX_KEY 255
96
97 /*
98  * Maximum Encoded Key size will be padded to a multiple of the blocksize
99  * i.e KMAC_MAX_KEY + KMAC_MAX_ENCODED_LEN = 258
100  * Padded to a multiple of KMAC_MAX_BLOCKSIZE
101  */
102 #define KMAC_MAX_KEY_ENCODED (KMAC_MAX_BLOCKSIZE * 2)
103
104 /* Fixed value of encode_string("KMAC") */
105 static const unsigned char kmac_string[] = {
106     0x01, 0x20, 0x4B, 0x4D, 0x41, 0x43
107 };
108
109
110 #define KMAC_FLAG_XOF_MODE          1
111
112 struct kmac_data_st {
113     void  *provctx;
114     EVP_MD_CTX *ctx;
115     PROV_DIGEST digest;
116     size_t out_len;
117     size_t key_len;
118     size_t custom_len;
119     /* If xof_mode = 1 then we use right_encode(0) */
120     int xof_mode;
121     /* key and custom are stored in encoded form */
122     unsigned char key[KMAC_MAX_KEY_ENCODED];
123     unsigned char custom[KMAC_MAX_CUSTOM_ENCODED];
124 };
125
126 static int encode_string(unsigned char *out, size_t *out_len,
127                          const unsigned char *in, size_t in_len);
128 static int right_encode(unsigned char *out, size_t *out_len, size_t bits);
129 static int bytepad(unsigned char *out, size_t *out_len,
130                    const unsigned char *in1, size_t in1_len,
131                    const unsigned char *in2, size_t in2_len,
132                    size_t w);
133 static int kmac_bytepad_encode_key(unsigned char *out, size_t *out_len,
134                                    const unsigned char *in, size_t in_len,
135                                    size_t w);
136
137 static void kmac_free(void *vmacctx)
138 {
139     struct kmac_data_st *kctx = vmacctx;
140
141     if (kctx != NULL) {
142         EVP_MD_CTX_free(kctx->ctx);
143         ossl_prov_digest_reset(&kctx->digest);
144         OPENSSL_cleanse(kctx->key, kctx->key_len);
145         OPENSSL_cleanse(kctx->custom, kctx->custom_len);
146         OPENSSL_free(kctx);
147     }
148 }
149
150 /*
151  * We have KMAC implemented as a hash, which we can use instead of
152  * reimplementing the EVP functionality with direct use of
153  * keccak_mac_init() and friends.
154  */
155 static struct kmac_data_st *kmac_new(void *provctx)
156 {
157     struct kmac_data_st *kctx;
158
159     if (!ossl_prov_is_running())
160         return NULL;
161
162     if ((kctx = OPENSSL_zalloc(sizeof(*kctx))) == NULL
163             || (kctx->ctx = EVP_MD_CTX_new()) == NULL) {
164         kmac_free(kctx);
165         return NULL;
166     }
167     kctx->provctx = provctx;
168     return kctx;
169 }
170
171 static void *kmac_fetch_new(void *provctx, const OSSL_PARAM *params)
172 {
173     struct kmac_data_st *kctx = kmac_new(provctx);
174
175     if (kctx == NULL)
176         return 0;
177     if (!ossl_prov_digest_load_from_params(&kctx->digest, params,
178                                       PROV_LIBCTX_OF(provctx))) {
179         kmac_free(kctx);
180         return 0;
181     }
182
183     kctx->out_len = EVP_MD_size(ossl_prov_digest_md(&kctx->digest));
184     return kctx;
185 }
186
187 static void *kmac128_new(void *provctx)
188 {
189     static const OSSL_PARAM kmac128_params[] = {
190         OSSL_PARAM_utf8_string("digest", OSSL_DIGEST_NAME_KECCAK_KMAC128,
191                                sizeof(OSSL_DIGEST_NAME_KECCAK_KMAC128)),
192         OSSL_PARAM_END
193     };
194     return kmac_fetch_new(provctx, kmac128_params);
195 }
196
197 static void *kmac256_new(void *provctx)
198 {
199     static const OSSL_PARAM kmac256_params[] = {
200         OSSL_PARAM_utf8_string("digest", OSSL_DIGEST_NAME_KECCAK_KMAC256,
201                                sizeof(OSSL_DIGEST_NAME_KECCAK_KMAC256)),
202         OSSL_PARAM_END
203     };
204     return kmac_fetch_new(provctx, kmac256_params);
205 }
206
207 static void *kmac_dup(void *vsrc)
208 {
209     struct kmac_data_st *src = vsrc;
210     struct kmac_data_st *dst;
211
212     if (!ossl_prov_is_running())
213         return NULL;
214
215     dst = kmac_new(src->provctx);
216     if (dst == NULL)
217         return NULL;
218
219     if (!EVP_MD_CTX_copy(dst->ctx, src->ctx)
220         || !ossl_prov_digest_copy(&dst->digest, &src->digest)) {
221         kmac_free(dst);
222         return NULL;
223     }
224
225     dst->out_len = src->out_len;
226     dst->key_len = src->key_len;
227     dst->custom_len = src->custom_len;
228     dst->xof_mode = src->xof_mode;
229     memcpy(dst->key, src->key, src->key_len);
230     memcpy(dst->custom, src->custom, dst->custom_len);
231
232     return dst;
233 }
234
235 static size_t kmac_size(void *vmacctx)
236 {
237     struct kmac_data_st *kctx = vmacctx;
238
239     return kctx->out_len;
240 }
241
242 static int kmac_setkey(struct kmac_data_st *kctx, const unsigned char *key,
243                        size_t keylen)
244 {
245     const EVP_MD *digest = ossl_prov_digest_md(&kctx->digest);
246     int w = EVP_MD_block_size(digest);
247
248     if (keylen < 4 || keylen > KMAC_MAX_KEY) {
249         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
250         return 0;
251     }
252     if (w < 0) {
253         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_DIGEST_LENGTH);
254         return 0;
255     }
256     if (!kmac_bytepad_encode_key(kctx->key, &kctx->key_len,
257                                  key, keylen, (size_t)w))
258         return 0;
259     return 1;
260 }
261
262 /*
263  * The init() assumes that any ctrl methods are set beforehand for
264  * md, key and custom. Setting the fields afterwards will have no
265  * effect on the output mac.
266  */
267 static int kmac_init(void *vmacctx, const unsigned char *key,
268                      size_t keylen, const OSSL_PARAM params[])
269 {
270     struct kmac_data_st *kctx = vmacctx;
271     EVP_MD_CTX *ctx = kctx->ctx;
272     unsigned char *out;
273     size_t out_len, block_len;
274     int res, t;
275
276     if (!ossl_prov_is_running() || !kmac_set_ctx_params(kctx, params))
277         return 0;
278
279     if (key != NULL) {
280         if (!kmac_setkey(kctx, key, keylen))
281             return 0;
282     } else if (kctx->key_len == 0) {
283         /* Check key has been set */
284         ERR_raise(ERR_LIB_PROV, PROV_R_NO_KEY_SET);
285         return 0;
286     }
287     if (!EVP_DigestInit_ex(kctx->ctx, ossl_prov_digest_md(&kctx->digest),
288                            NULL))
289         return 0;
290
291     t = EVP_MD_block_size(ossl_prov_digest_md(&kctx->digest));
292     if (t < 0) {
293         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_DIGEST_LENGTH);
294         return 0;
295     }
296     block_len = t;
297
298     /* Set default custom string if it is not already set */
299     if (kctx->custom_len == 0) {
300         const OSSL_PARAM cparams[] = {
301             OSSL_PARAM_octet_string(OSSL_MAC_PARAM_CUSTOM, "", 0),
302             OSSL_PARAM_END
303         };
304         (void)kmac_set_ctx_params(kctx, cparams);
305     }
306
307     if (!bytepad(NULL, &out_len, kmac_string, sizeof(kmac_string),
308                  kctx->custom, kctx->custom_len, block_len)) {
309         ERR_raise(ERR_LIB_PROV, ERR_R_INTERNAL_ERROR);
310         return 0;
311     }
312     out = OPENSSL_malloc(out_len);
313     if (out == NULL) {
314         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
315         return 0;
316     }
317     res = bytepad(out, NULL, kmac_string, sizeof(kmac_string),
318                   kctx->custom, kctx->custom_len, block_len)
319           && EVP_DigestUpdate(ctx, out, out_len)
320           && EVP_DigestUpdate(ctx, kctx->key, kctx->key_len);
321     OPENSSL_free(out);
322     return res;
323 }
324
325 static int kmac_update(void *vmacctx, const unsigned char *data,
326                        size_t datalen)
327 {
328     struct kmac_data_st *kctx = vmacctx;
329
330     return EVP_DigestUpdate(kctx->ctx, data, datalen);
331 }
332
333 static int kmac_final(void *vmacctx, unsigned char *out, size_t *outl,
334                       size_t outsize)
335 {
336     struct kmac_data_st *kctx = vmacctx;
337     EVP_MD_CTX *ctx = kctx->ctx;
338     size_t lbits, len;
339     unsigned char encoded_outlen[KMAC_MAX_ENCODED_HEADER_LEN];
340     int ok;
341
342     if (!ossl_prov_is_running())
343         return 0;
344
345     /* KMAC XOF mode sets the encoded length to 0 */
346     lbits = (kctx->xof_mode ? 0 : (kctx->out_len * 8));
347
348     ok = right_encode(encoded_outlen, &len, lbits)
349         && EVP_DigestUpdate(ctx, encoded_outlen, len)
350         && EVP_DigestFinalXOF(ctx, out, kctx->out_len);
351     *outl = kctx->out_len;
352     return ok;
353 }
354
355 static const OSSL_PARAM known_gettable_ctx_params[] = {
356     OSSL_PARAM_size_t(OSSL_MAC_PARAM_SIZE, NULL),
357     OSSL_PARAM_END
358 };
359 static const OSSL_PARAM *kmac_gettable_ctx_params(ossl_unused void *ctx,
360                                                   ossl_unused void *provctx)
361 {
362     return known_gettable_ctx_params;
363 }
364
365 static int kmac_get_ctx_params(void *vmacctx, OSSL_PARAM params[])
366 {
367     OSSL_PARAM *p;
368
369     if ((p = OSSL_PARAM_locate(params, OSSL_MAC_PARAM_SIZE)) != NULL)
370         return OSSL_PARAM_set_size_t(p, kmac_size(vmacctx));
371
372     return 1;
373 }
374
375 static const OSSL_PARAM known_settable_ctx_params[] = {
376     OSSL_PARAM_int(OSSL_MAC_PARAM_XOF, NULL),
377     OSSL_PARAM_size_t(OSSL_MAC_PARAM_SIZE, NULL),
378     OSSL_PARAM_octet_string(OSSL_MAC_PARAM_KEY, NULL, 0),
379     OSSL_PARAM_octet_string(OSSL_MAC_PARAM_CUSTOM, NULL, 0),
380     OSSL_PARAM_END
381 };
382 static const OSSL_PARAM *kmac_settable_ctx_params(ossl_unused void *ctx,
383                                                   ossl_unused void *provctx)
384 {
385     return known_settable_ctx_params;
386 }
387
388 /*
389  * The following params can be set any time before final():
390  *     - "outlen" or "size":    The requested output length.
391  *     - "xof":                 If set, this indicates that right_encoded(0)
392  *                              is part of the digested data, otherwise it
393  *                              uses right_encoded(requested output length).
394  *
395  * All other params should be set before init().
396  */
397 static int kmac_set_ctx_params(void *vmacctx, const OSSL_PARAM *params)
398 {
399     struct kmac_data_st *kctx = vmacctx;
400     const OSSL_PARAM *p;
401
402     if (params == NULL)
403         return 1;
404
405     if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_XOF)) != NULL
406         && !OSSL_PARAM_get_int(p, &kctx->xof_mode))
407         return 0;
408     if (((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_SIZE)) != NULL)
409         && !OSSL_PARAM_get_size_t(p, &kctx->out_len))
410         return 0;
411     if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_KEY)) != NULL
412             && !kmac_setkey(kctx, p->data, p->data_size))
413         return 0;
414     if ((p = OSSL_PARAM_locate_const(params, OSSL_MAC_PARAM_CUSTOM))
415         != NULL) {
416         if (p->data_size > KMAC_MAX_CUSTOM) {
417             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CUSTOM_LENGTH);
418             return 0;
419         }
420         if (!encode_string(kctx->custom, &kctx->custom_len,
421                            p->data, p->data_size))
422             return 0;
423     }
424     return 1;
425 }
426
427 /*
428  * Encoding/Padding Methods.
429  */
430
431 /* Returns the number of bytes required to store 'bits' into a byte array */
432 static unsigned int get_encode_size(size_t bits)
433 {
434     unsigned int cnt = 0, sz = sizeof(size_t);
435
436     while (bits && (cnt < sz)) {
437         ++cnt;
438         bits >>= 8;
439     }
440     /* If bits is zero 1 byte is required */
441     if (cnt == 0)
442         cnt = 1;
443     return cnt;
444 }
445
446 /*
447  * Convert an integer into bytes . The number of bytes is appended
448  * to the end of the buffer. Returns an array of bytes 'out' of size
449  * *out_len.
450  *
451  * e.g if bits = 32, out[2] = { 0x20, 0x01 }
452  *
453  */
454 static int right_encode(unsigned char *out, size_t *out_len, size_t bits)
455 {
456     unsigned int len = get_encode_size(bits);
457     int i;
458
459     /* The length is constrained to a single byte: 2040/8 = 255 */
460     if (len > 0xFF) {
461         ERR_raise(ERR_LIB_PROV, PROV_R_LENGTH_TOO_LARGE);
462         return 0;
463     }
464
465     /* MSB's are at the start of the bytes array */
466     for (i = len - 1; i >= 0; --i) {
467         out[i] = (unsigned char)(bits & 0xFF);
468         bits >>= 8;
469     }
470     /* Tack the length onto the end */
471     out[len] = (unsigned char)len;
472
473     /* The Returned length includes the tacked on byte */
474     *out_len = len + 1;
475     return 1;
476 }
477
478 /*
479  * Encodes a string with a left encoded length added. Note that the
480  * in_len is converted to bits (*8).
481  *
482  * e.g- in="KMAC" gives out[6] = { 0x01, 0x20, 0x4B, 0x4D, 0x41, 0x43 }
483  *                                 len   bits    K     M     A     C
484  */
485 static int encode_string(unsigned char *out, size_t *out_len,
486                          const unsigned char *in, size_t in_len)
487 {
488     if (in == NULL) {
489         *out_len = 0;
490     } else {
491         size_t i, bits, len;
492
493         bits = 8 * in_len;
494         len = get_encode_size(bits);
495         if (len > 0xFF) {
496             ERR_raise(ERR_LIB_PROV, PROV_R_LENGTH_TOO_LARGE);
497             return 0;
498         }
499
500         out[0] = len;
501         for (i = len; i > 0; --i) {
502             out[i] = (bits & 0xFF);
503             bits >>= 8;
504         }
505         memcpy(out + len + 1, in, in_len);
506         *out_len = (1 + len + in_len);
507     }
508     return 1;
509 }
510
511 /*
512  * Returns a zero padded encoding of the inputs in1 and an optional
513  * in2 (can be NULL). The padded output must be a multiple of the blocksize 'w'.
514  * The value of w is in bytes (< 256).
515  *
516  * The returned output is:
517  *    zero_padded(multiple of w, (left_encode(w) || in1 [|| in2])
518  */
519 static int bytepad(unsigned char *out, size_t *out_len,
520                    const unsigned char *in1, size_t in1_len,
521                    const unsigned char *in2, size_t in2_len, size_t w)
522 {
523     int len;
524     unsigned char *p = out;
525     int sz = w;
526
527     if (out == NULL) {
528         if (out_len == NULL) {
529             ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_NULL_PARAMETER);
530             return 0;
531         }
532         sz = 2 + in1_len + (in2 != NULL ? in2_len : 0);
533         *out_len = (sz + w - 1) / w * w;
534         return 1;
535     }
536
537     /* Left encoded w */
538     *p++ = 1;
539     *p++ = w;
540     /* || in1 */
541     memcpy(p, in1, in1_len);
542     p += in1_len;
543     /* [ || in2 ] */
544     if (in2 != NULL && in2_len > 0) {
545         memcpy(p, in2, in2_len);
546         p += in2_len;
547     }
548     /* Figure out the pad size (divisible by w) */
549     len = p - out;
550     sz = (len + w - 1) / w * w;
551     /* zero pad the end of the buffer */
552     if (sz != len)
553         memset(p, 0, sz - len);
554     if (out_len != NULL)
555         *out_len = sz;
556     return 1;
557 }
558
559 /*
560  * Returns out = bytepad(encode_string(in), w)
561  */
562 static int kmac_bytepad_encode_key(unsigned char *out, size_t *out_len,
563                                    const unsigned char *in, size_t in_len,
564                                    size_t w)
565 {
566     unsigned char tmp[KMAC_MAX_KEY + KMAC_MAX_ENCODED_HEADER_LEN];
567     size_t tmp_len;
568
569     if (!encode_string(tmp, &tmp_len, in, in_len))
570         return 0;
571
572     return bytepad(out, out_len, tmp, tmp_len, NULL, 0, w);
573 }
574
575 const OSSL_DISPATCH ossl_kmac128_functions[] = {
576     { OSSL_FUNC_MAC_NEWCTX, (void (*)(void))kmac128_new },
577     { OSSL_FUNC_MAC_DUPCTX, (void (*)(void))kmac_dup },
578     { OSSL_FUNC_MAC_FREECTX, (void (*)(void))kmac_free },
579     { OSSL_FUNC_MAC_INIT, (void (*)(void))kmac_init },
580     { OSSL_FUNC_MAC_UPDATE, (void (*)(void))kmac_update },
581     { OSSL_FUNC_MAC_FINAL, (void (*)(void))kmac_final },
582     { OSSL_FUNC_MAC_GETTABLE_CTX_PARAMS,
583       (void (*)(void))kmac_gettable_ctx_params },
584     { OSSL_FUNC_MAC_GET_CTX_PARAMS, (void (*)(void))kmac_get_ctx_params },
585     { OSSL_FUNC_MAC_SETTABLE_CTX_PARAMS,
586       (void (*)(void))kmac_settable_ctx_params },
587     { OSSL_FUNC_MAC_SET_CTX_PARAMS, (void (*)(void))kmac_set_ctx_params },
588     { 0, NULL }
589 };
590
591 const OSSL_DISPATCH ossl_kmac256_functions[] = {
592     { OSSL_FUNC_MAC_NEWCTX, (void (*)(void))kmac256_new },
593     { OSSL_FUNC_MAC_DUPCTX, (void (*)(void))kmac_dup },
594     { OSSL_FUNC_MAC_FREECTX, (void (*)(void))kmac_free },
595     { OSSL_FUNC_MAC_INIT, (void (*)(void))kmac_init },
596     { OSSL_FUNC_MAC_UPDATE, (void (*)(void))kmac_update },
597     { OSSL_FUNC_MAC_FINAL, (void (*)(void))kmac_final },
598     { OSSL_FUNC_MAC_GETTABLE_CTX_PARAMS,
599       (void (*)(void))kmac_gettable_ctx_params },
600     { OSSL_FUNC_MAC_GET_CTX_PARAMS, (void (*)(void))kmac_get_ctx_params },
601     { OSSL_FUNC_MAC_SETTABLE_CTX_PARAMS,
602       (void (*)(void))kmac_settable_ctx_params },
603     { OSSL_FUNC_MAC_SET_CTX_PARAMS, (void (*)(void))kmac_set_ctx_params },
604     { 0, NULL }
605 };