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