Coverage Report

Created: 2026-01-09 06:46

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
    {
91
      /* Straightforward encoding w/o extra checksum as used by ECDH.  */
92
0
      nframe = dek->keylen;
93
0
      log_assert (nframe > 4);  /*(for the log_debug)*/
94
0
      frame = xmalloc_secure (nframe);
95
0
      memcpy (frame, dek->key, nframe);
96
0
      if (DBG_CRYPTO)
97
0
        log_debug ("encode_session_key: "
98
0
                   "[%d] %02x  %02x %02x ...  %02x %02x %02x\n",
99
0
                   (int) dek->keylen, frame[0], frame[1], frame[2],
100
0
                   frame[nframe-3], frame[nframe-2], frame[nframe-1]);
101
102
0
      return gcry_mpi_set_opaque (NULL, frame, 8*nframe);
103
0
    }
104
105
0
  csum = 0;
106
0
  for (p = dek->key, i=0; i < dek->keylen; i++)
107
0
    csum += *p++;
108
109
  /* Shortcut for ECDH.  It's padding is minimal to simply make the
110
     output be a multiple of 8 bytes.  */
111
0
  if (openpgp_pk_algo == PUBKEY_ALGO_ECDH)
112
0
    {
113
      /* Pad to 8 byte granularity; the padding byte is the number of
114
       * padded bytes.
115
       *
116
       * A  DEK(k bytes)  CSUM(2 bytes) 0x 0x 0x 0x ... 0x
117
       *                                +---- x times ---+
118
       */
119
0
      nframe = (( 1 + dek->keylen + 2 /* The value so far is always odd. */
120
0
                  + 7 ) & (~7));
121
122
      /* alg+key+csum fit and the size is congruent to 8.  */
123
0
      log_assert (!(nframe%8) && nframe > 1 + dek->keylen + 2 );
124
125
0
      frame = xmalloc_secure (nframe);
126
0
      n = 0;
127
0
      frame[n++] = dek->algo;
128
0
      memcpy (frame+n, dek->key, dek->keylen);
129
0
      n += dek->keylen;
130
0
      frame[n++] = csum >> 8;
131
0
      frame[n++] = csum;
132
0
      i = nframe - n;         /* Number of padded bytes.  */
133
0
      memset (frame+n, i, i); /* Use it as the value of each padded byte.  */
134
0
      log_assert (n+i == nframe);
135
136
0
      if (DBG_CRYPTO)
137
0
        log_debug ("encode_session_key: "
138
0
                   "[%d] %02x  %02x %02x ...  %02x %02x %02x\n",
139
0
                   (int) nframe, frame[0], frame[1], frame[2],
140
0
                   frame[nframe-3], frame[nframe-2], frame[nframe-1]);
141
142
0
      return gcry_mpi_set_opaque (NULL, frame, 8*nframe);
143
0
    }
144
145
  /* The current limitation is that we can only use a session key
146
   * whose length is a multiple of BITS_PER_MPI_LIMB
147
   * I think we can live with that.
148
   */
149
0
  if (dek->keylen + 7 > nframe || !nframe)
150
0
    log_bug ("can't encode a %d bit key in a %d bits frame\n",
151
0
             dek->keylen*8, nbits );
152
153
  /* We encode the session key according to PKCS#1 v1.5 (see section
154
   * 13.1.1 of RFC 4880):
155
   *
156
   *     0  2  RND(i bytes)  0  A  DEK(k bytes)  CSUM(2 bytes)
157
   *
158
   * (But how can we store the leading 0 - the external representation
159
   *  of MPIs doesn't allow leading zeroes =:-)
160
   *
161
   * RND are (at least 1) non-zero random bytes.
162
   * A   is the cipher algorithm
163
   * DEK is the encryption key (session key) length k depends on the
164
   *     cipher algorithm (20 is used with blowfish160).
165
   * CSUM is the 16 bit checksum over the DEK
166
   */
167
168
0
  frame = xmalloc_secure( nframe );
169
0
  n = 0;
170
0
  frame[n++] = 0;
171
0
  frame[n++] = 2;
172
  /* The number of random bytes are the number of otherwise unused
173
     bytes.  See diagram above.  */
174
0
  i = nframe - 6 - dek->keylen;
175
0
  log_assert( i > 0 );
176
0
  p = gcry_random_bytes_secure (i, GCRY_STRONG_RANDOM);
177
  /* Replace zero bytes by new values.  */
178
0
  for (;;)
179
0
    {
180
0
      int j, k;
181
0
      byte *pp;
182
183
      /* Count the zero bytes. */
184
0
      for (j=k=0; j < i; j++ )
185
0
        if (!p[j])
186
0
          k++;
187
0
      if (!k)
188
0
        break; /* Okay: no zero bytes. */
189
0
      k += k/128 + 3; /* Better get some more. */
190
0
      pp = gcry_random_bytes_secure (k, GCRY_STRONG_RANDOM);
191
0
      for (j=0; j < i && k ;)
192
0
        {
193
0
          if (!p[j])
194
0
            p[j] = pp[--k];
195
0
          if (p[j])
196
0
            j++;
197
0
        }
198
0
      xfree (pp);
199
0
    }
200
0
  memcpy (frame+n, p, i);
201
0
  xfree (p);
202
0
  n += i;
203
0
  frame[n++] = 0;
204
0
  frame[n++] = dek->algo;
205
0
  memcpy (frame+n, dek->key, dek->keylen );
206
0
  n += dek->keylen;
207
0
  frame[n++] = csum >>8;
208
0
  frame[n++] = csum;
209
0
  log_assert (n == nframe);
210
0
  return gcry_mpi_set_opaque (NULL, frame, 8*n);
211
0
}
212
213
214
static gcry_mpi_t
215
do_encode_md( gcry_md_hd_t md, int algo, size_t len, unsigned nbits,
216
        const byte *asn, size_t asnlen )
217
0
{
218
0
    size_t nframe = (nbits+7) / 8;
219
0
    byte *frame;
220
0
    int i,n;
221
0
    gcry_mpi_t a;
222
223
0
    if (len + asnlen + 4  > nframe)
224
0
      {
225
0
        log_error ("can't encode a %d bit MD into a %d bits frame, algo=%d\n",
226
0
                   (int)(len*8), (int)nbits, algo);
227
0
        return NULL;
228
0
      }
229
230
    /* We encode the MD in this way:
231
     *
232
     *     0  1 PAD(n bytes)   0  ASN(asnlen bytes)  MD(len bytes)
233
     *
234
     * PAD consists of FF bytes.
235
     */
236
0
    frame = gcry_md_is_secure (md)? xmalloc_secure (nframe) : xmalloc (nframe);
237
0
    n = 0;
238
0
    frame[n++] = 0;
239
0
    frame[n++] = 1; /* block type */
240
0
    i = nframe - len - asnlen -3 ;
241
0
    log_assert( i > 1 );
242
0
    memset( frame+n, 0xff, i ); n += i;
243
0
    frame[n++] = 0;
244
0
    memcpy( frame+n, asn, asnlen ); n += asnlen;
245
0
    memcpy( frame+n, gcry_md_read (md, algo), len ); n += len;
246
0
    log_assert( n == nframe );
247
248
0
    if (gcry_mpi_scan( &a, GCRYMPI_FMT_USG, frame, n, &nframe ))
249
0
  BUG();
250
0
    xfree(frame);
251
252
    /* Note that PGP before version 2.3 encoded the MD as:
253
     *
254
     *   0   1   MD(16 bytes)   0   PAD(n bytes)   1
255
     *
256
     * The MD is always 16 bytes here because it's always MD5.  We do
257
     * not support pre-v2.3 signatures, but I'm including this comment
258
     * so the information is easily found in the future.
259
     */
260
261
0
    return a;
262
0
}
263
264
265
/****************
266
 * Encode a message digest into an MPI.
267
 * If it's for a DSA signature, make sure that the hash is large
268
 * enough to fill up q.  If the hash is too big, take the leftmost
269
 * bits.
270
 */
271
gcry_mpi_t
272
encode_md_value (PKT_public_key *pk, gcry_md_hd_t md, int hash_algo)
273
0
{
274
0
  gcry_mpi_t frame;
275
0
  size_t mdlen;
276
277
0
  log_assert (hash_algo);
278
0
  log_assert (pk);
279
280
0
  if (pk->pubkey_algo == PUBKEY_ALGO_EDDSA)
281
0
    {
282
      /* EdDSA signs data of arbitrary length.  Thus no special
283
         treatment is required.  */
284
0
      frame = gcry_mpi_set_opaque_copy (NULL, gcry_md_read (md, hash_algo),
285
0
                                        8*gcry_md_get_algo_dlen (hash_algo));
286
0
    }
287
0
  else if (pk->pubkey_algo == PUBKEY_ALGO_DSA
288
0
           || pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
289
0
    {
290
      /* It's a DSA signature, so find out the size of q.  */
291
292
0
      size_t qbits = gcry_mpi_get_nbits (pk->pkey[1]);
293
294
      /* pkey[1] is Q for ECDSA, which is an uncompressed point,
295
         i.e.  04 <x> <y>  */
296
0
      if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA)
297
0
        qbits = ecdsa_qbits_from_Q (qbits);
298
299
      /* Make sure it is a multiple of 8 bits. */
300
0
      if ((qbits%8))
301
0
  {
302
0
    log_error(_("DSA requires the hash length to be a"
303
0
          " multiple of 8 bits\n"));
304
0
    return NULL;
305
0
  }
306
307
      /* Don't allow any q smaller than 160 bits.  This might need a
308
   revisit as the DSA2 design firms up, but for now, we don't
309
   want someone to issue signatures from a key with a 16-bit q
310
   or something like that, which would look correct but allow
311
   trivial forgeries.  Yes, I know this rules out using MD5 with
312
   DSA. ;) */
313
0
      if (qbits < 160)
314
0
  {
315
0
    log_error (_("%s key %s uses an unsafe (%zu bit) hash\n"),
316
0
                     openpgp_pk_algo_name (pk->pubkey_algo),
317
0
                     keystr_from_pk (pk), qbits);
318
0
    return NULL;
319
0
  }
320
321
322
      /* ECDSA 521 is special has it is larger than the largest hash
323
         we have (SHA-512).  Thus we change the size for further
324
         processing to 512.  */
325
0
      if (pk->pubkey_algo == PUBKEY_ALGO_ECDSA && qbits > 512)
326
0
        qbits = 512;
327
328
      /* Check if we're too short.  Too long is safe as we'll
329
   automatically left-truncate.  */
330
0
      mdlen = gcry_md_get_algo_dlen (hash_algo);
331
0
      if (mdlen < qbits/8)
332
0
  {
333
0
    log_error (_("%s key %s requires a %zu bit or larger hash "
334
0
                       "(hash is %s)\n"),
335
0
                     openpgp_pk_algo_name (pk->pubkey_algo),
336
0
                     keystr_from_pk (pk), qbits,
337
0
                     gcry_md_algo_name (hash_algo));
338
0
    return NULL;
339
0
  }
340
341
     /* Note that we do the truncation by passing QBITS/8 as length to
342
        mpi_scan.  */
343
0
      if (gcry_mpi_scan (&frame, GCRYMPI_FMT_USG,
344
0
                         gcry_md_read (md, hash_algo), qbits/8, NULL))
345
0
        BUG();
346
0
    }
347
0
  else
348
0
    {
349
0
      gpg_error_t rc;
350
0
      byte *asn;
351
0
      size_t asnlen;
352
353
0
      rc = gcry_md_algo_info (hash_algo, GCRYCTL_GET_ASNOID, NULL, &asnlen);
354
0
      if (rc)
355
0
        log_fatal ("can't get OID of digest algorithm %d: %s\n",
356
0
                   hash_algo, gpg_strerror (rc));
357
0
      asn = xtrymalloc (asnlen);
358
0
      if (!asn)
359
0
        return NULL;
360
0
      if ( gcry_md_algo_info (hash_algo, GCRYCTL_GET_ASNOID, asn, &asnlen) )
361
0
        BUG();
362
0
      frame = do_encode_md (md, hash_algo, gcry_md_get_algo_dlen (hash_algo),
363
0
                            gcry_mpi_get_nbits (pk->pkey[0]), asn, asnlen);
364
0
      xfree (asn);
365
0
    }
366
367
0
  return frame;
368
0
}