LCOV - code coverage report
Current view: top level - scd - app-sc-hsm.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 0 913 0.0 %
Date: 2015-11-05 17:10:59 Functions: 0 28 0.0 %

          Line data    Source code
       1             : /* app-sc-hsm.c - The SmartCard-HSM card application (www.smartcard-hsm.com).
       2             :  *      Copyright (C) 2005 Free Software Foundation, Inc.
       3             :  *      Copyright (C) 2014 Andreas Schwier <andreas.schwier@cardcontact.de>
       4             :  *
       5             :  * This file is part of GnuPG.
       6             :  *
       7             :  * GnuPG is free software; you can redistribute it and/or modify
       8             :  * it under the terms of the GNU General Public License as published by
       9             :  * the Free Software Foundation; either version 3 of the License, or
      10             :  * (at your option) any later version.
      11             :  *
      12             :  * GnuPG is distributed in the hope that it will be useful,
      13             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      14             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      15             :  * GNU General Public License for more details.
      16             :  *
      17             :  * You should have received a copy of the GNU General Public License
      18             :  * along with this program; if not, see <http://www.gnu.org/licenses/>.
      19             :  */
      20             : 
      21             : /*
      22             :    Code in this driver is based on app-p15.c with modifications.
      23             :  */
      24             : 
      25             : #include <config.h>
      26             : #include <errno.h>
      27             : #include <stdio.h>
      28             : #include <stdlib.h>
      29             : #include <string.h>
      30             : #include <assert.h>
      31             : #include <time.h>
      32             : 
      33             : #include "scdaemon.h"
      34             : 
      35             : #include "iso7816.h"
      36             : #include "app-common.h"
      37             : #include "tlv.h"
      38             : #include "apdu.h"
      39             : 
      40             : 
      41             : /* The AID of the SmartCard-HSM applet. */
      42             : static char const sc_hsm_aid[] = { 0xE8, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x81,
      43             :                                    0xC3, 0x1F, 0x02, 0x01  };
      44             : 
      45             : 
      46             : /* Special file identifier for SmartCard-HSM */
      47             : typedef enum
      48             : {
      49             :     SC_HSM_PRKD_PREFIX = 0xC4,
      50             :     SC_HSM_CD_PREFIX = 0xC8,
      51             :     SC_HSM_DCOD_PREFIX = 0xC9,
      52             :     SC_HSM_CA_PREFIX = 0xCA,
      53             :     SC_HSM_KEY_PREFIX = 0xCC,
      54             :     SC_HSM_EE_PREFIX = 0xCE
      55             : } fid_prefix_type_t;
      56             : 
      57             : 
      58             : /* The key types supported by the SmartCard-HSM */
      59             : typedef enum
      60             :   {
      61             :     KEY_TYPE_RSA,
      62             :     KEY_TYPE_ECC
      63             :   } key_type_t;
      64             : 
      65             : 
      66             : /* A bit array with for the key usage flags from the
      67             :    commonKeyAttributes. */
      68             : struct keyusage_flags_s
      69             : {
      70             :     unsigned int encrypt: 1;
      71             :     unsigned int decrypt: 1;
      72             :     unsigned int sign: 1;
      73             :     unsigned int sign_recover: 1;
      74             :     unsigned int wrap: 1;
      75             :     unsigned int unwrap: 1;
      76             :     unsigned int verify: 1;
      77             :     unsigned int verify_recover: 1;
      78             :     unsigned int derive: 1;
      79             :     unsigned int non_repudiation: 1;
      80             : };
      81             : typedef struct keyusage_flags_s keyusage_flags_t;
      82             : 
      83             : 
      84             : 
      85             : /* This is an object to store information about a Certificate
      86             :    Directory File (CDF) in a format suitable for further processing by
      87             :    us. To keep memory management, simple we use a linked list of
      88             :    items; i.e. one such object represents one certificate and the list
      89             :    the entire CDF. */
      90             : struct cdf_object_s
      91             : {
      92             :   /* Link to next item when used in a linked list. */
      93             :   struct cdf_object_s *next;
      94             : 
      95             :   /* Length and allocated buffer with the Id of this object. */
      96             :   size_t objidlen;
      97             :   unsigned char *objid;
      98             : 
      99             :   /* To avoid reading a certificate more than once, we cache it in an
     100             :      allocated memory IMAGE of IMAGELEN. */
     101             :   size_t imagelen;
     102             :   unsigned char *image;
     103             : 
     104             :   /* EF containing certificate */
     105             :   unsigned short fid;
     106             : };
     107             : typedef struct cdf_object_s *cdf_object_t;
     108             : 
     109             : 
     110             : 
     111             : /* This is an object to store information about a Private Key
     112             :    Directory File (PrKDF) in a format suitable for further processing
     113             :    by us. To keep memory management, simple we use a linked list of
     114             :    items; i.e. one such object represents one certificate and the list
     115             :    the entire PrKDF. */
     116             : struct prkdf_object_s
     117             : {
     118             :   /* Link to next item when used in a linked list. */
     119             :   struct prkdf_object_s *next;
     120             : 
     121             :   /* Key type */
     122             :   key_type_t keytype;
     123             : 
     124             :   /* Key size in bits or 0 if unknown */
     125             :   size_t keysize;
     126             : 
     127             :   /* Length and allocated buffer with the Id of this object. */
     128             :   size_t objidlen;
     129             :   unsigned char *objid;
     130             : 
     131             :   /* The key's usage flags. */
     132             :   keyusage_flags_t usageflags;
     133             : 
     134             :   /* The keyReference */
     135             :   unsigned char key_reference;
     136             : };
     137             : typedef struct prkdf_object_s *prkdf_object_t;
     138             : 
     139             : 
     140             : 
     141             : /* Context local to this application. */
     142             : struct app_local_s
     143             : {
     144             :   /* Information on all certificates. */
     145             :   cdf_object_t certificate_info;
     146             :   /* Information on all trusted certificates. */
     147             :   cdf_object_t trusted_certificate_info;
     148             :   /* Information on all private keys. */
     149             :   prkdf_object_t private_key_info;
     150             : };
     151             : 
     152             : 
     153             : 
     154             : /*** Local prototypes.  ***/
     155             : static gpg_error_t readcert_by_cdf (app_t app, cdf_object_t cdf,
     156             :                                     unsigned char **r_cert, size_t *r_certlen);
     157             : 
     158             : 
     159             : 
     160             : /* Release the CDF object A  */
     161             : static void
     162           0 : release_cdflist (cdf_object_t a)
     163             : {
     164           0 :   while (a)
     165             :     {
     166           0 :       cdf_object_t tmp = a->next;
     167           0 :       xfree (a->image);
     168           0 :       xfree (a->objid);
     169           0 :       xfree (a);
     170           0 :       a = tmp;
     171             :     }
     172           0 : }
     173             : 
     174             : 
     175             : 
     176             : /* Release the PrKDF object A.  */
     177             : static void
     178           0 : release_prkdflist (prkdf_object_t a)
     179             : {
     180           0 :   while (a)
     181             :     {
     182           0 :       prkdf_object_t tmp = a->next;
     183           0 :       xfree (a->objid);
     184           0 :       xfree (a);
     185           0 :       a = tmp;
     186             :     }
     187           0 : }
     188             : 
     189             : 
     190             : 
     191             : /* Release all local resources.  */
     192             : static void
     193           0 : do_deinit (app_t app)
     194             : {
     195           0 :   if (app && app->app_local)
     196             :     {
     197           0 :       release_cdflist (app->app_local->certificate_info);
     198           0 :       release_cdflist (app->app_local->trusted_certificate_info);
     199           0 :       release_prkdflist (app->app_local->private_key_info);
     200           0 :       xfree (app->app_local);
     201           0 :       app->app_local = NULL;
     202             :     }
     203           0 : }
     204             : 
     205             : 
     206             : 
     207             : /* Get the list of EFs from the SmartCard-HSM.
     208             :  * On success a dynamically buffer containing the EF list is returned.
     209             :  * The caller is responsible for freeing the buffer.
     210             :  */
     211             : static gpg_error_t
     212           0 : list_ef (int slot, unsigned char **result, size_t *resultlen)
     213             : {
     214             :   int sw;
     215             : 
     216           0 :   if (!result || !resultlen)
     217           0 :     return gpg_error (GPG_ERR_INV_VALUE);
     218           0 :   *result = NULL;
     219           0 :   *resultlen = 0;
     220             : 
     221           0 :   sw = apdu_send_le (slot, 1, 0x80, 0x58, 0x00, 0x00, -1, NULL, 65536,
     222             :                      result, resultlen);
     223           0 :   if (sw != SW_SUCCESS)
     224             :     {
     225             :       /* Make sure that pending buffers are released. */
     226           0 :       xfree (*result);
     227           0 :       *result = NULL;
     228           0 :       *resultlen = 0;
     229             :     }
     230           0 :   return iso7816_map_sw (sw);
     231             : }
     232             : 
     233             : 
     234             : 
     235             : /* Do a select and a read for the file with EFID.  EFID_DESC is a
     236             :    description of the EF to be used with error messages.  On success
     237             :    BUFFER and BUFLEN contain the entire content of the EF.  The caller
     238             :    must free BUFFER only on success. */
     239             : static gpg_error_t
     240           0 : select_and_read_binary (int slot, unsigned short efid, const char *efid_desc,
     241             :                         unsigned char **buffer, size_t *buflen, int maxread)
     242             : {
     243             :   gpg_error_t err;
     244             :   unsigned char cdata[4];
     245             :   int sw;
     246             : 
     247           0 :   cdata[0] = 0x54;      /* Create ISO 7861-4 odd ins READ BINARY */
     248           0 :   cdata[1] = 0x02;
     249           0 :   cdata[2] = 0x00;
     250           0 :   cdata[3] = 0x00;
     251             : 
     252           0 :   sw = apdu_send_le(slot, 1, 0x00, 0xB1, efid >> 8, efid & 0xFF,
     253             :                     4, cdata, maxread, buffer, buflen);
     254             : 
     255           0 :   if (sw == SW_EOF_REACHED)
     256           0 :     sw = SW_SUCCESS;
     257             : 
     258           0 :   err = iso7816_map_sw (sw);
     259           0 :   if (err)
     260             :     {
     261           0 :       log_error ("error reading %s (0x%04X): %s\n",
     262             :                  efid_desc, efid, gpg_strerror (err));
     263           0 :       return err;
     264             :     }
     265           0 :   return 0;
     266             : }
     267             : 
     268             : 
     269             : 
     270             : /* Parse a cert Id string (or a key Id string) and return the binary
     271             :    object Id string in a newly allocated buffer stored at R_OBJID and
     272             :    R_OBJIDLEN.  On Error NULL will be stored there and an error code
     273             :    returned. On success caller needs to free the buffer at R_OBJID. */
     274             : static gpg_error_t
     275           0 : parse_certid (const char *certid, unsigned char **r_objid, size_t *r_objidlen)
     276             : {
     277             :   const char *s;
     278             :   size_t objidlen;
     279             :   unsigned char *objid;
     280             :   int i;
     281             : 
     282           0 :   *r_objid = NULL;
     283           0 :   *r_objidlen = 0;
     284             : 
     285           0 :   if (strncmp (certid, "HSM.", 4))
     286           0 :     return gpg_error (GPG_ERR_INV_ID);
     287           0 :   certid += 4;
     288             : 
     289           0 :   for (s=certid, objidlen=0; hexdigitp (s); s++, objidlen++)
     290             :     ;
     291           0 :   if (*s || !objidlen || (objidlen%2))
     292           0 :     return gpg_error (GPG_ERR_INV_ID);
     293           0 :   objidlen /= 2;
     294           0 :   objid = xtrymalloc (objidlen);
     295           0 :   if (!objid)
     296           0 :     return gpg_error_from_syserror ();
     297           0 :   for (s=certid, i=0; i < objidlen; i++, s+=2)
     298           0 :     objid[i] = xtoi_2 (s);
     299           0 :   *r_objid = objid;
     300           0 :   *r_objidlen = objidlen;
     301           0 :   return 0;
     302             : }
     303             : 
     304             : 
     305             : 
     306             : /* Find a certificate object by the certificate ID CERTID and store a
     307             :    pointer to it at R_CDF. */
     308             : static gpg_error_t
     309           0 : cdf_object_from_certid (app_t app, const char *certid, cdf_object_t *r_cdf)
     310             : {
     311             :   gpg_error_t err;
     312             :   size_t objidlen;
     313             :   unsigned char *objid;
     314             :   cdf_object_t cdf;
     315             : 
     316           0 :   err = parse_certid (certid, &objid, &objidlen);
     317           0 :   if (err)
     318           0 :     return err;
     319             : 
     320           0 :   for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
     321           0 :     if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
     322           0 :       break;
     323           0 :   if (!cdf)
     324           0 :     for (cdf = app->app_local->trusted_certificate_info; cdf; cdf = cdf->next)
     325           0 :       if (cdf->objidlen == objidlen && !memcmp (cdf->objid, objid, objidlen))
     326           0 :         break;
     327           0 :   xfree (objid);
     328           0 :   if (!cdf)
     329           0 :     return gpg_error (GPG_ERR_NOT_FOUND);
     330           0 :   *r_cdf = cdf;
     331           0 :   return 0;
     332             : }
     333             : 
     334             : 
     335             : 
     336             : /* Find a private key object by the key Id string KEYIDSTR and store a
     337             :    pointer to it at R_PRKDF. */
     338             : static gpg_error_t
     339           0 : prkdf_object_from_keyidstr (app_t app, const char *keyidstr,
     340             :                             prkdf_object_t *r_prkdf)
     341             : {
     342             :   gpg_error_t err;
     343             :   size_t objidlen;
     344             :   unsigned char *objid;
     345             :   prkdf_object_t prkdf;
     346             : 
     347           0 :   err = parse_certid (keyidstr, &objid, &objidlen);
     348           0 :   if (err)
     349           0 :     return err;
     350             : 
     351           0 :   for (prkdf = app->app_local->private_key_info; prkdf; prkdf = prkdf->next)
     352           0 :     if (prkdf->objidlen == objidlen && !memcmp (prkdf->objid, objid, objidlen))
     353           0 :       break;
     354           0 :   xfree (objid);
     355           0 :   if (!prkdf)
     356           0 :     return gpg_error (GPG_ERR_NOT_FOUND);
     357           0 :   *r_prkdf = prkdf;
     358           0 :   return 0;
     359             : }
     360             : 
     361             : 
     362             : 
     363             : /* Parse the BIT STRING with the keyUsageFlags from the
     364             :    CommonKeyAttributes. */
     365             : static gpg_error_t
     366           0 : parse_keyusage_flags (const unsigned char *der, size_t derlen,
     367             :                       keyusage_flags_t *usageflags)
     368             : {
     369             :   unsigned int bits, mask;
     370             :   int i, unused, full;
     371             : 
     372           0 :   memset (usageflags, 0, sizeof *usageflags);
     373           0 :   if (!derlen)
     374           0 :     return gpg_error (GPG_ERR_INV_OBJ);
     375             : 
     376           0 :   unused = *der++; derlen--;
     377           0 :   if ((!derlen && unused) || unused/8 > derlen)
     378           0 :     return gpg_error (GPG_ERR_ENCODING_PROBLEM);
     379           0 :   full = derlen - (unused+7)/8;
     380           0 :   unused %= 8;
     381           0 :   mask = 0;
     382           0 :   for (i=1; unused; i <<= 1, unused--)
     383           0 :     mask |= i;
     384             : 
     385             :   /* First octet */
     386           0 :   if (derlen)
     387             :     {
     388           0 :       bits = *der++; derlen--;
     389           0 :       if (full)
     390           0 :         full--;
     391             :       else
     392             :         {
     393           0 :           bits &= ~mask;
     394           0 :           mask = 0;
     395             :         }
     396             :     }
     397             :   else
     398           0 :     bits = 0;
     399           0 :   if ((bits & 0x80)) usageflags->encrypt = 1;
     400           0 :   if ((bits & 0x40)) usageflags->decrypt = 1;
     401           0 :   if ((bits & 0x20)) usageflags->sign = 1;
     402           0 :   if ((bits & 0x10)) usageflags->sign_recover = 1;
     403           0 :   if ((bits & 0x08)) usageflags->wrap = 1;
     404           0 :   if ((bits & 0x04)) usageflags->unwrap = 1;
     405           0 :   if ((bits & 0x02)) usageflags->verify = 1;
     406           0 :   if ((bits & 0x01)) usageflags->verify_recover = 1;
     407             : 
     408             :   /* Second octet. */
     409           0 :   if (derlen)
     410             :     {
     411           0 :       bits = *der++; derlen--;
     412           0 :       if (full)
     413           0 :         full--;
     414             :       else
     415             :         {
     416           0 :           bits &= ~mask;
     417           0 :           mask = 0;
     418             :         }
     419             :     }
     420             :   else
     421           0 :     bits = 0;
     422           0 :   if ((bits & 0x80)) usageflags->derive = 1;
     423           0 :   if ((bits & 0x40)) usageflags->non_repudiation = 1;
     424             : 
     425           0 :   return 0;
     426             : }
     427             : 
     428             : 
     429             : 
     430             : /* Read and parse a Private Key Directory File containing a single key
     431             :    description in PKCS#15 format.  For each private key a matching
     432             :    certificate description is created, if the certificate EF exists
     433             :    and contains a X.509 certificate.
     434             : 
     435             :    Example data:
     436             : 
     437             : 0000  30 2A 30 13 0C 11 4A 6F 65 20 44 6F 65 20 28 52  0*0...Joe Doe (R
     438             : 0010  53 41 32 30 34 38 29 30 07 04 01 01 03 02 02 74  SA2048)0.......t
     439             : 0020  A1 0A 30 08 30 02 04 00 02 02 08 00              ..0.0.......
     440             : 
     441             :    Decoded example:
     442             : 
     443             : SEQUENCE SIZE( 42 )
     444             :   SEQUENCE SIZE( 19 )
     445             :     UTF8-STRING SIZE( 17 )                -- label
     446             :       0000  4A 6F 65 20 44 6F 65 20 28 52 53 41 32 30 34 38  Joe Doe (RSA2048
     447             :       0010  29                                               )
     448             :   SEQUENCE SIZE( 7 )
     449             :     OCTET-STRING SIZE( 1 )                -- id
     450             :       0000  01
     451             :     BIT-STRING SIZE( 2 )                  -- key usage
     452             :       0000  02 74
     453             :   A1 [ CONTEXT 1 ] IMPLICIT SEQUENCE SIZE( 10 )
     454             :     SEQUENCE SIZE( 8 )
     455             :       SEQUENCE SIZE( 2 )
     456             :         OCTET-STRING SIZE( 0 )            -- empty path, req object in PKCS#15
     457             :       INTEGER SIZE( 2 )                   -- modulus size in bits
     458             :         0000  08 00
     459             : */
     460             : static gpg_error_t
     461           0 : read_ef_prkd (app_t app, unsigned short fid, prkdf_object_t *prkdresult,
     462             :               cdf_object_t *cdresult)
     463             : {
     464             :   gpg_error_t err;
     465           0 :   unsigned char *buffer = NULL;
     466             :   size_t buflen;
     467             :   const unsigned char *p;
     468             :   size_t n, objlen, hdrlen;
     469             :   int class, tag, constructed, ndef;
     470             :   int i;
     471             :   const unsigned char *pp;
     472             :   size_t nn;
     473             :   int where;
     474           0 :   const char *errstr = NULL;
     475           0 :   prkdf_object_t prkdf = NULL;
     476           0 :   cdf_object_t cdf = NULL;
     477             :   unsigned long ul;
     478             :   const unsigned char *objid;
     479             :   size_t objidlen;
     480             :   keyusage_flags_t usageflags;
     481             :   const char *s;
     482             :   key_type_t keytype;
     483             :   size_t keysize;
     484             : 
     485           0 :   if (!fid)
     486           0 :     return gpg_error (GPG_ERR_NO_DATA); /* No private keys. */
     487             : 
     488           0 :   err = select_and_read_binary (app->slot, fid, "PrKDF", &buffer, &buflen, 255);
     489           0 :   if (err)
     490           0 :     return err;
     491             : 
     492           0 :   p = buffer;
     493           0 :   n = buflen;
     494             : 
     495           0 :   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
     496             :                           &ndef, &objlen, &hdrlen);
     497           0 :   if (!err && (objlen > n || (tag != TAG_SEQUENCE && tag != 0x00)))
     498           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
     499           0 :   if (err)
     500             :     {
     501           0 :       log_error ("error parsing PrKDF record: %s\n", gpg_strerror (err));
     502           0 :       goto leave;
     503             :     }
     504             : 
     505           0 :   keytype = tag == 0x00 ? KEY_TYPE_ECC : KEY_TYPE_RSA;
     506             : 
     507           0 :   pp = p;
     508           0 :   nn = objlen;
     509           0 :   p += objlen;
     510           0 :   n -= objlen;
     511             : 
     512             :   /* Parse the commonObjectAttributes.  */
     513           0 :   where = __LINE__;
     514           0 :   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
     515             :                           &ndef, &objlen, &hdrlen);
     516           0 :   if (!err && (objlen > nn || tag != TAG_SEQUENCE))
     517           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
     518           0 :   if (err)
     519           0 :     goto parse_error;
     520             : 
     521             :   {
     522           0 :     const unsigned char *ppp = pp;
     523           0 :     size_t nnn = objlen;
     524             : 
     525           0 :     pp += objlen;
     526           0 :     nn -= objlen;
     527             : 
     528             :     /* Search the optional AuthId.  We need to skip the optional Label
     529             :        (UTF8STRING) and the optional CommonObjectFlags (BITSTRING). */
     530           0 :     where = __LINE__;
     531           0 :     err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
     532             :                             &ndef, &objlen, &hdrlen);
     533           0 :     if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
     534           0 :       err = gpg_error (GPG_ERR_INV_OBJ);
     535           0 :     if (gpg_err_code (err) == GPG_ERR_EOF)
     536           0 :       goto no_authid;
     537           0 :     if (err)
     538           0 :       goto parse_error;
     539             : 
     540           0 :     if (tag == TAG_UTF8_STRING)
     541             :       {
     542           0 :         ppp += objlen; /* Skip the Label. */
     543           0 :         nnn -= objlen;
     544             : 
     545           0 :         where = __LINE__;
     546           0 :         err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
     547             :                                 &ndef, &objlen, &hdrlen);
     548           0 :         if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
     549           0 :           err = gpg_error (GPG_ERR_INV_OBJ);
     550           0 :         if (gpg_err_code (err) == GPG_ERR_EOF)
     551           0 :           goto no_authid;
     552           0 :         if (err)
     553           0 :           goto parse_error;
     554             :       }
     555           0 :     if (tag == TAG_BIT_STRING)
     556             :       {
     557           0 :         ppp += objlen; /* Skip the CommonObjectFlags.  */
     558           0 :         nnn -= objlen;
     559             : 
     560           0 :         where = __LINE__;
     561           0 :         err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
     562             :                                 &ndef, &objlen, &hdrlen);
     563           0 :         if (!err && (objlen > nnn || class != CLASS_UNIVERSAL))
     564           0 :           err = gpg_error (GPG_ERR_INV_OBJ);
     565           0 :         if (gpg_err_code (err) == GPG_ERR_EOF)
     566           0 :           goto no_authid;
     567           0 :         if (err)
     568           0 :           goto parse_error;
     569             :       }
     570           0 :     if (tag == TAG_OCTET_STRING && objlen)
     571             :       {
     572             :         /* AuthId ignored */
     573             :       }
     574             :   no_authid:
     575             :     ;
     576             :   }
     577             : 
     578             :   /* Parse the commonKeyAttributes.  */
     579           0 :   where = __LINE__;
     580           0 :   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
     581             :       &ndef, &objlen, &hdrlen);
     582           0 :   if (!err && (objlen > nn || tag != TAG_SEQUENCE))
     583           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
     584           0 :   if (err)
     585           0 :     goto parse_error;
     586             : 
     587             :   {
     588           0 :     const unsigned char *ppp = pp;
     589           0 :     size_t nnn = objlen;
     590             : 
     591           0 :     pp += objlen;
     592           0 :     nn -= objlen;
     593             : 
     594             :     /* Get the Id. */
     595           0 :     where = __LINE__;
     596           0 :     err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
     597             :                             &ndef, &objlen, &hdrlen);
     598           0 :     if (!err && (objlen > nnn
     599           0 :                  || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
     600           0 :       err = gpg_error (GPG_ERR_INV_OBJ);
     601           0 :     if (err)
     602           0 :       goto parse_error;
     603             : 
     604           0 :     objid = ppp;
     605           0 :     objidlen = objlen;
     606           0 :     ppp += objlen;
     607           0 :     nnn -= objlen;
     608             : 
     609             :     /* Get the KeyUsageFlags. */
     610           0 :     where = __LINE__;
     611           0 :     err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
     612             :                             &ndef, &objlen, &hdrlen);
     613           0 :     if (!err && (objlen > nnn
     614           0 :                  || class != CLASS_UNIVERSAL || tag != TAG_BIT_STRING))
     615           0 :       err = gpg_error (GPG_ERR_INV_OBJ);
     616           0 :     if (err)
     617           0 :       goto parse_error;
     618             : 
     619           0 :     err = parse_keyusage_flags (ppp, objlen, &usageflags);
     620           0 :     if (err)
     621           0 :       goto parse_error;
     622             : 
     623           0 :     ppp += objlen;
     624           0 :     nnn -= objlen;
     625             : 
     626             :     /* Find the keyReference */
     627           0 :     where = __LINE__;
     628           0 :     err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
     629             :                             &ndef, &objlen, &hdrlen);
     630           0 :     if (gpg_err_code (err) == GPG_ERR_EOF)
     631           0 :       goto leave_cki;
     632           0 :     if (!err && objlen > nnn)
     633           0 :       err = gpg_error (GPG_ERR_INV_OBJ);
     634           0 :     if (err)
     635           0 :       goto parse_error;
     636             : 
     637           0 :     if (class == CLASS_UNIVERSAL && tag == TAG_BOOLEAN)
     638             :       {
     639             :         /* Skip the native element. */
     640           0 :         ppp += objlen;
     641           0 :         nnn -= objlen;
     642             : 
     643           0 :         err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
     644             :                                 &ndef, &objlen, &hdrlen);
     645           0 :         if (gpg_err_code (err) == GPG_ERR_EOF)
     646           0 :           goto leave_cki;
     647           0 :         if (!err && objlen > nnn)
     648           0 :           err = gpg_error (GPG_ERR_INV_OBJ);
     649           0 :         if (err)
     650           0 :           goto parse_error;
     651             :       }
     652           0 :     if (class == CLASS_UNIVERSAL && tag == TAG_BIT_STRING)
     653             :       {
     654             :         /* Skip the accessFlags. */
     655           0 :         ppp += objlen;
     656           0 :         nnn -= objlen;
     657             : 
     658           0 :         err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
     659             :                                 &ndef, &objlen, &hdrlen);
     660           0 :         if (gpg_err_code (err) == GPG_ERR_EOF)
     661           0 :           goto leave_cki;
     662           0 :         if (!err && objlen > nnn)
     663           0 :           err = gpg_error (GPG_ERR_INV_OBJ);
     664           0 :         if (err)
     665           0 :           goto parse_error;
     666             :       }
     667           0 :     if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER)
     668             :       {
     669             :         /* Yep, this is the keyReference.
     670             :            Note: UL is currently not used. */
     671           0 :         for (ul=0; objlen; objlen--)
     672             :           {
     673           0 :             ul <<= 8;
     674           0 :             ul |= (*ppp++) & 0xff;
     675           0 :             nnn--;
     676             :           }
     677             :       }
     678             : 
     679             :   leave_cki:
     680             :     ;
     681             :   }
     682             : 
     683             : 
     684             :   /* Skip subClassAttributes.  */
     685           0 :   where = __LINE__;
     686           0 :   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
     687             :                           &ndef, &objlen, &hdrlen);
     688           0 :   if (!err && objlen > nn)
     689           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
     690           0 :   if (err)
     691           0 :     goto parse_error;
     692           0 :   if (class == CLASS_CONTEXT && tag == 0)
     693             :     {
     694           0 :       pp += objlen;
     695           0 :       nn -= objlen;
     696             : 
     697           0 :       where = __LINE__;
     698           0 :       err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
     699             :                               &ndef, &objlen, &hdrlen);
     700             :     }
     701             : 
     702             :   /* Parse the keyAttributes.  */
     703           0 :   if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
     704           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
     705           0 :   if (err)
     706           0 :     goto parse_error;
     707             : 
     708           0 :   nn = objlen;
     709             : 
     710           0 :   where = __LINE__;
     711           0 :   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
     712             :                           &ndef, &objlen, &hdrlen);
     713           0 :   if (!err && objlen > nn)
     714           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
     715           0 :   if (err)
     716           0 :     goto parse_error;
     717             : 
     718           0 :   nn = objlen;
     719             : 
     720             :   /* Check that the reference is a Path object.  */
     721           0 :   where = __LINE__;
     722           0 :   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
     723             :                           &ndef, &objlen, &hdrlen);
     724           0 :   if (!err && objlen > nn)
     725           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
     726           0 :   if (err)
     727           0 :     goto parse_error;
     728           0 :   if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
     729             :     {
     730           0 :       errstr = "unsupported reference type";
     731           0 :       goto parse_error;
     732             :     }
     733             : 
     734           0 :   pp += objlen;
     735           0 :   nn -= objlen;
     736             : 
     737             :   /* Parse the key size object. */
     738           0 :   where = __LINE__;
     739           0 :   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
     740             :                           &ndef, &objlen, &hdrlen);
     741           0 :   if (!err && objlen > nn)
     742           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
     743           0 :   if (err)
     744           0 :     goto parse_error;
     745           0 :   keysize = 0;
     746           0 :   if (class == CLASS_UNIVERSAL && tag == TAG_INTEGER && objlen == 2)
     747             :     {
     748           0 :       keysize  = *pp++ << 8;
     749           0 :       keysize += *pp++;
     750             :     }
     751             : 
     752             :   /* Create a new PrKDF list item. */
     753           0 :   prkdf = xtrycalloc (1, sizeof *prkdf);
     754           0 :   if (!prkdf)
     755             :     {
     756           0 :       err = gpg_error_from_syserror ();
     757           0 :       goto leave;
     758             :     }
     759           0 :   prkdf->keytype = keytype;
     760           0 :   prkdf->keysize = keysize;
     761           0 :   prkdf->objidlen = objidlen;
     762           0 :   prkdf->objid = xtrymalloc (objidlen);
     763           0 :   if (!prkdf->objid)
     764             :     {
     765           0 :       err = gpg_error_from_syserror ();
     766           0 :       xfree (prkdf);
     767           0 :       prkdf = NULL;
     768           0 :       goto leave;
     769             :     }
     770           0 :   memcpy (prkdf->objid, objid, objidlen);
     771             : 
     772           0 :   prkdf->usageflags = usageflags;
     773           0 :   prkdf->key_reference = fid & 0xFF;
     774             : 
     775           0 :   log_debug ("PrKDF %04hX: id=", fid);
     776           0 :   for (i=0; i < prkdf->objidlen; i++)
     777           0 :     log_printf ("%02X", prkdf->objid[i]);
     778           0 :   log_printf (" keyref=0x%02X", prkdf->key_reference);
     779           0 :   log_printf (" keysize=%zu", prkdf->keysize);
     780           0 :   log_printf (" usage=");
     781           0 :   s = "";
     782           0 :   if (prkdf->usageflags.encrypt)
     783             :     {
     784           0 :       log_printf ("%sencrypt", s);
     785           0 :       s = ",";
     786             :     }
     787           0 :   if (prkdf->usageflags.decrypt)
     788             :     {
     789           0 :       log_printf ("%sdecrypt", s);
     790           0 :       s = ",";
     791             :     }
     792           0 :   if (prkdf->usageflags.sign)
     793             :     {
     794           0 :       log_printf ("%ssign", s);
     795           0 :       s = ",";
     796             :     }
     797           0 :   if (prkdf->usageflags.sign_recover)
     798             :     {
     799           0 :       log_printf ("%ssign_recover", s);
     800           0 :       s = ",";
     801             :     }
     802           0 :   if (prkdf->usageflags.wrap   )
     803             :     {
     804           0 :       log_printf ("%swrap", s);
     805           0 :       s = ",";
     806             :     }
     807           0 :   if (prkdf->usageflags.unwrap )
     808             :     {
     809           0 :       log_printf ("%sunwrap", s);
     810           0 :       s = ",";
     811             :     }
     812           0 :   if (prkdf->usageflags.verify )
     813             :     {
     814           0 :       log_printf ("%sverify", s);
     815           0 :       s = ",";
     816             :     }
     817           0 :   if (prkdf->usageflags.verify_recover)
     818             :     {
     819           0 :       log_printf ("%sverify_recover", s);
     820           0 :       s = ",";
     821             :     }
     822           0 :   if (prkdf->usageflags.derive )
     823             :     {
     824           0 :       log_printf ("%sderive", s);
     825           0 :       s = ",";
     826             :     }
     827           0 :   if (prkdf->usageflags.non_repudiation)
     828             :     {
     829           0 :       log_printf ("%snon_repudiation", s);
     830           0 :       s = ",";
     831             :     }
     832           0 :   log_printf ("\n");
     833             : 
     834           0 :   xfree (buffer);
     835           0 :   buffer = NULL;
     836           0 :   buflen = 0;
     837           0 :   err = select_and_read_binary (app->slot,
     838             :                                 ((SC_HSM_EE_PREFIX << 8) | (fid & 0xFF)),
     839             :                                 "CertEF", &buffer, &buflen, 1);
     840           0 :   if (!err && buffer[0] == 0x30)
     841             :     {
     842             :       /* Create a matching CDF list item. */
     843           0 :       cdf = xtrycalloc (1, sizeof *cdf);
     844           0 :       if (!cdf)
     845             :         {
     846           0 :           err = gpg_error_from_syserror ();
     847           0 :           goto leave;
     848             :         }
     849           0 :       cdf->objidlen = prkdf->objidlen;
     850           0 :       cdf->objid = xtrymalloc (cdf->objidlen);
     851           0 :       if (!cdf->objid)
     852             :         {
     853           0 :           err = gpg_error_from_syserror ();
     854           0 :           xfree (cdf);
     855           0 :           cdf = NULL;
     856           0 :           goto leave;
     857             :         }
     858           0 :       memcpy (cdf->objid, prkdf->objid, objidlen);
     859             : 
     860           0 :       cdf->fid = (SC_HSM_EE_PREFIX << 8) | (fid & 0xFF);
     861             : 
     862           0 :       log_debug ("CDF %04hX: id=", fid);
     863           0 :       for (i=0; i < cdf->objidlen; i++)
     864           0 :         log_printf ("%02X", cdf->objid[i]);
     865           0 :       log_printf (" fid=%04X\n", cdf->fid);
     866             :     }
     867             : 
     868           0 :   goto leave; /* Ready. */
     869             : 
     870             :  parse_error:
     871           0 :   log_error ("error parsing PrKDF record (%d): %s - skipped\n",
     872             :              where, errstr? errstr : gpg_strerror (err));
     873           0 :   err = 0;
     874             : 
     875             :  leave:
     876           0 :   xfree (buffer);
     877           0 :   if (err)
     878             :     {
     879           0 :       if (prkdf)
     880             :         {
     881           0 :           if (prkdf->objid)
     882           0 :             xfree (prkdf->objid);
     883           0 :           xfree (prkdf);
     884             :         }
     885           0 :       if (cdf)
     886             :         {
     887           0 :           if (cdf->objid)
     888           0 :             xfree (cdf->objid);
     889           0 :           xfree (cdf);
     890             :         }
     891             :     }
     892             :   else
     893             :     {
     894           0 :       prkdf->next = *prkdresult;
     895           0 :       *prkdresult = prkdf;
     896           0 :       if (cdf)
     897             :         {
     898           0 :           cdf->next = *cdresult;
     899           0 :           *cdresult = cdf;
     900             :         }
     901             :     }
     902           0 :   return err;
     903             : }
     904             : 
     905             : 
     906             : 
     907             : /* Read and parse the Certificate Description File identified by FID.
     908             :    On success a the CDF list gets stored at RESULT and the caller is
     909             :    then responsible of releasing the object.
     910             : 
     911             :    Example data:
     912             : 
     913             : 0000  30 35 30 11 0C 0B 43 65 72 74 69 66 69 63 61 74  050...Certificat
     914             : 0010  65 03 02 06 40 30 16 04 14 C2 01 7C 2F BA A4 4A  e...@0.....|/..J
     915             : 0020  4A BB B8 49 11 DB 4A CA AA 7E 6A 2D 1B A1 08 30  J..I..J..~j-...0
     916             : 0030  06 30 04 04 02 CA 00                             .0.....
     917             : 
     918             :    Decoded example:
     919             : 
     920             : SEQUENCE SIZE( 53 )
     921             :   SEQUENCE SIZE( 17 )
     922             :     UTF8-STRING SIZE( 11 )                      -- label
     923             :       0000  43 65 72 74 69 66 69 63 61 74 65                 Certificate
     924             :     BIT-STRING SIZE( 2 )                        -- common object attributes
     925             :       0000  06 40
     926             :   SEQUENCE SIZE( 22 )
     927             :     OCTET-STRING SIZE( 20 )                     -- id
     928             :       0000  C2 01 7C 2F BA A4 4A 4A BB B8 49 11 DB 4A CA AA
     929             :       0010  7E 6A 2D 1B
     930             :   A1 [ CONTEXT 1 ] IMPLICIT SEQUENCE SIZE( 8 )
     931             :     SEQUENCE SIZE( 6 )
     932             :       SEQUENCE SIZE( 4 )
     933             :         OCTET-STRING SIZE( 2 )                  -- path
     934             :           0000  CA 00                                            ..
     935             :  */
     936             : static gpg_error_t
     937           0 : read_ef_cd (app_t app, unsigned short fid, cdf_object_t *result)
     938             : {
     939             :   gpg_error_t err;
     940           0 :   unsigned char *buffer = NULL;
     941             :   size_t buflen;
     942             :   const unsigned char *p;
     943             :   size_t n, objlen, hdrlen;
     944             :   int class, tag, constructed, ndef;
     945             :   int i;
     946             :   const unsigned char *pp;
     947             :   size_t nn;
     948             :   int where;
     949           0 :   const char *errstr = NULL;
     950           0 :   cdf_object_t cdf = NULL;
     951             :   const unsigned char *objid;
     952             :   size_t objidlen;
     953             : 
     954           0 :   if (!fid)
     955           0 :     return gpg_error (GPG_ERR_NO_DATA); /* No certificates. */
     956             : 
     957           0 :   err = select_and_read_binary (app->slot, fid, "CDF", &buffer, &buflen, 255);
     958           0 :   if (err)
     959           0 :     return err;
     960             : 
     961           0 :   p = buffer;
     962           0 :   n = buflen;
     963             : 
     964           0 :   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
     965             :                           &ndef, &objlen, &hdrlen);
     966           0 :   if (!err && (objlen > n || tag != TAG_SEQUENCE))
     967           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
     968           0 :   if (err)
     969             :     {
     970           0 :       log_error ("error parsing CDF record: %s\n", gpg_strerror (err));
     971           0 :       goto leave;
     972             :     }
     973           0 :   pp = p;
     974           0 :   nn = objlen;
     975           0 :   p += objlen;
     976           0 :   n -= objlen;
     977             : 
     978             :   /* Skip the commonObjectAttributes.  */
     979           0 :   where = __LINE__;
     980           0 :   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
     981             :                           &ndef, &objlen, &hdrlen);
     982           0 :   if (!err && (objlen > nn || tag != TAG_SEQUENCE))
     983           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
     984           0 :   if (err)
     985           0 :     goto parse_error;
     986           0 :   pp += objlen;
     987           0 :   nn -= objlen;
     988             : 
     989             :   /* Parse the commonCertificateAttributes.  */
     990           0 :   where = __LINE__;
     991           0 :   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
     992             :                           &ndef, &objlen, &hdrlen);
     993           0 :   if (!err && (objlen > nn || tag != TAG_SEQUENCE))
     994           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
     995           0 :   if (err)
     996           0 :     goto parse_error;
     997             : 
     998             :   {
     999           0 :     const unsigned char *ppp = pp;
    1000           0 :     size_t nnn = objlen;
    1001             : 
    1002           0 :     pp += objlen;
    1003           0 :     nn -= objlen;
    1004             : 
    1005             :     /* Get the Id. */
    1006           0 :     where = __LINE__;
    1007           0 :     err = parse_ber_header (&ppp, &nnn, &class, &tag, &constructed,
    1008             :                             &ndef, &objlen, &hdrlen);
    1009           0 :     if (!err && (objlen > nnn
    1010           0 :                  || class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING))
    1011           0 :       err = gpg_error (GPG_ERR_INV_OBJ);
    1012           0 :     if (err)
    1013           0 :       goto parse_error;
    1014             : 
    1015           0 :     objid = ppp;
    1016           0 :     objidlen = objlen;
    1017             :   }
    1018             : 
    1019             :   /* Parse the certAttribute.  */
    1020           0 :   where = __LINE__;
    1021           0 :   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
    1022             :                           &ndef, &objlen, &hdrlen);
    1023           0 :   if (!err && (objlen > nn || class != CLASS_CONTEXT || tag != 1))
    1024           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
    1025           0 :   if (err)
    1026           0 :     goto parse_error;
    1027           0 :   nn = objlen;
    1028             : 
    1029           0 :   where = __LINE__;
    1030           0 :   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
    1031             :                           &ndef, &objlen, &hdrlen);
    1032           0 :   if (!err && (objlen > nn
    1033           0 :                || class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE))
    1034           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
    1035           0 :   if (err)
    1036           0 :     goto parse_error;
    1037           0 :   nn = objlen;
    1038             : 
    1039             :   /* Check that the reference is a Path object.  */
    1040           0 :   where = __LINE__;
    1041           0 :   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
    1042             :                           &ndef, &objlen, &hdrlen);
    1043           0 :   if (!err && objlen > nn)
    1044           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
    1045           0 :   if (err)
    1046           0 :     goto parse_error;
    1047           0 :   if (class != CLASS_UNIVERSAL || tag != TAG_SEQUENCE)
    1048             :     {
    1049           0 :       err = gpg_error (GPG_ERR_INV_OBJ);
    1050           0 :       goto parse_error;
    1051             :     }
    1052           0 :   nn = objlen;
    1053             : 
    1054             :   /* Parse the Path object. */
    1055           0 :   where = __LINE__;
    1056           0 :   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
    1057             :                           &ndef, &objlen, &hdrlen);
    1058           0 :   if (!err && objlen > nn)
    1059           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
    1060           0 :   if (err)
    1061           0 :     goto parse_error;
    1062             : 
    1063             :   /* Make sure that the next element is a non zero path and of
    1064             :      even length (FID are two bytes each). */
    1065           0 :   if (class != CLASS_UNIVERSAL || tag != TAG_OCTET_STRING
    1066           0 :       || (objlen & 1) )
    1067             :     {
    1068           0 :       errstr = "invalid path reference";
    1069           0 :       goto parse_error;
    1070             :     }
    1071             :   /* Create a new CDF list item. */
    1072           0 :   cdf = xtrycalloc (1, sizeof *cdf);
    1073           0 :   if (!cdf)
    1074             :     {
    1075           0 :       err = gpg_error_from_syserror ();
    1076           0 :       goto leave;
    1077             :     }
    1078           0 :   cdf->objidlen = objidlen;
    1079           0 :   cdf->objid = xtrymalloc (objidlen);
    1080           0 :   if (!cdf->objid)
    1081             :     {
    1082           0 :       err = gpg_error_from_syserror ();
    1083           0 :       xfree (cdf);
    1084           0 :       cdf = NULL;
    1085           0 :       goto leave;
    1086             :     }
    1087           0 :   memcpy (cdf->objid, objid, objidlen);
    1088             : 
    1089           0 :   cdf->fid = (SC_HSM_CA_PREFIX << 8) | (fid & 0xFF);
    1090             : 
    1091           0 :   log_debug ("CDF %04hX: id=", fid);
    1092           0 :   for (i=0; i < cdf->objidlen; i++)
    1093           0 :     log_printf ("%02X", cdf->objid[i]);
    1094             : 
    1095           0 :   goto leave;
    1096             : 
    1097             :  parse_error:
    1098           0 :   log_error ("error parsing CDF record (%d): %s - skipped\n",
    1099             :              where, errstr? errstr : gpg_strerror (err));
    1100           0 :   err = 0;
    1101             : 
    1102             :  leave:
    1103           0 :   xfree (buffer);
    1104           0 :   if (err)
    1105             :     {
    1106           0 :       if (cdf)
    1107             :         {
    1108           0 :           if (cdf->objid)
    1109           0 :             xfree (cdf->objid);
    1110           0 :           xfree (cdf);
    1111             :         }
    1112             :     }
    1113             :   else
    1114             :     {
    1115           0 :       cdf->next = *result;
    1116           0 :       *result = cdf;
    1117             :     }
    1118           0 :   return err;
    1119             : }
    1120             : 
    1121             : 
    1122             : 
    1123             : /* Read the device certificate and extract the serial number.
    1124             : 
    1125             :    EF.C_DevAut (2F02) contains two CVCs, the first is the device
    1126             :    certificate, the second is the issuer certificate.
    1127             : 
    1128             :    Example data:
    1129             : 
    1130             : 0000  7F 21 81 E2 7F 4E 81 9B 5F 29 01 00 42 0B 55 54  .!...N.._)..B.UT
    1131             : 0010  43 43 30 32 30 30 30 30 32 7F 49 4F 06 0A 04 00  CC0200002.IO....
    1132             : 0020  7F 00 07 02 02 02 02 03 86 41 04 6D FF D6 85 57  .........A.m...W
    1133             : 0030  40 FB 10 5D 94 71 8A 94 D2 5E 50 33 E7 1E C0 6C  @..].q...^P3...l
    1134             : 0040  63 D5 C8 FC BA F3 02 1D 70 23 F6 47 E8 35 48 EF  c.......p#.G.5H.
    1135             : 0050  B5 94 72 3C 6F BE C0 EB 9A C7 FB 06 59 26 CF 65  ..r<o.......Y&.e
    1136             : 0060  EF A1 72 E0 98 F3 F0 44 1B B7 71 5F 20 10 55 54  ..r....D..q_ .UT
    1137             : 0070  43 43 30 32 30 30 30 31 33 30 30 30 30 30 7F 4C  CC020001300000.L
    1138             : 0080  10 06 0B 2B 06 01 04 01 81 C3 1F 03 01 01 53 01  ...+..........S.
    1139             : 0090  00 5F 25 06 01 04 00 07 01 01 5F 24 06 02 01 00  ._%......._$....
    1140             : 00A0  03 02 07 5F 37 40 7F 73 04 3B 06 63 79 41 BE 1A  ..._7@.s.;.cyA..
    1141             : 00B0  9F FC F6 77 67 2B 8A 41 D1 11 F6 9B 54 44 AD 19  ...wg+.A....TD..
    1142             : 00C0  FB B8 0C C6 2F 34 71 8E 4F F6 92 59 34 61 D9 4F  ..../4q.O..Y4a.O
    1143             : 00D0  4A 86 36 A8 D8 9A C6 3C 17 7E 71 CE A8 26 D0 C5  J.6....<.~q..&..
    1144             : 00E0  25 61 78 9D 01 F8 7F 21 81 E0 7F 4E 81 99 5F 29  %ax....!...N.._)
    1145             : 00F0  01 00 42 0E 55 54 53 52 43 41 43 43 31 30 30 30  ..B.UTSRCACC1000
    1146             : 0100  30 31 7F 49 4F 06 0A 04 00 7F 00 07 02 02 02 02  01.IO...........
    1147             : 0110  03 86 41 04 2F EA 33 47 7F 45 81 E2 FC CB 66 87  ..A./.3G.E....f.
    1148             : 0120  4B 96 21 1D 68 81 73 F2 9F 8F 6B 91 F0 DE 4B 54  K.!.h.s...k...KT
    1149             : 0130  8E D8 F0 82 3D CB BE 10 98 A3 1E 4F F0 72 5C E5  ....=......O.r\.
    1150             : 0140  7B 1E F7 3C 68 09 03 E8 A0 3F 3E 06 C1 B0 3C 18  {..<h....?>...<.
    1151             : 0150  6B AC 06 EA 5F 20 0B 55 54 43 43 30 32 30 30 30  k..._ .UTCC02000
    1152             : 0160  30 32 7F 4C 10 06 0B 2B 06 01 04 01 81 C3 1F 03  02.L...+........
    1153             : 0170  01 01 53 01 80 5F 25 06 01 03 00 03 02 08 5F 24  ..S.._%......._$
    1154             : 0180  06 02 01 00 03 02 07 5F 37 40 93 C1 42 8B B3 8E  ......._7@..B...
    1155             : 0190  42 61 6F 2C 19 E6 98 41 BD AA 60 BD E0 DD 4E F0  Bao,...A..`...N.
    1156             : 01A0  15 D5 4F 71 B7 BB C3 3A F2 AD 27 5E DD EE 6D 12  ..Oq...:..'^..m.
    1157             : 01B0  76 E6 2B A0 4C 01 CA C1 26 0C 45 6D C6 CB EC 92  v.+.L...&.Em....
    1158             : 01C0  BF 38 18 AD 8F B2 29 40 A9 51                    .8....)@.Q
    1159             : 
    1160             :    The certificate format is defined in BSI TR-03110:
    1161             : 
    1162             : 7F21 [ APPLICATION 33 ] IMPLICIT SEQUENCE SIZE( 226 )
    1163             :   7F4E [ APPLICATION 78 ] IMPLICIT SEQUENCE SIZE( 155 )
    1164             :     5F29 [ APPLICATION 41 ] SIZE( 1 )                           -- profile id
    1165             :       0000  00
    1166             :     42 [ APPLICATION 2 ] SIZE( 11 )                             -- CAR
    1167             :       0000  55 54 43 43 30 32 30 30 30 30 32                 UTCC0200002
    1168             :     7F49 [ APPLICATION 73 ] IMPLICIT SEQUENCE SIZE( 79 )        -- public key
    1169             :       OBJECT IDENTIFIER = { id-TA-ECDSA-SHA-256 }
    1170             :       86 [ CONTEXT 6 ] SIZE( 65 )
    1171             :         0000  04 6D FF D6 85 57 40 FB 10 5D 94 71 8A 94 D2 5E
    1172             :         0010  50 33 E7 1E C0 6C 63 D5 C8 FC BA F3 02 1D 70 23
    1173             :         0020  F6 47 E8 35 48 EF B5 94 72 3C 6F BE C0 EB 9A C7
    1174             :         0030  FB 06 59 26 CF 65 EF A1 72 E0 98 F3 F0 44 1B B7
    1175             :         0040  71
    1176             :     5F20 [ APPLICATION 32 ] SIZE( 16 )                          -- CHR
    1177             :       0000  55 54 43 43 30 32 30 30 30 31 33 30 30 30 30 30  UTCC020001300000
    1178             :     7F4C [ APPLICATION 76 ] IMPLICIT SEQUENCE SIZE( 16 )        -- CHAT
    1179             :       OBJECT IDENTIFIER = { 1 3 6 1 4 1 24991 3 1 1 }
    1180             :       53 [ APPLICATION 19 ] SIZE( 1 )
    1181             :         0000  00
    1182             :     5F25 [ APPLICATION 37 ] SIZE( 6 )                           -- Valid from
    1183             :       0000  01 04 00 07 01 01
    1184             :     5F24 [ APPLICATION 36 ] SIZE( 6 )                           -- Valid to
    1185             :       0000  02 01 00 03 02 07
    1186             :   5F37 [ APPLICATION 55 ] SIZE( 64 )                            -- Signature
    1187             :     0000  7F 73 04 3B 06 63 79 41 BE 1A 9F FC F6 77 67 2B
    1188             :     0010  8A 41 D1 11 F6 9B 54 44 AD 19 FB B8 0C C6 2F 34
    1189             :     0020  71 8E 4F F6 92 59 34 61 D9 4F 4A 86 36 A8 D8 9A
    1190             :     0030  C6 3C 17 7E 71 CE A8 26 D0 C5 25 61 78 9D 01 F8
    1191             : 
    1192             :    The serial number is contained in tag 5F20, while the last 5 digits
    1193             :    are truncated.
    1194             :  */
    1195             : static gpg_error_t
    1196           0 : read_serialno(app_t app)
    1197             : {
    1198             :   gpg_error_t err;
    1199           0 :   unsigned char *buffer = NULL;
    1200             :   size_t buflen;
    1201             :   const unsigned char *p,*chr;
    1202             :   size_t n, objlen, hdrlen, chrlen;
    1203             :   int class, tag, constructed, ndef;
    1204             : 
    1205           0 :   err = select_and_read_binary (app->slot, 0x2F02, "EF.C_DevAut",
    1206             :                                 &buffer, &buflen, 512);
    1207           0 :   if (err)
    1208           0 :     return err;
    1209             : 
    1210           0 :   p = buffer;
    1211           0 :   n = buflen;
    1212             : 
    1213           0 :   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
    1214             :                           &ndef, &objlen, &hdrlen);
    1215           0 :   if (!err && (objlen > n || tag != 0x21))
    1216           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
    1217           0 :   if (err)
    1218             :     {
    1219           0 :       log_error ("error parsing C_DevAut: %s\n", gpg_strerror (err));
    1220           0 :       goto leave;
    1221             :     }
    1222             : 
    1223           0 :   chr = find_tlv (p, objlen, 0x5F20, &chrlen);
    1224           0 :   if (!chr || chrlen <= 5)
    1225             :     {
    1226           0 :       err = gpg_error (GPG_ERR_INV_OBJ);
    1227           0 :       log_error ("CHR not found in CVC\n");
    1228           0 :       goto leave;
    1229             :     }
    1230           0 :   chrlen -= 5;
    1231             : 
    1232           0 :   app->serialno = xtrymalloc (chrlen);
    1233           0 :   if (!app->serialno)
    1234             :     {
    1235           0 :       err = gpg_error_from_syserror ();
    1236           0 :       goto leave;
    1237             :     }
    1238             : 
    1239           0 :   app->serialnolen = chrlen;
    1240           0 :   memcpy (app->serialno, chr, chrlen);
    1241             : 
    1242             :  leave:
    1243           0 :   xfree (buffer);
    1244           0 :   return err;
    1245             : }
    1246             : 
    1247             : 
    1248             : /* Get all the basic information from the SmartCard-HSM, check the
    1249             :    structure and initialize our local context.  This is used once at
    1250             :    application initialization.  */
    1251             : static gpg_error_t
    1252           0 : read_meta (app_t app)
    1253             : {
    1254             :   gpg_error_t err;
    1255           0 :   unsigned char *eflist = NULL;
    1256           0 :   size_t eflistlen = 0;
    1257             :   int i;
    1258             : 
    1259           0 :   err = read_serialno(app);
    1260           0 :   if (err)
    1261           0 :     return err;
    1262             : 
    1263           0 :   err = list_ef (app->slot, &eflist, &eflistlen);
    1264           0 :   if (err)
    1265           0 :     return err;
    1266             : 
    1267           0 :   for (i = 0; i < eflistlen; i += 2)
    1268             :     {
    1269           0 :       switch(eflist[i])
    1270             :         {
    1271             :         case SC_HSM_KEY_PREFIX:
    1272           0 :           if (eflist[i + 1] == 0)    /* No key with ID=0 */
    1273           0 :             break;
    1274           0 :           err = read_ef_prkd (app, ((SC_HSM_PRKD_PREFIX << 8) | eflist[i + 1]),
    1275           0 :                               &app->app_local->private_key_info,
    1276           0 :                               &app->app_local->certificate_info);
    1277           0 :           if (gpg_err_code (err) == GPG_ERR_NO_DATA)
    1278           0 :             err = 0;
    1279           0 :           if (err)
    1280           0 :             return err;
    1281           0 :           break;
    1282             :         case SC_HSM_CD_PREFIX:
    1283           0 :           err = read_ef_cd (app, ((eflist[i] << 8) | eflist[i + 1]),
    1284           0 :                             &app->app_local->trusted_certificate_info);
    1285           0 :           if (gpg_err_code (err) == GPG_ERR_NO_DATA)
    1286           0 :             err = 0;
    1287           0 :           if (err)
    1288           0 :             return err;
    1289           0 :           break;
    1290             :         }
    1291             :     }
    1292             : 
    1293           0 :   xfree (eflist);
    1294             : 
    1295           0 :   return err;
    1296             : }
    1297             : 
    1298             : 
    1299             : 
    1300             : /* Helper to do_learn_status: Send information about all certificates
    1301             :    listed in CERTINFO back.  Use CERTTYPE as type of the
    1302             :    certificate. */
    1303             : static gpg_error_t
    1304           0 : send_certinfo (ctrl_t ctrl, const char *certtype, cdf_object_t certinfo)
    1305             : {
    1306           0 :   for (; certinfo; certinfo = certinfo->next)
    1307             :     {
    1308             :       char *buf, *p;
    1309             : 
    1310           0 :       buf = xtrymalloc (4 + certinfo->objidlen*2 + 1);
    1311           0 :       if (!buf)
    1312           0 :         return gpg_error_from_syserror ();
    1313           0 :       p = stpcpy (buf, "HSM.");
    1314           0 :       bin2hex (certinfo->objid, certinfo->objidlen, p);
    1315             : 
    1316           0 :       send_status_info (ctrl, "CERTINFO",
    1317             :                         certtype, strlen (certtype),
    1318             :                         buf, strlen (buf),
    1319             :                         NULL, (size_t)0);
    1320           0 :       xfree (buf);
    1321             :     }
    1322           0 :   return 0;
    1323             : }
    1324             : 
    1325             : 
    1326             : 
    1327             : /* Get the keygrip of the private key object PRKDF.  On success the
    1328             :    keygrip gets returned in the caller provided 41 byte buffer
    1329             :    R_GRIPSTR. */
    1330             : static gpg_error_t
    1331           0 : keygripstr_from_prkdf (app_t app, prkdf_object_t prkdf, char *r_gripstr)
    1332             : {
    1333             :   gpg_error_t err;
    1334             :   cdf_object_t cdf;
    1335             :   unsigned char *der;
    1336             :   size_t derlen;
    1337             :   ksba_cert_t cert;
    1338             : 
    1339             :   /* Look for a matching certificate. A certificate matches if the Id
    1340             :      matches the one of the private key info. */
    1341           0 :   for (cdf = app->app_local->certificate_info; cdf; cdf = cdf->next)
    1342           0 :     if (cdf->objidlen == prkdf->objidlen
    1343           0 :         && !memcmp (cdf->objid, prkdf->objid, prkdf->objidlen))
    1344           0 :       break;
    1345           0 :   if (!cdf)
    1346           0 :     return gpg_error (GPG_ERR_NOT_FOUND);
    1347             : 
    1348           0 :   err = readcert_by_cdf (app, cdf, &der, &derlen);
    1349           0 :   if (err)
    1350           0 :     return err;
    1351             : 
    1352           0 :   err = ksba_cert_new (&cert);
    1353           0 :   if (!err)
    1354           0 :     err = ksba_cert_init_from_mem (cert, der, derlen);
    1355           0 :   xfree (der);
    1356           0 :   if (!err)
    1357           0 :     err = app_help_get_keygrip_string (cert, r_gripstr);
    1358           0 :   ksba_cert_release (cert);
    1359             : 
    1360           0 :   return err;
    1361             : }
    1362             : 
    1363             : 
    1364             : 
    1365             : /* Helper to do_learn_status: Send information about all known
    1366             :    keypairs back. */
    1367             : static gpg_error_t
    1368           0 : send_keypairinfo (app_t app, ctrl_t ctrl, prkdf_object_t keyinfo)
    1369             : {
    1370             :   gpg_error_t err;
    1371             : 
    1372           0 :   for (; keyinfo; keyinfo = keyinfo->next)
    1373             :     {
    1374             :       char gripstr[40+1];
    1375             :       char *buf, *p;
    1376             : 
    1377           0 :       buf = xtrymalloc (4 + keyinfo->objidlen*2 + 1);
    1378           0 :       if (!buf)
    1379           0 :         return gpg_error_from_syserror ();
    1380           0 :       p = stpcpy (buf, "HSM.");
    1381           0 :       bin2hex (keyinfo->objid, keyinfo->objidlen, p);
    1382             : 
    1383           0 :       err = keygripstr_from_prkdf (app, keyinfo, gripstr);
    1384           0 :       if (err)
    1385             :         {
    1386           0 :           log_error ("can't get keygrip from %04X\n", keyinfo->key_reference);
    1387             :         }
    1388             :       else
    1389             :         {
    1390           0 :           assert (strlen (gripstr) == 40);
    1391           0 :           send_status_info (ctrl, "KEYPAIRINFO",
    1392             :                             gripstr, 40,
    1393             :                             buf, strlen (buf),
    1394             :                             NULL, (size_t)0);
    1395             :         }
    1396           0 :       xfree (buf);
    1397             :     }
    1398           0 :   return 0;
    1399             : }
    1400             : 
    1401             : 
    1402             : 
    1403             : /* This is the handler for the LEARN command. */
    1404             : static gpg_error_t
    1405           0 : do_learn_status (app_t app, ctrl_t ctrl, unsigned int flags)
    1406             : {
    1407             :   gpg_error_t err;
    1408             : 
    1409           0 :   if ((flags & 1))
    1410           0 :     err = 0;
    1411             :   else
    1412             :     {
    1413           0 :       err = send_certinfo (ctrl, "100", app->app_local->certificate_info);
    1414           0 :       if (!err)
    1415           0 :         err = send_certinfo (ctrl, "101",
    1416           0 :             app->app_local->trusted_certificate_info);
    1417             :     }
    1418             : 
    1419           0 :   if (!err)
    1420           0 :     err = send_keypairinfo (app, ctrl, app->app_local->private_key_info);
    1421             : 
    1422           0 :   return err;
    1423             : }
    1424             : 
    1425             : 
    1426             : 
    1427             : /* Read a certificate using the information in CDF and return the
    1428             :    certificate in a newly allocated buffer R_CERT and its length
    1429             :    R_CERTLEN. */
    1430             : static gpg_error_t
    1431           0 : readcert_by_cdf (app_t app, cdf_object_t cdf,
    1432             :                  unsigned char **r_cert, size_t *r_certlen)
    1433             : {
    1434             :   gpg_error_t err;
    1435           0 :   unsigned char *buffer = NULL;
    1436             :   const unsigned char *p, *save_p;
    1437             :   size_t buflen, n;
    1438             :   int class, tag, constructed, ndef;
    1439             :   size_t totobjlen, objlen, hdrlen;
    1440             :   int rootca;
    1441             :   int i;
    1442             : 
    1443           0 :   *r_cert = NULL;
    1444           0 :   *r_certlen = 0;
    1445             : 
    1446             :   /* First check whether it has been cached. */
    1447           0 :   if (cdf->image)
    1448             :     {
    1449           0 :       *r_cert = xtrymalloc (cdf->imagelen);
    1450           0 :       if (!*r_cert)
    1451           0 :         return gpg_error_from_syserror ();
    1452           0 :       memcpy (*r_cert, cdf->image, cdf->imagelen);
    1453           0 :       *r_certlen = cdf->imagelen;
    1454           0 :       return 0;
    1455             :     }
    1456             : 
    1457           0 :   err = select_and_read_binary (app->slot, cdf->fid, "CD",
    1458             :                                 &buffer, &buflen, 4096);
    1459           0 :   if (err)
    1460             :     {
    1461           0 :       log_error ("error reading certificate with Id ");
    1462           0 :       for (i=0; i < cdf->objidlen; i++)
    1463           0 :         log_printf ("%02X", cdf->objid[i]);
    1464           0 :       log_printf (": %s\n", gpg_strerror (err));
    1465           0 :       goto leave;
    1466             :     }
    1467             : 
    1468             :   /* Check whether this is really a certificate.  */
    1469           0 :   p = buffer;
    1470           0 :   n = buflen;
    1471           0 :   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
    1472             :                           &ndef, &objlen, &hdrlen);
    1473           0 :   if (err)
    1474           0 :     goto leave;
    1475             : 
    1476           0 :   if (class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed)
    1477           0 :     rootca = 0;
    1478           0 :   else if ( class == CLASS_UNIVERSAL && tag == TAG_SET && constructed )
    1479           0 :     rootca = 1;
    1480             :   else
    1481             :     {
    1482           0 :       err = gpg_error (GPG_ERR_INV_OBJ);
    1483           0 :       goto leave;
    1484             :     }
    1485           0 :   totobjlen = objlen + hdrlen;
    1486           0 :   assert (totobjlen <= buflen);
    1487             : 
    1488           0 :   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
    1489             :                           &ndef, &objlen, &hdrlen);
    1490           0 :   if (err)
    1491           0 :     goto leave;
    1492             : 
    1493           0 :   if (!rootca
    1494           0 :       && class == CLASS_UNIVERSAL && tag == TAG_OBJECT_ID && !constructed)
    1495             :     {
    1496             :       /* The certificate seems to be contained in a userCertificate
    1497             :          container.  Skip this and assume the following sequence is
    1498             :          the certificate. */
    1499           0 :       if (n < objlen)
    1500             :         {
    1501           0 :           err = gpg_error (GPG_ERR_INV_OBJ);
    1502           0 :           goto leave;
    1503             :         }
    1504           0 :       p += objlen;
    1505           0 :       n -= objlen;
    1506           0 :       save_p = p;
    1507           0 :       err = parse_ber_header (&p, &n, &class, &tag, &constructed,
    1508             :                               &ndef, &objlen, &hdrlen);
    1509           0 :       if (err)
    1510           0 :         goto leave;
    1511           0 :       if ( !(class == CLASS_UNIVERSAL && tag == TAG_SEQUENCE && constructed) )
    1512             :         {
    1513           0 :           err = gpg_error (GPG_ERR_INV_OBJ);
    1514           0 :           goto leave;
    1515             :         }
    1516           0 :       totobjlen = objlen + hdrlen;
    1517           0 :       assert (save_p + totobjlen <= buffer + buflen);
    1518           0 :       memmove (buffer, save_p, totobjlen);
    1519             :     }
    1520             : 
    1521           0 :   *r_cert = buffer;
    1522           0 :   buffer = NULL;
    1523           0 :   *r_certlen = totobjlen;
    1524             : 
    1525             :   /* Try to cache it. */
    1526           0 :   if (!cdf->image && (cdf->image = xtrymalloc (*r_certlen)))
    1527             :     {
    1528           0 :       memcpy (cdf->image, *r_cert, *r_certlen);
    1529           0 :       cdf->imagelen = *r_certlen;
    1530             :     }
    1531             : 
    1532             : 
    1533             :  leave:
    1534           0 :   xfree (buffer);
    1535           0 :   return err;
    1536             : }
    1537             : 
    1538             : 
    1539             : 
    1540             : /* Handler for the READCERT command.
    1541             : 
    1542             :    Read the certificate with id CERTID (as returned by learn_status in
    1543             :    the CERTINFO status lines) and return it in the freshly allocated
    1544             :    buffer to be stored at R_CERT and its length at R_CERTLEN.  A error
    1545             :    code will be returned on failure and R_CERT and R_CERTLEN will be
    1546             :    set to (NULL,0). */
    1547             : static gpg_error_t
    1548           0 : do_readcert (app_t app, const char *certid,
    1549             :              unsigned char **r_cert, size_t *r_certlen)
    1550             : {
    1551             :   gpg_error_t err;
    1552             :   cdf_object_t cdf;
    1553             : 
    1554           0 :   *r_cert = NULL;
    1555           0 :   *r_certlen = 0;
    1556           0 :   err = cdf_object_from_certid (app, certid, &cdf);
    1557           0 :   if (!err)
    1558           0 :     err = readcert_by_cdf (app, cdf, r_cert, r_certlen);
    1559           0 :   return err;
    1560             : }
    1561             : 
    1562             : 
    1563             : 
    1564             : /* Implement the GETATTR command.  This is similar to the LEARN
    1565             :    command but returns just one value via the status interface. */
    1566             : static gpg_error_t
    1567           0 : do_getattr (app_t app, ctrl_t ctrl, const char *name)
    1568             : {
    1569           0 :   if (!strcmp (name, "$AUTHKEYID"))
    1570             :     {
    1571             :       char *buf, *p;
    1572             :       prkdf_object_t prkdf;
    1573             : 
    1574             :       /* We return the ID of the first private key capable of
    1575             :          signing. */
    1576           0 :       for (prkdf = app->app_local->private_key_info; prkdf;
    1577           0 :            prkdf = prkdf->next)
    1578           0 :         if (prkdf->usageflags.sign)
    1579           0 :           break;
    1580           0 :       if (prkdf)
    1581             :         {
    1582           0 :           buf = xtrymalloc (4 + prkdf->objidlen*2 + 1);
    1583           0 :           if (!buf)
    1584           0 :             return gpg_error_from_syserror ();
    1585           0 :           p = stpcpy (buf, "HSM.");
    1586           0 :           bin2hex (prkdf->objid, prkdf->objidlen, p);
    1587             : 
    1588           0 :           send_status_info (ctrl, name, buf, strlen (buf), NULL, 0);
    1589           0 :           xfree (buf);
    1590           0 :           return 0;
    1591             :         }
    1592             :     }
    1593           0 :   else if (!strcmp (name, "$DISPSERIALNO"))
    1594             :     {
    1595           0 :       send_status_info (ctrl, name, app->serialno, app->serialnolen, NULL, 0);
    1596           0 :       return 0;
    1597             :     }
    1598             : 
    1599           0 :   return gpg_error (GPG_ERR_INV_NAME);
    1600             : }
    1601             : 
    1602             : 
    1603             : 
    1604             : /* Apply PKCS#1 V1.5 padding for signature operation.  The function
    1605             :  * combines padding, digest info and the hash value.  The buffer must
    1606             :  * be allocated by the caller matching the key size.  */
    1607             : static void
    1608           0 : apply_PKCS_padding(const unsigned char *dig, int diglen,
    1609             :                    const unsigned char *prefix, int prefixlen,
    1610             :                    unsigned char *buff, int bufflen)
    1611             : {
    1612             :   int i, n_ff;
    1613             : 
    1614             :   /* Caller must ensure a sufficient buffer.  */
    1615           0 :   if (diglen + prefixlen + 4 > bufflen)
    1616           0 :     return;
    1617           0 :   n_ff = bufflen - diglen - prefixlen - 3;
    1618             : 
    1619           0 :   *buff++ = 0x00;
    1620           0 :   *buff++ = 0x01;
    1621           0 :   for (i=0; i < n_ff; i++)
    1622           0 :     *buff++ = 0xFF;
    1623           0 :   *buff++ = 0x00;
    1624             : 
    1625           0 :   if (prefix)
    1626           0 :     memcpy (buff, prefix, prefixlen);
    1627           0 :   buff += prefixlen;
    1628           0 :   memcpy (buff, dig, diglen);
    1629             : }
    1630             : 
    1631             : 
    1632             : 
    1633             : /* Decode a digest info structure (DI,DILEN) to extract the hash
    1634             :  * value.  The buffer HASH to receive the digest must be provided by
    1635             :  * the caller with HASHLEN pointing to the inbound length.  HASHLEN is
    1636             :  * updated to the outbound length.  */
    1637             : static int
    1638           0 : hash_from_digestinfo (const unsigned char *di, size_t dilen,
    1639             :                       unsigned char *hash, size_t *hashlen)
    1640             : {
    1641             :   const unsigned char *p,*pp;
    1642             :   size_t n, nn, objlen, hdrlen;
    1643             :   int class, tag, constructed, ndef;
    1644             :   gpg_error_t err;
    1645             : 
    1646           0 :   p = di;
    1647           0 :   n = dilen;
    1648             : 
    1649           0 :   err = parse_ber_header (&p, &n, &class, &tag, &constructed,
    1650             :                           &ndef, &objlen, &hdrlen);
    1651           0 :   if (!err && (objlen > n || tag != TAG_SEQUENCE))
    1652           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
    1653           0 :   if ( err )
    1654           0 :     return err;
    1655             : 
    1656           0 :   pp = p;
    1657           0 :   nn = objlen;
    1658             : 
    1659           0 :   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
    1660             :                           &ndef, &objlen, &hdrlen);
    1661           0 :   if (!err && (objlen > nn || tag != TAG_SEQUENCE))
    1662           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
    1663           0 :   if ( err )
    1664           0 :     return err;
    1665             : 
    1666           0 :   pp += objlen;
    1667           0 :   nn -= objlen;
    1668             : 
    1669           0 :   err = parse_ber_header (&pp, &nn, &class, &tag, &constructed,
    1670             :                           &ndef, &objlen, &hdrlen);
    1671           0 :   if (!err && (objlen > nn || tag != TAG_OCTET_STRING))
    1672           0 :     err = gpg_error (GPG_ERR_INV_OBJ);
    1673           0 :   if ( err )
    1674           0 :     return err;
    1675             : 
    1676           0 :   if (*hashlen < objlen)
    1677           0 :     return gpg_error (GPG_ERR_TOO_SHORT);
    1678           0 :   memcpy (hash, pp, objlen);
    1679           0 :   *hashlen = objlen;
    1680           0 :   return 0;
    1681             : }
    1682             : 
    1683             : 
    1684             : /* Perform PIN verification
    1685             :  */
    1686             : static gpg_error_t
    1687           0 : verify_pin (app_t app, gpg_error_t (*pincb)(void*, const char *, char **),
    1688             :             void *pincb_arg)
    1689             : {
    1690             :   gpg_error_t err;
    1691             :   pininfo_t pininfo;
    1692             :   char *pinvalue;
    1693             :   char *prompt;
    1694             :   int sw;
    1695             : 
    1696           0 :   sw = apdu_send_simple (app->slot, 0, 0x00, ISO7816_VERIFY, 0x00, 0x81,
    1697             :                          -1, NULL);
    1698             : 
    1699           0 :   if (sw == SW_SUCCESS)
    1700           0 :     return 0;                   /* PIN already verified */
    1701             : 
    1702           0 :   if (sw == SW_REF_DATA_INV)
    1703             :     {
    1704           0 :       log_error ("SmartCard-HSM not initialized. Run sc-hsm-tool first\n");
    1705           0 :       return gpg_error (GPG_ERR_NO_PIN);
    1706             :     }
    1707             : 
    1708           0 :   if (sw == SW_CHV_BLOCKED)
    1709             :     {
    1710           0 :       log_error ("PIN Blocked\n");
    1711           0 :       return gpg_error (GPG_ERR_PIN_BLOCKED);
    1712             :     }
    1713             : 
    1714           0 :   memset (&pininfo, 0, sizeof pininfo);
    1715           0 :   pininfo.fixedlen = 0;
    1716           0 :   pininfo.minlen = 6;
    1717           0 :   pininfo.maxlen = 15;
    1718             : 
    1719           0 :   prompt = "||Please enter the PIN";
    1720             : 
    1721           0 :   if (!opt.disable_pinpad
    1722           0 :       && !iso7816_check_pinpad (app->slot, ISO7816_VERIFY, &pininfo) )
    1723             :     {
    1724           0 :       err = pincb (pincb_arg, prompt, NULL);
    1725           0 :       if (err)
    1726             :         {
    1727           0 :           log_info ("PIN callback returned error: %s\n", gpg_strerror (err));
    1728           0 :           return err;
    1729             :         }
    1730             : 
    1731           0 :       err = iso7816_verify_kp (app->slot, 0x81, &pininfo);
    1732           0 :       pincb (pincb_arg, NULL, NULL);  /* Dismiss the prompt. */
    1733             :     }
    1734             :   else
    1735             :     {
    1736           0 :       err = pincb (pincb_arg, prompt, &pinvalue);
    1737           0 :       if (err)
    1738             :         {
    1739           0 :           log_info ("PIN callback returned error: %s\n", gpg_strerror (err));
    1740           0 :           return err;
    1741             :         }
    1742             : 
    1743           0 :       err = iso7816_verify (app->slot, 0x81, pinvalue, strlen(pinvalue));
    1744           0 :       xfree (pinvalue);
    1745             :     }
    1746           0 :   if (err)
    1747             :     {
    1748           0 :       log_error ("PIN verification failed: %s\n", gpg_strerror (err));
    1749           0 :       return err;
    1750             :     }
    1751           0 :   log_debug ("PIN verification succeeded\n");
    1752           0 :   return err;
    1753             : }
    1754             : 
    1755             : 
    1756             : 
    1757             : /* Handler for the PKSIGN command.
    1758             : 
    1759             :    Create the signature and return the allocated result in OUTDATA.
    1760             :    If a PIN is required, the PINCB will be used to ask for the PIN;
    1761             :    that callback should return the PIN in an allocated buffer and
    1762             :    store that as the 3rd argument.
    1763             : 
    1764             :    The API is somewhat inconsistent: The caller can either supply
    1765             :    a plain hash and the algorithm in hashalgo or a complete
    1766             :    DigestInfo structure. The former is detect by characteristic length
    1767             :    of the provided data (20,28,32,48 or 64 byte).
    1768             : 
    1769             :    The function returns the RSA block in the size of the modulus or
    1770             :    the ECDSA signature in X9.62 format (SEQ/INT(r)/INT(s))
    1771             : */
    1772             : static gpg_error_t
    1773           0 : do_sign (app_t app, const char *keyidstr, int hashalgo,
    1774             :          gpg_error_t (*pincb)(void*, const char *, char **),
    1775             :          void *pincb_arg,
    1776             :          const void *indata, size_t indatalen,
    1777             :          unsigned char **outdata, size_t *outdatalen )
    1778             : {
    1779             :   static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */
    1780             :     { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03,
    1781             :       0x02, 0x01, 0x05, 0x00, 0x04, 0x14  };
    1782             :   static unsigned char sha1_prefix[15] =   /* (1.3.14.3.2.26) */
    1783             :     { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03,
    1784             :       0x02, 0x1a, 0x05, 0x00, 0x04, 0x14  };
    1785             :   static unsigned char sha224_prefix[19] = /* (2.16.840.1.101.3.4.2.4) */
    1786             :     { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48,
    1787             :       0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04,
    1788             :       0x1C  };
    1789             :   static unsigned char sha256_prefix[19] = /* (2.16.840.1.101.3.4.2.1) */
    1790             :     { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
    1791             :       0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
    1792             :       0x00, 0x04, 0x20  };
    1793             :   static unsigned char sha384_prefix[19] = /* (2.16.840.1.101.3.4.2.2) */
    1794             :     { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
    1795             :       0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05,
    1796             :       0x00, 0x04, 0x30  };
    1797             :   static unsigned char sha512_prefix[19] = /* (2.16.840.1.101.3.4.2.3) */
    1798             :     { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
    1799             :       0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05,
    1800             :       0x00, 0x04, 0x40  };
    1801             : 
    1802             :   gpg_error_t err;
    1803             :   unsigned char cdsblk[256]; /* Raw PKCS#1 V1.5 block with padding
    1804             :                                 (RSA) or hash.  */
    1805             :   prkdf_object_t prkdf;      /* The private key object. */
    1806             :   size_t cdsblklen;
    1807             :   unsigned char algoid;
    1808             :   int sw;
    1809             : 
    1810           0 :   if (!keyidstr || !*keyidstr)
    1811           0 :     return gpg_error (GPG_ERR_INV_VALUE);
    1812             : 
    1813           0 :   if (indatalen > 124)          /* Limit for 1024 bit key */
    1814           0 :     return gpg_error (GPG_ERR_INV_VALUE);
    1815             : 
    1816           0 :   err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
    1817           0 :   if (err)
    1818           0 :     return err;
    1819           0 :   if (!(prkdf->usageflags.sign || prkdf->usageflags.sign_recover
    1820           0 :         ||prkdf->usageflags.non_repudiation))
    1821             :     {
    1822           0 :       log_error ("key %s may not be used for signing\n", keyidstr);
    1823           0 :       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
    1824             :     }
    1825             : 
    1826           0 :   if (prkdf->keytype == KEY_TYPE_RSA)
    1827             :     {
    1828           0 :       algoid = 0x20;
    1829             : 
    1830           0 :       cdsblklen = prkdf->keysize >> 3;
    1831           0 :       if (!cdsblklen)
    1832           0 :         cdsblklen = 256;
    1833             : 
    1834           0 :       if (hashalgo == GCRY_MD_SHA1 && indatalen == 20)
    1835           0 :         apply_PKCS_padding (indata, indatalen,
    1836             :                             sha1_prefix, sizeof(sha1_prefix),
    1837             :                             cdsblk, cdsblklen);
    1838           0 :       else if (hashalgo == GCRY_MD_MD5 && indatalen == 20)
    1839           0 :         apply_PKCS_padding (indata, indatalen,
    1840             :                             rmd160_prefix, sizeof(rmd160_prefix),
    1841             :                             cdsblk, cdsblklen);
    1842           0 :       else if (hashalgo == GCRY_MD_SHA224 && indatalen == 28)
    1843           0 :         apply_PKCS_padding (indata, indatalen,
    1844             :                             sha224_prefix, sizeof(sha224_prefix),
    1845             :                             cdsblk, cdsblklen);
    1846           0 :       else if (hashalgo == GCRY_MD_SHA256 && indatalen == 32)
    1847           0 :         apply_PKCS_padding (indata, indatalen,
    1848             :                             sha256_prefix, sizeof(sha256_prefix),
    1849             :                             cdsblk, cdsblklen);
    1850           0 :       else if (hashalgo == GCRY_MD_SHA384 && indatalen == 48)
    1851           0 :         apply_PKCS_padding (indata, indatalen,
    1852             :                             sha384_prefix, sizeof(sha384_prefix),
    1853             :                             cdsblk, cdsblklen);
    1854           0 :       else if (hashalgo == GCRY_MD_SHA512 && indatalen == 64)
    1855           0 :         apply_PKCS_padding (indata, indatalen,
    1856             :                             sha512_prefix, sizeof(sha512_prefix),
    1857             :                             cdsblk, cdsblklen);
    1858             :       else  /* Assume it's already a digest info or TLS_MD5SHA1 */
    1859           0 :         apply_PKCS_padding (indata, indatalen, NULL, 0, cdsblk, cdsblklen);
    1860             :     }
    1861             :   else
    1862             :     {
    1863           0 :       algoid = 0x70;
    1864           0 :       if (indatalen != 20 && indatalen != 28 && indatalen != 32
    1865           0 :           && indatalen != 48 && indatalen != 64)
    1866             :         {
    1867           0 :           cdsblklen = sizeof(cdsblk);
    1868           0 :           err = hash_from_digestinfo (indata, indatalen, cdsblk, &cdsblklen);
    1869           0 :           if (err)
    1870             :             {
    1871           0 :               log_error ("DigestInfo invalid: %s\n", gpg_strerror (err));
    1872           0 :               return err;
    1873             :             }
    1874             :         }
    1875             :       else
    1876             :         {
    1877           0 :           memcpy (cdsblk, indata, indatalen);
    1878           0 :           cdsblklen = indatalen;
    1879             :         }
    1880             :     }
    1881             : 
    1882           0 :   err = verify_pin (app, pincb, pincb_arg);
    1883           0 :   if (err)
    1884           0 :     return err;
    1885             : 
    1886           0 :   sw = apdu_send_le (app->slot, 1, 0x80, 0x68, prkdf->key_reference, algoid,
    1887             :                      cdsblklen, cdsblk, 0, outdata, outdatalen);
    1888           0 :   return iso7816_map_sw (sw);
    1889             : }
    1890             : 
    1891             : 
    1892             : 
    1893             : /* Handler for the PKAUTH command.
    1894             : 
    1895             :    This is basically the same as the PKSIGN command but we first check
    1896             :    that the requested key is suitable for authentication; that is, it
    1897             :    must match the criteria used for the attribute $AUTHKEYID.  See
    1898             :    do_sign for calling conventions; there is no HASHALGO, though. */
    1899             : static gpg_error_t
    1900           0 : do_auth (app_t app, const char *keyidstr,
    1901             :          gpg_error_t (*pincb)(void*, const char *, char **),
    1902             :          void *pincb_arg,
    1903             :          const void *indata, size_t indatalen,
    1904             :          unsigned char **outdata, size_t *outdatalen )
    1905             : {
    1906             :   gpg_error_t err;
    1907             :   prkdf_object_t prkdf;
    1908             :   int algo;
    1909             : 
    1910           0 :   if (!keyidstr || !*keyidstr)
    1911           0 :     return gpg_error (GPG_ERR_INV_VALUE);
    1912             : 
    1913           0 :   err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
    1914           0 :   if (err)
    1915           0 :     return err;
    1916           0 :   if (!prkdf->usageflags.sign)
    1917             :     {
    1918           0 :       log_error ("key %s may not be used for authentication\n", keyidstr);
    1919           0 :       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
    1920             :     }
    1921             : 
    1922           0 :   algo = indatalen == 36? MD_USER_TLS_MD5SHA1 : GCRY_MD_SHA1;
    1923           0 :   return do_sign (app, keyidstr, algo, pincb, pincb_arg,
    1924             :                   indata, indatalen, outdata, outdatalen);
    1925             : }
    1926             : 
    1927             : 
    1928             : 
    1929             : /* Check PKCS#1 V1.5 padding and extract plain text.  The function
    1930             :  * allocates a buffer for the plain text.  The caller must release the
    1931             :  * buffer.  */
    1932             : static gpg_error_t
    1933           0 : strip_PKCS15_padding(unsigned char *src, int srclen, unsigned char **dst,
    1934             :                      size_t *dstlen)
    1935             : {
    1936             :   unsigned char *p;
    1937             : 
    1938           0 :   if (srclen < 2)
    1939           0 :     return gpg_error (GPG_ERR_DECRYPT_FAILED);
    1940           0 :   if (*src++ != 0x00)
    1941           0 :     return gpg_error (GPG_ERR_DECRYPT_FAILED);
    1942           0 :   if (*src++ != 0x02)
    1943           0 :     return gpg_error (GPG_ERR_DECRYPT_FAILED);
    1944           0 :   srclen -= 2;
    1945           0 :   while ((srclen > 0) && *src)
    1946             :     {
    1947           0 :       src++;
    1948           0 :       srclen--;
    1949             :     }
    1950             : 
    1951           0 :   if (srclen < 2)
    1952           0 :     return gpg_error (GPG_ERR_DECRYPT_FAILED);
    1953             : 
    1954           0 :   src++;
    1955           0 :   srclen--;
    1956             : 
    1957           0 :   p = xtrymalloc (srclen);
    1958           0 :   if (!p)
    1959           0 :     return gpg_error_from_syserror ();
    1960             : 
    1961           0 :   memcpy (p, src, srclen);
    1962           0 :   *dst = p;
    1963           0 :   *dstlen = srclen;
    1964             : 
    1965           0 :   return 0;
    1966             : }
    1967             : 
    1968             : 
    1969             : /* Decrypt a PKCS#1 V1.5 formatted cryptogram using the referenced
    1970             :    key.  */
    1971             : static gpg_error_t
    1972           0 : do_decipher (app_t app, const char *keyidstr,
    1973             :              gpg_error_t (*pincb)(void*, const char *, char **),
    1974             :              void *pincb_arg,
    1975             :              const void *indata, size_t indatalen,
    1976             :              unsigned char **outdata, size_t *outdatalen,
    1977             :              unsigned int *r_info)
    1978             : {
    1979             :   gpg_error_t err;
    1980             :   unsigned char p1blk[256]; /* Enciphered P1 block */
    1981             :   prkdf_object_t prkdf;     /* The private key object. */
    1982             :   unsigned char *rspdata;
    1983             :   size_t rspdatalen;
    1984             :   size_t p1blklen;
    1985             :   int sw;
    1986             : 
    1987           0 :   if (!keyidstr || !*keyidstr || !indatalen)
    1988           0 :     return gpg_error (GPG_ERR_INV_VALUE);
    1989             : 
    1990           0 :   err = prkdf_object_from_keyidstr (app, keyidstr, &prkdf);
    1991           0 :   if (err)
    1992           0 :     return err;
    1993           0 :   if (!(prkdf->usageflags.decrypt || prkdf->usageflags.unwrap))
    1994             :     {
    1995           0 :       log_error ("key %s may not be used for deciphering\n", keyidstr);
    1996           0 :       return gpg_error (GPG_ERR_WRONG_KEY_USAGE);
    1997             :     }
    1998             : 
    1999           0 :   if (prkdf->keytype != KEY_TYPE_RSA)
    2000           0 :     return gpg_error (GPG_ERR_NOT_SUPPORTED);
    2001             : 
    2002           0 :   p1blklen = prkdf->keysize >> 3;
    2003           0 :   if (!p1blklen)
    2004           0 :     p1blklen = 256;
    2005             : 
    2006             :   /* The input may be shorter (due to MPIs not storing leading zeroes)
    2007             :      or longer than the block size.  We put INDATA right aligned into
    2008             :      the buffer.  If INDATA is longer than the block size we truncate
    2009             :      it on the left. */
    2010           0 :   memset (p1blk, 0, sizeof(p1blk));
    2011           0 :   if (indatalen > p1blklen)
    2012           0 :     memcpy (p1blk, (unsigned char *)indata + (indatalen - p1blklen), p1blklen);
    2013             :   else
    2014           0 :     memcpy (p1blk + (p1blklen - indatalen), indata, indatalen);
    2015             : 
    2016             : 
    2017           0 :   err = verify_pin(app, pincb, pincb_arg);
    2018           0 :   if (err)
    2019           0 :     return err;
    2020             : 
    2021           0 :   sw = apdu_send_le (app->slot, 1, 0x80, 0x62, prkdf->key_reference, 0x21,
    2022             :                      p1blklen, p1blk, 0, &rspdata, &rspdatalen);
    2023           0 :   err = iso7816_map_sw (sw);
    2024           0 :   if (err)
    2025             :     {
    2026           0 :       log_error ("Decrypt failed: %s\n", gpg_strerror (err));
    2027           0 :       return err;
    2028             :     }
    2029             : 
    2030           0 :   err = strip_PKCS15_padding (rspdata, rspdatalen, outdata, outdatalen);
    2031           0 :   xfree (rspdata);
    2032             : 
    2033           0 :   if (!err)
    2034           0 :     *r_info |= APP_DECIPHER_INFO_NOPAD;
    2035             : 
    2036           0 :   return err;
    2037             : }
    2038             : 
    2039             : 
    2040             : 
    2041             : /*
    2042             :  * Select the SmartCard-HSM application on the card in SLOT.
    2043             :  */
    2044             : gpg_error_t
    2045           0 : app_select_sc_hsm (app_t app)
    2046             : {
    2047           0 :   int slot = app->slot;
    2048             :   int rc;
    2049             : 
    2050           0 :   rc = iso7816_select_application (slot, sc_hsm_aid, sizeof sc_hsm_aid, 0);
    2051           0 :   if (!rc)
    2052             :     {
    2053           0 :       app->apptype = "SC-HSM";
    2054             : 
    2055           0 :       app->app_local = xtrycalloc (1, sizeof *app->app_local);
    2056           0 :       if (!app->app_local)
    2057             :         {
    2058           0 :           rc = gpg_error_from_syserror ();
    2059           0 :           goto leave;
    2060             :         }
    2061             : 
    2062           0 :       rc = read_meta (app);
    2063           0 :       if (rc)
    2064           0 :         goto leave;
    2065             : 
    2066           0 :       app->fnc.deinit = do_deinit;
    2067           0 :       app->fnc.learn_status = do_learn_status;
    2068           0 :       app->fnc.readcert = do_readcert;
    2069           0 :       app->fnc.getattr = do_getattr;
    2070           0 :       app->fnc.setattr = NULL;
    2071           0 :       app->fnc.genkey = NULL;
    2072           0 :       app->fnc.sign = do_sign;
    2073           0 :       app->fnc.auth = do_auth;
    2074           0 :       app->fnc.decipher = do_decipher;
    2075           0 :       app->fnc.change_pin = NULL;
    2076           0 :       app->fnc.check_pin = NULL;
    2077             : 
    2078             :     leave:
    2079           0 :       if (rc)
    2080           0 :         do_deinit (app);
    2081             :    }
    2082             : 
    2083           0 :   return rc;
    2084             : }

Generated by: LCOV version 1.11