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