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