1 /* getkey.c - Get a key from the database
2 * Copyright (C) 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
4 * This file is part of GnuPG.
6 * GnuPG is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * GnuPG is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
37 #define MAX_PK_CACHE_ENTRIES 200
38 #define MAX_UID_CACHE_ENTRIES 200
40 #if MAX_PK_CACHE_ENTRIES < 2
41 #error We need the cache for key creation
49 KBNODE found_key; /* pointer into some keyblock */
53 KEYDB_HANDLE kr_handle;
56 KEYDB_SEARCH_DESC items[1];
68 typedef struct keyid_list {
69 struct keyid_list *next;
74 #if MAX_PK_CACHE_ENTRIES
75 typedef struct pk_cache_entry {
76 struct pk_cache_entry *next;
80 static pk_cache_entry_t pk_cache;
81 static int pk_cache_entries; /* number of entries in pk cache */
82 static int pk_cache_disabled;
85 #if MAX_UID_CACHE_ENTRIES < 5
86 #error we really need the userid cache
88 typedef struct user_id_db {
89 struct user_id_db *next;
94 static user_id_db_t user_id_db;
95 static int uid_cache_entries; /* number of entries in uid cache */
97 static void merge_selfsigs( KBNODE keyblock );
98 static int lookup( GETKEY_CTX ctx, KBNODE *ret_keyblock, int secmode );
99 static int check_revocation_keys(PKT_public_key *pk,PKT_signature *sig);
106 for(i=0; i < DIM(lkup_stats); i++ ) {
107 if( lkup_stats[i].any )
109 "lookup stats: mode=%-2d ok=%-6d nokey=%-6d err=%-6d\n",
111 lkup_stats[i].okay_count,
112 lkup_stats[i].nokey_count,
113 lkup_stats[i].error_count );
120 cache_public_key( PKT_public_key *pk )
122 #if MAX_PK_CACHE_ENTRIES
126 if( pk_cache_disabled )
132 if( is_ELGAMAL(pk->pubkey_algo)
133 || pk->pubkey_algo == PUBKEY_ALGO_DSA
134 || is_RSA(pk->pubkey_algo) ) {
135 keyid_from_pk( pk, keyid );
138 return; /* don't know how to get the keyid */
140 for( ce = pk_cache; ce; ce = ce->next )
141 if( ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1] ) {
143 log_debug("cache_public_key: already in cache\n");
147 if( pk_cache_entries >= MAX_PK_CACHE_ENTRIES ) {
148 /* fixme: use another algorithm to free some cache slots */
150 if( opt.verbose > 1 )
151 log_info(_("too many entries in pk cache - disabled\n"));
155 ce = m_alloc( sizeof *ce );
158 ce->pk = copy_public_key( NULL, pk );
159 ce->keyid[0] = keyid[0];
160 ce->keyid[1] = keyid[1];
166 * Return the user ID from the given keyblock.
167 * We use the primary uid flag which has been set by the merge_selfsigs
168 * function. The returned value is only valid as long as then given
169 * keyblock is not changed
172 get_primary_uid ( KBNODE keyblock, size_t *uidlen )
177 for (k=keyblock; k; k=k->next ) {
178 if ( k->pkt->pkttype == PKT_USER_ID
179 && !k->pkt->pkt.user_id->attrib_data
180 && k->pkt->pkt.user_id->is_primary ) {
181 *uidlen = k->pkt->pkt.user_id->len;
182 return k->pkt->pkt.user_id->name;
185 /* fixme: returning translatable constants instead of a user ID is
186 * not good because they are probably not utf-8 encoded. */
187 s = _("[User id not found]");
188 *uidlen = strlen (s);
194 release_keyid_list ( keyid_list_t k )
197 keyid_list_t k2 = k->next;
204 * Store the association of keyid and userid
205 * Feed only public keys to this function.
208 cache_user_id( KBNODE keyblock )
213 keyid_list_t keyids = NULL;
216 for (k=keyblock; k; k = k->next ) {
217 if ( k->pkt->pkttype == PKT_PUBLIC_KEY
218 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
219 keyid_list_t a = m_alloc_clear ( sizeof *a );
220 /* Hmmm: For a long list of keyids it might be an advantage
221 * to append the keys */
222 keyid_from_pk( k->pkt->pkt.public_key, a->keyid );
223 /* first check for duplicates */
224 for(r=user_id_db; r; r = r->next ) {
225 keyid_list_t b = r->keyids;
226 for ( b = r->keyids; b; b = b->next ) {
227 if( b->keyid[0] == a->keyid[0]
228 && b->keyid[1] == a->keyid[1] ) {
230 log_debug("cache_user_id: already in cache\n");
231 release_keyid_list ( keyids );
237 /* now put it into the cache */
243 BUG (); /* No key no fun */
246 uid = get_primary_uid ( keyblock, &uidlen );
248 if( uid_cache_entries >= MAX_UID_CACHE_ENTRIES ) {
249 /* fixme: use another algorithm to free some cache slots */
251 user_id_db = r->next;
252 release_keyid_list ( r->keyids );
256 r = m_alloc( sizeof *r + uidlen-1 );
259 memcpy(r->name, uid, r->len);
260 r->next = user_id_db;
267 getkey_disable_caches()
269 #if MAX_PK_CACHE_ENTRIES
271 pk_cache_entry_t ce, ce2;
273 for( ce = pk_cache; ce; ce = ce2 ) {
275 free_public_key( ce->pk );
279 pk_cache_entries = 0;
283 /* fixme: disable user id cache ? */
288 pk_from_block ( GETKEY_CTX ctx, PKT_public_key *pk, KBNODE keyblock )
290 KBNODE a = ctx->found_key ? ctx->found_key : keyblock;
292 assert ( a->pkt->pkttype == PKT_PUBLIC_KEY
293 || a->pkt->pkttype == PKT_PUBLIC_SUBKEY );
295 copy_public_key ( pk, a->pkt->pkt.public_key );
299 sk_from_block ( GETKEY_CTX ctx,
300 PKT_secret_key *sk, KBNODE keyblock )
302 KBNODE a = ctx->found_key ? ctx->found_key : keyblock;
304 assert ( a->pkt->pkttype == PKT_SECRET_KEY
305 || a->pkt->pkttype == PKT_SECRET_SUBKEY );
307 copy_secret_key( sk, a->pkt->pkt.secret_key);
312 * Get a public key and store it into the allocated pk
313 * can be called with PK set to NULL to just read it into some
314 * internal structures.
317 get_pubkey( PKT_public_key *pk, u32 *keyid )
322 #if MAX_PK_CACHE_ENTRIES
323 { /* Try to get it from the cache */
325 for( ce = pk_cache; ce; ce = ce->next ) {
326 if( ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1] ) {
328 copy_public_key( pk, ce->pk );
334 /* more init stuff */
336 pk = m_alloc_clear( sizeof *pk );
342 { struct getkey_ctx_s ctx;
344 memset( &ctx, 0, sizeof ctx );
345 ctx.exact = 1; /* use the key ID exactly as given */
346 ctx.not_allocated = 1;
347 ctx.kr_handle = keydb_new (0);
349 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
350 ctx.items[0].u.kid[0] = keyid[0];
351 ctx.items[0].u.kid[1] = keyid[1];
352 ctx.req_algo = pk->req_algo;
353 ctx.req_usage = pk->req_usage;
354 rc = lookup( &ctx, &kb, 0 );
356 pk_from_block ( &ctx, pk, kb );
358 get_pubkey_end( &ctx );
359 release_kbnode ( kb );
364 rc = G10ERR_NO_PUBKEY;
368 cache_public_key( pk );
376 get_pubkeyblock( u32 *keyid )
378 struct getkey_ctx_s ctx;
380 KBNODE keyblock = NULL;
382 memset( &ctx, 0, sizeof ctx );
383 /* no need to set exact here because we want the entire block */
384 ctx.not_allocated = 1;
385 ctx.kr_handle = keydb_new (0);
387 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
388 ctx.items[0].u.kid[0] = keyid[0];
389 ctx.items[0].u.kid[1] = keyid[1];
390 rc = lookup( &ctx, &keyblock, 0 );
391 get_pubkey_end( &ctx );
393 return rc ? NULL : keyblock;
400 * Get a secret key and store it into sk
403 get_seckey( PKT_secret_key *sk, u32 *keyid )
406 struct getkey_ctx_s ctx;
409 memset( &ctx, 0, sizeof ctx );
410 ctx.exact = 1; /* use the key ID exactly as given */
411 ctx.not_allocated = 1;
412 ctx.kr_handle = keydb_new (1);
414 ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
415 ctx.items[0].u.kid[0] = keyid[0];
416 ctx.items[0].u.kid[1] = keyid[1];
417 ctx.req_algo = sk->req_algo;
418 ctx.req_usage = sk->req_usage;
419 rc = lookup( &ctx, &kb, 1 );
421 sk_from_block ( &ctx, sk, kb );
423 get_seckey_end( &ctx );
424 release_kbnode ( kb );
427 /* check the secret key (this may prompt for a passprase to
428 * unlock the secret key
430 rc = check_secret_key( sk, 0 );
438 * Check whether the secret key is available. This is just a fast
439 * check and does not tell us whether the secret key is valid. It
440 * merely tells other whether there is some secret key.
441 * Returns: 0 := key is available
442 * G10ERR_NO_SECKEY := not availabe
445 seckey_available( u32 *keyid )
448 KEYDB_HANDLE hd = keydb_new (1);
450 rc = keydb_search_kid (hd, keyid);
452 rc = G10ERR_NO_SECKEY;
459 * Return the type of the user id:
461 * Please use the constants KEYDB_SERCH_MODE_xxx
462 * 0 = Invalid user ID
464 * 2 = match a substring
465 * 3 = match an email address
466 * 4 = match a substring of an email address
467 * 5 = match an email address, but compare from end
468 * 6 = word match mode
469 * 10 = it is a short KEYID (don't care about keyid[0])
470 * 11 = it is a long KEYID
471 * 12 = it is a trustdb index (keyid is looked up)
472 * 16 = it is a 16 byte fingerprint
473 * 20 = it is a 20 byte fingerprint
474 * 21 = Unified fingerprint :fpr:pk_algo:
475 * (We don't use pk_algo yet)
478 * - If the username starts with 8,9,16 or 17 hex-digits (the first one
479 * must be in the range 0..9), this is considered a keyid; depending
480 * on the length a short or complete one.
481 * - If the username starts with 32,33,40 or 41 hex-digits (the first one
482 * must be in the range 0..9), this is considered a fingerprint.
483 * - If the username starts with a left angle, we assume it is a complete
484 * email address and look only at this part.
485 * - If the username starts with a colon we assume it is a unified
486 * key specfification.
487 * - If the username starts with a '.', we assume it is the ending
488 * part of an email address
489 * - If the username starts with an '@', we assume it is a part of an
491 * - If the userid start with an '=' an exact compare is done.
492 * - If the userid starts with a '*' a case insensitive substring search is
493 * done (This is the default).
494 * - If the userid starts with a '+' we will compare individual words
495 * and a match requires that all the words are in the userid.
496 * Words are delimited by white space or "()<>[]{}.@-+_,;/&!"
497 * (note that you can't search for these characters). Compare
498 * is not case sensitive.
502 classify_user_id2( const char *name,
503 KEYDB_SEARCH_DESC *desc,
511 /* clear the structure so that the mode field is set to zero unless
512 * we set it to the correct value right at the end of this function */
513 memset (desc, 0, sizeof *desc);
515 /* skip leading spaces. Fixme: what is with trailing spaces? */
516 for(s = name; *s && isspace(*s); s++ )
520 case 0: /* empty string is an error */
523 case '.': /* an email address, compare from end */
524 mode = KEYDB_SEARCH_MODE_MAILEND;
529 case '<': /* an email address */
530 mode = KEYDB_SEARCH_MODE_MAIL;
534 case '@': /* part of an email address */
535 mode = KEYDB_SEARCH_MODE_MAILSUB;
540 case '=': /* exact compare */
541 mode = KEYDB_SEARCH_MODE_EXACT;
546 case '*': /* case insensitive substring search */
547 mode = KEYDB_SEARCH_MODE_SUBSTR;
552 case '+': /* compare individual words */
553 mode = KEYDB_SEARCH_MODE_WORDS;
558 case '#': /* local user id */
559 return 0; /* This is now obsolete and van't not be used anymore*/
561 case ':': /*Unified fingerprint */
566 se = strchr( ++s,':');
569 for (i=0,si=s; si < se; si++, i++ ) {
570 if ( !strchr("01234567890abcdefABCDEF", *si ) )
571 return 0; /* invalid digit */
573 if (i != 32 && i != 40)
574 return 0; /* invalid length of fpr*/
575 for (i=0,si=s; si < se; i++, si +=2)
576 desc->u.fpr[i] = hextobyte(si);
580 mode = KEYDB_SEARCH_MODE_FPR;
585 if (s[0] == '0' && s[1] == 'x') {
590 hexlength = strspn(s, "0123456789abcdefABCDEF");
591 if (hexlength >= 8 && s[hexlength] =='!') {
593 hexlength++; /* just for the following check */
596 /* check if a hexadecimal number is terminated by EOS or blank */
597 if (hexlength && s[hexlength] && !isspace(s[hexlength])) {
598 if (hexprefix) /* a "0x" prefix without correct */
599 return 0; /* termination is an error */
600 else /* The first chars looked like */
601 hexlength = 0; /* a hex number, but really were not. */
608 || (!hexprefix && hexlength == 9 && *s == '0')){
613 desc->u.kid[1] = strtoul( s, NULL, 16 );
614 mode = KEYDB_SEARCH_MODE_SHORT_KID;
616 else if (hexlength == 16
617 || (!hexprefix && hexlength == 17 && *s == '0')) {
623 desc->u.kid[0] = strtoul( buf, NULL, 16 );
624 desc->u.kid[1] = strtoul( s+8, NULL, 16 );
625 mode = KEYDB_SEARCH_MODE_LONG_KID;
627 else if (hexlength == 32 || (!hexprefix && hexlength == 33
629 /* md5 fingerprint */
633 memset(desc->u.fpr+16, 0, 4);
634 for (i=0; i < 16; i++, s+=2) {
635 int c = hextobyte(s);
640 mode = KEYDB_SEARCH_MODE_FPR16;
642 else if (hexlength == 40 || (!hexprefix && hexlength == 41
644 /* sha1/rmd160 fingerprint */
648 for (i=0; i < 20; i++, s+=2) {
649 int c = hextobyte(s);
654 mode = KEYDB_SEARCH_MODE_FPR20;
657 if (hexprefix) /* This was a hex number with a prefix */
658 return 0; /* and a wrong length */
662 mode = KEYDB_SEARCH_MODE_SUBSTR; /* default mode */
671 classify_user_id (const char *name, KEYDB_SEARCH_DESC *desc)
674 KEYDB_SEARCH_DESC dummy_desc;
678 return classify_user_id2 (name, desc, &dummy);
682 * Try to get the pubkey by the userid. This function looks for the
683 * first pubkey certificate which has the given name in a user_id.
684 * if pk/sk has the pubkey algo set, the function will only return
685 * a pubkey with that algo.
686 * The caller should provide storage for either the pk or the sk.
687 * If ret_kb is not NULL the function will return the keyblock there.
691 key_byname( GETKEY_CTX *retctx, STRLIST namelist,
692 PKT_public_key *pk, PKT_secret_key *sk, int secmode,
693 KBNODE *ret_kb, KEYDB_HANDLE *ret_kdbhd )
699 KBNODE help_kb = NULL;
702 if( retctx ) {/* reset the returned context in case of error */
703 assert (!ret_kdbhd); /* not allowed because the handle is
704 stored in the context */
710 /* build the search context */
711 for(n=0, r=namelist; r; r = r->next )
713 ctx = m_alloc_clear (sizeof *ctx + (n-1)*sizeof ctx->items );
716 for(n=0, r=namelist; r; r = r->next, n++ ) {
717 classify_user_id2 (r->d, &ctx->items[n], &exact);
721 if (!ctx->items[n].mode) {
723 return G10ERR_INV_USER_ID;
727 ctx->kr_handle = keydb_new (secmode);
733 ctx->req_algo = sk->req_algo;
734 ctx->req_usage = sk->req_usage;
736 rc = lookup( ctx, ret_kb, 1 );
738 sk_from_block ( ctx, sk, *ret_kb );
743 ctx->req_algo = pk->req_algo;
744 ctx->req_usage = pk->req_usage;
746 rc = lookup( ctx, ret_kb, 0 );
748 pk_from_block ( ctx, pk, *ret_kb );
752 release_kbnode ( help_kb );
754 if (retctx) /* caller wants the context */
758 *ret_kdbhd = ctx->kr_handle;
759 ctx->kr_handle = NULL;
761 get_pubkey_end (ctx);
768 * Find a public key from NAME and returh the keyblock or the key.
769 * If ret_kdb is not NULL, the KEYDB handle used to locate this keyblock is
770 * returned and the caller is responsible for closing it.
773 get_pubkey_byname (PKT_public_key *pk,
774 const char *name, KBNODE *ret_keyblock,
775 KEYDB_HANDLE *ret_kdbhd )
778 STRLIST namelist = NULL;
780 add_to_strlist( &namelist, name );
781 rc = key_byname( NULL, namelist, pk, NULL, 0, ret_keyblock, ret_kdbhd);
782 free_strlist( namelist );
787 get_pubkey_bynames( GETKEY_CTX *retctx, PKT_public_key *pk,
788 STRLIST names, KBNODE *ret_keyblock )
790 return key_byname( retctx, names, pk, NULL, 0, ret_keyblock, NULL);
794 get_pubkey_next( GETKEY_CTX ctx, PKT_public_key *pk, KBNODE *ret_keyblock )
798 rc = lookup( ctx, ret_keyblock, 0 );
799 if ( !rc && pk && ret_keyblock )
800 pk_from_block ( ctx, pk, *ret_keyblock );
807 get_pubkey_end( GETKEY_CTX ctx )
810 memset (&ctx->kbpos, 0, sizeof ctx->kbpos);
811 keydb_release (ctx->kr_handle);
812 if( !ctx->not_allocated )
821 * Search for a key with the given fingerprint.
823 * We should replace this with the _byname function. Thiscsan be done
824 * by creating a userID conforming to the unified fingerprint style.
827 get_pubkey_byfprint( PKT_public_key *pk,
828 const byte *fprint, size_t fprint_len)
832 if( fprint_len == 20 || fprint_len == 16 ) {
833 struct getkey_ctx_s ctx;
836 memset( &ctx, 0, sizeof ctx );
838 ctx.not_allocated = 1;
839 ctx.kr_handle = keydb_new (0);
841 ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
842 : KEYDB_SEARCH_MODE_FPR20;
843 memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
844 rc = lookup( &ctx, &kb, 0 );
846 pk_from_block ( &ctx, pk, kb );
847 release_kbnode ( kb );
848 get_pubkey_end( &ctx );
851 rc = G10ERR_GENERAL; /* Oops */
856 * Search for a key with the given fingerprint and return the
857 * complete keyblock which may have more than only this key.
860 get_keyblock_byfprint( KBNODE *ret_keyblock, const byte *fprint,
865 if( fprint_len == 20 || fprint_len == 16 ) {
866 struct getkey_ctx_s ctx;
868 memset( &ctx, 0, sizeof ctx );
869 ctx.not_allocated = 1;
870 ctx.kr_handle = keydb_new (0);
872 ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
873 : KEYDB_SEARCH_MODE_FPR20;
874 memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
875 rc = lookup( &ctx, ret_keyblock, 0 );
876 get_pubkey_end( &ctx );
879 rc = G10ERR_GENERAL; /* Oops */
886 * Get a secret key by name and store it into sk
887 * If NAME is NULL use the default key
890 get_seckey_byname2( GETKEY_CTX *retctx,
891 PKT_secret_key *sk, const char *name, int unprotect,
894 STRLIST namelist = NULL;
897 if( !name && opt.def_secret_key && *opt.def_secret_key ) {
898 add_to_strlist( &namelist, opt.def_secret_key );
899 rc = key_byname( retctx, namelist, NULL, sk, 1, retblock, NULL );
901 else if( !name ) { /* use the first one as default key */
902 struct getkey_ctx_s ctx;
905 assert (!retctx ); /* do we need this at all */
907 memset( &ctx, 0, sizeof ctx );
908 ctx.not_allocated = 1;
909 ctx.kr_handle = keydb_new (1);
911 ctx.items[0].mode = KEYDB_SEARCH_MODE_FIRST;
912 rc = lookup( &ctx, &kb, 1 );
914 sk_from_block ( &ctx, sk, kb );
915 release_kbnode ( kb );
916 get_seckey_end( &ctx );
919 add_to_strlist( &namelist, name );
920 rc = key_byname( retctx, namelist, NULL, sk, 1, retblock, NULL );
923 free_strlist( namelist );
925 if( !rc && unprotect )
926 rc = check_secret_key( sk, 0 );
932 get_seckey_byname( PKT_secret_key *sk, const char *name, int unlock )
934 return get_seckey_byname2 ( NULL, sk, name, unlock, NULL );
939 get_seckey_bynames( GETKEY_CTX *retctx, PKT_secret_key *sk,
940 STRLIST names, KBNODE *ret_keyblock )
942 return key_byname( retctx, names, NULL, sk, 1, ret_keyblock, NULL );
947 get_seckey_next( GETKEY_CTX ctx, PKT_secret_key *sk, KBNODE *ret_keyblock )
951 rc = lookup( ctx, ret_keyblock, 1 );
952 if ( !rc && sk && ret_keyblock )
953 sk_from_block ( ctx, sk, *ret_keyblock );
960 get_seckey_end( GETKEY_CTX ctx )
962 get_pubkey_end( ctx );
967 * Search for a key with the given fingerprint.
969 * We should replace this with the _byname function. Thiscsan be done
970 * by creating a userID conforming to the unified fingerprint style.
973 get_seckey_byfprint( PKT_secret_key *sk,
974 const byte *fprint, size_t fprint_len)
978 if( fprint_len == 20 || fprint_len == 16 ) {
979 struct getkey_ctx_s ctx;
982 memset( &ctx, 0, sizeof ctx );
984 ctx.not_allocated = 1;
985 ctx.kr_handle = keydb_new (1);
987 ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
988 : KEYDB_SEARCH_MODE_FPR20;
989 memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
990 rc = lookup( &ctx, &kb, 1 );
992 sk_from_block ( &ctx, sk, kb );
993 release_kbnode ( kb );
994 get_pubkey_end( &ctx );
997 rc = G10ERR_GENERAL; /* Oops */
1002 /************************************************
1003 ************* Merging stuff ********************
1004 ************************************************/
1007 * merge all selfsignatures with the keys.
1008 * FIXME: replace this at least for the public key parts
1009 * by merge_selfsigs.
1010 * It is still used in keyedit.c and
1011 * at 2 or 3 other places - check whether it is really needed.
1012 * It might be needed by the key edit and import stuff because
1013 * the keylock is changed.
1016 merge_keys_and_selfsig( KBNODE keyblock )
1018 PKT_public_key *pk = NULL;
1019 PKT_secret_key *sk = NULL;
1022 u32 kid[2] = { 0, 0 };
1025 if (keyblock && keyblock->pkt->pkttype == PKT_PUBLIC_KEY ) {
1026 /* divert to our new function */
1027 merge_selfsigs (keyblock);
1030 /* still need the old one because the new one can't handle secret keys */
1032 for(k=keyblock; k; k = k->next ) {
1033 if( k->pkt->pkttype == PKT_PUBLIC_KEY
1034 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
1035 pk = k->pkt->pkt.public_key; sk = NULL;
1036 if( pk->version < 4 )
1037 pk = NULL; /* not needed for old keys */
1038 else if( k->pkt->pkttype == PKT_PUBLIC_KEY )
1039 keyid_from_pk( pk, kid );
1040 else if( !pk->expiredate ) { /* and subkey */
1041 /* insert the expiration date here */
1042 /*FIXME!!! pk->expiredate = subkeys_expiretime( k, kid );*/
1046 else if( k->pkt->pkttype == PKT_SECRET_KEY
1047 || k->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1048 pk = NULL; sk = k->pkt->pkt.secret_key;
1049 if( sk->version < 4 )
1051 else if( k->pkt->pkttype == PKT_SECRET_KEY )
1052 keyid_from_sk( sk, kid );
1055 else if( (pk || sk ) && k->pkt->pkttype == PKT_SIGNATURE
1056 && (sig=k->pkt->pkt.signature)->sig_class >= 0x10
1057 && sig->sig_class <= 0x30 && sig->version > 3
1058 && !(sig->sig_class == 0x18 || sig->sig_class == 0x28)
1059 && sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1] ) {
1060 /* okay this is a self-signature which can be used.
1061 * This is not used for subkey binding signature, becuase this
1063 * FIXME: We should only use this if the signature is valid
1064 * but this is time consuming - we must provide another
1065 * way to handle this
1070 p = parse_sig_subpkt( sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL );
1072 ed = p? pk->timestamp + buffer_to_u32(p):0;
1073 if( sig->timestamp > sigdate ) {
1074 pk->expiredate = ed;
1075 sigdate = sig->timestamp;
1079 ed = p? sk->timestamp + buffer_to_u32(p):0;
1080 if( sig->timestamp > sigdate ) {
1081 sk->expiredate = ed;
1082 sigdate = sig->timestamp;
1087 if(pk && (pk->expiredate==0 ||
1088 (pk->max_expiredate && pk->expiredate>pk->max_expiredate)))
1089 pk->expiredate=pk->max_expiredate;
1091 if(sk && (sk->expiredate==0 ||
1092 (sk->max_expiredate && sk->expiredate>sk->max_expiredate)))
1093 sk->expiredate=sk->max_expiredate;
1098 * Apply information from SIGNODE (which is the valid self-signature
1099 * associated with that UID) to the UIDNODE:
1100 * - wether the UID has been revoked
1101 * - assumed creation date of the UID
1102 * - temporary store the keyflags here
1103 * - temporary store the key expiration time here
1104 * - mark whether the primary user ID flag hat been set.
1105 * - store the preferences
1108 fixup_uidnode ( KBNODE uidnode, KBNODE signode, u32 keycreated )
1110 PKT_user_id *uid = uidnode->pkt->pkt.user_id;
1111 PKT_signature *sig = signode->pkt->pkt.signature;
1112 const byte *p, *sym, *hash, *zip;
1113 size_t n, nsym, nhash, nzip;
1115 uid->created = 0; /* not created == invalid */
1116 if ( IS_UID_REV ( sig ) ) {
1117 uid->is_revoked = 1;
1118 return; /* has been revoked */
1121 uid->created = sig->timestamp; /* this one is okay */
1122 uid->selfsigversion = sig->version;
1123 /* If we got this far, it's not expired :) */
1124 uid->is_expired = 0;
1125 uid->expiredate = sig->expiredate;
1127 /* store the key flags in the helper variable for later processing */
1128 uid->help_key_usage = 0;
1129 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n );
1131 /* first octet of the keyflags */
1133 uid->help_key_usage |= PUBKEY_USAGE_SIG;
1135 uid->help_key_usage |= PUBKEY_USAGE_ENC;
1136 /* Note: we do not set the CERT flag here because it can be assumed
1137 * that thre is no real policy to set it. */
1140 /* ditto or the key expiration */
1141 uid->help_key_expire = 0;
1142 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1144 uid->help_key_expire = keycreated + buffer_to_u32(p);
1147 /* Set the primary user ID flag - we will later wipe out some
1148 * of them to only have one in our keyblock */
1149 uid->is_primary = 0;
1150 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL );
1152 uid->is_primary = 1;
1153 /* We could also query this from the unhashed area if it is not in
1154 * the hased area and then later try to decide which is the better
1155 * there should be no security problem with this.
1156 * For now we only look at the hashed one.
1159 /* Now build the preferences list. These must come from the
1160 hashed section so nobody can modify the ciphers a key is
1161 willing to accept. */
1162 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_SYM, &n );
1163 sym = p; nsym = p?n:0;
1164 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_HASH, &n );
1165 hash = p; nhash = p?n:0;
1166 p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_COMPR, &n );
1167 zip = p; nzip = p?n:0;
1169 m_free (uid->prefs);
1170 n = nsym + nhash + nzip;
1174 uid->prefs = m_alloc (sizeof (*uid->prefs) * (n+1));
1176 for (; nsym; nsym--, n++) {
1177 uid->prefs[n].type = PREFTYPE_SYM;
1178 uid->prefs[n].value = *sym++;
1180 for (; nhash; nhash--, n++) {
1181 uid->prefs[n].type = PREFTYPE_HASH;
1182 uid->prefs[n].value = *hash++;
1184 for (; nzip; nzip--, n++) {
1185 uid->prefs[n].type = PREFTYPE_ZIP;
1186 uid->prefs[n].value = *zip++;
1188 uid->prefs[n].type = PREFTYPE_NONE; /* end of list marker */
1189 uid->prefs[n].value = 0;
1192 /* see whether we have the MDC feature */
1193 uid->mdc_feature = 0;
1194 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
1195 if (p && n && (p[0] & 0x01))
1196 uid->mdc_feature = 1;
1201 merge_selfsigs_main( KBNODE keyblock, int *r_revoked )
1203 PKT_public_key *pk = NULL;
1206 u32 sigdate = 0, uiddate=0, uiddate2;
1207 KBNODE signode, uidnode, uidnode2;
1208 u32 curtime = make_timestamp ();
1209 unsigned int key_usage = 0;
1210 u32 keytimestamp = 0;
1212 int key_expire_seen = 0;
1213 byte sigversion = 0;
1216 if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY )
1218 pk = keyblock->pkt->pkt.public_key;
1219 keytimestamp = pk->timestamp;
1221 keyid_from_pk( pk, kid );
1222 pk->main_keyid[0] = kid[0];
1223 pk->main_keyid[1] = kid[1];
1225 if ( pk->version < 4 ) {
1226 /* before v4 the key packet itself contains the expiration
1227 * date and there was no way to change it, so we start with
1228 * the one from the key packet */
1229 key_expire = pk->max_expiredate;
1230 key_expire_seen = 1;
1233 /* first pass: find the latest direct key self-signature.
1234 * We assume that the newest one overrides all others
1237 /* In case this key was already merged */
1243 sigdate = 0; /* helper to find the latest signature */
1244 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next ) {
1245 if ( k->pkt->pkttype == PKT_SIGNATURE ) {
1246 PKT_signature *sig = k->pkt->pkt.signature;
1247 if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) {
1248 if ( check_key_signature( keyblock, k, NULL ) )
1249 ; /* signature did not verify */
1250 else if ( IS_KEY_REV (sig) ){
1251 /* key has been revoked - there is no way to override
1252 * such a revocation, so we theoretically can stop now.
1253 * We should not cope with expiration times for revocations
1254 * here because we have to assume that an attacker can
1255 * generate all kinds of signatures. However due to the
1256 * fact that the key has been revoked it does not harm
1257 * either and by continuing we gather some more info on
1262 else if ( IS_KEY_SIG (sig) ) {
1263 /* Add any revocation keys onto the pk. This is
1264 particularly interesting since we normally only
1265 get data from the most recent 1F signature, but
1266 you need multiple 1F sigs to properly handle
1267 revocation keys (PGP does it this way, and a
1268 revocation key could be sensitive and hence in a
1269 different signature). */
1274 m_realloc(pk->revkey,sizeof(struct revocation_key)*
1275 (pk->numrevkeys+sig->numrevkeys));
1277 for(i=0;i<sig->numrevkeys;i++)
1278 memcpy(&pk->revkey[pk->numrevkeys++],
1280 sizeof(struct revocation_key));
1283 if( sig->timestamp >= sigdate ) {
1284 if(sig->flags.expired)
1285 ; /* signature has expired - ignore it */
1287 sigdate = sig->timestamp;
1289 sigversion = sig->version;
1298 /* Remove dupes from the revocation keys */
1302 int i,j,x,changed=0;
1304 for(i=0;i<pk->numrevkeys;i++)
1306 for(j=i+1;j<pk->numrevkeys;j++)
1308 if(memcmp(&pk->revkey[i],&pk->revkey[j],
1309 sizeof(struct revocation_key))==0)
1313 for(x=j;x<pk->numrevkeys-1;x++)
1314 pk->revkey[x]=pk->revkey[x+1];
1324 pk->revkey=m_realloc(pk->revkey,
1325 pk->numrevkeys*sizeof(struct revocation_key));
1329 /* some information from a direct key signature take precedence
1330 * over the same information given in UID sigs.
1332 PKT_signature *sig = signode->pkt->pkt.signature;
1336 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n );
1338 /* first octet of the keyflags */
1340 key_usage |= PUBKEY_USAGE_SIG;
1342 key_usage |= PUBKEY_USAGE_ENC;
1345 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1347 key_expire = keytimestamp + buffer_to_u32(p);
1348 key_expire_seen = 1;
1351 /* mark that key as valid: one direct key signature should
1352 * render a key as valid */
1356 /* pass 1.5: look for key revocation signatures that were not made
1357 by the key (i.e. did a revocation key issue a revocation for
1358 us?). Only bother to do this if there is a revocation key in
1362 for(k=keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next )
1364 if ( k->pkt->pkttype == PKT_SIGNATURE )
1366 PKT_signature *sig = k->pkt->pkt.signature;
1368 if(IS_KEY_REV(sig) &&
1369 (sig->keyid[0]!=kid[0] || sig->keyid[1]!=kid[1]))
1371 if(check_revocation_keys(pk,sig))
1372 ; /* did not verify, or loop broken */
1376 /* In the future handle subkey and cert revocations?
1377 PGP doesn't, but it's in 2440. */
1382 /* second pass: look at the self-signature of all user IDs */
1383 signode = uidnode = NULL;
1384 sigdate = 0; /* helper to find the latest signature in one user ID */
1385 uiddate = 0; /* and over of all user IDs */
1386 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next ) {
1387 if ( k->pkt->pkttype == PKT_USER_ID ) {
1388 if ( uidnode && signode )
1389 fixup_uidnode ( uidnode, signode, keytimestamp );
1392 if ( sigdate > uiddate )
1396 else if ( k->pkt->pkttype == PKT_SIGNATURE && uidnode ) {
1397 PKT_signature *sig = k->pkt->pkt.signature;
1398 if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) {
1399 if ( check_key_signature( keyblock, k, NULL ) )
1400 ; /* signature did not verify */
1401 else if ( (IS_UID_SIG (sig) || IS_UID_REV (sig))
1402 && sig->timestamp >= sigdate ) {
1403 /* Note: we allow to invalidate cert revocations
1404 * by a newer signature. An attacker can't use this
1405 * because a key should be revoced with a key revocation.
1406 * The reason why we have to allow for that is that at
1407 * one time an email address may become invalid but later
1408 * the same email address may become valid again (hired,
1409 * fired, hired again).
1411 if(sig->flags.expired) {
1412 /* Expired uids don't get to be primary unless
1413 they are the only uid there is. */
1414 uidnode->pkt->pkt.user_id->is_primary=0;
1415 uidnode->pkt->pkt.user_id->is_expired=1;
1416 uidnode->pkt->pkt.user_id->expiredate=sig->expiredate;
1419 sigdate = sig->timestamp;
1421 if( sig->version > sigversion )
1422 sigversion = sig->version;
1428 if ( uidnode && signode ) {
1429 fixup_uidnode ( uidnode, signode, keytimestamp );
1433 /* If the key isn't valid yet, and we have
1434 --allow-non-selfsigned-uid set, then force it valid. */
1435 if(!pk->is_valid && opt.allow_non_selfsigned_uid)
1438 log_info(_("Invalid key %08lX made valid by "
1439 "--allow-non-selfsigned-uid\n"),
1440 (ulong)keyid_from_pk(pk,NULL));
1445 /* The key STILL isn't valid, so try and find an ultimately
1446 trusted signature. */
1451 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k=k->next)
1453 if ( k->pkt->pkttype == PKT_USER_ID )
1455 else if ( k->pkt->pkttype == PKT_SIGNATURE && uidnode )
1457 PKT_signature *sig = k->pkt->pkt.signature;
1459 if(sig->keyid[0] != kid[0] || sig->keyid[1]!=kid[1])
1461 PKT_public_key *ultimate_pk;
1463 ultimate_pk=m_alloc_clear(sizeof(*ultimate_pk));
1465 if(get_pubkey(ultimate_pk,sig->keyid)==0 &&
1466 check_key_signature(keyblock,k,NULL)==0 &&
1467 get_ownertrust(ultimate_pk)==TRUST_ULTIMATE)
1469 free_public_key(ultimate_pk);
1474 free_public_key(ultimate_pk);
1480 /* Record the highest selfsigversion so we know if this is a v3
1481 key through and through, or a v3 key with a v4 selfsig, which
1482 means we can trust the preferences (if any). */
1483 pk->selfsigversion=sigversion;
1485 /* Now that we had a look at all user IDs we can now get some information
1486 * from those user IDs.
1490 /* find the latest user ID with key flags set */
1491 uiddate = 0; /* helper to find the latest user ID */
1492 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1494 if ( k->pkt->pkttype == PKT_USER_ID ) {
1495 PKT_user_id *uid = k->pkt->pkt.user_id;
1496 if ( uid->help_key_usage && uid->created > uiddate ) {
1497 key_usage = uid->help_key_usage;
1498 uiddate = uid->created;
1503 if ( !key_usage ) { /* no key flags at all: get it from the algo */
1504 key_usage = openpgp_pk_algo_usage ( pk->pubkey_algo );
1506 else { /* check that the usage matches the usage as given by the algo */
1507 int x = openpgp_pk_algo_usage ( pk->pubkey_algo );
1508 if ( x ) /* mask it down to the actual allowed usage */
1511 pk->pubkey_usage = key_usage;
1513 if ( !key_expire_seen ) {
1514 /* find the latest valid user ID with a key expiration set
1515 * Note, that this may be a different one from the above because
1516 * some user IDs may have no expiration date set */
1518 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1520 if ( k->pkt->pkttype == PKT_USER_ID ) {
1521 PKT_user_id *uid = k->pkt->pkt.user_id;
1522 if ( uid->help_key_expire && uid->created > uiddate ) {
1523 key_expire = uid->help_key_expire;
1524 uiddate = uid->created;
1530 /* Currently only v3 keys have a maximum expiration date, but I'll
1531 bet v5 keys get this feature again. */
1532 if(key_expire==0 || (pk->max_expiredate && key_expire>pk->max_expiredate))
1533 key_expire=pk->max_expiredate;
1535 pk->has_expired = key_expire >= curtime? 0 : key_expire;
1536 pk->expiredate = key_expire;
1537 /* Fixme: we should see how to get rid of the expiretime fields but
1538 * this needs changes at other places too. */
1540 /* and now find the real primary user ID and delete all others */
1541 uiddate = uiddate2 = 0;
1542 uidnode = uidnode2 = NULL;
1543 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next ) {
1544 if ( k->pkt->pkttype == PKT_USER_ID &&
1545 !k->pkt->pkt.user_id->attrib_data) {
1546 PKT_user_id *uid = k->pkt->pkt.user_id;
1547 if ( uid->is_primary && uid->created > uiddate ) {
1548 uiddate = uid->created;
1551 if ( !uid->is_primary && uid->created > uiddate2 ) {
1552 uiddate2 = uid->created;
1558 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1560 if ( k->pkt->pkttype == PKT_USER_ID &&
1561 !k->pkt->pkt.user_id->attrib_data) {
1562 PKT_user_id *uid = k->pkt->pkt.user_id;
1564 uid->is_primary = 0;
1568 else if( uidnode2 ) {
1569 /* none is flagged primary - use the latest user ID we have */
1570 uidnode2->pkt->pkt.user_id->is_primary = 1;
1574 /* None of our uids were self-signed, so pick the first one to
1575 be the primary. This is the best we can do here since
1576 there are no self sigs to date the uids. */
1578 for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1581 if(k->pkt->pkttype==PKT_USER_ID &&
1582 !k->pkt->pkt.user_id->attrib_data)
1584 k->pkt->pkt.user_id->is_primary=1;
1593 merge_selfsigs_subkey( KBNODE keyblock, KBNODE subnode )
1595 PKT_public_key *mainpk = NULL, *subpk = NULL;
1601 u32 curtime = make_timestamp ();
1602 unsigned int key_usage = 0;
1603 u32 keytimestamp = 0;
1608 if ( subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY )
1610 mainpk = keyblock->pkt->pkt.public_key;
1611 if ( mainpk->version < 4 )
1612 return; /* (actually this should never happen) */
1613 keyid_from_pk( mainpk, mainkid );
1614 subpk = subnode->pkt->pkt.public_key;
1615 keytimestamp = subpk->timestamp;
1617 subpk->is_valid = 0;
1618 subpk->main_keyid[0] = mainpk->main_keyid[0];
1619 subpk->main_keyid[1] = mainpk->main_keyid[1];
1621 /* find the latest key binding self-signature. */
1623 sigdate = 0; /* helper to find the latest signature */
1624 for(k=subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1626 if ( k->pkt->pkttype == PKT_SIGNATURE ) {
1627 sig = k->pkt->pkt.signature;
1628 if ( sig->keyid[0] == mainkid[0] && sig->keyid[1]==mainkid[1] ) {
1629 if ( check_key_signature( keyblock, k, NULL ) )
1630 ; /* signature did not verify */
1631 else if ( IS_SUBKEY_REV (sig) ) {
1632 subpk->is_revoked = 1;
1633 /* although we could stop now, we continue to
1634 * figure out other information like the old expiration
1637 else if ( IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate ) {
1638 if(sig->flags.expired)
1639 ; /* signature has expired - ignore it */
1641 sigdate = sig->timestamp;
1650 return; /* no valid key binding */
1653 subpk->is_valid = 1;
1654 sig = signode->pkt->pkt.signature;
1656 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_FLAGS, &n );
1658 /* first octet of the keyflags */
1660 key_usage |= PUBKEY_USAGE_SIG;
1662 key_usage |= PUBKEY_USAGE_ENC;
1664 if ( !key_usage ) { /* no key flags at all: get it from the algo */
1665 key_usage = openpgp_pk_algo_usage ( subpk->pubkey_algo );
1667 else { /* check that the usage matches the usage as given by the algo */
1668 int x = openpgp_pk_algo_usage ( subpk->pubkey_algo );
1669 if ( x ) /* mask it down to the actual allowed usage */
1672 subpk->pubkey_usage = key_usage;
1674 p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
1676 key_expire = keytimestamp + buffer_to_u32(p);
1679 subpk->has_expired = key_expire >= curtime? 0 : key_expire;
1680 subpk->expiredate = key_expire;
1686 * Merge information from the self-signatures with the key, so that
1687 * we can later use them more easy.
1688 * The function works by first applying the self signatures to the
1689 * primary key and the to each subkey.
1690 * Here are the rules we use to decide which inormation from which
1691 * self-signature is used:
1692 * We check all self signatures or validity and ignore all invalid signatures.
1693 * All signatures are then ordered by their creation date ....
1694 * For the primary key:
1698 merge_selfsigs( KBNODE keyblock )
1702 PKT_public_key *main_pk;
1706 if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY ) {
1707 if (keyblock->pkt->pkttype == PKT_SECRET_KEY ) {
1708 log_error ("expected public key but found secret key "
1710 /* we better exit here becuase a public key is expected at
1711 other places too. FIXME: Figure this out earlier and
1712 don't get to here at all */
1718 merge_selfsigs_main ( keyblock, &revoked );
1719 main_pk = keyblock->pkt->pkt.public_key;
1721 /* if the primary key has been revoked we better set the revoke
1722 * flag on that key and all subkeys */
1723 for(k=keyblock; k; k = k->next ) {
1724 if ( k->pkt->pkttype == PKT_PUBLIC_KEY
1725 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
1726 PKT_public_key *pk = k->pkt->pkt.public_key;
1728 pk->main_keyid[0] = main_pk->main_keyid[0];
1729 pk->main_keyid[1] = main_pk->main_keyid[1];
1735 /* now merge in the data from each of the subkeys */
1736 for(k=keyblock; k; k = k->next ) {
1737 if ( k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
1738 merge_selfsigs_subkey ( keyblock, k );
1742 /* If the main key is not valid, then the subkeys aren't either,
1743 even if they have binding sigs. */
1744 if(!main_pk->is_valid)
1745 for(k=keyblock; k; k=k->next)
1746 if(k->pkt->pkttype==PKT_PUBLIC_SUBKEY)
1747 k->pkt->pkt.public_key->is_valid=0;
1749 /* set the preference list of all keys to those of the primary real
1750 * user ID. Note: we use these preferences when we don't know by
1751 * which user ID the key has been selected.
1752 * fixme: we should keep atoms of commonly used preferences or
1753 * use reference counting to optimize the preference lists storage.
1754 * FIXME: it might be better to use the intersection of
1756 * Do a similar thing for the MDC feature flag.
1760 for (k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) {
1761 if (k->pkt->pkttype == PKT_USER_ID
1762 && !k->pkt->pkt.user_id->attrib_data
1763 && k->pkt->pkt.user_id->is_primary) {
1764 prefs = k->pkt->pkt.user_id->prefs;
1765 mdc_feature = k->pkt->pkt.user_id->mdc_feature;
1769 for(k=keyblock; k; k = k->next ) {
1770 if ( k->pkt->pkttype == PKT_PUBLIC_KEY
1771 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
1772 PKT_public_key *pk = k->pkt->pkt.public_key;
1775 pk->prefs = copy_prefs (prefs);
1776 pk->mdc_feature = mdc_feature;
1783 * Merge the secret keys from secblock into the pubblock thereby
1784 * replacing the public (sub)keys with their secret counterparts Hmmm:
1785 * It might be better to get away from the concept of entire secret
1786 * keys at all and have a way to store just the real secret parts
1790 merge_public_with_secret ( KBNODE pubblock, KBNODE secblock )
1794 assert ( pubblock->pkt->pkttype == PKT_PUBLIC_KEY );
1795 assert ( secblock->pkt->pkttype == PKT_SECRET_KEY );
1797 for (pub=pubblock; pub; pub = pub->next ) {
1798 if ( pub->pkt->pkttype == PKT_PUBLIC_KEY ) {
1799 PKT_public_key *pk = pub->pkt->pkt.public_key;
1800 PKT_secret_key *sk = secblock->pkt->pkt.secret_key;
1801 assert ( pub == pubblock ); /* only in the first node */
1802 /* there is nothing to compare in this case, so just replace
1803 * some information */
1804 copy_public_parts_to_secret_key ( pk, sk );
1805 free_public_key ( pk );
1806 pub->pkt->pkttype = PKT_SECRET_KEY;
1807 pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
1809 else if ( pub->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
1811 PKT_public_key *pk = pub->pkt->pkt.public_key;
1813 /* this is more complicated: it may happen that the sequence
1814 * of the subkeys dosn't match, so we have to find the
1815 * appropriate secret key */
1816 for (sec=secblock->next; sec; sec = sec->next ) {
1817 if ( sec->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1818 PKT_secret_key *sk = sec->pkt->pkt.secret_key;
1819 if ( !cmp_public_secret_key ( pk, sk ) ) {
1820 copy_public_parts_to_secret_key ( pk, sk );
1821 free_public_key ( pk );
1822 pub->pkt->pkttype = PKT_SECRET_SUBKEY;
1823 pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
1829 BUG(); /* already checked in premerge */
1834 /* This function checks that for every public subkey a corresponding
1835 * secret subkey is available and deletes the public subkey otherwise.
1836 * We need this function because we can't delete it later when we
1837 * actually merge the secret parts into the pubring.
1838 * The function also plays some games with the node flags.
1841 premerge_public_with_secret ( KBNODE pubblock, KBNODE secblock )
1845 assert ( pubblock->pkt->pkttype == PKT_PUBLIC_KEY );
1846 assert ( secblock->pkt->pkttype == PKT_SECRET_KEY );
1848 for (pub=pubblock,last=NULL; pub; last = pub, pub = pub->next ) {
1849 pub->flag &= ~3; /* reset bits 0 and 1 */
1850 if ( pub->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
1852 PKT_public_key *pk = pub->pkt->pkt.public_key;
1854 for (sec=secblock->next; sec; sec = sec->next ) {
1855 if ( sec->pkt->pkttype == PKT_SECRET_SUBKEY ) {
1856 PKT_secret_key *sk = sec->pkt->pkt.secret_key;
1857 if ( !cmp_public_secret_key ( pk, sk ) ) {
1858 if ( sk->protect.s2k.mode == 1001 ) {
1859 /* The secret parts are not available so
1860 we can't use that key for signing etc.
1861 Fix the pubkey usage */
1862 pk->pubkey_usage &= ~PUBKEY_USAGE_SIG;
1864 /* transfer flag bits 0 and 1 to the pubblock */
1865 pub->flag |= (sec->flag &3);
1873 log_info ( "no secret subkey "
1874 "for public subkey %08lX - ignoring\n",
1875 (ulong)keyid_from_pk (pk,NULL) );
1876 /* we have to remove the subkey in this case */
1878 /* find the next subkey */
1879 for (next=pub->next,ll=pub;
1880 next && pub->pkt->pkttype != PKT_PUBLIC_SUBKEY;
1881 ll = next, next = next->next )
1885 /* release this public subkey with all sigs */
1887 release_kbnode( pub );
1888 /* let the loop continue */
1893 /* We need to copy the found bits (0 and 1) from the secret key to
1894 the public key. This has already been done for the subkeys but
1895 got lost on the primary key - fix it here *. */
1896 pubblock->flag |= (secblock->flag & 3);
1902 /* See see whether the key fits
1903 * our requirements and in case we do not
1904 * request the primary key, we should select
1905 * a suitable subkey.
1906 * FIXME: Check against PGP 7 whether we still need a kludge
1907 * to favor type 16 keys over type 20 keys when type 20
1908 * has not been explitely requested.
1909 * Returns: True when a suitable key has been found.
1911 * We have to distinguish four cases: FIXME!
1912 * 1. No usage and no primary key requested
1913 * Examples for this case are that we have a keyID to be used
1914 * for decrytion or verification.
1915 * 2. No usage but primary key requested
1916 * This is the case for all functions which work on an
1917 * entire keyblock, e.g. for editing or listing
1918 * 3. Usage and primary key requested
1920 * 4. Usage but no primary key requested
1922 * FIXME: Tell what is going to happen here and something about the rationale
1923 * Note: We don't use this function if no specific usage is requested;
1924 * This way the getkey functions can be used for plain key listings.
1926 * CTX ist the keyblock we are investigating, if FOUNDK is not NULL this
1927 * is the key we actually found by looking at the keyid or a fingerprint and
1928 * may eitehr point to the primary or one of the subkeys.
1932 finish_lookup (GETKEY_CTX ctx)
1934 KBNODE keyblock = ctx->keyblock;
1936 KBNODE foundk = NULL;
1937 PKT_user_id *foundu = NULL;
1938 #define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC)
1939 unsigned int req_usage = ( ctx->req_usage & USAGE_MASK );
1940 /* Request the primary if we're certifying another key, and also
1941 if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
1942 do not understand signatures made by a signing subkey. */
1943 int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) ||
1944 ((opt.pgp6 || opt.pgp7) && (ctx->req_usage & PUBKEY_USAGE_SIG));
1947 u32 curtime = make_timestamp ();
1949 assert( keyblock->pkt->pkttype == PKT_PUBLIC_KEY );
1951 ctx->found_key = NULL;
1954 for (k=keyblock; k; k = k->next) {
1955 if ( (k->flag & 1) ) {
1956 assert ( k->pkt->pkttype == PKT_PUBLIC_KEY
1957 || k->pkt->pkttype == PKT_PUBLIC_SUBKEY );
1964 for (k=keyblock; k; k = k->next) {
1965 if ( (k->flag & 2) ) {
1966 assert (k->pkt->pkttype == PKT_USER_ID);
1967 foundu = k->pkt->pkt.user_id;
1973 log_debug( "finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
1974 (ulong)keyid_from_pk( keyblock->pkt->pkt.public_key, NULL),
1975 foundk? "one":"all", req_usage);
1978 latest_key = foundk? foundk:keyblock;
1983 PKT_public_key *pk = foundk->pkt->pkt.public_key;
1985 free_user_id (pk->user_id);
1986 pk->user_id = scopy_user_id (foundu);
1987 ctx->found_key = foundk;
1988 cache_user_id( keyblock );
1989 return 1; /* found */
1994 /* do not look at subkeys if a certification key is requested */
1995 if ((!foundk || foundk->pkt->pkttype == PKT_PUBLIC_SUBKEY) && !req_prim) {
1997 /* either start a loop or check just this one subkey */
1998 for (k=foundk?foundk:keyblock; k; k = nextk ) {
2001 if ( k->pkt->pkttype != PKT_PUBLIC_SUBKEY )
2004 nextk = NULL; /* what a hack */
2005 pk = k->pkt->pkt.public_key;
2007 log_debug( "\tchecking subkey %08lX\n",
2008 (ulong)keyid_from_pk( pk, NULL));
2009 if ( !pk->is_valid ) {
2011 log_debug( "\tsubkey not valid\n");
2014 if ( pk->is_revoked ) {
2016 log_debug( "\tsubkey has been revoked\n");
2019 if ( pk->has_expired ) {
2021 log_debug( "\tsubkey has expired\n");
2024 if ( pk->timestamp > curtime && !opt.ignore_valid_from ) {
2026 log_debug( "\tsubkey not yet valid\n");
2030 if ( !((pk->pubkey_usage&USAGE_MASK) & req_usage) ) {
2032 log_debug( "\tusage does not match: want=%x have=%x\n",
2033 req_usage, pk->pubkey_usage );
2038 log_debug( "\tsubkey looks fine\n");
2039 if ( pk->timestamp > latest_date ) {
2040 latest_date = pk->timestamp;
2046 /* Okay now try the primary key unless we want an exact
2047 * key ID match on a subkey */
2048 if ((!latest_key && !(ctx->exact && foundk != keyblock)) || req_prim) {
2050 if (DBG_CACHE && !foundk && !req_prim )
2051 log_debug( "\tno suitable subkeys found - trying primary\n");
2052 pk = keyblock->pkt->pkt.public_key;
2053 if ( !pk->is_valid ) {
2055 log_debug( "\tprimary key not valid\n");
2057 else if ( pk->is_revoked ) {
2059 log_debug( "\tprimary key has been revoked\n");
2061 else if ( pk->has_expired ) {
2063 log_debug( "\tprimary key has expired\n");
2065 else if ( !((pk->pubkey_usage&USAGE_MASK) & req_usage) ) {
2067 log_debug( "\tprimary key usage does not match: "
2068 "want=%x have=%x\n",
2069 req_usage, pk->pubkey_usage );
2073 log_debug( "\tprimary key may be used\n");
2074 latest_key = keyblock;
2075 latest_date = pk->timestamp;
2079 if ( !latest_key ) {
2081 log_debug("\tno suitable key found - giving up\n");
2087 log_debug( "\tusing key %08lX\n",
2088 (ulong)keyid_from_pk( latest_key->pkt->pkt.public_key, NULL) );
2091 PKT_public_key *pk = latest_key->pkt->pkt.public_key;
2093 free_user_id (pk->user_id);
2094 pk->user_id = scopy_user_id (foundu);
2097 ctx->found_key = latest_key;
2099 if (latest_key != keyblock && opt.verbose) {
2100 log_info(_("using secondary key %08lX "
2101 "instead of primary key %08lX\n"),
2102 (ulong)keyid_from_pk( latest_key->pkt->pkt.public_key, NULL),
2103 (ulong)keyid_from_pk( keyblock->pkt->pkt.public_key, NULL) );
2106 cache_user_id( keyblock );
2108 return 1; /* found */
2113 lookup( GETKEY_CTX ctx, KBNODE *ret_keyblock, int secmode )
2116 KBNODE secblock = NULL; /* helper */
2117 int no_suitable_key = 0;
2120 while (!(rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems))) {
2121 /* If we are searching for the first key we have to make sure
2122 that the next interation does not no an implicit reset.
2123 This can be triggered by an empty key ring. */
2124 if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
2125 ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
2127 rc = keydb_get_keyblock (ctx->kr_handle, &ctx->keyblock);
2129 log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
2135 /* find the correspondig public key and use this
2136 * this one for the selection process */
2138 KBNODE k = ctx->keyblock;
2140 if (k->pkt->pkttype != PKT_SECRET_KEY)
2143 keyid_from_sk (k->pkt->pkt.secret_key, aki);
2144 k = get_pubkeyblock (aki);
2147 log_info(_("key %08lX: secret key without public key "
2148 "- skipped\n"), (ulong)aki[1] );
2151 secblock = ctx->keyblock;
2154 premerge_public_with_secret ( ctx->keyblock, secblock );
2157 /* warning: node flag bits 0 and 1 should be preserved by
2158 * merge_selfsigs. For secret keys, premerge did tranfer the
2159 * keys to the keyblock */
2160 merge_selfsigs ( ctx->keyblock );
2161 if ( finish_lookup (ctx) ) {
2162 no_suitable_key = 0;
2164 merge_public_with_secret ( ctx->keyblock,
2166 release_kbnode (secblock);
2172 no_suitable_key = 1;
2175 /* release resources and continue search */
2177 release_kbnode( secblock );
2180 release_kbnode( ctx->keyblock );
2181 ctx->keyblock = NULL;
2185 if( rc && rc != -1 )
2186 log_error("keydb_search failed: %s\n", g10_errstr(rc));
2189 *ret_keyblock = ctx->keyblock; /* return the keyblock */
2190 ctx->keyblock = NULL;
2192 else if (rc == -1 && no_suitable_key)
2193 rc = secmode ? G10ERR_UNU_SECKEY : G10ERR_UNU_PUBKEY;
2195 rc = secmode ? G10ERR_NO_SECKEY : G10ERR_NO_PUBKEY;
2198 release_kbnode( secblock );
2201 release_kbnode( ctx->keyblock );
2202 ctx->keyblock = NULL;
2212 * FIXME: Replace by the generic function
2213 * It does not work as it is right now - it is used at
2214 * 2 places: a) to get the key for an anonyous recipient
2215 * b) to get the ultimately trusted keys.
2216 * The a) usage might have some problems.
2218 * Enumerate all primary secret keys. Caller must use these procedure:
2219 * 1) create a void pointer and initialize it to NULL
2220 * 2) pass this void pointer by reference to this function
2221 * and provide space for the secret key (pass a buffer for sk)
2222 * 3) call this function as long as it does not return -1
2224 * 4) Always call this function a last time with SK set to NULL,
2225 * so that can free it's context.
2228 enum_secret_keys( void **context, PKT_secret_key *sk, int with_subkeys )
2240 if( !c ) { /* make a new context */
2241 c = m_alloc_clear( sizeof *c );
2243 c->hd = keydb_new (1);
2249 if( !sk ) { /* free the context */
2250 keydb_release (c->hd);
2251 release_kbnode (c->keyblock);
2261 /* get the next secret key from the current keyblock */
2262 for (; c->node; c->node = c->node->next) {
2263 if (c->node->pkt->pkttype == PKT_SECRET_KEY
2265 && c->node->pkt->pkttype == PKT_SECRET_SUBKEY) ) {
2266 copy_secret_key (sk, c->node->pkt->pkt.secret_key );
2267 c->node = c->node->next;
2268 return 0; /* found */
2271 release_kbnode (c->keyblock);
2272 c->keyblock = c->node = NULL;
2274 rc = c->first? keydb_search_first (c->hd) : keydb_search_next (c->hd);
2277 keydb_release (c->hd); c->hd = NULL;
2279 return -1; /* eof */
2282 rc = keydb_get_keyblock (c->hd, &c->keyblock);
2283 c->node = c->keyblock;
2286 return rc; /* error */
2291 /*********************************************
2292 *********** user ID printing helpers *******
2293 *********************************************/
2296 * Return a string with a printable representation of the user_id.
2297 * this string must be freed by m_free.
2300 get_user_id_string( u32 *keyid )
2305 /* try it two times; second pass reads from key resources */
2307 for(r=user_id_db; r; r = r->next ) {
2309 for (a=r->keyids; a; a= a->next ) {
2310 if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] ) {
2311 p = m_alloc( r->len + 10 );
2312 sprintf(p, "%08lX %.*s",
2313 (ulong)keyid[1], r->len, r->name );
2318 } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
2320 sprintf(p, "%08lX [?]", (ulong)keyid[1] );
2326 get_user_id_string_native( u32 *keyid )
2328 char *p = get_user_id_string( keyid );
2329 char *p2 = utf8_to_native( p, strlen(p), 0 );
2337 get_long_user_id_string( u32 *keyid )
2342 /* try it two times; second pass reads from key resources */
2344 for(r=user_id_db; r; r = r->next ) {
2346 for (a=r->keyids; a; a= a->next ) {
2347 if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] ) {
2348 p = m_alloc( r->len + 20 );
2349 sprintf(p, "%08lX%08lX %.*s",
2350 (ulong)keyid[0], (ulong)keyid[1],
2356 } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
2358 sprintf(p, "%08lX%08lX [?]", (ulong)keyid[0], (ulong)keyid[1] );
2363 get_user_id( u32 *keyid, size_t *rn )
2369 /* try it two times; second pass reads from key resources */
2371 for(r=user_id_db; r; r = r->next ) {
2373 for (a=r->keyids; a; a= a->next ) {
2374 if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] ) {
2375 p = m_alloc( r->len );
2376 memcpy(p, r->name, r->len );
2382 } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
2383 p = m_strdup( _("[User id not found]") );
2389 get_user_id_native( u32 *keyid )
2393 char *p = get_user_id( keyid, &rn );
2394 char *p2 = utf8_to_native( p, rn, 0 );
2401 get_ctx_handle(GETKEY_CTX ctx)
2403 return ctx->kr_handle;
2406 /* Check the revocation keys to see if any of them have revoked our
2407 pk. sig is the revocation sig. pk is the key it is on. This code
2408 will need to be modified if gpg ever becomes multi-threaded. Note
2409 that this is written so that a revoked revoker can still issue
2410 revocations: i.e. If A revokes B, but A is revoked, B is still
2411 revoked. I'm not completely convinced this is the proper behavior,
2412 but it matches how PGP does it. -dms */
2414 /* Return 0 if pk is revoked, non-0 if not revoked */
2416 check_revocation_keys(PKT_public_key *pk,PKT_signature *sig)
2421 assert(IS_KEY_REV(sig));
2422 assert((sig->keyid[0]!=pk->keyid[0]) || (sig->keyid[0]!=pk->keyid[1]));
2426 /* return -1 (i.e. not revoked), but mark the pk as uncacheable
2427 as we don't really know its revocation status until it is
2428 checked directly. */
2436 /* printf("looking at %08lX with a sig from %08lX\n",(ulong)pk->keyid[1],
2437 (ulong)sig->keyid[1]); */
2439 /* is the issuer of the sig one of our revokers? */
2440 if( !pk->revkey && pk->numrevkeys )
2443 for(i=0;i<pk->numrevkeys;i++) {
2446 keyid_from_fingerprint(pk->revkey[i].fpr,MAX_FINGERPRINT_LEN,keyid);
2448 if(keyid[0]==sig->keyid[0] && keyid[1]==sig->keyid[1]) {
2451 md=md_open(sig->digest_algo,0);
2452 hash_public_key(md,pk);
2453 if(signature_check(sig,md)==0) {