Coverage Report

Created: 2026-11-30 06:17

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/opensc/src/libopensc/cwa14890.c
Line
Count
Source
1
/**
2
 * cwa14890.c: Implementation of Secure Messaging according CWA-14890-1 and CWA-14890-2 standards.
3
 *
4
 * Copyright (C) 2010 Juan Antonio Martinez <jonsito@terra.es>
5
 *
6
 * This work is derived from many sources at OpenSC Project site,
7
 * (see references) and the information made public by Spanish
8
 * Direccion General de la Policia y de la Guardia Civil
9
 *
10
 * This library is free software; you can redistribute it and/or
11
 * modify it under the terms of the GNU Lesser General Public
12
 * License as published by the Free Software Foundation; either
13
 * version 2.1 of the License, or (at your option) any later version.
14
 *
15
 * This library is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18
 * Lesser General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Lesser General Public
21
 * License along with this library; if not, write to the Free Software
22
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23
 */
24
25
#define __CWA14890_C__
26
#ifdef HAVE_CONFIG_H
27
#include "config.h"
28
#endif
29
30
#if defined(ENABLE_OPENSSL) && defined(ENABLE_SM) /* empty file without openssl or sm */
31
32
#include <stdlib.h>
33
#include <string.h>
34
#include <ctype.h>
35
36
#include "asn1.h"
37
#include "opensc.h"
38
#include "cardctl.h"
39
#include "internal.h"
40
#include <openssl/rsa.h>
41
#include <openssl/bn.h>
42
#include <openssl/x509.h>
43
#include <openssl/des.h>
44
#include <openssl/rand.h>
45
#include "cwa14890.h"
46
#include "cwa-dnie.h"
47
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
48
# include <openssl/core_names.h>
49
# include <openssl/param_build.h>
50
# include <openssl/provider.h>
51
#endif
52
53
0
#define MAX_RESP_BUFFER_SIZE 2048
54
55
/**
56
 * Structure used to compose BER-TLV encoded data
57
 * according to iso7816-4 sect 5.2.2.
58
 *
59
 * Notice that current implementation does not handle properly
60
 * multibyte tag id. Just assume that tag is 1-byte length
61
 * Also, encodings for data length longer than 0x01000000 bytes
62
 * are not supported (tag 0x84)
63
 */
64
typedef struct cwa_tlv_st {
65
        u8 *buf;                /** local copy of TLV byte array */
66
        size_t buflen;          /** length of buffer */
67
        unsigned int tag;       /** tag ID */
68
        size_t len;             /** length of data field */
69
        u8 *data;               /** pointer to start of data in buf buffer */
70
} cwa_tlv_t;
71
72
/*********************** utility functions ************************/
73
74
/**
75
 * Dump an APDU before SM translation.
76
 *
77
 * This is mainly for debugging purposes. programmer should disable
78
 * this function in a production environment, as APDU will be shown
79
 * in text-plain on debug traces
80
 *
81
 * @param card Pointer to card driver data structure
82
 * @param apdu APDU to be encoded, or APDU response after decoded
83
 * @param flag 0: APDU is to be encoded: 1; APDU decoded response
84
 */
85
static void cwa_trace_apdu(sc_card_t * card, sc_apdu_t * apdu, int flag)
86
0
{
87
0
  char buf[2048];
88
0
  if (!card || !card->ctx || !apdu || card->ctx->debug < SC_LOG_DEBUG_NORMAL)
89
0
    return;
90
0
  if (flag == 0) { /* apdu command */
91
0
    if (apdu->datalen > 0) { /* apdu data to show */
92
0
      sc_hex_dump(apdu->data, apdu->datalen, buf, sizeof(buf));
93
0
      sc_log(card->ctx,
94
0
          "\nAPDU before encode: ==================================================\n"
95
0
          "CLA: %02X INS: %02X P1: %02X P2: %02X Lc: %02zX Le: %02zX DATA: [%5zu bytes]\n"
96
0
          "%s======================================================================\n",
97
0
          apdu->cla, apdu->ins, apdu->p1, apdu->p2,
98
0
          apdu->lc, apdu->le, apdu->datalen, buf);
99
0
    } else { /* apdu data field is empty */
100
0
      sc_log(card->ctx,
101
0
          "\nAPDU before encode: ==================================================\n"
102
0
          "CLA: %02X INS: %02X P1: %02X P2: %02X Lc: %02zX Le: %02zX (NO DATA)\n"
103
0
          "======================================================================\n",
104
0
          apdu->cla, apdu->ins, apdu->p1, apdu->p2,
105
0
          apdu->lc, apdu->le);
106
0
    }
107
0
  } else {   /* apdu response */
108
0
    sc_hex_dump(apdu->resp, apdu->resplen, buf, sizeof(buf));
109
0
    sc_log(card->ctx,
110
0
        "\nAPDU response after decode: ==========================================\n"
111
0
        "SW1: %02X SW2: %02X RESP: [%5zu bytes]\n"
112
0
        "%s======================================================================\n",
113
0
        apdu->sw1, apdu->sw2, apdu->resplen, buf);
114
0
  }
115
0
}
116
117
/**
118
 * Increase send sequence counter SSC.
119
 *
120
 * @param card smart card info structure
121
 * @return SC_SUCCESS if ok; else error code
122
 *
123
 * TODO: to further study: what about using bignum arithmetic?
124
 */
125
static int cwa_increase_ssc(sc_card_t * card)
126
0
{
127
0
  int n;
128
0
  struct sm_cwa_session * sm = &card->sm_ctx.info.session.cwa;
129
130
  /* preliminary checks */
131
0
  if (!card || !card->ctx )
132
0
    return SC_ERROR_INVALID_ARGUMENTS;
133
0
  LOG_FUNC_CALLED(card->ctx);
134
  /* u8 arithmetic; exit loop if no carry */
135
0
  sc_log(card->ctx, "Curr SSC: '%s'", sc_dump_hex(sm->ssc, 8));
136
0
  for (n = 7; n >= 0; n--) {
137
0
    sm->ssc[n]++;
138
0
    if ((sm->ssc[n]) != 0x00)
139
0
      break;
140
0
  }
141
0
  sc_log(card->ctx, "Next SSC: '%s'", sc_dump_hex(sm->ssc, 8));
142
0
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
143
0
}
144
145
/**
146
 * ISO 7816 padding.
147
 *
148
 * Adds an 0x80 at the end of buffer and as many zeroes to get len
149
 * multiple of 8
150
 * Buffer must be long enough to store additional bytes
151
 *
152
 * @param buffer where to compose data
153
 * @param len pointer to buffer length
154
 */
155
static void cwa_iso7816_padding(u8 * buf, size_t * buflen)
156
0
{
157
0
  buf[*buflen] = 0x80;
158
0
  (*buflen)++;
159
0
  for (; *buflen & 0x07; (*buflen)++)
160
0
    buf[*buflen] = 0x00;
161
0
}
162
163
/**
164
 * compose a BER-TLV data in provided buffer.
165
 *
166
 * Multibyte tag id are not supported
167
 * Also multibyte id 0x84 is unhandled
168
 *
169
 * Notice that TLV is composed starting at offset length from
170
 * the buffer. Consecutive calls to cwa_add_tlv, appends a new
171
 * TLV at the end of the buffer
172
 *
173
 * @param card card info structure
174
 * @param tag tag id
175
 * @param len data length
176
 * @param value data buffer
177
 * @param out pointer to dest data
178
 * @param outlen length of composed tlv data
179
 * @return SC_SUCCESS if ok; else error
180
 */
181
static int cwa_compose_tlv(sc_card_t * card,
182
         u8 tag,
183
         size_t len, u8 * data, u8 ** out, size_t * outlen)
184
0
{
185
0
  u8 *pt;
186
0
  size_t size;
187
0
  sc_context_t *ctx;
188
  /* preliminary checks */
189
0
  if (!card || !card->ctx || !out || !outlen)
190
0
    return SC_ERROR_INVALID_ARGUMENTS;
191
  /* commodity vars */
192
0
  ctx = card->ctx;
193
194
0
  LOG_FUNC_CALLED(ctx);
195
0
  pt = *out;
196
0
  size = *outlen;
197
198
  /* assume tag id is not multibyte */
199
0
  *(pt + size++) = tag;
200
  /* evaluate tag length value according iso7816-4 sect 5.2.2 */
201
0
  if (len < 0x80) {
202
0
    *(pt + size++) = len;
203
0
  } else if (len < 0x00000100) {
204
0
    *(pt + size++) = 0x81;
205
0
    *(pt + size++) = 0xff & len;
206
0
  } else if (len < 0x00010000) {
207
0
    *(pt + size++) = 0x82;
208
0
    *(pt + size++) = 0xff & (len >> 8);
209
0
    *(pt + size++) = 0xff & len;
210
0
  } else if (len < 0x01000000) {
211
0
    *(pt + size++) = 0x83;
212
0
    *(pt + size++) = 0xff & (len >> 16);
213
0
    *(pt + size++) = 0xff & (len >> 8);
214
0
    *(pt + size++) = 0xff & len;
215
0
  } else {   /* do not handle tag length 0x84 */
216
0
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
217
0
  }
218
  /* copy remaining data to buffer */
219
0
  if (len != 0)
220
0
    memcpy(pt + size, data, len);
221
0
  size += len;
222
0
  *outlen = size;
223
0
  LOG_FUNC_RETURN(ctx, SC_SUCCESS);
224
0
}
225
226
/**
227
 * Parse and APDU Response and extract specific BER-TLV data.
228
 *
229
 * NOTICE that iso7816 sect 5.2.2 states that Tag length may be 1 to n bytes
230
 * length. In this code we'll assume always tag length = 1 byte
231
 *
232
 * FIXME use `sc_asn1_read_tag` or similar instead
233
 *
234
 * @param card card info structure
235
 * @param data Buffer to look for tlv into
236
 * @param datalen Buffer len
237
 * @param tlv  array of TLV structure to store results into
238
 * @return SC_SUCCESS if OK; else error code
239
 */
240
static int cwa_parse_tlv(sc_card_t * card,
241
       u8 * buffer, size_t datalen,
242
       cwa_tlv_t tlv_array[]
243
    )
244
0
{
245
0
  const u8 *p = buffer;
246
0
  size_t left = datalen;
247
0
  sc_context_t *ctx = NULL;
248
249
  /* preliminary checks */
250
0
  if (!card || !card->ctx)
251
0
    return SC_ERROR_INVALID_ARGUMENTS;
252
  /* commodity vars */
253
0
  ctx = card->ctx;
254
255
0
  LOG_FUNC_CALLED(ctx);
256
0
  if (!tlv_array)
257
0
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
258
259
0
  while (left > 0) {
260
0
    unsigned int cla = 0, tag_val = 0;
261
0
    size_t tag_len = 0, header_len;
262
0
    const u8 *tlv_start = p;
263
0
    cwa_tlv_t *tlv = NULL;
264
0
    u8 raw_tag;
265
266
0
    int r = sc_asn1_read_tag(&p, left, &cla, &tag_val, &tag_len);
267
0
    if (r != SC_SUCCESS) {
268
0
      sc_log(ctx, "Failed to parse ASN.1 tag");
269
0
      LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_DATA);
270
0
    }
271
272
0
    header_len = (p - tlv_start);
273
0
    left -= header_len;
274
275
0
    raw_tag = (cla | tag_val);
276
0
    switch (raw_tag) {
277
0
    case CWA_SM_PLAIN_TAG:
278
0
      tlv = &tlv_array[0];
279
0
      break;  /* 0x81 Plain  */
280
0
    case CWA_SM_CRYPTO_TAG:
281
0
      tlv = &tlv_array[1];
282
0
      break;  /* 0x87 Crypto */
283
0
    case CWA_SM_MAC_TAG:
284
0
      tlv = &tlv_array[2];
285
0
      break;  /* 0x8E MAC CC */
286
0
    case CWA_SM_STATUS_TAG:
287
0
      tlv = &tlv_array[3];
288
0
      break;  /* 0x99 Status */
289
0
    default:  /* CWA_SM_LE_TAG (0x97) is not valid here */
290
0
      sc_log(ctx, "Invalid TLV Tag type: '0x%02X'", raw_tag);
291
0
      LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_DATA);
292
0
    }
293
0
    tlv->buf = (u8 *)tlv_start;
294
0
    tlv->tag = raw_tag;
295
0
    tlv->len = tag_len;
296
0
    tlv->data = (u8 *)p;
297
0
    tlv->buflen = header_len + tag_len;
298
0
    sc_log(ctx, "Found Tag: '0x%02X': Length: '%zu' Value:\n%s",
299
0
        tlv->tag, tlv->len, sc_dump_hex(tlv->data, tlv->len));
300
    /* set index to next Tag to jump to */
301
0
    p += tag_len;
302
0
    left -= tag_len;
303
0
  }
304
0
  LOG_FUNC_RETURN(ctx, SC_SUCCESS);  /* mark no error */
305
0
}
306
307
/*********************** authentication routines *******************/
308
309
/**
310
 * Verify certificates provided by card.
311
 *
312
 * This routine uses Root CA public key data From Annex III of manual
313
 * to verify intermediate CA icc certificate provided by card
314
 * if verify success, then extract public keys from intermediate CA
315
 * and verify icc certificate
316
 *
317
 * @param card pointer to sc_card_contex
318
 * @param sub_ca_cert icc intermediate CA certificate read from card
319
 * @param icc_ca icc certificate from card
320
 * @return SC_SUCCESS if verification is ok; else error code
321
 */
322
static int cwa_verify_icc_certificates(sc_card_t * card,
323
               cwa_provider_t * provider,
324
               X509 * sub_ca_cert, X509 * icc_cert)
325
0
{
326
0
  char *msg = NULL;
327
0
  int res = SC_SUCCESS;
328
0
  EVP_PKEY *root_ca_key = NULL;
329
0
  EVP_PKEY *sub_ca_key = NULL;
330
0
  sc_context_t *ctx = NULL;
331
332
  /* safety check */
333
0
  if (!card || !card->ctx || !provider)
334
0
    return SC_ERROR_INVALID_ARGUMENTS;
335
0
  ctx = card->ctx;
336
0
  LOG_FUNC_CALLED(ctx);
337
0
  if (!sub_ca_cert || !icc_cert) /* check received arguments */
338
0
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
339
340
  /* retrieve root ca pkey from provider */
341
0
  if (!provider->cwa_get_root_ca_pubkey) {
342
0
    msg = "No root CA public key provider";
343
0
    res = SC_ERROR_NOT_SUPPORTED;
344
0
    goto verify_icc_certificates_end;
345
0
  }
346
0
  res = provider->cwa_get_root_ca_pubkey(card, &root_ca_key);
347
0
  if (res != SC_SUCCESS) {
348
0
    msg = "Cannot get root CA public key";
349
0
    res = SC_ERROR_INTERNAL;
350
0
    goto verify_icc_certificates_end;
351
0
  }
352
353
  /* verify sub_ca_cert against root_ca_key */
354
0
  res = X509_verify(sub_ca_cert, root_ca_key);
355
0
  if (!res) {
356
0
    sc_log_openssl(ctx);
357
0
    msg = "Cannot verify icc Sub-CA certificate";
358
0
    res = SC_ERROR_SM_AUTHENTICATION_FAILED;
359
0
    goto verify_icc_certificates_end;
360
0
  }
361
362
  /* extract sub_ca_key from sub_ca_cert */
363
0
  if (!(sub_ca_key = X509_get_pubkey(sub_ca_cert))) {
364
0
    sc_log_openssl(ctx);
365
0
    msg = "Cannot extract public key icc Sub-CA certificate";
366
0
    res = SC_ERROR_INTERNAL;
367
0
    goto verify_icc_certificates_end;
368
0
  }
369
370
  /* verify icc_cert against sub_ca_key */
371
0
  res = X509_verify(icc_cert, sub_ca_key);
372
0
  if (!res) {
373
0
    sc_log_openssl(ctx);
374
0
    msg = "Cannot verify icc certificate";
375
0
    res = SC_ERROR_SM_AUTHENTICATION_FAILED;
376
0
    goto verify_icc_certificates_end;
377
0
  }
378
379
  /* arriving here means certificate verification success */
380
0
  res = SC_SUCCESS;
381
0
 verify_icc_certificates_end:
382
0
  if (root_ca_key)
383
0
    EVP_PKEY_free(root_ca_key);
384
0
  if (sub_ca_key)
385
0
    EVP_PKEY_free(sub_ca_key);
386
0
  if (res != SC_SUCCESS) {
387
0
    sc_log(ctx, "%s", msg);
388
0
  }
389
0
  LOG_FUNC_RETURN(ctx, res);
390
0
}
391
392
/**
393
 * Verify CVC certificates in SM establishment process.
394
 *
395
 * This is done by mean of 00 2A 00 AE
396
 * (Perform Security Operation: Verify Certificate )
397
 *
398
 * @param card pointer to card data
399
 * @param cert Certificate in CVC format
400
 * @param len  length of CVC certificate
401
 * @return SC_SUCCESS if ok; else error code
402
 */
403
static int cwa_verify_cvc_certificate(sc_card_t * card,
404
              const u8 * cert, size_t len)
405
0
{
406
0
  sc_apdu_t apdu;
407
0
  int result = SC_SUCCESS;
408
0
  sc_context_t *ctx = NULL;
409
410
  /* safety check */
411
0
  if (!card || !card->ctx)
412
0
    return SC_ERROR_INVALID_ARGUMENTS;
413
0
  ctx = card->ctx;
414
0
  LOG_FUNC_CALLED(ctx);
415
0
  if (!cert || (len <= 0)) /* check received arguments */
416
0
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
417
418
  /* compose apdu for Perform Security Operation (Verify cert) cmd */
419
0
  dnie_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x2A, 0x00, 0xAE, 0, len,
420
0
          NULL, 0, cert, len);
421
422
  /* send composed apdu and parse result */
423
0
  result = sc_transmit_apdu(card, &apdu);
424
0
  LOG_TEST_RET(ctx, result, "Verify CVC certificate failed");
425
0
  result = sc_check_sw(card, apdu.sw1, apdu.sw2);
426
0
  LOG_FUNC_RETURN(ctx, result);
427
0
}
428
429
/**
430
 * Alternate implementation for set_security environment.
431
 *
432
 * Used to handle raw apdu data in set_security_env() on SM establishment
433
 * Standard set_security_env() method has sc_security_env->buffer limited
434
 * to 8 bytes; so cannot send some of required SM commands.
435
 *
436
 * @param card pointer to card data
437
 * @param p1 apdu P1 parameter
438
 * @param p2 apdu P2 parameter
439
 * @param buffer raw data to be inserted in apdu
440
 * @param length size of buffer
441
 * @return SC_SUCCESS if ok; else error code
442
 */
443
static int cwa_set_security_env(sc_card_t * card,
444
        u8 p1, u8 p2, u8 * buffer, size_t length)
445
0
{
446
0
  sc_apdu_t apdu;
447
0
  int result = SC_SUCCESS;
448
0
  sc_context_t *ctx = NULL;
449
450
  /* safety check */
451
0
  if (!card || !card->ctx)
452
0
    return SC_ERROR_INVALID_ARGUMENTS;
453
0
  ctx = card->ctx;
454
0
  LOG_FUNC_CALLED(ctx);
455
0
  if (!buffer || (length <= 0)) /* check received arguments */
456
0
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
457
458
  /* compose apdu for Manage Security Environment cmd */
459
0
  dnie_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, p1, p2, 0, length,
460
0
          NULL, 0, buffer, length);
461
462
  /* send composed apdu and parse result */
463
0
  result = sc_transmit_apdu(card, &apdu);
464
0
  LOG_TEST_RET(ctx, result, "SM Set Security Environment failed");
465
0
  result = sc_check_sw(card, apdu.sw1, apdu.sw2);
466
0
  LOG_FUNC_RETURN(ctx, result);
467
0
}
468
469
/**
470
 * SM internal authenticate.
471
 *
472
 * Internal (Card) authentication (let the card verify sent ifd certs)
473
 *
474
 * @param card pointer to card data
475
 * @param sig signature buffer
476
 * @param dig_len signature buffer length
477
 * @param data data to be sent in apdu
478
 * @param datalen length of data to send
479
 * @return SC_SUCCESS if OK: else error code
480
 */
481
static int cwa_internal_auth(sc_card_t * card, u8 * sig, size_t sig_len, u8 * data, size_t datalen)
482
0
{
483
0
  sc_apdu_t apdu;
484
0
  u8 rbuf[SC_MAX_APDU_BUFFER_SIZE];
485
0
  int result = SC_SUCCESS;
486
0
  sc_context_t *ctx = NULL;
487
488
  /* safety check */
489
0
  if (!card || !card->ctx)
490
0
    return SC_ERROR_INVALID_ARGUMENTS;
491
0
  ctx = card->ctx;
492
0
  LOG_FUNC_CALLED(ctx);
493
0
  if (!sig || !data || (datalen <= 0)) /* check received arguments */
494
0
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
495
496
  /* compose apdu for Internal Authenticate cmd */
497
0
  dnie_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x88, 0x00, 0x00, 0x80, datalen,
498
0
          rbuf, sizeof(rbuf), data, datalen);
499
500
  /* send composed apdu and parse result */
501
0
  result = sc_transmit_apdu(card, &apdu);
502
0
  LOG_TEST_RET(ctx, result, "SM internal auth failed");
503
504
0
  result = sc_check_sw(card, apdu.sw1, apdu.sw2);
505
0
  LOG_TEST_RET(ctx, result, "SM internal auth invalid response");
506
507
0
  if (apdu.resplen != sig_len) /* invalid number of bytes received */
508
0
    LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
509
0
  memcpy(sig, apdu.resp, apdu.resplen); /* copy result to buffer */
510
0
  LOG_FUNC_RETURN(ctx, SC_SUCCESS);
511
0
}
512
513
/**
514
 * Compose signature data for external auth according CWA-14890.
515
 *
516
 * This code prepares data to be sent to ICC for external
517
 * authentication procedure
518
 *
519
 * Store resulting data  into sm->sig
520
 *
521
 * @param card pointer to st_card_t card data information
522
 * @param icc_pubkey public key of card
523
 * @param ifd_privkey private key of ifd
524
 * @param sn_icc card serial number
525
 * @param sig signature buffer
526
 * @param sig_len signature buffer length
527
 * @return SC_SUCCESS if ok; else errorcode
528
 */
529
static int cwa_prepare_external_auth(sc_card_t * card,
530
             EVP_PKEY *icc_pubkey,
531
             EVP_PKEY *ifd_privkey,
532
             u8 * sig,
533
             size_t sig_len)
534
0
{
535
  /* we have to compose following message:
536
     data = E[PK.ICC.AUT](SIGMIN)
537
     SIGMIN = min ( SIG, N.IFD-SIG )
538
     SIG= DS[SK.IFD.AUT] (
539
     0x6A  || - padding according iso 9796-2
540
     PRND2 || - (74 bytes) random data to make buffer 128 bytes length
541
     Kifd  || - (32 bytes)- ifd random generated key
542
     sha1_hash(
543
     PRND2   ||
544
     Kifd    ||
545
     RND.ICC || - (8 bytes) response to get_challenge() cmd
546
     SN.ICC  - (8 bytes) serial number from get_serialnr() cmd
547
     ) ||
548
     0xBC - iso 9796-2 padding
549
     ) - total: 128 bytes
550
551
     then, we should encrypt with our private key and then with icc pub key
552
     returning resulting data
553
   */
554
0
  char *msg = NULL;   /* to store error messages */
555
0
  int res = SC_SUCCESS;
556
0
  int bn_len = 0;
557
0
  u8 *buf1 = NULL;   /* where to encrypt with icc pub key */
558
0
  u8 *buf2 = NULL;   /* where to encrypt with ifd pub key */
559
0
  u8 *buf3 = NULL;   /* where to compose message to be encrypted */
560
0
  size_t len1 = 128, len2 = 128, len3 = 128;
561
0
  u8 *sha_buf = NULL;   /* to compose message to be sha'd */
562
0
  u8 *sha_data = NULL;   /* sha signature data */
563
0
  BIGNUM *bn = NULL;
564
0
  BIGNUM *bnsub = NULL;
565
0
  BIGNUM *bnres = NULL;
566
0
  sc_context_t *ctx = NULL;
567
0
  struct sm_cwa_session * sm = &card->sm_ctx.info.session.cwa;
568
0
  EVP_PKEY_CTX *pctx = NULL;
569
570
#if OPENSSL_VERSION_NUMBER < 0x30000000L
571
  const BIGNUM *ifd_privkey_n = NULL;
572
  const RSA *rsa_ifd_privkey = EVP_PKEY_get0_RSA(ifd_privkey);
573
  if (!rsa_ifd_privkey) {
574
    res = SC_ERROR_INTERNAL;
575
    msg = "Can not extract RSA object ifd priv";
576
    goto prepare_external_auth_end;
577
  }
578
#else
579
0
  BIGNUM *ifd_privkey_n = NULL;
580
0
#endif
581
582
  /* safety check */
583
0
  if (!card || !card->ctx)
584
0
    return SC_ERROR_INVALID_ARGUMENTS;
585
0
  ctx = card->ctx;
586
0
  LOG_FUNC_CALLED(ctx);
587
  /* check received arguments */
588
0
  if (!icc_pubkey || !ifd_privkey || !sm || !sig || sig_len != 128)
589
0
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
590
0
  buf1 = calloc(128, sizeof(u8));
591
0
  buf2 = calloc(128, sizeof(u8));
592
0
  buf3 = calloc(128, sizeof(u8));
593
0
  sha_buf = calloc(74 + 32 + 8 + 8, sizeof(u8));
594
0
  sha_data = calloc(SHA_DIGEST_LENGTH, sizeof(u8));
595
  /* alloc() resources */
596
0
  if (!buf1 || !buf2 || !buf3 || !sha_buf || !sha_data) {
597
0
    msg = "prepare external auth: calloc error";
598
0
    res = SC_ERROR_OUT_OF_MEMORY;
599
0
    goto prepare_external_auth_end;
600
0
  }
601
602
  /* compose buffer data */
603
0
  buf3[0] = 0x6A;   /* iso padding */
604
0
  if (RAND_bytes(buf3 + 1, 74) != 1 ||     /* pRND */
605
0
      RAND_bytes(sm->ifd.k, 32) != 1) { /* Kifd */
606
0
    sc_log_openssl(ctx);
607
0
    msg = "prepare external auth: random data error";
608
0
    res = SC_ERROR_INTERNAL;
609
0
    goto prepare_external_auth_end;
610
0
  }
611
0
  memcpy(buf3 + 1 + 74, sm->ifd.k, 32); /* copy Kifd into buffer */
612
  /* prepare data to be hashed */
613
0
  memcpy(sha_buf, buf3 + 1, 74);  /* copy pRND into sha_buf */
614
0
  memcpy(sha_buf + 74, buf3 + 1 + 74, 32);  /* copy kifd into sha_buf */
615
0
  memcpy(sha_buf + 74 + 32, sm->icc.rnd, 8);  /* copy 8 byte icc challenge */
616
0
  memcpy(sha_buf + 74 + 32 + 8, sm->icc.sn, 8); /* copy serialnr, 8 bytes */
617
0
  SHA1(sha_buf, 74 + 32 + 8 + 8, sha_data);
618
  /* copy hashed data into buffer */
619
0
  memcpy(buf3 + 1 + 74 + 32, sha_data, SHA_DIGEST_LENGTH);
620
0
  buf3[127] = 0xBC; /* iso padding */
621
622
  /* decrypt with ifd private key */
623
0
  pctx = EVP_PKEY_CTX_new(ifd_privkey, NULL);
624
0
  if (!pctx ||
625
0
      EVP_PKEY_decrypt_init(pctx) != 1 ||
626
0
      EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_NO_PADDING) != 1 ||
627
0
    EVP_PKEY_decrypt(pctx, buf2, &len2, buf3, 128) != 1) {
628
0
    sc_log_openssl(ctx);
629
0
    msg = "Prepare external auth: ifd_privk decrypt failed";
630
0
    res = SC_ERROR_SM_ENCRYPT_FAILED;
631
0
    EVP_PKEY_CTX_free(pctx);
632
0
    goto prepare_external_auth_end;
633
0
  }
634
0
  EVP_PKEY_CTX_free(pctx);
635
0
  pctx = NULL;
636
637
  /* evaluate value of minsig and store into buf3 */
638
0
  bn = BN_bin2bn(buf2, (int)len2, NULL);
639
0
  bnsub = BN_new();
640
0
  if (!bn || !bnsub) {
641
0
    sc_log_openssl(ctx);
642
0
    msg = "Prepare external auth: BN creation failed";
643
0
    res = SC_ERROR_INTERNAL;
644
0
    goto prepare_external_auth_end;
645
0
  }
646
#if OPENSSL_VERSION_NUMBER < 0x30000000L
647
  RSA_get0_key(rsa_ifd_privkey, &ifd_privkey_n, NULL, NULL);
648
#else
649
0
  if (EVP_PKEY_get_bn_param(ifd_privkey, OSSL_PKEY_PARAM_RSA_N, &ifd_privkey_n) != 1) {
650
0
    sc_log_openssl(ctx);
651
0
    msg = "Prepare external auth: BN get param failed";
652
0
    res = SC_ERROR_INTERNAL;
653
0
    goto prepare_external_auth_end;
654
0
  }
655
0
#endif
656
657
0
  res = BN_sub(bnsub, ifd_privkey_n, bn); /* eval N.IFD-SIG */
658
0
  if (res == 0) {   /* 1:success 0 fail */
659
0
    sc_log_openssl(ctx);
660
0
    msg = "Prepare external auth: BN sigmin evaluation failed";
661
0
    res = SC_ERROR_INTERNAL;
662
0
    goto prepare_external_auth_end;
663
0
  }
664
0
  bnres = (BN_cmp(bn, bnsub) < 0) ? bn : bnsub; /* choose min(SIG,N.IFD-SIG) */
665
0
  bn_len = BN_num_bytes(bnres);
666
0
  if (bn_len <= 0 || bn_len > 128) {
667
0
    sc_log_openssl(ctx);
668
0
    msg = "Prepare external auth: BN sigmin result is invalid size";
669
0
    res = SC_ERROR_INTERNAL;
670
0
    goto prepare_external_auth_end;
671
0
  }
672
0
  memset(buf3, 0, 128);
673
0
  len3 = BN_bn2bin(bnres, buf3 + (128 - bn_len)); /* convert result back into buf3 */
674
0
  if (len3 <= 0) {
675
0
    sc_log_openssl(ctx);
676
0
    msg = "Prepare external auth: BN to buffer conversion failed";
677
0
    res = SC_ERROR_INTERNAL;
678
0
    goto prepare_external_auth_end;
679
0
  }
680
0
  len3 = 128;
681
682
  /* re-encrypt result with icc public key */
683
0
  pctx = EVP_PKEY_CTX_new(icc_pubkey, NULL);
684
0
  if (!pctx ||
685
0
      EVP_PKEY_encrypt_init(pctx) != 1 ||
686
0
      EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_NO_PADDING) != 1 ||
687
0
      EVP_PKEY_encrypt(pctx, buf1, &len1, buf3, 128) != 1 ||
688
0
      (size_t)len1 != sig_len) {
689
0
    sc_log_openssl(ctx);
690
0
    msg = "Prepare external auth: icc_pubk encrypt failed";
691
0
    res = SC_ERROR_SM_ENCRYPT_FAILED;
692
0
    EVP_PKEY_CTX_free(pctx);
693
0
    goto prepare_external_auth_end;
694
0
  }
695
0
  EVP_PKEY_CTX_free(pctx);
696
697
  /* process done: copy result into cwa_internal buffer and return success */
698
0
  memcpy(sig, buf1, len1);
699
0
  res = SC_SUCCESS;
700
701
0
 prepare_external_auth_end:
702
0
  BN_free(bn);
703
0
  BN_free(bnsub);
704
0
  if (buf1) {
705
0
    sc_mem_clear(buf1, 128);
706
0
    free(buf1);
707
0
  }
708
0
  if (buf2) {
709
0
    sc_mem_clear(buf2, 128);
710
0
    free(buf2);
711
0
  }
712
0
  if (buf3) {
713
0
    sc_mem_clear(buf3, 128);
714
0
    free(buf3);
715
0
  }
716
0
  if (sha_buf) {
717
0
    sc_mem_clear(sha_buf, 74 + 32 + 8 + 1 + 7);
718
0
    free(sha_buf);
719
0
  }
720
0
  free(sha_data);
721
0
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
722
0
  BN_clear_free(ifd_privkey_n);
723
0
#endif
724
725
0
  if (res != SC_SUCCESS) {
726
0
    sc_log(ctx, "%s", msg);
727
0
  }
728
0
  LOG_FUNC_RETURN(ctx, res);
729
0
}
730
731
/**
732
 * SM external authenticate.
733
 *
734
 * Perform external (IFD) authenticate procedure (8.4.1.2)
735
 *
736
 * @param card pointer to card data
737
 * @param sig signature buffer
738
 * @param sig signature buffer length
739
 * @return SC_SUCCESS if OK: else error code
740
 */
741
static int cwa_external_auth(sc_card_t * card, u8 * sig, size_t sig_len)
742
0
{
743
0
  sc_apdu_t apdu;
744
0
  int result = SC_SUCCESS;
745
0
  sc_context_t *ctx = NULL;
746
747
  /* safety check */
748
0
  if (!card || !card->ctx)
749
0
    return SC_ERROR_INVALID_ARGUMENTS;
750
0
  ctx = card->ctx;
751
0
  LOG_FUNC_CALLED(ctx);
752
0
  if (!sig || sig_len == 0)
753
0
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
754
755
  /* compose apdu for External Authenticate cmd */
756
0
  dnie_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x82, 0x00, 0x00, 0, sig_len,
757
0
          NULL, 0, sig, sig_len);
758
759
  /* send composed apdu and parse result */
760
0
  result = sc_transmit_apdu(card, &apdu);
761
0
  LOG_TEST_RET(ctx, result, "SM external auth failed");
762
0
  result = sc_check_sw(card, apdu.sw1, apdu.sw2);
763
0
  LOG_TEST_RET(ctx, result, "SM external auth invalid response");
764
0
  LOG_FUNC_RETURN(ctx, SC_SUCCESS);
765
0
}
766
767
/**
768
 * SM creation of session keys.
769
 *
770
 * Compute Kenc,Kmac, and SSC  and store it into sm data
771
 *
772
 * @param card pointer to sc_card_t data
773
 * @return SC_SUCCESS if ok; else error code
774
 */
775
static int cwa_compute_session_keys(sc_card_t * card)
776
0
{
777
778
0
  char *msg = NULL;
779
0
  int n = 0;
780
0
  int res = SC_SUCCESS;
781
0
  u8 *kseed;    /* to compose kifd ^ kicc */
782
0
  u8 *data;   /* to compose kenc and kmac to be hashed */
783
0
  u8 *sha_data;   /* to store hash result */
784
0
  u8 kenc[4] = { 0x00, 0x00, 0x00, 0x01 };
785
0
  u8 kmac[4] = { 0x00, 0x00, 0x00, 0x02 };
786
0
  sc_context_t *ctx = NULL;
787
0
  struct sm_cwa_session * sm = &card->sm_ctx.info.session.cwa;
788
789
  /* safety check */
790
0
  if (!card || !card->ctx)
791
0
    return SC_ERROR_INVALID_ARGUMENTS;
792
0
  ctx = card->ctx;
793
0
  LOG_FUNC_CALLED(ctx);
794
  /* Just a literal transcription of cwa14890-1 sections 8.7.2 to 8.9 */
795
0
  kseed = calloc(32, sizeof(u8));
796
0
  data = calloc(32 + 4, sizeof(u8));
797
0
  sha_data = calloc(SHA_DIGEST_LENGTH, sizeof(u8));
798
0
  if (!kseed || !data || !sha_data) {
799
0
    msg = "Compute Session Keys: calloc() failed";
800
0
    res = SC_ERROR_OUT_OF_MEMORY;
801
0
    goto compute_session_keys_end;
802
0
  }
803
  /* compose kseed  (cwa-14890-1 sect 8.7.2) */
804
0
  for (n = 0; n < 32; n++)
805
0
    *(kseed + n) = sm->icc.k[n] ^ sm->ifd.k[n];
806
807
  /* evaluate kenc (cwa-14890-1 sect 8.8) */
808
0
  memcpy(data, kseed, 32);
809
0
  memcpy(data + 32, kenc, 4);
810
0
  SHA1(data, 32 + 4, sha_data);
811
0
  memcpy(sm->session_enc, sha_data, 16);  /* kenc=16 fsb sha((kifd^kicc)||00000001) */
812
813
  /* evaluate kmac */
814
0
  memset(data, 0, 32 + 4);
815
0
  memset(sha_data, 0, SHA_DIGEST_LENGTH); /* clear buffers */
816
817
0
  memcpy(data, kseed, 32);
818
0
  memcpy(data + 32, kmac, 4);
819
0
  SHA1(data, 32 + 4, sha_data);
820
0
  memcpy(sm->session_mac, sha_data, 16);  /* kmac=16 fsb sha((kifd^kicc)||00000002) */
821
822
  /* evaluate send sequence counter  (cwa-14890-1 sect 8.9 & 9.6 */
823
0
  memcpy(sm->ssc, sm->icc.rnd + 4, 4);  /* 4 least significant bytes of rndicc */
824
0
  memcpy(sm->ssc + 4, sm->ifd.rnd + 4, 4);  /* 4 least significant bytes of rndifd */
825
826
  /* arriving here means process ok */
827
0
  res = SC_SUCCESS;
828
829
0
 compute_session_keys_end:
830
0
  if (kseed) {
831
0
    sc_mem_clear(kseed, 32);
832
0
    free(kseed);
833
0
  }
834
0
  if (data) {
835
0
    sc_mem_clear(data, 32 + 4);
836
0
    free(data);
837
0
  }
838
0
  free(sha_data);
839
0
  if (res != SC_SUCCESS)
840
0
    sc_log(ctx, "%s", msg);
841
0
  else {
842
0
    sc_log(ctx, "Kenc: %s", sc_dump_hex(sm->session_enc, 16));
843
0
    sc_log(ctx, "Kmac: %s", sc_dump_hex(sm->session_mac, 16));
844
0
    sc_log(ctx, "SSC:  %s", sc_dump_hex(sm->ssc, 8));
845
0
  }
846
0
  LOG_FUNC_RETURN(ctx, res);
847
0
}
848
849
/*
850
 * Compare signature for internal auth procedure.
851
 *
852
 * @param data Received data to be checked
853
 * @param dlen data length
854
 * @param expected results
855
 * @return SC_SUCCESS or error code
856
 */
857
static int cwa_compare_signature(u8 * data, size_t dlen, u8 * ifd_data)
858
0
{
859
0
  u8 *buf = calloc(74 + 32 + 32, sizeof(u8));
860
0
  u8 *sha = calloc(SHA_DIGEST_LENGTH, sizeof(u8));
861
0
  int res = SC_SUCCESS;
862
0
  if (!buf || !sha) {
863
0
    res = SC_ERROR_OUT_OF_MEMORY;
864
0
    goto compare_signature_end;
865
0
  }
866
0
  res = SC_ERROR_INVALID_DATA;
867
0
  if (!data || !ifd_data || dlen != 128)
868
0
    goto compare_signature_end; /* check length */
869
0
  if (data[0] != 0x6a)
870
0
    goto compare_signature_end; /* iso 9796-2 padding */
871
0
  if (data[127] != 0xBC)
872
0
    goto compare_signature_end; /* iso 9796-2 padding */
873
0
  memcpy(buf, data + 1, 74 + 32);
874
0
  memcpy(buf + 74 + 32, ifd_data, 16);
875
0
  SHA1(buf, 74 + 32 + 16, sha);
876
0
  if (memcmp(data + 127 - SHA_DIGEST_LENGTH, sha, SHA_DIGEST_LENGTH) == 0)
877
0
    res = SC_SUCCESS;
878
0
 compare_signature_end:
879
0
  free(buf);
880
0
  free(sha);
881
0
  return res;
882
0
}
883
884
/**
885
 * check the result of internal_authenticate operation.
886
 *
887
 * Checks icc received data from internal auth procedure against
888
 * expected results
889
 *
890
 * @param card Pointer to sc_card_t data
891
 * @param icc_pubkey icc public key
892
 * @param ifd_privkey ifd private key
893
 * @param ifdbuf buffer containing ( RND.IFD || SN.IFD )
894
 * @param ifdlen buffer length; should be 16
895
 * @param sig signature buffer
896
 * @param sig_len signature buffer length
897
 * @return SC_SUCCESS if ok; else error code
898
 */
899
static int cwa_verify_internal_auth(sc_card_t * card,
900
            EVP_PKEY *icc_pubkey,
901
            EVP_PKEY *ifd_privkey,
902
            u8 * ifdbuf,
903
            size_t ifdlen,
904
            u8 * sig,
905
            size_t sig_len)
906
0
{
907
0
  int res = SC_SUCCESS;
908
0
  char *msg = NULL;
909
0
  u8 *buf1 = NULL; /* to decrypt with our private key */
910
0
  u8 *buf2 = NULL; /* to try SIGNUM==SIG */
911
0
  u8 *buf3 = NULL; /* to try SIGNUM==N.ICC-SIG */
912
0
  size_t len1 = 128, len2 = 128, len3 = 128, bn_len = 0;
913
0
  BIGNUM *bn = NULL;
914
0
  BIGNUM *sigbn = NULL;
915
0
  sc_context_t *ctx = NULL;
916
0
  struct sm_cwa_session * sm = &card->sm_ctx.info.session.cwa;
917
0
  EVP_PKEY_CTX *pctx = NULL;
918
919
#if OPENSSL_VERSION_NUMBER < 0x30000000L
920
  const BIGNUM *icc_pubkey_n = NULL;
921
  const RSA *rsa_icc_pubkey = EVP_PKEY_get0_RSA(icc_pubkey);
922
  if (!rsa_icc_pubkey) {
923
    res = SC_ERROR_INTERNAL;
924
    msg = "Can not extract RSA object icc pub";
925
    goto verify_internal_done;
926
  }
927
#else
928
0
  BIGNUM *icc_pubkey_n = NULL;
929
0
#endif
930
931
0
  if (!card || !card->ctx)
932
0
    return SC_ERROR_INVALID_ARGUMENTS;
933
0
  ctx = card->ctx;
934
0
  LOG_FUNC_CALLED(ctx);
935
0
  if (!ifdbuf || (ifdlen != 16)) {
936
0
    res = SC_ERROR_INVALID_ARGUMENTS;
937
0
    msg = "Null buffers received as parameters";
938
0
    goto verify_internal_done;
939
0
  }
940
0
  if (!icc_pubkey || !ifd_privkey || !sig || sig_len != 128) {
941
0
    res = SC_ERROR_SM_NO_SESSION_KEYS;
942
0
    msg = "Either provided icc_pubk, ifd_privk, or sig is null/invalid";
943
0
    goto verify_internal_done;
944
0
  }
945
0
  buf1 = (u8 *) calloc(128, sizeof(u8));  /* 128: RSA key len in bytes */
946
0
  buf2 = (u8 *) calloc(128, sizeof(u8));
947
0
  buf3 = (u8 *) calloc(128, sizeof(u8));
948
0
  if (!buf1 || !buf2 || !buf3) {
949
0
    msg = "Verify Signature: calloc() error";
950
0
    res = SC_ERROR_OUT_OF_MEMORY;
951
0
    goto verify_internal_done;
952
0
  }
953
954
  /*
955
     We have received data with this format:
956
     sigbuf = E[PK.IFD.AUT](SIGMIN)
957
     SIGMIN = min ( SIG, N.ICC-SIG )
958
     SIG= DS[SK.ICC.AUT] (
959
     0x6A  ||
960
     PRND1 ||
961
     Kicc  ||
962
     sha1_hash(PRND1 || Kicc || RND.IFD || SN.IFD) ||
963
     0xBC
964
     )
965
     So we should reverse the process and try to get valid results
966
   */
967
968
  /* decrypt data with our ifd priv key */
969
0
  pctx = EVP_PKEY_CTX_new(ifd_privkey, NULL);
970
0
  if (!pctx ||
971
0
      EVP_PKEY_decrypt_init(pctx) != 1 ||
972
0
      EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_NO_PADDING) != 1 ||
973
0
      EVP_PKEY_decrypt(pctx, buf1, &len1, sig, sig_len) != 1) {
974
0
    sc_log_openssl(ctx);
975
0
    msg = "Verify Signature: decrypt with ifd privk failed";
976
0
    res = SC_ERROR_SM_ENCRYPT_FAILED;
977
0
    EVP_PKEY_CTX_free(pctx);
978
0
    goto verify_internal_done;
979
0
  }
980
0
  EVP_PKEY_CTX_free(pctx);
981
0
  pctx = NULL;
982
983
  /* OK: now we have SIGMIN in buf1 */
984
  /* check if SIGMIN data matches SIG or N.ICC-SIG */
985
  /* evaluate DS[SK.ICC.AUTH](SIG) trying to decrypt with icc pubk */
986
0
  pctx = EVP_PKEY_CTX_new(icc_pubkey, NULL);
987
0
  if (!pctx ||
988
0
      EVP_PKEY_encrypt_init(pctx) != 1 ||
989
0
      EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_NO_PADDING) != 1 ||
990
0
      EVP_PKEY_encrypt(pctx, buf3, &len3, buf1, len1) != 1) {
991
0
    EVP_PKEY_CTX_free(pctx);
992
0
    sc_log_openssl(ctx);
993
0
    goto verify_nicc_sig; /* evaluate N.ICC-SIG and retry */
994
0
  }
995
996
0
  EVP_PKEY_CTX_free(pctx);
997
998
0
  res = cwa_compare_signature(buf3, len3, ifdbuf);
999
0
  if (res == SC_SUCCESS)
1000
0
    goto verify_internal_ok;
1001
1002
0
 verify_nicc_sig:
1003
  /*
1004
   * Arriving here means need to evaluate N.ICC-SIG
1005
   * So convert buffers to bignums to operate
1006
   */
1007
0
  bn = BN_bin2bn(buf1, (int)len1, NULL);  /* create BN data */
1008
0
  sigbn = BN_new();
1009
0
  if (!bn || !sigbn) {
1010
0
    sc_log_openssl(ctx);
1011
0
    msg = "Verify Signature: cannot bignums creation error";
1012
0
    res = SC_ERROR_OUT_OF_MEMORY;
1013
0
    goto verify_internal_done;
1014
0
  }
1015
#if OPENSSL_VERSION_NUMBER < 0x30000000L
1016
  RSA_get0_key(rsa_icc_pubkey, &icc_pubkey_n, NULL, NULL);
1017
#else
1018
0
  if (EVP_PKEY_get_bn_param(icc_pubkey, OSSL_PKEY_PARAM_RSA_N, &icc_pubkey_n) != 1) {
1019
0
    sc_log_openssl(ctx);
1020
0
    msg = "Verify Signature: BN get param failed";
1021
0
    res = SC_ERROR_INTERNAL;
1022
0
    goto verify_internal_done;
1023
0
  }
1024
0
#endif
1025
0
  res = BN_sub(sigbn, icc_pubkey_n, bn);  /* eval N.ICC-SIG */
1026
0
  if (!res) {
1027
0
    sc_log_openssl(ctx);
1028
0
    msg = "Verify Signature: evaluation of N.ICC-SIG failed";
1029
0
    res = SC_ERROR_INTERNAL;
1030
0
    goto verify_internal_done;
1031
0
  }
1032
0
  bn_len = (size_t)BN_num_bytes(sigbn);
1033
0
  if (bn_len == 0 || bn_len > 128) {
1034
0
    msg = "Verify Signature: unsupported RSA size";
1035
0
    res = SC_ERROR_INVALID_DATA;
1036
0
    goto verify_internal_done;
1037
0
  }
1038
0
  memset(buf2, 0, 128);
1039
0
  len2 = BN_bn2bin(sigbn, buf2 + (128 - bn_len)); /* copy result to buffer */
1040
0
  if (len2 <= 0) {
1041
0
    sc_log_openssl(ctx);
1042
0
    msg = "Verify Signature: cannot convert bignum to buffer";
1043
0
    res = SC_ERROR_INTERNAL;
1044
0
    goto verify_internal_done;
1045
0
  }
1046
0
  len2 = 128;
1047
  /* ok: check again with new data */
1048
  /* evaluate DS[SK.ICC.AUTH](I.ICC-SIG) trying to decrypt with icc pubk */
1049
0
  pctx = EVP_PKEY_CTX_new(icc_pubkey, NULL);
1050
0
  if (!pctx ||
1051
0
    EVP_PKEY_encrypt_init(pctx) != 1 ||
1052
0
    EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_NO_PADDING) != 1 ||
1053
0
    EVP_PKEY_encrypt(pctx, buf3, &len3, buf2, len2) != 1) {
1054
0
    sc_log_openssl(ctx);
1055
0
    msg = "Verify Signature: cannot get valid SIG data";
1056
0
    res = SC_ERROR_INVALID_DATA;
1057
0
    EVP_PKEY_CTX_free(pctx);
1058
0
    goto verify_internal_done;
1059
0
  }
1060
0
  EVP_PKEY_CTX_free(pctx);
1061
0
  pctx = NULL;
1062
1063
0
  res = cwa_compare_signature(buf3, len3, ifdbuf);
1064
0
  if (res != SC_SUCCESS) {
1065
0
    msg = "Verify Signature: cannot get valid SIG data";
1066
0
    res = SC_ERROR_INVALID_DATA;
1067
0
    goto verify_internal_done;
1068
0
  }
1069
  /* arriving here means OK: complete data structures */
1070
0
 verify_internal_ok:
1071
0
  memcpy(sm->icc.k, buf3 + 1 + 74, 32); /* extract Kicc from buf3 */
1072
0
  res = SC_SUCCESS;
1073
0
 verify_internal_done:
1074
0
  free(buf1);
1075
0
  free(buf2);
1076
0
  free(buf3);
1077
0
  BN_free(bn);
1078
0
  BN_free(sigbn);
1079
0
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
1080
0
  BN_clear_free(icc_pubkey_n);
1081
0
#endif
1082
0
  if (res != SC_SUCCESS) {
1083
0
    sc_log(ctx, "%s", msg);
1084
0
  }
1085
0
  LOG_FUNC_RETURN(ctx, res);
1086
0
}
1087
1088
/**
1089
 * Create Secure Messaging channel.
1090
 *
1091
 * This is the main entry point for CWA14890 SM channel creation.
1092
 * It closely follows cwa standard, with a minor modification:
1093
 * - ICC serial number is taken at the beginning of SM creation
1094
 * - ICC and IFD certificate agreement process is reversed, to allow
1095
 * card to retain key references on further process (this behavior
1096
 * is also defined in standard)
1097
 *
1098
 * Based on Several documents:
1099
 * - "Understanding the DNIe"
1100
 * - "Manual de comandos del DNIe"
1101
 * - ISO7816-4 and CWA14890-{1,2}
1102
 *
1103
 * @param card card info structure
1104
 * @param provider cwa14890 info provider
1105
 * @param flag requested init method ( OFF, COLD, WARM )
1106
 * @return SC_SUCCESS if OK; else error code
1107
 */
1108
int cwa_create_secure_channel(sc_card_t * card,
1109
            cwa_provider_t * provider, int flag)
1110
914
{
1111
914
  u8 *cert = NULL;
1112
914
  size_t certlen;
1113
1114
914
  int res = SC_SUCCESS;
1115
914
  char *msg = "Success";
1116
914
  u8 *new_tlv = NULL;
1117
1118
  /* data to get and parse certificates */
1119
914
  X509 *icc_cert = NULL;
1120
914
  X509 *ca_cert = NULL;
1121
914
  EVP_PKEY *icc_pubkey = NULL;
1122
914
  EVP_PKEY *ifd_privkey = NULL;
1123
914
  sc_context_t *ctx = NULL;
1124
914
  struct sm_cwa_session * sm = &card->sm_ctx.info.session.cwa;
1125
914
  u8 sig[128];
1126
1127
  /* several buffer and buffer pointers */
1128
914
  u8 *buffer = NULL;
1129
914
  size_t bufferlen;
1130
914
  u8 *tlv = NULL;   /* buffer to compose TLV messages */
1131
914
  size_t tlvlen = 0;
1132
914
  u8 rndbuf[16]; /* 8 RND.IFD + 8 SN.IFD */
1133
1134
  /* preliminary checks */
1135
914
  if (!card || !card->ctx )
1136
0
    return SC_ERROR_INVALID_ARGUMENTS;
1137
914
  if (!provider)
1138
0
    return SC_ERROR_SM_NOT_INITIALIZED;
1139
  /* commodity vars */
1140
914
  ctx = card->ctx;
1141
1142
914
  LOG_FUNC_CALLED(ctx);
1143
1144
  /* check requested initialization method */
1145
914
  switch (flag) {
1146
914
  case CWA_SM_OFF: /* disable SM */
1147
914
    card->sm_ctx.sm_mode = SM_MODE_NONE;
1148
914
    sc_log(ctx, "Setting CWA SM status to none");
1149
    /* request the Master File to provoke an SM error and close the channel */
1150
914
    res = sc_select_file(card, sc_get_mf_path(), NULL);
1151
914
    if (res == SC_ERROR_SM)
1152
15
      res = SC_SUCCESS;
1153
914
    LOG_FUNC_RETURN(ctx, res);
1154
0
  case CWA_SM_ON: /* force sm initialization process */
1155
0
    sc_log(ctx, "CWA SM initialization requested");
1156
0
    break;
1157
0
  default:
1158
0
    sc_log(ctx, "Invalid provided SM initialization flag");
1159
0
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
1160
914
  }
1161
1162
  /* OK: lets start process */
1163
1164
  /* call provider pre-operation method */
1165
0
  sc_log(ctx, "CreateSecureChannel pre-operations");
1166
0
  if (provider->cwa_create_pre_ops) {
1167
0
    res = provider->cwa_create_pre_ops(card, provider);
1168
0
    if (res != SC_SUCCESS) {
1169
0
      msg = "Create SM: provider pre_ops() failed";
1170
0
      sc_log(ctx, "%s", msg);
1171
0
      goto csc_end;
1172
0
    }
1173
0
  }
1174
1175
  /* retrieve icc serial number */
1176
0
  sc_log(ctx, "Retrieve ICC serial number");
1177
0
  if (provider->cwa_get_sn_icc) {
1178
0
    res = provider->cwa_get_sn_icc(card);
1179
0
    if (res != SC_SUCCESS) {
1180
0
      msg = "Retrieve ICC failed";
1181
0
      sc_log(ctx, "%s", msg);
1182
0
      goto csc_end;
1183
0
    }
1184
0
  } else {
1185
0
    msg = "Don't know how to obtain ICC serial number";
1186
0
    sc_log(ctx, "%s", msg);
1187
0
    res = SC_ERROR_INTERNAL;
1188
0
    goto csc_end;
1189
0
  }
1190
1191
  /*
1192
   * Notice that this code inverts ICC and IFD certificate standard
1193
   * checking sequence.
1194
   */
1195
1196
  /* Read Intermediate CA from card */
1197
0
  if (!provider->cwa_get_icc_intermediate_ca_cert) {
1198
0
    sc_log(ctx,
1199
0
           "Step 8.4.1.6: Skip Retrieving ICC intermediate CA");
1200
0
    ca_cert = NULL;
1201
0
  } else {
1202
0
    sc_log(ctx, "Step 8.4.1.7: Retrieving ICC intermediate CA");
1203
0
    res =
1204
0
        provider->cwa_get_icc_intermediate_ca_cert(card, &ca_cert);
1205
0
    if (res != SC_SUCCESS) {
1206
0
      msg =
1207
0
          "Cannot get ICC intermediate CA certificate from provider";
1208
0
      goto csc_end;
1209
0
    }
1210
0
  }
1211
1212
  /* Read ICC certificate from card */
1213
0
  sc_log(ctx, "Step 8.4.1.8: Retrieve ICC certificate");
1214
0
  res = provider->cwa_get_icc_cert(card, &icc_cert);
1215
0
  if (res != SC_SUCCESS) {
1216
0
    msg = "Cannot get ICC certificate from provider";
1217
0
    goto csc_end;
1218
0
  }
1219
1220
  /* Verify icc Card certificate chain */
1221
  /* Notice that Some implementations doesn't verify cert chain
1222
   * but simply verifies that icc_cert is a valid certificate */
1223
0
  if (ca_cert) {
1224
0
    sc_log(ctx, "Verifying ICC certificate chain");
1225
0
    res =
1226
0
        cwa_verify_icc_certificates(card, provider, ca_cert,
1227
0
            icc_cert);
1228
0
    if (res != SC_SUCCESS) {
1229
0
      res = SC_ERROR_SM_AUTHENTICATION_FAILED;
1230
0
      msg = "Icc Certificates verification failed";
1231
0
      goto csc_end;
1232
0
    }
1233
0
  } else {
1234
0
    sc_log(ctx, "Cannot verify Certificate chain. skip step");
1235
0
  }
1236
1237
  /* Extract public key from ICC certificate */
1238
0
  if (!(icc_pubkey = X509_get_pubkey(icc_cert))) {
1239
0
    res = SC_ERROR_INTERNAL;
1240
0
    sc_log_openssl(ctx);
1241
0
    msg = "Cannot extract public key from ICC certificate";
1242
0
    goto csc_end;
1243
0
  }
1244
1245
  /* Select Root CA in card for ifd certificate verification */
1246
0
  sc_log(ctx,
1247
0
         "Step 8.4.1.2: Select Root CA in card for IFD cert verification");
1248
0
  res = provider->cwa_get_root_ca_pubkey_ref(card, &buffer, &bufferlen);
1249
0
  if (res != SC_SUCCESS) {
1250
0
    msg = "Cannot get Root CA key reference from provider";
1251
0
    goto csc_end;
1252
0
  }
1253
0
  tlvlen = 0;
1254
0
  tlv = calloc(10 + bufferlen, sizeof(u8));
1255
0
  if (!tlv) {
1256
0
    msg = "calloc error";
1257
0
    res = SC_ERROR_OUT_OF_MEMORY;
1258
0
    goto csc_end;
1259
0
  }
1260
0
  res = cwa_compose_tlv(card, 0x83, bufferlen, buffer, &tlv, &tlvlen);
1261
0
  if (res != SC_SUCCESS) {
1262
0
    msg = "Cannot compose tlv for setting Root CA key reference";
1263
0
    goto csc_end;
1264
0
  }
1265
0
  res = cwa_set_security_env(card, 0x81, 0xB6, tlv, tlvlen);
1266
0
  if (res != SC_SUCCESS) {
1267
0
    msg = "Select Root CA key ref failed";
1268
0
    goto csc_end;
1269
0
  }
1270
1271
  /* Send IFD intermediate CA in CVC format C_CV_CA */
1272
0
  sc_log(ctx,
1273
0
         "Step 8.4.1.3: Send CVC IFD intermediate CA Cert for ICC verification");
1274
0
  res = provider->cwa_get_cvc_ca_cert(card, &cert, &certlen);
1275
0
  if (res != SC_SUCCESS) {
1276
0
    msg = "Get CVC CA cert from provider failed";
1277
0
    goto csc_end;
1278
0
  }
1279
0
  res = cwa_verify_cvc_certificate(card, cert, certlen);
1280
0
  if (res != SC_SUCCESS) {
1281
0
    msg = "Verify CVC CA failed";
1282
0
    goto csc_end;
1283
0
  }
1284
1285
  /* select public key reference for sent IFD intermediate CA certificate */
1286
0
  sc_log(ctx,
1287
0
         "Step 8.4.1.4: Select Intermediate CA pubkey ref for ICC verification");
1288
0
  res =
1289
0
      provider->cwa_get_intermediate_ca_pubkey_ref(card, &buffer,
1290
0
               &bufferlen);
1291
0
  if (res != SC_SUCCESS) {
1292
0
    msg = "Cannot get intermediate CA key reference from provider";
1293
0
    goto csc_end;
1294
0
  }
1295
0
  tlvlen = 0;
1296
0
  free(tlv);
1297
0
  tlv = calloc(10 + bufferlen, sizeof(u8));
1298
0
  if (!tlv) {
1299
0
    msg = "calloc error";
1300
0
    res = SC_ERROR_OUT_OF_MEMORY;
1301
0
    goto csc_end;
1302
0
  }
1303
0
  res = cwa_compose_tlv(card, 0x83, bufferlen, buffer, &tlv, &tlvlen);
1304
0
  if (res != SC_SUCCESS) {
1305
0
    msg =
1306
0
        "Cannot compose tlv for setting intermediate CA key reference";
1307
0
    goto csc_end;
1308
0
  }
1309
0
  res = cwa_set_security_env(card, 0x81, 0xB6, tlv, tlvlen);
1310
0
  if (res != SC_SUCCESS) {
1311
0
    msg = "Select CVC CA pubk failed";
1312
0
    goto csc_end;
1313
0
  }
1314
1315
  /* Send IFD certificate in CVC format C_CV_IFD */
1316
0
  sc_log(ctx,
1317
0
         "Step 8.4.1.5: Send CVC IFD Certificate for ICC verification");
1318
0
  res = provider->cwa_get_cvc_ifd_cert(card, &cert, &certlen);
1319
0
  if (res != SC_SUCCESS) {
1320
0
    msg = "Get CVC IFD cert from provider failed";
1321
0
    goto csc_end;
1322
0
  }
1323
0
  res = cwa_verify_cvc_certificate(card, cert, certlen);
1324
0
  if (res != SC_SUCCESS) {
1325
0
    msg = "Verify CVC IFD failed";
1326
0
    goto csc_end;
1327
0
  }
1328
1329
  /* remember that this code changes IFD and ICC Cert verification steps */
1330
1331
  /* select public key of ifd certificate and icc private key */
1332
0
  sc_log(ctx,
1333
0
         "Step 8.4.1.9: Send IFD pubk and ICC privk key references for Internal Auth");
1334
0
  res = provider->cwa_get_ifd_pubkey_ref(card, &buffer, &bufferlen);
1335
0
  if (res != SC_SUCCESS) {
1336
0
    msg = "Cannot get ifd public key reference from provider";
1337
0
    goto csc_end;
1338
0
  }
1339
0
  tlvlen = 0;
1340
0
  free(tlv);
1341
0
  tlv = calloc(10 + bufferlen, sizeof(u8));
1342
0
  if (!tlv) {
1343
0
    msg = "calloc error";
1344
0
    res = SC_ERROR_OUT_OF_MEMORY;
1345
0
    goto csc_end;
1346
0
  }
1347
0
  res = cwa_compose_tlv(card, 0x83, bufferlen, buffer, &tlv, &tlvlen);
1348
0
  if (res != SC_SUCCESS) {
1349
0
    msg = "Cannot compose tlv for setting ifd pubkey reference";
1350
0
    goto csc_end;
1351
0
  }
1352
0
  res = provider->cwa_get_icc_privkey_ref(card, &buffer, &bufferlen);
1353
0
  if (res != SC_SUCCESS) {
1354
0
    msg = "Cannot get icc private key reference from provider";
1355
0
    goto csc_end;
1356
0
  }
1357
  /* add this tlv to old one; realloc to avoid buffer overflow */
1358
0
  new_tlv = realloc(tlv, tlvlen + 10 + bufferlen);
1359
0
  if (!new_tlv) {
1360
0
    msg = "realloc error";
1361
0
    res = SC_ERROR_OUT_OF_MEMORY;
1362
0
    goto csc_end;
1363
0
  }
1364
0
  tlv = new_tlv;
1365
0
  res = cwa_compose_tlv(card, 0x84, bufferlen, buffer, &tlv, &tlvlen);
1366
0
  if (res != SC_SUCCESS) {
1367
0
    msg = "Cannot compose tlv for setting ifd pubkey reference";
1368
0
    goto csc_end;
1369
0
  }
1370
1371
0
  res = cwa_set_security_env(card, 0xC1, 0xA4, tlv, tlvlen);
1372
0
  if (res != SC_SUCCESS) {
1373
0
    msg = "Select CVC IFD pubk failed";
1374
0
    goto csc_end;
1375
0
  }
1376
1377
  /* Internal (Card) authentication (let the card verify sent ifd certs)
1378
     SN.IFD equals 8 lsb bytes of ifd.pubk ref according cwa14890 sec 8.4.1 */
1379
0
  sc_log(ctx, "Step 8.4.1.10: Perform Internal authentication");
1380
0
  res = provider->cwa_get_sn_ifd(card);
1381
0
  if (res != SC_SUCCESS) {
1382
0
    msg = "Cannot get ifd serial number from provider";
1383
0
    goto csc_end;
1384
0
  }
1385
  /* generate 8 random bytes */
1386
0
  if (RAND_bytes(sm->ifd.rnd, 8) != 1) {
1387
0
    msg = "Cannot generate random data";
1388
0
    res = SC_ERROR_INTERNAL;
1389
0
    goto csc_end;
1390
0
  }
1391
0
  memcpy(rndbuf, sm->ifd.rnd, 8); /* insert RND.IFD into rndbuf */
1392
0
  memcpy(rndbuf + 8, sm->ifd.sn, 8);  /* insert SN.IFD into rndbuf */
1393
0
  res = cwa_internal_auth(card, sig, 128, rndbuf, 16);
1394
0
  if (res != SC_SUCCESS) {
1395
0
    msg = "Internal auth cmd failed";
1396
0
    goto csc_end;
1397
0
  }
1398
1399
  /* retrieve ifd private key from provider */
1400
0
  res = provider->cwa_get_ifd_privkey(card, &ifd_privkey);
1401
0
  if (res != SC_SUCCESS) {
1402
0
    msg = "Cannot retrieve IFD private key from provider";
1403
0
    res = SC_ERROR_SM_NO_SESSION_KEYS;
1404
0
    goto csc_end;
1405
0
  }
1406
1407
  /* verify received signature */
1408
0
  sc_log(ctx, "Verify Internal Auth command response");
1409
0
  res = cwa_verify_internal_auth(card, icc_pubkey,  /* evaluated icc public key */
1410
0
               ifd_privkey, /* evaluated from DGP's Manual Annex 3 Data */
1411
0
               rndbuf,  /* RND.IFD || SN.IFD */
1412
0
               16,  /* rndbuf length; should be 16 */
1413
0
               sig, 128
1414
0
      );
1415
0
  if (res != SC_SUCCESS) {
1416
0
    msg = "Internal Auth Verify failed";
1417
0
    goto csc_end;
1418
0
  }
1419
1420
  /* get challenge: retrieve 8 random bytes from card */
1421
0
  sc_log(ctx, "Step 8.4.1.11: Prepare External Auth: Get Challenge");
1422
0
  res = sc_get_challenge(card, sm->icc.rnd, sizeof(sm->icc.rnd));
1423
0
  if (res != SC_SUCCESS) {
1424
0
    msg = "Get Challenge failed";
1425
0
    goto csc_end;
1426
0
  }
1427
1428
  /* compose signature data for external auth */
1429
0
  res = cwa_prepare_external_auth(card, icc_pubkey, ifd_privkey, sig, 128);
1430
0
  if (res != SC_SUCCESS) {
1431
0
    msg = "Prepare external auth failed";
1432
0
    goto csc_end;
1433
0
  }
1434
1435
  /* External (IFD)  authentication */
1436
0
  sc_log(ctx, "Step 8.4.1.12: Perform External (IFD) Authentication");
1437
0
  res = cwa_external_auth(card, sig, 128);
1438
0
  if (res != SC_SUCCESS) {
1439
0
    msg = "External auth cmd failed";
1440
0
    goto csc_end;
1441
0
  }
1442
1443
  /* Session key generation */
1444
0
  sc_log(ctx, "Step 8.4.2: Compute Session Keys");
1445
0
  res = cwa_compute_session_keys(card);
1446
0
  if (res != SC_SUCCESS) {
1447
0
    msg = "Session Key generation failed";
1448
0
    goto csc_end;
1449
0
  }
1450
1451
  /* call provider post-operation method */
1452
0
  sc_log(ctx, "CreateSecureChannel post-operations");
1453
0
  if (provider->cwa_create_post_ops) {
1454
0
    res = provider->cwa_create_post_ops(card, provider);
1455
0
    if (res != SC_SUCCESS) {
1456
0
      sc_log(ctx, "Create SM: provider post_ops() failed");
1457
0
      goto csc_end;
1458
0
    }
1459
0
  }
1460
1461
  /* arriving here means ok: cleanup */
1462
0
  res = SC_SUCCESS;
1463
0
 csc_end:
1464
0
  free(tlv);
1465
0
  X509_free(icc_cert);
1466
0
  X509_free(ca_cert);
1467
0
  EVP_PKEY_free(icc_pubkey);
1468
0
  EVP_PKEY_free(ifd_privkey);
1469
  /* setup SM state according result */
1470
0
  if (res != SC_SUCCESS) {
1471
0
    sc_log(ctx, "%s", msg);
1472
0
    card->sm_ctx.sm_mode = SM_MODE_NONE;
1473
0
  } else {
1474
0
    card->sm_ctx.sm_mode = SM_MODE_TRANSMIT;
1475
0
  }
1476
0
  LOG_FUNC_RETURN(ctx, res);
1477
0
}
1478
1479
/******************* SM internal APDU encoding / decoding functions ******/
1480
1481
/**
1482
 * Encode an APDU.
1483
 *
1484
 * Calling this functions means that It's has been verified
1485
 * That source apdu needs encoding
1486
 * Based on section 9 of CWA-14890 and Sect 6 of iso7816-4 standards
1487
 * And DNIe's manual
1488
 *
1489
 * @param card card info structure
1490
 * @param sm Secure Messaging state information
1491
 * @param from APDU to be encoded
1492
 * @param to where to store encoded apdu
1493
 * @return SC_SUCCESS if ok; else error code
1494
 */
1495
int cwa_encode_apdu(sc_card_t * card,
1496
        cwa_provider_t * provider, sc_apdu_t * from, sc_apdu_t * to)
1497
0
{
1498
0
  u8 *apdubuf = NULL;   /* to store resulting apdu */
1499
0
  size_t apdulen, tlv_len;
1500
0
  u8 *ccbuf = NULL;   /* where to store data to eval cryptographic checksum CC */
1501
0
  size_t cclen = 0;
1502
0
  u8 macbuf[8];   /* to store and compute CC */
1503
0
  char *msg = NULL;
1504
1505
0
  size_t i, j;    /* for xor loops */
1506
0
  int res = SC_SUCCESS;
1507
0
  sc_context_t *ctx = NULL;
1508
0
  struct sm_cwa_session * sm_session = &card->sm_ctx.info.session.cwa;
1509
0
  u8 *msgbuf = NULL; /* to encrypt apdu data */
1510
0
  u8 *cryptbuf = NULL;
1511
1512
0
  EVP_CIPHER_CTX *cctx = NULL;
1513
0
  EVP_CIPHER *alg = NULL;
1514
0
  unsigned char *key = NULL;
1515
0
  int tmplen = 0;
1516
1517
  /* mandatory check */
1518
0
  if (!card || !card->ctx || !provider)
1519
0
    return SC_ERROR_INVALID_ARGUMENTS;
1520
0
  ctx = card->ctx;
1521
1522
0
  LOG_FUNC_CALLED(ctx);
1523
  /* check remaining arguments */
1524
0
  if (!from || !to || !sm_session)
1525
0
    LOG_FUNC_RETURN(ctx, SC_ERROR_SM_NOT_INITIALIZED);
1526
0
  if (card->sm_ctx.sm_mode != SM_MODE_TRANSMIT)
1527
0
    LOG_FUNC_RETURN(ctx, SC_ERROR_SM_INVALID_LEVEL);
1528
1529
  /* reserve extra bytes for padding and tlv header */
1530
0
  msgbuf = calloc(12 + from->lc, sizeof(u8)); /* to encrypt apdu data */
1531
0
  cryptbuf = calloc(12 + from->lc, sizeof(u8));
1532
0
  if (!msgbuf || !cryptbuf) {
1533
0
    res = SC_ERROR_OUT_OF_MEMORY;
1534
0
    goto err;
1535
0
  }
1536
1537
  /* check if APDU is already encoded */
1538
0
  if ((from->cla & 0x0C) != 0) {
1539
0
    memcpy(to, from, sizeof(sc_apdu_t));
1540
0
    res = SC_SUCCESS; /* already encoded */
1541
0
    goto encode_end;
1542
0
  }
1543
0
  if (from->ins == 0xC0) {
1544
0
    memcpy(to, from, sizeof(sc_apdu_t));
1545
0
    res = SC_SUCCESS; /* dont encode GET Response cmd */
1546
0
    goto encode_end;
1547
0
  }
1548
1549
  /* trace APDU before encoding process */
1550
0
  cwa_trace_apdu(card, from, 0);
1551
1552
  /* reserve enough space for apdulen+tlv bytes
1553
   * to-be-crypted buffer and result apdu buffer */
1554
   /* TODO DEE add 4 more bytes for testing.... */
1555
0
  apdubuf = calloc(MAX(SC_MAX_APDU_BUFFER_SIZE, 20 + from->datalen),
1556
0
       sizeof(u8));
1557
0
  ccbuf = calloc(MAX(SC_MAX_APDU_BUFFER_SIZE, 20 + from->datalen),
1558
0
       sizeof(u8));
1559
  /* always create a new buffer for the encoded response */
1560
0
  to->resp = calloc(MAX_RESP_BUFFER_SIZE, sizeof(u8));
1561
0
  to->resplen = MAX_RESP_BUFFER_SIZE;
1562
0
  if (!apdubuf || !ccbuf || (!from->resp && !to->resp)) {
1563
0
    res = SC_ERROR_OUT_OF_MEMORY;
1564
0
    goto err;
1565
0
  }
1566
1567
  /* set up data on destination apdu */
1568
0
  to->cse = SC_APDU_CASE_4_SHORT;
1569
0
  to->cla = from->cla | 0x0C; /* mark apdu as encoded */
1570
0
  to->ins = from->ins;
1571
0
  to->p1 = from->p1;
1572
0
  to->p2 = from->p2;
1573
0
  to->le = from->le;
1574
0
  if (!to->le)
1575
0
    to->le = 255;
1576
0
  to->lc = 0;   /* to be evaluated */
1577
  /* fill buffer with header info */
1578
0
  *(ccbuf + cclen++) = to->cla;
1579
0
  *(ccbuf + cclen++) = to->ins;
1580
0
  *(ccbuf + cclen++) = to->p1;
1581
0
  *(ccbuf + cclen++) = to->p2;
1582
0
  cwa_iso7816_padding(ccbuf, &cclen); /* pad header (4 bytes pad) */
1583
1584
0
  if (!(cctx = EVP_CIPHER_CTX_new())) {
1585
0
    res = SC_ERROR_INTERNAL;
1586
0
    goto err;
1587
0
  }
1588
1589
  /* if no data, skip data encryption step */
1590
0
  if (from->lc != 0) {
1591
0
    unsigned char iv[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
1592
0
    int dlen = (int)from->lc;
1593
0
    size_t len = dlen;
1594
1595
    /* pad message */
1596
0
    memcpy(msgbuf, from->data, dlen);
1597
0
    cwa_iso7816_padding(msgbuf, &len);
1598
0
    dlen = (int)len;
1599
1600
    /* start kriptbuff with iso padding indicator */
1601
0
    *cryptbuf = 0x01;
1602
0
    key = sm_session->session_enc;
1603
1604
0
    alg = sc_evp_cipher(card->ctx, "DES-EDE-CBC");
1605
1606
0
    if (!alg ||
1607
0
        EVP_EncryptInit_ex(cctx, alg, NULL, key, iv) != 1 ||
1608
0
        EVP_CIPHER_CTX_set_padding(cctx, 0) != 1 ||
1609
0
        EVP_EncryptUpdate(cctx, cryptbuf + 1, &dlen, msgbuf, dlen) != 1 ||
1610
0
        EVP_EncryptFinal_ex(cctx, cryptbuf + 1 + dlen, &tmplen) != 1) {
1611
0
      msg = "Error in encrypting APDU";
1612
0
      res = SC_ERROR_INTERNAL;
1613
0
      goto encode_end;
1614
0
    }
1615
0
    dlen += tmplen;
1616
1617
    /* compose data TLV and add to result buffer */
1618
0
    res = cwa_compose_tlv(card, 0x87, dlen + 1, cryptbuf, &ccbuf, &cclen);
1619
0
    if (res != SC_SUCCESS) {
1620
0
      msg = "Error in compose tag 8x87 TLV";
1621
0
      goto encode_end;
1622
0
    }
1623
0
  } else if ((0xff & from->le) > 0) {
1624
    /* if le byte is declared, compose and add Le TLV */
1625
    /* FIXME: For DNIe we must not send the le bytes
1626
       when le == 256 but this goes against the standard
1627
       and might break other cards reusing this code */
1628
    /* NOTE: In FNMT MultiPKCS11 code this is an if, i.e.,
1629
       the le is only sent if no data (lc) is set.
1630
       In DNIe 3.0 pin verification sending both TLV return
1631
       69 88 "SM Data Object incorrect". For the moment it is
1632
       fixed sendind le=0 in pin verification apdu */
1633
0
    u8 le = 0xff & from->le;
1634
0
    res = cwa_compose_tlv(card, 0x97, 1, &le, &ccbuf, &cclen);
1635
0
    if (res != SC_SUCCESS) {
1636
0
      msg = "Encode APDU compose_tlv(0x97) failed";
1637
0
      goto encode_end;
1638
0
    }
1639
0
  }
1640
  /* copy current data to apdu buffer (skip header and header padding) */
1641
0
  if (cclen < 8) {
1642
0
    res = SC_ERROR_INTERNAL;
1643
0
    msg = "Incorrect checksum length";
1644
0
    goto encode_end;
1645
0
  }
1646
0
  memcpy(apdubuf, ccbuf + 8, cclen - 8);
1647
0
  apdulen = cclen - 8;
1648
  /* pad again ccbuffer to compute CC */
1649
0
  cwa_iso7816_padding(ccbuf, &cclen);
1650
1651
  /* sc_log(ctx,"data to compose mac: %s",sc_dump_hex(ccbuf,cclen)); */
1652
  /* compute MAC Cryptographic Checksum using kmac and increased SSC */
1653
0
  res = cwa_increase_ssc(card); /* increase send sequence counter */
1654
0
  if (res != SC_SUCCESS) {
1655
0
    msg = "Error in computing SSC";
1656
0
    goto encode_end;
1657
0
  }
1658
1659
0
  memcpy(macbuf, sm_session->ssc, 8); /* start with computed SSC */
1660
1661
0
  tmplen = 0;
1662
0
  key = sm_session->session_mac;
1663
1664
0
  sc_evp_cipher_free(alg);
1665
0
  alg = sc_evp_cipher(card->ctx, "DES-ECB");
1666
0
  if (!alg ||
1667
0
      EVP_EncryptInit_ex(cctx, alg, NULL, key, NULL) != 1 ||
1668
0
      EVP_CIPHER_CTX_set_padding(cctx, 0) != 1) {
1669
0
    msg = "Error in DES ECB encryption";
1670
0
    res = SC_ERROR_INTERNAL;
1671
0
    goto encode_end;
1672
0
  }
1673
1674
0
  for (i = 0; i < cclen; i += 8) { /* divide data in 8 byte blocks */
1675
    /* compute DES */
1676
0
    if (EVP_EncryptUpdate(cctx, macbuf, &tmplen, macbuf , 8) != 1) {
1677
0
      msg = "Error in DES ECB encryption";
1678
0
      res = SC_ERROR_INTERNAL;
1679
0
      goto encode_end;
1680
0
    }
1681
    /* XOR with next data and repeat */
1682
0
    for (j = 0; j < 8; j++)
1683
0
      macbuf[j] ^= ccbuf[i + j];
1684
0
  }
1685
0
  if (EVP_EncryptFinal_ex(cctx, macbuf + tmplen, &tmplen) != 1) {
1686
0
    msg = "Error in DES ECB encryption";
1687
0
    res = SC_ERROR_INTERNAL;
1688
0
    goto encode_end;
1689
0
  }
1690
1691
  /* and apply 3DES to result */
1692
0
  sc_evp_cipher_free(alg);
1693
0
  alg = sc_evp_cipher(card->ctx, "DES-EDE-ECB");
1694
1695
0
  if (!alg ||
1696
0
      EVP_EncryptInit_ex(cctx, alg, NULL, key, NULL) != 1 ||
1697
0
      EVP_CIPHER_CTX_set_padding(cctx, 0) != 1 ||
1698
0
      EVP_EncryptUpdate(cctx, macbuf, &tmplen, macbuf, 8) != 1 ||
1699
0
      EVP_EncryptFinal_ex(cctx, macbuf + tmplen, &tmplen) != 1) {
1700
0
    msg = "Error in 3DEC ECB encryption";
1701
0
    res = SC_ERROR_INTERNAL;
1702
0
    goto encode_end;
1703
0
  }
1704
1705
  /* compose and add computed MAC TLV to result buffer */
1706
0
  tlv_len = (card->atr.len > 15 && card->atr.value[15] >= DNIE_30_VERSION) ? 8 : 4;
1707
0
  sc_log(ctx, "Using TLV length: %zu", tlv_len);
1708
0
  res = cwa_compose_tlv(card, 0x8E, tlv_len, macbuf, &apdubuf, &apdulen);
1709
0
  if (res != SC_SUCCESS) {
1710
0
    msg = "Encode APDU compose_tlv(0x87) failed";
1711
0
    goto encode_end;
1712
0
  }
1713
1714
  /* rewrite resulting APDU */
1715
0
  to->lc = apdulen;
1716
0
  to->data = apdubuf;
1717
0
  to->datalen = apdulen;
1718
1719
  /* that's all folks */
1720
0
  res = SC_SUCCESS;
1721
0
  goto encode_end_apdu_valid;
1722
1723
0
err:
1724
0
encode_end:
1725
0
  free(apdubuf);
1726
0
  if (from->resp != to->resp) {
1727
0
    free(to->resp);
1728
0
    to->resp = NULL;
1729
0
  }
1730
0
encode_end_apdu_valid:
1731
0
  sc_evp_cipher_free(alg);
1732
0
  EVP_CIPHER_CTX_free(cctx);
1733
0
  if (msg) {
1734
0
    sc_log_openssl(ctx);
1735
0
    sc_log(ctx, "%s", msg);
1736
0
  }
1737
0
  free(msgbuf);
1738
0
  free(cryptbuf);
1739
0
  free(ccbuf);
1740
0
  LOG_FUNC_RETURN(ctx, res);
1741
0
}
1742
1743
/**
1744
 * Decode an APDU response.
1745
 *
1746
 * Calling this functions means that It's has been verified
1747
 * That apdu response comes in TLV encoded format and needs decoding
1748
 * Based on section 9 of CWA-14890 and Sect 6 of iso7816-4 standards
1749
 * And DNIe's manual
1750
 *
1751
 * @param card card info structure
1752
 * @param sm Secure Messaging state information
1753
 * @param from APDU with response to be decoded
1754
 * @param to where to store decoded apdu
1755
 * @return SC_SUCCESS if ok; else error code
1756
 */
1757
int cwa_decode_response(sc_card_t * card,
1758
      cwa_provider_t * provider,
1759
      sc_apdu_t * apdu)
1760
0
{
1761
0
  size_t i, j, tlv_len;
1762
0
  cwa_tlv_t tlv_array[4];
1763
0
  cwa_tlv_t *p_tlv = &tlv_array[0]; /* to store plain data (Tag 0x81) */
1764
0
  cwa_tlv_t *e_tlv = &tlv_array[1]; /* to store pad encoded data (Tag 0x87) */
1765
0
  cwa_tlv_t *m_tlv = &tlv_array[2]; /* to store mac CC (Tag 0x8E) */
1766
0
  cwa_tlv_t *s_tlv = &tlv_array[3]; /* to store sw1-sw2 status (Tag 0x99) */
1767
0
  u8 *buffer = NULL; /* buffer for data. pointers to this buffer are in tlv_array */
1768
0
  u8 *ccbuf = NULL; /* buffer for mac CC calculation */
1769
0
  size_t cclen = 0; /* ccbuf len */
1770
0
  u8 macbuf[8];   /* where to calculate mac */
1771
0
  size_t resplen = 0; /* respbuf length */
1772
0
  int res = SC_SUCCESS;
1773
0
  char *msg = NULL; /* to store error messages */
1774
0
  sc_context_t *ctx = NULL;
1775
0
  struct sm_cwa_session * sm_session = &card->sm_ctx.info.session.cwa;
1776
1777
0
  EVP_CIPHER_CTX *cctx = NULL;
1778
0
  EVP_CIPHER *alg = NULL;
1779
0
  unsigned char *key = NULL;
1780
0
  int tmplen = 0;
1781
1782
0
  if ((cctx = EVP_CIPHER_CTX_new()) == NULL) {
1783
0
    sc_log_openssl(ctx);
1784
0
    return SC_ERROR_INTERNAL;
1785
0
  }
1786
1787
  /* mandatory check */
1788
0
  if (!card || !card->ctx || !provider)
1789
0
    return SC_ERROR_INVALID_ARGUMENTS;
1790
0
  ctx = card->ctx;
1791
1792
0
  LOG_FUNC_CALLED(ctx);
1793
  /* check remaining arguments */
1794
0
  if ((apdu == NULL) || (sm_session == NULL))
1795
0
    LOG_FUNC_RETURN(ctx, SC_ERROR_SM_NOT_INITIALIZED);
1796
0
  if (card->sm_ctx.sm_mode != SM_MODE_TRANSMIT)
1797
0
    LOG_FUNC_RETURN(ctx, SC_ERROR_SM_INVALID_LEVEL);
1798
1799
  /* cwa14890 sect 9.3: check SW1 or SW2 for SM related errors */
1800
0
  if (apdu->sw1 == 0x69) {
1801
0
    if ((apdu->sw2 == 0x88) || (apdu->sw2 == 0x87)) {
1802
      /* configure the driver to re-establish the SM */
1803
0
      msg = "SM related errors in APDU response";
1804
0
      cwa_create_secure_channel(card, provider, CWA_SM_OFF);
1805
0
      res = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
1806
0
      goto response_decode_end;
1807
0
    }
1808
0
  }
1809
  /* if response is null/empty assume unencoded apdu */
1810
0
  if (!apdu->resp || (apdu->resplen == 0)) {
1811
0
    sc_log(ctx, "Empty APDU response: assume not cwa encoded");
1812
0
    return SC_SUCCESS;
1813
0
  }
1814
  /* checks if apdu response needs decoding by checking tags in response */
1815
0
  switch (*apdu->resp) {
1816
0
  case CWA_SM_PLAIN_TAG:
1817
0
  case CWA_SM_CRYPTO_TAG:
1818
0
  case CWA_SM_MAC_TAG:
1819
0
  case CWA_SM_LE_TAG:
1820
0
  case CWA_SM_STATUS_TAG:
1821
0
    break;    /* cwa tags found: continue decoding */
1822
0
  default:    /* else apdu response seems not to be cwa encoded */
1823
0
    sc_log(card->ctx, "APDU Response seems not to be cwa encoded");
1824
0
    return SC_SUCCESS; /* let process continue */
1825
0
  }
1826
1827
  /* parse response to find TLV's data and check results */
1828
0
  memset(tlv_array, 0, 4 * sizeof(cwa_tlv_t));
1829
  /* create buffer and copy data into */
1830
0
  buffer = calloc(apdu->resplen, sizeof(u8));
1831
0
  if (!buffer) {
1832
0
    msg = "Cannot allocate space for response buffer";
1833
0
    res = SC_ERROR_OUT_OF_MEMORY;
1834
0
    goto response_decode_end;
1835
0
  }
1836
0
  memcpy(buffer, apdu->resp, apdu->resplen);
1837
1838
0
  res = cwa_parse_tlv(card, buffer, apdu->resplen, tlv_array);
1839
0
  if (res != SC_SUCCESS) {
1840
0
    msg = "Error in TLV parsing";
1841
0
    goto response_decode_end;
1842
0
  }
1843
1844
  /* check consistency of received TLV's */
1845
0
  if (p_tlv->buf && e_tlv->buf) {
1846
0
    msg =
1847
0
        "Plain and Encoded data are mutually exclusive in apdu response";
1848
0
    res = SC_ERROR_INVALID_DATA;
1849
0
    goto response_decode_end;
1850
0
  }
1851
0
  if (!m_tlv->buf) {
1852
0
    msg = "No MAC TAG found in apdu response";
1853
0
    res = SC_ERROR_INVALID_DATA;
1854
0
    goto response_decode_end;
1855
0
  }
1856
0
  tlv_len = (card->atr.len > 15 && card->atr.value[15] >= DNIE_30_VERSION) ? 8 : 4;
1857
0
  if (m_tlv->len != tlv_len) {
1858
0
    msg = "Invalid MAC TAG Length";
1859
0
    res = SC_ERROR_INVALID_DATA;
1860
0
    goto response_decode_end;
1861
0
  }
1862
1863
  /* compose buffer to evaluate mac */
1864
1865
  /* reserve enough space for data+status+padding */
1866
0
  ccbuf =
1867
0
      calloc(e_tlv->buflen + s_tlv->buflen + p_tlv->buflen + 8,
1868
0
       sizeof(u8));
1869
0
  if (!ccbuf) {
1870
0
    msg = "Cannot allocate space for mac checking";
1871
0
    res = SC_ERROR_OUT_OF_MEMORY;
1872
0
    goto response_decode_end;
1873
0
  }
1874
  /* copy data into buffer */
1875
0
  cclen = 0;
1876
0
  if (e_tlv->buf) { /* encoded data */
1877
0
    memcpy(ccbuf, e_tlv->buf, e_tlv->buflen);
1878
0
    cclen = e_tlv->buflen;
1879
0
  }
1880
0
  if (p_tlv->buf) { /* plain data */
1881
0
    memcpy(ccbuf, p_tlv->buf, p_tlv->buflen);
1882
0
    cclen += p_tlv->buflen;
1883
0
  }
1884
0
  if (s_tlv->buf) { /* response status */
1885
0
    if (s_tlv->len != 2) {
1886
0
      msg = "Invalid SW TAG length";
1887
0
      res = SC_ERROR_INVALID_DATA;
1888
0
      goto response_decode_end;
1889
0
    }
1890
0
    memcpy(ccbuf + cclen, s_tlv->buf, s_tlv->buflen);
1891
0
    cclen += s_tlv->buflen;
1892
0
    apdu->sw1 = s_tlv->data[0];
1893
0
    apdu->sw2 = s_tlv->data[1];
1894
0
  }    /* if no response status tag, use sw1 and sw2 from apdu */
1895
  /* add iso7816 padding */
1896
0
  cwa_iso7816_padding(ccbuf, &cclen);
1897
1898
  /* evaluate mac by mean of kmac and increased SendSequence Counter SSC */
1899
1900
  /* increase SSC */
1901
0
  res = cwa_increase_ssc(card); /* increase send sequence counter */
1902
0
  if (res != SC_SUCCESS) {
1903
0
    msg = "Error in computing SSC";
1904
0
    goto response_decode_end;
1905
0
  }
1906
  /* set up key for mac computing */
1907
0
  key = sm_session->session_mac;
1908
1909
0
  alg = sc_evp_cipher(card->ctx, "DES-ECB");
1910
0
  if (!alg ||
1911
0
      EVP_EncryptInit_ex(cctx, alg, NULL, key, NULL) != 1 ||
1912
0
      EVP_CIPHER_CTX_set_padding(cctx, 0) != 1) {
1913
0
    sc_log_openssl(ctx);
1914
0
    msg = "Error in DES ECB encryption";
1915
0
    res = SC_ERROR_INTERNAL;
1916
0
    goto response_decode_end;
1917
0
  }
1918
1919
0
  memcpy(macbuf, sm_session->ssc, 8); /* start with computed SSC */
1920
0
  for (i = 0; i < cclen; i += 8) { /* divide data in 8 byte blocks */
1921
    /* compute DES */
1922
0
    if (EVP_EncryptUpdate(cctx, macbuf, &tmplen, macbuf, 8) != 1) {
1923
0
      sc_log_openssl(ctx);
1924
0
      msg = "Error in DES ECB encryption";
1925
0
      res = SC_ERROR_INTERNAL;
1926
0
      goto response_decode_end;
1927
0
    }
1928
    /* XOR with data and repeat */
1929
0
    for (j = 0; j < 8; j++)
1930
0
      macbuf[j] ^= ccbuf[i + j];
1931
0
  }
1932
0
  if (EVP_EncryptFinal_ex(cctx, macbuf + tmplen, &tmplen) != 1) {
1933
0
    sc_log_openssl(ctx);
1934
0
    msg = "Error in DES ECB encryption";
1935
0
    res = SC_ERROR_INTERNAL;
1936
0
    goto response_decode_end;
1937
0
  }
1938
1939
  /* finally apply 3DES to result */
1940
0
  sc_evp_cipher_free(alg);
1941
0
  alg = sc_evp_cipher(card->ctx, "DES-EDE-ECB");
1942
1943
0
  if (!alg ||
1944
0
      EVP_EncryptInit_ex(cctx, alg, NULL, key, NULL) != 1 ||
1945
0
      EVP_CIPHER_CTX_set_padding(cctx, 0) != 1 ||
1946
0
      EVP_EncryptUpdate(cctx, macbuf, &tmplen, macbuf, 8) != 1 ||
1947
0
      EVP_EncryptFinal_ex(cctx, macbuf + tmplen, &tmplen) != 1) {
1948
0
    sc_log_openssl(ctx);
1949
0
    msg = "Error in 3DEC ECB encryption";
1950
0
    res = SC_ERROR_INTERNAL;
1951
0
    goto response_decode_end;
1952
0
  }
1953
1954
  /* check evaluated mac with provided by apdu response */
1955
1956
0
  res = memcmp(m_tlv->data, macbuf, 4); /* check first 4 bytes */
1957
0
  if (res != 0) {
1958
0
    msg = "Error in MAC CC checking: value doesn't match";
1959
0
    res = SC_ERROR_SM_ENCRYPT_FAILED;
1960
0
    goto response_decode_end;
1961
0
  }
1962
1963
  /* allocate response buffer */
1964
0
  resplen = 10 + MAX(p_tlv->len, e_tlv->len); /* estimate response buflen */
1965
0
  if ((p_tlv->buf || e_tlv->buf) && (!apdu->resp || apdu->resplen < resplen)) {
1966
0
    msg = "Cannot allocate buffer to store response";
1967
0
    res = SC_ERROR_BUFFER_TOO_SMALL;
1968
0
    goto response_decode_end;
1969
0
  }
1970
0
  apdu->resplen = resplen;
1971
1972
  /* fill destination response apdu buffer with data */
1973
1974
  /* if plain data, just copy TLV data into apdu response */
1975
0
  if (p_tlv->buf) { /* plain data */
1976
0
    memcpy(apdu->resp, p_tlv->data, p_tlv->len);
1977
0
    apdu->resplen = p_tlv->len;
1978
0
  }
1979
1980
  /* if encoded data, decode and store into apdu response */
1981
0
  else if (e_tlv->buf) { /* encoded data */
1982
0
    unsigned char iv[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
1983
0
    int dlen = (int)apdu->resplen;
1984
    /* check data len */
1985
0
    if ((e_tlv->len < 9) || ((e_tlv->len - 1) % 8) != 0) {
1986
0
      msg = "Invalid length for Encoded data TLV";
1987
0
      res = SC_ERROR_INVALID_DATA;
1988
0
      goto response_decode_end;
1989
0
    }
1990
    /* first byte is padding info; check value */
1991
0
    if (e_tlv->data[0] != 0x01) {
1992
0
      msg = "Encoded TLV: Invalid padding info value";
1993
0
      res = SC_ERROR_INVALID_DATA;
1994
0
      goto response_decode_end;
1995
0
    }
1996
    /* prepare keys to decode */
1997
0
    key = sm_session->session_enc;
1998
1999
    /* decrypt into response buffer
2000
     * by using 3DES CBC by mean of kenc and iv={0,...0} */
2001
0
    sc_evp_cipher_free(alg);
2002
0
    alg = sc_evp_cipher(card->ctx, "DES-EDE-CBC");
2003
2004
0
    if (!alg ||
2005
0
        EVP_DecryptInit_ex(cctx, alg, NULL, key, iv) != 1 ||
2006
0
        EVP_CIPHER_CTX_set_padding(cctx, 0) != 1 ||
2007
0
        EVP_DecryptUpdate(cctx, apdu->resp, &dlen, &e_tlv->data[1], (int)(e_tlv->len - 1)) != 1 ||
2008
0
        EVP_DecryptFinal_ex(cctx, apdu->resp + dlen, &tmplen) != 1) {
2009
0
      sc_log_openssl(ctx);
2010
0
      res = SC_ERROR_INTERNAL;
2011
0
      msg = "Can not decrypt 3DES CBC";
2012
0
      goto response_decode_end;
2013
0
    }
2014
0
    apdu->resplen = dlen + tmplen;
2015
2016
    /* remove iso padding from response length */
2017
0
    for (; (apdu->resplen > 0) && *(apdu->resp + apdu->resplen - 1) == 0x00; apdu->resplen--) ;  /* empty loop */
2018
2019
0
    if (apdu->resplen == 0 || *(apdu->resp + apdu->resplen - 1) != 0x80) { /* check padding byte */
2020
0
      msg = "Decrypted TLV has no 0x80 iso padding indicator!";
2021
0
      res = SC_ERROR_INVALID_DATA;
2022
0
      goto response_decode_end;
2023
0
    }
2024
    /* everything ok: remove ending 0x80 from response */
2025
0
    apdu->resplen--;
2026
0
  }
2027
2028
0
  else
2029
0
    apdu->resplen = 0; /* neither plain, nor encoded data */
2030
2031
  /* that's all folks */
2032
0
  res = SC_SUCCESS;
2033
2034
0
 response_decode_end:
2035
0
  sc_evp_cipher_free(alg);
2036
0
  EVP_CIPHER_CTX_free(cctx);
2037
0
  free(buffer);
2038
0
  free(ccbuf);
2039
0
  if (msg) {
2040
0
    sc_log(ctx, "%s", msg);
2041
0
  } else {
2042
0
    cwa_trace_apdu(card, apdu, 1);
2043
0
  }      /* trace apdu response */
2044
0
  LOG_FUNC_RETURN(ctx, res);
2045
0
}
2046
2047
/********************* default provider for cwa14890 ****************/
2048
2049
/* pre and post operations */
2050
2051
static int default_create_pre_ops(sc_card_t * card, cwa_provider_t * provider)
2052
0
{
2053
0
  return SC_SUCCESS;
2054
0
}
2055
2056
static int default_create_post_ops(sc_card_t * card, cwa_provider_t * provider)
2057
0
{
2058
0
  return SC_SUCCESS;
2059
0
}
2060
2061
static int default_get_root_ca_pubkey(sc_card_t * card, EVP_PKEY ** root_ca_key)
2062
0
{
2063
0
  return SC_ERROR_NOT_SUPPORTED;
2064
0
}
2065
2066
/* retrieve CVC intermediate CA certificate and length */
2067
static int default_get_cvc_ca_cert(sc_card_t * card, u8 ** cert,
2068
           size_t * length)
2069
0
{
2070
0
  return SC_ERROR_NOT_SUPPORTED;
2071
0
}
2072
2073
/* retrieve CVC IFD certificate and length */
2074
static int default_get_cvc_ifd_cert(sc_card_t * card, u8 ** cert,
2075
            size_t * length)
2076
0
{
2077
0
  return SC_ERROR_NOT_SUPPORTED;
2078
0
}
2079
2080
static int default_get_ifd_privkey(sc_card_t * card, EVP_PKEY ** ifd_privkey)
2081
0
{
2082
0
  return SC_ERROR_NOT_SUPPORTED;
2083
0
}
2084
2085
/* get ICC intermediate CA  path */
2086
static int default_get_icc_intermediate_ca_cert(sc_card_t * card, X509 ** cert)
2087
0
{
2088
0
  return SC_ERROR_NOT_SUPPORTED;
2089
0
}
2090
2091
/* get ICC certificate path */
2092
static int default_get_icc_cert(sc_card_t * card, X509 ** cert)
2093
0
{
2094
0
  return SC_ERROR_NOT_SUPPORTED;
2095
0
}
2096
2097
/* Retrieve key reference for Root CA to validate CVC intermediate CA certs */
2098
static int default_get_root_ca_pubkey_ref(sc_card_t * card, u8 ** buf,
2099
            size_t * len)
2100
0
{
2101
0
  return SC_ERROR_NOT_SUPPORTED;
2102
0
}
2103
2104
/* Retrieve key reference for intermediate CA to validate IFD certs */
2105
static int default_get_intermediate_ca_pubkey_ref(sc_card_t * card, u8 ** buf,
2106
              size_t * len)
2107
0
{
2108
0
  return SC_ERROR_NOT_SUPPORTED;
2109
0
}
2110
2111
/* Retrieve key reference for IFD certificate */
2112
static int default_get_ifd_pubkey_ref(sc_card_t * card, u8 ** buf, size_t * len)
2113
0
{
2114
0
  return SC_ERROR_NOT_SUPPORTED;
2115
0
}
2116
2117
/* Retrieve key reference for ICC privkey */
2118
static int default_get_icc_privkey_ref(sc_card_t * card, u8 ** buf,
2119
               size_t * len)
2120
0
{
2121
0
  return SC_ERROR_NOT_SUPPORTED;
2122
0
}
2123
2124
/* Retrieve SN.IFD (8 bytes left padded with zeroes if needed) */
2125
static int default_get_sn_ifd(sc_card_t * card)
2126
0
{
2127
0
  return SC_ERROR_NOT_SUPPORTED;
2128
0
}
2129
2130
/* Retrieve SN.ICC (8 bytes left padded with zeroes if needed) */
2131
static int default_get_sn_icc(sc_card_t * card)
2132
0
{
2133
0
  return SC_ERROR_NOT_SUPPORTED;
2134
0
}
2135
2136
static cwa_provider_t default_cwa_provider = {
2137
2138
    /************ data related with SM operations *************************/
2139
2140
    /************ operations related with secure channel creation *********/
2141
2142
  /* pre and post operations */
2143
  default_create_pre_ops,
2144
  default_create_post_ops,
2145
2146
  /* Get ICC intermediate CA  path */
2147
  default_get_icc_intermediate_ca_cert,
2148
  /* Get ICC certificate path */
2149
  default_get_icc_cert,
2150
2151
  /* Obtain RSA public key from RootCA */
2152
  default_get_root_ca_pubkey,
2153
  /* Obtain RSA IFD private key */
2154
  default_get_ifd_privkey,
2155
2156
  /* Retrieve CVC intermediate CA certificate and length */
2157
  default_get_cvc_ca_cert,
2158
  /* Retrieve CVC IFD certificate and length */
2159
  default_get_cvc_ifd_cert,
2160
2161
  /* Get public key references for Root CA to validate intermediate CA cert */
2162
  default_get_root_ca_pubkey_ref,
2163
2164
  /* Get public key reference for IFD intermediate CA certificate */
2165
  default_get_intermediate_ca_pubkey_ref,
2166
2167
  /* Get public key reference for IFD CVC certificate */
2168
  default_get_ifd_pubkey_ref,
2169
2170
  /* Get ICC private key reference */
2171
  default_get_icc_privkey_ref,
2172
2173
  /* Get IFD Serial Number */
2174
  default_get_sn_ifd,
2175
2176
  /* Get ICC Serial Number */
2177
  default_get_sn_icc,
2178
2179
2180
};
2181
2182
/**
2183
 * Get a copy of default cwa provider.
2184
 *
2185
 * @param card pointer to card info structure
2186
 * @return copy of default provider or null on error
2187
 */
2188
cwa_provider_t *cwa_get_default_provider(sc_card_t * card)
2189
468
{
2190
468
  cwa_provider_t *res = NULL;
2191
468
  if (!card || !card->ctx)
2192
0
    return NULL;
2193
468
  LOG_FUNC_CALLED(card->ctx);
2194
468
  res = calloc(1, sizeof(cwa_provider_t));
2195
468
  if (!res) {
2196
0
    sc_log(card->ctx, "Cannot allocate space for cwa_provider");
2197
0
    return NULL;
2198
0
  }
2199
468
  memcpy(res, &default_cwa_provider, sizeof(cwa_provider_t));
2200
468
  return res;
2201
468
}
2202
2203
/* end of cwa14890.c */
2204
#undef __CWA14890_C__
2205
2206
#endif        /* ENABLE_OPENSSL */