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