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