"Fossies" - the Fresh Open Source Software Archive

Member "opensc-0.22.0/src/libopensc/card-gpk.c" (10 Aug 2021, 46679 Bytes) of package /linux/privat/opensc-0.22.0.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "card-gpk.c" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 0.21.0_vs_0.22.0.

    1 /*
    2  * card-gpk: Driver for GPK 4000 cards
    3  *
    4  * Copyright (C) 2002  Olaf Kirch <okir@suse.de>
    5  *
    6  * This library is free software; you can redistribute it and/or
    7  * modify it under the terms of the GNU Lesser General Public
    8  * License as published by the Free Software Foundation; either
    9  * version 2.1 of the License, or (at your option) any later version.
   10  *
   11  * This library is distributed in the hope that it will be useful,
   12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
   13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   14  * Lesser General Public License for more details.
   15  *
   16  * You should have received a copy of the GNU Lesser General Public
   17  * License along with this library; if not, write to the Free Software
   18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   19  */
   20 
   21 #if HAVE_CONFIG_H
   22 #include "config.h"
   23 #endif
   24 #ifdef ENABLE_OPENSSL   /* empty file without openssl */
   25 
   26 #include <stdlib.h>
   27 #include <string.h>
   28 #include <openssl/evp.h>
   29 #include <openssl/rand.h>
   30 
   31 #include "internal.h"
   32 #include "cardctl.h"
   33 #include "pkcs15.h"
   34 
   35 #define GPK_SEL_MF      0x00
   36 #define GPK_SEL_DF      0x01
   37 #define GPK_SEL_EF      0x02
   38 #define GPK_SEL_AID     0x04
   39 #define GPK_FID_MF      0x3F00
   40 
   41 #define GPK_FTYPE_SC        0x21
   42 
   43 #define GPK_SIGN_RSA_MD5    0x11
   44 #define GPK_SIGN_RSA_SHA    0x12
   45 #define GPK_SIGN_RSA_SSL    0x18
   46 #define GPK_VERIFY_RSA_MD5  0x21
   47 #define GPK_VERIFY_RSA_SHA  0x22
   48 #define GPK_AUTH_RSA_MD5    0x31
   49 #define GPK_AUTH_RSA_SHA    0x32
   50 #define GPK_AUTH_RSA_SSL    0x38
   51 #define GPK_UNWRAP_RSA      0x77
   52 
   53 #define GPK_MAX_PINS        8
   54 #define GPK_HASH_CHUNK      62
   55 
   56 /*
   57  * GPK4000 private data
   58  */
   59 struct gpk_private_data {
   60     /* The GPK usually do file offsets in multiples of
   61      * 4 bytes. This can be customized however. We
   62      * should really query for this during gpk_init */
   63     unsigned int    offset_shift;
   64     unsigned int    offset_mask;
   65     unsigned int    locked : 1,
   66             sample_card : 1;
   67 
   68     /* access control bits of file most recently selected */
   69     unsigned short int ac[3];
   70 
   71     /* is non-zero if we should use secure messaging */
   72     unsigned    key_set   : 1;
   73     unsigned int    key_reference;
   74     u8      key[16];
   75 
   76     /* crypto related data from set_security_env */
   77     unsigned int    sec_algorithm;
   78     unsigned int    sec_hash_len;
   79     unsigned int    sec_mod_len;
   80     unsigned int    sec_padding;
   81 };
   82 #define DRVDATA(card)   ((struct gpk_private_data *) ((card)->drv_data))
   83 
   84 static int  gpk_get_info(sc_card_t *, int, int, u8 *, size_t);
   85 
   86 /*
   87  * ATRs of GPK4000 cards courtesy of libscez
   88  */
   89 static const struct sc_atr_table gpk_atrs[] = {
   90     { "3B:27:00:80:65:A2:04:01:01:37", NULL, "GPK 4K", SC_CARD_TYPE_GPK_GPK4000_s, 0, NULL },
   91     { "3B:27:00:80:65:A2:05:01:01:37", NULL, "GPK 4K", SC_CARD_TYPE_GPK_GPK4000_sp, 0, NULL },
   92     { "3B:27:00:80:65:A2:0C:01:01:37", NULL, "GPK 4K", SC_CARD_TYPE_GPK_GPK4000_su256, 0, NULL },
   93     { "3B:A7:00:40:14:80:65:A2:14:01:01:37", NULL, "GPK 4K", SC_CARD_TYPE_GPK_GPK4000_sdo, 0, NULL },
   94     { "3B:A7:00:40:18:80:65:A2:08:01:01:52", NULL, "GPK 8K", SC_CARD_TYPE_GPK_GPK8000_8K, 0, NULL },
   95     { "3B:A7:00:40:18:80:65:A2:09:01:01:52", NULL, "GPK 8K", SC_CARD_TYPE_GPK_GPK8000_16K, 0, NULL },
   96     { "3B:A7:00:40:18:80:65:A2:09:01:02:52", NULL, "GPK 16K", SC_CARD_TYPE_GPK_GPK16000, 0, NULL },
   97     { "3B:A7:00:40:18:80:65:A2:09:01:03:52", NULL, "GPK 16K", SC_CARD_TYPE_GPK_GPK16000, 0, NULL },
   98     { NULL, NULL, NULL, 0, 0, NULL }
   99 };
  100 
  101 /*
  102  * Driver and card ops structures
  103  */
  104 static struct sc_card_operations    gpk_ops, *iso_ops;
  105 static struct sc_card_driver gpk_drv = {
  106     "Gemplus GPK",
  107     "gpk",
  108     &gpk_ops,
  109     NULL, 0, NULL
  110 };
  111 
  112 /*
  113  * return 1 if this driver can handle the card
  114  */
  115 static int
  116 gpk_match_card(sc_card_t *card)
  117 {
  118     int i;
  119 
  120     i = _sc_match_atr(card, gpk_atrs, &card->type);
  121     if (i < 0) {
  122         const u8 *hist_bytes = card->reader->atr_info.hist_bytes;
  123 
  124         /* Gemplus GPK docs say we can use just the 
  125          * FMN and PRN fields of the historical bytes
  126          * to recognize a GPK card
  127          *  See Table 43, pp. 188
  128          * We'll use the first 2 bytes as well
  129          */
  130 
  131         if ((card->reader->atr_info.hist_bytes_len >= 7)
  132             && (hist_bytes[0] == 0x80)
  133             && (hist_bytes[1] == 0x65)
  134             && (hist_bytes[2] == 0xa2)) {   /* FMN */
  135             if (hist_bytes[3] == 0x08) {    /* PRN? */
  136                 card->type = SC_CARD_TYPE_GPK_GPK8000;
  137                 return 1;
  138             }
  139             if (hist_bytes[3] == 0x09) {    /* PRN? */
  140                 card->type = SC_CARD_TYPE_GPK_GPK16000;
  141                 return 1;
  142             }
  143         }
  144         return 0;
  145     }
  146     return 1;
  147 }
  148 
  149 /*
  150  * Initialize the card struct
  151  */
  152 static int
  153 gpk_init(sc_card_t *card)
  154 {
  155     struct gpk_private_data *priv;
  156     unsigned long   exponent, flags, kg;
  157     unsigned char info[13];
  158 
  159     card->drv_data = priv = calloc(1, sizeof(*priv));
  160     if (card->drv_data == NULL)
  161         return SC_ERROR_OUT_OF_MEMORY;
  162 
  163     /* read/write/update binary expect offset to be the
  164      * number of 32 bit words.
  165      * offset_shift is the shift value.
  166      * offset_mask is the corresponding mask. */
  167     priv->offset_shift = 2;
  168     priv->offset_mask = 3;
  169     card->cla = 0x00;
  170 
  171     /* Set up algorithm info. GPK 16000 will do any RSA
  172      * exponent, earlier ones are restricted to 0x10001 */
  173     flags = SC_ALGORITHM_RSA_HASH_MD5 | SC_ALGORITHM_RSA_HASH_SHA1
  174         | SC_ALGORITHM_RSA_HASH_MD5_SHA1;
  175     flags |= SC_ALGORITHM_RSA_PAD_PKCS1 | SC_ALGORITHM_RSA_PAD_ANSI
  176         | SC_ALGORITHM_RSA_PAD_ISO9796;
  177     exponent = (card->type < SC_CARD_TYPE_GPK_GPK16000) ? 0x10001 : 0;
  178     kg = (card->type >= SC_CARD_TYPE_GPK_GPK8000) ? SC_ALGORITHM_ONBOARD_KEY_GEN : 0;
  179     _sc_card_add_rsa_alg(card,  512, flags|kg, exponent);
  180     _sc_card_add_rsa_alg(card,  768, flags, exponent);
  181     _sc_card_add_rsa_alg(card, 1024, flags|kg, exponent);
  182 
  183     /* Inspect the LOCK byte */
  184     if (gpk_get_info(card, 0x02, 0xA4, info, sizeof(info)) >= 0) {
  185         if (info[12] & 0x40) {
  186             priv->offset_shift = 0;
  187             priv->offset_mask = 0;
  188         }
  189         if (info[12] & 0x10) {
  190             /* DSA supported - add algo information.
  191              * It's highly unlikely we'll ever see this.
  192              */
  193         }
  194         if (info[12] & 0x08) {
  195             priv->locked = 1;
  196         }
  197         /* Sample cards use a transport key of "TEST KEYTEST KEY" */
  198         if (!memcmp(info+5, "\x00\xff\x00", 3)) {
  199             priv->sample_card = 1;
  200         }
  201     }
  202 
  203     /* State that we have an RNG */
  204     card->caps |= SC_CARD_CAP_RNG;
  205 
  206     /* Make sure max send/receive size is 4 byte aligned and <256. */
  207     card->max_recv_size = 252;
  208 
  209     return SC_SUCCESS;
  210 }
  211 
  212 /*
  213  * Card is being closed; discard any private data etc
  214  */
  215 static int
  216 gpk_finish(sc_card_t *card)
  217 {
  218     if (card->drv_data)
  219         free(card->drv_data);
  220     card->drv_data = NULL;
  221     return 0;
  222 }
  223 
  224 /*
  225  * Select a DF/EF
  226  */
  227 static int
  228 match_path(sc_card_t *card, unsigned short int **pathptr, size_t *pathlen,
  229         int need_info)
  230 {
  231     unsigned short int  *curptr, *ptr;
  232     size_t      curlen, len;
  233     size_t      i;
  234 
  235     curptr = (unsigned short int *) card->cache.current_path.value;
  236     curlen = card->cache.current_path.len;
  237     ptr    = *pathptr;
  238     len    = *pathlen;
  239 
  240     if (curlen < 1 || len < 1)
  241         return 0;
  242 
  243     /* Make sure path starts with MF.
  244      * Note the cached path should always begin with MF. */
  245     if (ptr[0] != GPK_FID_MF || curptr[0] != GPK_FID_MF)
  246         return 0;
  247 
  248     for (i = 1; i < len && i < curlen; i++) {
  249         if (ptr[i] != curptr[i])
  250             break;
  251     }
  252 
  253     if (len < curlen) {
  254         /* Caller asked us to select the DF, but the
  255          * current file is some EF within the DF we're
  256          * interested in. Say ACK */
  257         if (len == 2)
  258             goto okay;
  259         /* Anything else won't work */
  260         return 0;
  261     }
  262 
  263     /* In the case of an exact match:
  264      * If the caller needs info on the file to be selected,
  265      * make sure we at least select the file itself.
  266      * If the DF matches the current DF, just return the
  267      * FID */
  268     if (i == len && need_info) {
  269         if (i > 1) {
  270             *pathptr = ptr + len - 1;
  271             *pathlen = len - 1;
  272             return 1;
  273         }
  274         /* bummer */
  275         return 0;
  276     }
  277 
  278 okay:
  279     *pathptr = ptr + i;
  280     *pathlen = len - i;
  281     return 1;
  282 }
  283 
  284 static void
  285 ac_to_acl(unsigned int ac, sc_file_t *file, unsigned int op)
  286 {
  287     unsigned int    npins, pin;
  288 
  289     npins = (ac >> 14) & 3;
  290     if (npins == 3) {
  291         sc_file_add_acl_entry(file, op, SC_AC_NEVER,
  292                     SC_AC_KEY_REF_NONE);
  293         return;
  294     }
  295 
  296     sc_file_add_acl_entry(file, op, SC_AC_NONE, SC_AC_KEY_REF_NONE);
  297     pin = ac & 0xFF;
  298     if (npins >= 1)
  299         sc_file_add_acl_entry(file, op, SC_AC_CHV, (pin >> 4) & 0xF);
  300     if (npins == 2)
  301         sc_file_add_acl_entry(file, op, SC_AC_CHV, pin & 0xF);
  302 
  303     /* Check whether secure messaging key is specified */
  304     if (ac & 0x3F00)
  305         sc_file_add_acl_entry(file, op, SC_AC_PRO, (ac & 0x3F00) >> 8);
  306 }
  307 
  308 /*
  309  * Convert ACLs requested by the application to access condition
  310  * bits supported by the GPK. Since these do not map 1:1 there's
  311  * some fuzz involved.
  312  */
  313 static void
  314 acl_to_ac(sc_file_t *file, unsigned int op, u8 *ac)
  315 {
  316     const sc_acl_entry_t *acl;
  317     unsigned int    npins = 0;
  318 
  319     ac[0] = ac[1] = 0;
  320 
  321     if ((acl = sc_file_get_acl_entry(file, op)) == NULL)
  322         return;
  323 
  324     assert(acl->method != SC_AC_UNKNOWN);
  325     switch (acl->method) {
  326     case SC_AC_NEVER:
  327         ac[0] = 0xC0;
  328         return;
  329     case SC_AC_NONE:
  330         return;
  331     }
  332 
  333     while (acl) {
  334         if (acl->method == SC_AC_CHV) {
  335             /* Support up to 2 PINS only */
  336             if (++npins >= 2)
  337                 continue;
  338             ac[1] >>= 4;
  339             ac[1] |= acl->key_ref << 4;
  340             ac[0] += 0x40;
  341         }
  342         if (acl->method == SC_AC_PRO) {
  343             ac[0] |= acl->key_ref & 0x1f;
  344         }
  345         acl = acl->next;
  346     }
  347 }
  348 
  349 static int
  350 gpk_parse_fci(sc_card_t *card,
  351         const u8 *buf, size_t buflen,
  352         sc_file_t *file)
  353 {
  354     const u8    *end, *next;
  355     unsigned int    tag, len;
  356 
  357     end = buf + buflen;
  358     for (; buf + 2 < end; buf = next) {
  359         next = buf + 2 + buf[1];
  360         if (next > end)
  361             break;
  362         tag = *buf++;
  363         len = *buf++;
  364         if (tag == 0x84) {
  365             /* unknown purpose - usually the name, but
  366              * the content looks weird, such as
  367              * 84 0D A0 00 00 00 18 0F 00 00 01 63 00 01 04
  368              */
  369         } else
  370         if (tag == 0xC1 && len >= 2) {
  371             /* Seems to be the file id, followed by something
  372              * C1 04 02 00 00 00 */
  373             file->id = (buf[0] << 8) | buf[1];
  374         } else
  375         if (tag == 0xC2) {
  376             /* unknown purpose
  377              * C2 01 01
  378              */
  379         }
  380     }
  381 
  382     return 0;
  383 }
  384 
  385 static int
  386 gpk_parse_fileinfo(sc_card_t *card,
  387         const u8 *buf, size_t buflen,
  388         sc_file_t *file)
  389 {
  390     const u8    *sp, *end, *next;
  391     int     i, rc;
  392 
  393     memset(file, 0, sizeof(*file));
  394     for (i = 0; i < SC_MAX_AC_OPS; i++)
  395         sc_file_add_acl_entry(file, i, SC_AC_UNKNOWN, SC_AC_KEY_REF_NONE);
  396 
  397     end = buf + buflen;
  398     for (sp = buf; sp + 2 < end; sp = next) {
  399         next = sp + 2 + sp[1];
  400         if (next > end)
  401             break;
  402         if (sp[0] == 0x84) {
  403             /* ignore if name is longer than what it should be */
  404             if (sp[1] > sizeof(file->name))
  405                 continue;
  406             memset(file->name, 0, sizeof(file->name));
  407             memcpy(file->name, sp+2, sp[1]);
  408         } else
  409         if (sp[0] == 0x85) {
  410             unsigned int    ac[3], n;
  411 
  412             if (sp + 11 + 2*3 >= end)
  413                 break;
  414 
  415             file->id = (sp[4] << 8) | sp[5];
  416             file->size = (sp[8] << 8) | sp[9];
  417             file->record_length = sp[7];
  418 
  419             /* Map ACLs. Note the third AC byte is
  420              * valid of EFs only */
  421             for (n = 0; n < 3; n++)
  422                 ac[n] = (sp[10+2*n] << 8) | sp[11+2*n];
  423 
  424             /* Examine file type */
  425             switch (sp[6] & 7) {
  426             case 0x01: case 0x02: case 0x03: case 0x04:
  427             case 0x05: case 0x06: case 0x07:
  428                 file->type = SC_FILE_TYPE_WORKING_EF;
  429                 file->ef_structure = sp[6] & 7;
  430                 ac_to_acl(ac[0], file, SC_AC_OP_UPDATE);
  431                 ac_to_acl(ac[1], file, SC_AC_OP_WRITE);
  432                 ac_to_acl(ac[2], file, SC_AC_OP_READ);
  433                 break;
  434             case 0x00: /* 0x38 is DF */
  435                 file->type = SC_FILE_TYPE_DF;
  436                 /* Icky: the GPK uses different ACLs
  437                  * for creating data files and
  438                  * 'sensitive' i.e. key files */
  439                 ac_to_acl(ac[0], file, SC_AC_OP_LOCK);
  440                 ac_to_acl(ac[1], file, SC_AC_OP_CREATE);
  441                 sc_file_add_acl_entry(file, SC_AC_OP_SELECT,
  442                     SC_AC_NONE, SC_AC_KEY_REF_NONE);
  443                 sc_file_add_acl_entry(file, SC_AC_OP_DELETE,
  444                     SC_AC_NEVER, SC_AC_KEY_REF_NONE);
  445                 sc_file_add_acl_entry(file, SC_AC_OP_REHABILITATE,
  446                     SC_AC_NEVER, SC_AC_KEY_REF_NONE);
  447                 sc_file_add_acl_entry(file, SC_AC_OP_INVALIDATE,
  448                     SC_AC_NEVER, SC_AC_KEY_REF_NONE);
  449                 sc_file_add_acl_entry(file, SC_AC_OP_LIST_FILES,
  450                     SC_AC_NEVER, SC_AC_KEY_REF_NONE);
  451                 break;
  452             }
  453         } else
  454         if (sp[0] == 0x6f) {
  455             /* oops - this is a directory with an IADF.
  456              * This happens with the personalized GemSafe cards
  457              * for instance. */
  458             file->type = SC_FILE_TYPE_DF;
  459             rc = gpk_parse_fci(card, sp + 2, sp[1], file);
  460             if (rc < 0)
  461                 return rc;
  462         }
  463     }
  464 
  465     if (file->record_length)
  466         file->record_count = file->size / file->record_length;
  467     file->magic = SC_FILE_MAGIC;
  468 
  469     return 0;
  470 }
  471 
  472 static int
  473 gpk_select(sc_card_t *card, int kind,
  474         const u8 *buf, size_t buflen,
  475         sc_file_t **file)
  476 {
  477     struct gpk_private_data *priv = DRVDATA(card);
  478     sc_apdu_t   apdu;
  479     u8      resbuf[256];
  480     int     r;
  481 
  482     /* If we're about to select a DF, invalidate secure messaging keys */
  483     if (kind == GPK_SEL_MF || kind == GPK_SEL_DF) {
  484         memset(priv->key, 0, sizeof(priv->key));
  485         priv->key_set = 0;
  486     }
  487 
  488     /* do the apdu thing */
  489     memset(&apdu, 0, sizeof(apdu));
  490     apdu.cla = 0x00;
  491     apdu.cse = SC_APDU_CASE_3_SHORT;
  492     apdu.ins = 0xA4;
  493     apdu.p1 = kind;
  494     apdu.p2 = 0;
  495     apdu.data = buf;
  496     apdu.datalen = buflen;
  497     apdu.lc = apdu.datalen;
  498 
  499     if (file) {
  500         apdu.cse = SC_APDU_CASE_4_SHORT;
  501         apdu.resp = resbuf;
  502         apdu.resplen = sizeof(resbuf);
  503         apdu.le = sizeof(resbuf);
  504     }
  505 
  506     r = sc_transmit_apdu(card, &apdu);
  507     LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
  508     r = sc_check_sw(card, apdu.sw1, apdu.sw2);
  509     LOG_TEST_RET(card->ctx, r, "Card returned error");
  510 
  511     /* Nothing we can say about it... invalidate
  512      * path cache */
  513     if (kind == GPK_SEL_AID) {
  514         card->cache.current_path.len = 0;
  515     }
  516 
  517     if (file == NULL)
  518         return 0;
  519     *file = sc_file_new();
  520 
  521     r = gpk_parse_fileinfo(card, apdu.resp, apdu.resplen, *file);
  522     if (r < 0) {
  523         sc_file_free(*file);
  524         *file = NULL;
  525     }
  526     return r;
  527 }
  528 
  529 static int
  530 gpk_select_id(sc_card_t *card, int kind, unsigned int fid,
  531         sc_file_t **file)
  532 {
  533     sc_path_t   *cp = &card->cache.current_path;
  534     u8      fbuf[2];
  535     int     r;
  536 
  537     sc_log(card->ctx, 
  538         "gpk_select_id(0x%04X, kind=%u)\n", fid, kind);
  539 
  540     fbuf[0] = fid >> 8;
  541     fbuf[1] = fid & 0xff;
  542 
  543     r = gpk_select(card, kind, fbuf, 2, file);
  544 
  545     /* Fix up the path cache.
  546      * NB we never cache the ID of an EF, just the DF path */
  547     if (r == 0) {
  548         unsigned short int  *path;
  549 
  550         switch (kind) {
  551         case GPK_SEL_MF:
  552             cp->len = 0;
  553             /* fallthru */
  554         case GPK_SEL_DF:
  555             if (cp->len + 1 > SC_MAX_PATH_SIZE / 2) {
  556                 return SC_ERROR_INTERNAL;
  557             }
  558             path = (unsigned short int *) cp->value;
  559             path[cp->len++] = fid;
  560         }
  561     } else {
  562         cp->len = 0;
  563     }
  564     return r;
  565 }
  566 
  567 static int
  568 gpk_select_file(sc_card_t *card, const sc_path_t *path,
  569         sc_file_t **file)
  570 {
  571     unsigned short int  pathtmp[SC_MAX_PATH_SIZE/2];
  572     unsigned short int  *pathptr;
  573     size_t          pathlen, n;
  574     int         locked = 0, r = 0, use_relative = 0, retry = 1;
  575     u8          leaf_type;
  576 
  577     SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
  578 
  579     /* Handle the AID case first */
  580     if (path->type == SC_PATH_TYPE_DF_NAME) {
  581         if (path->len > 16)
  582             return SC_ERROR_INVALID_ARGUMENTS;
  583         r = gpk_select(card, GPK_SEL_AID,
  584                     path->value, path->len, file);
  585         goto done;
  586     }
  587 
  588     /* Now we know we're dealing with 16bit FIDs, either as
  589      * an absolute path name (SC_PATH_TYPE_PATH) or a relative
  590      * FID (SC_PATH_TYPE_FILE_ID)
  591      *
  592      * The API should really tell us whether this is a DF or EF
  593      * we're selecting. All we can do is read tea leaves...
  594      */
  595     leaf_type = GPK_SEL_EF;
  596 
  597 try_again:
  598     if ((path->len & 1) || path->len > sizeof(pathtmp))
  599         return SC_ERROR_INVALID_ARGUMENTS;
  600     pathptr = pathtmp;
  601     memset(pathtmp, 0, sizeof pathtmp);
  602     for (n = 0; n < path->len; n += 2)
  603         pathptr[n>>1] = (path->value[n] << 8)|path->value[n+1];
  604     pathlen = path->len >> 1;
  605 
  606     /* See whether we can skip an initial portion of the
  607      * (absolute) path */
  608     if (path->type == SC_PATH_TYPE_PATH) {
  609         /* Do not retry selecting if this cannot be a DF */
  610         if ((pathptr[0] == GPK_FID_MF && pathlen > 2)
  611          || (pathptr[0] != GPK_FID_MF && pathlen > 1))
  612             retry = 0;
  613         use_relative = match_path(card, &pathptr, &pathlen, file != 0);
  614         if (pathlen == 0)
  615             goto done;
  616     } else {
  617         /* SC_PATH_TYPE_FILEID */
  618         if (pathlen > 1)
  619             return SC_ERROR_INVALID_ARGUMENTS;
  620         use_relative = 1;
  621     }
  622 
  623     if (pathlen == 1 && pathptr[0] == GPK_FID_MF) {
  624         /* Select just the MF */
  625         leaf_type = GPK_SEL_MF;
  626     } else {
  627         if (!locked++) {
  628             r = sc_lock(card);
  629             LOG_TEST_RET(card->ctx, r, "sc_lock() failed");
  630         }
  631 
  632         /* Do we need to select the MF first? */
  633         if (!use_relative) {
  634             r = gpk_select_id(card, GPK_SEL_MF, GPK_FID_MF, NULL);
  635             if (r)
  636                 sc_unlock(card);
  637             LOG_TEST_RET(card->ctx, r, "Unable to select MF");
  638 
  639             /* Consume the MF FID if it's there */
  640             if (pathptr[0] == GPK_FID_MF) {
  641                 pathptr++;
  642                 pathlen--;
  643             }
  644             if (pathlen == 0)
  645                 goto done;
  646         }
  647 
  648         /* Next comes a DF, if at all.
  649          * This loop can deal with nesting levels > 1 even
  650          * though the GPK4000 doesn't support it. */
  651         while (pathlen > 1) {
  652             r = gpk_select_id(card, GPK_SEL_DF, pathptr[0], NULL);
  653             if (r)
  654                 sc_unlock(card);
  655             LOG_TEST_RET(card->ctx, r, "Unable to select DF");
  656             pathptr++;
  657             pathlen--;
  658         }
  659     }
  660 
  661     /* Remaining component will be a DF or EF. How do we find out?
  662      * All we can do is try */
  663     r = gpk_select_id(card, leaf_type, pathptr[0], file);
  664     if (r) {
  665         /* Did we guess EF, and were wrong? If so, invalidate
  666          * path cache and try again; this time aiming for a DF */
  667         if (leaf_type == GPK_SEL_EF && retry) {
  668             card->cache.current_path.len = 0;
  669             leaf_type = GPK_SEL_DF;
  670             goto try_again;
  671         }
  672     }
  673 
  674 done:
  675     if (locked)
  676         sc_unlock(card);
  677     return r;
  678 }
  679 
  680 /*
  681  * GPK versions of {read,write,update}_binary functions.
  682  * Required because by default the GPKs do word offsets
  683  */
  684 static int
  685 gpk_read_binary(sc_card_t *card, unsigned int offset,
  686         u8 *buf, size_t count, unsigned long flags)
  687 {
  688     struct gpk_private_data *priv = DRVDATA(card);
  689 
  690     if (offset & priv->offset_mask) {
  691         sc_log(card->ctx,  "Invalid file offset (not a multiple of %d)",
  692                 priv->offset_mask + 1);
  693         return SC_ERROR_INVALID_ARGUMENTS;
  694     }
  695     return iso_ops->read_binary(card, offset >> priv->offset_shift,
  696             buf, count, flags);
  697 }
  698 
  699 static int
  700 gpk_write_binary(sc_card_t *card, unsigned int offset,
  701         const u8 *buf, size_t count, unsigned long flags)
  702 {
  703     struct gpk_private_data *priv = DRVDATA(card);
  704 
  705     if (offset & priv->offset_mask) {
  706         sc_log(card->ctx,  "Invalid file offset (not a multiple of %d)",
  707                 priv->offset_mask + 1);
  708         return SC_ERROR_INVALID_ARGUMENTS;
  709     }
  710     return iso_ops->write_binary(card, offset >> priv->offset_shift,
  711             buf, count, flags);
  712 }
  713 
  714 static int
  715 gpk_update_binary(sc_card_t *card, unsigned int offset,
  716         const u8 *buf, size_t count, unsigned long flags)
  717 {
  718     struct gpk_private_data *priv = DRVDATA(card);
  719 
  720     if (offset & priv->offset_mask) {
  721         sc_log(card->ctx,  "Invalid file offset (not a multiple of %d)",
  722                 priv->offset_mask + 1);
  723         return SC_ERROR_INVALID_ARGUMENTS;
  724     }
  725     return iso_ops->update_binary(card, offset >> priv->offset_shift,
  726             buf, count, flags);
  727 }
  728 
  729 /*
  730  * Secure messaging
  731  */
  732 static int
  733 gpk_compute_crycks(sc_card_t *card, sc_apdu_t *apdu,
  734             u8 *crycks1)
  735 {
  736     struct gpk_private_data *priv = DRVDATA(card);
  737     u8      in[8], out[8], block[64];
  738     unsigned int    len = 0, i;
  739     int             r = SC_SUCCESS, outl;
  740     EVP_CIPHER_CTX  *ctx = NULL;
  741 
  742     ctx = EVP_CIPHER_CTX_new();
  743     if (ctx == NULL)
  744         return SC_ERROR_INTERNAL;
  745 
  746 
  747     /* Fill block with 0x00 and then with the data. */
  748     memset(block, 0x00, sizeof(block));
  749     block[len++] = apdu->cla;
  750     block[len++] = apdu->ins;
  751     block[len++] = apdu->p1;
  752     block[len++] = apdu->p2;
  753     block[len++] = apdu->lc + 3;
  754     if (apdu->datalen + len > sizeof(block))
  755         i = sizeof(block) - len;
  756     else
  757         i = apdu->datalen;
  758     memcpy(block+len, apdu->data, i);
  759     len += i;
  760 
  761     /* Set IV */
  762     memset(in, 0x00, 8);
  763 
  764     EVP_EncryptInit_ex(ctx, EVP_des_ede_cbc(), NULL, priv->key, in);
  765     for (i = 0; i < len; i += 8) {
  766         if (!EVP_EncryptUpdate(ctx, out, &outl, &block[i], 8)) {
  767             r = SC_ERROR_INTERNAL;
  768             break;
  769         }
  770     }
  771     EVP_CIPHER_CTX_free(ctx);
  772 
  773     memcpy((u8 *) (apdu->data + apdu->datalen), out + 5, 3);
  774     apdu->datalen += 3;
  775     apdu->lc += 3;
  776     apdu->le += 3;
  777     if (crycks1)
  778         memcpy(crycks1, out, 3);
  779     sc_mem_clear(in, sizeof(in));
  780     sc_mem_clear(out, sizeof(out));
  781     sc_mem_clear(block, sizeof(block));
  782     return r;
  783 }
  784 
  785 /*
  786  * Verify secure messaging response
  787  */
  788 static int
  789 gpk_verify_crycks(sc_card_t *card, sc_apdu_t *apdu, u8 *crycks)
  790 {
  791     if (apdu->resplen < 3
  792      || memcmp(apdu->resp + apdu->resplen - 3, crycks, 3)) {
  793         sc_log(card->ctx, 
  794             "Invalid secure messaging reply\n");
  795         return SC_ERROR_UNKNOWN_DATA_RECEIVED;
  796     }
  797     apdu->resplen -= 3;
  798     return 0;
  799 }
  800 
  801 /*
  802  * Create a file or directory.
  803  * This is a bit tricky because we abuse the ef_structure
  804  * field to transport file types that are non-standard
  805  * (the GPK4000 has lots of bizarre file types).
  806  */
  807 static int
  808 gpk_create_file(sc_card_t *card, sc_file_t *file)
  809 {
  810     struct gpk_private_data *priv = DRVDATA(card);
  811     sc_apdu_t   apdu;
  812     u8      data[28+3], crycks[3], resp[3];
  813     size_t      datalen, namelen;
  814     int     r;
  815 
  816     sc_log(card->ctx, 
  817         "gpk_create_file(0x%04X)\n", file->id);
  818 
  819     /* Prepare APDU */
  820     memset(&apdu, 0, sizeof(apdu));
  821     apdu.cla = 0x80;    /* assume no secure messaging */
  822     apdu.cse = SC_APDU_CASE_3_SHORT;
  823     apdu.ins = 0xE0;
  824     apdu.p2  = 0x00;
  825 
  826     /* clear data */
  827     memset(data, 0, sizeof(data));
  828     datalen = 12;
  829 
  830     /* FID */
  831     data[0] = file->id >> 8;
  832     data[1] = file->id & 0xFF;
  833 
  834     /* encode ACLs */
  835     if (file->type == SC_FILE_TYPE_DF) {
  836         /* The GPK4000 has separate AC bits for
  837          * creating sensitive files and creating
  838          * data files. Since OpenSC has just the notion
  839          * of "file" we use the same ACL for both AC words
  840          */
  841         apdu.p1 = 0x01; /* create DF */
  842         data[2] = 0x38;
  843         acl_to_ac(file, SC_AC_OP_CREATE, data + 6);
  844         acl_to_ac(file, SC_AC_OP_CREATE, data + 8);
  845         if ((namelen = file->namelen) != 0) {
  846             if (namelen > 16)
  847                 return SC_ERROR_INVALID_ARGUMENTS;
  848             memcpy(data+datalen, file->name, namelen);
  849             data[5] = namelen;
  850             datalen += namelen;
  851         }
  852     } else {
  853         apdu.p1 = 0x02; /* create EF */
  854         data[2] = file->ef_structure;
  855         data[3] = file->record_length;
  856         data[4] = file->size >> 8;
  857         data[5] = file->size & 0xff;
  858         acl_to_ac(file, SC_AC_OP_UPDATE, data + 6);
  859         acl_to_ac(file, SC_AC_OP_WRITE, data + 8);
  860         acl_to_ac(file, SC_AC_OP_READ, data + 10);
  861     }
  862 
  863     apdu.data = data;
  864     apdu.datalen = datalen;
  865     apdu.lc = datalen;
  866 
  867     if (priv->key_set) {
  868         apdu.cla = 0x84;
  869         apdu.cse = SC_APDU_CASE_4_SHORT;
  870         r = gpk_compute_crycks(card, &apdu, crycks);
  871         if (r)
  872             return r;
  873         apdu.resp = resp;
  874         apdu.resplen = sizeof(resp); /* XXX? */
  875     }
  876 
  877     r = sc_transmit_apdu(card, &apdu);
  878     LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
  879     r = sc_check_sw(card, apdu.sw1, apdu.sw2);
  880     LOG_TEST_RET(card->ctx, r, "Card returned error");
  881 
  882     /* verify secure messaging response */
  883     if (priv->key_set)
  884         r = gpk_verify_crycks(card, &apdu, crycks);
  885 
  886     return r;
  887 }
  888 
  889 /*
  890  * Set the secure messaging key following a Select FileKey
  891  */
  892 static int
  893 gpk_set_filekey(const u8 *key, const u8 *challenge,
  894         const u8 *r_rn, u8 *kats)
  895 {
  896     int         r = SC_SUCCESS, outl;
  897     EVP_CIPHER_CTX      * ctx = NULL;
  898     u8                      out[16];
  899 
  900     memcpy(out, key+8, 8);
  901     memcpy(out+8, key, 8);
  902 
  903     ctx = EVP_CIPHER_CTX_new();
  904     if (ctx == NULL)
  905         return SC_ERROR_INTERNAL;
  906 
  907     EVP_EncryptInit_ex(ctx, EVP_des_ede(), NULL, key, NULL);
  908     if (!EVP_EncryptUpdate(ctx, kats, &outl, r_rn+4, 8))
  909         r = SC_ERROR_INTERNAL;
  910 
  911     if (!EVP_CIPHER_CTX_cleanup(ctx))
  912         r = SC_ERROR_INTERNAL;
  913     if (r == SC_SUCCESS) {
  914         EVP_CIPHER_CTX_init(ctx);
  915         EVP_EncryptInit_ex(ctx, EVP_des_ede(), NULL, out, NULL);
  916         if (!EVP_EncryptUpdate(ctx, kats+8, &outl, r_rn+4, 8))
  917             r = SC_ERROR_INTERNAL;
  918     if (!EVP_CIPHER_CTX_cleanup(ctx))
  919         r = SC_ERROR_INTERNAL;
  920     }
  921     memset(out, 0, sizeof(out));
  922 
  923     /* Verify Cryptogram presented by the card terminal
  924      * XXX: what is the appropriate error code to return
  925      * here? INVALID_ARGS doesn't seem quite right
  926      */
  927     if (r == SC_SUCCESS) {
  928         EVP_CIPHER_CTX_init(ctx);
  929         EVP_EncryptInit_ex(ctx, EVP_des_ede(), NULL, kats, NULL);
  930         if (!EVP_EncryptUpdate(ctx, out, &outl, challenge, 8))
  931             r = SC_ERROR_INTERNAL;
  932         if (memcmp(r_rn, out+4, 4) != 0)
  933             r = SC_ERROR_INVALID_ARGUMENTS;
  934     }
  935 
  936     if (ctx)
  937         EVP_CIPHER_CTX_free(ctx);
  938 
  939     sc_mem_clear(out, sizeof(out));
  940     return r;
  941 }
  942 
  943 /*
  944  * Verify a key presented by the user for secure messaging
  945  */
  946 static int
  947 gpk_select_key(sc_card_t *card, int key_sfi, const u8 *buf, size_t buflen)
  948 {
  949     struct gpk_private_data *priv = DRVDATA(card);
  950     sc_apdu_t   apdu;
  951     u8      rnd[8], resp[258];
  952     int     r;
  953 
  954     SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
  955 
  956     if (buflen != 16)
  957         return SC_ERROR_INVALID_ARGUMENTS;
  958 
  959     /* now do the SelFk */
  960     RAND_bytes(rnd, sizeof(rnd));
  961     memset(&apdu, 0, sizeof(apdu));
  962     apdu.cla = 0x80;
  963     apdu.cse = SC_APDU_CASE_4_SHORT;
  964     apdu.ins = 0x28;
  965     apdu.p1  = 0;
  966     apdu.p2  = key_sfi;
  967     apdu.data = rnd;
  968     apdu.datalen = sizeof(rnd);
  969     apdu.lc = apdu.datalen;
  970     apdu.resp = resp;
  971     apdu.resplen = sizeof(resp);
  972     apdu.le = 12;
  973     
  974     r = sc_transmit_apdu(card, &apdu);
  975     LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
  976     r = sc_check_sw(card, apdu.sw1, apdu.sw2);
  977     LOG_TEST_RET(card->ctx, r, "Card returned error");
  978 
  979     if (apdu.resplen != 12) {
  980         r = SC_ERROR_UNKNOWN_DATA_RECEIVED;
  981     } else
  982     if ((r = gpk_set_filekey(buf, rnd, resp, priv->key)) == 0) {
  983         priv->key_set = 1;
  984         priv->key_reference = key_sfi;
  985     }
  986 
  987     sc_mem_clear(resp, sizeof(resp));
  988     return r;
  989 }
  990 
  991 /*
  992  * Select a security environment (Set Crypto Context in GPK docs).
  993  * When we get here, the PK file has already been selected.
  994  *
  995  * Issue: the GPK distinguishes between "signing" and
  996  * "card internal authentication". I don't know whether this
  997  * makes any difference in practice...
  998  *
  999  * Issue: it seems that sc_compute_signature() does not hash
 1000  * the data for the caller. So what is the purpose of HASH_SHA
 1001  * and other flags?
 1002  */
 1003 static int
 1004 gpk_set_security_env(sc_card_t *card,
 1005         const sc_security_env_t *env,
 1006         int se_num)
 1007 {
 1008     struct gpk_private_data *priv = DRVDATA(card);
 1009     sc_apdu_t   apdu;
 1010     unsigned int    context, algorithm;
 1011     unsigned int    file_id;
 1012     u8      sysrec[7];
 1013     int     r;
 1014 
 1015     /* According to several sources from GemPlus, they don't
 1016      * have off the shelf cards that do DSA. So I won't bother
 1017      * with implementing this stuff here. */
 1018     algorithm = SC_ALGORITHM_RSA;
 1019     if (env->flags & SC_SEC_ENV_ALG_PRESENT)
 1020         algorithm = env->algorithm;
 1021     if (algorithm != SC_ALGORITHM_RSA) {
 1022         sc_log(card->ctx,  "Algorithm not supported.\n");
 1023         return SC_ERROR_NOT_SUPPORTED;
 1024     }
 1025     priv->sec_algorithm = algorithm;
 1026 
 1027     /* If there's a key reference, it must be 0 */
 1028     if ((env->flags & SC_SEC_ENV_KEY_REF_PRESENT)
 1029      && (env->key_ref_len != 1 || env->key_ref[0] != 0)) {
 1030         sc_log(card->ctx,  "Unknown key referenced.\n");
 1031         return SC_ERROR_NOT_SUPPORTED;
 1032     }
 1033 
 1034     /* Right now, the OpenSC flags do not support any padding
 1035      * other than PKCS#1. */
 1036     if (env->flags & SC_ALGORITHM_RSA_PAD_PKCS1)
 1037         priv->sec_padding = 0;
 1038     else if (env->flags & SC_ALGORITHM_RSA_PAD_ANSI)
 1039         priv->sec_padding = 1;
 1040     else if (env->flags & SC_ALGORITHM_RSA_PAD_ISO9796)
 1041         priv->sec_padding = 2;
 1042     else {
 1043         sc_log(card->ctx,  "Padding algorithm not supported.\n");
 1044         return SC_ERROR_NOT_SUPPORTED;
 1045     }
 1046 
 1047     switch (env->operation) {
 1048     case SC_SEC_OPERATION_SIGN:
 1049         /* Again, the following may not make any difference
 1050          * because we don't do any hashing on-card. But
 1051          * what the hell, we have all those nice macros,
 1052          * so why not use them :) 
 1053          */
 1054         if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1) {
 1055             context = GPK_SIGN_RSA_SHA;
 1056             priv->sec_hash_len = 20;
 1057         } else
 1058         if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_MD5_SHA1) {
 1059             context = GPK_SIGN_RSA_SSL;
 1060             priv->sec_hash_len = 36;
 1061         } else
 1062         if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_MD5) {
 1063             context = GPK_SIGN_RSA_MD5;
 1064             priv->sec_hash_len = 16;
 1065         } else {
 1066             sc_log(card->ctx,  "Unsupported signature algorithm");
 1067             return SC_ERROR_NOT_SUPPORTED;
 1068         }
 1069         break;
 1070     case SC_SEC_OPERATION_DECIPHER:
 1071         context = GPK_UNWRAP_RSA;
 1072         break;
 1073     default:
 1074         sc_log(card->ctx,  "Crypto operation not supported.\n");
 1075         return SC_ERROR_NOT_SUPPORTED;
 1076     }
 1077 
 1078     /* Get the file ID */
 1079     if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT) {
 1080         if (env->file_ref.len != 2) {
 1081             sc_log(card->ctx,  "File reference: invalid length.\n");
 1082             return SC_ERROR_INVALID_ARGUMENTS;
 1083         }
 1084         file_id = (env->file_ref.value[0] << 8)
 1085             | env->file_ref.value[1];
 1086     } else {
 1087         sc_log(card->ctx,  "File reference missing.\n");
 1088         return SC_ERROR_INVALID_ARGUMENTS;
 1089     }
 1090 
 1091     /* Select the PK file. The caller has already selected
 1092      * the DF. */
 1093     r = gpk_select_id(card, GPK_SEL_EF, file_id, NULL);
 1094     LOG_TEST_RET(card->ctx, r, "Failed to select PK file");
 1095 
 1096     /* Read the sys record of the PK file to find out the key length */
 1097     r = sc_read_record(card, 1, sysrec, sizeof(sysrec),
 1098             SC_RECORD_BY_REC_NR);
 1099     LOG_TEST_RET(card->ctx, r, "Failed to read PK sysrec");
 1100     if (r != 7 || sysrec[0] != 0) {
 1101         sc_log(card->ctx,  "First record of file is not the sysrec");
 1102         return SC_ERROR_OBJECT_NOT_VALID;
 1103     }
 1104     if (sysrec[5] != 0x00) {
 1105         sc_log(card->ctx,  "Public key is not an RSA key");
 1106         return SC_ERROR_OBJECT_NOT_VALID;
 1107     }
 1108     switch (sysrec[1]) {
 1109     case 0x00: priv->sec_mod_len =  512 / 8; break;
 1110     case 0x10: priv->sec_mod_len =  768 / 8; break;
 1111     case 0x11: priv->sec_mod_len = 1024 / 8; break;
 1112     default:
 1113         sc_log(card->ctx,  "Unsupported modulus length");
 1114         return SC_ERROR_OBJECT_NOT_VALID;
 1115     }
 1116 
 1117     /* Now do SelectCryptoContext */
 1118     memset(&apdu, 0, sizeof(apdu));
 1119     apdu.cse = SC_APDU_CASE_1;
 1120     apdu.cla = 0x80;
 1121     apdu.ins = 0xA6;
 1122     apdu.p1  = file_id & 0x1f;
 1123     apdu.p2  = context;
 1124 
 1125     r = sc_transmit_apdu(card, &apdu);
 1126     LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
 1127     r = sc_check_sw(card, apdu.sw1, apdu.sw2);
 1128     LOG_TEST_RET(card->ctx, r, "Card returned error");
 1129 
 1130     return r;
 1131 }
 1132 
 1133 /*
 1134  * Restore security environment
 1135  * Not sure what this is supposed to do.
 1136  */
 1137 static int
 1138 gpk_restore_security_env(sc_card_t *card, int se_num)
 1139 {
 1140     return 0;
 1141 }
 1142 
 1143 /*
 1144  * Revert buffer (needed for all GPK crypto operations because
 1145  * they want LSB byte order internally
 1146  */
 1147 static int
 1148 reverse(u8 *out, size_t outlen, const u8 *in, size_t inlen)
 1149 {
 1150     if (inlen > outlen)
 1151         return SC_ERROR_BUFFER_TOO_SMALL;
 1152     outlen = inlen;
 1153     while (inlen--)
 1154         *out++ = in[inlen];
 1155     return outlen;
 1156 }
 1157 
 1158 /*
 1159  * Use the card's on-board hashing functions to hash some data
 1160  */
 1161 #ifdef dontuse
 1162 static int
 1163 gpk_hash(sc_card_t *card, const u8 *data, size_t datalen)
 1164 {
 1165     sc_apdu_t   apdu;
 1166     unsigned int    count, chain, len;
 1167     int     r;
 1168 
 1169     chain = 0x01;
 1170     for (count = 0; count < datalen; count += len) {
 1171         unsigned char   buffer[GPK_HASH_CHUNK+2];
 1172 
 1173         if ((len = datalen - count) > GPK_HASH_CHUNK)
 1174             len = GPK_HASH_CHUNK;
 1175         else
 1176             chain |= 0x10;
 1177         buffer[0] = 0x55;
 1178         buffer[1] = len;
 1179         memcpy(buffer+2, data + count, len);
 1180 
 1181         memset(&apdu, 0, sizeof(apdu));
 1182         apdu.cse = SC_APDU_CASE_3_SHORT;
 1183         apdu.cla = 0x80;
 1184         apdu.ins = 0xDA;
 1185         apdu.p1  = chain;
 1186         apdu.p2  = len;
 1187         apdu.lc  = len + 2;
 1188         apdu.data= buffer;
 1189         apdu.datalen = len + 2;
 1190 
 1191         r = sc_transmit_apdu(card, &apdu);
 1192         LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
 1193         r = sc_check_sw(card, apdu.sw1, apdu.sw2);
 1194         LOG_TEST_RET(card->ctx, r, "Card returned error");
 1195         chain = 0;
 1196     }
 1197 
 1198     return 0;
 1199 }
 1200 #endif
 1201 
 1202 /*
 1203  * Send the hashed data to the card.
 1204  */
 1205 static int
 1206 gpk_init_hashed(sc_card_t *card, const u8 *digest, unsigned int len)
 1207 {
 1208     sc_apdu_t   apdu;
 1209     u8      tsegid[64];
 1210     int     r;
 1211 
 1212     r = reverse(tsegid, sizeof(tsegid), digest, len);
 1213     LOG_TEST_RET(card->ctx, r, "Failed to reverse buffer");
 1214 
 1215     memset(&apdu, 0, sizeof(apdu));
 1216     apdu.cse = SC_APDU_CASE_3_SHORT;
 1217     apdu.cla = 0x80;
 1218     apdu.ins = 0xEA;
 1219     apdu.lc  = len;
 1220     apdu.data= tsegid;
 1221     apdu.datalen = len;
 1222 
 1223     r = sc_transmit_apdu(card, &apdu);
 1224     LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
 1225     r = sc_check_sw(card, apdu.sw1, apdu.sw2);
 1226     LOG_TEST_RET(card->ctx, r, "Card returned error");
 1227 
 1228     return r;
 1229 }
 1230 
 1231 /*
 1232  * Compute a signature.
 1233  * Note we hash everything manually and send it to the card.
 1234  */
 1235 static int
 1236 gpk_compute_signature(sc_card_t *card, const u8 *data,
 1237         size_t data_len, u8 * out, size_t outlen)
 1238 {
 1239     struct gpk_private_data *priv = DRVDATA(card);
 1240     sc_apdu_t   apdu;
 1241     u8      cardsig[1024/8];
 1242     int     r;
 1243 
 1244     if (data_len > priv->sec_mod_len) {
 1245         sc_log(card->ctx, 
 1246              "Data length (%"SC_FORMAT_LEN_SIZE_T"u) does not match key modulus %u.\n",
 1247              data_len, priv->sec_mod_len);
 1248         return SC_ERROR_INTERNAL;
 1249     }
 1250     if (sizeof(cardsig) < priv->sec_mod_len)
 1251         return SC_ERROR_BUFFER_TOO_SMALL;
 1252 
 1253     r = gpk_init_hashed(card, data, data_len);
 1254     LOG_TEST_RET(card->ctx, r, "Failed to send hash to card");
 1255 
 1256     /* Now sign the hash.
 1257      * The GPK has Internal Authenticate and PK_Sign. I am not
 1258      * sure what the difference between the two is. */
 1259     memset(&apdu, 0, sizeof(apdu));
 1260     apdu.cse = SC_APDU_CASE_2_SHORT;
 1261     apdu.cla = 0x80;
 1262     apdu.ins = 0x86;
 1263     apdu.p2  = priv->sec_padding;
 1264     apdu.resp= cardsig;
 1265     apdu.resplen = sizeof(cardsig);
 1266     apdu.le  = priv->sec_mod_len;
 1267 
 1268     r = sc_transmit_apdu(card, &apdu);
 1269     LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
 1270     r = sc_check_sw(card, apdu.sw1, apdu.sw2);
 1271     LOG_TEST_RET(card->ctx, r, "Card returned error");
 1272 
 1273     /* The GPK returns the signature as little endian numbers.
 1274      * Need to revert these */
 1275     r = reverse(out, outlen, cardsig, apdu.resplen);
 1276     LOG_TEST_RET(card->ctx, r, "Failed to reverse signature");
 1277 
 1278     return r;
 1279 }
 1280 
 1281 /*
 1282  * Decrypt some RSA encrypted piece of data.
 1283  * Due to legal restrictions, the GPK will not let you see the
 1284  * full cleartext block, just the last N bytes.
 1285  * The GPK documentation refers to N as the MaxSessionKey size,
 1286  * probably because this feature limits the maximum size of an
 1287  * SSL session key you will be able to decrypt using this card.
 1288  */
 1289 static int
 1290 gpk_decipher(sc_card_t *card, const u8 *in, size_t inlen,
 1291         u8 *out, size_t outlen)
 1292 {
 1293     struct gpk_private_data *priv = DRVDATA(card);
 1294     sc_apdu_t   apdu;
 1295     u8      buffer[256];
 1296     int     r;
 1297 
 1298     if (inlen != priv->sec_mod_len) {
 1299         sc_log(card->ctx, 
 1300              "Data length (%"SC_FORMAT_LEN_SIZE_T"u) does not match key modulus %u.\n",
 1301              inlen, priv->sec_mod_len);
 1302         return SC_ERROR_INVALID_ARGUMENTS;
 1303     }
 1304 
 1305     /* First revert the cryptogram */
 1306     r = reverse(buffer, sizeof(buffer), in, inlen);
 1307     LOG_TEST_RET(card->ctx, r, "Cryptogram too large");
 1308     in = buffer;
 1309 
 1310     sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x1C, 0x00, 0x00);
 1311     apdu.cla |= 0x80;
 1312     apdu.lc   = inlen;
 1313     apdu.data = in;
 1314     apdu.datalen = inlen;
 1315     apdu.le   = 256;        /* give me all you got :) */
 1316     apdu.resp = buffer;
 1317     apdu.resplen = sizeof(buffer);
 1318 
 1319     r = sc_transmit_apdu(card, &apdu);
 1320     LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
 1321     r = sc_check_sw(card, apdu.sw1, apdu.sw2);
 1322     LOG_TEST_RET(card->ctx, r, "Card returned error");
 1323 
 1324     /* Reverse the data we got back */
 1325     r = reverse(out, outlen, buffer, apdu.resplen);
 1326     LOG_TEST_RET(card->ctx, r, "Failed to reverse buffer");
 1327 
 1328     return r;
 1329 }
 1330 
 1331 /*
 1332  * Erase card
 1333  */
 1334 static int
 1335 gpk_erase_card(sc_card_t *card)
 1336 {
 1337     struct gpk_private_data *priv = DRVDATA(card);
 1338     sc_apdu_t   apdu;
 1339     u8      offset;
 1340     int     r;
 1341 
 1342     SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
 1343     switch (card->type) {
 1344     case SC_CARD_TYPE_GPK_GPK4000_su256:
 1345     case SC_CARD_TYPE_GPK_GPK4000_sdo:
 1346         offset = 0x6B;  /* courtesy gemplus hotline */
 1347         break;
 1348 
 1349     case SC_CARD_TYPE_GPK_GPK4000_s:
 1350         offset = 7;
 1351         break;
 1352 
 1353     case SC_CARD_TYPE_GPK_GPK8000:
 1354     case SC_CARD_TYPE_GPK_GPK8000_8K:
 1355     case SC_CARD_TYPE_GPK_GPK8000_16K:
 1356     case SC_CARD_TYPE_GPK_GPK16000:
 1357         offset = 0;
 1358         break;
 1359 
 1360     default:
 1361         return SC_ERROR_NOT_SUPPORTED;
 1362     }
 1363 
 1364     memset(&apdu, 0, sizeof(apdu));
 1365     apdu.cse = SC_APDU_CASE_1;
 1366     apdu.cla = 0xDB;
 1367     apdu.ins = 0xDE;
 1368     apdu.p2  = offset;
 1369 
 1370     r = sc_transmit_apdu(card, &apdu);
 1371     LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
 1372     r = sc_check_sw(card, apdu.sw1, apdu.sw2);
 1373     LOG_TEST_RET(card->ctx, r, "Card returned error");
 1374 
 1375     priv->key_set = 0;
 1376     SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
 1377 }
 1378 
 1379 /*
 1380  * Lock a file Access Condition.
 1381  *
 1382  * File must be selected, and we assume that any authentication
 1383  * that needs to be presented in order to allow this operation
 1384  * have been presented (ACs from the DF; AC1 for sensitive files,
 1385  * AC2 for normal files).
 1386  */
 1387 static int
 1388 gpk_lock(sc_card_t *card, struct sc_cardctl_gpk_lock *args)
 1389 {
 1390     struct gpk_private_data *priv = DRVDATA(card);
 1391     sc_file_t   *file = args->file;
 1392     sc_apdu_t   apdu;
 1393     u8      data[8], crycks[3], resp[3];
 1394     int     r;
 1395 
 1396     sc_log(card->ctx, 
 1397         "gpk_lock(0x%04X, %u)\n", file->id, args->operation);
 1398 
 1399     memset(data, 0, sizeof(data));
 1400     data[0] = file->id >> 8;
 1401     data[1] = file->id;
 1402     switch (args->operation) {
 1403     case SC_AC_OP_UPDATE:
 1404         data[2] = 0x40; break;
 1405     case SC_AC_OP_WRITE:
 1406         data[3] = 0x40; break;
 1407     case SC_AC_OP_READ:
 1408         data[4] = 0x40; break;
 1409     default:
 1410         return SC_ERROR_INVALID_ARGUMENTS;
 1411     }
 1412 
 1413     memset(&apdu, 0, sizeof(apdu));
 1414     apdu.cse = SC_APDU_CASE_3_SHORT;
 1415     apdu.cla = 0x80;
 1416     apdu.ins = 0x16;
 1417     apdu.p1  = (file->type == SC_FILE_TYPE_DF)? 1 : 2;
 1418     apdu.p2  = 0;
 1419     apdu.lc  = 5;
 1420     apdu.datalen = 5;
 1421     apdu.data = data;
 1422 
 1423     if (priv->key_set) {
 1424         apdu.cla = 0x84;
 1425         apdu.cse = SC_APDU_CASE_4_SHORT;
 1426         r = gpk_compute_crycks(card, &apdu, crycks);
 1427         if (r)
 1428             return r;
 1429         apdu.resp = resp;
 1430         apdu.resplen = sizeof(resp); /* XXX? */
 1431     }
 1432 
 1433     r = sc_transmit_apdu(card, &apdu);
 1434     LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
 1435     r = sc_check_sw(card, apdu.sw1, apdu.sw2);
 1436     LOG_TEST_RET(card->ctx, r, "Card returned error");
 1437 
 1438     if (priv->key_set)
 1439         r = gpk_verify_crycks(card, &apdu, crycks);
 1440 
 1441     return r;
 1442 }
 1443 
 1444 /*
 1445  * Initialize the private portion of a public key file
 1446  */
 1447 static int
 1448 gpk_pkfile_init(sc_card_t *card, struct sc_cardctl_gpk_pkinit *args)
 1449 {
 1450     sc_apdu_t   apdu;
 1451     int     r;
 1452 
 1453     sc_log(card->ctx, 
 1454         "gpk_pkfile_init(%u)\n", args->privlen);
 1455 
 1456     memset(&apdu, 0, sizeof(apdu));
 1457     apdu.cse = SC_APDU_CASE_1;
 1458     apdu.cla = 0x80;
 1459     apdu.ins = 0x12;
 1460     apdu.p1  = args->file->id & 0x1F;
 1461     apdu.p2  = args->privlen / 4;
 1462 
 1463     r = sc_transmit_apdu(card, &apdu);
 1464     LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
 1465     r = sc_check_sw(card, apdu.sw1, apdu.sw2);
 1466     LOG_TEST_RET(card->ctx, r, "Card returned error");
 1467 
 1468     return r;
 1469 }
 1470 
 1471 /*
 1472  * Initialize the private portion of a public key file
 1473  */
 1474 static int
 1475 gpk_generate_key(sc_card_t *card, struct sc_cardctl_gpk_genkey *args)
 1476 {
 1477     sc_apdu_t   apdu;
 1478     int     r;
 1479     u8      buffer[256];
 1480 
 1481     sc_log(card->ctx, 
 1482         "gpk_generate_key(%u)\n", args->privlen);
 1483     if (args->privlen != 512 && args->privlen != 1024) {
 1484         sc_log(card->ctx, 
 1485             "Key generation not supported for key length %d",
 1486             args->privlen);
 1487         return SC_ERROR_NOT_SUPPORTED;
 1488     }
 1489 
 1490     memset(&apdu, 0, sizeof(apdu));
 1491     apdu.cse = SC_APDU_CASE_2_SHORT;
 1492     apdu.cla = 0x80;
 1493     apdu.ins = 0xD2;
 1494     apdu.p1  = 0x80 | (args->fid & 0x1F);
 1495     apdu.p2  = (args->privlen == 1024) ? 0x11 : 0;
 1496     apdu.le  = args->privlen / 8 + 2;
 1497     apdu.resp = buffer;
 1498     apdu.resplen = 256;
 1499 
 1500     r = sc_transmit_apdu(card, &apdu);
 1501     LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
 1502     r = sc_check_sw(card, apdu.sw1, apdu.sw2);
 1503     LOG_TEST_RET(card->ctx, r, "Card returned error");
 1504 
 1505     /* Return the public key, inverted.
 1506      * The first two bytes must be stripped off. */
 1507     if (args->pubkey_len && apdu.resplen > 2) {
 1508         r = reverse(args->pubkey, args->pubkey_len,
 1509                 buffer + 2, apdu.resplen - 2);
 1510         LOG_TEST_RET(card->ctx, r, "Failed to reverse buffer");
 1511         args->pubkey_len = r;
 1512     }
 1513 
 1514     return r;
 1515 }
 1516 
 1517 /*
 1518  * Store a private key component
 1519  */
 1520 static int
 1521 gpk_pkfile_load(sc_card_t *card, struct sc_cardctl_gpk_pkload *args)
 1522 {
 1523     struct gpk_private_data *priv = DRVDATA(card);
 1524     sc_apdu_t   apdu;
 1525     unsigned int    n;
 1526     u8      temp[256];
 1527     int     r = SC_SUCCESS, outl;
 1528     EVP_CIPHER_CTX  * ctx;
 1529 
 1530     sc_log(card->ctx,  "gpk_pkfile_load(fid=%04x, len=%d, datalen=%d)\n",
 1531             args->file->id, args->len, args->datalen);
 1532 
 1533     ctx = EVP_CIPHER_CTX_new();
 1534     if (ctx == NULL)
 1535         return SC_ERROR_INTERNAL;
 1536 
 1537     if (0) {
 1538         sc_log_hex(card->ctx, "Sending (cleartext)",
 1539                 args->data, args->datalen);
 1540     }
 1541 
 1542     memset(&apdu, 0, sizeof(apdu));
 1543     apdu.cse = SC_APDU_CASE_3_SHORT;
 1544     apdu.cla = 0x80;
 1545     apdu.ins = 0x18;
 1546     apdu.p1  = args->file->id & 0x1F;
 1547     apdu.p2  = args->len;
 1548     apdu.lc  = args->datalen;
 1549 
 1550     /* encrypt the private key material */
 1551     assert(args->datalen <= sizeof(temp));
 1552     if (!priv->key_set) {
 1553         sc_log(card->ctx,  "No secure messaging key set!\n");
 1554         return SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
 1555     }
 1556 
 1557     EVP_EncryptInit_ex(ctx, EVP_des_ede(), NULL, priv->key, NULL);
 1558     for (n = 0; n < args->datalen; n += 8) {
 1559         if (!EVP_EncryptUpdate(ctx, temp+n, &outl, args->data + n, 8)) {
 1560             r = SC_ERROR_INTERNAL;
 1561             break;
 1562         }
 1563     }
 1564     if (ctx)
 1565         EVP_CIPHER_CTX_free(ctx);
 1566     if (r != SC_SUCCESS)
 1567         return SC_ERROR_INTERNAL;
 1568 
 1569     apdu.data = temp;
 1570     apdu.datalen = args->datalen;
 1571 
 1572     /* Forget the key. The card seems to forget it, too :) */
 1573     priv->key_set = 0;
 1574 
 1575     r = sc_transmit_apdu(card, &apdu);
 1576     LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
 1577     r = sc_check_sw(card, apdu.sw1, apdu.sw2);
 1578     LOG_TEST_RET(card->ctx, r, "Card returned error");
 1579 
 1580     LOG_FUNC_RETURN(card->ctx, r);
 1581 }
 1582 
 1583 /*
 1584  * This function lets pkcs15init query for the transport key
 1585  */
 1586 static int
 1587 gpk_get_default_key(sc_card_t *card, struct sc_cardctl_default_key *data)
 1588 {
 1589     if (data->method == SC_AC_PRO && data->key_ref == 1) {
 1590         if (data->len < 16)
 1591             return SC_ERROR_BUFFER_TOO_SMALL;
 1592         memcpy(data->key_data, "TEST KEYTEST KEY", 16);
 1593         data->len = 16;
 1594         return 0;
 1595     }
 1596     return SC_ERROR_NO_DEFAULT_KEY;
 1597 }
 1598 
 1599 /*
 1600  * GetInfo call
 1601  */
 1602 static int gpk_get_info(sc_card_t *card, int p1, int p2, u8 *buf,
 1603         size_t buflen)
 1604 {
 1605     sc_apdu_t   apdu;
 1606     int r, retry = 0;
 1607 
 1608     /* We may have to retry the get info command. It
 1609      * returns 6B00 if a previous command returned a 61xx response,
 1610      * but the host failed to collect the results.
 1611      *
 1612      * Note the additional sc_lock/sc_unlock pair, which
 1613      * is required to prevent sc_transmit_apdu from 
 1614      * calling logout(), which in turn does a SELECT MF
 1615      * without collecting the response :)
 1616      */
 1617     r = sc_lock(card);
 1618     LOG_TEST_RET(card->ctx, r, "sc_lock() failed");
 1619 
 1620     do {
 1621         memset(&apdu, 0, sizeof(apdu));
 1622         apdu.cse = SC_APDU_CASE_2_SHORT;
 1623         apdu.cla = 0x80;
 1624         apdu.ins = 0xC0;
 1625         apdu.p1  = p1;
 1626         apdu.p2  = p2;
 1627         apdu.le  = buflen;
 1628         apdu.resp = buf;
 1629         apdu.resplen = buflen;
 1630 
 1631         if ((r = sc_transmit_apdu(card, &apdu)) < 0) {
 1632             sc_log(card->ctx,  "APDU transmit failed: %s",
 1633                     sc_strerror(r));
 1634             sc_unlock(card);
 1635             return r;
 1636         }
 1637     } while (apdu.sw1 == 0x6B && apdu.sw2 == 0x00 && retry++ < 1);
 1638     sc_unlock(card);
 1639 
 1640     r = sc_check_sw(card, apdu.sw1, apdu.sw2);
 1641     LOG_TEST_RET(card->ctx, r, "Card returned error");
 1642 
 1643     return r;
 1644 }
 1645 
 1646 static int gpk_get_serialnr(sc_card_t *card, sc_serial_number_t *serial)
 1647 {
 1648     int r;
 1649     u8  rbuf[10];
 1650     sc_apdu_t apdu;
 1651 
 1652     if (card->type != SC_CARD_TYPE_GPK_GPK16000)
 1653         return SC_ERROR_NOT_SUPPORTED;
 1654 
 1655     if (!serial)
 1656         return SC_ERROR_INVALID_ARGUMENTS;
 1657     /* see if we have cached serial number */
 1658     if (card->serialnr.len) {
 1659         memcpy(serial, &card->serialnr, sizeof(*serial));
 1660         return SC_SUCCESS;
 1661     }
 1662     /* get serial number via Get CSN */
 1663     sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xb8, 0x00, 0x00);
 1664     apdu.cla |= 0x80;
 1665     apdu.resp = rbuf;
 1666     apdu.resplen = sizeof(rbuf);
 1667     apdu.le   = 8;
 1668     apdu.lc   = 0;
 1669     apdu.datalen = 0;
 1670         r = sc_transmit_apdu(card, &apdu);
 1671     LOG_TEST_RET(card->ctx, r, "APDU transmit failed");
 1672     if (apdu.sw1 != 0x90 || apdu.sw2 != 0x00)
 1673         return SC_ERROR_INTERNAL;
 1674     /* cache serial number */
 1675     memcpy(card->serialnr.value, apdu.resp, apdu.resplen);
 1676     card->serialnr.len = apdu.resplen;
 1677     /* copy and return serial number */
 1678     memcpy(serial, &card->serialnr, sizeof(*serial));
 1679     return SC_SUCCESS;
 1680 }
 1681 
 1682 /*
 1683  * Dispatch card_ctl calls
 1684  */
 1685 static int
 1686 gpk_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
 1687 {
 1688     switch (cmd) {
 1689     case SC_CARDCTL_ERASE_CARD:
 1690         return gpk_erase_card(card);
 1691     case SC_CARDCTL_GET_DEFAULT_KEY:
 1692         return gpk_get_default_key(card,
 1693                 (struct sc_cardctl_default_key *) ptr);
 1694     case SC_CARDCTL_GPK_VARIANT:
 1695         *(int *) ptr = card->type;
 1696         return 0;
 1697     case SC_CARDCTL_GPK_LOCK:
 1698         return gpk_lock(card, (struct sc_cardctl_gpk_lock *) ptr);
 1699     case SC_CARDCTL_GPK_PKINIT:
 1700         return gpk_pkfile_init(card,
 1701                    (struct sc_cardctl_gpk_pkinit *) ptr);
 1702     case SC_CARDCTL_GPK_PKLOAD:
 1703         return gpk_pkfile_load(card,
 1704                    (struct sc_cardctl_gpk_pkload *) ptr);
 1705     case SC_CARDCTL_GPK_IS_LOCKED:
 1706         *(int *) ptr = DRVDATA(card)->locked;
 1707         return 0;
 1708     case SC_CARDCTL_GPK_GENERATE_KEY:
 1709         return gpk_generate_key(card,
 1710                 (struct sc_cardctl_gpk_genkey *) ptr);
 1711     case SC_CARDCTL_GET_SERIALNR:
 1712         return gpk_get_serialnr(card, (sc_serial_number_t *) ptr);
 1713     }
 1714 
 1715 
 1716     return SC_ERROR_NOT_SUPPORTED;
 1717 }
 1718 
 1719 static int
 1720 gpk_build_pin_apdu(sc_card_t *card, sc_apdu_t *apdu, struct sc_pin_cmd_data *data)
 1721 {
 1722     static u8   sbuf[8];
 1723     int     r;
 1724 
 1725     if (data->pin_type != SC_AC_CHV)
 1726         return SC_ERROR_INVALID_ARGUMENTS;
 1727 
 1728     /* XXX deal with secure messaging here */
 1729     memset(apdu, 0, sizeof(*apdu));
 1730     apdu->cse   = SC_APDU_CASE_3_SHORT;
 1731 
 1732     data->flags |= SC_PIN_CMD_NEED_PADDING;
 1733 
 1734     switch (data->cmd) {
 1735     case SC_PIN_CMD_VERIFY:
 1736         /* Copy PIN to buffer and pad */
 1737         data->pin1.encoding = SC_PIN_ENCODING_ASCII;
 1738         data->pin1.pad_length = 8;
 1739         data->pin1.pad_char = 0x00;
 1740         data->pin1.offset = 5;
 1741         r = sc_build_pin(sbuf, 8, &data->pin1, 1);
 1742         if (r < 0)
 1743             return r;
 1744 
 1745         apdu->cla = 0x00;
 1746         apdu->ins = 0x20;
 1747         apdu->p1  = 0x00;
 1748         break;
 1749     case SC_PIN_CMD_CHANGE:
 1750     case SC_PIN_CMD_UNBLOCK:
 1751         /* Copy PINs to buffer, BCD-encoded, and pad */
 1752         data->pin1.encoding = SC_PIN_ENCODING_BCD;
 1753         data->pin1.pad_length = 8;
 1754         data->pin1.pad_char = 0x00;
 1755         data->pin1.offset = 5;
 1756         data->pin2.encoding = SC_PIN_ENCODING_BCD;
 1757         data->pin2.pad_length = 8;
 1758         data->pin2.pad_char = 0x00;
 1759         data->pin2.offset = 5 + 4;
 1760         if ((r = sc_build_pin(sbuf, 4, &data->pin1, 1)) < 0
 1761          || (r = sc_build_pin(sbuf + 4, 4, &data->pin2, 1)) < 0)
 1762             return r;
 1763 
 1764         apdu->cla = 0x80;
 1765         apdu->ins = 0x24;
 1766         apdu->p1  = (data->cmd == SC_PIN_CMD_CHANGE)? 0x00 : 0x01;
 1767         break;
 1768     default:
 1769         return SC_ERROR_NOT_SUPPORTED;
 1770     }
 1771 
 1772     apdu->p2    = data->pin_reference & 7;
 1773     apdu->lc    = 8;
 1774     apdu->datalen   = 8;
 1775     apdu->data  = sbuf;
 1776 
 1777     return 0;
 1778 }
 1779 
 1780 static int
 1781 gpk_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left)
 1782 {
 1783     sc_apdu_t apdu;
 1784     int r;
 1785 
 1786     /* Special case - External Authenticate */
 1787     if (data->cmd == SC_PIN_CMD_VERIFY
 1788      && data->pin_type == SC_AC_PRO)
 1789         return gpk_select_key(card,
 1790                 data->pin_reference,
 1791                 data->pin1.data,
 1792                 data->pin1.len);
 1793 
 1794     r = gpk_build_pin_apdu(card, &apdu, data);
 1795     if (r < 0)
 1796         return r;
 1797 
 1798     data->apdu = &apdu;
 1799 
 1800     r = iso_ops->pin_cmd(card, data, tries_left);
 1801 
 1802     data->apdu = NULL;
 1803     return r;
 1804 }
 1805 
 1806 /*
 1807  * Initialize the driver struct
 1808  */
 1809 static struct sc_card_driver *
 1810 sc_get_driver(void)
 1811 {
 1812     struct sc_card_driver *iso_drv;
 1813 
 1814     iso_drv = sc_get_iso7816_driver();
 1815     iso_ops = iso_drv->ops;
 1816     gpk_ops = *iso_ops;
 1817 
 1818     gpk_ops.match_card  = gpk_match_card;
 1819     gpk_ops.init        = gpk_init;
 1820     gpk_ops.finish      = gpk_finish;
 1821     gpk_ops.select_file = gpk_select_file;
 1822     gpk_ops.read_binary = gpk_read_binary;
 1823     gpk_ops.write_binary    = gpk_write_binary;
 1824     gpk_ops.update_binary   = gpk_update_binary;
 1825     gpk_ops.create_file = gpk_create_file;
 1826     /* gpk_ops.check_sw = gpk_check_sw; */
 1827     gpk_ops.card_ctl    = gpk_card_ctl;
 1828     gpk_ops.set_security_env= gpk_set_security_env;
 1829     gpk_ops.restore_security_env= gpk_restore_security_env;
 1830     gpk_ops.compute_signature= gpk_compute_signature;
 1831     gpk_ops.decipher    = gpk_decipher;
 1832     gpk_ops.pin_cmd     = gpk_pin_cmd;
 1833 
 1834     return &gpk_drv;
 1835 }
 1836 
 1837 struct sc_card_driver *
 1838 sc_get_gpk_driver(void)
 1839 {
 1840     return sc_get_driver();
 1841 }
 1842 #endif /* ENABLE_OPENSSL */