Coverage Report

Created: 2025-07-01 06:08

/src/opensc/src/libopensc/card-cac.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * card-cac.c: Support for CAC from NIST SP800-73
3
 * card-default.c: Support for cards with no driver
4
 *
5
 * Copyright (C) 2001, 2002  Juha Yrjölä <juha.yrjola@iki.fi>
6
 * Copyright (C) 2005,2006,2007,2008,2009,2010 Douglas E. Engert <deengert@anl.gov>
7
 * Copyright (C) 2006, Identity Alliance, Thomas Harning <thomas.harning@identityalliance.com>
8
 * Copyright (C) 2007, EMC, Russell Larner <rlarner@rsa.com>
9
 * Copyright (C) 2016 - 2018, Red Hat, Inc.
10
 *
11
 * CAC driver author: Robert Relyea <rrelyea@redhat.com>
12
 * Further work: Jakub Jelen <jjelen@redhat.com>
13
 *
14
 * This library is free software; you can redistribute it and/or
15
 * modify it under the terms of the GNU Lesser General Public
16
 * License as published by the Free Software Foundation; either
17
 * version 2.1 of the License, or (at your option) any later version.
18
 *
19
 * This library is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22
 * Lesser General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU Lesser General Public
25
 * License along with this library; if not, write to the Free Software
26
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27
 */
28
29
#ifdef HAVE_CONFIG_H
30
#include "config.h"
31
#endif
32
33
#include <ctype.h>
34
#include <fcntl.h>
35
#include <limits.h>
36
#include <stdlib.h>
37
#include <string.h>
38
39
#ifdef _WIN32
40
#include <io.h>
41
#else
42
#include <unistd.h>
43
#endif
44
45
#ifdef ENABLE_OPENSSL
46
#include <openssl/sha.h>
47
#endif /* ENABLE_OPENSSL */
48
49
#include "internal.h"
50
#include "simpletlv.h"
51
#include "cardctl.h"
52
#include "iso7816.h"
53
#include "card-cac-common.h"
54
#include "pkcs15.h"
55
56
/*
57
 *  CAC hardware and APDU constants
58
 */
59
0
#define CAC_MAX_CHUNK_SIZE 240
60
0
#define CAC_INS_SIGN_DECRYPT          0x42  /* A crypto operation */
61
0
#define CAC_INS_READ_FILE             0x52  /* read a TL or V file */
62
0
#define CAC_INS_GET_ACR               0x4c
63
0
#define CAC_INS_GET_PROPERTIES        0x56
64
0
#define CAC_P1_STEP    0x80
65
0
#define CAC_P1_FINAL   0x00
66
0
#define CAC_FILE_TAG    1
67
0
#define CAC_FILE_VALUE  2
68
/* TAGS in a TL file */
69
0
#define CAC_TAG_CERTIFICATE           0x70
70
0
#define CAC_TAG_CERTINFO              0x71
71
0
#define CAC_TAG_MSCUID                0x72
72
0
#define CAC_TAG_CUID                  0xF0
73
0
#define CAC_TAG_CC_VERSION_NUMBER     0xF1
74
0
#define CAC_TAG_GRAMMAR_VERION_NUMBER 0xF2
75
0
#define CAC_TAG_CARDURL               0xF3
76
0
#define CAC_TAG_PKCS15                0xF4
77
0
#define CAC_TAG_ACCESS_CONTROL        0xF6
78
0
#define CAC_TAG_DATA_MODEL            0xF5
79
0
#define CAC_TAG_CARD_APDU             0xF7
80
0
#define CAC_TAG_REDIRECTION           0xFA
81
0
#define CAC_TAG_CAPABILITY_TUPLES     0xFB
82
0
#define CAC_TAG_STATUS_TUPLES         0xFC
83
0
#define CAC_TAG_NEXT_CCC              0xFD
84
0
#define CAC_TAG_ERROR_CODES           0xFE
85
0
#define CAC_TAG_APPLET_FAMILY         0x01
86
0
#define CAC_TAG_NUMBER_APPLETS        0x94
87
0
#define CAC_TAG_APPLET_ENTRY          0x93
88
#define CAC_TAG_APPLET_AID            0x92
89
0
#define CAC_TAG_APPLET_INFORMATION    0x01
90
0
#define CAC_TAG_NUMBER_OF_OBJECTS     0x40
91
0
#define CAC_TAG_TV_BUFFER             0x50
92
0
#define CAC_TAG_PKI_OBJECT            0x51
93
0
#define CAC_TAG_OBJECT_ID             0x41
94
0
#define CAC_TAG_BUFFER_PROPERTIES     0x42
95
0
#define CAC_TAG_PKI_PROPERTIES        0x43
96
97
0
#define CAC_APP_TYPE_GENERAL          0x01
98
0
#define CAC_APP_TYPE_SKI              0x02
99
0
#define CAC_APP_TYPE_PKI              0x04
100
101
#define CAC_ACR_ACR                   0x00
102
#define CAC_ACR_APPLET_OBJECT         0x10
103
#define CAC_ACR_AMP                   0x20
104
0
#define CAC_ACR_SERVICE               0x21
105
106
0
#define CAC_MAX_CCC_DEPTH             16
107
108
/* hardware data structures (returned in the CCC) */
109
/* part of the card_url */
110
typedef struct cac_access_profile {
111
  u8 GCACR_listID;
112
  u8 GCACR_readTagListACRID;
113
  u8 GCACR_updatevalueACRID;
114
  u8 GCACR_readvalueACRID;
115
  u8 GCACR_createACRID;
116
  u8 GCACR_deleteACRID;
117
  u8 CryptoACR_listID;
118
  u8 CryptoACR_getChallengeACRID;
119
  u8 CryptoACR_internalAuthenicateACRID;
120
  u8 CryptoACR_pkiComputeACRID;
121
  u8 CryptoACR_readTagListACRID;
122
  u8 CryptoACR_updatevalueACRID;
123
  u8 CryptoACR_readvalueACRID;
124
  u8 CryptoACR_createACRID;
125
  u8 CryptoACR_deleteACRID;
126
} cac_access_profile_t;
127
128
/* part of the card url */
129
typedef struct cac_access_key_info {
130
  u8  keyFileID[2];
131
  u8  keynumber;
132
} cac_access_key_info_t;
133
134
typedef struct cac_card_url {
135
  u8 rid[5];
136
  u8 cardApplicationType;
137
  u8 objectID[2];
138
  u8 applicationID[2];
139
  cac_access_profile_t accessProfile;
140
  u8 pinID;          /* not used for VM cards */
141
  cac_access_key_info_t accessKeyInfo; /* not used for VM cards */
142
  u8 keyCryptoAlgorithm;               /* not used for VM cards */
143
} cac_card_url_t;
144
145
0
#define CAC_MAX_OBJECTS 16
146
147
typedef struct {
148
  /* OID has two bytes */
149
  unsigned char oid[2];
150
  /* Format is NOT SimpleTLV? */
151
  unsigned char simpletlv;
152
  /* Is certificate object and private key is initialized */
153
  unsigned char privatekey;
154
} cac_properties_object_t;
155
156
typedef struct {
157
  size_t num_objects;
158
  cac_properties_object_t objects[CAC_MAX_OBJECTS];
159
} cac_properties_t;
160
161
/*
162
 * Flags for Current Selected Object Type
163
 *   CAC files are TLV files, with TL and V separated. For generic
164
 *   containers we reintegrate the TL anv V portions into a single
165
 *   file to read. Certs are also TLV files, but pkcs15 wants the
166
 *   actual certificate. At select time we know the patch which tells
167
 *   us what time of files we want to read. We remember that type
168
 *   so that read_binary can do the appropriate processing.
169
 */
170
0
#define CAC_OBJECT_TYPE_CERT    1
171
0
#define CAC_OBJECT_TYPE_TLV_FILE  4
172
0
#define CAC_OBJECT_TYPE_GENERIC   5
173
174
/*
175
 * Set up the normal CAC paths
176
 */
177
#define CAC_2_RID "\xA0\x00\x00\x01\x16"
178
179
static const sc_path_t cac_ACA_Path = {
180
  "", 0,
181
  0,0,SC_PATH_TYPE_DF_NAME,
182
  { CAC_TO_AID(CAC_1_RID "\x10\x00") }
183
};
184
185
static const sc_path_t cac_CCC_Path = {
186
  "", 0,
187
  0,0,SC_PATH_TYPE_DF_NAME,
188
  { CAC_TO_AID(CAC_2_RID "\xDB\x00") }
189
};
190
191
/*
192
 *  CAC general objects defined in 4.3.1.2 of CAC Applet Developer Guide Version 1.0.
193
 *   doubles as a source for CAC-2 labels.
194
 */
195
static const cac_object_t cac_objects[] = {
196
  { "Person Instance", 0x200, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
197
    { CAC_TO_AID(CAC_1_RID "\x02\x00") }}},
198
  { "Personnel", 0x201, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
199
    { CAC_TO_AID(CAC_1_RID "\x02\x01") }}},
200
  { "Benefits", 0x202, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
201
    { CAC_TO_AID(CAC_1_RID "\x02\x02") }}},
202
  { "Other Benefits", 0x203, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
203
    { CAC_TO_AID(CAC_1_RID "\x02\x03") }}},
204
  { "PKI Credential", 0x2FD, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
205
    { CAC_TO_AID(CAC_1_RID "\x02\xFD") }}},
206
  { "PKI Certificate", 0x2FE, { { 0 }, 0, 0, 0, SC_PATH_TYPE_DF_NAME,
207
    { CAC_TO_AID(CAC_1_RID "\x02\xFE") }}},
208
};
209
210
static const int cac_object_count = sizeof(cac_objects)/sizeof(cac_objects[0]);
211
212
/*
213
 * use the object id to find our object info on the object in our CAC-1 list
214
 */
215
static const cac_object_t *cac_find_obj_by_id(unsigned short object_id)
216
0
{
217
0
  int i;
218
219
0
  for (i = 0; i < cac_object_count; i++) {
220
0
    if (cac_objects[i].fd == object_id) {
221
0
      return &cac_objects[i];
222
0
    }
223
0
  }
224
0
  return NULL;
225
0
}
226
227
/*
228
 * Lookup the path in the pki list to see if it is a cert path
229
 */
230
static int cac_is_cert(cac_private_data_t * priv, const sc_path_t *in_path)
231
0
{
232
0
  cac_object_t test_obj;
233
0
  test_obj.path = *in_path;
234
0
  test_obj.path.index = 0;
235
0
  test_obj.path.count = 0;
236
237
0
  return (list_contains(&priv->pki_list, &test_obj) != 0);
238
0
}
239
240
/*
241
 * Send a command and receive data.
242
 *
243
 * A caller may provide a buffer, and length to read. If not provided,
244
 * an internal 4096 byte buffer is used, and a copy is returned to the
245
 * caller. that need to be freed by the caller.
246
 *
247
 * modelled after a similar function in card-piv.c
248
 */
249
250
static int cac_apdu_io(sc_card_t *card, int ins, int p1, int p2,
251
  const u8 * sendbuf, size_t sendbuflen, u8 ** recvbuf,
252
  size_t * recvbuflen)
253
0
{
254
0
  int r;
255
0
  sc_apdu_t apdu = {0};
256
0
  u8 rbufinitbuf[CAC_MAX_SIZE];
257
0
  u8 *rbuf;
258
0
  size_t rbuflen;
259
0
  unsigned int apdu_case = SC_APDU_CASE_1;
260
261
262
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
263
264
0
  sc_log(card->ctx,
265
0
     "%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n",
266
0
     ins, p1, p2, sendbuflen, card->max_send_size,
267
0
     card->max_recv_size);
268
269
0
  rbuf = rbufinitbuf;
270
0
  rbuflen = sizeof(rbufinitbuf);
271
272
  /* if caller provided a buffer and length */
273
0
  if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) {
274
0
    rbuf = *recvbuf;
275
0
    rbuflen = *recvbuflen;
276
0
  }
277
278
0
  if (recvbuf) {
279
0
    if (sendbuf)
280
0
      apdu_case = SC_APDU_CASE_4_SHORT;
281
0
    else
282
0
      apdu_case = SC_APDU_CASE_2_SHORT;
283
0
  } else if (sendbuf)
284
0
    apdu_case = SC_APDU_CASE_3_SHORT;
285
286
287
0
  sc_format_apdu(card, &apdu, apdu_case, ins, p1, p2);
288
289
0
  apdu.lc = sendbuflen;
290
0
  apdu.datalen = sendbuflen;
291
0
  apdu.data = sendbuf;
292
293
0
  if (recvbuf) {
294
0
    apdu.resp = rbuf;
295
0
    apdu.le = (rbuflen > 255) ? 255 : rbuflen;
296
0
    apdu.resplen = rbuflen;
297
0
  } else {
298
0
     apdu.resp =  rbuf;
299
0
     apdu.le = 0;
300
0
     apdu.resplen = 0;
301
0
  }
302
303
0
  sc_log(card->ctx,
304
0
     "calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p",
305
0
     apdu.flags, apdu.le, apdu.resplen, apdu.resp);
306
307
  /* with new adpu.c and chaining, this actually reads the whole object */
308
0
  r = sc_transmit_apdu(card, &apdu);
309
310
0
  sc_log(card->ctx,
311
0
     "result r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x",
312
0
     r, apdu.resplen, apdu.sw1, apdu.sw2);
313
0
  if (r < 0) {
314
0
    sc_log(card->ctx, "Transmit failed");
315
0
    goto err;
316
0
  }
317
318
0
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
319
320
0
  if (r < 0) {
321
0
    sc_log(card->ctx,  "Card returned error ");
322
0
    goto err;
323
0
  }
324
325
0
  if (recvbuflen) {
326
0
    if (recvbuf && *recvbuf == NULL) {
327
0
      *recvbuf =  malloc(apdu.resplen);
328
0
      if (*recvbuf == NULL) {
329
0
        r = SC_ERROR_OUT_OF_MEMORY;
330
0
        goto err;
331
0
      }
332
0
      memcpy(*recvbuf, rbuf, apdu.resplen);
333
0
    }
334
0
    *recvbuflen =  apdu.resplen;
335
0
    r = (int)*recvbuflen;
336
0
  }
337
338
0
err:
339
0
  LOG_FUNC_RETURN(card->ctx, r);
340
0
}
341
342
/*
343
 * Get ACR of currently ACA applet identified by the  acr_type
344
 * 5.3.3.5 Get ACR APDU
345
 */
346
static int
347
cac_get_acr(sc_card_t *card, int acr_type, u8 **out_buf, size_t *out_len)
348
0
{
349
0
  u8 *out = NULL;
350
  /* XXX assuming it will not be longer than 255 B */
351
0
  size_t len = 256;
352
0
  int r;
353
354
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
355
356
  /* for simplicity we support only ACR without arguments now */
357
0
  if (acr_type != 0x00 && acr_type != 0x10
358
0
      && acr_type != 0x20 && acr_type != 0x21) {
359
0
    return SC_ERROR_INVALID_ARGUMENTS;
360
0
  }
361
362
0
  r = cac_apdu_io(card, CAC_INS_GET_ACR, acr_type, 0, NULL, 0, &out, &len);
363
0
  if (len == 0) {
364
0
    r = SC_ERROR_FILE_NOT_FOUND;
365
0
  }
366
0
  if (r < 0)
367
0
    goto fail;
368
369
0
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
370
0
      "got %"SC_FORMAT_LEN_SIZE_T"u bytes out=%p", len, out);
371
372
0
  *out_len = len;
373
0
  *out_buf = out;
374
0
  return SC_SUCCESS;
375
376
0
fail:
377
0
  if (out)
378
0
    free(out);
379
0
  *out_buf = NULL;
380
0
  *out_len = 0;
381
0
  return r;
382
0
}
383
384
/*
385
 * Read a CAC TLV file. Parameters specify if the TLV file is TL (Tag/Length) file or a V (value) file
386
 */
387
0
#define HIGH_BYTE_OF_SHORT(x) (((x)>> 8) & 0xff)
388
0
#define LOW_BYTE_OF_SHORT(x) ((x) & 0xff)
389
static int cac_read_file(sc_card_t *card, int file_type, u8 **out_buf, size_t *out_len)
390
0
{
391
0
  u8 params[2];
392
0
  u8 count[2] = {0};
393
0
  u8 *out = NULL;
394
0
  u8 *out_ptr = NULL;
395
0
  size_t offset = 0;
396
0
  size_t size = 0;
397
0
  size_t left = 0;
398
0
  size_t len = 0;
399
0
  int r;
400
401
0
  params[0] = file_type;
402
0
  params[1] = 2;
403
404
  /* get the size */
405
0
  len = sizeof(count);
406
0
  out_ptr = count;
407
0
  r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len);
408
0
  if (len == 0) {
409
0
    r = SC_ERROR_FILE_NOT_FOUND;
410
0
  }
411
0
  if (r < 0)
412
0
    goto fail;
413
414
0
  left = size = lebytes2ushort(count);
415
0
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
416
0
     "got %"SC_FORMAT_LEN_SIZE_T"u bytes out_ptr=%p count&=%p count[0]=0x%02x count[1]=0x%02x, len=0x%04"SC_FORMAT_LEN_SIZE_T"x (%"SC_FORMAT_LEN_SIZE_T"u)",
417
0
     len, out_ptr, &count, count[0], count[1], size, size);
418
0
  out = out_ptr = malloc(size);
419
0
  if (out == NULL) {
420
0
    r = SC_ERROR_OUT_OF_MEMORY;
421
0
    goto fail;
422
0
  }
423
0
  for (offset += 2; left > 0; offset += len, left -= len, out_ptr += len) {
424
0
    len = MIN(left, CAC_MAX_CHUNK_SIZE);
425
0
    params[1] = len;
426
0
    r = cac_apdu_io(card, CAC_INS_READ_FILE, HIGH_BYTE_OF_SHORT(offset), LOW_BYTE_OF_SHORT(offset),
427
0
            &params[0], sizeof(params), &out_ptr, &len);
428
    /* if there is no data, assume there is no file */
429
0
    if (len == 0) {
430
0
      r = SC_ERROR_FILE_NOT_FOUND;
431
0
    }
432
0
    if (r < 0) {
433
0
      goto fail;
434
0
    }
435
0
  }
436
0
  *out_len = size;
437
0
  *out_buf = out;
438
0
  return SC_SUCCESS;
439
0
fail:
440
0
  if (out)
441
0
    free(out);
442
0
  *out_len = 0;
443
0
  return r;
444
0
}
445
446
447
/*
448
 * Callers of this may be expecting a certificate,
449
 * select file will have saved the object type for us
450
 * as well as set that we want the cert from the object.
451
 */
452
static int cac_read_binary(sc_card_t *card, unsigned int idx,
453
    unsigned char *buf, size_t count, unsigned long *flags)
454
0
{
455
0
  cac_private_data_t * priv = CAC_DATA(card);
456
0
  int r = 0;
457
0
  u8 *tl = NULL, *val = NULL;
458
0
  const u8 *tl_ptr, *val_ptr, *tl_start;
459
0
  u8 *tlv_ptr;
460
0
  const u8 *cert_ptr;
461
0
  size_t tl_len = 0, val_len = 0, tlv_len;
462
0
  size_t len, tl_head_len, cert_len;
463
0
  u8 cert_type, tag;
464
465
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
466
467
  /* if we didn't return it all last time, return the remainder */
468
0
  if (priv->cached) {
469
0
    sc_log(card->ctx,
470
0
       "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u",
471
0
       idx, count);
472
0
    if (idx > priv->cache_buf_len) {
473
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_END_REACHED);
474
0
    }
475
0
    len = MIN(count, priv->cache_buf_len-idx);
476
0
    memcpy(buf, &priv->cache_buf[idx], len);
477
0
    LOG_FUNC_RETURN(card->ctx, (int)len);
478
0
  }
479
480
0
  sc_log(card->ctx,
481
0
     "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u",
482
0
     idx, count);
483
0
  if (priv->cache_buf) {
484
0
    free(priv->cache_buf);
485
0
    priv->cache_buf = NULL;
486
0
    priv->cache_buf_len = 0;
487
0
  }
488
489
490
0
  if (priv->object_type <= 0)
491
0
     LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
492
493
0
  r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len);
494
0
  if (r < 0)  {
495
0
    goto done;
496
0
  }
497
498
0
  r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len);
499
0
  if (r < 0)
500
0
    goto done;
501
502
0
  switch (priv->object_type) {
503
0
  case CAC_OBJECT_TYPE_TLV_FILE:
504
0
    tlv_len = tl_len + val_len;
505
0
    priv->cache_buf = malloc(tlv_len);
506
0
    if (priv->cache_buf == NULL) {
507
0
      r = SC_ERROR_OUT_OF_MEMORY;
508
0
      goto done;
509
0
    }
510
0
    priv->cache_buf_len = tlv_len;
511
512
0
    for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf;
513
0
        tl_len >= 2 && tlv_len > 0;
514
0
        val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) {
515
      /* get the tag and the length */
516
0
      tl_start = tl_ptr;
517
0
      r = sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len);
518
0
      if (r != SC_SUCCESS && r != SC_ERROR_TLV_END_OF_CONTENTS)
519
0
        break;
520
0
      tl_head_len = (tl_ptr - tl_start);
521
0
      sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr);
522
0
      tlv_len -= tl_head_len;
523
0
      tl_len -= tl_head_len;
524
525
      /* don't crash on bad data */
526
0
      if (val_len < len) {
527
0
        sc_log(card->ctx, "Received too long value %"SC_FORMAT_LEN_SIZE_T"u, "
528
0
            "while only %"SC_FORMAT_LEN_SIZE_T"u left. Truncating", len, val_len);
529
0
        len = val_len;
530
0
      }
531
      /* if we run out of return space, truncate */
532
0
      if (tlv_len < len) {
533
0
        len = tlv_len;
534
0
      }
535
0
      memcpy(tlv_ptr, val_ptr, len);
536
0
    }
537
0
    break;
538
539
0
  case CAC_OBJECT_TYPE_CERT:
540
    /* read file */
541
0
    sc_log(card->ctx,
542
0
       " obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)",
543
0
       val_len, val_len);
544
0
    cert_len = 0;
545
0
    cert_ptr = NULL;
546
0
    cert_type = 0;
547
0
    for (tl_ptr = tl, val_ptr = val; tl_len >= 2;
548
0
        val_len -= len, val_ptr += len, tl_len -= tl_head_len) {
549
0
      tl_start = tl_ptr;
550
0
      r = sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len);
551
0
      if (r != SC_SUCCESS && r != SC_ERROR_TLV_END_OF_CONTENTS)
552
0
        break;
553
0
      tl_head_len = tl_ptr - tl_start;
554
555
      /* incomplete value */
556
0
      if (val_len < len) {
557
0
        sc_log(card->ctx, "Read incomplete value %"SC_FORMAT_LEN_SIZE_T"u, "
558
0
            "while only %"SC_FORMAT_LEN_SIZE_T"u left", len, val_len);
559
0
        break;
560
0
      }
561
562
0
      if (tag == CAC_TAG_CERTIFICATE) {
563
0
        cert_len = len;
564
0
        cert_ptr = val_ptr;
565
0
      }
566
0
      if (tag == CAC_TAG_CERTINFO) {
567
0
        if ((len >= 1) && (val_len >=1)) {
568
0
          cert_type = *val_ptr;
569
0
        }
570
0
      }
571
0
      if (tag == CAC_TAG_MSCUID) {
572
0
        sc_log_hex(card->ctx, "MSCUID", val_ptr, len);
573
0
      }
574
0
    }
575
    /* if the info byte is 1, then the cert is compressed, decompress it */
576
0
    if ((cert_type & 0x3) == 1 && flags) {
577
0
      *flags |= SC_FILE_FLAG_COMPRESSED_AUTO;
578
0
    }
579
0
    if (cert_len > 0) {
580
0
      priv->cache_buf = malloc(cert_len);
581
0
      if (priv->cache_buf == NULL) {
582
0
        r = SC_ERROR_OUT_OF_MEMORY;
583
0
        goto done;
584
0
      }
585
0
      priv->cache_buf_len = cert_len;
586
0
      memcpy(priv->cache_buf, cert_ptr, cert_len);
587
0
    } else {
588
0
      sc_log(card->ctx, "Can't read zero-length certificate");
589
0
      goto done;
590
0
    }
591
0
    break;
592
0
  case CAC_OBJECT_TYPE_GENERIC:
593
    /* TODO
594
     * We have some two buffers in unknown encoding that we
595
     * need to present in PKCS#15 layer.
596
     */
597
0
  default:
598
    /* Unknown object type */
599
0
    sc_log(card->ctx, "Unknown object type: %x", priv->object_type);
600
0
    r = SC_ERROR_INTERNAL;
601
0
    goto done;
602
0
  }
603
604
  /* OK we've read the data, now copy the required portion out to the callers buffer */
605
0
  priv->cached = 1;
606
0
  len = MIN(count, priv->cache_buf_len-idx);
607
0
  memcpy(buf, &priv->cache_buf[idx], len);
608
0
  r = (int)len;
609
0
done:
610
0
  if (tl)
611
0
    free(tl);
612
0
  if (val)
613
0
    free(val);
614
0
  LOG_FUNC_RETURN(card->ctx, r);
615
0
}
616
617
/* initialize getting a list and return the number of elements in the list */
618
static int cac_get_init_and_get_count(list_t *list, cac_object_t **entry, int *countp)
619
0
{
620
0
  *countp = list_size(list);
621
0
  list_iterator_start(list);
622
0
  *entry = list_iterator_next(list);
623
0
  return SC_SUCCESS;
624
0
}
625
626
/* finalize the list iterator */
627
static int cac_final_iterator(list_t *list)
628
0
{
629
0
  list_iterator_stop(list);
630
0
  return SC_SUCCESS;
631
0
}
632
633
/* fill in the obj_info for the current object on the list and advance to the next object */
634
static int cac_fill_object_info(list_t *list, cac_object_t **entry, sc_pkcs15_data_info_t *obj_info)
635
0
{
636
0
  memset(obj_info, 0, sizeof(sc_pkcs15_data_info_t));
637
0
  if (*entry == NULL) {
638
0
    return SC_ERROR_FILE_END_REACHED;
639
0
  }
640
641
0
  obj_info->path = (*entry)->path;
642
0
  obj_info->path.count = CAC_MAX_SIZE-1; /* read something from the object */
643
0
  obj_info->id.value[0] = ((*entry)->fd >> 8) & 0xff;
644
0
  obj_info->id.value[1] = (*entry)->fd & 0xff;
645
0
  obj_info->id.len = 2;
646
0
  strncpy(obj_info->app_label, (*entry)->name, SC_PKCS15_MAX_LABEL_SIZE-1);
647
0
  *entry = list_iterator_next(list);
648
0
  return SC_SUCCESS;
649
0
}
650
651
static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial)
652
0
{
653
0
  cac_private_data_t * priv = CAC_DATA(card);
654
655
0
  LOG_FUNC_CALLED(card->ctx);
656
0
        if (card->serialnr.len)   {
657
0
                *serial = card->serialnr;
658
0
                LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
659
0
        }
660
0
  if (priv->cac_id_len) {
661
0
    serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR);
662
0
    memcpy(serial->value, priv->cac_id, serial->len);
663
0
    LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
664
0
  }
665
0
  LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND);
666
0
}
667
668
static int cac_get_ACA_path(sc_card_t *card, sc_path_t *path)
669
0
{
670
0
  cac_private_data_t * priv = CAC_DATA(card);
671
672
0
  LOG_FUNC_CALLED(card->ctx);
673
0
  if (priv->aca_path) {
674
0
    *path = *priv->aca_path;
675
0
  }
676
0
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
677
0
}
678
679
static int cac_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
680
0
{
681
0
  cac_private_data_t * priv = CAC_DATA(card);
682
683
0
  LOG_FUNC_CALLED(card->ctx);
684
0
  sc_log(card->ctx, "cmd=%ld ptr=%p", cmd, ptr);
685
686
0
  if (priv == NULL) {
687
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
688
0
  }
689
0
  switch(cmd) {
690
0
    case SC_CARDCTL_CAC_GET_ACA_PATH:
691
0
      return cac_get_ACA_path(card, (sc_path_t *) ptr);
692
0
    case SC_CARDCTL_GET_SERIALNR:
693
0
      return cac_get_serial_nr_from_CUID(card, (sc_serial_number_t *) ptr);
694
0
    case SC_CARDCTL_CAC_INIT_GET_GENERIC_OBJECTS:
695
0
      return cac_get_init_and_get_count(&priv->general_list, &priv->general_current, (int *)ptr);
696
0
    case SC_CARDCTL_CAC_INIT_GET_CERT_OBJECTS:
697
0
      return cac_get_init_and_get_count(&priv->pki_list, &priv->pki_current, (int *)ptr);
698
0
    case SC_CARDCTL_CAC_GET_NEXT_GENERIC_OBJECT:
699
0
      return cac_fill_object_info(&priv->general_list, &priv->general_current, (sc_pkcs15_data_info_t *)ptr);
700
0
    case SC_CARDCTL_CAC_GET_NEXT_CERT_OBJECT:
701
0
      return cac_fill_object_info(&priv->pki_list, &priv->pki_current, (sc_pkcs15_data_info_t *)ptr);
702
0
    case SC_CARDCTL_CAC_FINAL_GET_GENERIC_OBJECTS:
703
0
      return cac_final_iterator(&priv->general_list);
704
0
    case SC_CARDCTL_CAC_FINAL_GET_CERT_OBJECTS:
705
0
      return cac_final_iterator(&priv->pki_list);
706
0
  }
707
708
0
  LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
709
0
}
710
711
static int cac_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
712
0
{
713
  /* CAC requires 8 byte response */
714
0
  u8 rbuf[8];
715
0
  u8 *rbufp = &rbuf[0];
716
0
  size_t out_len = sizeof rbuf;
717
0
  int r;
718
719
0
  LOG_FUNC_CALLED(card->ctx);
720
721
0
  r = cac_apdu_io(card, 0x84, 0x00, 0x00, NULL, 0, &rbufp, &out_len);
722
0
  LOG_TEST_RET(card->ctx, r, "Could not get challenge");
723
724
0
  if (len < out_len) {
725
0
    out_len = len;
726
0
  }
727
0
  memcpy(rnd, rbuf, out_len);
728
729
0
  LOG_FUNC_RETURN(card->ctx, (int) out_len);
730
0
}
731
732
static int cac_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
733
0
{
734
0
  int r = SC_SUCCESS;
735
736
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
737
738
0
  sc_log(card->ctx,
739
0
     "flags=%08lx op=%d alg=%lu algf=%08lx algr=%08lx kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u\n",
740
0
     env->flags, env->operation, env->algorithm,
741
0
     env->algorithm_flags, env->algorithm_ref, env->key_ref[0],
742
0
     env->key_ref_len);
743
744
0
  if (env->algorithm != SC_ALGORITHM_RSA) {
745
0
     r = SC_ERROR_NO_CARD_SUPPORT;
746
0
  }
747
748
749
0
  SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
750
0
}
751
752
753
static int cac_restore_security_env(sc_card_t *card, int se_num)
754
0
{
755
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
756
757
0
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
758
0
}
759
760
761
static int cac_rsa_op(sc_card_t *card,
762
          const u8 * data, size_t datalen,
763
          u8 * out, size_t outlen)
764
0
{
765
0
  int r;
766
0
  u8 *outp, *rbuf;
767
0
  size_t rbuflen, outplen;
768
769
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
770
0
  sc_log(card->ctx,
771
0
     "datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n",
772
0
     datalen, outlen);
773
774
0
  outp = out;
775
0
  outplen = outlen;
776
777
  /* Not strictly necessary. This code requires the caller to have selected the correct PKI container
778
   * and authenticated to that container with the verifyPin command... All of this under the reader lock.
779
   * The PKCS #15 higher level driver code does all this correctly (it's the same for all cards, just
780
   * different sets of APDU's that need to be called), so this call is really a little bit of paranoia */
781
0
  r = sc_lock(card);
782
0
  if (r != SC_SUCCESS)
783
0
    LOG_FUNC_RETURN(card->ctx, r);
784
785
786
0
  rbuf = NULL;
787
0
  rbuflen = 0;
788
0
  for (; datalen > CAC_MAX_CHUNK_SIZE; data += CAC_MAX_CHUNK_SIZE, datalen -= CAC_MAX_CHUNK_SIZE) {
789
0
    r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_STEP,  0,
790
0
      data, CAC_MAX_CHUNK_SIZE, &rbuf, &rbuflen);
791
0
    if (r < 0) {
792
0
      break;
793
0
    }
794
0
    if (rbuflen != 0) {
795
0
      size_t n = MIN(rbuflen, outplen);
796
0
      memcpy(outp, rbuf, n);
797
0
      outp += n;
798
0
      outplen -= n;
799
0
    }
800
0
    free(rbuf);
801
0
    rbuf = NULL;
802
0
    rbuflen = 0;
803
0
  }
804
0
  if (r < 0) {
805
0
    goto err;
806
0
  }
807
0
  rbuf = NULL;
808
0
  rbuflen = 0;
809
0
  r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_FINAL, 0, data, datalen, &rbuf, &rbuflen);
810
0
  if (r < 0) {
811
0
    goto err;
812
0
  }
813
0
  if (rbuflen != 0) {
814
0
    size_t n = MIN(rbuflen, outplen);
815
0
    memcpy(outp, rbuf, n);
816
    /*outp += n;     unused */
817
0
    outplen -= n;
818
0
  }
819
0
  free(rbuf);
820
0
  rbuf = NULL;
821
0
  r = (int)(outlen - outplen);
822
823
0
err:
824
0
  sc_unlock(card);
825
0
  if (r < 0) {
826
0
    sc_mem_clear(out, outlen);
827
0
  }
828
0
  if (rbuf) {
829
0
    free(rbuf);
830
0
  }
831
832
0
  LOG_FUNC_RETURN(card->ctx, r);
833
0
}
834
835
static int cac_compute_signature(sc_card_t *card,
836
          const u8 * data, size_t datalen,
837
          u8 * out, size_t outlen)
838
0
{
839
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
840
841
0
  SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen));
842
0
}
843
844
static int cac_decipher(sc_card_t *card,
845
           const u8 * data, size_t datalen,
846
           u8 * out, size_t outlen)
847
0
{
848
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
849
850
0
  SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen));
851
0
}
852
853
static int cac_parse_properties_object(sc_card_t *card, u8 type,
854
    const u8 *data, size_t data_len, cac_properties_object_t *object)
855
0
{
856
0
  size_t len;
857
0
  const u8 *val, *val_end;
858
0
  u8 tag;
859
0
  int parsed = 0;
860
861
0
  if (data_len < 11)
862
0
    return -1;
863
864
  /* Initialize: non-PKI applet */
865
0
  object->privatekey = 0;
866
867
0
  val = data;
868
0
  val_end = data + data_len;
869
0
  for (; val < val_end; val += len) {
870
    /* get the tag and the length */
871
0
    if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
872
0
      break;
873
874
0
    switch (tag) {
875
0
    case CAC_TAG_OBJECT_ID:
876
0
      if (len != 2) {
877
0
        sc_log(card->ctx, "TAG: Object ID: "
878
0
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
879
0
        break;
880
0
      }
881
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
882
0
          "TAG: Object ID = 0x%02x 0x%02x", val[0], val[1]);
883
0
      memcpy(&object->oid, val, 2);
884
0
      parsed++;
885
0
      break;
886
887
0
    case CAC_TAG_BUFFER_PROPERTIES:
888
0
      if (len != 5) {
889
0
        sc_log(card->ctx, "TAG: Buffer Properties: "
890
0
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
891
0
        break;
892
0
      }
893
      /* First byte is "Type of Tag Supported" */
894
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
895
0
          "TAG: Buffer Properties: Type of Tag Supported = 0x%02x",
896
0
          val[0]);
897
0
      object->simpletlv = val[0];
898
0
      parsed++;
899
0
      break;
900
901
0
    case CAC_TAG_PKI_PROPERTIES:
902
      /* 4th byte is "Private Key Initialized" */
903
0
      if (len != 4) {
904
0
        sc_log(card->ctx, "TAG: PKI Properties: "
905
0
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
906
0
        break;
907
0
      }
908
0
      if (type != CAC_TAG_PKI_OBJECT) {
909
0
        sc_log(card->ctx, "TAG: PKI Properties outside of PKI Object");
910
0
        break;
911
0
      }
912
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
913
0
          "TAG: PKI Properties: Private Key Initialized = 0x%02x",
914
0
          val[2]);
915
0
      object->privatekey = val[2];
916
0
      parsed++;
917
0
      break;
918
919
0
    default:
920
      /* ignore tags we don't understand */
921
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
922
0
          "TAG: Unknown (0x%02x)",tag );
923
0
      break;
924
0
    }
925
0
  }
926
0
  if (parsed < 2)
927
0
    return SC_ERROR_INVALID_DATA;
928
929
0
  return SC_SUCCESS;
930
0
}
931
932
static int cac_get_properties(sc_card_t *card, cac_properties_t *prop)
933
0
{
934
0
  u8 *rbuf = NULL;
935
0
  size_t rbuflen = 0, len;
936
0
  const u8 *val, *val_end;
937
0
  u8 tag;
938
0
  size_t i = 0;
939
0
  int r;
940
0
  prop->num_objects = 0;
941
942
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
943
944
0
  r = cac_apdu_io(card, CAC_INS_GET_PROPERTIES, 0x01, 0x00, NULL, 0,
945
0
    &rbuf, &rbuflen);
946
0
  if (r < 0)
947
0
    return r;
948
949
0
  val = rbuf;
950
0
  val_end = val + rbuflen;
951
0
  for (; val < val_end; val += len) {
952
    /* get the tag and the length */
953
0
    if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
954
0
      break;
955
956
0
    switch (tag) {
957
0
    case CAC_TAG_APPLET_INFORMATION:
958
0
      if (len != 5) {
959
0
        sc_log(card->ctx, "TAG: Applet Information: "
960
0
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
961
0
        break;
962
0
      }
963
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
964
0
          "TAG: Applet Information: Family: 0x%0x", val[0]);
965
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
966
0
          "     Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x",
967
0
          val[1], val[2], val[3], val[4]);
968
0
      break;
969
970
0
    case CAC_TAG_NUMBER_OF_OBJECTS:
971
0
      if (len != 1) {
972
0
        sc_log(card->ctx, "TAG: Num objects: "
973
0
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
974
0
        break;
975
0
      }
976
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
977
0
          "TAG: Num objects = %hhd", *val);
978
      /* make sure we do not overrun buffer */
979
0
      prop->num_objects = MIN(val[0], CAC_MAX_OBJECTS);
980
0
      break;
981
982
0
    case CAC_TAG_TV_BUFFER:
983
0
      if (len != 17) {
984
0
        sc_log(card->ctx, "TAG: TV Object: "
985
0
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
986
0
        break;
987
0
      }
988
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
989
0
          "TAG: TV Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i);
990
0
      if (i >= CAC_MAX_OBJECTS) {
991
0
        free(rbuf);
992
0
        return SC_SUCCESS;
993
0
      }
994
995
0
      if (cac_parse_properties_object(card, tag, val, len,
996
0
          &prop->objects[i]) == SC_SUCCESS)
997
0
        i++;
998
0
      break;
999
1000
0
    case CAC_TAG_PKI_OBJECT:
1001
0
      if (len != 17) {
1002
0
        sc_log(card->ctx, "TAG: PKI Object: "
1003
0
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
1004
0
        break;
1005
0
      }
1006
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1007
0
          "TAG: PKI Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i);
1008
0
      if (i >= CAC_MAX_OBJECTS) {
1009
0
        free(rbuf);
1010
0
        return SC_SUCCESS;
1011
0
      }
1012
1013
0
      if (cac_parse_properties_object(card, tag, val, len,
1014
0
          &prop->objects[i]) == SC_SUCCESS)
1015
0
        i++;
1016
0
      break;
1017
1018
0
    default:
1019
      /* ignore tags we don't understand */
1020
0
      sc_log(card->ctx, "TAG: Unknown (0x%02x), len=%"
1021
0
          SC_FORMAT_LEN_SIZE_T"u", tag, len);
1022
0
      break;
1023
0
    }
1024
0
  }
1025
0
  free(rbuf);
1026
  /* sanity */
1027
0
  if (i != prop->num_objects)
1028
0
    sc_log(card->ctx, "The announced number of objects (%zu) "
1029
0
        "did not match reality (%"SC_FORMAT_LEN_SIZE_T"u)",
1030
0
        prop->num_objects, i);
1031
0
  prop->num_objects = i;
1032
1033
0
  return SC_SUCCESS;
1034
0
}
1035
1036
/*
1037
 * CAC cards use SC_PATH_SELECT_OBJECT_ID rather than SC_PATH_SELECT_FILE_ID. In order to use more
1038
 * of the PKCS #15 structure, we call the selection SC_PATH_SELECT_FILE_ID, but we set p1 to 2 instead
1039
 * of 0. Also cac1 does not do any FCI, but it doesn't understand not selecting it. It returns invalid INS
1040
 * if it doesn't like anything about the select, so we always 'request' FCI for CAC1
1041
 *
1042
 * The rest is just copied from iso7816_select_file
1043
 */
1044
static int cac_select_file_by_type(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out)
1045
0
{
1046
0
  struct sc_context *ctx;
1047
0
  struct sc_apdu apdu;
1048
0
  unsigned char buf[SC_MAX_APDU_BUFFER_SIZE];
1049
0
  unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
1050
0
  int r, pathtype;
1051
0
  size_t pathlen;
1052
0
  struct sc_file *file = NULL;
1053
0
  cac_private_data_t * priv = CAC_DATA(card);
1054
1055
0
  assert(card != NULL && in_path != NULL);
1056
0
  ctx = card->ctx;
1057
1058
0
  SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE);
1059
1060
0
  memcpy(path, in_path->value, in_path->len);
1061
0
  pathlen = in_path->len;
1062
0
  pathtype = in_path->type;
1063
1064
0
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1065
0
      "path=%s, path->value=%s path->type=%d (%x)",
1066
0
      sc_print_path(in_path),
1067
0
      sc_dump_hex(in_path->value, in_path->len),
1068
0
      in_path->type, in_path->type);
1069
0
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n",
1070
0
      file_out, in_path->index, in_path->count);
1071
1072
  /* Sigh, iso7816_select_file expects paths to keys to have specific
1073
   * formats. There is no override. We have to add some bytes to the
1074
   * path to make it happy.
1075
   * We only need to do this for private keys.
1076
   */
1077
0
  if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) {
1078
0
    path += 2;
1079
0
    pathlen -= 2;
1080
0
  }
1081
1082
1083
  /* CAC has multiple different type of objects that aren't PKCS #15. When we read
1084
   * them we need convert them to something PKCS #15 would understand. Find the object
1085
   * and object type here:
1086
   */
1087
0
  if (priv) { /* don't record anything if we haven't been initialized yet */
1088
0
    priv->object_type = CAC_OBJECT_TYPE_GENERIC;
1089
0
    if (cac_is_cert(priv, in_path)) {
1090
0
      priv->object_type = CAC_OBJECT_TYPE_CERT;
1091
0
    }
1092
1093
    /* forget any old cached values */
1094
0
    if (priv->cache_buf) {
1095
0
      free(priv->cache_buf);
1096
0
      priv->cache_buf = NULL;
1097
0
    }
1098
0
    priv->cache_buf_len = 0;
1099
0
    priv->cached = 0;
1100
0
  }
1101
1102
0
  if (in_path->aid.len) {
1103
0
    if (!pathlen) {
1104
0
      memcpy(path, in_path->aid.value, in_path->aid.len);
1105
0
      pathlen = in_path->aid.len;
1106
0
      pathtype = SC_PATH_TYPE_DF_NAME;
1107
0
    } else {
1108
      /* First, select the application */
1109
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" );
1110
0
      sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0);
1111
0
      apdu.data = in_path->aid.value;
1112
0
      apdu.datalen = in_path->aid.len;
1113
0
      apdu.lc = in_path->aid.len;
1114
1115
0
      r = sc_transmit_apdu(card, &apdu);
1116
0
      LOG_TEST_RET(ctx, r, "APDU transmit failed");
1117
0
      r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1118
0
      if (r)
1119
0
        LOG_FUNC_RETURN(ctx, r);
1120
1121
0
    }
1122
0
  }
1123
1124
0
  sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0);
1125
1126
0
  switch (pathtype) {
1127
  /* ideally we would had SC_PATH_TYPE_OBJECT_ID and add code to the iso7816 select.
1128
   * Unfortunately we'd also need to update the caching code as well. For now just
1129
   * use FILE_ID and change p1 here */
1130
0
  case SC_PATH_TYPE_FILE_ID:
1131
0
    apdu.p1 = 2;
1132
0
    if (pathlen != 2)
1133
0
      return SC_ERROR_INVALID_ARGUMENTS;
1134
0
    break;
1135
0
  case SC_PATH_TYPE_DF_NAME:
1136
0
    apdu.p1 = 4;
1137
0
    break;
1138
0
  default:
1139
0
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
1140
0
  }
1141
0
  apdu.lc = pathlen;
1142
0
  apdu.data = path;
1143
0
  apdu.datalen = pathlen;
1144
0
  apdu.resp = buf;
1145
0
  apdu.resplen = sizeof(buf);
1146
0
  apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256;
1147
1148
0
  if (file_out != NULL) {
1149
0
    apdu.p2 = 0;    /* first record, return FCI */
1150
0
  }
1151
0
  else {
1152
0
    apdu.p2 = 0x0C;
1153
0
  }
1154
1155
0
  r = sc_transmit_apdu(card, &apdu);
1156
0
  LOG_TEST_RET(ctx, r, "APDU transmit failed");
1157
1158
0
  if (file_out == NULL) {
1159
    /* For some cards 'SELECT' can be only with request to return FCI/FCP. */
1160
0
    r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1161
0
    if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86)   {
1162
0
      apdu.p2 = 0x00;
1163
0
      apdu.resplen = sizeof(buf);
1164
0
      if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS)
1165
0
        r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1166
0
    }
1167
0
    if (apdu.sw1 == 0x61)
1168
0
      LOG_FUNC_RETURN(ctx, SC_SUCCESS);
1169
0
    LOG_FUNC_RETURN(ctx, r);
1170
0
  }
1171
1172
0
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1173
0
  if (r)
1174
0
    LOG_FUNC_RETURN(ctx, r);
1175
1176
  /* This needs to come after the applet selection */
1177
0
  if (priv && in_path->len >= 2) {
1178
    /* get applet properties to know if we can treat the
1179
     * buffer as SimpleLTV and if we have PKI applet.
1180
     *
1181
     * Do this only if we select applets for reading
1182
     * (not during driver initialization)
1183
     */
1184
0
    cac_properties_t prop;
1185
0
    size_t i = -1;
1186
1187
0
    r = cac_get_properties(card, &prop);
1188
0
    if (r == SC_SUCCESS) {
1189
0
      for (i = 0; i < prop.num_objects; i++) {
1190
0
        sc_log(card->ctx, "Searching for our OID: 0x%02x 0x%02x = 0x%02x 0x%02x",
1191
0
            prop.objects[i].oid[0], prop.objects[i].oid[1],
1192
0
          in_path->value[0], in_path->value[1]);
1193
0
        if (memcmp(prop.objects[i].oid,
1194
0
            in_path->value, 2) == 0)
1195
0
          break;
1196
0
      }
1197
0
    }
1198
0
    if (i < prop.num_objects) {
1199
0
      if (prop.objects[i].privatekey)
1200
0
        priv->object_type = CAC_OBJECT_TYPE_CERT;
1201
0
      else if (prop.objects[i].simpletlv == 0)
1202
0
        priv->object_type = CAC_OBJECT_TYPE_TLV_FILE;
1203
0
    }
1204
0
  }
1205
1206
  /* CAC cards never return FCI, fake one */
1207
0
  file = sc_file_new();
1208
0
  if (file == NULL)
1209
0
      LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
1210
0
  file->path = *in_path;
1211
0
  file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */
1212
1213
0
  *file_out = file;
1214
0
  LOG_FUNC_RETURN(ctx, SC_SUCCESS);
1215
1216
0
}
1217
1218
static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out)
1219
0
{
1220
0
  return cac_select_file_by_type(card, in_path, file_out);
1221
0
}
1222
1223
static int cac_finish(sc_card_t *card)
1224
0
{
1225
0
  cac_private_data_t * priv = CAC_DATA(card);
1226
1227
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1228
0
  if (priv) {
1229
0
    cac_free_private_data(priv);
1230
0
  }
1231
0
  return SC_SUCCESS;
1232
0
}
1233
1234
1235
/* select the Card Capabilities Container on CAC-2 */
1236
static int cac_select_CCC(sc_card_t *card)
1237
0
{
1238
0
  return cac_select_file_by_type(card, &cac_CCC_Path, NULL);
1239
0
}
1240
1241
/* Select ACA in non-standard location */
1242
static int cac_select_ACA(sc_card_t *card)
1243
0
{
1244
0
  return cac_select_file_by_type(card, &cac_ACA_Path, NULL);
1245
0
}
1246
1247
static int cac_path_from_cardurl(sc_card_t *card, sc_path_t *path, cac_card_url_t *val, size_t len)
1248
0
{
1249
0
  if (len < 10) {
1250
0
    return SC_ERROR_INVALID_DATA;
1251
0
  }
1252
0
  sc_mem_clear(path, sizeof(sc_path_t));
1253
0
  memcpy(path->aid.value, &val->rid, sizeof(val->rid));
1254
0
  memcpy(&path->aid.value[5], val->applicationID, sizeof(val->applicationID));
1255
0
  path->aid.len = sizeof(val->rid) + sizeof(val->applicationID);
1256
0
  memcpy(path->value, val->objectID, sizeof(val->objectID));
1257
0
  path->len = sizeof(val->objectID);
1258
0
  path->type = SC_PATH_TYPE_FILE_ID;
1259
0
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1260
0
     "path->aid=%x %x %x %x %x %x %x  len=%"SC_FORMAT_LEN_SIZE_T"u, path->value = %x %x len=%"SC_FORMAT_LEN_SIZE_T"u path->type=%d (%x)",
1261
0
     path->aid.value[0], path->aid.value[1], path->aid.value[2],
1262
0
     path->aid.value[3], path->aid.value[4], path->aid.value[5],
1263
0
     path->aid.value[6], path->aid.len, path->value[0],
1264
0
     path->value[1], path->len, path->type, path->type);
1265
0
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1266
0
     "rid=%x %x %x %x %x  len=%"SC_FORMAT_LEN_SIZE_T"u appid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u objid= %x %x len=%"SC_FORMAT_LEN_SIZE_T"u",
1267
0
     val->rid[0], val->rid[1], val->rid[2], val->rid[3],
1268
0
     val->rid[4], sizeof(val->rid), val->applicationID[0],
1269
0
     val->applicationID[1], sizeof(val->applicationID),
1270
0
     val->objectID[0], val->objectID[1], sizeof(val->objectID));
1271
1272
0
  return SC_SUCCESS;
1273
0
}
1274
1275
static int cac_parse_aid(sc_card_t *card, cac_private_data_t *priv, const u8 *aid, int aid_len)
1276
0
{
1277
0
  cac_object_t new_object;
1278
0
  cac_properties_t prop;
1279
0
  size_t i;
1280
0
  int r;
1281
1282
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1283
1284
  /* Search for PKI applets (7 B). Ignore generic objects for now */
1285
0
  if (aid_len != 7 || (memcmp(aid, CAC_1_RID "\x01", 6) != 0
1286
0
      && memcmp(aid, CAC_1_RID "\x00", 6) != 0))
1287
0
    return SC_SUCCESS;
1288
1289
0
  sc_mem_clear(&new_object.path, sizeof(sc_path_t));
1290
0
  memcpy(new_object.path.aid.value, aid, aid_len);
1291
0
  new_object.path.aid.len = aid_len;
1292
1293
  /* Call without OID set will just select the AID without subsequent
1294
   * OID selection, which we need to figure out just now
1295
   */
1296
0
  r = cac_select_file_by_type(card, &new_object.path, NULL);
1297
0
  LOG_TEST_RET(card->ctx, r, "Cannot select AID");
1298
0
  r = cac_get_properties(card, &prop);
1299
0
  LOG_TEST_RET(card->ctx, r, "Cannot get CAC properties");
1300
1301
0
  for (i = 0; i < prop.num_objects; i++) {
1302
    /* don't fail just because we have more certs than we can support */
1303
0
    if (priv->cert_next >= MAX_CAC_SLOTS)
1304
0
      return SC_SUCCESS;
1305
1306
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1307
0
        "ACA: pki_object found, cert_next=%d (%s), privkey=%d",
1308
0
        priv->cert_next, get_cac_label(priv->cert_next),
1309
0
        prop.objects[i].privatekey);
1310
1311
    /* If the private key is not initialized, we can safely
1312
     * ignore this object here, but increase the pointer to follow
1313
     * the certificate labels
1314
     */
1315
0
    if (!prop.objects[i].privatekey) {
1316
0
      priv->cert_next++;
1317
0
      continue;
1318
0
    }
1319
1320
    /* OID here has always 2B */
1321
0
    memcpy(new_object.path.value, &prop.objects[i].oid, 2);
1322
0
    new_object.path.len = 2;
1323
0
    new_object.path.type = SC_PATH_TYPE_FILE_ID;
1324
0
    new_object.name = get_cac_label(priv->cert_next);
1325
0
    new_object.fd = priv->cert_next+1;
1326
0
    cac_add_object_to_list(&priv->pki_list, &new_object);
1327
0
    priv->cert_next++;
1328
0
  }
1329
1330
0
  return SC_SUCCESS;
1331
0
}
1332
1333
static int cac_parse_cardurl(sc_card_t *card, cac_private_data_t *priv, cac_card_url_t *val, size_t len)
1334
0
{
1335
0
  cac_object_t new_object;
1336
0
  const cac_object_t *obj;
1337
0
  unsigned short object_id;
1338
0
  int r;
1339
1340
0
  r = cac_path_from_cardurl(card, &new_object.path, val, len);
1341
0
  if (r != SC_SUCCESS) {
1342
0
    return r;
1343
0
  }
1344
0
  switch (val->cardApplicationType) {
1345
0
  case CAC_APP_TYPE_PKI:
1346
    /* we don't want to overflow the cac_label array. This test could
1347
     * go way if we create a label function that will create a unique label
1348
     * from a cert index.
1349
     */
1350
0
    if (priv->cert_next >= MAX_CAC_SLOTS)
1351
0
      break; /* don't fail just because we have more certs than we can support */
1352
0
    new_object.name = get_cac_label(priv->cert_next);
1353
0
    new_object.fd = priv->cert_next+1;
1354
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: pki_object found, cert_next=%d (%s),", priv->cert_next, new_object.name);
1355
0
    cac_add_object_to_list(&priv->pki_list, &new_object);
1356
0
    priv->cert_next++;
1357
0
    break;
1358
0
  case CAC_APP_TYPE_GENERAL:
1359
0
    object_id = bebytes2ushort(val->objectID);
1360
0
    obj = cac_find_obj_by_id(object_id);
1361
0
    if (obj == NULL)
1362
0
      break; /* don't fail just because we don't recognize the object */
1363
0
    new_object.name = obj->name;
1364
0
    new_object.fd = 0;
1365
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: gen_object found, objectID=%x (%s),", object_id, new_object.name);
1366
0
    cac_add_object_to_list(&priv->general_list, &new_object);
1367
0
    break;
1368
0
  case CAC_APP_TYPE_SKI:
1369
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: ski_object found");
1370
0
  break;
1371
0
  default:
1372
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: unknown object_object found (type=0x%02x)", val->cardApplicationType);
1373
    /* don't fail just because there is an unknown object in the CCC */
1374
0
    break;
1375
0
  }
1376
0
  return SC_SUCCESS;
1377
0
}
1378
1379
static int cac_parse_cuid(sc_card_t *card, cac_private_data_t *priv, cac_cuid_t *val, size_t len)
1380
0
{
1381
0
  size_t card_id_len;
1382
1383
0
  if (len < sizeof(cac_cuid_t)) {
1384
0
    return SC_ERROR_INVALID_DATA;
1385
0
  }
1386
1387
0
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "gsc_rid=%s", sc_dump_hex(val->gsc_rid, sizeof(val->gsc_rid)));
1388
0
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "manufacture id=%x", val->manufacturer_id);
1389
0
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "cac_type=%d", val->card_type);
1390
0
  card_id_len = len - (&val->card_id - (u8 *)val);
1391
0
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1392
0
     "card_id=%s (%"SC_FORMAT_LEN_SIZE_T"u)",
1393
0
     sc_dump_hex(&val->card_id, card_id_len),
1394
0
     card_id_len);
1395
0
  priv->cuid = *val;
1396
0
  free(priv->cac_id);
1397
0
  priv->cac_id = malloc(card_id_len);
1398
0
  if (priv->cac_id == NULL) {
1399
0
    return SC_ERROR_OUT_OF_MEMORY;
1400
0
  }
1401
0
  memcpy(priv->cac_id, &val->card_id, card_id_len);
1402
0
  priv->cac_id_len = card_id_len;
1403
0
  return SC_SUCCESS;
1404
0
}
1405
static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv, int depth);
1406
1407
static int cac_parse_CCC(sc_card_t *card, cac_private_data_t *priv, const u8 *tl,
1408
  size_t tl_len, u8 *val, size_t val_len, int depth)
1409
0
{
1410
0
  size_t len = 0;
1411
0
  const u8 *tl_end = tl + tl_len;
1412
0
  const u8 *val_end = val + val_len;
1413
0
  sc_path_t new_path;
1414
0
  int r;
1415
1416
1417
0
  for (; (tl < tl_end) && (val< val_end); val += len) {
1418
    /* get the tag and the length */
1419
0
    u8 tag;
1420
0
    r = sc_simpletlv_read_tag(&tl, tl_end - tl, &tag, &len);
1421
0
    if (r != SC_SUCCESS && r != SC_ERROR_TLV_END_OF_CONTENTS) {
1422
0
      sc_log(card->ctx, "Failed to parse tag from buffer");
1423
0
      break;
1424
0
    }
1425
0
    if (val + len > val_end) {
1426
0
      sc_log(card->ctx, "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
1427
0
      break;
1428
0
    }
1429
0
    switch (tag) {
1430
0
    case CAC_TAG_CUID:
1431
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CUID");
1432
0
      r = cac_parse_cuid(card, priv, (cac_cuid_t *)val, len);
1433
0
      if (r < 0)
1434
0
        return r;
1435
0
      break;
1436
0
    case CAC_TAG_CC_VERSION_NUMBER:
1437
0
      if (len != 1) {
1438
0
        sc_log(card->ctx, "TAG: CC Version: "
1439
0
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
1440
0
        break;
1441
0
      }
1442
      /* ignore the version numbers for now */
1443
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1444
0
        "TAG: CC Version = 0x%02x", *val);
1445
0
      break;
1446
0
    case CAC_TAG_GRAMMAR_VERION_NUMBER:
1447
0
      if (len != 1) {
1448
0
        sc_log(card->ctx, "TAG: Grammar Version: "
1449
0
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
1450
0
        break;
1451
0
      }
1452
      /* ignore the version numbers for now */
1453
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1454
0
        "TAG: Grammar Version = 0x%02x", *val);
1455
0
      break;
1456
0
    case CAC_TAG_CARDURL:
1457
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CARDURL");
1458
0
      r = cac_parse_cardurl(card, priv, (cac_card_url_t *)val, len);
1459
0
      if (r < 0)
1460
0
        return r;
1461
0
      break;
1462
    /*
1463
     * The following are really for file systems cards. This code only cares about CAC VM cards
1464
     */
1465
0
    case CAC_TAG_PKCS15:
1466
0
      if (len != 1) {
1467
0
        sc_log(card->ctx, "TAG: PKCS15: "
1468
0
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
1469
0
        break;
1470
0
      }
1471
      /* TODO should verify that this is '0'. If it's not
1472
       * zero, we should drop out of here and let the PKCS 15
1473
       * code handle this card */
1474
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: PKCS15 = 0x%02x", *val);
1475
0
      break;
1476
0
    case CAC_TAG_DATA_MODEL:
1477
0
      if (len != 1) {
1478
0
        sc_log(card->ctx, "TAG: Registered Data Model Number: "
1479
0
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
1480
0
        break;
1481
0
      }
1482
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: Registered Data Model Number (0x%02x)", *val);
1483
0
      break;
1484
0
    case CAC_TAG_CARD_APDU:
1485
0
    case CAC_TAG_CAPABILITY_TUPLES:
1486
0
    case CAC_TAG_STATUS_TUPLES:
1487
0
    case CAC_TAG_REDIRECTION:
1488
0
    case CAC_TAG_ERROR_CODES:
1489
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: FSSpecific(0x%02x)", tag);
1490
0
      break;
1491
0
    case CAC_TAG_ACCESS_CONTROL:
1492
      /* TODO handle access control later */
1493
0
      sc_log_hex(card->ctx, "TAG:ACCESS Control", val, len);
1494
0
      break;
1495
0
    case CAC_TAG_NEXT_CCC:
1496
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:NEXT CCC");
1497
0
      r = cac_path_from_cardurl(card, &new_path, (cac_card_url_t *)val, len);
1498
0
      if (r < 0)
1499
0
        return r;
1500
1501
0
      r = cac_select_file_by_type(card, &new_path, NULL);
1502
0
      if (r < 0)
1503
0
        return r;
1504
1505
      /* Increase depth to avoid infinite recursion */
1506
0
      r = cac_process_CCC(card, priv, depth + 1);
1507
0
      if (r < 0)
1508
0
        return r;
1509
0
      break;
1510
0
    default:
1511
      /* ignore tags we don't understand */
1512
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:Unknown (0x%02x)",tag );
1513
0
      break;
1514
0
    }
1515
0
  }
1516
0
  return SC_SUCCESS;
1517
0
}
1518
1519
static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv, int depth)
1520
0
{
1521
0
  u8 *tl = NULL, *val = NULL;
1522
0
  size_t tl_len = 0, val_len = 0;
1523
0
  int r;
1524
1525
0
  if (depth > CAC_MAX_CCC_DEPTH) {
1526
0
    sc_log(card->ctx, "Too much recursive CCC found. Exiting");
1527
0
    return SC_ERROR_INVALID_CARD;
1528
0
  }
1529
1530
0
  r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len);
1531
0
  if (r < 0)
1532
0
    goto done;
1533
1534
0
  r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len);
1535
0
  if (r < 0)
1536
0
    goto done;
1537
1538
0
  r = cac_parse_CCC(card, priv, tl, tl_len, val, val_len, depth);
1539
0
done:
1540
0
  if (tl)
1541
0
    free(tl);
1542
0
  if (val)
1543
0
    free(val);
1544
0
  return r;
1545
0
}
1546
1547
/* Service Applet Table (Table 5-21) should list all the applets on the
1548
 * card, which is a good start if we don't have CCC
1549
 */
1550
static int cac_parse_ACA_service(sc_card_t *card, cac_private_data_t *priv,
1551
    const u8 *val, size_t val_len)
1552
0
{
1553
0
  size_t len = 0;
1554
0
  const u8 *val_end = val + val_len;
1555
0
  int r;
1556
1557
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1558
1559
0
  for (; val < val_end; val += len) {
1560
    /* get the tag and the length */
1561
0
    u8 tag;
1562
0
    if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
1563
0
      break;
1564
1565
0
    switch (tag) {
1566
0
    case CAC_TAG_APPLET_FAMILY:
1567
0
      if (len != 5) {
1568
0
        sc_log(card->ctx, "TAG: Applet Information: "
1569
0
            "bad length %"SC_FORMAT_LEN_SIZE_T"u", len);
1570
0
        break;
1571
0
      }
1572
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1573
0
          "TAG: Applet Information: Family: 0x%02x", val[0]);
1574
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1575
0
          "     Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x",
1576
0
          val[1], val[2], val[3], val[4]);
1577
0
      break;
1578
0
    case CAC_TAG_NUMBER_APPLETS:
1579
0
      if (len != 1) {
1580
0
        sc_log(card->ctx, "TAG: Num applets: "
1581
0
            "bad length %"SC_FORMAT_LEN_SIZE_T"u", len);
1582
0
        break;
1583
0
      }
1584
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1585
0
          "TAG: Num applets = %hhd", *val);
1586
0
      break;
1587
0
    case CAC_TAG_APPLET_ENTRY:
1588
      /* Make sure we match the outer length */
1589
0
      if (len < 3 || val[2] != len - 3) {
1590
0
        sc_log(card->ctx, "TAG: Applet Entry: "
1591
0
            "bad length (%"SC_FORMAT_LEN_SIZE_T
1592
0
            "u) or length of internal buffer", len);
1593
0
        break;
1594
0
      }
1595
0
      sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE,
1596
0
          "TAG: Applet Entry: AID", val + 3, val[2]);
1597
      /* This is SimpleTLV prefixed with applet ID (1B) */
1598
0
      r = cac_parse_aid(card, priv, val + 3, val[2]);
1599
0
      if (r < 0)
1600
0
        return r;
1601
0
      break;
1602
0
    default:
1603
      /* ignore tags we don't understand */
1604
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1605
0
          "TAG: Unknown (0x%02x)", tag);
1606
0
      break;
1607
0
    }
1608
0
  }
1609
0
  return SC_SUCCESS;
1610
0
}
1611
1612
/* select a CAC pki applet by index */
1613
static int cac_select_pki_applet(sc_card_t *card, int index)
1614
0
{
1615
0
  sc_path_t applet_path = cac_cac_pki_obj.path;
1616
0
  applet_path.aid.value[applet_path.aid.len-1] = index;
1617
0
  return cac_select_file_by_type(card, &applet_path, NULL);
1618
0
}
1619
1620
/*
1621
 *  Find the first existing CAC applet. If none found, then this isn't a CAC
1622
 */
1623
static int cac_find_first_pki_applet(sc_card_t *card, int *index_out)
1624
0
{
1625
0
  int r, i;
1626
0
  for (i = 0; i < MAX_CAC_SLOTS; i++) {
1627
0
    r = cac_select_pki_applet(card, i);
1628
0
    if (r == SC_SUCCESS) {
1629
      /* Try to read first two bytes of the buffer to
1630
       * make sure it is not just malfunctioning card
1631
       */
1632
0
      u8 params[2] = {CAC_FILE_TAG, 2};
1633
0
      u8 data[2], *out_ptr = data;
1634
0
      size_t len = 2;
1635
0
      r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0,
1636
0
          &params[0], sizeof(params), &out_ptr, &len);
1637
0
      if (r != 2)
1638
0
        continue;
1639
1640
0
      *index_out = i;
1641
0
      return SC_SUCCESS;
1642
0
    }
1643
0
  }
1644
0
  return SC_ERROR_OBJECT_NOT_FOUND;
1645
0
}
1646
1647
/*
1648
 * This emulates CCC for Alt tokens, that do not come with CCC nor ACA applets
1649
 */
1650
static int cac_populate_cac_alt(sc_card_t *card, int index, cac_private_data_t *priv)
1651
0
{
1652
0
  int r, i;
1653
0
  cac_object_t pki_obj = cac_cac_pki_obj;
1654
0
  u8 buf[100];
1655
0
  u8 *val;
1656
1657
  /* populate PKI objects */
1658
0
  for (i = index; i < MAX_CAC_SLOTS; i++) {
1659
0
    r = cac_select_pki_applet(card, i);
1660
0
    if (r == SC_SUCCESS) {
1661
0
      pki_obj.name = get_cac_label(i);
1662
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1663
0
          "CAC: pki_object found, cert_next=%d (%s),", i, pki_obj.name);
1664
0
      pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i;
1665
0
      pki_obj.fd = i+1; /* don't use id of zero */
1666
0
      cac_add_object_to_list(&priv->pki_list, &pki_obj);
1667
0
    }
1668
0
  }
1669
1670
  /* populate non-PKI objects */
1671
0
  for (i=0; i < cac_object_count; i++) {
1672
0
    r = cac_select_file_by_type(card, &cac_objects[i].path, NULL);
1673
0
    if (r == SC_SUCCESS) {
1674
0
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1675
0
          "CAC: obj_object found, cert_next=%d (%s),",
1676
0
          i, cac_objects[i].name);
1677
0
      cac_add_object_to_list(&priv->general_list, &cac_objects[i]);
1678
0
    }
1679
0
  }
1680
1681
  /*
1682
   * create a cuid to simulate the cac 2 cuid.
1683
   */
1684
0
  priv->cuid = cac_cac_cuid;
1685
  /* create a serial number by hashing the first 100 bytes of the
1686
   * first certificate on the card */
1687
0
  r = cac_select_pki_applet(card, index);
1688
0
  if (r < 0) {
1689
0
    return r; /* shouldn't happen unless the card has been removed or is malfunctioning */
1690
0
  }
1691
0
  val = buf;
1692
0
  r = cac_read_binary(card, 0, val, sizeof(buf), 0);
1693
0
  if (r > 0) {
1694
0
#ifdef ENABLE_OPENSSL
1695
0
    size_t val_len = r;
1696
0
    free(priv->cac_id);
1697
0
    priv->cac_id = malloc(20);
1698
0
    if (priv->cac_id == NULL) {
1699
0
      return SC_ERROR_OUT_OF_MEMORY;
1700
0
    }
1701
0
    SHA1(val, val_len, priv->cac_id);
1702
0
    priv->cac_id_len = 20;
1703
0
    sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE,
1704
0
        "cuid", priv->cac_id, priv->cac_id_len);
1705
#else
1706
    sc_log(card->ctx, "OpenSSL Required");
1707
    return SC_ERROR_NOT_SUPPORTED;
1708
#endif /* ENABLE_OPENSSL */
1709
0
  }
1710
0
  return SC_SUCCESS;
1711
0
}
1712
1713
static int cac_process_ACA(sc_card_t *card, cac_private_data_t *priv)
1714
0
{
1715
0
  int r;
1716
0
  u8 *val = NULL;
1717
0
  size_t val_len;
1718
1719
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1720
1721
  /* Assuming ACA is already selected */
1722
0
  r = cac_get_acr(card, CAC_ACR_SERVICE, &val, &val_len);
1723
0
  if (r < 0)
1724
0
    goto done;
1725
1726
0
  r = cac_parse_ACA_service(card, priv, val, val_len);
1727
0
        if (r == SC_SUCCESS) {
1728
0
    priv->aca_path = malloc(sizeof(sc_path_t));
1729
0
    if (!priv->aca_path) {
1730
0
      r = SC_ERROR_OUT_OF_MEMORY;
1731
0
      goto done;
1732
0
    }
1733
0
    memcpy(priv->aca_path, &cac_ACA_Path, sizeof(sc_path_t));
1734
0
  }
1735
0
done:
1736
0
  if (val)
1737
0
    free(val);
1738
0
  LOG_FUNC_RETURN(card->ctx, r);
1739
0
}
1740
1741
/*
1742
 * Look for a CAC card. If it exists, initialize our data structures
1743
 */
1744
static int cac_find_and_initialize(sc_card_t *card, int initialize)
1745
0
{
1746
0
  int r, index;
1747
0
  cac_private_data_t *priv = NULL;
1748
1749
  /* already initialized? */
1750
0
  if (card->drv_data) {
1751
0
    return SC_SUCCESS;
1752
0
  }
1753
1754
  /* is this a CAC-2 specified in NIST Interagency Report 6887 -
1755
   * "Government Smart Card Interoperability Specification v2.1 July 2003" */
1756
0
  r = cac_select_CCC(card);
1757
0
  if (r == SC_SUCCESS) {
1758
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CCC found, is CAC-2");
1759
0
    if (!initialize) /* match card only */
1760
0
      return r;
1761
1762
0
    priv = cac_new_private_data();
1763
0
    if (!priv)
1764
0
      return SC_ERROR_OUT_OF_MEMORY;
1765
0
    r = cac_process_CCC(card, priv, 0);
1766
0
    if (r == SC_SUCCESS) {
1767
0
      card->type = SC_CARD_TYPE_CAC_II;
1768
0
      card->drv_data = priv;
1769
0
      return r;
1770
0
    }
1771
0
  }
1772
1773
  /* Even some ALT tokens can be missing CCC so we should try with ACA */
1774
0
  r = cac_select_ACA(card);
1775
0
  if (r == SC_SUCCESS) {
1776
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA found, is CAC-2 without CCC");
1777
0
    if (!initialize) /* match card only */
1778
0
      return r;
1779
1780
0
    if (!priv) {
1781
0
      priv = cac_new_private_data();
1782
0
      if (!priv)
1783
0
        return SC_ERROR_OUT_OF_MEMORY;
1784
0
    }
1785
0
    r = cac_process_ACA(card, priv);
1786
0
    if (r == SC_SUCCESS) {
1787
0
      card->type = SC_CARD_TYPE_CAC_ALT_HID;
1788
0
      card->drv_data = priv;
1789
0
      return r;
1790
0
    }
1791
0
  }
1792
1793
  /* is this a CAC Alt token without any accompanying structures */
1794
0
  r = cac_find_first_pki_applet(card, &index);
1795
0
  if (r == SC_SUCCESS) {
1796
0
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC Alt");
1797
0
    if (!initialize) /* match card only */
1798
0
      return r;
1799
1800
0
    if (!priv) {
1801
0
      priv = cac_new_private_data();
1802
0
      if (!priv)
1803
0
        return SC_ERROR_OUT_OF_MEMORY;
1804
0
    }
1805
0
    card->drv_data = priv; /* needed for the read_binary() */
1806
0
    r = cac_populate_cac_alt(card, index, priv);
1807
0
    if (r == SC_SUCCESS) {
1808
0
      card->type = SC_CARD_TYPE_CAC_II;
1809
0
      return r;
1810
0
    }
1811
0
    card->drv_data = NULL; /* reset on failure */
1812
0
  }
1813
0
  if (priv) {
1814
0
    cac_free_private_data(priv);
1815
0
  }
1816
0
  return r;
1817
0
}
1818
1819
1820
/* NOTE: returns a bool, 1 card matches, 0 it does not */
1821
static int cac_match_card(sc_card_t *card)
1822
0
{
1823
0
  int r;
1824
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1825
1826
0
  r = cac_find_and_initialize(card, 0);
1827
0
  return (r == SC_SUCCESS); /* never match */
1828
0
}
1829
1830
1831
static int cac_init(sc_card_t *card)
1832
0
{
1833
0
  int r;
1834
0
  unsigned long flags;
1835
1836
0
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1837
1838
0
  r = cac_find_and_initialize(card, 1);
1839
0
  if (r < 0) {
1840
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD);
1841
0
  }
1842
0
  flags = SC_ALGORITHM_RSA_RAW;
1843
1844
0
  _sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */
1845
0
  _sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */
1846
0
  _sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */
1847
1848
0
  card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO;
1849
1850
0
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
1851
0
}
1852
1853
static int cac_logout(sc_card_t *card)
1854
0
{
1855
0
  int index;
1856
0
  return cac_find_first_pki_applet(card, &index);
1857
0
}
1858
1859
static int cac_pin_cmd(sc_card_t *card, struct sc_pin_cmd_data *data, int *tries_left)
1860
0
{
1861
  /* CAC, like PIV needs Extra validation of (new) PIN during
1862
   * a PIN change request, to ensure it's not outside the
1863
   * FIPS 201 4.1.6.1 (numeric only) and * FIPS 140-2
1864
   * (6 character minimum) requirements.
1865
   */
1866
0
  sc_apdu_t apdu;
1867
0
  u8  sbuf[SC_MAX_APDU_BUFFER_SIZE];
1868
0
  struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
1869
0
  int rv;
1870
1871
0
  if (data->cmd == SC_PIN_CMD_CHANGE) {
1872
0
    size_t i = 0;
1873
0
    if (data->pin2.len < 6) {
1874
0
      return SC_ERROR_INVALID_PIN_LENGTH;
1875
0
    }
1876
0
    for(i=0; i < data->pin2.len; ++i) {
1877
0
      if (!isdigit(data->pin2.data[i])) {
1878
0
        return SC_ERROR_INVALID_DATA;
1879
0
      }
1880
0
    }
1881
1882
    /* We can change the PIN of Giesecke & Devrient CAC ALT tokens
1883
     * with a bit non-standard APDU */
1884
0
    if (card->type == SC_CARD_TYPE_CAC_ALT_HID) {
1885
0
      int r = 0;
1886
0
      r = iso7816_build_pin_apdu(card, &apdu, data, sbuf, sizeof(sbuf));
1887
0
      if (r < 0)
1888
0
        return r;
1889
      /* it requires P1 = 0x01 completely against the ISO specs */
1890
0
      apdu.p1 = 0x01;
1891
0
      data->apdu = &apdu;
1892
0
    }
1893
0
  }
1894
1895
0
  rv = iso_drv->ops->pin_cmd(card, data, tries_left);
1896
1897
0
  data->apdu = NULL;
1898
0
  return rv;
1899
0
}
1900
1901
static struct sc_card_operations cac_ops;
1902
1903
static struct sc_card_driver cac_drv = {
1904
  "Common Access Card (CAC)",
1905
  "cac",
1906
  &cac_ops,
1907
  NULL, 0, NULL
1908
};
1909
1910
static struct sc_card_driver * sc_get_driver(void)
1911
0
{
1912
0
  struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
1913
1914
0
  cac_ops = *iso_drv->ops;
1915
0
  cac_ops.match_card = cac_match_card;
1916
0
  cac_ops.init = cac_init;
1917
0
  cac_ops.finish = cac_finish;
1918
1919
0
  cac_ops.select_file =  cac_select_file; /* need to record object type */
1920
0
  cac_ops.get_challenge = cac_get_challenge;
1921
0
  cac_ops.read_binary = cac_read_binary;
1922
  /* CAC driver is read only */
1923
0
  cac_ops.write_binary = NULL;
1924
0
  cac_ops.set_security_env = cac_set_security_env;
1925
0
  cac_ops.restore_security_env = cac_restore_security_env;
1926
0
  cac_ops.compute_signature = cac_compute_signature;
1927
0
  cac_ops.decipher =  cac_decipher;
1928
0
  cac_ops.card_ctl = cac_card_ctl;
1929
0
  cac_ops.pin_cmd = cac_pin_cmd;
1930
0
  cac_ops.logout = cac_logout;
1931
1932
0
  return &cac_drv;
1933
0
}
1934
1935
1936
struct sc_card_driver * sc_get_cac_driver(void)
1937
0
{
1938
0
  return sc_get_driver();
1939
0
}