~ubuntu-branches/ubuntu/trusty/gnupg2/trusty-proposed

« back to all changes in this revision

Viewing changes to .pc/CVE-2013-4351.patch/g10/getkey.c

  • Committer: Package Import Robot
  • Author(s): Marc Deslauriers
  • Date: 2013-10-07 15:38:03 UTC
  • mfrom: (18.1.4 saucy)
  • Revision ID: package-import@ubuntu.com-20131007153803-9z5dpnkp34igz6ax
Tags: 2.0.20-1ubuntu3
* SECURITY UPDATE: incorrect no-usage-permitted flag handling
  - debian/patches/CVE-2013-4351.patch: correctly handle empty key flags
    in g10/getkey.c, g10/keygen.c, include/cipher.h.
  - CVE-2013-4351
* SECURITY UPDATE: denial of service via infinite recursion
  - debian/patches/CVE-2013-4402.patch: set limits on number of filters
    and nested packets in common/iobuf.c, g10/mainproc.c.
  - CVE-2013-4402

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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.
 
4
 *
 
5
 * This file is part of GnuPG.
 
6
 *
 
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.
 
11
 *
 
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.
 
16
 *
 
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/>.
 
19
 */
 
20
 
 
21
#include <config.h>
 
22
#include <stdio.h>
 
23
#include <stdlib.h>
 
24
#include <string.h>
 
25
#include <assert.h>
 
26
#include <ctype.h>
 
27
 
 
28
#include "gpg.h"
 
29
#include "util.h"
 
30
#include "packet.h"
 
31
#include "iobuf.h"
 
32
#include "keydb.h"
 
33
#include "options.h"
 
34
#include "main.h"
 
35
#include "trustdb.h"
 
36
#include "i18n.h"
 
37
#include "keyserver-internal.h"
 
38
 
 
39
#define MAX_PK_CACHE_ENTRIES   PK_UID_CACHE_SIZE
 
40
#define MAX_UID_CACHE_ENTRIES  PK_UID_CACHE_SIZE
 
41
 
 
42
#if MAX_PK_CACHE_ENTRIES < 2
 
43
#error We need the cache for key creation
 
44
#endif
 
45
 
 
46
struct getkey_ctx_s {
 
47
    int exact;
 
48
    KBNODE keyblock;
 
49
    KBPOS  kbpos;
 
50
    KBNODE found_key; /* Pointer into some keyblock. */
 
51
    strlist_t extra_list;  /* Will be freed when releasing the context.  */
 
52
    int last_rc;
 
53
    int req_usage;
 
54
    int req_algo;
 
55
    KEYDB_HANDLE kr_handle;
 
56
    int not_allocated;
 
57
    int nitems;
 
58
    KEYDB_SEARCH_DESC items[1];
 
59
};
 
60
 
 
61
#if 0
 
62
static struct {
 
63
    int any;
 
64
    int okay_count;
 
65
    int nokey_count;
 
66
    int error_count;
 
67
} lkup_stats[21];
 
68
#endif
 
69
 
 
70
typedef struct keyid_list {
 
71
    struct keyid_list *next;
 
72
    u32 keyid[2];
 
73
} *keyid_list_t;
 
74
 
 
75
 
 
76
#if MAX_PK_CACHE_ENTRIES
 
77
  typedef struct pk_cache_entry {
 
78
      struct pk_cache_entry *next;
 
79
      u32 keyid[2];
 
80
      PKT_public_key *pk;
 
81
  } *pk_cache_entry_t;
 
82
  static pk_cache_entry_t pk_cache;
 
83
  static int pk_cache_entries;   /* number of entries in pk cache */
 
84
  static int pk_cache_disabled;
 
85
#endif
 
86
 
 
87
#if MAX_UID_CACHE_ENTRIES < 5
 
88
#error we really need the userid cache
 
89
#endif
 
90
typedef struct user_id_db {
 
91
    struct user_id_db *next;
 
92
    keyid_list_t keyids;
 
93
    int len;
 
94
    char name[1];
 
95
} *user_id_db_t;
 
96
static user_id_db_t user_id_db;
 
97
static int uid_cache_entries;   /* number of entries in uid cache */
 
98
 
 
99
static void merge_selfsigs( KBNODE keyblock );
 
100
static int lookup( GETKEY_CTX ctx, KBNODE *ret_keyblock, int secmode );
 
101
 
 
102
#if 0
 
103
static void
 
104
print_stats()
 
105
{
 
106
    int i;
 
107
    for(i=0; i < DIM(lkup_stats); i++ ) {
 
108
        if( lkup_stats[i].any )
 
109
            fprintf(stderr,
 
110
                    "lookup stats: mode=%-2d  ok=%-6d  nokey=%-6d  err=%-6d\n",
 
111
                    i,
 
112
                    lkup_stats[i].okay_count,
 
113
                    lkup_stats[i].nokey_count,
 
114
                    lkup_stats[i].error_count );
 
115
    }
 
116
}
 
117
#endif
 
118
 
 
119
 
 
120
void
 
121
cache_public_key( PKT_public_key *pk )
 
122
{
 
123
#if MAX_PK_CACHE_ENTRIES
 
124
    pk_cache_entry_t ce;
 
125
    u32 keyid[2];
 
126
 
 
127
    if( pk_cache_disabled )
 
128
        return;
 
129
 
 
130
    if( pk->dont_cache )
 
131
        return;
 
132
 
 
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 );
 
137
    }
 
138
    else
 
139
        return; /* don't know how to get the keyid */
 
140
 
 
141
    for( ce = pk_cache; ce; ce = ce->next )
 
142
        if( ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1] ) {
 
143
            if( DBG_CACHE )
 
144
                log_debug("cache_public_key: already in cache\n");
 
145
            return;
 
146
        }
 
147
 
 
148
    if( pk_cache_entries >= MAX_PK_CACHE_ENTRIES ) {
 
149
        /* fixme: use another algorithm to free some cache slots */
 
150
        pk_cache_disabled=1;
 
151
        if( opt.verbose > 1 )
 
152
            log_info(_("too many entries in pk cache - disabled\n"));
 
153
        return;
 
154
    }
 
155
    pk_cache_entries++;
 
156
    ce = xmalloc( sizeof *ce );
 
157
    ce->next = pk_cache;
 
158
    pk_cache = ce;
 
159
    ce->pk = copy_public_key( NULL, pk );
 
160
    ce->keyid[0] = keyid[0];
 
161
    ce->keyid[1] = keyid[1];
 
162
#endif
 
163
}
 
164
 
 
165
 
 
166
/* Return a const utf-8 string with the text "[User ID not found]".
 
167
   This fucntion is required so that we don't need to switch gettext's
 
168
   encoding temporary. */
 
169
static const char *
 
170
user_id_not_found_utf8 (void)
 
171
{
 
172
  static char *text;
 
173
 
 
174
  if (!text)
 
175
    text = native_to_utf8 (_("[User ID not found]"));
 
176
  return text;
 
177
}
 
178
 
 
179
 
 
180
 
 
181
/*
 
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
 
186
 */
 
187
static const char *
 
188
get_primary_uid ( KBNODE keyblock, size_t *uidlen )
 
189
{
 
190
    KBNODE k;
 
191
    const char *s;
 
192
 
 
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;
 
199
        }
 
200
    } 
 
201
    s = user_id_not_found_utf8 ();
 
202
    *uidlen = strlen (s);
 
203
    return s;
 
204
}
 
205
 
 
206
 
 
207
static void
 
208
release_keyid_list ( keyid_list_t k )
 
209
{
 
210
    while (  k ) {
 
211
        keyid_list_t k2 = k->next;
 
212
        xfree (k);
 
213
        k = k2;
 
214
    }
 
215
}
 
216
 
 
217
/****************
 
218
 * Store the association of keyid and userid
 
219
 * Feed only public keys to this function.
 
220
 */
 
221
static void
 
222
cache_user_id( KBNODE keyblock )
 
223
{
 
224
    user_id_db_t r;
 
225
    const char *uid;
 
226
    size_t uidlen;
 
227
    keyid_list_t keyids = NULL;
 
228
    KBNODE k;
 
229
 
 
230
    for (k=keyblock; k; k = k->next ) {
 
231
        if ( k->pkt->pkttype == PKT_PUBLIC_KEY
 
232
             || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
 
233
            keyid_list_t a = xmalloc_clear ( sizeof *a );
 
234
            /* Hmmm: For a long list of keyids it might be an advantage
 
235
             * to append the keys */
 
236
            keyid_from_pk( k->pkt->pkt.public_key, a->keyid );
 
237
            /* first check for duplicates */
 
238
            for(r=user_id_db; r; r = r->next ) {
 
239
                keyid_list_t b = r->keyids;
 
240
                for ( b = r->keyids; b; b = b->next ) {
 
241
                    if( b->keyid[0] == a->keyid[0]
 
242
                        && b->keyid[1] == a->keyid[1] ) {
 
243
                        if( DBG_CACHE )
 
244
                            log_debug("cache_user_id: already in cache\n");
 
245
                        release_keyid_list ( keyids );
 
246
                        xfree ( a );
 
247
                        return;
 
248
                    }
 
249
                }
 
250
            }
 
251
            /* now put it into the cache */
 
252
            a->next = keyids;
 
253
            keyids = a;
 
254
        }
 
255
    }
 
256
    if ( !keyids )
 
257
        BUG (); /* No key no fun */
 
258
 
 
259
 
 
260
    uid = get_primary_uid ( keyblock, &uidlen );
 
261
 
 
262
    if( uid_cache_entries >= MAX_UID_CACHE_ENTRIES ) {
 
263
        /* fixme: use another algorithm to free some cache slots */
 
264
        r = user_id_db;
 
265
        user_id_db = r->next;
 
266
        release_keyid_list ( r->keyids );
 
267
        xfree(r);
 
268
        uid_cache_entries--;
 
269
    }
 
270
    r = xmalloc( sizeof *r + uidlen-1 );
 
271
    r->keyids = keyids;
 
272
    r->len = uidlen;
 
273
    memcpy(r->name, uid, r->len);
 
274
    r->next = user_id_db;
 
275
    user_id_db = r;
 
276
    uid_cache_entries++;
 
277
}
 
278
 
 
279
 
 
280
void
 
281
getkey_disable_caches()
 
282
{
 
283
#if MAX_PK_CACHE_ENTRIES
 
284
    {
 
285
        pk_cache_entry_t ce, ce2;
 
286
 
 
287
        for( ce = pk_cache; ce; ce = ce2 ) {
 
288
            ce2 = ce->next;
 
289
            free_public_key( ce->pk );
 
290
            xfree( ce );
 
291
        }
 
292
        pk_cache_disabled=1;
 
293
        pk_cache_entries = 0;
 
294
        pk_cache = NULL;
 
295
    }
 
296
#endif
 
297
    /* fixme: disable user id cache ? */
 
298
}
 
299
 
 
300
 
 
301
static void
 
302
pk_from_block ( GETKEY_CTX ctx, PKT_public_key *pk, KBNODE keyblock )
 
303
{
 
304
    KBNODE a = ctx->found_key ? ctx->found_key : keyblock;
 
305
 
 
306
    assert ( a->pkt->pkttype == PKT_PUBLIC_KEY
 
307
             ||  a->pkt->pkttype == PKT_PUBLIC_SUBKEY );
 
308
     
 
309
    copy_public_key ( pk, a->pkt->pkt.public_key );
 
310
}
 
311
 
 
312
static void
 
313
sk_from_block ( GETKEY_CTX ctx,
 
314
                PKT_secret_key *sk, KBNODE keyblock )
 
315
{
 
316
    KBNODE a = ctx->found_key ? ctx->found_key : keyblock;
 
317
 
 
318
    assert ( a->pkt->pkttype == PKT_SECRET_KEY
 
319
             ||  a->pkt->pkttype == PKT_SECRET_SUBKEY );
 
320
     
 
321
    copy_secret_key( sk, a->pkt->pkt.secret_key);
 
322
}
 
323
 
 
324
 
 
325
/****************
 
326
 * Get a public key and store it into the allocated pk
 
327
 * can be called with PK set to NULL to just read it into some
 
328
 * internal structures.
 
329
 */
 
330
int
 
331
get_pubkey( PKT_public_key *pk, u32 *keyid )
 
332
{
 
333
    int internal = 0;
 
334
    int rc = 0;
 
335
 
 
336
#if MAX_PK_CACHE_ENTRIES
 
337
    if(pk)
 
338
      {
 
339
        /* Try to get it from the cache.  We don't do this when pk is
 
340
           NULL as it does not guarantee that the user IDs are
 
341
           cached. */
 
342
        pk_cache_entry_t ce;
 
343
        for( ce = pk_cache; ce; ce = ce->next )
 
344
          {
 
345
            if( ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1] )
 
346
              {
 
347
                copy_public_key( pk, ce->pk );
 
348
                return 0;
 
349
              }
 
350
          }
 
351
      }
 
352
#endif
 
353
    /* more init stuff */
 
354
    if( !pk ) {
 
355
        pk = xmalloc_clear( sizeof *pk );
 
356
        internal++;
 
357
    }
 
358
 
 
359
 
 
360
    /* do a lookup */
 
361
    {   struct getkey_ctx_s ctx;
 
362
        KBNODE kb = NULL;
 
363
        memset( &ctx, 0, sizeof ctx );
 
364
        ctx.exact = 1; /* use the key ID exactly as given */
 
365
        ctx.not_allocated = 1;
 
366
        ctx.kr_handle = keydb_new (0);
 
367
        ctx.nitems = 1;
 
368
        ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
 
369
        ctx.items[0].u.kid[0] = keyid[0];
 
370
        ctx.items[0].u.kid[1] = keyid[1];
 
371
        ctx.req_algo  = pk->req_algo;
 
372
        ctx.req_usage = pk->req_usage;
 
373
        rc = lookup( &ctx, &kb, 0 );
 
374
        if ( !rc ) {
 
375
            pk_from_block ( &ctx, pk, kb );
 
376
        }
 
377
        get_pubkey_end( &ctx );
 
378
        release_kbnode ( kb );
 
379
    }
 
380
    if( !rc )
 
381
        goto leave;
 
382
 
 
383
    rc = G10ERR_NO_PUBKEY;
 
384
 
 
385
  leave:
 
386
    if( !rc )
 
387
        cache_public_key( pk );
 
388
    if( internal )
 
389
        free_public_key(pk);
 
390
    return rc;
 
391
}
 
392
 
 
393
 
 
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. */
 
398
int
 
399
get_pubkey_fast (PKT_public_key *pk, u32 *keyid)
 
400
{
 
401
  int rc = 0;
 
402
  KEYDB_HANDLE hd;
 
403
  KBNODE keyblock;
 
404
  u32 pkid[2];
 
405
  
 
406
  assert (pk);
 
407
#if MAX_PK_CACHE_ENTRIES
 
408
  { /* Try to get it from the cache */
 
409
    pk_cache_entry_t ce;
 
410
 
 
411
    for (ce = pk_cache; ce; ce = ce->next)
 
412
      {
 
413
        if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
 
414
          {
 
415
            if (pk)
 
416
              copy_public_key (pk, ce->pk);
 
417
            return 0;
 
418
          }
 
419
      }
 
420
  }
 
421
#endif
 
422
 
 
423
  hd = keydb_new (0);
 
424
  rc = keydb_search_kid (hd, keyid);
 
425
  if (rc == -1)
 
426
    {
 
427
      keydb_release (hd);
 
428
      return G10ERR_NO_PUBKEY;
 
429
    }
 
430
  rc = keydb_get_keyblock (hd, &keyblock);
 
431
  keydb_release (hd);
 
432
  if (rc) 
 
433
    {
 
434
      log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
 
435
      return G10ERR_NO_PUBKEY;
 
436
    }
 
437
 
 
438
  assert ( keyblock->pkt->pkttype == PKT_PUBLIC_KEY
 
439
           ||  keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY );
 
440
 
 
441
  keyid_from_pk(keyblock->pkt->pkt.public_key,pkid);
 
442
  if(keyid[0]==pkid[0] && keyid[1]==pkid[1])
 
443
    copy_public_key (pk, keyblock->pkt->pkt.public_key );
 
444
  else
 
445
    rc=G10ERR_NO_PUBKEY;
 
446
 
 
447
  release_kbnode (keyblock);
 
448
 
 
449
  /* Not caching key here since it won't have all of the fields
 
450
     properly set. */
 
451
 
 
452
  return rc;
 
453
}
 
454
 
 
455
 
 
456
KBNODE
 
457
get_pubkeyblock( u32 *keyid )
 
458
{
 
459
    struct getkey_ctx_s ctx;
 
460
    int rc = 0;
 
461
    KBNODE keyblock = NULL;
 
462
 
 
463
    memset( &ctx, 0, sizeof ctx );
 
464
    /* no need to set exact here because we want the entire block */
 
465
    ctx.not_allocated = 1;
 
466
    ctx.kr_handle = keydb_new (0);
 
467
    ctx.nitems = 1;
 
468
    ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
 
469
    ctx.items[0].u.kid[0] = keyid[0];
 
470
    ctx.items[0].u.kid[1] = keyid[1];
 
471
    rc = lookup( &ctx, &keyblock, 0 );
 
472
    get_pubkey_end( &ctx );
 
473
 
 
474
    return rc ? NULL : keyblock;
 
475
}
 
476
 
 
477
 
 
478
 
 
479
 
 
480
/****************
 
481
 * Get a secret key and store it into sk
 
482
 */
 
483
int
 
484
get_seckey( PKT_secret_key *sk, u32 *keyid )
 
485
{
 
486
    int rc;
 
487
    struct getkey_ctx_s ctx;
 
488
    KBNODE kb = NULL;
 
489
 
 
490
    memset( &ctx, 0, sizeof ctx );
 
491
    ctx.exact = 1; /* use the key ID exactly as given */
 
492
    ctx.not_allocated = 1;
 
493
    ctx.kr_handle = keydb_new (1);
 
494
    ctx.nitems = 1;
 
495
    ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
 
496
    ctx.items[0].u.kid[0] = keyid[0];
 
497
    ctx.items[0].u.kid[1] = keyid[1];
 
498
    ctx.req_algo  = sk->req_algo;
 
499
    ctx.req_usage = sk->req_usage;
 
500
    rc = lookup( &ctx, &kb, 1 );
 
501
    if ( !rc ) {
 
502
        sk_from_block ( &ctx, sk, kb );
 
503
    }
 
504
    get_seckey_end( &ctx );
 
505
    release_kbnode ( kb );
 
506
 
 
507
    if( !rc ) {
 
508
        /* check the secret key (this may prompt for a passprase to
 
509
         * unlock the secret key
 
510
         */
 
511
        rc = check_secret_key( sk, 0 );
 
512
    }
 
513
 
 
514
    return rc;
 
515
}
 
516
 
 
517
 
 
518
/****************
 
519
 * Check whether the secret key is available.  This is just a fast
 
520
 * check and does not tell us whether the secret key is valid.  It
 
521
 * merely tells other whether there is some secret key.
 
522
 * Returns: 0 := key is available
 
523
 * G10ERR_NO_SECKEY := not availabe
 
524
 */
 
525
int
 
526
seckey_available( u32 *keyid )
 
527
{
 
528
    int rc;
 
529
    KEYDB_HANDLE hd = keydb_new (1);
 
530
 
 
531
    rc = keydb_search_kid (hd, keyid);
 
532
    if ( rc == -1 )
 
533
        rc = G10ERR_NO_SECKEY;
 
534
    keydb_release (hd);
 
535
    return rc;
 
536
}
 
537
 
 
538
 
 
539
/****************
 
540
 * Return the type of the user id:
 
541
 *
 
542
 * Please use the constants KEYDB_SERCH_MODE_xxx
 
543
 *  0 = Invalid user ID
 
544
 *  1 = exact match
 
545
 *  2 = match a substring
 
546
 *  3 = match an email address
 
547
 *  4 = match a substring of an email address
 
548
 *  5 = match an email address, but compare from end
 
549
 *  6 = word match mode
 
550
 * 10 = it is a short KEYID (don't care about keyid[0])
 
551
 * 11 = it is a long  KEYID
 
552
 * 12 = it is a trustdb index (keyid is looked up)
 
553
 * 16 = it is a 16 byte fingerprint
 
554
 * 20 = it is a 20 byte fingerprint
 
555
 * 21 = Unified fingerprint :fpr:pk_algo:
 
556
 *      (We don't use pk_algo yet)
 
557
 *
 
558
 * Rules used:
 
559
 * - If the username starts with 8,9,16 or 17 hex-digits (the first one
 
560
 *   must be in the range 0..9), this is considered a keyid; depending
 
561
 *   on the length a short or complete one.
 
562
 * - If the username starts with 32,33,40 or 41 hex-digits (the first one
 
563
 *   must be in the range 0..9), this is considered a fingerprint.
 
564
 * - If the username starts with a left angle, we assume it is a complete
 
565
 *   email address and look only at this part.
 
566
 * - If the username starts with a colon we assume it is a unified 
 
567
 *   key specfification. 
 
568
 * - If the username starts with a '.', we assume it is the ending
 
569
 *   part of an email address
 
570
 * - If the username starts with an '@', we assume it is a part of an
 
571
 *   email address
 
572
 * - If the userid start with an '=' an exact compare is done.
 
573
 * - If the userid starts with a '*' a case insensitive substring search is
 
574
 *   done (This is the default).
 
575
 * - If the userid starts with a '+' we will compare individual words
 
576
 *   and a match requires that all the words are in the userid.
 
577
 *   Words are delimited by white space or "()<>[]{}.@-+_,;/&!"
 
578
 *   (note that you can't search for these characters). Compare
 
579
 *   is not case sensitive.
 
580
 * - If the userid starts with a '&' a 40 hex digits keygrip is expected.
 
581
 */
 
582
 
 
583
int
 
584
classify_user_id( const char *name, KEYDB_SEARCH_DESC *desc )
 
585
{
 
586
    const char *s;
 
587
    int hexprefix = 0;
 
588
    int hexlength;
 
589
    int mode = 0;   
 
590
    KEYDB_SEARCH_DESC dummy_desc;
 
591
 
 
592
    if (!desc)
 
593
        desc = &dummy_desc;
 
594
 
 
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);
 
598
 
 
599
    /* skip leading spaces.  Fixme: what is with trailing spaces? */
 
600
    for(s = name; *s && spacep (s); s++ )
 
601
        ;
 
602
 
 
603
    switch (*s) {
 
604
        case 0:    /* empty string is an error */
 
605
            return 0;
 
606
 
 
607
#if 0
 
608
        case '.':  /* an email address, compare from end */
 
609
            mode = KEYDB_SEARCH_MODE_MAILEND;
 
610
            s++;
 
611
            desc->u.name = s;
 
612
            break;
 
613
#endif
 
614
 
 
615
        case '<':  /* an email address */
 
616
            mode = KEYDB_SEARCH_MODE_MAIL;
 
617
            desc->u.name = s;
 
618
            break;
 
619
 
 
620
        case '@':  /* part of an email address */
 
621
            mode = KEYDB_SEARCH_MODE_MAILSUB;
 
622
            s++;
 
623
            desc->u.name = s;
 
624
            break;
 
625
 
 
626
        case '=':  /* exact compare */
 
627
            mode = KEYDB_SEARCH_MODE_EXACT;
 
628
            s++;
 
629
            desc->u.name = s;
 
630
            break;
 
631
 
 
632
        case '*':  /* case insensitive substring search */
 
633
            mode = KEYDB_SEARCH_MODE_SUBSTR;
 
634
            s++;
 
635
            desc->u.name = s;
 
636
            break;
 
637
 
 
638
#if 0
 
639
        case '+':  /* compare individual words */
 
640
            mode = KEYDB_SEARCH_MODE_WORDS;
 
641
            s++;
 
642
            desc->u.name = s;
 
643
            break;
 
644
#endif
 
645
 
 
646
        case '#':  /* local user id */
 
647
            return 0; /* This is now obsolete and can't not be used anymore*/
 
648
        
 
649
        case ':': /*Unified fingerprint */
 
650
            {  
 
651
                const char *se, *si;
 
652
                int i;
 
653
                
 
654
                se = strchr( ++s,':');
 
655
                if ( !se )
 
656
                    return 0;
 
657
                for (i=0,si=s; si < se; si++, i++ ) {
 
658
                    if ( !strchr("01234567890abcdefABCDEF", *si ) )
 
659
                        return 0; /* invalid digit */
 
660
                }
 
661
                if (i != 32 && i != 40)
 
662
                    return 0; /* invalid length of fpr*/
 
663
                for (i=0,si=s; si < se; i++, si +=2) 
 
664
                    desc->u.fpr[i] = hextobyte(si);
 
665
                for ( ; i < 20; i++)
 
666
                    desc->u.fpr[i]= 0;
 
667
                s = se + 1;
 
668
                mode = KEYDB_SEARCH_MODE_FPR;
 
669
            } 
 
670
            break;
 
671
           
 
672
        case '&':  /* keygrip */
 
673
          return 0; /* Not yet implememted. */
 
674
 
 
675
        default:
 
676
            if (s[0] == '0' && s[1] == 'x') {
 
677
                hexprefix = 1;
 
678
                s += 2;
 
679
            }
 
680
 
 
681
            hexlength = strspn(s, "0123456789abcdefABCDEF");
 
682
            if (hexlength >= 8 && s[hexlength] =='!') {
 
683
                desc->exact = 1;
 
684
                hexlength++; /* just for the following check */
 
685
            }
 
686
 
 
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. */
 
693
            }
 
694
 
 
695
            if (desc->exact)
 
696
                hexlength--;
 
697
 
 
698
            if (hexlength == 8
 
699
                || (!hexprefix && hexlength == 9 && *s == '0')){
 
700
                /* short keyid */
 
701
                if (hexlength == 9)
 
702
                    s++;
 
703
                desc->u.kid[0] = 0;
 
704
                desc->u.kid[1] = strtoul( s, NULL, 16 );
 
705
                mode = KEYDB_SEARCH_MODE_SHORT_KID;
 
706
            }
 
707
            else if (hexlength == 16
 
708
                     || (!hexprefix && hexlength == 17 && *s == '0')) {
 
709
                /* complete keyid */
 
710
                char buf[9];
 
711
                if (hexlength == 17)
 
712
                    s++;
 
713
                mem2str(buf, s, 9 );
 
714
                desc->u.kid[0] = strtoul( buf, NULL, 16 );
 
715
                desc->u.kid[1] = strtoul( s+8, NULL, 16 );
 
716
                mode = KEYDB_SEARCH_MODE_LONG_KID;
 
717
            }
 
718
            else if (hexlength == 32 || (!hexprefix && hexlength == 33
 
719
                                                            && *s == '0')) {
 
720
                /* md5 fingerprint */
 
721
                int i;
 
722
                if (hexlength == 33)
 
723
                    s++;
 
724
                memset(desc->u.fpr+16, 0, 4); 
 
725
                for (i=0; i < 16; i++, s+=2) {
 
726
                    int c = hextobyte(s);
 
727
                    if (c == -1)
 
728
                        return 0;
 
729
                    desc->u.fpr[i] = c;
 
730
                }
 
731
                mode = KEYDB_SEARCH_MODE_FPR16;
 
732
            }
 
733
            else if (hexlength == 40 || (!hexprefix && hexlength == 41
 
734
                                                              && *s == '0')) {
 
735
                /* sha1/rmd160 fingerprint */
 
736
                int i;
 
737
                if (hexlength == 41)
 
738
                    s++;
 
739
                for (i=0; i < 20; i++, s+=2) {
 
740
                    int c = hextobyte(s);
 
741
                    if (c == -1)
 
742
                        return 0;
 
743
                    desc->u.fpr[i] = c;
 
744
                }
 
745
                mode = KEYDB_SEARCH_MODE_FPR20;
 
746
            }
 
747
            else {
 
748
                if (hexprefix)  /* This was a hex number with a prefix */
 
749
                    return 0;   /* and a wrong length */
 
750
 
 
751
                desc->exact = 0;
 
752
                desc->u.name = s;
 
753
                mode = KEYDB_SEARCH_MODE_SUBSTR;   /* default mode */
 
754
            }
 
755
    }
 
756
 
 
757
    desc->mode = mode;
 
758
    return mode;
 
759
}
 
760
 
 
761
 
 
762
static int
 
763
skip_unusable (void *dummy, u32 *keyid, PKT_user_id *uid)
 
764
{
 
765
  int unusable=0;
 
766
  KBNODE keyblock;
 
767
  
 
768
  (void)dummy;
 
769
 
 
770
  keyblock=get_pubkeyblock(keyid);
 
771
  if(!keyblock)
 
772
    {
 
773
      log_error("error checking usability status of %s\n",keystr(keyid));
 
774
      goto leave;
 
775
    }
 
776
 
 
777
  /* Is the user ID in question revoked/expired? */
 
778
  if(uid)
 
779
    {
 
780
      KBNODE node;
 
781
 
 
782
      for(node=keyblock;node;node=node->next)
 
783
        {
 
784
          if(node->pkt->pkttype==PKT_USER_ID)
 
785
            {
 
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))
 
789
                {
 
790
                  unusable=1;
 
791
                  break;
 
792
                }
 
793
            }
 
794
        }
 
795
    }
 
796
 
 
797
  if(!unusable)
 
798
    unusable=pk_is_disabled(keyblock->pkt->pkt.public_key);
 
799
 
 
800
 leave:
 
801
  release_kbnode(keyblock);
 
802
  return unusable;
 
803
}
 
804
 
 
805
/****************
 
806
 * Try to get the pubkey by the userid. This function looks for the
 
807
 * first pubkey certificate which has the given name in a user_id.  if
 
808
 * pk/sk has the pubkey algo set, the function will only return a
 
809
 * pubkey with that algo.  If namelist is NULL, the first key is
 
810
 * returned.  The caller should provide storage for either the pk or
 
811
 * the sk.  If ret_kb is not NULL the function will return the
 
812
 * keyblock there.
 
813
 */
 
814
 
 
815
static int
 
816
key_byname( GETKEY_CTX *retctx, strlist_t namelist,
 
817
            PKT_public_key *pk, PKT_secret_key *sk,
 
818
            int secmode, int include_unusable,
 
819
            KBNODE *ret_kb, KEYDB_HANDLE *ret_kdbhd )
 
820
{
 
821
    int rc = 0;
 
822
    int n;
 
823
    strlist_t r;
 
824
    GETKEY_CTX ctx;
 
825
    KBNODE help_kb = NULL;
 
826
    
 
827
    if( retctx ) {/* reset the returned context in case of error */
 
828
        assert (!ret_kdbhd);  /* not allowed because the handle is
 
829
                                 stored in the context */
 
830
        *retctx = NULL;
 
831
    }
 
832
    if (ret_kdbhd)
 
833
        *ret_kdbhd = NULL;
 
834
 
 
835
    if(!namelist)
 
836
      {
 
837
        ctx = xmalloc_clear (sizeof *ctx);
 
838
        ctx->nitems = 1;
 
839
        ctx->items[0].mode=KEYDB_SEARCH_MODE_FIRST;
 
840
        if(!include_unusable)
 
841
          ctx->items[0].skipfnc=skip_unusable;
 
842
      }
 
843
    else
 
844
      {
 
845
        /* build the search context */
 
846
        for(n=0, r=namelist; r; r = r->next )
 
847
          n++;
 
848
 
 
849
        ctx = xmalloc_clear (sizeof *ctx + (n-1)*sizeof ctx->items );
 
850
        ctx->nitems = n;
 
851
 
 
852
        for(n=0, r=namelist; r; r = r->next, n++ )
 
853
          {
 
854
            classify_user_id (r->d, &ctx->items[n]);
 
855
        
 
856
            if (ctx->items[n].exact)
 
857
              ctx->exact = 1;
 
858
            if (!ctx->items[n].mode)
 
859
              {
 
860
                xfree (ctx);
 
861
                return G10ERR_INV_USER_ID;
 
862
              }
 
863
            if(!include_unusable
 
864
               && ctx->items[n].mode!=KEYDB_SEARCH_MODE_SHORT_KID
 
865
               && ctx->items[n].mode!=KEYDB_SEARCH_MODE_LONG_KID
 
866
               && ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR16
 
867
               && ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR20
 
868
               && ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR)
 
869
              ctx->items[n].skipfnc=skip_unusable;
 
870
          }
 
871
      }
 
872
 
 
873
    ctx->kr_handle = keydb_new (secmode);
 
874
    if ( !ret_kb ) 
 
875
        ret_kb = &help_kb;
 
876
 
 
877
    if( secmode ) {
 
878
        if (sk) {
 
879
            ctx->req_algo  = sk->req_algo;
 
880
            ctx->req_usage = sk->req_usage;
 
881
        }
 
882
        rc = lookup( ctx, ret_kb, 1 );
 
883
        if ( !rc && sk ) {
 
884
            sk_from_block ( ctx, sk, *ret_kb );
 
885
        }
 
886
    }
 
887
    else {
 
888
        if (pk) {
 
889
            ctx->req_algo  = pk->req_algo;
 
890
            ctx->req_usage = pk->req_usage;
 
891
        }
 
892
        rc = lookup( ctx, ret_kb, 0 );
 
893
        if ( !rc && pk ) {
 
894
            pk_from_block ( ctx, pk, *ret_kb );
 
895
        }
 
896
    }
 
897
 
 
898
    release_kbnode ( help_kb );
 
899
 
 
900
    if (retctx) /* caller wants the context */
 
901
        *retctx = ctx;
 
902
    else {
 
903
        if (ret_kdbhd) {
 
904
            *ret_kdbhd = ctx->kr_handle;
 
905
            ctx->kr_handle = NULL;
 
906
        }
 
907
        get_pubkey_end (ctx);
 
908
    }
 
909
 
 
910
    return rc;
 
911
}
 
912
 
 
913
 
 
914
 
 
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.  */
 
922
int
 
923
get_pubkey_byname (GETKEY_CTX *retctx, PKT_public_key *pk,
 
924
                   const char *name, KBNODE *ret_keyblock,
 
925
                   KEYDB_HANDLE *ret_kdbhd, int include_unusable, 
 
926
                   int no_akl)
 
927
{
 
928
  int rc;
 
929
  strlist_t namelist = NULL;
 
930
  struct akl *akl;
 
931
  int is_mbox;
 
932
  int nodefault = 0;
 
933
  int anylocalfirst = 0;
 
934
 
 
935
  if (retctx)
 
936
    *retctx = NULL;
 
937
 
 
938
  is_mbox = is_valid_mailbox (name);
 
939
 
 
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. 
 
943
 
 
944
     ANYLOCALFIRST is set if the search order has the local method
 
945
     before any other or if "local" is used first by default.  This
 
946
     makes sure that if a RETCTX is used it gets only set if a local
 
947
     search has precedence over the other search methods and only then
 
948
     a followup call to get_pubkey_next shall succeed.  */
 
949
  if (!no_akl)
 
950
    {
 
951
      for (akl=opt.auto_key_locate; akl; akl=akl->next)
 
952
        if (akl->type == AKL_NODEFAULT || akl->type == AKL_LOCAL)
 
953
          {
 
954
            nodefault = 1;
 
955
            break;
 
956
          }
 
957
      for (akl=opt.auto_key_locate; akl; akl=akl->next)
 
958
        if (akl->type != AKL_NODEFAULT)
 
959
          {
 
960
            if (akl->type == AKL_LOCAL)
 
961
              anylocalfirst = 1;
 
962
            break;
 
963
          }
 
964
    }
 
965
 
 
966
  if (!nodefault)
 
967
    anylocalfirst = 1;
 
968
 
 
969
  if (nodefault && is_mbox)
 
970
    {
 
971
      /* Nodefault but a mailbox - let the AKL locate the key.  */
 
972
      rc = G10ERR_NO_PUBKEY;
 
973
    }
 
974
  else
 
975
    {
 
976
      add_to_strlist (&namelist, name);
 
977
      rc = key_byname (retctx, namelist, pk, NULL, 0,
 
978
                       include_unusable, ret_keyblock, ret_kdbhd);
 
979
    }
 
980
 
 
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)
 
984
    {
 
985
      for (akl=opt.auto_key_locate; akl; akl=akl->next)
 
986
        {
 
987
          unsigned char *fpr = NULL;
 
988
          size_t fpr_len;
 
989
          int did_key_byname = 0;
 
990
          int no_fingerprint = 0;
 
991
          const char *mechanism = "?";
 
992
          
 
993
          switch(akl->type)
 
994
            {
 
995
            case AKL_NODEFAULT:
 
996
              /* This is a dummy mechanism.  */
 
997
              mechanism = "None";
 
998
              rc = G10ERR_NO_PUBKEY;
 
999
              break;
 
1000
 
 
1001
            case AKL_LOCAL:
 
1002
              mechanism = "Local";
 
1003
              did_key_byname = 1;
 
1004
              if (retctx)
 
1005
                {
 
1006
                  get_pubkey_end (*retctx);
 
1007
                  *retctx = NULL;
 
1008
                }
 
1009
              add_to_strlist (&namelist, name);
 
1010
              rc = key_byname (anylocalfirst? retctx:NULL,
 
1011
                               namelist, pk, NULL, 0,
 
1012
                               include_unusable, ret_keyblock, ret_kdbhd);
 
1013
              break;
 
1014
 
 
1015
            case AKL_CERT:
 
1016
              mechanism = "DNS CERT";
 
1017
              glo_ctrl.in_auto_key_retrieve++;
 
1018
              rc=keyserver_import_cert(name,&fpr,&fpr_len);
 
1019
              glo_ctrl.in_auto_key_retrieve--;
 
1020
              break;
 
1021
 
 
1022
            case AKL_PKA:
 
1023
              mechanism = "PKA";
 
1024
              glo_ctrl.in_auto_key_retrieve++;
 
1025
              rc=keyserver_import_pka(name,&fpr,&fpr_len);
 
1026
              glo_ctrl.in_auto_key_retrieve--;
 
1027
              break;
 
1028
 
 
1029
            case AKL_LDAP:
 
1030
              mechanism = "LDAP";
 
1031
              glo_ctrl.in_auto_key_retrieve++;
 
1032
              rc=keyserver_import_ldap(name,&fpr,&fpr_len);
 
1033
              glo_ctrl.in_auto_key_retrieve--;
 
1034
              break;
 
1035
 
 
1036
            case AKL_KEYSERVER:
 
1037
              /* Strictly speaking, we don't need to only use a valid
 
1038
                 mailbox for the getname search, but it helps cut down
 
1039
                 on the problem of searching for something like "john"
 
1040
                 and getting a whole lot of keys back. */
 
1041
              if(opt.keyserver)
 
1042
                {
 
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--;
 
1047
                }
 
1048
              else
 
1049
                {
 
1050
                  mechanism = "Unconfigured keyserver";
 
1051
                  rc = G10ERR_NO_PUBKEY;
 
1052
                }
 
1053
              break;
 
1054
 
 
1055
            case AKL_SPEC:
 
1056
              {
 
1057
                struct keyserver_spec *keyserver;
 
1058
 
 
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--;
 
1064
              }
 
1065
              break;
 
1066
            }
 
1067
          
 
1068
          /* Use the fingerprint of the key that we actually fetched.
 
1069
             This helps prevent problems where the key that we fetched
 
1070
             doesn't have the same name that we used to fetch it.  In
 
1071
             the case of CERT and PKA, this is an actual security
 
1072
             requirement as the URL might point to a key put in by an
 
1073
             attacker.  By forcing the use of the fingerprint, we
 
1074
             won't use the attacker's key here. */
 
1075
          if (!rc && fpr)
 
1076
            {
 
1077
              char fpr_string[MAX_FINGERPRINT_LEN*2+1];
 
1078
 
 
1079
              assert(fpr_len<=MAX_FINGERPRINT_LEN);
 
1080
 
 
1081
              free_strlist(namelist);
 
1082
              namelist=NULL;
 
1083
 
 
1084
              bin2hex (fpr, fpr_len, fpr_string);
 
1085
              
 
1086
              if(opt.verbose)
 
1087
                log_info("auto-key-locate found fingerprint %s\n",fpr_string);
 
1088
 
 
1089
              add_to_strlist( &namelist, fpr_string );
 
1090
            }
 
1091
          else if (!rc && !fpr && !did_key_byname)
 
1092
            {
 
1093
              no_fingerprint = 1;
 
1094
              rc = G10ERR_NO_PUBKEY;
 
1095
            }
 
1096
          xfree (fpr);
 
1097
          fpr = NULL;
 
1098
 
 
1099
          if (!rc && !did_key_byname)
 
1100
            {
 
1101
              if (retctx)
 
1102
                {
 
1103
                  get_pubkey_end (*retctx);
 
1104
                  *retctx = NULL;
 
1105
                }
 
1106
              rc = key_byname (anylocalfirst?retctx:NULL,
 
1107
                               namelist, pk, NULL, 0,
 
1108
                               include_unusable, ret_keyblock, ret_kdbhd);
 
1109
            }
 
1110
          if (!rc)
 
1111
            {
 
1112
              /* Key found.  */
 
1113
              log_info (_("automatically retrieved `%s' via %s\n"),
 
1114
                        name, mechanism);
 
1115
              break;  
 
1116
            }
 
1117
          if (rc != G10ERR_NO_PUBKEY || opt.verbose || no_fingerprint)
 
1118
            log_info (_("error retrieving `%s' via %s: %s\n"),
 
1119
                      name, mechanism, 
 
1120
                      no_fingerprint? _("No fingerprint"):g10_errstr(rc));
 
1121
        }
 
1122
    }
 
1123
 
 
1124
  
 
1125
  if (rc && retctx)
 
1126
    {
 
1127
      get_pubkey_end (*retctx);
 
1128
      *retctx = NULL;
 
1129
    }
 
1130
 
 
1131
  if (retctx && *retctx)
 
1132
    {
 
1133
      assert (!(*retctx)->extra_list);
 
1134
      (*retctx)->extra_list = namelist;
 
1135
    }
 
1136
  else
 
1137
    free_strlist (namelist);
 
1138
  return rc;
 
1139
}
 
1140
 
 
1141
 
 
1142
int
 
1143
get_pubkey_bynames( GETKEY_CTX *retctx, PKT_public_key *pk,
 
1144
                    strlist_t names, KBNODE *ret_keyblock )
 
1145
{
 
1146
    return key_byname( retctx, names, pk, NULL, 0, 1, ret_keyblock, NULL);
 
1147
}
 
1148
 
 
1149
int
 
1150
get_pubkey_next( GETKEY_CTX ctx, PKT_public_key *pk, KBNODE *ret_keyblock )
 
1151
{
 
1152
    int rc;
 
1153
 
 
1154
    rc = lookup( ctx, ret_keyblock, 0 );
 
1155
    if ( !rc && pk && ret_keyblock )
 
1156
        pk_from_block ( ctx, pk, *ret_keyblock );
 
1157
    
 
1158
    return rc;
 
1159
}
 
1160
 
 
1161
void
 
1162
get_pubkey_end( GETKEY_CTX ctx )
 
1163
{
 
1164
    if( ctx ) {
 
1165
        memset (&ctx->kbpos, 0, sizeof ctx->kbpos);
 
1166
        keydb_release (ctx->kr_handle);
 
1167
        free_strlist (ctx->extra_list);
 
1168
        if( !ctx->not_allocated )
 
1169
            xfree( ctx );
 
1170
    }
 
1171
}
 
1172
 
 
1173
 
 
1174
/****************
 
1175
 * Search for a key with the given fingerprint.
 
1176
 * FIXME:
 
1177
 * We should replace this with the _byname function.  Thiscsan be done
 
1178
 * by creating a userID conforming to the unified fingerprint style. 
 
1179
 */
 
1180
int
 
1181
get_pubkey_byfprint( PKT_public_key *pk,
 
1182
                     const byte *fprint, size_t fprint_len)
 
1183
{
 
1184
    int rc;
 
1185
 
 
1186
    if( fprint_len == 20 || fprint_len == 16 ) {
 
1187
        struct getkey_ctx_s ctx;
 
1188
        KBNODE kb = NULL;
 
1189
 
 
1190
        memset( &ctx, 0, sizeof ctx );
 
1191
        ctx.exact = 1 ;
 
1192
        ctx.not_allocated = 1;
 
1193
        ctx.kr_handle = keydb_new (0);
 
1194
        ctx.nitems = 1;
 
1195
        ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
 
1196
                                          : KEYDB_SEARCH_MODE_FPR20;
 
1197
        memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
 
1198
        rc = lookup( &ctx, &kb, 0 );
 
1199
        if (!rc && pk )
 
1200
            pk_from_block ( &ctx, pk, kb );
 
1201
        release_kbnode ( kb );
 
1202
        get_pubkey_end( &ctx );
 
1203
    }
 
1204
    else
 
1205
        rc = G10ERR_GENERAL; /* Oops */
 
1206
    return rc;
 
1207
}
 
1208
 
 
1209
 
 
1210
/* Get a public key and store it into the allocated pk.  This function
 
1211
   differs from get_pubkey_byfprint() in that it does not do a check
 
1212
   of the key to avoid recursion.  It should be used only in very
 
1213
   certain cases.  PK may be NULL to check just for the existance of
 
1214
   the key. */
 
1215
int
 
1216
get_pubkey_byfprint_fast (PKT_public_key *pk,
 
1217
                          const byte *fprint, size_t fprint_len)
 
1218
{
 
1219
  int rc = 0;
 
1220
  KEYDB_HANDLE hd;
 
1221
  KBNODE keyblock;
 
1222
  byte fprbuf[MAX_FINGERPRINT_LEN];
 
1223
  int i;
 
1224
  
 
1225
  for (i=0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
 
1226
    fprbuf[i] = fprint[i];
 
1227
  while (i < MAX_FINGERPRINT_LEN) 
 
1228
    fprbuf[i++] = 0;
 
1229
 
 
1230
  hd = keydb_new (0);
 
1231
  rc = keydb_search_fpr (hd, fprbuf);
 
1232
  if (rc == -1)
 
1233
    {
 
1234
      keydb_release (hd);
 
1235
      return G10ERR_NO_PUBKEY;
 
1236
    }
 
1237
  rc = keydb_get_keyblock (hd, &keyblock);
 
1238
  keydb_release (hd);
 
1239
  if (rc) 
 
1240
    {
 
1241
      log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
 
1242
      return G10ERR_NO_PUBKEY;
 
1243
    }
 
1244
  
 
1245
  assert ( keyblock->pkt->pkttype == PKT_PUBLIC_KEY
 
1246
           ||  keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY );
 
1247
  if (pk)
 
1248
    copy_public_key (pk, keyblock->pkt->pkt.public_key );
 
1249
  release_kbnode (keyblock);
 
1250
 
 
1251
  /* Not caching key here since it won't have all of the fields
 
1252
     properly set. */
 
1253
 
 
1254
  return 0;
 
1255
}
 
1256
 
 
1257
/****************
 
1258
 * Search for a key with the given fingerprint and return the
 
1259
 * complete keyblock which may have more than only this key.
 
1260
 */
 
1261
int
 
1262
get_keyblock_byfprint( KBNODE *ret_keyblock, const byte *fprint,
 
1263
                                                size_t fprint_len )
 
1264
{
 
1265
    int rc;
 
1266
 
 
1267
    if( fprint_len == 20 || fprint_len == 16 ) {
 
1268
        struct getkey_ctx_s ctx;
 
1269
 
 
1270
        memset( &ctx, 0, sizeof ctx );
 
1271
        ctx.not_allocated = 1;
 
1272
        ctx.kr_handle = keydb_new (0);
 
1273
        ctx.nitems = 1;
 
1274
        ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
 
1275
                                          : KEYDB_SEARCH_MODE_FPR20;
 
1276
        memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
 
1277
        rc = lookup( &ctx, ret_keyblock, 0 );
 
1278
        get_pubkey_end( &ctx );
 
1279
    }
 
1280
    else
 
1281
        rc = G10ERR_GENERAL; /* Oops */
 
1282
 
 
1283
    return rc;
 
1284
}
 
1285
 
 
1286
 
 
1287
/****************
 
1288
 * Get a secret key by name and store it into sk
 
1289
 * If NAME is NULL use the default key
 
1290
 */
 
1291
static int
 
1292
get_seckey_byname2( GETKEY_CTX *retctx,
 
1293
                    PKT_secret_key *sk, const char *name, int unprotect,
 
1294
                    KBNODE *retblock )
 
1295
{
 
1296
  strlist_t namelist = NULL;
 
1297
  int rc,include_unusable=1;
 
1298
 
 
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. */
 
1301
 
 
1302
  if( !name && opt.def_secret_key && *opt.def_secret_key )
 
1303
    add_to_strlist( &namelist, opt.def_secret_key );
 
1304
  else if(name)
 
1305
    add_to_strlist( &namelist, name );
 
1306
  else
 
1307
    include_unusable=0;
 
1308
 
 
1309
  rc = key_byname( retctx, namelist, NULL, sk, 1, include_unusable,
 
1310
                   retblock, NULL );
 
1311
 
 
1312
  free_strlist( namelist );
 
1313
 
 
1314
  if( !rc && unprotect )
 
1315
    rc = check_secret_key( sk, 0 );
 
1316
 
 
1317
  return rc;
 
1318
}
 
1319
 
 
1320
int 
 
1321
get_seckey_byname( PKT_secret_key *sk, const char *name, int unlock )
 
1322
{
 
1323
    return get_seckey_byname2 ( NULL, sk, name, unlock, NULL );
 
1324
}
 
1325
 
 
1326
 
 
1327
int
 
1328
get_seckey_bynames( GETKEY_CTX *retctx, PKT_secret_key *sk,
 
1329
                    strlist_t names, KBNODE *ret_keyblock )
 
1330
{
 
1331
    return key_byname( retctx, names, NULL, sk, 1, 1, ret_keyblock, NULL );
 
1332
}
 
1333
 
 
1334
 
 
1335
int
 
1336
get_seckey_next( GETKEY_CTX ctx, PKT_secret_key *sk, KBNODE *ret_keyblock )
 
1337
{
 
1338
    int rc;
 
1339
 
 
1340
    rc = lookup( ctx, ret_keyblock, 1 );
 
1341
    if ( !rc && sk && ret_keyblock )
 
1342
        sk_from_block ( ctx, sk, *ret_keyblock );
 
1343
 
 
1344
    return rc;
 
1345
}
 
1346
 
 
1347
 
 
1348
void
 
1349
get_seckey_end( GETKEY_CTX ctx )
 
1350
{
 
1351
    get_pubkey_end( ctx );
 
1352
}
 
1353
 
 
1354
 
 
1355
/****************
 
1356
 * Search for a key with the given fingerprint.
 
1357
 * FIXME:
 
1358
 * We should replace this with the _byname function.  Thiscsan be done
 
1359
 * by creating a userID conforming to the unified fingerprint style. 
 
1360
 */
 
1361
int
 
1362
get_seckey_byfprint( PKT_secret_key *sk,
 
1363
                     const byte *fprint, size_t fprint_len)
 
1364
{
 
1365
    int rc;
 
1366
 
 
1367
    if( fprint_len == 20 || fprint_len == 16 ) {
 
1368
        struct getkey_ctx_s ctx;
 
1369
        KBNODE kb = NULL;
 
1370
 
 
1371
        memset( &ctx, 0, sizeof ctx );
 
1372
        ctx.exact = 1 ;
 
1373
        ctx.not_allocated = 1;
 
1374
        ctx.kr_handle = keydb_new (1);
 
1375
        ctx.nitems = 1;
 
1376
        ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
 
1377
                                          : KEYDB_SEARCH_MODE_FPR20;
 
1378
        memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
 
1379
        rc = lookup( &ctx, &kb, 1 );
 
1380
        if (!rc && sk )
 
1381
            sk_from_block ( &ctx, sk, kb );
 
1382
        release_kbnode ( kb );
 
1383
        get_seckey_end( &ctx );
 
1384
    }
 
1385
    else
 
1386
        rc = G10ERR_GENERAL; /* Oops */
 
1387
    return rc;
 
1388
}
 
1389
 
 
1390
 
 
1391
/* Search for a secret key with the given fingerprint and return the
 
1392
   complete keyblock which may have more than only this key. */
 
1393
int
 
1394
get_seckeyblock_byfprint (KBNODE *ret_keyblock, const byte *fprint,
 
1395
                          size_t fprint_len )
 
1396
{
 
1397
  int rc;
 
1398
  struct getkey_ctx_s ctx;
 
1399
  
 
1400
  if (fprint_len != 20 && fprint_len == 16)
 
1401
    return G10ERR_GENERAL; /* Oops */
 
1402
    
 
1403
  memset (&ctx, 0, sizeof ctx);
 
1404
  ctx.not_allocated = 1;
 
1405
  ctx.kr_handle = keydb_new (1);
 
1406
  ctx.nitems = 1;
 
1407
  ctx.items[0].mode = (fprint_len==16
 
1408
                       ? KEYDB_SEARCH_MODE_FPR16
 
1409
                       : KEYDB_SEARCH_MODE_FPR20);
 
1410
  memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
 
1411
  rc = lookup (&ctx, ret_keyblock, 1);
 
1412
  get_seckey_end (&ctx);
 
1413
  
 
1414
  return rc;
 
1415
}
 
1416
 
 
1417
 
 
1418
 
 
1419
/************************************************
 
1420
 ************* Merging stuff ********************
 
1421
 ************************************************/
 
1422
 
 
1423
/****************
 
1424
 * merge all selfsignatures with the keys.
 
1425
 * FIXME: replace this at least for the public key parts
 
1426
 *        by merge_selfsigs.
 
1427
 *        It is still used in keyedit.c and
 
1428
 *        at 2 or 3 other places - check whether it is really needed.
 
1429
 *        It might be needed by the key edit and import stuff because
 
1430
 *        the keylock is changed.
 
1431
 */
 
1432
void
 
1433
merge_keys_and_selfsig( KBNODE keyblock )
 
1434
{
 
1435
    PKT_public_key *pk = NULL;
 
1436
    PKT_secret_key *sk = NULL;
 
1437
    PKT_signature *sig;
 
1438
    KBNODE k;
 
1439
    u32 kid[2] = { 0, 0 };
 
1440
    u32 sigdate = 0;
 
1441
 
 
1442
    if (keyblock && keyblock->pkt->pkttype == PKT_PUBLIC_KEY ) {
 
1443
        /* divert to our new function */
 
1444
        merge_selfsigs (keyblock);
 
1445
        return;
 
1446
    }
 
1447
    /* still need the old one because the new one can't handle secret keys */
 
1448
 
 
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 );*/
 
1460
            }
 
1461
            sigdate = 0;
 
1462
        }
 
1463
        else if( k->pkt->pkttype == PKT_SECRET_KEY
 
1464
            || k->pkt->pkttype == PKT_SECRET_SUBKEY ) {
 
1465
            pk = NULL; sk = k->pkt->pkt.secret_key;
 
1466
            if( sk->version < 4 )
 
1467
                sk = NULL;
 
1468
            else if( k->pkt->pkttype == PKT_SECRET_KEY )
 
1469
                keyid_from_sk( sk, kid );
 
1470
            sigdate = 0;
 
1471
        }
 
1472
        else if( (pk || sk ) && k->pkt->pkttype == PKT_SIGNATURE
 
1473
                 && (sig=k->pkt->pkt.signature)->sig_class >= 0x10
 
1474
                 && sig->sig_class <= 0x30 && sig->version > 3
 
1475
                 && !(sig->sig_class == 0x18 || sig->sig_class == 0x28)
 
1476
                 && sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1] ) {
 
1477
            /* okay this is a self-signature which can be used.
 
1478
             * This is not used for subkey binding signature, becuase this
 
1479
             * is done above.
 
1480
             * FIXME: We should only use this if the signature is valid
 
1481
             *        but this is time consuming - we must provide another
 
1482
             *        way to handle this
 
1483
             */
 
1484
            const byte *p;
 
1485
            u32 ed;
 
1486
 
 
1487
            p = parse_sig_subpkt( sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL );
 
1488
            if( pk ) {
 
1489
                ed = p? pk->timestamp + buffer_to_u32(p):0;
 
1490
                if( sig->timestamp > sigdate ) {
 
1491
                    pk->expiredate = ed;
 
1492
                    sigdate = sig->timestamp;
 
1493
                }
 
1494
            }
 
1495
            else {
 
1496
                ed = p? sk->timestamp + buffer_to_u32(p):0;
 
1497
                if( sig->timestamp > sigdate ) {
 
1498
                    sk->expiredate = ed;
 
1499
                    sigdate = sig->timestamp;
 
1500
                }
 
1501
            }
 
1502
        }
 
1503
 
 
1504
        if(pk && (pk->expiredate==0 ||
 
1505
                  (pk->max_expiredate && pk->expiredate>pk->max_expiredate)))
 
1506
          pk->expiredate=pk->max_expiredate;
 
1507
 
 
1508
        if(sk && (sk->expiredate==0 ||
 
1509
                  (sk->max_expiredate && sk->expiredate>sk->max_expiredate)))
 
1510
          sk->expiredate=sk->max_expiredate;
 
1511
    }
 
1512
}
 
1513
 
 
1514
static int
 
1515
parse_key_usage(PKT_signature *sig)
 
1516
{
 
1517
  int key_usage=0;
 
1518
  const byte *p;
 
1519
  size_t n;
 
1520
  byte flags;
 
1521
 
 
1522
  p=parse_sig_subpkt(sig->hashed,SIGSUBPKT_KEY_FLAGS,&n);
 
1523
  if(p && n)
 
1524
    {
 
1525
      /* first octet of the keyflags */
 
1526
      flags=*p;
 
1527
 
 
1528
      if(flags & 1)
 
1529
        {
 
1530
          key_usage |= PUBKEY_USAGE_CERT;
 
1531
          flags&=~1;
 
1532
        }
 
1533
 
 
1534
      if(flags & 2)
 
1535
        {
 
1536
          key_usage |= PUBKEY_USAGE_SIG;
 
1537
          flags&=~2;
 
1538
        }
 
1539
 
 
1540
      /* We do not distinguish between encrypting communications and
 
1541
         encrypting storage. */
 
1542
      if(flags & (0x04|0x08))
 
1543
        {
 
1544
          key_usage |= PUBKEY_USAGE_ENC;
 
1545
          flags&=~(0x04|0x08);
 
1546
        }
 
1547
 
 
1548
      if(flags & 0x20)
 
1549
        {
 
1550
          key_usage |= PUBKEY_USAGE_AUTH;
 
1551
          flags&=~0x20;
 
1552
        }
 
1553
 
 
1554
      if(flags)
 
1555
        key_usage |= PUBKEY_USAGE_UNKNOWN;
 
1556
    }
 
1557
 
 
1558
  /* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
 
1559
     capability that we do not handle.  This serves to distinguish
 
1560
     between a zero key usage which we handle as the default
 
1561
     capabilities for that algorithm, and a usage that we do not
 
1562
     handle. */
 
1563
 
 
1564
  return key_usage;
 
1565
}
 
1566
 
 
1567
/*
 
1568
 * Apply information from SIGNODE (which is the valid self-signature
 
1569
 * associated with that UID) to the UIDNODE:
 
1570
 * - wether the UID has been revoked
 
1571
 * - assumed creation date of the UID
 
1572
 * - temporary store the keyflags here
 
1573
 * - temporary store the key expiration time here
 
1574
 * - mark whether the primary user ID flag hat been set.
 
1575
 * - store the preferences
 
1576
 */
 
1577
static void
 
1578
fixup_uidnode ( KBNODE uidnode, KBNODE signode, u32 keycreated )
 
1579
{
 
1580
    PKT_user_id   *uid = uidnode->pkt->pkt.user_id;
 
1581
    PKT_signature *sig = signode->pkt->pkt.signature;
 
1582
    const byte *p, *sym, *hash, *zip;
 
1583
    size_t n, nsym, nhash, nzip;
 
1584
 
 
1585
    sig->flags.chosen_selfsig = 1; /* we chose this one */
 
1586
    uid->created = 0; /* not created == invalid */
 
1587
    if ( IS_UID_REV ( sig ) ) 
 
1588
      {
 
1589
        uid->is_revoked = 1;
 
1590
        return; /* has been revoked */
 
1591
      }
 
1592
    else
 
1593
      uid->is_revoked = 0;
 
1594
 
 
1595
    uid->expiredate = sig->expiredate;
 
1596
 
 
1597
    if (sig->flags.expired)
 
1598
      {
 
1599
        uid->is_expired = 1;
 
1600
        return; /* has expired */
 
1601
      }
 
1602
    else
 
1603
      uid->is_expired = 0;
 
1604
 
 
1605
    uid->created = sig->timestamp; /* this one is okay */
 
1606
    uid->selfsigversion = sig->version;
 
1607
    /* If we got this far, it's not expired :) */
 
1608
    uid->is_expired = 0;
 
1609
 
 
1610
    /* store the key flags in the helper variable for later processing */
 
1611
    uid->help_key_usage=parse_key_usage(sig);
 
1612
 
 
1613
    /* ditto for the key expiration */
 
1614
    p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
 
1615
    if( p && buffer_to_u32(p) )
 
1616
      uid->help_key_expire = keycreated + buffer_to_u32(p);
 
1617
    else
 
1618
      uid->help_key_expire = 0;
 
1619
 
 
1620
    /* Set the primary user ID flag - we will later wipe out some
 
1621
     * of them to only have one in our keyblock */
 
1622
    uid->is_primary = 0;
 
1623
    p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL );
 
1624
    if ( p && *p )
 
1625
        uid->is_primary = 2;
 
1626
    /* We could also query this from the unhashed area if it is not in
 
1627
     * the hased area and then later try to decide which is the better
 
1628
     * there should be no security problem with this.
 
1629
     * For now we only look at the hashed one. 
 
1630
     */
 
1631
 
 
1632
    /* Now build the preferences list.  These must come from the
 
1633
       hashed section so nobody can modify the ciphers a key is
 
1634
       willing to accept. */
 
1635
    p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_SYM, &n );
 
1636
    sym = p; nsym = p?n:0;
 
1637
    p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_HASH, &n );
 
1638
    hash = p; nhash = p?n:0;
 
1639
    p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_COMPR, &n );
 
1640
    zip = p; nzip = p?n:0;
 
1641
    if (uid->prefs) 
 
1642
        xfree (uid->prefs);
 
1643
    n = nsym + nhash + nzip;
 
1644
    if (!n)
 
1645
        uid->prefs = NULL;
 
1646
    else {
 
1647
        uid->prefs = xmalloc (sizeof (*uid->prefs) * (n+1));
 
1648
        n = 0;
 
1649
        for (; nsym; nsym--, n++) {
 
1650
            uid->prefs[n].type = PREFTYPE_SYM;
 
1651
            uid->prefs[n].value = *sym++;
 
1652
        }
 
1653
        for (; nhash; nhash--, n++) {
 
1654
            uid->prefs[n].type = PREFTYPE_HASH;
 
1655
            uid->prefs[n].value = *hash++;
 
1656
        }
 
1657
        for (; nzip; nzip--, n++) {
 
1658
            uid->prefs[n].type = PREFTYPE_ZIP;
 
1659
            uid->prefs[n].value = *zip++;
 
1660
        }
 
1661
        uid->prefs[n].type = PREFTYPE_NONE; /* end of list marker */
 
1662
        uid->prefs[n].value = 0;
 
1663
    }
 
1664
 
 
1665
    /* see whether we have the MDC feature */
 
1666
    uid->flags.mdc = 0;
 
1667
    p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
 
1668
    if (p && n && (p[0] & 0x01))
 
1669
        uid->flags.mdc = 1;
 
1670
 
 
1671
    /* and the keyserver modify flag */
 
1672
    uid->flags.ks_modify = 1;
 
1673
    p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
 
1674
    if (p && n && (p[0] & 0x80))
 
1675
        uid->flags.ks_modify = 0;
 
1676
}
 
1677
 
 
1678
static void
 
1679
sig_to_revoke_info(PKT_signature *sig,struct revoke_info *rinfo)
 
1680
{
 
1681
  rinfo->date = sig->timestamp;
 
1682
  rinfo->algo = sig->pubkey_algo;
 
1683
  rinfo->keyid[0] = sig->keyid[0];
 
1684
  rinfo->keyid[1] = sig->keyid[1];
 
1685
}
 
1686
 
 
1687
static void
 
1688
merge_selfsigs_main(KBNODE keyblock, int *r_revoked, struct revoke_info *rinfo)
 
1689
{
 
1690
    PKT_public_key *pk = NULL;
 
1691
    KBNODE k;
 
1692
    u32 kid[2];
 
1693
    u32 sigdate, uiddate, uiddate2;
 
1694
    KBNODE signode, uidnode, uidnode2;
 
1695
    u32 curtime = make_timestamp ();
 
1696
    unsigned int key_usage = 0;
 
1697
    u32 keytimestamp = 0;
 
1698
    u32 key_expire = 0;
 
1699
    int key_expire_seen = 0;
 
1700
    byte sigversion = 0;
 
1701
 
 
1702
    *r_revoked = 0;
 
1703
    memset(rinfo,0,sizeof(*rinfo));
 
1704
 
 
1705
    if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY )
 
1706
        BUG ();
 
1707
    pk = keyblock->pkt->pkt.public_key;
 
1708
    keytimestamp = pk->timestamp;
 
1709
 
 
1710
    keyid_from_pk( pk, kid );
 
1711
    pk->main_keyid[0] = kid[0];
 
1712
    pk->main_keyid[1] = kid[1];
 
1713
 
 
1714
    if ( pk->version < 4 ) {
 
1715
        /* before v4 the key packet itself contains the expiration
 
1716
         * date and there was no way to change it, so we start with
 
1717
         * the one from the key packet */
 
1718
        key_expire = pk->max_expiredate;
 
1719
        key_expire_seen = 1;
 
1720
    }
 
1721
 
 
1722
    /* first pass: find the latest direct key self-signature.
 
1723
     * We assume that the newest one overrides all others
 
1724
     */
 
1725
 
 
1726
    /* In case this key was already merged */
 
1727
    xfree(pk->revkey);
 
1728
    pk->revkey=NULL;
 
1729
    pk->numrevkeys=0;
 
1730
 
 
1731
    signode = NULL;
 
1732
    sigdate = 0; /* helper to find the latest signature */
 
1733
    for(k=keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next ) {
 
1734
        if ( k->pkt->pkttype == PKT_SIGNATURE ) {
 
1735
            PKT_signature *sig = k->pkt->pkt.signature;
 
1736
            if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) { 
 
1737
                if ( check_key_signature( keyblock, k, NULL ) )
 
1738
                    ; /* signature did not verify */
 
1739
                else if ( IS_KEY_REV (sig) ){
 
1740
                    /* key has been revoked - there is no way to override
 
1741
                     * such a revocation, so we theoretically can stop now.
 
1742
                     * We should not cope with expiration times for revocations
 
1743
                     * here because we have to assume that an attacker can
 
1744
                     * generate all kinds of signatures.  However due to the
 
1745
                     * fact that the key has been revoked it does not harm
 
1746
                     * either and by continuing we gather some more info on 
 
1747
                     * that key.
 
1748
                     */ 
 
1749
                    *r_revoked = 1;
 
1750
                    sig_to_revoke_info(sig,rinfo);
 
1751
                }
 
1752
                else if ( IS_KEY_SIG (sig) ) {
 
1753
                  /* Add any revocation keys onto the pk.  This is
 
1754
                     particularly interesting since we normally only
 
1755
                     get data from the most recent 1F signature, but
 
1756
                     you need multiple 1F sigs to properly handle
 
1757
                     revocation keys (PGP does it this way, and a
 
1758
                     revocation key could be sensitive and hence in a
 
1759
                     different signature). */
 
1760
                  if(sig->revkey) {
 
1761
                    int i;
 
1762
 
 
1763
                    pk->revkey=
 
1764
                      xrealloc(pk->revkey,sizeof(struct revocation_key)*
 
1765
                                (pk->numrevkeys+sig->numrevkeys));
 
1766
 
 
1767
                    for(i=0;i<sig->numrevkeys;i++)
 
1768
                      memcpy(&pk->revkey[pk->numrevkeys++],
 
1769
                             sig->revkey[i],
 
1770
                             sizeof(struct revocation_key));
 
1771
                  }
 
1772
 
 
1773
                  if( sig->timestamp >= sigdate ) {
 
1774
                    if(sig->flags.expired)
 
1775
                        ; /* signature has expired - ignore it */
 
1776
                    else {
 
1777
                        sigdate = sig->timestamp;
 
1778
                        signode = k;
 
1779
                        if( sig->version > sigversion )
 
1780
                          sigversion = sig->version;
 
1781
 
 
1782
                    }
 
1783
                  }
 
1784
                }
 
1785
            }
 
1786
        }
 
1787
    }
 
1788
 
 
1789
    /* Remove dupes from the revocation keys */
 
1790
 
 
1791
    if(pk->revkey)
 
1792
      {
 
1793
        int i,j,x,changed=0;
 
1794
 
 
1795
        for(i=0;i<pk->numrevkeys;i++)
 
1796
          {
 
1797
            for(j=i+1;j<pk->numrevkeys;j++)
 
1798
              {
 
1799
                if(memcmp(&pk->revkey[i],&pk->revkey[j],
 
1800
                          sizeof(struct revocation_key))==0)
 
1801
                  {
 
1802
                    /* remove j */
 
1803
 
 
1804
                    for(x=j;x<pk->numrevkeys-1;x++)
 
1805
                      pk->revkey[x]=pk->revkey[x+1];
 
1806
 
 
1807
                    pk->numrevkeys--;
 
1808
                    j--;
 
1809
                    changed=1;
 
1810
                  }
 
1811
              }
 
1812
          }
 
1813
 
 
1814
        if(changed)
 
1815
          pk->revkey=xrealloc(pk->revkey,
 
1816
                               pk->numrevkeys*sizeof(struct revocation_key));
 
1817
      }
 
1818
 
 
1819
    if ( signode )
 
1820
      {
 
1821
        /* some information from a direct key signature take precedence
 
1822
         * over the same information given in UID sigs.
 
1823
         */
 
1824
        PKT_signature *sig = signode->pkt->pkt.signature;
 
1825
        const byte *p;
 
1826
 
 
1827
        key_usage=parse_key_usage(sig);
 
1828
 
 
1829
        p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
 
1830
        if( p && buffer_to_u32(p) )
 
1831
          {
 
1832
            key_expire = keytimestamp + buffer_to_u32(p);
 
1833
            key_expire_seen = 1;
 
1834
          }
 
1835
 
 
1836
        /* mark that key as valid: one direct key signature should 
 
1837
         * render a key as valid */
 
1838
        pk->is_valid = 1;
 
1839
      }
 
1840
 
 
1841
    /* pass 1.5: look for key revocation signatures that were not made
 
1842
       by the key (i.e. did a revocation key issue a revocation for
 
1843
       us?).  Only bother to do this if there is a revocation key in
 
1844
       the first place and we're not revoked already. */
 
1845
 
 
1846
    if(!*r_revoked && pk->revkey)
 
1847
      for(k=keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next )
 
1848
        {
 
1849
          if ( k->pkt->pkttype == PKT_SIGNATURE )
 
1850
            {
 
1851
              PKT_signature *sig = k->pkt->pkt.signature;
 
1852
 
 
1853
              if(IS_KEY_REV(sig) &&
 
1854
                 (sig->keyid[0]!=kid[0] || sig->keyid[1]!=kid[1]))
 
1855
                { 
 
1856
                  int rc=check_revocation_keys(pk,sig);
 
1857
                  if(rc==0)
 
1858
                    {
 
1859
                      *r_revoked=2;
 
1860
                      sig_to_revoke_info(sig,rinfo);
 
1861
                      /* don't continue checking since we can't be any
 
1862
                         more revoked than this */
 
1863
                      break;
 
1864
                    }
 
1865
                  else if(rc==G10ERR_NO_PUBKEY)
 
1866
                    pk->maybe_revoked=1;
 
1867
 
 
1868
                  /* A failure here means the sig did not verify, was
 
1869
                     not issued by a revocation key, or a revocation
 
1870
                     key loop was broken.  If a revocation key isn't
 
1871
                     findable, however, the key might be revoked and
 
1872
                     we don't know it. */
 
1873
 
 
1874
                  /* TODO: In the future handle subkey and cert
 
1875
                     revocations?  PGP doesn't, but it's in 2440. */
 
1876
                }
 
1877
            }
 
1878
        }
 
1879
 
 
1880
    /* second pass: look at the self-signature of all user IDs */
 
1881
    signode = uidnode = NULL;
 
1882
    sigdate = 0; /* helper to find the latest signature in one user ID */
 
1883
    for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next ) {
 
1884
        if ( k->pkt->pkttype == PKT_USER_ID ) {
 
1885
            if ( uidnode && signode ) 
 
1886
              {
 
1887
                fixup_uidnode ( uidnode, signode, keytimestamp );
 
1888
                pk->is_valid=1;
 
1889
              }
 
1890
            uidnode = k;
 
1891
            signode = NULL;
 
1892
            sigdate = 0;
 
1893
        }
 
1894
        else if ( k->pkt->pkttype == PKT_SIGNATURE && uidnode ) {
 
1895
            PKT_signature *sig = k->pkt->pkt.signature;
 
1896
            if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) { 
 
1897
                if ( check_key_signature( keyblock, k, NULL ) )
 
1898
                    ; /* signature did not verify */
 
1899
                else if ( (IS_UID_SIG (sig) || IS_UID_REV (sig))
 
1900
                          && sig->timestamp >= sigdate )
 
1901
                  {
 
1902
                    /* Note: we allow to invalidate cert revocations
 
1903
                     * by a newer signature.  An attacker can't use this
 
1904
                     * because a key should be revoced with a key revocation.
 
1905
                     * The reason why we have to allow for that is that at
 
1906
                     * one time an email address may become invalid but later
 
1907
                     * the same email address may become valid again (hired,
 
1908
                     * fired, hired again).
 
1909
                     */
 
1910
 
 
1911
                    sigdate = sig->timestamp;
 
1912
                    signode = k;
 
1913
                    signode->pkt->pkt.signature->flags.chosen_selfsig=0;
 
1914
                    if( sig->version > sigversion )
 
1915
                      sigversion = sig->version;
 
1916
                  }
 
1917
            }
 
1918
        }
 
1919
    }
 
1920
    if ( uidnode && signode ) {
 
1921
        fixup_uidnode ( uidnode, signode, keytimestamp );
 
1922
        pk->is_valid = 1;
 
1923
    }
 
1924
 
 
1925
    /* If the key isn't valid yet, and we have
 
1926
       --allow-non-selfsigned-uid set, then force it valid. */
 
1927
    if(!pk->is_valid && opt.allow_non_selfsigned_uid)
 
1928
      {
 
1929
        if(opt.verbose)
 
1930
          log_info(_("Invalid key %s made valid by"
 
1931
                     " --allow-non-selfsigned-uid\n"),keystr_from_pk(pk));
 
1932
        pk->is_valid = 1;
 
1933
      }
 
1934
 
 
1935
    /* The key STILL isn't valid, so try and find an ultimately
 
1936
       trusted signature. */
 
1937
    if(!pk->is_valid)
 
1938
      {
 
1939
        uidnode=NULL;
 
1940
 
 
1941
        for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k=k->next)
 
1942
          {
 
1943
            if ( k->pkt->pkttype == PKT_USER_ID )
 
1944
              uidnode = k;
 
1945
            else if ( k->pkt->pkttype == PKT_SIGNATURE && uidnode )
 
1946
              {
 
1947
                PKT_signature *sig = k->pkt->pkt.signature;
 
1948
 
 
1949
                if(sig->keyid[0] != kid[0] || sig->keyid[1]!=kid[1])
 
1950
                  {
 
1951
                    PKT_public_key *ultimate_pk;
 
1952
 
 
1953
                    ultimate_pk=xmalloc_clear(sizeof(*ultimate_pk));
 
1954
 
 
1955
                    /* We don't want to use the full get_pubkey to
 
1956
                       avoid infinite recursion in certain cases.
 
1957
                       There is no reason to check that an ultimately
 
1958
                       trusted key is still valid - if it has been
 
1959
                       revoked or the user should also renmove the
 
1960
                       ultimate trust flag.  */
 
1961
                    if(get_pubkey_fast(ultimate_pk,sig->keyid)==0
 
1962
                       && check_key_signature2(keyblock,k,ultimate_pk,
 
1963
                                               NULL,NULL,NULL,NULL)==0
 
1964
                       && get_ownertrust(ultimate_pk)==TRUST_ULTIMATE)
 
1965
                      {
 
1966
                        free_public_key(ultimate_pk);
 
1967
                        pk->is_valid=1;
 
1968
                        break;
 
1969
                      }
 
1970
 
 
1971
                    free_public_key(ultimate_pk);
 
1972
                  }
 
1973
              }
 
1974
          }
 
1975
      }
 
1976
 
 
1977
    /* Record the highest selfsig version so we know if this is a v3
 
1978
       key through and through, or a v3 key with a v4 selfsig
 
1979
       somewhere.  This is useful in a few places to know if the key
 
1980
       must be treated as PGP2-style or OpenPGP-style.  Note that a
 
1981
       selfsig revocation with a higher version number will also raise
 
1982
       this value.  This is okay since such a revocation must be
 
1983
       issued by the user (i.e. it cannot be issued by someone else to
 
1984
       modify the key behavior.) */
 
1985
 
 
1986
    pk->selfsigversion=sigversion;
 
1987
 
 
1988
    /* Now that we had a look at all user IDs we can now get some information
 
1989
     * from those user IDs.
 
1990
     */
 
1991
    
 
1992
    if ( !key_usage ) {
 
1993
        /* find the latest user ID with key flags set */
 
1994
        uiddate = 0; /* helper to find the latest user ID */
 
1995
        for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
 
1996
            k = k->next ) {
 
1997
            if ( k->pkt->pkttype == PKT_USER_ID ) {
 
1998
                PKT_user_id *uid = k->pkt->pkt.user_id;
 
1999
                if ( uid->help_key_usage && uid->created > uiddate ) {
 
2000
                    key_usage = uid->help_key_usage;
 
2001
                    uiddate = uid->created;
 
2002
                }
 
2003
            }
 
2004
        }
 
2005
    }
 
2006
    if ( !key_usage ) { /* no key flags at all: get it from the algo */
 
2007
        key_usage = openpgp_pk_algo_usage ( pk->pubkey_algo );
 
2008
    }
 
2009
    else { /* check that the usage matches the usage as given by the algo */
 
2010
        int x = openpgp_pk_algo_usage ( pk->pubkey_algo );
 
2011
        if ( x ) /* mask it down to the actual allowed usage */
 
2012
            key_usage &= x; 
 
2013
    }
 
2014
 
 
2015
    /* Whatever happens, it's a primary key, so it can certify. */
 
2016
    pk->pubkey_usage = key_usage|PUBKEY_USAGE_CERT;
 
2017
 
 
2018
    if ( !key_expire_seen ) {
 
2019
        /* find the latest valid user ID with a key expiration set 
 
2020
         * Note, that this may be a different one from the above because
 
2021
         * some user IDs may have no expiration date set */
 
2022
        uiddate = 0; 
 
2023
        for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
 
2024
            k = k->next ) {
 
2025
            if ( k->pkt->pkttype == PKT_USER_ID ) {
 
2026
                PKT_user_id *uid = k->pkt->pkt.user_id;
 
2027
                if ( uid->help_key_expire && uid->created > uiddate ) {
 
2028
                    key_expire = uid->help_key_expire;
 
2029
                    uiddate = uid->created;
 
2030
                }
 
2031
            }
 
2032
        }
 
2033
    }
 
2034
 
 
2035
    /* Currently only v3 keys have a maximum expiration date, but I'll
 
2036
       bet v5 keys get this feature again. */
 
2037
    if(key_expire==0 || (pk->max_expiredate && key_expire>pk->max_expiredate))
 
2038
      key_expire=pk->max_expiredate;
 
2039
 
 
2040
    pk->has_expired = key_expire >= curtime? 0 : key_expire;
 
2041
    pk->expiredate = key_expire;
 
2042
 
 
2043
    /* Fixme: we should see how to get rid of the expiretime fields  but
 
2044
     * this needs changes at other places too. */
 
2045
 
 
2046
    /* and now find the real primary user ID and delete all others */
 
2047
    uiddate = uiddate2 = 0;
 
2048
    uidnode = uidnode2 = NULL;
 
2049
    for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next ) {
 
2050
        if ( k->pkt->pkttype == PKT_USER_ID &&
 
2051
             !k->pkt->pkt.user_id->attrib_data) {
 
2052
            PKT_user_id *uid = k->pkt->pkt.user_id;
 
2053
            if (uid->is_primary)
 
2054
              {
 
2055
                if(uid->created > uiddate)
 
2056
                  {
 
2057
                    uiddate = uid->created;
 
2058
                    uidnode = k;
 
2059
                  }
 
2060
                else if(uid->created==uiddate && uidnode)
 
2061
                  {
 
2062
                    /* The dates are equal, so we need to do a
 
2063
                       different (and arbitrary) comparison.  This
 
2064
                       should rarely, if ever, happen.  It's good to
 
2065
                       try and guarantee that two different GnuPG
 
2066
                       users with two different keyrings at least pick
 
2067
                       the same primary. */
 
2068
                    if(cmp_user_ids(uid,uidnode->pkt->pkt.user_id)>0)
 
2069
                      uidnode=k;
 
2070
                  }
 
2071
              }
 
2072
            else
 
2073
              {
 
2074
                if(uid->created > uiddate2)
 
2075
                  {
 
2076
                    uiddate2 = uid->created;
 
2077
                    uidnode2 = k;
 
2078
                  }
 
2079
                else if(uid->created==uiddate2 && uidnode2)
 
2080
                  {
 
2081
                    if(cmp_user_ids(uid,uidnode2->pkt->pkt.user_id)>0)
 
2082
                      uidnode2=k;
 
2083
                  }
 
2084
              }
 
2085
        }
 
2086
    }
 
2087
    if ( uidnode ) {
 
2088
        for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
 
2089
            k = k->next ) {
 
2090
            if ( k->pkt->pkttype == PKT_USER_ID &&
 
2091
                 !k->pkt->pkt.user_id->attrib_data) {
 
2092
                PKT_user_id *uid = k->pkt->pkt.user_id;
 
2093
                if ( k != uidnode ) 
 
2094
                    uid->is_primary = 0;
 
2095
            }
 
2096
        }
 
2097
    }
 
2098
    else if( uidnode2 ) {
 
2099
        /* none is flagged primary - use the latest user ID we have,
 
2100
           and disambiguate with the arbitrary packet comparison. */
 
2101
        uidnode2->pkt->pkt.user_id->is_primary = 1;
 
2102
    }
 
2103
    else
 
2104
      {
 
2105
        /* None of our uids were self-signed, so pick the one that
 
2106
           sorts first to be the primary.  This is the best we can do
 
2107
           here since there are no self sigs to date the uids. */
 
2108
 
 
2109
        uidnode = NULL;
 
2110
 
 
2111
        for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
 
2112
            k = k->next )
 
2113
          {
 
2114
            if(k->pkt->pkttype==PKT_USER_ID
 
2115
               && !k->pkt->pkt.user_id->attrib_data)
 
2116
              {
 
2117
                if(!uidnode)
 
2118
                  {
 
2119
                    uidnode=k;
 
2120
                    uidnode->pkt->pkt.user_id->is_primary=1;
 
2121
                    continue;
 
2122
                  }
 
2123
                else
 
2124
                  {
 
2125
                    if(cmp_user_ids(k->pkt->pkt.user_id,
 
2126
                                    uidnode->pkt->pkt.user_id)>0)
 
2127
                      {
 
2128
                        uidnode->pkt->pkt.user_id->is_primary=0;
 
2129
                        uidnode=k;
 
2130
                        uidnode->pkt->pkt.user_id->is_primary=1;
 
2131
                      }
 
2132
                    else
 
2133
                      k->pkt->pkt.user_id->is_primary=0; /* just to be
 
2134
                                                            safe */
 
2135
                  }
 
2136
              }
 
2137
          }
 
2138
      }
 
2139
}
 
2140
 
 
2141
/* Convert a buffer to a signature.  Useful for 0x19 embedded sigs.
 
2142
   Caller must free the signature when they are done. */
 
2143
static PKT_signature *
 
2144
buf_to_sig(const byte *buf,size_t len)
 
2145
{
 
2146
  PKT_signature *sig=xmalloc_clear(sizeof(PKT_signature));
 
2147
  IOBUF iobuf=iobuf_temp_with_content(buf,len);
 
2148
  int save_mode=set_packet_list_mode(0);
 
2149
 
 
2150
  if(parse_signature(iobuf,PKT_SIGNATURE,len,sig)!=0)
 
2151
    {
 
2152
      xfree(sig);
 
2153
      sig=NULL;
 
2154
    }
 
2155
 
 
2156
  set_packet_list_mode(save_mode);
 
2157
  iobuf_close(iobuf);
 
2158
 
 
2159
  return sig;
 
2160
}
 
2161
 
 
2162
static void
 
2163
merge_selfsigs_subkey( KBNODE keyblock, KBNODE subnode )
 
2164
{
 
2165
    PKT_public_key *mainpk = NULL, *subpk = NULL;
 
2166
    PKT_signature *sig;
 
2167
    KBNODE k;
 
2168
    u32 mainkid[2];
 
2169
    u32 sigdate = 0;
 
2170
    KBNODE signode;
 
2171
    u32 curtime = make_timestamp ();
 
2172
    unsigned int key_usage = 0;
 
2173
    u32 keytimestamp = 0;
 
2174
    u32 key_expire = 0;
 
2175
    const byte *p;
 
2176
 
 
2177
    if ( subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY )
 
2178
        BUG ();
 
2179
    mainpk = keyblock->pkt->pkt.public_key;
 
2180
    if ( mainpk->version < 4 )
 
2181
        return; /* (actually this should never happen) */
 
2182
    keyid_from_pk( mainpk, mainkid );
 
2183
    subpk = subnode->pkt->pkt.public_key;
 
2184
    keytimestamp = subpk->timestamp;
 
2185
 
 
2186
    subpk->is_valid = 0;
 
2187
    subpk->main_keyid[0] = mainpk->main_keyid[0];
 
2188
    subpk->main_keyid[1] = mainpk->main_keyid[1];
 
2189
 
 
2190
    /* find the latest key binding self-signature. */
 
2191
    signode = NULL;
 
2192
    sigdate = 0; /* helper to find the latest signature */
 
2193
    for(k=subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
 
2194
                                                        k = k->next ) {
 
2195
        if ( k->pkt->pkttype == PKT_SIGNATURE ) {
 
2196
            sig = k->pkt->pkt.signature;
 
2197
            if ( sig->keyid[0] == mainkid[0] && sig->keyid[1]==mainkid[1] ) { 
 
2198
                if ( check_key_signature( keyblock, k, NULL ) )
 
2199
                    ; /* signature did not verify */
 
2200
                else if ( IS_SUBKEY_REV (sig) ) {
 
2201
                  /* Note that this means that the date on a
 
2202
                     revocation sig does not matter - even if the
 
2203
                     binding sig is dated after the revocation sig,
 
2204
                     the subkey is still marked as revoked.  This
 
2205
                     seems ok, as it is just as easy to make new
 
2206
                     subkeys rather than re-sign old ones as the
 
2207
                     problem is in the distribution.  Plus, PGP (7)
 
2208
                     does this the same way.  */
 
2209
                    subpk->is_revoked = 1;
 
2210
                    sig_to_revoke_info(sig,&subpk->revoked);
 
2211
                    /* although we could stop now, we continue to 
 
2212
                     * figure out other information like the old expiration
 
2213
                     * time */
 
2214
                }
 
2215
                else if ( IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate )
 
2216
                  {
 
2217
                    if(sig->flags.expired)
 
2218
                      ; /* signature has expired - ignore it */
 
2219
                    else
 
2220
                      {
 
2221
                        sigdate = sig->timestamp;
 
2222
                        signode = k;
 
2223
                        signode->pkt->pkt.signature->flags.chosen_selfsig=0;
 
2224
                      }
 
2225
                  }
 
2226
            }
 
2227
        }
 
2228
    }
 
2229
 
 
2230
    /* no valid key binding */
 
2231
    if ( !signode )
 
2232
      return;
 
2233
 
 
2234
    sig = signode->pkt->pkt.signature;
 
2235
    sig->flags.chosen_selfsig=1; /* so we know which selfsig we chose later */
 
2236
 
 
2237
    key_usage=parse_key_usage(sig);
 
2238
    if ( !key_usage )
 
2239
      {
 
2240
        /* no key flags at all: get it from the algo */
 
2241
        key_usage = openpgp_pk_algo_usage ( subpk->pubkey_algo );
 
2242
      }
 
2243
    else
 
2244
      {
 
2245
        /* check that the usage matches the usage as given by the algo */
 
2246
        int x = openpgp_pk_algo_usage ( subpk->pubkey_algo );
 
2247
        if ( x ) /* mask it down to the actual allowed usage */
 
2248
          key_usage &= x; 
 
2249
      }
 
2250
 
 
2251
    subpk->pubkey_usage = key_usage;
 
2252
    
 
2253
    p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
 
2254
    if ( p && buffer_to_u32(p) )
 
2255
        key_expire = keytimestamp + buffer_to_u32(p);
 
2256
    else
 
2257
        key_expire = 0;
 
2258
    subpk->has_expired = key_expire >= curtime? 0 : key_expire;
 
2259
    subpk->expiredate = key_expire;
 
2260
 
 
2261
    /* algo doesn't exist */
 
2262
    if(openpgp_pk_test_algo(subpk->pubkey_algo))
 
2263
      return;
 
2264
 
 
2265
    subpk->is_valid = 1;
 
2266
 
 
2267
    /* Find the most recent 0x19 embedded signature on our self-sig. */
 
2268
    if(subpk->backsig==0)
 
2269
      {
 
2270
        int seq=0;
 
2271
        size_t n;
 
2272
        PKT_signature *backsig=NULL;
 
2273
 
 
2274
        sigdate=0;
 
2275
 
 
2276
        /* We do this while() since there may be other embedded
 
2277
           signatures in the future.  We only want 0x19 here. */
 
2278
 
 
2279
        while((p=enum_sig_subpkt(sig->hashed,
 
2280
                                 SIGSUBPKT_SIGNATURE,&n,&seq,NULL)))
 
2281
          if(n>3 && ((p[0]==3 && p[2]==0x19) || (p[0]==4 && p[1]==0x19)))
 
2282
            {
 
2283
              PKT_signature *tempsig=buf_to_sig(p,n);
 
2284
              if(tempsig)
 
2285
                {
 
2286
                  if(tempsig->timestamp>sigdate)
 
2287
                    {
 
2288
                      if(backsig)
 
2289
                        free_seckey_enc(backsig);
 
2290
 
 
2291
                      backsig=tempsig;
 
2292
                      sigdate=backsig->timestamp;
 
2293
                    }
 
2294
                  else
 
2295
                    free_seckey_enc(tempsig);
 
2296
                }
 
2297
            }
 
2298
 
 
2299
        seq=0;
 
2300
 
 
2301
        /* It is safe to have this in the unhashed area since the 0x19
 
2302
           is located on the selfsig for convenience, not security. */
 
2303
 
 
2304
        while((p=enum_sig_subpkt(sig->unhashed,SIGSUBPKT_SIGNATURE,
 
2305
                                 &n,&seq,NULL)))
 
2306
          if(n>3 && ((p[0]==3 && p[2]==0x19) || (p[0]==4 && p[1]==0x19)))
 
2307
            {
 
2308
              PKT_signature *tempsig=buf_to_sig(p,n);
 
2309
              if(tempsig)
 
2310
                {
 
2311
                  if(tempsig->timestamp>sigdate)
 
2312
                    {
 
2313
                      if(backsig)
 
2314
                        free_seckey_enc(backsig);
 
2315
 
 
2316
                      backsig=tempsig;
 
2317
                      sigdate=backsig->timestamp;
 
2318
                    }
 
2319
                  else
 
2320
                    free_seckey_enc(tempsig);
 
2321
                }
 
2322
            }
 
2323
 
 
2324
        if(backsig)
 
2325
          {
 
2326
            /* At ths point, backsig contains the most recent 0x19 sig.
 
2327
               Let's see if it is good. */
 
2328
 
 
2329
            /* 2==valid, 1==invalid, 0==didn't check */
 
2330
            if(check_backsig(mainpk,subpk,backsig)==0)
 
2331
              subpk->backsig=2;
 
2332
            else
 
2333
              subpk->backsig=1;
 
2334
 
 
2335
            free_seckey_enc(backsig);
 
2336
          }
 
2337
      }
 
2338
}
 
2339
 
 
2340
 
 
2341
/* 
 
2342
 * Merge information from the self-signatures with the key, so that
 
2343
 * we can later use them more easy.
 
2344
 * The function works by first applying the self signatures to the
 
2345
 * primary key and the to each subkey.
 
2346
 * Here are the rules we use to decide which inormation from which
 
2347
 * self-signature is used:
 
2348
 * We check all self signatures or validity and ignore all invalid signatures.
 
2349
 * All signatures are then ordered by their creation date ....
 
2350
 * For the primary key:
 
2351
 *   FIXME the docs    
 
2352
 */
 
2353
static void
 
2354
merge_selfsigs( KBNODE keyblock )
 
2355
{
 
2356
    KBNODE k;
 
2357
    int revoked;
 
2358
    struct revoke_info rinfo;
 
2359
    PKT_public_key *main_pk;
 
2360
    prefitem_t *prefs;
 
2361
    int mdc_feature;
 
2362
 
 
2363
    if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY ) {
 
2364
        if (keyblock->pkt->pkttype == PKT_SECRET_KEY ) {
 
2365
            log_error ("expected public key but found secret key "
 
2366
                       "- must stop\n");
 
2367
            /* we better exit here becuase a public key is expected at
 
2368
               other places too.  FIXME: Figure this out earlier and
 
2369
               don't get to here at all */
 
2370
            g10_exit (1);
 
2371
        }
 
2372
        BUG ();
 
2373
    }
 
2374
 
 
2375
    merge_selfsigs_main ( keyblock, &revoked, &rinfo );
 
2376
 
 
2377
    /* now merge in the data from each of the subkeys */
 
2378
    for(k=keyblock; k; k = k->next ) {
 
2379
        if (  k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
 
2380
            merge_selfsigs_subkey ( keyblock, k );
 
2381
        }
 
2382
    }
 
2383
 
 
2384
    main_pk = keyblock->pkt->pkt.public_key;
 
2385
    if ( revoked || main_pk->has_expired || !main_pk->is_valid ) {
 
2386
        /* if the primary key is revoked, expired, or invalid we
 
2387
         * better set the appropriate flags on that key and all
 
2388
         * subkeys */
 
2389
        for(k=keyblock; k; k = k->next ) {
 
2390
            if ( k->pkt->pkttype == PKT_PUBLIC_KEY
 
2391
                || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
 
2392
                PKT_public_key *pk = k->pkt->pkt.public_key;
 
2393
                if(!main_pk->is_valid)
 
2394
                  pk->is_valid = 0;
 
2395
                if(revoked && !pk->is_revoked)
 
2396
                  {
 
2397
                    pk->is_revoked = revoked;
 
2398
                    memcpy(&pk->revoked,&rinfo,sizeof(rinfo));
 
2399
                  }
 
2400
                if(main_pk->has_expired)
 
2401
                  pk->has_expired = main_pk->has_expired;
 
2402
            }
 
2403
        }
 
2404
        return;
 
2405
    }
 
2406
 
 
2407
    /* set the preference list of all keys to those of the primary real
 
2408
     * user ID.  Note: we use these preferences when we don't know by
 
2409
     * which user ID the key has been selected.
 
2410
     * fixme: we should keep atoms of commonly used preferences or
 
2411
     * use reference counting to optimize the preference lists storage.
 
2412
     * FIXME: it might be better to use the intersection of 
 
2413
     * all preferences.
 
2414
     * Do a similar thing for the MDC feature flag.
 
2415
     */
 
2416
    prefs = NULL;
 
2417
    mdc_feature = 0;
 
2418
    for (k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) {
 
2419
        if (k->pkt->pkttype == PKT_USER_ID
 
2420
            && !k->pkt->pkt.user_id->attrib_data
 
2421
            && k->pkt->pkt.user_id->is_primary) {
 
2422
            prefs = k->pkt->pkt.user_id->prefs;
 
2423
            mdc_feature = k->pkt->pkt.user_id->flags.mdc;
 
2424
            break;
 
2425
        }
 
2426
    }    
 
2427
    for(k=keyblock; k; k = k->next ) {
 
2428
        if ( k->pkt->pkttype == PKT_PUBLIC_KEY
 
2429
             || k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
 
2430
            PKT_public_key *pk = k->pkt->pkt.public_key;
 
2431
            if (pk->prefs)
 
2432
                xfree (pk->prefs);
 
2433
            pk->prefs = copy_prefs (prefs);
 
2434
            pk->mdc_feature = mdc_feature;
 
2435
        }
 
2436
    }
 
2437
}
 
2438
 
 
2439
 
 
2440
/*
 
2441
 * Merge the secret keys from secblock into the pubblock thereby
 
2442
 * replacing the public (sub)keys with their secret counterparts Hmmm:
 
2443
 * It might be better to get away from the concept of entire secret
 
2444
 * keys at all and have a way to store just the real secret parts
 
2445
 * from the key.
 
2446
 */
 
2447
static void
 
2448
merge_public_with_secret ( KBNODE pubblock, KBNODE secblock )
 
2449
{
 
2450
    KBNODE pub;
 
2451
 
 
2452
    assert ( pubblock->pkt->pkttype == PKT_PUBLIC_KEY );
 
2453
    assert ( secblock->pkt->pkttype == PKT_SECRET_KEY );
 
2454
    
 
2455
    for (pub=pubblock; pub; pub = pub->next ) {
 
2456
        if ( pub->pkt->pkttype == PKT_PUBLIC_KEY ) {
 
2457
             PKT_public_key *pk = pub->pkt->pkt.public_key;
 
2458
             PKT_secret_key *sk = secblock->pkt->pkt.secret_key;
 
2459
             assert ( pub == pubblock ); /* only in the first node */
 
2460
             /* there is nothing to compare in this case, so just replace
 
2461
              * some information */
 
2462
             copy_public_parts_to_secret_key ( pk, sk );
 
2463
             free_public_key ( pk );
 
2464
             pub->pkt->pkttype = PKT_SECRET_KEY;
 
2465
             pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
 
2466
        }
 
2467
        else if ( pub->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
 
2468
            KBNODE sec;
 
2469
            PKT_public_key *pk = pub->pkt->pkt.public_key;
 
2470
 
 
2471
            /* this is more complicated: it may happen that the sequence
 
2472
             * of the subkeys dosn't match, so we have to find the
 
2473
             * appropriate secret key */
 
2474
            for (sec=secblock->next; sec; sec = sec->next ) {
 
2475
                if ( sec->pkt->pkttype == PKT_SECRET_SUBKEY ) {
 
2476
                    PKT_secret_key *sk = sec->pkt->pkt.secret_key;
 
2477
                    if ( !cmp_public_secret_key ( pk, sk ) ) {
 
2478
                        copy_public_parts_to_secret_key ( pk, sk );
 
2479
                        free_public_key ( pk );
 
2480
                        pub->pkt->pkttype = PKT_SECRET_SUBKEY;
 
2481
                        pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
 
2482
                        break;
 
2483
                    }
 
2484
                }
 
2485
            }
 
2486
            if ( !sec ) 
 
2487
                BUG(); /* already checked in premerge */
 
2488
        }
 
2489
    }
 
2490
}
 
2491
 
 
2492
/* This function checks that for every public subkey a corresponding
 
2493
 * secret subkey is available and deletes the public subkey otherwise.
 
2494
 * We need this function because we can't delete it later when we
 
2495
 * actually merge the secret parts into the pubring.
 
2496
 * The function also plays some games with the node flags.
 
2497
 */
 
2498
static void
 
2499
premerge_public_with_secret ( KBNODE pubblock, KBNODE secblock )
 
2500
{
 
2501
    KBNODE last, pub;
 
2502
 
 
2503
    assert ( pubblock->pkt->pkttype == PKT_PUBLIC_KEY );
 
2504
    assert ( secblock->pkt->pkttype == PKT_SECRET_KEY );
 
2505
    
 
2506
    for (pub=pubblock,last=NULL; pub; last = pub, pub = pub->next ) {
 
2507
        pub->flag &= ~3; /* reset bits 0 and 1 */
 
2508
        if ( pub->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
 
2509
            KBNODE sec;
 
2510
            PKT_public_key *pk = pub->pkt->pkt.public_key;
 
2511
 
 
2512
            for (sec=secblock->next; sec; sec = sec->next ) {
 
2513
                if ( sec->pkt->pkttype == PKT_SECRET_SUBKEY ) {
 
2514
                    PKT_secret_key *sk = sec->pkt->pkt.secret_key;
 
2515
                    if ( !cmp_public_secret_key ( pk, sk ) ) {
 
2516
                        if ( sk->protect.s2k.mode == 1001 ) {
 
2517
                            /* The secret parts are not available so
 
2518
                               we can't use that key for signing etc.
 
2519
                               Fix the pubkey usage */
 
2520
                            pk->pubkey_usage &= ~(PUBKEY_USAGE_SIG
 
2521
                                                  |PUBKEY_USAGE_AUTH);
 
2522
                        }
 
2523
                        /* transfer flag bits 0 and 1 to the pubblock */
 
2524
                        pub->flag |= (sec->flag &3);
 
2525
                        break;
 
2526
                    }
 
2527
                }
 
2528
            }
 
2529
            if ( !sec ) {
 
2530
                KBNODE next, ll;
 
2531
 
 
2532
                if (opt.verbose)
 
2533
                  log_info (_("no secret subkey"
 
2534
                              " for public subkey %s - ignoring\n"),  
 
2535
                            keystr_from_pk (pk));
 
2536
                /* we have to remove the subkey in this case */
 
2537
                assert ( last );
 
2538
                /* find the next subkey */
 
2539
                for (next=pub->next,ll=pub;
 
2540
                     next && next->pkt->pkttype != PKT_PUBLIC_SUBKEY;
 
2541
                     ll = next, next = next->next ) 
 
2542
                    ;
 
2543
                /* make new link */
 
2544
                last->next = next;
 
2545
                /* release this public subkey with all sigs */
 
2546
                ll->next = NULL;
 
2547
                release_kbnode( pub );
 
2548
                /* let the loop continue */
 
2549
                pub = last;
 
2550
            }
 
2551
        }
 
2552
    }
 
2553
    /* We need to copy the found bits (0 and 1) from the secret key to
 
2554
       the public key.  This has already been done for the subkeys but
 
2555
       got lost on the primary key - fix it here *. */
 
2556
    pubblock->flag |= (secblock->flag & 3);
 
2557
}
 
2558
 
 
2559
 
 
2560
 
 
2561
 
 
2562
/* See see whether the key fits
 
2563
 * our requirements and in case we do not
 
2564
 * request the primary key, we should select
 
2565
 * a suitable subkey.
 
2566
 * FIXME: Check against PGP 7 whether we still need a kludge
 
2567
 *        to favor type 16 keys over type 20 keys when type 20
 
2568
 *        has not been explitely requested.
 
2569
 * Returns: True when a suitable key has been found.
 
2570
 *
 
2571
 * We have to distinguish four cases:  FIXME!
 
2572
 *  1. No usage and no primary key requested
 
2573
 *     Examples for this case are that we have a keyID to be used
 
2574
 *     for decrytion or verification.
 
2575
 *  2. No usage but primary key requested
 
2576
 *     This is the case for all functions which work on an
 
2577
 *     entire keyblock, e.g. for editing or listing
 
2578
 *  3. Usage and primary key requested
 
2579
 *     FXME
 
2580
 *  4. Usage but no primary key requested
 
2581
 *     FIXME
 
2582
 * FIXME: Tell what is going to happen here and something about the rationale
 
2583
 * Note: We don't use this function if no specific usage is requested;
 
2584
 *       This way the getkey functions can be used for plain key listings.
 
2585
 *
 
2586
 * CTX ist the keyblock we are investigating, if FOUNDK is not NULL this
 
2587
 * is the key we actually found by looking at the keyid or a fingerprint and
 
2588
 * may eitehr point to the primary or one of the subkeys.
 
2589
 */
 
2590
 
 
2591
static int
 
2592
finish_lookup (GETKEY_CTX ctx)
 
2593
{
 
2594
    KBNODE keyblock = ctx->keyblock;
 
2595
    KBNODE k;
 
2596
    KBNODE foundk = NULL;
 
2597
    PKT_user_id *foundu = NULL;
 
2598
#define USAGE_MASK  (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
 
2599
    unsigned int req_usage = ( ctx->req_usage & USAGE_MASK );
 
2600
    /* Request the primary if we're certifying another key, and also
 
2601
       if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
 
2602
       do not understand signatures made by a signing subkey.  PGP 8
 
2603
       does. */
 
2604
    int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) ||
 
2605
      ((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG));
 
2606
    u32 latest_date;
 
2607
    KBNODE latest_key;
 
2608
    u32 curtime = make_timestamp ();
 
2609
 
 
2610
    assert( keyblock->pkt->pkttype == PKT_PUBLIC_KEY );
 
2611
   
 
2612
    ctx->found_key = NULL;
 
2613
 
 
2614
    if (ctx->exact) {
 
2615
        for (k=keyblock; k; k = k->next) {
 
2616
            if ( (k->flag & 1) ) {
 
2617
                assert ( k->pkt->pkttype == PKT_PUBLIC_KEY
 
2618
                         || k->pkt->pkttype == PKT_PUBLIC_SUBKEY );
 
2619
                foundk = k;
 
2620
                break;
 
2621
            }
 
2622
        }
 
2623
    }
 
2624
 
 
2625
    for (k=keyblock; k; k = k->next) {
 
2626
        if ( (k->flag & 2) ) {
 
2627
            assert (k->pkt->pkttype == PKT_USER_ID);
 
2628
            foundu = k->pkt->pkt.user_id;
 
2629
            break;
 
2630
        }
 
2631
    }
 
2632
 
 
2633
    if ( DBG_CACHE )
 
2634
        log_debug( "finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
 
2635
                   (ulong)keyid_from_pk( keyblock->pkt->pkt.public_key, NULL),
 
2636
                   foundk? "one":"all", req_usage);
 
2637
 
 
2638
    if (!req_usage) {
 
2639
        latest_key = foundk? foundk:keyblock;
 
2640
        goto found;
 
2641
    }
 
2642
    
 
2643
    latest_date = 0;
 
2644
    latest_key  = NULL;
 
2645
    /* do not look at subkeys if a certification key is requested */
 
2646
    if ((!foundk || foundk->pkt->pkttype == PKT_PUBLIC_SUBKEY) && !req_prim) {
 
2647
        KBNODE nextk;
 
2648
        /* either start a loop or check just this one subkey */
 
2649
        for (k=foundk?foundk:keyblock; k; k = nextk ) {
 
2650
            PKT_public_key *pk;
 
2651
            nextk = k->next;
 
2652
            if ( k->pkt->pkttype != PKT_PUBLIC_SUBKEY )
 
2653
                continue;
 
2654
            if ( foundk )
 
2655
                nextk = NULL;  /* what a hack */
 
2656
            pk = k->pkt->pkt.public_key;
 
2657
            if (DBG_CACHE)
 
2658
                log_debug( "\tchecking subkey %08lX\n",
 
2659
                           (ulong)keyid_from_pk( pk, NULL));
 
2660
            if ( !pk->is_valid ) {
 
2661
                if (DBG_CACHE)
 
2662
                    log_debug( "\tsubkey not valid\n");
 
2663
                continue;
 
2664
            }
 
2665
            if ( pk->is_revoked ) {
 
2666
                if (DBG_CACHE)
 
2667
                    log_debug( "\tsubkey has been revoked\n");
 
2668
                continue;
 
2669
            }
 
2670
            if ( pk->has_expired ) {
 
2671
                if (DBG_CACHE)
 
2672
                    log_debug( "\tsubkey has expired\n");
 
2673
                continue;
 
2674
            }
 
2675
            if ( pk->timestamp > curtime && !opt.ignore_valid_from ) {
 
2676
                if (DBG_CACHE)
 
2677
                    log_debug( "\tsubkey not yet valid\n");
 
2678
                continue;
 
2679
            }
 
2680
            
 
2681
            if ( !((pk->pubkey_usage&USAGE_MASK) & req_usage) ) {
 
2682
                if (DBG_CACHE)
 
2683
                    log_debug( "\tusage does not match: want=%x have=%x\n",
 
2684
                               req_usage, pk->pubkey_usage );
 
2685
                continue;
 
2686
            }
 
2687
 
 
2688
            if (DBG_CACHE)
 
2689
                log_debug( "\tsubkey might be fine\n");
 
2690
            /* In case a key has a timestamp of 0 set, we make sure
 
2691
               that it is used.  A better change would be to compare
 
2692
               ">=" but that might also change the selected keys and
 
2693
               is as such a more intrusive change.  */
 
2694
            if ( pk->timestamp > latest_date
 
2695
                 || (!pk->timestamp && !latest_date)) {
 
2696
                latest_date = pk->timestamp;
 
2697
                latest_key  = k;
 
2698
            }
 
2699
        }
 
2700
    }
 
2701
 
 
2702
    /* Okay now try the primary key unless we want an exact 
 
2703
     * key ID match on a subkey */
 
2704
    if ((!latest_key && !(ctx->exact && foundk != keyblock)) || req_prim) {
 
2705
        PKT_public_key *pk;
 
2706
        if (DBG_CACHE && !foundk && !req_prim )
 
2707
            log_debug( "\tno suitable subkeys found - trying primary\n");
 
2708
        pk = keyblock->pkt->pkt.public_key;
 
2709
        if ( !pk->is_valid ) {
 
2710
            if (DBG_CACHE)
 
2711
                log_debug( "\tprimary key not valid\n");
 
2712
        }
 
2713
        else if ( pk->is_revoked ) {
 
2714
            if (DBG_CACHE)
 
2715
                log_debug( "\tprimary key has been revoked\n");
 
2716
        }
 
2717
        else if ( pk->has_expired ) {
 
2718
            if (DBG_CACHE)
 
2719
                log_debug( "\tprimary key has expired\n");
 
2720
        }
 
2721
        else  if ( !((pk->pubkey_usage&USAGE_MASK) & req_usage) ) {
 
2722
            if (DBG_CACHE)
 
2723
                log_debug( "\tprimary key usage does not match: "
 
2724
                           "want=%x have=%x\n",
 
2725
                           req_usage, pk->pubkey_usage );
 
2726
        }
 
2727
        else { /* okay */
 
2728
            if (DBG_CACHE)
 
2729
                log_debug( "\tprimary key may be used\n");
 
2730
            latest_key = keyblock;
 
2731
            latest_date = pk->timestamp;
 
2732
        }
 
2733
    }
 
2734
    
 
2735
    if ( !latest_key ) {
 
2736
        if (DBG_CACHE)
 
2737
            log_debug("\tno suitable key found -  giving up\n");
 
2738
        return 0;
 
2739
    }
 
2740
 
 
2741
 found:
 
2742
    if (DBG_CACHE)
 
2743
        log_debug( "\tusing key %08lX\n",
 
2744
                (ulong)keyid_from_pk( latest_key->pkt->pkt.public_key, NULL) );
 
2745
 
 
2746
    if (latest_key) {
 
2747
        PKT_public_key *pk = latest_key->pkt->pkt.public_key;
 
2748
        if (pk->user_id)
 
2749
            free_user_id (pk->user_id);
 
2750
        pk->user_id = scopy_user_id (foundu);
 
2751
    }    
 
2752
        
 
2753
    ctx->found_key = latest_key;
 
2754
 
 
2755
    if (latest_key != keyblock && opt.verbose)
 
2756
      {
 
2757
        char *tempkeystr=
 
2758
          xstrdup(keystr_from_pk(latest_key->pkt->pkt.public_key));
 
2759
        log_info(_("using subkey %s instead of primary key %s\n"),
 
2760
                 tempkeystr, keystr_from_pk(keyblock->pkt->pkt.public_key));
 
2761
        xfree(tempkeystr);
 
2762
      }
 
2763
 
 
2764
    cache_user_id( keyblock );
 
2765
    
 
2766
    return 1; /* found */
 
2767
}
 
2768
 
 
2769
 
 
2770
static int
 
2771
lookup( GETKEY_CTX ctx, KBNODE *ret_keyblock, int secmode )
 
2772
{
 
2773
    int rc;
 
2774
    KBNODE secblock = NULL; /* helper */
 
2775
    int no_suitable_key = 0;
 
2776
    
 
2777
    rc = 0;
 
2778
    while (!(rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems))) {
 
2779
        /* If we are searching for the first key we have to make sure
 
2780
           that the next iteration does not do an implicit reset.
 
2781
           This can be triggered by an empty key ring. */
 
2782
        if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
 
2783
            ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
 
2784
 
 
2785
        rc = keydb_get_keyblock (ctx->kr_handle, &ctx->keyblock);
 
2786
        if (rc) {
 
2787
            log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
 
2788
            rc = 0;
 
2789
            goto skip;
 
2790
        }
 
2791
                       
 
2792
        if ( secmode ) {
 
2793
            /* find the correspondig public key and use this 
 
2794
             * this one for the selection process */
 
2795
            u32 aki[2];
 
2796
            KBNODE k = ctx->keyblock;
 
2797
            
 
2798
            if (k->pkt->pkttype != PKT_SECRET_KEY)
 
2799
                BUG();
 
2800
 
 
2801
            keyid_from_sk (k->pkt->pkt.secret_key, aki);
 
2802
            k = get_pubkeyblock (aki);
 
2803
            if( !k )
 
2804
              {
 
2805
                if (!opt.quiet)
 
2806
                  log_info(_("key %s: secret key without public key"
 
2807
                             " - skipped\n"), keystr(aki));
 
2808
                goto skip;
 
2809
              }
 
2810
            secblock = ctx->keyblock;
 
2811
            ctx->keyblock = k;
 
2812
 
 
2813
            premerge_public_with_secret ( ctx->keyblock, secblock );
 
2814
        }
 
2815
 
 
2816
        /* warning: node flag bits 0 and 1 should be preserved by
 
2817
         * merge_selfsigs.  For secret keys, premerge did tranfer the
 
2818
         * keys to the keyblock */
 
2819
        merge_selfsigs ( ctx->keyblock );
 
2820
        if ( finish_lookup (ctx) ) {
 
2821
            no_suitable_key = 0;
 
2822
            if ( secmode ) {
 
2823
                merge_public_with_secret ( ctx->keyblock,
 
2824
                                           secblock);
 
2825
                release_kbnode (secblock);
 
2826
                secblock = NULL;
 
2827
            }
 
2828
            goto found;
 
2829
        }
 
2830
        else
 
2831
            no_suitable_key = 1;
 
2832
        
 
2833
      skip:
 
2834
        /* release resources and continue search */
 
2835
        if ( secmode ) {
 
2836
            release_kbnode( secblock );
 
2837
            secblock = NULL;
 
2838
        }
 
2839
        release_kbnode( ctx->keyblock );
 
2840
        ctx->keyblock = NULL;
 
2841
    }
 
2842
 
 
2843
  found:
 
2844
    if( rc && rc != -1 )
 
2845
        log_error("keydb_search failed: %s\n", g10_errstr(rc));
 
2846
 
 
2847
    if( !rc ) {
 
2848
        *ret_keyblock = ctx->keyblock; /* return the keyblock */
 
2849
        ctx->keyblock = NULL;
 
2850
    }
 
2851
    else if (rc == -1 && no_suitable_key)
 
2852
        rc = secmode ? G10ERR_UNU_SECKEY : G10ERR_UNU_PUBKEY;
 
2853
    else if( rc == -1 )
 
2854
        rc = secmode ? G10ERR_NO_SECKEY : G10ERR_NO_PUBKEY;
 
2855
 
 
2856
    if ( secmode ) {
 
2857
        release_kbnode( secblock );
 
2858
        secblock = NULL;
 
2859
    }
 
2860
    release_kbnode( ctx->keyblock );
 
2861
    ctx->keyblock = NULL;
 
2862
 
 
2863
    ctx->last_rc = rc;
 
2864
    return rc;
 
2865
}
 
2866
 
 
2867
 
 
2868
 
 
2869
 
 
2870
/****************
 
2871
 * FIXME: Replace by the generic function 
 
2872
 *        It does not work as it is right now - it is used at 
 
2873
 *        2 places:  a) to get the key for an anonyous recipient
 
2874
 *                   b) to get the ultimately trusted keys.
 
2875
 *        The a) usage might have some problems.
 
2876
 *
 
2877
 * set with_subkeys true to include subkeys
 
2878
 * set with_spm true to include secret-parts-missing keys
 
2879
 *
 
2880
 * Enumerate all primary secret keys.  Caller must use these procedure:
 
2881
 *  1) create a void pointer and initialize it to NULL
 
2882
 *  2) pass this void pointer by reference to this function
 
2883
 *     and provide space for the secret key (pass a buffer for sk)
 
2884
 *  3) call this function as long as it does not return -1
 
2885
 *     to indicate EOF.
 
2886
 *  4) Always call this function a last time with SK set to NULL,
 
2887
 *     so that can free it's context.
 
2888
 */
 
2889
int
 
2890
enum_secret_keys( void **context, PKT_secret_key *sk,
 
2891
                  int with_subkeys, int with_spm )
 
2892
{
 
2893
    int rc=0;
 
2894
    struct {
 
2895
        int eof;
 
2896
        int first;
 
2897
        KEYDB_HANDLE hd;
 
2898
        KBNODE keyblock;
 
2899
        KBNODE node;
 
2900
    } *c = *context;
 
2901
 
 
2902
 
 
2903
    if( !c ) { /* make a new context */
 
2904
        c = xmalloc_clear( sizeof *c );
 
2905
        *context = c;
 
2906
        c->hd = keydb_new (1);
 
2907
        c->first = 1;
 
2908
        c->keyblock = NULL;
 
2909
        c->node = NULL;
 
2910
    }
 
2911
 
 
2912
    if( !sk ) { /* free the context */
 
2913
        keydb_release (c->hd);
 
2914
        release_kbnode (c->keyblock);
 
2915
        xfree( c );
 
2916
        *context = NULL;
 
2917
        return 0;
 
2918
    }
 
2919
 
 
2920
    if( c->eof )
 
2921
        return -1;
 
2922
 
 
2923
    do {
 
2924
        /* get the next secret key from the current keyblock */
 
2925
        for (; c->node; c->node = c->node->next) {
 
2926
            if ((c->node->pkt->pkttype == PKT_SECRET_KEY
 
2927
                || (with_subkeys
 
2928
                    && c->node->pkt->pkttype == PKT_SECRET_SUBKEY) )
 
2929
                && !(c->node->pkt->pkt.secret_key->protect.s2k.mode==1001
 
2930
                     && !with_spm)) {
 
2931
                copy_secret_key (sk, c->node->pkt->pkt.secret_key );
 
2932
                c->node = c->node->next;
 
2933
                return 0; /* found */
 
2934
            }
 
2935
        }
 
2936
        release_kbnode (c->keyblock);
 
2937
        c->keyblock = c->node = NULL;
 
2938
        
 
2939
        rc = c->first? keydb_search_first (c->hd) : keydb_search_next (c->hd);
 
2940
        c->first = 0;
 
2941
        if (rc) {
 
2942
            keydb_release (c->hd); c->hd = NULL;
 
2943
            c->eof = 1;
 
2944
            return -1; /* eof */
 
2945
        }
 
2946
        
 
2947
        rc = keydb_get_keyblock (c->hd, &c->keyblock);
 
2948
        c->node = c->keyblock;
 
2949
    } while (!rc);
 
2950
 
 
2951
    return rc; /* error */
 
2952
}
 
2953
 
 
2954
 
 
2955
 
 
2956
/*********************************************
 
2957
 ***********  user ID printing helpers *******
 
2958
 *********************************************/
 
2959
 
 
2960
/****************
 
2961
 * Return a string with a printable representation of the user_id.
 
2962
 * this string must be freed by xfree.
 
2963
 */
 
2964
char*
 
2965
get_user_id_string( u32 *keyid )
 
2966
{
 
2967
  user_id_db_t r;
 
2968
  char *p;
 
2969
  int pass=0;
 
2970
  /* try it two times; second pass reads from key resources */
 
2971
  do
 
2972
    {
 
2973
      for(r=user_id_db; r; r = r->next )
 
2974
        {
 
2975
          keyid_list_t a;
 
2976
          for (a=r->keyids; a; a= a->next )
 
2977
            {
 
2978
              if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] )
 
2979
                {
 
2980
                  p = xmalloc( keystrlen() + 1 + r->len + 1 );
 
2981
                  sprintf(p, "%s %.*s", keystr(keyid), r->len, r->name );
 
2982
                  return p;
 
2983
                }
 
2984
            }
 
2985
        }
 
2986
    } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
 
2987
  p = xmalloc( keystrlen() + 5 );
 
2988
  sprintf(p, "%s [?]", keystr(keyid));
 
2989
  return p;
 
2990
}
 
2991
 
 
2992
 
 
2993
char*
 
2994
get_user_id_string_native ( u32 *keyid )
 
2995
{
 
2996
  char *p = get_user_id_string( keyid );
 
2997
  char *p2 = utf8_to_native( p, strlen(p), 0 );
 
2998
  xfree(p);
 
2999
  return p2;
 
3000
}
 
3001
 
 
3002
 
 
3003
char*
 
3004
get_long_user_id_string( u32 *keyid )
 
3005
{
 
3006
    user_id_db_t r;
 
3007
    char *p;
 
3008
    int pass=0;
 
3009
    /* try it two times; second pass reads from key resources */
 
3010
    do {
 
3011
        for(r=user_id_db; r; r = r->next ) {
 
3012
            keyid_list_t a;
 
3013
            for (a=r->keyids; a; a= a->next ) {
 
3014
                if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] ) {
 
3015
                    p = xmalloc( r->len + 20 );
 
3016
                    sprintf(p, "%08lX%08lX %.*s",
 
3017
                            (ulong)keyid[0], (ulong)keyid[1],
 
3018
                            r->len, r->name );
 
3019
                    return p;
 
3020
                }
 
3021
            }
 
3022
        }
 
3023
    } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
 
3024
    p = xmalloc( 25 );
 
3025
    sprintf(p, "%08lX%08lX [?]", (ulong)keyid[0], (ulong)keyid[1] );
 
3026
    return p;
 
3027
}
 
3028
 
 
3029
char*
 
3030
get_user_id( u32 *keyid, size_t *rn )
 
3031
{
 
3032
    user_id_db_t r;
 
3033
    char *p;
 
3034
    int pass=0;
 
3035
 
 
3036
    /* try it two times; second pass reads from key resources */
 
3037
    do {
 
3038
        for(r=user_id_db; r; r = r->next ) {
 
3039
            keyid_list_t a;
 
3040
            for (a=r->keyids; a; a= a->next ) {
 
3041
                if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] ) {
 
3042
                    p = xmalloc( r->len );
 
3043
                    memcpy(p, r->name, r->len );
 
3044
                    *rn = r->len;
 
3045
                    return p;
 
3046
                }
 
3047
            }
 
3048
        }
 
3049
    } while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
 
3050
    p = xstrdup( user_id_not_found_utf8 () );
 
3051
    *rn = strlen(p);
 
3052
    return p;
 
3053
}
 
3054
 
 
3055
char*
 
3056
get_user_id_native( u32 *keyid )
 
3057
{
 
3058
  size_t rn;
 
3059
  char *p = get_user_id( keyid, &rn );
 
3060
  char *p2 = utf8_to_native( p, rn, 0 );
 
3061
  xfree(p);
 
3062
  return p2;
 
3063
}
 
3064
 
 
3065
KEYDB_HANDLE
 
3066
get_ctx_handle(GETKEY_CTX ctx)
 
3067
{
 
3068
  return ctx->kr_handle;
 
3069
}
 
3070
 
 
3071
static void
 
3072
free_akl(struct akl *akl)
 
3073
{
 
3074
  if(akl->spec)
 
3075
    free_keyserver_spec(akl->spec);
 
3076
 
 
3077
  xfree(akl);
 
3078
}
 
3079
 
 
3080
void
 
3081
release_akl(void)
 
3082
{
 
3083
  while(opt.auto_key_locate)
 
3084
    {
 
3085
      struct akl *akl2=opt.auto_key_locate;
 
3086
      opt.auto_key_locate=opt.auto_key_locate->next;
 
3087
      free_akl(akl2);
 
3088
    }
 
3089
}
 
3090
 
 
3091
/* Returns false on error. */
 
3092
int
 
3093
parse_auto_key_locate(char *options)
 
3094
{
 
3095
  char *tok;
 
3096
 
 
3097
  while((tok=optsep(&options)))
 
3098
    {
 
3099
      struct akl *akl,*check,*last=NULL;
 
3100
      int dupe=0;
 
3101
 
 
3102
      if(tok[0]=='\0')
 
3103
        continue;
 
3104
 
 
3105
      akl=xmalloc_clear(sizeof(*akl));
 
3106
 
 
3107
      if(ascii_strcasecmp(tok,"nodefault")==0)
 
3108
        akl->type=AKL_NODEFAULT;
 
3109
      else if(ascii_strcasecmp(tok,"local")==0)
 
3110
        akl->type=AKL_LOCAL;
 
3111
      else if(ascii_strcasecmp(tok,"ldap")==0)
 
3112
        akl->type=AKL_LDAP;
 
3113
      else if(ascii_strcasecmp(tok,"keyserver")==0)
 
3114
        akl->type=AKL_KEYSERVER;
 
3115
#ifdef USE_DNS_CERT
 
3116
      else if(ascii_strcasecmp(tok,"cert")==0)
 
3117
        akl->type=AKL_CERT;
 
3118
#endif
 
3119
#ifdef USE_DNS_PKA
 
3120
      else if(ascii_strcasecmp(tok,"pka")==0)
 
3121
        akl->type=AKL_PKA;
 
3122
#endif
 
3123
      else if((akl->spec=parse_keyserver_uri(tok,1,NULL,0)))
 
3124
        akl->type=AKL_SPEC;
 
3125
      else
 
3126
        {
 
3127
          free_akl(akl);
 
3128
          return 0;
 
3129
        }
 
3130
 
 
3131
      /* We must maintain the order the user gave us */
 
3132
      for(check=opt.auto_key_locate;check;last=check,check=check->next)
 
3133
        {
 
3134
          /* Check for duplicates */
 
3135
          if(check->type==akl->type
 
3136
             && (akl->type!=AKL_SPEC
 
3137
                 || (akl->type==AKL_SPEC
 
3138
                     && strcmp(check->spec->uri,akl->spec->uri)==0)))
 
3139
            {
 
3140
              dupe=1;
 
3141
              free_akl(akl);
 
3142
              break;
 
3143
            }
 
3144
        }
 
3145
 
 
3146
      if(!dupe)
 
3147
        {
 
3148
          if(last)
 
3149
            last->next=akl;
 
3150
          else
 
3151
            opt.auto_key_locate=akl;
 
3152
        }
 
3153
    }
 
3154
 
 
3155
  return 1;
 
3156
}