* srv.c (getsrv): Raise maximum packet size to 2048, as PACKETSZ is
[gnupg.git] / g10 / pkclist.c
blob3203a7ea6ae643544f014651a69796cc6d048df0
1 /* pkclist.c - create a list of public keys
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
3 * 2008 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 /****************
44 * Show the revocation reason as it is stored with the given signature
46 static void
47 do_show_revocation_reason( PKT_signature *sig )
49 size_t n, nn;
50 const byte *p, *pp;
51 int seq = 0;
52 const char *text;
54 while( (p = enum_sig_subpkt (sig->hashed, SIGSUBPKT_REVOC_REASON,
55 &n, &seq, NULL )) ) {
56 if( !n )
57 continue; /* invalid - just skip it */
59 if( *p == 0 )
60 text = _("No reason specified");
61 else if( *p == 0x01 )
62 text = _("Key is superseded");
63 else if( *p == 0x02 )
64 text = _("Key has been compromised");
65 else if( *p == 0x03 )
66 text = _("Key is no longer used");
67 else if( *p == 0x20 )
68 text = _("User ID is no longer valid");
69 else
70 text = NULL;
72 log_info( _("reason for revocation: ") );
73 if( text )
74 fputs( text, log_get_stream() );
75 else
76 fprintf( log_get_stream(), "code=%02x", *p );
77 log_printf ("\n");
78 n--; p++;
79 pp = NULL;
80 do {
81 /* We don't want any empty lines, so skip them */
82 while( n && *p == '\n' ) {
83 p++;
84 n--;
86 if( n ) {
87 pp = memchr( p, '\n', n );
88 nn = pp? pp - p : n;
89 log_info ( _("revocation comment: ") );
90 print_string ( log_get_stream(), p, nn, 0 );
91 log_printf ("\n");
92 p += nn; n -= nn;
94 } while( pp );
98 /* Mode 0: try and find the revocation based on the pk (i.e. check
99 subkeys, etc.) Mode 1: use only the revocation on the main pk */
101 void
102 show_revocation_reason( PKT_public_key *pk, int mode )
104 /* Hmmm, this is not so easy becuase we have to duplicate the code
105 * used in the trustbd to calculate the keyflags. We need to find
106 * a clean way to check revocation certificates on keys and
107 * signatures. And there should be no duplicate code. Because we
108 * enter this function only when the trustdb told us that we have
109 * a revoked key, we could simply look for a revocation cert and
110 * display this one, when there is only one. Let's try to do this
111 * until we have a better solution. */
112 KBNODE node, keyblock = NULL;
113 byte fingerprint[MAX_FINGERPRINT_LEN];
114 size_t fingerlen;
115 int rc;
117 /* get the keyblock */
118 fingerprint_from_pk( pk, fingerprint, &fingerlen );
119 rc = get_keyblock_byfprint( &keyblock, fingerprint, fingerlen );
120 if( rc ) { /* that should never happen */
121 log_debug( "failed to get the keyblock\n");
122 return;
125 for( node=keyblock; node; node = node->next ) {
126 if( (mode && node->pkt->pkttype == PKT_PUBLIC_KEY) ||
127 ( ( node->pkt->pkttype == PKT_PUBLIC_KEY
128 || node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
129 && !cmp_public_keys( node->pkt->pkt.public_key, pk ) ) )
130 break;
132 if( !node ) {
133 log_debug("Oops, PK not in keyblock\n");
134 release_kbnode( keyblock );
135 return;
137 /* now find the revocation certificate */
138 for( node = node->next; node ; node = node->next ) {
139 if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY )
140 break;
141 if( node->pkt->pkttype == PKT_SIGNATURE
142 && (node->pkt->pkt.signature->sig_class == 0x20
143 || node->pkt->pkt.signature->sig_class == 0x28 ) ) {
144 /* FIXME: we should check the signature here */
145 do_show_revocation_reason ( node->pkt->pkt.signature );
146 break;
150 /* We didn't find it, so check if the whole key is revoked */
151 if(!node && !mode)
152 show_revocation_reason(pk,1);
154 release_kbnode( keyblock );
158 /****************
159 * mode: 0 = standard
160 * 1 = Without key info and additional menu option 'm'
161 * this does also add an option to set the key to ultimately trusted.
162 * Returns:
163 * -2 = nothing changed - caller should show some additional info
164 * -1 = quit operation
165 * 0 = nothing changed
166 * 1 = new ownertrust now in new_trust
168 static int
169 do_edit_ownertrust (PKT_public_key *pk, int mode,
170 unsigned *new_trust, int defer_help )
172 char *p;
173 u32 keyid[2];
174 int changed=0;
175 int quit=0;
176 int show=0;
177 int min_num;
178 int did_help=defer_help;
179 unsigned int minimum=get_min_ownertrust(pk);
181 switch(minimum)
183 default:
184 case TRUST_UNDEFINED: min_num=1; break;
185 case TRUST_NEVER: min_num=2; break;
186 case TRUST_MARGINAL: min_num=3; break;
187 case TRUST_FULLY: min_num=4; break;
190 keyid_from_pk (pk, keyid);
191 for(;;) {
192 /* A string with valid answers.
194 Note to translators: These are the allowed answers in lower and
195 uppercase. Below you will find the matching strings which
196 should be translated accordingly and the letter changed to
197 match the one in the answer string.
199 i = please show me more information
200 m = back to the main menu
201 s = skip this key
202 q = quit
204 const char *ans = _("iImMqQsS");
206 if( !did_help )
208 if( !mode )
210 KBNODE keyblock, un;
212 tty_printf(_("No trust value assigned to:\n"));
213 tty_printf("%4u%c/%s %s\n",nbits_from_pk( pk ),
214 pubkey_letter( pk->pubkey_algo ),
215 keystr(keyid), datestr_from_pk( pk ) );
216 p=get_user_id_native(keyid);
217 tty_printf(_(" \"%s\"\n"),p);
218 xfree(p);
220 keyblock = get_pubkeyblock (keyid);
221 if (!keyblock)
222 BUG ();
223 for (un=keyblock; un; un = un->next)
225 if (un->pkt->pkttype != PKT_USER_ID )
226 continue;
227 if (un->pkt->pkt.user_id->is_revoked )
228 continue;
229 if (un->pkt->pkt.user_id->is_expired )
230 continue;
231 /* Only skip textual primaries */
232 if (un->pkt->pkt.user_id->is_primary
233 && !un->pkt->pkt.user_id->attrib_data )
234 continue;
236 if((opt.verify_options&VERIFY_SHOW_PHOTOS)
237 && un->pkt->pkt.user_id->attrib_data)
238 show_photos(un->pkt->pkt.user_id->attribs,
239 un->pkt->pkt.user_id->numattribs,pk,NULL,
240 un->pkt->pkt.user_id);
242 p=utf8_to_native(un->pkt->pkt.user_id->name,
243 un->pkt->pkt.user_id->len,0);
245 tty_printf(_(" aka \"%s\"\n"),p);
248 print_fingerprint (pk, NULL, 2);
249 tty_printf("\n");
250 release_kbnode (keyblock);
253 if(opt.trust_model==TM_DIRECT)
255 tty_printf(_("How much do you trust that this key actually "
256 "belongs to the named user?\n"));
257 tty_printf("\n");
259 else
261 /* This string also used in keyedit.c:trustsig_prompt */
262 tty_printf(_("Please decide how far you trust this user to"
263 " correctly verify other users' keys\n"
264 "(by looking at passports, checking fingerprints from"
265 " different sources, etc.)\n"));
266 tty_printf("\n");
269 if(min_num<=1)
270 tty_printf (_(" %d = I don't know or won't say\n"), 1);
271 if(min_num<=2)
272 tty_printf (_(" %d = I do NOT trust\n"), 2);
273 if(min_num<=3)
274 tty_printf (_(" %d = I trust marginally\n"), 3);
275 if(min_num<=4)
276 tty_printf (_(" %d = I trust fully\n"), 4);
277 if (mode)
278 tty_printf (_(" %d = I trust ultimately\n"), 5);
279 #if 0
280 /* not yet implemented */
281 tty_printf (" i = please show me more information\n");
282 #endif
283 if( mode )
284 tty_printf(_(" m = back to the main menu\n"));
285 else
287 tty_printf(_(" s = skip this key\n"));
288 tty_printf(_(" q = quit\n"));
290 tty_printf("\n");
291 if(minimum)
292 tty_printf(_("The minimum trust level for this key is: %s\n\n"),
293 trust_value_to_string(minimum));
294 did_help = 1;
296 if( strlen(ans) != 8 )
297 BUG();
298 p = cpr_get("edit_ownertrust.value",_("Your decision? "));
299 trim_spaces(p);
300 cpr_kill_prompt();
301 if( !*p )
302 did_help = 0;
303 else if( *p && p[1] )
305 else if( !p[1] && ((*p >= '0'+min_num) && *p <= (mode?'5':'4')) )
307 unsigned int trust;
308 switch( *p )
310 case '1': trust = TRUST_UNDEFINED; break;
311 case '2': trust = TRUST_NEVER ; break;
312 case '3': trust = TRUST_MARGINAL ; break;
313 case '4': trust = TRUST_FULLY ; break;
314 case '5': trust = TRUST_ULTIMATE ; break;
315 default: BUG();
317 if (trust == TRUST_ULTIMATE
318 && !cpr_get_answer_is_yes ("edit_ownertrust.set_ultimate.okay",
319 _("Do you really want to set this key"
320 " to ultimate trust? (y/N) ")))
321 ; /* no */
322 else
324 *new_trust = trust;
325 changed = 1;
326 break;
329 #if 0
330 /* not yet implemented */
331 else if( *p == ans[0] || *p == ans[1] )
333 tty_printf(_("Certificates leading to an ultimately trusted key:\n"));
334 show = 1;
335 break;
337 #endif
338 else if( mode && (*p == ans[2] || *p == ans[3] || *p == CONTROL_D ) )
340 break ; /* back to the menu */
342 else if( !mode && (*p == ans[6] || *p == ans[7] ) )
344 break; /* skip */
346 else if( !mode && (*p == ans[4] || *p == ans[5] ) )
348 quit = 1;
349 break ; /* back to the menu */
351 xfree(p); p = NULL;
353 xfree(p);
354 return show? -2: quit? -1 : changed;
358 * Display a menu to change the ownertrust of the key PK (which should
359 * be a primary key).
360 * For mode values see do_edit_ownertrust ()
363 edit_ownertrust (PKT_public_key *pk, int mode )
365 unsigned int trust = 0;
366 int no_help = 0;
368 for(;;)
370 switch ( do_edit_ownertrust (pk, mode, &trust, no_help ) )
372 case -1: /* quit */
373 return -1;
374 case -2: /* show info */
375 no_help = 1;
376 break;
377 case 1: /* trust value set */
378 trust &= ~TRUST_FLAG_DISABLED;
379 trust |= get_ownertrust (pk) & TRUST_FLAG_DISABLED;
380 update_ownertrust (pk, trust );
381 return 1;
382 default:
383 return 0;
389 /****************
390 * Check whether we can trust this pk which has a trustlevel of TRUSTLEVEL
391 * Returns: true if we trust.
393 static int
394 do_we_trust( PKT_public_key *pk, unsigned int trustlevel )
396 /* We should not be able to get here with a revoked or expired
397 key */
398 if(trustlevel & TRUST_FLAG_REVOKED
399 || trustlevel & TRUST_FLAG_SUB_REVOKED
400 || (trustlevel & TRUST_MASK) == TRUST_EXPIRED)
401 BUG();
403 if( opt.trust_model==TM_ALWAYS )
405 if( opt.verbose )
406 log_info("No trust check due to `--trust-model always' option\n");
407 return 1;
410 switch(trustlevel & TRUST_MASK)
412 default:
413 log_error ("invalid trustlevel %u returned from validation layer\n",
414 trustlevel);
415 /* fall thru */
416 case TRUST_UNKNOWN:
417 case TRUST_UNDEFINED:
418 log_info(_("%s: There is no assurance this key belongs"
419 " to the named user\n"),keystr_from_pk(pk));
420 return 0; /* no */
422 case TRUST_MARGINAL:
423 log_info(_("%s: There is limited assurance this key belongs"
424 " to the named user\n"),keystr_from_pk(pk));
425 return 1; /* yes */
427 case TRUST_FULLY:
428 if( opt.verbose )
429 log_info(_("This key probably belongs to the named user\n"));
430 return 1; /* yes */
432 case TRUST_ULTIMATE:
433 if( opt.verbose )
434 log_info(_("This key belongs to us\n"));
435 return 1; /* yes */
438 return 1; /*NOTREACHED*/
442 /****************
443 * wrapper around do_we_trust, so we can ask whether to use the
444 * key anyway.
446 static int
447 do_we_trust_pre( PKT_public_key *pk, unsigned int trustlevel )
449 int rc;
451 rc = do_we_trust( pk, trustlevel );
453 if( !opt.batch && !rc )
455 print_pubkey_info(NULL,pk);
456 print_fingerprint (pk, NULL, 2);
457 tty_printf("\n");
459 tty_printf(
460 _("It is NOT certain that the key belongs to the person named\n"
461 "in the user ID. If you *really* know what you are doing,\n"
462 "you may answer the next question with yes.\n"));
464 tty_printf("\n");
467 if (is_status_enabled ())
469 u32 kid[2];
470 char *hint_str;
472 keyid_from_pk (pk, kid);
473 hint_str = get_long_user_id_string ( kid );
474 write_status_text ( STATUS_USERID_HINT, hint_str );
475 xfree (hint_str);
478 if( cpr_get_answer_is_yes("untrusted_key.override",
479 _("Use this key anyway? (y/N) ")) )
480 rc = 1;
482 /* Hmmm: Should we set a flag to tell the user about
483 * his decision the next time he encrypts for this recipient?
487 return rc;
491 /****************
492 * Check whether we can trust this signature.
493 * Returns: Error if we shall not trust this signatures.
496 check_signatures_trust( PKT_signature *sig )
498 PKT_public_key *pk = xmalloc_clear( sizeof *pk );
499 unsigned int trustlevel;
500 int rc=0;
502 rc = get_pubkey( pk, sig->keyid );
503 if (rc)
504 { /* this should not happen */
505 log_error("Ooops; the key vanished - can't check the trust\n");
506 rc = G10ERR_NO_PUBKEY;
507 goto leave;
510 if ( opt.trust_model==TM_ALWAYS )
512 if( !opt.quiet )
513 log_info(_("WARNING: Using untrusted key!\n"));
514 if (opt.with_fingerprint)
515 print_fingerprint (pk, NULL, 1);
516 goto leave;
519 if(pk->maybe_revoked && !pk->is_revoked)
520 log_info(_("WARNING: this key might be revoked (revocation key"
521 " not present)\n"));
523 trustlevel = get_validity (pk, NULL);
525 if ( (trustlevel & TRUST_FLAG_REVOKED) )
527 write_status( STATUS_KEYREVOKED );
528 if(pk->is_revoked==2)
529 log_info(_("WARNING: This key has been revoked by its"
530 " designated revoker!\n"));
531 else
532 log_info(_("WARNING: This key has been revoked by its owner!\n"));
533 log_info(_(" This could mean that the signature is forged.\n"));
534 show_revocation_reason( pk, 0 );
536 else if ((trustlevel & TRUST_FLAG_SUB_REVOKED) )
538 write_status( STATUS_KEYREVOKED );
539 log_info(_("WARNING: This subkey has been revoked by its owner!\n"));
540 show_revocation_reason( pk, 0 );
543 if ((trustlevel & TRUST_FLAG_DISABLED))
544 log_info (_("Note: This key has been disabled.\n"));
546 /* If we have PKA information adjust the trustlevel. */
547 if (sig->pka_info && sig->pka_info->valid)
549 unsigned char fpr[MAX_FINGERPRINT_LEN];
550 PKT_public_key *primary_pk;
551 size_t fprlen;
552 int okay;
555 primary_pk = xmalloc_clear (sizeof *primary_pk);
556 get_pubkey (primary_pk, pk->main_keyid);
557 fingerprint_from_pk (primary_pk, fpr, &fprlen);
558 free_public_key (primary_pk);
560 if ( fprlen == 20 && !memcmp (sig->pka_info->fpr, fpr, 20) )
562 okay = 1;
563 write_status_text (STATUS_PKA_TRUST_GOOD, sig->pka_info->email);
564 log_info (_("Note: Verified signer's address is `%s'\n"),
565 sig->pka_info->email);
567 else
569 okay = 0;
570 write_status_text (STATUS_PKA_TRUST_BAD, sig->pka_info->email);
571 log_info (_("Note: Signer's address `%s' "
572 "does not match DNS entry\n"), sig->pka_info->email);
575 switch ( (trustlevel & TRUST_MASK) )
577 case TRUST_UNKNOWN:
578 case TRUST_UNDEFINED:
579 case TRUST_MARGINAL:
580 if (okay && opt.verify_options&VERIFY_PKA_TRUST_INCREASE)
582 trustlevel = ((trustlevel & ~TRUST_MASK) | TRUST_FULLY);
583 log_info (_("trustlevel adjusted to FULL"
584 " due to valid PKA info\n"));
586 /* (fall through) */
587 case TRUST_FULLY:
588 if (!okay)
590 trustlevel = ((trustlevel & ~TRUST_MASK) | TRUST_NEVER);
591 log_info (_("trustlevel adjusted to NEVER"
592 " due to bad PKA info\n"));
594 break;
598 /* Now let the user know what up with the trustlevel. */
599 switch ( (trustlevel & TRUST_MASK) )
601 case TRUST_EXPIRED:
602 log_info(_("Note: This key has expired!\n"));
603 print_fingerprint (pk, NULL, 1);
604 break;
606 default:
607 log_error ("invalid trustlevel %u returned from validation layer\n",
608 trustlevel);
609 /* fall thru */
610 case TRUST_UNKNOWN:
611 case TRUST_UNDEFINED:
612 write_status( STATUS_TRUST_UNDEFINED );
613 log_info(_("WARNING: This key is not certified with"
614 " a trusted signature!\n"));
615 log_info(_(" There is no indication that the "
616 "signature belongs to the owner.\n" ));
617 print_fingerprint (pk, NULL, 1);
618 break;
620 case TRUST_NEVER:
621 /* currently we won't get that status */
622 write_status( STATUS_TRUST_NEVER );
623 log_info(_("WARNING: We do NOT trust this key!\n"));
624 log_info(_(" The signature is probably a FORGERY.\n"));
625 if (opt.with_fingerprint)
626 print_fingerprint (pk, NULL, 1);
627 rc = gpg_error (GPG_ERR_BAD_SIGNATURE);
628 break;
630 case TRUST_MARGINAL:
631 write_status( STATUS_TRUST_MARGINAL );
632 log_info(_("WARNING: This key is not certified with"
633 " sufficiently trusted signatures!\n"));
634 log_info(_(" It is not certain that the"
635 " signature belongs to the owner.\n" ));
636 print_fingerprint (pk, NULL, 1);
637 break;
639 case TRUST_FULLY:
640 write_status( STATUS_TRUST_FULLY );
641 if (opt.with_fingerprint)
642 print_fingerprint (pk, NULL, 1);
643 break;
645 case TRUST_ULTIMATE:
646 write_status( STATUS_TRUST_ULTIMATE );
647 if (opt.with_fingerprint)
648 print_fingerprint (pk, NULL, 1);
649 break;
652 leave:
653 free_public_key( pk );
654 return rc;
658 void
659 release_pk_list( PK_LIST pk_list )
661 PK_LIST pk_rover;
663 for( ; pk_list; pk_list = pk_rover ) {
664 pk_rover = pk_list->next;
665 free_public_key( pk_list->pk );
666 xfree( pk_list );
671 static int
672 key_present_in_pk_list(PK_LIST pk_list, PKT_public_key *pk)
674 for( ; pk_list; pk_list = pk_list->next)
675 if (cmp_public_keys(pk_list->pk, pk) == 0)
676 return 0;
678 return -1;
682 /****************
683 * Return a malloced string with a default reciepient if there is any
685 static char *
686 default_recipient(void)
688 PKT_secret_key *sk;
689 byte fpr[MAX_FINGERPRINT_LEN+1];
690 size_t n;
691 char *p;
692 int i;
694 if( opt.def_recipient )
695 return xstrdup( opt.def_recipient );
696 if( !opt.def_recipient_self )
697 return NULL;
698 sk = xmalloc_clear( sizeof *sk );
699 i = get_seckey_byname( sk, NULL, 0 );
700 if( i ) {
701 free_secret_key( sk );
702 return NULL;
704 n = MAX_FINGERPRINT_LEN;
705 fingerprint_from_sk( sk, fpr, &n );
706 free_secret_key( sk );
707 p = xmalloc( 2*n+3 );
708 *p++ = '0';
709 *p++ = 'x';
710 for(i=0; i < n; i++ )
711 sprintf( p+2*i, "%02X", fpr[i] );
712 p -= 2;
713 return p;
716 static int
717 expand_id(const char *id,strlist_t *into,unsigned int flags)
719 struct groupitem *groups;
720 int count=0;
722 for(groups=opt.grouplist;groups;groups=groups->next)
724 /* need strcasecmp() here, as this should be localized */
725 if(strcasecmp(groups->name,id)==0)
727 strlist_t each,sl;
729 /* this maintains the current utf8-ness */
730 for(each=groups->values;each;each=each->next)
732 sl=add_to_strlist(into,each->d);
733 sl->flags=flags;
734 count++;
737 break;
741 return count;
744 /* For simplicity, and to avoid potential loops, we only expand once -
745 you can't make an alias that points to an alias. */
746 static strlist_t
747 expand_group(strlist_t input)
749 strlist_t sl,output=NULL,rover;
751 for(rover=input;rover;rover=rover->next)
752 if(expand_id(rover->d,&output,rover->flags)==0)
754 /* Didn't find any groups, so use the existing string */
755 sl=add_to_strlist(&output,rover->d);
756 sl->flags=rover->flags;
759 return output;
763 /* This is the central function to collect the keys for recipients.
764 It is thus used to prepare a public key encryption. encrypt-to
765 keys, default keys and the keys for the actual recipients are all
766 collected here. When not in batch mode and no recipient has been
767 passed on the commandline, the function will also ask for
768 recipients.
770 RCPTS is a string list with the recipients; NULL is an allowed
771 value but not very useful. Group expansion is done on these names;
772 they may be in any of the user Id formats we can handle. The flags
773 bits for each string in the string list are used for:
774 Bit 0: This is an encrypt-to recipient.
775 Bit 1: This is a hidden recipient.
777 USE is the desired use for the key - usually PUBKEY_USAGE_ENC.
779 On success a list of keys is stored at the address RET_PK_LIST; the
780 caller must free this list. On error the value at this address is
781 not changed.
784 build_pk_list( strlist_t rcpts, PK_LIST *ret_pk_list, unsigned int use )
786 PK_LIST pk_list = NULL;
787 PKT_public_key *pk=NULL;
788 int rc=0;
789 int any_recipients=0;
790 strlist_t rov,remusr;
791 char *def_rec = NULL;
793 /* Try to expand groups if any have been defined. */
794 if (opt.grouplist)
795 remusr = expand_group (rcpts);
796 else
797 remusr = rcpts;
799 /* Check whether there are any recipients in the list and build the
800 * list of the encrypt-to ones (we always trust them). */
801 for ( rov = remusr; rov; rov = rov->next )
803 if ( !(rov->flags & 1) )
805 /* This is a regular recipient; i.e. not an encrypt-to
806 one. */
807 any_recipients = 1;
809 /* Hidden recipients are not allowed while in PGP mode,
810 issue a warning and switch into GnuPG mode. */
811 if ((rov->flags&2) && (PGP2 || PGP6 || PGP7 || PGP8))
813 log_info(_("you may not use %s while in %s mode\n"),
814 "--hidden-recipient",
815 compliance_option_string());
817 compliance_failure();
820 else if ( (use & PUBKEY_USAGE_ENC) && !opt.no_encrypt_to )
822 /* Encryption has been requested and --encrypt-to has not
823 been disabled. Check this encrypt-to key. */
824 pk = xmalloc_clear( sizeof *pk );
825 pk->req_usage = use;
827 /* We explicitly allow encrypt-to to an disabled key; thus
828 we pass 1for the second last argument and 1 as the last
829 argument to disable AKL. */
830 if ( (rc = get_pubkey_byname (NULL, pk, rov->d, NULL, NULL, 1, 1)) )
832 free_public_key ( pk ); pk = NULL;
833 log_error (_("%s: skipped: %s\n"), rov->d, g10_errstr(rc) );
834 write_status_text_and_buffer (STATUS_INV_RECP, "0 ",
835 rov->d, strlen (rov->d), -1);
836 goto fail;
838 else if ( !(rc=openpgp_pk_test_algo2 (pk->pubkey_algo, use)) )
840 /* Skip the actual key if the key is already present
841 * in the list. Add it to our list if not. */
842 if (key_present_in_pk_list(pk_list, pk) == 0)
844 free_public_key (pk); pk = NULL;
845 log_info (_("%s: skipped: public key already present\n"),
846 rov->d);
848 else
850 PK_LIST r;
851 r = xmalloc( sizeof *r );
852 r->pk = pk; pk = NULL;
853 r->next = pk_list;
854 r->flags = (rov->flags&2)?1:0;
855 pk_list = r;
857 /* Hidden encrypt-to recipients are not allowed while
858 in PGP mode, issue a warning and switch into
859 GnuPG mode. */
860 if ((r->flags&1) && (PGP2 || PGP6 || PGP7 || PGP8))
862 log_info(_("you may not use %s while in %s mode\n"),
863 "--hidden-encrypt-to",
864 compliance_option_string());
866 compliance_failure();
870 else
872 /* The public key is not usable for encryption or not
873 available. */
874 free_public_key( pk ); pk = NULL;
875 log_error(_("%s: skipped: %s\n"), rov->d, g10_errstr(rc) );
876 write_status_text_and_buffer (STATUS_INV_RECP, "0 ",
877 rov->d, strlen (rov->d), -1);
878 goto fail;
883 /* If we don't have any recipients yet and we are not in batch mode
884 drop into interactive selection mode. */
885 if ( !any_recipients && !opt.batch )
887 int have_def_rec;
888 char *answer = NULL;
889 strlist_t backlog = NULL;
891 if (pk_list)
892 any_recipients = 1;
893 def_rec = default_recipient();
894 have_def_rec = !!def_rec;
895 if ( !have_def_rec )
896 tty_printf(_("You did not specify a user ID. (you may use \"-r\")\n"));
898 for (;;)
900 rc = 0;
901 xfree(answer);
902 if ( have_def_rec )
904 /* A default recipient is taken as the first entry. */
905 answer = def_rec;
906 def_rec = NULL;
908 else if (backlog)
910 /* This is part of our trick to expand and display groups. */
911 answer = strlist_pop (&backlog);
913 else
915 /* Show the list of already collected recipients and ask
916 for more. */
917 PK_LIST iter;
919 tty_printf("\n");
920 tty_printf(_("Current recipients:\n"));
921 for (iter=pk_list;iter;iter=iter->next)
923 u32 keyid[2];
925 keyid_from_pk(iter->pk,keyid);
926 tty_printf("%4u%c/%s %s \"",
927 nbits_from_pk(iter->pk),
928 pubkey_letter(iter->pk->pubkey_algo),
929 keystr(keyid),
930 datestr_from_pk(iter->pk));
932 if (iter->pk->user_id)
933 tty_print_utf8_string(iter->pk->user_id->name,
934 iter->pk->user_id->len);
935 else
937 size_t n;
938 char *p = get_user_id( keyid, &n );
939 tty_print_utf8_string( p, n );
940 xfree(p);
942 tty_printf("\"\n");
945 answer = cpr_get_utf8("pklist.user_id.enter",
946 _("\nEnter the user ID. "
947 "End with an empty line: "));
948 trim_spaces(answer);
949 cpr_kill_prompt();
952 if ( !answer || !*answer )
954 xfree(answer);
955 break; /* No more recipients entered - get out of loop. */
958 /* Do group expand here too. The trick here is to continue
959 the loop if any expansion occured. The code above will
960 then list all expanded keys. */
961 if (expand_id(answer,&backlog,0))
962 continue;
964 /* Get and check key for the current name. */
965 if (pk)
966 free_public_key (pk);
967 pk = xmalloc_clear( sizeof *pk );
968 pk->req_usage = use;
969 rc = get_pubkey_byname (NULL, pk, answer, NULL, NULL, 0, 0 );
970 if (rc)
971 tty_printf(_("No such user ID.\n"));
972 else if ( !(rc=openpgp_pk_test_algo2 (pk->pubkey_algo, use)) )
974 if ( have_def_rec )
976 /* No validation for a default recipient. */
977 if (!key_present_in_pk_list(pk_list, pk))
979 free_public_key (pk); pk = NULL;
980 log_info (_("skipped: public key "
981 "already set as default recipient\n") );
983 else
985 PK_LIST r = xmalloc (sizeof *r);
986 r->pk = pk; pk = NULL;
987 r->next = pk_list;
988 r->flags = 0; /* No throwing default ids. */
989 pk_list = r;
991 any_recipients = 1;
992 continue;
994 else
995 { /* Check validity of this key. */
996 int trustlevel;
998 trustlevel = get_validity (pk, pk->user_id);
999 if ( (trustlevel & TRUST_FLAG_DISABLED) )
1001 tty_printf (_("Public key is disabled.\n") );
1003 else if ( do_we_trust_pre (pk, trustlevel) )
1005 /* Skip the actual key if the key is already
1006 * present in the list */
1007 if (!key_present_in_pk_list(pk_list, pk))
1009 free_public_key(pk); pk = NULL;
1010 log_info(_("skipped: public key already set\n") );
1012 else
1014 PK_LIST r;
1015 r = xmalloc( sizeof *r );
1016 r->pk = pk; pk = NULL;
1017 r->next = pk_list;
1018 r->flags = 0; /* No throwing interactive ids. */
1019 pk_list = r;
1021 any_recipients = 1;
1022 continue;
1026 xfree(def_rec); def_rec = NULL;
1027 have_def_rec = 0;
1029 if ( pk )
1031 free_public_key( pk );
1032 pk = NULL;
1035 else if ( !any_recipients && (def_rec = default_recipient()) )
1037 /* We are in batch mode and have only a default recipient. */
1038 pk = xmalloc_clear( sizeof *pk );
1039 pk->req_usage = use;
1041 /* The default recipient is allowed to be disabled; thus pass 1
1042 as second last argument. We also don't want an AKL. */
1043 rc = get_pubkey_byname (NULL, pk, def_rec, NULL, NULL, 1, 1);
1044 if (rc)
1045 log_error(_("unknown default recipient \"%s\"\n"), def_rec );
1046 else if ( !(rc=openpgp_pk_test_algo2(pk->pubkey_algo, use)) )
1048 /* Mark any_recipients here since the default recipient
1049 would have been used if it wasn't already there. It
1050 doesn't really matter if we got this key from the default
1051 recipient or an encrypt-to. */
1052 any_recipients = 1;
1053 if (!key_present_in_pk_list(pk_list, pk))
1054 log_info (_("skipped: public key already set "
1055 "as default recipient\n"));
1056 else
1058 PK_LIST r = xmalloc( sizeof *r );
1059 r->pk = pk; pk = NULL;
1060 r->next = pk_list;
1061 r->flags = 0; /* No throwing default ids. */
1062 pk_list = r;
1065 if ( pk )
1067 free_public_key( pk );
1068 pk = NULL;
1070 xfree(def_rec); def_rec = NULL;
1072 else
1074 /* General case: Check all keys. */
1075 any_recipients = 0;
1076 for (; remusr; remusr = remusr->next )
1078 if ( (remusr->flags & 1) )
1079 continue; /* encrypt-to keys are already handled. */
1081 pk = xmalloc_clear( sizeof *pk );
1082 pk->req_usage = use;
1083 if ((rc = get_pubkey_byname (NULL, pk, remusr->d, NULL, NULL, 0, 0)))
1085 /* Key not found or other error. */
1086 free_public_key( pk ); pk = NULL;
1087 log_error(_("%s: skipped: %s\n"), remusr->d, g10_errstr(rc) );
1088 write_status_text_and_buffer (STATUS_INV_RECP, "0 ",
1089 remusr->d, strlen (remusr->d),
1090 -1);
1091 goto fail;
1093 else if ( !(rc=openpgp_pk_test_algo2(pk->pubkey_algo, use )) )
1095 /* Key found and usable. Check validity. */
1096 int trustlevel;
1098 trustlevel = get_validity (pk, pk->user_id);
1099 if ( (trustlevel & TRUST_FLAG_DISABLED) )
1101 /*Key has been disabled. */
1102 free_public_key(pk); pk = NULL;
1103 log_info(_("%s: skipped: public key is disabled\n"),
1104 remusr->d);
1105 write_status_text_and_buffer (STATUS_INV_RECP, "0 ",
1106 remusr->d,
1107 strlen (remusr->d),
1108 -1);
1109 rc=G10ERR_UNU_PUBKEY;
1110 goto fail;
1112 else if ( do_we_trust_pre( pk, trustlevel ) )
1114 /* Note: do_we_trust may have changed the trustlevel */
1116 /* We have at least one valid recipient. It doesn't
1117 * matters if this recipient is already present. */
1118 any_recipients = 1;
1120 /* Skip the actual key if the key is already present
1121 * in the list */
1122 if (!key_present_in_pk_list(pk_list, pk))
1124 free_public_key(pk); pk = NULL;
1125 log_info(_("%s: skipped: public key already present\n"),
1126 remusr->d);
1128 else
1130 PK_LIST r;
1131 r = xmalloc( sizeof *r );
1132 r->pk = pk; pk = NULL;
1133 r->next = pk_list;
1134 r->flags = (remusr->flags&2)?1:0;
1135 pk_list = r;
1138 else
1139 { /* We don't trust this key. */
1140 free_public_key( pk ); pk = NULL;
1141 write_status_text_and_buffer (STATUS_INV_RECP, "10 ",
1142 remusr->d,
1143 strlen (remusr->d),
1144 -1);
1145 rc=G10ERR_UNU_PUBKEY;
1146 goto fail;
1149 else
1151 /* Key found but not usable for us (e.g. sign-only key). */
1152 free_public_key( pk ); pk = NULL;
1153 write_status_text_and_buffer (STATUS_INV_RECP, "0 ",
1154 remusr->d,
1155 strlen (remusr->d),
1156 -1);
1157 log_error(_("%s: skipped: %s\n"), remusr->d, g10_errstr(rc) );
1158 goto fail;
1163 if ( !rc && !any_recipients )
1165 log_error(_("no valid addressees\n"));
1166 write_status_text (STATUS_NO_RECP, "0");
1167 rc = G10ERR_NO_USER_ID;
1170 fail:
1172 if ( rc )
1173 release_pk_list( pk_list );
1174 else
1175 *ret_pk_list = pk_list;
1176 if (opt.grouplist)
1177 free_strlist(remusr);
1178 return rc;
1182 /* In pgp6 mode, disallow all ciphers except IDEA (1), 3DES (2), and
1183 CAST5 (3), all hashes except MD5 (1), SHA1 (2), and RIPEMD160 (3),
1184 and all compressions except none (0) and ZIP (1). pgp7 and pgp8
1185 mode expands the cipher list to include AES128 (7), AES192 (8),
1186 AES256 (9), and TWOFISH (10). pgp8 adds the SHA-256 hash (8). For
1187 a true PGP key all of this is unneeded as they are the only items
1188 present in the preferences subpacket, but checking here covers the
1189 weird case of encrypting to a key that had preferences from a
1190 different implementation which was then used with PGP. I am not
1191 completely comfortable with this as the right thing to do, as it
1192 slightly alters the list of what the user is supposedly requesting.
1193 It is not against the RFC however, as the preference chosen will
1194 never be one that the user didn't specify somewhere ("The
1195 implementation may use any mechanism to pick an algorithm in the
1196 intersection"), and PGP has no mechanism to fix such a broken
1197 preference list, so I'm including it. -dms */
1200 algo_available( preftype_t preftype, int algo, const union pref_hint *hint)
1202 if( preftype == PREFTYPE_SYM )
1204 if(PGP6 && (algo != CIPHER_ALGO_IDEA
1205 && algo != CIPHER_ALGO_3DES
1206 && algo != CIPHER_ALGO_CAST5))
1207 return 0;
1209 if(PGP7 && (algo != CIPHER_ALGO_IDEA
1210 && algo != CIPHER_ALGO_3DES
1211 && algo != CIPHER_ALGO_CAST5
1212 && algo != CIPHER_ALGO_AES
1213 && algo != CIPHER_ALGO_AES192
1214 && algo != CIPHER_ALGO_AES256
1215 && algo != CIPHER_ALGO_TWOFISH))
1216 return 0;
1218 /* PGP8 supports all the ciphers we do.. */
1220 return algo && !openpgp_cipher_test_algo ( algo );
1222 else if( preftype == PREFTYPE_HASH )
1224 if (hint && hint->digest_length)
1226 if (hint->digest_length!=20 || opt.flags.dsa2)
1228 /* If --enable-dsa2 is set or the hash isn't 160 bits
1229 (which implies DSA2), then we'll accept a hash that
1230 is larger than we need. Otherwise we won't accept
1231 any hash that isn't exactly the right size. */
1232 if (hint->digest_length > gcry_md_get_algo_dlen (algo))
1233 return 0;
1235 else if (hint->digest_length != gcry_md_get_algo_dlen (algo))
1236 return 0;
1239 if((PGP6 || PGP7) && (algo != DIGEST_ALGO_MD5
1240 && algo != DIGEST_ALGO_SHA1
1241 && algo != DIGEST_ALGO_RMD160))
1242 return 0;
1245 if(PGP8 && (algo != DIGEST_ALGO_MD5
1246 && algo != DIGEST_ALGO_SHA1
1247 && algo != DIGEST_ALGO_RMD160
1248 && algo != DIGEST_ALGO_SHA256))
1249 return 0;
1251 return algo && !openpgp_md_test_algo (algo);
1253 else if( preftype == PREFTYPE_ZIP )
1255 if((PGP6 || PGP7) && (algo != COMPRESS_ALGO_NONE
1256 && algo != COMPRESS_ALGO_ZIP))
1257 return 0;
1259 /* PGP8 supports all the compression algos we do */
1261 return !check_compress_algo( algo );
1263 else
1264 return 0;
1267 /****************
1268 * Return -1 if we could not find an algorithm.
1271 select_algo_from_prefs(PK_LIST pk_list, int preftype,
1272 int request, const union pref_hint *hint)
1274 PK_LIST pkr;
1275 u32 bits[8];
1276 const prefitem_t *prefs;
1277 int result=-1,i;
1278 unsigned int best=-1;
1279 byte scores[256];
1281 if( !pk_list )
1282 return -1;
1284 memset(bits,0xFF,sizeof(bits));
1285 memset(scores,0,sizeof(scores));
1287 for( pkr = pk_list; pkr; pkr = pkr->next )
1289 u32 mask[8];
1290 int rank=1,implicit=-1;
1292 memset(mask,0,sizeof(mask));
1294 switch(preftype)
1296 case PREFTYPE_SYM:
1297 /* IDEA is implicitly there for v3 keys with v3 selfsigs if
1298 --pgp2 mode is on. This was a 2440 thing that was
1299 dropped from 4880 but is still relevant to GPG's 1991
1300 support. All this doesn't mean IDEA is actually
1301 available, of course. */
1302 if(PGP2 && pkr->pk->version<4 && pkr->pk->selfsigversion<4)
1303 implicit=CIPHER_ALGO_IDEA;
1304 else
1305 implicit=CIPHER_ALGO_3DES;
1307 break;
1309 case PREFTYPE_HASH:
1310 /* While I am including this code for completeness, note
1311 that currently --pgp2 mode locks the hash at MD5, so this
1312 code will never even be called. Even if the hash wasn't
1313 locked at MD5, we don't support sign+encrypt in --pgp2
1314 mode, and that's the only time PREFTYPE_HASH is used
1315 anyway. -dms */
1317 /* MD5 is there for v3 keys with v3 selfsigs when --pgp2 is
1318 on. */
1319 if(PGP2 && pkr->pk->version<4 && pkr->pk->selfsigversion<4)
1320 implicit=DIGEST_ALGO_MD5;
1321 else
1322 implicit=DIGEST_ALGO_SHA1;
1324 break;
1326 case PREFTYPE_ZIP:
1327 /* Uncompressed is always an option. */
1328 implicit=COMPRESS_ALGO_NONE;
1331 if (pkr->pk->user_id) /* selected by user ID */
1332 prefs = pkr->pk->user_id->prefs;
1333 else
1334 prefs = pkr->pk->prefs;
1336 if( prefs )
1338 for (i=0; prefs[i].type; i++ )
1340 if( prefs[i].type == preftype )
1342 scores[prefs[i].value]+=rank;
1343 mask[prefs[i].value/32] |= 1<<(prefs[i].value%32);
1345 rank++;
1347 /* We saw the implicit algorithm, so we don't need
1348 tack it on the end ourselves. */
1349 if(implicit==prefs[i].value)
1350 implicit=-1;
1355 if(rank==1 && preftype==PREFTYPE_ZIP)
1357 /* If the compression preferences are not present, they are
1358 assumed to be ZIP, Uncompressed (RFC4880:13.3.1) */
1359 scores[1]=1; /* ZIP is first choice */
1360 scores[0]=2; /* Uncompressed is second choice */
1361 mask[0]|=3;
1364 /* If the key didn't have the implicit algorithm listed
1365 explicitly, add it here at the tail of the list. */
1366 if(implicit>-1)
1368 scores[implicit]+=rank;
1369 mask[implicit/32] |= 1<<(implicit%32);
1372 for(i=0;i<8;i++)
1373 bits[i]&=mask[i];
1376 /* We've now scored all of the algorithms, and the usable ones have
1377 bits set. Let's pick the winner. */
1379 /* The caller passed us a request. Can we use it? */
1380 if(request>-1 && (bits[request/32] & (1<<(request%32))) &&
1381 algo_available(preftype,request,hint))
1382 result=request;
1384 if(result==-1)
1386 /* If we have personal prefs set, use them. */
1387 prefs=NULL;
1388 if(preftype==PREFTYPE_SYM && opt.personal_cipher_prefs)
1389 prefs=opt.personal_cipher_prefs;
1390 else if(preftype==PREFTYPE_HASH && opt.personal_digest_prefs)
1391 prefs=opt.personal_digest_prefs;
1392 else if(preftype==PREFTYPE_ZIP && opt.personal_compress_prefs)
1393 prefs=opt.personal_compress_prefs;
1395 if( prefs )
1396 for(i=0; prefs[i].type; i++ )
1398 if(bits[prefs[i].value/32] & (1<<(prefs[i].value%32))
1399 && algo_available( preftype, prefs[i].value, hint))
1401 result = prefs[i].value;
1402 break;
1407 if(result==-1)
1409 /* At this point, we have not selected an algorithm due to a
1410 special request or via personal prefs. Pick the highest
1411 ranked algorithm (i.e. the one with the lowest score). */
1413 for(i=0;i<256;i++)
1415 /* Note the '<' here. This means in case of a tie, we will
1416 favor the lower algorithm number. We have a choice
1417 between the lower number (probably an older algorithm
1418 with more time in use), or the higher number (probably a
1419 newer algorithm with less time in use). Older is
1420 probably safer here, even though the newer algorithms
1421 tend to be "stronger". */
1422 if(scores[i] && scores[i]<best
1423 && (bits[i/32] & (1<<(i%32)))
1424 && algo_available(preftype,i,hint))
1426 best=scores[i];
1427 result=i;
1431 /* "If you are building an authentication system, the recipient
1432 may specify a preferred signing algorithm. However, the
1433 signer would be foolish to use a weak algorithm simply
1434 because the recipient requests it." (RFC4880:14). If we
1435 settle on MD5, and SHA1 is also available, use SHA1 instead.
1436 Note that if the user intentionally chose MD5 by putting it
1437 in their personal prefs, then we do what the user said (as we
1438 never reach this code). */
1439 if(preftype==PREFTYPE_HASH && result==DIGEST_ALGO_MD5
1440 && (bits[0] & (1<<DIGEST_ALGO_SHA1)))
1441 result=DIGEST_ALGO_SHA1;
1444 return result;
1448 * Select the MDC flag from the pk_list. We can only use MDC if all
1449 * recipients support this feature.
1452 select_mdc_from_pklist (PK_LIST pk_list)
1454 PK_LIST pkr;
1456 if ( !pk_list )
1457 return 0;
1459 for (pkr = pk_list; pkr; pkr = pkr->next)
1461 int mdc;
1463 if (pkr->pk->user_id) /* selected by user ID */
1464 mdc = pkr->pk->user_id->flags.mdc;
1465 else
1466 mdc = pkr->pk->mdc_feature;
1467 if (!mdc)
1468 return 0; /* At least one recipient does not support it. */
1470 return 1; /* Can be used. */
1474 /* Print a warning for all keys in PK_LIST missing the MDC feature. */
1475 void
1476 warn_missing_mdc_from_pklist (PK_LIST pk_list)
1478 PK_LIST pkr;
1480 for (pkr = pk_list; pkr; pkr = pkr->next)
1482 int mdc;
1484 if (pkr->pk->user_id) /* selected by user ID */
1485 mdc = pkr->pk->user_id->flags.mdc;
1486 else
1487 mdc = pkr->pk->mdc_feature;
1488 if (!mdc)
1489 log_info (_("Note: key %s has no %s feature\n"),
1490 keystr_from_pk (pkr->pk), "MDC");
1494 void
1495 warn_missing_aes_from_pklist (PK_LIST pk_list)
1497 PK_LIST pkr;
1499 for (pkr = pk_list; pkr; pkr = pkr->next)
1501 const prefitem_t *prefs;
1502 int i;
1503 int gotit = 0;
1505 prefs = pkr->pk->user_id? pkr->pk->user_id->prefs : pkr->pk->prefs;
1506 if (prefs)
1508 for (i=0; !gotit && prefs[i].type; i++ )
1509 if (prefs[i].type == PREFTYPE_SYM
1510 && prefs[i].value == CIPHER_ALGO_AES)
1511 gotit++;
1513 if (!gotit)
1514 log_info (_("Note: key %s has no preference for %s\n"),
1515 keystr_from_pk (pkr->pk), "AES");