Coverage Report

Created: 2026-12-01 06:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gnupg/common/kem.c
Line
Count
Source
1
/* kem.c -  KEM helper functions
2
 * Copyright (C) 2024, 2026  g10 Code GmbH.
3
 *
4
 * This file is part of GnuPG.
5
 *
6
 * GnuPG is free software; you can redistribute and/or modify this
7
 * part of GnuPG under the terms of either
8
 *
9
 *   - the GNU Lesser General Public License as published by the Free
10
 *     Software Foundation; either version 3 of the License, or (at
11
 *     your option) any later version.
12
 *
13
 * or
14
 *
15
 *   - the GNU General Public License as published by the Free
16
 *     Software Foundation; either version 2 of the License, or (at
17
 *     your option) any later version.
18
 *
19
 * or both in parallel, as here.
20
 *
21
 * GnuPG is distributed in the hope that it will be useful, but
22
 * WITHOUT ANY WARRANTY; without even the implied warranty of
23
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
24
 * General Public License for more details.
25
 *
26
 * You should have received copies of the GNU General Public License
27
 * and the GNU Lesser General Public License along with this program;
28
 * if not, see <https://www.gnu.org/licenses/>.
29
 * SPDX-License-Identifier: (LGPL-3.0-or-later OR GPL-2.0-or-later)
30
 */
31
32
#include <config.h>
33
#include <stdlib.h>
34
#include <string.h>
35
#include <gpg-error.h>
36
#include <gcrypt.h>
37
38
#include "mischelp.h"
39
#include "util.h"
40
#include "kemhelp.h"
41
42
/* domSeperation as per *PGP specs. */
43
0
#define KMAC_KEY "OpenPGPCompositeKeyDerivationFunction"
44
45
/* customizationString as per *PGP specs. */
46
0
#define KMAC_CUSTOM "KDF"
47
48
/* The blocksize used for Keccak by compute_kmac256.  */
49
0
#define KECCAK512_BLOCKSIZE 136
50
51
52
53
static gpg_error_t
54
compute_kmac256 (void *digest, size_t digestlen,
55
                 const void *key, size_t keylen,
56
                 const void *custom, size_t customlen,
57
                 gcry_buffer_t *data_iov, int data_iovlen)
58
0
{
59
0
  gpg_error_t err;
60
0
  gcry_buffer_t iov[20];
61
0
  const unsigned char headPAD[2] = { 1, KECCAK512_BLOCKSIZE };
62
0
  unsigned char headK[3];
63
0
  const unsigned char pad[KECCAK512_BLOCKSIZE] = { 0 };
64
0
  unsigned char right_encode_L[3];
65
0
  unsigned int len;
66
0
  int iovcnt;
67
68
0
  if (data_iovlen >= DIM(iov) - 6)
69
0
    return gpg_error (GPG_ERR_TOO_LARGE);
70
71
  /* Check the validity conditions of NIST SP 800-185 */
72
0
  if (keylen >= 255 || customlen >= 255 || digestlen >= 255)
73
0
    return gpg_error (GPG_ERR_TOO_LARGE);
74
75
0
  iovcnt = 0;
76
0
  iov[iovcnt].data = "KMAC";
77
0
  iov[iovcnt].off = 0;
78
0
  iov[iovcnt].len = 4;
79
0
  iovcnt++;
80
81
0
  iov[iovcnt].data = (void *)custom;
82
0
  iov[iovcnt].off = 0;
83
0
  iov[iovcnt].len = customlen;
84
0
  iovcnt++;
85
86
0
  iov[iovcnt].data = (void *)headPAD;
87
0
  iov[iovcnt].off = 0;
88
0
  iov[iovcnt].len = sizeof (headPAD);
89
0
  iovcnt++;
90
91
0
  if (keylen < 32)
92
0
    {
93
0
      headK[0] = 1;
94
0
      headK[1] = (keylen*8)&0xff;
95
0
      iov[iovcnt].data = headK;
96
0
      iov[iovcnt].off = 0;
97
0
      iov[iovcnt].len = 2;
98
0
    }
99
0
  else
100
0
    {
101
0
      headK[0] = 2;
102
0
      headK[1] = (keylen*8)>>8;
103
0
      headK[2] = (keylen*8)&0xff;
104
0
      iov[iovcnt].data = headK;
105
0
      iov[iovcnt].off = 0;
106
0
      iov[iovcnt].len = 3;
107
0
    }
108
0
  iovcnt++;
109
110
0
  iov[iovcnt].data = (void *)key;
111
0
  iov[iovcnt].off = 0;
112
0
  iov[iovcnt].len = keylen;
113
0
  iovcnt++;
114
115
0
  len = iov[2].len + iov[3].len + iov[4].len;
116
0
  len %= KECCAK512_BLOCKSIZE;
117
118
0
  iov[iovcnt].data = (unsigned char *)pad;
119
0
  iov[iovcnt].off = 0;
120
0
  iov[iovcnt].len = sizeof (pad) - len;
121
0
  iovcnt++;
122
123
0
  memcpy (&iov[iovcnt], data_iov, data_iovlen * sizeof (gcry_buffer_t));
124
0
  iovcnt += data_iovlen;
125
126
0
  if (digestlen < 32)
127
0
    {
128
0
      right_encode_L[0] = (digestlen * 8) & 0xff;
129
0
      right_encode_L[1] = 1;
130
0
    }
131
0
  else
132
0
    {
133
0
      right_encode_L[0] = (digestlen * 8) >> 8;
134
0
      right_encode_L[1] = (digestlen * 8) & 0xff;
135
0
      right_encode_L[2] = 2;
136
0
    }
137
138
0
  iov[iovcnt].data = right_encode_L;
139
0
  iov[iovcnt].off = 0;
140
0
  iov[iovcnt].len = 3;
141
0
  iovcnt++;
142
143
0
  err = gcry_md_hash_buffers_ext (GCRY_MD_CSHAKE256, 0,
144
0
                                  digest, digestlen, iov, iovcnt);
145
0
  return err;
146
0
}
147
148
149
/* Compute KEK for ECC with KDF_ALGO, HASHALGO, ECDH result, and
150
 * KDF_PARAMS.
151
 *
152
 * KDF_PARAMS is specified by upper layer.
153
 */
154
gpg_error_t
155
gnupg_ecc_kem_kdf (void *kek, size_t kek_len, int kdf_algo,
156
                   int hashalgo, const void *ecdh, size_t ecdh_len,
157
                   const unsigned char *kdf_params, size_t kdf_params_len)
158
0
{
159
  /* Traditional ECC */
160
0
  gpg_error_t err;
161
0
  gcry_kdf_hd_t hd;
162
0
  unsigned long param[1];
163
164
0
  param[0] = kek_len;
165
0
  err = gcry_kdf_open (&hd, kdf_algo, hashalgo, param, 1,
166
0
                       ecdh, ecdh_len, NULL, 0, NULL, 0,
167
0
                       kdf_params, kdf_params_len);
168
0
  if (!err)
169
0
    {
170
0
      gcry_kdf_compute (hd, NULL);
171
0
      gcry_kdf_final (hd, kek_len, kek);
172
0
      gcry_kdf_close (hd);
173
0
    }
174
175
0
  return err;
176
0
}
177
178
179
/* Compute KEK for ECC with HASHALGO, ECDH result, ciphertext in
180
 * ECC_CT (which is an ephemeral key), and public key in ECC_PK.
181
 */
182
gpg_error_t
183
gnupg_ecc_kem_simple_kdf (void *kek, size_t kek_len,
184
                          int hashalgo, const void *ecdh, size_t ecdh_len,
185
                          const void *ecc_ct, size_t ecc_ct_len,
186
                          const void *ecc_pk, size_t ecc_pk_len)
187
0
{
188
  /* ECC part in composite KEM */
189
0
  gcry_buffer_t iov[3];
190
0
  unsigned int dlen;
191
192
0
  dlen = gcry_md_get_algo_dlen (hashalgo);
193
0
  if (kek_len != dlen)
194
0
    return gpg_error (GPG_ERR_INV_LENGTH);
195
196
0
  memset (iov, 0, sizeof (iov));
197
198
0
  iov[0].data = (unsigned char *)ecdh;
199
0
  iov[0].len = ecdh_len;
200
0
  iov[1].data = (unsigned char *)ecc_ct;
201
0
  iov[1].len = ecc_ct_len;
202
0
  iov[2].data = (unsigned char *)ecc_pk;
203
0
  iov[2].len = ecc_pk_len;
204
0
  gcry_md_hash_buffers (hashalgo, 0, kek, iov, 3);
205
206
0
  return 0;
207
0
}
208
209
210
/* Compute KEK by combining two KEMs.  The caller provides a buffer
211
 * KEK allocated with size KEK_LEN which will receive the computed
212
 * KEK. (ECC_SS, ECC_SS_LEN) is the shared secret of the first key.
213
 * (ECC_CT, ECC_CT_LEN) is the ciphertext of the first key.
214
 * (MLKEM_SS, ECC_SS_LEN) is the shared secret of the second key.
215
 * (MLKEM_CT, MLKEM_CT_LEN) is the ciphertext of the second key.
216
 * (FIXEDINFO, FIXEDINFO_LEN) is an octet string used to bind the KEK
217
 * to a the key; for PGP we use the concatenation of the session key's
218
 * algorithm id and the v5 fingerprint of the key.  */
219
gpg_error_t
220
gnupg_kem_combiner (void *kek, size_t kek_len,
221
                    const void *ecc_ss, size_t ecc_ss_len,
222
                    const void *ecc_ct, size_t ecc_ct_len,
223
                    const void *mlkem_ss, size_t mlkem_ss_len,
224
                    const void *mlkem_ct, size_t mlkem_ct_len,
225
                    const void *fixedinfo, size_t fixedinfo_len)
226
0
{
227
0
  gpg_error_t err;
228
0
  gcry_buffer_t iov[6];
229
230
0
  memset (iov, 0, sizeof (iov));
231
232
0
  iov[0].data = "\x00\x00\x00\x01"; /* Counter */
233
0
  iov[0].len = 4;
234
235
0
  iov[1].data = (unsigned char *)ecc_ss;
236
0
  iov[1].len = ecc_ss_len;
237
238
0
  iov[2].data = (unsigned char *)ecc_ct;
239
0
  iov[2].len = ecc_ct_len;
240
241
0
  iov[3].data = (unsigned char *)mlkem_ss;
242
0
  iov[3].len = mlkem_ss_len;
243
244
0
  iov[4].data = (unsigned char *)mlkem_ct;
245
0
  iov[4].len = mlkem_ct_len;
246
247
0
  iov[5].data = (unsigned char *)fixedinfo;
248
0
  iov[5].len = fixedinfo_len;
249
250
0
  err = compute_kmac256 (kek, kek_len,
251
0
                         KMAC_KEY, strlen (KMAC_KEY),
252
0
                         KMAC_CUSTOM, strlen (KMAC_CUSTOM), iov, 6);
253
0
  return err;
254
0
}
255
256
257
/* Compute KEK by combining two KEMs; this ise the RFC9980 version
258
 * using SHA3-256.  The caller provides a buffer KEK allocated with
259
 * size KEK_LEN which will receive the computed
260
 * KEK. (ECC_SS,ECC_SS_LEN) is the shared secret of the first key.
261
 * (ECC_CT,ECC_CT_LEN) is the ciphertext of the first key.
262
 * (ECC_PK,ECC_PK_LEN) is the public key of the first key.
263
 * (MLKEM_SS,ECC_SS_LEN) is the shared secret of the second key.
264
 * (FIXEDINFO, FIXEDINFO_LEN) is an octet string used to bind the KEK
265
 * to a the key.  */
266
gpg_error_t
267
gnupg_kem_combiner_sha3_256 (void *kek, size_t kek_len,
268
                             const void *ecc_ss, size_t ecc_ss_len,
269
                             const void *ecc_ct, size_t ecc_ct_len,
270
                             const void *ecc_pk, size_t ecc_pk_len,
271
                             const void *mlkem_ss, size_t mlkem_ss_len,
272
                             const void *fixedinfo, size_t fixedinfo_len)
273
0
{
274
0
  gpg_error_t err;
275
0
  gcry_buffer_t iov[5];
276
277
0
  memset (iov, 0, sizeof (iov));
278
279
0
  iov[0].data = (unsigned char *)mlkem_ss;
280
0
  iov[0].len = mlkem_ss_len;
281
282
0
  iov[1].data = (unsigned char *)ecc_ss;
283
0
  iov[1].len = ecc_ss_len;
284
285
0
  iov[2].data = (unsigned char *)ecc_ct;
286
0
  iov[2].len = ecc_ct_len;
287
288
0
  iov[3].data = (unsigned char *)ecc_pk;
289
0
  iov[3].len = ecc_pk_len;
290
291
0
  iov[4].data = (unsigned char *)fixedinfo;
292
0
  iov[4].len = fixedinfo_len;
293
294
0
  err = gcry_md_hash_buffers_ext (GCRY_MD_SHA3_256, 0,
295
0
                                  kek, kek_len, iov, 5);
296
0
  return err;
297
0
}
298
299
300

301
302
#define ECC_CURVE25519_INDEX 0
303
static const struct gnupg_ecc_params ecc_table[] =
304
  {
305
    {
306
      "Curve25519",
307
      33, 32, 32,
308
      GCRY_MD_SHA3_256, GCRY_KEM_RAW_X25519,
309
      1, 1, 0
310
    },
311
    {
312
      "ietf25",
313
      32, 32, 32,
314
      GCRY_MD_SHA3_256, GCRY_KEM_RAW_X25519,
315
      0, 0, 0
316
    },
317
    {
318
      "X448",
319
      56, 56, 56,
320
      GCRY_MD_SHA3_512, GCRY_KEM_RAW_X448,
321
      0, 0, 0
322
    },
323
    {
324
      "NIST P-256",
325
      65, 32, 65,
326
      GCRY_MD_SHA3_256, GCRY_KEM_RAW_P256R1,
327
      0, 0, 1
328
    },
329
    {
330
      "NIST P-384",
331
      97, 48, 97,
332
      GCRY_MD_SHA3_512, GCRY_KEM_RAW_P384R1,
333
      0, 0, 1
334
    },
335
    {
336
      "NIST P-521",
337
      133, 66, 133,
338
      GCRY_MD_SHA3_512, GCRY_KEM_RAW_P521R1,
339
      0, 0, 1
340
    },
341
    {
342
      "brainpoolP256r1",
343
      65, 32, 65,
344
      GCRY_MD_SHA3_256, GCRY_KEM_RAW_BP256,
345
      0, 0, 1
346
    },
347
    {
348
      "brainpoolP384r1",
349
      97, 48, 97,
350
      GCRY_MD_SHA3_512, GCRY_KEM_RAW_BP384,
351
      0, 0, 1
352
    },
353
    {
354
      "brainpoolP512r1",
355
      129, 64, 129,
356
      GCRY_MD_SHA3_512, GCRY_KEM_RAW_BP512,
357
      0, 0, 1
358
    },
359
#ifdef GCRY_KEM_RAW_P256K1
360
    {
361
      "secp256k1",
362
      65, 32, 65,
363
      GCRY_MD_SHA3_256, GCRY_KEM_RAW_P256K1,
364
      0, 0, 1
365
    },
366
#endif
367
    { NULL, 0, 0, 0, 0, 0, 0, 0, 0 }
368
};
369
370
371
/* Return the ECC parameters for CURVE.  CURVE is expected to be the
372
 * canonical name.  */
373
const struct gnupg_ecc_params *
374
gnupg_get_ecc_params (const char *curve)
375
0
{
376
0
  int i;
377
378
0
  for (i = 0; ecc_table[i].curve; i++)
379
0
    if (!strcmp (ecc_table[i].curve, curve))
380
0
      return &ecc_table[i];
381
382
0
  return NULL;
383
0
}
384
385
386
387
/* Derive a session key for composite CMS algos. With GENERATE set the
388
 * input is a session key, with GENERATE clear the input is the
389
 * encrypted key; reversed if GENERATE is not set.
390
 * (SHARED,SHARED_LEN) gives the shared secret from which a KEK is
391
 * derived.  (INPKEY,INPKEY_LEN) is the the encrypted key or in
392
 * generate mode the session key.  That key will be
393
 * decrypted/encrypted and hashed to formthe session key or the
394
 * encrypted key.  PQCALGOSTR, WRAPALSOSTR, and KDFALGOSTR derscribe
395
 * the used algorithms.  OUTKEY_LEN is the requested length for the
396
 * output.  On success the allocated output is stored at R_OUTKEY.
397
 * ENABLE_DEBUG enables debug output.  */
398
gpg_error_t
399
gnupg_kem_derive_or_gen_seskey (int enable_debug, int generate,
400
                                const void *shared, size_t shared_len,
401
                                const void *inpkey, size_t inpkey_len,
402
                                const char *pqcalgostr,
403
                                const char *wrapalgostr,
404
                                const char *kdfalgostr,
405
                                size_t outkey_len,
406
                                void **r_outkey)
407
0
{
408
0
  gpg_error_t err;
409
0
  void *outkey;
410
0
  gcry_cipher_hd_t hd;
411
0
  gcry_kdf_hd_t kdfhd;
412
0
  unsigned long kdfparam[1];
413
0
  int wrapalgo, kdfalgo, kdfmacalgo;
414
0
  void *kek = NULL;
415
0
  size_t kek_len;
416
  /* Template for the RFC-9629 key derivation:
417
   *  CMSORIforKEMOtherInfo ::= SEQUENCE {
418
   *    wrap KeyEncryptionAlgorithmIdentifier,
419
   *    kekLength INTEGER (1..65535),
420
   *    ukm [0] EXPLICIT UserKeyingMaterial OPTIONAL } */
421
0
  unsigned char cmsoriforkemotherinfo[18] =
422
0
    { 0x30, 0x10, 0x30, 0x0b, 0x06,
423
0
      0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x2d,
424
0
      0x02, 0x01, 0x20 };
425
0
#define CMSORIFORKEMOTHERINFO_OID 14    /* Offset to the last OID byte.  */
426
0
#define CMSORIFORKEMOTHERINFO_KEKLEN 17 /* Offset to the KEK_LEN byte.   */
427
428
429
0
  if (!strcmp (wrapalgostr, "aes256-wrap"))
430
0
    {
431
0
      wrapalgo = GCRY_CIPHER_AES256;
432
0
      cmsoriforkemotherinfo[CMSORIFORKEMOTHERINFO_OID] = 45;
433
0
    }
434
0
  else if (!strcmp (wrapalgostr, "aes192-wrap"))
435
0
    {
436
0
      wrapalgo = GCRY_CIPHER_AES192;
437
0
      cmsoriforkemotherinfo[CMSORIFORKEMOTHERINFO_OID] = 25;
438
0
    }
439
0
  else if (!strcmp (wrapalgostr, "aes128-wrap"))
440
0
    {
441
0
      wrapalgo = GCRY_CIPHER_AES128;
442
0
      cmsoriforkemotherinfo[CMSORIFORKEMOTHERINFO_OID] = 5;
443
0
    }
444
0
  else
445
0
    return gpg_error (GPG_ERR_CIPHER_ALGO);
446
447
0
  if (!strcmp (kdfalgostr, "hkdf-sha256"))
448
0
    {
449
0
      kdfalgo = GCRY_KDF_HKDF;
450
0
      kdfmacalgo = GCRY_MAC_HMAC_SHA256;
451
0
    }
452
0
  else
453
0
    return gpg_error (GPG_ERR_DIGEST_ALGO);
454
455
  /* Check that the requested length matches and then allocate.  */
456
0
  if (generate)
457
0
    {
458
0
      if (inpkey_len + 8 != outkey_len)
459
0
        {
460
0
          log_info ("%s: session key size %zu does not fit for '%s'\n",
461
0
                    __func__, outkey_len, pqcalgostr);
462
0
          return gpg_error (GPG_ERR_INV_DATA);
463
0
        }
464
0
    }
465
0
  else
466
0
    {
467
0
      if (inpkey_len != outkey_len + 8)
468
0
        {
469
0
          log_info ("%s: encrypted key size %zu does not fit for '%s'\n",
470
0
                    __func__, inpkey_len, pqcalgostr);
471
0
          return gpg_error (GPG_ERR_INV_DATA);
472
0
        }
473
0
    }
474
475
  /* Note: From here on jump to the leave label on error.  */
476
0
  kek_len = generate? inpkey_len : outkey_len;
477
478
  /* Check the length of the KEK.  This also makes sure that it fits
479
   * the DER encoding in the template. */
480
0
  if (kek_len < 16 || kek_len > 127)
481
0
    {
482
0
      log_info ("%s: requested output key length is wrong (%zu)\n",
483
0
                __func__, outkey_len);
484
0
      err = gpg_error (GPG_ERR_INV_LENGTH);
485
0
      goto leave;
486
0
    }
487
0
  cmsoriforkemotherinfo[CMSORIFORKEMOTHERINFO_KEKLEN] = kek_len;
488
489
0
  kek = xtrymalloc_secure (kek_len);
490
0
  if (!kek)
491
0
    {
492
0
      err = gpg_error_from_syserror ();
493
0
      goto leave;
494
0
    }
495
496
0
  outkey = xtrymalloc_secure (outkey_len);
497
0
  if (!outkey)
498
0
    {
499
0
      err = gpg_error_from_syserror ();
500
0
      goto leave;
501
0
    }
502
503
0
  err = gcry_cipher_open (&hd, wrapalgo, GCRY_CIPHER_MODE_AESWRAP, 0);
504
0
  if (err)
505
0
    {
506
0
      log_error ("%s: failed to initialize '%s': %s\n",
507
0
                 __func__, wrapalgostr, gpg_strerror (err));
508
0
      goto leave;
509
0
    }
510
511
0
  kdfparam[0] = kek_len;
512
  /* log_debug ("%s: kdfalgo=%d kdfmacalgo=%d kddparm[0]=%lu\n", __func__, */
513
  /*            kdfalgo, kdfmacalgo, kdfparam[0]); */
514
  /* log_printhex (shared, shared_len, "%s: shared", __func__); */
515
  /* log_printhex (cmsoriforkemotherinfo, sizeof cmsoriforkemotherinfo, */
516
  /*               "%s: cmsoriforkemotherinfo", __func__); */
517
0
  err = gcry_kdf_open (&kdfhd, kdfalgo, kdfmacalgo,
518
0
                       kdfparam, 1,
519
0
                       shared, shared_len,
520
0
                       NULL, 0, NULL, 0,
521
0
                       cmsoriforkemotherinfo, sizeof cmsoriforkemotherinfo);
522
0
  if (err)
523
0
    {
524
0
      log_error ("%s: failed to open the HKDF function: %s\n",
525
0
                 __func__, gpg_strerror (err));
526
0
      gcry_cipher_close (hd);
527
0
      goto leave;
528
0
    }
529
530
0
  err = gcry_kdf_compute (kdfhd, NULL);
531
0
  if (!err)
532
0
    err = gcry_kdf_final (kdfhd, kek_len, kek);
533
0
  gcry_kdf_close (kdfhd);
534
535
0
  if (enable_debug)
536
0
    log_printhex (kek, kek_len, "Derived KEK :");
537
538
0
  err = gcry_cipher_setkey (hd, kek, kek_len);
539
0
  if (!err)
540
0
    {
541
0
      if (generate)
542
0
        err = gcry_cipher_encrypt (hd, outkey, outkey_len,
543
0
                                   inpkey, inpkey_len);
544
0
      else
545
0
        err = gcry_cipher_decrypt (hd, outkey, outkey_len,
546
0
                                   inpkey, inpkey_len);
547
0
    }
548
0
  gcry_cipher_close (hd);
549
0
  if (err)
550
0
    {
551
0
      log_error ("%s: error %s key using %s: %s\n",
552
0
                 __func__, generate? "encrypting": "decrypting",
553
0
                 wrapalgostr, gpg_strerror (err));
554
0
      goto leave;
555
0
    }
556
557
  /* Success:  Return the key.  */
558
0
  *r_outkey = outkey;
559
0
  outkey = NULL;
560
561
0
 leave:
562
0
  if (kek)
563
0
    {
564
0
      wipememory (kek, kek_len);
565
0
      xfree (kek);
566
0
    }
567
0
  if (outkey)
568
0
    {
569
0
      wipememory (outkey, outkey_len);
570
0
      xfree (outkey);
571
0
    }
572
0
  return err;
573
0
}