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, struct pubkey_enc_list *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
is_algo_in_prefs(kbnode_t keyblock,preftype_t type,int algo)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
get_session_key(ctrl_t ctrl,struct pubkey_enc_list * list,DEK * dek)75 get_session_key (ctrl_t ctrl, struct pubkey_enc_list *list, DEK *dek)
76 {
77   PKT_public_key *sk = NULL;
78   gpg_error_t err;
79   void *enum_context = NULL;
80   u32 keyid[2];
81   int search_for_secret_keys = 1;
82   struct pubkey_enc_list *k;
83 
84   if (DBG_CLOCK)
85     log_clock ("get_session_key enter");
86 
87   while (search_for_secret_keys)
88     {
89       sk = xmalloc_clear (sizeof *sk);
90       err = enum_secret_keys (ctrl, &enum_context, sk);
91       if (err)
92         break;
93 
94       /* Check compliance.  */
95       if (! gnupg_pk_is_allowed (opt.compliance, PK_USE_DECRYPTION,
96                                  sk->pubkey_algo, 0,
97                                  sk->pkey, nbits_from_pk (sk), NULL))
98         {
99           log_info (_("key %s is not suitable for decryption"
100                       " in %s mode\n"),
101                     keystr_from_pk (sk),
102                     gnupg_compliance_option_string (opt.compliance));
103           continue;
104         }
105 
106       /* FIXME: The list needs to be sorted so that we try the keys in
107        * an appropriate order.  For example:
108        * - On-disk keys w/o protection
109        * - On-disk keys with a cached passphrase
110        * - On-card keys of an active card
111        * - On-disk keys with protection
112        * - On-card keys from cards which are not plugged it.  Here a
113        *   cancel-all button should stop asking for other cards.
114        * Without any anonymous keys the sorting can be skipped.
115        */
116       for (k = list; k; k = k->next)
117         {
118           if (!(k->pubkey_algo == PUBKEY_ALGO_ELGAMAL_E
119                 || k->pubkey_algo == PUBKEY_ALGO_ECDH
120                 || k->pubkey_algo == PUBKEY_ALGO_RSA
121                 || k->pubkey_algo == PUBKEY_ALGO_RSA_E
122                 || k->pubkey_algo == PUBKEY_ALGO_ELGAMAL))
123             continue;
124 
125           if (openpgp_pk_test_algo2 (k->pubkey_algo, PUBKEY_USAGE_ENC))
126             continue;
127 
128           if (sk->pubkey_algo != k->pubkey_algo)
129             continue;
130 
131           keyid_from_pk (sk, keyid);
132 
133           if (!k->keyid[0] && !k->keyid[1])
134             {
135               if (opt.skip_hidden_recipients)
136                 continue;
137 
138               if (!opt.quiet)
139                 log_info (_("anonymous recipient; trying secret key %s ...\n"),
140                           keystr (keyid));
141             }
142           else if (opt.try_all_secrets
143                    || (k->keyid[0] == keyid[0] && k->keyid[1] == keyid[1]))
144             {
145               if (!opt.quiet && !(sk->pubkey_usage & PUBKEY_USAGE_ENC))
146                 log_info (_("used key is not marked for encryption use.\n"));
147             }
148           else
149             continue;
150 
151           err = get_it (ctrl, k, dek, sk, keyid);
152           k->result = err;
153           if (!err)
154             {
155               if (!opt.quiet && !k->keyid[0] && !k->keyid[1])
156                 {
157                   log_info (_("okay, we are the anonymous recipient.\n"));
158                   if (!(sk->pubkey_usage & PUBKEY_USAGE_ENC))
159                     log_info (_("used key is not marked for encryption use.\n")
160                               );
161                 }
162               search_for_secret_keys = 0;
163               break;
164             }
165           else if (gpg_err_code (err) == GPG_ERR_FULLY_CANCELED)
166             {
167               search_for_secret_keys = 0;
168               break; /* Don't try any more secret keys.  */
169             }
170         }
171     }
172   enum_secret_keys (ctrl, &enum_context, NULL);  /* free context */
173 
174   if (gpg_err_code (err) == GPG_ERR_EOF)
175     {
176       err = gpg_error (GPG_ERR_NO_SECKEY);
177 
178       /* Return the last specific error, if any.  */
179       for (k = list; k; k = k->next)
180         if (k->result != -1)
181           err = k->result;
182     }
183 
184   if (DBG_CLOCK)
185     log_clock ("get_session_key leave");
186   return err;
187 }
188 
189 
190 static gpg_error_t
get_it(ctrl_t ctrl,struct pubkey_enc_list * enc,DEK * dek,PKT_public_key * sk,u32 * keyid)191 get_it (ctrl_t ctrl,
192         struct pubkey_enc_list *enc, DEK *dek, PKT_public_key *sk, u32 *keyid)
193 {
194   gpg_error_t err;
195   byte *frame = NULL;
196   unsigned int n;
197   size_t nframe;
198   u16 csum, csum2;
199   int padding;
200   gcry_sexp_t s_data;
201   char *desc;
202   char *keygrip;
203   byte fp[MAX_FINGERPRINT_LEN];
204 
205   if (DBG_CLOCK)
206     log_clock ("decryption start");
207 
208   /* Get the keygrip.  */
209   err = hexkeygrip_from_pk (sk, &keygrip);
210   if (err)
211     goto leave;
212 
213   /* Convert the data to an S-expression.  */
214   if (sk->pubkey_algo == PUBKEY_ALGO_ELGAMAL
215       || sk->pubkey_algo == PUBKEY_ALGO_ELGAMAL_E)
216     {
217       if (!enc->data[0] || !enc->data[1])
218         err = gpg_error (GPG_ERR_BAD_MPI);
219       else
220         err = gcry_sexp_build (&s_data, NULL, "(enc-val(elg(a%m)(b%m)))",
221                                enc->data[0], enc->data[1]);
222     }
223   else if (sk->pubkey_algo == PUBKEY_ALGO_RSA
224            || sk->pubkey_algo == PUBKEY_ALGO_RSA_E)
225     {
226       if (!enc->data[0])
227         err = gpg_error (GPG_ERR_BAD_MPI);
228       else
229         err = gcry_sexp_build (&s_data, NULL, "(enc-val(rsa(a%m)))",
230                                enc->data[0]);
231     }
232   else if (sk->pubkey_algo == PUBKEY_ALGO_ECDH)
233     {
234       if (!enc->data[0] || !enc->data[1])
235         err = gpg_error (GPG_ERR_BAD_MPI);
236       else
237         err = gcry_sexp_build (&s_data, NULL, "(enc-val(ecdh(s%m)(e%m)))",
238                                enc->data[1], enc->data[0]);
239     }
240   else
241     err = gpg_error (GPG_ERR_BUG);
242 
243   if (err)
244     goto leave;
245 
246   if (sk->pubkey_algo == PUBKEY_ALGO_ECDH)
247     fingerprint_from_pk (sk, fp, NULL);
248 
249   /* Decrypt. */
250   desc = gpg_format_keydesc (ctrl, sk, FORMAT_KEYDESC_NORMAL, 1);
251   err = agent_pkdecrypt (NULL, keygrip,
252                          desc, sk->keyid, sk->main_keyid, sk->pubkey_algo,
253                          s_data, &frame, &nframe, &padding);
254   xfree (desc);
255   gcry_sexp_release (s_data);
256   if (err)
257     goto leave;
258 
259   /* Now get the DEK (data encryption key) from the frame
260    *
261    * Old versions encode the DEK in this format (msb is left):
262    *
263    *     0  1  DEK(16 bytes)  CSUM(2 bytes)  0  RND(n bytes) 2
264    *
265    * Later versions encode the DEK like this:
266    *
267    *     0  2  RND(n bytes)  0  A  DEK(k bytes)  CSUM(2 bytes)
268    *
269    * (mpi_get_buffer already removed the leading zero).
270    *
271    * RND are non-zero randow bytes.
272    * A   is the cipher algorithm
273    * DEK is the encryption key (session key) with length k
274    * CSUM
275    */
276   if (DBG_CRYPTO)
277     log_printhex (frame, nframe, "DEK frame:");
278   n = 0;
279 
280   if (sk->pubkey_algo == PUBKEY_ALGO_ECDH)
281     {
282       gcry_mpi_t decoded;
283 
284       /* At the beginning the frame are the bytes of shared point MPI.  */
285       err = pk_ecdh_decrypt (&decoded, fp, enc->data[1]/*encr data as an MPI*/,
286                              frame, nframe, sk->pkey);
287       if(err)
288         goto leave;
289 
290       xfree (frame);
291       err = gcry_mpi_aprint (GCRYMPI_FMT_USG, &frame, &nframe, decoded);
292       mpi_release (decoded);
293       if (err)
294         goto leave;
295 
296       /* Now the frame are the bytes decrypted but padded session key.  */
297       if (!nframe || nframe <= 8
298           || frame[nframe-1] > nframe)
299         {
300           err = gpg_error (GPG_ERR_WRONG_SECKEY);
301           goto leave;
302         }
303       nframe -= frame[nframe-1]; /* Remove padding.  */
304       log_assert (!n); /* (used just below) */
305     }
306   else
307     {
308       if (padding)
309         {
310           if (n + 7 > nframe)
311             {
312               err = gpg_error (GPG_ERR_WRONG_SECKEY);
313               goto leave;
314             }
315 
316           /* FIXME: Actually the leading zero is required but due to
317            * the way we encode the output in libgcrypt as an MPI we
318            * are not able to encode that leading zero.  However, when
319            * using a Smartcard we are doing it the right way and
320            * therefore we have to skip the zero.  This should be fixed
321            * in gpg-agent of course. */
322           if (!frame[n])
323             n++;
324 
325           if (frame[n] == 1 && frame[nframe - 1] == 2)
326             {
327               log_info (_("old encoding of the DEK is not supported\n"));
328               err = gpg_error (GPG_ERR_CIPHER_ALGO);
329               goto leave;
330             }
331           if (frame[n] != 2) /* Something went wrong.  */
332             {
333               err = gpg_error (GPG_ERR_WRONG_SECKEY);
334               goto leave;
335             }
336           for (n++; n < nframe && frame[n]; n++) /* Skip the random bytes.  */
337             ;
338           n++; /* Skip the zero byte.  */
339         }
340     }
341 
342   if (n + 4 > nframe)
343     {
344       err = gpg_error (GPG_ERR_WRONG_SECKEY);
345       goto leave;
346     }
347 
348   dek->keylen = nframe - (n + 1) - 2;
349   dek->algo = frame[n++];
350   err = openpgp_cipher_test_algo (dek->algo);
351   if (err)
352     {
353       if (!opt.quiet && gpg_err_code (err) == GPG_ERR_CIPHER_ALGO)
354         {
355           log_info (_("cipher algorithm %d%s is unknown or disabled\n"),
356                     dek->algo,
357                     dek->algo == CIPHER_ALGO_IDEA ? " (IDEA)" : "");
358         }
359       dek->algo = 0;
360       goto leave;
361     }
362   if (dek->keylen != openpgp_cipher_get_algo_keylen (dek->algo))
363     {
364       err = gpg_error (GPG_ERR_WRONG_SECKEY);
365       goto leave;
366     }
367 
368   /* Copy the key to DEK and compare the checksum.  */
369   csum = buf16_to_u16 (frame+nframe-2);
370   memcpy (dek->key, frame + n, dek->keylen);
371   for (csum2 = 0, n = 0; n < dek->keylen; n++)
372     csum2 += dek->key[n];
373   if (csum != csum2)
374     {
375       err = gpg_error (GPG_ERR_WRONG_SECKEY);
376       goto leave;
377     }
378   if (DBG_CLOCK)
379     log_clock ("decryption ready");
380   if (DBG_CRYPTO)
381     log_printhex (dek->key, dek->keylen, "DEK is:");
382 
383   /* Check that the algo is in the preferences and whether it has
384    * expired.  Also print a status line with the key's fingerprint.  */
385   {
386     PKT_public_key *pk = NULL;
387     PKT_public_key *mainpk = NULL;
388     KBNODE pkb = get_pubkeyblock (ctrl, keyid);
389 
390     if (!pkb)
391       {
392         err = -1;
393         log_error ("oops: public key not found for preference check\n");
394       }
395     else if (pkb->pkt->pkt.public_key->selfsigversion > 3
396              && dek->algo != CIPHER_ALGO_3DES
397              && !opt.quiet
398              && !is_algo_in_prefs (pkb, PREFTYPE_SYM, dek->algo))
399       log_info (_("WARNING: cipher algorithm %s not found in recipient"
400                   " preferences\n"), openpgp_cipher_algo_name (dek->algo));
401 
402     if (!err)
403       {
404         kbnode_t k;
405         int first = 1;
406 
407         for (k = pkb; k; k = k->next)
408           {
409             if (k->pkt->pkttype == PKT_PUBLIC_KEY
410                 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY)
411               {
412                 u32 aki[2];
413 
414                 if (first)
415                   {
416                     first = 0;
417                     mainpk = k->pkt->pkt.public_key;
418                   }
419 
420                 keyid_from_pk (k->pkt->pkt.public_key, aki);
421                 if (aki[0] == keyid[0] && aki[1] == keyid[1])
422                   {
423                     pk = k->pkt->pkt.public_key;
424                     break;
425                   }
426               }
427           }
428         if (!pk)
429           BUG ();
430         if (pk->expiredate && pk->expiredate <= make_timestamp ())
431           {
432             log_info (_("Note: secret key %s expired at %s\n"),
433                       keystr (keyid), asctimestamp (pk->expiredate));
434           }
435       }
436 
437     if (pk && pk->flags.revoked)
438       {
439         log_info (_("Note: key has been revoked"));
440         log_printf ("\n");
441         show_revocation_reason (ctrl, pk, 1);
442       }
443 
444     if (is_status_enabled () && pk && mainpk)
445       {
446         char pkhex[MAX_FINGERPRINT_LEN*2+1];
447         char mainpkhex[MAX_FINGERPRINT_LEN*2+1];
448 
449         hexfingerprint (pk, pkhex, sizeof pkhex);
450         hexfingerprint (mainpk, mainpkhex, sizeof mainpkhex);
451 
452         /* Note that we do not want to create a trustdb just for
453          * getting the ownertrust: If there is no trustdb there can't
454          * be ulitmately trusted key anyway and thus the ownertrust
455          * value is irrelevant.  */
456         write_status_printf (STATUS_DECRYPTION_KEY, "%s %s %c",
457                              pkhex, mainpkhex,
458                              get_ownertrust_info (ctrl, mainpk, 1));
459 
460       }
461 
462     release_kbnode (pkb);
463     err = 0;
464   }
465 
466  leave:
467   xfree (frame);
468   xfree (keygrip);
469   return err;
470 }
471 
472 
473 /*
474  * Get the session key from the given string.
475  * String is supposed to be formatted as this:
476  *  <algo-id>:<even-number-of-hex-digits>
477  */
478 gpg_error_t
get_override_session_key(DEK * dek,const char * string)479 get_override_session_key (DEK *dek, const char *string)
480 {
481   const char *s;
482   int i;
483 
484   if (!string)
485     return GPG_ERR_BAD_KEY;
486   dek->algo = atoi (string);
487   if (dek->algo < 1)
488     return GPG_ERR_BAD_KEY;
489   if (!(s = strchr (string, ':')))
490     return GPG_ERR_BAD_KEY;
491   s++;
492   for (i = 0; i < DIM (dek->key) && *s; i++, s += 2)
493     {
494       int c = hextobyte (s);
495       if (c == -1)
496         return GPG_ERR_BAD_KEY;
497       dek->key[i] = c;
498     }
499   if (*s)
500     return GPG_ERR_BAD_KEY;
501   dek->keylen = i;
502   return 0;
503 }
504