~ubuntu-branches/ubuntu/jaunty/gnupg2/jaunty

« back to all changes in this revision

Viewing changes to g10/app-openpgp.c

  • Committer: Bazaar Package Importer
  • Author(s): Andreas Mueller
  • Date: 2005-03-29 10:30:32 UTC
  • Revision ID: james.westby@ubuntu.com-20050329103032-sj42n2ain3ipx310
Tags: upstream-1.9.15
ImportĀ upstreamĀ versionĀ 1.9.15

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* app-openpgp.c - The OpenPGP card application.
 
2
 *      Copyright (C) 2003, 2004 Free Software Foundation, Inc.
 
3
 *
 
4
 * This file is part of GnuPG.
 
5
 *
 
6
 * GnuPG is free software; you can redistribute it and/or modify
 
7
 * it under the terms of the GNU General Public License as published by
 
8
 * the Free Software Foundation; either version 2 of the License, or
 
9
 * (at your option) any later version.
 
10
 *
 
11
 * GnuPG is distributed in the hope that it will be useful,
 
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
14
 * GNU General Public License for more details.
 
15
 *
 
16
 * You should have received a copy of the GNU General Public License
 
17
 * along with this program; if not, write to the Free Software
 
18
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 
19
 *
 
20
 * $Id: app-openpgp.c,v 1.21 2004/12/09 16:57:30 wk Exp $
 
21
 */
 
22
 
 
23
#include <config.h>
 
24
#include <errno.h>
 
25
#include <stdio.h>
 
26
#include <stdlib.h>
 
27
#include <string.h>
 
28
#include <assert.h>
 
29
#include <time.h>
 
30
 
 
31
#if GNUPG_MAJOR_VERSION == 1
 
32
/* This is used with GnuPG version < 1.9.  The code has been source
 
33
   copied from the current GnuPG >= 1.9  and is maintained over
 
34
   there. */
 
35
#include "options.h"
 
36
#include "errors.h"
 
37
#include "memory.h"
 
38
#include "util.h"
 
39
#include "cardglue.h"
 
40
#else /* GNUPG_MAJOR_VERSION != 1 */
 
41
#include "scdaemon.h"
 
42
#endif /* GNUPG_MAJOR_VERSION != 1 */
 
43
 
 
44
#include "i18n.h"
 
45
#include "iso7816.h"
 
46
#include "app-common.h"
 
47
#include "tlv.h"
 
48
 
 
49
 
 
50
static struct {
 
51
  int tag;
 
52
  int constructed;
 
53
  int get_from;  /* Constructed DO with this DO or 0 for direct access. */
 
54
  int binary;
 
55
  int dont_cache;
 
56
  int flush_on_error;
 
57
  int get_immediate_in_v11; /* Enable a hack to bypass the cache of
 
58
                               this data object if it is used in 1.1
 
59
                               and later versions of the card.  This
 
60
                               does not work with composite DO and is
 
61
                               currently only useful for the CHV
 
62
                               status bytes. */
 
63
  char *desc;
 
64
} data_objects[] = {
 
65
  { 0x005E, 0,    0, 1, 0, 0, 0, "Login Data" },
 
66
  { 0x5F50, 0,    0, 0, 0, 0, 0, "URL" },
 
67
  { 0x0065, 1,    0, 1, 0, 0, 0, "Cardholder Related Data"},
 
68
  { 0x005B, 0, 0x65, 0, 0, 0, 0, "Name" },
 
69
  { 0x5F2D, 0, 0x65, 0, 0, 0, 0, "Language preferences" },
 
70
  { 0x5F35, 0, 0x65, 0, 0, 0, 0, "Sex" },
 
71
  { 0x006E, 1,    0, 1, 0, 0, 0, "Application Related Data" },
 
72
  { 0x004F, 0, 0x6E, 1, 0, 0, 0, "AID" },
 
73
  { 0x0073, 1,    0, 1, 0, 0, 0, "Discretionary Data Objects" },
 
74
  { 0x0047, 0, 0x6E, 1, 1, 0, 0, "Card Capabilities" },
 
75
  { 0x00C0, 0, 0x6E, 1, 1, 0, 0, "Extended Card Capabilities" },
 
76
  { 0x00C1, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Signature" },
 
77
  { 0x00C2, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Decryption" },
 
78
  { 0x00C3, 0, 0x6E, 1, 1, 0, 0, "Algorithm Attributes Authentication" },
 
79
  { 0x00C4, 0, 0x6E, 1, 0, 1, 1, "CHV Status Bytes" },
 
80
  { 0x00C5, 0, 0x6E, 1, 0, 0, 0, "Fingerprints" },
 
81
  { 0x00C6, 0, 0x6E, 1, 0, 0, 0, "CA Fingerprints" },
 
82
  { 0x00CD, 0, 0x6E, 1, 0, 0, 0, "Generation time" },
 
83
  { 0x007A, 1,    0, 1, 0, 0, 0, "Security Support Template" },
 
84
  { 0x0093, 0, 0x7A, 1, 1, 0, 0, "Digital Signature Counter" },
 
85
  { 0x0101, 0,    0, 0, 0, 0, 0, "Private DO 1"},
 
86
  { 0x0102, 0,    0, 0, 0, 0, 0, "Private DO 2"},
 
87
  { 0x0103, 0,    0, 0, 0, 0, 0, "Private DO 3"},
 
88
  { 0x0104, 0,    0, 0, 0, 0, 0, "Private DO 4"},
 
89
  { 0 }
 
90
};
 
91
 
 
92
 
 
93
struct cache_s {
 
94
  struct cache_s *next;
 
95
  int tag;
 
96
  size_t length;
 
97
  unsigned char data[1];
 
98
};
 
99
 
 
100
struct app_local_s {
 
101
  struct cache_s *cache;
 
102
  struct 
 
103
  {
 
104
    unsigned int get_challenge:1;
 
105
    unsigned int key_import:1;
 
106
    unsigned int change_force_chv:1;
 
107
    unsigned int private_dos:1;
 
108
  } extcap;
 
109
  struct
 
110
  {
 
111
    unsigned int no_sync:1;   /* Do not sync CHV1 and CHV2 */
 
112
    unsigned int def_chv2:1;  /* Use 123456 for CHV2.  */
 
113
  } flags;
 
114
};
 
115
 
 
116
 
 
117
static unsigned long convert_sig_counter_value (const unsigned char *value,
 
118
                                                size_t valuelen);
 
119
static unsigned long get_sig_counter (APP app);
 
120
 
 
121
/* Deconstructor. */
 
122
static void
 
123
do_deinit (app_t app)
 
124
{
 
125
  if (app && app->app_local)
 
126
    {
 
127
      struct cache_s *c, *c2;
 
128
 
 
129
      for (c = app->app_local->cache; c; c = c2)
 
130
        {
 
131
          c2 = c->next;
 
132
          xfree (c);
 
133
        }
 
134
      xfree (app->app_local);
 
135
      app->app_local = NULL;
 
136
    }
 
137
}
 
138
 
 
139
 
 
140
/* Wrapper around iso7816_get_data which first tries to get the data
 
141
   from the cache. */
 
142
static gpg_error_t
 
143
get_cached_data (app_t app, int tag, 
 
144
                 unsigned char **result, size_t *resultlen)
 
145
{
 
146
  gpg_error_t err;
 
147
  int i;
 
148
  unsigned char *p;
 
149
  size_t len;
 
150
  struct cache_s *c;
 
151
 
 
152
  *result = NULL;
 
153
  *resultlen = 0;
 
154
 
 
155
  for (c=app->app_local->cache; c; c = c->next)
 
156
    if (c->tag == tag)
 
157
      {
 
158
        if(c->length)
 
159
          {
 
160
            p = xtrymalloc (c->length);
 
161
            if (!p)
 
162
              return gpg_error (gpg_err_code_from_errno (errno));
 
163
            memcpy (p, c->data, c->length);
 
164
            *result = p;
 
165
          }
 
166
 
 
167
        *resultlen = c->length;
 
168
 
 
169
        return 0;
 
170
      }
 
171
 
 
172
  
 
173
  err = iso7816_get_data (app->slot, tag, &p, &len);
 
174
  if (err)
 
175
    return err;
 
176
  *result = p;
 
177
  *resultlen = len;
 
178
 
 
179
  /* Check whether we should cache this object. */
 
180
  for (i=0; data_objects[i].tag; i++)
 
181
    if (data_objects[i].tag == tag)
 
182
      {
 
183
        if (data_objects[i].dont_cache)
 
184
          return 0;
 
185
        break;
 
186
      }
 
187
 
 
188
  /* No, cache it. */
 
189
 
 
190
  for (c=app->app_local->cache; c; c = c->next)
 
191
    assert (c->tag != tag);
 
192
  
 
193
  c = xtrymalloc (sizeof *c + len);
 
194
  if (c)
 
195
    {
 
196
      memcpy (c->data, p, len);
 
197
      c->length = len;
 
198
      c->tag = tag;
 
199
      c->next = app->app_local->cache;
 
200
      app->app_local->cache = c;
 
201
    }
 
202
 
 
203
  return 0;
 
204
}
 
205
 
 
206
/* Remove DO at TAG from the cache. */
 
207
static void
 
208
flush_cache_item (app_t app, int tag)
 
209
{
 
210
  struct cache_s *c, *cprev;
 
211
  int i;
 
212
 
 
213
  if (!app->app_local)
 
214
    return;
 
215
 
 
216
  for (c=app->app_local->cache, cprev=NULL; c ; cprev=c, c = c->next)
 
217
    if (c->tag == tag)
 
218
      {
 
219
        if (cprev)
 
220
          cprev->next = c->next;
 
221
        else
 
222
          app->app_local->cache = c->next;
 
223
        xfree (c);
 
224
 
 
225
        for (c=app->app_local->cache; c ; c = c->next)
 
226
          {
 
227
            assert (c->tag != tag); /* Oops: duplicated entry. */
 
228
          }
 
229
        return;
 
230
      }
 
231
 
 
232
  /* Try again if we have an outer tag. */
 
233
  for (i=0; data_objects[i].tag; i++)
 
234
    if (data_objects[i].tag == tag && data_objects[i].get_from
 
235
        && data_objects[i].get_from != tag)
 
236
      flush_cache_item (app, data_objects[i].get_from);
 
237
}
 
238
 
 
239
/* Flush all entries from the cache which might be out of sync after
 
240
   an error. */
 
241
static void
 
242
flush_cache_after_error (app_t app)
 
243
{
 
244
  int i;
 
245
 
 
246
  for (i=0; data_objects[i].tag; i++)
 
247
    if (data_objects[i].flush_on_error)
 
248
      flush_cache_item (app, data_objects[i].tag);
 
249
}
 
250
 
 
251
 
 
252
/* Flush the entire cache. */
 
253
static void
 
254
flush_cache (app_t app)
 
255
{
 
256
  if (app && app->app_local)
 
257
    {
 
258
      struct cache_s *c, *c2;
 
259
 
 
260
      for (c = app->app_local->cache; c; c = c2)
 
261
        {
 
262
          c2 = c->next;
 
263
          xfree (c);
 
264
        }
 
265
      app->app_local->cache = NULL;
 
266
    }
 
267
}
 
268
 
 
269
 
 
270
/* Get the DO identified by TAG from the card in SLOT and return a
 
271
   buffer with its content in RESULT and NBYTES.  The return value is
 
272
   NULL if not found or a pointer which must be used to release the
 
273
   buffer holding value. */
 
274
static void *
 
275
get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes)
 
276
{
 
277
  int rc, i;
 
278
  unsigned char *buffer;
 
279
  size_t buflen;
 
280
  unsigned char *value;
 
281
  size_t valuelen;
 
282
 
 
283
  *result = NULL;
 
284
  *nbytes = 0;
 
285
  for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
 
286
    ;
 
287
 
 
288
  if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11)
 
289
    {
 
290
      if( iso7816_get_data (app->slot, tag, &buffer, &buflen))
 
291
        return NULL;
 
292
      *result = buffer;
 
293
      *nbytes = buflen;
 
294
      return buffer;
 
295
    }
 
296
 
 
297
  value = NULL;
 
298
  rc = -1;
 
299
  if (data_objects[i].tag && data_objects[i].get_from)
 
300
    {
 
301
      rc = get_cached_data (app, data_objects[i].get_from,
 
302
                            &buffer, &buflen);
 
303
      if (!rc)
 
304
        {
 
305
          const unsigned char *s;
 
306
 
 
307
          s = find_tlv (buffer, buflen, tag, &valuelen);
 
308
          if (!s)
 
309
            value = NULL; /* not found */
 
310
          else if (valuelen > buflen - (s - buffer))
 
311
            {
 
312
              log_error ("warning: constructed DO too short\n");
 
313
              value = NULL;
 
314
              xfree (buffer); buffer = NULL;
 
315
            }
 
316
          else
 
317
            value = buffer + (s - buffer);
 
318
        }
 
319
    }
 
320
 
 
321
  if (!value) /* Not in a constructed DO, try simple. */
 
322
    {
 
323
      rc = get_cached_data (app, tag, &buffer, &buflen);
 
324
      if (!rc)
 
325
        {
 
326
          value = buffer;
 
327
          valuelen = buflen;
 
328
        }
 
329
    }
 
330
 
 
331
  if (!rc)
 
332
    {
 
333
      *nbytes = valuelen;
 
334
      *result = value;
 
335
      return buffer;
 
336
    }
 
337
  return NULL;
 
338
}
 
339
 
 
340
 
 
341
static void
 
342
dump_all_do (int slot)
 
343
{
 
344
  int rc, i, j;
 
345
  unsigned char *buffer;
 
346
  size_t buflen;
 
347
  
 
348
  for (i=0; data_objects[i].tag; i++)
 
349
    {
 
350
      if (data_objects[i].get_from)
 
351
        continue;
 
352
 
 
353
      rc = iso7816_get_data (slot, data_objects[i].tag, &buffer, &buflen);
 
354
      if (gpg_err_code (rc) == GPG_ERR_NO_OBJ)
 
355
        ;
 
356
      else if (rc) 
 
357
        log_info ("DO `%s' not available: %s\n",
 
358
                  data_objects[i].desc, gpg_strerror (rc));
 
359
      else
 
360
        {
 
361
          if (data_objects[i].binary)
 
362
            {
 
363
              log_info ("DO `%s': ", data_objects[i].desc);
 
364
              log_printhex ("", buffer, buflen);
 
365
            }
 
366
          else
 
367
            log_info ("DO `%s': `%.*s'\n",
 
368
                      data_objects[i].desc,
 
369
                      (int)buflen, buffer); /* FIXME: sanitize */
 
370
 
 
371
          if (data_objects[i].constructed)
 
372
            {
 
373
              for (j=0; data_objects[j].tag; j++)
 
374
                {
 
375
                  const unsigned char *value;
 
376
                  size_t valuelen;
 
377
                  
 
378
                  if (j==i || data_objects[i].tag != data_objects[j].get_from)
 
379
                    continue;
 
380
                  value = find_tlv (buffer, buflen,
 
381
                                    data_objects[j].tag, &valuelen);
 
382
                  if (!value)
 
383
                    ; /* not found */
 
384
                  else if (valuelen > buflen - (value - buffer))
 
385
                    log_error ("warning: constructed DO too short\n");
 
386
                  else
 
387
                    {
 
388
                      if (data_objects[j].binary)
 
389
                        {
 
390
                          log_info ("DO `%s': ", data_objects[j].desc);
 
391
                          log_printhex ("", value, valuelen);
 
392
                        }
 
393
                      else
 
394
                        log_info ("DO `%s': `%.*s'\n",
 
395
                                  data_objects[j].desc,
 
396
                                  (int)valuelen, value); /* FIXME: sanitize */
 
397
                    }
 
398
                }
 
399
            }
 
400
        }
 
401
      xfree (buffer); buffer = NULL;
 
402
    }
 
403
}
 
404
 
 
405
 
 
406
/* Count the number of bits, assuming the A represents an unsigned big
 
407
   integer of length LEN bytes. */
 
408
static unsigned int
 
409
count_bits (const unsigned char *a, size_t len)
 
410
{
 
411
  unsigned int n = len * 8;
 
412
  int i;
 
413
 
 
414
  for (; len && !*a; len--, a++, n -=8)
 
415
    ;
 
416
  if (len)
 
417
    {
 
418
      for (i=7; i && !(*a & (1<<i)); i--)
 
419
        n--;
 
420
    }
 
421
  return n;
 
422
}
 
423
 
 
424
/* GnuPG makes special use of the login-data DO, this fucntion parses
 
425
   the login data to store the flags for later use.  It may be called
 
426
   at any time and should be called after changing the login-data DO.
 
427
 
 
428
   Everything up to a LF is considered a mailbox or account name.  If
 
429
   the first LF is follewed by DC4 (0x14) control sequence are
 
430
   expected up to the next LF.  Control sequences are separated by FS
 
431
   (0x28) and consist of key=value pairs.  There is one key defined:
 
432
 
 
433
    F=<flags>
 
434
 
 
435
    Were FLAGS is a plain hexadecimal number representing flag values.
 
436
    The lsb is here the rightmost bit.  Defined flags bits are:
 
437
 
 
438
      Bit 0 = CHV1 and CHV2 are not syncronized
 
439
      Bit 1 = CHV2 has been been set to the default PIN of "123456"
 
440
              (this implies that bit 0 is also set).
 
441
 
 
442
*/
 
443
static void
 
444
parse_login_data (app_t app)
 
445
{
 
446
  unsigned char *buffer, *p;
 
447
  size_t buflen, len;
 
448
  void *relptr;
 
449
 
 
450
  /* Set defaults.  */
 
451
  app->app_local->flags.no_sync = 0;
 
452
  app->app_local->flags.def_chv2 = 0;
 
453
 
 
454
  /* Read the DO.  */
 
455
  relptr = get_one_do (app, 0x005E, &buffer, &buflen);
 
456
  if (!relptr)
 
457
    return; /* Ooops. */
 
458
  for (; buflen; buflen--, buffer++)
 
459
    if (*buffer == '\n')
 
460
      break;
 
461
  if (buflen < 2 || buffer[1] != '\x14')
 
462
    return; /* No control sequences.  */
 
463
  buflen--;
 
464
  buffer++;
 
465
  do
 
466
    {
 
467
      buflen--;
 
468
      buffer++;
 
469
      if (buflen > 1 && *buffer == 'F' && buffer[1] == '=')
 
470
        {
 
471
          /* Flags control sequence found.  */
 
472
          int lastdig = 0;
 
473
 
 
474
          /* For now we are only interested in the last digit, so skip
 
475
             any leading digits but bail out on invalid characters. */
 
476
          for (p=buffer+2, len = buflen-2; len && hexdigitp (p); p++, len--)
 
477
            lastdig = xtoi_1 (p);
 
478
          if (len && !(*p == '\n' || *p == '\x18'))
 
479
            goto next;  /* Invalid characters in field.  */
 
480
          app->app_local->flags.no_sync = !!(lastdig & 1);
 
481
          app->app_local->flags.def_chv2 = (lastdig & 3) == 3;
 
482
        }
 
483
    next:
 
484
      for (; buflen && *buffer != '\x18'; buflen--, buffer++)
 
485
        if (*buffer == '\n')
 
486
          buflen = 1; 
 
487
    }
 
488
  while (buflen);
 
489
 
 
490
  xfree (relptr);
 
491
}
 
492
 
 
493
/* Note, that FPR must be at least 20 bytes. */
 
494
static int 
 
495
store_fpr (int slot, int keynumber, u32 timestamp,
 
496
           const unsigned char *m, size_t mlen,
 
497
           const unsigned char *e, size_t elen, 
 
498
           unsigned char *fpr, unsigned int card_version)
 
499
{
 
500
  unsigned int n, nbits;
 
501
  unsigned char *buffer, *p;
 
502
  int rc;
 
503
  
 
504
  for (; mlen && !*m; mlen--, m++) /* strip leading zeroes */
 
505
    ;
 
506
  for (; elen && !*e; elen--, e++) /* strip leading zeroes */
 
507
    ;
 
508
 
 
509
  n = 6 + 2 + mlen + 2 + elen;
 
510
  p = buffer = xtrymalloc (3 + n);
 
511
  if (!buffer)
 
512
    return gpg_error (gpg_err_code_from_errno (errno));
 
513
  
 
514
  *p++ = 0x99;     /* ctb */
 
515
  *p++ = n >> 8;   /* 2 byte length header */
 
516
  *p++ = n;
 
517
  *p++ = 4;        /* key packet version */
 
518
  *p++ = timestamp >> 24;
 
519
  *p++ = timestamp >> 16;
 
520
  *p++ = timestamp >>  8;
 
521
  *p++ = timestamp;
 
522
  *p++ = 1; /* RSA */
 
523
  nbits = count_bits (m, mlen);
 
524
  *p++ = nbits >> 8;
 
525
  *p++ = nbits;
 
526
  memcpy (p, m, mlen); p += mlen;
 
527
  nbits = count_bits (e, elen);
 
528
  *p++ = nbits >> 8;
 
529
  *p++ = nbits;
 
530
  memcpy (p, e, elen); p += elen;
 
531
    
 
532
  gcry_md_hash_buffer (GCRY_MD_SHA1, fpr, buffer, n+3);
 
533
 
 
534
  xfree (buffer);
 
535
 
 
536
  rc = iso7816_put_data (slot, (card_version > 0x0007? 0xC7 : 0xC6)
 
537
                               + keynumber, fpr, 20);
 
538
  if (rc)
 
539
    log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc));
 
540
 
 
541
  if (!rc && card_version > 0x0100)
 
542
    {
 
543
      unsigned char buf[4];
 
544
 
 
545
      buf[0] = timestamp >> 24;
 
546
      buf[1] = timestamp >> 16;
 
547
      buf[2] = timestamp >>  8;
 
548
      buf[3] = timestamp;
 
549
 
 
550
      rc = iso7816_put_data (slot, 0xCE + keynumber, buf, 4);
 
551
      if (rc)
 
552
        log_error (_("failed to store the creation date: %s\n"),
 
553
                   gpg_strerror (rc));
 
554
    }
 
555
 
 
556
  return rc;
 
557
}
 
558
 
 
559
       
 
560
static void
 
561
send_fpr_if_not_null (ctrl_t ctrl, const char *keyword,
 
562
                      int number, const unsigned char *fpr)
 
563
{                      
 
564
  int i;
 
565
  char buf[41];
 
566
  char numbuf[25];
 
567
 
 
568
  for (i=0; i < 20 && !fpr[i]; i++)
 
569
    ;
 
570
  if (i==20)
 
571
    return; /* All zero. */
 
572
  for (i=0; i< 20; i++)
 
573
    sprintf (buf+2*i, "%02X", fpr[i]);
 
574
  if (number == -1)
 
575
    *numbuf = 0; /* Don't print the key number */
 
576
  else
 
577
    sprintf (numbuf, "%d", number);
 
578
  send_status_info (ctrl, keyword,
 
579
                    numbuf, (size_t)strlen(numbuf),
 
580
                    buf, (size_t)strlen (buf), NULL, 0);
 
581
}
 
582
 
 
583
static void
 
584
send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,
 
585
                          int number, const unsigned char *stamp)
 
586
{                      
 
587
  char numbuf1[50], numbuf2[50];
 
588
  unsigned long value;
 
589
 
 
590
  value = (stamp[0] << 24) | (stamp[1]<<16) | (stamp[2]<<8) | stamp[3];
 
591
  if (!value)
 
592
    return;
 
593
  sprintf (numbuf1, "%d", number);
 
594
  sprintf (numbuf2, "%lu", value);
 
595
  send_status_info (ctrl, keyword,
 
596
                    numbuf1, (size_t)strlen(numbuf1),
 
597
                    numbuf2, (size_t)strlen(numbuf2), NULL, 0);
 
598
}
 
599
 
 
600
static void
 
601
send_key_data (ctrl_t ctrl, const char *name, 
 
602
               const unsigned char *a, size_t alen)
 
603
{
 
604
  char *p, *buf = xmalloc (alen*2+1);
 
605
  
 
606
  for (p=buf; alen; a++, alen--, p += 2)
 
607
    sprintf (p, "%02X", *a);
 
608
 
 
609
  send_status_info (ctrl, "KEY-DATA",
 
610
                    name, (size_t)strlen(name), 
 
611
                    buf, (size_t)strlen (buf),
 
612
                    NULL, 0);
 
613
  xfree (buf);
 
614
}
 
615
 
 
616
/* Implement the GETATTR command.  This is similar to the LEARN
 
617
   command but returns just one value via the status interface. */
 
618
static int 
 
619
do_getattr (app_t app, ctrl_t ctrl, const char *name)
 
620
{
 
621
  static struct {
 
622
    const char *name;
 
623
    int tag;
 
624
    int special;
 
625
  } table[] = {
 
626
    { "DISP-NAME",    0x005B },
 
627
    { "LOGIN-DATA",   0x005E },
 
628
    { "DISP-LANG",    0x5F2D },
 
629
    { "DISP-SEX",     0x5F35 },
 
630
    { "PUBKEY-URL",   0x5F50 },
 
631
    { "KEY-FPR",      0x00C5, 3 },
 
632
    { "KEY-TIME",     0x00CD, 4 },
 
633
    { "CA-FPR",       0x00C6, 3 },
 
634
    { "CHV-STATUS",   0x00C4, 1 }, 
 
635
    { "SIG-COUNTER",  0x0093, 2 },
 
636
    { "SERIALNO",     0x004F, -1 },
 
637
    { "AID",          0x004F },
 
638
    { "EXTCAP",       0x0000, -2 },
 
639
    { "PRIVATE-DO-1", 0x0101 },
 
640
    { "PRIVATE-DO-2", 0x0102 },
 
641
    { "PRIVATE-DO-3", 0x0103 },
 
642
    { "PRIVATE-DO-4", 0x0104 },
 
643
    { NULL, 0 }
 
644
  };
 
645
  int idx, i;
 
646
  void *relptr;
 
647
  unsigned char *value;
 
648
  size_t valuelen;
 
649
 
 
650
  for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
 
651
    ;
 
652
  if (!table[idx].name)
 
653
    return gpg_error (GPG_ERR_INV_NAME); 
 
654
  
 
655
  if (table[idx].special == -1)
 
656
    {
 
657
      /* The serial number is very special.  We could have used the
 
658
         AID DO to retrieve it, but we have it already in the app
 
659
         context and the stamp argument is required anyway which we
 
660
         can't by other means. The AID DO is available anyway but not
 
661
         hex formatted. */
 
662
      char *serial;
 
663
      time_t stamp;
 
664
      char tmp[50];
 
665
 
 
666
      if (!app_get_serial_and_stamp (app, &serial, &stamp))
 
667
        {
 
668
          sprintf (tmp, "%lu", (unsigned long)stamp);
 
669
          send_status_info (ctrl, "SERIALNO",
 
670
                            serial, strlen (serial),
 
671
                            tmp, strlen (tmp),
 
672
                            NULL, 0);
 
673
          xfree (serial);
 
674
        }
 
675
      return 0;
 
676
    }
 
677
  if (table[idx].special == -2)
 
678
    {
 
679
      char tmp[50];
 
680
 
 
681
      sprintf (tmp, "gc=%d ki=%d fc=%d pd=%d", 
 
682
               app->app_local->extcap.get_challenge,
 
683
               app->app_local->extcap.key_import,
 
684
               app->app_local->extcap.change_force_chv,
 
685
               app->app_local->extcap.private_dos);
 
686
      send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
 
687
      return 0;
 
688
    }
 
689
 
 
690
  relptr = get_one_do (app, table[idx].tag, &value, &valuelen);
 
691
  if (relptr)
 
692
    {
 
693
      if (table[idx].special == 1)
 
694
        {
 
695
          char numbuf[7*23];
 
696
          
 
697
          for (i=0,*numbuf=0; i < valuelen && i < 7; i++)
 
698
            sprintf (numbuf+strlen (numbuf), " %d", value[i]); 
 
699
          send_status_info (ctrl, table[idx].name,
 
700
                            numbuf, strlen (numbuf), NULL, 0);
 
701
        }
 
702
      else if (table[idx].special == 2)
 
703
        {
 
704
          char numbuf[50];
 
705
 
 
706
          sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen));
 
707
          send_status_info (ctrl, table[idx].name,
 
708
                            numbuf, strlen (numbuf), NULL, 0);
 
709
        }
 
710
      else if (table[idx].special == 3)
 
711
        {
 
712
          if (valuelen >= 60)
 
713
            for (i=0; i < 3; i++)
 
714
              send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
 
715
        }
 
716
      else if (table[idx].special == 4)
 
717
        {
 
718
          if (valuelen >= 12)
 
719
            for (i=0; i < 3; i++)
 
720
              send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
 
721
        }
 
722
      else
 
723
        send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
 
724
 
 
725
      xfree (relptr);
 
726
    }
 
727
  return 0;
 
728
}
 
729
 
 
730
 
 
731
static int
 
732
do_learn_status (app_t app, ctrl_t ctrl)
 
733
{
 
734
  do_getattr (app, ctrl, "EXTCAP");
 
735
  do_getattr (app, ctrl, "DISP-NAME");
 
736
  do_getattr (app, ctrl, "DISP-LANG");
 
737
  do_getattr (app, ctrl, "DISP-SEX");
 
738
  do_getattr (app, ctrl, "PUBKEY-URL");
 
739
  do_getattr (app, ctrl, "LOGIN-DATA");
 
740
  do_getattr (app, ctrl, "KEY-FPR");
 
741
  if (app->card_version > 0x0100)
 
742
    do_getattr (app, ctrl, "KEY-TIME");
 
743
  do_getattr (app, ctrl, "CA-FPR");
 
744
  do_getattr (app, ctrl, "CHV-STATUS");
 
745
  do_getattr (app, ctrl, "SIG-COUNTER");
 
746
  if (app->app_local->extcap.private_dos)
 
747
    {
 
748
      do_getattr (app, ctrl, "PRIVATE-DO-1");
 
749
      do_getattr (app, ctrl, "PRIVATE-DO-2");
 
750
      if (app->did_chv2)
 
751
        do_getattr (app, ctrl, "PRIVATE-DO-3");
 
752
      if (app->did_chv3)
 
753
        do_getattr (app, ctrl, "PRIVATE-DO-4");
 
754
    }
 
755
 
 
756
  return 0;
 
757
}
 
758
 
 
759
 
 
760
/* Verify CHV2 if required.  Depending on the configuration of the
 
761
   card CHV1 will also be verified. */
 
762
static int
 
763
verify_chv2 (app_t app,
 
764
             int (*pincb)(void*, const char *, char **),
 
765
             void *pincb_arg)
 
766
{
 
767
  int rc = 0;
 
768
 
 
769
  if (!app->did_chv2) 
 
770
    {
 
771
      char *pinvalue;
 
772
 
 
773
      rc = pincb (pincb_arg, "PIN", &pinvalue); 
 
774
      if (rc)
 
775
        {
 
776
          log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
 
777
          return rc;
 
778
        }
 
779
 
 
780
      if (strlen (pinvalue) < 6)
 
781
        {
 
782
          log_error (_("PIN for CHV%d is too short;"
 
783
                       " minimum length is %d\n"), 2, 6);
 
784
          xfree (pinvalue);
 
785
          return gpg_error (GPG_ERR_BAD_PIN);
 
786
        }
 
787
 
 
788
      rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
 
789
      if (rc)
 
790
        {
 
791
          log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
 
792
          xfree (pinvalue);
 
793
          flush_cache_after_error (app);
 
794
          return rc;
 
795
        }
 
796
      app->did_chv2 = 1;
 
797
 
 
798
      if (!app->did_chv1 && !app->force_chv1)
 
799
        {
 
800
          rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
 
801
          if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
 
802
            rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
 
803
          if (rc)
 
804
            {
 
805
              log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
 
806
              xfree (pinvalue);
 
807
              flush_cache_after_error (app);
 
808
              return rc;
 
809
            }
 
810
          app->did_chv1 = 1;
 
811
        }
 
812
      xfree (pinvalue);
 
813
    }
 
814
  return rc;
 
815
}
 
816
 
 
817
/* Verify CHV3 if required. */
 
818
static int
 
819
verify_chv3 (app_t app,
 
820
             int (*pincb)(void*, const char *, char **),
 
821
             void *pincb_arg)
 
822
{
 
823
  int rc = 0;
 
824
 
 
825
#if GNUPG_MAJOR_VERSION != 1
 
826
  if (!opt.allow_admin)
 
827
    {
 
828
      log_info (_("access to admin commands is not configured\n"));
 
829
      return gpg_error (GPG_ERR_EACCES);
 
830
    }
 
831
#endif
 
832
      
 
833
  if (!app->did_chv3) 
 
834
    {
 
835
      char *pinvalue;
 
836
      void *relptr;
 
837
      unsigned char *value;
 
838
      size_t valuelen;
 
839
      int reread_chv_status;
 
840
      
 
841
 
 
842
      relptr = get_one_do (app, 0x00C4, &value, &valuelen);
 
843
      if (!relptr || valuelen < 7)
 
844
        {
 
845
          log_error (_("error retrieving CHV status from card\n"));
 
846
          xfree (relptr);
 
847
          return gpg_error (GPG_ERR_CARD);
 
848
        }
 
849
      if (value[6] == 0)
 
850
        {
 
851
          log_info (_("card is permanently locked!\n"));
 
852
          xfree (relptr);
 
853
          return gpg_error (GPG_ERR_BAD_PIN);
 
854
        }
 
855
 
 
856
      reread_chv_status = (value[6] < 3);
 
857
 
 
858
      log_info(_("%d Admin PIN attempts remaining before card"
 
859
                 " is permanently locked\n"), value[6]);
 
860
      xfree (relptr);
 
861
 
 
862
      /* Note to translators: Do not translate the "|A|" prefix but
 
863
         keep it at the start of the string.  We need this elsewhere
 
864
         to get some infos on the string. */
 
865
      rc = pincb (pincb_arg, _("|A|Admin PIN"), &pinvalue); 
 
866
      if (rc)
 
867
        {
 
868
          log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
 
869
          return rc;
 
870
        }
 
871
 
 
872
      if (strlen (pinvalue) < 8)
 
873
        {
 
874
          log_error (_("PIN for CHV%d is too short;"
 
875
                       " minimum length is %d\n"), 3, 8);
 
876
          xfree (pinvalue);
 
877
          return gpg_error (GPG_ERR_BAD_PIN);
 
878
        }
 
879
 
 
880
      rc = iso7816_verify (app->slot, 0x83, pinvalue, strlen (pinvalue));
 
881
      xfree (pinvalue);
 
882
      if (rc)
 
883
        {
 
884
          log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
 
885
          flush_cache_after_error (app);
 
886
          return rc;
 
887
        }
 
888
      app->did_chv3 = 1;
 
889
      /* If the PIN has been entered wrongly before, we need to flush
 
890
         the cached value so that the next read correctly reflects the
 
891
         resetted retry counter.  Note that version 1.1 of the specs
 
892
         allow direct reading of that DO, so that we could actually
 
893
         flush it in all cases. */
 
894
      if (reread_chv_status)
 
895
        flush_cache_item (app, 0x00C4);
 
896
    }
 
897
  return rc;
 
898
}
 
899
 
 
900
 
 
901
/* Handle the SETATTR operation. All arguments are already basically
 
902
   checked. */
 
903
static int 
 
904
do_setattr (app_t app, const char *name,
 
905
            int (*pincb)(void*, const char *, char **),
 
906
            void *pincb_arg,
 
907
            const unsigned char *value, size_t valuelen)
 
908
{
 
909
  gpg_error_t rc;
 
910
  int idx;
 
911
  static struct {
 
912
    const char *name;
 
913
    int tag;
 
914
    int need_chv;
 
915
    int special;
 
916
  } table[] = {
 
917
    { "DISP-NAME",    0x005B, 3 },
 
918
    { "LOGIN-DATA",   0x005E, 3, 2 },
 
919
    { "DISP-LANG",    0x5F2D, 3 },
 
920
    { "DISP-SEX",     0x5F35, 3 },
 
921
    { "PUBKEY-URL",   0x5F50, 3 },
 
922
    { "CHV-STATUS-1", 0x00C4, 3, 1 },
 
923
    { "CA-FPR-1",     0x00CA, 3 },
 
924
    { "CA-FPR-2",     0x00CB, 3 },
 
925
    { "CA-FPR-3",     0x00CC, 3 },
 
926
    { "PRIVATE-DO-1", 0x0101, 2 },
 
927
    { "PRIVATE-DO-2", 0x0102, 3 },
 
928
    { "PRIVATE-DO-3", 0x0103, 2 },
 
929
    { "PRIVATE-DO-4", 0x0104, 3 },
 
930
    { NULL, 0 }
 
931
  };
 
932
 
 
933
 
 
934
  for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
 
935
    ;
 
936
  if (!table[idx].name)
 
937
    return gpg_error (GPG_ERR_INV_NAME); 
 
938
 
 
939
  switch (table[idx].need_chv)
 
940
    {
 
941
    case 2:
 
942
      rc = verify_chv2 (app, pincb, pincb_arg);
 
943
      break;
 
944
    case 3:
 
945
      rc = verify_chv3 (app, pincb, pincb_arg);
 
946
      break;
 
947
    default:
 
948
      rc = 0;
 
949
    }
 
950
  if (rc)
 
951
    return rc;
 
952
 
 
953
  /* Flush the cache before writing it, so that the next get operation
 
954
     will reread the data from the card and thus get synced in case of
 
955
     errors (e.g. data truncated by the card). */
 
956
  flush_cache_item (app, table[idx].tag);
 
957
  rc = iso7816_put_data (app->slot, table[idx].tag, value, valuelen);
 
958
  if (rc)
 
959
    log_error ("failed to set `%s': %s\n", table[idx].name, gpg_strerror (rc));
 
960
 
 
961
  if (table[idx].special == 1)
 
962
    app->force_chv1 = (valuelen && *value == 0);
 
963
  else if (table[idx].special == 2)
 
964
    parse_login_data (app);
 
965
 
 
966
  return rc;
 
967
}
 
968
 
 
969
 
 
970
/* Handle the PASSWD command. */
 
971
static int 
 
972
do_change_pin (app_t app, ctrl_t ctrl,  const char *chvnostr, int reset_mode,
 
973
               int (*pincb)(void*, const char *, char **),
 
974
               void *pincb_arg)
 
975
{
 
976
  int rc = 0;
 
977
  int chvno = atoi (chvnostr);
 
978
  char *pinvalue;
 
979
 
 
980
  if (reset_mode && chvno == 3)
 
981
    {
 
982
      rc = gpg_error (GPG_ERR_INV_ID);
 
983
      goto leave;
 
984
    }
 
985
  else if (reset_mode || chvno == 3)
 
986
    {
 
987
      /* we always require that the PIN is entered. */
 
988
      app->did_chv3 = 0;
 
989
      rc = verify_chv3 (app, pincb, pincb_arg);
 
990
      if (rc)
 
991
        goto leave;
 
992
    }
 
993
  else if (chvno == 1 || chvno == 2)
 
994
    {
 
995
      /* CHV1 and CVH2 should always have the same value, thus we
 
996
         enforce it here.  */
 
997
      int save_force = app->force_chv1;
 
998
 
 
999
      app->force_chv1 = 0;
 
1000
      app->did_chv1 = 0;
 
1001
      app->did_chv2 = 0;
 
1002
      rc = verify_chv2 (app, pincb, pincb_arg);
 
1003
      app->force_chv1 = save_force;
 
1004
      if (rc)
 
1005
        goto leave;
 
1006
    }
 
1007
  else
 
1008
    {
 
1009
      rc = gpg_error (GPG_ERR_INV_ID);
 
1010
      goto leave;
 
1011
    }
 
1012
 
 
1013
  if (chvno == 3)
 
1014
    app->did_chv3 = 0;
 
1015
  else
 
1016
    app->did_chv1 = app->did_chv2 = 0;
 
1017
 
 
1018
  /* Note to translators: Do not translate the "|*|" prefixes but
 
1019
     keep it at the start of the string.  We need this elsewhere
 
1020
     to get some infos on the string. */
 
1021
  rc = pincb (pincb_arg, chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"), 
 
1022
              &pinvalue); 
 
1023
  if (rc)
 
1024
    {
 
1025
      log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
 
1026
      goto leave;
 
1027
    }
 
1028
 
 
1029
  if (reset_mode)
 
1030
    {
 
1031
      rc = iso7816_reset_retry_counter (app->slot, 0x81,
 
1032
                                        pinvalue, strlen (pinvalue));
 
1033
      if (!rc)
 
1034
        rc = iso7816_reset_retry_counter (app->slot, 0x82,
 
1035
                                          pinvalue, strlen (pinvalue));
 
1036
    }
 
1037
  else
 
1038
    {
 
1039
      if (chvno == 1 || chvno == 2)
 
1040
        {
 
1041
          rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
 
1042
                                              pinvalue, strlen (pinvalue));
 
1043
          if (!rc)
 
1044
            rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
 
1045
                                                pinvalue, strlen (pinvalue));
 
1046
        }
 
1047
      else
 
1048
        rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
 
1049
                                            pinvalue, strlen (pinvalue));
 
1050
    }
 
1051
  xfree (pinvalue);
 
1052
  if (rc)
 
1053
    flush_cache_after_error (app);
 
1054
 
 
1055
 leave:
 
1056
  return rc;
 
1057
}
 
1058
 
 
1059
 
 
1060
 
 
1061
/* Handle the GENKEY command. */
 
1062
static int 
 
1063
do_genkey (app_t app, ctrl_t ctrl,  const char *keynostr, unsigned int flags,
 
1064
          int (*pincb)(void*, const char *, char **),
 
1065
          void *pincb_arg)
 
1066
{
 
1067
  int rc;
 
1068
  int i;
 
1069
  char numbuf[30];
 
1070
  unsigned char fprbuf[20];
 
1071
  const unsigned char *fpr;
 
1072
  const unsigned char *keydata, *m, *e;
 
1073
  unsigned char *buffer;
 
1074
  size_t buflen, keydatalen, n, mlen, elen;
 
1075
  time_t created_at;
 
1076
  int keyno = atoi (keynostr);
 
1077
  int force = (flags & 1);
 
1078
  time_t start_at;
 
1079
 
 
1080
  if (keyno < 1 || keyno > 3)
 
1081
    return gpg_error (GPG_ERR_INV_ID);
 
1082
  keyno--;
 
1083
 
 
1084
  /* We flush the cache to increase the traffic before a key
 
1085
     generation.  This _might_ help a card to gather more entropy. */
 
1086
  flush_cache (app);
 
1087
 
 
1088
  rc = iso7816_get_data (app->slot, 0x006E, &buffer, &buflen);
 
1089
  if (rc)
 
1090
    {
 
1091
      log_error (_("error reading application data\n"));
 
1092
      return gpg_error (GPG_ERR_GENERAL);
 
1093
    }
 
1094
  fpr = find_tlv (buffer, buflen, 0x00C5, &n);
 
1095
  if (!fpr || n != 60)
 
1096
    {
 
1097
      rc = gpg_error (GPG_ERR_GENERAL);
 
1098
      log_error (_("error reading fingerprint DO\n"));
 
1099
      goto leave;
 
1100
    }
 
1101
  fpr += 20*keyno;
 
1102
  for (i=0; i < 20 && !fpr[i]; i++)
 
1103
    ;
 
1104
  if (i!=20 && !force)
 
1105
    {
 
1106
      rc = gpg_error (GPG_ERR_EEXIST);
 
1107
      log_error (_("key already exists\n"));
 
1108
      goto leave;
 
1109
    }
 
1110
  else if (i!=20)
 
1111
    log_info (_("existing key will be replaced\n"));
 
1112
  else
 
1113
    log_info (_("generating new key\n"));
 
1114
 
 
1115
 
 
1116
  rc = verify_chv3 (app, pincb, pincb_arg);
 
1117
  if (rc)
 
1118
    goto leave;
 
1119
 
 
1120
  xfree (buffer); buffer = NULL;
 
1121
 
 
1122
#if 1
 
1123
  log_info (_("please wait while key is being generated ...\n"));
 
1124
  start_at = time (NULL);
 
1125
  rc = iso7816_generate_keypair 
 
1126
#else
 
1127
#warning key generation temporary replaced by reading an existing key.
 
1128
  rc = iso7816_read_public_key
 
1129
#endif
 
1130
                              (app->slot, 
 
1131
                                 keyno == 0? "\xB6" :
 
1132
                                 keyno == 1? "\xB8" : "\xA4",
 
1133
                                 2,
 
1134
                                 &buffer, &buflen);
 
1135
  if (rc)
 
1136
    {
 
1137
      rc = gpg_error (GPG_ERR_CARD);
 
1138
      log_error (_("generating key failed\n"));
 
1139
      goto leave;
 
1140
    }
 
1141
  log_info (_("key generation completed (%d seconds)\n"),
 
1142
            (int)(time (NULL) - start_at));
 
1143
  keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
 
1144
  if (!keydata)
 
1145
    {
 
1146
      rc = gpg_error (GPG_ERR_CARD);
 
1147
      log_error (_("response does not contain the public key data\n"));
 
1148
      goto leave;
 
1149
    }
 
1150
 
 
1151
  m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
 
1152
  if (!m)
 
1153
    {
 
1154
      rc = gpg_error (GPG_ERR_CARD);
 
1155
      log_error (_("response does not contain the RSA modulus\n"));
 
1156
      goto leave;
 
1157
    }
 
1158
/*    log_printhex ("RSA n:", m, mlen); */
 
1159
  send_key_data (ctrl, "n", m, mlen);
 
1160
 
 
1161
  e = find_tlv (keydata, keydatalen, 0x0082, &elen);
 
1162
  if (!e)
 
1163
    {
 
1164
      rc = gpg_error (GPG_ERR_CARD);
 
1165
      log_error (_("response does not contain the RSA public exponent\n"));
 
1166
      goto leave;
 
1167
    }
 
1168
/*    log_printhex ("RSA e:", e, elen); */
 
1169
  send_key_data (ctrl, "e", e, elen);
 
1170
 
 
1171
  created_at = gnupg_get_time ();
 
1172
  sprintf (numbuf, "%lu", (unsigned long)created_at);
 
1173
  send_status_info (ctrl, "KEY-CREATED-AT",
 
1174
                    numbuf, (size_t)strlen(numbuf), NULL, 0);
 
1175
 
 
1176
  rc = store_fpr (app->slot, keyno, (u32)created_at,
 
1177
                  m, mlen, e, elen, fprbuf, app->card_version);
 
1178
  if (rc)
 
1179
    goto leave;
 
1180
  send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
 
1181
 
 
1182
 
 
1183
 leave:
 
1184
  xfree (buffer);
 
1185
  return rc;
 
1186
}
 
1187
 
 
1188
 
 
1189
static unsigned long
 
1190
convert_sig_counter_value (const unsigned char *value, size_t valuelen)
 
1191
{
 
1192
  unsigned long ul;
 
1193
 
 
1194
  if (valuelen == 3 )
 
1195
    ul = (value[0] << 16) | (value[1] << 8) | value[2];
 
1196
  else
 
1197
    {
 
1198
      log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
 
1199
      ul = 0;
 
1200
    }
 
1201
  return ul;
 
1202
}
 
1203
 
 
1204
static unsigned long
 
1205
get_sig_counter (app_t app)
 
1206
{
 
1207
  void *relptr;
 
1208
  unsigned char *value;
 
1209
  size_t valuelen;
 
1210
  unsigned long ul;
 
1211
 
 
1212
  relptr = get_one_do (app, 0x0093, &value, &valuelen);
 
1213
  if (!relptr)
 
1214
    return 0;
 
1215
  ul = convert_sig_counter_value (value, valuelen);
 
1216
  xfree (relptr);
 
1217
  return ul;
 
1218
}
 
1219
 
 
1220
static int
 
1221
compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
 
1222
{
 
1223
  const unsigned char *fpr;
 
1224
  unsigned char *buffer;
 
1225
  size_t buflen, n;
 
1226
  int rc, i;
 
1227
  
 
1228
  assert (keyno >= 1 && keyno <= 3);
 
1229
 
 
1230
  rc = get_cached_data (app, 0x006E, &buffer, &buflen);
 
1231
  if (rc)
 
1232
    {
 
1233
      log_error (_("error reading application data\n"));
 
1234
      return gpg_error (GPG_ERR_GENERAL);
 
1235
    }
 
1236
  fpr = find_tlv (buffer, buflen, 0x00C5, &n);
 
1237
  if (!fpr || n != 60)
 
1238
    {
 
1239
      xfree (buffer);
 
1240
      log_error (_("error reading fingerprint DO\n"));
 
1241
      return gpg_error (GPG_ERR_GENERAL);
 
1242
    }
 
1243
  fpr += (keyno-1)*20;
 
1244
  for (i=0; i < 20; i++)
 
1245
    if (sha1fpr[i] != fpr[i])
 
1246
      {
 
1247
        xfree (buffer);
 
1248
        return gpg_error (GPG_ERR_WRONG_SECKEY);
 
1249
      }
 
1250
  xfree (buffer);
 
1251
  return 0;
 
1252
}
 
1253
 
 
1254
 
 
1255
  /* If a fingerprint has been specified check it against the one on
 
1256
     the card.  This is allows for a meaningful error message in case
 
1257
     the key on the card has been replaced but the shadow information
 
1258
     known to gpg was not updated.  If there is no fingerprint we
 
1259
     assume that this is okay. */
 
1260
static int
 
1261
check_against_given_fingerprint (app_t app, const char *fpr, int keyno)
 
1262
{
 
1263
  unsigned char tmp[20];
 
1264
  const char *s;
 
1265
  int n;
 
1266
 
 
1267
  for (s=fpr, n=0; hexdigitp (s); s++, n++)
 
1268
    ;
 
1269
  if (n != 40)
 
1270
    return gpg_error (GPG_ERR_INV_ID);
 
1271
  else if (!*s)
 
1272
    ; /* okay */
 
1273
  else
 
1274
    return gpg_error (GPG_ERR_INV_ID);
 
1275
 
 
1276
  for (s=fpr, n=0; n < 20; s += 2, n++)
 
1277
        tmp[n] = xtoi_2 (s);
 
1278
  return compare_fingerprint (app, keyno, tmp);
 
1279
}
 
1280
 
 
1281
 
 
1282
 
 
1283
/* Compute a digital signature on INDATA which is expected to be the
 
1284
   raw message digest. For this application the KEYIDSTR consists of
 
1285
   the serialnumber and the fingerprint delimited by a slash.
 
1286
 
 
1287
   Note that this fucntion may return the error code
 
1288
   GPG_ERR_WRONG_CARD to indicate that the card currently present does
 
1289
   not match the one required for the requested action (e.g. the
 
1290
   serial number does not match). */
 
1291
static int 
 
1292
do_sign (app_t app, const char *keyidstr, int hashalgo,
 
1293
         int (*pincb)(void*, const char *, char **),
 
1294
         void *pincb_arg,
 
1295
         const void *indata, size_t indatalen,
 
1296
         unsigned char **outdata, size_t *outdatalen )
 
1297
{
 
1298
  static unsigned char sha1_prefix[15] = /* Object ID is 1.3.14.3.2.26 */
 
1299
  { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
 
1300
    0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 };
 
1301
  static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
 
1302
  { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
 
1303
    0x02, 0x01, 0x05, 0x00, 0x04, 0x14 };
 
1304
  int rc;
 
1305
  unsigned char data[35];
 
1306
  unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
 
1307
  const char *s;
 
1308
  int n;
 
1309
  const char *fpr = NULL;
 
1310
  unsigned long sigcount;
 
1311
 
 
1312
  if (!keyidstr || !*keyidstr)
 
1313
    return gpg_error (GPG_ERR_INV_VALUE);
 
1314
  if (indatalen != 20)
 
1315
    return gpg_error (GPG_ERR_INV_VALUE);
 
1316
 
 
1317
  /* Check whether an OpenPGP card of any version has been requested. */
 
1318
  if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
 
1319
    return gpg_error (GPG_ERR_INV_ID);
 
1320
  
 
1321
  for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
 
1322
    ;
 
1323
  if (n != 32)
 
1324
    return gpg_error (GPG_ERR_INV_ID);
 
1325
  else if (!*s)
 
1326
    ; /* no fingerprint given: we allow this for now. */
 
1327
  else if (*s == '/')
 
1328
    fpr = s + 1; 
 
1329
  else
 
1330
    return gpg_error (GPG_ERR_INV_ID);
 
1331
 
 
1332
  for (s=keyidstr, n=0; n < 16; s += 2, n++)
 
1333
    tmp_sn[n] = xtoi_2 (s);
 
1334
 
 
1335
  if (app->serialnolen != 16)
 
1336
    return gpg_error (GPG_ERR_INV_CARD);
 
1337
  if (memcmp (app->serialno, tmp_sn, 16))
 
1338
    return gpg_error (GPG_ERR_WRONG_CARD);
 
1339
 
 
1340
  /* If a fingerprint has been specified check it against the one on
 
1341
     the card.  This is allows for a meaningful error message in case
 
1342
     the key on the card has been replaced but the shadow information
 
1343
     known to gpg was not updated.  If there is no fingerprint, gpg
 
1344
     will detect a bogus signature anyway due to the
 
1345
     verify-after-signing feature. */
 
1346
  rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
 
1347
  if (rc)
 
1348
    return rc;
 
1349
 
 
1350
  if (hashalgo == GCRY_MD_SHA1)
 
1351
    memcpy (data, sha1_prefix, 15);
 
1352
  else if (hashalgo == GCRY_MD_RMD160)
 
1353
    memcpy (data, rmd160_prefix, 15);
 
1354
  else 
 
1355
    return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
 
1356
  memcpy (data+15, indata, indatalen);
 
1357
 
 
1358
  sigcount = get_sig_counter (app);
 
1359
  log_info (_("signatures created so far: %lu\n"), sigcount);
 
1360
 
 
1361
  if (!app->did_chv1 || app->force_chv1 ) 
 
1362
    {
 
1363
      char *pinvalue;
 
1364
 
 
1365
      {
 
1366
        char *prompt;
 
1367
#define PROMPTSTRING  _("PIN [sigs done: %lu]")
 
1368
 
 
1369
        prompt = malloc (strlen (PROMPTSTRING) + 50);
 
1370
        if (!prompt)
 
1371
          return gpg_error_from_errno (errno);
 
1372
        sprintf (prompt, PROMPTSTRING, sigcount);
 
1373
        rc = pincb (pincb_arg, prompt, &pinvalue); 
 
1374
        free (prompt);
 
1375
#undef PROMPTSTRING
 
1376
      }
 
1377
      if (rc)
 
1378
        {
 
1379
          log_info (_("PIN callback returned error: %s\n"), gpg_strerror (rc));
 
1380
          return rc;
 
1381
        }
 
1382
 
 
1383
      if (strlen (pinvalue) < 6)
 
1384
        {
 
1385
          log_error (_("PIN for CHV%d is too short;"
 
1386
                       " minimum length is %d\n"), 1, 6);
 
1387
          xfree (pinvalue);
 
1388
          return gpg_error (GPG_ERR_BAD_PIN);
 
1389
        }
 
1390
 
 
1391
      rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
 
1392
      if (rc)
 
1393
        {
 
1394
          log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
 
1395
          xfree (pinvalue);
 
1396
          flush_cache_after_error (app);
 
1397
          return rc;
 
1398
        }
 
1399
      app->did_chv1 = 1;
 
1400
      if (!app->did_chv2)
 
1401
        {
 
1402
          /* We should also verify CHV2. */
 
1403
          rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
 
1404
          if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
 
1405
            rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
 
1406
          if (rc)
 
1407
            {
 
1408
              log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
 
1409
              xfree (pinvalue);
 
1410
              flush_cache_after_error (app);
 
1411
              return rc;
 
1412
            }
 
1413
          app->did_chv2 = 1;
 
1414
        }
 
1415
      xfree (pinvalue);
 
1416
    }
 
1417
 
 
1418
  rc = iso7816_compute_ds (app->slot, data, 35, outdata, outdatalen);
 
1419
  return rc;
 
1420
}
 
1421
 
 
1422
/* Compute a digital signature using the INTERNAL AUTHENTICATE command
 
1423
   on INDATA which is expected to be the raw message digest. For this
 
1424
   application the KEYIDSTR consists of the serialnumber and the
 
1425
   fingerprint delimited by a slash.
 
1426
 
 
1427
   Note that this fucntion may return the error code
 
1428
   GPG_ERR_WRONG_CARD to indicate that the card currently present does
 
1429
   not match the one required for the requested action (e.g. the
 
1430
   serial number does not match). */
 
1431
static int 
 
1432
do_auth (app_t app, const char *keyidstr,
 
1433
         int (*pincb)(void*, const char *, char **),
 
1434
         void *pincb_arg,
 
1435
         const void *indata, size_t indatalen,
 
1436
         unsigned char **outdata, size_t *outdatalen )
 
1437
{
 
1438
  int rc;
 
1439
  unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
 
1440
  const char *s;
 
1441
  int n;
 
1442
  const char *fpr = NULL;
 
1443
 
 
1444
  if (!keyidstr || !*keyidstr)
 
1445
    return gpg_error (GPG_ERR_INV_VALUE);
 
1446
  if (indatalen > 50) /* For a 1024 bit key. */
 
1447
    return gpg_error (GPG_ERR_INV_VALUE);
 
1448
 
 
1449
  /* Check whether an OpenPGP card of any version has been requested. */
 
1450
  if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
 
1451
    return gpg_error (GPG_ERR_INV_ID);
 
1452
  
 
1453
  for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
 
1454
    ;
 
1455
  if (n != 32)
 
1456
    return gpg_error (GPG_ERR_INV_ID);
 
1457
  else if (!*s)
 
1458
    ; /* no fingerprint given: we allow this for now. */
 
1459
  else if (*s == '/')
 
1460
    fpr = s + 1; 
 
1461
  else
 
1462
    return gpg_error (GPG_ERR_INV_ID);
 
1463
 
 
1464
  for (s=keyidstr, n=0; n < 16; s += 2, n++)
 
1465
    tmp_sn[n] = xtoi_2 (s);
 
1466
 
 
1467
  if (app->serialnolen != 16)
 
1468
    return gpg_error (GPG_ERR_INV_CARD);
 
1469
  if (memcmp (app->serialno, tmp_sn, 16))
 
1470
    return gpg_error (GPG_ERR_WRONG_CARD);
 
1471
 
 
1472
  /* If a fingerprint has been specified check it against the one on
 
1473
     the card.  This is allows for a meaningful error message in case
 
1474
     the key on the card has been replaced but the shadow information
 
1475
     known to gpg was not updated.  If there is no fingerprint, gpg
 
1476
     will detect a bogus signature anyway due to the
 
1477
     verify-after-signing feature. */
 
1478
  rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
 
1479
  if (rc)
 
1480
    return rc;
 
1481
 
 
1482
  rc = verify_chv2 (app, pincb, pincb_arg);
 
1483
  if (!rc)
 
1484
    rc = iso7816_internal_authenticate (app->slot, indata, indatalen,
 
1485
                                        outdata, outdatalen);
 
1486
  return rc;
 
1487
}
 
1488
 
 
1489
 
 
1490
static int 
 
1491
do_decipher (app_t app, const char *keyidstr,
 
1492
             int (pincb)(void*, const char *, char **),
 
1493
             void *pincb_arg,
 
1494
             const void *indata, size_t indatalen,
 
1495
             unsigned char **outdata, size_t *outdatalen )
 
1496
{
 
1497
  int rc;
 
1498
  unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
 
1499
  const char *s;
 
1500
  int n;
 
1501
  const char *fpr = NULL;
 
1502
 
 
1503
  if (!keyidstr || !*keyidstr || !indatalen)
 
1504
    return gpg_error (GPG_ERR_INV_VALUE);
 
1505
 
 
1506
  /* Check whether an OpenPGP card of any version has been requested. */
 
1507
  if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
 
1508
    return gpg_error (GPG_ERR_INV_ID);
 
1509
  
 
1510
  for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
 
1511
    ;
 
1512
  if (n != 32)
 
1513
    return gpg_error (GPG_ERR_INV_ID);
 
1514
  else if (!*s)
 
1515
    ; /* no fingerprint given: we allow this for now. */
 
1516
  else if (*s == '/')
 
1517
    fpr = s + 1; 
 
1518
  else
 
1519
    return gpg_error (GPG_ERR_INV_ID);
 
1520
 
 
1521
  for (s=keyidstr, n=0; n < 16; s += 2, n++)
 
1522
    tmp_sn[n] = xtoi_2 (s);
 
1523
 
 
1524
  if (app->serialnolen != 16)
 
1525
    return gpg_error (GPG_ERR_INV_CARD);
 
1526
  if (memcmp (app->serialno, tmp_sn, 16))
 
1527
    return gpg_error (GPG_ERR_WRONG_CARD);
 
1528
 
 
1529
  /* If a fingerprint has been specified check it against the one on
 
1530
     the card.  This is allows for a meaningful error message in case
 
1531
     the key on the card has been replaced but the shadow information
 
1532
     known to gpg was not updated.  If there is no fingerprint, the
 
1533
     decryption will won't produce the right plaintext anyway. */
 
1534
  rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0;
 
1535
  if (rc)
 
1536
    return rc;
 
1537
 
 
1538
  rc = verify_chv2 (app, pincb, pincb_arg);
 
1539
  if (!rc)
 
1540
    rc = iso7816_decipher (app->slot, indata, indatalen, 0,
 
1541
                           outdata, outdatalen);
 
1542
  return rc;
 
1543
}
 
1544
 
 
1545
 
 
1546
/* Perform a simple verify operation for CHV1 and CHV2, so that
 
1547
   further operations won't ask for CHV2 and it is possible to do a
 
1548
   cheap check on the PIN: If there is something wrong with the PIN
 
1549
   entry system, only the regular CHV will get blocked and not the
 
1550
   dangerous CHV3.  KEYIDSTR is the usual card's serial number; an
 
1551
   optional fingerprint part will be ignored. */
 
1552
static int 
 
1553
do_check_pin (app_t app, const char *keyidstr,
 
1554
              int (pincb)(void*, const char *, char **),
 
1555
              void *pincb_arg)
 
1556
{
 
1557
  unsigned char tmp_sn[20]; 
 
1558
  const char *s;
 
1559
  int n;
 
1560
 
 
1561
  if (!keyidstr || !*keyidstr)
 
1562
    return gpg_error (GPG_ERR_INV_VALUE);
 
1563
 
 
1564
  /* Check whether an OpenPGP card of any version has been requested. */
 
1565
  if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
 
1566
    return gpg_error (GPG_ERR_INV_ID);
 
1567
  
 
1568
  for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
 
1569
    ;
 
1570
  if (n != 32)
 
1571
    return gpg_error (GPG_ERR_INV_ID);
 
1572
  else if (!*s)
 
1573
    ; /* No fingerprint given: we allow this for now. */
 
1574
  else if (*s == '/')
 
1575
    ; /* We ignore a fingerprint. */
 
1576
  else
 
1577
    return gpg_error (GPG_ERR_INV_ID);
 
1578
 
 
1579
  for (s=keyidstr, n=0; n < 16; s += 2, n++)
 
1580
    tmp_sn[n] = xtoi_2 (s);
 
1581
 
 
1582
  if (app->serialnolen != 16)
 
1583
    return gpg_error (GPG_ERR_INV_CARD);
 
1584
  if (memcmp (app->serialno, tmp_sn, 16))
 
1585
    return gpg_error (GPG_ERR_WRONG_CARD);
 
1586
  /* Yes, there is a race conditions: The user might pull the card
 
1587
     right here and we won't notice that.  However this is not a
 
1588
     problem and the check above is merely for a graceful failure
 
1589
     between operations. */
 
1590
 
 
1591
  return verify_chv2 (app, pincb, pincb_arg);
 
1592
}
 
1593
 
 
1594
 
 
1595
 
 
1596
 
 
1597
/* Select the OpenPGP application on the card in SLOT.  This function
 
1598
   must be used before any other OpenPGP application functions. */
 
1599
int
 
1600
app_select_openpgp (app_t app)
 
1601
{
 
1602
  static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
 
1603
  int slot = app->slot;
 
1604
  int rc;
 
1605
  unsigned char *buffer;
 
1606
  size_t buflen;
 
1607
  void *relptr;
 
1608
  
 
1609
  rc = iso7816_select_application (slot, aid, sizeof aid);
 
1610
  if (!rc)
 
1611
    {
 
1612
      unsigned int manufacturer;
 
1613
 
 
1614
      app->apptype = "OPENPGP";
 
1615
 
 
1616
      app->did_chv1 = 0;
 
1617
      app->did_chv2 = 0;
 
1618
      app->did_chv3 = 0;
 
1619
      app->app_local = NULL;
 
1620
 
 
1621
      /* The OpenPGP card returns the serial number as part of the
 
1622
         AID; because we prefer to use OpenPGP serial numbers, we
 
1623
         replace a possibly already set one from a EF.GDO with this
 
1624
         one.  Note, that for current OpenPGP cards, no EF.GDO exists
 
1625
         and thus it won't matter at all. */
 
1626
      rc = iso7816_get_data (slot, 0x004F, &buffer, &buflen);
 
1627
      if (rc)
 
1628
        goto leave;
 
1629
      if (opt.verbose)
 
1630
        {
 
1631
          log_info ("AID: ");
 
1632
          log_printhex ("", buffer, buflen);
 
1633
        }
 
1634
 
 
1635
      app->card_version = buffer[6] << 8;
 
1636
      app->card_version |= buffer[7];
 
1637
      manufacturer = (buffer[8]<<8 | buffer[9]);
 
1638
 
 
1639
      xfree (app->serialno);
 
1640
      app->serialno = buffer;
 
1641
      app->serialnolen = buflen;
 
1642
      buffer = NULL;
 
1643
      app->app_local = xtrycalloc (1, sizeof *app->app_local);
 
1644
      if (!app->app_local)
 
1645
        {
 
1646
          rc = gpg_error (gpg_err_code_from_errno (errno));
 
1647
          goto leave;
 
1648
        }
 
1649
 
 
1650
      relptr = get_one_do (app, 0x00C4, &buffer, &buflen);
 
1651
      if (!relptr)
 
1652
        {
 
1653
          log_error (_("can't access %s - invalid OpenPGP card?\n"),
 
1654
                     "CHV Status Bytes");
 
1655
          goto leave;
 
1656
        }
 
1657
      app->force_chv1 = (buflen && *buffer == 0);
 
1658
      xfree (relptr);
 
1659
 
 
1660
      relptr = get_one_do (app, 0x00C0, &buffer, &buflen);
 
1661
      if (!relptr)
 
1662
        {
 
1663
          log_error (_("can't access %s - invalid OpenPGP card?\n"),
 
1664
                     "Extended Capability Flags" );
 
1665
          goto leave;
 
1666
        }
 
1667
      if (buflen)
 
1668
        {
 
1669
          app->app_local->extcap.get_challenge    = !!(*buffer & 0x40);
 
1670
          app->app_local->extcap.key_import       = !!(*buffer & 0x20);
 
1671
          app->app_local->extcap.change_force_chv = !!(*buffer & 0x10);
 
1672
          app->app_local->extcap.private_dos      = !!(*buffer & 0x08);
 
1673
        }
 
1674
      xfree (relptr);
 
1675
      
 
1676
      /* Some of the first cards accidently don't set the
 
1677
         CHANGE_FORCE_CHV bit but allow it anyway. */
 
1678
      if (app->card_version <= 0x0100 && manufacturer == 1)
 
1679
        app->app_local->extcap.change_force_chv = 1;
 
1680
 
 
1681
      parse_login_data (app);
 
1682
 
 
1683
      if (opt.verbose > 1)
 
1684
        dump_all_do (slot);
 
1685
 
 
1686
      app->fnc.deinit = do_deinit;
 
1687
      app->fnc.learn_status = do_learn_status;
 
1688
      app->fnc.readcert = NULL;
 
1689
      app->fnc.getattr = do_getattr;
 
1690
      app->fnc.setattr = do_setattr;
 
1691
      app->fnc.genkey = do_genkey;
 
1692
      app->fnc.sign = do_sign;
 
1693
      app->fnc.auth = do_auth;
 
1694
      app->fnc.decipher = do_decipher;
 
1695
      app->fnc.change_pin = do_change_pin;
 
1696
      app->fnc.check_pin = do_check_pin;
 
1697
   }
 
1698
 
 
1699
leave:
 
1700
  if (rc)
 
1701
    do_deinit (app);
 
1702
  return rc;
 
1703
}
 
1704
 
 
1705
 
 
1706
 
 
1707
/* This function is a hack to retrieve essential information about the
 
1708
   card to be displayed by simple tools.  It mostly resembles what the
 
1709
   LEARN command returns. All parameters return allocated strings or
 
1710
   buffers or NULL if the data object is not available.  All returned
 
1711
   values are sanitized. */
 
1712
int
 
1713
app_openpgp_cardinfo (app_t app,
 
1714
                      char **serialno,
 
1715
                      char **disp_name,
 
1716
                      char **pubkey_url,
 
1717
                      unsigned char **fpr1,
 
1718
                      unsigned char **fpr2,
 
1719
                      unsigned char **fpr3)
 
1720
{
 
1721
  int rc;
 
1722
  void *relptr;
 
1723
  unsigned char *value;
 
1724
  size_t valuelen;
 
1725
 
 
1726
  if (serialno)
 
1727
    {
 
1728
      time_t dummy;
 
1729
 
 
1730
      *serialno = NULL;
 
1731
      rc = app_get_serial_and_stamp (app, serialno, &dummy);
 
1732
      if (rc)
 
1733
        {
 
1734
          log_error (_("error getting serial number: %s\n"),
 
1735
                     gpg_strerror (rc));
 
1736
          return rc;
 
1737
        }
 
1738
    }
 
1739
      
 
1740
  if (disp_name)
 
1741
    {
 
1742
      *disp_name = NULL;
 
1743
      relptr = get_one_do (app, 0x005B, &value, &valuelen);
 
1744
      if (relptr)
 
1745
        {
 
1746
          *disp_name = make_printable_string (value, valuelen, 0);
 
1747
          xfree (relptr);
 
1748
        }
 
1749
    }
 
1750
 
 
1751
  if (pubkey_url)
 
1752
    {
 
1753
      *pubkey_url = NULL;
 
1754
      relptr = get_one_do (app, 0x5F50, &value, &valuelen);
 
1755
      if (relptr)
 
1756
        {
 
1757
          *pubkey_url = make_printable_string (value, valuelen, 0);
 
1758
          xfree (relptr);
 
1759
        }
 
1760
    }
 
1761
 
 
1762
  if (fpr1)
 
1763
    *fpr1 = NULL;
 
1764
  if (fpr2)
 
1765
    *fpr2 = NULL;
 
1766
  if (fpr3)
 
1767
    *fpr3 = NULL;
 
1768
  relptr = get_one_do (app, 0x00C5, &value, &valuelen);
 
1769
  if (relptr && valuelen >= 60)
 
1770
    {
 
1771
      if (fpr1)
 
1772
        {
 
1773
          *fpr1 = xmalloc (20);
 
1774
          memcpy (*fpr1, value +  0, 20);
 
1775
        }
 
1776
      if (fpr2)
 
1777
        {
 
1778
          *fpr2 = xmalloc (20);
 
1779
          memcpy (*fpr2, value + 20, 20);
 
1780
        }
 
1781
      if (fpr3)
 
1782
        {
 
1783
          *fpr3 = xmalloc (20);
 
1784
          memcpy (*fpr3, value + 40, 20);
 
1785
        }
 
1786
    }
 
1787
  xfree (relptr);
 
1788
 
 
1789
  return 0;
 
1790
}
 
1791
 
 
1792
 
 
1793
 
 
1794
/* This function is currently only used by the sc-copykeys program to
 
1795
   store a key on the smartcard.  app_t ist the application handle,
 
1796
   KEYNO is the number of the key and PINCB, PINCB_ARG are used to ask
 
1797
   for the SO PIN.  TEMPLATE and TEMPLATE_LEN describe a buffer with
 
1798
   the key template to store. CREATED_AT is the timestamp used to
 
1799
   create the fingerprint. M, MLEN is the RSA modulus and E, ELEN the
 
1800
   RSA public exponent. This function silently overwrites an existing
 
1801
   key.*/
 
1802
int 
 
1803
app_openpgp_storekey (app_t app, int keyno,
 
1804
                      unsigned char *template, size_t template_len,
 
1805
                      time_t created_at,
 
1806
                      const unsigned char *m, size_t mlen,
 
1807
                      const unsigned char *e, size_t elen,
 
1808
                      int (*pincb)(void*, const char *, char **),
 
1809
                      void *pincb_arg)
 
1810
{
 
1811
  int rc;
 
1812
  unsigned char fprbuf[20];
 
1813
 
 
1814
  if (keyno < 1 || keyno > 3)
 
1815
    return gpg_error (GPG_ERR_INV_ID);
 
1816
  keyno--;
 
1817
 
 
1818
  rc = verify_chv3 (app, pincb, pincb_arg);
 
1819
  if (rc)
 
1820
    goto leave;
 
1821
 
 
1822
  flush_cache (app);
 
1823
 
 
1824
  rc = iso7816_put_data (app->slot,
 
1825
                         (app->card_version > 0x0007? 0xE0 : 0xE9) + keyno,
 
1826
                         template, template_len);
 
1827
  if (rc)
 
1828
    {
 
1829
      log_error (_("failed to store the key: %s\n"), gpg_strerror (rc));
 
1830
      rc = gpg_error (GPG_ERR_CARD);
 
1831
      goto leave;
 
1832
    }
 
1833
 
 
1834
/*    log_printhex ("RSA n:", m, mlen);  */
 
1835
/*    log_printhex ("RSA e:", e, elen);  */
 
1836
 
 
1837
  rc = store_fpr (app->slot, keyno, (u32)created_at,
 
1838
                  m, mlen, e, elen, fprbuf, app->card_version);
 
1839
 
 
1840
 leave:
 
1841
  return rc;
 
1842
}
 
1843
 
 
1844
 
 
1845
/* Utility function for external tools: Read the public RSA key at
 
1846
   KEYNO and return modulus and exponent in (M,MLEN) and (E,ELEN). */
 
1847
int 
 
1848
app_openpgp_readkey (app_t app, int keyno, unsigned char **m, size_t *mlen,
 
1849
                     unsigned char **e, size_t *elen)
 
1850
{
 
1851
  int rc;
 
1852
  const unsigned char *keydata, *a;
 
1853
  unsigned char *buffer;
 
1854
  size_t buflen, keydatalen, alen;
 
1855
 
 
1856
  *m = NULL;
 
1857
  *e = NULL;
 
1858
 
 
1859
  if (keyno < 1 || keyno > 3)
 
1860
    return gpg_error (GPG_ERR_INV_ID);
 
1861
  keyno--;
 
1862
 
 
1863
  rc = iso7816_read_public_key(app->slot, 
 
1864
                               keyno == 0? "\xB6" :
 
1865
                               keyno == 1? "\xB8" : "\xA4",
 
1866
                               2,
 
1867
                               &buffer, &buflen);
 
1868
  if (rc)
 
1869
    {
 
1870
      rc = gpg_error (GPG_ERR_CARD);
 
1871
      log_error (_("reading the key failed\n"));
 
1872
      goto leave;
 
1873
    }
 
1874
 
 
1875
  keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
 
1876
  if (!keydata)
 
1877
    {
 
1878
      log_error (_("response does not contain the public key data\n"));
 
1879
      rc = gpg_error (GPG_ERR_CARD);
 
1880
      goto leave;
 
1881
    }
 
1882
 
 
1883
  a = find_tlv (keydata, keydatalen, 0x0081, &alen);
 
1884
  if (!a)
 
1885
    {
 
1886
      log_error (_("response does not contain the RSA modulus\n"));
 
1887
      rc = gpg_error (GPG_ERR_CARD);
 
1888
      goto leave;
 
1889
    }
 
1890
  *mlen = alen;
 
1891
  *m = xmalloc (alen);
 
1892
  memcpy (*m, a, alen);
 
1893
  
 
1894
  a = find_tlv (keydata, keydatalen, 0x0082, &alen);
 
1895
  if (!a)
 
1896
    {
 
1897
      log_error (_("response does not contain the RSA public exponent\n"));
 
1898
      rc = gpg_error (GPG_ERR_CARD);
 
1899
      goto leave;
 
1900
    }
 
1901
  *elen = alen;
 
1902
  *e = xmalloc (alen);
 
1903
  memcpy (*e, a, alen);
 
1904
 
 
1905
 leave:
 
1906
  xfree (buffer);
 
1907
  if (rc)
 
1908
    { 
 
1909
      xfree (*m); *m = NULL;
 
1910
      xfree (*e); *e = NULL;
 
1911
    }
 
1912
  return rc;
 
1913
}