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