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