chiark / gitweb /
dirmngr: hkp: Avoid potential race condition when some hosts die.
[gnupg2.git] / g10 / pubkey-enc.c
1 /* pubkey-enc.c - Process a public key encoded packet.
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2006, 2009,
3  *               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 "packet.h"
29 #include "keydb.h"
30 #include "trustdb.h"
31 #include "status.h"
32 #include "options.h"
33 #include "main.h"
34 #include "i18n.h"
35 #include "pkglue.h"
36 #include "call-agent.h"
37 #include "host2net.h"
38
39
40 static gpg_error_t get_it (PKT_pubkey_enc *k,
41                            DEK *dek, PKT_public_key *sk, u32 *keyid);
42
43
44 /* Check that the given algo is mentioned in one of the valid user-ids. */
45 static int
46 is_algo_in_prefs (kbnode_t keyblock, preftype_t type, int algo)
47 {
48   kbnode_t k;
49
50   for (k = keyblock; k; k = k->next)
51     {
52       if (k->pkt->pkttype == PKT_USER_ID)
53         {
54           PKT_user_id *uid = k->pkt->pkt.user_id;
55           prefitem_t *prefs = uid->prefs;
56
57           if (uid->created && prefs && !uid->is_revoked && !uid->is_expired)
58             {
59               for (; prefs->type; prefs++)
60                 if (prefs->type == type && prefs->value == algo)
61                   return 1;
62             }
63         }
64     }
65   return 0;
66 }
67
68
69 /*
70  * Get the session key from a pubkey enc packet and return it in DEK,
71  * which should have been allocated in secure memory by the caller.
72  */
73 gpg_error_t
74 get_session_key (ctrl_t ctrl, PKT_pubkey_enc * k, DEK * dek)
75 {
76   PKT_public_key *sk = NULL;
77   int rc;
78
79   if (DBG_CLOCK)
80     log_clock ("get_session_key enter");
81
82   rc = openpgp_pk_test_algo2 (k->pubkey_algo, PUBKEY_USAGE_ENC);
83   if (rc)
84     goto leave;
85
86   if ((k->keyid[0] || k->keyid[1]) && !opt.try_all_secrets)
87     {
88       sk = xmalloc_clear (sizeof *sk);
89       sk->pubkey_algo = k->pubkey_algo; /* We want a pubkey with this algo.  */
90       if (!(rc = get_seckey (sk, k->keyid)))
91         rc = get_it (k, dek, sk, k->keyid);
92     }
93   else if (opt.skip_hidden_recipients)
94     rc = gpg_error (GPG_ERR_NO_SECKEY);
95   else  /* Anonymous receiver: Try all available secret keys.  */
96     {
97       void *enum_context = NULL;
98       u32 keyid[2];
99
100       for (;;)
101         {
102           free_public_key (sk);
103           sk = xmalloc_clear (sizeof *sk);
104           rc = enum_secret_keys (ctrl, &enum_context, sk);
105           if (rc)
106             {
107               rc = GPG_ERR_NO_SECKEY;
108               break;
109             }
110           if (sk->pubkey_algo != k->pubkey_algo)
111             continue;
112           if (!(sk->pubkey_usage & PUBKEY_USAGE_ENC))
113             continue;
114           keyid_from_pk (sk, keyid);
115           if (!opt.quiet)
116             log_info (_("anonymous recipient; trying secret key %s ...\n"),
117                       keystr (keyid));
118
119           rc = get_it (k, dek, sk, keyid);
120           if (!rc)
121             {
122               if (!opt.quiet)
123                 log_info (_("okay, we are the anonymous recipient.\n"));
124               break;
125             }
126           else if (gpg_err_code (rc) == GPG_ERR_FULLY_CANCELED)
127             break; /* Don't try any more secret keys.  */
128         }
129       enum_secret_keys (ctrl, &enum_context, NULL);  /* free context */
130     }
131
132 leave:
133   free_public_key (sk);
134   if (DBG_CLOCK)
135     log_clock ("get_session_key leave");
136   return rc;
137 }
138
139
140 static gpg_error_t
141 get_it (PKT_pubkey_enc *enc, DEK *dek, PKT_public_key *sk, u32 *keyid)
142 {
143   gpg_error_t err;
144   byte *frame = NULL;
145   unsigned int n;
146   size_t nframe;
147   u16 csum, csum2;
148   int padding;
149   gcry_sexp_t s_data;
150   char *desc;
151   char *keygrip;
152   byte fp[MAX_FINGERPRINT_LEN];
153   size_t fpn;
154
155   if (DBG_CLOCK)
156     log_clock ("decryption start");
157
158   /* Get the keygrip.  */
159   err = hexkeygrip_from_pk (sk, &keygrip);
160   if (err)
161     goto leave;
162
163   /* Convert the data to an S-expression.  */
164   if (sk->pubkey_algo == PUBKEY_ALGO_ELGAMAL
165       || sk->pubkey_algo == PUBKEY_ALGO_ELGAMAL_E)
166     {
167       if (!enc->data[0] || !enc->data[1])
168         err = gpg_error (GPG_ERR_BAD_MPI);
169       else
170         err = gcry_sexp_build (&s_data, NULL, "(enc-val(elg(a%m)(b%m)))",
171                                enc->data[0], enc->data[1]);
172     }
173   else if (sk->pubkey_algo == PUBKEY_ALGO_RSA
174            || sk->pubkey_algo == PUBKEY_ALGO_RSA_E)
175     {
176       if (!enc->data[0])
177         err = gpg_error (GPG_ERR_BAD_MPI);
178       else
179         err = gcry_sexp_build (&s_data, NULL, "(enc-val(rsa(a%m)))",
180                                enc->data[0]);
181     }
182   else if (sk->pubkey_algo == PUBKEY_ALGO_ECDH)
183     {
184       if (!enc->data[0] || !enc->data[1])
185         err = gpg_error (GPG_ERR_BAD_MPI);
186       else
187         err = gcry_sexp_build (&s_data, NULL, "(enc-val(ecdh(s%m)(e%m)))",
188                                enc->data[1], enc->data[0]);
189     }
190   else
191     err = gpg_error (GPG_ERR_BUG);
192
193   if (err)
194     goto leave;
195
196   if (sk->pubkey_algo == PUBKEY_ALGO_ECDH)
197     {
198       fingerprint_from_pk (sk, fp, &fpn);
199       log_assert (fpn == 20);
200     }
201
202   /* Decrypt. */
203   desc = gpg_format_keydesc (sk, FORMAT_KEYDESC_NORMAL, 1);
204   err = agent_pkdecrypt (NULL, keygrip,
205                          desc, sk->keyid, sk->main_keyid, sk->pubkey_algo,
206                          s_data, &frame, &nframe, &padding);
207   xfree (desc);
208   gcry_sexp_release (s_data);
209   if (err)
210     goto leave;
211
212   /* Now get the DEK (data encryption key) from the frame
213    *
214    * Old versions encode the DEK in in this format (msb is left):
215    *
216    *     0  1  DEK(16 bytes)  CSUM(2 bytes)  0  RND(n bytes) 2
217    *
218    * Later versions encode the DEK like this:
219    *
220    *     0  2  RND(n bytes)  0  A  DEK(k bytes)  CSUM(2 bytes)
221    *
222    * (mpi_get_buffer already removed the leading zero).
223    *
224    * RND are non-zero randow bytes.
225    * A   is the cipher algorithm
226    * DEK is the encryption key (session key) with length k
227    * CSUM
228    */
229   if (DBG_CRYPTO)
230     log_printhex ("DEK frame:", frame, nframe);
231   n = 0;
232
233   if (sk->pubkey_algo == PUBKEY_ALGO_ECDH)
234     {
235       gcry_mpi_t shared_mpi;
236       gcry_mpi_t decoded;
237
238       /* At the beginning the frame are the bytes of shared point MPI.  */
239       err = gcry_mpi_scan (&shared_mpi, GCRYMPI_FMT_USG, frame, nframe, NULL);
240       if (err)
241         {
242           err = gpg_error (GPG_ERR_WRONG_SECKEY);
243           goto leave;
244         }
245
246       err = pk_ecdh_decrypt (&decoded, fp, enc->data[1]/*encr data as an MPI*/,
247                              shared_mpi, sk->pkey);
248       mpi_release (shared_mpi);
249       if(err)
250         goto leave;
251
252       xfree (frame);
253       err = gcry_mpi_aprint (GCRYMPI_FMT_USG, &frame, &nframe, decoded);
254       mpi_release (decoded);
255       if (err)
256         goto leave;
257
258       /* Now the frame are the bytes decrypted but padded session key.  */
259
260       /* Allow double padding for the benefit of DEK size concealment.
261          Higher than this is wasteful. */
262       if (!nframe || frame[nframe-1] > 8*2 || nframe <= 8
263           || frame[nframe-1] > nframe)
264         {
265           err = gpg_error (GPG_ERR_WRONG_SECKEY);
266           goto leave;
267         }
268       nframe -= frame[nframe-1]; /* Remove padding.  */
269       log_assert (!n); /* (used just below) */
270     }
271   else
272     {
273       if (padding)
274         {
275           if (n + 7 > nframe)
276             {
277               err = gpg_error (GPG_ERR_WRONG_SECKEY);
278               goto leave;
279             }
280           if (frame[n] == 1 && frame[nframe - 1] == 2)
281             {
282               log_info (_("old encoding of the DEK is not supported\n"));
283               err = gpg_error (GPG_ERR_CIPHER_ALGO);
284               goto leave;
285             }
286           if (frame[n] != 2) /* Something went wrong.  */
287             {
288               err = gpg_error (GPG_ERR_WRONG_SECKEY);
289               goto leave;
290             }
291           for (n++; n < nframe && frame[n]; n++) /* Skip the random bytes.  */
292             ;
293           n++; /* Skip the zero byte.  */
294         }
295     }
296
297   if (n + 4 > nframe)
298     {
299       err = gpg_error (GPG_ERR_WRONG_SECKEY);
300       goto leave;
301     }
302
303   dek->keylen = nframe - (n + 1) - 2;
304   dek->algo = frame[n++];
305   err = openpgp_cipher_test_algo (dek->algo);
306   if (err)
307     {
308       if (!opt.quiet && gpg_err_code (err) == GPG_ERR_CIPHER_ALGO)
309         {
310           log_info (_("cipher algorithm %d%s is unknown or disabled\n"),
311                     dek->algo,
312                     dek->algo == CIPHER_ALGO_IDEA ? " (IDEA)" : "");
313         }
314       dek->algo = 0;
315       goto leave;
316     }
317   if (dek->keylen != openpgp_cipher_get_algo_keylen (dek->algo))
318     {
319       err = gpg_error (GPG_ERR_WRONG_SECKEY);
320       goto leave;
321     }
322
323   /* Copy the key to DEK and compare the checksum.  */
324   csum = buf16_to_u16 (frame+nframe-2);
325   memcpy (dek->key, frame + n, dek->keylen);
326   for (csum2 = 0, n = 0; n < dek->keylen; n++)
327     csum2 += dek->key[n];
328   if (csum != csum2)
329     {
330       err = gpg_error (GPG_ERR_WRONG_SECKEY);
331       goto leave;
332     }
333   if (DBG_CLOCK)
334     log_clock ("decryption ready");
335   if (DBG_CRYPTO)
336     log_printhex ("DEK is:", dek->key, dek->keylen);
337
338   /* Check that the algo is in the preferences and whether it has expired.  */
339   {
340     PKT_public_key *pk = NULL;
341     KBNODE pkb = get_pubkeyblock (keyid);
342
343     if (!pkb)
344       {
345         err = -1;
346         log_error ("oops: public key not found for preference check\n");
347       }
348     else if (pkb->pkt->pkt.public_key->selfsigversion > 3
349              && dek->algo != CIPHER_ALGO_3DES
350              && !opt.quiet
351              && !is_algo_in_prefs (pkb, PREFTYPE_SYM, dek->algo))
352       log_info (_("WARNING: cipher algorithm %s not found in recipient"
353                   " preferences\n"), openpgp_cipher_algo_name (dek->algo));
354     if (!err)
355       {
356         KBNODE k;
357
358         for (k = pkb; k; k = k->next)
359           {
360             if (k->pkt->pkttype == PKT_PUBLIC_KEY
361                 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
362               {
363                 u32 aki[2];
364                 keyid_from_pk (k->pkt->pkt.public_key, aki);
365
366                 if (aki[0] == keyid[0] && aki[1] == keyid[1])
367                   {
368                     pk = k->pkt->pkt.public_key;
369                     break;
370                   }
371               }
372           }
373         if (!pk)
374           BUG ();
375         if (pk->expiredate && pk->expiredate <= make_timestamp ())
376           {
377             log_info (_("Note: secret key %s expired at %s\n"),
378                       keystr (keyid), asctimestamp (pk->expiredate));
379           }
380       }
381
382     if (pk && pk->flags.revoked)
383       {
384         log_info (_("Note: key has been revoked"));
385         log_printf ("\n");
386         show_revocation_reason (pk, 1);
387       }
388
389     release_kbnode (pkb);
390     err = 0;
391   }
392
393  leave:
394   xfree (frame);
395   xfree (keygrip);
396   return err;
397 }
398
399
400 /*
401  * Get the session key from the given string.
402  * String is supposed to be formatted as this:
403  *  <algo-id>:<even-number-of-hex-digits>
404  */
405 gpg_error_t
406 get_override_session_key (DEK *dek, const char *string)
407 {
408   const char *s;
409   int i;
410
411   if (!string)
412     return GPG_ERR_BAD_KEY;
413   dek->algo = atoi (string);
414   if (dek->algo < 1)
415     return GPG_ERR_BAD_KEY;
416   if (!(s = strchr (string, ':')))
417     return GPG_ERR_BAD_KEY;
418   s++;
419   for (i = 0; i < DIM (dek->key) && *s; i++, s += 2)
420     {
421       int c = hextobyte (s);
422       if (c == -1)
423         return GPG_ERR_BAD_KEY;
424       dek->key[i] = c;
425     }
426   if (*s)
427     return GPG_ERR_BAD_KEY;
428   dek->keylen = i;
429   return 0;
430 }