LCOV - code coverage report
Current view: top level - scd - app-openpgp.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 0 2141 0.0 %
Date: 2016-09-12 13:01:59 Functions: 0 54 0.0 %

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

Generated by: LCOV version 1.11