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/>.
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
50 KBNODE found_key; /* Pointer into some keyblock. */
51 strlist_t extra_list; /* Will be freed when releasing the context. */
55 KEYDB_HANDLE kr_handle;
58 KEYDB_SEARCH_DESC items[1];
70 typedef struct keyid_list {
71 struct keyid_list *next;
76 #if MAX_PK_CACHE_ENTRIES
77 typedef struct pk_cache_entry {
78 struct pk_cache_entry *next;
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;
87 #if MAX_UID_CACHE_ENTRIES < 5
88 #error we really need the userid cache
90 typedef struct user_id_db {
91 struct user_id_db *next;
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 );
107 for(i=0; i < DIM(lkup_stats); i++ ) {
108 if( lkup_stats[i].any )
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 );
121 cache_public_key( PKT_public_key *pk )
123 #if MAX_PK_CACHE_ENTRIES
127 if( pk_cache_disabled )
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 );
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] ) {
144 log_debug("cache_public_key: already in cache\n");
148 if( pk_cache_entries >= MAX_PK_CACHE_ENTRIES ) {
149 /* fixme: use another algorithm to free some cache slots */
151 if( opt.verbose > 1 )
152 log_info(_("too many entries in pk cache - disabled\n"));
156 ce = xmalloc( sizeof *ce );
159 ce->pk = copy_public_key( NULL, pk );
160 ce->keyid[0] = keyid[0];
161 ce->keyid[1] = keyid[1];
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. */
170 user_id_not_found_utf8 (void)
175 text = native_to_utf8 (_("[User ID not found]"));
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
188 get_primary_uid ( KBNODE keyblock, size_t *uidlen )
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);
208 release_keyid_list ( keyid_list_t k )
211 keyid_list_t k2 = k->next;
218 * Store the association of keyid and userid
219 * Feed only public keys to this function.
222 cache_user_id( KBNODE keyblock )
227 keyid_list_t keyids = NULL;
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] ) {
244 log_debug("cache_user_id: already in cache\n");
245 release_keyid_list ( keyids );
251 /* now put it into the cache */
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 */
265 user_id_db = r->next;
266 release_keyid_list ( r->keyids );
270 r = xmalloc( sizeof *r + uidlen-1 );
273 memcpy(r->name, uid, r->len);
274 r->next = user_id_db;
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 ) {
289 free_public_key( ce->pk );
293 pk_cache_entries = 0;
297 /* fixme: disable user id cache ? */
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 );
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);
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 )
336 #if MAX_PK_CACHE_ENTRIES
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
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 );
353 /* more init stuff */
355 pk = xmalloc_clear( sizeof *pk );
361 { struct getkey_ctx_s ctx;
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);
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 );
375 pk_from_block ( &ctx, pk, kb );
377 get_pubkey_end( &ctx );
378 release_kbnode ( kb );
383 rc = G10ERR_NO_PUBKEY;
387 cache_public_key( pk );
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)
407 #if MAX_PK_CACHE_ENTRIES
408 { /* Try to get it from the cache */
411 for (ce = pk_cache; ce; ce = ce->next)
413 if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
416 copy_public_key (pk, ce->pk);
424 rc = keydb_search_kid (hd, keyid);
428 return G10ERR_NO_PUBKEY;
430 rc = keydb_get_keyblock (hd, &keyblock);
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 );
447 release_kbnode (keyblock);
449 /* Not caching key here since it won't have all of the fields
457 get_pubkeyblock( u32 *keyid )
459 struct getkey_ctx_s ctx;
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);
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;
481 * Get a secret key and store it into sk
484 get_seckey( PKT_secret_key *sk, u32 *keyid )
487 struct getkey_ctx_s ctx;
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);
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 );
502 sk_from_block ( &ctx, sk, kb );
504 get_seckey_end( &ctx );
505 release_kbnode ( kb );
508 /* check the secret key (this may prompt for a passprase to
509 * unlock the secret key
511 rc = check_secret_key( sk, 0 );
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 )
529 KEYDB_HANDLE hd = keydb_new (1);
531 rc = keydb_search_kid (hd, keyid);
533 rc = G10ERR_NO_SECKEY;
540 * Return the type of the user id:
542 * Please use the constants KEYDB_SERCH_MODE_xxx
543 * 0 = Invalid user ID
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)
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
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 )
590 KEYDB_SEARCH_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++ )
604 case 0: /* empty string is an error */
608 case '.': /* an email address, compare from end */
609 mode = KEYDB_SEARCH_MODE_MAILEND;
615 case '<': /* an email address */
616 mode = KEYDB_SEARCH_MODE_MAIL;
620 case '@': /* part of an email address */
621 mode = KEYDB_SEARCH_MODE_MAILSUB;
626 case '=': /* exact compare */
627 mode = KEYDB_SEARCH_MODE_EXACT;
632 case '*': /* case insensitive substring search */
633 mode = KEYDB_SEARCH_MODE_SUBSTR;
639 case '+': /* compare individual words */
640 mode = KEYDB_SEARCH_MODE_WORDS;
646 case '#': /* local user id */
647 return 0; /* This is now obsolete and can't not be used anymore*/
649 case ':': /*Unified fingerprint */
654 se = strchr( ++s,':');
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);
668 mode = KEYDB_SEARCH_MODE_FPR;
672 case '&': /* keygrip */
673 return 0; /* Not yet implememted. */
676 if (s[0] == '0' && s[1] == 'x') {
681 hexlength = strspn(s, "0123456789abcdefABCDEF");
682 if (hexlength >= 8 && s[hexlength] =='!') {
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. */
699 || (!hexprefix && hexlength == 9 && *s == '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')) {
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
720 /* md5 fingerprint */
724 memset(desc->u.fpr+16, 0, 4);
725 for (i=0; i < 16; i++, s+=2) {
726 int c = hextobyte(s);
731 mode = KEYDB_SEARCH_MODE_FPR16;
733 else if (hexlength == 40 || (!hexprefix && hexlength == 41
735 /* sha1/rmd160 fingerprint */
739 for (i=0; i < 20; i++, s+=2) {
740 int c = hextobyte(s);
745 mode = KEYDB_SEARCH_MODE_FPR20;
748 if (hexprefix) /* This was a hex number with a prefix */
749 return 0; /* and a wrong length */
753 mode = KEYDB_SEARCH_MODE_SUBSTR; /* default mode */
763 skip_unusable (void *dummy, u32 *keyid, PKT_user_id *uid)
770 keyblock=get_pubkeyblock(keyid);
773 log_error("error checking usability status of %s\n",keystr(keyid));
777 /* Is the user ID in question revoked/expired? */
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))
798 unusable=pk_is_disabled(keyblock->pkt->pkt.public_key);
801 release_kbnode(keyblock);
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
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 )
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 */
837 ctx = xmalloc_clear (sizeof *ctx);
839 ctx->items[0].mode=KEYDB_SEARCH_MODE_FIRST;
840 if(!include_unusable)
841 ctx->items[0].skipfnc=skip_unusable;
845 /* build the search context */
846 for(n=0, r=namelist; r; r = r->next )
849 ctx = xmalloc_clear (sizeof *ctx + (n-1)*sizeof ctx->items );
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)
858 if (!ctx->items[n].mode)
861 return G10ERR_INV_USER_ID;
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);
879 ctx->req_algo = sk->req_algo;
880 ctx->req_usage = sk->req_usage;
882 rc = lookup( ctx, ret_kb, 1 );
884 sk_from_block ( ctx, sk, *ret_kb );
889 ctx->req_algo = pk->req_algo;
890 ctx->req_usage = pk->req_usage;
892 rc = lookup( ctx, ret_kb, 0 );
894 pk_from_block ( ctx, pk, *ret_kb );
898 release_kbnode ( help_kb );
900 if (retctx) /* caller wants the context */
904 *ret_kdbhd = ctx->kr_handle;
905 ctx->kr_handle = NULL;
907 get_pubkey_end (ctx);
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,
929 strlist_t namelist = NULL;
933 int anylocalfirst = 0;
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. */
951 for (akl=opt.auto_key_locate; akl; akl=akl->next)
952 if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
957 for (akl=opt.auto_key_locate; akl; akl=akl->next)
958 if (akl->type != AKL_NODEFAULT)
960 if (akl->type == AKL_LOCAL)
969 if (nodefault && is_mbox)
971 /* Nodefault but a mailbox - let the AKL locate the key. */
972 rc = G10ERR_NO_PUBKEY;
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;
989 int did_key_byname = 0;
990 int no_fingerprint = 0;
991 const char *mechanism = "?";
996 /* This is a dummy mechanism. */
998 rc = G10ERR_NO_PUBKEY;
1002 mechanism = "Local";
1006 get_pubkey_end (*retctx);
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);
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--;
1024 glo_ctrl.in_auto_key_retrieve++;
1025 rc=keyserver_import_pka(name,&fpr,&fpr_len);
1026 glo_ctrl.in_auto_key_retrieve--;
1031 glo_ctrl.in_auto_key_retrieve++;
1032 rc=keyserver_import_ldap(name,&fpr,&fpr_len);
1033 glo_ctrl.in_auto_key_retrieve--;
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. */
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--;
1050 mechanism = "Unconfigured keyserver";
1051 rc = G10ERR_NO_PUBKEY;
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--;
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. */
1077 char fpr_string[MAX_FINGERPRINT_LEN*2+1];
1079 assert(fpr_len<=MAX_FINGERPRINT_LEN);
1081 free_strlist(namelist);
1084 bin2hex (fpr, fpr_len, fpr_string);
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)
1094 rc = G10ERR_NO_PUBKEY;
1099 if (!rc && !did_key_byname)
1103 get_pubkey_end (*retctx);
1106 rc = key_byname (anylocalfirst?retctx:NULL,
1107 namelist, pk, NULL, 0,
1108 include_unusable, ret_keyblock, ret_kdbhd);
1113 log_info (_("automatically retrieved `%s' via %s\n"),
1117 if (rc != G10ERR_NO_PUBKEY || opt.verbose || no_fingerprint)
1118 log_info (_("error retrieving `%s' via %s: %s\n"),
1120 no_fingerprint? _("No fingerprint"):g10_errstr(rc));
1127 get_pubkey_end (*retctx);
1131 if (retctx && *retctx)
1133 assert (!(*retctx)->extra_list);
1134 (*retctx)->extra_list = namelist;
1137 free_strlist (namelist);
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 )
1154 rc = lookup( ctx, ret_keyblock, 0 );
1155 if ( !rc && pk && ret_keyblock )
1156 pk_from_block ( ctx, pk, *ret_keyblock );
1162 get_pubkey_end( GETKEY_CTX 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 )
1175 * Search for a key with the given fingerprint.
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)
1186 if( fprint_len == 20 || fprint_len == 16 ) {
1187 struct getkey_ctx_s ctx;
1190 memset( &ctx, 0, sizeof ctx );
1192 ctx.not_allocated = 1;
1193 ctx.kr_handle = keydb_new (0);
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 );
1200 pk_from_block ( &ctx, pk, kb );
1201 release_kbnode ( kb );
1202 get_pubkey_end( &ctx );
1205 rc = G10ERR_GENERAL; /* Oops */
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
1216 get_pubkey_byfprint_fast (PKT_public_key *pk,
1217 const byte *fprint, size_t fprint_len)
1222 byte fprbuf[MAX_FINGERPRINT_LEN];
1225 for (i=0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
1226 fprbuf[i] = fprint[i];
1227 while (i < MAX_FINGERPRINT_LEN)
1231 rc = keydb_search_fpr (hd, fprbuf);
1235 return G10ERR_NO_PUBKEY;
1237 rc = keydb_get_keyblock (hd, &keyblock);
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 );
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
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,
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);
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 );
1281 rc = G10ERR_GENERAL; /* Oops */
1288 * Get a secret key by name and store it into sk
1289 * If NAME is NULL use the default key
1292 get_seckey_byname2( GETKEY_CTX *retctx,
1293 PKT_secret_key *sk, const char *name, int unprotect,
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 );
1305 add_to_strlist( &namelist, name );
1309 rc = key_byname( retctx, namelist, NULL, sk, 1, include_unusable,
1312 free_strlist( namelist );
1314 if( !rc && unprotect )
1315 rc = check_secret_key( sk, 0 );
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 )
1340 rc = lookup( ctx, ret_keyblock, 1 );
1341 if ( !rc && sk && ret_keyblock )
1342 sk_from_block ( ctx, sk, *ret_keyblock );
1349 get_seckey_end( GETKEY_CTX ctx )
1351 get_pubkey_end( ctx );
1356 * Search for a key with the given fingerprint.
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)
1367 if( fprint_len == 20 || fprint_len == 16 ) {
1368 struct getkey_ctx_s ctx;
1371 memset( &ctx, 0, sizeof ctx );
1373 ctx.not_allocated = 1;
1374 ctx.kr_handle = keydb_new (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 );
1381 sk_from_block ( &ctx, sk, kb );
1382 release_kbnode ( kb );
1383 get_seckey_end( &ctx );
1386 rc = G10ERR_GENERAL; /* Oops */
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,
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);
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);
1419 /************************************************
1420 ************* Merging stuff ********************
1421 ************************************************/
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.
1433 merge_keys_and_selfsig( KBNODE keyblock )
1435 PKT_public_key *pk = NULL;
1436 PKT_secret_key *sk = NULL;
1439 u32 kid[2] = { 0, 0 };
1442 if (keyblock && keyblock->pkt->pkttype == PKT_PUBLIC_KEY ) {
1443 /* divert to our new function */
1444 merge_selfsigs (keyblock);
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 );*/
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 )
1468 else if( k->pkt->pkttype == PKT_SECRET_KEY )
1469 keyid_from_sk( sk, kid );
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
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
1487 p = parse_sig_subpkt( sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL );
1489 ed = p? pk->timestamp + buffer_to_u32(p):0;
1490 if( sig->timestamp > sigdate ) {
1491 pk->expiredate = ed;
1492 sigdate = sig->timestamp;
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;
1515 parse_key_usage(PKT_signature *sig)
1522 p=parse_sig_subpkt(sig->hashed,SIGSUBPKT_KEY_FLAGS,&n);
1525 /* first octet of the keyflags */
1530 key_usage |= PUBKEY_USAGE_CERT;
1536 key_usage |= PUBKEY_USAGE_SIG;
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);
1550 key_usage |= PUBKEY_USAGE_AUTH;
1555 key_usage |= PUBKEY_USAGE_UNKNOWN;
1558 key_usage |= PUBKEY_USAGE_NONE;
1560 else if (p) /* Key flags of length zero. */
1561 key_usage |= PUBKEY_USAGE_NONE;
1563 /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
1564 capability that we do not handle. This serves to distinguish
1565 between a zero key usage which we handle as the default
1566 capabilities for that algorithm, and a usage that we do not
1567 handle. Likewise we use PUBKEY_USAGE_NONE to indicate that
1568 key_flags have been given but they do not specify any usage. */
1574 * Apply information from SIGNODE (which is the valid self-signature
1575 * associated with that UID) to the UIDNODE:
1576 * - wether the UID has been revoked
1577 * - assumed creation date of the UID
1578 * - temporary store the keyflags here
1579 * - temporary store the key expiration time here
1580 * - mark whether the primary user ID flag hat been set.
1581 * - store the preferences
1584 fixup_uidnode ( KBNODE uidnode, KBNODE signode, u32 keycreated )
1586 PKT_user_id *uid = uidnode->pkt->pkt.user_id;
1587 PKT_signature *sig = signode->pkt->pkt.signature;
1588 const byte *p, *sym, *hash, *zip;
1589 size_t n, nsym, nhash, nzip;
1591 sig->flags.chosen_selfsig = 1; /* we chose this one */
1592 uid->created = 0; /* not created == invalid */
1593 if ( IS_UID_REV ( sig ) )
1595 uid->is_revoked = 1;
1596 return; /* has been revoked */
1599 uid->is_revoked = 0;
1601 uid->expiredate = sig->expiredate;
1603 if (sig->flags.expired)
1605 uid->is_expired = 1;
1606 return; /* has expired */
1609 uid->is_expired = 0;
1611 uid->created = sig->timestamp; /* this one is okay */
1612 uid->selfsigversion = sig->version;
1613 /* If we got this far, it's not expired :) */
1614 uid->is_expired = 0;
1616 /* store the key flags in the helper variable for later processing */
1617 uid->help_key_usage=parse_key_usage(sig);
1619 /* ditto for the key expiration */
1620 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1621 if( p && buffer_to_u32(p) )
1622 uid->help_key_expire = keycreated + buffer_to_u32(p);
1624 uid->help_key_expire = 0;
1626 /* Set the primary user ID flag - we will later wipe out some
1627 * of them to only have one in our keyblock */
1628 uid->is_primary = 0;
1629 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL );
1631 uid->is_primary = 2;
1632 /* We could also query this from the unhashed area if it is not in
1633 * the hased area and then later try to decide which is the better
1634 * there should be no security problem with this.
1635 * For now we only look at the hashed one.
1638 /* Now build the preferences list. These must come from the
1639 hashed section so nobody can modify the ciphers a key is
1640 willing to accept. */
1641 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_SYM, &n );
1642 sym = p; nsym = p?n:0;
1643 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_HASH, &n );
1644 hash = p; nhash = p?n:0;
1645 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_COMPR, &n );
1646 zip = p; nzip = p?n:0;
1649 n = nsym + nhash + nzip;
1653 uid->prefs = xmalloc (sizeof (*uid->prefs) * (n+1));
1655 for (; nsym; nsym--, n++) {
1656 uid->prefs[n].type = PREFTYPE_SYM;
1657 uid->prefs[n].value = *sym++;
1659 for (; nhash; nhash--, n++) {
1660 uid->prefs[n].type = PREFTYPE_HASH;
1661 uid->prefs[n].value = *hash++;
1663 for (; nzip; nzip--, n++) {
1664 uid->prefs[n].type = PREFTYPE_ZIP;
1665 uid->prefs[n].value = *zip++;
1667 uid->prefs[n].type = PREFTYPE_NONE; /* end of list marker */
1668 uid->prefs[n].value = 0;
1671 /* see whether we have the MDC feature */
1673 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
1674 if (p && n && (p[0] & 0x01))
1677 /* and the keyserver modify flag */
1678 uid->flags.ks_modify = 1;
1679 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
1680 if (p && n && (p[0] & 0x80))
1681 uid->flags.ks_modify = 0;
1685 sig_to_revoke_info(PKT_signature *sig,struct revoke_info *rinfo)
1687 rinfo->date = sig->timestamp;
1688 rinfo->algo = sig->pubkey_algo;
1689 rinfo->keyid[0] = sig->keyid[0];
1690 rinfo->keyid[1] = sig->keyid[1];
1694 merge_selfsigs_main(KBNODE keyblock, int *r_revoked, struct revoke_info *rinfo)
1696 PKT_public_key *pk = NULL;
1699 u32 sigdate, uiddate, uiddate2;
1700 KBNODE signode, uidnode, uidnode2;
1701 u32 curtime = make_timestamp ();
1702 unsigned int key_usage = 0;
1703 u32 keytimestamp = 0;
1705 int key_expire_seen = 0;
1706 byte sigversion = 0;
1709 memset(rinfo,0,sizeof(*rinfo));
1711 if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY )
1713 pk = keyblock->pkt->pkt.public_key;
1714 keytimestamp = pk->timestamp;
1716 keyid_from_pk( pk, kid );
1717 pk->main_keyid[0] = kid[0];
1718 pk->main_keyid[1] = kid[1];
1720 if ( pk->version < 4 ) {
1721 /* before v4 the key packet itself contains the expiration
1722 * date and there was no way to change it, so we start with
1723 * the one from the key packet */
1724 key_expire = pk->max_expiredate;
1725 key_expire_seen = 1;
1728 /* first pass: find the latest direct key self-signature.
1729 * We assume that the newest one overrides all others
1732 /* In case this key was already merged */
1738 sigdate = 0; /* helper to find the latest signature */
1739 for(k=keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next ) {
1740 if ( k->pkt->pkttype == PKT_SIGNATURE ) {
1741 PKT_signature *sig = k->pkt->pkt.signature;
1742 if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) {
1743 if ( check_key_signature( keyblock, k, NULL ) )
1744 ; /* signature did not verify */
1745 else if ( IS_KEY_REV (sig) ){
1746 /* key has been revoked - there is no way to override
1747 * such a revocation, so we theoretically can stop now.
1748 * We should not cope with expiration times for revocations
1749 * here because we have to assume that an attacker can
1750 * generate all kinds of signatures. However due to the
1751 * fact that the key has been revoked it does not harm
1752 * either and by continuing we gather some more info on
1756 sig_to_revoke_info(sig,rinfo);
1758 else if ( IS_KEY_SIG (sig) ) {
1759 /* Add any revocation keys onto the pk. This is
1760 particularly interesting since we normally only
1761 get data from the most recent 1F signature, but
1762 you need multiple 1F sigs to properly handle
1763 revocation keys (PGP does it this way, and a
1764 revocation key could be sensitive and hence in a
1765 different signature). */
1770 xrealloc(pk->revkey,sizeof(struct revocation_key)*
1771 (pk->numrevkeys+sig->numrevkeys));
1773 for(i=0;i<sig->numrevkeys;i++)
1774 memcpy(&pk->revkey[pk->numrevkeys++],
1776 sizeof(struct revocation_key));
1779 if( sig->timestamp >= sigdate ) {
1780 if(sig->flags.expired)
1781 ; /* signature has expired - ignore it */
1783 sigdate = sig->timestamp;
1785 if( sig->version > sigversion )
1786 sigversion = sig->version;
1795 /* Remove dupes from the revocation keys */
1799 int i,j,x,changed=0;
1801 for(i=0;i<pk->numrevkeys;i++)
1803 for(j=i+1;j<pk->numrevkeys;j++)
1805 if(memcmp(&pk->revkey[i],&pk->revkey[j],
1806 sizeof(struct revocation_key))==0)
1810 for(x=j;x<pk->numrevkeys-1;x++)
1811 pk->revkey[x]=pk->revkey[x+1];
1821 pk->revkey=xrealloc(pk->revkey,
1822 pk->numrevkeys*sizeof(struct revocation_key));
1827 /* some information from a direct key signature take precedence
1828 * over the same information given in UID sigs.
1830 PKT_signature *sig = signode->pkt->pkt.signature;
1833 key_usage=parse_key_usage(sig);
1835 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1836 if( p && buffer_to_u32(p) )
1838 key_expire = keytimestamp + buffer_to_u32(p);
1839 key_expire_seen = 1;
1842 /* mark that key as valid: one direct key signature should
1843 * render a key as valid */
1847 /* pass 1.5: look for key revocation signatures that were not made
1848 by the key (i.e. did a revocation key issue a revocation for
1849 us?). Only bother to do this if there is a revocation key in
1850 the first place and we're not revoked already. */
1852 if(!*r_revoked && pk->revkey)
1853 for(k=keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next )
1855 if ( k->pkt->pkttype == PKT_SIGNATURE )
1857 PKT_signature *sig = k->pkt->pkt.signature;
1859 if(IS_KEY_REV(sig) &&
1860 (sig->keyid[0]!=kid[0] || sig->keyid[1]!=kid[1]))
1862 int rc=check_revocation_keys(pk,sig);
1866 sig_to_revoke_info(sig,rinfo);
1867 /* don't continue checking since we can't be any
1868 more revoked than this */
1871 else if(rc==G10ERR_NO_PUBKEY)
1872 pk->maybe_revoked=1;
1874 /* A failure here means the sig did not verify, was
1875 not issued by a revocation key, or a revocation
1876 key loop was broken. If a revocation key isn't
1877 findable, however, the key might be revoked and
1878 we don't know it. */
1880 /* TODO: In the future handle subkey and cert
1881 revocations? PGP doesn't, but it's in 2440. */
1886 /* second pass: look at the self-signature of all user IDs */
1887 signode = uidnode = NULL;
1888 sigdate = 0; /* helper to find the latest signature in one user ID */
1889 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next ) {
1890 if ( k->pkt->pkttype == PKT_USER_ID ) {
1891 if ( uidnode && signode )
1893 fixup_uidnode ( uidnode, signode, keytimestamp );
1900 else if ( k->pkt->pkttype == PKT_SIGNATURE && uidnode ) {
1901 PKT_signature *sig = k->pkt->pkt.signature;
1902 if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) {
1903 if ( check_key_signature( keyblock, k, NULL ) )
1904 ; /* signature did not verify */
1905 else if ( (IS_UID_SIG (sig) || IS_UID_REV (sig))
1906 && sig->timestamp >= sigdate )
1908 /* Note: we allow to invalidate cert revocations
1909 * by a newer signature. An attacker can't use this
1910 * because a key should be revoced with a key revocation.
1911 * The reason why we have to allow for that is that at
1912 * one time an email address may become invalid but later
1913 * the same email address may become valid again (hired,
1914 * fired, hired again).
1917 sigdate = sig->timestamp;
1919 signode->pkt->pkt.signature->flags.chosen_selfsig=0;
1920 if( sig->version > sigversion )
1921 sigversion = sig->version;
1926 if ( uidnode && signode ) {
1927 fixup_uidnode ( uidnode, signode, keytimestamp );
1931 /* If the key isn't valid yet, and we have
1932 --allow-non-selfsigned-uid set, then force it valid. */
1933 if(!pk->is_valid && opt.allow_non_selfsigned_uid)
1936 log_info(_("Invalid key %s made valid by"
1937 " --allow-non-selfsigned-uid\n"),keystr_from_pk(pk));
1941 /* The key STILL isn't valid, so try and find an ultimately
1942 trusted signature. */
1947 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k=k->next)
1949 if ( k->pkt->pkttype == PKT_USER_ID )
1951 else if ( k->pkt->pkttype == PKT_SIGNATURE && uidnode )
1953 PKT_signature *sig = k->pkt->pkt.signature;
1955 if(sig->keyid[0] != kid[0] || sig->keyid[1]!=kid[1])
1957 PKT_public_key *ultimate_pk;
1959 ultimate_pk=xmalloc_clear(sizeof(*ultimate_pk));
1961 /* We don't want to use the full get_pubkey to
1962 avoid infinite recursion in certain cases.
1963 There is no reason to check that an ultimately
1964 trusted key is still valid - if it has been
1965 revoked or the user should also renmove the
1966 ultimate trust flag. */
1967 if(get_pubkey_fast(ultimate_pk,sig->keyid)==0
1968 && check_key_signature2(keyblock,k,ultimate_pk,
1969 NULL,NULL,NULL,NULL)==0
1970 && get_ownertrust(ultimate_pk)==TRUST_ULTIMATE)
1972 free_public_key(ultimate_pk);
1977 free_public_key(ultimate_pk);
1983 /* Record the highest selfsig version so we know if this is a v3
1984 key through and through, or a v3 key with a v4 selfsig
1985 somewhere. This is useful in a few places to know if the key
1986 must be treated as PGP2-style or OpenPGP-style. Note that a
1987 selfsig revocation with a higher version number will also raise
1988 this value. This is okay since such a revocation must be
1989 issued by the user (i.e. it cannot be issued by someone else to
1990 modify the key behavior.) */
1992 pk->selfsigversion=sigversion;
1994 /* Now that we had a look at all user IDs we can now get some information
1995 * from those user IDs.
1999 /* find the latest user ID with key flags set */
2000 uiddate = 0; /* helper to find the latest user ID */
2001 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2003 if ( k->pkt->pkttype == PKT_USER_ID ) {
2004 PKT_user_id *uid = k->pkt->pkt.user_id;
2005 if ( uid->help_key_usage && uid->created > uiddate ) {
2006 key_usage = uid->help_key_usage;
2007 uiddate = uid->created;
2012 if ( !key_usage ) { /* no key flags at all: get it from the algo */
2013 key_usage = openpgp_pk_algo_usage ( pk->pubkey_algo );
2015 else { /* check that the usage matches the usage as given by the algo */
2016 int x = openpgp_pk_algo_usage ( pk->pubkey_algo );
2017 if ( x ) /* mask it down to the actual allowed usage */
2021 /* Whatever happens, it's a primary key, so it can certify. */
2022 pk->pubkey_usage = key_usage|PUBKEY_USAGE_CERT;
2024 if ( !key_expire_seen ) {
2025 /* find the latest valid user ID with a key expiration set
2026 * Note, that this may be a different one from the above because
2027 * some user IDs may have no expiration date set */
2029 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2031 if ( k->pkt->pkttype == PKT_USER_ID ) {
2032 PKT_user_id *uid = k->pkt->pkt.user_id;
2033 if ( uid->help_key_expire && uid->created > uiddate ) {
2034 key_expire = uid->help_key_expire;
2035 uiddate = uid->created;
2041 /* Currently only v3 keys have a maximum expiration date, but I'll
2042 bet v5 keys get this feature again. */
2043 if(key_expire==0 || (pk->max_expiredate && key_expire>pk->max_expiredate))
2044 key_expire=pk->max_expiredate;
2046 pk->has_expired = key_expire >= curtime? 0 : key_expire;
2047 pk->expiredate = key_expire;
2049 /* Fixme: we should see how to get rid of the expiretime fields but
2050 * this needs changes at other places too. */
2052 /* and now find the real primary user ID and delete all others */
2053 uiddate = uiddate2 = 0;
2054 uidnode = uidnode2 = NULL;
2055 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next ) {
2056 if ( k->pkt->pkttype == PKT_USER_ID &&
2057 !k->pkt->pkt.user_id->attrib_data) {
2058 PKT_user_id *uid = k->pkt->pkt.user_id;
2059 if (uid->is_primary)
2061 if(uid->created > uiddate)
2063 uiddate = uid->created;
2066 else if(uid->created==uiddate && uidnode)
2068 /* The dates are equal, so we need to do a
2069 different (and arbitrary) comparison. This
2070 should rarely, if ever, happen. It's good to
2071 try and guarantee that two different GnuPG
2072 users with two different keyrings at least pick
2073 the same primary. */
2074 if(cmp_user_ids(uid,uidnode->pkt->pkt.user_id)>0)
2080 if(uid->created > uiddate2)
2082 uiddate2 = uid->created;
2085 else if(uid->created==uiddate2 && uidnode2)
2087 if(cmp_user_ids(uid,uidnode2->pkt->pkt.user_id)>0)
2094 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2096 if ( k->pkt->pkttype == PKT_USER_ID &&
2097 !k->pkt->pkt.user_id->attrib_data) {
2098 PKT_user_id *uid = k->pkt->pkt.user_id;
2100 uid->is_primary = 0;
2104 else if( uidnode2 ) {
2105 /* none is flagged primary - use the latest user ID we have,
2106 and disambiguate with the arbitrary packet comparison. */
2107 uidnode2->pkt->pkt.user_id->is_primary = 1;
2111 /* None of our uids were self-signed, so pick the one that
2112 sorts first to be the primary. This is the best we can do
2113 here since there are no self sigs to date the uids. */
2117 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2120 if(k->pkt->pkttype==PKT_USER_ID
2121 && !k->pkt->pkt.user_id->attrib_data)
2126 uidnode->pkt->pkt.user_id->is_primary=1;
2131 if(cmp_user_ids(k->pkt->pkt.user_id,
2132 uidnode->pkt->pkt.user_id)>0)
2134 uidnode->pkt->pkt.user_id->is_primary=0;
2136 uidnode->pkt->pkt.user_id->is_primary=1;
2139 k->pkt->pkt.user_id->is_primary=0; /* just to be
2147 /* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
2148 Caller must free the signature when they are done. */
2149 static PKT_signature *
2150 buf_to_sig(const byte *buf,size_t len)
2152 PKT_signature *sig=xmalloc_clear(sizeof(PKT_signature));
2153 IOBUF iobuf=iobuf_temp_with_content(buf,len);
2154 int save_mode=set_packet_list_mode(0);
2156 if(parse_signature(iobuf,PKT_SIGNATURE,len,sig)!=0)
2162 set_packet_list_mode(save_mode);
2169 merge_selfsigs_subkey( KBNODE keyblock, KBNODE subnode )
2171 PKT_public_key *mainpk = NULL, *subpk = NULL;
2177 u32 curtime = make_timestamp ();
2178 unsigned int key_usage = 0;
2179 u32 keytimestamp = 0;
2183 if ( subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY )
2185 mainpk = keyblock->pkt->pkt.public_key;
2186 if ( mainpk->version < 4 )
2187 return; /* (actually this should never happen) */
2188 keyid_from_pk( mainpk, mainkid );
2189 subpk = subnode->pkt->pkt.public_key;
2190 keytimestamp = subpk->timestamp;
2192 subpk->is_valid = 0;
2193 subpk->main_keyid[0] = mainpk->main_keyid[0];
2194 subpk->main_keyid[1] = mainpk->main_keyid[1];
2196 /* find the latest key binding self-signature. */
2198 sigdate = 0; /* helper to find the latest signature */
2199 for(k=subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2201 if ( k->pkt->pkttype == PKT_SIGNATURE ) {
2202 sig = k->pkt->pkt.signature;
2203 if ( sig->keyid[0] == mainkid[0] && sig->keyid[1]==mainkid[1] ) {
2204 if ( check_key_signature( keyblock, k, NULL ) )
2205 ; /* signature did not verify */
2206 else if ( IS_SUBKEY_REV (sig) ) {
2207 /* Note that this means that the date on a
2208 revocation sig does not matter - even if the
2209 binding sig is dated after the revocation sig,
2210 the subkey is still marked as revoked. This
2211 seems ok, as it is just as easy to make new
2212 subkeys rather than re-sign old ones as the
2213 problem is in the distribution. Plus, PGP (7)
2214 does this the same way. */
2215 subpk->is_revoked = 1;
2216 sig_to_revoke_info(sig,&subpk->revoked);
2217 /* although we could stop now, we continue to
2218 * figure out other information like the old expiration
2221 else if ( IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate )
2223 if(sig->flags.expired)
2224 ; /* signature has expired - ignore it */
2227 sigdate = sig->timestamp;
2229 signode->pkt->pkt.signature->flags.chosen_selfsig=0;
2236 /* no valid key binding */
2240 sig = signode->pkt->pkt.signature;
2241 sig->flags.chosen_selfsig=1; /* so we know which selfsig we chose later */
2243 key_usage=parse_key_usage(sig);
2246 /* no key flags at all: get it from the algo */
2247 key_usage = openpgp_pk_algo_usage ( subpk->pubkey_algo );
2251 /* check that the usage matches the usage as given by the algo */
2252 int x = openpgp_pk_algo_usage ( subpk->pubkey_algo );
2253 if ( x ) /* mask it down to the actual allowed usage */
2257 subpk->pubkey_usage = key_usage;
2259 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
2260 if ( p && buffer_to_u32(p) )
2261 key_expire = keytimestamp + buffer_to_u32(p);
2264 subpk->has_expired = key_expire >= curtime? 0 : key_expire;
2265 subpk->expiredate = key_expire;
2267 /* algo doesn't exist */
2268 if(openpgp_pk_test_algo(subpk->pubkey_algo))
2271 subpk->is_valid = 1;
2273 /* Find the most recent 0x19 embedded signature on our self-sig. */
2274 if(subpk->backsig==0)
2278 PKT_signature *backsig=NULL;
2282 /* We do this while() since there may be other embedded
2283 signatures in the future. We only want 0x19 here. */
2285 while((p=enum_sig_subpkt(sig->hashed,
2286 SIGSUBPKT_SIGNATURE,&n,&seq,NULL)))
2287 if(n>3 && ((p[0]==3 && p[2]==0x19) || (p[0]==4 && p[1]==0x19)))
2289 PKT_signature *tempsig=buf_to_sig(p,n);
2292 if(tempsig->timestamp>sigdate)
2295 free_seckey_enc(backsig);
2298 sigdate=backsig->timestamp;
2301 free_seckey_enc(tempsig);
2307 /* It is safe to have this in the unhashed area since the 0x19
2308 is located on the selfsig for convenience, not security. */
2310 while((p=enum_sig_subpkt(sig->unhashed,SIGSUBPKT_SIGNATURE,
2312 if(n>3 && ((p[0]==3 && p[2]==0x19) || (p[0]==4 && p[1]==0x19)))
2314 PKT_signature *tempsig=buf_to_sig(p,n);
2317 if(tempsig->timestamp>sigdate)
2320 free_seckey_enc(backsig);
2323 sigdate=backsig->timestamp;
2326 free_seckey_enc(tempsig);
2332 /* At ths point, backsig contains the most recent 0x19 sig.
2333 Let's see if it is good. */
2335 /* 2==valid, 1==invalid, 0==didn't check */
2336 if(check_backsig(mainpk,subpk,backsig)==0)
2341 free_seckey_enc(backsig);
2348 * Merge information from the self-signatures with the key, so that
2349 * we can later use them more easy.
2350 * The function works by first applying the self signatures to the
2351 * primary key and the to each subkey.
2352 * Here are the rules we use to decide which inormation from which
2353 * self-signature is used:
2354 * We check all self signatures or validity and ignore all invalid signatures.
2355 * All signatures are then ordered by their creation date ....
2356 * For the primary key:
2360 merge_selfsigs( KBNODE keyblock )
2364 struct revoke_info rinfo;
2365 PKT_public_key *main_pk;
2369 if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY ) {
2370 if (keyblock->pkt->pkttype == PKT_SECRET_KEY ) {
2371 log_error ("expected public key but found secret key "
2373 /* we better exit here becuase a public key is expected at
2374 other places too. FIXME: Figure this out earlier and
2375 don't get to here at all */
2381 merge_selfsigs_main ( keyblock, &revoked, &rinfo );
2383 /* now merge in the data from each of the subkeys */
2384 for(k=keyblock; k; k = k->next ) {
2385 if ( k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2386 merge_selfsigs_subkey ( keyblock, k );
2390 main_pk = keyblock->pkt->pkt.public_key;
2391 if ( revoked || main_pk->has_expired || !main_pk->is_valid ) {
2392 /* if the primary key is revoked, expired, or invalid we
2393 * better set the appropriate flags on that key and all
2395 for(k=keyblock; k; k = k->next ) {
2396 if ( k->pkt->pkttype == PKT_PUBLIC_KEY
2397 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2398 PKT_public_key *pk = k->pkt->pkt.public_key;
2399 if(!main_pk->is_valid)
2401 if(revoked && !pk->is_revoked)
2403 pk->is_revoked = revoked;
2404 memcpy(&pk->revoked,&rinfo,sizeof(rinfo));
2406 if(main_pk->has_expired)
2407 pk->has_expired = main_pk->has_expired;
2413 /* set the preference list of all keys to those of the primary real
2414 * user ID. Note: we use these preferences when we don't know by
2415 * which user ID the key has been selected.
2416 * fixme: we should keep atoms of commonly used preferences or
2417 * use reference counting to optimize the preference lists storage.
2418 * FIXME: it might be better to use the intersection of
2420 * Do a similar thing for the MDC feature flag.
2424 for (k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) {
2425 if (k->pkt->pkttype == PKT_USER_ID
2426 && !k->pkt->pkt.user_id->attrib_data
2427 && k->pkt->pkt.user_id->is_primary) {
2428 prefs = k->pkt->pkt.user_id->prefs;
2429 mdc_feature = k->pkt->pkt.user_id->flags.mdc;
2433 for(k=keyblock; k; k = k->next ) {
2434 if ( k->pkt->pkttype == PKT_PUBLIC_KEY
2435 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2436 PKT_public_key *pk = k->pkt->pkt.public_key;
2439 pk->prefs = copy_prefs (prefs);
2440 pk->mdc_feature = mdc_feature;
2447 * Merge the secret keys from secblock into the pubblock thereby
2448 * replacing the public (sub)keys with their secret counterparts Hmmm:
2449 * It might be better to get away from the concept of entire secret
2450 * keys at all and have a way to store just the real secret parts
2454 merge_public_with_secret ( KBNODE pubblock, KBNODE secblock )
2458 assert ( pubblock->pkt->pkttype == PKT_PUBLIC_KEY );
2459 assert ( secblock->pkt->pkttype == PKT_SECRET_KEY );
2461 for (pub=pubblock; pub; pub = pub->next ) {
2462 if ( pub->pkt->pkttype == PKT_PUBLIC_KEY ) {
2463 PKT_public_key *pk = pub->pkt->pkt.public_key;
2464 PKT_secret_key *sk = secblock->pkt->pkt.secret_key;
2465 assert ( pub == pubblock ); /* only in the first node */
2466 /* there is nothing to compare in this case, so just replace
2467 * some information */
2468 copy_public_parts_to_secret_key ( pk, sk );
2469 free_public_key ( pk );
2470 pub->pkt->pkttype = PKT_SECRET_KEY;
2471 pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
2473 else if ( pub->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2475 PKT_public_key *pk = pub->pkt->pkt.public_key;
2477 /* this is more complicated: it may happen that the sequence
2478 * of the subkeys dosn't match, so we have to find the
2479 * appropriate secret key */
2480 for (sec=secblock->next; sec; sec = sec->next ) {
2481 if ( sec->pkt->pkttype == PKT_SECRET_SUBKEY ) {
2482 PKT_secret_key *sk = sec->pkt->pkt.secret_key;
2483 if ( !cmp_public_secret_key ( pk, sk ) ) {
2484 copy_public_parts_to_secret_key ( pk, sk );
2485 free_public_key ( pk );
2486 pub->pkt->pkttype = PKT_SECRET_SUBKEY;
2487 pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
2493 BUG(); /* already checked in premerge */
2498 /* This function checks that for every public subkey a corresponding
2499 * secret subkey is available and deletes the public subkey otherwise.
2500 * We need this function because we can't delete it later when we
2501 * actually merge the secret parts into the pubring.
2502 * The function also plays some games with the node flags.
2505 premerge_public_with_secret ( KBNODE pubblock, KBNODE secblock )
2509 assert ( pubblock->pkt->pkttype == PKT_PUBLIC_KEY );
2510 assert ( secblock->pkt->pkttype == PKT_SECRET_KEY );
2512 for (pub=pubblock,last=NULL; pub; last = pub, pub = pub->next ) {
2513 pub->flag &= ~3; /* reset bits 0 and 1 */
2514 if ( pub->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
2516 PKT_public_key *pk = pub->pkt->pkt.public_key;
2518 for (sec=secblock->next; sec; sec = sec->next ) {
2519 if ( sec->pkt->pkttype == PKT_SECRET_SUBKEY ) {
2520 PKT_secret_key *sk = sec->pkt->pkt.secret_key;
2521 if ( !cmp_public_secret_key ( pk, sk ) ) {
2522 if ( sk->protect.s2k.mode == 1001 ) {
2523 /* The secret parts are not available so
2524 we can't use that key for signing etc.
2525 Fix the pubkey usage */
2526 pk->pubkey_usage &= ~(PUBKEY_USAGE_SIG
2527 |PUBKEY_USAGE_AUTH);
2529 /* transfer flag bits 0 and 1 to the pubblock */
2530 pub->flag |= (sec->flag &3);
2539 log_info (_("no secret subkey"
2540 " for public subkey %s - ignoring\n"),
2541 keystr_from_pk (pk));
2542 /* we have to remove the subkey in this case */
2544 /* find the next subkey */
2545 for (next=pub->next,ll=pub;
2546 next && next->pkt->pkttype != PKT_PUBLIC_SUBKEY;
2547 ll = next, next = next->next )
2551 /* release this public subkey with all sigs */
2553 release_kbnode( pub );
2554 /* let the loop continue */
2559 /* We need to copy the found bits (0 and 1) from the secret key to
2560 the public key. This has already been done for the subkeys but
2561 got lost on the primary key - fix it here *. */
2562 pubblock->flag |= (secblock->flag & 3);
2568 /* See see whether the key fits
2569 * our requirements and in case we do not
2570 * request the primary key, we should select
2571 * a suitable subkey.
2572 * FIXME: Check against PGP 7 whether we still need a kludge
2573 * to favor type 16 keys over type 20 keys when type 20
2574 * has not been explitely requested.
2575 * Returns: True when a suitable key has been found.
2577 * We have to distinguish four cases: FIXME!
2578 * 1. No usage and no primary key requested
2579 * Examples for this case are that we have a keyID to be used
2580 * for decrytion or verification.
2581 * 2. No usage but primary key requested
2582 * This is the case for all functions which work on an
2583 * entire keyblock, e.g. for editing or listing
2584 * 3. Usage and primary key requested
2586 * 4. Usage but no primary key requested
2588 * FIXME: Tell what is going to happen here and something about the rationale
2589 * Note: We don't use this function if no specific usage is requested;
2590 * This way the getkey functions can be used for plain key listings.
2592 * CTX ist the keyblock we are investigating, if FOUNDK is not NULL this
2593 * is the key we actually found by looking at the keyid or a fingerprint and
2594 * may eitehr point to the primary or one of the subkeys.
2598 finish_lookup (GETKEY_CTX ctx)
2600 KBNODE keyblock = ctx->keyblock;
2602 KBNODE foundk = NULL;
2603 PKT_user_id *foundu = NULL;
2604 #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
2605 unsigned int req_usage = ( ctx->req_usage & USAGE_MASK );
2606 /* Request the primary if we're certifying another key, and also
2607 if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
2608 do not understand signatures made by a signing subkey. PGP 8
2610 int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) ||
2611 ((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG));
2614 u32 curtime = make_timestamp ();
2616 assert( keyblock->pkt->pkttype == PKT_PUBLIC_KEY );
2618 ctx->found_key = NULL;
2621 for (k=keyblock; k; k = k->next) {
2622 if ( (k->flag & 1) ) {
2623 assert ( k->pkt->pkttype == PKT_PUBLIC_KEY
2624 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY );
2631 for (k=keyblock; k; k = k->next) {
2632 if ( (k->flag & 2) ) {
2633 assert (k->pkt->pkttype == PKT_USER_ID);
2634 foundu = k->pkt->pkt.user_id;
2640 log_debug( "finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
2641 (ulong)keyid_from_pk( keyblock->pkt->pkt.public_key, NULL),
2642 foundk? "one":"all", req_usage);
2645 latest_key = foundk? foundk:keyblock;
2651 /* do not look at subkeys if a certification key is requested */
2652 if ((!foundk || foundk->pkt->pkttype == PKT_PUBLIC_SUBKEY) && !req_prim) {
2654 /* either start a loop or check just this one subkey */
2655 for (k=foundk?foundk:keyblock; k; k = nextk ) {
2658 if ( k->pkt->pkttype != PKT_PUBLIC_SUBKEY )
2661 nextk = NULL; /* what a hack */
2662 pk = k->pkt->pkt.public_key;
2664 log_debug( "\tchecking subkey %08lX\n",
2665 (ulong)keyid_from_pk( pk, NULL));
2666 if ( !pk->is_valid ) {
2668 log_debug( "\tsubkey not valid\n");
2671 if ( pk->is_revoked ) {
2673 log_debug( "\tsubkey has been revoked\n");
2676 if ( pk->has_expired ) {
2678 log_debug( "\tsubkey has expired\n");
2681 if ( pk->timestamp > curtime && !opt.ignore_valid_from ) {
2683 log_debug( "\tsubkey not yet valid\n");
2687 if ( !((pk->pubkey_usage&USAGE_MASK) & req_usage) ) {
2689 log_debug( "\tusage does not match: want=%x have=%x\n",
2690 req_usage, pk->pubkey_usage );
2695 log_debug( "\tsubkey might be fine\n");
2696 /* In case a key has a timestamp of 0 set, we make sure
2697 that it is used. A better change would be to compare
2698 ">=" but that might also change the selected keys and
2699 is as such a more intrusive change. */
2700 if ( pk->timestamp > latest_date
2701 || (!pk->timestamp && !latest_date)) {
2702 latest_date = pk->timestamp;
2708 /* Okay now try the primary key unless we want an exact
2709 * key ID match on a subkey */
2710 if ((!latest_key && !(ctx->exact && foundk != keyblock)) || req_prim) {
2712 if (DBG_CACHE && !foundk && !req_prim )
2713 log_debug( "\tno suitable subkeys found - trying primary\n");
2714 pk = keyblock->pkt->pkt.public_key;
2715 if ( !pk->is_valid ) {
2717 log_debug( "\tprimary key not valid\n");
2719 else if ( pk->is_revoked ) {
2721 log_debug( "\tprimary key has been revoked\n");
2723 else if ( pk->has_expired ) {
2725 log_debug( "\tprimary key has expired\n");
2727 else if ( !((pk->pubkey_usage&USAGE_MASK) & req_usage) ) {
2729 log_debug( "\tprimary key usage does not match: "
2730 "want=%x have=%x\n",
2731 req_usage, pk->pubkey_usage );
2735 log_debug( "\tprimary key may be used\n");
2736 latest_key = keyblock;
2737 latest_date = pk->timestamp;
2741 if ( !latest_key ) {
2743 log_debug("\tno suitable key found - giving up\n");
2749 log_debug( "\tusing key %08lX\n",
2750 (ulong)keyid_from_pk( latest_key->pkt->pkt.public_key, NULL) );
2753 PKT_public_key *pk = latest_key->pkt->pkt.public_key;
2755 free_user_id (pk->user_id);
2756 pk->user_id = scopy_user_id (foundu);
2759 ctx->found_key = latest_key;
2761 if (latest_key != keyblock && opt.verbose)
2764 xstrdup(keystr_from_pk(latest_key->pkt->pkt.public_key));
2765 log_info(_("using subkey %s instead of primary key %s\n"),
2766 tempkeystr, keystr_from_pk(keyblock->pkt->pkt.public_key));
2770 cache_user_id( keyblock );
2772 return 1; /* found */
2777 lookup( GETKEY_CTX ctx, KBNODE *ret_keyblock, int secmode )
2780 KBNODE secblock = NULL; /* helper */
2781 int no_suitable_key = 0;
2784 while (!(rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems))) {
2785 /* If we are searching for the first key we have to make sure
2786 that the next iteration does not do an implicit reset.
2787 This can be triggered by an empty key ring. */
2788 if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
2789 ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
2791 rc = keydb_get_keyblock (ctx->kr_handle, &ctx->keyblock);
2793 log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
2799 /* find the correspondig public key and use this
2800 * this one for the selection process */
2802 KBNODE k = ctx->keyblock;
2804 if (k->pkt->pkttype != PKT_SECRET_KEY)
2807 keyid_from_sk (k->pkt->pkt.secret_key, aki);
2808 k = get_pubkeyblock (aki);
2812 log_info(_("key %s: secret key without public key"
2813 " - skipped\n"), keystr(aki));
2816 secblock = ctx->keyblock;
2819 premerge_public_with_secret ( ctx->keyblock, secblock );
2822 /* warning: node flag bits 0 and 1 should be preserved by
2823 * merge_selfsigs. For secret keys, premerge did tranfer the
2824 * keys to the keyblock */
2825 merge_selfsigs ( ctx->keyblock );
2826 if ( finish_lookup (ctx) ) {
2827 no_suitable_key = 0;
2829 merge_public_with_secret ( ctx->keyblock,
2831 release_kbnode (secblock);
2837 no_suitable_key = 1;
2840 /* release resources and continue search */
2842 release_kbnode( secblock );
2845 release_kbnode( ctx->keyblock );
2846 ctx->keyblock = NULL;
2850 if( rc && rc != -1 )
2851 log_error("keydb_search failed: %s\n", g10_errstr(rc));
2854 *ret_keyblock = ctx->keyblock; /* return the keyblock */
2855 ctx->keyblock = NULL;
2857 else if (rc == -1 && no_suitable_key)
2858 rc = secmode ? G10ERR_UNU_SECKEY : G10ERR_UNU_PUBKEY;
2860 rc = secmode ? G10ERR_NO_SECKEY : G10ERR_NO_PUBKEY;
2863 release_kbnode( secblock );
2866 release_kbnode( ctx->keyblock );
2867 ctx->keyblock = NULL;
2877 * FIXME: Replace by the generic function
2878 * It does not work as it is right now - it is used at
2879 * 2 places: a) to get the key for an anonyous recipient
2880 * b) to get the ultimately trusted keys.
2881 * The a) usage might have some problems.
2883 * set with_subkeys true to include subkeys
2884 * set with_spm true to include secret-parts-missing keys
2886 * Enumerate all primary secret keys. Caller must use these procedure:
2887 * 1) create a void pointer and initialize it to NULL
2888 * 2) pass this void pointer by reference to this function
2889 * and provide space for the secret key (pass a buffer for sk)
2890 * 3) call this function as long as it does not return -1
2892 * 4) Always call this function a last time with SK set to NULL,
2893 * so that can free it's context.
2896 enum_secret_keys( void **context, PKT_secret_key *sk,
2897 int with_subkeys, int with_spm )
2909 if( !c ) { /* make a new context */
2910 c = xmalloc_clear( sizeof *c );
2912 c->hd = keydb_new (1);
2918 if( !sk ) { /* free the context */
2919 keydb_release (c->hd);
2920 release_kbnode (c->keyblock);
2930 /* get the next secret key from the current keyblock */
2931 for (; c->node; c->node = c->node->next) {
2932 if ((c->node->pkt->pkttype == PKT_SECRET_KEY
2934 && c->node->pkt->pkttype == PKT_SECRET_SUBKEY) )
2935 && !(c->node->pkt->pkt.secret_key->protect.s2k.mode==1001
2937 copy_secret_key (sk, c->node->pkt->pkt.secret_key );
2938 c->node = c->node->next;
2939 return 0; /* found */
2942 release_kbnode (c->keyblock);
2943 c->keyblock = c->node = NULL;
2945 rc = c->first? keydb_search_first (c->hd) : keydb_search_next (c->hd);
2948 keydb_release (c->hd); c->hd = NULL;
2950 return -1; /* eof */
2953 rc = keydb_get_keyblock (c->hd, &c->keyblock);
2954 c->node = c->keyblock;
2957 return rc; /* error */
2962 /*********************************************
2963 *********** user ID printing helpers *******
2964 *********************************************/
2967 * Return a string with a printable representation of the user_id.
2968 * this string must be freed by xfree.
2971 get_user_id_string( u32 *keyid )
2976 /* try it two times; second pass reads from key resources */
2979 for(r=user_id_db; r; r = r->next )
2982 for (a=r->keyids; a; a= a->next )
2984 if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] )
2986 p = xmalloc( keystrlen() + 1 + r->len + 1 );
2987 sprintf(p, "%s %.*s", keystr(keyid), r->len, r->name );
2992 } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
2993 p = xmalloc( keystrlen() + 5 );
2994 sprintf(p, "%s [?]", keystr(keyid));
3000 get_user_id_string_native ( u32 *keyid )
3002 char *p = get_user_id_string( keyid );
3003 char *p2 = utf8_to_native( p, strlen(p), 0 );
3010 get_long_user_id_string( u32 *keyid )
3015 /* try it two times; second pass reads from key resources */
3017 for(r=user_id_db; r; r = r->next ) {
3019 for (a=r->keyids; a; a= a->next ) {
3020 if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] ) {
3021 p = xmalloc( r->len + 20 );
3022 sprintf(p, "%08lX%08lX %.*s",
3023 (ulong)keyid[0], (ulong)keyid[1],
3029 } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
3031 sprintf(p, "%08lX%08lX [?]", (ulong)keyid[0], (ulong)keyid[1] );
3036 get_user_id( u32 *keyid, size_t *rn )
3042 /* Try it two times; second pass reads from key resources. */
3045 for (r = user_id_db; r; r = r->next)
3048 for (a = r->keyids; a; a = a->next)
3050 if (a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1])
3052 /* An empty string as user id is possible. Make
3053 sure that the malloc allocates one byte and does
3055 p = xmalloc (r->len? r->len : 1);
3056 memcpy (p, r->name, r->len);
3063 while (++pass < 2 && !get_pubkey (NULL, keyid));
3064 p = xstrdup (user_id_not_found_utf8 ());
3070 get_user_id_native( u32 *keyid )
3073 char *p = get_user_id( keyid, &rn );
3074 char *p2 = utf8_to_native( p, rn, 0 );
3080 get_ctx_handle(GETKEY_CTX ctx)
3082 return ctx->kr_handle;
3086 free_akl(struct akl *akl)
3089 free_keyserver_spec(akl->spec);
3097 while(opt.auto_key_locate)
3099 struct akl *akl2=opt.auto_key_locate;
3100 opt.auto_key_locate=opt.auto_key_locate->next;
3105 /* Returns false on error. */
3107 parse_auto_key_locate(char *options)
3111 while((tok=optsep(&options)))
3113 struct akl *akl,*check,*last=NULL;
3119 akl=xmalloc_clear(sizeof(*akl));
3121 if(ascii_strcasecmp(tok,"nodefault")==0)
3122 akl->type=AKL_NODEFAULT;
3123 else if(ascii_strcasecmp(tok,"local")==0)
3124 akl->type=AKL_LOCAL;
3125 else if(ascii_strcasecmp(tok,"ldap")==0)
3127 else if(ascii_strcasecmp(tok,"keyserver")==0)
3128 akl->type=AKL_KEYSERVER;
3130 else if(ascii_strcasecmp(tok,"cert")==0)
3134 else if(ascii_strcasecmp(tok,"pka")==0)
3137 else if((akl->spec=parse_keyserver_uri(tok,1,NULL,0)))
3145 /* We must maintain the order the user gave us */
3146 for(check=opt.auto_key_locate;check;last=check,check=check->next)
3148 /* Check for duplicates */
3149 if(check->type==akl->type
3150 && (akl->type!=AKL_SPEC
3151 || (akl->type==AKL_SPEC
3152 && strcmp(check->spec->uri,akl->spec->uri)==0)))
3165 opt.auto_key_locate=akl;