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