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