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