Coverage Report

Created: 2026-10-08 07:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/gnupg/g10/seskey.c
Line
Count
Source
1
/* seskey.c -  make session keys etc.
2
 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
3
 *               2006, 2009, 2010 Free Software Foundation, Inc.
4
 *
5
 * This file is part of GnuPG.
6
 *
7
 * GnuPG is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * GnuPG is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, see <https://www.gnu.org/licenses/>.
19
 */
20
21
#include <config.h>
22
#include <stdio.h>
23
#include <stdlib.h>
24
#include <string.h>
25
26
#include "gpg.h"
27
#include "../common/util.h"
28
#include "options.h"
29
#include "main.h"
30
#include "../common/i18n.h"
31
32
33
/* Generate a new session key in *DEK that is appropriate for the
34
 * algorithm DEK->ALGO (i.e., ensure that the key is not weak).
35
 *
36
 * This function overwrites DEK->KEYLEN, DEK->KEY.  The rest of the
37
 * fields are left as is.  */
38
void
39
make_session_key( DEK *dek )
40
0
{
41
0
    gcry_cipher_hd_t chd;
42
0
    int i, rc;
43
44
0
    dek->keylen = openpgp_cipher_get_algo_keylen (dek->algo);
45
46
0
    if (openpgp_cipher_open (&chd, dek->algo, GCRY_CIPHER_MODE_CFB,
47
0
           (GCRY_CIPHER_SECURE
48
0
            | (dek->algo >= 100 ?
49
0
         0 : GCRY_CIPHER_ENABLE_SYNC))) )
50
0
      BUG();
51
0
    gcry_randomize (dek->key, dek->keylen, GCRY_STRONG_RANDOM );
52
0
    for (i=0; i < 16; i++ )
53
0
      {
54
0
  rc = gcry_cipher_setkey (chd, dek->key, dek->keylen);
55
0
  if (!rc)
56
0
          {
57
0
      gcry_cipher_close (chd);
58
0
      return;
59
0
          }
60
0
        if (gpg_err_code (rc) != GPG_ERR_WEAK_KEY)
61
0
          BUG();
62
0
  log_info(_("weak key created - retrying\n") );
63
  /* Renew the session key until we get a non-weak key. */
64
0
  gcry_randomize (dek->key, dek->keylen, GCRY_STRONG_RANDOM);
65
0
      }
66
0
    log_fatal (_("cannot avoid weak key for symmetric cipher; "
67
0
                 "tried %d times!\n"), i);
68
0
}
69
70
71
/* Encode the session key stored in DEK as an MPI in preparation to
72
 * encrypt it with the public key algorithm OPENPGP_PK_ALGO with a key
73
 * whose length (the size of the public key) is NBITS.
74
 *
75
 * On success, returns an MPI, which the caller must free using
76
 * gcry_mpi_release().  */
77
gcry_mpi_t
78
encode_session_key (int openpgp_pk_algo, DEK *dek, unsigned int nbits)
79
0
{
80
0
  size_t nframe = (nbits+7) / 8;
81
0
  byte *p;
82
0
  byte *frame;
83
0
  int i,n;
84
0
  u16 csum;
85
86
0
  if (DBG_CRYPTO)
87
0
    log_debug ("encode_session_key: encoding %d byte DEK", dek->keylen);
88
89
0
  if (openpgp_pk_algo == PUBKEY_ALGO_KYBER
90
0
      || openpgp_pk_algo == PUBKEY_ALGO_X25519
91
0
      || IS_PUBKEY_ALGO_MLK (openpgp_pk_algo))
92
0
    {
93
      /* Straightforward encoding w/o extra checksum as used by ECDH.  */
94
0
      nframe = dek->keylen;
95
0
      log_assert (nframe > 4);  /*(for the log_debug)*/
96
0
      frame = xmalloc_secure (nframe);
97
0
      memcpy (frame, dek->key, nframe);
98
0
      if (DBG_CRYPTO)
99
0
        log_debug ("encode_session_key: "
100
0
                   "[%d] %02x  %02x %02x ...  %02x %02x %02x\n",
101
0
                   (int) dek->keylen, frame[0], frame[1], frame[2],
102
0
                   frame[nframe-3], frame[nframe-2], frame[nframe-1]);
103
104
0
      return gcry_mpi_set_opaque (NULL, frame, 8*nframe);
105
0
    }
106
107
0
  csum = 0;
108
0
  for (p = dek->key, i=0; i < dek->keylen; i++)
109
0
    csum += *p++;
110
111
  /* Shortcut for ECDH.  It's padding is minimal to simply make the
112
     output be a multiple of 8 bytes.  */
113
0
  if (openpgp_pk_algo == PUBKEY_ALGO_ECDH)
114
0
    {
115
      /* Pad to 8 byte granularity; the padding byte is the number of
116
       * padded bytes.
117
       *
118
       * A  DEK(k bytes)  CSUM(2 bytes) 0x 0x 0x 0x ... 0x
119
       *                                +---- x times ---+
120
       */
121
0
      nframe = (( 1 + dek->keylen + 2 /* The value so far is always odd. */
122
0
                  + 7 ) & (~7));
123
124
      /* alg+key+csum fit and the size is congruent to 8.  */
125
0
      log_assert (!(nframe%8) && nframe > 1 + dek->keylen + 2 );
126
127
0
      frame = xmalloc_secure (nframe);
128
0
      n = 0;
129
0
      frame[n++] = dek->algo;
130
0
      memcpy (frame+n, dek->key, dek->keylen);
131
0
      n += dek->keylen;
132
0
      frame[n++] = csum >> 8;
133
0
      frame[n++] = csum;
134
0
      i = nframe - n;         /* Number of padded bytes.  */
135
0
      memset (frame+n, i, i); /* Use it as the value of each padded byte.  */
136
0
      log_assert (n+i == nframe);
137
138
0
      if (DBG_CRYPTO)
139
0
        log_debug ("encode_session_key: "
140
0
                   "[%d] %02x  %02x %02x ...  %02x %02x %02x\n",
141
0
                   (int) nframe, frame[0], frame[1], frame[2],
142
0
                   frame[nframe-3], frame[nframe-2], frame[nframe-1]);
143
144
0
      return gcry_mpi_set_opaque (NULL, frame, 8*nframe);
145
0
    }
146
147
  /* The current limitation is that we can only use a session key
148
   * whose length is a multiple of BITS_PER_MPI_LIMB
149
   * I think we can live with that.
150
   */
151
0
  if (dek->keylen + 7 > nframe || !nframe)
152
0
    log_bug ("can't encode a %d bit key in a %d bits frame\n",
153
0
             dek->keylen*8, nbits );
154
155
  /* We encode the session key according to PKCS#1 v1.5 (see section
156
   * 13.1.1 of RFC 4880):
157
   *
158
   *     0  2  RND(i bytes)  0  A  DEK(k bytes)  CSUM(2 bytes)
159
   *
160
   * (But how can we store the leading 0 - the external representation
161
   *  of MPIs doesn't allow leading zeroes =:-)
162
   *
163
   * RND are (at least 1) non-zero random bytes.
164
   * A   is the cipher algorithm
165
   * DEK is the encryption key (session key) length k depends on the
166
   *     cipher algorithm (20 is used with blowfish160).
167
   * CSUM is the 16 bit checksum over the DEK
168
   */
169
170
0
  frame = xmalloc_secure( nframe );
171
0
  n = 0;
172
0
  frame[n++] = 0;
173
0
  frame[n++] = 2;
174
  /* The number of random bytes are the number of otherwise unused
175
     bytes.  See diagram above.  */
176
0
  i = nframe - 6 - dek->keylen;
177
0
  log_assert( i > 0 );
178
0
  p = gcry_random_bytes_secure (i, GCRY_STRONG_RANDOM);
179
  /* Replace zero bytes by new values.  */
180
0
  for (;;)
181
0
    {
182
0
      int j, k;
183
0
      byte *pp;
184
185
      /* Count the zero bytes. */
186
0
      for (j=k=0; j < i; j++ )
187
0
        if (!p[j])
188
0
          k++;
189
0
      if (!k)
190
0
        break; /* Okay: no zero bytes. */
191
0
      k += k/128 + 3; /* Better get some more. */
192
0
      pp = gcry_random_bytes_secure (k, GCRY_STRONG_RANDOM);
193
0
      for (j=0; j < i && k ;)
194
0
        {
195
0
          if (!p[j])
196
0
            p[j] = pp[--k];
197
0
          if (p[j])
198
0
            j++;
199
0
        }
200
0
      xfree (pp);
201
0
    }
202
0
  memcpy (frame+n, p, i);
203
0
  xfree (p);
204
0
  n += i;
205
0
  frame[n++] = 0;
206
0
  frame[n++] = dek->algo;
207
0
  memcpy (frame+n, dek->key, dek->keylen );
208
0
  n += dek->keylen;
209
0
  frame[n++] = csum >>8;
210
0
  frame[n++] = csum;
211
0
  log_assert (n == nframe);
212
0
  return gcry_mpi_set_opaque (NULL, frame, 8*n);
213
0
}
214
215
216
static gcry_mpi_t
217
do_encode_md( gcry_md_hd_t md, int algo, size_t len, unsigned nbits,
218
        const byte *asn, size_t asnlen )
219
0
{
220
0
    size_t nframe = (nbits+7) / 8;
221
0
    byte *frame;
222
0
    int i,n;
223
0
    gcry_mpi_t a;
224
225
0
    if (len + asnlen + 4  > nframe)
226
0
      {
227
0
        log_error ("can't encode a %d bit MD into a %d bits frame, algo=%d\n",
228
0
                   (int)(len*8), (int)nbits, algo);
229
0
        return NULL;
230
0
      }
231
232
    /* We encode the MD in this way:
233
     *
234
     *     0  1 PAD(n bytes)   0  ASN(asnlen bytes)  MD(len bytes)
235
     *
236
     * PAD consists of FF bytes.
237
     */
238
0
    frame = gcry_md_is_secure (md)? xmalloc_secure (nframe) : xmalloc (nframe);
239
0
    n = 0;
240
0
    frame[n++] = 0;
241
0
    frame[n++] = 1; /* block type */
242
0
    i = nframe - len - asnlen -3 ;
243
0
    log_assert( i > 1 );
244
0
    memset( frame+n, 0xff, i ); n += i;
245
0
    frame[n++] = 0;
246
0
    memcpy( frame+n, asn, asnlen ); n += asnlen;
247
0
    memcpy( frame+n, gcry_md_read (md, algo), len ); n += len;
248
0
    log_assert( n == nframe );
249
250
0
    if (gcry_mpi_scan( &a, GCRYMPI_FMT_USG, frame, n, &nframe ))
251
0
  BUG();
252
0
    xfree(frame);
253
254
    /* Note that PGP before version 2.3 encoded the MD as:
255
     *
256
     *   0   1   MD(16 bytes)   0   PAD(n bytes)   1
257
     *
258
     * The MD is always 16 bytes here because it's always MD5.  We do
259
     * not support pre-v2.3 signatures, but I'm including this comment
260
     * so the information is easily found in the future.
261
     */
262
263
0
    return a;
264
0
}
265
266
267
/****************
268
 * Encode a message digest into an MPI.
269
 * If it's for a DSA signature, make sure that the hash is large
270
 * enough to fill up q.  If the hash is too big, take the leftmost
271
 * bits.
272
 */
273
gcry_mpi_t
274
encode_md_value (PKT_public_key *pk, gcry_md_hd_t md, int hash_algo)
275
0
{
276
0
  gcry_mpi_t frame;
277
0
  size_t mdlen;
278
279
0
  log_assert (hash_algo);
280
0
  log_assert (pk);
281
282
0
  if (pk->pubkey_algo == PUBKEY_ALGO_EDDSA
283
0
      || pk->pubkey_algo == PUBKEY_ALGO_ED25519)
284
0
    {
285
      /* EdDSA signs data of arbitrary length.  Thus no special
286
         treatment is required.  */
287
0
      frame = gcry_mpi_set_opaque_copy (NULL, gcry_md_read (md, hash_algo),
288
0
                                        8*gcry_md_get_algo_dlen (hash_algo));
289
0
    }
290
0
  else if (pk->pubkey_algo == PUBKEY_ALGO_DSA
291
0
           || pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
292
0
    {
293
      /* It's a DSA signature, so find out the size of q.  */
294
295
0
      size_t qbits = gcry_mpi_get_nbits (pk->pkey[1]);
296
297
      /* pkey[1] is Q for ECDSA, which is an uncompressed point,
298
         i.e.  04 <x> <y>  */
299
0
      if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
300
0
        qbits = ecdsa_qbits_from_Q (qbits);
301
302
      /* Make sure it is a multiple of 8 bits. */
303
0
      if ((qbits%8))
304
0
  {
305
0
    log_error(_("DSA requires the hash length to be a"
306
0
          " multiple of 8 bits\n"));
307
0
    return NULL;
308
0
  }
309
310
      /* Don't allow any q smaller than 160 bits.  This might need a
311
   revisit as the DSA2 design firms up, but for now, we don't
312
   want someone to issue signatures from a key with a 16-bit q
313
   or something like that, which would look correct but allow
314
   trivial forgeries.  Yes, I know this rules out using MD5 with
315
   DSA. ;) */
316
0
      if (qbits < 160)
317
0
  {
318
0
    log_error (_("%s key %s uses an unsafe (%zu bit) hash\n"),
319
0
                     openpgp_pk_algo_name (pk->pubkey_algo),
320
0
                     keystr_from_pk (pk), qbits);
321
0
    return NULL;
322
0
  }
323
324
325
      /* ECDSA 521 is special has it is larger than the largest hash
326
         we have (SHA-512).  Thus we change the size for further
327
         processing to 512.  */
328
0
      if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA && qbits > 512)
329
0
        qbits = 512;
330
331
      /* Check if we're too short.  Too long is safe as we'll
332
   automatically left-truncate.  */
333
0
      mdlen = gcry_md_get_algo_dlen (hash_algo);
334
0
      if (mdlen < qbits/8)
335
0
  {
336
0
    log_error (_("%s key %s requires a %zu bit or larger hash "
337
0
                       "(hash is %s)\n"),
338
0
                     openpgp_pk_algo_name (pk->pubkey_algo),
339
0
                     keystr_from_pk (pk), qbits,
340
0
                     gcry_md_algo_name (hash_algo));
341
0
    return NULL;
342
0
  }
343
344
     /* Note that we do the truncation by passing QBITS/8 as length to
345
        mpi_scan.  */
346
0
      if (gcry_mpi_scan (&frame, GCRYMPI_FMT_USG,
347
0
                         gcry_md_read (md, hash_algo), qbits/8, NULL))
348
0
        BUG();
349
0
    }
350
0
  else
351
0
    {
352
0
      gpg_error_t rc;
353
0
      byte *asn;
354
0
      size_t asnlen;
355
356
0
      rc = gcry_md_algo_info (hash_algo, GCRYCTL_GET_ASNOID, NULL, &asnlen);
357
0
      if (rc)
358
0
        log_fatal ("can't get OID of digest algorithm %d: %s\n",
359
0
                   hash_algo, gpg_strerror (rc));
360
0
      asn = xtrymalloc (asnlen);
361
0
      if (!asn)
362
0
        return NULL;
363
0
      if ( gcry_md_algo_info (hash_algo, GCRYCTL_GET_ASNOID, asn, &asnlen) )
364
0
        BUG();
365
0
      frame = do_encode_md (md, hash_algo, gcry_md_get_algo_dlen (hash_algo),
366
0
                            gcry_mpi_get_nbits (pk->pkey[0]), asn, asnlen);
367
0
      xfree (asn);
368
0
    }
369
370
0
  return frame;
371
0
}