abe2e9ace0055f41c098ca9d795051c59bde3e14
[openssl.git] / providers / implementations / ciphers / ciphercommon_gcm.c
1 /*
2  * Copyright 2019-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 /* Dispatch functions for gcm mode */
11
12 #include "prov/ciphercommon.h"
13 #include "prov/ciphercommon_gcm.h"
14 #include "prov/providercommon.h"
15 #include "prov/providercommonerr.h"
16 #include <openssl/rand.h>
17 #include "prov/provider_ctx.h"
18
19 static int gcm_tls_init(PROV_GCM_CTX *dat, unsigned char *aad, size_t aad_len);
20 static int gcm_tls_iv_set_fixed(PROV_GCM_CTX *ctx, unsigned char *iv,
21                                 size_t len);
22 static int gcm_tls_cipher(PROV_GCM_CTX *ctx, unsigned char *out, size_t *padlen,
23                           const unsigned char *in, size_t len);
24 static int gcm_cipher_internal(PROV_GCM_CTX *ctx, unsigned char *out,
25                                size_t *padlen, const unsigned char *in,
26                                size_t len);
27
28 void gcm_initctx(void *provctx, PROV_GCM_CTX *ctx, size_t keybits,
29                  const PROV_GCM_HW *hw, size_t ivlen_min)
30 {
31     ctx->pad = 1;
32     ctx->mode = EVP_CIPH_GCM_MODE;
33     ctx->taglen = UNINITIALISED_SIZET;
34     ctx->tls_aad_len = UNINITIALISED_SIZET;
35     ctx->ivlen_min = ivlen_min;
36     ctx->ivlen = (EVP_GCM_TLS_FIXED_IV_LEN + EVP_GCM_TLS_EXPLICIT_IV_LEN);
37     ctx->keylen = keybits / 8;
38     ctx->hw = hw;
39     ctx->libctx = PROV_LIBRARY_CONTEXT_OF(provctx);
40 }
41
42 static int gcm_init(void *vctx, const unsigned char *key, size_t keylen,
43                     const unsigned char *iv, size_t ivlen, int enc)
44 {
45     PROV_GCM_CTX *ctx = (PROV_GCM_CTX *)vctx;
46
47     if (!ossl_prov_is_running())
48         return 0;
49
50     ctx->enc = enc;
51
52     if (iv != NULL) {
53         if (ivlen < ctx->ivlen_min || ivlen > sizeof(ctx->iv)) {
54             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_IV_LENGTH);
55             return 0;
56         }
57         ctx->ivlen = ivlen;
58         memcpy(ctx->iv, iv, ivlen);
59         ctx->iv_state = IV_STATE_BUFFERED;
60     }
61
62     if (key != NULL) {
63         if (keylen != ctx->keylen) {
64             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
65             return 0;
66         }
67         return ctx->hw->setkey(ctx, key, ctx->keylen);
68     }
69     return 1;
70 }
71
72 int gcm_einit(void *vctx, const unsigned char *key, size_t keylen,
73               const unsigned char *iv, size_t ivlen)
74 {
75     return gcm_init(vctx, key, keylen, iv, ivlen, 1);
76 }
77
78 int gcm_dinit(void *vctx, const unsigned char *key, size_t keylen,
79               const unsigned char *iv, size_t ivlen)
80 {
81     return gcm_init(vctx, key, keylen, iv, ivlen, 0);
82 }
83
84 /* increment counter (64-bit int) by 1 */
85 static void ctr64_inc(unsigned char *counter)
86 {
87     int n = 8;
88     unsigned char c;
89
90     do {
91         --n;
92         c = counter[n];
93         ++c;
94         counter[n] = c;
95         if (c > 0)
96             return;
97     } while (n > 0);
98 }
99
100 static int getivgen(PROV_GCM_CTX *ctx, unsigned char *out, size_t olen)
101 {
102     if (!ctx->iv_gen
103         || !ctx->key_set
104         || !ctx->hw->setiv(ctx, ctx->iv, ctx->ivlen))
105         return 0;
106     if (olen == 0 || olen > ctx->ivlen)
107         olen = ctx->ivlen;
108     memcpy(out, ctx->iv + ctx->ivlen - olen, olen);
109     /*
110      * Invocation field will be at least 8 bytes in size and so no need
111      * to check wrap around or increment more than last 8 bytes.
112      */
113     ctr64_inc(ctx->iv + ctx->ivlen - 8);
114     ctx->iv_state = IV_STATE_COPIED;
115     return 1;
116 }
117
118 static int setivinv(PROV_GCM_CTX *ctx, unsigned char *in, size_t inl)
119 {
120     if (!ctx->iv_gen
121         || !ctx->key_set
122         || ctx->enc)
123         return 0;
124
125     memcpy(ctx->iv + ctx->ivlen - inl, in, inl);
126     if (!ctx->hw->setiv(ctx, ctx->iv, ctx->ivlen))
127         return 0;
128     ctx->iv_state = IV_STATE_COPIED;
129     return 1;
130 }
131
132 int gcm_get_ctx_params(void *vctx, OSSL_PARAM params[])
133 {
134     PROV_GCM_CTX *ctx = (PROV_GCM_CTX *)vctx;
135     OSSL_PARAM *p;
136     size_t sz;
137
138     p = OSSL_PARAM_locate(params, OSSL_CIPHER_PARAM_IVLEN);
139     if (p != NULL && !OSSL_PARAM_set_size_t(p, ctx->ivlen)) {
140         ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_SET_PARAMETER);
141         return 0;
142     }
143     p = OSSL_PARAM_locate(params, OSSL_CIPHER_PARAM_KEYLEN);
144     if (p != NULL && !OSSL_PARAM_set_size_t(p, ctx->keylen)) {
145         ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_SET_PARAMETER);
146         return 0;
147     }
148     p = OSSL_PARAM_locate(params, OSSL_CIPHER_PARAM_AEAD_TAGLEN);
149     if (p != NULL) {
150         size_t taglen = (ctx->taglen != UNINITIALISED_SIZET) ? ctx->taglen :
151                          GCM_TAG_MAX_SIZE;
152
153         if (!OSSL_PARAM_set_size_t(p, taglen)) {
154             ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_SET_PARAMETER);
155             return 0;
156         }
157     }
158
159     p = OSSL_PARAM_locate(params, OSSL_CIPHER_PARAM_IV);
160     if (p != NULL) {
161         if (ctx->iv_state == IV_STATE_UNINITIALISED)
162             return 0;
163         if (ctx->ivlen > p->data_size) {
164             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_IV_LENGTH);
165             return 0;
166         }
167         if (!OSSL_PARAM_set_octet_string(p, ctx->iv, ctx->ivlen)
168             && !OSSL_PARAM_set_octet_ptr(p, &ctx->iv, ctx->ivlen)) {
169             ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_SET_PARAMETER);
170             return 0;
171         }
172     }
173
174     p = OSSL_PARAM_locate(params, OSSL_CIPHER_PARAM_IV_STATE);
175     if (p != NULL) {
176         if (ctx->iv_state == IV_STATE_UNINITIALISED)
177             return 0;
178         if (ctx->ivlen > p->data_size) {
179             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_IV_LENGTH);
180             return 0;
181         }
182         if (!OSSL_PARAM_set_octet_string(p, ctx->iv, ctx->ivlen)
183             && !OSSL_PARAM_set_octet_ptr(p, &ctx->iv, ctx->ivlen)) {
184             ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_SET_PARAMETER);
185             return 0;
186         }
187     }
188
189     p = OSSL_PARAM_locate(params, OSSL_CIPHER_PARAM_AEAD_TLS1_AAD_PAD);
190     if (p != NULL && !OSSL_PARAM_set_size_t(p, ctx->tls_aad_pad_sz)) {
191         ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_SET_PARAMETER);
192         return 0;
193     }
194     p = OSSL_PARAM_locate(params, OSSL_CIPHER_PARAM_AEAD_TAG);
195     if (p != NULL) {
196         sz = p->data_size;
197         if (sz == 0
198             || sz > EVP_GCM_TLS_TAG_LEN
199             || !ctx->enc
200             || ctx->taglen == UNINITIALISED_SIZET) {
201             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_TAG);
202             return 0;
203         }
204         if (!OSSL_PARAM_set_octet_string(p, ctx->buf, sz)) {
205             ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_SET_PARAMETER);
206             return 0;
207         }
208     }
209     p = OSSL_PARAM_locate(params, OSSL_CIPHER_PARAM_AEAD_TLS1_GET_IV_GEN);
210     if (p != NULL) {
211         if (p->data == NULL
212             || p->data_type != OSSL_PARAM_OCTET_STRING
213             || !getivgen(ctx, p->data, p->data_size))
214             return 0;
215     }
216     return 1;
217 }
218
219 int gcm_set_ctx_params(void *vctx, const OSSL_PARAM params[])
220 {
221     PROV_GCM_CTX *ctx = (PROV_GCM_CTX *)vctx;
222     const OSSL_PARAM *p;
223     size_t sz;
224     void *vp;
225
226     p = OSSL_PARAM_locate_const(params, OSSL_CIPHER_PARAM_AEAD_TAG);
227     if (p != NULL) {
228         vp = ctx->buf;
229         if (!OSSL_PARAM_get_octet_string(p, &vp, EVP_GCM_TLS_TAG_LEN, &sz)) {
230             ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_GET_PARAMETER);
231             return 0;
232         }
233         if (sz == 0 || ctx->enc) {
234             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_TAG);
235             return 0;
236         }
237         ctx->taglen = sz;
238     }
239
240     p = OSSL_PARAM_locate_const(params, OSSL_CIPHER_PARAM_AEAD_IVLEN);
241     if (p != NULL) {
242         if (!OSSL_PARAM_get_size_t(p, &sz)) {
243             ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_GET_PARAMETER);
244             return 0;
245         }
246         if (sz == 0 || sz > sizeof(ctx->iv)) {
247             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_IV_LENGTH);
248             return 0;
249         }
250         ctx->ivlen = sz;
251     }
252
253     p = OSSL_PARAM_locate_const(params, OSSL_CIPHER_PARAM_AEAD_TLS1_AAD);
254     if (p != NULL) {
255         if (p->data_type != OSSL_PARAM_OCTET_STRING) {
256             ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_GET_PARAMETER);
257             return 0;
258         }
259         sz = gcm_tls_init(ctx, p->data, p->data_size);
260         if (sz == 0) {
261             ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_AAD);
262             return 0;
263         }
264         ctx->tls_aad_pad_sz = sz;
265     }
266
267     p = OSSL_PARAM_locate_const(params, OSSL_CIPHER_PARAM_AEAD_TLS1_IV_FIXED);
268     if (p != NULL) {
269         if (p->data_type != OSSL_PARAM_OCTET_STRING) {
270             ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_GET_PARAMETER);
271             return 0;
272         }
273         if (gcm_tls_iv_set_fixed(ctx, p->data, p->data_size) == 0) {
274             ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_GET_PARAMETER);
275             return 0;
276         }
277     }
278     p = OSSL_PARAM_locate_const(params, OSSL_CIPHER_PARAM_AEAD_TLS1_SET_IV_INV);
279     if (p != NULL) {
280         if (p->data == NULL
281             || p->data_type != OSSL_PARAM_OCTET_STRING
282             || !setivinv(ctx, p->data, p->data_size))
283             return 0;
284     }
285
286
287     return 1;
288 }
289
290 int gcm_stream_update(void *vctx, unsigned char *out, size_t *outl,
291                       size_t outsize, const unsigned char *in, size_t inl)
292 {
293     PROV_GCM_CTX *ctx = (PROV_GCM_CTX *)vctx;
294
295     if (inl == 0) {
296         *outl = 0;
297         return 1;
298     }
299
300     if (outsize < inl) {
301         ERR_raise(ERR_LIB_PROV, PROV_R_OUTPUT_BUFFER_TOO_SMALL);
302         return 0;
303     }
304
305     if (gcm_cipher_internal(ctx, out, outl, in, inl) <= 0) {
306         ERR_raise(ERR_LIB_PROV, PROV_R_CIPHER_OPERATION_FAILED);
307         return 0;
308     }
309     return 1;
310 }
311
312 int gcm_stream_final(void *vctx, unsigned char *out, size_t *outl,
313                      size_t outsize)
314 {
315     PROV_GCM_CTX *ctx = (PROV_GCM_CTX *)vctx;
316     int i;
317
318     if (!ossl_prov_is_running())
319         return 0;
320
321     i = gcm_cipher_internal(ctx, out, outl, NULL, 0);
322     if (i <= 0)
323         return 0;
324
325     *outl = 0;
326     return 1;
327 }
328
329 int gcm_cipher(void *vctx,
330                unsigned char *out, size_t *outl, size_t outsize,
331                const unsigned char *in, size_t inl)
332 {
333     PROV_GCM_CTX *ctx = (PROV_GCM_CTX *)vctx;
334
335     if (!ossl_prov_is_running())
336         return 0;
337
338     if (outsize < inl) {
339         ERR_raise(ERR_LIB_PROV, PROV_R_OUTPUT_BUFFER_TOO_SMALL);
340         return 0;
341     }
342
343     if (gcm_cipher_internal(ctx, out, outl, in, inl) <= 0)
344         return 0;
345
346     *outl = inl;
347     return 1;
348 }
349
350 /*
351  * See SP800-38D (GCM) Section 8 "Uniqueness requirement on IVS and keys"
352  *
353  * See also 8.2.2 RBG-based construction.
354  * Random construction consists of a free field (which can be NULL) and a
355  * random field which will use a DRBG that can return at least 96 bits of
356  * entropy strength. (The DRBG must be seeded by the FIPS module).
357  */
358 static int gcm_iv_generate(PROV_GCM_CTX *ctx, int offset)
359 {
360     int sz = ctx->ivlen - offset;
361
362     /* Must be at least 96 bits */
363     if (sz <= 0 || ctx->ivlen < GCM_IV_DEFAULT_SIZE)
364         return 0;
365
366     /* Use DRBG to generate random iv */
367     if (RAND_bytes_ex(ctx->libctx, ctx->iv + offset, sz) <= 0)
368         return 0;
369     ctx->iv_state = IV_STATE_BUFFERED;
370     ctx->iv_gen_rand = 1;
371     return 1;
372 }
373
374 static int gcm_cipher_internal(PROV_GCM_CTX *ctx, unsigned char *out,
375                                size_t *padlen, const unsigned char *in,
376                                size_t len)
377 {
378     size_t olen = 0;
379     int rv = 0;
380     const PROV_GCM_HW *hw = ctx->hw;
381
382     if (ctx->tls_aad_len != UNINITIALISED_SIZET)
383         return gcm_tls_cipher(ctx, out, padlen, in, len);
384
385     if (!ctx->key_set || ctx->iv_state == IV_STATE_FINISHED)
386         goto err;
387
388     /*
389      * FIPS requires generation of AES-GCM IV's inside the FIPS module.
390      * The IV can still be set externally (the security policy will state that
391      * this is not FIPS compliant). There are some applications
392      * where setting the IV externally is the only option available.
393      */
394     if (ctx->iv_state == IV_STATE_UNINITIALISED) {
395         if (!ctx->enc || !gcm_iv_generate(ctx, 0))
396             goto err;
397     }
398
399     if (ctx->iv_state == IV_STATE_BUFFERED) {
400         if (!hw->setiv(ctx, ctx->iv, ctx->ivlen))
401             goto err;
402         ctx->iv_state = IV_STATE_COPIED;
403     }
404
405     if (in != NULL) {
406         /*  The input is AAD if out is NULL */
407         if (out == NULL) {
408             if (!hw->aadupdate(ctx, in, len))
409                 goto err;
410         } else {
411             /* The input is ciphertext OR plaintext */
412             if (!hw->cipherupdate(ctx, in, len, out))
413                 goto err;
414         }
415     } else {
416         /* The tag must be set before actually decrypting data */
417         if (!ctx->enc && ctx->taglen == UNINITIALISED_SIZET)
418             goto err;
419         if (!hw->cipherfinal(ctx, ctx->buf))
420             goto err;
421         ctx->iv_state = IV_STATE_FINISHED; /* Don't reuse the IV */
422         goto finish;
423     }
424     olen = len;
425 finish:
426     rv = 1;
427 err:
428     *padlen = olen;
429     return rv;
430 }
431
432 static int gcm_tls_init(PROV_GCM_CTX *dat, unsigned char *aad, size_t aad_len)
433 {
434     unsigned char *buf;
435     size_t len;
436
437     if (!ossl_prov_is_running() || aad_len != EVP_AEAD_TLS1_AAD_LEN)
438        return 0;
439
440     /* Save the aad for later use. */
441     buf = dat->buf;
442     memcpy(buf, aad, aad_len);
443     dat->tls_aad_len = aad_len;
444     dat->tls_enc_records = 0;
445
446     len = buf[aad_len - 2] << 8 | buf[aad_len - 1];
447     /* Correct length for explicit iv. */
448     if (len < EVP_GCM_TLS_EXPLICIT_IV_LEN)
449         return 0;
450     len -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
451
452     /* If decrypting correct for tag too. */
453     if (!dat->enc) {
454         if (len < EVP_GCM_TLS_TAG_LEN)
455             return 0;
456         len -= EVP_GCM_TLS_TAG_LEN;
457     }
458     buf[aad_len - 2] = (unsigned char)(len >> 8);
459     buf[aad_len - 1] = (unsigned char)(len & 0xff);
460     /* Extra padding: tag appended to record. */
461     return EVP_GCM_TLS_TAG_LEN;
462 }
463
464 static int gcm_tls_iv_set_fixed(PROV_GCM_CTX *ctx, unsigned char *iv,
465                                 size_t len)
466 {
467     /* Special case: -1 length restores whole IV */
468     if (len == (size_t)-1) {
469         memcpy(ctx->iv, iv, ctx->ivlen);
470         ctx->iv_gen = 1;
471         ctx->iv_state = IV_STATE_BUFFERED;
472         return 1;
473     }
474     /* Fixed field must be at least 4 bytes and invocation field at least 8 */
475     if ((len < EVP_GCM_TLS_FIXED_IV_LEN)
476         || (ctx->ivlen - (int)len) < EVP_GCM_TLS_EXPLICIT_IV_LEN)
477             return 0;
478     if (len > 0)
479         memcpy(ctx->iv, iv, len);
480     if (ctx->enc
481         && RAND_bytes_ex(ctx->libctx, ctx->iv + len, ctx->ivlen - len) <= 0)
482             return 0;
483     ctx->iv_gen = 1;
484     ctx->iv_state = IV_STATE_BUFFERED;
485     return 1;
486 }
487
488 /*
489  * Handle TLS GCM packet format. This consists of the last portion of the IV
490  * followed by the payload and finally the tag. On encrypt generate IV,
491  * encrypt payload and write the tag. On verify retrieve IV, decrypt payload
492  * and verify tag.
493  */
494 static int gcm_tls_cipher(PROV_GCM_CTX *ctx, unsigned char *out, size_t *padlen,
495                           const unsigned char *in, size_t len)
496 {
497     int rv = 0;
498     size_t arg = EVP_GCM_TLS_EXPLICIT_IV_LEN;
499     size_t plen = 0;
500     unsigned char *tag = NULL;
501
502     if (!ossl_prov_is_running() || !ctx->key_set)
503         goto err;
504
505     /* Encrypt/decrypt must be performed in place */
506     if (out != in || len < (EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN))
507         goto err;
508
509     /*
510      * Check for too many keys as per FIPS 140-2 IG A.5 "Key/IV Pair Uniqueness
511      * Requirements from SP 800-38D".  The requirements is for one party to the
512      * communication to fail after 2^64 - 1 keys.  We do this on the encrypting
513      * side only.
514      */
515     if (ctx->enc && ++ctx->tls_enc_records == 0) {
516         ERR_raise(ERR_LIB_PROV, EVP_R_TOO_MANY_RECORDS);
517         goto err;
518     }
519
520     /*
521      * Set IV from start of buffer or generate IV and write to start of
522      * buffer.
523      */
524     if (ctx->enc) {
525         if (!getivgen(ctx, out, arg))
526             goto err;
527     } else {
528         if (!setivinv(ctx, out, arg))
529             goto err;
530     }
531
532     /* Fix buffer and length to point to payload */
533     in += EVP_GCM_TLS_EXPLICIT_IV_LEN;
534     out += EVP_GCM_TLS_EXPLICIT_IV_LEN;
535     len -= EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN;
536
537     tag = ctx->enc ? out + len : (unsigned char *)in + len;
538     if (!ctx->hw->oneshot(ctx, ctx->buf, ctx->tls_aad_len, in, len, out, tag,
539                           EVP_GCM_TLS_TAG_LEN)) {
540         if (!ctx->enc)
541             OPENSSL_cleanse(out, len);
542         goto err;
543     }
544     if (ctx->enc)
545         plen =  len + EVP_GCM_TLS_EXPLICIT_IV_LEN + EVP_GCM_TLS_TAG_LEN;
546     else
547         plen = len;
548
549     rv = 1;
550 err:
551     ctx->iv_state = IV_STATE_FINISHED;
552     ctx->tls_aad_len = UNINITIALISED_SIZET;
553     *padlen = plen;
554     return rv;
555 }
556