~ubuntu-branches/ubuntu/precise/gnupg2/precise-updates

« back to all changes in this revision

Viewing changes to .pc/CVE-2015-1607.patch/scd/app-openpgp.c

  • Committer: Package Import Robot
  • Author(s): Marc Deslauriers
  • Date: 2015-03-27 08:20:03 UTC
  • Revision ID: package-import@ubuntu.com-20150327082003-doob38ydqdxubnf1
Tags: 2.0.17-2ubuntu2.12.04.6
* Screen responses from keyservers (LP: #1409117)
  - d/p/0001-Screen-keyserver-responses.patch
  - d/p/0002-Make-screening-of-keyserver-result-work-with-multi-k.patch
  - d/p/0003-Add-kbnode_t-for-easier-backporting.patch
  - d/p/0004-gpg-Fix-regression-due-to-the-keyserver-import-filte.patch
* Fix large key size regression from CVE-2014-5270 changes (LP: #1371766)
  - d/p/Add-build-and-runtime-support-for-larger-RSA-key.patch
  - debian/rules: build with --enable-large-secmem
* SECURITY UPDATE: invalid memory read via invalid keyring
  - debian/patches/CVE-2015-1606.patch: skip all packets not allowed in
    a keyring in g10/keyring.c.
  - CVE-2015-1606
* SECURITY UPDATE: memcpy with overlapping ranges
  - debian/patches/CVE-2015-1607.patch: use inline functions to convert
    buffer data to scalars in common/iobuf.c, g10/build-packet.c,
    g10/getkey.c, g10/keygen.c, g10/keyid.c, g10/main.h, g10/misc.c,
    g10/parse-packet.c, g10/tdbio.c, g10/trustdb.c, include/host2net.h,
    kbx/keybox-dump.c, kbx/keybox-openpgp.c, kbx/keybox-search.c,
    kbx/keybox-update.c, scd/apdu.c, scd/app-openpgp.c,
    scd/ccid-driver.c, scd/pcsc-wrapper.c, tools/ccidmon.c.
  - CVE-2015-1607

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, 2005, 2007, 2008,
 
3
 *               2009 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
/* Some notes:
 
22
 
 
23
   CHV means Card Holder Verification and is nothing else than a PIN
 
24
   or password.  That term seems to have been used originally with GSM
 
25
   cards.  Version v2 of the specs changes the term to the clearer
 
26
   term PW for password.  We use the terms here interchangeable
 
27
   because we do not want to change existing strings i18n wise.
 
28
 
 
29
   Version 2 of the specs also drops the separate PW2 which was
 
30
   required in v1 due to ISO requirements.  It is now possible to have
 
31
   one physical PW but two reference to it so that they can be
 
32
   individually be verified (e.g. to implement a forced verification
 
33
   for one key).  Thus you will noticed the use of PW2 with the verify
 
34
   command but not with change_reference_data because the latter
 
35
   operates directly on the physical PW.
 
36
 
 
37
   The Reset Code (RC) as implemented by v2 cards uses the same error
 
38
   counter as the PW2 of v1 cards.  By default no RC is set and thus
 
39
   that error counter is set to 0.  After setting the RC the error
 
40
   counter will be initialized to 3.
 
41
 
 
42
 */
 
43
 
 
44
#include <config.h>
 
45
#include <errno.h>
 
46
#include <stdio.h>
 
47
#include <stdlib.h>
 
48
#include <string.h>
 
49
#include <assert.h>
 
50
#include <time.h>
 
51
 
 
52
#if GNUPG_MAJOR_VERSION == 1
 
53
/* This is used with GnuPG version < 1.9.  The code has been source
 
54
   copied from the current GnuPG >= 1.9  and is maintained over
 
55
   there. */
 
56
#include "options.h"
 
57
#include "errors.h"
 
58
#include "memory.h"
 
59
#include "util.h"
 
60
#include "cardglue.h"
 
61
#else /* GNUPG_MAJOR_VERSION != 1 */
 
62
#include "scdaemon.h"
 
63
#endif /* GNUPG_MAJOR_VERSION != 1 */
 
64
 
 
65
#include "i18n.h"
 
66
#include "iso7816.h"
 
67
#include "app-common.h"
 
68
#include "tlv.h"
 
69
 
 
70
 
 
71
/* A table describing the DOs of the card.  */
 
72
static struct {
 
73
  int tag;
 
74
  int constructed;
 
75
  int get_from;  /* Constructed DO with this DO or 0 for direct access. */
 
76
  int binary:1;
 
77
  int dont_cache:1;
 
78
  int flush_on_error:1;
 
79
  int get_immediate_in_v11:1; /* Enable a hack to bypass the cache of
 
80
                                 this data object if it is used in 1.1
 
81
                                 and later versions of the card.  This
 
82
                                 does not work with composite DO and
 
83
                                 is currently only useful for the CHV
 
84
                                 status bytes. */
 
85
  int try_extlen:1;           /* Large object; try to use an extended
 
86
                                 length APDU.  */
 
87
  char *desc;
 
88
} data_objects[] = {
 
89
  { 0x005E, 0,    0, 1, 0, 0, 0, 0, "Login Data" },
 
90
  { 0x5F50, 0,    0, 0, 0, 0, 0, 0, "URL" },
 
91
  { 0x5F52, 0,    0, 1, 0, 0, 0, 0, "Historical Bytes" },
 
92
  { 0x0065, 1,    0, 1, 0, 0, 0, 0, "Cardholder Related Data"},
 
93
  { 0x005B, 0, 0x65, 0, 0, 0, 0, 0, "Name" },
 
94
  { 0x5F2D, 0, 0x65, 0, 0, 0, 0, 0, "Language preferences" },
 
95
  { 0x5F35, 0, 0x65, 0, 0, 0, 0, 0, "Sex" },
 
96
  { 0x006E, 1,    0, 1, 0, 0, 0, 0, "Application Related Data" },
 
97
  { 0x004F, 0, 0x6E, 1, 0, 0, 0, 0, "AID" },
 
98
  { 0x0073, 1,    0, 1, 0, 0, 0, 0, "Discretionary Data Objects" },
 
99
  { 0x0047, 0, 0x6E, 1, 1, 0, 0, 0, "Card Capabilities" },
 
100
  { 0x00C0, 0, 0x6E, 1, 1, 0, 0, 0, "Extended Card Capabilities" },
 
101
  { 0x00C1, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Signature" },
 
102
  { 0x00C2, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Decryption" },
 
103
  { 0x00C3, 0, 0x6E, 1, 1, 0, 0, 0, "Algorithm Attributes Authentication" },
 
104
  { 0x00C4, 0, 0x6E, 1, 0, 1, 1, 0, "CHV Status Bytes" },
 
105
  { 0x00C5, 0, 0x6E, 1, 0, 0, 0, 0, "Fingerprints" },
 
106
  { 0x00C6, 0, 0x6E, 1, 0, 0, 0, 0, "CA Fingerprints" },
 
107
  { 0x00CD, 0, 0x6E, 1, 0, 0, 0, 0, "Generation time" },
 
108
  { 0x007A, 1,    0, 1, 0, 0, 0, 0, "Security Support Template" },
 
109
  { 0x0093, 0, 0x7A, 1, 1, 0, 0, 0, "Digital Signature Counter" },
 
110
  { 0x0101, 0,    0, 0, 0, 0, 0, 0, "Private DO 1"},
 
111
  { 0x0102, 0,    0, 0, 0, 0, 0, 0, "Private DO 2"},
 
112
  { 0x0103, 0,    0, 0, 0, 0, 0, 0, "Private DO 3"},
 
113
  { 0x0104, 0,    0, 0, 0, 0, 0, 0, "Private DO 4"},
 
114
  { 0x7F21, 1,    0, 1, 0, 0, 0, 1, "Cardholder certificate"},
 
115
  { 0 }
 
116
};
 
117
 
 
118
 
 
119
/* The format of RSA private keys.  */
 
120
typedef enum
 
121
  { 
 
122
    RSA_UNKNOWN_FMT,
 
123
    RSA_STD,
 
124
    RSA_STD_N,
 
125
    RSA_CRT,
 
126
    RSA_CRT_N
 
127
  } 
 
128
rsa_key_format_t;
 
129
 
 
130
 
 
131
/* One cache item for DOs.  */
 
132
struct cache_s {
 
133
  struct cache_s *next;
 
134
  int tag;
 
135
  size_t length;
 
136
  unsigned char data[1];
 
137
};
 
138
 
 
139
 
 
140
/* Object with application (i.e. OpenPGP card) specific data.  */
 
141
struct app_local_s {
 
142
  /* A linked list with cached DOs.  */
 
143
  struct cache_s *cache;
 
144
  
 
145
  /* Keep track of the public keys.  */
 
146
  struct
 
147
  {
 
148
    int read_done;   /* True if we have at least tried to read them.  */
 
149
    unsigned char *key; /* This is a malloced buffer with a canonical
 
150
                           encoded S-expression encoding a public
 
151
                           key. Might be NULL if key is not
 
152
                           available.  */
 
153
    size_t keylen;      /* The length of the above S-expression.  This
 
154
                           is usually only required for cross checks
 
155
                           because the length of an S-expression is
 
156
                           implicitly available.  */
 
157
  } pk[3];
 
158
 
 
159
  unsigned char status_indicator; /* The card status indicator.  */
 
160
 
 
161
  /* Keep track of the ISO card capabilities.  */
 
162
  struct
 
163
  {
 
164
    unsigned int cmd_chaining:1;  /* Command chaining is supported.  */
 
165
    unsigned int ext_lc_le:1;     /* Extended Lc and Le are supported.  */
 
166
  } cardcap;
 
167
 
 
168
  /* Keep track of extended card capabilities.  */
 
169
  struct 
 
170
  {
 
171
    unsigned int is_v2:1;              /* This is a v2.0 compatible card.  */
 
172
    unsigned int get_challenge:1;
 
173
    unsigned int key_import:1;
 
174
    unsigned int change_force_chv:1;
 
175
    unsigned int private_dos:1;
 
176
    unsigned int algo_attr_change:1;   /* Algorithm attributes changeable.  */
 
177
    unsigned int sm_supported:1;       /* Secure Messaging is supported.  */
 
178
    unsigned int sm_aes128:1;          /* Use AES-128 for SM.  */
 
179
    unsigned int max_certlen_3:16;
 
180
    unsigned int max_get_challenge:16; /* Maximum size for get_challenge.  */
 
181
    unsigned int max_cmd_data:16;      /* Maximum data size for a command.  */
 
182
    unsigned int max_rsp_data:16;      /* Maximum size of a response.  */
 
183
  } extcap;
 
184
 
 
185
  /* Flags used to control the application.  */
 
186
  struct
 
187
  {
 
188
    unsigned int no_sync:1;   /* Do not sync CHV1 and CHV2 */
 
189
    unsigned int def_chv2:1;  /* Use 123456 for CHV2.  */
 
190
  } flags;
 
191
 
 
192
  struct
 
193
  {
 
194
    unsigned int n_bits;     /* Size of the modulus in bits.  The rest
 
195
                                of this strucuire is only valid if
 
196
                                this is not 0.  */
 
197
    unsigned int e_bits;     /* Size of the public exponent in bits.  */
 
198
    rsa_key_format_t format;  
 
199
  } keyattr[3];
 
200
 
 
201
};
 
202
 
 
203
 
 
204
 
 
205
/***** Local prototypes  *****/
 
206
static unsigned long convert_sig_counter_value (const unsigned char *value,
 
207
                                                size_t valuelen);
 
208
static unsigned long get_sig_counter (app_t app);
 
209
static gpg_error_t do_auth (app_t app, const char *keyidstr,
 
210
                            gpg_error_t (*pincb)(void*, const char *, char **),
 
211
                            void *pincb_arg,
 
212
                            const void *indata, size_t indatalen,
 
213
                            unsigned char **outdata, size_t *outdatalen);
 
214
static void parse_algorithm_attribute (app_t app, int keyno);
 
215
static gpg_error_t change_keyattr_from_string
 
216
                           (app_t app, 
 
217
                            gpg_error_t (*pincb)(void*, const char *, char **),
 
218
                            void *pincb_arg,
 
219
                            const void *value, size_t valuelen);
 
220
 
 
221
 
 
222
 
 
223
 
 
224
 
 
225
/* Deconstructor. */
 
226
static void
 
227
do_deinit (app_t app)
 
228
{
 
229
  if (app && app->app_local)
 
230
    {
 
231
      struct cache_s *c, *c2;
 
232
      int i;
 
233
 
 
234
      for (c = app->app_local->cache; c; c = c2)
 
235
        {
 
236
          c2 = c->next;
 
237
          xfree (c);
 
238
        }
 
239
 
 
240
      for (i=0; i < DIM (app->app_local->pk); i++)
 
241
        {
 
242
          xfree (app->app_local->pk[i].key);
 
243
          app->app_local->pk[i].read_done = 0;
 
244
        }
 
245
      xfree (app->app_local);
 
246
      app->app_local = NULL;
 
247
    }
 
248
}
 
249
 
 
250
 
 
251
/* Wrapper around iso7816_get_data which first tries to get the data
 
252
   from the cache.  With GET_IMMEDIATE passed as true, the cache is
 
253
   bypassed.  With TRY_EXTLEN extended lengths APDUs are use if
 
254
   supported by the card.  */
 
255
static gpg_error_t
 
256
get_cached_data (app_t app, int tag, 
 
257
                 unsigned char **result, size_t *resultlen,
 
258
                 int get_immediate, int try_extlen)
 
259
{
 
260
  gpg_error_t err;
 
261
  int i;
 
262
  unsigned char *p;
 
263
  size_t len;
 
264
  struct cache_s *c;
 
265
  int exmode;
 
266
 
 
267
  *result = NULL;
 
268
  *resultlen = 0;
 
269
 
 
270
  if (!get_immediate)
 
271
    {
 
272
      for (c=app->app_local->cache; c; c = c->next)
 
273
        if (c->tag == tag)
 
274
          {
 
275
            if(c->length)
 
276
              {
 
277
                p = xtrymalloc (c->length);
 
278
                if (!p)
 
279
                  return gpg_error (gpg_err_code_from_errno (errno));
 
280
                memcpy (p, c->data, c->length);
 
281
                *result = p;
 
282
              }
 
283
            
 
284
            *resultlen = c->length;
 
285
            
 
286
            return 0;
 
287
          }
 
288
    }
 
289
  
 
290
  if (try_extlen && app->app_local->cardcap.ext_lc_le)
 
291
    exmode = app->app_local->extcap.max_rsp_data;
 
292
  else
 
293
    exmode = 0;
 
294
 
 
295
  err = iso7816_get_data (app->slot, exmode, tag, &p, &len);
 
296
  if (err)
 
297
    return err;
 
298
  *result = p;
 
299
  *resultlen = len;
 
300
 
 
301
  /* Check whether we should cache this object. */
 
302
  if (get_immediate)
 
303
    return 0;
 
304
 
 
305
  for (i=0; data_objects[i].tag; i++)
 
306
    if (data_objects[i].tag == tag)
 
307
      {
 
308
        if (data_objects[i].dont_cache)
 
309
          return 0;
 
310
        break;
 
311
      }
 
312
 
 
313
  /* Okay, cache it. */
 
314
  for (c=app->app_local->cache; c; c = c->next)
 
315
    assert (c->tag != tag);
 
316
  
 
317
  c = xtrymalloc (sizeof *c + len);
 
318
  if (c)
 
319
    {
 
320
      memcpy (c->data, p, len);
 
321
      c->length = len;
 
322
      c->tag = tag;
 
323
      c->next = app->app_local->cache;
 
324
      app->app_local->cache = c;
 
325
    }
 
326
 
 
327
  return 0;
 
328
}
 
329
 
 
330
/* Remove DO at TAG from the cache. */
 
331
static void
 
332
flush_cache_item (app_t app, int tag)
 
333
{
 
334
  struct cache_s *c, *cprev;
 
335
  int i;
 
336
 
 
337
  if (!app->app_local)
 
338
    return;
 
339
 
 
340
  for (c=app->app_local->cache, cprev=NULL; c ; cprev=c, c = c->next)
 
341
    if (c->tag == tag)
 
342
      {
 
343
        if (cprev)
 
344
          cprev->next = c->next;
 
345
        else
 
346
          app->app_local->cache = c->next;
 
347
        xfree (c);
 
348
 
 
349
        for (c=app->app_local->cache; c ; c = c->next)
 
350
          {
 
351
            assert (c->tag != tag); /* Oops: duplicated entry. */
 
352
          }
 
353
        return;
 
354
      }
 
355
 
 
356
  /* Try again if we have an outer tag. */
 
357
  for (i=0; data_objects[i].tag; i++)
 
358
    if (data_objects[i].tag == tag && data_objects[i].get_from
 
359
        && data_objects[i].get_from != tag)
 
360
      flush_cache_item (app, data_objects[i].get_from);
 
361
}
 
362
 
 
363
/* Flush all entries from the cache which might be out of sync after
 
364
   an error. */
 
365
static void
 
366
flush_cache_after_error (app_t app)
 
367
{
 
368
  int i;
 
369
 
 
370
  for (i=0; data_objects[i].tag; i++)
 
371
    if (data_objects[i].flush_on_error)
 
372
      flush_cache_item (app, data_objects[i].tag);
 
373
}
 
374
 
 
375
 
 
376
/* Flush the entire cache. */
 
377
static void
 
378
flush_cache (app_t app)
 
379
{
 
380
  if (app && app->app_local)
 
381
    {
 
382
      struct cache_s *c, *c2;
 
383
 
 
384
      for (c = app->app_local->cache; c; c = c2)
 
385
        {
 
386
          c2 = c->next;
 
387
          xfree (c);
 
388
        }
 
389
      app->app_local->cache = NULL;
 
390
    }
 
391
}
 
392
 
 
393
 
 
394
/* Get the DO identified by TAG from the card in SLOT and return a
 
395
   buffer with its content in RESULT and NBYTES.  The return value is
 
396
   NULL if not found or a pointer which must be used to release the
 
397
   buffer holding value. */
 
398
static void *
 
399
get_one_do (app_t app, int tag, unsigned char **result, size_t *nbytes,
 
400
            int *r_rc)
 
401
{
 
402
  int rc, i;
 
403
  unsigned char *buffer;
 
404
  size_t buflen;
 
405
  unsigned char *value;
 
406
  size_t valuelen;
 
407
  int dummyrc;
 
408
  int exmode;
 
409
 
 
410
  if (!r_rc)
 
411
    r_rc = &dummyrc;
 
412
 
 
413
  *result = NULL;
 
414
  *nbytes = 0;
 
415
  *r_rc = 0;
 
416
  for (i=0; data_objects[i].tag && data_objects[i].tag != tag; i++)
 
417
    ;
 
418
 
 
419
  if (app->card_version > 0x0100 && data_objects[i].get_immediate_in_v11)
 
420
    {
 
421
      if (data_objects[i].try_extlen && app->app_local->cardcap.ext_lc_le)
 
422
        exmode = app->app_local->extcap.max_rsp_data;
 
423
      else
 
424
        exmode = 0;
 
425
      rc = iso7816_get_data (app->slot, exmode, tag, &buffer, &buflen);
 
426
      if (rc)
 
427
        {
 
428
          *r_rc = rc;
 
429
          return NULL;
 
430
        }
 
431
      *result = buffer;
 
432
      *nbytes = buflen;
 
433
      return buffer;
 
434
    }
 
435
 
 
436
  value = NULL;
 
437
  rc = -1;
 
438
  if (data_objects[i].tag && data_objects[i].get_from)
 
439
    {
 
440
      rc = get_cached_data (app, data_objects[i].get_from,
 
441
                            &buffer, &buflen,
 
442
                            (data_objects[i].dont_cache 
 
443
                             || data_objects[i].get_immediate_in_v11),
 
444
                            data_objects[i].try_extlen);
 
445
      if (!rc)
 
446
        {
 
447
          const unsigned char *s;
 
448
 
 
449
          s = find_tlv_unchecked (buffer, buflen, tag, &valuelen);
 
450
          if (!s)
 
451
            value = NULL; /* not found */
 
452
          else if (valuelen > buflen - (s - buffer))
 
453
            {
 
454
              log_error ("warning: constructed DO too short\n");
 
455
              value = NULL;
 
456
              xfree (buffer); buffer = NULL;
 
457
            }
 
458
          else
 
459
            value = buffer + (s - buffer);
 
460
        }
 
461
    }
 
462
 
 
463
  if (!value) /* Not in a constructed DO, try simple. */
 
464
    {
 
465
      rc = get_cached_data (app, tag, &buffer, &buflen,
 
466
                            (data_objects[i].dont_cache 
 
467
                             || data_objects[i].get_immediate_in_v11),
 
468
                            data_objects[i].try_extlen);
 
469
      if (!rc)
 
470
        {
 
471
          value = buffer;
 
472
          valuelen = buflen;
 
473
        }
 
474
    }
 
475
 
 
476
  if (!rc)
 
477
    {
 
478
      *nbytes = valuelen;
 
479
      *result = value;
 
480
      return buffer;
 
481
    }
 
482
  *r_rc = rc;
 
483
  return NULL;
 
484
}
 
485
 
 
486
 
 
487
static void
 
488
dump_all_do (int slot)
 
489
{
 
490
  int rc, i, j;
 
491
  unsigned char *buffer;
 
492
  size_t buflen;
 
493
  
 
494
  for (i=0; data_objects[i].tag; i++)
 
495
    {
 
496
      if (data_objects[i].get_from)
 
497
        continue;
 
498
 
 
499
      /* We don't try extended length APDU because such large DO would
 
500
         be pretty useless in a log file.  */
 
501
      rc = iso7816_get_data (slot, 0, data_objects[i].tag, &buffer, &buflen);
 
502
      if (gpg_err_code (rc) == GPG_ERR_NO_OBJ)
 
503
        ;
 
504
      else if (rc) 
 
505
        log_info ("DO `%s' not available: %s\n",
 
506
                  data_objects[i].desc, gpg_strerror (rc));
 
507
      else
 
508
        {
 
509
          if (data_objects[i].binary)
 
510
            {
 
511
              log_info ("DO `%s': ", data_objects[i].desc);
 
512
              log_printhex ("", buffer, buflen);
 
513
            }
 
514
          else
 
515
            log_info ("DO `%s': `%.*s'\n",
 
516
                      data_objects[i].desc,
 
517
                      (int)buflen, buffer); /* FIXME: sanitize */
 
518
 
 
519
          if (data_objects[i].constructed)
 
520
            {
 
521
              for (j=0; data_objects[j].tag; j++)
 
522
                {
 
523
                  const unsigned char *value;
 
524
                  size_t valuelen;
 
525
                  
 
526
                  if (j==i || data_objects[i].tag != data_objects[j].get_from)
 
527
                    continue;
 
528
                  value = find_tlv_unchecked (buffer, buflen,
 
529
                                              data_objects[j].tag, &valuelen);
 
530
                  if (!value)
 
531
                    ; /* not found */
 
532
                  else if (valuelen > buflen - (value - buffer))
 
533
                    log_error ("warning: constructed DO too short\n");
 
534
                  else
 
535
                    {
 
536
                      if (data_objects[j].binary)
 
537
                        {
 
538
                          log_info ("DO `%s': ", data_objects[j].desc);
 
539
                          if (valuelen > 200)
 
540
                            log_info ("[%u]\n", (unsigned int)valuelen);
 
541
                          else
 
542
                            log_printhex ("", value, valuelen);
 
543
                        }
 
544
                      else
 
545
                        log_info ("DO `%s': `%.*s'\n",
 
546
                                  data_objects[j].desc,
 
547
                                  (int)valuelen, value); /* FIXME: sanitize */
 
548
                    }
 
549
                }
 
550
            }
 
551
        }
 
552
      xfree (buffer); buffer = NULL;
 
553
    }
 
554
}
 
555
 
 
556
 
 
557
/* Count the number of bits, assuming the A represents an unsigned big
 
558
   integer of length LEN bytes. */
 
559
static unsigned int
 
560
count_bits (const unsigned char *a, size_t len)
 
561
{
 
562
  unsigned int n = len * 8;
 
563
  int i;
 
564
 
 
565
  for (; len && !*a; len--, a++, n -=8)
 
566
    ;
 
567
  if (len)
 
568
    {
 
569
      for (i=7; i && !(*a & (1<<i)); i--)
 
570
        n--;
 
571
    }
 
572
  return n;
 
573
}
 
574
 
 
575
/* GnuPG makes special use of the login-data DO, this function parses
 
576
   the login data to store the flags for later use.  It may be called
 
577
   at any time and should be called after changing the login-data DO.
 
578
 
 
579
   Everything up to a LF is considered a mailbox or account name.  If
 
580
   the first LF is followed by DC4 (0x14) control sequence are
 
581
   expected up to the next LF.  Control sequences are separated by FS
 
582
   (0x18) and consist of key=value pairs.  There is one key defined:
 
583
 
 
584
    F=<flags>
 
585
 
 
586
    Were FLAGS is a plain hexadecimal number representing flag values.
 
587
    The lsb is here the rightmost bit.  Defined flags bits are:
 
588
 
 
589
      Bit 0 = CHV1 and CHV2 are not syncronized
 
590
      Bit 1 = CHV2 has been been set to the default PIN of "123456"
 
591
              (this implies that bit 0 is also set).
 
592
 
 
593
*/
 
594
static void
 
595
parse_login_data (app_t app)
 
596
{
 
597
  unsigned char *buffer, *p;
 
598
  size_t buflen, len;
 
599
  void *relptr;
 
600
 
 
601
  /* Set defaults.  */
 
602
  app->app_local->flags.no_sync = 0;
 
603
  app->app_local->flags.def_chv2 = 0;
 
604
 
 
605
  /* Read the DO.  */
 
606
  relptr = get_one_do (app, 0x005E, &buffer, &buflen, NULL);
 
607
  if (!relptr)
 
608
    return; /* Ooops. */
 
609
  for (; buflen; buflen--, buffer++)
 
610
    if (*buffer == '\n')
 
611
      break;
 
612
  if (buflen < 2 || buffer[1] != '\x14')
 
613
    return; /* No control sequences.  */
 
614
  buflen--;
 
615
  buffer++;
 
616
  do
 
617
    {
 
618
      buflen--;
 
619
      buffer++;
 
620
      if (buflen > 1 && *buffer == 'F' && buffer[1] == '=')
 
621
        {
 
622
          /* Flags control sequence found.  */
 
623
          int lastdig = 0;
 
624
 
 
625
          /* For now we are only interested in the last digit, so skip
 
626
             any leading digits but bail out on invalid characters. */
 
627
          for (p=buffer+2, len = buflen-2; len && hexdigitp (p); p++, len--)
 
628
            lastdig = xtoi_1 (p);
 
629
          if (len && !(*p == '\n' || *p == '\x18'))
 
630
            goto next;  /* Invalid characters in field.  */
 
631
          app->app_local->flags.no_sync = !!(lastdig & 1);
 
632
          app->app_local->flags.def_chv2 = (lastdig & 3) == 3;
 
633
        }
 
634
    next:
 
635
      for (; buflen && *buffer != '\x18'; buflen--, buffer++)
 
636
        if (*buffer == '\n')
 
637
          buflen = 1; 
 
638
    }
 
639
  while (buflen);
 
640
 
 
641
  xfree (relptr);
 
642
}
 
643
 
 
644
/* Note, that FPR must be at least 20 bytes. */
 
645
static gpg_error_t 
 
646
store_fpr (app_t app, int keynumber, u32 timestamp,
 
647
           const unsigned char *m, size_t mlen,
 
648
           const unsigned char *e, size_t elen, 
 
649
           unsigned char *fpr, unsigned int card_version)
 
650
{
 
651
  unsigned int n, nbits;
 
652
  unsigned char *buffer, *p;
 
653
  int tag, tag2;
 
654
  int rc;
 
655
  
 
656
  for (; mlen && !*m; mlen--, m++) /* strip leading zeroes */
 
657
    ;
 
658
  for (; elen && !*e; elen--, e++) /* strip leading zeroes */
 
659
    ;
 
660
 
 
661
  n = 6 + 2 + mlen + 2 + elen;
 
662
  p = buffer = xtrymalloc (3 + n);
 
663
  if (!buffer)
 
664
    return gpg_error_from_syserror ();
 
665
  
 
666
  *p++ = 0x99;     /* ctb */
 
667
  *p++ = n >> 8;   /* 2 byte length header */
 
668
  *p++ = n;
 
669
  *p++ = 4;        /* key packet version */
 
670
  *p++ = timestamp >> 24;
 
671
  *p++ = timestamp >> 16;
 
672
  *p++ = timestamp >>  8;
 
673
  *p++ = timestamp;
 
674
  *p++ = 1; /* RSA */
 
675
  nbits = count_bits (m, mlen);
 
676
  *p++ = nbits >> 8;
 
677
  *p++ = nbits;
 
678
  memcpy (p, m, mlen); p += mlen;
 
679
  nbits = count_bits (e, elen);
 
680
  *p++ = nbits >> 8;
 
681
  *p++ = nbits;
 
682
  memcpy (p, e, elen); p += elen;
 
683
    
 
684
  gcry_md_hash_buffer (GCRY_MD_SHA1, fpr, buffer, n+3);
 
685
 
 
686
  xfree (buffer);
 
687
 
 
688
  tag = (card_version > 0x0007? 0xC7 : 0xC6) + keynumber;
 
689
  flush_cache_item (app, tag);
 
690
  tag2 = 0xCE + keynumber;
 
691
  flush_cache_item (app, tag2);
 
692
 
 
693
  rc = iso7816_put_data (app->slot, 0, tag, fpr, 20);
 
694
  if (rc)
 
695
    log_error (_("failed to store the fingerprint: %s\n"),gpg_strerror (rc));
 
696
 
 
697
  if (!rc && card_version > 0x0100)
 
698
    {
 
699
      unsigned char buf[4];
 
700
 
 
701
      buf[0] = timestamp >> 24;
 
702
      buf[1] = timestamp >> 16;
 
703
      buf[2] = timestamp >>  8;
 
704
      buf[3] = timestamp;
 
705
 
 
706
      rc = iso7816_put_data (app->slot, 0, tag2, buf, 4);
 
707
      if (rc)
 
708
        log_error (_("failed to store the creation date: %s\n"),
 
709
                   gpg_strerror (rc));
 
710
    }
 
711
 
 
712
  return rc;
 
713
}
 
714
 
 
715
       
 
716
static void
 
717
send_fpr_if_not_null (ctrl_t ctrl, const char *keyword,
 
718
                      int number, const unsigned char *fpr)
 
719
{                      
 
720
  int i;
 
721
  char buf[41];
 
722
  char numbuf[25];
 
723
 
 
724
  for (i=0; i < 20 && !fpr[i]; i++)
 
725
    ;
 
726
  if (i==20)
 
727
    return; /* All zero. */
 
728
  bin2hex (fpr, 20, buf);
 
729
  if (number == -1)
 
730
    *numbuf = 0; /* Don't print the key number */
 
731
  else
 
732
    sprintf (numbuf, "%d", number);
 
733
  send_status_info (ctrl, keyword,
 
734
                    numbuf, (size_t)strlen(numbuf),
 
735
                    buf, (size_t)strlen (buf), NULL, 0);
 
736
}
 
737
 
 
738
static void
 
739
send_fprtime_if_not_null (ctrl_t ctrl, const char *keyword,
 
740
                          int number, const unsigned char *stamp)
 
741
{                      
 
742
  char numbuf1[50], numbuf2[50];
 
743
  unsigned long value;
 
744
 
 
745
  value = (stamp[0] << 24) | (stamp[1]<<16) | (stamp[2]<<8) | stamp[3];
 
746
  if (!value)
 
747
    return;
 
748
  sprintf (numbuf1, "%d", number);
 
749
  sprintf (numbuf2, "%lu", value);
 
750
  send_status_info (ctrl, keyword,
 
751
                    numbuf1, (size_t)strlen(numbuf1),
 
752
                    numbuf2, (size_t)strlen(numbuf2), NULL, 0);
 
753
}
 
754
 
 
755
static void
 
756
send_key_data (ctrl_t ctrl, const char *name, 
 
757
               const unsigned char *a, size_t alen)
 
758
{
 
759
  char *buf;
 
760
  
 
761
  buf = bin2hex (a, alen, NULL);
 
762
  if (!buf)
 
763
    {
 
764
      log_error ("memory allocation error in send_key_data\n");
 
765
      return;
 
766
    }
 
767
 
 
768
  send_status_info (ctrl, "KEY-DATA",
 
769
                    name, (size_t)strlen(name), 
 
770
                    buf, (size_t)strlen (buf),
 
771
                    NULL, 0);
 
772
  xfree (buf);
 
773
}
 
774
 
 
775
 
 
776
static void
 
777
send_key_attr (ctrl_t ctrl, app_t app, const char *keyword, int number)
 
778
{                      
 
779
  char buffer[200];
 
780
 
 
781
  assert (number >=0 && number < DIM(app->app_local->keyattr));
 
782
 
 
783
  /* We only support RSA thus the algo identifier is fixed to 1.  */
 
784
  snprintf (buffer, sizeof buffer, "%d 1 %u %u %d",
 
785
            number+1,
 
786
            app->app_local->keyattr[number].n_bits,
 
787
            app->app_local->keyattr[number].e_bits,
 
788
            app->app_local->keyattr[number].format);
 
789
  send_status_direct (ctrl, keyword, buffer);
 
790
}
 
791
 
 
792
 
 
793
/* Implement the GETATTR command.  This is similar to the LEARN
 
794
   command but returns just one value via the status interface. */
 
795
static gpg_error_t 
 
796
do_getattr (app_t app, ctrl_t ctrl, const char *name)
 
797
{
 
798
  static struct {
 
799
    const char *name;
 
800
    int tag;
 
801
    int special;
 
802
  } table[] = {
 
803
    { "DISP-NAME",    0x005B },
 
804
    { "LOGIN-DATA",   0x005E },
 
805
    { "DISP-LANG",    0x5F2D },
 
806
    { "DISP-SEX",     0x5F35 },
 
807
    { "PUBKEY-URL",   0x5F50 },
 
808
    { "KEY-FPR",      0x00C5, 3 },
 
809
    { "KEY-TIME",     0x00CD, 4 },
 
810
    { "KEY-ATTR",     0x0000, -5 },
 
811
    { "CA-FPR",       0x00C6, 3 },
 
812
    { "CHV-STATUS",   0x00C4, 1 }, 
 
813
    { "SIG-COUNTER",  0x0093, 2 },
 
814
    { "SERIALNO",     0x004F, -1 },
 
815
    { "AID",          0x004F },
 
816
    { "EXTCAP",       0x0000, -2 },
 
817
    { "PRIVATE-DO-1", 0x0101 },
 
818
    { "PRIVATE-DO-2", 0x0102 },
 
819
    { "PRIVATE-DO-3", 0x0103 },
 
820
    { "PRIVATE-DO-4", 0x0104 },
 
821
    { "$AUTHKEYID",   0x0000, -3 },
 
822
    { "$DISPSERIALNO",0x0000, -4 },
 
823
    { NULL, 0 }
 
824
  };
 
825
  int idx, i, rc;
 
826
  void *relptr;
 
827
  unsigned char *value;
 
828
  size_t valuelen;
 
829
 
 
830
  for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
 
831
    ;
 
832
  if (!table[idx].name)
 
833
    return gpg_error (GPG_ERR_INV_NAME); 
 
834
  
 
835
  if (table[idx].special == -1)
 
836
    {
 
837
      /* The serial number is very special.  We could have used the
 
838
         AID DO to retrieve it, but we have it already in the app
 
839
         context and the stamp argument is required anyway which we
 
840
         can't by other means. The AID DO is available anyway but not
 
841
         hex formatted. */
 
842
      char *serial;
 
843
      time_t stamp;
 
844
      char tmp[50];
 
845
 
 
846
      if (!app_get_serial_and_stamp (app, &serial, &stamp))
 
847
        {
 
848
          sprintf (tmp, "%lu", (unsigned long)stamp);
 
849
          send_status_info (ctrl, "SERIALNO",
 
850
                            serial, strlen (serial),
 
851
                            tmp, strlen (tmp),
 
852
                            NULL, 0);
 
853
          xfree (serial);
 
854
        }
 
855
      return 0;
 
856
    }
 
857
  if (table[idx].special == -2)
 
858
    {
 
859
      char tmp[100];
 
860
 
 
861
      snprintf (tmp, sizeof tmp,
 
862
                "gc=%d ki=%d fc=%d pd=%d mcl3=%u aac=%d sm=%d", 
 
863
                app->app_local->extcap.get_challenge,
 
864
                app->app_local->extcap.key_import,
 
865
                app->app_local->extcap.change_force_chv,
 
866
                app->app_local->extcap.private_dos,
 
867
                app->app_local->extcap.max_certlen_3,
 
868
                app->app_local->extcap.algo_attr_change,
 
869
                (app->app_local->extcap.sm_supported
 
870
                 ? (app->app_local->extcap.sm_aes128? 7 : 2)
 
871
                 : 0));
 
872
      send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
 
873
      return 0;
 
874
    }
 
875
  if (table[idx].special == -3)
 
876
    {
 
877
      char const tmp[] = "OPENPGP.3";
 
878
      send_status_info (ctrl, table[idx].name, tmp, strlen (tmp), NULL, 0);
 
879
      return 0;
 
880
    }
 
881
  if (table[idx].special == -4)
 
882
    {
 
883
      char *serial;
 
884
      time_t stamp;
 
885
    
 
886
      if (!app_get_serial_and_stamp (app, &serial, &stamp))
 
887
        {
 
888
          if (strlen (serial) > 16+12)
 
889
            {
 
890
              send_status_info (ctrl, table[idx].name, serial+16, 12, NULL, 0);
 
891
              xfree (serial);
 
892
              return 0;
 
893
            }
 
894
          xfree (serial);
 
895
        }
 
896
      return gpg_error (GPG_ERR_INV_NAME); 
 
897
    }
 
898
  if (table[idx].special == -5)
 
899
    {
 
900
      for (i=0; i < 3; i++)
 
901
        send_key_attr (ctrl, app, table[idx].name, i);
 
902
      return 0;
 
903
    }
 
904
 
 
905
  relptr = get_one_do (app, table[idx].tag, &value, &valuelen, &rc);
 
906
  if (relptr)
 
907
    {
 
908
      if (table[idx].special == 1)
 
909
        {
 
910
          char numbuf[7*23];
 
911
          
 
912
          for (i=0,*numbuf=0; i < valuelen && i < 7; i++)
 
913
            sprintf (numbuf+strlen (numbuf), " %d", value[i]); 
 
914
          send_status_info (ctrl, table[idx].name,
 
915
                            numbuf, strlen (numbuf), NULL, 0);
 
916
        }
 
917
      else if (table[idx].special == 2)
 
918
        {
 
919
          char numbuf[50];
 
920
 
 
921
          sprintf (numbuf, "%lu", convert_sig_counter_value (value, valuelen));
 
922
          send_status_info (ctrl, table[idx].name,
 
923
                            numbuf, strlen (numbuf), NULL, 0);
 
924
        }
 
925
      else if (table[idx].special == 3)
 
926
        {
 
927
          if (valuelen >= 60)
 
928
            for (i=0; i < 3; i++)
 
929
              send_fpr_if_not_null (ctrl, table[idx].name, i+1, value+i*20);
 
930
        }
 
931
      else if (table[idx].special == 4)
 
932
        {
 
933
          if (valuelen >= 12)
 
934
            for (i=0; i < 3; i++)
 
935
              send_fprtime_if_not_null (ctrl, table[idx].name, i+1, value+i*4);
 
936
        }
 
937
      else
 
938
        send_status_info (ctrl, table[idx].name, value, valuelen, NULL, 0);
 
939
 
 
940
      xfree (relptr);
 
941
    }
 
942
  return rc;
 
943
}
 
944
 
 
945
/* Retrieve the fingerprint from the card inserted in SLOT and write
 
946
   the according hex representation to FPR.  Caller must have provide
 
947
   a buffer at FPR of least 41 bytes.  Returns 0 on success or an
 
948
   error code. */
 
949
#if GNUPG_MAJOR_VERSION > 1
 
950
static gpg_error_t
 
951
retrieve_fpr_from_card (app_t app, int keyno, char *fpr)
 
952
{
 
953
  gpg_error_t err = 0;
 
954
  void *relptr;
 
955
  unsigned char *value;
 
956
  size_t valuelen;
 
957
 
 
958
  assert (keyno >=0 && keyno <= 2);
 
959
 
 
960
  relptr = get_one_do (app, 0x00C5, &value, &valuelen, NULL);
 
961
  if (relptr && valuelen >= 60)
 
962
    bin2hex (value+keyno*20, 20, fpr);
 
963
  else
 
964
    err = gpg_error (GPG_ERR_NOT_FOUND);
 
965
  xfree (relptr);
 
966
  return err;
 
967
}
 
968
#endif /*GNUPG_MAJOR_VERSION > 1*/
 
969
 
 
970
 
 
971
/* Retrieve the public key material for the RSA key, whose fingerprint
 
972
   is FPR, from gpg output, which can be read through the stream FP.
 
973
   The RSA modulus will be stored at the address of M and MLEN, the
 
974
   public exponent at E and ELEN.  Returns zero on success, an error
 
975
   code on failure.  Caller must release the allocated buffers at M
 
976
   and E if the function returns success.  */
 
977
#if GNUPG_MAJOR_VERSION > 1
 
978
static gpg_error_t
 
979
retrieve_key_material (FILE *fp, const char *hexkeyid,
 
980
                       const unsigned char **m, size_t *mlen,
 
981
                       const unsigned char **e, size_t *elen)
 
982
{
 
983
  gcry_error_t err = 0;
 
984
  char *line = NULL;    /* read_line() buffer. */
 
985
  size_t line_size = 0; /* Helper for for read_line. */
 
986
  int found_key = 0;    /* Helper to find a matching key. */
 
987
  unsigned char *m_new = NULL;
 
988
  unsigned char *e_new = NULL;
 
989
  size_t m_new_n = 0;
 
990
  size_t e_new_n = 0;
 
991
 
 
992
  /* Loop over all records until we have found the subkey
 
993
     corresponding to the fingerprint. Inm general the first record
 
994
     should be the pub record, but we don't rely on that.  Given that
 
995
     we only need to look at one key, it is sufficient to compare the
 
996
     keyid so that we don't need to look at "fpr" records. */
 
997
  for (;;)
 
998
    {
 
999
      char *p;
 
1000
      char *fields[6];
 
1001
      int nfields;
 
1002
      size_t max_length;
 
1003
      gcry_mpi_t mpi;
 
1004
      int i;
 
1005
 
 
1006
      max_length = 4096;
 
1007
      i = read_line (fp, &line, &line_size, &max_length);
 
1008
      if (!i)
 
1009
        break; /* EOF. */
 
1010
      if (i < 0)
 
1011
        {
 
1012
          err = gpg_error_from_syserror ();
 
1013
          goto leave; /* Error. */
 
1014
        }
 
1015
      if (!max_length)
 
1016
        {
 
1017
          err = gpg_error (GPG_ERR_TRUNCATED);
 
1018
          goto leave;  /* Line truncated - we better stop processing.  */
 
1019
        }
 
1020
 
 
1021
      /* Parse the line into fields. */
 
1022
      for (nfields=0, p=line; p && nfields < DIM (fields); nfields++)
 
1023
        {
 
1024
          fields[nfields] = p;
 
1025
          p = strchr (p, ':');
 
1026
          if (p)
 
1027
            *(p++) = 0;
 
1028
        }
 
1029
      if (!nfields)
 
1030
        continue; /* No fields at all - skip line.  */
 
1031
 
 
1032
      if (!found_key)
 
1033
        {
 
1034
          if ( (!strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
 
1035
               && nfields > 4 && !strcmp (fields[4], hexkeyid))
 
1036
            found_key = 1;
 
1037
          continue;
 
1038
        }
 
1039
      
 
1040
      if ( !strcmp (fields[0], "sub") || !strcmp (fields[0], "pub") )
 
1041
        break; /* Next key - stop.  */
 
1042
 
 
1043
      if ( strcmp (fields[0], "pkd") )
 
1044
        continue; /* Not a key data record.  */
 
1045
      i = 0; /* Avoid erroneous compiler warning. */
 
1046
      if ( nfields < 4 || (i = atoi (fields[1])) < 0 || i > 1
 
1047
           || (!i && m_new) || (i && e_new))
 
1048
        {
 
1049
          err = gpg_error (GPG_ERR_GENERAL);
 
1050
          goto leave; /* Error: Invalid key data record or not an RSA key.  */
 
1051
        }
 
1052
      
 
1053
      err = gcry_mpi_scan (&mpi, GCRYMPI_FMT_HEX, fields[3], 0, NULL);
 
1054
      if (err)
 
1055
        mpi = NULL;
 
1056
      else if (!i)
 
1057
        err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &m_new, &m_new_n, mpi);
 
1058
      else
 
1059
        err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &e_new, &e_new_n, mpi);
 
1060
      gcry_mpi_release (mpi);
 
1061
      if (err)
 
1062
        goto leave;
 
1063
    }
 
1064
  
 
1065
  if (m_new && e_new)
 
1066
    {
 
1067
      *m = m_new;
 
1068
      *mlen = m_new_n;
 
1069
      m_new = NULL;
 
1070
      *e = e_new;
 
1071
      *elen = e_new_n;
 
1072
      e_new = NULL;
 
1073
    }
 
1074
  else
 
1075
    err = gpg_error (GPG_ERR_GENERAL);
 
1076
 
 
1077
 leave:
 
1078
  xfree (m_new);
 
1079
  xfree (e_new);
 
1080
  xfree (line);
 
1081
  return err;
 
1082
}
 
1083
#endif /*GNUPG_MAJOR_VERSION > 1*/
 
1084
 
 
1085
 
 
1086
/* Get the public key for KEYNO and store it as an S-expresion with
 
1087
   the APP handle.  On error that field gets cleared.  If we already
 
1088
   know about the public key we will just return.  Note that this does
 
1089
   not mean a key is available; this is soley indicated by the
 
1090
   presence of the app->app_local->pk[KEYNO-1].key field.
 
1091
 
 
1092
   Note that GnuPG 1.x does not need this and it would be too time
 
1093
   consuming to send it just for the fun of it. However, given that we
 
1094
   use the same code in gpg 1.4, we can't use the gcry S-expresion
 
1095
   here but need to open encode it. */
 
1096
#if GNUPG_MAJOR_VERSION > 1
 
1097
static gpg_error_t
 
1098
get_public_key (app_t app, int keyno)
 
1099
{
 
1100
  gpg_error_t err = 0;
 
1101
  unsigned char *buffer;
 
1102
  const unsigned char *keydata, *m, *e;
 
1103
  size_t buflen, keydatalen, mlen, elen;
 
1104
  unsigned char *mbuf = NULL;
 
1105
  unsigned char *ebuf = NULL;
 
1106
  char *keybuf = NULL;
 
1107
  char *keybuf_p;
 
1108
 
 
1109
  if (keyno < 1 || keyno > 3)
 
1110
    return gpg_error (GPG_ERR_INV_ID);
 
1111
  keyno--;
 
1112
 
 
1113
  /* Already cached? */
 
1114
  if (app->app_local->pk[keyno].read_done)
 
1115
    return 0;
 
1116
 
 
1117
  xfree (app->app_local->pk[keyno].key);
 
1118
  app->app_local->pk[keyno].key = NULL;
 
1119
  app->app_local->pk[keyno].keylen = 0;
 
1120
 
 
1121
  m = e = NULL; /* (avoid cc warning) */
 
1122
 
 
1123
  if (app->card_version > 0x0100)
 
1124
    {
 
1125
      int exmode, le_value;
 
1126
 
 
1127
      /* We may simply read the public key out of these cards.  */
 
1128
      if (app->app_local->cardcap.ext_lc_le)
 
1129
        {
 
1130
          exmode = 1;    /* Use extended length.  */
 
1131
          le_value = app->app_local->extcap.max_rsp_data;
 
1132
        }
 
1133
      else
 
1134
        {
 
1135
          exmode = 0;
 
1136
          le_value = 256; /* Use legacy value. */
 
1137
        }
 
1138
 
 
1139
      err = iso7816_read_public_key 
 
1140
        (app->slot, exmode,
 
1141
         (const unsigned char*)(keyno == 0? "\xB6" :
 
1142
                                keyno == 1? "\xB8" : "\xA4"), 2,  
 
1143
         le_value,
 
1144
         &buffer, &buflen);
 
1145
      if (err)
 
1146
        {
 
1147
          log_error (_("reading public key failed: %s\n"), gpg_strerror (err));
 
1148
          goto leave;
 
1149
        }
 
1150
 
 
1151
      keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
 
1152
      if (!keydata)
 
1153
        {
 
1154
          err = gpg_error (GPG_ERR_CARD);
 
1155
          log_error (_("response does not contain the public key data\n"));
 
1156
          goto leave;
 
1157
        }
 
1158
 
 
1159
      m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
 
1160
      if (!m)
 
1161
        {
 
1162
          err = gpg_error (GPG_ERR_CARD);
 
1163
          log_error (_("response does not contain the RSA modulus\n"));
 
1164
          goto leave;
 
1165
        }
 
1166
      
 
1167
 
 
1168
      e = find_tlv (keydata, keydatalen, 0x0082, &elen);
 
1169
      if (!e)
 
1170
        {
 
1171
          err = gpg_error (GPG_ERR_CARD);
 
1172
          log_error (_("response does not contain the RSA public exponent\n"));
 
1173
          goto leave;
 
1174
        }
 
1175
 
 
1176
      /* Prepend numbers with a 0 if needed.  */
 
1177
      if (mlen && (*m & 0x80))
 
1178
        {
 
1179
          mbuf = xtrymalloc ( mlen + 1);
 
1180
          if (!mbuf)
 
1181
            {
 
1182
              err = gpg_error_from_syserror ();
 
1183
              goto leave;
 
1184
            }
 
1185
          *mbuf = 0;
 
1186
          memcpy (mbuf+1, m, mlen);
 
1187
          mlen++;
 
1188
          m = mbuf;
 
1189
        }
 
1190
      if (elen && (*e & 0x80))
 
1191
        {
 
1192
          ebuf = xtrymalloc ( elen + 1);
 
1193
          if (!ebuf)
 
1194
            {
 
1195
              err = gpg_error_from_syserror ();
 
1196
              goto leave;
 
1197
            }
 
1198
          *ebuf = 0;
 
1199
          memcpy (ebuf+1, e, elen);
 
1200
          elen++;
 
1201
          e = ebuf;
 
1202
        }
 
1203
 
 
1204
    }
 
1205
  else
 
1206
    {
 
1207
      /* Due to a design problem in v1.0 cards we can't get the public
 
1208
         key out of these cards without doing a verify on CHV3.
 
1209
         Clearly that is not an option and thus we try to locate the
 
1210
         key using an external helper.
 
1211
 
 
1212
         The helper we use here is gpg itself, which should know about
 
1213
         the key in any case.  */
 
1214
 
 
1215
      char fpr[41];
 
1216
      char *hexkeyid;
 
1217
      char *command = NULL;
 
1218
      FILE *fp;
 
1219
      int ret;
 
1220
 
 
1221
      buffer = NULL; /* We don't need buffer.  */
 
1222
 
 
1223
      err = retrieve_fpr_from_card (app, keyno, fpr);
 
1224
      if (err)
 
1225
        {
 
1226
          log_error ("error while retrieving fpr from card: %s\n",
 
1227
                     gpg_strerror (err));
 
1228
          goto leave;
 
1229
        }
 
1230
      hexkeyid = fpr + 24;
 
1231
 
 
1232
      ret = estream_asprintf (&command,
 
1233
                              "gpg --list-keys --with-colons --with-key-data '%s'",
 
1234
                              fpr);
 
1235
      if (ret < 0)
 
1236
        {
 
1237
          err = gpg_error_from_syserror ();
 
1238
          goto leave;
 
1239
        }
 
1240
 
 
1241
      fp = popen (command, "r");
 
1242
      xfree (command);
 
1243
      if (!fp)
 
1244
        {
 
1245
          err = gpg_error_from_syserror ();
 
1246
          log_error ("running gpg failed: %s\n", gpg_strerror (err));
 
1247
          goto leave;
 
1248
        }
 
1249
 
 
1250
      err = retrieve_key_material (fp, hexkeyid, &m, &mlen, &e, &elen);
 
1251
      fclose (fp);
 
1252
      if (err)
 
1253
        {
 
1254
          log_error ("error while retrieving key material through pipe: %s\n",
 
1255
                     gpg_strerror (err));
 
1256
          goto leave;
 
1257
        }
 
1258
    }
 
1259
 
 
1260
  /* Allocate a buffer to construct the S-expression.  */
 
1261
  /* FIXME: We should provide a generalized S-expression creation
 
1262
     mechanism. */
 
1263
  keybuf = xtrymalloc (50 + 2*35 + mlen + elen + 1);
 
1264
  if (!keybuf)
 
1265
    {
 
1266
      err = gpg_error_from_syserror ();
 
1267
      goto leave;
 
1268
    }
 
1269
  
 
1270
  sprintf (keybuf, "(10:public-key(3:rsa(1:n%u:", (unsigned int) mlen);
 
1271
  keybuf_p = keybuf + strlen (keybuf);
 
1272
  memcpy (keybuf_p, m, mlen);
 
1273
  keybuf_p += mlen;
 
1274
  sprintf (keybuf_p, ")(1:e%u:", (unsigned int)elen);
 
1275
  keybuf_p += strlen (keybuf_p);
 
1276
  memcpy (keybuf_p, e, elen);
 
1277
  keybuf_p += elen;
 
1278
  strcpy (keybuf_p, ")))");
 
1279
  keybuf_p += strlen (keybuf_p);
 
1280
  
 
1281
  app->app_local->pk[keyno].key = (unsigned char*)keybuf;
 
1282
  app->app_local->pk[keyno].keylen = (keybuf_p - keybuf);
 
1283
 
 
1284
 leave:
 
1285
  /* Set a flag to indicate that we tried to read the key.  */
 
1286
  app->app_local->pk[keyno].read_done = 1;
 
1287
 
 
1288
  xfree (buffer);
 
1289
  xfree (mbuf);
 
1290
  xfree (ebuf);
 
1291
  return 0;
 
1292
}
 
1293
#endif /* GNUPG_MAJOR_VERSION > 1 */
 
1294
 
 
1295
 
 
1296
 
 
1297
/* Send the KEYPAIRINFO back. KEYNO needs to be in the range [1,3].
 
1298
   This is used by the LEARN command. */
 
1299
static gpg_error_t
 
1300
send_keypair_info (app_t app, ctrl_t ctrl, int keyno)
 
1301
{
 
1302
  gpg_error_t err = 0;
 
1303
  /* Note that GnuPG 1.x does not need this and it would be too time
 
1304
     consuming to send it just for the fun of it. */
 
1305
#if GNUPG_MAJOR_VERSION > 1
 
1306
  unsigned char grip[20];
 
1307
  char gripstr[41];
 
1308
  char idbuf[50];
 
1309
 
 
1310
  err = get_public_key (app, keyno);
 
1311
  if (err)
 
1312
    goto leave;
 
1313
  
 
1314
  assert (keyno >= 1 && keyno <= 3);
 
1315
  if (!app->app_local->pk[keyno-1].key)
 
1316
    goto leave; /* No such key - ignore. */
 
1317
 
 
1318
  err = keygrip_from_canon_sexp (app->app_local->pk[keyno-1].key,
 
1319
                                 app->app_local->pk[keyno-1].keylen,
 
1320
                                 grip);
 
1321
  if (err)
 
1322
    goto leave;
 
1323
  
 
1324
  bin2hex (grip, 20, gripstr);
 
1325
 
 
1326
  sprintf (idbuf, "OPENPGP.%d", keyno);
 
1327
  send_status_info (ctrl, "KEYPAIRINFO", 
 
1328
                    gripstr, 40, 
 
1329
                    idbuf, strlen (idbuf), 
 
1330
                    NULL, (size_t)0);
 
1331
 
 
1332
 leave:
 
1333
#endif /* GNUPG_MAJOR_VERSION > 1 */
 
1334
 
 
1335
  return err; 
 
1336
}
 
1337
 
 
1338
 
 
1339
/* Handle the LEARN command for OpenPGP.  */
 
1340
static gpg_error_t
 
1341
do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
 
1342
{
 
1343
  (void)flags;
 
1344
  
 
1345
  do_getattr (app, ctrl, "EXTCAP");
 
1346
  do_getattr (app, ctrl, "DISP-NAME");
 
1347
  do_getattr (app, ctrl, "DISP-LANG");
 
1348
  do_getattr (app, ctrl, "DISP-SEX");
 
1349
  do_getattr (app, ctrl, "PUBKEY-URL");
 
1350
  do_getattr (app, ctrl, "LOGIN-DATA");
 
1351
  do_getattr (app, ctrl, "KEY-FPR");
 
1352
  if (app->card_version > 0x0100)
 
1353
    do_getattr (app, ctrl, "KEY-TIME");
 
1354
  do_getattr (app, ctrl, "CA-FPR");
 
1355
  do_getattr (app, ctrl, "CHV-STATUS");
 
1356
  do_getattr (app, ctrl, "SIG-COUNTER");
 
1357
  if (app->app_local->extcap.private_dos)
 
1358
    {
 
1359
      do_getattr (app, ctrl, "PRIVATE-DO-1");
 
1360
      do_getattr (app, ctrl, "PRIVATE-DO-2");
 
1361
      if (app->did_chv2)
 
1362
        do_getattr (app, ctrl, "PRIVATE-DO-3");
 
1363
      if (app->did_chv3)
 
1364
        do_getattr (app, ctrl, "PRIVATE-DO-4");
 
1365
    }
 
1366
  send_keypair_info (app, ctrl, 1);
 
1367
  send_keypair_info (app, ctrl, 2);
 
1368
  send_keypair_info (app, ctrl, 3);
 
1369
  /* Note: We do not send the Cardholder Certificate, because that is
 
1370
     relativly long and for OpenPGP applications not really needed.  */
 
1371
  return 0;
 
1372
}
 
1373
 
 
1374
 
 
1375
/* Handle the READKEY command for OpenPGP.  On success a canonical
 
1376
   encoded S-expression with the public key will get stored at PK and
 
1377
   its length (for assertions) at PKLEN; the caller must release that
 
1378
   buffer. On error PK and PKLEN are not changed and an error code is
 
1379
   returned.  */
 
1380
static gpg_error_t
 
1381
do_readkey (app_t app, const char *keyid, unsigned char **pk, size_t *pklen)
 
1382
{
 
1383
#if GNUPG_MAJOR_VERSION > 1
 
1384
  gpg_error_t err;
 
1385
  int keyno;
 
1386
  unsigned char *buf;
 
1387
 
 
1388
  if (!strcmp (keyid, "OPENPGP.1"))
 
1389
    keyno = 1;
 
1390
  else if (!strcmp (keyid, "OPENPGP.2"))
 
1391
    keyno = 2;
 
1392
  else if (!strcmp (keyid, "OPENPGP.3"))
 
1393
    keyno = 3;
 
1394
  else
 
1395
    return gpg_error (GPG_ERR_INV_ID);
 
1396
 
 
1397
  err = get_public_key (app, keyno);
 
1398
  if (err)
 
1399
    return err;
 
1400
 
 
1401
  buf = app->app_local->pk[keyno-1].key;
 
1402
  if (!buf)
 
1403
    return gpg_error (GPG_ERR_NO_PUBKEY);
 
1404
  *pklen = app->app_local->pk[keyno-1].keylen;;
 
1405
  *pk = xtrymalloc (*pklen);
 
1406
  if (!*pk)
 
1407
    {
 
1408
      err = gpg_error_from_syserror ();
 
1409
      *pklen = 0;
 
1410
      return err;
 
1411
    }
 
1412
  memcpy (*pk, buf, *pklen);
 
1413
  return 0;
 
1414
#else
 
1415
  return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
 
1416
#endif
 
1417
}
 
1418
 
 
1419
/* Read the standard certificate of an OpenPGP v2 card.  It is
 
1420
   returned in a freshly allocated buffer with that address stored at
 
1421
   CERT and the length of the certificate stored at CERTLEN.  CERTID
 
1422
   needs to be set to "OPENPGP.3".  */
 
1423
static gpg_error_t
 
1424
do_readcert (app_t app, const char *certid,
 
1425
             unsigned char **cert, size_t *certlen)
 
1426
{
 
1427
#if GNUPG_MAJOR_VERSION > 1
 
1428
  gpg_error_t err;
 
1429
  unsigned char *buffer;
 
1430
  size_t buflen;
 
1431
  void *relptr;
 
1432
 
 
1433
  *cert = NULL;
 
1434
  *certlen = 0;
 
1435
  if (strcmp (certid, "OPENPGP.3"))
 
1436
    return gpg_error (GPG_ERR_INV_ID);
 
1437
  if (!app->app_local->extcap.is_v2)
 
1438
    return gpg_error (GPG_ERR_NOT_FOUND);
 
1439
 
 
1440
  relptr = get_one_do (app, 0x7F21, &buffer, &buflen, NULL);
 
1441
  if (!relptr)
 
1442
    return gpg_error (GPG_ERR_NOT_FOUND);
 
1443
 
 
1444
  if (!buflen)
 
1445
    err = gpg_error (GPG_ERR_NOT_FOUND);
 
1446
  else if (!(*cert = xtrymalloc (buflen)))
 
1447
    err = gpg_error_from_syserror ();
 
1448
  else
 
1449
    {
 
1450
      memcpy (*cert, buffer, buflen);
 
1451
      *certlen = buflen;
 
1452
      err  = 0;
 
1453
    }
 
1454
  xfree (relptr);
 
1455
  return err;
 
1456
#else
 
1457
  return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
 
1458
#endif
 
1459
}
 
1460
 
 
1461
 
 
1462
/* Verify a CHV either using using the pinentry or if possibile by
 
1463
   using a keypad.  PINCB and PINCB_ARG describe the usual callback
 
1464
   for the pinentry.  CHVNO must be either 1 or 2. SIGCOUNT is only
 
1465
   used with CHV1.  PINVALUE is the address of a pointer which will
 
1466
   receive a newly allocated block with the actual PIN (this is useful
 
1467
   in case that PIN shall be used for another verify operation).  The
 
1468
   caller needs to free this value.  If the function returns with
 
1469
   success and NULL is stored at PINVALUE, the caller should take this
 
1470
   as an indication that the keypad has been used.
 
1471
   */
 
1472
static gpg_error_t
 
1473
verify_a_chv (app_t app,
 
1474
              gpg_error_t (*pincb)(void*, const char *, char **),
 
1475
              void *pincb_arg,
 
1476
              int chvno, unsigned long sigcount, char **pinvalue)
 
1477
{
 
1478
  int rc = 0;
 
1479
  char *prompt_buffer = NULL;
 
1480
  const char *prompt;
 
1481
  iso7816_pininfo_t pininfo;
 
1482
  int minlen = 6;
 
1483
 
 
1484
  assert (chvno == 1 || chvno == 2);
 
1485
 
 
1486
  *pinvalue = NULL;
 
1487
 
 
1488
  if (chvno == 2 && app->app_local->flags.def_chv2)
 
1489
    {
 
1490
      /* Special case for def_chv2 mechanism. */
 
1491
      if (opt.verbose)
 
1492
        log_info (_("using default PIN as %s\n"), "CHV2");
 
1493
      rc = iso7816_verify (app->slot, 0x82, "123456", 6);
 
1494
      if (rc)
 
1495
        {
 
1496
          /* Verification of CHV2 with the default PIN failed,
 
1497
             although the card pretends to have the default PIN set as
 
1498
             CHV2.  We better disable the def_chv2 flag now. */
 
1499
          log_info (_("failed to use default PIN as %s: %s"
 
1500
                      " - disabling further default use\n"),
 
1501
                    "CHV2", gpg_strerror (rc));
 
1502
          app->app_local->flags.def_chv2 = 0;
 
1503
        }
 
1504
      return rc;
 
1505
    }
 
1506
 
 
1507
  memset (&pininfo, 0, sizeof pininfo);
 
1508
  pininfo.mode = 1;
 
1509
  pininfo.minlen = minlen;
 
1510
 
 
1511
 
 
1512
  if (chvno == 1)
 
1513
    {
 
1514
#define PROMPTSTRING  _("||Please enter the PIN%%0A[sigs done: %lu]")
 
1515
      size_t promptsize = strlen (PROMPTSTRING) + 50;
 
1516
 
 
1517
      prompt_buffer = xtrymalloc (promptsize);
 
1518
      if (!prompt_buffer)
 
1519
        return gpg_error_from_syserror ();
 
1520
      snprintf (prompt_buffer, promptsize-1, PROMPTSTRING, sigcount);
 
1521
      prompt = prompt_buffer;
 
1522
#undef PROMPTSTRING
 
1523
    }
 
1524
  else
 
1525
    prompt = _("||Please enter the PIN");
 
1526
 
 
1527
  
 
1528
  if (!opt.disable_keypad
 
1529
      && !iso7816_check_keypad (app->slot, ISO7816_VERIFY, &pininfo) )
 
1530
    {
 
1531
      /* The reader supports the verify command through the keypad.
 
1532
         Note that the pincb appends a text to the prompt telling the
 
1533
         user to use the keypad. */
 
1534
      rc = pincb (pincb_arg, prompt, NULL); 
 
1535
      prompt = NULL;
 
1536
      xfree (prompt_buffer); 
 
1537
      prompt_buffer = NULL;
 
1538
      if (rc)
 
1539
        {
 
1540
          log_info (_("PIN callback returned error: %s\n"),
 
1541
                    gpg_strerror (rc));
 
1542
          return rc;
 
1543
        }
 
1544
      rc = iso7816_verify_kp (app->slot, 0x80+chvno, "", 0, &pininfo); 
 
1545
      /* Dismiss the prompt. */
 
1546
      pincb (pincb_arg, NULL, NULL);
 
1547
 
 
1548
      assert (!*pinvalue);
 
1549
    }
 
1550
  else
 
1551
    {
 
1552
      /* The reader has no keypad or we don't want to use it. */
 
1553
      rc = pincb (pincb_arg, prompt, pinvalue); 
 
1554
      prompt = NULL;
 
1555
      xfree (prompt_buffer); 
 
1556
      prompt_buffer = NULL;
 
1557
      if (rc)
 
1558
        {
 
1559
          log_info (_("PIN callback returned error: %s\n"),
 
1560
                    gpg_strerror (rc));
 
1561
          return rc;
 
1562
        }
 
1563
      
 
1564
      if (strlen (*pinvalue) < minlen)
 
1565
        {
 
1566
          log_error (_("PIN for CHV%d is too short;"
 
1567
                       " minimum length is %d\n"), chvno, minlen);
 
1568
          xfree (*pinvalue);
 
1569
          *pinvalue = NULL;
 
1570
          return gpg_error (GPG_ERR_BAD_PIN);
 
1571
        }
 
1572
 
 
1573
      rc = iso7816_verify (app->slot, 0x80+chvno,
 
1574
                           *pinvalue, strlen (*pinvalue));
 
1575
    }
 
1576
  
 
1577
  if (rc)
 
1578
    {
 
1579
      log_error (_("verify CHV%d failed: %s\n"), chvno, gpg_strerror (rc));
 
1580
      xfree (*pinvalue);
 
1581
      *pinvalue = NULL;
 
1582
      flush_cache_after_error (app);
 
1583
    }
 
1584
 
 
1585
  return rc;
 
1586
}
 
1587
 
 
1588
 
 
1589
/* Verify CHV2 if required.  Depending on the configuration of the
 
1590
   card CHV1 will also be verified. */
 
1591
static gpg_error_t
 
1592
verify_chv2 (app_t app,
 
1593
             gpg_error_t (*pincb)(void*, const char *, char **),
 
1594
             void *pincb_arg)
 
1595
{
 
1596
  int rc;
 
1597
  char *pinvalue;
 
1598
 
 
1599
  if (app->did_chv2) 
 
1600
    return 0;  /* We already verified CHV2.  */
 
1601
 
 
1602
  rc = verify_a_chv (app, pincb, pincb_arg, 2, 0, &pinvalue);
 
1603
  if (rc)
 
1604
    return rc;
 
1605
  app->did_chv2 = 1;
 
1606
  
 
1607
  if (!app->did_chv1 && !app->force_chv1 && pinvalue)
 
1608
    {
 
1609
      /* For convenience we verify CHV1 here too.  We do this only if
 
1610
         the card is not configured to require a verification before
 
1611
         each CHV1 controlled operation (force_chv1) and if we are not
 
1612
         using the keypad (PINVALUE == NULL). */
 
1613
      rc = iso7816_verify (app->slot, 0x81, pinvalue, strlen (pinvalue));
 
1614
      if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
 
1615
        rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
 
1616
      if (rc)
 
1617
        {
 
1618
          log_error (_("verify CHV%d failed: %s\n"), 1, gpg_strerror (rc));
 
1619
          flush_cache_after_error (app);
 
1620
        }
 
1621
      else
 
1622
        app->did_chv1 = 1;
 
1623
    }
 
1624
 
 
1625
  xfree (pinvalue);
 
1626
 
 
1627
  return rc;
 
1628
}
 
1629
 
 
1630
 
 
1631
/* Build the prompt to enter the Admin PIN.  The prompt depends on the
 
1632
   current sdtate of the card.  */
 
1633
static gpg_error_t 
 
1634
build_enter_admin_pin_prompt (app_t app, char **r_prompt)
 
1635
{
 
1636
  void *relptr;
 
1637
  unsigned char *value;
 
1638
  size_t valuelen;
 
1639
  int remaining;
 
1640
  char *prompt;
 
1641
 
 
1642
  *r_prompt = NULL;
 
1643
 
 
1644
  relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
 
1645
  if (!relptr || valuelen < 7)
 
1646
    {
 
1647
      log_error (_("error retrieving CHV status from card\n"));
 
1648
      xfree (relptr);
 
1649
      return gpg_error (GPG_ERR_CARD);
 
1650
    }
 
1651
  if (value[6] == 0)
 
1652
    {
 
1653
      log_info (_("card is permanently locked!\n"));
 
1654
      xfree (relptr);
 
1655
      return gpg_error (GPG_ERR_BAD_PIN);
 
1656
    }
 
1657
  remaining = value[6];
 
1658
  xfree (relptr);
 
1659
  
 
1660
  log_info(_("%d Admin PIN attempts remaining before card"
 
1661
             " is permanently locked\n"), remaining);
 
1662
 
 
1663
  if (remaining < 3)
 
1664
    {
 
1665
      /* TRANSLATORS: Do not translate the "|A|" prefix but keep it at
 
1666
         the start of the string.  Use %%0A to force a linefeed.  */
 
1667
      prompt = xtryasprintf (_("|A|Please enter the Admin PIN%%0A"
 
1668
                               "[remaining attempts: %d]"), remaining);
 
1669
    }
 
1670
  else
 
1671
    prompt = xtrystrdup (_("|A|Please enter the Admin PIN"));
 
1672
  
 
1673
  if (!prompt)
 
1674
    return gpg_error_from_syserror ();
 
1675
  
 
1676
  *r_prompt = prompt;
 
1677
  return 0;
 
1678
}
 
1679
 
 
1680
 
 
1681
/* Verify CHV3 if required. */
 
1682
static gpg_error_t
 
1683
verify_chv3 (app_t app,
 
1684
             gpg_error_t (*pincb)(void*, const char *, char **),
 
1685
             void *pincb_arg)
 
1686
{
 
1687
  int rc = 0;
 
1688
 
 
1689
#if GNUPG_MAJOR_VERSION != 1
 
1690
  if (!opt.allow_admin)
 
1691
    {
 
1692
      log_info (_("access to admin commands is not configured\n"));
 
1693
      return gpg_error (GPG_ERR_EACCES);
 
1694
    }
 
1695
#endif
 
1696
      
 
1697
  if (!app->did_chv3) 
 
1698
    {
 
1699
      iso7816_pininfo_t pininfo;
 
1700
      int minlen = 8;
 
1701
      char *prompt;
 
1702
 
 
1703
      memset (&pininfo, 0, sizeof pininfo);
 
1704
      pininfo.mode = 1;
 
1705
      pininfo.minlen = minlen;
 
1706
 
 
1707
      rc = build_enter_admin_pin_prompt (app, &prompt);
 
1708
      if (rc)
 
1709
        return rc;
 
1710
 
 
1711
      if (!opt.disable_keypad
 
1712
          && !iso7816_check_keypad (app->slot, ISO7816_VERIFY, &pininfo) )
 
1713
        {
 
1714
          /* The reader supports the verify command through the keypad. */
 
1715
          rc = pincb (pincb_arg, prompt, NULL); 
 
1716
          xfree (prompt);
 
1717
          prompt = NULL;
 
1718
          if (rc)
 
1719
            {
 
1720
              log_info (_("PIN callback returned error: %s\n"),
 
1721
                        gpg_strerror (rc));
 
1722
              return rc;
 
1723
            }
 
1724
          rc = iso7816_verify_kp (app->slot, 0x83, "", 0, &pininfo); 
 
1725
          /* Dismiss the prompt. */
 
1726
          pincb (pincb_arg, NULL, NULL);
 
1727
        }
 
1728
      else
 
1729
        {
 
1730
          char *pinvalue;
 
1731
 
 
1732
          rc = pincb (pincb_arg, prompt, &pinvalue); 
 
1733
          xfree (prompt);
 
1734
          prompt = NULL;
 
1735
          if (rc)
 
1736
            {
 
1737
              log_info (_("PIN callback returned error: %s\n"),
 
1738
                        gpg_strerror (rc));
 
1739
              return rc;
 
1740
            }
 
1741
          
 
1742
          if (strlen (pinvalue) < minlen)
 
1743
            {
 
1744
              log_error (_("PIN for CHV%d is too short;"
 
1745
                           " minimum length is %d\n"), 3, minlen);
 
1746
              xfree (pinvalue);
 
1747
              return gpg_error (GPG_ERR_BAD_PIN);
 
1748
            }
 
1749
          
 
1750
          rc = iso7816_verify (app->slot, 0x83, pinvalue, strlen (pinvalue));
 
1751
          xfree (pinvalue);
 
1752
        }
 
1753
      
 
1754
      if (rc)
 
1755
        {
 
1756
          log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
 
1757
          flush_cache_after_error (app);
 
1758
          return rc;
 
1759
        }
 
1760
      app->did_chv3 = 1;
 
1761
    }
 
1762
  return rc;
 
1763
}
 
1764
 
 
1765
 
 
1766
/* Handle the SETATTR operation. All arguments are already basically
 
1767
   checked. */
 
1768
static gpg_error_t 
 
1769
do_setattr (app_t app, const char *name,
 
1770
            gpg_error_t (*pincb)(void*, const char *, char **),
 
1771
            void *pincb_arg,
 
1772
            const unsigned char *value, size_t valuelen)
 
1773
{
 
1774
  gpg_error_t rc;
 
1775
  int idx;
 
1776
  static struct {
 
1777
    const char *name;
 
1778
    int tag;
 
1779
    int need_chv;
 
1780
    int special;
 
1781
    unsigned int need_v2:1;
 
1782
  } table[] = {
 
1783
    { "DISP-NAME",    0x005B, 3 },
 
1784
    { "LOGIN-DATA",   0x005E, 3, 2 },
 
1785
    { "DISP-LANG",    0x5F2D, 3 },
 
1786
    { "DISP-SEX",     0x5F35, 3 },
 
1787
    { "PUBKEY-URL",   0x5F50, 3 },
 
1788
    { "CHV-STATUS-1", 0x00C4, 3, 1 },
 
1789
    { "CA-FPR-1",     0x00CA, 3 },
 
1790
    { "CA-FPR-2",     0x00CB, 3 },
 
1791
    { "CA-FPR-3",     0x00CC, 3 },
 
1792
    { "PRIVATE-DO-1", 0x0101, 2 },
 
1793
    { "PRIVATE-DO-2", 0x0102, 3 },
 
1794
    { "PRIVATE-DO-3", 0x0103, 2 },
 
1795
    { "PRIVATE-DO-4", 0x0104, 3 },
 
1796
    { "CERT-3",       0x7F21, 3, 0, 1 },
 
1797
    { "SM-KEY-ENC",   0x00D1, 3, 0, 1 },
 
1798
    { "SM-KEY-MAC",   0x00D2, 3, 0, 1 },
 
1799
    { "KEY-ATTR",     0,      0, 3, 1 },
 
1800
    { NULL, 0 }
 
1801
  };
 
1802
  int exmode;
 
1803
 
 
1804
  for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
 
1805
    ;
 
1806
  if (!table[idx].name)
 
1807
    return gpg_error (GPG_ERR_INV_NAME); 
 
1808
  if (table[idx].need_v2 && !app->app_local->extcap.is_v2)
 
1809
    return gpg_error (GPG_ERR_NOT_SUPPORTED); /* Not yet supported.  */
 
1810
 
 
1811
  if (table[idx].special == 3)
 
1812
    return change_keyattr_from_string (app, pincb, pincb_arg, value, valuelen);
 
1813
 
 
1814
  switch (table[idx].need_chv)
 
1815
    {
 
1816
    case 2:
 
1817
      rc = verify_chv2 (app, pincb, pincb_arg);
 
1818
      break;
 
1819
    case 3:
 
1820
      rc = verify_chv3 (app, pincb, pincb_arg);
 
1821
      break;
 
1822
    default:
 
1823
      rc = 0;
 
1824
    }
 
1825
  if (rc)
 
1826
    return rc;
 
1827
 
 
1828
  /* Flush the cache before writing it, so that the next get operation
 
1829
     will reread the data from the card and thus get synced in case of
 
1830
     errors (e.g. data truncated by the card). */
 
1831
  flush_cache_item (app, table[idx].tag);
 
1832
 
 
1833
  if (app->app_local->cardcap.ext_lc_le && valuelen > 254)
 
1834
    exmode = 1;    /* Use extended length w/o a limit.  */
 
1835
  else if (app->app_local->cardcap.cmd_chaining && valuelen > 254)
 
1836
    exmode = -254; /* Command chaining with max. 254 bytes.  */
 
1837
  else
 
1838
    exmode = 0;
 
1839
  rc = iso7816_put_data (app->slot, exmode, table[idx].tag, value, valuelen);
 
1840
  if (rc)
 
1841
    log_error ("failed to set `%s': %s\n", table[idx].name, gpg_strerror (rc));
 
1842
 
 
1843
  if (table[idx].special == 1)
 
1844
    app->force_chv1 = (valuelen && *value == 0);
 
1845
  else if (table[idx].special == 2)
 
1846
    parse_login_data (app);
 
1847
 
 
1848
  return rc;
 
1849
}
 
1850
 
 
1851
 
 
1852
/* Handle the WRITECERT command for OpenPGP.  This rites the standard
 
1853
   certifciate to the card; CERTID needs to be set to "OPENPGP.3".
 
1854
   PINCB and PINCB_ARG are the usual arguments for the pinentry
 
1855
   callback.  */
 
1856
static gpg_error_t
 
1857
do_writecert (app_t app, ctrl_t ctrl,
 
1858
              const char *certidstr, 
 
1859
              gpg_error_t (*pincb)(void*, const char *, char **),
 
1860
              void *pincb_arg,
 
1861
              const unsigned char *certdata, size_t certdatalen)
 
1862
{
 
1863
  (void)ctrl;
 
1864
#if GNUPG_MAJOR_VERSION > 1
 
1865
  if (strcmp (certidstr, "OPENPGP.3"))
 
1866
    return gpg_error (GPG_ERR_INV_ID);
 
1867
  if (!certdata || !certdatalen)
 
1868
    return gpg_error (GPG_ERR_INV_ARG);
 
1869
  if (!app->app_local->extcap.is_v2)
 
1870
    return gpg_error (GPG_ERR_NOT_SUPPORTED);
 
1871
  if (certdatalen > app->app_local->extcap.max_certlen_3)
 
1872
    return gpg_error (GPG_ERR_TOO_LARGE);
 
1873
  return do_setattr (app, "CERT-3", pincb, pincb_arg, certdata, certdatalen);
 
1874
#else
 
1875
  return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
 
1876
#endif
 
1877
}
 
1878
 
 
1879
 
 
1880
 
 
1881
/* Handle the PASSWD command.  The following combinations are
 
1882
   possible:
 
1883
 
 
1884
    Flags  CHVNO Vers.  Description
 
1885
    RESET    1   1      Verify CHV3 and set a new CHV1 and CHV2
 
1886
    RESET    1   2      Verify PW3 and set a new PW1.
 
1887
    RESET    2   1      Verify CHV3 and set a new CHV1 and CHV2.
 
1888
    RESET    2   2      Verify PW3 and set a new Reset Code.
 
1889
    RESET    3   any    Returns GPG_ERR_INV_ID.
 
1890
     -       1   1      Verify CHV2 and set a new CHV1 and CHV2.
 
1891
     -       1   2      Verify PW1 and set a new PW1.
 
1892
     -       2   1      Verify CHV2 and set a new CHV1 and CHV2.
 
1893
     -       2   2      Verify Reset Code and set a new PW1.
 
1894
     -       3   any    Verify CHV3/PW3 and set a new CHV3/PW3.
 
1895
 */
 
1896
static gpg_error_t 
 
1897
do_change_pin (app_t app, ctrl_t ctrl,  const char *chvnostr, 
 
1898
               unsigned int flags,
 
1899
               gpg_error_t (*pincb)(void*, const char *, char **),
 
1900
               void *pincb_arg)
 
1901
{
 
1902
  int rc = 0;
 
1903
  int chvno = atoi (chvnostr);
 
1904
  char *resetcode = NULL;
 
1905
  char *oldpinvalue = NULL;
 
1906
  char *pinvalue;
 
1907
  int reset_mode = !!(flags & APP_CHANGE_FLAG_RESET);
 
1908
  int set_resetcode = 0;
 
1909
 
 
1910
  (void)ctrl;
 
1911
 
 
1912
  if (reset_mode && chvno == 3)
 
1913
    {
 
1914
      rc = gpg_error (GPG_ERR_INV_ID);
 
1915
      goto leave;
 
1916
    }
 
1917
 
 
1918
  if (!app->app_local->extcap.is_v2)
 
1919
    {
 
1920
      /* Version 1 cards.  */
 
1921
 
 
1922
      if (reset_mode || chvno == 3)
 
1923
        {
 
1924
          /* We always require that the PIN is entered. */
 
1925
          app->did_chv3 = 0;
 
1926
          rc = verify_chv3 (app, pincb, pincb_arg);
 
1927
          if (rc)
 
1928
            goto leave;
 
1929
        }
 
1930
      else if (chvno == 1 || chvno == 2)
 
1931
        {
 
1932
          /* On a v1.x card CHV1 and CVH2 should always have the same
 
1933
             value, thus we enforce it here.  */
 
1934
          int save_force = app->force_chv1;
 
1935
          
 
1936
          app->force_chv1 = 0;
 
1937
          app->did_chv1 = 0;
 
1938
          app->did_chv2 = 0;
 
1939
          rc = verify_chv2 (app, pincb, pincb_arg);
 
1940
          app->force_chv1 = save_force;
 
1941
          if (rc)
 
1942
            goto leave;
 
1943
        }
 
1944
      else
 
1945
        {
 
1946
          rc = gpg_error (GPG_ERR_INV_ID);
 
1947
          goto leave;
 
1948
        }
 
1949
    }
 
1950
  else
 
1951
    {
 
1952
      /* Version 2 cards.  */
 
1953
 
 
1954
      if (reset_mode)
 
1955
        {
 
1956
          /* To reset a PIN the Admin PIN is required. */
 
1957
          app->did_chv3 = 0;
 
1958
          rc = verify_chv3 (app, pincb, pincb_arg);
 
1959
          if (rc)
 
1960
            goto leave;
 
1961
          
 
1962
          if (chvno == 2)
 
1963
            set_resetcode = 1;
 
1964
        }
 
1965
      else if (chvno == 1 || chvno == 3)
 
1966
        {
 
1967
          int minlen = (chvno ==3)? 8 : 6;
 
1968
          char *promptbuf = NULL;
 
1969
          const char *prompt;
 
1970
 
 
1971
          if (chvno == 3)
 
1972
            {
 
1973
              rc = build_enter_admin_pin_prompt (app, &promptbuf);
 
1974
              if (rc)
 
1975
                goto leave;
 
1976
              prompt = promptbuf;
 
1977
            }
 
1978
          else
 
1979
            prompt = _("||Please enter the PIN");
 
1980
          rc = pincb (pincb_arg, prompt, &oldpinvalue);
 
1981
          xfree (promptbuf);
 
1982
          promptbuf = NULL;
 
1983
          if (rc)
 
1984
            {
 
1985
              log_info (_("PIN callback returned error: %s\n"),
 
1986
                        gpg_strerror (rc));
 
1987
              goto leave;
 
1988
            }
 
1989
 
 
1990
          if (strlen (oldpinvalue) < minlen)
 
1991
            {
 
1992
              log_info (_("PIN for CHV%d is too short;"
 
1993
                          " minimum length is %d\n"), chvno, minlen);
 
1994
              rc = gpg_error (GPG_ERR_BAD_PIN);
 
1995
              goto leave;
 
1996
            }
 
1997
        }
 
1998
      else if (chvno == 2)
 
1999
        {
 
2000
          /* There is no PW2 for v2 cards.  We use this condition to
 
2001
             allow a PW reset using the Reset Code.  */
 
2002
          void *relptr;
 
2003
          unsigned char *value;
 
2004
          size_t valuelen;
 
2005
          int remaining;
 
2006
          int minlen = 8;
 
2007
 
 
2008
          relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
 
2009
          if (!relptr || valuelen < 7)
 
2010
            {
 
2011
              log_error (_("error retrieving CHV status from card\n"));
 
2012
              xfree (relptr);
 
2013
              rc = gpg_error (GPG_ERR_CARD);
 
2014
              goto leave;
 
2015
            }
 
2016
          remaining = value[5];
 
2017
          xfree (relptr);
 
2018
          if (!remaining)
 
2019
            {
 
2020
              log_error (_("Reset Code not or not anymore available\n"));
 
2021
              rc = gpg_error (GPG_ERR_BAD_PIN);
 
2022
              goto leave;
 
2023
            }          
 
2024
          
 
2025
          rc = pincb (pincb_arg,
 
2026
                      _("||Please enter the Reset Code for the card"),
 
2027
                      &resetcode); 
 
2028
          if (rc)
 
2029
            {
 
2030
              log_info (_("PIN callback returned error: %s\n"), 
 
2031
                        gpg_strerror (rc));
 
2032
              goto leave;
 
2033
            }
 
2034
          if (strlen (resetcode) < minlen)
 
2035
            {
 
2036
              log_info (_("Reset Code is too short; minimum length is %d\n"),
 
2037
                        minlen);
 
2038
              rc = gpg_error (GPG_ERR_BAD_PIN);
 
2039
              goto leave;
 
2040
            }
 
2041
        }
 
2042
      else
 
2043
        {
 
2044
          rc = gpg_error (GPG_ERR_INV_ID);
 
2045
          goto leave;
 
2046
        }
 
2047
    }
 
2048
 
 
2049
  if (chvno == 3)
 
2050
    app->did_chv3 = 0;
 
2051
  else
 
2052
    app->did_chv1 = app->did_chv2 = 0;
 
2053
 
 
2054
  /* TRANSLATORS: Do not translate the "|*|" prefixes but
 
2055
     keep it at the start of the string.  We need this elsewhere
 
2056
     to get some infos on the string. */
 
2057
  rc = pincb (pincb_arg, 
 
2058
              set_resetcode? _("|RN|New Reset Code") :
 
2059
              chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"), 
 
2060
              &pinvalue); 
 
2061
  if (rc)
 
2062
    {
 
2063
      log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
 
2064
      goto leave;
 
2065
    }
 
2066
 
 
2067
 
 
2068
  if (resetcode)
 
2069
    {
 
2070
      char *buffer;
 
2071
 
 
2072
      buffer = xtrymalloc (strlen (resetcode) + strlen (pinvalue) + 1);
 
2073
      if (!buffer)
 
2074
        rc = gpg_error_from_syserror ();
 
2075
      else
 
2076
        {
 
2077
          strcpy (stpcpy (buffer, resetcode), pinvalue);
 
2078
          rc = iso7816_reset_retry_counter_with_rc (app->slot, 0x81,
 
2079
                                                    buffer, strlen (buffer));
 
2080
          wipememory (buffer, strlen (buffer));
 
2081
          xfree (buffer);
 
2082
        }
 
2083
    }
 
2084
  else if (set_resetcode)
 
2085
    {
 
2086
      if (strlen (pinvalue) < 8)
 
2087
        {
 
2088
          log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
 
2089
          rc = gpg_error (GPG_ERR_BAD_PIN);
 
2090
        }
 
2091
      else
 
2092
        rc = iso7816_put_data (app->slot, 0, 0xD3,
 
2093
                               pinvalue, strlen (pinvalue));
 
2094
    }
 
2095
  else if (reset_mode)
 
2096
    {
 
2097
      rc = iso7816_reset_retry_counter (app->slot, 0x81,
 
2098
                                        pinvalue, strlen (pinvalue));
 
2099
      if (!rc && !app->app_local->extcap.is_v2)
 
2100
        rc = iso7816_reset_retry_counter (app->slot, 0x82,
 
2101
                                          pinvalue, strlen (pinvalue));
 
2102
    }
 
2103
  else if (!app->app_local->extcap.is_v2)
 
2104
    {
 
2105
      /* Version 1 cards.  */
 
2106
      if (chvno == 1 || chvno == 2)
 
2107
        {
 
2108
          rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
 
2109
                                              pinvalue, strlen (pinvalue));
 
2110
          if (!rc)
 
2111
            rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
 
2112
                                                pinvalue, strlen (pinvalue));
 
2113
        }
 
2114
      else /* CHVNO == 3 */
 
2115
        {
 
2116
          rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
 
2117
                                              pinvalue, strlen (pinvalue));
 
2118
        }
 
2119
    }
 
2120
  else
 
2121
    {
 
2122
      /* Version 2 cards.  */
 
2123
      assert (chvno == 1 || chvno == 3);
 
2124
      
 
2125
      rc = iso7816_change_reference_data (app->slot, 0x80 + chvno,
 
2126
                                          oldpinvalue, strlen (oldpinvalue),
 
2127
                                          pinvalue, strlen (pinvalue));
 
2128
    }
 
2129
 
 
2130
  if (pinvalue)
 
2131
    {
 
2132
      wipememory (pinvalue, strlen (pinvalue));
 
2133
      xfree (pinvalue);
 
2134
    }
 
2135
  if (rc)
 
2136
    flush_cache_after_error (app);
 
2137
 
 
2138
 leave:
 
2139
  if (resetcode)
 
2140
    {
 
2141
      wipememory (resetcode, strlen (resetcode));
 
2142
      xfree (resetcode);
 
2143
    }
 
2144
  if (oldpinvalue)
 
2145
    {
 
2146
      wipememory (oldpinvalue, strlen (oldpinvalue));
 
2147
      xfree (oldpinvalue);
 
2148
    }
 
2149
  return rc;
 
2150
}
 
2151
 
 
2152
 
 
2153
/* Check whether a key already exists.  KEYIDX is the index of the key
 
2154
   (0..2).  If FORCE is TRUE a diagnositic will be printed but no
 
2155
   error returned if the key already exists.  The flag GENERATING is
 
2156
   only used to print correct messages. */
 
2157
static gpg_error_t
 
2158
does_key_exist (app_t app, int keyidx, int generating, int force)
 
2159
{
 
2160
  const unsigned char *fpr;
 
2161
  unsigned char *buffer;
 
2162
  size_t buflen, n;
 
2163
  int i;
 
2164
 
 
2165
  assert (keyidx >=0 && keyidx <= 2);
 
2166
 
 
2167
  if (iso7816_get_data (app->slot, 0, 0x006E, &buffer, &buflen))
 
2168
    {
 
2169
      log_error (_("error reading application data\n"));
 
2170
      return gpg_error (GPG_ERR_GENERAL);
 
2171
    }
 
2172
  fpr = find_tlv (buffer, buflen, 0x00C5, &n);
 
2173
  if (!fpr || n < 60)
 
2174
    {
 
2175
      log_error (_("error reading fingerprint DO\n"));
 
2176
      xfree (buffer);
 
2177
      return gpg_error (GPG_ERR_GENERAL);
 
2178
    }
 
2179
  fpr += 20*keyidx;
 
2180
  for (i=0; i < 20 && !fpr[i]; i++)
 
2181
    ;
 
2182
  xfree (buffer);
 
2183
  if (i!=20 && !force)
 
2184
    {
 
2185
      log_error (_("key already exists\n"));
 
2186
      return gpg_error (GPG_ERR_EEXIST);
 
2187
    }
 
2188
  else if (i!=20)
 
2189
    log_info (_("existing key will be replaced\n"));
 
2190
  else if (generating)
 
2191
    log_info (_("generating new key\n"));
 
2192
  else
 
2193
    log_info (_("writing new key\n"));
 
2194
  return 0;
 
2195
}
 
2196
 
 
2197
 
 
2198
/* Create a TLV tag and value and store it at BUFFER.  Return the length
 
2199
   of tag and length.  A LENGTH greater than 65535 is truncated. */
 
2200
static size_t
 
2201
add_tlv (unsigned char *buffer, unsigned int tag, size_t length)
 
2202
 
2203
  unsigned char *p = buffer;
 
2204
 
 
2205
  assert (tag <= 0xffff);
 
2206
  if ( tag > 0xff )
 
2207
    *p++ = tag >> 8;
 
2208
  *p++ = tag;
 
2209
  if (length < 128)
 
2210
    *p++ = length;
 
2211
  else if (length < 256)
 
2212
    {
 
2213
      *p++ = 0x81;
 
2214
      *p++ = length;
 
2215
    }
 
2216
  else
 
2217
    {
 
2218
      if (length > 0xffff)
 
2219
        length = 0xffff;
 
2220
      *p++ = 0x82;
 
2221
      *p++ = length >> 8;
 
2222
      *p++ = length;
 
2223
    }
 
2224
 
 
2225
  return p - buffer;
 
2226
}
 
2227
 
 
2228
 
 
2229
/* Build the private key template as specified in the OpenPGP specs
 
2230
   v2.0 section 4.3.3.7.  */
 
2231
static gpg_error_t
 
2232
build_privkey_template (app_t app, int keyno,
 
2233
                        const unsigned char *rsa_n, size_t rsa_n_len,
 
2234
                        const unsigned char *rsa_e, size_t rsa_e_len,
 
2235
                        const unsigned char *rsa_p, size_t rsa_p_len,
 
2236
                        const unsigned char *rsa_q, size_t rsa_q_len,
 
2237
                        unsigned char **result, size_t *resultlen)
 
2238
{
 
2239
  size_t rsa_e_reqlen;
 
2240
  unsigned char privkey[7*(1+3)];
 
2241
  size_t privkey_len;
 
2242
  unsigned char exthdr[2+2+3];
 
2243
  size_t exthdr_len;
 
2244
  unsigned char suffix[2+3];
 
2245
  size_t suffix_len;
 
2246
  unsigned char *tp;
 
2247
  size_t datalen;
 
2248
  unsigned char *template;
 
2249
  size_t template_size;
 
2250
 
 
2251
  *result = NULL;
 
2252
  *resultlen = 0;
 
2253
 
 
2254
  switch (app->app_local->keyattr[keyno].format)
 
2255
    {
 
2256
    case RSA_STD:
 
2257
    case RSA_STD_N:
 
2258
      break;
 
2259
    case RSA_CRT:
 
2260
    case RSA_CRT_N:
 
2261
      return gpg_error (GPG_ERR_NOT_SUPPORTED);
 
2262
 
 
2263
    default:
 
2264
      return gpg_error (GPG_ERR_INV_VALUE);
 
2265
    }
 
2266
 
 
2267
  /* Get the required length for E.  */
 
2268
  rsa_e_reqlen = app->app_local->keyattr[keyno].e_bits/8;
 
2269
  assert (rsa_e_len <= rsa_e_reqlen);
 
2270
 
 
2271
  /* Build the 7f48 cardholder private key template.  */
 
2272
  datalen = 0;
 
2273
  tp = privkey;
 
2274
 
 
2275
  tp += add_tlv (tp, 0x91, rsa_e_reqlen);
 
2276
  datalen += rsa_e_reqlen;
 
2277
 
 
2278
  tp += add_tlv (tp, 0x92, rsa_p_len);
 
2279
  datalen += rsa_p_len;
 
2280
 
 
2281
  tp += add_tlv (tp, 0x93, rsa_q_len);
 
2282
  datalen += rsa_q_len;
 
2283
 
 
2284
  if (app->app_local->keyattr[keyno].format == RSA_STD_N
 
2285
      || app->app_local->keyattr[keyno].format == RSA_CRT_N)
 
2286
    {
 
2287
      tp += add_tlv (tp, 0x97, rsa_n_len);
 
2288
      datalen += rsa_n_len;
 
2289
    }
 
2290
  privkey_len = tp - privkey;
 
2291
 
 
2292
  /* Build the extended header list without the private key template.  */
 
2293
  tp = exthdr;
 
2294
  *tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4;
 
2295
  *tp++ = 0;
 
2296
  tp += add_tlv (tp, 0x7f48, privkey_len);
 
2297
  exthdr_len = tp - exthdr;
 
2298
 
 
2299
  /* Build the 5f48 suffix of the data.  */
 
2300
  tp = suffix;
 
2301
  tp += add_tlv (tp, 0x5f48, datalen);
 
2302
  suffix_len = tp - suffix;
 
2303
 
 
2304
  /* Now concatenate everything.  */
 
2305
  template_size = (1 + 3   /* 0x4d and len. */
 
2306
                   + exthdr_len
 
2307
                   + privkey_len
 
2308
                   + suffix_len
 
2309
                   + datalen);
 
2310
  tp = template = xtrymalloc_secure (template_size);
 
2311
  if (!template)
 
2312
    return gpg_error_from_syserror ();
 
2313
 
 
2314
  tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen);
 
2315
  memcpy (tp, exthdr, exthdr_len);
 
2316
  tp += exthdr_len;
 
2317
  memcpy (tp, privkey, privkey_len);
 
2318
  tp += privkey_len;
 
2319
  memcpy (tp, suffix, suffix_len);
 
2320
  tp += suffix_len;
 
2321
 
 
2322
  memcpy (tp, rsa_e, rsa_e_len);
 
2323
  if (rsa_e_len < rsa_e_reqlen)
 
2324
    {
 
2325
      /* Right justify E. */
 
2326
      memmove (tp + rsa_e_reqlen - rsa_e_len, tp, rsa_e_len);
 
2327
      memset (tp, 0, rsa_e_reqlen - rsa_e_len);
 
2328
    }                 
 
2329
  tp += rsa_e_reqlen;
 
2330
      
 
2331
  memcpy (tp, rsa_p, rsa_p_len);
 
2332
  tp += rsa_p_len;
 
2333
      
 
2334
  memcpy (tp, rsa_q, rsa_q_len);
 
2335
  tp += rsa_q_len;
 
2336
  
 
2337
  if (app->app_local->keyattr[keyno].format == RSA_STD_N
 
2338
      || app->app_local->keyattr[keyno].format == RSA_CRT_N)
 
2339
    {
 
2340
      memcpy (tp, rsa_n, rsa_n_len);
 
2341
      tp += rsa_n_len;
 
2342
    }
 
2343
 
 
2344
  /* Sanity check.  We don't know the exact length because we
 
2345
     allocated 3 bytes for the first length header.  */
 
2346
  assert (tp - template <= template_size);
 
2347
 
 
2348
  *result = template;
 
2349
  *resultlen = tp - template;
 
2350
  return 0;
 
2351
}
 
2352
 
 
2353
 
 
2354
/* Helper for do_writekley to change the size of a key.  Not ethat
 
2355
   this deletes the entire key without asking.  */
 
2356
static gpg_error_t
 
2357
change_keyattr (app_t app, int keyno, unsigned int nbits,
 
2358
                gpg_error_t (*pincb)(void*, const char *, char **),
 
2359
                void *pincb_arg)
 
2360
{
 
2361
  gpg_error_t err;
 
2362
  unsigned char *buffer;
 
2363
  size_t buflen;
 
2364
  void *relptr;
 
2365
 
 
2366
  assert (keyno >=0 && keyno <= 2);
 
2367
 
 
2368
  if (nbits > 3072)
 
2369
    return gpg_error (GPG_ERR_TOO_LARGE);
 
2370
 
 
2371
  /* Read the current attributes into a buffer.  */
 
2372
  relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL);
 
2373
  if (!relptr)
 
2374
    return gpg_error (GPG_ERR_CARD);
 
2375
  if (buflen < 6 || buffer[0] != 1)
 
2376
    {
 
2377
      /* Attriutes too short or not an RSA key.  */
 
2378
      xfree (relptr);
 
2379
      return gpg_error (GPG_ERR_CARD);
 
2380
    }
 
2381
  
 
2382
  /* We only change n_bits and don't touch anything else.  Before we
 
2383
     do so, we round up NBITS to a sensible way in the same way as
 
2384
     gpg's key generation does it.  This may help to sort out problems
 
2385
     with a few bits too short keys.  */
 
2386
  nbits = ((nbits + 31) / 32) * 32;
 
2387
  buffer[1] = (nbits >> 8);
 
2388
  buffer[2] = nbits;
 
2389
 
 
2390
  /* Prepare for storing the key.  */
 
2391
  err = verify_chv3 (app, pincb, pincb_arg);
 
2392
  if (err)
 
2393
    {
 
2394
      xfree (relptr);
 
2395
      return err;
 
2396
    }
 
2397
 
 
2398
  /* Change the attribute.  */
 
2399
  err = iso7816_put_data (app->slot, 0, 0xC1+keyno, buffer, buflen);
 
2400
  xfree (relptr);
 
2401
  if (err)
 
2402
    log_error ("error changing size of key %d to %u bits\n", keyno+1, nbits);
 
2403
  else
 
2404
    log_info ("size of key %d changed to %u bits\n", keyno+1, nbits);
 
2405
  flush_cache (app);
 
2406
  parse_algorithm_attribute (app, keyno);
 
2407
  app->did_chv1 = 0;
 
2408
  app->did_chv2 = 0;
 
2409
  app->did_chv3 = 0;
 
2410
  return err;
 
2411
}
 
2412
 
 
2413
 
 
2414
/* Helper to process an setattr command for name KEY-ATTR.  It expects
 
2415
   a string "--force <keyno> <algo> <nbits>" in (VALUE,VALUELEN).  */
 
2416
static gpg_error_t 
 
2417
change_keyattr_from_string (app_t app, 
 
2418
                            gpg_error_t (*pincb)(void*, const char *, char **),
 
2419
                            void *pincb_arg,
 
2420
                            const void *value, size_t valuelen)
 
2421
{
 
2422
  gpg_error_t err;
 
2423
  char *string;
 
2424
  int keyno, algo;
 
2425
  unsigned int nbits;
 
2426
 
 
2427
  /* VALUE is expected to be a string but not guaranteed to be
 
2428
     terminated.  Thus copy it to an allocated buffer first. */
 
2429
  string = xtrymalloc (valuelen+1);
 
2430
  if (!string)
 
2431
    return gpg_error_from_syserror ();
 
2432
  memcpy (string, value, valuelen);
 
2433
  string[valuelen] = 0;
 
2434
 
 
2435
  /* Because this function deletes the key we require the string
 
2436
     "--force" in the data to make clear that something serious might
 
2437
     happen.  */
 
2438
  if (sscanf (string, " --force %d %d %u", &keyno, &algo, &nbits) != 3)
 
2439
    err = gpg_error (GPG_ERR_INV_DATA);
 
2440
  else if (keyno < 1 || keyno > 3)
 
2441
    err = gpg_error (GPG_ERR_INV_ID);
 
2442
  else if (algo != 1)
 
2443
    err = gpg_error (GPG_ERR_PUBKEY_ALGO); /* Not RSA.  */
 
2444
  else if (nbits < 1024)
 
2445
    err = gpg_error (GPG_ERR_TOO_SHORT);
 
2446
  else
 
2447
    err = change_keyattr (app, keyno-1, nbits, pincb, pincb_arg);
 
2448
 
 
2449
  xfree (string);
 
2450
  return err;
 
2451
}
 
2452
 
 
2453
 
 
2454
/* Handle the WRITEKEY command for OpenPGP.  This function expects a
 
2455
   canonical encoded S-expression with the secret key in KEYDATA and
 
2456
   its length (for assertions) in KEYDATALEN.  KEYID needs to be the
 
2457
   usual keyid which for OpenPGP is the string "OPENPGP.n" with
 
2458
   n=1,2,3.  Bit 0 of FLAGS indicates whether an existing key shall
 
2459
   get overwritten.  PINCB and PINCB_ARG are the usual arguments for
 
2460
   the pinentry callback.  */
 
2461
static gpg_error_t
 
2462
do_writekey (app_t app, ctrl_t ctrl,
 
2463
             const char *keyid, unsigned int flags,
 
2464
             gpg_error_t (*pincb)(void*, const char *, char **),
 
2465
             void *pincb_arg,
 
2466
             const unsigned char *keydata, size_t keydatalen)
 
2467
{
 
2468
  gpg_error_t err;
 
2469
  int force = (flags & 1);
 
2470
  int keyno;
 
2471
  const unsigned char *buf, *tok;
 
2472
  size_t buflen, toklen;
 
2473
  int depth, last_depth1, last_depth2;
 
2474
  const unsigned char *rsa_n = NULL;
 
2475
  const unsigned char *rsa_e = NULL;
 
2476
  const unsigned char *rsa_p = NULL;
 
2477
  const unsigned char *rsa_q = NULL;
 
2478
  size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
 
2479
  unsigned int nbits;
 
2480
  unsigned int maxbits;
 
2481
  unsigned char *template = NULL;
 
2482
  unsigned char *tp;
 
2483
  size_t template_len;
 
2484
  unsigned char fprbuf[20];
 
2485
  u32 created_at = 0;
 
2486
 
 
2487
  (void)ctrl;
 
2488
 
 
2489
  if (!strcmp (keyid, "OPENPGP.1"))
 
2490
    keyno = 0;
 
2491
  else if (!strcmp (keyid, "OPENPGP.2"))
 
2492
    keyno = 1;
 
2493
  else if (!strcmp (keyid, "OPENPGP.3"))
 
2494
    keyno = 2;
 
2495
  else
 
2496
    return gpg_error (GPG_ERR_INV_ID);
 
2497
  
 
2498
  err = does_key_exist (app, keyno, 0, force);
 
2499
  if (err)
 
2500
    return err;
 
2501
 
 
2502
 
 
2503
  /* 
 
2504
     Parse the S-expression
 
2505
   */
 
2506
  buf = keydata;
 
2507
  buflen = keydatalen;
 
2508
  depth = 0;
 
2509
  if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
 
2510
    goto leave;
 
2511
  if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
 
2512
    goto leave;
 
2513
  if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
 
2514
    {
 
2515
      if (!tok)
 
2516
        ;
 
2517
      else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
 
2518
        log_info ("protected-private-key passed to writekey\n");
 
2519
      else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
 
2520
        log_info ("shadowed-private-key passed to writekey\n");
 
2521
      err = gpg_error (GPG_ERR_BAD_SECKEY);
 
2522
      goto leave;
 
2523
    }
 
2524
  if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
 
2525
    goto leave;
 
2526
  if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
 
2527
    goto leave;
 
2528
  if (!tok || toklen != 3 || memcmp ("rsa", tok, toklen))
 
2529
    {
 
2530
      err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
 
2531
      goto leave;
 
2532
    }
 
2533
  last_depth1 = depth;
 
2534
  while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
 
2535
         && depth && depth >= last_depth1)
 
2536
    {
 
2537
      if (tok)
 
2538
        {
 
2539
          err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
 
2540
          goto leave;
 
2541
        }
 
2542
      if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
 
2543
        goto leave;
 
2544
      if (tok && toklen == 1)
 
2545
        {
 
2546
          const unsigned char **mpi;
 
2547
          size_t *mpi_len;
 
2548
 
 
2549
          switch (*tok)
 
2550
            {
 
2551
            case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break; 
 
2552
            case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break; 
 
2553
            case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break; 
 
2554
            case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break; 
 
2555
            default: mpi = NULL;  mpi_len = NULL; break;
 
2556
            }
 
2557
          if (mpi && *mpi)
 
2558
            {
 
2559
              err = gpg_error (GPG_ERR_DUP_VALUE);
 
2560
              goto leave;
 
2561
            }
 
2562
          if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
 
2563
            goto leave;
 
2564
          if (tok && mpi)
 
2565
            {
 
2566
              /* Strip off leading zero bytes and save. */
 
2567
              for (;toklen && !*tok; toklen--, tok++)
 
2568
                ;
 
2569
              *mpi = tok;
 
2570
              *mpi_len = toklen;
 
2571
            }
 
2572
        }
 
2573
      /* Skip until end of list. */
 
2574
      last_depth2 = depth;
 
2575
      while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
 
2576
             && depth && depth >= last_depth2)
 
2577
        ;
 
2578
      if (err)
 
2579
        goto leave;
 
2580
    }
 
2581
  /* Parse other attributes. */
 
2582
  last_depth1 = depth;
 
2583
  while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
 
2584
         && depth && depth >= last_depth1)
 
2585
    {
 
2586
      if (tok)
 
2587
        {
 
2588
          err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
 
2589
          goto leave;
 
2590
        }
 
2591
      if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
 
2592
        goto leave;
 
2593
      if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
 
2594
        {
 
2595
          if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
 
2596
            goto leave;
 
2597
          if (tok)
 
2598
            {
 
2599
              for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
 
2600
                   tok++, toklen--)
 
2601
                created_at = created_at*10 + (*tok - '0');
 
2602
            }
 
2603
        }
 
2604
      /* Skip until end of list. */
 
2605
      last_depth2 = depth;
 
2606
      while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
 
2607
             && depth && depth >= last_depth2)
 
2608
        ;
 
2609
      if (err)
 
2610
        goto leave;
 
2611
    }
 
2612
 
 
2613
 
 
2614
  /* Check that we have all parameters and that they match the card
 
2615
     description. */
 
2616
  if (!created_at)
 
2617
    {
 
2618
      log_error (_("creation timestamp missing\n"));
 
2619
      err = gpg_error (GPG_ERR_INV_VALUE);
 
2620
      goto leave;
 
2621
    }
 
2622
 
 
2623
  maxbits = app->app_local->keyattr[keyno].n_bits;
 
2624
  nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
 
2625
  if (opt.verbose)
 
2626
    log_info ("RSA modulus size is %u bits (%u bytes)\n", 
 
2627
              nbits, (unsigned int)rsa_n_len);
 
2628
  if (nbits && nbits != maxbits
 
2629
      && app->app_local->extcap.algo_attr_change)
 
2630
    {
 
2631
      /* Try to switch the key to a new length.  */
 
2632
      err = change_keyattr (app, keyno, nbits, pincb, pincb_arg);
 
2633
      if (!err)
 
2634
        maxbits = app->app_local->keyattr[keyno].n_bits;
 
2635
    }
 
2636
  if (nbits != maxbits)
 
2637
    {
 
2638
      log_error (_("RSA modulus missing or not of size %d bits\n"), 
 
2639
                 (int)maxbits);
 
2640
      err = gpg_error (GPG_ERR_BAD_SECKEY);
 
2641
      goto leave;
 
2642
    }
 
2643
 
 
2644
  maxbits = app->app_local->keyattr[keyno].e_bits;
 
2645
  if (maxbits > 32 && !app->app_local->extcap.is_v2)
 
2646
    maxbits = 32; /* Our code for v1 does only support 32 bits.  */
 
2647
  nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
 
2648
  if (nbits < 2 || nbits > maxbits)
 
2649
    {
 
2650
      log_error (_("RSA public exponent missing or larger than %d bits\n"),
 
2651
                 (int)maxbits);
 
2652
      err = gpg_error (GPG_ERR_BAD_SECKEY);
 
2653
      goto leave;
 
2654
    }
 
2655
 
 
2656
  maxbits = app->app_local->keyattr[keyno].n_bits/2;
 
2657
  nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
 
2658
  if (nbits != maxbits)
 
2659
    {
 
2660
      log_error (_("RSA prime %s missing or not of size %d bits\n"), 
 
2661
                 "P", (int)maxbits);
 
2662
      err = gpg_error (GPG_ERR_BAD_SECKEY);
 
2663
      goto leave;
 
2664
    }
 
2665
  nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
 
2666
  if (nbits != maxbits)
 
2667
    {
 
2668
      log_error (_("RSA prime %s missing or not of size %d bits\n"), 
 
2669
                 "Q", (int)maxbits);
 
2670
      err = gpg_error (GPG_ERR_BAD_SECKEY);
 
2671
      goto leave;
 
2672
    }
 
2673
  
 
2674
  /* We need to remove the cached public key.  */
 
2675
  xfree (app->app_local->pk[keyno].key);
 
2676
  app->app_local->pk[keyno].key = NULL;
 
2677
  app->app_local->pk[keyno].keylen = 0;
 
2678
  app->app_local->pk[keyno].read_done = 0;
 
2679
 
 
2680
 
 
2681
  if (app->app_local->extcap.is_v2)
 
2682
    {
 
2683
      /* Build the private key template as described in section 4.3.3.7 of
 
2684
         the OpenPGP card specs version 2.0.  */
 
2685
      int exmode;
 
2686
 
 
2687
      err = build_privkey_template (app, keyno,
 
2688
                                    rsa_n, rsa_n_len,
 
2689
                                    rsa_e, rsa_e_len,
 
2690
                                    rsa_p, rsa_p_len,
 
2691
                                    rsa_q, rsa_q_len,
 
2692
                                    &template, &template_len);
 
2693
      if (err)
 
2694
        goto leave;
 
2695
 
 
2696
      /* Prepare for storing the key.  */
 
2697
      err = verify_chv3 (app, pincb, pincb_arg);
 
2698
      if (err)
 
2699
        goto leave;
 
2700
 
 
2701
      /* Store the key. */
 
2702
      if (app->app_local->cardcap.ext_lc_le && template_len > 254)
 
2703
        exmode = 1;    /* Use extended length w/o a limit.  */
 
2704
      else if (app->app_local->cardcap.cmd_chaining && template_len > 254)
 
2705
        exmode = -254;
 
2706
      else
 
2707
        exmode = 0;
 
2708
      err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
 
2709
                                  template, template_len);
 
2710
    }
 
2711
  else
 
2712
    {
 
2713
      /* Build the private key template as described in section 4.3.3.6 of
 
2714
         the OpenPGP card specs version 1.1:
 
2715
         0xC0   <length> public exponent
 
2716
         0xC1   <length> prime p 
 
2717
         0xC2   <length> prime q 
 
2718
      */
 
2719
      assert (rsa_e_len <= 4);
 
2720
      template_len = (1 + 1 + 4
 
2721
                      + 1 + 1 + rsa_p_len
 
2722
                      + 1 + 1 + rsa_q_len);
 
2723
      template = tp = xtrymalloc_secure (template_len);
 
2724
      if (!template)
 
2725
        {
 
2726
          err = gpg_error_from_syserror ();
 
2727
          goto leave;
 
2728
        }
 
2729
      *tp++ = 0xC0;
 
2730
      *tp++ = 4;
 
2731
      memcpy (tp, rsa_e, rsa_e_len);
 
2732
      if (rsa_e_len < 4)
 
2733
        {
 
2734
          /* Right justify E. */
 
2735
          memmove (tp+4-rsa_e_len, tp, rsa_e_len);
 
2736
          memset (tp, 0, 4-rsa_e_len);
 
2737
        }                 
 
2738
      tp += 4;
 
2739
      
 
2740
      *tp++ = 0xC1;
 
2741
      *tp++ = rsa_p_len;
 
2742
      memcpy (tp, rsa_p, rsa_p_len);
 
2743
      tp += rsa_p_len;
 
2744
      
 
2745
      *tp++ = 0xC2;
 
2746
      *tp++ = rsa_q_len;
 
2747
      memcpy (tp, rsa_q, rsa_q_len);
 
2748
      tp += rsa_q_len;
 
2749
      
 
2750
      assert (tp - template == template_len);
 
2751
      
 
2752
      /* Prepare for storing the key.  */
 
2753
      err = verify_chv3 (app, pincb, pincb_arg);
 
2754
      if (err)
 
2755
        goto leave;
 
2756
 
 
2757
      /* Store the key. */
 
2758
      err = iso7816_put_data (app->slot, 0,
 
2759
                              (app->card_version > 0x0007? 0xE0:0xE9)+keyno,
 
2760
                              template, template_len);
 
2761
    }
 
2762
  if (err)
 
2763
    {
 
2764
      log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
 
2765
      goto leave;
 
2766
    }
 
2767
 
 
2768
  err = store_fpr (app, keyno, created_at,
 
2769
                  rsa_n, rsa_n_len, rsa_e, rsa_e_len,
 
2770
                  fprbuf, app->card_version);
 
2771
  if (err)
 
2772
    goto leave;
 
2773
 
 
2774
 
 
2775
 leave:
 
2776
  xfree (template);
 
2777
  return err;
 
2778
}
 
2779
 
 
2780
 
 
2781
/* Handle the GENKEY command. */
 
2782
static gpg_error_t 
 
2783
do_genkey (app_t app, ctrl_t ctrl,  const char *keynostr, unsigned int flags,
 
2784
           time_t createtime,
 
2785
           gpg_error_t (*pincb)(void*, const char *, char **),
 
2786
           void *pincb_arg)
 
2787
{
 
2788
  int rc;
 
2789
  char numbuf[30];
 
2790
  unsigned char fprbuf[20];
 
2791
  const unsigned char *keydata, *m, *e;
 
2792
  unsigned char *buffer = NULL;
 
2793
  size_t buflen, keydatalen, mlen, elen;
 
2794
  time_t created_at;
 
2795
  int keyno = atoi (keynostr);
 
2796
  int force = (flags & 1);
 
2797
  time_t start_at;
 
2798
  int exmode;
 
2799
  int le_value;
 
2800
  unsigned int keybits; 
 
2801
 
 
2802
  if (keyno < 1 || keyno > 3)
 
2803
    return gpg_error (GPG_ERR_INV_ID);
 
2804
  keyno--;
 
2805
 
 
2806
  /* We flush the cache to increase the traffic before a key
 
2807
     generation.  This _might_ help a card to gather more entropy. */
 
2808
  flush_cache (app);
 
2809
 
 
2810
  /* Obviously we need to remove the cached public key.  */
 
2811
  xfree (app->app_local->pk[keyno].key);
 
2812
  app->app_local->pk[keyno].key = NULL;
 
2813
  app->app_local->pk[keyno].keylen = 0;
 
2814
  app->app_local->pk[keyno].read_done = 0;
 
2815
 
 
2816
  /* Check whether a key already exists.  */
 
2817
  rc = does_key_exist (app, keyno, 1, force);
 
2818
  if (rc)
 
2819
    return rc;
 
2820
 
 
2821
  /* Because we send the key parameter back via status lines we need
 
2822
     to put a limit on the max. allowed keysize.  2048 bit will
 
2823
     already lead to a 527 byte long status line and thus a 4096 bit
 
2824
     key would exceed the Assuan line length limit.  */ 
 
2825
  keybits = app->app_local->keyattr[keyno].n_bits;
 
2826
  if (keybits > 3072)
 
2827
    return gpg_error (GPG_ERR_TOO_LARGE);
 
2828
 
 
2829
  /* Prepare for key generation by verifying the Admin PIN.  */
 
2830
  rc = verify_chv3 (app, pincb, pincb_arg);
 
2831
  if (rc)
 
2832
    goto leave;
 
2833
 
 
2834
  /* Test whether we will need extended length mode.  (1900 is an
 
2835
     arbitrary length which for sure fits into a short apdu.)  */
 
2836
  if (app->app_local->cardcap.ext_lc_le && keybits > 1900)
 
2837
    {
 
2838
      exmode = 1;    /* Use extended length w/o a limit.  */
 
2839
      le_value = app->app_local->extcap.max_rsp_data;
 
2840
      /* No need to check le_value because it comes from a 16 bit
 
2841
         value and thus can't create an overflow on a 32 bit
 
2842
         system.  */ 
 
2843
    }
 
2844
  else
 
2845
    {
 
2846
      exmode = 0;
 
2847
      le_value = 256; /* Use legacy value. */
 
2848
    }
 
2849
 
 
2850
  log_info (_("please wait while key is being generated ...\n"));
 
2851
  start_at = time (NULL);
 
2852
  rc = iso7816_generate_keypair 
 
2853
/* # warning key generation temporary replaced by reading an existing key. */
 
2854
/*   rc = iso7816_read_public_key */
 
2855
    (app->slot, exmode, 
 
2856
     (const unsigned char*)(keyno == 0? "\xB6" :
 
2857
                            keyno == 1? "\xB8" : "\xA4"), 2,
 
2858
     le_value,
 
2859
     &buffer, &buflen);
 
2860
  if (rc)
 
2861
    {
 
2862
      rc = gpg_error (GPG_ERR_CARD);
 
2863
      log_error (_("generating key failed\n"));
 
2864
      goto leave;
 
2865
    }
 
2866
  log_info (_("key generation completed (%d seconds)\n"),
 
2867
            (int)(time (NULL) - start_at));
 
2868
 
 
2869
  keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
 
2870
  if (!keydata)
 
2871
    {
 
2872
      rc = gpg_error (GPG_ERR_CARD);
 
2873
      log_error (_("response does not contain the public key data\n"));
 
2874
      goto leave;
 
2875
    }
 
2876
 
 
2877
  m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
 
2878
  if (!m)
 
2879
    {
 
2880
      rc = gpg_error (GPG_ERR_CARD);
 
2881
      log_error (_("response does not contain the RSA modulus\n"));
 
2882
      goto leave;
 
2883
    }
 
2884
  /* log_printhex ("RSA n:", m, mlen); */
 
2885
  send_key_data (ctrl, "n", m, mlen);
 
2886
 
 
2887
  e = find_tlv (keydata, keydatalen, 0x0082, &elen);
 
2888
  if (!e)
 
2889
    {
 
2890
      rc = gpg_error (GPG_ERR_CARD);
 
2891
      log_error (_("response does not contain the RSA public exponent\n"));
 
2892
      goto leave;
 
2893
    }
 
2894
  /* log_printhex ("RSA e:", e, elen); */
 
2895
  send_key_data (ctrl, "e", e, elen);
 
2896
 
 
2897
  created_at = createtime? createtime : gnupg_get_time ();
 
2898
  sprintf (numbuf, "%lu", (unsigned long)created_at);
 
2899
  send_status_info (ctrl, "KEY-CREATED-AT",
 
2900
                    numbuf, (size_t)strlen(numbuf), NULL, 0);
 
2901
 
 
2902
  rc = store_fpr (app, keyno, (u32)created_at,
 
2903
                  m, mlen, e, elen, fprbuf, app->card_version);
 
2904
  if (rc)
 
2905
    goto leave;
 
2906
  send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
 
2907
 
 
2908
 
 
2909
 leave:
 
2910
  xfree (buffer);
 
2911
  return rc;
 
2912
}
 
2913
 
 
2914
 
 
2915
static unsigned long
 
2916
convert_sig_counter_value (const unsigned char *value, size_t valuelen)
 
2917
{
 
2918
  unsigned long ul;
 
2919
 
 
2920
  if (valuelen == 3 )
 
2921
    ul = (value[0] << 16) | (value[1] << 8) | value[2];
 
2922
  else
 
2923
    {
 
2924
      log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
 
2925
      ul = 0;
 
2926
    }
 
2927
  return ul;
 
2928
}
 
2929
 
 
2930
static unsigned long
 
2931
get_sig_counter (app_t app)
 
2932
{
 
2933
  void *relptr;
 
2934
  unsigned char *value;
 
2935
  size_t valuelen;
 
2936
  unsigned long ul;
 
2937
 
 
2938
  relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
 
2939
  if (!relptr)
 
2940
    return 0;
 
2941
  ul = convert_sig_counter_value (value, valuelen);
 
2942
  xfree (relptr);
 
2943
  return ul;
 
2944
}
 
2945
 
 
2946
static gpg_error_t
 
2947
compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
 
2948
{
 
2949
  const unsigned char *fpr;
 
2950
  unsigned char *buffer;
 
2951
  size_t buflen, n;
 
2952
  int rc, i;
 
2953
  
 
2954
  assert (keyno >= 1 && keyno <= 3);
 
2955
 
 
2956
  rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0, 0);
 
2957
  if (rc)
 
2958
    {
 
2959
      log_error (_("error reading application data\n"));
 
2960
      return gpg_error (GPG_ERR_GENERAL);
 
2961
    }
 
2962
  fpr = find_tlv (buffer, buflen, 0x00C5, &n);
 
2963
  if (!fpr || n != 60)
 
2964
    {
 
2965
      xfree (buffer);
 
2966
      log_error (_("error reading fingerprint DO\n"));
 
2967
      return gpg_error (GPG_ERR_GENERAL);
 
2968
    }
 
2969
  fpr += (keyno-1)*20;
 
2970
  for (i=0; i < 20; i++)
 
2971
    if (sha1fpr[i] != fpr[i])
 
2972
      {
 
2973
        xfree (buffer);
 
2974
        log_info (_("fingerprint on card does not match requested one\n"));
 
2975
        return gpg_error (GPG_ERR_WRONG_SECKEY);
 
2976
      }
 
2977
  xfree (buffer);
 
2978
  return 0;
 
2979
}
 
2980
 
 
2981
 
 
2982
/* If a fingerprint has been specified check it against the one on the
 
2983
   card.  This allows for a meaningful error message in case the key
 
2984
   on the card has been replaced but the shadow information known to
 
2985
   gpg has not been updated.  If there is no fingerprint we assume
 
2986
   that this is okay. */
 
2987
static gpg_error_t
 
2988
check_against_given_fingerprint (app_t app, const char *fpr, int keyno)
 
2989
{
 
2990
  unsigned char tmp[20];
 
2991
  const char *s;
 
2992
  int n;
 
2993
 
 
2994
  for (s=fpr, n=0; hexdigitp (s); s++, n++)
 
2995
    ;
 
2996
  if (n != 40)
 
2997
    return gpg_error (GPG_ERR_INV_ID);
 
2998
  else if (!*s)
 
2999
    ; /* okay */
 
3000
  else
 
3001
    return gpg_error (GPG_ERR_INV_ID);
 
3002
 
 
3003
  for (s=fpr, n=0; n < 20; s += 2, n++)
 
3004
        tmp[n] = xtoi_2 (s);
 
3005
  return compare_fingerprint (app, keyno, tmp);
 
3006
}
 
3007
 
 
3008
 
 
3009
 
 
3010
/* Compute a digital signature on INDATA which is expected to be the
 
3011
   raw message digest. For this application the KEYIDSTR consists of
 
3012
   the serialnumber and the fingerprint delimited by a slash.
 
3013
 
 
3014
   Note that this function may return the error code
 
3015
   GPG_ERR_WRONG_CARD to indicate that the card currently present does
 
3016
   not match the one required for the requested action (e.g. the
 
3017
   serial number does not match). 
 
3018
   
 
3019
   As a special feature a KEYIDSTR of "OPENPGP.3" redirects the
 
3020
   operation to the auth command.
 
3021
*/
 
3022
static gpg_error_t 
 
3023
do_sign (app_t app, const char *keyidstr, int hashalgo,
 
3024
         gpg_error_t (*pincb)(void*, const char *, char **),
 
3025
         void *pincb_arg,
 
3026
         const void *indata, size_t indatalen,
 
3027
         unsigned char **outdata, size_t *outdatalen )
 
3028
{
 
3029
  static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
 
3030
    { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
 
3031
      0x02, 0x01, 0x05, 0x00, 0x04, 0x14  };
 
3032
  static unsigned char sha1_prefix[15] =   /* (1.3.14.3.2.26) */
 
3033
    { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
 
3034
      0x02, 0x1a, 0x05, 0x00, 0x04, 0x14  };
 
3035
  static unsigned char sha224_prefix[19] = /* (2.16.840.1.101.3.4.2.4) */
 
3036
    { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
 
3037
      0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04,
 
3038
      0x1C  };
 
3039
  static unsigned char sha256_prefix[19] = /* (2.16.840.1.101.3.4.2.1) */
 
3040
    { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
 
3041
      0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
 
3042
      0x00, 0x04, 0x20  };
 
3043
  static unsigned char sha384_prefix[19] = /* (2.16.840.1.101.3.4.2.2) */
 
3044
    { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
 
3045
      0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
 
3046
      0x00, 0x04, 0x30  };
 
3047
  static unsigned char sha512_prefix[19] = /* (2.16.840.1.101.3.4.2.3) */
 
3048
    { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
 
3049
      0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
 
3050
      0x00, 0x04, 0x40  };
 
3051
  int rc;
 
3052
  unsigned char data[19+64];
 
3053
  size_t datalen;
 
3054
  unsigned char tmp_sn[20]; /* Actually 16 bytes but also for the fpr. */
 
3055
  const char *s;
 
3056
  int n;
 
3057
  const char *fpr = NULL;
 
3058
  unsigned long sigcount;
 
3059
  int use_auth = 0;
 
3060
  int exmode, le_value;
 
3061
 
 
3062
  if (!keyidstr || !*keyidstr)
 
3063
    return gpg_error (GPG_ERR_INV_VALUE);
 
3064
 
 
3065
  /* Strip off known prefixes.  */
 
3066
#define X(a,b,c,d) \
 
3067
  if (hashalgo == GCRY_MD_ ## a                               \
 
3068
      && (d)                                                  \
 
3069
      && indatalen == sizeof b ## _prefix + (c)               \
 
3070
      && !memcmp (indata, b ## _prefix, sizeof b ## _prefix)) \
 
3071
    {                                                         \
 
3072
      indata = (const char*)indata + sizeof b ## _prefix;     \
 
3073
      indatalen -= sizeof b ## _prefix;                       \
 
3074
    }                                                         
 
3075
 
 
3076
  if (indatalen == 20)
 
3077
    ;  /* Assume a plain SHA-1 or RMD160 digest has been given.  */
 
3078
  else X(SHA1,   sha1,   20, 1)
 
3079
  else X(RMD160, rmd160, 20, 1)
 
3080
  else X(SHA224, sha224, 28, app->app_local->extcap.is_v2)
 
3081
  else X(SHA256, sha256, 32, app->app_local->extcap.is_v2)
 
3082
  else X(SHA384, sha384, 48, app->app_local->extcap.is_v2)
 
3083
  else X(SHA512, sha512, 64, app->app_local->extcap.is_v2)
 
3084
  else if ((indatalen == 28 || indatalen == 32 
 
3085
            || indatalen == 48 || indatalen ==64)
 
3086
           && app->app_local->extcap.is_v2)
 
3087
    ;  /* Assume a plain SHA-3 digest has been given.  */
 
3088
  else
 
3089
    {
 
3090
      log_error (_("card does not support digest algorithm %s\n"),
 
3091
                 gcry_md_algo_name (hashalgo));
 
3092
      /* Or the supplied digest length does not match an algorithm.  */
 
3093
      return gpg_error (GPG_ERR_INV_VALUE);
 
3094
    }
 
3095
#undef X
 
3096
 
 
3097
  /* Check whether an OpenPGP card of any version has been requested. */
 
3098
  if (!strcmp (keyidstr, "OPENPGP.1"))
 
3099
    ;
 
3100
  else if (!strcmp (keyidstr, "OPENPGP.3"))
 
3101
    use_auth = 1;
 
3102
  else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
 
3103
    return gpg_error (GPG_ERR_INV_ID);
 
3104
  else
 
3105
    {
 
3106
      for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
 
3107
        ;
 
3108
      if (n != 32)
 
3109
        return gpg_error (GPG_ERR_INV_ID);
 
3110
      else if (!*s)
 
3111
        ; /* no fingerprint given: we allow this for now. */
 
3112
      else if (*s == '/')
 
3113
        fpr = s + 1; 
 
3114
      else
 
3115
        return gpg_error (GPG_ERR_INV_ID);
 
3116
 
 
3117
      for (s=keyidstr, n=0; n < 16; s += 2, n++)
 
3118
        tmp_sn[n] = xtoi_2 (s);
 
3119
 
 
3120
      if (app->serialnolen != 16)
 
3121
        return gpg_error (GPG_ERR_INV_CARD);
 
3122
      if (memcmp (app->serialno, tmp_sn, 16))
 
3123
        return gpg_error (GPG_ERR_WRONG_CARD);
 
3124
    }
 
3125
 
 
3126
  /* If a fingerprint has been specified check it against the one on
 
3127
     the card.  This is allows for a meaningful error message in case
 
3128
     the key on the card has been replaced but the shadow information
 
3129
     known to gpg was not updated.  If there is no fingerprint, gpg
 
3130
     will detect a bogus signature anyway due to the
 
3131
     verify-after-signing feature. */
 
3132
  rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
 
3133
  if (rc)
 
3134
    return rc;
 
3135
 
 
3136
  /* Concatenate prefix and digest.  */
 
3137
#define X(a,b,d) \
 
3138
  if (hashalgo == GCRY_MD_ ## a && (d) )                      \
 
3139
    {                                                         \
 
3140
      datalen = sizeof b ## _prefix + indatalen;              \
 
3141
      assert (datalen <= sizeof data);                        \
 
3142
      memcpy (data, b ## _prefix, sizeof b ## _prefix);       \
 
3143
      memcpy (data + sizeof b ## _prefix, indata, indatalen); \
 
3144
    }                                                         
 
3145
 
 
3146
  X(SHA1,   sha1,   1)
 
3147
  else X(RMD160, rmd160, 1)
 
3148
  else X(SHA224, sha224, app->app_local->extcap.is_v2)
 
3149
  else X(SHA256, sha256, app->app_local->extcap.is_v2)
 
3150
  else X(SHA384, sha384, app->app_local->extcap.is_v2)
 
3151
  else X(SHA512, sha512, app->app_local->extcap.is_v2)
 
3152
  else 
 
3153
    return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
 
3154
#undef X
 
3155
 
 
3156
  /* Redirect to the AUTH command if asked to. */
 
3157
  if (use_auth)
 
3158
    {
 
3159
      return do_auth (app, "OPENPGP.3", pincb, pincb_arg,
 
3160
                      data, datalen,
 
3161
                      outdata, outdatalen);
 
3162
    }
 
3163
 
 
3164
  /* Show the number of signature done using this key.  */
 
3165
  sigcount = get_sig_counter (app);
 
3166
  log_info (_("signatures created so far: %lu\n"), sigcount);
 
3167
 
 
3168
  /* Check CHV if needed.  */
 
3169
  if (!app->did_chv1 || app->force_chv1 ) 
 
3170
    {
 
3171
      char *pinvalue;
 
3172
 
 
3173
      rc = verify_a_chv (app, pincb, pincb_arg, 1, sigcount, &pinvalue);
 
3174
      if (rc)
 
3175
        return rc;
 
3176
 
 
3177
      app->did_chv1 = 1;
 
3178
 
 
3179
      /* For cards with versions < 2 we want to keep CHV1 and CHV2 in
 
3180
         sync, thus we verify CHV2 here using the given PIN.  Cards
 
3181
         with version2 to not have the need for a separate CHV2 and
 
3182
         internally use just one.  Obviously we can't do that if the
 
3183
         keypad has been used. */
 
3184
      if (!app->did_chv2 && pinvalue && !app->app_local->extcap.is_v2)
 
3185
        {
 
3186
          rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
 
3187
          if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
 
3188
            rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
 
3189
          if (rc)
 
3190
            {
 
3191
              log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
 
3192
              xfree (pinvalue);
 
3193
              flush_cache_after_error (app);
 
3194
              return rc;
 
3195
            }
 
3196
          app->did_chv2 = 1;
 
3197
        }
 
3198
      xfree (pinvalue);
 
3199
    }
 
3200
 
 
3201
 
 
3202
  if (app->app_local->cardcap.ext_lc_le)
 
3203
    {
 
3204
      exmode = 1;    /* Use extended length.  */
 
3205
      le_value = app->app_local->extcap.max_rsp_data;
 
3206
    }
 
3207
  else
 
3208
    {
 
3209
      exmode = 0;
 
3210
      le_value = 0; 
 
3211
    }
 
3212
  rc = iso7816_compute_ds (app->slot, exmode, data, datalen, le_value,
 
3213
                           outdata, outdatalen);
 
3214
  return rc;
 
3215
}
 
3216
 
 
3217
/* Compute a digital signature using the INTERNAL AUTHENTICATE command
 
3218
   on INDATA which is expected to be the raw message digest. For this
 
3219
   application the KEYIDSTR consists of the serialnumber and the
 
3220
   fingerprint delimited by a slash.  Optionally the id OPENPGP.3 may
 
3221
   be given.
 
3222
 
 
3223
   Note that this function may return the error code
 
3224
   GPG_ERR_WRONG_CARD to indicate that the card currently present does
 
3225
   not match the one required for the requested action (e.g. the
 
3226
   serial number does not match). */
 
3227
static gpg_error_t 
 
3228
do_auth (app_t app, const char *keyidstr,
 
3229
         gpg_error_t (*pincb)(void*, const char *, char **),
 
3230
         void *pincb_arg,
 
3231
         const void *indata, size_t indatalen,
 
3232
         unsigned char **outdata, size_t *outdatalen )
 
3233
{
 
3234
  int rc;
 
3235
  unsigned char tmp_sn[20]; /* Actually 16 but we use it also for the fpr. */
 
3236
  const char *s;
 
3237
  int n;
 
3238
  const char *fpr = NULL;
 
3239
 
 
3240
  if (!keyidstr || !*keyidstr)
 
3241
    return gpg_error (GPG_ERR_INV_VALUE);
 
3242
  if (indatalen > 101) /* For a 2048 bit key. */
 
3243
    return gpg_error (GPG_ERR_INV_VALUE);
 
3244
 
 
3245
  /* Check whether an OpenPGP card of any version has been requested. */
 
3246
  if (!strcmp (keyidstr, "OPENPGP.3"))
 
3247
    ;
 
3248
  else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
 
3249
    return gpg_error (GPG_ERR_INV_ID);
 
3250
  else
 
3251
    {
 
3252
      for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
 
3253
        ;
 
3254
      if (n != 32)
 
3255
        return gpg_error (GPG_ERR_INV_ID);
 
3256
      else if (!*s)
 
3257
        ; /* no fingerprint given: we allow this for now. */
 
3258
      else if (*s == '/')
 
3259
        fpr = s + 1; 
 
3260
      else
 
3261
        return gpg_error (GPG_ERR_INV_ID);
 
3262
 
 
3263
      for (s=keyidstr, n=0; n < 16; s += 2, n++)
 
3264
        tmp_sn[n] = xtoi_2 (s);
 
3265
      
 
3266
      if (app->serialnolen != 16)
 
3267
        return gpg_error (GPG_ERR_INV_CARD);
 
3268
      if (memcmp (app->serialno, tmp_sn, 16))
 
3269
        return gpg_error (GPG_ERR_WRONG_CARD);
 
3270
    }
 
3271
 
 
3272
  /* If a fingerprint has been specified check it against the one on
 
3273
     the card.  This is allows for a meaningful error message in case
 
3274
     the key on the card has been replaced but the shadow information
 
3275
     known to gpg was not updated.  If there is no fingerprint, gpg
 
3276
     will detect a bogus signature anyway due to the
 
3277
     verify-after-signing feature. */
 
3278
  rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
 
3279
  if (rc)
 
3280
    return rc;
 
3281
 
 
3282
  rc = verify_chv2 (app, pincb, pincb_arg);
 
3283
  if (!rc)
 
3284
    {
 
3285
      int exmode, le_value;
 
3286
 
 
3287
      if (app->app_local->cardcap.ext_lc_le)
 
3288
        {
 
3289
          exmode = 1;    /* Use extended length.  */
 
3290
          le_value = app->app_local->extcap.max_rsp_data;
 
3291
        }
 
3292
      else
 
3293
        {
 
3294
          exmode = 0;
 
3295
          le_value = 0; 
 
3296
        }
 
3297
      rc = iso7816_internal_authenticate (app->slot, exmode,
 
3298
                                          indata, indatalen, le_value,
 
3299
                                          outdata, outdatalen);
 
3300
    }
 
3301
  return rc;
 
3302
}
 
3303
 
 
3304
 
 
3305
static gpg_error_t 
 
3306
do_decipher (app_t app, const char *keyidstr,
 
3307
             gpg_error_t (*pincb)(void*, const char *, char **),
 
3308
             void *pincb_arg,
 
3309
             const void *indata, size_t indatalen,
 
3310
             unsigned char **outdata, size_t *outdatalen )
 
3311
{
 
3312
  int rc;
 
3313
  unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
 
3314
  const char *s;
 
3315
  int n;
 
3316
  const char *fpr = NULL;
 
3317
  int exmode, le_value;
 
3318
 
 
3319
  if (!keyidstr || !*keyidstr || !indatalen)
 
3320
    return gpg_error (GPG_ERR_INV_VALUE);
 
3321
 
 
3322
  /* Check whether an OpenPGP card of any version has been requested. */
 
3323
  if (!strcmp (keyidstr, "OPENPGP.2"))
 
3324
    ;
 
3325
  else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
 
3326
    return gpg_error (GPG_ERR_INV_ID);
 
3327
  else
 
3328
    {
 
3329
      for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
 
3330
        ;
 
3331
      if (n != 32)
 
3332
        return gpg_error (GPG_ERR_INV_ID);
 
3333
      else if (!*s)
 
3334
        ; /* no fingerprint given: we allow this for now. */
 
3335
      else if (*s == '/')
 
3336
        fpr = s + 1; 
 
3337
      else
 
3338
        return gpg_error (GPG_ERR_INV_ID);
 
3339
      
 
3340
      for (s=keyidstr, n=0; n < 16; s += 2, n++)
 
3341
        tmp_sn[n] = xtoi_2 (s);
 
3342
      
 
3343
      if (app->serialnolen != 16)
 
3344
        return gpg_error (GPG_ERR_INV_CARD);
 
3345
      if (memcmp (app->serialno, tmp_sn, 16))
 
3346
        return gpg_error (GPG_ERR_WRONG_CARD);
 
3347
    }
 
3348
 
 
3349
  /* If a fingerprint has been specified check it against the one on
 
3350
     the card.  This is allows for a meaningful error message in case
 
3351
     the key on the card has been replaced but the shadow information
 
3352
     known to gpg was not updated.  If there is no fingerprint, the
 
3353
     decryption won't produce the right plaintext anyway. */
 
3354
  rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0;
 
3355
  if (rc)
 
3356
    return rc;
 
3357
 
 
3358
  rc = verify_chv2 (app, pincb, pincb_arg);
 
3359
  if (!rc)
 
3360
    {
 
3361
      size_t fixuplen;
 
3362
      unsigned char *fixbuf = NULL;
 
3363
      int padind = 0;
 
3364
 
 
3365
      /* We might encounter a couple of leading zeroes in the
 
3366
         cryptogram.  Due to internal use of MPIs thease leading
 
3367
         zeroes are stripped.  However the OpenPGP card expects
 
3368
         exactly 128 bytes for the cryptogram (for a 1k key).  Thus we
 
3369
         need to fix it up.  We do this for up to 16 leading zero
 
3370
         bytes; a cryptogram with more than this is with a very high
 
3371
         probability anyway broken.  */
 
3372
      if (indatalen >= (128-16) && indatalen < 128)      /* 1024 bit key.  */
 
3373
        fixuplen = 128 - indatalen;
 
3374
      else if (indatalen >= (192-16) && indatalen < 192) /* 1536 bit key.  */
 
3375
        fixuplen = 192 - indatalen;
 
3376
      else if (indatalen >= (256-16) && indatalen < 256) /* 2048 bit key.  */
 
3377
        fixuplen = 256 - indatalen;
 
3378
      else if (indatalen >= (384-16) && indatalen < 384) /* 3072 bit key.  */
 
3379
        fixuplen = 384 - indatalen;
 
3380
      else
 
3381
        fixuplen = 0;
 
3382
 
 
3383
      if (fixuplen)
 
3384
        {
 
3385
          /* While we have to prepend stuff anyway, we can also
 
3386
             include the padding byte here so that iso1816_decipher
 
3387
             does not need to do another data mangling.  */
 
3388
          fixuplen++;
 
3389
 
 
3390
          fixbuf = xtrymalloc (fixuplen + indatalen);
 
3391
          if (!fixbuf)
 
3392
            return gpg_error_from_syserror ();
 
3393
          
 
3394
          memset (fixbuf, 0, fixuplen);
 
3395
          memcpy (fixbuf+fixuplen, indata, indatalen);
 
3396
          indata = fixbuf;
 
3397
          indatalen = fixuplen + indatalen;
 
3398
          padind = -1; /* Already padded.  */
 
3399
        }
 
3400
 
 
3401
      if (app->app_local->cardcap.ext_lc_le && indatalen > 254 )
 
3402
        {
 
3403
          exmode = 1;    /* Extended length w/o a limit.  */
 
3404
          le_value = app->app_local->extcap.max_rsp_data;
 
3405
        }
 
3406
      else if (app->app_local->cardcap.cmd_chaining && indatalen > 254)
 
3407
        {
 
3408
          exmode = -254; /* Command chaining with max. 254 bytes.  */
 
3409
          le_value = 0;
 
3410
        }
 
3411
      else
 
3412
        exmode = le_value = 0;    
 
3413
 
 
3414
      rc = iso7816_decipher (app->slot, exmode, 
 
3415
                             indata, indatalen, le_value, padind,
 
3416
                             outdata, outdatalen);
 
3417
      xfree (fixbuf);
 
3418
    }
 
3419
 
 
3420
  return rc;
 
3421
}
 
3422
 
 
3423
 
 
3424
/* Perform a simple verify operation for CHV1 and CHV2, so that
 
3425
   further operations won't ask for CHV2 and it is possible to do a
 
3426
   cheap check on the PIN: If there is something wrong with the PIN
 
3427
   entry system, only the regular CHV will get blocked and not the
 
3428
   dangerous CHV3.  KEYIDSTR is the usual card's serial number; an
 
3429
   optional fingerprint part will be ignored.
 
3430
 
 
3431
   There is a special mode if the keyidstr is "<serialno>[CHV3]" with
 
3432
   the "[CHV3]" being a literal string:  The Admin Pin is checked if
 
3433
   and only if the retry counter is still at 3. */
 
3434
static gpg_error_t 
 
3435
do_check_pin (app_t app, const char *keyidstr,
 
3436
              gpg_error_t (*pincb)(void*, const char *, char **),
 
3437
              void *pincb_arg)
 
3438
{
 
3439
  unsigned char tmp_sn[20]; 
 
3440
  const char *s;
 
3441
  int n;
 
3442
  int admin_pin = 0;
 
3443
 
 
3444
  if (!keyidstr || !*keyidstr)
 
3445
    return gpg_error (GPG_ERR_INV_VALUE);
 
3446
 
 
3447
  /* Check whether an OpenPGP card of any version has been requested. */
 
3448
  if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
 
3449
    return gpg_error (GPG_ERR_INV_ID);
 
3450
  
 
3451
  for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
 
3452
    ;
 
3453
  if (n != 32)
 
3454
    return gpg_error (GPG_ERR_INV_ID);
 
3455
  else if (!*s)
 
3456
    ; /* No fingerprint given: we allow this for now. */
 
3457
  else if (*s == '/')
 
3458
    ; /* We ignore a fingerprint. */
 
3459
  else if (!strcmp (s, "[CHV3]") )
 
3460
    admin_pin = 1;
 
3461
  else
 
3462
    return gpg_error (GPG_ERR_INV_ID);
 
3463
 
 
3464
  for (s=keyidstr, n=0; n < 16; s += 2, n++)
 
3465
    tmp_sn[n] = xtoi_2 (s);
 
3466
 
 
3467
  if (app->serialnolen != 16)
 
3468
    return gpg_error (GPG_ERR_INV_CARD);
 
3469
  if (memcmp (app->serialno, tmp_sn, 16))
 
3470
    return gpg_error (GPG_ERR_WRONG_CARD);
 
3471
 
 
3472
  /* Yes, there is a race conditions: The user might pull the card
 
3473
     right here and we won't notice that.  However this is not a
 
3474
     problem and the check above is merely for a graceful failure
 
3475
     between operations. */
 
3476
 
 
3477
  if (admin_pin)
 
3478
    {
 
3479
      void *relptr;
 
3480
      unsigned char *value;
 
3481
      size_t valuelen;
 
3482
      int count;
 
3483
      
 
3484
      relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
 
3485
      if (!relptr || valuelen < 7)
 
3486
        {
 
3487
          log_error (_("error retrieving CHV status from card\n"));
 
3488
          xfree (relptr);
 
3489
          return gpg_error (GPG_ERR_CARD);
 
3490
        }
 
3491
      count = value[6];
 
3492
      xfree (relptr);
 
3493
 
 
3494
      if (!count)
 
3495
        {
 
3496
          log_info (_("card is permanently locked!\n"));
 
3497
          return gpg_error (GPG_ERR_BAD_PIN);
 
3498
        }
 
3499
      else if (value[6] < 3)
 
3500
        {
 
3501
          log_info (_("verification of Admin PIN is currently prohibited "
 
3502
                      "through this command\n"));
 
3503
          return gpg_error (GPG_ERR_GENERAL);
 
3504
        }
 
3505
 
 
3506
      app->did_chv3 = 0; /* Force verification.  */
 
3507
      return verify_chv3 (app, pincb, pincb_arg);
 
3508
    }
 
3509
  else
 
3510
    return verify_chv2 (app, pincb, pincb_arg);
 
3511
}
 
3512
 
 
3513
 
 
3514
/* Show information about card capabilities.  */
 
3515
static void
 
3516
show_caps (struct app_local_s *s)
 
3517
{
 
3518
  log_info ("Version-2 ......: %s\n", s->extcap.is_v2? "yes":"no");
 
3519
  log_info ("Get-Challenge ..: %s", s->extcap.get_challenge? "yes":"no");
 
3520
  if (s->extcap.get_challenge)
 
3521
    log_printf (" (%u bytes max)", s->extcap.max_get_challenge);
 
3522
  log_info ("Key-Import .....: %s\n", s->extcap.key_import? "yes":"no");
 
3523
  log_info ("Change-Force-PW1: %s\n", s->extcap.change_force_chv? "yes":"no");
 
3524
  log_info ("Private-DOs ....: %s\n", s->extcap.private_dos? "yes":"no");
 
3525
  log_info ("Algo-Attr-Change: %s\n", s->extcap.algo_attr_change? "yes":"no");
 
3526
  log_info ("SM-Support .....: %s", s->extcap.sm_supported? "yes":"no");
 
3527
  if (s->extcap.sm_supported)
 
3528
    log_printf (" (%s)", s->extcap.sm_aes128? "AES-128":"3DES");
 
3529
  log_info ("Max-Cert3-Len ..: %u\n", s->extcap.max_certlen_3);
 
3530
  log_info ("Max-Cmd-Data ...: %u\n", s->extcap.max_cmd_data);
 
3531
  log_info ("Max-Rsp-Data ...: %u\n", s->extcap.max_rsp_data);
 
3532
  log_info ("Cmd-Chaining ...: %s\n", s->cardcap.cmd_chaining?"yes":"no");
 
3533
  log_info ("Ext-Lc-Le ......: %s\n", s->cardcap.ext_lc_le?"yes":"no");
 
3534
  log_info ("Status Indicator: %02X\n", s->status_indicator);
 
3535
 
 
3536
  log_info ("GnuPG-No-Sync ..: %s\n",  s->flags.no_sync? "yes":"no");
 
3537
  log_info ("GnuPG-Def-PW2 ..: %s\n",  s->flags.def_chv2? "yes":"no");
 
3538
}
 
3539
 
 
3540
 
 
3541
/* Parse the historical bytes in BUFFER of BUFLEN and store them in
 
3542
   APPLOC.  */
 
3543
static void
 
3544
parse_historical (struct app_local_s *apploc, 
 
3545
                  const unsigned char * buffer, size_t buflen)
 
3546
{
 
3547
  /* Example buffer: 00 31 C5 73 C0 01 80 00 90 00  */
 
3548
  if (buflen < 4)
 
3549
    {
 
3550
      log_error ("warning: historical bytes are too short\n");
 
3551
      return; /* Too short.  */
 
3552
    }
 
3553
  if (*buffer)
 
3554
    {
 
3555
      log_error ("warning: bad category indicator in historical bytes\n");
 
3556
      return; 
 
3557
    }
 
3558
  
 
3559
  /* Skip category indicator.  */
 
3560
  buffer++;
 
3561
  buflen--;
 
3562
 
 
3563
  /* Get the status indicator.  */
 
3564
  apploc->status_indicator = buffer[buflen-3];
 
3565
  buflen -= 3;
 
3566
 
 
3567
  /* Parse the compact TLV.  */
 
3568
  while (buflen)
 
3569
    {
 
3570
      unsigned int tag = (*buffer & 0xf0) >> 4;
 
3571
      unsigned int len = (*buffer & 0x0f);
 
3572
      if (len+1 > buflen)
 
3573
        {
 
3574
          log_error ("warning: bad Compact-TLV in historical bytes\n");
 
3575
          return; /* Error.  */
 
3576
        }
 
3577
      buffer++;
 
3578
      buflen--;
 
3579
      if (tag == 7 && len == 3)
 
3580
        {
 
3581
          /* Card capabilities.  */
 
3582
          apploc->cardcap.cmd_chaining = !!(buffer[2] & 0x80);
 
3583
          apploc->cardcap.ext_lc_le    = !!(buffer[2] & 0x40);
 
3584
        }
 
3585
      buffer += len;
 
3586
      buflen -= len;
 
3587
    }
 
3588
}
 
3589
 
 
3590
 
 
3591
/* Parse and optionally show the algorithm attributes for KEYNO.
 
3592
   KEYNO must be in the range 0..2.  */
 
3593
static void 
 
3594
parse_algorithm_attribute (app_t app, int keyno)
 
3595
 
3596
  unsigned char *buffer;
 
3597
  size_t buflen;
 
3598
  void *relptr;
 
3599
  const char const desc[3][5] = {"sign", "encr", "auth"};
 
3600
 
 
3601
  assert (keyno >=0 && keyno <= 2);
 
3602
 
 
3603
  app->app_local->keyattr[keyno].n_bits = 0;
 
3604
      
 
3605
  relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL);
 
3606
  if (!relptr)
 
3607
    {
 
3608
      log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
 
3609
      return;
 
3610
    }
 
3611
  if (buflen < 1)
 
3612
    {
 
3613
      log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
 
3614
      xfree (relptr);
 
3615
      return;
 
3616
    }
 
3617
 
 
3618
  if (opt.verbose)
 
3619
    log_info ("Key-Attr-%s ..: ", desc[keyno]);
 
3620
  if (*buffer == 1 && (buflen == 5 || buflen == 6))
 
3621
    {
 
3622
      app->app_local->keyattr[keyno].n_bits = (buffer[1]<<8 | buffer[2]);
 
3623
      app->app_local->keyattr[keyno].e_bits = (buffer[3]<<8 | buffer[4]);
 
3624
      app->app_local->keyattr[keyno].format = 0;
 
3625
      if (buflen < 6)
 
3626
        app->app_local->keyattr[keyno].format = RSA_STD;
 
3627
      else
 
3628
        app->app_local->keyattr[keyno].format = (buffer[5] == 0? RSA_STD   :
 
3629
                                                 buffer[5] == 1? RSA_STD_N :
 
3630
                                                 buffer[5] == 2? RSA_CRT   :
 
3631
                                                 buffer[5] == 3? RSA_CRT_N : 
 
3632
                                                 RSA_UNKNOWN_FMT);
 
3633
 
 
3634
      if (opt.verbose)
 
3635
        log_printf
 
3636
          ("RSA, n=%u, e=%u, fmt=%s\n",
 
3637
           app->app_local->keyattr[keyno].n_bits,
 
3638
           app->app_local->keyattr[keyno].e_bits,
 
3639
           app->app_local->keyattr[keyno].format == RSA_STD?  "std"  :
 
3640
           app->app_local->keyattr[keyno].format == RSA_STD_N?"std+n":
 
3641
           app->app_local->keyattr[keyno].format == RSA_CRT?  "crt"  :
 
3642
           app->app_local->keyattr[keyno].format == RSA_CRT_N?"crt+n":"?");
 
3643
    }
 
3644
  else if (opt.verbose)
 
3645
    log_printhex ("", buffer, buflen);
 
3646
 
 
3647
  xfree (relptr);
 
3648
}
 
3649
 
 
3650
/* Select the OpenPGP application on the card in SLOT.  This function
 
3651
   must be used before any other OpenPGP application functions. */
 
3652
gpg_error_t
 
3653
app_select_openpgp (app_t app)
 
3654
{
 
3655
  static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
 
3656
  int slot = app->slot;
 
3657
  int rc;
 
3658
  unsigned char *buffer;
 
3659
  size_t buflen;
 
3660
  void *relptr;
 
3661
  
 
3662
  /* Note that the card can't cope with P2=0xCO, thus we need to pass a
 
3663
     special flag value. */
 
3664
  rc = iso7816_select_application (slot, aid, sizeof aid, 0x0001);
 
3665
  if (!rc)
 
3666
    {
 
3667
      unsigned int manufacturer;
 
3668
 
 
3669
      app->apptype = "OPENPGP";
 
3670
 
 
3671
      app->did_chv1 = 0;
 
3672
      app->did_chv2 = 0;
 
3673
      app->did_chv3 = 0;
 
3674
      app->app_local = NULL;
 
3675
 
 
3676
      /* The OpenPGP card returns the serial number as part of the
 
3677
         AID; because we prefer to use OpenPGP serial numbers, we
 
3678
         replace a possibly already set one from a EF.GDO with this
 
3679
         one.  Note, that for current OpenPGP cards, no EF.GDO exists
 
3680
         and thus it won't matter at all. */
 
3681
      rc = iso7816_get_data (slot, 0, 0x004F, &buffer, &buflen);
 
3682
      if (rc)
 
3683
        goto leave;
 
3684
      if (opt.verbose)
 
3685
        {
 
3686
          log_info ("AID: ");
 
3687
          log_printhex ("", buffer, buflen);
 
3688
        }
 
3689
 
 
3690
      app->card_version = buffer[6] << 8;
 
3691
      app->card_version |= buffer[7];
 
3692
      manufacturer = (buffer[8]<<8 | buffer[9]);
 
3693
 
 
3694
      xfree (app->serialno);
 
3695
      app->serialno = buffer;
 
3696
      app->serialnolen = buflen;
 
3697
      buffer = NULL;
 
3698
      app->app_local = xtrycalloc (1, sizeof *app->app_local);
 
3699
      if (!app->app_local)
 
3700
        {
 
3701
          rc = gpg_error (gpg_err_code_from_errno (errno));
 
3702
          goto leave;
 
3703
        }
 
3704
 
 
3705
      if (app->card_version >= 0x0200)
 
3706
        app->app_local->extcap.is_v2 = 1;
 
3707
 
 
3708
 
 
3709
      /* Read the historical bytes.  */
 
3710
      relptr = get_one_do (app, 0x5f52, &buffer, &buflen, NULL);
 
3711
      if (relptr)
 
3712
        {
 
3713
          if (opt.verbose)
 
3714
            {
 
3715
              log_info ("Historical Bytes: ");
 
3716
              log_printhex ("", buffer, buflen);
 
3717
            }
 
3718
          parse_historical (app->app_local, buffer, buflen);
 
3719
          xfree (relptr);
 
3720
        }
 
3721
 
 
3722
      /* Read the force-chv1 flag.  */
 
3723
      relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL);
 
3724
      if (!relptr)
 
3725
        {
 
3726
          log_error (_("can't access %s - invalid OpenPGP card?\n"),
 
3727
                     "CHV Status Bytes");
 
3728
          goto leave;
 
3729
        }
 
3730
      app->force_chv1 = (buflen && *buffer == 0);
 
3731
      xfree (relptr);
 
3732
 
 
3733
      /* Read the extended capabilities.  */
 
3734
      relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL);
 
3735
      if (!relptr)
 
3736
        {
 
3737
          log_error (_("can't access %s - invalid OpenPGP card?\n"),
 
3738
                     "Extended Capability Flags" );
 
3739
          goto leave;
 
3740
        }
 
3741
      if (buflen)
 
3742
        {
 
3743
          app->app_local->extcap.sm_supported     = !!(*buffer & 0x80);
 
3744
          app->app_local->extcap.get_challenge    = !!(*buffer & 0x40);
 
3745
          app->app_local->extcap.key_import       = !!(*buffer & 0x20);
 
3746
          app->app_local->extcap.change_force_chv = !!(*buffer & 0x10);
 
3747
          app->app_local->extcap.private_dos      = !!(*buffer & 0x08);
 
3748
          app->app_local->extcap.algo_attr_change = !!(*buffer & 0x04);
 
3749
        }
 
3750
      if (buflen >= 10)
 
3751
        {
 
3752
          /* Available with v2 cards.  */
 
3753
          app->app_local->extcap.sm_aes128     = (buffer[1] == 1);
 
3754
          app->app_local->extcap.max_get_challenge 
 
3755
                                               = (buffer[2] << 8 | buffer[3]);
 
3756
          app->app_local->extcap.max_certlen_3 = (buffer[4] << 8 | buffer[5]);
 
3757
          app->app_local->extcap.max_cmd_data  = (buffer[6] << 8 | buffer[7]);
 
3758
          app->app_local->extcap.max_rsp_data  = (buffer[8] << 8 | buffer[9]);
 
3759
        }
 
3760
      xfree (relptr);
 
3761
 
 
3762
      /* Some of the first cards accidently don't set the
 
3763
         CHANGE_FORCE_CHV bit but allow it anyway. */
 
3764
      if (app->card_version <= 0x0100 && manufacturer == 1)
 
3765
        app->app_local->extcap.change_force_chv = 1;
 
3766
 
 
3767
      parse_login_data (app);
 
3768
 
 
3769
      if (opt.verbose)
 
3770
        show_caps (app->app_local);
 
3771
 
 
3772
      parse_algorithm_attribute (app, 0);
 
3773
      parse_algorithm_attribute (app, 1);
 
3774
      parse_algorithm_attribute (app, 2);
 
3775
      
 
3776
      if (opt.verbose > 1)
 
3777
        dump_all_do (slot);
 
3778
 
 
3779
      app->fnc.deinit = do_deinit;
 
3780
      app->fnc.learn_status = do_learn_status;
 
3781
      app->fnc.readcert = do_readcert;
 
3782
      app->fnc.readkey = do_readkey;
 
3783
      app->fnc.getattr = do_getattr;
 
3784
      app->fnc.setattr = do_setattr;
 
3785
      app->fnc.writecert = do_writecert;
 
3786
      app->fnc.writekey = do_writekey;
 
3787
      app->fnc.genkey = do_genkey;
 
3788
      app->fnc.sign = do_sign;
 
3789
      app->fnc.auth = do_auth;
 
3790
      app->fnc.decipher = do_decipher;
 
3791
      app->fnc.change_pin = do_change_pin;
 
3792
      app->fnc.check_pin = do_check_pin;
 
3793
   }
 
3794
 
 
3795
leave:
 
3796
  if (rc)
 
3797
    do_deinit (app);
 
3798
  return rc;
 
3799
}
 
3800
 
 
3801
 
 
3802