LCOV - code coverage report
Current view: top level - scd - app-openpgp.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 0 2116 0.0 %
Date: 2015-11-05 17:10: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 soley indicated by the
    1227             :    presence of the app->app_local->pk[KEYNO].key field.
    1228             : 
    1229             :    Note that GnuPG 1.x does not need this and it would be too time
    1230             :    consuming to send it just for the fun of it. However, given that we
    1231             :    use the same code in gpg 1.4, we can't use the gcry S-expresion
    1232             :    here but need to open encode it. */
    1233             : #if GNUPG_MAJOR_VERSION > 1
    1234             : static gpg_error_t
    1235           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 0;
    1472             : }
    1473             : #endif /* GNUPG_MAJOR_VERSION > 1 */
    1474             : 
    1475             : 
    1476             : 
    1477             : /* Send the KEYPAIRINFO back. KEY needs to be in the range [1,3].
    1478             :    This is used by the LEARN command. */
    1479             : static gpg_error_t
    1480           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             :      relativly 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 possibile by
    1679             :    using a pinpad.  PINCB and PINCB_ARG describe the usual callback
    1680             :    for the pinentry.  CHVNO must be either 1 or 2. SIGCOUNT is only
    1681             :    used with CHV1.  PINVALUE is the address of a pointer which will
    1682             :    receive a newly allocated block with the actual PIN (this is useful
    1683             :    in case that PIN shall be used for another verify operation).  The
    1684             :    caller needs to free this value.  If the function returns with
    1685             :    success and NULL is stored at PINVALUE, the caller should take this
    1686             :    as an indication that the pinpad has been used.
    1687             :    */
    1688             : static gpg_error_t
    1689           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(_("%d Admin PIN attempts remaining before card"
    1878             :              " is permanently locked\n"), remaining);
    1879             : 
    1880           0 :   if (remaining < 3)
    1881             :     {
    1882             :       /* TRANSLATORS: Do not translate the "|A|" prefix but keep it at
    1883             :          the start of the string.  Use %%0A to force a linefeed.  */
    1884           0 :       prompt = xtryasprintf (_("|A|Please enter the Admin PIN%%0A"
    1885             :                                "[remaining attempts: %d]"), remaining);
    1886             :     }
    1887             :   else
    1888           0 :     prompt = xtrystrdup (_("|A|Please enter the Admin PIN"));
    1889             : 
    1890           0 :   if (!prompt)
    1891           0 :     return gpg_error_from_syserror ();
    1892             : 
    1893           0 :   *r_prompt = prompt;
    1894           0 :   return 0;
    1895             : }
    1896             : 
    1897             : 
    1898             : /* Verify CHV3 if required. */
    1899             : static gpg_error_t
    1900           0 : verify_chv3 (app_t app,
    1901             :              gpg_error_t (*pincb)(void*, const char *, char **),
    1902             :              void *pincb_arg)
    1903             : {
    1904           0 :   int rc = 0;
    1905             : 
    1906             : #if GNUPG_MAJOR_VERSION != 1
    1907           0 :   if (!opt.allow_admin)
    1908             :     {
    1909           0 :       log_info (_("access to admin commands is not configured\n"));
    1910           0 :       return gpg_error (GPG_ERR_EACCES);
    1911             :     }
    1912             : #endif
    1913             : 
    1914           0 :   if (!app->did_chv3)
    1915             :     {
    1916             :       pininfo_t pininfo;
    1917           0 :       int minlen = 8;
    1918             :       char *prompt;
    1919             : 
    1920           0 :       memset (&pininfo, 0, sizeof pininfo);
    1921           0 :       pininfo.fixedlen = -1;
    1922           0 :       pininfo.minlen = minlen;
    1923             : 
    1924           0 :       rc = build_enter_admin_pin_prompt (app, &prompt);
    1925           0 :       if (rc)
    1926           0 :         return rc;
    1927             : 
    1928           0 :       if (!opt.disable_pinpad
    1929           0 :           && !iso7816_check_pinpad (app->slot, ISO7816_VERIFY, &pininfo)
    1930           0 :           && !check_pinpad_request (app, &pininfo, 1))
    1931             :         {
    1932             :           /* The reader supports the verify command through the pinpad. */
    1933           0 :           rc = pincb (pincb_arg, prompt, NULL);
    1934           0 :           xfree (prompt);
    1935           0 :           prompt = NULL;
    1936           0 :           if (rc)
    1937             :             {
    1938           0 :               log_info (_("PIN callback returned error: %s\n"),
    1939             :                         gpg_strerror (rc));
    1940           0 :               return rc;
    1941             :             }
    1942           0 :           rc = iso7816_verify_kp (app->slot, 0x83, &pininfo);
    1943             :           /* Dismiss the prompt. */
    1944           0 :           pincb (pincb_arg, NULL, NULL);
    1945             :         }
    1946             :       else
    1947             :         {
    1948             :           char *pinvalue;
    1949             : 
    1950           0 :           rc = pincb (pincb_arg, prompt, &pinvalue);
    1951           0 :           xfree (prompt);
    1952           0 :           prompt = NULL;
    1953           0 :           if (rc)
    1954             :             {
    1955           0 :               log_info (_("PIN callback returned error: %s\n"),
    1956             :                         gpg_strerror (rc));
    1957           0 :               return rc;
    1958             :             }
    1959             : 
    1960           0 :           if (strlen (pinvalue) < minlen)
    1961             :             {
    1962           0 :               log_error (_("PIN for CHV%d is too short;"
    1963             :                            " minimum length is %d\n"), 3, minlen);
    1964           0 :               xfree (pinvalue);
    1965           0 :               return gpg_error (GPG_ERR_BAD_PIN);
    1966             :             }
    1967             : 
    1968           0 :           rc = iso7816_verify (app->slot, 0x83, pinvalue, strlen (pinvalue));
    1969           0 :           xfree (pinvalue);
    1970             :         }
    1971             : 
    1972           0 :       if (rc)
    1973             :         {
    1974           0 :           log_error (_("verify CHV%d failed: %s\n"), 3, gpg_strerror (rc));
    1975           0 :           flush_cache_after_error (app);
    1976           0 :           return rc;
    1977             :         }
    1978           0 :       app->did_chv3 = 1;
    1979             :     }
    1980           0 :   return rc;
    1981             : }
    1982             : 
    1983             : 
    1984             : /* Handle the SETATTR operation. All arguments are already basically
    1985             :    checked. */
    1986             : static gpg_error_t
    1987           0 : do_setattr (app_t app, const char *name,
    1988             :             gpg_error_t (*pincb)(void*, const char *, char **),
    1989             :             void *pincb_arg,
    1990             :             const unsigned char *value, size_t valuelen)
    1991             : {
    1992             :   gpg_error_t rc;
    1993             :   int idx;
    1994             :   static struct {
    1995             :     const char *name;
    1996             :     int tag;
    1997             :     int need_chv;
    1998             :     int special;
    1999             :     unsigned int need_v2:1;
    2000             :   } table[] = {
    2001             :     { "DISP-NAME",    0x005B, 3 },
    2002             :     { "LOGIN-DATA",   0x005E, 3, 2 },
    2003             :     { "DISP-LANG",    0x5F2D, 3 },
    2004             :     { "DISP-SEX",     0x5F35, 3 },
    2005             :     { "PUBKEY-URL",   0x5F50, 3 },
    2006             :     { "CHV-STATUS-1", 0x00C4, 3, 1 },
    2007             :     { "CA-FPR-1",     0x00CA, 3 },
    2008             :     { "CA-FPR-2",     0x00CB, 3 },
    2009             :     { "CA-FPR-3",     0x00CC, 3 },
    2010             :     { "PRIVATE-DO-1", 0x0101, 2 },
    2011             :     { "PRIVATE-DO-2", 0x0102, 3 },
    2012             :     { "PRIVATE-DO-3", 0x0103, 2 },
    2013             :     { "PRIVATE-DO-4", 0x0104, 3 },
    2014             :     { "CERT-3",       0x7F21, 3, 0, 1 },
    2015             :     { "SM-KEY-ENC",   0x00D1, 3, 0, 1 },
    2016             :     { "SM-KEY-MAC",   0x00D2, 3, 0, 1 },
    2017             :     { "KEY-ATTR",     0,      0, 3, 1 },
    2018             :     { "AESKEY",       0x00D5, 3, 0, 1 },
    2019             :     { NULL, 0 }
    2020             :   };
    2021             :   int exmode;
    2022             : 
    2023           0 :   for (idx=0; table[idx].name && strcmp (table[idx].name, name); idx++)
    2024             :     ;
    2025           0 :   if (!table[idx].name)
    2026           0 :     return gpg_error (GPG_ERR_INV_NAME);
    2027           0 :   if (table[idx].need_v2 && !app->app_local->extcap.is_v2)
    2028           0 :     return gpg_error (GPG_ERR_NOT_SUPPORTED); /* Not yet supported.  */
    2029             : 
    2030           0 :   if (table[idx].special == 3)
    2031           0 :     return change_keyattr_from_string (app, pincb, pincb_arg, value, valuelen);
    2032             : 
    2033           0 :   switch (table[idx].need_chv)
    2034             :     {
    2035             :     case 2:
    2036           0 :       rc = verify_chv2 (app, pincb, pincb_arg);
    2037           0 :       break;
    2038             :     case 3:
    2039           0 :       rc = verify_chv3 (app, pincb, pincb_arg);
    2040           0 :       break;
    2041             :     default:
    2042           0 :       rc = 0;
    2043             :     }
    2044           0 :   if (rc)
    2045           0 :     return rc;
    2046             : 
    2047             :   /* Flush the cache before writing it, so that the next get operation
    2048             :      will reread the data from the card and thus get synced in case of
    2049             :      errors (e.g. data truncated by the card). */
    2050           0 :   flush_cache_item (app, table[idx].tag);
    2051             : 
    2052           0 :   if (app->app_local->cardcap.ext_lc_le && valuelen > 254)
    2053           0 :     exmode = 1;    /* Use extended length w/o a limit.  */
    2054           0 :   else if (app->app_local->cardcap.cmd_chaining && valuelen > 254)
    2055           0 :     exmode = -254; /* Command chaining with max. 254 bytes.  */
    2056             :   else
    2057           0 :     exmode = 0;
    2058           0 :   rc = iso7816_put_data (app->slot, exmode, table[idx].tag, value, valuelen);
    2059           0 :   if (rc)
    2060           0 :     log_error ("failed to set '%s': %s\n", table[idx].name, gpg_strerror (rc));
    2061             : 
    2062           0 :   if (table[idx].special == 1)
    2063           0 :     app->force_chv1 = (valuelen && *value == 0);
    2064           0 :   else if (table[idx].special == 2)
    2065           0 :     parse_login_data (app);
    2066             : 
    2067           0 :   return rc;
    2068             : }
    2069             : 
    2070             : 
    2071             : /* Handle the WRITECERT command for OpenPGP.  This rites the standard
    2072             :    certifciate to the card; CERTID needs to be set to "OPENPGP.3".
    2073             :    PINCB and PINCB_ARG are the usual arguments for the pinentry
    2074             :    callback.  */
    2075             : static gpg_error_t
    2076           0 : do_writecert (app_t app, ctrl_t ctrl,
    2077             :               const char *certidstr,
    2078             :               gpg_error_t (*pincb)(void*, const char *, char **),
    2079             :               void *pincb_arg,
    2080             :               const unsigned char *certdata, size_t certdatalen)
    2081             : {
    2082             :   (void)ctrl;
    2083             : #if GNUPG_MAJOR_VERSION > 1
    2084           0 :   if (strcmp (certidstr, "OPENPGP.3"))
    2085           0 :     return gpg_error (GPG_ERR_INV_ID);
    2086           0 :   if (!certdata || !certdatalen)
    2087           0 :     return gpg_error (GPG_ERR_INV_ARG);
    2088           0 :   if (!app->app_local->extcap.is_v2)
    2089           0 :     return gpg_error (GPG_ERR_NOT_SUPPORTED);
    2090           0 :   if (certdatalen > app->app_local->extcap.max_certlen_3)
    2091           0 :     return gpg_error (GPG_ERR_TOO_LARGE);
    2092           0 :   return do_setattr (app, "CERT-3", pincb, pincb_arg, certdata, certdatalen);
    2093             : #else
    2094             :   return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
    2095             : #endif
    2096             : }
    2097             : 
    2098             : 
    2099             : 
    2100             : /* Handle the PASSWD command.  The following combinations are
    2101             :    possible:
    2102             : 
    2103             :     Flags  CHVNO Vers.  Description
    2104             :     RESET    1   1      Verify CHV3 and set a new CHV1 and CHV2
    2105             :     RESET    1   2      Verify PW3 and set a new PW1.
    2106             :     RESET    2   1      Verify CHV3 and set a new CHV1 and CHV2.
    2107             :     RESET    2   2      Verify PW3 and set a new Reset Code.
    2108             :     RESET    3   any    Returns GPG_ERR_INV_ID.
    2109             :      -       1   1      Verify CHV2 and set a new CHV1 and CHV2.
    2110             :      -       1   2      Verify PW1 and set a new PW1.
    2111             :      -       2   1      Verify CHV2 and set a new CHV1 and CHV2.
    2112             :      -       2   2      Verify Reset Code and set a new PW1.
    2113             :      -       3   any    Verify CHV3/PW3 and set a new CHV3/PW3.
    2114             :  */
    2115             : static gpg_error_t
    2116           0 : do_change_pin (app_t app, ctrl_t ctrl,  const char *chvnostr,
    2117             :                unsigned int flags,
    2118             :                gpg_error_t (*pincb)(void*, const char *, char **),
    2119             :                void *pincb_arg)
    2120             : {
    2121           0 :   int rc = 0;
    2122           0 :   int chvno = atoi (chvnostr);
    2123           0 :   char *resetcode = NULL;
    2124           0 :   char *oldpinvalue = NULL;
    2125           0 :   char *pinvalue = NULL;
    2126           0 :   int reset_mode = !!(flags & APP_CHANGE_FLAG_RESET);
    2127           0 :   int set_resetcode = 0;
    2128             :   pininfo_t pininfo;
    2129           0 :   int use_pinpad = 0;
    2130           0 :   int minlen = 6;
    2131             : 
    2132             :   (void)ctrl;
    2133           0 :   memset (&pininfo, 0, sizeof pininfo);
    2134           0 :   pininfo.fixedlen = -1;
    2135           0 :   pininfo.minlen = minlen;
    2136             : 
    2137           0 :   if (reset_mode && chvno == 3)
    2138             :     {
    2139           0 :       rc = gpg_error (GPG_ERR_INV_ID);
    2140           0 :       goto leave;
    2141             :     }
    2142             : 
    2143           0 :   if (!app->app_local->extcap.is_v2)
    2144             :     {
    2145             :       /* Version 1 cards.  */
    2146             : 
    2147           0 :       if (reset_mode || chvno == 3)
    2148             :         {
    2149             :           /* We always require that the PIN is entered. */
    2150           0 :           app->did_chv3 = 0;
    2151           0 :           rc = verify_chv3 (app, pincb, pincb_arg);
    2152           0 :           if (rc)
    2153           0 :             goto leave;
    2154             :         }
    2155           0 :       else if (chvno == 1 || chvno == 2)
    2156           0 :         {
    2157             :           /* On a v1.x card CHV1 and CVH2 should always have the same
    2158             :              value, thus we enforce it here.  */
    2159           0 :           int save_force = app->force_chv1;
    2160             : 
    2161           0 :           app->force_chv1 = 0;
    2162           0 :           app->did_chv1 = 0;
    2163           0 :           app->did_chv2 = 0;
    2164           0 :           rc = verify_chv2 (app, pincb, pincb_arg);
    2165           0 :           app->force_chv1 = save_force;
    2166           0 :           if (rc)
    2167           0 :             goto leave;
    2168             :         }
    2169             :       else
    2170             :         {
    2171           0 :           rc = gpg_error (GPG_ERR_INV_ID);
    2172           0 :           goto leave;
    2173             :         }
    2174             :     }
    2175             :   else
    2176             :     {
    2177             :       /* Version 2 cards.  */
    2178             : 
    2179           0 :       if (!opt.disable_pinpad
    2180           0 :           && !iso7816_check_pinpad (app->slot,
    2181             :                                     ISO7816_CHANGE_REFERENCE_DATA, &pininfo)
    2182           0 :           && !check_pinpad_request (app, &pininfo, chvno == 3))
    2183           0 :         use_pinpad = 1;
    2184             : 
    2185           0 :       if (reset_mode)
    2186             :         {
    2187             :           /* To reset a PIN the Admin PIN is required. */
    2188           0 :           use_pinpad = 0;
    2189           0 :           app->did_chv3 = 0;
    2190           0 :           rc = verify_chv3 (app, pincb, pincb_arg);
    2191           0 :           if (rc)
    2192           0 :             goto leave;
    2193             : 
    2194           0 :           if (chvno == 2)
    2195           0 :             set_resetcode = 1;
    2196             :         }
    2197           0 :       else if (chvno == 1 || chvno == 3)
    2198             :         {
    2199           0 :           if (!use_pinpad)
    2200             :             {
    2201           0 :               char *promptbuf = NULL;
    2202             :               const char *prompt;
    2203             : 
    2204           0 :               if (chvno == 3)
    2205             :                 {
    2206           0 :                   minlen = 8;
    2207           0 :                   rc = build_enter_admin_pin_prompt (app, &promptbuf);
    2208           0 :                   if (rc)
    2209           0 :                     goto leave;
    2210           0 :                   prompt = promptbuf;
    2211             :                 }
    2212             :               else
    2213           0 :                 prompt = _("||Please enter the PIN");
    2214           0 :               rc = pincb (pincb_arg, prompt, &oldpinvalue);
    2215           0 :               xfree (promptbuf);
    2216           0 :               promptbuf = NULL;
    2217           0 :               if (rc)
    2218             :                 {
    2219           0 :                   log_info (_("PIN callback returned error: %s\n"),
    2220             :                             gpg_strerror (rc));
    2221           0 :                   goto leave;
    2222             :                 }
    2223             : 
    2224           0 :               if (strlen (oldpinvalue) < minlen)
    2225             :                 {
    2226           0 :                   log_info (_("PIN for CHV%d is too short;"
    2227             :                               " minimum length is %d\n"), chvno, minlen);
    2228           0 :                   rc = gpg_error (GPG_ERR_BAD_PIN);
    2229           0 :                   goto leave;
    2230             :                 }
    2231             :             }
    2232             :         }
    2233           0 :       else if (chvno == 2)
    2234             :         {
    2235             :           /* There is no PW2 for v2 cards.  We use this condition to
    2236             :              allow a PW reset using the Reset Code.  */
    2237             :           void *relptr;
    2238             :           unsigned char *value;
    2239             :           size_t valuelen;
    2240             :           int remaining;
    2241             : 
    2242           0 :           use_pinpad = 0;
    2243           0 :           minlen = 8;
    2244           0 :           relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
    2245           0 :           if (!relptr || valuelen < 7)
    2246             :             {
    2247           0 :               log_error (_("error retrieving CHV status from card\n"));
    2248           0 :               xfree (relptr);
    2249           0 :               rc = gpg_error (GPG_ERR_CARD);
    2250           0 :               goto leave;
    2251             :             }
    2252           0 :           remaining = value[5];
    2253           0 :           xfree (relptr);
    2254           0 :           if (!remaining)
    2255             :             {
    2256           0 :               log_error (_("Reset Code not or not anymore available\n"));
    2257           0 :               rc = gpg_error (GPG_ERR_BAD_PIN);
    2258           0 :               goto leave;
    2259             :             }
    2260             : 
    2261           0 :           rc = pincb (pincb_arg,
    2262           0 :                       _("||Please enter the Reset Code for the card"),
    2263             :                       &resetcode);
    2264           0 :           if (rc)
    2265             :             {
    2266           0 :               log_info (_("PIN callback returned error: %s\n"),
    2267             :                         gpg_strerror (rc));
    2268           0 :               goto leave;
    2269             :             }
    2270           0 :           if (strlen (resetcode) < minlen)
    2271             :             {
    2272           0 :               log_info (_("Reset Code is too short; minimum length is %d\n"),
    2273             :                         minlen);
    2274           0 :               rc = gpg_error (GPG_ERR_BAD_PIN);
    2275           0 :               goto leave;
    2276             :             }
    2277             :         }
    2278             :       else
    2279             :         {
    2280           0 :           rc = gpg_error (GPG_ERR_INV_ID);
    2281           0 :           goto leave;
    2282             :         }
    2283             :     }
    2284             : 
    2285           0 :   if (chvno == 3)
    2286           0 :     app->did_chv3 = 0;
    2287             :   else
    2288           0 :     app->did_chv1 = app->did_chv2 = 0;
    2289             : 
    2290           0 :   if (!use_pinpad)
    2291             :     {
    2292             :       /* TRANSLATORS: Do not translate the "|*|" prefixes but
    2293             :          keep it at the start of the string.  We need this elsewhere
    2294             :          to get some infos on the string. */
    2295           0 :       rc = pincb (pincb_arg, set_resetcode? _("|RN|New Reset Code") :
    2296             :                   chvno == 3? _("|AN|New Admin PIN") : _("|N|New PIN"),
    2297             :                   &pinvalue);
    2298           0 :       if (rc)
    2299             :         {
    2300           0 :           log_error (_("error getting new PIN: %s\n"), gpg_strerror (rc));
    2301           0 :           goto leave;
    2302             :         }
    2303             :     }
    2304             : 
    2305             : 
    2306           0 :   if (resetcode)
    2307             :     {
    2308             :       char *buffer;
    2309             : 
    2310           0 :       buffer = xtrymalloc (strlen (resetcode) + strlen (pinvalue) + 1);
    2311           0 :       if (!buffer)
    2312           0 :         rc = gpg_error_from_syserror ();
    2313             :       else
    2314             :         {
    2315           0 :           strcpy (stpcpy (buffer, resetcode), pinvalue);
    2316           0 :           rc = iso7816_reset_retry_counter_with_rc (app->slot, 0x81,
    2317             :                                                     buffer, strlen (buffer));
    2318           0 :           wipememory (buffer, strlen (buffer));
    2319           0 :           xfree (buffer);
    2320             :         }
    2321             :     }
    2322           0 :   else if (set_resetcode)
    2323             :     {
    2324           0 :       if (strlen (pinvalue) < 8)
    2325             :         {
    2326           0 :           log_error (_("Reset Code is too short; minimum length is %d\n"), 8);
    2327           0 :           rc = gpg_error (GPG_ERR_BAD_PIN);
    2328             :         }
    2329             :       else
    2330           0 :         rc = iso7816_put_data (app->slot, 0, 0xD3,
    2331             :                                pinvalue, strlen (pinvalue));
    2332             :     }
    2333           0 :   else if (reset_mode)
    2334             :     {
    2335           0 :       rc = iso7816_reset_retry_counter (app->slot, 0x81,
    2336             :                                         pinvalue, strlen (pinvalue));
    2337           0 :       if (!rc && !app->app_local->extcap.is_v2)
    2338           0 :         rc = iso7816_reset_retry_counter (app->slot, 0x82,
    2339             :                                           pinvalue, strlen (pinvalue));
    2340             :     }
    2341           0 :   else if (!app->app_local->extcap.is_v2)
    2342             :     {
    2343             :       /* Version 1 cards.  */
    2344           0 :       if (chvno == 1 || chvno == 2)
    2345             :         {
    2346           0 :           rc = iso7816_change_reference_data (app->slot, 0x81, NULL, 0,
    2347             :                                               pinvalue, strlen (pinvalue));
    2348           0 :           if (!rc)
    2349           0 :             rc = iso7816_change_reference_data (app->slot, 0x82, NULL, 0,
    2350             :                                                 pinvalue, strlen (pinvalue));
    2351             :         }
    2352             :       else /* CHVNO == 3 */
    2353             :         {
    2354           0 :           rc = iso7816_change_reference_data (app->slot, 0x80 + chvno, NULL, 0,
    2355             :                                               pinvalue, strlen (pinvalue));
    2356             :         }
    2357             :     }
    2358             :   else
    2359             :     {
    2360             :       /* Version 2 cards.  */
    2361           0 :       assert (chvno == 1 || chvno == 3);
    2362             : 
    2363           0 :       if (use_pinpad)
    2364             :         {
    2365           0 :           rc = pincb (pincb_arg,
    2366             :                       chvno == 3 ?
    2367             :                       _("||Please enter the Admin PIN and New Admin PIN") :
    2368             :                       _("||Please enter the PIN and New PIN"), NULL);
    2369           0 :           if (rc)
    2370             :             {
    2371           0 :               log_info (_("PIN callback returned error: %s\n"),
    2372             :                         gpg_strerror (rc));
    2373           0 :               goto leave;
    2374             :             }
    2375           0 :           rc = iso7816_change_reference_data_kp (app->slot, 0x80 + chvno, 0,
    2376             :                                                  &pininfo);
    2377           0 :           pincb (pincb_arg, NULL, NULL); /* Dismiss the prompt. */
    2378             :         }
    2379             :       else
    2380           0 :         rc = iso7816_change_reference_data (app->slot, 0x80 + chvno,
    2381             :                                             oldpinvalue, strlen (oldpinvalue),
    2382             :                                             pinvalue, strlen (pinvalue));
    2383             :     }
    2384             : 
    2385           0 :   if (pinvalue)
    2386             :     {
    2387           0 :       wipememory (pinvalue, strlen (pinvalue));
    2388           0 :       xfree (pinvalue);
    2389             :     }
    2390           0 :   if (rc)
    2391           0 :     flush_cache_after_error (app);
    2392             : 
    2393             :  leave:
    2394           0 :   if (resetcode)
    2395             :     {
    2396           0 :       wipememory (resetcode, strlen (resetcode));
    2397           0 :       xfree (resetcode);
    2398             :     }
    2399           0 :   if (oldpinvalue)
    2400             :     {
    2401           0 :       wipememory (oldpinvalue, strlen (oldpinvalue));
    2402           0 :       xfree (oldpinvalue);
    2403             :     }
    2404           0 :   return rc;
    2405             : }
    2406             : 
    2407             : 
    2408             : /* Check whether a key already exists.  KEYIDX is the index of the key
    2409             :    (0..2).  If FORCE is TRUE a diagnositic will be printed but no
    2410             :    error returned if the key already exists.  The flag GENERATING is
    2411             :    only used to print correct messages. */
    2412             : static gpg_error_t
    2413           0 : does_key_exist (app_t app, int keyidx, int generating, int force)
    2414             : {
    2415             :   const unsigned char *fpr;
    2416             :   unsigned char *buffer;
    2417             :   size_t buflen, n;
    2418             :   int i;
    2419             : 
    2420           0 :   assert (keyidx >=0 && keyidx <= 2);
    2421             : 
    2422           0 :   if (iso7816_get_data (app->slot, 0, 0x006E, &buffer, &buflen))
    2423             :     {
    2424           0 :       log_error (_("error reading application data\n"));
    2425           0 :       return gpg_error (GPG_ERR_GENERAL);
    2426             :     }
    2427           0 :   fpr = find_tlv (buffer, buflen, 0x00C5, &n);
    2428           0 :   if (!fpr || n < 60)
    2429             :     {
    2430           0 :       log_error (_("error reading fingerprint DO\n"));
    2431           0 :       xfree (buffer);
    2432           0 :       return gpg_error (GPG_ERR_GENERAL);
    2433             :     }
    2434           0 :   fpr += 20*keyidx;
    2435           0 :   for (i=0; i < 20 && !fpr[i]; i++)
    2436             :     ;
    2437           0 :   xfree (buffer);
    2438           0 :   if (i!=20 && !force)
    2439             :     {
    2440           0 :       log_error (_("key already exists\n"));
    2441           0 :       return gpg_error (GPG_ERR_EEXIST);
    2442             :     }
    2443           0 :   else if (i!=20)
    2444           0 :     log_info (_("existing key will be replaced\n"));
    2445           0 :   else if (generating)
    2446           0 :     log_info (_("generating new key\n"));
    2447             :   else
    2448           0 :     log_info (_("writing new key\n"));
    2449           0 :   return 0;
    2450             : }
    2451             : 
    2452             : 
    2453             : /* Create a TLV tag and value and store it at BUFFER.  Return the length
    2454             :    of tag and length.  A LENGTH greater than 65535 is truncated. */
    2455             : static size_t
    2456           0 : add_tlv (unsigned char *buffer, unsigned int tag, size_t length)
    2457             : {
    2458           0 :   unsigned char *p = buffer;
    2459             : 
    2460           0 :   assert (tag <= 0xffff);
    2461           0 :   if ( tag > 0xff )
    2462           0 :     *p++ = tag >> 8;
    2463           0 :   *p++ = tag;
    2464           0 :   if (length < 128)
    2465           0 :     *p++ = length;
    2466           0 :   else if (length < 256)
    2467             :     {
    2468           0 :       *p++ = 0x81;
    2469           0 :       *p++ = length;
    2470             :     }
    2471             :   else
    2472             :     {
    2473           0 :       if (length > 0xffff)
    2474           0 :         length = 0xffff;
    2475           0 :       *p++ = 0x82;
    2476           0 :       *p++ = length >> 8;
    2477           0 :       *p++ = length;
    2478             :     }
    2479             : 
    2480           0 :   return p - buffer;
    2481             : }
    2482             : 
    2483             : 
    2484             : static gpg_error_t
    2485           0 : build_privkey_template (app_t app, int keyno,
    2486             :                         const unsigned char *rsa_n, size_t rsa_n_len,
    2487             :                         const unsigned char *rsa_e, size_t rsa_e_len,
    2488             :                         const unsigned char *rsa_p, size_t rsa_p_len,
    2489             :                         const unsigned char *rsa_q, size_t rsa_q_len,
    2490             :                         const unsigned char *rsa_u, size_t rsa_u_len,
    2491             :                         const unsigned char *rsa_dp, size_t rsa_dp_len,
    2492             :                         const unsigned char *rsa_dq, size_t rsa_dq_len,
    2493             :                         unsigned char **result, size_t *resultlen)
    2494             : {
    2495             :   size_t rsa_e_reqlen;
    2496             :   unsigned char privkey[7*(1+3+3)];
    2497             :   size_t privkey_len;
    2498             :   unsigned char exthdr[2+2+3];
    2499             :   size_t exthdr_len;
    2500             :   unsigned char suffix[2+3];
    2501             :   size_t suffix_len;
    2502             :   unsigned char *tp;
    2503             :   size_t datalen;
    2504             :   unsigned char *template;
    2505             :   size_t template_size;
    2506             : 
    2507           0 :   *result = NULL;
    2508           0 :   *resultlen = 0;
    2509             : 
    2510           0 :   switch (app->app_local->keyattr[keyno].rsa.format)
    2511             :     {
    2512             :     case RSA_STD:
    2513             :     case RSA_STD_N:
    2514             :     case RSA_CRT:
    2515             :     case RSA_CRT_N:
    2516           0 :       break;
    2517             : 
    2518             :     default:
    2519           0 :       return gpg_error (GPG_ERR_INV_VALUE);
    2520             :     }
    2521             : 
    2522             :   /* Get the required length for E. Rounded up to the nearest byte  */
    2523           0 :   rsa_e_reqlen = (app->app_local->keyattr[keyno].rsa.e_bits + 7) / 8;
    2524           0 :   assert (rsa_e_len <= rsa_e_reqlen);
    2525             : 
    2526             :   /* Build the 7f48 cardholder private key template.  */
    2527           0 :   datalen = 0;
    2528           0 :   tp = privkey;
    2529             : 
    2530           0 :   tp += add_tlv (tp, 0x91, rsa_e_reqlen);
    2531           0 :   datalen += rsa_e_reqlen;
    2532             : 
    2533           0 :   tp += add_tlv (tp, 0x92, rsa_p_len);
    2534           0 :   datalen += rsa_p_len;
    2535             : 
    2536           0 :   tp += add_tlv (tp, 0x93, rsa_q_len);
    2537           0 :   datalen += rsa_q_len;
    2538             : 
    2539           0 :   if (app->app_local->keyattr[keyno].rsa.format == RSA_CRT
    2540           0 :       || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N)
    2541             :     {
    2542           0 :       tp += add_tlv (tp, 0x94, rsa_u_len);
    2543           0 :       datalen += rsa_u_len;
    2544           0 :       tp += add_tlv (tp, 0x95, rsa_dp_len);
    2545           0 :       datalen += rsa_dp_len;
    2546           0 :       tp += add_tlv (tp, 0x96, rsa_dq_len);
    2547           0 :       datalen += rsa_dq_len;
    2548             :     }
    2549             : 
    2550           0 :   if (app->app_local->keyattr[keyno].rsa.format == RSA_STD_N
    2551           0 :       || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N)
    2552             :     {
    2553           0 :       tp += add_tlv (tp, 0x97, rsa_n_len);
    2554           0 :       datalen += rsa_n_len;
    2555             :     }
    2556           0 :   privkey_len = tp - privkey;
    2557             : 
    2558             :   /* Build the extended header list without the private key template.  */
    2559           0 :   tp = exthdr;
    2560           0 :   *tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4;
    2561           0 :   *tp++ = 0;
    2562           0 :   tp += add_tlv (tp, 0x7f48, privkey_len);
    2563           0 :   exthdr_len = tp - exthdr;
    2564             : 
    2565             :   /* Build the 5f48 suffix of the data.  */
    2566           0 :   tp = suffix;
    2567           0 :   tp += add_tlv (tp, 0x5f48, datalen);
    2568           0 :   suffix_len = tp - suffix;
    2569             : 
    2570             :   /* Now concatenate everything.  */
    2571           0 :   template_size = (1 + 3   /* 0x4d and len. */
    2572             :                    + exthdr_len
    2573           0 :                    + privkey_len
    2574           0 :                    + suffix_len
    2575           0 :                    + datalen);
    2576           0 :   tp = template = xtrymalloc_secure (template_size);
    2577           0 :   if (!template)
    2578           0 :     return gpg_error_from_syserror ();
    2579             : 
    2580           0 :   tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen);
    2581           0 :   memcpy (tp, exthdr, exthdr_len);
    2582           0 :   tp += exthdr_len;
    2583           0 :   memcpy (tp, privkey, privkey_len);
    2584           0 :   tp += privkey_len;
    2585           0 :   memcpy (tp, suffix, suffix_len);
    2586           0 :   tp += suffix_len;
    2587             : 
    2588           0 :   memcpy (tp, rsa_e, rsa_e_len);
    2589           0 :   if (rsa_e_len < rsa_e_reqlen)
    2590             :     {
    2591             :       /* Right justify E. */
    2592           0 :       memmove (tp + rsa_e_reqlen - rsa_e_len, tp, rsa_e_len);
    2593           0 :       memset (tp, 0, rsa_e_reqlen - rsa_e_len);
    2594             :     }
    2595           0 :   tp += rsa_e_reqlen;
    2596             : 
    2597           0 :   memcpy (tp, rsa_p, rsa_p_len);
    2598           0 :   tp += rsa_p_len;
    2599             : 
    2600           0 :   memcpy (tp, rsa_q, rsa_q_len);
    2601           0 :   tp += rsa_q_len;
    2602             : 
    2603           0 :   if (app->app_local->keyattr[keyno].rsa.format == RSA_CRT
    2604           0 :       || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N)
    2605             :     {
    2606           0 :       memcpy (tp, rsa_u, rsa_u_len);
    2607           0 :       tp += rsa_u_len;
    2608           0 :       memcpy (tp, rsa_dp, rsa_dp_len);
    2609           0 :       tp += rsa_dp_len;
    2610           0 :       memcpy (tp, rsa_dq, rsa_dq_len);
    2611           0 :       tp += rsa_dq_len;
    2612             :     }
    2613             : 
    2614           0 :   if (app->app_local->keyattr[keyno].rsa.format == RSA_STD_N
    2615           0 :       || app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N)
    2616             :     {
    2617           0 :       memcpy (tp, rsa_n, rsa_n_len);
    2618           0 :       tp += rsa_n_len;
    2619             :     }
    2620             : 
    2621             :   /* Sanity check.  We don't know the exact length because we
    2622             :      allocated 3 bytes for the first length header.  */
    2623           0 :   assert (tp - template <= template_size);
    2624             : 
    2625           0 :   *result = template;
    2626           0 :   *resultlen = tp - template;
    2627           0 :   return 0;
    2628             : }
    2629             : 
    2630             : static gpg_error_t
    2631           0 : build_ecc_privkey_template (app_t app, int keyno,
    2632             :                             const unsigned char *ecc_d, size_t ecc_d_len,
    2633             :                             unsigned char **result, size_t *resultlen)
    2634             : {
    2635             :   unsigned char privkey[2];
    2636             :   size_t privkey_len;
    2637             :   unsigned char exthdr[2+2+1];
    2638             :   size_t exthdr_len;
    2639             :   unsigned char suffix[2+1];
    2640             :   size_t suffix_len;
    2641             :   unsigned char *tp;
    2642             :   size_t datalen;
    2643             :   unsigned char *template;
    2644             :   size_t template_size;
    2645             : 
    2646             :   (void)app;
    2647             : 
    2648           0 :   *result = NULL;
    2649           0 :   *resultlen = 0;
    2650             : 
    2651             :   /* Build the 7f48 cardholder private key template.  */
    2652           0 :   datalen = 0;
    2653           0 :   tp = privkey;
    2654             : 
    2655           0 :   tp += add_tlv (tp, 0x92, ecc_d_len);
    2656           0 :   datalen += ecc_d_len;
    2657             : 
    2658           0 :   privkey_len = tp - privkey;
    2659             : 
    2660             :   /* Build the extended header list without the private key template.  */
    2661           0 :   tp = exthdr;
    2662           0 :   *tp++ = keyno ==0 ? 0xb6 : keyno == 1? 0xb8 : 0xa4;
    2663           0 :   *tp++ = 0;
    2664           0 :   tp += add_tlv (tp, 0x7f48, privkey_len);
    2665           0 :   exthdr_len = tp - exthdr;
    2666             : 
    2667             :   /* Build the 5f48 suffix of the data.  */
    2668           0 :   tp = suffix;
    2669           0 :   tp += add_tlv (tp, 0x5f48, datalen);
    2670           0 :   suffix_len = tp - suffix;
    2671             : 
    2672             :   /* Now concatenate everything.  */
    2673           0 :   template_size = (1 + 1   /* 0x4d and len. */
    2674             :                    + exthdr_len
    2675           0 :                    + privkey_len
    2676           0 :                    + suffix_len
    2677           0 :                    + datalen);
    2678           0 :   tp = template = xtrymalloc_secure (template_size);
    2679           0 :   if (!template)
    2680           0 :     return gpg_error_from_syserror ();
    2681             : 
    2682           0 :   tp += add_tlv (tp, 0x4d, exthdr_len + privkey_len + suffix_len + datalen);
    2683           0 :   memcpy (tp, exthdr, exthdr_len);
    2684           0 :   tp += exthdr_len;
    2685           0 :   memcpy (tp, privkey, privkey_len);
    2686           0 :   tp += privkey_len;
    2687           0 :   memcpy (tp, suffix, suffix_len);
    2688           0 :   tp += suffix_len;
    2689             : 
    2690           0 :   memcpy (tp, ecc_d, ecc_d_len);
    2691           0 :   tp += ecc_d_len;
    2692             : 
    2693           0 :   assert (tp - template == template_size);
    2694             : 
    2695           0 :   *result = template;
    2696           0 :   *resultlen = tp - template;
    2697           0 :   return 0;
    2698             : }
    2699             : 
    2700             : 
    2701             : /* Helper for do_writekley to change the size of a key.  Not ethat
    2702             :    this deletes the entire key without asking.  */
    2703             : static gpg_error_t
    2704           0 : change_keyattr (app_t app, int keyno, const unsigned char *buf, size_t buflen,
    2705             :                 gpg_error_t (*pincb)(void*, const char *, char **),
    2706             :                 void *pincb_arg)
    2707             : {
    2708             :   gpg_error_t err;
    2709             : 
    2710           0 :   assert (keyno >=0 && keyno <= 2);
    2711             : 
    2712             :   /* Prepare for storing the key.  */
    2713           0 :   err = verify_chv3 (app, pincb, pincb_arg);
    2714           0 :   if (err)
    2715           0 :     return err;
    2716             : 
    2717             :   /* Change the attribute.  */
    2718           0 :   err = iso7816_put_data (app->slot, 0, 0xC1+keyno, buf, buflen);
    2719           0 :   if (err)
    2720           0 :     log_error ("error changing key attribute (key=%d)\n", keyno+1);
    2721             :   else
    2722           0 :     log_info ("key attribute changed (key=%d)\n", keyno+1);
    2723           0 :   flush_cache (app);
    2724           0 :   parse_algorithm_attribute (app, keyno);
    2725           0 :   app->did_chv1 = 0;
    2726           0 :   app->did_chv2 = 0;
    2727           0 :   app->did_chv3 = 0;
    2728           0 :   return err;
    2729             : }
    2730             : 
    2731             : 
    2732             : static gpg_error_t
    2733           0 : change_rsa_keyattr (app_t app, int keyno, unsigned int nbits,
    2734             :                     gpg_error_t (*pincb)(void*, const char *, char **),
    2735             :                     void *pincb_arg)
    2736             : {
    2737           0 :   gpg_error_t err = 0;
    2738             :   unsigned char *buf;
    2739             :   size_t buflen;
    2740             :   void *relptr;
    2741             : 
    2742             :   /* Read the current attributes into a buffer.  */
    2743           0 :   relptr = get_one_do (app, 0xC1+keyno, &buf, &buflen, NULL);
    2744           0 :   if (!relptr)
    2745           0 :     err = gpg_error (GPG_ERR_CARD);
    2746           0 :   else if (buflen < 6 || buf[0] != PUBKEY_ALGO_RSA)
    2747             :     {
    2748             :       /* Attriutes too short or not an RSA key.  */
    2749           0 :       xfree (relptr);
    2750           0 :       err = gpg_error (GPG_ERR_CARD);
    2751             :     }
    2752             :   else
    2753             :     {
    2754             :       /* We only change n_bits and don't touch anything else.  Before we
    2755             :          do so, we round up NBITS to a sensible way in the same way as
    2756             :          gpg's key generation does it.  This may help to sort out problems
    2757             :          with a few bits too short keys.  */
    2758           0 :       nbits = ((nbits + 31) / 32) * 32;
    2759           0 :       buf[1] = (nbits >> 8);
    2760           0 :       buf[2] = nbits;
    2761           0 :       err = change_keyattr (app, keyno, buf, buflen, pincb, pincb_arg);
    2762           0 :       xfree (relptr);
    2763             :     }
    2764             : 
    2765           0 :   return err;
    2766             : }
    2767             : 
    2768             : 
    2769             : /* Helper to process an setattr command for name KEY-ATTR.
    2770             :    In (VALUE,VALUELEN), it expects following string:
    2771             :         RSA: "--force <key> <algo> rsa<nbits>"
    2772             :         ECC: "--force <key> <algo> <curvename>"
    2773             :   */
    2774             : static gpg_error_t
    2775           0 : change_keyattr_from_string (app_t app,
    2776             :                             gpg_error_t (*pincb)(void*, const char *, char **),
    2777             :                             void *pincb_arg,
    2778             :                             const void *value, size_t valuelen)
    2779             : {
    2780           0 :   gpg_error_t err = 0;
    2781             :   char *string;
    2782             :   int key, keyno, algo;
    2783           0 :   int n = 0;
    2784             : 
    2785             :   /* VALUE is expected to be a string but not guaranteed to be
    2786             :      terminated.  Thus copy it to an allocated buffer first. */
    2787           0 :   string = xtrymalloc (valuelen+1);
    2788           0 :   if (!string)
    2789           0 :     return gpg_error_from_syserror ();
    2790           0 :   memcpy (string, value, valuelen);
    2791           0 :   string[valuelen] = 0;
    2792             : 
    2793             :   /* Because this function deletes the key we require the string
    2794             :      "--force" in the data to make clear that something serious might
    2795             :      happen.  */
    2796           0 :   sscanf (string, "--force %d %d %n", &key, &algo, &n);
    2797           0 :   if (n < 12)
    2798             :     {
    2799           0 :       err = gpg_error (GPG_ERR_INV_DATA);
    2800           0 :       goto leave;
    2801             :     }
    2802             : 
    2803           0 :   keyno = key - 1;
    2804           0 :   if (keyno < 0 || keyno > 2)
    2805           0 :     err = gpg_error (GPG_ERR_INV_ID);
    2806           0 :   else if (algo == PUBKEY_ALGO_RSA)
    2807             :     {
    2808             :       unsigned int nbits;
    2809             : 
    2810           0 :       errno = 0;
    2811           0 :       nbits = strtoul (string+n+3, NULL, 10);
    2812           0 :       if (errno)
    2813           0 :         err = gpg_error (GPG_ERR_INV_DATA);
    2814           0 :       else if (nbits < 1024)
    2815           0 :         err = gpg_error (GPG_ERR_TOO_SHORT);
    2816           0 :       else if (nbits > 4096)
    2817           0 :         err = gpg_error (GPG_ERR_TOO_LARGE);
    2818             :       else
    2819           0 :         err = change_rsa_keyattr (app, keyno, nbits, pincb, pincb_arg);
    2820             :     }
    2821           0 :   else if (algo == PUBKEY_ALGO_ECDH || algo == PUBKEY_ALGO_ECDSA
    2822           0 :            || algo == PUBKEY_ALGO_EDDSA)
    2823           0 :     {
    2824             :       const char *oidstr;
    2825             :       gcry_mpi_t oid;
    2826             :       const unsigned char *oidbuf;
    2827             :       size_t oid_len;
    2828             : 
    2829           0 :       oidstr = openpgp_curve_to_oid (string+n, NULL);
    2830           0 :       if (!oidstr)
    2831             :         {
    2832           0 :           err = gpg_error (GPG_ERR_INV_DATA);
    2833           0 :           goto leave;
    2834             :         }
    2835             : 
    2836           0 :       err = openpgp_oid_from_str (oidstr, &oid);
    2837           0 :       if (err)
    2838           0 :         goto leave;
    2839             : 
    2840           0 :       oidbuf = gcry_mpi_get_opaque (oid, &n);
    2841           0 :       oid_len = (n+7)/8;
    2842             : 
    2843             :       /* We have enough room at STRING.  */
    2844           0 :       string[0] = algo;
    2845           0 :       memcpy (string+1, oidbuf+1, oid_len-1);
    2846           0 :       err = change_keyattr (app, keyno, string, oid_len, pincb, pincb_arg);
    2847           0 :       gcry_mpi_release (oid);
    2848             :     }
    2849             :   else
    2850           0 :     err = gpg_error (GPG_ERR_PUBKEY_ALGO);
    2851             : 
    2852             :  leave:
    2853           0 :   xfree (string);
    2854           0 :   return err;
    2855             : }
    2856             : 
    2857             : 
    2858             : static gpg_error_t
    2859           0 : rsa_writekey (app_t app, gpg_error_t (*pincb)(void*, const char *, char **),
    2860             :               void *pincb_arg, int keyno,
    2861             :               const unsigned char *buf, size_t buflen, int depth)
    2862             : {
    2863             :   gpg_error_t err;
    2864             :   const unsigned char *tok;
    2865             :   size_t toklen;
    2866             :   int last_depth1, last_depth2;
    2867           0 :   const unsigned char *rsa_n = NULL;
    2868           0 :   const unsigned char *rsa_e = NULL;
    2869           0 :   const unsigned char *rsa_p = NULL;
    2870           0 :   const unsigned char *rsa_q = NULL;
    2871             :   size_t rsa_n_len, rsa_e_len, rsa_p_len, rsa_q_len;
    2872             :   unsigned int nbits;
    2873             :   unsigned int maxbits;
    2874           0 :   unsigned char *template = NULL;
    2875             :   unsigned char *tp;
    2876             :   size_t template_len;
    2877             :   unsigned char fprbuf[20];
    2878           0 :   u32 created_at = 0;
    2879             : 
    2880           0 :   if (app->app_local->keyattr[keyno].key_type != KEY_TYPE_RSA)
    2881             :     {
    2882           0 :       log_error (_("unsupported algorithm: %s"), "RSA");
    2883           0 :       err = gpg_error (GPG_ERR_INV_VALUE);
    2884           0 :       goto leave;
    2885             :     }
    2886             : 
    2887           0 :   last_depth1 = depth;
    2888           0 :   while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
    2889           0 :          && depth && depth >= last_depth1)
    2890             :     {
    2891           0 :       if (tok)
    2892             :         {
    2893           0 :           err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
    2894           0 :           goto leave;
    2895             :         }
    2896           0 :       if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
    2897           0 :         goto leave;
    2898           0 :       if (tok && toklen == 1)
    2899             :         {
    2900             :           const unsigned char **mpi;
    2901             :           size_t *mpi_len;
    2902             : 
    2903           0 :           switch (*tok)
    2904             :             {
    2905           0 :             case 'n': mpi = &rsa_n; mpi_len = &rsa_n_len; break;
    2906           0 :             case 'e': mpi = &rsa_e; mpi_len = &rsa_e_len; break;
    2907           0 :             case 'p': mpi = &rsa_p; mpi_len = &rsa_p_len; break;
    2908           0 :             case 'q': mpi = &rsa_q; mpi_len = &rsa_q_len;break;
    2909           0 :             default: mpi = NULL;  mpi_len = NULL; break;
    2910             :             }
    2911           0 :           if (mpi && *mpi)
    2912             :             {
    2913           0 :               err = gpg_error (GPG_ERR_DUP_VALUE);
    2914           0 :               goto leave;
    2915             :             }
    2916           0 :           if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
    2917           0 :             goto leave;
    2918           0 :           if (tok && mpi)
    2919             :             {
    2920             :               /* Strip off leading zero bytes and save. */
    2921           0 :               for (;toklen && !*tok; toklen--, tok++)
    2922             :                 ;
    2923           0 :               *mpi = tok;
    2924           0 :               *mpi_len = toklen;
    2925             :             }
    2926             :         }
    2927             :       /* Skip until end of list. */
    2928           0 :       last_depth2 = depth;
    2929           0 :       while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
    2930           0 :              && depth && depth >= last_depth2)
    2931             :         ;
    2932           0 :       if (err)
    2933           0 :         goto leave;
    2934             :     }
    2935             :   /* Parse other attributes. */
    2936           0 :   last_depth1 = depth;
    2937           0 :   while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
    2938           0 :          && depth && depth >= last_depth1)
    2939             :     {
    2940           0 :       if (tok)
    2941             :         {
    2942           0 :           err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
    2943           0 :           goto leave;
    2944             :         }
    2945           0 :       if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
    2946           0 :         goto leave;
    2947           0 :       if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
    2948             :         {
    2949           0 :           if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
    2950           0 :             goto leave;
    2951           0 :           if (tok)
    2952             :             {
    2953           0 :               for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
    2954           0 :                    tok++, toklen--)
    2955           0 :                 created_at = created_at*10 + (*tok - '0');
    2956             :             }
    2957             :         }
    2958             :       /* Skip until end of list. */
    2959           0 :       last_depth2 = depth;
    2960           0 :       while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
    2961           0 :              && depth && depth >= last_depth2)
    2962             :         ;
    2963           0 :       if (err)
    2964           0 :         goto leave;
    2965             :     }
    2966             : 
    2967             : 
    2968             :   /* Check that we have all parameters and that they match the card
    2969             :      description. */
    2970           0 :   if (!created_at)
    2971             :     {
    2972           0 :       log_error (_("creation timestamp missing\n"));
    2973           0 :       err = gpg_error (GPG_ERR_INV_VALUE);
    2974           0 :       goto leave;
    2975             :     }
    2976             : 
    2977           0 :   maxbits = app->app_local->keyattr[keyno].rsa.n_bits;
    2978           0 :   nbits = rsa_n? count_bits (rsa_n, rsa_n_len) : 0;
    2979           0 :   if (opt.verbose)
    2980           0 :     log_info ("RSA modulus size is %u bits (%u bytes)\n",
    2981             :               nbits, (unsigned int)rsa_n_len);
    2982           0 :   if (nbits && nbits != maxbits
    2983           0 :       && app->app_local->extcap.algo_attr_change)
    2984             :     {
    2985             :       /* Try to switch the key to a new length.  */
    2986           0 :       err = change_rsa_keyattr (app, keyno, nbits, pincb, pincb_arg);
    2987           0 :       if (!err)
    2988           0 :         maxbits = app->app_local->keyattr[keyno].rsa.n_bits;
    2989             :     }
    2990           0 :   if (nbits != maxbits)
    2991             :     {
    2992           0 :       log_error (_("RSA modulus missing or not of size %d bits\n"),
    2993             :                  (int)maxbits);
    2994           0 :       err = gpg_error (GPG_ERR_BAD_SECKEY);
    2995           0 :       goto leave;
    2996             :     }
    2997             : 
    2998           0 :   maxbits = app->app_local->keyattr[keyno].rsa.e_bits;
    2999           0 :   if (maxbits > 32 && !app->app_local->extcap.is_v2)
    3000           0 :     maxbits = 32; /* Our code for v1 does only support 32 bits.  */
    3001           0 :   nbits = rsa_e? count_bits (rsa_e, rsa_e_len) : 0;
    3002           0 :   if (nbits < 2 || nbits > maxbits)
    3003             :     {
    3004           0 :       log_error (_("RSA public exponent missing or larger than %d bits\n"),
    3005             :                  (int)maxbits);
    3006           0 :       err = gpg_error (GPG_ERR_BAD_SECKEY);
    3007           0 :       goto leave;
    3008             :     }
    3009             : 
    3010           0 :   maxbits = app->app_local->keyattr[keyno].rsa.n_bits/2;
    3011           0 :   nbits = rsa_p? count_bits (rsa_p, rsa_p_len) : 0;
    3012           0 :   if (nbits != maxbits)
    3013             :     {
    3014           0 :       log_error (_("RSA prime %s missing or not of size %d bits\n"),
    3015             :                  "P", (int)maxbits);
    3016           0 :       err = gpg_error (GPG_ERR_BAD_SECKEY);
    3017           0 :       goto leave;
    3018             :     }
    3019           0 :   nbits = rsa_q? count_bits (rsa_q, rsa_q_len) : 0;
    3020           0 :   if (nbits != maxbits)
    3021             :     {
    3022           0 :       log_error (_("RSA prime %s missing or not of size %d bits\n"),
    3023             :                  "Q", (int)maxbits);
    3024           0 :       err = gpg_error (GPG_ERR_BAD_SECKEY);
    3025           0 :       goto leave;
    3026             :     }
    3027             : 
    3028             :   /* We need to remove the cached public key.  */
    3029           0 :   xfree (app->app_local->pk[keyno].key);
    3030           0 :   app->app_local->pk[keyno].key = NULL;
    3031           0 :   app->app_local->pk[keyno].keylen = 0;
    3032           0 :   app->app_local->pk[keyno].read_done = 0;
    3033             : 
    3034             : 
    3035           0 :   if (app->app_local->extcap.is_v2)
    3036             :     {
    3037             :       unsigned char *rsa_u, *rsa_dp, *rsa_dq;
    3038             :       size_t rsa_u_len, rsa_dp_len, rsa_dq_len;
    3039             :       gcry_mpi_t mpi_e, mpi_p, mpi_q;
    3040           0 :       gcry_mpi_t mpi_u = gcry_mpi_snew (0);
    3041           0 :       gcry_mpi_t mpi_dp = gcry_mpi_snew (0);
    3042           0 :       gcry_mpi_t mpi_dq = gcry_mpi_snew (0);
    3043           0 :       gcry_mpi_t mpi_tmp = gcry_mpi_snew (0);
    3044             :       int exmode;
    3045             : 
    3046             :       /* Calculate the u, dp and dq components needed by RSA_CRT cards */
    3047           0 :       gcry_mpi_scan (&mpi_e, GCRYMPI_FMT_USG, rsa_e, rsa_e_len, NULL);
    3048           0 :       gcry_mpi_scan (&mpi_p, GCRYMPI_FMT_USG, rsa_p, rsa_p_len, NULL);
    3049           0 :       gcry_mpi_scan (&mpi_q, GCRYMPI_FMT_USG, rsa_q, rsa_q_len, NULL);
    3050             : 
    3051           0 :       gcry_mpi_invm (mpi_u, mpi_q, mpi_p);
    3052           0 :       gcry_mpi_sub_ui (mpi_tmp, mpi_p, 1);
    3053           0 :       gcry_mpi_invm (mpi_dp, mpi_e, mpi_tmp);
    3054           0 :       gcry_mpi_sub_ui (mpi_tmp, mpi_q, 1);
    3055           0 :       gcry_mpi_invm (mpi_dq, mpi_e, mpi_tmp);
    3056             : 
    3057           0 :       gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_u, &rsa_u_len, mpi_u);
    3058           0 :       gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_dp, &rsa_dp_len, mpi_dp);
    3059           0 :       gcry_mpi_aprint (GCRYMPI_FMT_USG, &rsa_dq, &rsa_dq_len, mpi_dq);
    3060             : 
    3061           0 :       gcry_mpi_release (mpi_e);
    3062           0 :       gcry_mpi_release (mpi_p);
    3063           0 :       gcry_mpi_release (mpi_q);
    3064           0 :       gcry_mpi_release (mpi_u);
    3065           0 :       gcry_mpi_release (mpi_dp);
    3066           0 :       gcry_mpi_release (mpi_dq);
    3067           0 :       gcry_mpi_release (mpi_tmp);
    3068             : 
    3069             :       /* Build the private key template as described in section 4.3.3.7 of
    3070             :          the OpenPGP card specs version 2.0.  */
    3071           0 :       err = build_privkey_template (app, keyno,
    3072             :                                     rsa_n, rsa_n_len,
    3073             :                                     rsa_e, rsa_e_len,
    3074             :                                     rsa_p, rsa_p_len,
    3075             :                                     rsa_q, rsa_q_len,
    3076             :                                     rsa_u, rsa_u_len,
    3077             :                                     rsa_dp, rsa_dp_len,
    3078             :                                     rsa_dq, rsa_dq_len,
    3079             :                                     &template, &template_len);
    3080           0 :       xfree(rsa_u);
    3081           0 :       xfree(rsa_dp);
    3082           0 :       xfree(rsa_dq);
    3083             : 
    3084           0 :       if (err)
    3085           0 :         goto leave;
    3086             : 
    3087             :       /* Prepare for storing the key.  */
    3088           0 :       err = verify_chv3 (app, pincb, pincb_arg);
    3089           0 :       if (err)
    3090           0 :         goto leave;
    3091             : 
    3092             :       /* Store the key. */
    3093           0 :       if (app->app_local->cardcap.ext_lc_le && template_len > 254)
    3094           0 :         exmode = 1;    /* Use extended length w/o a limit.  */
    3095           0 :       else if (app->app_local->cardcap.cmd_chaining && template_len > 254)
    3096           0 :         exmode = -254;
    3097             :       else
    3098           0 :         exmode = 0;
    3099           0 :       err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
    3100             :                                   template, template_len);
    3101             :     }
    3102             :   else
    3103             :     {
    3104             :       /* Build the private key template as described in section 4.3.3.6 of
    3105             :          the OpenPGP card specs version 1.1:
    3106             :          0xC0   <length> public exponent
    3107             :          0xC1   <length> prime p
    3108             :          0xC2   <length> prime q
    3109             :       */
    3110           0 :       assert (rsa_e_len <= 4);
    3111           0 :       template_len = (1 + 1 + 4
    3112             :                       + 1 + 1 + rsa_p_len
    3113           0 :                       + 1 + 1 + rsa_q_len);
    3114           0 :       template = tp = xtrymalloc_secure (template_len);
    3115           0 :       if (!template)
    3116             :         {
    3117           0 :           err = gpg_error_from_syserror ();
    3118           0 :           goto leave;
    3119             :         }
    3120           0 :       *tp++ = 0xC0;
    3121           0 :       *tp++ = 4;
    3122           0 :       memcpy (tp, rsa_e, rsa_e_len);
    3123           0 :       if (rsa_e_len < 4)
    3124             :         {
    3125             :           /* Right justify E. */
    3126           0 :           memmove (tp+4-rsa_e_len, tp, rsa_e_len);
    3127           0 :           memset (tp, 0, 4-rsa_e_len);
    3128             :         }
    3129           0 :       tp += 4;
    3130             : 
    3131           0 :       *tp++ = 0xC1;
    3132           0 :       *tp++ = rsa_p_len;
    3133           0 :       memcpy (tp, rsa_p, rsa_p_len);
    3134           0 :       tp += rsa_p_len;
    3135             : 
    3136           0 :       *tp++ = 0xC2;
    3137           0 :       *tp++ = rsa_q_len;
    3138           0 :       memcpy (tp, rsa_q, rsa_q_len);
    3139           0 :       tp += rsa_q_len;
    3140             : 
    3141           0 :       assert (tp - template == template_len);
    3142             : 
    3143             :       /* Prepare for storing the key.  */
    3144           0 :       err = verify_chv3 (app, pincb, pincb_arg);
    3145           0 :       if (err)
    3146           0 :         goto leave;
    3147             : 
    3148             :       /* Store the key. */
    3149           0 :       err = iso7816_put_data (app->slot, 0,
    3150           0 :                               (app->card_version > 0x0007? 0xE0:0xE9)+keyno,
    3151             :                               template, template_len);
    3152             :     }
    3153           0 :   if (err)
    3154             :     {
    3155           0 :       log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
    3156           0 :       goto leave;
    3157             :     }
    3158             : 
    3159           0 :   err = store_fpr (app, keyno, created_at, fprbuf, PUBKEY_ALGO_RSA,
    3160             :                    rsa_n, rsa_n_len, rsa_e, rsa_e_len);
    3161           0 :   if (err)
    3162           0 :     goto leave;
    3163             : 
    3164             : 
    3165             :  leave:
    3166           0 :   xfree (template);
    3167           0 :   return err;
    3168             : }
    3169             : 
    3170             : 
    3171             : static gpg_error_t
    3172           0 : ecc_writekey (app_t app, gpg_error_t (*pincb)(void*, const char *, char **),
    3173             :               void *pincb_arg, int keyno,
    3174             :               const unsigned char *buf, size_t buflen, int depth)
    3175             : {
    3176             :   gpg_error_t err;
    3177             :   const unsigned char *tok;
    3178             :   size_t toklen;
    3179             :   int last_depth1, last_depth2;
    3180           0 :   const unsigned char *ecc_q = NULL;
    3181           0 :   const unsigned char *ecc_d = NULL;
    3182             :   size_t ecc_q_len, ecc_d_len;
    3183           0 :   u32 created_at = 0;
    3184           0 :   const char *oidstr = NULL;
    3185           0 :   int flag_djb_tweak = 0;
    3186             :   int algo;
    3187             :   gcry_mpi_t oid;
    3188           0 :   const unsigned char *oidbuf = NULL;
    3189             :   unsigned int n;
    3190             :   size_t oid_len;
    3191             :   unsigned char fprbuf[20];
    3192             : 
    3193             :   /* (private-key(ecc(curve%s)(q%m)(d%m))(created-at%d)):
    3194             :      curve = "NIST P-256" */
    3195             :   /* (private-key(ecc(curve%s)(q%m)(d%m))(created-at%d)):
    3196             :      curve = "secp256k1" */
    3197             :   /* (private-key(ecc(curve%s)(flags eddsa)(q%m)(d%m))(created-at%d)):
    3198             :       curve = "Ed25519" */
    3199           0 :   last_depth1 = depth;
    3200           0 :   while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
    3201           0 :          && depth && depth >= last_depth1)
    3202             :     {
    3203           0 :       if (tok)
    3204             :         {
    3205           0 :           err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
    3206           0 :           goto leave;
    3207             :         }
    3208           0 :       if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
    3209           0 :         goto leave;
    3210             : 
    3211           0 :       if (tok && toklen == 5 && !memcmp (tok, "curve", 5))
    3212           0 :         {
    3213             :           unsigned char *curve;
    3214             : 
    3215           0 :           if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
    3216           0 :             goto leave;
    3217             : 
    3218           0 :           curve = xtrymalloc (toklen+1);
    3219           0 :           if (!curve)
    3220             :             {
    3221           0 :               err = gpg_error_from_syserror ();
    3222           0 :               goto leave;
    3223             :             }
    3224             : 
    3225           0 :           memcpy (curve, tok, toklen);
    3226           0 :           curve[toklen] = 0;
    3227           0 :           oidstr = openpgp_curve_to_oid (curve, NULL);
    3228           0 :           xfree (curve);
    3229             :         }
    3230           0 :       else if (tok && toklen == 5 && !memcmp (tok, "flags", 5))
    3231             :         {
    3232           0 :           if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
    3233           0 :             goto leave;
    3234             : 
    3235           0 :           if (tok)
    3236             :             {
    3237           0 :               if ((toklen == 5 && !memcmp (tok, "eddsa", 5))
    3238           0 :                   || (toklen == 9 && !memcmp (tok, "djb-tweak", 9)))
    3239           0 :                 flag_djb_tweak = 1;
    3240             :             }
    3241             :         }
    3242           0 :       else if (tok && toklen == 1)
    3243             :         {
    3244             :           const unsigned char **buf2;
    3245             :           size_t *buf2len;
    3246           0 :           int native = flag_djb_tweak;
    3247             : 
    3248           0 :           switch (*tok)
    3249             :             {
    3250           0 :             case 'q': buf2 = &ecc_q; buf2len = &ecc_q_len; break;
    3251           0 :             case 'd': buf2 = &ecc_d; buf2len = &ecc_d_len; native = 0; break;
    3252           0 :             default: buf2 = NULL;  buf2len = NULL; break;
    3253             :             }
    3254           0 :           if (buf2 && *buf2)
    3255             :             {
    3256           0 :               err = gpg_error (GPG_ERR_DUP_VALUE);
    3257           0 :               goto leave;
    3258             :             }
    3259           0 :           if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
    3260           0 :             goto leave;
    3261           0 :           if (tok && buf2)
    3262             :             {
    3263           0 :               if (!native)
    3264             :                 /* Strip off leading zero bytes and save. */
    3265           0 :                 for (;toklen && !*tok; toklen--, tok++)
    3266             :                   ;
    3267             : 
    3268           0 :               *buf2 = tok;
    3269           0 :               *buf2len = toklen;
    3270             :             }
    3271             :         }
    3272             :       /* Skip until end of list. */
    3273           0 :       last_depth2 = depth;
    3274           0 :       while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
    3275           0 :              && depth && depth >= last_depth2)
    3276             :         ;
    3277           0 :       if (err)
    3278           0 :         goto leave;
    3279             :     }
    3280             :   /* Parse other attributes. */
    3281           0 :   last_depth1 = depth;
    3282           0 :   while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
    3283           0 :          && depth && depth >= last_depth1)
    3284             :     {
    3285           0 :       if (tok)
    3286             :         {
    3287           0 :           err = gpg_error (GPG_ERR_UNKNOWN_SEXP);
    3288           0 :           goto leave;
    3289             :         }
    3290           0 :       if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
    3291           0 :         goto leave;
    3292           0 :       if (tok && toklen == 10 && !memcmp ("created-at", tok, toklen))
    3293             :         {
    3294           0 :           if ((err = parse_sexp (&buf,&buflen,&depth,&tok,&toklen)))
    3295           0 :             goto leave;
    3296           0 :           if (tok)
    3297             :             {
    3298           0 :               for (created_at=0; toklen && *tok && *tok >= '0' && *tok <= '9';
    3299           0 :                    tok++, toklen--)
    3300           0 :                 created_at = created_at*10 + (*tok - '0');
    3301             :             }
    3302             :         }
    3303             :       /* Skip until end of list. */
    3304           0 :       last_depth2 = depth;
    3305           0 :       while (!(err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen))
    3306           0 :              && depth && depth >= last_depth2)
    3307             :         ;
    3308           0 :       if (err)
    3309           0 :         goto leave;
    3310             :     }
    3311             : 
    3312             : 
    3313             :   /* Check that we have all parameters and that they match the card
    3314             :      description. */
    3315           0 :   if (!oidstr)
    3316             :     {
    3317           0 :       log_error (_("unsupported curve\n"));
    3318           0 :       err = gpg_error (GPG_ERR_INV_VALUE);
    3319           0 :       goto leave;
    3320             :     }
    3321           0 :   if (!created_at)
    3322             :     {
    3323           0 :       log_error (_("creation timestamp missing\n"));
    3324           0 :       err = gpg_error (GPG_ERR_INV_VALUE);
    3325           0 :       goto leave;
    3326             :     }
    3327           0 :   if (flag_djb_tweak && keyno != 1)
    3328           0 :     algo = PUBKEY_ALGO_EDDSA;
    3329           0 :   else if (keyno == 1)
    3330           0 :     algo = PUBKEY_ALGO_ECDH;
    3331             :   else
    3332           0 :     algo = PUBKEY_ALGO_ECDSA;
    3333             : 
    3334           0 :   err = openpgp_oid_from_str (oidstr, &oid);
    3335           0 :   if (err)
    3336           0 :     goto leave;
    3337           0 :   oidbuf = gcry_mpi_get_opaque (oid, &n);
    3338           0 :   oid_len = (n+7)/8;
    3339           0 :   if (!oidbuf)
    3340             :     {
    3341           0 :       err = gpg_error_from_syserror ();
    3342           0 :       gcry_mpi_release (oid);
    3343           0 :       goto leave;
    3344             :     }
    3345             : 
    3346           0 :   if (app->app_local->keyattr[keyno].key_type != KEY_TYPE_ECC
    3347           0 :       || app->app_local->keyattr[keyno].ecc.oid != oidstr
    3348           0 :       || app->app_local->keyattr[keyno].ecc.flags != flag_djb_tweak)
    3349             :     {
    3350           0 :       if (app->app_local->extcap.algo_attr_change)
    3351             :         {
    3352           0 :           unsigned char keyattr[oid_len];
    3353             : 
    3354           0 :           keyattr[0] = algo;
    3355           0 :           memcpy (keyattr+1, oidbuf+1, oid_len-1);
    3356           0 :           err = change_keyattr (app, keyno, keyattr, oid_len, pincb, pincb_arg);
    3357           0 :           if (err)
    3358           0 :             goto leave;
    3359             :         }
    3360             :       else
    3361             :         {
    3362           0 :           log_error ("key attribute on card doesn't match\n");
    3363           0 :           err = gpg_error (GPG_ERR_INV_VALUE);
    3364           0 :           goto leave;
    3365             :         }
    3366             :     }
    3367             : 
    3368           0 :   if (opt.verbose)
    3369           0 :     log_info ("ECC private key size is %u bytes\n", (unsigned int)ecc_d_len);
    3370             : 
    3371             :   /* We need to remove the cached public key.  */
    3372           0 :   xfree (app->app_local->pk[keyno].key);
    3373           0 :   app->app_local->pk[keyno].key = NULL;
    3374           0 :   app->app_local->pk[keyno].keylen = 0;
    3375           0 :   app->app_local->pk[keyno].read_done = 0;
    3376             : 
    3377           0 :   if (app->app_local->extcap.is_v2)
    3378             :     {
    3379             :       /* Build the private key template as described in section 4.3.3.7 of
    3380             :          the OpenPGP card specs version 2.0.  */
    3381             :       unsigned char *template;
    3382             :       size_t template_len;
    3383             :       int exmode;
    3384             : 
    3385           0 :       err = build_ecc_privkey_template (app, keyno,
    3386             :                                         ecc_d, ecc_d_len,
    3387             :                                         &template, &template_len);
    3388           0 :       if (err)
    3389           0 :         goto leave;
    3390             : 
    3391             :       /* Prepare for storing the key.  */
    3392           0 :       err = verify_chv3 (app, pincb, pincb_arg);
    3393           0 :       if (err)
    3394             :         {
    3395           0 :           xfree (template);
    3396           0 :           goto leave;
    3397             :         }
    3398             : 
    3399             :       /* Store the key. */
    3400           0 :       if (app->app_local->cardcap.ext_lc_le && template_len > 254)
    3401           0 :         exmode = 1;    /* Use extended length w/o a limit.  */
    3402           0 :       else if (app->app_local->cardcap.cmd_chaining && template_len > 254)
    3403           0 :         exmode = -254;
    3404             :       else
    3405           0 :         exmode = 0;
    3406           0 :       err = iso7816_put_data_odd (app->slot, exmode, 0x3fff,
    3407             :                                   template, template_len);
    3408           0 :       xfree (template);
    3409             :     }
    3410             :   else
    3411           0 :     err = gpg_error (GPG_ERR_NOT_SUPPORTED);
    3412             : 
    3413           0 :   if (err)
    3414             :     {
    3415           0 :       log_error (_("failed to store the key: %s\n"), gpg_strerror (err));
    3416           0 :       goto leave;
    3417             :     }
    3418             : 
    3419           0 :   err = store_fpr (app, keyno, created_at, fprbuf, algo, oidbuf, oid_len,
    3420             :                    ecc_q, ecc_q_len, "\x03\x01\x08\x07", (size_t)4);
    3421             : 
    3422             :  leave:
    3423           0 :   if (oidbuf)
    3424           0 :     gcry_mpi_release (oid);
    3425           0 :   return err;
    3426             : }
    3427             : 
    3428             : /* Handle the WRITEKEY command for OpenPGP.  This function expects a
    3429             :    canonical encoded S-expression with the secret key in KEYDATA and
    3430             :    its length (for assertions) in KEYDATALEN.  KEYID needs to be the
    3431             :    usual keyid which for OpenPGP is the string "OPENPGP.n" with
    3432             :    n=1,2,3.  Bit 0 of FLAGS indicates whether an existing key shall
    3433             :    get overwritten.  PINCB and PINCB_ARG are the usual arguments for
    3434             :    the pinentry callback.  */
    3435             : static gpg_error_t
    3436           0 : do_writekey (app_t app, ctrl_t ctrl,
    3437             :              const char *keyid, unsigned int flags,
    3438             :              gpg_error_t (*pincb)(void*, const char *, char **),
    3439             :              void *pincb_arg,
    3440             :              const unsigned char *keydata, size_t keydatalen)
    3441             : {
    3442             :   gpg_error_t err;
    3443           0 :   int force = (flags & 1);
    3444             :   int keyno;
    3445             :   const unsigned char *buf, *tok;
    3446             :   size_t buflen, toklen;
    3447             :   int depth;
    3448             : 
    3449             :   (void)ctrl;
    3450             : 
    3451           0 :   if (!strcmp (keyid, "OPENPGP.1"))
    3452           0 :     keyno = 0;
    3453           0 :   else if (!strcmp (keyid, "OPENPGP.2"))
    3454           0 :     keyno = 1;
    3455           0 :   else if (!strcmp (keyid, "OPENPGP.3"))
    3456           0 :     keyno = 2;
    3457             :   else
    3458           0 :     return gpg_error (GPG_ERR_INV_ID);
    3459             : 
    3460           0 :   err = does_key_exist (app, keyno, 0, force);
    3461           0 :   if (err)
    3462           0 :     return err;
    3463             : 
    3464             : 
    3465             :   /*
    3466             :      Parse the S-expression
    3467             :    */
    3468           0 :   buf = keydata;
    3469           0 :   buflen = keydatalen;
    3470           0 :   depth = 0;
    3471           0 :   if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
    3472           0 :     goto leave;
    3473           0 :   if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
    3474           0 :     goto leave;
    3475           0 :   if (!tok || toklen != 11 || memcmp ("private-key", tok, toklen))
    3476             :     {
    3477           0 :       if (!tok)
    3478             :         ;
    3479           0 :       else if (toklen == 21 && !memcmp ("protected-private-key", tok, toklen))
    3480           0 :         log_info ("protected-private-key passed to writekey\n");
    3481           0 :       else if (toklen == 20 && !memcmp ("shadowed-private-key", tok, toklen))
    3482           0 :         log_info ("shadowed-private-key passed to writekey\n");
    3483           0 :       err = gpg_error (GPG_ERR_BAD_SECKEY);
    3484           0 :       goto leave;
    3485             :     }
    3486           0 :   if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
    3487           0 :     goto leave;
    3488           0 :   if ((err = parse_sexp (&buf, &buflen, &depth, &tok, &toklen)))
    3489           0 :     goto leave;
    3490           0 :   if (tok && toklen == 3 && memcmp ("rsa", tok, toklen) == 0)
    3491           0 :     err = rsa_writekey (app, pincb, pincb_arg, keyno, buf, buflen, depth);
    3492           0 :   else if (tok && toklen == 3 && memcmp ("ecc", tok, toklen) == 0)
    3493           0 :     err = ecc_writekey (app, pincb, pincb_arg, keyno, buf, buflen, depth);
    3494             :   else
    3495             :     {
    3496           0 :       err = gpg_error (GPG_ERR_WRONG_PUBKEY_ALGO);
    3497           0 :       goto leave;
    3498             :     }
    3499             : 
    3500             :  leave:
    3501           0 :   return err;
    3502             : }
    3503             : 
    3504             : 
    3505             : 
    3506             : /* Handle the GENKEY command. */
    3507             : static gpg_error_t
    3508           0 : do_genkey (app_t app, ctrl_t ctrl,  const char *keynostr, unsigned int flags,
    3509             :            time_t createtime,
    3510             :            gpg_error_t (*pincb)(void*, const char *, char **),
    3511             :            void *pincb_arg)
    3512             : {
    3513             :   int rc;
    3514             :   char numbuf[30];
    3515             :   unsigned char fprbuf[20];
    3516             :   const unsigned char *keydata, *m, *e;
    3517           0 :   unsigned char *buffer = NULL;
    3518             :   size_t buflen, keydatalen, mlen, elen;
    3519             :   time_t created_at;
    3520           0 :   int keyno = atoi (keynostr) - 1;
    3521           0 :   int force = (flags & 1);
    3522             :   time_t start_at;
    3523             :   int exmode;
    3524             :   int le_value;
    3525             :   unsigned int keybits;
    3526             : 
    3527           0 :   if (keyno < 0 || keyno > 2)
    3528           0 :     return gpg_error (GPG_ERR_INV_ID);
    3529             : 
    3530             :   /* We flush the cache to increase the traffic before a key
    3531             :      generation.  This _might_ help a card to gather more entropy. */
    3532           0 :   flush_cache (app);
    3533             : 
    3534             :   /* Obviously we need to remove the cached public key.  */
    3535           0 :   xfree (app->app_local->pk[keyno].key);
    3536           0 :   app->app_local->pk[keyno].key = NULL;
    3537           0 :   app->app_local->pk[keyno].keylen = 0;
    3538           0 :   app->app_local->pk[keyno].read_done = 0;
    3539             : 
    3540             :   /* Check whether a key already exists.  */
    3541           0 :   rc = does_key_exist (app, keyno, 1, force);
    3542           0 :   if (rc)
    3543           0 :     return rc;
    3544             : 
    3545             :   /* Because we send the key parameter back via status lines we need
    3546             :      to put a limit on the max. allowed keysize.  2048 bit will
    3547             :      already lead to a 527 byte long status line and thus a 4096 bit
    3548             :      key would exceed the Assuan line length limit.  */
    3549           0 :   keybits = app->app_local->keyattr[keyno].rsa.n_bits;
    3550           0 :   if (keybits > 4096)
    3551           0 :     return gpg_error (GPG_ERR_TOO_LARGE);
    3552             : 
    3553             :   /* Prepare for key generation by verifying the Admin PIN.  */
    3554           0 :   rc = verify_chv3 (app, pincb, pincb_arg);
    3555           0 :   if (rc)
    3556           0 :     goto leave;
    3557             : 
    3558             :   /* Test whether we will need extended length mode.  (1900 is an
    3559             :      arbitrary length which for sure fits into a short apdu.)  */
    3560           0 :   if (app->app_local->cardcap.ext_lc_le && keybits > 1900)
    3561             :     {
    3562           0 :       exmode = 1;    /* Use extended length w/o a limit.  */
    3563           0 :       le_value = app->app_local->extcap.max_rsp_data;
    3564             :       /* No need to check le_value because it comes from a 16 bit
    3565             :          value and thus can't create an overflow on a 32 bit
    3566             :          system.  */
    3567             :     }
    3568             :   else
    3569             :     {
    3570           0 :       exmode = 0;
    3571           0 :       le_value = 256; /* Use legacy value. */
    3572             :     }
    3573             : 
    3574           0 :   log_info (_("please wait while key is being generated ...\n"));
    3575           0 :   start_at = time (NULL);
    3576           0 :   rc = iso7816_generate_keypair
    3577             : /* # warning key generation temporary replaced by reading an existing key. */
    3578             : /*   rc = iso7816_read_public_key */
    3579             :     (app->slot, exmode,
    3580             :      (const unsigned char*)(keyno == 0? "\xB6" :
    3581             :                             keyno == 1? "\xB8" : "\xA4"), 2,
    3582             :      le_value,
    3583             :      &buffer, &buflen);
    3584           0 :   if (rc)
    3585             :     {
    3586           0 :       rc = gpg_error (GPG_ERR_CARD);
    3587           0 :       log_error (_("generating key failed\n"));
    3588           0 :       goto leave;
    3589             :     }
    3590           0 :   log_info (_("key generation completed (%d seconds)\n"),
    3591           0 :             (int)(time (NULL) - start_at));
    3592             : 
    3593           0 :   keydata = find_tlv (buffer, buflen, 0x7F49, &keydatalen);
    3594           0 :   if (!keydata)
    3595             :     {
    3596           0 :       rc = gpg_error (GPG_ERR_CARD);
    3597           0 :       log_error (_("response does not contain the public key data\n"));
    3598           0 :       goto leave;
    3599             :     }
    3600             : 
    3601           0 :   m = find_tlv (keydata, keydatalen, 0x0081, &mlen);
    3602           0 :   if (!m)
    3603             :     {
    3604           0 :       rc = gpg_error (GPG_ERR_CARD);
    3605           0 :       log_error (_("response does not contain the RSA modulus\n"));
    3606           0 :       goto leave;
    3607             :     }
    3608             :   /* log_printhex ("RSA n:", m, mlen); */
    3609           0 :   send_key_data (ctrl, "n", m, mlen);
    3610             : 
    3611           0 :   e = find_tlv (keydata, keydatalen, 0x0082, &elen);
    3612           0 :   if (!e)
    3613             :     {
    3614           0 :       rc = gpg_error (GPG_ERR_CARD);
    3615           0 :       log_error (_("response does not contain the RSA public exponent\n"));
    3616           0 :       goto leave;
    3617             :     }
    3618             :   /* log_printhex ("RSA e:", e, elen); */
    3619           0 :   send_key_data (ctrl, "e", e, elen);
    3620             : 
    3621           0 :   created_at = createtime? createtime : gnupg_get_time ();
    3622           0 :   sprintf (numbuf, "%lu", (unsigned long)created_at);
    3623           0 :   send_status_info (ctrl, "KEY-CREATED-AT",
    3624             :                     numbuf, (size_t)strlen(numbuf), NULL, 0);
    3625             : 
    3626           0 :   rc = store_fpr (app, keyno, (u32)created_at, fprbuf, PUBKEY_ALGO_RSA,
    3627             :                   m, mlen, e, elen);
    3628           0 :   if (rc)
    3629           0 :     goto leave;
    3630           0 :   send_fpr_if_not_null (ctrl, "KEY-FPR", -1, fprbuf);
    3631             : 
    3632             : 
    3633             :  leave:
    3634           0 :   xfree (buffer);
    3635           0 :   return rc;
    3636             : }
    3637             : 
    3638             : 
    3639             : static unsigned long
    3640           0 : convert_sig_counter_value (const unsigned char *value, size_t valuelen)
    3641             : {
    3642             :   unsigned long ul;
    3643             : 
    3644           0 :   if (valuelen == 3 )
    3645           0 :     ul = (value[0] << 16) | (value[1] << 8) | value[2];
    3646             :   else
    3647             :     {
    3648           0 :       log_error (_("invalid structure of OpenPGP card (DO 0x93)\n"));
    3649           0 :       ul = 0;
    3650             :     }
    3651           0 :   return ul;
    3652             : }
    3653             : 
    3654             : static unsigned long
    3655           0 : get_sig_counter (app_t app)
    3656             : {
    3657             :   void *relptr;
    3658             :   unsigned char *value;
    3659             :   size_t valuelen;
    3660             :   unsigned long ul;
    3661             : 
    3662           0 :   relptr = get_one_do (app, 0x0093, &value, &valuelen, NULL);
    3663           0 :   if (!relptr)
    3664           0 :     return 0;
    3665           0 :   ul = convert_sig_counter_value (value, valuelen);
    3666           0 :   xfree (relptr);
    3667           0 :   return ul;
    3668             : }
    3669             : 
    3670             : static gpg_error_t
    3671           0 : compare_fingerprint (app_t app, int keyno, unsigned char *sha1fpr)
    3672             : {
    3673             :   const unsigned char *fpr;
    3674             :   unsigned char *buffer;
    3675             :   size_t buflen, n;
    3676             :   int rc, i;
    3677             : 
    3678           0 :   assert (keyno >= 0 && keyno <= 2);
    3679             : 
    3680           0 :   rc = get_cached_data (app, 0x006E, &buffer, &buflen, 0, 0);
    3681           0 :   if (rc)
    3682             :     {
    3683           0 :       log_error (_("error reading application data\n"));
    3684           0 :       return gpg_error (GPG_ERR_GENERAL);
    3685             :     }
    3686           0 :   fpr = find_tlv (buffer, buflen, 0x00C5, &n);
    3687           0 :   if (!fpr || n != 60)
    3688             :     {
    3689           0 :       xfree (buffer);
    3690           0 :       log_error (_("error reading fingerprint DO\n"));
    3691           0 :       return gpg_error (GPG_ERR_GENERAL);
    3692             :     }
    3693           0 :   fpr += keyno*20;
    3694           0 :   for (i=0; i < 20; i++)
    3695           0 :     if (sha1fpr[i] != fpr[i])
    3696             :       {
    3697           0 :         xfree (buffer);
    3698           0 :         log_info (_("fingerprint on card does not match requested one\n"));
    3699           0 :         return gpg_error (GPG_ERR_WRONG_SECKEY);
    3700             :       }
    3701           0 :   xfree (buffer);
    3702           0 :   return 0;
    3703             : }
    3704             : 
    3705             : 
    3706             : /* If a fingerprint has been specified check it against the one on the
    3707             :    card.  This allows for a meaningful error message in case the key
    3708             :    on the card has been replaced but the shadow information known to
    3709             :    gpg has not been updated.  If there is no fingerprint we assume
    3710             :    that this is okay. */
    3711             : static gpg_error_t
    3712           0 : check_against_given_fingerprint (app_t app, const char *fpr, int key)
    3713             : {
    3714             :   unsigned char tmp[20];
    3715             :   const char *s;
    3716             :   int n;
    3717             : 
    3718           0 :   for (s=fpr, n=0; hexdigitp (s); s++, n++)
    3719             :     ;
    3720           0 :   if (n != 40)
    3721           0 :     return gpg_error (GPG_ERR_INV_ID);
    3722           0 :   else if (!*s)
    3723             :     ; /* okay */
    3724             :   else
    3725           0 :     return gpg_error (GPG_ERR_INV_ID);
    3726             : 
    3727           0 :   for (s=fpr, n=0; n < 20; s += 2, n++)
    3728           0 :         tmp[n] = xtoi_2 (s);
    3729           0 :   return compare_fingerprint (app, key-1, tmp);
    3730             : }
    3731             : 
    3732             : 
    3733             : 
    3734             : /* Compute a digital signature on INDATA which is expected to be the
    3735             :    raw message digest. For this application the KEYIDSTR consists of
    3736             :    the serialnumber and the fingerprint delimited by a slash.
    3737             : 
    3738             :    Note that this function may return the error code
    3739             :    GPG_ERR_WRONG_CARD to indicate that the card currently present does
    3740             :    not match the one required for the requested action (e.g. the
    3741             :    serial number does not match).
    3742             : 
    3743             :    As a special feature a KEYIDSTR of "OPENPGP.3" redirects the
    3744             :    operation to the auth command.
    3745             : */
    3746             : static gpg_error_t
    3747           0 : do_sign (app_t app, const char *keyidstr, int hashalgo,
    3748             :          gpg_error_t (*pincb)(void*, const char *, char **),
    3749             :          void *pincb_arg,
    3750             :          const void *indata, size_t indatalen,
    3751             :          unsigned char **outdata, size_t *outdatalen )
    3752             : {
    3753             :   static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
    3754             :     { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
    3755             :       0x02, 0x01, 0x05, 0x00, 0x04, 0x14  };
    3756             :   static unsigned char sha1_prefix[15] =   /* (1.3.14.3.2.26) */
    3757             :     { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
    3758             :       0x02, 0x1a, 0x05, 0x00, 0x04, 0x14  };
    3759             :   static unsigned char sha224_prefix[19] = /* (2.16.840.1.101.3.4.2.4) */
    3760             :     { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
    3761             :       0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04,
    3762             :       0x1C  };
    3763             :   static unsigned char sha256_prefix[19] = /* (2.16.840.1.101.3.4.2.1) */
    3764             :     { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
    3765             :       0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
    3766             :       0x00, 0x04, 0x20  };
    3767             :   static unsigned char sha384_prefix[19] = /* (2.16.840.1.101.3.4.2.2) */
    3768             :     { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
    3769             :       0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
    3770             :       0x00, 0x04, 0x30  };
    3771             :   static unsigned char sha512_prefix[19] = /* (2.16.840.1.101.3.4.2.3) */
    3772             :     { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
    3773             :       0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
    3774             :       0x00, 0x04, 0x40  };
    3775             :   int rc;
    3776             :   unsigned char data[19+64];
    3777             :   size_t datalen;
    3778             :   unsigned char tmp_sn[20]; /* Actually 16 bytes but also for the fpr. */
    3779             :   const char *s;
    3780             :   int n;
    3781           0 :   const char *fpr = NULL;
    3782             :   unsigned long sigcount;
    3783           0 :   int use_auth = 0;
    3784             :   int exmode, le_value;
    3785             : 
    3786           0 :   if (!keyidstr || !*keyidstr)
    3787           0 :     return gpg_error (GPG_ERR_INV_VALUE);
    3788             : 
    3789             :   /* Strip off known prefixes.  */
    3790             : #define X(a,b,c,d) \
    3791             :   if (hashalgo == GCRY_MD_ ## a                               \
    3792             :       && (d)                                                  \
    3793             :       && indatalen == sizeof b ## _prefix + (c)               \
    3794             :       && !memcmp (indata, b ## _prefix, sizeof b ## _prefix)) \
    3795             :     {                                                         \
    3796             :       indata = (const char*)indata + sizeof b ## _prefix;     \
    3797             :       indatalen -= sizeof b ## _prefix;                       \
    3798             :     }
    3799             : 
    3800           0 :   if (indatalen == 20)
    3801             :     ;  /* Assume a plain SHA-1 or RMD160 digest has been given.  */
    3802           0 :   else X(SHA1,   sha1,   20, 1)
    3803           0 :   else X(RMD160, rmd160, 20, 1)
    3804           0 :   else X(SHA224, sha224, 28, app->app_local->extcap.is_v2)
    3805           0 :   else X(SHA256, sha256, 32, app->app_local->extcap.is_v2)
    3806           0 :   else X(SHA384, sha384, 48, app->app_local->extcap.is_v2)
    3807           0 :   else X(SHA512, sha512, 64, app->app_local->extcap.is_v2)
    3808           0 :   else if ((indatalen == 28 || indatalen == 32
    3809           0 :             || indatalen == 48 || indatalen ==64)
    3810           0 :            && app->app_local->extcap.is_v2)
    3811             :     ;  /* Assume a plain SHA-3 digest has been given.  */
    3812             :   else
    3813             :     {
    3814           0 :       log_error (_("card does not support digest algorithm %s\n"),
    3815             :                  gcry_md_algo_name (hashalgo));
    3816             :       /* Or the supplied digest length does not match an algorithm.  */
    3817           0 :       return gpg_error (GPG_ERR_INV_VALUE);
    3818             :     }
    3819             : #undef X
    3820             : 
    3821             :   /* Check whether an OpenPGP card of any version has been requested. */
    3822           0 :   if (!strcmp (keyidstr, "OPENPGP.1"))
    3823             :     ;
    3824           0 :   else if (!strcmp (keyidstr, "OPENPGP.3"))
    3825           0 :     use_auth = 1;
    3826           0 :   else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
    3827           0 :     return gpg_error (GPG_ERR_INV_ID);
    3828             :   else
    3829             :     {
    3830           0 :       for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
    3831             :         ;
    3832           0 :       if (n != 32)
    3833           0 :         return gpg_error (GPG_ERR_INV_ID);
    3834           0 :       else if (!*s)
    3835             :         ; /* no fingerprint given: we allow this for now. */
    3836           0 :       else if (*s == '/')
    3837           0 :         fpr = s + 1;
    3838             :       else
    3839           0 :         return gpg_error (GPG_ERR_INV_ID);
    3840             : 
    3841           0 :       for (s=keyidstr, n=0; n < 16; s += 2, n++)
    3842           0 :         tmp_sn[n] = xtoi_2 (s);
    3843             : 
    3844           0 :       if (app->serialnolen != 16)
    3845           0 :         return gpg_error (GPG_ERR_INV_CARD);
    3846           0 :       if (memcmp (app->serialno, tmp_sn, 16))
    3847           0 :         return gpg_error (GPG_ERR_WRONG_CARD);
    3848             :     }
    3849             : 
    3850             :   /* If a fingerprint has been specified check it against the one on
    3851             :      the card.  This is allows for a meaningful error message in case
    3852             :      the key on the card has been replaced but the shadow information
    3853             :      known to gpg was not updated.  If there is no fingerprint, gpg
    3854             :      will detect a bogus signature anyway due to the
    3855             :      verify-after-signing feature. */
    3856           0 :   rc = fpr? check_against_given_fingerprint (app, fpr, 1) : 0;
    3857           0 :   if (rc)
    3858           0 :     return rc;
    3859             : 
    3860             :   /* Concatenate prefix and digest.  */
    3861             : #define X(a,b,d) \
    3862             :   if (hashalgo == GCRY_MD_ ## a && (d) )                      \
    3863             :     {                                                         \
    3864             :       datalen = sizeof b ## _prefix + indatalen;              \
    3865             :       assert (datalen <= sizeof data);                        \
    3866             :       memcpy (data, b ## _prefix, sizeof b ## _prefix);       \
    3867             :       memcpy (data + sizeof b ## _prefix, indata, indatalen); \
    3868             :     }
    3869             : 
    3870           0 :   if (use_auth
    3871           0 :       || app->app_local->keyattr[use_auth? 2: 0].key_type == KEY_TYPE_RSA)
    3872             :     {
    3873           0 :       X(SHA1,   sha1,   1)
    3874           0 :       else X(RMD160, rmd160, 1)
    3875           0 :       else X(SHA224, sha224, app->app_local->extcap.is_v2)
    3876           0 :       else X(SHA256, sha256, app->app_local->extcap.is_v2)
    3877           0 :       else X(SHA384, sha384, app->app_local->extcap.is_v2)
    3878           0 :       else X(SHA512, sha512, app->app_local->extcap.is_v2)
    3879             :       else
    3880           0 :         return gpg_error (GPG_ERR_UNSUPPORTED_ALGORITHM);
    3881             :     }
    3882             :   else
    3883             :     {
    3884           0 :       datalen = indatalen;
    3885           0 :       memcpy (data, indata, indatalen);
    3886             :     }
    3887             : #undef X
    3888             : 
    3889             :   /* Redirect to the AUTH command if asked to. */
    3890           0 :   if (use_auth)
    3891             :     {
    3892           0 :       return do_auth (app, "OPENPGP.3", pincb, pincb_arg,
    3893             :                       data, datalen,
    3894             :                       outdata, outdatalen);
    3895             :     }
    3896             : 
    3897             :   /* Show the number of signature done using this key.  */
    3898           0 :   sigcount = get_sig_counter (app);
    3899           0 :   log_info (_("signatures created so far: %lu\n"), sigcount);
    3900             : 
    3901             :   /* Check CHV if needed.  */
    3902           0 :   if (!app->did_chv1 || app->force_chv1 )
    3903             :     {
    3904             :       char *pinvalue;
    3905             : 
    3906           0 :       rc = verify_a_chv (app, pincb, pincb_arg, 1, sigcount, &pinvalue);
    3907           0 :       if (rc)
    3908           0 :         return rc;
    3909             : 
    3910           0 :       app->did_chv1 = 1;
    3911             : 
    3912             :       /* For cards with versions < 2 we want to keep CHV1 and CHV2 in
    3913             :          sync, thus we verify CHV2 here using the given PIN.  Cards
    3914             :          with version2 to not have the need for a separate CHV2 and
    3915             :          internally use just one.  Obviously we can't do that if the
    3916             :          pinpad has been used. */
    3917           0 :       if (!app->did_chv2 && pinvalue && !app->app_local->extcap.is_v2)
    3918             :         {
    3919           0 :           rc = iso7816_verify (app->slot, 0x82, pinvalue, strlen (pinvalue));
    3920           0 :           if (gpg_err_code (rc) == GPG_ERR_BAD_PIN)
    3921           0 :             rc = gpg_error (GPG_ERR_PIN_NOT_SYNCED);
    3922           0 :           if (rc)
    3923             :             {
    3924           0 :               log_error (_("verify CHV%d failed: %s\n"), 2, gpg_strerror (rc));
    3925           0 :               xfree (pinvalue);
    3926           0 :               flush_cache_after_error (app);
    3927           0 :               return rc;
    3928             :             }
    3929           0 :           app->did_chv2 = 1;
    3930             :         }
    3931           0 :       xfree (pinvalue);
    3932             :     }
    3933             : 
    3934             : 
    3935           0 :   if (app->app_local->cardcap.ext_lc_le)
    3936             :     {
    3937           0 :       exmode = 1;    /* Use extended length.  */
    3938           0 :       le_value = app->app_local->extcap.max_rsp_data;
    3939             :     }
    3940             :   else
    3941             :     {
    3942           0 :       exmode = 0;
    3943           0 :       le_value = 0;
    3944             :     }
    3945           0 :   rc = iso7816_compute_ds (app->slot, exmode, data, datalen, le_value,
    3946             :                            outdata, outdatalen);
    3947           0 :   return rc;
    3948             : }
    3949             : 
    3950             : /* Compute a digital signature using the INTERNAL AUTHENTICATE command
    3951             :    on INDATA which is expected to be the raw message digest. For this
    3952             :    application the KEYIDSTR consists of the serialnumber and the
    3953             :    fingerprint delimited by a slash.  Optionally the id OPENPGP.3 may
    3954             :    be given.
    3955             : 
    3956             :    Note that this function may return the error code
    3957             :    GPG_ERR_WRONG_CARD to indicate that the card currently present does
    3958             :    not match the one required for the requested action (e.g. the
    3959             :    serial number does not match). */
    3960             : static gpg_error_t
    3961           0 : do_auth (app_t app, const char *keyidstr,
    3962             :          gpg_error_t (*pincb)(void*, const char *, char **),
    3963             :          void *pincb_arg,
    3964             :          const void *indata, size_t indatalen,
    3965             :          unsigned char **outdata, size_t *outdatalen )
    3966             : {
    3967             :   int rc;
    3968             :   unsigned char tmp_sn[20]; /* Actually 16 but we use it also for the fpr. */
    3969             :   const char *s;
    3970             :   int n;
    3971           0 :   const char *fpr = NULL;
    3972             : 
    3973           0 :   if (!keyidstr || !*keyidstr)
    3974           0 :     return gpg_error (GPG_ERR_INV_VALUE);
    3975           0 :   if (app->app_local->keyattr[2].key_type == KEY_TYPE_RSA
    3976           0 :       && indatalen > 101) /* For a 2048 bit key. */
    3977           0 :     return gpg_error (GPG_ERR_INV_VALUE);
    3978             : 
    3979           0 :   if (app->app_local->keyattr[2].key_type == KEY_TYPE_ECC)
    3980             :     {
    3981           0 :       if (!app->app_local->keyattr[2].ecc.flags
    3982           0 :           && (indatalen == 51 || indatalen == 67 || indatalen == 83))
    3983           0 :         {
    3984           0 :           const char *p = (const char *)indata + 19;
    3985           0 :           indata = p;
    3986           0 :           indatalen -= 19;
    3987             :         }
    3988             :       else
    3989             :         {
    3990           0 :           const char *p = (const char *)indata + 15;
    3991           0 :           indata = p;
    3992           0 :           indatalen -= 15;
    3993             :         }
    3994             :     }
    3995             : 
    3996             :   /* Check whether an OpenPGP card of any version has been requested. */
    3997           0 :   if (!strcmp (keyidstr, "OPENPGP.3"))
    3998             :     ;
    3999           0 :   else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
    4000           0 :     return gpg_error (GPG_ERR_INV_ID);
    4001             :   else
    4002             :     {
    4003           0 :       for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
    4004             :         ;
    4005           0 :       if (n != 32)
    4006           0 :         return gpg_error (GPG_ERR_INV_ID);
    4007           0 :       else if (!*s)
    4008             :         ; /* no fingerprint given: we allow this for now. */
    4009           0 :       else if (*s == '/')
    4010           0 :         fpr = s + 1;
    4011             :       else
    4012           0 :         return gpg_error (GPG_ERR_INV_ID);
    4013             : 
    4014           0 :       for (s=keyidstr, n=0; n < 16; s += 2, n++)
    4015           0 :         tmp_sn[n] = xtoi_2 (s);
    4016             : 
    4017           0 :       if (app->serialnolen != 16)
    4018           0 :         return gpg_error (GPG_ERR_INV_CARD);
    4019           0 :       if (memcmp (app->serialno, tmp_sn, 16))
    4020           0 :         return gpg_error (GPG_ERR_WRONG_CARD);
    4021             :     }
    4022             : 
    4023             :   /* If a fingerprint has been specified check it against the one on
    4024             :      the card.  This is allows for a meaningful error message in case
    4025             :      the key on the card has been replaced but the shadow information
    4026             :      known to gpg was not updated.  If there is no fingerprint, gpg
    4027             :      will detect a bogus signature anyway due to the
    4028             :      verify-after-signing feature. */
    4029           0 :   rc = fpr? check_against_given_fingerprint (app, fpr, 3) : 0;
    4030           0 :   if (rc)
    4031           0 :     return rc;
    4032             : 
    4033           0 :   rc = verify_chv2 (app, pincb, pincb_arg);
    4034           0 :   if (!rc)
    4035             :     {
    4036             :       int exmode, le_value;
    4037             : 
    4038           0 :       if (app->app_local->cardcap.ext_lc_le)
    4039             :         {
    4040           0 :           exmode = 1;    /* Use extended length.  */
    4041           0 :           le_value = app->app_local->extcap.max_rsp_data;
    4042             :         }
    4043             :       else
    4044             :         {
    4045           0 :           exmode = 0;
    4046           0 :           le_value = 0;
    4047             :         }
    4048           0 :       rc = iso7816_internal_authenticate (app->slot, exmode,
    4049             :                                           indata, indatalen, le_value,
    4050             :                                           outdata, outdatalen);
    4051             :     }
    4052           0 :   return rc;
    4053             : }
    4054             : 
    4055             : 
    4056             : static gpg_error_t
    4057           0 : do_decipher (app_t app, const char *keyidstr,
    4058             :              gpg_error_t (*pincb)(void*, const char *, char **),
    4059             :              void *pincb_arg,
    4060             :              const void *indata, size_t indatalen,
    4061             :              unsigned char **outdata, size_t *outdatalen,
    4062             :              unsigned int *r_info)
    4063             : {
    4064             :   int rc;
    4065             :   unsigned char tmp_sn[20]; /* actually 16 but we use it also for the fpr. */
    4066             :   const char *s;
    4067             :   int n;
    4068           0 :   const char *fpr = NULL;
    4069             :   int exmode, le_value;
    4070           0 :   unsigned char *fixbuf = NULL;
    4071           0 :   int padind = 0;
    4072           0 :   int fixuplen = 0;
    4073             : 
    4074           0 :   if (!keyidstr || !*keyidstr || !indatalen)
    4075           0 :     return gpg_error (GPG_ERR_INV_VALUE);
    4076             : 
    4077             :   /* Check whether an OpenPGP card of any version has been requested. */
    4078           0 :   if (!strcmp (keyidstr, "OPENPGP.2"))
    4079             :     ;
    4080           0 :   else if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
    4081           0 :     return gpg_error (GPG_ERR_INV_ID);
    4082             :   else
    4083             :     {
    4084           0 :       for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
    4085             :         ;
    4086           0 :       if (n != 32)
    4087           0 :         return gpg_error (GPG_ERR_INV_ID);
    4088           0 :       else if (!*s)
    4089             :         ; /* no fingerprint given: we allow this for now. */
    4090           0 :       else if (*s == '/')
    4091           0 :         fpr = s + 1;
    4092             :       else
    4093           0 :         return gpg_error (GPG_ERR_INV_ID);
    4094             : 
    4095           0 :       for (s=keyidstr, n=0; n < 16; s += 2, n++)
    4096           0 :         tmp_sn[n] = xtoi_2 (s);
    4097             : 
    4098           0 :       if (app->serialnolen != 16)
    4099           0 :         return gpg_error (GPG_ERR_INV_CARD);
    4100           0 :       if (memcmp (app->serialno, tmp_sn, 16))
    4101           0 :         return gpg_error (GPG_ERR_WRONG_CARD);
    4102             :     }
    4103             : 
    4104             :   /* If a fingerprint has been specified check it against the one on
    4105             :      the card.  This is allows for a meaningful error message in case
    4106             :      the key on the card has been replaced but the shadow information
    4107             :      known to gpg was not updated.  If there is no fingerprint, the
    4108             :      decryption won't produce the right plaintext anyway. */
    4109           0 :   rc = fpr? check_against_given_fingerprint (app, fpr, 2) : 0;
    4110           0 :   if (rc)
    4111           0 :     return rc;
    4112             : 
    4113           0 :   rc = verify_chv2 (app, pincb, pincb_arg);
    4114           0 :   if (rc)
    4115           0 :     return rc;
    4116             : 
    4117           0 :   if (indatalen == 16 + 1 || indatalen == 32 + 1)
    4118             :     /* PSO:DECIPHER with symmetric key.  */
    4119           0 :     padind = -1;
    4120           0 :   else if (app->app_local->keyattr[1].key_type == KEY_TYPE_RSA)
    4121             :     {
    4122             :       /* We might encounter a couple of leading zeroes in the
    4123             :          cryptogram.  Due to internal use of MPIs these leading zeroes
    4124             :          are stripped.  However the OpenPGP card expects exactly 128
    4125             :          bytes for the cryptogram (for a 1k key).  Thus we need to fix
    4126             :          it up.  We do this for up to 16 leading zero bytes; a
    4127             :          cryptogram with more than this is with a very high
    4128             :          probability anyway broken.  If a signed conversion was used
    4129             :          we may also encounter one leading zero followed by the correct
    4130             :          length.  We fix that as well.  */
    4131           0 :       if (indatalen >= (128-16) && indatalen < 128)      /* 1024 bit key.  */
    4132           0 :         fixuplen = 128 - indatalen;
    4133           0 :       else if (indatalen >= (192-16) && indatalen < 192) /* 1536 bit key.  */
    4134           0 :         fixuplen = 192 - indatalen;
    4135           0 :       else if (indatalen >= (256-16) && indatalen < 256) /* 2048 bit key.  */
    4136           0 :         fixuplen = 256 - indatalen;
    4137           0 :       else if (indatalen >= (384-16) && indatalen < 384) /* 3072 bit key.  */
    4138           0 :         fixuplen = 384 - indatalen;
    4139           0 :       else if (indatalen >= (512-16) && indatalen < 512) /* 4096 bit key.  */
    4140           0 :         fixuplen = 512 - indatalen;
    4141           0 :       else if (!*(const char *)indata && (indatalen == 129
    4142           0 :                                           || indatalen == 193
    4143           0 :                                           || indatalen == 257
    4144           0 :                                           || indatalen == 385
    4145           0 :                                           || indatalen == 513))
    4146           0 :         fixuplen = -1;
    4147             :       else
    4148           0 :         fixuplen = 0;
    4149             : 
    4150           0 :       if (fixuplen > 0)
    4151             :         {
    4152             :           /* While we have to prepend stuff anyway, we can also
    4153             :              include the padding byte here so that iso1816_decipher
    4154             :              does not need to do another data mangling.  */
    4155           0 :           fixuplen++;
    4156             : 
    4157           0 :           fixbuf = xtrymalloc (fixuplen + indatalen);
    4158           0 :           if (!fixbuf)
    4159           0 :             return gpg_error_from_syserror ();
    4160             : 
    4161           0 :           memset (fixbuf, 0, fixuplen);
    4162           0 :           memcpy (fixbuf+fixuplen, indata, indatalen);
    4163           0 :           indata = fixbuf;
    4164           0 :           indatalen = fixuplen + indatalen;
    4165           0 :           padind = -1; /* Already padded.  */
    4166             :         }
    4167           0 :       else if (fixuplen < 0)
    4168             :         {
    4169             :           /* We use the extra leading zero as the padding byte.  */
    4170           0 :           padind = -1;
    4171             :         }
    4172             :     }
    4173           0 :   else if (app->app_local->keyattr[1].key_type == KEY_TYPE_ECC)
    4174             :     {
    4175           0 :       fixuplen = 7;
    4176           0 :       fixbuf = xtrymalloc (fixuplen + indatalen);
    4177           0 :       if (!fixbuf)
    4178           0 :         return gpg_error_from_syserror ();
    4179             : 
    4180             :       /* Build 'Cipher DO' */
    4181           0 :       fixbuf[0] = '\xa6';
    4182           0 :       fixbuf[1] = (char)(indatalen+5);
    4183           0 :       fixbuf[2] = '\x7f';
    4184           0 :       fixbuf[3] = '\x49';
    4185           0 :       fixbuf[4] = (char)(indatalen+2);
    4186           0 :       fixbuf[5] = '\x86';
    4187           0 :       fixbuf[6] = (char)indatalen;
    4188           0 :       memcpy (fixbuf+fixuplen, indata, indatalen);
    4189           0 :       indata = fixbuf;
    4190           0 :       indatalen = fixuplen + indatalen;
    4191             : 
    4192           0 :       padind = -1;
    4193             :     }
    4194             :   else
    4195           0 :     return gpg_error (GPG_ERR_INV_VALUE);
    4196             : 
    4197           0 :   if (app->app_local->cardcap.ext_lc_le && indatalen > 254 )
    4198             :     {
    4199           0 :       exmode = 1;    /* Extended length w/o a limit.  */
    4200           0 :       le_value = app->app_local->extcap.max_rsp_data;
    4201             :     }
    4202           0 :   else if (app->app_local->cardcap.cmd_chaining && indatalen > 254)
    4203             :     {
    4204           0 :       exmode = -254; /* Command chaining with max. 254 bytes.  */
    4205           0 :       le_value = 0;
    4206             :     }
    4207             :   else
    4208           0 :     exmode = le_value = 0;
    4209             : 
    4210           0 :   rc = iso7816_decipher (app->slot, exmode,
    4211             :                          indata, indatalen, le_value, padind,
    4212             :                          outdata, outdatalen);
    4213           0 :   xfree (fixbuf);
    4214             : 
    4215           0 :   if (gpg_err_code (rc) == GPG_ERR_CARD /* actual SW is 0x640a */
    4216           0 :       && app->app_local->manufacturer == 5
    4217           0 :       && app->card_version == 0x0200)
    4218           0 :     log_info ("NOTE: Cards with manufacturer id 5 and s/n <= 346 (0x15a)"
    4219             :               " do not work with encryption keys > 2048 bits\n");
    4220             : 
    4221           0 :   *r_info |= APP_DECIPHER_INFO_NOPAD;
    4222             : 
    4223           0 :   return rc;
    4224             : }
    4225             : 
    4226             : 
    4227             : /* Perform a simple verify operation for CHV1 and CHV2, so that
    4228             :    further operations won't ask for CHV2 and it is possible to do a
    4229             :    cheap check on the PIN: If there is something wrong with the PIN
    4230             :    entry system, only the regular CHV will get blocked and not the
    4231             :    dangerous CHV3.  KEYIDSTR is the usual card's serial number; an
    4232             :    optional fingerprint part will be ignored.
    4233             : 
    4234             :    There is a special mode if the keyidstr is "<serialno>[CHV3]" with
    4235             :    the "[CHV3]" being a literal string:  The Admin Pin is checked if
    4236             :    and only if the retry counter is still at 3. */
    4237             : static gpg_error_t
    4238           0 : do_check_pin (app_t app, const char *keyidstr,
    4239             :               gpg_error_t (*pincb)(void*, const char *, char **),
    4240             :               void *pincb_arg)
    4241             : {
    4242             :   unsigned char tmp_sn[20];
    4243             :   const char *s;
    4244             :   int n;
    4245           0 :   int admin_pin = 0;
    4246             : 
    4247           0 :   if (!keyidstr || !*keyidstr)
    4248           0 :     return gpg_error (GPG_ERR_INV_VALUE);
    4249             : 
    4250             :   /* Check whether an OpenPGP card of any version has been requested. */
    4251           0 :   if (strlen (keyidstr) < 32 || strncmp (keyidstr, "D27600012401", 12))
    4252           0 :     return gpg_error (GPG_ERR_INV_ID);
    4253             : 
    4254           0 :   for (s=keyidstr, n=0; hexdigitp (s); s++, n++)
    4255             :     ;
    4256           0 :   if (n != 32)
    4257           0 :     return gpg_error (GPG_ERR_INV_ID);
    4258           0 :   else if (!*s)
    4259             :     ; /* No fingerprint given: we allow this for now. */
    4260           0 :   else if (*s == '/')
    4261             :     ; /* We ignore a fingerprint. */
    4262           0 :   else if (!strcmp (s, "[CHV3]") )
    4263           0 :     admin_pin = 1;
    4264             :   else
    4265           0 :     return gpg_error (GPG_ERR_INV_ID);
    4266             : 
    4267           0 :   for (s=keyidstr, n=0; n < 16; s += 2, n++)
    4268           0 :     tmp_sn[n] = xtoi_2 (s);
    4269             : 
    4270           0 :   if (app->serialnolen != 16)
    4271           0 :     return gpg_error (GPG_ERR_INV_CARD);
    4272           0 :   if (memcmp (app->serialno, tmp_sn, 16))
    4273           0 :     return gpg_error (GPG_ERR_WRONG_CARD);
    4274             : 
    4275             :   /* Yes, there is a race conditions: The user might pull the card
    4276             :      right here and we won't notice that.  However this is not a
    4277             :      problem and the check above is merely for a graceful failure
    4278             :      between operations. */
    4279             : 
    4280           0 :   if (admin_pin)
    4281             :     {
    4282             :       void *relptr;
    4283             :       unsigned char *value;
    4284             :       size_t valuelen;
    4285             :       int count;
    4286             : 
    4287           0 :       relptr = get_one_do (app, 0x00C4, &value, &valuelen, NULL);
    4288           0 :       if (!relptr || valuelen < 7)
    4289             :         {
    4290           0 :           log_error (_("error retrieving CHV status from card\n"));
    4291           0 :           xfree (relptr);
    4292           0 :           return gpg_error (GPG_ERR_CARD);
    4293             :         }
    4294           0 :       count = value[6];
    4295           0 :       xfree (relptr);
    4296             : 
    4297           0 :       if (!count)
    4298             :         {
    4299           0 :           log_info (_("card is permanently locked!\n"));
    4300           0 :           return gpg_error (GPG_ERR_BAD_PIN);
    4301             :         }
    4302           0 :       else if (count < 3)
    4303             :         {
    4304           0 :           log_info (_("verification of Admin PIN is currently prohibited "
    4305             :                       "through this command\n"));
    4306           0 :           return gpg_error (GPG_ERR_GENERAL);
    4307             :         }
    4308             : 
    4309           0 :       app->did_chv3 = 0; /* Force verification.  */
    4310           0 :       return verify_chv3 (app, pincb, pincb_arg);
    4311             :     }
    4312             :   else
    4313           0 :     return verify_chv2 (app, pincb, pincb_arg);
    4314             : }
    4315             : 
    4316             : 
    4317             : /* Show information about card capabilities.  */
    4318             : static void
    4319           0 : show_caps (struct app_local_s *s)
    4320             : {
    4321           0 :   log_info ("Version-2 ......: %s\n", s->extcap.is_v2? "yes":"no");
    4322           0 :   log_info ("Get-Challenge ..: %s", s->extcap.get_challenge? "yes":"no");
    4323           0 :   if (s->extcap.get_challenge)
    4324           0 :     log_printf (" (%u bytes max)", s->extcap.max_get_challenge);
    4325           0 :   log_info ("Key-Import .....: %s\n", s->extcap.key_import? "yes":"no");
    4326           0 :   log_info ("Change-Force-PW1: %s\n", s->extcap.change_force_chv? "yes":"no");
    4327           0 :   log_info ("Private-DOs ....: %s\n", s->extcap.private_dos? "yes":"no");
    4328           0 :   log_info ("Algo-Attr-Change: %s\n", s->extcap.algo_attr_change? "yes":"no");
    4329           0 :   log_info ("SM-Support .....: %s", s->extcap.sm_supported? "yes":"no");
    4330           0 :   if (s->extcap.sm_supported)
    4331           0 :     log_printf (" (%s)", s->extcap.sm_algo==2? "3DES":
    4332           0 :                 (s->extcap.sm_algo==2? "AES-128" : "AES-256"));
    4333           0 :   log_info ("Max-Cert3-Len ..: %u\n", s->extcap.max_certlen_3);
    4334           0 :   log_info ("Max-Cmd-Data ...: %u\n", s->extcap.max_cmd_data);
    4335           0 :   log_info ("Max-Rsp-Data ...: %u\n", s->extcap.max_rsp_data);
    4336           0 :   log_info ("Cmd-Chaining ...: %s\n", s->cardcap.cmd_chaining?"yes":"no");
    4337           0 :   log_info ("Ext-Lc-Le ......: %s\n", s->cardcap.ext_lc_le?"yes":"no");
    4338           0 :   log_info ("Status Indicator: %02X\n", s->status_indicator);
    4339           0 :   log_info ("Symmetric crypto: %s\n", s->extcap.has_decrypt? "yes":"no");
    4340           0 :   log_info ("Button..........: %s\n", s->extcap.has_button? "yes":"no");
    4341             : 
    4342           0 :   log_info ("GnuPG-No-Sync ..: %s\n",  s->flags.no_sync? "yes":"no");
    4343           0 :   log_info ("GnuPG-Def-PW2 ..: %s\n",  s->flags.def_chv2? "yes":"no");
    4344           0 : }
    4345             : 
    4346             : 
    4347             : /* Parse the historical bytes in BUFFER of BUFLEN and store them in
    4348             :    APPLOC.  */
    4349             : static void
    4350           0 : parse_historical (struct app_local_s *apploc,
    4351             :                   const unsigned char * buffer, size_t buflen)
    4352             : {
    4353             :   /* Example buffer: 00 31 C5 73 C0 01 80 00 90 00  */
    4354           0 :   if (buflen < 4)
    4355             :     {
    4356           0 :       log_error ("warning: historical bytes are too short\n");
    4357           0 :       return; /* Too short.  */
    4358             :     }
    4359           0 :   if (*buffer)
    4360             :     {
    4361           0 :       log_error ("warning: bad category indicator in historical bytes\n");
    4362           0 :       return;
    4363             :     }
    4364             : 
    4365             :   /* Skip category indicator.  */
    4366           0 :   buffer++;
    4367           0 :   buflen--;
    4368             : 
    4369             :   /* Get the status indicator.  */
    4370           0 :   apploc->status_indicator = buffer[buflen-3];
    4371           0 :   buflen -= 3;
    4372             : 
    4373             :   /* Parse the compact TLV.  */
    4374           0 :   while (buflen)
    4375             :     {
    4376           0 :       unsigned int tag = (*buffer & 0xf0) >> 4;
    4377           0 :       unsigned int len = (*buffer & 0x0f);
    4378           0 :       if (len+1 > buflen)
    4379             :         {
    4380           0 :           log_error ("warning: bad Compact-TLV in historical bytes\n");
    4381           0 :           return; /* Error.  */
    4382             :         }
    4383           0 :       buffer++;
    4384           0 :       buflen--;
    4385           0 :       if (tag == 7 && len == 3)
    4386             :         {
    4387             :           /* Card capabilities.  */
    4388           0 :           apploc->cardcap.cmd_chaining = !!(buffer[2] & 0x80);
    4389           0 :           apploc->cardcap.ext_lc_le    = !!(buffer[2] & 0x40);
    4390             :         }
    4391           0 :       buffer += len;
    4392           0 :       buflen -= len;
    4393             :     }
    4394             : }
    4395             : 
    4396             : 
    4397             : /*
    4398             :  * Check if the OID in an DER encoding is available by GnuPG/libgcrypt,
    4399             :  * and return the constant string in dotted decimal form.
    4400             :  * Return NULL if not available.
    4401             :  * The constant string is not allocated dynamically, never free it.
    4402             :  */
    4403             : static const char *
    4404           0 : ecc_oid (unsigned char *buf, size_t buflen)
    4405             : {
    4406             :   gcry_mpi_t oid;
    4407             :   char *oidstr;
    4408             :   const char *result;
    4409             :   unsigned char *oidbuf;
    4410             : 
    4411           0 :   oidbuf = xtrymalloc (buflen + 1);
    4412           0 :   if (!oidbuf)
    4413           0 :     return NULL;
    4414             : 
    4415           0 :   memcpy (oidbuf+1, buf, buflen);
    4416           0 :   oidbuf[0] = buflen;
    4417           0 :   oid = gcry_mpi_set_opaque (NULL, oidbuf, (buflen+1) * 8);
    4418           0 :   if (!oid)
    4419             :     {
    4420           0 :       xfree (oidbuf);
    4421           0 :       return NULL;
    4422             :     }
    4423             : 
    4424           0 :   oidstr = openpgp_oid_to_str (oid);
    4425           0 :   gcry_mpi_release (oid);
    4426           0 :   if (!oidstr)
    4427           0 :     return NULL;
    4428             : 
    4429           0 :   result = openpgp_curve_to_oid (oidstr, NULL);
    4430           0 :   xfree (oidstr);
    4431           0 :   return result;
    4432             : }
    4433             : 
    4434             : 
    4435             : /* Parse and optionally show the algorithm attributes for KEYNO.
    4436             :    KEYNO must be in the range 0..2.  */
    4437             : static void
    4438           0 : parse_algorithm_attribute (app_t app, int keyno)
    4439             : {
    4440             :   unsigned char *buffer;
    4441             :   size_t buflen;
    4442             :   void *relptr;
    4443           0 :   const char desc[3][5] = {"sign", "encr", "auth"};
    4444             : 
    4445           0 :   assert (keyno >=0 && keyno <= 2);
    4446             : 
    4447           0 :   app->app_local->keyattr[keyno].key_type = KEY_TYPE_RSA;
    4448           0 :   app->app_local->keyattr[keyno].rsa.n_bits = 0;
    4449             : 
    4450           0 :   relptr = get_one_do (app, 0xC1+keyno, &buffer, &buflen, NULL);
    4451           0 :   if (!relptr)
    4452             :     {
    4453           0 :       log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
    4454           0 :       return;
    4455             :     }
    4456           0 :   if (buflen < 1)
    4457             :     {
    4458           0 :       log_error ("error reading DO 0x%02X\n", 0xc1+keyno);
    4459           0 :       xfree (relptr);
    4460           0 :       return;
    4461             :     }
    4462             : 
    4463           0 :   if (opt.verbose)
    4464           0 :     log_info ("Key-Attr-%s ..: ", desc[keyno]);
    4465           0 :   if (*buffer == PUBKEY_ALGO_RSA && (buflen == 5 || buflen == 6))
    4466             :     {
    4467           0 :       app->app_local->keyattr[keyno].rsa.n_bits = (buffer[1]<<8 | buffer[2]);
    4468           0 :       app->app_local->keyattr[keyno].rsa.e_bits = (buffer[3]<<8 | buffer[4]);
    4469           0 :       app->app_local->keyattr[keyno].rsa.format = 0;
    4470           0 :       if (buflen < 6)
    4471           0 :         app->app_local->keyattr[keyno].rsa.format = RSA_STD;
    4472             :       else
    4473           0 :         app->app_local->keyattr[keyno].rsa.format = (buffer[5] == 0? RSA_STD   :
    4474           0 :                                                      buffer[5] == 1? RSA_STD_N :
    4475           0 :                                                      buffer[5] == 2? RSA_CRT   :
    4476           0 :                                                      buffer[5] == 3? RSA_CRT_N :
    4477             :                                                      RSA_UNKNOWN_FMT);
    4478             : 
    4479           0 :       if (opt.verbose)
    4480           0 :         log_printf
    4481             :           ("RSA, n=%u, e=%u, fmt=%s\n",
    4482           0 :            app->app_local->keyattr[keyno].rsa.n_bits,
    4483           0 :            app->app_local->keyattr[keyno].rsa.e_bits,
    4484           0 :            app->app_local->keyattr[keyno].rsa.format == RSA_STD?  "std"  :
    4485           0 :            app->app_local->keyattr[keyno].rsa.format == RSA_STD_N?"std+n":
    4486           0 :            app->app_local->keyattr[keyno].rsa.format == RSA_CRT?  "crt"  :
    4487           0 :            app->app_local->keyattr[keyno].rsa.format == RSA_CRT_N?"crt+n":"?");
    4488             :     }
    4489           0 :   else if (*buffer == PUBKEY_ALGO_ECDH || *buffer == PUBKEY_ALGO_ECDSA
    4490           0 :            || *buffer == PUBKEY_ALGO_EDDSA)
    4491           0 :     {
    4492           0 :       const char *oid = ecc_oid (buffer + 1, buflen - 1);
    4493             : 
    4494           0 :       if (!oid)
    4495           0 :         log_printhex ("Curve with OID not supported: ", buffer+1, buflen-1);
    4496             :       else
    4497             :         {
    4498           0 :           app->app_local->keyattr[keyno].key_type = KEY_TYPE_ECC;
    4499           0 :           app->app_local->keyattr[keyno].ecc.oid = oid;
    4500           0 :           if (*buffer == PUBKEY_ALGO_EDDSA
    4501           0 :               || (*buffer == PUBKEY_ALGO_ECDH
    4502           0 :                   && !strcmp (app->app_local->keyattr[keyno].ecc.oid,
    4503             :                               "1.3.6.1.4.1.3029.1.5.1")))
    4504           0 :             app->app_local->keyattr[keyno].ecc.flags = ECC_FLAG_DJB_TWEAK;
    4505             :           else
    4506           0 :             app->app_local->keyattr[keyno].ecc.flags = 0;
    4507           0 :           if (opt.verbose)
    4508           0 :             log_printf
    4509           0 :               ("ECC, curve=%s%s\n", app->app_local->keyattr[keyno].ecc.oid,
    4510           0 :                !app->app_local->keyattr[keyno].ecc.flags ? "":
    4511           0 :                keyno==1? " (djb-tweak)": " (eddsa)");
    4512             :         }
    4513             :     }
    4514           0 :   else if (opt.verbose)
    4515           0 :     log_printhex ("", buffer, buflen);
    4516             : 
    4517           0 :   xfree (relptr);
    4518             : }
    4519             : 
    4520             : /* Select the OpenPGP application on the card in SLOT.  This function
    4521             :    must be used before any other OpenPGP application functions. */
    4522             : gpg_error_t
    4523           0 : app_select_openpgp (app_t app)
    4524             : {
    4525             :   static char const aid[] = { 0xD2, 0x76, 0x00, 0x01, 0x24, 0x01 };
    4526           0 :   int slot = app->slot;
    4527             :   int rc;
    4528             :   unsigned char *buffer;
    4529             :   size_t buflen;
    4530             :   void *relptr;
    4531             : 
    4532             :   /* Note that the card can't cope with P2=0xCO, thus we need to pass a
    4533             :      special flag value. */
    4534           0 :   rc = iso7816_select_application (slot, aid, sizeof aid, 0x0001);
    4535           0 :   if (!rc)
    4536             :     {
    4537             :       unsigned int manufacturer;
    4538             : 
    4539           0 :       app->apptype = "OPENPGP";
    4540             : 
    4541           0 :       app->did_chv1 = 0;
    4542           0 :       app->did_chv2 = 0;
    4543           0 :       app->did_chv3 = 0;
    4544           0 :       app->app_local = NULL;
    4545             : 
    4546             :       /* The OpenPGP card returns the serial number as part of the
    4547             :          AID; because we prefer to use OpenPGP serial numbers, we
    4548             :          replace a possibly already set one from a EF.GDO with this
    4549             :          one.  Note, that for current OpenPGP cards, no EF.GDO exists
    4550             :          and thus it won't matter at all. */
    4551           0 :       rc = iso7816_get_data (slot, 0, 0x004F, &buffer, &buflen);
    4552           0 :       if (rc)
    4553           0 :         goto leave;
    4554           0 :       if (opt.verbose)
    4555             :         {
    4556           0 :           log_info ("AID: ");
    4557           0 :           log_printhex ("", buffer, buflen);
    4558             :         }
    4559             : 
    4560           0 :       app->card_version = buffer[6] << 8;
    4561           0 :       app->card_version |= buffer[7];
    4562           0 :       manufacturer = (buffer[8]<<8 | buffer[9]);
    4563             : 
    4564           0 :       xfree (app->serialno);
    4565           0 :       app->serialno = buffer;
    4566           0 :       app->serialnolen = buflen;
    4567           0 :       buffer = NULL;
    4568           0 :       app->app_local = xtrycalloc (1, sizeof *app->app_local);
    4569           0 :       if (!app->app_local)
    4570             :         {
    4571           0 :           rc = gpg_error (gpg_err_code_from_errno (errno));
    4572           0 :           goto leave;
    4573             :         }
    4574             : 
    4575           0 :       app->app_local->manufacturer = manufacturer;
    4576             : 
    4577           0 :       if (app->card_version >= 0x0200)
    4578           0 :         app->app_local->extcap.is_v2 = 1;
    4579             : 
    4580             : 
    4581             :       /* Read the historical bytes.  */
    4582           0 :       relptr = get_one_do (app, 0x5f52, &buffer, &buflen, NULL);
    4583           0 :       if (relptr)
    4584             :         {
    4585           0 :           if (opt.verbose)
    4586             :             {
    4587           0 :               log_info ("Historical Bytes: ");
    4588           0 :               log_printhex ("", buffer, buflen);
    4589             :             }
    4590           0 :           parse_historical (app->app_local, buffer, buflen);
    4591           0 :           xfree (relptr);
    4592             :         }
    4593             : 
    4594             :       /* Read the force-chv1 flag.  */
    4595           0 :       relptr = get_one_do (app, 0x00C4, &buffer, &buflen, NULL);
    4596           0 :       if (!relptr)
    4597             :         {
    4598           0 :           log_error (_("can't access %s - invalid OpenPGP card?\n"),
    4599             :                      "CHV Status Bytes");
    4600           0 :           goto leave;
    4601             :         }
    4602           0 :       app->force_chv1 = (buflen && *buffer == 0);
    4603           0 :       xfree (relptr);
    4604             : 
    4605             :       /* Read the extended capabilities.  */
    4606           0 :       relptr = get_one_do (app, 0x00C0, &buffer, &buflen, NULL);
    4607           0 :       if (!relptr)
    4608             :         {
    4609           0 :           log_error (_("can't access %s - invalid OpenPGP card?\n"),
    4610             :                      "Extended Capability Flags" );
    4611           0 :           goto leave;
    4612             :         }
    4613           0 :       if (buflen)
    4614             :         {
    4615           0 :           app->app_local->extcap.sm_supported     = !!(*buffer & 0x80);
    4616           0 :           app->app_local->extcap.get_challenge    = !!(*buffer & 0x40);
    4617           0 :           app->app_local->extcap.key_import       = !!(*buffer & 0x20);
    4618           0 :           app->app_local->extcap.change_force_chv = !!(*buffer & 0x10);
    4619           0 :           app->app_local->extcap.private_dos      = !!(*buffer & 0x08);
    4620           0 :           app->app_local->extcap.algo_attr_change = !!(*buffer & 0x04);
    4621           0 :           app->app_local->extcap.has_decrypt      = !!(*buffer & 0x02);
    4622             :         }
    4623           0 :       if (buflen >= 10)
    4624             :         {
    4625             :           /* Available with v2 cards.  */
    4626           0 :           app->app_local->extcap.sm_algo = buffer[1];
    4627           0 :           app->app_local->extcap.max_get_challenge
    4628           0 :                                                = (buffer[2] << 8 | buffer[3]);
    4629           0 :           app->app_local->extcap.max_certlen_3 = (buffer[4] << 8 | buffer[5]);
    4630           0 :           app->app_local->extcap.max_cmd_data  = (buffer[6] << 8 | buffer[7]);
    4631           0 :           app->app_local->extcap.max_rsp_data  = (buffer[8] << 8 | buffer[9]);
    4632             :         }
    4633           0 :       xfree (relptr);
    4634             : 
    4635             :       /* Some of the first cards accidently don't set the
    4636             :          CHANGE_FORCE_CHV bit but allow it anyway. */
    4637           0 :       if (app->card_version <= 0x0100 && manufacturer == 1)
    4638           0 :         app->app_local->extcap.change_force_chv = 1;
    4639             : 
    4640             :       /* Check optional DO of "General Feature Management" for button.  */
    4641           0 :       relptr = get_one_do (app, 0x7f74, &buffer, &buflen, NULL);
    4642           0 :       if (relptr)
    4643             :         /* It must be: 03 81 01 20 */
    4644           0 :         app->app_local->extcap.has_button = 1;
    4645             : 
    4646           0 :       parse_login_data (app);
    4647             : 
    4648           0 :       if (opt.verbose)
    4649           0 :         show_caps (app->app_local);
    4650             : 
    4651           0 :       parse_algorithm_attribute (app, 0);
    4652           0 :       parse_algorithm_attribute (app, 1);
    4653           0 :       parse_algorithm_attribute (app, 2);
    4654             : 
    4655           0 :       if (opt.verbose > 1)
    4656           0 :         dump_all_do (slot);
    4657             : 
    4658           0 :       app->fnc.deinit = do_deinit;
    4659           0 :       app->fnc.learn_status = do_learn_status;
    4660           0 :       app->fnc.readcert = do_readcert;
    4661           0 :       app->fnc.readkey = do_readkey;
    4662           0 :       app->fnc.getattr = do_getattr;
    4663           0 :       app->fnc.setattr = do_setattr;
    4664           0 :       app->fnc.writecert = do_writecert;
    4665           0 :       app->fnc.writekey = do_writekey;
    4666           0 :       app->fnc.genkey = do_genkey;
    4667           0 :       app->fnc.sign = do_sign;
    4668           0 :       app->fnc.auth = do_auth;
    4669           0 :       app->fnc.decipher = do_decipher;
    4670           0 :       app->fnc.change_pin = do_change_pin;
    4671           0 :       app->fnc.check_pin = do_check_pin;
    4672             :    }
    4673             : 
    4674             : leave:
    4675           0 :   if (rc)
    4676           0 :     do_deinit (app);
    4677           0 :   return rc;
    4678             : }

Generated by: LCOV version 1.11