Imported Upstream version 2.2.37
[platform/upstream/gpg2.git] / g10 / pkclist.c
1 /* pkclist.c - create a list of public keys
2  * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
3  *               2008, 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 #include <errno.h>
26
27 #include "gpg.h"
28 #include "options.h"
29 #include "packet.h"
30 #include "../common/status.h"
31 #include "keydb.h"
32 #include "../common/util.h"
33 #include "main.h"
34 #include "trustdb.h"
35 #include "../common/ttyio.h"
36 #include "../common/status.h"
37 #include "photoid.h"
38 #include "../common/i18n.h"
39 #include "tofu.h"
40
41 #define CONTROL_D ('D' - 'A' + 1)
42
43 static void
44 send_status_inv_recp (int reason, const char *name)
45 {
46   char buf[40];
47
48   snprintf (buf, sizeof buf, "%d ", reason);
49   write_status_text_and_buffer (STATUS_INV_RECP, buf,
50                                 name, strlen (name),
51                                 -1);
52 }
53
54
55 /****************
56  * Show the revocation reason as it is stored with the given signature
57  */
58 static void
59 do_show_revocation_reason( PKT_signature *sig )
60 {
61     size_t n, nn;
62     const byte *p, *pp;
63     int seq = 0;
64     const char *text;
65
66     while( (p = enum_sig_subpkt (sig->hashed, SIGSUBPKT_REVOC_REASON,
67                                  &n, &seq, NULL )) ) {
68         if( !n )
69             continue; /* invalid - just skip it */
70
71         if( *p == 0 )
72             text = _("No reason specified");
73         else if( *p == 0x01 )
74             text = _("Key is superseded");
75         else if( *p == 0x02 )
76             text = _("Key has been compromised");
77         else if( *p == 0x03 )
78             text = _("Key is no longer used");
79         else if( *p == 0x20 )
80             text = _("User ID is no longer valid");
81         else
82             text = NULL;
83
84         log_info ( _("reason for revocation: "));
85         if (text)
86           log_printf ("%s\n", text);
87         else
88           log_printf ("code=%02x\n", *p );
89         n--; p++;
90         pp = NULL;
91         do {
92             /* We don't want any empty lines, so skip them */
93             while( n && *p == '\n' ) {
94                 p++;
95                 n--;
96             }
97             if( n ) {
98                 pp = memchr( p, '\n', n );
99                 nn = pp? pp - p : n;
100                 log_info ( _("revocation comment: ") );
101                 es_write_sanitized (log_get_stream(), p, nn, NULL, NULL);
102                 log_printf ("\n");
103                 p += nn; n -= nn;
104             }
105         } while( pp );
106     }
107 }
108
109 /* Mode 0: try and find the revocation based on the pk (i.e. check
110    subkeys, etc.)  Mode 1: use only the revocation on the main pk */
111
112 void
113 show_revocation_reason (ctrl_t ctrl, PKT_public_key *pk, int mode)
114 {
115     /* Hmmm, this is not so easy because we have to duplicate the code
116      * used in the trustdb to calculate the keyflags.  We need to find
117      * a clean way to check revocation certificates on keys and
118      * signatures.  And there should be no duplicate code.  Because we
119      * enter this function only when the trustdb told us that we have
120      * a revoked key, we could simply look for a revocation cert and
121      * display this one, when there is only one. Let's try to do this
122      * until we have a better solution.  */
123     KBNODE node, keyblock = NULL;
124     byte fingerprint[MAX_FINGERPRINT_LEN];
125     size_t fingerlen;
126     int rc;
127
128     /* get the keyblock */
129     fingerprint_from_pk( pk, fingerprint, &fingerlen );
130     rc = get_pubkey_byfprint (ctrl, NULL, &keyblock, fingerprint, fingerlen);
131     if( rc ) { /* that should never happen */
132         log_debug( "failed to get the keyblock\n");
133         return;
134     }
135
136     for( node=keyblock; node; node = node->next ) {
137         if( (mode && node->pkt->pkttype == PKT_PUBLIC_KEY) ||
138           ( ( node->pkt->pkttype == PKT_PUBLIC_KEY
139               || node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
140             && !cmp_public_keys( node->pkt->pkt.public_key, pk ) ) )
141             break;
142     }
143     if( !node ) {
144         log_debug("Oops, PK not in keyblock\n");
145         release_kbnode( keyblock );
146         return;
147     }
148     /* now find the revocation certificate */
149     for( node = node->next; node ; node = node->next ) {
150         if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
151             break;
152         if( node->pkt->pkttype == PKT_SIGNATURE
153             && (node->pkt->pkt.signature->sig_class == 0x20
154                 || node->pkt->pkt.signature->sig_class == 0x28 ) ) {
155                 /* FIXME: we should check the signature here */
156                 do_show_revocation_reason ( node->pkt->pkt.signature );
157                 break;
158         }
159     }
160
161     /* We didn't find it, so check if the whole key is revoked */
162     if(!node && !mode)
163       show_revocation_reason (ctrl, pk, 1);
164
165     release_kbnode( keyblock );
166 }
167
168
169 /****************
170  * mode: 0 = standard
171  *       1 = Without key info and additional menu option 'm'
172  *           this does also add an option to set the key to ultimately trusted.
173  * Returns:
174  *      -2 = nothing changed - caller should show some additional info
175  *      -1 = quit operation
176  *       0 = nothing changed
177  *       1 = new ownertrust now in new_trust
178  */
179 #ifndef NO_TRUST_MODELS
180 static int
181 do_edit_ownertrust (ctrl_t ctrl, PKT_public_key *pk, int mode,
182                     unsigned *new_trust, int defer_help )
183 {
184   char *p;
185   u32 keyid[2];
186   int changed=0;
187   int quit=0;
188   int show=0;
189   int min_num;
190   int did_help=defer_help;
191   unsigned int minimum = tdb_get_min_ownertrust (ctrl, pk, 0);
192
193   switch(minimum)
194     {
195     default:
196     case TRUST_UNDEFINED: min_num=1; break;
197     case TRUST_NEVER:     min_num=2; break;
198     case TRUST_MARGINAL:  min_num=3; break;
199     case TRUST_FULLY:     min_num=4; break;
200     }
201
202   keyid_from_pk (pk, keyid);
203   for(;;) {
204     /* A string with valid answers.
205
206        TRANSLATORS: These are the allowed answers in lower and
207        uppercase.  Below you will find the matching strings which
208        should be translated accordingly and the letter changed to
209        match the one in the answer string.
210
211          i = please show me more information
212          m = back to the main menu
213          s = skip this key
214          q = quit
215     */
216     const char *ans = _("iImMqQsS");
217
218     if( !did_help )
219       {
220         if( !mode )
221           {
222             KBNODE keyblock, un;
223
224             tty_printf (_("No trust value assigned to:\n"));
225             print_key_line (ctrl, NULL, pk, 0);
226
227             p = get_user_id_native (ctrl, keyid);
228             tty_printf (_("      \"%s\"\n"),p);
229             xfree (p);
230
231             keyblock = get_pubkeyblock (ctrl, keyid);
232             if (!keyblock)
233                 BUG ();
234             for (un=keyblock; un; un = un->next)
235               {
236                 if (un->pkt->pkttype != PKT_USER_ID )
237                   continue;
238                 if (un->pkt->pkt.user_id->flags.revoked)
239                   continue;
240                 if (un->pkt->pkt.user_id->flags.expired)
241                   continue;
242                 /* Only skip textual primaries */
243                 if (un->pkt->pkt.user_id->flags.primary
244                     && !un->pkt->pkt.user_id->attrib_data )
245                   continue;
246
247                 if((opt.verify_options&VERIFY_SHOW_PHOTOS)
248                    && un->pkt->pkt.user_id->attrib_data)
249                   show_photos (ctrl,
250                                un->pkt->pkt.user_id->attribs,
251                                un->pkt->pkt.user_id->numattribs, pk,
252                                un->pkt->pkt.user_id);
253
254                 p=utf8_to_native(un->pkt->pkt.user_id->name,
255                                  un->pkt->pkt.user_id->len,0);
256
257                 tty_printf(_("  aka \"%s\"\n"),p);
258               }
259
260             print_fingerprint (ctrl, NULL, pk, 2);
261             tty_printf("\n");
262             release_kbnode (keyblock);
263           }
264
265         if(opt.trust_model==TM_DIRECT)
266           {
267             tty_printf(_("How much do you trust that this key actually "
268                          "belongs to the named user?\n"));
269             tty_printf("\n");
270           }
271         else
272           {
273             /* This string also used in keyedit.c:trustsig_prompt */
274             tty_printf(_("Please decide how far you trust this user to"
275                          " correctly verify other users' keys\n"
276                          "(by looking at passports, checking fingerprints from"
277                          " different sources, etc.)\n"));
278             tty_printf("\n");
279           }
280
281         if(min_num<=1)
282           tty_printf (_("  %d = I don't know or won't say\n"), 1);
283         if(min_num<=2)
284           tty_printf (_("  %d = I do NOT trust\n"), 2);
285         if(min_num<=3)
286           tty_printf (_("  %d = I trust marginally\n"), 3);
287         if(min_num<=4)
288           tty_printf (_("  %d = I trust fully\n"), 4);
289         if (mode)
290           tty_printf (_("  %d = I trust ultimately\n"), 5);
291 #if 0
292         /* not yet implemented */
293         tty_printf ("  i = please show me more information\n");
294 #endif
295         if( mode )
296           tty_printf(_("  m = back to the main menu\n"));
297         else
298           {
299             tty_printf(_("  s = skip this key\n"));
300             tty_printf(_("  q = quit\n"));
301           }
302         tty_printf("\n");
303         if(minimum)
304           tty_printf(_("The minimum trust level for this key is: %s\n\n"),
305                      trust_value_to_string(minimum));
306         did_help = 1;
307       }
308     if( strlen(ans) != 8 )
309       BUG();
310     p = cpr_get("edit_ownertrust.value",_("Your decision? "));
311     trim_spaces(p);
312     cpr_kill_prompt();
313     if( !*p )
314       did_help = 0;
315     else if( *p && p[1] )
316       ;
317     else if( !p[1] && ((*p >= '0'+min_num) && *p <= (mode?'5':'4')) )
318       {
319         unsigned int trust;
320         switch( *p )
321           {
322           case '1': trust = TRUST_UNDEFINED; break;
323           case '2': trust = TRUST_NEVER    ; break;
324           case '3': trust = TRUST_MARGINAL ; break;
325           case '4': trust = TRUST_FULLY    ; break;
326           case '5': trust = TRUST_ULTIMATE ; break;
327           default: BUG();
328           }
329         if (trust == TRUST_ULTIMATE
330             && !cpr_get_answer_is_yes ("edit_ownertrust.set_ultimate.okay",
331                                        _("Do you really want to set this key"
332                                          " to ultimate trust? (y/N) ")))
333           ; /* no */
334         else
335           {
336             *new_trust = trust;
337             changed = 1;
338             break;
339           }
340       }
341 #if 0
342     /* not yet implemented */
343     else if( *p == ans[0] || *p == ans[1] )
344       {
345         tty_printf(_("Certificates leading to an ultimately trusted key:\n"));
346         show = 1;
347         break;
348       }
349 #endif
350     else if( mode && (*p == ans[2] || *p == ans[3] || *p == CONTROL_D ) )
351       {
352         break ; /* back to the menu */
353       }
354     else if( !mode && (*p == ans[6] || *p == ans[7] ) )
355       {
356         break; /* skip */
357       }
358     else if( !mode && (*p == ans[4] || *p == ans[5] ) )
359       {
360         quit = 1;
361         break ; /* back to the menu */
362       }
363     xfree(p); p = NULL;
364   }
365   xfree(p);
366   return show? -2: quit? -1 : changed;
367 }
368 #endif /*!NO_TRUST_MODELS*/
369
370
371 /*
372  * Display a menu to change the ownertrust of the key PK (which should
373  * be a primary key).
374  * For mode values see do_edit_ownertrust ()
375  */
376 #ifndef NO_TRUST_MODELS
377 int
378 edit_ownertrust (ctrl_t ctrl, PKT_public_key *pk, int mode )
379 {
380   unsigned int trust = 0;
381   int no_help = 0;
382
383   for(;;)
384     {
385       switch ( do_edit_ownertrust (ctrl, pk, mode, &trust, no_help ) )
386         {
387         case -1: /* quit */
388           return -1;
389         case -2: /* show info */
390           no_help = 1;
391           break;
392         case 1: /* trust value set */
393           trust &= ~TRUST_FLAG_DISABLED;
394           trust |= get_ownertrust (ctrl, pk) & TRUST_FLAG_DISABLED;
395           update_ownertrust (ctrl, pk, trust );
396           return 1;
397         default:
398           return 0;
399         }
400     }
401 }
402 #endif /*!NO_TRUST_MODELS*/
403
404
405 /****************
406  * Check whether we can trust this pk which has a trustlevel of TRUSTLEVEL
407  * Returns: true if we trust.
408  */
409 static int
410 do_we_trust( PKT_public_key *pk, unsigned int trustlevel )
411 {
412   /* We should not be able to get here with a revoked or expired
413      key */
414   if(trustlevel & TRUST_FLAG_REVOKED
415      || trustlevel & TRUST_FLAG_SUB_REVOKED
416      || (trustlevel & TRUST_MASK) == TRUST_EXPIRED)
417     BUG();
418
419   if( opt.trust_model==TM_ALWAYS )
420     {
421       if( opt.verbose )
422         log_info("No trust check due to '--trust-model always' option\n");
423       return 1;
424     }
425
426   switch(trustlevel & TRUST_MASK)
427     {
428     default:
429       log_error ("invalid trustlevel %u returned from validation layer\n",
430                  trustlevel);
431       /* fall through */
432     case TRUST_UNKNOWN:
433     case TRUST_UNDEFINED:
434       log_info(_("%s: There is no assurance this key belongs"
435                  " to the named user\n"),keystr_from_pk(pk));
436       return 0; /* no */
437
438     case TRUST_MARGINAL:
439       log_info(_("%s: There is limited assurance this key belongs"
440                  " to the named user\n"),keystr_from_pk(pk));
441       return 1; /* yes */
442
443     case TRUST_FULLY:
444       if( opt.verbose )
445         log_info(_("This key probably belongs to the named user\n"));
446       return 1; /* yes */
447
448     case TRUST_ULTIMATE:
449       if( opt.verbose )
450         log_info(_("This key belongs to us\n"));
451       return 1; /* yes */
452
453     case TRUST_NEVER:
454       /* This can be returned by TOFU, which can return negative
455          assertions.  */
456       log_info(_("%s: This key is bad!  It has been marked as untrusted!\n"),
457                keystr_from_pk(pk));
458       return 0; /* no */
459     }
460
461   return 1; /*NOTREACHED*/
462 }
463
464
465 /****************
466  * wrapper around do_we_trust, so we can ask whether to use the
467  * key anyway.
468  */
469 static int
470 do_we_trust_pre (ctrl_t ctrl, PKT_public_key *pk, unsigned int trustlevel )
471 {
472   int rc;
473
474   rc = do_we_trust( pk, trustlevel );
475
476   if( !opt.batch && !rc )
477     {
478       print_pubkey_info (ctrl, NULL,pk);
479       print_fingerprint (ctrl, NULL, pk, 2);
480       tty_printf("\n");
481
482       if ((trustlevel & TRUST_MASK) == TRUST_NEVER)
483         tty_printf(
484           _("This key is bad!  It has been marked as untrusted!  If you\n"
485             "*really* know what you are doing, you may answer the next\n"
486             "question with yes.\n"));
487       else
488         tty_printf(
489           _("It is NOT certain that the key belongs to the person named\n"
490             "in the user ID.  If you *really* know what you are doing,\n"
491             "you may answer the next question with yes.\n"));
492
493       tty_printf("\n");
494
495
496       if (is_status_enabled ())
497         {
498           u32 kid[2];
499           char *hint_str;
500
501           keyid_from_pk (pk, kid);
502           hint_str = get_long_user_id_string (ctrl, kid);
503           write_status_text ( STATUS_USERID_HINT, hint_str );
504           xfree (hint_str);
505         }
506
507       if( cpr_get_answer_is_yes("untrusted_key.override",
508                                 _("Use this key anyway? (y/N) "))  )
509         rc = 1;
510
511       /* Hmmm: Should we set a flag to tell the user about
512        *         his decision the next time he encrypts for this recipient?
513        */
514     }
515
516   return rc;
517 }
518
519
520 /* Write a TRUST_foo status line inclduing the validation model.  */
521 static void
522 write_trust_status (int statuscode, int trustlevel)
523 {
524 #ifdef NO_TRUST_MODELS
525   write_status (statuscode);
526 #else /* NO_TRUST_MODELS */
527   int tm;
528
529   /* For the combined tofu+pgp method, we return the trust model which
530    * was responsible for the trustlevel.  */
531   if (opt.trust_model == TM_TOFU_PGP)
532     tm = (trustlevel & TRUST_FLAG_TOFU_BASED)? TM_TOFU : TM_PGP;
533   else
534     tm = opt.trust_model;
535   write_status_strings (statuscode, "0 ", trust_model_string (tm), NULL);
536 #endif /* NO_TRUST_MODELS */
537 }
538
539
540 /****************
541  * Check whether we can trust this signature.
542  * Returns an error code if we should not trust this signature.
543  */
544 int
545 check_signatures_trust (ctrl_t ctrl, PKT_signature *sig)
546 {
547   PKT_public_key *pk = xmalloc_clear( sizeof *pk );
548   unsigned int trustlevel = TRUST_UNKNOWN;
549   int rc=0;
550
551   rc = get_pubkey_for_sig (ctrl, pk, sig, NULL);
552   if (rc)
553     { /* this should not happen */
554       log_error("Ooops; the key vanished  - can't check the trust\n");
555       rc = GPG_ERR_NO_PUBKEY;
556       goto leave;
557     }
558
559   if ( opt.trust_model==TM_ALWAYS )
560     {
561       if( !opt.quiet )
562         log_info(_("WARNING: Using untrusted key!\n"));
563       if (opt.with_fingerprint)
564         print_fingerprint (ctrl, NULL, pk, 1);
565       goto leave;
566     }
567
568   if(pk->flags.maybe_revoked && !pk->flags.revoked)
569     log_info(_("WARNING: this key might be revoked (revocation key"
570                " not present)\n"));
571
572   trustlevel = get_validity (ctrl, NULL, pk, NULL, sig, 1);
573
574   if ( (trustlevel & TRUST_FLAG_REVOKED) )
575     {
576       write_status( STATUS_KEYREVOKED );
577       if(pk->flags.revoked == 2)
578         log_info(_("WARNING: This key has been revoked by its"
579                    " designated revoker!\n"));
580       else
581         log_info(_("WARNING: This key has been revoked by its owner!\n"));
582       log_info(_("         This could mean that the signature is forged.\n"));
583       show_revocation_reason (ctrl, pk, 0);
584     }
585   else if ((trustlevel & TRUST_FLAG_SUB_REVOKED) )
586     {
587       write_status( STATUS_KEYREVOKED );
588       log_info(_("WARNING: This subkey has been revoked by its owner!\n"));
589       show_revocation_reason (ctrl, pk, 0);
590     }
591
592   if ((trustlevel & TRUST_FLAG_DISABLED))
593     log_info (_("Note: This key has been disabled.\n"));
594
595   /* If we have PKA information adjust the trustlevel. */
596   if (sig->pka_info && sig->pka_info->valid)
597     {
598       unsigned char fpr[MAX_FINGERPRINT_LEN];
599       PKT_public_key *primary_pk;
600       size_t fprlen;
601       int okay;
602
603
604       primary_pk = xmalloc_clear (sizeof *primary_pk);
605       get_pubkey (ctrl, primary_pk, pk->main_keyid);
606       fingerprint_from_pk (primary_pk, fpr, &fprlen);
607       free_public_key (primary_pk);
608
609       if ( fprlen == 20 && !memcmp (sig->pka_info->fpr, fpr, 20) )
610         {
611           okay = 1;
612           write_status_text (STATUS_PKA_TRUST_GOOD, sig->pka_info->email);
613           log_info (_("Note: Verified signer's address is '%s'\n"),
614                     sig->pka_info->email);
615         }
616       else
617         {
618           okay = 0;
619           write_status_text (STATUS_PKA_TRUST_BAD, sig->pka_info->email);
620           log_info (_("Note: Signer's address '%s' "
621                       "does not match DNS entry\n"), sig->pka_info->email);
622         }
623
624       switch ( (trustlevel & TRUST_MASK) )
625         {
626         case TRUST_UNKNOWN:
627         case TRUST_UNDEFINED:
628         case TRUST_MARGINAL:
629           if (okay && opt.verify_options&VERIFY_PKA_TRUST_INCREASE)
630             {
631               trustlevel = ((trustlevel & ~TRUST_MASK) | TRUST_FULLY);
632               log_info (_("trustlevel adjusted to FULL"
633                           " due to valid PKA info\n"));
634             }
635           /* fall through */
636         case TRUST_FULLY:
637           if (!okay)
638             {
639               trustlevel = ((trustlevel & ~TRUST_MASK) | TRUST_NEVER);
640               log_info (_("trustlevel adjusted to NEVER"
641                           " due to bad PKA info\n"));
642             }
643           break;
644         }
645     }
646
647   /* Now let the user know what up with the trustlevel. */
648   switch ( (trustlevel & TRUST_MASK) )
649     {
650     case TRUST_EXPIRED:
651       log_info(_("Note: This key has expired!\n"));
652       print_fingerprint (ctrl, NULL, pk, 1);
653       break;
654
655     default:
656       log_error ("invalid trustlevel %u returned from validation layer\n",
657                  trustlevel);
658       /* fall through */
659     case TRUST_UNKNOWN:
660     case TRUST_UNDEFINED:
661       write_trust_status (STATUS_TRUST_UNDEFINED, trustlevel);
662       log_info(_("WARNING: This key is not certified with"
663                  " a trusted signature!\n"));
664       log_info(_("         There is no indication that the "
665                  "signature belongs to the owner.\n" ));
666       print_fingerprint (ctrl, NULL, pk, 1);
667       break;
668
669     case TRUST_NEVER:
670       /* This level can be returned by TOFU, which supports negative
671        * assertions.  */
672       write_trust_status (STATUS_TRUST_NEVER, trustlevel);
673       log_info(_("WARNING: We do NOT trust this key!\n"));
674       log_info(_("         The signature is probably a FORGERY.\n"));
675       if (opt.with_fingerprint)
676         print_fingerprint (ctrl, NULL, pk, 1);
677       rc = gpg_error (GPG_ERR_BAD_SIGNATURE);
678       break;
679
680     case TRUST_MARGINAL:
681       write_trust_status (STATUS_TRUST_MARGINAL, trustlevel);
682       log_info(_("WARNING: This key is not certified with"
683                  " sufficiently trusted signatures!\n"));
684       log_info(_("         It is not certain that the"
685                  " signature belongs to the owner.\n" ));
686       print_fingerprint (ctrl, NULL, pk, 1);
687       break;
688
689     case TRUST_FULLY:
690       write_trust_status (STATUS_TRUST_FULLY, trustlevel);
691       if (opt.with_fingerprint)
692         print_fingerprint (ctrl, NULL, pk, 1);
693       break;
694
695     case TRUST_ULTIMATE:
696       write_trust_status (STATUS_TRUST_ULTIMATE, trustlevel);
697       if (opt.with_fingerprint)
698         print_fingerprint (ctrl, NULL, pk, 1);
699       break;
700     }
701
702  leave:
703   free_public_key( pk );
704   return rc;
705 }
706
707
708 void
709 release_pk_list (pk_list_t pk_list)
710 {
711   PK_LIST pk_rover;
712
713   for ( ; pk_list; pk_list = pk_rover)
714     {
715       pk_rover = pk_list->next;
716       free_public_key ( pk_list->pk );
717       xfree ( pk_list );
718     }
719 }
720
721
722 static int
723 key_present_in_pk_list(PK_LIST pk_list, PKT_public_key *pk)
724 {
725     for( ; pk_list; pk_list = pk_list->next)
726         if (cmp_public_keys(pk_list->pk, pk) == 0)
727             return 0;
728
729     return -1;
730 }
731
732
733 /*
734  * Return a malloced string with a default recipient if there is any
735  * Fixme: We don't distinguish between malloc failure and no-default-recipient.
736  */
737 static char *
738 default_recipient (ctrl_t ctrl)
739 {
740   PKT_public_key *pk;
741   char *result;
742
743   if (opt.def_recipient)
744     return xtrystrdup (opt.def_recipient);
745
746   if (!opt.def_recipient_self)
747     return NULL;
748   pk = xtrycalloc (1, sizeof *pk );
749   if (!pk)
750     return NULL;
751   if (get_seckey_default (ctrl, pk))
752     {
753       free_public_key (pk);
754       return NULL;
755     }
756   result = hexfingerprint (pk, NULL, 0);
757   free_public_key (pk);
758   return result;
759 }
760
761
762 static int
763 expand_id(const char *id,strlist_t *into,unsigned int flags)
764 {
765   struct groupitem *groups;
766   int count=0;
767
768   for(groups=opt.grouplist;groups;groups=groups->next)
769     {
770       /* need strcasecmp() here, as this should be localized */
771       if(strcasecmp(groups->name,id)==0)
772         {
773           strlist_t each,sl;
774
775           /* this maintains the current utf8-ness */
776           for(each=groups->values;each;each=each->next)
777             {
778               sl=add_to_strlist(into,each->d);
779               sl->flags=flags;
780               count++;
781             }
782
783           break;
784         }
785     }
786
787   return count;
788 }
789
790 /* For simplicity, and to avoid potential loops, we only expand once -
791  * you can't make an alias that points to an alias.  */
792 static strlist_t
793 expand_group (strlist_t input)
794 {
795   strlist_t output = NULL;
796   strlist_t sl, rover;
797
798   for (rover = input; rover; rover = rover->next)
799     if (!(rover->flags & PK_LIST_FROM_FILE)
800         && !expand_id(rover->d,&output,rover->flags))
801       {
802         /* Didn't find any groups, so use the existing string */
803         sl=add_to_strlist(&output,rover->d);
804         sl->flags=rover->flags;
805       }
806
807   return output;
808 }
809
810
811 /* Helper for build_pk_list to find and check one key.  This helper is
812  * also used directly in server mode by the RECIPIENTS command.  On
813  * success the new key is added to PK_LIST_ADDR.  NAME is the user id
814  * of the key.  USE the requested usage and a set MARK_HIDDEN will
815  * mark the key in the updated list as a hidden recipient.  If
816  * FROM_FILE is true, NAME is not a user ID but the name of a file
817  * holding a key. */
818 gpg_error_t
819 find_and_check_key (ctrl_t ctrl, const char *name, unsigned int use,
820                     int mark_hidden, int from_file, pk_list_t *pk_list_addr)
821 {
822   int rc;
823   PKT_public_key *pk;
824   KBNODE keyblock = NULL;
825
826   if (!name || !*name)
827     return gpg_error (GPG_ERR_INV_USER_ID);
828
829   pk = xtrycalloc (1, sizeof *pk);
830   if (!pk)
831     return gpg_error_from_syserror ();
832   pk->req_usage = use;
833
834   if (from_file)
835     rc = get_pubkey_fromfile (ctrl, pk, name);
836   else
837     rc = get_best_pubkey_byname (ctrl, GET_PUBKEY_NORMAL,
838                                  NULL, pk, name, &keyblock, 0);
839   if (rc)
840     {
841       int code;
842
843       /* Key not found or other error. */
844       log_error (_("%s: skipped: %s\n"), name, gpg_strerror (rc) );
845       switch (gpg_err_code (rc))
846         {
847         case GPG_ERR_NO_SECKEY:
848         case GPG_ERR_NO_PUBKEY:   code =  1; break;
849         case GPG_ERR_INV_USER_ID: code = 14; break;
850         default: code = 0; break;
851         }
852       send_status_inv_recp (code, name);
853       free_public_key (pk);
854       return rc;
855     }
856
857   rc = openpgp_pk_test_algo2 (pk->pubkey_algo, use);
858   if (rc)
859     {
860       /* Key found but not usable for us (e.g. sign-only key). */
861       release_kbnode (keyblock);
862       send_status_inv_recp (3, name); /* Wrong key usage */
863       log_error (_("%s: skipped: %s\n"), name, gpg_strerror (rc) );
864       free_public_key (pk);
865       return rc;
866     }
867
868   /* Key found and usable.  Check validity. */
869   if (!from_file)
870     {
871       int trustlevel;
872
873       trustlevel = get_validity (ctrl, keyblock, pk, pk->user_id, NULL, 1);
874       release_kbnode (keyblock);
875       if ( (trustlevel & TRUST_FLAG_DISABLED) )
876         {
877           /* Key has been disabled. */
878           send_status_inv_recp (13, name);
879           log_info (_("%s: skipped: public key is disabled\n"), name);
880           free_public_key (pk);
881           return GPG_ERR_UNUSABLE_PUBKEY;
882         }
883
884       if ( !do_we_trust_pre (ctrl, pk, trustlevel) )
885         {
886           /* We don't trust this key.  */
887           send_status_inv_recp (10, name);
888           free_public_key (pk);
889           return GPG_ERR_UNUSABLE_PUBKEY;
890         }
891     }
892
893   /* Skip the actual key if the key is already present in the
894      list.  */
895   if (!key_present_in_pk_list (*pk_list_addr, pk))
896     {
897       if (!opt.quiet)
898         log_info (_("%s: skipped: public key already present\n"), name);
899       free_public_key (pk);
900     }
901   else
902     {
903       pk_list_t r;
904
905       r = xtrymalloc (sizeof *r);
906       if (!r)
907         {
908           rc = gpg_error_from_syserror ();
909           free_public_key (pk);
910           return rc;
911         }
912       r->pk = pk;
913       r->next = *pk_list_addr;
914       r->flags = mark_hidden? 1:0;
915       *pk_list_addr = r;
916     }
917
918   return 0;
919 }
920
921
922
923 /* This is the central function to collect the keys for recipients.
924  * It is thus used to prepare a public key encryption. encrypt-to
925  * keys, default keys and the keys for the actual recipients are all
926  * collected here.  When not in batch mode and no recipient has been
927  * passed on the commandline, the function will also ask for
928  * recipients.
929  *
930  * RCPTS is a string list with the recipients; NULL is an allowed
931  * value but not very useful.  Group expansion is done on these names;
932  * they may be in any of the user Id formats we can handle.  The flags
933  * bits for each string in the string list are used for:
934  *
935  * - PK_LIST_ENCRYPT_TO :: This is an encrypt-to recipient.
936  * - PK_LIST_HIDDEN     :: This is a hidden recipient.
937  * - PK_LIST_FROM_FILE  :: The argument is a file with a key.
938  *
939  * On success a list of keys is stored at the address RET_PK_LIST; the
940  * caller must free this list.  On error the value at this address is
941  * not changed.
942  */
943 int
944 build_pk_list (ctrl_t ctrl, strlist_t rcpts, PK_LIST *ret_pk_list)
945 {
946   PK_LIST pk_list = NULL;
947   PKT_public_key *pk=NULL;
948   int rc=0;
949   int any_recipients=0;
950   strlist_t rov,remusr;
951   char *def_rec = NULL;
952   char pkstrbuf[PUBKEY_STRING_SIZE];
953
954   /* Try to expand groups if any have been defined. */
955   if (opt.grouplist)
956     remusr = expand_group (rcpts);
957   else
958     remusr = rcpts;
959
960   /* XXX: Change this function to use get_pubkeys instead of
961      get_pubkey_byname to detect ambiguous key specifications and warn
962      about duplicate keyblocks.  For ambiguous key specifications on
963      the command line or provided interactively, prompt the user to
964      select the best key.  If a key specification is ambiguous and we
965      are in batch mode, die.  */
966
967   if (opt.encrypt_to_default_key)
968     {
969       static int warned;
970
971       const char *default_key = parse_def_secret_key (ctrl);
972       if (default_key)
973         {
974           PK_LIST r = xmalloc_clear (sizeof *r);
975
976           r->pk = xmalloc_clear (sizeof *r->pk);
977           r->pk->req_usage = PUBKEY_USAGE_ENC;
978
979           rc = get_pubkey_byname (ctrl, GET_PUBKEY_NO_AKL,
980                                   NULL, r->pk, default_key, NULL, NULL, 0);
981           if (rc)
982             {
983               xfree (r->pk);
984               xfree (r);
985
986               log_error (_("can't encrypt to '%s'\n"), default_key);
987               if (!opt.quiet)
988                 log_info (_("(check argument of option '%s')\n"),
989                           "--default-key");
990             }
991           else
992             {
993               r->next = pk_list;
994               r->flags = 0;
995               pk_list = r;
996             }
997         }
998       else if (opt.def_secret_key)
999         {
1000           if (! warned)
1001             log_info (_("option '%s' given, but no valid default keys given\n"),
1002                       "--encrypt-to-default-key");
1003           warned = 1;
1004         }
1005       else
1006         {
1007           if (! warned)
1008             log_info (_("option '%s' given, but option '%s' not given\n"),
1009                       "--encrypt-to-default-key", "--default-key");
1010           warned = 1;
1011         }
1012     }
1013
1014   /* Check whether there are any recipients in the list and build the
1015    * list of the encrypt-to ones (we always trust them). */
1016   for ( rov = remusr; rov; rov = rov->next )
1017     {
1018       if ( !(rov->flags & PK_LIST_ENCRYPT_TO) )
1019         {
1020           /* This is a regular recipient; i.e. not an encrypt-to
1021              one. */
1022           any_recipients = 1;
1023
1024           /* Hidden recipients are not allowed while in PGP mode,
1025              issue a warning and switch into GnuPG mode. */
1026           if ((rov->flags & PK_LIST_HIDDEN) && (PGP6 || PGP7 || PGP8))
1027             {
1028               log_info(_("option '%s' may not be used in %s mode\n"),
1029                        "--hidden-recipient",
1030                        gnupg_compliance_option_string (opt.compliance));
1031
1032               compliance_failure();
1033             }
1034         }
1035       else if (!opt.no_encrypt_to)
1036         {
1037           /* --encrypt-to has not been disabled.  Check this
1038              encrypt-to key. */
1039           pk = xmalloc_clear( sizeof *pk );
1040           pk->req_usage = PUBKEY_USAGE_ENC;
1041
1042           /* We explicitly allow encrypt-to to an disabled key; thus
1043              we pass 1 for the second last argument and 1 as the last
1044              argument to disable AKL. */
1045           if ((rc = get_pubkey_byname (ctrl, GET_PUBKEY_NO_AKL,
1046                                        NULL, pk, rov->d, NULL, NULL, 1)))
1047             {
1048               free_public_key ( pk ); pk = NULL;
1049               log_error (_("%s: skipped: %s\n"), rov->d, gpg_strerror (rc) );
1050               send_status_inv_recp (0, rov->d);
1051               goto fail;
1052             }
1053           else if ( !(rc=openpgp_pk_test_algo2 (pk->pubkey_algo,
1054                                                 PUBKEY_USAGE_ENC)) )
1055             {
1056               /* Skip the actual key if the key is already present
1057                * in the list.  Add it to our list if not. */
1058               if (key_present_in_pk_list(pk_list, pk) == 0)
1059                 {
1060                   free_public_key (pk); pk = NULL;
1061                   if (!opt.quiet)
1062                     log_info (_("%s: skipped: public key already present\n"),
1063                               rov->d);
1064                 }
1065               else
1066                 {
1067                   PK_LIST r;
1068                   r = xmalloc( sizeof *r );
1069                   r->pk = pk; pk = NULL;
1070                   r->next = pk_list;
1071                   r->flags = (rov->flags&PK_LIST_HIDDEN)?1:0;
1072                   pk_list = r;
1073
1074                   /* Hidden encrypt-to recipients are not allowed while
1075                      in PGP mode, issue a warning and switch into
1076                      GnuPG mode. */
1077                   if ((r->flags&PK_LIST_ENCRYPT_TO) && (PGP6 || PGP7 || PGP8))
1078                     {
1079                       log_info(_("option '%s' may not be used in %s mode\n"),
1080                                "--hidden-encrypt-to",
1081                                gnupg_compliance_option_string (opt.compliance));
1082
1083                       compliance_failure();
1084                     }
1085                 }
1086             }
1087           else
1088             {
1089               /* The public key is not usable for encryption. */
1090               free_public_key( pk ); pk = NULL;
1091               log_error(_("%s: skipped: %s\n"), rov->d, gpg_strerror (rc) );
1092               send_status_inv_recp (3, rov->d); /* Wrong key usage */
1093               goto fail;
1094             }
1095         }
1096     }
1097
1098   /* If we don't have any recipients yet and we are not in batch mode
1099      drop into interactive selection mode. */
1100   if ( !any_recipients && !opt.batch )
1101     {
1102       int have_def_rec;
1103       char *answer = NULL;
1104       strlist_t backlog = NULL;
1105
1106       if (pk_list)
1107         any_recipients = 1;
1108       def_rec = default_recipient(ctrl);
1109       have_def_rec = !!def_rec;
1110       if ( !have_def_rec )
1111         tty_printf(_("You did not specify a user ID. (you may use \"-r\")\n"));
1112
1113       for (;;)
1114         {
1115           rc = 0;
1116           xfree(answer);
1117           if ( have_def_rec )
1118             {
1119               /* A default recipient is taken as the first entry. */
1120               answer = def_rec;
1121               def_rec = NULL;
1122             }
1123           else if (backlog)
1124             {
1125               /* This is part of our trick to expand and display groups. */
1126               answer = strlist_pop (&backlog);
1127             }
1128           else
1129             {
1130               /* Show the list of already collected recipients and ask
1131                  for more. */
1132               PK_LIST iter;
1133
1134               tty_printf("\n");
1135               tty_printf(_("Current recipients:\n"));
1136               for (iter=pk_list;iter;iter=iter->next)
1137                 {
1138                   u32 keyid[2];
1139
1140                   keyid_from_pk(iter->pk,keyid);
1141                   tty_printf ("%s/%s %s \"",
1142                               pubkey_string (iter->pk,
1143                                              pkstrbuf, sizeof pkstrbuf),
1144                               keystr(keyid),
1145                               datestr_from_pk (iter->pk));
1146
1147                   if (iter->pk->user_id)
1148                     tty_print_utf8_string(iter->pk->user_id->name,
1149                                           iter->pk->user_id->len);
1150                   else
1151                     {
1152                       size_t n;
1153                       char *p = get_user_id (ctrl, keyid, &n, NULL);
1154                       tty_print_utf8_string ( p, n );
1155                       xfree(p);
1156                     }
1157                   tty_printf("\"\n");
1158                 }
1159
1160               answer = cpr_get_utf8("pklist.user_id.enter",
1161                                     _("\nEnter the user ID.  "
1162                                       "End with an empty line: "));
1163               trim_spaces(answer);
1164               cpr_kill_prompt();
1165             }
1166
1167           if ( !answer || !*answer )
1168             {
1169               xfree(answer);
1170               break;  /* No more recipients entered - get out of loop. */
1171             }
1172
1173           /* Do group expand here too.  The trick here is to continue
1174              the loop if any expansion occurred.  The code above will
1175              then list all expanded keys. */
1176           if (expand_id(answer,&backlog,0))
1177             continue;
1178
1179           /* Get and check key for the current name. */
1180           free_public_key (pk);
1181           pk = xmalloc_clear( sizeof *pk );
1182           pk->req_usage = PUBKEY_USAGE_ENC;
1183           rc = get_pubkey_byname (ctrl, GET_PUBKEY_NORMAL,
1184                                   NULL, pk, answer, NULL, NULL, 0);
1185           if (rc)
1186             tty_printf(_("No such user ID.\n"));
1187           else if ( !(rc=openpgp_pk_test_algo2 (pk->pubkey_algo,
1188                                                 PUBKEY_USAGE_ENC)) )
1189             {
1190               if ( have_def_rec )
1191                 {
1192                   /* No validation for a default recipient. */
1193                   if (!key_present_in_pk_list(pk_list, pk))
1194                     {
1195                       free_public_key (pk);
1196                       pk = NULL;
1197                       log_info (_("skipped: public key "
1198                                   "already set as default recipient\n") );
1199                     }
1200                   else
1201                     {
1202                       PK_LIST r = xmalloc (sizeof *r);
1203                       r->pk = pk; pk = NULL;
1204                       r->next = pk_list;
1205                       r->flags = 0; /* No throwing default ids. */
1206                       pk_list = r;
1207                     }
1208                   any_recipients = 1;
1209                   continue;
1210                 }
1211               else
1212                 { /* Check validity of this key. */
1213                   int trustlevel;
1214
1215                   trustlevel =
1216                     get_validity (ctrl, NULL, pk, pk->user_id, NULL, 1);
1217                   if ( (trustlevel & TRUST_FLAG_DISABLED) )
1218                     {
1219                       tty_printf (_("Public key is disabled.\n") );
1220                     }
1221                   else if ( do_we_trust_pre (ctrl, pk, trustlevel) )
1222                     {
1223                       /* Skip the actual key if the key is already
1224                        * present in the list */
1225                       if (!key_present_in_pk_list(pk_list, pk))
1226                         {
1227                           free_public_key (pk);
1228                           pk = NULL;
1229                           log_info(_("skipped: public key already set\n") );
1230                         }
1231                       else
1232                         {
1233                           PK_LIST r;
1234                           r = xmalloc( sizeof *r );
1235                           r->pk = pk; pk = NULL;
1236                           r->next = pk_list;
1237                           r->flags = 0; /* No throwing interactive ids. */
1238                           pk_list = r;
1239                         }
1240                       any_recipients = 1;
1241                       continue;
1242                     }
1243                 }
1244             }
1245           xfree(def_rec); def_rec = NULL;
1246           have_def_rec = 0;
1247         }
1248       if ( pk )
1249         {
1250           free_public_key( pk );
1251           pk = NULL;
1252         }
1253     }
1254   else if ( !any_recipients && (def_rec = default_recipient(ctrl)) )
1255     {
1256       /* We are in batch mode and have only a default recipient. */
1257       pk = xmalloc_clear( sizeof *pk );
1258       pk->req_usage = PUBKEY_USAGE_ENC;
1259
1260       /* The default recipient is allowed to be disabled; thus pass 1
1261          as second last argument.  We also don't want an AKL. */
1262       rc = get_pubkey_byname (ctrl, GET_PUBKEY_NO_AKL,
1263                               NULL, pk, def_rec, NULL, NULL, 1);
1264       if (rc)
1265         log_error(_("unknown default recipient \"%s\"\n"), def_rec );
1266       else if ( !(rc=openpgp_pk_test_algo2(pk->pubkey_algo,
1267                                            PUBKEY_USAGE_ENC)) )
1268         {
1269           /* Mark any_recipients here since the default recipient
1270              would have been used if it wasn't already there.  It
1271              doesn't really matter if we got this key from the default
1272              recipient or an encrypt-to. */
1273           any_recipients = 1;
1274           if (!key_present_in_pk_list(pk_list, pk))
1275             log_info (_("skipped: public key already set "
1276                         "as default recipient\n"));
1277           else
1278             {
1279               PK_LIST r = xmalloc( sizeof *r );
1280               r->pk = pk; pk = NULL;
1281               r->next = pk_list;
1282               r->flags = 0; /* No throwing default ids. */
1283               pk_list = r;
1284             }
1285         }
1286       if ( pk )
1287         {
1288           free_public_key( pk );
1289           pk = NULL;
1290         }
1291       xfree(def_rec); def_rec = NULL;
1292     }
1293   else
1294     {
1295       /* General case: Check all keys. */
1296       any_recipients = 0;
1297       for (; remusr; remusr = remusr->next )
1298         {
1299           if ( (remusr->flags & PK_LIST_ENCRYPT_TO) )
1300             continue; /* encrypt-to keys are already handled. */
1301
1302           rc = find_and_check_key (ctrl, remusr->d, PUBKEY_USAGE_ENC,
1303                                    !!(remusr->flags&PK_LIST_HIDDEN),
1304                                    !!(remusr->flags&PK_LIST_FROM_FILE),
1305                                    &pk_list);
1306           if (rc)
1307             goto fail;
1308           any_recipients = 1;
1309         }
1310     }
1311
1312   if ( !rc && !any_recipients )
1313     {
1314       log_error(_("no valid addressees\n"));
1315       write_status_text (STATUS_NO_RECP, "0");
1316       rc = GPG_ERR_NO_USER_ID;
1317     }
1318
1319 #ifdef USE_TOFU
1320   if (! rc && (opt.trust_model == TM_TOFU_PGP || opt.trust_model == TM_TOFU))
1321     {
1322       PK_LIST iter;
1323       for (iter = pk_list; iter; iter = iter->next)
1324         {
1325           int rc2;
1326
1327           /* Note: we already resolved any conflict when looking up
1328              the key.  Don't annoy the user again if she selected
1329              accept once.  */
1330           rc2 = tofu_register_encryption (ctrl, iter->pk, NULL, 0);
1331           if (rc2)
1332             log_info ("WARNING: Failed to register encryption to %s"
1333                       " with TOFU engine\n",
1334                       keystr (pk_main_keyid (iter->pk)));
1335           else if (DBG_TRUST)
1336             log_debug ("Registered encryption to %s with TOFU DB.\n",
1337                       keystr (pk_main_keyid (iter->pk)));
1338         }
1339     }
1340 #endif /*USE_TOFU*/
1341
1342  fail:
1343
1344   if ( rc )
1345     release_pk_list( pk_list );
1346   else
1347     *ret_pk_list = pk_list;
1348   if (opt.grouplist)
1349     free_strlist(remusr);
1350   return rc;
1351 }
1352
1353
1354 /* In pgp6 mode, disallow all ciphers except IDEA (1), 3DES (2), and
1355    CAST5 (3), all hashes except MD5 (1), SHA1 (2), and RIPEMD160 (3),
1356    and all compressions except none (0) and ZIP (1).  pgp7 and pgp8
1357    mode expands the cipher list to include AES128 (7), AES192 (8),
1358    AES256 (9), and TWOFISH (10).  pgp8 adds the SHA-256 hash (8).  For
1359    a true PGP key all of this is unneeded as they are the only items
1360    present in the preferences subpacket, but checking here covers the
1361    weird case of encrypting to a key that had preferences from a
1362    different implementation which was then used with PGP.  I am not
1363    completely comfortable with this as the right thing to do, as it
1364    slightly alters the list of what the user is supposedly requesting.
1365    It is not against the RFC however, as the preference chosen will
1366    never be one that the user didn't specify somewhere ("The
1367    implementation may use any mechanism to pick an algorithm in the
1368    intersection"), and PGP has no mechanism to fix such a broken
1369    preference list, so I'm including it. -dms */
1370
1371 int
1372 algo_available( preftype_t preftype, int algo, const struct pref_hint *hint)
1373 {
1374   if( preftype == PREFTYPE_SYM )
1375     {
1376       if(PGP6 && (algo != CIPHER_ALGO_IDEA
1377                   && algo != CIPHER_ALGO_3DES
1378                   && algo != CIPHER_ALGO_CAST5))
1379         return 0;
1380
1381       if(PGP7 && (algo != CIPHER_ALGO_IDEA
1382                   && algo != CIPHER_ALGO_3DES
1383                   && algo != CIPHER_ALGO_CAST5
1384                   && algo != CIPHER_ALGO_AES
1385                   && algo != CIPHER_ALGO_AES192
1386                   && algo != CIPHER_ALGO_AES256
1387                   && algo != CIPHER_ALGO_TWOFISH))
1388         return 0;
1389
1390       /* PGP8 supports all the ciphers we do.. */
1391
1392       return algo && !openpgp_cipher_test_algo ( algo );
1393     }
1394   else if( preftype == PREFTYPE_HASH )
1395     {
1396       if (hint && hint->digest_length)
1397         {
1398           unsigned int n = gcry_md_get_algo_dlen (algo);
1399
1400           if (hint->exact)
1401             {
1402               /* For example ECDSA requires an exact hash value so
1403                * that we do not truncate.  For DSA we allow truncation
1404                * and thus exact is not set.  */
1405               if (hint->digest_length != n)
1406                 return 0;
1407             }
1408           else if (hint->digest_length!=20 || opt.flags.dsa2)
1409             {
1410               /* If --enable-dsa2 is set or the hash isn't 160 bits
1411                  (which implies DSA2), then we'll accept a hash that
1412                  is larger than we need.  Otherwise we won't accept
1413                  any hash that isn't exactly the right size. */
1414               if (hint->digest_length > n)
1415                 return 0;
1416             }
1417           else if (hint->digest_length != n)
1418             return 0;
1419         }
1420
1421       if((PGP6 || PGP7) && (algo != DIGEST_ALGO_MD5
1422                             && algo != DIGEST_ALGO_SHA1
1423                             && algo != DIGEST_ALGO_RMD160))
1424         return 0;
1425
1426
1427       if(PGP8 && (algo != DIGEST_ALGO_MD5
1428                   && algo != DIGEST_ALGO_SHA1
1429                   && algo != DIGEST_ALGO_RMD160
1430                   && algo != DIGEST_ALGO_SHA256))
1431         return 0;
1432
1433       return algo && !openpgp_md_test_algo (algo);
1434     }
1435   else if( preftype == PREFTYPE_ZIP )
1436     {
1437       if((PGP6 || PGP7) && (algo != COMPRESS_ALGO_NONE
1438                             && algo != COMPRESS_ALGO_ZIP))
1439         return 0;
1440
1441       /* PGP8 supports all the compression algos we do */
1442
1443       return !check_compress_algo( algo );
1444     }
1445   else
1446     return 0;
1447 }
1448
1449 /****************
1450  * Return -1 if we could not find an algorithm.
1451  */
1452 int
1453 select_algo_from_prefs(PK_LIST pk_list, int preftype,
1454                        int request, const struct pref_hint *hint)
1455 {
1456   PK_LIST pkr;
1457   u32 bits[8];
1458   const prefitem_t *prefs;
1459   int result=-1,i;
1460   u16 scores[256];
1461
1462   if( !pk_list )
1463     return -1;
1464
1465   memset(bits,0xFF,sizeof(bits));
1466   memset(scores,0,sizeof(scores));
1467
1468   for( pkr = pk_list; pkr; pkr = pkr->next )
1469     {
1470       u32 mask[8];
1471       int rank=1,implicit=-1;
1472
1473       memset(mask,0,sizeof(mask));
1474
1475       switch(preftype)
1476         {
1477         case PREFTYPE_SYM:
1478           /* IDEA is implicitly there for v3 keys with v3 selfsigs if
1479              --pgp2 mode is on.  This was a 2440 thing that was
1480              dropped from 4880 but is still relevant to GPG's 1991
1481              support.  All this doesn't mean IDEA is actually
1482              available, of course. */
1483           implicit=CIPHER_ALGO_3DES;
1484
1485           break;
1486
1487         case PREFTYPE_HASH:
1488           /* While I am including this code for completeness, note
1489              that currently --pgp2 mode locks the hash at MD5, so this
1490              code will never even be called.  Even if the hash wasn't
1491              locked at MD5, we don't support sign+encrypt in --pgp2
1492              mode, and that's the only time PREFTYPE_HASH is used
1493              anyway. -dms
1494
1495              Because "de-vs" compliance does not allow SHA-1 it does
1496              not make sense to assign SHA-1 as implicit algorithm.
1497              Instead it is better to use SHA-256 as implicit algorithm
1498              (which will be the case for rfc4880bis anyway).  */
1499
1500           if (opt.compliance == CO_DE_VS)
1501             implicit = DIGEST_ALGO_SHA256;
1502           else
1503             implicit = DIGEST_ALGO_SHA1;
1504
1505           break;
1506
1507         case PREFTYPE_ZIP:
1508           /* Uncompressed is always an option. */
1509           implicit=COMPRESS_ALGO_NONE;
1510         }
1511
1512       if (pkr->pk->user_id) /* selected by user ID */
1513         prefs = pkr->pk->user_id->prefs;
1514       else
1515         prefs = pkr->pk->prefs;
1516
1517       if( prefs )
1518         {
1519           for (i=0; prefs[i].type; i++ )
1520             {
1521               if( prefs[i].type == preftype )
1522                 {
1523                   /* Make sure all scores don't add up past 0xFFFF
1524                      (and roll around) */
1525                   if(rank+scores[prefs[i].value]<=0xFFFF)
1526                     scores[prefs[i].value]+=rank;
1527                   else
1528                     scores[prefs[i].value]=0xFFFF;
1529
1530                   mask[prefs[i].value/32] |= 1<<(prefs[i].value%32);
1531
1532                   rank++;
1533
1534                   /* We saw the implicit algorithm, so we don't need
1535                      tack it on the end ourselves. */
1536                   if(implicit==prefs[i].value)
1537                     implicit=-1;
1538                 }
1539             }
1540         }
1541
1542       if(rank==1 && preftype==PREFTYPE_ZIP)
1543         {
1544           /* If the compression preferences are not present, they are
1545              assumed to be ZIP, Uncompressed (RFC4880:13.3.1) */
1546           scores[1]=1; /* ZIP is first choice */
1547           scores[0]=2; /* Uncompressed is second choice */
1548           mask[0]|=3;
1549         }
1550
1551       /* If the key didn't have the implicit algorithm listed
1552          explicitly, add it here at the tail of the list. */
1553       if(implicit>-1)
1554         {
1555           scores[implicit]+=rank;
1556           mask[implicit/32] |= 1<<(implicit%32);
1557         }
1558
1559       for(i=0;i<8;i++)
1560         bits[i]&=mask[i];
1561     }
1562
1563   /* We've now scored all of the algorithms, and the usable ones have
1564      bits set.  Let's pick the winner. */
1565
1566   /* The caller passed us a request.  Can we use it? */
1567   if(request>-1 && (bits[request/32] & (1<<(request%32))) &&
1568      algo_available(preftype,request,hint))
1569     result=request;
1570
1571   if(result==-1)
1572     {
1573       /* If we have personal prefs set, use them. */
1574       prefs=NULL;
1575       if(preftype==PREFTYPE_SYM && opt.personal_cipher_prefs)
1576         prefs=opt.personal_cipher_prefs;
1577       else if(preftype==PREFTYPE_HASH && opt.personal_digest_prefs)
1578         prefs=opt.personal_digest_prefs;
1579       else if(preftype==PREFTYPE_ZIP && opt.personal_compress_prefs)
1580         prefs=opt.personal_compress_prefs;
1581
1582       if( prefs )
1583         for(i=0; prefs[i].type; i++ )
1584           {
1585             if(bits[prefs[i].value/32] & (1<<(prefs[i].value%32))
1586                && algo_available( preftype, prefs[i].value, hint))
1587               {
1588                 result = prefs[i].value;
1589                 break;
1590               }
1591           }
1592     }
1593
1594   if(result==-1)
1595     {
1596       unsigned int best=-1;
1597
1598       /* At this point, we have not selected an algorithm due to a
1599          special request or via personal prefs.  Pick the highest
1600          ranked algorithm (i.e. the one with the lowest score). */
1601
1602       if(preftype==PREFTYPE_HASH && scores[DIGEST_ALGO_MD5])
1603         {
1604           /* "If you are building an authentication system, the recipient
1605              may specify a preferred signing algorithm. However, the
1606              signer would be foolish to use a weak algorithm simply
1607              because the recipient requests it." (RFC4880:14).  If any
1608              other hash algorithm is available, pretend that MD5 isn't.
1609              Note that if the user intentionally chose MD5 by putting it
1610              in their personal prefs, then we do what the user said (as we
1611              never reach this code). */
1612
1613           for(i=DIGEST_ALGO_MD5+1;i<256;i++)
1614             if(scores[i])
1615               {
1616                 scores[DIGEST_ALGO_MD5]=0;
1617                 break;
1618               }
1619         }
1620
1621       for(i=0;i<256;i++)
1622         {
1623           /* Note the '<' here.  This means in case of a tie, we will
1624              favor the lower algorithm number.  We have a choice
1625              between the lower number (probably an older algorithm
1626              with more time in use), or the higher number (probably a
1627              newer algorithm with less time in use).  Older is
1628              probably safer here, even though the newer algorithms
1629              tend to be "stronger". */
1630           if(scores[i] && scores[i]<best
1631              && (bits[i/32] & (1<<(i%32)))
1632              && algo_available(preftype,i,hint))
1633             {
1634               best=scores[i];
1635               result=i;
1636             }
1637         }
1638     }
1639
1640   return result;
1641 }
1642
1643 /*
1644  * Select the MDC flag from the pk_list.  We can only use MDC if all
1645  * recipients support this feature.
1646  */
1647 int
1648 select_mdc_from_pklist (PK_LIST pk_list)
1649 {
1650   PK_LIST pkr;
1651
1652   if ( !pk_list )
1653     return 0;
1654
1655   for (pkr = pk_list; pkr; pkr = pkr->next)
1656     {
1657       int mdc;
1658
1659       if (pkr->pk->user_id) /* selected by user ID */
1660         mdc = pkr->pk->user_id->flags.mdc;
1661       else
1662         mdc = pkr->pk->flags.mdc;
1663       if (!mdc)
1664         return 0;  /* At least one recipient does not support it. */
1665     }
1666   return 1; /* Can be used. */
1667 }
1668
1669
1670 /* Print a warning for all keys in PK_LIST missing the MDC feature. */
1671 void
1672 warn_missing_mdc_from_pklist (PK_LIST pk_list)
1673 {
1674   PK_LIST pkr;
1675
1676   for (pkr = pk_list; pkr; pkr = pkr->next)
1677     {
1678       int mdc;
1679
1680       if (pkr->pk->user_id) /* selected by user ID */
1681         mdc = pkr->pk->user_id->flags.mdc;
1682       else
1683         mdc = pkr->pk->flags.mdc;
1684       if (!mdc)
1685         log_info (_("Note: key %s has no %s feature\n"),
1686                   keystr_from_pk (pkr->pk), "MDC");
1687     }
1688 }
1689
1690 void
1691 warn_missing_aes_from_pklist (PK_LIST pk_list)
1692 {
1693   PK_LIST pkr;
1694
1695   for (pkr = pk_list; pkr; pkr = pkr->next)
1696     {
1697       const prefitem_t *prefs;
1698       int i;
1699       int gotit = 0;
1700
1701       prefs = pkr->pk->user_id? pkr->pk->user_id->prefs : pkr->pk->prefs;
1702       if (prefs)
1703         {
1704           for (i=0; !gotit && prefs[i].type; i++ )
1705             if (prefs[i].type == PREFTYPE_SYM
1706                 && prefs[i].value == CIPHER_ALGO_AES)
1707               gotit++;
1708         }
1709       if (!gotit)
1710         log_info (_("Note: key %s has no preference for %s\n"),
1711                   keystr_from_pk (pkr->pk), "AES");
1712     }
1713 }