Coverage Report

Created: 2026-09-01 06:16

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