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