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

Generated by: LCOV version 1.11