Fixed EOF detection for encrypted packets.
[gnupg.git] / g10 / pkclist.c
blob16835926e8b4f42ce3bf6aa6cae814d7a37b3610
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 Free Software Foundation, Inc.
5 * This file is part of GnuPG.
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.
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.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <assert.h>
28 #include "gpg.h"
29 #include "options.h"
30 #include "packet.h"
31 #include "status.h"
32 #include "keydb.h"
33 #include "util.h"
34 #include "main.h"
35 #include "trustdb.h"
36 #include "ttyio.h"
37 #include "status.h"
38 #include "photoid.h"
39 #include "i18n.h"
41 #define CONTROL_D ('D' - 'A' + 1)
43 static void
44 send_status_inv_recp (int reason, const char *name)
46 char buf[40];
48 snprintf (buf, sizeof buf, "%d ", reason);
49 write_status_text_and_buffer (STATUS_INV_RECP, buf,
50 name, strlen (name),
51 -1);
55 /****************
56 * Show the revocation reason as it is stored with the given signature
58 static void
59 do_show_revocation_reason( PKT_signature *sig )
61 size_t n, nn;
62 const byte *p, *pp;
63 int seq = 0;
64 const char *text;
66 while( (p = enum_sig_subpkt (sig->hashed, SIGSUBPKT_REVOC_REASON,
67 &n, &seq, NULL )) ) {
68 if( !n )
69 continue; /* invalid - just skip it */
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;
84 log_info( _("reason for revocation: ") );
85 if( text )
86 fputs( text, log_get_stream() );
87 else
88 fprintf( log_get_stream(), "code=%02x", *p );
89 log_printf ("\n");
90 n--; p++;
91 pp = NULL;
92 do {
93 /* We don't want any empty lines, so skip them */
94 while( n && *p == '\n' ) {
95 p++;
96 n--;
98 if( n ) {
99 pp = memchr( p, '\n', n );
100 nn = pp? pp - p : n;
101 log_info ( _("revocation comment: ") );
102 print_string ( log_get_stream(), p, nn, 0 );
103 log_printf ("\n");
104 p += nn; n -= nn;
106 } while( pp );
110 /* Mode 0: try and find the revocation based on the pk (i.e. check
111 subkeys, etc.) Mode 1: use only the revocation on the main pk */
113 void
114 show_revocation_reason( PKT_public_key *pk, int mode )
116 /* Hmmm, this is not so easy becuase we have to duplicate the code
117 * used in the trustbd to calculate the keyflags. We need to find
118 * a clean way to check revocation certificates on keys and
119 * signatures. And there should be no duplicate code. Because we
120 * enter this function only when the trustdb told us that we have
121 * a revoked key, we could simply look for a revocation cert and
122 * display this one, when there is only one. Let's try to do this
123 * until we have a better solution. */
124 KBNODE node, keyblock = NULL;
125 byte fingerprint[MAX_FINGERPRINT_LEN];
126 size_t fingerlen;
127 int rc;
129 /* get the keyblock */
130 fingerprint_from_pk( pk, fingerprint, &fingerlen );
131 rc = get_keyblock_byfprint( &keyblock, fingerprint, fingerlen );
132 if( rc ) { /* that should never happen */
133 log_debug( "failed to get the keyblock\n");
134 return;
137 for( node=keyblock; node; node = node->next ) {
138 if( (mode && node->pkt->pkttype == PKT_PUBLIC_KEY) ||
139 ( ( node->pkt->pkttype == PKT_PUBLIC_KEY
140 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
141 && !cmp_public_keys( node->pkt->pkt.public_key, pk ) ) )
142 break;
144 if( !node ) {
145 log_debug("Oops, PK not in keyblock\n");
146 release_kbnode( keyblock );
147 return;
149 /* now find the revocation certificate */
150 for( node = node->next; node ; node = node->next ) {
151 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
152 break;
153 if( node->pkt->pkttype == PKT_SIGNATURE
154 && (node->pkt->pkt.signature->sig_class == 0x20
155 || node->pkt->pkt.signature->sig_class == 0x28 ) ) {
156 /* FIXME: we should check the signature here */
157 do_show_revocation_reason ( node->pkt->pkt.signature );
158 break;
162 /* We didn't find it, so check if the whole key is revoked */
163 if(!node && !mode)
164 show_revocation_reason(pk,1);
166 release_kbnode( keyblock );
170 /****************
171 * mode: 0 = standard
172 * 1 = Without key info and additional menu option 'm'
173 * this does also add an option to set the key to ultimately trusted.
174 * Returns:
175 * -2 = nothing changed - caller should show some additional info
176 * -1 = quit operation
177 * 0 = nothing changed
178 * 1 = new ownertrust now in new_trust
180 static int
181 do_edit_ownertrust (PKT_public_key *pk, int mode,
182 unsigned *new_trust, int defer_help )
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=get_min_ownertrust(pk);
193 switch(minimum)
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;
202 keyid_from_pk (pk, keyid);
203 for(;;) {
204 /* A string with valid answers.
206 Note to 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.
211 i = please show me more information
212 m = back to the main menu
213 s = skip this key
214 q = quit
216 const char *ans = _("iImMqQsS");
218 if( !did_help )
220 if( !mode )
222 KBNODE keyblock, un;
224 tty_printf(_("No trust value assigned to:\n"));
225 tty_printf("%4u%c/%s %s\n",nbits_from_pk( pk ),
226 pubkey_letter( pk->pubkey_algo ),
227 keystr(keyid), datestr_from_pk( pk ) );
228 p=get_user_id_native(keyid);
229 tty_printf(_(" \"%s\"\n"),p);
230 xfree(p);
232 keyblock = get_pubkeyblock (keyid);
233 if (!keyblock)
234 BUG ();
235 for (un=keyblock; un; un = un->next)
237 if (un->pkt->pkttype != PKT_USER_ID )
238 continue;
239 if (un->pkt->pkt.user_id->is_revoked )
240 continue;
241 if (un->pkt->pkt.user_id->is_expired )
242 continue;
243 /* Only skip textual primaries */
244 if (un->pkt->pkt.user_id->is_primary
245 && !un->pkt->pkt.user_id->attrib_data )
246 continue;
248 if((opt.verify_options&VERIFY_SHOW_PHOTOS)
249 && un->pkt->pkt.user_id->attrib_data)
250 show_photos(un->pkt->pkt.user_id->attribs,
251 un->pkt->pkt.user_id->numattribs,pk,NULL,
252 un->pkt->pkt.user_id);
254 p=utf8_to_native(un->pkt->pkt.user_id->name,
255 un->pkt->pkt.user_id->len,0);
257 tty_printf(_(" aka \"%s\"\n"),p);
260 print_fingerprint (pk, NULL, 2);
261 tty_printf("\n");
262 release_kbnode (keyblock);
265 if(opt.trust_model==TM_DIRECT)
267 tty_printf(_("How much do you trust that this key actually "
268 "belongs to the named user?\n"));
269 tty_printf("\n");
271 else
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");
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
299 tty_printf(_(" s = skip this key\n"));
300 tty_printf(_(" q = quit\n"));
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;
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] )
317 else if( !p[1] && ((*p >= '0'+min_num) && *p <= (mode?'5':'4')) )
319 unsigned int trust;
320 switch( *p )
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();
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
336 *new_trust = trust;
337 changed = 1;
338 break;
341 #if 0
342 /* not yet implemented */
343 else if( *p == ans[0] || *p == ans[1] )
345 tty_printf(_("Certificates leading to an ultimately trusted key:\n"));
346 show = 1;
347 break;
349 #endif
350 else if( mode && (*p == ans[2] || *p == ans[3] || *p == CONTROL_D ) )
352 break ; /* back to the menu */
354 else if( !mode && (*p == ans[6] || *p == ans[7] ) )
356 break; /* skip */
358 else if( !mode && (*p == ans[4] || *p == ans[5] ) )
360 quit = 1;
361 break ; /* back to the menu */
363 xfree(p); p = NULL;
365 xfree(p);
366 return show? -2: quit? -1 : changed;
370 * Display a menu to change the ownertrust of the key PK (which should
371 * be a primary key).
372 * For mode values see do_edit_ownertrust ()
375 edit_ownertrust (PKT_public_key *pk, int mode )
377 unsigned int trust = 0;
378 int no_help = 0;
380 for(;;)
382 switch ( do_edit_ownertrust (pk, mode, &trust, no_help ) )
384 case -1: /* quit */
385 return -1;
386 case -2: /* show info */
387 no_help = 1;
388 break;
389 case 1: /* trust value set */
390 trust &= ~TRUST_FLAG_DISABLED;
391 trust |= get_ownertrust (pk) & TRUST_FLAG_DISABLED;
392 update_ownertrust (pk, trust );
393 return 1;
394 default:
395 return 0;
401 /****************
402 * Check whether we can trust this pk which has a trustlevel of TRUSTLEVEL
403 * Returns: true if we trust.
405 static int
406 do_we_trust( PKT_public_key *pk, unsigned int trustlevel )
408 /* We should not be able to get here with a revoked or expired
409 key */
410 if(trustlevel & TRUST_FLAG_REVOKED
411 || trustlevel & TRUST_FLAG_SUB_REVOKED
412 || (trustlevel & TRUST_MASK) == TRUST_EXPIRED)
413 BUG();
415 if( opt.trust_model==TM_ALWAYS )
417 if( opt.verbose )
418 log_info("No trust check due to `--trust-model always' option\n");
419 return 1;
422 switch(trustlevel & TRUST_MASK)
424 default:
425 log_error ("invalid trustlevel %u returned from validation layer\n",
426 trustlevel);
427 /* fall thru */
428 case TRUST_UNKNOWN:
429 case TRUST_UNDEFINED:
430 log_info(_("%s: There is no assurance this key belongs"
431 " to the named user\n"),keystr_from_pk(pk));
432 return 0; /* no */
434 case TRUST_MARGINAL:
435 log_info(_("%s: There is limited assurance this key belongs"
436 " to the named user\n"),keystr_from_pk(pk));
437 return 1; /* yes */
439 case TRUST_FULLY:
440 if( opt.verbose )
441 log_info(_("This key probably belongs to the named user\n"));
442 return 1; /* yes */
444 case TRUST_ULTIMATE:
445 if( opt.verbose )
446 log_info(_("This key belongs to us\n"));
447 return 1; /* yes */
450 return 1; /*NOTREACHED*/
454 /****************
455 * wrapper around do_we_trust, so we can ask whether to use the
456 * key anyway.
458 static int
459 do_we_trust_pre( PKT_public_key *pk, unsigned int trustlevel )
461 int rc;
463 rc = do_we_trust( pk, trustlevel );
465 if( !opt.batch && !rc )
467 print_pubkey_info(NULL,pk);
468 print_fingerprint (pk, NULL, 2);
469 tty_printf("\n");
471 tty_printf(
472 _("It is NOT certain that the key belongs to the person named\n"
473 "in the user ID. If you *really* know what you are doing,\n"
474 "you may answer the next question with yes.\n"));
476 tty_printf("\n");
479 if (is_status_enabled ())
481 u32 kid[2];
482 char *hint_str;
484 keyid_from_pk (pk, kid);
485 hint_str = get_long_user_id_string ( kid );
486 write_status_text ( STATUS_USERID_HINT, hint_str );
487 xfree (hint_str);
490 if( cpr_get_answer_is_yes("untrusted_key.override",
491 _("Use this key anyway? (y/N) ")) )
492 rc = 1;
494 /* Hmmm: Should we set a flag to tell the user about
495 * his decision the next time he encrypts for this recipient?
499 return rc;
503 /****************
504 * Check whether we can trust this signature.
505 * Returns: Error if we shall not trust this signatures.
508 check_signatures_trust( PKT_signature *sig )
510 PKT_public_key *pk = xmalloc_clear( sizeof *pk );
511 unsigned int trustlevel;
512 int rc=0;
514 rc = get_pubkey( pk, sig->keyid );
515 if (rc)
516 { /* this should not happen */
517 log_error("Ooops; the key vanished - can't check the trust\n");
518 rc = G10ERR_NO_PUBKEY;
519 goto leave;
522 if ( opt.trust_model==TM_ALWAYS )
524 if( !opt.quiet )
525 log_info(_("WARNING: Using untrusted key!\n"));
526 if (opt.with_fingerprint)
527 print_fingerprint (pk, NULL, 1);
528 goto leave;
531 if(pk->maybe_revoked && !pk->is_revoked)
532 log_info(_("WARNING: this key might be revoked (revocation key"
533 " not present)\n"));
535 trustlevel = get_validity (pk, NULL);
537 if ( (trustlevel & TRUST_FLAG_REVOKED) )
539 write_status( STATUS_KEYREVOKED );
540 if(pk->is_revoked==2)
541 log_info(_("WARNING: This key has been revoked by its"
542 " designated revoker!\n"));
543 else
544 log_info(_("WARNING: This key has been revoked by its owner!\n"));
545 log_info(_(" This could mean that the signature is forged.\n"));
546 show_revocation_reason( pk, 0 );
548 else if ((trustlevel & TRUST_FLAG_SUB_REVOKED) )
550 write_status( STATUS_KEYREVOKED );
551 log_info(_("WARNING: This subkey has been revoked by its owner!\n"));
552 show_revocation_reason( pk, 0 );
555 if ((trustlevel & TRUST_FLAG_DISABLED))
556 log_info (_("Note: This key has been disabled.\n"));
558 /* If we have PKA information adjust the trustlevel. */
559 if (sig->pka_info && sig->pka_info->valid)
561 unsigned char fpr[MAX_FINGERPRINT_LEN];
562 PKT_public_key *primary_pk;
563 size_t fprlen;
564 int okay;
567 primary_pk = xmalloc_clear (sizeof *primary_pk);
568 get_pubkey (primary_pk, pk->main_keyid);
569 fingerprint_from_pk (primary_pk, fpr, &fprlen);
570 free_public_key (primary_pk);
572 if ( fprlen == 20 && !memcmp (sig->pka_info->fpr, fpr, 20) )
574 okay = 1;
575 write_status_text (STATUS_PKA_TRUST_GOOD, sig->pka_info->email);
576 log_info (_("Note: Verified signer's address is `%s'\n"),
577 sig->pka_info->email);
579 else
581 okay = 0;
582 write_status_text (STATUS_PKA_TRUST_BAD, sig->pka_info->email);
583 log_info (_("Note: Signer's address `%s' "
584 "does not match DNS entry\n"), sig->pka_info->email);
587 switch ( (trustlevel & TRUST_MASK) )
589 case TRUST_UNKNOWN:
590 case TRUST_UNDEFINED:
591 case TRUST_MARGINAL:
592 if (okay && opt.verify_options&VERIFY_PKA_TRUST_INCREASE)
594 trustlevel = ((trustlevel & ~TRUST_MASK) | TRUST_FULLY);
595 log_info (_("trustlevel adjusted to FULL"
596 " due to valid PKA info\n"));
598 /* (fall through) */
599 case TRUST_FULLY:
600 if (!okay)
602 trustlevel = ((trustlevel & ~TRUST_MASK) | TRUST_NEVER);
603 log_info (_("trustlevel adjusted to NEVER"
604 " due to bad PKA info\n"));
606 break;
610 /* Now let the user know what up with the trustlevel. */
611 switch ( (trustlevel & TRUST_MASK) )
613 case TRUST_EXPIRED:
614 log_info(_("Note: This key has expired!\n"));
615 print_fingerprint (pk, NULL, 1);
616 break;
618 default:
619 log_error ("invalid trustlevel %u returned from validation layer\n",
620 trustlevel);
621 /* fall thru */
622 case TRUST_UNKNOWN:
623 case TRUST_UNDEFINED:
624 write_status( STATUS_TRUST_UNDEFINED );
625 log_info(_("WARNING: This key is not certified with"
626 " a trusted signature!\n"));
627 log_info(_(" There is no indication that the "
628 "signature belongs to the owner.\n" ));
629 print_fingerprint (pk, NULL, 1);
630 break;
632 case TRUST_NEVER:
633 /* currently we won't get that status */
634 write_status( STATUS_TRUST_NEVER );
635 log_info(_("WARNING: We do NOT trust this key!\n"));
636 log_info(_(" The signature is probably a FORGERY.\n"));
637 if (opt.with_fingerprint)
638 print_fingerprint (pk, NULL, 1);
639 rc = gpg_error (GPG_ERR_BAD_SIGNATURE);
640 break;
642 case TRUST_MARGINAL:
643 write_status( STATUS_TRUST_MARGINAL );
644 log_info(_("WARNING: This key is not certified with"
645 " sufficiently trusted signatures!\n"));
646 log_info(_(" It is not certain that the"
647 " signature belongs to the owner.\n" ));
648 print_fingerprint (pk, NULL, 1);
649 break;
651 case TRUST_FULLY:
652 write_status( STATUS_TRUST_FULLY );
653 if (opt.with_fingerprint)
654 print_fingerprint (pk, NULL, 1);
655 break;
657 case TRUST_ULTIMATE:
658 write_status( STATUS_TRUST_ULTIMATE );
659 if (opt.with_fingerprint)
660 print_fingerprint (pk, NULL, 1);
661 break;
664 leave:
665 free_public_key( pk );
666 return rc;
670 void
671 release_pk_list (pk_list_t pk_list)
673 PK_LIST pk_rover;
675 for ( ; pk_list; pk_list = pk_rover)
677 pk_rover = pk_list->next;
678 free_public_key ( pk_list->pk );
679 xfree ( pk_list );
684 static int
685 key_present_in_pk_list(PK_LIST pk_list, PKT_public_key *pk)
687 for( ; pk_list; pk_list = pk_list->next)
688 if (cmp_public_keys(pk_list->pk, pk) == 0)
689 return 0;
691 return -1;
695 /****************
696 * Return a malloced string with a default recipient if there is any
698 static char *
699 default_recipient(void)
701 PKT_secret_key *sk;
702 byte fpr[MAX_FINGERPRINT_LEN+1];
703 size_t n;
704 char *p;
705 int i;
707 if( opt.def_recipient )
708 return xstrdup( opt.def_recipient );
709 if( !opt.def_recipient_self )
710 return NULL;
711 sk = xmalloc_clear( sizeof *sk );
712 i = get_seckey_byname( sk, NULL, 0 );
713 if( i ) {
714 free_secret_key( sk );
715 return NULL;
717 n = MAX_FINGERPRINT_LEN;
718 fingerprint_from_sk( sk, fpr, &n );
719 free_secret_key( sk );
720 p = xmalloc( 2*n+3 );
721 *p++ = '0';
722 *p++ = 'x';
723 for(i=0; i < n; i++ )
724 sprintf( p+2*i, "%02X", fpr[i] );
725 p -= 2;
726 return p;
729 static int
730 expand_id(const char *id,strlist_t *into,unsigned int flags)
732 struct groupitem *groups;
733 int count=0;
735 for(groups=opt.grouplist;groups;groups=groups->next)
737 /* need strcasecmp() here, as this should be localized */
738 if(strcasecmp(groups->name,id)==0)
740 strlist_t each,sl;
742 /* this maintains the current utf8-ness */
743 for(each=groups->values;each;each=each->next)
745 sl=add_to_strlist(into,each->d);
746 sl->flags=flags;
747 count++;
750 break;
754 return count;
757 /* For simplicity, and to avoid potential loops, we only expand once -
758 you can't make an alias that points to an alias. */
759 static strlist_t
760 expand_group(strlist_t input)
762 strlist_t sl,output=NULL,rover;
764 for(rover=input;rover;rover=rover->next)
765 if(expand_id(rover->d,&output,rover->flags)==0)
767 /* Didn't find any groups, so use the existing string */
768 sl=add_to_strlist(&output,rover->d);
769 sl->flags=rover->flags;
772 return output;
776 /* Helper for build_pk_list to find and check one key. This helper is
777 also used directly in server mode by the RECIPIENTS command. On
778 success the new key is added to PK_LIST_ADDR. NAME is the user id
779 of the key. USE the requested usage and a set MARK_HIDDEN will mark
780 the key in the updated list as a hidden recipient. */
781 gpg_error_t
782 find_and_check_key (const char *name, unsigned int use,
783 int mark_hidden, pk_list_t *pk_list_addr)
785 int rc;
786 PKT_public_key *pk;
787 int trustlevel;
789 if (!name || !*name)
790 return gpg_error (GPG_ERR_INV_NAME);
792 pk = xtrycalloc (1, sizeof *pk);
793 if (!pk)
794 return gpg_error_from_syserror ();
795 pk->req_usage = use;
797 rc = get_pubkey_byname (NULL, pk, name, NULL, NULL, 0, 0);
798 if (rc)
800 /* Key not found or other error. */
801 log_error (_("%s: skipped: %s\n"), name, g10_errstr(rc) );
802 send_status_inv_recp (0, name);
803 free_public_key (pk);
804 return rc;
807 rc = openpgp_pk_test_algo2 (pk->pubkey_algo, use);
808 if (rc)
810 /* Key found but not usable for us (e.g. sign-only key). */
811 send_status_inv_recp (0, name);
812 log_error (_("%s: skipped: %s\n"), name, g10_errstr(rc) );
813 free_public_key (pk);
814 return rc;
817 /* Key found and usable. Check validity. */
818 trustlevel = get_validity (pk, pk->user_id);
819 if ( (trustlevel & TRUST_FLAG_DISABLED) )
821 /* Key has been disabled. */
822 send_status_inv_recp (0, name);
823 log_info (_("%s: skipped: public key is disabled\n"), name);
824 free_public_key (pk);
825 return G10ERR_UNU_PUBKEY;
828 if ( !do_we_trust_pre (pk, trustlevel) )
830 /* We don't trust this key. */
831 send_status_inv_recp (10, name);
832 free_public_key (pk);
833 return G10ERR_UNU_PUBKEY;
835 /* Note: do_we_trust may have changed the trustlevel. */
837 /* Skip the actual key if the key is already present in the
838 list. */
839 if (!key_present_in_pk_list (*pk_list_addr, pk))
841 log_info (_("%s: skipped: public key already present\n"), name);
842 free_public_key (pk);
844 else
846 pk_list_t r;
848 r = xtrymalloc (sizeof *r);
849 if (!r)
851 rc = gpg_error_from_syserror ();
852 free_public_key (pk);
853 return rc;
855 r->pk = pk;
856 r->next = *pk_list_addr;
857 r->flags = mark_hidden? 1:0;
858 *pk_list_addr = r;
861 return 0;
866 /* This is the central function to collect the keys for recipients.
867 It is thus used to prepare a public key encryption. encrypt-to
868 keys, default keys and the keys for the actual recipients are all
869 collected here. When not in batch mode and no recipient has been
870 passed on the commandline, the function will also ask for
871 recipients.
873 RCPTS is a string list with the recipients; NULL is an allowed
874 value but not very useful. Group expansion is done on these names;
875 they may be in any of the user Id formats we can handle. The flags
876 bits for each string in the string list are used for:
877 Bit 0: This is an encrypt-to recipient.
878 Bit 1: This is a hidden recipient.
880 USE is the desired use for the key - usually PUBKEY_USAGE_ENC.
882 On success a list of keys is stored at the address RET_PK_LIST; the
883 caller must free this list. On error the value at this address is
884 not changed.
887 build_pk_list( strlist_t rcpts, PK_LIST *ret_pk_list, unsigned int use )
889 PK_LIST pk_list = NULL;
890 PKT_public_key *pk=NULL;
891 int rc=0;
892 int any_recipients=0;
893 strlist_t rov,remusr;
894 char *def_rec = NULL;
896 /* Try to expand groups if any have been defined. */
897 if (opt.grouplist)
898 remusr = expand_group (rcpts);
899 else
900 remusr = rcpts;
902 /* Check whether there are any recipients in the list and build the
903 * list of the encrypt-to ones (we always trust them). */
904 for ( rov = remusr; rov; rov = rov->next )
906 if ( !(rov->flags & 1) )
908 /* This is a regular recipient; i.e. not an encrypt-to
909 one. */
910 any_recipients = 1;
912 /* Hidden recipients are not allowed while in PGP mode,
913 issue a warning and switch into GnuPG mode. */
914 if ((rov->flags&2) && (PGP2 || PGP6 || PGP7 || PGP8))
916 log_info(_("you may not use %s while in %s mode\n"),
917 "--hidden-recipient",
918 compliance_option_string());
920 compliance_failure();
923 else if ( (use & PUBKEY_USAGE_ENC) && !opt.no_encrypt_to )
925 /* Encryption has been requested and --encrypt-to has not
926 been disabled. Check this encrypt-to key. */
927 pk = xmalloc_clear( sizeof *pk );
928 pk->req_usage = use;
930 /* We explicitly allow encrypt-to to an disabled key; thus
931 we pass 1for the second last argument and 1 as the last
932 argument to disable AKL. */
933 if ( (rc = get_pubkey_byname (NULL, pk, rov->d, NULL, NULL, 1, 1)) )
935 free_public_key ( pk ); pk = NULL;
936 log_error (_("%s: skipped: %s\n"), rov->d, g10_errstr(rc) );
937 send_status_inv_recp (0, rov->d);
938 goto fail;
940 else if ( !(rc=openpgp_pk_test_algo2 (pk->pubkey_algo, use)) )
942 /* Skip the actual key if the key is already present
943 * in the list. Add it to our list if not. */
944 if (key_present_in_pk_list(pk_list, pk) == 0)
946 free_public_key (pk); pk = NULL;
947 log_info (_("%s: skipped: public key already present\n"),
948 rov->d);
950 else
952 PK_LIST r;
953 r = xmalloc( sizeof *r );
954 r->pk = pk; pk = NULL;
955 r->next = pk_list;
956 r->flags = (rov->flags&2)?1:0;
957 pk_list = r;
959 /* Hidden encrypt-to recipients are not allowed while
960 in PGP mode, issue a warning and switch into
961 GnuPG mode. */
962 if ((r->flags&1) && (PGP2 || PGP6 || PGP7 || PGP8))
964 log_info(_("you may not use %s while in %s mode\n"),
965 "--hidden-encrypt-to",
966 compliance_option_string());
968 compliance_failure();
972 else
974 /* The public key is not usable for encryption or not
975 available. */
976 free_public_key( pk ); pk = NULL;
977 log_error(_("%s: skipped: %s\n"), rov->d, g10_errstr(rc) );
978 send_status_inv_recp (0, rov->d);
979 goto fail;
984 /* If we don't have any recipients yet and we are not in batch mode
985 drop into interactive selection mode. */
986 if ( !any_recipients && !opt.batch )
988 int have_def_rec;
989 char *answer = NULL;
990 strlist_t backlog = NULL;
992 if (pk_list)
993 any_recipients = 1;
994 def_rec = default_recipient();
995 have_def_rec = !!def_rec;
996 if ( !have_def_rec )
997 tty_printf(_("You did not specify a user ID. (you may use \"-r\")\n"));
999 for (;;)
1001 rc = 0;
1002 xfree(answer);
1003 if ( have_def_rec )
1005 /* A default recipient is taken as the first entry. */
1006 answer = def_rec;
1007 def_rec = NULL;
1009 else if (backlog)
1011 /* This is part of our trick to expand and display groups. */
1012 answer = strlist_pop (&backlog);
1014 else
1016 /* Show the list of already collected recipients and ask
1017 for more. */
1018 PK_LIST iter;
1020 tty_printf("\n");
1021 tty_printf(_("Current recipients:\n"));
1022 for (iter=pk_list;iter;iter=iter->next)
1024 u32 keyid[2];
1026 keyid_from_pk(iter->pk,keyid);
1027 tty_printf("%4u%c/%s %s \"",
1028 nbits_from_pk(iter->pk),
1029 pubkey_letter(iter->pk->pubkey_algo),
1030 keystr(keyid),
1031 datestr_from_pk(iter->pk));
1033 if (iter->pk->user_id)
1034 tty_print_utf8_string(iter->pk->user_id->name,
1035 iter->pk->user_id->len);
1036 else
1038 size_t n;
1039 char *p = get_user_id( keyid, &n );
1040 tty_print_utf8_string( p, n );
1041 xfree(p);
1043 tty_printf("\"\n");
1046 answer = cpr_get_utf8("pklist.user_id.enter",
1047 _("\nEnter the user ID. "
1048 "End with an empty line: "));
1049 trim_spaces(answer);
1050 cpr_kill_prompt();
1053 if ( !answer || !*answer )
1055 xfree(answer);
1056 break; /* No more recipients entered - get out of loop. */
1059 /* Do group expand here too. The trick here is to continue
1060 the loop if any expansion occured. The code above will
1061 then list all expanded keys. */
1062 if (expand_id(answer,&backlog,0))
1063 continue;
1065 /* Get and check key for the current name. */
1066 if (pk)
1067 free_public_key (pk);
1068 pk = xmalloc_clear( sizeof *pk );
1069 pk->req_usage = use;
1070 rc = get_pubkey_byname (NULL, pk, answer, NULL, NULL, 0, 0 );
1071 if (rc)
1072 tty_printf(_("No such user ID.\n"));
1073 else if ( !(rc=openpgp_pk_test_algo2 (pk->pubkey_algo, use)) )
1075 if ( have_def_rec )
1077 /* No validation for a default recipient. */
1078 if (!key_present_in_pk_list(pk_list, pk))
1080 free_public_key (pk); pk = NULL;
1081 log_info (_("skipped: public key "
1082 "already set as default recipient\n") );
1084 else
1086 PK_LIST r = xmalloc (sizeof *r);
1087 r->pk = pk; pk = NULL;
1088 r->next = pk_list;
1089 r->flags = 0; /* No throwing default ids. */
1090 pk_list = r;
1092 any_recipients = 1;
1093 continue;
1095 else
1096 { /* Check validity of this key. */
1097 int trustlevel;
1099 trustlevel = get_validity (pk, pk->user_id);
1100 if ( (trustlevel & TRUST_FLAG_DISABLED) )
1102 tty_printf (_("Public key is disabled.\n") );
1104 else if ( do_we_trust_pre (pk, trustlevel) )
1106 /* Skip the actual key if the key is already
1107 * present in the list */
1108 if (!key_present_in_pk_list(pk_list, pk))
1110 free_public_key(pk); pk = NULL;
1111 log_info(_("skipped: public key already set\n") );
1113 else
1115 PK_LIST r;
1116 r = xmalloc( sizeof *r );
1117 r->pk = pk; pk = NULL;
1118 r->next = pk_list;
1119 r->flags = 0; /* No throwing interactive ids. */
1120 pk_list = r;
1122 any_recipients = 1;
1123 continue;
1127 xfree(def_rec); def_rec = NULL;
1128 have_def_rec = 0;
1130 if ( pk )
1132 free_public_key( pk );
1133 pk = NULL;
1136 else if ( !any_recipients && (def_rec = default_recipient()) )
1138 /* We are in batch mode and have only a default recipient. */
1139 pk = xmalloc_clear( sizeof *pk );
1140 pk->req_usage = use;
1142 /* The default recipient is allowed to be disabled; thus pass 1
1143 as second last argument. We also don't want an AKL. */
1144 rc = get_pubkey_byname (NULL, pk, def_rec, NULL, NULL, 1, 1);
1145 if (rc)
1146 log_error(_("unknown default recipient \"%s\"\n"), def_rec );
1147 else if ( !(rc=openpgp_pk_test_algo2(pk->pubkey_algo, use)) )
1149 /* Mark any_recipients here since the default recipient
1150 would have been used if it wasn't already there. It
1151 doesn't really matter if we got this key from the default
1152 recipient or an encrypt-to. */
1153 any_recipients = 1;
1154 if (!key_present_in_pk_list(pk_list, pk))
1155 log_info (_("skipped: public key already set "
1156 "as default recipient\n"));
1157 else
1159 PK_LIST r = xmalloc( sizeof *r );
1160 r->pk = pk; pk = NULL;
1161 r->next = pk_list;
1162 r->flags = 0; /* No throwing default ids. */
1163 pk_list = r;
1166 if ( pk )
1168 free_public_key( pk );
1169 pk = NULL;
1171 xfree(def_rec); def_rec = NULL;
1173 else
1175 /* General case: Check all keys. */
1176 any_recipients = 0;
1177 for (; remusr; remusr = remusr->next )
1179 if ( (remusr->flags & 1) )
1180 continue; /* encrypt-to keys are already handled. */
1182 rc = find_and_check_key (remusr->d, use, !!(remusr->flags&2),
1183 &pk_list);
1184 if (rc)
1185 goto fail;
1186 any_recipients = 1;
1190 if ( !rc && !any_recipients )
1192 log_error(_("no valid addressees\n"));
1193 write_status_text (STATUS_NO_RECP, "0");
1194 rc = G10ERR_NO_USER_ID;
1197 fail:
1199 if ( rc )
1200 release_pk_list( pk_list );
1201 else
1202 *ret_pk_list = pk_list;
1203 if (opt.grouplist)
1204 free_strlist(remusr);
1205 return rc;
1209 /* In pgp6 mode, disallow all ciphers except IDEA (1), 3DES (2), and
1210 CAST5 (3), all hashes except MD5 (1), SHA1 (2), and RIPEMD160 (3),
1211 and all compressions except none (0) and ZIP (1). pgp7 and pgp8
1212 mode expands the cipher list to include AES128 (7), AES192 (8),
1213 AES256 (9), and TWOFISH (10). pgp8 adds the SHA-256 hash (8). For
1214 a true PGP key all of this is unneeded as they are the only items
1215 present in the preferences subpacket, but checking here covers the
1216 weird case of encrypting to a key that had preferences from a
1217 different implementation which was then used with PGP. I am not
1218 completely comfortable with this as the right thing to do, as it
1219 slightly alters the list of what the user is supposedly requesting.
1220 It is not against the RFC however, as the preference chosen will
1221 never be one that the user didn't specify somewhere ("The
1222 implementation may use any mechanism to pick an algorithm in the
1223 intersection"), and PGP has no mechanism to fix such a broken
1224 preference list, so I'm including it. -dms */
1227 algo_available( preftype_t preftype, int algo, const union pref_hint *hint)
1229 if( preftype == PREFTYPE_SYM )
1231 if(PGP6 && (algo != CIPHER_ALGO_IDEA
1232 && algo != CIPHER_ALGO_3DES
1233 && algo != CIPHER_ALGO_CAST5))
1234 return 0;
1236 if(PGP7 && (algo != CIPHER_ALGO_IDEA
1237 && algo != CIPHER_ALGO_3DES
1238 && algo != CIPHER_ALGO_CAST5
1239 && algo != CIPHER_ALGO_AES
1240 && algo != CIPHER_ALGO_AES192
1241 && algo != CIPHER_ALGO_AES256
1242 && algo != CIPHER_ALGO_TWOFISH))
1243 return 0;
1245 /* PGP8 supports all the ciphers we do.. */
1247 return algo && !openpgp_cipher_test_algo ( algo );
1249 else if( preftype == PREFTYPE_HASH )
1251 if (hint && hint->digest_length)
1253 if (hint->digest_length!=20 || opt.flags.dsa2)
1255 /* If --enable-dsa2 is set or the hash isn't 160 bits
1256 (which implies DSA2), then we'll accept a hash that
1257 is larger than we need. Otherwise we won't accept
1258 any hash that isn't exactly the right size. */
1259 if (hint->digest_length > gcry_md_get_algo_dlen (algo))
1260 return 0;
1262 else if (hint->digest_length != gcry_md_get_algo_dlen (algo))
1263 return 0;
1266 if((PGP6 || PGP7) && (algo != DIGEST_ALGO_MD5
1267 && algo != DIGEST_ALGO_SHA1
1268 && algo != DIGEST_ALGO_RMD160))
1269 return 0;
1272 if(PGP8 && (algo != DIGEST_ALGO_MD5
1273 && algo != DIGEST_ALGO_SHA1
1274 && algo != DIGEST_ALGO_RMD160
1275 && algo != DIGEST_ALGO_SHA256))
1276 return 0;
1278 return algo && !openpgp_md_test_algo (algo);
1280 else if( preftype == PREFTYPE_ZIP )
1282 if((PGP6 || PGP7) && (algo != COMPRESS_ALGO_NONE
1283 && algo != COMPRESS_ALGO_ZIP))
1284 return 0;
1286 /* PGP8 supports all the compression algos we do */
1288 return !check_compress_algo( algo );
1290 else
1291 return 0;
1294 /****************
1295 * Return -1 if we could not find an algorithm.
1298 select_algo_from_prefs(PK_LIST pk_list, int preftype,
1299 int request, const union pref_hint *hint)
1301 PK_LIST pkr;
1302 u32 bits[8];
1303 const prefitem_t *prefs;
1304 int result=-1,i;
1305 unsigned int best=-1;
1306 byte scores[256];
1308 if( !pk_list )
1309 return -1;
1311 memset(bits,0xFF,sizeof(bits));
1312 memset(scores,0,sizeof(scores));
1314 for( pkr = pk_list; pkr; pkr = pkr->next )
1316 u32 mask[8];
1317 int rank=1,implicit=-1;
1319 memset(mask,0,sizeof(mask));
1321 switch(preftype)
1323 case PREFTYPE_SYM:
1324 /* IDEA is implicitly there for v3 keys with v3 selfsigs if
1325 --pgp2 mode is on. This was a 2440 thing that was
1326 dropped from 4880 but is still relevant to GPG's 1991
1327 support. All this doesn't mean IDEA is actually
1328 available, of course. */
1329 if(PGP2 && pkr->pk->version<4 && pkr->pk->selfsigversion<4)
1330 implicit=CIPHER_ALGO_IDEA;
1331 else
1332 implicit=CIPHER_ALGO_3DES;
1334 break;
1336 case PREFTYPE_HASH:
1337 /* While I am including this code for completeness, note
1338 that currently --pgp2 mode locks the hash at MD5, so this
1339 code will never even be called. Even if the hash wasn't
1340 locked at MD5, we don't support sign+encrypt in --pgp2
1341 mode, and that's the only time PREFTYPE_HASH is used
1342 anyway. -dms */
1344 /* MD5 is there for v3 keys with v3 selfsigs when --pgp2 is
1345 on. */
1346 if(PGP2 && pkr->pk->version<4 && pkr->pk->selfsigversion<4)
1347 implicit=DIGEST_ALGO_MD5;
1348 else
1349 implicit=DIGEST_ALGO_SHA1;
1351 break;
1353 case PREFTYPE_ZIP:
1354 /* Uncompressed is always an option. */
1355 implicit=COMPRESS_ALGO_NONE;
1358 if (pkr->pk->user_id) /* selected by user ID */
1359 prefs = pkr->pk->user_id->prefs;
1360 else
1361 prefs = pkr->pk->prefs;
1363 if( prefs )
1365 for (i=0; prefs[i].type; i++ )
1367 if( prefs[i].type == preftype )
1369 scores[prefs[i].value]+=rank;
1370 mask[prefs[i].value/32] |= 1<<(prefs[i].value%32);
1372 rank++;
1374 /* We saw the implicit algorithm, so we don't need
1375 tack it on the end ourselves. */
1376 if(implicit==prefs[i].value)
1377 implicit=-1;
1382 if(rank==1 && preftype==PREFTYPE_ZIP)
1384 /* If the compression preferences are not present, they are
1385 assumed to be ZIP, Uncompressed (RFC4880:13.3.1) */
1386 scores[1]=1; /* ZIP is first choice */
1387 scores[0]=2; /* Uncompressed is second choice */
1388 mask[0]|=3;
1391 /* If the key didn't have the implicit algorithm listed
1392 explicitly, add it here at the tail of the list. */
1393 if(implicit>-1)
1395 scores[implicit]+=rank;
1396 mask[implicit/32] |= 1<<(implicit%32);
1399 for(i=0;i<8;i++)
1400 bits[i]&=mask[i];
1403 /* We've now scored all of the algorithms, and the usable ones have
1404 bits set. Let's pick the winner. */
1406 /* The caller passed us a request. Can we use it? */
1407 if(request>-1 && (bits[request/32] & (1<<(request%32))) &&
1408 algo_available(preftype,request,hint))
1409 result=request;
1411 if(result==-1)
1413 /* If we have personal prefs set, use them. */
1414 prefs=NULL;
1415 if(preftype==PREFTYPE_SYM && opt.personal_cipher_prefs)
1416 prefs=opt.personal_cipher_prefs;
1417 else if(preftype==PREFTYPE_HASH && opt.personal_digest_prefs)
1418 prefs=opt.personal_digest_prefs;
1419 else if(preftype==PREFTYPE_ZIP && opt.personal_compress_prefs)
1420 prefs=opt.personal_compress_prefs;
1422 if( prefs )
1423 for(i=0; prefs[i].type; i++ )
1425 if(bits[prefs[i].value/32] & (1<<(prefs[i].value%32))
1426 && algo_available( preftype, prefs[i].value, hint))
1428 result = prefs[i].value;
1429 break;
1434 if(result==-1)
1436 /* At this point, we have not selected an algorithm due to a
1437 special request or via personal prefs. Pick the highest
1438 ranked algorithm (i.e. the one with the lowest score). */
1440 for(i=0;i<256;i++)
1442 /* Note the '<' here. This means in case of a tie, we will
1443 favor the lower algorithm number. We have a choice
1444 between the lower number (probably an older algorithm
1445 with more time in use), or the higher number (probably a
1446 newer algorithm with less time in use). Older is
1447 probably safer here, even though the newer algorithms
1448 tend to be "stronger". */
1449 if(scores[i] && scores[i]<best
1450 && (bits[i/32] & (1<<(i%32)))
1451 && algo_available(preftype,i,hint))
1453 best=scores[i];
1454 result=i;
1458 /* "If you are building an authentication system, the recipient
1459 may specify a preferred signing algorithm. However, the
1460 signer would be foolish to use a weak algorithm simply
1461 because the recipient requests it." (RFC4880:14). If we
1462 settle on MD5, and SHA1 is also available, use SHA1 instead.
1463 Note that if the user intentionally chose MD5 by putting it
1464 in their personal prefs, then we do what the user said (as we
1465 never reach this code). */
1466 if(preftype==PREFTYPE_HASH && result==DIGEST_ALGO_MD5
1467 && (bits[0] & (1<<DIGEST_ALGO_SHA1)))
1468 result=DIGEST_ALGO_SHA1;
1471 return result;
1475 * Select the MDC flag from the pk_list. We can only use MDC if all
1476 * recipients support this feature.
1479 select_mdc_from_pklist (PK_LIST pk_list)
1481 PK_LIST pkr;
1483 if ( !pk_list )
1484 return 0;
1486 for (pkr = pk_list; pkr; pkr = pkr->next)
1488 int mdc;
1490 if (pkr->pk->user_id) /* selected by user ID */
1491 mdc = pkr->pk->user_id->flags.mdc;
1492 else
1493 mdc = pkr->pk->mdc_feature;
1494 if (!mdc)
1495 return 0; /* At least one recipient does not support it. */
1497 return 1; /* Can be used. */
1501 /* Print a warning for all keys in PK_LIST missing the MDC feature. */
1502 void
1503 warn_missing_mdc_from_pklist (PK_LIST pk_list)
1505 PK_LIST pkr;
1507 for (pkr = pk_list; pkr; pkr = pkr->next)
1509 int mdc;
1511 if (pkr->pk->user_id) /* selected by user ID */
1512 mdc = pkr->pk->user_id->flags.mdc;
1513 else
1514 mdc = pkr->pk->mdc_feature;
1515 if (!mdc)
1516 log_info (_("Note: key %s has no %s feature\n"),
1517 keystr_from_pk (pkr->pk), "MDC");
1521 void
1522 warn_missing_aes_from_pklist (PK_LIST pk_list)
1524 PK_LIST pkr;
1526 for (pkr = pk_list; pkr; pkr = pkr->next)
1528 const prefitem_t *prefs;
1529 int i;
1530 int gotit = 0;
1532 prefs = pkr->pk->user_id? pkr->pk->user_id->prefs : pkr->pk->prefs;
1533 if (prefs)
1535 for (i=0; !gotit && prefs[i].type; i++ )
1536 if (prefs[i].type == PREFTYPE_SYM
1537 && prefs[i].value == CIPHER_ALGO_AES)
1538 gotit++;
1540 if (!gotit)
1541 log_info (_("Note: key %s has no preference for %s\n"),
1542 keystr_from_pk (pkr->pk), "AES");