Coverage Report

Created: 2025-12-07 06:38

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
2.14k
#define CAC_MAX_CHUNK_SIZE 240
60
783
#define CAC_INS_SIGN_DECRYPT          0x42  /* A crypto operation */
61
207k
#define CAC_INS_READ_FILE             0x52  /* read a TL or V file */
62
2.88k
#define CAC_INS_GET_ACR               0x4c
63
4.07k
#define CAC_INS_GET_PROPERTIES        0x56
64
470
#define CAC_P1_STEP    0x80
65
313
#define CAC_P1_FINAL   0x00
66
23.1k
#define CAC_FILE_TAG    1
67
16.4k
#define CAC_FILE_VALUE  2
68
/* TAGS in a TL file */
69
19.1k
#define CAC_TAG_CERTIFICATE           0x70
70
19.1k
#define CAC_TAG_CERTINFO              0x71
71
19.1k
#define CAC_TAG_MSCUID                0x72
72
18.3k
#define CAC_TAG_CUID                  0xF0
73
12.1k
#define CAC_TAG_CC_VERSION_NUMBER     0xF1
74
14.6k
#define CAC_TAG_GRAMMAR_VERION_NUMBER 0xF2
75
72.7k
#define CAC_TAG_CARDURL               0xF3
76
2.52k
#define CAC_TAG_PKCS15                0xF4
77
3.68k
#define CAC_TAG_ACCESS_CONTROL        0xF6
78
4.52k
#define CAC_TAG_DATA_MODEL            0xF5
79
4.21k
#define CAC_TAG_CARD_APDU             0xF7
80
15.5k
#define CAC_TAG_REDIRECTION           0xFA
81
8.60k
#define CAC_TAG_CAPABILITY_TUPLES     0xFB
82
11.9k
#define CAC_TAG_STATUS_TUPLES         0xFC
83
12.6k
#define CAC_TAG_NEXT_CCC              0xFD
84
16.0k
#define CAC_TAG_ERROR_CODES           0xFE
85
4.62k
#define CAC_TAG_APPLET_FAMILY         0x01
86
3.70k
#define CAC_TAG_NUMBER_APPLETS        0x94
87
9.13k
#define CAC_TAG_APPLET_ENTRY          0x93
88
#define CAC_TAG_APPLET_AID            0x92
89
6.45k
#define CAC_TAG_APPLET_INFORMATION    0x01
90
6.77k
#define CAC_TAG_NUMBER_OF_OBJECTS     0x40
91
6.89k
#define CAC_TAG_TV_BUFFER             0x50
92
19.4k
#define CAC_TAG_PKI_OBJECT            0x51
93
12.1k
#define CAC_TAG_OBJECT_ID             0x41
94
8.28k
#define CAC_TAG_BUFFER_PROPERTIES     0x42
95
10.7k
#define CAC_TAG_PKI_PROPERTIES        0x43
96
97
33.4k
#define CAC_APP_TYPE_GENERAL          0x01
98
2.13k
#define CAC_APP_TYPE_SKI              0x02
99
8.88k
#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
2.88k
#define CAC_ACR_SERVICE               0x21
105
106
15.1k
#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
17.2k
#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
13.3k
#define CAC_OBJECT_TYPE_CERT    1
171
470
#define CAC_OBJECT_TYPE_TLV_FILE  4
172
48.7k
#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
33.4k
{
217
33.4k
  int i;
218
219
151k
  for (i = 0; i < cac_object_count; i++) {
220
143k
    if (cac_objects[i].fd == object_id) {
221
26.0k
      return &cac_objects[i];
222
26.0k
    }
223
143k
  }
224
7.38k
  return NULL;
225
33.4k
}
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
48.7k
{
232
48.7k
  cac_object_t test_obj;
233
48.7k
  test_obj.path = *in_path;
234
48.7k
  test_obj.path.index = 0;
235
48.7k
  test_obj.path.count = 0;
236
237
48.7k
  return (list_contains(&priv->pki_list, &test_obj) != 0);
238
48.7k
}
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
216k
{
254
216k
  int r;
255
216k
  sc_apdu_t apdu = {0};
256
216k
  u8 rbufinitbuf[CAC_MAX_SIZE];
257
216k
  u8 *rbuf;
258
216k
  size_t rbuflen;
259
216k
  unsigned int apdu_case = SC_APDU_CASE_1;
260
261
262
216k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
263
264
216k
  sc_log(card->ctx,
265
216k
     "%02x %02x %02x %"SC_FORMAT_LEN_SIZE_T"u : %"SC_FORMAT_LEN_SIZE_T"u %"SC_FORMAT_LEN_SIZE_T"u\n",
266
216k
     ins, p1, p2, sendbuflen, card->max_send_size,
267
216k
     card->max_recv_size);
268
269
216k
  rbuf = rbufinitbuf;
270
216k
  rbuflen = sizeof(rbufinitbuf);
271
272
  /* if caller provided a buffer and length */
273
216k
  if (recvbuf && *recvbuf && recvbuflen && *recvbuflen) {
274
209k
    rbuf = *recvbuf;
275
209k
    rbuflen = *recvbuflen;
276
209k
  }
277
278
216k
  if (recvbuf) {
279
216k
    if (sendbuf)
280
208k
      apdu_case = SC_APDU_CASE_4_SHORT;
281
8.32k
    else
282
8.32k
      apdu_case = SC_APDU_CASE_2_SHORT;
283
216k
  } else if (sendbuf)
284
0
    apdu_case = SC_APDU_CASE_3_SHORT;
285
286
287
216k
  sc_format_apdu(card, &apdu, apdu_case, ins, p1, p2);
288
289
216k
  apdu.lc = sendbuflen;
290
216k
  apdu.datalen = sendbuflen;
291
216k
  apdu.data = sendbuf;
292
293
216k
  if (recvbuf) {
294
216k
    apdu.resp = rbuf;
295
216k
    apdu.le = (rbuflen > 255) ? 255 : rbuflen;
296
216k
    apdu.resplen = rbuflen;
297
216k
  } else {
298
0
     apdu.resp =  rbuf;
299
0
     apdu.le = 0;
300
0
     apdu.resplen = 0;
301
0
  }
302
303
216k
  sc_log(card->ctx,
304
216k
     "calling sc_transmit_apdu flags=%lx le=%"SC_FORMAT_LEN_SIZE_T"u, resplen=%"SC_FORMAT_LEN_SIZE_T"u, resp=%p",
305
216k
     apdu.flags, apdu.le, apdu.resplen, apdu.resp);
306
307
  /* with new adpu.c and chaining, this actually reads the whole object */
308
216k
  r = sc_transmit_apdu(card, &apdu);
309
310
216k
  sc_log(card->ctx,
311
216k
     "result r=%d apdu.resplen=%"SC_FORMAT_LEN_SIZE_T"u sw1=%02x sw2=%02x",
312
216k
     r, apdu.resplen, apdu.sw1, apdu.sw2);
313
216k
  if (r < 0) {
314
1.28k
    sc_log(card->ctx, "Transmit failed");
315
1.28k
    goto err;
316
1.28k
  }
317
318
215k
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
319
320
215k
  if (r < 0) {
321
3.58k
    sc_log(card->ctx,  "Card returned error ");
322
3.58k
    goto err;
323
3.58k
  }
324
325
212k
  if (recvbuflen) {
326
212k
    if (recvbuf && *recvbuf == NULL) {
327
7.07k
      *recvbuf =  malloc(apdu.resplen);
328
7.07k
      if (*recvbuf == NULL) {
329
0
        r = SC_ERROR_OUT_OF_MEMORY;
330
0
        goto err;
331
0
      }
332
7.07k
      memcpy(*recvbuf, rbuf, apdu.resplen);
333
7.07k
    }
334
212k
    *recvbuflen =  apdu.resplen;
335
212k
    r = (int)*recvbuflen;
336
212k
  }
337
338
216k
err:
339
216k
  LOG_FUNC_RETURN(card->ctx, r);
340
216k
}
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
2.88k
{
349
2.88k
  u8 *out = NULL;
350
  /* XXX assuming it will not be longer than 255 B */
351
2.88k
  size_t len = 256;
352
2.88k
  int r;
353
354
2.88k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
355
356
  /* for simplicity we support only ACR without arguments now */
357
2.88k
  if (acr_type != 0x00 && acr_type != 0x10
358
2.88k
      && acr_type != 0x20 && acr_type != 0x21) {
359
0
    return SC_ERROR_INVALID_ARGUMENTS;
360
0
  }
361
362
2.88k
  r = cac_apdu_io(card, CAC_INS_GET_ACR, acr_type, 0, NULL, 0, &out, &len);
363
2.88k
  if (len == 0) {
364
84
    r = SC_ERROR_FILE_NOT_FOUND;
365
84
  }
366
2.88k
  if (r < 0)
367
276
    goto fail;
368
369
2.60k
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
370
2.60k
      "got %"SC_FORMAT_LEN_SIZE_T"u bytes out=%p", len, out);
371
372
2.60k
  *out_len = len;
373
2.60k
  *out_buf = out;
374
2.60k
  return SC_SUCCESS;
375
376
276
fail:
377
276
  if (out)
378
84
    free(out);
379
276
  *out_buf = NULL;
380
276
  *out_len = 0;
381
276
  return r;
382
2.88k
}
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
168k
#define HIGH_BYTE_OF_SHORT(x) (((x)>> 8) & 0xff)
388
168k
#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
36.5k
{
391
36.5k
  u8 params[2];
392
36.5k
  u8 count[2] = {0};
393
36.5k
  u8 *out = NULL;
394
36.5k
  u8 *out_ptr = NULL;
395
36.5k
  size_t offset = 0;
396
36.5k
  size_t size = 0;
397
36.5k
  size_t left = 0;
398
36.5k
  size_t len = 0;
399
36.5k
  int r;
400
401
36.5k
  params[0] = file_type;
402
36.5k
  params[1] = 2;
403
404
  /* get the size */
405
36.5k
  len = sizeof(count);
406
36.5k
  out_ptr = count;
407
36.5k
  r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0, &params[0], sizeof(params), &out_ptr, &len);
408
36.5k
  if (len == 0) {
409
1.08k
    r = SC_ERROR_FILE_NOT_FOUND;
410
1.08k
  }
411
36.5k
  if (r < 0)
412
2.61k
    goto fail;
413
414
33.8k
  left = size = lebytes2ushort(count);
415
33.8k
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
416
33.8k
     "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
33.8k
     len, out_ptr, &count, count[0], count[1], size, size);
418
33.8k
  out = out_ptr = malloc(size);
419
33.8k
  if (out == NULL) {
420
0
    r = SC_ERROR_OUT_OF_MEMORY;
421
0
    goto fail;
422
0
  }
423
200k
  for (offset += 2; left > 0; offset += len, left -= len, out_ptr += len) {
424
168k
    len = MIN(left, CAC_MAX_CHUNK_SIZE);
425
168k
    params[1] = len;
426
168k
    r = cac_apdu_io(card, CAC_INS_READ_FILE, HIGH_BYTE_OF_SHORT(offset), LOW_BYTE_OF_SHORT(offset),
427
168k
            &params[0], sizeof(params), &out_ptr, &len);
428
    /* if there is no data, assume there is no file */
429
168k
    if (len == 0) {
430
350
      r = SC_ERROR_FILE_NOT_FOUND;
431
350
    }
432
168k
    if (r < 0) {
433
1.42k
      goto fail;
434
1.42k
    }
435
168k
  }
436
32.4k
  *out_len = size;
437
32.4k
  *out_buf = out;
438
32.4k
  return SC_SUCCESS;
439
4.04k
fail:
440
4.04k
  if (out)
441
1.42k
    free(out);
442
4.04k
  *out_len = 0;
443
4.04k
  return r;
444
33.8k
}
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
6.91k
{
455
6.91k
  cac_private_data_t * priv = CAC_DATA(card);
456
6.91k
  int r = 0;
457
6.91k
  u8 *tl = NULL, *val = NULL;
458
6.91k
  const u8 *tl_ptr, *val_ptr, *tl_start;
459
6.91k
  u8 *tlv_ptr;
460
6.91k
  const u8 *cert_ptr;
461
6.91k
  size_t tl_len = 0, val_len = 0, tlv_len;
462
6.91k
  size_t len, tl_head_len, cert_len;
463
6.91k
  u8 cert_type, tag;
464
465
6.91k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
466
467
  /* if we didn't return it all last time, return the remainder */
468
6.91k
  if (priv->cached) {
469
1.97k
    sc_log(card->ctx,
470
1.97k
       "returning cached value idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u",
471
1.97k
       idx, count);
472
1.97k
    if (idx > priv->cache_buf_len) {
473
0
      LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_END_REACHED);
474
0
    }
475
1.97k
    len = MIN(count, priv->cache_buf_len-idx);
476
1.97k
    memcpy(buf, &priv->cache_buf[idx], len);
477
1.97k
    LOG_FUNC_RETURN(card->ctx, (int)len);
478
1.97k
  }
479
480
4.94k
  sc_log(card->ctx,
481
4.94k
     "clearing cache idx=%d count=%"SC_FORMAT_LEN_SIZE_T"u",
482
4.94k
     idx, count);
483
4.94k
  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
4.94k
  if (priv->object_type <= 0)
491
4.94k
     LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
492
493
4.94k
  r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len);
494
4.94k
  if (r < 0)  {
495
2.75k
    goto done;
496
2.75k
  }
497
498
2.19k
  r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len);
499
2.19k
  if (r < 0)
500
256
    goto done;
501
502
1.93k
  switch (priv->object_type) {
503
224
  case CAC_OBJECT_TYPE_TLV_FILE:
504
224
    tlv_len = tl_len + val_len;
505
224
    priv->cache_buf = malloc(tlv_len);
506
224
    if (priv->cache_buf == NULL) {
507
0
      r = SC_ERROR_OUT_OF_MEMORY;
508
0
      goto done;
509
0
    }
510
224
    priv->cache_buf_len = tlv_len;
511
512
224
    for (tl_ptr = tl, val_ptr=val, tlv_ptr = priv->cache_buf;
513
13.0k
        tl_len >= 2 && tlv_len > 0;
514
12.8k
        val_len -= len, tlv_len -= len, val_ptr += len, tlv_ptr += len) {
515
      /* get the tag and the length */
516
12.8k
      tl_start = tl_ptr;
517
12.8k
      r = sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len);
518
12.8k
      if (r != SC_SUCCESS && r != SC_ERROR_TLV_END_OF_CONTENTS)
519
13
        break;
520
12.8k
      tl_head_len = (tl_ptr - tl_start);
521
12.8k
      sc_simpletlv_put_tag(tag, len, tlv_ptr, tlv_len, &tlv_ptr);
522
12.8k
      tlv_len -= tl_head_len;
523
12.8k
      tl_len -= tl_head_len;
524
525
      /* don't crash on bad data */
526
12.8k
      if (val_len < len) {
527
8.83k
        sc_log(card->ctx, "Received too long value %"SC_FORMAT_LEN_SIZE_T"u, "
528
8.83k
            "while only %"SC_FORMAT_LEN_SIZE_T"u left. Truncating", len, val_len);
529
8.83k
        len = val_len;
530
8.83k
      }
531
      /* if we run out of return space, truncate */
532
12.8k
      if (tlv_len < len) {
533
0
        len = tlv_len;
534
0
      }
535
12.8k
      memcpy(tlv_ptr, val_ptr, len);
536
12.8k
    }
537
224
    break;
538
539
1.69k
  case CAC_OBJECT_TYPE_CERT:
540
    /* read file */
541
1.69k
    sc_log(card->ctx,
542
1.69k
       " obj= cert_file, val_len=%"SC_FORMAT_LEN_SIZE_T"u (0x%04"SC_FORMAT_LEN_SIZE_T"x)",
543
1.69k
       val_len, val_len);
544
1.69k
    cert_len = 0;
545
1.69k
    cert_ptr = NULL;
546
1.69k
    cert_type = 0;
547
20.8k
    for (tl_ptr = tl, val_ptr = val; tl_len >= 2;
548
19.8k
        val_len -= len, val_ptr += len, tl_len -= tl_head_len) {
549
19.8k
      tl_start = tl_ptr;
550
19.8k
      r = sc_simpletlv_read_tag(&tl_ptr, tl_len, &tag, &len);
551
19.8k
      if (r != SC_SUCCESS && r != SC_ERROR_TLV_END_OF_CONTENTS)
552
52
        break;
553
19.8k
      tl_head_len = tl_ptr - tl_start;
554
555
      /* incomplete value */
556
19.8k
      if (val_len < len) {
557
643
        sc_log(card->ctx, "Read incomplete value %"SC_FORMAT_LEN_SIZE_T"u, "
558
643
            "while only %"SC_FORMAT_LEN_SIZE_T"u left", len, val_len);
559
643
        break;
560
643
      }
561
562
19.1k
      if (tag == CAC_TAG_CERTIFICATE) {
563
781
        cert_len = len;
564
781
        cert_ptr = val_ptr;
565
781
      }
566
19.1k
      if (tag == CAC_TAG_CERTINFO) {
567
2.88k
        if ((len >= 1) && (val_len >=1)) {
568
1.98k
          cert_type = *val_ptr;
569
1.98k
        }
570
2.88k
      }
571
19.1k
      if (tag == CAC_TAG_MSCUID) {
572
448
        sc_log_hex(card->ctx, "MSCUID", val_ptr, len);
573
448
      }
574
19.1k
    }
575
    /* if the info byte is 1, then the cert is compressed, decompress it */
576
1.69k
    if ((cert_type & 0x3) == 1 && flags) {
577
438
      *flags |= SC_FILE_FLAG_COMPRESSED_AUTO;
578
438
    }
579
1.69k
    if (cert_len > 0) {
580
552
      priv->cache_buf = malloc(cert_len);
581
552
      if (priv->cache_buf == NULL) {
582
0
        r = SC_ERROR_OUT_OF_MEMORY;
583
0
        goto done;
584
0
      }
585
552
      priv->cache_buf_len = cert_len;
586
552
      memcpy(priv->cache_buf, cert_ptr, cert_len);
587
1.14k
    } else {
588
1.14k
      sc_log(card->ctx, "Can't read zero-length certificate");
589
1.14k
      goto done;
590
1.14k
    }
591
552
    break;
592
552
  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
12
  default:
598
    /* Unknown object type */
599
12
    sc_log(card->ctx, "Unknown object type: %x", priv->object_type);
600
12
    r = SC_ERROR_INTERNAL;
601
12
    goto done;
602
1.93k
  }
603
604
  /* OK we've read the data, now copy the required portion out to the callers buffer */
605
776
  priv->cached = 1;
606
776
  len = MIN(count, priv->cache_buf_len-idx);
607
776
  memcpy(buf, &priv->cache_buf[idx], len);
608
776
  r = (int)len;
609
4.94k
done:
610
4.94k
  if (tl)
611
2.19k
    free(tl);
612
4.94k
  if (val)
613
1.93k
    free(val);
614
4.94k
  LOG_FUNC_RETURN(card->ctx, r);
615
4.94k
}
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
8.93k
{
620
8.93k
  *countp = list_size(list);
621
8.93k
  list_iterator_start(list);
622
8.93k
  *entry = list_iterator_next(list);
623
8.93k
  return SC_SUCCESS;
624
8.93k
}
625
626
/* finalize the list iterator */
627
static int cac_final_iterator(list_t *list)
628
8.93k
{
629
8.93k
  list_iterator_stop(list);
630
8.93k
  return SC_SUCCESS;
631
8.93k
}
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
30.8k
{
636
30.8k
  memset(obj_info, 0, sizeof(sc_pkcs15_data_info_t));
637
30.8k
  if (*entry == NULL) {
638
0
    return SC_ERROR_FILE_END_REACHED;
639
0
  }
640
641
30.8k
  obj_info->path = (*entry)->path;
642
30.8k
  obj_info->path.count = CAC_MAX_SIZE-1; /* read something from the object */
643
30.8k
  obj_info->id.value[0] = ((*entry)->fd >> 8) & 0xff;
644
30.8k
  obj_info->id.value[1] = (*entry)->fd & 0xff;
645
30.8k
  obj_info->id.len = 2;
646
30.8k
  strncpy(obj_info->app_label, (*entry)->name, SC_PKCS15_MAX_LABEL_SIZE-1);
647
30.8k
  *entry = list_iterator_next(list);
648
30.8k
  return SC_SUCCESS;
649
30.8k
}
650
651
static int cac_get_serial_nr_from_CUID(sc_card_t* card, sc_serial_number_t* serial)
652
4.46k
{
653
4.46k
  cac_private_data_t * priv = CAC_DATA(card);
654
655
4.46k
  LOG_FUNC_CALLED(card->ctx);
656
4.46k
        if (card->serialnr.len)   {
657
0
                *serial = card->serialnr;
658
0
                LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
659
0
        }
660
4.46k
  if (priv->cac_id_len) {
661
973
    serial->len = MIN(priv->cac_id_len, SC_MAX_SERIALNR);
662
973
    memcpy(serial->value, priv->cac_id, serial->len);
663
973
    LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
664
973
  }
665
3.49k
  LOG_FUNC_RETURN(card->ctx, SC_ERROR_FILE_NOT_FOUND);
666
3.49k
}
667
668
static int cac_get_ACA_path(sc_card_t *card, sc_path_t *path)
669
4.46k
{
670
4.46k
  cac_private_data_t * priv = CAC_DATA(card);
671
672
4.46k
  LOG_FUNC_CALLED(card->ctx);
673
4.46k
  if (priv->aca_path) {
674
1.77k
    *path = *priv->aca_path;
675
1.77k
  }
676
4.46k
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
677
4.46k
}
678
679
static int cac_card_ctl(sc_card_t *card, unsigned long cmd, void *ptr)
680
65.2k
{
681
65.2k
  cac_private_data_t * priv = CAC_DATA(card);
682
683
65.2k
  LOG_FUNC_CALLED(card->ctx);
684
65.2k
  sc_log(card->ctx, "cmd=%ld ptr=%p", cmd, ptr);
685
686
65.2k
  if (priv == NULL) {
687
0
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INTERNAL);
688
0
  }
689
65.2k
  switch(cmd) {
690
4.46k
    case SC_CARDCTL_CAC_GET_ACA_PATH:
691
4.46k
      return cac_get_ACA_path(card, (sc_path_t *) ptr);
692
4.46k
    case SC_CARDCTL_GET_SERIALNR:
693
4.46k
      return cac_get_serial_nr_from_CUID(card, (sc_serial_number_t *) ptr);
694
4.46k
    case SC_CARDCTL_CAC_INIT_GET_GENERIC_OBJECTS:
695
4.46k
      return cac_get_init_and_get_count(&priv->general_list, &priv->general_current, (int *)ptr);
696
4.46k
    case SC_CARDCTL_CAC_INIT_GET_CERT_OBJECTS:
697
4.46k
      return cac_get_init_and_get_count(&priv->pki_list, &priv->pki_current, (int *)ptr);
698
17.1k
    case SC_CARDCTL_CAC_GET_NEXT_GENERIC_OBJECT:
699
17.1k
      return cac_fill_object_info(&priv->general_list, &priv->general_current, (sc_pkcs15_data_info_t *)ptr);
700
13.7k
    case SC_CARDCTL_CAC_GET_NEXT_CERT_OBJECT:
701
13.7k
      return cac_fill_object_info(&priv->pki_list, &priv->pki_current, (sc_pkcs15_data_info_t *)ptr);
702
4.46k
    case SC_CARDCTL_CAC_FINAL_GET_GENERIC_OBJECTS:
703
4.46k
      return cac_final_iterator(&priv->general_list);
704
4.46k
    case SC_CARDCTL_CAC_FINAL_GET_CERT_OBJECTS:
705
4.46k
      return cac_final_iterator(&priv->pki_list);
706
65.2k
  }
707
708
7.60k
  LOG_FUNC_RETURN(card->ctx, SC_ERROR_NOT_SUPPORTED);
709
7.60k
}
710
711
static int cac_get_challenge(sc_card_t *card, u8 *rnd, size_t len)
712
1.37k
{
713
  /* CAC requires 8 byte response */
714
1.37k
  u8 rbuf[8];
715
1.37k
  u8 *rbufp = &rbuf[0];
716
1.37k
  size_t out_len = sizeof rbuf;
717
1.37k
  int r;
718
719
1.37k
  LOG_FUNC_CALLED(card->ctx);
720
721
1.37k
  r = cac_apdu_io(card, 0x84, 0x00, 0x00, NULL, 0, &rbufp, &out_len);
722
1.37k
  LOG_TEST_RET(card->ctx, r, "Could not get challenge");
723
724
815
  if (len < out_len) {
725
3
    out_len = len;
726
3
  }
727
815
  memcpy(rnd, rbuf, out_len);
728
729
815
  LOG_FUNC_RETURN(card->ctx, (int) out_len);
730
815
}
731
732
static int cac_set_security_env(sc_card_t *card, const sc_security_env_t *env, int se_num)
733
339
{
734
339
  int r = SC_SUCCESS;
735
736
339
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
737
738
339
  sc_log(card->ctx,
739
339
     "flags=%08lx op=%d alg=%lu algf=%08lx algr=%08lx kr0=%02x, krfl=%"SC_FORMAT_LEN_SIZE_T"u\n",
740
339
     env->flags, env->operation, env->algorithm,
741
339
     env->algorithm_flags, env->algorithm_ref, env->key_ref[0],
742
339
     env->key_ref_len);
743
744
339
  if (env->algorithm != SC_ALGORITHM_RSA) {
745
0
     r = SC_ERROR_NO_CARD_SUPPORT;
746
0
  }
747
748
749
339
  SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r);
750
339
}
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
339
{
765
339
  int r;
766
339
  u8 *outp, *rbuf;
767
339
  size_t rbuflen, outplen;
768
769
339
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
770
339
  sc_log(card->ctx,
771
339
     "datalen=%"SC_FORMAT_LEN_SIZE_T"u outlen=%"SC_FORMAT_LEN_SIZE_T"u\n",
772
339
     datalen, outlen);
773
774
339
  outp = out;
775
339
  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
339
  r = sc_lock(card);
782
339
  if (r != SC_SUCCESS)
783
339
    LOG_FUNC_RETURN(card->ctx, r);
784
785
786
339
  rbuf = NULL;
787
339
  rbuflen = 0;
788
783
  for (; datalen > CAC_MAX_CHUNK_SIZE; data += CAC_MAX_CHUNK_SIZE, datalen -= CAC_MAX_CHUNK_SIZE) {
789
470
    r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_STEP,  0,
790
470
      data, CAC_MAX_CHUNK_SIZE, &rbuf, &rbuflen);
791
470
    if (r < 0) {
792
26
      break;
793
26
    }
794
444
    if (rbuflen != 0) {
795
240
      size_t n = MIN(rbuflen, outplen);
796
240
      memcpy(outp, rbuf, n);
797
240
      outp += n;
798
240
      outplen -= n;
799
240
    }
800
444
    free(rbuf);
801
444
    rbuf = NULL;
802
444
    rbuflen = 0;
803
444
  }
804
339
  if (r < 0) {
805
26
    goto err;
806
26
  }
807
313
  rbuf = NULL;
808
313
  rbuflen = 0;
809
313
  r = cac_apdu_io(card, CAC_INS_SIGN_DECRYPT, CAC_P1_FINAL, 0, data, datalen, &rbuf, &rbuflen);
810
313
  if (r < 0) {
811
66
    goto err;
812
66
  }
813
247
  if (rbuflen != 0) {
814
170
    size_t n = MIN(rbuflen, outplen);
815
170
    memcpy(outp, rbuf, n);
816
    /*outp += n;     unused */
817
170
    outplen -= n;
818
170
  }
819
247
  free(rbuf);
820
247
  rbuf = NULL;
821
247
  r = (int)(outlen - outplen);
822
823
339
err:
824
339
  sc_unlock(card);
825
339
  if (r < 0) {
826
92
    sc_mem_clear(out, outlen);
827
92
  }
828
339
  if (rbuf) {
829
0
    free(rbuf);
830
0
  }
831
832
339
  LOG_FUNC_RETURN(card->ctx, r);
833
339
}
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
76
{
839
76
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
840
841
76
  SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen));
842
76
}
843
844
static int cac_decipher(sc_card_t *card,
845
           const u8 * data, size_t datalen,
846
           u8 * out, size_t outlen)
847
263
{
848
263
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
849
850
263
  SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, cac_rsa_op(card, data, datalen, out, outlen));
851
263
}
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
17.1k
{
856
17.1k
  size_t len;
857
17.1k
  const u8 *val, *val_end;
858
17.1k
  u8 tag;
859
17.1k
  int parsed = 0;
860
861
17.1k
  if (data_len < 11)
862
0
    return -1;
863
864
  /* Initialize: non-PKI applet */
865
17.1k
  object->privatekey = 0;
866
867
17.1k
  val = data;
868
17.1k
  val_end = data + data_len;
869
78.6k
  for (; val < val_end; val += len) {
870
    /* get the tag and the length */
871
72.7k
    if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
872
11.3k
      break;
873
874
61.4k
    switch (tag) {
875
12.1k
    case CAC_TAG_OBJECT_ID:
876
12.1k
      if (len != 2) {
877
4.59k
        sc_log(card->ctx, "TAG: Object ID: "
878
4.59k
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
879
4.59k
        break;
880
4.59k
      }
881
7.57k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
882
7.57k
          "TAG: Object ID = 0x%02x 0x%02x", val[0], val[1]);
883
7.57k
      memcpy(&object->oid, val, 2);
884
7.57k
      parsed++;
885
7.57k
      break;
886
887
8.28k
    case CAC_TAG_BUFFER_PROPERTIES:
888
8.28k
      if (len != 5) {
889
3.80k
        sc_log(card->ctx, "TAG: Buffer Properties: "
890
3.80k
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
891
3.80k
        break;
892
3.80k
      }
893
      /* First byte is "Type of Tag Supported" */
894
4.48k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
895
4.48k
          "TAG: Buffer Properties: Type of Tag Supported = 0x%02x",
896
4.48k
          val[0]);
897
4.48k
      object->simpletlv = val[0];
898
4.48k
      parsed++;
899
4.48k
      break;
900
901
10.7k
    case CAC_TAG_PKI_PROPERTIES:
902
      /* 4th byte is "Private Key Initialized" */
903
10.7k
      if (len != 4) {
904
5.10k
        sc_log(card->ctx, "TAG: PKI Properties: "
905
5.10k
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
906
5.10k
        break;
907
5.10k
      }
908
5.63k
      if (type != CAC_TAG_PKI_OBJECT) {
909
1.88k
        sc_log(card->ctx, "TAG: PKI Properties outside of PKI Object");
910
1.88k
        break;
911
1.88k
      }
912
3.74k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
913
3.74k
          "TAG: PKI Properties: Private Key Initialized = 0x%02x",
914
3.74k
          val[2]);
915
3.74k
      object->privatekey = val[2];
916
3.74k
      parsed++;
917
3.74k
      break;
918
919
30.2k
    default:
920
      /* ignore tags we don't understand */
921
30.2k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
922
30.2k
          "TAG: Unknown (0x%02x)",tag );
923
30.2k
      break;
924
61.4k
    }
925
61.4k
  }
926
17.1k
  if (parsed < 2)
927
12.6k
    return SC_ERROR_INVALID_DATA;
928
929
4.53k
  return SC_SUCCESS;
930
17.1k
}
931
932
static int cac_get_properties(sc_card_t *card, cac_properties_t *prop)
933
4.07k
{
934
4.07k
  u8 *rbuf = NULL;
935
4.07k
  size_t rbuflen = 0, len;
936
4.07k
  const u8 *val, *val_end;
937
4.07k
  u8 tag;
938
4.07k
  size_t i = 0;
939
4.07k
  int r;
940
4.07k
  prop->num_objects = 0;
941
942
4.07k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
943
944
4.07k
  r = cac_apdu_io(card, CAC_INS_GET_PROPERTIES, 0x01, 0x00, NULL, 0,
945
4.07k
    &rbuf, &rbuflen);
946
4.07k
  if (r < 0)
947
376
    return r;
948
949
3.69k
  val = rbuf;
950
3.69k
  val_end = val + rbuflen;
951
79.9k
  for (; val < val_end; val += len) {
952
    /* get the tag and the length */
953
78.1k
    if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
954
1.80k
      break;
955
956
76.3k
    switch (tag) {
957
6.45k
    case CAC_TAG_APPLET_INFORMATION:
958
6.45k
      if (len != 5) {
959
4.29k
        sc_log(card->ctx, "TAG: Applet Information: "
960
4.29k
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
961
4.29k
        break;
962
4.29k
      }
963
2.16k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
964
2.16k
          "TAG: Applet Information: Family: 0x%0x", val[0]);
965
2.16k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
966
2.16k
          "     Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x",
967
2.16k
          val[1], val[2], val[3], val[4]);
968
2.16k
      break;
969
970
6.77k
    case CAC_TAG_NUMBER_OF_OBJECTS:
971
6.77k
      if (len != 1) {
972
1.64k
        sc_log(card->ctx, "TAG: Num objects: "
973
1.64k
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
974
1.64k
        break;
975
1.64k
      }
976
5.12k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
977
5.12k
          "TAG: Num objects = %hhd", *val);
978
      /* make sure we do not overrun buffer */
979
5.12k
      prop->num_objects = MIN(val[0], CAC_MAX_OBJECTS);
980
5.12k
      break;
981
982
6.89k
    case CAC_TAG_TV_BUFFER:
983
6.89k
      if (len != 17) {
984
1.87k
        sc_log(card->ctx, "TAG: TV Object: "
985
1.87k
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
986
1.87k
        break;
987
1.87k
      }
988
5.01k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
989
5.01k
          "TAG: TV Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i);
990
5.01k
      if (i >= CAC_MAX_OBJECTS) {
991
17
        free(rbuf);
992
17
        return SC_SUCCESS;
993
17
      }
994
995
5.00k
      if (cac_parse_properties_object(card, tag, val, len,
996
5.00k
          &prop->objects[i]) == SC_SUCCESS)
997
717
        i++;
998
5.00k
      break;
999
1000
13.8k
    case CAC_TAG_PKI_OBJECT:
1001
13.8k
      if (len != 17) {
1002
1.58k
        sc_log(card->ctx, "TAG: PKI Object: "
1003
1.58k
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
1004
1.58k
        break;
1005
1.58k
      }
1006
12.2k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1007
12.2k
          "TAG: PKI Object nr. %"SC_FORMAT_LEN_SIZE_T"u", i);
1008
12.2k
      if (i >= CAC_MAX_OBJECTS) {
1009
65
        free(rbuf);
1010
65
        return SC_SUCCESS;
1011
65
      }
1012
1013
12.1k
      if (cac_parse_properties_object(card, tag, val, len,
1014
12.1k
          &prop->objects[i]) == SC_SUCCESS)
1015
3.81k
        i++;
1016
12.1k
      break;
1017
1018
42.4k
    default:
1019
      /* ignore tags we don't understand */
1020
42.4k
      sc_log(card->ctx, "TAG: Unknown (0x%02x), len=%"
1021
42.4k
          SC_FORMAT_LEN_SIZE_T"u", tag, len);
1022
42.4k
      break;
1023
76.3k
    }
1024
76.3k
  }
1025
3.61k
  free(rbuf);
1026
  /* sanity */
1027
3.61k
  if (i != prop->num_objects)
1028
894
    sc_log(card->ctx, "The announced number of objects (%zu) "
1029
3.61k
        "did not match reality (%"SC_FORMAT_LEN_SIZE_T"u)",
1030
3.61k
        prop->num_objects, i);
1031
3.61k
  prop->num_objects = i;
1032
1033
3.61k
  return SC_SUCCESS;
1034
3.69k
}
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
571k
{
1046
571k
  struct sc_context *ctx;
1047
571k
  struct sc_apdu apdu;
1048
571k
  unsigned char buf[SC_MAX_APDU_BUFFER_SIZE];
1049
571k
  unsigned char pathbuf[SC_MAX_PATH_SIZE], *path = pathbuf;
1050
571k
  int r, pathtype;
1051
571k
  size_t pathlen;
1052
571k
  struct sc_file *file = NULL;
1053
571k
  cac_private_data_t * priv = CAC_DATA(card);
1054
1055
571k
  assert(card != NULL && in_path != NULL);
1056
571k
  ctx = card->ctx;
1057
1058
571k
  SC_FUNC_CALLED(ctx, SC_LOG_DEBUG_VERBOSE);
1059
1060
571k
  memcpy(path, in_path->value, in_path->len);
1061
571k
  pathlen = in_path->len;
1062
571k
  pathtype = in_path->type;
1063
1064
571k
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1065
571k
      "path=%s, path->value=%s path->type=%d (%x)",
1066
571k
      sc_print_path(in_path),
1067
571k
      sc_dump_hex(in_path->value, in_path->len),
1068
571k
      in_path->type, in_path->type);
1069
571k
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "file_out=%p index=%d count=%d\n",
1070
571k
      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
571k
  if ((pathlen > 2) && (pathlen <= 4) && memcmp(path, "\x3F\x00", 2) == 0) {
1078
11.2k
    path += 2;
1079
11.2k
    pathlen -= 2;
1080
11.2k
  }
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
571k
  if (priv) { /* don't record anything if we haven't been initialized yet */
1088
48.7k
    priv->object_type = CAC_OBJECT_TYPE_GENERIC;
1089
48.7k
    if (cac_is_cert(priv, in_path)) {
1090
11.5k
      priv->object_type = CAC_OBJECT_TYPE_CERT;
1091
11.5k
    }
1092
1093
    /* forget any old cached values */
1094
48.7k
    if (priv->cache_buf) {
1095
586
      free(priv->cache_buf);
1096
586
      priv->cache_buf = NULL;
1097
586
    }
1098
48.7k
    priv->cache_buf_len = 0;
1099
48.7k
    priv->cached = 0;
1100
48.7k
  }
1101
1102
571k
  if (in_path->aid.len) {
1103
560k
    if (!pathlen) {
1104
542k
      memcpy(path, in_path->aid.value, in_path->aid.len);
1105
542k
      pathlen = in_path->aid.len;
1106
542k
      pathtype = SC_PATH_TYPE_DF_NAME;
1107
542k
    } else {
1108
      /* First, select the application */
1109
17.9k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"select application" );
1110
17.9k
      sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 4, 0);
1111
17.9k
      apdu.data = in_path->aid.value;
1112
17.9k
      apdu.datalen = in_path->aid.len;
1113
17.9k
      apdu.lc = in_path->aid.len;
1114
1115
17.9k
      r = sc_transmit_apdu(card, &apdu);
1116
17.9k
      LOG_TEST_RET(ctx, r, "APDU transmit failed");
1117
17.8k
      r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1118
17.8k
      if (r)
1119
17.8k
        LOG_FUNC_RETURN(ctx, r);
1120
1121
17.8k
    }
1122
560k
  }
1123
1124
568k
  sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0, 0);
1125
1126
568k
  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
15.0k
  case SC_PATH_TYPE_FILE_ID:
1131
15.0k
    apdu.p1 = 2;
1132
15.0k
    if (pathlen != 2)
1133
0
      return SC_ERROR_INVALID_ARGUMENTS;
1134
15.0k
    break;
1135
542k
  case SC_PATH_TYPE_DF_NAME:
1136
542k
    apdu.p1 = 4;
1137
542k
    break;
1138
10.9k
  default:
1139
10.9k
    LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
1140
568k
  }
1141
557k
  apdu.lc = pathlen;
1142
557k
  apdu.data = path;
1143
557k
  apdu.datalen = pathlen;
1144
557k
  apdu.resp = buf;
1145
557k
  apdu.resplen = sizeof(buf);
1146
557k
  apdu.le = sc_get_max_recv_size(card) < 256 ? sc_get_max_recv_size(card) : 256;
1147
1148
557k
  if (file_out != NULL) {
1149
7.66k
    apdu.p2 = 0;    /* first record, return FCI */
1150
7.66k
  }
1151
550k
  else {
1152
550k
    apdu.p2 = 0x0C;
1153
550k
  }
1154
1155
557k
  r = sc_transmit_apdu(card, &apdu);
1156
557k
  LOG_TEST_RET(ctx, r, "APDU transmit failed");
1157
1158
552k
  if (file_out == NULL) {
1159
    /* For some cards 'SELECT' can be only with request to return FCI/FCP. */
1160
544k
    r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1161
544k
    if (apdu.sw1 == 0x6A && apdu.sw2 == 0x86)   {
1162
793
      apdu.p2 = 0x00;
1163
793
      apdu.resplen = sizeof(buf);
1164
793
      if (sc_transmit_apdu(card, &apdu) == SC_SUCCESS)
1165
439
        r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1166
793
    }
1167
544k
    if (apdu.sw1 == 0x61)
1168
544k
      LOG_FUNC_RETURN(ctx, SC_SUCCESS);
1169
544k
    LOG_FUNC_RETURN(ctx, r);
1170
544k
  }
1171
1172
7.60k
  r = sc_check_sw(card, apdu.sw1, apdu.sw2);
1173
7.60k
  if (r)
1174
7.60k
    LOG_FUNC_RETURN(ctx, r);
1175
1176
  /* This needs to come after the applet selection */
1177
4.40k
  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
2.19k
    cac_properties_t prop;
1185
2.19k
    size_t i = -1;
1186
1187
2.19k
    r = cac_get_properties(card, &prop);
1188
2.19k
    if (r == SC_SUCCESS) {
1189
2.28k
      for (i = 0; i < prop.num_objects; i++) {
1190
757
        sc_log(card->ctx, "Searching for our OID: 0x%02x 0x%02x = 0x%02x 0x%02x",
1191
757
            prop.objects[i].oid[0], prop.objects[i].oid[1],
1192
757
          in_path->value[0], in_path->value[1]);
1193
757
        if (memcmp(prop.objects[i].oid,
1194
757
            in_path->value, 2) == 0)
1195
334
          break;
1196
757
      }
1197
1.85k
    }
1198
2.19k
    if (i < prop.num_objects) {
1199
334
      if (prop.objects[i].privatekey)
1200
66
        priv->object_type = CAC_OBJECT_TYPE_CERT;
1201
268
      else if (prop.objects[i].simpletlv == 0)
1202
246
        priv->object_type = CAC_OBJECT_TYPE_TLV_FILE;
1203
334
    }
1204
2.19k
  }
1205
1206
  /* CAC cards never return FCI, fake one */
1207
4.40k
  file = sc_file_new();
1208
4.40k
  if (file == NULL)
1209
4.40k
      LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
1210
4.40k
  file->path = *in_path;
1211
4.40k
  file->size = CAC_MAX_SIZE; /* we don't know how big, just give a large size until we can read the file */
1212
1213
4.40k
  *file_out = file;
1214
4.40k
  LOG_FUNC_RETURN(ctx, SC_SUCCESS);
1215
1216
4.40k
}
1217
1218
static int cac_select_file(sc_card_t *card, const sc_path_t *in_path, sc_file_t **file_out)
1219
22.5k
{
1220
22.5k
  return cac_select_file_by_type(card, in_path, file_out);
1221
22.5k
}
1222
1223
static int cac_finish(sc_card_t *card)
1224
4.64k
{
1225
4.64k
  cac_private_data_t * priv = CAC_DATA(card);
1226
1227
4.64k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1228
4.64k
  if (priv) {
1229
4.64k
    cac_free_private_data(priv);
1230
4.64k
  }
1231
4.64k
  return SC_SUCCESS;
1232
4.64k
}
1233
1234
1235
/* select the Card Capabilities Container on CAC-2 */
1236
static int cac_select_CCC(sc_card_t *card)
1237
38.5k
{
1238
38.5k
  return cac_select_file_by_type(card, &cac_CCC_Path, NULL);
1239
38.5k
}
1240
1241
/* Select ACA in non-standard location */
1242
static int cac_select_ACA(sc_card_t *card)
1243
31.4k
{
1244
31.4k
  return cac_select_file_by_type(card, &cac_ACA_Path, NULL);
1245
31.4k
}
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
85.4k
{
1249
85.4k
  if (len < 10) {
1250
96
    return SC_ERROR_INVALID_DATA;
1251
96
  }
1252
85.3k
  sc_mem_clear(path, sizeof(sc_path_t));
1253
85.3k
  memcpy(path->aid.value, &val->rid, sizeof(val->rid));
1254
85.3k
  memcpy(&path->aid.value[5], val->applicationID, sizeof(val->applicationID));
1255
85.3k
  path->aid.len = sizeof(val->rid) + sizeof(val->applicationID);
1256
85.3k
  memcpy(path->value, val->objectID, sizeof(val->objectID));
1257
85.3k
  path->len = sizeof(val->objectID);
1258
85.3k
  path->type = SC_PATH_TYPE_FILE_ID;
1259
85.3k
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1260
85.3k
     "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
85.3k
     path->aid.value[0], path->aid.value[1], path->aid.value[2],
1262
85.3k
     path->aid.value[3], path->aid.value[4], path->aid.value[5],
1263
85.3k
     path->aid.value[6], path->aid.len, path->value[0],
1264
85.3k
     path->value[1], path->len, path->type, path->type);
1265
85.3k
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1266
85.3k
     "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
85.3k
     val->rid[0], val->rid[1], val->rid[2], val->rid[3],
1268
85.3k
     val->rid[4], sizeof(val->rid), val->applicationID[0],
1269
85.3k
     val->applicationID[1], sizeof(val->applicationID),
1270
85.3k
     val->objectID[0], val->objectID[1], sizeof(val->objectID));
1271
1272
85.3k
  return SC_SUCCESS;
1273
85.4k
}
1274
1275
static int cac_parse_aid(sc_card_t *card, cac_private_data_t *priv, const u8 *aid, int aid_len)
1276
5.94k
{
1277
5.94k
  cac_object_t new_object;
1278
5.94k
  cac_properties_t prop;
1279
5.94k
  size_t i;
1280
5.94k
  int r;
1281
1282
5.94k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1283
1284
  /* Search for PKI applets (7 B). Ignore generic objects for now */
1285
5.94k
  if (aid_len != 7 || (memcmp(aid, CAC_1_RID "\x01", 6) != 0
1286
2.91k
      && memcmp(aid, CAC_1_RID "\x00", 6) != 0))
1287
3.95k
    return SC_SUCCESS;
1288
1289
1.99k
  sc_mem_clear(&new_object.path, sizeof(sc_path_t));
1290
1.99k
  memcpy(new_object.path.aid.value, aid, aid_len);
1291
1.99k
  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
1.99k
  r = cac_select_file_by_type(card, &new_object.path, NULL);
1297
1.99k
  LOG_TEST_RET(card->ctx, r, "Cannot select AID");
1298
1.88k
  r = cac_get_properties(card, &prop);
1299
1.88k
  LOG_TEST_RET(card->ctx, r, "Cannot get CAC properties");
1300
1301
4.10k
  for (i = 0; i < prop.num_objects; i++) {
1302
    /* don't fail just because we have more certs than we can support */
1303
2.35k
    if (priv->cert_next >= MAX_CAC_SLOTS)
1304
85
      return SC_SUCCESS;
1305
1306
2.26k
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1307
2.26k
        "ACA: pki_object found, cert_next=%d (%s), privkey=%d",
1308
2.26k
        priv->cert_next, get_cac_label(priv->cert_next),
1309
2.26k
        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
2.26k
    if (!prop.objects[i].privatekey) {
1316
1.40k
      priv->cert_next++;
1317
1.40k
      continue;
1318
1.40k
    }
1319
1320
    /* OID here has always 2B */
1321
862
    memcpy(new_object.path.value, &prop.objects[i].oid, 2);
1322
862
    new_object.path.len = 2;
1323
862
    new_object.path.type = SC_PATH_TYPE_FILE_ID;
1324
862
    new_object.name = get_cac_label(priv->cert_next);
1325
862
    new_object.fd = priv->cert_next+1;
1326
862
    cac_add_object_to_list(&priv->pki_list, &new_object);
1327
862
    priv->cert_next++;
1328
862
  }
1329
1330
1.75k
  return SC_SUCCESS;
1331
1.83k
}
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
72.7k
{
1335
72.7k
  cac_object_t new_object;
1336
72.7k
  const cac_object_t *obj;
1337
72.7k
  unsigned short object_id;
1338
72.7k
  int r;
1339
1340
72.7k
  r = cac_path_from_cardurl(card, &new_object.path, val, len);
1341
72.7k
  if (r != SC_SUCCESS) {
1342
54
    return r;
1343
54
  }
1344
72.7k
  switch (val->cardApplicationType) {
1345
8.88k
  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
8.88k
    if (priv->cert_next >= MAX_CAC_SLOTS)
1351
2.90k
      break; /* don't fail just because we have more certs than we can support */
1352
5.98k
    new_object.name = get_cac_label(priv->cert_next);
1353
5.98k
    new_object.fd = priv->cert_next+1;
1354
5.98k
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: pki_object found, cert_next=%d (%s),", priv->cert_next, new_object.name);
1355
5.98k
    cac_add_object_to_list(&priv->pki_list, &new_object);
1356
5.98k
    priv->cert_next++;
1357
5.98k
    break;
1358
33.4k
  case CAC_APP_TYPE_GENERAL:
1359
33.4k
    object_id = bebytes2ushort(val->objectID);
1360
33.4k
    obj = cac_find_obj_by_id(object_id);
1361
33.4k
    if (obj == NULL)
1362
7.38k
      break; /* don't fail just because we don't recognize the object */
1363
26.0k
    new_object.name = obj->name;
1364
26.0k
    new_object.fd = 0;
1365
26.0k
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: gen_object found, objectID=%x (%s),", object_id, new_object.name);
1366
26.0k
    cac_add_object_to_list(&priv->general_list, &new_object);
1367
26.0k
    break;
1368
2.13k
  case CAC_APP_TYPE_SKI:
1369
2.13k
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"CARDURL: ski_object found");
1370
2.13k
  break;
1371
28.2k
  default:
1372
28.2k
    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
28.2k
    break;
1375
72.7k
  }
1376
72.7k
  return SC_SUCCESS;
1377
72.7k
}
1378
1379
static int cac_parse_cuid(sc_card_t *card, cac_private_data_t *priv, cac_cuid_t *val, size_t len)
1380
18.3k
{
1381
18.3k
  size_t card_id_len;
1382
1383
18.3k
  if (len < sizeof(cac_cuid_t)) {
1384
23
    return SC_ERROR_INVALID_DATA;
1385
23
  }
1386
1387
18.2k
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "gsc_rid=%s", sc_dump_hex(val->gsc_rid, sizeof(val->gsc_rid)));
1388
18.2k
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "manufacture id=%x", val->manufacturer_id);
1389
18.2k
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "cac_type=%d", val->card_type);
1390
18.2k
  card_id_len = len - (&val->card_id - (u8 *)val);
1391
18.2k
  sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1392
18.2k
     "card_id=%s (%"SC_FORMAT_LEN_SIZE_T"u)",
1393
18.2k
     sc_dump_hex(&val->card_id, card_id_len),
1394
18.2k
     card_id_len);
1395
18.2k
  priv->cuid = *val;
1396
18.2k
  free(priv->cac_id);
1397
18.2k
  priv->cac_id = malloc(card_id_len);
1398
18.2k
  if (priv->cac_id == NULL) {
1399
0
    return SC_ERROR_OUT_OF_MEMORY;
1400
0
  }
1401
18.2k
  memcpy(priv->cac_id, &val->card_id, card_id_len);
1402
18.2k
  priv->cac_id_len = card_id_len;
1403
18.2k
  return SC_SUCCESS;
1404
18.2k
}
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
14.0k
{
1410
14.0k
  size_t len = 0;
1411
14.0k
  const u8 *tl_end = tl + tl_len;
1412
14.0k
  const u8 *val_end = val + val_len;
1413
14.0k
  sc_path_t new_path;
1414
14.0k
  int r;
1415
1416
1417
200k
  for (; (tl < tl_end) && (val< val_end); val += len) {
1418
    /* get the tag and the length */
1419
198k
    u8 tag;
1420
198k
    r = sc_simpletlv_read_tag(&tl, tl_end - tl, &tag, &len);
1421
198k
    if (r != SC_SUCCESS && r != SC_ERROR_TLV_END_OF_CONTENTS) {
1422
180
      sc_log(card->ctx, "Failed to parse tag from buffer");
1423
180
      break;
1424
180
    }
1425
198k
    if (val + len > val_end) {
1426
8.73k
      sc_log(card->ctx, "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
1427
8.73k
      break;
1428
8.73k
    }
1429
189k
    switch (tag) {
1430
18.3k
    case CAC_TAG_CUID:
1431
18.3k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CUID");
1432
18.3k
      r = cac_parse_cuid(card, priv, (cac_cuid_t *)val, len);
1433
18.3k
      if (r < 0)
1434
23
        return r;
1435
18.2k
      break;
1436
18.2k
    case CAC_TAG_CC_VERSION_NUMBER:
1437
12.1k
      if (len != 1) {
1438
1.87k
        sc_log(card->ctx, "TAG: CC Version: "
1439
1.87k
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
1440
1.87k
        break;
1441
1.87k
      }
1442
      /* ignore the version numbers for now */
1443
10.2k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1444
10.2k
        "TAG: CC Version = 0x%02x", *val);
1445
10.2k
      break;
1446
14.6k
    case CAC_TAG_GRAMMAR_VERION_NUMBER:
1447
14.6k
      if (len != 1) {
1448
3.74k
        sc_log(card->ctx, "TAG: Grammar Version: "
1449
3.74k
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
1450
3.74k
        break;
1451
3.74k
      }
1452
      /* ignore the version numbers for now */
1453
10.8k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1454
10.8k
        "TAG: Grammar Version = 0x%02x", *val);
1455
10.8k
      break;
1456
72.7k
    case CAC_TAG_CARDURL:
1457
72.7k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:CARDURL");
1458
72.7k
      r = cac_parse_cardurl(card, priv, (cac_card_url_t *)val, len);
1459
72.7k
      if (r < 0)
1460
54
        return r;
1461
72.7k
      break;
1462
    /*
1463
     * The following are really for file systems cards. This code only cares about CAC VM cards
1464
     */
1465
72.7k
    case CAC_TAG_PKCS15:
1466
2.52k
      if (len != 1) {
1467
1.05k
        sc_log(card->ctx, "TAG: PKCS15: "
1468
1.05k
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
1469
1.05k
        break;
1470
1.05k
      }
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
1.47k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: PKCS15 = 0x%02x", *val);
1475
1.47k
      break;
1476
4.52k
    case CAC_TAG_DATA_MODEL:
1477
4.52k
      if (len != 1) {
1478
907
        sc_log(card->ctx, "TAG: Registered Data Model Number: "
1479
907
            "Invalid length %"SC_FORMAT_LEN_SIZE_T"u", len);
1480
907
        break;
1481
907
      }
1482
3.61k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: Registered Data Model Number (0x%02x)", *val);
1483
3.61k
      break;
1484
4.21k
    case CAC_TAG_CARD_APDU:
1485
8.60k
    case CAC_TAG_CAPABILITY_TUPLES:
1486
11.9k
    case CAC_TAG_STATUS_TUPLES:
1487
15.5k
    case CAC_TAG_REDIRECTION:
1488
16.0k
    case CAC_TAG_ERROR_CODES:
1489
16.0k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG: FSSpecific(0x%02x)", tag);
1490
16.0k
      break;
1491
3.68k
    case CAC_TAG_ACCESS_CONTROL:
1492
      /* TODO handle access control later */
1493
3.68k
      sc_log_hex(card->ctx, "TAG:ACCESS Control", val, len);
1494
3.68k
      break;
1495
12.6k
    case CAC_TAG_NEXT_CCC:
1496
12.6k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:NEXT CCC");
1497
12.6k
      r = cac_path_from_cardurl(card, &new_path, (cac_card_url_t *)val, len);
1498
12.6k
      if (r < 0)
1499
42
        return r;
1500
1501
12.6k
      r = cac_select_file_by_type(card, &new_path, NULL);
1502
12.6k
      if (r < 0)
1503
259
        return r;
1504
1505
      /* Increase depth to avoid infinite recursion */
1506
12.3k
      r = cac_process_CCC(card, priv, depth + 1);
1507
12.3k
      if (r < 0)
1508
2.45k
        return r;
1509
9.90k
      break;
1510
31.9k
    default:
1511
      /* ignore tags we don't understand */
1512
31.9k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,"TAG:Unknown (0x%02x)",tag );
1513
31.9k
      break;
1514
189k
    }
1515
189k
  }
1516
11.2k
  return SC_SUCCESS;
1517
14.0k
}
1518
1519
static int cac_process_CCC(sc_card_t *card, cac_private_data_t *priv, int depth)
1520
15.1k
{
1521
15.1k
  u8 *tl = NULL, *val = NULL;
1522
15.1k
  size_t tl_len = 0, val_len = 0;
1523
15.1k
  int r;
1524
1525
15.1k
  if (depth > CAC_MAX_CCC_DEPTH) {
1526
13
    sc_log(card->ctx, "Too much recursive CCC found. Exiting");
1527
13
    return SC_ERROR_INVALID_CARD;
1528
13
  }
1529
1530
15.1k
  r = cac_read_file(card, CAC_FILE_TAG, &tl, &tl_len);
1531
15.1k
  if (r < 0)
1532
876
    goto done;
1533
1534
14.2k
  r = cac_read_file(card, CAC_FILE_VALUE, &val, &val_len);
1535
14.2k
  if (r < 0)
1536
156
    goto done;
1537
1538
14.0k
  r = cac_parse_CCC(card, priv, tl, tl_len, val, val_len, depth);
1539
15.1k
done:
1540
15.1k
  if (tl)
1541
14.2k
    free(tl);
1542
15.1k
  if (val)
1543
14.0k
    free(val);
1544
15.1k
  return r;
1545
14.0k
}
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
2.60k
{
1553
2.60k
  size_t len = 0;
1554
2.60k
  const u8 *val_end = val + val_len;
1555
2.60k
  int r;
1556
1557
2.60k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1558
1559
36.5k
  for (; val < val_end; val += len) {
1560
    /* get the tag and the length */
1561
35.9k
    u8 tag;
1562
35.9k
    if (sc_simpletlv_read_tag(&val, val_end - val, &tag, &len) != SC_SUCCESS)
1563
1.85k
      break;
1564
1565
34.1k
    switch (tag) {
1566
4.62k
    case CAC_TAG_APPLET_FAMILY:
1567
4.62k
      if (len != 5) {
1568
2.35k
        sc_log(card->ctx, "TAG: Applet Information: "
1569
2.35k
            "bad length %"SC_FORMAT_LEN_SIZE_T"u", len);
1570
2.35k
        break;
1571
2.35k
      }
1572
2.27k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1573
2.27k
          "TAG: Applet Information: Family: 0x%02x", val[0]);
1574
2.27k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1575
2.27k
          "     Applet Version: 0x%02x 0x%02x 0x%02x 0x%02x",
1576
2.27k
          val[1], val[2], val[3], val[4]);
1577
2.27k
      break;
1578
3.70k
    case CAC_TAG_NUMBER_APPLETS:
1579
3.70k
      if (len != 1) {
1580
1.92k
        sc_log(card->ctx, "TAG: Num applets: "
1581
1.92k
            "bad length %"SC_FORMAT_LEN_SIZE_T"u", len);
1582
1.92k
        break;
1583
1.92k
      }
1584
1.78k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1585
1.78k
          "TAG: Num applets = %hhd", *val);
1586
1.78k
      break;
1587
9.13k
    case CAC_TAG_APPLET_ENTRY:
1588
      /* Make sure we match the outer length */
1589
9.13k
      if (len < 3 || val[2] != len - 3) {
1590
3.18k
        sc_log(card->ctx, "TAG: Applet Entry: "
1591
3.18k
            "bad length (%"SC_FORMAT_LEN_SIZE_T
1592
3.18k
            "u) or length of internal buffer", len);
1593
3.18k
        break;
1594
3.18k
      }
1595
5.94k
      sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE,
1596
5.94k
          "TAG: Applet Entry: AID", val + 3, val[2]);
1597
      /* This is SimpleTLV prefixed with applet ID (1B) */
1598
5.94k
      r = cac_parse_aid(card, priv, val + 3, val[2]);
1599
5.94k
      if (r < 0)
1600
159
        return r;
1601
5.79k
      break;
1602
16.6k
    default:
1603
      /* ignore tags we don't understand */
1604
16.6k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1605
16.6k
          "TAG: Unknown (0x%02x)", tag);
1606
16.6k
      break;
1607
34.1k
    }
1608
34.1k
  }
1609
2.44k
  return SC_SUCCESS;
1610
2.60k
}
1611
1612
/* select a CAC pki applet by index */
1613
static int cac_select_pki_applet(sc_card_t *card, int index)
1614
456k
{
1615
456k
  sc_path_t applet_path = cac_cac_pki_obj.path;
1616
456k
  applet_path.aid.value[applet_path.aid.len-1] = index;
1617
456k
  return cac_select_file_by_type(card, &applet_path, NULL);
1618
456k
}
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
28.5k
{
1625
28.5k
  int r, i;
1626
465k
  for (i = 0; i < MAX_CAC_SLOTS; i++) {
1627
438k
    r = cac_select_pki_applet(card, i);
1628
438k
    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
3.11k
      u8 params[2] = {CAC_FILE_TAG, 2};
1633
3.11k
      u8 data[2], *out_ptr = data;
1634
3.11k
      size_t len = 2;
1635
3.11k
      r = cac_apdu_io(card, CAC_INS_READ_FILE, 0, 0,
1636
3.11k
          &params[0], sizeof(params), &out_ptr, &len);
1637
3.11k
      if (r != 2)
1638
1.51k
        continue;
1639
1640
1.60k
      *index_out = i;
1641
1.60k
      return SC_SUCCESS;
1642
3.11k
    }
1643
438k
  }
1644
26.9k
  return SC_ERROR_OBJECT_NOT_FOUND;
1645
28.5k
}
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
1.32k
{
1652
1.32k
  int r, i;
1653
1.32k
  cac_object_t pki_obj = cac_cac_pki_obj;
1654
1.32k
  u8 buf[100];
1655
1.32k
  u8 *val;
1656
1657
  /* populate PKI objects */
1658
18.2k
  for (i = index; i < MAX_CAC_SLOTS; i++) {
1659
16.9k
    r = cac_select_pki_applet(card, i);
1660
16.9k
    if (r == SC_SUCCESS) {
1661
7.52k
      pki_obj.name = get_cac_label(i);
1662
7.52k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1663
7.52k
          "CAC: pki_object found, cert_next=%d (%s),", i, pki_obj.name);
1664
7.52k
      pki_obj.path.aid.value[pki_obj.path.aid.len-1] = i;
1665
7.52k
      pki_obj.fd = i+1; /* don't use id of zero */
1666
7.52k
      cac_add_object_to_list(&priv->pki_list, &pki_obj);
1667
7.52k
    }
1668
16.9k
  }
1669
1670
  /* populate non-PKI objects */
1671
9.28k
  for (i=0; i < cac_object_count; i++) {
1672
7.96k
    r = cac_select_file_by_type(card, &cac_objects[i].path, NULL);
1673
7.96k
    if (r == SC_SUCCESS) {
1674
2.97k
      sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE,
1675
2.97k
          "CAC: obj_object found, cert_next=%d (%s),",
1676
2.97k
          i, cac_objects[i].name);
1677
2.97k
      cac_add_object_to_list(&priv->general_list, &cac_objects[i]);
1678
2.97k
    }
1679
7.96k
  }
1680
1681
  /*
1682
   * create a cuid to simulate the cac 2 cuid.
1683
   */
1684
1.32k
  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
1.32k
  r = cac_select_pki_applet(card, index);
1688
1.32k
  if (r < 0) {
1689
472
    return r; /* shouldn't happen unless the card has been removed or is malfunctioning */
1690
472
  }
1691
855
  val = buf;
1692
855
  r = cac_read_binary(card, 0, val, sizeof(buf), 0);
1693
855
  if (r > 0) {
1694
45
#ifdef ENABLE_OPENSSL
1695
45
    size_t val_len = r;
1696
45
    free(priv->cac_id);
1697
45
    priv->cac_id = malloc(20);
1698
45
    if (priv->cac_id == NULL) {
1699
0
      return SC_ERROR_OUT_OF_MEMORY;
1700
0
    }
1701
45
    SHA1(val, val_len, priv->cac_id);
1702
45
    priv->cac_id_len = 20;
1703
45
    sc_debug_hex(card->ctx, SC_LOG_DEBUG_VERBOSE,
1704
45
        "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
45
  }
1710
855
  return SC_SUCCESS;
1711
855
}
1712
1713
static int cac_process_ACA(sc_card_t *card, cac_private_data_t *priv)
1714
2.88k
{
1715
2.88k
  int r;
1716
2.88k
  u8 *val = NULL;
1717
2.88k
  size_t val_len;
1718
1719
2.88k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1720
1721
  /* Assuming ACA is already selected */
1722
2.88k
  r = cac_get_acr(card, CAC_ACR_SERVICE, &val, &val_len);
1723
2.88k
  if (r < 0)
1724
276
    goto done;
1725
1726
2.60k
  r = cac_parse_ACA_service(card, priv, val, val_len);
1727
2.60k
        if (r == SC_SUCCESS) {
1728
2.44k
    priv->aca_path = malloc(sizeof(sc_path_t));
1729
2.44k
    if (!priv->aca_path) {
1730
0
      r = SC_ERROR_OUT_OF_MEMORY;
1731
0
      goto done;
1732
0
    }
1733
2.44k
    memcpy(priv->aca_path, &cac_ACA_Path, sizeof(sc_path_t));
1734
2.44k
  }
1735
2.88k
done:
1736
2.88k
  if (val)
1737
2.60k
    free(val);
1738
2.88k
  LOG_FUNC_RETURN(card->ctx, r);
1739
2.88k
}
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
38.5k
{
1746
38.5k
  int r, index;
1747
38.5k
  cac_private_data_t *priv = NULL;
1748
1749
  /* already initialized? */
1750
38.5k
  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
38.5k
  r = cac_select_CCC(card);
1757
38.5k
  if (r == SC_SUCCESS) {
1758
8.49k
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "CCC found, is CAC-2");
1759
8.49k
    if (!initialize) /* match card only */
1760
5.72k
      return r;
1761
1762
2.76k
    priv = cac_new_private_data();
1763
2.76k
    if (!priv)
1764
0
      return SC_ERROR_OUT_OF_MEMORY;
1765
2.76k
    r = cac_process_CCC(card, priv, 0);
1766
2.76k
    if (r == SC_SUCCESS) {
1767
1.34k
      card->type = SC_CARD_TYPE_CAC_II;
1768
1.34k
      card->drv_data = priv;
1769
1.34k
      return r;
1770
1.34k
    }
1771
2.76k
  }
1772
1773
  /* Even some ALT tokens can be missing CCC so we should try with ACA */
1774
31.4k
  r = cac_select_ACA(card);
1775
31.4k
  if (r == SC_SUCCESS) {
1776
3.34k
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "ACA found, is CAC-2 without CCC");
1777
3.34k
    if (!initialize) /* match card only */
1778
466
      return r;
1779
1780
2.88k
    if (!priv) {
1781
2.59k
      priv = cac_new_private_data();
1782
2.59k
      if (!priv)
1783
0
        return SC_ERROR_OUT_OF_MEMORY;
1784
2.59k
    }
1785
2.88k
    r = cac_process_ACA(card, priv);
1786
2.88k
    if (r == SC_SUCCESS) {
1787
2.44k
      card->type = SC_CARD_TYPE_CAC_ALT_HID;
1788
2.44k
      card->drv_data = priv;
1789
2.44k
      return r;
1790
2.44k
    }
1791
2.88k
  }
1792
1793
  /* is this a CAC Alt token without any accompanying structures */
1794
28.5k
  r = cac_find_first_pki_applet(card, &index);
1795
28.5k
  if (r == SC_SUCCESS) {
1796
1.60k
    sc_debug(card->ctx, SC_LOG_DEBUG_VERBOSE, "PKI applet found, is bare CAC Alt");
1797
1.60k
    if (!initialize) /* match card only */
1798
277
      return r;
1799
1800
1.32k
    if (!priv) {
1801
957
      priv = cac_new_private_data();
1802
957
      if (!priv)
1803
0
        return SC_ERROR_OUT_OF_MEMORY;
1804
957
    }
1805
1.32k
    card->drv_data = priv; /* needed for the read_binary() */
1806
1.32k
    r = cac_populate_cac_alt(card, index, priv);
1807
1.32k
    if (r == SC_SUCCESS) {
1808
855
      card->type = SC_CARD_TYPE_CAC_II;
1809
855
      return r;
1810
855
    }
1811
472
    card->drv_data = NULL; /* reset on failure */
1812
472
  }
1813
27.4k
  if (priv) {
1814
1.67k
    cac_free_private_data(priv);
1815
1.67k
  }
1816
27.4k
  return r;
1817
28.5k
}
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
32.0k
{
1823
32.0k
  int r;
1824
32.0k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1825
1826
32.0k
  r = cac_find_and_initialize(card, 0);
1827
32.0k
  return (r == SC_SUCCESS); /* never match */
1828
32.0k
}
1829
1830
1831
static int cac_init(sc_card_t *card)
1832
6.47k
{
1833
6.47k
  int r;
1834
6.47k
  unsigned long flags;
1835
1836
6.47k
  SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE);
1837
1838
6.47k
  r = cac_find_and_initialize(card, 1);
1839
6.47k
  if (r < 0) {
1840
1.82k
    LOG_FUNC_RETURN(card->ctx, SC_ERROR_INVALID_CARD);
1841
1.82k
  }
1842
4.64k
  flags = SC_ALGORITHM_RSA_RAW;
1843
1844
4.64k
  _sc_card_add_rsa_alg(card, 1024, flags, 0); /* mandatory */
1845
4.64k
  _sc_card_add_rsa_alg(card, 2048, flags, 0); /* optional */
1846
4.64k
  _sc_card_add_rsa_alg(card, 3072, flags, 0); /* optional */
1847
1848
4.64k
  card->caps |= SC_CARD_CAP_RNG | SC_CARD_CAP_ISO7816_PIN_INFO;
1849
1850
4.64k
  LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
1851
4.64k
}
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
770
{
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
770
  sc_apdu_t apdu;
1867
770
  u8  sbuf[SC_MAX_APDU_BUFFER_SIZE];
1868
770
  struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
1869
770
  int rv;
1870
1871
770
  if (data->cmd == SC_PIN_CMD_CHANGE) {
1872
29
    size_t i = 0;
1873
29
    if (data->pin2.len < 6) {
1874
5
      return SC_ERROR_INVALID_PIN_LENGTH;
1875
5
    }
1876
142
    for(i=0; i < data->pin2.len; ++i) {
1877
129
      if (!isdigit(data->pin2.data[i])) {
1878
11
        return SC_ERROR_INVALID_DATA;
1879
11
      }
1880
129
    }
1881
1882
    /* We can change the PIN of Giesecke & Devrient CAC ALT tokens
1883
     * with a bit non-standard APDU */
1884
13
    if (card->type == SC_CARD_TYPE_CAC_ALT_HID) {
1885
10
      int r = 0;
1886
10
      r = iso7816_build_pin_apdu(card, &apdu, data, sbuf, sizeof(sbuf));
1887
10
      if (r < 0)
1888
0
        return r;
1889
      /* it requires P1 = 0x01 completely against the ISO specs */
1890
10
      apdu.p1 = 0x01;
1891
10
      data->apdu = &apdu;
1892
10
    }
1893
13
  }
1894
1895
754
  rv = iso_drv->ops->pin_cmd(card, data, tries_left);
1896
1897
754
  data->apdu = NULL;
1898
754
  return rv;
1899
770
}
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
208k
{
1912
208k
  struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
1913
1914
208k
  cac_ops = *iso_drv->ops;
1915
208k
  cac_ops.match_card = cac_match_card;
1916
208k
  cac_ops.init = cac_init;
1917
208k
  cac_ops.finish = cac_finish;
1918
1919
208k
  cac_ops.select_file =  cac_select_file; /* need to record object type */
1920
208k
  cac_ops.get_challenge = cac_get_challenge;
1921
208k
  cac_ops.read_binary = cac_read_binary;
1922
  /* CAC driver is read only */
1923
208k
  cac_ops.write_binary = NULL;
1924
208k
  cac_ops.set_security_env = cac_set_security_env;
1925
208k
  cac_ops.restore_security_env = cac_restore_security_env;
1926
208k
  cac_ops.compute_signature = cac_compute_signature;
1927
208k
  cac_ops.decipher =  cac_decipher;
1928
208k
  cac_ops.card_ctl = cac_card_ctl;
1929
208k
  cac_ops.pin_cmd = cac_pin_cmd;
1930
208k
  cac_ops.logout = cac_logout;
1931
1932
208k
  return &cac_drv;
1933
208k
}
1934
1935
1936
struct sc_card_driver * sc_get_cac_driver(void)
1937
208k
{
1938
208k
  return sc_get_driver();
1939
208k
}