agent/
[gnupg.git] / g10 / getkey.c
blob54843cfb2f081f1bda8302c130da313140d774da
1 /* getkey.c - Get a key from the database
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3 * 2007, 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 <assert.h>
26 #include <ctype.h>
28 #include "gpg.h"
29 #include "util.h"
30 #include "packet.h"
31 #include "iobuf.h"
32 #include "keydb.h"
33 #include "options.h"
34 #include "main.h"
35 #include "trustdb.h"
36 #include "i18n.h"
37 #include "keyserver-internal.h"
39 #define MAX_PK_CACHE_ENTRIES PK_UID_CACHE_SIZE
40 #define MAX_UID_CACHE_ENTRIES PK_UID_CACHE_SIZE
42 #if MAX_PK_CACHE_ENTRIES < 2
43 #error We need the cache for key creation
44 #endif
46 struct getkey_ctx_s {
47 int exact;
48 KBNODE keyblock;
49 KBPOS kbpos;
50 KBNODE found_key; /* Pointer into some keyblock. */
51 strlist_t extra_list; /* Will be freed when releasing the context. */
52 int last_rc;
53 int req_usage;
54 int req_algo;
55 KEYDB_HANDLE kr_handle;
56 int not_allocated;
57 int nitems;
58 KEYDB_SEARCH_DESC items[1];
61 #if 0
62 static struct {
63 int any;
64 int okay_count;
65 int nokey_count;
66 int error_count;
67 } lkup_stats[21];
68 #endif
70 typedef struct keyid_list {
71 struct keyid_list *next;
72 u32 keyid[2];
73 } *keyid_list_t;
76 #if MAX_PK_CACHE_ENTRIES
77 typedef struct pk_cache_entry {
78 struct pk_cache_entry *next;
79 u32 keyid[2];
80 PKT_public_key *pk;
81 } *pk_cache_entry_t;
82 static pk_cache_entry_t pk_cache;
83 static int pk_cache_entries; /* number of entries in pk cache */
84 static int pk_cache_disabled;
85 #endif
87 #if MAX_UID_CACHE_ENTRIES < 5
88 #error we really need the userid cache
89 #endif
90 typedef struct user_id_db {
91 struct user_id_db *next;
92 keyid_list_t keyids;
93 int len;
94 char name[1];
95 } *user_id_db_t;
96 static user_id_db_t user_id_db;
97 static int uid_cache_entries; /* number of entries in uid cache */
99 static void merge_selfsigs( KBNODE keyblock );
100 static int lookup( GETKEY_CTX ctx, KBNODE *ret_keyblock, int secmode );
102 #if 0
103 static void
104 print_stats()
106 int i;
107 for(i=0; i < DIM(lkup_stats); i++ ) {
108 if( lkup_stats[i].any )
109 fprintf(stderr,
110 "lookup stats: mode=%-2d ok=%-6d nokey=%-6d err=%-6d\n",
112 lkup_stats[i].okay_count,
113 lkup_stats[i].nokey_count,
114 lkup_stats[i].error_count );
117 #endif
120 void
121 cache_public_key( PKT_public_key *pk )
123 #if MAX_PK_CACHE_ENTRIES
124 pk_cache_entry_t ce;
125 u32 keyid[2];
127 if( pk_cache_disabled )
128 return;
130 if( pk->dont_cache )
131 return;
133 if( is_ELGAMAL(pk->pubkey_algo)
134 || pk->pubkey_algo == PUBKEY_ALGO_DSA
135 || is_RSA(pk->pubkey_algo) ) {
136 keyid_from_pk( pk, keyid );
138 else
139 return; /* don't know how to get the keyid */
141 for( ce = pk_cache; ce; ce = ce->next )
142 if( ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1] ) {
143 if( DBG_CACHE )
144 log_debug("cache_public_key: already in cache\n");
145 return;
148 if( pk_cache_entries >= MAX_PK_CACHE_ENTRIES ) {
149 /* fixme: use another algorithm to free some cache slots */
150 pk_cache_disabled=1;
151 if( opt.verbose > 1 )
152 log_info(_("too many entries in pk cache - disabled\n"));
153 return;
155 pk_cache_entries++;
156 ce = xmalloc( sizeof *ce );
157 ce->next = pk_cache;
158 pk_cache = ce;
159 ce->pk = copy_public_key( NULL, pk );
160 ce->keyid[0] = keyid[0];
161 ce->keyid[1] = keyid[1];
162 #endif
166 /* Return a const utf-8 string with the text "[User ID not found]".
167 This fucntion is required so that we don't need to switch gettext's
168 encoding temporary. */
169 static const char *
170 user_id_not_found_utf8 (void)
172 static char *text;
174 if (!text)
175 text = native_to_utf8 (_("[User ID not found]"));
176 return text;
182 * Return the user ID from the given keyblock.
183 * We use the primary uid flag which has been set by the merge_selfsigs
184 * function. The returned value is only valid as long as then given
185 * keyblock is not changed
187 static const char *
188 get_primary_uid ( KBNODE keyblock, size_t *uidlen )
190 KBNODE k;
191 const char *s;
193 for (k=keyblock; k; k=k->next ) {
194 if ( k->pkt->pkttype == PKT_USER_ID
195 && !k->pkt->pkt.user_id->attrib_data
196 && k->pkt->pkt.user_id->is_primary ) {
197 *uidlen = k->pkt->pkt.user_id->len;
198 return k->pkt->pkt.user_id->name;
201 s = user_id_not_found_utf8 ();
202 *uidlen = strlen (s);
203 return s;
207 static void
208 release_keyid_list ( keyid_list_t k )
210 while ( k ) {
211 keyid_list_t k2 = k->next;
212 xfree (k);
213 k = k2;
217 /****************
218 * Store the association of keyid and userid
219 * Feed only public keys to this function.
221 static void
222 cache_user_id( KBNODE keyblock )
224 user_id_db_t r;
225 const char *uid;
226 size_t uidlen;
227 keyid_list_t keyids = NULL;
228 KBNODE k;
230 for (k=keyblock; k; k = k->next ) {
231 if ( k->pkt->pkttype == PKT_PUBLIC_KEY
232 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
233 keyid_list_t a = xmalloc_clear ( sizeof *a );
234 /* Hmmm: For a long list of keyids it might be an advantage
235 * to append the keys */
236 keyid_from_pk( k->pkt->pkt.public_key, a->keyid );
237 /* first check for duplicates */
238 for(r=user_id_db; r; r = r->next ) {
239 keyid_list_t b = r->keyids;
240 for ( b = r->keyids; b; b = b->next ) {
241 if( b->keyid[0] == a->keyid[0]
242 && b->keyid[1] == a->keyid[1] ) {
243 if( DBG_CACHE )
244 log_debug("cache_user_id: already in cache\n");
245 release_keyid_list ( keyids );
246 xfree ( a );
247 return;
251 /* now put it into the cache */
252 a->next = keyids;
253 keyids = a;
256 if ( !keyids )
257 BUG (); /* No key no fun */
260 uid = get_primary_uid ( keyblock, &uidlen );
262 if( uid_cache_entries >= MAX_UID_CACHE_ENTRIES ) {
263 /* fixme: use another algorithm to free some cache slots */
264 r = user_id_db;
265 user_id_db = r->next;
266 release_keyid_list ( r->keyids );
267 xfree(r);
268 uid_cache_entries--;
270 r = xmalloc( sizeof *r + uidlen-1 );
271 r->keyids = keyids;
272 r->len = uidlen;
273 memcpy(r->name, uid, r->len);
274 r->next = user_id_db;
275 user_id_db = r;
276 uid_cache_entries++;
280 void
281 getkey_disable_caches()
283 #if MAX_PK_CACHE_ENTRIES
285 pk_cache_entry_t ce, ce2;
287 for( ce = pk_cache; ce; ce = ce2 ) {
288 ce2 = ce->next;
289 free_public_key( ce->pk );
290 xfree( ce );
292 pk_cache_disabled=1;
293 pk_cache_entries = 0;
294 pk_cache = NULL;
296 #endif
297 /* fixme: disable user id cache ? */
301 static void
302 pk_from_block ( GETKEY_CTX ctx, PKT_public_key *pk, KBNODE keyblock )
304 KBNODE a = ctx->found_key ? ctx->found_key : keyblock;
306 assert ( a->pkt->pkttype == PKT_PUBLIC_KEY
307 || a->pkt->pkttype == PKT_PUBLIC_SUBKEY );
309 copy_public_key ( pk, a->pkt->pkt.public_key );
312 static void
313 sk_from_block ( GETKEY_CTX ctx,
314 PKT_secret_key *sk, KBNODE keyblock )
316 KBNODE a = ctx->found_key ? ctx->found_key : keyblock;
318 assert ( a->pkt->pkttype == PKT_SECRET_KEY
319 || a->pkt->pkttype == PKT_SECRET_SUBKEY );
321 copy_secret_key( sk, a->pkt->pkt.secret_key);
325 /****************
326 * Get a public key and store it into the allocated pk
327 * can be called with PK set to NULL to just read it into some
328 * internal structures.
331 get_pubkey( PKT_public_key *pk, u32 *keyid )
333 int internal = 0;
334 int rc = 0;
336 #if MAX_PK_CACHE_ENTRIES
337 if(pk)
339 /* Try to get it from the cache. We don't do this when pk is
340 NULL as it does not guarantee that the user IDs are
341 cached. */
342 pk_cache_entry_t ce;
343 for( ce = pk_cache; ce; ce = ce->next )
345 if( ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1] )
347 copy_public_key( pk, ce->pk );
348 return 0;
352 #endif
353 /* more init stuff */
354 if( !pk ) {
355 pk = xmalloc_clear( sizeof *pk );
356 internal++;
360 /* do a lookup */
361 { struct getkey_ctx_s ctx;
362 KBNODE kb = NULL;
363 memset( &ctx, 0, sizeof ctx );
364 ctx.exact = 1; /* use the key ID exactly as given */
365 ctx.not_allocated = 1;
366 ctx.kr_handle = keydb_new (0);
367 ctx.nitems = 1;
368 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
369 ctx.items[0].u.kid[0] = keyid[0];
370 ctx.items[0].u.kid[1] = keyid[1];
371 ctx.req_algo = pk->req_algo;
372 ctx.req_usage = pk->req_usage;
373 rc = lookup( &ctx, &kb, 0 );
374 if ( !rc ) {
375 pk_from_block ( &ctx, pk, kb );
377 get_pubkey_end( &ctx );
378 release_kbnode ( kb );
380 if( !rc )
381 goto leave;
383 rc = G10ERR_NO_PUBKEY;
385 leave:
386 if( !rc )
387 cache_public_key( pk );
388 if( internal )
389 free_public_key(pk);
390 return rc;
394 /* Get a public key and store it into the allocated pk. This function
395 differs from get_pubkey() in that it does not do a check of the key
396 to avoid recursion. It should be used only in very certain cases.
397 It will only retrieve primary keys. */
399 get_pubkey_fast (PKT_public_key *pk, u32 *keyid)
401 int rc = 0;
402 KEYDB_HANDLE hd;
403 KBNODE keyblock;
404 u32 pkid[2];
406 assert (pk);
407 #if MAX_PK_CACHE_ENTRIES
408 { /* Try to get it from the cache */
409 pk_cache_entry_t ce;
411 for (ce = pk_cache; ce; ce = ce->next)
413 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
415 if (pk)
416 copy_public_key (pk, ce->pk);
417 return 0;
421 #endif
423 hd = keydb_new (0);
424 rc = keydb_search_kid (hd, keyid);
425 if (rc == -1)
427 keydb_release (hd);
428 return G10ERR_NO_PUBKEY;
430 rc = keydb_get_keyblock (hd, &keyblock);
431 keydb_release (hd);
432 if (rc)
434 log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
435 return G10ERR_NO_PUBKEY;
438 assert ( keyblock->pkt->pkttype == PKT_PUBLIC_KEY
439 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY );
441 keyid_from_pk(keyblock->pkt->pkt.public_key,pkid);
442 if(keyid[0]==pkid[0] && keyid[1]==pkid[1])
443 copy_public_key (pk, keyblock->pkt->pkt.public_key );
444 else
445 rc=G10ERR_NO_PUBKEY;
447 release_kbnode (keyblock);
449 /* Not caching key here since it won't have all of the fields
450 properly set. */
452 return rc;
456 KBNODE
457 get_pubkeyblock( u32 *keyid )
459 struct getkey_ctx_s ctx;
460 int rc = 0;
461 KBNODE keyblock = NULL;
463 memset( &ctx, 0, sizeof ctx );
464 /* no need to set exact here because we want the entire block */
465 ctx.not_allocated = 1;
466 ctx.kr_handle = keydb_new (0);
467 ctx.nitems = 1;
468 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
469 ctx.items[0].u.kid[0] = keyid[0];
470 ctx.items[0].u.kid[1] = keyid[1];
471 rc = lookup( &ctx, &keyblock, 0 );
472 get_pubkey_end( &ctx );
474 return rc ? NULL : keyblock;
480 /****************
481 * Get a secret key and store it into sk
484 get_seckey( PKT_secret_key *sk, u32 *keyid )
486 int rc;
487 struct getkey_ctx_s ctx;
488 KBNODE kb = NULL;
490 memset( &ctx, 0, sizeof ctx );
491 ctx.exact = 1; /* use the key ID exactly as given */
492 ctx.not_allocated = 1;
493 ctx.kr_handle = keydb_new (1);
494 ctx.nitems = 1;
495 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
496 ctx.items[0].u.kid[0] = keyid[0];
497 ctx.items[0].u.kid[1] = keyid[1];
498 ctx.req_algo = sk->req_algo;
499 ctx.req_usage = sk->req_usage;
500 rc = lookup( &ctx, &kb, 1 );
501 if ( !rc ) {
502 sk_from_block ( &ctx, sk, kb );
504 get_seckey_end( &ctx );
505 release_kbnode ( kb );
507 if( !rc ) {
508 /* check the secret key (this may prompt for a passprase to
509 * unlock the secret key
511 rc = check_secret_key( sk, 0 );
514 return rc;
518 /****************
519 * Check whether the secret key is available. This is just a fast
520 * check and does not tell us whether the secret key is valid. It
521 * merely tells other whether there is some secret key.
522 * Returns: 0 := key is available
523 * G10ERR_NO_SECKEY := not availabe
526 seckey_available( u32 *keyid )
528 int rc;
529 KEYDB_HANDLE hd = keydb_new (1);
531 rc = keydb_search_kid (hd, keyid);
532 if ( rc == -1 )
533 rc = G10ERR_NO_SECKEY;
534 keydb_release (hd);
535 return rc;
539 /****************
540 * Return the type of the user id:
542 * Please use the constants KEYDB_SERCH_MODE_xxx
543 * 0 = Invalid user ID
544 * 1 = exact match
545 * 2 = match a substring
546 * 3 = match an email address
547 * 4 = match a substring of an email address
548 * 5 = match an email address, but compare from end
549 * 6 = word match mode
550 * 10 = it is a short KEYID (don't care about keyid[0])
551 * 11 = it is a long KEYID
552 * 12 = it is a trustdb index (keyid is looked up)
553 * 16 = it is a 16 byte fingerprint
554 * 20 = it is a 20 byte fingerprint
555 * 21 = Unified fingerprint :fpr:pk_algo:
556 * (We don't use pk_algo yet)
558 * Rules used:
559 * - If the username starts with 8,9,16 or 17 hex-digits (the first one
560 * must be in the range 0..9), this is considered a keyid; depending
561 * on the length a short or complete one.
562 * - If the username starts with 32,33,40 or 41 hex-digits (the first one
563 * must be in the range 0..9), this is considered a fingerprint.
564 * - If the username starts with a left angle, we assume it is a complete
565 * email address and look only at this part.
566 * - If the username starts with a colon we assume it is a unified
567 * key specfification.
568 * - If the username starts with a '.', we assume it is the ending
569 * part of an email address
570 * - If the username starts with an '@', we assume it is a part of an
571 * email address
572 * - If the userid start with an '=' an exact compare is done.
573 * - If the userid starts with a '*' a case insensitive substring search is
574 * done (This is the default).
575 * - If the userid starts with a '+' we will compare individual words
576 * and a match requires that all the words are in the userid.
577 * Words are delimited by white space or "()<>[]{}.@-+_,;/&!"
578 * (note that you can't search for these characters). Compare
579 * is not case sensitive.
580 * - If the userid starts with a '&' a 40 hex digits keygrip is expected.
584 classify_user_id( const char *name, KEYDB_SEARCH_DESC *desc )
586 const char *s;
587 int hexprefix = 0;
588 int hexlength;
589 int mode = 0;
590 KEYDB_SEARCH_DESC dummy_desc;
592 if (!desc)
593 desc = &dummy_desc;
595 /* clear the structure so that the mode field is set to zero unless
596 * we set it to the correct value right at the end of this function */
597 memset (desc, 0, sizeof *desc);
599 /* skip leading spaces. Fixme: what is with trailing spaces? */
600 for(s = name; *s && spacep (s); s++ )
603 switch (*s) {
604 case 0: /* empty string is an error */
605 return 0;
607 #if 0
608 case '.': /* an email address, compare from end */
609 mode = KEYDB_SEARCH_MODE_MAILEND;
610 s++;
611 desc->u.name = s;
612 break;
613 #endif
615 case '<': /* an email address */
616 mode = KEYDB_SEARCH_MODE_MAIL;
617 desc->u.name = s;
618 break;
620 case '@': /* part of an email address */
621 mode = KEYDB_SEARCH_MODE_MAILSUB;
622 s++;
623 desc->u.name = s;
624 break;
626 case '=': /* exact compare */
627 mode = KEYDB_SEARCH_MODE_EXACT;
628 s++;
629 desc->u.name = s;
630 break;
632 case '*': /* case insensitive substring search */
633 mode = KEYDB_SEARCH_MODE_SUBSTR;
634 s++;
635 desc->u.name = s;
636 break;
638 #if 0
639 case '+': /* compare individual words */
640 mode = KEYDB_SEARCH_MODE_WORDS;
641 s++;
642 desc->u.name = s;
643 break;
644 #endif
646 case '#': /* local user id */
647 return 0; /* This is now obsolete and can't not be used anymore*/
649 case ':': /*Unified fingerprint */
651 const char *se, *si;
652 int i;
654 se = strchr( ++s,':');
655 if ( !se )
656 return 0;
657 for (i=0,si=s; si < se; si++, i++ ) {
658 if ( !strchr("01234567890abcdefABCDEF", *si ) )
659 return 0; /* invalid digit */
661 if (i != 32 && i != 40)
662 return 0; /* invalid length of fpr*/
663 for (i=0,si=s; si < se; i++, si +=2)
664 desc->u.fpr[i] = hextobyte(si);
665 for ( ; i < 20; i++)
666 desc->u.fpr[i]= 0;
667 s = se + 1;
668 mode = KEYDB_SEARCH_MODE_FPR;
670 break;
672 case '&': /* keygrip */
673 return 0; /* Not yet implememted. */
675 default:
676 if (s[0] == '0' && s[1] == 'x') {
677 hexprefix = 1;
678 s += 2;
681 hexlength = strspn(s, "0123456789abcdefABCDEF");
682 if (hexlength >= 8 && s[hexlength] =='!') {
683 desc->exact = 1;
684 hexlength++; /* just for the following check */
687 /* check if a hexadecimal number is terminated by EOS or blank */
688 if (hexlength && s[hexlength] && !spacep(s+hexlength)) {
689 if (hexprefix) /* a "0x" prefix without correct */
690 return 0; /* termination is an error */
691 else /* The first chars looked like */
692 hexlength = 0; /* a hex number, but really were not. */
695 if (desc->exact)
696 hexlength--;
698 if (hexlength == 8
699 || (!hexprefix && hexlength == 9 && *s == '0')){
700 /* short keyid */
701 if (hexlength == 9)
702 s++;
703 desc->u.kid[0] = 0;
704 desc->u.kid[1] = strtoul( s, NULL, 16 );
705 mode = KEYDB_SEARCH_MODE_SHORT_KID;
707 else if (hexlength == 16
708 || (!hexprefix && hexlength == 17 && *s == '0')) {
709 /* complete keyid */
710 char buf[9];
711 if (hexlength == 17)
712 s++;
713 mem2str(buf, s, 9 );
714 desc->u.kid[0] = strtoul( buf, NULL, 16 );
715 desc->u.kid[1] = strtoul( s+8, NULL, 16 );
716 mode = KEYDB_SEARCH_MODE_LONG_KID;
718 else if (hexlength == 32 || (!hexprefix && hexlength == 33
719 && *s == '0')) {
720 /* md5 fingerprint */
721 int i;
722 if (hexlength == 33)
723 s++;
724 memset(desc->u.fpr+16, 0, 4);
725 for (i=0; i < 16; i++, s+=2) {
726 int c = hextobyte(s);
727 if (c == -1)
728 return 0;
729 desc->u.fpr[i] = c;
731 mode = KEYDB_SEARCH_MODE_FPR16;
733 else if (hexlength == 40 || (!hexprefix && hexlength == 41
734 && *s == '0')) {
735 /* sha1/rmd160 fingerprint */
736 int i;
737 if (hexlength == 41)
738 s++;
739 for (i=0; i < 20; i++, s+=2) {
740 int c = hextobyte(s);
741 if (c == -1)
742 return 0;
743 desc->u.fpr[i] = c;
745 mode = KEYDB_SEARCH_MODE_FPR20;
747 else {
748 if (hexprefix) /* This was a hex number with a prefix */
749 return 0; /* and a wrong length */
751 desc->exact = 0;
752 desc->u.name = s;
753 mode = KEYDB_SEARCH_MODE_SUBSTR; /* default mode */
757 desc->mode = mode;
758 return mode;
762 static int
763 skip_unusable (void *dummy, u32 *keyid, PKT_user_id *uid)
765 int unusable=0;
766 KBNODE keyblock;
768 (void)dummy;
770 keyblock=get_pubkeyblock(keyid);
771 if(!keyblock)
773 log_error("error checking usability status of %s\n",keystr(keyid));
774 goto leave;
777 /* Is the user ID in question revoked/expired? */
778 if(uid)
780 KBNODE node;
782 for(node=keyblock;node;node=node->next)
784 if(node->pkt->pkttype==PKT_USER_ID)
786 if(cmp_user_ids(uid,node->pkt->pkt.user_id)==0
787 && (node->pkt->pkt.user_id->is_revoked
788 || node->pkt->pkt.user_id->is_expired))
790 unusable=1;
791 break;
797 if(!unusable)
798 unusable=pk_is_disabled(keyblock->pkt->pkt.public_key);
800 leave:
801 release_kbnode(keyblock);
802 return unusable;
805 /****************
806 * Try to get the pubkey by the userid. This function looks for the
807 * first pubkey certificate which has the given name in a user_id. if
808 * pk/sk has the pubkey algo set, the function will only return a
809 * pubkey with that algo. If namelist is NULL, the first key is
810 * returned. The caller should provide storage for either the pk or
811 * the sk. If ret_kb is not NULL the function will return the
812 * keyblock there.
815 static int
816 key_byname( GETKEY_CTX *retctx, strlist_t namelist,
817 PKT_public_key *pk, PKT_secret_key *sk,
818 int secmode, int include_unusable,
819 KBNODE *ret_kb, KEYDB_HANDLE *ret_kdbhd )
821 int rc = 0;
822 int n;
823 strlist_t r;
824 GETKEY_CTX ctx;
825 KBNODE help_kb = NULL;
827 if( retctx ) {/* reset the returned context in case of error */
828 assert (!ret_kdbhd); /* not allowed because the handle is
829 stored in the context */
830 *retctx = NULL;
832 if (ret_kdbhd)
833 *ret_kdbhd = NULL;
835 if(!namelist)
837 ctx = xmalloc_clear (sizeof *ctx);
838 ctx->nitems = 1;
839 ctx->items[0].mode=KEYDB_SEARCH_MODE_FIRST;
840 if(!include_unusable)
841 ctx->items[0].skipfnc=skip_unusable;
843 else
845 /* build the search context */
846 for(n=0, r=namelist; r; r = r->next )
847 n++;
849 ctx = xmalloc_clear (sizeof *ctx + (n-1)*sizeof ctx->items );
850 ctx->nitems = n;
852 for(n=0, r=namelist; r; r = r->next, n++ )
854 classify_user_id (r->d, &ctx->items[n]);
856 if (ctx->items[n].exact)
857 ctx->exact = 1;
858 if (!ctx->items[n].mode)
860 xfree (ctx);
861 return G10ERR_INV_USER_ID;
863 if(!include_unusable
864 && ctx->items[n].mode!=KEYDB_SEARCH_MODE_SHORT_KID
865 && ctx->items[n].mode!=KEYDB_SEARCH_MODE_LONG_KID
866 && ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR16
867 && ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR20
868 && ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR)
869 ctx->items[n].skipfnc=skip_unusable;
873 ctx->kr_handle = keydb_new (secmode);
874 if ( !ret_kb )
875 ret_kb = &help_kb;
877 if( secmode ) {
878 if (sk) {
879 ctx->req_algo = sk->req_algo;
880 ctx->req_usage = sk->req_usage;
882 rc = lookup( ctx, ret_kb, 1 );
883 if ( !rc && sk ) {
884 sk_from_block ( ctx, sk, *ret_kb );
887 else {
888 if (pk) {
889 ctx->req_algo = pk->req_algo;
890 ctx->req_usage = pk->req_usage;
892 rc = lookup( ctx, ret_kb, 0 );
893 if ( !rc && pk ) {
894 pk_from_block ( ctx, pk, *ret_kb );
898 release_kbnode ( help_kb );
900 if (retctx) /* caller wants the context */
901 *retctx = ctx;
902 else {
903 if (ret_kdbhd) {
904 *ret_kdbhd = ctx->kr_handle;
905 ctx->kr_handle = NULL;
907 get_pubkey_end (ctx);
910 return rc;
915 /* Find a public key from NAME and return the keyblock or the key. If
916 ret_kdb is not NULL, the KEYDB handle used to locate this keyblock
917 is returned and the caller is responsible for closing it. If a key
918 was not found (or if local search has been disabled) and NAME is a
919 valid RFC822 mailbox and --auto-key-locate has been enabled, we try
920 to import the key via the online mechanisms defined by
921 --auto-key-locate. */
923 get_pubkey_byname (GETKEY_CTX *retctx, PKT_public_key *pk,
924 const char *name, KBNODE *ret_keyblock,
925 KEYDB_HANDLE *ret_kdbhd, int include_unusable,
926 int no_akl)
928 int rc;
929 strlist_t namelist = NULL;
930 struct akl *akl;
931 int is_mbox;
932 int nodefault = 0;
933 int anylocalfirst = 0;
935 if (retctx)
936 *retctx = NULL;
938 is_mbox = is_valid_mailbox (name);
940 /* Check whether we the default local search has been disabled.
941 This is the case if either the "nodefault" or the "local" keyword
942 are in the list of auto key locate mechanisms.
944 ANYLOCALFIRST is set if the search order has the local method
945 before any other or if "local" is used first by default. This
946 makes sure that if a RETCTX is used it gets only set if a local
947 search has precedence over the other search methods and only then
948 a followup call to get_pubkey_next shall succeed. */
949 if (!no_akl)
951 for (akl=opt.auto_key_locate; akl; akl=akl->next)
952 if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
954 nodefault = 1;
955 break;
957 for (akl=opt.auto_key_locate; akl; akl=akl->next)
958 if (akl->type != AKL_NODEFAULT)
960 if (akl->type == AKL_LOCAL)
961 anylocalfirst = 1;
962 break;
966 if (!nodefault)
967 anylocalfirst = 1;
969 if (nodefault && is_mbox)
971 /* Nodefault but a mailbox - let the AKL locate the key. */
972 rc = G10ERR_NO_PUBKEY;
974 else
976 add_to_strlist (&namelist, name);
977 rc = key_byname (retctx, namelist, pk, NULL, 0,
978 include_unusable, ret_keyblock, ret_kdbhd);
981 /* If the requested name resembles a valid mailbox and automatic
982 retrieval has been enabled, we try to import the key. */
983 if (gpg_err_code (rc) == G10ERR_NO_PUBKEY && !no_akl && is_mbox)
985 for (akl=opt.auto_key_locate; akl; akl=akl->next)
987 unsigned char *fpr = NULL;
988 size_t fpr_len;
989 int did_key_byname = 0;
990 int no_fingerprint = 0;
991 const char *mechanism = "?";
993 switch(akl->type)
995 case AKL_NODEFAULT:
996 /* This is a dummy mechanism. */
997 mechanism = "None";
998 rc = G10ERR_NO_PUBKEY;
999 break;
1001 case AKL_LOCAL:
1002 mechanism = "Local";
1003 did_key_byname = 1;
1004 if (retctx)
1006 get_pubkey_end (*retctx);
1007 *retctx = NULL;
1009 add_to_strlist (&namelist, name);
1010 rc = key_byname (anylocalfirst? retctx:NULL,
1011 namelist, pk, NULL, 0,
1012 include_unusable, ret_keyblock, ret_kdbhd);
1013 break;
1015 case AKL_CERT:
1016 mechanism = "DNS CERT";
1017 glo_ctrl.in_auto_key_retrieve++;
1018 rc=keyserver_import_cert(name,&fpr,&fpr_len);
1019 glo_ctrl.in_auto_key_retrieve--;
1020 break;
1022 case AKL_PKA:
1023 mechanism = "PKA";
1024 glo_ctrl.in_auto_key_retrieve++;
1025 rc=keyserver_import_pka(name,&fpr,&fpr_len);
1026 glo_ctrl.in_auto_key_retrieve--;
1027 break;
1029 case AKL_LDAP:
1030 mechanism = "LDAP";
1031 glo_ctrl.in_auto_key_retrieve++;
1032 rc=keyserver_import_ldap(name,&fpr,&fpr_len);
1033 glo_ctrl.in_auto_key_retrieve--;
1034 break;
1036 case AKL_KEYSERVER:
1037 /* Strictly speaking, we don't need to only use a valid
1038 mailbox for the getname search, but it helps cut down
1039 on the problem of searching for something like "john"
1040 and getting a whole lot of keys back. */
1041 if(opt.keyserver)
1043 mechanism = opt.keyserver->uri;
1044 glo_ctrl.in_auto_key_retrieve++;
1045 rc=keyserver_import_name(name,&fpr,&fpr_len,opt.keyserver);
1046 glo_ctrl.in_auto_key_retrieve--;
1048 else
1050 mechanism = "Unconfigured keyserver";
1051 rc = G10ERR_NO_PUBKEY;
1053 break;
1055 case AKL_SPEC:
1057 struct keyserver_spec *keyserver;
1059 mechanism = akl->spec->uri;
1060 keyserver=keyserver_match(akl->spec);
1061 glo_ctrl.in_auto_key_retrieve++;
1062 rc=keyserver_import_name(name,&fpr,&fpr_len,keyserver);
1063 glo_ctrl.in_auto_key_retrieve--;
1065 break;
1068 /* Use the fingerprint of the key that we actually fetched.
1069 This helps prevent problems where the key that we fetched
1070 doesn't have the same name that we used to fetch it. In
1071 the case of CERT and PKA, this is an actual security
1072 requirement as the URL might point to a key put in by an
1073 attacker. By forcing the use of the fingerprint, we
1074 won't use the attacker's key here. */
1075 if (!rc && fpr)
1077 char fpr_string[MAX_FINGERPRINT_LEN*2+1];
1079 assert(fpr_len<=MAX_FINGERPRINT_LEN);
1081 free_strlist(namelist);
1082 namelist=NULL;
1084 bin2hex (fpr, fpr_len, fpr_string);
1086 if(opt.verbose)
1087 log_info("auto-key-locate found fingerprint %s\n",fpr_string);
1089 add_to_strlist( &namelist, fpr_string );
1091 else if (!rc && !fpr && !did_key_byname)
1093 no_fingerprint = 1;
1094 rc = G10ERR_NO_PUBKEY;
1096 xfree (fpr);
1097 fpr = NULL;
1099 if (!rc && !did_key_byname)
1101 if (retctx)
1103 get_pubkey_end (*retctx);
1104 *retctx = NULL;
1106 rc = key_byname (anylocalfirst?retctx:NULL,
1107 namelist, pk, NULL, 0,
1108 include_unusable, ret_keyblock, ret_kdbhd);
1110 if (!rc)
1112 /* Key found. */
1113 log_info (_("automatically retrieved `%s' via %s\n"),
1114 name, mechanism);
1115 break;
1117 if (rc != G10ERR_NO_PUBKEY || opt.verbose || no_fingerprint)
1118 log_info (_("error retrieving `%s' via %s: %s\n"),
1119 name, mechanism,
1120 no_fingerprint? _("No fingerprint"):g10_errstr(rc));
1125 if (rc && retctx)
1127 get_pubkey_end (*retctx);
1128 *retctx = NULL;
1131 if (retctx && *retctx)
1133 assert (!(*retctx)->extra_list);
1134 (*retctx)->extra_list = namelist;
1136 else
1137 free_strlist (namelist);
1138 return rc;
1143 get_pubkey_bynames( GETKEY_CTX *retctx, PKT_public_key *pk,
1144 strlist_t names, KBNODE *ret_keyblock )
1146 return key_byname( retctx, names, pk, NULL, 0, 1, ret_keyblock, NULL);
1150 get_pubkey_next( GETKEY_CTX ctx, PKT_public_key *pk, KBNODE *ret_keyblock )
1152 int rc;
1154 rc = lookup( ctx, ret_keyblock, 0 );
1155 if ( !rc && pk && ret_keyblock )
1156 pk_from_block ( ctx, pk, *ret_keyblock );
1158 return rc;
1161 void
1162 get_pubkey_end( GETKEY_CTX ctx )
1164 if( ctx ) {
1165 memset (&ctx->kbpos, 0, sizeof ctx->kbpos);
1166 keydb_release (ctx->kr_handle);
1167 free_strlist (ctx->extra_list);
1168 if( !ctx->not_allocated )
1169 xfree( ctx );
1174 /****************
1175 * Search for a key with the given fingerprint.
1176 * FIXME:
1177 * We should replace this with the _byname function. Thiscsan be done
1178 * by creating a userID conforming to the unified fingerprint style.
1181 get_pubkey_byfprint( PKT_public_key *pk,
1182 const byte *fprint, size_t fprint_len)
1184 int rc;
1186 if( fprint_len == 20 || fprint_len == 16 ) {
1187 struct getkey_ctx_s ctx;
1188 KBNODE kb = NULL;
1190 memset( &ctx, 0, sizeof ctx );
1191 ctx.exact = 1 ;
1192 ctx.not_allocated = 1;
1193 ctx.kr_handle = keydb_new (0);
1194 ctx.nitems = 1;
1195 ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
1196 : KEYDB_SEARCH_MODE_FPR20;
1197 memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
1198 rc = lookup( &ctx, &kb, 0 );
1199 if (!rc && pk )
1200 pk_from_block ( &ctx, pk, kb );
1201 release_kbnode ( kb );
1202 get_pubkey_end( &ctx );
1204 else
1205 rc = G10ERR_GENERAL; /* Oops */
1206 return rc;
1210 /* Get a public key and store it into the allocated pk. This function
1211 differs from get_pubkey_byfprint() in that it does not do a check
1212 of the key to avoid recursion. It should be used only in very
1213 certain cases. PK may be NULL to check just for the existance of
1214 the key. */
1216 get_pubkey_byfprint_fast (PKT_public_key *pk,
1217 const byte *fprint, size_t fprint_len)
1219 int rc = 0;
1220 KEYDB_HANDLE hd;
1221 KBNODE keyblock;
1222 byte fprbuf[MAX_FINGERPRINT_LEN];
1223 int i;
1225 for (i=0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1226 fprbuf[i] = fprint[i];
1227 while (i < MAX_FINGERPRINT_LEN)
1228 fprbuf[i++] = 0;
1230 hd = keydb_new (0);
1231 rc = keydb_search_fpr (hd, fprbuf);
1232 if (rc == -1)
1234 keydb_release (hd);
1235 return G10ERR_NO_PUBKEY;
1237 rc = keydb_get_keyblock (hd, &keyblock);
1238 keydb_release (hd);
1239 if (rc)
1241 log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
1242 return G10ERR_NO_PUBKEY;
1245 assert ( keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1246 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY );
1247 if (pk)
1248 copy_public_key (pk, keyblock->pkt->pkt.public_key );
1249 release_kbnode (keyblock);
1251 /* Not caching key here since it won't have all of the fields
1252 properly set. */
1254 return 0;
1257 /****************
1258 * Search for a key with the given fingerprint and return the
1259 * complete keyblock which may have more than only this key.
1262 get_keyblock_byfprint( KBNODE *ret_keyblock, const byte *fprint,
1263 size_t fprint_len )
1265 int rc;
1267 if( fprint_len == 20 || fprint_len == 16 ) {
1268 struct getkey_ctx_s ctx;
1270 memset( &ctx, 0, sizeof ctx );
1271 ctx.not_allocated = 1;
1272 ctx.kr_handle = keydb_new (0);
1273 ctx.nitems = 1;
1274 ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
1275 : KEYDB_SEARCH_MODE_FPR20;
1276 memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
1277 rc = lookup( &ctx, ret_keyblock, 0 );
1278 get_pubkey_end( &ctx );
1280 else
1281 rc = G10ERR_GENERAL; /* Oops */
1283 return rc;
1287 /****************
1288 * Get a secret key by name and store it into sk
1289 * If NAME is NULL use the default key
1291 static int
1292 get_seckey_byname2( GETKEY_CTX *retctx,
1293 PKT_secret_key *sk, const char *name, int unprotect,
1294 KBNODE *retblock )
1296 strlist_t namelist = NULL;
1297 int rc,include_unusable=1;
1299 /* If we have no name, try to use the default secret key. If we
1300 have no default, we'll use the first usable one. */
1302 if( !name && opt.def_secret_key && *opt.def_secret_key )
1303 add_to_strlist( &namelist, opt.def_secret_key );
1304 else if(name)
1305 add_to_strlist( &namelist, name );
1306 else
1307 include_unusable=0;
1309 rc = key_byname( retctx, namelist, NULL, sk, 1, include_unusable,
1310 retblock, NULL );
1312 free_strlist( namelist );
1314 if( !rc && unprotect )
1315 rc = check_secret_key( sk, 0 );
1317 return rc;
1320 int
1321 get_seckey_byname( PKT_secret_key *sk, const char *name, int unlock )
1323 return get_seckey_byname2 ( NULL, sk, name, unlock, NULL );
1328 get_seckey_bynames( GETKEY_CTX *retctx, PKT_secret_key *sk,
1329 strlist_t names, KBNODE *ret_keyblock )
1331 return key_byname( retctx, names, NULL, sk, 1, 1, ret_keyblock, NULL );
1336 get_seckey_next( GETKEY_CTX ctx, PKT_secret_key *sk, KBNODE *ret_keyblock )
1338 int rc;
1340 rc = lookup( ctx, ret_keyblock, 1 );
1341 if ( !rc && sk && ret_keyblock )
1342 sk_from_block ( ctx, sk, *ret_keyblock );
1344 return rc;
1348 void
1349 get_seckey_end( GETKEY_CTX ctx )
1351 get_pubkey_end( ctx );
1355 /****************
1356 * Search for a key with the given fingerprint.
1357 * FIXME:
1358 * We should replace this with the _byname function. Thiscsan be done
1359 * by creating a userID conforming to the unified fingerprint style.
1362 get_seckey_byfprint( PKT_secret_key *sk,
1363 const byte *fprint, size_t fprint_len)
1365 int rc;
1367 if( fprint_len == 20 || fprint_len == 16 ) {
1368 struct getkey_ctx_s ctx;
1369 KBNODE kb = NULL;
1371 memset( &ctx, 0, sizeof ctx );
1372 ctx.exact = 1 ;
1373 ctx.not_allocated = 1;
1374 ctx.kr_handle = keydb_new (1);
1375 ctx.nitems = 1;
1376 ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
1377 : KEYDB_SEARCH_MODE_FPR20;
1378 memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
1379 rc = lookup( &ctx, &kb, 1 );
1380 if (!rc && sk )
1381 sk_from_block ( &ctx, sk, kb );
1382 release_kbnode ( kb );
1383 get_seckey_end( &ctx );
1385 else
1386 rc = G10ERR_GENERAL; /* Oops */
1387 return rc;
1391 /* Search for a secret key with the given fingerprint and return the
1392 complete keyblock which may have more than only this key. */
1394 get_seckeyblock_byfprint (KBNODE *ret_keyblock, const byte *fprint,
1395 size_t fprint_len )
1397 int rc;
1398 struct getkey_ctx_s ctx;
1400 if (fprint_len != 20 && fprint_len == 16)
1401 return G10ERR_GENERAL; /* Oops */
1403 memset (&ctx, 0, sizeof ctx);
1404 ctx.not_allocated = 1;
1405 ctx.kr_handle = keydb_new (1);
1406 ctx.nitems = 1;
1407 ctx.items[0].mode = (fprint_len==16
1408 ? KEYDB_SEARCH_MODE_FPR16
1409 : KEYDB_SEARCH_MODE_FPR20);
1410 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1411 rc = lookup (&ctx, ret_keyblock, 1);
1412 get_seckey_end (&ctx);
1414 return rc;
1419 /************************************************
1420 ************* Merging stuff ********************
1421 ************************************************/
1423 /****************
1424 * merge all selfsignatures with the keys.
1425 * FIXME: replace this at least for the public key parts
1426 * by merge_selfsigs.
1427 * It is still used in keyedit.c and
1428 * at 2 or 3 other places - check whether it is really needed.
1429 * It might be needed by the key edit and import stuff because
1430 * the keylock is changed.
1432 void
1433 merge_keys_and_selfsig( KBNODE keyblock )
1435 PKT_public_key *pk = NULL;
1436 PKT_secret_key *sk = NULL;
1437 PKT_signature *sig;
1438 KBNODE k;
1439 u32 kid[2] = { 0, 0 };
1440 u32 sigdate = 0;
1442 if (keyblock && keyblock->pkt->pkttype == PKT_PUBLIC_KEY ) {
1443 /* divert to our new function */
1444 merge_selfsigs (keyblock);
1445 return;
1447 /* still need the old one because the new one can't handle secret keys */
1449 for(k=keyblock; k; k = k->next ) {
1450 if( k->pkt->pkttype == PKT_PUBLIC_KEY
1451 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
1452 pk = k->pkt->pkt.public_key; sk = NULL;
1453 if( pk->version < 4 )
1454 pk = NULL; /* not needed for old keys */
1455 else if( k->pkt->pkttype == PKT_PUBLIC_KEY )
1456 keyid_from_pk( pk, kid );
1457 else if( !pk->expiredate ) { /* and subkey */
1458 /* insert the expiration date here */
1459 /*FIXME!!! pk->expiredate = subkeys_expiretime( k, kid );*/
1461 sigdate = 0;
1463 else if( k->pkt->pkttype == PKT_SECRET_KEY
1464 || k->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1465 pk = NULL; sk = k->pkt->pkt.secret_key;
1466 if( sk->version < 4 )
1467 sk = NULL;
1468 else if( k->pkt->pkttype == PKT_SECRET_KEY )
1469 keyid_from_sk( sk, kid );
1470 sigdate = 0;
1472 else if( (pk || sk ) && k->pkt->pkttype == PKT_SIGNATURE
1473 && (sig=k->pkt->pkt.signature)->sig_class >= 0x10
1474 && sig->sig_class <= 0x30 && sig->version > 3
1475 && !(sig->sig_class == 0x18 || sig->sig_class == 0x28)
1476 && sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1] ) {
1477 /* okay this is a self-signature which can be used.
1478 * This is not used for subkey binding signature, becuase this
1479 * is done above.
1480 * FIXME: We should only use this if the signature is valid
1481 * but this is time consuming - we must provide another
1482 * way to handle this
1484 const byte *p;
1485 u32 ed;
1487 p = parse_sig_subpkt( sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL );
1488 if( pk ) {
1489 ed = p? pk->timestamp + buffer_to_u32(p):0;
1490 if( sig->timestamp > sigdate ) {
1491 pk->expiredate = ed;
1492 sigdate = sig->timestamp;
1495 else {
1496 ed = p? sk->timestamp + buffer_to_u32(p):0;
1497 if( sig->timestamp > sigdate ) {
1498 sk->expiredate = ed;
1499 sigdate = sig->timestamp;
1504 if(pk && (pk->expiredate==0 ||
1505 (pk->max_expiredate && pk->expiredate>pk->max_expiredate)))
1506 pk->expiredate=pk->max_expiredate;
1508 if(sk && (sk->expiredate==0 ||
1509 (sk->max_expiredate && sk->expiredate>sk->max_expiredate)))
1510 sk->expiredate=sk->max_expiredate;
1514 static int
1515 parse_key_usage(PKT_signature *sig)
1517 int key_usage=0;
1518 const byte *p;
1519 size_t n;
1520 byte flags;
1522 p=parse_sig_subpkt(sig->hashed,SIGSUBPKT_KEY_FLAGS,&n);
1523 if(p && n)
1525 /* first octet of the keyflags */
1526 flags=*p;
1528 if(flags & 1)
1530 key_usage |= PUBKEY_USAGE_CERT;
1531 flags&=~1;
1534 if(flags & 2)
1536 key_usage |= PUBKEY_USAGE_SIG;
1537 flags&=~2;
1540 /* We do not distinguish between encrypting communications and
1541 encrypting storage. */
1542 if(flags & (0x04|0x08))
1544 key_usage |= PUBKEY_USAGE_ENC;
1545 flags&=~(0x04|0x08);
1548 if(flags & 0x20)
1550 key_usage |= PUBKEY_USAGE_AUTH;
1551 flags&=~0x20;
1554 if(flags)
1555 key_usage |= PUBKEY_USAGE_UNKNOWN;
1558 /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
1559 capability that we do not handle. This serves to distinguish
1560 between a zero key usage which we handle as the default
1561 capabilities for that algorithm, and a usage that we do not
1562 handle. */
1564 return key_usage;
1568 * Apply information from SIGNODE (which is the valid self-signature
1569 * associated with that UID) to the UIDNODE:
1570 * - wether the UID has been revoked
1571 * - assumed creation date of the UID
1572 * - temporary store the keyflags here
1573 * - temporary store the key expiration time here
1574 * - mark whether the primary user ID flag hat been set.
1575 * - store the preferences
1577 static void
1578 fixup_uidnode ( KBNODE uidnode, KBNODE signode, u32 keycreated )
1580 PKT_user_id *uid = uidnode->pkt->pkt.user_id;
1581 PKT_signature *sig = signode->pkt->pkt.signature;
1582 const byte *p, *sym, *hash, *zip;
1583 size_t n, nsym, nhash, nzip;
1585 sig->flags.chosen_selfsig = 1; /* we chose this one */
1586 uid->created = 0; /* not created == invalid */
1587 if ( IS_UID_REV ( sig ) )
1589 uid->is_revoked = 1;
1590 return; /* has been revoked */
1592 else
1593 uid->is_revoked = 0;
1595 uid->expiredate = sig->expiredate;
1597 if (sig->flags.expired)
1599 uid->is_expired = 1;
1600 return; /* has expired */
1602 else
1603 uid->is_expired = 0;
1605 uid->created = sig->timestamp; /* this one is okay */
1606 uid->selfsigversion = sig->version;
1607 /* If we got this far, it's not expired :) */
1608 uid->is_expired = 0;
1610 /* store the key flags in the helper variable for later processing */
1611 uid->help_key_usage=parse_key_usage(sig);
1613 /* ditto for the key expiration */
1614 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1615 if( p && buffer_to_u32(p) )
1616 uid->help_key_expire = keycreated + buffer_to_u32(p);
1617 else
1618 uid->help_key_expire = 0;
1620 /* Set the primary user ID flag - we will later wipe out some
1621 * of them to only have one in our keyblock */
1622 uid->is_primary = 0;
1623 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL );
1624 if ( p && *p )
1625 uid->is_primary = 2;
1626 /* We could also query this from the unhashed area if it is not in
1627 * the hased area and then later try to decide which is the better
1628 * there should be no security problem with this.
1629 * For now we only look at the hashed one.
1632 /* Now build the preferences list. These must come from the
1633 hashed section so nobody can modify the ciphers a key is
1634 willing to accept. */
1635 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_SYM, &n );
1636 sym = p; nsym = p?n:0;
1637 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_HASH, &n );
1638 hash = p; nhash = p?n:0;
1639 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_COMPR, &n );
1640 zip = p; nzip = p?n:0;
1641 if (uid->prefs)
1642 xfree (uid->prefs);
1643 n = nsym + nhash + nzip;
1644 if (!n)
1645 uid->prefs = NULL;
1646 else {
1647 uid->prefs = xmalloc (sizeof (*uid->prefs) * (n+1));
1648 n = 0;
1649 for (; nsym; nsym--, n++) {
1650 uid->prefs[n].type = PREFTYPE_SYM;
1651 uid->prefs[n].value = *sym++;
1653 for (; nhash; nhash--, n++) {
1654 uid->prefs[n].type = PREFTYPE_HASH;
1655 uid->prefs[n].value = *hash++;
1657 for (; nzip; nzip--, n++) {
1658 uid->prefs[n].type = PREFTYPE_ZIP;
1659 uid->prefs[n].value = *zip++;
1661 uid->prefs[n].type = PREFTYPE_NONE; /* end of list marker */
1662 uid->prefs[n].value = 0;
1665 /* see whether we have the MDC feature */
1666 uid->flags.mdc = 0;
1667 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
1668 if (p && n && (p[0] & 0x01))
1669 uid->flags.mdc = 1;
1671 /* and the keyserver modify flag */
1672 uid->flags.ks_modify = 1;
1673 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
1674 if (p && n && (p[0] & 0x80))
1675 uid->flags.ks_modify = 0;
1678 static void
1679 sig_to_revoke_info(PKT_signature *sig,struct revoke_info *rinfo)
1681 rinfo->date = sig->timestamp;
1682 rinfo->algo = sig->pubkey_algo;
1683 rinfo->keyid[0] = sig->keyid[0];
1684 rinfo->keyid[1] = sig->keyid[1];
1687 static void
1688 merge_selfsigs_main(KBNODE keyblock, int *r_revoked, struct revoke_info *rinfo)
1690 PKT_public_key *pk = NULL;
1691 KBNODE k;
1692 u32 kid[2];
1693 u32 sigdate, uiddate, uiddate2;
1694 KBNODE signode, uidnode, uidnode2;
1695 u32 curtime = make_timestamp ();
1696 unsigned int key_usage = 0;
1697 u32 keytimestamp = 0;
1698 u32 key_expire = 0;
1699 int key_expire_seen = 0;
1700 byte sigversion = 0;
1702 *r_revoked = 0;
1703 memset(rinfo,0,sizeof(*rinfo));
1705 if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY )
1706 BUG ();
1707 pk = keyblock->pkt->pkt.public_key;
1708 keytimestamp = pk->timestamp;
1710 keyid_from_pk( pk, kid );
1711 pk->main_keyid[0] = kid[0];
1712 pk->main_keyid[1] = kid[1];
1714 if ( pk->version < 4 ) {
1715 /* before v4 the key packet itself contains the expiration
1716 * date and there was no way to change it, so we start with
1717 * the one from the key packet */
1718 key_expire = pk->max_expiredate;
1719 key_expire_seen = 1;
1722 /* first pass: find the latest direct key self-signature.
1723 * We assume that the newest one overrides all others
1726 /* In case this key was already merged */
1727 xfree(pk->revkey);
1728 pk->revkey=NULL;
1729 pk->numrevkeys=0;
1731 signode = NULL;
1732 sigdate = 0; /* helper to find the latest signature */
1733 for(k=keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next ) {
1734 if ( k->pkt->pkttype == PKT_SIGNATURE ) {
1735 PKT_signature *sig = k->pkt->pkt.signature;
1736 if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) {
1737 if ( check_key_signature( keyblock, k, NULL ) )
1738 ; /* signature did not verify */
1739 else if ( IS_KEY_REV (sig) ){
1740 /* key has been revoked - there is no way to override
1741 * such a revocation, so we theoretically can stop now.
1742 * We should not cope with expiration times for revocations
1743 * here because we have to assume that an attacker can
1744 * generate all kinds of signatures. However due to the
1745 * fact that the key has been revoked it does not harm
1746 * either and by continuing we gather some more info on
1747 * that key.
1749 *r_revoked = 1;
1750 sig_to_revoke_info(sig,rinfo);
1752 else if ( IS_KEY_SIG (sig) ) {
1753 /* Add any revocation keys onto the pk. This is
1754 particularly interesting since we normally only
1755 get data from the most recent 1F signature, but
1756 you need multiple 1F sigs to properly handle
1757 revocation keys (PGP does it this way, and a
1758 revocation key could be sensitive and hence in a
1759 different signature). */
1760 if(sig->revkey) {
1761 int i;
1763 pk->revkey=
1764 xrealloc(pk->revkey,sizeof(struct revocation_key)*
1765 (pk->numrevkeys+sig->numrevkeys));
1767 for(i=0;i<sig->numrevkeys;i++)
1768 memcpy(&pk->revkey[pk->numrevkeys++],
1769 sig->revkey[i],
1770 sizeof(struct revocation_key));
1773 if( sig->timestamp >= sigdate ) {
1774 if(sig->flags.expired)
1775 ; /* signature has expired - ignore it */
1776 else {
1777 sigdate = sig->timestamp;
1778 signode = k;
1779 if( sig->version > sigversion )
1780 sigversion = sig->version;
1789 /* Remove dupes from the revocation keys */
1791 if(pk->revkey)
1793 int i,j,x,changed=0;
1795 for(i=0;i<pk->numrevkeys;i++)
1797 for(j=i+1;j<pk->numrevkeys;j++)
1799 if(memcmp(&pk->revkey[i],&pk->revkey[j],
1800 sizeof(struct revocation_key))==0)
1802 /* remove j */
1804 for(x=j;x<pk->numrevkeys-1;x++)
1805 pk->revkey[x]=pk->revkey[x+1];
1807 pk->numrevkeys--;
1808 j--;
1809 changed=1;
1814 if(changed)
1815 pk->revkey=xrealloc(pk->revkey,
1816 pk->numrevkeys*sizeof(struct revocation_key));
1819 if ( signode )
1821 /* some information from a direct key signature take precedence
1822 * over the same information given in UID sigs.
1824 PKT_signature *sig = signode->pkt->pkt.signature;
1825 const byte *p;
1827 key_usage=parse_key_usage(sig);
1829 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1830 if( p && buffer_to_u32(p) )
1832 key_expire = keytimestamp + buffer_to_u32(p);
1833 key_expire_seen = 1;
1836 /* mark that key as valid: one direct key signature should
1837 * render a key as valid */
1838 pk->is_valid = 1;
1841 /* pass 1.5: look for key revocation signatures that were not made
1842 by the key (i.e. did a revocation key issue a revocation for
1843 us?). Only bother to do this if there is a revocation key in
1844 the first place and we're not revoked already. */
1846 if(!*r_revoked && pk->revkey)
1847 for(k=keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next )
1849 if ( k->pkt->pkttype == PKT_SIGNATURE )
1851 PKT_signature *sig = k->pkt->pkt.signature;
1853 if(IS_KEY_REV(sig) &&
1854 (sig->keyid[0]!=kid[0] || sig->keyid[1]!=kid[1]))
1856 int rc=check_revocation_keys(pk,sig);
1857 if(rc==0)
1859 *r_revoked=2;
1860 sig_to_revoke_info(sig,rinfo);
1861 /* don't continue checking since we can't be any
1862 more revoked than this */
1863 break;
1865 else if(rc==G10ERR_NO_PUBKEY)
1866 pk->maybe_revoked=1;
1868 /* A failure here means the sig did not verify, was
1869 not issued by a revocation key, or a revocation
1870 key loop was broken. If a revocation key isn't
1871 findable, however, the key might be revoked and
1872 we don't know it. */
1874 /* TODO: In the future handle subkey and cert
1875 revocations? PGP doesn't, but it's in 2440. */
1880 /* second pass: look at the self-signature of all user IDs */
1881 signode = uidnode = NULL;
1882 sigdate = 0; /* helper to find the latest signature in one user ID */
1883 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next ) {
1884 if ( k->pkt->pkttype == PKT_USER_ID ) {
1885 if ( uidnode && signode )
1887 fixup_uidnode ( uidnode, signode, keytimestamp );
1888 pk->is_valid=1;
1890 uidnode = k;
1891 signode = NULL;
1892 sigdate = 0;
1894 else if ( k->pkt->pkttype == PKT_SIGNATURE && uidnode ) {
1895 PKT_signature *sig = k->pkt->pkt.signature;
1896 if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) {
1897 if ( check_key_signature( keyblock, k, NULL ) )
1898 ; /* signature did not verify */
1899 else if ( (IS_UID_SIG (sig) || IS_UID_REV (sig))
1900 && sig->timestamp >= sigdate )
1902 /* Note: we allow to invalidate cert revocations
1903 * by a newer signature. An attacker can't use this
1904 * because a key should be revoced with a key revocation.
1905 * The reason why we have to allow for that is that at
1906 * one time an email address may become invalid but later
1907 * the same email address may become valid again (hired,
1908 * fired, hired again).
1911 sigdate = sig->timestamp;
1912 signode = k;
1913 signode->pkt->pkt.signature->flags.chosen_selfsig=0;
1914 if( sig->version > sigversion )
1915 sigversion = sig->version;
1920 if ( uidnode && signode ) {
1921 fixup_uidnode ( uidnode, signode, keytimestamp );
1922 pk->is_valid = 1;
1925 /* If the key isn't valid yet, and we have
1926 --allow-non-selfsigned-uid set, then force it valid. */
1927 if(!pk->is_valid && opt.allow_non_selfsigned_uid)
1929 if(opt.verbose)
1930 log_info(_("Invalid key %s made valid by"
1931 " --allow-non-selfsigned-uid\n"),keystr_from_pk(pk));
1932 pk->is_valid = 1;
1935 /* The key STILL isn't valid, so try and find an ultimately
1936 trusted signature. */
1937 if(!pk->is_valid)
1939 uidnode=NULL;
1941 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k=k->next)
1943 if ( k->pkt->pkttype == PKT_USER_ID )
1944 uidnode = k;
1945 else if ( k->pkt->pkttype == PKT_SIGNATURE && uidnode )
1947 PKT_signature *sig = k->pkt->pkt.signature;
1949 if(sig->keyid[0] != kid[0] || sig->keyid[1]!=kid[1])
1951 PKT_public_key *ultimate_pk;
1953 ultimate_pk=xmalloc_clear(sizeof(*ultimate_pk));
1955 /* We don't want to use the full get_pubkey to
1956 avoid infinite recursion in certain cases.
1957 There is no reason to check that an ultimately
1958 trusted key is still valid - if it has been
1959 revoked or the user should also renmove the
1960 ultimate trust flag. */
1961 if(get_pubkey_fast(ultimate_pk,sig->keyid)==0
1962 && check_key_signature2(keyblock,k,ultimate_pk,
1963 NULL,NULL,NULL,NULL)==0
1964 && get_ownertrust(ultimate_pk)==TRUST_ULTIMATE)
1966 free_public_key(ultimate_pk);
1967 pk->is_valid=1;
1968 break;
1971 free_public_key(ultimate_pk);
1977 /* Record the highest selfsig version so we know if this is a v3
1978 key through and through, or a v3 key with a v4 selfsig
1979 somewhere. This is useful in a few places to know if the key
1980 must be treated as PGP2-style or OpenPGP-style. Note that a
1981 selfsig revocation with a higher version number will also raise
1982 this value. This is okay since such a revocation must be
1983 issued by the user (i.e. it cannot be issued by someone else to
1984 modify the key behavior.) */
1986 pk->selfsigversion=sigversion;
1988 /* Now that we had a look at all user IDs we can now get some information
1989 * from those user IDs.
1992 if ( !key_usage ) {
1993 /* find the latest user ID with key flags set */
1994 uiddate = 0; /* helper to find the latest user ID */
1995 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1996 k = k->next ) {
1997 if ( k->pkt->pkttype == PKT_USER_ID ) {
1998 PKT_user_id *uid = k->pkt->pkt.user_id;
1999 if ( uid->help_key_usage && uid->created > uiddate ) {
2000 key_usage = uid->help_key_usage;
2001 uiddate = uid->created;
2006 if ( !key_usage ) { /* no key flags at all: get it from the algo */
2007 key_usage = openpgp_pk_algo_usage ( pk->pubkey_algo );
2009 else { /* check that the usage matches the usage as given by the algo */
2010 int x = openpgp_pk_algo_usage ( pk->pubkey_algo );
2011 if ( x ) /* mask it down to the actual allowed usage */
2012 key_usage &= x;
2015 /* Whatever happens, it's a primary key, so it can certify. */
2016 pk->pubkey_usage = key_usage|PUBKEY_USAGE_CERT;
2018 if ( !key_expire_seen ) {
2019 /* find the latest valid user ID with a key expiration set
2020 * Note, that this may be a different one from the above because
2021 * some user IDs may have no expiration date set */
2022 uiddate = 0;
2023 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2024 k = k->next ) {
2025 if ( k->pkt->pkttype == PKT_USER_ID ) {
2026 PKT_user_id *uid = k->pkt->pkt.user_id;
2027 if ( uid->help_key_expire && uid->created > uiddate ) {
2028 key_expire = uid->help_key_expire;
2029 uiddate = uid->created;
2035 /* Currently only v3 keys have a maximum expiration date, but I'll
2036 bet v5 keys get this feature again. */
2037 if(key_expire==0 || (pk->max_expiredate && key_expire>pk->max_expiredate))
2038 key_expire=pk->max_expiredate;
2040 pk->has_expired = key_expire >= curtime? 0 : key_expire;
2041 pk->expiredate = key_expire;
2043 /* Fixme: we should see how to get rid of the expiretime fields but
2044 * this needs changes at other places too. */
2046 /* and now find the real primary user ID and delete all others */
2047 uiddate = uiddate2 = 0;
2048 uidnode = uidnode2 = NULL;
2049 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next ) {
2050 if ( k->pkt->pkttype == PKT_USER_ID &&
2051 !k->pkt->pkt.user_id->attrib_data) {
2052 PKT_user_id *uid = k->pkt->pkt.user_id;
2053 if (uid->is_primary)
2055 if(uid->created > uiddate)
2057 uiddate = uid->created;
2058 uidnode = k;
2060 else if(uid->created==uiddate && uidnode)
2062 /* The dates are equal, so we need to do a
2063 different (and arbitrary) comparison. This
2064 should rarely, if ever, happen. It's good to
2065 try and guarantee that two different GnuPG
2066 users with two different keyrings at least pick
2067 the same primary. */
2068 if(cmp_user_ids(uid,uidnode->pkt->pkt.user_id)>0)
2069 uidnode=k;
2072 else
2074 if(uid->created > uiddate2)
2076 uiddate2 = uid->created;
2077 uidnode2 = k;
2079 else if(uid->created==uiddate2 && uidnode2)
2081 if(cmp_user_ids(uid,uidnode2->pkt->pkt.user_id)>0)
2082 uidnode2=k;
2087 if ( uidnode ) {
2088 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2089 k = k->next ) {
2090 if ( k->pkt->pkttype == PKT_USER_ID &&
2091 !k->pkt->pkt.user_id->attrib_data) {
2092 PKT_user_id *uid = k->pkt->pkt.user_id;
2093 if ( k != uidnode )
2094 uid->is_primary = 0;
2098 else if( uidnode2 ) {
2099 /* none is flagged primary - use the latest user ID we have,
2100 and disambiguate with the arbitrary packet comparison. */
2101 uidnode2->pkt->pkt.user_id->is_primary = 1;
2103 else
2105 /* None of our uids were self-signed, so pick the one that
2106 sorts first to be the primary. This is the best we can do
2107 here since there are no self sigs to date the uids. */
2109 uidnode = NULL;
2111 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2112 k = k->next )
2114 if(k->pkt->pkttype==PKT_USER_ID
2115 && !k->pkt->pkt.user_id->attrib_data)
2117 if(!uidnode)
2119 uidnode=k;
2120 uidnode->pkt->pkt.user_id->is_primary=1;
2121 continue;
2123 else
2125 if(cmp_user_ids(k->pkt->pkt.user_id,
2126 uidnode->pkt->pkt.user_id)>0)
2128 uidnode->pkt->pkt.user_id->is_primary=0;
2129 uidnode=k;
2130 uidnode->pkt->pkt.user_id->is_primary=1;
2132 else
2133 k->pkt->pkt.user_id->is_primary=0; /* just to be
2134 safe */
2141 /* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
2142 Caller must free the signature when they are done. */
2143 static PKT_signature *
2144 buf_to_sig(const byte *buf,size_t len)
2146 PKT_signature *sig=xmalloc_clear(sizeof(PKT_signature));
2147 IOBUF iobuf=iobuf_temp_with_content(buf,len);
2148 int save_mode=set_packet_list_mode(0);
2150 if(parse_signature(iobuf,PKT_SIGNATURE,len,sig)!=0)
2152 xfree(sig);
2153 sig=NULL;
2156 set_packet_list_mode(save_mode);
2157 iobuf_close(iobuf);
2159 return sig;
2162 static void
2163 merge_selfsigs_subkey( KBNODE keyblock, KBNODE subnode )
2165 PKT_public_key *mainpk = NULL, *subpk = NULL;
2166 PKT_signature *sig;
2167 KBNODE k;
2168 u32 mainkid[2];
2169 u32 sigdate = 0;
2170 KBNODE signode;
2171 u32 curtime = make_timestamp ();
2172 unsigned int key_usage = 0;
2173 u32 keytimestamp = 0;
2174 u32 key_expire = 0;
2175 const byte *p;
2177 if ( subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY )
2178 BUG ();
2179 mainpk = keyblock->pkt->pkt.public_key;
2180 if ( mainpk->version < 4 )
2181 return; /* (actually this should never happen) */
2182 keyid_from_pk( mainpk, mainkid );
2183 subpk = subnode->pkt->pkt.public_key;
2184 keytimestamp = subpk->timestamp;
2186 subpk->is_valid = 0;
2187 subpk->main_keyid[0] = mainpk->main_keyid[0];
2188 subpk->main_keyid[1] = mainpk->main_keyid[1];
2190 /* find the latest key binding self-signature. */
2191 signode = NULL;
2192 sigdate = 0; /* helper to find the latest signature */
2193 for(k=subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2194 k = k->next ) {
2195 if ( k->pkt->pkttype == PKT_SIGNATURE ) {
2196 sig = k->pkt->pkt.signature;
2197 if ( sig->keyid[0] == mainkid[0] && sig->keyid[1]==mainkid[1] ) {
2198 if ( check_key_signature( keyblock, k, NULL ) )
2199 ; /* signature did not verify */
2200 else if ( IS_SUBKEY_REV (sig) ) {
2201 /* Note that this means that the date on a
2202 revocation sig does not matter - even if the
2203 binding sig is dated after the revocation sig,
2204 the subkey is still marked as revoked. This
2205 seems ok, as it is just as easy to make new
2206 subkeys rather than re-sign old ones as the
2207 problem is in the distribution. Plus, PGP (7)
2208 does this the same way. */
2209 subpk->is_revoked = 1;
2210 sig_to_revoke_info(sig,&subpk->revoked);
2211 /* although we could stop now, we continue to
2212 * figure out other information like the old expiration
2213 * time */
2215 else if ( IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate )
2217 if(sig->flags.expired)
2218 ; /* signature has expired - ignore it */
2219 else
2221 sigdate = sig->timestamp;
2222 signode = k;
2223 signode->pkt->pkt.signature->flags.chosen_selfsig=0;
2230 /* no valid key binding */
2231 if ( !signode )
2232 return;
2234 sig = signode->pkt->pkt.signature;
2235 sig->flags.chosen_selfsig=1; /* so we know which selfsig we chose later */
2237 key_usage=parse_key_usage(sig);
2238 if ( !key_usage )
2240 /* no key flags at all: get it from the algo */
2241 key_usage = openpgp_pk_algo_usage ( subpk->pubkey_algo );
2243 else
2245 /* check that the usage matches the usage as given by the algo */
2246 int x = openpgp_pk_algo_usage ( subpk->pubkey_algo );
2247 if ( x ) /* mask it down to the actual allowed usage */
2248 key_usage &= x;
2251 subpk->pubkey_usage = key_usage;
2253 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2254 if ( p && buffer_to_u32(p) )
2255 key_expire = keytimestamp + buffer_to_u32(p);
2256 else
2257 key_expire = 0;
2258 subpk->has_expired = key_expire >= curtime? 0 : key_expire;
2259 subpk->expiredate = key_expire;
2261 /* algo doesn't exist */
2262 if(openpgp_pk_test_algo(subpk->pubkey_algo))
2263 return;
2265 subpk->is_valid = 1;
2267 /* Find the most recent 0x19 embedded signature on our self-sig. */
2268 if(subpk->backsig==0)
2270 int seq=0;
2271 size_t n;
2272 PKT_signature *backsig=NULL;
2274 sigdate=0;
2276 /* We do this while() since there may be other embedded
2277 signatures in the future. We only want 0x19 here. */
2279 while((p=enum_sig_subpkt(sig->hashed,
2280 SIGSUBPKT_SIGNATURE,&n,&seq,NULL)))
2281 if(n>3 && ((p[0]==3 && p[2]==0x19) || (p[0]==4 && p[1]==0x19)))
2283 PKT_signature *tempsig=buf_to_sig(p,n);
2284 if(tempsig)
2286 if(tempsig->timestamp>sigdate)
2288 if(backsig)
2289 free_seckey_enc(backsig);
2291 backsig=tempsig;
2292 sigdate=backsig->timestamp;
2294 else
2295 free_seckey_enc(tempsig);
2299 seq=0;
2301 /* It is safe to have this in the unhashed area since the 0x19
2302 is located on the selfsig for convenience, not security. */
2304 while((p=enum_sig_subpkt(sig->unhashed,SIGSUBPKT_SIGNATURE,
2305 &n,&seq,NULL)))
2306 if(n>3 && ((p[0]==3 && p[2]==0x19) || (p[0]==4 && p[1]==0x19)))
2308 PKT_signature *tempsig=buf_to_sig(p,n);
2309 if(tempsig)
2311 if(tempsig->timestamp>sigdate)
2313 if(backsig)
2314 free_seckey_enc(backsig);
2316 backsig=tempsig;
2317 sigdate=backsig->timestamp;
2319 else
2320 free_seckey_enc(tempsig);
2324 if(backsig)
2326 /* At ths point, backsig contains the most recent 0x19 sig.
2327 Let's see if it is good. */
2329 /* 2==valid, 1==invalid, 0==didn't check */
2330 if(check_backsig(mainpk,subpk,backsig)==0)
2331 subpk->backsig=2;
2332 else
2333 subpk->backsig=1;
2335 free_seckey_enc(backsig);
2342 * Merge information from the self-signatures with the key, so that
2343 * we can later use them more easy.
2344 * The function works by first applying the self signatures to the
2345 * primary key and the to each subkey.
2346 * Here are the rules we use to decide which inormation from which
2347 * self-signature is used:
2348 * We check all self signatures or validity and ignore all invalid signatures.
2349 * All signatures are then ordered by their creation date ....
2350 * For the primary key:
2351 * FIXME the docs
2353 static void
2354 merge_selfsigs( KBNODE keyblock )
2356 KBNODE k;
2357 int revoked;
2358 struct revoke_info rinfo;
2359 PKT_public_key *main_pk;
2360 prefitem_t *prefs;
2361 int mdc_feature;
2363 if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY ) {
2364 if (keyblock->pkt->pkttype == PKT_SECRET_KEY ) {
2365 log_error ("expected public key but found secret key "
2366 "- must stop\n");
2367 /* we better exit here becuase a public key is expected at
2368 other places too. FIXME: Figure this out earlier and
2369 don't get to here at all */
2370 g10_exit (1);
2372 BUG ();
2375 merge_selfsigs_main ( keyblock, &revoked, &rinfo );
2377 /* now merge in the data from each of the subkeys */
2378 for(k=keyblock; k; k = k->next ) {
2379 if ( k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2380 merge_selfsigs_subkey ( keyblock, k );
2384 main_pk = keyblock->pkt->pkt.public_key;
2385 if ( revoked || main_pk->has_expired || !main_pk->is_valid ) {
2386 /* if the primary key is revoked, expired, or invalid we
2387 * better set the appropriate flags on that key and all
2388 * subkeys */
2389 for(k=keyblock; k; k = k->next ) {
2390 if ( k->pkt->pkttype == PKT_PUBLIC_KEY
2391 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2392 PKT_public_key *pk = k->pkt->pkt.public_key;
2393 if(!main_pk->is_valid)
2394 pk->is_valid = 0;
2395 if(revoked && !pk->is_revoked)
2397 pk->is_revoked = revoked;
2398 memcpy(&pk->revoked,&rinfo,sizeof(rinfo));
2400 if(main_pk->has_expired)
2401 pk->has_expired = main_pk->has_expired;
2404 return;
2407 /* set the preference list of all keys to those of the primary real
2408 * user ID. Note: we use these preferences when we don't know by
2409 * which user ID the key has been selected.
2410 * fixme: we should keep atoms of commonly used preferences or
2411 * use reference counting to optimize the preference lists storage.
2412 * FIXME: it might be better to use the intersection of
2413 * all preferences.
2414 * Do a similar thing for the MDC feature flag.
2416 prefs = NULL;
2417 mdc_feature = 0;
2418 for (k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) {
2419 if (k->pkt->pkttype == PKT_USER_ID
2420 && !k->pkt->pkt.user_id->attrib_data
2421 && k->pkt->pkt.user_id->is_primary) {
2422 prefs = k->pkt->pkt.user_id->prefs;
2423 mdc_feature = k->pkt->pkt.user_id->flags.mdc;
2424 break;
2427 for(k=keyblock; k; k = k->next ) {
2428 if ( k->pkt->pkttype == PKT_PUBLIC_KEY
2429 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2430 PKT_public_key *pk = k->pkt->pkt.public_key;
2431 if (pk->prefs)
2432 xfree (pk->prefs);
2433 pk->prefs = copy_prefs (prefs);
2434 pk->mdc_feature = mdc_feature;
2441 * Merge the secret keys from secblock into the pubblock thereby
2442 * replacing the public (sub)keys with their secret counterparts Hmmm:
2443 * It might be better to get away from the concept of entire secret
2444 * keys at all and have a way to store just the real secret parts
2445 * from the key.
2447 static void
2448 merge_public_with_secret ( KBNODE pubblock, KBNODE secblock )
2450 KBNODE pub;
2452 assert ( pubblock->pkt->pkttype == PKT_PUBLIC_KEY );
2453 assert ( secblock->pkt->pkttype == PKT_SECRET_KEY );
2455 for (pub=pubblock; pub; pub = pub->next ) {
2456 if ( pub->pkt->pkttype == PKT_PUBLIC_KEY ) {
2457 PKT_public_key *pk = pub->pkt->pkt.public_key;
2458 PKT_secret_key *sk = secblock->pkt->pkt.secret_key;
2459 assert ( pub == pubblock ); /* only in the first node */
2460 /* there is nothing to compare in this case, so just replace
2461 * some information */
2462 copy_public_parts_to_secret_key ( pk, sk );
2463 free_public_key ( pk );
2464 pub->pkt->pkttype = PKT_SECRET_KEY;
2465 pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
2467 else if ( pub->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2468 KBNODE sec;
2469 PKT_public_key *pk = pub->pkt->pkt.public_key;
2471 /* this is more complicated: it may happen that the sequence
2472 * of the subkeys dosn't match, so we have to find the
2473 * appropriate secret key */
2474 for (sec=secblock->next; sec; sec = sec->next ) {
2475 if ( sec->pkt->pkttype == PKT_SECRET_SUBKEY ) {
2476 PKT_secret_key *sk = sec->pkt->pkt.secret_key;
2477 if ( !cmp_public_secret_key ( pk, sk ) ) {
2478 copy_public_parts_to_secret_key ( pk, sk );
2479 free_public_key ( pk );
2480 pub->pkt->pkttype = PKT_SECRET_SUBKEY;
2481 pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
2482 break;
2486 if ( !sec )
2487 BUG(); /* already checked in premerge */
2492 /* This function checks that for every public subkey a corresponding
2493 * secret subkey is available and deletes the public subkey otherwise.
2494 * We need this function because we can't delete it later when we
2495 * actually merge the secret parts into the pubring.
2496 * The function also plays some games with the node flags.
2498 static void
2499 premerge_public_with_secret ( KBNODE pubblock, KBNODE secblock )
2501 KBNODE last, pub;
2503 assert ( pubblock->pkt->pkttype == PKT_PUBLIC_KEY );
2504 assert ( secblock->pkt->pkttype == PKT_SECRET_KEY );
2506 for (pub=pubblock,last=NULL; pub; last = pub, pub = pub->next ) {
2507 pub->flag &= ~3; /* reset bits 0 and 1 */
2508 if ( pub->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2509 KBNODE sec;
2510 PKT_public_key *pk = pub->pkt->pkt.public_key;
2512 for (sec=secblock->next; sec; sec = sec->next ) {
2513 if ( sec->pkt->pkttype == PKT_SECRET_SUBKEY ) {
2514 PKT_secret_key *sk = sec->pkt->pkt.secret_key;
2515 if ( !cmp_public_secret_key ( pk, sk ) ) {
2516 if ( sk->protect.s2k.mode == 1001 ) {
2517 /* The secret parts are not available so
2518 we can't use that key for signing etc.
2519 Fix the pubkey usage */
2520 pk->pubkey_usage &= ~(PUBKEY_USAGE_SIG
2521 |PUBKEY_USAGE_AUTH);
2523 /* transfer flag bits 0 and 1 to the pubblock */
2524 pub->flag |= (sec->flag &3);
2525 break;
2529 if ( !sec ) {
2530 KBNODE next, ll;
2532 if (opt.verbose)
2533 log_info (_("no secret subkey"
2534 " for public subkey %s - ignoring\n"),
2535 keystr_from_pk (pk));
2536 /* we have to remove the subkey in this case */
2537 assert ( last );
2538 /* find the next subkey */
2539 for (next=pub->next,ll=pub;
2540 next && next->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2541 ll = next, next = next->next )
2543 /* make new link */
2544 last->next = next;
2545 /* release this public subkey with all sigs */
2546 ll->next = NULL;
2547 release_kbnode( pub );
2548 /* let the loop continue */
2549 pub = last;
2553 /* We need to copy the found bits (0 and 1) from the secret key to
2554 the public key. This has already been done for the subkeys but
2555 got lost on the primary key - fix it here *. */
2556 pubblock->flag |= (secblock->flag & 3);
2562 /* See see whether the key fits
2563 * our requirements and in case we do not
2564 * request the primary key, we should select
2565 * a suitable subkey.
2566 * FIXME: Check against PGP 7 whether we still need a kludge
2567 * to favor type 16 keys over type 20 keys when type 20
2568 * has not been explitely requested.
2569 * Returns: True when a suitable key has been found.
2571 * We have to distinguish four cases: FIXME!
2572 * 1. No usage and no primary key requested
2573 * Examples for this case are that we have a keyID to be used
2574 * for decrytion or verification.
2575 * 2. No usage but primary key requested
2576 * This is the case for all functions which work on an
2577 * entire keyblock, e.g. for editing or listing
2578 * 3. Usage and primary key requested
2579 * FXME
2580 * 4. Usage but no primary key requested
2581 * FIXME
2582 * FIXME: Tell what is going to happen here and something about the rationale
2583 * Note: We don't use this function if no specific usage is requested;
2584 * This way the getkey functions can be used for plain key listings.
2586 * CTX ist the keyblock we are investigating, if FOUNDK is not NULL this
2587 * is the key we actually found by looking at the keyid or a fingerprint and
2588 * may eitehr point to the primary or one of the subkeys.
2591 static int
2592 finish_lookup (GETKEY_CTX ctx)
2594 KBNODE keyblock = ctx->keyblock;
2595 KBNODE k;
2596 KBNODE foundk = NULL;
2597 PKT_user_id *foundu = NULL;
2598 #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
2599 unsigned int req_usage = ( ctx->req_usage & USAGE_MASK );
2600 /* Request the primary if we're certifying another key, and also
2601 if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
2602 do not understand signatures made by a signing subkey. PGP 8
2603 does. */
2604 int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) ||
2605 ((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG));
2606 u32 latest_date;
2607 KBNODE latest_key;
2608 u32 curtime = make_timestamp ();
2610 assert( keyblock->pkt->pkttype == PKT_PUBLIC_KEY );
2612 ctx->found_key = NULL;
2614 if (ctx->exact) {
2615 for (k=keyblock; k; k = k->next) {
2616 if ( (k->flag & 1) ) {
2617 assert ( k->pkt->pkttype == PKT_PUBLIC_KEY
2618 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY );
2619 foundk = k;
2620 break;
2625 for (k=keyblock; k; k = k->next) {
2626 if ( (k->flag & 2) ) {
2627 assert (k->pkt->pkttype == PKT_USER_ID);
2628 foundu = k->pkt->pkt.user_id;
2629 break;
2633 if ( DBG_CACHE )
2634 log_debug( "finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
2635 (ulong)keyid_from_pk( keyblock->pkt->pkt.public_key, NULL),
2636 foundk? "one":"all", req_usage);
2638 if (!req_usage) {
2639 latest_key = foundk? foundk:keyblock;
2640 goto found;
2643 latest_date = 0;
2644 latest_key = NULL;
2645 /* do not look at subkeys if a certification key is requested */
2646 if ((!foundk || foundk->pkt->pkttype == PKT_PUBLIC_SUBKEY) && !req_prim) {
2647 KBNODE nextk;
2648 /* either start a loop or check just this one subkey */
2649 for (k=foundk?foundk:keyblock; k; k = nextk ) {
2650 PKT_public_key *pk;
2651 nextk = k->next;
2652 if ( k->pkt->pkttype != PKT_PUBLIC_SUBKEY )
2653 continue;
2654 if ( foundk )
2655 nextk = NULL; /* what a hack */
2656 pk = k->pkt->pkt.public_key;
2657 if (DBG_CACHE)
2658 log_debug( "\tchecking subkey %08lX\n",
2659 (ulong)keyid_from_pk( pk, NULL));
2660 if ( !pk->is_valid ) {
2661 if (DBG_CACHE)
2662 log_debug( "\tsubkey not valid\n");
2663 continue;
2665 if ( pk->is_revoked ) {
2666 if (DBG_CACHE)
2667 log_debug( "\tsubkey has been revoked\n");
2668 continue;
2670 if ( pk->has_expired ) {
2671 if (DBG_CACHE)
2672 log_debug( "\tsubkey has expired\n");
2673 continue;
2675 if ( pk->timestamp > curtime && !opt.ignore_valid_from ) {
2676 if (DBG_CACHE)
2677 log_debug( "\tsubkey not yet valid\n");
2678 continue;
2681 if ( !((pk->pubkey_usage&USAGE_MASK) & req_usage) ) {
2682 if (DBG_CACHE)
2683 log_debug( "\tusage does not match: want=%x have=%x\n",
2684 req_usage, pk->pubkey_usage );
2685 continue;
2688 if (DBG_CACHE)
2689 log_debug( "\tsubkey might be fine\n");
2690 /* In case a key has a timestamp of 0 set, we make sure
2691 that it is used. A better change would be to compare
2692 ">=" but that might also change the selected keys and
2693 is as such a more intrusive change. */
2694 if ( pk->timestamp > latest_date
2695 || (!pk->timestamp && !latest_date)) {
2696 latest_date = pk->timestamp;
2697 latest_key = k;
2702 /* Okay now try the primary key unless we want an exact
2703 * key ID match on a subkey */
2704 if ((!latest_key && !(ctx->exact && foundk != keyblock)) || req_prim) {
2705 PKT_public_key *pk;
2706 if (DBG_CACHE && !foundk && !req_prim )
2707 log_debug( "\tno suitable subkeys found - trying primary\n");
2708 pk = keyblock->pkt->pkt.public_key;
2709 if ( !pk->is_valid ) {
2710 if (DBG_CACHE)
2711 log_debug( "\tprimary key not valid\n");
2713 else if ( pk->is_revoked ) {
2714 if (DBG_CACHE)
2715 log_debug( "\tprimary key has been revoked\n");
2717 else if ( pk->has_expired ) {
2718 if (DBG_CACHE)
2719 log_debug( "\tprimary key has expired\n");
2721 else if ( !((pk->pubkey_usage&USAGE_MASK) & req_usage) ) {
2722 if (DBG_CACHE)
2723 log_debug( "\tprimary key usage does not match: "
2724 "want=%x have=%x\n",
2725 req_usage, pk->pubkey_usage );
2727 else { /* okay */
2728 if (DBG_CACHE)
2729 log_debug( "\tprimary key may be used\n");
2730 latest_key = keyblock;
2731 latest_date = pk->timestamp;
2735 if ( !latest_key ) {
2736 if (DBG_CACHE)
2737 log_debug("\tno suitable key found - giving up\n");
2738 return 0;
2741 found:
2742 if (DBG_CACHE)
2743 log_debug( "\tusing key %08lX\n",
2744 (ulong)keyid_from_pk( latest_key->pkt->pkt.public_key, NULL) );
2746 if (latest_key) {
2747 PKT_public_key *pk = latest_key->pkt->pkt.public_key;
2748 if (pk->user_id)
2749 free_user_id (pk->user_id);
2750 pk->user_id = scopy_user_id (foundu);
2753 ctx->found_key = latest_key;
2755 if (latest_key != keyblock && opt.verbose)
2757 char *tempkeystr=
2758 xstrdup(keystr_from_pk(latest_key->pkt->pkt.public_key));
2759 log_info(_("using subkey %s instead of primary key %s\n"),
2760 tempkeystr, keystr_from_pk(keyblock->pkt->pkt.public_key));
2761 xfree(tempkeystr);
2764 cache_user_id( keyblock );
2766 return 1; /* found */
2770 static int
2771 lookup( GETKEY_CTX ctx, KBNODE *ret_keyblock, int secmode )
2773 int rc;
2774 KBNODE secblock = NULL; /* helper */
2775 int no_suitable_key = 0;
2777 rc = 0;
2778 while (!(rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems))) {
2779 /* If we are searching for the first key we have to make sure
2780 that the next iteration does not do an implicit reset.
2781 This can be triggered by an empty key ring. */
2782 if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
2783 ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
2785 rc = keydb_get_keyblock (ctx->kr_handle, &ctx->keyblock);
2786 if (rc) {
2787 log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
2788 rc = 0;
2789 goto skip;
2792 if ( secmode ) {
2793 /* find the correspondig public key and use this
2794 * this one for the selection process */
2795 u32 aki[2];
2796 KBNODE k = ctx->keyblock;
2798 if (k->pkt->pkttype != PKT_SECRET_KEY)
2799 BUG();
2801 keyid_from_sk (k->pkt->pkt.secret_key, aki);
2802 k = get_pubkeyblock (aki);
2803 if( !k )
2805 if (!opt.quiet)
2806 log_info(_("key %s: secret key without public key"
2807 " - skipped\n"), keystr(aki));
2808 goto skip;
2810 secblock = ctx->keyblock;
2811 ctx->keyblock = k;
2813 premerge_public_with_secret ( ctx->keyblock, secblock );
2816 /* warning: node flag bits 0 and 1 should be preserved by
2817 * merge_selfsigs. For secret keys, premerge did tranfer the
2818 * keys to the keyblock */
2819 merge_selfsigs ( ctx->keyblock );
2820 if ( finish_lookup (ctx) ) {
2821 no_suitable_key = 0;
2822 if ( secmode ) {
2823 merge_public_with_secret ( ctx->keyblock,
2824 secblock);
2825 release_kbnode (secblock);
2826 secblock = NULL;
2828 goto found;
2830 else
2831 no_suitable_key = 1;
2833 skip:
2834 /* release resources and continue search */
2835 if ( secmode ) {
2836 release_kbnode( secblock );
2837 secblock = NULL;
2839 release_kbnode( ctx->keyblock );
2840 ctx->keyblock = NULL;
2843 found:
2844 if( rc && rc != -1 )
2845 log_error("keydb_search failed: %s\n", g10_errstr(rc));
2847 if( !rc ) {
2848 *ret_keyblock = ctx->keyblock; /* return the keyblock */
2849 ctx->keyblock = NULL;
2851 else if (rc == -1 && no_suitable_key)
2852 rc = secmode ? G10ERR_UNU_SECKEY : G10ERR_UNU_PUBKEY;
2853 else if( rc == -1 )
2854 rc = secmode ? G10ERR_NO_SECKEY : G10ERR_NO_PUBKEY;
2856 if ( secmode ) {
2857 release_kbnode( secblock );
2858 secblock = NULL;
2860 release_kbnode( ctx->keyblock );
2861 ctx->keyblock = NULL;
2863 ctx->last_rc = rc;
2864 return rc;
2870 /****************
2871 * FIXME: Replace by the generic function
2872 * It does not work as it is right now - it is used at
2873 * 2 places: a) to get the key for an anonyous recipient
2874 * b) to get the ultimately trusted keys.
2875 * The a) usage might have some problems.
2877 * set with_subkeys true to include subkeys
2878 * set with_spm true to include secret-parts-missing keys
2880 * Enumerate all primary secret keys. Caller must use these procedure:
2881 * 1) create a void pointer and initialize it to NULL
2882 * 2) pass this void pointer by reference to this function
2883 * and provide space for the secret key (pass a buffer for sk)
2884 * 3) call this function as long as it does not return -1
2885 * to indicate EOF.
2886 * 4) Always call this function a last time with SK set to NULL,
2887 * so that can free it's context.
2890 enum_secret_keys( void **context, PKT_secret_key *sk,
2891 int with_subkeys, int with_spm )
2893 int rc=0;
2894 struct {
2895 int eof;
2896 int first;
2897 KEYDB_HANDLE hd;
2898 KBNODE keyblock;
2899 KBNODE node;
2900 } *c = *context;
2903 if( !c ) { /* make a new context */
2904 c = xmalloc_clear( sizeof *c );
2905 *context = c;
2906 c->hd = keydb_new (1);
2907 c->first = 1;
2908 c->keyblock = NULL;
2909 c->node = NULL;
2912 if( !sk ) { /* free the context */
2913 keydb_release (c->hd);
2914 release_kbnode (c->keyblock);
2915 xfree( c );
2916 *context = NULL;
2917 return 0;
2920 if( c->eof )
2921 return -1;
2923 do {
2924 /* get the next secret key from the current keyblock */
2925 for (; c->node; c->node = c->node->next) {
2926 if ((c->node->pkt->pkttype == PKT_SECRET_KEY
2927 || (with_subkeys
2928 && c->node->pkt->pkttype == PKT_SECRET_SUBKEY) )
2929 && !(c->node->pkt->pkt.secret_key->protect.s2k.mode==1001
2930 && !with_spm)) {
2931 copy_secret_key (sk, c->node->pkt->pkt.secret_key );
2932 c->node = c->node->next;
2933 return 0; /* found */
2936 release_kbnode (c->keyblock);
2937 c->keyblock = c->node = NULL;
2939 rc = c->first? keydb_search_first (c->hd) : keydb_search_next (c->hd);
2940 c->first = 0;
2941 if (rc) {
2942 keydb_release (c->hd); c->hd = NULL;
2943 c->eof = 1;
2944 return -1; /* eof */
2947 rc = keydb_get_keyblock (c->hd, &c->keyblock);
2948 c->node = c->keyblock;
2949 } while (!rc);
2951 return rc; /* error */
2956 /*********************************************
2957 *********** user ID printing helpers *******
2958 *********************************************/
2960 /****************
2961 * Return a string with a printable representation of the user_id.
2962 * this string must be freed by xfree.
2964 char*
2965 get_user_id_string( u32 *keyid )
2967 user_id_db_t r;
2968 char *p;
2969 int pass=0;
2970 /* try it two times; second pass reads from key resources */
2973 for(r=user_id_db; r; r = r->next )
2975 keyid_list_t a;
2976 for (a=r->keyids; a; a= a->next )
2978 if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] )
2980 p = xmalloc( keystrlen() + 1 + r->len + 1 );
2981 sprintf(p, "%s %.*s", keystr(keyid), r->len, r->name );
2982 return p;
2986 } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
2987 p = xmalloc( keystrlen() + 5 );
2988 sprintf(p, "%s [?]", keystr(keyid));
2989 return p;
2993 char*
2994 get_user_id_string_native ( u32 *keyid )
2996 char *p = get_user_id_string( keyid );
2997 char *p2 = utf8_to_native( p, strlen(p), 0 );
2998 xfree(p);
2999 return p2;
3003 char*
3004 get_long_user_id_string( u32 *keyid )
3006 user_id_db_t r;
3007 char *p;
3008 int pass=0;
3009 /* try it two times; second pass reads from key resources */
3010 do {
3011 for(r=user_id_db; r; r = r->next ) {
3012 keyid_list_t a;
3013 for (a=r->keyids; a; a= a->next ) {
3014 if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] ) {
3015 p = xmalloc( r->len + 20 );
3016 sprintf(p, "%08lX%08lX %.*s",
3017 (ulong)keyid[0], (ulong)keyid[1],
3018 r->len, r->name );
3019 return p;
3023 } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
3024 p = xmalloc( 25 );
3025 sprintf(p, "%08lX%08lX [?]", (ulong)keyid[0], (ulong)keyid[1] );
3026 return p;
3029 char*
3030 get_user_id( u32 *keyid, size_t *rn )
3032 user_id_db_t r;
3033 char *p;
3034 int pass=0;
3036 /* try it two times; second pass reads from key resources */
3037 do {
3038 for(r=user_id_db; r; r = r->next ) {
3039 keyid_list_t a;
3040 for (a=r->keyids; a; a= a->next ) {
3041 if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] ) {
3042 p = xmalloc( r->len );
3043 memcpy(p, r->name, r->len );
3044 *rn = r->len;
3045 return p;
3049 } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
3050 p = xstrdup( user_id_not_found_utf8 () );
3051 *rn = strlen(p);
3052 return p;
3055 char*
3056 get_user_id_native( u32 *keyid )
3058 size_t rn;
3059 char *p = get_user_id( keyid, &rn );
3060 char *p2 = utf8_to_native( p, rn, 0 );
3061 xfree(p);
3062 return p2;
3065 KEYDB_HANDLE
3066 get_ctx_handle(GETKEY_CTX ctx)
3068 return ctx->kr_handle;
3071 static void
3072 free_akl(struct akl *akl)
3074 if(akl->spec)
3075 free_keyserver_spec(akl->spec);
3077 xfree(akl);
3080 void
3081 release_akl(void)
3083 while(opt.auto_key_locate)
3085 struct akl *akl2=opt.auto_key_locate;
3086 opt.auto_key_locate=opt.auto_key_locate->next;
3087 free_akl(akl2);
3091 /* Returns false on error. */
3093 parse_auto_key_locate(char *options)
3095 char *tok;
3097 while((tok=optsep(&options)))
3099 struct akl *akl,*check,*last=NULL;
3100 int dupe=0;
3102 if(tok[0]=='\0')
3103 continue;
3105 akl=xmalloc_clear(sizeof(*akl));
3107 if(ascii_strcasecmp(tok,"nodefault")==0)
3108 akl->type=AKL_NODEFAULT;
3109 else if(ascii_strcasecmp(tok,"local")==0)
3110 akl->type=AKL_LOCAL;
3111 else if(ascii_strcasecmp(tok,"ldap")==0)
3112 akl->type=AKL_LDAP;
3113 else if(ascii_strcasecmp(tok,"keyserver")==0)
3114 akl->type=AKL_KEYSERVER;
3115 #ifdef USE_DNS_CERT
3116 else if(ascii_strcasecmp(tok,"cert")==0)
3117 akl->type=AKL_CERT;
3118 #endif
3119 #ifdef USE_DNS_PKA
3120 else if(ascii_strcasecmp(tok,"pka")==0)
3121 akl->type=AKL_PKA;
3122 #endif
3123 else if((akl->spec=parse_keyserver_uri(tok,1,NULL,0)))
3124 akl->type=AKL_SPEC;
3125 else
3127 free_akl(akl);
3128 return 0;
3131 /* We must maintain the order the user gave us */
3132 for(check=opt.auto_key_locate;check;last=check,check=check->next)
3134 /* Check for duplicates */
3135 if(check->type==akl->type
3136 && (akl->type!=AKL_SPEC
3137 || (akl->type==AKL_SPEC
3138 && strcmp(check->spec->uri,akl->spec->uri)==0)))
3140 dupe=1;
3141 free_akl(akl);
3142 break;
3146 if(!dupe)
3148 if(last)
3149 last->next=akl;
3150 else
3151 opt.auto_key_locate=akl;
3155 return 1;