2008-05-15 Marcus Brinkmann <marcus@g10code.de>
[gnupg.git] / g10 / getkey.c
blob65d373b81e32e9ccac134dbb09242d85ce7d1a5b
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 keyblock=get_pubkeyblock(keyid);
769 if(!keyblock)
771 log_error("error checking usability status of %s\n",keystr(keyid));
772 goto leave;
775 /* Is the user ID in question revoked/expired? */
776 if(uid)
778 KBNODE node;
780 for(node=keyblock;node;node=node->next)
782 if(node->pkt->pkttype==PKT_USER_ID)
784 if(cmp_user_ids(uid,node->pkt->pkt.user_id)==0
785 && (node->pkt->pkt.user_id->is_revoked
786 || node->pkt->pkt.user_id->is_expired))
788 unusable=1;
789 break;
795 if(!unusable)
796 unusable=pk_is_disabled(keyblock->pkt->pkt.public_key);
798 leave:
799 release_kbnode(keyblock);
800 return unusable;
803 /****************
804 * Try to get the pubkey by the userid. This function looks for the
805 * first pubkey certificate which has the given name in a user_id. if
806 * pk/sk has the pubkey algo set, the function will only return a
807 * pubkey with that algo. If namelist is NULL, the first key is
808 * returned. The caller should provide storage for either the pk or
809 * the sk. If ret_kb is not NULL the function will return the
810 * keyblock there.
813 static int
814 key_byname( GETKEY_CTX *retctx, strlist_t namelist,
815 PKT_public_key *pk, PKT_secret_key *sk,
816 int secmode, int include_unusable,
817 KBNODE *ret_kb, KEYDB_HANDLE *ret_kdbhd )
819 int rc = 0;
820 int n;
821 strlist_t r;
822 GETKEY_CTX ctx;
823 KBNODE help_kb = NULL;
825 if( retctx ) {/* reset the returned context in case of error */
826 assert (!ret_kdbhd); /* not allowed because the handle is
827 stored in the context */
828 *retctx = NULL;
830 if (ret_kdbhd)
831 *ret_kdbhd = NULL;
833 if(!namelist)
835 ctx = xmalloc_clear (sizeof *ctx);
836 ctx->nitems = 1;
837 ctx->items[0].mode=KEYDB_SEARCH_MODE_FIRST;
838 if(!include_unusable)
839 ctx->items[0].skipfnc=skip_unusable;
841 else
843 /* build the search context */
844 for(n=0, r=namelist; r; r = r->next )
845 n++;
847 ctx = xmalloc_clear (sizeof *ctx + (n-1)*sizeof ctx->items );
848 ctx->nitems = n;
850 for(n=0, r=namelist; r; r = r->next, n++ )
852 classify_user_id (r->d, &ctx->items[n]);
854 if (ctx->items[n].exact)
855 ctx->exact = 1;
856 if (!ctx->items[n].mode)
858 xfree (ctx);
859 return G10ERR_INV_USER_ID;
861 if(!include_unusable
862 && ctx->items[n].mode!=KEYDB_SEARCH_MODE_SHORT_KID
863 && ctx->items[n].mode!=KEYDB_SEARCH_MODE_LONG_KID
864 && ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR16
865 && ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR20
866 && ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR)
867 ctx->items[n].skipfnc=skip_unusable;
871 ctx->kr_handle = keydb_new (secmode);
872 if ( !ret_kb )
873 ret_kb = &help_kb;
875 if( secmode ) {
876 if (sk) {
877 ctx->req_algo = sk->req_algo;
878 ctx->req_usage = sk->req_usage;
880 rc = lookup( ctx, ret_kb, 1 );
881 if ( !rc && sk ) {
882 sk_from_block ( ctx, sk, *ret_kb );
885 else {
886 if (pk) {
887 ctx->req_algo = pk->req_algo;
888 ctx->req_usage = pk->req_usage;
890 rc = lookup( ctx, ret_kb, 0 );
891 if ( !rc && pk ) {
892 pk_from_block ( ctx, pk, *ret_kb );
896 release_kbnode ( help_kb );
898 if (retctx) /* caller wants the context */
899 *retctx = ctx;
900 else {
901 if (ret_kdbhd) {
902 *ret_kdbhd = ctx->kr_handle;
903 ctx->kr_handle = NULL;
905 get_pubkey_end (ctx);
908 return rc;
913 /* Find a public key from NAME and return the keyblock or the key. If
914 ret_kdb is not NULL, the KEYDB handle used to locate this keyblock
915 is returned and the caller is responsible for closing it. If a key
916 was not found (or if local search has been disabled) and NAME is a
917 valid RFC822 mailbox and --auto-key-locate has been enabled, we try
918 to import the key via the online mechanisms defined by
919 --auto-key-locate. */
921 get_pubkey_byname (GETKEY_CTX *retctx, PKT_public_key *pk,
922 const char *name, KBNODE *ret_keyblock,
923 KEYDB_HANDLE *ret_kdbhd, int include_unusable,
924 int no_akl)
926 int rc;
927 strlist_t namelist = NULL;
928 struct akl *akl;
929 int is_mbox;
930 int nodefault = 0;
931 int anylocalfirst = 0;
933 if (retctx)
934 *retctx = NULL;
936 is_mbox = is_valid_mailbox (name);
938 /* Check whether we the default local search has been disabled.
939 This is the case if either the "nodefault" or the "local" keyword
940 are in the list of auto key locate mechanisms.
942 ANYLOCALFIRST is set if the search order has the local method
943 before any other or if "local" is used first by default. This
944 makes sure that if a RETCTX is used it gets only set if a local
945 search has precedence over the other search methods and only then
946 a followup call to get_pubkey_next shall succeed. */
947 if (!no_akl)
949 for (akl=opt.auto_key_locate; akl; akl=akl->next)
950 if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
952 nodefault = 1;
953 break;
955 for (akl=opt.auto_key_locate; akl; akl=akl->next)
956 if (akl->type != AKL_NODEFAULT)
958 if (akl->type == AKL_LOCAL)
959 anylocalfirst = 1;
960 break;
964 if (!nodefault)
965 anylocalfirst = 1;
967 if (nodefault && is_mbox)
969 /* Nodefault but a mailbox - let the AKL locate the key. */
970 rc = G10ERR_NO_PUBKEY;
972 else
974 add_to_strlist (&namelist, name);
975 rc = key_byname (retctx, namelist, pk, NULL, 0,
976 include_unusable, ret_keyblock, ret_kdbhd);
979 /* If the requested name resembles a valid mailbox and automatic
980 retrieval has been enabled, we try to import the key. */
981 if (gpg_err_code (rc) == G10ERR_NO_PUBKEY && !no_akl && is_mbox)
983 for (akl=opt.auto_key_locate; akl; akl=akl->next)
985 unsigned char *fpr = NULL;
986 size_t fpr_len;
987 int did_key_byname = 0;
988 int no_fingerprint = 0;
989 const char *mechanism = "?";
991 switch(akl->type)
993 case AKL_NODEFAULT:
994 /* This is a dummy mechanism. */
995 mechanism = "None";
996 rc = G10ERR_NO_PUBKEY;
997 break;
999 case AKL_LOCAL:
1000 mechanism = "Local";
1001 did_key_byname = 1;
1002 if (retctx)
1004 get_pubkey_end (*retctx);
1005 *retctx = NULL;
1007 add_to_strlist (&namelist, name);
1008 rc = key_byname (anylocalfirst? retctx:NULL,
1009 namelist, pk, NULL, 0,
1010 include_unusable, ret_keyblock, ret_kdbhd);
1011 break;
1013 case AKL_CERT:
1014 mechanism = "DNS CERT";
1015 glo_ctrl.in_auto_key_retrieve++;
1016 rc=keyserver_import_cert(name,&fpr,&fpr_len);
1017 glo_ctrl.in_auto_key_retrieve--;
1018 break;
1020 case AKL_PKA:
1021 mechanism = "PKA";
1022 glo_ctrl.in_auto_key_retrieve++;
1023 rc=keyserver_import_pka(name,&fpr,&fpr_len);
1024 glo_ctrl.in_auto_key_retrieve--;
1025 break;
1027 case AKL_LDAP:
1028 mechanism = "LDAP";
1029 glo_ctrl.in_auto_key_retrieve++;
1030 rc=keyserver_import_ldap(name,&fpr,&fpr_len);
1031 glo_ctrl.in_auto_key_retrieve--;
1032 break;
1034 case AKL_KEYSERVER:
1035 /* Strictly speaking, we don't need to only use a valid
1036 mailbox for the getname search, but it helps cut down
1037 on the problem of searching for something like "john"
1038 and getting a whole lot of keys back. */
1039 if(opt.keyserver)
1041 mechanism = opt.keyserver->uri;
1042 glo_ctrl.in_auto_key_retrieve++;
1043 rc=keyserver_import_name(name,&fpr,&fpr_len,opt.keyserver);
1044 glo_ctrl.in_auto_key_retrieve--;
1046 else
1048 mechanism = "Unconfigured keyserver";
1049 rc = G10ERR_NO_PUBKEY;
1051 break;
1053 case AKL_SPEC:
1055 struct keyserver_spec *keyserver;
1057 mechanism = akl->spec->uri;
1058 keyserver=keyserver_match(akl->spec);
1059 glo_ctrl.in_auto_key_retrieve++;
1060 rc=keyserver_import_name(name,&fpr,&fpr_len,keyserver);
1061 glo_ctrl.in_auto_key_retrieve--;
1063 break;
1066 /* Use the fingerprint of the key that we actually fetched.
1067 This helps prevent problems where the key that we fetched
1068 doesn't have the same name that we used to fetch it. In
1069 the case of CERT and PKA, this is an actual security
1070 requirement as the URL might point to a key put in by an
1071 attacker. By forcing the use of the fingerprint, we
1072 won't use the attacker's key here. */
1073 if (!rc && fpr)
1075 char fpr_string[MAX_FINGERPRINT_LEN*2+1];
1077 assert(fpr_len<=MAX_FINGERPRINT_LEN);
1079 free_strlist(namelist);
1080 namelist=NULL;
1082 bin2hex (fpr, fpr_len, fpr_string);
1084 if(opt.verbose)
1085 log_info("auto-key-locate found fingerprint %s\n",fpr_string);
1087 add_to_strlist( &namelist, fpr_string );
1089 else if (!rc && !fpr && !did_key_byname)
1091 no_fingerprint = 1;
1092 rc = G10ERR_NO_PUBKEY;
1094 xfree (fpr);
1095 fpr = NULL;
1097 if (!rc && !did_key_byname)
1099 if (retctx)
1101 get_pubkey_end (*retctx);
1102 *retctx = NULL;
1104 rc = key_byname (anylocalfirst?retctx:NULL,
1105 namelist, pk, NULL, 0,
1106 include_unusable, ret_keyblock, ret_kdbhd);
1108 if (!rc)
1110 /* Key found. */
1111 log_info (_("automatically retrieved `%s' via %s\n"),
1112 name, mechanism);
1113 break;
1115 if (rc != G10ERR_NO_PUBKEY || opt.verbose || no_fingerprint)
1116 log_info (_("error retrieving `%s' via %s: %s\n"),
1117 name, mechanism,
1118 no_fingerprint? _("No fingerprint"):g10_errstr(rc));
1123 if (rc && retctx)
1125 get_pubkey_end (*retctx);
1126 *retctx = NULL;
1129 if (retctx && *retctx)
1131 assert (!(*retctx)->extra_list);
1132 (*retctx)->extra_list = namelist;
1134 else
1135 free_strlist (namelist);
1136 return rc;
1141 get_pubkey_bynames( GETKEY_CTX *retctx, PKT_public_key *pk,
1142 strlist_t names, KBNODE *ret_keyblock )
1144 return key_byname( retctx, names, pk, NULL, 0, 1, ret_keyblock, NULL);
1148 get_pubkey_next( GETKEY_CTX ctx, PKT_public_key *pk, KBNODE *ret_keyblock )
1150 int rc;
1152 rc = lookup( ctx, ret_keyblock, 0 );
1153 if ( !rc && pk && ret_keyblock )
1154 pk_from_block ( ctx, pk, *ret_keyblock );
1156 return rc;
1159 void
1160 get_pubkey_end( GETKEY_CTX ctx )
1162 if( ctx ) {
1163 memset (&ctx->kbpos, 0, sizeof ctx->kbpos);
1164 keydb_release (ctx->kr_handle);
1165 free_strlist (ctx->extra_list);
1166 if( !ctx->not_allocated )
1167 xfree( ctx );
1172 /****************
1173 * Search for a key with the given fingerprint.
1174 * FIXME:
1175 * We should replace this with the _byname function. Thiscsan be done
1176 * by creating a userID conforming to the unified fingerprint style.
1179 get_pubkey_byfprint( PKT_public_key *pk,
1180 const byte *fprint, size_t fprint_len)
1182 int rc;
1184 if( fprint_len == 20 || fprint_len == 16 ) {
1185 struct getkey_ctx_s ctx;
1186 KBNODE kb = NULL;
1188 memset( &ctx, 0, sizeof ctx );
1189 ctx.exact = 1 ;
1190 ctx.not_allocated = 1;
1191 ctx.kr_handle = keydb_new (0);
1192 ctx.nitems = 1;
1193 ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
1194 : KEYDB_SEARCH_MODE_FPR20;
1195 memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
1196 rc = lookup( &ctx, &kb, 0 );
1197 if (!rc && pk )
1198 pk_from_block ( &ctx, pk, kb );
1199 release_kbnode ( kb );
1200 get_pubkey_end( &ctx );
1202 else
1203 rc = G10ERR_GENERAL; /* Oops */
1204 return rc;
1208 /* Get a public key and store it into the allocated pk. This function
1209 differs from get_pubkey_byfprint() in that it does not do a check
1210 of the key to avoid recursion. It should be used only in very
1211 certain cases. PK may be NULL to check just for the existance of
1212 the key. */
1214 get_pubkey_byfprint_fast (PKT_public_key *pk,
1215 const byte *fprint, size_t fprint_len)
1217 int rc = 0;
1218 KEYDB_HANDLE hd;
1219 KBNODE keyblock;
1220 byte fprbuf[MAX_FINGERPRINT_LEN];
1221 int i;
1223 for (i=0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1224 fprbuf[i] = fprint[i];
1225 while (i < MAX_FINGERPRINT_LEN)
1226 fprbuf[i++] = 0;
1228 hd = keydb_new (0);
1229 rc = keydb_search_fpr (hd, fprbuf);
1230 if (rc == -1)
1232 keydb_release (hd);
1233 return G10ERR_NO_PUBKEY;
1235 rc = keydb_get_keyblock (hd, &keyblock);
1236 keydb_release (hd);
1237 if (rc)
1239 log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
1240 return G10ERR_NO_PUBKEY;
1243 assert ( keyblock->pkt->pkttype == PKT_PUBLIC_KEY
1244 || keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY );
1245 if (pk)
1246 copy_public_key (pk, keyblock->pkt->pkt.public_key );
1247 release_kbnode (keyblock);
1249 /* Not caching key here since it won't have all of the fields
1250 properly set. */
1252 return 0;
1255 /****************
1256 * Search for a key with the given fingerprint and return the
1257 * complete keyblock which may have more than only this key.
1260 get_keyblock_byfprint( KBNODE *ret_keyblock, const byte *fprint,
1261 size_t fprint_len )
1263 int rc;
1265 if( fprint_len == 20 || fprint_len == 16 ) {
1266 struct getkey_ctx_s ctx;
1268 memset( &ctx, 0, sizeof ctx );
1269 ctx.not_allocated = 1;
1270 ctx.kr_handle = keydb_new (0);
1271 ctx.nitems = 1;
1272 ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
1273 : KEYDB_SEARCH_MODE_FPR20;
1274 memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
1275 rc = lookup( &ctx, ret_keyblock, 0 );
1276 get_pubkey_end( &ctx );
1278 else
1279 rc = G10ERR_GENERAL; /* Oops */
1281 return rc;
1285 /****************
1286 * Get a secret key by name and store it into sk
1287 * If NAME is NULL use the default key
1289 static int
1290 get_seckey_byname2( GETKEY_CTX *retctx,
1291 PKT_secret_key *sk, const char *name, int unprotect,
1292 KBNODE *retblock )
1294 strlist_t namelist = NULL;
1295 int rc,include_unusable=1;
1297 /* If we have no name, try to use the default secret key. If we
1298 have no default, we'll use the first usable one. */
1300 if( !name && opt.def_secret_key && *opt.def_secret_key )
1301 add_to_strlist( &namelist, opt.def_secret_key );
1302 else if(name)
1303 add_to_strlist( &namelist, name );
1304 else
1305 include_unusable=0;
1307 rc = key_byname( retctx, namelist, NULL, sk, 1, include_unusable,
1308 retblock, NULL );
1310 free_strlist( namelist );
1312 if( !rc && unprotect )
1313 rc = check_secret_key( sk, 0 );
1315 return rc;
1318 int
1319 get_seckey_byname( PKT_secret_key *sk, const char *name, int unlock )
1321 return get_seckey_byname2 ( NULL, sk, name, unlock, NULL );
1326 get_seckey_bynames( GETKEY_CTX *retctx, PKT_secret_key *sk,
1327 strlist_t names, KBNODE *ret_keyblock )
1329 return key_byname( retctx, names, NULL, sk, 1, 1, ret_keyblock, NULL );
1334 get_seckey_next( GETKEY_CTX ctx, PKT_secret_key *sk, KBNODE *ret_keyblock )
1336 int rc;
1338 rc = lookup( ctx, ret_keyblock, 1 );
1339 if ( !rc && sk && ret_keyblock )
1340 sk_from_block ( ctx, sk, *ret_keyblock );
1342 return rc;
1346 void
1347 get_seckey_end( GETKEY_CTX ctx )
1349 get_pubkey_end( ctx );
1353 /****************
1354 * Search for a key with the given fingerprint.
1355 * FIXME:
1356 * We should replace this with the _byname function. Thiscsan be done
1357 * by creating a userID conforming to the unified fingerprint style.
1360 get_seckey_byfprint( PKT_secret_key *sk,
1361 const byte *fprint, size_t fprint_len)
1363 int rc;
1365 if( fprint_len == 20 || fprint_len == 16 ) {
1366 struct getkey_ctx_s ctx;
1367 KBNODE kb = NULL;
1369 memset( &ctx, 0, sizeof ctx );
1370 ctx.exact = 1 ;
1371 ctx.not_allocated = 1;
1372 ctx.kr_handle = keydb_new (1);
1373 ctx.nitems = 1;
1374 ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
1375 : KEYDB_SEARCH_MODE_FPR20;
1376 memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
1377 rc = lookup( &ctx, &kb, 1 );
1378 if (!rc && sk )
1379 sk_from_block ( &ctx, sk, kb );
1380 release_kbnode ( kb );
1381 get_seckey_end( &ctx );
1383 else
1384 rc = G10ERR_GENERAL; /* Oops */
1385 return rc;
1389 /* Search for a secret key with the given fingerprint and return the
1390 complete keyblock which may have more than only this key. */
1392 get_seckeyblock_byfprint (KBNODE *ret_keyblock, const byte *fprint,
1393 size_t fprint_len )
1395 int rc;
1396 struct getkey_ctx_s ctx;
1398 if (fprint_len != 20 && fprint_len == 16)
1399 return G10ERR_GENERAL; /* Oops */
1401 memset (&ctx, 0, sizeof ctx);
1402 ctx.not_allocated = 1;
1403 ctx.kr_handle = keydb_new (1);
1404 ctx.nitems = 1;
1405 ctx.items[0].mode = (fprint_len==16
1406 ? KEYDB_SEARCH_MODE_FPR16
1407 : KEYDB_SEARCH_MODE_FPR20);
1408 memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
1409 rc = lookup (&ctx, ret_keyblock, 1);
1410 get_seckey_end (&ctx);
1412 return rc;
1417 /************************************************
1418 ************* Merging stuff ********************
1419 ************************************************/
1421 /****************
1422 * merge all selfsignatures with the keys.
1423 * FIXME: replace this at least for the public key parts
1424 * by merge_selfsigs.
1425 * It is still used in keyedit.c and
1426 * at 2 or 3 other places - check whether it is really needed.
1427 * It might be needed by the key edit and import stuff because
1428 * the keylock is changed.
1430 void
1431 merge_keys_and_selfsig( KBNODE keyblock )
1433 PKT_public_key *pk = NULL;
1434 PKT_secret_key *sk = NULL;
1435 PKT_signature *sig;
1436 KBNODE k;
1437 u32 kid[2] = { 0, 0 };
1438 u32 sigdate = 0;
1440 if (keyblock && keyblock->pkt->pkttype == PKT_PUBLIC_KEY ) {
1441 /* divert to our new function */
1442 merge_selfsigs (keyblock);
1443 return;
1445 /* still need the old one because the new one can't handle secret keys */
1447 for(k=keyblock; k; k = k->next ) {
1448 if( k->pkt->pkttype == PKT_PUBLIC_KEY
1449 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
1450 pk = k->pkt->pkt.public_key; sk = NULL;
1451 if( pk->version < 4 )
1452 pk = NULL; /* not needed for old keys */
1453 else if( k->pkt->pkttype == PKT_PUBLIC_KEY )
1454 keyid_from_pk( pk, kid );
1455 else if( !pk->expiredate ) { /* and subkey */
1456 /* insert the expiration date here */
1457 /*FIXME!!! pk->expiredate = subkeys_expiretime( k, kid );*/
1459 sigdate = 0;
1461 else if( k->pkt->pkttype == PKT_SECRET_KEY
1462 || k->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1463 pk = NULL; sk = k->pkt->pkt.secret_key;
1464 if( sk->version < 4 )
1465 sk = NULL;
1466 else if( k->pkt->pkttype == PKT_SECRET_KEY )
1467 keyid_from_sk( sk, kid );
1468 sigdate = 0;
1470 else if( (pk || sk ) && k->pkt->pkttype == PKT_SIGNATURE
1471 && (sig=k->pkt->pkt.signature)->sig_class >= 0x10
1472 && sig->sig_class <= 0x30 && sig->version > 3
1473 && !(sig->sig_class == 0x18 || sig->sig_class == 0x28)
1474 && sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1] ) {
1475 /* okay this is a self-signature which can be used.
1476 * This is not used for subkey binding signature, becuase this
1477 * is done above.
1478 * FIXME: We should only use this if the signature is valid
1479 * but this is time consuming - we must provide another
1480 * way to handle this
1482 const byte *p;
1483 u32 ed;
1485 p = parse_sig_subpkt( sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL );
1486 if( pk ) {
1487 ed = p? pk->timestamp + buffer_to_u32(p):0;
1488 if( sig->timestamp > sigdate ) {
1489 pk->expiredate = ed;
1490 sigdate = sig->timestamp;
1493 else {
1494 ed = p? sk->timestamp + buffer_to_u32(p):0;
1495 if( sig->timestamp > sigdate ) {
1496 sk->expiredate = ed;
1497 sigdate = sig->timestamp;
1502 if(pk && (pk->expiredate==0 ||
1503 (pk->max_expiredate && pk->expiredate>pk->max_expiredate)))
1504 pk->expiredate=pk->max_expiredate;
1506 if(sk && (sk->expiredate==0 ||
1507 (sk->max_expiredate && sk->expiredate>sk->max_expiredate)))
1508 sk->expiredate=sk->max_expiredate;
1512 static int
1513 parse_key_usage(PKT_signature *sig)
1515 int key_usage=0;
1516 const byte *p;
1517 size_t n;
1518 byte flags;
1520 p=parse_sig_subpkt(sig->hashed,SIGSUBPKT_KEY_FLAGS,&n);
1521 if(p && n)
1523 /* first octet of the keyflags */
1524 flags=*p;
1526 if(flags & 1)
1528 key_usage |= PUBKEY_USAGE_CERT;
1529 flags&=~1;
1532 if(flags & 2)
1534 key_usage |= PUBKEY_USAGE_SIG;
1535 flags&=~2;
1538 /* We do not distinguish between encrypting communications and
1539 encrypting storage. */
1540 if(flags & (0x04|0x08))
1542 key_usage |= PUBKEY_USAGE_ENC;
1543 flags&=~(0x04|0x08);
1546 if(flags & 0x20)
1548 key_usage |= PUBKEY_USAGE_AUTH;
1549 flags&=~0x20;
1552 if(flags)
1553 key_usage |= PUBKEY_USAGE_UNKNOWN;
1556 /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
1557 capability that we do not handle. This serves to distinguish
1558 between a zero key usage which we handle as the default
1559 capabilities for that algorithm, and a usage that we do not
1560 handle. */
1562 return key_usage;
1566 * Apply information from SIGNODE (which is the valid self-signature
1567 * associated with that UID) to the UIDNODE:
1568 * - wether the UID has been revoked
1569 * - assumed creation date of the UID
1570 * - temporary store the keyflags here
1571 * - temporary store the key expiration time here
1572 * - mark whether the primary user ID flag hat been set.
1573 * - store the preferences
1575 static void
1576 fixup_uidnode ( KBNODE uidnode, KBNODE signode, u32 keycreated )
1578 PKT_user_id *uid = uidnode->pkt->pkt.user_id;
1579 PKT_signature *sig = signode->pkt->pkt.signature;
1580 const byte *p, *sym, *hash, *zip;
1581 size_t n, nsym, nhash, nzip;
1583 sig->flags.chosen_selfsig = 1; /* we chose this one */
1584 uid->created = 0; /* not created == invalid */
1585 if ( IS_UID_REV ( sig ) )
1587 uid->is_revoked = 1;
1588 return; /* has been revoked */
1590 else
1591 uid->is_revoked = 0;
1593 uid->expiredate = sig->expiredate;
1595 if (sig->flags.expired)
1597 uid->is_expired = 1;
1598 return; /* has expired */
1600 else
1601 uid->is_expired = 0;
1603 uid->created = sig->timestamp; /* this one is okay */
1604 uid->selfsigversion = sig->version;
1605 /* If we got this far, it's not expired :) */
1606 uid->is_expired = 0;
1608 /* store the key flags in the helper variable for later processing */
1609 uid->help_key_usage=parse_key_usage(sig);
1611 /* ditto for the key expiration */
1612 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1613 if( p && buffer_to_u32(p) )
1614 uid->help_key_expire = keycreated + buffer_to_u32(p);
1615 else
1616 uid->help_key_expire = 0;
1618 /* Set the primary user ID flag - we will later wipe out some
1619 * of them to only have one in our keyblock */
1620 uid->is_primary = 0;
1621 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL );
1622 if ( p && *p )
1623 uid->is_primary = 2;
1624 /* We could also query this from the unhashed area if it is not in
1625 * the hased area and then later try to decide which is the better
1626 * there should be no security problem with this.
1627 * For now we only look at the hashed one.
1630 /* Now build the preferences list. These must come from the
1631 hashed section so nobody can modify the ciphers a key is
1632 willing to accept. */
1633 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_SYM, &n );
1634 sym = p; nsym = p?n:0;
1635 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_HASH, &n );
1636 hash = p; nhash = p?n:0;
1637 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_COMPR, &n );
1638 zip = p; nzip = p?n:0;
1639 if (uid->prefs)
1640 xfree (uid->prefs);
1641 n = nsym + nhash + nzip;
1642 if (!n)
1643 uid->prefs = NULL;
1644 else {
1645 uid->prefs = xmalloc (sizeof (*uid->prefs) * (n+1));
1646 n = 0;
1647 for (; nsym; nsym--, n++) {
1648 uid->prefs[n].type = PREFTYPE_SYM;
1649 uid->prefs[n].value = *sym++;
1651 for (; nhash; nhash--, n++) {
1652 uid->prefs[n].type = PREFTYPE_HASH;
1653 uid->prefs[n].value = *hash++;
1655 for (; nzip; nzip--, n++) {
1656 uid->prefs[n].type = PREFTYPE_ZIP;
1657 uid->prefs[n].value = *zip++;
1659 uid->prefs[n].type = PREFTYPE_NONE; /* end of list marker */
1660 uid->prefs[n].value = 0;
1663 /* see whether we have the MDC feature */
1664 uid->flags.mdc = 0;
1665 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
1666 if (p && n && (p[0] & 0x01))
1667 uid->flags.mdc = 1;
1669 /* and the keyserver modify flag */
1670 uid->flags.ks_modify = 1;
1671 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
1672 if (p && n && (p[0] & 0x80))
1673 uid->flags.ks_modify = 0;
1676 static void
1677 sig_to_revoke_info(PKT_signature *sig,struct revoke_info *rinfo)
1679 rinfo->date = sig->timestamp;
1680 rinfo->algo = sig->pubkey_algo;
1681 rinfo->keyid[0] = sig->keyid[0];
1682 rinfo->keyid[1] = sig->keyid[1];
1685 static void
1686 merge_selfsigs_main(KBNODE keyblock, int *r_revoked, struct revoke_info *rinfo)
1688 PKT_public_key *pk = NULL;
1689 KBNODE k;
1690 u32 kid[2];
1691 u32 sigdate, uiddate, uiddate2;
1692 KBNODE signode, uidnode, uidnode2;
1693 u32 curtime = make_timestamp ();
1694 unsigned int key_usage = 0;
1695 u32 keytimestamp = 0;
1696 u32 key_expire = 0;
1697 int key_expire_seen = 0;
1698 byte sigversion = 0;
1700 *r_revoked = 0;
1701 memset(rinfo,0,sizeof(*rinfo));
1703 if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY )
1704 BUG ();
1705 pk = keyblock->pkt->pkt.public_key;
1706 keytimestamp = pk->timestamp;
1708 keyid_from_pk( pk, kid );
1709 pk->main_keyid[0] = kid[0];
1710 pk->main_keyid[1] = kid[1];
1712 if ( pk->version < 4 ) {
1713 /* before v4 the key packet itself contains the expiration
1714 * date and there was no way to change it, so we start with
1715 * the one from the key packet */
1716 key_expire = pk->max_expiredate;
1717 key_expire_seen = 1;
1720 /* first pass: find the latest direct key self-signature.
1721 * We assume that the newest one overrides all others
1724 /* In case this key was already merged */
1725 xfree(pk->revkey);
1726 pk->revkey=NULL;
1727 pk->numrevkeys=0;
1729 signode = NULL;
1730 sigdate = 0; /* helper to find the latest signature */
1731 for(k=keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next ) {
1732 if ( k->pkt->pkttype == PKT_SIGNATURE ) {
1733 PKT_signature *sig = k->pkt->pkt.signature;
1734 if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) {
1735 if ( check_key_signature( keyblock, k, NULL ) )
1736 ; /* signature did not verify */
1737 else if ( IS_KEY_REV (sig) ){
1738 /* key has been revoked - there is no way to override
1739 * such a revocation, so we theoretically can stop now.
1740 * We should not cope with expiration times for revocations
1741 * here because we have to assume that an attacker can
1742 * generate all kinds of signatures. However due to the
1743 * fact that the key has been revoked it does not harm
1744 * either and by continuing we gather some more info on
1745 * that key.
1747 *r_revoked = 1;
1748 sig_to_revoke_info(sig,rinfo);
1750 else if ( IS_KEY_SIG (sig) ) {
1751 /* Add any revocation keys onto the pk. This is
1752 particularly interesting since we normally only
1753 get data from the most recent 1F signature, but
1754 you need multiple 1F sigs to properly handle
1755 revocation keys (PGP does it this way, and a
1756 revocation key could be sensitive and hence in a
1757 different signature). */
1758 if(sig->revkey) {
1759 int i;
1761 pk->revkey=
1762 xrealloc(pk->revkey,sizeof(struct revocation_key)*
1763 (pk->numrevkeys+sig->numrevkeys));
1765 for(i=0;i<sig->numrevkeys;i++)
1766 memcpy(&pk->revkey[pk->numrevkeys++],
1767 sig->revkey[i],
1768 sizeof(struct revocation_key));
1771 if( sig->timestamp >= sigdate ) {
1772 if(sig->flags.expired)
1773 ; /* signature has expired - ignore it */
1774 else {
1775 sigdate = sig->timestamp;
1776 signode = k;
1777 if( sig->version > sigversion )
1778 sigversion = sig->version;
1787 /* Remove dupes from the revocation keys */
1789 if(pk->revkey)
1791 int i,j,x,changed=0;
1793 for(i=0;i<pk->numrevkeys;i++)
1795 for(j=i+1;j<pk->numrevkeys;j++)
1797 if(memcmp(&pk->revkey[i],&pk->revkey[j],
1798 sizeof(struct revocation_key))==0)
1800 /* remove j */
1802 for(x=j;x<pk->numrevkeys-1;x++)
1803 pk->revkey[x]=pk->revkey[x+1];
1805 pk->numrevkeys--;
1806 j--;
1807 changed=1;
1812 if(changed)
1813 pk->revkey=xrealloc(pk->revkey,
1814 pk->numrevkeys*sizeof(struct revocation_key));
1817 if ( signode )
1819 /* some information from a direct key signature take precedence
1820 * over the same information given in UID sigs.
1822 PKT_signature *sig = signode->pkt->pkt.signature;
1823 const byte *p;
1825 key_usage=parse_key_usage(sig);
1827 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1828 if( p && buffer_to_u32(p) )
1830 key_expire = keytimestamp + buffer_to_u32(p);
1831 key_expire_seen = 1;
1834 /* mark that key as valid: one direct key signature should
1835 * render a key as valid */
1836 pk->is_valid = 1;
1839 /* pass 1.5: look for key revocation signatures that were not made
1840 by the key (i.e. did a revocation key issue a revocation for
1841 us?). Only bother to do this if there is a revocation key in
1842 the first place and we're not revoked already. */
1844 if(!*r_revoked && pk->revkey)
1845 for(k=keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next )
1847 if ( k->pkt->pkttype == PKT_SIGNATURE )
1849 PKT_signature *sig = k->pkt->pkt.signature;
1851 if(IS_KEY_REV(sig) &&
1852 (sig->keyid[0]!=kid[0] || sig->keyid[1]!=kid[1]))
1854 int rc=check_revocation_keys(pk,sig);
1855 if(rc==0)
1857 *r_revoked=2;
1858 sig_to_revoke_info(sig,rinfo);
1859 /* don't continue checking since we can't be any
1860 more revoked than this */
1861 break;
1863 else if(rc==G10ERR_NO_PUBKEY)
1864 pk->maybe_revoked=1;
1866 /* A failure here means the sig did not verify, was
1867 not issued by a revocation key, or a revocation
1868 key loop was broken. If a revocation key isn't
1869 findable, however, the key might be revoked and
1870 we don't know it. */
1872 /* TODO: In the future handle subkey and cert
1873 revocations? PGP doesn't, but it's in 2440. */
1878 /* second pass: look at the self-signature of all user IDs */
1879 signode = uidnode = NULL;
1880 sigdate = 0; /* helper to find the latest signature in one user ID */
1881 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next ) {
1882 if ( k->pkt->pkttype == PKT_USER_ID ) {
1883 if ( uidnode && signode )
1885 fixup_uidnode ( uidnode, signode, keytimestamp );
1886 pk->is_valid=1;
1888 uidnode = k;
1889 signode = NULL;
1890 sigdate = 0;
1892 else if ( k->pkt->pkttype == PKT_SIGNATURE && uidnode ) {
1893 PKT_signature *sig = k->pkt->pkt.signature;
1894 if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) {
1895 if ( check_key_signature( keyblock, k, NULL ) )
1896 ; /* signature did not verify */
1897 else if ( (IS_UID_SIG (sig) || IS_UID_REV (sig))
1898 && sig->timestamp >= sigdate )
1900 /* Note: we allow to invalidate cert revocations
1901 * by a newer signature. An attacker can't use this
1902 * because a key should be revoced with a key revocation.
1903 * The reason why we have to allow for that is that at
1904 * one time an email address may become invalid but later
1905 * the same email address may become valid again (hired,
1906 * fired, hired again).
1909 sigdate = sig->timestamp;
1910 signode = k;
1911 signode->pkt->pkt.signature->flags.chosen_selfsig=0;
1912 if( sig->version > sigversion )
1913 sigversion = sig->version;
1918 if ( uidnode && signode ) {
1919 fixup_uidnode ( uidnode, signode, keytimestamp );
1920 pk->is_valid = 1;
1923 /* If the key isn't valid yet, and we have
1924 --allow-non-selfsigned-uid set, then force it valid. */
1925 if(!pk->is_valid && opt.allow_non_selfsigned_uid)
1927 if(opt.verbose)
1928 log_info(_("Invalid key %s made valid by"
1929 " --allow-non-selfsigned-uid\n"),keystr_from_pk(pk));
1930 pk->is_valid = 1;
1933 /* The key STILL isn't valid, so try and find an ultimately
1934 trusted signature. */
1935 if(!pk->is_valid)
1937 uidnode=NULL;
1939 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k=k->next)
1941 if ( k->pkt->pkttype == PKT_USER_ID )
1942 uidnode = k;
1943 else if ( k->pkt->pkttype == PKT_SIGNATURE && uidnode )
1945 PKT_signature *sig = k->pkt->pkt.signature;
1947 if(sig->keyid[0] != kid[0] || sig->keyid[1]!=kid[1])
1949 PKT_public_key *ultimate_pk;
1951 ultimate_pk=xmalloc_clear(sizeof(*ultimate_pk));
1953 /* We don't want to use the full get_pubkey to
1954 avoid infinite recursion in certain cases.
1955 There is no reason to check that an ultimately
1956 trusted key is still valid - if it has been
1957 revoked or the user should also renmove the
1958 ultimate trust flag. */
1959 if(get_pubkey_fast(ultimate_pk,sig->keyid)==0
1960 && check_key_signature2(keyblock,k,ultimate_pk,
1961 NULL,NULL,NULL,NULL)==0
1962 && get_ownertrust(ultimate_pk)==TRUST_ULTIMATE)
1964 free_public_key(ultimate_pk);
1965 pk->is_valid=1;
1966 break;
1969 free_public_key(ultimate_pk);
1975 /* Record the highest selfsig version so we know if this is a v3
1976 key through and through, or a v3 key with a v4 selfsig
1977 somewhere. This is useful in a few places to know if the key
1978 must be treated as PGP2-style or OpenPGP-style. Note that a
1979 selfsig revocation with a higher version number will also raise
1980 this value. This is okay since such a revocation must be
1981 issued by the user (i.e. it cannot be issued by someone else to
1982 modify the key behavior.) */
1984 pk->selfsigversion=sigversion;
1986 /* Now that we had a look at all user IDs we can now get some information
1987 * from those user IDs.
1990 if ( !key_usage ) {
1991 /* find the latest user ID with key flags set */
1992 uiddate = 0; /* helper to find the latest user ID */
1993 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1994 k = k->next ) {
1995 if ( k->pkt->pkttype == PKT_USER_ID ) {
1996 PKT_user_id *uid = k->pkt->pkt.user_id;
1997 if ( uid->help_key_usage && uid->created > uiddate ) {
1998 key_usage = uid->help_key_usage;
1999 uiddate = uid->created;
2004 if ( !key_usage ) { /* no key flags at all: get it from the algo */
2005 key_usage = openpgp_pk_algo_usage ( pk->pubkey_algo );
2007 else { /* check that the usage matches the usage as given by the algo */
2008 int x = openpgp_pk_algo_usage ( pk->pubkey_algo );
2009 if ( x ) /* mask it down to the actual allowed usage */
2010 key_usage &= x;
2013 /* Whatever happens, it's a primary key, so it can certify. */
2014 pk->pubkey_usage = key_usage|PUBKEY_USAGE_CERT;
2016 if ( !key_expire_seen ) {
2017 /* find the latest valid user ID with a key expiration set
2018 * Note, that this may be a different one from the above because
2019 * some user IDs may have no expiration date set */
2020 uiddate = 0;
2021 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2022 k = k->next ) {
2023 if ( k->pkt->pkttype == PKT_USER_ID ) {
2024 PKT_user_id *uid = k->pkt->pkt.user_id;
2025 if ( uid->help_key_expire && uid->created > uiddate ) {
2026 key_expire = uid->help_key_expire;
2027 uiddate = uid->created;
2033 /* Currently only v3 keys have a maximum expiration date, but I'll
2034 bet v5 keys get this feature again. */
2035 if(key_expire==0 || (pk->max_expiredate && key_expire>pk->max_expiredate))
2036 key_expire=pk->max_expiredate;
2038 pk->has_expired = key_expire >= curtime? 0 : key_expire;
2039 pk->expiredate = key_expire;
2041 /* Fixme: we should see how to get rid of the expiretime fields but
2042 * this needs changes at other places too. */
2044 /* and now find the real primary user ID and delete all others */
2045 uiddate = uiddate2 = 0;
2046 uidnode = uidnode2 = NULL;
2047 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next ) {
2048 if ( k->pkt->pkttype == PKT_USER_ID &&
2049 !k->pkt->pkt.user_id->attrib_data) {
2050 PKT_user_id *uid = k->pkt->pkt.user_id;
2051 if (uid->is_primary)
2053 if(uid->created > uiddate)
2055 uiddate = uid->created;
2056 uidnode = k;
2058 else if(uid->created==uiddate && uidnode)
2060 /* The dates are equal, so we need to do a
2061 different (and arbitrary) comparison. This
2062 should rarely, if ever, happen. It's good to
2063 try and guarantee that two different GnuPG
2064 users with two different keyrings at least pick
2065 the same primary. */
2066 if(cmp_user_ids(uid,uidnode->pkt->pkt.user_id)>0)
2067 uidnode=k;
2070 else
2072 if(uid->created > uiddate2)
2074 uiddate2 = uid->created;
2075 uidnode2 = k;
2077 else if(uid->created==uiddate2 && uidnode2)
2079 if(cmp_user_ids(uid,uidnode2->pkt->pkt.user_id)>0)
2080 uidnode2=k;
2085 if ( uidnode ) {
2086 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2087 k = k->next ) {
2088 if ( k->pkt->pkttype == PKT_USER_ID &&
2089 !k->pkt->pkt.user_id->attrib_data) {
2090 PKT_user_id *uid = k->pkt->pkt.user_id;
2091 if ( k != uidnode )
2092 uid->is_primary = 0;
2096 else if( uidnode2 ) {
2097 /* none is flagged primary - use the latest user ID we have,
2098 and disambiguate with the arbitrary packet comparison. */
2099 uidnode2->pkt->pkt.user_id->is_primary = 1;
2101 else
2103 /* None of our uids were self-signed, so pick the one that
2104 sorts first to be the primary. This is the best we can do
2105 here since there are no self sigs to date the uids. */
2107 uidnode = NULL;
2109 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2110 k = k->next )
2112 if(k->pkt->pkttype==PKT_USER_ID
2113 && !k->pkt->pkt.user_id->attrib_data)
2115 if(!uidnode)
2117 uidnode=k;
2118 uidnode->pkt->pkt.user_id->is_primary=1;
2119 continue;
2121 else
2123 if(cmp_user_ids(k->pkt->pkt.user_id,
2124 uidnode->pkt->pkt.user_id)>0)
2126 uidnode->pkt->pkt.user_id->is_primary=0;
2127 uidnode=k;
2128 uidnode->pkt->pkt.user_id->is_primary=1;
2130 else
2131 k->pkt->pkt.user_id->is_primary=0; /* just to be
2132 safe */
2139 /* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
2140 Caller must free the signature when they are done. */
2141 static PKT_signature *
2142 buf_to_sig(const byte *buf,size_t len)
2144 PKT_signature *sig=xmalloc_clear(sizeof(PKT_signature));
2145 IOBUF iobuf=iobuf_temp_with_content(buf,len);
2146 int save_mode=set_packet_list_mode(0);
2148 if(parse_signature(iobuf,PKT_SIGNATURE,len,sig)!=0)
2150 xfree(sig);
2151 sig=NULL;
2154 set_packet_list_mode(save_mode);
2155 iobuf_close(iobuf);
2157 return sig;
2160 static void
2161 merge_selfsigs_subkey( KBNODE keyblock, KBNODE subnode )
2163 PKT_public_key *mainpk = NULL, *subpk = NULL;
2164 PKT_signature *sig;
2165 KBNODE k;
2166 u32 mainkid[2];
2167 u32 sigdate = 0;
2168 KBNODE signode;
2169 u32 curtime = make_timestamp ();
2170 unsigned int key_usage = 0;
2171 u32 keytimestamp = 0;
2172 u32 key_expire = 0;
2173 const byte *p;
2175 if ( subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY )
2176 BUG ();
2177 mainpk = keyblock->pkt->pkt.public_key;
2178 if ( mainpk->version < 4 )
2179 return; /* (actually this should never happen) */
2180 keyid_from_pk( mainpk, mainkid );
2181 subpk = subnode->pkt->pkt.public_key;
2182 keytimestamp = subpk->timestamp;
2184 subpk->is_valid = 0;
2185 subpk->main_keyid[0] = mainpk->main_keyid[0];
2186 subpk->main_keyid[1] = mainpk->main_keyid[1];
2188 /* find the latest key binding self-signature. */
2189 signode = NULL;
2190 sigdate = 0; /* helper to find the latest signature */
2191 for(k=subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2192 k = k->next ) {
2193 if ( k->pkt->pkttype == PKT_SIGNATURE ) {
2194 sig = k->pkt->pkt.signature;
2195 if ( sig->keyid[0] == mainkid[0] && sig->keyid[1]==mainkid[1] ) {
2196 if ( check_key_signature( keyblock, k, NULL ) )
2197 ; /* signature did not verify */
2198 else if ( IS_SUBKEY_REV (sig) ) {
2199 /* Note that this means that the date on a
2200 revocation sig does not matter - even if the
2201 binding sig is dated after the revocation sig,
2202 the subkey is still marked as revoked. This
2203 seems ok, as it is just as easy to make new
2204 subkeys rather than re-sign old ones as the
2205 problem is in the distribution. Plus, PGP (7)
2206 does this the same way. */
2207 subpk->is_revoked = 1;
2208 sig_to_revoke_info(sig,&subpk->revoked);
2209 /* although we could stop now, we continue to
2210 * figure out other information like the old expiration
2211 * time */
2213 else if ( IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate )
2215 if(sig->flags.expired)
2216 ; /* signature has expired - ignore it */
2217 else
2219 sigdate = sig->timestamp;
2220 signode = k;
2221 signode->pkt->pkt.signature->flags.chosen_selfsig=0;
2228 /* no valid key binding */
2229 if ( !signode )
2230 return;
2232 sig = signode->pkt->pkt.signature;
2233 sig->flags.chosen_selfsig=1; /* so we know which selfsig we chose later */
2235 key_usage=parse_key_usage(sig);
2236 if ( !key_usage )
2238 /* no key flags at all: get it from the algo */
2239 key_usage = openpgp_pk_algo_usage ( subpk->pubkey_algo );
2241 else
2243 /* check that the usage matches the usage as given by the algo */
2244 int x = openpgp_pk_algo_usage ( subpk->pubkey_algo );
2245 if ( x ) /* mask it down to the actual allowed usage */
2246 key_usage &= x;
2249 subpk->pubkey_usage = key_usage;
2251 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2252 if ( p && buffer_to_u32(p) )
2253 key_expire = keytimestamp + buffer_to_u32(p);
2254 else
2255 key_expire = 0;
2256 subpk->has_expired = key_expire >= curtime? 0 : key_expire;
2257 subpk->expiredate = key_expire;
2259 /* algo doesn't exist */
2260 if(openpgp_pk_test_algo(subpk->pubkey_algo))
2261 return;
2263 subpk->is_valid = 1;
2265 /* Find the most recent 0x19 embedded signature on our self-sig. */
2266 if(subpk->backsig==0)
2268 int seq=0;
2269 size_t n;
2270 PKT_signature *backsig=NULL;
2272 sigdate=0;
2274 /* We do this while() since there may be other embedded
2275 signatures in the future. We only want 0x19 here. */
2277 while((p=enum_sig_subpkt(sig->hashed,
2278 SIGSUBPKT_SIGNATURE,&n,&seq,NULL)))
2279 if(n>3 && ((p[0]==3 && p[2]==0x19) || (p[0]==4 && p[1]==0x19)))
2281 PKT_signature *tempsig=buf_to_sig(p,n);
2282 if(tempsig)
2284 if(tempsig->timestamp>sigdate)
2286 if(backsig)
2287 free_seckey_enc(backsig);
2289 backsig=tempsig;
2290 sigdate=backsig->timestamp;
2292 else
2293 free_seckey_enc(tempsig);
2297 seq=0;
2299 /* It is safe to have this in the unhashed area since the 0x19
2300 is located on the selfsig for convenience, not security. */
2302 while((p=enum_sig_subpkt(sig->unhashed,SIGSUBPKT_SIGNATURE,
2303 &n,&seq,NULL)))
2304 if(n>3 && ((p[0]==3 && p[2]==0x19) || (p[0]==4 && p[1]==0x19)))
2306 PKT_signature *tempsig=buf_to_sig(p,n);
2307 if(tempsig)
2309 if(tempsig->timestamp>sigdate)
2311 if(backsig)
2312 free_seckey_enc(backsig);
2314 backsig=tempsig;
2315 sigdate=backsig->timestamp;
2317 else
2318 free_seckey_enc(tempsig);
2322 if(backsig)
2324 /* At ths point, backsig contains the most recent 0x19 sig.
2325 Let's see if it is good. */
2327 /* 2==valid, 1==invalid, 0==didn't check */
2328 if(check_backsig(mainpk,subpk,backsig)==0)
2329 subpk->backsig=2;
2330 else
2331 subpk->backsig=1;
2333 free_seckey_enc(backsig);
2340 * Merge information from the self-signatures with the key, so that
2341 * we can later use them more easy.
2342 * The function works by first applying the self signatures to the
2343 * primary key and the to each subkey.
2344 * Here are the rules we use to decide which inormation from which
2345 * self-signature is used:
2346 * We check all self signatures or validity and ignore all invalid signatures.
2347 * All signatures are then ordered by their creation date ....
2348 * For the primary key:
2349 * FIXME the docs
2351 static void
2352 merge_selfsigs( KBNODE keyblock )
2354 KBNODE k;
2355 int revoked;
2356 struct revoke_info rinfo;
2357 PKT_public_key *main_pk;
2358 prefitem_t *prefs;
2359 int mdc_feature;
2361 if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY ) {
2362 if (keyblock->pkt->pkttype == PKT_SECRET_KEY ) {
2363 log_error ("expected public key but found secret key "
2364 "- must stop\n");
2365 /* we better exit here becuase a public key is expected at
2366 other places too. FIXME: Figure this out earlier and
2367 don't get to here at all */
2368 g10_exit (1);
2370 BUG ();
2373 merge_selfsigs_main ( keyblock, &revoked, &rinfo );
2375 /* now merge in the data from each of the subkeys */
2376 for(k=keyblock; k; k = k->next ) {
2377 if ( k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2378 merge_selfsigs_subkey ( keyblock, k );
2382 main_pk = keyblock->pkt->pkt.public_key;
2383 if ( revoked || main_pk->has_expired || !main_pk->is_valid ) {
2384 /* if the primary key is revoked, expired, or invalid we
2385 * better set the appropriate flags on that key and all
2386 * subkeys */
2387 for(k=keyblock; k; k = k->next ) {
2388 if ( k->pkt->pkttype == PKT_PUBLIC_KEY
2389 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2390 PKT_public_key *pk = k->pkt->pkt.public_key;
2391 if(!main_pk->is_valid)
2392 pk->is_valid = 0;
2393 if(revoked && !pk->is_revoked)
2395 pk->is_revoked = revoked;
2396 memcpy(&pk->revoked,&rinfo,sizeof(rinfo));
2398 if(main_pk->has_expired)
2399 pk->has_expired = main_pk->has_expired;
2402 return;
2405 /* set the preference list of all keys to those of the primary real
2406 * user ID. Note: we use these preferences when we don't know by
2407 * which user ID the key has been selected.
2408 * fixme: we should keep atoms of commonly used preferences or
2409 * use reference counting to optimize the preference lists storage.
2410 * FIXME: it might be better to use the intersection of
2411 * all preferences.
2412 * Do a similar thing for the MDC feature flag.
2414 prefs = NULL;
2415 mdc_feature = 0;
2416 for (k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) {
2417 if (k->pkt->pkttype == PKT_USER_ID
2418 && !k->pkt->pkt.user_id->attrib_data
2419 && k->pkt->pkt.user_id->is_primary) {
2420 prefs = k->pkt->pkt.user_id->prefs;
2421 mdc_feature = k->pkt->pkt.user_id->flags.mdc;
2422 break;
2425 for(k=keyblock; k; k = k->next ) {
2426 if ( k->pkt->pkttype == PKT_PUBLIC_KEY
2427 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2428 PKT_public_key *pk = k->pkt->pkt.public_key;
2429 if (pk->prefs)
2430 xfree (pk->prefs);
2431 pk->prefs = copy_prefs (prefs);
2432 pk->mdc_feature = mdc_feature;
2439 * Merge the secret keys from secblock into the pubblock thereby
2440 * replacing the public (sub)keys with their secret counterparts Hmmm:
2441 * It might be better to get away from the concept of entire secret
2442 * keys at all and have a way to store just the real secret parts
2443 * from the key.
2445 static void
2446 merge_public_with_secret ( KBNODE pubblock, KBNODE secblock )
2448 KBNODE pub;
2450 assert ( pubblock->pkt->pkttype == PKT_PUBLIC_KEY );
2451 assert ( secblock->pkt->pkttype == PKT_SECRET_KEY );
2453 for (pub=pubblock; pub; pub = pub->next ) {
2454 if ( pub->pkt->pkttype == PKT_PUBLIC_KEY ) {
2455 PKT_public_key *pk = pub->pkt->pkt.public_key;
2456 PKT_secret_key *sk = secblock->pkt->pkt.secret_key;
2457 assert ( pub == pubblock ); /* only in the first node */
2458 /* there is nothing to compare in this case, so just replace
2459 * some information */
2460 copy_public_parts_to_secret_key ( pk, sk );
2461 free_public_key ( pk );
2462 pub->pkt->pkttype = PKT_SECRET_KEY;
2463 pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
2465 else if ( pub->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2466 KBNODE sec;
2467 PKT_public_key *pk = pub->pkt->pkt.public_key;
2469 /* this is more complicated: it may happen that the sequence
2470 * of the subkeys dosn't match, so we have to find the
2471 * appropriate secret key */
2472 for (sec=secblock->next; sec; sec = sec->next ) {
2473 if ( sec->pkt->pkttype == PKT_SECRET_SUBKEY ) {
2474 PKT_secret_key *sk = sec->pkt->pkt.secret_key;
2475 if ( !cmp_public_secret_key ( pk, sk ) ) {
2476 copy_public_parts_to_secret_key ( pk, sk );
2477 free_public_key ( pk );
2478 pub->pkt->pkttype = PKT_SECRET_SUBKEY;
2479 pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
2480 break;
2484 if ( !sec )
2485 BUG(); /* already checked in premerge */
2490 /* This function checks that for every public subkey a corresponding
2491 * secret subkey is available and deletes the public subkey otherwise.
2492 * We need this function because we can't delete it later when we
2493 * actually merge the secret parts into the pubring.
2494 * The function also plays some games with the node flags.
2496 static void
2497 premerge_public_with_secret ( KBNODE pubblock, KBNODE secblock )
2499 KBNODE last, pub;
2501 assert ( pubblock->pkt->pkttype == PKT_PUBLIC_KEY );
2502 assert ( secblock->pkt->pkttype == PKT_SECRET_KEY );
2504 for (pub=pubblock,last=NULL; pub; last = pub, pub = pub->next ) {
2505 pub->flag &= ~3; /* reset bits 0 and 1 */
2506 if ( pub->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2507 KBNODE sec;
2508 PKT_public_key *pk = pub->pkt->pkt.public_key;
2510 for (sec=secblock->next; sec; sec = sec->next ) {
2511 if ( sec->pkt->pkttype == PKT_SECRET_SUBKEY ) {
2512 PKT_secret_key *sk = sec->pkt->pkt.secret_key;
2513 if ( !cmp_public_secret_key ( pk, sk ) ) {
2514 if ( sk->protect.s2k.mode == 1001 ) {
2515 /* The secret parts are not available so
2516 we can't use that key for signing etc.
2517 Fix the pubkey usage */
2518 pk->pubkey_usage &= ~(PUBKEY_USAGE_SIG
2519 |PUBKEY_USAGE_AUTH);
2521 /* transfer flag bits 0 and 1 to the pubblock */
2522 pub->flag |= (sec->flag &3);
2523 break;
2527 if ( !sec ) {
2528 KBNODE next, ll;
2530 if (opt.verbose)
2531 log_info (_("no secret subkey"
2532 " for public subkey %s - ignoring\n"),
2533 keystr_from_pk (pk));
2534 /* we have to remove the subkey in this case */
2535 assert ( last );
2536 /* find the next subkey */
2537 for (next=pub->next,ll=pub;
2538 next && next->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2539 ll = next, next = next->next )
2541 /* make new link */
2542 last->next = next;
2543 /* release this public subkey with all sigs */
2544 ll->next = NULL;
2545 release_kbnode( pub );
2546 /* let the loop continue */
2547 pub = last;
2551 /* We need to copy the found bits (0 and 1) from the secret key to
2552 the public key. This has already been done for the subkeys but
2553 got lost on the primary key - fix it here *. */
2554 pubblock->flag |= (secblock->flag & 3);
2560 /* See see whether the key fits
2561 * our requirements and in case we do not
2562 * request the primary key, we should select
2563 * a suitable subkey.
2564 * FIXME: Check against PGP 7 whether we still need a kludge
2565 * to favor type 16 keys over type 20 keys when type 20
2566 * has not been explitely requested.
2567 * Returns: True when a suitable key has been found.
2569 * We have to distinguish four cases: FIXME!
2570 * 1. No usage and no primary key requested
2571 * Examples for this case are that we have a keyID to be used
2572 * for decrytion or verification.
2573 * 2. No usage but primary key requested
2574 * This is the case for all functions which work on an
2575 * entire keyblock, e.g. for editing or listing
2576 * 3. Usage and primary key requested
2577 * FXME
2578 * 4. Usage but no primary key requested
2579 * FIXME
2580 * FIXME: Tell what is going to happen here and something about the rationale
2581 * Note: We don't use this function if no specific usage is requested;
2582 * This way the getkey functions can be used for plain key listings.
2584 * CTX ist the keyblock we are investigating, if FOUNDK is not NULL this
2585 * is the key we actually found by looking at the keyid or a fingerprint and
2586 * may eitehr point to the primary or one of the subkeys.
2589 static int
2590 finish_lookup (GETKEY_CTX ctx)
2592 KBNODE keyblock = ctx->keyblock;
2593 KBNODE k;
2594 KBNODE foundk = NULL;
2595 PKT_user_id *foundu = NULL;
2596 #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
2597 unsigned int req_usage = ( ctx->req_usage & USAGE_MASK );
2598 /* Request the primary if we're certifying another key, and also
2599 if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
2600 do not understand signatures made by a signing subkey. PGP 8
2601 does. */
2602 int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) ||
2603 ((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG));
2604 u32 latest_date;
2605 KBNODE latest_key;
2606 u32 curtime = make_timestamp ();
2608 assert( keyblock->pkt->pkttype == PKT_PUBLIC_KEY );
2610 ctx->found_key = NULL;
2612 if (ctx->exact) {
2613 for (k=keyblock; k; k = k->next) {
2614 if ( (k->flag & 1) ) {
2615 assert ( k->pkt->pkttype == PKT_PUBLIC_KEY
2616 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY );
2617 foundk = k;
2618 break;
2623 for (k=keyblock; k; k = k->next) {
2624 if ( (k->flag & 2) ) {
2625 assert (k->pkt->pkttype == PKT_USER_ID);
2626 foundu = k->pkt->pkt.user_id;
2627 break;
2631 if ( DBG_CACHE )
2632 log_debug( "finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
2633 (ulong)keyid_from_pk( keyblock->pkt->pkt.public_key, NULL),
2634 foundk? "one":"all", req_usage);
2636 if (!req_usage) {
2637 latest_key = foundk? foundk:keyblock;
2638 goto found;
2641 if (!req_usage) {
2642 PKT_public_key *pk = foundk->pkt->pkt.public_key;
2643 if (pk->user_id)
2644 free_user_id (pk->user_id);
2645 pk->user_id = scopy_user_id (foundu);
2646 ctx->found_key = foundk;
2647 cache_user_id( keyblock );
2648 return 1; /* found */
2651 latest_date = 0;
2652 latest_key = NULL;
2653 /* do not look at subkeys if a certification key is requested */
2654 if ((!foundk || foundk->pkt->pkttype == PKT_PUBLIC_SUBKEY) && !req_prim) {
2655 KBNODE nextk;
2656 /* either start a loop or check just this one subkey */
2657 for (k=foundk?foundk:keyblock; k; k = nextk ) {
2658 PKT_public_key *pk;
2659 nextk = k->next;
2660 if ( k->pkt->pkttype != PKT_PUBLIC_SUBKEY )
2661 continue;
2662 if ( foundk )
2663 nextk = NULL; /* what a hack */
2664 pk = k->pkt->pkt.public_key;
2665 if (DBG_CACHE)
2666 log_debug( "\tchecking subkey %08lX\n",
2667 (ulong)keyid_from_pk( pk, NULL));
2668 if ( !pk->is_valid ) {
2669 if (DBG_CACHE)
2670 log_debug( "\tsubkey not valid\n");
2671 continue;
2673 if ( pk->is_revoked ) {
2674 if (DBG_CACHE)
2675 log_debug( "\tsubkey has been revoked\n");
2676 continue;
2678 if ( pk->has_expired ) {
2679 if (DBG_CACHE)
2680 log_debug( "\tsubkey has expired\n");
2681 continue;
2683 if ( pk->timestamp > curtime && !opt.ignore_valid_from ) {
2684 if (DBG_CACHE)
2685 log_debug( "\tsubkey not yet valid\n");
2686 continue;
2689 if ( !((pk->pubkey_usage&USAGE_MASK) & req_usage) ) {
2690 if (DBG_CACHE)
2691 log_debug( "\tusage does not match: want=%x have=%x\n",
2692 req_usage, pk->pubkey_usage );
2693 continue;
2696 if (DBG_CACHE)
2697 log_debug( "\tsubkey looks fine\n");
2698 if ( pk->timestamp > latest_date ) {
2699 latest_date = pk->timestamp;
2700 latest_key = k;
2705 /* Okay now try the primary key unless we want an exact
2706 * key ID match on a subkey */
2707 if ((!latest_key && !(ctx->exact && foundk != keyblock)) || req_prim) {
2708 PKT_public_key *pk;
2709 if (DBG_CACHE && !foundk && !req_prim )
2710 log_debug( "\tno suitable subkeys found - trying primary\n");
2711 pk = keyblock->pkt->pkt.public_key;
2712 if ( !pk->is_valid ) {
2713 if (DBG_CACHE)
2714 log_debug( "\tprimary key not valid\n");
2716 else if ( pk->is_revoked ) {
2717 if (DBG_CACHE)
2718 log_debug( "\tprimary key has been revoked\n");
2720 else if ( pk->has_expired ) {
2721 if (DBG_CACHE)
2722 log_debug( "\tprimary key has expired\n");
2724 else if ( !((pk->pubkey_usage&USAGE_MASK) & req_usage) ) {
2725 if (DBG_CACHE)
2726 log_debug( "\tprimary key usage does not match: "
2727 "want=%x have=%x\n",
2728 req_usage, pk->pubkey_usage );
2730 else { /* okay */
2731 if (DBG_CACHE)
2732 log_debug( "\tprimary key may be used\n");
2733 latest_key = keyblock;
2734 latest_date = pk->timestamp;
2738 if ( !latest_key ) {
2739 if (DBG_CACHE)
2740 log_debug("\tno suitable key found - giving up\n");
2741 return 0;
2744 found:
2745 if (DBG_CACHE)
2746 log_debug( "\tusing key %08lX\n",
2747 (ulong)keyid_from_pk( latest_key->pkt->pkt.public_key, NULL) );
2749 if (latest_key) {
2750 PKT_public_key *pk = latest_key->pkt->pkt.public_key;
2751 if (pk->user_id)
2752 free_user_id (pk->user_id);
2753 pk->user_id = scopy_user_id (foundu);
2756 ctx->found_key = latest_key;
2758 if (latest_key != keyblock && opt.verbose)
2760 char *tempkeystr=
2761 xstrdup(keystr_from_pk(latest_key->pkt->pkt.public_key));
2762 log_info(_("using subkey %s instead of primary key %s\n"),
2763 tempkeystr, keystr_from_pk(keyblock->pkt->pkt.public_key));
2764 xfree(tempkeystr);
2767 cache_user_id( keyblock );
2769 return 1; /* found */
2773 static int
2774 lookup( GETKEY_CTX ctx, KBNODE *ret_keyblock, int secmode )
2776 int rc;
2777 KBNODE secblock = NULL; /* helper */
2778 int no_suitable_key = 0;
2780 rc = 0;
2781 while (!(rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems))) {
2782 /* If we are searching for the first key we have to make sure
2783 that the next iteration does not do an implicit reset.
2784 This can be triggered by an empty key ring. */
2785 if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
2786 ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
2788 rc = keydb_get_keyblock (ctx->kr_handle, &ctx->keyblock);
2789 if (rc) {
2790 log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
2791 rc = 0;
2792 goto skip;
2795 if ( secmode ) {
2796 /* find the correspondig public key and use this
2797 * this one for the selection process */
2798 u32 aki[2];
2799 KBNODE k = ctx->keyblock;
2801 if (k->pkt->pkttype != PKT_SECRET_KEY)
2802 BUG();
2804 keyid_from_sk (k->pkt->pkt.secret_key, aki);
2805 k = get_pubkeyblock (aki);
2806 if( !k )
2808 if (!opt.quiet)
2809 log_info(_("key %s: secret key without public key"
2810 " - skipped\n"), keystr(aki));
2811 goto skip;
2813 secblock = ctx->keyblock;
2814 ctx->keyblock = k;
2816 premerge_public_with_secret ( ctx->keyblock, secblock );
2819 /* warning: node flag bits 0 and 1 should be preserved by
2820 * merge_selfsigs. For secret keys, premerge did tranfer the
2821 * keys to the keyblock */
2822 merge_selfsigs ( ctx->keyblock );
2823 if ( finish_lookup (ctx) ) {
2824 no_suitable_key = 0;
2825 if ( secmode ) {
2826 merge_public_with_secret ( ctx->keyblock,
2827 secblock);
2828 release_kbnode (secblock);
2829 secblock = NULL;
2831 goto found;
2833 else
2834 no_suitable_key = 1;
2836 skip:
2837 /* release resources and continue search */
2838 if ( secmode ) {
2839 release_kbnode( secblock );
2840 secblock = NULL;
2842 release_kbnode( ctx->keyblock );
2843 ctx->keyblock = NULL;
2846 found:
2847 if( rc && rc != -1 )
2848 log_error("keydb_search failed: %s\n", g10_errstr(rc));
2850 if( !rc ) {
2851 *ret_keyblock = ctx->keyblock; /* return the keyblock */
2852 ctx->keyblock = NULL;
2854 else if (rc == -1 && no_suitable_key)
2855 rc = secmode ? G10ERR_UNU_SECKEY : G10ERR_UNU_PUBKEY;
2856 else if( rc == -1 )
2857 rc = secmode ? G10ERR_NO_SECKEY : G10ERR_NO_PUBKEY;
2859 if ( secmode ) {
2860 release_kbnode( secblock );
2861 secblock = NULL;
2863 release_kbnode( ctx->keyblock );
2864 ctx->keyblock = NULL;
2866 ctx->last_rc = rc;
2867 return rc;
2873 /****************
2874 * FIXME: Replace by the generic function
2875 * It does not work as it is right now - it is used at
2876 * 2 places: a) to get the key for an anonyous recipient
2877 * b) to get the ultimately trusted keys.
2878 * The a) usage might have some problems.
2880 * set with_subkeys true to include subkeys
2881 * set with_spm true to include secret-parts-missing keys
2883 * Enumerate all primary secret keys. Caller must use these procedure:
2884 * 1) create a void pointer and initialize it to NULL
2885 * 2) pass this void pointer by reference to this function
2886 * and provide space for the secret key (pass a buffer for sk)
2887 * 3) call this function as long as it does not return -1
2888 * to indicate EOF.
2889 * 4) Always call this function a last time with SK set to NULL,
2890 * so that can free it's context.
2893 enum_secret_keys( void **context, PKT_secret_key *sk,
2894 int with_subkeys, int with_spm )
2896 int rc=0;
2897 struct {
2898 int eof;
2899 int first;
2900 KEYDB_HANDLE hd;
2901 KBNODE keyblock;
2902 KBNODE node;
2903 } *c = *context;
2906 if( !c ) { /* make a new context */
2907 c = xmalloc_clear( sizeof *c );
2908 *context = c;
2909 c->hd = keydb_new (1);
2910 c->first = 1;
2911 c->keyblock = NULL;
2912 c->node = NULL;
2915 if( !sk ) { /* free the context */
2916 keydb_release (c->hd);
2917 release_kbnode (c->keyblock);
2918 xfree( c );
2919 *context = NULL;
2920 return 0;
2923 if( c->eof )
2924 return -1;
2926 do {
2927 /* get the next secret key from the current keyblock */
2928 for (; c->node; c->node = c->node->next) {
2929 if ((c->node->pkt->pkttype == PKT_SECRET_KEY
2930 || (with_subkeys
2931 && c->node->pkt->pkttype == PKT_SECRET_SUBKEY) )
2932 && !(c->node->pkt->pkt.secret_key->protect.s2k.mode==1001
2933 && !with_spm)) {
2934 copy_secret_key (sk, c->node->pkt->pkt.secret_key );
2935 c->node = c->node->next;
2936 return 0; /* found */
2939 release_kbnode (c->keyblock);
2940 c->keyblock = c->node = NULL;
2942 rc = c->first? keydb_search_first (c->hd) : keydb_search_next (c->hd);
2943 c->first = 0;
2944 if (rc) {
2945 keydb_release (c->hd); c->hd = NULL;
2946 c->eof = 1;
2947 return -1; /* eof */
2950 rc = keydb_get_keyblock (c->hd, &c->keyblock);
2951 c->node = c->keyblock;
2952 } while (!rc);
2954 return rc; /* error */
2959 /*********************************************
2960 *********** user ID printing helpers *******
2961 *********************************************/
2963 /****************
2964 * Return a string with a printable representation of the user_id.
2965 * this string must be freed by xfree.
2967 char*
2968 get_user_id_string( u32 *keyid )
2970 user_id_db_t r;
2971 char *p;
2972 int pass=0;
2973 /* try it two times; second pass reads from key resources */
2976 for(r=user_id_db; r; r = r->next )
2978 keyid_list_t a;
2979 for (a=r->keyids; a; a= a->next )
2981 if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] )
2983 p = xmalloc( keystrlen() + 1 + r->len + 1 );
2984 sprintf(p, "%s %.*s", keystr(keyid), r->len, r->name );
2985 return p;
2989 } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
2990 p = xmalloc( keystrlen() + 5 );
2991 sprintf(p, "%s [?]", keystr(keyid));
2992 return p;
2996 char*
2997 get_user_id_string_native ( u32 *keyid )
2999 char *p = get_user_id_string( keyid );
3000 char *p2 = utf8_to_native( p, strlen(p), 0 );
3001 xfree(p);
3002 return p2;
3006 char*
3007 get_long_user_id_string( u32 *keyid )
3009 user_id_db_t r;
3010 char *p;
3011 int pass=0;
3012 /* try it two times; second pass reads from key resources */
3013 do {
3014 for(r=user_id_db; r; r = r->next ) {
3015 keyid_list_t a;
3016 for (a=r->keyids; a; a= a->next ) {
3017 if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] ) {
3018 p = xmalloc( r->len + 20 );
3019 sprintf(p, "%08lX%08lX %.*s",
3020 (ulong)keyid[0], (ulong)keyid[1],
3021 r->len, r->name );
3022 return p;
3026 } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
3027 p = xmalloc( 25 );
3028 sprintf(p, "%08lX%08lX [?]", (ulong)keyid[0], (ulong)keyid[1] );
3029 return p;
3032 char*
3033 get_user_id( u32 *keyid, size_t *rn )
3035 user_id_db_t r;
3036 char *p;
3037 int pass=0;
3039 /* try it two times; second pass reads from key resources */
3040 do {
3041 for(r=user_id_db; r; r = r->next ) {
3042 keyid_list_t a;
3043 for (a=r->keyids; a; a= a->next ) {
3044 if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] ) {
3045 p = xmalloc( r->len );
3046 memcpy(p, r->name, r->len );
3047 *rn = r->len;
3048 return p;
3052 } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
3053 p = xstrdup( user_id_not_found_utf8 () );
3054 *rn = strlen(p);
3055 return p;
3058 char*
3059 get_user_id_native( u32 *keyid )
3061 size_t rn;
3062 char *p = get_user_id( keyid, &rn );
3063 char *p2 = utf8_to_native( p, rn, 0 );
3064 xfree(p);
3065 return p2;
3068 KEYDB_HANDLE
3069 get_ctx_handle(GETKEY_CTX ctx)
3071 return ctx->kr_handle;
3074 static void
3075 free_akl(struct akl *akl)
3077 if(akl->spec)
3078 free_keyserver_spec(akl->spec);
3080 xfree(akl);
3083 void
3084 release_akl(void)
3086 while(opt.auto_key_locate)
3088 struct akl *akl2=opt.auto_key_locate;
3089 opt.auto_key_locate=opt.auto_key_locate->next;
3090 free_akl(akl2);
3094 /* Returns false on error. */
3096 parse_auto_key_locate(char *options)
3098 char *tok;
3100 while((tok=optsep(&options)))
3102 struct akl *akl,*check,*last=NULL;
3103 int dupe=0;
3105 if(tok[0]=='\0')
3106 continue;
3108 akl=xmalloc_clear(sizeof(*akl));
3110 if(ascii_strcasecmp(tok,"nodefault")==0)
3111 akl->type=AKL_NODEFAULT;
3112 else if(ascii_strcasecmp(tok,"local")==0)
3113 akl->type=AKL_LOCAL;
3114 else if(ascii_strcasecmp(tok,"ldap")==0)
3115 akl->type=AKL_LDAP;
3116 else if(ascii_strcasecmp(tok,"keyserver")==0)
3117 akl->type=AKL_KEYSERVER;
3118 #ifdef USE_DNS_CERT
3119 else if(ascii_strcasecmp(tok,"cert")==0)
3120 akl->type=AKL_CERT;
3121 #endif
3122 #ifdef USE_DNS_PKA
3123 else if(ascii_strcasecmp(tok,"pka")==0)
3124 akl->type=AKL_PKA;
3125 #endif
3126 else if((akl->spec=parse_keyserver_uri(tok,1,NULL,0)))
3127 akl->type=AKL_SPEC;
3128 else
3130 free_akl(akl);
3131 return 0;
3134 /* We must maintain the order the user gave us */
3135 for(check=opt.auto_key_locate;check;last=check,check=check->next)
3137 /* Check for duplicates */
3138 if(check->type==akl->type
3139 && (akl->type!=AKL_SPEC
3140 || (akl->type==AKL_SPEC
3141 && strcmp(check->spec->uri,akl->spec->uri)==0)))
3143 dupe=1;
3144 free_akl(akl);
3145 break;
3149 if(!dupe)
3151 if(last)
3152 last->next=akl;
3153 else
3154 opt.auto_key_locate=akl;
3158 return 1;